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
186,970
<p>What ReSharper 4.0 templates for <strong>C#</strong> do you use?</p> <p>Let's share these in the following format:</p> <hr> <h2>[Title]</h2> <p><em>Optional description</em> </p> <p><strong>Shortcut:</strong> shortcut<br> <strong>Available in:</strong> [AvailabilitySetting]</p> <pre><code>// Resharper template code snippet // comes here </code></pre> <p><strong>Macros properties</strong> (if present):</p> <ul> <li><strong>Macro1</strong> - Value - EditableOccurence</li> <li><strong>Macro2</strong> - Value - EditableOccurence</li> </ul> <hr> <ul> <li>One macro per answer, please!</li> <li>Here are some samples for <a href="https://stackoverflow.com/questions/186970/what-resharper-40-templates-for-c-do-you-use#186978">NUnit test fixture</a> and <a href="https://stackoverflow.com/questions/186970/what-resharper-40-templates-for-c-do-you-use#186978">Standalone NUnit test case</a> that describe live templates in the suggested format.</li> </ul>
[ { "answer_id": 186974, "author": "Rinat Abdullin", "author_id": 47366, "author_profile": "https://Stackoverflow.com/users/47366", "pm_score": 4, "selected": false, "text": "<h2>Create new unit test fixture for some type</h2>\n\n<p><strong>Shortcut:</strong> ntf<br>\n<strong>Available in:</strong> C# 2.0+ files where type member declaration or namespace declaration is allowed</p>\n\n<pre><code>[NUnit.Framework.TestFixtureAttribute]\npublic sealed class $TypeToTest$Tests\n{\n [NUnit.Framework.TestAttribute]\n public void $Test$()\n {\n var t = new $TypeToTest$()\n $END$\n }\n}\n</code></pre>\n\n<p><strong>Macros:</strong></p>\n\n<ul>\n<li><strong>TypeToTest</strong> - none - #2</li>\n<li><strong>Test</strong> - none - V</li>\n</ul>\n" }, { "answer_id": 186978, "author": "Rinat Abdullin", "author_id": 47366, "author_profile": "https://Stackoverflow.com/users/47366", "pm_score": 4, "selected": false, "text": "<h2>Create new stand-alone unit test case</h2>\n\n<p><strong>Shortcut:</strong> ntc<br>\n<strong>Available in:</strong> C# 2.0+ files where type member declaration is allowed</p>\n\n<pre><code>[NUnit.Framework.TestAttribute]\npublic void $Test$()\n{\n $END$\n}\n</code></pre>\n\n<p><strong>Macros:</strong></p>\n\n<ul>\n<li><strong>Test</strong> - none - V</li>\n</ul>\n" }, { "answer_id": 187841, "author": "Ed Ball", "author_id": 23818, "author_profile": "https://Stackoverflow.com/users/23818", "pm_score": 5, "selected": false, "text": "<h2>Implement 'Dispose(bool)' Method</h2>\n\n<p><em>Implement <a href=\"http://www.bluebytesoftware.com/blog/2005/04/08/DGUpdateDisposeFinalizationAndResourceManagement.aspx\" rel=\"noreferrer\">Joe Duffy's Dispose Pattern</a></em> </p>\n\n<p><strong>Shortcut:</strong> dispose</p>\n\n<p><strong>Available in:</strong> C# 2.0+ files where type member declaration is allowed</p>\n\n<pre><code>public void Dispose()\n{\n Dispose(true);\n System.GC.SuppressFinalize(this);\n}\n\nprotected virtual void Dispose(bool disposing)\n{\n if (!disposed)\n {\n if (disposing)\n {\n if ($MEMBER$ != null)\n {\n $MEMBER$.Dispose();\n $MEMBER$ = null;\n }\n }\n\n disposed = true;\n }\n}\n\n~$CLASS$()\n{\n Dispose(false);\n}\n\nprivate bool disposed;\n</code></pre>\n\n<p><strong>Macros properties</strong>:</p>\n\n<ul>\n<li><strong>MEMBER</strong> - Suggest variable of System.IDisposable - Editable Occurence #1</li>\n<li><strong>CLASS</strong> - Containing type name</li>\n</ul>\n" }, { "answer_id": 191890, "author": "Rinat Abdullin", "author_id": 47366, "author_profile": "https://Stackoverflow.com/users/47366", "pm_score": 2, "selected": false, "text": "<h2>Create test case stub for NUnit</h2>\n\n<p><em>This one could serve as a reminder (of functionality to implement or test) that shows up in the unit test runner (as any other ignored test),</em></p>\n\n<p><strong>Shortcut:</strong> nts<br>\n<strong>Available in:</strong> C# 2.0+ files where type member declaration is allowed</p>\n\n<pre><code>[Test, Ignore]\npublic void $TestName$()\n{\n throw new NotImplementedException();\n}\n$END$\n</code></pre>\n" }, { "answer_id": 227019, "author": "Rinat Abdullin", "author_id": 47366, "author_profile": "https://Stackoverflow.com/users/47366", "pm_score": 2, "selected": false, "text": "<h2>Create sanity check to ensure that an argument is never null</h2>\n\n<p><strong>Shortcut:</strong> eann<br>\n<strong>Available in:</strong> C# 2.0+ files where type statement is allowed</p>\n\n<pre><code>Enforce.ArgumentNotNull($inner$, \"$inner$\");\n</code></pre>\n\n<p><strong>Macros:</strong></p>\n\n<ul>\n<li><strong>inner</strong> - Suggest parameter - #1</li>\n</ul>\n\n<p><strong>Remarks:</strong>\n<em>Although this snippet targets open source .NET <a href=\"http://rabdullin.com/projects/lokad-shared/\" rel=\"nofollow noreferrer\">Lokad.Shared</a> library, it could be easily adapted to any other type of argument check.</em></p>\n" }, { "answer_id": 259116, "author": "Ray Hayes", "author_id": 7093, "author_profile": "https://Stackoverflow.com/users/7093", "pm_score": 2, "selected": false, "text": "<h2>Trace - Writeline, with format</h2>\n\n<p>Very simple template to add a trace with a formatted string (like Debug.WriteLine supports already).</p>\n\n<p><strong>Shortcut:</strong> twlf<br>\n<strong>Available in:</strong> C# 2.0+ files where statement is allowed</p>\n\n<pre><code>Trace.WriteLine(string.Format(\"$MASK$\",$ARGUMENT$));\n</code></pre>\n\n<p><strong>Macros properties:</strong></p>\n\n<ul>\n<li><strong>Argument</strong> - <code>value</code> - EditableOccurence</li>\n<li><strong>Mask</strong> - <code>\"{0}\"</code> - EditableOccurence</li>\n</ul>\n" }, { "answer_id": 333490, "author": "Kjetil Klaussen", "author_id": 15599, "author_profile": "https://Stackoverflow.com/users/15599", "pm_score": 3, "selected": false, "text": "<p><strong>Assert.AreEqual</strong></p>\n\n<p><em>Simple template to add asserts to a unit test</em></p>\n\n<p><strong>Shortcut</strong>: ae<br>\n<strong>Available in</strong>: in C# 2.0+ files where statement is allowed</p>\n\n<pre><code>Assert.AreEqual($expected$, $actual$);$END$\n</code></pre>\n\n<p>Fluent version :</p>\n\n<pre><code>Assert.That($expected$, Is.EqualTo($actual$));$END$\n</code></pre>\n" }, { "answer_id": 503797, "author": "Ian G", "author_id": 5764, "author_profile": "https://Stackoverflow.com/users/5764", "pm_score": 2, "selected": false, "text": "<h1>New COM Class</h1>\n\n<p><strong>Shortcut</strong>: comclass</p>\n\n<p><strong>Available in</strong>: C# 2.0+ files where type member declaration or namespace declaration is allowed</p>\n\n<pre><code>[ComVisible(true)]\n[ClassInterface(ClassInterfaceType.None)]\n[Guid(\"$GUID$\")]\npublic class $NAME$ : $INTERFACE$\n{\n $END$\n}\n</code></pre>\n\n<p><strong>Macros</strong></p>\n\n<ul>\n<li><strong>GUID</strong> - New GUID</li>\n<li><strong>NAME</strong> - Editable</li>\n<li><strong>INTERFACE</strong> - Editable</li>\n</ul>\n" }, { "answer_id": 609796, "author": "Drew Noakes", "author_id": 24874, "author_profile": "https://Stackoverflow.com/users/24874", "pm_score": 2, "selected": false, "text": "<h1>Assert Invoke Not Required</h1>\n\n<p>Useful when developing WinForms applications where you want to be sure that code is executing on the correct thread for a given item. Note that <code>Control</code> implements <code>ISynchronizeInvoke</code>.</p>\n\n<p><strong>Shortcut</strong>: ani</p>\n\n<p><strong>Available in</strong>: C# 2.0+ files statement is allowed</p>\n\n<pre><code>Debug.Assert(!$SYNC_INVOKE$.InvokeRequired, \"InvokeRequired\");\n</code></pre>\n\n<p><strong>Macros</strong></p>\n\n<ul>\n<li><strong>SYNC_INVOKE</strong> - Suggest variable of <code>System.ComponentModel.ISynchronizeInvoke</code></li>\n</ul>\n" }, { "answer_id": 609824, "author": "Drew Noakes", "author_id": 24874, "author_profile": "https://Stackoverflow.com/users/24874", "pm_score": 2, "selected": false, "text": "<h1>Invoke if Required</h1>\n\n<p>Useful when developing WinForms applications where a method should be callable from non-UI threads, and that method should then marshall the call onto the UI thread.</p>\n\n<p><strong>Shortcut</strong>: inv</p>\n\n<p><strong>Available in</strong>: C# 3.0+ files statement is allowed</p>\n\n<pre><code>if (InvokeRequired)\n{\n Invoke((System.Action)delegate { $METHOD_NAME$($END$); });\n return;\n}\n</code></pre>\n\n<p><strong>Macros</strong></p>\n\n<ul>\n<li><strong>METHOD_NAME</strong> - Containing type member name</li>\n</ul>\n\n<hr>\n\n<p>You would normally use this template as the first statement in a given method and the result resembles:</p>\n\n<pre><code>void DoSomething(Type1 arg1)\n{\n if (InvokeRequired)\n {\n Invoke((Action)delegate { DoSomething(arg1); });\n return;\n }\n\n // Rest of method will only execute on the correct thread\n // ...\n}\n</code></pre>\n" }, { "answer_id": 639581, "author": "Daver", "author_id": 68095, "author_profile": "https://Stackoverflow.com/users/68095", "pm_score": 2, "selected": false, "text": "<h2>MSTest Test Method</h2>\n\n<p>This is a bit lame but it's useful. Hopefully someone will get some utility out of it.</p>\n\n<p>Shortcut: testMethod</p>\n\n<p>Available in: C# 2.0</p>\n\n<pre><code>[TestMethod]\npublic void $TestName$()\n{\n throw new NotImplementedException();\n\n //Arrange.\n\n //Act.\n\n //Assert.\n}\n\n$END$\n</code></pre>\n" }, { "answer_id": 639618, "author": "womp", "author_id": 63756, "author_profile": "https://Stackoverflow.com/users/63756", "pm_score": 3, "selected": false, "text": "<h2>Quick ExpectedException Shortcut</h2>\n<p>Just a quick shortcut to add to my unit test attributes.</p>\n<p><strong>Shortcut</strong>: ee</p>\n<p><strong>Available in</strong>: Available in: C# 2.0+ files where type member declaration is allowed</p>\n<pre><code>[ExpectedException(typeof($TYPE$))]\n</code></pre>\n" }, { "answer_id": 871250, "author": "Chris Brandsma", "author_id": 9443, "author_profile": "https://Stackoverflow.com/users/9443", "pm_score": 3, "selected": false, "text": "<p>Declare a log4net logger for the current type.</p>\n\n<p><strong>Shortcut:</strong> log</p>\n\n<p><strong>Available in:</strong> C# 2.0+ files where type member declaration is allowed</p>\n\n<pre><code>private static readonly log4net.ILog log = log4net.LogManager.GetLogger(typeof($TYPE$));\n</code></pre>\n\n<p><strong>Macros properties</strong>:</p>\n\n<ul>\n<li><strong>TYPE</strong> - Containing type name</li>\n</ul>\n" }, { "answer_id": 1493338, "author": "paraquat", "author_id": 144067, "author_profile": "https://Stackoverflow.com/users/144067", "pm_score": 2, "selected": false, "text": "<h2>NUnit Setup method</h2>\n\n<p><strong>Shortcut:</strong> setup<br>\n<strong>Available in:</strong> Available in: C# 2.0+ files where type member declaration is allowed</p>\n\n<pre><code>[NUnit.Framework.SetUp]\npublic void SetUp()\n{\n $END$\n}\n</code></pre>\n" }, { "answer_id": 1493361, "author": "paraquat", "author_id": 144067, "author_profile": "https://Stackoverflow.com/users/144067", "pm_score": 2, "selected": false, "text": "<h2>NUnit Teardown method</h2>\n\n<p><strong>Shortcut:</strong> teardown<br>\n<strong>Available in:</strong> Available in: C# 2.0+ files where type member declaration is allowed</p>\n\n<pre><code>[NUnit.Framework.TearDown]\npublic void TearDown()\n{\n $END$\n}\n</code></pre>\n" }, { "answer_id": 1499011, "author": "Chris Doggett", "author_id": 64203, "author_profile": "https://Stackoverflow.com/users/64203", "pm_score": 3, "selected": false, "text": "<h2>Check if variable is null</h2>\n\n<p><strong>Shortcut:</strong> ifn<br>\n<strong>Available in:</strong> C# 2.0+ files</p>\n\n<pre><code>if (null == $var$)\n{\n $END$\n}\n</code></pre>\n\n<h2>Check if variable is not null</h2>\n\n<p><strong>Shortcut:</strong> ifnn<br>\n<strong>Available in:</strong> C# 2.0+ files</p>\n\n<pre><code>if (null != $var$)\n{\n $END$\n}\n</code></pre>\n" }, { "answer_id": 1503327, "author": "Karsten", "author_id": 44726, "author_profile": "https://Stackoverflow.com/users/44726", "pm_score": 1, "selected": false, "text": "<h1><strong>New Typemock isolator fake</strong></h1>\n\n<p><strong>Shortcut</strong>: fake<br>\n<strong>Available in</strong>: [in c# 2.0 files where statement is allowed]</p>\n\n<p>$TYPE$ $Name$Fake = Isolate.Fake.Instance();<br>\nIsolate.WhenCalled(() => $Name$Fake.)</p>\n\n<p>Macros properties:<br>\n * $TYPE$ - Suggest type for a new variable<br>\n * $Name$ - Value of <strong>another variable</strong> (<em>Type</em>) with the first character in lower case</p>\n" }, { "answer_id": 2452390, "author": "Ray", "author_id": 4872, "author_profile": "https://Stackoverflow.com/users/4872", "pm_score": 0, "selected": false, "text": "<h2>Rhino Mocks Record-Playback Syntax</h2>\n\n<p><strong>Shortcut</strong>: RhinoMocksRecordPlaybackSyntax *</p>\n\n<p><strong>Available in:</strong> C# 2.0+ files</p>\n\n<p><strong>Note:</strong> This code snippet is dependent on MockRepository (<code>var mocks = new new MockRepository();</code>) being already declared and initialized somewhere else.</p>\n\n<pre><code>using (mocks.Record())\n{\n $END$\n}\n\nusing (mocks.Playback())\n{\n\n}\n</code></pre>\n\n<p>*might seem a bit long for a shortcut name but with intellisense not an issue when typing. also have other code snippets for Rhino Mocks so fully qualifying the name makes it easier to group them together visually</p>\n" }, { "answer_id": 2627586, "author": "Ray", "author_id": 4872, "author_profile": "https://Stackoverflow.com/users/4872", "pm_score": 0, "selected": false, "text": "<h2>Rhino Mocks Expect Methods</h2>\n\n<p><strong>Shortcut</strong>: RhinoMocksExpectMethod</p>\n\n<p><strong>Available in:</strong> C# 2.0+ files</p>\n\n<pre><code>Expect.Call($EXPECT_CODE$).Return($RETURN_VALUE$);\n</code></pre>\n\n<p><strong>Shortcut</strong>: RhinoMocksExpectVoidMethod</p>\n\n<p><strong>Available in:</strong> C# 2.0+ files</p>\n\n<pre><code>Expect.Call(delegate { $EXPECT_CODE$; });\n</code></pre>\n" }, { "answer_id": 2677220, "author": "Bryce Fischer", "author_id": 450139, "author_profile": "https://Stackoverflow.com/users/450139", "pm_score": 1, "selected": false, "text": "<p>Since I'm working with Unity right now, I've come up with a few to make my life a bit easier:</p>\n\n<hr>\n\n<h2>Type Alias</h2>\n\n<p><strong>Shortcut</strong>: ta<br>\n<strong>Available in</strong>: *.xml; *.config </p>\n\n<pre><code>&lt;typeAlias alias=\"$ALIAS$\" type=\"$TYPE$,$ASSEMBLY$\"/&gt;\n</code></pre>\n\n<hr>\n\n<h2>Type Declaration</h2>\n\n<p>This is a type with no name and no arguments</p>\n\n<p><strong>Shortcut</strong>: tp<br>\n<strong>Available in</strong>: *.xml; *.config </p>\n\n<pre><code>&lt;type type=\"$TYPE$\" mapTo=\"$MAPTYPE$\"/&gt;\n</code></pre>\n\n<hr>\n\n<h2>Type Declaration (with name)</h2>\n\n<p>This is a type with name and no arguments</p>\n\n<p><strong>Shortcut</strong>: tn<br>\n<strong>Available in</strong>: *.xml; *.config </p>\n\n<pre><code>&lt;type type=\"$TYPE$\" mapTo=\"$MAPTYPE$\" name=\"$NAME$\"/&gt;\n</code></pre>\n\n<hr>\n\n<h2>Type Declaration With Constructor</h2>\n\n<p>This is a type with name and no arguments</p>\n\n<p><strong>Shortcut</strong>: tpc<br>\n<strong>Available in</strong>: *.xml; *.config </p>\n\n<pre><code>&lt;type type=\"$TYPE$\" mapTo=\"$MAPTYPE$\"&gt;\n &lt;typeConfig&gt;\n &lt;constructor&gt;\n $PARAMS$\n &lt;/constructor&gt;\n &lt;/typeConfig&gt;\n&lt;/type&gt;\n</code></pre>\n\n<p>etc....</p>\n" }, { "answer_id": 3588387, "author": "jhappoldt", "author_id": 52307, "author_profile": "https://Stackoverflow.com/users/52307", "pm_score": 0, "selected": false, "text": "<p>Borrowing from Drew Noakes excellent idea, here is an implementation of invoke for Silverlight.</p>\n\n<p><strong>Shortcut: dca</strong></p>\n\n<p><strong>Available in: C# 3.0 files</strong></p>\n\n<pre><code>if (!Dispatcher.CheckAccess())\n{\n Dispatcher.BeginInvoke((Action)delegate { $METHOD_NAME$(sender, e); });\n return;\n}\n\n$END$\n</code></pre>\n\n<p><strong>Macros</strong></p>\n\n<ul>\n<li><code>$METHOD_NAME$</code> non-editable name of the current containing method.</li>\n</ul>\n" }, { "answer_id": 3588457, "author": "Vaccano", "author_id": 16241, "author_profile": "https://Stackoverflow.com/users/16241", "pm_score": 3, "selected": false, "text": "<h2>MS Test Unit Test</h2>\n\n<p><em>New MS Test Unit test using AAA syntax and the naming convention found in the <a href=\"http://www.manning.com/osherove/\" rel=\"nofollow noreferrer\">Art Of Unit Testing</a></em> </p>\n\n<p><strong>Shortcut:</strong> testing (or tst, or whatever you want)<br>\n<strong>Available in:</strong> C# 2.0+ files where type member declaration is allowed</p>\n\n<pre><code>[TestMethod]\npublic void $MethodName$_$StateUnderTest$_$ExpectedBehavior$()\n{\n // Arrange\n $END$\n\n // Act\n\n\n // Assert\n\n}\n</code></pre>\n\n<p><strong>Macros properties</strong> (if present):</p>\n\n<ul>\n<li><strong>MethodName</strong> - The name of the method under test</li>\n<li><strong>StateUnderTest</strong> - The state you are trying to test </li>\n<li><strong>ExpectedBehavior</strong> - What you expect to happen </li>\n</ul>\n" }, { "answer_id": 3683058, "author": "Igor Brejc", "author_id": 55408, "author_profile": "https://Stackoverflow.com/users/55408", "pm_score": 1, "selected": false, "text": "<p><strong>log4net XML Configuration Block</strong></p>\n\n<p>You can import the template directly:</p>\n\n<pre><code>&lt;TemplatesExport family=\"Live Templates\"&gt;\n &lt;Template uid=\"49c599bb-a1ec-4def-a2ad-01de05799843\" shortcut=\"log4\" description=\"inserts log4net XML configuration block\" text=\" &amp;lt;configSections&amp;gt;&amp;#xD;&amp;#xA; &amp;lt;section name=&amp;quot;log4net&amp;quot; type=&amp;quot;log4net.Config.Log4NetConfigurationSectionHandler,log4net&amp;quot; /&amp;gt;&amp;#xD;&amp;#xA; &amp;lt;/configSections&amp;gt;&amp;#xD;&amp;#xA;&amp;#xD;&amp;#xA; &amp;lt;log4net debug=&amp;quot;false&amp;quot;&amp;gt;&amp;#xD;&amp;#xA; &amp;lt;appender name=&amp;quot;LogFileAppender&amp;quot; type=&amp;quot;log4net.Appender.RollingFileAppender&amp;quot;&amp;gt;&amp;#xD;&amp;#xA; &amp;lt;param name=&amp;quot;File&amp;quot; value=&amp;quot;logs\\\\$LogFileName$.log&amp;quot; /&amp;gt;&amp;#xD;&amp;#xA; &amp;lt;param name=&amp;quot;AppendToFile&amp;quot; value=&amp;quot;false&amp;quot; /&amp;gt;&amp;#xD;&amp;#xA; &amp;lt;param name=&amp;quot;RollingStyle&amp;quot; value=&amp;quot;Size&amp;quot; /&amp;gt;&amp;#xD;&amp;#xA; &amp;lt;param name=&amp;quot;MaxSizeRollBackups&amp;quot; value=&amp;quot;5&amp;quot; /&amp;gt;&amp;#xD;&amp;#xA; &amp;lt;param name=&amp;quot;MaximumFileSize&amp;quot; value=&amp;quot;5000KB&amp;quot; /&amp;gt;&amp;#xD;&amp;#xA; &amp;lt;param name=&amp;quot;StaticLogFileName&amp;quot; value=&amp;quot;true&amp;quot; /&amp;gt;&amp;#xD;&amp;#xA;&amp;#xD;&amp;#xA; &amp;lt;layout type=&amp;quot;log4net.Layout.PatternLayout&amp;quot;&amp;gt;&amp;#xD;&amp;#xA; &amp;lt;param name=&amp;quot;ConversionPattern&amp;quot; value=&amp;quot;%date [%3thread] %-5level %-40logger{3} - %message%newline&amp;quot; /&amp;gt;&amp;#xD;&amp;#xA; &amp;lt;/layout&amp;gt;&amp;#xD;&amp;#xA; &amp;lt;/appender&amp;gt;&amp;#xD;&amp;#xA;&amp;#xD;&amp;#xA; &amp;lt;appender name=&amp;quot;ConsoleAppender&amp;quot; type=&amp;quot;log4net.Appender.ConsoleAppender&amp;quot;&amp;gt;&amp;#xD;&amp;#xA; &amp;lt;layout type=&amp;quot;log4net.Layout.PatternLayout&amp;quot;&amp;gt;&amp;#xD;&amp;#xA; &amp;lt;param name=&amp;quot;ConversionPattern&amp;quot; value=&amp;quot;%message%newline&amp;quot; /&amp;gt;&amp;#xD;&amp;#xA; &amp;lt;/layout&amp;gt;&amp;#xD;&amp;#xA; &amp;lt;/appender&amp;gt;&amp;#xD;&amp;#xA;&amp;#xD;&amp;#xA; &amp;lt;root&amp;gt;&amp;#xD;&amp;#xA; &amp;lt;priority value=&amp;quot;DEBUG&amp;quot; /&amp;gt;&amp;#xD;&amp;#xA; &amp;lt;appender-ref ref=&amp;quot;LogFileAppender&amp;quot; /&amp;gt;&amp;#xD;&amp;#xA; &amp;lt;/root&amp;gt;&amp;#xD;&amp;#xA; &amp;lt;/log4net&amp;gt;&amp;#xD;&amp;#xA;\" reformat=\"False\" shortenQualifiedReferences=\"False\"&gt;\n &lt;Context&gt;\n &lt;FileNameContext mask=\"*.config\" /&gt;\n &lt;/Context&gt;\n &lt;Categories /&gt;\n &lt;Variables&gt;\n &lt;Variable name=\"LogFileName\" expression=\"getOutputName()\" initialRange=\"0\" /&gt;\n &lt;/Variables&gt;\n &lt;CustomProperties /&gt;\n &lt;/Template&gt;\n&lt;/TemplatesExport&gt;\n</code></pre>\n" }, { "answer_id": 3729088, "author": "codekaizen", "author_id": 58391, "author_profile": "https://Stackoverflow.com/users/58391", "pm_score": 2, "selected": false, "text": "<h2>New C# Guid</h2>\n<p><em>Generates a new System.Guid instance initialized to a new generated guid value</em></p>\n<p><strong>Shortcut:</strong> csguid\n<strong>Available in:</strong> in C# 2.0+ files</p>\n<pre><code>new System.Guid(&quot;$GUID$&quot;)\n</code></pre>\n<p><strong>Macros properties</strong>:</p>\n<ul>\n<li><strong>GUID</strong> - New GUID - False</li>\n</ul>\n" }, { "answer_id": 4790889, "author": "Dmitrii Lobanov", "author_id": 100110, "author_profile": "https://Stackoverflow.com/users/100110", "pm_score": 3, "selected": false, "text": "<h2>Write StyleCop-compliant summary for class constructor</h2>\n\n<p><em>(if you are tired of constantly typing in long standard summary for every constructor so it complies to StyleCop rule SA1642)</em></p>\n\n<p><strong>Shortcut:</strong> csum</p>\n\n<p><strong>Available in:</strong> C# 2.0+</p>\n\n<pre><code>Initializes a new instance of the &lt;see cref=\"$classname$\"/&gt; class.$END$\n</code></pre>\n\n<p><strong>Macros:</strong></p>\n\n<ul>\n<li><strong>classname</strong> - Containing type name - V</li>\n</ul>\n" }, { "answer_id": 5001023, "author": "Sean Kearon", "author_id": 2608, "author_profile": "https://Stackoverflow.com/users/2608", "pm_score": 5, "selected": false, "text": "<h2>Simple Lambda</h2>\n\n<p>So simple, so useful - a little lambda:</p>\n\n<p><strong>Shortcut</strong>: x</p>\n\n<p><strong>Available</strong>: C# where expression is allowed.</p>\n\n<pre><code>x =&gt; x.$END$\n</code></pre>\n\n<p>Macros: none.</p>\n" }, { "answer_id": 5008117, "author": "Sean Kearon", "author_id": 2608, "author_profile": "https://Stackoverflow.com/users/2608", "pm_score": 4, "selected": false, "text": "<h2>Check if a string is null or empty.</h2>\n<p><em>If you're using .Net 4 you may prefer to use string.IsNullOrWhiteSpace().</em></p>\n<p><strong>Shortcut</strong>: sne</p>\n<p><strong>Available in</strong>: C# 2.0+ where expression is allowed.</p>\n<pre><code>string.IsNullOrEmpty($VAR$)\n</code></pre>\n<p><strong>Macro properties</strong>:</p>\n<ul>\n<li>VAR - suggest a variable of type string. Editible = true.</li>\n</ul>\n" }, { "answer_id": 5008509, "author": "Sean Kearon", "author_id": 2608, "author_profile": "https://Stackoverflow.com/users/2608", "pm_score": 3, "selected": false, "text": "<h2>Notify Property Changed</h2>\n\n<p><em>This is my favourite because I use it often and it does a lot of work for me.</em></p>\n\n<p><strong>Shortcut</strong>: npc</p>\n\n<p><strong>Available in</strong>: C# 2.0+ where expression is allowed.</p>\n\n<pre><code>if (value != _$LOWEREDMEMBER$)\n{\n _$LOWEREDMEMBER$ = value;\n NotifyPropertyChanged(\"$MEMBER$\");\n}\n</code></pre>\n\n<p><strong>Macros</strong>:</p>\n\n<ul>\n<li>MEMBER - Containing member type name. Not editable. <em>Note: make sure this one is first in the list.</em></li>\n<li>LOWEREDMEMBER - Value of MEMBER with the first character in lower case. Not editable.</li>\n</ul>\n\n<p><strong>Usage</strong>:\nInside a property setter like this:</p>\n\n<pre><code>private string _dateOfBirth;\npublic string DateOfBirth\n{\n get { return _dateOfBirth; }\n set\n {\n npc&lt;--tab from here\n }\n}\n</code></pre>\n\n<p>It assumes that your backing variable starts with an \"_\". Replace this with whatever you use. It also assumes that you have a property change method something like this:</p>\n\n<pre><code>private void NotifyPropertyChanged(String info)\n{\n if (PropertyChanged != null)\n {\n PropertyChanged(this, new PropertyChangedEventArgs(info));\n }\n}\n</code></pre>\n\n<p>In reality, the version of this I use is lambda based ('cos I loves my lambdas!) and produces the below. The principles are the same as the above.</p>\n\n<pre><code>public decimal CircuitConductorLive\n{\n get { return _circuitConductorLive; }\n set { Set(x =&gt; x.CircuitConductorLive, ref _circuitConductorLive, value); }\n}\n</code></pre>\n\n<p>That's when I'm not using the extremely elegant and useful <a href=\"http://www.sharpcrafters.com/solutions/ui#data-binding\" rel=\"noreferrer\">PostSharp to do the whole INotifyPropertyChanged thing for no effort</a>, that is.</p>\n" }, { "answer_id": 5019071, "author": "James Kovacs", "author_id": 251305, "author_profile": "https://Stackoverflow.com/users/251305", "pm_score": 3, "selected": false, "text": "<h2>Lots of Lambdas</h2>\n\n<p>Create a lambda expression with a different variable declaration for easy nesting.</p>\n\n<p><strong>Shortcut:</strong> la, lb, lc</p>\n\n<p><strong>Available in:</strong> C# 3.0+ files where expression or query clause is allowed</p>\n\n<p><em>la</em> is defined as:</p>\n\n<pre><code>x =&gt; x.$END$\n</code></pre>\n\n<p><em>lb</em> is defined as:</p>\n\n<pre><code>y =&gt; y.$END$\n</code></pre>\n\n<p><em>lc</em> is defined as:</p>\n\n<pre><code>z =&gt; z.$END$\n</code></pre>\n\n<p>This is similar to Sean Kearon above, except I define multiple lambda live templates for easy nesting of lambdas. \"<em>la</em>\" is most commonly used, but others are useful when dealing with expressions like this:</p>\n\n<pre><code>items.ForEach(x =&gt; x.Children.ForEach(y =&gt; Console.WriteLine(y.Name)));\n</code></pre>\n" }, { "answer_id": 5019098, "author": "James Kovacs", "author_id": 251305, "author_profile": "https://Stackoverflow.com/users/251305", "pm_score": 3, "selected": false, "text": "<h2>Wait for It...</h2>\n\n<p>Pause for user input before end of a console application.</p>\n\n<p><strong>Shortcut:</strong> pause</p>\n\n<p><strong>Available in:</strong> C# 2.0+ files where statement is allowed</p>\n\n<pre><code>System.Console.WriteLine(\"Press &lt;ENTER&gt; to exit...\");\nSystem.Console.ReadLine();$END$\n</code></pre>\n" }, { "answer_id": 5019232, "author": "James Kovacs", "author_id": 251305, "author_profile": "https://Stackoverflow.com/users/251305", "pm_score": 1, "selected": false, "text": "<h2>Make Method Virtual</h2>\n\n<p>Adds virtual keyword. Especially useful when using NHibernate, EF, or similar framework where methods and/or properties must be virtual to enable lazy loading or proxying.</p>\n\n<p><strong>Shortcut:</strong> v</p>\n\n<p><strong>Available in:</strong> C# 2.0+ file where type member declaration is allowed</p>\n\n<pre><code>virtual $END$\n</code></pre>\n\n<p>The trick here is the space after virtual, which might be hard to see above. The actual template is \"virtual $END$\" with reformat code enabled. This allows you to go to the insert point below (denoted by |) and type v:</p>\n\n<pre><code>public |string Name { get; set; }\n</code></pre>\n" }, { "answer_id": 5541672, "author": "David R. Longnecker", "author_id": 1754, "author_profile": "https://Stackoverflow.com/users/1754", "pm_score": 0, "selected": false, "text": "<h2>Machine.Specifications - Because of</h2>\n\n<p>As a heavy mspec user, I have several live templates specifically for MSpec. Here's a quick one for setting up a because and catching the error.</p>\n\n<p><strong>Shortcut:</strong> bece<br/>\n<strong>Available in:</strong> C# 2.0+ files where type member declaration or namespace declaration is allowed</p>\n\n<p><strong>bece - Because of (with exception catching)</strong>\n<pre><code>Protected static Exception exception;\nBecause of = () => exception = Catch.Exception(() => $something$);\n$END$\n</pre></code></p>\n" }, { "answer_id": 5543434, "author": "David R. Longnecker", "author_id": 1754, "author_profile": "https://Stackoverflow.com/users/1754", "pm_score": 3, "selected": false, "text": "<h2>AutoMapper Property Mapping</h2>\n\n<p><strong>Shortcut:</strong> fm</p>\n\n<p><strong>Available in:</strong> C# 2.0+ files where statement is allowed</p>\n\n<p><pre><code>.ForMember(d => d$property$, o => o.MapFrom(s => s$src_property$))\n$END$\n</pre></code></p>\n\n<p><strong>Macros:</strong></p>\n\n<ul>\n<li>property - editable occurrence</li>\n<li>src_property - editable occurrence</li>\n</ul>\n\n<p><strong>Note:</strong> </p>\n\n<p>I leave the lambda \"dot\" off so that I can hit . immediately and get property intellisense. \n Requires AutoMapper (<a href=\"http://automapper.codeplex.com/\">http://automapper.codeplex.com/</a>). </p>\n" }, { "answer_id": 5699815, "author": "Jonas Van der Aa", "author_id": 176541, "author_profile": "https://Stackoverflow.com/users/176541", "pm_score": 3, "selected": false, "text": "<p><strong>Dependency property generation</strong></p>\n\n<p><em>Generates a dependency property</em></p>\n\n<p><strong>Shortcut:</strong> dp<br/>\n<strong>Available in:</strong> C# 3.0 where member declaration is allowed</p>\n\n<pre><code>public static readonly System.Windows.DependencyProperty $PropertyName$Property =\n System.Windows.DependencyProperty.Register(\"$PropertyName$\",\n typeof ($PropertyType$),\n typeof ($OwnerType$));\n\n public $PropertyType$ $PropertyName$\n {\n get { return ($PropertyType$) GetValue($PropertyName$Property); }\n set { SetValue($PropertyName$Property, value); }\n }\n\n$END$\n</code></pre>\n\n<p>Macros properties (if present):</p>\n\n<p>PropertyName - No Macro - #3<br/>\nPropertyType - Guess type expected at this point - #2<br/>\nOwnerType - Containing type name - no editable occurence</p>\n" }, { "answer_id": 6595191, "author": "Richard Dingwall", "author_id": 91551, "author_profile": "https://Stackoverflow.com/users/91551", "pm_score": 0, "selected": false, "text": "<h2>Machine.Specifications - It</h2>\n\n<p><strong>Shortcut:</strong> it</p>\n\n<p><strong>Available in:</strong> C# 2.0+ files where type member declaration or namespace declaration is allowed</p>\n\n<pre><code>Machine.Specifications.It $should_$ =\n () =&gt; \n {\n\n };\n</code></pre>\n\n<p><strong>Macros properties</strong> (if present):</p>\n\n<ul>\n<li><strong>should_</strong> - (No Macro) - EditableOccurence</li>\n</ul>\n" }, { "answer_id": 9236368, "author": "Michael Kropat", "author_id": 27581, "author_profile": "https://Stackoverflow.com/users/27581", "pm_score": 1, "selected": false, "text": "<h2>Equals</h2>\n\n<p><em>Neither .NET in general nor the default “equals” template make it easy to bang out a good, simple Equals method. While <a href=\"https://stackoverflow.com/questions/2509965/writing-a-good-c-sharp-equals-method\">there</a> <a href=\"http://msdn.microsoft.com/en-us/library/336aedhh%28v=vs.100%29.aspx\" rel=\"nofollow noreferrer\">are</a> <a href=\"http://www.infoq.com/articles/Equality-Overloading-DotNET\" rel=\"nofollow noreferrer\">many</a> <a href=\"https://blogs.msdn.com/b/jaredpar/archive/2009/01/15/if-you-implement-iequatable-t-you-still-must-override-object-s-equals-and-gethashcode.aspx\" rel=\"nofollow noreferrer\">thoughts</a> on how to write a good Equals method, I think the following suffices for 90% of simple cases. For anything more complicated — especially when it comes to inheritance — it might be better <a href=\"https://stackoverflow.com/a/2510092/27581\">to not use Equals at all</a>.</em></p>\n\n<p><strong>Shortcut:</strong> equals<br>\n<strong>Available in:</strong> C# 2.0+ type members</p>\n\n<pre><code>public override sealed bool Equals(object other) {\n return Equals(other as $TYPE$);\n}\n\npublic bool Equals($TYPE$ other) {\n return !ReferenceEquals(other, null) &amp;&amp; $END$;\n}\n\npublic override int GetHashCode() {\n // *Always* call Equals.\n return 0;\n}\n</code></pre>\n\n<p><strong>Macros properties</strong>:</p>\n\n<ul>\n<li><strong>TYPE</strong> - Containing type name - Not Editable</li>\n</ul>\n" } ]
2008/10/09
[ "https://Stackoverflow.com/questions/186970", "https://Stackoverflow.com", "https://Stackoverflow.com/users/47366/" ]
What ReSharper 4.0 templates for **C#** do you use? Let's share these in the following format: --- [Title] ------- *Optional description* **Shortcut:** shortcut **Available in:** [AvailabilitySetting] ``` // Resharper template code snippet // comes here ``` **Macros properties** (if present): * **Macro1** - Value - EditableOccurence * **Macro2** - Value - EditableOccurence --- * One macro per answer, please! * Here are some samples for [NUnit test fixture](https://stackoverflow.com/questions/186970/what-resharper-40-templates-for-c-do-you-use#186978) and [Standalone NUnit test case](https://stackoverflow.com/questions/186970/what-resharper-40-templates-for-c-do-you-use#186978) that describe live templates in the suggested format.
Implement 'Dispose(bool)' Method -------------------------------- *Implement [Joe Duffy's Dispose Pattern](http://www.bluebytesoftware.com/blog/2005/04/08/DGUpdateDisposeFinalizationAndResourceManagement.aspx)* **Shortcut:** dispose **Available in:** C# 2.0+ files where type member declaration is allowed ``` public void Dispose() { Dispose(true); System.GC.SuppressFinalize(this); } protected virtual void Dispose(bool disposing) { if (!disposed) { if (disposing) { if ($MEMBER$ != null) { $MEMBER$.Dispose(); $MEMBER$ = null; } } disposed = true; } } ~$CLASS$() { Dispose(false); } private bool disposed; ``` **Macros properties**: * **MEMBER** - Suggest variable of System.IDisposable - Editable Occurence #1 * **CLASS** - Containing type name
187,000
<p>I have an asp.net website that allows the user to download largish files - 30mb to about 60mb. Sometimes the download works fine but often it fails at some varying point before the download finishes with the message saying that the connection with the server was reset.</p> <p>Originally I was simply using Server.TransmitFile but after reading up a bit I am now using the code posted below. I am also setting the Server.ScriptTimeout value to 3600 in the Page_Init event.</p> <pre><code>private void DownloadFile(string fname, bool forceDownload) { string path = MapPath(fname); string name = Path.GetFileName(path); string ext = Path.GetExtension(path); string type = ""; // set known types based on file extension if (ext != null) { switch (ext.ToLower()) { case ".mp3": type = "audio/mpeg"; break; case ".htm": case ".html": type = "text/HTML"; break; case ".txt": type = "text/plain"; break; case ".doc": case ".rtf": type = "Application/msword"; break; } } if (forceDownload) { Response.AppendHeader("content-disposition", "attachment; filename=" + name.Replace(" ", "_")); } if (type != "") { Response.ContentType = type; } else { Response.ContentType = "application/x-msdownload"; } System.IO.Stream iStream = null; // Buffer to read 10K bytes in chunk: byte[] buffer = new Byte[10000]; // Length of the file: int length; // Total bytes to read: long dataToRead; try { // Open the file. iStream = new System.IO.FileStream(path, System.IO.FileMode.Open, System.IO.FileAccess.Read, System.IO.FileShare.Read); // Total bytes to read: dataToRead = iStream.Length; //Response.ContentType = "application/octet-stream"; //Response.AddHeader("Content-Disposition", "attachment; filename=" + filename); // Read the bytes. while (dataToRead &gt; 0) { // Verify that the client is connected. if (Response.IsClientConnected) { // Read the data in buffer. length = iStream.Read(buffer, 0, 10000); // Write the data to the current output stream. Response.OutputStream.Write(buffer, 0, length); // Flush the data to the HTML output. Response.Flush(); buffer = new Byte[10000]; dataToRead = dataToRead - length; } else { //prevent infinite loop if user disconnects dataToRead = -1; } } } catch (Exception ex) { // Trap the error, if any. Response.Write("Error : " + ex.Message); } finally { if (iStream != null) { //Close the file. iStream.Close(); } Response.Close(); } } </code></pre>
[ { "answer_id": 187022, "author": "kaa", "author_id": 2105, "author_profile": "https://Stackoverflow.com/users/2105", "pm_score": 2, "selected": false, "text": "<p>Will</p>\n\n<pre><code>&lt;configuration&gt;\n &lt;system.web&gt;\n &lt;httpRuntime executionTimeout=\"3600\"/&gt;\n &lt;/system.web&gt;\n&lt;/configuration&gt;\n</code></pre>\n\n<p>help anything?</p>\n\n<p>The inner loop that writes the data seems a bit convoluted, I would at least change it to:</p>\n\n<pre><code>int length;\nwhile( Response.IsClientConnected &amp;&amp; \n (length=iStream.Read(buffer,0,buffer.Length))&gt;0 ) \n{\n Response.OutputStream.Write(buffer,0,length);\n Response.Flush();\n}\n</code></pre>\n\n<p>There is no need to reallocate the buffer each round through the loop, you can simply re-use it after you have written it to the output.</p>\n\n<p>A further improvement would be to use asyncronous IO but that is for another day.</p>\n" }, { "answer_id": 339345, "author": "daveywc", "author_id": 10135, "author_profile": "https://Stackoverflow.com/users/10135", "pm_score": 1, "selected": true, "text": "<p>The final fix for this problem was to make a modification in the web.config file. I simply had to change sessionState mode=\"InProc\" to sessionState mode=\"StateServer\". </p>\n" }, { "answer_id": 2867014, "author": "Abhishek Shrivastava", "author_id": 328116, "author_profile": "https://Stackoverflow.com/users/328116", "pm_score": 2, "selected": false, "text": "<p>I had a similar problem when I was using FileUpload Control and I was uploading a file size >4MB . I used to get 'The connection was reset' error page. And this the steps that I followed to fix the problem:</p>\n\n<p>Go to the web.config file and set a size limit that is appropriate for the types of files that you expect to be uploaded. The default size limit is 4096 kilobytes (KB), or 4 megabytes (MB). You can allow larger files to be uploaded by setting the maxRequestLength attribute of the httpRuntime element. To increase the maximum allowable file size for the entire application, set the maxRequestLength attribute in the Web.config file.</p>\n\n<p>For example to allow 10MB (10240 KB) file..I used (REPLACE '[' with '&lt;' and ']' with '>')<br><br>\n [configuration]<br>\n [system.web]<br>\n [httpRuntime maxRequestLength=\"10240\"/] <br>\n [/system.web]<br>\n[/configuration]</p>\n" }, { "answer_id": 12861312, "author": "Greg Finzer", "author_id": 52962, "author_profile": "https://Stackoverflow.com/users/52962", "pm_score": 0, "selected": false, "text": "<p>What ended up working for me is doing a Response.End and also doing a using statement with the file stream. Here is the code that I have:</p>\n\n<pre><code>public partial class ssl_Report_StreamReport : BaseReportPage\n{\n protected void Page_Load(object sender, EventArgs e)\n {\n //Get the parameters\n string reportName = Utils.ParseStringRequest(Request, \"reportName\") ?? string.Empty;\n string reportGuid = Session[\"reportGuid\"].ToString();\n string path = Path.Combine(ReportPath(), Utils.GetSessionReportName(reportName, reportGuid));\n\n using (var fileStream = File.Open(path, FileMode.Open))\n {\n Response.ClearHeaders();\n Response.Clear();\n Response.ContentType = \"application/octet-stream\";\n Response.AddHeader(\"Content-Disposition\", \"attachment; filename=\\\"\" + reportName + \"\\\"\");\n Response.AddHeader(\"Content-Length\", fileStream.Length.ToString(CultureInfo.InvariantCulture));\n StreamHelper.CopyStream(fileStream, Response.OutputStream);\n Response.Flush();\n Response.End();\n }\n\n ReportProcessor.ClearReport(Session.SessionID, path);\n }\n}\n\n\npublic static class StreamHelper\n{\n public static void CopyStream(Stream input, Stream output)\n {\n byte[] buffer = new byte[32768];\n int read;\n while ((read = input.Read(buffer, 0, buffer.Length)) &gt; 0)\n {\n output.Write(buffer, 0, read);\n }\n }\n}\n</code></pre>\n" } ]
2008/10/09
[ "https://Stackoverflow.com/questions/187000", "https://Stackoverflow.com", "https://Stackoverflow.com/users/10135/" ]
I have an asp.net website that allows the user to download largish files - 30mb to about 60mb. Sometimes the download works fine but often it fails at some varying point before the download finishes with the message saying that the connection with the server was reset. Originally I was simply using Server.TransmitFile but after reading up a bit I am now using the code posted below. I am also setting the Server.ScriptTimeout value to 3600 in the Page\_Init event. ``` private void DownloadFile(string fname, bool forceDownload) { string path = MapPath(fname); string name = Path.GetFileName(path); string ext = Path.GetExtension(path); string type = ""; // set known types based on file extension if (ext != null) { switch (ext.ToLower()) { case ".mp3": type = "audio/mpeg"; break; case ".htm": case ".html": type = "text/HTML"; break; case ".txt": type = "text/plain"; break; case ".doc": case ".rtf": type = "Application/msword"; break; } } if (forceDownload) { Response.AppendHeader("content-disposition", "attachment; filename=" + name.Replace(" ", "_")); } if (type != "") { Response.ContentType = type; } else { Response.ContentType = "application/x-msdownload"; } System.IO.Stream iStream = null; // Buffer to read 10K bytes in chunk: byte[] buffer = new Byte[10000]; // Length of the file: int length; // Total bytes to read: long dataToRead; try { // Open the file. iStream = new System.IO.FileStream(path, System.IO.FileMode.Open, System.IO.FileAccess.Read, System.IO.FileShare.Read); // Total bytes to read: dataToRead = iStream.Length; //Response.ContentType = "application/octet-stream"; //Response.AddHeader("Content-Disposition", "attachment; filename=" + filename); // Read the bytes. while (dataToRead > 0) { // Verify that the client is connected. if (Response.IsClientConnected) { // Read the data in buffer. length = iStream.Read(buffer, 0, 10000); // Write the data to the current output stream. Response.OutputStream.Write(buffer, 0, length); // Flush the data to the HTML output. Response.Flush(); buffer = new Byte[10000]; dataToRead = dataToRead - length; } else { //prevent infinite loop if user disconnects dataToRead = -1; } } } catch (Exception ex) { // Trap the error, if any. Response.Write("Error : " + ex.Message); } finally { if (iStream != null) { //Close the file. iStream.Close(); } Response.Close(); } } ```
The final fix for this problem was to make a modification in the web.config file. I simply had to change sessionState mode="InProc" to sessionState mode="StateServer".
187,001
<p>Is it possible to provide WCF with a custom proxy address and custom credentials? </p> <p>I've found this answer on stackoverflow: <a href="https://stackoverflow.com/questions/105499/how-to-set-proxy-with-credentials-to-generated-wcf-client">How to set proxy with credentials to generated WCF client?</a>, but I've got a complication, the service I'm authenticating against uses its own authentication, so I've got to use two sets of credentials (one to get through the proxy, and the other to authenticate against the service)</p> <p>I'm using the technique described in the answers to the other question to provide the service credentials. e.g.</p> <pre><code>client.ClientCredentials.UserName.UserName = username; client.ClientCredentials.UserName.Password = password; </code></pre> <p>I can set the address of the proxy using something like this:</p> <pre><code>(client.Endpoint.Binding as WSHttpBinding).ProxyAddress = ...; </code></pre> <p>How do I set what is effectively two sets of credentials? (NB: The credentials for the proxy and the actual service are different!) Also note that the proxy details are not necessarily the default system proxy details.</p>
[ { "answer_id": 187152, "author": "sebagomez", "author_id": 23893, "author_profile": "https://Stackoverflow.com/users/23893", "pm_score": 2, "selected": false, "text": "<p>The client credentials you're setting are fine in order to authenticate to your services.<br>\nFor proxy authentication you need to use HttpTransportSecurity.ProxyCredentials.</p>\n\n<p>This link might help you out.</p>\n\n<p><a href=\"http://msdn.microsoft.com/en-us/library/system.servicemodel.httptransportsecurity.proxycredentialtype.aspx\" rel=\"nofollow noreferrer\">http://msdn.microsoft.com/en-us/library/system.servicemodel.httptransportsecurity.proxycredentialtype.aspx</a></p>\n" }, { "answer_id": 2111642, "author": "Bradley Grainger", "author_id": 23633, "author_profile": "https://Stackoverflow.com/users/23633", "pm_score": 5, "selected": true, "text": "<p>If you set the <a href=\"http://msdn.microsoft.com/en-us/library/system.net.webrequest.defaultwebproxy.aspx\" rel=\"noreferrer\">WebRequest.DefaultWebProxy</a> property to a new WebProxy with credentials, WCF will use it for all HTTP requests that it makes. (This will affect all HttpWebRequests used by the application unless explicitly overridden).</p>\n\n<pre><code>// get this information from the user / config file / etc.\nUri proxyAddress;\nstring userName;\nstring password;\n\n// set this before any web requests or WCF calls\nWebRequest.DefaultWebProxy = new WebProxy(proxyAddress)\n{\n Credentials = new NetworkCredential(userName, password),\n};\n</code></pre>\n\n<p>My <a href=\"http://code.logos.com/blog/2010/01/using_http_proxy_servers.html\" rel=\"noreferrer\">blog post on proxy servers</a> contains further details.</p>\n" } ]
2008/10/09
[ "https://Stackoverflow.com/questions/187001", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1313/" ]
Is it possible to provide WCF with a custom proxy address and custom credentials? I've found this answer on stackoverflow: [How to set proxy with credentials to generated WCF client?](https://stackoverflow.com/questions/105499/how-to-set-proxy-with-credentials-to-generated-wcf-client), but I've got a complication, the service I'm authenticating against uses its own authentication, so I've got to use two sets of credentials (one to get through the proxy, and the other to authenticate against the service) I'm using the technique described in the answers to the other question to provide the service credentials. e.g. ``` client.ClientCredentials.UserName.UserName = username; client.ClientCredentials.UserName.Password = password; ``` I can set the address of the proxy using something like this: ``` (client.Endpoint.Binding as WSHttpBinding).ProxyAddress = ...; ``` How do I set what is effectively two sets of credentials? (NB: The credentials for the proxy and the actual service are different!) Also note that the proxy details are not necessarily the default system proxy details.
If you set the [WebRequest.DefaultWebProxy](http://msdn.microsoft.com/en-us/library/system.net.webrequest.defaultwebproxy.aspx) property to a new WebProxy with credentials, WCF will use it for all HTTP requests that it makes. (This will affect all HttpWebRequests used by the application unless explicitly overridden). ``` // get this information from the user / config file / etc. Uri proxyAddress; string userName; string password; // set this before any web requests or WCF calls WebRequest.DefaultWebProxy = new WebProxy(proxyAddress) { Credentials = new NetworkCredential(userName, password), }; ``` My [blog post on proxy servers](http://code.logos.com/blog/2010/01/using_http_proxy_servers.html) contains further details.
187,004
<p>I have a large legacy system to maintain. The codebase uses threads all over the place and those threads share a lot of mutable data. I know, sounds bad. Anyway, don't answer "rewrite the whole application from scratch" or I'll vote you down :-) I have tried to run some static analysis tools on the codebase, but none of those seem to catch this case which occurs a lot in our source code: multiple threads are reading and writing variables which are not marked as volatile or synchronized at all. Typically this occurs on "runFlag"-type variables. An example of this is on Effective Java 2nd edition page 260:</p> <pre><code>public class StopThread { private static boolean stopRequested; public static void main(String[] args) throws InterruptedException { Thread backgroundThread = new Thread(new Runnable() { public void run() { int i = 0; while (!stopRequested) { i++; } } }); backgroundThread.start(); Thread.sleep(1000); stopRequested = true; } } </code></pre> <p>This example never finishes on Windows/Linux with "-server" startup parameter given to Sun JVM. So, is there any (semi-)automatic way to find these issues, or do I have to rely totally on code reviews?</p>
[ { "answer_id": 187054, "author": "Chris Vest", "author_id": 13251, "author_profile": "https://Stackoverflow.com/users/13251", "pm_score": 1, "selected": false, "text": "<p>FindBugs and professional tools based on it are your best hope, but don't count on them finding all of the concurrency woes in your code.</p>\n\n<p>If things are in that bad a shape, then you should supplement the tooling with analysis by a human java concurrency expert.</p>\n\n<p>This is a hard problem because <em>conclusively prooving</em> the correctness of an existing, but modified, code base is probably going to be unrealistic - especially in the face of concurrent usage.</p>\n" }, { "answer_id": 187196, "author": "Tom Hawtin - tackline", "author_id": 4725, "author_profile": "https://Stackoverflow.com/users/4725", "pm_score": 2, "selected": false, "text": "<p>The latest version of FindBugs will attempt to check that fields marked with the <code>@GuardedBy</code> annotation are accessed only within the appropriate guard code.</p>\n" }, { "answer_id": 188163, "author": "Alex Miller", "author_id": 7671, "author_profile": "https://Stackoverflow.com/users/7671", "pm_score": 1, "selected": false, "text": "<p>Coverity makes some static and dynamic analysis tools that may help.</p>\n\n<p><a href=\"http://www.coverity.com/\" rel=\"nofollow noreferrer\">http://www.coverity.com/</a></p>\n" }, { "answer_id": 188792, "author": "McDowell", "author_id": 304, "author_profile": "https://Stackoverflow.com/users/304", "pm_score": 3, "selected": false, "text": "<p>Chris Grindstaff wrote an article <a href=\"http://www.ibm.com/developerworks/java/library/j-findbug2/\" rel=\"noreferrer\">FindBugs, Part 2: Writing custom detectors</a> in which he describes how to use the <a href=\"http://jakarta.apache.org/bcel/index.html\" rel=\"noreferrer\">BCEL</a> to add your own rules. (BCEL isn't the only bytecode library - but it is the one used by FindBugs.)</p>\n\n<p>The code below emits any cases where a method accesses a static method or field. You could run it on any type that implements <em>Runnable</em>.</p>\n\n<pre><code>public class StaticInvocationFinder extends EmptyVisitor {\n\n @Override\n public void visitMethod(Method obj) {\n System.out.println(\"==========================\");\n System.out.println(\"method:\" + obj.getName());\n\n Code code = obj.getCode();\n InstructionList instructions = new InstructionList(code.getCode());\n for (Instruction instruction : instructions.getInstructions()) {\n // static field or method\n if (Constants.INVOKESTATIC == instruction.getOpcode()) {\n if (instruction instanceof InvokeInstruction) {\n InvokeInstruction invokeInstruction = (InvokeInstruction) instruction;\n ConstantPoolGen cpg = new ConstantPoolGen(obj\n .getConstantPool());\n System.out.println(\"static access:\"\n + invokeInstruction.getMethodName(cpg));\n System.out.println(\" on type:\"\n + invokeInstruction.getReferenceType(cpg));\n }\n }\n }\n instructions.dispose();\n }\n\n public static void main(String[] args) throws Exception {\n JavaClass javaClass = Repository.lookupClass(\"StopThread$1\");\n\n StaticInvocationFinder visitor = new StaticInvocationFinder();\n DescendingVisitor classWalker = new DescendingVisitor(javaClass,\n visitor);\n classWalker.visit();\n }\n\n}\n</code></pre>\n\n<p>This code emits the following:</p>\n\n<pre><code>==========================\nmethod:&lt;init&gt;\n==========================\nmethod:run\nstatic access:access$0\n on type:StopThread\n</code></pre>\n\n<p>It would be possible to then scan the type <em>StopThread</em>, find the field and check to see if it is <em>volatile</em>.</p>\n\n<p>Checking for synchronization is possible, but might get tricky due to multiple MONITOREXIT conditions. Walking up call stacks could be difficult too, but then this isn't a trivial problem. However, I think it would be relatively easy to check for a bug pattern if it has been implemented consistently.</p>\n\n<p>BCEL looks scantly documented and really hairy until you find the <em>BCELifier</em> class. If you run it on a class, it spits out Java source of how you would build the class in BCEL. Running it on <em>StopThread</em> gives this for generating the <em>access$0</em> synthetic accessor:</p>\n\n<pre><code> private void createMethod_2() {\n InstructionList il = new InstructionList();\n MethodGen method = new MethodGen(ACC_STATIC | ACC_SYNTHETIC, Type.BOOLEAN, Type.NO_ARGS, new String[] { }, \"access$0\", \"StopThread\", il, _cp);\n\n InstructionHandle ih_0 = il.append(_factory.createFieldAccess(\"StopThread\", \"stopRequested\", Type.BOOLEAN, Constants.GETSTATIC));\n il.append(_factory.createReturn(Type.INT));\n method.setMaxStack();\n method.setMaxLocals();\n _cg.addMethod(method.getMethod());\n il.dispose();\n }\n</code></pre>\n" }, { "answer_id": 300009, "author": "ketorin", "author_id": 24094, "author_profile": "https://Stackoverflow.com/users/24094", "pm_score": 2, "selected": false, "text": "<p>Coverity Thread Analyzer does the job, but that is quite expensive. IBM Multi-Thread Run-time Analysis Tool for Java seems to be able to detect those but it appears somewhat more difficult to set up. These are dynamical analysis tools that detect which actual variables were accessed from different threads without proper synchronization or volatility, so results are more accurate than with static analysis, and are able to find lots of issues that static analysis is unable to detect.</p>\n\n<p>If your code is mostly or at least partly properly synchronized, fixing FindBugs (or other static analysis) concurrency checks might help too, at least rules IS2_INCONSISTENT_SYNC and UG_SYNC_SET_UNSYNC_GET might be good ones to start with.</p>\n" } ]
2008/10/09
[ "https://Stackoverflow.com/questions/187004", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4110/" ]
I have a large legacy system to maintain. The codebase uses threads all over the place and those threads share a lot of mutable data. I know, sounds bad. Anyway, don't answer "rewrite the whole application from scratch" or I'll vote you down :-) I have tried to run some static analysis tools on the codebase, but none of those seem to catch this case which occurs a lot in our source code: multiple threads are reading and writing variables which are not marked as volatile or synchronized at all. Typically this occurs on "runFlag"-type variables. An example of this is on Effective Java 2nd edition page 260: ``` public class StopThread { private static boolean stopRequested; public static void main(String[] args) throws InterruptedException { Thread backgroundThread = new Thread(new Runnable() { public void run() { int i = 0; while (!stopRequested) { i++; } } }); backgroundThread.start(); Thread.sleep(1000); stopRequested = true; } } ``` This example never finishes on Windows/Linux with "-server" startup parameter given to Sun JVM. So, is there any (semi-)automatic way to find these issues, or do I have to rely totally on code reviews?
Chris Grindstaff wrote an article [FindBugs, Part 2: Writing custom detectors](http://www.ibm.com/developerworks/java/library/j-findbug2/) in which he describes how to use the [BCEL](http://jakarta.apache.org/bcel/index.html) to add your own rules. (BCEL isn't the only bytecode library - but it is the one used by FindBugs.) The code below emits any cases where a method accesses a static method or field. You could run it on any type that implements *Runnable*. ``` public class StaticInvocationFinder extends EmptyVisitor { @Override public void visitMethod(Method obj) { System.out.println("=========================="); System.out.println("method:" + obj.getName()); Code code = obj.getCode(); InstructionList instructions = new InstructionList(code.getCode()); for (Instruction instruction : instructions.getInstructions()) { // static field or method if (Constants.INVOKESTATIC == instruction.getOpcode()) { if (instruction instanceof InvokeInstruction) { InvokeInstruction invokeInstruction = (InvokeInstruction) instruction; ConstantPoolGen cpg = new ConstantPoolGen(obj .getConstantPool()); System.out.println("static access:" + invokeInstruction.getMethodName(cpg)); System.out.println(" on type:" + invokeInstruction.getReferenceType(cpg)); } } } instructions.dispose(); } public static void main(String[] args) throws Exception { JavaClass javaClass = Repository.lookupClass("StopThread$1"); StaticInvocationFinder visitor = new StaticInvocationFinder(); DescendingVisitor classWalker = new DescendingVisitor(javaClass, visitor); classWalker.visit(); } } ``` This code emits the following: ``` ========================== method:<init> ========================== method:run static access:access$0 on type:StopThread ``` It would be possible to then scan the type *StopThread*, find the field and check to see if it is *volatile*. Checking for synchronization is possible, but might get tricky due to multiple MONITOREXIT conditions. Walking up call stacks could be difficult too, but then this isn't a trivial problem. However, I think it would be relatively easy to check for a bug pattern if it has been implemented consistently. BCEL looks scantly documented and really hairy until you find the *BCELifier* class. If you run it on a class, it spits out Java source of how you would build the class in BCEL. Running it on *StopThread* gives this for generating the *access$0* synthetic accessor: ``` private void createMethod_2() { InstructionList il = new InstructionList(); MethodGen method = new MethodGen(ACC_STATIC | ACC_SYNTHETIC, Type.BOOLEAN, Type.NO_ARGS, new String[] { }, "access$0", "StopThread", il, _cp); InstructionHandle ih_0 = il.append(_factory.createFieldAccess("StopThread", "stopRequested", Type.BOOLEAN, Constants.GETSTATIC)); il.append(_factory.createReturn(Type.INT)); method.setMaxStack(); method.setMaxLocals(); _cg.addMethod(method.getMethod()); il.dispose(); } ```
187,018
<p>In a page, on the load event, I am dynamically creating controls for display on the page. This is all working properly. the trouble I am having is when adding extenders from the AJAX control toolkit, specifically I am trying to add rounded corners to a button control. No errors are thrown, but the AJAX Extension functionality does not appear in the displayed page.</p> <p>Does anyone have any ideas on what I am not doing correctly, or if its even possible?</p> <pre><code>Dim container As HtmlGenericControl Dim edit As Button Dim editRoundedCorners As AjaxControlToolkit.RoundedCornersExtender For each item in items container = New HtmlGenericControl("div") container.ID = "container_" &amp; item.code edit = New Button() edit.ID = "edit_" &amp; item.code edit.Text = "Edit" edit.Style("padding") = "0 0 0 4px" edit.SkinID = "smallEditButton" editRoundedCorners = New AjaxControlToolkit.RoundedCornersExtender() editRoundedCorners.BorderColor = edit.BorderColor editRoundedCorners.ID = edit.ID &amp; "_RoundedCorners" editRoundedCorners.Corners = AjaxControlToolkit.BoxCorners.All editRoundedCorners.Radius = 3 editRoundedCorners.TargetControlID = edit.ID container.Controls.Add(editRoundedCorners) container.Controls.Add(edit) pageContainer.Controls.Add(container) Next </code></pre> <p>(pageContainer is a div on the page)</p>
[ { "answer_id": 187033, "author": "Rob", "author_id": 7872, "author_profile": "https://Stackoverflow.com/users/7872", "pm_score": 2, "selected": false, "text": "<p>You need to add the \"editRoundedCorners\" to the page, or containers, Controls collection, so try adding the line:</p>\n\n<pre><code>Controls.Add(editRoundedCorners)\n</code></pre>\n\n<p>just before \"'add them to page control collection\" as you may only be adding the edit button, whereas both are required.</p>\n" }, { "answer_id": 189385, "author": "Compulsion", "author_id": 3675, "author_profile": "https://Stackoverflow.com/users/3675", "pm_score": 2, "selected": false, "text": "<p>I'm using C#, so I'll be using that syntax.</p>\n\n<p>As Rob said, you'll need to add the Extender to the page. You can do this by:</p>\n\n<pre><code>*parentCtrl*.Controls.Add(*extendername*);\n</code></pre>\n\n<p>or, alternatively</p>\n\n<pre><code>*controltype* *controlname* = (*controltype*)Page.LoadControl(typeof(*controltype*), new object[]{});\n</code></pre>\n\n<p>If you're passing parameters on to the control, put them in the object array.</p>\n" }, { "answer_id": 201309, "author": "troyappeldorn", "author_id": 27566, "author_profile": "https://Stackoverflow.com/users/27566", "pm_score": 2, "selected": true, "text": "<p>You cannot apply a RoundedCornersExtender to input elements such as TextBox or Buttons.</p>\n" } ]
2008/10/09
[ "https://Stackoverflow.com/questions/187018", "https://Stackoverflow.com", "https://Stackoverflow.com/users/16391/" ]
In a page, on the load event, I am dynamically creating controls for display on the page. This is all working properly. the trouble I am having is when adding extenders from the AJAX control toolkit, specifically I am trying to add rounded corners to a button control. No errors are thrown, but the AJAX Extension functionality does not appear in the displayed page. Does anyone have any ideas on what I am not doing correctly, or if its even possible? ``` Dim container As HtmlGenericControl Dim edit As Button Dim editRoundedCorners As AjaxControlToolkit.RoundedCornersExtender For each item in items container = New HtmlGenericControl("div") container.ID = "container_" & item.code edit = New Button() edit.ID = "edit_" & item.code edit.Text = "Edit" edit.Style("padding") = "0 0 0 4px" edit.SkinID = "smallEditButton" editRoundedCorners = New AjaxControlToolkit.RoundedCornersExtender() editRoundedCorners.BorderColor = edit.BorderColor editRoundedCorners.ID = edit.ID & "_RoundedCorners" editRoundedCorners.Corners = AjaxControlToolkit.BoxCorners.All editRoundedCorners.Radius = 3 editRoundedCorners.TargetControlID = edit.ID container.Controls.Add(editRoundedCorners) container.Controls.Add(edit) pageContainer.Controls.Add(container) Next ``` (pageContainer is a div on the page)
You cannot apply a RoundedCornersExtender to input elements such as TextBox or Buttons.
187,040
<p>I Have an old vbs script file being kicked off by an AutoSys job. Can I, and how do I, return an int return value to indicate success or failure?</p>
[ { "answer_id": 187051, "author": "Rob", "author_id": 7872, "author_profile": "https://Stackoverflow.com/users/7872", "pm_score": 6, "selected": false, "text": "<p>Try:</p>\n\n<pre><code>WScript.Quit n\n</code></pre>\n\n<p>Where n is the ERRORLEVEL you want to return</p>\n" }, { "answer_id": 187055, "author": "Philip.ie", "author_id": 180142, "author_profile": "https://Stackoverflow.com/users/180142", "pm_score": 6, "selected": true, "text": "<p>I found the answer :0)</p>\n\n<pre><code> DIM returnValue\n returnValue = 99\n WScript.Quit(returnValue)\n</code></pre>\n\n<p>This seems to work well.</p>\n" } ]
2008/10/09
[ "https://Stackoverflow.com/questions/187040", "https://Stackoverflow.com", "https://Stackoverflow.com/users/180142/" ]
I Have an old vbs script file being kicked off by an AutoSys job. Can I, and how do I, return an int return value to indicate success or failure?
I found the answer :0) ``` DIM returnValue returnValue = 99 WScript.Quit(returnValue) ``` This seems to work well.
187,046
<p>Has anyone seen a tool that will integrate code coverage results with SCM/VCS to attribute untested lines of code to developers? For example, is there a tool that will take NCover's Coverage.Xml, combine it with SVN blame, and produce a report that tells me things like developer who commits most untested code?</p>
[ { "answer_id": 187051, "author": "Rob", "author_id": 7872, "author_profile": "https://Stackoverflow.com/users/7872", "pm_score": 6, "selected": false, "text": "<p>Try:</p>\n\n<pre><code>WScript.Quit n\n</code></pre>\n\n<p>Where n is the ERRORLEVEL you want to return</p>\n" }, { "answer_id": 187055, "author": "Philip.ie", "author_id": 180142, "author_profile": "https://Stackoverflow.com/users/180142", "pm_score": 6, "selected": true, "text": "<p>I found the answer :0)</p>\n\n<pre><code> DIM returnValue\n returnValue = 99\n WScript.Quit(returnValue)\n</code></pre>\n\n<p>This seems to work well.</p>\n" } ]
2008/10/09
[ "https://Stackoverflow.com/questions/187046", "https://Stackoverflow.com", "https://Stackoverflow.com/users/26479/" ]
Has anyone seen a tool that will integrate code coverage results with SCM/VCS to attribute untested lines of code to developers? For example, is there a tool that will take NCover's Coverage.Xml, combine it with SVN blame, and produce a report that tells me things like developer who commits most untested code?
I found the answer :0) ``` DIM returnValue returnValue = 99 WScript.Quit(returnValue) ``` This seems to work well.
187,057
<p>I want to know how the glBlendFunc works. For example, i have 2 gl textures, where the alpha is on tex1, i want to have alpha in my final image. Where the color is on tex1, i want the color from tex2 to be.</p>
[ { "answer_id": 187309, "author": "Lee Baldwin", "author_id": 5200, "author_profile": "https://Stackoverflow.com/users/5200", "pm_score": 1, "selected": false, "text": "<p>glBlendFunc applies only to how the final color fragment gets blended with the frame buffer. I think what you want is multitexturing, to combine the two textures by blending the texture stages using glTexEnv, or using a fragment shader to combine the the two textures.</p>\n" }, { "answer_id": 187494, "author": "akalenuk", "author_id": 25459, "author_profile": "https://Stackoverflow.com/users/25459", "pm_score": 1, "selected": false, "text": "<p>Sorry, can't do this with simple blending. We for instance used to do the same thing using frament shaders.</p>\n" }, { "answer_id": 193253, "author": "BigSandwich", "author_id": 26983, "author_profile": "https://Stackoverflow.com/users/26983", "pm_score": 1, "selected": false, "text": "<p>Seconding the shaders. If you can use a shader its much easier to just do what you want with the data rather than messing with arcane blending functions.</p>\n" }, { "answer_id": 195803, "author": "DavidG", "author_id": 25893, "author_profile": "https://Stackoverflow.com/users/25893", "pm_score": 1, "selected": true, "text": "<p>Sadly, this is for openGL ES on the iPhone, so no shaders, but point taken. My problem was a very simplified version of the questions, i needed to apply a simple color ( incl alpha ), to a part of a defined texture. As Lee pointed out, texture blending is to allow alpha to show up on the framebuffer. The solution was to insist that the artist makes the \"action bit\" of the texture white, and then assigning a color to the vertices that i render. Something like this.</p>\n\n<pre><code>glTexCoordPointer( 2, GL_FLOAT, 0, sprite-&gt;GetTexBuffer() );\nglVertexPointer( 3, GL_FLOAT, 0, sprite-&gt;GetVertexBuffer() );\nglColorPointer( 4, GL_FLOAT, 0, sprite-&gt;GetColorBuffer() );\nglDrawArrays( GL_TRIANGLES, 0, 6 ); // Draw 2 triangles\n</code></pre>\n\n<p>Where even tho it has a texture, having the color means it adds to the texture's color, so where it's an alpha, it remains alpha, and where it is white ( as i had to make it ), it becomes the color of the color pointer at the point.</p>\n" } ]
2008/10/09
[ "https://Stackoverflow.com/questions/187057", "https://Stackoverflow.com", "https://Stackoverflow.com/users/25893/" ]
I want to know how the glBlendFunc works. For example, i have 2 gl textures, where the alpha is on tex1, i want to have alpha in my final image. Where the color is on tex1, i want the color from tex2 to be.
Sadly, this is for openGL ES on the iPhone, so no shaders, but point taken. My problem was a very simplified version of the questions, i needed to apply a simple color ( incl alpha ), to a part of a defined texture. As Lee pointed out, texture blending is to allow alpha to show up on the framebuffer. The solution was to insist that the artist makes the "action bit" of the texture white, and then assigning a color to the vertices that i render. Something like this. ``` glTexCoordPointer( 2, GL_FLOAT, 0, sprite->GetTexBuffer() ); glVertexPointer( 3, GL_FLOAT, 0, sprite->GetVertexBuffer() ); glColorPointer( 4, GL_FLOAT, 0, sprite->GetColorBuffer() ); glDrawArrays( GL_TRIANGLES, 0, 6 ); // Draw 2 triangles ``` Where even tho it has a texture, having the color means it adds to the texture's color, so where it's an alpha, it remains alpha, and where it is white ( as i had to make it ), it becomes the color of the color pointer at the point.
187,059
<p>I have a page with a tab control and each control has almost 15 controls. In total there are 10 tabs and about 150 controls in a page (controls like drop down list, textbox, radiobutton, listbox only).</p> <p>My requirement is that there is a button (submit) at the bottom of the page. I need to check using JavaScript that at least 3 options are selected out of 150 controls in that page irrespective of the tabs which they choose. </p> <p>Please suggest the simplest and easiest way which this could be done in JavaScript on my aspx page.</p>
[ { "answer_id": 187156, "author": "Chris Kimpton", "author_id": 48310, "author_profile": "https://Stackoverflow.com/users/48310", "pm_score": 0, "selected": false, "text": "<p>I would look at something based on the prototype <a href=\"http://www.prototypejs.org/api/form#method-serializeelements\" rel=\"nofollow noreferrer\">serialize</a> method - it can give you a hash of all form controls - it might give you a headstart on what you want. </p>\n\n<p>Something like firebug will help you see what you get and assess if it meets your needs.</p>\n" }, { "answer_id": 187220, "author": "Tom", "author_id": 20, "author_profile": "https://Stackoverflow.com/users/20", "pm_score": 0, "selected": false, "text": "<p>You say that you need to validate that at least three of the options should be selected, but is there a chance that you'd need to validate more than those three? Do the controls have a unique ID or class name? Are you using a specific framework (jQuery, Prototype, etc)?</p>\n\n<p>Without knowing more about your project, it's hard to make any solid suggestions, but using pure JavaScript (without a framework), and assuming that you have, say, unique class names I'd say...</p>\n\n<ul>\n<li>After the DOM has loaded, load all of the controls you need to validate into an array (get them via their ID or class name)</li>\n<li>Attach an event listener to submit to catch whenever it has been clicked</li>\n<li>Before the submit actually occurs, iterate through your list of controls and validate each one as necessary. If the validation is good, continue with the submit's default action; otherwise, return some form of error message to the user.</li>\n</ul>\n\n<p>This may sound like a very general solution, but it's hard to give any concrete code without knowing more about your setup.</p>\n" }, { "answer_id": 187222, "author": "Kon", "author_id": 22303, "author_profile": "https://Stackoverflow.com/users/22303", "pm_score": 3, "selected": true, "text": "<p>Assuming there's only one form on the page (if more then loop through forms and nest the below loop within).</p>\n\n<pre><code> var selectedCount = 0;\n var element;\n\n for (var i = 0; i &lt; document.forms[0].elements.length; i++)\n {\n element = document.forms[0].elements[i];\n\n switch (element.type)\n {\n case 'text':\n if (element.value.length &gt; 0)\n {\n selectedCount++;\n }\n break;\n case 'select-one':\n if (element.selectedIndex &gt; 0)\n {\n selectedCount++;\n }\n break;\n //etc - add cases for checkbox, radio, etc.\n }\n }\n</code></pre>\n" }, { "answer_id": 193618, "author": "Aaron Powell", "author_id": 11388, "author_profile": "https://Stackoverflow.com/users/11388", "pm_score": 0, "selected": false, "text": "<p>jQuery would be a lot simpler to get the controls on the page:</p>\n\n<pre><code>var inputs = $('input');\nvar selects = $('select');\n\nvar textBoxes = $(\"input[type='text']\");\n</code></pre>\n" }, { "answer_id": 20698325, "author": "John Wu", "author_id": 2791540, "author_profile": "https://Stackoverflow.com/users/2791540", "pm_score": 0, "selected": false, "text": "<p>You really should look into using <a href=\"http://jquery.com/\" rel=\"nofollow\">jquery</a> to solve this problem. It's free and all the cool Javascript programmers are using it these days!</p>\n\n<p>If you use jquery, your problem becomes quite trivial. The following line of code would search the entire page and return the number of list items anywhere that are selected.</p>\n\n<pre><code>var count = $(\"option:selected\").length;\n</code></pre>\n" } ]
2008/10/09
[ "https://Stackoverflow.com/questions/187059", "https://Stackoverflow.com", "https://Stackoverflow.com/users/22162/" ]
I have a page with a tab control and each control has almost 15 controls. In total there are 10 tabs and about 150 controls in a page (controls like drop down list, textbox, radiobutton, listbox only). My requirement is that there is a button (submit) at the bottom of the page. I need to check using JavaScript that at least 3 options are selected out of 150 controls in that page irrespective of the tabs which they choose. Please suggest the simplest and easiest way which this could be done in JavaScript on my aspx page.
Assuming there's only one form on the page (if more then loop through forms and nest the below loop within). ``` var selectedCount = 0; var element; for (var i = 0; i < document.forms[0].elements.length; i++) { element = document.forms[0].elements[i]; switch (element.type) { case 'text': if (element.value.length > 0) { selectedCount++; } break; case 'select-one': if (element.selectedIndex > 0) { selectedCount++; } break; //etc - add cases for checkbox, radio, etc. } } ```
187,069
<p>It seems the ObservableCollection only support add, remove, clear operation from the UI thread, It throw Not Support Exception if it is operated by a NO UI thread. I tried to override methods of ObservableCollection, unfortunatly, I met lots of problems. Any one can provide me a ObservableCollection sample which can be operated by multi-threads? Many thanks!</p>
[ { "answer_id": 187081, "author": "Mark Ingram", "author_id": 986, "author_profile": "https://Stackoverflow.com/users/986", "pm_score": 4, "selected": true, "text": "<p>Using the link provided by <a href=\"https://stackoverflow.com/questions/187069/can-not-operate-observablecollection-in-multi-threads#187078\">Kent</a>, you could use the following code to modify a collection across threads:</p>\n\n<pre><code>while (!Monitor.TryEnter(_lock, 10))\n{\n DoEvents();\n}\n\ntry\n{\n //modify collection\n}\nfinally\n{\n Monitor.Exit(_lock);\n}\n</code></pre>\n\n<p>If however you're just looking to modify the collection on your original thread you can try using a callback to your UI thread. I normally do something like this:</p>\n\n<pre><code>this.Dispatcher.Invoke(new MyDelegate((myParam) =&gt;\n{\n this.MyCollection.Add(myParam);\n}), state);\n</code></pre>\n" }, { "answer_id": 187096, "author": "Bob King", "author_id": 6897, "author_profile": "https://Stackoverflow.com/users/6897", "pm_score": 2, "selected": false, "text": "<p>You've basically got to Invoke or BeginInvoke over to the UI thread to do those operations.</p>\n\n<pre><code>Public Delegate Sub AddItemDelegate(ByVal item As T)\n\nPublic Sub AddItem(ByVal item As T)\n If Application.Current.Dispatcher.CheckAccess() Then\n Me.Add(item)\n Else\n Application.Current.Dispatcher.Invoke(Threading.DispatcherPriority.Normal, New AddItemDelegate(AddressOf AddItem), item)\n End If\nEnd Sub\n</code></pre>\n" }, { "answer_id": 13389450, "author": "Jesse Chisholm", "author_id": 1456887, "author_profile": "https://Stackoverflow.com/users/1456887", "pm_score": 2, "selected": false, "text": "<p>Personally, I find Bob's style of answer easier to use than Mark's style of answer. Here are the C# WPF snippets for doing this:</p>\n\n<ol>\n<li><p>in your class's constructor, get the current dispatcher as you create\nyour observable collections. Because, as you pointed out, modifications need to\nbe done on the <strong>original</strong> thread, which may not be the <em>main</em> GUI thread.\nSo <strong>Application.Current.Dispatcher</strong> isn't alwasys right,\nand not all classes have a <strong>this.Dispatcher</strong>.</p>\n\n<pre><code>_dispatcher = System.Windows.Threading.Dispatcher.CurrentDispatcher;\n_data = new ObservableCollection&lt;MyDataItemClass&gt;();\n</code></pre></li>\n<li><p>Use the dispatcher to Invoke your code sections\nthat need the original thread.</p>\n\n<pre><code>_dispatcher.Invoke(new Action(() =&gt; { _data.Add(dataItem); }));\n</code></pre></li>\n</ol>\n\n<p>That should do the trick for you. Though there are situations you might prefer <strong>.BeginInvoke</strong> instead of <strong>.Invoke</strong>.</p>\n" }, { "answer_id": 14298053, "author": "Richard Griffiths", "author_id": 1864489, "author_profile": "https://Stackoverflow.com/users/1864489", "pm_score": 2, "selected": false, "text": "<p>You might want to investigate my answer to this perhaps -but <code>please note</code> that the code came from here and cannot be credited to me. Though I tried to implement it in VB. : <a href=\"http://geekswithblogs.net/NewThingsILearned/archive/2008/01/16/have-worker-thread-update-observablecollection-that-is-bound-to-a.aspx\" rel=\"nofollow\">Original Site</a></p>\n\n<p>I've used this to populate a WPF listbox from a class that has an ObservableCollectionEx populated asynchronously from an access database. It does work.</p>\n\n<pre><code>public class ObservableCollectionEx&lt;T&gt; : ObservableCollection&lt;T&gt;\n{\n // Override the event so this class can access it\n public override event System.Collections.Specialized.NotifyCollectionChangedEventHandler \n CollectionChanged;\n\n protected override void OnCollectionChanged (System.Collections.Specialized.NotifyCollectionChangedEventArgs e)\n {\n // Be nice - use BlockReentrancy like MSDN said\n using (BlockReentrancy())\n {\n System.Collections.Specialized.NotifyCollectionChangedEventHandler eventHandler = CollectionChanged;\n if (eventHandler == null)\n return;\n\n Delegate[] delegates = eventHandler.GetInvocationList();\n // Walk thru invocation list\n foreach (System.Collections.Specialized.NotifyCollectionChangedEventHandler handler in delegates)\n {\n DispatcherObject dispatcherObject = handler.Target as DispatcherObject;\n // If the subscriber is a DispatcherObject and different thread\n if (dispatcherObject != null &amp;&amp; dispatcherObject.CheckAccess() == false)\n {\n // Invoke handler in the target dispatcher's thread\n dispatcherObject.Dispatcher.Invoke(DispatcherPriority.DataBind, handler, this, e);\n }\n else // Execute handler as is\n handler(this, e);\n }\n }\n}\n}\n</code></pre>\n" } ]
2008/10/09
[ "https://Stackoverflow.com/questions/187069", "https://Stackoverflow.com", "https://Stackoverflow.com/users/25749/" ]
It seems the ObservableCollection only support add, remove, clear operation from the UI thread, It throw Not Support Exception if it is operated by a NO UI thread. I tried to override methods of ObservableCollection, unfortunatly, I met lots of problems. Any one can provide me a ObservableCollection sample which can be operated by multi-threads? Many thanks!
Using the link provided by [Kent](https://stackoverflow.com/questions/187069/can-not-operate-observablecollection-in-multi-threads#187078), you could use the following code to modify a collection across threads: ``` while (!Monitor.TryEnter(_lock, 10)) { DoEvents(); } try { //modify collection } finally { Monitor.Exit(_lock); } ``` If however you're just looking to modify the collection on your original thread you can try using a callback to your UI thread. I normally do something like this: ``` this.Dispatcher.Invoke(new MyDelegate((myParam) => { this.MyCollection.Add(myParam); }), state); ```
187,073
<p>I'm using the sortable function in jquery to sequence a faq list. Needless to say, i'm new to this concept. Anybody have any good examples of the backend for this. I have the front working fine, but updating the sequence in the database is another story. My backend is ColdFusion btw.</p> <p>Thanks in advance</p>
[ { "answer_id": 187111, "author": "Tomasz Tybulewicz", "author_id": 17405, "author_profile": "https://Stackoverflow.com/users/17405", "pm_score": 5, "selected": true, "text": "<p>Define the faq:</p>\n\n<pre><code>&lt;div id=\"faq\"&gt;\n &lt;div id=\"q1\"&gt;...&lt;/div&gt;\n &lt;div id=\"q2\"&gt;...&lt;/div&gt;\n (...)\n &lt;div id=\"q100\"&gt;..&lt;/div&gt;\n&lt;/div&gt;\n</code></pre>\n\n<p>Make faq sortable:</p>\n\n<pre><code>&lt;script type=\"text/javascript\"&gt;\n $(\"#faq\").sortable();\n&lt;/script&gt;\n</code></pre>\n\n<p>Form submitted:</p>\n\n<pre><code>&lt;form action=\"...\" id=\"faq_form\"&gt;\n &lt;input type=\"hidden\" name=\"faqs\" id=\"faqs\" /&gt;\n ...\n&lt;/form&gt;\n</code></pre>\n\n<p>Add sorted sequence to form</p>\n\n<pre><code>&lt;script type=\"text/javascript&gt;\n $(\"#faq_form\").submit(function() {\n $(\"#faqs\").val($(\"#faq\").sortable('toArray'))\n })\n&lt;/script&gt;\n</code></pre>\n\n<p>When form is submitted, field \"faqs\" will contain comma separated id's from #faq like this:\nq1,q3,q10,q11,q2,q100...</p>\n\n<p>Just parse it and save to DB</p>\n" }, { "answer_id": 3228140, "author": "Mohammad Faheem", "author_id": 389205, "author_profile": "https://Stackoverflow.com/users/389205", "pm_score": 2, "selected": false, "text": "<p>Here is simple example of Jquery UI Sortable,how it can be used with div's.</p>\n\n<p>First include libraries in your html:</p>\n\n<pre><code> &lt;link href=\"http://ajax.googleapis.com/ajax/libs/jqueryui/1.8/themes/base/jquery-ui.css\" rel=\"stylesheet\" type=\"text/css\"/&gt;` &lt;script src=\"http://ajax.googleapis.com/ajax/libs/jquery/1.4/jquery.min.js\"&gt;&lt;/script&gt;`&lt;script src=\"http://ajax.googleapis.com/ajax/libs/jqueryui/1.8/jquery-ui.min.js\"&gt;&lt;/script&gt;``\n</code></pre>\n\n<p>Html for making sortable:</p>\n\n<pre><code>&lt;div id=\"target\"&gt;\n &lt;div style=\"cursor: move;\" class=\"entity\"&gt;\n &lt;div class=\"digit\"&gt;&lt;span&gt;1&lt;/span&gt;&lt;tab /&gt;&amp;nbsp; First Item &lt;/div&gt; \n &lt;/div&gt; \n &lt;div style=\"cursor: move;\" class=\"entity\"&gt;\n &lt;div class=\"digit\"&gt;&lt;span&gt;2&lt;/span&gt;&amp;nbsp; Second Item&lt;/div&gt; \n &lt;/div&gt; \n &lt;div style=\"cursor: move;\" class=\"entity\"&gt;\n &lt;div class=\"digit\"&gt;&lt;span&gt;3&lt;/span&gt;&amp;nbsp; Third Item&lt;/div&gt; \n &lt;/div&gt;\n &lt;div style=\"cursor: move;\" class=\"entity\"&gt;\n &lt;div class=\"digit\"&gt;&lt;span&gt;4&lt;/span&gt;&amp;nbsp; Fourth Item&lt;/div&gt; \n &lt;/div&gt;\n &lt;div style=\"cursor: move;\" class=\"entity\"&gt;\n &lt;div class=\"digit\"&gt;&lt;span&gt;5&lt;/span&gt;&amp;nbsp; Fifth Item&lt;/div&gt; \n &lt;/div&gt;\n&lt;/div&gt;\n</code></pre>\n\n<p>Here is the sortable function:</p>\n\n<pre><code>$(document).ready(function() {\n $('#target').sortable({\n items:'div.entity', //the div which we want to make sortable \n scroll:true, //If set to true, the page \n //scrolls when coming to an edge.\n update:function(event,ui){ renumber(); } //This event is triggered when the user \n //stopped sorting and the DOM position has changed.\n });\n});\n</code></pre>\n\n<p>renuber() is called from the Sortable update event handler callback:</p>\n\n<pre><code>function renumber()\n{\n $('.digit span').each(function(index,element) {\n $(element).html(index+1);\n });\n}\n</code></pre>\n" } ]
2008/10/09
[ "https://Stackoverflow.com/questions/187073", "https://Stackoverflow.com", "https://Stackoverflow.com/users/26121/" ]
I'm using the sortable function in jquery to sequence a faq list. Needless to say, i'm new to this concept. Anybody have any good examples of the backend for this. I have the front working fine, but updating the sequence in the database is another story. My backend is ColdFusion btw. Thanks in advance
Define the faq: ``` <div id="faq"> <div id="q1">...</div> <div id="q2">...</div> (...) <div id="q100">..</div> </div> ``` Make faq sortable: ``` <script type="text/javascript"> $("#faq").sortable(); </script> ``` Form submitted: ``` <form action="..." id="faq_form"> <input type="hidden" name="faqs" id="faqs" /> ... </form> ``` Add sorted sequence to form ``` <script type="text/javascript> $("#faq_form").submit(function() { $("#faqs").val($("#faq").sortable('toArray')) }) </script> ``` When form is submitted, field "faqs" will contain comma separated id's from #faq like this: q1,q3,q10,q11,q2,q100... Just parse it and save to DB
187,076
<p>I have a CSV file that holds about 200,000 - 300,000 records. Most of the records can be separated and inserted into a MySQL database with a simple </p> <pre><code>$line = explode("\n", $fileData); </code></pre> <p>and then the values separated with</p> <pre><code>$lineValues = explode(',', $line); </code></pre> <p>and then inserted into the database using the proper data type i.e int, float, string, text, etc.</p> <p>However, some of the records have a text column that includes a \n in the string. Which breaks when using the $line = explode("\n", $fileData); method. Each line of data that needs to be inserted into the database has approximately 216 columns. not every line has a record with a \n in the string. However, each time a \n is found in the line it is enclosed between a pair of single quotes (')</p> <p>each line is set up in the following format:</p> <pre><code>id,data,data,data,text,more data </code></pre> <p>example:</p> <pre><code>1,0,0,0,'Hello World,0 2,0,0,0,'Hello World',0 3,0,0,0,'Hi',0 4,0,0,0,,0 </code></pre> <p>As you can see from the example, most records can be easily split with the methods shown above. Its the second record in the example that causes the problem.</p> <p>New lines are only \n and the file does not include \r in the file at all.</p>
[ { "answer_id": 187091, "author": "ConroyP", "author_id": 2287, "author_profile": "https://Stackoverflow.com/users/2287", "pm_score": -1, "selected": false, "text": "<p>If you could be guaranteed that each new line beginning with a number is a valid new-line (i.e. not in the middle of a text description) then you could try something like the below:</p>\n\n<pre><code>// Replace all new-line then id patterns with new-line 0+id\n$line = preg_replace('/\\n(\\d)/',\"\\n0$1\",$line);\n\n// Split on new-line then id\n$linevalues = preg_split(\"/\\n\\d/\",$data);\n</code></pre>\n\n<p>The first step identifies all lines which have a new line followed by a numeric value. It then prepends \"0\" to this numeric value. The second line splits where it find a new-line then integer.</p>\n\n<p>The \"0\" is added to the front of the id as <a href=\"http://ie2.php.net/manual/en/function.preg-split.php\" rel=\"nofollow noreferrer\"><code>preg_split</code></a> removes the chars it matches from the subsequent matches.</p>\n\n<p>As I say, this will only work if you're sure that the text which breaks a line won't start a new line with a number.</p>\n" }, { "answer_id": 187101, "author": "finnw", "author_id": 12048, "author_profile": "https://Stackoverflow.com/users/12048", "pm_score": 2, "selected": true, "text": "<p>If the csv data is in a file, you can just use fgetcsv() as others have pointed out.\nfgetcsv handles embedded newlines correctly.</p>\n\n<p>However if your csv data is in a string (like $fileData in your example) the following method may be useful as str_getcsv() only works on a row at a time and cannot split a whole file into records.</p>\n\n<p>You can detect the embedded newlines by counting the quotes in each line. If there are an odd number of quotes, you have an incomplete line, so concatenate this line with the following line. Once you have an even number of quotes, you have a complete record.</p>\n\n<p>Once you have a complete record, split it at the quotes (again using explode()). Odd-numbered fields are quoted (thus embedded commas are not special), even-numbered fields are not.</p>\n\n<p>Example:</p>\n\n<pre><code># Split file into physical lines (records may span lines)\n$lines = explode(\"\\n\", $fileData);\n\n# Re-assemble records\n$records = array ();\n$record = '';\n$lineSep = '';\nforeach ($lines as $line) {\n # Escape @ symbol so we can use it as a marker (as it does not conflict with\n # any special CSV character.)\n $line = str_replace('@', '@a', $line);\n\n # Escape commas as we don't yet know which ones are separators\n $line = str_replace(',', '@c', $line);\n\n # Escape quotes in a form that uses no special characters\n $line = str_replace(\"\\\\'\", '@q', $line);\n $line = str_replace('\\\\', '@b', $line);\n\n $record .= $lineSep . $line;\n $lineSep = \"\\n\";\n\n # Must have an even number of quotes in a complete record!\n if (substr_count($record, \"'\") % 2 == 0) {\n $records[] = $record;\n $record = '';\n $lineSep = '';\n }\n}\nif (strlen($record) &gt; 0) {\n $records[] = $record;\n}\n\n$rows = array ();\n\nforeach ($records as $record) {\n $chunks_in = explode(\"'\", $record);\n $chunks_out = array ();\n\n # Decode escaped quotes/backslashes.\n # Decode field-separating commas (unless quoted)\n foreach ($chunks_in as $i =&gt; $chunk) {\n # Unescape quotes &amp; backslashes\n $chunk = str_replace('@q', \"'\", $chunk);\n $chunk = str_replace('@b', '\\\\', $chunk);\n if ($i % 2 == 0) {\n # Unescape commas\n $chunk = str_replace('@c', ',', $chunk);\n }\n $chunks_out[] = $chunk;\n }\n\n # Join back together, discarding unescaped quotes\n $record = join('', $chunks_out);\n\n $chunks_in = explode(',', $record);\n $row = array ();\n foreach ($chunks_in as $chunk) {\n $chunk = str_replace('@c', ',', $chunk);\n $chunk = str_replace('@a', '@', $chunk);\n $row[] = $chunk;\n }\n $rows[] = $row;\n}\n</code></pre>\n" }, { "answer_id": 187122, "author": "Henrik Paul", "author_id": 2238, "author_profile": "https://Stackoverflow.com/users/2238", "pm_score": 1, "selected": false, "text": "<p>how about manually iterating through the data, from start to finish, with a for-loop or two? It's slower than <code>explode()</code>, but it's easier to get consistent and reliable results regarding quotes.</p>\n\n<p>If you choose this method, remeber to take escaped quotes into account.</p>\n" }, { "answer_id": 187154, "author": "pilsetnieks", "author_id": 6615, "author_profile": "https://Stackoverflow.com/users/6615", "pm_score": 2, "selected": false, "text": "<p>The other advice here is, of course, valid, especially if you aim to write your own CSV parser, however, if you just want to get the data out, use <a href=\"http://php.net/fgetcsv\" rel=\"nofollow noreferrer\">fgetcsv()</a> function and don't worry about implementation details.</p>\n" }, { "answer_id": 187186, "author": "KernelM", "author_id": 22328, "author_profile": "https://Stackoverflow.com/users/22328", "pm_score": 0, "selected": false, "text": "<p>Use <code>fgetcsv</code> and it'll take care of all of that for you. Unless there's some overriding reason you need to have your own CSV parser.</p>\n" } ]
2008/10/09
[ "https://Stackoverflow.com/questions/187076", "https://Stackoverflow.com", "https://Stackoverflow.com/users/24802/" ]
I have a CSV file that holds about 200,000 - 300,000 records. Most of the records can be separated and inserted into a MySQL database with a simple ``` $line = explode("\n", $fileData); ``` and then the values separated with ``` $lineValues = explode(',', $line); ``` and then inserted into the database using the proper data type i.e int, float, string, text, etc. However, some of the records have a text column that includes a \n in the string. Which breaks when using the $line = explode("\n", $fileData); method. Each line of data that needs to be inserted into the database has approximately 216 columns. not every line has a record with a \n in the string. However, each time a \n is found in the line it is enclosed between a pair of single quotes (') each line is set up in the following format: ``` id,data,data,data,text,more data ``` example: ``` 1,0,0,0,'Hello World,0 2,0,0,0,'Hello World',0 3,0,0,0,'Hi',0 4,0,0,0,,0 ``` As you can see from the example, most records can be easily split with the methods shown above. Its the second record in the example that causes the problem. New lines are only \n and the file does not include \r in the file at all.
If the csv data is in a file, you can just use fgetcsv() as others have pointed out. fgetcsv handles embedded newlines correctly. However if your csv data is in a string (like $fileData in your example) the following method may be useful as str\_getcsv() only works on a row at a time and cannot split a whole file into records. You can detect the embedded newlines by counting the quotes in each line. If there are an odd number of quotes, you have an incomplete line, so concatenate this line with the following line. Once you have an even number of quotes, you have a complete record. Once you have a complete record, split it at the quotes (again using explode()). Odd-numbered fields are quoted (thus embedded commas are not special), even-numbered fields are not. Example: ``` # Split file into physical lines (records may span lines) $lines = explode("\n", $fileData); # Re-assemble records $records = array (); $record = ''; $lineSep = ''; foreach ($lines as $line) { # Escape @ symbol so we can use it as a marker (as it does not conflict with # any special CSV character.) $line = str_replace('@', '@a', $line); # Escape commas as we don't yet know which ones are separators $line = str_replace(',', '@c', $line); # Escape quotes in a form that uses no special characters $line = str_replace("\\'", '@q', $line); $line = str_replace('\\', '@b', $line); $record .= $lineSep . $line; $lineSep = "\n"; # Must have an even number of quotes in a complete record! if (substr_count($record, "'") % 2 == 0) { $records[] = $record; $record = ''; $lineSep = ''; } } if (strlen($record) > 0) { $records[] = $record; } $rows = array (); foreach ($records as $record) { $chunks_in = explode("'", $record); $chunks_out = array (); # Decode escaped quotes/backslashes. # Decode field-separating commas (unless quoted) foreach ($chunks_in as $i => $chunk) { # Unescape quotes & backslashes $chunk = str_replace('@q', "'", $chunk); $chunk = str_replace('@b', '\\', $chunk); if ($i % 2 == 0) { # Unescape commas $chunk = str_replace('@c', ',', $chunk); } $chunks_out[] = $chunk; } # Join back together, discarding unescaped quotes $record = join('', $chunks_out); $chunks_in = explode(',', $record); $row = array (); foreach ($chunks_in as $chunk) { $chunk = str_replace('@c', ',', $chunk); $chunk = str_replace('@a', '@', $chunk); $row[] = $chunk; } $rows[] = $row; } ```
187,098
<p>I am writing a dhtml application that creates an interactive simulation of a system. The data for the simulation is generated from another tool, and there is already a very large amount of legacy data.</p> <p>Some steps in the simulation require that we play "voice-over" clips of audio. I've been unable to find an easy way to accomplish this across multiple browsers. </p> <p><a href="http://www.schillmania.com/projects/soundmanager2/" rel="noreferrer">Soundmanager2</a> comes pretty close to what I need, but it will only play mp3 files, and the legacy data may contain some .wav files as well. </p> <p>Does anyone have any other libraries that might help?</p>
[ { "answer_id": 187117, "author": "Ilya Kochetov", "author_id": 15329, "author_profile": "https://Stackoverflow.com/users/15329", "pm_score": 3, "selected": false, "text": "<p>I believe that the simplest and most convenient way would be to play the sound using a small Flash clip. I appreciate it's not a JavaScript solution but it IS the easiest way to achieve your goal</p>\n\n<p>Some extra links from the previous <a href=\"https://stackoverflow.com/questions/82141/producing-2-or-more-short-sounds-when-a-web-page-loads#82181\">similar question</a>:</p>\n\n<ul>\n<li>Scriptaculous, a Javascript library: <a href=\"http://github.com/madrobby/scriptaculous/wikis/sound\" rel=\"nofollow noreferrer\">http://github.com/madrobby/scriptaculous/wikis/sound</a></li>\n<li>an opensource Flash project: Easy Musicplayer For Flash <a href=\"http://emff.sourceforge.net/\" rel=\"nofollow noreferrer\">http://emff.sourceforge.net/</a></li>\n</ul>\n" }, { "answer_id": 187187, "author": "ceejayoz", "author_id": 1902010, "author_profile": "https://Stackoverflow.com/users/1902010", "pm_score": 3, "selected": false, "text": "<p>If you're using Prototype, the Scriptaculous library <a href=\"http://github.com/madrobby/scriptaculous/wikis/sound\" rel=\"nofollow noreferrer\">has a sound API</a>. jQuery <a href=\"http://dev.jquery.com/browser/trunk/plugins/sound/jquery.sound.js?rev=5750\" rel=\"nofollow noreferrer\">appears to have a plugin</a>, too.</p>\n" }, { "answer_id": 187415, "author": "dacracot", "author_id": 13930, "author_profile": "https://Stackoverflow.com/users/13930", "pm_score": 7, "selected": true, "text": "<p>You will have to include a plug-in like Real Audio or QuickTime to handle the .wav file, but this should work...</p>\n\n<pre><code>//======================================================================\nvar soundEmbed = null;\n//======================================================================\nfunction soundPlay(which)\n {\n if (!soundEmbed)\n {\n soundEmbed = document.createElement(\"embed\");\n soundEmbed.setAttribute(\"src\", \"/snd/\"+which+\".wav\");\n soundEmbed.setAttribute(\"hidden\", true);\n soundEmbed.setAttribute(\"autostart\", true);\n }\n else\n {\n document.body.removeChild(soundEmbed);\n soundEmbed.removed = true;\n soundEmbed = null;\n soundEmbed = document.createElement(\"embed\");\n soundEmbed.setAttribute(\"src\", \"/snd/\"+which+\".wav\");\n soundEmbed.setAttribute(\"hidden\", true);\n soundEmbed.setAttribute(\"autostart\", true);\n }\n soundEmbed.removed = false;\n document.body.appendChild(soundEmbed);\n }\n//======================================================================\n</code></pre>\n" }, { "answer_id": 187440, "author": "cheeaun", "author_id": 20838, "author_profile": "https://Stackoverflow.com/users/20838", "pm_score": 2, "selected": false, "text": "<p>If you are using Mootools, there is the <a href=\"http://msteigerwalt.com/widgets/sounds/\" rel=\"nofollow noreferrer\">MooSound plugin</a>.</p>\n" }, { "answer_id": 1935187, "author": "joshoreefe", "author_id": 235405, "author_profile": "https://Stackoverflow.com/users/235405", "pm_score": 3, "selected": false, "text": "<p>dacracots code is clean basic dom, but perhaps written without a second thought?\nOf course you check the existance of an earlier embed first, and save the duplicate\nembed creation lines. </p>\n\n<pre><code>var soundEmbed = null;\n//=====================================================================\n\nfunction soundPlay(which)\n{\n if (soundEmbed)\n document.body.removeChild(soundEmbed);\n soundEmbed = document.createElement(\"embed\");\n soundEmbed.setAttribute(\"src\", \"/snd/\"+which+\".wav\");\n soundEmbed.setAttribute(\"hidden\", true);\n soundEmbed.setAttribute(\"autostart\", true);\n document.body.appendChild(soundEmbed);\n}\n</code></pre>\n\n<p>Came across the thoughts here while scanning for a solution for somewhat similar situation. Unfortunately my browser Mozilla/5.0 (X11; U; Linux i686; en-US; rv:1.9.0.15) Gecko/2009102814 Ubuntu/8.04 (hardy) Firefox/3.0.15 dies when trying this.</p>\n\n<p>After installing latest updates, firefox still crashes, opera keeps alive.</p>\n" }, { "answer_id": 3885939, "author": "Alon Gubkin", "author_id": 140937, "author_profile": "https://Stackoverflow.com/users/140937", "pm_score": 3, "selected": false, "text": "<p>You can use the HTML5 <code>&lt;audio&gt;</code> tag.</p>\n" }, { "answer_id": 7760017, "author": "Howard", "author_id": 459778, "author_profile": "https://Stackoverflow.com/users/459778", "pm_score": 3, "selected": false, "text": "<p>I liked dacracot's answer... here is a similar solution in jQuery:</p>\n\n<pre><code>function Play(sound) {\n $(\"#sound_\").remove()\n $('body').append('&lt;embed id=\"sound_\" autostart=\"true\" hidden=\"true\" src=\"/static/sound/' + sound + '.wav\" /&gt;');\n}\n</code></pre>\n" }, { "answer_id": 13807759, "author": "Andrew Mackenzie", "author_id": 573149, "author_profile": "https://Stackoverflow.com/users/573149", "pm_score": 2, "selected": false, "text": "<pre><code>&lt;audio controls&gt;\n &lt;source src=\"horse.ogg\" type=\"audio/ogg\"&gt;\n &lt;source src=\"horse.mp3\" type=\"audio/mpeg\"&gt;\nYour browser does not support the audio element.\n&lt;/audio&gt;\n</code></pre>\n\n<p>See <a href=\"http://www.w3schools.com/html/html5_audio.asp\" rel=\"nofollow\">http://www.w3schools.com/html/html5_audio.asp</a> for more details.</p>\n" }, { "answer_id": 23625670, "author": "Andrew Howard", "author_id": 1402073, "author_profile": "https://Stackoverflow.com/users/1402073", "pm_score": 1, "selected": false, "text": "<p>There is a far more simpler solution to this rather than having to resort to plug-ins. IE has it's own bgsound property and there is another way you can make it work for all other browsers. Check out my tutorial here = <a href=\"http://www.andy-howard.com/how-to-play-sounds-cross-browser-including-ie/index.html\" rel=\"nofollow\">http://www.andy-howard.com/how-to-play-sounds-cross-browser-including-ie/index.html</a></p>\n" }, { "answer_id": 59308578, "author": "Hugo", "author_id": 3214497, "author_profile": "https://Stackoverflow.com/users/3214497", "pm_score": 0, "selected": false, "text": "<p>For a cross browser solution with wav files I would suggest to make an <code>&lt;audio&gt;</code> tag default and then go for the <code>&lt;embed&gt;</code> solution that @dacracot suggested before <a href=\"https://stackoverflow.com/a/187415/3214497\">here</a> if the user is in IE, you can check it easily with a little search here in SO.</p>\n" } ]
2008/10/09
[ "https://Stackoverflow.com/questions/187098", "https://Stackoverflow.com", "https://Stackoverflow.com/users/22383/" ]
I am writing a dhtml application that creates an interactive simulation of a system. The data for the simulation is generated from another tool, and there is already a very large amount of legacy data. Some steps in the simulation require that we play "voice-over" clips of audio. I've been unable to find an easy way to accomplish this across multiple browsers. [Soundmanager2](http://www.schillmania.com/projects/soundmanager2/) comes pretty close to what I need, but it will only play mp3 files, and the legacy data may contain some .wav files as well. Does anyone have any other libraries that might help?
You will have to include a plug-in like Real Audio or QuickTime to handle the .wav file, but this should work... ``` //====================================================================== var soundEmbed = null; //====================================================================== function soundPlay(which) { if (!soundEmbed) { soundEmbed = document.createElement("embed"); soundEmbed.setAttribute("src", "/snd/"+which+".wav"); soundEmbed.setAttribute("hidden", true); soundEmbed.setAttribute("autostart", true); } else { document.body.removeChild(soundEmbed); soundEmbed.removed = true; soundEmbed = null; soundEmbed = document.createElement("embed"); soundEmbed.setAttribute("src", "/snd/"+which+".wav"); soundEmbed.setAttribute("hidden", true); soundEmbed.setAttribute("autostart", true); } soundEmbed.removed = false; document.body.appendChild(soundEmbed); } //====================================================================== ```
187,100
<p>I have an object that needs a test if the object data is valid. The validation itself would be called from the thread that instatiated the object, it looks like this:</p> <pre><code> { if (_step.Equals(string.Empty)) return false; if (_type.Equals(string.Empty)) return false; if (_setup.Equals(string.Empty)) return false; return true; } </code></pre> <p>Would it be better to implement this as a property, or as a method, and why? I have read the answers to a <a href="https://stackoverflow.com/questions/164023/what-guidelines-are-appropriate-for-determining-when-to-implement-a-class-membe">related question</a>, but I don't think this specific question is covered there.</p>
[ { "answer_id": 187110, "author": "Gregor", "author_id": 26153, "author_profile": "https://Stackoverflow.com/users/26153", "pm_score": 1, "selected": false, "text": "<p>I would say as a Property.</p>\n\n<pre><code>if(something.IsValid) { ...\n</code></pre>\n\n<p>looks better then</p>\n\n<pre><code>if(something.IsValid()) { ...\n</code></pre>\n\n<p>Also an example from MSDN: <a href=\"http://msdn.microsoft.com/en-us/library/system.web.ui.page.isvalid(VS.71).aspx\" rel=\"nofollow noreferrer\">http://msdn.microsoft.com/en-us/library/system.web.ui.page.isvalid(VS.71).aspx</a></p>\n" }, { "answer_id": 187112, "author": "Rob", "author_id": 7872, "author_profile": "https://Stackoverflow.com/users/7872", "pm_score": 4, "selected": true, "text": "<p>My personal opinion here would be:</p>\n\n<ul>\n<li>If the \"validate\" method mutates the object in any way (which your example doesn't) then make it a method.</li>\n<li>If the object remains un-changed after validation, make it a property.</li>\n</ul>\n" }, { "answer_id": 187118, "author": "Konrad Rudolph", "author_id": 1968, "author_profile": "https://Stackoverflow.com/users/1968", "pm_score": 1, "selected": false, "text": "<p>That code needs refactoring. This is how you write code in Java, not in C#. In C#, you've got operator overloading.</p>\n\n<pre><code>if (_step == \"\")) return false;\nif (_type == \"\")) return false;\nif (_setup == \"\")) return false;\n</code></pre>\n\n<p>This is the idiomatic way of doing the comparison. Your way, besides being more verbose, is just unexpected and inconsistent in C#.</p>\n\n<p>If, <em>and only if</em>, there's a chance that these strings are actually <code>null</code> instead of empty, use the following instead:</p>\n\n<pre><code>if (string.IsNullOrEmpty(_step)) return false;\n</code></pre>\n" } ]
2008/10/09
[ "https://Stackoverflow.com/questions/187100", "https://Stackoverflow.com", "https://Stackoverflow.com/users/22114/" ]
I have an object that needs a test if the object data is valid. The validation itself would be called from the thread that instatiated the object, it looks like this: ``` { if (_step.Equals(string.Empty)) return false; if (_type.Equals(string.Empty)) return false; if (_setup.Equals(string.Empty)) return false; return true; } ``` Would it be better to implement this as a property, or as a method, and why? I have read the answers to a [related question](https://stackoverflow.com/questions/164023/what-guidelines-are-appropriate-for-determining-when-to-implement-a-class-membe), but I don't think this specific question is covered there.
My personal opinion here would be: * If the "validate" method mutates the object in any way (which your example doesn't) then make it a method. * If the object remains un-changed after validation, make it a property.
187,125
<p>Trying to create a user account in a test. But getting a Object reference is not set to an instanve of an object error when running it.</p> <p>Here's my MemberShip provider class, it's in a class library MyCompany.MyApp.Domain.dll:</p> <pre><code>using System; using System.Collections.Generic; using System.Web.Security; namespace MyCompany.MyApp.Domain { public class MyMembershipProvider : SqlMembershipProvider { const int defaultPasswordLength = 8; private int resetPasswordLength; public override void Initialize(string name, System.Collections.Specialized.NameValueCollection config) { resetPasswordLength = defaultPasswordLength; string resetPasswordLengthConfig = config["resetPasswordLength"]; if (!String.IsNullOrEmpty(resetPasswordLengthConfig)) { config.Remove("resetPasswordLength"); if (!int.TryParse(resetPasswordLengthConfig, out resetPasswordLength)) { resetPasswordLength = defaultPasswordLength; } } base.Initialize(name, config); } public override string GeneratePassword() { return Utils.PasswordGenerator.GeneratePasswordAsWord(resetPasswordLength); } } } </code></pre> <p>Here's my App.Config for my seperate Test Class Library MyCompany.MyApp.Doman.Test.dll that references my business domain library above:</p> <pre><code>&lt;?xml version="1.0" encoding="utf-8" ?&gt; &lt;configuration&gt; &lt;connectionStrings&gt; &lt;add name="SqlServer" connectionString="data source=mycomp\SQL2008;Integrated Security=SSPI;Initial Catalog=myDatabase" providerName="System.Data.SqlClient"/&gt; &lt;/connectionStrings&gt; &lt;system.web&gt; &lt;membership defaultProvider="MyMembershipProvider" userIsOnlineTimeWindow="15"&gt; &lt;providers&gt; &lt;clear/&gt; &lt;add name="MyMembershipProvider" type="MyCompany.MyApp.Domain.MyMembershipProvider,MyCompany.MyApp.Domain" connectionStringName="SqlServer" applicationName="MyApp" minRequiredNonalphanumericCharacters="0" enablePasswordRetrieval="false" enablePasswordReset="true" requiresQuestionAndAnswer="false" requiresUniqueEmail="true" passwordFormat="Hashed"/&gt; &lt;/providers&gt; &lt;/membership&gt; &lt;/system.web&gt; &lt;/configuration&gt; </code></pre> <p>Here's my method that throws "Object reference is not set to an instanve of an object"</p> <pre><code>public class MemberTest { public static void CreateAdminMemberIfNotExists() { MembershipCreateStatus status; status = MembershipCreateStatus.ProviderError; MyMembershipProvider provider = new MyMembershipProvider(); provider.CreateUser("Admin", "password", "[email protected]", "Question", "Answer", true, Guid.NewGuid(), out status); } } </code></pre> <p>it throws on the provider.CreateUser line</p>
[ { "answer_id": 187142, "author": "Chris Kimpton", "author_id": 48310, "author_profile": "https://Stackoverflow.com/users/48310", "pm_score": 0, "selected": false, "text": "<p>Is the error directly on provider.CreateUser or somewhere down the stack inside it - perhaps you could check for null before calling.</p>\n\n<p>Perhaps a dependancy is missing - have you got the relevant DB dll's on the path?</p>\n" }, { "answer_id": 187165, "author": "csgero", "author_id": 21764, "author_profile": "https://Stackoverflow.com/users/21764", "pm_score": 3, "selected": true, "text": "<p>I'm quite sure you should call provider.Initialize(...) in your test code before calling CreateUser.</p>\n" }, { "answer_id": 190658, "author": "hollystyles", "author_id": 2083160, "author_profile": "https://Stackoverflow.com/users/2083160", "pm_score": 1, "selected": false, "text": "<p>Well not quite anyone had the answer. csgero was on the right track though initialize was the problem. But just calling that directly was not a solution. This works:</p>\n\n<pre><code>public class MemberTest\n {\n public static void CreateAdminMemberIfNotExists()\n {\n MembershipCreateStatus status;\n MembershipUser member = Membership.CreateUser(\"Admin\", \"password\", \"[email protected]\", \"Question\", \"Answer\", true, out status);\n }\n }\n</code></pre>\n\n<p>I believe instantiating my membership provider directly requires setting the config properties typically stored in the app.config or web.config and then calling initialize. Calling the static CreateUser method on the Mebership class however causes the config to be read, then the type specified in the config is parsed, loaded and initialised.</p>\n" } ]
2008/10/09
[ "https://Stackoverflow.com/questions/187125", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2083160/" ]
Trying to create a user account in a test. But getting a Object reference is not set to an instanve of an object error when running it. Here's my MemberShip provider class, it's in a class library MyCompany.MyApp.Domain.dll: ``` using System; using System.Collections.Generic; using System.Web.Security; namespace MyCompany.MyApp.Domain { public class MyMembershipProvider : SqlMembershipProvider { const int defaultPasswordLength = 8; private int resetPasswordLength; public override void Initialize(string name, System.Collections.Specialized.NameValueCollection config) { resetPasswordLength = defaultPasswordLength; string resetPasswordLengthConfig = config["resetPasswordLength"]; if (!String.IsNullOrEmpty(resetPasswordLengthConfig)) { config.Remove("resetPasswordLength"); if (!int.TryParse(resetPasswordLengthConfig, out resetPasswordLength)) { resetPasswordLength = defaultPasswordLength; } } base.Initialize(name, config); } public override string GeneratePassword() { return Utils.PasswordGenerator.GeneratePasswordAsWord(resetPasswordLength); } } } ``` Here's my App.Config for my seperate Test Class Library MyCompany.MyApp.Doman.Test.dll that references my business domain library above: ``` <?xml version="1.0" encoding="utf-8" ?> <configuration> <connectionStrings> <add name="SqlServer" connectionString="data source=mycomp\SQL2008;Integrated Security=SSPI;Initial Catalog=myDatabase" providerName="System.Data.SqlClient"/> </connectionStrings> <system.web> <membership defaultProvider="MyMembershipProvider" userIsOnlineTimeWindow="15"> <providers> <clear/> <add name="MyMembershipProvider" type="MyCompany.MyApp.Domain.MyMembershipProvider,MyCompany.MyApp.Domain" connectionStringName="SqlServer" applicationName="MyApp" minRequiredNonalphanumericCharacters="0" enablePasswordRetrieval="false" enablePasswordReset="true" requiresQuestionAndAnswer="false" requiresUniqueEmail="true" passwordFormat="Hashed"/> </providers> </membership> </system.web> </configuration> ``` Here's my method that throws "Object reference is not set to an instanve of an object" ``` public class MemberTest { public static void CreateAdminMemberIfNotExists() { MembershipCreateStatus status; status = MembershipCreateStatus.ProviderError; MyMembershipProvider provider = new MyMembershipProvider(); provider.CreateUser("Admin", "password", "[email protected]", "Question", "Answer", true, Guid.NewGuid(), out status); } } ``` it throws on the provider.CreateUser line
I'm quite sure you should call provider.Initialize(...) in your test code before calling CreateUser.
187,137
<p>This is my query:</p> <pre><code>$query = $this-&gt;db-&gt;query(' SELECT archives.id, archives.signature, type_of_source.description, media_type.description, origin.description FROM archives, type_of_source, media_type, origin WHERE archives.type_of_source_id = type_of_source.id AND type_of_source.media_type_id = media_type.id AND archives.origin_id = origin.id ORDER BY archives.id ASC '); </code></pre> <p>But how to output the result? This works, but only gets the last description (origin.description):</p> <pre><code>foreach ($query-&gt;result_array() as $row) { echo $row['description']; } </code></pre> <p>This doesn't work: </p> <pre><code>foreach ($query-&gt;result_array() as $row) { echo $row['type_of_source.description']; } </code></pre> <p>Or should I rename the columns (e.g. type_of_source_description)?</p>
[ { "answer_id": 187175, "author": "pilsetnieks", "author_id": 6615, "author_profile": "https://Stackoverflow.com/users/6615", "pm_score": 4, "selected": true, "text": "<p>This actually has very little to do with CodeIgniter and a lot with how mysql_fetch_assoc provides the query results.</p>\n<p>The solution is that you should rename the columns inside the query using <code>&quot;AS&quot;</code>, e.g.</p>\n<pre><code>select type_of_source.description as type_of_source_description, origin.descripotion as origin_descripotion from ....\n</code></pre>\n" }, { "answer_id": 187376, "author": "Pittsburgh DBA", "author_id": 10224, "author_profile": "https://Stackoverflow.com/users/10224", "pm_score": 2, "selected": false, "text": "<p>Just alias the columns in the SELECT statement. Do not modify your database. The standard practice is to use aliasing in your SQL statements.</p>\n<p>From PostgreSQL's docs for <code>&quot;SELECT&quot;</code>:</p>\n<p>&quot;Using the clause AS output_name, another name can be specified for an output column.&quot;</p>\n<p><a href=\"http://www.postgresql.org/docs/8.0/interactive/sql-select.html\" rel=\"nofollow noreferrer\">PostgreSQL SELECT</a></p>\n" }, { "answer_id": 289871, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 1, "selected": false, "text": "<p>I recommend not to use it that way instead, you can rename output columns with <code>AS</code>.</p>\n" } ]
2008/10/09
[ "https://Stackoverflow.com/questions/187137", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4196/" ]
This is my query: ``` $query = $this->db->query(' SELECT archives.id, archives.signature, type_of_source.description, media_type.description, origin.description FROM archives, type_of_source, media_type, origin WHERE archives.type_of_source_id = type_of_source.id AND type_of_source.media_type_id = media_type.id AND archives.origin_id = origin.id ORDER BY archives.id ASC '); ``` But how to output the result? This works, but only gets the last description (origin.description): ``` foreach ($query->result_array() as $row) { echo $row['description']; } ``` This doesn't work: ``` foreach ($query->result_array() as $row) { echo $row['type_of_source.description']; } ``` Or should I rename the columns (e.g. type\_of\_source\_description)?
This actually has very little to do with CodeIgniter and a lot with how mysql\_fetch\_assoc provides the query results. The solution is that you should rename the columns inside the query using `"AS"`, e.g. ``` select type_of_source.description as type_of_source_description, origin.descripotion as origin_descripotion from .... ```
187,138
<p>How would you store formatted blocks of text (line breaks, tabs, lists - etc.) in a database (nothing specific) to be displayed on the web (XHTML) while maintaining a level of abstraction so that the data can be used in other applications or if the structure of the website were to change in the future?</p>
[ { "answer_id": 187175, "author": "pilsetnieks", "author_id": 6615, "author_profile": "https://Stackoverflow.com/users/6615", "pm_score": 4, "selected": true, "text": "<p>This actually has very little to do with CodeIgniter and a lot with how mysql_fetch_assoc provides the query results.</p>\n<p>The solution is that you should rename the columns inside the query using <code>&quot;AS&quot;</code>, e.g.</p>\n<pre><code>select type_of_source.description as type_of_source_description, origin.descripotion as origin_descripotion from ....\n</code></pre>\n" }, { "answer_id": 187376, "author": "Pittsburgh DBA", "author_id": 10224, "author_profile": "https://Stackoverflow.com/users/10224", "pm_score": 2, "selected": false, "text": "<p>Just alias the columns in the SELECT statement. Do not modify your database. The standard practice is to use aliasing in your SQL statements.</p>\n<p>From PostgreSQL's docs for <code>&quot;SELECT&quot;</code>:</p>\n<p>&quot;Using the clause AS output_name, another name can be specified for an output column.&quot;</p>\n<p><a href=\"http://www.postgresql.org/docs/8.0/interactive/sql-select.html\" rel=\"nofollow noreferrer\">PostgreSQL SELECT</a></p>\n" }, { "answer_id": 289871, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 1, "selected": false, "text": "<p>I recommend not to use it that way instead, you can rename output columns with <code>AS</code>.</p>\n" } ]
2008/10/09
[ "https://Stackoverflow.com/questions/187138", "https://Stackoverflow.com", "https://Stackoverflow.com/users/23746/" ]
How would you store formatted blocks of text (line breaks, tabs, lists - etc.) in a database (nothing specific) to be displayed on the web (XHTML) while maintaining a level of abstraction so that the data can be used in other applications or if the structure of the website were to change in the future?
This actually has very little to do with CodeIgniter and a lot with how mysql\_fetch\_assoc provides the query results. The solution is that you should rename the columns inside the query using `"AS"`, e.g. ``` select type_of_source.description as type_of_source_description, origin.descripotion as origin_descripotion from .... ```
187,146
<p>Why is the order of tables important when combining an outer &amp; an inner join ? the following fails with postgres:</p> <pre><code>SELECT grp.number AS number, tags.value AS tag FROM groups grp, insrel archiverel LEFT OUTER JOIN ownrel ownrel ON grp.number = ownrel.dnumber LEFT OUTER JOIN tags tags ON tags.number = ownrel.snumber WHERE archiverel.snumber = 11128188 AND archiverel.dnumber = grp.number </code></pre> <p>with result:</p> <pre><code>ERROR: invalid reference to FROM-clause entry for table "grp" LINE 5: LEFT OUTER JOIN ownrel ownrel ON grp.number = ownrel.d... ^ HINT: There is an entry for table "grp", but it cannot be referenced from this part of the query. </code></pre> <p>when the groups are reversed in the FROM it all works:</p> <pre><code>SELECT grp.number AS number, tags.value AS tag FROM insrel archiverel, groups grp LEFT OUTER JOIN ownrel ownrel ON grp.number = ownrel.dnumber LEFT OUTER JOIN tags tags ON tags.number = ownrel.snumber WHERE archiverel.snumber = 11128188 AND archiverel.dnumber = grp.number </code></pre>
[ { "answer_id": 187164, "author": "RB.", "author_id": 15393, "author_profile": "https://Stackoverflow.com/users/15393", "pm_score": 3, "selected": false, "text": "<p>Because in the first one grp is not part of the join the ON clause belongs to.</p>\n" }, { "answer_id": 187184, "author": "Jeffrey L Whitledge", "author_id": 10174, "author_profile": "https://Stackoverflow.com/users/10174", "pm_score": 2, "selected": false, "text": "<p>I don't know what is causing that behavior, if it's a bug or by design, but it should work fine if you stick with one form of join or the other.</p>\n\n<pre><code>SELECT grp.number AS number, \n tags.value AS tag \nFROM groups grp\nJOIN insrel archiverel ON archiverel.dnumber = grp.number\nLEFT OUTER JOIN ownrel ownrel ON grp.number = ownrel.dnumber \nLEFT OUTER JOIN tags tags ON tags.number = ownrel.snumber \nWHERE archiverel.snumber = 11128188\n</code></pre>\n\n<p>I would be interested to know more if the behavior is by design.</p>\n" }, { "answer_id": 187224, "author": "Joel Coehoorn", "author_id": 3043, "author_profile": "https://Stackoverflow.com/users/3043", "pm_score": 2, "selected": false, "text": "<p>For an inner join, the order of the tables is not important.</p>\n\n<p>For an outer join, it is. <em>All</em> the rows from the table on the side specified (is it a LEFT or RIGHT join) will be included, while only rows that match the join criteria will be included from the table on the other side.</p>\n\n<p>Because OUTER JOINS keep all rows from one side, they are said to (in general) increase result sets. INNER JOINS only keep rows from both sides if they match, so they are said (in general) to reduce result sets. Thus, you typically want to do your INNER JOINS before the OUTER JOINS (when possible).</p>\n\n<p>In your case, it's almost certainly a result of the evil A,B syntax. </p>\n" }, { "answer_id": 187275, "author": "Cowan", "author_id": 17041, "author_profile": "https://Stackoverflow.com/users/17041", "pm_score": 4, "selected": false, "text": "<p>I don't think anyone's quite nailed this, or explained it very well. You're combining 'old style' (theta) and 'new style' (ANSI) joins, which I strongly suspect are being grouped in ways you don't expect. Look at it this way:</p>\n\n\n\n<pre><code>SELECT * FROM a, b JOIN c ON a.x = c.x\n</code></pre>\n\n<p>is like saying</p>\n\n<pre><code>SELECT * FROM a, (b JOIN c on a.x = c.x)\n</code></pre>\n\n<p>where the bracketed thing represents a bunch of tables merged into one virtual table, to be joined on with a theta-join against 'a'. Obviously the 'a' table can't be part of the join as it's only being joined onto later. Reverse it, and you're doing</p>\n\n<pre><code>SELECT * FROM b, (a JOIN c on a.x = c.x)\n</code></pre>\n\n<p>which is perfectly understandable and so fine. I'm not sure why you're not using ANSI join syntax for all of it though, seems a little weird (and cruel to the person who has to maintain it!)</p>\n" }, { "answer_id": 187277, "author": "Dave Costa", "author_id": 6568, "author_profile": "https://Stackoverflow.com/users/6568", "pm_score": 5, "selected": true, "text": "<p>I believe that you can think of this as an operator precedence issue.</p>\n\n<p>When you write this:</p>\n\n<pre><code>FROM groups grp,\n insrel archiverel \nLEFT OUTER JOIN ownrel ownrel ON grp.number = ownrel.dnumber \nLEFT OUTER JOIN tags tags ON tags.number = ownrel.snumber \n</code></pre>\n\n<p>I think it is interpreted by the parser like this:</p>\n\n<pre><code>FROM groups grp,\n(\n (\n insrel archiverel \n LEFT OUTER JOIN ownrel ownrel ON grp.number = ownrel.dnumber \n )\nLEFT OUTER JOIN tags tags ON tags.number = ownrel.snumber\n)\n</code></pre>\n\n<p>If so, then in the innermost join \"grp\" is unbound.</p>\n\n<p>When you reverse the lines with \"groups\" and \"insrel\", the innermost join applies to \"groups\" and \"ownrel\", so it works.</p>\n\n<p>Probably this would work as well:</p>\n\n<pre><code> FROM groups grp\n JOIN insrel archiverel ON archiverel.dnumber = grp.number\n LEFT OUTER JOIN ownrel ownrel ON grp.number = ownrel.dnumber \n LEFT OUTER JOIN tags tags ON tags.number = ownrel.snumber \nWHERE archiverel.snumber = 11128188\n</code></pre>\n" } ]
2008/10/09
[ "https://Stackoverflow.com/questions/187146", "https://Stackoverflow.com", "https://Stackoverflow.com/users/26486/" ]
Why is the order of tables important when combining an outer & an inner join ? the following fails with postgres: ``` SELECT grp.number AS number, tags.value AS tag FROM groups grp, insrel archiverel LEFT OUTER JOIN ownrel ownrel ON grp.number = ownrel.dnumber LEFT OUTER JOIN tags tags ON tags.number = ownrel.snumber WHERE archiverel.snumber = 11128188 AND archiverel.dnumber = grp.number ``` with result: ``` ERROR: invalid reference to FROM-clause entry for table "grp" LINE 5: LEFT OUTER JOIN ownrel ownrel ON grp.number = ownrel.d... ^ HINT: There is an entry for table "grp", but it cannot be referenced from this part of the query. ``` when the groups are reversed in the FROM it all works: ``` SELECT grp.number AS number, tags.value AS tag FROM insrel archiverel, groups grp LEFT OUTER JOIN ownrel ownrel ON grp.number = ownrel.dnumber LEFT OUTER JOIN tags tags ON tags.number = ownrel.snumber WHERE archiverel.snumber = 11128188 AND archiverel.dnumber = grp.number ```
I believe that you can think of this as an operator precedence issue. When you write this: ``` FROM groups grp, insrel archiverel LEFT OUTER JOIN ownrel ownrel ON grp.number = ownrel.dnumber LEFT OUTER JOIN tags tags ON tags.number = ownrel.snumber ``` I think it is interpreted by the parser like this: ``` FROM groups grp, ( ( insrel archiverel LEFT OUTER JOIN ownrel ownrel ON grp.number = ownrel.dnumber ) LEFT OUTER JOIN tags tags ON tags.number = ownrel.snumber ) ``` If so, then in the innermost join "grp" is unbound. When you reverse the lines with "groups" and "insrel", the innermost join applies to "groups" and "ownrel", so it works. Probably this would work as well: ``` FROM groups grp JOIN insrel archiverel ON archiverel.dnumber = grp.number LEFT OUTER JOIN ownrel ownrel ON grp.number = ownrel.dnumber LEFT OUTER JOIN tags tags ON tags.number = ownrel.snumber WHERE archiverel.snumber = 11128188 ```
187,188
<p>We are hosting a site for a client and they want us to include the header they have on their server into the pages we are hosting. So whenever they change it, it will automatically change on our site.</p> <p>We are attempting to use the "include" tag in our JSP code. The code we are using is as follows:</p> <p><code>&lt;%@ include file="www.CLIENT.com/CLIENT2/MiddlePageFiles/Vendor_header.html" %&gt;</code></p> <p>We also tried </p> <p><code>&lt;%@ include file="**http://**www.CLIENT.com/CLIENT2/MiddlePageFiles/Vendor_header.html" %&gt;</code></p> <p>Unfortunately these aren't working for us. What seems to be happening is that the code is ONLY looking locally for this file and never seems to go "outside" to look for it.</p> <p>We are able to pull the header into our page when we use an iframe but because of the way the header is constructed/coded the mouse over drop-down menus aren't working as they should when we use the iframe. The drop-down menus are "cascading" underneath the rest of the content on the page and we weren't able to bring them to the "top". </p> <p>As a temporary work around, were are hosting the HTML on our own servers.</p> <p>Any ideas? </p>
[ { "answer_id": 187201, "author": "Eli Courtwright", "author_id": 1694, "author_profile": "https://Stackoverflow.com/users/1694", "pm_score": 1, "selected": false, "text": "<p>JSP includes don't support including remote files, which is why a relative URL is required: <a href=\"http://java.sun.com/products/jsp/syntax/1.2/syntaxref1214.html\" rel=\"nofollow noreferrer\">http://java.sun.com/products/jsp/syntax/1.2/syntaxref1214.html</a></p>\n\n<p>I suggest writing a function which opens a connection to that page and downloads the contents and then prints them to your own <code>out</code> stream. Then you can put that function in a local file and just <code>include</code> that.</p>\n" }, { "answer_id": 187230, "author": "Cheekysoft", "author_id": 1820, "author_profile": "https://Stackoverflow.com/users/1820", "pm_score": 3, "selected": true, "text": "<p>If you choose to do this in Java, it's nice and easy using the HttpClient from Apache Commons.</p>\n\n<pre><code>public static String fetchSourceHtml( String urlString ) {\n\n try {\n HttpClient httpClient = new HttpClient();\n GetMethod getMethod = new GetMethod( urlString );\n getMethod.setFollowRedirects( true );\n\n int httpStatus = httpClient.executeMethod( getMethod );\n\n if (httpStatus &gt;= 400) {\n return \"\";\n }\n\n String sourceHtml = getMethod.getResponseBodyAsString();\n return sourceHtml;\n }\n catch (IOException e) {\n return \"\";\n }\n}\n</code></pre>\n\n<p>For a quick and dirty solution, your JSP you can call this method directly. You could, of course, create a taglib tag to call the method if you prefer.</p>\n\n<p>You may want to change the time-out and retry mechanism for HttpClient. By default it will automatically try up to a maximum of 3 times with each attempt timing out after 30s.</p>\n\n<p>However, you probably want to look into caching the strings for a suitable period of time. You really don't want to make 2 blocking external http requests for each page access to your site.</p>\n" }, { "answer_id": 187232, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": -1, "selected": false, "text": "<p>JSP includes are not meant to work like that with external servers. Here is a completely horrible way to fix your problem, but it was the only option for me in a similar situation. Write a class to actually parse the html from that site, and then print it out. I would add that whenever you are going to do something like this, it is always a good idea to have some sort of authentication mechanism in place.</p>\n" }, { "answer_id": 187338, "author": "Keeg", "author_id": 21059, "author_profile": "https://Stackoverflow.com/users/21059", "pm_score": 1, "selected": false, "text": "<p>How about using the JSTL core library and doing:</p>\n\n<pre><code>&lt;c:import url=\"http://www.CLIENT.com/CLIENT2/MiddlePageFiles/Vendor_header.html\" /&gt;\n</code></pre>\n\n<p>That should be able to include remote content at request time. </p>\n" } ]
2008/10/09
[ "https://Stackoverflow.com/questions/187188", "https://Stackoverflow.com", "https://Stackoverflow.com/users/26488/" ]
We are hosting a site for a client and they want us to include the header they have on their server into the pages we are hosting. So whenever they change it, it will automatically change on our site. We are attempting to use the "include" tag in our JSP code. The code we are using is as follows: `<%@ include file="www.CLIENT.com/CLIENT2/MiddlePageFiles/Vendor_header.html" %>` We also tried `<%@ include file="**http://**www.CLIENT.com/CLIENT2/MiddlePageFiles/Vendor_header.html" %>` Unfortunately these aren't working for us. What seems to be happening is that the code is ONLY looking locally for this file and never seems to go "outside" to look for it. We are able to pull the header into our page when we use an iframe but because of the way the header is constructed/coded the mouse over drop-down menus aren't working as they should when we use the iframe. The drop-down menus are "cascading" underneath the rest of the content on the page and we weren't able to bring them to the "top". As a temporary work around, were are hosting the HTML on our own servers. Any ideas?
If you choose to do this in Java, it's nice and easy using the HttpClient from Apache Commons. ``` public static String fetchSourceHtml( String urlString ) { try { HttpClient httpClient = new HttpClient(); GetMethod getMethod = new GetMethod( urlString ); getMethod.setFollowRedirects( true ); int httpStatus = httpClient.executeMethod( getMethod ); if (httpStatus >= 400) { return ""; } String sourceHtml = getMethod.getResponseBodyAsString(); return sourceHtml; } catch (IOException e) { return ""; } } ``` For a quick and dirty solution, your JSP you can call this method directly. You could, of course, create a taglib tag to call the method if you prefer. You may want to change the time-out and retry mechanism for HttpClient. By default it will automatically try up to a maximum of 3 times with each attempt timing out after 30s. However, you probably want to look into caching the strings for a suitable period of time. You really don't want to make 2 blocking external http requests for each page access to your site.
187,189
<p>Assume the following code:</p> <pre><code>using (SqlConnection conn = new SqlConnection(connectionString)) { ... using (SqlCommand comm = new SqlCommand(...)) { .. do stuff .. if(condition) Response.Redirect("somepage.aspx"); } } </code></pre> <p>Will the Response.Redirect() exit from the using blocks cause it to dispose all connections? </p> <p>Or, alternatively, is there any way to exit a using block that won't cause disposal?</p> <p>EDIT: I don't want to exit without disposal. I want to be aware of any pitfalls that would cause it not to work. -- Barring crashes of course, but then I'm pretty sure all objects are disposed --the hard way-- in that situation</p> <p>I've accepted an answer, which essentially says "I don't know" but it's a very well researched "I don't know"</p> <p>For the mean time, I'm going to assume that Response.Redirect aborts the using statement and code with that in mind. -- Until proven otherwise.</p>
[ { "answer_id": 187193, "author": "jop", "author_id": 11830, "author_profile": "https://Stackoverflow.com/users/11830", "pm_score": 2, "selected": false, "text": "<p>Q: Or, alternatively, is there any way to exit a using block that won't cause disposal?</p>\n\n<p>A: None.</p>\n\n<p>See this for more info: <a href=\"https://stackoverflow.com/questions/149609/c-using-syntax#149643\">C# &quot;Using&quot; Syntax</a></p>\n" }, { "answer_id": 187203, "author": "Jason Short", "author_id": 19974, "author_profile": "https://Stackoverflow.com/users/19974", "pm_score": 0, "selected": false, "text": "<p>All using statements are scope based. So no matter how you exit the function everyone that was stack based at that point is cleaned up from the using. Exceptions, returns, etc. </p>\n\n<p>I don't know of any way to prevent one from firing even if you wanted to for some reason.</p>\n" }, { "answer_id": 187210, "author": "yfeldblum", "author_id": 12349, "author_profile": "https://Stackoverflow.com/users/12349", "pm_score": 2, "selected": false, "text": "<p>Response.Redirect terminates the server-side execution.</p>\n\n<p>In the normal course of execution, exiting a using-block triggers object disposal. Exceptions to this rule may occur e.g. when the process is shut down, when the computer is shut down, when a thread is aborted, etc. But not in the normal course of execution.</p>\n\n<p>Look into Server.Transfer. It may help you accomplish your goals.</p>\n" }, { "answer_id": 187211, "author": "Leandro López", "author_id": 22695, "author_profile": "https://Stackoverflow.com/users/22695", "pm_score": 0, "selected": false, "text": "<p>Why would you like to exit an using block without the disposal? That's not the idea of the using block.</p>\n\n<p>Do not use it if you like to, but I wouldn't recommend it.</p>\n" }, { "answer_id": 187234, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 0, "selected": false, "text": "<p>What's wrong with:</p>\n\n<blockquote>\n <p>using(SqlCommand comm = new SqlCommand(...))<br />\n {<br />\n ...<br />\n if(condition)<br />\n {</p>\n \n <blockquote>\n <p>//We have decided this is true so we don't need the using any more<br />\n //Disposal Code</p>\n </blockquote>\n \n <p>break;<br />\n //or continue; if that's better<br />\n }<br />\n //Code that executes in the case of \"if\" not true.<br />\n }</p>\n \n <p>Response.Redirect(page);\"</p>\n</blockquote>\n\n<p>?</p>\n" }, { "answer_id": 187239, "author": "Jason Z", "author_id": 2470, "author_profile": "https://Stackoverflow.com/users/2470", "pm_score": 3, "selected": true, "text": "<p>From <a href=\"http://msdn.microsoft.com/en-us/library/aa973248.aspx\" rel=\"nofollow noreferrer\">http://msdn.microsoft.com/en-us/library/aa973248.aspx</a></p>\n\n<blockquote>\n <p>Calling Response.Redirect WILL NOT\n execute the finally block. Therefore,\n before any redirection or transfer of\n processing can occur, you must dispose\n of the objects.</p>\n</blockquote>\n\n<p>Yes, it does not directly address the Using statement, but it is a common enough programming practice to be aware of. Also, that article refers to SharePoint, but as SP is built on ASP.NET 2.0, I think it is still relevant.</p>\n" }, { "answer_id": 187290, "author": "Even Mien", "author_id": 73794, "author_profile": "https://Stackoverflow.com/users/73794", "pm_score": 3, "selected": false, "text": "<p>From <a href=\"http://msdn.microsoft.com/en-us/library/aa973248.aspx\" rel=\"noreferrer\">http://msdn.microsoft.com/en-us/library/aa973248.aspx</a> and <a href=\"http://msdn.microsoft.com/en-us/magazine/cc163298.aspx\" rel=\"noreferrer\">http://msdn.microsoft.com/en-us/magazine/cc163298.aspx</a>:</p>\n<blockquote>\n<p><strong>Calling Response.Redirect WILL NOT\nexecute the finally block</strong> (<em>and\nlanguage-specific keywords like the C#\n&quot;using&quot; statement</em>). Therefore,\nbefore any redirection or transfer of\nprocessing can occur, you must dispose\nof the objects.</p>\n</blockquote>\n<p>But from <a href=\"http://msdn.microsoft.com/en-us/library/system.threading.threadabortexception.aspx\" rel=\"noreferrer\">http://msdn.microsoft.com/en-us/library/system.threading.threadabortexception.aspx</a>:</p>\n<blockquote>\n<p>When a call is made to the Abort\nmethod to destroy a thread, the common\nlanguage runtime throws a\nThreadAbortException.\nThreadAbortException is a special\nexception that can be caught, but it\nwill automatically be raised again at\nthe end of the catch block. <strong>When this\nexception is raised, the runtime\nexecutes all the finally blocks before\nending the thread.</strong> Since the thread\ncan do an unbounded computation in the\nfinally blocks, or call\nThread..::.ResetAbort to cancel the\nabort, there is no guarantee that the\nthread will ever end. If you want to\nwait until the aborted thread has\nended, you can call the\nThread..::.Join method. Join is a\nblocking call that does not return\nuntil the thread actually stops\nexecuting.</p>\n</blockquote>\n<p>Sounds like a test is in order...</p>\n" } ]
2008/10/09
[ "https://Stackoverflow.com/questions/187189", "https://Stackoverflow.com", "https://Stackoverflow.com/users/18907/" ]
Assume the following code: ``` using (SqlConnection conn = new SqlConnection(connectionString)) { ... using (SqlCommand comm = new SqlCommand(...)) { .. do stuff .. if(condition) Response.Redirect("somepage.aspx"); } } ``` Will the Response.Redirect() exit from the using blocks cause it to dispose all connections? Or, alternatively, is there any way to exit a using block that won't cause disposal? EDIT: I don't want to exit without disposal. I want to be aware of any pitfalls that would cause it not to work. -- Barring crashes of course, but then I'm pretty sure all objects are disposed --the hard way-- in that situation I've accepted an answer, which essentially says "I don't know" but it's a very well researched "I don't know" For the mean time, I'm going to assume that Response.Redirect aborts the using statement and code with that in mind. -- Until proven otherwise.
From <http://msdn.microsoft.com/en-us/library/aa973248.aspx> > > Calling Response.Redirect WILL NOT > execute the finally block. Therefore, > before any redirection or transfer of > processing can occur, you must dispose > of the objects. > > > Yes, it does not directly address the Using statement, but it is a common enough programming practice to be aware of. Also, that article refers to SharePoint, but as SP is built on ASP.NET 2.0, I think it is still relevant.
187,198
<p>I was thinking earlier today about an idea for a small game and stumbled upon how to implement it. The idea is that the player can make a series of moves that cause a little effect, but if done in a specific sequence would cause a greater effect. So far so good, this I know how to do. Obviously, I had to make it be more complicated (because we love to make it more complicated), so I thought that there could be more than one possible path for the sequence that would both cause greater effects, albeit different ones. Also, part of some sequences could be the beggining of other sequences, or even whole sequences could be contained by other bigger sequences. Now I don't know for sure the best way to implement this. I had some ideas, though.</p> <p>1) I could implement a circular n-linked list. But since the list of moves never end, I fear it might cause a stack overflow ™. The idea is that every node would have n children and upon receiving a command, it might lead you to one of his children or, if no children was available to such command, lead you back to the beggining. Upon arrival on any children, a couple of functions would be executed causing the small and big effect. This might, though, lead to a lot of duplicated nodes on the tree to cope up with all the possible sequences ending on that specific move with different effects, which might be a pain to maintain but I am not sure. I never tried something this complex on code, only theoretically. Does this algorithm exist and have a name? Is it a good idea?</p> <p>2) I could implement a state machine. Then instead of wandering around a linked list, I'd have some giant nested switch that would call functions and update the machine state accordingly. Seems simpler to implement, but... well... doesn't seem fun... nor ellegant. Giant switchs always seem ugly to me, but would this work better? </p> <p>3) Suggestions? I am good, but I am far inexperienced. The good thing of the coding field is that no matter how weird your problem is, someone solved it in the past, but you must know where to look. Someone might have a better idea than those I had, and I really wanted to hear suggestions.</p>
[ { "answer_id": 187240, "author": "warren", "author_id": 4418, "author_profile": "https://Stackoverflow.com/users/4418", "pm_score": 1, "selected": false, "text": "<p>What you're describing sounds very similar to the technology tree in a game live Civilization.</p>\n\n<p>I don't know how the Civ authors built theirs, but I'd be inclined to use a multigraph to represent possible 'moves' - there will be some you can start at with no 'experience', and once you're in them, there will be multiple paths through to the end.</p>\n\n<p>Draw-out what potential options you can have at each stage of the game, and then draw lines going from some options to others.</p>\n\n<p>That should give you a start on implementation, as graphs are [relatively] easy concepts to implement and utilize.</p>\n" }, { "answer_id": 187267, "author": "Sergey Volegov", "author_id": 9024, "author_profile": "https://Stackoverflow.com/users/9024", "pm_score": 2, "selected": false, "text": "<p>You might want to implement a state machine anyway, but you don't have to hardcode state transitions.<br>\nTry to make a graph of states, where link between state A to state B will mean A can lead to B.<br>\nThen you can traverse graph at runtime to find where player goes.</p>\n\n<p>Edit: You can define graph node as:<br>\n-state-id<br>\n-list of links to other states, \n where every link defines:<br>\n -state-id<br>\n -precondition, a list of states what must be visited before going to this state</p>\n" }, { "answer_id": 187276, "author": "Jason Z", "author_id": 2470, "author_profile": "https://Stackoverflow.com/users/2470", "pm_score": 1, "selected": false, "text": "<p>Sounds like a <a href=\"http://en.wikipedia.org/wiki/Neural_network\" rel=\"nofollow noreferrer\">neural network</a>. You could create one and train it to recognize the patterns that cause the various effects you are looking for.</p>\n" }, { "answer_id": 187332, "author": "user21714", "author_id": 21714, "author_profile": "https://Stackoverflow.com/users/21714", "pm_score": 1, "selected": false, "text": "<p>What you're describing sounds somewhat similar to a dependency graph or a word graph. You might look into those.</p>\n" }, { "answer_id": 187350, "author": "Cowan", "author_id": 17041, "author_profile": "https://Stackoverflow.com/users/17041", "pm_score": 3, "selected": true, "text": "<p>I'm not absolutely completely sure that I understand exactly what you're saying, but as an analagous situation, say someone's inputting an endless stream of numbers on the keyboard. '117' is a magic sequence, '468' is another one, '411799' is another (which contains the first one). </p>\n\n<p>So if the user enters:</p>\n\n<blockquote>\n <p>55468411799</p>\n</blockquote>\n\n<p>you want to fire 'magic events' at the *s:</p>\n\n<blockquote>\n <p>55468*4117*99*</p>\n</blockquote>\n\n<p>or something like that, right? If that's analagous to the problem you're talking about, then what about something like (Java-like pseudocode):</p>\n\n<pre><code>MagicSequence fireworks = new MagicSequence(new FireworksAction(), 1, 1, 7);\nMagicSequence playMusic = new MagicSequence(new MusicAction(), 4, 6, 8);\nMagicSequence fixUserADrink = new MagicSequence(new ManhattanAction(), 4, 1, 1, 7, 9, 9);\n\nCollection&lt;MagicSequence&gt; sequences = ... all of the above ...;\n\nwhile (true) {\n int num = readNumberFromUser();\n for (MagicSequence seq : sequences) {\n seq.handleNumber(num);\n }\n}\n</code></pre>\n\n<p>while MagicSequence has something like:</p>\n\n<pre><code>Action action = ... populated from constructor ...;\nint[] sequence = ... populated from constructor ...;\nint position = 0;\n\npublic void handleNumber(int num) {\n if (num == sequence[position]) {\n // They've entered the next number in the sequence\n position++;\n if (position == sequence.length) {\n // They've got it all!\n action.fire();\n position = 0; // Or disable this Sequence from accepting more numbers if it's a once-off\n }\n } else {\n position = 0; // missed a number, start again!\n }\n}\n</code></pre>\n" }, { "answer_id": 187422, "author": "Javier", "author_id": 11649, "author_profile": "https://Stackoverflow.com/users/11649", "pm_score": 1, "selected": false, "text": "<p>create a small state machine for each effect that you'd want. at each user action, 'broadcast' it to all state machines. most of then won't care, but some will advance, or maybe go backwards. when one of them reaches it's goal, produce the desired effect.</p>\n\n<p>to keep the code neat, don't hardcode the state machines, instead build a simple data structure that encodes the state graph: each state is a node with a list of interesting events, each one points to the next state's node. Each machine's state is simply a reference to the appropriate state node.</p>\n\n<p>edit: It seems Cowan's advice is equivalent to this, but he optimises his state machines to express only simple sequences. seems enough for your specific problem, but more complex conditions could need a more general solution.</p>\n" }, { "answer_id": 187532, "author": "Ralph M. Rickenbach", "author_id": 4549416, "author_profile": "https://Stackoverflow.com/users/4549416", "pm_score": 1, "selected": false, "text": "<p>@Cowan, @Javier: Nice idea, mind if I add to it?</p>\n\n<p>Let the MagicSequence objects listen to the incoming stream of user input, that is notify them of the input (broadcast) and let each of them add the input to there internal input stream. This stream is cleared when the input is not the expected next input in the pattern that would have the MagicSequence fire its action. As soon as the pattern is completed, fire the action and clear the internal input stream.</p>\n\n<p>Optimize this by only feeding input to the MagicSequences that are waiting for it. This could be done two ways:</p>\n\n<ol>\n<li><p>You have an object that lets all MagicSequences connect with events that correspond with numbers in their patterns. MagicSequence(1,1,7) would add itself to got1 and got7, for example: </p>\n\n<p>UserInput.got1 += MagicSequnece[i].SendMeInput;</p></li>\n<li><p>You could optimize this such that after each input MagicSequences deregister from invalid events and register with valid ones.</p></li>\n</ol>\n" } ]
2008/10/09
[ "https://Stackoverflow.com/questions/187198", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5954/" ]
I was thinking earlier today about an idea for a small game and stumbled upon how to implement it. The idea is that the player can make a series of moves that cause a little effect, but if done in a specific sequence would cause a greater effect. So far so good, this I know how to do. Obviously, I had to make it be more complicated (because we love to make it more complicated), so I thought that there could be more than one possible path for the sequence that would both cause greater effects, albeit different ones. Also, part of some sequences could be the beggining of other sequences, or even whole sequences could be contained by other bigger sequences. Now I don't know for sure the best way to implement this. I had some ideas, though. 1) I could implement a circular n-linked list. But since the list of moves never end, I fear it might cause a stack overflow ™. The idea is that every node would have n children and upon receiving a command, it might lead you to one of his children or, if no children was available to such command, lead you back to the beggining. Upon arrival on any children, a couple of functions would be executed causing the small and big effect. This might, though, lead to a lot of duplicated nodes on the tree to cope up with all the possible sequences ending on that specific move with different effects, which might be a pain to maintain but I am not sure. I never tried something this complex on code, only theoretically. Does this algorithm exist and have a name? Is it a good idea? 2) I could implement a state machine. Then instead of wandering around a linked list, I'd have some giant nested switch that would call functions and update the machine state accordingly. Seems simpler to implement, but... well... doesn't seem fun... nor ellegant. Giant switchs always seem ugly to me, but would this work better? 3) Suggestions? I am good, but I am far inexperienced. The good thing of the coding field is that no matter how weird your problem is, someone solved it in the past, but you must know where to look. Someone might have a better idea than those I had, and I really wanted to hear suggestions.
I'm not absolutely completely sure that I understand exactly what you're saying, but as an analagous situation, say someone's inputting an endless stream of numbers on the keyboard. '117' is a magic sequence, '468' is another one, '411799' is another (which contains the first one). So if the user enters: > > 55468411799 > > > you want to fire 'magic events' at the \*s: > > 55468\*4117\*99\* > > > or something like that, right? If that's analagous to the problem you're talking about, then what about something like (Java-like pseudocode): ``` MagicSequence fireworks = new MagicSequence(new FireworksAction(), 1, 1, 7); MagicSequence playMusic = new MagicSequence(new MusicAction(), 4, 6, 8); MagicSequence fixUserADrink = new MagicSequence(new ManhattanAction(), 4, 1, 1, 7, 9, 9); Collection<MagicSequence> sequences = ... all of the above ...; while (true) { int num = readNumberFromUser(); for (MagicSequence seq : sequences) { seq.handleNumber(num); } } ``` while MagicSequence has something like: ``` Action action = ... populated from constructor ...; int[] sequence = ... populated from constructor ...; int position = 0; public void handleNumber(int num) { if (num == sequence[position]) { // They've entered the next number in the sequence position++; if (position == sequence.length) { // They've got it all! action.fire(); position = 0; // Or disable this Sequence from accepting more numbers if it's a once-off } } else { position = 0; // missed a number, start again! } } ```
187,216
<p>What is the best way for converting phone numbers into international format (E.164) using Java?</p> <p>Given a 'phone number' and a country id (let's say an ISO country code), I would like to convert it into a standard E.164 international format phone number.</p> <p>I am sure I can do it by hand quite easily - but I would not be sure it would work correctly in all situations.</p> <p>Which Java framework/library/utility would you recommend to accomplish this?</p> <p>P.S. The 'phone number' could be anything identifiable by the general public - such as</p> <pre><code>* (510) 786-0404 * 1-800-GOT-MILK * +44-(0)800-7310658 </code></pre> <p>that last one is my favourite - it is how some people write their number in the UK and means that you should either use the +44 or you should use the 0.</p> <p>The E.164 format number should be all numeric, and use the full international country code (e.g.+44)</p>
[ { "answer_id": 190179, "author": "cletus", "author_id": 18393, "author_profile": "https://Stackoverflow.com/users/18393", "pm_score": 3, "selected": false, "text": "<p>Speaking from experience at writing this kind of thing, it's really difficult to do with 100% reliability. I've written some Java code to do this that is reasonably good at processing the data we have but won't be applicable in every country. Questions you need to ask are:</p>\n\n<p>Are the character to number mappings consistent between countries? The US uses a lot of this (eg 1800-GOT-MILK) but in Australia, as one example, its pretty rare. What you'd need to do is ensure that you were doing the correct mapping for the country in question if it varies (it might not). I don't know what countries that use different alphabets (eg Cyrilic in Russia and the former Eastern block countries) do;</p>\n\n<p>You have to accept that your solution will not be 100% and you should not expect it to be. You need to take a \"best guess\" approach. For example, theres no real way of knowing that 132345 is a valid phone number in Australia, as is 1300 123 456 but that these are the only two patterns that are for 13xx numbers and they're not callable from overseas;</p>\n\n<p>You also have to ask if you want to validate regions (area codes). I believe the US uses a system where the second digit of the area code is a 1 or a 0. This may have once been the case but I'm not sure if it still applies. Whatever the case, many other countries will have other rules. In Australia, the valid area codes for landlines and mobile (cell) phones are two digits (the first is 0). 08, 03 and 04 are all valid. 01 isn't. How do you cater for that? Do you want to?</p>\n\n<p>Countries use different conventions no matter how many digits they're writing. You have to decide if you want to accept something other than the \"norm\". These are all common in Australia:</p>\n\n<ul>\n<li>(02) 1234 5678</li>\n<li>02 1234 5678</li>\n<li>0411 123 123 (but I've never seen 04 1112 3456)</li>\n<li>131 123</li>\n<li>13 1123</li>\n<li>131 123</li>\n<li>1 300 123 123</li>\n<li>1300 123 123</li>\n<li>02-1234-5678</li>\n<li>1300-234-234</li>\n<li>+44 78 1234 1234</li>\n<li>+44 (0)78 1234 1234</li>\n<li>+44-78-1234-1234</li>\n<li>+44-(0)78-1234-1234</li>\n<li>0011 44 78 1234 1234 (0011 is the standard international dialling code)</li>\n<li>(44) 078 1234 1234 (not common)</li>\n</ul>\n\n<p>And thats just off the top of my head. For one country. In France, for example, its common the write the phone number in number pairs (12 34 56 78) and they pronounce it that way too: instead of:</p>\n\n<p>un (one), deux (two), trois (three), ...</p>\n\n<p>its</p>\n\n<p>douze (twelve), trente-quatre (thirty four), ... </p>\n\n<p>Do you want to cater for that level of cultural difference? I would assume not but the question is worth considering just in case you make your rules too strict.</p>\n\n<p>Also some people may append extension numbers on phone numbers, possibly with \"ext\" or similar abbreviation. Do you want to cater for that?</p>\n\n<p>Sorry, no code here. Just a list of questions to ask yourself and issues to consider. As others have said, a series of regular expressions can do much of the above but ultimately phone number fields are (mostly) free form text at the end of the day.</p>\n" }, { "answer_id": 190242, "author": "Windows programmer", "author_id": 23705, "author_profile": "https://Stackoverflow.com/users/23705", "pm_score": 0, "selected": false, "text": "<p>In some countries you can validate 112 as a valid phone number, but if you stick a country code in front of it it won't be valid any more. In other countries you can't validate 112 but you can validate 911 as a valid phone number.</p>\n\n<p>I've seen some phones that put Q on the 7 key and Z on the 9 key. I've seen some phones that put Q and Z on the 0 key, and some that put Q and Z on the 1 key.</p>\n\n<p>An area code that existed yesterday might not exist today, and vice-versa.</p>\n\n<p>In half of North America (country code 1), the second digit rule used to be 0 or 1 for area codes, but that rule went away 10 years ago.</p>\n" }, { "answer_id": 194932, "author": "Vihung", "author_id": 15452, "author_profile": "https://Stackoverflow.com/users/15452", "pm_score": 1, "selected": false, "text": "<p>Thanks for the answers. As stated in the original question, I am much more interested in the formatting of the number into the standard format than I am in determining if it is a valid (as in genuine) phone number.</p>\n\n<p>I have some hand crafted code currently that takes a phone number String (as entered by the user) and a source country context and target country context (the country from where the number is being dialed, and the country to where the number is being dialed - this is known to the system) and then does the following conversion in steps</p>\n\n<ol>\n<li><p>Strip all whitespace from the number</p></li>\n<li><p>Translate all alpha into digits - using a lookup table of letter to digit (e.g. A-->2, B-->2, C-->2, D-->3) etc. for the keypad (I was not aware that some keypads distribute these differently)</p></li>\n<li><p>Strip all punctuation - keeping a preceding '+' intact if it exists (in case the number is already in some sort of international format).</p></li>\n<li><p>Determine if the number has an international dialling prefix for the country context - e.g. if source context is the UK, I would see if it starts with a '00' - and replace it with a '+'. I do not currently check whether the digits following the '00' are followed by the international dialing code for the target country. I look up the international dialing prefix for the source country in a lookup table (e.g. GB-->'00', US-->'011' etc.)</p></li>\n<li><p>Determine if the number has a local dialing prefix for the country context - e.g. if the source context is the UK, I would look to see if it starts with a '0' - and replace it with a '+' followed by the international dialing code for the target country. I look up the local dialing prefix for the source country in a lookup table (e.g. GB-->'0', US-->'1' etc.), and the international dialing code for the target country in another lookup table (e.g.'GB'='44', US='1')</p></li>\n</ol>\n\n<p>It seems to work for everything I have thrown at it so far - except for the +44(0)1234-567-890 situation - I will add a special case check for that one.</p>\n\n<p>Writing it was not hard - and I can add special cases for each strange exception I come across. But I would really like to know if there is a standard solution.</p>\n\n<p>The phone companies seem to deal with this thing every day. I never get inconsistent results when dialing numbers using the PSTN. For example, in the US (where mobile phones have the same area codes as landlines, I could dial +1-123-456-7890, or 011-1-123-456-7890 (where 011 is the international dialing prefix in the US and 1 is the international dialing code for the US), 1-123-456-7890 (where 1 is the local dialing prefix in the US) or even 456-7890 (assuming I was in the 123 area code at the time) and get the same results each time. I assume that internally these dialed numbers get converted to the same E.164 standard format, and that the conversion is all done in software.</p>\n" }, { "answer_id": 195093, "author": "Henk", "author_id": 4613, "author_profile": "https://Stackoverflow.com/users/4613", "pm_score": 0, "selected": false, "text": "<p>I'm not aware of a standard library or framework available for formatting telephone numbers into E.164.</p>\n\n<p>The solution used for our product, which requires formatting PBX provided caller-id into E.164, is to deploy a file (database table) containing the E.164 format information for all countries applicable.\nThis has the advantage that the application can be updated (to handle all the strange corner cases in various PSTN networks) w/out requiring changes to the production code base.</p>\n\n<p>The table contains a row for each country code and information regarding area code length and subscriber length. There may be multiple entries for a country depending on what variations are possible with area code and subscriber number lengths.</p>\n\n<p>Using New Zealand PSTN (partial) dial plan as an example of the table..</p>\n\n<pre><code>CC AREA_CODE AREA_CODE_LENGTH SUBSCRIBER SUBSCRIBER_LENGTH\n64 1 7\n64 21 2 7\n64 275 3 6\n</code></pre>\n\n<p>We do something similar to what you have described, i.e. strip the provided telephone number of any non-digit characters and then format based on various rules regarding overall number plan length, outside access code, and long distance/international access codes.</p>\n" }, { "answer_id": 250808, "author": "Alnitak", "author_id": 6782, "author_profile": "https://Stackoverflow.com/users/6782", "pm_score": 1, "selected": false, "text": "<p>To be honest, it sounds like you've got most of the bases covered already.</p>\n\n<p>The +44(0)800 format sometimes (incorrectly) used in the UK is annoying and isn't strictly valid according to E.123, which is the ITU-T recommendation for how numbers should be displayed. If you haven't got a copy of E.123 it's worth a look.</p>\n\n<p>For what it's worth, the telephone network itself doesn't always use E.164. Often there'll be a flag in the ISDN signalling generated by the PBX (or in the network if you're on a steam phone) which tells the network whether the number being dialled is local, national or international.</p>\n" }, { "answer_id": 5264810, "author": "Collin Peters", "author_id": 354767, "author_profile": "https://Stackoverflow.com/users/354767", "pm_score": 7, "selected": true, "text": "<p>Google provides a library for working with phone numbers. The same one they use for Android</p>\n\n<p><a href=\"http://code.google.com/p/libphonenumber/\">http://code.google.com/p/libphonenumber/</a></p>\n\n<pre><code>String swissNumberStr = \"044 668 18 00\"\nPhoneNumberUtil phoneUtil = PhoneNumberUtil.getInstance();\ntry {\n PhoneNumber swissNumberProto = phoneUtil.parse(swissNumberStr, \"CH\");\n} catch (NumberParseException e) {\n System.err.println(\"NumberParseException was thrown: \" + e.toString());\n}\n\n// Produces \"+41 44 668 18 00\"\nSystem.out.println(phoneUtil.format(swissNumberProto, PhoneNumberFormat.INTERNATIONAL));\n// Produces \"044 668 18 00\"\nSystem.out.println(phoneUtil.format(swissNumberProto, PhoneNumberFormat.NATIONAL));\n// Produces \"+41446681800\"\nSystem.out.println(phoneUtil.format(swissNumberProto, PhoneNumberFormat.E164));\n</code></pre>\n" }, { "answer_id": 7687504, "author": "arksoft", "author_id": 312939, "author_profile": "https://Stackoverflow.com/users/312939", "pm_score": 2, "selected": false, "text": "<p>This was my solution:</p>\n\n<pre><code>public static String FixPhoneNumber(Context ctx, String rawNumber)\n{\n String fixedNumber = \"\";\n\n // get current location iso code\n TelephonyManager telMgr = (TelephonyManager) ctx.getSystemService(Context.TELEPHONY_SERVICE);\n String curLocale = telMgr.getNetworkCountryIso().toUpperCase();\n\n PhoneNumberUtil phoneUtil = PhoneNumberUtil.getInstance();\n Phonenumber.PhoneNumber phoneNumberProto;\n\n // gets the international dialling code for our current location\n String curDCode = String.format(\"%d\", phoneUtil.getCountryCodeForRegion(curLocale));\n String ourDCode = \"\";\n\n if(rawNumber.indexOf(\"+\") == 0)\n {\n int bIndex = rawNumber.indexOf(\"(\");\n int hIndex = rawNumber.indexOf(\"-\");\n int eIndex = rawNumber.indexOf(\" \");\n\n if(bIndex != -1)\n {\n ourDCode = rawNumber.substring(1, bIndex);\n }\n else if(hIndex != -1) \n { \n ourDCode = rawNumber.substring(1, hIndex);\n }\n else if(eIndex != -1)\n {\n ourDCode = rawNumber.substring(1, eIndex);\n }\n else\n {\n ourDCode = curDCode;\n } \n }\n else\n {\n ourDCode = curDCode;\n }\n\n try \n {\n phoneNumberProto = phoneUtil.parse(rawNumber, curLocale);\n } \n\n catch (NumberParseException e) \n {\n return rawNumber;\n }\n\n if(curDCode.compareTo(ourDCode) == 0)\n fixedNumber = phoneUtil.format(phoneNumberProto, PhoneNumberFormat.NATIONAL);\n else\n fixedNumber = phoneUtil.format(phoneNumberProto, PhoneNumberFormat.INTERNATIONAL);\n\n return fixedNumber.replace(\" \", \"\");\n}\n</code></pre>\n\n<p>I hope this helps someone with the same problem.</p>\n\n<p>Enjoy and use freely.</p>\n" } ]
2008/10/09
[ "https://Stackoverflow.com/questions/187216", "https://Stackoverflow.com", "https://Stackoverflow.com/users/15452/" ]
What is the best way for converting phone numbers into international format (E.164) using Java? Given a 'phone number' and a country id (let's say an ISO country code), I would like to convert it into a standard E.164 international format phone number. I am sure I can do it by hand quite easily - but I would not be sure it would work correctly in all situations. Which Java framework/library/utility would you recommend to accomplish this? P.S. The 'phone number' could be anything identifiable by the general public - such as ``` * (510) 786-0404 * 1-800-GOT-MILK * +44-(0)800-7310658 ``` that last one is my favourite - it is how some people write their number in the UK and means that you should either use the +44 or you should use the 0. The E.164 format number should be all numeric, and use the full international country code (e.g.+44)
Google provides a library for working with phone numbers. The same one they use for Android <http://code.google.com/p/libphonenumber/> ``` String swissNumberStr = "044 668 18 00" PhoneNumberUtil phoneUtil = PhoneNumberUtil.getInstance(); try { PhoneNumber swissNumberProto = phoneUtil.parse(swissNumberStr, "CH"); } catch (NumberParseException e) { System.err.println("NumberParseException was thrown: " + e.toString()); } // Produces "+41 44 668 18 00" System.out.println(phoneUtil.format(swissNumberProto, PhoneNumberFormat.INTERNATIONAL)); // Produces "044 668 18 00" System.out.println(phoneUtil.format(swissNumberProto, PhoneNumberFormat.NATIONAL)); // Produces "+41446681800" System.out.println(phoneUtil.format(swissNumberProto, PhoneNumberFormat.E164)); ```
187,219
<p>I'm using ccl/openmcl on Mac OS X. (latest versions of both). When the lisp prompt is displayed, using the cursor keys to navigate the current line results in escape codes, rather than movement, eg:</p> <p><code>Welcome to Clozure Common Lisp Version 1.2-r9226-RC1 (DarwinX8664)!<br> ? (^[[D</code></p> <p>Here I've pressed the <code>(</code> key, and then the <code>left cursor</code> key.</p> <p>When I run ccl/openmcl on a Debian Etch box, the cursor behaves as expected, and moves the insert point one position left.</p> <p>I guess this is some sort of terminal configuration option?</p>
[ { "answer_id": 187393, "author": "Matthias Benkard", "author_id": 15517, "author_profile": "https://Stackoverflow.com/users/15517", "pm_score": 3, "selected": true, "text": "<p>If Clozure CL doesn't provide native readline/editline/whatever support or is configured not to use it, you can run it with rlwrap, for example:</p>\n\n<pre><code>rlwrap openmcl\n</code></pre>\n\n<p>rlwrap can be obtained via <a href=\"http://www.macports.org/\" rel=\"nofollow noreferrer\">MacPorts</a> or directly from <a href=\"http://utopia.knoware.nl/~hlub/rlwrap/\" rel=\"nofollow noreferrer\">http://utopia.knoware.nl/~hlub/rlwrap/</a>.</p>\n" }, { "answer_id": 188218, "author": "Attila Lendvai", "author_id": 14464, "author_profile": "https://Stackoverflow.com/users/14464", "pm_score": 2, "selected": false, "text": "<p>i know that i'm not answering the question with this, but you should not spend much time directly using a lisp repl.</p>\n\n<p>using emacs and <a href=\"http://common-lisp.net/project/slime/\" rel=\"nofollow noreferrer\">slime</a> is a much more convenient way of interacting with a lisp. you have an inspector and a debugger at hand, you can jump to the source code of the functions, etc.</p>\n" } ]
2008/10/09
[ "https://Stackoverflow.com/questions/187219", "https://Stackoverflow.com", "https://Stackoverflow.com/users/10019/" ]
I'm using ccl/openmcl on Mac OS X. (latest versions of both). When the lisp prompt is displayed, using the cursor keys to navigate the current line results in escape codes, rather than movement, eg: `Welcome to Clozure Common Lisp Version 1.2-r9226-RC1 (DarwinX8664)! ? (^[[D` Here I've pressed the `(` key, and then the `left cursor` key. When I run ccl/openmcl on a Debian Etch box, the cursor behaves as expected, and moves the insert point one position left. I guess this is some sort of terminal configuration option?
If Clozure CL doesn't provide native readline/editline/whatever support or is configured not to use it, you can run it with rlwrap, for example: ``` rlwrap openmcl ``` rlwrap can be obtained via [MacPorts](http://www.macports.org/) or directly from <http://utopia.knoware.nl/~hlub/rlwrap/>.
187,229
<p>Why does this work:</p> <pre><code>$(window).keydown(function(event){ alert(event.keyCode); }); </code></pre> <p>but not this:</p> <pre><code>$('#ajaxSearchText').keydown(function(event){ alert(event.keyCode); }); </code></pre> <p>I'm testing with Firefox 3. Interestingly, neither of them work in IE7.</p>
[ { "answer_id": 187262, "author": "Mote", "author_id": 24789, "author_profile": "https://Stackoverflow.com/users/24789", "pm_score": 1, "selected": false, "text": "<p>Try using</p>\n\n<pre><code>$('#ajaxSearchText').keyup(function(event){\n alert(event.keyCode);\n});\n</code></pre>\n\n<p>works for me perfectly. Also check the id of the textarea</p>\n" }, { "answer_id": 190205, "author": "Alexander Prokofyev", "author_id": 11256, "author_profile": "https://Stackoverflow.com/users/11256", "pm_score": 4, "selected": true, "text": "<p>Checked this in Chrome, IE7 and Firefox 3.0.3. Works as it should. jQuery version 1.2.6.</p>\n\n<pre><code>&lt;html&gt; \n &lt;head&gt; \n &lt;script type=\"text/javascript\" src=\"jquery-1.2.6.js\"&gt;&lt;/script&gt; \n &lt;script type=\"text/javascript\"&gt; \n $(function() \n {\n $(\"#ajaxSearchText\").keydown(function(event)\n {\n alert(event.keyCode);\n });\n });\n &lt;/script&gt; \n &lt;/head&gt; \n &lt;body&gt; \n &lt;input type=\"text\" id=\"ajaxSearchText\"&gt;&lt;/input&gt;\n &lt;/body&gt; \n&lt;/html&gt; \n</code></pre>\n" }, { "answer_id": 221337, "author": "penderi", "author_id": 32027, "author_profile": "https://Stackoverflow.com/users/32027", "pm_score": 2, "selected": false, "text": "<p>For all your keydown/keyup/keyboard needs, use the jQuery hotkeys plugin. </p>\n\n<p>Saw this a few months ago and it never fails to impress it. Follow the jump for the plugin demo ... <a href=\"http://code.google.com/p/js-hotkeys/\" rel=\"nofollow noreferrer\">http://code.google.com/p/js-hotkeys/</a></p>\n\n<p>It maps ALL keys on a keyboard including combos. Hope it helps!</p>\n" }, { "answer_id": 338157, "author": "Rik Heywood", "author_id": 4012, "author_profile": "https://Stackoverflow.com/users/4012", "pm_score": 2, "selected": false, "text": "<p>To fix the issues in IE6 and IE7, try this...</p>\n\n<pre><code>$(function() \n{\n $(document).keydown(function(event){\n alert(event.keyCode);\n });\n});\n</code></pre>\n\n<p>Attaching the event to the <code>$(document)</code> seems to be the magic things here.</p>\n\n<p>Your first bit of code really should work in IE as well though. It seems to be down to a bug in jQuery that will hopefully be fixed soon...</p>\n\n<p>Here is a link to the bug report in jQuery. <a href=\"https://bugs.jquery.com/ticket/3614\" rel=\"nofollow noreferrer\">https://bugs.jquery.com/ticket/3614</a></p>\n" }, { "answer_id": 2527753, "author": "Simon_Weaver", "author_id": 16940, "author_profile": "https://Stackoverflow.com/users/16940", "pm_score": -1, "selected": false, "text": "<p>Because key events are not supported on the 'window' object.</p>\n\n<p><a href=\"http://www.w3schools.com/jsref/obj_window.asp\" rel=\"nofollow noreferrer\">http://www.w3schools.com/jsref/obj_window.asp</a></p>\n\n<p>But only on 'document':</p>\n\n<p><a href=\"http://www.w3schools.com/jsref/dom_obj_event.asp\" rel=\"nofollow noreferrer\">http://www.w3schools.com/jsref/dom_obj_event.asp</a></p>\n\n<p>If it ever worked then it was a bug in jQuery.</p>\n" }, { "answer_id": 6114797, "author": "Kristian", "author_id": 680578, "author_profile": "https://Stackoverflow.com/users/680578", "pm_score": 0, "selected": false, "text": "<pre><code>$('#searchInput').keydown(function() {\n alert('testing');\n});\n</code></pre>\n\n<p>will not work. However, if you wrap it in a function:</p>\n\n<pre><code>$(function()\n{\n $('#searchInput').keydown(function() {\n alert('testing');\n });\n});\n</code></pre>\n\n<p>it will work. </p>\n\n<p>Without that function declaration, it only works on objects like document and window.</p>\n" } ]
2008/10/09
[ "https://Stackoverflow.com/questions/187229", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4639/" ]
Why does this work: ``` $(window).keydown(function(event){ alert(event.keyCode); }); ``` but not this: ``` $('#ajaxSearchText').keydown(function(event){ alert(event.keyCode); }); ``` I'm testing with Firefox 3. Interestingly, neither of them work in IE7.
Checked this in Chrome, IE7 and Firefox 3.0.3. Works as it should. jQuery version 1.2.6. ``` <html> <head> <script type="text/javascript" src="jquery-1.2.6.js"></script> <script type="text/javascript"> $(function() { $("#ajaxSearchText").keydown(function(event) { alert(event.keyCode); }); }); </script> </head> <body> <input type="text" id="ajaxSearchText"></input> </body> </html> ```
187,231
<p>I'm having trouble selecting elements that are part of an specific namespace. My xpath expression works in XMLSpy but fails when using the Xalan libraries..</p> <pre><code>&lt;item&gt; &lt;media:content attrb="xyz"&gt; &lt;dcterms:valid&gt;VALUE&lt;/dcterms:valid&gt; &lt;/media:content&gt; &lt;/item&gt; </code></pre> <p>My expression is <code>./item/media:content/dcterms:valid</code>. I've already added both namespace definitions to my XSLT. Again, this selects the right values in XMLSpy but fails when running through Xalan library.</p> <p>Any ideas?</p>
[ { "answer_id": 187339, "author": "Ray Lu", "author_id": 11413, "author_profile": "https://Stackoverflow.com/users/11413", "pm_score": 0, "selected": false, "text": "<p>Have you tried to define the namespace of the XML blob?</p>\n\n<pre><code>&lt;item xmlns:dcterms=\"http://dcterms.example\" xmlns:media=\"http://media.example\"&gt;\n &lt;media:content attrb=\"xyz\"&gt;\n &lt;dcterms:valid&gt;VALUE&lt;/dcterms:valid&gt;\n &lt;/media:content&gt;\n&lt;/item&gt;\n</code></pre>\n\n<p>i.e. </p>\n\n<ul>\n<li>xmlns:dcterms=\"http://dcterms.example\"</li>\n<li>xmlns:media=\"http://media.example\"</li>\n</ul>\n" }, { "answer_id": 192262, "author": "dacracot", "author_id": 13930, "author_profile": "https://Stackoverflow.com/users/13930", "pm_score": -1, "selected": false, "text": "<p>Perhaps XMLSpy has implemented the 2.x XSLT spec of which I believe XPath is a part.\n Xalan on the other hand is still 1.x.</p>\n" }, { "answer_id": 192786, "author": "James Sulak", "author_id": 207, "author_profile": "https://Stackoverflow.com/users/207", "pm_score": 0, "selected": false, "text": "<p>In what context are you trying to evaluate your XPath from? (For example, an XSLT?) If is the root element, you might try removing the leading \".\": \"/item/media:content/dcterms:valid.\" If there is a series of items, you might try adding another slash at the beginning: \"//item/media:content/dcterms:valid.\" That will select all the items in the document that match that criteria, no matter where in the document structure they are located.</p>\n" }, { "answer_id": 193980, "author": "Kornel", "author_id": 27009, "author_profile": "https://Stackoverflow.com/users/27009", "pm_score": 0, "selected": false, "text": "<p>Prefixes in XML are meaningless until they're bound to a certain namespace, and this is also true for XPath expressions – it won't match simply because you've used same prefix.</p>\n\n<p>You must create your own PrefixResolver class which will give full namespace URIs for prefixes you have in your XPath expression.</p>\n" }, { "answer_id": 195816, "author": "Michael Hall", "author_id": 7156, "author_profile": "https://Stackoverflow.com/users/7156", "pm_score": 1, "selected": false, "text": "<p>You'll need to implement a <a href=\"http://xml.apache.org/xalan-j/apidocs/org/apache/xml/utils/PrefixResolver.html\" rel=\"nofollow noreferrer\"><code>org.apache.xml.utils.PrefixResolver</code></a> to map the prefix to namespace URI, and then pass an instance to the <code>XPath</code> instance you use. This will allow you to use different prefixes in your XPath expressions from those in your documents (which you might not control).</p>\n\n<p>For example, you could create an implementation that uses a pair of maps (one to map from prefix -> namespace URI, and one from URI to prefix).</p>\n\n<p>In JAXP, the equivalent interface to implement is <a href=\"http://java.sun.com/javase/6/docs/api/javax/xml/namespace/NamespaceContext.html\" rel=\"nofollow noreferrer\"><code>javax.xml.namespace.NamespaceContext</code></a>.</p>\n" }, { "answer_id": 195831, "author": "extraneon", "author_id": 24582, "author_profile": "https://Stackoverflow.com/users/24582", "pm_score": 0, "selected": false, "text": "<p>You could try a XPath select on the local-name and (optionally) give a namespace URI. And example:</p>\n<pre><code>/*[local-name()='NewHireList' and namespace-uri()='http://BRE.NewHireList']/*[local-name()='Record' and namespace-uri()='']\n</code></pre>\n<p>See <a href=\"https://web.archive.org/web/20131123192811/http://geekswithblogs.net:80/brokenrules/archive/2005/06/06/42250.aspx\" rel=\"nofollow noreferrer\">this page</a> for more, or google on local-name and XPath.</p>\n" } ]
2008/10/09
[ "https://Stackoverflow.com/questions/187231", "https://Stackoverflow.com", "https://Stackoverflow.com/users/10913/" ]
I'm having trouble selecting elements that are part of an specific namespace. My xpath expression works in XMLSpy but fails when using the Xalan libraries.. ``` <item> <media:content attrb="xyz"> <dcterms:valid>VALUE</dcterms:valid> </media:content> </item> ``` My expression is `./item/media:content/dcterms:valid`. I've already added both namespace definitions to my XSLT. Again, this selects the right values in XMLSpy but fails when running through Xalan library. Any ideas?
You'll need to implement a [`org.apache.xml.utils.PrefixResolver`](http://xml.apache.org/xalan-j/apidocs/org/apache/xml/utils/PrefixResolver.html) to map the prefix to namespace URI, and then pass an instance to the `XPath` instance you use. This will allow you to use different prefixes in your XPath expressions from those in your documents (which you might not control). For example, you could create an implementation that uses a pair of maps (one to map from prefix -> namespace URI, and one from URI to prefix). In JAXP, the equivalent interface to implement is [`javax.xml.namespace.NamespaceContext`](http://java.sun.com/javase/6/docs/api/javax/xml/namespace/NamespaceContext.html).
187,237
<p>I have a .NET string which is Base64 encoded representation of an array of encrypted bytes. It is produced like this:</p> <pre><code>String Encrypt( String message ) { CryptoStream cryptostream = ... StreamWriter stream = new StreamWriter( cryptostream ); ... return Convert.ToBase64String( ... ); } </code></pre> <p>Now I want a decryption function like</p> <pre><code>String Decrypt( String cypher ) { TextReader reader = new StringReader( cypher ); byte[] buffer = new byte[ cypher.Length ]; for( int i = 0; i &lt; cypher.Length; ++i ) { buffer[ i ] = (byte) reader.Read(); } FromBase64Transform transformer = new FromBase64Transform(); MemoryStream raw = new MemoryStream ( transformer.TransformFinalBlock( buffer, 0, buffer.Length ) ); ... } </code></pre> <p>Is there a way to use FromBase64Transform <em>directly</em> with CryptoStream (as the .NET documentation suggests), instead of manually converting the string to bytes, then manually decoding the bytes, and finally decrypting the decoded bytes?</p>
[ { "answer_id": 187575, "author": "Jérôme Laban", "author_id": 26346, "author_profile": "https://Stackoverflow.com/users/26346", "pm_score": 0, "selected": false, "text": "<p>There is no public built-in way to stream from a string, as of .NET 3.5.</p>\n\n<p>You can implement a simple StringStream class that inherits from Stream, which will free you from having to convert the string to an array of bytes.</p>\n" }, { "answer_id": 191630, "author": "GvS", "author_id": 11492, "author_profile": "https://Stackoverflow.com/users/11492", "pm_score": 2, "selected": true, "text": "<p>I always the the <a href=\"http://msdn.microsoft.com/en-us/library/system.convert.frombase64string.aspx\" rel=\"nofollow noreferrer\">Convert</a> class to convert the string into an array of Byte.</p>\n\n<p>An example:</p>\n\n<pre><code> public static string DeCryptString(string s) {\n byte[] b = System.Convert.FromBase64String(s);\n\n using (MemoryStream ms = new MemoryStream(b)) \n using (CryptoStream cs = /* Create decrypting stream here */)\n using (StreamReader sr = new StreamReader(cs)) {\n string buf = sr.ReadToEnd();\n return buf;\n }\n } // DeCryptString\n</code></pre>\n" } ]
2008/10/09
[ "https://Stackoverflow.com/questions/187237", "https://Stackoverflow.com", "https://Stackoverflow.com/users/13372/" ]
I have a .NET string which is Base64 encoded representation of an array of encrypted bytes. It is produced like this: ``` String Encrypt( String message ) { CryptoStream cryptostream = ... StreamWriter stream = new StreamWriter( cryptostream ); ... return Convert.ToBase64String( ... ); } ``` Now I want a decryption function like ``` String Decrypt( String cypher ) { TextReader reader = new StringReader( cypher ); byte[] buffer = new byte[ cypher.Length ]; for( int i = 0; i < cypher.Length; ++i ) { buffer[ i ] = (byte) reader.Read(); } FromBase64Transform transformer = new FromBase64Transform(); MemoryStream raw = new MemoryStream ( transformer.TransformFinalBlock( buffer, 0, buffer.Length ) ); ... } ``` Is there a way to use FromBase64Transform *directly* with CryptoStream (as the .NET documentation suggests), instead of manually converting the string to bytes, then manually decoding the bytes, and finally decrypting the decoded bytes?
I always the the [Convert](http://msdn.microsoft.com/en-us/library/system.convert.frombase64string.aspx) class to convert the string into an array of Byte. An example: ``` public static string DeCryptString(string s) { byte[] b = System.Convert.FromBase64String(s); using (MemoryStream ms = new MemoryStream(b)) using (CryptoStream cs = /* Create decrypting stream here */) using (StreamReader sr = new StreamReader(cs)) { string buf = sr.ReadToEnd(); return buf; } } // DeCryptString ```
187,245
<p>Where I work, we maintain an FTP site that needs occasional cleanup.</p> <p>Are there any tools out there to create a site map of an FTP site? It would greatly simplify clean up tasks.</p> <p>Thanks!</p>
[ { "answer_id": 187575, "author": "Jérôme Laban", "author_id": 26346, "author_profile": "https://Stackoverflow.com/users/26346", "pm_score": 0, "selected": false, "text": "<p>There is no public built-in way to stream from a string, as of .NET 3.5.</p>\n\n<p>You can implement a simple StringStream class that inherits from Stream, which will free you from having to convert the string to an array of bytes.</p>\n" }, { "answer_id": 191630, "author": "GvS", "author_id": 11492, "author_profile": "https://Stackoverflow.com/users/11492", "pm_score": 2, "selected": true, "text": "<p>I always the the <a href=\"http://msdn.microsoft.com/en-us/library/system.convert.frombase64string.aspx\" rel=\"nofollow noreferrer\">Convert</a> class to convert the string into an array of Byte.</p>\n\n<p>An example:</p>\n\n<pre><code> public static string DeCryptString(string s) {\n byte[] b = System.Convert.FromBase64String(s);\n\n using (MemoryStream ms = new MemoryStream(b)) \n using (CryptoStream cs = /* Create decrypting stream here */)\n using (StreamReader sr = new StreamReader(cs)) {\n string buf = sr.ReadToEnd();\n return buf;\n }\n } // DeCryptString\n</code></pre>\n" } ]
2008/10/09
[ "https://Stackoverflow.com/questions/187245", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1145/" ]
Where I work, we maintain an FTP site that needs occasional cleanup. Are there any tools out there to create a site map of an FTP site? It would greatly simplify clean up tasks. Thanks!
I always the the [Convert](http://msdn.microsoft.com/en-us/library/system.convert.frombase64string.aspx) class to convert the string into an array of Byte. An example: ``` public static string DeCryptString(string s) { byte[] b = System.Convert.FromBase64String(s); using (MemoryStream ms = new MemoryStream(b)) using (CryptoStream cs = /* Create decrypting stream here */) using (StreamReader sr = new StreamReader(cs)) { string buf = sr.ReadToEnd(); return buf; } } // DeCryptString ```
187,255
<p>I'm trying to make a select that calculates affiliate payouts.</p> <p>my approach is pretty simple.</p> <pre><code>SELECT month(payments.timestmap) ,sum(if(payments.amount&gt;=29.95,4,0)) As Tier4 ,sum(if(payments.amount&gt;=24.95&lt;=29.94,3,0)) As Tier3 ,sum(if(payments.amount&gt;=19.95&lt;=24.94,2,0)) As Tier2 FROM payments GROUP BY month(payments.timestamp) </code></pre> <p>The above does not work because MySQL is not evaluating the second part of the condition. Btw it does not cause a syntax error and the select will return results.</p> <p>Before the above I tried what I was assuming would work like "<code>amount between 24.94 AND 29.94</code>" this caused an error. so then I tried "<code>amount &gt;= 24.94 AND &lt;= 29.94</code>" </p> <p>So is it possible to have a range comparison using IF in MySql?</p>
[ { "answer_id": 187270, "author": "ConroyP", "author_id": 2287, "author_profile": "https://Stackoverflow.com/users/2287", "pm_score": 4, "selected": true, "text": "<p>The second part of the expression evaluates when you use <code>AND</code> - </p>\n\n<pre><code>SELECT\n month(payments.timestmap)\n,sum(if(payments.amount&gt;=29.95,4,0)) As Tier4\n,sum(if(payments.amount&gt;=24.95 AND payments.amount&lt;=29.94,3,0)) As Tier3\n,sum(if(payments.amount&gt;=19.95 AND payments.amount&lt;=24.94,2,0)) As Tier2\nFROM payments\nGROUP BY month(payments.timestamp)\n</code></pre>\n\n<p>I'm not entirely sure why the <code>between</code> clause didn't work for you, but the above should do the job.</p>\n" }, { "answer_id": 187278, "author": "Thomas Owens", "author_id": 572, "author_profile": "https://Stackoverflow.com/users/572", "pm_score": 2, "selected": false, "text": "<p>There is always the <a href=\"http://dev.mysql.com/doc/refman/5.0/en/comparison-operators.html#operator_between\" rel=\"nofollow noreferrer\">BETWEEN...AND...</a> operator in MySQL.</p>\n" }, { "answer_id": 187285, "author": "KernelM", "author_id": 22328, "author_profile": "https://Stackoverflow.com/users/22328", "pm_score": 1, "selected": false, "text": "<p>What error did your first attempt give you? It should definitely work. However, note that the second form you have is incorrect syntax. It should be <code>amount >= 24.94 and amount &lt;= 29.94</code>.</p>\n" }, { "answer_id": 7584892, "author": "geilt", "author_id": 849560, "author_profile": "https://Stackoverflow.com/users/849560", "pm_score": 1, "selected": false, "text": "<pre><code>SELECT\nmonth( payments.timestamp )\n,sum( if( payments.amount &gt;= 29.95, 4, 0 ) ) As Tier4\n,sum( if( payments.amount BETWEEN 24.95 AND 29.94, 3, 0 ) ) As Tier3\n,sum( if( payments.amount BETWEEN 19.95 AND 24.94, 2, 0 ) ) As Tier2\nFROM payments\nGROUP BY month( payments.timestamp )\n</code></pre>\n\n<p>This should work also, I tested both with BETWEEN and with > &lt; to make sure they worked the same in one of my queries. So yes, both work.</p>\n" } ]
2008/10/09
[ "https://Stackoverflow.com/questions/187255", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3747/" ]
I'm trying to make a select that calculates affiliate payouts. my approach is pretty simple. ``` SELECT month(payments.timestmap) ,sum(if(payments.amount>=29.95,4,0)) As Tier4 ,sum(if(payments.amount>=24.95<=29.94,3,0)) As Tier3 ,sum(if(payments.amount>=19.95<=24.94,2,0)) As Tier2 FROM payments GROUP BY month(payments.timestamp) ``` The above does not work because MySQL is not evaluating the second part of the condition. Btw it does not cause a syntax error and the select will return results. Before the above I tried what I was assuming would work like "`amount between 24.94 AND 29.94`" this caused an error. so then I tried "`amount >= 24.94 AND <= 29.94`" So is it possible to have a range comparison using IF in MySql?
The second part of the expression evaluates when you use `AND` - ``` SELECT month(payments.timestmap) ,sum(if(payments.amount>=29.95,4,0)) As Tier4 ,sum(if(payments.amount>=24.95 AND payments.amount<=29.94,3,0)) As Tier3 ,sum(if(payments.amount>=19.95 AND payments.amount<=24.94,2,0)) As Tier2 FROM payments GROUP BY month(payments.timestamp) ``` I'm not entirely sure why the `between` clause didn't work for you, but the above should do the job.
187,273
<p>Building on <a href="https://stackoverflow.com/questions/1476/how-do-you-express-binary-literals-in-python#13107">How Do You Express Binary Literals in Python</a>, I was thinking about sensible, intuitive ways to do that Programming 101 chestnut of displaying integers in base-2 form. This is the best I came up with, but I'd like to replace it with a better algorithm, or at least one that should have screaming-fast performance. </p> <pre><code>def num_bin(N, places=8): def bit_at_p(N, p): ''' find the bit at place p for number n ''' two_p = 1 &lt;&lt; p # 2 ^ p, using bitshift, will have exactly one # bit set, at place p x = N &amp; two_p # binary composition, will be one where *both* numbers # have a 1 at that bit. this can only happen # at position p. will yield two_p if N has a 1 at # bit p return int(x &gt; 0) bits = ( bit_at_p(N,x) for x in xrange(places)) return "".join( (str(x) for x in bits) ) # or, more consisely # return "".join([str(int((N &amp; 1 &lt;&lt; x)&gt;0)) for x in xrange(places)]) </code></pre>
[ { "answer_id": 187536, "author": "Brian", "author_id": 9493, "author_profile": "https://Stackoverflow.com/users/9493", "pm_score": 5, "selected": true, "text": "<p>For best efficiency, you generally want to process more than a single bit at a time.\nYou can use a simple method to get a fixed width binary representation. eg.</p>\n\n<pre><code>def _bin(x, width):\n return ''.join(str((x&gt;&gt;i)&amp;1) for i in xrange(width-1,-1,-1))\n</code></pre>\n\n<p>_bin(x, 8) will now give a zero padded representation of x's lower 8 bits. This can be used to build a lookup table, allowing your converter to process 8 bits at a time (or more if you want to devote the memory to it).</p>\n\n<pre><code>_conv_table = [_bin(x,8) for x in range(256)]\n</code></pre>\n\n<p>Then you can use this in your real function, stripping off leading zeroes when returning it. I've also added handling for signed numbers, as without it you will get an infinite loop (Negative integers conceptually have an infinite number of set sign bits.)</p>\n\n<pre><code>def bin(x):\n if x == 0: \n return '0' #Special case: Don't strip leading zero if no other digits\n elif x &lt; 0:\n sign='-'\n x*=-1\n else:\n sign = ''\n l=[]\n while x:\n l.append(_conv_table[x &amp; 0xff])\n x &gt;&gt;= 8\n return sign + ''.join(reversed(l)).lstrip(\"0\")\n</code></pre>\n\n<p>[Edit] Changed code to handle signed integers.<br>\n[Edit2] Here are some timing figures of the various solutions. bin is the function above, constantin_bin is from <a href=\"https://stackoverflow.com/questions/187273/base-2-binary-representation-using-python#189579\">Constantin's answer</a> and num_bin is the original version. Out of curiosity, I also tried a 16 bit lookup table variant of the above (bin16 below), and tried out Python3's builtin bin() function. All timings were for 100000 runs using an 01010101 bit pattern.</p>\n\n<pre><code>Num Bits: 8 16 32 64 128 256\n---------------------------------------------------------------------\nbin 0.544 0.586 0.744 1.942 1.854 3.357 \nbin16 0.542 0.494 0.592 0.773 1.150 1.886\nconstantin_bin 2.238 3.803 7.794 17.869 34.636 94.799\nnum_bin 3.712 5.693 12.086 32.566 67.523 128.565\nPython3's bin 0.079 0.045 0.062 0.069 0.212 0.201 \n</code></pre>\n\n<p>As you can see, when processing long values using large chunks really pays off, but nothing beats the low-level C code of python3's builtin (which bizarrely seems consistently faster at 256 bits than 128!). Using a 16 bit lookup table improves things, but probably isn't worth it unless you really need it, as it uses up a large chunk of memory, and can introduce a small but noticalbe startup delay to precompute the table.</p>\n" }, { "answer_id": 189579, "author": "Constantin", "author_id": 20310, "author_profile": "https://Stackoverflow.com/users/20310", "pm_score": 2, "selected": false, "text": "<p>Not screaming-fast, but straightforward:</p>\n\n<pre><code>&gt;&gt;&gt; def bin(x):\n... sign = '-' if x &lt; 0 else ''\n... x = abs(x)\n... bits = []\n... while x:\n... x, rmost = divmod(x, 2)\n... bits.append(rmost)\n... return sign + ''.join(str(b) for b in reversed(bits or [0]))\n</code></pre>\n\n<p>It is also faster than <code>num_bin</code>:</p>\n\n<pre><code>&gt;&gt;&gt; import timeit\n&gt;&gt;&gt; t_bin = timeit.Timer('bin(0xf0)', 'from __main__ import bin')\n&gt;&gt;&gt; print t_bin.timeit(number=100000)\n4.19453350997\n&gt;&gt;&gt; t_num_bin = timeit.Timer('num_bin(0xf0)', 'from __main__ import num_bin')\n&gt;&gt;&gt; print t_num_bin.timeit(number=100000)\n4.70694716882\n</code></pre>\n\n<p>Even more, it actually works correctly (for my definition of \"correctness\" :)):</p>\n\n<pre><code>&gt;&gt;&gt; bin(1)\n'1'\n&gt;&gt;&gt; num_bin(1)\n'10000000'\n</code></pre>\n" } ]
2008/10/09
[ "https://Stackoverflow.com/questions/187273", "https://Stackoverflow.com", "https://Stackoverflow.com/users/15842/" ]
Building on [How Do You Express Binary Literals in Python](https://stackoverflow.com/questions/1476/how-do-you-express-binary-literals-in-python#13107), I was thinking about sensible, intuitive ways to do that Programming 101 chestnut of displaying integers in base-2 form. This is the best I came up with, but I'd like to replace it with a better algorithm, or at least one that should have screaming-fast performance. ``` def num_bin(N, places=8): def bit_at_p(N, p): ''' find the bit at place p for number n ''' two_p = 1 << p # 2 ^ p, using bitshift, will have exactly one # bit set, at place p x = N & two_p # binary composition, will be one where *both* numbers # have a 1 at that bit. this can only happen # at position p. will yield two_p if N has a 1 at # bit p return int(x > 0) bits = ( bit_at_p(N,x) for x in xrange(places)) return "".join( (str(x) for x in bits) ) # or, more consisely # return "".join([str(int((N & 1 << x)>0)) for x in xrange(places)]) ```
For best efficiency, you generally want to process more than a single bit at a time. You can use a simple method to get a fixed width binary representation. eg. ``` def _bin(x, width): return ''.join(str((x>>i)&1) for i in xrange(width-1,-1,-1)) ``` \_bin(x, 8) will now give a zero padded representation of x's lower 8 bits. This can be used to build a lookup table, allowing your converter to process 8 bits at a time (or more if you want to devote the memory to it). ``` _conv_table = [_bin(x,8) for x in range(256)] ``` Then you can use this in your real function, stripping off leading zeroes when returning it. I've also added handling for signed numbers, as without it you will get an infinite loop (Negative integers conceptually have an infinite number of set sign bits.) ``` def bin(x): if x == 0: return '0' #Special case: Don't strip leading zero if no other digits elif x < 0: sign='-' x*=-1 else: sign = '' l=[] while x: l.append(_conv_table[x & 0xff]) x >>= 8 return sign + ''.join(reversed(l)).lstrip("0") ``` [Edit] Changed code to handle signed integers. [Edit2] Here are some timing figures of the various solutions. bin is the function above, constantin\_bin is from [Constantin's answer](https://stackoverflow.com/questions/187273/base-2-binary-representation-using-python#189579) and num\_bin is the original version. Out of curiosity, I also tried a 16 bit lookup table variant of the above (bin16 below), and tried out Python3's builtin bin() function. All timings were for 100000 runs using an 01010101 bit pattern. ``` Num Bits: 8 16 32 64 128 256 --------------------------------------------------------------------- bin 0.544 0.586 0.744 1.942 1.854 3.357 bin16 0.542 0.494 0.592 0.773 1.150 1.886 constantin_bin 2.238 3.803 7.794 17.869 34.636 94.799 num_bin 3.712 5.693 12.086 32.566 67.523 128.565 Python3's bin 0.079 0.045 0.062 0.069 0.212 0.201 ``` As you can see, when processing long values using large chunks really pays off, but nothing beats the low-level C code of python3's builtin (which bizarrely seems consistently faster at 256 bits than 128!). Using a 16 bit lookup table improves things, but probably isn't worth it unless you really need it, as it uses up a large chunk of memory, and can introduce a small but noticalbe startup delay to precompute the table.
187,279
<p>I want to create a simple box with a header bar containing a title and some tool buttons. I have the following markup:</p> <pre><code>&lt;div style="float:left"&gt; &lt;div style="background-color:blue; padding: 1px; height: 20px;"&gt; &lt;div style="float: left; background-color:green;"&gt;title&lt;/div&gt; &lt;div style="float: right; background-color:yellow;"&gt;toolbar&lt;/div&gt; &lt;/div&gt; &lt;div style="clear: both; width: 200px; background-color: red;"&gt;content&lt;/div&gt; &lt;/div&gt; </code></pre> <p>This renders fine in Firefox and Chrome:</p> <p><a href="http://www.boplicity.nl/images/firefox.jpg">http://www.boplicity.nl/images/firefox.jpg</a></p> <p>However IE7 totally messes up and puts the right floated element to the right of the page:</p> <p><a href="http://www.boplicity.nl/images/ie7.jpg">http://www.boplicity.nl/images/ie7.jpg</a></p> <p>Can this be fixed?</p>
[ { "answer_id": 187311, "author": "Mote", "author_id": 24789, "author_profile": "https://Stackoverflow.com/users/24789", "pm_score": -1, "selected": false, "text": "<p>Make this <code>&lt;div style=\"background-color:blue; padding: 1px; height: 20px;&gt;</code> the parent of the 2 floating divs also <code>clear:all</code></p>\n" }, { "answer_id": 187313, "author": "Marko Dumic", "author_id": 5817, "author_profile": "https://Stackoverflow.com/users/5817", "pm_score": 6, "selected": true, "text": "<p>Specify width in outermost div. \nIf that width in your content div means this is the total width of your box, simply add it to the outermost div, and (optionally) remove it from content, like this:</p>\n\n<pre><code>&lt;div style=\"float:left; width: 200px;\"&gt;\n &lt;div style=\"background-color:blue; padding: 1px; height: 20px;\"&gt;\n &lt;div style=\"float: left; background-color:green;\"&gt;title&lt;/div&gt;\n &lt;div style=\"float: right; background-color:yellow;\"&gt;toolbar&lt;/div&gt;\n &lt;/div&gt;\n &lt;div style=\"clear: both; background-color: red;\"&gt;content&lt;/div&gt;\n&lt;/div&gt;\n</code></pre>\n" }, { "answer_id": 187860, "author": "Sam Murray-Sutton", "author_id": 2977, "author_profile": "https://Stackoverflow.com/users/2977", "pm_score": 2, "selected": false, "text": "<p>This is just a quick answer, so I hold my hands up if it doesn't quite work. I think Marko's solution will probably work if you just add min-width rather than width. If you are trying to cater for ie6 as well, you may need to use a hack, as min width is not supported by ie6 and it's descendants.</p>\n\n<p>So this should work with IE7 and other modern browers. Set the min-width to whatever is appropriate.</p>\n\n<pre><code>&lt;div style=\"float:left; min-width: 200px;\"&gt;\n &lt;div style=\"background-color:blue; padding: 1px; height: 20px;\"&gt;\n &lt;div style=\"float: left; background-color:green;\"&gt;title&lt;/div&gt;\n &lt;div style=\"float: right; background-color:yellow;\"&gt;toolbar&lt;/div&gt;\n &lt;/div&gt;\n &lt;div style=\"clear: both; background-color: red;\"&gt;content&lt;/div&gt;\n&lt;/div&gt;\n</code></pre>\n" }, { "answer_id": 1040518, "author": "Kees de Kooter", "author_id": 26496, "author_profile": "https://Stackoverflow.com/users/26496", "pm_score": 2, "selected": false, "text": "<p>I fixed it using jQuery to emulate the behaviour of the non-IE browsers:</p>\n\n<pre><code> // IE fix for div widths - size header to width of content\n if (!$.support.cssFloat) {\n $(\"div:has(.boxheader) &gt; table\").each(function () {\n $(this).parent().width($(this).width());\n });\n }\n</code></pre>\n" }, { "answer_id": 4174335, "author": "Toni", "author_id": 506928, "author_profile": "https://Stackoverflow.com/users/506928", "pm_score": 1, "selected": false, "text": "<p>Try putting <code>position:relative;</code> to parent-element and to the child-element. It solved the problem for me.</p>\n" }, { "answer_id": 8760056, "author": "Premanshu", "author_id": 987695, "author_profile": "https://Stackoverflow.com/users/987695", "pm_score": 1, "selected": false, "text": "<p>Got to know recently that the right floated elements need to be appended with the divs before the other elements. This is the easiest fix without adding a line of change.</p>\n\n<pre><code>&lt;div style=\"background-color:blue; padding: 1px; height: 20px;\"&gt;\n &lt;div style=\"float: right; background-color:green;\"&gt;title&lt;/div&gt;\n &lt;div style=\"float: left; background-color:yellow;\"&gt;toolbar&lt;/div&gt;\n&lt;/div&gt;\n</code></pre>\n" } ]
2008/10/09
[ "https://Stackoverflow.com/questions/187279", "https://Stackoverflow.com", "https://Stackoverflow.com/users/26496/" ]
I want to create a simple box with a header bar containing a title and some tool buttons. I have the following markup: ``` <div style="float:left"> <div style="background-color:blue; padding: 1px; height: 20px;"> <div style="float: left; background-color:green;">title</div> <div style="float: right; background-color:yellow;">toolbar</div> </div> <div style="clear: both; width: 200px; background-color: red;">content</div> </div> ``` This renders fine in Firefox and Chrome: <http://www.boplicity.nl/images/firefox.jpg> However IE7 totally messes up and puts the right floated element to the right of the page: <http://www.boplicity.nl/images/ie7.jpg> Can this be fixed?
Specify width in outermost div. If that width in your content div means this is the total width of your box, simply add it to the outermost div, and (optionally) remove it from content, like this: ``` <div style="float:left; width: 200px;"> <div style="background-color:blue; padding: 1px; height: 20px;"> <div style="float: left; background-color:green;">title</div> <div style="float: right; background-color:yellow;">toolbar</div> </div> <div style="clear: both; background-color: red;">content</div> </div> ```
187,284
<p>I have log4net running on my AsP.NET site. I'm able to log messages to my DB Table, but it isn't logging the ThreadContext properties. For example:</p> <pre><code>ThreadContext.Properties["Url"] = HttpContext.Current.Request.Url.ToString(); ThreadContext.Properties["HttpReferer"] = HttpContext.Current.Request.ServerVariables["HTTP_REFERER"]; </code></pre> <p>My log4net.config adds those values as parameters into my SQL DB table:</p> <pre><code>&lt;parameter&gt; &lt;parameterName value="@URL"/&gt; &lt;dbType value="String"/&gt; &lt;size value="512"/&gt; &lt;layout type="log4net.Layout.PatternLayout"&gt; &lt;conversionPattern value="%property{log4net:Url}"/&gt; &lt;/layout&gt; &lt;/parameter&gt; &lt;parameter&gt; &lt;parameterName value="@HttpReferer"/&gt; &lt;dbType value="String"/&gt; &lt;size value="512"/&gt; &lt;layout type="log4net.Layout.PatternLayout"&gt; &lt;conversionPattern value="%property{log4net:HttpReferer}"/&gt; &lt;/layout&gt; &lt;/parameter&gt; </code></pre> <p>As I debug, I see that those ThreadContext properties are being set, but they aren't getting into the DB. </p> <p>How can I get that to work?</p>
[ { "answer_id": 187437, "author": "Chris Kimpton", "author_id": 48310, "author_profile": "https://Stackoverflow.com/users/48310", "pm_score": 0, "selected": false, "text": "<p>Can you turn on log4net verbose/debug/show sql to see what its doing at that level? Is there perhaps another bit of config thats needed to tie it all together?</p>\n" }, { "answer_id": 188730, "author": "sgwill", "author_id": 1204, "author_profile": "https://Stackoverflow.com/users/1204", "pm_score": 5, "selected": true, "text": "<p>So, it turns out the config was to blame. It was slightly wrong:</p>\n\n<p>Original:</p>\n\n<pre><code>&lt;conversionPattern value=\"%property{log4net:HttpReferer}\"/&gt;\n</code></pre>\n\n<p>Changed:</p>\n\n<pre><code>&lt;conversionPattern value=\"%property{HttpReferer}\"/&gt;\n</code></pre>\n\n<p>I had to take out the \"log4net:\" inside of property. </p>\n\n<p>What's odd is that one property still required log4net:propertyName. I have absolutely no idea why it works this way, but that's the fix that worked!</p>\n" } ]
2008/10/09
[ "https://Stackoverflow.com/questions/187284", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1204/" ]
I have log4net running on my AsP.NET site. I'm able to log messages to my DB Table, but it isn't logging the ThreadContext properties. For example: ``` ThreadContext.Properties["Url"] = HttpContext.Current.Request.Url.ToString(); ThreadContext.Properties["HttpReferer"] = HttpContext.Current.Request.ServerVariables["HTTP_REFERER"]; ``` My log4net.config adds those values as parameters into my SQL DB table: ``` <parameter> <parameterName value="@URL"/> <dbType value="String"/> <size value="512"/> <layout type="log4net.Layout.PatternLayout"> <conversionPattern value="%property{log4net:Url}"/> </layout> </parameter> <parameter> <parameterName value="@HttpReferer"/> <dbType value="String"/> <size value="512"/> <layout type="log4net.Layout.PatternLayout"> <conversionPattern value="%property{log4net:HttpReferer}"/> </layout> </parameter> ``` As I debug, I see that those ThreadContext properties are being set, but they aren't getting into the DB. How can I get that to work?
So, it turns out the config was to blame. It was slightly wrong: Original: ``` <conversionPattern value="%property{log4net:HttpReferer}"/> ``` Changed: ``` <conversionPattern value="%property{HttpReferer}"/> ``` I had to take out the "log4net:" inside of property. What's odd is that one property still required log4net:propertyName. I have absolutely no idea why it works this way, but that's the fix that worked!
187,287
<p>I am using link to sql, I have a connected set of objects.</p> <p>I start out and do a linq statement like this</p> <pre><code>Dim L= from II in context.InventoryItems select II Dim L2 = L.tolist </code></pre> <p>The second line was so that I could narrow down where the problem was occuring. When the second line is hit I get an error "The EntitySet is already loaded and the source cannot be changed"</p> <p>Any ideas what might be causing this?</p>
[ { "answer_id": 227888, "author": "Matt V", "author_id": 30456, "author_profile": "https://Stackoverflow.com/users/30456", "pm_score": 1, "selected": false, "text": "<p>Omer's comment brings up a very good point: is this DataContext being re-used from a previous operation? If so, you may want to check out Dino Esposito's <a href=\"http://weblogs.asp.net/despos/archive/2008/03/19/more-on-datacontext-in-hopefully-a-realistic-world.aspx\" rel=\"nofollow noreferrer\">blog post</a> regarding lifetime of the DataContext to make sure you're not keeping it around too long.</p>\n\n<p>That error sounds like maybe you have already loaded data from the InventoryItems table using that DataContext and possibly made some changes to entities bound to the DataContext that you have not yet submitted. If you try your code with a brand new DataContext without specifying any special DataLoadOptions it should work.</p>\n" }, { "answer_id": 9592217, "author": "Solmead", "author_id": 2496, "author_profile": "https://Stackoverflow.com/users/2496", "pm_score": 1, "selected": true, "text": "<p>For anyone interested, be careful what you do in the constructor, I was initializing some stuff in the constructor that I shouldn't have been and it caused an error on loading from the datacontext.</p>\n" } ]
2008/10/09
[ "https://Stackoverflow.com/questions/187287", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2496/" ]
I am using link to sql, I have a connected set of objects. I start out and do a linq statement like this ``` Dim L= from II in context.InventoryItems select II Dim L2 = L.tolist ``` The second line was so that I could narrow down where the problem was occuring. When the second line is hit I get an error "The EntitySet is already loaded and the source cannot be changed" Any ideas what might be causing this?
For anyone interested, be careful what you do in the constructor, I was initializing some stuff in the constructor that I shouldn't have been and it caused an error on loading from the datacontext.
187,305
<p>I am using a FormView to update an existing SQL Server record. The rows from the sqldatasource display fine in the FormView and I can edit them. When I click Update, I get the ItemUpdating event but not the ItemUpdated event and the revisions are not written to the database. </p> <p>Can anyone help me in this please. </p>
[ { "answer_id": 187320, "author": "ine", "author_id": 4965, "author_profile": "https://Stackoverflow.com/users/4965", "pm_score": 0, "selected": false, "text": "<p>If you take out the ItemUpdating event and the ItemUpdated event, does your SQL statement execute without errors?</p>\n\n<p>If so, why don't you post some of the code you are using?</p>\n" }, { "answer_id": 187323, "author": "Solmead", "author_id": 2496, "author_profile": "https://Stackoverflow.com/users/2496", "pm_score": 0, "selected": false, "text": "<p>Can we see what the sqldatasource looks like? Did you remember to put all the parameters in the sqldatasource under the insert and update parameters list?</p>\n\n<p>Oh also are you setting the cancel property at all in the itemupdating event?</p>\n" }, { "answer_id": 227942, "author": "Matt V", "author_id": 30456, "author_profile": "https://Stackoverflow.com/users/30456", "pm_score": 1, "selected": false, "text": "<p>In your ItemUpdating event handler, make sure of the following things:</p>\n\n<p>-If you are not using optimistic concurrency checking, remove any old values the FormView may be placing in the OldValues collection.</p>\n\n<p>-Make sure that all of the parameters required by your stored procedure, query, or data source have values and are named correctly in either the Keys or NewValues collections (and make sure that no duplicates exist).</p>\n\n<p>In some cases (usually when an ObjectDataSource is involved), I've had to override the values set by the FormView control, by doing something like this:</p>\n\n<pre><code>protected void myFormView_ItemUpdating(object sender, FormViewUpdateEventArgs e)\n {\n\n // remove the old values\n e.Keys.Clear();\n e.OldValues.Clear();\n e.NewValues.Clear();\n\n // set the parameter for the key\n e.Keys.Add(\"@key\", valueGoesHere);\n\n // set other parameters\n e.NewValues.Add(\"@param1\", aValue);\n e.NewValues.Add(\"@param2\", anotherValue);\n }\n</code></pre>\n\n<p>It's not pretty, but it give you absolute control over what gets passed to the DataSource. Generally you should not have to do this if the controls in your FormView are all bound using Bind() for two-way databinding (instead of Eval), but at the very least you could put a break point in ItemUpdating and open up the e.Keys, e.OldValues, and e.NewValues collections to see if the contents are what you expected. </p>\n\n<p>A next step would be to launch SQL Server Profiler to run a trace and examine the actual query being performed.</p>\n" } ]
2008/10/09
[ "https://Stackoverflow.com/questions/187305", "https://Stackoverflow.com", "https://Stackoverflow.com/users/14752/" ]
I am using a FormView to update an existing SQL Server record. The rows from the sqldatasource display fine in the FormView and I can edit them. When I click Update, I get the ItemUpdating event but not the ItemUpdated event and the revisions are not written to the database. Can anyone help me in this please.
In your ItemUpdating event handler, make sure of the following things: -If you are not using optimistic concurrency checking, remove any old values the FormView may be placing in the OldValues collection. -Make sure that all of the parameters required by your stored procedure, query, or data source have values and are named correctly in either the Keys or NewValues collections (and make sure that no duplicates exist). In some cases (usually when an ObjectDataSource is involved), I've had to override the values set by the FormView control, by doing something like this: ``` protected void myFormView_ItemUpdating(object sender, FormViewUpdateEventArgs e) { // remove the old values e.Keys.Clear(); e.OldValues.Clear(); e.NewValues.Clear(); // set the parameter for the key e.Keys.Add("@key", valueGoesHere); // set other parameters e.NewValues.Add("@param1", aValue); e.NewValues.Add("@param2", anotherValue); } ``` It's not pretty, but it give you absolute control over what gets passed to the DataSource. Generally you should not have to do this if the controls in your FormView are all bound using Bind() for two-way databinding (instead of Eval), but at the very least you could put a break point in ItemUpdating and open up the e.Keys, e.OldValues, and e.NewValues collections to see if the contents are what you expected. A next step would be to launch SQL Server Profiler to run a trace and examine the actual query being performed.
187,319
<p>I could use some help writing a regular expression. In my Django application, users can hit the following URL:</p> <pre><code>http://www.example.com/A1/B2/C3 </code></pre> <p>I'd like to create a regular expression that allows accepts any of the following as a valid URL:</p> <pre><code>http://www.example.com/A1 http://www.example.com/A1/B2 http://www.example.com/A1/B2/C3 </code></pre> <p>I'm guessing I need to use the "OR" conditional, but I'm having trouble getting my regex to validate. Any thoughts?</p> <p><strong>UPDATE</strong>: Here is the regex so far. Note that I have not included the "<a href="http://www.example.com" rel="nofollow noreferrer">http://www.example.com</a>" portion -- Django handles that for me. I'm just concerned with validating 1,2, or 3 subdirectories.</p> <pre><code>^(\w{1,20})|((\w{1,20})/(\w{1,20}))|((\w{1,20})/(\w{1,20})/(\w{1,20}))$ </code></pre>
[ { "answer_id": 187392, "author": "James Curran", "author_id": 12725, "author_profile": "https://Stackoverflow.com/users/12725", "pm_score": 1, "selected": false, "text": "<pre><code>http://www\\.example\\.com/A1(/B2(/C3)?)?\n</code></pre>\n" }, { "answer_id": 187395, "author": "Andre Bossard", "author_id": 21027, "author_profile": "https://Stackoverflow.com/users/21027", "pm_score": 4, "selected": true, "text": "<p>Skip the <code>|</code>, use the <code>?</code> and <code>()</code></p>\n\n<p><code>http://www\\.example\\.com/A1(/B2(/C3)?)?</code></p>\n\n<p>And if you replace the A1-C3 with a pattern:</p>\n\n<p><code>http://www\\.example\\.com/[^/]*(/[^/]*(/[^/]*)?)?</code></p>\n\n<p>Explanation:</p>\n\n<ul>\n<li>it matches every string that starts with <code>http://www.example.com/A1</code></li>\n<li>it can match an additional <code>/B2</code> and even an additional <code>/C3</code>, but <code>/C3</code> is only matched, when there is a <code>/B2</code></li>\n<li><code>[^/]*</code> (as many non slashes as possible)</li>\n<li>if you need the A1-C3 in special capture groups, you can use this:</li>\n</ul>\n\n<p><code>http://www\\.example\\.com/([^/]*)(/([^/]*)(/([^/]*))?)?</code></p>\n\n<p>Will give (<code>groupnumber: content</code>):</p>\n\n<pre><code>matches: 0: (http://www.example.com/dir1/dir2/dir3)\n1: (dir1)\n2: (/dir2/dir3)\n3: (dir2)\n4: (/dir3)\n5: (dir3)\n</code></pre>\n\n<p>You can check it out online <a href=\"http://www.regextester.com/\" rel=\"nofollow noreferrer\">here</a> or get this <a href=\"http://www.weitz.de/regex-coach/\" rel=\"nofollow noreferrer\">tool</a> (yes it's free, and it's even written in Lisp...).</p>\n" }, { "answer_id": 187404, "author": "Epaga", "author_id": 6583, "author_profile": "https://Stackoverflow.com/users/6583", "pm_score": 1, "selected": false, "text": "<pre><code> ^(\\w{1,20})(/\\w{1,20})*\n</code></pre>\n\n<p>this is for as many subdirectories as you like if you only want 2:</p>\n\n<pre><code> ^(\\w{1,20})(/\\w{1,20}){0,2}\n</code></pre>\n" }, { "answer_id": 187409, "author": "Lucas Oman", "author_id": 6726, "author_profile": "https://Stackoverflow.com/users/6726", "pm_score": 1, "selected": false, "text": "<p>If I'm understanding, I think you just need another set of parens around the whole OR statement:</p>\n\n<pre><code>^((\\w{1,20})|((\\w{1,20})/(\\w{1,20}))|((\\w{1,20})/(\\w{1,20})/(\\w{1,20})))$\n</code></pre>\n" }, { "answer_id": 206123, "author": "akaihola", "author_id": 15770, "author_profile": "https://Stackoverflow.com/users/15770", "pm_score": 1, "selected": false, "text": "<p>Be aware that Django's <a href=\"http://docs.djangoproject.com/en/dev/topics/http/urls/#id2\" rel=\"nofollow noreferrer\">reverse URL matching</a> (permalinks, <code>reverse()</code> and <code>{% url %}</code>) can handle a limited subset of regular expressions. To be able to use them, it's sometimes necessary to split complex regexes into separate URL dispatcher rules.</p>\n" }, { "answer_id": 1167804, "author": "Adam Nelson", "author_id": 26235, "author_profile": "https://Stackoverflow.com/users/26235", "pm_score": 2, "selected": false, "text": "<p>There's a much more Django way to do this:</p>\n\n<pre><code>urlpatterns = patterns('',\n url(r'^(?P&lt;object_slug1&gt;\\w{2}/(?P&lt;object_slug2&gt;\\w{2}/(?P&lt;object_slug3&gt;\\w{2})$', direct_to_template, {\"template\": \"two_levels_deep.html\"}, name=\"two_deep\"),\n url(r'^(?P&lt;object_slug1&gt;\\w{2}/(?P&lt;object_slug2&gt;\\w{2})$', direct_to_template, {\"template\": \"one_level_deep.html\"}, name=\"one_deep\"),\n url(r'^(?P&lt;object_slug1&gt;\\w{2})$', direct_to_template, {\"template\": \"homepage.html\"}, name=\"home\"),\n)\n</code></pre>\n\n<p>The other methods don't take advantage of Django's power to pass variables.</p>\n\n<p>Edit: I switched the order of the urlpattern to be more obvious for the parser (i.e. bottom up is more defined than top down).</p>\n" } ]
2008/10/09
[ "https://Stackoverflow.com/questions/187319", "https://Stackoverflow.com", "https://Stackoverflow.com/users/10040/" ]
I could use some help writing a regular expression. In my Django application, users can hit the following URL: ``` http://www.example.com/A1/B2/C3 ``` I'd like to create a regular expression that allows accepts any of the following as a valid URL: ``` http://www.example.com/A1 http://www.example.com/A1/B2 http://www.example.com/A1/B2/C3 ``` I'm guessing I need to use the "OR" conditional, but I'm having trouble getting my regex to validate. Any thoughts? **UPDATE**: Here is the regex so far. Note that I have not included the "<http://www.example.com>" portion -- Django handles that for me. I'm just concerned with validating 1,2, or 3 subdirectories. ``` ^(\w{1,20})|((\w{1,20})/(\w{1,20}))|((\w{1,20})/(\w{1,20})/(\w{1,20}))$ ```
Skip the `|`, use the `?` and `()` `http://www\.example\.com/A1(/B2(/C3)?)?` And if you replace the A1-C3 with a pattern: `http://www\.example\.com/[^/]*(/[^/]*(/[^/]*)?)?` Explanation: * it matches every string that starts with `http://www.example.com/A1` * it can match an additional `/B2` and even an additional `/C3`, but `/C3` is only matched, when there is a `/B2` * `[^/]*` (as many non slashes as possible) * if you need the A1-C3 in special capture groups, you can use this: `http://www\.example\.com/([^/]*)(/([^/]*)(/([^/]*))?)?` Will give (`groupnumber: content`): ``` matches: 0: (http://www.example.com/dir1/dir2/dir3) 1: (dir1) 2: (/dir2/dir3) 3: (dir2) 4: (/dir3) 5: (dir3) ``` You can check it out online [here](http://www.regextester.com/) or get this [tool](http://www.weitz.de/regex-coach/) (yes it's free, and it's even written in Lisp...).
187,326
<p>Is exposing CRUD operations through SOAP web services a bad idea? My instinct tells me that it is not least of which because the overhead of doing database calls overhead could be huge. I'm struggling to find documentation for/against this (anti)pattern so I was wondering if anyone could point me to some documentation or has an opinion on the matter. </p> <p>Also, if anyone knows of best practises (and/or documentation to that effect) when designing soap services, that would be great.</p> <p>Here's an example of how the web service would look:</p> <ul> <li>Create</li> <li>Delete</li> <li>Execute</li> <li>Fetch</li> <li>Update </li> </ul> <p>And here's what the implementation would look like:</p> <pre><code>[WebMethod] public byte[] Fetch(byte[] requestData) { SelectRequest request = (SelectRequest)Deserialize(requestData); DbManager crudManager = new DbManager(); object result = crudManager.Select(request.ObjectType, request.Criteria); return Serialize(result); } </code></pre>
[ { "answer_id": 187424, "author": "Ilya Kochetov", "author_id": 15329, "author_profile": "https://Stackoverflow.com/users/15329", "pm_score": 0, "selected": false, "text": "<p>There is nothing wrong with exposing the CRUD operations via SOAP web-services per se.</p>\n\n<p>You will obviously find quite a lot of examples for such services.</p>\n\n<p>However depending on your particular requirements you might find that for you using SOAP is too much overhead or that you could be better off using use JSON/AJAX etc.</p>\n\n<p>So I believe that unless you will provide additional details about your particular details there is no good answer for your question.</p>\n" }, { "answer_id": 187449, "author": "Ian", "author_id": 4396, "author_profile": "https://Stackoverflow.com/users/4396", "pm_score": 2, "selected": false, "text": "<p>I think publishing a SOAP service that exposes CRUD operations to anonymous, public \"users\" would be a particularly bad idea. If, however, you can restrict one or both of these caveats, then I see nothing wrong with it (moreover I've implemented such services many times).</p>\n\n<ul>\n<li><p>You can require, in addition to whatever method parameters your require to perform the operation, username &amp; password parameters that in effect authenticates the originator prior to processing the request: a failure to authenticate can be signalled with the return of a SOAP exception. If you were especially paranoid, you could optionally run the service over SSL</p></li>\n<li><p>You can have the server solution that deals with sending and receiving the requests filter based on IP, onyl allowing requests from a list of approved addresses.</p></li>\n</ul>\n\n<p>Yes, there are overheads to running requests over SOAP (as opposed to exposing direct database access) - namely the processing time to wrap a request into a HTTP request, open a socket &amp; send it (and the reverse at the receiving end and the again for the response) - but, it does have advantages.</p>\n\n<p>Java (though the NetBeans IDE) and .Net (through VS), both support consumption of Web Services into projects / solutions - the biggest benefit of this is that objects / structures on the remote service are automatically translated into native objects in the consuming application, which is exceptionally handy.</p>\n" }, { "answer_id": 187452, "author": "Nick", "author_id": 22407, "author_profile": "https://Stackoverflow.com/users/22407", "pm_score": 2, "selected": false, "text": "<p>If all you want to do is CRUD over the web, I'd look at some different technologies for doing REST instead of using WS*. <a href=\"http://www.microsoft.com/sql/dataservices/default.mspx\" rel=\"nofollow noreferrer\">SQL Data Services</a> (formerly Project Astoria) might actually be a good alternative.</p>\n" }, { "answer_id": 187484, "author": "blowdart", "author_id": 2525, "author_profile": "https://Stackoverflow.com/users/2525", "pm_score": 2, "selected": false, "text": "<p>If you want to use SOAP in a RESTful manner then there is a interesting standard for this, <a href=\"http://www.w3.org/Submission/WS-Transfer/\" rel=\"nofollow noreferrer\">WS-Transfer</a>; which provides loosely coupled CRUD endpoints; from which you inspect the message and act upon your entities accordingly.</p>\n\n<p>Then you can layer whatever else you want on top, WS-Secure, WS-Reliable messaging and so on.</p>\n" } ]
2008/10/09
[ "https://Stackoverflow.com/questions/187326", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9539/" ]
Is exposing CRUD operations through SOAP web services a bad idea? My instinct tells me that it is not least of which because the overhead of doing database calls overhead could be huge. I'm struggling to find documentation for/against this (anti)pattern so I was wondering if anyone could point me to some documentation or has an opinion on the matter. Also, if anyone knows of best practises (and/or documentation to that effect) when designing soap services, that would be great. Here's an example of how the web service would look: * Create * Delete * Execute * Fetch * Update And here's what the implementation would look like: ``` [WebMethod] public byte[] Fetch(byte[] requestData) { SelectRequest request = (SelectRequest)Deserialize(requestData); DbManager crudManager = new DbManager(); object result = crudManager.Select(request.ObjectType, request.Criteria); return Serialize(result); } ```
I think publishing a SOAP service that exposes CRUD operations to anonymous, public "users" would be a particularly bad idea. If, however, you can restrict one or both of these caveats, then I see nothing wrong with it (moreover I've implemented such services many times). * You can require, in addition to whatever method parameters your require to perform the operation, username & password parameters that in effect authenticates the originator prior to processing the request: a failure to authenticate can be signalled with the return of a SOAP exception. If you were especially paranoid, you could optionally run the service over SSL * You can have the server solution that deals with sending and receiving the requests filter based on IP, onyl allowing requests from a list of approved addresses. Yes, there are overheads to running requests over SOAP (as opposed to exposing direct database access) - namely the processing time to wrap a request into a HTTP request, open a socket & send it (and the reverse at the receiving end and the again for the response) - but, it does have advantages. Java (though the NetBeans IDE) and .Net (through VS), both support consumption of Web Services into projects / solutions - the biggest benefit of this is that objects / structures on the remote service are automatically translated into native objects in the consuming application, which is exceptionally handy.
187,357
<p>Consider this:</p> <pre><code>var query = from r in this._db.Recipes where r.RecipesID == recipeID select new { r.RecipesID, r.RecipesName }; </code></pre> <p>How would i get individual columns in my <code>query</code> object without using a for-loop?</p> <p>Basicly: how do I translate <code>DataTable.Rows[0]["ColumnName"]</code> into Linq syntax?</p>
[ { "answer_id": 187401, "author": "Chris Shaffer", "author_id": 6744, "author_profile": "https://Stackoverflow.com/users/6744", "pm_score": 0, "selected": false, "text": "<p>Sorry, misunderstood your question. As others are saying, you can use ToList() to get a List back. An alternative if all you need is the first one, just use:</p>\n\n<pre><code>\nquery.First().ColumnName\n</code></pre>\n\n<p>or if you want to avoid an exception on empty list:</p>\n\n<pre><code>\nvar obj = query.FirstOrDefault();\nif (obj != null)\n obj.ColumnName;\n</code></pre>\n\n<hr>\n\n<p>Original Answer (so the comment makes sense):</p>\n\n<p>Use <a href=\"http://blogs.msdn.com/adonet/archive/2007/01/26/querying-datasets-introduction-to-linq-to-dataset.aspx\" rel=\"nofollow noreferrer\">Linq to Datasets</a>. Basically would be something like:</p>\n\n<pre><code>\nvar query = from r in yourTable.AsEnumerable()\nselect r.Field&lt;string>(\"ColumnName\");\n</code></pre>\n" }, { "answer_id": 187413, "author": "James Curran", "author_id": 12725, "author_profile": "https://Stackoverflow.com/users/12725", "pm_score": 2, "selected": false, "text": "<p>It's really unclear what you are looking for, as your two samples are compatible. </p>\n\n<p>As close as I can figure, what you want is:</p>\n\n<pre><code>var rows = query.ToList();\nstring name = rows[0].RecipesName;\n</code></pre>\n" }, { "answer_id": 187507, "author": "Richard Poole", "author_id": 26003, "author_profile": "https://Stackoverflow.com/users/26003", "pm_score": 2, "selected": false, "text": "<pre><code>string name = this._db.Recipes.Single(r =&gt; r.RecipesID == recipeID).RecipesName;\n</code></pre>\n" }, { "answer_id": 189527, "author": "cllpse", "author_id": 20946, "author_profile": "https://Stackoverflow.com/users/20946", "pm_score": 2, "selected": true, "text": "<p>This is the way to go about it:</p>\n\n<pre><code>DataContext dc = new DataContext();\n\nvar recipe = (from r in dc.Recipes \n where r.RecipesID == 1\n select r).FirstOrDefault();\n\nif (recipe != null)\n{\n id = recipe.RecipesID;\n name = recipe.RecipesName;\n}\n</code></pre>\n" } ]
2008/10/09
[ "https://Stackoverflow.com/questions/187357", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20946/" ]
Consider this: ``` var query = from r in this._db.Recipes where r.RecipesID == recipeID select new { r.RecipesID, r.RecipesName }; ``` How would i get individual columns in my `query` object without using a for-loop? Basicly: how do I translate `DataTable.Rows[0]["ColumnName"]` into Linq syntax?
This is the way to go about it: ``` DataContext dc = new DataContext(); var recipe = (from r in dc.Recipes where r.RecipesID == 1 select r).FirstOrDefault(); if (recipe != null) { id = recipe.RecipesID; name = recipe.RecipesName; } ```
187,359
<p>We use Visual Studio 2008 and Surround SCM for source control. SCM drops files into each directory named ".MySCMServerInfo" which are user specific data files that shouldn't be checked into source control. They are similar to the .scc files dropped by Visual Source Safe. We also have several WAPs (Web Application Projects) that we develop. All these .MySCMServerInfo files show up in the solution tree and the Pending Checkins window when they should not. There has to be some way to force VS to ignore files of a given extension because it ignores .scc files. How do I get VS to ignore .MySCMServerInfo files within a WAP?</p>
[ { "answer_id": 193133, "author": "Craig Quillen", "author_id": 18456, "author_profile": "https://Stackoverflow.com/users/18456", "pm_score": 0, "selected": false, "text": "<p>Using the file system hidden bit should work.</p>\n" }, { "answer_id": 296353, "author": "Charles", "author_id": 24898, "author_profile": "https://Stackoverflow.com/users/24898", "pm_score": 3, "selected": true, "text": "<p>I have new information about this issue. Setting the hidden bit on .MySCMServerInfo file causes Surround SCM to loose track of the modification state for files. It starts thinking files are out-of-date when they are not, and it always attemps to get new versions.</p>\n\n<p>Instead, set this registry key if you're using Visual Studio 2008:</p>\n\n<pre><code>[HKEY_LOCAL_MACHINE\\SOFTWARE\\Microsoft\\VisualStudio\\9.0\\Packages\\\n{8FF02D1A-C177-4ac8-A62F-88FC6EA65F57}\\IgnorableFiles\\.MySCMServerInfo]\n</code></pre>\n\n<p>Set this registry key if you're using Visual Studio 2005:</p>\n\n<pre><code>[HKEY_LOCAL_MACHINE\\SOFTWARE\\Microsoft\\VisualStudio\\8.0\\Packages\\\n{8FF02D1A-C177-4ac8-A62F-88FC6EA65F57}\\IgnorableFiles\\.MySCMServerInfo]\n</code></pre>\n\n<p>These will tell Visual Studio to not display .MySCMServerInfo files within the Solution tree and the Pending Checkins view.</p>\n" }, { "answer_id": 35192314, "author": "RonnBlack", "author_id": 81730, "author_profile": "https://Stackoverflow.com/users/81730", "pm_score": 0, "selected": false, "text": "<p>Late Answer but hopefully useful to others.</p>\n\n<p>I began experiencing this problem when using Visual Studio 2015 with the new ASP.Net 5 Project templates. (I presume this is because the new templates automatically include everything in the folder rather than only showing the things that are listed in the project file).</p>\n\n<p>Showing these files in the Solution explorer change be prevented by right clicking the file and selecting \"Hide from Solution Explorer\" but this didn't prevent SCM from including them in the Pending Check-ins Window.</p>\n\n<p>The correct way to deal with this problem is:</p>\n\n<ol>\n<li>Select the file(s) in Solution Explorer</li>\n<li>Select the File > Source Control > Exclude from Source Control</li>\n</ol>\n\n<p><a href=\"http://www.seapine.com/knowledgebase/index.php?View=entry&amp;EntryID=751\" rel=\"nofollow\">Reference</a></p>\n\n<hr>\n\n<p><em><b>NOTE:</b></em> Right Click in the Solution Explorer DOESN'T have this option.</p>\n" } ]
2008/10/09
[ "https://Stackoverflow.com/questions/187359", "https://Stackoverflow.com", "https://Stackoverflow.com/users/24898/" ]
We use Visual Studio 2008 and Surround SCM for source control. SCM drops files into each directory named ".MySCMServerInfo" which are user specific data files that shouldn't be checked into source control. They are similar to the .scc files dropped by Visual Source Safe. We also have several WAPs (Web Application Projects) that we develop. All these .MySCMServerInfo files show up in the solution tree and the Pending Checkins window when they should not. There has to be some way to force VS to ignore files of a given extension because it ignores .scc files. How do I get VS to ignore .MySCMServerInfo files within a WAP?
I have new information about this issue. Setting the hidden bit on .MySCMServerInfo file causes Surround SCM to loose track of the modification state for files. It starts thinking files are out-of-date when they are not, and it always attemps to get new versions. Instead, set this registry key if you're using Visual Studio 2008: ``` [HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\VisualStudio\9.0\Packages\ {8FF02D1A-C177-4ac8-A62F-88FC6EA65F57}\IgnorableFiles\.MySCMServerInfo] ``` Set this registry key if you're using Visual Studio 2005: ``` [HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\VisualStudio\8.0\Packages\ {8FF02D1A-C177-4ac8-A62F-88FC6EA65F57}\IgnorableFiles\.MySCMServerInfo] ``` These will tell Visual Studio to not display .MySCMServerInfo files within the Solution tree and the Pending Checkins view.
187,380
<p>Ruby is becoming <a href="http://www.tiobe.com/index.php/content/paperinfo/tpci/index.html" rel="noreferrer">popular</a>, largely from the influence Ruby on Rails, but it feels like it is currently struggling through its adolescence. There are a lot of similarities between Ruby and Smalltalk -- <a href="http://ruby.gemstone.com/" rel="noreferrer">maglev</a> is a testament to that. Despite having a more unusual syntax, Smalltalk has all (if not more) of the object-oriented beauty of Ruby. </p> <p>From what I have read, Smalltalk seems to have Ruby beat on:</p> <ul> <li>Maturity (developed in the 1970's)</li> <li>Stability</li> <li>Commercial support</li> <li><a href="http://www.wiresong.ca/monticello/" rel="noreferrer">Distributed source control</a> (understands structure of code, not just text diffing)</li> <li>Several <a href="http://en.wikipedia.org/wiki/Smalltalk#List_of_implementations" rel="noreferrer">implementations of the VM</a></li> <li>Cross-platform support</li> <li>The <a href="http://www.seaside.st/" rel="noreferrer">seaside web framework</a> as a <a href="http://www.sauria.com/blog/2005/11/10" rel="noreferrer">strong alternative to Rails</a> </li> </ul> <p>It seems like Ruby is just reinventing the wheel. So, why don't Ruby developers use SmallTalk? <strong>What does Ruby have the Smalltalk doesn't?</strong> </p> <p><em>For the record: I'm a Ruby guy with little to no experience in Smalltalk, but I'm starting to wonder why.</em></p> <hr> <p><strong>Edit:</strong> I think the ease-of-scripting issue has been addressed by <a href="http://en.wikipedia.org/wiki/GNU_Smalltalk" rel="noreferrer">GNU Smalltalk</a>. As I understand it, this allows you to write smalltalk in regular old text files, and you no longer need to be in the Smalltalk IDE. You can then <a href="http://www.gnu.org/software/smalltalk/manual/html_node/Invocation.html#Invocation" rel="noreferrer">run your scripts</a> with:</p> <pre><code>gst smalltalk_file </code></pre>
[ { "answer_id": 187400, "author": "coder1", "author_id": 3018, "author_profile": "https://Stackoverflow.com/users/3018", "pm_score": 3, "selected": false, "text": "<p>Ruby is the current buzz language. It's easier to market software built with it right now than a language developed in the 70s.</p>\n" }, { "answer_id": 187403, "author": "Simon Knights", "author_id": 15868, "author_profile": "https://Stackoverflow.com/users/15868", "pm_score": 3, "selected": false, "text": "<p>For me its not so much a case of what Ruby has, but what Ruby hasn't. And the thing that it doesn't have is the need for a VM and complete environment.</p>\n\n<p>Smalltalk is great - its where I learnt OO concepts, but for ease of use I go for Ruby. I can write Ruby code in my favourite editor and run it form the command line.</p>\n\n<p>So, for me, thats what I choose Ruby over Smalltalk.</p>\n" }, { "answer_id": 187412, "author": "Chris Kimpton", "author_id": 48310, "author_profile": "https://Stackoverflow.com/users/48310", "pm_score": 2, "selected": false, "text": "<p>I've done a little Smalltalk - the IDE is one thing I remember - does Ruby have good IDE support?</p>\n" }, { "answer_id": 187444, "author": "Steve g", "author_id": 12092, "author_profile": "https://Stackoverflow.com/users/12092", "pm_score": 0, "selected": false, "text": "<p>I think part of the problem is the development-environment-is-the-runtime. This gives a lot of power, but it also presents a larger learning curve. </p>\n\n<p><a href=\"http://wiki.squeak.org/squeak/2230\" rel=\"nofollow noreferrer\">Here</a> is a hello world tutorial.</p>\n\n<p>This is very different from other languages where I just need to know how to open a text editor and copy and paste text, hit save, and run a compiler. I HAVE to know how to use the environment. That tutorial doesn't even show me how to create a basic program (which is likely more a fault of that tutorial) that I can run.</p>\n\n<p>There is definately a higher cost of just getting things going than most other languages.</p>\n\n<p>Most languages have some nice eye-catching code that they can show off. I haven't seen that with Smalltalk. I also think that there is some stigma to Smalltalk because it has been around so long and it is still relatively obscure.</p>\n" }, { "answer_id": 187542, "author": "Kevin Kaske", "author_id": 2737, "author_profile": "https://Stackoverflow.com/users/2737", "pm_score": 3, "selected": false, "text": "<p>Community! Ruby and especially Rails has such a great community. When messing around with smalltalk it seemed that there were not as many screen casts, articles, blog posts, etc. written about Smalltalk.</p>\n" }, { "answer_id": 187573, "author": "Simon Knights", "author_id": 15868, "author_profile": "https://Stackoverflow.com/users/15868", "pm_score": 4, "selected": false, "text": "<p>Stephane Ducasse has some great Smalltalk books available here:</p>\n\n<p><a href=\"http://stephane.ducasse.free.fr/FreeBooks.html\" rel=\"noreferrer\">http://stephane.ducasse.free.fr/FreeBooks.html</a></p>\n\n<p>so although the Smalltalk community is not as prolific as the Ruby and Rails communities, there is still some great help out there.</p>\n" }, { "answer_id": 189248, "author": "ConcernedOfTunbridgeWells", "author_id": 15401, "author_profile": "https://Stackoverflow.com/users/15401", "pm_score": 7, "selected": true, "text": "<p>I'm more of a Pythonista than a Ruby user, however the same things hold for Ruby for much the same reasons.</p>\n\n<ul>\n<li><p>The architecture of Smalltalk is somewhat insular whereas Python and Ruby were built from the ground up to facilitate integration. Smalltalk never really gained a body of hybrid application support in the way that Python and Ruby have, so the concept of 'smalltalk as embedded scripting language' never caught on.<br><br>As an aside, Java was not the easiest thing to interface with other code bases (JNI is fairly clumsy), but that did not stop it from gaining mindshare. IMO the interfacing argument is significant - ease of embedding hasn't hurt Python - but this argument only holds moderate weight as not all applications require this capability. Also, later versions of Smalltalk did substantially address the insularity.</p></li>\n<li><p>The class library of most of the main smalltalk implementations (VisualWorks, VisualAge etc.) was large and had reputation for a fairly steep learning curve. Most key functionality in Smalltalk is hidden away somewhere in the class library, even basic stuff like streams and collections. The language paradigm is also something of a culture shock for someone not familiar with it, and the piecemeal view of the program presented by the browser is quite different to what most people were used to.<br><br>The overall effect is that Smalltalk got a (somewhat deserved) reputation for being difficult to learn; it takes quite a bit of time and effort to become a really proficient Smalltalk programmer. Ruby and Python are much easier to learn and to bring new programmers up to speed with.</p></li>\n<li><p>Historically, mainstream Smalltalk implementations were quite expensive and needed exotic hardware to run, as can be seen <a href=\"http://groups.google.co.uk/group/net.lang.st80/browse_thread/thread/c35c4ad7fad659c4?hl=en#\" rel=\"noreferrer\">this net.lang.st80 posting from 1983</a>. Windows 3.1, NT and '95 and OS/2 were the first mass market operating systems on mainstream hardware capable of supporting a Smalltalk implementation with decent native system integration. Previously, Mac or workstation hardware were the cheapest platforms capable of running Smalltalk effectively. Some implementations (particularly Digitalk) supported PC operating systems quite well and did succeed in gaining some traction.<br><br>However, OS/2 was never that successful and Windows did not achieve mainstream acceptance until the mid 1990s. Unfortunately this coincided with the rise of the Web as a platform and a large marketing push behind Java. Java grabbed most of the mindshare in the latter part of the 1990s, rendering Smalltalk a bit of an also-ran.</p></li>\n<li><p>Ruby and Python work in a more conventional toolchain and are not tightly coupled to a specific development environment. While the Smalltalk IDEs I have used are nice enough I use PythonWin for Python development largely because it has a nice editor with syntax highlighting and doesn't get underfoot.<br><br>However, Smalltalk is was designed to be used with an IDE (in fact, Smalltalk was the original graphical IDE) and still has some nice features not replicated by other systems. Testing code with highlight and 'Show it' is still a very nice feature that I have never seen in a Python IDE, although I can't speak for Ruby.</p></li>\n<li><p>Smalltalk was somewhat late coming to the web application party. Early efforts such as VisualWave were never terribly successful and it was not until Seaside came out that a decent web framework got acceptance in Smalltalk circles. In the meantime Java EE has had a complete acceptance lifecycle starting with raving fanboys promoting it and finally getting bored and moving onto Ruby ;-}<br><br>Ironically, Seaside is starting to get a bit of mindshare among the cognoscenti so we may find that Smalltalk rides that cycle back into popularity.</p></li>\n</ul>\n\n<p>Having said that, Smalltalk is a very nice system once you've worked out how to drive it. </p>\n" }, { "answer_id": 193844, "author": "vesan", "author_id": 27032, "author_profile": "https://Stackoverflow.com/users/27032", "pm_score": 4, "selected": false, "text": "<blockquote>\n <p>It's true the languages are very much alike. The shallow way to interpret that is to call Ruby a Smalltalk cover band. The more reasonable interpretation is that Smalltalk's closed system isolated it, while Ruby's participation in the Unix ecology and habit of appropriating features from every language under the sun gives it an infinitely gentler adoption curve and effortless integration with kickass tools like Git.</p>\n</blockquote>\n\n<p><a href=\"http://gilesbowkett.blogspot.com/2008/10/smalltalk-complaints-and-opportunities.html\" rel=\"noreferrer\">Giles Bowkett</a></p>\n" }, { "answer_id": 193887, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 0, "selected": false, "text": "<p>I think the BIGGEST difference is that Ruby is much more similar to perl in terms of USEAGE. Smalltalk never got a foothold into the \"scripting\" languages.</p>\n\n<p>The VM is really cool and I hope ruby will have something similar to it so we can treat everything on our OS that is written in ruby as object in memory space, however until then I simply enjoy Ruby's terse, short syntax, the ability to just write a tiny script and reuse it later. Ruby got all the advantages of perl and the OOP is much more similar to smalltalk than perl's OOP hack.</p>\n" }, { "answer_id": 193943, "author": "dbr", "author_id": 745, "author_profile": "https://Stackoverflow.com/users/745", "pm_score": 3, "selected": false, "text": "<p>You answered the question in your first line: \"Ruby is becoming popular\"</p>\n\n<ul>\n<li>There are a <em>lot</em> of interesting modules, projects and such based around Ruby. </li>\n<li>If you have trouble doing something in Ruby, it will be trivial to find help somewhere.</li>\n<li>Ruby is installed on a <em>lot</em> of computers now (It's included by default on OS X, many Linux distros, and there are good installers for Windows) - I've not seen smalltalk installed by default on any machine I've used..</li>\n</ul>\n\n<p>I would say wether or not one language is superior to another is irrelevant.. As an example, PHP may not be the \"best\" language ever, but I would still consider using it over Ruby on Rails (a \"better\" tool for creating websites) because it is so widespread.</p>\n\n<p>Basically, specific pros and cons of a language are far less important than everything surrounding it - namely the community.</p>\n" }, { "answer_id": 194068, "author": "Jonke", "author_id": 15638, "author_profile": "https://Stackoverflow.com/users/15638", "pm_score": 5, "selected": false, "text": "<p>I think your question is somewhat missing the point.\n<em>You</em> shouldn't choose, you should <strong>learn</strong> them both!</p>\n\n<p>If you truly are in a position that you can choose the next framework(vm, infrastructure) then you need to decided what to use and can ask a specific question with pros and cons from the perspective of what your application is inteded to do.</p>\n\n<p>I have used smalltalk (love it) and ruby (love it).</p>\n\n<p>At home or for open source project I can use every language I like, but when doing work I have to adopt.</p>\n\n<p>I started to use ruby (at work) because we needed some scripting language that behaved more-or-less equally under solaris,linux and windows(98,2000,xp). Ruby was at that time unknown to average-joe and there didn't exist any rails. But it was easy to sell to everyone involved. </p>\n\n<p>(Why not python? the truth ? I once spend a week hunting for a bug that happened when a terminal converted my space to a tab and the intending got messed up).</p>\n\n<p>So people started to code more and more in ruby because it was so relaxing, enjoying and not a cloud on the sky.</p>\n\n<p><a href=\"http://www.paulgraham.com/popular.html\" rel=\"noreferrer\">Paul Graham sums it up</a></p>\n\n<blockquote>\n <p>It's true, certainly, that most people don't choose programming languages simply based on their merits. Most programmers are told what language to use by someone else. </p>\n</blockquote>\n\n<p>and </p>\n\n<blockquote>\n <p>To be attractive to hackers, a\n language must be good for writing the\n kinds of programs they want to write.\n And that means, perhaps surprisingly,\n that it has to be good for writing\n throwaway programs.</p>\n</blockquote>\n\n<p><a href=\"http://www.randomhacks.net/articles/2005/12/03/why-ruby-is-an-acceptable-lisp\" rel=\"noreferrer\">And when were at the Lisp land try to replace LISP with smalltalk</a></p>\n\n<blockquote>\n <blockquote>\n <p>Ruby’s libraries, community, and momentum are good</p>\n </blockquote>\n \n <p>So if LISP is still more powerful than\n Ruby, why not use LISP? The typical\n objections to programming in LISP are:</p>\n \n <ol>\n <li>There aren’t enough libraries.</li>\n <li>We can’t hire LISP programmers.</li>\n <li>LISP has gone nowhere in the past 20 years.</li>\n </ol>\n \n <p>These aren’t overwhelming objections,\n but they’re certainly worth\n considering.</p>\n</blockquote>\n\n<p>and</p>\n\n<blockquote>\n <p>Now, given a choice between a powerful\n language, and popular language, it may\n make excellent sense to pick the\n powerful one. But if the difference in\n power is minor, being popular has all\n sorts of nice advantages. In 2005, I’d\n think long and hard before choosing\n LISP over Ruby. I’d probably only do\n it if I needed optimized code, or\n macros which acted as full-fledged\n compilers.</p>\n</blockquote>\n" }, { "answer_id": 194087, "author": "Michael Easter", "author_id": 12704, "author_profile": "https://Stackoverflow.com/users/12704", "pm_score": 4, "selected": false, "text": "<p>what does Ruby have that Smalltalk doesn't?</p>\n\n<ul>\n<li>Massive, current support by major platforms (IronRuby and jRuby) that enrich the set of libraries</li>\n<li>Evangelists like Dave Thomas who, for years, have been touring around the country preaching the gospel of their language. I have seen Dave at <em>Java conferences</em> stating he doesn't know Java and that he prefers Ruby.</li>\n<li>Strong, current real estate on the bookshelves</li>\n<li>The creator of Ruby has said that he thinks about the programmer: Ruby's syntax seems to have this Zen appeal. It is hard to pin down, yet seems to galvanize the fans.</li>\n<li>Creative, dynamic presentations like <a href=\"https://www.youtube.com/watch?v=0XDawYp9mKY\" rel=\"nofollow noreferrer\">Giles</a> and <a href=\"http://www.youtube.com/watch?v=_2VXUQwGHZg\" rel=\"nofollow noreferrer\">this one</a> that gain mindshare</li>\n</ul>\n\n<p>I think your point is well-taken. As a friend once put it, Ruby might be \"old wine in a new bottle\" vis-a-vis Smalltalk. But sometimes the new bottle matters. A wine has to be in the right place at the right time.</p>\n" }, { "answer_id": 194232, "author": "Mario Aquino", "author_id": 23085, "author_profile": "https://Stackoverflow.com/users/23085", "pm_score": 6, "selected": false, "text": "<p>When I leave my house in the morning to go to work, I often struggle with the decision to make a left or right turn out of my drive way (I live in the middle of a street). Either way will get me to my destination. One way leads me to the highway which, depending on traffic, will probably get me to the office the quickest. I get to drive very fast for at least part of the way and I have a good chance of seeing a pretty girl or two on their way to work :-)</p>\n\n<p>The other way allows me to travel down a very enchanting, windy back road with complete tree cover. That path is quite enjoyable and of the two approaches is definitely the more fun, though it means that I will get to the office later than I would have had I taken the highway. Each way has its merits. On days that I am in a big hurry, I will usually take the highway though I may run into traffic and I also increase my chances of getting into an accident (if I am not careful in my haste). Other days I may choose the woody path and be driving along, enjoying the scenery and realize that I am running late. I may try to speed up, raising my chances of getting a ticket or causing an accident myself.</p>\n\n<p>Neither way is better than the other. They each have their benefits and risks, and each will get me to my goal.</p>\n" }, { "answer_id": 245936, "author": "Avdi", "author_id": 20487, "author_profile": "https://Stackoverflow.com/users/20487", "pm_score": 3, "selected": false, "text": "<p>I think everyone who has been working with Ruby for a while recognizes its deep debt to Smalltalk. As one of these people, what do I like about Ruby over Smalltalk? I think from a strictly language perspective, it's the sugar. Ruby is deliberately a very syntax-sugary language, whereas Smalltalk is a very syntax-minimal language. Ruby is essentially the Smalltalk object model with Perlish syntax sugar. I happen to like the sugar and find it makes programming more fun.</p>\n" }, { "answer_id": 266483, "author": "grettke", "author_id": 121526, "author_profile": "https://Stackoverflow.com/users/121526", "pm_score": 2, "selected": false, "text": "<p>Because Smalltalk distributions were priced in multiples of $1000USD whereas Ruby is free.</p>\n" }, { "answer_id": 347158, "author": "daduffer", "author_id": 43473, "author_profile": "https://Stackoverflow.com/users/43473", "pm_score": 2, "selected": false, "text": "<p>Use Ruby because it has might have business legs, Smalltalk doesn't.</p>\n\n<p>I can tell you from personal experience. Still using Smalltalk, love it, and have used a couple flavors. Although Smalltalk is a great language, and is everything you mentioned, you wont likely convince the average CIO/CTO to use Smalltalk on a new project. Of course, you might even have a hard time convincing a conservative CIO/CTO to use Ruby. In the end you have to be very careful if you want sustained long term commercial support and the ability to find off-the-street employees that can support your systems in the future. As an example, Smalltalk was a really big thing in the early 90's and IBM invested heavily into it in the late 90's. For IBM Smalltalk was going to be the next language for all business applications. IBM put Smalltalk on everything including their mainframe systems. Java became popular, took over the market, and Smalltalk became a niche player. Over a year ago IBM dumped the language (their term is sunset). Also, take a look at the History. ParkPlace and Digitalk where the first major commercial players in the Smalltalk arena, they merged and then went out of business.</p>\n" }, { "answer_id": 438986, "author": "Andy Dent", "author_id": 53870, "author_profile": "https://Stackoverflow.com/users/53870", "pm_score": 4, "selected": false, "text": "<p>Smalltalk:\npeople forwards ifTrue: [think] ifFalse: [not thinking]</p>\n\n<p>Ruby:\npeople think forwards unless thinking backwards</p>\n\n<p>1) Smalltalk's RPN-like control flow by messages is like Lisp - it's regular and cool but weirds people out.</p>\n\n<p>2) Ruby lets people write code using the idiomatic way people speak - do blah <em>unless</em> there's a reason not to.</p>\n\n<p><strong>update</strong> rewrote the Smalltalk sample to actually be more legal code..</p>\n" }, { "answer_id": 579235, "author": "sal", "author_id": 13753, "author_profile": "https://Stackoverflow.com/users/13753", "pm_score": 2, "selected": false, "text": "<p>Ruby is to Smalltalk as Arabic numerals are to Roman numerals. Same math, easier syntax.</p>\n" }, { "answer_id": 669143, "author": "Igor Stasenko", "author_id": 69325, "author_profile": "https://Stackoverflow.com/users/69325", "pm_score": 5, "selected": false, "text": "<p>I would say the opposite: Smalltalk syntax is one of the simplest and powerful programming language syntaxes.</p>\n" }, { "answer_id": 691720, "author": "Charlie Flowers", "author_id": 80112, "author_profile": "https://Stackoverflow.com/users/80112", "pm_score": 4, "selected": false, "text": "<p>Guess who said this? (quote is close, maybe not exact): \"I always thought Smalltalk would beat Java. I just didn't know if would be called 'Ruby' when it did so.\"</p>\n\n<p>Drum roll ....</p>\n\n<p>...</p>\n\n<p>The answer is ... Kent Beck</p>\n" }, { "answer_id": 814743, "author": "Stuart Ellis", "author_id": 96242, "author_profile": "https://Stackoverflow.com/users/96242", "pm_score": 0, "selected": false, "text": "<p>I would go further than Jonke's answer, and say there are now a large number of languages that have a very strong community, almost enough to suit every taste, and a subset of these have mainstream recognition (i.e. your manager will let you use them at work as well).</p>\n\n<p>It's easy to learn the basics of a language, but to actually use it effectively you need to invest enough time to learn the platform and the tools, as well as the syntax and the idioms. IIRC, McConnell claims that it takes about three years to become truly proficient.</p>\n\n<p>Given those things, it's hard to justify spending a lot of time on languages like LISP and Smalltalk, although they are interesting and perhaps educational to look at.</p>\n" }, { "answer_id": 869943, "author": "jmay", "author_id": 83249, "author_profile": "https://Stackoverflow.com/users/83249", "pm_score": 2, "selected": false, "text": "<p>Interesting perspective from Robert Martin (from RailsConf 2009): <a href=\"http://railsconf.blip.tv/file/2089545/\" rel=\"nofollow noreferrer\">\"What Killed Smalltalk Could Kill Ruby, Too\"</a></p>\n" }, { "answer_id": 948900, "author": "Mei", "author_id": 82775, "author_profile": "https://Stackoverflow.com/users/82775", "pm_score": 2, "selected": false, "text": "<p>I love both Smalltalk and Ruby - but have found that Ruby is more applicable to what I do daily, and is closer to my heart (practically speaking). What does Ruby offer that Smalltalk doesn't?</p>\n\n<ul>\n<li>Text-based scripting</li>\n<li>Low implementation requirements (runs in more places)</li>\n<li>Easier to learn and justify (Perl and Python programmers will have <em>no</em> trouble</li>\n<li>Easier to move programs around - text files!</li>\n<li>Interfaces well with native environment</li>\n<li>Anywhere Java runs, jRuby runs...</li>\n<li>Bigger and much more active community</li>\n</ul>\n\n<p>Some have mentioned gst (GNU Smalltalk); the problems still hold.</p>\n" }, { "answer_id": 1750752, "author": "Bob Jarvis - Слава Україні", "author_id": 213136, "author_profile": "https://Stackoverflow.com/users/213136", "pm_score": 4, "selected": false, "text": "<p>Beats me. I spent a year checking out Ruby and doing some smallish projects to see how I liked it. I guess I'm a Smalltalk bigot because every time I'd sit down to work with Ruby I'd sigh and think \"I'd really rather be doing this in Smalltalk\". Finally I gave in and went back to Smalltalk. Now I'm happier. Happier is gooder.</p>\n\n<p>Which of course begs the question, \"Why?\". In no particular order:</p>\n\n<ol>\n<li>Because the IDE blows away anything else I've ever worked with. This includes a bunch of platforms from ISPF on IBM mainframes to Microsoft's Visual (.*), include things such as Visual Basic 4-6, Visual C++ (various incarnations), Borland's Turbo Pascal and descendants (e.g. Delphi), and stuff on DEC machines in both character mode and under X-Windows.</li>\n<li>Because the image is a beautiful place to live. I can find what I want in there. If I can't figure out how to do something I know that <em>somewhere</em> in the image is an example of what I'm trying to do - all I have to do is hunt until I find it. And it's self-documenting - if you want to see the details of how something works you just open a browser on the class you're interested in, look at the method, and that's how it works. (OK, eventually you'll hit something that calls a primitive, and then it's \"here there be dragons\", but it's usually understandable from context). It's possible to do similar things in Ruby/C++/C, but it's not as easy. Easy is better.</li>\n<li>The language is minimal and consistent. Three kinds of messages - unary, binary, and keyword. That describes the priority of execution, too - unary messages first, then binary messages, then keyword messages. Use parentheses to help things out. Dang little syntax, really - it's all done with message sends. (OK, assignment isn't a message send, it's an operator. So's the 'return' operator (^). Blocks are enclosed by square brace pairs ([ ] ). Might be one or two other 'magic' bits in there, but darn little...).</li>\n<li>Blocks. Yeah, I know, they're there in Ruby (and others), but dang it, you literally can't program in Smalltalk without using them. You're <em>forced</em> to learn how to use them. Sometimes being forced is good.</li>\n<li>Object-oriented programming without compromise - or alternatives, for that matter. You can't pretend that you're \"doing objects\" while still doing the same old thing.</li>\n<li>Because it will stretch your brain. The comfortable constructs we've all gotten used to (if-then-else, do-while, for( ; ; ), etc) are no longer there so you have to Learn Something New. There are equivalents to all the above (and more), but you're going to have to learn to think differently. Differently is good.</li>\n</ol>\n\n<p>On the other hand this may just be the ramblings of a guy who's been programming since the days when mainframes ruled the earth, we had to walk five miles to work through blinding snowstorms, uphill both ways, and computers used donuts for memory. I've got nothing against Ruby/Java/C/C++/, they're all useful in context, but give me Smalltalk or give me...well, maybe I should learn Lisp or Scheme or... :-)</p>\n" }, { "answer_id": 1837004, "author": "Dafydd Rees", "author_id": 96168, "author_profile": "https://Stackoverflow.com/users/96168", "pm_score": 3, "selected": false, "text": "<p><strong>You can find a job pretty easily doing Ruby.</strong> Although I really love Smalltalk, it's virtually impossible to get into the Smalltalk niche. There is work around in it, but if you didn't get in when it was popular it's virtually impossible now.</p>\n\n<p>All the other reasons pale into insignificance because you need to spend plenty of time, focused on real work to learn a language properly. If you're not independently wealthy, the best way to do that is exposure to it at work.</p>\n" }, { "answer_id": 2481002, "author": "vfclists", "author_id": 172406, "author_profile": "https://Stackoverflow.com/users/172406", "pm_score": 0, "selected": false, "text": "<p>As a latecomer to discussion, the main problem with Smalltalk and Lisp is that you can't run them with CGI or FastCGI on shared hosting.</p>\n\n<p>The unwashed masses are never going to use them if they need VPS or dedicated servers to use them. IMHO Seaside is superior to almost anything out ther, but will it run on Dreamhost or Webfaction?</p>\n" }, { "answer_id": 4004492, "author": "Sebastian Sastre", "author_id": 485081, "author_profile": "https://Stackoverflow.com/users/485081", "pm_score": 2, "selected": false, "text": "<p>Use whatever makes you more powerful and faster to beat your challenge.</p>\n\n<p>For <a href=\"http://flowingconcept.com\" rel=\"nofollow\">us</a>, a little in house framework, we built in top of seaside is really our superpower.</p>\n\n<p>I love the RoR community, it has the right attitude. That's very very valuable. But at the same time, technologically, seaside makes you stronger against more complicated problems.</p>\n\n<p>You can do great seaside web apps using open-source stuff.</p>\n\n<p>dabbledb was a sartup based on seaside and, hey! Avi sold it to twitter in june this year!</p>\n\n<p>I say you don't need to wait for others to approve your initiative.</p>\n\n<p>Just go for it. Make it done. Show us that works.</p>\n\n<p>You're not alone. We are on the same boat.</p>\n" }, { "answer_id": 4410948, "author": "Sean DeNigris", "author_id": 424245, "author_profile": "https://Stackoverflow.com/users/424245", "pm_score": 3, "selected": false, "text": "<p>Ruby (or any other language) is more popular than Smalltalk (or any other language) because we live in a chaotic universe. To wit:</p>\n\n<ul>\n<li>From Dave Thomas himself, \"[after\nthe] video on 'How to Build a Blog in\nTen Minutes'... Ruby went from being\na nice little niche language, to\nbeing 'a language you wrote Rails\napps in'\" (<a href=\"http://confreaks.net/videos/368-rubyconf2010-keynote\" rel=\"nofollow noreferrer\">Ruby Conference 2010\nkeynote</a>).</li>\n<li>Early Smalltalk vendors charged prohibitively</li>\n<li>Smalltalk, because it was invented (ahead of its time) 30 years ago, occurs to many as an old, \"dead\" language (like FORTRAN)</li>\n<li>corporations consider Smalltalk such a competitive advantage that <a href=\"https://stackoverflow.com/questions/3633293/are-there-any-commercial-projects-using-squeak-smalltalk-that-are-not-web-based/4405172#4405172\">they hide its use</a></li>\n</ul>\n\n<p>While the languages are similar in OO features, Smalltalk's <em>killer</em> advantage is the live, open environment (the much-misunderstood 'image'). After you check out <a href=\"http://www.pharocasts.com/2010/02/programming-with-live-objects.html\" rel=\"nofollow noreferrer\">this example of programming in Smalltalk</a>, the debate is over.</p>\n" } ]
2008/10/09
[ "https://Stackoverflow.com/questions/187380", "https://Stackoverflow.com", "https://Stackoverflow.com/users/23899/" ]
Ruby is becoming [popular](http://www.tiobe.com/index.php/content/paperinfo/tpci/index.html), largely from the influence Ruby on Rails, but it feels like it is currently struggling through its adolescence. There are a lot of similarities between Ruby and Smalltalk -- [maglev](http://ruby.gemstone.com/) is a testament to that. Despite having a more unusual syntax, Smalltalk has all (if not more) of the object-oriented beauty of Ruby. From what I have read, Smalltalk seems to have Ruby beat on: * Maturity (developed in the 1970's) * Stability * Commercial support * [Distributed source control](http://www.wiresong.ca/monticello/) (understands structure of code, not just text diffing) * Several [implementations of the VM](http://en.wikipedia.org/wiki/Smalltalk#List_of_implementations) * Cross-platform support * The [seaside web framework](http://www.seaside.st/) as a [strong alternative to Rails](http://www.sauria.com/blog/2005/11/10) It seems like Ruby is just reinventing the wheel. So, why don't Ruby developers use SmallTalk? **What does Ruby have the Smalltalk doesn't?** *For the record: I'm a Ruby guy with little to no experience in Smalltalk, but I'm starting to wonder why.* --- **Edit:** I think the ease-of-scripting issue has been addressed by [GNU Smalltalk](http://en.wikipedia.org/wiki/GNU_Smalltalk). As I understand it, this allows you to write smalltalk in regular old text files, and you no longer need to be in the Smalltalk IDE. You can then [run your scripts](http://www.gnu.org/software/smalltalk/manual/html_node/Invocation.html#Invocation) with: ``` gst smalltalk_file ```
I'm more of a Pythonista than a Ruby user, however the same things hold for Ruby for much the same reasons. * The architecture of Smalltalk is somewhat insular whereas Python and Ruby were built from the ground up to facilitate integration. Smalltalk never really gained a body of hybrid application support in the way that Python and Ruby have, so the concept of 'smalltalk as embedded scripting language' never caught on. As an aside, Java was not the easiest thing to interface with other code bases (JNI is fairly clumsy), but that did not stop it from gaining mindshare. IMO the interfacing argument is significant - ease of embedding hasn't hurt Python - but this argument only holds moderate weight as not all applications require this capability. Also, later versions of Smalltalk did substantially address the insularity. * The class library of most of the main smalltalk implementations (VisualWorks, VisualAge etc.) was large and had reputation for a fairly steep learning curve. Most key functionality in Smalltalk is hidden away somewhere in the class library, even basic stuff like streams and collections. The language paradigm is also something of a culture shock for someone not familiar with it, and the piecemeal view of the program presented by the browser is quite different to what most people were used to. The overall effect is that Smalltalk got a (somewhat deserved) reputation for being difficult to learn; it takes quite a bit of time and effort to become a really proficient Smalltalk programmer. Ruby and Python are much easier to learn and to bring new programmers up to speed with. * Historically, mainstream Smalltalk implementations were quite expensive and needed exotic hardware to run, as can be seen [this net.lang.st80 posting from 1983](http://groups.google.co.uk/group/net.lang.st80/browse_thread/thread/c35c4ad7fad659c4?hl=en#). Windows 3.1, NT and '95 and OS/2 were the first mass market operating systems on mainstream hardware capable of supporting a Smalltalk implementation with decent native system integration. Previously, Mac or workstation hardware were the cheapest platforms capable of running Smalltalk effectively. Some implementations (particularly Digitalk) supported PC operating systems quite well and did succeed in gaining some traction. However, OS/2 was never that successful and Windows did not achieve mainstream acceptance until the mid 1990s. Unfortunately this coincided with the rise of the Web as a platform and a large marketing push behind Java. Java grabbed most of the mindshare in the latter part of the 1990s, rendering Smalltalk a bit of an also-ran. * Ruby and Python work in a more conventional toolchain and are not tightly coupled to a specific development environment. While the Smalltalk IDEs I have used are nice enough I use PythonWin for Python development largely because it has a nice editor with syntax highlighting and doesn't get underfoot. However, Smalltalk is was designed to be used with an IDE (in fact, Smalltalk was the original graphical IDE) and still has some nice features not replicated by other systems. Testing code with highlight and 'Show it' is still a very nice feature that I have never seen in a Python IDE, although I can't speak for Ruby. * Smalltalk was somewhat late coming to the web application party. Early efforts such as VisualWave were never terribly successful and it was not until Seaside came out that a decent web framework got acceptance in Smalltalk circles. In the meantime Java EE has had a complete acceptance lifecycle starting with raving fanboys promoting it and finally getting bored and moving onto Ruby ;-} Ironically, Seaside is starting to get a bit of mindshare among the cognoscenti so we may find that Smalltalk rides that cycle back into popularity. Having said that, Smalltalk is a very nice system once you've worked out how to drive it.
187,406
<pre><code>private string? typeOfContract { get { return (string?)ViewState["typeOfContract"]; } set { ViewState["typeOfContract"] = value; } } </code></pre> <p>Later in the code I use it like this:</p> <pre><code>typeOfContract = Request.QueryString["type"]; </code></pre> <p>I am getting the following error at the declaration of <code>typeOfContract</code> line stating:</p> <blockquote> <p>The type 'string' must be a non-nullable value type in order to use it as parameter 'T' in the generic type or method 'System.Nullable&lt;T>'</p> </blockquote> <p>Any ideas? Basically, I want to make sure that <code>"type"</code> exists in the <code>QueryString</code> before performing an action.</p>
[ { "answer_id": 187416, "author": "Joe", "author_id": 13087, "author_profile": "https://Stackoverflow.com/users/13087", "pm_score": 9, "selected": true, "text": "<p>System.String is a reference type and already \"nullable\".</p>\n\n<p>Nullable&lt;T> and the ? suffix are for value types such as Int32, Double, DateTime, etc.</p>\n" }, { "answer_id": 187419, "author": "jop", "author_id": 11830, "author_profile": "https://Stackoverflow.com/users/11830", "pm_score": 5, "selected": false, "text": "<p>You are making it complicated. <code>string</code> is already nullable. You don't need to make it <strong>more</strong> nullable. Take out the <code>?</code> on the property type.</p>\n" }, { "answer_id": 187430, "author": "Szymon Rozga", "author_id": 7583, "author_profile": "https://Stackoverflow.com/users/7583", "pm_score": 4, "selected": false, "text": "<p>string cannot be the parameter to Nullable because string is not a value type. String is a reference type. </p>\n\n<pre><code>string s = null; \n</code></pre>\n\n<p>is a very valid statement and there is not need to make it nullable.</p>\n\n<pre><code>private string typeOfContract\n {\n get { return ViewState[\"typeOfContract\"] as string; }\n set { ViewState[\"typeOfContract\"] = value; }\n }\n</code></pre>\n\n<p>should work because of the <strong>as</strong> keyword.</p>\n" }, { "answer_id": 187431, "author": "csgero", "author_id": 21764, "author_profile": "https://Stackoverflow.com/users/21764", "pm_score": 4, "selected": false, "text": "<p>String is a reference type, so you don't need to (and cannot) use <code>Nullable&lt;T&gt;</code> here. Just declare typeOfContract as string and simply check for null after getting it from the query string. Or use String.IsNullOrEmpty if you want to handle empty string values the same as null.</p>\n" }, { "answer_id": 10620020, "author": "James Oravec", "author_id": 1190934, "author_profile": "https://Stackoverflow.com/users/1190934", "pm_score": 2, "selected": false, "text": "<p>For nullable, use <code>?</code> with all of the <strong>C# primitives</strong>, except for string.</p>\n\n<p>The following page gives a list of the <strong>C# primitives</strong>:\n<a href=\"http://msdn.microsoft.com/en-us/library/aa711900(v=vs.71).aspx\" rel=\"nofollow\">http://msdn.microsoft.com/en-us/library/aa711900(v=vs.71).aspx</a></p>\n" } ]
2008/10/09
[ "https://Stackoverflow.com/questions/187406", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4144/" ]
``` private string? typeOfContract { get { return (string?)ViewState["typeOfContract"]; } set { ViewState["typeOfContract"] = value; } } ``` Later in the code I use it like this: ``` typeOfContract = Request.QueryString["type"]; ``` I am getting the following error at the declaration of `typeOfContract` line stating: > > The type 'string' must be a non-nullable value type in order to use > it as parameter 'T' in the generic type or method > 'System.Nullable<T>' > > > Any ideas? Basically, I want to make sure that `"type"` exists in the `QueryString` before performing an action.
System.String is a reference type and already "nullable". Nullable<T> and the ? suffix are for value types such as Int32, Double, DateTime, etc.
187,414
<p>I don't really <em>get</em> lambda expressions. While they've been around since the days of ALGOL, I didn't start hearing about them until fairly recently, when Python and Ruby became very popular. Now that C# has the <code>=&gt;</code> syntax, people in my world (.NET) are talking about lamdba expressions more and more.</p> <p>I've read the Wikipedia article on the lambda calculus, but I'm not really a math guy. I don't really understand it from a practical perspective. When would I use lambda expressions? Why? How would I know that it's what I should be doing?</p> <p>Can you show examples of how you would solve problems with lambda expressions, in a before-and-after format? Any imperative language is fine, but C# would be easiest for me to understand.</p>
[ { "answer_id": 187423, "author": "Chris Young", "author_id": 9417, "author_profile": "https://Stackoverflow.com/users/9417", "pm_score": 2, "selected": false, "text": "<p>The answers to <a href=\"https://stackoverflow.com/questions/150129/what-is-a-lambda\">this question</a> might be useful to you.</p>\n" }, { "answer_id": 187432, "author": "Jon Skeet", "author_id": 22656, "author_profile": "https://Stackoverflow.com/users/22656", "pm_score": 6, "selected": true, "text": "<p>Basically as far as C# is concerned, lambda expressions are an easy way to create a delegate (or an expression tree, but let's leave those aside for now).</p>\n\n<p>In C# 1 we could only create delegate instances from normal methods.\nIn C# 2 we gained anonymous methods.\nIn C# 3 we gained lambda expressions, which are like more concise anonymous methods.</p>\n\n<p>They're particularly concise when you want to express some logic which takes one value and returns a value. For instance, in the context of LINQ:</p>\n\n<pre><code> // Only include children - a predicate\nvar query = dataSource.Where(person =&gt; person.Age &lt; 18) \n // Transform to sequence of names - a projection\n .Select(person =&gt; person.Name);\n</code></pre>\n\n<p>There's a fuller discussion of this - along with other aspects - in <a href=\"http://csharpindepth.com/Articles/Chapter5/Closures.aspx\" rel=\"noreferrer\">my article on closures</a>.</p>\n" }, { "answer_id": 187436, "author": "Jimmeh", "author_id": 20749, "author_profile": "https://Stackoverflow.com/users/20749", "pm_score": 0, "selected": false, "text": "<p>My main use of lambda expressions in .NET has been when working with lists. Using a lambda expression you can build up a query on a list in a similar way as you would build an SQL statement to search a database table.</p>\n" }, { "answer_id": 187442, "author": "Tetha", "author_id": 17663, "author_profile": "https://Stackoverflow.com/users/17663", "pm_score": 2, "selected": false, "text": "<p>lambda functions are just anonymous functions.</p>\n\n<p>For example, in python, you want to double all elements in a list. There are pretty much three ways to do so:</p>\n\n<p>List-expressions: </p>\n\n<pre><code>[2*x for x in list]\n</code></pre>\n\n<p>explicit function:</p>\n\n<pre><code>def double(x):\n return 2*x\nmap(double, list) # iirc\n</code></pre>\n\n<p>with lambdas:</p>\n\n<pre><code>double = lambda x : 2*x\nmap(double, list)\n</code></pre>\n\n<p>So, a lambda in most languages is just a way to avoid the syntactic overhead of creating a new function. </p>\n" }, { "answer_id": 187445, "author": "orlando calresian", "author_id": 21165, "author_profile": "https://Stackoverflow.com/users/21165", "pm_score": 1, "selected": false, "text": "<p>This is one of the better explanations I've seen of how to understand the big ideas in using lambda expressions in C#: </p>\n\n<p><a href=\"http://www.developingfor.net/c-30/upgrade-your-c-skills-part-3-lambda-expressions.html\" rel=\"nofollow noreferrer\">http://www.developingfor.net/c-30/upgrade-your-c-skills-part-3-lambda-expressions.html</a></p>\n" }, { "answer_id": 187470, "author": "Jonas", "author_id": 24946, "author_profile": "https://Stackoverflow.com/users/24946", "pm_score": 0, "selected": false, "text": "<p>A lambda expression is a functional value (in the same sense that 'int' and 'string' are values). This means that it is possible to</p>\n\n<ul>\n<li>define a variable that holds a lambda expression (this is the same as defining a function)</li>\n<li>return a lambda expression from a method or function</li>\n<li>send a lambda expression as an argument to a function or method</li>\n</ul>\n\n<p>Take a look at functions like map, filter or fold (in any functional language) to see how lambda expressions are used as arguments to other functions.</p>\n" } ]
2008/10/09
[ "https://Stackoverflow.com/questions/187414", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7565/" ]
I don't really *get* lambda expressions. While they've been around since the days of ALGOL, I didn't start hearing about them until fairly recently, when Python and Ruby became very popular. Now that C# has the `=>` syntax, people in my world (.NET) are talking about lamdba expressions more and more. I've read the Wikipedia article on the lambda calculus, but I'm not really a math guy. I don't really understand it from a practical perspective. When would I use lambda expressions? Why? How would I know that it's what I should be doing? Can you show examples of how you would solve problems with lambda expressions, in a before-and-after format? Any imperative language is fine, but C# would be easiest for me to understand.
Basically as far as C# is concerned, lambda expressions are an easy way to create a delegate (or an expression tree, but let's leave those aside for now). In C# 1 we could only create delegate instances from normal methods. In C# 2 we gained anonymous methods. In C# 3 we gained lambda expressions, which are like more concise anonymous methods. They're particularly concise when you want to express some logic which takes one value and returns a value. For instance, in the context of LINQ: ``` // Only include children - a predicate var query = dataSource.Where(person => person.Age < 18) // Transform to sequence of names - a projection .Select(person => person.Name); ``` There's a fuller discussion of this - along with other aspects - in [my article on closures](http://csharpindepth.com/Articles/Chapter5/Closures.aspx).
187,438
<p>I have currently an installed pgsql instance that is running on port <code>1486</code>. I want to change this port to <code>5433</code>, how should I proceed for this?</p>
[ { "answer_id": 187457, "author": "Neall", "author_id": 619, "author_profile": "https://Stackoverflow.com/users/619", "pm_score": 9, "selected": true, "text": "<p>There should be a line in your <code>postgresql.conf</code> file that says:</p>\n\n<pre><code>port = 1486\n</code></pre>\n\n<p>Change that.</p>\n\n<p>The location of the file can vary depending on your install options. On Debian-based distros it is <code>/etc/postgresql/8.3/main/</code></p>\n\n<p>On Windows it is <code>C:\\Program Files\\PostgreSQL\\9.3\\data</code></p>\n\n<p>Don't forget to <code>sudo service postgresql restart</code> for changes to take effect.</p>\n" }, { "answer_id": 2530381, "author": "Frank Heikens", "author_id": 271959, "author_profile": "https://Stackoverflow.com/users/271959", "pm_score": 5, "selected": false, "text": "<p>You can also change the port when starting up:</p>\n\n<pre><code>$ pg_ctl -o \"-F -p 5433\" start\n</code></pre>\n\n<p>Or</p>\n\n<pre><code>$ postgres -p 5433\n</code></pre>\n\n<p>More about this in the <a href=\"http://www.postgresql.org/docs/8.4/interactive/reference-server.html\" rel=\"noreferrer\">manual</a>.</p>\n" } ]
2008/10/09
[ "https://Stackoverflow.com/questions/187438", "https://Stackoverflow.com", "https://Stackoverflow.com/users/22554/" ]
I have currently an installed pgsql instance that is running on port `1486`. I want to change this port to `5433`, how should I proceed for this?
There should be a line in your `postgresql.conf` file that says: ``` port = 1486 ``` Change that. The location of the file can vary depending on your install options. On Debian-based distros it is `/etc/postgresql/8.3/main/` On Windows it is `C:\Program Files\PostgreSQL\9.3\data` Don't forget to `sudo service postgresql restart` for changes to take effect.
187,448
<p>Using OpenXML SDK, I want to insert basic HTML snippets into a Word document.</p> <p>How would you do this:</p> <ul> <li>Manipulating XML directly ?</li> <li>Using an XSLT ?</li> <li>using AltChunk ?</li> </ul> <p>Moreover, C# or VB examples are more than welcome :)</p>
[ { "answer_id": 196887, "author": "Gaspar Nagy", "author_id": 26530, "author_profile": "https://Stackoverflow.com/users/26530", "pm_score": 2, "selected": false, "text": "<p>I'm not sure, what you actually would like to achieve. The OpenXML documents have an own html-like (WordprocessingML) notation for the formatting elements (like paragraph, bold text, etc.). If you would like to add some text to a doc, with basic formatting, than I rather suggest to use the OpenXML syntax and format the inserted text with that.</p>\n\n<p>If you have a html snippet, that you must include into the doc as it is, you can use the \"external content\" feature of OpenXML. With external content, you can include the HTML document to the package, and create a reference (altChunk) in the doc in the position, where you want to include this. The disadvantage of this solution, that not all tools will support (or support properly) the generated document, therefore I don't recommend this solution, unless you really cannot change the HTML source.</p>\n\n<p>How to include any content (the wordml) to a openxml word doc is an independent question IMHO, and the answer depends very much on how complex modifications you want to apply, and how big the document is. For a simple document, I would simply read out the document part from the package, obtain it's stream and load it to an XmlDocument. You can insert additional content to the XmlDocument quite easily, and then save it back to the package. If the document is big, or you need complex modifications in multiple places, XSLT is a good option.</p>\n" }, { "answer_id": 317064, "author": "Dirk Vollmar", "author_id": 40347, "author_profile": "https://Stackoverflow.com/users/40347", "pm_score": 3, "selected": false, "text": "<p>Well, hard to give general advice, because it depends strongly on your input what is best. </p>\n\n<p>Here's a simple example inserting a paragraph into a DOCX document for each paragraph in an (X)HTML document using OpenXML SDK v2.0 and an XPathDocument:</p>\n\n<pre><code> void ConvertHTML(string htmlFileName, string docFileName)\n {\n // Create a Wordprocessing document. \n using (WordprocessingDocument package = WordprocessingDocument.Create(docFileName, WordprocessingDocumentType.Document))\n {\n // Add a new main document part. \n package.AddMainDocumentPart();\n\n // Create the Document DOM. \n package.MainDocumentPart.Document = new Document(new Body());\n Body body = package.MainDocumentPart.Document.Body;\n\n XPathDocument htmlDoc = new XPathDocument(htmlFileName);\n\n XPathNavigator navigator = htmlDoc.CreateNavigator();\n XmlNamespaceManager mngr = new XmlNamespaceManager(navigator.NameTable);\n mngr.AddNamespace(\"xhtml\", \"http://www.w3.org/1999/xhtml\");\n\n XPathNodeIterator ni = navigator.Select(\"//xhtml:p\", mngr);\n while (ni.MoveNext())\n {\n body.AppendChild&lt;Paragraph&gt;(new Paragraph(new Run(new Text(ni.Current.Value))));\n }\n\n // Save changes to the main document part. \n package.MainDocumentPart.Document.Save();\n }\n }\n</code></pre>\n\n<p>The example requires your input to be valid XML, otherwise you will get an exception when creating the XPathDocument. </p>\n\n<p>Please note that this is a very basic example not taking any formatting, headings, lists etc into account.</p>\n" }, { "answer_id": 5252121, "author": "Riko", "author_id": 160801, "author_profile": "https://Stackoverflow.com/users/160801", "pm_score": 3, "selected": false, "text": "<p>Here is another (relatively new) alternative</p>\n\n<p><a href=\"http://notesforhtml2openxml.codeplex.com/\" rel=\"noreferrer\">http://notesforhtml2openxml.codeplex.com/</a></p>\n" } ]
2008/10/09
[ "https://Stackoverflow.com/questions/187448", "https://Stackoverflow.com", "https://Stackoverflow.com/users/22970/" ]
Using OpenXML SDK, I want to insert basic HTML snippets into a Word document. How would you do this: * Manipulating XML directly ? * Using an XSLT ? * using AltChunk ? Moreover, C# or VB examples are more than welcome :)
Well, hard to give general advice, because it depends strongly on your input what is best. Here's a simple example inserting a paragraph into a DOCX document for each paragraph in an (X)HTML document using OpenXML SDK v2.0 and an XPathDocument: ``` void ConvertHTML(string htmlFileName, string docFileName) { // Create a Wordprocessing document. using (WordprocessingDocument package = WordprocessingDocument.Create(docFileName, WordprocessingDocumentType.Document)) { // Add a new main document part. package.AddMainDocumentPart(); // Create the Document DOM. package.MainDocumentPart.Document = new Document(new Body()); Body body = package.MainDocumentPart.Document.Body; XPathDocument htmlDoc = new XPathDocument(htmlFileName); XPathNavigator navigator = htmlDoc.CreateNavigator(); XmlNamespaceManager mngr = new XmlNamespaceManager(navigator.NameTable); mngr.AddNamespace("xhtml", "http://www.w3.org/1999/xhtml"); XPathNodeIterator ni = navigator.Select("//xhtml:p", mngr); while (ni.MoveNext()) { body.AppendChild<Paragraph>(new Paragraph(new Run(new Text(ni.Current.Value)))); } // Save changes to the main document part. package.MainDocumentPart.Document.Save(); } } ``` The example requires your input to be valid XML, otherwise you will get an exception when creating the XPathDocument. Please note that this is a very basic example not taking any formatting, headings, lists etc into account.
187,454
<p>I have the following problem using subversion:</p> <p>I'm currently working on the trunk of my project and plan to do some refactoring (which includes renaming files or moving files to different directories).</p> <p>At the same time someone else is working on the same project on a branch.</p> <p>At some time I want to merge the changes made on the branch back to the trunk. That includes changes made to files (on the branch) that have been renamed on the trunk.</p> <p>I did some tests and it seems that either subversion is not capable of following these changes or I'm missing someting (which is what I hope for). I tested this using the following script (should work in bash, assumes an svn repository at "<a href="http://myserver/svn/sandbox" rel="noreferrer">http://myserver/svn/sandbox</a>"):</p> <pre><code>svn co http://myserver/svn/sandbox cd sandbox/ mkdir -p MyProject/trunk MyProject/branches MyProject/tags cat - &lt;&lt;EOF &gt;MyProject/trunk/FileOne.txt Test 1 2 EOF svn add MyProject svn commit -m "init" # create a branch svn copy http://myserver/svn/sandbox/MyProject/trunk http://myserver/svn/sandbox/MyProject/branches/Branch_1 svn copy http://myserver/svn/sandbox/MyProject/trunk http://myserver/svn/sandbox/MyProject/branches/Branch_1 # rename the file svn move MyProject/trunk/FileOne.txt MyProject/trunk/FileTwo.txt svn commit -m "renamed file" svn update # change the content of FileOne in branch cat - &lt;&lt;EOF &gt;MyProject/branches/Branch_1/FileOne.txt Test 2 3 EOF svn commit -m "changed branch" # I now try to merge the changes in FileOne back to FileTwo cd MyProject/trunk/ svn merge -r1:HEAD http://myserver/svn/sandbox/MyProject/branches/Branch_1 # but this yields the following message: # Skipped missing target: 'FileOne.txt' </code></pre> <p>Any help is greatly appreciated.</p> <p>Edit: Perhaps the process suggested by mikegrb could by somewhat automated by first generating a map of renamed files (old->new) from the svn log command on the trunk:</p> <pre><code>svn log -v ------------------------------------------------------------------------ r33 | sme | 2008-10-09 15:17:54 +0200 (Do, 09 Okt 2008) | 1 line Changed paths: D /MyProject/trunk/FileOne.txt A /MyProject/trunk/FileTwo.txt (from /MyProject/trunk/FileOne.txt:31) resulting map: {FileOne.txt =&gt; FileTwo.txt} </code></pre> <p>Now use this map to change filenames in the patch file generated on the branch. </p> <p>Original:</p> <pre><code>Index: FileOne.txt =================================================================== --- FileOne.txt (.../trunk) (revision 31) +++ FileOne.txt (.../branches/Branch_1) (revision 34) @@ -1,3 +1,3 @@ Test -1 2 +3 </code></pre> <p>modified:</p> <pre><code>Index: FileTwo.txt =================================================================== --- FileTwo.txt (.../trunk) (revision 31) +++ FileTwo.txt (.../branches/Branch_1) (revision 34) @@ -1,3 +1,3 @@ Test -1 2 +3 </code></pre> <p>Just an Idea, haven't done it yet.</p>
[ { "answer_id": 187472, "author": "mspmsp", "author_id": 21724, "author_profile": "https://Stackoverflow.com/users/21724", "pm_score": 1, "selected": false, "text": "<p>It's likely that you'll have to rename them in the branch. Can you merge the revision that renamed them from the trunk to branch? That might save some time. Otherwise, you'll have to rename them in the branch. Then try the merge back to the trunk.</p>\n" }, { "answer_id": 187478, "author": "mikegrb", "author_id": 13462, "author_profile": "https://Stackoverflow.com/users/13462", "pm_score": 4, "selected": false, "text": "<p>Unfortunately, this is one of the limitations of subversion. When we recently had a similar situation to deal with our solution was to create one giant diff for the branch and then go through it file by file manually patching trunk. Files that have been renamed and are not found will cause patch to prompt for the file name to patch. Very sub optimal. Watch out for binary files which won't show in the diff. This was one of the big factors that prompted us to evaluate other version control systems and ultimately decide to transition to git.</p>\n" }, { "answer_id": 187485, "author": "Chris Kimpton", "author_id": 48310, "author_profile": "https://Stackoverflow.com/users/48310", "pm_score": 6, "selected": true, "text": "<p>I think this is an existing subversion <a href=\"http://subversion.tigris.org/issues/show_bug.cgi?id=898\" rel=\"noreferrer\">bug</a> - but don't hold your breath, its been open since 2002.</p>\n" }, { "answer_id": 12075884, "author": "angularsen", "author_id": 134761, "author_profile": "https://Stackoverflow.com/users/134761", "pm_score": 1, "selected": false, "text": "<p>A workaround is to sync the branch with the trunk before syncing the trunk with the branch. </p>\n\n<p>The difference is that trunk to branch has a file to apply changes (move) to, while branch to trunk does not have a file to apply changes (modify) to. This is simply because SVN does not seem to track where files are moved/renamed. I don't know why it doesn't, hopefully there is a good reason for it.</p>\n\n<p>Example:</p>\n\n<ul>\n<li>rev 1: /trunk/foo.txt moved to /trunk/folder/foo.txt</li>\n<li>rev 2: /branches/mybranch/foo.txt is modified</li>\n</ul>\n\n<p>How to merge foo.txt changes into trunk?</p>\n\n<p>Solution:</p>\n\n<ol>\n<li>Merge all revisions from trunk to mybranch and commit. This will cause foo.txt to move.</li>\n<li>Merge all revisions from mybranch to trunk. This will update the contents of foo.txt, since they now have the same path.</li>\n</ol>\n\n<p>Note: If you have moved/renamed different files on both trunk and mybranch, then you are in for a ride. I guess you will have to selectively merge in the changes so that you do moves/renames first in both directions, then merge changes.</p>\n" } ]
2008/10/09
[ "https://Stackoverflow.com/questions/187454", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4497/" ]
I have the following problem using subversion: I'm currently working on the trunk of my project and plan to do some refactoring (which includes renaming files or moving files to different directories). At the same time someone else is working on the same project on a branch. At some time I want to merge the changes made on the branch back to the trunk. That includes changes made to files (on the branch) that have been renamed on the trunk. I did some tests and it seems that either subversion is not capable of following these changes or I'm missing someting (which is what I hope for). I tested this using the following script (should work in bash, assumes an svn repository at "<http://myserver/svn/sandbox>"): ``` svn co http://myserver/svn/sandbox cd sandbox/ mkdir -p MyProject/trunk MyProject/branches MyProject/tags cat - <<EOF >MyProject/trunk/FileOne.txt Test 1 2 EOF svn add MyProject svn commit -m "init" # create a branch svn copy http://myserver/svn/sandbox/MyProject/trunk http://myserver/svn/sandbox/MyProject/branches/Branch_1 svn copy http://myserver/svn/sandbox/MyProject/trunk http://myserver/svn/sandbox/MyProject/branches/Branch_1 # rename the file svn move MyProject/trunk/FileOne.txt MyProject/trunk/FileTwo.txt svn commit -m "renamed file" svn update # change the content of FileOne in branch cat - <<EOF >MyProject/branches/Branch_1/FileOne.txt Test 2 3 EOF svn commit -m "changed branch" # I now try to merge the changes in FileOne back to FileTwo cd MyProject/trunk/ svn merge -r1:HEAD http://myserver/svn/sandbox/MyProject/branches/Branch_1 # but this yields the following message: # Skipped missing target: 'FileOne.txt' ``` Any help is greatly appreciated. Edit: Perhaps the process suggested by mikegrb could by somewhat automated by first generating a map of renamed files (old->new) from the svn log command on the trunk: ``` svn log -v ------------------------------------------------------------------------ r33 | sme | 2008-10-09 15:17:54 +0200 (Do, 09 Okt 2008) | 1 line Changed paths: D /MyProject/trunk/FileOne.txt A /MyProject/trunk/FileTwo.txt (from /MyProject/trunk/FileOne.txt:31) resulting map: {FileOne.txt => FileTwo.txt} ``` Now use this map to change filenames in the patch file generated on the branch. Original: ``` Index: FileOne.txt =================================================================== --- FileOne.txt (.../trunk) (revision 31) +++ FileOne.txt (.../branches/Branch_1) (revision 34) @@ -1,3 +1,3 @@ Test -1 2 +3 ``` modified: ``` Index: FileTwo.txt =================================================================== --- FileTwo.txt (.../trunk) (revision 31) +++ FileTwo.txt (.../branches/Branch_1) (revision 34) @@ -1,3 +1,3 @@ Test -1 2 +3 ``` Just an Idea, haven't done it yet.
I think this is an existing subversion [bug](http://subversion.tigris.org/issues/show_bug.cgi?id=898) - but don't hold your breath, its been open since 2002.
187,455
<p>How can I count the number of elements in an array, because contrary to logic array.count(string) does not count all the elements in the array, it just searches for the number of occurrences of string.</p>
[ { "answer_id": 187463, "author": "Trent", "author_id": 9083, "author_profile": "https://Stackoverflow.com/users/9083", "pm_score": 9, "selected": true, "text": "<p>The method len() returns the number of elements in the list.</p>\n\n<p>Syntax:</p>\n\n<pre><code>len(myArray)\n</code></pre>\n\n<p>Eg:</p>\n\n<pre><code>myArray = [1, 2, 3]\nlen(myArray)\n</code></pre>\n\n<p>Output:</p>\n\n<pre><code>3\n</code></pre>\n\n<p></p>\n" }, { "answer_id": 187493, "author": "Kevin Little", "author_id": 14028, "author_profile": "https://Stackoverflow.com/users/14028", "pm_score": 2, "selected": false, "text": "<p>Or,</p>\n\n<pre><code>myArray.__len__()\n</code></pre>\n\n<p>if you want to be oopy; \"len(myArray)\" is a lot easier to type! :)</p>\n" }, { "answer_id": 188867, "author": "Jeremy Brown", "author_id": 21776, "author_profile": "https://Stackoverflow.com/users/21776", "pm_score": 5, "selected": false, "text": "<p><code>len</code> is a built-in function that calls the given container object's <code>__len__</code> member function to get the number of elements in the object. </p>\n\n<p>Functions encased with double underscores are usually \"special methods\" implementing one of the standard interfaces in Python (container, number, etc). Special methods are used via syntactic sugar (object creation, container indexing and slicing, attribute access, built-in functions, etc.).</p>\n\n<p>Using <code>obj.__len__()</code> wouldn't be the correct way of using the special method, but I don't see why the others were modded down so much.</p>\n" }, { "answer_id": 31467803, "author": "Evan Young", "author_id": 4946606, "author_profile": "https://Stackoverflow.com/users/4946606", "pm_score": 2, "selected": false, "text": "<p>Before I saw this, I thought to myself, \"I need to make a way to do this!\"</p>\n\n<pre><code>for tempVar in arrayName: tempVar+=1\n</code></pre>\n\n<p>And then I thought, \"There must be a simpler way to do this.\" and I was right.</p>\n\n<p><code>len(arrayName)</code></p>\n" }, { "answer_id": 31937513, "author": "user2993689", "author_id": 2993689, "author_profile": "https://Stackoverflow.com/users/2993689", "pm_score": 4, "selected": false, "text": "<p>If you have a multi-dimensional array, len() might not give you the value you are looking for. For instance:</p>\n\n<pre class=\"lang-py prettyprint-override\"><code>import numpy as np\na = np.arange(10).reshape(2, 5)\nprint len(a) == 2\n</code></pre>\n\n<p>This code block will return true, telling you the size of the array is 2. However, there are in fact 10 elements in this 2D array. In the case of multi-dimensional arrays, len() gives you the length of the <em>first</em> dimension of the array i.e. </p>\n\n<pre class=\"lang-py prettyprint-override\"><code>import numpy as np\nlen(a) == np.shape(a)[0]\n</code></pre>\n\n<p>To get the number of elements in a multi-dimensional array of arbitrary shape:</p>\n\n<pre class=\"lang-py prettyprint-override\"><code>import numpy as np\nsize = 1\nfor dim in np.shape(a): size *= dim\n</code></pre>\n" } ]
2008/10/09
[ "https://Stackoverflow.com/questions/187455", "https://Stackoverflow.com", "https://Stackoverflow.com/users/115/" ]
How can I count the number of elements in an array, because contrary to logic array.count(string) does not count all the elements in the array, it just searches for the number of occurrences of string.
The method len() returns the number of elements in the list. Syntax: ``` len(myArray) ``` Eg: ``` myArray = [1, 2, 3] len(myArray) ``` Output: ``` 3 ```
187,482
<p>I'd like to use the newer <code>&lt;button&gt;</code> tag in an ASP.NET website which, among other things, allows CSS-styled text and embedding a graphic inside the button. The asp:Button control renders as <code>&lt;input type="button"&gt;</code>, is there any way to make a preexisting control render to <code>&lt;button&gt;</code>?</p> <p>From what I've read there is an incompatibility with IE posting the button's markup instead of the value attribute when the button is located within a <code>&lt;form&gt;</code>, but in ASP.NET it will be using the onclick event to fire __doPostBack anyway, so I don't think that this would be a problem.</p> <p>Are there any reasons why I shouldn't use this? If not, how would you go about supporting it with asp:Button, or a new server control based on it? I would prefer to not write my own server control if that can be avoided.</p> <hr> <p>At first the <code>&lt;button runat="server"&gt;</code> solution worked, but I immediately ran into a situation where it needs to have a CommandName property, which the HtmlButton control doesn't have. It looks like I'm going to need to create a control inherited from Button after all. </p> <p>What do I need to do in order to override the render method and make it render what I want?</p> <hr> <p><strong>UPDATE</strong></p> <p>DanHerbert's reply has made me interested in finding a solution to this again, so I've spent some more time working on it. </p> <p>First, there's a far easier way of overloading the TagName:</p> <pre><code>public ModernButton() : base(HtmlTextWriterTag.Button) { } </code></pre> <p>The problem with Dan's solution as it stands is the innerhtml of the tag is placed into the value property, which causes a validation error on postback. A related problem is, even if you render the value property correctly, IE's braindead implementation of the <code>&lt;button&gt;</code> tag posts the innerhtml instead of the value anyway. So, any implementation of this needs to override the AddAttributesToRender method in order to correctly render the value property, and also provide some sort of workaround for IE so it doesn't completely screw up the postback.</p> <p>The IE problem may be insurmountable if you want to take advantage of the CommandName/CommandArgument properties for a databound control. Hopefully someone can suggest a workaround for this.</p> <p>I have made progress on the rendering:</p> <p><a href="http://gist.github.com/69841" rel="noreferrer">ModernButton.cs</a></p> <p>This renders as a proper html <code>&lt;button&gt;</code> with the correct value, but it doesn't work with the ASP.Net PostBack system. I've written some of what I need to provide the <code>Command</code> event, but it doesn't fire.</p> <p>When inspecting this button side-by-side with a regular asp:Button, they look the same other than the differences I need. So I'm not sure how ASP.Net is wiring up the <code>Command</code> event in this case.</p> <p>An additional problem is, nested server controls aren't rendered (as you can see with the ParseChildren(false) attribute). It's pretty easy to inject literal html text into the control during render, but how do you allow support for nested server controls?</p>
[ { "answer_id": 187527, "author": "Tsvetomir Tsonev", "author_id": 25449, "author_profile": "https://Stackoverflow.com/users/25449", "pm_score": 2, "selected": false, "text": "<p>I would go with a LinkButton and style it with CSS as appropriate.</p>\n" }, { "answer_id": 187566, "author": "Steven Robbins", "author_id": 26507, "author_profile": "https://Stackoverflow.com/users/26507", "pm_score": 3, "selected": false, "text": "<p>You could make a new control, inheriting from Button, and override the render method, or use a .browser file to override all Buttons in the site, similar to the way the CSS Friendly stuff works for the TreeView control etc.</p>\n" }, { "answer_id": 187944, "author": "Wayne", "author_id": 8236, "author_profile": "https://Stackoverflow.com/users/8236", "pm_score": 3, "selected": false, "text": "<p>You can use the <a href=\"http://msdn.microsoft.com/en-us/library/system.web.ui.webcontrols.button.usesubmitbehavior.aspx\" rel=\"noreferrer\">Button.UseSubmitBehavior</a> property as discussed in <a href=\"http://www.xerratus.com/2006/11/22/HowToGetASPNET20ButtonWebControlToRenderAsInputTypebutton.aspx\" rel=\"noreferrer\">this article about rendering an ASP.NET Button control as a button</a>.\n<hr>\nEDIT: Sorry.. that's what I get for skimming questions on my lunch break. Are there reasons why you wouldn't just use a &lt;button runat=\"server\"&gt; tag or an <a href=\"http://msdn.microsoft.com/en-us/library/a8fd2268(VS.80).aspx\" rel=\"noreferrer\">HtmlButton</a>? </p>\n" }, { "answer_id": 573990, "author": "Dan Herbert", "author_id": 392, "author_profile": "https://Stackoverflow.com/users/392", "pm_score": 5, "selected": false, "text": "<p>I stumbled upon your question looking for the same exact thing. I ended up using <a href=\"http://www.red-gate.com/products/reflector/\" rel=\"noreferrer\">Reflector</a> to figure out how the ASP.NET <code>Button</code> control is actually rendered. It turns out to be really easy to change.</p>\n\n<p>It really just comes down to overriding the <code>TagName</code> and <code>TagKey</code> properties of the <code>Button</code> class. After you've done that, you just need to make sure you render the contents of the button manually since the original <code>Button</code> class never had contents to render and the control will render a text-less button if you don't render the contents.</p>\n\n<p><strong>Update:</strong> </p>\n\n<p>It's possible to make a few small modifications to the Button control through inheritance and still work fairly well. This solution eliminates the need to implement your own event handlers for OnCommand (although if you want to learn how to do that I can show you how that is handled). It also fixes the issue of submitting a value that has markup in it, except for IE probably. I'm still not sure how to fix IE's poor implementation of the Button tag though. That may just be a truly technical limitation that is impossible to work around...</p>\n\n<pre><code>[ParseChildren(false)]\n[PersistChildren(true)]\npublic class ModernButton : Button\n{\n protected override string TagName\n {\n get { return \"button\"; }\n }\n\n protected override HtmlTextWriterTag TagKey\n {\n get { return HtmlTextWriterTag.Button; }\n }\n\n // Create a new implementation of the Text property which\n // will be ignored by the parent class, giving us the freedom\n // to use this property as we please.\n public new string Text\n {\n get { return ViewState[\"NewText\"] as string; }\n set { ViewState[\"NewText\"] = HttpUtility.HtmlDecode(value); }\n }\n\n protected override void OnPreRender(System.EventArgs e)\n {\n base.OnPreRender(e);\n // I wasn't sure what the best way to handle 'Text' would\n // be. Text is treated as another control which gets added\n // to the end of the button's control collection in this \n //implementation\n LiteralControl lc = new LiteralControl(this.Text);\n Controls.Add(lc);\n\n // Add a value for base.Text for the parent class\n // If the following line is omitted, the 'value' \n // attribute will be blank upon rendering\n base.Text = UniqueID;\n }\n\n protected override void RenderContents(HtmlTextWriter writer)\n {\n RenderChildren(writer);\n }\n}\n</code></pre>\n\n<p>To use this control, you have a few options. One is to place controls directly into the ASP markup. </p>\n\n<pre><code>&lt;uc:ModernButton runat=\"server\" \n ID=\"btnLogin\" \n OnClick=\"btnLogin_Click\" \n Text=\"Purplemonkeydishwasher\"&gt;\n &lt;img src=\"../someUrl/img.gif\" alt=\"img\" /&gt;\n &lt;asp:Label ID=\"Label1\" runat=\"server\" Text=\"Login\" /&gt;\n&lt;/uc:ModernButton&gt;\n</code></pre>\n\n<p>You can also add the controls to the control collection of the button in your code-behind.</p>\n\n<pre><code>// This code probably won't work too well \"as is\"\n// since there is nothing being defined about these\n// controls, but you get the idea.\nbtnLogin.Controls.Add(new Label());\nbtnLogin.Controls.Add(new Table());\n</code></pre>\n\n<p>I don't know how well a combination of both options works as I haven't tested that.</p>\n\n<p>The only downside to this control right now is that I don't think it will remember your controls across PostBacks. I haven't tested this so it may already work, but I doubt it does. You'll need to add some ViewState management code for sub-controls to be handled across PostBacks I think, however this probably isn't an issue for you. Adding ViewState support shouldn't be terribly hard to do, although if needed that can easily be added.</p>\n" }, { "answer_id": 975539, "author": "David Andersson", "author_id": 120521, "author_profile": "https://Stackoverflow.com/users/120521", "pm_score": 1, "selected": false, "text": "<p>I've been struggling all day with this -- my custom <code>&lt;button/&gt;</code> generated control not working:</p>\n\n<blockquote>\n <p>System.Web.HttpRequestValidationException: A potentially dangerous Request.Form value was detected from the client</p>\n</blockquote>\n\n<p>What happens is that .Net adds a <code>name</code> attribute:</p>\n\n<pre><code>&lt;button type=\"submit\" name=\"ctl02\" value=\"Content\" class=\"btn \"&gt;\n &lt;span&gt;Content&lt;/span&gt;\n&lt;/button&gt;\n</code></pre>\n\n<p>The <code>name</code> attribute throws the server error when using IE 6 and IE 7. Everything works fine in other browsers (Opera, IE 8, Firefox, Safari).</p>\n\n<p>The cure is to hack away that <code>name</code> attribute. Still I haven't figured that out.</p>\n" }, { "answer_id": 1171539, "author": "Philippe", "author_id": 27219, "author_profile": "https://Stackoverflow.com/users/27219", "pm_score": 5, "selected": false, "text": "<p>Although you say that using the [button runat=\"server\"] is not a good enough solution it is important to mention it - a lot of .NET programmers are afraid of using the \"native\" HTML tags...</p>\n\n<p>Use:</p>\n\n<pre><code>&lt;button id=\"btnSubmit\" runat=\"server\" class=\"myButton\" \n onserverclick=\"btnSubmit_Click\"&gt;Hello&lt;/button&gt;\n</code></pre>\n\n<p>This usually works perfectly fine and everybody is happy in my team.</p>\n" }, { "answer_id": 31879094, "author": "Daniel Liuzzi", "author_id": 88709, "author_profile": "https://Stackoverflow.com/users/88709", "pm_score": 6, "selected": true, "text": "<p>This is an old question, but for those of us unlucky enough still having to maintain ASP.NET Web Forms applications, I went through this myself while trying to include Bootstrap glyphs inside of built-in button controls.</p>\n\n<p>As per Bootstrap documentation, the desired markup is as follows:</p>\n\n<pre class=\"lang-html prettyprint-override\"><code>&lt;button class=\"btn btn-default\"&gt;\n &lt;span class=\"glyphicon glyphicon-search\" aria-hidden=\"true\"&gt;&lt;/span&gt;\n Search\n&lt;/button&gt;\n</code></pre>\n\n<p>I needed this markup to be rendered by a server control, so I set out to find options.</p>\n\n<h1>Button</h1>\n\n<p>This would be the first logical step, but —as this question explains— Button renders an <code>&lt;input&gt;</code> element instead of <code>&lt;button&gt;</code>, so adding inner HTML is not possible.</p>\n\n<h1>LinkButton (credit to <a href=\"https://stackoverflow.com/a/187527\">Tsvetomir Tsonev's answer</a>)</h1>\n\n<p><strong>Source</strong></p>\n\n<pre class=\"lang-html prettyprint-override\"><code>&lt;asp:LinkButton runat=\"server\" ID=\"uxSearch\" CssClass=\"btn btn-default\"&gt;\n &lt;span class=\"glyphicon glyphicon-search\" aria-hidden=\"true\"&gt;&lt;/span&gt;\n Search\n&lt;/asp:LinkButton&gt;\n</code></pre>\n\n<p><strong>Output</strong></p>\n\n<pre class=\"lang-html prettyprint-override\"><code>&lt;a id=\"uxSearch\" class=\"btn btn-default\" href=\"javascript:__doPostBack(&amp;#39;uxSearch&amp;#39;,&amp;#39;&amp;#39;)\"&gt;\n &lt;span class=\"glyphicon glyphicon-search\" aria-hidden=\"true\"&gt;&lt;/span&gt;\n Search\n&lt;/a&gt;\n</code></pre>\n\n<p><strong>Pros</strong></p>\n\n<ul>\n<li>Looks OK</li>\n<li><code>Command</code> event; <code>CommandName</code> and <code>CommandArgument</code> properties</li>\n</ul>\n\n<p><strong>Cons</strong></p>\n\n<ul>\n<li>Renders <code>&lt;a&gt;</code> instead of <code>&lt;button&gt;</code></li>\n<li>Renders and relies on obtrusive JavaScript</li>\n</ul>\n\n<h1>HtmlButton (credit to <a href=\"https://stackoverflow.com/a/1171539\">Philippe's answer</a>)</h1>\n\n<p><strong>Source</strong></p>\n\n<pre class=\"lang-html prettyprint-override\"><code>&lt;button runat=\"server\" id=\"uxSearch\" class=\"btn btn-default\"&gt;\n &lt;span class=\"glyphicon glyphicon-search\" aria-hidden=\"true\"&gt;&lt;/span&gt;\n Search\n&lt;/button&gt;\n</code></pre>\n\n<p><strong>Result</strong></p>\n\n<pre class=\"lang-html prettyprint-override\"><code>&lt;button onclick=\"__doPostBack('uxSearch','')\" id=\"uxSearch\" class=\"btn btn-default\"&gt;\n &lt;span class=\"glyphicon glyphicon-search\" aria-hidden=\"true\"&gt;&lt;/span&gt;\n Search\n&lt;/button&gt;\n</code></pre>\n\n<p><strong>Pros</strong></p>\n\n<ul>\n<li>Looks OK</li>\n<li>Renders proper <code>&lt;button&gt;</code> element</li>\n</ul>\n\n<p><strong>Cons</strong></p>\n\n<ul>\n<li>No <code>Command</code> event; no <code>CommandName</code> or <code>CommandArgument</code> properties</li>\n<li>Renders and relies on obtrusive JavaScript to handle its <code>ServerClick</code> event</li>\n</ul>\n\n<hr>\n\n<p>At this point it is clear that none of the built-in controls seem suitable, so the next logical step is try and modify them to achieve the desired functionality.</p>\n\n<h1>Custom control (credit to <a href=\"https://stackoverflow.com/a/573990\">Dan Herbert's answer</a>)</h1>\n\n<p><strong>NOTE: This is based on Dan's code, so all credit goes to him.</strong></p>\n\n<pre class=\"lang-cs prettyprint-override\"><code>using System.Web.UI;\nusing System.Web.UI.WebControls;\n\nnamespace ModernControls\n{\n [ParseChildren]\n public class ModernButton : Button\n {\n public new string Text\n {\n get { return (string)ViewState[\"NewText\"] ?? \"\"; }\n set { ViewState[\"NewText\"] = value; }\n }\n\n public string Value\n {\n get { return base.Text; }\n set { base.Text = value; }\n }\n\n protected override HtmlTextWriterTag TagKey\n {\n get { return HtmlTextWriterTag.Button; }\n }\n\n protected override void AddParsedSubObject(object obj)\n {\n var literal = obj as LiteralControl;\n if (literal == null) return;\n Text = literal.Text;\n }\n\n protected override void RenderContents(HtmlTextWriter writer)\n {\n writer.Write(Text);\n }\n }\n}\n</code></pre>\n\n<p>I have stripped the class down to the bare minimum, and refactored it to achieve the same functionality with as little code as possible. I also added a couple of improvements. Namely:</p>\n\n<ul>\n<li>Remove <code>PersistChildren</code> attribute (seems unnecessary)</li>\n<li>Remove <code>TagName</code> override (seems unnecessary)</li>\n<li>Remove HTML decoding from <code>Text</code> (base class already handles this)</li>\n<li>Leave <code>OnPreRender</code> intact; override <code>AddParsedSubObject</code> instead (simpler)</li>\n<li>Simplify <code>RenderContents</code> override</li>\n<li>Add a <code>Value</code> property (see below)</li>\n<li>Add a namespace (to include a sample of <strong>@ Register</strong> directive)</li>\n<li>Add necessary <code>using</code> directives</li>\n</ul>\n\n<p>The <code>Value</code> property simply accesses the old <code>Text</code> property. This is because the native Button control renders a <code>value</code> attribute anyway (with <code>Text</code> as its value). Since <code>value</code> is a valid attribute of the <code>&lt;button&gt;</code> element, I decided to include a property for it.</p>\n\n<p><strong>Source</strong></p>\n\n<pre class=\"lang-html prettyprint-override\"><code>&lt;%@ Register TagPrefix=\"mc\" Namespace=\"ModernControls\" %&gt;\n\n&lt;mc:ModernButton runat=\"server\" ID=\"uxSearch\" Value=\"Foo\" CssClass=\"btn btn-default\" &gt;\n &lt;span class=\"glyphicon glyphicon-search\" aria-hidden=\"true\"&gt;&lt;/span&gt;\n Search\n&lt;/mc:ModernButton&gt;\n</code></pre>\n\n<p><strong>Output</strong></p>\n\n<pre class=\"lang-html prettyprint-override\"><code>&lt;button type=\"submit\" name=\"uxSearch\" value=\"Foo\" id=\"uxSearch\" class=\"btn btn-default\"&gt;\n &lt;span class=\"glyphicon glyphicon-search\" aria-hidden=\"true\"&gt;&lt;/span&gt;\n Search\n&lt;/button&gt;\n</code></pre>\n\n<p><strong>Pros</strong></p>\n\n<ul>\n<li>Looks OK</li>\n<li>Renders a proper <code>&lt;button&gt;</code> element</li>\n<li><code>Command</code> event; <code>CommandName</code> and <code>CommandArgument</code> properties</li>\n<li>Does not render or rely on obtrusive JavaScript</li>\n</ul>\n\n<p><strong>Cons</strong></p>\n\n<ul>\n<li>None (other than not being a built-in control)</li>\n</ul>\n" } ]
2008/10/09
[ "https://Stackoverflow.com/questions/187482", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1249/" ]
I'd like to use the newer `<button>` tag in an ASP.NET website which, among other things, allows CSS-styled text and embedding a graphic inside the button. The asp:Button control renders as `<input type="button">`, is there any way to make a preexisting control render to `<button>`? From what I've read there is an incompatibility with IE posting the button's markup instead of the value attribute when the button is located within a `<form>`, but in ASP.NET it will be using the onclick event to fire \_\_doPostBack anyway, so I don't think that this would be a problem. Are there any reasons why I shouldn't use this? If not, how would you go about supporting it with asp:Button, or a new server control based on it? I would prefer to not write my own server control if that can be avoided. --- At first the `<button runat="server">` solution worked, but I immediately ran into a situation where it needs to have a CommandName property, which the HtmlButton control doesn't have. It looks like I'm going to need to create a control inherited from Button after all. What do I need to do in order to override the render method and make it render what I want? --- **UPDATE** DanHerbert's reply has made me interested in finding a solution to this again, so I've spent some more time working on it. First, there's a far easier way of overloading the TagName: ``` public ModernButton() : base(HtmlTextWriterTag.Button) { } ``` The problem with Dan's solution as it stands is the innerhtml of the tag is placed into the value property, which causes a validation error on postback. A related problem is, even if you render the value property correctly, IE's braindead implementation of the `<button>` tag posts the innerhtml instead of the value anyway. So, any implementation of this needs to override the AddAttributesToRender method in order to correctly render the value property, and also provide some sort of workaround for IE so it doesn't completely screw up the postback. The IE problem may be insurmountable if you want to take advantage of the CommandName/CommandArgument properties for a databound control. Hopefully someone can suggest a workaround for this. I have made progress on the rendering: [ModernButton.cs](http://gist.github.com/69841) This renders as a proper html `<button>` with the correct value, but it doesn't work with the ASP.Net PostBack system. I've written some of what I need to provide the `Command` event, but it doesn't fire. When inspecting this button side-by-side with a regular asp:Button, they look the same other than the differences I need. So I'm not sure how ASP.Net is wiring up the `Command` event in this case. An additional problem is, nested server controls aren't rendered (as you can see with the ParseChildren(false) attribute). It's pretty easy to inject literal html text into the control during render, but how do you allow support for nested server controls?
This is an old question, but for those of us unlucky enough still having to maintain ASP.NET Web Forms applications, I went through this myself while trying to include Bootstrap glyphs inside of built-in button controls. As per Bootstrap documentation, the desired markup is as follows: ```html <button class="btn btn-default"> <span class="glyphicon glyphicon-search" aria-hidden="true"></span> Search </button> ``` I needed this markup to be rendered by a server control, so I set out to find options. Button ====== This would be the first logical step, but —as this question explains— Button renders an `<input>` element instead of `<button>`, so adding inner HTML is not possible. LinkButton (credit to [Tsvetomir Tsonev's answer](https://stackoverflow.com/a/187527)) ====================================================================================== **Source** ```html <asp:LinkButton runat="server" ID="uxSearch" CssClass="btn btn-default"> <span class="glyphicon glyphicon-search" aria-hidden="true"></span> Search </asp:LinkButton> ``` **Output** ```html <a id="uxSearch" class="btn btn-default" href="javascript:__doPostBack(&#39;uxSearch&#39;,&#39;&#39;)"> <span class="glyphicon glyphicon-search" aria-hidden="true"></span> Search </a> ``` **Pros** * Looks OK * `Command` event; `CommandName` and `CommandArgument` properties **Cons** * Renders `<a>` instead of `<button>` * Renders and relies on obtrusive JavaScript HtmlButton (credit to [Philippe's answer](https://stackoverflow.com/a/1171539)) =============================================================================== **Source** ```html <button runat="server" id="uxSearch" class="btn btn-default"> <span class="glyphicon glyphicon-search" aria-hidden="true"></span> Search </button> ``` **Result** ```html <button onclick="__doPostBack('uxSearch','')" id="uxSearch" class="btn btn-default"> <span class="glyphicon glyphicon-search" aria-hidden="true"></span> Search </button> ``` **Pros** * Looks OK * Renders proper `<button>` element **Cons** * No `Command` event; no `CommandName` or `CommandArgument` properties * Renders and relies on obtrusive JavaScript to handle its `ServerClick` event --- At this point it is clear that none of the built-in controls seem suitable, so the next logical step is try and modify them to achieve the desired functionality. Custom control (credit to [Dan Herbert's answer](https://stackoverflow.com/a/573990)) ===================================================================================== **NOTE: This is based on Dan's code, so all credit goes to him.** ```cs using System.Web.UI; using System.Web.UI.WebControls; namespace ModernControls { [ParseChildren] public class ModernButton : Button { public new string Text { get { return (string)ViewState["NewText"] ?? ""; } set { ViewState["NewText"] = value; } } public string Value { get { return base.Text; } set { base.Text = value; } } protected override HtmlTextWriterTag TagKey { get { return HtmlTextWriterTag.Button; } } protected override void AddParsedSubObject(object obj) { var literal = obj as LiteralControl; if (literal == null) return; Text = literal.Text; } protected override void RenderContents(HtmlTextWriter writer) { writer.Write(Text); } } } ``` I have stripped the class down to the bare minimum, and refactored it to achieve the same functionality with as little code as possible. I also added a couple of improvements. Namely: * Remove `PersistChildren` attribute (seems unnecessary) * Remove `TagName` override (seems unnecessary) * Remove HTML decoding from `Text` (base class already handles this) * Leave `OnPreRender` intact; override `AddParsedSubObject` instead (simpler) * Simplify `RenderContents` override * Add a `Value` property (see below) * Add a namespace (to include a sample of **@ Register** directive) * Add necessary `using` directives The `Value` property simply accesses the old `Text` property. This is because the native Button control renders a `value` attribute anyway (with `Text` as its value). Since `value` is a valid attribute of the `<button>` element, I decided to include a property for it. **Source** ```html <%@ Register TagPrefix="mc" Namespace="ModernControls" %> <mc:ModernButton runat="server" ID="uxSearch" Value="Foo" CssClass="btn btn-default" > <span class="glyphicon glyphicon-search" aria-hidden="true"></span> Search </mc:ModernButton> ``` **Output** ```html <button type="submit" name="uxSearch" value="Foo" id="uxSearch" class="btn btn-default"> <span class="glyphicon glyphicon-search" aria-hidden="true"></span> Search </button> ``` **Pros** * Looks OK * Renders a proper `<button>` element * `Command` event; `CommandName` and `CommandArgument` properties * Does not render or rely on obtrusive JavaScript **Cons** * None (other than not being a built-in control)
187,495
<p>In my program, how can I read the properties set in AssemblyInfo.cs:</p> <pre><code>[assembly: AssemblyTitle("My Product")] [assembly: AssemblyDescription("...")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("Radeldudel inc.")] [assembly: AssemblyProduct("My Product")] [assembly: AssemblyCopyright("Copyright @ me 2008")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] </code></pre> <p>I'd like to display some of these values to the user of my program, so I'd like to know how to load them from the main program and from komponent assemblies I'm using.</p>
[ { "answer_id": 187529, "author": "Jeff Yates", "author_id": 23234, "author_profile": "https://Stackoverflow.com/users/23234", "pm_score": 7, "selected": true, "text": "<p>This is reasonably easy. You have to use reflection. You need an instance of Assembly that represents the assembly with the attributes you want to read. An easy way of getting this is to do:</p>\n\n<pre><code>typeof(MyTypeInAssembly).Assembly\n</code></pre>\n\n<p>Then you can do this, for example:</p>\n\n<pre><code>object[] attributes = assembly.GetCustomAttributes(typeof(AssemblyProductAttribute), false);\n\nAssemblyProductAttribute attribute = null;\nif (attributes.Length &gt; 0)\n{\n attribute = attributes[0] as AssemblyProductAttribute;\n}\n</code></pre>\n\n<p>Referencing <code>attribute.Product</code> will now give you the value you passed to the attribute in your AssemblyInfo.cs. Of course, if the attribute you look for can occur more than once, you may get multiple instances in the array returned by GetCustomAttributes, but this is not usually an issue for assembly level attributes like the ones you hope to retrieve.</p>\n" }, { "answer_id": 874889, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 3, "selected": false, "text": "<p>Ok, perhaps a bit out of date now for the original question but I will present this for future reference anyway.</p>\n\n<p>If you want to do it from inside the assembly itself then use the following :</p>\n\n<pre><code>using System.Runtime.InteropServices;\nusing System.Reflection;\n\nobject[] customAttributes = this.GetType().Assembly.GetCustomAttributes(false);\n</code></pre>\n\n<p>You can then iterate through all of the custom attributes to find the one(s) you require e.g.</p>\n\n<pre><code>foreach (object attribute in customAttributes)\n{\n string assemblyGuid = string.Empty; \n\n if (attribute.GetType() == typeof(GuidAttribute))\n {\n assemblyGuid = ((GuidAttribute) attribute).Value;\n break;\n }\n}\n</code></pre>\n" }, { "answer_id": 20077072, "author": "dmihailescu", "author_id": 376495, "author_profile": "https://Stackoverflow.com/users/376495", "pm_score": 4, "selected": false, "text": "<p>I've created this extension method that uses Linq:</p>\n\n<pre><code>public static T GetAssemblyAttribute&lt;T&gt;(this System.Reflection.Assembly ass) where T : Attribute\n{\n object[] attributes = ass.GetCustomAttributes(typeof(T), false);\n if (attributes == null || attributes.Length == 0)\n return null;\n return attributes.OfType&lt;T&gt;().SingleOrDefault();\n}\n</code></pre>\n\n<p>and then you can conveniently use it like that:</p>\n\n<pre><code>var attr = targetAssembly.GetAssemblyAttribute&lt;AssemblyDescriptionAttribute&gt;();\nif(attr != null)\n Console.WriteLine(\"{0} Assembly Description:{1}\", Environment.NewLine, attr.Description);\n</code></pre>\n" }, { "answer_id": 28447667, "author": "Kavindu Dodanduwa", "author_id": 3197055, "author_profile": "https://Stackoverflow.com/users/3197055", "pm_score": 3, "selected": false, "text": "<p>Okay, I'm tried to go through many resources to find a method to extract .dll attributes for a <code>Assembly.LoadFrom(path)</code> . But unfortunately I couldn't find any good resource. And this question was the top most result for searching on <code>c# get assembly attributes</code> (For me at least) So I thought of sharing my work.</p>\n\n<p>I wrote following simple Console Program to retrieve general assembly attributes after many hours of struggle. Here I have provided the code so anyone can use it for further reference work. </p>\n\n<p>I use <code>CustomAttributes</code> property for this. Feel free to comment on this approach</p>\n\n<p>Code :</p>\n\n<pre><code>using System;\nusing System.Reflection;\n\nnamespace MetaGetter\n{\n class Program\n {\n static void Main(string[] args)\n {\n Assembly assembly = Assembly.LoadFrom(\"Path to assembly\");\n\n foreach (CustomAttributeData attributedata in assembly.CustomAttributes)\n {\n Console.WriteLine(\" Name : {0}\",attributedata.AttributeType.Name);\n\n foreach (CustomAttributeTypedArgument argumentset in attributedata.ConstructorArguments)\n {\n Console.WriteLine(\" &gt;&gt; Value : {0} \\n\" ,argumentset.Value);\n }\n }\n\n Console.ReadKey();\n }\n }\n}\n</code></pre>\n\n<p>Sample Output :</p>\n\n<pre><code>Name : AssemblyTitleAttribute\n &gt;&gt; Value : \"My Product\"\n</code></pre>\n" }, { "answer_id": 40285188, "author": "Stefan Steiger", "author_id": 155077, "author_profile": "https://Stackoverflow.com/users/155077", "pm_score": 2, "selected": false, "text": "<p>I use this:</p>\n\n<pre><code>public static string Title\n{\n get\n {\n return GetCustomAttribute&lt;AssemblyTitleAttribute&gt;(a =&gt; a.Title);\n }\n}\n</code></pre>\n\n<p>for reference:</p>\n\n<pre><code>using System;\nusing System.Reflection;\nusing System.Runtime.CompilerServices;\n\n\n\nnamespace Extensions\n{\n\n\n public static class AssemblyInfo\n {\n\n\n private static Assembly m_assembly;\n\n static AssemblyInfo()\n {\n m_assembly = Assembly.GetEntryAssembly();\n }\n\n\n public static void Configure(Assembly ass)\n {\n m_assembly = ass;\n }\n\n\n public static T GetCustomAttribute&lt;T&gt;() where T : Attribute\n {\n object[] customAttributes = m_assembly.GetCustomAttributes(typeof(T), false);\n if (customAttributes.Length != 0)\n {\n return (T)((object)customAttributes[0]);\n }\n return default(T);\n }\n\n public static string GetCustomAttribute&lt;T&gt;(Func&lt;T, string&gt; getProperty) where T : Attribute\n {\n T customAttribute = GetCustomAttribute&lt;T&gt;();\n if (customAttribute != null)\n {\n return getProperty(customAttribute);\n }\n return null;\n }\n\n public static int GetCustomAttribute&lt;T&gt;(Func&lt;T, int&gt; getProperty) where T : Attribute\n {\n T customAttribute = GetCustomAttribute&lt;T&gt;();\n if (customAttribute != null)\n {\n return getProperty(customAttribute);\n }\n return 0;\n }\n\n\n\n public static Version Version\n {\n get\n {\n return m_assembly.GetName().Version;\n }\n }\n\n\n public static string Title\n {\n get\n {\n return GetCustomAttribute&lt;AssemblyTitleAttribute&gt;(\n delegate(AssemblyTitleAttribute a)\n {\n return a.Title;\n }\n );\n }\n }\n\n public static string Description\n {\n get\n {\n return GetCustomAttribute&lt;AssemblyDescriptionAttribute&gt;(\n delegate(AssemblyDescriptionAttribute a)\n {\n return a.Description;\n }\n );\n }\n }\n\n\n public static string Product\n {\n get\n {\n return GetCustomAttribute&lt;AssemblyProductAttribute&gt;(\n delegate(AssemblyProductAttribute a)\n {\n return a.Product;\n }\n );\n }\n }\n\n\n public static string Copyright\n {\n get\n {\n return GetCustomAttribute&lt;AssemblyCopyrightAttribute&gt;(\n delegate(AssemblyCopyrightAttribute a)\n {\n return a.Copyright;\n }\n );\n }\n }\n\n\n\n public static string Company\n {\n get\n {\n return GetCustomAttribute&lt;AssemblyCompanyAttribute&gt;(\n delegate(AssemblyCompanyAttribute a)\n {\n return a.Company;\n }\n );\n }\n }\n\n\n public static string InformationalVersion\n {\n get\n {\n return GetCustomAttribute&lt;AssemblyInformationalVersionAttribute&gt;(\n delegate(AssemblyInformationalVersionAttribute a)\n {\n return a.InformationalVersion;\n }\n );\n }\n }\n\n\n\n public static int ProductId\n {\n get\n {\n return GetCustomAttribute&lt;AssemblyProductIdAttribute&gt;(\n delegate(AssemblyProductIdAttribute a)\n {\n return a.ProductId;\n }\n );\n }\n }\n\n\n public static string Location\n {\n get\n {\n return m_assembly.Location;\n }\n }\n\n }\n\n}\n</code></pre>\n" }, { "answer_id": 50062061, "author": "Walter Verhoeven", "author_id": 8000382, "author_profile": "https://Stackoverflow.com/users/8000382", "pm_score": 3, "selected": false, "text": "<p>I personally really like the implementation of <a href=\"http://lancelarsen.com/reading-values-from-assemblyinfo-cs/\" rel=\"nofollow noreferrer\">lance Larsen and his static AssemblyInfo class</a>.</p>\n<p>One basically pastes the class in his assembly (I usually use the already existing AssemblyInfo.cs file as it fits naming convention)</p>\n<p>The code to paste is:</p>\n<pre><code>internal static class AssemblyInfo\n{\n public static string Company { get { return GetExecutingAssemblyAttribute&lt;AssemblyCompanyAttribute&gt;(a =&gt; a.Company); } }\n public static string Product { get { return GetExecutingAssemblyAttribute&lt;AssemblyProductAttribute&gt;(a =&gt; a.Product); } }\n public static string Copyright { get { return GetExecutingAssemblyAttribute&lt;AssemblyCopyrightAttribute&gt;(a =&gt; a.Copyright); } }\n public static string Trademark { get { return GetExecutingAssemblyAttribute&lt;AssemblyTrademarkAttribute&gt;(a =&gt; a.Trademark); } }\n public static string Title { get { return GetExecutingAssemblyAttribute&lt;AssemblyTitleAttribute&gt;(a =&gt; a.Title); } }\n public static string Description { get { return GetExecutingAssemblyAttribute&lt;AssemblyDescriptionAttribute&gt;(a =&gt; a.Description); } }\n public static string Configuration { get { return GetExecutingAssemblyAttribute&lt;AssemblyConfigurationAttribute&gt;(a =&gt; a.Configuration); } }\n public static string FileVersion { get { return GetExecutingAssemblyAttribute&lt;AssemblyFileVersionAttribute&gt;(a =&gt; a.Version); } }\n\n public static Version Version { get { return Assembly.GetExecutingAssembly().GetName().Version; } }\n public static string VersionFull { get { return Version.ToString(); } }\n public static string VersionMajor { get { return Version.Major.ToString(); } }\n public static string VersionMinor { get { return Version.Minor.ToString(); } }\n public static string VersionBuild { get { return Version.Build.ToString(); } }\n public static string VersionRevision { get { return Version.Revision.ToString(); } }\n\n private static string GetExecutingAssemblyAttribute&lt;T&gt;(Func&lt;T, string&gt; value) where T : Attribute\n {\n T attribute = (T)Attribute.GetCustomAttribute(Assembly.GetExecutingAssembly(), typeof(T));\n return value.Invoke(attribute);\n }\n}\n</code></pre>\n<p>You add a using System; to the top of the file and you're good to go.</p>\n<p>For my applications i use this class to set/get/work with my local users settings using:</p>\n<pre><code>internal class ApplicationData\n{\n\n DirectoryInfo roamingDataFolder;\n DirectoryInfo localDataFolder;\n DirectoryInfo appDataFolder;\n\n public ApplicationData()\n {\n appDataFolder = new DirectoryInfo(Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData), AssemblyInfo.Product,&quot;Data&quot;));\n roamingDataFolder = new DirectoryInfo(Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData),AssemblyInfo.Product));\n localDataFolder = new DirectoryInfo(Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData), AssemblyInfo.Product));\n\n if (!roamingDataFolder.Exists) \n roamingDataFolder.Create();\n\n if (!localDataFolder.Exists)\n localDataFolder.Create();\n if (!appDataFolder.Exists)\n appDataFolder.Create();\n\n }\n\n /// &lt;summary&gt;\n /// Gets the roaming application folder location.\n /// &lt;/summary&gt;\n /// &lt;value&gt;The roaming data directory.&lt;/value&gt;\n public DirectoryInfo RoamingDataFolder =&gt; roamingDataFolder;\n\n\n /// &lt;summary&gt;\n /// Gets the local application folder location.\n /// &lt;/summary&gt;\n /// &lt;value&gt;The local data directory.&lt;/value&gt;\n public DirectoryInfo LocalDataFolder =&gt; localDataFolder;\n\n /// &lt;summary&gt;\n /// Gets the local data folder location.\n /// &lt;/summary&gt;\n /// &lt;value&gt;The local data directory.&lt;/value&gt;\n public DirectoryInfo AppDataFolder =&gt; appDataFolder;\n}\n</code></pre>\n<p>Have a look at Larsens website (MVP), he has cool stuff to draw Inspiration from.</p>\n" }, { "answer_id": 54101934, "author": "glopes", "author_id": 628228, "author_profile": "https://Stackoverflow.com/users/628228", "pm_score": 2, "selected": false, "text": "<p>If you know the attribute you are looking for is unique, it is much easier to use this often overlooked static helper method of the <code>Attribute</code> class:</p>\n\n<pre class=\"lang-cs prettyprint-override\"><code>var attribute = Attribute.GetCustomAttribute(assembly, typeof(AssemblyTitleAttribute))\n</code></pre>\n\n<p>This is easier because you don't need to mess around with arrays, or worry about that pesky <code>inherit</code> parameter. You just get the single attribute value directly, or <code>null</code> if none exists.</p>\n" }, { "answer_id": 58189887, "author": "Randall Deetz", "author_id": 1096739, "author_profile": "https://Stackoverflow.com/users/1096739", "pm_score": 2, "selected": false, "text": "<p>This is a great way to retrieve specific attributes in a single line of code. No special class required.</p>\n\n<pre><code>string company = ((AssemblyCompanyAttribute)Attribute.GetCustomAttribute(Assembly.GetExecutingAssembly(), typeof(AssemblyCompanyAttribute), false)).Company;\n</code></pre>\n" } ]
2008/10/09
[ "https://Stackoverflow.com/questions/187495", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7021/" ]
In my program, how can I read the properties set in AssemblyInfo.cs: ``` [assembly: AssemblyTitle("My Product")] [assembly: AssemblyDescription("...")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("Radeldudel inc.")] [assembly: AssemblyProduct("My Product")] [assembly: AssemblyCopyright("Copyright @ me 2008")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] ``` I'd like to display some of these values to the user of my program, so I'd like to know how to load them from the main program and from komponent assemblies I'm using.
This is reasonably easy. You have to use reflection. You need an instance of Assembly that represents the assembly with the attributes you want to read. An easy way of getting this is to do: ``` typeof(MyTypeInAssembly).Assembly ``` Then you can do this, for example: ``` object[] attributes = assembly.GetCustomAttributes(typeof(AssemblyProductAttribute), false); AssemblyProductAttribute attribute = null; if (attributes.Length > 0) { attribute = attributes[0] as AssemblyProductAttribute; } ``` Referencing `attribute.Product` will now give you the value you passed to the attribute in your AssemblyInfo.cs. Of course, if the attribute you look for can occur more than once, you may get multiple instances in the array returned by GetCustomAttributes, but this is not usually an issue for assembly level attributes like the ones you hope to retrieve.
187,505
<p>I have few different applications among which I'd like to share a C# enum. I can't quite figure out how to share an enum declaration between a regular application and a WCF service. </p> <p>Here's the situation. I have 2 lightweight C# destop apps and a WCF webservice that all need to share enum values. </p> <p>Client 1 has </p> <pre><code> Method1( MyEnum e, string sUserId ); </code></pre> <p>Client 2 has </p> <pre><code>Method2( MyEnum e, string sUserId ); </code></pre> <p>Webservice has </p> <pre><code>ServiceMethod1( MyEnum e, string sUserId, string sSomeData); </code></pre> <p>My initial though was to create a library called Common.dll to encapsulate the enum and then just reference that library in all of the projects where the enum is needed. However, WCF makes things difficult because you need to markup the enum for it to be an integral part of the service. Like this: </p> <pre><code>[ServiceContract] [ServiceKnownType(typeof(MyEnum))] public interface IMyService { [OperationContract] ServiceMethod1( MyEnum e, string sUserId, string sSomeData); } [DataContract] public enum MyEnum{ [EnumMember] red, [EnumMember] green, [EnumMember] blue }; </code></pre> <p>So .... Is there a way to share an enum among a WCF service and other applictions? </p>
[ { "answer_id": 187845, "author": "Szymon Rozga", "author_id": 7583, "author_profile": "https://Stackoverflow.com/users/7583", "pm_score": 7, "selected": true, "text": "<p>Using the Common library should be fine. Enumerations are serializable and the DataContract attributes are not needed. </p>\n\n<p>See:\n<a href=\"http://msdn.microsoft.com/en-us/library/ms731923.aspx\" rel=\"noreferrer\">http://msdn.microsoft.com/en-us/library/ms731923.aspx</a></p>\n\n<blockquote>\n <p>Enumeration types. Enumerations, including flag enumerations, are\n serializable. Optionally, enumeration types can be marked with the\n DataContractAttribute attribute, in which case every member that\n participates in serialization must be marked with the\n EnumMemberAttribute attribute</p>\n</blockquote>\n\n<p>EDIT: Even so, there should be no issue with having the enum marked as a DataContract and having client libraries using it.</p>\n" }, { "answer_id": 187866, "author": "Joachim Kerschbaumer", "author_id": 20227, "author_profile": "https://Stackoverflow.com/users/20227", "pm_score": 0, "selected": false, "text": "<p>you could assign int values to your Enum members and just use int's for transfer and when necessary cast them back into your Enum type</p>\n" }, { "answer_id": 189029, "author": "Keith G", "author_id": 5208, "author_profile": "https://Stackoverflow.com/users/5208", "pm_score": 5, "selected": false, "text": "<p>I must have had some issues with an outdated service reference or something. I went back and created a common library containing the enum, and everything works fine. I simply added a using reference to the service interface's file. </p>\n\n<pre><code>using Common; \n\n[ServiceContract]\n[ServiceKnownType(typeof(MyEnum))]\npublic interface IMyService\n{\n [OperationContract]\n ServiceMethod1( MyEnum e, string sUserId, string sSomeData);\n}\n</code></pre>\n\n<p>and I dropped the following:</p>\n\n<pre><code>[DataContract]\npublic enum MyEnum{ [EnumMember] red, [EnumMember] green, [EnumMember] blue };\n</code></pre>\n\n<p>I guess since the enum is referenced via ServiceKnownType, it didn't need to be marked up in the external library with [DataContract] or [Enumerator]</p>\n" }, { "answer_id": 3371312, "author": "Pilsator", "author_id": 403068, "author_profile": "https://Stackoverflow.com/users/403068", "pm_score": 5, "selected": false, "text": "<p>I had a quite weird problem and thought it might be interesting to you. I also had problems that I got a connection stop when I used enums in my data contract. It took me quite a while to find out what the real problem was: I used enums with int values assigned. They started by 1 instead of 0. Obviously WCF requires that there is an enum value equal to 0 for serialization. If you don't state any values within your enumeration, an automatic int value mapping will be done for you starting by 0, so everything's fine. But when you copy paste some other enum definition where the 0 value is not assigned you won't get that to your client through WCF - strange but true!</p>\n" } ]
2008/10/09
[ "https://Stackoverflow.com/questions/187505", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5208/" ]
I have few different applications among which I'd like to share a C# enum. I can't quite figure out how to share an enum declaration between a regular application and a WCF service. Here's the situation. I have 2 lightweight C# destop apps and a WCF webservice that all need to share enum values. Client 1 has ``` Method1( MyEnum e, string sUserId ); ``` Client 2 has ``` Method2( MyEnum e, string sUserId ); ``` Webservice has ``` ServiceMethod1( MyEnum e, string sUserId, string sSomeData); ``` My initial though was to create a library called Common.dll to encapsulate the enum and then just reference that library in all of the projects where the enum is needed. However, WCF makes things difficult because you need to markup the enum for it to be an integral part of the service. Like this: ``` [ServiceContract] [ServiceKnownType(typeof(MyEnum))] public interface IMyService { [OperationContract] ServiceMethod1( MyEnum e, string sUserId, string sSomeData); } [DataContract] public enum MyEnum{ [EnumMember] red, [EnumMember] green, [EnumMember] blue }; ``` So .... Is there a way to share an enum among a WCF service and other applictions?
Using the Common library should be fine. Enumerations are serializable and the DataContract attributes are not needed. See: <http://msdn.microsoft.com/en-us/library/ms731923.aspx> > > Enumeration types. Enumerations, including flag enumerations, are > serializable. Optionally, enumeration types can be marked with the > DataContractAttribute attribute, in which case every member that > participates in serialization must be marked with the > EnumMemberAttribute attribute > > > EDIT: Even so, there should be no issue with having the enum marked as a DataContract and having client libraries using it.
187,506
<p>I'm involved with updating an Access solution. It has a good amount of VBA, a number of queries, a small amount of tables, and a few forms for data entry &amp; report generation. It's an ideal candidate for Access.</p> <p>I want to make changes to the table design, the VBA, the queries, and the forms. How can I track my changes with version control? (we use Subversion, but this goes for any flavor) I can stick the entire mdb in subversion, but that will be storing a binary file, and I won't be able to tell that I just changed one line of VBA code.</p> <p>I thought about copying the VBA code to separate files, and saving those, but I could see those quickly getting out of sync with what's in the database.</p>
[ { "answer_id": 187547, "author": "Patrick Cuff", "author_id": 7903, "author_profile": "https://Stackoverflow.com/users/7903", "pm_score": 1, "selected": false, "text": "<p>I found this tool on SourceForge: <a href=\"http://sourceforge.net/projects/avc/\" rel=\"nofollow noreferrer\">http://sourceforge.net/projects/avc/</a></p>\n\n<p>I haven't used it, but it may be a start for you. There may be some other 3rd party tools that integrate with VSS or SVN that do what you need.</p>\n\n<p>Personally I just keep a plain text file handy to keep a change log. When I commit the binary MDB, I use the entries in the change log as my commit comment.</p>\n" }, { "answer_id": 187703, "author": "BIBD", "author_id": 685, "author_profile": "https://Stackoverflow.com/users/685", "pm_score": 1, "selected": false, "text": "<p>For completeness... </p>\n\n<p>There's always \"Visual Studio [YEAR] Tools for the Microsoft Office System\" \n(<a href=\"http://msdn.microsoft.com/en-us/vs2005/aa718673.aspx\" rel=\"nofollow noreferrer\">http://msdn.microsoft.com/en-us/vs2005/aa718673.aspx</a>) but that seems to require VSS. To me VSS (auto corrupting) is worse than my 347 save points on my uber backuped network share.</p>\n" }, { "answer_id": 188524, "author": "Brettski", "author_id": 5836, "author_profile": "https://Stackoverflow.com/users/5836", "pm_score": 4, "selected": false, "text": "<p>It appears to be something quite available in Access:</p>\n\n<p>This <a href=\"http://blogs.msdn.com/access/archive/2008/05/14/access-source-code-control-and-team-foundation-server.aspx\" rel=\"noreferrer\">link</a> from msdn explains how to install a source control add-in for Microsoft Access. This shipped as a free download as a part of the Access Developer Extensions for Access 2007 and as a separate free add-in for Access 2003.</p>\n\n<p>I am glad you asked this question and I took the time to look it up, as I would like this ability too. The link above has more information on this and links to the add-ins. </p>\n\n<p>Update:<br>\nI installed the add-in for Access 2003. It will only work with VSS, but it does allow me to put Access objects (forms, queries, tables, modules, ect) into the repository. When you go edit any item in the repo you are asked to check it out, but you don't have to. Next I am going to check how it handles being opened and changed on a systems without the add-in. I am not a fan of VSS, but I really do like the thought of storing access objects in a repo.</p>\n\n<p>Update2:<br>\nMachines without the add-in are unable to make any changes to the database structure (add table fields, query parameters, etc.). At first I thought this might be a problem if someone needed to, as there was no apparent way to remove the Access database from source control if Access didn't have the add-in loaded. </p>\n\n<p>Id discovered that running \"compact and repair\" database prompts you if you want to remove the database from source control. I opted yes and was able to edit the database without the add-in. The article in the <a href=\"http://blogs.msdn.com/access/archive/2008/05/14/access-source-code-control-and-team-foundation-server.aspx\" rel=\"noreferrer\">link</a> above also give instructions in setting up Access 2003 and 2007 to use Team System. If you can find a MSSCCI provider for SVN, there is a good chance you can get that to work.</p>\n" }, { "answer_id": 188999, "author": "Philippe Grondier", "author_id": 11436, "author_profile": "https://Stackoverflow.com/users/11436", "pm_score": 4, "selected": false, "text": "<p>We developped our own internal tool, where:</p>\n\n<ol>\n<li>Modules: are exported as txt files and then compared with \"file compare tool\" (freeware)</li>\n<li>Forms: are exported through the undocument application.saveAsText command. It is then possible to see the differences between 2 different versions (\"file compare tool\" once again).</li>\n<li>Macros: we do not have any macro to compare, as we only have the \"autoexec\" macro with one line launching the main VBA procedure</li>\n<li>Queries: are just text strings stored in a table: see infra</li>\n<li>tables: we wrote our own table comparer, listing differences in records AND table structure.</li>\n</ol>\n\n<p>The whole system is smart enough to allow us to produce \"runtime\" versions of our Access application, automatically generated from txt files (modules, and forms being recreated with the undocument application.loadFromText command) and mdb files (tables).</p>\n\n<p>It might sound strange but it works.</p>\n" }, { "answer_id": 211210, "author": "Oliver", "author_id": 28828, "author_profile": "https://Stackoverflow.com/users/28828", "pm_score": 9, "selected": true, "text": "<p>We wrote our own script in VBScript, that uses the undocumented Application.SaveAsText() in Access to export all code, form, macro and report modules. Here it is, it should give you some pointers. (Beware: some of the messages are in german, but you can easily change that.)</p>\n\n<p>EDIT:\nTo summarize various comments below:\n<del>Our Project assumes an .adp-file. In order to get this work with .mdb/.accdb, you have to change OpenAccessProject() to OpenCurrentDatabase()</del>. (Updated to use <code>OpenAccessProject()</code> if it sees a .adp extension, else use <code>OpenCurrentDatabase()</code>.)</p>\n\n<p>decompose.vbs:</p>\n\n\n\n<pre class=\"lang-vb prettyprint-override\"><code>' Usage:\n' CScript decompose.vbs &lt;input file&gt; &lt;path&gt;\n\n' Converts all modules, classes, forms and macros from an Access Project file (.adp) &lt;input file&gt; to\n' text and saves the results in separate files to &lt;path&gt;. Requires Microsoft Access.\n'\n\nOption Explicit\n\nconst acForm = 2\nconst acModule = 5\nconst acMacro = 4\nconst acReport = 3\n\n' BEGIN CODE\nDim fso\nSet fso = CreateObject(\"Scripting.FileSystemObject\")\n\ndim sADPFilename\nIf (WScript.Arguments.Count = 0) then\n MsgBox \"Bitte den Dateinamen angeben!\", vbExclamation, \"Error\"\n Wscript.Quit()\nEnd if\nsADPFilename = fso.GetAbsolutePathName(WScript.Arguments(0))\n\nDim sExportpath\nIf (WScript.Arguments.Count = 1) then\n sExportpath = \"\"\nelse\n sExportpath = WScript.Arguments(1)\nEnd If\n\n\nexportModulesTxt sADPFilename, sExportpath\n\nIf (Err &lt;&gt; 0) and (Err.Description &lt;&gt; NULL) Then\n MsgBox Err.Description, vbExclamation, \"Error\"\n Err.Clear\nEnd If\n\nFunction exportModulesTxt(sADPFilename, sExportpath)\n Dim myComponent\n Dim sModuleType\n Dim sTempname\n Dim sOutstring\n\n dim myType, myName, myPath, sStubADPFilename\n myType = fso.GetExtensionName(sADPFilename)\n myName = fso.GetBaseName(sADPFilename)\n myPath = fso.GetParentFolderName(sADPFilename)\n\n If (sExportpath = \"\") then\n sExportpath = myPath &amp; \"\\Source\\\"\n End If\n sStubADPFilename = sExportpath &amp; myName &amp; \"_stub.\" &amp; myType\n\n WScript.Echo \"copy stub to \" &amp; sStubADPFilename &amp; \"...\"\n On Error Resume Next\n fso.CreateFolder(sExportpath)\n On Error Goto 0\n fso.CopyFile sADPFilename, sStubADPFilename\n\n WScript.Echo \"starting Access...\"\n Dim oApplication\n Set oApplication = CreateObject(\"Access.Application\")\n WScript.Echo \"opening \" &amp; sStubADPFilename &amp; \" ...\"\n If (Right(sStubADPFilename,4) = \".adp\") Then\n oApplication.OpenAccessProject sStubADPFilename\n Else\n oApplication.OpenCurrentDatabase sStubADPFilename\n End If\n\n oApplication.Visible = false\n\n dim dctDelete\n Set dctDelete = CreateObject(\"Scripting.Dictionary\")\n WScript.Echo \"exporting...\"\n Dim myObj\n For Each myObj In oApplication.CurrentProject.AllForms\n WScript.Echo \" \" &amp; myObj.fullname\n oApplication.SaveAsText acForm, myObj.fullname, sExportpath &amp; \"\\\" &amp; myObj.fullname &amp; \".form\"\n oApplication.DoCmd.Close acForm, myObj.fullname\n dctDelete.Add \"FO\" &amp; myObj.fullname, acForm\n Next\n For Each myObj In oApplication.CurrentProject.AllModules\n WScript.Echo \" \" &amp; myObj.fullname\n oApplication.SaveAsText acModule, myObj.fullname, sExportpath &amp; \"\\\" &amp; myObj.fullname &amp; \".bas\"\n dctDelete.Add \"MO\" &amp; myObj.fullname, acModule\n Next\n For Each myObj In oApplication.CurrentProject.AllMacros\n WScript.Echo \" \" &amp; myObj.fullname\n oApplication.SaveAsText acMacro, myObj.fullname, sExportpath &amp; \"\\\" &amp; myObj.fullname &amp; \".mac\"\n dctDelete.Add \"MA\" &amp; myObj.fullname, acMacro\n Next\n For Each myObj In oApplication.CurrentProject.AllReports\n WScript.Echo \" \" &amp; myObj.fullname\n oApplication.SaveAsText acReport, myObj.fullname, sExportpath &amp; \"\\\" &amp; myObj.fullname &amp; \".report\"\n dctDelete.Add \"RE\" &amp; myObj.fullname, acReport\n Next\n\n WScript.Echo \"deleting...\"\n dim sObjectname\n For Each sObjectname In dctDelete\n WScript.Echo \" \" &amp; Mid(sObjectname, 3)\n oApplication.DoCmd.DeleteObject dctDelete(sObjectname), Mid(sObjectname, 3)\n Next\n\n oApplication.CloseCurrentDatabase\n oApplication.CompactRepair sStubADPFilename, sStubADPFilename &amp; \"_\"\n oApplication.Quit\n\n fso.CopyFile sStubADPFilename &amp; \"_\", sStubADPFilename\n fso.DeleteFile sStubADPFilename &amp; \"_\"\n\n\nEnd Function\n\nPublic Function getErr()\n Dim strError\n strError = vbCrLf &amp; \"----------------------------------------------------------------------------------------------------------------------------------------\" &amp; vbCrLf &amp; _\n \"From \" &amp; Err.source &amp; \":\" &amp; vbCrLf &amp; _\n \" Description: \" &amp; Err.Description &amp; vbCrLf &amp; _\n \" Code: \" &amp; Err.Number &amp; vbCrLf\n getErr = strError\nEnd Function\n</code></pre>\n\n<p>If you need a clickable Command, instead of using the command line, create a file named \"decompose.cmd\" with</p>\n\n<pre class=\"lang-vb prettyprint-override\"><code>cscript decompose.vbs youraccessapplication.adp\n</code></pre>\n\n<p>By default, all exported files go into a \"Scripts\" subfolder of your Access-application. The .adp/mdb file is also copied to this location (with a \"stub\" suffix) and stripped of all the exported modules, making it really small. </p>\n\n<p>You MUST checkin this stub with the source-files, because most access settings and custom menu-bars cannot be exported any other way. Just be sure to commit changes to this file only, if you really changed some setting or menu.</p>\n\n<p>Note: If you have any Autoexec-Makros defined in your Application, you may have to hold the Shift-key when you invoke the decompose to prevent it from executing and interfering with the export!</p>\n\n<p>Of course, there is also the reverse script, to build the Application from the \"Source\"-Directory:</p>\n\n<p>compose.vbs:</p>\n\n<pre class=\"lang-vb prettyprint-override\"><code>' Usage:\n' WScript compose.vbs &lt;file&gt; &lt;path&gt;\n\n' Converts all modules, classes, forms and macros in a directory created by \"decompose.vbs\"\n' and composes then into an Access Project file (.adp). This overwrites any existing Modules with the\n' same names without warning!!!\n' Requires Microsoft Access.\n\nOption Explicit\n\nconst acForm = 2\nconst acModule = 5\nconst acMacro = 4\nconst acReport = 3\n\nConst acCmdCompileAndSaveAllModules = &amp;H7E\n\n' BEGIN CODE\nDim fso\nSet fso = CreateObject(\"Scripting.FileSystemObject\")\n\ndim sADPFilename\nIf (WScript.Arguments.Count = 0) then\n MsgBox \"Please enter the file name!\", vbExclamation, \"Error\"\n Wscript.Quit()\nEnd if\nsADPFilename = fso.GetAbsolutePathName(WScript.Arguments(0))\n\nDim sPath\nIf (WScript.Arguments.Count = 1) then\n sPath = \"\"\nelse\n sPath = WScript.Arguments(1)\nEnd If\n\n\nimportModulesTxt sADPFilename, sPath\n\nIf (Err &lt;&gt; 0) and (Err.Description &lt;&gt; NULL) Then\n MsgBox Err.Description, vbExclamation, \"Error\"\n Err.Clear\nEnd If\n\nFunction importModulesTxt(sADPFilename, sImportpath)\n Dim myComponent\n Dim sModuleType\n Dim sTempname\n Dim sOutstring\n\n ' Build file and pathnames\n dim myType, myName, myPath, sStubADPFilename\n myType = fso.GetExtensionName(sADPFilename)\n myName = fso.GetBaseName(sADPFilename)\n myPath = fso.GetParentFolderName(sADPFilename)\n\n ' if no path was given as argument, use a relative directory\n If (sImportpath = \"\") then\n sImportpath = myPath &amp; \"\\Source\\\"\n End If\n sStubADPFilename = sImportpath &amp; myName &amp; \"_stub.\" &amp; myType\n\n ' check for existing file and ask to overwrite with the stub\n if (fso.FileExists(sADPFilename)) Then\n WScript.StdOut.Write sADPFilename &amp; \" exists. Overwrite? (y/n) \"\n dim sInput\n sInput = WScript.StdIn.Read(1)\n if (sInput &lt;&gt; \"y\") Then\n WScript.Quit\n end if\n\n fso.CopyFile sADPFilename, sADPFilename &amp; \".bak\"\n end if\n\n fso.CopyFile sStubADPFilename, sADPFilename\n\n ' launch MSAccess\n WScript.Echo \"starting Access...\"\n Dim oApplication\n Set oApplication = CreateObject(\"Access.Application\")\n WScript.Echo \"opening \" &amp; sADPFilename &amp; \" ...\"\n If (Right(sStubADPFilename,4) = \".adp\") Then\n oApplication.OpenAccessProject sADPFilename\n Else\n oApplication.OpenCurrentDatabase sADPFilename\n End If\n oApplication.Visible = false\n\n Dim folder\n Set folder = fso.GetFolder(sImportpath)\n\n ' load each file from the import path into the stub\n Dim myFile, objectname, objecttype\n for each myFile in folder.Files\n objecttype = fso.GetExtensionName(myFile.Name)\n objectname = fso.GetBaseName(myFile.Name)\n WScript.Echo \" \" &amp; objectname &amp; \" (\" &amp; objecttype &amp; \")\"\n\n if (objecttype = \"form\") then\n oApplication.LoadFromText acForm, objectname, myFile.Path\n elseif (objecttype = \"bas\") then\n oApplication.LoadFromText acModule, objectname, myFile.Path\n elseif (objecttype = \"mac\") then\n oApplication.LoadFromText acMacro, objectname, myFile.Path\n elseif (objecttype = \"report\") then\n oApplication.LoadFromText acReport, objectname, myFile.Path\n end if\n\n next\n\n oApplication.RunCommand acCmdCompileAndSaveAllModules\n oApplication.Quit\nEnd Function\n\nPublic Function getErr()\n Dim strError\n strError = vbCrLf &amp; \"----------------------------------------------------------------------------------------------------------------------------------------\" &amp; vbCrLf &amp; _\n \"From \" &amp; Err.source &amp; \":\" &amp; vbCrLf &amp; _\n \" Description: \" &amp; Err.Description &amp; vbCrLf &amp; _\n \" Code: \" &amp; Err.Number &amp; vbCrLf\n getErr = strError\nEnd Function\n</code></pre>\n\n<p>Again, this goes with a companion \"compose.cmd\" containing:</p>\n\n<pre class=\"lang-vb prettyprint-override\"><code>cscript compose.vbs youraccessapplication.adp\n</code></pre>\n\n<p>It asks you to confirm overwriting your current application and first creates a backup, if you do. It then collects all source-files in the Source-Directory and re-inserts them into the stub.</p>\n\n<p>Have Fun!</p>\n" }, { "answer_id": 215930, "author": "ChuckB", "author_id": 5281, "author_profile": "https://Stackoverflow.com/users/5281", "pm_score": 2, "selected": false, "text": "<p>There's a gotcha - VSS 6.0 can only accept MDB's using the add-in under a certain number of objects, which includes all local tables, queries, modules, and forms. Don't know the exact object limit.</p>\n\n<p>To build our 10 year old prod floor app, which is huge, we are forced to combine 3 or 4 separate MDBs out of SS into one MDB , which complicates automated builds to the point we don't waste time doing it.</p>\n\n<p>I think I'll try the script above to spew this MDb into SVN and simplify builds for everyone.</p>\n" }, { "answer_id": 1711333, "author": "Summer-Time", "author_id": 207005, "author_profile": "https://Stackoverflow.com/users/207005", "pm_score": 1, "selected": false, "text": "<p>i'm using the <a href=\"http://www.microsoft.com/downloads/details.aspx?familyid=2ea45ff4-a916-48c5-8f84-44b91fa774bc&amp;displaylang=en\" rel=\"nofollow noreferrer\">Access 2003 Add-in: Source Code Control</a>. It works fine. One Problem are invalid characters like a \":\". </p>\n\n<p>I'm checkin in and out. Internly the Add-In do the same as the code up there, but with more tool support. I can see if an object is checked out and refresh the objects.</p>\n" }, { "answer_id": 1849498, "author": "DaveParillo", "author_id": 167483, "author_profile": "https://Stackoverflow.com/users/167483", "pm_score": 4, "selected": false, "text": "<p>Olivers answer rocks, but the <code>CurrentProject</code> reference was not working for me. I ended up ripping the guts out of the middle of his export and replacing it with this, based on a similar solution by <a href=\"http://www.accessmvp.com/Arvin/DocDatabase.txt\" rel=\"nofollow noreferrer\">Arvin Meyer</a>. Has the advantage of exporting Queries if you are using an mdb instead of an adp.</p>\n\n<pre class=\"lang-vb prettyprint-override\"><code>' Writes database componenets to a series of text files\n' @author Arvin Meyer\n' @date June 02, 1999\nFunction DocDatabase(oApp)\n Dim dbs \n Dim cnt \n Dim doc \n Dim i\n Dim prefix\n Dim dctDelete\n Dim docName\n\n Const acQuery = 1\n\n Set dctDelete = CreateObject(\"Scripting.Dictionary\")\n\n Set dbs = oApp.CurrentDb() ' use CurrentDb() to refresh Collections\n Set cnt = dbs.Containers(\"Forms\")\n prefix = oApp.CurrentProject.Path &amp; \"\\\"\n For Each doc In cnt.Documents\n oApp.SaveAsText acForm, doc.Name, prefix &amp; doc.Name &amp; \".frm\"\n dctDelete.Add \"frm_\" &amp; doc.Name, acForm\n Next\n\n Set cnt = dbs.Containers(\"Reports\")\n For Each doc In cnt.Documents\n oApp.SaveAsText acReport, doc.Name, prefix &amp; doc.Name &amp; \".rpt\"\n dctDelete.Add \"rpt_\" &amp; doc.Name, acReport\n Next\n\n Set cnt = dbs.Containers(\"Scripts\")\n For Each doc In cnt.Documents\n oApp.SaveAsText acMacro, doc.Name, prefix &amp; doc.Name &amp; \".vbs\"\n dctDelete.Add \"vbs_\" &amp; doc.Name, acMacro\n Next\n\n Set cnt = dbs.Containers(\"Modules\")\n For Each doc In cnt.Documents\n oApp.SaveAsText acModule, doc.Name, prefix &amp; doc.Name &amp; \".bas\"\n dctDelete.Add \"bas_\" &amp; doc.Name, acModule\n Next\n\n For i = 0 To dbs.QueryDefs.Count - 1\n oApp.SaveAsText acQuery, dbs.QueryDefs(i).Name, prefix &amp; dbs.QueryDefs(i).Name &amp; \".txt\"\n dctDelete.Add \"qry_\" &amp; dbs.QueryDefs(i).Name, acQuery\n Next\n\n WScript.Echo \"deleting \" &amp; dctDelete.Count &amp; \" objects.\"\n For Each docName In dctDelete\n WScript.Echo \" \" &amp; Mid(docName, 5)\n oApp.DoCmd.DeleteObject dctDelete(docName), Mid(docName, 5)\n Next\n\n Set doc = Nothing\n Set cnt = Nothing\n Set dbs = Nothing\n Set dctDelete = Nothing\n\nEnd Function\n</code></pre>\n" }, { "answer_id": 3488355, "author": "Cory", "author_id": 186778, "author_profile": "https://Stackoverflow.com/users/186778", "pm_score": 2, "selected": false, "text": "<p>For those using Access 2010, SaveAsText is not a visible method in Intellisense but it appears to be a valid method, as Arvin Meyer's script <a href=\"https://stackoverflow.com/questions/187506/how-do-you-use-version-control-with-access-development/2366218#2366218\">mentioned earlier</a> worked fine for me.</p>\n\n<p>Interestingly, <a href=\"http://msdn.microsoft.com/en-us/library/ff821429.aspx\" rel=\"nofollow noreferrer\">SaveAsAXL</a> is new to 2010 and has the same signature as SaveAsText, though it appears it will only work with web databases, which require SharePoint Server 2010.</p>\n" }, { "answer_id": 3500327, "author": "Benjamin Brauer", "author_id": 422551, "author_profile": "https://Stackoverflow.com/users/422551", "pm_score": 2, "selected": false, "text": "<p>We had the same issue a while ago. </p>\n\n<p>Our first try was a third-party tool which offers a proxy of the SourceSafe API for Subversion to be used with MS Access and VB 6. The Tool can be found <a href=\"http://www.pushok.com/soft_svn.php\" rel=\"nofollow noreferrer\">here</a>. </p>\n\n<p>As we were not that satisfied with that tool we switched over to Visual SourceSafe and the VSS Acces Plugin.</p>\n" }, { "answer_id": 6312883, "author": "mnieto", "author_id": 777551, "author_profile": "https://Stackoverflow.com/users/777551", "pm_score": 3, "selected": false, "text": "<p>Based on the ideas of this post and similar entries in some blogs I have wrote an application that works with mdb and adp file formats. It import/export all database objects (including tables, references, relations and database properties) to plain text files.\nWith those files you can work with a any source version control. Next version will allow import back the plain text files to the database. There will be also a command line tool</p>\n\n<p>You can download the application or the source code from: <a href=\"http://accesssvn.codeplex.com/\">http://accesssvn.codeplex.com/</a></p>\n\n<p>regards</p>\n" }, { "answer_id": 9740061, "author": "JKK", "author_id": 1058864, "author_profile": "https://Stackoverflow.com/users/1058864", "pm_score": 3, "selected": false, "text": "<p>Resurrecting an old thread but this is a good one. I've implemented the two scripts (compose.vbs / decompose.vbs) for my own project and ran into a problem with old .mdb files:</p>\n\n<p>It stalls when it gets to a form that includes the code: </p>\n\n<pre><code>NoSaveCTIWhenDisabled =1\n</code></pre>\n\n<p>Access says it has a problem and that's the end of the story. I ran some tests and played around trying to get around this issue and found this thread with a work around at the end:</p>\n\n<p><a href=\"http://social.msdn.microsoft.com/Forums/en-US/accessdev/thread/691887f4-b345-4ea0-9158-6183e812bfa2/\" rel=\"nofollow\">Can't create database</a></p>\n\n<p>Basically (in case the thread goes dead), you take the .mdb and do a \"Save as\" to the new .accdb format. Then the source safe or compose/decompose stuff will work. I also had to play around for 10 minutes to get the right command line syntax for the (de)compose scripts to work right so here's that info as well:</p>\n\n<p>To compose (say your stuff is located in C:\\SControl (create a sub folder named Source to store the extracted files):</p>\n\n<pre><code>'(to extract for importing to source control)\ncscript compose.vbs database.accdb \n\n'(to rebuild from extracted files saved from an earlier date)\ncscript decompose.vbs database.accdb C:\\SControl\\Source\\\n</code></pre>\n\n<p>That's it!</p>\n\n<p>The versions of Access where I've experienced the problem above include Access 2000-2003 \".mdb\" databases and fixed the problem by saving them into the 2007-2010 \".accdb\" formats prior to running the compose/decompose scripts. After the conversion the scripts work just fine!</p>\n" }, { "answer_id": 13927283, "author": "Friedrich", "author_id": 15068, "author_profile": "https://Stackoverflow.com/users/15068", "pm_score": 2, "selected": false, "text": "<p>I'm using Oasis-Svn\n<a href=\"http://dev2dev.de/\" rel=\"nofollow\">http://dev2dev.de/</a></p>\n\n<p>I just can tell it has saved me at least once. My mdb was growing beyond 2 GB and that broke it. I could go back to an old version and import the Forms and just lost a day or so of work. </p>\n" }, { "answer_id": 18637342, "author": "WolfgangP", "author_id": 2750748, "author_profile": "https://Stackoverflow.com/users/2750748", "pm_score": 1, "selected": false, "text": "<p>You can also connect your MS Access to the Team Foundation Server. There is also a free Express variant for up to 5 developers. Works really well!</p>\n\n<ul>\n<li><a href=\"http://geekswithblogs.net/michaelazocar/archive/2008/06/26/ms-access-and-tfs.aspx\" rel=\"nofollow\">English guide</a></li>\n<li><a href=\"http://www.microsoft.com/visualstudio/deu/products/visual-studio-team-foundation-server-express\" rel=\"nofollow\">Team Foundation Server 2012 Express</a></li>\n</ul>\n\n<p>Edit: fixed link</p>\n" }, { "answer_id": 21149015, "author": "JBickford", "author_id": 118346, "author_profile": "https://Stackoverflow.com/users/118346", "pm_score": 0, "selected": false, "text": "<p>I tried to help contribute to his answer by adding an export option for Queries within the access database. (With ample help from <a href=\"https://stackoverflow.com/questions/1275502/using-vba-to-export-all-ms-access-sql-queries-to-text-files\">other</a> SO <a href=\"https://stackoverflow.com/questions/20252599/how-do-you-export-ms-access-query-objects-to-text-file\">answers</a>)</p>\n\n<pre><code>Dim def\nSet stream = fso.CreateTextFile(sExportpath &amp; \"\\\" &amp; myName &amp; \".queries.txt\")\n For Each def In oApplication.CurrentDb.QueryDefs\n\n WScript.Echo \" Exporting Queries to Text...\"\n stream.WriteLine(\"Name: \" &amp; def.Name)\n stream.WriteLine(def.SQL)\n stream.writeline \"--------------------------\"\n stream.writeline \" \"\n\n Next\nstream.Close\n</code></pre>\n\n<p>Haven't be able to work that back into the 'compose' feature, but that's not what I need it to do right now. </p>\n\n<p>Note: I also added \".txt\" to each of the exported file names in <em>decompose.vbs</em> so that the source control would immediately show me the file diffs.</p>\n\n<p>Hope that helps! </p>\n\n<hr>\n" }, { "answer_id": 26253820, "author": "Daniel Hillebrand", "author_id": 4031178, "author_profile": "https://Stackoverflow.com/users/4031178", "pm_score": 1, "selected": false, "text": "<p>The answer from Oliver works great. Please find my extended version below that adds support for Access queries.</p>\n\n<p>(please <a href=\"https://stackoverflow.com/a/211210/78522\">see answer from Oliver</a> for more information/usage)</p>\n\n<p>decompose.vbs:</p>\n\n\n\n<pre class=\"lang-vb prettyprint-override\"><code>' Usage:\n' CScript decompose.vbs &lt;input file&gt; &lt;path&gt;\n\n' Converts all modules, classes, forms and macros from an Access Project file (.adp) &lt;input file&gt; to\n' text and saves the results in separate files to &lt;path&gt;. Requires Microsoft Access.\n'\nOption Explicit\n\nconst acForm = 2\nconst acModule = 5\nconst acMacro = 4\nconst acReport = 3\nconst acQuery = 1\n\n' BEGIN CODE\nDim fso\nSet fso = CreateObject(\"Scripting.FileSystemObject\")\n\ndim sADPFilename\nIf (WScript.Arguments.Count = 0) then\n MsgBox \"Bitte den Dateinamen angeben!\", vbExclamation, \"Error\"\n Wscript.Quit()\nEnd if\nsADPFilename = fso.GetAbsolutePathName(WScript.Arguments(0))\n\nDim sExportpath\nIf (WScript.Arguments.Count = 1) then\n sExportpath = \"\"\nelse\n sExportpath = WScript.Arguments(1)\nEnd If\n\n\nexportModulesTxt sADPFilename, sExportpath\n\nIf (Err &lt;&gt; 0) and (Err.Description &lt;&gt; NULL) Then\n MsgBox Err.Description, vbExclamation, \"Error\"\n Err.Clear\nEnd If\n\nFunction exportModulesTxt(sADPFilename, sExportpath)\n Dim myComponent\n Dim sModuleType\n Dim sTempname\n Dim sOutstring\n\n dim myType, myName, myPath, sStubADPFilename\n myType = fso.GetExtensionName(sADPFilename)\n myName = fso.GetBaseName(sADPFilename)\n myPath = fso.GetParentFolderName(sADPFilename)\n\n If (sExportpath = \"\") then\n sExportpath = myPath &amp; \"\\Source\\\"\n End If\n sStubADPFilename = sExportpath &amp; myName &amp; \"_stub.\" &amp; myType\n\n WScript.Echo \"copy stub to \" &amp; sStubADPFilename &amp; \"...\"\n On Error Resume Next\n fso.CreateFolder(sExportpath)\n On Error Goto 0\n fso.CopyFile sADPFilename, sStubADPFilename\n\n WScript.Echo \"starting Access...\"\n Dim oApplication\n Set oApplication = CreateObject(\"Access.Application\")\n WScript.Echo \"opening \" &amp; sStubADPFilename &amp; \" ...\"\n If (Right(sStubADPFilename,4) = \".adp\") Then\n oApplication.OpenAccessProject sStubADPFilename\n Else\n oApplication.OpenCurrentDatabase sStubADPFilename\n End If\n\n oApplication.Visible = false\n\n dim dctDelete\n Set dctDelete = CreateObject(\"Scripting.Dictionary\")\n WScript.Echo \"exporting...\"\n Dim myObj\n\n For Each myObj In oApplication.CurrentProject.AllForms\n WScript.Echo \" \" &amp; myObj.fullname\n oApplication.SaveAsText acForm, myObj.fullname, sExportpath &amp; \"\\\" &amp; myObj.fullname &amp; \".form\"\n oApplication.DoCmd.Close acForm, myObj.fullname\n dctDelete.Add \"FO\" &amp; myObj.fullname, acForm\n Next\n For Each myObj In oApplication.CurrentProject.AllModules\n WScript.Echo \" \" &amp; myObj.fullname\n oApplication.SaveAsText acModule, myObj.fullname, sExportpath &amp; \"\\\" &amp; myObj.fullname &amp; \".bas\"\n dctDelete.Add \"MO\" &amp; myObj.fullname, acModule\n Next\n For Each myObj In oApplication.CurrentProject.AllMacros\n WScript.Echo \" \" &amp; myObj.fullname\n oApplication.SaveAsText acMacro, myObj.fullname, sExportpath &amp; \"\\\" &amp; myObj.fullname &amp; \".mac\"\n dctDelete.Add \"MA\" &amp; myObj.fullname, acMacro\n Next\n For Each myObj In oApplication.CurrentProject.AllReports\n WScript.Echo \" \" &amp; myObj.fullname\n oApplication.SaveAsText acReport, myObj.fullname, sExportpath &amp; \"\\\" &amp; myObj.fullname &amp; \".report\"\n dctDelete.Add \"RE\" &amp; myObj.fullname, acReport\n Next\n For Each myObj In oApplication.CurrentDb.QueryDefs\n if not left(myObj.name,3) = \"~sq\" then 'exclude queries defined by the forms. Already included in the form itself\n WScript.Echo \" \" &amp; myObj.name\n oApplication.SaveAsText acQuery, myObj.name, sExportpath &amp; \"\\\" &amp; myObj.name &amp; \".query\"\n oApplication.DoCmd.Close acQuery, myObj.name\n dctDelete.Add \"FO\" &amp; myObj.name, acQuery\n end if\n Next\n\n WScript.Echo \"deleting...\"\n dim sObjectname\n For Each sObjectname In dctDelete\n WScript.Echo \" \" &amp; Mid(sObjectname, 3)\n oApplication.DoCmd.DeleteObject dctDelete(sObjectname), Mid(sObjectname, 3)\n Next\n\n oApplication.CloseCurrentDatabase\n oApplication.CompactRepair sStubADPFilename, sStubADPFilename &amp; \"_\"\n oApplication.Quit\n\n fso.CopyFile sStubADPFilename &amp; \"_\", sStubADPFilename\n fso.DeleteFile sStubADPFilename &amp; \"_\"\n\n\nEnd Function\n\nPublic Function getErr()\n Dim strError\n strError = vbCrLf &amp; \"----------------------------------------------------------------------------------------------------------------------------------------\" &amp; vbCrLf &amp; _\n \"From \" &amp; Err.source &amp; \":\" &amp; vbCrLf &amp; _\n \" Description: \" &amp; Err.Description &amp; vbCrLf &amp; _\n \" Code: \" &amp; Err.Number &amp; vbCrLf\n getErr = strError\nEnd Function\n</code></pre>\n\n<p>compose.vbs:</p>\n\n<pre class=\"lang-vb prettyprint-override\"><code>' Usage:\n' WScript compose.vbs &lt;file&gt; &lt;path&gt;\n\n' Converts all modules, classes, forms and macros in a directory created by \"decompose.vbs\"\n' and composes then into an Access Project file (.adp). This overwrites any existing Modules with the\n' same names without warning!!!\n' Requires Microsoft Access.\n\nOption Explicit\n\nconst acForm = 2\nconst acModule = 5\nconst acMacro = 4\nconst acReport = 3\nconst acQuery = 1\n\nConst acCmdCompileAndSaveAllModules = &amp;H7E\n\n' BEGIN CODE\nDim fso\nSet fso = CreateObject(\"Scripting.FileSystemObject\")\n\ndim sADPFilename\nIf (WScript.Arguments.Count = 0) then\n MsgBox \"Bitte den Dateinamen angeben!\", vbExclamation, \"Error\"\n Wscript.Quit()\nEnd if\nsADPFilename = fso.GetAbsolutePathName(WScript.Arguments(0))\n\nDim sPath\nIf (WScript.Arguments.Count = 1) then\n sPath = \"\"\nelse\n sPath = WScript.Arguments(1)\nEnd If\n\n\nimportModulesTxt sADPFilename, sPath\n\nIf (Err &lt;&gt; 0) and (Err.Description &lt;&gt; NULL) Then\n MsgBox Err.Description, vbExclamation, \"Error\"\n Err.Clear\nEnd If\n\nFunction importModulesTxt(sADPFilename, sImportpath)\n Dim myComponent\n Dim sModuleType\n Dim sTempname\n Dim sOutstring\n\n ' Build file and pathnames\n dim myType, myName, myPath, sStubADPFilename\n myType = fso.GetExtensionName(sADPFilename)\n myName = fso.GetBaseName(sADPFilename)\n myPath = fso.GetParentFolderName(sADPFilename)\n\n ' if no path was given as argument, use a relative directory\n If (sImportpath = \"\") then\n sImportpath = myPath &amp; \"\\Source\\\"\n End If\n sStubADPFilename = sImportpath &amp; myName &amp; \"_stub.\" &amp; myType\n\n ' check for existing file and ask to overwrite with the stub\n if (fso.FileExists(sADPFilename)) Then\n WScript.StdOut.Write sADPFilename &amp; \" existiert bereits. Überschreiben? (j/n) \"\n dim sInput\n sInput = WScript.StdIn.Read(1)\n if (sInput &lt;&gt; \"j\") Then\n WScript.Quit\n end if\n\n fso.CopyFile sADPFilename, sADPFilename &amp; \".bak\"\n end if\n\n fso.CopyFile sStubADPFilename, sADPFilename\n\n ' launch MSAccess\n WScript.Echo \"starting Access...\"\n Dim oApplication\n Set oApplication = CreateObject(\"Access.Application\")\n WScript.Echo \"opening \" &amp; sADPFilename &amp; \" ...\"\n If (Right(sStubADPFilename,4) = \".adp\") Then\n oApplication.OpenAccessProject sADPFilename\n Else\n oApplication.OpenCurrentDatabase sADPFilename\n End If\n oApplication.Visible = false\n\n Dim folder\n Set folder = fso.GetFolder(sImportpath)\n\n ' load each file from the import path into the stub\n Dim myFile, objectname, objecttype\n for each myFile in folder.Files\n objecttype = fso.GetExtensionName(myFile.Name)\n objectname = fso.GetBaseName(myFile.Name)\n WScript.Echo \" \" &amp; objectname &amp; \" (\" &amp; objecttype &amp; \")\"\n\n if (objecttype = \"form\") then\n oApplication.LoadFromText acForm, objectname, myFile.Path\n elseif (objecttype = \"bas\") then\n oApplication.LoadFromText acModule, objectname, myFile.Path\n elseif (objecttype = \"mac\") then\n oApplication.LoadFromText acMacro, objectname, myFile.Path\n elseif (objecttype = \"report\") then\n oApplication.LoadFromText acReport, objectname, myFile.Path\n elseif (objecttype = \"query\") then\n oApplication.LoadFromText acQuery, objectname, myFile.Path\n end if\n\n next\n\n oApplication.RunCommand acCmdCompileAndSaveAllModules\n oApplication.Quit\nEnd Function\n\nPublic Function getErr()\n Dim strError\n strError = vbCrLf &amp; \"----------------------------------------------------------------------------------------------------------------------------------------\" &amp; vbCrLf &amp; _\n \"From \" &amp; Err.source &amp; \":\" &amp; vbCrLf &amp; _\n \" Description: \" &amp; Err.Description &amp; vbCrLf &amp; _\n \" Code: \" &amp; Err.Number &amp; vbCrLf\n getErr = strError\nEnd Function\n</code></pre>\n" }, { "answer_id": 26820495, "author": "hansfn", "author_id": 334497, "author_profile": "https://Stackoverflow.com/users/334497", "pm_score": 4, "selected": false, "text": "<p>The compose/decompose solution posted by Oliver is great, but it has some problems:</p>\n\n<ul>\n<li>The files are encoded as UCS-2 (UTF-16) which can cause version control systems/tools to consider the files to be binary.</li>\n<li>The files contain a lot of cruft that changes often - checksums, printer information and more. This is a serious problem if you want clean diffs or need to cooperate on the project.</li>\n</ul>\n\n<p>I was planning to fix this myself, but discovered there is already a good solution available: <a href=\"https://github.com/timabell/msaccess-vcs-integration\">timabell/msaccess-vcs-integration</a> on GitHub. I have tested msaccess-vcs-integration and it does work great. </p>\n\n<p><strong>Updated 3rd of March 2015</strong>: The project was originally maintained/owned by bkidwell on Github, but it was <a href=\"https://github.com/bkidwell/msaccess-vcs-integration/commit/849870c9c2cc8a2a2eae9325e721b2ae3e25792c\">transferred to timabell</a> - link above to project is updated accordingly. There are some forks from the original project by bkidwell, for example <a href=\"https://github.com/ArminBra/msaccess-vcs-integration\">by ArminBra</a> and <a href=\"https://github.com/matonb/msaccess-vcs-integration\">by matonb</a>, which AFAICT shouldn't be used.</p>\n\n<p>The downside to using msaccess-vcs-integration compared to Olivers's decompose solution:</p>\n\n<ul>\n<li>It's significantly slower. I'm sure that the speed issue can be fixed, but I don't need to export my project to text that often ...</li>\n<li>It doesn't create a stub Access project with the exported stuff removed. This can also be fixed (by adopting code from the decompose script), but again - not that important.</li>\n</ul>\n\n<p>Anyway, my clear recommendation is msaccess-vcs-integration. It solved all the problems I had with using Git on the exported files.</p>\n" }, { "answer_id": 35308115, "author": "VolleyballAddictSandiego", "author_id": 5765277, "author_profile": "https://Stackoverflow.com/users/5765277", "pm_score": 0, "selected": false, "text": "<p>This entry describes a totally different approach from the other entries, and may not be what you're looking for. So I won't be offended if you ignore this. But at least it is food for thought.</p>\n\n<p>In some professional commercial software development environments, configuration management (CM) of software deliverables is not normally done <em>within</em> the software application itself or software project itself. CM is imposed upon the final deliverable products, by saving the software in a special CM folder, where both the file and its folder are marked with version identification.\nFor example, Clearcase allows the data manager to \"check in\" a software file, assign it a \"branch\", assign it a \"bubble\", and apply \"labels\".\nWhen you want to see and download a file, you have to configure your \"config spec\" to point to the version you want, then cd into the folder and there it is.</p>\n\n<p>Just an idea.</p>\n" }, { "answer_id": 35501159, "author": "Jakub M.", "author_id": 4863744, "author_profile": "https://Stackoverflow.com/users/4863744", "pm_score": 2, "selected": false, "text": "<h1>Text-file only solution (queries, tables and relationships included)</h1>\n<p>I have altered the Oliver's pair of scripts so that they export/import <strong>relationships, tables and queries</strong> in addition to modules, classes, forms and macros. <em>Everything</em> is saved into plaintext files, so there is <strong>no database file</strong> created to be stored with the text files in version control.</p>\n\n<h2>Export into text files (decompose.vbs)</h2>\n<pre class=\"lang-vb prettyprint-override\"><code>' Usage:\n' cscript decompose.vbs &lt;input file&gt; &lt;path&gt;\n\n' Converts all modules, classes, forms and macros from an Access Project file (.adp) &lt;input file&gt; to\n' text and saves the results in separate files to &lt;path&gt;. Requires Microsoft Access.\nOption Explicit\n\nConst acForm = 2\nConst acModule = 5\nConst acMacro = 4\nConst acReport = 3\nConst acQuery = 1\nConst acExportTable = 0\n\n' BEGIN CODE\nDim fso, relDoc, ACCDBFilename, sExportpath\nSet fso = CreateObject(&quot;Scripting.FileSystemObject&quot;)\nSet relDoc = CreateObject(&quot;Microsoft.XMLDOM&quot;)\n\nIf (Wscript.Arguments.Count = 0) Then\n MsgBox &quot;Please provide the .accdb database file&quot;, vbExclamation, &quot;Error&quot;\n Wscript.Quit()\nEnd If\nACCDBFilename = fso.GetAbsolutePathName(Wscript.Arguments(0))\n\nIf (Wscript.Arguments.Count = 1) Then\n sExportpath = &quot;&quot;\nElse\n sExportpath = Wscript.Arguments(1)\nEnd If\n\n\nexportModulesTxt ACCDBFilename, sExportpath\n\nIf (Err &lt;&gt; 0) And (Err.Description &lt;&gt; Null) Then\n MsgBox Err.Description, vbExclamation, &quot;Error&quot;\n Err.Clear\nEnd If\n\nFunction exportModulesTxt(ACCDBFilename, sExportpath)\n Dim myComponent, sModuleType, sTempname, sOutstring\n Dim myType, myName, myPath, hasRelations\n myType = fso.GetExtensionName(ACCDBFilename)\n myName = fso.GetBaseName(ACCDBFilename)\n myPath = fso.GetParentFolderName(ACCDBFilename)\n\n 'if no path was given as argument, use a relative directory\n If (sExportpath = &quot;&quot;) Then\n sExportpath = myPath &amp; &quot;\\Source&quot;\n End If\n 'On Error Resume Next\n fso.DeleteFolder (sExportpath)\n fso.CreateFolder (sExportpath)\n On Error GoTo 0\n\n Wscript.Echo &quot;starting Access...&quot;\n Dim oApplication\n Set oApplication = CreateObject(&quot;Access.Application&quot;)\n Wscript.Echo &quot;Opening &quot; &amp; ACCDBFilename &amp; &quot; ...&quot;\n If (Right(ACCDBFilename, 4) = &quot;.adp&quot;) Then\n oApplication.OpenAccessProject ACCDBFilename\n Else\n oApplication.OpenCurrentDatabase ACCDBFilename\n End If\n oApplication.Visible = False\n\n Wscript.Echo &quot;exporting...&quot;\n Dim myObj\n For Each myObj In oApplication.CurrentProject.AllForms\n Wscript.Echo &quot;Exporting FORM &quot; &amp; myObj.FullName\n oApplication.SaveAsText acForm, myObj.FullName, sExportpath &amp; &quot;\\&quot; &amp; myObj.FullName &amp; &quot;.form.txt&quot;\n oApplication.DoCmd.Close acForm, myObj.FullName\n Next\n For Each myObj In oApplication.CurrentProject.AllModules\n Wscript.Echo &quot;Exporting MODULE &quot; &amp; myObj.FullName\n oApplication.SaveAsText acModule, myObj.FullName, sExportpath &amp; &quot;\\&quot; &amp; myObj.FullName &amp; &quot;.module.txt&quot;\n Next\n For Each myObj In oApplication.CurrentProject.AllMacros\n Wscript.Echo &quot;Exporting MACRO &quot; &amp; myObj.FullName\n oApplication.SaveAsText acMacro, myObj.FullName, sExportpath &amp; &quot;\\&quot; &amp; myObj.FullName &amp; &quot;.macro.txt&quot;\n Next\n For Each myObj In oApplication.CurrentProject.AllReports\n Wscript.Echo &quot;Exporting REPORT &quot; &amp; myObj.FullName\n oApplication.SaveAsText acReport, myObj.FullName, sExportpath &amp; &quot;\\&quot; &amp; myObj.FullName &amp; &quot;.report.txt&quot;\n Next\n For Each myObj In oApplication.CurrentDb.QueryDefs\n Wscript.Echo &quot;Exporting QUERY &quot; &amp; myObj.Name\n oApplication.SaveAsText acQuery, myObj.Name, sExportpath &amp; &quot;\\&quot; &amp; myObj.Name &amp; &quot;.query.txt&quot;\n Next\n For Each myObj In oApplication.CurrentDb.TableDefs\n If Not Left(myObj.Name, 4) = &quot;MSys&quot; Then\n Wscript.Echo &quot;Exporting TABLE &quot; &amp; myObj.Name\n oApplication.ExportXml acExportTable, myObj.Name, , sExportpath &amp; &quot;\\&quot; &amp; myObj.Name &amp; &quot;.table.txt&quot;\n 'put the file path as a second parameter if you want to export the table data as well, instead of ommiting it and passing it into a third parameter for structure only\n End If\n Next\n\n hasRelations = False\n relDoc.appendChild relDoc.createElement(&quot;Relations&quot;)\n For Each myObj In oApplication.CurrentDb.Relations 'loop though all the relations\n If Not Left(myObj.Name, 4) = &quot;MSys&quot; Then\n Dim relName, relAttrib, relTable, relFoTable, fld\n hasRelations = True\n\n relDoc.ChildNodes(0).appendChild relDoc.createElement(&quot;Relation&quot;)\n Set relName = relDoc.createElement(&quot;Name&quot;)\n relName.Text = myObj.Name\n relDoc.ChildNodes(0).LastChild.appendChild relName\n\n Set relAttrib = relDoc.createElement(&quot;Attributes&quot;)\n relAttrib.Text = myObj.Attributes\n relDoc.ChildNodes(0).LastChild.appendChild relAttrib\n\n Set relTable = relDoc.createElement(&quot;Table&quot;)\n relTable.Text = myObj.Table\n relDoc.ChildNodes(0).LastChild.appendChild relTable\n\n Set relFoTable = relDoc.createElement(&quot;ForeignTable&quot;)\n relFoTable.Text = myObj.ForeignTable\n relDoc.ChildNodes(0).LastChild.appendChild relFoTable\n\n Wscript.Echo &quot;Exporting relation &quot; &amp; myObj.Name &amp; &quot; between tables &quot; &amp; myObj.Table &amp; &quot; -&gt; &quot; &amp; myObj.ForeignTable\n\n For Each fld In myObj.Fields 'in case the relationship works with more fields\n Dim lf, ff\n relDoc.ChildNodes(0).LastChild.appendChild relDoc.createElement(&quot;Field&quot;)\n\n Set lf = relDoc.createElement(&quot;Name&quot;)\n lf.Text = fld.Name\n relDoc.ChildNodes(0).LastChild.LastChild.appendChild lf\n\n Set ff = relDoc.createElement(&quot;ForeignName&quot;)\n ff.Text = fld.ForeignName\n relDoc.ChildNodes(0).LastChild.LastChild.appendChild ff\n\n Wscript.Echo &quot; Involving fields &quot; &amp; fld.Name &amp; &quot; -&gt; &quot; &amp; fld.ForeignName\n Next\n End If\n Next\n If hasRelations Then\n relDoc.InsertBefore relDoc.createProcessingInstruction(&quot;xml&quot;, &quot;version='1.0'&quot;), relDoc.ChildNodes(0)\n relDoc.Save sExportpath &amp; &quot;\\relations.rel.txt&quot;\n Wscript.Echo &quot;Relations successfuly saved in file relations.rel.txt&quot;\n End If\n\n oApplication.CloseCurrentDatabase\n oApplication.Quit\n\nEnd Function\n</code></pre>\n<p>You can execute this script by calling <code>cscript decompose.vbs &lt;path to file to decompose&gt; &lt;folder to store text files&gt;</code>. In case you omit the second parameter, it will create 'Source' folder where the database is located. Please note that destination folder will be wiped if it already exists.</p>\n<h3>Include data in the exported tables</h3>\n<p>Replace line 93: <code>oApplication.ExportXML acExportTable, myObj.Name, , sExportpath &amp; &quot;\\&quot; &amp; myObj.Name &amp; &quot;.table.txt&quot;</code></p>\n<p>with line <code>oApplication.ExportXML acExportTable, myObj.Name, sExportpath &amp; &quot;\\&quot; &amp; myObj.Name &amp; &quot;.table.txt&quot;</code></p>\n<h2><strike>Import into</strike> Create database file (compose.vbs)</h2>\n<pre class=\"lang-vb prettyprint-override\"><code>' Usage:\n' cscript compose.vbs &lt;file&gt; &lt;path&gt;\n\n' Reads all modules, classes, forms, macros, queries, tables and their relationships in a directory created by &quot;decompose.vbs&quot;\n' and composes then into an Access Database file (.accdb).\n' Requires Microsoft Access.\nOption Explicit\n\nConst acForm = 2\nConst acModule = 5\nConst acMacro = 4\nConst acReport = 3\nConst acQuery = 1\nConst acStructureOnly = 0 'change 0 to 1 if you want import StructureAndData instead of StructureOnly\nConst acCmdCompileAndSaveAllModules = &amp;H7E\n\nDim fso, relDoc, ACCDBFilename, sPath\nSet fso = CreateObject(&quot;Scripting.FileSystemObject&quot;)\nSet relDoc = CreateObject(&quot;Microsoft.XMLDOM&quot;)\n\nIf (Wscript.Arguments.Count = 0) Then\n MsgBox &quot;Please provide the .accdb database file&quot;, vbExclamation, &quot;Error&quot;\n Wscript.Quit()\nEnd If\n\nACCDBFilename = fso.GetAbsolutePathName(Wscript.Arguments(0))\nIf (Wscript.Arguments.Count = 1) Then\n sPath = &quot;&quot;\nElse\n sPath = Wscript.Arguments(1)\nEnd If\n\n\nimportModulesTxt ACCDBFilename, sPath\n\nIf (Err &lt;&gt; 0) And (Err.Description &lt;&gt; Null) Then\n MsgBox Err.Description, vbExclamation, &quot;Error&quot;\n Err.Clear\nEnd If\n\n\nFunction importModulesTxt(ACCDBFilename, sImportpath)\n Dim myComponent, sModuleType, sTempname, sOutstring\n\n ' Build file and pathnames\n Dim myType, myName, myPath\n myType = fso.GetExtensionName(ACCDBFilename)\n myName = fso.GetBaseName(ACCDBFilename)\n myPath = fso.GetParentFolderName(ACCDBFilename)\n\n ' if no path was given as argument, use a relative directory\n If (sImportpath = &quot;&quot;) Then\n sImportpath = myPath &amp; &quot;\\Source\\&quot;\n End If\n\n ' check for existing file and ask to overwrite with the stub\n If fso.FileExists(ACCDBFilename) Then\n Wscript.StdOut.Write ACCDBFilename &amp; &quot; already exists. Overwrite? (y/n) &quot;\n Dim sInput\n sInput = Wscript.StdIn.Read(1)\n If (sInput &lt;&gt; &quot;y&quot;) Then\n Wscript.Quit\n Else\n If fso.FileExists(ACCDBFilename &amp; &quot;.bak&quot;) Then\n fso.DeleteFile (ACCDBFilename &amp; &quot;.bak&quot;)\n End If\n fso.MoveFile ACCDBFilename, ACCDBFilename &amp; &quot;.bak&quot;\n End If\n End If\n\n Wscript.Echo &quot;starting Access...&quot;\n Dim oApplication\n Set oApplication = CreateObject(&quot;Access.Application&quot;)\n Wscript.Echo &quot;Opening &quot; &amp; ACCDBFilename\n If (Right(ACCDBFilename, 4) = &quot;.adp&quot;) Then\n oApplication.CreateAccessProject ACCDBFilename\n Else\n oApplication.NewCurrentDatabase ACCDBFilename\n End If\n oApplication.Visible = False\n\n Dim folder\n Set folder = fso.GetFolder(sImportpath)\n\n 'load each file from the import path into the stub\n Dim myFile, objectname, objecttype\n For Each myFile In folder.Files\n objectname = fso.GetBaseName(myFile.Name) 'get rid of .txt extension\n objecttype = fso.GetExtensionName(objectname)\n objectname = fso.GetBaseName(objectname)\n\n Select Case objecttype\n Case &quot;form&quot;\n Wscript.Echo &quot;Importing FORM from file &quot; &amp; myFile.Name\n oApplication.LoadFromText acForm, objectname, myFile.Path\n Case &quot;module&quot;\n Wscript.Echo &quot;Importing MODULE from file &quot; &amp; myFile.Name\n oApplication.LoadFromText acModule, objectname, myFile.Path\n Case &quot;macro&quot;\n Wscript.Echo &quot;Importing MACRO from file &quot; &amp; myFile.Name\n oApplication.LoadFromText acMacro, objectname, myFile.Path\n Case &quot;report&quot;\n Wscript.Echo &quot;Importing REPORT from file &quot; &amp; myFile.Name\n oApplication.LoadFromText acReport, objectname, myFile.Path\n Case &quot;query&quot;\n Wscript.Echo &quot;Importing QUERY from file &quot; &amp; myFile.Name\n oApplication.LoadFromText acQuery, objectname, myFile.Path\n Case &quot;table&quot;\n Wscript.Echo &quot;Importing TABLE from file &quot; &amp; myFile.Name\n oApplication.ImportXml myFile.Path, acStructureOnly\n Case &quot;rel&quot;\n Wscript.Echo &quot;Found RELATIONSHIPS file &quot; &amp; myFile.Name &amp; &quot; ... opening, it will be processed after everything else has been imported&quot;\n relDoc.Load (myFile.Path)\n End Select\n Next\n\n If relDoc.readyState Then\n Wscript.Echo &quot;Preparing to build table dependencies...&quot;\n Dim xmlRel, xmlField, accessRel, relTable, relName, relFTable, relAttr, i\n For Each xmlRel In relDoc.SelectNodes(&quot;/Relations/Relation&quot;) 'loop through every Relation node inside .xml file\n relName = xmlRel.SelectSingleNode(&quot;Name&quot;).Text\n relTable = xmlRel.SelectSingleNode(&quot;Table&quot;).Text\n relFTable = xmlRel.SelectSingleNode(&quot;ForeignTable&quot;).Text\n relAttr = xmlRel.SelectSingleNode(&quot;Attributes&quot;).Text\n\n 'remove any possible conflicting relations or indexes\n On Error Resume Next\n oApplication.CurrentDb.Relations.Delete (relName)\n oApplication.CurrentDb.TableDefs(relTable).Indexes.Delete (relName)\n oApplication.CurrentDb.TableDefs(relFTable).Indexes.Delete (relName)\n On Error GoTo 0\n\n Wscript.Echo &quot;Creating relation &quot; &amp; relName &amp; &quot; between tables &quot; &amp; relTable &amp; &quot; -&gt; &quot; &amp; relFTable\n Set accessRel = oApplication.CurrentDb.CreateRelation(relName, relTable, relFTable, relAttr) 'create the relationship object\n\n For Each xmlField In xmlRel.SelectNodes(&quot;Field&quot;) 'in case the relationship works with more fields\n accessRel.Fields.Append accessRel.CreateField(xmlField.SelectSingleNode(&quot;Name&quot;).Text)\n accessRel.Fields(xmlField.SelectSingleNode(&quot;Name&quot;).Text).ForeignName = xmlField.SelectSingleNode(&quot;ForeignName&quot;).Text\n Wscript.Echo &quot; Involving fields &quot; &amp; xmlField.SelectSingleNode(&quot;Name&quot;).Text &amp; &quot; -&gt; &quot; &amp; xmlField.SelectSingleNode(&quot;ForeignName&quot;).Text\n Next\n\n oApplication.CurrentDb.Relations.Append accessRel 'append the newly created relationship to the database\n Wscript.Echo &quot; Relationship added&quot;\n Next\n End If\n\n oApplication.RunCommand acCmdCompileAndSaveAllModules\n oApplication.Quit\nEnd Function\n</code></pre>\n<p>You can execute this script by calling <code>cscript compose.vbs &lt;path to file which should be created&gt; &lt;folder with text files&gt;</code>. In case you omit the second parameter, it will look into 'Source' folder where the database should be created.</p>\n<h3>Import data from text file</h3>\n<p>Replace line 14: <code>const acStructureOnly = 0</code> with <code>const acStructureOnly = 1</code>. This will work only if you have included the data in exported table.</p>\n<h2>Things that are not covered</h2>\n<ol>\n<li>I have tested this only with .accdb files, so with anything else there might be some bugs.</li>\n<li>Setting are not exported, I would recommend creating the Macro that will apply the setting at start of the database.</li>\n<li>Some unknown queries sometimes get exported that are preceded with '~'. I don't know if they are necessary.</li>\n<li>MSAccess object names can contain characters that are <em>invalid for filenames</em> - the script will fail when trying to write them. You may <a href=\"https://stackoverflow.com/a/11778694/548792\">normalize all filenames</a>, but then you cannot import them back.</li>\n</ol>\n<p>One of my other resources while working on this script was <a href=\"https://stackoverflow.com/a/354954/4863744\">this answer</a>, which helped me to figure out how to export relationships.</p>\n" }, { "answer_id": 46453438, "author": "CTristan", "author_id": 1410257, "author_profile": "https://Stackoverflow.com/users/1410257", "pm_score": 0, "selected": false, "text": "<p>For anyone stuck with Access 97, I was not able to get the other answers to work. Using a combination of <a href=\"https://stackoverflow.com/a/211210/1410257\">Oliver's</a> and <a href=\"https://stackoverflow.com/a/1849498/1410257\">DaveParillo's</a> excellent answers and making some modifications, I was able to get the scripts working with our Access 97 databases. It's also a bit more user-friendly since it asks which folder to place the files.</p>\n\n<p>AccessExport.vbs:</p>\n\n<pre><code>' Converts all modules, classes, forms and macros from an Access file (.mdb) &lt;input file&gt; to\n' text and saves the results in separate files to &lt;path&gt;. Requires Microsoft Access.\nOption Explicit\n\nConst acQuery = 1\nConst acForm = 2\nConst acModule = 5\nConst acMacro = 4\nConst acReport = 3\nConst acCmdCompactDatabase = 4\nConst TemporaryFolder = 2\n\nDim strMDBFileName : strMDBFileName = SelectDatabaseFile\nDim strExportPath : strExportPath = SelectExportFolder\nCreateExportFolders(strExportPath)\nDim objProgressWindow\nDim strOverallProgress\nCreateProgressWindow objProgressWindow\nDim strTempMDBFileName\nCopyToTempDatabase strMDBFileName, strTempMDBFileName, strOverallProgress\nDim objAccess\nDim objDatabase\nOpenAccessDatabase objAccess, objDatabase, strTempMDBFileName, strOverallProgress\nExportQueries objAccess, objDatabase, objProgressWindow, strExportPath, strOverallProgress\nExportForms objAccess, objDatabase, objProgressWindow, strExportPath, strOverallProgress\nExportReports objAccess, objDatabase, objProgressWindow, strExportPath, strOverallProgress\nExportMacros objAccess, objDatabase, objProgressWindow, strExportPath, strOverallProgress\nExportModules objAccess, objDatabase, objProgressWindow, strExportPath, strOverallProgress\nobjAccess.CloseCurrentDatabase\nobjAccess.Quit\nDeleteTempDatabase strTempMDBFileName, strOverallProgress\nobjProgressWindow.Quit\nMsgBox \"Successfully exported database.\"\n\nPrivate Function SelectDatabaseFile()\n MsgBox \"Please select the Access database to export.\"\n Dim objFileOpen : Set objFileOpen = CreateObject(\"SAFRCFileDlg.FileOpen\")\n If objFileOpen.OpenFileOpenDlg Then\n SelectDatabaseFile = objFileOpen.FileName\n Else\n WScript.Quit()\n End If\nEnd Function\n\nPrivate Function SelectExportFolder()\n Dim objShell : Set objShell = CreateObject(\"Shell.Application\")\n SelectExportFolder = objShell.BrowseForFolder(0, \"Select folder to export the database to:\", 0, \"\").self.path &amp; \"\\\"\nEnd Function\n\nPrivate Sub CreateExportFolders(strExportPath)\n Dim objFileSystem : Set objFileSystem = CreateObject(\"Scripting.FileSystemObject\")\n MsgBox \"Existing folders from a previous Access export under \" &amp; strExportPath &amp; \" will be deleted!\"\n If objFileSystem.FolderExists(strExportPath &amp; \"Queries\\\") Then\n objFileSystem.DeleteFolder strExportPath &amp; \"Queries\", true\n End If\n objFileSystem.CreateFolder(strExportPath &amp; \"Queries\\\")\n If objFileSystem.FolderExists(strExportPath &amp; \"Forms\\\") Then\n objFileSystem.DeleteFolder strExportPath &amp; \"Forms\", true\n End If\n objFileSystem.CreateFolder(strExportPath &amp; \"Forms\\\")\n If objFileSystem.FolderExists(strExportPath &amp; \"Reports\\\") Then\n objFileSystem.DeleteFolder strExportPath &amp; \"Reports\", true\n End If\n objFileSystem.CreateFolder(strExportPath &amp; \"Reports\\\")\n If objFileSystem.FolderExists(strExportPath &amp; \"Macros\\\") Then\n objFileSystem.DeleteFolder strExportPath &amp; \"Macros\", true\n End If\n objFileSystem.CreateFolder(strExportPath &amp; \"Macros\\\")\n If objFileSystem.FolderExists(strExportPath &amp; \"Modules\\\") Then\n objFileSystem.DeleteFolder strExportPath &amp; \"Modules\", true\n End If\n objFileSystem.CreateFolder(strExportPath &amp; \"Modules\\\")\nEnd Sub\n\nPrivate Sub CreateProgressWindow(objProgressWindow)\n Set objProgressWindow = CreateObject (\"InternetExplorer.Application\")\n objProgressWindow.Navigate \"about:blank\"\n objProgressWindow.ToolBar = 0\n objProgressWindow.StatusBar = 0\n objProgressWindow.Width = 320\n objProgressWindow.Height = 240\n objProgressWindow.Visible = 1\n objProgressWindow.Document.Title = \"Access export in progress\"\nEnd Sub\n\nPrivate Sub CopyToTempDatabase(strMDBFileName, strTempMDBFileName, strOverallProgress)\n strOverallProgress = strOverallProgress &amp; \"Copying to temporary database...&lt;br/&gt;\"\n Dim objFileSystem : Set objFileSystem = CreateObject(\"Scripting.FileSystemObject\")\n strTempMDBFileName = objFileSystem.GetSpecialFolder(TemporaryFolder) &amp; \"\\\" &amp; objFileSystem.GetBaseName(strMDBFileName) &amp; \"_temp.mdb\"\n objFileSystem.CopyFile strMDBFileName, strTempMDBFileName\nEnd Sub\n\nPrivate Sub OpenAccessDatabase(objAccess, objDatabase, strTempMDBFileName, strOverallProgress)\n strOverallProgress = strOverallProgress &amp; \"Compacting temporary database...&lt;br/&gt;\"\n Set objAccess = CreateObject(\"Access.Application\")\n objAccess.Visible = false\n CompactAccessDatabase objAccess, strTempMDBFileName\n strOverallProgress = strOverallProgress &amp; \"Opening temporary database...&lt;br/&gt;\"\n objAccess.OpenCurrentDatabase strTempMDBFileName\n Set objDatabase = objAccess.CurrentDb\nEnd Sub\n\n' Sometimes the Compact Database command errors out, and it's not serious if the database isn't compacted first.\nPrivate Sub CompactAccessDatabase(objAccess, strTempMDBFileName)\n On Error Resume Next\n Dim objFileSystem : Set objFileSystem = CreateObject(\"Scripting.FileSystemObject\")\n objAccess.DbEngine.CompactDatabase strTempMDBFileName, strTempMDBFileName &amp; \"_\"\n objFileSystem.CopyFile strTempMDBFileName &amp; \"_\", strTempMDBFileName\n objFileSystem.DeleteFile strTempMDBFileName &amp; \"_\"\nEnd Sub\n\nPrivate Sub ExportQueries(objAccess, objDatabase, objProgressWindow, strExportPath, strOverallProgress)\n strOverallProgress = strOverallProgress &amp; \"Exporting Queries (Step 1 of 5)...&lt;br/&gt;\"\n Dim counter\n For counter = 0 To objDatabase.QueryDefs.Count - 1\n objProgressWindow.Document.Body.InnerHTML = strOverallProgress &amp; counter + 1 &amp; \" of \" &amp; objDatabase.QueryDefs.Count\n objAccess.SaveAsText acQuery, objDatabase.QueryDefs(counter).Name, strExportPath &amp; \"Queries\\\" &amp; Clean(objDatabase.QueryDefs(counter).Name) &amp; \".sql\"\n Next\nEnd Sub\n\nPrivate Sub ExportForms(objAccess, objDatabase, objProgressWindow, strExportPath, strOverallProgress)\n strOverallProgress = strOverallProgress &amp; \"Exporting Forms (Step 2 of 5)...&lt;br/&gt;\"\n Dim counter : counter = 1\n Dim objContainer : Set objContainer = objDatabase.Containers(\"Forms\")\n Dim objDocument\n For Each objDocument In objContainer.Documents\n objProgressWindow.Document.Body.InnerHTML = strOverallProgress &amp; counter &amp; \" of \" &amp; objContainer.Documents.Count\n counter = counter + 1\n objAccess.SaveAsText acForm, objDocument.Name, strExportPath &amp; \"Forms\\\" &amp; Clean(objDocument.Name) &amp; \".form\"\n objAccess.DoCmd.Close acForm, objDocument.Name\n Next\nEnd Sub\n\nPrivate Sub ExportReports(objAccess, objDatabase, objProgressWindow, strExportPath, strOverallProgress)\n strOverallProgress = strOverallProgress &amp; \"Exporting Reports (Step 3 of 5)...&lt;br/&gt;\"\n Dim counter : counter = 1\n Dim objContainer : Set objContainer = objDatabase.Containers(\"Reports\")\n Dim objDocument\n For Each objDocument In objContainer.Documents\n objProgressWindow.Document.Body.InnerHTML = strOverallProgress &amp; counter &amp; \" of \" &amp; objContainer.Documents.Count\n counter = counter + 1\n objAccess.SaveAsText acReport, objDocument.Name, strExportPath &amp; \"Reports\\\" &amp; Clean(objDocument.Name) &amp; \".report\"\n Next\nEnd Sub\n\nPrivate Sub ExportMacros(objAccess, objDatabase, objProgressWindow, strExportPath, strOverallProgress)\n strOverallProgress = strOverallProgress &amp; \"Exporting Macros (Step 4 of 5)...&lt;br/&gt;\"\n Dim counter : counter = 1\n Dim objContainer : Set objContainer = objDatabase.Containers(\"Scripts\")\n Dim objDocument\n For Each objDocument In objContainer.Documents\n objProgressWindow.Document.Body.InnerHTML = strOverallProgress &amp; counter &amp; \" of \" &amp; objContainer.Documents.Count\n counter = counter + 1\n objAccess.SaveAsText acMacro, objDocument.Name, strExportPath &amp; \"Macros\\\" &amp; Clean(objDocument.Name) &amp; \".macro\"\n Next\nEnd Sub\n\nPrivate Sub ExportModules(objAccess, objDatabase, objProgressWindow, strExportPath, strOverallProgress)\n strOverallProgress = strOverallProgress &amp; \"Exporting Modules (Step 5 of 5)...&lt;br/&gt;\"\n Dim counter : counter = 1\n Dim objContainer : Set objContainer = objDatabase.Containers(\"Modules\")\n Dim objDocument\n For Each objDocument In objContainer.Documents\n objProgressWindow.Document.Body.InnerHTML = strOverallProgress &amp; counter &amp; \" of \" &amp; objContainer.Documents.Count\n counter = counter + 1\n objAccess.SaveAsText acModule, objDocument.Name, strExportPath &amp; \"Modules\\\" &amp; Clean(objDocument.Name) &amp; \".module\"\n Next\nEnd Sub\n\nPrivate Sub DeleteTempDatabase(strTempMDBFileName, strOverallProgress)\n On Error Resume Next\n strOverallProgress = strOverallProgress &amp; \"Deleting temporary database...&lt;br/&gt;\"\n Dim objFileSystem : Set objFileSystem = CreateObject(\"Scripting.FileSystemObject\")\n objFileSystem.DeleteFile strTempMDBFileName, true\nEnd Sub\n\n' Windows doesn't like certain characters, so we have to filter those out of the name when exporting\nPrivate Function Clean(strInput)\n Dim objRegexp : Set objRegexp = New RegExp\n objRegexp.IgnoreCase = True\n objRegexp.Global = True\n objRegexp.Pattern = \"[\\\\/:*?\"\"&lt;&gt;|]\"\n Dim strOutput\n If objRegexp.Test(strInput) Then\n strOutput = objRegexp.Replace(strInput, \"\")\n MsgBox strInput &amp; \" is being exported as \" &amp; strOutput\n Else\n strOutput = strInput\n End If\n Clean = strOutput\nEnd Function\n</code></pre>\n\n<p>And for importing files into the database, should you need to recreate the database from scratch or you wish to modify files outside of Access for some reason.</p>\n\n<p>AccessImport.vbs:</p>\n\n<pre><code>' Imports all of the queries, forms, reports, macros, and modules from text\n' files to an Access file (.mdb). Requires Microsoft Access.\nOption Explicit\n\nconst acQuery = 1\nconst acForm = 2\nconst acModule = 5\nconst acMacro = 4\nconst acReport = 3\nconst acCmdCompileAndSaveAllModules = &amp;H7E\n\nDim strMDBFilename : strMDBFilename = SelectDatabaseFile\nCreateBackup strMDBFilename\nDim strImportPath : strImportPath = SelectImportFolder\nDim objAccess\nDim objDatabase\nOpenAccessDatabase objAccess, objDatabase, strMDBFilename\nDim objProgressWindow\nDim strOverallProgress\nCreateProgressWindow objProgressWindow\nImportQueries objAccess, objDatabase, objProgressWindow, strImportPath, strOverallProgress\nImportForms objAccess, objDatabase, objProgressWindow, strImportPath, strOverallProgress\nImportReports objAccess, objDatabase, objProgressWindow, strImportPath, strOverallProgress\nImportMacros objAccess, objDatabase, objProgressWindow, strImportPath, strOverallProgress\nImportModules objAccess, objDatabase, objProgressWindow, strImportPath, strOverallProgress\nobjAccess.CloseCurrentDatabase\nobjAccess.Quit\nobjProgressWindow.Quit\nMsgBox \"Successfully imported objects into the database.\"\n\nPrivate Function SelectDatabaseFile()\n MsgBox \"Please select the Access database to import the objects from. ALL EXISTING OBJECTS WITH THE SAME NAME WILL BE OVERWRITTEN!\"\n Dim objFileOpen : Set objFileOpen = CreateObject( \"SAFRCFileDlg.FileOpen\" )\n If objFileOpen.OpenFileOpenDlg Then\n SelectDatabaseFile = objFileOpen.FileName\n Else\n WScript.Quit()\n End If\nEnd Function\n\nPrivate Function SelectImportFolder()\n Dim objShell : Set objShell = WScript.CreateObject(\"Shell.Application\")\n SelectImportFolder = objShell.BrowseForFolder(0, \"Select folder to import the database objects from:\", 0, \"\").self.path &amp; \"\\\"\nEnd Function\n\nPrivate Sub CreateBackup(strMDBFilename)\n Dim objFileSystem : Set objFileSystem = CreateObject(\"Scripting.FileSystemObject\")\n objFileSystem.CopyFile strMDBFilename, strMDBFilename &amp; \".bak\"\nEnd Sub\n\nPrivate Sub OpenAccessDatabase(objAccess, objDatabase, strMDBFileName)\n Set objAccess = CreateObject(\"Access.Application\")\n objAccess.OpenCurrentDatabase strMDBFilename\n objAccess.Visible = false\n Set objDatabase = objAccess.CurrentDb\nEnd Sub\n\nPrivate Sub CreateProgressWindow(ByRef objProgressWindow)\n Set objProgressWindow = CreateObject (\"InternetExplorer.Application\")\n objProgressWindow.Navigate \"about:blank\"\n objProgressWindow.ToolBar = 0\n objProgressWindow.StatusBar = 0\n objProgressWindow.Width = 320\n objProgressWindow.Height = 240\n objProgressWindow.Visible = 1\n objProgressWindow.Document.Title = \"Access import in progress\"\nEnd Sub\n\nPrivate Sub ImportQueries(objAccess, objDatabase, objProgressWindow, strImportPath, strOverallProgress)\n strOverallProgress = \"Importing Queries (Step 1 of 5)...&lt;br/&gt;\"\n Dim counter : counter = 0\n Dim folder : Set folder = objFileSystem.GetFolder(strImportPath &amp; \"Queries\\\")\n Dim objFileSystem : Set objFileSystem = CreateObject(\"Scripting.FileSystemObject\")\n Dim file\n Dim strQueryName\n For Each file in folder.Files\n objProgressWindow.Document.Body.InnerHTML = strOverallProgress &amp; counter + 1 &amp; \" of \" &amp; folder.Files.Count\n strQueryName = objFileSystem.GetBaseName(file.Name)\n objAccess.LoadFromText acQuery, strQueryName, file.Path\n counter = counter + 1\n Next\nEnd Sub\n\nPrivate Sub ImportForms(objAccess, objDatabase, objProgressWindow, strImportPath, strOverallProgress)\n strOverallProgress = strOverallProgress &amp; \"Importing Forms (Step 2 of 5)...&lt;br/&gt;\"\n Dim counter : counter = 0\n Dim folder : Set folder = objFileSystem.GetFolder(strImportPath &amp; \"Forms\\\")\n Dim objFileSystem : Set objFileSystem = CreateObject(\"Scripting.FileSystemObject\")\n Dim file\n Dim strFormName\n For Each file in folder.Files\n objProgressWindow.Document.Body.InnerHTML = strOverallProgress &amp; counter + 1 &amp; \" of \" &amp; folder.Files.Count\n strFormName = objFileSystem.GetBaseName(file.Name)\n objAccess.LoadFromText acForm, strFormName, file.Path\n counter = counter + 1\n Next\nEnd Sub\n\nPrivate Sub ImportReports(objAccess, objDatabase, objProgressWindow, strImportPath, strOverallProgress)\n strOverallProgress = strOverallProgress &amp; \"Importing Reports (Step 3 of 5)...&lt;br/&gt;\"\n Dim counter : counter = 0\n Dim folder : Set folder = objFileSystem.GetFolder(strImportPath &amp; \"Reports\\\")\n Dim objFileSystem : Set objFileSystem = CreateObject(\"Scripting.FileSystemObject\")\n Dim file\n Dim strReportName\n For Each file in folder.Files\n objProgressWindow.Document.Body.InnerHTML = strOverallProgress &amp; counter + 1 &amp; \" of \" &amp; folder.Files.Count\n strReportName = objFileSystem.GetBaseName(file.Name)\n objAccess.LoadFromText acReport, strReportName, file.Path\n counter = counter + 1\n Next\nEnd Sub\n\nPrivate Sub ImportMacros(objAccess, objDatabase, objProgressWindow, strImportPath, strOverallProgress)\n strOverallProgress = strOverallProgress &amp; \"Importing Macros (Step 4 of 5)...&lt;br/&gt;\"\n Dim counter : counter = 0\n Dim folder : Set folder = objFileSystem.GetFolder(strImportPath &amp; \"Macros\\\")\n Dim objFileSystem : Set objFileSystem = CreateObject(\"Scripting.FileSystemObject\")\n Dim file\n Dim strMacroName\n For Each file in folder.Files\n objProgressWindow.Document.Body.InnerHTML = strOverallProgress &amp; counter + 1 &amp; \" of \" &amp; folder.Files.Count\n strMacroName = objFileSystem.GetBaseName(file.Name)\n objAccess.LoadFromText acMacro, strMacroName, file.Path\n counter = counter + 1\n Next\nEnd Sub\n\nPrivate Sub ImportModules(objAccess, objDatabase, objProgressWindow, strImportPath, strOverallProgress)\n strOverallProgress = strOverallProgress &amp; \"Importing Modules (Step 5 of 5)...&lt;br/&gt;\"\n Dim counter : counter = 0\n Dim folder : Set folder = objFileSystem.GetFolder(strImportPath &amp; \"Modules\\\")\n Dim objFileSystem : Set objFileSystem = CreateObject(\"Scripting.FileSystemObject\")\n Dim file\n Dim strModuleName\n For Each file in folder.Files\n objProgressWindow.Document.Body.InnerHTML = strOverallProgress &amp; counter + 1 &amp; \" of \" &amp; folder.Files.Count\n strModuleName = objFileSystem.GetBaseName(file.Name)\n objAccess.LoadFromText acModule, strModuleName, file.Path\n counter = counter + 1\n Next\n\n ' We need to compile the database whenever any module code changes.\n If Not objAccess.IsCompiled Then\n objAccess.RunCommand acCmdCompileAndSaveAllModules\n End If\nEnd Sub\n</code></pre>\n" }, { "answer_id": 72054343, "author": "Daniel Seeger", "author_id": 10711858, "author_profile": "https://Stackoverflow.com/users/10711858", "pm_score": 0, "selected": false, "text": "<p>I am using OASIS-SVN from <a href=\"https://dev2dev.de/\" rel=\"nofollow noreferrer\">https://dev2dev.de/</a>\nThis is not for free but for a small price.</p>\n<p>It exports code, qrys, frms etc. to a folder.\nFrom there I am using Git.</p>\n" } ]
2008/10/09
[ "https://Stackoverflow.com/questions/187506", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1753/" ]
I'm involved with updating an Access solution. It has a good amount of VBA, a number of queries, a small amount of tables, and a few forms for data entry & report generation. It's an ideal candidate for Access. I want to make changes to the table design, the VBA, the queries, and the forms. How can I track my changes with version control? (we use Subversion, but this goes for any flavor) I can stick the entire mdb in subversion, but that will be storing a binary file, and I won't be able to tell that I just changed one line of VBA code. I thought about copying the VBA code to separate files, and saving those, but I could see those quickly getting out of sync with what's in the database.
We wrote our own script in VBScript, that uses the undocumented Application.SaveAsText() in Access to export all code, form, macro and report modules. Here it is, it should give you some pointers. (Beware: some of the messages are in german, but you can easily change that.) EDIT: To summarize various comments below: ~~Our Project assumes an .adp-file. In order to get this work with .mdb/.accdb, you have to change OpenAccessProject() to OpenCurrentDatabase()~~. (Updated to use `OpenAccessProject()` if it sees a .adp extension, else use `OpenCurrentDatabase()`.) decompose.vbs: ```vb ' Usage: ' CScript decompose.vbs <input file> <path> ' Converts all modules, classes, forms and macros from an Access Project file (.adp) <input file> to ' text and saves the results in separate files to <path>. Requires Microsoft Access. ' Option Explicit const acForm = 2 const acModule = 5 const acMacro = 4 const acReport = 3 ' BEGIN CODE Dim fso Set fso = CreateObject("Scripting.FileSystemObject") dim sADPFilename If (WScript.Arguments.Count = 0) then MsgBox "Bitte den Dateinamen angeben!", vbExclamation, "Error" Wscript.Quit() End if sADPFilename = fso.GetAbsolutePathName(WScript.Arguments(0)) Dim sExportpath If (WScript.Arguments.Count = 1) then sExportpath = "" else sExportpath = WScript.Arguments(1) End If exportModulesTxt sADPFilename, sExportpath If (Err <> 0) and (Err.Description <> NULL) Then MsgBox Err.Description, vbExclamation, "Error" Err.Clear End If Function exportModulesTxt(sADPFilename, sExportpath) Dim myComponent Dim sModuleType Dim sTempname Dim sOutstring dim myType, myName, myPath, sStubADPFilename myType = fso.GetExtensionName(sADPFilename) myName = fso.GetBaseName(sADPFilename) myPath = fso.GetParentFolderName(sADPFilename) If (sExportpath = "") then sExportpath = myPath & "\Source\" End If sStubADPFilename = sExportpath & myName & "_stub." & myType WScript.Echo "copy stub to " & sStubADPFilename & "..." On Error Resume Next fso.CreateFolder(sExportpath) On Error Goto 0 fso.CopyFile sADPFilename, sStubADPFilename WScript.Echo "starting Access..." Dim oApplication Set oApplication = CreateObject("Access.Application") WScript.Echo "opening " & sStubADPFilename & " ..." If (Right(sStubADPFilename,4) = ".adp") Then oApplication.OpenAccessProject sStubADPFilename Else oApplication.OpenCurrentDatabase sStubADPFilename End If oApplication.Visible = false dim dctDelete Set dctDelete = CreateObject("Scripting.Dictionary") WScript.Echo "exporting..." Dim myObj For Each myObj In oApplication.CurrentProject.AllForms WScript.Echo " " & myObj.fullname oApplication.SaveAsText acForm, myObj.fullname, sExportpath & "\" & myObj.fullname & ".form" oApplication.DoCmd.Close acForm, myObj.fullname dctDelete.Add "FO" & myObj.fullname, acForm Next For Each myObj In oApplication.CurrentProject.AllModules WScript.Echo " " & myObj.fullname oApplication.SaveAsText acModule, myObj.fullname, sExportpath & "\" & myObj.fullname & ".bas" dctDelete.Add "MO" & myObj.fullname, acModule Next For Each myObj In oApplication.CurrentProject.AllMacros WScript.Echo " " & myObj.fullname oApplication.SaveAsText acMacro, myObj.fullname, sExportpath & "\" & myObj.fullname & ".mac" dctDelete.Add "MA" & myObj.fullname, acMacro Next For Each myObj In oApplication.CurrentProject.AllReports WScript.Echo " " & myObj.fullname oApplication.SaveAsText acReport, myObj.fullname, sExportpath & "\" & myObj.fullname & ".report" dctDelete.Add "RE" & myObj.fullname, acReport Next WScript.Echo "deleting..." dim sObjectname For Each sObjectname In dctDelete WScript.Echo " " & Mid(sObjectname, 3) oApplication.DoCmd.DeleteObject dctDelete(sObjectname), Mid(sObjectname, 3) Next oApplication.CloseCurrentDatabase oApplication.CompactRepair sStubADPFilename, sStubADPFilename & "_" oApplication.Quit fso.CopyFile sStubADPFilename & "_", sStubADPFilename fso.DeleteFile sStubADPFilename & "_" End Function Public Function getErr() Dim strError strError = vbCrLf & "----------------------------------------------------------------------------------------------------------------------------------------" & vbCrLf & _ "From " & Err.source & ":" & vbCrLf & _ " Description: " & Err.Description & vbCrLf & _ " Code: " & Err.Number & vbCrLf getErr = strError End Function ``` If you need a clickable Command, instead of using the command line, create a file named "decompose.cmd" with ```vb cscript decompose.vbs youraccessapplication.adp ``` By default, all exported files go into a "Scripts" subfolder of your Access-application. The .adp/mdb file is also copied to this location (with a "stub" suffix) and stripped of all the exported modules, making it really small. You MUST checkin this stub with the source-files, because most access settings and custom menu-bars cannot be exported any other way. Just be sure to commit changes to this file only, if you really changed some setting or menu. Note: If you have any Autoexec-Makros defined in your Application, you may have to hold the Shift-key when you invoke the decompose to prevent it from executing and interfering with the export! Of course, there is also the reverse script, to build the Application from the "Source"-Directory: compose.vbs: ```vb ' Usage: ' WScript compose.vbs <file> <path> ' Converts all modules, classes, forms and macros in a directory created by "decompose.vbs" ' and composes then into an Access Project file (.adp). This overwrites any existing Modules with the ' same names without warning!!! ' Requires Microsoft Access. Option Explicit const acForm = 2 const acModule = 5 const acMacro = 4 const acReport = 3 Const acCmdCompileAndSaveAllModules = &H7E ' BEGIN CODE Dim fso Set fso = CreateObject("Scripting.FileSystemObject") dim sADPFilename If (WScript.Arguments.Count = 0) then MsgBox "Please enter the file name!", vbExclamation, "Error" Wscript.Quit() End if sADPFilename = fso.GetAbsolutePathName(WScript.Arguments(0)) Dim sPath If (WScript.Arguments.Count = 1) then sPath = "" else sPath = WScript.Arguments(1) End If importModulesTxt sADPFilename, sPath If (Err <> 0) and (Err.Description <> NULL) Then MsgBox Err.Description, vbExclamation, "Error" Err.Clear End If Function importModulesTxt(sADPFilename, sImportpath) Dim myComponent Dim sModuleType Dim sTempname Dim sOutstring ' Build file and pathnames dim myType, myName, myPath, sStubADPFilename myType = fso.GetExtensionName(sADPFilename) myName = fso.GetBaseName(sADPFilename) myPath = fso.GetParentFolderName(sADPFilename) ' if no path was given as argument, use a relative directory If (sImportpath = "") then sImportpath = myPath & "\Source\" End If sStubADPFilename = sImportpath & myName & "_stub." & myType ' check for existing file and ask to overwrite with the stub if (fso.FileExists(sADPFilename)) Then WScript.StdOut.Write sADPFilename & " exists. Overwrite? (y/n) " dim sInput sInput = WScript.StdIn.Read(1) if (sInput <> "y") Then WScript.Quit end if fso.CopyFile sADPFilename, sADPFilename & ".bak" end if fso.CopyFile sStubADPFilename, sADPFilename ' launch MSAccess WScript.Echo "starting Access..." Dim oApplication Set oApplication = CreateObject("Access.Application") WScript.Echo "opening " & sADPFilename & " ..." If (Right(sStubADPFilename,4) = ".adp") Then oApplication.OpenAccessProject sADPFilename Else oApplication.OpenCurrentDatabase sADPFilename End If oApplication.Visible = false Dim folder Set folder = fso.GetFolder(sImportpath) ' load each file from the import path into the stub Dim myFile, objectname, objecttype for each myFile in folder.Files objecttype = fso.GetExtensionName(myFile.Name) objectname = fso.GetBaseName(myFile.Name) WScript.Echo " " & objectname & " (" & objecttype & ")" if (objecttype = "form") then oApplication.LoadFromText acForm, objectname, myFile.Path elseif (objecttype = "bas") then oApplication.LoadFromText acModule, objectname, myFile.Path elseif (objecttype = "mac") then oApplication.LoadFromText acMacro, objectname, myFile.Path elseif (objecttype = "report") then oApplication.LoadFromText acReport, objectname, myFile.Path end if next oApplication.RunCommand acCmdCompileAndSaveAllModules oApplication.Quit End Function Public Function getErr() Dim strError strError = vbCrLf & "----------------------------------------------------------------------------------------------------------------------------------------" & vbCrLf & _ "From " & Err.source & ":" & vbCrLf & _ " Description: " & Err.Description & vbCrLf & _ " Code: " & Err.Number & vbCrLf getErr = strError End Function ``` Again, this goes with a companion "compose.cmd" containing: ```vb cscript compose.vbs youraccessapplication.adp ``` It asks you to confirm overwriting your current application and first creates a backup, if you do. It then collects all source-files in the Source-Directory and re-inserts them into the stub. Have Fun!
187,515
<p>I have two arrays. One contains <code>id=&gt;count</code> and the other contains <code>id=&gt;name</code>. I'm trying to produce a single array that is <code>name=&gt;count</code>. Any suggestions on a straightforward way to do this?</p> <p>I have looked at the <a href="http://us2.php.net/manual/en/ref.array.php" rel="nofollow noreferrer">Array Functions in the PHP Manual</a> and didn't see anything that stood out as doing what I want, so I'm guessing I'll need a combination of functions, but I'm having trouble coming up with something that's not convoluted.</p>
[ { "answer_id": 187533, "author": "KernelM", "author_id": 22328, "author_profile": "https://Stackoverflow.com/users/22328", "pm_score": 3, "selected": true, "text": "<p>Something like:</p>\n\n<pre><code>foreach($countA as $id =&gt; $count)\n{\n $newArray[$nameA[$id]] = $count;\n}\n</code></pre>\n\n<p>This does assume that the keys are in correspondence between the two arrays, since your requirements are ambiguous otherwise.</p>\n" }, { "answer_id": 187534, "author": "Andrew Moore", "author_id": 26210, "author_profile": "https://Stackoverflow.com/users/26210", "pm_score": 2, "selected": false, "text": "<p>Use <a href=\"http://ca.php.net/manual/en/function.array-combine.php\" rel=\"nofollow noreferrer\">array_combine</a>...</p>\n\n<pre><code>$countArray = array(0 =&gt; 1, 1 =&gt; 5);\n$namesArray = array(0 =&gt; \"Bob\", 1 =&gt; \"Alice\");\n\n$assocArray = array_combine($namesArray, $countArray);\n</code></pre>\n\n<p><strong>Edit:</strong> Here is a revised solution for the new requirements expressed in comment #2</p>\n\n<pre><code>$assocArray = array();\nforeach($namesArray as $id =&gt; $name) {\n $assocArray[$name] = (array_key_exists($id, $countArray)) ? $countArray[$id] : 0;\n}\n</code></pre>\n" } ]
2008/10/09
[ "https://Stackoverflow.com/questions/187515", "https://Stackoverflow.com", "https://Stackoverflow.com/users/572/" ]
I have two arrays. One contains `id=>count` and the other contains `id=>name`. I'm trying to produce a single array that is `name=>count`. Any suggestions on a straightforward way to do this? I have looked at the [Array Functions in the PHP Manual](http://us2.php.net/manual/en/ref.array.php) and didn't see anything that stood out as doing what I want, so I'm guessing I'll need a combination of functions, but I'm having trouble coming up with something that's not convoluted.
Something like: ``` foreach($countA as $id => $count) { $newArray[$nameA[$id]] = $count; } ``` This does assume that the keys are in correspondence between the two arrays, since your requirements are ambiguous otherwise.
187,526
<p>I'd like to be able to run my aliases from my .bashrc in the "Run Application" dialog that comes up when you hit Alt+F2 in Ubuntu/Gnome.</p> <p>Does anyone know how to do this?</p>
[ { "answer_id": 198830, "author": "Anders Eurenius", "author_id": 1421, "author_profile": "https://Stackoverflow.com/users/1421", "pm_score": 3, "selected": true, "text": "<p><a href=\"http://www.freedesktop.org/wiki/Specifications\" rel=\"nofollow noreferrer\">http://www.freedesktop.org/wiki/Specifications</a> is probably a good place to start. I find these quite hard to follow most of the time, but sometimes you can figure it out. Specifically, the \"Desktop Entry Specification\".</p>\n\n<p>Also, I don't think you'll be able to use any aliases from <code>.bashrc</code>, at least not without writing some kind of wrapper script. I think it needs to be an executable file. Of course, you could just use the good old symlinks- to- same + what's- my- name trick...</p>\n\n<p>(Which, for reference, goes like this:</p>\n\n<ol>\n<li>Make a script which uses its own name as a parameter.</li>\n<li>Make symlinks to said script using the parameter values as the link names.)</li>\n</ol>\n\n<hr>\n\n<h1>Investigating...</h1>\n\n<p>Some casual investigation reveals that creating these is fairly simple if you use Nautilus, (at least the version I have):</p>\n\n<ol>\n<li>Bring up the context menu for some random file, and use \"Open With\"->\"Open with Other Application\".</li>\n<li>Unfold the \"Use a custom command\" and type in something like:\n\n<ol>\n<li><code>xterm -e 'bash -c \"unzip -l %f; sleep 5\"'</code></li>\n</ol></li>\n<li>This results in\n\n<ol>\n<li>the command being run (so don't type <code>rm -rf</code>)</li>\n<li>a file in <code>~/.local/share/applications/</code> called <code>xterm-usercreated.desktop</code></li>\n</ol></li>\n</ol>\n\n<p>Here at least, I get the follow file:</p>\n\n<pre><code>[Desktop Entry]\nEncoding=UTF-8\nName=xterm\nMimeType=application/zip;\nExec=xterm -e 'bash -c \"unzip -l %f; sleep 5\"' %f\nType=Application\nTerminal=false\nNoDisplay=true\n</code></pre>\n\n<p>4: Looking at the system xterm .desktop I find this:</p>\n\n<pre><code>[Desktop Entry]\nType=Application\nEncoding=UTF-8\nName=XTerm\nGenericName=\nComment=XTerm: terminal emulator for X\nIcon=/usr/share/pixmaps/xterm-color_32x32.xpm\nExec=xterm\nTerminal=false\nCategories=X-Debian-Applications-Terminal-Emulators;\n</code></pre>\n\n<p>5: Editing the .usercreated.desktop file to this:</p>\n\n<pre><code>[Desktop Entry] \nType=Application \nEncoding=UTF-8 \nName=xtermz \nExec=xterm -e 'bash -c \"unzip -l %f; sleep 5\"' %f \nTerminal=false \nCategories=X-Local-WTF \n</code></pre>\n\n<p>6: Run xdg-desktop-menu forceupdate --mode user</p>\n\n<p>7: \"xtermz\" now shows up in the list... Success!</p>\n\n<p>8: Yuck! This also makes it appear in the main menu, under \"Other\". Weird!</p>\n\n<hr>\n\n<h2>Some notes:</h2>\n\n<ul>\n<li>In my Debian/testing, <code>xdg-desktop-menu</code> and friends (notably <code>xdg-icon-resource</code>) live in the <code>xdg-utils</code> package.</li>\n<li>You should be able to create a <code>.desktop</code> file from scratch.</li>\n<li>You should be able to install the <code>.desktop</code> file using <code>xdg-desktop-menu install</code> blah blah</li>\n</ul>\n" }, { "answer_id": 234832, "author": "Brad Parks", "author_id": 26510, "author_profile": "https://Stackoverflow.com/users/26510", "pm_score": 1, "selected": false, "text": "<p>I couldn't get the aliases working, so I did this instead:</p>\n\n<ul>\n<li><p>Created a shell script to do what I want and put it in my home dir</p></li>\n<li><p>Put a link to my shell script in <strong>/usr/bin:</strong> </p>\n\n<ul>\n<li>e.g <strong>sudo ln -s ~/bin/MyShellScript.sh /usr/bin/MyShortcutName</strong></li>\n</ul></li>\n</ul>\n\n<p>It works!</p>\n" }, { "answer_id": 2753932, "author": "Nostoc", "author_id": 330870, "author_profile": "https://Stackoverflow.com/users/330870", "pm_score": 1, "selected": false, "text": "<p>I couldn't get the aliases working, so I did this instead:</p>\n\n<p>Created a shell script to do what I want and put it in my home dir\nPut a link to my shell script in /usr/bin:\ne.g <code>sudo ln -s ~/bin/MyShellScript.sh /usr/bin/MyShortcutName</code>\nIt works!</p>\n\n<p>It works because /usr/bin is in your path variable. a better alternative would be to create a hidden directory in your home, like ~/.scripts/</p>\n\n<p>and then add this directory to your path. you can now put all your scripts in that dir.</p>\n" }, { "answer_id": 10000461, "author": "plinio", "author_id": 1311320, "author_profile": "https://Stackoverflow.com/users/1311320", "pm_score": 2, "selected": false, "text": "<p>You can just add a symbolic link to /usr/bin: <code>ln -s &lt;YOUR_ALIAS_PATCH&gt; &lt;ALIAS_NAME&gt;</code></p>\n" }, { "answer_id": 17927472, "author": "gzS", "author_id": 2603364, "author_profile": "https://Stackoverflow.com/users/2603364", "pm_score": 1, "selected": false, "text": "<p>You can do a couple of things. As Brad Parks + Nostoc says, you could put in your local path a script that executes the program:</p>\n\n<pre><code>$ cat my/local/path/terminal\n#! /bin/bash\ngnome-terminal\n</code></pre>\n\n<p>If you don't want to do this for your many aliases, then add a single \"alias executor\" to your local path:</p>\n\n<pre><code>$ cat my/local/path/myAlias\n#! /bin/bash\nCMD=\"$*\"\neval \"$CMD\"\n</code></pre>\n\n<p>Then, in the dialog, you would type \"myAlias aliasedProgram arg1 arg2 etc\".</p>\n" }, { "answer_id": 25618955, "author": "michael", "author_id": 127971, "author_profile": "https://Stackoverflow.com/users/127971", "pm_score": 0, "selected": false, "text": "<p>Instead of using alt-f2 to run commands outside the terminal, I use gnome-do instead; it is much more convenient &amp; flexible (once it's set up). You're still not going to be able to run shell \"aliases\", but you can configure gnome-do to use the \"files and folders\" plugin, and then any \"*.desktop\" applications you like to execute will be available for running, opening, etc. You can also have shell scripts executed in the same way. </p>\n" }, { "answer_id": 25629268, "author": "VinGarcia", "author_id": 2905274, "author_profile": "https://Stackoverflow.com/users/2905274", "pm_score": 0, "selected": false, "text": "<p>I did something similar to @YAG.</p>\n\n<p>i created a bash script in /usr/local/bin called 'my':</p>\n\n<pre><code>echo -e '#!/usr/bin/bash\\n~/bin/$@' &gt; ~/temp\nsudo cp ~/temp /usr/local/bin/my\nrm ~/temp\n</code></pre>\n\n<p>Now if i want to call a script inside ~/bin from Alt+F2 i just type:</p>\n\n<pre><code>my script.sh\n</code></pre>\n\n<p>The advantages are that all users will access their own ~/bin directory, and you don't have to make a new symlink for each ~/bin/* file.</p>\n\n<p>The disadvantage is that you need to type 'my' everytime, and can't count on the auto-complete feature of alt+f2 to complete 'script.sh'</p>\n" }, { "answer_id": 33537689, "author": "Jason Eisner", "author_id": 5026802, "author_profile": "https://Stackoverflow.com/users/5026802", "pm_score": 1, "selected": false, "text": "<p>I created this script under the name /usr/bin/b, and gave it global read/execute permission:</p>\n\n<pre><code>#!/bin/bash -i\neval \"$@\"\n</code></pre>\n\n<p>Now I can use the command </p>\n\n<pre><code>b foo arg1 arg2\n</code></pre>\n\n<p>which basically runs</p>\n\n<pre><code>foo arg1 arg2\n</code></pre>\n\n<p>as if it had been typed in an interactive shell. It's fine to use aliases, compound commands, etc.</p>\n" }, { "answer_id": 33930536, "author": "maxkoryukov", "author_id": 1115187, "author_profile": "https://Stackoverflow.com/users/1115187", "pm_score": 2, "selected": false, "text": "<p>There is a very simple solution for Linux Mint and Ubuntu (I did not check it on other distros):</p>\n\n<pre class=\"lang-bash prettyprint-override\"><code>mkdir ~/bin #actually, need to run this line just once\ncd ~/bin\nln -s /bin/any/your/application.sh YOUR_ALIAS_NAME\n</code></pre>\n\n<p>For example, I like to run <code>calc</code> from <strong>Alt+F2</strong> menu, so my script is:</p>\n\n<pre class=\"lang-bash prettyprint-override\"><code>mkdir ~/bin\ncd ~/bin\nln -s /usr/bin/gnome-calculator calc\n</code></pre>\n\n<p>If you want to pass any parameters, you could create a short shell script in <code>~/bin</code>:</p>\n\n<pre class=\"lang-bash prettyprint-override\"><code>#create the file:\necho '#!/bin/sh\nfirefox --private-window' &gt; ~/bin/pfx\n#make my script executable:\nchmod 755 ~/bin/pfx\n</code></pre>\n\n<hr>\n\n<p>The solution based on the fact, that there is a file named <code>.profile</code> in home dir out of the box. I hope, your already know, what is <a href=\"https://unix.stackexchange.com/questions/40708/what-is-the-difference-between-profile-bashrc-bash-profile-gnomer\"><code>.profile</code> file</a>. As part of its job, this file appends <code>~/bin</code> to the <code>$PATH</code> (if <code>bin</code> exists).</p>\n\n<p>I thought, <em><code>bin</code> in home</em> is not secure, but this article recommends to follow described way: <a href=\"https://help.ubuntu.com/community/HomeFolder#Installing_Software_Into_The_Home_Directory\" rel=\"nofollow noreferrer\">https://help.ubuntu.com/community/HomeFolder#Installing_Software_Into_The_Home_Directory</a></p>\n" }, { "answer_id": 52874965, "author": "xwl", "author_id": 448076, "author_profile": "https://Stackoverflow.com/users/448076", "pm_score": 0, "selected": false, "text": "<p>Simply type: bash -ic 'MY_ALIAS'</p>\n" } ]
2008/10/09
[ "https://Stackoverflow.com/questions/187526", "https://Stackoverflow.com", "https://Stackoverflow.com/users/26510/" ]
I'd like to be able to run my aliases from my .bashrc in the "Run Application" dialog that comes up when you hit Alt+F2 in Ubuntu/Gnome. Does anyone know how to do this?
<http://www.freedesktop.org/wiki/Specifications> is probably a good place to start. I find these quite hard to follow most of the time, but sometimes you can figure it out. Specifically, the "Desktop Entry Specification". Also, I don't think you'll be able to use any aliases from `.bashrc`, at least not without writing some kind of wrapper script. I think it needs to be an executable file. Of course, you could just use the good old symlinks- to- same + what's- my- name trick... (Which, for reference, goes like this: 1. Make a script which uses its own name as a parameter. 2. Make symlinks to said script using the parameter values as the link names.) --- Investigating... ================ Some casual investigation reveals that creating these is fairly simple if you use Nautilus, (at least the version I have): 1. Bring up the context menu for some random file, and use "Open With"->"Open with Other Application". 2. Unfold the "Use a custom command" and type in something like: 1. `xterm -e 'bash -c "unzip -l %f; sleep 5"'` 3. This results in 1. the command being run (so don't type `rm -rf`) 2. a file in `~/.local/share/applications/` called `xterm-usercreated.desktop` Here at least, I get the follow file: ``` [Desktop Entry] Encoding=UTF-8 Name=xterm MimeType=application/zip; Exec=xterm -e 'bash -c "unzip -l %f; sleep 5"' %f Type=Application Terminal=false NoDisplay=true ``` 4: Looking at the system xterm .desktop I find this: ``` [Desktop Entry] Type=Application Encoding=UTF-8 Name=XTerm GenericName= Comment=XTerm: terminal emulator for X Icon=/usr/share/pixmaps/xterm-color_32x32.xpm Exec=xterm Terminal=false Categories=X-Debian-Applications-Terminal-Emulators; ``` 5: Editing the .usercreated.desktop file to this: ``` [Desktop Entry] Type=Application Encoding=UTF-8 Name=xtermz Exec=xterm -e 'bash -c "unzip -l %f; sleep 5"' %f Terminal=false Categories=X-Local-WTF ``` 6: Run xdg-desktop-menu forceupdate --mode user 7: "xtermz" now shows up in the list... Success! 8: Yuck! This also makes it appear in the main menu, under "Other". Weird! --- Some notes: ----------- * In my Debian/testing, `xdg-desktop-menu` and friends (notably `xdg-icon-resource`) live in the `xdg-utils` package. * You should be able to create a `.desktop` file from scratch. * You should be able to install the `.desktop` file using `xdg-desktop-menu install` blah blah
187,531
<p>I have a package that I just made and I have an "old-mode" that basically makes it work like it worked before: importing everything into the current namespace. One of the nice things about having this as a package is that we no longer have to do that. Anyway, what I would like to do is have it so that whenever anyone does:</p> <pre><code>use Foo qw(:oldmode); </code></pre> <p>I throw a warning that this is deprecated and that they should either import only what they need or just access functions with Foo->fun();</p> <p>Any ideas on how to do this?</p>
[ { "answer_id": 187541, "author": "moritz", "author_id": 14132, "author_profile": "https://Stackoverflow.com/users/14132", "pm_score": 4, "selected": false, "text": "<p>You write your own <code>sub import</code> in <code>package Foo</code> that will get called with the parameter list from <code>use Foo</code>.</p>\n\n<p>An example:</p>\n\n<pre><code>package Foo;\nuse Exporter;\n\nsub import {\n warn \"called with paramters '@_'\";\n\n # do the real import work\n goto &amp;{Exporter-&gt;can('import')};\n}\n</code></pre>\n\n<p>So in sub <code>import</code> you can search the argument list for the deprecated tag, and then throw a warning.</p>\n\n<p><em>Update</em>: As Axeman points out, you should call <code>goto &amp;{Exporter-&gt;can('import')}</code>. This form of goto replaces the current subroutine call on the stack, preserving the current arguments (if any). That's needed because Exporter's import() method will export to its caller's namespace.</p>\n" }, { "answer_id": 187625, "author": "Axeman", "author_id": 11289, "author_profile": "https://Stackoverflow.com/users/11289", "pm_score": 5, "selected": true, "text": "<p>Well, as you specifically state that you want to alarm in the cases of <code>use Mod qw&lt;:oldmode&gt;;</code> This works better:</p>\n\n<pre><code>package Foo;\nuse base qw&lt;Exporter&gt;;\nuse Carp qw&lt;carp&gt;;\n...\nsub import { \n #if ( grep { $_ eq ':oldmode' } @_ ) { # Perl 5.8\n if ( @_ ~~ ':oldmode' ) { # Perl 5.10 \n carp( 'import called with :oldmode!' );\n }\n goto &amp;{Exporter-&gt;can( 'import' )};\n}\n</code></pre>\n\n<p>Thanks to Frew, for mentioning the Perl 5.10 smart match syntax. I'm learning all the ways to work Perl 5.10 into my code. </p>\n\n<p><strong>Note:</strong> the standard way to use exporter in an import sub is to either manipulate <code>$Exporter::ExportLevel</code> or to call <code>Foo-&gt;export_to_level( 1, @_ );</code> But I like the way above. It's quicker and, I think, simpler.</p>\n" } ]
2008/10/09
[ "https://Stackoverflow.com/questions/187531", "https://Stackoverflow.com", "https://Stackoverflow.com/users/12448/" ]
I have a package that I just made and I have an "old-mode" that basically makes it work like it worked before: importing everything into the current namespace. One of the nice things about having this as a package is that we no longer have to do that. Anyway, what I would like to do is have it so that whenever anyone does: ``` use Foo qw(:oldmode); ``` I throw a warning that this is deprecated and that they should either import only what they need or just access functions with Foo->fun(); Any ideas on how to do this?
Well, as you specifically state that you want to alarm in the cases of `use Mod qw<:oldmode>;` This works better: ``` package Foo; use base qw<Exporter>; use Carp qw<carp>; ... sub import { #if ( grep { $_ eq ':oldmode' } @_ ) { # Perl 5.8 if ( @_ ~~ ':oldmode' ) { # Perl 5.10 carp( 'import called with :oldmode!' ); } goto &{Exporter->can( 'import' )}; } ``` Thanks to Frew, for mentioning the Perl 5.10 smart match syntax. I'm learning all the ways to work Perl 5.10 into my code. **Note:** the standard way to use exporter in an import sub is to either manipulate `$Exporter::ExportLevel` or to call `Foo->export_to_level( 1, @_ );` But I like the way above. It's quicker and, I think, simpler.
187,537
<p>Is there a case insensitive version of the <a href="http://docs.jquery.com/Selectors/contains" rel="noreferrer">:contains</a> jQuery selector or should I do the work manually by looping over all elements and comparing their .text() to my string?</p>
[ { "answer_id": 187557, "author": "Pat", "author_id": 238, "author_profile": "https://Stackoverflow.com/users/238", "pm_score": 8, "selected": true, "text": "<p>What I ended up doing for jQuery 1.2 is :</p>\n\n<pre><code>jQuery.extend(\n jQuery.expr[':'], { \n Contains : \"jQuery(a).text().toUpperCase().indexOf(m[3].toUpperCase())&gt;=0\" \n});\n</code></pre>\n\n<p>This will extend jquery to have a :Contains selector that is case insensitive, the :contains selector remains unchanged.</p>\n\n<p>Edit: For jQuery 1.3 (thanks @user95227) and later you need</p>\n\n<pre><code>jQuery.expr[':'].Contains = function(a,i,m){\n return jQuery(a).text().toUpperCase().indexOf(m[3].toUpperCase())&gt;=0;\n};\n</code></pre>\n\n<p>Edit: \nApparently accessing the DOM directly by using</p>\n\n<pre><code>(a.textContent || a.innerText || \"\") \n</code></pre>\n\n<p>instead of </p>\n\n<pre><code>jQuery(a).text()\n</code></pre>\n\n<p>In the previous expression speeds it up considerably so try at your own risk if speed is an issue. (see <a href=\"https://stackoverflow.com/users/171662/john\">@John</a> 's <a href=\"https://stackoverflow.com/questions/1407434/is-there-any-way-to-speed-up-this-solution-for-a-case-insensitive-jquery-contai\">question</a>)</p>\n\n<p>Latest edit: For jQuery 1.8 it should be:</p>\n\n<pre><code>jQuery.expr[\":\"].Contains = jQuery.expr.createPseudo(function(arg) {\n return function( elem ) {\n return jQuery(elem).text().toUpperCase().indexOf(arg.toUpperCase()) &gt;= 0;\n };\n});\n</code></pre>\n" }, { "answer_id": 190183, "author": "Alexander Prokofyev", "author_id": 11256, "author_profile": "https://Stackoverflow.com/users/11256", "pm_score": 5, "selected": false, "text": "<p>If someone (like me) is interested what do <em>a</em> and <em>m[3]</em> mean in <em>Contains</em> definition.</p>\n\n<hr>\n\n<p><strong>KEY/LEGEND: Params made available by jQuery for use in the selector definitions:</strong> </p>\n\n<p><em>r</em> = jQuery array of elements being scrutinised. (eg: <em>r.length</em> = Number of elements) </p>\n\n<p><em>i</em> = index of element currently under scrutiny, within array <em>r</em>. </p>\n\n<p><em>a</em> = element currently under scrutiny. Selector statement must return true to include it in its matched results. </p>\n\n<p><em>m[2]</em> = nodeName or * that we a looking for (left of colon). </p>\n\n<p><em>m[3]</em> = param passed into the :selector(param). Typically an index number, as in <em>:nth-of-type(5)</em>, or a string, as in <em>:color(blue)</em>.</p>\n" }, { "answer_id": 783874, "author": "user95227", "author_id": 95227, "author_profile": "https://Stackoverflow.com/users/95227", "pm_score": 5, "selected": false, "text": "<p>As of jQuery 1.3, this method is deprecated. To get this to work it needs to be defined as a function:</p>\n\n<pre><code>jQuery.expr[':'].Contains = function(a,i,m){\n return jQuery(a).text().toUpperCase().indexOf(m[3].toUpperCase())&gt;=0;\n};\n</code></pre>\n" }, { "answer_id": 994213, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 3, "selected": false, "text": "<pre><code>jQuery.expr[':'].contains = function(a,i,m){\n return jQuery(a).text().toUpperCase().indexOf(m[3].toUpperCase())&gt;=0;\n};\n</code></pre>\n\n<p>The update code works great in 1.3, but \"contains\" should be lower case on the first letter unlike the previous example. </p>\n" }, { "answer_id": 4936066, "author": "montrealmike", "author_id": 454375, "author_profile": "https://Stackoverflow.com/users/454375", "pm_score": 7, "selected": false, "text": "<p>To make it optionally case insensitive:\n<a href=\"http://bugs.jquery.com/ticket/278\" rel=\"noreferrer\">http://bugs.jquery.com/ticket/278</a></p>\n\n<pre><code>$.extend($.expr[':'], {\n 'containsi': function(elem, i, match, array)\n {\n return (elem.textContent || elem.innerText || '').toLowerCase()\n .indexOf((match[3] || \"\").toLowerCase()) &gt;= 0;\n }\n});\n</code></pre>\n\n<p>then use <code>:containsi</code> instead of <code>:contains</code></p>\n" }, { "answer_id": 11326196, "author": "Brock Adams", "author_id": 331508, "author_profile": "https://Stackoverflow.com/users/331508", "pm_score": 4, "selected": false, "text": "<p>A variation that seems to perform slightly faster and that also <strong>allows regular expressions</strong> is:</p>\n\n<pre><code>jQuery.extend (\n jQuery.expr[':'].containsCI = function (a, i, m) {\n //-- faster than jQuery(a).text()\n var sText = (a.textContent || a.innerText || \"\"); \n var zRegExp = new RegExp (m[3], 'i');\n return zRegExp.test (sText);\n }\n);\n</code></pre>\n\n<p><br></p>\n\n<hr>\n\n<p>Not only is this case-insensitive, but it allows powerful searches like:</p>\n\n<ul>\n<li><code>$(\"p:containsCI('\\\\bup\\\\b')\")</code> (Matches \"Up\" or \"up\", but not \"upper\", \"wakeup\", etc.)</li>\n<li><code>$(\"p:containsCI('(?:Red|Blue) state')\")</code> (Matches \"red state\" or \"blue state\", but not \"up state\", etc.)</li>\n<li><code>$(\"p:containsCI('^\\\\s*Stocks?')\")</code> (Matches \"stock\" or \"stocks\", but only at the start of the paragraph (ignoring any leading whitespace).)</li>\n</ul>\n" }, { "answer_id": 12113443, "author": "seagullJS", "author_id": 1593862, "author_profile": "https://Stackoverflow.com/users/1593862", "pm_score": 5, "selected": false, "text": "<p>In jQuery 1.8 you will need to use </p>\n\n<pre><code>jQuery.expr[\":\"].icontains = jQuery.expr.createPseudo(function (arg) { \n return function (elem) { \n return jQuery(elem).text().toUpperCase().indexOf(arg.toUpperCase()) &gt;= 0; \n }; \n});\n</code></pre>\n" }, { "answer_id": 16776915, "author": "ErickBest", "author_id": 2290703, "author_profile": "https://Stackoverflow.com/users/2290703", "pm_score": 4, "selected": false, "text": "<p>May be late.... but,</p>\n\n<p>I'd prefer to go this way..</p>\n\n<pre><code>$.extend($.expr[\":\"], {\n\"MyCaseInsensitiveContains\": function(elem, i, match, array) {\nreturn (elem.textContent || elem.innerText || \"\").toLowerCase().indexOf((match[3] || \"\").toLowerCase()) &gt;= 0;\n}\n});\n</code></pre>\n\n<p>This way, you <strong>DO NOT</strong> tamper with jQuery's NATIVE <em>'.contains'</em>... You may need the default one later...if tampered with, you might find yourself back to <strong><em>stackOverFlow</em></strong>...</p>\n" }, { "answer_id": 34719928, "author": "Umesh Patil", "author_id": 1200323, "author_profile": "https://Stackoverflow.com/users/1200323", "pm_score": 3, "selected": false, "text": "<p>Refer below to use \":contains\" to find text ignoring its case sensitivity from an HTML code,</p>\n\n<pre><code> $.expr[\":\"].contains = $.expr.createPseudo(function(arg) {\n return function( elem ) {\n return $(elem).text().toUpperCase().indexOf(arg.toUpperCase()) &gt;= 0;\n };\n });\n $(\"#searchTextBox\").keypress(function() {\n if($(\"#searchTextBox\").val().length &gt; 0){\n $(\".rows\").css(\"display\",\"none\");\n var userSerarchField = $(\"#searchTextBox\").val();\n $(\".rows:contains('\"+ userSerarchField +\"')\").css(\"display\",\"block\");\n } else {\n $(\".rows\").css(\"display\",\"block\");\n } \n });\n</code></pre>\n\n<p>You can also use this link to find case ignoring code based on your jquery version,\n<a href=\"https://css-tricks.com/snippets/jquery/make-jquery-contains-case-insensitive/\" rel=\"nofollow noreferrer\">Make jQuery :contains Case-Insensitive</a></p>\n" }, { "answer_id": 36392273, "author": "shao.lo", "author_id": 820013, "author_profile": "https://Stackoverflow.com/users/820013", "pm_score": 0, "selected": false, "text": "<p>I had a similar problem with the following not working...</p>\n\n<pre><code>// This doesn't catch flac or Flac\n$('div.story span.Quality:not(:contains(\"FLAC\"))').css(\"background-color\", 'yellow');\n</code></pre>\n\n<p>This works and without the need for an extension</p>\n\n<pre><code>$('div.story span.Quality:not([data*=\"flac\"])').css(\"background-color\", 'yellow');\n</code></pre>\n\n<p>This works too, but probably falls into the \"manually looping\" category....</p>\n\n<pre><code>$('div.story span.Quality').contents().filter(function()\n{\n return !/flac/i.test(this.nodeValue);\n}).parent().css(\"background-color\", 'yellow');\n</code></pre>\n" }, { "answer_id": 50006690, "author": "Howard", "author_id": 1040634, "author_profile": "https://Stackoverflow.com/users/1040634", "pm_score": 2, "selected": false, "text": "<p>A faster version using regular expressions.</p>\n\n<pre><code>$.expr[':'].icontains = function(el, i, m) { // checks for substring (case insensitive)\n var search = m[3];\n if (!search) return false;\n\n var pattern = new RegExp(search, 'i');\n return pattern.test($(el).text());\n};\n</code></pre>\n" }, { "answer_id": 59730613, "author": "劉鎮瑲", "author_id": 7786739, "author_profile": "https://Stackoverflow.com/users/7786739", "pm_score": 0, "selected": false, "text": "<p>New a variable I give it name subString and put string you want to search in some elements text. Then using Jquery selector select elements you need like my example <code>$(\"elementsYouNeed\")</code> and filter by <code>.filter()</code>. In the <code>.filter()</code> it will compare each elements in <code>$(\"elementsYouNeed\")</code> with the function. </p>\n\n<p>In the function i using <code>.toLowerCase()</code> for element text also subString that can avoid case sensitive condition and check if there is a subString in it. After that the <code>.filter()</code> method constructs a new jQuery object from a subset of the matching elements. </p>\n\n<p>Now you can get the match elements in matchObjects and do whatever you want. </p>\n\n<pre><code>var subString =\"string you want to match\".toLowerCase();\n\nvar matchObjects = $(\"elementsYouNeed\").filter(function () {return $(this).text().toLowerCase().indexOf(subString) &gt; -1;});\n</code></pre>\n" } ]
2008/10/09
[ "https://Stackoverflow.com/questions/187537", "https://Stackoverflow.com", "https://Stackoverflow.com/users/238/" ]
Is there a case insensitive version of the [:contains](http://docs.jquery.com/Selectors/contains) jQuery selector or should I do the work manually by looping over all elements and comparing their .text() to my string?
What I ended up doing for jQuery 1.2 is : ``` jQuery.extend( jQuery.expr[':'], { Contains : "jQuery(a).text().toUpperCase().indexOf(m[3].toUpperCase())>=0" }); ``` This will extend jquery to have a :Contains selector that is case insensitive, the :contains selector remains unchanged. Edit: For jQuery 1.3 (thanks @user95227) and later you need ``` jQuery.expr[':'].Contains = function(a,i,m){ return jQuery(a).text().toUpperCase().indexOf(m[3].toUpperCase())>=0; }; ``` Edit: Apparently accessing the DOM directly by using ``` (a.textContent || a.innerText || "") ``` instead of ``` jQuery(a).text() ``` In the previous expression speeds it up considerably so try at your own risk if speed is an issue. (see [@John](https://stackoverflow.com/users/171662/john) 's [question](https://stackoverflow.com/questions/1407434/is-there-any-way-to-speed-up-this-solution-for-a-case-insensitive-jquery-contai)) Latest edit: For jQuery 1.8 it should be: ``` jQuery.expr[":"].Contains = jQuery.expr.createPseudo(function(arg) { return function( elem ) { return jQuery(elem).text().toUpperCase().indexOf(arg.toUpperCase()) >= 0; }; }); ```
187,550
<p>I have a lot of Java source code that requires custom pre-processing. I'd like rid of it but that's not feasible right now so I'm stuck with it. Given that I have an unfortunate problem that shouldn't have existed in the first place, how do I solve it using maven? </p> <p>(For the full story, I'm replacing a python-based build system with a maven one, so one improvement at a time please. Fixing the non-standard source code is harder, and will come later.)</p> <p>Is it possible using any existing Maven plugins to actually alter the source files during compile time? (Obviously leaving the original, unprocessed code alone)</p> <p>To be clear, by preprocessing I mean preprocessing in the same sense as antenna or a C compiler would preprocess the code, and by custom I mean that it's completely proprietary and looks nothing at all like C or antenna preprocessing.</p>
[ { "answer_id": 187973, "author": "Keeg", "author_id": 21059, "author_profile": "https://Stackoverflow.com/users/21059", "pm_score": 2, "selected": false, "text": "<p>Maven plugins can hook into the build process at pre-compile time yes, as for whether or not any existing ones will help I have no idea. </p>\n\n<p>I wrote a maven plugin a couple of years ago as part of a university project though, and while the documentation was a bit lacking at the time, it wasn't too complicated. So you may look into rolling your own, there should be plenty of open source projects you can rip ideas or code from (ours was BSD-licenced for instance...)</p>\n" }, { "answer_id": 189299, "author": "Travis B. Hartwell", "author_id": 10873, "author_profile": "https://Stackoverflow.com/users/10873", "pm_score": 4, "selected": true, "text": "<p>This is something that is very doable and I've done something very similar in the past.</p>\n\n<p>An example from a project of mine, where I used the antrun plug-in to execute an external program to process sources:</p>\n\n<pre><code> &lt;build&gt;\n &lt;plugins&gt;\n &lt;plugin&gt;\n &lt;groupId&gt;org.apache.maven.plugins&lt;/groupId&gt;\n &lt;artifactId&gt;maven-antrun-plugin&lt;/artifactId&gt;\n &lt;executions&gt;\n &lt;execution&gt;\n &lt;id&gt;process-sources&lt;/id&gt;\n &lt;phase&gt;process-sources&lt;/phase&gt;\n &lt;configuration&gt;\n &lt;tasks&gt;\n &lt;!-- Put the code to run the program here --&gt;\n &lt;/tasks&gt;\n &lt;/configuration&gt;\n &lt;goals&gt;\n &lt;goal&gt;run&lt;/goal&gt;\n &lt;/goals&gt;\n &lt;/execution&gt;\n &lt;/executions&gt;\n &lt;/plugin&gt;\n &lt;/plugins&gt;\n&lt;/build&gt;\n</code></pre>\n\n<p>Note the tag where I indicate the phase where this is run. Documentation for the lifecycles in Maven is <a href=\"http://maven.apache.org/guides/introduction/introduction-to-the-lifecycle.html\" rel=\"noreferrer\">here</a>. Another option is to actually write your own Maven plug-in that does this. It's a little more complex, but is also doable. You will still configure it similarly to what I have documented here.</p>\n" }, { "answer_id": 8386222, "author": "Igor Maznitsa", "author_id": 1081657, "author_profile": "https://Stackoverflow.com/users/1081657", "pm_score": 3, "selected": false, "text": "<p>There is a Java preprocessor with support of MAVEN: <a href=\"https://github.com/raydac/java-comment-preprocessor\" rel=\"nofollow noreferrer\">java-comment-preprocessor</a></p>\n" } ]
2008/10/09
[ "https://Stackoverflow.com/questions/187550", "https://Stackoverflow.com", "https://Stackoverflow.com/users/974/" ]
I have a lot of Java source code that requires custom pre-processing. I'd like rid of it but that's not feasible right now so I'm stuck with it. Given that I have an unfortunate problem that shouldn't have existed in the first place, how do I solve it using maven? (For the full story, I'm replacing a python-based build system with a maven one, so one improvement at a time please. Fixing the non-standard source code is harder, and will come later.) Is it possible using any existing Maven plugins to actually alter the source files during compile time? (Obviously leaving the original, unprocessed code alone) To be clear, by preprocessing I mean preprocessing in the same sense as antenna or a C compiler would preprocess the code, and by custom I mean that it's completely proprietary and looks nothing at all like C or antenna preprocessing.
This is something that is very doable and I've done something very similar in the past. An example from a project of mine, where I used the antrun plug-in to execute an external program to process sources: ``` <build> <plugins> <plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-antrun-plugin</artifactId> <executions> <execution> <id>process-sources</id> <phase>process-sources</phase> <configuration> <tasks> <!-- Put the code to run the program here --> </tasks> </configuration> <goals> <goal>run</goal> </goals> </execution> </executions> </plugin> </plugins> </build> ``` Note the tag where I indicate the phase where this is run. Documentation for the lifecycles in Maven is [here](http://maven.apache.org/guides/introduction/introduction-to-the-lifecycle.html). Another option is to actually write your own Maven plug-in that does this. It's a little more complex, but is also doable. You will still configure it similarly to what I have documented here.
187,552
<p>What's the best way of capturing an mp3 stream coming off of http and saving it to disk with python?</p> <p>Thus far I've tried</p> <pre><code>target = open(target_path, "w") conn = urllib.urlopen(stream_url) while True: target.write(conn.read(buf_size)) </code></pre> <p>This gives me data but its garbled or wont play in mp3 players.</p>
[ { "answer_id": 187563, "author": "Adam Rosenfield", "author_id": 9530, "author_profile": "https://Stackoverflow.com/users/9530", "pm_score": 5, "selected": true, "text": "<p>If you're on Windows, you might accidentally be doing CRLF conversions, corrupting the binary data. Try opening <code>target</code> in binary mode:</p>\n\n<pre><code>target = open(target_path, \"wb\")\n</code></pre>\n" }, { "answer_id": 3193428, "author": "Boiler", "author_id": 385355, "author_profile": "https://Stackoverflow.com/users/385355", "pm_score": 2, "selected": false, "text": "<p>The best way for this is:</p>\n\n<pre><code>urllib.urlretrieve(stream_url, target_path);\n</code></pre>\n" }, { "answer_id": 50496223, "author": "never_comment", "author_id": 8452041, "author_profile": "https://Stackoverflow.com/users/8452041", "pm_score": 1, "selected": false, "text": "<p>Perhaps the syntax changed from the previous urllib answer (that got me to the correct answer btw), but this syntax works for python3:</p>\n\n<pre><code>import urllib.request\n\nurllib.request.urlretrieve(stream_url, target_path)\n</code></pre>\n" } ]
2008/10/09
[ "https://Stackoverflow.com/questions/187552", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2906/" ]
What's the best way of capturing an mp3 stream coming off of http and saving it to disk with python? Thus far I've tried ``` target = open(target_path, "w") conn = urllib.urlopen(stream_url) while True: target.write(conn.read(buf_size)) ``` This gives me data but its garbled or wont play in mp3 players.
If you're on Windows, you might accidentally be doing CRLF conversions, corrupting the binary data. Try opening `target` in binary mode: ``` target = open(target_path, "wb") ```
187,560
<p>I am migrating a site from SharePoint 2 to 3 (in fact, from SharePoint Portal Server 2003 to Microsoft Office SharePoint Server 2007). There are a handful of 3rd party web parts and since this is a migration, not an in-place upgrade, I need to install these web parts on the new farm.</p> <p>How do I do this, given that I have the packaged up web parts as provided by the SharePoint Configuration Analyzer in the form of cab files? Can I simply deploy these cab files somehow, even though they are not packaged as solutions? Or do I need to pull the cab files apart and repackage them as solutions? Or do I need to get new versions of the web parts, written for SharePoint 3, and maybe edit the pages that use them?</p>
[ { "answer_id": 187791, "author": "AdamBT", "author_id": 22426, "author_profile": "https://Stackoverflow.com/users/22426", "pm_score": 0, "selected": false, "text": "<p>You should be able to pull them apart and either repackage them as solutions or manually deploy them. Obviously, if they are real complicated webparts that have other dependencies, this might become more difficult.</p>\n" }, { "answer_id": 188684, "author": "Ryan", "author_id": 20198, "author_profile": "https://Stackoverflow.com/users/20198", "pm_score": 3, "selected": true, "text": "<p>You can still install .CAB files with WSSv3 using the same STSADM command as you used in WSSv2</p>\n\n<pre><code>STSADM -o addwppack -filename &lt;filename.CAB&gt;\n</code></pre>\n\n<p>However, maybe you should get in touch with the providers of these 3rd party web parts? Perhaps they will have versions for WSSv3 packaged as WSP's? </p>\n\n<p>Also can you be sure that the WSSv2 versions will actually work on WSSv3? They often do, but not always.</p>\n" } ]
2008/10/09
[ "https://Stackoverflow.com/questions/187560", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3142/" ]
I am migrating a site from SharePoint 2 to 3 (in fact, from SharePoint Portal Server 2003 to Microsoft Office SharePoint Server 2007). There are a handful of 3rd party web parts and since this is a migration, not an in-place upgrade, I need to install these web parts on the new farm. How do I do this, given that I have the packaged up web parts as provided by the SharePoint Configuration Analyzer in the form of cab files? Can I simply deploy these cab files somehow, even though they are not packaged as solutions? Or do I need to pull the cab files apart and repackage them as solutions? Or do I need to get new versions of the web parts, written for SharePoint 3, and maybe edit the pages that use them?
You can still install .CAB files with WSSv3 using the same STSADM command as you used in WSSv2 ``` STSADM -o addwppack -filename <filename.CAB> ``` However, maybe you should get in touch with the providers of these 3rd party web parts? Perhaps they will have versions for WSSv3 packaged as WSP's? Also can you be sure that the WSSv2 versions will actually work on WSSv3? They often do, but not always.
187,567
<p>I used Visual Studio's Application Wizard to create a skeleton MFC program with a multi-document interface. When I start this program, it automatically creates a child frame, which I don't want it to do - I need the main frame's client area to be empty until the user chooses to open a file.</p> <p>The debugger tells me that a CChildFrame object is created when the application class's InitInstance() function calls ProcessShellCommand(), but what is a good entry point for me to override this behaviour?</p>
[ { "answer_id": 187931, "author": "jeffm", "author_id": 1544, "author_profile": "https://Stackoverflow.com/users/1544", "pm_score": 3, "selected": true, "text": "<p>This worked for me -- change</p>\n\n<pre><code>if (!ProcessShellCommand(cmdInfo))\n</code></pre>\n\n<p>to</p>\n\n<pre><code>if (cmdInfo.m_nShellCommand != CCommandLineInfo::FileNew &amp;&amp; !ProcessShellCommand(cmdInfo))\n</code></pre>\n\n<p>in your app's InitInstance() function.</p>\n" }, { "answer_id": 188576, "author": "Serge Wautier", "author_id": 12379, "author_profile": "https://Stackoverflow.com/users/12379", "pm_score": 1, "selected": false, "text": "<p>Skipping the ProcessShellCommand() call (in case of FileNew) in InitInstance() is indeed the way to go.</p>\n" }, { "answer_id": 190286, "author": "titanae", "author_id": 2387, "author_profile": "https://Stackoverflow.com/users/2387", "pm_score": 3, "selected": false, "text": "<p>This works, it maintains printing/opening from the shell etc.</p>\n\n<pre><code>// Parse command line for standard shell commands, DDE, file open\nCCommandLineInfo cmdInfo;\nParseCommandLine(cmdInfo);\n\nif ( cmdInfo.m_nShellCommand == CCommandLineInfo::FileNew )\n{\n cmdInfo.m_nShellCommand = CCommandLineInfo::FileNothing ;\n}\n\n// Dispatch commands specified on the command line\nif (!ProcessShellCommand(cmdInfo))\n return FALSE;\n</code></pre>\n" }, { "answer_id": 2251383, "author": "Jatin Zaveri", "author_id": 271787, "author_profile": "https://Stackoverflow.com/users/271787", "pm_score": 1, "selected": false, "text": "<p>Do one thing..</p>\n\n<p>in your XXXApp.cpp file</p>\n\n<p>in this Method:-</p>\n\n<p>comment the following line..\n/*</p>\n\n<pre><code> CCommandLineInfo cmdInfo;\nParseCommandLine(cmdInfo);\n\n// Dispatch commands specified on the command line. Will return FALSE if\n// app was launched with /RegServer, /Register, /Unregserver or /Unregister.\nif (!ProcessShellCommand(cmdInfo))\n return; \n</code></pre>\n\n<p>*/</p>\n\n<p>like this....</p>\n" } ]
2008/10/09
[ "https://Stackoverflow.com/questions/187567", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11575/" ]
I used Visual Studio's Application Wizard to create a skeleton MFC program with a multi-document interface. When I start this program, it automatically creates a child frame, which I don't want it to do - I need the main frame's client area to be empty until the user chooses to open a file. The debugger tells me that a CChildFrame object is created when the application class's InitInstance() function calls ProcessShellCommand(), but what is a good entry point for me to override this behaviour?
This worked for me -- change ``` if (!ProcessShellCommand(cmdInfo)) ``` to ``` if (cmdInfo.m_nShellCommand != CCommandLineInfo::FileNew && !ProcessShellCommand(cmdInfo)) ``` in your app's InitInstance() function.
187,588
<p>We have a shrink wrap type Windows server application where we need to create a self signed certificate on the server to be used by some WCF web services. From our searches on the web, it appears that the makecert utility in the PlatformSDK from Microsoft cannot be distributed with our application, so we're looking for alternatives. </p> <p>Does anyone know how to use OpenSSL to create a certificate and get it into the Windows LocalMachine certificate store? Or, alternatively is it straight forward to insert the certificate into the store in a .NET application and should we just create the certificate file with openssl? Any help/suggestions would be appreciated. </p>
[ { "answer_id": 187622, "author": "blowdart", "author_id": 2525, "author_profile": "https://Stackoverflow.com/users/2525", "pm_score": 2, "selected": false, "text": "<p>Woohoo! It's time for pinvoke for you</p>\n\n<p>crypt32 provides a <a href=\"http://msdn.microsoft.com/en-us/library/aa376039.aspx\" rel=\"nofollow noreferrer\">CertCreateSelfSignCertificate</a> function; if that succeeds you can store it in the user's personal store (or the machine store assuming you're working elevated)</p>\n" }, { "answer_id": 189048, "author": "Mike L", "author_id": 12085, "author_profile": "https://Stackoverflow.com/users/12085", "pm_score": 2, "selected": false, "text": "<p>I haven't used OpenSSL, but I'm in the same boat and have found this article helpful:</p>\n\n<p><a href=\"http://www.codeproject.com/KB/WCF/wcf_certificates.aspx\" rel=\"nofollow noreferrer\">Securing WCF Services with Certificates</a></p>\n\n<p>The author walks you through installing Microsoft Certificate Services, creating a CA that can be added to the trusted certificate authorities (on both client and server, since it's self signed), then generating client and server certificates that chain from the self-signed CA cert.</p>\n\n<p>You won't need the client certs, but it does help you to create a self-signed CA and server cert.</p>\n" }, { "answer_id": 2273239, "author": "Naveen", "author_id": 220854, "author_profile": "https://Stackoverflow.com/users/220854", "pm_score": 4, "selected": true, "text": "<p>[Unfortunately, I can't comment on anything yet, so I'll post this as an answer.]</p>\n\n<p>I see that this post is a bit old, but I'm in a similar boat and I found this in the Visual Studio 2008 redist.txt file:</p>\n\n<pre><code>Windows SDK Files\n\nSubject to the license terms for the software, the following files may be distributed unmodified:\n\nMageUI.exe\nMage.exe\nMakecert.exe\n</code></pre>\n\n<p>Not sure if something has changed (and if my interpretation is correct), but it looks like makecert.exe included as part of the Windows SDK, which is in-turn included as part of the VS2008 install can actually be redistributed. </p>\n" }, { "answer_id": 4871901, "author": "anon", "author_id": 572731, "author_profile": "https://Stackoverflow.com/users/572731", "pm_score": 2, "selected": false, "text": "<p>One alternative for programmatically generating certificates is Bouncy Castle's C#-version.\n<a href=\"http://www.bouncycastle.org/csharp/\" rel=\"nofollow\">http://www.bouncycastle.org/csharp/</a></p>\n" }, { "answer_id": 31089855, "author": "Vishal", "author_id": 2625026, "author_profile": "https://Stackoverflow.com/users/2625026", "pm_score": 3, "selected": false, "text": "<p>You can now Create Self Signed Certificates with PowerShell\nThe commands you need are New-SelfSignedCertificate and Export-PfxCertificate.\nEx:\nto create a certificate</p>\n\n<pre><code>New-SelfSignedCertificate -certstorelocation cert:\\localmachine\\my -dnsname orin.windowsitpro.internal\n</code></pre>\n\n<p>to export it </p>\n\n<pre><code>Export-PfxCertificate -cert cert:\\localMachine\\my\\CE0976529B02DE058C9CB2C0E64AD79DAFB18CF4 -FilePath e:\\temp\\cert.pfx -Password $pwd\n</code></pre>\n\n<p>This link is really helpful</p>\n\n<p><a href=\"http://windowsitpro.com/blog/creating-self-signed-certificates-powershell\" rel=\"nofollow noreferrer\">https://www.itprotoday.com/powershell/creating-self-signed-certificates-powershell</a></p>\n" } ]
2008/10/09
[ "https://Stackoverflow.com/questions/187588", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3429/" ]
We have a shrink wrap type Windows server application where we need to create a self signed certificate on the server to be used by some WCF web services. From our searches on the web, it appears that the makecert utility in the PlatformSDK from Microsoft cannot be distributed with our application, so we're looking for alternatives. Does anyone know how to use OpenSSL to create a certificate and get it into the Windows LocalMachine certificate store? Or, alternatively is it straight forward to insert the certificate into the store in a .NET application and should we just create the certificate file with openssl? Any help/suggestions would be appreciated.
[Unfortunately, I can't comment on anything yet, so I'll post this as an answer.] I see that this post is a bit old, but I'm in a similar boat and I found this in the Visual Studio 2008 redist.txt file: ``` Windows SDK Files Subject to the license terms for the software, the following files may be distributed unmodified: MageUI.exe Mage.exe Makecert.exe ``` Not sure if something has changed (and if my interpretation is correct), but it looks like makecert.exe included as part of the Windows SDK, which is in-turn included as part of the VS2008 install can actually be redistributed.
187,619
<p>I have headers in <code>&lt;h1&gt;</code> through <code>&lt;h6&gt;</code> tags. Is there a way that I can use JavaScript to generate a table of contents for the contents that serves as anchor tags as well?</p> <p>I would like the output to be something like:</p> <pre><code>&lt;ol&gt; &lt;li&gt;Header 1&lt;/li&gt; &lt;li&gt;Header 1&lt;/li&gt; &lt;li&gt;Header 2&lt;/li&gt; &lt;li&gt;Header 3&lt;/li&gt; &lt;/ol&gt; </code></pre> <p>I am not currently using a JavaScript framework, but I don't see why I couldn't use one.</p> <p>I am also looking for something done, since I'm guessing this is a common problem, but if not, a starting point to roll my own would be good.</p>
[ { "answer_id": 187634, "author": "Amir Arad", "author_id": 11813, "author_profile": "https://Stackoverflow.com/users/11813", "pm_score": -1, "selected": false, "text": "<p>after page load, cycle through the DOM and look for the elements that interest you. build a nice list of anchors and add it to the document at the place of your desire.</p>\n" }, { "answer_id": 187649, "author": "Ates Goral", "author_id": 23501, "author_profile": "https://Stackoverflow.com/users/23501", "pm_score": 1, "selected": false, "text": "<p>Are you looking for a prepackaged solution or are you asking how this can be implemented?</p>\n\n<p>For the latter, you could use <del><code>getElementsByTagName()</code> recursively on <code>&lt;h1&gt;</code> through <code>&lt;h6&gt;</code></del> XPath to iterate through all <code>&lt;h*&gt;</code> elements and construct the corresponding nested <code>&lt;ul&gt;</code> or <code>&lt;ol&gt;</code> lists. You'd also have to add the <code>&lt;a&gt;</code> tags to the headers.</p>\n" }, { "answer_id": 187664, "author": "Francis Beaudet", "author_id": 14604, "author_profile": "https://Stackoverflow.com/users/14604", "pm_score": 3, "selected": false, "text": "<p>JQuery comes to mind as a fast and easy solution. A quick google search for <em>jquery table of contents</em> yields two promising results:</p>\n\n<ul>\n<li><a href=\"http://solidgone.org/jqtoc\" rel=\"noreferrer\">jqTOC</a></li>\n<li><a href=\"http://www.packtpub.com/article/using-jquery-script-for-creating-dynamic-table-of-contents\" rel=\"noreferrer\">Article on how to do this manually</a></li>\n</ul>\n" }, { "answer_id": 187692, "author": "Sergey Ilinsky", "author_id": 23815, "author_profile": "https://Stackoverflow.com/users/23815", "pm_score": 0, "selected": false, "text": "<p>Check out the component you are looking for on this page: <a href=\"http://www.ilinsky.com/articles/XMLHttpRequest/\" rel=\"nofollow noreferrer\">Re-inventing XMLHttpRequest: Cross-browser implementation with sniffing capabilities</a></p>\n\n<p>It walks over entire document and creates a TOC with all h1-h6 elements reflected in an openable (upon hover) structure. The component is standalone and it doesn't use any library.</p>\n" }, { "answer_id": 187946, "author": "Ates Goral", "author_id": 23501, "author_profile": "https://Stackoverflow.com/users/23501", "pm_score": 7, "selected": true, "text": "<p>I couldn't resist putting together a quick implementation.</p>\n\n<p>Add the following script anywhere on your page:</p>\n\n<pre><code>window.onload = function () {\n var toc = \"\";\n var level = 0;\n\n document.getElementById(\"contents\").innerHTML =\n document.getElementById(\"contents\").innerHTML.replace(\n /&lt;h([\\d])&gt;([^&lt;]+)&lt;\\/h([\\d])&gt;/gi,\n function (str, openLevel, titleText, closeLevel) {\n if (openLevel != closeLevel) {\n return str;\n }\n\n if (openLevel &gt; level) {\n toc += (new Array(openLevel - level + 1)).join(\"&lt;ul&gt;\");\n } else if (openLevel &lt; level) {\n toc += (new Array(level - openLevel + 1)).join(\"&lt;/ul&gt;\");\n }\n\n level = parseInt(openLevel);\n\n var anchor = titleText.replace(/ /g, \"_\");\n toc += \"&lt;li&gt;&lt;a href=\\\"#\" + anchor + \"\\\"&gt;\" + titleText\n + \"&lt;/a&gt;&lt;/li&gt;\";\n\n return \"&lt;h\" + openLevel + \"&gt;&lt;a name=\\\"\" + anchor + \"\\\"&gt;\"\n + titleText + \"&lt;/a&gt;&lt;/h\" + closeLevel + \"&gt;\";\n }\n );\n\n if (level) {\n toc += (new Array(level + 1)).join(\"&lt;/ul&gt;\");\n }\n\n document.getElementById(\"toc\").innerHTML += toc;\n};\n</code></pre>\n\n<p>Your page should be structured something like this:</p>\n\n<pre><code>&lt;body&gt;\n &lt;div id=\"toc\"&gt;\n &lt;h3&gt;Table of Contents&lt;/h3&gt;\n &lt;/div&gt;\n &lt;hr/&gt;\n &lt;div id=\"contents\"&gt;\n &lt;h1&gt;Fruits&lt;/h1&gt;\n &lt;h2&gt;Red Fruits&lt;/h2&gt;\n &lt;h3&gt;Apple&lt;/h3&gt;\n &lt;h3&gt;Raspberry&lt;/h3&gt;\n &lt;h2&gt;Orange Fruits&lt;/h2&gt;\n &lt;h3&gt;Orange&lt;/h3&gt;\n &lt;h3&gt;Tangerine&lt;/h3&gt;\n &lt;h1&gt;Vegetables&lt;/h1&gt;\n &lt;h2&gt;Vegetables Which Are Actually Fruits&lt;/h2&gt;\n &lt;h3&gt;Tomato&lt;/h3&gt;\n &lt;h3&gt;Eggplant&lt;/h3&gt;\n &lt;/div&gt;\n&lt;/body&gt;\n</code></pre>\n\n<p>You can see it in action at <a href=\"https://codepen.io/scheinercc/pen/KEowRK\" rel=\"noreferrer\">https://codepen.io/scheinercc/pen/KEowRK</a> (old link: <a href=\"http://magnetiq.com/exports/toc.htm\" rel=\"noreferrer\">http://magnetiq.com/exports/toc.htm</a> (Works in IE, FF, Safari, Opera))</p>\n" }, { "answer_id": 19185002, "author": "d13", "author_id": 1282216, "author_profile": "https://Stackoverflow.com/users/1282216", "pm_score": 3, "selected": false, "text": "<p>Here's a great script to do this:</p>\n\n<p><a href=\"https://github.com/matthewkastor/html-table-of-contents/wiki\" rel=\"noreferrer\">https://github.com/matthewkastor/html-table-of-contents/wiki</a></p>\n\n<p>To use it:</p>\n\n<ol>\n<li><p>Add this tag:</p>\n\n<pre><code>&lt;script src=\"./node_modules/html-table-of-contents/src/html-table-of-contents.js\" type=\"text/javascript\"&gt;\n</code></pre></li>\n<li><p>Call the function, such as in your body's onload attribute:</p>\n\n<pre><code>&lt;body onload=\"htmlTableOfContents();\"&gt; \n</code></pre></li>\n</ol>\n\n<p>Here is the definition of the method that does the generation:</p>\n\n<pre><code>/**\n * Generates a table of contents for your document based on the headings\n * present. Anchors are injected into the document and the\n * entries in the table of contents are linked to them. The table of\n * contents will be generated inside of the first element with the id `toc`.\n * @param {HTMLDOMDocument} documentRef Optional A reference to the document\n * object. Defaults to `document`.\n * @author Matthew Christopher Kastor-Inare III\n * @version 20130726\n * @example\n * // call this after the page has loaded\n * htmlTableOfContents();\n */\nfunction htmlTableOfContents (documentRef) {\n var documentRef = documentRef || document;\n var toc = documentRef.getElementById('toc');\n var headings = [].slice.call(documentRef.body.querySelectorAll('h1, h2, h3, h4, h5, h6'));\n headings.forEach(function (heading, index) {\n var anchor = documentRef.createElement('a');\n anchor.setAttribute('name', 'toc' + index);\n anchor.setAttribute('id', 'toc' + index);\n\n var link = documentRef.createElement('a');\n link.setAttribute('href', '#toc' + index);\n link.textContent = heading.textContent;\n\n var div = documentRef.createElement('div');\n div.setAttribute('class', heading.tagName.toLowerCase());\n\n div.appendChild(link);\n toc.appendChild(div);\n heading.parentNode.insertBefore(anchor, heading);\n });\n}\n\ntry {\n module.exports = htmlTableOfContents;\n} catch (e) {\n // module.exports is not defined\n}\n</code></pre>\n" }, { "answer_id": 28792557, "author": "shuseel", "author_id": 3090434, "author_profile": "https://Stackoverflow.com/users/3090434", "pm_score": -1, "selected": false, "text": "<p>You can <a href=\"http://www.siteforinfotech.com/2015/02/how-to-create-table-of-contents-using-javascript.html\" rel=\"nofollow\">create dynamic table of contents for any HTML document using JavaScript</a> which can show the list of headings from h1 to h6 with links to the headings and make easier to navigate through the document using the following steps.</p>\n\n<p>At first create window.onload function that runs automatically when the document finishes loading as given below</p>\n\n<p><div class=\"snippet\" data-lang=\"js\" data-hide=\"false\">\r\n<div class=\"snippet-code\">\r\n<pre class=\"snippet-code-js lang-js prettyprint-override\"><code>window.onload=function(){\r\n\r\nfunction getSelectedText(){\r\nif (window.getSelection)\r\nreturn window.getSelection().toString()+\"\r\n\"+document.URL;\r\nelse if (document.selection)\r\n return document.selection.createRange().text+\"\r\n\"+document.URL;\r\n}\r\nvar toc=document.getElementById(\"TOC\");\r\nif(!toc) {\r\n toc=document.createElement(\"div\");\r\n toc.id=\"TOC\";\r\n document.body.insertBefore(toc, document.body.firstChild);\r\n}</code></pre>\r\n</div>\r\n</div>\r\n</p>\n\n<p>Add the following codes to the function to find all through tags and sets them as headings.</p>\n\n<p><div class=\"snippet\" data-lang=\"js\" data-hide=\"false\">\r\n<div class=\"snippet-code\">\r\n<pre class=\"snippet-code-js lang-js prettyprint-override\"><code>var headings;\r\nif (document.querySelectorAll) \r\nheadings=document.querySelectorAll(\"h1, h2, h3, h4, h5, h6\");\r\nelse\r\nheadings=findHeadings(document.body, []);</code></pre>\r\n</div>\r\n</div>\r\n</p>\n\n<p>Use the following CSS code to design the Table of contents</p>\n\n<pre class=\"lang-css prettyprint-override\"><code>#TOC {border:solid black 1px; margin:10px; padding:10px;}\n.TOCEntry{font-family:sans-serief;}\n.TOCEntry a{text-decoration:none;}\n.TOCLevel1{font-size:17pt; font-weight:bold;}\n.TOCLevel2{font-size:16pt; font-weight:bold;}\n.TOCLevel3{font-size:15pt; font-weight:bold;}\n.TOCLevel4{font-size:14pt; margin-left:.25in;}\n.TOCSectNum{display:none;}\n</code></pre>\n\n\n\n<p>Here is a full JavaScript Code To Create Table of Contents within script tag.</p>\n\n<p><div class=\"snippet\" data-lang=\"js\" data-hide=\"false\">\r\n<div class=\"snippet-code\">\r\n<pre class=\"snippet-code-js lang-js prettyprint-override\"><code>window.onload=function(){\r\n\r\nfunction getSelectedText(){\r\nif (window.getSelection)\r\nreturn window.getSelection().toString()+\"&lt;br/&gt;\"+document.URL;\r\nelse if (document.selection)\r\n return document.selection.createRange().text+\"&lt;br/&gt;\"+document.URL;\r\n}\r\n\r\nvar toc=document.getElementById(\"TOC\");\r\nif(!toc) {\r\n toc=document.createElement(\"div\");\r\n toc.id=\"TOC\";\r\n document.body.insertBefore(toc, document.body.firstChild);\r\n}\r\nvar headings;\r\nif (document.querySelectorAll) \r\nheadings=document.querySelectorAll(\"h1, h2, h3, h4, h5, h6\");\r\nelse\r\nheadings=findHeadings(document.body, []);\r\n\r\nfunction findHeadings(root, sects){\r\n for(var c=root.firstChild; c!=null; c=c.nextSibling){\r\nif (c.nodeType!==1) continue;\r\nif (c.tagName.length==2 &amp;&amp; c.tagName.charAt(0)==\"H\")\r\nsects.push(c);\r\nelse\r\nfindHeadings(c, sects);\r\n}\r\nreturn sects;\r\n}\r\n\r\nvar sectionNumbers=[0,0,0,0,0,0];\r\n\r\nfor(var h=0; h&lt;headings.length; h++) {\r\n var heading=headings[h];\r\n\r\nif(heading.parentNode==toc) continue;\r\n\r\nvar level=parseInt(heading.tagName.charAt(1));\r\nif (isNaN(level)||level&lt;1||level&gt;6) continue;\r\n\r\nsectionNumbers[level-1]++;\r\nfor(var i=level; i&lt;6; i++) sectionNumbers[i]=0;\r\n\r\nvar sectionNumber=sectionNumbers.slice(0, level).join(\".\");\r\n\r\nvar span=document.createElement(\"span\");\r\nspan.className=\"TOCSectNum\";\r\nspan.innerHTML=sectionNumber;\r\nheading.insertBefore(span, heading.firstChild);\r\nheading.id=\"TOC\"+sectionNumber;\r\nvar anchor=document.createElement(\"a\");\r\nheading.parentNode.insertBefore(anchor, heading);\r\nanchor.appendChild(heading);\r\n\r\nvar link=document.createElement(\"a\");\r\nlink.href=\"#TOC\"+sectionNumber; \r\nlink.innerHTML=heading.innerHTML;\r\n\r\nvar entry=document.createElement(\"div\");\r\nentry.className=\"TOCEntry TOCLevel\" + level;\r\nentry.appendChild(link);\r\n\r\ntoc.appendChild(entry);\r\n}\r\n};</code></pre>\r\n</div>\r\n</div>\r\n\nSource:<a href=\"http://www.siteforinfotech.com/2015/02/how-to-create-table-of-contents-using-javascript.html\" rel=\"nofollow\">How to Create Table of Contents Using JavaScript</a></p>\n" }, { "answer_id": 32867186, "author": "Hendrik", "author_id": 5393185, "author_profile": "https://Stackoverflow.com/users/5393185", "pm_score": 3, "selected": false, "text": "<p>I've modified the function in AtesGoral's accepted answer to output correctly nested lists and valid HTML5.</p>\n\n<p>Just add the code below to your scripts and call <code>TableOfContents(container, output);</code> on load, where <em>container</em> is the class or id of your content element and <em>output</em> is the class or id of the TOC element. Default values are '#contents' and '#toc', respectively.</p>\n\n<p>See <a href=\"http://codepen.io/aufmkolk/pen/RWKLzr\" rel=\"noreferrer\">http://codepen.io/aufmkolk/pen/RWKLzr</a> for a working demo.</p>\n\n<pre><code>function TableOfContents(container, output) {\nvar toc = \"\";\nvar level = 0;\nvar container = document.querySelector(container) || document.querySelector('#contents');\nvar output = output || '#toc';\n\ncontainer.innerHTML =\n container.innerHTML.replace(\n /&lt;h([\\d])&gt;([^&lt;]+)&lt;\\/h([\\d])&gt;/gi,\n function (str, openLevel, titleText, closeLevel) {\n if (openLevel != closeLevel) {\n return str;\n }\n\n if (openLevel &gt; level) {\n toc += (new Array(openLevel - level + 1)).join('&lt;ul&gt;');\n } else if (openLevel &lt; level) {\n toc += (new Array(level - openLevel + 1)).join('&lt;/li&gt;&lt;/ul&gt;');\n } else {\n toc += (new Array(level+ 1)).join('&lt;/li&gt;');\n }\n\n level = parseInt(openLevel);\n\n var anchor = titleText.replace(/ /g, \"_\");\n toc += '&lt;li&gt;&lt;a href=\"#' + anchor + '\"&gt;' + titleText\n + '&lt;/a&gt;';\n\n return '&lt;h' + openLevel + '&gt;&lt;a href=\"#' + anchor + '\" id=\"' + anchor + '\"&gt;'\n + titleText + '&lt;/a&gt;&lt;/h' + closeLevel + '&gt;';\n }\n );\n\nif (level) {\n toc += (new Array(level + 1)).join('&lt;/ul&gt;');\n}\ndocument.querySelector(output).innerHTML += toc;\n};\n</code></pre>\n" }, { "answer_id": 37335124, "author": "Frank Pimenta", "author_id": 6358506, "author_profile": "https://Stackoverflow.com/users/6358506", "pm_score": 0, "selected": false, "text": "<pre><code> let headers = document.querySelectorAll('h1,h2,h3,h4,h5,h6');\n let list = document.createElement('ol');\n\n let _el = list;\n for(i=0; i&lt;headers.length; i++) {\n while(_el) {\n let li = document.createElement('li');\n li.innerText = headers[i].innerText;\n li.setAttribute('tagName', headers[i].tagName);\n if(_el.getAttribute('tagName') &lt; headers[i].tagName) {\n let ol = _el.children.length &gt; 0 ? ol = _el.querySelector('ol') : document.createElement('ol');\n ol.appendChild(li);\n _el.appendChild(ol);\n _el = li;\n break;\n } else {\n if(_el.tagName == 'OL') {\n _el.appendChild(li);\n _el = li;\n break;\n } else if (!_el.parentNode.parentNode) {\n _el.parentNode.appendChild(li);\n _el = li;\n break;\n }\n else {\n _el = _el.parentNode.parentNode;\n }\n }\n }\n }\n console.log(list);\n</code></pre>\n" }, { "answer_id": 37335781, "author": "Frank Pimenta", "author_id": 6358506, "author_profile": "https://Stackoverflow.com/users/6358506", "pm_score": 0, "selected": false, "text": "<pre><code> this.insert = (el, h) =&gt; {\n let li = document.createElement('li');\n li.innerText = h.innerText;\n li.setAttribute('tagName', h.tagName);\n if(el.tagName == 'OL') {\n el.appendChild(li);\n return li;\n } else if(el.getAttribute('tagName') &lt; h.tagName) {\n let ol = el.children.length &gt; 0 ? ol = el.querySelector('ol') : document.createElement('ol');\n ol.appendChild(li);\n el.appendChild(ol);\n return li;\n } else if(!el.parentNode.parentNode) {\n el.parentNode.appendChild(li);\n return li;\n } else {\n return this.insert(el.parentNode.parentNode, h);\n }\n }\n\n this.parse = (headers) =&gt; {\n let list = document.createElement('ol');\n let el = list;\n for(i=0; i&lt;headers.length; i++) {\n el = this.insert(el, headers[i]);\n }\n return list;\n }\n let headers = document.querySelectorAll('h1,h2,h3,h4,h5,h6');\n let toc = this.parse(headers);\n console.log(toc);\n</code></pre>\n" }, { "answer_id": 41085566, "author": "Hasse Björk", "author_id": 4405465, "author_profile": "https://Stackoverflow.com/users/4405465", "pm_score": 2, "selected": false, "text": "<p>I really love <a href=\"https://stackoverflow.com/a/19185002\">d13's answer</a>, but would like to improve it slightly to use html5 notations and keep a header's existing id:</p>\n\n<pre><code>document.addEventListener('DOMContentLoaded', function() {\n htmlTableOfContents();\n} ); \n\nfunction htmlTableOfContents( documentRef ) {\n var documentRef = documentRef || document;\n var toc = documentRef.getElementById(\"toc\");\n// Use headings inside &lt;article&gt; only:\n// var headings = [].slice.call(documentRef.body.querySelectorAll('article h1, article h2, article h3, article h4, article h5, article h6'));\n var headings = [].slice.call(documentRef.body.querySelectorAll('h1, h2, h3, h4, h5, h6'));\n headings.forEach(function (heading, index) {\n var ref = \"toc\" + index;\n if ( heading.hasAttribute( \"id\" ) ) \n ref = heading.getAttribute( \"id\" );\n else\n heading.setAttribute( \"id\", ref );\n\n var link = documentRef.createElement( \"a\" );\n link.setAttribute( \"href\", \"#\"+ ref );\n link.textContent = heading.textContent;\n\n var div = documentRef.createElement( \"div\" );\n div.setAttribute( \"class\", heading.tagName.toLowerCase() );\n div.appendChild( link );\n toc.appendChild( div );\n });\n}\n\ntry {\n module.exports = htmlTableOfContents;\n} catch (e) {\n // module.exports is not defined\n}\n</code></pre>\n\n<p>You use it by including the script in your header.</p>\n\n<p>The awesome thing is, you can use stylesheets for your table of contents:</p>\n\n<pre><code>&lt;style&gt;\n #toc div.h1 { margin-left: 0 }\n #toc div.h2 { margin-left: 1em }\n #toc div.h3 { margin-left: 2em }\n #toc div.h4 { margin-left: 3em }\n&lt;/style&gt;\n</code></pre>\n\n<p>In my personal script, I use a slightly different selector:</p>\n\n<pre><code>var headings = [].slice.call(documentRef.body.querySelectorAll(\"article h1, article h2, article h3, article h4, article h5, h6\"));\n</code></pre>\n\n<p>The main page is kept inside <code>&lt;article&gt;&lt;/article&gt;</code> and the script will search for headings inside the main article only. I can use a heading inside the table of contents, like <code>&lt;nav id=\"toc\"&gt;&lt;h3&gt;Table of contents&lt;/h3&gt;&lt;/nav&gt;</code> or in a footer/header without it showing up inside the toc.</p>\n\n<p>In the comments below <a href=\"https://stackoverflow.com/users/1076652/gabriel-hautclocq\">Gabriel Hautclocq</a> has optimizations of the article code. He also points out, this is not strictly a list but a list-like div structure, which is simpler and generates shorter code.</p>\n" }, { "answer_id": 51333337, "author": "KingNonso", "author_id": 8676374, "author_profile": "https://Stackoverflow.com/users/8676374", "pm_score": 2, "selected": false, "text": "<p>So I had a problem with the answer provided by @Ates Goral and @Hendrik, I use a WYSIWYG which adds some html snippets in the H1-h6 elements like br tags and the rest. So the code breaks and doesn't recognize it as a valid h element since it doesn't match the search pattern. Also some WYSIWYG leave empty h-tags which are not excluded since they have no content. And the various modifications that follows often break with the same problem.\nA major bug I fixed was that if you had a heading, with the same text it would only reference the first- solutions provided by @Ates Goral and @Hendrik</p>\n\n<p>I should state that this solution is good if you are generating the table of content from data stored in the database. And I used some of the solutions above and built upon, especially @Ates Goral and @Hendrik</p>\n\n<pre><code>function TableOfContents(container, output) {\n var txt = \"toc-\"; \n var toc = \"\";\n var start = 0;\n var output = output || '#toc';\n\n var container = document.querySelector(container) || document.querySelector('#contents');\n var c = container.children;\n\n for (var i = 0; i &lt; c.length; i++) {\n var isHeading = c[i].nodeName.match(/^H\\d+$/) ;\n if(c[i].nodeName.match(/^H\\d+$/)){\n var level = c[i].nodeName.substr(1);\n// get header content regardless of whether it contains a html or not that breaks the reg exp pattern\n var headerText = (c[i].textContent);\n// generate unique ids as tag anchors\n var anchor = txt+i;\n\n var tag = '&lt;a href=\"#' + anchor + '\" id=\"' + anchor + '\"&gt;' + headerText + '&lt;/a&gt;';\n\n c[i].innerHTML = tag;\n\n if(headerText){\n if (level &gt; start) {\n toc += (new Array(level - start + 1)).join('&lt;ul&gt;');\n } else if (level &lt; start) {\n toc += (new Array(start - level + 1)).join('&lt;/li&gt;&lt;/ul&gt;');\n } else {\n toc += (new Array(start+ 1)).join('&lt;/li&gt;');\n }\n start = parseInt(level);\n toc += '&lt;li&gt;&lt;a href=\"#' + anchor + '\"&gt;' + headerText + '&lt;/a&gt;';\n }\n }\n }\n if (start) {\n toc += (new Array(start + 1)).join('&lt;/ul&gt;');\n }\n document.querySelector(output).innerHTML += toc;\n}\n\ndocument.addEventListener('DOMContentLoaded', function() {\n TableOfContents();\n }\n ); \n</code></pre>\n" }, { "answer_id": 67184970, "author": "denpost", "author_id": 5052378, "author_profile": "https://Stackoverflow.com/users/5052378", "pm_score": 0, "selected": false, "text": "<p>Here's a jQuery-based function that analyzes heading elements <code>&lt;h1&gt;</code>, <code>&lt;h2&gt;</code> ... in provided content and returns jQuery object with TOC hierarchy that you may append to your page:</p>\n<pre><code>&lt;div class=&quot;table_of_contents&quot;&gt;\n &lt;ul&gt;\n &lt;a href=&quot;#Level1_Heading&quot;&gt;Level1 Heading&lt;/a&gt;\n &lt;li&gt;\n &lt;a href=&quot;#Level2_Heading&quot;&gt;Level2 Heading&lt;/a&gt;\n &lt;ul&gt;\n ...\n &lt;/li&gt;\n &lt;/ul&gt;\n&lt;/div&gt;\n</code></pre>\n<p>It also modifies <code>$content</code> by inserting invisible <code>&lt;a name=&quot;...&quot;&gt;</code> anchors to which a user will jump when clicking the created TOC items.</p>\n<pre><code>function generate_toc($content) {\n let $toc = $(&quot;&lt;div&gt;&quot;, {class: &quot;table_of_contents&quot;});\n let level2$toc_item = {0: $toc};\n let used_anchors = {};\n $content.find(&quot;h1, h2, h3, h4, h5&quot;).each(function() {\n // find out the level of heading\n let level = parseInt($(this).prop(&quot;tagName&quot;).replace(/[^0-9]/gi, &quot;&quot;));\n let heading_text = $(this).text();\n // define the unique anchor id\n let heading_anchor = heading_text.replace(/[^a-z0-9]/gi, &quot;_&quot;);\n while (heading_anchor in used_anchors) {heading_anchor += &quot;_&quot;;}\n used_anchors[heading_anchor] = true; \n // add target point into main content\n $(this).prepend($(&quot;&lt;a&gt;&quot;, {name: heading_anchor}));\n // find the parent level for TOC item\n let parent_level = level-1;\n for (; !(parent_level in level2$toc_item); parent_level--); \n // remove all jumped over levels\n for (let l in level2$toc_item) {\n if (parseInt(l) &gt; parent_level) {\n delete level2$toc_item[l];\n }\n }\n let $parent = level2$toc_item[parent_level];\n // create new TOC item inside parent's &lt;ul&gt;\n level2$toc_item[level] = $(&quot;&lt;li&gt;&quot;).appendTo(\n $parent.children(&quot;ul&quot;).length == 1\n ? $($parent.children(&quot;ul&quot;)[0])\n : $(&quot;&lt;ul&gt;&quot;).appendTo($parent)\n ).append($(&quot;&lt;a&gt;&quot;, {href: `#${heading_anchor}`}).text(heading_text));\n });\n return $toc;\n}\n</code></pre>\n<p>Example of use:</p>\n<pre><code>$(&quot;body&quot;).prepend(generate_toc(&quot;body&quot;));\n</code></pre>\n" }, { "answer_id": 67552284, "author": "CMSG", "author_id": 8469099, "author_profile": "https://Stackoverflow.com/users/8469099", "pm_score": 3, "selected": false, "text": "<p>This is a vanilla JavaScript version of a Table of Contents I came up with for work.</p>\n<p>It looks for all the headings in a specified content container and creates IDs for them, then generates the TOC links. I have it adding classes for styling and use nested lists to create a hierarchy.</p>\n<pre><code>window.addEventListener('DOMContentLoaded', function (event) { // Let the DOM content load before running the script.\n//Get all headings only from the actual contents.\nvar contentContainer = document.getElementById('content'); // Add this div to the html\nvar headings = contentContainer.querySelectorAll('h1,h2,h3,h4'); // You can do as many or as few headings as you need.\n\nvar tocContainer = document.getElementById('toc'); // Add this div to the HTML\n// create ul element and set the attributes.\nvar ul = document.createElement('ul');\n\nul.setAttribute('id', 'tocList');\nul.setAttribute('class', 'sidenav')\n\n// Loop through the headings NodeList\nfor (i = 0; i &lt;= headings.length - 1; i++) {\n\n var id = headings[i].innerHTML.toLowerCase().replace(/ /g, &quot;-&quot;); // Set the ID to the header text, all lower case with hyphens instead of spaces.\n var level = headings[i].localName.replace(&quot;h&quot;, &quot;&quot;); // Getting the header a level for hierarchy\n var title = headings[i].innerHTML; // Set the title to the text of the header\n\n headings[i].setAttribute(&quot;id&quot;, id) // Set header ID to its text in lower case text with hyphens instead of spaces.\n\n var li = document.createElement('li'); // create li element.\n li.setAttribute('class', 'sidenav__item') // Assign a class to the li\n\n var a = document.createElement('a'); // Create a link\n a.setAttribute(&quot;href&quot;, &quot;#&quot; + id) // Set the href to the heading ID\n a.innerHTML = title; // Set the link text to the heading text\n \n // Create the hierarchy\n if(level == 1) {\n li.appendChild(a); // Append the link to the list item\n ul.appendChild(li); // append li to ul.\n } else if (level == 2) {\n child = document.createElement('ul'); // Create a sub-list\n child.setAttribute('class', 'sidenav__sublist')\n li.appendChild(a); \n child.appendChild(li);\n ul.appendChild(child);\n } else if (level == 3) {\n grandchild = document.createElement('ul');\n grandchild.setAttribute('class', 'sidenav__sublist')\n li.appendChild(a);\n grandchild.appendChild(li);\n child.appendChild(grandchild);\n } else if (level == 4) {\n great_grandchild = document.createElement('ul');\n great_grandchild.setAttribute('class', 'sidenav__sublist');\n li.append(a);\n great_grandchild.appendChild(li);\n grandchild.appendChild(great_grandchild);\n }\n}\n\ntoc.appendChild(ul); // add list to the container\n\n// Add a class to the first list item to allow for toggling active state.\nvar links = tocContainer.getElementsByClassName(&quot;sidenav__item&quot;);\n\nlinks[0].classList.add('current');\n\n// Loop through the links and add the active class to the current/clicked link\nfor (var i = 0; i &lt; links.length; i++) {\n links[i].addEventListener(&quot;click&quot;, function() {\n var current = document.getElementsByClassName(&quot;current&quot;);\n current[0].className = current[0].className.replace(&quot; current&quot;, &quot;&quot;);\n this.className += &quot; current&quot;;\n });\n}\n});\n</code></pre>\n<p>I have a demo on <a href=\"https://codepen.io/cgurski/pen/qBrNrPo\" rel=\"nofollow noreferrer\">CodePen</a>.</p>\n" }, { "answer_id": 69260236, "author": "Carson", "author_id": 9935654, "author_profile": "https://Stackoverflow.com/users/9935654", "pm_score": 0, "selected": false, "text": "<p>The key is to capture the data of headings and convert it into an object<sup> <code>TocItem</code> see below code</sup>.</p>\n<p>As for the TOC presentation, you can use <a href=\"https://developer.mozilla.org/en-US/docs/Web/HTML/Element/ul\" rel=\"nofollow noreferrer\">ul</a> or rely on <a href=\"https://markmap.js.org/\" rel=\"nofollow noreferrer\">markmap.js</a>, <a href=\"https://github.com/d3/d3\" rel=\"nofollow noreferrer\">d3.js</a> to generate, etc.</p>\n<h3>core code</h3>\n<pre class=\"lang-js prettyprint-override\"><code>/**\n * @param {string} text\n * @param {int} level\n * @param {TocItem} parent\n * */\nfunction TocItem(text, level, parent = undefined) {\n this.text = text\n this.level = level\n this.id = undefined\n this.parent = parent\n this.children = []\n}\n\n/**\n* @param {[HTMLHeadingElement]} headingSet\n* */\nfunction parse(headingSet) {\n const tocData = []\n let curLevel = 0\n let preTocItem = undefined\n\n headingSet.forEach(heading =&gt; {\n const hLevel = heading.outerHTML.match(/&lt;h([\\d]).*&gt;/)[1]\n const titleText = heading.innerText\n\n switch (hLevel &gt;= curLevel) {\n case true:\n if (preTocItem === undefined) {\n preTocItem = new TocItem(titleText, hLevel)\n tocData.push(preTocItem)\n } else {\n const curTocItem = new TocItem(titleText, hLevel)\n const parent = curTocItem.level &gt; preTocItem.level ? preTocItem : preTocItem.parent\n curTocItem.parent = parent\n parent.children.push(curTocItem)\n preTocItem = curTocItem\n }\n break\n case false:\n // We need to find the appropriate parent node from the preTocItem\n const curTocItem = new TocItem(titleText, hLevel)\n while (1) {\n if (preTocItem.level &lt; curTocItem.level) {\n preTocItem.children.push(curTocItem)\n preTocItem = curTocItem\n break\n }\n preTocItem = preTocItem.parent\n\n if (preTocItem === undefined) {\n tocData.push(curTocItem)\n preTocItem = curTocItem\n break\n }\n }\n break\n }\n\n curLevel = hLevel\n\n if (heading.id === &quot;&quot;) {\n heading.id = titleText.replace(/ /g, &quot;-&quot;).toLowerCase()\n }\n preTocItem.id = heading.id\n })\n\n return tocData\n}\n</code></pre>\n<h3>Example</h3>\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;style&gt;\n /* CSS is not necessary. That is for look better and easy to test. */\n\n /* Longer pages, so you can test to see if you can actually get to the specified location after clicking. */\n body {\n min-height: 160rem\n }\n\n /* similar to the bootstrap */\n .fixed-top {\n position: fixed;\n top: 0;\n right: 50vw;\n z-index: 1000;\n }\n&lt;/style&gt;\n\n&lt;div id=\"target\"&gt;\n &lt;h1 id=\"my-app\"&gt;App1&lt;/h1&gt;\n &lt;h2&gt;Video&lt;/h2&gt;\n &lt;h3&gt;mp4&lt;/h3&gt;\n &lt;h3&gt;webm&lt;/h3&gt;\n\n &lt;h2&gt;Audio&lt;/h2&gt;\n &lt;h3&gt;Mp3&lt;/h3&gt;\n &lt;h3&gt;m4a&lt;/h3&gt;\n\n &lt;h1&gt;App2&lt;/h1&gt;\n &lt;h2&gt;Overview&lt;/h2&gt;\n&lt;/div&gt;\n\n&lt;script&gt;\n\n class TOC {\n /**\n * @param {[HTMLHeadingElement]} headingSet\n * */\n static parse(headingSet) {\n const tocData = []\n let curLevel = 0\n let preTocItem = undefined\n\n headingSet.forEach(heading =&gt; {\n const hLevel = heading.outerHTML.match(/&lt;h([\\d]).*&gt;/)[1]\n const titleText = heading.innerText\n\n switch (hLevel &gt;= curLevel) {\n case true:\n if (preTocItem === undefined) {\n preTocItem = new TocItem(titleText, hLevel)\n tocData.push(preTocItem)\n } else {\n const curTocItem = new TocItem(titleText, hLevel)\n const parent = curTocItem.level &gt; preTocItem.level ? preTocItem : preTocItem.parent\n curTocItem.parent = parent\n parent.children.push(curTocItem)\n preTocItem = curTocItem\n }\n break\n case false:\n // We need to find the appropriate parent node from the preTocItem\n const curTocItem = new TocItem(titleText, hLevel)\n while (1) {\n if (preTocItem.level &lt; curTocItem.level) {\n preTocItem.children.push(curTocItem)\n preTocItem = curTocItem\n break\n }\n preTocItem = preTocItem.parent\n\n if (preTocItem === undefined) {\n tocData.push(curTocItem)\n preTocItem = curTocItem\n break\n }\n }\n break\n }\n\n curLevel = hLevel\n\n if (heading.id === \"\") {\n heading.id = titleText.replace(/ /g, \"-\").toLowerCase()\n }\n preTocItem.id = heading.id\n })\n\n return tocData\n }\n\n /**\n * @param {[TocItem]} tocData\n * @return {string}\n * */\n static build(tocData) {\n let result = \"&lt;ul&gt;\"\n tocData.forEach(toc =&gt; {\n result += `&lt;li&gt;&lt;a href=#${toc.id}&gt;${toc.text}&lt;/a&gt;&lt;/li&gt;`\n if (toc.children.length) {\n result += `${TOC.build(toc.children)}`\n }\n })\n return result + \"&lt;/ul&gt;\"\n }\n }\n\n /**\n * @param {string} text\n * @param {int} level\n * @param {TocItem} parent\n * */\n function TocItem(text, level, parent = undefined) {\n this.text = text\n this.level = level\n this.id = undefined\n this.parent = parent\n this.children = []\n }\n\n window.onload = () =&gt; {\n\n const headingSet = document.querySelectorAll(\"h1, h2, h3, h4, h5, h6\") // You can also select only the titles you are interested in.\n const tocData = TOC.parse(headingSet)\n \n console.log(tocData)\n\n const tocHTMLContent = TOC.build(tocData)\n const frag = document.createRange().createContextualFragment(`&lt;fieldset class=\"fixed-top\"&gt;&lt;legend&gt;TOC&lt;/legend&gt;${tocHTMLContent}&lt;/fieldset&gt;`)\n document.querySelector(`body`).insertBefore(frag, document.querySelector(`body`).firstChild)\n }\n&lt;/script&gt;</code></pre>\r\n</div>\r\n</div>\r\n</p>\n<p><em>vanilla JavaScript</em> too</p>\n" }, { "answer_id": 70199468, "author": "Levi Cole", "author_id": 3804924, "author_profile": "https://Stackoverflow.com/users/3804924", "pm_score": 0, "selected": false, "text": "<p>I may be a bit late to the game but I've put together my own jQuery plugin...</p>\n<p>Available via jsDeliver CDN: <a href=\"https://cdn.jsdelivr.net/npm/@thelevicole/toc.js@1/dist/toc.jquery.js\" rel=\"nofollow noreferrer\">https://cdn.jsdelivr.net/npm/@thelevicole/toc.js@1/dist/toc.jquery.js</a></p>\n<p>A quick example of page structure:</p>\n<pre class=\"lang-html prettyprint-override\"><code>&lt;div class=&quot;table-of-contents&quot;&gt;&lt;/div&gt;\n&lt;h1&gt;Heading 1&lt;/h1&gt;\n&lt;h2&gt;Heading 2&lt;/h2&gt;\n&lt;h3&gt;Heading 3&lt;/h3&gt;\n&lt;h2&gt;Heading 2&lt;/h2&gt;\n&lt;h2&gt;Heading 2&lt;/h2&gt;\n&lt;h1&gt;Heading 1&lt;/h1&gt;\n</code></pre>\n<p>Now initiate the plugin:</p>\n<pre class=\"lang-js prettyprint-override\"><code>$('.table-of-contents').tableOfContents();\n</code></pre>\n<p>Which will output this list:</p>\n<pre class=\"lang-html prettyprint-override\"><code>&lt;ul class=&quot;toc-list&quot;&gt;\n &lt;li class=&quot;toc-item&quot;&gt;\n &lt;a href=&quot;#heading-1&quot; class=&quot;toc-link&quot;&gt;Heading 1&lt;/a&gt;\n &lt;ul class=&quot;toc-list&quot;&gt;\n &lt;li class=&quot;toc-item&quot;&gt;\n &lt;a href=&quot;#heading-2&quot; class=&quot;toc-link&quot;&gt;Heading 2&lt;/a&gt;\n &lt;ul class=&quot;toc-list&quot;&gt;\n &lt;li class=&quot;toc-item&quot;&gt;\n &lt;a href=&quot;#heading-3&quot; class=&quot;toc-link&quot;&gt;Heading 3&lt;/a&gt;\n &lt;/li&gt;\n &lt;/ul&gt;\n &lt;/li&gt;\n &lt;li class=&quot;toc-item&quot;&gt;\n &lt;a href=&quot;#heading-4&quot; class=&quot;toc-link&quot;&gt;Heading 2&lt;/a&gt;\n &lt;/li&gt;\n &lt;li class=&quot;toc-item&quot;&gt;\n &lt;a href=&quot;#heading-5&quot; class=&quot;toc-link&quot;&gt;Heading 2&lt;/a&gt;\n &lt;/li&gt;\n &lt;/ul&gt;\n &lt;/li&gt;\n &lt;li class=&quot;toc-item&quot;&gt;\n &lt;a href=&quot;#heading-6&quot; class=&quot;toc-link&quot;&gt;Heading 1&lt;/a&gt;\n &lt;/li&gt;\n&lt;/ul&gt;\n</code></pre>\n<p>Screenshot for reference:</p>\n<p><a href=\"https://i.stack.imgur.com/lXWdG.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/lXWdG.png\" alt=\"enter image description here\" /></a></p>\n<hr />\n<p>There are a number of options that can be passed...</p>\n<pre class=\"lang-js prettyprint-override\"><code>$('.table-of-contents').tableOfContents({\n contentTarget: $( document.body ), // The element with content.\n selectors: 'h1$1; h2$2; h3$3; h4$4; h5$5; h6$6;', // Tree structure.\n nestingDepth: -1, // How deep we'll allow nesting. -1 for infinate.\n slugLength: 40, // The max number of chars in the hash slug.\n anchors: true, // Add anchors to headings.\n anchorText: '#', // The symbol added to headings.\n orderedList: false // True to use &lt;ol&gt; instead of &lt;ul&gt;\n});\n</code></pre>\n<p>The <code>selectors</code> option allows you create a table of contents from other selectors not just h1, h2, h3's etc.</p>\n<p>The selector option accepts a string, array or object of selectors and depths:</p>\n<p><strong>String</strong></p>\n<pre class=\"lang-js prettyprint-override\"><code>$('.table-of-contents').tableOfContents({\n // '{selector}${depth}; {selector}${depth}; ...'\n selectors: 'h1$1; h2$2; h3$3; p:not(.my-class)$2; ...'\n});\n</code></pre>\n<p>The selector pattern is fairly straight forward, and follows a simple pattern. We first have the DOM/CSS selector {selector} followed by the nesting depth which starts with a dollar symbol ${depth} and finished with a semicolon ;</p>\n<p>The default pattern used for nested headings looks like this: <code>'h1$1; h2$2; h3$3; h4$4; h5$5; h6$6;'</code></p>\n<p><strong>Array</strong></p>\n<pre class=\"lang-js prettyprint-override\"><code>$('.table-of-contents').tableOfContents({\n selectors: [\n // '{selector}${depth}'\n 'h1$1',\n 'h2$2',\n 'h3$3',\n 'p:not(.my-class)$2',\n ...\n ]\n});\n</code></pre>\n<p><strong>Object</strong></p>\n<pre class=\"lang-js prettyprint-override\"><code>$('.table-of-contents').tableOfContents({\n selectors: {\n // '{selector}': {depth}\n 'h1': 1,\n 'h2': 2,\n 'h3': 3,\n 'p:not(.my-class)': 2,\n ...\n }\n});\n</code></pre>\n<p>Custom selector example:</p>\n<pre class=\"lang-html prettyprint-override\"><code>&lt;div class=&quot;table-of-contents&quot;&gt;&lt;/div&gt;\n\n&lt;article&gt;\n &lt;p class=&quot;level-1&quot;&gt;I'm level 1&lt;/p&gt;\n &lt;p class=&quot;level-2&quot;&gt;I'm level 2&lt;/p&gt;\n &lt;p class=&quot;level-1&quot;&gt;I'm level 1 again&lt;/p&gt;\n &lt;p class=&quot;level-2&quot;&gt;I'm level 2 again&lt;/p&gt;\n &lt;p class=&quot;level-3&quot;&gt;I'm level 3&lt;/p&gt;\n &lt;p&gt;&lt;strong&gt;I'm a div element&lt;/strong&gt;&lt;/p&gt;\n &lt;p class=&quot;level-2&quot;&gt;I'm level 2&lt;/p&gt;\n&lt;/article&gt;\n</code></pre>\n<pre class=\"lang-js prettyprint-override\"><code>$('.table-of-contents').tableOfContents({\n contentTarget: 'article',\n selectors: '.level-1 $1; .level-2 $2; .level-3 $3; p &gt; strong $4'\n});\n</code></pre>\n<p>Will result in...</p>\n<p><a href=\"https://i.stack.imgur.com/zmUCQ.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/zmUCQ.png\" alt=\"enter image description here\" /></a></p>\n<hr />\n<p>I haven't yet had chance to write proper documentation but you can follow this project on GitHub: <a href=\"https://github.com/thelevicole/toc.js\" rel=\"nofollow noreferrer\">https://github.com/thelevicole/toc.js</a> or see the homepage here: <a href=\"https://thelevicole.com/toc.js/\" rel=\"nofollow noreferrer\">https://thelevicole.com/toc.js/</a></p>\n" } ]
2008/10/09
[ "https://Stackoverflow.com/questions/187619", "https://Stackoverflow.com", "https://Stackoverflow.com/users/572/" ]
I have headers in `<h1>` through `<h6>` tags. Is there a way that I can use JavaScript to generate a table of contents for the contents that serves as anchor tags as well? I would like the output to be something like: ``` <ol> <li>Header 1</li> <li>Header 1</li> <li>Header 2</li> <li>Header 3</li> </ol> ``` I am not currently using a JavaScript framework, but I don't see why I couldn't use one. I am also looking for something done, since I'm guessing this is a common problem, but if not, a starting point to roll my own would be good.
I couldn't resist putting together a quick implementation. Add the following script anywhere on your page: ``` window.onload = function () { var toc = ""; var level = 0; document.getElementById("contents").innerHTML = document.getElementById("contents").innerHTML.replace( /<h([\d])>([^<]+)<\/h([\d])>/gi, function (str, openLevel, titleText, closeLevel) { if (openLevel != closeLevel) { return str; } if (openLevel > level) { toc += (new Array(openLevel - level + 1)).join("<ul>"); } else if (openLevel < level) { toc += (new Array(level - openLevel + 1)).join("</ul>"); } level = parseInt(openLevel); var anchor = titleText.replace(/ /g, "_"); toc += "<li><a href=\"#" + anchor + "\">" + titleText + "</a></li>"; return "<h" + openLevel + "><a name=\"" + anchor + "\">" + titleText + "</a></h" + closeLevel + ">"; } ); if (level) { toc += (new Array(level + 1)).join("</ul>"); } document.getElementById("toc").innerHTML += toc; }; ``` Your page should be structured something like this: ``` <body> <div id="toc"> <h3>Table of Contents</h3> </div> <hr/> <div id="contents"> <h1>Fruits</h1> <h2>Red Fruits</h2> <h3>Apple</h3> <h3>Raspberry</h3> <h2>Orange Fruits</h2> <h3>Orange</h3> <h3>Tangerine</h3> <h1>Vegetables</h1> <h2>Vegetables Which Are Actually Fruits</h2> <h3>Tomato</h3> <h3>Eggplant</h3> </div> </body> ``` You can see it in action at <https://codepen.io/scheinercc/pen/KEowRK> (old link: <http://magnetiq.com/exports/toc.htm> (Works in IE, FF, Safari, Opera))
187,621
<p>I am aware of how to setup autocompletion of python objects in the python interpreter (on unix). </p> <ul> <li>Google shows many hits for explanations on how to do this.</li> <li>Unfortunately, there are so many references to that it is difficult to find what I need to do, which is slightly different.</li> </ul> <p>I need to know how to enable, tab/auto completion of arbitrary items in a command-line program written in python.</p> <p>My specific use case is a command-line python program that needs to send emails. I want to be able to autocomplete email addresses (I have the addresses on disk) when the user types part of it (and optionally presses the TAB key).</p> <p>I do not need it to work on windows or mac, just linux.</p>
[ { "answer_id": 187660, "author": "ephemient", "author_id": 20713, "author_profile": "https://Stackoverflow.com/users/20713", "pm_score": 7, "selected": true, "text": "<p>Use Python's <code>readline</code> bindings. For example,</p>\n\n<pre><code>import readline\n\ndef completer(text, state):\n options = [i for i in commands if i.startswith(text)]\n if state &lt; len(options):\n return options[state]\n else:\n return None\n\nreadline.parse_and_bind(\"tab: complete\")\nreadline.set_completer(completer)\n</code></pre>\n\n<p>The official <a href=\"https://docs.python.org/2/library/readline.html\" rel=\"noreferrer\">module docs</a> aren't much more detailed, see the <a href=\"http://tiswww.case.edu/php/chet/readline/readline.html#SEC44\" rel=\"noreferrer\">readline docs</a> for more info.</p>\n" }, { "answer_id": 187701, "author": "Florian Bösch", "author_id": 19435, "author_profile": "https://Stackoverflow.com/users/19435", "pm_score": 6, "selected": false, "text": "<p>Follow the <a href=\"http://docs.python.org/library/cmd.html#cmd.Cmd.cmdloop\" rel=\"noreferrer\">cmd documentation</a> and you'll be fine</p>\n\n<pre><code>import cmd\n\naddresses = [\n '[email protected]',\n '[email protected]',\n '[email protected]',\n]\n\nclass MyCmd(cmd.Cmd):\n def do_send(self, line):\n pass\n\n def complete_send(self, text, line, start_index, end_index):\n if text:\n return [\n address for address in addresses\n if address.startswith(text)\n ]\n else:\n return addresses\n\n\nif __name__ == '__main__':\n my_cmd = MyCmd()\n my_cmd.cmdloop()\n</code></pre>\n\n<p>Output for tab -> tab -> send -> tab -> tab -> f -> tab</p>\n\n<pre><code>(Cmd)\nhelp send\n(Cmd) send\[email protected] [email protected] [email protected]\n(Cmd) send [email protected]\n(Cmd)\n</code></pre>\n" }, { "answer_id": 197158, "author": "Owen", "author_id": 12592, "author_profile": "https://Stackoverflow.com/users/12592", "pm_score": 6, "selected": false, "text": "<p>Since you say \"NOT interpreter\" in your question, I guess you don't want answers involving python readline and suchlike. (<strong><em>edit</strong>: in hindsight, that's obviously not the case. Ho hum. I think this info is interesting anyway, so I'll leave it here.</em>)</p>\n\n<p>I think you might be after <a href=\"http://www.debian-administration.org/articles/317\" rel=\"noreferrer\">this</a>.</p>\n\n<p>It's about adding shell-level completion to arbitrary commands, extending bash's own tab-completion.</p>\n\n<p>In a nutshell, you'll create a file containing a shell-function that will generate possible completions, save it into <code>/etc/bash_completion.d/</code> and register it with the command <code>complete</code>. Here's a snippet from the linked page:</p>\n\n<pre><code>_foo() \n{\n local cur prev opts\n COMPREPLY=()\n cur=\"${COMP_WORDS[COMP_CWORD]}\"\n prev=\"${COMP_WORDS[COMP_CWORD-1]}\"\n opts=\"--help --verbose --version\"\n\n if [[ ${cur} == -* ]] ; then\n COMPREPLY=( $(compgen -W \"${opts}\" -- ${cur}) )\n return 0\n fi\n}\ncomplete -F _foo foo\n</code></pre>\n\n<p>In this case, the typing <code>foo --[TAB]</code> will give you the values in the variable <code>opts</code>, i.e. <code>--help</code>, <code>--verbose</code> and <code>--version</code>. For your purposes, you'll essentially want to customise the values that are put into <code>opts</code>.</p>\n\n<p>Do have a look at the example on the linked page, it's all pretty straightforward. </p>\n" }, { "answer_id": 209915, "author": "Paul D. Eden", "author_id": 3045, "author_profile": "https://Stackoverflow.com/users/3045", "pm_score": 4, "selected": false, "text": "<p>Here is a full-working version of the code that was very supplied by ephemient <a href=\"https://stackoverflow.com/questions/187621/how-to-make-a-python-command-line-program-autocomplete-arbitrary-things-not-int#187660\">here</a> (thank you).</p>\n\n<pre><code>import readline\n\naddrs = ['[email protected]', '[email protected]', '[email protected]']\n\ndef completer(text, state):\n options = [x for x in addrs if x.startswith(text)]\n try:\n return options[state]\n except IndexError:\n return None\n\nreadline.set_completer(completer)\nreadline.parse_and_bind(\"tab: complete\")\n\nwhile 1:\n a = raw_input(\"&gt; \")\n print \"You entered\", a\n</code></pre>\n" }, { "answer_id": 19554961, "author": "user178047", "author_id": 2345251, "author_profile": "https://Stackoverflow.com/users/2345251", "pm_score": 4, "selected": false, "text": "<pre><code># ~/.pythonrc\nimport rlcompleter, readline\nreadline.parse_and_bind('tab:complete')\n\n# ~/.bashrc\nexport PYTHONSTARTUP=~/.pythonrc\n</code></pre>\n" }, { "answer_id": 23959790, "author": "qed", "author_id": 562222, "author_profile": "https://Stackoverflow.com/users/562222", "pm_score": 5, "selected": false, "text": "<p>I am surprised that nobody has mentioned argcomplete, here is an example from the docs:</p>\n\n<pre><code>from argcomplete.completers import ChoicesCompleter\n\nparser.add_argument(\"--protocol\", choices=('http', 'https', 'ssh', 'rsync', 'wss'))\nparser.add_argument(\"--proto\").completer=ChoicesCompleter(('http', 'https', 'ssh', 'rsync', 'wss'))\n</code></pre>\n" }, { "answer_id": 55426280, "author": "Seperman", "author_id": 1497443, "author_profile": "https://Stackoverflow.com/users/1497443", "pm_score": 1, "selected": false, "text": "<p>The posted answers work fine but I have open sourced an autocomplete library that I wrote at work. We have been using it for a while in production and it is fast, stable and easy to use. It even has a demo mode so you can quickly test what you would get as you type words.</p>\n<p>To install it, simply run: <code>pip install fast-autocomplete</code></p>\n<p>Here is an example:</p>\n<pre class=\"lang-py prettyprint-override\"><code>&gt;&gt;&gt; from fast_autocomplete import AutoComplete\n&gt;&gt;&gt; words = {'book': {}, 'burrito': {}, 'pizza': {}, 'pasta':{}}\n&gt;&gt;&gt; autocomplete = AutoComplete(words=words)\n&gt;&gt;&gt; autocomplete.search(word='b', max_cost=3, size=3)\n[['book'], ['burrito']]\n&gt;&gt;&gt; autocomplete.search(word='bu', max_cost=3, size=3)\n[['burrito']]\n&gt;&gt;&gt; autocomplete.search(word='barrito', max_cost=3, size=3) # mis-spelling\n[['burrito']]\n</code></pre>\n<p>Checkout: <a href=\"https://github.com/seperman/fast-autocomplete\" rel=\"nofollow noreferrer\">https://github.com/seperman/fast-autocomplete</a> for the source code.</p>\n<p>And here is an explanation of how it works: <a href=\"http://zepworks.com/posts/you-autocomplete-me/\" rel=\"nofollow noreferrer\">http://zepworks.com/posts/you-autocomplete-me/</a></p>\n<p>It deals with mis-spellings and optionally sorting by the weight of the word. (let's say <code>burrito</code> is more important than <code>book</code>, then you give <code>burrito</code> a higher &quot;count&quot; and it will show up first before <code>book</code> in the results.</p>\n<p>Words is a dictionary and each word can have a context. For example the &quot;count&quot;, how to display the word, some other context around the word etc. In this example words didn't have any context.</p>\n" }, { "answer_id": 56363696, "author": "Flux", "author_id": 5916915, "author_profile": "https://Stackoverflow.com/users/5916915", "pm_score": 4, "selected": false, "text": "<p>You can try using the <a href=\"https://github.com/prompt-toolkit/python-prompt-toolkit\" rel=\"noreferrer\">Python Prompt Toolkit</a>, a library for building interactive command line applications in Python.</p>\n\n<p>The library makes it easy to add interactive autocomplete functionality, allowing the user to use the <kbd>Tab</kbd> key to visually cycle through the available choices. The library is cross-platform (Linux, OS X, FreeBSD, OpenBSD, Windows). Example:</p>\n\n<p><a href=\"https://i.stack.imgur.com/h4TmQ.gif\" rel=\"noreferrer\" title=\"pgcli\"><img src=\"https://i.stack.imgur.com/h4TmQ.gif\" alt=\"pgcli - Python Prompt Toolkit\" title=\"pgcli\"></a></p>\n\n<p>(Image source: <a href=\"https://github.com/dbcli/pgcli\" rel=\"noreferrer\">pcgli</a>)</p>\n" }, { "answer_id": 68425698, "author": "WaXxX333", "author_id": 12556213, "author_profile": "https://Stackoverflow.com/users/12556213", "pm_score": 1, "selected": false, "text": "<p>This works well.</p>\n<pre class=\"lang-py prettyprint-override\"><code>#!/usr/bin/python3\n\nimport readline\nreadline.parse_and_bind(&quot;tab: complete&quot;)\n\ndef complete(text,state):\n volcab = ['dog','cat','rabbit','bird','slug','snail']\n results = [x for x in volcab if x.startswith(text)] + [None]\n return results[state]\n\nreadline.set_completer(complete)\n\nline = input('prompt&gt; ')\n</code></pre>\n" } ]
2008/10/09
[ "https://Stackoverflow.com/questions/187621", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3045/" ]
I am aware of how to setup autocompletion of python objects in the python interpreter (on unix). * Google shows many hits for explanations on how to do this. * Unfortunately, there are so many references to that it is difficult to find what I need to do, which is slightly different. I need to know how to enable, tab/auto completion of arbitrary items in a command-line program written in python. My specific use case is a command-line python program that needs to send emails. I want to be able to autocomplete email addresses (I have the addresses on disk) when the user types part of it (and optionally presses the TAB key). I do not need it to work on windows or mac, just linux.
Use Python's `readline` bindings. For example, ``` import readline def completer(text, state): options = [i for i in commands if i.startswith(text)] if state < len(options): return options[state] else: return None readline.parse_and_bind("tab: complete") readline.set_completer(completer) ``` The official [module docs](https://docs.python.org/2/library/readline.html) aren't much more detailed, see the [readline docs](http://tiswww.case.edu/php/chet/readline/readline.html#SEC44) for more info.
187,640
<p>Is it good practice to have a class constructor that uses default parameters, or should I use separate overloaded constructors? For example:</p> <pre><code>// Use this... class foo { private: std::string name_; unsigned int age_; public: foo(const std::string&amp; name = "", const unsigned int age = 0) : name_(name), age_(age) { ... } }; // Or this? class foo { private: std::string name_; unsigned int age_; public: foo() : name_(""), age_(0) { } foo(const std::string&amp; name, const unsigned int age) : name_(name), age_(age) { ... } }; </code></pre> <p>Either version seems to work, e.g.:</p> <pre><code>foo f1; foo f2("Name", 30); </code></pre> <p>Which style do you prefer or recommend and why?</p>
[ { "answer_id": 187650, "author": "luke", "author_id": 16434, "author_profile": "https://Stackoverflow.com/users/16434", "pm_score": 8, "selected": true, "text": "<p>Definitely a matter of style. I prefer constructors with default parameters, so long as the parameters make sense. Classes in the standard use them as well, which speaks in their favor.</p>\n\n<p>One thing to watch out for is if you have defaults for all but one parameter, your class can be implicitly converted from that parameter type. Check out <a href=\"https://stackoverflow.com/questions/174349/forcing-single-argument-constructors-to-be-explicit-in-c\">this thread</a> for more info.</p>\n" }, { "answer_id": 187678, "author": "Paul Nathan", "author_id": 26227, "author_profile": "https://Stackoverflow.com/users/26227", "pm_score": 4, "selected": false, "text": "<p>In my experience, default parameters seem cool at the time and make my laziness factor happy, but then down the road I'm using the class and I am surprised when the default kicks in. So I don't really think it's a good idea; better to have a className::className() and then a className::init(<em>arglist</em>). Just for that maintainability edge.</p>\n" }, { "answer_id": 187693, "author": "Sam Stokes", "author_id": 20131, "author_profile": "https://Stackoverflow.com/users/20131", "pm_score": 6, "selected": false, "text": "<p>I'd go with the default arguments, especially since C++ doesn't let you chain constructors (so you end up having to duplicate the initialiser list, and possibly more, for each overload).</p>\n\n<p>That said, there are some gotchas with default arguments, including the fact that constants may be inlined (and thereby become part of your class' binary interface). Another to watch out for is that adding default arguments can turn an explicit multi-argument constructor into an implicit one-argument constructor:</p>\n\n<pre><code>class Vehicle {\npublic:\n Vehicle(int wheels, std::string name = \"Mini\");\n};\n\nVehicle x = 5; // this compiles just fine... did you really want it to?\n</code></pre>\n" }, { "answer_id": 187706, "author": "James Curran", "author_id": 12725, "author_profile": "https://Stackoverflow.com/users/12725", "pm_score": 2, "selected": false, "text": "<p>I would go with the default parameters, for this reason: Your example assumes that ctor parameters directly correspond to member variables. But what if that is not the case, and you have to process the parameters before the object is initialize. Having one common ctor would be the best way to go.</p>\n" }, { "answer_id": 187714, "author": "Luc Touraille", "author_id": 20984, "author_profile": "https://Stackoverflow.com/users/20984", "pm_score": 2, "selected": false, "text": "<p>One thing bothering me with default parameters is that you can't specify the last parameters but use the default values for the first ones. For example, in your code, you can't create a Foo with no name but a given age (however, if I remember correctly, this will be possible in C++0x, with the unified constructing syntax). Sometimes, this makes sense, but it can also be really awkward.</p>\n\n<p>In my opinion, there is no rule of thumb. Personnaly, I tend to use multiple overloaded constructors (or methods), except if only the last argument needs a default value.</p>\n" }, { "answer_id": 187939, "author": "Nik Reiman", "author_id": 14302, "author_profile": "https://Stackoverflow.com/users/14302", "pm_score": 2, "selected": false, "text": "<p>If creating constructors with arguments is bad (as many would argue), then making them with default arguments is even worse. I've recently started to come around to the opinion that ctor arguments are bad, because your ctor logic should <em>be as minimal as possible</em>. How do you deal with error handling in the ctor, should somebody pass in an argument that doesn't make any sense? You can either throw an exception, which is bad news unless all of your callers are prepared to wrap any \"new\" calls inside of try blocks, or setting some \"is-initialized\" member variable, which is kind of a dirty hack.</p>\n\n<p>Therefore, the only way to make sure that the arguments passed into the initialization stage of your object is to set up a separate initialize() method where you can check the return code.</p>\n\n<p>The use of default arguments is bad for two reasons; first of all, if you want to add another argument to the ctor, then you are stuck putting it at the beginning and changing the entire API. Furthermore, most programmers are accustomed to figuring out an API by the way that it's used in practice -- this is <em>especially</em> true for non-public API's used inside of an organization where formal documentation may not exist. When other programmers see that the majority of the calls don't contain any arguments, they will do the same, remaining blissfully unaware of the default behavior your default arguments impose on them.</p>\n\n<p>Also, it's worth noting that the <a href=\"https://google.github.io/styleguide/cppguide.html#Doing_Work_in_Constructors\" rel=\"nofollow noreferrer\">google C++ style guide</a> shuns both ctor arguments (unless absolutely necessary), and <a href=\"https://google.github.io/styleguide/cppguide.html#Default_Arguments\" rel=\"nofollow noreferrer\">default arguments to functions or methods</a>.</p>\n" }, { "answer_id": 188006, "author": "paercebal", "author_id": 14089, "author_profile": "https://Stackoverflow.com/users/14089", "pm_score": 4, "selected": false, "text": "<p>This discussion apply both to constructors, but also methods and functions.</p>\n<h2>Using default parameters?</h2>\n<p>The good thing is that you won't need to overload constructors/methods/functions for each case:</p>\n<pre><code>// Header\nvoid doSomething(int i = 25) ;\n\n// Source\nvoid doSomething(int i)\n{\n // Do something with i\n}\n</code></pre>\n<p>The bad thing is that you must declare your default in the header, so you have an hidden dependancy: Like when you change the code of an inlined function, if you change the default value in your header, you'll need to recompile all sources using this header to be sure they will use the new default.</p>\n<p>If you don't, the sources will still use the old default value.</p>\n<h2>using overloaded constructors/methods/functions?</h2>\n<p>The good thing is that if your functions are not inlined, you then control the default value in the source by choosing how one function will behave. For example:</p>\n<pre><code>// Header\nvoid doSomething() ;\nvoid doSomething(int i) ;\n\n// Source\n\nvoid doSomething()\n{\n doSomething(25) ;\n}\n\nvoid doSomething(int i)\n{\n // Do something with i\n}\n</code></pre>\n<p>The problem is that you have to maintain multiple constructors/methods/functions, and their forwardings.</p>\n" }, { "answer_id": 188016, "author": "Nick", "author_id": 26240, "author_profile": "https://Stackoverflow.com/users/26240", "pm_score": 0, "selected": false, "text": "<p>Matter of style, but as Matt said, definitely consider marking constructors with default arguments which would allow implicit conversion as 'explicit' to avoid unintended automatic conversion. It's not a requirement (and may not be preferable if you're making a wrapper class which you want to implicitly convert to), but it can prevent errors.</p>\n\n<p>I personally like defaults when appropriate, because I dislike repeated code. YMMV.</p>\n" }, { "answer_id": 188020, "author": "Rodney Schuler", "author_id": 6188, "author_profile": "https://Stackoverflow.com/users/6188", "pm_score": 3, "selected": false, "text": "<p>Either approach works. But if you have a long list of optional parameters make a default constructor and then have your set function return a reference to this. Then chain the settors.</p>\n\n<pre><code>class Thingy2\n{\npublic:\n enum Color{red,gree,blue};\n Thingy2();\n\n Thingy2 &amp; color(Color);\n Color color()const;\n\n Thingy2 &amp; length(double);\n double length()const;\n Thingy2 &amp; width(double);\n double width()const;\n Thingy2 &amp; height(double);\n double height()const;\n\n Thingy2 &amp; rotationX(double);\n double rotationX()const;\n Thingy2 &amp; rotatationY(double);\n double rotatationY()const;\n Thingy2 &amp; rotationZ(double);\n double rotationZ()const;\n}\n\nmain()\n{\n // gets default rotations\n Thingy2 * foo=new Thingy2().color(ret)\n .length(1).width(4).height(9)\n // gets default color and sizes\n Thingy2 * bar=new Thingy2()\n .rotationX(0.0).rotationY(PI),rotationZ(0.5*PI);\n // everything specified.\n Thingy2 * thing=new Thingy2().color(ret)\n .length(1).width(4).height(9)\n .rotationX(0.0).rotationY(PI),rotationZ(0.5*PI);\n}\n</code></pre>\n\n<p>Now when constructing the objects you can pick an choose which properties to override and which ones you have set are explicitly named. Much more readable :)</p>\n\n<p>Also, you no longer have to remember the order of the arguments to the constructor.</p>\n" }, { "answer_id": 188206, "author": "Richard Corden", "author_id": 11698, "author_profile": "https://Stackoverflow.com/users/11698", "pm_score": 3, "selected": false, "text": "<p><a href=\"https://stackoverflow.com/questions/187640/default-parameters-with-c-constructors#187693\">Sam's</a> answer gives the reason that default arguments are preferable for constructors rather than overloading. I just want to add that C++-0x will allow <a href=\"http://en.wikipedia.org/wiki/C%2B%2B0x#Object_construction_improvement\" rel=\"nofollow noreferrer\">delegation</a> from one constructor to another, thereby removing the need for defaults.</p>\n" }, { "answer_id": 189756, "author": "Yang Lu", "author_id": 26670, "author_profile": "https://Stackoverflow.com/users/26670", "pm_score": 2, "selected": false, "text": "<p>Mostly personal choice. However, overload can do anything default parameter can do, but <strong>not</strong> vice versa.</p>\n\n<p>Example:</p>\n\n<p>You can use overload to write A(int x, foo&amp; a) and A(int x), but you cannot use default parameter to write A(int x, foo&amp; = null).</p>\n\n<p>The general rule is to use whatever makes sense and makes the code more readable.</p>\n" }, { "answer_id": 2219723, "author": "peter", "author_id": 178910, "author_profile": "https://Stackoverflow.com/users/178910", "pm_score": 2, "selected": false, "text": "<p>One more thing to consider is whether or not the class could be used in an array:</p>\n\n<pre><code>foo bar[400];\n</code></pre>\n\n<p>In this scenario, there is no advantage to using the default parameter.</p>\n\n<p>This would certainly NOT work:</p>\n\n<pre><code>foo bar(\"david\", 34)[400]; // NOPE\n</code></pre>\n" } ]
2008/10/09
[ "https://Stackoverflow.com/questions/187640", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9236/" ]
Is it good practice to have a class constructor that uses default parameters, or should I use separate overloaded constructors? For example: ``` // Use this... class foo { private: std::string name_; unsigned int age_; public: foo(const std::string& name = "", const unsigned int age = 0) : name_(name), age_(age) { ... } }; // Or this? class foo { private: std::string name_; unsigned int age_; public: foo() : name_(""), age_(0) { } foo(const std::string& name, const unsigned int age) : name_(name), age_(age) { ... } }; ``` Either version seems to work, e.g.: ``` foo f1; foo f2("Name", 30); ``` Which style do you prefer or recommend and why?
Definitely a matter of style. I prefer constructors with default parameters, so long as the parameters make sense. Classes in the standard use them as well, which speaks in their favor. One thing to watch out for is if you have defaults for all but one parameter, your class can be implicitly converted from that parameter type. Check out [this thread](https://stackoverflow.com/questions/174349/forcing-single-argument-constructors-to-be-explicit-in-c) for more info.
187,669
<p>I have a linker command file that assigns the top address of the stack into a variable </p> <pre><code>_stack = . + 0x80000; </code></pre> <p>I want to use this address in a 'c' program - I want to copy the stack to another location and then update the stack pointer to point to the new location before doing a destructive memory test on the orginal bank of RAM.</p> <p>I'm finding that if I do something like</p> <pre><code>extern u32 *_stack; myFunction(_stack); </code></pre> <p>Then the function seems to get passed the value stored at the stack location </p> <pre><code>lwz r3,0(r8) </code></pre> <p>Rather than the address of the stack itself. Can anyone help?</p>
[ { "answer_id": 187722, "author": "Paul Nathan", "author_id": 26227, "author_profile": "https://Stackoverflow.com/users/26227", "pm_score": 0, "selected": false, "text": "<p><em>myFunction(&amp;_stack);</em> should pass myFunction the address of the variable * _stack*.\nElse, it will pass the value contained in the variable <em>_stack</em>. </p>\n" }, { "answer_id": 187727, "author": "Mark Ransom", "author_id": 5987, "author_profile": "https://Stackoverflow.com/users/5987", "pm_score": 4, "selected": true, "text": "<p>Try</p>\n\n<pre><code>extern u32 _stack;\nU32 * stackPtr;\nstackPtr = &amp;_stack;\n</code></pre>\n" }, { "answer_id": 194229, "author": "Tall Jeff", "author_id": 1553, "author_profile": "https://Stackoverflow.com/users/1553", "pm_score": 1, "selected": false, "text": "<p>I believe the most natural [ie: correct] way to declare this is based on the notion of thinking of the stack as an array in memory with the stack pointer being a location within that array:</p>\n\n<pre><code>extern U32 _stack[];\nU32 *stackPtr;\nstackPtr = _stack;\n</code></pre>\n" } ]
2008/10/09
[ "https://Stackoverflow.com/questions/187669", "https://Stackoverflow.com", "https://Stackoverflow.com/users/23402/" ]
I have a linker command file that assigns the top address of the stack into a variable ``` _stack = . + 0x80000; ``` I want to use this address in a 'c' program - I want to copy the stack to another location and then update the stack pointer to point to the new location before doing a destructive memory test on the orginal bank of RAM. I'm finding that if I do something like ``` extern u32 *_stack; myFunction(_stack); ``` Then the function seems to get passed the value stored at the stack location ``` lwz r3,0(r8) ``` Rather than the address of the stack itself. Can anyone help?
Try ``` extern u32 _stack; U32 * stackPtr; stackPtr = &_stack; ```
187,687
<p>The following ListCellRenderer does not receive click events on the nested ComboBoxes. Do I need to enable something?</p> <pre><code>class FilterCellRenderer implements ListCellRenderer { public Component getListCellRendererComponent(JList list, Object value, int index, boolean isSelected, boolean cellHasFocus) { Filter filter = (Filter)value; JPanel filterPanel = new JPanel(); FlowLayout layout = new FlowLayout(); layout.setAlignment(FlowLayout.LEFT); filterPanel.setLayout(layout); filterPanel.add(new JLabel(filter.getLabel())); final List&lt;Object&gt; options = filter.getOptions(); if (options.size() &gt; 1) { JComboBox optionCombo = new JComboBox(new AbstractComboBoxModel() { public int getSize() { return options.size(); } public Object getElementAt(int index) { return options.get(index); } }); optionCombo.setSelectedItem(filter.getValue()); filterPanel.add(optionCombo); } if (isSelected) { filterPanel.setBackground(list.getSelectionBackground()); filterPanel.setForeground(list.getSelectionForeground()); } return filterPanel; } } </code></pre>
[ { "answer_id": 188563, "author": "Tom Hawtin - tackline", "author_id": 4725, "author_profile": "https://Stackoverflow.com/users/4725", "pm_score": 0, "selected": false, "text": "<p>It's a little bit tricky this. I believe you need to replace the JList with a single column JTable. Then set a table cell editor as well as renderer. IIRC, there might be a problem losing the first click (which gets used to select that cell edited).</p>\n\n<p>Also it's a very good idea to reuse the components between each call to getCellRendererComponent. The components are used as a stamp and then discarded. Performance will suck massively if they are recreated each time.</p>\n" }, { "answer_id": 189014, "author": "Draemon", "author_id": 26334, "author_profile": "https://Stackoverflow.com/users/26334", "pm_score": 1, "selected": false, "text": "<p>Renderer components in swing work like \"rubber stamps\" -they are just used to render/paint a value and are not added to the parent container in the usual way (just think how a single component could be added in multiple places!).</p>\n\n<p>It sounds like you may want an editor rather than a renderer (an editor is a fully-fledged component, added in one place at any given time). Failing that you will have to install the MouseListener on the JList instead.</p>\n" }, { "answer_id": 193429, "author": "Allain Lalonde", "author_id": 2443, "author_profile": "https://Stackoverflow.com/users/2443", "pm_score": 1, "selected": false, "text": "<p>Since I didn't need to select rows, I ended up just dynamically adding and elements to a JPanel with a custom layout. Allowed for full component behaviour without having to hack a table.</p>\n" } ]
2008/10/09
[ "https://Stackoverflow.com/questions/187687", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2443/" ]
The following ListCellRenderer does not receive click events on the nested ComboBoxes. Do I need to enable something? ``` class FilterCellRenderer implements ListCellRenderer { public Component getListCellRendererComponent(JList list, Object value, int index, boolean isSelected, boolean cellHasFocus) { Filter filter = (Filter)value; JPanel filterPanel = new JPanel(); FlowLayout layout = new FlowLayout(); layout.setAlignment(FlowLayout.LEFT); filterPanel.setLayout(layout); filterPanel.add(new JLabel(filter.getLabel())); final List<Object> options = filter.getOptions(); if (options.size() > 1) { JComboBox optionCombo = new JComboBox(new AbstractComboBoxModel() { public int getSize() { return options.size(); } public Object getElementAt(int index) { return options.get(index); } }); optionCombo.setSelectedItem(filter.getValue()); filterPanel.add(optionCombo); } if (isSelected) { filterPanel.setBackground(list.getSelectionBackground()); filterPanel.setForeground(list.getSelectionForeground()); } return filterPanel; } } ```
Renderer components in swing work like "rubber stamps" -they are just used to render/paint a value and are not added to the parent container in the usual way (just think how a single component could be added in multiple places!). It sounds like you may want an editor rather than a renderer (an editor is a fully-fledged component, added in one place at any given time). Failing that you will have to install the MouseListener on the JList instead.
187,695
<p>I've just seen this in the MS Visual Studio docs and the part in bold doesn't make sense to me. Is it wrong or am I not understanding it properly? If you run this, b appears to hold "hello" (as I would expect) and not "h".</p> <p>Strings are <em>immutable</em>--the contents of a string object cannot be changed after the object is created, although the syntax makes it appear as if you can do this. For example, when you write this code, the compiler actually creates a new string object to hold the new sequence of characters, <strong>and the variable b continues to hold "h"</strong>. </p> <p>string b = "h";</p> <p>b += "ello";</p>
[ { "answer_id": 187709, "author": "user7116", "author_id": 7116, "author_profile": "https://Stackoverflow.com/users/7116", "pm_score": 3, "selected": false, "text": "<p>You've done an addition AND an assignment in one step. Strings are immutable, but also a reference type.</p>\n\n<pre><code>string b = \"h\";\nb = b + \"ello\";\n</code></pre>\n\n<p>We can look at the pseudo-memory like this:</p>\n\n<pre><code>string b = \"h\"; // b := 0x00001000 [\"h\"]\nstring tmp1 = \"ello\"; // tmp1 := 0x00002000 [\"ello\"]\nstring tmp2 = b + tmp1; // tmp2 := 0x00003000 [\"hello\"]\nstring b = tmp2; // b := 0x00003000 [\"hello\"]\n</code></pre>\n\n<p>I'm not entirely sure where you're getting that text, because as I read the documentation for the <a href=\"http://msdn.microsoft.com/en-us/library/362314fe.aspx\" rel=\"nofollow noreferrer\">string</a> class I find (not that I think \"h\" actually gets garbage collected):</p>\n\n<blockquote>\n <p>Strings are immutable--the contents of a string object cannot be changed after the object is created, although the syntax makes it appear as if you can do this. For example, when you write this code, the compiler actually creates a new string object to hold the new sequence of characters, and that new object is assigned to b. The string \"h\" is then eligible for garbage collection.</p>\n</blockquote>\n\n<p>@Jon Skeet brings up that \"h\" will never be garbage collected due to string interning, and I agree with him, but even moreso the C# Standard agrees with him, otherwise the following from §2.4.4.5 String literals could not be true:</p>\n\n<blockquote>\n <p>Each string literal does not necessarily result in a new string instance. When two or more string literals that are equivalent according to the string equality operator (§7.9.7) appear in the same program, these string literals refer to the same string instance. </p>\n</blockquote>\n" }, { "answer_id": 187719, "author": "Mark Heath", "author_id": 7532, "author_profile": "https://Stackoverflow.com/users/7532", "pm_score": 1, "selected": false, "text": "<p>There are now three strings. One is the original \"h\", one is \"ello\" and the third is \"hello\". Your b variable points to the \"hello\" string. The other two strings have no references to them and can be thrown away up by the garbage collector.</p>\n" }, { "answer_id": 187721, "author": "Jon Skeet", "author_id": 22656, "author_profile": "https://Stackoverflow.com/users/22656", "pm_score": 2, "selected": false, "text": "<p>Yes, the docs are wrong. (The docs for a number of string methods imply mutability too. They're basically poorly written.)</p>\n\n<p>Heck, even the use of \"the compiler\" creating the new string object is off. Basically it's doing:</p>\n\n<pre><code>string b = \"h\";\nb = string.Concat(b, \"ello\");\n</code></pre>\n\n<p>At that point the compiler's job is done - it's the framework which creates the new string object.</p>\n" }, { "answer_id": 187728, "author": "James Curran", "author_id": 12725, "author_profile": "https://Stackoverflow.com/users/12725", "pm_score": 2, "selected": false, "text": "<p>A string cannot change, but a string variable can be assigned a different value. What you are doing is closer to :</p>\n\n<pre><code>string b = \"h\";\nstring temp = b + \"ello\";\nb = temp;\n</code></pre>\n\n<p>To show the actual immutablity of string, this will fail:</p>\n\n<pre><code> string b=\"hello\";\n if(b[0] == 'h') // we can read via indexer\n b[0] = 'H'; // but this will fail.\n</code></pre>\n" }, { "answer_id": 187737, "author": "Morgan Cheng", "author_id": 26349, "author_profile": "https://Stackoverflow.com/users/26349", "pm_score": 0, "selected": false, "text": "<p>string b = \"h\";\nb += \"ello\";</p>\n\n<p>b is just a reference to object in heap.\nActually, after the \"+=\" operation, b doesn't reference to the original \"h\" any more. Now, it reference to a new string object \"hello\" which is concatenation of \"h\" and \"ello\". The \"h\" string will be collected by GC.</p>\n" }, { "answer_id": 187743, "author": "Whisk", "author_id": 908, "author_profile": "https://Stackoverflow.com/users/908", "pm_score": 0, "selected": false, "text": "<p>What's happening is that you're making a new variable that holds 'hello', and then changing b to reference this, the memory for the 'old' b still contains 'h', but that's no longer needed so the garbage collector will clean it up. This is why it's so good to use stringbuilders when iterating and sticking strings together - see <a href=\"http://www.c-sharpcorner.com/UploadFile/mahesh/StringBuilderComp11232005235258PM/StringBuilderComp.aspx\" rel=\"nofollow noreferrer\">this</a> for more info.</p>\n" }, { "answer_id": 187772, "author": "hwiechers", "author_id": 5883, "author_profile": "https://Stackoverflow.com/users/5883", "pm_score": 2, "selected": false, "text": "<p>The docs are wrong.\nThe variable b now holds \"hello\". The string is immutable but the variable can be reassigned.</p>\n" }, { "answer_id": 187783, "author": "Sam", "author_id": 7021, "author_profile": "https://Stackoverflow.com/users/7021", "pm_score": 2, "selected": false, "text": "<p>The misunderstanding here is about <strong>reference types</strong>:<br>\n<strong>String is a reference type</strong>, not a value type. This means, your variable <strong>b is not an object</strong> of type string, it is a <strong>reference to an object</strong> of type string in memory.<br>\nWhat the doc says, is that <strong>the object in memory is immutable</strong>.<br>\nStill, <strong>your reference to the object can be changed</strong> to point to some other (immutable) object in memory.<br>\nFor you it might look like the content of the object has changed, but in the memory it has not, and this is all that <em>immutable</em> thingy is about.</p>\n\n<p>The string itself <strong>is</strong> immutable. What your example changed was not the string class in memory, but the reference your variable is pointing to.</p>\n\n<p>See this slightly modified code:</p>\n\n<pre><code>string b = \"h\";\nstring m1 = b;\nb += \"ello\";\n// now b == \"hello\", m1 == \"h\"\n</code></pre>\n\n<p>In the end b will point to \"hello\", while m1 will point to \"h\". For you it might seem like \"h\" has changed to \"hello\", but it has not. b+=\"ello\" created a new string class containing \"hello\" and assigned it to b, while the old b still is present in Memory and still contains \"b\".</p>\n\n<p>If string was not immutable, m1 would contain \"hello\", too, instead of just \"b\", because both b and m1 pointed to the same reference.</p>\n" }, { "answer_id": 187848, "author": "Dave Costa", "author_id": 6568, "author_profile": "https://Stackoverflow.com/users/6568", "pm_score": 3, "selected": false, "text": "<p>People don't seem to be understanding the question. No one is arguing that string objects aren't immutable. The point of contention is what he bolded:</p>\n\n<blockquote>\n <p>and the variable b continues to hold\n \"h\"</p>\n</blockquote>\n\n<p>I agree with the OP that this portion of the doc is incorrect on two counts:</p>\n\n<p>(1) In the obvious intuitive sense that if you print(b) (or whatever the correct statement is in this language) after his two sample lines you will get \"hello\" as the result.<br>\n(2) In the strict sense that the variable b doesn't <strong>hold</strong> \"h\", \"hello\", or any string value. It holds a reference to a string object.</p>\n\n<p>The contents of the variable b do change as a result of the assignment -- it changes from a point to string object \"h\" to a pointer to string object \"hello\".</p>\n\n<p>When they say \"hold\" what they really mean is \"points to\". And they are wrong, after the assignment b no longer points to \"h\".</p>\n\n<p>I think the example they really wanted to give is this:</p>\n\n<pre><code>string a = \"h\";\nstring b = a;\nb += \"ello\";\n</code></pre>\n\n<p>The point being that a would, I believe, still point to \"h\"; i.e., the assignment to b doesn't modify the object it was pointing to, it creates a new object and changes b to point to it.</p>\n\n<p>(I don't actually write C# but this is my understanding.)</p>\n" }, { "answer_id": 187856, "author": "SeaDrive", "author_id": 19267, "author_profile": "https://Stackoverflow.com/users/19267", "pm_score": 0, "selected": false, "text": "<p>I don't know what C# does, but I did read about this in Java, and an implementation based on Java would be more like this:</p>\n\n<p>string b = \"h\" ;</p>\n\n<p>b = (new StringBuilder(b)).Append(\"ello\").ToString() ;</p>\n\n<p>The point is that the \"+\" or \"Append\" does not exist for string because string is immutable.</p>\n" }, { "answer_id": 188002, "author": "OscarRyz", "author_id": 20654, "author_profile": "https://Stackoverflow.com/users/20654", "pm_score": 0, "selected": false, "text": "<p>Try this:</p>\n\n<pre><code>string b = \"h\";\nstring c = b + \"ello\"; // b still == \"h\", c = \"hello\"\nstring d = string.concat(b, \"ello\"); // d == hello, b still \"h\"\n</code></pre>\n\n<p>Why b is still \"h\" ? Because \"b\" is not an object, it is an object <strong>reference</strong>. There is nothing you can do to the object referenced by b to change it. If strings where mutable then using:</p>\n\n<pre><code>string b = \"ello\";\nstring f = b.Insert(\"h\",0);\n</code></pre>\n\n<p>would modify b to \"hello\" ( because h was inserted at position 0 ) but as it is inmutable b remains \"ello\".</p>\n\n<p>If you change the reference to other object that a different thing.</p>\n\n<pre><code>b = \"ello\";\nb = \"Some other string\";\n// b not references \"Some other string\" , but the object \"ello\" remains unchanged.\n</code></pre>\n\n<p>I hope it helps ( and works :S ) </p>\n" }, { "answer_id": 188363, "author": "shahkalpesh", "author_id": 23574, "author_profile": "https://Stackoverflow.com/users/23574", "pm_score": 0, "selected": false, "text": "<p>Simply put, strings cannot be modified in place (if string is an array of characters)</p>\n" }, { "answer_id": 11234811, "author": "supercat", "author_id": 363751, "author_profile": "https://Stackoverflow.com/users/363751", "pm_score": 0, "selected": false, "text": "<p>It would perhaps be clearest to regard all class-type storage locations as holding \"object IDs\". Suppose that, initially, the compiler has assigned <code>ID #123</code> to the string \"h\" and has assigned <code>ID #547</code> to the string \"ello\". Then after the statement <code>b = \"h\";</code>, the variable <code>b</code> will hold <code>ID #123</code>. The statement <code>b += \"ello\";</code> will cause the compiler to pass <code>ID #123</code> and <code>ID #547</code> to the <code>+</code> operator for string, which will in turn pass them to the <code>String.Concat</code> method. That method will in turn ask the system to create a new object (e.g. <code>ID #915</code>) of type <code>System.String</code>, holding the five characters <code>\"hello\"</code>, and return that object to the caller. The compiler will then store <code>ID #915</code> into <code>b</code>.</p>\n" } ]
2008/10/09
[ "https://Stackoverflow.com/questions/187695", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
I've just seen this in the MS Visual Studio docs and the part in bold doesn't make sense to me. Is it wrong or am I not understanding it properly? If you run this, b appears to hold "hello" (as I would expect) and not "h". Strings are *immutable*--the contents of a string object cannot be changed after the object is created, although the syntax makes it appear as if you can do this. For example, when you write this code, the compiler actually creates a new string object to hold the new sequence of characters, **and the variable b continues to hold "h"**. string b = "h"; b += "ello";
You've done an addition AND an assignment in one step. Strings are immutable, but also a reference type. ``` string b = "h"; b = b + "ello"; ``` We can look at the pseudo-memory like this: ``` string b = "h"; // b := 0x00001000 ["h"] string tmp1 = "ello"; // tmp1 := 0x00002000 ["ello"] string tmp2 = b + tmp1; // tmp2 := 0x00003000 ["hello"] string b = tmp2; // b := 0x00003000 ["hello"] ``` I'm not entirely sure where you're getting that text, because as I read the documentation for the [string](http://msdn.microsoft.com/en-us/library/362314fe.aspx) class I find (not that I think "h" actually gets garbage collected): > > Strings are immutable--the contents of a string object cannot be changed after the object is created, although the syntax makes it appear as if you can do this. For example, when you write this code, the compiler actually creates a new string object to hold the new sequence of characters, and that new object is assigned to b. The string "h" is then eligible for garbage collection. > > > @Jon Skeet brings up that "h" will never be garbage collected due to string interning, and I agree with him, but even moreso the C# Standard agrees with him, otherwise the following from §2.4.4.5 String literals could not be true: > > Each string literal does not necessarily result in a new string instance. When two or more string literals that are equivalent according to the string equality operator (§7.9.7) appear in the same program, these string literals refer to the same string instance. > > >
187,713
<p>In C++, what's the generic way to convert any floating point value (float) to <a href="http://en.wikipedia.org/wiki/Fixed-point_arithmetic" rel="noreferrer"><strong>fixed point</strong></a> (int, 16:16 or 24:8)?</p> <p><strong>EDIT:</strong> For clarification, fixed-point values have two parts to them: an integer part and a fractional part. The integer part can be represented by a signed or unsigned integer data type. The fractional part is represented by an unsigned data integer data type.</p> <p>Let's make an analogy with money for the sake of clarity. The fractional part may represent cents -- a fractional part of a dollar. The range of the 'cents' data type would be 0 to 99. If a 8-bit unsigned integer were to be used for fixed-point math, then the fractional part would be split into 256 evenly divisible parts.</p> <p>I hope that clears things up.</p>
[ { "answer_id": 187808, "author": "Kevin", "author_id": 6386, "author_profile": "https://Stackoverflow.com/users/6386", "pm_score": 6, "selected": true, "text": "<p>Here you go:</p>\n\n<pre><code>// A signed fixed-point 16:16 class\nclass FixedPoint_16_16\n{\n short intPart;\n unsigned short fracPart;\n\npublic:\n FixedPoint_16_16(double d)\n {\n *this = d; // calls operator=\n }\n\n FixedPoint_16_16&amp; operator=(double d)\n {\n intPart = static_cast&lt;short&gt;(d);\n fracPart = static_cast&lt;unsigned short&gt;\n (numeric_limits&lt;unsigned short&gt; + 1.0)*d);\n return *this;\n }\n\n // Other operators can be defined here\n};\n</code></pre>\n\n<p><strong>EDIT:</strong> Here's a more general class based on anothercommon way to deal with fixed-point numbers (and which KPexEA pointed out):</p>\n\n<pre><code>template &lt;class BaseType, size_t FracDigits&gt;\nclass fixed_point\n{\n const static BaseType factor = 1 &lt;&lt; FracDigits;\n\n BaseType data;\n\npublic:\n fixed_point(double d)\n {\n *this = d; // calls operator=\n }\n\n fixed_point&amp; operator=(double d)\n {\n data = static_cast&lt;BaseType&gt;(d*factor);\n return *this;\n }\n\n BaseType raw_data() const\n {\n return data;\n }\n\n // Other operators can be defined here\n};\n\n\nfixed_point&lt;int, 8&gt; fp1; // Will be signed 24:8 (if int is 32-bits)\nfixed_point&lt;unsigned int, 16&gt; fp1; // Will be unsigned 16:16 (if int is 32-bits)\n</code></pre>\n" }, { "answer_id": 187816, "author": "bugmagnet", "author_id": 426, "author_profile": "https://Stackoverflow.com/users/426", "pm_score": 0, "selected": false, "text": "<p>This is fine for converting from floating point to integer, but the O.P. also wanted <a href=\"http://en.wikipedia.org/wiki/Fixed-point_arithmetic\" rel=\"nofollow noreferrer\">fixed point</a>. </p>\n\n<p>Now how you'd do that in C++, I don't know (C++ not being something I can think in readily). Perhaps try a scaled-integer approach, i.e. use a 32 or 64 bit integer and programmatically allocate the last, say, 6 digits to what's on the right hand side of the decimal point. </p>\n" }, { "answer_id": 187823, "author": "KPexEA", "author_id": 13676, "author_profile": "https://Stackoverflow.com/users/13676", "pm_score": 5, "selected": false, "text": "<p>A cast from float to integer will throw away the fractional portion so if you want to keep that fraction around as fixed point then you just multiply the float before casting it. The below code will not check for overflow mind you.</p>\n\n<p>If you want 16:16</p>\n\n<pre><code>double f = 1.2345;\nint n;\n\nn=(int)(f*65536);\n</code></pre>\n\n<p>if you want 24:8</p>\n\n<pre><code>double f = 1.2345;\nint n;\n\nn=(int)(f*256);\n</code></pre>\n" }, { "answer_id": 187834, "author": "workmad3", "author_id": 16035, "author_profile": "https://Stackoverflow.com/users/16035", "pm_score": -1, "selected": false, "text": "<p>There isn't any built in support in C++ for fixed point numbers. Your best bet would be to write a wrapper 'FixedInt' class that takes doubles and converts them.</p>\n\n<p>As for a generic method to convert... the int part is easy enough, just grab the integer part of the value and store it in the upper bits... decimal part would be something along the lines of:</p>\n\n<pre><code>for (int i = 1; i &lt;= precision; i++)\n{\n if (decimal_part &gt; 1.f/(float)(i + 1)\n {\n decimal_part -= 1.f/(float)(i + 1);\n fixint_value |= (1 &lt;&lt; precision - i);\n }\n}\n</code></pre>\n\n<p>although this is likely to contain bugs still</p>\n" }, { "answer_id": 187993, "author": "Greg Whitfield", "author_id": 2102, "author_profile": "https://Stackoverflow.com/users/2102", "pm_score": 3, "selected": false, "text": "<p>**** Edit** : <em>My first comment applies to before Kevin's edit,but I'll leave it here for posterity. Answers change so quickly here sometimes!</em></p>\n\n<p>The problem with Kevin's approach is that with Fixed Point you are normally packing into a guaranteed word size (typically 32bits). Declaring the two parts separately leaves you to the whim of your compiler's structure packing. Yes you could force it, but it does not work for anything other than 16:16 representation.</p>\n\n<p>KPexEA is closer to the mark by packing everything into int - although I would use \"signed long\" to try and be explicit on 32bits. Then you can use his approach for generating the fixed point value, and bit slicing do extract the component parts again. His suggestion also covers the 24:8 case.</p>\n\n<p>( And everyone else who suggested just static_cast.....what were you thinking? ;) )</p>\n" }, { "answer_id": 253466, "author": "CVertex", "author_id": 209, "author_profile": "https://Stackoverflow.com/users/209", "pm_score": 1, "selected": false, "text": "<p>I gave the answer to the guy that wrote the best answer, but I really used a related questions code that points <a href=\"https://web.archive.org/web/20080917044553/http://www.codef00.com/coding.php\" rel=\"nofollow noreferrer\">here</a>.</p>\n\n<p>It used templates and was easy to ditch dependencies on the boost lib.</p>\n" } ]
2008/10/09
[ "https://Stackoverflow.com/questions/187713", "https://Stackoverflow.com", "https://Stackoverflow.com/users/209/" ]
In C++, what's the generic way to convert any floating point value (float) to [**fixed point**](http://en.wikipedia.org/wiki/Fixed-point_arithmetic) (int, 16:16 or 24:8)? **EDIT:** For clarification, fixed-point values have two parts to them: an integer part and a fractional part. The integer part can be represented by a signed or unsigned integer data type. The fractional part is represented by an unsigned data integer data type. Let's make an analogy with money for the sake of clarity. The fractional part may represent cents -- a fractional part of a dollar. The range of the 'cents' data type would be 0 to 99. If a 8-bit unsigned integer were to be used for fixed-point math, then the fractional part would be split into 256 evenly divisible parts. I hope that clears things up.
Here you go: ``` // A signed fixed-point 16:16 class class FixedPoint_16_16 { short intPart; unsigned short fracPart; public: FixedPoint_16_16(double d) { *this = d; // calls operator= } FixedPoint_16_16& operator=(double d) { intPart = static_cast<short>(d); fracPart = static_cast<unsigned short> (numeric_limits<unsigned short> + 1.0)*d); return *this; } // Other operators can be defined here }; ``` **EDIT:** Here's a more general class based on anothercommon way to deal with fixed-point numbers (and which KPexEA pointed out): ``` template <class BaseType, size_t FracDigits> class fixed_point { const static BaseType factor = 1 << FracDigits; BaseType data; public: fixed_point(double d) { *this = d; // calls operator= } fixed_point& operator=(double d) { data = static_cast<BaseType>(d*factor); return *this; } BaseType raw_data() const { return data; } // Other operators can be defined here }; fixed_point<int, 8> fp1; // Will be signed 24:8 (if int is 32-bits) fixed_point<unsigned int, 16> fp1; // Will be unsigned 16:16 (if int is 32-bits) ```
187,736
<p>I'm writing a command line tool to help my web app. It needs a password to connect to the service. I'd like the script to show a password prompt so I don't have to pass it as a command line argument. </p> <p>That's easy enough, but I'd like it to not echo the password to the screen as it's typed. How can I do this with PHP? </p> <p>Bonus points for doing it in pure PHP (no <code>system('stty')</code>) and replacing the characters with <code>*</code>. </p> <p><strong>EDIT:</strong></p> <p>The script will run on a unix like system (linux or mac). The script is written in PHP, and will most likely stay like that.</p> <p>Also, for the record, the <code>stty</code> way of doing it is:</p> <pre><code>echo "Password: "; system('stty -echo'); $password = trim(fgets(STDIN)); system('stty echo'); // add a new line since the users CR didn't echo echo "\n"; </code></pre> <p>I'd prefer to not have the <code>system()</code> calls in there.</p>
[ { "answer_id": 187821, "author": "Gabriel Gilini", "author_id": 25853, "author_profile": "https://Stackoverflow.com/users/25853", "pm_score": 2, "selected": false, "text": "<p>I guess that there is no simple way of doing it (actually I can't think of any way) without using stty -echo.\nIf you intent running it on windows, you could create a batch script that would provide the unechoed typed info to your php script.</p>\n\n<pre><code>@echo off\ncls\nSET /P uname=Enter Username:\necho hP1X500P[PZBBBfh#b##fXf-V@`$fPf]f3/f1/5++u5&gt;in.com\nset /p password=Enter password :&lt;nul\nfor /f “tokens=*” %%i in (’in.com’) do set password=%%i\ndel in.com\necho.\nc:\\php\\php.exe d:\\php\\test.php %uname% “%password%”\nPause\n</code></pre>\n\n<p>example taken from <a href=\"http://www.indiangnu.org/2008/php-hide-user-input-using-batch-script-windows/\" rel=\"nofollow noreferrer\">http://www.indiangnu.org/2008/php-hide-user-input-using-batch-script-windows/</a></p>\n" }, { "answer_id": 188357, "author": "Randy", "author_id": 9361, "author_profile": "https://Stackoverflow.com/users/9361", "pm_score": 4, "selected": false, "text": "<p>Depending on your environment (i.e., not on Windows), you can use the ncurses library (specifically, the <a href=\"http://us.php.net/manual/en/function.ncurses-noecho.php\" rel=\"noreferrer\">ncurses_noecho()</a> function to stop keyboard echo and <a href=\"http://us.php.net/manual/en/function.ncurses-getch.php\" rel=\"noreferrer\">ncurses_getch()</a> to read the input) to get the password without displaying it on screen.</p>\n" }, { "answer_id": 188431, "author": "SchizoDuckie", "author_id": 18077, "author_profile": "https://Stackoverflow.com/users/18077", "pm_score": 0, "selected": false, "text": "<p>Why not use an SSH connection? You can abstract the commands away, redirect input/output and have full control.</p>\n\n<p>You can provide someone with a pure clean shell with as little rights as neccesary, and let the password just be POST'ed along with to SSH2::Connect() to open the shell.</p>\n\n<p>I created a nice class to work with the php SSH2 extension, maybe it helps you;\n(and it also does secure file transfers)</p>\n\n<pre><code>&lt;?php\n\n/**\n * SSH2\n * \n * @package Pork\n * @author SchizoDuckie\n * @version 1.0\n * @access public\n */\nclass SSH2\n{\n private $host;\n private $port;\n private $connection;\n private $timeout;\n private $debugMode;\n private $debugPointer;\n public $connected; \n public $error;\n\n\n /**\n * SSH2::__construct()\n * \n * @param mixed $host\n * @param integer $port\n * @param integer $timeout\n * @return\n */\n function __construct($host, $port=22, $timeout=10)\n {\n $this-&gt;host = $host;\n $this-&gt;port = $port;\n $this-&gt;timeout = 10;\n $this-&gt;error = 'not connected';\n $this-&gt;connection = false;\n $this-&gt;debugMode = Settings::Load()-&gt;-&gt;get('Debug', 'Debugmode');\n $this-&gt;debugPointer = ($this-&gt;debugMode) ? fopen('./logs/'.date('Y-m-d--H-i-s').'.log', 'w+') : false;\n $this-&gt;connected = false;\n\n }\n\n\n /**\n * SSH2::connect()\n * \n * @param mixed $username\n * @param mixed $password\n * @return\n */\n function connect($username, $password)\n {\n $this-&gt;connection = ssh2_connect($this-&gt;host, $this-&gt;port);\n if (!$this-&gt;connection) return $this-&gt;error(\"Could not connect to {$this-&gt;host}:{$this-&gt;port}\");\n $this-&gt;debug(\"Connected to {$this-&gt;host}:{$this-&gt;port}\");\n $authenticated = ssh2_auth_password($this-&gt;connection, $username, $password);\n if(!$authenticated) return $this-&gt;error(\"Could not authenticate: {$username}, check your password\");\n $this-&gt;debug(\"Authenticated successfully as {$username}\");\n $this-&gt;connected = true;\n\n return true;\n }\n\n /**\n * SSH2::exec()\n *\n * @param mixed $command shell command to execute\n * @param bool $onAvailableFunction a function to handle any available data.\n * @param bool $blocking blocking or non-blocking mode. This 'hangs' php execution until the command has completed if you set it to true. If you just want to start an import and go on, use this icm onAvailableFunction and false\n * @return\n */\n function exec($command, $onAvailableFunction=false, $blocking=true)\n {\n $output = '';\n $stream = ssh2_exec($this-&gt;connection, $command);\n $this-&gt;debug(\"Exec: {$command}\");\n if($onAvailableFunction !== false)\n {\n $lastReceived = time();\n $timeout =false;\n while (!feof($stream) &amp;&amp; !$timeout)\n {\n $input = fgets($stream, 1024);\n if(strlen($input) &gt;0)\n {\n call_user_func($onAvailableFunction, $input);\n $this-&gt;debug($input);\n $lastReceived = time();\n }\n else\n {\n if(time() - $lastReceived &gt;= $this-&gt;timeout)\n {\n $timeout = true;\n $this-&gt;error('Connection timed out');\n return($this-&gt;error);\n }\n }\n }\n }\n if($blocking === true &amp;&amp; $onAvailableFunction === false)\n {\n stream_set_blocking($stream, true);\n $output = stream_get_contents($stream);\n $this-&gt;debug($output);\n }\n fclose($stream);\n return($output);\n }\n\n\n /**\n * SSH2::createDirectory()\n *\n * Creates a directory via sftp\n *\n * @param string $dirname\n * @return boolean success\n * \n */\n function createDirectory($dirname)\n {\n $ftpconnection = ssh2_sftp ($this-&gt;connection);\n $dircreated = ssh2_sftp_mkdir($ftpconnection, $dirname, true);\n if(!$dircreated) \n {\n $this-&gt;debug(\"Directory not created: \".$dirname);\n }\n return $dircreated;\n }\n\n public function listFiles($dirname)\n {\n $input = $this-&gt;exec(escapeshellcmd(\"ls {$dirname}\"));\n return(explode(\"\\n\", trim($input)));\n\n }\n\n public function sendFile($filename, $remotename)\n {\n $this-&gt;debug(\"sending {$filename} to {$remotename} \");\n if(file_exists($filename) &amp;&amp; is_readable($filename))\n {\n $result = ssh2_scp_send($this-&gt;connection, $filename, $remotename, 0664);\n }\n else\n {\n $this-&gt;debug(\"Unable to read file : \".$filename);\n return false;\n }\n if(!$result) $this-&gt;debug(\"Failure uploading {$filename} to {$remotename}\");\n return $result;\n }\n\n public function getFile($remotename, $localfile)\n {\n $this-&gt;debug(\"grabbing {$remotename} to {$localfile}\");\n $result = ssh2_scp_recv($this-&gt;connection, $remotename, $localfile);\n\n if(!$result) $this-&gt;debug(\"Failure downloading {$remotename} to {$localfile}\");\n return $result;\n }\n\n /**\n * SSH2::debug()\n * \n * @param mixed $message\n * @return\n */\n function debug($message) \n {\n if($this-&gt;debugMode)\n {\n fwrite($this-&gt;debugPointer, date('Y-m-d H:i:s').\" : \".$message.\"\\n\");\n }\n }\n\n\n\n /**\n * SSH2::error()\n * \n * @param mixed $errorMsg\n * @return\n */\n function error($errorMsg) \n {\n $this-&gt;error = $errorMsg;\n $this-&gt;debug($errorMsg);\n return false;\n } \n\n /**\n * SSH2::__destruct()\n * \n * @return\n */\n function __destruct() \n {\n if($this-&gt;connection){\n $this-&gt;connection = null;\n }\n if($this-&gt;debugMode &amp;&amp; $this-&gt;debugPointer)\n {\n fclose($this-&gt;debugPointer);\n }\n } \n\n\n}\n</code></pre>\n\n<p>Usage example:</p>\n\n<pre><code>$settings = Settings::Load()-&gt;Get(\"SecureServer\");\n$ssh = new SSH2($settings['host']);\nif( $ssh-&gt;connect($settings['username'], $settings['password']))\n{\n echo $ssh-&gt;exec(\"ls -la \".$settings['path'], false, true); \n flush(); \n}\n</code></pre>\n" }, { "answer_id": 298681, "author": "Slipo", "author_id": 38432, "author_profile": "https://Stackoverflow.com/users/38432", "pm_score": 0, "selected": false, "text": "<p>Theorically you can do it using stream_set_blocking(), but looks like there are some PHP bugs managing STDIN.</p>\n\n<p>Look:\n<a href=\"http://bugs.php.net/bug.php?id=34972\" rel=\"nofollow noreferrer\">http://bugs.php.net/bug.php?id=34972</a>\n<a href=\"http://bugs.php.net/bug.php?id=36030\" rel=\"nofollow noreferrer\">http://bugs.php.net/bug.php?id=36030</a></p>\n\n<p>Try yourself:</p>\n\n<pre><code>echo \"Enter Password: \";\n$stdin = fopen('php://stdin','r');\n// Trying to disable stream blocking\nstream_set_blocking($stdin, FALSE) or die ('Failed to disable stdin blocking');\n// Trying to set stream timeout to 1sec\nstream_set_timeout ($stdin, 1) or die ('Failed to enable stdin timeout');</code></pre>\n" }, { "answer_id": 1674175, "author": "DaveHauenstein", "author_id": 202654, "author_profile": "https://Stackoverflow.com/users/202654", "pm_score": 6, "selected": true, "text": "<p>Found on <a href=\"http://www.sitepoint.com/blogs/2009/05/01/interactive-cli-password-prompt-in-php/\" rel=\"noreferrer\">sitepoint</a>.</p>\n\n<pre><code>function prompt_silent($prompt = \"Enter Password:\") {\n if (preg_match('/^win/i', PHP_OS)) {\n $vbscript = sys_get_temp_dir() . 'prompt_password.vbs';\n file_put_contents(\n $vbscript, 'wscript.echo(InputBox(\"'\n . addslashes($prompt)\n . '\", \"\", \"password here\"))');\n $command = \"cscript //nologo \" . escapeshellarg($vbscript);\n $password = rtrim(shell_exec($command));\n unlink($vbscript);\n return $password;\n } else {\n $command = \"/usr/bin/env bash -c 'echo OK'\";\n if (rtrim(shell_exec($command)) !== 'OK') {\n trigger_error(\"Can't invoke bash\");\n return;\n }\n $command = \"/usr/bin/env bash -c 'read -s -p \\\"\"\n . addslashes($prompt)\n . \"\\\" mypassword &amp;&amp; echo \\$mypassword'\";\n $password = rtrim(shell_exec($command));\n echo \"\\n\";\n return $password;\n }\n}\n</code></pre>\n" }, { "answer_id": 12126105, "author": "Seldaek", "author_id": 6512, "author_profile": "https://Stackoverflow.com/users/6512", "pm_score": 3, "selected": false, "text": "<p>You can use my <a href=\"https://github.com/Seldaek/hidden-input\">hiddeninput.exe</a> file to get real hidden input without leaking the information anywhere on screen.</p>\n\n<pre><code>&lt;?php\n\necho 'Enter password: ';\n$password = exec('hiddeninput.exe');\necho PHP_EOL;\n\necho 'Password was: ' . $password . PHP_EOL;\n</code></pre>\n\n<p>If you remove the last echo, the password should never show up, but you can use that for validation obvoiusly.</p>\n" }, { "answer_id": 17238943, "author": "robert petranovic", "author_id": 920470, "author_profile": "https://Stackoverflow.com/users/920470", "pm_score": 1, "selected": false, "text": "<p>The accepted answer is not good enough. First of all, the Windows solution doesn't work on Windows 7 and above. The solution for other OSs depends on Bash and bash built-in 'read'. However, there are systems which does not use Bash (eg. OpenBSD) and where this obviously won't work. </p>\n\n<p>In this <a href=\"https://blog.dsl-platform.com/hiding-input-from-console-in-php/\" rel=\"nofollow\">blog</a> I've discussed solution which works on almost any Unix based OS and Windows from 95 to 8. The Windows solution uses external program written in C on top Win32 API. The solution for other OSs uses external command 'stty'. I have yet to see a Unix based system which does not have 'stty'</p>\n" }, { "answer_id": 25706521, "author": "mpyw", "author_id": 1846562, "author_profile": "https://Stackoverflow.com/users/1846562", "pm_score": 2, "selected": false, "text": "<p>This is the easiest solution for all platforms:</p>\n\n<pre><code>function prompt($message = 'prompt: ', $hidden = false) {\n if (PHP_SAPI !== 'cli') {\n return false;\n }\n echo $message;\n $ret = \n $hidden\n ? exec(\n PHP_OS === 'WINNT' || PHP_OS === 'WIN32'\n ? __DIR__ . '\\prompt_win.bat'\n : 'read -s PW; echo $PW'\n )\n : rtrim(fgets(STDIN), PHP_EOL)\n ;\n if ($hidden) {\n echo PHP_EOL;\n }\n return $ret;\n}\n</code></pre>\n\n<p>Then create <code>prompt_win.bat</code> in the same directory:</p>\n\n<pre><code>SetLocal DisableDelayedExpansion\nSet \"Line=\"\nFor /F %%# In ('\"Prompt;$H &amp; For %%# in (1) Do Rem\"') Do (\n Set \"BS=%%#\"\n)\n\n:loop_start\n Set \"Key=\"\n For /F \"delims=\" %%# In ('Xcopy /L /W \"%~f0\" \"%~f0\" 2^&gt;Nul') Do (\n If Not Defined Key (\n Set \"Key=%%#\"\n )\n )\n Set \"Key=%Key:~-1%\"\n SetLocal EnableDelayedExpansion\n If Not Defined Key (\n Goto :loop_end\n )\n If %BS%==^%Key% (\n Set \"Key=\"\n If Defined Line (\n Set \"Line=!Line:~0,-1!\"\n )\n )\n If Not Defined Line (\n EndLocal\n Set \"Line=%Key%\"\n ) Else (\n For /F \"delims=\" %%# In (\"!Line!\") Do (\n EndLocal\n Set \"Line=%%#%Key%\"\n )\n )\n Goto :loop_start\n:loop_end\n\nEcho;!Line!\n</code></pre>\n" }, { "answer_id": 39310049, "author": "JMW", "author_id": 553820, "author_profile": "https://Stackoverflow.com/users/553820", "pm_score": 2, "selected": false, "text": "<p><strong>Works on every windows system, that has powershell support.</strong> (source from: <a href=\"http://www.qxs.ch/2013/02/08/php-cli-password-prompts-on-windows-7/\" rel=\"nofollow\">http://www.qxs.ch/2013/02/08/php-cli-password-prompts-on-windows-7/</a> )</p>\n\n<pre><code>&lt;?php\n// please set the path to your powershell, here it is: C:\\Windows\\system32\\WindowsPowerShell\\v1.0\\powershell.exe\n$pwd=shell_exec('C:\\Windows\\system32\\WindowsPowerShell\\v1.0\\powershell.exe -Command \"$Password=Read-Host -assecurestring \\\"Please enter your password\\\" ; $PlainPassword = [System.Runtime.InteropServices.Marshal]::PtrToStringAuto([System.Runtime.InteropServices.Marshal]::SecureStringToBSTR($Password)) ; echo $PlainPassword;\"');\n$pwd=explode(\"\\n\", $pwd); $pwd=$pwd[0];\necho \"You have entered the following password: $pwd\\n\";\n</code></pre>\n" }, { "answer_id": 51747444, "author": "Pitpat", "author_id": 10197827, "author_profile": "https://Stackoverflow.com/users/10197827", "pm_score": 3, "selected": false, "text": "<p>The below method works under Linux CLI but not under Windows CLI or Apache. It also only works with chars in the standard Ascii table (It would not take much to make it compatible with extended char sets though).</p>\n\n<p>I have put a bit of code in to protect against copy and paste passwords. If the bit between the two comments is removed then a password can be injected/pasted in.</p>\n\n<p>I hope this helps someone.</p>\n\n<pre><code>&lt;?php\n\n echo(\"Password: \");\n $strPassword=getObscuredText();\n echo(\"\\n\");\n echo(\"You entered: \".$strPassword.\"\\n\");\n\n function getObscuredText($strMaskChar='*')\n {\n if(!is_string($strMaskChar) || $strMaskChar=='')\n {\n $strMaskChar='*';\n }\n $strMaskChar=substr($strMaskChar,0,1);\n readline_callback_handler_install('', function(){});\n $strObscured='';\n while(true)\n {\n $strChar = stream_get_contents(STDIN, 1);\n $intCount=0;\n// Protect against copy and paste passwords\n// Comment \\/\\/\\/ to remove password injection protection\n $arrRead = array(STDIN);\n $arrWrite = NULL;\n $arrExcept = NULL;\n while (stream_select($arrRead, $arrWrite, $arrExcept, 0,0) &amp;&amp; in_array(STDIN, $arrRead)) \n {\n stream_get_contents(STDIN, 1);\n $intCount++;\n }\n// /\\/\\/\\\n// End of protection against copy and paste passwords\n if($strChar===chr(10))\n {\n break;\n }\n if ($intCount===0)\n {\n if(ord($strChar)===127)\n {\n if(strlen($strObscured)&gt;0)\n {\n $strObscured=substr($strObscured,0,strlen($strObscured)-1);\n echo(chr(27).chr(91).\"D\".\" \".chr(27).chr(91).\"D\");\n }\n }\n elseif ($strChar&gt;=' ')\n {\n $strObscured.=$strChar;\n echo($strMaskChar);\n //echo(ord($strChar));\n }\n }\n }\n readline_callback_handler_remove();\n return($strObscured);\n }\n?&gt;\n</code></pre>\n" }, { "answer_id": 70205575, "author": "Arvy", "author_id": 2415019, "author_profile": "https://Stackoverflow.com/users/2415019", "pm_score": 0, "selected": false, "text": "<pre><code>system('stty -echo');\n</code></pre>\n<p>to disable the current terminal echo, and:</p>\n<pre><code>system('stty echo');\n</code></pre>\n<p>to reenable it. Set it before and after <code>fgets</code>.</p>\n" } ]
2008/10/09
[ "https://Stackoverflow.com/questions/187736", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2506/" ]
I'm writing a command line tool to help my web app. It needs a password to connect to the service. I'd like the script to show a password prompt so I don't have to pass it as a command line argument. That's easy enough, but I'd like it to not echo the password to the screen as it's typed. How can I do this with PHP? Bonus points for doing it in pure PHP (no `system('stty')`) and replacing the characters with `*`. **EDIT:** The script will run on a unix like system (linux or mac). The script is written in PHP, and will most likely stay like that. Also, for the record, the `stty` way of doing it is: ``` echo "Password: "; system('stty -echo'); $password = trim(fgets(STDIN)); system('stty echo'); // add a new line since the users CR didn't echo echo "\n"; ``` I'd prefer to not have the `system()` calls in there.
Found on [sitepoint](http://www.sitepoint.com/blogs/2009/05/01/interactive-cli-password-prompt-in-php/). ``` function prompt_silent($prompt = "Enter Password:") { if (preg_match('/^win/i', PHP_OS)) { $vbscript = sys_get_temp_dir() . 'prompt_password.vbs'; file_put_contents( $vbscript, 'wscript.echo(InputBox("' . addslashes($prompt) . '", "", "password here"))'); $command = "cscript //nologo " . escapeshellarg($vbscript); $password = rtrim(shell_exec($command)); unlink($vbscript); return $password; } else { $command = "/usr/bin/env bash -c 'echo OK'"; if (rtrim(shell_exec($command)) !== 'OK') { trigger_error("Can't invoke bash"); return; } $command = "/usr/bin/env bash -c 'read -s -p \"" . addslashes($prompt) . "\" mypassword && echo \$mypassword'"; $password = rtrim(shell_exec($command)); echo "\n"; return $password; } } ```
187,742
<p>I have this:</p> <pre><code>public string Log { get { return log; } protected set { if (log != value) { MarkModified(PropertyNames.Log, log); log = value; } } } </code></pre> <p>And my utility class for databinding does this:</p> <pre><code>PropertyInfo pi = ReflectionHelper.GetPropertyInfo(boundObjectType, sourceProperty); if (!pi.CanWrite) SetReadOnlyCharacteristics(boundEditor); </code></pre> <p>But PropertyInfo.CanWrite does not care whether the set is publicly accessible, only that it exists.</p> <p>How can I determine if there's a <strong>public</strong> set, not just <strong>any</strong> set?</p>
[ { "answer_id": 187769, "author": "Darren Kopp", "author_id": 77, "author_profile": "https://Stackoverflow.com/users/77", "pm_score": 2, "selected": false, "text": "<p>You need to use the <a href=\"http://msdn.microsoft.com/en-us/library/system.reflection.bindingflags.aspx\" rel=\"nofollow noreferrer\">BindingFlags</a>. Something like </p>\n\n<pre><code>PropertyInfo property = type.GetProperty(\"MyProperty\", BindingFlags.Public | BindingFlags.SetProperty | BindingFlags.Instance);\n</code></pre>\n" }, { "answer_id": 187775, "author": "James Curran", "author_id": 12725, "author_profile": "https://Stackoverflow.com/users/12725", "pm_score": 0, "selected": false, "text": "<p>Inside your ReflectionHelper.GetPropertyInfo(), you presumably to a boundObjectType.GetType().GetProperties(), where the BindingFlags parameter apparently includes BindingFlags.NonPublic. You want to specify just BindingFlags.Public</p>\n" }, { "answer_id": 187778, "author": "Ilya Ryzhenkov", "author_id": 18575, "author_profile": "https://Stackoverflow.com/users/18575", "pm_score": 1, "selected": false, "text": "<p>Call GetSetMethod on PropertyInfo, obtain MethodInfo and examine its properties, like IsPublic. </p>\n" }, { "answer_id": 187793, "author": "Jon Skeet", "author_id": 22656, "author_profile": "https://Stackoverflow.com/users/22656", "pm_score": 2, "selected": true, "text": "<p>An alternative to the suggested changes to ReflectionHelper in other answers is to call <code>pi.GetSetMethod(false)</code> and see if the result is null.</p>\n" }, { "answer_id": 187794, "author": "Nick", "author_id": 22407, "author_profile": "https://Stackoverflow.com/users/22407", "pm_score": 0, "selected": false, "text": "<p>Well it's a little hard to tell since you have a \"ReflectionHelper\" class where we cannot see the source. However, my first guess is that you aren't properly setting the BindingFlags attribute when you call Type.GetProperty. You need to OR in the Public enumeration flag to ensure that only Public values are returned.</p>\n" } ]
2008/10/09
[ "https://Stackoverflow.com/questions/187742", "https://Stackoverflow.com", "https://Stackoverflow.com/users/549/" ]
I have this: ``` public string Log { get { return log; } protected set { if (log != value) { MarkModified(PropertyNames.Log, log); log = value; } } } ``` And my utility class for databinding does this: ``` PropertyInfo pi = ReflectionHelper.GetPropertyInfo(boundObjectType, sourceProperty); if (!pi.CanWrite) SetReadOnlyCharacteristics(boundEditor); ``` But PropertyInfo.CanWrite does not care whether the set is publicly accessible, only that it exists. How can I determine if there's a **public** set, not just **any** set?
An alternative to the suggested changes to ReflectionHelper in other answers is to call `pi.GetSetMethod(false)` and see if the result is null.
187,770
<p>I have a database called foo and a database called bar. I have a table in foo called tblFoobar that I want to move (data and all) to database bar from database foo. What is the SQL statement to do this?</p>
[ { "answer_id": 187785, "author": "Amy B", "author_id": 8155, "author_profile": "https://Stackoverflow.com/users/8155", "pm_score": 9, "selected": true, "text": "<p>On SQL Server? and on the same database server? Use three part naming.</p>\n\n<pre><code>INSERT INTO bar..tblFoobar( *fieldlist* )\nSELECT *fieldlist* FROM foo..tblFoobar\n</code></pre>\n\n<p>This just moves the data. If you want to move the table definition (and other attributes such as permissions and indexes), you'll have to do something else.</p>\n" }, { "answer_id": 187833, "author": "leoinfo", "author_id": 6948, "author_profile": "https://Stackoverflow.com/users/6948", "pm_score": 7, "selected": false, "text": "<p>This should work:</p>\n<pre><code>SELECT * \nINTO DestinationDB..MyDestinationTable \nFROM SourceDB..MySourceTable \n</code></pre>\n<p>It will <strong>not</strong> copy constraints, defaults or indexes. The table created will <strong>not</strong> have a clustered index.</p>\n<p>Alternatively you could:</p>\n<pre><code>INSERT INTO DestinationDB..MyDestinationTable \nSELECT * FROM SourceDB..MySourceTable\n</code></pre>\n<p>If your destination table exists and is empty.</p>\n" }, { "answer_id": 187837, "author": "ScottStonehouse", "author_id": 2342, "author_profile": "https://Stackoverflow.com/users/2342", "pm_score": 5, "selected": false, "text": "<ol>\n<li><p>Script the <code>create table</code> in management studio, run that script in bar to create the table. (Right click table in object explorer, script table as, create to...)</p></li>\n<li><p><code>INSERT bar.[schema].table SELECT * FROM foo.[schema].table</code></p></li>\n</ol>\n" }, { "answer_id": 187852, "author": "David", "author_id": 18981, "author_profile": "https://Stackoverflow.com/users/18981", "pm_score": 9, "selected": false, "text": "<p>SQL Server Management Studio's \"Import Data\" task (right-click on the DB name, then tasks) will do most of this for you. Run it from the database you want to copy the data into.</p>\n\n<p>If the tables don't exist it will create them for you, but you'll probably have to recreate any indexes and such. If the tables do exist, it will append the new data by default but you can adjust that (edit mappings) so it will delete all existing data.</p>\n\n<p>I use this all the time and it works fairly well.</p>\n" }, { "answer_id": 7733780, "author": "ryan", "author_id": 135397, "author_profile": "https://Stackoverflow.com/users/135397", "pm_score": 4, "selected": false, "text": "<p>You can also use the <strong><a href=\"http://blog.sqlauthority.com/2009/07/29/sql-server-2008-copy-database-with-data-generate-t-sql-for-inserting-data-from-one-table-to-another-table/\">Generate SQL Server Scripts Wizard</a></strong> to help guide the creation of SQL script's that can do the following: </p>\n\n<ul>\n<li>copy the table schema</li>\n<li>any constraints (identity, default values, etc)</li>\n<li>data within the table</li>\n<li>and many other options if needed </li>\n</ul>\n\n<p>Good example workflow for <strong>SQL Server 2008</strong> with screen shots shown <a href=\"http://blog.sqlauthority.com/2009/07/29/sql-server-2008-copy-database-with-data-generate-t-sql-for-inserting-data-from-one-table-to-another-table/\">here</a>. </p>\n" }, { "answer_id": 10466996, "author": "NeverHopeless", "author_id": 751527, "author_profile": "https://Stackoverflow.com/users/751527", "pm_score": 3, "selected": false, "text": "<p>You may go with this way: ( a general example )</p>\n<pre><code>insert into QualityAssuranceDB.dbo.Customers (columnA, ColumnB)\nSelect columnA, columnB from DeveloperDB.dbo.Customers\n</code></pre>\n<p>Also if you need to generate the column names as well to put in insert clause, use:</p>\n<pre><code> select (name + ',') as TableColumns from sys.columns \nwhere object_id = object_id('YourTableName')\n</code></pre>\n<p>Copy the result and paste into query window to represent your table column names and even this will exclude the identity column as well:</p>\n<pre><code> select (name + ',') as TableColumns from sys.columns \nwhere object_id = object_id('YourTableName') and is_identity = 0\n</code></pre>\n<p>Remember the script to copy rows will work if the databases belongs to the same location.</p>\n<hr />\n<p>You can Try This.</p>\n<pre><code>select * into &lt;Destination_table&gt; from &lt;Servername&gt;.&lt;DatabaseName&gt;.dbo.&lt;sourceTable&gt;\n</code></pre>\n<p>Server name is optional if both DB is in same server.</p>\n" }, { "answer_id": 15520278, "author": "Igor Voplov", "author_id": 2160520, "author_profile": "https://Stackoverflow.com/users/2160520", "pm_score": 6, "selected": false, "text": "<p>If it’s one table only then all you need to do is </p>\n\n<ul>\n<li>Script table definition</li>\n<li>Create new table in another database </li>\n<li>Update rules, indexes, permissions and such</li>\n<li>Import data (several insert into examples are already shown above)</li>\n</ul>\n\n<p>One thing you’ll have to consider is other updates such as migrating other objects in the future. Note that your source and destination tables do not have the same name. This means that you’ll also have to make changes if you dependent objects such as views, stored procedures and other. </p>\n\n<p>Whit one or several objects you can go manually w/o any issues. However, when there are more than just a few updates 3rd party comparison tools come in very handy. Right now I’m using <a href=\"http://www.apexsql.com/sql_tools_diff.aspx\" rel=\"noreferrer\">ApexSQL Diff</a> for schema migrations but you can’t go wrong with any other tool out there.</p>\n" }, { "answer_id": 69825362, "author": "Francesco Mantovani", "author_id": 4652358, "author_profile": "https://Stackoverflow.com/users/4652358", "pm_score": 0, "selected": false, "text": "<p>I give you three options:</p>\n<p>If they are two databases on the same instance do:</p>\n<pre><code>SELECT * INTO My_New_Table FROM [HumanResources].[Department];\n</code></pre>\n<p>If they are two databases on different servers and you have linked servers do:</p>\n<pre><code>SELECT * INTO My_New_Table FROM [ServerName].[AdventureWorks2012].[HumanResources].[Department];\n</code></pre>\n<p>If they are two databases on different servers and you don't have linked servers do:</p>\n<pre><code>SELECT * INTO My_New_Table\nFROM OPENROWSET('SQLNCLI', 'Server=My_Remote_Server;Trusted_Connection=yes;',\n 'SELECT * FROM AdventureWorks2012.HumanResources.Department');\n</code></pre>\n" } ]
2008/10/09
[ "https://Stackoverflow.com/questions/187770", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7952/" ]
I have a database called foo and a database called bar. I have a table in foo called tblFoobar that I want to move (data and all) to database bar from database foo. What is the SQL statement to do this?
On SQL Server? and on the same database server? Use three part naming. ``` INSERT INTO bar..tblFoobar( *fieldlist* ) SELECT *fieldlist* FROM foo..tblFoobar ``` This just moves the data. If you want to move the table definition (and other attributes such as permissions and indexes), you'll have to do something else.
187,774
<p>I have XML that looks like</p> <pre><code>&lt;answers&gt; &lt;answer&gt; &lt;question-number&gt;1&lt;/question-number&gt; &lt;value&gt;3&lt;/value&gt; &lt;mean xsi:nil="1" /&gt; &lt;/answer&gt; &lt;answer&gt; &lt;question-number&gt;2&lt;/question-number&gt; &lt;value&gt;2&lt;/value&gt; &lt;mean&gt;2.3&lt;/mean&gt; &lt;/answer&gt; &lt;answer&gt; &lt;question-number&gt;3&lt;/question-number&gt; &lt;value&gt;3&lt;/value&gt; &lt;mean xsi:nil="1" /&gt; &lt;/answer&gt; .... &lt;/answers&gt; </code></pre> <p>I'm formatting each answer using xsl:for-each. If there is a mean present I have a graphical representation of the mean. For some potential lists of answers the mean will always be null.</p> <p>At the bottom of the page I want to put a legend explaining the graphical representation of the mean. But I only want it to appear if I actually displayed a mean at all. So I want to be able to do a check, after closing the xsl:for-each, to say "do any of the answer elements have a non-null mean value?".</p> <p>Really not sure how to do that. </p>
[ { "answer_id": 187843, "author": "Robert Gould", "author_id": 15124, "author_profile": "https://Stackoverflow.com/users/15124", "pm_score": 0, "selected": false, "text": "<p>Something like this should work. if you have any means it will return true</p>\n\n<pre><code>&lt;xs:if test=\"/answers/answer/mean\"&gt;You have a mean&lt;/xs:if&gt;\n</code></pre>\n\n<p>I think this is what you mean.</p>\n\n<p>Edit: maybe this?</p>\n\n<pre><code>&lt;xs:if test=\"(count(/answers/answer/mean)==1)\"&gt;You have a mean&lt;xs:if&gt;\n</code></pre>\n\n<p>Not sure if this works, but it might</p>\n\n<pre><code>&lt;xs:if test=\"/answers/answer/mean != nil\"&gt;You have a mean&lt;/xs:if&gt;\n</code></pre>\n" }, { "answer_id": 187933, "author": "Jasper", "author_id": 18702, "author_profile": "https://Stackoverflow.com/users/18702", "pm_score": 3, "selected": false, "text": "<p>do any of the answer elements have a non-null mean value?\nbased on roberts example</p>\n\n<pre><code>&lt;xs:if test=\"(count(/answers/answer/mean[not(@xsi:nil)])&gt;0\"&gt;&lt;xs:if&gt;\n</code></pre>\n\n<p>EDIT:</p>\n\n<pre><code>&lt;xs:if test=\"//answer/mean[not(text())]\"&gt;&lt;xs:if&gt;\n</code></pre>\n\n<p>LAST EDIT (before going home...)</p>\n\n<pre><code>&lt;xs:if test=\"//answer/mean[attribute::xsi:nil]\"&gt;&lt;xs:if&gt;\n</code></pre>\n" }, { "answer_id": 187938, "author": "Dave DuPlantis", "author_id": 8174, "author_profile": "https://Stackoverflow.com/users/8174", "pm_score": 0, "selected": false, "text": "<p>What about something like this?</p>\n\n<pre><code> &lt;xsl:for-each select=\"/answers/answer\"&gt;\n &lt;xsl:if test=\"mean &amp;gt;= 0\"&gt;\n ... other code ...\n &lt;/xsl:if&gt;\n &lt;/xsl:for-each&gt;\n</code></pre>\n" }, { "answer_id": 187942, "author": "workmad3", "author_id": 16035, "author_profile": "https://Stackoverflow.com/users/16035", "pm_score": 2, "selected": false, "text": "<pre><code>&lt;xs:if test=\"count(/answers/answer/mean[@xsi:nil != '1']) &gt; 0\"&gt;Mean stuff here&lt;/xs:if&gt;\n</code></pre>\n\n<p>Should do what you want (count the means where the xsi:nil attribute isn't set to 1)</p>\n" }, { "answer_id": 188426, "author": "Jacob Mattison", "author_id": 1237, "author_profile": "https://Stackoverflow.com/users/1237", "pm_score": 2, "selected": true, "text": "<p>Here's what finally worked for me:</p>\n\n<pre><code>&lt;xsl:if test=\"//answers/answer/mean&gt;0\"&gt;\n</code></pre>\n\n<p>That is to say, \"do there exist any answer elements for which the mean value is greater than zero\". Fortunately I know that the mean value, if there is one, will in fact always be greater than zero -- unfortunately this isn't a generalized solution for this reason.</p>\n\n<p>I still think the approach that jasper and workmad3 were taking (checking for the xsi:nil attribute) ought to work, but I couldn't get the syntax to actually... work.</p>\n\n<p>Many thanks, all.</p>\n" } ]
2008/10/09
[ "https://Stackoverflow.com/questions/187774", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1237/" ]
I have XML that looks like ``` <answers> <answer> <question-number>1</question-number> <value>3</value> <mean xsi:nil="1" /> </answer> <answer> <question-number>2</question-number> <value>2</value> <mean>2.3</mean> </answer> <answer> <question-number>3</question-number> <value>3</value> <mean xsi:nil="1" /> </answer> .... </answers> ``` I'm formatting each answer using xsl:for-each. If there is a mean present I have a graphical representation of the mean. For some potential lists of answers the mean will always be null. At the bottom of the page I want to put a legend explaining the graphical representation of the mean. But I only want it to appear if I actually displayed a mean at all. So I want to be able to do a check, after closing the xsl:for-each, to say "do any of the answer elements have a non-null mean value?". Really not sure how to do that.
Here's what finally worked for me: ``` <xsl:if test="//answers/answer/mean>0"> ``` That is to say, "do there exist any answer elements for which the mean value is greater than zero". Fortunately I know that the mean value, if there is one, will in fact always be greater than zero -- unfortunately this isn't a generalized solution for this reason. I still think the approach that jasper and workmad3 were taking (checking for the xsi:nil attribute) ought to work, but I couldn't get the syntax to actually... work. Many thanks, all.
187,777
<p>How can I get the BSSID / MAC (Media Access Control) address of the wireless access point my system is connected to using C#?</p> <p>Note that I'm interested in the BSSID of the WAP. This is different from the MAC address of the networking portion of the WAP.</p>
[ { "answer_id": 187867, "author": "Iain", "author_id": 5993, "author_profile": "https://Stackoverflow.com/users/5993", "pm_score": 6, "selected": true, "text": "<p>The following needs to be executed programmatically:</p>\n\n<pre><code>netsh wlan show networks mode=Bssid | findstr \"BSSID\"\n</code></pre>\n\n<p>The above shows the access point's wireless MAC addresses which is different from:</p>\n\n<pre><code>arp -a | findstr 192.168.1.254\n</code></pre>\n\n<p>This is because the access point has 2 MAC addresses. One for the wireless device and one for the networking device. I want the wireless MAC but get the networking MAC using <em>arp</em>.</p>\n\n<p>Using the <a href=\"http://www.codeplex.com/managedwifi\" rel=\"nofollow noreferrer\">Managed Wifi API</a>:</p>\n\n<pre><code>var wlanClient = new WlanClient();\nforeach (WlanClient.WlanInterface wlanInterface in wlanClient.Interfaces)\n{\n Wlan.WlanBssEntry[] wlanBssEntries = wlanInterface.GetNetworkBssList();\n foreach (Wlan.WlanBssEntry wlanBssEntry in wlanBssEntries)\n {\n byte[] macAddr = wlanBssEntry.dot11Bssid;\n var macAddrLen = (uint) macAddr.Length;\n var str = new string[(int) macAddrLen];\n for (int i = 0; i &lt; macAddrLen; i++)\n {\n str[i] = macAddr[i].ToString(\"x2\");\n }\n string mac = string.Join(\"\", str);\n Console.WriteLine(mac);\n }\n}\n</code></pre>\n" }, { "answer_id": 188050, "author": "Tim Farley", "author_id": 4425, "author_profile": "https://Stackoverflow.com/users/4425", "pm_score": 2, "selected": false, "text": "<p>About getting that result from ARP.EXE programmatically:</p>\n\n<p>The Win32 API to get this is in the <a href=\"http://msdn.microsoft.com/en-us/library/aa366073(VS.85).aspx\" rel=\"nofollow noreferrer\">IP Helper</a> group of functions and it is called <a href=\"http://msdn.microsoft.com/en-us/library/aa365956(VS.85).aspx\" rel=\"nofollow noreferrer\">GetIpNetTable()</a>. The <a href=\"http://www.pinvoke.net/search.aspx?search=GetIpNetTable\" rel=\"nofollow noreferrer\">P/Invoke signature for it is here</a>. You'll have to write some code to marshal the results out of it, and its one of those fun Win32 APIs with variable length results.</p>\n\n<p>Another way to do this would be to use <a href=\"http://msdn.microsoft.com/en-us/library/aa310909(VS.71).aspx\" rel=\"nofollow noreferrer\">Windows Management Instrumentation</a> which does have a nice set of wrapper classes in the <a href=\"http://msdn.microsoft.com/en-us/library/aa720682(VS.71).aspx\" rel=\"nofollow noreferrer\">System.Management and System.Management.Instrumentation namespaces</a>. But the down side is the WMI service must be running for that to work. I've dug around but I can't seem to find the exact object in the WMI tree that contains the equivalent information. I'm pretty sure it exists because I see third-party tools on the net that claim to retrieve this info using this API. Maybe someone else will chime in with that part.</p>\n" }, { "answer_id": 7797261, "author": "Lennard", "author_id": 999671, "author_profile": "https://Stackoverflow.com/users/999671", "pm_score": 2, "selected": false, "text": "<pre><code>using System;\nusing System.Diagnostics;\n\nclass Program\n{\n static void Main(string[] args)\n { \n Process proc = new Process();\n proc.StartInfo.CreateNoWindow = true;\n proc.StartInfo.FileName = \"cmd\";\n\n proc.StartInfo.Arguments = @\"/C \"\"netsh wlan show networks mode=bssid | findstr BSSID \"\"\";\n\n proc.StartInfo.RedirectStandardOutput = true; \n proc.StartInfo.UseShellExecute = false;\n proc.Start();\n string output = proc.StandardOutput.ReadToEnd();\n proc.WaitForExit(); \n\n Console.WriteLine(output); \n } \n}\n</code></pre>\n\n<p>Beware of syntax error like curly braces all that. But the concept is here. You may create Scan function by periodically invoking this process. Correct me if something goes wrong. </p>\n" } ]
2008/10/09
[ "https://Stackoverflow.com/questions/187777", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5993/" ]
How can I get the BSSID / MAC (Media Access Control) address of the wireless access point my system is connected to using C#? Note that I'm interested in the BSSID of the WAP. This is different from the MAC address of the networking portion of the WAP.
The following needs to be executed programmatically: ``` netsh wlan show networks mode=Bssid | findstr "BSSID" ``` The above shows the access point's wireless MAC addresses which is different from: ``` arp -a | findstr 192.168.1.254 ``` This is because the access point has 2 MAC addresses. One for the wireless device and one for the networking device. I want the wireless MAC but get the networking MAC using *arp*. Using the [Managed Wifi API](http://www.codeplex.com/managedwifi): ``` var wlanClient = new WlanClient(); foreach (WlanClient.WlanInterface wlanInterface in wlanClient.Interfaces) { Wlan.WlanBssEntry[] wlanBssEntries = wlanInterface.GetNetworkBssList(); foreach (Wlan.WlanBssEntry wlanBssEntry in wlanBssEntries) { byte[] macAddr = wlanBssEntry.dot11Bssid; var macAddrLen = (uint) macAddr.Length; var str = new string[(int) macAddrLen]; for (int i = 0; i < macAddrLen; i++) { str[i] = macAddr[i].ToString("x2"); } string mac = string.Join("", str); Console.WriteLine(mac); } } ```
187,779
<p>Is it possible to update IIS on Windows XP from 5.1 to 6?</p> <p>If so how?</p> <p>Thanks.</p>
[ { "answer_id": 187802, "author": "Grant Wagner", "author_id": 9254, "author_profile": "https://Stackoverflow.com/users/9254", "pm_score": 6, "selected": true, "text": "<p>No, it is not possible. The version of IIS is tied to a specific version of Windows.</p>\n\n<pre><code>XP = IIS 5.1\n2003 = IIS 6\n2008 = IIS 7\n</code></pre>\n\n<p>More information available at <a href=\"http://support.microsoft.com/kb/224609\" rel=\"noreferrer\">http://support.microsoft.com/kb/224609</a>.</p>\n" }, { "answer_id": 187813, "author": "curtisk", "author_id": 17651, "author_profile": "https://Stackoverflow.com/users/17651", "pm_score": 2, "selected": false, "text": "<p>No, I believe it is just for Win2003 and x64 XP Pro</p>\n" }, { "answer_id": 1973868, "author": "bokac", "author_id": 240094, "author_profile": "https://Stackoverflow.com/users/240094", "pm_score": 1, "selected": false, "text": "<p>it is possible if you have XP x64 Pro</p>\n" }, { "answer_id": 3156426, "author": "David Waters", "author_id": 12148, "author_profile": "https://Stackoverflow.com/users/12148", "pm_score": 4, "selected": false, "text": "<p>It is now possible to Run IIS 7 - Express on XP, this is a full iis for developing but not deploying web applications.</p>\n\n<p>see <a href=\"http://weblogs.asp.net/scottgu/archive/2010/06/28/introducing-iis-express.aspx\" rel=\"noreferrer\">http://weblogs.asp.net/scottgu/archive/2010/06/28/introducing-iis-express.aspx</a></p>\n" } ]
2008/10/09
[ "https://Stackoverflow.com/questions/187779", "https://Stackoverflow.com", "https://Stackoverflow.com/users/12148/" ]
Is it possible to update IIS on Windows XP from 5.1 to 6? If so how? Thanks.
No, it is not possible. The version of IIS is tied to a specific version of Windows. ``` XP = IIS 5.1 2003 = IIS 6 2008 = IIS 7 ``` More information available at <http://support.microsoft.com/kb/224609>.
187,795
<p>For simplicity lets say I have two flex mxml pages. </p> <p>form.mxml<br> button.mxml</p> <p>If the form.mxml page had the following code, it should work fine:</p> <pre><code>&lt;custom:SelectView dSource="{_thedata}" id="form" visible="false"&gt; &lt;/custom:SelectView&gt; &lt;mx:LinkButton label="Show" id="lbShow" click="form.visible=true;&gt; &lt;mx:LinkButton label="Show" id="lbHide" click="form.visible=false;&gt; </code></pre> <p>But if the code was like:</p> <p>form.mxml</p> <pre><code> &lt;custom:SelectView dSource="{_thedata}" id="form" visible="false"&gt; &lt;/custom:SelectView&gt; </code></pre> <p>button.mxml</p> <pre><code>&lt;mx:LinkButton label="Show" id="lbShow" click="form.visible=true;&gt; &lt;mx:LinkButton label="Show" id="lbHide" click="form.visible=false;&gt; </code></pre> <p>how can I make a call from button.mxml to change form.mxml</p> <p>---- a bit more details ---</p> <p>My page actually looks like this: where query:AdvancedSearchFields is basically including a flex form into the page, and I want it to show/hide the custom view below after the search is complete. </p> <pre><code>&lt;query:AdvancedSearchFields searchType="projects" searchCategory="advanced" visible="true" id="AdvancedSearch" /&gt; &lt;custom:SelectView dSource="{_searchResults}" id="sv" visible="false"&gt; </code></pre>
[ { "answer_id": 187889, "author": "Matt Dillard", "author_id": 863, "author_profile": "https://Stackoverflow.com/users/863", "pm_score": 0, "selected": false, "text": "<p>Your <code>button.mxml</code> class must have a reference to the instance of the 'form' class which will be affected. Then it can operate on it directly:</p>\n\n<p><em>Button.mxml:</em></p>\n\n<pre><code>&lt;mx:Script&gt;\n&lt;![CDATA[\n [Bindable] public var myForm:MyFormClass;\n]]&gt;\n&lt;/mx:Script&gt;\n\n&lt;mx:LinkButton label=\"Show\" id=\"lbShow\" click=\"myForm.form.visible=true;\"&gt;\n&lt;mx:LinkButton label=\"Show\" id=\"lbHide\" click=\"myForm.form.visible=false;\"&gt;\n</code></pre>\n\n<p>Generally, the most logical place to set this variable is in the parent of your <code>Button</code> class.</p>\n" }, { "answer_id": 187914, "author": "Herms", "author_id": 1409, "author_profile": "https://Stackoverflow.com/users/1409", "pm_score": 3, "selected": true, "text": "<p>You could write a custom method that handles the button click events and raises a custom event. Then in form.mxml you can handle that event.</p>\n\n<p>Splitting it up like this is a bit cleaner, as it makes the button.mxml file work on its own. Having Button.mxml have a direct reference to your form causes a tight-coupling between the two, and generally you should avoid tight-coupling.</p>\n\n<p>EDIT: I just had another thought that also avoids tight-coupling and is a bit simpler:</p>\n\n<p><em>form.mxml</em></p>\n\n<pre><code>&lt;custom:SelectView dSource=\"{_thedata}\" id=\"form\" visible=\"{buttons.showForm}\"&gt;\n&lt;/custom:SelectView&gt;\n\n&lt;!-- include your buttons.mxml component using an ID of \"buttons\" --&gt;\n</code></pre>\n\n<p><em>buttons.mxml</em></p>\n\n<pre><code>&lt;mx:Script&gt;\n&lt;![CDATA[\n [Bindable] public var showForm:Boolean = true;\n]]&gt;\n&lt;/mx:Script&gt;\n\n&lt;mx:LinkButton label=\"Show\" id=\"lbShow\" click=\"this.showForm=true;\"&gt;\n&lt;mx:LinkButton label=\"Hide\" id=\"lbHide\" click=\"this.showForm=false;\"&gt;\n</code></pre>\n\n<p>This essentially emulates using a custom event by using variable binding. Any time the showForm variable in buttons changes the visible property of the SelectView will be updated via the bindings. This is lighter-weight than creating a custom event (though I think custom events are a bit better of a design for it).</p>\n" }, { "answer_id": 200030, "author": "Aaron", "author_id": 23965, "author_profile": "https://Stackoverflow.com/users/23965", "pm_score": 0, "selected": false, "text": "<p>If you need to deal with this problem more often, I'd suggest using an MVC framework like PureMVC. It's set up so that you have a Mediator object that listens for events from MXML components, then sends a notification which can be picked up by any other mediator. Then that mediator can manipulate its own visual component based on the notification and its associated data.</p>\n\n<p>In the context of what you're doing (the simple version), you're okay with the basic solution. But once you're dealing with four or five or more components with lots of logic, you will not be happy at all.</p>\n" } ]
2008/10/09
[ "https://Stackoverflow.com/questions/187795", "https://Stackoverflow.com", "https://Stackoverflow.com/users/24563/" ]
For simplicity lets say I have two flex mxml pages. form.mxml button.mxml If the form.mxml page had the following code, it should work fine: ``` <custom:SelectView dSource="{_thedata}" id="form" visible="false"> </custom:SelectView> <mx:LinkButton label="Show" id="lbShow" click="form.visible=true;> <mx:LinkButton label="Show" id="lbHide" click="form.visible=false;> ``` But if the code was like: form.mxml ``` <custom:SelectView dSource="{_thedata}" id="form" visible="false"> </custom:SelectView> ``` button.mxml ``` <mx:LinkButton label="Show" id="lbShow" click="form.visible=true;> <mx:LinkButton label="Show" id="lbHide" click="form.visible=false;> ``` how can I make a call from button.mxml to change form.mxml ---- a bit more details --- My page actually looks like this: where query:AdvancedSearchFields is basically including a flex form into the page, and I want it to show/hide the custom view below after the search is complete. ``` <query:AdvancedSearchFields searchType="projects" searchCategory="advanced" visible="true" id="AdvancedSearch" /> <custom:SelectView dSource="{_searchResults}" id="sv" visible="false"> ```
You could write a custom method that handles the button click events and raises a custom event. Then in form.mxml you can handle that event. Splitting it up like this is a bit cleaner, as it makes the button.mxml file work on its own. Having Button.mxml have a direct reference to your form causes a tight-coupling between the two, and generally you should avoid tight-coupling. EDIT: I just had another thought that also avoids tight-coupling and is a bit simpler: *form.mxml* ``` <custom:SelectView dSource="{_thedata}" id="form" visible="{buttons.showForm}"> </custom:SelectView> <!-- include your buttons.mxml component using an ID of "buttons" --> ``` *buttons.mxml* ``` <mx:Script> <![CDATA[ [Bindable] public var showForm:Boolean = true; ]]> </mx:Script> <mx:LinkButton label="Show" id="lbShow" click="this.showForm=true;"> <mx:LinkButton label="Hide" id="lbHide" click="this.showForm=false;"> ``` This essentially emulates using a custom event by using variable binding. Any time the showForm variable in buttons changes the visible property of the SelectView will be updated via the bindings. This is lighter-weight than creating a custom event (though I think custom events are a bit better of a design for it).
187,797
<p>Say I've got a class like this:</p> <pre><code>class Test { int x; SomeClass s; } </code></pre> <p>And I instantiate it like this:</p> <pre><code>Test* t = new Test; </code></pre> <p>Is x on the stack, or the heap? What about s?</p>
[ { "answer_id": 187806, "author": "Avdi", "author_id": 20487, "author_profile": "https://Stackoverflow.com/users/20487", "pm_score": 3, "selected": false, "text": "<p>Since you've used <code>new</code>, it's all on the heap, stored [more or less] contiguously in <code>t</code>'s memory area.</p>\n" }, { "answer_id": 187811, "author": "moonshadow", "author_id": 11834, "author_profile": "https://Stackoverflow.com/users/11834", "pm_score": 4, "selected": false, "text": "<pre><code>Test a;\nTest *t = new Test;\n</code></pre>\n\n<p>a, and all its members, are on the stack.</p>\n\n<p>The object pointed to by t, and all its members, are on the heap.</p>\n\n<p>The pointer t is on the stack.</p>\n" }, { "answer_id": 187812, "author": "James Curran", "author_id": 12725, "author_profile": "https://Stackoverflow.com/users/12725", "pm_score": 3, "selected": false, "text": "<p>t is on the stack. The object at *t is on the heap. It contains an int and a SomeClass object next to each other in a unit.</p>\n" }, { "answer_id": 187814, "author": "Luc Touraille", "author_id": 20984, "author_profile": "https://Stackoverflow.com/users/20984", "pm_score": 1, "selected": false, "text": "<p>Since you're using new, you're allocating your object on the heap. Consequently, every members of the Test pointed by t are on the heap too.</p>\n" }, { "answer_id": 187951, "author": "paercebal", "author_id": 14089, "author_profile": "https://Stackoverflow.com/users/14089", "pm_score": 4, "selected": true, "text": "<p>Each time you &quot;instantiate&quot; an object/symbol using a new (we are speaking C++ here), a new memory zone will be allocated for this object. If not, it will be put on the &quot;local&quot; memory zone.</p>\n<p>The problem is that I have no standard definition for &quot;local&quot; memory zone.</p>\n<h2>An example</h2>\n<p>This means that, for example:</p>\n<pre><code>struct A\n{\n A()\n {\n c = new C() ;\n }\n\n B b ;\n C * c ;\n}\n\nvoid doSomething()\n{\n A aa00 ;\n A * aa01 = new A() ;\n}\n</code></pre>\n<p>The object aa00 is allocated on the stack.</p>\n<p>As aa00::b is allocated on a &quot;local&quot; memory according to aa00, aa00::b is allocated inside the memory range allocated by the new aa00 instruction. Thus, aa00::b is also allocated on stack.</p>\n<p>But aa00::c is a pointer, allocated with new, so the object designed by aa00::c is on the heap.</p>\n<p>Now, the tricky example: aa01 is allocated via a new, and as such, on the heap.</p>\n<p>In that case, as aa01::b is allocated on a &quot;local&quot; memory according to aa01, aa01::b is allocated inside the memory range allocated by the new aa01 instruction. Thus, aa01::b is on the heap, &quot;inside&quot; the memory already allocated for aa01.</p>\n<p>As aa01::c is a pointer, allocated with new, the object designed by aa01::c is on the heap, in another memory range than the one allocated for aa01.</p>\n<h2>Conclusion</h2>\n<p>So, the point of the game is:<br>\n1 - What's the &quot;local&quot; memory of the studied object: Stack of Heap?<br>\n2 - if the object is allocated through new, then it is outside this local memory, i.e., it is elsewhere on the heap<br>\n3 - if the object is allocated &quot;without new&quot;, then it is inside the local memory.<br>\n4 - If the &quot;local&quot; memory is on the stack, then the object allocated without new is on the stack, too.<br>\n5 - If the &quot;local&quot; memory is on the heap, then the object allocated without new is on the heap, too, but still inside the local memory.<br></p>\n<p>Sorry, I have no better vocabulary to express those concepts.</p>\n" }, { "answer_id": 188174, "author": "DJClayworth", "author_id": 19276, "author_profile": "https://Stackoverflow.com/users/19276", "pm_score": 1, "selected": false, "text": "<pre><code>class MyClass {\n int i;\n MyInnerClass m;\n MyInnerClass *p = new MyInnerClass();\n}\n\nMyClass a;\nMyClass *b = new MyClass();\n</code></pre>\n\n<p>a is on the stack; its members a.i and a.m (including any members of a.m) and a.p (the pointer, not the object it points to) are part of it and so also on the stack.</p>\n\n<p>The object pointed to by a.p is on the heap.</p>\n\n<p>The object pointed to by b is on the heap, including all its members; and so is the object pointed to by b.p.</p>\n" } ]
2008/10/09
[ "https://Stackoverflow.com/questions/187797", "https://Stackoverflow.com", "https://Stackoverflow.com/users/12828/" ]
Say I've got a class like this: ``` class Test { int x; SomeClass s; } ``` And I instantiate it like this: ``` Test* t = new Test; ``` Is x on the stack, or the heap? What about s?
Each time you "instantiate" an object/symbol using a new (we are speaking C++ here), a new memory zone will be allocated for this object. If not, it will be put on the "local" memory zone. The problem is that I have no standard definition for "local" memory zone. An example ---------- This means that, for example: ``` struct A { A() { c = new C() ; } B b ; C * c ; } void doSomething() { A aa00 ; A * aa01 = new A() ; } ``` The object aa00 is allocated on the stack. As aa00::b is allocated on a "local" memory according to aa00, aa00::b is allocated inside the memory range allocated by the new aa00 instruction. Thus, aa00::b is also allocated on stack. But aa00::c is a pointer, allocated with new, so the object designed by aa00::c is on the heap. Now, the tricky example: aa01 is allocated via a new, and as such, on the heap. In that case, as aa01::b is allocated on a "local" memory according to aa01, aa01::b is allocated inside the memory range allocated by the new aa01 instruction. Thus, aa01::b is on the heap, "inside" the memory already allocated for aa01. As aa01::c is a pointer, allocated with new, the object designed by aa01::c is on the heap, in another memory range than the one allocated for aa01. Conclusion ---------- So, the point of the game is: 1 - What's the "local" memory of the studied object: Stack of Heap? 2 - if the object is allocated through new, then it is outside this local memory, i.e., it is elsewhere on the heap 3 - if the object is allocated "without new", then it is inside the local memory. 4 - If the "local" memory is on the stack, then the object allocated without new is on the stack, too. 5 - If the "local" memory is on the heap, then the object allocated without new is on the heap, too, but still inside the local memory. Sorry, I have no better vocabulary to express those concepts.
187,799
<p>Let me start by saying I'm a huge fan of the elegance of this pattern -- I have a group of basic entities that I have implemented builders for (specifically for testing). However I have found (and this may be the caveat) that as my program evolved I kept having to go back and re-work the builders. In the end, it really hasn't seemed worth it to keep them updated, and I've gone back to primarily keeping a Object Mother that has a lot of pre-configured entities. Should I continue to update the builders for future use, or is the TDBs something that should only be created once you're design has reached some stability and the Object Mother becomes too large?</p> <p>Also note, I've found I'm not using the builders anywhere else in the app, as I enjoy using .Net 3.0 's new syntax for property initialization.</p>
[ { "answer_id": 218542, "author": "Enrico Campidoglio", "author_id": 26396, "author_profile": "https://Stackoverflow.com/users/26396", "pm_score": 1, "selected": false, "text": "<p>If the test data builders become too complex to maintain, I would recommend switching to a <strong>mocking framework</strong>, which makes it more convenient to produce domain test objects with a known state.<br /><br />\nMoreover with mocks you could make the test objects be more than simple stubs, and actually participate in what the test is asserting, by setting <strong>expectations</strong> on how their properties and methods are invoked.</p>\n" }, { "answer_id": 222686, "author": "craigb", "author_id": 18590, "author_profile": "https://Stackoverflow.com/users/18590", "pm_score": 4, "selected": true, "text": "<p>I like using fluent builders for the object under test to express the nature of the object I'm creating. ObjectMothers tend to get unwieldy and tend to (in the implementations I've come across) end up hiding details of the objects creation.</p>\n\n<p>Compare:</p>\n\n<pre><code>User fred = CreateUser(\"fred\").WithReputation(900)\n .WithScholarBadge()\n .WithCriticBadge()\n</code></pre>\n\n<p>vs:</p>\n\n<pre><code>User fred = UserObjectMother.Fred()\n</code></pre>\n\n<p>To express the idea that the user has rep 900 and those two particular badges would be unweildy to do with the ObjectMother. The tendecy I've seen is developers then finding this method that builds <code>Fred()</code>, which is close to what they need so they add more attributes to the object. The fluent builder on the other hand is expressive as to what is being built, and is easy to create specific users for the test as required.</p>\n\n<p>That said, I also end up using these patterns exclusively in test code as the production code does not usually require this sort of expressiveness.</p>\n" }, { "answer_id": 33691394, "author": "Andrew Chaa", "author_id": 437961, "author_profile": "https://Stackoverflow.com/users/437961", "pm_score": 1, "selected": false, "text": "<p>Lambda syntax can makes the fluent interface more succinct</p>\n\n<p>For example,</p>\n\n<pre><code>User fred = new UserTestDataBuilder()\n .With(u =&gt; u.Name = \"fred\")\n .With(u =&gt; u.Reputation = 900)\n .With(u =&gt; u.ScholarBadge = true)\n .With(u =&gt; u.CriticBadge = true)\n</code></pre>\n\n<p>You just need an Action method and a class for the properties to populate.</p>\n\n<pre><code>public class UserSpec\n{\n public string Name {get; set;}\n public int Reputation {get; set;}\n ...\n}\n\npublic class UserTestDataBuilder() \n{\n private UserSpec _userSpec = new UserSpec();\n public UserTestDataBuilder With(Action&lt;UserSpec&gt; action) \n {\n action(_userSpec);\n return this;\n }\n\n public User Build() \n {\n return new User(_userSpec.Name, _userSpec.Reputation, _userSpec.ScholarBadge, _userSpec.CriticBadge);\n }\n}\n</code></pre>\n" } ]
2008/10/09
[ "https://Stackoverflow.com/questions/187799", "https://Stackoverflow.com", "https://Stackoverflow.com/users/25807/" ]
Let me start by saying I'm a huge fan of the elegance of this pattern -- I have a group of basic entities that I have implemented builders for (specifically for testing). However I have found (and this may be the caveat) that as my program evolved I kept having to go back and re-work the builders. In the end, it really hasn't seemed worth it to keep them updated, and I've gone back to primarily keeping a Object Mother that has a lot of pre-configured entities. Should I continue to update the builders for future use, or is the TDBs something that should only be created once you're design has reached some stability and the Object Mother becomes too large? Also note, I've found I'm not using the builders anywhere else in the app, as I enjoy using .Net 3.0 's new syntax for property initialization.
I like using fluent builders for the object under test to express the nature of the object I'm creating. ObjectMothers tend to get unwieldy and tend to (in the implementations I've come across) end up hiding details of the objects creation. Compare: ``` User fred = CreateUser("fred").WithReputation(900) .WithScholarBadge() .WithCriticBadge() ``` vs: ``` User fred = UserObjectMother.Fred() ``` To express the idea that the user has rep 900 and those two particular badges would be unweildy to do with the ObjectMother. The tendecy I've seen is developers then finding this method that builds `Fred()`, which is close to what they need so they add more attributes to the object. The fluent builder on the other hand is expressive as to what is being built, and is easy to create specific users for the test as required. That said, I also end up using these patterns exclusively in test code as the production code does not usually require this sort of expressiveness.
187,836
<p>Sometimes while debugging, I need to restart a service on a remote machine. Currently, I'm doing this via Remote Desktop. How can it be done from the command line on my local machine?</p>
[ { "answer_id": 187854, "author": "Vinko Vrsalovic", "author_id": 5190, "author_profile": "https://Stackoverflow.com/users/5190", "pm_score": 9, "selected": true, "text": "<p>You can use the services console, clicking on the left hand side and then selecting the \"Connect to another computer\" option in the Action menu.</p>\n\n<p>If you wish to use the command line only, you can use</p>\n\n<pre><code>sc \\\\machine stop &lt;service&gt;\n</code></pre>\n" }, { "answer_id": 187862, "author": "Stephen Wrighton", "author_id": 7516, "author_profile": "https://Stackoverflow.com/users/7516", "pm_score": 0, "selected": false, "text": "<p>Well, if you have Visual Studio (I know it's in 2005, not sure about earlier versions though), you can add the remote machine to your \"Server Explorer\" tag. At that point, you'll have access to the SERVICES that are running, or can be ran, from that machine (as well as event logs, and queues, and a couple other interesting things).</p>\n" }, { "answer_id": 187863, "author": "alexmac", "author_id": 23066, "author_profile": "https://Stackoverflow.com/users/23066", "pm_score": 0, "selected": false, "text": "<p>One way would be to enable telnet server on the machin you want to control services on (add/remove windows components)</p>\n\n<p>Open dos prompt<br>\nType telnet <em>yourmachineip/name</em><BR>\nLog on<BR>\ntype net start &amp;serviceName* e.g. w3svc<BR></p>\n\n<p>This will start IIS or you can use net stop to stop a service. </p>\n\n<p>Depending on your setup you need to look at a way of securing the telnet connection as I think its unencrypted.</p>\n" }, { "answer_id": 187873, "author": "Ryan Duffield", "author_id": 2696, "author_profile": "https://Stackoverflow.com/users/2696", "pm_score": 5, "selected": false, "text": "<p>You can use mmc:</p>\n\n<ol>\n<li>Start / Run. Type \"mmc\". </li>\n<li>File / Add/Remove Snap-in... Click \"Add...\"</li>\n<li>Find \"Services\" and click \"Add\"</li>\n<li>Select \"Another computer:\" and type the host name / IP address of the remote machine. Click Finish, Close, etc.</li>\n</ol>\n\n<p>At that point you will be able to manage services as if they were on your local machine.</p>\n" }, { "answer_id": 187874, "author": "Philibert Perusse", "author_id": 7984, "author_profile": "https://Stackoverflow.com/users/7984", "pm_score": 3, "selected": false, "text": "<p>You can use <a href=\"http://technet.microsoft.com/en-us/sysinternals/bb795533.aspx\" rel=\"noreferrer\">System Internals</a> <strong>PSEXEC</strong> command to remotely execute a <strong>net stop yourservice</strong>, then <strong>net start yourservice</strong></p>\n" }, { "answer_id": 187875, "author": "tafa", "author_id": 22186, "author_profile": "https://Stackoverflow.com/users/22186", "pm_score": 1, "selected": false, "text": "<p>I would suggest you to have a look at <a href=\"http://rshd.sourceforge.net/\" rel=\"nofollow noreferrer\">RSHD</a></p>\n\n<p>You do not need to bother for a client, Windows has it by default.</p>\n" }, { "answer_id": 187918, "author": "Andrew Moore", "author_id": 26210, "author_profile": "https://Stackoverflow.com/users/26210", "pm_score": 3, "selected": false, "text": "<p>Using command line, you can do this:</p>\n\n<pre><code>AT \\\\computername time \"NET STOP servicename\"\nAT \\\\computername time \"NET START servicename\"\n</code></pre>\n" }, { "answer_id": 188589, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 0, "selected": false, "text": "<p>Several good solutions here. If you're still on Win2K and can't install anything on the remote computer, this also works:</p>\n\n<p>Open the Computer Management Console (right click My Computer, choose Manage; open from Administrative Tools in the Start Menu; or open from the MMC using the snap-in).</p>\n\n<p>Right click on your computer name and choose \"Connect to Remote Computer\"</p>\n\n<p>Put in the computer name and credentials and you have full access to many admin functions including the services control panel.</p>\n" } ]
2008/10/09
[ "https://Stackoverflow.com/questions/187836", "https://Stackoverflow.com", "https://Stackoverflow.com/users/549/" ]
Sometimes while debugging, I need to restart a service on a remote machine. Currently, I'm doing this via Remote Desktop. How can it be done from the command line on my local machine?
You can use the services console, clicking on the left hand side and then selecting the "Connect to another computer" option in the Action menu. If you wish to use the command line only, you can use ``` sc \\machine stop <service> ```
187,849
<p>I am experiencing some weird behavior with localized messages reported from my background worker process in my windows forms application.</p> <p>The application is a setup application with windows forms. The application launches a background worker to perform and IIS reset and then install MSIs.</p> <p>The first time I run the application on a Spanish Win Server 2003 VM the forms are in spanish but not the BWP messages. If i immediately run it again, the messages are in spanish.</p> <p>The .Resources files are embedded resources and are extracted to the temp directory upon application startup.</p> <p>My code retrieves the localized strings through a custom resource manager class. This class creates a file based resource to the .Resources files in the temp directory. This is working correctly because the windows forms labels and title are localized every time.</p> <p>Has anyone experienced this? I'm absolutely stuck, please help. Thanks, Andrew</p>
[ { "answer_id": 190502, "author": "Brian", "author_id": 19299, "author_profile": "https://Stackoverflow.com/users/19299", "pm_score": 1, "selected": false, "text": "<p>The culture info is in thread-local storage, so if the background worker runs processes on different threads, this may be expected.</p>\n\n<p><a href=\"http://msdn.microsoft.com/en-us/library/system.globalization.cultureinfo.currentculture.aspx\" rel=\"nofollow noreferrer\">http://msdn.microsoft.com/en-us/library/system.globalization.cultureinfo.currentculture.aspx</a></p>\n\n<p><a href=\"http://msdn.microsoft.com/en-us/library/system.threading.thread.currentculture.aspx\" rel=\"nofollow noreferrer\">http://msdn.microsoft.com/en-us/library/system.threading.thread.currentculture.aspx</a></p>\n\n<p>I am not sure what the recommended practice for transfering culture info across threads, though.</p>\n" }, { "answer_id": 8898322, "author": "Maik Preuss", "author_id": 1154412, "author_profile": "https://Stackoverflow.com/users/1154412", "pm_score": 2, "selected": false, "text": "<p>If your UIThread runs an other UICulture than your BackgroundWorker you can explicit change the culture of the worker thread by using an callback like this:</p>\n\n<pre><code> private delegate CultureInfo GetUICultureCallback();\n\n private CultureInfo GetUICulture()\n {\n if (this.InvokeRequired)\n {\n return (CultureInfo)this.Invoke(new GetUICultureCallback(GetUICulture));\n }\n\n return System.Threading.Thread.CurrentThread.CurrentUICulture;\n }\n\n void backgroundWorker_DoWork(object sender, DoWorkEventArgs e)\n {\n System.Threading.Thread.CurrentThread.CurrentUICulture = GetUICulture();\n\n for (; ; )\n {\n if (backgroundWorker.CancellationPending)\n {\n e.Cancel = true;\n return;\n }\n.\n.\n.\n</code></pre>\n" } ]
2008/10/09
[ "https://Stackoverflow.com/questions/187849", "https://Stackoverflow.com", "https://Stackoverflow.com/users/26540/" ]
I am experiencing some weird behavior with localized messages reported from my background worker process in my windows forms application. The application is a setup application with windows forms. The application launches a background worker to perform and IIS reset and then install MSIs. The first time I run the application on a Spanish Win Server 2003 VM the forms are in spanish but not the BWP messages. If i immediately run it again, the messages are in spanish. The .Resources files are embedded resources and are extracted to the temp directory upon application startup. My code retrieves the localized strings through a custom resource manager class. This class creates a file based resource to the .Resources files in the temp directory. This is working correctly because the windows forms labels and title are localized every time. Has anyone experienced this? I'm absolutely stuck, please help. Thanks, Andrew
If your UIThread runs an other UICulture than your BackgroundWorker you can explicit change the culture of the worker thread by using an callback like this: ``` private delegate CultureInfo GetUICultureCallback(); private CultureInfo GetUICulture() { if (this.InvokeRequired) { return (CultureInfo)this.Invoke(new GetUICultureCallback(GetUICulture)); } return System.Threading.Thread.CurrentThread.CurrentUICulture; } void backgroundWorker_DoWork(object sender, DoWorkEventArgs e) { System.Threading.Thread.CurrentThread.CurrentUICulture = GetUICulture(); for (; ; ) { if (backgroundWorker.CancellationPending) { e.Cancel = true; return; } . . . ```
187,851
<p>How can I open a synchronous dialog in Flex? I need to call a function from an External Interface (JavaScript) that will open a simple dialog in the Flex application and returns an value according to the button the user has clicked (OK/Cancel).</p> <p>So it should by a synchronous call to a dialog, i.e. the call waits until the user has closed the dialog like this.</p> <pre><code>//This function is called by JavaScript function onApplicationUnload():Boolean { var result:Boolean; result = showDialogAndWaitForResult(); return result } </code></pre> <p>Does anybody know how I can do this? I could write a loop that waits until the dialog has set a flag and then reads the result to return it, but there must be something that is way more elegant and reusable for waiting of the completion of other asynchronous calls.</p> <p><strong>EDIT:</strong> Unfortunately a callback does not work as the JavaScript function that calls onApplicationUnload() itself has to return a value (similar to the onApplicationUnload() function in Flex). This JavaScript function has a fixed signature as it is called by a framework and I cannot change it. Or in other words: The call from JavaScript to Flex must also be synchronous.</p>
[ { "answer_id": 187955, "author": "David Arno", "author_id": 7122, "author_profile": "https://Stackoverflow.com/users/7122", "pm_score": 2, "selected": false, "text": "<p>Flex doesn't work in a synchronous fashion, as it is a single thread application and so needs your code to hand execution back to the \"core\" in order to handle user input etc.</p>\n\n<p>The way to do it is to make your dialogue's behaviour asynchronous:</p>\n\n<pre><code>function onApplicationUnload():void\n{\n showDialog(resultMethod);\n}\n\nfunction resultMethod(result:Boolean):void\n{\n ExternalInterface.call(\"javaScriptCallback\", [result]);\n}\n</code></pre>\n" }, { "answer_id": 188466, "author": "Herms", "author_id": 1409, "author_profile": "https://Stackoverflow.com/users/1409", "pm_score": 3, "selected": true, "text": "<p>You can't do that in Flex. As David mentioned, Flex is single-threaded, so you can't have your function block while the dialog is being processed.</p>\n\n<p>Your best bet might be to use a Javascript popup. You'll have a lot less control over the window, but it should behave the way you want (blocking the function until it's been closed).</p>\n" }, { "answer_id": 211485, "author": "Yaba", "author_id": 7524, "author_profile": "https://Stackoverflow.com/users/7524", "pm_score": 0, "selected": false, "text": "<p>OK... after all I found a possible solution. But I guess hardly everybody is going to do that seriously :-(</p>\n\n<p>The solution focuses around using a while loop to check for a result and then return the function that is being called by JavaScript. However we need a way to sleep in the while loop, while we are waiting for the result. However calls to JavaScript are synchronous. Now the trick is to make a sleep in JavaScript, which is also not directly available here, but can be done using a synchronous XML Http Request like described on this <a href=\"http://narayanraman.blogspot.com/2005/12/javascript-sleep-or-wait.html\" rel=\"nofollow noreferrer\">blog</a>.</p>\n\n<p>As I said - I won't recommend this only as last resort. For my problem I have resorted to ugly JavaScript popups.</p>\n" }, { "answer_id": 211494, "author": "Mark Ingram", "author_id": 986, "author_profile": "https://Stackoverflow.com/users/986", "pm_score": -1, "selected": false, "text": "<p>You can fake a synchronous dialog in flex by popping up a dialog then disabling everything in the background. You can see this in action if you do <code>Alert.show(\"Hello World\");</code> in an application. The background will grey out and the user won't be able to click on any UI in the background. The app will \"wait\" until the user clicks the OK button.</p>\n" }, { "answer_id": 634637, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 0, "selected": false, "text": "<p>Have your dialog call another function in flex to process the result of the user selection:</p>\n\n<pre><code>private function deleteFileCheck():void\n{\n Alert.show(\"Are you sure you want to delete this file?\",\n \"Confirm Delete\",\n Alert.YES| Alert.NO,\n this, deleteFileHandler, null, Alert.NO);\n}\n\nprivate function deleteFileHandler(event:CloseEvent):void\n{\n if (event.detail == Alert.YES)\n {\n ...do your processing here\n }\n}\n</code></pre>\n" }, { "answer_id": 2648089, "author": "Grafton", "author_id": 317822, "author_profile": "https://Stackoverflow.com/users/317822", "pm_score": 1, "selected": false, "text": "<p>Have your Flex code use an event to wait for the dialog. In the main thread, register an event handler that waits for the dialog to close. On OK in the dialog, dispatch the dialog complete event.</p>\n\n<p>With Cairngorm, this is something like:</p>\n\n<p>In the main thread:</p>\n\n<p><code>CairngormEventDispatcher.getInstance().addEventListener(ClosingDialogCompleteEvent.DIALOG_COMPLETE, onClosingDialogComplete);</code></p>\n\n<p>(if you want to avoid returning until complete, loop on a timer and global variable.)</p>\n\n<p>In the dialog closing handler:</p>\n\n<p><code>CairngormEventDispatcher.dispatchEvent(new ClosingDialogCompleteEvent(&lt;parameters&gt;));</code></p>\n\n<p>The event handler:</p>\n\n<pre><code>\npublic function onClosingDialogComplete (e: ClosingDialogCompleteEvent):void\n{\n param1 = e.param1;\n param2 = e.param2;\n // etc.\n // Continue processing or set the global variable that signals the main thread to continue.\n}\n</code></pre>\n\n<p>For this to work, the class ClosingDialogCompleteEvent has to be defined. Partial code for the class is:</p>\n\n<pre><code>\npackage com. ... .event // You define where the event lives.\n{\nimport com.adobe.cairngorm.control.CairngormEvent;\n\npublic class ClosingDialogCompleteEvent extends CairngormEvent\n{\n // Event type.\n public static const DIALOG_COMPLETE:String = \"dialogComplete\";\n\n public var param1:String;\n public var param2:String;\n\n public function ClosingDialogCompleteEvent(param1:String, param2:String)\n {\n super(DIALOG_COMPLETE);\n this.param1 = param1;\n this.param2 = param2;\n }\n}\n}\n</code></pre>\n\n<p>Waiting on an event is the best way to synchronize in Flex. It works well for startup dialogs too. In a flex-only application it works especially well.</p>\n" }, { "answer_id": 2771413, "author": "arvind", "author_id": 333188, "author_profile": "https://Stackoverflow.com/users/333188", "pm_score": 1, "selected": false, "text": "<p>I have explained a workaround to create synchronous alert in flex</p>\n\n<p><a href=\"http://reallypseudorandom.blogspot.com/2010/05/flash-asynchronous-alert-and-pause.html\" rel=\"nofollow noreferrer\">http://reallypseudorandom.blogspot.com/2010/05/flash-asynchronous-alert-and-pause.html</a></p>\n" } ]
2008/10/09
[ "https://Stackoverflow.com/questions/187851", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7524/" ]
How can I open a synchronous dialog in Flex? I need to call a function from an External Interface (JavaScript) that will open a simple dialog in the Flex application and returns an value according to the button the user has clicked (OK/Cancel). So it should by a synchronous call to a dialog, i.e. the call waits until the user has closed the dialog like this. ``` //This function is called by JavaScript function onApplicationUnload():Boolean { var result:Boolean; result = showDialogAndWaitForResult(); return result } ``` Does anybody know how I can do this? I could write a loop that waits until the dialog has set a flag and then reads the result to return it, but there must be something that is way more elegant and reusable for waiting of the completion of other asynchronous calls. **EDIT:** Unfortunately a callback does not work as the JavaScript function that calls onApplicationUnload() itself has to return a value (similar to the onApplicationUnload() function in Flex). This JavaScript function has a fixed signature as it is called by a framework and I cannot change it. Or in other words: The call from JavaScript to Flex must also be synchronous.
You can't do that in Flex. As David mentioned, Flex is single-threaded, so you can't have your function block while the dialog is being processed. Your best bet might be to use a Javascript popup. You'll have a lot less control over the window, but it should behave the way you want (blocking the function until it's been closed).
187,886
<p>I need to grant select permission for all tables owned by a specific user to another user. Can I do this with a single command along the lines of:</p> <pre><code>Grant Select on OwningUser.* to ReceivingUser </code></pre> <p>Or do I have to generate the sql for each table with something along the lines of:</p> <pre><code> Select 'GRANT SELECT ON OwningUser.'||Table_Name||'TO ReceivingUser' From All_Tables Where Owner='OWNINGUSER' </code></pre>
[ { "answer_id": 189496, "author": "DCookie", "author_id": 8670, "author_profile": "https://Stackoverflow.com/users/8670", "pm_score": 7, "selected": true, "text": "<p>Well, it's not a single statement, but it's about as close as you can get with oracle:</p>\n\n<pre><code>BEGIN\n FOR R IN (SELECT owner, table_name FROM all_tables WHERE owner='TheOwner') LOOP\n EXECUTE IMMEDIATE 'grant select on '||R.owner||'.'||R.table_name||' to TheUser';\n END LOOP;\nEND; \n</code></pre>\n" }, { "answer_id": 18511808, "author": "user2729366", "author_id": 2729366, "author_profile": "https://Stackoverflow.com/users/2729366", "pm_score": 2, "selected": false, "text": "<p>yes, its possible, run this command:</p>\n\n<p>lets say you have user called <code>thoko</code></p>\n\n<pre><code>grant select any table, insert any table, delete any table, update any table to thoko;\n</code></pre>\n\n<p>note: worked on oracle database</p>\n" }, { "answer_id": 39404932, "author": "dcvetkov", "author_id": 6812202, "author_profile": "https://Stackoverflow.com/users/6812202", "pm_score": 2, "selected": false, "text": "<p>tables + views + error reporting</p>\n\n<pre><code>SET SERVEROUT ON\nDECLARE\n o_type VARCHAR2(60) := '';\n o_name VARCHAR2(60) := '';\n o_owner VARCHAR2(60) := '';\n l_error_message VARCHAR2(500) := '';\nBEGIN\n FOR R IN (SELECT owner, object_type, object_name\n FROM all_objects \n WHERE owner='SCHEMANAME'\n AND object_type IN ('TABLE','VIEW')\n ORDER BY 1,2,3) LOOP\n BEGIN\n o_type := r.object_type;\n o_owner := r.owner;\n o_name := r.object_name;\n DBMS_OUTPUT.PUT_LINE(o_type||' '||o_owner||'.'||o_name);\n EXECUTE IMMEDIATE 'grant select on '||o_owner||'.'||o_name||' to USERNAME';\n EXCEPTION\n WHEN OTHERS THEN\n l_error_message := sqlerrm;\n DBMS_OUTPUT.PUT_LINE('Error with '||o_type||' '||o_owner||'.'||o_name||': '|| l_error_message);\n CONTINUE;\n END;\n END LOOP;\nEND;\n/\n</code></pre>\n" }, { "answer_id": 46579155, "author": "J. Chomel", "author_id": 6019417, "author_profile": "https://Stackoverflow.com/users/6019417", "pm_score": 0, "selected": false, "text": "<p>From <a href=\"http://psoug.org/reference/roles.html\" rel=\"nofollow noreferrer\">http://psoug.org/reference/roles.html</a>, create a procedure on your database for your user to do it:</p>\n\n<pre><code>CREATE OR REPLACE PROCEDURE GRANT_SELECT(to_user in varchar2) AS\n\n CURSOR ut_cur IS SELECT table_name FROM user_tables;\n\n RetVal NUMBER;\n sCursor INT;\n sqlstr VARCHAR2(250);\n\nBEGIN\n FOR ut_rec IN ut_cur\n LOOP\n sqlstr := 'GRANT SELECT ON '|| ut_rec.table_name || ' TO ' || to_user;\n sCursor := dbms_sql.open_cursor;\n dbms_sql.parse(sCursor,sqlstr, dbms_sql.native);\n RetVal := dbms_sql.execute(sCursor);\n dbms_sql.close_cursor(sCursor);\n\n END LOOP;\nEND grant_select;\n</code></pre>\n" } ]
2008/10/09
[ "https://Stackoverflow.com/questions/187886", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9940/" ]
I need to grant select permission for all tables owned by a specific user to another user. Can I do this with a single command along the lines of: ``` Grant Select on OwningUser.* to ReceivingUser ``` Or do I have to generate the sql for each table with something along the lines of: ``` Select 'GRANT SELECT ON OwningUser.'||Table_Name||'TO ReceivingUser' From All_Tables Where Owner='OWNINGUSER' ```
Well, it's not a single statement, but it's about as close as you can get with oracle: ``` BEGIN FOR R IN (SELECT owner, table_name FROM all_tables WHERE owner='TheOwner') LOOP EXECUTE IMMEDIATE 'grant select on '||R.owner||'.'||R.table_name||' to TheUser'; END LOOP; END; ```
187,893
<p>This is what I'd like to do, but it doesn't seem possible: (edit: changed single to double quotes)</p> <pre><code>function get_archives($limit, $offset) { $query = $this-&gt;db-&gt;query(" SELECT archivalie.id, archivalie.signature, type_of_source.description AS type_of_source_description, media_type.description AS media_type_description, origin.description AS origin_description FROM archivalie, type_of_source, media_type, origin WHERE archivalie.type_of_source_id = type_of_source.id AND type_of_source.media_type_id = media_type.id AND archivalie.origin_id = origin.id ORDER BY archivalie.id ASC LIMIT $limit, $offset "); // etc... } </code></pre> <p>It gives this error: (edit: new error message using double quotes, and with an offset number passed in the URL)</p> <pre><code>ERROR: LIMIT #,# syntax is not supported HINT: Use separate LIMIT and OFFSET clauses. </code></pre> <p>It only works if you pass the variables using the ActiveRecord format:</p> <pre><code>$this-&gt;db-&gt;select('archivalie.id, archivalie.signature, etc, etc'); // from, where, etc. $this-&gt;db-&gt;limit($limit, $offset); $query = $this-&gt;db-&gt;get(); </code></pre>
[ { "answer_id": 187904, "author": "Greg", "author_id": 24181, "author_profile": "https://Stackoverflow.com/users/24181", "pm_score": -1, "selected": false, "text": "<p>If you used double quotes instead of single quotes it would work, but you'd be open to an injection attack if the variables weren't sanitized properly.</p>\n" }, { "answer_id": 190539, "author": "meleyal", "author_id": 4196, "author_profile": "https://Stackoverflow.com/users/4196", "pm_score": 1, "selected": false, "text": "<p>This worked:</p>\n\n<pre><code>$query = $this-&gt;db-&gt;query(\"\n SELECT archivalie.id, \n archivalie.signature, \n type_of_source.description AS type_of_source_description, \n media_type.description AS media_type_description,\n origin.description AS origin_description\n\n FROM archivalie, \n type_of_source, \n media_type,\n origin\n\n WHERE archivalie.type_of_source_id = type_of_source.id \n AND type_of_source.media_type_id = media_type.id \n AND archivalie.origin_id = origin.id \n\n ORDER BY archivalie.id ASC\n LIMIT $limit\n OFFSET $offset\n\");\n</code></pre>\n\n<p>But it requires a check to assign a default value if no offset is present in the URL. From my controller:</p>\n\n<pre><code># Check/assign an offset\n$offset = (!$this-&gt;uri-&gt;segment(3)) ? 0 : $this-&gt;uri-&gt;segment(3);\n\n# Get the data\n$archives = $this-&gt;archive-&gt;get_archives($config['per_page'], $offset);\n</code></pre>\n" }, { "answer_id": 12884069, "author": "Angel Talavera", "author_id": 405164, "author_profile": "https://Stackoverflow.com/users/405164", "pm_score": 2, "selected": false, "text": "<pre><code>$query = $this-&gt;db-&gt;query('\nSELECT archivalie.id, \n archivalie.signature, \n type_of_source.description AS type_of_source_description, \n media_type.description AS media_type_description,\n origin.description AS origin_description\nFROM archivalie, \n type_of_source, \n media_type,\n origin\nWHERE archivalie.type_of_source_id = type_of_source.id \nAND type_of_source.media_type_id = media_type.id \nAND archivalie.origin_id = origin.id \nORDER BY archivalie.id ASC\nLIMIT ?\nOFFSET ?',array($limit,$offset));\n</code></pre>\n" }, { "answer_id": 41008420, "author": "Kinjal Dixit", "author_id": 6629, "author_profile": "https://Stackoverflow.com/users/6629", "pm_score": 0, "selected": false, "text": "<p>It has to do with the data type of the parameter. If you don't want Codeigniter to add the `'' single quotes, make sure you are passing an integer.</p>\n<pre><code>$page = '10'; // for some reason this arrives as a string\n$sql = &quot;select * from customers limit 10 offset ?&quot;;\n$result = $this-&gt;db-&gt;query($sql, array(intval($page));\n</code></pre>\n" } ]
2008/10/09
[ "https://Stackoverflow.com/questions/187893", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4196/" ]
This is what I'd like to do, but it doesn't seem possible: (edit: changed single to double quotes) ``` function get_archives($limit, $offset) { $query = $this->db->query(" SELECT archivalie.id, archivalie.signature, type_of_source.description AS type_of_source_description, media_type.description AS media_type_description, origin.description AS origin_description FROM archivalie, type_of_source, media_type, origin WHERE archivalie.type_of_source_id = type_of_source.id AND type_of_source.media_type_id = media_type.id AND archivalie.origin_id = origin.id ORDER BY archivalie.id ASC LIMIT $limit, $offset "); // etc... } ``` It gives this error: (edit: new error message using double quotes, and with an offset number passed in the URL) ``` ERROR: LIMIT #,# syntax is not supported HINT: Use separate LIMIT and OFFSET clauses. ``` It only works if you pass the variables using the ActiveRecord format: ``` $this->db->select('archivalie.id, archivalie.signature, etc, etc'); // from, where, etc. $this->db->limit($limit, $offset); $query = $this->db->get(); ```
``` $query = $this->db->query(' SELECT archivalie.id, archivalie.signature, type_of_source.description AS type_of_source_description, media_type.description AS media_type_description, origin.description AS origin_description FROM archivalie, type_of_source, media_type, origin WHERE archivalie.type_of_source_id = type_of_source.id AND type_of_source.media_type_id = media_type.id AND archivalie.origin_id = origin.id ORDER BY archivalie.id ASC LIMIT ? OFFSET ?',array($limit,$offset)); ```
187,894
<p>From C#, I want to do the equivalent of the following:</p> <pre><code>arp -a |findstr 192.168.1.254 </code></pre> <p>Alternatively, the answer could call the <a href="http://msdn.microsoft.com/en-us/library/aa366358.aspx" rel="noreferrer">SendARP</a> function and get the results.</p> <p>This will allow my application to do some other processing that requires the MAC address.</p>
[ { "answer_id": 187929, "author": "jop", "author_id": 11830, "author_profile": "https://Stackoverflow.com/users/11830", "pm_score": 6, "selected": true, "text": "<p>SendARP P/Invoke goes like this:</p>\n\n<pre><code>[DllImport(\"iphlpapi.dll\", ExactSpelling=true)]\npublic static extern int SendARP( int destIp, int srcIP, byte[] macAddr, ref uint physicalAddrLen );\n</code></pre>\n\n<p><a href=\"http://www.pinvoke.net/default.aspx/iphlpapi/SendARP.html\" rel=\"noreferrer\">PInvoke.NET</a> has this example:</p>\n\n<pre><code>IPAddress dst = IPAddress.Parse(\"192.168.2.1\"); // the destination IP address\n\nbyte[] macAddr = new byte[6];\nuint macAddrLen = (uint)macAddr.Length;\n\nif (SendARP(BitConverter.ToInt32(dst.GetAddressBytes(), 0), 0, macAddr, ref macAddrLen) != 0)\n throw new InvalidOperationException(\"SendARP failed.\");\n\nstring[] str = new string[(int)macAddrLen];\nfor (int i=0; i&lt;macAddrLen; i++)\n str[i] = macAddr[i].ToString(\"x2\");\n\nConsole.WriteLine(string.Join(\":\", str));\n</code></pre>\n" }, { "answer_id": 187945, "author": "bugmagnet", "author_id": 426, "author_profile": "https://Stackoverflow.com/users/426", "pm_score": 1, "selected": false, "text": "<p>Hook into the WMI subsystem. Some VBScript code to get going in the right direction is <a href=\"http://www.microsoft.com/technet/scriptcenter/resources/qanda/jun05/hey0614.mspx\" rel=\"nofollow noreferrer\">here</a></p>\n" }, { "answer_id": 187972, "author": "Douglas Anderson", "author_id": 5678, "author_profile": "https://Stackoverflow.com/users/5678", "pm_score": 1, "selected": false, "text": "<p>To find your own:</p>\n\n<p>Add a reference to System.Management</p>\n\n<pre><code>ManagementClass mc = new ManagementClass(\"Win32_NetworkAdapterConfiguration\");\n\nManagementObjectCollection mcCol = mc.GetInstances();\n\nforeach (ManagementObject mcObj in mcCol)\n{\n Console.WriteLine(mcObj[\"Caption\"].ToString());\n Console.WriteLine(mcObj[\"MacAddress\"].ToString());\n}\n</code></pre>\n\n<p>Not sure about finding that of another device.</p>\n" }, { "answer_id": 37155004, "author": "Dominic Jonas", "author_id": 6229375, "author_profile": "https://Stackoverflow.com/users/6229375", "pm_score": 2, "selected": false, "text": "<p>Here is my solution.</p>\n\n<pre><code>public static class MacResolver\n{\n /// &lt;summary&gt;\n /// Convert a string into Int32 \n /// &lt;/summary&gt;\n [DllImport(\"Ws2_32.dll\")]\n private static extern Int32 inet_addr(string ip);\n\n /// &lt;summary&gt;\n /// The main funtion \n /// &lt;/summary&gt; \n [DllImport(\"Iphlpapi.dll\")]\n private static extern int SendARP(Int32 dest, Int32 host, ref Int64 mac, ref Int32 len);\n\n /// &lt;summary&gt;\n /// Returns the MACAddress by a string.\n /// &lt;/summary&gt;\n public static Int64 GetRemoteMAC(string remoteIP)\n { \n Int32 ldest = inet_addr(remoteIP);\n\n try\n {\n Int64 macinfo = 0; \n Int32 len = 6; \n\n int res = SendARP(ldest, 0, ref macinfo, ref len);\n\n return macinfo; \n }\n catch (Exception e)\n {\n return 0;\n }\n }\n\n /// &lt;summary&gt;\n /// Format a long/Int64 into string. \n /// &lt;/summary&gt;\n public static string FormatMac(this Int64 mac, char separator)\n {\n if (mac &lt;= 0)\n return \"00-00-00-00-00-00\";\n\n char[] oldmac = Convert.ToString(mac, 16).PadLeft(12, '0').ToCharArray();\n\n System.Text.StringBuilder newMac = new System.Text.StringBuilder(17);\n\n if (oldmac.Length &lt; 12)\n return \"00-00-00-00-00-00\";\n\n newMac.Append(oldmac[10]);\n newMac.Append(oldmac[11]);\n newMac.Append(separator);\n newMac.Append(oldmac[8]);\n newMac.Append(oldmac[9]);\n newMac.Append(separator);\n newMac.Append(oldmac[6]);\n newMac.Append(oldmac[7]);\n newMac.Append(separator);\n newMac.Append(oldmac[4]);\n newMac.Append(oldmac[5]);\n newMac.Append(separator);\n newMac.Append(oldmac[2]);\n newMac.Append(oldmac[3]);\n newMac.Append(separator);\n newMac.Append(oldmac[0]);\n newMac.Append(oldmac[1]);\n\n return newMac.ToString();\n }\n}\n</code></pre>\n" } ]
2008/10/09
[ "https://Stackoverflow.com/questions/187894", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5993/" ]
From C#, I want to do the equivalent of the following: ``` arp -a |findstr 192.168.1.254 ``` Alternatively, the answer could call the [SendARP](http://msdn.microsoft.com/en-us/library/aa366358.aspx) function and get the results. This will allow my application to do some other processing that requires the MAC address.
SendARP P/Invoke goes like this: ``` [DllImport("iphlpapi.dll", ExactSpelling=true)] public static extern int SendARP( int destIp, int srcIP, byte[] macAddr, ref uint physicalAddrLen ); ``` [PInvoke.NET](http://www.pinvoke.net/default.aspx/iphlpapi/SendARP.html) has this example: ``` IPAddress dst = IPAddress.Parse("192.168.2.1"); // the destination IP address byte[] macAddr = new byte[6]; uint macAddrLen = (uint)macAddr.Length; if (SendARP(BitConverter.ToInt32(dst.GetAddressBytes(), 0), 0, macAddr, ref macAddrLen) != 0) throw new InvalidOperationException("SendARP failed."); string[] str = new string[(int)macAddrLen]; for (int i=0; i<macAddrLen; i++) str[i] = macAddr[i].ToString("x2"); Console.WriteLine(string.Join(":", str)); ```
187,913
<p>What I'd like to avoid: </p> <pre><code>ManagementClass m = new ManagementClass("Win32_LogicalDisk"); ManagementObjectCollection managementObjects = m.GetInstances(); List&lt;ManagementObject&gt; managementList = new List&lt;ManagementObject&gt;(); foreach(ManagementObject m in managementObjects){ managementList.Add(m); } </code></pre> <p>Isn't there a way to get that collection into a List that looks something like: </p> <pre><code>List&lt;ManagementObject&gt; managementList = new List&lt;ManagementObjec&gt;(collection_array); </code></pre>
[ { "answer_id": 187922, "author": "steffenj", "author_id": 15328, "author_profile": "https://Stackoverflow.com/users/15328", "pm_score": 1, "selected": false, "text": "<p>You could try:</p>\n\n<pre><code>List&lt;ManagementObject&gt; managementList = new List&lt;ManagementObject&gt;(managementObjects.ToArray());\n</code></pre>\n\n<p>Not sure if .ToArray() is available for the collection.\nIf you do use the code you posted, make sure you initialize the List with the number of existing elements:</p>\n\n<pre><code>List&lt;ManagementObject&gt; managementList = new List&lt;ManagementObject&gt;(managementObjects.Count); // or .Length\n</code></pre>\n" }, { "answer_id": 187923, "author": "Marc Gravell", "author_id": 23354, "author_profile": "https://Stackoverflow.com/users/23354", "pm_score": 8, "selected": true, "text": "<p>What version of the framework? With 3.5 you could presumably use:</p>\n\n<pre><code>List&lt;ManagementObject&gt; managementList = managementObjects.Cast&lt;ManagementObject&gt;().ToList();\n</code></pre>\n\n<p>(edited to remove simpler version; I checked and <code>ManagementObjectCollection</code> only implements the non-generic <code>IEnumerable</code> form)</p>\n" }, { "answer_id": 187957, "author": "MagicKat", "author_id": 8505, "author_profile": "https://Stackoverflow.com/users/8505", "pm_score": 0, "selected": false, "text": "<p>As long as ManagementObjectCollection implements IEnumerable&lt;ManagementObject&gt; you can do:</p>\n\n<pre><code>List&lt;ManagementObject&gt; managementList = new List&lt;ManagementObjec&gt;(managementObjects);\n</code></pre>\n\n<p>If it doesn't, then you are stuck doing it the way that you are doing it.</p>\n" }, { "answer_id": 187967, "author": "mancaus", "author_id": 13797, "author_profile": "https://Stackoverflow.com/users/13797", "pm_score": 2, "selected": false, "text": "<p><code>managementObjects.Cast&lt;ManagementBaseObject&gt;().ToList();</code> is a good choice.</p>\n\n<p>You could improve performance by pre-initialising the list capacity:</p>\n\n<pre><code>\n public static class Helpers\n {\n public static List&lt;T&gt; CollectionToList&lt;T&gt;(this System.Collections.ICollection other)\n {\n var output = new List&lt;T&gt;(other.Count);\n\n output.AddRange(other.Cast&lt;T&gt;());\n\n return output;\n }\n }\n</code></pre>\n" }, { "answer_id": 649425, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": -1, "selected": false, "text": "<p>you can convert like below code snippet</p>\n\n<pre><code>Collection&lt;A&gt; obj=new Collection&lt;return ListRetunAPI()&gt;\n</code></pre>\n" }, { "answer_id": 12517929, "author": "stoto", "author_id": 81641, "author_profile": "https://Stackoverflow.com/users/81641", "pm_score": 2, "selected": false, "text": "<p>Since 3.5, anything inherited from System.Collection.IEnumerable has the convenient extension method OfType available.</p>\n\n<p>If your collection is from ICollection or IEnumerable, you can just do this:</p>\n\n<pre><code>List&lt;ManagementObject&gt; managementList = ManagementObjectCollection.OfType&lt;ManagementObject&gt;().ToList();\n</code></pre>\n\n<p>Can't find any way simpler. : )</p>\n" }, { "answer_id": 31767807, "author": "jacobsgriffith", "author_id": 941632, "author_profile": "https://Stackoverflow.com/users/941632", "pm_score": 5, "selected": false, "text": "<p>You could use</p>\n\n<pre><code>using System.Linq;\n</code></pre>\n\n<p>That will give you a ToList&lt;> extension method for ICollection&lt;></p>\n" } ]
2008/10/09
[ "https://Stackoverflow.com/questions/187913", "https://Stackoverflow.com", "https://Stackoverflow.com/users/64/" ]
What I'd like to avoid: ``` ManagementClass m = new ManagementClass("Win32_LogicalDisk"); ManagementObjectCollection managementObjects = m.GetInstances(); List<ManagementObject> managementList = new List<ManagementObject>(); foreach(ManagementObject m in managementObjects){ managementList.Add(m); } ``` Isn't there a way to get that collection into a List that looks something like: ``` List<ManagementObject> managementList = new List<ManagementObjec>(collection_array); ```
What version of the framework? With 3.5 you could presumably use: ``` List<ManagementObject> managementList = managementObjects.Cast<ManagementObject>().ToList(); ``` (edited to remove simpler version; I checked and `ManagementObjectCollection` only implements the non-generic `IEnumerable` form)
187,920
<p>I'm logged into a SQL Server 2005 database as a non-sa user, 'bhk', that is a member of the 'public' server role only. The following code tries to execute within a stored procedure called by user 'bhk'. This line of code...</p> <pre><code>TRUNCATE TABLE #Table1 DBCC CHECKIDENT('#Table1', RESEED, @SequenceNumber) WITH NO_INFOMSGS </code></pre> <p>causes this error...</p> <blockquote> <p>User 'guest' does not have permission to run DBCC CHECKIDENT for object<br> '#Table1__00000000007F'.</p> </blockquote> <p>I'm aware of the permissions required to run DBCC CHECKIDENT...<br> <strong><em>Caller must own the table</strong>, or be a member of the sysadmin fixed server role, the db_owner fixed database role, or the db_ddladmin fixed database role.</em></p> <p>So I have two questions:</p> <ol> <li>Since 'bhk' is calling a stored procedure that creates a temporary table, shouldn't 'bhk' be the owner and be allowed to run DBCC CHECKIDENT?</li> <li>Why does the error message return that user 'guest' doesn't have permission? To my knowledge, I'm not logged in as 'guest'.</li> </ol> <p>Any help would be greatly appreciated.</p>
[ { "answer_id": 194185, "author": "splattne", "author_id": 6461, "author_profile": "https://Stackoverflow.com/users/6461", "pm_score": 2, "selected": false, "text": "<p>You wrote:</p>\n\n<blockquote>\n <p>\"Caller must own the table, or be a\n member of the sysadmin fixed server\n role, the db_owner fixed.\"</p>\n</blockquote>\n\n<p>So (if it's not a bug), according to <a href=\"http://en.wikipedia.org/wiki/Columbo\" rel=\"nofollow noreferrer\">Lieutenant Columbo's</a> impeccable logic, each of the premisses must be false. That means, <strong>the caller does not own the table,</strong> even if he created it.</p>\n\n<p>In fact, it seems that all objects created in tempd <strong>are owned by dbo</strong> by default. You can examine it, if you do following in Query Analyzer:</p>\n\n<ol>\n<li>Connect to <em>your database</em> using the low-permission user.</li>\n<li>Execute: <code>CREATE TABLE #NotMyTable (TestID int identity)</code></li>\n<li>Connect to <em>tempdb</em> of the same SQL Server <strong>as dbo</strong> </li>\n<li>Execute: <code>SELECT user_name(uid) FROM sysobjects WHERE name LIKE '#NotMyTable%'</code> </li>\n</ol>\n\n<p>You'll see that dbo is the owner of the temporary table.</p>\n\n<p><strong>So, what could be a solution?</strong></p>\n\n<p>(Foreword: <em>I don't like that kind of manipulation, but the intellectual stimulus is driving me... ;-)</em> )</p>\n\n<p>So, you could write another stored procedure which updates the UID in sysobjects of the tempdb to the value of your user (<em>shiver!</em>). I tested it only in Query Analyzer. After the Update I could execute your DBCC CHECKIDENT command.</p>\n" }, { "answer_id": 197069, "author": "Tim C", "author_id": 7585, "author_profile": "https://Stackoverflow.com/users/7585", "pm_score": 1, "selected": false, "text": "<p>An alternate solution to doing the TRUNCATE and CHECKIDENT commands would be to simply drop and re-create your temporary table. E.g.</p>\n\n<pre><code>DROP TABLE #Table1\n\nCREATE TABLE #Table1\n(\n ....\n)\n</code></pre>\n\n<p>This may not be the most efficient solution though.</p>\n" }, { "answer_id": 198027, "author": "Tim C", "author_id": 7585, "author_profile": "https://Stackoverflow.com/users/7585", "pm_score": 4, "selected": true, "text": "<p>Here is an alternate solution, that may work if you need to re-seed with a sequence number of more than 1.</p>\n\n<pre><code>TRUNCATE #Table1\n\nSET IDENTITY_INSERT #Table1 ON\n\nINSERT INTO #Table1 (TableID) -- This is your primary key field\nVALUES (@SequenceNumber - 1)\n\nSET IDENTITY_INSERT #Table1 OFF\n\nDELETE FROM #Table1\n</code></pre>\n\n<p>What this is doing is to set the IDENTITY_INSERT on your temporary table, to allow you to add a row with an explicit ID. You can then delete this row, but further inserts should start from the last sequence number.</p>\n" }, { "answer_id": 4935938, "author": "Bob", "author_id": 608486, "author_profile": "https://Stackoverflow.com/users/608486", "pm_score": 2, "selected": false, "text": "<p>You can accomplish this by fully qualifying the tempdb table. </p>\n\n<pre><code>DBCC CHECKIDENT([tempdb..#Table1], RESEED, @SequenceNumber) WITH NO_INFOMSGS\n</code></pre>\n" }, { "answer_id": 10386179, "author": "John Christensen", "author_id": 1194, "author_profile": "https://Stackoverflow.com/users/1194", "pm_score": 1, "selected": false, "text": "<p>I just ran into this. The answer I came to was to give the relevant account the permissions in the tempdb database where, apparantly, these tables were created.</p>\n" } ]
2008/10/09
[ "https://Stackoverflow.com/questions/187920", "https://Stackoverflow.com", "https://Stackoverflow.com/users/14360/" ]
I'm logged into a SQL Server 2005 database as a non-sa user, 'bhk', that is a member of the 'public' server role only. The following code tries to execute within a stored procedure called by user 'bhk'. This line of code... ``` TRUNCATE TABLE #Table1 DBCC CHECKIDENT('#Table1', RESEED, @SequenceNumber) WITH NO_INFOMSGS ``` causes this error... > > User 'guest' does not have permission > to run DBCC CHECKIDENT for object > > '#Table1\_\_00000000007F'. > > > I'm aware of the permissions required to run DBCC CHECKIDENT... ***Caller must own the table***, or be a member of the sysadmin fixed server role, the db\_owner fixed database role, or the db\_ddladmin fixed database role. So I have two questions: 1. Since 'bhk' is calling a stored procedure that creates a temporary table, shouldn't 'bhk' be the owner and be allowed to run DBCC CHECKIDENT? 2. Why does the error message return that user 'guest' doesn't have permission? To my knowledge, I'm not logged in as 'guest'. Any help would be greatly appreciated.
Here is an alternate solution, that may work if you need to re-seed with a sequence number of more than 1. ``` TRUNCATE #Table1 SET IDENTITY_INSERT #Table1 ON INSERT INTO #Table1 (TableID) -- This is your primary key field VALUES (@SequenceNumber - 1) SET IDENTITY_INSERT #Table1 OFF DELETE FROM #Table1 ``` What this is doing is to set the IDENTITY\_INSERT on your temporary table, to allow you to add a row with an explicit ID. You can then delete this row, but further inserts should start from the last sequence number.
187,974
<p>I have a simple Word to Pdf converter as an MSBuild Task. The task takes Word files (ITaskItems) as input and Pdf files (ITaskItems) as output. The script uses a Target transform for conversion:</p> <pre><code>&lt;Project DefaultTargets="Build" xmlns="http://schemas.microsoft.com/developer/msbuild/2003" ToolsVersion="3.5"&gt; &lt;UsingTask AssemblyFile="$(MSBuildExtensionsPath)\MyTasks.dll" TaskName="MyTasks.DocToPdf" /&gt; &lt;Target Name="Build" DependsOnTargets="Convert" /&gt; &lt;Target Name="Convert" Inputs="@(WordDocuments)" Outputs="@(WordDocuments-&gt;'%(FileName).pdf')"&gt; &lt;DocToPdf Inputs="@(WordDocuments)" Outputs="%(FileName).pdf"&gt; &lt;Output TaskParameter="ConvertedFiles" ItemName="PdfDocuments" /&gt; &lt;/DocToPdf&gt; &lt;/Target&gt; &lt;ItemGroup&gt; &lt;WordDocuments Include="One.doc" /&gt; &lt;WordDocuments Include="SubDir\Two.doc" /&gt; &lt;WordDocuments Include="**\*.doc" /&gt; &lt;/ItemGroup&gt; &lt;/Project&gt; </code></pre> <p>What's happening is that SubDir\Two.doc gets converted on every incremental build, One.doc does not (ie MSBuild correctly skips that file because it was already converted). If I use the recursive items spec (the third one above), I get the same behaviour (ie. One.doc only gets converted if the PDF is out of date or missing, but all documents in subdirectories always get converted regardless).</p> <p>What am I doing wrong here?</p>
[ { "answer_id": 188060, "author": "lesscode", "author_id": 18482, "author_profile": "https://Stackoverflow.com/users/18482", "pm_score": 3, "selected": true, "text": "<p>I found the problem. It turns out that I had some logic in the Task that would turn any relative path specified for a PDF file into an absolute path. Once I removed that and changed the script to this:</p>\n\n<pre><code> &lt;Target Name=\"Convert\"\n Inputs=\"@(WordDocuments)\"\n Outputs=\"@(WordDocuments-&gt;'%(RelativeDir)%(FileName).pdf')\"&gt;\n &lt;DocToPdf Inputs=\"%(WordDocuments.Identity)\"\n Outputs=\"%(RelativeDir)%(FileName).pdf\"&gt;\n &lt;Output TaskParameter=\"ConvertedFiles\" ItemName=\"PdfDocuments\" /&gt;\n &lt;/DocToPdf&gt;\n &lt;/Target&gt;\n</code></pre>\n\n<p>I got the behaviour I expected.</p>\n" }, { "answer_id": 193205, "author": "Adam", "author_id": 1341, "author_profile": "https://Stackoverflow.com/users/1341", "pm_score": 0, "selected": false, "text": "<p>Here's my example of a task that performs incremental builds on items found recursively through subdirectories:</p>\n\n<pre><code> &lt;Target Name=\"Build\" Inputs=\"@(RequestTextFiles)\" Outputs=\"@(RequestTextFiles -&gt; '%(Rootdir)%(Directory)%(Filename).out')\"&gt;\n\n &lt;DoSomething SourceFiles=\"@(RequestTextFiles)\" /&gt;\n\n &lt;/Target&gt;\n</code></pre>\n\n<p>This maps 1:1 with an input file, and an output file with the same name, that outputs to the same path with a different extension, namely 'out' in this case.</p>\n" } ]
2008/10/09
[ "https://Stackoverflow.com/questions/187974", "https://Stackoverflow.com", "https://Stackoverflow.com/users/18482/" ]
I have a simple Word to Pdf converter as an MSBuild Task. The task takes Word files (ITaskItems) as input and Pdf files (ITaskItems) as output. The script uses a Target transform for conversion: ``` <Project DefaultTargets="Build" xmlns="http://schemas.microsoft.com/developer/msbuild/2003" ToolsVersion="3.5"> <UsingTask AssemblyFile="$(MSBuildExtensionsPath)\MyTasks.dll" TaskName="MyTasks.DocToPdf" /> <Target Name="Build" DependsOnTargets="Convert" /> <Target Name="Convert" Inputs="@(WordDocuments)" Outputs="@(WordDocuments->'%(FileName).pdf')"> <DocToPdf Inputs="@(WordDocuments)" Outputs="%(FileName).pdf"> <Output TaskParameter="ConvertedFiles" ItemName="PdfDocuments" /> </DocToPdf> </Target> <ItemGroup> <WordDocuments Include="One.doc" /> <WordDocuments Include="SubDir\Two.doc" /> <WordDocuments Include="**\*.doc" /> </ItemGroup> </Project> ``` What's happening is that SubDir\Two.doc gets converted on every incremental build, One.doc does not (ie MSBuild correctly skips that file because it was already converted). If I use the recursive items spec (the third one above), I get the same behaviour (ie. One.doc only gets converted if the PDF is out of date or missing, but all documents in subdirectories always get converted regardless). What am I doing wrong here?
I found the problem. It turns out that I had some logic in the Task that would turn any relative path specified for a PDF file into an absolute path. Once I removed that and changed the script to this: ``` <Target Name="Convert" Inputs="@(WordDocuments)" Outputs="@(WordDocuments->'%(RelativeDir)%(FileName).pdf')"> <DocToPdf Inputs="%(WordDocuments.Identity)" Outputs="%(RelativeDir)%(FileName).pdf"> <Output TaskParameter="ConvertedFiles" ItemName="PdfDocuments" /> </DocToPdf> </Target> ``` I got the behaviour I expected.
187,981
<p>I have the following regular expression : I figured out most of the part which is as follows :</p> <pre> ValidationExpression="^[\u0020\u0027\u002C\u002D\u0030-\u0039\u0041-\u005A\u005F\u0061-\u007A\u00C0-\u00FF°&#46;/]{1,256}$" u0020 : SPACE u0027 : APOSTROPHE u002C : COMMA u002D : HYPHEN / MINUS u0030-\u0039\ : 0-9 u0041-\u005A : A - Z u005F : UNDERSCORE u0061-\u007A\ : a - z u00C0-\u00FF°&#46;/ : ?? </pre> <p>Need help in understanding the final part of the validation expression : </p> <pre>u00C0-\u00FF°&#46;/</pre> <p>Anyone has any idea what does this mean?</p>
[ { "answer_id": 188003, "author": "Robert K", "author_id": 24950, "author_profile": "https://Stackoverflow.com/users/24950", "pm_score": 2, "selected": false, "text": "<p>\\u00C0 - \\u00FF are letters with accents on them, though that isn't all of them. And \"°\" is just the degree character. However, \"./\" should probably be \"\\.\" to permit period characters.</p>\n" }, { "answer_id": 188022, "author": "Luk", "author_id": 5789, "author_profile": "https://Stackoverflow.com/users/5789", "pm_score": 3, "selected": true, "text": "<p>weird... according to the character map on Windows I'd say \"À to ÿ\"</p>\n\n<p>Those are some variations (accents, cedillas) on A, C, E, I, D, N, O, U, Y, the german Sharp s, ...</p>\n" }, { "answer_id": 188029, "author": "Vinko Vrsalovic", "author_id": 5190, "author_profile": "https://Stackoverflow.com/users/5190", "pm_score": 1, "selected": false, "text": "<p>Your question is mistitled, you want help with <a href=\"http://wikipedia.org/wiki/Unicode\" rel=\"nofollow noreferrer\">Unicode</a> <a href=\"http://wikipedia.org/wiki/Code_point\" rel=\"nofollow noreferrer\">codepoints</a>. You can check them, for instance, <a href=\"http://namidst.com/stuff/unidata/\" rel=\"nofollow noreferrer\">here</a>.</p>\n\n<p>They are the second half of Latin1 Supplement, including accentuated vocals and some other characters. See the above links.</p>\n" }, { "answer_id": 188048, "author": "Brad Knowles", "author_id": 14360, "author_profile": "https://Stackoverflow.com/users/14360", "pm_score": -1, "selected": false, "text": "<p>It looks to be the range of characters presented in the last 2 columns in TABLE ASCII-II at the following link to <a href=\"http://www.cdrummond.qc.ca/cegep/informat/Professeurs/Alain/files/ascii.htm\" rel=\"nofollow noreferrer\">The Extended ASCII Chart</a></p>\n" }, { "answer_id": 188202, "author": "John Nilsson", "author_id": 24243, "author_profile": "https://Stackoverflow.com/users/24243", "pm_score": 0, "selected": false, "text": "<p>Using <a href=\"http://rishida.net/scripts/uniview/conversion.php\" rel=\"nofollow noreferrer\">http://rishida.net/scripts/uniview/conversion.php</a>\nI got: ',-0-9A-Z_a-zÀ-ÿ</p>\n" }, { "answer_id": 49766641, "author": "Roland Illig", "author_id": 225757, "author_profile": "https://Stackoverflow.com/users/225757", "pm_score": 0, "selected": false, "text": "<p>Your result of splitting the original string looks weird, as if you hadn't understood what a Unicode escape sequence is. It should rather look like:</p>\n\n<pre><code>\\u0020\n\\u0027\n\\u002C\n\\u002D\n\\u0030-\\u0039\n\\u0041-\\u005A\n\\u005F\n\\u0061-\\u007A\n\\u00C0-\\u00FF\n°\n.\n/\n</code></pre>\n\n<p>You can look up the meaning of these code points at the Unicode web site:</p>\n\n<ul>\n<li><a href=\"https://www.unicode.org/charts/PDF/U0000.pdf\" rel=\"nofollow noreferrer\">https://www.unicode.org/charts/PDF/U0000.pdf</a> (Basic Latin)</li>\n<li><a href=\"https://www.unicode.org/charts/PDF/U0080.pdf\" rel=\"nofollow noreferrer\">https://www.unicode.org/charts/PDF/U0080.pdf</a> (Latin-1 Supplement)</li>\n<li><a href=\"https://www.unicode.org/charts/PDF/U1F600.pdf\" rel=\"nofollow noreferrer\">https://www.unicode.org/charts/PDF/U1F600.pdf</a> (Emoticons)</li>\n</ul>\n\n<p>The last three characters mean exactly what is written:</p>\n\n<ul>\n<li>degree sign</li>\n<li>dot/period/full stop</li>\n<li>forward slash</li>\n</ul>\n" } ]
2008/10/09
[ "https://Stackoverflow.com/questions/187981", "https://Stackoverflow.com", "https://Stackoverflow.com/users/24958/" ]
I have the following regular expression : I figured out most of the part which is as follows : ``` ValidationExpression="^[\u0020\u0027\u002C\u002D\u0030-\u0039\u0041-\u005A\u005F\u0061-\u007A\u00C0-\u00FF°./]{1,256}$" u0020 : SPACE u0027 : APOSTROPHE u002C : COMMA u002D : HYPHEN / MINUS u0030-\u0039\ : 0-9 u0041-\u005A : A - Z u005F : UNDERSCORE u0061-\u007A\ : a - z u00C0-\u00FF°./ : ?? ``` Need help in understanding the final part of the validation expression : ``` u00C0-\u00FF°./ ``` Anyone has any idea what does this mean?
weird... according to the character map on Windows I'd say "À to ÿ" Those are some variations (accents, cedillas) on A, C, E, I, D, N, O, U, Y, the german Sharp s, ...
187,987
<p>I was wondering if this seemed to familiar to any experience NHibernate developers or if someone could give me an idea as to where to start to try and resolve this issue:</p> <p>I inherited an NHibernate site written in ASP.NET 1.1 using NHibernate 0.6 and .NET remoting to the DAL layer residing on the database server. I have been trying to upgrade it to ASP.NET 3.5 and NHibernate 1.2.1.4. </p> <p>I replaced the .NET remoting setup with a direct database connection and everything works fine until the site gets under some load and then NHibernate calls start to intermittently fail throwing an exception: ADOException could not execute query followed by the NHibernate generated SQL statements.</p> <p>The stack trace given with the error is:</p> <pre><code>NHibernate.Loader.Loader.LoadEntity(ISessionImplementor session, Object id, IType identifierType, Object optionalObject, Type optionalEntityName, Object optionalIdentifier, IEntityPersister persister) at NHibernate.Loader.Entity.AbstractEntityLoader.Load(ISessionImplementor session, Object id, Object optionalObject, Object optionalId) at NHibernate.Loader.Entity.AbstractEntityLoader.Load(Object id, Object optionalObject, ISessionImplementor session) at NHibernate.Persister.Entity.AbstractEntityPersister.Load(Object id, Object optionalObject, LockMode lockMode, ISessionImplementor session) at NHibernate.Impl.SessionImpl.DoLoad(Type theClass, Object id, Object optionalObject, LockMode lockMode, Boolean checkDeleted) at NHibernate.Impl.SessionImpl.DoLoadByClass(Type clazz, Object id, Boolean checkDeleted, Boolean allowProxyCreation) at NHibernate.Impl.SessionImpl.Load(Type clazz, Object id) </code></pre>
[ { "answer_id": 188026, "author": "mspmsp", "author_id": 21724, "author_profile": "https://Stackoverflow.com/users/21724", "pm_score": 1, "selected": false, "text": "<ul>\n<li>verify your connection settings.</li>\n<li>if you can, cache objects as much as you can to avoid battering the server</li>\n<li>make sure you've got your tables indexed...that's a huge one</li>\n<li>make sure log4net's logging is turned to warn/error so you're not writing an encyclopedia to the logs</li>\n</ul>\n" }, { "answer_id": 191278, "author": "CtrAltDel", "author_id": 26550, "author_profile": "https://Stackoverflow.com/users/26550", "pm_score": 2, "selected": false, "text": "<p>Problem was non thread-safe nhibernate session factory. Changed project to use an http module to use one nhibernate session per request (and made sure not to open a session for rquests on non .as*x files) and all is well.</p>\n" } ]
2008/10/09
[ "https://Stackoverflow.com/questions/187987", "https://Stackoverflow.com", "https://Stackoverflow.com/users/26550/" ]
I was wondering if this seemed to familiar to any experience NHibernate developers or if someone could give me an idea as to where to start to try and resolve this issue: I inherited an NHibernate site written in ASP.NET 1.1 using NHibernate 0.6 and .NET remoting to the DAL layer residing on the database server. I have been trying to upgrade it to ASP.NET 3.5 and NHibernate 1.2.1.4. I replaced the .NET remoting setup with a direct database connection and everything works fine until the site gets under some load and then NHibernate calls start to intermittently fail throwing an exception: ADOException could not execute query followed by the NHibernate generated SQL statements. The stack trace given with the error is: ``` NHibernate.Loader.Loader.LoadEntity(ISessionImplementor session, Object id, IType identifierType, Object optionalObject, Type optionalEntityName, Object optionalIdentifier, IEntityPersister persister) at NHibernate.Loader.Entity.AbstractEntityLoader.Load(ISessionImplementor session, Object id, Object optionalObject, Object optionalId) at NHibernate.Loader.Entity.AbstractEntityLoader.Load(Object id, Object optionalObject, ISessionImplementor session) at NHibernate.Persister.Entity.AbstractEntityPersister.Load(Object id, Object optionalObject, LockMode lockMode, ISessionImplementor session) at NHibernate.Impl.SessionImpl.DoLoad(Type theClass, Object id, Object optionalObject, LockMode lockMode, Boolean checkDeleted) at NHibernate.Impl.SessionImpl.DoLoadByClass(Type clazz, Object id, Boolean checkDeleted, Boolean allowProxyCreation) at NHibernate.Impl.SessionImpl.Load(Type clazz, Object id) ```
Problem was non thread-safe nhibernate session factory. Changed project to use an http module to use one nhibernate session per request (and made sure not to open a session for rquests on non .as\*x files) and all is well.
187,998
<p>Is there any way in SQL Server to get the results starting at a given offset? For example, in another type of SQL database, it's possible to do:</p> <pre><code>SELECT * FROM MyTable OFFSET 50 LIMIT 25 </code></pre> <p>to get results 51-75. This construct does not appear to exist in SQL Server. </p> <p>How can I accomplish this without loading all the rows I don't care about? Thanks! </p>
[ { "answer_id": 188031, "author": "Unsliced", "author_id": 2902, "author_profile": "https://Stackoverflow.com/users/2902", "pm_score": 2, "selected": false, "text": "<p>Depending on your version ou cannot do it directly, but you could do something hacky like</p>\n\n<pre><code>select top 25 *\nfrom ( \n select top 75 *\n from table \n order by field asc\n) a \norder by field desc \n</code></pre>\n\n<p>where 'field' is the key. </p>\n" }, { "answer_id": 188040, "author": "leoinfo", "author_id": 6948, "author_profile": "https://Stackoverflow.com/users/6948", "pm_score": 5, "selected": false, "text": "<p>This is one way (SQL2000)</p>\n\n<pre><code>SELECT * FROM\n(\n SELECT TOP (@pageSize) * FROM\n (\n SELECT TOP (@pageNumber * @pageSize) *\n FROM tableName \n ORDER BY columnName ASC\n ) AS t1 \n ORDER BY columnName DESC\n) AS t2 \nORDER BY columnName ASC\n</code></pre>\n\n<p>and this is another way (SQL 2005)</p>\n\n<pre><code>;WITH results AS (\n SELECT \n rowNo = ROW_NUMBER() OVER( ORDER BY columnName ASC )\n , *\n FROM tableName \n) \nSELECT * \nFROM results\nWHERE rowNo between (@pageNumber-1)*@pageSize+1 and @pageNumber*@pageSize\n</code></pre>\n" }, { "answer_id": 188044, "author": "Brian Kim", "author_id": 5704, "author_profile": "https://Stackoverflow.com/users/5704", "pm_score": 8, "selected": true, "text": "<p>I would avoid using <code>SELECT *</code>. Specify columns you actually want even though it may be all of them.</p>\n\n<p><strong>SQL Server 2005+</strong></p>\n\n<pre><code>SELECT col1, col2 \nFROM (\n SELECT col1, col2, ROW_NUMBER() OVER (ORDER BY ID) AS RowNum\n FROM MyTable\n) AS MyDerivedTable\nWHERE MyDerivedTable.RowNum BETWEEN @startRow AND @endRow\n</code></pre>\n\n<p><strong>SQL Server 2000</strong></p>\n\n<p><a href=\"https://web.archive.org/web/20210506081930/http://www.4guysfromrolla.com/webtech/041206-1.shtml\" rel=\"noreferrer\">Efficiently Paging Through Large Result Sets in SQL Server 2000</a></p>\n\n<p><a href=\"https://web.archive.org/web/20211020131201/https://www.4guysfromrolla.com/webtech/042606-1.shtml\" rel=\"noreferrer\">A More Efficient Method for Paging Through Large Result Sets</a></p>\n" }, { "answer_id": 188053, "author": "Matthias Meid", "author_id": 17713, "author_profile": "https://Stackoverflow.com/users/17713", "pm_score": 4, "selected": false, "text": "<p>You can use <code>ROW_NUMBER()</code> function to get what you want:</p>\n\n<pre><code>SELECT *\nFROM (SELECT ROW_NUMBER() OVER(ORDER BY id) RowNr, id FROM tbl) t\nWHERE RowNr BETWEEN 10 AND 20\n</code></pre>\n" }, { "answer_id": 188061, "author": "Aheho", "author_id": 21155, "author_profile": "https://Stackoverflow.com/users/21155", "pm_score": 1, "selected": false, "text": "<p>In SqlServer2005 you can do the following:</p>\n\n<pre><code>DECLARE @Limit INT\nDECLARE @Offset INT\nSET @Offset = 120000\nSET @Limit = 10\n\nSELECT \n * \nFROM\n(\n SELECT \n row_number() \n OVER \n (ORDER BY column) AS rownum, column2, column3, .... columnX\n FROM \n table\n) AS A\nWHERE \n A.rownum BETWEEN (@Offset) AND (@Offset + @Limit-1) \n</code></pre>\n" }, { "answer_id": 1809287, "author": "Patrik Melander", "author_id": 220100, "author_profile": "https://Stackoverflow.com/users/220100", "pm_score": 2, "selected": false, "text": "<p>You should be careful when using the <code>ROW_NUMBER() OVER (ORDER BY)</code> statement as performance is quite poor. Same goes for using Common Table Expressions with <code>ROW_NUMBER()</code> that is even worse. I'm using the following snippet that has proven to be slightly faster than using a table variable with an identity to provide the page number.</p>\n\n<pre><code>DECLARE @Offset INT = 120000\nDECLARE @Limit INT = 10\n\nDECLARE @ROWCOUNT INT = @Offset+@Limit\nSET ROWCOUNT @ROWCOUNT\n\nSELECT * FROM MyTable INTO #ResultSet\nWHERE MyTable.Type = 1\n\nSELECT * FROM\n(\n SELECT *, ROW_NUMBER() OVER(ORDER BY SortConst ASC) As RowNumber FROM\n (\n SELECT *, 1 As SortConst FROM #ResultSet\n ) AS ResultSet\n) AS Page\nWHERE RowNumber BETWEEN @Offset AND @ROWCOUNT\n\nDROP TABLE #ResultSet\n</code></pre>\n" }, { "answer_id": 5525978, "author": "Martin Smith", "author_id": 73226, "author_profile": "https://Stackoverflow.com/users/73226", "pm_score": 7, "selected": false, "text": "<p>If you will be processing all pages in order then simply remembering the last key value seen on the previous page and using <code>TOP (25) ... WHERE Key &gt; @last_key ORDER BY Key</code> can be the best performing method if suitable indexes exist to allow this to be seeked efficiently - or <a href=\"https://dba.stackexchange.com/a/68280/3690\">an API cursor</a> if they don't.</p>\n\n<p>For selecting an arbitary page the best solution for SQL Server 2005 - 2008 R2 is probably <code>ROW_NUMBER</code> and <code>BETWEEN</code></p>\n\n<p>For SQL Server 2012+ you can use the enhanced <a href=\"http://msdn.microsoft.com/en-us/library/ms188385%28SQL.110%29.aspx\" rel=\"noreferrer\">ORDER BY</a> clause for this need.</p>\n\n<pre><code>SELECT *\nFROM MyTable \nORDER BY OrderingColumn ASC \nOFFSET 50 ROWS \nFETCH NEXT 25 ROWS ONLY \n</code></pre>\n\n<p>Though <a href=\"http://sqlblogcasts.com/blogs/sqlandthelike/archive/2010/11/10/denali-paging-is-it-win-win.aspx\" rel=\"noreferrer\">it remains to be seen how well performing this option will be</a>.</p>\n" }, { "answer_id": 10145878, "author": "Capilé", "author_id": 819311, "author_profile": "https://Stackoverflow.com/users/819311", "pm_score": 0, "selected": false, "text": "<p>I've been searching for this answer for a while now (for generic queries) and found out another way of doing it on SQL Server 2000+ using ROWCOUNT and cursors and without TOP or any temporary table.</p>\n\n<p>Using the <code>SET ROWCOUNT [OFFSET+LIMIT]</code> you can limit the results, and with cursors, go directly to the row you wish, then loop 'till the end.</p>\n\n<p>So your query would be like this:</p>\n\n<pre><code>SET ROWCOUNT 75 -- (50 + 25)\nDECLARE MyCursor SCROLL CURSOR FOR SELECT * FROM pessoas\nOPEN MyCursor\nFETCH ABSOLUTE 50 FROM MyCursor -- OFFSET\nWHILE @@FETCH_STATUS = 0 BEGIN\n FETCH next FROM MyCursor\nEND\nCLOSE MyCursor\nDEALLOCATE MyCursor\nSET ROWCOUNT 0\n</code></pre>\n" }, { "answer_id": 13072194, "author": "Arthur van Dijk", "author_id": 1774650, "author_profile": "https://Stackoverflow.com/users/1774650", "pm_score": 3, "selected": false, "text": "<p>For tables with more and large data columns, I prefer:</p>\n\n<pre><code>SELECT \n tablename.col1,\n tablename.col2,\n tablename.col3,\n ...\nFROM\n(\n (\n SELECT\n col1\n FROM \n (\n SELECT col1, ROW_NUMBER() OVER (ORDER BY col1 ASC) AS RowNum\n FROM tablename\n WHERE ([CONDITION])\n )\n AS T1 WHERE T1.RowNum BETWEEN [OFFSET] AND [OFFSET + LIMIT]\n )\n AS T2 INNER JOIN tablename ON T2.col1=tablename.col1\n);\n</code></pre>\n\n<p>-</p>\n\n<pre><code>[CONDITION] can contain any WHERE clause for searching.\n[OFFSET] specifies the start,\n[LIMIT] the maximum results.\n</code></pre>\n\n<p>It has much better performance on tables with large data like BLOBs, because the ROW_NUMBER function only has to look through one column, and only the matching rows are returned with all columns.</p>\n" }, { "answer_id": 15487131, "author": "Ravi Ramaswamy", "author_id": 2184090, "author_profile": "https://Stackoverflow.com/users/2184090", "pm_score": 1, "selected": false, "text": "<p>I use this technique for pagination. I do not fetch all the rows. For example, if my page needs to display the top 100 rows I fetch only the 100 with where clause. The output of the SQL should have a unique key.</p>\n\n<p>The table has the following:</p>\n\n<pre><code>ID, KeyId, Rank\n</code></pre>\n\n<p>The same rank will be assigned for more than one KeyId.</p>\n\n<p>SQL is <code>select top 2 * from Table1 where Rank &gt;= @Rank and ID &gt; @Id</code></p>\n\n<p>For the first time I pass 0 for both. The second time pass 1 &amp; 14. 3rd time pass 2 and 6....</p>\n\n<p>The value of the 10th record Rank &amp; Id is passed to the next</p>\n\n<pre><code>11 21 1\n14 22 1\n7 11 1\n6 19 2\n12 31 2\n13 18 2\n</code></pre>\n\n<p>This will have the least stress on the system</p>\n" }, { "answer_id": 20749237, "author": "PerfectLion", "author_id": 3130456, "author_profile": "https://Stackoverflow.com/users/3130456", "pm_score": 3, "selected": false, "text": "<p>See my select for paginator</p>\n\n<pre><code>SELECT TOP @limit * FROM (\n SELECT ROW_NUMBER() OVER (ORDER BY colunx ASC) offset, * FROM (\n\n -- YOU SELECT HERE\n SELECT * FROM mytable\n\n\n ) myquery\n) paginator\nWHERE offset &gt; @offset\n</code></pre>\n\n<p>This solves the pagination ;)</p>\n" }, { "answer_id": 23613493, "author": "Lukas Eder", "author_id": 521799, "author_profile": "https://Stackoverflow.com/users/521799", "pm_score": 3, "selected": false, "text": "<p>There is <code>OFFSET .. FETCH</code> in SQL Server 2012, but you will need to specify an <code>ORDER BY</code> column.</p>\n\n<p>If you really don't have any explicit column that you could pass as an <code>ORDER BY</code> column (as others have suggested), then you can use this trick:</p>\n\n<pre><code>SELECT * FROM MyTable \nORDER BY @@VERSION \nOFFSET 50 ROWS FETCH NEXT 25 ROWS ONLY\n</code></pre>\n\n<p>... or</p>\n\n<pre><code>SELECT * FROM MyTable \nORDER BY (SELECT 0)\nOFFSET 50 ROWS FETCH NEXT 25 ROWS ONLY\n</code></pre>\n\n<p>We're using it in <a href=\"http://www.jooq.org\" rel=\"noreferrer\">jOOQ</a> when users do not explicitly specify an order. This will then produce pretty random ordering without any additional costs.</p>\n" }, { "answer_id": 23777477, "author": "Jithin Shaji", "author_id": 3265371, "author_profile": "https://Stackoverflow.com/users/3265371", "pm_score": 2, "selected": false, "text": "<pre><code>SELECT TOP 75 * FROM MyTable\nEXCEPT \nSELECT TOP 50 * FROM MyTable\n</code></pre>\n" }, { "answer_id": 30094393, "author": "Shb", "author_id": 4281154, "author_profile": "https://Stackoverflow.com/users/4281154", "pm_score": 2, "selected": false, "text": "<p>Following will display 25 records excluding first 50 records works in SQL Server 2012.</p>\n\n<pre><code>SELECT * FROM MyTable ORDER BY ID OFFSET 50 ROWS FETCH NEXT 25 ROWS ONLY;\n</code></pre>\n\n<p>you can replace ID as your requirement</p>\n" }, { "answer_id": 41661284, "author": "8Unlimited8", "author_id": 3526863, "author_profile": "https://Stackoverflow.com/users/3526863", "pm_score": 1, "selected": false, "text": "<p>Best way to do it without wasting time to order records is like this :</p>\n\n<pre><code>select 0 as tmp,Column1 from Table1 Order by tmp OFFSET 5000000 ROWS FETCH NEXT 50 ROWS ONLY\n</code></pre>\n\n<p>it takes less than one second!<br>\nbest solution for large tables.</p>\n" }, { "answer_id": 61351735, "author": "Tejasvi Hegde", "author_id": 1726296, "author_profile": "https://Stackoverflow.com/users/1726296", "pm_score": 1, "selected": false, "text": "<p>With SQL Server 2012 (11.x) and later and Azure SQL Database, you can also have \"fetch_row_count_expression\", you can also have ORDER BY clause along with this. </p>\n\n<pre><code>USE AdventureWorks2012; \nGO \n-- Specifying variables for OFFSET and FETCH values \nDECLARE @skip int = 0 , @take int = 8; \nSELECT DepartmentID, Name, GroupName \nFROM HumanResources.Department \nORDER BY DepartmentID ASC \n OFFSET @skip ROWS \n FETCH NEXT @take ROWS ONLY; \n</code></pre>\n\n<p><a href=\"https://learn.microsoft.com/en-us/sql/t-sql/queries/select-order-by-clause-transact-sql?view=sql-server-ver15\" rel=\"nofollow noreferrer\">https://learn.microsoft.com/en-us/sql/t-sql/queries/select-order-by-clause-transact-sql?view=sql-server-ver15</a></p>\n\n<p><strong>Note</strong>\nOFFSET Specifies the <em>number of rows to skip</em> before it starts to return rows from the query expression. It is NOT the starting row number. So, it has to be 0 to include first record.</p>\n" }, { "answer_id": 68969012, "author": "mrsagar105", "author_id": 15160381, "author_profile": "https://Stackoverflow.com/users/15160381", "pm_score": 0, "selected": false, "text": "<h2>Method 1:</h2>\n<p><strong>Ordering seem to matter here</strong></p>\n<p>Bringing limit before offset seems to work.</p>\n<pre><code>SELECT *\nFROM MyTable\nLIMIT 25\nOFFSET 50\n</code></pre>\n<hr />\n<h2>Method 2:</h2>\n<p><strong>Alternatively, you can use limit only</strong><br>\nLIMIT takes two values<br>\n1st: Offset value<br>\n2nd: No of rows to be displayed</p>\n<p>SELECT *<br>\nFROM MyTable<br>\nLIMIT (OffsetValue), (NoOfRows)</p>\n<pre><code>SELECT *\nFROM MyTable\nLIMIT 50, 25\n</code></pre>\n" } ]
2008/10/09
[ "https://Stackoverflow.com/questions/187998", "https://Stackoverflow.com", "https://Stackoverflow.com/users/420/" ]
Is there any way in SQL Server to get the results starting at a given offset? For example, in another type of SQL database, it's possible to do: ``` SELECT * FROM MyTable OFFSET 50 LIMIT 25 ``` to get results 51-75. This construct does not appear to exist in SQL Server. How can I accomplish this without loading all the rows I don't care about? Thanks!
I would avoid using `SELECT *`. Specify columns you actually want even though it may be all of them. **SQL Server 2005+** ``` SELECT col1, col2 FROM ( SELECT col1, col2, ROW_NUMBER() OVER (ORDER BY ID) AS RowNum FROM MyTable ) AS MyDerivedTable WHERE MyDerivedTable.RowNum BETWEEN @startRow AND @endRow ``` **SQL Server 2000** [Efficiently Paging Through Large Result Sets in SQL Server 2000](https://web.archive.org/web/20210506081930/http://www.4guysfromrolla.com/webtech/041206-1.shtml) [A More Efficient Method for Paging Through Large Result Sets](https://web.archive.org/web/20211020131201/https://www.4guysfromrolla.com/webtech/042606-1.shtml)
187,999
<p>One small function of a large program examines assemblies in a folder and replaces out-of-date assemblies with the latest versions. To accomplish this, it needs to read the version numbers of the existing assembly files without actually loading those assemblies into the executing process.</p>
[ { "answer_id": 188036, "author": "jop", "author_id": 11830, "author_profile": "https://Stackoverflow.com/users/11830", "pm_score": 3, "selected": false, "text": "<p>Use <code>AssemblyName.GetAssemblyName(\"assembly.dll\");</code>, then parse the name. According to <a href=\"http://msdn.microsoft.com/en-us/library/system.reflection.assemblyname.getassemblyname.aspx\" rel=\"noreferrer\">MSDN</a>:</p>\n\n<blockquote>\n <p>This will only work if the file\n contains an assembly manifest. This\n method causes the file to be opened\n and closed, but the assembly is not\n added to this domain.</p>\n</blockquote>\n" }, { "answer_id": 188038, "author": "Joel B Fant", "author_id": 22211, "author_profile": "https://Stackoverflow.com/users/22211", "pm_score": 6, "selected": true, "text": "<p>I found the following <a href=\"http://blogs.msdn.com/alejacma/archive/2008/09/05/how-to-get-assembly-version-without-loading-it.aspx\" rel=\"noreferrer\">in this article</a>.</p>\n\n<pre><code>using System.Reflection;\nusing System.IO;\n\n...\n\n// Get current and updated assemblies\nAssemblyName currentAssemblyName = AssemblyName.GetAssemblyName(currentAssemblyPath);\nAssemblyName updatedAssemblyName = AssemblyName.GetAssemblyName(updatedAssemblyPath);\n\n// Compare both versions\nif (updatedAssemblyName.Version.CompareTo(currentAssemblyName.Version) &lt;= 0)\n{\n // There's nothing to update\n return;\n}\n\n// Update older version\nFile.Copy(updatedAssemblyPath, currentAssemblyPath, true);\n</code></pre>\n" }, { "answer_id": 188045, "author": "Marc Gravell", "author_id": 23354, "author_profile": "https://Stackoverflow.com/users/23354", "pm_score": 4, "selected": false, "text": "<p>Depending on the files, one option might be <code>FileVersionInfo</code> - i.e.</p>\n\n<pre><code>FileVersionInfo fvi = FileVersionInfo.GetVersionInfo(path)\nstring ver = fvi.FileVersion;\n</code></pre>\n\n<p>The problem is that this depends on the code having the <code>[AssemblyFileVersion]</code> attribute, and it matching the <code>[AssemblyVersion]</code> attribute.</p>\n\n<p>I think I'd look at the AssemblyName options suggested by others first, though.</p>\n" }, { "answer_id": 21755415, "author": "Bjørn", "author_id": 3306167, "author_profile": "https://Stackoverflow.com/users/3306167", "pm_score": 2, "selected": false, "text": "<p>Just for the record: Here's how to get the file version in C#.NET Compact Framework. It's basically from OpenNETCF but quite shorter and exctacted so it can by copy'n'pasted. Hope it'll help...</p>\n\n<pre><code>public static Version GetFileVersionCe(string fileName)\n{\n int handle = 0;\n int length = GetFileVersionInfoSize(fileName, ref handle);\n Version v = null;\n if (length &gt; 0)\n {\n IntPtr buffer = System.Runtime.InteropServices.Marshal.AllocHGlobal(length);\n if (GetFileVersionInfo(fileName, handle, length, buffer))\n {\n IntPtr fixedbuffer = IntPtr.Zero;\n int fixedlen = 0;\n if (VerQueryValue(buffer, \"\\\\\", ref fixedbuffer, ref fixedlen))\n {\n byte[] fixedversioninfo = new byte[fixedlen];\n System.Runtime.InteropServices.Marshal.Copy(fixedbuffer, fixedversioninfo, 0, fixedlen);\n v = new Version(\n BitConverter.ToInt16(fixedversioninfo, 10), \n BitConverter.ToInt16(fixedversioninfo, 8), \n BitConverter.ToInt16(fixedversioninfo, 14),\n BitConverter.ToInt16(fixedversioninfo, 12));\n }\n }\n Marshal.FreeHGlobal(buffer);\n }\n return v;\n}\n\n[DllImport(\"coredll\", EntryPoint = \"GetFileVersionInfo\", SetLastError = true)]\nprivate static extern bool GetFileVersionInfo(string filename, int handle, int len, IntPtr buffer);\n[DllImport(\"coredll\", EntryPoint = \"GetFileVersionInfoSize\", SetLastError = true)]\nprivate static extern int GetFileVersionInfoSize(string filename, ref int handle);\n[DllImport(\"coredll\", EntryPoint = \"VerQueryValue\", SetLastError = true)]\nprivate static extern bool VerQueryValue(IntPtr buffer, string subblock, ref IntPtr blockbuffer, ref int len);\n</code></pre>\n" }, { "answer_id": 66390504, "author": "Eric Patrick", "author_id": 1088293, "author_profile": "https://Stackoverflow.com/users/1088293", "pm_score": 0, "selected": false, "text": "<p>A <code>.netcore</code> update to Joel's answer, using <a href=\"https://learn.microsoft.com/en-us/dotnet/core/dependency-loading/understanding-assemblyloadcontext\" rel=\"nofollow noreferrer\">AssemblyLoadContext</a>:</p>\n<pre class=\"lang-cs prettyprint-override\"><code>using System.IO;\nusing System.Reflection;\nusing System.Runtime.Loader;\n\n...\n\n// Get current and updated assemblies\nAssemblyName currentAssemblyName = AssemblyLoadContext.GetAssemblyName(currentAssemblyPath);\nAssemblyName updatedAssemblyName = AssemblyLoadContext.GetAssemblyName(updatedAssemblyPath);\n\n// Compare both versions\nif (updatedAssemblyName.Version.CompareTo(currentAssemblyName.Version) &lt;= 0)\n{\n // There's nothing to update\n return;\n}\n\n// Update older version\nFile.Copy(updatedAssemblyPath, currentAssemblyPath, true);\n</code></pre>\n<blockquote>\n<p>I found this useful in analyzing DLLs running (and locked) by a Windows Service, a much cleaner alternative to creating a separate <code>AppDomain</code>.</p>\n</blockquote>\n" } ]
2008/10/09
[ "https://Stackoverflow.com/questions/187999", "https://Stackoverflow.com", "https://Stackoverflow.com/users/26553/" ]
One small function of a large program examines assemblies in a folder and replaces out-of-date assemblies with the latest versions. To accomplish this, it needs to read the version numbers of the existing assembly files without actually loading those assemblies into the executing process.
I found the following [in this article](http://blogs.msdn.com/alejacma/archive/2008/09/05/how-to-get-assembly-version-without-loading-it.aspx). ``` using System.Reflection; using System.IO; ... // Get current and updated assemblies AssemblyName currentAssemblyName = AssemblyName.GetAssemblyName(currentAssemblyPath); AssemblyName updatedAssemblyName = AssemblyName.GetAssemblyName(updatedAssemblyPath); // Compare both versions if (updatedAssemblyName.Version.CompareTo(currentAssemblyName.Version) <= 0) { // There's nothing to update return; } // Update older version File.Copy(updatedAssemblyPath, currentAssemblyPath, true); ```
188,001
<p>I am attempting to rewrite my <a href="http://ForestPad.com" rel="nofollow noreferrer">ForestPad</a> application utilizing WPF for the presentation layer. In WinForms, I am populating each node programmatically but I would like to take advantage of the databinding capabilities of WPF, if possible.</p> <p>In general, what is the best way to two-way databind the WPF TreeView to an Xml document?</p> <p>A generic solution is fine but for reference, the structure of the Xml document that I am trying to bind to looks like this:</p> <pre><code>&lt;?xml version="1.0" encoding="utf-8"?&gt; &lt;forestPad guid="6c9325de-dfbe-4878-9d91-1a9f1a7696b0" created="5/14/2004 1:05:10 AM" updated="5/14/2004 1:07:41 AM"&gt; &lt;forest name="A forest node" guid="b441a196-7468-47c8-a010-7ff83429a37b" created="01/01/2003 1:00:00 AM" updated="5/14/2004 1:06:15 AM"&gt; &lt;data&gt; &lt;![CDATA[A forest node This is the text of the forest node.]]&gt; &lt;/data&gt; &lt;tree name="A tree node" guid="768eae66-e9df-4999-b950-01fa9be1a5cf" created="5/14/2004 1:05:38 AM" updated="5/14/2004 1:06:11 AM"&gt; &lt;data&gt; &lt;![CDATA[A tree node This is the text of the tree node.]]&gt; &lt;/data&gt; &lt;branch name="A branch node" guid="be4b0993-d4e4-4249-8aa5-fa9c940ae2be" created="5/14/2004 1:06:00 AM" updated="5/14/2004 1:06:24 AM"&gt; &lt;data&gt; &lt;![CDATA[A branch node This is the text of the branch node.]]&gt;&lt;/data&gt; &lt;leaf name="A leaf node" guid="9c76ff4e-3ae2-450e-b1d2-232b687214aa" created="5/14/2004 1:06:26 AM" updated="5/14/2004 1:06:38 AM"&gt; &lt;data&gt; &lt;![CDATA[A leaf node This is the text of the leaf node.]]&gt; &lt;/data&gt; &lt;/leaf&gt; &lt;/branch&gt; &lt;/tree&gt; &lt;/forest&gt; &lt;/forestPad&gt; </code></pre>
[ { "answer_id": 188084, "author": "Joel B Fant", "author_id": 22211, "author_profile": "https://Stackoverflow.com/users/22211", "pm_score": 4, "selected": true, "text": "<p>Well, it would be easier if your element hierarchy was more like...</p>\n\n<pre><code>&lt;node type=\"forest\"&gt;\n &lt;node type=\"tree\"&gt;\n ...\n</code></pre>\n\n<p>...rather than your current schema.</p>\n\n<p>As-is, you'll need 4 <code>HierarchicalDataTemplate</code>s, one for each hierarchical element including the root, and one <code>DataTemplate</code> for <code>leaf</code> elements:</p>\n\n<pre><code>&lt;Window.Resources&gt;\n &lt;HierarchicalDataTemplate\n DataType=\"forestPad\"\n ItemsSource=\"{Binding XPath=forest}\"&gt;\n &lt;TextBlock\n Text=\"a forestpad\" /&gt;\n &lt;/HierarchicalDataTemplate&gt;\n &lt;HierarchicalDataTemplate\n DataType=\"forest\"\n ItemsSource=\"{Binding XPath=tree}\"&gt;\n &lt;TextBox\n Text=\"{Binding XPath=data}\" /&gt;\n &lt;/HierarchicalDataTemplate&gt;\n &lt;HierarchicalDataTemplate\n DataType=\"tree\"\n ItemsSource=\"{Binding XPath=branch}\"&gt;\n &lt;TextBox\n Text=\"{Binding XPath=data}\" /&gt;\n &lt;/HierarchicalDataTemplate&gt;\n &lt;HierarchicalDataTemplate\n DataType=\"branch\"\n ItemsSource=\"{Binding XPath=leaf}\"&gt;\n &lt;TextBox\n Text=\"{Binding XPath=data}\" /&gt;\n &lt;/HierarchicalDataTemplate&gt;\n &lt;DataTemplate\n DataType=\"leaf\"&gt;\n &lt;TextBox\n Text=\"{Binding XPath=data}\" /&gt;\n &lt;/DataTemplate&gt;\n\n &lt;XmlDataProvider\n x:Key=\"dataxml\"\n XPath=\"forestPad\" Source=\"D:\\fp.xml\"&gt;\n &lt;/XmlDataProvider&gt;\n&lt;/Window.Resources&gt;\n</code></pre>\n\n<p>You can instead set the <code>Source</code> of the <code>XmlDataProvider</code> programmatically:</p>\n\n<pre><code>dp = this.FindResource( \"dataxml\" ) as XmlDataProvider;\ndp.Source = new Uri( @\"D:\\fp.xml\" );\n</code></pre>\n\n<p>Also, re-saving your edits is as easy as this:</p>\n\n<pre><code>dp.Document.Save( dp.Source.LocalPath );\n</code></pre>\n\n<p>The <code>TreeView</code> itself needs a <code>Name</code> and an <code>ItemsSource</code> bonded to the <code>XmlDataProvider</code>:</p>\n\n<pre><code>&lt;TreeView\n Name=\"treeview\"\n ItemsSource=\"{Binding Source={StaticResource dataxml}, XPath=.}\"&gt;\n</code></pre>\n\n<p>I this example, I did <code>TwoWay</code> binding with <code>TextBox</code>es on each node, but when it comes to editing just one node at a time in a separate, single <code>TextBox</code> or other control, you would be binding it to the currently selected item of the <code>TreeView</code>. You would also change the above <code>TextBox</code>es to <code>TextBlock</code>s, as clicking in the <code>TextBox</code> does not actually select the corresponding <code>TreeViewItem</code>.</p>\n\n<pre><code>&lt;TextBox\n DataContext=\"{Binding ElementName=treeview, Path=SelectedItem}\"\n Text=\"{Binding XPath=data, UpdateSourceTrigger=PropertyChanged}\"/&gt;\n</code></pre>\n\n<p>The reason you must use two <code>Binding</code>s is that you cannot use <code>Path</code> and <code>XPath</code> together.</p>\n\n<p><strong>Edit:</strong></p>\n\n<p>Timothy Lee Russell asked about saving CDATA to the data elements. First, a little on <code>InnerXml</code> and <code>InnerText</code>.</p>\n\n<p>Behind the scenes, <code>XmlDataProvider</code> is using an <code>XmlDocument</code>, with it's tree of <code>XmlNodes</code>. When a string such as \"stuff\" is assigned to the <code>InnerXml</code> property of an <code>XmlNode</code>, then those tags are really tags. No escaping is done when getting or setting <code>InnerXml</code>, and it is parsed as XML.</p>\n\n<p>However, if it is instead assigned to the <code>InnerText</code> property, the angle brackets will be escaped with entities &amp;lt; and &amp;gt;. The reverse happens when the value is retreived. Entities (like &amp;lt;) are resolved back into characters (like &lt;).</p>\n\n<p>Therefore, if the strings we store in the data elements contain XML, entities have been escaped, and we need to undo that simply by retrieving <code>InnerText</code> before adding a CDATA section as the node's child...</p>\n\n<pre><code>XmlDocument doc = dp.Document;\n\nXmlNodeList nodes = doc.SelectNodes( \"//data\" );\n\nforeach ( XmlNode node in nodes ) {\n string data = node.InnerText;\n node.InnerText = \"\";\n XmlCDataSection cdata = doc.CreateCDataSection( data );\n node.AppendChild( cdata );\n}\n\ndoc.Save( dp.Source.LocalPath );\n</code></pre>\n\n<p>If the node already has a CDATA section and the value has not been changed in any way, then it still has a CDATA section and we essentially replace it with the same. However, through our binding, if we change the value of the data elements contents, it replaces the CDATA in favor of an escaped string. Then we have to fix them.</p>\n" }, { "answer_id": 188101, "author": "Shaun Bowe", "author_id": 1514, "author_profile": "https://Stackoverflow.com/users/1514", "pm_score": 2, "selected": false, "text": "<p>We had a similar issue. You may find reading <a href=\"http://www.codeproject.com/KB/WPF/TreeViewWithViewModel.aspx\" rel=\"nofollow noreferrer\">this article</a> helpful. We used the ViewModel pattern described and it simplified everything.</p>\n" }, { "answer_id": 71343808, "author": "B. Fuller", "author_id": 5552085, "author_profile": "https://Stackoverflow.com/users/5552085", "pm_score": 1, "selected": false, "text": "<p>I know this is an old post, but there's a more elegant solution. You can indeed use a single <code>HierarchicalDataTemplate</code>, if you use an XPath expression that selects all of the nodes that you want the template to use: <code>XPath=tree|branch|leaf</code>.</p>\n<pre><code>&lt;HierarchicalDataTemplate x:Key=&quot;forestTemplate&quot;\n ItemsSource=&quot;{Binding XPath=tree|branch|leaf}&quot;&gt;\n &lt;TextBlock Text=&quot;{Binding XPath=data}&quot; /&gt;\n&lt;/HierarchicalDataTemplate&gt;\n</code></pre>\n<p>Here's a full <code>Page</code> example with XData embedded in the <code>XmlDataProvider1</code>:</p>\n<pre><code>&lt;Page \n xmlns=&quot;http://schemas.microsoft.com/winfx/2006/xaml/presentation&quot;\n xmlns:x=&quot;http://schemas.microsoft.com/winfx/2006/xaml&quot;&gt;\n &lt;Page.Resources&gt;\n &lt;XmlDataProvider x:Key=&quot;sampleForestPad&quot; XPath=&quot;forestPad/forest&quot;&gt;\n &lt;x:XData&gt;\n &lt;forestPad xmlns=&quot;&quot;\n guid=&quot;6c9325de-dfbe-4878-9d91-1a9f1a7696b0&quot;\n created=&quot;5/14/2004 1:05:10 AM&quot;\n updated=&quot;5/14/2004 1:07:41 AM&quot;&gt;\n &lt;forest \n name=&quot;A forest node&quot;\n guid=&quot;b441a196-7468-47c8-a010-7ff83429a37b&quot;\n created=&quot;01/01/2003 1:00:00 AM&quot;\n updated=&quot;5/14/2004 1:06:15 AM&quot;&gt;\n &lt;data&gt;\n &lt;![CDATA[A forest node\n This is the text of the forest node.]]&gt;\n &lt;/data&gt;\n &lt;tree\n name=&quot;A tree node&quot;\n guid=&quot;768eae66-e9df-4999-b950-01fa9be1a5cf&quot;\n created=&quot;5/14/2004 1:05:38 AM&quot;\n updated=&quot;5/14/2004 1:06:11 AM&quot;&gt;\n &lt;data&gt;\n &lt;![CDATA[A tree node\n This is the text of the tree node.]]&gt;\n &lt;/data&gt;\n &lt;branch\n name=&quot;A branch node&quot;\n guid=&quot;be4b0993-d4e4-4249-8aa5-fa9c940ae2be&quot;\n created=&quot;5/14/2004 1:06:00 AM&quot;\n updated=&quot;5/14/2004 1:06:24 AM&quot;&gt;\n &lt;data&gt;\n &lt;![CDATA[A branch node\n This is the text of the branch node.]]&gt;&lt;/data&gt;\n &lt;leaf\n name=&quot;A leaf node&quot;\n guid=&quot;9c76ff4e-3ae2-450e-b1d2-232b687214aa&quot;\n created=&quot;5/14/2004 1:06:26 AM&quot;\n updated=&quot;5/14/2004 1:06:38 AM&quot;&gt;\n &lt;data&gt;\n &lt;![CDATA[A leaf node\n This is the text of the leaf node.]]&gt;\n &lt;/data&gt;\n &lt;/leaf&gt;\n &lt;/branch&gt;\n &lt;/tree&gt;\n &lt;/forest&gt;\n &lt;/forestPad&gt;\n &lt;/x:XData&gt;\n &lt;/XmlDataProvider&gt;\n\n &lt;HierarchicalDataTemplate x:Key=&quot;forestTemplate&quot;\n ItemsSource=&quot;{Binding XPath=tree|branch|leaf}&quot;&gt;\n &lt;TextBlock Text=&quot;{Binding XPath=data}&quot; /&gt;\n &lt;/HierarchicalDataTemplate&gt;\n\n &lt;Style TargetType=&quot;TreeViewItem&quot;&gt;\n &lt;Setter Property=&quot;IsExpanded&quot; Value=&quot;True&quot;/&gt;\n &lt;/Style&gt;\n &lt;/Page.Resources&gt;\n\n &lt;TreeView ItemsSource=&quot;{Binding Source={StaticResource sampleForestPad}}&quot;\n ItemTemplate=&quot;{StaticResource forestTemplate}&quot;/&gt;\n&lt;/Page&gt;\n</code></pre>\n<p>This will render as:</p>\n<p><a href=\"https://i.stack.imgur.com/gjfgJ.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/gjfgJ.png\" alt=\"ForestTreeView\" /></a></p>\n" } ]
2008/10/09
[ "https://Stackoverflow.com/questions/188001", "https://Stackoverflow.com", "https://Stackoverflow.com/users/12919/" ]
I am attempting to rewrite my [ForestPad](http://ForestPad.com) application utilizing WPF for the presentation layer. In WinForms, I am populating each node programmatically but I would like to take advantage of the databinding capabilities of WPF, if possible. In general, what is the best way to two-way databind the WPF TreeView to an Xml document? A generic solution is fine but for reference, the structure of the Xml document that I am trying to bind to looks like this: ``` <?xml version="1.0" encoding="utf-8"?> <forestPad guid="6c9325de-dfbe-4878-9d91-1a9f1a7696b0" created="5/14/2004 1:05:10 AM" updated="5/14/2004 1:07:41 AM"> <forest name="A forest node" guid="b441a196-7468-47c8-a010-7ff83429a37b" created="01/01/2003 1:00:00 AM" updated="5/14/2004 1:06:15 AM"> <data> <![CDATA[A forest node This is the text of the forest node.]]> </data> <tree name="A tree node" guid="768eae66-e9df-4999-b950-01fa9be1a5cf" created="5/14/2004 1:05:38 AM" updated="5/14/2004 1:06:11 AM"> <data> <![CDATA[A tree node This is the text of the tree node.]]> </data> <branch name="A branch node" guid="be4b0993-d4e4-4249-8aa5-fa9c940ae2be" created="5/14/2004 1:06:00 AM" updated="5/14/2004 1:06:24 AM"> <data> <![CDATA[A branch node This is the text of the branch node.]]></data> <leaf name="A leaf node" guid="9c76ff4e-3ae2-450e-b1d2-232b687214aa" created="5/14/2004 1:06:26 AM" updated="5/14/2004 1:06:38 AM"> <data> <![CDATA[A leaf node This is the text of the leaf node.]]> </data> </leaf> </branch> </tree> </forest> </forestPad> ```
Well, it would be easier if your element hierarchy was more like... ``` <node type="forest"> <node type="tree"> ... ``` ...rather than your current schema. As-is, you'll need 4 `HierarchicalDataTemplate`s, one for each hierarchical element including the root, and one `DataTemplate` for `leaf` elements: ``` <Window.Resources> <HierarchicalDataTemplate DataType="forestPad" ItemsSource="{Binding XPath=forest}"> <TextBlock Text="a forestpad" /> </HierarchicalDataTemplate> <HierarchicalDataTemplate DataType="forest" ItemsSource="{Binding XPath=tree}"> <TextBox Text="{Binding XPath=data}" /> </HierarchicalDataTemplate> <HierarchicalDataTemplate DataType="tree" ItemsSource="{Binding XPath=branch}"> <TextBox Text="{Binding XPath=data}" /> </HierarchicalDataTemplate> <HierarchicalDataTemplate DataType="branch" ItemsSource="{Binding XPath=leaf}"> <TextBox Text="{Binding XPath=data}" /> </HierarchicalDataTemplate> <DataTemplate DataType="leaf"> <TextBox Text="{Binding XPath=data}" /> </DataTemplate> <XmlDataProvider x:Key="dataxml" XPath="forestPad" Source="D:\fp.xml"> </XmlDataProvider> </Window.Resources> ``` You can instead set the `Source` of the `XmlDataProvider` programmatically: ``` dp = this.FindResource( "dataxml" ) as XmlDataProvider; dp.Source = new Uri( @"D:\fp.xml" ); ``` Also, re-saving your edits is as easy as this: ``` dp.Document.Save( dp.Source.LocalPath ); ``` The `TreeView` itself needs a `Name` and an `ItemsSource` bonded to the `XmlDataProvider`: ``` <TreeView Name="treeview" ItemsSource="{Binding Source={StaticResource dataxml}, XPath=.}"> ``` I this example, I did `TwoWay` binding with `TextBox`es on each node, but when it comes to editing just one node at a time in a separate, single `TextBox` or other control, you would be binding it to the currently selected item of the `TreeView`. You would also change the above `TextBox`es to `TextBlock`s, as clicking in the `TextBox` does not actually select the corresponding `TreeViewItem`. ``` <TextBox DataContext="{Binding ElementName=treeview, Path=SelectedItem}" Text="{Binding XPath=data, UpdateSourceTrigger=PropertyChanged}"/> ``` The reason you must use two `Binding`s is that you cannot use `Path` and `XPath` together. **Edit:** Timothy Lee Russell asked about saving CDATA to the data elements. First, a little on `InnerXml` and `InnerText`. Behind the scenes, `XmlDataProvider` is using an `XmlDocument`, with it's tree of `XmlNodes`. When a string such as "stuff" is assigned to the `InnerXml` property of an `XmlNode`, then those tags are really tags. No escaping is done when getting or setting `InnerXml`, and it is parsed as XML. However, if it is instead assigned to the `InnerText` property, the angle brackets will be escaped with entities &lt; and &gt;. The reverse happens when the value is retreived. Entities (like &lt;) are resolved back into characters (like <). Therefore, if the strings we store in the data elements contain XML, entities have been escaped, and we need to undo that simply by retrieving `InnerText` before adding a CDATA section as the node's child... ``` XmlDocument doc = dp.Document; XmlNodeList nodes = doc.SelectNodes( "//data" ); foreach ( XmlNode node in nodes ) { string data = node.InnerText; node.InnerText = ""; XmlCDataSection cdata = doc.CreateCDataSection( data ); node.AppendChild( cdata ); } doc.Save( dp.Source.LocalPath ); ``` If the node already has a CDATA section and the value has not been changed in any way, then it still has a CDATA section and we essentially replace it with the same. However, through our binding, if we change the value of the data elements contents, it replaces the CDATA in favor of an escaped string. Then we have to fix them.
188,007
<p>I'm using my code-behind page to create a save button programmatically:</p> <pre><code> Button btnSave = new Button(); btnSave.ID = "btnSave"; btnSave.Text = "Save"; </code></pre> <p>However I think this must create an html button or perhaps needs something else as I cannot seem to set the OnClick attribute in the following line, I can specify OnClientClick but this isn't the one I want to set.</p>
[ { "answer_id": 188021, "author": "Mitchel Sellers", "author_id": 13279, "author_profile": "https://Stackoverflow.com/users/13279", "pm_score": 3, "selected": false, "text": "<p>You would be adding a handler to the OnClick using the += syntax if you want to register a handler for the OnClick event in the code behind.</p>\n\n<pre><code>//Add the handler to your button, passing the name of the handling method \nbtnSave.Click += new System.EventHandler(btnSave_Click);\n\nprotected void btnSave_Click(object sender, EventArgs e)\n{\n //Your custom code goes here\n}\n</code></pre>\n" }, { "answer_id": 188056, "author": "Erikk Ross", "author_id": 18772, "author_profile": "https://Stackoverflow.com/users/18772", "pm_score": 5, "selected": true, "text": "<pre><code>Button btnSave = new Button(); \nbtnSave.ID = \"btnSave\"; \nbtnSave.Text = \"Save\"; \nbtnSave.Click += new System.EventHandler(btnSave_Click);\n\nprotected void btnSave_Click(object sender, EventArgs e)\n{\n //do something when button clicked. \n}\n</code></pre>\n" }, { "answer_id": 188080, "author": "Joel Coehoorn", "author_id": 3043, "author_profile": "https://Stackoverflow.com/users/3043", "pm_score": 3, "selected": false, "text": "<p>Also remember that when the user clicks the button it will force a postback, which creates a <em>new instance</em> of your page class. The old instance where you created the button is already gone. You need to make sure that this new instance of the class also adds your button -- and it's event handler -- <em>prior to the load phase</em>, or the event handler won't run (the page's load event still will, however).</p>\n" } ]
2008/10/09
[ "https://Stackoverflow.com/questions/188007", "https://Stackoverflow.com", "https://Stackoverflow.com/users/26126/" ]
I'm using my code-behind page to create a save button programmatically: ``` Button btnSave = new Button(); btnSave.ID = "btnSave"; btnSave.Text = "Save"; ``` However I think this must create an html button or perhaps needs something else as I cannot seem to set the OnClick attribute in the following line, I can specify OnClientClick but this isn't the one I want to set.
``` Button btnSave = new Button(); btnSave.ID = "btnSave"; btnSave.Text = "Save"; btnSave.Click += new System.EventHandler(btnSave_Click); protected void btnSave_Click(object sender, EventArgs e) { //do something when button clicked. } ```
188,043
<p>Ok guys just a small game:</p> <p>I have some specifications for a project. At some point they ask for the following to encrypt a password over the net, saying that it is a challenge response protocol:</p> <pre> CLIENT ----------------------------- SERVER (1)ask for challenge --------------&gt; (2) &lt;---------------------------- send SHA1 taken from the time (this is the challenge) (3) make SHA1 xor PASSWORD --------&gt; if it's equal to SHA1 xor stored password (4) &lt;---------------------------- Grant access </pre> <p>For those who don't know it SHA stands for Secure Hashing Algorithm, a standard algorithm for cryptography.</p> <p>I hope it's clear. Question is: If I sniff packets 2 and 3 (the "challenge" and the "challenge xor password", I do have the actual password just with another xor between them both!?!? There is other way to implement this kind of protocol?? </p>
[ { "answer_id": 188058, "author": "Greg Dean", "author_id": 1200558, "author_profile": "https://Stackoverflow.com/users/1200558", "pm_score": 2, "selected": false, "text": "<p>You would be able to reverse engineer the password. You want to send the SHA of the password, not the password itself. Rolling your own security protocols is almost never a good idea. Can you not use SSL or something equivalent?</p>\n\n<p><a href=\"http://en.wikipedia.org/wiki/Cryptographic_nonce\" rel=\"nofollow noreferrer\">http://en.wikipedia.org/wiki/Cryptographic_nonce</a></p>\n" }, { "answer_id": 188059, "author": "Rob Walker", "author_id": 3631, "author_profile": "https://Stackoverflow.com/users/3631", "pm_score": 1, "selected": false, "text": "<p>You are right -- if you capture the challenge and (challenge XOR password) then extracting the password is easy.</p>\n\n<p>You need to use proper encryption in step 3, not XOR. Encrypt the challenge with the password. </p>\n\n<p>To make an attacker's life harder you could add random data to what you encrypt to: e.g. encrypt paddingCHALLENGEpadding. The server doesn't care what the padding is, it knows where to look for the challenge, but it means an attacker won't know what the whole plaintext is.</p>\n" }, { "answer_id": 188102, "author": "Tom Ritter", "author_id": 8435, "author_profile": "https://Stackoverflow.com/users/8435", "pm_score": 2, "selected": false, "text": "<p>That's a pretty horrible protocol. If this is something someone wants you to implement, refuse to. There are existing, vetted protocols for this type of thing. If this is a game where you point out all the flaws - okay.</p>\n\n<ul>\n<li>Anyone who hears steps 2 &amp; 3 knows the password</li>\n<li>Anyone who hears step 3 and notes the time can brute-force the password if he has any idea of the precision of the time on the server</li>\n<li>I can pretend to be a server (arp poisoning, dns rediction, etc), and get your password, never completing step 4 and feigning a timeout</li>\n<li>Vulnerable to Man in the Middle Attacks because there's no shared secret between client/server or certificates on the server</li>\n<li>Relies on the server storing the SHA1(time) and waiting for a response, so I can overload the server with requests for challenges and never reply.</li>\n</ul>\n\n<p>And I'm definetly missing some more.</p>\n" }, { "answer_id": 188108, "author": "rcreswick", "author_id": 3446, "author_profile": "https://Stackoverflow.com/users/3446", "pm_score": 1, "selected": false, "text": "<p>As the other's have pointed out, you are correct. Also keep in mind that someone could intercept communication (3) and potentially resend it while the real user is experiencing network issues (eg: a DDOS), the impostor would then be logged in and often that is sufficient to change the password (that is, many systems don't require that you supply a password inorder to change it once you are logged in).</p>\n\n<p>You may want to consider HMAC (keyed-Hash Message Authentication Code). I've blogged about it in detail here: <a href=\"http://blog.ciscavate.org/2007/09/creating-a-secure-webauth-system-part-1-hmac.html\" rel=\"nofollow noreferrer\">http://blog.ciscavate.org/2007/09/creating-a-secure-webauth-system-part-1-hmac.html</a> and I'll give a quick summary below.</p>\n\n<p>HMAC is a method of ensuring that a message was generated by someone with access to a shared secret. HMAC makes use of some sort of one-way hashing function (like MD5 or SHA-1) to encrypt the secret along with a message. This generates a short digest of 16-20 bytes that acts as a fingerprint of the message+secret combination. When the digest is sent along with the message, the receiver (our server) can re-generate the hash with the same HMAC calculation and compare the locally generated digest with the digest that came along with the message. Remember: the server has the secret too, so it has enough information to confirm the digest. (This only considers the problem of verifying the origin of a message, but you can use the same approach to encrypt the entire message, if you use a different secret, say a set of public keys.)</p>\n" }, { "answer_id": 188112, "author": "Bruno De Fraine", "author_id": 6918, "author_profile": "https://Stackoverflow.com/users/6918", "pm_score": 3, "selected": true, "text": "<p>How about the following:</p>\n\n<ol>\n<li>Server sends a random challenge</li>\n<li>Client sends SHA1 checksum of (challenge+password)</li>\n<li>Servers compares against SHA1 checksum of (challenge+stored password)</li>\n</ol>\n" }, { "answer_id": 188128, "author": "workmad3", "author_id": 16035, "author_profile": "https://Stackoverflow.com/users/16035", "pm_score": 0, "selected": false, "text": "<p>The way I would do this is the following:</p>\n\n<ol>\n<li>Challenge the server. </li>\n<li><p>Server responds with it's public key\n(for, say RSA encryption) digitally\nsigned.</p></li>\n<li><p>Client verifies PK, and encrypts\npassword with the key, then\ndigitally signs the encrypted\npassword.</p></li>\n<li><p>Server verifies signing and decrypts\nthe password to store/check it.</p></li>\n</ol>\n\n<p>The digital signing is important here as it acts as the beginning of preventing man in the middle attacks.</p>\n" }, { "answer_id": 190872, "author": "Nick Johnson", "author_id": 12030, "author_profile": "https://Stackoverflow.com/users/12030", "pm_score": 0, "selected": false, "text": "<p>As others have pointed out, yes, this is a poor challenge response algorithm.</p>\n\n<p>You probably want to check out <a href=\"http://en.wikipedia.org/wiki/Digest_access_authentication\" rel=\"nofollow noreferrer\">Digest Authentication</a>, as used by HTTP. In fact, if your protocol is over HTTP, you can skip writing your own and just use or implement this.</p>\n" }, { "answer_id": 190906, "author": "axel_c", "author_id": 20272, "author_profile": "https://Stackoverflow.com/users/20272", "pm_score": 0, "selected": false, "text": "<p>public key encryption? Use the server's public key to encrypt the password.</p>\n" }, { "answer_id": 190910, "author": "SharePoint Newbie", "author_id": 21586, "author_profile": "https://Stackoverflow.com/users/21586", "pm_score": 0, "selected": false, "text": "<p>Although it is never a good solution to roll out your own cryptographic protocol, and it is something I would not suggest....</p>\n\n<p>To overcome the problem that you are facing...\nF - A function which takes in the password and a pseudorandom monotonically increasing value and returns a number. For e.g. Hash(Hash(Password) ^ Timestamp)</p>\n\n<ol>\n<li>Server : Ask for Challenge, Send (Timestamp). Remember Last Timestamp Sent.</li>\n<li>Client, Send Response (Send F(Password, Timestamp) and Timestamp)</li>\n<li>Server: Check Client by using Hash(Password) and Timestamp sent by the client (> Timestamp sent in Challenge).</li>\n<li>If Client is correct, grant access.</li>\n<li>Ensure present timestamp is greater than all client sent timestamps before next challenge to prevent replay attacks.</li>\n</ol>\n\n<p>Kind regards,\nAshish Sharma</p>\n" }, { "answer_id": 1757941, "author": "Paul Nathan", "author_id": 26227, "author_profile": "https://Stackoverflow.com/users/26227", "pm_score": 0, "selected": false, "text": "<p>I believe the Diffie-hellman is a well-known and solid key exchange protocol?</p>\n" } ]
2008/10/09
[ "https://Stackoverflow.com/questions/188043", "https://Stackoverflow.com", "https://Stackoverflow.com/users/366094/" ]
Ok guys just a small game: I have some specifications for a project. At some point they ask for the following to encrypt a password over the net, saying that it is a challenge response protocol: ``` CLIENT ----------------------------- SERVER (1)ask for challenge --------------> (2) <---------------------------- send SHA1 taken from the time (this is the challenge) (3) make SHA1 xor PASSWORD --------> if it's equal to SHA1 xor stored password (4) <---------------------------- Grant access ``` For those who don't know it SHA stands for Secure Hashing Algorithm, a standard algorithm for cryptography. I hope it's clear. Question is: If I sniff packets 2 and 3 (the "challenge" and the "challenge xor password", I do have the actual password just with another xor between them both!?!? There is other way to implement this kind of protocol??
How about the following: 1. Server sends a random challenge 2. Client sends SHA1 checksum of (challenge+password) 3. Servers compares against SHA1 checksum of (challenge+stored password)
188,057
<p>Quick question. What do you think, I have a few sites that use a 3 level drop-down menu that will be broken if IE8 released with its current CSS standards in IE8 beta2. So do I take the time to redo those drop downs now? I realize that the way they rendered CSS changed completely between beta 1 and 2, but 2 was/is supposed the be a general use beta and seeing as it is the final beta you would think something as crucial as CSS rendering would have been touched up to work properly.</p> <p>So what do you think, do you wait until 80% (random statistic) of ie7 users automatically update to IE8 and then worry about a broken navigation menu if it still exists. Or do you waste the time now. </p> <p>... if I had it my way all web developers would just make sure that their page did not work in IE8 and then Microsoft would be forced to properly handle CSS.... But I don't usually get things my way.</p>
[ { "answer_id": 188066, "author": "Gabriel Isenberg", "author_id": 1473493, "author_profile": "https://Stackoverflow.com/users/1473493", "pm_score": 4, "selected": true, "text": "<p>You can add the meta tag to force IE7 compatible rendering. Your site continues to work, no changes are made to the web site and life is happy for everyone.</p>\n\n<p>That said, i'm curious about the \"forced to properly handle CSS\" bit; IE8 has been pretty big win for CSS standards, but I could be missing the bandwagon. ;)</p>\n\n<p>HTML change necessary to force emulated IE7 rendering involves adding a meta tag immediately after the head node.</p>\n\n<pre><code>&lt;head&gt;\n &lt;meta http-equiv=\"X-UA-Compatible\" content=\"IE=EmulateIE7\"/&gt;\n ...\n&lt;/head&gt;\n</code></pre>\n" }, { "answer_id": 188069, "author": "Mitchel Sellers", "author_id": 13279, "author_profile": "https://Stackoverflow.com/users/13279", "pm_score": 0, "selected": false, "text": "<p>Personally I find that it really depends on the audience, and the level of effort needed to fix the issue.</p>\n\n<p>If I can make a quick, couple hour fix to make it compliant, even if it is for a small subset of users, great! However, if it is much more involved, then I start to balance the potential adoption rate, the potential for Microsoft to change the behavior again, etc.</p>\n\n<p>Will MS change the CSS? I don't think anyone really knows that answer....</p>\n" }, { "answer_id": 188073, "author": "tloach", "author_id": 14092, "author_profile": "https://Stackoverflow.com/users/14092", "pm_score": 0, "selected": false, "text": "<p>I would wait until they release - maybe make a simpler version that you can quickly switch to for IE8 just in case, but don't trust anything you see in a beta version.</p>\n" } ]
2008/10/09
[ "https://Stackoverflow.com/questions/188057", "https://Stackoverflow.com", "https://Stackoverflow.com/users/19226/" ]
Quick question. What do you think, I have a few sites that use a 3 level drop-down menu that will be broken if IE8 released with its current CSS standards in IE8 beta2. So do I take the time to redo those drop downs now? I realize that the way they rendered CSS changed completely between beta 1 and 2, but 2 was/is supposed the be a general use beta and seeing as it is the final beta you would think something as crucial as CSS rendering would have been touched up to work properly. So what do you think, do you wait until 80% (random statistic) of ie7 users automatically update to IE8 and then worry about a broken navigation menu if it still exists. Or do you waste the time now. ... if I had it my way all web developers would just make sure that their page did not work in IE8 and then Microsoft would be forced to properly handle CSS.... But I don't usually get things my way.
You can add the meta tag to force IE7 compatible rendering. Your site continues to work, no changes are made to the web site and life is happy for everyone. That said, i'm curious about the "forced to properly handle CSS" bit; IE8 has been pretty big win for CSS standards, but I could be missing the bandwagon. ;) HTML change necessary to force emulated IE7 rendering involves adding a meta tag immediately after the head node. ``` <head> <meta http-equiv="X-UA-Compatible" content="IE=EmulateIE7"/> ... </head> ```
188,098
<p>I have a problem when an unhandeld exception occurs while debugging a WinForm VB.NET project.</p> <p>The problem is that my application terminates and I have to start the application again, instead of retrying the action as was the case in VS2003</p> <p>The unhandeld exception is implemented in the new My.MyApplication class found in ApplicationEvents.vb</p> <pre><code>Private Sub MyApplication_UnhandledException(ByVal sender As Object, ByVal e As Microsoft.VisualBasic.ApplicationServices.UnhandledExceptionEventArgs) Handles Me.UnhandledException Dim handler As New GlobalErrorHandler() handler.HandleError(e.Exception) e.ExitApplication = False End Sub </code></pre> <p>Note: handler.HandleError just shows a dialog box and logs the error to a log file.</p> <p>I also tried the following code that used to work in VS2003 but it results in the same behaviour when run in VS2008:</p> <pre><code> AddHandler System.Windows.Forms.Application.ThreadException, AddressOf OnApplicationErrorHandler AddHandler AppDomain.CurrentDomain.UnhandledException, AddressOf OnUnhandledExceptionHandler </code></pre> <p>OnApplicationErrorHandler and OnUnhandledExceptionHandler does the same as handle.HandleError</p> <p>Running the application outside VS2008 results in the expected behaviour (the application doesn't terminate) but it is increasing our test cycle during debugging.</p> <p><strong>Update:</strong> I have added sample code in my answer to demonstrate this problem in C#</p>
[ { "answer_id": 188817, "author": "Jeffrey", "author_id": 3259, "author_profile": "https://Stackoverflow.com/users/3259", "pm_score": 0, "selected": false, "text": "<p>I'm not sure about VS2008, but I had the same issue for awhile in VS2005. It turns out I just had to go to Debug->Exceptions (or Crtl + Alt + E) and make sure that all the Thrown boxes are unchecked, but all the User-unhandled boxes are checked.</p>\n\n<p>You may have something different and funky going on with the code you have, but it may fix this behavior.</p>\n" }, { "answer_id": 190244, "author": "Philip Fourie", "author_id": 11123, "author_profile": "https://Stackoverflow.com/users/11123", "pm_score": 1, "selected": false, "text": "<p>OK I have done more work on this but still don't have an answer.\nI found that this problem is not only related to VB.NET but also to C#</p>\n\n<p>Here is simple C# program that demonstrates the problem:</p>\n\n<pre><code>using System;\nusing System.Windows.Forms;\nnamespace TestCSharpUnhandledException\n{\n public partial class Form1 : Form\n {\n public Form1()\n {\n InitializeComponent();\n\n Application.ThreadException += new System.Threading.ThreadExceptionEventHandler(Application_ThreadException);\n AppDomain.CurrentDomain.UnhandledException += new UnhandledExceptionEventHandler(CurrentDomain_UnhandledException);\n }\n\n void CurrentDomain_UnhandledException(object sender, UnhandledExceptionEventArgs e)\n {\n MessageBox.Show(\"Oops an unhandled exception, terminating:\" + e.IsTerminating); \n }\n\n void Application_ThreadException(object sender, System.Threading.ThreadExceptionEventArgs e)\n {\n MessageBox.Show(\"Oops an unhandled thread exception\");\n }\n\n private void button1_Click(object sender, EventArgs e)\n {\n throw new Exception(\"Dummy unhandled exception\");\n }\n }\n}\n</code></pre>\n\n<p>What I found interesting is debugging in <strong>VS the UnhandledException</strong> event is thrown but running the application outside VS causes the <strong>ThreadException</strong> to fire.</p>\n\n<p>Also inside VS the e.IsTerminating is set to true, ultimately I want this to be false. (This is a read only property)</p>\n" }, { "answer_id": 190269, "author": "Philip Fourie", "author_id": 11123, "author_profile": "https://Stackoverflow.com/users/11123", "pm_score": 2, "selected": true, "text": "<p>Ok I found the answer to this issue in this blog post: <a href=\"http://www.julmar.com/blog/mark/PermaLink,guid,f733e261-5d39-4ca1-be1a-c422f3cf1f1b.aspx\" rel=\"nofollow noreferrer\">Handling \"Unhandled Exceptions\" in .NET 2.0</a></p>\n\n<p>Thank you Mark!</p>\n\n<p>The short answer is: </p>\n\n<pre><code>Application.SetUnhandledExceptionMode(UnhandledExceptionMode.CatchException);\n</code></pre>\n\n<p>This causes the same behaviour during debug and run mode. Resulting in VS not closing while debugging</p>\n" } ]
2008/10/09
[ "https://Stackoverflow.com/questions/188098", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11123/" ]
I have a problem when an unhandeld exception occurs while debugging a WinForm VB.NET project. The problem is that my application terminates and I have to start the application again, instead of retrying the action as was the case in VS2003 The unhandeld exception is implemented in the new My.MyApplication class found in ApplicationEvents.vb ``` Private Sub MyApplication_UnhandledException(ByVal sender As Object, ByVal e As Microsoft.VisualBasic.ApplicationServices.UnhandledExceptionEventArgs) Handles Me.UnhandledException Dim handler As New GlobalErrorHandler() handler.HandleError(e.Exception) e.ExitApplication = False End Sub ``` Note: handler.HandleError just shows a dialog box and logs the error to a log file. I also tried the following code that used to work in VS2003 but it results in the same behaviour when run in VS2008: ``` AddHandler System.Windows.Forms.Application.ThreadException, AddressOf OnApplicationErrorHandler AddHandler AppDomain.CurrentDomain.UnhandledException, AddressOf OnUnhandledExceptionHandler ``` OnApplicationErrorHandler and OnUnhandledExceptionHandler does the same as handle.HandleError Running the application outside VS2008 results in the expected behaviour (the application doesn't terminate) but it is increasing our test cycle during debugging. **Update:** I have added sample code in my answer to demonstrate this problem in C#
Ok I found the answer to this issue in this blog post: [Handling "Unhandled Exceptions" in .NET 2.0](http://www.julmar.com/blog/mark/PermaLink,guid,f733e261-5d39-4ca1-be1a-c422f3cf1f1b.aspx) Thank you Mark! The short answer is: ``` Application.SetUnhandledExceptionMode(UnhandledExceptionMode.CatchException); ``` This causes the same behaviour during debug and run mode. Resulting in VS not closing while debugging
188,099
<p>Howdy. Consider the following:</p> <pre><code>SQL&gt; DECLARE 2 b1 BOOLEAN; 3 b2 BOOLEAN; 4 FUNCTION checkit RETURN BOOLEAN IS 5 BEGIN 6 dbms_output.put_line('inside checkit'); 7 RETURN TRUE; 8 END checkit; 9 10 PROCEDURE outp(n VARCHAR2, p BOOLEAN) IS 11 BEGIN 12 IF p THEN 13 dbms_output.put_line(n||' is true'); 14 ELSE 15 dbms_output.put_line(n||' is false'); 16 END IF; 17 END; 18 BEGIN 19 b1 := TRUE OR checkit; 20 outp('b1',b1); 21 b2 := checkit OR TRUE; 22 outp('b2',b2); 23 END; 24 / b1 is true inside checkit b2 is true PL/SQL procedure successfully completed SQL&gt; </code></pre> <p>Notice that the results of the OR statements are order dependent. If I place the function call first, then the function is executed regardless of the value of the other term. It appears that an OR statement is evaluated left to right until a TRUE is obtained, at which point processing stops and the result it TRUE. </p> <p>My question is, is this something I can rely on? Or could this behavior change in future releases of PL/SQL? If it could change, is there a way to force the function to be evaluated that I can rely on (without creating another variable and using a separate assignment statement)?</p>
[ { "answer_id": 188107, "author": "Justin Cave", "author_id": 10397, "author_profile": "https://Stackoverflow.com/users/10397", "pm_score": 4, "selected": true, "text": "<p>Yes. PL/SQL performs <a href=\"http://download.oracle.com/docs/cd/B19306_01/appdev.102/b14261/fundamentals.htm#sthref481\" rel=\"noreferrer\">short circuit evaluation</a> of logical expressions from left to right.</p>\n" }, { "answer_id": 188119, "author": "JosephStyons", "author_id": 672, "author_profile": "https://Stackoverflow.com/users/672", "pm_score": 0, "selected": false, "text": "<p>This is called \"short-circuit evaluation\", and it is the norm in most languages, <a href=\"http://download.oracle.com/docs/cd/B19306_01/appdev.102/b14261/fundamentals.htm#CIHGJBFD\" rel=\"nofollow noreferrer\">including PL/SQL</a>.</p>\n" }, { "answer_id": 188192, "author": "Tony Andrews", "author_id": 18747, "author_profile": "https://Stackoverflow.com/users/18747", "pm_score": 1, "selected": false, "text": "<blockquote>\n <p>If it could change, is there a way to force the function to be evaluated that I can rely on (without creating another variable and using a separate assignment statement)?</p>\n</blockquote>\n\n<p>If you require that the function must be evaulated even when it is logically superfluous to do so, that implies that it does something other than simply return TRUE or FALSE, e.g. perhaps it updates a table. It isn't considered good practice for PL/SQL functions to have such \"side effects\". </p>\n" }, { "answer_id": 188696, "author": "David Aldridge", "author_id": 6742, "author_profile": "https://Stackoverflow.com/users/6742", "pm_score": 1, "selected": false, "text": "<p>In the documentation it states that short circuit evaluation applies to IF, CASE and CASE expressions: I'd bet that it also applies in the example that you quote but it's technically not documented that it does so. It might be worth raising a ticket with Oracle on this behaviour to get it confirmed.</p>\n" }, { "answer_id": 598591, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 0, "selected": false, "text": "<p>It evaluates OR statements from left to right and AND statements from right to left. I did not find myself any documentation of it. </p>\n" }, { "answer_id": 2385362, "author": "mutoss", "author_id": 214472, "author_profile": "https://Stackoverflow.com/users/214472", "pm_score": 0, "selected": false, "text": "<p>what exactly do you mean by \"..and AND statements from right to left\"? <br>\nthis is from the oracle documentation=><br></p>\n\n<p><B>In the following example, notice that when valid has the value FALSE, the whole expression yields FALSE regardless of the value of done:</p>\n\n<p>valid AND done</B></p>\n\n<p>you can check the order in the following example:</p>\n\n<p>DECLARE <br>\n b1 BOOLEAN;<br>\n b2 BOOLEAN;<br></p>\n\n<p>FUNCTION checkit (v NUMBER)<br>\n RETURN BOOLEAN<br>\n IS<br>\n BEGIN<br>\n DBMS_OUTPUT.put_line ('inside checkit:' || v);<br>\n RETURN TRUE;<br>\n END checkit;<br></p>\n\n<p>PROCEDURE outp (n VARCHAR2, p BOOLEAN)<br>\n IS<br>\n BEGIN<br>\n IF p<br>\n THEN<br>\n DBMS_OUTPUT.put_line (n || ' is true');<br>\n ELSE<br>\n DBMS_OUTPUT.put_line (n || ' is false');<br>\n END IF;<br>\n END;<br>\nBEGIN<br>\n b1 := checkit (1) AND checkit (2);<br>\n outp ('b1', b1);<br>\n b2 := checkit (3) AND checkit (4);<br>\n outp ('b2', b2);<br>\nEND;<br></p>\n\n<hr>\n\n<p>inside checkit:1<br>\ninside checkit:2<br>\nb1 is true<br>\ninside checkit:3<br>\ninside checkit:4<br>\nb2 is true<br></p>\n" } ]
2008/10/09
[ "https://Stackoverflow.com/questions/188099", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8670/" ]
Howdy. Consider the following: ``` SQL> DECLARE 2 b1 BOOLEAN; 3 b2 BOOLEAN; 4 FUNCTION checkit RETURN BOOLEAN IS 5 BEGIN 6 dbms_output.put_line('inside checkit'); 7 RETURN TRUE; 8 END checkit; 9 10 PROCEDURE outp(n VARCHAR2, p BOOLEAN) IS 11 BEGIN 12 IF p THEN 13 dbms_output.put_line(n||' is true'); 14 ELSE 15 dbms_output.put_line(n||' is false'); 16 END IF; 17 END; 18 BEGIN 19 b1 := TRUE OR checkit; 20 outp('b1',b1); 21 b2 := checkit OR TRUE; 22 outp('b2',b2); 23 END; 24 / b1 is true inside checkit b2 is true PL/SQL procedure successfully completed SQL> ``` Notice that the results of the OR statements are order dependent. If I place the function call first, then the function is executed regardless of the value of the other term. It appears that an OR statement is evaluated left to right until a TRUE is obtained, at which point processing stops and the result it TRUE. My question is, is this something I can rely on? Or could this behavior change in future releases of PL/SQL? If it could change, is there a way to force the function to be evaluated that I can rely on (without creating another variable and using a separate assignment statement)?
Yes. PL/SQL performs [short circuit evaluation](http://download.oracle.com/docs/cd/B19306_01/appdev.102/b14261/fundamentals.htm#sthref481) of logical expressions from left to right.
188,114
<p>I'm trying to write a log file from an ASP.NET application under IIS7, but keep getting the following exception:</p> <blockquote> <p>UnauthorizedAccessException "Access to the path 'C:\Users\Brady\Exports' is denied."</p> </blockquote> <p>I have given write access to the iis_iusrs, iis_wpg, and aspnet users, based on various advices found by Google, but still get the error. Can someone please explain how I can create a log file in that directory, or, will creating a log directory under the web application itself automatically allow writing the file, and is this not perhaps a better solution?</p>
[ { "answer_id": 188125, "author": "Mitchel Sellers", "author_id": 13279, "author_profile": "https://Stackoverflow.com/users/13279", "pm_score": 3, "selected": true, "text": "<p>You need to grant permission to one of the following accounts</p>\n\n<pre><code>ASPNET - Win XP and Win 2000\nNETWORK SERVICE - Win Vista and 2003\n</code></pre>\n\n<p>These are the defaults, if the application pool has been configured for a different process account then you would need to work with that specific account.</p>\n" }, { "answer_id": 188132, "author": "Pseudo Masochist", "author_id": 8529, "author_profile": "https://Stackoverflow.com/users/8529", "pm_score": 0, "selected": false, "text": "<p>I think Mitchel's got it, but I'll add that troubleshooting these kinds of things is infinitely easier using SysInternals' <a href=\"http://technet.microsoft.com/en-us/sysinternals/bb896645.aspx\" rel=\"nofollow noreferrer\">Process Monitor</a> (<a href=\"http://technet.microsoft.com/en-us/sysinternals/bb896642.aspx\" rel=\"nofollow noreferrer\">FileMon</a> for legacy systems) to take away the guesswork/trial and error.</p>\n" }, { "answer_id": 197246, "author": "icelava", "author_id": 2663, "author_profile": "https://Stackoverflow.com/users/2663", "pm_score": 0, "selected": false, "text": "<p>If you are Impersonating some other user in ASP.NET, that user account must have permission to write to that directory. I highly recommend <em>not</em> setting a user's personal folder path as the location to store a web application's log or data. That requires the ASP.NET worker process account to have access to that user's private folder, if they are not the same account.</p>\n\n<p>Allocating a common area, for example D:\\webapps\\logapp\\logfiles, is encouraged. With the appropriate permissions given, of course.</p>\n" } ]
2008/10/09
[ "https://Stackoverflow.com/questions/188114", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8741/" ]
I'm trying to write a log file from an ASP.NET application under IIS7, but keep getting the following exception: > > UnauthorizedAccessException > "Access to the path 'C:\Users\Brady\Exports' is denied." > > > I have given write access to the iis\_iusrs, iis\_wpg, and aspnet users, based on various advices found by Google, but still get the error. Can someone please explain how I can create a log file in that directory, or, will creating a log directory under the web application itself automatically allow writing the file, and is this not perhaps a better solution?
You need to grant permission to one of the following accounts ``` ASPNET - Win XP and Win 2000 NETWORK SERVICE - Win Vista and 2003 ``` These are the defaults, if the application pool has been configured for a different process account then you would need to work with that specific account.
188,118
<p>I've tried this, but it doesn't work:</p> <pre><code>col * format a20000 </code></pre> <p>Do I really have to list every column specifically? That is a huge pain in the arse.</p>
[ { "answer_id": 188135, "author": "someguy", "author_id": 8913, "author_profile": "https://Stackoverflow.com/users/8913", "pm_score": 5, "selected": false, "text": "<p>Never mind, figured it out:</p>\n\n<pre><code>set wrap off\nset linesize 3000 -- (or to a sufficiently large value to hold your results page)\n</code></pre>\n\n<p>Which I found by:</p>\n\n<pre><code>show all\n</code></pre>\n\n<p>And looking for some option that seemed relevant.</p>\n" }, { "answer_id": 188144, "author": "Patrick Cuff", "author_id": 7903, "author_profile": "https://Stackoverflow.com/users/7903", "pm_score": 5, "selected": false, "text": "<p>I use a generic query I call \"dump\" (why? I don't know) that looks like this:</p>\n\n<pre><code>SET NEWPAGE NONE\nSET PAGESIZE 0\nSET SPACE 0\nSET LINESIZE 16000\nSET ECHO OFF\nSET FEEDBACK OFF\nSET VERIFY OFF\nSET HEADING OFF\nSET TERMOUT OFF\nSET TRIMOUT ON\nSET TRIMSPOOL ON\nSET COLSEP |\n\nspool &amp;1..txt\n\n@@&amp;1\n\nspool off\nexit\n</code></pre>\n\n<p>I then call SQL*Plus passing the actual SQL script I want to run as an argument:</p>\n\n<pre><code>sqlplus -S user/password@database @dump.sql my_real_query.sql\n</code></pre>\n\n<p>The result is written to a file </p>\n\n<blockquote>\n <p><code>my_real_query.sql.txt</code></p>\n</blockquote>\n\n<p>.</p>\n" }, { "answer_id": 44264587, "author": "Camilo Peña", "author_id": 6851347, "author_profile": "https://Stackoverflow.com/users/6851347", "pm_score": 0, "selected": false, "text": "<pre class=\"lang-sql prettyprint-override\"><code>set WRAP OFF\nset PAGESIZE 0\n</code></pre>\n\n<p>Try using those settings.</p>\n" }, { "answer_id": 48007491, "author": "Aziz Zoaib", "author_id": 9138097, "author_profile": "https://Stackoverflow.com/users/9138097", "pm_score": 1, "selected": false, "text": "<pre><code>set linesize 3000\n\nset wrap off\n\nset termout off\n\nset pagesize 0 embedded on\n\nset trimspool on\n</code></pre>\n\n<p>Try with all above values.</p>\n" } ]
2008/10/09
[ "https://Stackoverflow.com/questions/188118", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8913/" ]
I've tried this, but it doesn't work: ``` col * format a20000 ``` Do I really have to list every column specifically? That is a huge pain in the arse.
Never mind, figured it out: ``` set wrap off set linesize 3000 -- (or to a sufficiently large value to hold your results page) ``` Which I found by: ``` show all ``` And looking for some option that seemed relevant.
188,120
<p>So .NET 3.0/3.5 provides us with lots of new ways to query, sort, and manipulate data, thanks to all the neat functions supplied with LINQ. Sometimes, I need to compare user-defined types that don't have a built-in comparison operator. In many cases, the comparison is really simple -- something like foo1.key ?= foo2.key. Rather than creating a new IEqualityComparer for the type, can I simply specify the comparison inline using anonymous delegates/lambda functions? Something like:</p> <pre><code>var f1 = ..., f2 = ...; var f3 = f1.Except( f2, new IEqualityComparer( (Foo a, Foo b) => a.key.CompareTo(b.key) ) ); </code></pre> <p>I'm pretty sure the above doesn't actually work. I just don't want to have to make something as "heavy" as a whole class just to tell the program how to compare apples to apples.</p>
[ { "answer_id": 188130, "author": "Jon Skeet", "author_id": 22656, "author_profile": "https://Stackoverflow.com/users/22656", "pm_score": 7, "selected": true, "text": "<p>My <a href=\"http://pobox.com/~skeet/csharp/miscutil\" rel=\"noreferrer\">MiscUtil</a> library contains a ProjectionComparer to build an IComparer&lt;T> from a projection delegate. It would be the work of 10 minutes to make a ProjectionEqualityComparer to do the same thing.</p>\n\n<p>EDIT: Here's the code for ProjectionEqualityComparer:</p>\n\n<pre><code>using System;\nusing System.Collections.Generic;\n\n/// &lt;summary&gt;\n/// Non-generic class to produce instances of the generic class,\n/// optionally using type inference.\n/// &lt;/summary&gt;\npublic static class ProjectionEqualityComparer\n{\n /// &lt;summary&gt;\n /// Creates an instance of ProjectionEqualityComparer using the specified projection.\n /// &lt;/summary&gt;\n /// &lt;typeparam name=\"TSource\"&gt;Type parameter for the elements to be compared&lt;/typeparam&gt;\n /// &lt;typeparam name=\"TKey\"&gt;Type parameter for the keys to be compared,\n /// after being projected from the elements&lt;/typeparam&gt;\n /// &lt;param name=\"projection\"&gt;Projection to use when determining the key of an element&lt;/param&gt;\n /// &lt;returns&gt;A comparer which will compare elements by projecting \n /// each element to its key, and comparing keys&lt;/returns&gt;\n public static ProjectionEqualityComparer&lt;TSource, TKey&gt; Create&lt;TSource, TKey&gt;(Func&lt;TSource, TKey&gt; projection)\n {\n return new ProjectionEqualityComparer&lt;TSource, TKey&gt;(projection);\n }\n\n /// &lt;summary&gt;\n /// Creates an instance of ProjectionEqualityComparer using the specified projection.\n /// The ignored parameter is solely present to aid type inference.\n /// &lt;/summary&gt;\n /// &lt;typeparam name=\"TSource\"&gt;Type parameter for the elements to be compared&lt;/typeparam&gt;\n /// &lt;typeparam name=\"TKey\"&gt;Type parameter for the keys to be compared,\n /// after being projected from the elements&lt;/typeparam&gt;\n /// &lt;param name=\"ignored\"&gt;Value is ignored - type may be used by type inference&lt;/param&gt;\n /// &lt;param name=\"projection\"&gt;Projection to use when determining the key of an element&lt;/param&gt;\n /// &lt;returns&gt;A comparer which will compare elements by projecting\n /// each element to its key, and comparing keys&lt;/returns&gt;\n public static ProjectionEqualityComparer&lt;TSource, TKey&gt; Create&lt;TSource, TKey&gt;\n (TSource ignored,\n Func&lt;TSource, TKey&gt; projection)\n {\n return new ProjectionEqualityComparer&lt;TSource, TKey&gt;(projection);\n }\n\n}\n\n/// &lt;summary&gt;\n/// Class generic in the source only to produce instances of the \n/// doubly generic class, optionally using type inference.\n/// &lt;/summary&gt;\npublic static class ProjectionEqualityComparer&lt;TSource&gt;\n{\n /// &lt;summary&gt;\n /// Creates an instance of ProjectionEqualityComparer using the specified projection.\n /// &lt;/summary&gt;\n /// &lt;typeparam name=\"TKey\"&gt;Type parameter for the keys to be compared,\n /// after being projected from the elements&lt;/typeparam&gt;\n /// &lt;param name=\"projection\"&gt;Projection to use when determining the key of an element&lt;/param&gt;\n /// &lt;returns&gt;A comparer which will compare elements by projecting each element to its key,\n /// and comparing keys&lt;/returns&gt; \n public static ProjectionEqualityComparer&lt;TSource, TKey&gt; Create&lt;TKey&gt;(Func&lt;TSource, TKey&gt; projection)\n {\n return new ProjectionEqualityComparer&lt;TSource, TKey&gt;(projection);\n }\n}\n\n/// &lt;summary&gt;\n/// Comparer which projects each element of the comparison to a key, and then compares\n/// those keys using the specified (or default) comparer for the key type.\n/// &lt;/summary&gt;\n/// &lt;typeparam name=\"TSource\"&gt;Type of elements which this comparer \n/// will be asked to compare&lt;/typeparam&gt;\n/// &lt;typeparam name=\"TKey\"&gt;Type of the key projected\n/// from the element&lt;/typeparam&gt;\npublic class ProjectionEqualityComparer&lt;TSource, TKey&gt; : IEqualityComparer&lt;TSource&gt;\n{\n readonly Func&lt;TSource, TKey&gt; projection;\n readonly IEqualityComparer&lt;TKey&gt; comparer;\n\n /// &lt;summary&gt;\n /// Creates a new instance using the specified projection, which must not be null.\n /// The default comparer for the projected type is used.\n /// &lt;/summary&gt;\n /// &lt;param name=\"projection\"&gt;Projection to use during comparisons&lt;/param&gt;\n public ProjectionEqualityComparer(Func&lt;TSource, TKey&gt; projection)\n : this(projection, null)\n {\n }\n\n /// &lt;summary&gt;\n /// Creates a new instance using the specified projection, which must not be null.\n /// &lt;/summary&gt;\n /// &lt;param name=\"projection\"&gt;Projection to use during comparisons&lt;/param&gt;\n /// &lt;param name=\"comparer\"&gt;The comparer to use on the keys. May be null, in\n /// which case the default comparer will be used.&lt;/param&gt;\n public ProjectionEqualityComparer(Func&lt;TSource, TKey&gt; projection, IEqualityComparer&lt;TKey&gt; comparer)\n {\n if (projection == null)\n {\n throw new ArgumentNullException(\"projection\");\n }\n this.comparer = comparer ?? EqualityComparer&lt;TKey&gt;.Default;\n this.projection = projection;\n }\n\n /// &lt;summary&gt;\n /// Compares the two specified values for equality by applying the projection\n /// to each value and then using the equality comparer on the resulting keys. Null\n /// references are never passed to the projection.\n /// &lt;/summary&gt;\n public bool Equals(TSource x, TSource y)\n {\n if (x == null &amp;&amp; y == null)\n {\n return true;\n }\n if (x == null || y == null)\n {\n return false;\n }\n return comparer.Equals(projection(x), projection(y));\n }\n\n /// &lt;summary&gt;\n /// Produces a hash code for the given value by projecting it and\n /// then asking the equality comparer to find the hash code of\n /// the resulting key.\n /// &lt;/summary&gt;\n public int GetHashCode(TSource obj)\n {\n if (obj == null)\n {\n throw new ArgumentNullException(\"obj\");\n }\n return comparer.GetHashCode(projection(obj));\n }\n}\n</code></pre>\n\n<p>And here's a sample use:</p>\n\n<pre><code>var f3 = f1.Except(f2, ProjectionEqualityComparer&lt;Foo&gt;.Create(a =&gt; a.key));\n</code></pre>\n" }, { "answer_id": 743228, "author": "Sam Saffron", "author_id": 17174, "author_profile": "https://Stackoverflow.com/users/17174", "pm_score": 3, "selected": false, "text": "<p>I find providing extra helpers on IEnumerable is a cleaner way to do this.</p>\n\n<p>See: <a href=\"https://stackoverflow.com/questions/742682/distinct-list-of-objects-based-on-an-arbitrary-key-in-linq/742784#742784\">this question</a></p>\n\n<p>So you could have: </p>\n\n<pre><code>var f3 = f1.Except(\n f2, \n (a, b) =&gt; a.key.CompareTo(b.key)\n );\n</code></pre>\n\n<p>If you define the extension methods properly</p>\n" }, { "answer_id": 10720211, "author": "mike", "author_id": 495956, "author_profile": "https://Stackoverflow.com/users/495956", "pm_score": 5, "selected": false, "text": "<p>here is a simple helper class that should do what you want</p>\n\n<pre><code>public class EqualityComparer&lt;T&gt; : IEqualityComparer&lt;T&gt;\n{\n public EqualityComparer(Func&lt;T, T, bool&gt; cmp)\n {\n this.cmp = cmp;\n }\n public bool Equals(T x, T y)\n {\n return cmp(x, y);\n }\n\n public int GetHashCode(T obj)\n {\n return obj.GetHashCode();\n }\n\n public Func&lt;T, T, bool&gt; cmp { get; set; }\n}\n</code></pre>\n\n<p>you can use it like this:</p>\n\n<pre><code>processed.Union(suburbs, new EqualityComparer&lt;Suburb&gt;((s1, s2)\n =&gt; s1.SuburbId == s2.SuburbId));\n</code></pre>\n" }, { "answer_id": 21320500, "author": "Jeremy Thomas", "author_id": 115352, "author_profile": "https://Stackoverflow.com/users/115352", "pm_score": 3, "selected": false, "text": "<p>This project does something similar: <a href=\"http://linqcomparer.codeplex.com\">AnonymousComparer - lambda compare selector for Linq</a>, it has Extensions for LINQ Standard Query Operators as well.</p>\n" }, { "answer_id": 29393382, "author": "Tamas Ionut", "author_id": 920202, "author_profile": "https://Stackoverflow.com/users/920202", "pm_score": 3, "selected": false, "text": "<p>Why not something like: </p>\n\n<pre><code> public class Comparer&lt;T&gt; : IEqualityComparer&lt;T&gt;\n {\n private readonly Func&lt;T, T, bool&gt; _equalityComparer;\n\n public Comparer(Func&lt;T, T, bool&gt; equalityComparer)\n {\n _equalityComparer = equalityComparer;\n }\n\n public bool Equals(T first, T second)\n {\n return _equalityComparer(first, second);\n }\n\n public int GetHashCode(T value)\n {\n return value.GetHashCode();\n }\n }\n</code></pre>\n\n<p>and then you could do for instance something like (e.g. in the case of <code>Intersect</code> in <code>IEnumerable&lt;T&gt;</code>):</p>\n\n<pre><code>list.Intersect(otherList, new Comparer&lt;T&gt;( (x, y) =&gt; x.Property == y.Property));\n</code></pre>\n\n<p>The <code>Comparer</code> class can be put in a utilities project and used wherever is needed.</p>\n\n<p>I only now see the Sam Saffron's answer (which is very similar to this one).</p>\n" }, { "answer_id": 33303472, "author": "mheyman", "author_id": 240845, "author_profile": "https://Stackoverflow.com/users/240845", "pm_score": 1, "selected": false, "text": "<p>For small sets, you can do:</p>\n\n<pre><code>f3 = f1.Where(x1 =&gt; f2.All(x2 =&gt; x2.key != x1.key));\n</code></pre>\n\n<p>For large sets, you will want something more efficient in the search like:</p>\n\n<pre><code>var tmp = new HashSet&lt;string&gt;(f2.Select(f =&gt; f.key));\nf3 = f1.Where(f =&gt; tmp.Add(f.key));\n</code></pre>\n\n<p>But, here, the <code>Type</code> of <em>key</em> must implement <code>IEqualityComparer</code> (above I assumed it was a <code>string</code>). So, this doesn't really answer your question about using a lambda in this situation but it does use less code then some of the answers that do.</p>\n\n<p>You might rely on the optimizer and shorten the second solution to:</p>\n\n<pre><code>f3 = f1.Where(x1 =&gt; (new HashSet&lt;string&gt;(f2.Select(x2 =&gt; x2.key))).Add(x1.key));\n</code></pre>\n\n<p>but, I haven't run tests to know if it runs at the same speed. And that one liner might be too clever to maintain.</p>\n" }, { "answer_id": 51548721, "author": "kofifus", "author_id": 460084, "author_profile": "https://Stackoverflow.com/users/460084", "pm_score": -1, "selected": false, "text": "<p>Like the other answers but more concise c# 7:</p>\n\n<pre><code>public class LambdaComparer&lt;T&gt; : IEqualityComparer&lt;T&gt; {\n private readonly Func&lt;T, T, bool&gt; lambdaComparer;\n private readonly Func&lt;T, int&gt; lambdaHash;\n public LambdaComparer(Func&lt;T, T, bool&gt; lambdaComparer) : this(lambdaComparer, o =&gt; o.GetHashCode()) {}\n public LambdaComparer(Func&lt;T, T, bool&gt; lambdaComparer, Func&lt;T, int&gt; lambdaHash) { this.lambdaComparer = lambdaComparer; this.lambdaHash = lambdaHash; }\n public bool Equals(T x, T y) =&gt; lambdaComparer is null ? false : lambdaComparer(x, y);\n public int GetHashCode(T obj) =&gt; lambdaHash is null ? 0 : lambdaHash(obj);\n}\n</code></pre>\n\n<p>then:</p>\n\n<pre><code>var a=List&lt;string&gt; { \"a\", \"b\" };\nvar b=List&lt;string&gt; { \"a\", \"*\" };\nreturn a.SequenceEquals(b, new LambdaComparer&lt;string&gt;((s1, s2) =&gt; s1 is null ? s2 is null : s1 == s2 || s2 == \"*\"); \n</code></pre>\n" }, { "answer_id": 56561286, "author": "OriolBG", "author_id": 2587320, "author_profile": "https://Stackoverflow.com/users/2587320", "pm_score": 1, "selected": false, "text": "<p>Building on other answers the creation of a generic comparer was the one I liked most. But I got a problem with Linq <code>Enumerable.Union</code> (<a href=\"https://learn.microsoft.com/en-us/dotnet/api/system.linq.enumerable.union\" rel=\"nofollow noreferrer\">msdn .Net reference</a>) which was that its using the GetHashCode directly without taking into account the Equals override.</p>\n\n<p>That took me to implement the Comparer as:</p>\n\n<pre><code>public class Comparer&lt;T&gt; : IEqualityComparer&lt;T&gt;\n{\n private readonly Func&lt;T, int&gt; _hashFunction;\n\n public Comparer(Func&lt;T, int&gt; hashFunction)\n {\n _hashFunction = hashFunction;\n }\n\n public bool Equals(T first, T second)\n {\n return _hashFunction(first) == _hashFunction(second);\n }\n\n public int GetHashCode(T value)\n {\n return _hashFunction(value);\n }\n}\n</code></pre>\n\n<p>Using it like this:</p>\n\n<pre><code>list.Union(otherList, new Comparer&lt;T&gt;( x =&gt; x.StringValue.GetHashCode()));\n</code></pre>\n\n<p>Note that comparison might give some false positive since information being compared is mapped to an <code>int</code> value.</p>\n" }, { "answer_id": 60283638, "author": "WhiteleyJ", "author_id": 961738, "author_profile": "https://Stackoverflow.com/users/961738", "pm_score": 3, "selected": false, "text": "<p>So I know this is a workaround to your question, but when I find that I've run into the situation you have here (Combining a list and filtering duplicates), and Distinct needs an IEquityComparer that I don't have, I usually go with a Concat -> Group -> Select.</p>\n\n<p>Original</p>\n\n<pre><code>var f1 = ...,\n f2 = ...;\nvar f3 = f1.Except(\n f2, new IEqualityComparer(\n (Foo a, Foo b) =&gt; a.key.CompareTo(b.key)\n ) );\n</code></pre>\n\n<p>New</p>\n\n<pre><code>var f1 = ...,\n f2 = ...;\nvar distinctF = f1\n .Concat(f2) // Combine the lists\n .GroupBy(x =&gt; x.key) // Group them up by our equity comparison key\n .Select(x =&gt; x.FirstOrDefault()); // Just grab one of them.\n</code></pre>\n\n<p>Note that in the GroupBy() you have the opportunity to add logic to create hybrid keys like:</p>\n\n<pre><code>.GroupBy(f =&gt; new Uri(f.Url).PathAndQuery) \n</code></pre>\n\n<p>As well as in the Select() if you want to want to specify which list the resulting item comes from you can say:</p>\n\n<pre><code>.Select(x =&gt; x.FirstOrDefault(y =&gt; f1.Contains(y))\n</code></pre>\n\n<p>Hope that helps!</p>\n" } ]
2008/10/09
[ "https://Stackoverflow.com/questions/188120", "https://Stackoverflow.com", "https://Stackoverflow.com/users/26286/" ]
So .NET 3.0/3.5 provides us with lots of new ways to query, sort, and manipulate data, thanks to all the neat functions supplied with LINQ. Sometimes, I need to compare user-defined types that don't have a built-in comparison operator. In many cases, the comparison is really simple -- something like foo1.key ?= foo2.key. Rather than creating a new IEqualityComparer for the type, can I simply specify the comparison inline using anonymous delegates/lambda functions? Something like: ``` var f1 = ..., f2 = ...; var f3 = f1.Except( f2, new IEqualityComparer( (Foo a, Foo b) => a.key.CompareTo(b.key) ) ); ``` I'm pretty sure the above doesn't actually work. I just don't want to have to make something as "heavy" as a whole class just to tell the program how to compare apples to apples.
My [MiscUtil](http://pobox.com/~skeet/csharp/miscutil) library contains a ProjectionComparer to build an IComparer<T> from a projection delegate. It would be the work of 10 minutes to make a ProjectionEqualityComparer to do the same thing. EDIT: Here's the code for ProjectionEqualityComparer: ``` using System; using System.Collections.Generic; /// <summary> /// Non-generic class to produce instances of the generic class, /// optionally using type inference. /// </summary> public static class ProjectionEqualityComparer { /// <summary> /// Creates an instance of ProjectionEqualityComparer using the specified projection. /// </summary> /// <typeparam name="TSource">Type parameter for the elements to be compared</typeparam> /// <typeparam name="TKey">Type parameter for the keys to be compared, /// after being projected from the elements</typeparam> /// <param name="projection">Projection to use when determining the key of an element</param> /// <returns>A comparer which will compare elements by projecting /// each element to its key, and comparing keys</returns> public static ProjectionEqualityComparer<TSource, TKey> Create<TSource, TKey>(Func<TSource, TKey> projection) { return new ProjectionEqualityComparer<TSource, TKey>(projection); } /// <summary> /// Creates an instance of ProjectionEqualityComparer using the specified projection. /// The ignored parameter is solely present to aid type inference. /// </summary> /// <typeparam name="TSource">Type parameter for the elements to be compared</typeparam> /// <typeparam name="TKey">Type parameter for the keys to be compared, /// after being projected from the elements</typeparam> /// <param name="ignored">Value is ignored - type may be used by type inference</param> /// <param name="projection">Projection to use when determining the key of an element</param> /// <returns>A comparer which will compare elements by projecting /// each element to its key, and comparing keys</returns> public static ProjectionEqualityComparer<TSource, TKey> Create<TSource, TKey> (TSource ignored, Func<TSource, TKey> projection) { return new ProjectionEqualityComparer<TSource, TKey>(projection); } } /// <summary> /// Class generic in the source only to produce instances of the /// doubly generic class, optionally using type inference. /// </summary> public static class ProjectionEqualityComparer<TSource> { /// <summary> /// Creates an instance of ProjectionEqualityComparer using the specified projection. /// </summary> /// <typeparam name="TKey">Type parameter for the keys to be compared, /// after being projected from the elements</typeparam> /// <param name="projection">Projection to use when determining the key of an element</param> /// <returns>A comparer which will compare elements by projecting each element to its key, /// and comparing keys</returns> public static ProjectionEqualityComparer<TSource, TKey> Create<TKey>(Func<TSource, TKey> projection) { return new ProjectionEqualityComparer<TSource, TKey>(projection); } } /// <summary> /// Comparer which projects each element of the comparison to a key, and then compares /// those keys using the specified (or default) comparer for the key type. /// </summary> /// <typeparam name="TSource">Type of elements which this comparer /// will be asked to compare</typeparam> /// <typeparam name="TKey">Type of the key projected /// from the element</typeparam> public class ProjectionEqualityComparer<TSource, TKey> : IEqualityComparer<TSource> { readonly Func<TSource, TKey> projection; readonly IEqualityComparer<TKey> comparer; /// <summary> /// Creates a new instance using the specified projection, which must not be null. /// The default comparer for the projected type is used. /// </summary> /// <param name="projection">Projection to use during comparisons</param> public ProjectionEqualityComparer(Func<TSource, TKey> projection) : this(projection, null) { } /// <summary> /// Creates a new instance using the specified projection, which must not be null. /// </summary> /// <param name="projection">Projection to use during comparisons</param> /// <param name="comparer">The comparer to use on the keys. May be null, in /// which case the default comparer will be used.</param> public ProjectionEqualityComparer(Func<TSource, TKey> projection, IEqualityComparer<TKey> comparer) { if (projection == null) { throw new ArgumentNullException("projection"); } this.comparer = comparer ?? EqualityComparer<TKey>.Default; this.projection = projection; } /// <summary> /// Compares the two specified values for equality by applying the projection /// to each value and then using the equality comparer on the resulting keys. Null /// references are never passed to the projection. /// </summary> public bool Equals(TSource x, TSource y) { if (x == null && y == null) { return true; } if (x == null || y == null) { return false; } return comparer.Equals(projection(x), projection(y)); } /// <summary> /// Produces a hash code for the given value by projecting it and /// then asking the equality comparer to find the hash code of /// the resulting key. /// </summary> public int GetHashCode(TSource obj) { if (obj == null) { throw new ArgumentNullException("obj"); } return comparer.GetHashCode(projection(obj)); } } ``` And here's a sample use: ``` var f3 = f1.Except(f2, ProjectionEqualityComparer<Foo>.Create(a => a.key)); ```
188,124
<p>I am writing a website with Visual Studio 2008 and ASP.NET 3.5. I have a masterpage set up to simplify the layout and to keep the content pages for content rather than content and layout.</p> <p>The navigation is list, css'd so it looks like a bar. In order to highlight the page on the bar, the list item needs to look like this <code>&lt;li id="current"&gt;</code>. I do not want to use <code>&lt;asp:ContentPlaceHolder&gt;</code> if I can avoid it. Is there some code I can add to each of my pages (or just to the masterpage?) to accomplish this or am I stuck using <code>&lt;asp:ContentPlaceHolder&gt;</code>'s?</p>
[ { "answer_id": 188142, "author": "Mitchel Sellers", "author_id": 13279, "author_profile": "https://Stackoverflow.com/users/13279", "pm_score": 0, "selected": false, "text": "<p>The use or non use of ContentPlaceHolder will not affect which element has the id=\"current\" set on it.</p>\n\n<p>You will have to look at some method, either in your codebehind for the master page, a javascript function or something else when rendering the menu component to properly add the id=\"current\" to the list when it is created.</p>\n" }, { "answer_id": 188152, "author": "AdamB", "author_id": 2176, "author_profile": "https://Stackoverflow.com/users/2176", "pm_score": -1, "selected": false, "text": "<p>I would use javascript to accomplish this. In css, change your #current to be a class (.current) and then have id's on each of your ListItems that you create. Then using RegisterStartupScript, call a javascript method that gets the appropriate ListItem and assigns it a style of current. Using Prototype, this would look like $('MyPageLi').className = 'current'.</p>\n" }, { "answer_id": 188173, "author": "John Sheehan", "author_id": 1786, "author_profile": "https://Stackoverflow.com/users/1786", "pm_score": 4, "selected": true, "text": "<p>Add a property to your master page called Page Section</p>\n\n<pre><code>public string PageSection { get; set; }\n</code></pre>\n\n<p>Add a MasterType page directive to the top of your content pages</p>\n\n<pre><code>&lt;%@ MasterType VirtualPath=\"~/foo.master\" %&gt;\n</code></pre>\n\n<p>In your content page code behind, set the PageSection property of the master page</p>\n\n<pre><code>Master.PageSection = \"home\"; \n</code></pre>\n\n<p>In your master page, make the body tag a server tag</p>\n\n<pre><code>&lt;body ID=\"bodyTag\" runat=\"server\"&gt;\n</code></pre>\n\n<p>In the master page code behind, use that property to set a class on the body tag</p>\n\n<pre><code>bodyTag.Attributes.Add(\"class\", this.PageSection);\n</code></pre>\n\n<p>Give each of your nav items a unique ID attribute.</p>\n\n<p>In your css, change the display of the nav items based on the current page class</p>\n\n<pre><code>.home #homeNavItem,\n.contact #contactNavItem\n{ \n color: #f00; \n} \n</code></pre>\n" }, { "answer_id": 189069, "author": "Dave Rutledge", "author_id": 2486915, "author_profile": "https://Stackoverflow.com/users/2486915", "pm_score": 2, "selected": false, "text": "<p>It's a better semantic match and likely an easier variable to set to keep the navigation using the same classes or ids everywhere and only alter the body element's id to match:</p>\n\n<pre><code>&lt;li id=\"homeNav\"&gt;home&lt;/li&gt;\n&lt;li id=\"blogNav\"&gt;blog&lt;/li&gt;\n</code></pre>\n\n<p>and then on each page...</p>\n\n<pre><code>&lt;body id=\"home\"&gt;\n&lt;body id=\"blog\"&gt;\n</code></pre>\n\n<p>And in the css:</p>\n\n<pre><code>#home #homeNav {background-image:url(homeNav-on.jpg);}\n#blog #blogNav {background-image:url(blogNav-on.jpg);}\n</code></pre>\n" }, { "answer_id": 458017, "author": "Joshua Carmody", "author_id": 8409, "author_profile": "https://Stackoverflow.com/users/8409", "pm_score": 4, "selected": false, "text": "<p>Have you considered using a Web.sitemap file? It makes it real easy. If your sitemap file looks like this...</p>\n\n<pre><code>&lt;?xml version=\"1.0\" encoding=\"utf-8\" ?&gt;\n&lt;siteMap xmlns=\"http://schemas.microsoft.com/AspNet/SiteMap-File-1.0\" &gt;\n &lt;siteMapNode&gt;\n &lt;siteMapNode url=\"~/Default.aspx\" title=\"Home\" description=\"\" /&gt;\n &lt;siteMapNode url=\"~/Blog.aspx\" title=\"Blog\" description=\"\" /&gt;\n &lt;siteMapNode url=\"~/AboutUs.aspx\" title=\"AboutUs\" description=\"\" /&gt;\n &lt;/siteMapNode&gt;\n&lt;/siteMap&gt;\n</code></pre>\n\n<p>...then you can do this in your master page to achieve the results you want:</p>\n\n<pre><code>&lt;asp:SiteMapDataSource ID=\"sitemapdata\" runat=\"server\" ShowStartingNode=\"false\" /&gt;\n&lt;ul id=\"navigation\"&gt;\n &lt;asp:Repeater runat=\"server\" ID=\"navrepeater\" DataSourceID=\"sitemapdata\"&gt;\n &lt;ItemTemplate&gt;\n &lt;li class=\"&lt;%# SiteMap.CurrentNode.Equals(Container.DataItem) ? \"activenav\" : \"inactivenav\" %&gt;\"&gt;&lt;a href=\"&lt;%# DataBinder.Eval(Container.DataItem, \"url\") %&gt;\"&gt;&lt;%# DataBinder.Eval(Container.DataItem, \"title\") %&gt;&lt;/a&gt;&lt;/li&gt;\n &lt;/ItemTemplate&gt;\n &lt;/asp:Repeater&gt;\n&lt;/ul&gt;\n</code></pre>\n\n<p>The current page's LI will have a class of \"activenav\" (or whatever you decide to use), and the others will have a class of \"inactivenav\". You can write your CSS accordingly. This is the technique I use on my site and it works great.</p>\n" }, { "answer_id": 2307652, "author": "Fras", "author_id": 278315, "author_profile": "https://Stackoverflow.com/users/278315", "pm_score": 0, "selected": false, "text": "<p>How about creating a protected string property in your masterpage code class? Override the OnLoad:</p>\n\n<pre><code>protected string _bodyId;\n\nprotected override void OnLoad(EventArgs e)\n{\n _bodyId = \"your css id name\";\n}\n</code></pre>\n\n<p>Then in your masterpage aspx:</p>\n\n<pre><code>&lt;body id=\"&lt;%= _bodyId %&gt;\"&gt;\n</code></pre>\n\n<p>Then you don't have to mess with your CSS, especially useful if the CSS came from a design agency.</p>\n" }, { "answer_id": 18634060, "author": "Minesh Shah", "author_id": 2711201, "author_profile": "https://Stackoverflow.com/users/2711201", "pm_score": 0, "selected": false, "text": "<p>Here's how we've achieved it using JQuery by appending the css class to change the background.</p>\n\n<pre><code>$(\"ul.nav &gt; li &gt; a:contains('&lt;%= SiteMap.CurrentNode.ParentNode.Title %&gt;')\").addClass(\"navselected\");\n</code></pre>\n\n<p>The \"<code>.nav</code>\" in <code>ul.nav</code> (in Jquery) is the css class applied to the UL tag. </p>\n\n<p><code>:contains</code> helps checking the contents of all \"a\" tag/element within the ul->li->a with ParentNode Title that is printed in Menu...</p>\n\n<p>If found, applies the css class named navselected to the specific ul->li->a tag/element.</p>\n\n<p>Regards, Minesh Shah</p>\n\n<p>Systems Plus Pvt. Ltd.</p>\n\n<p>www.systems-plus.com</p>\n" } ]
2008/10/09
[ "https://Stackoverflow.com/questions/188124", "https://Stackoverflow.com", "https://Stackoverflow.com/users/25515/" ]
I am writing a website with Visual Studio 2008 and ASP.NET 3.5. I have a masterpage set up to simplify the layout and to keep the content pages for content rather than content and layout. The navigation is list, css'd so it looks like a bar. In order to highlight the page on the bar, the list item needs to look like this `<li id="current">`. I do not want to use `<asp:ContentPlaceHolder>` if I can avoid it. Is there some code I can add to each of my pages (or just to the masterpage?) to accomplish this or am I stuck using `<asp:ContentPlaceHolder>`'s?
Add a property to your master page called Page Section ``` public string PageSection { get; set; } ``` Add a MasterType page directive to the top of your content pages ``` <%@ MasterType VirtualPath="~/foo.master" %> ``` In your content page code behind, set the PageSection property of the master page ``` Master.PageSection = "home"; ``` In your master page, make the body tag a server tag ``` <body ID="bodyTag" runat="server"> ``` In the master page code behind, use that property to set a class on the body tag ``` bodyTag.Attributes.Add("class", this.PageSection); ``` Give each of your nav items a unique ID attribute. In your css, change the display of the nav items based on the current page class ``` .home #homeNavItem, .contact #contactNavItem { color: #f00; } ```
188,138
<p>I've seen a number of references to gzipping a javascript to save download time. <em>But</em> I also see a number of warnings that certain browsers do not support this.</p> <p>I have two different methods at my disposal:</p> <ol> <li>use <code>mod_deflate</code> to make Apache compress JS/CSS files in a given directory through htaccess</li> <li>use <code>ob_start('gzhandler')</code> to compress a file and return it to the browser with the correct headers.</li> </ol> <p>The problems with method 1 are that not all browsers support mod_deflate, and I have no clue how to write the <code>.htaccess</code> file to be smart enough to adjust for this.</p> <p>The problem with method 2 is that there is no definitive answer about how to tell if a browser supports a gzipped script, or stylesheet, and that if it does what mime-type must be given as the content type in the header.</p> <p>I need some advice. First, which method is more universally accepted by browsers? Second, how do I decay using either method to provide the uncompressed backup script? Third, would <code>&lt;script src="js/lib.js.gz" type="text/javascript"&gt;&lt;/script&gt;</code> work by itself? (It obviously wouldn't decay.)</p> <p>For the record, I'm using PHP5 with mod_deflate and full gzip creation capabilities, and my doctype is xhtml strict. Also, the javascript itself is compressed with YUI. <strong>Edit:</strong> I just went back and looked, but I have only Apache 1.3; I thought I had 2, so sorry for mentioning mod_deflate when I probably don't have it.</p>
[ { "answer_id": 188205, "author": "nsayer", "author_id": 13757, "author_profile": "https://Stackoverflow.com/users/13757", "pm_score": 2, "selected": false, "text": "<p>The best way to achieve this is for your server to support inline gzip. You would take the \".gz\" off both the script tag's src attribute and store the file on the server uncompressed. If the client supported it, the server would automatically send the script as a gzip encoded result. This does cost your server some extra CPU, but the file gets compressed for those clients that support it, while older clients still get the expanded version.</p>\n\n<p>Check out mod_deflate for apache2. mod_gzip is the equivalent for Apache 1.x.</p>\n" }, { "answer_id": 188216, "author": "Owen", "author_id": 4853, "author_profile": "https://Stackoverflow.com/users/4853", "pm_score": 5, "selected": true, "text": "<p>mod_deflate and php's gzhandler both are based on zlib, so in that sense there is little difference to a browser how the content is being compressed.</p>\n\n<p>in response to your first concern, you can set module specific .htaccess info like this:</p>\n\n<pre><code>&lt;IfModule mod_deflate.c&gt;\n # stuff\n&lt;/IfModule&gt;\n</code></pre>\n\n<p>in response to your second concern, you can detect for browser support in PHP:</p>\n\n<pre><code>if (strstr($_SERVER['HTTP_ACCEPT_ENCODING'], 'gzip') ) {\n ob_start('ob_gzhandler');\n header(\"Content-Encoding: gzip\");\n// etc...\n}\n</code></pre>\n\n<p>here's some untested .htaccess that should be able to handle negotiation of compressed vs uncompressed .js files: (<a href=\"http://zuble.blogspot.com/2007/02/compressed-js-and-modrewrite.html\" rel=\"noreferrer\">source</a>)</p>\n\n<pre><code>&lt;FilesMatch \"\\\\.js.gz$\"&gt;\n ForceType text/javascript\n Header set Content-Encoding: gzip\n&lt;/FilesMatch&gt;\n&lt;FilesMatch \"\\\\.js$\"&gt;\n RewriteEngine On\n RewriteCond %{HTTP_USER_AGENT} !\".*Safari.*\"\n RewriteCond %{HTTP:Accept-Encoding} gzip\n RewriteCond %{REQUEST_FILENAME}.gz -f\n RewriteRule (.*)\\.js$ $1\\.js.gz [L]\n ForceType text/javascript\n&lt;/FilesMatch&gt; \n</code></pre>\n" }, { "answer_id": 188271, "author": "Ates Goral", "author_id": 23501, "author_profile": "https://Stackoverflow.com/users/23501", "pm_score": 2, "selected": false, "text": "<p>If the browser is properly setting it's <code>Accept-Encoding</code> header, you should be able to tell if the browser can support gzip:</p>\n\n<pre><code>Accept-Encoding: gzip,deflate\n</code></pre>\n" } ]
2008/10/09
[ "https://Stackoverflow.com/questions/188138", "https://Stackoverflow.com", "https://Stackoverflow.com/users/24950/" ]
I've seen a number of references to gzipping a javascript to save download time. *But* I also see a number of warnings that certain browsers do not support this. I have two different methods at my disposal: 1. use `mod_deflate` to make Apache compress JS/CSS files in a given directory through htaccess 2. use `ob_start('gzhandler')` to compress a file and return it to the browser with the correct headers. The problems with method 1 are that not all browsers support mod\_deflate, and I have no clue how to write the `.htaccess` file to be smart enough to adjust for this. The problem with method 2 is that there is no definitive answer about how to tell if a browser supports a gzipped script, or stylesheet, and that if it does what mime-type must be given as the content type in the header. I need some advice. First, which method is more universally accepted by browsers? Second, how do I decay using either method to provide the uncompressed backup script? Third, would `<script src="js/lib.js.gz" type="text/javascript"></script>` work by itself? (It obviously wouldn't decay.) For the record, I'm using PHP5 with mod\_deflate and full gzip creation capabilities, and my doctype is xhtml strict. Also, the javascript itself is compressed with YUI. **Edit:** I just went back and looked, but I have only Apache 1.3; I thought I had 2, so sorry for mentioning mod\_deflate when I probably don't have it.
mod\_deflate and php's gzhandler both are based on zlib, so in that sense there is little difference to a browser how the content is being compressed. in response to your first concern, you can set module specific .htaccess info like this: ``` <IfModule mod_deflate.c> # stuff </IfModule> ``` in response to your second concern, you can detect for browser support in PHP: ``` if (strstr($_SERVER['HTTP_ACCEPT_ENCODING'], 'gzip') ) { ob_start('ob_gzhandler'); header("Content-Encoding: gzip"); // etc... } ``` here's some untested .htaccess that should be able to handle negotiation of compressed vs uncompressed .js files: ([source](http://zuble.blogspot.com/2007/02/compressed-js-and-modrewrite.html)) ``` <FilesMatch "\\.js.gz$"> ForceType text/javascript Header set Content-Encoding: gzip </FilesMatch> <FilesMatch "\\.js$"> RewriteEngine On RewriteCond %{HTTP_USER_AGENT} !".*Safari.*" RewriteCond %{HTTP:Accept-Encoding} gzip RewriteCond %{REQUEST_FILENAME}.gz -f RewriteRule (.*)\.js$ $1\.js.gz [L] ForceType text/javascript </FilesMatch> ```
188,141
<p>I'm using C# on Framework 3.5. I'm looking to quickly sort a Generic <code>List&lt;T&gt;</code>. For the sake of this example, let's say I have a List of a <code>Person</code> type with a property of lastname. How would I sort this List using a lambda expression?</p> <pre><code>List&lt;Person&gt; people = PopulateList(); people.OrderBy(???? =&gt; ?????) </code></pre>
[ { "answer_id": 188149, "author": "Danimal", "author_id": 2757, "author_profile": "https://Stackoverflow.com/users/2757", "pm_score": 5, "selected": false, "text": "<pre><code>people.OrderBy(person =&gt; person.lastname).ToList();\n</code></pre>\n" }, { "answer_id": 188154, "author": "Jon Skeet", "author_id": 22656, "author_profile": "https://Stackoverflow.com/users/22656", "pm_score": 7, "selected": false, "text": "<p>Do you need the list to be sorted in place, or just an ordered sequence of the contents of the list? The latter is easier:</p>\n\n<pre><code>var peopleInOrder = people.OrderBy(person =&gt; person.LastName);\n</code></pre>\n\n<p>To sort in place, you'd need an <code>IComparer&lt;Person></code> or a <code>Comparison&lt;Person></code>. For that, you may wish to consider <code>ProjectionComparer</code> in <a href=\"http://pobox.com/~skeet/csharp/miscutil\" rel=\"noreferrer\">MiscUtil</a>.</p>\n\n<p>(I know I keep bringing MiscUtil up - it just keeps being relevant...)</p>\n" }, { "answer_id": 188155, "author": "Marc Gravell", "author_id": 23354, "author_profile": "https://Stackoverflow.com/users/23354", "pm_score": 11, "selected": true, "text": "<p>If you mean an in-place sort (i.e. the list is updated):</p>\n\n<pre><code>people.Sort((x, y) =&gt; string.Compare(x.LastName, y.LastName));\n</code></pre>\n\n<p>If you mean a new list:</p>\n\n<pre><code>var newList = people.OrderBy(x=&gt;x.LastName).ToList(); // ToList optional\n</code></pre>\n" }, { "answer_id": 4387813, "author": "Bruno", "author_id": 535015, "author_profile": "https://Stackoverflow.com/users/535015", "pm_score": 4, "selected": false, "text": "<pre><code>private void SortGridGenerico&lt; T &gt;(\n ref List&lt; T &gt; lista \n , SortDirection sort\n , string propriedadeAOrdenar)\n{\n\n if (!string.IsNullOrEmpty(propriedadeAOrdenar)\n &amp;&amp; lista != null\n &amp;&amp; lista.Count &gt; 0)\n {\n\n Type t = lista[0].GetType();\n\n if (sort == SortDirection.Ascending)\n {\n\n lista = lista.OrderBy(\n a =&gt; t.InvokeMember(\n propriedadeAOrdenar\n , System.Reflection.BindingFlags.GetProperty\n , null\n , a\n , null\n )\n ).ToList();\n }\n else\n {\n lista = lista.OrderByDescending(\n a =&gt; t.InvokeMember(\n propriedadeAOrdenar\n , System.Reflection.BindingFlags.GetProperty\n , null\n , a\n , null\n )\n ).ToList();\n }\n }\n}\n</code></pre>\n" }, { "answer_id": 4835701, "author": "Iman", "author_id": 184572, "author_profile": "https://Stackoverflow.com/users/184572", "pm_score": 3, "selected": false, "text": "<p>for me <a href=\"http://www.codedigest.com/Articles/CSHARP/84_Sorting_in_Generic_List.aspx\" rel=\"nofollow\">this useful dummy guide - Sorting in Generic List -</a> worked.\nit helps you to understand 4 ways(overloads) to do this job with very complete and clear explanations and simple examples </p>\n\n<ul>\n<li>List.Sort ()</li>\n<li>List.Sort (Generic Comparison)</li>\n<li>List.Sort (Generic IComparer)</li>\n<li>List.Sort (Int32, Int32, Generic IComparer) </li>\n</ul>\n" }, { "answer_id": 6865722, "author": "vampire203", "author_id": 868320, "author_profile": "https://Stackoverflow.com/users/868320", "pm_score": 5, "selected": false, "text": "<p>you can use linq :) using :</p>\n\n<pre><code>System.linq;\nvar newList = people.OrderBy(x=&gt;x.Name).ToList();\n</code></pre>\n" }, { "answer_id": 15744398, "author": "AnshuMan SrivAstav", "author_id": 2232244, "author_profile": "https://Stackoverflow.com/users/2232244", "pm_score": 3, "selected": false, "text": "<p>You can use this code snippet:</p>\n\n<pre><code>var New1 = EmpList.OrderBy(z =&gt; z.Age).ToList();\n</code></pre>\n\n<p>where <code>New1</code> is a <code>List&lt;Employee&gt;</code>.</p>\n\n<p><code>EmpList</code> is variable of a <code>List&lt;Employee&gt;</code>.</p>\n\n<p><code>z</code> is a variable of <code>Employee</code> type.</p>\n" }, { "answer_id": 21503079, "author": "howserss", "author_id": 787622, "author_profile": "https://Stackoverflow.com/users/787622", "pm_score": 2, "selected": false, "text": "<p>This is a generic sorter. Called with the switch below.</p>\n\n<p>dvm.PagePermissions is a property on my ViewModel of type \n List T in this case T is a EF6 model class called page_permission.</p>\n\n<p>dvm.UserNameSortDir is a string property on the viewmodel that holds the next sort direction. The one that is actaully used in the view.</p>\n\n<pre><code>switch (sortColumn)\n{\n case \"user_name\":\n dvm.PagePermissions = Sort(dvm.PagePermissions, p =&gt; p.user_name, ref sortDir);\n dvm.UserNameSortDir = sortDir;\n break;\n case \"role_name\":\n dvm.PagePermissions = Sort(dvm.PagePermissions, p =&gt; p.role_name, ref sortDir);\n dvm.RoleNameSortDir = sortDir;\n break;\n case \"page_name\":\n dvm.PagePermissions = Sort(dvm.PagePermissions, p =&gt; p.page_name, ref sortDir);\n dvm.PageNameSortDir = sortDir;\n break;\n} \n\n\npublic List&lt;T&gt; Sort&lt;T,TKey&gt;(List&lt;T&gt; list, Func&lt;T, TKey&gt; sorter, ref string direction)\n {\n if (direction == \"asc\")\n {\n list = list.OrderBy(sorter).ToList();\n direction = \"desc\";\n }\n else\n {\n list = list.OrderByDescending(sorter).ToList();\n direction = \"asc\";\n }\n return list;\n }\n</code></pre>\n" }, { "answer_id": 28274075, "author": "rosselder83", "author_id": 3556685, "author_profile": "https://Stackoverflow.com/users/3556685", "pm_score": 3, "selected": false, "text": "<p>You can also use</p>\n\n<pre><code>model.People = model.People.OrderBy(x =&gt; x.Name).ToList();\n</code></pre>\n" }, { "answer_id": 73709627, "author": "Misha Zaslavsky", "author_id": 2667173, "author_profile": "https://Stackoverflow.com/users/2667173", "pm_score": 0, "selected": false, "text": "<p>In .NET 7 preview you can use the <a href=\"https://devblogs.microsoft.com/dotnet/announcing-dotnet-7-preview-7/#usage\" rel=\"nofollow noreferrer\">simplified ordering</a> of <code>System.Linq</code>. It also has some performance improvements.</p>\n<pre><code>var sorted = people.Order();\n</code></pre>\n<p>Also, be aware that the <code>Sort</code> method has a better performance in most cases because you don't allocate a new list.</p>\n" } ]
2008/10/09
[ "https://Stackoverflow.com/questions/188141", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7215/" ]
I'm using C# on Framework 3.5. I'm looking to quickly sort a Generic `List<T>`. For the sake of this example, let's say I have a List of a `Person` type with a property of lastname. How would I sort this List using a lambda expression? ``` List<Person> people = PopulateList(); people.OrderBy(???? => ?????) ```
If you mean an in-place sort (i.e. the list is updated): ``` people.Sort((x, y) => string.Compare(x.LastName, y.LastName)); ``` If you mean a new list: ``` var newList = people.OrderBy(x=>x.LastName).ToList(); // ToList optional ```
188,147
<p>Trying to setup the exception_logger plugin on a production server. Everything worked fine on the dev machine. Trying to rake db:migrate on the prod server and i get this error:</p> <pre><code>rake aborted! no such file to load -- pagination </code></pre> <p>What am i missing?</p>
[ { "answer_id": 188228, "author": "Christoph Schiessl", "author_id": 20467, "author_profile": "https://Stackoverflow.com/users/20467", "pm_score": 1, "selected": false, "text": "<p>Obviously the error is related to the pagination plugin. That means the error may not be related to exception_logger at all...</p>\n\n<p>Try <code>rake db:migrate --trace</code> and add the additional output to your question!</p>\n" }, { "answer_id": 188268, "author": "Jason Miesionczek", "author_id": 18811, "author_profile": "https://Stackoverflow.com/users/18811", "pm_score": 0, "selected": false, "text": "<pre><code>** Invoke db:migrate (first_time)\n** Invoke environment (first_time)\n** Execute environment\nrake aborted!\nno such file to load -- pagination\n/home/12348/data/rubygems/lib/rubygems/custom_require.rb:27:in `gem_original_require'\n/home/12348/data/rubygems/lib/rubygems/custom_require.rb:27:in `require'\n/home/12348/data/rubygems/gems/gems/activesupport-2.1.0/lib/active_support/dependencies.rb:509:in `require'\n/home/12348/data/rubygems/gems/gems/activesupport-2.1.0/lib/active_support/dependencies.rb:354:in `new_constants_in'\n/home/12348/data/rubygems/gems/gems/activesupport-2.1.0/lib/active_support/dependencies.rb:509:in `require'\n/nfs/c01/h06/mnt/12348/containers/rails/mpg_prod/vendor/plugins/classic_pagination/init.rb:24:in `evaluate_init_rb'\n/home/12348/data/rubygems/gems/gems/rails-2.1.0/lib/rails/plugin.rb:95:in `evaluate_init_rb'\n/home/12348/data/rubygems/gems/gems/activesupport-2.1.0/lib/active_support/core_ext/kernel/reporting.rb:11:in `silence_warnings'\n/home/12348/data/rubygems/gems/gems/rails-2.1.0/lib/rails/plugin.rb:91:in `evaluate_init_rb'\n/home/12348/data/rubygems/gems/gems/rails-2.1.0/lib/rails/plugin.rb:44:in `load'\n/home/12348/data/rubygems/gems/gems/rails-2.1.0/lib/rails/plugin/loader.rb:33:in `load_plugins'\n/home/12348/data/rubygems/gems/gems/rails-2.1.0/lib/rails/plugin/loader.rb:32:in `each'\n/home/12348/data/rubygems/gems/gems/rails-2.1.0/lib/rails/plugin/loader.rb:32:in `load_plugins'\n/home/12348/data/rubygems/gems/gems/rails-2.1.0/lib/initializer.rb:283:in `load_plugins'\n/home/12348/data/rubygems/gems/gems/rails-2.1.0/lib/initializer.rb:138:in `process'\n/home/12348/data/rubygems/gems/gems/rails-2.1.0/lib/initializer.rb:93:in `send'\n/home/12348/data/rubygems/gems/gems/rails-2.1.0/lib/initializer.rb:93:in `run'\n/nfs/c01/h06/mnt/12348/containers/rails/mpg_prod/config/environment.rb:13\n/home/12348/data/rubygems/lib/rubygems/custom_require.rb:27:in `gem_original_require'\n/home/12348/data/rubygems/lib/rubygems/custom_require.rb:27:in `require'\n/home/12348/data/rubygems/gems/gems/activesupport-2.1.0/lib/active_support/dependencies.rb:509:in `require'\n/home/12348/data/rubygems/gems/gems/activesupport-2.1.0/lib/active_support/dependencies.rb:354:in `new_constants_in'\n/home/12348/data/rubygems/gems/gems/activesupport-2.1.0/lib/active_support/dependencies.rb:509:in `require'\n/home/12348/data/rubygems/gems/gems/rails-2.1.0/lib/tasks/misc.rake:3\n/home/12348/data/rubygems/gems/gems/rake-0.8.1/lib/rake.rb:546:in `call'\n/home/12348/data/rubygems/gems/gems/rake-0.8.1/lib/rake.rb:546:in `execute'\n/home/12348/data/rubygems/gems/gems/rake-0.8.1/lib/rake.rb:541:in `each'\n/home/12348/data/rubygems/gems/gems/rake-0.8.1/lib/rake.rb:541:in `execute'\n/home/12348/data/rubygems/gems/gems/rake-0.8.1/lib/rake.rb:508:in `invoke_with_call_chain'\n/usr/lib/ruby/1.8/thread.rb:135:in `synchronize'\n/home/12348/data/rubygems/gems/gems/rake-0.8.1/lib/rake.rb:501:in `invoke_with_call_chain'\n/home/12348/data/rubygems/gems/gems/rake-0.8.1/lib/rake.rb:518:in `invoke_prerequisites'\n/home/12348/data/rubygems/gems/gems/rake-0.8.1/lib/rake.rb:1183:in `each'\n/home/12348/data/rubygems/gems/gems/rake-0.8.1/lib/rake.rb:1183:in `send'\n/home/12348/data/rubygems/gems/gems/rake-0.8.1/lib/rake.rb:1183:in `each'\n/home/12348/data/rubygems/gems/gems/rake-0.8.1/lib/rake.rb:515:in `invoke_prerequisites'\n/home/12348/data/rubygems/gems/gems/rake-0.8.1/lib/rake.rb:507:in `invoke_with_call_chain'\n/usr/lib/ruby/1.8/thread.rb:135:in `synchronize'\n/home/12348/data/rubygems/gems/gems/rake-0.8.1/lib/rake.rb:501:in `invoke_with_call_chain'\n/home/12348/data/rubygems/gems/gems/rake-0.8.1/lib/rake.rb:494:in `invoke'\n/home/12348/data/rubygems/gems/gems/rake-0.8.1/lib/rake.rb:1931:in `invoke_task'\n/home/12348/data/rubygems/gems/gems/rake-0.8.1/lib/rake.rb:1909:in `top_level'\n/home/12348/data/rubygems/gems/gems/rake-0.8.1/lib/rake.rb:1909:in `each'\n/home/12348/data/rubygems/gems/gems/rake-0.8.1/lib/rake.rb:1909:in `top_level'\n/home/12348/data/rubygems/gems/gems/rake-0.8.1/lib/rake.rb:1948:in `standard_exception_handling'\n/home/12348/data/rubygems/gems/gems/rake-0.8.1/lib/rake.rb:1903:in `top_level'\n/home/12348/data/rubygems/gems/gems/rake-0.8.1/lib/rake.rb:1881:in `run'\n/home/12348/data/rubygems/gems/gems/rake-0.8.1/lib/rake.rb:1948:in `standard_exception_handling'\n/home/12348/data/rubygems/gems/gems/rake-0.8.1/lib/rake.rb:1878:in `run'\n/home/12348/data/rubygems/gems/gems/rake-0.8.1/bin/rake:31\n/home/12348/data/rubygems/gems/bin/rake:19:in `load'\n/home/12348/data/rubygems/gems/bin/rake:19\n</code></pre>\n" }, { "answer_id": 190034, "author": "JasonOng", "author_id": 6048, "author_profile": "https://Stackoverflow.com/users/6048", "pm_score": -1, "selected": false, "text": "<ol>\n<li>Your rake is being aborted while loading <strong>environment.rb</strong>. </li>\n<li>Check for any <strong>missing gems</strong> that are declared in it ton your production machine.</li>\n<li>\"<strong>sudo gem install\"</strong> those that are missing </li>\n<li>Check environment.rb loads up properly by issuing <strong>\"script/console\"</strong> on your temimal</li>\n</ol>\n" }, { "answer_id": 194491, "author": "danpickett", "author_id": 21788, "author_profile": "https://Stackoverflow.com/users/21788", "pm_score": 3, "selected": true, "text": "<p>Classic Pagination is not supported in 2.1 - or at least it is a dead library</p>\n\n<p><a href=\"http://workingwithrails.com/railsplugin/5289-classic-pagination\" rel=\"nofollow noreferrer\">http://workingwithrails.com/railsplugin/5289-classic-pagination</a></p>\n\n<p>Have a look at will_paginate - </p>\n\n<p><a href=\"http://github.com/mislav/will_paginate/wikis\" rel=\"nofollow noreferrer\">http://github.com/mislav/will_paginate/wikis</a></p>\n\n<p>that's what all the cool kids are using :-)</p>\n" } ]
2008/10/09
[ "https://Stackoverflow.com/questions/188147", "https://Stackoverflow.com", "https://Stackoverflow.com/users/18811/" ]
Trying to setup the exception\_logger plugin on a production server. Everything worked fine on the dev machine. Trying to rake db:migrate on the prod server and i get this error: ``` rake aborted! no such file to load -- pagination ``` What am i missing?
Classic Pagination is not supported in 2.1 - or at least it is a dead library <http://workingwithrails.com/railsplugin/5289-classic-pagination> Have a look at will\_paginate - <http://github.com/mislav/will_paginate/wikis> that's what all the cool kids are using :-)
188,160
<p>How have you decided to handle data/control validation in your silverlight applications? </p>
[ { "answer_id": 188459, "author": "Bryant", "author_id": 10893, "author_profile": "https://Stackoverflow.com/users/10893", "pm_score": 1, "selected": false, "text": "<p>Haven't done much of this yet personally, but some good starting points <a href=\"http://weblogs.asp.net/manishdalal/archive/2008/09/10/silverlight-business-application-part-5-validation-refactored.aspx\" rel=\"nofollow noreferrer\">here</a>. I imagine that these will come as part of a future release, but for now we'll probably have to roll our own using ASP.NET validators as a starting point.</p>\n" }, { "answer_id": 198728, "author": "Yuval Peled", "author_id": 20257, "author_profile": "https://Stackoverflow.com/users/20257", "pm_score": 2, "selected": false, "text": "<p>You can throw and capture data validation exceptions.</p>\n\n<p>To manage both of these types of errors need to take 3 steps:</p>\n\n<ol>\n<li>Identify the error handler either in the control or higher in the visiblity hierarchy (e.g., a container; in this case the grid that contains the text box)</li>\n<li>Set NotifyOnValidationError and ValidateOnException to true. The latter tells the Binding Engine to create a validation error event when an exception occurs. The former tells the Binding Engine to raise the BindingValidationError event when a validation error occurs.</li>\n<li>Create the event handler named in step 1.</li>\n</ol>\n\n<p>Taken from <a href=\"http://silverlight.net/blogs/jesseliberty/archive/2008/10/13/data-binding-data-validation.aspx\" rel=\"nofollow noreferrer\">here</a>.</p>\n\n<p>Sample code:</p>\n\n<pre><code>// page.xaml.cs\n\nprivate bool clean = true;\n\n\nprivate void LayoutRoot_BindingValidationError( \n object sender, ValidationErrorEventArgs e )\n{\n if ( e.Action == ValidationErrorEventAction.Added )\n {\n QuantityOnHand.Background = new SolidColorBrush( Colors.Red );\n clean = false;\n }\n else if ( e.Action == ValidationErrorEventAction.Removed )\n {\n QuantityOnHand.Background = new SolidColorBrush( Colors.White );\n clean = true;\n }\n}\n\n\n\n// page.xaml\n\n&lt;Grid x:Name=\"LayoutRoot\" Background=\"White\" BindingValidationError=\"LayoutRoot_BindingValidationError\" &gt;\n\n&lt;TextBox x:Name=\"QuantityOnHand\" \n Text=\"{Binding Mode=TwoWay, Path=QuantityOnHand, \n NotifyOnValidationError=true, ValidatesOnExceptions=true }\"\n VerticalAlignment=\"Bottom\"\n HorizontalAlignment=\"Left\"\n Height=\"30\" Width=\"90\"red\n Grid.Row=\"4\" Grid.Column=\"1\" /&gt;\n\n\n// book.cs\n\npublic int QuantityOnHand\n{\n get { return quantityOnHand; }\n set\n {\n if ( value &lt; 0 )\n {\n throw new Exception( \"Quantity on hand cannot be negative!\" );\n }\n quantityOnHand = value;\n NotifyPropertyChanged( \"QuantityOnHand\" );\n } // end set\n}\n</code></pre>\n" }, { "answer_id": 216967, "author": "Craig Nicholson", "author_id": 28305, "author_profile": "https://Stackoverflow.com/users/28305", "pm_score": -1, "selected": false, "text": "<p>You might want to look at <a href=\"http://www.postsharp.org/\" rel=\"nofollow noreferrer\">PostSharp</a>, it makes attributing your client-side data model very simple.</p>\n" }, { "answer_id": 300651, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 1, "selected": false, "text": "<p>If you are experiencing problems trying to implement this, it's not because your code is broken, it's because the feature is broken in the DataGrid. Check out the article by Jesse Liberty <a href=\"http://jesseliberty.com/2008/10/22/it-aint-you-babe%E2%80%A6-a-not-a-bug-bug-in-datagrid/\" rel=\"nofollow noreferrer\">here</a>.</p>\n" }, { "answer_id": 6301878, "author": "Pankaj Awasthi", "author_id": 522781, "author_profile": "https://Stackoverflow.com/users/522781", "pm_score": 0, "selected": false, "text": "<p>A very easy validation control source code is given at this location:</p>\n\n<p><a href=\"http://silverlightvalidator.codeplex.com/SourceControl/changeset/view/20754#\" rel=\"nofollow\">http://silverlightvalidator.codeplex.com/SourceControl/changeset/view/20754#</a></p>\n\n<p>The following are the conditions under which it works.\n1. The indicator showing invalid values assumes the position of the control to validate, therefore controls should be tightly packed in a row and column so that it indicates adjacent to the control.\n2. It doesn't work for the validating on the ChildWindow.</p>\n\n<p>I had to modify the code to include the conditions of childwindow in the validatorbase class as follows:</p>\n" }, { "answer_id": 6301921, "author": "Pankaj Awasthi", "author_id": 522781, "author_profile": "https://Stackoverflow.com/users/522781", "pm_score": 0, "selected": false, "text": "<pre><code>using System;\nusing System.Net;\nusing System.Windows;\nusing System.Windows.Controls;\nusing System.Windows.Documents;\nusing System.Windows.Ink;\nusing System.Windows.Input;\nusing System.Windows.Media;\nusing System.Windows.Media.Animation;\nusing System.Windows.Shapes;\nusing Silverlight.Validators.Controls;\n\nnamespace Silverlight.Validators\n{\n public enum ValidationType\n {\n Validator,\n OnDemand\n }\n\n\n public abstract class ValidatorBase : DependencyObject\n {\n protected ValidatorManager Manager { get; set; }\n\n\n public string ManagerName { get; set; }\n public ValidationType ValidationType { get; set; }\n public IIndicator Indicator { get; set; }\n public FrameworkElement ElementToValidate { get; set; }\n public bool IsRequired { get; set; }\n public bool IsValid { get; set; }\n public Brush InvalidBackground { get; set; }\n public Brush InvalidBorder { get; set; }\n public Thickness InvalidBorderThickness { get; set; }\n public string ErrorMessage { get; set; }\n\n private Brush OrigBackground = null;\n private Brush OrigBorder = null;\n private Thickness OrigBorderThickness = new Thickness(1);\n private object OrigTooltip = null;\n\n public ValidatorBase()\n {\n IsRequired = false;\n IsValid = true;\n ManagerName = \"\";\n this.ValidationType = ValidationType.Validator;\n }\n\n public void Initialize(FrameworkElement element)\n {\n ElementToValidate = element;\n element.Loaded += new RoutedEventHandler(element_Loaded);\n }\n\n private bool loaded = false;\n public UserControl UserControl { get; set; }\n public ChildWindow ChildUserControl { get; set; }\n private void element_Loaded(object sender, RoutedEventArgs e)\n {\n if (!loaded)\n {\n\n this.UserControl = FindUserControl(ElementToValidate);\n //UserControl o = FindUserControl(ElementToValidate);\n this.ChildUserControl = FindChildUserControl(ElementToValidate);\n //MessageBox.Show(o.GetType().BaseType.ToString());\n //no usercontrol. throw error?\n if ((this.UserControl == null) &amp;&amp; (this.ChildUserControl==null)) return;\n\n if (this.UserControl != null)\n this.Manager = FindManager(this.UserControl, ManagerName);\n else if (this.ChildUserControl != null)\n this.Manager = FindManager(this.ChildUserControl, ManagerName);\n\n\n if (this.Manager == null)\n {\n System.Diagnostics.Debug.WriteLine(String.Format(\"No ValidatorManager found named '{0}'\", ManagerName));\n throw new Exception(String.Format(\"No ValidatorManager found named '{0}'\", ManagerName));\n }\n\n this.Manager.Register(ElementToValidate, this);\n\n if (ValidationType == ValidationType.Validator)\n {\n ActivateValidationRoutine();\n }\n\n //Use the properties from the manager if they are not set at the control level\n if (this.InvalidBackground == null)\n {\n this.InvalidBackground = this.Manager.InvalidBackground;\n }\n\n if (this.InvalidBorder == null)\n {\n this.InvalidBorder = this.Manager.InvalidBorder;\n\n if (InvalidBorderThickness.Bottom == 0)\n {\n this.InvalidBorderThickness = this.Manager.InvalidBorderThickness;\n }\n }\n\n if (this.Indicator ==null)\n {\n Type x = this.Manager.Indicator.GetType();\n this.Indicator = x.GetConstructor(System.Type.EmptyTypes).Invoke(null) as IIndicator;\n foreach (var param in x.GetProperties())\n {\n var val = param.GetValue(this.Manager.Indicator, null);\n if (param.CanWrite &amp;&amp; val!= null &amp;&amp; val.GetType().IsPrimitive)\n {\n param.SetValue(this.Indicator, val, null);\n }\n }\n }\n loaded = true;\n }\n ElementToValidate.Loaded -= new RoutedEventHandler(element_Loaded);\n }\n\n public void SetManagerAndControl(ValidatorManager manager, FrameworkElement element)\n {\n this.Manager = manager;\n this.ElementToValidate = element;\n }\n\n public bool Validate(bool checkControl)\n {\n bool newIsValid;\n if (checkControl)\n {\n newIsValid= ValidateControl() &amp;&amp; ValidateRequired();\n }\n else\n {\n newIsValid = ValidateRequired();\n }\n\n if (newIsValid &amp;&amp; !IsValid)\n {\n ControlValid();\n }\n if (!newIsValid &amp;&amp; IsValid)\n {\n ControlNotValid();\n }\n IsValid=newIsValid;\n return IsValid;\n }\n\n public virtual void ActivateValidationRoutine()\n {\n ElementToValidate.LostFocus += new RoutedEventHandler(ElementToValidate_LostFocus);\n ElementToValidate.KeyUp += new KeyEventHandler(ElementToValidate_KeyUp);\n }\n\n /// &lt;summary&gt;\n /// Find the nearest UserControl up the control tree for the FrameworkElement passed in\n /// &lt;/summary&gt;\n /// &lt;param name=\"element\"&gt;Control to validate&lt;/param&gt;\n protected static UserControl FindUserControl(FrameworkElement element)\n {\n if (element == null)\n {\n return null;\n }\n if (element.Parent != null)\n {\n //MessageBox.Show(element.Parent.GetType().BaseType.ToString());\n if (element.Parent is UserControl)\n {\n return element.Parent as UserControl;\n }\n return FindUserControl(element.Parent as FrameworkElement);\n }\n return null;\n }\n protected static ChildWindow FindChildUserControl(FrameworkElement element)\n {\n if (element == null)\n {\n return null;\n }\n if (element.Parent != null)\n {\n //MessageBox.Show(element.Parent.GetType().BaseType.ToString());\n if (element.Parent is ChildWindow)\n {\n return element.Parent as ChildWindow;\n }\n return FindChildUserControl(element.Parent as FrameworkElement);\n }\n return null;\n }\n\n protected virtual void ElementToValidate_KeyUp(object sender, RoutedEventArgs e)\n {\n Dispatcher.BeginInvoke(delegate() { Validate(false); });\n }\n\n protected virtual void ElementToValidate_LostFocus(object sender, RoutedEventArgs e)\n {\n Dispatcher.BeginInvoke(delegate() { Validate(true); });\n }\n\n protected abstract bool ValidateControl();\n\n protected bool ValidateRequired()\n {\n if (IsRequired &amp;&amp; ElementToValidate is TextBox)\n {\n TextBox box = ElementToValidate as TextBox;\n return !String.IsNullOrEmpty(box.Text);\n }\n return true;\n }\n\n protected void ControlNotValid()\n {\n GoToInvalidStyle();\n }\n\n protected void ControlValid()\n {\n GoToValidStyle();\n }\n\n protected virtual void GoToInvalidStyle()\n {\n if (!string.IsNullOrEmpty(this.ErrorMessage))\n {\n object tooltip = ToolTipService.GetToolTip(ElementToValidate);\n\n if (tooltip != null)\n {\n OrigTooltip = tooltip;\n }\n\n //causing a onownermouseleave error currently...\n this.ElementToValidate.ClearValue(ToolTipService.ToolTipProperty);\n\n SetToolTip(this.ElementToValidate, this.ErrorMessage);\n }\n\n if (Indicator != null)\n {\n Indicator.ShowIndicator(this);\n }\n\n if (ElementToValidate is TextBox)\n {\n TextBox box = ElementToValidate as TextBox;\n\n if (InvalidBackground != null)\n {\n if (OrigBackground == null)\n {\n OrigBackground = box.Background;\n }\n box.Background = InvalidBackground;\n }\n\n if (InvalidBorder != null)\n {\n if (OrigBorder == null)\n {\n OrigBorder = box.BorderBrush;\n OrigBorderThickness = box.BorderThickness;\n }\n box.BorderBrush = InvalidBorder;\n\n if (InvalidBorderThickness != null)\n {\n box.BorderThickness = InvalidBorderThickness;\n }\n }\n } \n }\n\n protected virtual void GoToValidStyle()\n {\n if (!string.IsNullOrEmpty(this.ErrorMessage))\n {\n this.ElementToValidate.ClearValue(ToolTipService.ToolTipProperty);\n\n if (this.OrigTooltip != null)\n {\n SetToolTip(this.ElementToValidate, this.OrigTooltip);\n }\n }\n\n if (Indicator != null)\n {\n Indicator.HideIndicator();\n }\n\n if (ElementToValidate is TextBox)\n {\n TextBox box = ElementToValidate as TextBox;\n if (OrigBackground != null)\n {\n box.Background = OrigBackground;\n }\n\n if (OrigBorder != null)\n {\n box.BorderBrush = OrigBorder;\n\n if (OrigBorderThickness != null)\n {\n box.BorderThickness = OrigBorderThickness;\n }\n }\n }\n }\n\n protected void SetToolTip(FrameworkElement element, object tooltip)\n {\n Dispatcher.BeginInvoke(() =&gt;\n ToolTipService.SetToolTip(element, tooltip));\n }\n\n private ValidatorManager FindManager(UserControl c, string groupName)\n {\n string defaultName = \"_DefaultValidatorManager\";\n var mgr = this.UserControl.FindName(ManagerName);\n if (mgr == null)\n {\n mgr = this.UserControl.FindName(defaultName);\n }\n if (mgr == null)\n {\n mgr = new ValidatorManager()\n {\n Name = defaultName\n };\n Panel g = c.FindName(\"LayoutRoot\") as Panel;\n g.Children.Add(mgr as ValidatorManager);\n }\n return mgr as ValidatorManager;\n }\n\n private ValidatorManager FindManager(ChildWindow c, string groupName)\n {\n string defaultName = \"_DefaultValidatorManager\";\n var mgr = this.ChildUserControl.FindName(ManagerName);\n if (mgr == null)\n {\n mgr = this.ChildUserControl.FindName(defaultName);\n }\n if (mgr == null)\n {\n mgr = new ValidatorManager()\n {\n Name = defaultName\n };\n Panel g = c.FindName(\"LayoutRoot\") as Panel;\n g.Children.Add(mgr as ValidatorManager);\n }\n return mgr as ValidatorManager;\n }\n\n }\n}\n</code></pre>\n" } ]
2008/10/09
[ "https://Stackoverflow.com/questions/188160", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5618/" ]
How have you decided to handle data/control validation in your silverlight applications?
You can throw and capture data validation exceptions. To manage both of these types of errors need to take 3 steps: 1. Identify the error handler either in the control or higher in the visiblity hierarchy (e.g., a container; in this case the grid that contains the text box) 2. Set NotifyOnValidationError and ValidateOnException to true. The latter tells the Binding Engine to create a validation error event when an exception occurs. The former tells the Binding Engine to raise the BindingValidationError event when a validation error occurs. 3. Create the event handler named in step 1. Taken from [here](http://silverlight.net/blogs/jesseliberty/archive/2008/10/13/data-binding-data-validation.aspx). Sample code: ``` // page.xaml.cs private bool clean = true; private void LayoutRoot_BindingValidationError( object sender, ValidationErrorEventArgs e ) { if ( e.Action == ValidationErrorEventAction.Added ) { QuantityOnHand.Background = new SolidColorBrush( Colors.Red ); clean = false; } else if ( e.Action == ValidationErrorEventAction.Removed ) { QuantityOnHand.Background = new SolidColorBrush( Colors.White ); clean = true; } } // page.xaml <Grid x:Name="LayoutRoot" Background="White" BindingValidationError="LayoutRoot_BindingValidationError" > <TextBox x:Name="QuantityOnHand" Text="{Binding Mode=TwoWay, Path=QuantityOnHand, NotifyOnValidationError=true, ValidatesOnExceptions=true }" VerticalAlignment="Bottom" HorizontalAlignment="Left" Height="30" Width="90"red Grid.Row="4" Grid.Column="1" /> // book.cs public int QuantityOnHand { get { return quantityOnHand; } set { if ( value < 0 ) { throw new Exception( "Quantity on hand cannot be negative!" ); } quantityOnHand = value; NotifyPropertyChanged( "QuantityOnHand" ); } // end set } ```