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
212,715
<p>I'm trying to use the giveio.sys driver which requires a "file" to be opened before you can access protected memory. I'm looking at a C example from WinAVR/AVRdude that uses the syntax:</p> <pre class="lang-c prettyprint-override"><code> #define DRIVERNAME "\\\\.\\giveio" HANDLE h = CreateFile(DRIVERNAME, GENERIC_READ, 0, NULL, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL); </code></pre> <p>but this does not seem to work in Python - I just get a "The specified path is invalid" error, for both</p> <pre><code>f = os.open("\\\\.\\giveio", os.O_RDONLY) </code></pre> <p>and </p> <pre><code>f = os.open("//./giveio", os.O_RDONLY) </code></pre> <p>Why doesn't this do the same thing?</p> <p><strong>Edited</strong> to hopefully reduce confusion of ideas (thanks Will). I did verify that the device driver is running via the batch files that come with AVRdude.</p> <p><strong>Further edited</strong> to clarify SamB's bounty.</p>
[ { "answer_id": 214066, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 2, "selected": false, "text": "<p>You're question is very confusing to say the least. </p>\n\n<p>1> The code you pasted is using a trick to communicate with the driver using its 'DOSNAME' i.e.</p>\n\n<pre><code>\\\\.\\DRIVERNAME\n</code></pre>\n\n<p>2> Have you created &amp; loaded the 'giveio' driver ?</p>\n\n<p>The reason the driver handles this calls is because of this</p>\n\n<p><a href=\"http://msdn.microsoft.com/en-us/library/ms806162.aspx\" rel=\"nofollow noreferrer\">http://msdn.microsoft.com/en-us/library/ms806162.aspx</a></p>\n" }, { "answer_id": 214727, "author": "willurd", "author_id": 1943957, "author_profile": "https://Stackoverflow.com/users/1943957", "pm_score": 2, "selected": false, "text": "<p>I'm not sure if that's possible. As an alternative, you could write a C/C++ program that does all that kernel space work for you and interface with it in Python via <a href=\"http://www.python.org/doc/2.5.2/lib/module-subprocess.html\" rel=\"nofollow noreferrer\">the subprocess module</a> or <a href=\"http://www.language-binding.net/\" rel=\"nofollow noreferrer\">Python C/C++ bindings</a> (and <a href=\"http://wiki.cacr.caltech.edu/danse/index.php/Writing_C_extensions_for_Python\" rel=\"nofollow noreferrer\">another link</a> for that).</p>\n" }, { "answer_id": 214867, "author": "Will Dean", "author_id": 987, "author_profile": "https://Stackoverflow.com/users/987", "pm_score": 2, "selected": false, "text": "<p>I don't know anything about Python, but I do know a bit about drivers. You're not trying to 'open a file in kernel space' at all - you're just trying to open a handle to a device which happens to be made to look a bit like opening a file.</p>\n\n<p>CreateFile is a user-mode function, and everything you're doing here is user-mode, not kernel mode.</p>\n\n<p>As xenon says, your call may be failing because you haven't loaded the driver yet, or because whatever Python call you're using to do the CreateFile is not passing the write parameters in.</p>\n\n<p>I've never used giveio.sys myself, but personally I would establish that it was loaded correctly by using 'C' or C++ (or some pre-written app) before I tried to get it working via Python.</p>\n" }, { "answer_id": 218562, "author": "apaulsen", "author_id": 28984, "author_profile": "https://Stackoverflow.com/users/28984", "pm_score": 3, "selected": false, "text": "<p>Solution: in python you have to use win32file.CreateFile() instead of open(). Thanks everyone for telling me what I was trying to do, it helped me find the answer!</p>\n" }, { "answer_id": 5870770, "author": "Grim", "author_id": 561323, "author_profile": "https://Stackoverflow.com/users/561323", "pm_score": 1, "selected": false, "text": "<p>There are 2 ways to do this.</p>\n\n<p>The first way is using the win32 python bindings</p>\n\n<pre><code>h = win32file.CreateFile\n</code></pre>\n\n<p>Or using ctypes</p>\n" }, { "answer_id": 5891868, "author": "Warren P", "author_id": 84704, "author_profile": "https://Stackoverflow.com/users/84704", "pm_score": 2, "selected": false, "text": "<p>It sounds to me like you're asking why os.open is not magically equal to calling CreateFile with a very specific set of parameters. Kostya's answer is practical in that it tells you that you can use the Win32 python bindings to call CreateFile which is a Win32 API, directly.</p>\n\n<p>Anything other than doing direct CreateFile/readFile/writeFile IO is going to introduce another layer on top (the python file objects and their behaviours) that restricts you to the parameters that os.open supports. os.open creates a python file object, which is not exactly the same thing, and not intended to provide all of Win32 CreateFile's options.</p>\n\n<p>That means, for example, that no exact analog of GENERIC_READ, or OPEN_EXISTING, or FILE_ATTRIBUTE_NORMAL are guaranteed to exist.</p>\n\n<p>My best guess is that os.open is not intended to replace direct calls to CreateFile, for such odd purposes as the one you're using it for.</p>\n\n<p>If you can read C, why not open up the sources for python and read the implementation of os.open. If you really must go through os.open, you're going to find out what parameters to pass to it, so that in the end, os.open's implementation (in C) calls CreateFile in Win32 API with the correct parameters above. All of that seems more like work, than just using Kostya's suggestion.</p>\n" } ]
2008/10/17
[ "https://Stackoverflow.com/questions/212715", "https://Stackoverflow.com", "https://Stackoverflow.com/users/28984/" ]
I'm trying to use the giveio.sys driver which requires a "file" to be opened before you can access protected memory. I'm looking at a C example from WinAVR/AVRdude that uses the syntax: ```c #define DRIVERNAME "\\\\.\\giveio" HANDLE h = CreateFile(DRIVERNAME, GENERIC_READ, 0, NULL, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL); ``` but this does not seem to work in Python - I just get a "The specified path is invalid" error, for both ``` f = os.open("\\\\.\\giveio", os.O_RDONLY) ``` and ``` f = os.open("//./giveio", os.O_RDONLY) ``` Why doesn't this do the same thing? **Edited** to hopefully reduce confusion of ideas (thanks Will). I did verify that the device driver is running via the batch files that come with AVRdude. **Further edited** to clarify SamB's bounty.
Solution: in python you have to use win32file.CreateFile() instead of open(). Thanks everyone for telling me what I was trying to do, it helped me find the answer!
212,718
<p>The NUnit documentation doesn't tell me when to use a method with a <code>TestFixtureSetup</code> and when to do the setup in the constructor.</p> <pre><code>public class MyTest { private MyClass myClass; public MyTest() { myClass = new MyClass(); } [TestFixtureSetUp] public void Init() { myClass = new MyClass(); } } </code></pre> <p>Are there any good/bad practices about the <code>TestFixtureSetup</code> versus default constructor or isn't there any difference?</p>
[ { "answer_id": 212769, "author": "Sam Wessel", "author_id": 4734, "author_profile": "https://Stackoverflow.com/users/4734", "pm_score": 6, "selected": false, "text": "<p>Why would you need to use a constructor in your test classes?</p>\n\n<p>I use <code>[SetUp]</code> and <code>[TearDown]</code> marked methods for code to be executed before and after each test, and similarly <code>[TestFixtureSetUp]</code> and <code>[TestFixtureTearDown]</code> marked methods for code to be executed only once before and after all test in the fixture have been run.</p>\n\n<p>I guess you could probably substitute the <code>[TestFixtureSetUp]</code> for a constructor (although I haven't tried), but this only seems to break from the clear convention that the marked methods provide.</p>\n" }, { "answer_id": 213172, "author": "casademora", "author_id": 5619, "author_profile": "https://Stackoverflow.com/users/5619", "pm_score": 5, "selected": true, "text": "<p>I think this has been one of the issues that hasn't been addressed by the nUnit team. However, there is the excellent <a href=\"http://www.codeplex.com/xunit\" rel=\"noreferrer\">xUnit project</a> that saw this exact issue and decided that constructors were a good thing to use on <a href=\"http://www.codeplex.com/xunit/Wiki/View.aspx?title=Comparisons&amp;referringTitle=Home#attributes\" rel=\"noreferrer\">test fixture initialization</a>.</p>\n\n<p>For nunit, my best practice in this case has been to use the <code>TestFixtureSetUp</code>, <code>TestFixtureTearDown</code>, <code>SetUp</code>, and <code>TearDown</code> methods as described in the documentation. </p>\n\n<p>I think it also helps me when I don't think of an nUnit test fixture as a normal class, even though you are defining it with that construct. I think of them as fixtures, and that gets me over the mental hurdle and allows me to overlook this issue. </p>\n" }, { "answer_id": 830473, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 4, "selected": false, "text": "<p>I have often wondered what the need for <code>[TestFixtureSetUp]</code> was, given that there is a simple, well understood first class language construct that does exactly the same thing.</p>\n\n<p>My preference is to use constructors, to take advantage of the readonly keyword ensuring member variables cannot be reinitialised.</p>\n" }, { "answer_id": 1181456, "author": "ripper234", "author_id": 11236, "author_profile": "https://Stackoverflow.com/users/11236", "pm_score": 2, "selected": false, "text": "<p>I think I have a negative good answer - the reason to use a constructor instead of the attribute is when you have an inheritence between test classes.</p>\n\n<p>Only one method annotated with <code>[TestFixtureSetup]</code> will be called (on the concrete class only), but the other fixture initializers will not. In this case I'd rather put the initialization in the constructor, which has a well-defined semantics for inheritance :)</p>\n" }, { "answer_id": 3580745, "author": "Ergwun", "author_id": 177018, "author_profile": "https://Stackoverflow.com/users/177018", "pm_score": 4, "selected": false, "text": "<p>One thing you can't do with <code>[TestFixtureSetup]</code> that you can do in the constructor is receive parameters from the <code>[TestFixture]</code> .</p>\n\n<p>If you want to parameterise your test fixture, then you will have to use the constructor for at least <em>some</em> of the set-up. So far, I've only used this for integration tests, e.g. for testing a data access layer with multiple data providers:</p>\n\n<pre><code>[TestFixture(\"System.Data.SqlClient\",\n \"Server=(local)\\\\SQLEXPRESS;Initial Catalog=MyTestDatabase;Integrated Security=True;Pooling=False\"))]\n[TestFixture(\"System.Data.SQLite\", \"Data Source=MyTestDatabase.s3db\")])]\ninternal class MyDataAccessLayerIntegrationTests\n{\n MyDataAccessLayerIntegrationTests(\n string dataProvider,\n string connectionString)\n {\n ...\n }\n}\n</code></pre>\n" }, { "answer_id": 8817850, "author": "oderibas", "author_id": 470325, "author_profile": "https://Stackoverflow.com/users/470325", "pm_score": 4, "selected": false, "text": "<p>There is difference between constructor and method marked with <code>[TestFixtureSetUp]</code> attribute. According to NUnit documentation:</p>\n\n<blockquote>\n <p>It is advisable that the constructor not have any side effects, since NUnit may construct the object multiple times in the course of a session.</p>\n</blockquote>\n\n<p>So if you have any expensive initialization it is better to use <code>TestFixtureSetUp</code>.</p>\n" }, { "answer_id": 11011682, "author": "nonexistent myth", "author_id": 1453240, "author_profile": "https://Stackoverflow.com/users/1453240", "pm_score": -1, "selected": false, "text": "<p>The constructor and the <code>SetUp</code> methods are used differently:<br>\nThe constructor is run only once.<br>\nHowever, the <code>SetUp</code> methods are run multiple times, before every test case is executed.</p>\n" }, { "answer_id": 35290105, "author": "Shankar S", "author_id": 2584363, "author_profile": "https://Stackoverflow.com/users/2584363", "pm_score": 2, "selected": false, "text": "<p><code>[TestFixtureSetUp]</code> and <code>[TestFixtureTearDown]</code> are for whole test class. runs only once.</p>\n\n<p><code>[SetUp]</code> and <code>[TearDown]</code> are for every test method(test). runs for every test.</p>\n" }, { "answer_id": 36043052, "author": "Novaterata", "author_id": 2323964, "author_profile": "https://Stackoverflow.com/users/2323964", "pm_score": 2, "selected": false, "text": "<p>An important difference between constructor and TestFixtureSetUp is that, in NUnit 2 at least, constructor code is actually executed on test enumeration, not just test running, so basically you want to limit ctor code to only populating readonly, i.e. parameter, values. Anything that causes side-effects or does any actual work needs to either be wrapped in a Lazy or done in the TestFixtureSetUp / OneTimeSetUp. So, you can think of the constructor as solely a place to configure the test. Whereas the TestFixtureSetUp is where the test fixture, the required initial state of the system before tests are run, is initialized.</p>\n" }, { "answer_id": 74661613, "author": "RM.", "author_id": 310691, "author_profile": "https://Stackoverflow.com/users/310691", "pm_score": 0, "selected": false, "text": "<p>The method with [SetUp] may be async. The constructor can not be.</p>\n" } ]
2008/10/17
[ "https://Stackoverflow.com/questions/212718", "https://Stackoverflow.com", "https://Stackoverflow.com/users/13376/" ]
The NUnit documentation doesn't tell me when to use a method with a `TestFixtureSetup` and when to do the setup in the constructor. ``` public class MyTest { private MyClass myClass; public MyTest() { myClass = new MyClass(); } [TestFixtureSetUp] public void Init() { myClass = new MyClass(); } } ``` Are there any good/bad practices about the `TestFixtureSetup` versus default constructor or isn't there any difference?
I think this has been one of the issues that hasn't been addressed by the nUnit team. However, there is the excellent [xUnit project](http://www.codeplex.com/xunit) that saw this exact issue and decided that constructors were a good thing to use on [test fixture initialization](http://www.codeplex.com/xunit/Wiki/View.aspx?title=Comparisons&referringTitle=Home#attributes). For nunit, my best practice in this case has been to use the `TestFixtureSetUp`, `TestFixtureTearDown`, `SetUp`, and `TearDown` methods as described in the documentation. I think it also helps me when I don't think of an nUnit test fixture as a normal class, even though you are defining it with that construct. I think of them as fixtures, and that gets me over the mental hurdle and allows me to overlook this issue.
212,734
<p>How do you automatically start a service after running an install from a Visual Studio Setup Project?</p> <p>I just figured this one out and thought I would share the answer for the general good. Answer to follow. I am open to other and better ways of doing this.</p>
[ { "answer_id": 212736, "author": "Jason Z", "author_id": 2470, "author_profile": "https://Stackoverflow.com/users/2470", "pm_score": 7, "selected": true, "text": "<p>Add the following class to your project.</p>\n\n<pre><code>using System.ServiceProcess; \n\nclass ServInstaller : ServiceInstaller\n{\n protected override void OnCommitted(System.Collections.IDictionary savedState)\n {\n ServiceController sc = new ServiceController(\"YourServiceNameGoesHere\");\n sc.Start();\n }\n}\n</code></pre>\n\n<p>The Setup Project will pick up the class and run your service after the installer finishes.</p>\n" }, { "answer_id": 732740, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 3, "selected": false, "text": "<p>thanks it run OK...</p>\n\n<pre><code>private System.ServiceProcess.ServiceInstaller serviceInstaller1;\n\nprivate void serviceInstaller1_AfterInstall(object sender, InstallEventArgs e)\n{\n ServiceController sc = new ServiceController(\"YourServiceName\");\n sc.Start();\n}\n</code></pre>\n" }, { "answer_id": 769445, "author": "andynil", "author_id": 446, "author_profile": "https://Stackoverflow.com/users/446", "pm_score": 5, "selected": false, "text": "<p>Small addition to accepted answer:</p>\n\n<p>You can also fetch the service name like this - avoiding any problems if service name is changed in the future:</p>\n\n<pre><code>protected override void OnCommitted(System.Collections.IDictionary savedState)\n{\n new ServiceController(serviceInstaller1.ServiceName).Start();\n}\n</code></pre>\n\n<p>(Every Installer has a ServiceProcessInstaller and a ServiceInstaller. Here the ServiceInstaller is called serviceInstaller1.)</p>\n" }, { "answer_id": 10531267, "author": "HeWillem", "author_id": 558133, "author_profile": "https://Stackoverflow.com/users/558133", "pm_score": 3, "selected": false, "text": "<p>Instead of creating your own class, select the service installer in the project installer and add an event handler to the Comitted event:</p>\n\n<pre><code>private void serviceInstallerService1_Committed(object sender, InstallEventArgs e)\n{\n var serviceInstaller = sender as ServiceInstaller;\n // Start the service after it is installed.\n if (serviceInstaller != null &amp;&amp; serviceInstaller.StartType == ServiceStartMode.Automatic)\n {\n var serviceController = new ServiceController(serviceInstaller.ServiceName);\n serviceController.Start();\n }\n}\n</code></pre>\n\n<p>It will start your service only if startup type is set to automatic.</p>\n" }, { "answer_id": 10661276, "author": "Jeffrey Roughgarden", "author_id": 381465, "author_profile": "https://Stackoverflow.com/users/381465", "pm_score": 2, "selected": false, "text": "<p>Based on the snippets above, my ProjectInstaller.cs file wound up looking like this for a service named FSWServiceMgr.exe. The service did start after installation. As a side note, remember to click on the Properties tab (not right-click) when the setup project is selected in the Solution Explorer to set the company and so forth.</p>\n\n<hr>\n\n<pre><code>using System.ComponentModel;\nusing System.Configuration.Install;\nusing System.ServiceProcess;\n\nnamespace FSWManager {\n [RunInstaller(true)]\n public partial class ProjectInstaller : Installer {\n public ProjectInstaller() {\n InitializeComponent();\n this.FSWServiceMgr.AfterInstall += FSWServiceMgr_AfterInstall;\n }\n\n static void FSWServiceMgr_AfterInstall(object sender, InstallEventArgs e) {\n new ServiceController(\"FSWServiceMgr\").Start();\n }\n }\n}\n</code></pre>\n" }, { "answer_id": 10762880, "author": "Keith", "author_id": 65775, "author_profile": "https://Stackoverflow.com/users/65775", "pm_score": 5, "selected": false, "text": "<p>This approach uses the Installer class and the least amount of code.</p>\n\n<pre><code>using System.ComponentModel;\nusing System.Configuration.Install;\nusing System.ServiceProcess;\n\nnamespace MyProject\n{\n [RunInstaller(true)]\n public partial class ProjectInstaller : Installer\n {\n public ProjectInstaller()\n {\n InitializeComponent();\n serviceInstaller1.AfterInstall += (sender, args) =&gt; new ServiceController(serviceInstaller1.ServiceName).Start();\n }\n }\n}\n</code></pre>\n\n<p>Define <code>serviceInstaller1</code> (type ServiceInstaller) in the Installer class designer and also set its <code>ServiceName</code> property in the designer.</p>\n" }, { "answer_id": 50206281, "author": "Sagar Kapadia", "author_id": 6028866, "author_profile": "https://Stackoverflow.com/users/6028866", "pm_score": 0, "selected": false, "text": "<p>There is also another way which does not involve code. You can use the Service Control Table. Edit the generated msi file with orca.exe, and add an entry to the <a href=\"https://msdn.microsoft.com/en-us/library/windows/desktop/aa371634(v=vs.85).aspx\" rel=\"nofollow noreferrer\">ServiceControl Table</a>.</p>\n\n<p>Only the ServiceControl, Name,Event and Component_ columns are mandatory. The Component_ column contains the ComponentId from the File Table. (Select the File in the file table, and copy the Component_value to the ServiceControl table.)</p>\n\n<p>The last step is to update the value of StartServices to 6575 in table InstallExecutesequence. This is sufficient to start the service.</p>\n\n<p>By the way, the service install table allows you to configure the installer to install the windows service.</p>\n" } ]
2008/10/17
[ "https://Stackoverflow.com/questions/212734", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2470/" ]
How do you automatically start a service after running an install from a Visual Studio Setup Project? I just figured this one out and thought I would share the answer for the general good. Answer to follow. I am open to other and better ways of doing this.
Add the following class to your project. ``` using System.ServiceProcess; class ServInstaller : ServiceInstaller { protected override void OnCommitted(System.Collections.IDictionary savedState) { ServiceController sc = new ServiceController("YourServiceNameGoesHere"); sc.Start(); } } ``` The Setup Project will pick up the class and run your service after the installer finishes.
212,745
<p>I'm on OS X 10.5.5 (though it does not matter much I guess)</p> <p>I have a set of text files with fancy characters like double backquotes, ellipsises ("...") in one character etc. </p> <p>I need to convert these files to good old plain 7-bit ASCII, preferably without losing character meaning (that is, convert those ellipses to three periods, backquotes to usual "s etc.).</p> <p>Please advise some smart command-line (bash) tool/script to do that.</p>
[ { "answer_id": 212875, "author": "unwind", "author_id": 28169, "author_profile": "https://Stackoverflow.com/users/28169", "pm_score": 1, "selected": false, "text": "<p><a href=\"http://www.manpagez.com/man/1/iconv/\" rel=\"nofollow noreferrer\">iconv</a> should do it, as far as I know. Not 100% certain about how it handles conversions where one input character should/could become several output characters, such as with the ellipsis example ... Something to try!</p>\n\n<p>Update: I did try it, and it seems it doesn't work. It fails, possibly since it doesn't know how to express ellipsis (the test character I used) in a \"smaller\" encoding. Converting from UTF-8 to UTF-16 went fine. :/ Still, iconv might be worth investigating further.</p>\n" }, { "answer_id": 212923, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 1, "selected": false, "text": "<p>Have a look at transliteration tools; I like <a href=\"http://search.cpan.org/~sburke/Text-Unidecode-0.04/lib/Text/Unidecode.pm\" rel=\"nofollow noreferrer\">Unidecode</a> (in Perl), and it's not too hard to port to other languages.</p>\n" }, { "answer_id": 212955, "author": "Josh Lee", "author_id": 19750, "author_profile": "https://Stackoverflow.com/users/19750", "pm_score": 3, "selected": true, "text": "<p>The <a href=\"http://elinks.or.cz/\" rel=\"nofollow noreferrer\">Elinks</a> web browser will convert Unicode entities to their ASCII equivalents, giving things like \"--\" for \"—\" and \"...\" for \"…\", etc. There is a python module <a href=\"http://code.google.com/p/python-elinks/\" rel=\"nofollow noreferrer\">python-elinks</a> which uses the same conversion table, and it would be trivial to turn it into a shell filter, like this:</p>\n\n<pre><code>#!/usr/bin/env python\nimport elinks\nimport sys\nfor line in sys.stdin:\n line = line.decode('utf-8')\n sys.stdout.write(line.encode('ASCII', 'elinks'))\n</code></pre>\n" }, { "answer_id": 212969, "author": "Jonathan Leffler", "author_id": 15168, "author_profile": "https://Stackoverflow.com/users/15168", "pm_score": 0, "selected": false, "text": "<p>There was a question yesterday or the day before about file renaming, and I showed a Perl script <code>rename.pl</code> that would be usable for the task. The problem area is knowing how the odd characters are encoded, and devising the correct sequence of transliterations. I'd probably do it with an adaptation of that script that did all the mappings sequentially. Doing it one character at a time would be unduly fiddly.</p>\n\n<p>Question was: <a href=\"https://stackoverflow.com/questions/208181/how-to-rename-with-prefixsuffix\">How to rename with prefix/suffix</a></p>\n" }, { "answer_id": 354969, "author": "glennkentwell", "author_id": 32795, "author_profile": "https://Stackoverflow.com/users/32795", "pm_score": 1, "selected": false, "text": "<p>I have used iconv to convert a file from UTF-16LE (little-endian as I found out by trial and error) that was created by TextPad in Windows into ASCII on OSX like this:</p>\n\n<pre><code> cat utf16file.txt |iconv -f UTF-16LE -t ASCII &gt; asciifile.txt\n</code></pre>\n\n<p>You can pipe through hexdump as well to view the characters and make sure you're getting the right output, the terminal knows how to interpret UTF-16 and displays it properly so you can't tell just but doing 'cat' on the file:</p>\n\n<pre><code>cat utf16file.txt | iconv -f UTF-16LE -t ASCII | hexdump -C \n</code></pre>\n\n<p>This shows the layout with the hex char codes and the ASCII characters to the right-hand side, and you can try different encodings in the -f \"from\" parameter to figure out what you're dealing with.</p>\n\n<p>Use 'iconv -l' to list the character sets iconv can use on your system.</p>\n" } ]
2008/10/17
[ "https://Stackoverflow.com/questions/212745", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6236/" ]
I'm on OS X 10.5.5 (though it does not matter much I guess) I have a set of text files with fancy characters like double backquotes, ellipsises ("...") in one character etc. I need to convert these files to good old plain 7-bit ASCII, preferably without losing character meaning (that is, convert those ellipses to three periods, backquotes to usual "s etc.). Please advise some smart command-line (bash) tool/script to do that.
The [Elinks](http://elinks.or.cz/) web browser will convert Unicode entities to their ASCII equivalents, giving things like "--" for "—" and "..." for "…", etc. There is a python module [python-elinks](http://code.google.com/p/python-elinks/) which uses the same conversion table, and it would be trivial to turn it into a shell filter, like this: ``` #!/usr/bin/env python import elinks import sys for line in sys.stdin: line = line.decode('utf-8') sys.stdout.write(line.encode('ASCII', 'elinks')) ```
212,762
<p>I need generate <a href="https://stackoverflow.com/questions/27921/what-is-the-best-way-to-create-a-thumbnail-using-aspnet">thumbnails</a> for a bunch of jpegs (200,000+) but I want to make sure all of my thumbs have a equal height and width. However, I don't want to change the proportions of the image so I need to add empty space to the shorter dimension to "square it up". The empty space's background color is variable. </p> <p>Here's the code snippet I'm using to generate the thumbs. What's the best way to do the squaring?</p> <pre><code> Dim imgDest As System.Drawing.Bitmap = New Bitmap(ScaleWidth, ScaleHeight) imgDest.SetResolution(TARGET_RESOLUTION, TARGET_RESOLUTION) Dim grDest As Graphics = Graphics.FromImage(imgDest) grDest.DrawImage(SourceImage, 0, 0, imgDest.Width, imgDest.Height) </code></pre>
[ { "answer_id": 212791, "author": "Vaibhav", "author_id": 380, "author_profile": "https://Stackoverflow.com/users/380", "pm_score": 3, "selected": true, "text": "<p>How about this. Maybe you should draw a black (or whichever color) rectangle on the Bitmap first.</p>\n\n<p>And then when you are placing the resized image, just calculate the placement of the image based on whichever dimension is shorter, and then move that dimension by half the difference (and keep the other on 0).</p>\n\n<p>Wouldn't that work?</p>\n" }, { "answer_id": 216042, "author": "Ates Goral", "author_id": 23501, "author_profile": "https://Stackoverflow.com/users/23501", "pm_score": 2, "selected": false, "text": "<p>Like <strong>Vaibhav</strong> said, first paint the entire thumbnail area with black. This will be simpler than first fitting the image into the thumbnail and then determining which rectangles to paint black to achieve <a href=\"http://en.wikipedia.org/wiki/Pillarbox\" rel=\"nofollow noreferrer\">pillarboxing</a> or <a href=\"http://en.wikipedia.org/wiki/Letterbox\" rel=\"nofollow noreferrer\">letterboxing</a>.</p>\n\n<p>Pseudo-code for a general solution to fit an <code>imageWidth</code> x <code>imageHeight</code> image into a <code>thumbWidth</code> x <code>thumbHeight</code> (doesn't have to be a square) area:</p>\n\n<pre><code>imageRatio = imageWidth / imageHeight;\nthumbRatio = thumbWidth / thumbHeight;\n\nzoomFactor = imageRatio &gt;= thumbRatio\n ? thumbWidth / imageWidth \n : thumbHeight / imageHeight;\n\ndestWidth = imageWidth * zoomFactor;\ndestHeight = imageHeight * zoomFactor;\n\ndrawImage(\n (thumbWidth - destWidth) &gt;&gt; 1,\n (thumbHeight - destHeight) &gt;&gt; 1,\n destWidth,\n destHeight);\n</code></pre>\n" } ]
2008/10/17
[ "https://Stackoverflow.com/questions/212762", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4796/" ]
I need generate [thumbnails](https://stackoverflow.com/questions/27921/what-is-the-best-way-to-create-a-thumbnail-using-aspnet) for a bunch of jpegs (200,000+) but I want to make sure all of my thumbs have a equal height and width. However, I don't want to change the proportions of the image so I need to add empty space to the shorter dimension to "square it up". The empty space's background color is variable. Here's the code snippet I'm using to generate the thumbs. What's the best way to do the squaring? ``` Dim imgDest As System.Drawing.Bitmap = New Bitmap(ScaleWidth, ScaleHeight) imgDest.SetResolution(TARGET_RESOLUTION, TARGET_RESOLUTION) Dim grDest As Graphics = Graphics.FromImage(imgDest) grDest.DrawImage(SourceImage, 0, 0, imgDest.Width, imgDest.Height) ```
How about this. Maybe you should draw a black (or whichever color) rectangle on the Bitmap first. And then when you are placing the resized image, just calculate the placement of the image based on whichever dimension is shorter, and then move that dimension by half the difference (and keep the other on 0). Wouldn't that work?
212,763
<p>My Win form app doesn't seem to like FormsAuthentication, I'm totally new to hashing so any help to convert this would be very welcome. Thanks.</p> <pre><code>//Write hash protected TextBox tbPassword; protected Literal liHashedPassword; { string strHashedPassword = FormsAuthentication.HashPasswordForStoringInConfigFile(tbPassword.Text, "sha1"); liHashedPassword.Text = "Hashed Password is: " + strHashedPassword; } //read hash string strUserInputtedHashedPassword = FormsAuthentication.HashPasswordForStoringInConfigFile( tbPassword.Text, "sha1"); if(strUserInputtedHashedPassword == GetUsersHashedPasswordUsingUserName(tbUserName.Text)) { // sign-in successful } else { // sign-in failed } </code></pre>
[ { "answer_id": 212772, "author": "Vaibhav", "author_id": 380, "author_profile": "https://Stackoverflow.com/users/380", "pm_score": 1, "selected": false, "text": "<p>I think it should work. All you need to do is reference System.Web.Security in your code (and add it as a reference in your Visual Studio Project).</p>\n" }, { "answer_id": 212783, "author": "James Curran", "author_id": 12725, "author_profile": "https://Stackoverflow.com/users/12725", "pm_score": 2, "selected": false, "text": "<p>The FormsAuthentication is defined in the System.Web.Security namespace which is in the System.Web.dll assembly.</p>\n\n<p>Just because you are writing a WinForm app does not stop you from using that namespace or referencing that assembly; they are just not done by default as they would be for a WebForms app.</p>\n" }, { "answer_id": 212822, "author": "Mark Cidade", "author_id": 1659, "author_profile": "https://Stackoverflow.com/users/1659", "pm_score": 5, "selected": false, "text": "<pre><code>using System.Security.Cryptography;\n\npublic static string EncodePasswordToBase64(string password)\n{ byte[] bytes = Encoding.Unicode.GetBytes(password);\n byte[] inArray = HashAlgorithm.Create(\"SHA1\").ComputeHash(bytes);\n return Convert.ToBase64String(inArray);\n} \n</code></pre>\n\n\n" }, { "answer_id": 212846, "author": "user28636", "author_id": 28636, "author_profile": "https://Stackoverflow.com/users/28636", "pm_score": 1, "selected": false, "text": "<p>If you actually have to 'ship' this forms app, maybe adding System.Web.Security is not such a good idea...</p>\n\n<p>If you need an SHA1 hash, there is a very easy to use .net cryptography library with examples on msdn. The key is to </p>\n\n<ol>\n<li>take what you want to encrypt</li>\n<li>turn it into bytes for whichever encoding(ascii, utf*) you are using</li>\n<li>Use one of the many hashing schemes builtin to .Net to get the hashed bytes</li>\n<li>turn those bytes back into a string in the same encoding as in step 2</li>\n<li>Save the resulting hashed string somewhere for later comparison</li>\n</ol>\n\n<hr>\n\n<pre><code>//step 1 and 2\nbyte[] data = System.Text.Encoding.Unicode.GetBytes(tbPassword.Text,);\nbyte[] result; \n\n//step 3\nSHA1 sha = new SHA1CryptoServiceProvider(); \nresult = sha.ComputeHash(data);\n\n//step 4\nstring storableHashResult = System.Text.Encoding.Unicode.ToString(result);\n\n//step 5\n // add your code here\n</code></pre>\n" }, { "answer_id": 276002, "author": "woany", "author_id": 15623, "author_profile": "https://Stackoverflow.com/users/15623", "pm_score": 1, "selected": false, "text": "<p>Could you not use the BitConverter function instead of the \"x2\" loop?</p>\n\n<p>e.g.</p>\n\n<p>return BitConverter.ToString(hash).Replace(\"-\", \"\");</p>\n" }, { "answer_id": 12718924, "author": "thashiznets", "author_id": 1718716, "author_profile": "https://Stackoverflow.com/users/1718716", "pm_score": 2, "selected": false, "text": "<p>If you are using the hashing for user credentials I suggest you do more than just hashing, you ideally want key stretching as well.</p>\n\n<p>Here is an API to do what you want in a secure fashion:</p>\n\n<p><a href=\"https://sourceforge.net/projects/pwdtknet/\" rel=\"nofollow\">https://sourceforge.net/projects/pwdtknet/</a></p>\n" } ]
2008/10/17
[ "https://Stackoverflow.com/questions/212763", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
My Win form app doesn't seem to like FormsAuthentication, I'm totally new to hashing so any help to convert this would be very welcome. Thanks. ``` //Write hash protected TextBox tbPassword; protected Literal liHashedPassword; { string strHashedPassword = FormsAuthentication.HashPasswordForStoringInConfigFile(tbPassword.Text, "sha1"); liHashedPassword.Text = "Hashed Password is: " + strHashedPassword; } //read hash string strUserInputtedHashedPassword = FormsAuthentication.HashPasswordForStoringInConfigFile( tbPassword.Text, "sha1"); if(strUserInputtedHashedPassword == GetUsersHashedPasswordUsingUserName(tbUserName.Text)) { // sign-in successful } else { // sign-in failed } ```
``` using System.Security.Cryptography; public static string EncodePasswordToBase64(string password) { byte[] bytes = Encoding.Unicode.GetBytes(password); byte[] inArray = HashAlgorithm.Create("SHA1").ComputeHash(bytes); return Convert.ToBase64String(inArray); } ```
212,797
<p>It seems</p> <pre><code>import Queue Queue.Queue().get(timeout=10) </code></pre> <p>is keyboard interruptible (ctrl-c) whereas</p> <pre><code>import Queue Queue.Queue().get() </code></pre> <p>is not. I could always create a loop;</p> <pre><code>import Queue q = Queue() while True: try: q.get(timeout=1000) except Queue.Empty: pass </code></pre> <p>but this seems like a strange thing to do.</p> <p>So, is there a way of getting an indefinitely waiting but keyboard interruptible Queue.get()?</p>
[ { "answer_id": 212975, "author": "Eli Courtwright", "author_id": 1694, "author_profile": "https://Stackoverflow.com/users/1694", "pm_score": 4, "selected": true, "text": "<p><code>Queue</code> objects have this behavior because they lock using <code>Condition</code> objects form the <code>threading</code> module. So your solution is really the only way to go.</p>\n\n<p>However, if you really want a <code>Queue</code> method that does this, you can monkeypatch the <code>Queue</code> class. For example:</p>\n\n<pre><code>def interruptable_get(self):\n while True:\n try:\n return self.get(timeout=1000)\n except Queue.Empty:\n pass\nQueue.interruptable_get = interruptable_get\n</code></pre>\n\n<p>This would let you say</p>\n\n<pre><code>q.interruptable_get()\n</code></pre>\n\n<p>instead of</p>\n\n<pre><code>interruptable_get(q)\n</code></pre>\n\n<p>although monkeypatching is generally discouraged by the Python community in cases such as these, since a regular function seems just as good.</p>\n" }, { "answer_id": 216719, "author": "Anders Waldenborg", "author_id": 24082, "author_profile": "https://Stackoverflow.com/users/24082", "pm_score": 2, "selected": false, "text": "<p>This may not apply to your use case at all. But I've successfully used this pattern in several cases: (sketchy and likely buggy, but you get the point).</p>\n\n<pre><code>STOP = object()\n\ndef consumer(q):\n while True:\n x = q.get()\n if x is STOP:\n return\n consume(x)\n\ndef main()\n q = Queue()\n c=threading.Thread(target=consumer,args=[q])\n\n try:\n run_producer(q)\n except KeybordInterrupt:\n q.enqueue(STOP)\n c.join()\n</code></pre>\n" } ]
2008/10/17
[ "https://Stackoverflow.com/questions/212797", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2010/" ]
It seems ``` import Queue Queue.Queue().get(timeout=10) ``` is keyboard interruptible (ctrl-c) whereas ``` import Queue Queue.Queue().get() ``` is not. I could always create a loop; ``` import Queue q = Queue() while True: try: q.get(timeout=1000) except Queue.Empty: pass ``` but this seems like a strange thing to do. So, is there a way of getting an indefinitely waiting but keyboard interruptible Queue.get()?
`Queue` objects have this behavior because they lock using `Condition` objects form the `threading` module. So your solution is really the only way to go. However, if you really want a `Queue` method that does this, you can monkeypatch the `Queue` class. For example: ``` def interruptable_get(self): while True: try: return self.get(timeout=1000) except Queue.Empty: pass Queue.interruptable_get = interruptable_get ``` This would let you say ``` q.interruptable_get() ``` instead of ``` interruptable_get(q) ``` although monkeypatching is generally discouraged by the Python community in cases such as these, since a regular function seems just as good.
212,805
<pre><code>Object o = new Long[0] System.out.println( o.getClass().isArray() ) System.out.println( o.getClass().getName() ) Class ofArray = ??? </code></pre> <p>Running the first 3 lines emits;</p> <pre><code>true [Ljava.lang.Long; </code></pre> <p>How do I get ??? to be type long? I could parse the string and do a Class.forname(), but thats grotty. What's the easy way?</p>
[ { "answer_id": 212816, "author": "ddimitrov", "author_id": 18187, "author_profile": "https://Stackoverflow.com/users/18187", "pm_score": 5, "selected": false, "text": "<p><a href=\"http://docs.oracle.com/javase/1.5.0/docs/api/java/lang/Class.html#getComponentType()\" rel=\"noreferrer\">http://java.sun.com/j2se/1.5.0/docs/api/java/lang/Class.html#getComponentType()</a>:</p>\n\n<blockquote>\n<pre><code>public Class&lt;?&gt; getComponentType()\n</code></pre>\n \n <p>Returns the <code>Class</code> representing the component type of an array. If this class does not represent an array class this method returns null... </p>\n</blockquote>\n" }, { "answer_id": 212817, "author": "sakana", "author_id": 28921, "author_profile": "https://Stackoverflow.com/users/28921", "pm_score": 7, "selected": true, "text": "<p>Just write </p>\n\n<pre><code>Class ofArray = o.getClass().getComponentType();\n</code></pre>\n\n<p>From <a href=\"http://docs.oracle.com/javase/8/docs/api/java/lang/Class.html#getComponentType--\" rel=\"noreferrer\">the JavaDoc</a>:</p>\n\n<blockquote>\n <p><code>public Class&lt;?&gt; getComponentType()</code></p>\n \n <p>Returns the <code>Class</code> representing the component type of an array. If this class does not represent an array class this method returns <code>null</code>.</p>\n</blockquote>\n" }, { "answer_id": 212855, "author": "Daniel Spiewak", "author_id": 9815, "author_profile": "https://Stackoverflow.com/users/9815", "pm_score": 3, "selected": false, "text": "<p>@ddimitrov is the correct answer. Put into code it looks like this:</p>\n\n<pre><code>public &lt;T&gt; Class&lt;T&gt; testArray(T[] array) {\n return array.getClass().getComponentType();\n}\n</code></pre>\n\n<p>Even more generally, we can test first to see if the type represents an array, and <em>then</em> get its component:</p>\n\n<pre><code>Object maybeArray = ...\nClass&lt;?&gt; clazz = maybeArray.getClass();\nif (clazz.isArray()) {\n System.out.printf(\"Array of type %s\", clazz.getComponentType());\n} else {\n System.out.println(\"Not an array\");\n}\n</code></pre>\n\n<p>A specific example would be applying this method to an array for which the component type is already known:</p>\n\n<pre><code>String[] arr = {\"Daniel\", \"Chris\", \"Joseph\"};\narr.getClass().getComponentType(); // =&gt; java.lang.String\n</code></pre>\n\n<p>Pretty straightforward!</p>\n" } ]
2008/10/17
[ "https://Stackoverflow.com/questions/212805", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6580/" ]
``` Object o = new Long[0] System.out.println( o.getClass().isArray() ) System.out.println( o.getClass().getName() ) Class ofArray = ??? ``` Running the first 3 lines emits; ``` true [Ljava.lang.Long; ``` How do I get ??? to be type long? I could parse the string and do a Class.forname(), but thats grotty. What's the easy way?
Just write ``` Class ofArray = o.getClass().getComponentType(); ``` From [the JavaDoc](http://docs.oracle.com/javase/8/docs/api/java/lang/Class.html#getComponentType--): > > `public Class<?> getComponentType()` > > > Returns the `Class` representing the component type of an array. If this class does not represent an array class this method returns `null`. > > >
212,821
<p>In this class for example, I want to force a limit of characters the first/last name can allow.</p> <pre><code>public class Person { public string FirstName { get; set; } public string LastName { get; set; } } </code></pre> <p>Is there a way to force the string limit restriction for the first or last name, so <strong>when the client serializes this</strong> before sending it to me, it would throw an error on their side if it violates the lenght restriction?</p> <p>Update: this needs to be identified and forced in the WSDL itself, and not after I've recieved the invalid data.</p>
[ { "answer_id": 212836, "author": "Mitchel Sellers", "author_id": 13279, "author_profile": "https://Stackoverflow.com/users/13279", "pm_score": 0, "selected": false, "text": "<p>COnvert the property from an auto property and validate it yourself, you could then throw an argument exception or something similar that they would have to handle before submission.</p>\n\n<p>NOTE: if languages other than .NET will be calling you most likely want to be validating it on the service side as well. Or at minimun test to see how it would work in another language.</p>\n" }, { "answer_id": 212917, "author": "Mark Cidade", "author_id": 1659, "author_profile": "https://Stackoverflow.com/users/1659", "pm_score": 2, "selected": false, "text": "<p>You can apply XML Schema validation (e.g., <em>maxLength</em> facet) using <a href=\"https://web.archive.org/web/20150118095235/http://msdn.microsoft.com/en-us/magazine/cc164115.aspx\" rel=\"nofollow noreferrer\">SOAP Extensions</a>:</p>\n\n<pre><code>[ValidationSchema(\"person.xsd\")]\npublic class Person { /* ... */ }\n\n&lt;!-- person.xsd --&gt;\n\n&lt;?xml version=\"1.0\"?&gt;\n&lt;xsd:schema xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\"&gt;\n\n &lt;xsd:element name=\"Person\" type=\"PersonType\" /&gt;\n\n &lt;xsd:simpleType name=\"NameString\"&gt;\n &lt;xsd:restriction base=\"xsd:string\"&gt;\n &lt;xsd:maxLength value=\"255\"/&gt;\n &lt;/xsd:restriction&gt;\n &lt;/xsd:simpleType&gt;\n\n &lt;xsd:complexType name=\"PersonType\"&gt;\n &lt;xsd:sequence&gt;\n &lt;xsd:element name=\"FirstName\" type=\"NameString\" maxOccurs=\"1\"/&gt;\n &lt;xsd:element name=\"LastName\" type=\"NameString\" maxOccurs=\"1\"/&gt;\n &lt;/xsd:sequence&gt;\n &lt;/xsd:complexType&gt;\n&lt;/xsd:schema&gt;\n</code></pre>\n" }, { "answer_id": 5469051, "author": "Jason", "author_id": 681540, "author_profile": "https://Stackoverflow.com/users/681540", "pm_score": 4, "selected": false, "text": "<p>necro time... It worth mentioning though.</p>\n\n<pre><code>using System.ComponentModel.DataAnnotations;\npublic class Person\n{\n [StringLength(255, ErrorMessage = \"Error\")]\n public string FirstName { get; set; }\n [StringLength(255, ErrorMessage = \"Error\")]\n public string LastName { get; set; }\n}\n</code></pre>\n" } ]
2008/10/17
[ "https://Stackoverflow.com/questions/212821", "https://Stackoverflow.com", "https://Stackoverflow.com/users/820/" ]
In this class for example, I want to force a limit of characters the first/last name can allow. ``` public class Person { public string FirstName { get; set; } public string LastName { get; set; } } ``` Is there a way to force the string limit restriction for the first or last name, so **when the client serializes this** before sending it to me, it would throw an error on their side if it violates the lenght restriction? Update: this needs to be identified and forced in the WSDL itself, and not after I've recieved the invalid data.
necro time... It worth mentioning though. ``` using System.ComponentModel.DataAnnotations; public class Person { [StringLength(255, ErrorMessage = "Error")] public string FirstName { get; set; } [StringLength(255, ErrorMessage = "Error")] public string LastName { get; set; } } ```
212,896
<p>With the recent announcement of .NET 4.0 and Visual Studio 2010, it is becoming ever more difficult to keep track of what .NET Framework versions build on what version of the CLR and belong with which version(s) of Visual Studio.</p> <p>Is there a definitive table that shows these relationships?</p>
[ { "answer_id": 212912, "author": "DOK", "author_id": 27637, "author_profile": "https://Stackoverflow.com/users/27637", "pm_score": 3, "selected": false, "text": "<p>It's hard to find, isn't it? I believe these are the versions (ignoring service packs)</p>\n\n<ul>\n<li>Visual Studio version 6 = last one before <a href=\"http://en.wikipedia.org/wiki/.NET_Framework\" rel=\"nofollow noreferrer\">.NET</a>, released in 1998</li>\n<li>Visual Studio 2002 = version 7.1, Rainier, first .NET version retroactively added 2002 to the name, .NET 1.0 -- released Feb 2002</li>\n<li>Visual Studio 2003 = version 7, Everett, .NET 1.1 -- released early 2003.</li>\n<li>Visual Studio 2005 = version 8 Whidbey, .NET 2.0 &amp; 3.0 -- launch was Nov 2005. No longer called Visual Studio .NET</li>\n<li>Visual Studio 2008 = version 9 Orcas, .NET 3.5 -- released 11/19/2007 as 9.0.21022.8</li>\n<li>Visual Studio 2010 = version 10 Hawaii</li>\n</ul>\n\n<p>The next version of Visual Studio Team System is Rosario.</p>\n\n<p><em><a href=\"http://support.microsoft.com/kb/318785\" rel=\"nofollow noreferrer\">How to determine which versions and service pack levels of the Microsoft .NET Framework are installed</a></em> will give you more information about build numbers and service packs, but only through .NET 2.0.</p>\n" }, { "answer_id": 212929, "author": "Scott Dorman", "author_id": 1559, "author_profile": "https://Stackoverflow.com/users/1559", "pm_score": 7, "selected": true, "text": "<pre>\nVisual Studio CLR .NET Framework\n----------------------------------------------------------------------------------------\nVisual Studio .NET (Ranier) 1.0.3705 1.0\nVisual Studio 2003 (Everett) 1.1.4322 1.1\nVisual Studio 2005 (Whidbey) 2.0.50727 2.0\nVisual Studio 2005 with .NET 3.0 Extensions 2.0.50727 2.0, 3.0\nVisual Studio 2008 (Orcas) 2.0.50727 2.0 SP1, 3.0 SP1, 3.5\nVisual Studio 2008 SP1 2.0.50727 2.0 SP2, 3.0 SP2, 3.5 SP1\nVisual Studio 2010 (Hawaii) 4.0.30319 4.0\n</pre>\n\n<p>Expanding on this a bit, and including some of the information from dok1's answer, the actual version numbers for the different shipped builds of the .NET Framework are available on Aaron Stebner's <a href=\"http://blogs.msdn.com/astebner/archive/2005/07/12/what-net-framework-version-numbers-go-with-what-service-pack.aspx\" rel=\"noreferrer\">blog</a>, which covers everything from 1.0 through 3.5 SP1.</p>\n\n<p>The actual Visual Studio version numbers are:</p>\n\n<pre>\nProduct Name Version Ship Date\n----------------------------------------------------------------------------------------\nVisual Studio .NET 7.0.?? 02/2002\nVisual Studio .NET 2002 Service Pack 1 7.0.??\nVisual Studio 2003 7.1.?? 04/2003\nVisual Studio 2003 Service Pack 1 7.1.6030 09/13/2006\nVisual Studio 2005 8.0.5072.42\nVisual Studio 2005 Service Pack 1 12/14/2006\nVisual Studio 2008 9.0.21022.8 11/19/2007 \nVisual Studio 2008 SP1 9.0.30729.1\nVisual Studio 2010 10.0.30319.1 04/12/2010\nVisual Studio 2010 SP1 10.0.40219.1 03/03/2011\n</pre>\n\n<p><em>Please help fill in the missing pieces. This is all I could easily find online.</em></p>\n\n<p><em>Thanks to @DannySmurf for the information on the full version numbers for the CLR.</em></p>\n" }, { "answer_id": 884347, "author": "Lucas", "author_id": 24231, "author_profile": "https://Stackoverflow.com/users/24231", "pm_score": 5, "selected": false, "text": "<p>Note that while 3.0 bascially only added new assemblies (same CLR), 3.5 added new assemblies, new compiler, and updated the CLR to SP1 level.</p>\n\n<p>Framework 4.0 will be a whole new CLR (4.0, no CLR 3.x) which will run side-by-side with CLRs 1.1 and 2.0. It will also have all-new assemblies versioned 4.0 instead of using the 2.0 assemblies.</p>\n\n<pre>\nFramework CLR and Assemblies Release\n----------------------------------------------------------\n1.0 RTM 1.0.3705.0 Visual Studio .NET (aka VS.NET 2002)\n1.0 SP1 1.0.3705.209\n1.0 SP2 1.0.3705.288\n1.0 SP3 1.0.3705.6018\n\n1.1 RTM 1.1.4322.573 VS.NET 2003\n1.1 SP1 1.1.4322.2032\n1.1 SP1 1.1.4322.2300 Windows Server 2003\n\n2.0 RTM 2.0.50727.42 Visual Studio 2005 RTM\n2.0 RTM 2.0.50727.312 Windows Vista\n2.0 SP1 2.0.50727.1433 Visual Studio 2008 RTM and .NET 3.5 RTM\n2.0 SP2 2.0.50727.3053 Visual Studio 2008 SP1 and .NET 3.5 SP1\n2.0 SP2 2.0.50727.4016 Windows Vista SP2 and Windows Server 2008 SP2\n2.0 SP2 2.0.50727.4927 Windows 7\n\nFramework CLR New assemblies\n----------------------------------------------------------\n3.0 RTM 2.0 RTM 3.0.4506.30 The only \"out-of-band\" non-SP framework release\n3.0 SP1 2.0 SP1 3.0.4506.648 Visual Studio 2008 RTM and .NET 3.5 RTM\n3.0 SP2 2.0 SP2 3.0.4506.2123 Visual Studio 2008 SP1 and .NET 3.5 SP1\n\n3.5 RTM 2.0 SP1 3.5.21022.8 Visual Studio 2008 RTM and .NET 3.5 RTM\n3.5 SP1 2.0 SP2 3.5.30729.01 Visual Studio 2008 SP1 and .NET 3.5 SP1\n3.5 SP1 2.0 SP2 3.5.30729.4926 Windows 7\n\nFramework CLR and Assemblies Release\n----------------------------------------------------------\n4.0 RTM 4.0.30319.1 Visual Studio 2010\n</pre>\n\n<p>(This was collected from various answers and linked documents, especially the MSDN article <em><a href=\"http://support.microsoft.com/kb/318785\" rel=\"nofollow noreferrer\">How to determine which versions and service pack levels of the Microsoft .NET Framework are installed</a></em> linked by <a href=\"https://stackoverflow.com/questions/212896/how-do-the-net-framework-clr-and-visual-studio-version-numbers-relate-to-each-o/212912#212912\">DOK</a>.) A full list with KB update versions and support retirement dates can be found on Wikipedia, <em><a href=\"http://en.wikipedia.org/wiki/List_of_.NET_Framework_versions\" rel=\"nofollow noreferrer\">List of .NET Framework versions</a></em>.</p>\n" }, { "answer_id": 2625837, "author": "Scott P", "author_id": 33848, "author_profile": "https://Stackoverflow.com/users/33848", "pm_score": 0, "selected": false, "text": "<p>Framework 4.0 RTM<P>Visual Studio 2010<p>Assembly Version 4.0.30319<p>Date 4/12/2010</p>\n" } ]
2008/10/17
[ "https://Stackoverflow.com/questions/212896", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1559/" ]
With the recent announcement of .NET 4.0 and Visual Studio 2010, it is becoming ever more difficult to keep track of what .NET Framework versions build on what version of the CLR and belong with which version(s) of Visual Studio. Is there a definitive table that shows these relationships?
``` Visual Studio CLR .NET Framework ---------------------------------------------------------------------------------------- Visual Studio .NET (Ranier) 1.0.3705 1.0 Visual Studio 2003 (Everett) 1.1.4322 1.1 Visual Studio 2005 (Whidbey) 2.0.50727 2.0 Visual Studio 2005 with .NET 3.0 Extensions 2.0.50727 2.0, 3.0 Visual Studio 2008 (Orcas) 2.0.50727 2.0 SP1, 3.0 SP1, 3.5 Visual Studio 2008 SP1 2.0.50727 2.0 SP2, 3.0 SP2, 3.5 SP1 Visual Studio 2010 (Hawaii) 4.0.30319 4.0 ``` Expanding on this a bit, and including some of the information from dok1's answer, the actual version numbers for the different shipped builds of the .NET Framework are available on Aaron Stebner's [blog](http://blogs.msdn.com/astebner/archive/2005/07/12/what-net-framework-version-numbers-go-with-what-service-pack.aspx), which covers everything from 1.0 through 3.5 SP1. The actual Visual Studio version numbers are: ``` Product Name Version Ship Date ---------------------------------------------------------------------------------------- Visual Studio .NET 7.0.?? 02/2002 Visual Studio .NET 2002 Service Pack 1 7.0.?? Visual Studio 2003 7.1.?? 04/2003 Visual Studio 2003 Service Pack 1 7.1.6030 09/13/2006 Visual Studio 2005 8.0.5072.42 Visual Studio 2005 Service Pack 1 12/14/2006 Visual Studio 2008 9.0.21022.8 11/19/2007 Visual Studio 2008 SP1 9.0.30729.1 Visual Studio 2010 10.0.30319.1 04/12/2010 Visual Studio 2010 SP1 10.0.40219.1 03/03/2011 ``` *Please help fill in the missing pieces. This is all I could easily find online.* *Thanks to @DannySmurf for the information on the full version numbers for the CLR.*
212,900
<p>I've used lex and yacc (more usually bison) in the past for various projects, usually translators (such as a subset of EDIF streamed into an EDA app). Additionally, I've had to support code based on lex/yacc grammars dating back decades. So I know my way around the tools, though I'm no expert.</p> <p>I've seen positive comments about Antlr in various fora in the past, and I'm curious as to what I may be missing. So if you've used both, please tell me what's better or more advanced in Antlr. My current constraints are that I work in a C++ shop, and any product we ship will not include Java, so the resulting parsers would have to follow that rule.</p>
[ { "answer_id": 212930, "author": "Daniel Spiewak", "author_id": 9815, "author_profile": "https://Stackoverflow.com/users/9815", "pm_score": 8, "selected": true, "text": "<h3>Update/warning: This answer may be out of date!</h3>\n<hr />\n<p>One major difference is that ANTLR generates an LL(*) parser, whereas YACC and Bison both generate parsers that are LALR. This is an important distinction for a number of applications, the most obvious being operators:</p>\n<pre><code>expr ::= expr '+' expr\n | expr '-' expr\n | '(' expr ')'\n | NUM ;\n</code></pre>\n<p>ANTLR is entirely incapable of handling this grammar as-is. To use ANTLR (or any other LL parser generator), you would need to convert this grammar to something that is not left-recursive. However, Bison has no problem with grammars of this form. You would need to declare '+' and '-' as left-associative operators, but that is not strictly required for left recursion. A better example might be dispatch:</p>\n<pre><code>expr ::= expr '.' ID '(' actuals ')' ;\n\nactuals ::= actuals ',' expr | expr ;\n</code></pre>\n<p>Notice that both the <code>expr</code> and the <code>actuals</code> rules are left-recursive. This produces a much more efficient AST when it comes time for code generation because it avoids the need for multiple registers and unnecessary spilling (a left-leaning tree can be collapsed whereas a right-leaning tree cannot).</p>\n<p>In terms of personal taste, I think that LALR grammars are a lot easier to construct and debug. The downside is you have to deal with somewhat cryptic errors like shift-reduce and (the dreaded) reduce-reduce. These are errors that Bison catches when generating the parser, so it doesn't affect the end-user experience, but it can make the development process a bit more interesting. ANTLR is generally considered to be easier to use than YACC/Bison for precisely this reason.</p>\n" }, { "answer_id": 332753, "author": "John with waffle", "author_id": 279, "author_profile": "https://Stackoverflow.com/users/279", "pm_score": 3, "selected": false, "text": "<p>Another advantage of ANTRL is that you can use <a href=\"http://www.antlr.org/works/index.html\" rel=\"noreferrer\">ANTLRWORKS</a>, although I can't say that this is a strict advantage, as there may be similar tools for other generators as well.</p>\n" }, { "answer_id": 897927, "author": "Cristian Diaconescu", "author_id": 11545, "author_profile": "https://Stackoverflow.com/users/11545", "pm_score": 5, "selected": false, "text": "<p>A couple advantages for ANTLR:</p>\n\n<ul>\n<li>can output parsers in various languages - Java not required for running the generated parser.</li>\n<li>Awesome GUI makes grammar debugging easy (e.g. you can see the generated AST's right in the GUI, no extra tools required)</li>\n<li>Generated code is actually human-readable (it's one of the goals of ANTLR) and the fact that it generates LL parsers surely helps in this regard. </li>\n<li>definition of terminals is context-free as well (as opposed to regex in (f)lex) - thus permitting, for instance, the definition of <em>terminals</em> containing properly-closed parentheses</li>\n</ul>\n\n<p>My .02$</p>\n" }, { "answer_id": 1900429, "author": "trijezdci", "author_id": 231202, "author_profile": "https://Stackoverflow.com/users/231202", "pm_score": 7, "selected": false, "text": "<p>The most significant difference between YACC/Bison and ANTLR is the type of grammars these tools can process. YACC/Bison handle LALR grammars, ANTLR handles LL grammars.</p>\n\n<p>Often, people who have worked with LALR grammars for a long time, will find working with LL grammars more difficult and vice versa. That does not mean that the grammars or tools are inherently more difficult to work with. Which tool you find easier to use will mostly come down to familiarity with the type of grammar.</p>\n\n<p>As far as advantages go, there are aspects where LALR grammars have advantages over LL grammars and there are other aspects where LL grammars have advantages over LALR grammars. </p>\n\n<p>YACC/Bison generate table driven parsers, which means the \"processing logic\" is contained in the parser program's data, not so much in the parser's code. The pay off is that even a parser for a very complex language has a relatively small code footprint. This was more important in the 1960s and 1970s when hardware was very limited. Table driven parser generators go back to this era and small code footprint was a main requirement back then.</p>\n\n<p>ANTLR generates recursive descent parsers, which means the \"processing logic\" is contained in the parser's code, as each production rule of the grammar is represented by a function in the parser's code. The pay off is that it is easier to understand what the parser is doing by reading its code. Also, recursive descent parsers are typically faster than table driven ones. However, for very complex languages, the code footprint will be larger. This was a problem in the 1960s and 1970s. Back then, only relatively small languages like Pascal for instance were implemented this way due to hardware limitations.</p>\n\n<p>ANTLR generated parsers are typically in the vicinity of 10.000 lines of code and more. Handwritten recursive descent parsers are often in the same ballpark. Wirth's Oberon compiler is perhaps the most compact one with about 4000 lines of code including code generation, but Oberon is a very compact language with only about 40 production rules.</p>\n\n<p>As somebody has pointed out already, a big plus for ANTLR is the graphical IDE tool, called ANTLRworks. It is a complete grammar and language design laboratory. It visualises your grammar rules as you type them and if it finds any conflicts it will show you graphically what the conflict is and what causes it. It can even automatically refactor and resolve conflicts such as left-recursion. Once you have a conflict free grammar, you can let ANTLRworks parse an input file of your language and build a parse tree and AST for you and show the tree graphically in the IDE. This is a very big advantage because it can save you many hours of work: You will find conceptual errors in your language design before you start coding! I have not found any such tool for LALR grammars, it seems there isn't any such tool.</p>\n\n<p>Even to people who do not wish to generate their parsers but hand code them, ANTLRworks is a great tool for language design/prototyping. Quite possibly the best such tool available. Unfortunately, that doesn't help you if you want to build LALR parsers. Switching from LALR to LL simply to take advantage of ANTLRworks may well be worthwhile, but for some people, switching grammar types can be a very painful experience. In other words: YMMV.</p>\n" }, { "answer_id": 10831533, "author": "justme", "author_id": 1428113, "author_profile": "https://Stackoverflow.com/users/1428113", "pm_score": 3, "selected": false, "text": "<ul>\n<li>Bison and Flex result in a smaller memory footprint, but you have no graphical IDE.</li>\n<li>antlr uses more memory, but you have antlrworks, a graphical IDE.</li>\n</ul>\n\n<p>Bison/Flex memory usage is typically a mbyte or so. Contrast that with antlr - assuming it uses 512 bytes of memory for every token in the file you want to parse. 4 million tokens and you are out of virtual memory on a 32-bit system.</p>\n\n<p>If the file which you wish to parse is large, antlr may run out of memory, so if you just want to parse a configuration file, it would be a viable solution. Otherwise, if you want to parse a file with lots of data, try Bison.</p>\n" } ]
2008/10/17
[ "https://Stackoverflow.com/questions/212900", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3778/" ]
I've used lex and yacc (more usually bison) in the past for various projects, usually translators (such as a subset of EDIF streamed into an EDA app). Additionally, I've had to support code based on lex/yacc grammars dating back decades. So I know my way around the tools, though I'm no expert. I've seen positive comments about Antlr in various fora in the past, and I'm curious as to what I may be missing. So if you've used both, please tell me what's better or more advanced in Antlr. My current constraints are that I work in a C++ shop, and any product we ship will not include Java, so the resulting parsers would have to follow that rule.
### Update/warning: This answer may be out of date! --- One major difference is that ANTLR generates an LL(\*) parser, whereas YACC and Bison both generate parsers that are LALR. This is an important distinction for a number of applications, the most obvious being operators: ``` expr ::= expr '+' expr | expr '-' expr | '(' expr ')' | NUM ; ``` ANTLR is entirely incapable of handling this grammar as-is. To use ANTLR (or any other LL parser generator), you would need to convert this grammar to something that is not left-recursive. However, Bison has no problem with grammars of this form. You would need to declare '+' and '-' as left-associative operators, but that is not strictly required for left recursion. A better example might be dispatch: ``` expr ::= expr '.' ID '(' actuals ')' ; actuals ::= actuals ',' expr | expr ; ``` Notice that both the `expr` and the `actuals` rules are left-recursive. This produces a much more efficient AST when it comes time for code generation because it avoids the need for multiple registers and unnecessary spilling (a left-leaning tree can be collapsed whereas a right-leaning tree cannot). In terms of personal taste, I think that LALR grammars are a lot easier to construct and debug. The downside is you have to deal with somewhat cryptic errors like shift-reduce and (the dreaded) reduce-reduce. These are errors that Bison catches when generating the parser, so it doesn't affect the end-user experience, but it can make the development process a bit more interesting. ANTLR is generally considered to be easier to use than YACC/Bison for precisely this reason.
212,906
<p>My customer is replacing MS Office with OpenOffice in some workstations. My program export a file to Excel using the .xml extension (using open format) and opens it using the current associated program (using ShellExecute)</p> <p>The problem is that OpenOffice does not register the .xml extension associated with it.</p> <p>Manually association works fine, but I want to make a .reg or something to easily change the setting.</p> <p>I'm looking in the registry in a PC with the change already made, but the </p> <pre><code>"HKEY_CLASSES_ROOT\.xml" </code></pre> <p>key does not have anything referencing OpenOffice.</p> <p>Where is the association stored? How can I make a script to do the work?</p>
[ { "answer_id": 212921, "author": "Tomalak", "author_id": 18771, "author_profile": "https://Stackoverflow.com/users/18771", "pm_score": 5, "selected": true, "text": "<p>The real association is stored in the key that <code>\"HKEY_CLASSES_ROOT\\.xml\"</code> points to.</p>\n\n<p>On my machine, the default value of that key says <code>\"xmlfile\"</code>, most likely that is the same for yours.</p>\n\n<p>So let's go to <code>\"HKEY_CLASSES_ROOT\\xmlfile\"</code>. There you can see (and change) what command is going to be used to launch that type of file:</p>\n\n<pre><code>HKEY_CLASSES_ROOT\\xmlfile\\shell\\open\\command\n</code></pre>\n\n<p>Windows uses this kind of redirection to map multiple file extensions to the same file type, and thus to the same application.</p>\n\n<p>Under <code>\"HKEY_CLASSES_ROOT\\xmlfile\\shell\"</code> there are multiple sub-keys that resemble the \"verbs\" of what you can do to the file. Again, the default value of the <code>\"shell\"</code> key decides which of these verbs is used if you double click the file. In my case this is <code>\"open\"</code>.</p>\n\n<p><strong>Conclusion:</strong></p>\n\n<p>With that knowledge, the easiest way to make an association scriptable is to use regedit to export a .reg file containing that change, and apply it to the target computer with a double click or:</p>\n\n<pre><code>regedit /s new_xml_association.reg\n</code></pre>\n\n<p>or (if you are on XP or higher and know what you do) overwrite the current value with:</p>\n\n<pre><code>reg add \"HKEY_CLASSES_ROOT\\xmlfile\\shell\\open\\command\" /ve /d \"path\\to\\program %1\"\n</code></pre>\n\n<p>At any rate, a deeper look into <code>reg add/?</code> command is advised. The first solution is safer.</p>\n" }, { "answer_id": 212984, "author": "kenny", "author_id": 3225, "author_profile": "https://Stackoverflow.com/users/3225", "pm_score": 2, "selected": false, "text": "<p>consider the dos command <code>assoc</code>:</p>\n\n<blockquote>\n <p>C:>assoc /?\n Displays or modifies file extension\n associations</p>\n \n <p>ASSOC [.ext[=[fileType]]]</p>\n \n <p>.ext Specifies the file\n extension to associate the file type\n with fileType Specifies the file\n type to associate with the file\n extension</p>\n \n <p>Type ASSOC without parameters to\n display the current file associations.\n If ASSOC is invoked with just a file\n extension, it displays the current\n file association for that file\n extension. Specify nothing for the\n file type and the command will delete\n the association for the file\n extension.</p>\n</blockquote>\n" }, { "answer_id": 3719316, "author": "TheCodeKing", "author_id": 215057, "author_profile": "https://Stackoverflow.com/users/215057", "pm_score": -1, "selected": false, "text": "<p>I just came across this whilst searching for the same answer. I found a better solution using the Windows FindExecutable API, that can be used from C# using PInvoke.</p>\n\n<p><a href=\"http://www.pinvoke.net/default.aspx/shell32.findexecutable\" rel=\"nofollow noreferrer\">http://www.pinvoke.net/default.aspx/shell32.findexecutable</a></p>\n" }, { "answer_id": 12482098, "author": "user373533", "author_id": 373533, "author_profile": "https://Stackoverflow.com/users/373533", "pm_score": 1, "selected": false, "text": "<p>Using file associations in this case seems like the wrong thing to do. <em>You</em> want your application to open the file in OpenOffice but what if your user wants to leave the file association for XML files untouched? What if something else on their system also relies on that association? You are breaking their system in that case. If you are the IT person then perhaps that is OK (still questionable programming practice), but if not then this is a bad thing to do.</p>\n\n<p>Use the OpenOffice COM implementation to open the file instead.</p>\n\n<p>Good simple example here:\n<a href=\"http://www.kalitech.fr/clients/doc/VB_APIOOo_en.html\" rel=\"nofollow\">http://www.kalitech.fr/clients/doc/VB_APIOOo_en.html</a></p>\n" } ]
2008/10/17
[ "https://Stackoverflow.com/questions/212906", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2385/" ]
My customer is replacing MS Office with OpenOffice in some workstations. My program export a file to Excel using the .xml extension (using open format) and opens it using the current associated program (using ShellExecute) The problem is that OpenOffice does not register the .xml extension associated with it. Manually association works fine, but I want to make a .reg or something to easily change the setting. I'm looking in the registry in a PC with the change already made, but the ``` "HKEY_CLASSES_ROOT\.xml" ``` key does not have anything referencing OpenOffice. Where is the association stored? How can I make a script to do the work?
The real association is stored in the key that `"HKEY_CLASSES_ROOT\.xml"` points to. On my machine, the default value of that key says `"xmlfile"`, most likely that is the same for yours. So let's go to `"HKEY_CLASSES_ROOT\xmlfile"`. There you can see (and change) what command is going to be used to launch that type of file: ``` HKEY_CLASSES_ROOT\xmlfile\shell\open\command ``` Windows uses this kind of redirection to map multiple file extensions to the same file type, and thus to the same application. Under `"HKEY_CLASSES_ROOT\xmlfile\shell"` there are multiple sub-keys that resemble the "verbs" of what you can do to the file. Again, the default value of the `"shell"` key decides which of these verbs is used if you double click the file. In my case this is `"open"`. **Conclusion:** With that knowledge, the easiest way to make an association scriptable is to use regedit to export a .reg file containing that change, and apply it to the target computer with a double click or: ``` regedit /s new_xml_association.reg ``` or (if you are on XP or higher and know what you do) overwrite the current value with: ``` reg add "HKEY_CLASSES_ROOT\xmlfile\shell\open\command" /ve /d "path\to\program %1" ``` At any rate, a deeper look into `reg add/?` command is advised. The first solution is safer.
212,919
<p>I need to change the permissions of a directory to be owned by the Everyone user with all access rights on this directory. I'm a bit new to the Win32 API, so I'm somewhat lost in the SetSecurity* functions.</p>
[ { "answer_id": 213716, "author": "Jason", "author_id": 26302, "author_profile": "https://Stackoverflow.com/users/26302", "pm_score": 2, "selected": false, "text": "<p>Ok, I figured it out:</p>\n\n<pre><code>SetSecurityInfo(hDir, SE_FILE_OBJECT, DACL_SECURITY_INFORMATION, NULL, NULL, NULL, NULL);\n</code></pre>\n\n<p>This will give all permissions to all users for the given directory handle.</p>\n" }, { "answer_id": 213877, "author": "Jonathan Leffler", "author_id": 15168, "author_profile": "https://Stackoverflow.com/users/15168", "pm_score": 2, "selected": false, "text": "<p>Are you sure this is a good idea? I spend a lot of time removing public access (especially public write access) from files and directories on Unix systems, in part because allowing anyone to remove or add files to a directory is an open invitation to abuse.</p>\n" } ]
2008/10/17
[ "https://Stackoverflow.com/questions/212919", "https://Stackoverflow.com", "https://Stackoverflow.com/users/26302/" ]
I need to change the permissions of a directory to be owned by the Everyone user with all access rights on this directory. I'm a bit new to the Win32 API, so I'm somewhat lost in the SetSecurity\* functions.
Ok, I figured it out: ``` SetSecurityInfo(hDir, SE_FILE_OBJECT, DACL_SECURITY_INFORMATION, NULL, NULL, NULL, NULL); ``` This will give all permissions to all users for the given directory handle.
212,939
<p>MySQL 5.0.45</p> <p>What is the syntax to alter a table to allow a column to be null, alternately what's wrong with this:</p> <pre><code>ALTER mytable MODIFY mycolumn varchar(255) null; </code></pre> <p>I interpreted the manual as just run the above and it would recreate the column, this time allowing null. The server is telling me I have syntactical errors. I just don't see them.</p>
[ { "answer_id": 212947, "author": "Daniel Spiewak", "author_id": 9815, "author_profile": "https://Stackoverflow.com/users/9815", "pm_score": 11, "selected": true, "text": "<p>You want the following:</p>\n\n<pre><code>ALTER TABLE mytable MODIFY mycolumn VARCHAR(255);\n</code></pre>\n\n<p>Columns are nullable by default. As long as the column is not declared <code>UNIQUE</code> or <code>NOT NULL</code>, there shouldn't be any problems.</p>\n" }, { "answer_id": 212966, "author": "ConroyP", "author_id": 2287, "author_profile": "https://Stackoverflow.com/users/2287", "pm_score": 8, "selected": false, "text": "<p>Your syntax error is caused by a missing \"table\" in the query</p>\n\n<pre><code>ALTER TABLE mytable MODIFY mycolumn varchar(255) null;\n</code></pre>\n" }, { "answer_id": 1368689, "author": "Gerald Senarclens de Grancy", "author_id": 104659, "author_profile": "https://Stackoverflow.com/users/104659", "pm_score": 3, "selected": false, "text": "<p>Under some circumstances (if you get \"ERROR 1064 (42000): You have an error in your SQL syntax;...\") you need to do</p>\n\n<pre><code>ALTER TABLE mytable MODIFY mytable.mycolumn varchar(255);\n</code></pre>\n" }, { "answer_id": 8254845, "author": "Krishnrohit", "author_id": 1063633, "author_profile": "https://Stackoverflow.com/users/1063633", "pm_score": 5, "selected": false, "text": "<p>My solution:</p>\n\n<pre><code>ALTER TABLE table_name CHANGE column_name column_name type DEFAULT NULL\n</code></pre>\n\n<p>For example:</p>\n\n<pre><code>ALTER TABLE SCHEDULE CHANGE date date DATETIME DEFAULT NULL;\n</code></pre>\n" }, { "answer_id": 31966476, "author": "Jan Nejedly", "author_id": 2947740, "author_profile": "https://Stackoverflow.com/users/2947740", "pm_score": -1, "selected": false, "text": "<p>Use:\n<code>ALTER TABLE mytable MODIFY mycolumn VARCHAR(255);</code></p>\n" }, { "answer_id": 55777515, "author": "Hmerman6006", "author_id": 10177977, "author_profile": "https://Stackoverflow.com/users/10177977", "pm_score": 3, "selected": false, "text": "<p>My solution is the same as @Krishnrohit:</p>\n\n<pre><code>ALTER TABLE `table` CHANGE `column_current_name` `new_column_name` DATETIME NULL;\n</code></pre>\n\n<p>I actually had the column set as <code>NOT NULL</code> but with the above query it was changed to <code>NULL</code>.</p>\n\n<p>P.S. I know this an old thread but nobody seems to acknowledge that <code>CHANGE</code> is also correct.</p>\n" } ]
2008/10/17
[ "https://Stackoverflow.com/questions/212939", "https://Stackoverflow.com", "https://Stackoverflow.com/users/13285/" ]
MySQL 5.0.45 What is the syntax to alter a table to allow a column to be null, alternately what's wrong with this: ``` ALTER mytable MODIFY mycolumn varchar(255) null; ``` I interpreted the manual as just run the above and it would recreate the column, this time allowing null. The server is telling me I have syntactical errors. I just don't see them.
You want the following: ``` ALTER TABLE mytable MODIFY mycolumn VARCHAR(255); ``` Columns are nullable by default. As long as the column is not declared `UNIQUE` or `NOT NULL`, there shouldn't be any problems.
212,965
<p>What I want to do is the following:</p> <ol> <li>read in multiple line input from <code>stdin</code> into variable <code>A</code></li> <li>make various operations on <code>A</code></li> <li>pipe <code>A</code> without losing delimiter symbols (<code>\n</code>,<code>\r</code>,<code>\t</code>,etc) to another command</li> </ol> <p>The current problem is that, I can't read it in with <code>read</code> command, because it stops reading at newline.</p> <p>I can read stdin with <code>cat</code>, like this:</p> <pre><code>my_var=`cat /dev/stdin` </code></pre> <p>, but then I don't know how to print it. So that the newline, tab, and other delimiters are still there.</p> <p>My sample script looks like this:</p> <pre><code>#!/usr/local/bin/bash A=`cat /dev/stdin` if [ ${#A} -eq 0 ]; then exit 0 else cat ${A} | /usr/local/sbin/nextcommand fi </code></pre>
[ { "answer_id": 212987, "author": "Tanktalus", "author_id": 23512, "author_profile": "https://Stackoverflow.com/users/23512", "pm_score": 7, "selected": true, "text": "<p>This is working for me:</p>\n\n<pre><code>myvar=`cat`\n\necho \"$myvar\"\n</code></pre>\n\n<p>The quotes around <code>$myvar</code> are important.</p>\n" }, { "answer_id": 213007, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 3, "selected": false, "text": "<p>Yes it works for me too. Thanks.</p>\n\n<pre><code>myvar=`cat`\n</code></pre>\n\n<p>is the same as</p>\n\n<pre><code>myvar=`cat /dev/stdin`\n</code></pre>\n\n<p>Well yes. From the <code>bash</code> man page:</p>\n\n<blockquote>\n <p>Enclosing characters in double quotes\n preserves the literal value of all\n characters within the quotes,\n with the exception of $, `, \\, and, when history expansion is\n enabled, !. The characters $ and `\n retain their special meaning within double quotes.</p>\n</blockquote>\n" }, { "answer_id": 15269128, "author": "Ingo Karkat", "author_id": 813602, "author_profile": "https://Stackoverflow.com/users/813602", "pm_score": 5, "selected": false, "text": "<p>In Bash, there's an alternative way; <code>man bash</code> mentions:</p>\n\n<blockquote>\n <p>The command substitution <code>$(cat file)</code> can be replaced by the equivalent but faster <code>$(&lt; file)</code>.</p>\n</blockquote>\n\n<pre><code>$ myVar=$(&lt;/dev/stdin)\nhello\nthis is test\n$ echo \"$myVar\"\nhello\nthis is test\n</code></pre>\n" }, { "answer_id": 22064369, "author": "Sergey Grigoriev", "author_id": 1921113, "author_profile": "https://Stackoverflow.com/users/1921113", "pm_score": 4, "selected": false, "text": "<p><strong>tee</strong> does the job</p>\n\n<pre><code>#!/bin/bash\nmyVar=$(tee)\n</code></pre>\n" }, { "answer_id": 25738463, "author": "Ingo Karkat", "author_id": 813602, "author_profile": "https://Stackoverflow.com/users/813602", "pm_score": 3, "selected": false, "text": "<p>If you do care about preserving trailing newlines at the end of the output, use this:</p>\n\n<pre><code>myVar=$(cat; echo x)\nmyVar=${myVar%x}\nprintf %s \"$myVar\"\n</code></pre>\n\n<p>This uses the trick from <a href=\"http://wiki.bash-hackers.org/syntax/expansion/cmdsubst#examples\" rel=\"noreferrer\">here</a>.</p>\n" }, { "answer_id": 47343371, "author": "DocSalvager", "author_id": 470211, "author_profile": "https://Stackoverflow.com/users/470211", "pm_score": 4, "selected": false, "text": "<h2>[updated]</h2>\n\n<p>This assignment will hang indefinitely if there is nothing in the pipe...</p>\n\n<pre><code>var=\"$(&lt; /dev/stdin)\"\n</code></pre>\n\n<p>We can prevent this though by doing a timeout <code>read</code> for the first character. If it times out, the return code will be greater than 128 and we'll know the STDIN pipe (a.k.a <code>/dev/stdin</code>) is empty.</p>\n\n<p>Otherwise, we get the rest of STDIN by...</p>\n\n<ul>\n<li>setting <code>IFS</code> to NULL for just the <code>read</code> command</li>\n<li>turning off escapes with <code>-r</code></li>\n<li>eliminating read's delimiter with <code>-d ''</code>.</li>\n<li>and finally, appending that to the character we got initially</li>\n</ul>\n\n<p>Thus...</p>\n\n<pre><code>__=\"\"\n_stdin=\"\"\n\nread -N1 -t1 __ &amp;&amp; {\n (( $? &lt;= 128 )) &amp;&amp; {\n IFS= read -rd '' _stdin\n _stdin=\"$__$_stdin\"\n }\n}\n</code></pre>\n\n<p>This technique avoids using <code>var=\"$(command ...)\"</code> Command Substitution which, by design, will always strip off any trailing newlines.</p>\n\n<p>If Command Substitution is preferred, to preserve trailing newlines we can append one or more delimiter characters to the output inside the <code>$()</code> and then strip them off outside.</p>\n\n<p>For example <em>( note <code>$(parens)</code> in first command and <code>${braces}</code> in second )</em>...</p>\n\n<pre><code>_stdin=\"$(awk '{print}; END {print \"|||\"}' /dev/stdin)\"\n_stdin=\"${_stdin%|||}\"\n</code></pre>\n" }, { "answer_id": 69184102, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 2, "selected": false, "text": "<p>Read can also be used setting option -d [DELIMITER], in which `input' DELIMITER is one character long. If you set <code>-read d ''</code> then it reads until null or all input.</p>\n<p>Just remember Bash cannot hold null bytes in variables, anyways.</p>\n<pre class=\"lang-sh prettyprint-override\"><code>read -d'' myvar\necho &quot;$myvar&quot;\n</code></pre>\n<p>Obs: trailing newline bytes are not preserved, though..</p>\n" } ]
2008/10/17
[ "https://Stackoverflow.com/questions/212965", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
What I want to do is the following: 1. read in multiple line input from `stdin` into variable `A` 2. make various operations on `A` 3. pipe `A` without losing delimiter symbols (`\n`,`\r`,`\t`,etc) to another command The current problem is that, I can't read it in with `read` command, because it stops reading at newline. I can read stdin with `cat`, like this: ``` my_var=`cat /dev/stdin` ``` , but then I don't know how to print it. So that the newline, tab, and other delimiters are still there. My sample script looks like this: ``` #!/usr/local/bin/bash A=`cat /dev/stdin` if [ ${#A} -eq 0 ]; then exit 0 else cat ${A} | /usr/local/sbin/nextcommand fi ```
This is working for me: ``` myvar=`cat` echo "$myvar" ``` The quotes around `$myvar` are important.
212,968
<p>I have a scenario in a system which I've tried to simplify as best as I can. We have a table of (lets call them) artefacts, artefacts can be accessed by any number of security roles and security roles can access any number of artefacts. As such, we have 3 tables in the database - one describing artefacts, one describing roles and a many-to-many association table linking artefact ID to Role ID.</p> <p>Domain wise, we have two classes - one for a role and one for an artefact. the artefact class has an IList property that returns a list of roles that can access it. (Roles however do not offer a property to get artefacts that can be accessed).</p> <p>As such, the nhibernate mapping for artefact contains the following;</p> <pre class="lang-xml prettyprint-override"><code>&lt;bag name="AccessRoles" table="ArtefactAccess" order-by="RoleID" lazy="true" access="field.camelcase-underscore" optimistic-lock="false"&gt; &lt;key column="ArtefactID"/&gt; &lt;many-to-many class="Role" column="RoleID"/&gt; &lt;/bag&gt; </code></pre> <p>This all works fine and if I delete an artefact, the association table is cleaned up appropriately and all references between the removed artefact and roles are removed (the role isn't deleted though, correctly - as we don't want orphans deleted).</p> <p>The problem is - how to delete a role and have it clear up the association table automatically. If I presently try to delete a role, I get a reference constraint as there are still entries in the association table for the role. The only way to successfully delete a role is to query for all artefacts that link to that role, remove the role from the artefact's role collection, update the artefacts and then delete the role - not very efficient or nice, especially when in the un-simplified system, roles can be associated with any number of other tables/objects.</p> <p>I need to be able to hint to NHibernate that I want this association table cleared whenever I delete a role - is this possible, and if so - how do I do it?</p> <p>Thanks for any help.</p>
[ { "answer_id": 213065, "author": "Elie", "author_id": 23249, "author_profile": "https://Stackoverflow.com/users/23249", "pm_score": 0, "selected": false, "text": "<p>You could make a mapping for the association table, and then call delete on that table where the Role_id is the value you are about to delete, and then perform the delete of the role itself. Should be fairly straightforward to do this.</p>\n" }, { "answer_id": 213749, "author": "Santiago Palladino", "author_id": 12791, "author_profile": "https://Stackoverflow.com/users/12791", "pm_score": 0, "selected": false, "text": "<p>Although I believe NHibernate must provide a way to do this without having the collection in the roles C# class, you can always set this behaviour in SQL. Select on cascade delete for the FK in the database and it should be automatic, just watch out for NHib's cache.</p>\n\n<p>But I strongly advice you to use this as a last resource.</p>\n" }, { "answer_id": 214138, "author": "kͩeͣmͮpͥ ͩ", "author_id": 26479, "author_profile": "https://Stackoverflow.com/users/26479", "pm_score": 0, "selected": false, "text": "<p>You need to create a mapping from Role to <code>Artifact</code>.</p>\n\n<p>You can make it lazy-loading, and map it to a protected virtual member, so that it never actually gets accessed, but you need that mapping there for NHibernate to know that it has to delete the roles from the <code>ArtefactAccess</code> table</p>\n" }, { "answer_id": 407171, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 4, "selected": true, "text": "<p>Since I was looking for this answer and found this thread on google (without an answer) I figured I'd post my solution to this. With three tables: Role, RolesToAccess(ManyToMany), Access.</p>\n\n<p>Create the following mappings:\nAccess:</p>\n\n<pre><code>&lt;bag name=\"Roles\" table=\"RolesToAccess\" cascade=\"none\" lazy=\"false\"&gt;\n &lt;key column=\"AccessId\" /&gt;\n &lt;many-to-many column=\"AccessId\" class=\"Domain.Compound,Domain\" /&gt;\n &lt;/bag&gt;\n\n&lt;bag name=\"RolesToAccess\" cascade=\"save-update\" inverse=\"true\" lazy=\"false\"&gt;\n &lt;key column=\"AccessId\" on-delete=\"cascade\" /&gt;\n &lt;one-to-many class=\"Domain.RolesToAccess,Domain\" /&gt;\n &lt;/bag&gt;\n</code></pre>\n\n<p>Roles:</p>\n\n<pre><code>&lt;bag name=\"Accesses\" table=\"RolesToAccess\" cascade=\"none\" lazy=\"false\"&gt;\n &lt;key column=\"RoleId\" /&gt;\n &lt;many-to-many column=\"RoleId\" class=\"Domain.Compound,Domain\" /&gt;\n &lt;/bag&gt;\n\n&lt;bag name=\"RolesToAccess\" cascade=\"save-update\" inverse=\"true\" lazy=\"false\"&gt;\n &lt;key column=\"RoleId\" on-delete=\"cascade\" /&gt;\n &lt;one-to-many class=\"Domain.RolesToAccess,Domain\" /&gt;\n &lt;/bag&gt;\n</code></pre>\n\n<p>As mentioned above you can make the RolesToAccess properties protected so they don't pollute your model.</p>\n" }, { "answer_id": 4421934, "author": "pvolders", "author_id": 480421, "author_profile": "https://Stackoverflow.com/users/480421", "pm_score": 1, "selected": false, "text": "<p>What you say here:</p>\n\n<blockquote>\n <p>The only way to successfully delete a role is to query for all artefacts that link to that role, remove the role from the artefact's role collection, update the artefacts and then delete the role - not very efficient or nice, especially when in the un-simplified system, roles can be associated with any number of other tables/objects.</p>\n</blockquote>\n\n<p>Is not necessary. Suppose you don't want to map the association table (make it a domain object), you can still perform deletes on both ends with minimal code.</p>\n\n<p>Let's say there are 3 tables: Role, Artifact, and ArtifactAccess (the link table).\nIn your mapping, you only have domain objects for Role and Artifact. Both have a bag for the many-many association. </p>\n\n<p>Role:</p>\n\n<pre><code> &lt;bag name=\"Artifacts\" table=\"[ArtifactAccess]\" schema=\"[Dbo]\" lazy=\"true\"\n inverse=\"false\" cascade=\"none\" generic=\"true\"&gt;\n &lt;key column=\"[ArtifactID]\"/&gt;\n\n &lt;many-to-many column=\"[RoleID]\" class=\"Role\" /&gt;\n &lt;/bag&gt;\n</code></pre>\n\n<p>Artifact:</p>\n\n<pre><code> &lt;bag name=\"Roles\" table=\"[ArtifactAccess]\" schema=\"[Dbo]\" lazy=\"true\"\n inverse=\"false\" cascade=\"none\" generic=\"true\"&gt;\n &lt;key column=\"[RoleID]\"/&gt;\n\n &lt;many-to-many column=\"[ArtifactID]\" class=\"Role\" /&gt;\n &lt;/bag&gt;\n</code></pre>\n\n<p>As you can see, both ends have inverse=false specified. The NHibernate documentation recommends you to choose one end of your association as the 'inverse' end, but nothing stops you from using both as 'controlling end'. When performing updates or inserts, this works from both directions without a hitch. When performing deletes of either one of the ends, you get a FK violation error because the association table is not updated, true. But you can solve this by just clearing the collection to the other end, before performing the delete, which is a lot less complex than what you do, which is looking in the 'other' end of the association if there are uses of 'this' end. If this is a bit confusing, here is a code example. If you only have one end in control, for your complex delete you need to do:</p>\n\n<pre><code>foreach(var artifact in role.Artifacts)\n foreach(var role in artifact.Roles)\n if(role == roleToDelete)\n artifact.Roles.Remove(role)\n artifact.Save();\nroleToDelete.Delete();\n</code></pre>\n\n<p>What I do when deleting a role is something like</p>\n\n<pre><code>roleToDelete.Artifacts.Clear(); //removes the association record\nroleToDelete.Delete(); // removes the artifact record\n</code></pre>\n\n<p>It's one extra line of code, but this way you don't need to make a decision on which end of the association is the inverse end. You also don't need to map the association table for full control.</p>\n" } ]
2008/10/17
[ "https://Stackoverflow.com/questions/212968", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20524/" ]
I have a scenario in a system which I've tried to simplify as best as I can. We have a table of (lets call them) artefacts, artefacts can be accessed by any number of security roles and security roles can access any number of artefacts. As such, we have 3 tables in the database - one describing artefacts, one describing roles and a many-to-many association table linking artefact ID to Role ID. Domain wise, we have two classes - one for a role and one for an artefact. the artefact class has an IList property that returns a list of roles that can access it. (Roles however do not offer a property to get artefacts that can be accessed). As such, the nhibernate mapping for artefact contains the following; ```xml <bag name="AccessRoles" table="ArtefactAccess" order-by="RoleID" lazy="true" access="field.camelcase-underscore" optimistic-lock="false"> <key column="ArtefactID"/> <many-to-many class="Role" column="RoleID"/> </bag> ``` This all works fine and if I delete an artefact, the association table is cleaned up appropriately and all references between the removed artefact and roles are removed (the role isn't deleted though, correctly - as we don't want orphans deleted). The problem is - how to delete a role and have it clear up the association table automatically. If I presently try to delete a role, I get a reference constraint as there are still entries in the association table for the role. The only way to successfully delete a role is to query for all artefacts that link to that role, remove the role from the artefact's role collection, update the artefacts and then delete the role - not very efficient or nice, especially when in the un-simplified system, roles can be associated with any number of other tables/objects. I need to be able to hint to NHibernate that I want this association table cleared whenever I delete a role - is this possible, and if so - how do I do it? Thanks for any help.
Since I was looking for this answer and found this thread on google (without an answer) I figured I'd post my solution to this. With three tables: Role, RolesToAccess(ManyToMany), Access. Create the following mappings: Access: ``` <bag name="Roles" table="RolesToAccess" cascade="none" lazy="false"> <key column="AccessId" /> <many-to-many column="AccessId" class="Domain.Compound,Domain" /> </bag> <bag name="RolesToAccess" cascade="save-update" inverse="true" lazy="false"> <key column="AccessId" on-delete="cascade" /> <one-to-many class="Domain.RolesToAccess,Domain" /> </bag> ``` Roles: ``` <bag name="Accesses" table="RolesToAccess" cascade="none" lazy="false"> <key column="RoleId" /> <many-to-many column="RoleId" class="Domain.Compound,Domain" /> </bag> <bag name="RolesToAccess" cascade="save-update" inverse="true" lazy="false"> <key column="RoleId" on-delete="cascade" /> <one-to-many class="Domain.RolesToAccess,Domain" /> </bag> ``` As mentioned above you can make the RolesToAccess properties protected so they don't pollute your model.
212,988
<p>I have created an item swapper control consisting in two listboxes and some buttons that allow me to swap items between the two lists. The swapping is done using javascript. I also move items up and down in the list. Basically when I move the items to the list box on the right I store the datakeys of the elements (GUIDs) in a hiddenfield. On postback I simply read the GUIDs from the field. Everything works great but on postback, I get the following exception:</p> <blockquote> <p>Invalid postback or callback argument. Event validation is enabled using in configuration or &lt;%@ Page EnableEventValidation="true" %> in a page. For security purposes, this feature verifies that arguments to postback or callback events originate from the server control that originally rendered them. If the data is valid and expected, use the ClientScriptManager.RegisterForEventValidation method in order to register the postback or callback data for validation. </p> </blockquote> <p>I've prepared a test application. All you have to do is download the archive and run the project. On the web page select the 3 items, press Add all, then move the third element up one level and then hit "Button". The error will show up. Turning event validation off is by no means acceptable. Can anyone help me, I've spent two already days without finding a solution.</p> <p><a href="http://cid-c9672af9b84b07ef.skydrive.live.com/self.aspx/TestApp/TestProject.zip" rel="noreferrer">TEST APPLICATION</a></p>
[ { "answer_id": 213169, "author": "tvanfosson", "author_id": 12950, "author_profile": "https://Stackoverflow.com/users/12950", "pm_score": 0, "selected": false, "text": "<p>It's complaining because the selected item in a list was not present in the list when it was rendered. Consider using PageMethods via AJAX to get your data back to your form instead of PostBack. Or use a non-input controls to hold the data -- like unordered lists that you move list elements back and forth between. You can put the GUIDs in hidden spans inside the list element where you can get at them if need be.</p>\n" }, { "answer_id": 213466, "author": "Aleris", "author_id": 20417, "author_profile": "https://Stackoverflow.com/users/20417", "pm_score": 2, "selected": false, "text": "<p>The problem is that the saved view state of the list and the data received on postback do not match. The event validation issue is most likely just one of the possible problems that might appear because of this approach. The architecture of webforms does not allow this kind of uses and, most likely, there will be more problems with this approach, even if you succeed to avoid the event validation issue. You have several alternatives:</p>\n\n<p>1) The simplest is to do the swapping logic on server instead of using javascript. This way the view state will be preserved between postbacks and the added overhead of multiple round trips to the server might not be an issue.</p>\n\n<p>2) If the multiple round trips to server is an issue, write a server control that handles it's own view state. This is of course a much engaging approach.</p>\n\n<p>3) A middle ground approach could be to use two simple html lists (just write the html tags without using the asp.net controls) and maintain on the client side from javascript a list of id's in a hidden field. On post back just parse the hidden field and extract the id's ignoring the html lists.</p>\n\n<p>I would go with 1 if there aren't SERIOUS arguments against it.</p>\n" }, { "answer_id": 213535, "author": "kjv", "author_id": 1360, "author_profile": "https://Stackoverflow.com/users/1360", "pm_score": 1, "selected": true, "text": "<p>The first option will bring considerable overhead. I have defined my own custom listbox control derived from the listbox class and performed an override of the loadpostback data:</p>\n\n<pre><code>public class CustomListBox : ListBox\n{\n protected override bool LoadPostData(string postDataKey, System.Collections.Specialized.NameValueCollection postCollection)\n {\n return true;\n }\n}\n</code></pre>\n\n<p>Using this instead of the regular listbox in my user control solved the problem, however are there any risks associated with my approach?</p>\n" }, { "answer_id": 214593, "author": "Samuel Kim", "author_id": 437435, "author_profile": "https://Stackoverflow.com/users/437435", "pm_score": 1, "selected": false, "text": "<p>A few possible options:</p>\n\n<ul>\n<li><p>If possible, disable ViewState on the two lists. Without ViewState, the server won't know what the original values were and hence will not error. With this approach, you will need to repopulate the lists (due to lack of ViewState) and may need to track the selection manually - or will need to populate the lists during OnInit phase.</p></li>\n<li><p>Turn off event validation (if you can)</p></li>\n<li><p>Populate both lists fully on the server side and use client side script (javascript) to remove entries from the two lists as required.</p></li>\n</ul>\n" }, { "answer_id": 215583, "author": "Rob", "author_id": 2595, "author_profile": "https://Stackoverflow.com/users/2595", "pm_score": 0, "selected": false, "text": "<p>By chance, did you try this already? Do this whenever you muck with the list in any way.</p>\n\n<pre><code>document.getElementById(\"listbox\").selectedIndex = -1;\n</code></pre>\n" }, { "answer_id": 8222376, "author": "Tom", "author_id": 882436, "author_profile": "https://Stackoverflow.com/users/882436", "pm_score": 0, "selected": false, "text": "<p>Alternatively, you can use a server-side HtmlSelect in place of a ListBox to work around the event validation issue. Best of all, you may be able to leave much of your code-behind intact (ie. list population logic is the same as ListBox).</p>\n\n<pre><code>&lt;select runat=\"server\" id=\"myList\" multiple=\"true\" /&gt;\n</code></pre>\n" }, { "answer_id": 33810783, "author": "Gerbus", "author_id": 303659, "author_profile": "https://Stackoverflow.com/users/303659", "pm_score": 0, "selected": false, "text": "<p>You could override the Render event to register all possible listbox items with both listboxes. That way no matter what items are moved where, the validation is expecting them.</p>\n\n<pre><code>protected override void Render(HtmlTextWriter writer)\n{\n foreach (DictionaryEntry entry in ColumnConfig) { \n Page.ClientScript.RegisterForEventValidation(lstbxColumnsToExport.UniqueID,(string)entry.Key);\n Page.ClientScript.RegisterForEventValidation(lstbxNonExportColumns.UniqueID,(string)entry.Key);\n }\n base.Render(writer);\n}\n</code></pre>\n" } ]
2008/10/17
[ "https://Stackoverflow.com/questions/212988", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1360/" ]
I have created an item swapper control consisting in two listboxes and some buttons that allow me to swap items between the two lists. The swapping is done using javascript. I also move items up and down in the list. Basically when I move the items to the list box on the right I store the datakeys of the elements (GUIDs) in a hiddenfield. On postback I simply read the GUIDs from the field. Everything works great but on postback, I get the following exception: > > Invalid postback or callback argument. Event validation is enabled using in configuration or <%@ Page EnableEventValidation="true" %> in a page. For security purposes, this feature verifies that arguments to postback or callback events originate from the server control that originally rendered them. If the data is valid and expected, use the ClientScriptManager.RegisterForEventValidation method in order to register the postback or callback data for validation. > > > I've prepared a test application. All you have to do is download the archive and run the project. On the web page select the 3 items, press Add all, then move the third element up one level and then hit "Button". The error will show up. Turning event validation off is by no means acceptable. Can anyone help me, I've spent two already days without finding a solution. [TEST APPLICATION](http://cid-c9672af9b84b07ef.skydrive.live.com/self.aspx/TestApp/TestProject.zip)
The first option will bring considerable overhead. I have defined my own custom listbox control derived from the listbox class and performed an override of the loadpostback data: ``` public class CustomListBox : ListBox { protected override bool LoadPostData(string postDataKey, System.Collections.Specialized.NameValueCollection postCollection) { return true; } } ``` Using this instead of the regular listbox in my user control solved the problem, however are there any risks associated with my approach?
212,999
<p>After using Hudson for continuous integration with a prior project, I want to set up a continuous integration server for the iPhone projects I'm working on now. After doing some research it looks like there aren't any CI engines designed specifically for Xcode, but one guy has had success <a href="http://www.pragmaticautomation.com/cgi-bin/pragauto.cgi/Build/XcodeOnCC.rdoc" rel="noreferrer">using Cruise Control combined with the xcodebuild CLI tool</a>. Has anyone here tried this? Are there any CI engines that work well with Xcode projects?</p> <p>I'm probably going to give Cruise Control a try. I'll post an answer with my findings.</p>
[ { "answer_id": 213101, "author": "Colin Barrett", "author_id": 23106, "author_profile": "https://Stackoverflow.com/users/23106", "pm_score": 3, "selected": false, "text": "<p>Adium is using <a href=\"http://buildbot.net\" rel=\"nofollow noreferrer\">buildbot</a> with Xcode quite effectively. We wrote a simple makefile that calls xcodebuild with the proper targets and configurations, but I'm pretty sure that's optional.</p>\n" }, { "answer_id": 215104, "author": "catlan", "author_id": 23028, "author_profile": "https://Stackoverflow.com/users/23028", "pm_score": 2, "selected": false, "text": "<p>I think you should be still able to use Hudson. Hudson is very flexible and allows you also to use shell scripts for building: <a href=\"http://hudson.gotdns.com/wiki/display/HUDSON/Building+a+software+project#Buildingasoftwareproject-ShellScriptsandWindowsBatchCommands\" rel=\"nofollow noreferrer\">Shell Scripts and Windows Batch Commands</a></p>\n\n<p>Just enter there xcodebuild. Take a look at the xcodebuild man page to see the options of xcodebuild.</p>\n" }, { "answer_id": 219458, "author": "heckj", "author_id": 19477, "author_profile": "https://Stackoverflow.com/users/19477", "pm_score": 3, "selected": false, "text": "<p>I've used CruiseControl with Xcode (similiar to what Pragmatic Automation suggested) and had reasonable success. I'm also very familiar with CruiseControl and it's relatively horrific configuration format setup.</p>\n\n<p>I've also used BuildBot to good effect, but found that it's strengths didn't really match my needs (distributed slaves building and reporting across multiple different systems). Configurating buildbot setups can be an art in and of itself, although it's not difficult. It's all essentially writing scripts in python.</p>\n\n<p>Since Hudson has become available, I'd recommend it as an avenue for running continuous integration. It has a web based interface (CruiseControl's primary deficiency in my mind) and is very flexible in the various systems that it supports. You can invoke command line driven builds quite easily and very obviously. That said, I haven't set up an instance using Hudson and Xcode, where I have for the other systems, so this is partially speculation on my part.</p>\n" }, { "answer_id": 323523, "author": "Jeffrey Fredrick", "author_id": 35894, "author_profile": "https://Stackoverflow.com/users/35894", "pm_score": 2, "selected": false, "text": "<p>If you don't mind living on the cutting edge I've just committed an <a href=\"http://blog.jeffreyfredrick.com/2008/11/27/continuous-integration-for-iphonexcode-projects/\" rel=\"nofollow noreferrer\">xcode builder</a> for CruiseControl.</p>\n" }, { "answer_id": 1182726, "author": "Silentcode", "author_id": 145054, "author_profile": "https://Stackoverflow.com/users/145054", "pm_score": 6, "selected": true, "text": "<p>I'm successfully using Hudson on the mac with xcodebuild. With the release of the 3.0 iPhone sdk you have compete control over the target, configuration and sdk that the project is to be built against. </p>\n\n<p>It's as simple as creating a build step in hudson and telling xcodebuild to build the project:</p>\n\n<pre><code>xcodebuild -target \"myAppAppStore\" -configuration \"DistributionAppStore\" -sdk iphoneos2.1\n</code></pre>\n\n<p>The upfront work has paid off for me as my builds just work without any additional thought. I've written a detailed description on my blog if anyone is interested.</p>\n\n<p><a href=\"http://silent-code.blogspot.com/2009/07/iphone-app-distribution-made-easy-part.html\" rel=\"nofollow noreferrer\">iPhone app distribution made easy</a></p>\n" }, { "answer_id": 2172791, "author": "Ciryon", "author_id": 22012, "author_profile": "https://Stackoverflow.com/users/22012", "pm_score": 4, "selected": false, "text": "<p>Resurrecting this thread. I didn't find a satisfactory solution to getting automated XCode builds with unit tests on a build server so I did some investigating and coding. The result is <a href=\"http://blog.jayway.com/2010/01/31/continuos-integration-for-xcode-projects/\" rel=\"nofollow noreferrer\">this blog post</a> explaining it all and <a href=\"http://github.com/ciryon/OCUnit2JUnit\" rel=\"nofollow noreferrer\">this Ruby script</a> that converts OCUnit output from xcodebuild to the XML format that JUnit uses for test reports. The build server I picked was <a href=\"http://hudson-ci.org/\" rel=\"nofollow noreferrer\">Hudson</a>.</p>\n\n<p>Update 3/2 2012: I have updated this to use some custom shell scripts for building and running. Available <a href=\"https://github.com/ciryon/xcodebuild-script\" rel=\"nofollow noreferrer\">here</a>. It's good not only for continuous integration, but also building from command line on your own machine.</p>\n" }, { "answer_id": 10936465, "author": "bentford", "author_id": 946, "author_profile": "https://Stackoverflow.com/users/946", "pm_score": 1, "selected": false, "text": "<p>Jenkins seems to work well for some people. (Although, I have never used any CI server before. )</p>\n\n<p><a href=\"https://wiki.jenkins-ci.org/display/JENKINS/Xcode+Plugin\" rel=\"nofollow\">https://wiki.jenkins-ci.org/display/JENKINS/Xcode+Plugin</a></p>\n" }, { "answer_id": 12047528, "author": "Tinolover", "author_id": 1605887, "author_profile": "https://Stackoverflow.com/users/1605887", "pm_score": 0, "selected": false, "text": "<p>Jenkins works fine.\nYou can Either build your xcode project by writing your own shell script then let Jenkins run it, or you can also use xcode plugin.</p>\n\n<p>But you have to be aware of the authority problem. With little tweaks in Jenkins configurations, you'll be able to manage your CI server in very little time.</p>\n" }, { "answer_id": 17097018, "author": "Rafael Gorski", "author_id": 1016362, "author_profile": "https://Stackoverflow.com/users/1016362", "pm_score": 3, "selected": false, "text": "<p>Apple just release (June 10th, 2013) for OSX Mavericks(OS X 10.9) a new continuous integration platform which is the most integrated continuous integration solution that I have seen before.\nIt is available from developer.apple.com, here in this page has the details:</p>\n\n<p><a href=\"https://developer.apple.com/library/ios/documentation/IDEs/Conceptual/xcode_guide-continuous_integration/\" rel=\"nofollow\">https://developer.apple.com/library/ios/documentation/IDEs/Conceptual/xcode_guide-continuous_integration/</a></p>\n\n<p>I recommend to see the wwdc 2013 presentation on the topic.</p>\n" } ]
2008/10/17
[ "https://Stackoverflow.com/questions/212999", "https://Stackoverflow.com", "https://Stackoverflow.com/users/17188/" ]
After using Hudson for continuous integration with a prior project, I want to set up a continuous integration server for the iPhone projects I'm working on now. After doing some research it looks like there aren't any CI engines designed specifically for Xcode, but one guy has had success [using Cruise Control combined with the xcodebuild CLI tool](http://www.pragmaticautomation.com/cgi-bin/pragauto.cgi/Build/XcodeOnCC.rdoc). Has anyone here tried this? Are there any CI engines that work well with Xcode projects? I'm probably going to give Cruise Control a try. I'll post an answer with my findings.
I'm successfully using Hudson on the mac with xcodebuild. With the release of the 3.0 iPhone sdk you have compete control over the target, configuration and sdk that the project is to be built against. It's as simple as creating a build step in hudson and telling xcodebuild to build the project: ``` xcodebuild -target "myAppAppStore" -configuration "DistributionAppStore" -sdk iphoneos2.1 ``` The upfront work has paid off for me as my builds just work without any additional thought. I've written a detailed description on my blog if anyone is interested. [iPhone app distribution made easy](http://silent-code.blogspot.com/2009/07/iphone-app-distribution-made-easy-part.html)
213,002
<p>I have some data grouped in a table by a certain criteria, and for each group it is computed an average —well, the real case is a bit more tricky— of the values from each of the detail rows that belong to that group. This average is shown in each group footer rows. Let's see this simple example:</p> <p><img src="https://farm4.static.flickr.com/3008/2958165686_088405e1ef_o.jpg" alt="Report table"></p> <p>What I want now is to show a grand total on the <strong>table footer</strong>. The grand total should be computed by <em>adding</em> each group's average (for instance, in this example the grand total should be 20 + 15 = 35). However, I can't nest aggregate functions. How can I do?</p>
[ { "answer_id": 217355, "author": "Pulsehead", "author_id": 2156, "author_profile": "https://Stackoverflow.com/users/2156", "pm_score": 1, "selected": false, "text": "<p>Unfortunately I'm away from my reporting development box at the moment but it's either:<br>\n=(sum(Fields!Column1 + sum(Fields!Column2))<br>\nOR <br>\n=SUM(sum(Fields!Column1) + sum(Fields!Column2))</p>\n\n<p>I'm pretty sure it's the first of the 2.</p>\n" }, { "answer_id": 305734, "author": "Potbelly Programmer", "author_id": 38623, "author_profile": "https://Stackoverflow.com/users/38623", "pm_score": 2, "selected": false, "text": "<p>You just need to add the SUM() function in the table footer which is the outer scope of both groups and will sum them all together. If you are summing on a condition, you may need to put that in there also.</p>\n" }, { "answer_id": 305766, "author": "user33675", "author_id": 33675, "author_profile": "https://Stackoverflow.com/users/33675", "pm_score": 3, "selected": true, "text": "<p>Reporting Services (2005, maybe 2008, too) don't support aggregates of aggregates directly.</p>\n\n<p>Use a custom report assembly, code references and named objects (Report Properties, References) that allow you to aggregate the values yourself.</p>\n\n<p>Your code could look like this:</p>\n\n<pre><code>Public Sub New()\n\n m_valueTable = New DataTable(tableName:=\"DoubleValueList\")\n\n 'Type reference to System.Double\n Dim doubleType = Type.GetType(typeName:=\"System.Double\")\n\n ' Add a single Double column to hold values\n m_valueTable.Columns.Add(columnName:=\"Value\", type:=doubleType)\n\n ' Add aggregation column\n m_sumColumn = m_valueTable.Columns.Add(columnName:=\"Sum\", type:=doubleType, expression:=\"Sum(Value)\")\nEnd Sub\nPublic Function Aggregate(ByVal value As Double) As Double\n\n ' Appends a row using a 1-element object array. \n ' If there will be more than 1 column, more values need to be supplied respectively.\n m_valueTable.Rows.Add(value)\n\n Aggregate = value\nEnd Function\nPublic ReadOnly Property Sum() As Double\n Get\n\n If 0 = m_valueTable.Rows.Count Then\n Sum = 0\n Else\n Sum = CDbl(m_valueTable.Rows(0)(m_sumColumn))\n End If\n End Get\nEnd Property\n</code></pre>\n\n<p>Name you reference for example DoubleAggregator. Then replace the group expressions with \"Code.DoubleAggregator.Aggregate(Avg(Fields!Column2.Value))\" and the expression for Total with \"Code.DoubleAggregator.Sum()\".</p>\n" }, { "answer_id": 6243255, "author": "Martina White", "author_id": 784768, "author_profile": "https://Stackoverflow.com/users/784768", "pm_score": 1, "selected": false, "text": "<p>You can't really, but you can trick it. I blooged a solution to this here:\n<a href=\"http://dataqueen.unlimitedviz.com/2011/05/ssrs-aggregate-last-ytd-or-last-child-value-in-an-ssas-query/\" rel=\"nofollow\">http://dataqueen.unlimitedviz.com/2011/05/ssrs-aggregate-last-ytd-or-last-child-value-in-an-ssas-query/</a></p>\n" }, { "answer_id": 18295862, "author": "Soma Sarkar", "author_id": 1887212, "author_profile": "https://Stackoverflow.com/users/1887212", "pm_score": 1, "selected": false, "text": "<p>you can simply do as following:\nSum(CInt(Fields!TestValue.Value))\n or Sum(CInt(Fields!DollarAmountOfCheck.Value),\"DataSet1\") \nsometime when data is coming through WCF, it does not accept Sum() function. but this works fine in that case.</p>\n" } ]
2008/10/17
[ "https://Stackoverflow.com/questions/213002", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1679/" ]
I have some data grouped in a table by a certain criteria, and for each group it is computed an average —well, the real case is a bit more tricky— of the values from each of the detail rows that belong to that group. This average is shown in each group footer rows. Let's see this simple example: ![Report table](https://farm4.static.flickr.com/3008/2958165686_088405e1ef_o.jpg) What I want now is to show a grand total on the **table footer**. The grand total should be computed by *adding* each group's average (for instance, in this example the grand total should be 20 + 15 = 35). However, I can't nest aggregate functions. How can I do?
Reporting Services (2005, maybe 2008, too) don't support aggregates of aggregates directly. Use a custom report assembly, code references and named objects (Report Properties, References) that allow you to aggregate the values yourself. Your code could look like this: ``` Public Sub New() m_valueTable = New DataTable(tableName:="DoubleValueList") 'Type reference to System.Double Dim doubleType = Type.GetType(typeName:="System.Double") ' Add a single Double column to hold values m_valueTable.Columns.Add(columnName:="Value", type:=doubleType) ' Add aggregation column m_sumColumn = m_valueTable.Columns.Add(columnName:="Sum", type:=doubleType, expression:="Sum(Value)") End Sub Public Function Aggregate(ByVal value As Double) As Double ' Appends a row using a 1-element object array. ' If there will be more than 1 column, more values need to be supplied respectively. m_valueTable.Rows.Add(value) Aggregate = value End Function Public ReadOnly Property Sum() As Double Get If 0 = m_valueTable.Rows.Count Then Sum = 0 Else Sum = CDbl(m_valueTable.Rows(0)(m_sumColumn)) End If End Get End Property ``` Name you reference for example DoubleAggregator. Then replace the group expressions with "Code.DoubleAggregator.Aggregate(Avg(Fields!Column2.Value))" and the expression for Total with "Code.DoubleAggregator.Sum()".
213,015
<p>I have over a TB of home movies with horrible file names. Finding what you want is impossible. I would like to rename all files to the time they were originally recorded (not the file time they were placed on my computer). Some applications (like Ulead Video Studio) can access this information, which I believe is embedded in the CODEC.</p> <p>I would LOVE to find how how either I can write a .Net app to extract this information to rename my files so I can easily organize them OR find an application that will do this for me. Thank you very much in advanced.</p> <p>additional information:: home movies were captured on miniDV and DVD camcorders.</p>
[ { "answer_id": 213050, "author": "Mayowa", "author_id": 18593, "author_profile": "https://Stackoverflow.com/users/18593", "pm_score": 1, "selected": false, "text": "<p>Here is a bit of code that i found a while back that should get you started.</p>\n\n<p><a href=\"http://www.developerfusion.com/code/3435/a-convenient-wrapper-class-to-get-file-info/\" rel=\"nofollow noreferrer\">http://www.developerfusion.com/code/3435/a-convenient-wrapper-class-to-get-file-info/</a></p>\n" }, { "answer_id": 214303, "author": "Mr Fooz", "author_id": 25050, "author_profile": "https://Stackoverflow.com/users/25050", "pm_score": 1, "selected": false, "text": "<p>There's a good chance you're out of luck unless the original capture used absolute timestamps. In my experience, most capture applications use time 0 for the first frame, not a universal time. To check this out, get <a href=\"http://blog.monogram.sk/janos/tools/monogram-graphstudio/\" rel=\"nofollow noreferrer\">GraphStudio</a>, load the file in it, then look at the start time in the properties for the first output pin.</p>\n\n<p>You might look at using <a href=\"http://www.headbands.com/gspot/\" rel=\"nofollow noreferrer\">GSpot</a> to see if the metadata you're looking for is even present in the files. For your AVI files, you might also look into <a href=\"http://virtualdub.org\" rel=\"nofollow noreferrer\">VirtualDub</a>'s RIFF features in its hex editor. Unless your capture application was nice to you, that data was probably never recorded.</p>\n\n<p>Assuming that the original timestamps are available somehow, I'd suggest looking at the source of whichever application helped you find it.</p>\n\n<p>For my videos, I've taken to grabbing the metadata at capture time, storing it in an XML file and having my transcoding / post-processing apps keep the last modified timestamp fixed as the original timestamps. </p>\n" }, { "answer_id": 6050589, "author": "PhilT", "author_id": 759912, "author_profile": "https://Stackoverflow.com/users/759912", "pm_score": 3, "selected": false, "text": "<p>Here is a hacky howto based on mplayer that works at least for the MOV files produced by my camera:</p>\n\n<pre><code>mplayer -vo null -ao null -frames 0 -identify myfile.MOV 2&gt;/dev/null|grep creation_time:\n</code></pre>\n\n<p>I use it to batch-rename them:</p>\n\n<pre><code>for m in MVI*.MOV; do\n t=$(mplayer -vo null -ao null -frames 0 -identify $m 2&gt;/dev/null|grep creation_time:|sed 's/.*creation_time: *//;s/[-:]//g;s/ /-/')\n mv ${m} ${t}_${m}\ndone\n</code></pre>\n" }, { "answer_id": 16814606, "author": "Robert Siemer", "author_id": 825924, "author_profile": "https://Stackoverflow.com/users/825924", "pm_score": 1, "selected": false, "text": "<p>I can’t talk about DVD, but the <a href=\"http://en.wikipedia.org/wiki/DV\" rel=\"nofollow\">Digital Video (DV)</a> codec does indeed store time and date (as set in the camera) on each single frame!</p>\n\n<p>For Linux, programs like <code>dvgrab</code> handle those timestamps, for Windows I believe a tool named dvdate.exe does.</p>\n\n<p>DV video can be stored in AVI containers (.avi), raw (.dv or .dif) and QuickTime (.mov). But not all AVIs are DV. 60min of DV video is about 13GB. – If your files are smaller, they are probably already converted to other codecs and the timestamps are lost.</p>\n" }, { "answer_id": 36683933, "author": "FredG", "author_id": 1532175, "author_profile": "https://Stackoverflow.com/users/1532175", "pm_score": 1, "selected": false, "text": "<p>You should have a look at exiftool. It's an non-GUI utility that allow you to access such information in many media files metadata</p>\n\n<p><a href=\"http://www.sno.phy.queensu.ca/~phil/exiftool/#supported\" rel=\"nofollow\">http://www.sno.phy.queensu.ca/~phil/exiftool/#supported</a></p>\n\n<p>You can probably extract exiftool output to make a nice GUI to rename in any language you want. I have my own python script for that.</p>\n" } ]
2008/10/17
[ "https://Stackoverflow.com/questions/213015", "https://Stackoverflow.com", "https://Stackoverflow.com/users/29027/" ]
I have over a TB of home movies with horrible file names. Finding what you want is impossible. I would like to rename all files to the time they were originally recorded (not the file time they were placed on my computer). Some applications (like Ulead Video Studio) can access this information, which I believe is embedded in the CODEC. I would LOVE to find how how either I can write a .Net app to extract this information to rename my files so I can easily organize them OR find an application that will do this for me. Thank you very much in advanced. additional information:: home movies were captured on miniDV and DVD camcorders.
Here is a hacky howto based on mplayer that works at least for the MOV files produced by my camera: ``` mplayer -vo null -ao null -frames 0 -identify myfile.MOV 2>/dev/null|grep creation_time: ``` I use it to batch-rename them: ``` for m in MVI*.MOV; do t=$(mplayer -vo null -ao null -frames 0 -identify $m 2>/dev/null|grep creation_time:|sed 's/.*creation_time: *//;s/[-:]//g;s/ /-/') mv ${m} ${t}_${m} done ```
213,027
<p>The following code was produced by a consultant working for my group. I'm not a C++ developer (worked in many languages, though) but would like some independent opinions on the following code. This is in Visual Studio C++ 6.0. I've got a gut reaction (not a good one, obviously), but I'd like some "gut reactions" from seasoned (or even not so unseasoned) C++ developers out there. Thanks in advance!</p> <pre><code>// Example call strColHeader = insert_escape(strColHeader, ',', '\\'); //Get rid of the commas and make it an escape character </code></pre> <p>...snip...</p> <pre><code>CString insert_escape ( CString originalString, char charFind, char charInsert ) { bool continueLoop = true; int currentInd = 0; do { int occurenceInd = originalString.Find(charFind, currentInd); if(occurenceInd&gt;0) { originalString.Insert(occurenceInd, charInsert); currentInd = occurenceInd + 2; } else { continueLoop = false; } } while(continueLoop); return(originalString); } </code></pre>
[ { "answer_id": 213040, "author": "Nick", "author_id": 26240, "author_profile": "https://Stackoverflow.com/users/26240", "pm_score": 2, "selected": false, "text": "<p>CString has a Replace() method... (that was my 1st reaction)</p>\n\n<p>I have seen a lot of bad code, and lots worse than this. However, not using built-in functionality when there's no apparent good reason not to is... poor.</p>\n" }, { "answer_id": 213041, "author": "gbjbaanb", "author_id": 13744, "author_profile": "https://Stackoverflow.com/users/13744", "pm_score": 4, "selected": false, "text": "<p>hmm. I think </p>\n\n<pre><code>CString strColHeader;\nstrColHeader.Replace(\",\", \"\\\\,\") \n</code></pre>\n\n<p>would do just as well.</p>\n\n<p>I don't like the code, I tend to break from the while loop instead of having an unnecessary bool 'continue' flag. That goes double when he could have used <code>while (occurenceInd != 0)</code> as his loop control variable instead of the boolean.</p>\n\n<p>Incrementing the counter also relies on \"+2\" which doesn't seem immediately understandable (not at a quick glance), and lastly (and most importantly) he doesn't seem to do comments.</p>\n" }, { "answer_id": 213094, "author": "Paul Nathan", "author_id": 26227, "author_profile": "https://Stackoverflow.com/users/26227", "pm_score": 0, "selected": false, "text": "<p>Looks alright, if a bit, I dunno, hack. Better to use the library, but I wouldn't go and rewrite this routine.</p>\n" }, { "answer_id": 213244, "author": "Konrad Rudolph", "author_id": 1968, "author_profile": "https://Stackoverflow.com/users/1968", "pm_score": 0, "selected": false, "text": "<blockquote>\n <p>This is in Visual Studio C++ 6.0.</p>\n</blockquote>\n\n<p>Gut reaction: <em>blech</em>. Seriously! The C++ compiler shipped with VC++ 6 is known to be buggy and generally performing very badly and it's 10 years old.</p>\n\n<p>@Downvoters: consider it! I mean this in all seriousness. VC6 is just comparatively unproductive and <em>should not be used any more</em>! Especially since Microsoft discontinued its support for the software. There are cases where this can't be avoided but they are rare. In most cases, an upgrade of the code base saves money. VC++ 6 just doesn't allow to harness the potential of C++ which makes an objectively inferior tool.</p>\n" }, { "answer_id": 213248, "author": "Ed Altorfer", "author_id": 26552, "author_profile": "https://Stackoverflow.com/users/26552", "pm_score": 0, "selected": false, "text": "<p>Looks like people have tackled some of the functionality aspects of this code for you, but I'd suggest staying away from variable naming like you've employed here. </p>\n\n<p>With the exception of UI controls, it is generally frowned upon to use Hungarian notation. This is more important with numbers...for example:</p>\n\n<p>I declare:</p>\n\n<p>float fMyNumber = 0.00;</p>\n\n<p>And then I use that in my entire application. But then, later, I change that to a double because I realize that I need more precision. Now I have:</p>\n\n<p>double fMyNumber = 0.00;</p>\n\n<p>It's true that most good refactoring tools could fix this for you, but it's probably best not to attach those prefixes. They are more common in some languages than others, but from a general style perspective, you should try to avoid them. Unless you're using Notepad, you probably have something akin to Intellisense, so you don't really need to look at the variable name to figure out what type it is.</p>\n" }, { "answer_id": 213255, "author": "Phil Hannent", "author_id": 24459, "author_profile": "https://Stackoverflow.com/users/24459", "pm_score": 0, "selected": false, "text": "<p>There is always a better implementation. If you are using the function as an example of the consultant not being very good you might also want to consider that while they did not know a function that already existed they might have experience and understanding of project construction. </p>\n\n<p>Software development is not just about the perfect function but also how good the architecture of the whole thing is.</p>\n" }, { "answer_id": 213258, "author": "JohnMcG", "author_id": 1674, "author_profile": "https://Stackoverflow.com/users/1674", "pm_score": 2, "selected": false, "text": "<p>If you're wanting an evaluation of this developer's C++ skill level, I'd say this demonstrates the lower end of intermediate.</p>\n\n<p>The code gets the job done, and doesn't contain any obvious \"howlers,\" but as others have written, there are better ways of doing this.</p>\n" }, { "answer_id": 213362, "author": "Jackson", "author_id": 29061, "author_profile": "https://Stackoverflow.com/users/29061", "pm_score": 0, "selected": false, "text": "<p>I always worry when I see a do .. while loop; IMO they're always harder to understand.</p>\n" }, { "answer_id": 213398, "author": "Eclipse", "author_id": 8701, "author_profile": "https://Stackoverflow.com/users/8701", "pm_score": 4, "selected": false, "text": "<p>There's an off-by-one bug sitting there right in the middle:\nTake a look at what happens if the first character is a comma: \",abc,def,ghi\": I'm assuming the desired output would be \"\\,abc\\,def\\,ghi\", but instead you get the original string back:</p>\n\n<pre><code>int occurenceInd = originalString.Find(charFind, currentInd);\n</code></pre>\n\n<p>OccurrenceInd returns 0, since it found charFind at the first character.</p>\n\n<pre><code>if(occurenceInd&gt;0) \n</code></pre>\n\n<p>0 isn't greater than 0, so take the else branch and return the original string. <a href=\"http://msdn.microsoft.com/en-us/library/aa314323(VS.60).aspx\" rel=\"nofollow noreferrer\">CString::Find</a> returns -1 when it can't find something, so at the very least that comparison should be:</p>\n\n<pre><code>if(occurrenceInd &gt;= 0)\n</code></pre>\n\n<p>The best way would be to use the Replace function, but if you want to do it by hand, a better implementation would probably look something like this:</p>\n\n<pre><code>CString insert_escape ( const CString &amp;originalString, char charFind, char charInsert ) {\n std::string escaped;\n // Reserve enough space for each character to be escaped\n escaped.reserve(originalString.GetLength() * 2); \n for (int iOriginal = 0; iOriginal &lt; originalString.GetLength(); ++iOriginal) {\n if (originalString[iOriginal] == charFind)\n escaped += charInsert;\n escaped += originalString[iOriginal];\n }\n return CString(escaped.c_str());\n}\n</code></pre>\n" }, { "answer_id": 213526, "author": "Ates Goral", "author_id": 23501, "author_profile": "https://Stackoverflow.com/users/23501", "pm_score": 2, "selected": false, "text": "<p>My gut reaction is: <strong>WTF</strong>. Initially by how the code is formatted (there are lots of things I don't like about the formatting) and then by examination of what the code is actually doing.</p>\n\n<p>There's a serious issue with this developer's understanding of object copying in C++. The example is a WTF in itself (if the developer of the function really used his/her own function like this):</p>\n\n<pre><code>// Example call\nstrColHeader = insert_escape(strColHeader, ',', '\\\\'); //Get rid of the commas and make it an escape character\n\nCString insert_escape ( CString originalString, char charFind, char charInsert )\n</code></pre>\n\n<ol>\n<li>Pass a <strong>copy</strong> of <code>strColHeader</code> as <code>originalString</code> (notice that there's no <code>&amp;</code>)</li>\n<li>The function modified this copy (fine)</li>\n<li>The function returns a <strong>copy</strong> of the copy, which in turn <strong>replaces</strong> the original <code>strColHeader</code>. The compiler will probably optimize this out to a single copy but still, passing around object copies like this doesn't work for C++. One should know about references.</li>\n</ol>\n\n<p>A more seasoned developer would have designed this function as:</p>\n\n<pre><code>void insert_escape(CString &amp;originalString, char charFind, char charInsert)\n</code></pre>\n\n<p>or:</p>\n\n<pre><code>CString insert_escape(const CString &amp;originalString, char charFind, char charInsert)\n</code></pre>\n\n<p>(And probably would have named the parameters a bit differently)</p>\n\n<p>And as many have pointed out, the sane thing the developer could have done was to check the API documentation to see if <code>CString</code> already had a <code>Replace</code> method...</p>\n" }, { "answer_id": 213658, "author": "Sol", "author_id": 27029, "author_profile": "https://Stackoverflow.com/users/27029", "pm_score": 3, "selected": false, "text": "<p>The mistakes have already been mentioned. But they strike me as the sort of problems anyone might have with quickly dashed-off code which has not been properly tested, particularly if they are not familiar with CString.</p>\n\n<p>I'd worry more about the stylistic things, as they suggest someone who is not comfortable with C++. The use of the bool continueLoop is just plain poor C++. It represents a third of the function's code that could be eliminated by the use of a simple if...break construct, making the code easier to follow in the process.</p>\n\n<p>Also, the variable name \"originalString\" is very misleading. Because they pass it by value, it's not the original string, it's a copy of it! Then they modify the string anyway, so it no longer is the same object or the same string of text as the original. This double lie suggests muddled thought patterns.</p>\n" }, { "answer_id": 217169, "author": "paercebal", "author_id": 14089, "author_profile": "https://Stackoverflow.com/users/14089", "pm_score": 2, "selected": false, "text": "<p>I won't provide an alternative code, as it would only add to the code already provided.</p>\n\n<p>But, my gut feeling is that there's something wrong with the code.</p>\n\n<p>To prove it, I will enumerate some points in the original function that shows its developer was not an experienced C++ developer, points that you should investigate if you need a clean implementation:</p>\n\n<ul>\n<li><strong>copy</strong> : parameters are passed as copy instead of const-reference. This is a big NO NO in C++ when considering objects.</li>\n<li><strong>bug</strong> I guess there is an error in the \"if(occurenceInd>0)\" part. By reading CString's doc on MSDN, the CString::Find method returns -1, and not 0 when the find failed. This code tells me if a comma was the first character, it would not be escaped, which is probably not the point of the function</li>\n<li><strong>unneeded variable</strong> : \"continueLoop\" is not needed. Replacing the code \"continueLoop = false\" by \"continue\" and the line \"while(continueLoop)\" by \"while(true)\" is enough. Note that, continuing this reasoning enable the coder to change the functions internal (replacing a do...while by a simple while)</li>\n<li><strong>changing return type</strong> : Probably picking at details, but I would offer an alternative function which, instead of returning the result string, would accept is as a reference (one less copy on return), the original function being inlined and calling the alternative.</li>\n<li><strong>adding const whenever possible</strong> again, picking at detail: the two \"char\" parameters should be const, if only to avoid modifying them by accident.</li>\n<li><strong>possible multiple reallocation</strong> the function relies on potential multiple reallocations of the CString data. Josh's solution of using std::string's reserve is a good one.</li>\n<li><strong>using fully CString API</strong> : But unlike Josh, because you seem to use CString, I would avoid the std::string and use CString::GetBufferSetLength and CString::ReleaseBuffer, which enable me to have the same code, with one less object allocation.</li>\n<li><strong>Mysterious Insert method?</strong> it's me, or there is no CString::Insert ??? (see <a href=\"http://msdn.microsoft.com/en-us/library/aa252634(VS.60).aspx\" rel=\"nofollow noreferrer\">http://msdn.microsoft.com/en-us/library/aa252634(VS.60).aspx</a>). In fact, I even failed to find CString in the same MSDN for Visual C++ 2008 and 2005... This could be because I should <em>really</em> go to sleep, but still, I guess this is worth investigating</li>\n</ul>\n" }, { "answer_id": 256410, "author": "Adam Liss", "author_id": 29157, "author_profile": "https://Stackoverflow.com/users/29157", "pm_score": 1, "selected": false, "text": "<p>Is this consultant being paid by the line of code? Several folks have pointed out that the <code>CString</code> class already provides this functionality, so even if you're not a programmer, you know:</p>\n\n<ul>\n<li>The function is unnecessary. It adds to the complexity, size, and possibly the execution time of the program.</li>\n<li>The <code>CString</code> function probably works and is probably efficient; this one may or may not be.</li>\n<li>The <code>CString</code> function is documented, and is therefore supportable.</li>\n<li>The consultant is either unfamiliar with the standard <code>CString</code> function or thought he/she could do better by writing a new one.\n\n<ul>\n<li>One might conclude that the consultant is unfamiliar with other standard features and best practices.</li>\n<li>Choosing to write new code for a basic feature, without considering that a standard version may exist, is an accepted bad practice.</li>\n</ul></li>\n</ul>\n\n<p>And perhaps the biggest, reddest flag of all: your instincts prodded you to get opinions from the StackOverflow community.</p>\n\n<p>Trust your instincts.</p>\n" } ]
2008/10/17
[ "https://Stackoverflow.com/questions/213027", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
The following code was produced by a consultant working for my group. I'm not a C++ developer (worked in many languages, though) but would like some independent opinions on the following code. This is in Visual Studio C++ 6.0. I've got a gut reaction (not a good one, obviously), but I'd like some "gut reactions" from seasoned (or even not so unseasoned) C++ developers out there. Thanks in advance! ``` // Example call strColHeader = insert_escape(strColHeader, ',', '\\'); //Get rid of the commas and make it an escape character ``` ...snip... ``` CString insert_escape ( CString originalString, char charFind, char charInsert ) { bool continueLoop = true; int currentInd = 0; do { int occurenceInd = originalString.Find(charFind, currentInd); if(occurenceInd>0) { originalString.Insert(occurenceInd, charInsert); currentInd = occurenceInd + 2; } else { continueLoop = false; } } while(continueLoop); return(originalString); } ```
hmm. I think ``` CString strColHeader; strColHeader.Replace(",", "\\,") ``` would do just as well. I don't like the code, I tend to break from the while loop instead of having an unnecessary bool 'continue' flag. That goes double when he could have used `while (occurenceInd != 0)` as his loop control variable instead of the boolean. Incrementing the counter also relies on "+2" which doesn't seem immediately understandable (not at a quick glance), and lastly (and most importantly) he doesn't seem to do comments.
213,042
<p>I tried "x = y ** e", but that didn't work.</p>
[ { "answer_id": 213043, "author": "Evan Teran", "author_id": 13430, "author_profile": "https://Stackoverflow.com/users/13430", "pm_score": 8, "selected": true, "text": "<p>use the <code>pow</code> function (it takes <code>float</code>s/<code>double</code>s though).</p>\n\n<p><code>man pow</code>:</p>\n\n<pre><code> #include &lt;math.h&gt;\n\n double pow(double x, double y);\n float powf(float x, float y);\n long double powl(long double x, long double y);\n</code></pre>\n\n<p><strong>EDIT</strong>: For the special case of positive integer powers of <code>2</code>, you can use bit shifting: <code>(1 &lt;&lt; x)</code> will equal <code>2</code> to the power <code>x</code>. There are some potential gotchas with this, but generally, it would be correct.</p>\n" }, { "answer_id": 213064, "author": "Adam Rosenfield", "author_id": 9530, "author_profile": "https://Stackoverflow.com/users/9530", "pm_score": 5, "selected": false, "text": "<p>To add to what <a href=\"https://stackoverflow.com/questions/213042/how-do-you-do-exponentiation-in-c#213043\">Evan</a> said: C does not have a built-in operator for exponentiation, because it is not a primitive operation for most CPUs. Thus, it's implemented as a library function.</p>\n\n<p>Also, for computing the function e^x, you can use the <code>exp(double)</code>, <code>expf(float)</code>, and <code>expl(long double)</code> functions.</p>\n\n<p>Note that you do <strong>not</strong> want to use the <code>^</code> operator, which is the <em>bitwise exclusive OR</em> operator.</p>\n" }, { "answer_id": 213260, "author": "None", "author_id": 25012, "author_profile": "https://Stackoverflow.com/users/25012", "pm_score": 2, "selected": false, "text": "<p>or you could just write the power function, with recursion as a added bonus</p>\n\n<pre><code>int power(int x, int y){\n if(y == 0)\n return 1;\n return (x * power(x,y-1) );\n }\n</code></pre>\n\n<p>yes,yes i know this is less effecient space and time complexity but recursion is just more fun!!</p>\n" }, { "answer_id": 213322, "author": "ephemient", "author_id": 20713, "author_profile": "https://Stackoverflow.com/users/20713", "pm_score": 5, "selected": false, "text": "<p><code>pow</code> only works on floating-point numbers (<code>double</code>s, actually). If you want to take powers of integers, and the base isn't known to be an exponent of <code>2</code>, you'll have to roll your own.</p>\n\n<p>Usually the dumb way is good enough.</p>\n\n<pre><code>int power(int base, unsigned int exp) {\n int i, result = 1;\n for (i = 0; i &lt; exp; i++)\n result *= base;\n return result;\n }\n</code></pre>\n\n<p>Here's a recursive solution which takes <code>O(log n)</code> space and time instead of the easy <code>O(1)</code> space <code>O(n)</code> time:</p>\n\n<pre><code>int power(int base, int exp) {\n if (exp == 0)\n return 1;\n else if (exp % 2)\n return base * power(base, exp - 1);\n else {\n int temp = power(base, exp / 2);\n return temp * temp;\n }\n}\n</code></pre>\n" }, { "answer_id": 213897, "author": "Jonathan Leffler", "author_id": 15168, "author_profile": "https://Stackoverflow.com/users/15168", "pm_score": 3, "selected": false, "text": "<p>The non-recursive version of the function is not too hard - here it is for integers:</p>\n\n<pre><code>long powi(long x, unsigned n)\n{\n long p = x;\n long r = 1;\n\n while (n &gt; 0)\n {\n if (n % 2 == 1)\n r *= p;\n p *= p;\n n /= 2;\n }\n\n return(r);\n}\n</code></pre>\n\n<p>(Hacked out of code for raising a double value to an integer power - had to remove the code to deal with reciprocals, for example.)</p>\n" }, { "answer_id": 4641585, "author": "Anonymous", "author_id": 504056, "author_profile": "https://Stackoverflow.com/users/504056", "pm_score": 2, "selected": false, "text": "<pre><code>int power(int x,int y){\n int r=1;\n do{\n r*=r;\n if(y%2)\n r*=x;\n }while(y&gt;&gt;=1);\n return r;\n};\n</code></pre>\n\n<p>(iterative)</p>\n\n<pre><code>int power(int x,int y){\n return y?(y%2?x:1)*power(x*x,y&gt;&gt;1):1;\n};\n</code></pre>\n\n<p>(if it has to be recursive)</p>\n\n<p>imo, the algorithm should definitely be O(logn)</p>\n" }, { "answer_id": 11552955, "author": "kallikak", "author_id": 966208, "author_profile": "https://Stackoverflow.com/users/966208", "pm_score": 3, "selected": false, "text": "<p>Similar to an earlier answer, this will handle positive and negative integer powers of a double nicely.</p>\n\n<pre><code>double intpow(double a, int b)\n{\n double r = 1.0;\n if (b &lt; 0)\n {\n a = 1.0 / a;\n b = -b;\n }\n while (b)\n {\n if (b &amp; 1)\n r *= a;\n a *= a;\n b &gt;&gt;= 1;\n }\n return r;\n}\n</code></pre>\n" } ]
2008/10/17
[ "https://Stackoverflow.com/questions/213042", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7598/" ]
I tried "x = y \*\* e", but that didn't work.
use the `pow` function (it takes `float`s/`double`s though). `man pow`: ``` #include <math.h> double pow(double x, double y); float powf(float x, float y); long double powl(long double x, long double y); ``` **EDIT**: For the special case of positive integer powers of `2`, you can use bit shifting: `(1 << x)` will equal `2` to the power `x`. There are some potential gotchas with this, but generally, it would be correct.
213,045
<p>I have a class library with some extension methods written in C# and an old website written in VB.</p> <p>I want to call my extension methods from the VB code but they don't appear in intelisense and I get compile errors when I visit the site.</p> <p>I have got all the required <em>Import</em>s because other classes contained in the same namespaces are appearing fine in Intelisense.</p> <p>Any suggestions</p> <p><strong>EDIT:</strong> More info to help with some comments.</p> <p>my implementation looks like this </p> <pre><code>//C# code compiled as DLL namespace x.y { public static class z { public static string q (this string s){ return s + " " + s; } } } </code></pre> <p>and my usage like this </p> <pre><code>Imports x.y '...' Dim r as string = "greg" Dim s as string = r.q() ' does not show in intelisense ' and throws error : Compiler Error Message: BC30203: Identifier expected. </code></pre>
[ { "answer_id": 213066, "author": "ICR", "author_id": 214, "author_profile": "https://Stackoverflow.com/users/214", "pm_score": 2, "selected": false, "text": "<p>Extension methods are just syntactic sugar for static methods. So</p>\n\n<pre><code>public static string MyExtMethod(this string s)\n</code></pre>\n\n<p>can be called in both VB.NET and C# with</p>\n\n<pre><code>MyExtMethod(\"myArgument\")\n</code></pre>\n" }, { "answer_id": 213070, "author": "Jason Jackson", "author_id": 13103, "author_profile": "https://Stackoverflow.com/users/13103", "pm_score": 0, "selected": false, "text": "<p>I don't know if you can call them in the same dot notation as you would in C#, but I would think that the static extension methods would show up as static functions with the fist argument as the extended type. So you should be able to call the actually class in VB with:</p>\n\n<pre><code>StaticClass.ExtensionMethod(theString, arg1, ..., argN)\n</code></pre>\n\n<p>Where in C# you would have just written:</p>\n\n<pre><code>theString.ExtensionMethod(arg1, ..., argN);\n</code></pre>\n\n<p>With StaticClass being the name of the static class in which you defined your extension methods.</p>\n" }, { "answer_id": 213318, "author": "Konrad Rudolph", "author_id": 1968, "author_profile": "https://Stackoverflow.com/users/1968", "pm_score": 0, "selected": false, "text": "<blockquote>\n <p>… and an old website written in VB.</p>\n</blockquote>\n\n<p>Does “old” here imply perhaps that you also use an old version of VB here? Anyway, since extension methods are just vanilla static (“<code>Shared</code>”) methods decorated with an attribute, you <em>should</em> be able to call them in any case.</p>\n\n<p>If this isn't possible you either try to call them “extension style” in an old version of VB or you're referencing the wrong version of your C# assembly.</p>\n\n<p>Edit: are you sure you're <code>Import</code>ing the <em>whole</em> namespace, i.e. <code>x.y</code> and not just <code>x</code>? VB is able to access nested namespaces easier than C# so you can use classes from namespace <code>x.y</code> using the following code in VB. However, for extension methods to work, the <em>full</em> path has to be <code>Import</code>ed.</p>\n\n<pre><code>Imports x\nDim x As New y.SomeClass()\n</code></pre>\n" }, { "answer_id": 213338, "author": "kͩeͣmͮpͥ ͩ", "author_id": 26479, "author_profile": "https://Stackoverflow.com/users/26479", "pm_score": 1, "selected": false, "text": "<pre><code>Imports x.y\n\n'...'\nDim r As String = \"greg\"\nDim s As String = r.q() 'same as z.q(r) \n</code></pre>\n" }, { "answer_id": 213361, "author": "Konrad Rudolph", "author_id": 1968, "author_profile": "https://Stackoverflow.com/users/1968", "pm_score": 2, "selected": false, "text": "<p>OK. Based on the error message you are definitely <em>not</em> using the most recent VB version (VB 9!) or the error isn't related to this problem at all because then you'd get another error if the method wasn't found:</p>\n\n<blockquote>\n <p>Error 1 'q' is not a member of 'String'.</p>\n</blockquote>\n" }, { "answer_id": 213450, "author": "Jon Skeet", "author_id": 22656, "author_profile": "https://Stackoverflow.com/users/22656", "pm_score": 4, "selected": true, "text": "<p>It works for me, although there are a couple of quirks. First, I created a C# class library targeting .NET 3.5. Here's the only code in the project:</p>\n\n<pre><code>using System;\n\nnamespace ExtensionLibrary\n{\n public static class Extensions\n {\n public static string CustomExtension(this string text)\n {\n char[] chars = text.ToCharArray();\n Array.Reverse(chars);\n return new string(chars);\n }\n }\n}\n</code></pre>\n\n<p>Then I created a VB console app targeting .NET 3.5, and added a reference to my C# project. I renamed Module1.vb to Test.vb, and here's the code:</p>\n\n<pre><code>Imports ExtensionLibrary\n\nModule Test\n\n Sub Main()\n Console.WriteLine(\"Hello\".CustomExtension())\n End Sub\n\nEnd Module\n</code></pre>\n\n<p>This compiles and runs. (I would have called the method Reverse() but I wasn't sure whether VB might magically have reverse abilities already somewhere - I'm not a VB expert by a long chalk.)</p>\n\n<p>Initially, I wasn't offered ExtensionLibrary as an import from Intellisense. Even after building, the \"Imports ExtensionLibrary\" is greyed out, and a lightbulb offers the opportunity to remove the supposedly redundant import. (Doing so breaks the project.) It's possible that this is ReSharper rather than Visual Studio, mind you.</p>\n\n<p>So to cut a long story short, it can be done, and it should work just fine. I don't suppose the problem is that you're either using an old version of VB or your project isn't targeting .NET 3.5?</p>\n\n<p>As noted in comments: there's one additional quirk, which is that <a href=\"https://stackoverflow.com/questions/3227888\">extension methods won't be found when the compile-time type of the target is <code>Object</code></a>.</p>\n" }, { "answer_id": 213512, "author": "kͩeͣmͮpͥ ͩ", "author_id": 26479, "author_profile": "https://Stackoverflow.com/users/26479", "pm_score": 0, "selected": false, "text": "<p>Two things to check:</p>\n\n<ol>\n<li>You're Targeting .Net 3.5</li>\n<li>You're referencing the DLL</li>\n</ol>\n\n<p>Some tools might incorrectly suggest extension methods for projects that don't support them.</p>\n" }, { "answer_id": 523978, "author": "Greg B", "author_id": 1741868, "author_profile": "https://Stackoverflow.com/users/1741868", "pm_score": -1, "selected": false, "text": "<p>This was quite a while ago and I can't really how I solved it, but needless to say, it was user error. I probably restarted my computer and away it went.</p>\n" }, { "answer_id": 3742072, "author": "NagyBandi", "author_id": 451429, "author_profile": "https://Stackoverflow.com/users/451429", "pm_score": 0, "selected": false, "text": "<p>I ran into the same problem, and might accidentally have stumbled upon the solution. If I used</p>\n\n<pre><code>x.y.r.q()\n</code></pre>\n\n<p>, it threw the same error for me as well. But if I imported x.y, it worked, so:</p>\n\n<pre><code>using x.y;\n...\nr.q()\n</code></pre>\n\n<p>was fine.</p>\n\n<p>So apparently you have to import it in the declaration to make it work.</p>\n" }, { "answer_id": 12211281, "author": "Keith", "author_id": 905, "author_profile": "https://Stackoverflow.com/users/905", "pm_score": 1, "selected": false, "text": "<p>I think I've <a href=\"https://stackoverflow.com/questions/10829615\">encountered a similar problem</a>: VB.Net is quite happy to compile on through extension methods and leave them to be inferred at run-time if <code>Option Strict</code> is off.</p>\n\n<p>However, VB.Net really doesn't seem to like extension methods on basic types. You can't extend <code>Object</code> and it can't resolve it if you do:</p>\n\n<p>C#</p>\n\n<pre><code>namespace NS\n...\n\npublic static class Utility {\n\n public static void Something(this object input) { ...\n\n public static void Something(this string input) { ...\n\n}\n\n// Works fine, resolves to 2nd method\n\"test\".Something();\n\n// At compile time C# converts the above to:\nUtility.Something(\"test\");\n</code></pre>\n\n<p>However this goes wrong in VB.Net:</p>\n\n<pre><code>Option Infer On\nOption Explicit On\nOption Strict Off\nImports NS\n...\n\n Dim r as String = \"test\" \n r.Something()\n</code></pre>\n\n<p>That compiles without error, but at run time fails because <code>Something</code> is not a method of <code>String</code> - the compiler has failed to replace the syntactic sugar of the extension method with the the static call to <code>Utility.Something</code>.</p>\n\n<p>The question is why? Well unlike C#, <em>VB.Net can't handle any extension to <code>Object</code></em>! The valid extension method in C# confuses the VB.Net compiler.</p>\n\n<p>As a general VB.Net rule, I'd avoid using extension methods with any of the basic .Net types (<code>Object</code>, <code>String</code>, <code>Integer</code>, etc). You also have to be careful with <code>Option Infer</code> as while it's on by default in Visual Studio it's off by default for command line compiles, <code>VBCodeProvider</code>, and possibly in web sites (depending on your web.config). When it's off everything in VB.Net is considered to be an <code>Object</code> and all extension methods will be left until run time (and will therefore fail).</p>\n\n<p>I think Microsoft really dropped the ball when they added extension methods to VB.Net, I think it was an afterthought to try (and fail) to make it consistent with C#. </p>\n" } ]
2008/10/17
[ "https://Stackoverflow.com/questions/213045", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1741868/" ]
I have a class library with some extension methods written in C# and an old website written in VB. I want to call my extension methods from the VB code but they don't appear in intelisense and I get compile errors when I visit the site. I have got all the required *Import*s because other classes contained in the same namespaces are appearing fine in Intelisense. Any suggestions **EDIT:** More info to help with some comments. my implementation looks like this ``` //C# code compiled as DLL namespace x.y { public static class z { public static string q (this string s){ return s + " " + s; } } } ``` and my usage like this ``` Imports x.y '...' Dim r as string = "greg" Dim s as string = r.q() ' does not show in intelisense ' and throws error : Compiler Error Message: BC30203: Identifier expected. ```
It works for me, although there are a couple of quirks. First, I created a C# class library targeting .NET 3.5. Here's the only code in the project: ``` using System; namespace ExtensionLibrary { public static class Extensions { public static string CustomExtension(this string text) { char[] chars = text.ToCharArray(); Array.Reverse(chars); return new string(chars); } } } ``` Then I created a VB console app targeting .NET 3.5, and added a reference to my C# project. I renamed Module1.vb to Test.vb, and here's the code: ``` Imports ExtensionLibrary Module Test Sub Main() Console.WriteLine("Hello".CustomExtension()) End Sub End Module ``` This compiles and runs. (I would have called the method Reverse() but I wasn't sure whether VB might magically have reverse abilities already somewhere - I'm not a VB expert by a long chalk.) Initially, I wasn't offered ExtensionLibrary as an import from Intellisense. Even after building, the "Imports ExtensionLibrary" is greyed out, and a lightbulb offers the opportunity to remove the supposedly redundant import. (Doing so breaks the project.) It's possible that this is ReSharper rather than Visual Studio, mind you. So to cut a long story short, it can be done, and it should work just fine. I don't suppose the problem is that you're either using an old version of VB or your project isn't targeting .NET 3.5? As noted in comments: there's one additional quirk, which is that [extension methods won't be found when the compile-time type of the target is `Object`](https://stackoverflow.com/questions/3227888).
213,078
<p>Alright so I'm essentialyl trying to code something that will combine two files together in VB and output a single file that when run, runs both of them. I've grabbed this source from several places online and am just trying to get it to work. We have the main program that combines them with a GUI</p> <pre><code>Const FileSplit = "@&lt;&gt;#&lt;&gt;#&lt;&gt;@" Private Sub cmdAdd_Click() With Dlg .Filter = "All Files(*.*) | *.*" .DialogTitle = "Please Select a File..." .ShowOpen End With lsFiles.AddItem (Dlg.FileName) End Sub Private Sub cmdBuild_Click() Dim sStub As String, sFiles As String, i As Integer Open App.Path &amp; "\stub.exe" For Binary As #1 sStub = Space(LOF(1)) Get #1, , sStub Close #1 Open App.Path &amp; "\boundfile.exe" For Binary As #1 Put #1, , sStub &amp; FileSplit For i = 0 To lsFiles.ListCount - 1 Open lsFiles.List(i) For Binary As #2 sFiles = Space(LOF(2)) Get #2, , sFiles Close #2 Put #1, , sFiles &amp; FileSplit Next i Close #1 MsgBox "Files Successfully Combined" End Sub </code></pre> <p>And then we have a second App that acts as a stub</p> <pre><code>Const FileSplit = "@&lt;&gt;#&lt;&gt;#&lt;&gt;@" Private Declare Function ShellExecute Lib "shell32.dll" Alias "ShellExecuteA" (ByVal hwnd As Long, ByVal lpOperation As String, ByVal lpFile As String, ByVal lpParameters As String, ByVal lpDirectory As String, ByVal nShowCmd As Long) As Long Private Sub Form_Load() Dim sStub As String, sFiles() As String, i As Integer Open App.Path &amp; "\" &amp; App.EXEName &amp; ".exe" For Binary As #1 sStub = Input(LOF(1), 1) Get #1, , stub Close #1 sFiles = Split(sStub, FileSplit) For i = 1 To UBound(sFiles()) Open Environ("tmp") &amp; "\tmp" &amp; i &amp; ".exe" For Binary As #1 Put #1, , sFiles(i) Close #1 Call ShellExecute(0, vbNullString, Environ("tmp") &amp; "\tmp" &amp; i &amp; ".exe", vbNullString, vbNullString, vbNormalFocus) Next i End End Sub </code></pre> <p>however when the files are combined and run all I get is a dosbox opening and closing. Any ideas?</p>
[ { "answer_id": 213234, "author": "Mitchel Sellers", "author_id": 13279, "author_profile": "https://Stackoverflow.com/users/13279", "pm_score": 0, "selected": false, "text": "<p>I would start by comparing the temporary files, are you successfully re-writing out the files where they are exact matches to that of the source?</p>\n" }, { "answer_id": 235561, "author": "smbarbour", "author_id": 29115, "author_profile": "https://Stackoverflow.com/users/29115", "pm_score": 2, "selected": false, "text": "<p>One major issue is that you are using String variables which terminate at the first null character (ASCII code 0)</p>\n\n<p>Since executable files are binary, it is exceptionally likely that they are are not being copied into (or out of) the file in full.</p>\n\n<p>As a result, I would suggest reading the files into a Byte array and encoding them using an algorithm that produces only printable characters (such as Base64). Alternately, you could devise some scheme of searching through the Byte arrays to find the EOF delimiters.</p>\n\n<p>I'm going to favorite this item, as it appears that this is the start of an interesting way to embed files within an executable. With sufficient coding, you could also embed the original filenames and extensions as well as specifying what behavior to perform after expansion. Add in some compression, and you've got a pretty sweet app.</p>\n" }, { "answer_id": 235586, "author": "Svante Svenson", "author_id": 19707, "author_profile": "https://Stackoverflow.com/users/19707", "pm_score": 0, "selected": false, "text": "<p>When using Open...As Binary and Put, some data about the string is being added to the output messing things up. Instead use Open...For Output and Print. And end your print line with a semicolon to not intert a linebreak. Also your stub is a bit weird, changed the stuff I mentioned above and that in your code as follows::</p>\n\n<pre><code>Const FileSplit = \"@&lt;&gt;#&lt;&gt;#&lt;&gt;@\"\n\nPrivate Sub cmdAdd_Click()\n With Dlg\n .Filter = \"All Files(*.*) | *.*\"\n .DialogTitle = \"Please Select a File...\"\n .ShowOpen\n End With\n lsFiles.AddItem (Dlg.FileName)\nEnd Sub\n\nPrivate Sub cmdBuild_Click()\n Dim sStub As String, sFiles As String, i As Integer\n Open App.Path &amp; \"\\stub.exe\" For Binary As #1\n sStub = Space(LOF(1))\n Get #1, , sStub\n Close #1\n Open App.Path &amp; \"\\boundfile.exe\" For Output As #1\n Print #1, sStub &amp; FileSplit;\n For i = 0 To lsFiles.ListCount - 1\n Open lsFiles.List(i) For Binary As #2\n sFiles = Space(LOF(2))\n Get #2, , sFiles\n Close #2\n Print #1, sFiles &amp; FileSplit;\n Next i\n Close #1\n MsgBox \"Files Successfully Combined\"\nEnd Sub\n</code></pre>\n\n<p>and</p>\n\n<pre><code>Const FileSplit = \"@&lt;&gt;#&lt;&gt;#&lt;&gt;@\"\nPrivate Declare Function ShellExecute Lib \"shell32.dll\" Alias \"ShellExecuteA\" (ByVal hwnd As Long, ByVal lpOperation As String, ByVal lpFile As String, ByVal lpParameters As String, ByVal lpDirectory As String, ByVal nShowCmd As Long) As Long\n\nPrivate Sub Form_Load()\n Dim sStub As String, sFiles() As String, i As Integer\n Open App.Path &amp; \"\\\" &amp; App.EXEName &amp; \".exe\" For Binary As #1\n sStub = Space(LOF(1))\n Get #1, , sStub\n Close #1\n sFiles = Split(sStub, FileSplit)\n For i = 1 To UBound(sFiles())\n Open Environ(\"tmp\") &amp; \"\\tmp\" &amp; i &amp; \".exe\" For Output As #1\n Print #1, sFiles(i);\n Close #1\n Call ShellExecute(0, vbNullString, Environ(\"tmp\") &amp; \"\\tmp\" &amp; i &amp; \".exe\", vbNullString, vbNullString, vbNormalFocus)\n Next i \n End\nEnd Sub\n</code></pre>\n" } ]
2008/10/17
[ "https://Stackoverflow.com/questions/213078", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
Alright so I'm essentialyl trying to code something that will combine two files together in VB and output a single file that when run, runs both of them. I've grabbed this source from several places online and am just trying to get it to work. We have the main program that combines them with a GUI ``` Const FileSplit = "@<>#<>#<>@" Private Sub cmdAdd_Click() With Dlg .Filter = "All Files(*.*) | *.*" .DialogTitle = "Please Select a File..." .ShowOpen End With lsFiles.AddItem (Dlg.FileName) End Sub Private Sub cmdBuild_Click() Dim sStub As String, sFiles As String, i As Integer Open App.Path & "\stub.exe" For Binary As #1 sStub = Space(LOF(1)) Get #1, , sStub Close #1 Open App.Path & "\boundfile.exe" For Binary As #1 Put #1, , sStub & FileSplit For i = 0 To lsFiles.ListCount - 1 Open lsFiles.List(i) For Binary As #2 sFiles = Space(LOF(2)) Get #2, , sFiles Close #2 Put #1, , sFiles & FileSplit Next i Close #1 MsgBox "Files Successfully Combined" End Sub ``` And then we have a second App that acts as a stub ``` Const FileSplit = "@<>#<>#<>@" Private Declare Function ShellExecute Lib "shell32.dll" Alias "ShellExecuteA" (ByVal hwnd As Long, ByVal lpOperation As String, ByVal lpFile As String, ByVal lpParameters As String, ByVal lpDirectory As String, ByVal nShowCmd As Long) As Long Private Sub Form_Load() Dim sStub As String, sFiles() As String, i As Integer Open App.Path & "\" & App.EXEName & ".exe" For Binary As #1 sStub = Input(LOF(1), 1) Get #1, , stub Close #1 sFiles = Split(sStub, FileSplit) For i = 1 To UBound(sFiles()) Open Environ("tmp") & "\tmp" & i & ".exe" For Binary As #1 Put #1, , sFiles(i) Close #1 Call ShellExecute(0, vbNullString, Environ("tmp") & "\tmp" & i & ".exe", vbNullString, vbNullString, vbNormalFocus) Next i End End Sub ``` however when the files are combined and run all I get is a dosbox opening and closing. Any ideas?
One major issue is that you are using String variables which terminate at the first null character (ASCII code 0) Since executable files are binary, it is exceptionally likely that they are are not being copied into (or out of) the file in full. As a result, I would suggest reading the files into a Byte array and encoding them using an algorithm that produces only printable characters (such as Base64). Alternately, you could devise some scheme of searching through the Byte arrays to find the EOF delimiters. I'm going to favorite this item, as it appears that this is the start of an interesting way to embed files within an executable. With sufficient coding, you could also embed the original filenames and extensions as well as specifying what behavior to perform after expansion. Add in some compression, and you've got a pretty sweet app.
213,085
<p>I'm working on a forums system. I'm trying to allow users to see the posts they've made. In order for this link to work, I'd need to jump to the <strong>page</strong> on the particular topic they posted in that contained their post, so the bookmarks could work, etc. Since this is a new feature on an old forum, I'd like to code it so that the forum system doesn't have to keep track of every post, but can simply populate this list automatically.</p> <p>I know how to populate the list, but I need to do this: </p> <p>Given a query, where will X row within the query (guaranteed to be unique by some combination of identifiers) appear? As in, how many rows would I have to offset to get to it? This would be in a sorted query.</p> <p>Ideally, I'd like to do this with SQL and not PHP, but if it can't be done in SQL I guess that's an answer too. ^_^</p> <p>Thanks</p>
[ { "answer_id": 213099, "author": "AndyG", "author_id": 27678, "author_profile": "https://Stackoverflow.com/users/27678", "pm_score": 0, "selected": false, "text": "<p>The thing about databases is that there is no real \"order\" to them. You can use the SCOPE_IDENTITY operator to return the unique ID of the inserted record, then write some sort of function to paginate until that record is found.</p>\n" }, { "answer_id": 213126, "author": "Troy Howard", "author_id": 19258, "author_profile": "https://Stackoverflow.com/users/19258", "pm_score": 2, "selected": false, "text": "<p>If you're using MSSQL, you could use <a href=\"http://msdn.microsoft.com/en-us/library/ms186734.aspx\" rel=\"nofollow noreferrer\">ROW_NUMBER()</a> function to add an auto-incrementing number to each row in a query. </p>\n\n<p>I don't know what good that would do you though. But it will do what you asked -- assign a number to the position of a row within the result set of a given query. </p>\n\n<p>If this is written in ph though, you're probably using mySQL.</p>\n" }, { "answer_id": 213186, "author": "Owen", "author_id": 4853, "author_profile": "https://Stackoverflow.com/users/4853", "pm_score": 3, "selected": true, "text": "<p>hmm this solution makes a few assumptions, but i think it should work for what you're trying to do if i understand it correctly:</p>\n\n<pre><code>SELECT count(post_id) FROM posts\n WHERE thread_id = '{$thread_id}' AND date_posted &lt;= '{$date_posted}'\n</code></pre>\n\n<p>this will get you the number of rows in a particular thread (which i assume you've pre-calculated) which are equal to, or earlier than the date posted (the specific user post in question).</p>\n\n<p>based on this information (say 15th post in that thread), you can calculate what page the result would be on based on the forums paging values. ie</p>\n\n<pre><code>// dig around forum code for number of items per page\n$itemsPerPage = 10; // let's say\n$ourCount = getQueryResultFromAbove(); \n\n// this is the page that post will be on\n$page = ceil($ourCount / $itemsPerPage);\n\n// for example\n$link = '/thread.php?thread_id='.$thread_id.'&amp;page='.$page;\n</code></pre>\n" }, { "answer_id": 213189, "author": "James Curran", "author_id": 12725, "author_profile": "https://Stackoverflow.com/users/12725", "pm_score": 0, "selected": false, "text": "<p>Expanding on Troy's suggestion, you'd need a sub-query, basically,</p>\n\n<pre><code> select row_number() OVER(ORDER BY MessageDate DESC) \n AS 'RowNum', * from MESSAGES\n</code></pre>\n\n<p>then put an outer select to do the real work:</p>\n\n<pre><code> select RowNum, Title, Body, Author from (\n select row_number() OVER(ORDER BY MessageDate DESC) \n AS 'RowNum', * from MESSAGES)\n where AuthorID = @User\n</code></pre>\n\n<p>Use rownum to calculate the page number.</p>\n" }, { "answer_id": 213200, "author": "Vinko Vrsalovic", "author_id": 5190, "author_profile": "https://Stackoverflow.com/users/5190", "pm_score": 0, "selected": false, "text": "<p>I agree with Troy, you probably are going around this wrongly, to fix it we'd have to know more details, but in any case in MySQL you can do that like this</p>\n\n<pre><code>SET @i=0;\nSELECT number FROM (SELECT *,@i:=@i+1 as number FROM Posts \nORDER BY &lt;order_clause&gt;) as a WHERE &lt;unique_condition_over_a&gt;\n</code></pre>\n\n<p>In PostgreSQL you could use a temporary sequence:</p>\n\n<pre><code>CREATE TEMPORARY SEQUENCE counter;\nSELECT number FROM (SELECT *,nextval('sequence') as number FROM Posts \nORDER BY &lt;order_clause&gt;) as a WHERE &lt;unique_condition_over_a&gt;\n</code></pre>\n" }, { "answer_id": 213217, "author": "Kris", "author_id": 18565, "author_profile": "https://Stackoverflow.com/users/18565", "pm_score": 0, "selected": false, "text": "<p>I think you mean something like this (MySQL)?</p>\n\n<pre><code>START TRANSACTION;\n\nSET @rows_count = 0;\nSET @user_id = ...;\nSET @page_size = ...;\n\nSELECT \n @rows_count := @rows_count + 1 AS RowNumber\n ,CEIL( @rows_count / @page_size ) AS PageNumber\nFROM ForumPost P\nWHERE \n P.PosterId = @user_id;\n\nROLLBACK;\n</code></pre>\n" }, { "answer_id": 213315, "author": "Cervo", "author_id": 16219, "author_profile": "https://Stackoverflow.com/users/16219", "pm_score": 0, "selected": false, "text": "<p>Most SQL platforms have a proprietary extension of IDENTITY columns or sequences that increment with every item in a table. Most also have temporary tables.</p>\n\n<pre><code>CREATE TABLE OF QUERY RESULTS WITH IDENTITY COLUMN\n\nINSERT INTO TABLE \nQUERY \nORDER BY something\n</code></pre>\n\n<p>then the identity column is the number in the query and it tells you how many entries are before/after it.</p>\n\n<p>The important thing is to order by something. Otherwise you may get different orders with each query in which case your number means nothing...</p>\n" } ]
2008/10/17
[ "https://Stackoverflow.com/questions/213085", "https://Stackoverflow.com", "https://Stackoverflow.com/users/19521/" ]
I'm working on a forums system. I'm trying to allow users to see the posts they've made. In order for this link to work, I'd need to jump to the **page** on the particular topic they posted in that contained their post, so the bookmarks could work, etc. Since this is a new feature on an old forum, I'd like to code it so that the forum system doesn't have to keep track of every post, but can simply populate this list automatically. I know how to populate the list, but I need to do this: Given a query, where will X row within the query (guaranteed to be unique by some combination of identifiers) appear? As in, how many rows would I have to offset to get to it? This would be in a sorted query. Ideally, I'd like to do this with SQL and not PHP, but if it can't be done in SQL I guess that's an answer too. ^\_^ Thanks
hmm this solution makes a few assumptions, but i think it should work for what you're trying to do if i understand it correctly: ``` SELECT count(post_id) FROM posts WHERE thread_id = '{$thread_id}' AND date_posted <= '{$date_posted}' ``` this will get you the number of rows in a particular thread (which i assume you've pre-calculated) which are equal to, or earlier than the date posted (the specific user post in question). based on this information (say 15th post in that thread), you can calculate what page the result would be on based on the forums paging values. ie ``` // dig around forum code for number of items per page $itemsPerPage = 10; // let's say $ourCount = getQueryResultFromAbove(); // this is the page that post will be on $page = ceil($ourCount / $itemsPerPage); // for example $link = '/thread.php?thread_id='.$thread_id.'&page='.$page; ```
213,118
<p>In MFC I'm trying to set a null handler timer (ie. no windows). But I'm unable to process the WM_TIMER event in the CWinApp MESSAGE_MAP. Is this possible? If so, how?</p>
[ { "answer_id": 213155, "author": "Adam Tegen", "author_id": 4066, "author_profile": "https://Stackoverflow.com/users/4066", "pm_score": 2, "selected": false, "text": "<p>I've done this by making an invisible window and setting a timer on it.</p>\n" }, { "answer_id": 213776, "author": "Shog9", "author_id": 811, "author_profile": "https://Stackoverflow.com/users/811", "pm_score": 5, "selected": true, "text": "<p>As told by MSDN, there are two modes of operation for <a href=\"http://msdn.microsoft.com/en-us/library/ms644906.aspx\" rel=\"noreferrer\"><code>SetTimer()</code></a>: one that associates a timer with a window, and one that associates a timer with a thread's message queue. When you have a window, you can use the former; otherwise, you must use the latter. And <code>CWinApp</code> <em>isn't</em> a window.</p>\n<h3>Catching timer messages in the thread queue</h3>\n<pre><code>UINT_PTR uTimerId = SetTimer(NULL, 0, 2000, NULL);\nTRACE(_T(&quot;Timer created - ID=%x\\n&quot;), uTimerId);\n</code></pre>\n<p>This will create a new timer, set to fire every two seconds, associated only with the current thread's message queue. You don't get to specify a timer ID when you aren't associating it with a window, so save the ID returned in a class member or something - <a href=\"http://blogs.msdn.com/oldnewthing/archive/2008/10/16/9001218.aspx\" rel=\"noreferrer\">you'll have a rough time killing the timer later on if you forget</a>. You could then process this in a <code>CWinApp::PreTranslateMessage()</code> override:</p>\n<pre><code>BOOL CMyFunkyApp::PreTranslateMessage(MSG* pMsg)\n{\n if (pMsg-&gt;message == WM_TIMER)\n {\n TRACE(_T(&quot;Timer fired - ID=%x\\n&quot;), pMsg-&gt;wParam);\n }\n\n return CWinApp::PreTranslateMessage(pMsg);\n}\n</code></pre>\n<p>Note that hooking into the thread's message loop like this is the <em>only</em> way to handle a timer set up this way - as we discussed, there's no window, and although MFC does provide a message map facility for <code>CWinApp</code> you can't use the <code>ON_WM_*()</code> macros because... well, because <em>it's not a window</em>. However, there is another, <em>slightly</em> less-messy way: callbacks.</p>\n<h3>Handling timer messages with a callback</h3>\n<pre><code>void CALLBACK TimerCallback(HWND, UINT, UINT_PTR id, DWORD dwTime)\n{\n TRACE(_T(&quot;Timer fired - ID=%x\\n&quot;), id);\n}\n\n//...\n\nUINT_PTR uTimerId = SetTimer(NULL, 0, 2000, &amp;TimerCallback);\nTRACE(_T(&quot;Timer created - ID=%x\\n&quot;), uTimerId);\n</code></pre>\n<p>This does almost <em>exactly</em> the same thing as the first example: a new timer is configured to fire every two seconds, associated with the current thread's message queue... but <em>this</em> one has a callback address associated with it. And the default message handler knows to call the callback when such a timer message is processed, so you don't have to bother hooking into the message loop.</p>\n<p>So there you go. Two ways of using timers from <code>CWinApp</code>.</p>\n" }, { "answer_id": 213789, "author": "John Dyer", "author_id": 2862, "author_profile": "https://Stackoverflow.com/users/2862", "pm_score": 2, "selected": false, "text": "<p>Check out this post by Raymond Chen. There are some interesting nuggets for what your working on that might keep you out of trouble.</p>\n\n<p><a href=\"http://blogs.msdn.com/oldnewthing/archive/2008/10/16/9001218.aspx\" rel=\"nofollow noreferrer\">Why your thread is spending all its time processing meaningless thread timers</a></p>\n" } ]
2008/10/17
[ "https://Stackoverflow.com/questions/213118", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
In MFC I'm trying to set a null handler timer (ie. no windows). But I'm unable to process the WM\_TIMER event in the CWinApp MESSAGE\_MAP. Is this possible? If so, how?
As told by MSDN, there are two modes of operation for [`SetTimer()`](http://msdn.microsoft.com/en-us/library/ms644906.aspx): one that associates a timer with a window, and one that associates a timer with a thread's message queue. When you have a window, you can use the former; otherwise, you must use the latter. And `CWinApp` *isn't* a window. ### Catching timer messages in the thread queue ``` UINT_PTR uTimerId = SetTimer(NULL, 0, 2000, NULL); TRACE(_T("Timer created - ID=%x\n"), uTimerId); ``` This will create a new timer, set to fire every two seconds, associated only with the current thread's message queue. You don't get to specify a timer ID when you aren't associating it with a window, so save the ID returned in a class member or something - [you'll have a rough time killing the timer later on if you forget](http://blogs.msdn.com/oldnewthing/archive/2008/10/16/9001218.aspx). You could then process this in a `CWinApp::PreTranslateMessage()` override: ``` BOOL CMyFunkyApp::PreTranslateMessage(MSG* pMsg) { if (pMsg->message == WM_TIMER) { TRACE(_T("Timer fired - ID=%x\n"), pMsg->wParam); } return CWinApp::PreTranslateMessage(pMsg); } ``` Note that hooking into the thread's message loop like this is the *only* way to handle a timer set up this way - as we discussed, there's no window, and although MFC does provide a message map facility for `CWinApp` you can't use the `ON_WM_*()` macros because... well, because *it's not a window*. However, there is another, *slightly* less-messy way: callbacks. ### Handling timer messages with a callback ``` void CALLBACK TimerCallback(HWND, UINT, UINT_PTR id, DWORD dwTime) { TRACE(_T("Timer fired - ID=%x\n"), id); } //... UINT_PTR uTimerId = SetTimer(NULL, 0, 2000, &TimerCallback); TRACE(_T("Timer created - ID=%x\n"), uTimerId); ``` This does almost *exactly* the same thing as the first example: a new timer is configured to fire every two seconds, associated with the current thread's message queue... but *this* one has a callback address associated with it. And the default message handler knows to call the callback when such a timer message is processed, so you don't have to bother hooking into the message loop. So there you go. Two ways of using timers from `CWinApp`.
213,121
<blockquote> <p><strong>Possible Duplicate:</strong><br> <a href="https://stackoverflow.com/questions/2023977/c-difference-of-keywords-typename-and-class-in-templates">C++ difference of keywords ‘typename’ and ‘class’ in templates</a> </p> </blockquote> <p>When defining a function template or class template in C++, one can write this:</p> <pre><code>template &lt;class T&gt; ... </code></pre> <p>or one can write this:</p> <pre><code>template &lt;typename T&gt; ... </code></pre> <p>Is there a good reason to prefer one over the other?</p> <hr> <p>I accepted the most popular (and interesting) answer, but the real answer seems to be "No, there is no good reason to prefer one over the other."</p> <ul> <li>They are equivalent (except as noted below).</li> <li>Some people have reasons to always use <code>typename</code>.</li> <li>Some people have reasons to always use <code>class</code>.</li> <li>Some people have reasons to use both.</li> <li>Some people don't care which one they use.</li> </ul> <p>Note, however, that before C++17 in the case of <em>template template</em> parameters, use of <code>class</code> instead of <code>typename</code> was required. See <a href="https://stackoverflow.com/a/11311432/3964522">user1428839's answer</a> below. (But this particular case is not a matter of preference, it was a requirement of the language.)</p>
[ { "answer_id": 213133, "author": "Grant Limberg", "author_id": 27314, "author_profile": "https://Stackoverflow.com/users/27314", "pm_score": 1, "selected": false, "text": "<p>As far as I know, it doesn't matter which one you use. They're equivalent in the eyes of the compiler. Use whichever one you prefer. I normally use class.</p>\n" }, { "answer_id": 213135, "author": "itsmatt", "author_id": 7862, "author_profile": "https://Stackoverflow.com/users/7862", "pm_score": 10, "selected": true, "text": "<p>Stan Lippman talked about this <a href=\"https://learn.microsoft.com/archive/blogs/slippman/why-c-supports-both-class-and-typename-for-type-parameters\" rel=\"noreferrer\">here</a>. I thought it was interesting.</p>\n\n<p><em>Summary</em>: Stroustrup originally used <code>class</code> to specify types in templates to avoid introducing a new keyword. Some in the committee worried that this overloading of the keyword led to confusion. Later, the committee introduced a new keyword <code>typename</code> to resolve syntactic ambiguity, and decided to let it also be used to specify template types to reduce confusion, but for backward compatibility, <code>class</code> kept its overloaded meaning.</p>\n" }, { "answer_id": 213146, "author": "DarenW", "author_id": 10468, "author_profile": "https://Stackoverflow.com/users/10468", "pm_score": 8, "selected": false, "text": "<p>According to Scott Myers, Effective C++ (3rd ed.) item 42 (which must, of course, be the ultimate answer) - the difference is \"nothing\". </p>\n\n<p>Advice is to use \"class\" if it is expected T will always be a class, with \"typename\" if other types (int, char* whatever) may be expected. Consider it a usage hint.</p>\n" }, { "answer_id": 213149, "author": "Michael Burr", "author_id": 12711, "author_profile": "https://Stackoverflow.com/users/12711", "pm_score": 6, "selected": false, "text": "<p>I prefer to use typename because I'm not a fan of overloaded keywords (jeez - how many different meanings does <code>static</code> have for various different contexts?).</p>\n" }, { "answer_id": 213534, "author": "Frederik Slijkerman", "author_id": 12416, "author_profile": "https://Stackoverflow.com/users/12416", "pm_score": 3, "selected": false, "text": "<p>It doesn't matter at all, but class makes it look like T can only be a class, while it can of course be any type. So typename is more accurate. On the other hand, most people use class, so that is probably easier to read generally.</p>\n" }, { "answer_id": 213708, "author": "Aaron", "author_id": 14153, "author_profile": "https://Stackoverflow.com/users/14153", "pm_score": 3, "selected": false, "text": "<p>In response to <a href=\"https://stackoverflow.com/questions/213121/c-use-class-or-typename-for-template-parameters#213149\">Mike B</a>, I prefer to use 'class' as, within a template, 'typename' has an overloaded meaning, but 'class' does not. Take this checked integer type example:</p>\n\n<pre><code>template &lt;class IntegerType&gt;\nclass smart_integer {\npublic: \n typedef integer_traits&lt;Integer&gt; traits;\n IntegerType operator+=(IntegerType value){\n typedef typename traits::larger_integer_t larger_t;\n larger_t interm = larger_t(myValue) + larger_t(value); \n if(interm &gt; traits::max() || interm &lt; traits::min())\n throw overflow();\n myValue = IntegerType(interm);\n }\n}\n</code></pre>\n\n<p><code>larger_integer_t</code> is a dependent name, so it requires 'typename' to preceed it so that the parser can recognize that <code>larger_integer_t</code> is a type. <strong>class</strong>, on the otherhand, has no such overloaded meaning.</p>\n\n<p>That... or I'm just lazy at heart. I type 'class' far more often than 'typename', and thus find it much easier to type. Or it could be a sign that I write too much OO code.</p>\n" }, { "answer_id": 1637011, "author": "muenalan", "author_id": 92155, "author_profile": "https://Stackoverflow.com/users/92155", "pm_score": -1, "selected": false, "text": "<p>Extending DarenW's comment.</p>\n\n<p>Once typename and class are not accepted to be very different, it might be still valid to be strict on their use. Use class only if is really a class, and typename when its a basic type, such as <strong>char</strong>.</p>\n\n<p>These types are indeed also accepted instead of <strong>typename</strong></p>\n\n<blockquote>\n <p>template&lt; <strong>char</strong> <em>myc</em> = '/' ></p>\n</blockquote>\n\n<p>which would be in this case even superior to typename or class. </p>\n\n<p>Think of \"hintfullness\" or intelligibility to other people. And actually consider that 3rd party software/scripts might try to use the code/information to guess what is happening with the template (consider swig).</p>\n" }, { "answer_id": 2558958, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 3, "selected": false, "text": "<p>Just pure history. <a href=\"https://learn.microsoft.com/en-us/archive/blogs/slippman/why-c-supports-both-class-and-typename-for-type-parameters\" rel=\"nofollow noreferrer\">Quote from Stan Lippman</a>:</p>\n<blockquote>\n<p>The reason for the two keywords is historical. In the original template specification, Stroustrup reused the existing class keyword to specify a type parameter rather than introduce a new keyword that might of course break existing programs. It wasn't that a new keyword wasn't considered -- just that it wasn't considered necessary given its potential disruption. And up until the ISO-C++ standard, this was the only way to declare a type parameter.</p>\n</blockquote>\n<p>But one should use <strong>typename</strong> rather than <strong>class</strong>!\nSee the link for more info, but think about the following code:</p>\n<pre><code>template &lt;class T&gt;\nclass Demonstration { \npublic:\nvoid method() {\n T::A *aObj; // oops ...\n};\n</code></pre>\n" }, { "answer_id": 11311432, "author": "JorenHeit", "author_id": 1428839, "author_profile": "https://Stackoverflow.com/users/1428839", "pm_score": 7, "selected": false, "text": "<p>As an addition to all above posts, the use of the <code>class</code> keyword <i>is</i> forced (up to and including C++14) when dealing with <i>template template</i> parameters, e.g.:</p>\n\n<pre><code>template &lt;template &lt;typename, typename&gt; class Container, typename Type&gt;\nclass MyContainer: public Container&lt;Type, std::allocator&lt;Type&gt;&gt;\n{ /*...*/ };\n</code></pre>\n\n<p>In this example, <code>typename Container</code> would have generated a compiler error, something like this:</p>\n\n<pre><code>error: expected 'class' before 'Container'\n</code></pre>\n" }, { "answer_id": 11616000, "author": "user541686", "author_id": 541686, "author_profile": "https://Stackoverflow.com/users/541686", "pm_score": 4, "selected": false, "text": "<h3>There <em>is</em> a difference, and you should prefer <code>class</code> to <code>typename</code>.</h3>\n<h3>But why?</h3>\n<p><code>typename</code> is illegal for template template arguments, so to be consistent, you should use <code>class</code>:</p>\n<pre><code>template&lt;template&lt;class&gt; typename MyTemplate, class Bar&gt; class Foo { }; // :(\ntemplate&lt;template&lt;class&gt; class MyTemplate, class Bar&gt; class Foo { }; // :)\n</code></pre>\n" } ]
2008/10/17
[ "https://Stackoverflow.com/questions/213121", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1175/" ]
> > **Possible Duplicate:** > > [C++ difference of keywords ‘typename’ and ‘class’ in templates](https://stackoverflow.com/questions/2023977/c-difference-of-keywords-typename-and-class-in-templates) > > > When defining a function template or class template in C++, one can write this: ``` template <class T> ... ``` or one can write this: ``` template <typename T> ... ``` Is there a good reason to prefer one over the other? --- I accepted the most popular (and interesting) answer, but the real answer seems to be "No, there is no good reason to prefer one over the other." * They are equivalent (except as noted below). * Some people have reasons to always use `typename`. * Some people have reasons to always use `class`. * Some people have reasons to use both. * Some people don't care which one they use. Note, however, that before C++17 in the case of *template template* parameters, use of `class` instead of `typename` was required. See [user1428839's answer](https://stackoverflow.com/a/11311432/3964522) below. (But this particular case is not a matter of preference, it was a requirement of the language.)
Stan Lippman talked about this [here](https://learn.microsoft.com/archive/blogs/slippman/why-c-supports-both-class-and-typename-for-type-parameters). I thought it was interesting. *Summary*: Stroustrup originally used `class` to specify types in templates to avoid introducing a new keyword. Some in the committee worried that this overloading of the keyword led to confusion. Later, the committee introduced a new keyword `typename` to resolve syntactic ambiguity, and decided to let it also be used to specify template types to reduce confusion, but for backward compatibility, `class` kept its overloaded meaning.
213,128
<p>We're running into issues with how we specify font sizes. If we specify the font sizes using pt, they don't always look the same across browsers/platforms. If we specify font sizes using px, IE6 users can't resize the text.</p>
[ { "answer_id": 213137, "author": "John Topley", "author_id": 1450, "author_profile": "https://Stackoverflow.com/users/1450", "pm_score": 1, "selected": false, "text": "<p>You should always use relative units for font sizes, such as em.</p>\n" }, { "answer_id": 213141, "author": "eyelidlessness", "author_id": 17964, "author_profile": "https://Stackoverflow.com/users/17964", "pm_score": 1, "selected": false, "text": "<p><a href=\"http://developer.yahoo.com/yui/fonts/#fontsize\" rel=\"nofollow noreferrer\">http://developer.yahoo.com/yui/fonts/#fontsize</a> (edit: I believe this assumes their base CSS, but it is assuming a base size of 13px; I believe even IE properly resizes percent-sized text where the percents are measured against a px size.)</p>\n\n<p>That said, you are never going to get pixel-perfect font sizing, <strong>especially</strong> if you are trying to match a graphical mockup, but even just browser to browser, things will differ in text rendering.</p>\n" }, { "answer_id": 213407, "author": "Nathan Long", "author_id": 4376, "author_profile": "https://Stackoverflow.com/users/4376", "pm_score": 3, "selected": true, "text": "<p><a href=\"http://www.alistapart.com/articles/howtosizetextincss/\" rel=\"nofollow noreferrer\">An article on A List Apart</a> (November 2007) explored this in depth in various browsers and concluded:</p>\n\n<blockquote>\n <p>Sizing text and line-height in ems, with a percentage specified on the body (and an optional caveat for Safari 2), was shown to provide accurate, resizable text across all browsers in common use today. This is a technique you can put in your kit bag and use as a best practice for sizing text in CSS that satisfies both designers and readers.</p>\n</blockquote>\n\n<p>They provided <a href=\"http://www.alistapart.com/d/howtosizetextincss/ss-test-6.html\" rel=\"nofollow noreferrer\">screen shots</a> of how this technique looks in most popular browsers. Here is the code they used:</p>\n\n<pre><code>&lt;style type=\"text/css\"&gt;`\nbody {\n font-size:100%;\n line-height:1.125em;\n}\n\n.bodytext p {\n font-size:0.875em;\n}\n\n.sidenote {\n font-size:0.75em;\n}\n&lt;/style&gt;\n\n&lt;!--[if !IE]&gt;--&gt;\n\n&lt;style type=\"text/css\"&gt;\nbody {\n font-size:16px;\n}\n&lt;/style&gt;\n\n&lt;!--&lt;[endif]--&gt;\n</code></pre>\n" }, { "answer_id": 214097, "author": "Jethro Larson", "author_id": 22425, "author_profile": "https://Stackoverflow.com/users/22425", "pm_score": 1, "selected": false, "text": "<p>You're always going to have trouble matching mockups unless you use px. \n<a href=\"http://www.456bereastreet.com/archive/200602/setting_font_size_in_pixels/\" rel=\"nofollow noreferrer\">http://www.456bereastreet.com/archive/200602/setting_font_size_in_pixels/</a><br>\nI don't feel there's anything particularly wrong with using px for your web pages. Especially since almost all the modern browsers--save for webkit--use zooming as opposed to text-resizing by default. </p>\n\n<p>I still might stick to what Nathan suggests as it allows you more design agility, as you can quickly scale the whole site's font sizes by changing only one of them. But if you're lazy or want it really spot-on, then you don't have to be afraid of px. </p>\n" }, { "answer_id": 214768, "author": "cowgod", "author_id": 6406, "author_profile": "https://Stackoverflow.com/users/6406", "pm_score": 2, "selected": false, "text": "<p>contrary to what others have answered, you should never ever use pixels for font sizes. internet explorer 6 still has a large piece of the browser market pie and it absolutely will not resize text that is specified with a pixel size (as mentioned in the question). you should always strive to use \"em\"s.</p>\n\n<p>i use a technique similar to what others have suggested here whereby i \"reset\" the css styles across the board to remove any browser inconsistencies with font sizing and positioning. i like <a href=\"http://meyerweb.com/eric/thoughts/2007/05/01/reset-reloaded/\" rel=\"nofollow noreferrer\">eric meyer's reset reloaded</a> styles as a base. you could also use the <a href=\"http://developer.yahoo.com/yui/reset/\" rel=\"nofollow noreferrer\">yahoo reset css</a> method if you wanted to dig into that whole library.</p>\n\n<p>next, i use <a href=\"http://www.thenoodleincident.com/tutorials/typography/\" rel=\"nofollow noreferrer\">owen briggs' sane css typography template</a>. you may notice that it hasn't been updated since 2003 but is still absolutely solid with today's browsers.</p>\n\n<p>once you get this base, it's a simple matter of changing the font percentage on the <code>&lt;body&gt;</code> tag that will easily scale all the fonts across your website in the same manner.</p>\n\n<p>for the impatient, here's eric meyer's reset css and owen briggs' typography css mashed together (parsed through <a href=\"http://floele.flyspray.org/csstidy//css_optimiser.php\" rel=\"nofollow noreferrer\">this excellent css formatter</a>):</p>\n\n<pre><code>html,body,div,span,applet,object,iframe,h1,h2,h3,h4,h5,h6,p,blockquote,pre,a,abbr,acronym,address,big,cite,code,del,dfn,em,font,img,ins,kbd,q,s,samp,small,strike,strong,sub,sup,tt,var,dl,dt,dd,ol,ul,li,fieldset,form,label,legend,table,caption,tbody,tfoot,thead,tr,th,td{border:0;outline:0;font-weight:inherit;font-style:inherit;font-size:100%;font-family:inherit;vertical-align:baseline;margin:0;padding:0;}\n:focus{outline:0;}\nbody{line-height:1;font-family:verdana, arial, helvetica, sans-serif;font-size:76%;}\nol,ul{list-style:none;}\ntable{border-collapse:separate;border-spacing:0;}\ncaption,th,td{text-align:left;font-weight:400;}\nblockquote:before,blockquote:after,q:before,q:after{content:\"\";}\nblockquote,q{quotes:\"\" \"\";}\na{text-decoration:none;font-weight:700;color:#000;}\na:hover{text-decoration:underline;}\nh1{font-size:2em;font-weight:400;margin-top:0;margin-bottom:0;}\nh2{font-size:1.7em;font-weight:400;margin:1.2em 0;}\nh3{font-size:1.4em;font-weight:400;margin:1.2em 0;}\nh4{font-size:1.2em;font-weight:700;margin:1.2em 0;}\nh5{font-size:1em;font-weight:700;margin:1.2em 0;}\nh6{font-size:.8em;font-weight:700;margin:1.2em 0;}\nimg{border:0;}\nol,ul,li{font-size:1em;line-height:1.8em;margin-top:.2em;margin-bottom:.1em;}\np{font-size:1em;line-height:1.8em;margin:1.2em 0;}\nli &gt; p{margin-top:.2em;}\npre{font-family:monospace;font-size:1em;}\nstrong,b{font-weight:700;}\n</code></pre>\n" } ]
2008/10/17
[ "https://Stackoverflow.com/questions/213128", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1538/" ]
We're running into issues with how we specify font sizes. If we specify the font sizes using pt, they don't always look the same across browsers/platforms. If we specify font sizes using px, IE6 users can't resize the text.
[An article on A List Apart](http://www.alistapart.com/articles/howtosizetextincss/) (November 2007) explored this in depth in various browsers and concluded: > > Sizing text and line-height in ems, with a percentage specified on the body (and an optional caveat for Safari 2), was shown to provide accurate, resizable text across all browsers in common use today. This is a technique you can put in your kit bag and use as a best practice for sizing text in CSS that satisfies both designers and readers. > > > They provided [screen shots](http://www.alistapart.com/d/howtosizetextincss/ss-test-6.html) of how this technique looks in most popular browsers. Here is the code they used: ``` <style type="text/css">` body { font-size:100%; line-height:1.125em; } .bodytext p { font-size:0.875em; } .sidenote { font-size:0.75em; } </style> <!--[if !IE]>--> <style type="text/css"> body { font-size:16px; } </style> <!--<[endif]--> ```
213,148
<p>Can anyone tell the function to sort the columns of a gridview in c# asp.net.</p> <p>The databound to gridview is from datacontext created using linq. I wanted to click the header of the column to sort the data.</p> <p>Thanks!</p>
[ { "answer_id": 213154, "author": "Kon", "author_id": 22303, "author_profile": "https://Stackoverflow.com/users/22303", "pm_score": 2, "selected": false, "text": "<p><a href=\"http://msdn.microsoft.com/en-us/library/ms745786.aspx\" rel=\"nofollow noreferrer\">http://msdn.microsoft.com/en-us/library/ms745786.aspx</a></p>\n\n<p><a href=\"https://web.archive.org/web/20210612115758/https://aspnet.4guysfromrolla.com/articles/012308-1.aspx\" rel=\"nofollow noreferrer\">https://web.archive.org/web/20210612115758/https://aspnet.4guysfromrolla.com/articles/012308-1.aspx</a></p>\n" }, { "answer_id": 213158, "author": "Jeremy B.", "author_id": 28567, "author_profile": "https://Stackoverflow.com/users/28567", "pm_score": 0, "selected": false, "text": "<p>more information on sorting in a gridview can be found here: <a href=\"http://msdn.microsoft.com/en-us/library/hwf94875.aspx\" rel=\"nofollow noreferrer\">MSDN Gridview sorting</a> the methodology used to get the data should not matter, you can use the same sorting.</p>\n" }, { "answer_id": 213306, "author": "craigmoliver", "author_id": 12252, "author_profile": "https://Stackoverflow.com/users/12252", "pm_score": 0, "selected": false, "text": "<p>add:</p>\n\n<pre><code> AllowSorting=\"true\"\n</code></pre>\n\n<p>to the <code>&lt;asp:GridView /&gt;</code> tag, that should do it</p>\n" }, { "answer_id": 213541, "author": "Daniel Schaffer", "author_id": 2596, "author_profile": "https://Stackoverflow.com/users/2596", "pm_score": 0, "selected": false, "text": "<blockquote>\n <p>When I do that Alone it gives an error\n \"The GridView 'GridView1' fired event\n Sorting which wasn't handled.</p>\n</blockquote>\n\n<p>I've had that happen before... I've just created a throwaway handler, and then everything seemed to start working after that. Not the prettiest solution, but it worked for me.</p>\n\n<p>That said, I didn't see any reference to a data source in your GridView code. You'll need something like this:</p>\n\n<pre><code>&lt;asp:LinqDataSource ID=\"dsMyDataSource\" runat=\"server\"\nDataContextTypeName=\"MyDataContext\"\nTableName=\"MyTable\"\nAllowSort=\"true\" /&gt;\n</code></pre>\n\n<p>And then in your GridView:</p>\n\n<pre><code>&lt;asp:GridView ID=\"gvMyGridView\" runat=\"server\" DataSourceID=\"dsMyDataSource\" ... /&gt;\n</code></pre>\n" }, { "answer_id": 229560, "author": "Georg", "author_id": 30776, "author_profile": "https://Stackoverflow.com/users/30776", "pm_score": 0, "selected": false, "text": "<p>In the Properties Panel double Click on the Sorting Entry. \nA new Function will be created. \nIn this Function write the Code to fill the Gridview. \nThe only difference is to change the query based on GridViewSortEventArgs e</p>\n\n<p>e.SortExpression \nand<br>\ne.SortDirection allways Ascending :-( </p>\n\n<p>I hope this very short Answer helps</p>\n" }, { "answer_id": 233569, "author": "Georg", "author_id": 30776, "author_profile": "https://Stackoverflow.com/users/30776", "pm_score": 0, "selected": false, "text": "<p>In Half Pseudocode for SQL Query</p>\n\n<pre><code>string Query= string.Empty;\nstring SortExpression = string.Empty;\n\n// HDFSort is an HiddenField !!!\n\nprotected void SortCommand_OnClick(object sender, GridViewSortEventArgs e)\n{\n SortExpression = e.SortExpression; \n Query = YourQuery + \" ORDER BY \"+SortExpression +\" \"+ HDFSort.Value ;\n HDFSort.Value = HDFSort.Value== \"ASC\" ? \"DESC\" : \"ASC\";\n RefreshGridView();\n}\n\nprotected void RefreshGridView()\n{\n GridView1.DataSource = DBObject.GetData(Query);\n GridView1.DataBind();\n}\n</code></pre>\n" }, { "answer_id": 357276, "author": "davidfowl", "author_id": 45091, "author_profile": "https://Stackoverflow.com/users/45091", "pm_score": 3, "selected": false, "text": "<p>There are 2 things you need to do to get this right.</p>\n\n<ol>\n<li>Keep the sorting state is viewstate(SortDirection and SortExpression)</li>\n<li>You generate the correct linq expression based on the current sorting state.</li>\n</ol>\n\n<p>Manually handle the <strong>Sorting</strong> event in the grid and use this helper I wrote to sort by SortExpression and SortDirection:</p>\n\n<pre><code>public static IQueryable&lt;T&gt; SortBy&lt;T&gt;(IQueryable&lt;T&gt; source, string sortExpression, SortDirection direction) {\n if (source == null) {\n throw new ArgumentNullException(\"source\");\n }\n\n string methodName = \"OrderBy\";\n if (direction == SortDirection.Descending) {\n methodName += \"Descending\";\n }\n\n var paramExp = Expression.Parameter(typeof(T), String.Empty);\n var propExp = Expression.PropertyOrField(paramExp, sortExpression);\n\n // p =&gt; p.sortExpression\n var sortLambda = Expression.Lambda(propExp, paramExp);\n\n var methodCallExp = Expression.Call(\n typeof(Queryable),\n methodName,\n new[] { typeof(T), propExp.Type },\n source.Expression,\n Expression.Quote(sortLambda)\n );\n\n return (IQueryable&lt;T&gt;)source.Provider.CreateQuery(methodCallExp);\n}\n</code></pre>\n\n<p>db.Products.SortBy(e.SortExpression, e.SortDirection)</p>\n\n<p>Check out <a href=\"http://weblogs.asp.net/davidfowler/archive/2008/10/21/datacontrols-101-part-2-why-you-should-love-datasource-controls.aspx\" rel=\"noreferrer\">my blog post </a> on how to do this:</p>\n" } ]
2008/10/17
[ "https://Stackoverflow.com/questions/213148", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
Can anyone tell the function to sort the columns of a gridview in c# asp.net. The databound to gridview is from datacontext created using linq. I wanted to click the header of the column to sort the data. Thanks!
There are 2 things you need to do to get this right. 1. Keep the sorting state is viewstate(SortDirection and SortExpression) 2. You generate the correct linq expression based on the current sorting state. Manually handle the **Sorting** event in the grid and use this helper I wrote to sort by SortExpression and SortDirection: ``` public static IQueryable<T> SortBy<T>(IQueryable<T> source, string sortExpression, SortDirection direction) { if (source == null) { throw new ArgumentNullException("source"); } string methodName = "OrderBy"; if (direction == SortDirection.Descending) { methodName += "Descending"; } var paramExp = Expression.Parameter(typeof(T), String.Empty); var propExp = Expression.PropertyOrField(paramExp, sortExpression); // p => p.sortExpression var sortLambda = Expression.Lambda(propExp, paramExp); var methodCallExp = Expression.Call( typeof(Queryable), methodName, new[] { typeof(T), propExp.Type }, source.Expression, Expression.Quote(sortLambda) ); return (IQueryable<T>)source.Provider.CreateQuery(methodCallExp); } ``` db.Products.SortBy(e.SortExpression, e.SortDirection) Check out [my blog post](http://weblogs.asp.net/davidfowler/archive/2008/10/21/datacontrols-101-part-2-why-you-should-love-datasource-controls.aspx) on how to do this:
213,151
<p>EDIT: It seems to be something with having the two queues in the same schema.</p> <p>I’m trying to experiment with queue propagation but I’m not seeing records in the destination queue. But that could easily be because I don’t have all the pieces in place.</p> <p>Does anyone have a test case they could post? I’ll include what I tried below. I found the troubleshooting in the docs a little light and the propagation is such a black box, it’s hard to know why this isn’t moving.</p> <p>Here’s what I have; no laughing.</p> <hr> <pre><code>CREATE OR REPLACE TYPE test_payload AS OBJECT( test_id NUMBER, test_dt DATE); DECLARE subscriber SYS.aq$_agent; BEGIN --- Create Originating Queue and start it DBMS_AQADM.create_queue_table( queue_table =&gt; 'Test_MQT', queue_payload_type =&gt; 'Test_Payload', multiple_consumers =&gt; TRUE ); --- multiple subscriber DBMS_AQADM.create_queue( 'Test_Q', 'Test_MQT' ); DBMS_AQADM.start_queue( queue_name =&gt; 'Test_Q' ); --- Create Destination Queue and start it DBMS_AQADM.create_queue_table( queue_table =&gt; 'Dest_MQT', queue_payload_type =&gt; 'Test_Payload', multiple_consumers =&gt; TRUE ); DBMS_AQADM.create_queue( 'Dest_Q', 'Dest_MQT' ); DBMS_AQADM.start_queue( queue_name =&gt; 'Dest_Q' ); --- Add Subscriber and schedule propagation subscriber := SYS.aq$_agent( 'test_local_sub', 'Dest_Q', NULL ); DBMS_AQADM.add_subscriber( queue_name =&gt; 'Test_Q', subscriber =&gt; subscriber ); DBMS_AQADM.schedule_propagation( queue_name =&gt; 'Test_Q', destination_queue =&gt; 'Dest_Q' ); END; DECLARE enqueue_options DBMS_AQ.enqueue_options_t; message_properties DBMS_AQ.message_properties_t; message_handle RAW( 16 ); MESSAGE test_payload; BEGIN MESSAGE := test_payload( 2, SYSDATE ); DBMS_AQ.enqueue( queue_name =&gt; 'Test_Q', enqueue_options =&gt; enqueue_options, message_properties =&gt; message_properties, payload =&gt; MESSAGE, msgid =&gt; message_handle ); COMMIT; END; DECLARE dequeue_options DBMS_AQ.dequeue_options_t; message_properties DBMS_AQ.message_properties_t; message_handle RAW( 16 ); MESSAGE test_payload; BEGIN dequeue_options.navigation := DBMS_AQ.first_message; DBMS_AQ.dequeue( queue_name =&gt; 'Dest_Q', dequeue_options =&gt; dequeue_options, message_properties =&gt; message_properties, payload =&gt; MESSAGE, msgid =&gt; message_handle ); DBMS_OUTPUT.put_line( 'Test_ID: ' || MESSAGE.test_id ); DBMS_OUTPUT.put_line( 'Test_Date: ' || MESSAGE.test_dt ); COMMIT; END; </code></pre>
[ { "answer_id": 215092, "author": "TheSoftwareJedi", "author_id": 18941, "author_profile": "https://Stackoverflow.com/users/18941", "pm_score": 1, "selected": false, "text": "<p>Perhaps you need to enable it?</p>\n\n<pre><code>DBMS_AQADM.ENABLE_PROPAGATION_SCHEDULE(queue_name =&gt; 'Test_Q'); \n</code></pre>\n" }, { "answer_id": 217404, "author": "Brian", "author_id": 700, "author_profile": "https://Stackoverflow.com/users/700", "pm_score": 0, "selected": false, "text": "<p>You might want to read thru this Tom Kyte thread on AQ:</p>\n\n<p><a href=\"http://asktom.oracle.com/pls/asktom/f?p=100:11:0::::P11_QUESTION_ID:8760267539329#tom1246632800346467977\" rel=\"nofollow noreferrer\">http://asktom.oracle.com/pls/asktom/f?p=100:11:0::::P11_QUESTION_ID:8760267539329#tom1246632800346467977</a></p>\n" }, { "answer_id": 250923, "author": "ScottCher", "author_id": 24179, "author_profile": "https://Stackoverflow.com/users/24179", "pm_score": 1, "selected": true, "text": "<p>You Need to have a default subscriber to the destination queue of the propagation. Something needs to be there to listen</p>\n" } ]
2008/10/17
[ "https://Stackoverflow.com/questions/213151", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
EDIT: It seems to be something with having the two queues in the same schema. I’m trying to experiment with queue propagation but I’m not seeing records in the destination queue. But that could easily be because I don’t have all the pieces in place. Does anyone have a test case they could post? I’ll include what I tried below. I found the troubleshooting in the docs a little light and the propagation is such a black box, it’s hard to know why this isn’t moving. Here’s what I have; no laughing. --- ``` CREATE OR REPLACE TYPE test_payload AS OBJECT( test_id NUMBER, test_dt DATE); DECLARE subscriber SYS.aq$_agent; BEGIN --- Create Originating Queue and start it DBMS_AQADM.create_queue_table( queue_table => 'Test_MQT', queue_payload_type => 'Test_Payload', multiple_consumers => TRUE ); --- multiple subscriber DBMS_AQADM.create_queue( 'Test_Q', 'Test_MQT' ); DBMS_AQADM.start_queue( queue_name => 'Test_Q' ); --- Create Destination Queue and start it DBMS_AQADM.create_queue_table( queue_table => 'Dest_MQT', queue_payload_type => 'Test_Payload', multiple_consumers => TRUE ); DBMS_AQADM.create_queue( 'Dest_Q', 'Dest_MQT' ); DBMS_AQADM.start_queue( queue_name => 'Dest_Q' ); --- Add Subscriber and schedule propagation subscriber := SYS.aq$_agent( 'test_local_sub', 'Dest_Q', NULL ); DBMS_AQADM.add_subscriber( queue_name => 'Test_Q', subscriber => subscriber ); DBMS_AQADM.schedule_propagation( queue_name => 'Test_Q', destination_queue => 'Dest_Q' ); END; DECLARE enqueue_options DBMS_AQ.enqueue_options_t; message_properties DBMS_AQ.message_properties_t; message_handle RAW( 16 ); MESSAGE test_payload; BEGIN MESSAGE := test_payload( 2, SYSDATE ); DBMS_AQ.enqueue( queue_name => 'Test_Q', enqueue_options => enqueue_options, message_properties => message_properties, payload => MESSAGE, msgid => message_handle ); COMMIT; END; DECLARE dequeue_options DBMS_AQ.dequeue_options_t; message_properties DBMS_AQ.message_properties_t; message_handle RAW( 16 ); MESSAGE test_payload; BEGIN dequeue_options.navigation := DBMS_AQ.first_message; DBMS_AQ.dequeue( queue_name => 'Dest_Q', dequeue_options => dequeue_options, message_properties => message_properties, payload => MESSAGE, msgid => message_handle ); DBMS_OUTPUT.put_line( 'Test_ID: ' || MESSAGE.test_id ); DBMS_OUTPUT.put_line( 'Test_Date: ' || MESSAGE.test_dt ); COMMIT; END; ```
You Need to have a default subscriber to the destination queue of the propagation. Something needs to be there to listen
213,167
<p>I'm looking at the code for a phase accumulator, and I must be a simpleton because I don't get it. The code is simple enough:</p> <pre> Every Clock Tick do: accum = accum + NCO_param; return accum; </pre> <p>accum is a 32-bit register. Obviously, at some point it will roll-over.</p> <p>My question really is: How does this relate to the phase?</p>
[ { "answer_id": 213372, "author": "Eli Bendersky", "author_id": 8206, "author_profile": "https://Stackoverflow.com/users/8206", "pm_score": 3, "selected": true, "text": "<p><a href=\"http://en.wikipedia.org/wiki/Direct_digital_synthesis\" rel=\"nofollow noreferrer\">This article</a> may help. </p>\n\n<p>In the running step, the counter (properly called the phase accumulator) is instructed to advance by a certain increment on each pulse from the frequency reference. The output of the phase accumulator (the phase) is used to select each item in the data table in turn. Finally, the DAC converts this sequence of data to an analogue waveform.</p>\n\n<blockquote>\n <p>In the running step, the counter\n (properly called the phase\n accumulator) is instructed to advance\n by a certain increment on each pulse\n from the frequency reference. The\n output of the phase accumulator (the\n phase) is used to select each item in\n the data table in turn. Finally, the\n DAC converts this sequence of data to\n an analogue waveform.\n To generate a periodic waveform, the\n circuit is set up so that one pass\n through the table takes a time equal\n to the period of the waveform. For\n example, if the reference frequency is\n 1 MHz, and the table contains 1000\n entries, then a complete pass through\n the table with a phase increment of 1\n will take 1000 / 1 MHz = 1 ms, so the\n frequency of the output waveform will\n be 1/(1 ms) = 1 kHz.</p>\n \n <p>This system can generate a higher\n output frequency simply by increasing\n the phase increment so that the\n counter runs through the table more\n quickly. In the example above, the\n phase increment is equal to 1, so the\n next possible frequency is obtained by\n setting the increment to 2, resulting\n in a doubling of output frequency. To\n obtain a finer control of frequency\n than this, the standard phase\n increment can be set to, say, 10. This\n then allows slightly higher or lower\n output frequencies. For example,\n increasing the increment to 11 would\n increase the output frequency by 10%,\n and reducing it to 9 would decrease\n the output frequency by the same\n proportion. The more precision\n required over the frequency, the more\n bits are needed in the counter.</p>\n</blockquote>\n" }, { "answer_id": 214472, "author": "Benoit", "author_id": 10703, "author_profile": "https://Stackoverflow.com/users/10703", "pm_score": 2, "selected": false, "text": "<p>Answering my own question, I found another interesting article <a href=\"http://www.automotivedesignline.com/showArticle.jhtml?articleID=205921175\" rel=\"nofollow noreferrer\">online</a> describing a phase accumulator for frequency synthesis.</p>\n\n<p>Here is my understanding of how the phase accumulator works:<br>\nThe accumulator register actually represents 360 degrees. Thus, a value of 0 represents 0 degree, a value of 2^32 represents 360 degrees.</p>\n\n<p>The phase accumulator adds a value (M) every clock tick. This represents the angle moving around the circle by (M/2^32) degrees. When the register overflows, we simply cycled through a full 360 degree and start over.</p>\n" }, { "answer_id": 27747391, "author": "LifeInTheTrees", "author_id": 2040877, "author_profile": "https://Stackoverflow.com/users/2040877", "pm_score": 0, "selected": false, "text": "<p>The formula is this: </p>\n\n<p>Example using oscillors that have a period of waveform(x) period = x(0-1) rather than x(0-2Pi)</p>\n\n<p>One variable per audio stream called acc/accumulator,</p>\n\n<p>Every sample, accumulate it by accadd:</p>\n\n<pre><code> var accadd = 1.0/( sampleRate / p2freq( note ) ) ;\n acc+= accadd;\n acc = acc%1.0;// not sure to do this as accurately using if statement. can reset acc every noteOn\n</code></pre>\n\n<p>If you are using classical Sin with 2pi period, use 2pi instead of 1.0</p>\n\n<p>Like that the waveform will run from 0-1 at p2freq(note) periods per second.</p>\n" } ]
2008/10/17
[ "https://Stackoverflow.com/questions/213167", "https://Stackoverflow.com", "https://Stackoverflow.com/users/10703/" ]
I'm looking at the code for a phase accumulator, and I must be a simpleton because I don't get it. The code is simple enough: ``` Every Clock Tick do: accum = accum + NCO_param; return accum; ``` accum is a 32-bit register. Obviously, at some point it will roll-over. My question really is: How does this relate to the phase?
[This article](http://en.wikipedia.org/wiki/Direct_digital_synthesis) may help. In the running step, the counter (properly called the phase accumulator) is instructed to advance by a certain increment on each pulse from the frequency reference. The output of the phase accumulator (the phase) is used to select each item in the data table in turn. Finally, the DAC converts this sequence of data to an analogue waveform. > > In the running step, the counter > (properly called the phase > accumulator) is instructed to advance > by a certain increment on each pulse > from the frequency reference. The > output of the phase accumulator (the > phase) is used to select each item in > the data table in turn. Finally, the > DAC converts this sequence of data to > an analogue waveform. > To generate a periodic waveform, the > circuit is set up so that one pass > through the table takes a time equal > to the period of the waveform. For > example, if the reference frequency is > 1 MHz, and the table contains 1000 > entries, then a complete pass through > the table with a phase increment of 1 > will take 1000 / 1 MHz = 1 ms, so the > frequency of the output waveform will > be 1/(1 ms) = 1 kHz. > > > This system can generate a higher > output frequency simply by increasing > the phase increment so that the > counter runs through the table more > quickly. In the example above, the > phase increment is equal to 1, so the > next possible frequency is obtained by > setting the increment to 2, resulting > in a doubling of output frequency. To > obtain a finer control of frequency > than this, the standard phase > increment can be set to, say, 10. This > then allows slightly higher or lower > output frequencies. For example, > increasing the increment to 11 would > increase the output frequency by 10%, > and reducing it to 9 would decrease > the output frequency by the same > proportion. The more precision > required over the frequency, the more > bits are needed in the counter. > > >
213,173
<p>I have a single image with 9 different states and the appropriate background-position rules set up as classes to show the different states. I can't use the :hover pseudo-selector because the background image being changed is not the same element that is being hovered over. I have defined the classes this way:</p> <pre><code>#chooser_nav {width:580px; height:38px; background:transparent url(/assets/images/chooser-tabs.jpg) 0 0 no-repeat; margin-left:34px;} #chooser_nav.feat {background-position:0 0;} #chooser_nav.inv {background-position:0 -114px;} #chooser_nav.bts {background-position:0 -228px;} #chooser_nav.featinv {background-position:0 -38px;} #chooser_nav.featbts {background-position:0 -76px;} #chooser_nav.invfeat {background-position:0 -152px;} #chooser_nav.invbts {background-position:0 -190px;} #chooser_nav.btsfeat {background-position:0 -266px;} #chooser_nav.btsinv {background-position:0 -304px;} </code></pre> <p>Then, using jQuery, I have a series of hover rules based on a previous click event (the here-undeclared "cur" variable is properly declared elsewhere):</p> <pre><code> $("#featured_races a").hover(function(){ cur == "feat" ? $("#chooser_nav").attr("class", cur) : $("#chooser_nav").attr("class", cur+"feat"); }, function(){ $("#chooser_nav").attr("class", cur); }); $("#invitational_races a").hover(function(){ cur == "inv" ? $("#chooser_nav").attr("class", cur) : $("#chooser_nav").attr("class", cur+"inv"); }, function(){ $("#chooser_nav").attr("class", cur); }); $("#behind_the_scenes a").hover(function(){ cur == "bts" ? $("#chooser_nav").attr("class", cur) : $("#chooser_nav").attr("class", cur+"bts"); }, function(){ $("#chooser_nav").attr("class", cur); }); </code></pre> <p>So, in Moz and WebKit browsers, this works fine. The classes are applied and the background image changes accordingly. Works in IE7 as well. However, in IE6, the background image never changes. The classes get applied appropriately, I verified this with the DOM viewer in MS's web dev tool. So, the jQuery is working. The class is getting applied, but no change is visibly occurring.</p> <p>I'm kinda stumped here... Help me, Crackoverflow... you're my only hope...</p> <p>EDIT: As far as className vs. setAttribute... the class is changing. attr("class", cur) is working. However, once the class is changed, the resulting rules are not applied visually... but the change of class is occurring.</p> <p>EDIT 2: As for jQuery's class-specific methods: I originally had them in the code, and the result was the same. Again, the problem is not with the class not getting applied to the element... this has been verified to be happening. it's that once the class is on the element, for some reason, the element is not following the CSS rules set for that class...</p>
[ { "answer_id": 213213, "author": "Kornel", "author_id": 27009, "author_profile": "https://Stackoverflow.com/users/27009", "pm_score": 0, "selected": false, "text": "<p>Use <code>className</code> DOM property. <code>setAttribute()</code> is utterly broken in IE &lt; 8.</p>\n" }, { "answer_id": 215156, "author": "Borgar", "author_id": 27388, "author_profile": "https://Stackoverflow.com/users/27388", "pm_score": 2, "selected": false, "text": "<p>Guess one: Rendering bug 1</p>\n\n<p>Make sure that you have triggered hasLayout on the elements. You can do this by giving them a height or, if that isn't a posibility then position = relative &amp; z-index = 1, will also trigger hasLayout. Try it for these elements + suspect parent elements.</p>\n\n<pre><code>/* fix hasLayout bug for IE */\ndiv#id {\n _height : 0;\n min-height : 0;\n}\n</code></pre>\n\n<p>Guess two: Rendering bug 2</p>\n\n<p>Sometimes, it may be necessary to force more rendering calculation than what the browser has decided. You can give the DOM a good kick by touching the body class:</p>\n\n<pre><code>document.body.className += '';\n</code></pre>\n\n<p>Guess three: Selector problems</p>\n\n<p>IE6 doesn't support multiple class selectors, and maybe ID+Class except in some cases. </p>\n\n<pre><code>div.class1.class2 {\n border : 1px solid red; /* this will normally not work in IE6 */\n}\n</code></pre>\n\n<p>I don't have IE to test with at the moment and can't remember weather #id.class is supposed to work (I feel it should), but I generally avoid any such things for IE6. You may need to change your selectors.</p>\n\n<p>You'll need to set up a test to see if your selectors are working at all.</p>\n\n<p>Variations that might work:</p>\n\n<pre><code>.inv#chooser_nav { background-position : 0 -114px; }\n</code></pre>\n\n<p>Or you might need to single the element out by a parent:</p>\n\n<pre><code>#someparent .inv { background-position : 0 -114px; }\n</code></pre>\n\n<p>IE6 additionally has problems with hover, so that might also be a factor. </p>\n\n<p>Hope this helps. I'm sorry I can't be more definite, but getting past IE6's quirks is largely done with good old methods of trial and error, brute force, guessing, and a generous helping of patience.</p>\n" }, { "answer_id": 610620, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 0, "selected": false, "text": "<p>I ran into a similar problem; the class name was applied, the text colot changed as expected, however the background images did not immediately update. After I hovered over or out of the actual element the background was updated.</p>\n\n<p>It turned out to be a conflict with the DD_belatedPNG library.</p>\n" }, { "answer_id": 610648, "author": "Magnar", "author_id": 1123, "author_profile": "https://Stackoverflow.com/users/1123", "pm_score": 1, "selected": false, "text": "<p>IE6 has problems with the \"double\" css rules you are using.</p>\n\n<pre><code>#chooser_nav.bts {background-position:0 -228px;}\n</code></pre>\n\n<p>You are selecting an element with ID <code>chooser_nav</code> <em>and</em> class <code>bts</code>. This (very useful) construct just isn't reliable in IE6. If you can remove the ID-specifier, or target a parent element instead, that should fix your problem:</p>\n\n<pre><code>.bts {background-position:0 -228px;}\n</code></pre>\n\n<p>or</p>\n\n<pre><code>#chooser_nav_parent .bts {background-position:0 -228px;}\n</code></pre>\n" }, { "answer_id": 1458579, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 0, "selected": false, "text": "<p>I had this problem in ie7.</p>\n\n<p>basically i was changing a class on a parent element to hide some elements and show others.\nthe class changed and the element that was showing when the page was loaded was hiding and showing fine but the element that was not showing when the page was loaded never showed.</p>\n\n<p>i noticed this only happened in some scenarios (god only knows to predict it).</p>\n\n<p>my solution was to only hide the elements after the page was loaded with javascript.</p>\n" } ]
2008/10/17
[ "https://Stackoverflow.com/questions/213173", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9414/" ]
I have a single image with 9 different states and the appropriate background-position rules set up as classes to show the different states. I can't use the :hover pseudo-selector because the background image being changed is not the same element that is being hovered over. I have defined the classes this way: ``` #chooser_nav {width:580px; height:38px; background:transparent url(/assets/images/chooser-tabs.jpg) 0 0 no-repeat; margin-left:34px;} #chooser_nav.feat {background-position:0 0;} #chooser_nav.inv {background-position:0 -114px;} #chooser_nav.bts {background-position:0 -228px;} #chooser_nav.featinv {background-position:0 -38px;} #chooser_nav.featbts {background-position:0 -76px;} #chooser_nav.invfeat {background-position:0 -152px;} #chooser_nav.invbts {background-position:0 -190px;} #chooser_nav.btsfeat {background-position:0 -266px;} #chooser_nav.btsinv {background-position:0 -304px;} ``` Then, using jQuery, I have a series of hover rules based on a previous click event (the here-undeclared "cur" variable is properly declared elsewhere): ``` $("#featured_races a").hover(function(){ cur == "feat" ? $("#chooser_nav").attr("class", cur) : $("#chooser_nav").attr("class", cur+"feat"); }, function(){ $("#chooser_nav").attr("class", cur); }); $("#invitational_races a").hover(function(){ cur == "inv" ? $("#chooser_nav").attr("class", cur) : $("#chooser_nav").attr("class", cur+"inv"); }, function(){ $("#chooser_nav").attr("class", cur); }); $("#behind_the_scenes a").hover(function(){ cur == "bts" ? $("#chooser_nav").attr("class", cur) : $("#chooser_nav").attr("class", cur+"bts"); }, function(){ $("#chooser_nav").attr("class", cur); }); ``` So, in Moz and WebKit browsers, this works fine. The classes are applied and the background image changes accordingly. Works in IE7 as well. However, in IE6, the background image never changes. The classes get applied appropriately, I verified this with the DOM viewer in MS's web dev tool. So, the jQuery is working. The class is getting applied, but no change is visibly occurring. I'm kinda stumped here... Help me, Crackoverflow... you're my only hope... EDIT: As far as className vs. setAttribute... the class is changing. attr("class", cur) is working. However, once the class is changed, the resulting rules are not applied visually... but the change of class is occurring. EDIT 2: As for jQuery's class-specific methods: I originally had them in the code, and the result was the same. Again, the problem is not with the class not getting applied to the element... this has been verified to be happening. it's that once the class is on the element, for some reason, the element is not following the CSS rules set for that class...
Guess one: Rendering bug 1 Make sure that you have triggered hasLayout on the elements. You can do this by giving them a height or, if that isn't a posibility then position = relative & z-index = 1, will also trigger hasLayout. Try it for these elements + suspect parent elements. ``` /* fix hasLayout bug for IE */ div#id { _height : 0; min-height : 0; } ``` Guess two: Rendering bug 2 Sometimes, it may be necessary to force more rendering calculation than what the browser has decided. You can give the DOM a good kick by touching the body class: ``` document.body.className += ''; ``` Guess three: Selector problems IE6 doesn't support multiple class selectors, and maybe ID+Class except in some cases. ``` div.class1.class2 { border : 1px solid red; /* this will normally not work in IE6 */ } ``` I don't have IE to test with at the moment and can't remember weather #id.class is supposed to work (I feel it should), but I generally avoid any such things for IE6. You may need to change your selectors. You'll need to set up a test to see if your selectors are working at all. Variations that might work: ``` .inv#chooser_nav { background-position : 0 -114px; } ``` Or you might need to single the element out by a parent: ``` #someparent .inv { background-position : 0 -114px; } ``` IE6 additionally has problems with hover, so that might also be a factor. Hope this helps. I'm sorry I can't be more definite, but getting past IE6's quirks is largely done with good old methods of trial and error, brute force, guessing, and a generous helping of patience.
213,181
<p>Umm, I guess my questions in the title:</p> <p>How do I turn on Option Strict / Infer in a VB.NET aspx page without a code behind file?</p> <pre><code>&lt;%@ Page Language="VB" %&gt; &lt;script runat="server"&gt; Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) End Sub &lt;/script&gt; </code></pre>
[ { "answer_id": 213190, "author": "IAmCodeMonkey", "author_id": 27613, "author_profile": "https://Stackoverflow.com/users/27613", "pm_score": 5, "selected": true, "text": "<pre><code>&lt;%@ Page Language=\"VB\" Strict=\"true\" %&gt;\n</code></pre>\n" }, { "answer_id": 213198, "author": "Mitchel Sellers", "author_id": 13279, "author_profile": "https://Stackoverflow.com/users/13279", "pm_score": 2, "selected": false, "text": "<p>Change the top line to </p>\n\n<pre><code>&lt;%@ Page Language=\"VB\" strict=\"True\" %&gt;\n</code></pre>\n" } ]
2008/10/17
[ "https://Stackoverflow.com/questions/213181", "https://Stackoverflow.com", "https://Stackoverflow.com/users/26/" ]
Umm, I guess my questions in the title: How do I turn on Option Strict / Infer in a VB.NET aspx page without a code behind file? ``` <%@ Page Language="VB" %> <script runat="server"> Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) End Sub </script> ```
``` <%@ Page Language="VB" Strict="true" %> ```
213,192
<p>In my ideal world, what I'm looking for would exist as something along the lines of this:</p> <pre><code>public string UserDefinedField { get { return _userDefinedField; } internal set { _userDefinedField = value; } set { _userDefinedField = value; ChangedFields.Add(Fields.UserDefinedField); } } </code></pre> <p>Where one statement is executed regardless of the access modifier, and another statement is executed if it's called from an external assembly or class.</p> <p>I'm sure I could code something by using reflection and checking up the current call stack to see if the caller is in the same assembly, but I'm looking to see if there's a more elegant approach than that.</p>
[ { "answer_id": 213207, "author": "Isak Savo", "author_id": 8521, "author_profile": "https://Stackoverflow.com/users/8521", "pm_score": 3, "selected": true, "text": "<pre><code>public string UserDefinedField\n{\n get { return _userDefinedField; }\n set { SetField(value); ChangedFields.Add(Fields.UserDefinedField); }\n}\n\n// Call this from internal methods and use the public property for other cases\ninternal string SetField(string userValue)\n{\n _userDefinedField = userValue;\n}\n</code></pre>\n\n<p>You <strong>could</strong> get the caller information by <a href=\"http://msdn.microsoft.com/en-us/library/system.diagnostics.stacktrace.aspx\" rel=\"nofollow noreferrer\">examining the calling stack</a> but that is extremely slow (compared to the above) and I wouldn't recommend it.</p>\n" }, { "answer_id": 213211, "author": "MojoFilter", "author_id": 93, "author_profile": "https://Stackoverflow.com/users/93", "pm_score": 0, "selected": false, "text": "<p>This isn't exactly what you're asking, but in a case like that, I would use an internal method to set the value directly.</p>\n\n<pre><code>...\ninternal void SetUserDefinedField(string val) {\n _userDefinedField = val;\n}\n...\n</code></pre>\n" }, { "answer_id": 213296, "author": "kͩeͣmͮpͥ ͩ", "author_id": 26479, "author_profile": "https://Stackoverflow.com/users/26479", "pm_score": 1, "selected": false, "text": "<p>Redefining Isak's Answer</p>\n\n<pre><code>public string UserDefinedField\n{\n get { return InternalUserDefinedField; }\n set { InternalUserDefinedField = value; ChangedFields.Add(Fields.UserDefinedField); }\n}\n\ninternal string InternalUserDefinedField \n{\n get { return _userDefinedField; }\n set { _userDefinedField= value; }\n}\n</code></pre>\n" }, { "answer_id": 222095, "author": "Jeremy Frey", "author_id": 13412, "author_profile": "https://Stackoverflow.com/users/13412", "pm_score": 0, "selected": false, "text": "<p>If anyone is interested in the reflection route, this code looks like it'd work, but I'd be hesitant to use it over the other suggestions posted so far:</p>\n\n<pre><code>// assumes callers know where they're located at in the current stack trace.\nprivate Boolean IsExternallyCalled(int methodDepth)\n{\n System.Diagnostics.StackTrace trace = new System.Diagnostics.StackTrace();\n\n System.Type callingType = trace.GetFrame(methodDepth).GetMethod().ReflectedType;\n System.Reflection.Assembly a = System.Reflection.Assembly.GetAssembly(callingType);\n\n return !(a.Equals(System.Reflection.Assembly.GetCallingAssembly()));\n}\n</code></pre>\n\n<p>The problem I have with the other examples posted so far are the fact that other classes, even in the same assembly, require internal knowledge of how this particular class operates in order to call the \"correct\" setter. This doesn't smell as it would if I placed the same constraint on outside assemblies, but I'd rather separate my concerns out a tad more.</p>\n" } ]
2008/10/17
[ "https://Stackoverflow.com/questions/213192", "https://Stackoverflow.com", "https://Stackoverflow.com/users/13412/" ]
In my ideal world, what I'm looking for would exist as something along the lines of this: ``` public string UserDefinedField { get { return _userDefinedField; } internal set { _userDefinedField = value; } set { _userDefinedField = value; ChangedFields.Add(Fields.UserDefinedField); } } ``` Where one statement is executed regardless of the access modifier, and another statement is executed if it's called from an external assembly or class. I'm sure I could code something by using reflection and checking up the current call stack to see if the caller is in the same assembly, but I'm looking to see if there's a more elegant approach than that.
``` public string UserDefinedField { get { return _userDefinedField; } set { SetField(value); ChangedFields.Add(Fields.UserDefinedField); } } // Call this from internal methods and use the public property for other cases internal string SetField(string userValue) { _userDefinedField = userValue; } ``` You **could** get the caller information by [examining the calling stack](http://msdn.microsoft.com/en-us/library/system.diagnostics.stacktrace.aspx) but that is extremely slow (compared to the above) and I wouldn't recommend it.
213,195
<p>When I try to login to this site using my yahoo openid, it takes me to the yahoo site, I click "continue" meaning that i <em>want</em> to send my authentication details to stackoverflow.com and stackoverflow.com gives me the following error underneath the login text field:</p> <p>Unable to log in with your OpenID provider:</p> <p>failed to authenticate, returning Failed. Please ensure your identifier is correct and try again. </p>
[ { "answer_id": 213207, "author": "Isak Savo", "author_id": 8521, "author_profile": "https://Stackoverflow.com/users/8521", "pm_score": 3, "selected": true, "text": "<pre><code>public string UserDefinedField\n{\n get { return _userDefinedField; }\n set { SetField(value); ChangedFields.Add(Fields.UserDefinedField); }\n}\n\n// Call this from internal methods and use the public property for other cases\ninternal string SetField(string userValue)\n{\n _userDefinedField = userValue;\n}\n</code></pre>\n\n<p>You <strong>could</strong> get the caller information by <a href=\"http://msdn.microsoft.com/en-us/library/system.diagnostics.stacktrace.aspx\" rel=\"nofollow noreferrer\">examining the calling stack</a> but that is extremely slow (compared to the above) and I wouldn't recommend it.</p>\n" }, { "answer_id": 213211, "author": "MojoFilter", "author_id": 93, "author_profile": "https://Stackoverflow.com/users/93", "pm_score": 0, "selected": false, "text": "<p>This isn't exactly what you're asking, but in a case like that, I would use an internal method to set the value directly.</p>\n\n<pre><code>...\ninternal void SetUserDefinedField(string val) {\n _userDefinedField = val;\n}\n...\n</code></pre>\n" }, { "answer_id": 213296, "author": "kͩeͣmͮpͥ ͩ", "author_id": 26479, "author_profile": "https://Stackoverflow.com/users/26479", "pm_score": 1, "selected": false, "text": "<p>Redefining Isak's Answer</p>\n\n<pre><code>public string UserDefinedField\n{\n get { return InternalUserDefinedField; }\n set { InternalUserDefinedField = value; ChangedFields.Add(Fields.UserDefinedField); }\n}\n\ninternal string InternalUserDefinedField \n{\n get { return _userDefinedField; }\n set { _userDefinedField= value; }\n}\n</code></pre>\n" }, { "answer_id": 222095, "author": "Jeremy Frey", "author_id": 13412, "author_profile": "https://Stackoverflow.com/users/13412", "pm_score": 0, "selected": false, "text": "<p>If anyone is interested in the reflection route, this code looks like it'd work, but I'd be hesitant to use it over the other suggestions posted so far:</p>\n\n<pre><code>// assumes callers know where they're located at in the current stack trace.\nprivate Boolean IsExternallyCalled(int methodDepth)\n{\n System.Diagnostics.StackTrace trace = new System.Diagnostics.StackTrace();\n\n System.Type callingType = trace.GetFrame(methodDepth).GetMethod().ReflectedType;\n System.Reflection.Assembly a = System.Reflection.Assembly.GetAssembly(callingType);\n\n return !(a.Equals(System.Reflection.Assembly.GetCallingAssembly()));\n}\n</code></pre>\n\n<p>The problem I have with the other examples posted so far are the fact that other classes, even in the same assembly, require internal knowledge of how this particular class operates in order to call the \"correct\" setter. This doesn't smell as it would if I placed the same constraint on outside assemblies, but I'd rather separate my concerns out a tad more.</p>\n" } ]
2008/10/17
[ "https://Stackoverflow.com/questions/213195", "https://Stackoverflow.com", "https://Stackoverflow.com/users/29049/" ]
When I try to login to this site using my yahoo openid, it takes me to the yahoo site, I click "continue" meaning that i *want* to send my authentication details to stackoverflow.com and stackoverflow.com gives me the following error underneath the login text field: Unable to log in with your OpenID provider: failed to authenticate, returning Failed. Please ensure your identifier is correct and try again.
``` public string UserDefinedField { get { return _userDefinedField; } set { SetField(value); ChangedFields.Add(Fields.UserDefinedField); } } // Call this from internal methods and use the public property for other cases internal string SetField(string userValue) { _userDefinedField = userValue; } ``` You **could** get the caller information by [examining the calling stack](http://msdn.microsoft.com/en-us/library/system.diagnostics.stacktrace.aspx) but that is extremely slow (compared to the above) and I wouldn't recommend it.
213,214
<p>I'm in a 10 person team working on a large legacy code base with a less than ideal product owner. Our backlog is in pretty bad shape and large epics have frequently been breaking our sprints. The team also struggles with its definition of done - some members write unit test religiously, others don't, sometimes depending on time available.</p> <p>So, I've been seeing some interesting burndown patterns, and I'm wondering which patterns others are seeing and what they mean.</p> <p>Pattern 1:</p> <pre><code># # # # # # # # # # # # # # # # # # # # # # # # # # # # </code></pre> <ul> <li>Positive explanation: "All good."</li> <li>Negative explanation: "Too good to be true. What's <strong>really</strong> going on?"</li> </ul> <p>Pattern 2:</p> <pre><code># # # # # # # # # # # # # # # # # # # # # # </code></pre> <ul> <li>Positive explanation: "This was way easier than we thought, let's pull in more stories."</li> <li>Negative explanation: ??</li> </ul> <p>Pattern 3:</p> <pre><code># # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # </code></pre> <ul> <li>Positive explanation: "Not sure about this work at first, then turns out easier than we thought."</li> <li>Negative explanation: "Not enough progress, let's stop writing unit tests to get 'done' on time."</li> </ul>
[ { "answer_id": 213289, "author": "MojoFilter", "author_id": 93, "author_profile": "https://Stackoverflow.com/users/93", "pm_score": 3, "selected": true, "text": "<p>This is recognized around our office as the \"Ah, crap! I forgot about that.\" burndown:</p>\n\n<pre><code> # # #\n # # # #\n # # # # #\n # # # # # #\n# # # # # # #\n# # # # # # # #\n# # # # # # # #\n</code></pre>\n" }, { "answer_id": 213307, "author": "plinth", "author_id": 20481, "author_profile": "https://Stackoverflow.com/users/20481", "pm_score": 2, "selected": false, "text": "<p>Pattern 2 on the negative side is \"didn't estimate too well\".</p>\n\n<p>Here are some burndown charts I've used. Ignore the background pictures - they are there just to entertain the people I work with and have nothing to do with our work otherwise.\n<a href=\"http://www.atalasoft.com/cs/photos/techtalkgallery/images/16157/425x285.aspx\" rel=\"nofollow noreferrer\">alt text http://www.atalasoft.com/cs/photos/techtalkgallery/images/16157/425x285.aspx</a></p>\n\n<p>I love this chart. It's very typical of a good chart we start a little slowly as we shed other tasks, bear down into the work, get interrupted by other things and push to finish.</p>\n\n<p><a href=\"http://www.atalasoft.com/cs/photos/techtalkgallery/images/16155/425x262.aspx\" rel=\"nofollow noreferrer\">alt text http://www.atalasoft.com/cs/photos/techtalkgallery/images/16155/425x262.aspx</a></p>\n\n<p>In this chart we started very steadily and then took off actually finished ahead of time.</p>\n\n<p><a href=\"http://www.atalasoft.com/cs/photos/techtalkgallery/images/16156/425x264.aspx\" rel=\"nofollow noreferrer\">alt text http://www.atalasoft.com/cs/photos/techtalkgallery/images/16156/425x264.aspx</a></p>\n\n<p>In this chart you can see that we started very typically and then a task that looked easy turned out to be heinously hard. I think we ended up halting this sprint and building a new one.</p>\n" }, { "answer_id": 215827, "author": "Adrian Wible", "author_id": 23105, "author_profile": "https://Stackoverflow.com/users/23105", "pm_score": 1, "selected": false, "text": "<p>One problem with burndowns is that changes in scope are mixed in with progress against scope.</p>\n\n<p>In your example 2, a possible explanation is... holy smoke, I probably shouldn't have waited until the end of the iteration to start this risky story/task... it's alot more effort than I expected!</p>\n\n<p>In example 3, you may have added scope early or discovered that work is more effort than expected (e.g. task is estimated at 4 hours one day, then 4 hours the next after 8 hours of work and discovery that the task is much harder).</p>\n\n<p>I prefer burn-ups to burn-downs for this reason... it disassociates the scope changes from the progress into two lines - one scope and one remaining work, so you can see the impact of scope change more clearly.</p>\n" }, { "answer_id": 222134, "author": "Fabian Buch", "author_id": 28968, "author_profile": "https://Stackoverflow.com/users/28968", "pm_score": 0, "selected": false, "text": "<p>Here it's often like that:</p>\n\n<pre><code>#####\n#######\n########\n#########\n#########\n#########\n##########\n</code></pre>\n\n<p>Positive: Delivery on time.</p>\n\n<p>Negative: Too big backlog items or too many backlog items started at the same time from the beginning.</p>\n" }, { "answer_id": 222310, "author": "Hibri", "author_id": 15946, "author_profile": "https://Stackoverflow.com/users/15946", "pm_score": 1, "selected": false, "text": "<p>My view is not to take burndown charts too seriously. They are an indicator. In the end it is about if you completed a story or not. </p>\n\n<p>Are you having effective retrospectives at the end of your sprints ? </p>\n\n<p>Are retrospective actions followed up on ?</p>\n\n<p>If you find that people don't write unit tests religiously make them do it ( if that is your team standard).\nAgree on a common definition of done and stick to it. See <a href=\"https://stackoverflow.com/questions/170009/your-scrum-definition-of-done#170181\">definition of done</a></p>\n\n<p>Having an agile process like SCRUM needs constant inspection and adapting.</p>\n\n<p>To me it looks like there are problems but your team is not addressing those problems. If the product owner is less than ideal, issues related to this should come up in your retrospectives so you can avoid it in the next sprint.</p>\n\n<p>if you have epics you can always break them down, re-prioritise and re-plan them. </p>\n" }, { "answer_id": 318760, "author": "joshua.ewer", "author_id": 28664, "author_profile": "https://Stackoverflow.com/users/28664", "pm_score": 0, "selected": false, "text": "<p>Here's one I haven't seen here yet. It happened on our last sprint. </p>\n\n<pre><code>#\n##\n###\n#####\n#############\n##################\n###################\n####################\n</code></pre>\n\n<p>It's the \"we made better than expected progress on our first tasks, then thought were were ahead, slacked off, then had to push hard catch up at the end or risk slipping a feature.\" </p>\n\n<p>Lesson learned: Burndowns are great for tracking past efforts, but aren't necessarily representative of your future progress.</p>\n" } ]
2008/10/17
[ "https://Stackoverflow.com/questions/213214", "https://Stackoverflow.com", "https://Stackoverflow.com/users/13041/" ]
I'm in a 10 person team working on a large legacy code base with a less than ideal product owner. Our backlog is in pretty bad shape and large epics have frequently been breaking our sprints. The team also struggles with its definition of done - some members write unit test religiously, others don't, sometimes depending on time available. So, I've been seeing some interesting burndown patterns, and I'm wondering which patterns others are seeing and what they mean. Pattern 1: ``` # # # # # # # # # # # # # # # # # # # # # # # # # # # # ``` * Positive explanation: "All good." * Negative explanation: "Too good to be true. What's **really** going on?" Pattern 2: ``` # # # # # # # # # # # # # # # # # # # # # # ``` * Positive explanation: "This was way easier than we thought, let's pull in more stories." * Negative explanation: ?? Pattern 3: ``` # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # ``` * Positive explanation: "Not sure about this work at first, then turns out easier than we thought." * Negative explanation: "Not enough progress, let's stop writing unit tests to get 'done' on time."
This is recognized around our office as the "Ah, crap! I forgot about that." burndown: ``` # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # ```
213,237
<p>In Django, given excerpts from an application <em>animals</em> likeso:</p> <p>A <em>animals/models.py</em> with: </p> <pre><code>from django.db import models from django.contrib.contenttypes.models import ContentType class Animal(models.Model): content_type = models.ForeignKey(ContentType,editable=False,null=True) name = models.CharField() class Dog(Animal): is_lucky = models.BooleanField() class Cat(Animal): lives_left = models.IntegerField() </code></pre> <p>And an <em>animals/urls.py</em>:</p> <pre><code>from django.conf.urls.default import * from animals.models import Animal, Dog, Cat dict = { 'model' : Animal } urlpatterns = ( url(r'^edit/(?P&lt;object_id&gt;\d+)$', 'create_update.update_object', dict), ) </code></pre> <p>How can one use generic views to edit Dog and/or Cat using the same form?</p> <p>I.e. The <em>form</em> object that is passed to <em>animals/animal_form.html</em> will be Animal, and thus won't contain any of the specifics for the derived classes Dog and Cat. How could I have Django automatically pass a form for the child class to <em>animal/animals_form.html</em>?</p> <p>Incidentally, I'm using <a href="http://www.djangosnippets.org/snippets/1031/" rel="nofollow noreferrer">Djangosnippets #1031</a> for ContentType management, so Animal would have a method named <em>as_leaf_class</em> that returns the derived class.</p> <p>Clearly, one could create forms for each derived class, but that's quite a lot of unnecessary duplication (as the templates will all be generic -- essentially {{ form.as_p }}).</p> <p>Incidentally, it's best to assume that Animal will probably be one of several unrelated base classes with the same problem, so an ideal solution would be generic.</p> <p>Thank you in advance for the help.</p>
[ { "answer_id": 213393, "author": "Javier", "author_id": 11649, "author_profile": "https://Stackoverflow.com/users/11649", "pm_score": 0, "selected": false, "text": "<p>AFAICT, cats and dogs are on different DB tables, and maybe there's no Animal table. but you're using one URL pattern for all. somewhere you need to choose between each.</p>\n\n<p>I'd use a different URL patter for cats and dogs, both would call <code>'create_update.update_object'</code>; but using a different <code>dict</code> for each. one with <code>'model':Dog</code> and the other with <code>'model':Cat</code></p>\n\n<p>or maybe you want a single table where each record can be a cat or a dog? i don't think you can use inherited models for that.</p>\n" }, { "answer_id": 215488, "author": "Brian M. Hunt", "author_id": 19212, "author_profile": "https://Stackoverflow.com/users/19212", "pm_score": 2, "selected": true, "text": "<p>Alright, here's what I've done, and it seems to work and be a sensible design (though I stand to be corrected!).</p>\n\n<p>In a core library (e.g. mysite.core.views.create_update), I've written a decorator:</p>\n\n<pre><code>from django.contrib.contenttypes.models import ContentType\nfrom django.views.generic import create_update\n\ndef update_object_as_child(parent_model_class):\n \"\"\"\n Given a base models.Model class, decorate a function to return \n create_update.update_object, on the child class.\n\n e.g.\n @update_object(Animal)\n def update_object(request, object_id):\n pass\n\n kwargs should have an object_id defined.\n \"\"\"\n\n def decorator(function):\n def wrapper(request, **kwargs):\n # may raise KeyError\n id = kwargs['object_id']\n\n parent_obj = parent_model_class.objects.get( pk=id )\n\n # following http://www.djangosnippets.org/snippets/1031/\n child_class = parent_obj.content_type.model_class()\n\n kwargs['model'] = child_class\n\n # rely on the generic code for testing/validation/404\n return create_update.update_object(request, **kwargs)\n return wrapper\n\n return decorator\n</code></pre>\n\n<p>And in animals/views.py, I have:</p>\n\n<pre><code>from mysite.core.views.create_update import update_object_as_child\n\n@update_object_as_child(Animal)\ndef edit_animal(request, object_id):\n pass\n</code></pre>\n\n<p>And in animals/urls.py, I have:</p>\n\n<pre><code>urlpatterns += patterns('animals.views',\n url(r'^edit/(?P&lt;object_id&gt;\\d+)$', 'edit_animal', name=\"edit_animal\"),\n)\n</code></pre>\n\n<p>Now I only need a unique edit function for each base class, which is trivial to create with a decorator.</p>\n\n<p>Hope someone finds that helpful, and I'd be delighted to have feedback.</p>\n" } ]
2008/10/17
[ "https://Stackoverflow.com/questions/213237", "https://Stackoverflow.com", "https://Stackoverflow.com/users/19212/" ]
In Django, given excerpts from an application *animals* likeso: A *animals/models.py* with: ``` from django.db import models from django.contrib.contenttypes.models import ContentType class Animal(models.Model): content_type = models.ForeignKey(ContentType,editable=False,null=True) name = models.CharField() class Dog(Animal): is_lucky = models.BooleanField() class Cat(Animal): lives_left = models.IntegerField() ``` And an *animals/urls.py*: ``` from django.conf.urls.default import * from animals.models import Animal, Dog, Cat dict = { 'model' : Animal } urlpatterns = ( url(r'^edit/(?P<object_id>\d+)$', 'create_update.update_object', dict), ) ``` How can one use generic views to edit Dog and/or Cat using the same form? I.e. The *form* object that is passed to *animals/animal\_form.html* will be Animal, and thus won't contain any of the specifics for the derived classes Dog and Cat. How could I have Django automatically pass a form for the child class to *animal/animals\_form.html*? Incidentally, I'm using [Djangosnippets #1031](http://www.djangosnippets.org/snippets/1031/) for ContentType management, so Animal would have a method named *as\_leaf\_class* that returns the derived class. Clearly, one could create forms for each derived class, but that's quite a lot of unnecessary duplication (as the templates will all be generic -- essentially {{ form.as\_p }}). Incidentally, it's best to assume that Animal will probably be one of several unrelated base classes with the same problem, so an ideal solution would be generic. Thank you in advance for the help.
Alright, here's what I've done, and it seems to work and be a sensible design (though I stand to be corrected!). In a core library (e.g. mysite.core.views.create\_update), I've written a decorator: ``` from django.contrib.contenttypes.models import ContentType from django.views.generic import create_update def update_object_as_child(parent_model_class): """ Given a base models.Model class, decorate a function to return create_update.update_object, on the child class. e.g. @update_object(Animal) def update_object(request, object_id): pass kwargs should have an object_id defined. """ def decorator(function): def wrapper(request, **kwargs): # may raise KeyError id = kwargs['object_id'] parent_obj = parent_model_class.objects.get( pk=id ) # following http://www.djangosnippets.org/snippets/1031/ child_class = parent_obj.content_type.model_class() kwargs['model'] = child_class # rely on the generic code for testing/validation/404 return create_update.update_object(request, **kwargs) return wrapper return decorator ``` And in animals/views.py, I have: ``` from mysite.core.views.create_update import update_object_as_child @update_object_as_child(Animal) def edit_animal(request, object_id): pass ``` And in animals/urls.py, I have: ``` urlpatterns += patterns('animals.views', url(r'^edit/(?P<object_id>\d+)$', 'edit_animal', name="edit_animal"), ) ``` Now I only need a unique edit function for each base class, which is trivial to create with a decorator. Hope someone finds that helpful, and I'd be delighted to have feedback.
213,238
<p>Just playing around with the now released Silverlight 2.0. I'm trying to put a simple Calendar in a control. However the project doesn't seem to know what I'm talking about:-</p> <pre><code>&lt;UserControl x:Class="MyFirstSL2.Test" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" &gt; &lt;Grid Background="#FF5C7590"&gt; &lt;Calendar /&gt; &lt;/Grid&gt; &lt;/UserControl&gt; </code></pre> <p>Visual Studio 2008 just puts blue line under the Calendar saying the type Calendar not found. Do I need to add an assembly? Which one? Do I need to add another namespace to the Xaml?</p>
[ { "answer_id": 213304, "author": "MojoFilter", "author_id": 93, "author_profile": "https://Stackoverflow.com/users/93", "pm_score": 0, "selected": false, "text": "<p>I'm pretty sure there's no calendar control in Silverlight that is analogous to the ASP.Net control or the windows forms control. I'm pretty sure there's not a pre-packaged control like that for WPF, either.</p>\n" }, { "answer_id": 213592, "author": "Tim Heuer", "author_id": 705, "author_profile": "https://Stackoverflow.com/users/705", "pm_score": 5, "selected": true, "text": "<p>The calendar control is an SDK control in the assembly System.Windows.Controls namespace -- look at %program files%\\Microsoft SDKs\\Silverlight\\v2.0\\Libraries\\Client add a namespace to your xaml (after you add a reference):</p>\n\n<pre><code>xmlns:basics=\"clr-namespace:System.Windows.Controls;assembly=System.Windows.Controls\"\n</code></pre>\n\n<p>Then to use:</p>\n\n<pre><code>&lt;basics:Calendar /&gt;\n</code></pre>\n\n<p>Hope this helps!</p>\n" }, { "answer_id": 353016, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 1, "selected": false, "text": "<p>add a reference to </p>\n\n<p>C:\\Program Files\\Microsoft SDKs\\Silverlight\\v2.0\\Libraries\\Client</p>\n\n<p>system.windows.controls.dll </p>\n\n<p>Use Expressions Blend or VS2008 SP1 to add the control to the UI</p>\n" }, { "answer_id": 1488887, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 0, "selected": false, "text": "<p>Instead of trying to figure out how the toolkit allows for an embeded calendar control I created a custom control here <a href=\"http://slcalendarcontrol.codeplex.com/\" rel=\"nofollow noreferrer\">http://slcalendarcontrol.codeplex.com/</a> check it out.</p>\n" } ]
2008/10/17
[ "https://Stackoverflow.com/questions/213238", "https://Stackoverflow.com", "https://Stackoverflow.com/users/17516/" ]
Just playing around with the now released Silverlight 2.0. I'm trying to put a simple Calendar in a control. However the project doesn't seem to know what I'm talking about:- ``` <UserControl x:Class="MyFirstSL2.Test" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" > <Grid Background="#FF5C7590"> <Calendar /> </Grid> </UserControl> ``` Visual Studio 2008 just puts blue line under the Calendar saying the type Calendar not found. Do I need to add an assembly? Which one? Do I need to add another namespace to the Xaml?
The calendar control is an SDK control in the assembly System.Windows.Controls namespace -- look at %program files%\Microsoft SDKs\Silverlight\v2.0\Libraries\Client add a namespace to your xaml (after you add a reference): ``` xmlns:basics="clr-namespace:System.Windows.Controls;assembly=System.Windows.Controls" ``` Then to use: ``` <basics:Calendar /> ``` Hope this helps!
213,249
<p>I am wondering - What's the most effective way of parsing something like:</p> <pre><code>{{HEADER}} Hello my name is {{NAME}} {{#CONTENT}} This is the content ... {{#PERSONS}} &lt;p&gt;My name is {{NAME}}.&lt;/p&gt; {{/PERSONS}} {{/CONTENT}} {{FOOTER}} </code></pre> <p>Of course this is intended to be somewhat of a templating system in the end, so my plan is to create a hashmap to "lay over" the template, as something like this</p> <pre><code>$hash = array( 'HEADER' =&gt; 'This is a header', 'NAME' =&gt; 'David', 'CONTENT' =&gt; array('PERSONS' =&gt; array(array('NAME' =&gt; 'Heino'), array('NAME' =&gt; 'Sebastian')), 'FOOTER' =&gt; 'This is the footer' ); </code></pre> <p>It's worth noticing that the "sections" (the tags that start with #), can be repeated more than once, and i think this is what trips me up ...</p> <p>Also, any section can contain any number of other sections, and regular tags...</p> <p>So.. how'd you do it?</p>
[ { "answer_id": 213270, "author": "Kibbee", "author_id": 1862, "author_profile": "https://Stackoverflow.com/users/1862", "pm_score": 0, "selected": false, "text": "<p>You would bet better off using something with an existing parser like XML or JSON so you don't have to write your own parser, and so that others can easily write documents for your parser without needing specialized tools. However, if you want to write your own parser, you probably want to look into using <a href=\"http://en.wikipedia.org/wiki/Lex_programming_tool\" rel=\"nofollow noreferrer\">Lex</a> and <a href=\"http://en.wikipedia.org/wiki/Yacc\" rel=\"nofollow noreferrer\">Yacc</a>.</p>\n" }, { "answer_id": 213343, "author": "Jesse Dearing", "author_id": 1804, "author_profile": "https://Stackoverflow.com/users/1804", "pm_score": 0, "selected": false, "text": "<p>I would go with a third party parser because I like to work smarter and not harder, but if you're doing this as an exercise or you really want to build your own template engine (in PHP I assume because of the tag), I would start with reviewing design patterns, the <a href=\"http://en.wikipedia.org/wiki/Composite_pattern\" rel=\"nofollow noreferrer\">composite design pattern</a> specifically.</p>\n\n<p>The composite pattern is used a lot in the Java framework for stuff like this including XML parsing.</p>\n" }, { "answer_id": 213344, "author": "Troy Howard", "author_id": 19258, "author_profile": "https://Stackoverflow.com/users/19258", "pm_score": 2, "selected": true, "text": "<p>Is the expected output of this something like: </p>\n\n<p>This is a header</p>\n\n<p>Hello my name is David</p>\n\n<pre><code>This is the content ...\n\nMy name is Heino.\n\nMy name is Sebastian.\n</code></pre>\n\n<p>This is the footer</p>\n\n<hr>\n\n<p>How are you managing the relationship of nested arrays in the hash map to repeatable sections in the template? What is the actual behaviour of the template supposed to be? If an array is provided for a non-section element, what will it do? If a section element is provided a single value, will it be treated the same as an array with only a single element (I assume so)?</p>\n\n<p>Anyhow, with regards to the parser for the template (regardless of what you end up doing with the mapping of data)... What I would do is create a class for each type of token, including a generic one for non-token content. These would inherit from a common token base class with overridable Parse, Render and Map methods. </p>\n\n<p>Chart out your state diagram and figure out what your entry and exit points are for each state, then encode that into the call structure between the tokens. In the end you want to yield an enumerable collection of tokens that describes your template. </p>\n\n<p>Once you have that in an abstract form, you can iteate over the collection calling Map on the tokens to assign the data from the hashmap to the tokens, and then call Render to render the template into it's final form. </p>\n\n<p>Hope that helps.</p>\n" }, { "answer_id": 213589, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 0, "selected": false, "text": "<p>I would use something like this inside a .php separate file:</p>\n\n<pre><code>&lt;?php echo $HEADER ?&gt;\n\nHello my name is &lt;?php echo $NAME?&gt;\n\n&lt;div id=\"CONTENT\"&gt;\n This is the content ...\n\n &lt;?php foreach ($PERSONS as $PERSON) : ?&gt;\n\n &lt;p&gt;My name is &lt;?php echo $PERSON['NAME']?&gt;.&lt;/p&gt;\n\n &lt;?php endforeach ?&gt;\n\n&lt;/div&gt;\n\n&lt;?php echo $FOOTER ?&gt;\n</code></pre>\n\n<p>And just include the above file inside the one where the referenced variables are populated.</p>\n\n<p>Believe it or not, PHP already provides all the features that templating systems out there are claiming to implement. There is no need to add another layer of abstraction (and complexity) on top of PHP. </p>\n" }, { "answer_id": 213662, "author": "Scott Reynen", "author_id": 10837, "author_profile": "https://Stackoverflow.com/users/10837", "pm_score": 0, "selected": false, "text": "<p>I use <a href=\"http://php.net/dom\" rel=\"nofollow noreferrer\">PHP's DOM</a> for this. My template language is simply HTML with ID and class attributes. If you want to stick with your plan, though, I'd use <a href=\"http://php.net/preg_replace_callback\" rel=\"nofollow noreferrer\">preg_replace_callback</a> with a pattern that matches your syntax and a callback function that finds the appropriate replacement in your hash, calling itself recursively on container elements.</p>\n" }, { "answer_id": 214074, "author": "Bob Fanger", "author_id": 19165, "author_profile": "https://Stackoverflow.com/users/19165", "pm_score": 1, "selected": false, "text": "<p>The most efficient way to is to <strong>compile</strong> the template to php code. And just <strong>include</strong> the compiled version.</p>\n\n<p>The <a href=\"http://www.smarty.net\" rel=\"nofollow noreferrer\">Smarty Template Engine</a> does something similar. You can also look at the smarty source and check how they parse tags.</p>\n" } ]
2008/10/17
[ "https://Stackoverflow.com/questions/213249", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20538/" ]
I am wondering - What's the most effective way of parsing something like: ``` {{HEADER}} Hello my name is {{NAME}} {{#CONTENT}} This is the content ... {{#PERSONS}} <p>My name is {{NAME}}.</p> {{/PERSONS}} {{/CONTENT}} {{FOOTER}} ``` Of course this is intended to be somewhat of a templating system in the end, so my plan is to create a hashmap to "lay over" the template, as something like this ``` $hash = array( 'HEADER' => 'This is a header', 'NAME' => 'David', 'CONTENT' => array('PERSONS' => array(array('NAME' => 'Heino'), array('NAME' => 'Sebastian')), 'FOOTER' => 'This is the footer' ); ``` It's worth noticing that the "sections" (the tags that start with #), can be repeated more than once, and i think this is what trips me up ... Also, any section can contain any number of other sections, and regular tags... So.. how'd you do it?
Is the expected output of this something like: This is a header Hello my name is David ``` This is the content ... My name is Heino. My name is Sebastian. ``` This is the footer --- How are you managing the relationship of nested arrays in the hash map to repeatable sections in the template? What is the actual behaviour of the template supposed to be? If an array is provided for a non-section element, what will it do? If a section element is provided a single value, will it be treated the same as an array with only a single element (I assume so)? Anyhow, with regards to the parser for the template (regardless of what you end up doing with the mapping of data)... What I would do is create a class for each type of token, including a generic one for non-token content. These would inherit from a common token base class with overridable Parse, Render and Map methods. Chart out your state diagram and figure out what your entry and exit points are for each state, then encode that into the call structure between the tokens. In the end you want to yield an enumerable collection of tokens that describes your template. Once you have that in an abstract form, you can iteate over the collection calling Map on the tokens to assign the data from the hashmap to the tokens, and then call Render to render the template into it's final form. Hope that helps.
213,251
<p>I've been reading that Adobe has made crossdomain.xml stricter in flash 9-10 and I'm wondering of someone can paste me a copy of one that they know works. Having some trouble finding a recent sample on Adobe's site.</p>
[ { "answer_id": 213272, "author": "Mitch Haile", "author_id": 28807, "author_profile": "https://Stackoverflow.com/users/28807", "pm_score": 8, "selected": true, "text": "<p>This is what I've been using for development:</p>\n\n<pre><code>&lt;?xml version=\"1.0\" ?&gt;\n&lt;cross-domain-policy&gt;\n&lt;allow-access-from domain=\"*\" /&gt;\n&lt;/cross-domain-policy&gt;\n</code></pre>\n\n<p>This is a very liberal approach, but is fine for my application.</p>\n\n<p><strong>As others have pointed out below, beware the risks of this.</strong></p>\n" }, { "answer_id": 215346, "author": "ThePants", "author_id": 29260, "author_profile": "https://Stackoverflow.com/users/29260", "pm_score": 5, "selected": false, "text": "<p>If you're using webservices, you'll also need the 'allow-http-request-headers-from' element. Here's our default, development, 'allow everything' policy.</p>\n\n<pre><code>&lt;?xml version=\"1.0\" ?&gt;\n&lt;cross-domain-policy&gt;\n &lt;site-control permitted-cross-domain-policies=\"master-only\"/&gt;\n &lt;allow-access-from domain=\"*\"/&gt;\n &lt;allow-http-request-headers-from domain=\"*\" headers=\"*\"/&gt;\n&lt;/cross-domain-policy&gt;\n</code></pre>\n" }, { "answer_id": 5472417, "author": "Zhami", "author_id": 65934, "author_profile": "https://Stackoverflow.com/users/65934", "pm_score": 5, "selected": false, "text": "<p>Take a look at Twitter's:</p>\n\n<p><a href=\"http://twitter.com/crossdomain.xml\" rel=\"noreferrer\">http://twitter.com/crossdomain.xml</a></p>\n\n<pre><code>&lt;?xml version=\"1.0\" encoding=\"UTF-8\"?&gt;\n&lt;cross-domain-policy xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xsi:noNamespaceSchemaLocation=\"http://www.adobe.com/xml/schemas/PolicyFile.xsd\"&gt;\n &lt;allow-access-from domain=\"twitter.com\" /&gt;\n &lt;allow-access-from domain=\"api.twitter.com\" /&gt;\n &lt;allow-access-from domain=\"search.twitter.com\" /&gt;\n &lt;allow-access-from domain=\"static.twitter.com\" /&gt;\n &lt;site-control permitted-cross-domain-policies=\"master-only\"/&gt;\n &lt;allow-http-request-headers-from domain=\"*.twitter.com\" headers=\"*\" secure=\"true\"/&gt;\n&lt;/cross-domain-policy&gt;\n</code></pre>\n" }, { "answer_id": 10259429, "author": "trante", "author_id": 429938, "author_profile": "https://Stackoverflow.com/users/429938", "pm_score": 3, "selected": false, "text": "<p>In production site this seems suitable:</p>\n\n<pre><code>&lt;?xml version=\"1.0\"?&gt;\n&lt;cross-domain-policy&gt;\n&lt;allow-access-from domain=\"www.mysite.com\" /&gt;\n&lt;allow-access-from domain=\"mysite.com\" /&gt;\n&lt;/cross-domain-policy&gt;\n</code></pre>\n" }, { "answer_id": 31488228, "author": "ThisClark", "author_id": 1161948, "author_profile": "https://Stackoverflow.com/users/1161948", "pm_score": 3, "selected": false, "text": "<p>A version of <strong>crossdomain.xml</strong> used to be packaged with the <a href=\"https://html5boilerplate.com/\" rel=\"nofollow noreferrer\">HTML5 Boilerplate</a> which is <em>the product of many years of iterative development and combined community knowledge.</em> However, it has since been deleted from the repository. I've copied it verbatim here, and included a link to the commit where it was deleted below.</p>\n\n<pre><code>&lt;?xml version=\"1.0\"?&gt;\n&lt;!DOCTYPE cross-domain-policy SYSTEM \"http://www.adobe.com/xml/dtds/cross-domain-policy.dtd\"&gt;\n&lt;cross-domain-policy&gt;\n &lt;!-- Read this: https://www.adobe.com/devnet/articles/crossdomain_policy_file_spec.html --&gt;\n\n &lt;!-- Most restrictive policy: --&gt;\n &lt;site-control permitted-cross-domain-policies=\"none\"/&gt;\n\n &lt;!-- Least restrictive policy: --&gt;\n &lt;!--\n &lt;site-control permitted-cross-domain-policies=\"all\"/&gt;\n &lt;allow-access-from domain=\"*\" to-ports=\"*\" secure=\"false\"/&gt;\n &lt;allow-http-request-headers-from domain=\"*\" headers=\"*\" secure=\"false\"/&gt;\n --&gt;\n&lt;/cross-domain-policy&gt;\n</code></pre>\n\n<p>Deleted in #1881<br>\n<a href=\"https://github.com/h5bp/html5-boilerplate/commit/58a2ba81d250301e7b5e3da28ae4c1b42d91b2c2\" rel=\"nofollow noreferrer\">https://github.com/h5bp/html5-boilerplate/commit/58a2ba81d250301e7b5e3da28ae4c1b42d91b2c2</a></p>\n" } ]
2008/10/17
[ "https://Stackoverflow.com/questions/213251", "https://Stackoverflow.com", "https://Stackoverflow.com/users/18309/" ]
I've been reading that Adobe has made crossdomain.xml stricter in flash 9-10 and I'm wondering of someone can paste me a copy of one that they know works. Having some trouble finding a recent sample on Adobe's site.
This is what I've been using for development: ``` <?xml version="1.0" ?> <cross-domain-policy> <allow-access-from domain="*" /> </cross-domain-policy> ``` This is a very liberal approach, but is fine for my application. **As others have pointed out below, beware the risks of this.**
213,266
<p>How do I go about positioning a JDialog at the center of the screen?</p>
[ { "answer_id": 213291, "author": "johnstok", "author_id": 27929, "author_profile": "https://Stackoverflow.com/users/27929", "pm_score": 8, "selected": true, "text": "<p>In Java 1.4+ you can do:</p>\n\n<pre><code>final JDialog d = new JDialog();\nd.setSize(200,200);\nd.setLocationRelativeTo(null);\nd.setVisible(true);\n</code></pre>\n\n<p>Or perhaps (pre 1.4):</p>\n\n<pre><code>final JDialog d = new JDialog();\nd.setSize(200, 200);\nfinal Toolkit toolkit = Toolkit.getDefaultToolkit();\nfinal Dimension screenSize = toolkit.getScreenSize();\nfinal int x = (screenSize.width - d.getWidth()) / 2;\nfinal int y = (screenSize.height - d.getHeight()) / 2;\nd.setLocation(x, y);\nd.setVisible(true);\n</code></pre>\n" }, { "answer_id": 215630, "author": "ZeissS", "author_id": 23760, "author_profile": "https://Stackoverflow.com/users/23760", "pm_score": 2, "selected": false, "text": "<p>AFAIK you can pass a GraphicEnvironment to each JDialog/JFrame/JWindow constructor. This object describes the monitor to use.</p>\n" }, { "answer_id": 582346, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 3, "selected": false, "text": "<p>here's my solution to retrieve screen dimension with multiple monitors.</p>\n\n<pre><code>import java.awt.*;\nimport javax.swing.JFrame;\n\n/**\n * Méthodes statiques pour récupérer les informations d'un écran.\n *\n * @author Jean-Claude Stritt\n * @version 1.0 / 24.2.2009\n */\npublic class ScreenInfo {\n\n /**\n * Permet de récupérer le numéro de l'écran par rapport à la fenêtre affichée.\n * @return le numéro 1, 2, ... (ID) de l'écran\n */\n public static int getScreenID( JFrame jf ) {\n int scrID = 1;\n GraphicsEnvironment ge = GraphicsEnvironment.getLocalGraphicsEnvironment();\n GraphicsDevice[] gd = ge.getScreenDevices();\n for (int i = 0; i &lt; gd.length; i++) {\n GraphicsConfiguration gc = gd[i].getDefaultConfiguration();\n Rectangle r = gc.getBounds();\n if (r.contains(jf.getLocation())) {\n scrID = i+1;\n }\n }\n return scrID;\n }\n\n /**\n * Permet de récupérer la dimension (largeur, hauteur) en px d'un écran spécifié.\n * @param scrID --&gt; le n° d'écran\n * @return la dimension (largeur, hauteur) en pixels de l'écran spécifié\n */\n public static Dimension getScreenDimension( int scrID ) {\n Dimension d = new Dimension(0, 0);\n if (scrID &gt; 0) {\n GraphicsEnvironment ge = GraphicsEnvironment.getLocalGraphicsEnvironment();\n DisplayMode mode = ge.getScreenDevices()[scrID - 1].getDisplayMode();\n d.setSize(mode.getWidth(), mode.getHeight());\n }\n return d;\n }\n\n /**\n * Permet de récupérer la largeur en pixels d'un écran spécifié.\n * @param scrID --&gt; le n° d'écran\n * @return la largeur en px de l'écran spécifié\n */\n public static int getScreenWidth( int scrID ) {\n Dimension d = getScreenDimension(scrID);\n return d.width;\n }\n\n /**\n * Permet de récupérer la hauteur en pixels d'un écran spécifié.\n * @param scrID --&gt; le n° d'écran\n * @return la hauteur en px de l'écran spécifié\n */\n public static int getScreenHeight( int scrID ) {\n Dimension d = getScreenDimension(scrID);\n return d.height;\n }\n\n}\n</code></pre>\n" }, { "answer_id": 9577907, "author": "Java42", "author_id": 1250303, "author_profile": "https://Stackoverflow.com/users/1250303", "pm_score": 3, "selected": false, "text": "<p>Two helpers for centering within the screen or within the parent.</p>\n\n<pre><code>// Center on screen ( absolute true/false (exact center or 25% upper left) )\npublic void centerOnScreen(final Component c, final boolean absolute) {\n final int width = c.getWidth();\n final int height = c.getHeight();\n final Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize();\n int x = (screenSize.width / 2) - (width / 2);\n int y = (screenSize.height / 2) - (height / 2);\n if (!absolute) {\n x /= 2;\n y /= 2;\n }\n c.setLocation(x, y);\n}\n\n// Center on parent ( absolute true/false (exact center or 25% upper left) )\npublic void centerOnParent(final Window child, final boolean absolute) {\n child.pack();\n boolean useChildsOwner = child.getOwner() != null ? ((child.getOwner() instanceof JFrame) || (child.getOwner() instanceof JDialog)) : false;\n final Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize();\n final Dimension parentSize = useChildsOwner ? child.getOwner().getSize() : screenSize ;\n final Point parentLocationOnScreen = useChildsOwner ? child.getOwner().getLocationOnScreen() : new Point(0,0) ;\n final Dimension childSize = child.getSize();\n childSize.width = Math.min(childSize.width, screenSize.width);\n childSize.height = Math.min(childSize.height, screenSize.height);\n child.setSize(childSize); \n int x;\n int y;\n if ((child.getOwner() != null) &amp;&amp; child.getOwner().isShowing()) {\n x = (parentSize.width - childSize.width) / 2;\n y = (parentSize.height - childSize.height) / 2;\n x += parentLocationOnScreen.x;\n y += parentLocationOnScreen.y;\n } else {\n x = (screenSize.width - childSize.width) / 2;\n y = (screenSize.height - childSize.height) / 2;\n }\n if (!absolute) {\n x /= 2;\n y /= 2;\n }\n child.setLocation(x, y);\n}\n</code></pre>\n" }, { "answer_id": 15926711, "author": "Kunax", "author_id": 2266196, "author_profile": "https://Stackoverflow.com/users/2266196", "pm_score": 4, "selected": false, "text": "<p>Use this line after the <code>pack()</code> method:</p>\n\n<pre><code>setLocation((Toolkit.getDefaultToolkit().getScreenSize().width)/2 - getWidth()/2, (Toolkit.getDefaultToolkit().getScreenSize().height)/2 - getHeight()/2);\n</code></pre>\n" } ]
2008/10/17
[ "https://Stackoverflow.com/questions/213266", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2443/" ]
How do I go about positioning a JDialog at the center of the screen?
In Java 1.4+ you can do: ``` final JDialog d = new JDialog(); d.setSize(200,200); d.setLocationRelativeTo(null); d.setVisible(true); ``` Or perhaps (pre 1.4): ``` final JDialog d = new JDialog(); d.setSize(200, 200); final Toolkit toolkit = Toolkit.getDefaultToolkit(); final Dimension screenSize = toolkit.getScreenSize(); final int x = (screenSize.width - d.getWidth()) / 2; final int y = (screenSize.height - d.getHeight()) / 2; d.setLocation(x, y); d.setVisible(true); ```
213,267
<p>I'm trying to pass one method to another in elisp, and then have that method execute it. Here is an example:</p> <pre><code>(defun t1 () "t1") (defun t2 () "t1") (defun call-t (t) ; how do I execute "t"? (t)) ; How do I pass in method reference? (call-t 't1) </code></pre>
[ { "answer_id": 213511, "author": "Timo Geusch", "author_id": 29068, "author_profile": "https://Stackoverflow.com/users/29068", "pm_score": 6, "selected": true, "text": "<p>First, I'm not sure that naming your function <code>t</code> is helping as 't' is used as the <a href=\"http://www.mcs.vuw.ac.nz/cgi-bin/info2www?(elisp)nil+and+t\" rel=\"noreferrer\">truth value</a> in lisp.</p>\n\n<p>That said, the following code works for me:</p>\n\n<pre><code>(defun test-func-1 () \"test-func-1\"\n (interactive \"*\")\n (insert-string \"testing callers\"))\n\n(defun func-caller (callee)\n \"Execute callee\"\n (funcall callee))\n\n(func-caller 'test-func-1)\n</code></pre>\n\n<p>Please note the use of 'funcall', which triggers the actual function call.</p>\n" }, { "answer_id": 226770, "author": "Jouni K. Seppänen", "author_id": 26575, "author_profile": "https://Stackoverflow.com/users/26575", "pm_score": 3, "selected": false, "text": "<p>The note towards the end of &quot;<a href=\"https://www.gnu.org/software/emacs/manual/html_node/elisp/Anonymous-Functions.html#index-_0023_0027-syntax\" rel=\"nofollow noreferrer\">§13.7 Anonymous Functions</a>&quot; in the <a href=\"https://www.gnu.org/software/emacs/manual/html_node/elisp/index.html#SEC_Contents\" rel=\"nofollow noreferrer\">Emacs Lisp manual</a> says that you can quote functions with <code>#'</code> instead of <code>'</code> to signal to the byte compiler that the symbol always names a function.</p>\n" }, { "answer_id": 63721766, "author": "Víctor Ponce", "author_id": 13667103, "author_profile": "https://Stackoverflow.com/users/13667103", "pm_score": 0, "selected": false, "text": "<p>Above answers are okey, but you can do something more interesting with defmacro, wich evaluates functions later for some reason:</p>\n<pre><code>(defun n1 ()\n &quot;n1&quot;)\n\n(defmacro call-n (n)\n (apply n))\n\n(call-n (n1))\n</code></pre>\n<p>A practical example with a for loop that takes any amount of functions and their arguments:</p>\n<pre><code>(defmacro for (i &amp;optional i++ &amp;rest body)\n &quot;c-like for-loop&quot;\n (unless (numberp i++) (push i++ body) (setq i++ 1))\n\n (while (/= i 0)\n (let ((args 0))\n (while (nth args body)\n (apply (car (nth args body))\n (cdr (nth args body)))\n (setq args (1+ args))))\n (setq i (- i i++))\n )\n )\n</code></pre>\n" } ]
2008/10/17
[ "https://Stackoverflow.com/questions/213267", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9435/" ]
I'm trying to pass one method to another in elisp, and then have that method execute it. Here is an example: ``` (defun t1 () "t1") (defun t2 () "t1") (defun call-t (t) ; how do I execute "t"? (t)) ; How do I pass in method reference? (call-t 't1) ```
First, I'm not sure that naming your function `t` is helping as 't' is used as the [truth value](http://www.mcs.vuw.ac.nz/cgi-bin/info2www?(elisp)nil+and+t) in lisp. That said, the following code works for me: ``` (defun test-func-1 () "test-func-1" (interactive "*") (insert-string "testing callers")) (defun func-caller (callee) "Execute callee" (funcall callee)) (func-caller 'test-func-1) ``` Please note the use of 'funcall', which triggers the actual function call.
213,271
<p>window.scrollMaxY can be set via that property in IE and older versions of Firefox, but when trying in FF3 it says "Cannot set this property as it only has a getter".</p> <p>What is my alternative?</p> <p>EDIT:</p> <p>The reason why I'm asking is that I'm fixing some very horrible JS written by someone else, it has a function to keep a div centered on the page while scrolling, and has this line:</p> <pre><code>// Fixes Firefox incrementing page height while scrolling window.scrollMaxY = scrollMaxY </code></pre> <p>Obviously this doesn't work, but the main issue is that when the page is scrolled, it grows in length.</p>
[ { "answer_id": 213511, "author": "Timo Geusch", "author_id": 29068, "author_profile": "https://Stackoverflow.com/users/29068", "pm_score": 6, "selected": true, "text": "<p>First, I'm not sure that naming your function <code>t</code> is helping as 't' is used as the <a href=\"http://www.mcs.vuw.ac.nz/cgi-bin/info2www?(elisp)nil+and+t\" rel=\"noreferrer\">truth value</a> in lisp.</p>\n\n<p>That said, the following code works for me:</p>\n\n<pre><code>(defun test-func-1 () \"test-func-1\"\n (interactive \"*\")\n (insert-string \"testing callers\"))\n\n(defun func-caller (callee)\n \"Execute callee\"\n (funcall callee))\n\n(func-caller 'test-func-1)\n</code></pre>\n\n<p>Please note the use of 'funcall', which triggers the actual function call.</p>\n" }, { "answer_id": 226770, "author": "Jouni K. Seppänen", "author_id": 26575, "author_profile": "https://Stackoverflow.com/users/26575", "pm_score": 3, "selected": false, "text": "<p>The note towards the end of &quot;<a href=\"https://www.gnu.org/software/emacs/manual/html_node/elisp/Anonymous-Functions.html#index-_0023_0027-syntax\" rel=\"nofollow noreferrer\">§13.7 Anonymous Functions</a>&quot; in the <a href=\"https://www.gnu.org/software/emacs/manual/html_node/elisp/index.html#SEC_Contents\" rel=\"nofollow noreferrer\">Emacs Lisp manual</a> says that you can quote functions with <code>#'</code> instead of <code>'</code> to signal to the byte compiler that the symbol always names a function.</p>\n" }, { "answer_id": 63721766, "author": "Víctor Ponce", "author_id": 13667103, "author_profile": "https://Stackoverflow.com/users/13667103", "pm_score": 0, "selected": false, "text": "<p>Above answers are okey, but you can do something more interesting with defmacro, wich evaluates functions later for some reason:</p>\n<pre><code>(defun n1 ()\n &quot;n1&quot;)\n\n(defmacro call-n (n)\n (apply n))\n\n(call-n (n1))\n</code></pre>\n<p>A practical example with a for loop that takes any amount of functions and their arguments:</p>\n<pre><code>(defmacro for (i &amp;optional i++ &amp;rest body)\n &quot;c-like for-loop&quot;\n (unless (numberp i++) (push i++ body) (setq i++ 1))\n\n (while (/= i 0)\n (let ((args 0))\n (while (nth args body)\n (apply (car (nth args body))\n (cdr (nth args body)))\n (setq args (1+ args))))\n (setq i (- i i++))\n )\n )\n</code></pre>\n" } ]
2008/10/17
[ "https://Stackoverflow.com/questions/213271", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1965/" ]
window.scrollMaxY can be set via that property in IE and older versions of Firefox, but when trying in FF3 it says "Cannot set this property as it only has a getter". What is my alternative? EDIT: The reason why I'm asking is that I'm fixing some very horrible JS written by someone else, it has a function to keep a div centered on the page while scrolling, and has this line: ``` // Fixes Firefox incrementing page height while scrolling window.scrollMaxY = scrollMaxY ``` Obviously this doesn't work, but the main issue is that when the page is scrolled, it grows in length.
First, I'm not sure that naming your function `t` is helping as 't' is used as the [truth value](http://www.mcs.vuw.ac.nz/cgi-bin/info2www?(elisp)nil+and+t) in lisp. That said, the following code works for me: ``` (defun test-func-1 () "test-func-1" (interactive "*") (insert-string "testing callers")) (defun func-caller (callee) "Execute callee" (funcall callee)) (func-caller 'test-func-1) ``` Please note the use of 'funcall', which triggers the actual function call.
213,295
<p>I'm storing an ArrayList of Ids in a processing script that I want to spit out as a comma delimited list for output to the debug log. Is there a way I can get this easily without looping through things?</p> <p>EDIT: Thanks to Joel for pointing out the List(Of T) that is available in .net 2.0 and above. That makes things TONS easier if you have it available.</p>
[ { "answer_id": 213305, "author": "Dillie-O", "author_id": 71, "author_profile": "https://Stackoverflow.com/users/71", "pm_score": 8, "selected": true, "text": "<p>Yes, I'm answering my own question, but I haven't found it here yet and thought this was a rather slick thing:</p>\n\n<p>...in VB.NET:</p>\n\n<pre><code>String.Join(\",\", CType(TargetArrayList.ToArray(Type.GetType(\"System.String\")), String()))\n</code></pre>\n\n<p>...in C#</p>\n\n<pre><code>string.Join(\",\", (string[])TargetArrayList.ToArray(Type.GetType(\"System.String\")))\n</code></pre>\n\n<p>The only \"gotcha\" to these is that the ArrayList must have the items stored as Strings if you're using Option Strict to make sure the conversion takes place properly.</p>\n\n<p>EDIT: If you're using .net 2.0 or above, simply create a List(Of String) type object and you can get what you need with. Many thanks to Joel for bringing this up!</p>\n\n<pre><code>String.Join(\",\", TargetList.ToArray())\n</code></pre>\n" }, { "answer_id": 213320, "author": "mspmsp", "author_id": 21724, "author_profile": "https://Stackoverflow.com/users/21724", "pm_score": 4, "selected": false, "text": "<p>Something like:</p>\n\n<pre><code>String.Join(\",\", myArrayList.toArray(string.GetType()) );\n</code></pre>\n\n<p>Which basically loops ya know...</p>\n\n<p><strong>EDIT</strong></p>\n\n<p>how about:</p>\n\n<pre><code>string.Join(\",\", Array.ConvertAll&lt;object, string&gt;(a.ToArray(), Convert.ToString));\n</code></pre>\n" }, { "answer_id": 213367, "author": "Echostorm", "author_id": 12862, "author_profile": "https://Stackoverflow.com/users/12862", "pm_score": 2, "selected": false, "text": "<pre><code>foo.ToArray().Aggregate((a, b) =&gt; (a + \",\" + b)).ToString()\n</code></pre>\n\n<p>or </p>\n\n<pre><code>string.Concat(foo.ToArray().Select(a =&gt; a += \",\").ToArray())\n</code></pre>\n\n<p>Updating, as this is extremely old. You should, of course, use string.Join now. It didn't exist as an option at the time of writing.</p>\n" }, { "answer_id": 213448, "author": "Konrad Rudolph", "author_id": 1968, "author_profile": "https://Stackoverflow.com/users/1968", "pm_score": 4, "selected": false, "text": "<p>The solutions so far are all quite complicated. The idiomatic solution should doubtless be:</p>\n\n<pre><code>String.Join(\",\", x.Cast(Of String)().ToArray())\n</code></pre>\n\n<p>There's no need for fancy acrobatics in new framework versions. Supposing a not-so-modern version, the following would be easiest:</p>\n\n<pre><code>Console.WriteLine(String.Join(\",\", CType(x.ToArray(GetType(String)), String())))\n</code></pre>\n\n<p>mspmsp's second solution is a nice approach as well but it's not working because it misses the <code>AddressOf</code> keyword. Also, <code>Convert.ToString</code> is rather inefficient (lots of unnecessary internal evaluations) and the <code>Convert</code> class is generally not very cleanly designed. I tend to avoid it, especially since it's completely redundant.</p>\n" }, { "answer_id": 10191829, "author": "Jim Lahman", "author_id": 584962, "author_profile": "https://Stackoverflow.com/users/584962", "pm_score": 2, "selected": false, "text": "<p>Here's a simple example demonstrating the creation of a comma delimited string using String.Join() from a list of Strings:</p>\n\n<pre><code>List&lt;string&gt; histList = new List&lt;string&gt;();\nhistList.Add(dt.ToString(\"MM/dd/yyyy::HH:mm:ss.ffff\"));\nhistList.Add(Index.ToString());\n/*arValue is array of Singles */\nforeach (Single s in arValue)\n{\n histList.Add(s.ToString());\n}\nString HistLine = String.Join(\",\", histList.ToArray());\n</code></pre>\n" }, { "answer_id": 35198293, "author": "bashburak", "author_id": 5882534, "author_profile": "https://Stackoverflow.com/users/5882534", "pm_score": 3, "selected": false, "text": "<p><code>string.Join(\" ,\", myArrayList.ToArray());</code> This will work with .net framework 4.5</p>\n" }, { "answer_id": 65640025, "author": "Monzur", "author_id": 1331294, "author_profile": "https://Stackoverflow.com/users/1331294", "pm_score": 0, "selected": false, "text": "<p>So far I found this is a good and quick solution</p>\n<pre><code>//CPID[] is the array\nstring cps = &quot;&quot;;\nif (CPID.Length &gt; 0)\n{ \n foreach (var item in CPID)\n {\n cps += item.Trim() + &quot;,&quot;;\n }\n}\n//Use the string cps\n</code></pre>\n" } ]
2008/10/17
[ "https://Stackoverflow.com/questions/213295", "https://Stackoverflow.com", "https://Stackoverflow.com/users/71/" ]
I'm storing an ArrayList of Ids in a processing script that I want to spit out as a comma delimited list for output to the debug log. Is there a way I can get this easily without looping through things? EDIT: Thanks to Joel for pointing out the List(Of T) that is available in .net 2.0 and above. That makes things TONS easier if you have it available.
Yes, I'm answering my own question, but I haven't found it here yet and thought this was a rather slick thing: ...in VB.NET: ``` String.Join(",", CType(TargetArrayList.ToArray(Type.GetType("System.String")), String())) ``` ...in C# ``` string.Join(",", (string[])TargetArrayList.ToArray(Type.GetType("System.String"))) ``` The only "gotcha" to these is that the ArrayList must have the items stored as Strings if you're using Option Strict to make sure the conversion takes place properly. EDIT: If you're using .net 2.0 or above, simply create a List(Of String) type object and you can get what you need with. Many thanks to Joel for bringing this up! ``` String.Join(",", TargetList.ToArray()) ```
213,299
<p>I've implemented a .NET Web control that uses the callback structure implemented in ASP.Net 2.0. It's an autodropdown control, and it works correctly in IE 6.0/7.0 and Google Chrome. Here's the relevant callback function:</p> <pre><code>function ReceiveServerData(args, context) { document.getElementById(context).style.zIndex = 300; document.getElementById(context).style.visibility = 'visible'; document.getElementById(context).innerHTML = args; fixHover(context); } </code></pre> <p>In Firefox, "args" is always the same data, so the innerHTML of the <code>&lt;div&gt;</code> that is the display for my dropdown always shows the same items. I've doublechecked my client-side code, and the right information is being sent client->server and in return server-> client.</p> <p>Of note, in the "WebForm_DoCallback" function created by the .NET framework, the following snippet is getting called:</p> <pre><code>if (setRequestHeaderMethodExists) { xmlRequest.onreadystatechange = WebForm_CallbackComplete; callback.xmlRequest = xmlRequest; xmlRequest.open("POST", theForm.action, true); xmlRequest.setRequestHeader("Content-Type", "application/x-www-form-urlencoded"); xmlRequest.send(postData); return; } </code></pre> <p>and the callback function ReceiveServerData is called both on <code>xmlRequest.open("POST", theForm.action, true);</code> and <code>xmlRequest.send(postData);</code>. I wonder if this is causing an error, but I'm at the end of my debugging skills.</p> <p>Edited to add -- ReceiveServerData is not being called twice the very first time I use the dropdown -- in fact, the dropdown works correctly for the very first keystroke. It stops working, and doubles the callback with old return data, after the first keystroke.</p>
[ { "answer_id": 220090, "author": "Atanas Korchev", "author_id": 10141, "author_profile": "https://Stackoverflow.com/users/10141", "pm_score": 0, "selected": false, "text": "<p>I am not sure if this would help but I have patched the ASP.NET 2.0 callbacks like this (minified code):</p>\n\n<pre><code>function WebForm_CallbackComplete()\n{\n for(var i=0; i&lt; __pendingCallbacks.length;i++)\n {\n var _f3=__pendingCallbacks[i];\n if(_f3 &amp;&amp; _f3.xmlRequest &amp;&amp; (_f3.xmlRequest.readyState==4))\n {\n __pendingCallbacks[i]=null;\n WebForm_ExecuteCallback(_f3);\n if(!_f3.async)\n {\n __synchronousCallBackIndex=-1;\n }\n var _f4=\"__CALLBACKFRAME\"+i;\n var _f5=document.getElementById(_f4);\n if(_f5)\n {\n _f5.parentNode.removeChild(_f5);\n }\n }\n }\n}\n</code></pre>\n\n<p>If you check the actual implementation of WebForm_CallbackComplete you would spot a few issues. You can try pasting that JavaScript within your form tag to see if it would make a difference.</p>\n" }, { "answer_id": 220713, "author": "Brendan Kowitz", "author_id": 25767, "author_profile": "https://Stackoverflow.com/users/25767", "pm_score": 0, "selected": false, "text": "<p>I think you need to provide more information, it's probably unlikely that this problem is because of asp.net's built-in js. How is the event being set up to catch keystrokes, are you accidently adding events? How it the scriptservice being called? Just double check all the basics to make sure it's not something crazy and simple like that.</p>\n" }, { "answer_id": 971813, "author": "Ken Smith", "author_id": 68231, "author_profile": "https://Stackoverflow.com/users/68231", "pm_score": 1, "selected": false, "text": "<p>For what it's worth, the MS AJAX Function.createCallback() doesn't seem to work correctly in FireFox. See this post here, with repro code:</p>\n\n<p><a href=\"https://stackoverflow.com/questions/969326/function-createcallback-doesnt-pass-context-correctly-in-firefox/969362#969362\">Function.createCallback doesn&#39;t pass context correctly in FireFox</a></p>\n\n<p>It appears that the context variable loses its state when it's passed to the callback function.</p>\n" } ]
2008/10/17
[ "https://Stackoverflow.com/questions/213299", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11947/" ]
I've implemented a .NET Web control that uses the callback structure implemented in ASP.Net 2.0. It's an autodropdown control, and it works correctly in IE 6.0/7.0 and Google Chrome. Here's the relevant callback function: ``` function ReceiveServerData(args, context) { document.getElementById(context).style.zIndex = 300; document.getElementById(context).style.visibility = 'visible'; document.getElementById(context).innerHTML = args; fixHover(context); } ``` In Firefox, "args" is always the same data, so the innerHTML of the `<div>` that is the display for my dropdown always shows the same items. I've doublechecked my client-side code, and the right information is being sent client->server and in return server-> client. Of note, in the "WebForm\_DoCallback" function created by the .NET framework, the following snippet is getting called: ``` if (setRequestHeaderMethodExists) { xmlRequest.onreadystatechange = WebForm_CallbackComplete; callback.xmlRequest = xmlRequest; xmlRequest.open("POST", theForm.action, true); xmlRequest.setRequestHeader("Content-Type", "application/x-www-form-urlencoded"); xmlRequest.send(postData); return; } ``` and the callback function ReceiveServerData is called both on `xmlRequest.open("POST", theForm.action, true);` and `xmlRequest.send(postData);`. I wonder if this is causing an error, but I'm at the end of my debugging skills. Edited to add -- ReceiveServerData is not being called twice the very first time I use the dropdown -- in fact, the dropdown works correctly for the very first keystroke. It stops working, and doubles the callback with old return data, after the first keystroke.
For what it's worth, the MS AJAX Function.createCallback() doesn't seem to work correctly in FireFox. See this post here, with repro code: [Function.createCallback doesn't pass context correctly in FireFox](https://stackoverflow.com/questions/969326/function-createcallback-doesnt-pass-context-correctly-in-firefox/969362#969362) It appears that the context variable loses its state when it's passed to the callback function.
213,303
<p>There are many tools out there for writing and managing requirements, but are there any good ones for reviewing them? </p> <p>I'm not talking about <strong><em>managing</em></strong> reviews, but automation tools that look for common requirement blunders (such as using negative requirements, or ones that are worded in a way that makes testing difficult).<br> More of a screening tool that someone writing requirements can use to screen their document before distributing to a group of reviewers so that the review process need not be slowed down by everyone commenting on the same easily recognizable issues.</p> <p>I'm curious if anyone's used anything like this in the past.</p>
[ { "answer_id": 213452, "author": "kenny", "author_id": 3225, "author_profile": "https://Stackoverflow.com/users/3225", "pm_score": 3, "selected": true, "text": "<p>I'm working on a console application that takes a xml configuration file like this:</p>\n\n<pre><code>&lt;?xml version=\"1.0\" encoding=\"utf-8\"?&gt;\n&lt;ReqCheck&gt;\n &lt;Categories name=\"Reconsider wording\"&gt;\n &lt;Keyword&gt;may&lt;/Keyword&gt;\n &lt;Keyword&gt;should&lt;/Keyword&gt;\n &lt;/Categories&gt;\n &lt;Categories name=\"Potential logic problem\" format=\"{0}: consider both then and else conditions.\"&gt;\n &lt;Keyword&gt;not&lt;/Keyword&gt;\n &lt;/Categories&gt;\n&lt;/ReqCheck&gt;\n</code></pre>\n\n<p>The application takes a MS-Word document and adds 'balloon-style' comments to the document. </p>\n" }, { "answer_id": 236267, "author": "Yarik", "author_id": 31415, "author_profile": "https://Stackoverflow.com/users/31415", "pm_score": 0, "selected": false, "text": "<p>You might want to take a look at <a href=\"http://www.ravenflow.com/\" rel=\"nofollow noreferrer\">Ravenflow products</a>. I did not try them myself yet, but their features seem to be very close to what you are looking for...</p>\n\n<p><strong>NB:</strong> Ravenflow products are likely to be prohibitively expensive for small- and even medium-size teams/companies...</p>\n" } ]
2008/10/17
[ "https://Stackoverflow.com/questions/213303", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2382102/" ]
There are many tools out there for writing and managing requirements, but are there any good ones for reviewing them? I'm not talking about ***managing*** reviews, but automation tools that look for common requirement blunders (such as using negative requirements, or ones that are worded in a way that makes testing difficult). More of a screening tool that someone writing requirements can use to screen their document before distributing to a group of reviewers so that the review process need not be slowed down by everyone commenting on the same easily recognizable issues. I'm curious if anyone's used anything like this in the past.
I'm working on a console application that takes a xml configuration file like this: ``` <?xml version="1.0" encoding="utf-8"?> <ReqCheck> <Categories name="Reconsider wording"> <Keyword>may</Keyword> <Keyword>should</Keyword> </Categories> <Categories name="Potential logic problem" format="{0}: consider both then and else conditions."> <Keyword>not</Keyword> </Categories> </ReqCheck> ``` The application takes a MS-Word document and adds 'balloon-style' comments to the document.
213,309
<p>Is it possible to create, for instance, a box model hack while using in-line CSS?</p> <p>For example:</p> <p><code>&lt;div id="blah" style="padding: 5px; margin: 5px; width: 30px; /*IE5-6 Equivalent here*/"&gt;</code></p> <p>Thanks! </p>
[ { "answer_id": 213342, "author": "eyelidlessness", "author_id": 17964, "author_profile": "https://Stackoverflow.com/users/17964", "pm_score": 0, "selected": false, "text": "<p>The most appropriate answer is <strong>don't</strong>. (Edit: to be clear, I mean don't do it inline, I don't mean don't use CSS hacks.)</p>\n\n<p>Edit: This doesn't work, IE ignores the conditional comment. Leaving the answer here to not be a bastard.</p>\n\n<p>The next most appropriate answer is conditional comments:</p>\n\n<pre><code>&lt;div id=\"blah\" style=\"padding: 5px; margin: 5px; width: 30px; &lt;!--[if lte IE 6]&gt; ... &lt;![endif]--&gt;\"&gt;\n</code></pre>\n" }, { "answer_id": 213351, "author": "alexp206", "author_id": 666, "author_profile": "https://Stackoverflow.com/users/666", "pm_score": 2, "selected": false, "text": "<p>Without arguing for or against CSS hacks, personally if I needed to do something like that, I would prefer to use a conditional comment:</p>\n\n<pre><code>&lt;!--[if lt IE 7]&gt;\n&lt;style&gt;\n#blah {\npadding: 5px;\nmargin: 5px;\nwidth: 30px;\n}\n&lt;/style&gt;\n&lt;![endif]--&gt;\n</code></pre>\n" }, { "answer_id": 213458, "author": "John Dunagan", "author_id": 28939, "author_profile": "https://Stackoverflow.com/users/28939", "pm_score": 3, "selected": false, "text": "<p>I'd go outside - slap a class on that element, or use the ID you have, and handle the styling externally.</p>\n\n<p>I'd also concur with the conditional comments answers preceding mine.</p>\n\n<p>That said: As an <strong>absolute</strong> last resort, you can use the following style hacks to target &lt;= IE6, and even IE7. The trouble comes when/if they fix IE8 to defeat your hack.</p>\n\n<pre><code>.foo {\npadding: 5px;\n^padding: 4px; /* this targets all IE, including 7. It must go first, or it overrides the following hack */\n_padding: 3px; /* this targets &gt;= IE6 */\nwidth: 30px;\n}\n</code></pre>\n\n<p>Good luck.</p>\n" }, { "answer_id": 213612, "author": "Atanas Korchev", "author_id": 10141, "author_profile": "https://Stackoverflow.com/users/10141", "pm_score": 4, "selected": false, "text": "<p>You can use the \"prefixing\" hack in inline styles as well:</p>\n\n<pre><code>&lt;div style=\"*background:red\"&gt;&lt;/div&gt;\n</code></pre>\n\n<p>Just make sure you put the IE hacks at the end of the style attribute. However I second the opinion that inline styles should be avoided when possible. Conditional comments and a separate CSS file for Internet Explorer seem to be the best way to handle such issues.</p>\n" }, { "answer_id": 213673, "author": "savetheclocktower", "author_id": 25720, "author_profile": "https://Stackoverflow.com/users/25720", "pm_score": 0, "selected": false, "text": "<p>Keep in mind that IE 6 needs the box model hack <em>in quirks mode</em> but not <em>in standards mode</em>. IE 5 and IE 5.5 need the BMH all the time.</p>\n\n<p>So if you're in standards mode, you'll need to use something like <a href=\"http://tantek.com/CSS/Examples/boxmodelhack.html\" rel=\"nofollow noreferrer\">the original <code>voice-family</code> hack</a> (which targets IE 5.X and <em>not</em> IE 6). If you're in quirks mode, any old IE &lt;= 6 hack will do.</p>\n\n<p>(The content of your question suggests to me that your page renders in quirks mode.) </p>\n" }, { "answer_id": 214048, "author": "Paul M", "author_id": 28241, "author_profile": "https://Stackoverflow.com/users/28241", "pm_score": 0, "selected": false, "text": "<p>Yeah like everyone above, if you can avoid doing it inline do!! But if you really need to go inline then parser filters are probably your best bet, these are certain characters you can use on properties such as the underscore hack in ie6</p>\n\n<pre><code>print(\"code sample\");\n\n style=\"position:relative;padding:5px; _position:absolute; _padding:10px;\" \n</code></pre>\n\n<p>ie6 will still get the underscored styles, everyone else will just ignore them!</p>\n\n<p>There is also using !important instead of underscore.</p>\n\n<p>have a play around and see what happens, but again like above, try and avoid like the plague :)</p>\n" }, { "answer_id": 2510607, "author": "Gabriel Hurley", "author_id": 114672, "author_profile": "https://Stackoverflow.com/users/114672", "pm_score": 0, "selected": false, "text": "<p>The best solution is to work in Standards Mode rather than Quirks Mode.... that'll eliminate the need for the majority of your box model hacks right away.</p>\n\n<p>Beyond that, conditional comments with an IE-specific stylesheet are far cleaner and more maintainable. That method has been good enough for most every top-notch designer for the last several years... unless there's something specific about your site that requires it all to be inline I suggest taking a step back and looking at the root problems instead of how you can patch these little symptoms as they appear.<a href=\"http://sonicloft.net/im/52\" rel=\"nofollow noreferrer\">alt text http://sonicloft.net/im/52</a></p>\n" } ]
2008/10/17
[ "https://Stackoverflow.com/questions/213309", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
Is it possible to create, for instance, a box model hack while using in-line CSS? For example: `<div id="blah" style="padding: 5px; margin: 5px; width: 30px; /*IE5-6 Equivalent here*/">` Thanks!
You can use the "prefixing" hack in inline styles as well: ``` <div style="*background:red"></div> ``` Just make sure you put the IE hacks at the end of the style attribute. However I second the opinion that inline styles should be avoided when possible. Conditional comments and a separate CSS file for Internet Explorer seem to be the best way to handle such issues.
213,333
<p>I have a generic class in C# with 2 constructors:</p> <pre><code>public Houses(params T[] InitialiseElements) {} public Houses(int Num, T DefaultValue) {} </code></pre> <p>Constructing an object using int as the generic type and passing in two ints as arguments causes the 'incorrect' constructor to be called (from my point of view).</p> <p>E.g. <code>Houses&lt;int&gt; houses = new Houses&lt;int&gt;(1,2)</code> - calls the 2nd construtor. Passing in any other number of ints into the constructor will call the 1st constructor.</p> <p>Is there any way around this other than removing the params keyword and forcing users to pass an array of T when using the first constructor?</p>
[ { "answer_id": 213354, "author": "Jon B", "author_id": 27414, "author_profile": "https://Stackoverflow.com/users/27414", "pm_score": 2, "selected": false, "text": "<p>Perhaps instead of Params you could pass in IEnumerable</p>\n\n<pre><code>public Houses(IEnumerable&lt;T&gt; InitialiseElements){}\n</code></pre>\n" }, { "answer_id": 213355, "author": "Joel Coehoorn", "author_id": 3043, "author_profile": "https://Stackoverflow.com/users/3043", "pm_score": 2, "selected": false, "text": "<p>The 2nd constructor is a more <em>exact</em> match, which is the criteria used to evaluate which constructor is correct.</p>\n" }, { "answer_id": 213403, "author": "Jon Skeet", "author_id": 22656, "author_profile": "https://Stackoverflow.com/users/22656", "pm_score": 5, "selected": true, "text": "<p>A clearer solution would be to have two static factory methods. If you put these into a nongeneric class, you can also benefit from type inference:</p>\n\n<pre><code>public static class Houses\n{\n public static Houses&lt;T&gt; CreateFromElements&lt;T&gt;(params T[] initialElements)\n {\n return new Houses&lt;T&gt;(initialElements);\n }\n\n public Houses&lt;T&gt; CreateFromDefault&lt;T&gt;(int count, T defaultValue)\n {\n return new Houses&lt;T&gt;(count, defaultValue);\n }\n}\n</code></pre>\n\n<p>Example of calling:</p>\n\n<pre><code>Houses&lt;string&gt; x = Houses.CreateFromDefault(10, \"hi\");\nHouses&lt;int&gt; y = Houses.CreateFromElements(20, 30, 40);\n</code></pre>\n\n<p>Then your generic type's constructor doesn't need the \"params\" bit, and there'll be no confusion.</p>\n" }, { "answer_id": 213807, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 2, "selected": false, "text": "<p>Given the following since the original did not have too much information on the class etc.</p>\n\n<p>The compiler is going to decide new House(1,2) matches the second constructor exactly and use that, notice that I took the answer with the most up votes and it did not work.</p>\n\n<pre><code>using System;\nusing System.Collections.Generic;\nusing System.Linq;\nusing System.Text;\n\nnamespace GenericTest\n{\n public class House&lt;T&gt;\n {\n public House(params T[] values)\n {\n System.Console.WriteLine(\"Params T[]\");\n }\n public House(int num, T defaultVal)\n {\n System.Console.WriteLine(\"int, T\");\n }\n\n public static House&lt;T&gt; CreateFromDefault&lt;T&gt;(int count, T defaultVal)\n {\n return new House&lt;T&gt;(count, defaultVal);\n }\n }\n\n class Program\n {\n static void Main(string[] args)\n {\n House&lt;int&gt; test = new House&lt;int&gt;(1, 2); // prints int, t\n House&lt;int&gt; test1 = new House&lt;int&gt;(new int[] {1, 2}); // prints parms\n House&lt;string&gt; test2 = new House&lt;string&gt;(1, \"string\"); // print int, t\n House&lt;string&gt; test3 = new House&lt;string&gt;(\"string\", \"string\"); // print parms\n House&lt;int&gt; test4 = House&lt;int&gt;.CreateFromDefault&lt;int&gt;(1, 2); // print int, t\n }\n }\n}\n</code></pre>\n" } ]
2008/10/17
[ "https://Stackoverflow.com/questions/213333", "https://Stackoverflow.com", "https://Stackoverflow.com/users/29059/" ]
I have a generic class in C# with 2 constructors: ``` public Houses(params T[] InitialiseElements) {} public Houses(int Num, T DefaultValue) {} ``` Constructing an object using int as the generic type and passing in two ints as arguments causes the 'incorrect' constructor to be called (from my point of view). E.g. `Houses<int> houses = new Houses<int>(1,2)` - calls the 2nd construtor. Passing in any other number of ints into the constructor will call the 1st constructor. Is there any way around this other than removing the params keyword and forcing users to pass an array of T when using the first constructor?
A clearer solution would be to have two static factory methods. If you put these into a nongeneric class, you can also benefit from type inference: ``` public static class Houses { public static Houses<T> CreateFromElements<T>(params T[] initialElements) { return new Houses<T>(initialElements); } public Houses<T> CreateFromDefault<T>(int count, T defaultValue) { return new Houses<T>(count, defaultValue); } } ``` Example of calling: ``` Houses<string> x = Houses.CreateFromDefault(10, "hi"); Houses<int> y = Houses.CreateFromElements(20, 30, 40); ``` Then your generic type's constructor doesn't need the "params" bit, and there'll be no confusion.
213,360
<p>I have a Dictionary where I hold data for movieclips, and I want the data to be garbage collected if I stop using the movieclips. I'm using the weak keys parameters, and it works perfectly with other data, however I've run into a problem. </p> <p>This code works great:</p> <pre><code>var mc = new MovieClip(); var dic = new Dictionary(true); dic[mc] = 12; mc = null; System.gc(); System.gc(); for (var obj in dic) trace(obj); //this doesn't execute </code></pre> <p>But when I actually use the movieclip, it stops working:</p> <pre><code>var mc = new MovieClip(); var dic = new Dictionary(true); dic[mc] = 12; addChild(mc); removeChild(mc); mc = null; System.gc(); System.gc(); for (var obj in dic) trace(obj); //this prints [object Movieclip] </code></pre> <p>Why does this happen? Is it something I'm doing wrong? Is there a workaround?</p> <p>Edit: I know that for this specific example I can use <code>delete dic[mc]</code>, but of course this is a simplified case. In general, I don't want to manually have to remove the movieclip from the dictionary, but it should be automatic when I don't reference it anymore in the rest of the application.</p> <p>Edit2: I tried testing what Aaron said, and came up with just weird stuff... just iterating the dictionary (without doing anything) changes the behaviour:</p> <pre><code>var mc = new MovieClip(); var dic = new Dictionary(true); dic[mc] = 12; addChild(mc); removeChild(mc); mc = null; for (var objeto in dic) {} // &lt;-- try commenting out this line addEventListener('enterFrame', f); // I print the contents every frame, to see if // it gets removed after awhile function f(evento) { System.gc(); System.gc(); for (var objeto in dic) trace(objeto); } </code></pre> <p>This keeps printing [object Movieclip] every frame, unless I comment out the indicated line, where it doesn't print anything.</p>
[ { "answer_id": 213513, "author": "Aaron H.", "author_id": 16258, "author_profile": "https://Stackoverflow.com/users/16258", "pm_score": 2, "selected": true, "text": "<p>I believe that the problem is one of timing. I think that when you call remove child, the reference count isn't getting updated until later in the \"frame\". (I think this is what is happening anyway.)</p>\n\n<p>The code below demonstrates why I think this is true. (I'm using flex, but it appears to reproduce your issue.)</p>\n\n<p>The code below outputs: </p>\n\n<pre><code>[object MovieClip]\nhere\n</code></pre>\n\n<p>If you call otherfoo directly at the end of somefoo(), you get:</p>\n\n<pre><code>[object MovieClip]\nhere\n[object MovieClip]\n</code></pre>\n\n<hr>\n\n<pre><code>&lt;?xml version=\"1.0\" encoding=\"utf-8\"?&gt;\n&lt;mx:Application xmlns:mx=\"http://www.adobe.com/2006/mxml\" layout=\"absolute\" mouseDown=\"somefoo()\"&gt;\n&lt;mx:Script&gt;\n &lt;![CDATA[\n import mx.core.UIComponent;\n private var dic:Dictionary = new Dictionary(true);\n private var ui:UIComponent = new UIComponent();\n private var mc:MovieClip = new MovieClip();\n\n private function somefoo():void {\n this.addChild(ui);\n\n dic[mc] = 12;\n ui.addChild(mc);\n ui.removeChild(mc);\n for (var obj:Object in dic)\n trace(obj); //this prints [MovieClip]\n\n this.removeChild(ui);\n\n // callLater causes the function to be called in the _next_ frame.\n callLater(otherfoo);\n }\n\n private function otherfoo():void\n {\n trace(\"here\");\n mc = null;\n System.gc();\n System.gc();\n\n for (var obj:Object in dic)\n trace(obj); //this prints [MovieClip]\n\n }\n ]]&gt;\n&lt;/mx:Script&gt;\n&lt;/mx:Application&gt;\n</code></pre>\n" }, { "answer_id": 213669, "author": "Antti", "author_id": 6037, "author_profile": "https://Stackoverflow.com/users/6037", "pm_score": 0, "selected": false, "text": "<p>In you're example code here you're never adding the movieclip to the dictionary, but the int 12 instead? Probably a typo.</p>\n\n<p>If you want the dictionary to have a list of what's currently on the stage, why not have i as a util class instead that listens to Event.ADDED_TO_STAGE and Event.REMOVED_FROM_STAGE and modify the dictionary accordingly? A dictionary doesn't automatically delete references if they get removed from the stage. Also gc in this case has nothing to do with this.</p>\n" } ]
2008/10/17
[ "https://Stackoverflow.com/questions/213360", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1815/" ]
I have a Dictionary where I hold data for movieclips, and I want the data to be garbage collected if I stop using the movieclips. I'm using the weak keys parameters, and it works perfectly with other data, however I've run into a problem. This code works great: ``` var mc = new MovieClip(); var dic = new Dictionary(true); dic[mc] = 12; mc = null; System.gc(); System.gc(); for (var obj in dic) trace(obj); //this doesn't execute ``` But when I actually use the movieclip, it stops working: ``` var mc = new MovieClip(); var dic = new Dictionary(true); dic[mc] = 12; addChild(mc); removeChild(mc); mc = null; System.gc(); System.gc(); for (var obj in dic) trace(obj); //this prints [object Movieclip] ``` Why does this happen? Is it something I'm doing wrong? Is there a workaround? Edit: I know that for this specific example I can use `delete dic[mc]`, but of course this is a simplified case. In general, I don't want to manually have to remove the movieclip from the dictionary, but it should be automatic when I don't reference it anymore in the rest of the application. Edit2: I tried testing what Aaron said, and came up with just weird stuff... just iterating the dictionary (without doing anything) changes the behaviour: ``` var mc = new MovieClip(); var dic = new Dictionary(true); dic[mc] = 12; addChild(mc); removeChild(mc); mc = null; for (var objeto in dic) {} // <-- try commenting out this line addEventListener('enterFrame', f); // I print the contents every frame, to see if // it gets removed after awhile function f(evento) { System.gc(); System.gc(); for (var objeto in dic) trace(objeto); } ``` This keeps printing [object Movieclip] every frame, unless I comment out the indicated line, where it doesn't print anything.
I believe that the problem is one of timing. I think that when you call remove child, the reference count isn't getting updated until later in the "frame". (I think this is what is happening anyway.) The code below demonstrates why I think this is true. (I'm using flex, but it appears to reproduce your issue.) The code below outputs: ``` [object MovieClip] here ``` If you call otherfoo directly at the end of somefoo(), you get: ``` [object MovieClip] here [object MovieClip] ``` --- ``` <?xml version="1.0" encoding="utf-8"?> <mx:Application xmlns:mx="http://www.adobe.com/2006/mxml" layout="absolute" mouseDown="somefoo()"> <mx:Script> <![CDATA[ import mx.core.UIComponent; private var dic:Dictionary = new Dictionary(true); private var ui:UIComponent = new UIComponent(); private var mc:MovieClip = new MovieClip(); private function somefoo():void { this.addChild(ui); dic[mc] = 12; ui.addChild(mc); ui.removeChild(mc); for (var obj:Object in dic) trace(obj); //this prints [MovieClip] this.removeChild(ui); // callLater causes the function to be called in the _next_ frame. callLater(otherfoo); } private function otherfoo():void { trace("here"); mc = null; System.gc(); System.gc(); for (var obj:Object in dic) trace(obj); //this prints [MovieClip] } ]]> </mx:Script> </mx:Application> ```
213,368
<p>I want to write a script, to be packaged into a gem, which will modify its parameters and then <code>exec</code> a new ruby process with the modified params. In other words, something similar to a shell script which modifies its params and then does an <code>exec $SHELL $*</code>. In order to do this, I need a robust way of discovering the path of the ruby executable which is executing the current script. I also need to get the full parameters passed to the current process - both the Ruby parameters and the script arguments. </p>
[ { "answer_id": 216242, "author": "Vitalie", "author_id": 27913, "author_profile": "https://Stackoverflow.com/users/27913", "pm_score": 3, "selected": false, "text": "<p>If you want to check on linux: read files:</p>\n\n<ul>\n<li>/proc/PID/exe </li>\n<li>/proc/PID/cmdline</li>\n</ul>\n\n<p>Other useful info can be found in /proc/PID dir</p>\n" }, { "answer_id": 1600492, "author": "rogerdpack", "author_id": 32453, "author_profile": "https://Stackoverflow.com/users/32453", "pm_score": 0, "selected": false, "text": "<p>For the script parameters, of course, use <code>ARGV</code>.</p>\n" }, { "answer_id": 11477062, "author": "Avdi", "author_id": 20487, "author_profile": "https://Stackoverflow.com/users/20487", "pm_score": 4, "selected": true, "text": "<p>The Rake source code does it like this:</p>\n\n<pre><code> RUBY = File.join(Config::CONFIG['bindir'], Config::CONFIG['ruby_install_name']).\n sub(/.*\\s.*/m, '\"\\&amp;\"')\n</code></pre>\n" }, { "answer_id": 73394452, "author": "Michiel de Mare", "author_id": 136, "author_profile": "https://Stackoverflow.com/users/136", "pm_score": 0, "selected": false, "text": "<p><code>File.join(RbConfig::CONFIG['bindir'], RbConfig::CONFIG['ruby_install_name'])</code></p>\n" } ]
2008/10/17
[ "https://Stackoverflow.com/questions/213368", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20487/" ]
I want to write a script, to be packaged into a gem, which will modify its parameters and then `exec` a new ruby process with the modified params. In other words, something similar to a shell script which modifies its params and then does an `exec $SHELL $*`. In order to do this, I need a robust way of discovering the path of the ruby executable which is executing the current script. I also need to get the full parameters passed to the current process - both the Ruby parameters and the script arguments.
The Rake source code does it like this: ``` RUBY = File.join(Config::CONFIG['bindir'], Config::CONFIG['ruby_install_name']). sub(/.*\s.*/m, '"\&"') ```
213,375
<p>I am trying to create a new instance of Excel using VBA using:</p> <pre class="lang-vb prettyprint-override"><code>Set XlApp = New Excel.Application </code></pre> <p>The problem is that this new instance of Excel doesn't load all the addins that load when I open Excel normally...Is there anything in the Excel Application object for loading in all the user-specified addins?</p> <p>I'm not trying to load a specific add-in, but rather make the new Excel application behave as though the user opened it themself, so I'm really looking for a list of all the user-selected add-ins that usually load when opening Excel.</p>
[ { "answer_id": 214006, "author": "Mike Rosenblum", "author_id": 10429, "author_profile": "https://Stackoverflow.com/users/10429", "pm_score": 3, "selected": false, "text": "<p>Using <code>CreateObject(\"Excel.Application\")</code> would have the same result as using <code>New Excel.Application</code>, unfortunately.</p>\n\n<p>You will have to load the Addins that you need individually by file path &amp; name using the <code>Application.Addins.Add(string fileName)</code> method.</p>\n" }, { "answer_id": 806720, "author": "Jon Fournier", "author_id": 5106, "author_profile": "https://Stackoverflow.com/users/5106", "pm_score": 6, "selected": true, "text": "<p>I looked into this problem again, and the Application.Addins collection seems to have all the addins listed in the Tools->Addins menu, with a boolean value stating whether or not an addin is installed. So what seems to work for me now is to loop through all addins and if .Installed = true then I set .Installed to False and back to True, and that seems to properly load my addins.</p>\n\n<pre><code>Function ReloadXLAddins(TheXLApp As Excel.Application) As Boolean\n\n Dim CurrAddin As Excel.AddIn\n\n For Each CurrAddin In TheXLApp.AddIns\n If CurrAddin.Installed Then\n CurrAddin.Installed = False\n CurrAddin.Installed = True\n End If\n Next CurrAddin\n\nEnd Function\n</code></pre>\n" }, { "answer_id": 16969757, "author": "Ben Brandt", "author_id": 641985, "author_profile": "https://Stackoverflow.com/users/641985", "pm_score": 2, "selected": false, "text": "<p>I'm leaving this answer here for anyone else who ran into this problem, but using JavaScript.</p>\n\n<p>A little background... In my company we have a 3rd party web app that used JavaScript to launch Excel and generate a spreadsheet on the fly. We also have an Excel add-in that overrides the behavior of the Save button. The add-in gives you the option of saving the file locally or in our online document management system.</p>\n\n<p>After we upgraded to Windows 7 and Office 2010, we noticed a problem with our spreadsheet-generating web app. When JavaScript generated a spreadsheet in Excel, suddenly the Save button no longer worked. You would click save and nothing happened.</p>\n\n<p>Using the other answers here I was able to construct a solution in JavaScript. Essentially we would create the Excel Application object in memory, then reload a specific add-in to get our save button behavior back. Here's a simplified version of our fix:</p>\n\n<pre><code>function GenerateSpreadsheet()\n{\n var ExcelApp = getExcel();\n if (ExcelApp == null){ return; }\n\n reloadAddIn(ExcelApp);\n\n ExcelApp.WorkBooks.Add;\n ExcelApp.Visible = true;\n sheet = ExcelApp.ActiveSheet;\n\n var now = new Date();\n ExcelApp.Cells(1,1).value = 'This is an auto-generated spreadsheet, created using Javascript and ActiveX in Internet Explorer';\n\n ExcelApp.ActiveSheet.Columns(\"A:IV\").EntireColumn.AutoFit; \n ExcelApp.ActiveSheet.Rows(\"1:65536\").EntireRow.AutoFit;\n ExcelApp.ActiveSheet.Range(\"A1\").Select;\n\n ExcelApp = null;\n}\n\nfunction getExcel() {\n try {\n return new ActiveXObject(\"Excel.Application\");\n } catch(e) {\n alert(\"Unable to open Excel. Please check your security settings.\");\n return null;\n }\n}\n\nfunction reloadAddIn(ExcelApp) {\n // Fixes problem with save button not working in Excel,\n // by reloading the add-in responsible for the custom save button behavior\n try {\n ExcelApp.AddIns2.Item(\"AddInName\").Installed = false;\n ExcelApp.AddIns2.Item(\"AddInName\").Installed = true;\n } catch (e) { }\n}\n</code></pre>\n" } ]
2008/10/17
[ "https://Stackoverflow.com/questions/213375", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5106/" ]
I am trying to create a new instance of Excel using VBA using: ```vb Set XlApp = New Excel.Application ``` The problem is that this new instance of Excel doesn't load all the addins that load when I open Excel normally...Is there anything in the Excel Application object for loading in all the user-specified addins? I'm not trying to load a specific add-in, but rather make the new Excel application behave as though the user opened it themself, so I'm really looking for a list of all the user-selected add-ins that usually load when opening Excel.
I looked into this problem again, and the Application.Addins collection seems to have all the addins listed in the Tools->Addins menu, with a boolean value stating whether or not an addin is installed. So what seems to work for me now is to loop through all addins and if .Installed = true then I set .Installed to False and back to True, and that seems to properly load my addins. ``` Function ReloadXLAddins(TheXLApp As Excel.Application) As Boolean Dim CurrAddin As Excel.AddIn For Each CurrAddin In TheXLApp.AddIns If CurrAddin.Installed Then CurrAddin.Installed = False CurrAddin.Installed = True End If Next CurrAddin End Function ```
213,411
<p>I have tree tables, Customer, Invoice and InvoiceRow with the standard relations. </p> <p>These I have to export in one fixed field length file with the first two characters of each row identifying the row type. The row types have different specifications.</p> <p>I could probably do it with a nested loop in a script block, but this is my first ever SSIS package and that solution feels wrong.</p> <p>edit:</p> <p>The output has to have: </p> <pre><code>Customer Invoice Rows Customer Invoice Rows and so on </code></pre>
[ { "answer_id": 213432, "author": "Harper Shelby", "author_id": 21196, "author_profile": "https://Stackoverflow.com/users/21196", "pm_score": 0, "selected": false, "text": "<p>Process your three tables so that the outputs are all appropriate for your output file (including the row type designator). You'll have to do this in three separate flow paths in your data flow, then bring the rows together in a Union All data flow element. From there, process them as needed to create your output file.</p>\n" }, { "answer_id": 214579, "author": "JarrettV", "author_id": 16340, "author_profile": "https://Stackoverflow.com/users/16340", "pm_score": 2, "selected": true, "text": "<p>Your gut feeling on doing this using a Script Destination component is correct. Unfortunately, this scenario doesn't jive with SSIS well. I don't consider this a beginner package. If you must use SSIS then I'd start by inner joining all the data so there is one row for each InvoiceRow, containing the data needed from all three tables.</p>\n\n<p>CustomerCols, InvoiceCols, RowCols</p>\n\n<p>Then, in the script destination component you'll need to keep track of the customer and invoice values, as they change you'll need to write extra rows to the output.</p>\n\n<p>See <a href=\"http://msdn.microsoft.com/en-us/library/ms135939.aspx\" rel=\"nofollow noreferrer\">Creating a Destination with the Script Component</a> for more information on script destination.</p>\n\n<p>My experience shows that script destinations can have good performance.</p>\n" }, { "answer_id": 220899, "author": "Michael Entin", "author_id": 19880, "author_profile": "https://Stackoverflow.com/users/19880", "pm_score": 1, "selected": false, "text": "<p>I would avoid writing Script Destination, and use just Script Transform + Flat File Destination. This way, you concentrate on the logical output (strings of data), while allowing SSIS to do actual writing to the file (it might be a bit more efficient, plus you concentrate on your business, not on writing to files).</p>\n\n<p>First, you'll need to get denormalized data. You can do joins and sorts in the DBMS, but if you don't want to put too much pressure on DBMS - just get sorted data out of it and merge it using two SSIS Merge Join transforms.</p>\n\n<p>Then do the script: keep running values of current Customer and Invoice, output them when they change, output InvoiceRow on every input. Something like this:</p>\n\n<pre><code>if (this.CustomerID != InputBuffer.CustomerID) {\n this.CustomerID = InputBuffer.CustomerID;\n OutputBuffer.AddRow();\n OutputBuffer.OutputColumn = \"Customer: \" + InputBuffer.CustomerID + \" \" + InputBuffer.CustomerName;\n}\n// repeat the same code for Invoice\n\nOutputBuffer.AddRow();\nOutputBuffer.OutputColumn = \"InvoiceRow: \" + InputBuffer.InvoiceRowPrice;\n</code></pre>\n\n<p>Finally, add a Flat File Destination with a single column (OutputColumn created by the script) to write this to the file.</p>\n" } ]
2008/10/17
[ "https://Stackoverflow.com/questions/213411", "https://Stackoverflow.com", "https://Stackoverflow.com/users/21761/" ]
I have tree tables, Customer, Invoice and InvoiceRow with the standard relations. These I have to export in one fixed field length file with the first two characters of each row identifying the row type. The row types have different specifications. I could probably do it with a nested loop in a script block, but this is my first ever SSIS package and that solution feels wrong. edit: The output has to have: ``` Customer Invoice Rows Customer Invoice Rows and so on ```
Your gut feeling on doing this using a Script Destination component is correct. Unfortunately, this scenario doesn't jive with SSIS well. I don't consider this a beginner package. If you must use SSIS then I'd start by inner joining all the data so there is one row for each InvoiceRow, containing the data needed from all three tables. CustomerCols, InvoiceCols, RowCols Then, in the script destination component you'll need to keep track of the customer and invoice values, as they change you'll need to write extra rows to the output. See [Creating a Destination with the Script Component](http://msdn.microsoft.com/en-us/library/ms135939.aspx) for more information on script destination. My experience shows that script destinations can have good performance.
213,421
<p>Dependency injection seems to be a good thing. In general, should dependencies be injected at the methods that require them, or should they be injected in the contructor of the class?</p> <p>See the samples below to demonstrate the two ways to inject the same dependency.</p> <pre><code>//Inject the dependency into the methods that require ImportantClass Class Something { public Something() { //empty } public void A() { //do something without x } public void B(ImportantClass x) { //do something with x } public void C(ImportantClass x) { //do something with x } } //Inject the dependency into the constructor once Class Something { private ImportantClass _x public Something(ImportantClass x) { this._x = x; } public void A() { //do something without x } public void B() { //do something with this._x } public void C() { //do something with this._x } } </code></pre>
[ { "answer_id": 213425, "author": "johnstok", "author_id": 27929, "author_profile": "https://Stackoverflow.com/users/27929", "pm_score": 5, "selected": true, "text": "<p>The major benefit of constructor injection is that it allows your fields to be marked final. For example:</p>\n\n<pre><code>class Foo {\n private final Bar _bar;\n\n Foo(Bar bar) {\n _bar=bar;\n }\n}\n</code></pre>\n\n<p>The following page has a great list of the pro's and con's: <a href=\"http://code.google.com/p/google-guice/wiki/MinimizeMutability\" rel=\"noreferrer\">Guice Best Practices</a>:</p>\n\n<p><strong>Method injection</strong></p>\n\n<ul>\n<li>+ Isn't field injection</li>\n<li>+ Only thing that works for some strange edge cases</li>\n</ul>\n\n<p><strong>Constructor injection</strong></p>\n\n<ul>\n<li>+ Fields can be final!</li>\n<li>+ Injection cannot possibly have been skipped</li>\n<li>+ Easy to see dependencies at a glance</li>\n<li>+ It's what the idea of construction is all about</li>\n<li>- No optional injections</li>\n<li>- Useless when DI library can't do instantiation itself</li>\n<li>- Subclasses need to \"know about\" the injections needed by their superclasses</li>\n<li>- Less convenient for tests that only \"care about\" one of the parameters</li>\n</ul>\n" }, { "answer_id": 213439, "author": "smaclell", "author_id": 22914, "author_profile": "https://Stackoverflow.com/users/22914", "pm_score": 2, "selected": false, "text": "<p>By not injecting the dependency at each method you then force each caller to know or retrieve the dependency.</p>\n\n<p>Also from a tooling standpoint there are many frameworks available (at least in .NET) that enable or make constructor injection much easier to do. This should not sway the decision but makes it much more attractive.</p>\n\n<p>Good luck.</p>\n" }, { "answer_id": 213440, "author": "Steve g", "author_id": 12092, "author_profile": "https://Stackoverflow.com/users/12092", "pm_score": 0, "selected": false, "text": "<p><a href=\"http://crazybob.org\" rel=\"nofollow noreferrer\">Crazy Bob Lee</a> says use constructor injection whenever possible. Only use method injection when you don't have control over instantiation (like in a servlet).</p>\n" }, { "answer_id": 213532, "author": "tvanfosson", "author_id": 12950, "author_profile": "https://Stackoverflow.com/users/12950", "pm_score": 2, "selected": false, "text": "<p>Another method is to user a setter for the dependency. Sometimes this is combined with constructor injection. This can be useful if you want to change which implementation you are using later without having to recreate the instance.</p>\n\n<pre class=\"lang-cs prettyprint-override\"><code>public interface IFoo\n{\n void Do();\n}\n\npublic class DefaultFoo : IFoo\n{\n public void Do()\n {\n }\n}\n\npublic class UsesFoo\n{\n private IFoo foo;\n public IFoo Foo\n {\n set { this.foo = value; }\n }\n\n public UsesFoo()\n {\n this.Foo = new DefaultFoo();\n }\n\n public UsesFoo( IFoo foo )\n {\n this.Foo = foo;\n }\n\n public void DoFoo()\n {\n this.Foo.Do();\n }\n}\n</code></pre>\n" }, { "answer_id": 238776, "author": "leora", "author_id": 4653, "author_profile": "https://Stackoverflow.com/users/4653", "pm_score": 2, "selected": false, "text": "<p>If you inject during the methods than you are not differentiating the behavioral abstraction from the concrete dependencies. This is a big no no :). You want to depend on abstractions so you are not coupled with the dependencies of your classes dependencies . . . </p>\n\n<p>Since your constructor would not be there in any interface that your concrete class supports than you are not coupling to that dependency. But the method calls would have that issue.</p>\n\n<p>Here is a good article on this tiopic:</p>\n\n<p><a href=\"http://chrisdonnan.com/blog/2007/05/20/conquest-through-extreme-composition-glue-part-2/\" rel=\"nofollow noreferrer\">http://chrisdonnan.com/blog/2007/05/20/conquest-through-extreme-composition-glue-part-2/</a></p>\n" } ]
2008/10/17
[ "https://Stackoverflow.com/questions/213421", "https://Stackoverflow.com", "https://Stackoverflow.com/users/681/" ]
Dependency injection seems to be a good thing. In general, should dependencies be injected at the methods that require them, or should they be injected in the contructor of the class? See the samples below to demonstrate the two ways to inject the same dependency. ``` //Inject the dependency into the methods that require ImportantClass Class Something { public Something() { //empty } public void A() { //do something without x } public void B(ImportantClass x) { //do something with x } public void C(ImportantClass x) { //do something with x } } //Inject the dependency into the constructor once Class Something { private ImportantClass _x public Something(ImportantClass x) { this._x = x; } public void A() { //do something without x } public void B() { //do something with this._x } public void C() { //do something with this._x } } ```
The major benefit of constructor injection is that it allows your fields to be marked final. For example: ``` class Foo { private final Bar _bar; Foo(Bar bar) { _bar=bar; } } ``` The following page has a great list of the pro's and con's: [Guice Best Practices](http://code.google.com/p/google-guice/wiki/MinimizeMutability): **Method injection** * + Isn't field injection * + Only thing that works for some strange edge cases **Constructor injection** * + Fields can be final! * + Injection cannot possibly have been skipped * + Easy to see dependencies at a glance * + It's what the idea of construction is all about * - No optional injections * - Useless when DI library can't do instantiation itself * - Subclasses need to "know about" the injections needed by their superclasses * - Less convenient for tests that only "care about" one of the parameters
213,427
<p>Is it currently possible to translate C# code into an Abstract Syntax Tree?</p> <p>Edit: some clarification; I don't necessarily expect the compiler to generate the AST for me - a parser would be fine, although I'd like to use something "official." Lambda expressions are unfortunately not going to be sufficient given they don't allow me to use statement bodies, which is what I'm looking for.</p>
[ { "answer_id": 213484, "author": "Rob Walker", "author_id": 3631, "author_profile": "https://Stackoverflow.com/users/3631", "pm_score": 3, "selected": false, "text": "<p>Check out .NET <a href=\"https://learn.microsoft.com/en-us/dotnet/framework/reflection-and-codedom/using-the-codedom\" rel=\"nofollow noreferrer\">CodeDom</a> support. There is an old article on code project for a <a href=\"https://www.codeproject.com/Articles/2502/C-CodeDOM-parser\" rel=\"nofollow noreferrer\">C# CodeDOM parser</a>, but it won't support the new language features.</p>\n<p>There is also supposed to be support in #develop for generating a CodeDom tree from C# source code according to this <a href=\"https://web.archive.org/web/20200214175901/http://geekswithblogs.net:80/willemf/archive/2006/07/24/86075.aspx\" rel=\"nofollow noreferrer\">posting</a>.</p>\n" }, { "answer_id": 213485, "author": "Alexander Gladysh", "author_id": 6236, "author_profile": "https://Stackoverflow.com/users/6236", "pm_score": 0, "selected": false, "text": "<p>Please see the R# project (sorry the docs are in Russian, but there are some code examples). It allows AST manipulations on C# code.</p>\n\n<p><a href=\"http://www.rsdn.ru/projects/rsharp/article/rsharp_mag.xml\" rel=\"nofollow noreferrer\">http://www.rsdn.ru/projects/rsharp/article/rsharp_mag.xml</a></p>\n\n<p>Project's SVN is <a href=\"http://svn.rsdn.ru/svn/RSharp/\" rel=\"nofollow noreferrer\">here</a>: (URL updated, thanks, <a href=\"https://stackoverflow.com/users/12045/derigel\">derigel</a>)</p>\n\n<p>Also please see the <a href=\"http://nemerle.org/Main_Page\" rel=\"nofollow noreferrer\">Nemerle</a> language. It is a .Net language with strong support for metaprogramming.</p>\n" }, { "answer_id": 213510, "author": "Konrad Rudolph", "author_id": 1968, "author_profile": "https://Stackoverflow.com/users/1968", "pm_score": 4, "selected": false, "text": "<blockquote>\n <p>Is it currently possible to translate C# code into an Abstract Syntax Tree?</p>\n</blockquote>\n\n<p>Yes, trivially in special circumstances (= using the new <a href=\"http://msdn.microsoft.com/en-us/library/bb397951.aspx\" rel=\"nofollow noreferrer\">Expressions framework</a>):</p>\n\n<pre><code>// Requires 'using System.Linq.Expressions;'\nExpression&lt;Func&lt;int, int&gt;&gt; f = x =&gt; x * 2;\n</code></pre>\n\n<p>This creates an expression tree for the lambda, i.e. a function taking an <code>int</code> and returning the double. You can modify the expression tree by using the Expressions framework (= the classes from in that namespace) and then compile it at run-time:</p>\n\n<pre><code>var newBody = Expression.Add(f.Body, Expression.Constant(1));\nf = Expression.Lambda&lt;Func&lt;int, int&gt;&gt;(newBody, f.Parameters);\nvar compiled = f.Compile();\nConsole.WriteLine(compiled(5)); // Result: 11\n</code></pre>\n\n<p>Notice that all expressions are immutable so they have to be built anew by composition. In this case, I've prepended an addition of 1.</p>\n\n<p>Notice that these expression trees only work on real expressions i.e. content found in a C# function. You can't get syntax trees for higher constructs such as classes this way. Use the CodeDom framework for these.</p>\n" }, { "answer_id": 299622, "author": "Erik Forbes", "author_id": 16942, "author_profile": "https://Stackoverflow.com/users/16942", "pm_score": 2, "selected": false, "text": "<p>It looks like this sort of functionality will be included with whatever comes after C# 4, according to <a href=\"http://channel9.msdn.com/pdc2008/TL16/\" rel=\"nofollow noreferrer\">Anders Hejlsberg's 'Future of C#' PDC video</a>.</p>\n" }, { "answer_id": 319003, "author": "Erik Forbes", "author_id": 16942, "author_profile": "https://Stackoverflow.com/users/16942", "pm_score": 2, "selected": false, "text": "<p>The <a href=\"http://antlr.org/\" rel=\"nofollow noreferrer\">ANTLR Parser Generator</a> has a grammar for C# 3.0 which covers everything except for LINQ syntax.</p>\n" }, { "answer_id": 1286851, "author": "Ira Baxter", "author_id": 120163, "author_profile": "https://Stackoverflow.com/users/120163", "pm_score": 1, "selected": false, "text": "<p>Our <a href=\"http://www.semanticdesigns.com/Products/FrontEnds/CSharpFrontEnd.html\" rel=\"nofollow noreferrer\">C# front end for DMS</a> parses full C# 3.0 including LINQ and produces ASTs. DMS in fact is an ecosystem for analyzing/transforming source code using ASTs for front-end provided langauges.</p>\n\n<p>EDIT 3/10/2010: ... Now handles full C# 4.0</p>\n\n<p>EDIT: 6/27/2014: Handles C# 5.0 since quite awhile.</p>\n\n<p>EDIT: 6/15/2016: Handles C# 6.0. See <a href=\"https://stackoverflow.com/a/37847714/120163\">https://stackoverflow.com/a/37847714/120163</a> for a sample AST.</p>\n" }, { "answer_id": 1515777, "author": "yeeen", "author_id": 150254, "author_profile": "https://Stackoverflow.com/users/150254", "pm_score": 2, "selected": false, "text": "<p>ANTLR is not very useful. LINQ is not what you want.</p>\n\n<p>Try Mono.Cecil! <a href=\"http://www.mono-project.com/Cecil\" rel=\"nofollow noreferrer\">http://www.mono-project.com/Cecil</a></p>\n\n<p>It is used in many projects, including NDepend! <a href=\"http://www.ndepend.com/\" rel=\"nofollow noreferrer\">http://www.ndepend.com/</a></p>\n" }, { "answer_id": 2214839, "author": "Dinis Cruz", "author_id": 262379, "author_profile": "https://Stackoverflow.com/users/262379", "pm_score": 1, "selected": false, "text": "<p>I've just answered on another thread here at StackOverflow a solution where I implemented an API to <a href=\"https://stackoverflow.com/questions/81406/parser-for-c/2214810#2214810\">create and manipulate AST from C# Source Code</a></p>\n" }, { "answer_id": 5230482, "author": "NN_", "author_id": 558098, "author_profile": "https://Stackoverflow.com/users/558098", "pm_score": 2, "selected": false, "text": "<p>There is much powerful than R# project.\nNemerle.Peg:</p>\n\n<p><a href=\"https://code.google.com/p/nemerle/source/browse/nemerle/trunk/snippets/peg-parser/\" rel=\"nofollow\">https://code.google.com/p/nemerle/source/browse/nemerle/trunk/snippets/peg-parser/</a></p>\n\n<p>And it has C# Parser which parsers all C# code and translates it to AST !</p>\n\n<p><a href=\"https://code.google.com/p/nemerle/source/browse/nemerle/trunk/snippets/csharp-parser/\" rel=\"nofollow\">https://code.google.com/p/nemerle/source/browse/nemerle/trunk/snippets/csharp-parser/</a> </p>\n\n<p>You can download installer here: <a href=\"https://code.google.com/p/nemerle/\" rel=\"nofollow\">https://code.google.com/p/nemerle/</a></p>\n" }, { "answer_id": 5230543, "author": "SK-logic", "author_id": 293147, "author_profile": "https://Stackoverflow.com/users/293147", "pm_score": 0, "selected": false, "text": "<p>It is strange that nobody suggested hacking the existing Mono C# compiler.</p>\n" }, { "answer_id": 7919953, "author": "Paul Rubel", "author_id": 351984, "author_profile": "https://Stackoverflow.com/users/351984", "pm_score": 5, "selected": true, "text": "<p>The <a href=\"http://msdn.microsoft.com/en-us/roslyn\" rel=\"noreferrer\">Roslyn</a> project is in Visual Studio 2010 and gives you programmatic access to the <a href=\"http://msdn.microsoft.com/en-us/hh543916\" rel=\"noreferrer\">Syntax Tree</a>, among other things. </p>\n\n<pre><code>SyntaxTree tree = SyntaxTree.ParseCompilationUnit(\n @\" C# code here \");\nvar root = (CompilationUnitSyntax)tree.Root;\n</code></pre>\n" }, { "answer_id": 10474490, "author": "konrad.kruczynski", "author_id": 549315, "author_profile": "https://Stackoverflow.com/users/549315", "pm_score": 2, "selected": false, "text": "<p>Personally, I would use <a href=\"http://wiki.sharpdevelop.net/NRefactory.ashx\" rel=\"nofollow\">NRefactory</a>, which is free, open source and gains popularity.</p>\n" } ]
2008/10/17
[ "https://Stackoverflow.com/questions/213427", "https://Stackoverflow.com", "https://Stackoverflow.com/users/16942/" ]
Is it currently possible to translate C# code into an Abstract Syntax Tree? Edit: some clarification; I don't necessarily expect the compiler to generate the AST for me - a parser would be fine, although I'd like to use something "official." Lambda expressions are unfortunately not going to be sufficient given they don't allow me to use statement bodies, which is what I'm looking for.
The [Roslyn](http://msdn.microsoft.com/en-us/roslyn) project is in Visual Studio 2010 and gives you programmatic access to the [Syntax Tree](http://msdn.microsoft.com/en-us/hh543916), among other things. ``` SyntaxTree tree = SyntaxTree.ParseCompilationUnit( @" C# code here "); var root = (CompilationUnitSyntax)tree.Root; ```
213,429
<p>I'm having trouble dynamically adding controls inside an update panel with partial postbacks. I've read many articles on dynamic controls and I understand how to add and maintain them with postbacks but most of that information doesn't apply and won't work for partial postbacks. I can't find any useful information about adding and maintaining them with UpdatePanels. I'd like to do this without creating a web service if it's possible. Does anyone have any ideas or references to some helpful information?</p>
[ { "answer_id": 214854, "author": "sven", "author_id": 46, "author_profile": "https://Stackoverflow.com/users/46", "pm_score": 5, "selected": true, "text": "<p>This is, I think, one of the common pitfalls for asp.net programmers but isn't actually that hard to get it right when you know what is going on (always remember your viewstate!).</p>\n<p>the following piece of code explains how things can be done. It's a simple page where a user can click on a menu which will trigger an action that will add a user control to the page inside the updatepanel.<br />\n(This code is borrowed <a href=\"https://web.archive.org/web/20200804033347/http://geekswithblogs.net/rashid/archive/2007/08/11/Loading-UserControl-Dynamically-in-UpdatePanel.aspx\" rel=\"nofollow noreferrer\">from here</a>, and has lots more of information concerning this topic)</p>\n<pre><code>&lt;%@ Page Language=&quot;C#&quot; AutoEventWireup=&quot;true&quot; CodeFile=&quot;SampleMenu1.aspx.cs&quot; Inherits=&quot;SampleMenuPage1&quot; %&gt;\n&lt;!DOCTYPE html PUBLIC &quot;-//W3C//DTD XHTML 1.0 Transitional//EN&quot; &quot;http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd&quot;&gt;\n&lt;html xmlns=&quot;http://www.w3.org/1999/xhtml&quot; &gt;\n&lt;head runat=&quot;server&quot;&gt;\n &lt;title&gt;Sample Menu&lt;/title&gt;\n&lt;/head&gt;\n&lt;body&gt;\n &lt;form id=&quot;form1&quot; runat=&quot;server&quot;&gt;\n &lt;asp:Menu ID=&quot;Menu1&quot; runat=&quot;server&quot; OnMenuItemClick=&quot;Menu1_MenuItemClick&quot;&gt;\n &lt;Items&gt;\n &lt;asp:MenuItem Text=&quot;File&quot;&gt;\n &lt;asp:MenuItem Text=&quot;Load Control1&quot;&gt;&lt;/asp:MenuItem&gt;\n &lt;asp:MenuItem Text=&quot;Load Control2&quot;&gt;&lt;/asp:MenuItem&gt;\n &lt;asp:MenuItem Text=&quot;Load Control3&quot;&gt;&lt;/asp:MenuItem&gt;\n &lt;/asp:MenuItem&gt;\n &lt;/Items&gt;\n &lt;/asp:Menu&gt;\n &lt;br /&gt;\n &lt;br /&gt;\n &lt;asp:ScriptManager ID=&quot;ScriptManager1&quot; runat=&quot;server&quot;&gt;&lt;/asp:ScriptManager&gt;\n &lt;asp:UpdatePanel ID=&quot;UpdatePanel1&quot; runat=&quot;server&quot; UpdateMode=&quot;Conditional&quot;&gt;\n &lt;ContentTemplate&gt;\n &lt;asp:PlaceHolder ID=&quot;PlaceHolder1&quot; runat=&quot;server&quot;&gt;&lt;/asp:PlaceHolder&gt;\n &lt;/ContentTemplate&gt;\n &lt;Triggers&gt;\n &lt;asp:AsyncPostBackTrigger ControlID=&quot;Menu1&quot; /&gt;\n &lt;/Triggers&gt;\n &lt;/asp:UpdatePanel&gt;\n &lt;/form&gt;\n&lt;/body&gt;\n&lt;/html&gt;\n</code></pre>\n<p>and</p>\n<pre><code>using System;\nusing System.Web;\nusing System.Web.UI;\nusing System.Web.UI.WebControls;\n\npublic partial class PlainSampleMenuPage : System.Web.UI.Page\n{\n private const string BASE_PATH = &quot;~/DynamicControlLoading/&quot;;\n\n private string LastLoadedControl\n {\n get\n {\n return ViewState[&quot;LastLoaded&quot;] as string;\n }\n set\n {\n ViewState[&quot;LastLoaded&quot;] = value;\n }\n }\n\n private void LoadUserControl()\n {\n string controlPath = LastLoadedControl;\n\n if (!string.IsNullOrEmpty(controlPath))\n {\n PlaceHolder1.Controls.Clear();\n UserControl uc = (UserControl)LoadControl(controlPath);\n PlaceHolder1.Controls.Add(uc);\n }\n }\n\n protected void Page_Load(object sender, EventArgs e)\n {\n LoadUserControl();\n }\n\n protected void Menu1_MenuItemClick(object sender, MenuEventArgs e)\n {\n MenuItem menu = e.Item;\n\n string controlPath = string.Empty;\n\n switch (menu.Text)\n {\n case &quot;Load Control2&quot;:\n controlPath = BASE_PATH + &quot;SampleControl2.ascx&quot;;\n break;\n case &quot;Load Control3&quot;:\n controlPath = BASE_PATH + &quot;SampleControl3.ascx&quot;;\n break;\n default:\n controlPath = BASE_PATH + &quot;SampleControl1.ascx&quot;;\n break;\n }\n\n LastLoadedControl = controlPath;\n LoadUserControl();\n }\n}\n</code></pre>\n<p>for the code behind.</p>\n<p>That's basically it. You can clearly see that the viewstate is being kept with <em>LastLoadedControl</em> while the controls themselves are dynamically added to the page (inside the updatePanel (actually inside the placeHolder inside the updatePanel) when the user clicks on a menu item, which will send an asynchronous postback to the server.</p>\n<p>More information can also be found here:</p>\n<ul>\n<li><a href=\"https://web.archive.org/web/20210707024005/http://aspnet.4guysfromrolla.com/articles/081402-1.aspx\" rel=\"nofollow noreferrer\">http://aspnet.4guysfromrolla.com/articles/081402-1.aspx</a></li>\n<li><a href=\"https://web.archive.org/web/20210707024009/http://aspnet.4guysfromrolla.com/articles/082102-1.aspx\" rel=\"nofollow noreferrer\">http://aspnet.4guysfromrolla.com/articles/082102-1.aspx</a></li>\n</ul>\n<p>and of course on <a href=\"https://web.archive.org/web/20200804033347/http://geekswithblogs.net/rashid/archive/2007/08/11/Loading-UserControl-Dynamically-in-UpdatePanel.aspx\" rel=\"nofollow noreferrer\">the website that holds the example code</a> I used here.</p>\n" }, { "answer_id": 909655, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 2, "selected": false, "text": "<p>I encountered the problem that using the method mentioned above, LoadUserControl() is called twice when handling an event. I've read through some other articles and would like to show you my modification:</p>\n\n<p>1) Use LoadViewstate instead of Page_Load to load the user control:</p>\n\n<pre><code>protected override void LoadViewState(object savedState)\n{\n base.LoadViewState(savedState);\n\n if (!string.IsNullOrEmpty(CurrentUserControl))\n LoadDataTypeEditorControl(CurrentUserControl, panelFVE);\n}\n</code></pre>\n\n<p>2) Don't forget to set the control id when loading the usercontrol:</p>\n\n<pre><code>private void LoadDataTypeEditorControl(string userControlName, Control containerControl)\n{\n using (UserControl myControl = (UserControl) LoadControl(userControlName))\n {\n containerControl.Controls.Clear();\n\n string userControlID = userControlName.Split('.')[0];\n myControl.ID = userControlID.Replace(\"/\", \"\").Replace(\"~\", \"\");\n containerControl.Controls.Add(myControl);\n }\n this.CurrentUserControl = userControlName;\n}\n</code></pre>\n" }, { "answer_id": 13469570, "author": "Shoham", "author_id": 1297578, "author_profile": "https://Stackoverflow.com/users/1297578", "pm_score": 2, "selected": false, "text": "<p>Try this:</p>\n\n<pre><code>Literal literal = new Literal();\nliteral.Text = \"&lt;script type='text/javascript' src='http://www.googleadservices.com/pagead/conversion.js'&gt;\";\nUpdatePanel1.ContentTemplateContainer.Controls.Add(literal);\n</code></pre>\n\n<p>You can replace the content of literal with any HTML content you want...</p>\n" } ]
2008/10/17
[ "https://Stackoverflow.com/questions/213429", "https://Stackoverflow.com", "https://Stackoverflow.com/users/18785/" ]
I'm having trouble dynamically adding controls inside an update panel with partial postbacks. I've read many articles on dynamic controls and I understand how to add and maintain them with postbacks but most of that information doesn't apply and won't work for partial postbacks. I can't find any useful information about adding and maintaining them with UpdatePanels. I'd like to do this without creating a web service if it's possible. Does anyone have any ideas or references to some helpful information?
This is, I think, one of the common pitfalls for asp.net programmers but isn't actually that hard to get it right when you know what is going on (always remember your viewstate!). the following piece of code explains how things can be done. It's a simple page where a user can click on a menu which will trigger an action that will add a user control to the page inside the updatepanel. (This code is borrowed [from here](https://web.archive.org/web/20200804033347/http://geekswithblogs.net/rashid/archive/2007/08/11/Loading-UserControl-Dynamically-in-UpdatePanel.aspx), and has lots more of information concerning this topic) ``` <%@ Page Language="C#" AutoEventWireup="true" CodeFile="SampleMenu1.aspx.cs" Inherits="SampleMenuPage1" %> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml" > <head runat="server"> <title>Sample Menu</title> </head> <body> <form id="form1" runat="server"> <asp:Menu ID="Menu1" runat="server" OnMenuItemClick="Menu1_MenuItemClick"> <Items> <asp:MenuItem Text="File"> <asp:MenuItem Text="Load Control1"></asp:MenuItem> <asp:MenuItem Text="Load Control2"></asp:MenuItem> <asp:MenuItem Text="Load Control3"></asp:MenuItem> </asp:MenuItem> </Items> </asp:Menu> <br /> <br /> <asp:ScriptManager ID="ScriptManager1" runat="server"></asp:ScriptManager> <asp:UpdatePanel ID="UpdatePanel1" runat="server" UpdateMode="Conditional"> <ContentTemplate> <asp:PlaceHolder ID="PlaceHolder1" runat="server"></asp:PlaceHolder> </ContentTemplate> <Triggers> <asp:AsyncPostBackTrigger ControlID="Menu1" /> </Triggers> </asp:UpdatePanel> </form> </body> </html> ``` and ``` using System; using System.Web; using System.Web.UI; using System.Web.UI.WebControls; public partial class PlainSampleMenuPage : System.Web.UI.Page { private const string BASE_PATH = "~/DynamicControlLoading/"; private string LastLoadedControl { get { return ViewState["LastLoaded"] as string; } set { ViewState["LastLoaded"] = value; } } private void LoadUserControl() { string controlPath = LastLoadedControl; if (!string.IsNullOrEmpty(controlPath)) { PlaceHolder1.Controls.Clear(); UserControl uc = (UserControl)LoadControl(controlPath); PlaceHolder1.Controls.Add(uc); } } protected void Page_Load(object sender, EventArgs e) { LoadUserControl(); } protected void Menu1_MenuItemClick(object sender, MenuEventArgs e) { MenuItem menu = e.Item; string controlPath = string.Empty; switch (menu.Text) { case "Load Control2": controlPath = BASE_PATH + "SampleControl2.ascx"; break; case "Load Control3": controlPath = BASE_PATH + "SampleControl3.ascx"; break; default: controlPath = BASE_PATH + "SampleControl1.ascx"; break; } LastLoadedControl = controlPath; LoadUserControl(); } } ``` for the code behind. That's basically it. You can clearly see that the viewstate is being kept with *LastLoadedControl* while the controls themselves are dynamically added to the page (inside the updatePanel (actually inside the placeHolder inside the updatePanel) when the user clicks on a menu item, which will send an asynchronous postback to the server. More information can also be found here: * [http://aspnet.4guysfromrolla.com/articles/081402-1.aspx](https://web.archive.org/web/20210707024005/http://aspnet.4guysfromrolla.com/articles/081402-1.aspx) * [http://aspnet.4guysfromrolla.com/articles/082102-1.aspx](https://web.archive.org/web/20210707024009/http://aspnet.4guysfromrolla.com/articles/082102-1.aspx) and of course on [the website that holds the example code](https://web.archive.org/web/20200804033347/http://geekswithblogs.net/rashid/archive/2007/08/11/Loading-UserControl-Dynamically-in-UpdatePanel.aspx) I used here.
213,430
<p>So, I've started to create some Ruby unit tests that use <a href="http://selenium-rc.openqa.org/" rel="nofollow noreferrer">Selenium RC</a> to test my web app directly in the browser. I'm using the <a href="http://github.com/ph7/selenium-client/tree/master" rel="nofollow noreferrer">Selenum-Client</a> for ruby. I've created a base class for all my other selenium tests to inherit from.</p> <p>This creates numerous SeleniumDriver instances and all the methods that are missing are called on each instance. This essentially runs the tests in parallel.</p> <p><strong>How have other people automated this?</strong></p> <p>This is my implementation:</p> <pre><code>class SeleniumTest &lt; Test::Unit::TestCase def setup @seleniums = %w(*firefox *iexplore).map do |browser| puts 'creating browser ' + browser Selenium::SeleniumDriver.new("localhost", 4444, browser, "http://localhost:3003", 10000) end start open start_address end def teardown stop end #sub-classes should override this if they want to change it def start_address "http://localhost:3003/" end # Overrides standard "open" method def open(addr) method_missing 'open', addr end # Overrides standard "type" method def type(inputLocator, value) method_missing 'type', inputLocator, value end # Overrides standard "select" method def select(inputLocator, optionLocator) method_missing 'select', inputLocator, optionLocator end def method_missing(method_name, *args) @seleniums.each do |selenium_driver| if args.empty? selenium_driver.send method_name else selenium_driver.send method_name, *args end end end end </code></pre> <p>This works, but if one browser fails, the whole test fails and there is no way to know which browser it failed on.</p>
[ { "answer_id": 216472, "author": "Dan Fitch", "author_id": 27614, "author_profile": "https://Stackoverflow.com/users/27614", "pm_score": 0, "selected": false, "text": "<p><em>Disclaimer: Not a selenium expert.</em></p>\n\n<p>Do you just want to know which browser failed, or do you want to run the test across all browsers and then report the total failures when it's done?</p>\n\n<p>The former is pretty simple if you store the drivers by hash in your setup. (I'm sure there's a fancy-pants way to do this with Hash.inject, but I'm lazy.)</p>\n\n<pre><code>@seleniums = {}\n%w(*firefox *iexplore).each do |browser|\n puts 'creating browser ' + browser\n @seleniums[browser] = Selenium::SeleniumDriver.new(\"localhost\", 4444, browser, \"http://localhost:3003\", 10000)\nend\n</code></pre>\n\n<p>Then change your core function to modify exceptions to include the name of the driver being used, something like:</p>\n\n<pre><code>@seleniums.each do |name, driver|\n begin\n driver.send method_name, *args\n rescue Exception =&gt; ex\n raise ex.exception(ex.message + \" (in #{name})\")\n end\nend\n</code></pre>\n\n<p>Should get you close.</p>\n" }, { "answer_id": 216919, "author": "ya23", "author_id": 29430, "author_profile": "https://Stackoverflow.com/users/29430", "pm_score": 3, "selected": true, "text": "<p>Did you try <a href=\"http://selenium-grid.openqa.org/how_it_works.html\" rel=\"nofollow noreferrer\">Selenium Grid</a>? I think it creates pretty good summary report which shows details you need. I may be wrong, as I didn't use it for quite a while.</p>\n" }, { "answer_id": 221109, "author": "Daniel Beardsley", "author_id": 13216, "author_profile": "https://Stackoverflow.com/users/13216", "pm_score": 1, "selected": false, "text": "<p>I ended up modifying Selenium's protocol.rb to raise an <strong><code>AssertionFailedError</code> with both the <code>@browser_string</code> and the message returned</strong> from the Selenium RC if the response didn't start with \"OK\". I also modified the <code>http_post</code> method to return the whole response body and the <code>method_missing</code> to return an array of return values for issuing get_X commands to the Selenium RC.</p>\n\n<p><strong>Add this code to the code in the question</strong> and you should be able to see which assertions fail on which browsers.</p>\n\n<pre><code># Overrides a few Driver methods to make assertions return the\n# browser string if they fail\nmodule Selenium\n module Client\n class Driver\n def remote_control_command(verb, args=[])\n timeout(default_timeout_in_seconds) do\n status, response = http_post(http_request_for(verb, args))\n raise Test::Unit::AssertionFailedError.new(\"Browser:#{@browser_string} result:#{response}\") if status != 'OK'\n return response[3..-1]\n end\n end\n\n def http_post(data)\n http = Net::HTTP.new(@server_host, @server_port)\n response = http.post('/selenium-server/driver/', data, HTTP_HEADERS)\n #return the first 2 characters and the entire response body\n [ response.body[0..1], response.body ]\n end\n end\n end\nend\n\n#Modify your method_missing to use seleniums.map to return the\n#results of all the function calls as an array\nclass SeleniumTest &lt; Test::Unit::TestCase\n def method_missing(method_name, *args)\n self.class.seleniums.map do |selenium_driver|\n selenium_driver.send(method_name, *args)\n end\n end\nend \n</code></pre>\n" }, { "answer_id": 1750068, "author": "hkshambesh", "author_id": 183124, "author_profile": "https://Stackoverflow.com/users/183124", "pm_score": 0, "selected": false, "text": "<p>you need to treat every test independently. So if one test fails it will carry on testing other tests. Check out <a href=\"http://www.phpunit.de/manual/3.4/en/selenium.html\" rel=\"nofollow noreferrer\">phpunit and selenium rc</a> </p>\n" } ]
2008/10/17
[ "https://Stackoverflow.com/questions/213430", "https://Stackoverflow.com", "https://Stackoverflow.com/users/13216/" ]
So, I've started to create some Ruby unit tests that use [Selenium RC](http://selenium-rc.openqa.org/) to test my web app directly in the browser. I'm using the [Selenum-Client](http://github.com/ph7/selenium-client/tree/master) for ruby. I've created a base class for all my other selenium tests to inherit from. This creates numerous SeleniumDriver instances and all the methods that are missing are called on each instance. This essentially runs the tests in parallel. **How have other people automated this?** This is my implementation: ``` class SeleniumTest < Test::Unit::TestCase def setup @seleniums = %w(*firefox *iexplore).map do |browser| puts 'creating browser ' + browser Selenium::SeleniumDriver.new("localhost", 4444, browser, "http://localhost:3003", 10000) end start open start_address end def teardown stop end #sub-classes should override this if they want to change it def start_address "http://localhost:3003/" end # Overrides standard "open" method def open(addr) method_missing 'open', addr end # Overrides standard "type" method def type(inputLocator, value) method_missing 'type', inputLocator, value end # Overrides standard "select" method def select(inputLocator, optionLocator) method_missing 'select', inputLocator, optionLocator end def method_missing(method_name, *args) @seleniums.each do |selenium_driver| if args.empty? selenium_driver.send method_name else selenium_driver.send method_name, *args end end end end ``` This works, but if one browser fails, the whole test fails and there is no way to know which browser it failed on.
Did you try [Selenium Grid](http://selenium-grid.openqa.org/how_it_works.html)? I think it creates pretty good summary report which shows details you need. I may be wrong, as I didn't use it for quite a while.
213,461
<p>Is there a maximum length when using window.returnValue (variant) in a modal? </p> <p>I am calling a modal window using showModalDialog() and returning a comma delimited string. After selecting a group of users, I am putting them into a stringbuilder to display in a literal.</p> <pre><code>Dim strReturn As New StringBuilder strReturn.Append("&lt;script type=""text/javascript""&gt;window.returnValue='") Dim strUsers As New StringBuilder For Each dtRow As DataRow In GetSelectedUserTable.Rows If strUsers.ToString.Length &gt; 0 Then strUsers.Append(",") End If strUsers.Append(dtRow("UserID")) Next strReturn.Append(strUsers.ToString) strReturn.Append("';window.close();&lt;/script&gt;") litReturnJavascript.Text = strReturn.ToString </code></pre> <p>So would there be a limit on how many characters can be added to the window.returnValue?</p>
[ { "answer_id": 213591, "author": "Jason Bunting", "author_id": 1790, "author_profile": "https://Stackoverflow.com/users/1790", "pm_score": 3, "selected": true, "text": "<p>First, in what browser are you having problems? <code>window.returnValue</code> isn't even supported in Firefox, maybe not even other browsers.</p>\n\n<p>Second, have you looked the value of <code>strUsers</code> after building it to make sure there are no single or double quotes in that string?</p>\n\n<p>I would guess that the maximum size/length of that property would be determined more by your system's memory than anything else.</p>\n\n<hr>\n\n<p>EDIT: Maybe you should look at using <code>window.open()</code> to open a new window and <code>window.opener</code> to set the value on the parent form instead - it is supported by more browsers. Just a suggestion...</p>\n" }, { "answer_id": 213634, "author": "Steve Wright", "author_id": 3256, "author_profile": "https://Stackoverflow.com/users/3256", "pm_score": 0, "selected": false, "text": "<p>My users have to use IE6 (not my call), and the modal is already wired for IE so that is why I am using showModalDialog.</p>\n\n<p>strUsers will always be a comma delimited list of integers</p>\n\n<pre><code>E.G.: 384834,583882,343993,391823,302103\n</code></pre>\n" }, { "answer_id": 214940, "author": "David Robbins", "author_id": 19799, "author_profile": "https://Stackoverflow.com/users/19799", "pm_score": 1, "selected": false, "text": "<p>JasonBunting has a good suggestion. You can have the modal dialog update the parent before you close it. This way you can pass objects back and forth between your windows without worrying about the limitation of the return value. For example, you could have a hidden field on the parent that you update with your return values.</p>\n" } ]
2008/10/17
[ "https://Stackoverflow.com/questions/213461", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3256/" ]
Is there a maximum length when using window.returnValue (variant) in a modal? I am calling a modal window using showModalDialog() and returning a comma delimited string. After selecting a group of users, I am putting them into a stringbuilder to display in a literal. ``` Dim strReturn As New StringBuilder strReturn.Append("<script type=""text/javascript"">window.returnValue='") Dim strUsers As New StringBuilder For Each dtRow As DataRow In GetSelectedUserTable.Rows If strUsers.ToString.Length > 0 Then strUsers.Append(",") End If strUsers.Append(dtRow("UserID")) Next strReturn.Append(strUsers.ToString) strReturn.Append("';window.close();</script>") litReturnJavascript.Text = strReturn.ToString ``` So would there be a limit on how many characters can be added to the window.returnValue?
First, in what browser are you having problems? `window.returnValue` isn't even supported in Firefox, maybe not even other browsers. Second, have you looked the value of `strUsers` after building it to make sure there are no single or double quotes in that string? I would guess that the maximum size/length of that property would be determined more by your system's memory than anything else. --- EDIT: Maybe you should look at using `window.open()` to open a new window and `window.opener` to set the value on the parent form instead - it is supported by more browsers. Just a suggestion...
213,465
<p>Before you answer, this question is complicated:</p> <ol> <li>We are developing in asp.net / asp.net mvc / jQuery but I'm open to solutions on any platform using any framework</li> <li>I think logic like sorting / hiding columns / re-arranging columns / validation (where it makes sense) should be on the client-side</li> <li>I think logic like searching / updating the db / running workflows should be on the server side (just because of security / debugging reasons)</li> </ol> <p>What we are trying to do is <strong>NOT CREATE A MESS</strong> in our UI by writing a bunch of JavaScript to deal with the same feature in different contexts. I understand that I can use a JavaScript file + object oriented JavaScript, I'm looking for the pattern that makes it all easier.</p> <p>One solution proposed was to have an MVC model on both the client and server side, where we can encapsulate JavaScript functionality in client side controllers, then use them in different parts of the site. However, this means that we have 2 MVC implementations!</p> <p>Is this overkill? How would you expand on this solution? What other solutions are there?</p>
[ { "answer_id": 213517, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 3, "selected": true, "text": "<p>On two; you should always have server side validation as well as client side validation</p>\n\n<p>On three; if you can find a way to manipulate the DB on the client side that would be impressive ;)</p>\n\n<p>I don't know how ASP.net works though, so I am solely speaking from my PHP experience.</p>\n\n<p>I would write controls that are paired by server and client code. Each control needs a form, client side logic and server side logic. The form is written out by your templating engine, the client side logic is attached to the form and written in JS and the server side logic is a controller/action pair somewhere that manipulates the model. Clearly, you would not want to couple your client side logic to a specific action/controller, so be sure to define an interface that can be used to talk to your control instead...</p>\n\n<p>Then for each form I would write a class in javascript that instances your controls. For example; you may have a control:</p>\n\n<pre><code>{include file = \"list_view.php\" id = \"ListView1\" data = $Data.List}\n</code></pre>\n\n<p>which would print your form out. Then in your page controller class:</p>\n\n<pre><code>this.ListView1 = new ListViewController({id : \"ListView1\", serverCtrl : \"Users\"});\n</code></pre>\n\n<p>Now you can use \"this.ListView1\" to manipulate the list view. The list view controller does stuff like makes AJAX queries for new pages if the use presses the next page button - and also handles columns and sorting (which will also delegate to the server).</p>\n" }, { "answer_id": 213528, "author": "kentaromiura", "author_id": 27340, "author_profile": "https://Stackoverflow.com/users/27340", "pm_score": -1, "selected": false, "text": "<p>... It depends...</p>\n\n<p>Actually the best things is developing the UI using a css / javascript / html for a \nstyle / behaviour / structure + data, in these days people wants ajax interactions\n(they see that cooly things everywhere so they expectation is that they don't have to reload entire pages everytime) so I think you should take this into consideration.\nBTW MVC ends when your content is served, and it <em>haven't to be</em> HTML content, you can serve xml or json in your View.</p>\n\n<p>ASP.NET MVC permit to return Content(\"TEXT\") so you can organize your back end using MVC\nand user interaction/behaviour in javascript, for example when an ajax call is sent to the server \nyou are calling the Controller part of your application, so you can call an Ajax action that switch to an ajax Model that render as JSON and return to the JS part of your UI (The behavioural part).</p>\n\n<p>Since the Behavioural part is defined in your View part (initial View is composed of CSS / HTML JS) so as long as is a presentational part <em>I think</em> you haven't broken the MVC patterns.</p>\n\n<p>PS. I' m was forgetting to say that obviously DB actions stay in your model\n(you can think at model as the place where the Data Access Layer + Business Object Layer stay)</p>\n" }, { "answer_id": 214948, "author": "David Robbins", "author_id": 19799, "author_profile": "https://Stackoverflow.com/users/19799", "pm_score": 2, "selected": false, "text": "<p>I just googled this so take it with a grain of salt. <a href=\"http://javascriptmvc.com/\" rel=\"nofollow noreferrer\">JavascriptMVC</a> claims to be a MVC framework. Again, I have no experience with it but it may be worth a look.</p>\n" }, { "answer_id": 217119, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 1, "selected": false, "text": "<p>If you are using MVC, then I assume your view utilizes a template engine. Each page is associated with a template, and each template usually contains a reference to one or more scripts. The question is, how are your scripts referenced in the template? Are they static, or are they dynamic? Within your controllers, you should have the option to include any scripts in the view used for a page regardless of the template. I often suggest this \"include it when needed\" approach because simulating MVC client-side means exactly what you said it means -- you have two MVC frameworks now to maintain. Not only that -- with most client-side models they have direct access to your server-side model, which defeats the purpose of your server-side MVC. You're now bypassing the controller completely.</p>\n\n<p>When it comes to JavaScript, the best thing to do is to keep it very simple. With jQuery, you have an even better chance of making this happen. Every page gets the core, and you have several other JavaScript files in the same folder, each one being a plugin or extension of the jQuery object that maps to very specific functionality. If developers want to know if functionality already exists, all you do is check the file system where the JavaScript files are located. If the plugin exists, include it in your controller for use in a page. This way you can build helpers on the server-side that sit between your client-side app and any existing controllers. The helper is specific to that functionality and plugin, and you do not open up blanket access to your models from the client-side.</p>\n" }, { "answer_id": 635552, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 2, "selected": false, "text": "<p>Keep it simple. Build your application to be fully functional in the MVC ASP.Net framework. No JavaScript required at this stage of testing.</p>\n\n<p>Now add the nice stuff by linking jQuery in your site.master (Google link) and at the bottom of your Views that require a web 2.0 experience, link to appropriate JS files that add the functionality unobtrusively. Switch off JS and your app degrades back to the previous step.</p>\n\n<p>For example, you want to add client-side validation in addition to server-side. The JS file would attach an event handler to the forms onsubmit. The handler would then use an object that has been generated by the server (The same object used for server validation) which would be best as a JSON object because that's compatible with JS and ASP.NET. The members of the object would be the rules to check and error messages to write into the DOM at the same location you opted for the server-side errors. Your handler returning false until all is valid and true when correct.</p>\n\n<p>You want a nice fancy feature, such as a lightbox view of your pictures. Add a plugin for your view, modify the markup <code>&lt;ul id=\"lightup\"&gt;</code> ..., add the code:</p>\n\n<pre>\n$(function() {\n $(#lightup).showit(400); // or something like that\n});\n</pre>\n\n<p>and your good to go.</p>\n\n<p>Try to separate shared functionality from your server code into a web service or page so that both the client, through XHR and the server, can share the same functionality/data. </p>\n" }, { "answer_id": 1261209, "author": "sam", "author_id": 154462, "author_profile": "https://Stackoverflow.com/users/154462", "pm_score": 1, "selected": false, "text": "<p>don't return json/xml to views and build them with jquery dom generation on the client. It's ok performance wise on decent machines, but I made this mistake and when trying to view the site with my iphone it takes 60 seconds to load...and I'm the only person on the site! :-)</p>\n\n<p>so at this point I just use jquery dom injection for ajaxy updates and not rendering the entire page.</p>\n" } ]
2008/10/17
[ "https://Stackoverflow.com/questions/213465", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8360/" ]
Before you answer, this question is complicated: 1. We are developing in asp.net / asp.net mvc / jQuery but I'm open to solutions on any platform using any framework 2. I think logic like sorting / hiding columns / re-arranging columns / validation (where it makes sense) should be on the client-side 3. I think logic like searching / updating the db / running workflows should be on the server side (just because of security / debugging reasons) What we are trying to do is **NOT CREATE A MESS** in our UI by writing a bunch of JavaScript to deal with the same feature in different contexts. I understand that I can use a JavaScript file + object oriented JavaScript, I'm looking for the pattern that makes it all easier. One solution proposed was to have an MVC model on both the client and server side, where we can encapsulate JavaScript functionality in client side controllers, then use them in different parts of the site. However, this means that we have 2 MVC implementations! Is this overkill? How would you expand on this solution? What other solutions are there?
On two; you should always have server side validation as well as client side validation On three; if you can find a way to manipulate the DB on the client side that would be impressive ;) I don't know how ASP.net works though, so I am solely speaking from my PHP experience. I would write controls that are paired by server and client code. Each control needs a form, client side logic and server side logic. The form is written out by your templating engine, the client side logic is attached to the form and written in JS and the server side logic is a controller/action pair somewhere that manipulates the model. Clearly, you would not want to couple your client side logic to a specific action/controller, so be sure to define an interface that can be used to talk to your control instead... Then for each form I would write a class in javascript that instances your controls. For example; you may have a control: ``` {include file = "list_view.php" id = "ListView1" data = $Data.List} ``` which would print your form out. Then in your page controller class: ``` this.ListView1 = new ListViewController({id : "ListView1", serverCtrl : "Users"}); ``` Now you can use "this.ListView1" to manipulate the list view. The list view controller does stuff like makes AJAX queries for new pages if the use presses the next page button - and also handles columns and sorting (which will also delegate to the server).
213,476
<p>I'm working on trying to generate a report from a couple of database tables. The simplified version looks like this</p> <pre><code>Campaign ---------- CampaignID Source ----------------------- Source_ID | Campaign_ID Content --------------------------------------------------------- Content_ID | Campaign_ID | Content_Row_ID | Content_Value </code></pre> <p>The report needs to read like this:</p> <pre><code>CampaignID - SourceID - ContentRowID(Value(A)) - ContentRowID(Value(B)) </code></pre> <p>Where ContentRowID(Value(A)) means "Find a row the has a given CampaignID, and a ContentRowId of "A" and then get the ContentValue for that row"</p> <p>Essentially, I have to "pivot" (I think that's the correct term) the rows into columns...</p> <p>It's an Oracle 10g database...</p> <p>Any suggestions?</p>
[ { "answer_id": 213578, "author": "Barry Brown", "author_id": 17312, "author_profile": "https://Stackoverflow.com/users/17312", "pm_score": 2, "selected": true, "text": "<p>This is my first stab at it. Refinement coming once I know more about the contents of the Content table.</p>\n\n<p>First, you need a temporary table:</p>\n\n<pre><code>CREATE TABLE pivot (count integer);\nINSERT INTO pivot VALUES (1);\nINSERT INTO pivot VALUES (2);\n</code></pre>\n\n<p>Now we're ready to query.</p>\n\n<pre><code>SELECT campaignid, sourceid, a.contentvalue, b.contentvalue\nFROM content a, content b, pivot, source\nWHERE source.campaignid = content.campaignid\nAND pivot = 1 AND a.contentrowid = 'A'\nAND pivot = 2 AND b.contentrowid = 'B'\n</code></pre>\n" }, { "answer_id": 213665, "author": "Barry Brown", "author_id": 17312, "author_profile": "https://Stackoverflow.com/users/17312", "pm_score": 0, "selected": false, "text": "<p>If you need a dynamic number of columns, I don't believe this can be done in standard SQL which, alas, exceeds my knowledge. But there are features of Oracle that can do it. I found some resources:</p>\n\n<p><a href=\"http://www.sqlsnippets.com/en/topic-12200.html\" rel=\"nofollow noreferrer\">http://www.sqlsnippets.com/en/topic-12200.html</a></p>\n\n<p><a href=\"http://asktom.oracle.com/pls/asktom/f?p=100:11:0::::P11_QUESTION_ID:124812348063#41097616566309\" rel=\"nofollow noreferrer\">http://asktom.oracle.com/pls/asktom/f?p=100:11:0::::P11_QUESTION_ID:124812348063#41097616566309</a></p>\n" }, { "answer_id": 213709, "author": "Walter Mitty", "author_id": 19937, "author_profile": "https://Stackoverflow.com/users/19937", "pm_score": 0, "selected": false, "text": "<p>If you have \"Oracle, the Complete Reference\" look for a section entitled, \"Turning a Table on Its Side\". This gives detailed examples and instructions for performing a pivot, although the edition I have doesn't call it a pivot.</p>\n\n<p>Another term for \"pivoting a table\" is crosstabulation. </p>\n\n<p>One of the easiest tools to use for performing crosstabulation is MS Access. If you have MS Access, and you can establish a table link from an Access database to your source table, you're already halfway there. </p>\n\n<p>At that point, you can crank up the \"Query Wizard\", and ask it to build a crosstab query for you. It really is as easy as answering the questions the wizard asks you. The unfortunate side of this solution is that if look at the resulting query in SQL view, you'll see some SQL that's peculiar to the Access dialect of SQL, and cannot be used, in general, across other platforms.</p>\n\n<p>You may also be able to download some simple analysis tools from the Oracle website, and use one of those tools to perform a crosstabulation for you. </p>\n\n<p>Once again, if you really want to do it in SQL, \"Oracle, the Complete Reference\" should help you out.</p>\n" }, { "answer_id": 213745, "author": "Leigh Riffel", "author_id": 27010, "author_profile": "https://Stackoverflow.com/users/27010", "pm_score": 1, "selected": false, "text": "<p>If you don't have a dynamic number of columns and your dataset isn't too large you could do this...</p>\n\n<pre><code>SELECT CampaignID, SourceID, \n (SELECT Content_Value FROM Content c \n WHERE c.Campaign_ID=s.Campaign_ID \n AND Content_Row_ID = 39100 \n AND rownum&lt;=1) AS Value39100,\n (SELECT Content_Value FROM Content c \n WHERE c.Campaign_ID=s.Campaign_ID \n AND Content_Row_ID = 39200 \n AND rownum&lt;=1) AS Value39200\nFROM Source s;\n</code></pre>\n\n<p>Repeat the subquery for each additonal Content_Row_ID.</p>\n" }, { "answer_id": 213748, "author": "Bill Karwin", "author_id": 20860, "author_profile": "https://Stackoverflow.com/users/20860", "pm_score": 1, "selected": false, "text": "<p>To do this in standard SQL, you do need to know all the distinct values of Content_Row_ID, and do a join per distinct value. Then you need a column per distinct value of Content_Row_ID. </p>\n\n<pre><code>SELECT CA.Campaign_ID, \n C1.Content_Value AS \"39100\",\n C2.Content_Value AS \"39200\",\n C3.Content_Value AS \"39300\"\nFROM Campaign CA\n LEFT OUTER JOIN Content C1 ON (CA.Campaign_ID = C1.Campaign_ID \n AND C1.Content_Row_ID = 39100)\n LEFT OUTER JOIN Content C2 ON (CA.Campaign_ID = C2.Campaign_ID \n AND C2.Content_Row_ID = 39200)\n LEFT OUTER JOIN Content C3 ON (CA.Campaign_ID = C3.Campaign_ID \n AND C3.Content_Row_ID = 39300);\n</code></pre>\n\n<p>As the number of distinct values grows larger, this query becomes too expensive to run efficiently. It's probably easier to fetch the data more simply and reformat it in PL/SQL or in application code.</p>\n" }, { "answer_id": 214355, "author": "Anders Eurenius", "author_id": 1421, "author_profile": "https://Stackoverflow.com/users/1421", "pm_score": 2, "selected": false, "text": "<p>Bill Karwin mentions this, but I think this deserves to be pointed out very clearly:</p>\n\n<p><strong>SQL doesn't do what you're asking for, so any \"solution\" you get is going to be a kludge.</strong></p>\n\n<p>If you <em>know</em>, for sure, it's always going to run on an Oracle 10, then sure, Walter Mitty's crosstabulation might do it. The right way to do it is to work the easiest combination of sort order in the query and application code to lay it out right.</p>\n\n<ul>\n<li>It works on other database systems,</li>\n<li>it doesn't risk any other layers crapping out (I remember MySQL having a problem with >255 columns for instance. Are you sure you <em>interface library</em> copes as well as the db itself?)</li>\n<li>it's (usually) not that much harder.</li>\n</ul>\n\n<p>If you need to, you can just ask for the <code>Content_Row_ID</code>s first, then ask for whatever rows you need, ordered by <code>CampaignID</code>, <code>ContentRowID</code>, which would give you each (populated) cell in left-to-right, line-by-line order.</p>\n\n<hr>\n\n<p>Ps.</p>\n\n<p>There are a bunch of stuff that modern man thinks SQL should have/do that just isn't there. This is one, generated ranges is another, recursive closure, parametric <code>ORDER BY</code>, standardised programming language... the list goes on. (though, admittedly, there's a trick for <code>ORDER BY</code>)</p>\n" }, { "answer_id": 214413, "author": "Leigh Riffel", "author_id": 27010, "author_profile": "https://Stackoverflow.com/users/27010", "pm_score": 1, "selected": false, "text": "<p>Bill Karwin and Anders Eurenius are correct that there is no solution that is straightforward, nor is there any solution at all when the number of resulting column values is not known in advance. Oracle 11g does simplify it somewhat with <a href=\"http://www.oracle.com/technology/pub/articles/oracle-database-11g-top-features/11g-pivot.html\" rel=\"nofollow noreferrer\">the PIVOT operator</a>, but the columns still have to be known in advance and that doesn't meet the 10g criteria of your question.</p>\n" }, { "answer_id": 337014, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 0, "selected": false, "text": "<p>If you don't know the number of columns up front just bring back a normal sql query and use server side code like I listed here: <a href=\"https://stackoverflow.com/questions/333181/a-question-about-datagrid-and-sql-query\">Filling Datagrid And Sql Query</a></p>\n" }, { "answer_id": 3197287, "author": "Almeida", "author_id": 401300, "author_profile": "https://Stackoverflow.com/users/401300", "pm_score": 0, "selected": false, "text": "<p>I Did a solution with this SQL. I Needed that the rows be the number of classes and the columns be the sumary of each classe by month, so, the first column is the sumary of row and each ohters columns are the sumary of each month, and the last row is the sumary of complete column month by month.</p>\n\n<p>Good luck</p>\n\n<pre><code>Select DS.Cla,\nSum(case\nwhen (Extract(year from DS.Data) =:intYear) then DS.PRE\nelse 0\nend) as ToTal,\nSum(case\nwhen (Extract(month from DS.Data) =1) then DS.PRE\nelse 0\nend) as Jan,\nSum(case\nwhen (Extract(month from DS.Data) =2) then DS.PRE\nelse 0\nend) as FEV,\nSum(case\nwhen (Extract(month from DS.Data) =3) then DS.PRE\nelse 0\nend) as MAR,\nSum(case\nwhen (Extract(month from DS.Data) =4) then DS.PRE\nelse 0\nend) as ABR,\nSum(case\nwhen (Extract(month from DS.Data) =5) then DS.PRE\nelse 0\nend) as MAI,\nSum(case\nwhen (Extract(month from DS.Data) =6) then DS.PRE\nelse 0\nend) as JUN,\nSum(case\nwhen (Extract(month from DS.Data) =7) then DS.PRE\nelse 0\nend) as JUL,\nSum(case\nwhen (Extract(month from DS.Data) =8) then DS.PRE\nelse 0\nend) as AGO,\nSum(case\nwhen (Extract(month from DS.Data) =9) then DS.PRE\nelse 0\nend) as SETE,\nSum(case\nwhen (Extract(month from DS.Data) =10) then DS.PRE\nelse 0\nend) as OUT,\nSum(case\nwhen (Extract(month from DS.Data) =11) then DS.PRE\nelse 0\nend) as NOV,\nSum(case\nwhen (Extract(month from DS.Data) =12) then DS.PRE\nelse 0\nend) as DEZ\nfrom Dados DS\nWhere DS.Cla &gt; 0\nAnd Extract(Year from DS.Data) = :intYear\ngroup by DS.CLA\n\nUnion All\n\nSelect 0*count(DS.cla), 0*count(DS.cla),\nSum(case\nwhen (Extract(month from DS.Data) =1) then DS.PRE\nelse 0\nend) as JAN,\nSum(case\nwhen (Extract(month from DS.Data) =2) then DS.PRE\nelse 0\nend) as FEV,\nSum(case\nwhen (Extract(month from DS.Data) =3) then DS.PRE\nelse 0\nend) as MAR,\nSum(case\nwhen (Extract(month from DS.Data) =4) then DS.PRE\nelse 0\nend) as ABR,\nSum(case\nwhen (Extract(month from DS.Data) =5) then DS.PRE\nelse 0\nend) as MAI,\nSum(case\nwhen (Extract(month from DS.Data) =6) then DS.PRE\nelse 0\nend) as JUN,\nSum(case\nwhen (Extract(month from DS.Data) =7) then DS.PRE\nelse 0\nend) as JUL,\nSum(case\nwhen (Extract(month from DS.Data) =8) then DS.PRE\nelse 0\nend) as AGO,\nSum(case\nwhen (Extract(month from DS.Data) =9) then DS.PRE\nelse 0\nend) as SETE,\nSum(case\nwhen (Extract(month from DS.Data) =10) then DS.PRE\nelse 0\nend) as OUT,\nSum(case\nwhen (Extract(month from DS.Data) =11) then DS.PRE\nelse 0\nend) as NOV,\nSum(case\nwhen (Extract(month from DS.Data) =12) then DS.PRE\nelse 0\nend) as DEZ\nfrom Dados DS\nWhere DS.Cla &gt; 0\nAnd Extract(Year from DS.Data) = :intYear\n</code></pre>\n" } ]
2008/10/17
[ "https://Stackoverflow.com/questions/213476", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5590/" ]
I'm working on trying to generate a report from a couple of database tables. The simplified version looks like this ``` Campaign ---------- CampaignID Source ----------------------- Source_ID | Campaign_ID Content --------------------------------------------------------- Content_ID | Campaign_ID | Content_Row_ID | Content_Value ``` The report needs to read like this: ``` CampaignID - SourceID - ContentRowID(Value(A)) - ContentRowID(Value(B)) ``` Where ContentRowID(Value(A)) means "Find a row the has a given CampaignID, and a ContentRowId of "A" and then get the ContentValue for that row" Essentially, I have to "pivot" (I think that's the correct term) the rows into columns... It's an Oracle 10g database... Any suggestions?
This is my first stab at it. Refinement coming once I know more about the contents of the Content table. First, you need a temporary table: ``` CREATE TABLE pivot (count integer); INSERT INTO pivot VALUES (1); INSERT INTO pivot VALUES (2); ``` Now we're ready to query. ``` SELECT campaignid, sourceid, a.contentvalue, b.contentvalue FROM content a, content b, pivot, source WHERE source.campaignid = content.campaignid AND pivot = 1 AND a.contentrowid = 'A' AND pivot = 2 AND b.contentrowid = 'B' ```
213,480
<p>How can I bring a console application window to front in C# (especially when running the Visual Studio debugger)?</p>
[ { "answer_id": 213582, "author": "Jon Skeet", "author_id": 22656, "author_profile": "https://Stackoverflow.com/users/22656", "pm_score": 5, "selected": true, "text": "<p>It's hacky, it's horrible, but it works for me (thanks, <a href=\"http://pinvoke.net/\" rel=\"noreferrer\">pinvoke.net</a>!):</p>\n\n<pre><code>using System;\nusing System.Diagnostics;\nusing System.Runtime.InteropServices;\nusing System.Threading;\n\npublic class Test \n{\n\n [DllImport(\"user32.dll\")]\n [return: MarshalAs(UnmanagedType.Bool)]\n static extern bool SetForegroundWindow(IntPtr hWnd);\n\n [DllImport(\"user32.dll\", EntryPoint=\"FindWindow\", SetLastError = true)]\n static extern IntPtr FindWindowByCaption(IntPtr zeroOnly, string lpWindowName);\n\n public static void Main()\n {\n string originalTitle = Console.Title;\n string uniqueTitle = Guid.NewGuid().ToString();\n Console.Title = uniqueTitle;\n Thread.Sleep(50);\n IntPtr handle = FindWindowByCaption(IntPtr.Zero, uniqueTitle);\n\n if (handle == IntPtr.Zero)\n {\n Console.WriteLine(\"Oops, cant find main window.\");\n return;\n }\n Console.Title = originalTitle;\n\n while (true)\n {\n Thread.Sleep(3000);\n Console.WriteLine(SetForegroundWindow(handle));\n }\n }\n}\n</code></pre>\n" }, { "answer_id": 213642, "author": "tvanfosson", "author_id": 12950, "author_profile": "https://Stackoverflow.com/users/12950", "pm_score": -1, "selected": false, "text": "<p>Get two monitors (at least) and open VisualStudio in the secondary monitor. When you run your app from within VisualStudio it will start up by default on the primary monitor. Since it's the last app to be opened, it starts on top and changing over to VisualStudio doesn't affect it. Works for me anyway.</p>\n\n<p>If you don't already have a second monitor, IMHO, you should.</p>\n" }, { "answer_id": 12066376, "author": "ryanb9", "author_id": 1388309, "author_profile": "https://Stackoverflow.com/users/1388309", "pm_score": 4, "selected": false, "text": "<p>This is what I would do. </p>\n\n<pre><code>[DllImport(\"kernel32.dll\", ExactSpelling = true)]\npublic static extern IntPtr GetConsoleWindow();\n\n[DllImport(\"user32.dll\")]\n[return: MarshalAs(UnmanagedType.Bool)]\npublic static extern bool SetForegroundWindow(IntPtr hWnd);\n\npublic void BringConsoleToFront()\n{\n SetForegroundWindow(GetConsoleWindow()); \n}\n</code></pre>\n" } ]
2008/10/17
[ "https://Stackoverflow.com/questions/213480", "https://Stackoverflow.com", "https://Stackoverflow.com/users/25571/" ]
How can I bring a console application window to front in C# (especially when running the Visual Studio debugger)?
It's hacky, it's horrible, but it works for me (thanks, [pinvoke.net](http://pinvoke.net/)!): ``` using System; using System.Diagnostics; using System.Runtime.InteropServices; using System.Threading; public class Test { [DllImport("user32.dll")] [return: MarshalAs(UnmanagedType.Bool)] static extern bool SetForegroundWindow(IntPtr hWnd); [DllImport("user32.dll", EntryPoint="FindWindow", SetLastError = true)] static extern IntPtr FindWindowByCaption(IntPtr zeroOnly, string lpWindowName); public static void Main() { string originalTitle = Console.Title; string uniqueTitle = Guid.NewGuid().ToString(); Console.Title = uniqueTitle; Thread.Sleep(50); IntPtr handle = FindWindowByCaption(IntPtr.Zero, uniqueTitle); if (handle == IntPtr.Zero) { Console.WriteLine("Oops, cant find main window."); return; } Console.Title = originalTitle; while (true) { Thread.Sleep(3000); Console.WriteLine(SetForegroundWindow(handle)); } } } ```
213,506
<p>I get the following warning when using <code>java.net.URLEncoder.encode</code>:</p> <pre>warning: [deprecation] encode(java.lang.String) in java.net.URLEncoder has been deprecated</pre> <p>What should I be using instead?</p>
[ { "answer_id": 213519, "author": "Will Wagner", "author_id": 25468, "author_profile": "https://Stackoverflow.com/users/25468", "pm_score": 9, "selected": true, "text": "<p>Use the other <code>encode</code> method in <a href=\"http://docs.oracle.com/javase/8/docs/api/java/net/URLEncoder.html#encode-java.lang.String-java.lang.String-\" rel=\"noreferrer\">URLEncoder</a>:</p>\n\n<pre><code>URLEncoder.encode(String, String)\n</code></pre>\n\n<p>The first parameter is the text to encode; the second is the name of the character encoding to use (e.g., <code>UTF-8</code>). For example:</p>\n\n<pre><code>System.out.println(\n URLEncoder.encode(\n \"urlParameterString\",\n java.nio.charset.StandardCharsets.UTF_8.toString()\n )\n);\n</code></pre>\n" }, { "answer_id": 20258706, "author": "Atul Darne", "author_id": 996695, "author_profile": "https://Stackoverflow.com/users/996695", "pm_score": 5, "selected": false, "text": "<p>You should use:</p>\n\n<pre><code>URLEncoder.encode(\"NAME\", \"UTF-8\");\n</code></pre>\n" }, { "answer_id": 23402253, "author": "user3591718", "author_id": 3591718, "author_profile": "https://Stackoverflow.com/users/3591718", "pm_score": 1, "selected": false, "text": "<p>The first parameter is the String to encode; the second is the name of the character encoding to use (e.g., UTF-8).</p>\n" }, { "answer_id": 23945523, "author": "htafoya", "author_id": 505152, "author_profile": "https://Stackoverflow.com/users/505152", "pm_score": 0, "selected": false, "text": "<p>As an additional reference for the other responses, instead of using <strong>\"UTF-8\"</strong> you can use:</p>\n\n<p><code>HTTP.UTF_8</code> </p>\n\n<p>which is included since Java 4 as part of the org.apache.http.protocol library, which is included also since Android API 1.</p>\n" }, { "answer_id": 25669212, "author": "Jorgesys", "author_id": 250260, "author_profile": "https://Stackoverflow.com/users/250260", "pm_score": 5, "selected": false, "text": "<p>Use the class <a href=\"http://docs.oracle.com/javase/6/docs/api/java/net/URLEncoder.html\" rel=\"noreferrer\"><strong>URLEncoder</strong></a>:</p>\n\n<pre><code>URLEncoder.encode(String s, String enc)\n</code></pre>\n\n<p>Where :</p>\n\n<blockquote>\n <p><strong>s</strong> - String to be translated.</p>\n \n <p><strong>enc</strong> - The name of a supported <a href=\"http://docs.oracle.com/javase/6/docs/api/java/lang/package-summary.html#charenc\" rel=\"noreferrer\"><strong>character encoding</strong></a>.</p>\n</blockquote>\n\n<p><strong>Standard charsets:</strong></p>\n\n<blockquote>\n <p><strong>US-ASCII</strong> Seven-bit ASCII, a.k.a. ISO646-US, a.k.a. the Basic Latin block of the Unicode character set\n ISO-8859-1 ISO Latin Alphabet No. 1, a.k.a. ISO-LATIN-1</p>\n \n <p><strong>UTF-8</strong> Eight-bit UCS Transformation Format</p>\n \n <p><strong>UTF-16BE</strong> Sixteen-bit UCS Transformation Format, big-endian byte order</p>\n \n <p><strong>UTF-16LE</strong> Sixteen-bit UCS Transformation Format, little-endian byte order</p>\n \n <p><strong>UTF-16</strong> Sixteen-bit UCS Transformation Format, byte order identified by an optional byte-order mark</p>\n</blockquote>\n\n<p><strong>Example:</strong></p>\n\n<pre><code>import java.net.URLEncoder;\n\nString stringEncoded = URLEncoder.encode(\n \"This text must be encoded! aeiou áéíóú ñ, peace!\", \"UTF-8\");\n</code></pre>\n" }, { "answer_id": 58532158, "author": "R. Kåbis", "author_id": 11047692, "author_profile": "https://Stackoverflow.com/users/11047692", "pm_score": 1, "selected": false, "text": "<p>The usage of <code>org.apache.commons.httpclient.URI</code> is not strictly an issue; what is an issue is that you target the wrong constructor, which <em>is</em> depreciated.</p>\n\n<p>Using just</p>\n\n<pre><code>new URI( [string] );\n</code></pre>\n\n<p>Will indeed flag it as depreciated. What is needed is to provide at minimum one additional argument (the first, below), and ideally two:</p>\n\n<ol>\n<li><code>escaped</code>: true if URI character sequence is in escaped form. false otherwise.</li>\n<li><code>charset</code>: the charset string to do escape encoding, if\nrequired</li>\n</ol>\n\n<p>This will target a non-depreciated constructor within that class. So an ideal usage would be as such:</p>\n\n<pre><code>new URI( [string], true, StandardCharsets.UTF_8.toString() );\n</code></pre>\n\n<p>A bit crazy-late in the game (a hair over 11 years later - <em>egad!</em>), but I hope this helps someone else, especially if the method at the far end is <em>still</em> expecting a URI, such as <code>org.apache.commons.httpclient.setURI()</code>.</p>\n" } ]
2008/10/17
[ "https://Stackoverflow.com/questions/213506", "https://Stackoverflow.com", "https://Stackoverflow.com/users/338/" ]
I get the following warning when using `java.net.URLEncoder.encode`: ``` warning: [deprecation] encode(java.lang.String) in java.net.URLEncoder has been deprecated ``` What should I be using instead?
Use the other `encode` method in [URLEncoder](http://docs.oracle.com/javase/8/docs/api/java/net/URLEncoder.html#encode-java.lang.String-java.lang.String-): ``` URLEncoder.encode(String, String) ``` The first parameter is the text to encode; the second is the name of the character encoding to use (e.g., `UTF-8`). For example: ``` System.out.println( URLEncoder.encode( "urlParameterString", java.nio.charset.StandardCharsets.UTF_8.toString() ) ); ```
213,543
<p>My MySQL database contains several tables using different storage engines (specifically myisam and innodb). How can I find out which tables are using which engine?</p>
[ { "answer_id": 213545, "author": "Greg", "author_id": 24181, "author_profile": "https://Stackoverflow.com/users/24181", "pm_score": 10, "selected": true, "text": "<pre><code>SHOW TABLE STATUS WHERE Name = 'xxx'\n</code></pre>\n<p>This will give you (among other things) an <code>Engine</code> column, which is what you want.</p>\n" }, { "answer_id": 213561, "author": "Javier", "author_id": 11649, "author_profile": "https://Stackoverflow.com/users/11649", "pm_score": 6, "selected": false, "text": "<pre><code>SHOW CREATE TABLE &lt;tablename&gt;;\n</code></pre>\n\n<p>Less parseable but more readable than <code>SHOW TABLE STATUS</code>.</p>\n" }, { "answer_id": 1297804, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 6, "selected": false, "text": "<p>Or just run this:</p>\n<pre><code>show table status;\n</code></pre>\n<p>This will list all tables and related details on your database.</p>\n" }, { "answer_id": 4225613, "author": "Jocker", "author_id": 513552, "author_profile": "https://Stackoverflow.com/users/513552", "pm_score": 8, "selected": false, "text": "<p>To show a list of all the tables in a database and their engines, use this SQL query:</p>\n\n<pre><code>SELECT TABLE_NAME,\n ENGINE\nFROM information_schema.TABLES\nWHERE TABLE_SCHEMA = 'dbname';\n</code></pre>\n\n<p>Replace <code>dbname</code> with your database name.</p>\n" }, { "answer_id": 7043322, "author": "Evan Donovan", "author_id": 263877, "author_profile": "https://Stackoverflow.com/users/263877", "pm_score": 4, "selected": false, "text": "<p>Bit of a tweak to Jocker's response (I would post as a comment, but I don't have enough karma yet):</p>\n\n<pre><code>SELECT TABLE_NAME, ENGINE\n FROM information_schema.TABLES\n WHERE TABLE_SCHEMA = 'database' AND ENGINE IS NOT NULL;\n</code></pre>\n\n<p>This excludes MySQL views from the list, which don't have an engine.</p>\n" }, { "answer_id": 14306616, "author": "Nicholas", "author_id": 1072064, "author_profile": "https://Stackoverflow.com/users/1072064", "pm_score": 3, "selected": false, "text": "<pre><code>SHOW CREATE TABLE &lt;tablename&gt;\\G\n</code></pre>\n\n<p>will format it much nicer compared to the output of</p>\n\n<pre><code>SHOW CREATE TABLE &lt;tablename&gt;;\n</code></pre>\n\n<p>The <code>\\G</code> trick is also useful to remember for many other queries/commands.</p>\n" }, { "answer_id": 17988828, "author": "harsha vardhan", "author_id": 2641241, "author_profile": "https://Stackoverflow.com/users/2641241", "pm_score": 0, "selected": false, "text": "<p>go to information_schema database there you will find 'tables' table then select it;</p>\n\n<p>Mysql>use information_schema;\nMysql> select table_name,engine from tables;</p>\n" }, { "answer_id": 23013791, "author": "magic", "author_id": 3523892, "author_profile": "https://Stackoverflow.com/users/3523892", "pm_score": 3, "selected": false, "text": "<pre><code>mysqlshow -i &lt;database_name&gt;\n</code></pre>\n\n<p>will show the info for all tables of a specific database.</p>\n\n<pre><code>mysqlshow -i &lt;database_name&gt; &lt;table_name&gt; \n</code></pre>\n\n<p>will do so just for a specific table.</p>\n" }, { "answer_id": 27763333, "author": "David Thomas", "author_id": 583715, "author_profile": "https://Stackoverflow.com/users/583715", "pm_score": 2, "selected": false, "text": "<p>Yet another way, perhaps the shortest to get status of a single or matched set of tables:</p>\n\n<pre><code>SHOW TABLE STATUS LIKE 'table';\n</code></pre>\n\n<p>You can then use LIKE operators for example:</p>\n\n<pre><code>SHOW TABLE STATUS LIKE 'field_data_%';\n</code></pre>\n" }, { "answer_id": 31385272, "author": "sjas", "author_id": 805284, "author_profile": "https://Stackoverflow.com/users/805284", "pm_score": 2, "selected": false, "text": "<p>If you are a linux user:</p>\n\n<p>To show the engines for all tables for all databases on a mysql server, without tables <code>information_schema</code>, <code>mysql</code>, <code>performance_schema</code>:</p>\n\n<pre><code>less &lt; &lt;({ for i in $(mysql -e \"show databases;\" | cat | grep -v -e Database-e information_schema -e mysql -e performance_schema); do echo \"--------------------$i--------------------\"; mysql -e \"use $i; show table status;\"; done } | column -t)\n</code></pre>\n\n<p>You might love this, if you are on linux, at least.</p>\n\n<p>Will open all info for all tables in <code>less</code>, press <code>-S</code> to chop overly long lines.</p>\n\n<p>Example output: </p>\n\n<pre><code>--------------------information_schema--------------------\nName Engine Version Row_format Rows Avg_row_length Data_length Max_data_length Index_length Data_free Auto_increment Create_time Update_time Check_time C\nCHARACTER_SETS MEMORY 10 Fixed NULL 384 0 16434816 0 0 NULL 2015-07-13 15:48:45 NULL N\nCOLLATIONS MEMORY 10 Fixed NULL 231 0 16704765 0 0 NULL 2015-07-13 15:48:45 NULL N\nCOLLATION_CHARACTER_SET_APPLICABILITY MEMORY 10 Fixed NULL 195 0 16357770 0 0 NULL 2015-07-13 15:48:45 NULL N\nCOLUMNS MyISAM 10 Dynamic NULL 0 0 281474976710655 1024 0 NULL 2015-07-13 15:48:45 2015-07-13 1\nCOLUMN_PRIVILEGES MEMORY 10 Fixed NULL 2565 0 16757145 0 0 NULL 2015-07-13 15:48:45 NULL N\nENGINES MEMORY 10 Fixed NULL 490 0 16574250 0 0 NULL 2015-07-13 15:48:45 NULL N\nEVENTS MyISAM 10 Dynamic NULL 0 0 281474976710655 1024 0 NULL 2015-07-13 15:48:45 2015-07-13 1\nFILES MEMORY 10 Fixed NULL 2677 0 16758020 0 0 NULL 2015-07-13 15:48:45 NULL N\nGLOBAL_STATUS MEMORY 10 Fixed NULL 3268 0 16755036 0 0 NULL 2015-07-13 15:48:45 NULL N\nGLOBAL_VARIABLES MEMORY 10 Fixed NULL 3268 0 16755036 0 0 NULL 2015-07-13 15:48:45 NULL N\nKEY_COLUMN_USAGE MEMORY 10 Fixed NULL 4637 0 16762755 0 \n\n.\n.\n.\n</code></pre>\n" }, { "answer_id": 32756219, "author": "T30", "author_id": 1677209, "author_profile": "https://Stackoverflow.com/users/1677209", "pm_score": 3, "selected": false, "text": "<p>If you're using <a href=\"https://www.mysql.com/products/workbench/\" rel=\"nofollow noreferrer\">MySQL Workbench</a>, right-click a table and select <code>alter table</code>.</p>\n<p>In that window you can see your table Engine and also change it.</p>\n<p><img src=\"https://i.stack.imgur.com/zc2Nx.png\" alt=\"\" /></p>\n" }, { "answer_id": 54620228, "author": "Zahid", "author_id": 5556824, "author_profile": "https://Stackoverflow.com/users/5556824", "pm_score": 3, "selected": false, "text": "<blockquote>\n <p>show table status from database_name;</p>\n</blockquote>\n\n<p>It will list all tables from the mentioned database.<br>\n<strong>Example output</strong></p>\n\n<p><a href=\"https://i.stack.imgur.com/8yVDn.png\" rel=\"noreferrer\"><img src=\"https://i.stack.imgur.com/8yVDn.png\" alt=\"sample output of mysql db\"></a></p>\n\n<blockquote>\n <p>show table status where name=your_desired_table_name;</p>\n</blockquote>\n\n<p>It will show the storage engine used by the mentioned table.</p>\n" }, { "answer_id": 54688991, "author": "mytuny", "author_id": 9052686, "author_profile": "https://Stackoverflow.com/users/9052686", "pm_score": 0, "selected": false, "text": "<p>If you are a <strong>GUI</strong> guy and just want to find it in <strong>PhpMyAdmin</strong>, than pick the table of your choice and head over the <code>Operations</code> tab >> <code>Table options</code> >> <code>Storage Engine</code>.\nYou can even change it from there using the drop-down options list.</p>\n\n<p>PS: This guide is based on version 4.8 of PhpMyAdmin. Can't guarantee the same path for very older versions.</p>\n" }, { "answer_id": 69294846, "author": "mabreu0", "author_id": 6016579, "author_profile": "https://Stackoverflow.com/users/6016579", "pm_score": 0, "selected": false, "text": "<p>Apart from examples showed in previous entries, you can also get that from information_schema db with standard query as follows :</p>\n<pre><code>use information_schema;\n\nselect NAME from INNODB_TABLES where NAME like &quot;db_name%&quot;;\n</code></pre>\n" } ]
2008/10/17
[ "https://Stackoverflow.com/questions/213543", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9435/" ]
My MySQL database contains several tables using different storage engines (specifically myisam and innodb). How can I find out which tables are using which engine?
``` SHOW TABLE STATUS WHERE Name = 'xxx' ``` This will give you (among other things) an `Engine` column, which is what you want.
213,568
<p>Backstory: I have a PKCS#12 (p12) certificate with a symmetric cipher (password) that I used OpenSSL to convert to a PEM; opening that as text I see it contains both a <code>BEGIN/END CERTIFICATE</code> section as well as <code>BEGIN/END RSA PRIVATE KEY</code>. The .NET Framework <code>X509Certificate</code> class only supports the "ASN.1 DER" format, so I used OpenSSL to convert the PEM to DER. Unfortunately it appears doing this doesn't include the private key which is what I need for making an SSL connection with <code>SslStream</code> &amp; <code>TcpClient</code>.</p> <pre><code>X509CertificateCollection certsFromFile = new X509CertificateCollection(); X509Certificate2 cert = new X509Certificate2("my.der.crt"); if (!cert.HasPrivateKey) throw new Exception("No private key"); certsFromFile.Add(cert); TcpClient tcpclient = new TcpClient(hostname, port); SslStream sslstream = new SslStream(tcpclient.GetStream(), false, null, null); sslstream.AuthenticateAsClient(hostname, certsFromFile, SslProtocols.Ssl3, false); sslstream.Close(); tcpclient.Close(); </code></pre> <p>How do I take this PEM file and make it into a DER while retaining the private key information so I can use it in .NET for signing?</p>
[ { "answer_id": 213579, "author": "nsayer", "author_id": 13757, "author_profile": "https://Stackoverflow.com/users/13757", "pm_score": 0, "selected": false, "text": "<p>Certificates and keys are generally stored separately. Cut the PEM file into two files, one with the certificate and one with the key. You can then use the openssl toolkit to convert each file separately into a DER file.</p>\n" }, { "answer_id": 213599, "author": "Neil C. Obremski", "author_id": 9642, "author_profile": "https://Stackoverflow.com/users/9642", "pm_score": 3, "selected": true, "text": "<p>Oops, I'm behind the times! Looks like <code>X509Certificate2</code> can read PKCS#12 files so there's no need for any conversion.</p>\n" } ]
2008/10/17
[ "https://Stackoverflow.com/questions/213568", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9642/" ]
Backstory: I have a PKCS#12 (p12) certificate with a symmetric cipher (password) that I used OpenSSL to convert to a PEM; opening that as text I see it contains both a `BEGIN/END CERTIFICATE` section as well as `BEGIN/END RSA PRIVATE KEY`. The .NET Framework `X509Certificate` class only supports the "ASN.1 DER" format, so I used OpenSSL to convert the PEM to DER. Unfortunately it appears doing this doesn't include the private key which is what I need for making an SSL connection with `SslStream` & `TcpClient`. ``` X509CertificateCollection certsFromFile = new X509CertificateCollection(); X509Certificate2 cert = new X509Certificate2("my.der.crt"); if (!cert.HasPrivateKey) throw new Exception("No private key"); certsFromFile.Add(cert); TcpClient tcpclient = new TcpClient(hostname, port); SslStream sslstream = new SslStream(tcpclient.GetStream(), false, null, null); sslstream.AuthenticateAsClient(hostname, certsFromFile, SslProtocols.Ssl3, false); sslstream.Close(); tcpclient.Close(); ``` How do I take this PEM file and make it into a DER while retaining the private key information so I can use it in .NET for signing?
Oops, I'm behind the times! Looks like `X509Certificate2` can read PKCS#12 files so there's no need for any conversion.
213,584
<p>I have written an Excel VBA macro which imports data from a HTML file (stored locally) before performing calculations on the data.</p> <p>At the moment the HTML file is referred to with an absolute path:</p> <pre><code>Workbooks.Open FileName:="C:\Documents and Settings\Senior Caterer\My Documents\Endurance Calculation\TRICATEndurance Summary.html" </code></pre> <p>However I want to use a relative path to refer to it as opposed to absolute (this is because I want to distribute the spreadsheet to colleagues who might not use the same folder structure). As the html file and the excel spreadsheet sit in the same folder I would not have thought this would be difficult, however I am just completely unable to do it. I have searched on the web and the suggested solutions have all appeared very complicated.</p> <p>I am using Excel 2000 and 2002 at work, but as I plan to distribute it I would want it to work with as many versions of Excel as possible.</p> <p>Any suggestions gratefully received.</p>
[ { "answer_id": 213602, "author": "yalestar", "author_id": 2177, "author_profile": "https://Stackoverflow.com/users/2177", "pm_score": 4, "selected": false, "text": "<p>You could use one of these for the relative path root:</p>\n\n<pre><code>ActiveWorkbook.Path\nThisWorkbook.Path\nApp.Path\n</code></pre>\n" }, { "answer_id": 213818, "author": "Mike Woodhouse", "author_id": 1060, "author_profile": "https://Stackoverflow.com/users/1060", "pm_score": 2, "selected": false, "text": "<p>I think the problem is that opening the file without a path will only work if your \"current directory\" is set correctly.</p>\n\n<p>Try typing \"Debug.Print CurDir\" in the Immediate Window - that should show the location for your default files as set in Tools...Options.</p>\n\n<p>I'm not sure I'm completely happy with it, perhaps because it's somewhat of a legacy VB command, but you could do this:</p>\n\n<pre><code>ChDir ThisWorkbook.Path\n</code></pre>\n\n<p>I think I'd prefer to use ThisWorkbook.Path to construct a path to the HTML file. I'm a big fan of the FileSystemObject in the Scripting Runtime (which always seems to be installed), so I'd be happier to do something like this (after setting a reference to Microsoft Scripting Runtime):</p>\n\n<pre><code>Const HTML_FILE_NAME As String = \"my_input.html\"\n\nWith New FileSystemObject\n With .OpenTextFile(.BuildPath(ThisWorkbook.Path, HTML_FILE_NAME), ForReading)\n ' Now we have a TextStream object that we can use to read the file\n End With\nEnd With\n</code></pre>\n" }, { "answer_id": 214335, "author": "dbb", "author_id": 25675, "author_profile": "https://Stackoverflow.com/users/25675", "pm_score": 7, "selected": true, "text": "<p>Just to clarify what yalestar said, this will give you the relative path:</p>\n\n<pre><code>Workbooks.Open FileName:= ThisWorkbook.Path &amp; \"\\TRICATEndurance Summary.html\"\n</code></pre>\n" }, { "answer_id": 21099670, "author": "SK.", "author_id": 2524202, "author_profile": "https://Stackoverflow.com/users/2524202", "pm_score": 1, "selected": false, "text": "<p>You can provide more flexibility to your users by provide <strong>Browser Button</strong> to them</p>\n\n<pre><code>Private Sub btn_browser_file_Click()\nDim xRow As Long\nDim sh1 As Worksheet\nDim xl_app As Excel.Application\nDim xl_wk As Excel.Workbook\nDim WS As Workbook\nDim xDirect$, xFname$, InitialFoldr$\nInitialFoldr$ = \"C:\\\"\nWith Application.FileDialog(msoFileDialogFolderPicker)\n .InitialFileName = Application.DefaultFilePath &amp; \"\\\"\n .Title = \"Please select a folder to list Files from\"\n .InitialFileName = InitialFoldr$\n .Show\n Range(\"H13\").Activate\n If .SelectedItems.Count &lt;&gt; 0 Then\n xDirect$ = .SelectedItems(1) &amp; \"\\\"\n Range(\"h12\").Value = xDirect$\n xFname$ = Dir(xDirect$, 7)\n Do While xFname$ &lt;&gt; \"\"\n If (Format(FileDateTime(xDirect$ &amp; \"\\\" &amp; xFname$), \"MM/DD/YYYY\") &gt; Format(Range(\"H10\").Value, \"MM/DD/YYYY\")) Then\n ActiveCell.Offset(xRow) = xFname$\n xRow = xRow + 1\n xFname$ = Dir\n Else\n xFname$ = Dir\n xRow = xRow\n End If\n Loop\n End If\nEnd With\n</code></pre>\n\n<p>with this piece of code you can achieve this, easily. <strong>Tested code</strong> </p>\n" }, { "answer_id": 32298258, "author": "Lurds", "author_id": 5281177, "author_profile": "https://Stackoverflow.com/users/5281177", "pm_score": -1, "selected": false, "text": "<p>i think this may help. Below Macro checks if folder exists, if does not then create the folder and save in both xls and pdf formats in such folder. It happens that the folder is shared with the involved people so everybody is updated.</p>\n\n<pre><code>Sub PDF_laudo_e_Prod_SP_Sem_Ajuste_Preco()\n'\n' PDF_laudo_e_Prod_SP_Sem_Ajuste_Preco Macro\n'\n\n'\n\n\nDim MyFolder As String\nDim LaudoName As String\nDim NF1Name As String\nDim OrigFolder As String\n\nMyFolder = ThisWorkbook.path &amp; \"\\\" &amp; Sheets(\"Laudo\").Range(\"C9\")\nLaudoName = Sheets(\"Laudo\").Range(\"K27\")\nNF1Name = Sheets(\"PROD SP sem ajuste\").Range(\"Q3\")\nOrigFolder = ThisWorkbook.path\n\nSheets(\"Laudo\").Select\nColumns(\"D:P\").Select\nSelection.EntireColumn.Hidden = True\n\nIf Dir(MyFolder, vbDirectory) &lt;&gt; \"\" Then\nSheets(\"Laudo\").ExportAsFixedFormat Type:=xlTypePDF, filename:=MyFolder &amp; \"\\\" &amp; LaudoName &amp; \".pdf\", Quality:=xlQualityMinimum, _\nIncludeDocProperties:=True, IgnorePrintAreas:=False, OpenAfterPublish:= _\nFalse\n\nSheets(\"PROD SP sem ajuste\").ExportAsFixedFormat Type:=xlTypePDF, filename:=MyFolder &amp; \"\\\" &amp; NF1Name &amp; \".pdf\", Quality:=xlQualityMinimum, _\nIncludeDocProperties:=True, IgnorePrintAreas:=False, OpenAfterPublish:= _\nFalse\n\nThisWorkbook.SaveAs filename:=MyFolder &amp; \"\\\" &amp; LaudoName\n\nApplication.DisplayAlerts = False\n\nThisWorkbook.SaveAs filename:=OrigFolder &amp; \"\\\" &amp; \"Entregas e Instrucao Barter 2015 - beta\"\n\nApplication.DisplayAlerts = True\n\nElse\nMkDir MyFolder\nSheets(\"Laudo\").ExportAsFixedFormat Type:=xlTypePDF, filename:=MyFolder &amp; \"\\\" &amp; LaudoName &amp; \".pdf\", Quality:=xlQualityMinimum, _\nIncludeDocProperties:=True, IgnorePrintAreas:=False, OpenAfterPublish:= _\nFalse\n\nSheets(\"PROD SP sem ajuste\").ExportAsFixedFormat Type:=xlTypePDF, filename:=MyFolder &amp; \"\\\" &amp; NF1Name &amp; \".pdf\", Quality:=xlQualityMinimum, _\nIncludeDocProperties:=True, IgnorePrintAreas:=False, OpenAfterPublish:= _\nFalse\n\nThisWorkbook.SaveAs filename:=MyFolder &amp; \"\\\" &amp; LaudoName\n\nApplication.DisplayAlerts = False\n\nThisWorkbook.SaveAs filename:=OrigFolder &amp; \"\\\" &amp; \"Entregas e Instrucao Barter 2015 - beta\"\n\nApplication.DisplayAlerts = True\n\nEnd If\n\nSheets(\"Laudo\").Select\nColumns(\"C:Q\").Select\nSelection.EntireColumn.Hidden = False\nRange(\"A1\").Select\n\nEnd Sub\n</code></pre>\n" }, { "answer_id": 55457282, "author": "robotik", "author_id": 2866644, "author_profile": "https://Stackoverflow.com/users/2866644", "pm_score": 2, "selected": false, "text": "<p>if current directory of the operating system is the path of the workbook you are using, <code>Workbooks.Open FileName:= \"TRICATEndurance Summary.html\"</code> would suffice. if you are making calculations with the path, you can refer to current directory as <code>.</code> and then <code>\\</code> to tell the file is in that dir, and in case you have to change the os's current directory to your workbook's path, you can use <code>ChDrive</code> and <code>ChDir</code> to do so.</p>\n\n<pre><code>ChDrive ThisWorkbook.Path\nChDir ThisWorkbook.Path\nWorkbooks.Open FileName:= \".\\TRICATEndurance Summary.html\"\n</code></pre>\n" }, { "answer_id": 64286849, "author": "Paul", "author_id": 14422724, "author_profile": "https://Stackoverflow.com/users/14422724", "pm_score": -1, "selected": false, "text": "<p>It maybe is not the best way to do it. But the only I found to get the Absolute path is to calculate how many times the syntax .. was in the string and then use the function gotoparent as many times that syntax comes in the hyperlink adress. (in my case, my field is a hyperlink address.\nPs: This code requires the reference to microsoft scripting runtime</p>\n<pre><code>Function AbsolutePath(strRelativePath As String, strCurrentFileName As String) As String\nDim fso As Object\nDim strCurrentProjectpath As String\nDim strGoToParentFolder As String\nDim strOrigineFolder As String\nDim strPath As String\nDim lngParentFolder As Long\n\n\n''Pour retrouver le répertoire parent\nSet fso = CreateObject(&quot;Scripting.FileSystemObject&quot;)\n\n'' détermine le répertire du projet actif\nstrCurrentProjectpath = CurrentProject.Path\n\n'' détermine le nom du répertoire dans lequel le fichier d'origine se trouve\nstrOrigineFolder = Replace(Replace(Replace(strRelativePath, strCurrentFileName, &quot;&quot;), &quot;..&quot;, &quot;&quot;), &quot;\\&quot;, &quot;&quot;)\n\n''Extraction du chemin relatif (ex. ..\\..\\..)\nstrGoToParentFolder = Replace(Replace(strRelativePath, strOrigineFolder, &quot;&quot;), strCurrentFileName, &quot;&quot;)\n\n''retourne le nombre de fois qu'il faut remonter au répertoire parent\nlngParentsFolder = Len(Replace(strGoToParentFolder, &quot;\\&quot;, &quot;&quot;)) / 2\n\n''détermine la valeur d'origine du répertoire du début\nstrPath = strCurrentProjectpath\n\nVérifie s 'il faut aller au répertoire parent\nIf lngParentsFolder &lt; 1 Then\n 'si non, alors répertoire parent et répertoire d'origine du fichier\n strPath = strCurrentProjectpath &amp; &quot;\\&quot; &amp; strOrigineFolder\nElse\n ''si oui, nous faisons la boucle pour retourner au répertoire d'origine\n For i = 1 To lngParentsFolder\n strPath = fso.GetParentFolderName(strPath)\n Next i\nEnd If\n\n''retournons le répertoire parent du fichier et son répertoire d'origine [le OUTPUT]\nAbsolutePath = strPath &amp; strOrigineFolder &amp; &quot;\\&quot;\n\nEnd Function\n</code></pre>\n" }, { "answer_id": 64385376, "author": "Petter", "author_id": 4874138, "author_profile": "https://Stackoverflow.com/users/4874138", "pm_score": 0, "selected": false, "text": "<p>Here's my quick and simple function for getting the absolute path from a relative path.</p>\n<p>The difference from the accepted answer is that this function can handle relative paths that moves up to parent folders.</p>\n<p>Example:</p>\n<pre><code>Workbooks.Open FileName:=GetAbsolutePath(&quot;..\\..\\TRICATEndurance Summary.html&quot;)\n</code></pre>\n<p>Code:</p>\n<pre><code>' Gets an absolute path from a relative path in the active workbook\nPublic Function GetAbsolutePath(relativePath As String) As String\n \n Dim absPath As String\n Dim pos As Integer\n \n absPath = ActiveWorkbook.Path\n \n ' Make sure paths are in correct format\n relativePath = Replace(relativePath, &quot;/&quot;, &quot;\\&quot;)\n absPath = Replace(absPath, &quot;/&quot;, &quot;\\&quot;)\n \n Do While Left$(relativePath, 3) = &quot;..\\&quot;\n \n ' Remove level from relative path\n relativePath = Mid$(relativePath, 4)\n \n ' Remove level from absolute path\n pos = InStrRev(absPath, &quot;\\&quot;)\n absPath = Left$(absPath, pos - 1)\n \n Loop\n \n GetAbsolutePath = PathCombine(absPath, relativePath)\n \nEnd Function\n</code></pre>\n" } ]
2008/10/17
[ "https://Stackoverflow.com/questions/213584", "https://Stackoverflow.com", "https://Stackoverflow.com/users/29070/" ]
I have written an Excel VBA macro which imports data from a HTML file (stored locally) before performing calculations on the data. At the moment the HTML file is referred to with an absolute path: ``` Workbooks.Open FileName:="C:\Documents and Settings\Senior Caterer\My Documents\Endurance Calculation\TRICATEndurance Summary.html" ``` However I want to use a relative path to refer to it as opposed to absolute (this is because I want to distribute the spreadsheet to colleagues who might not use the same folder structure). As the html file and the excel spreadsheet sit in the same folder I would not have thought this would be difficult, however I am just completely unable to do it. I have searched on the web and the suggested solutions have all appeared very complicated. I am using Excel 2000 and 2002 at work, but as I plan to distribute it I would want it to work with as many versions of Excel as possible. Any suggestions gratefully received.
Just to clarify what yalestar said, this will give you the relative path: ``` Workbooks.Open FileName:= ThisWorkbook.Path & "\TRICATEndurance Summary.html" ```
213,628
<p>I have embedded a Python interpreter in a C program. Suppose the C program reads some bytes from a file into a char array and learns (somehow) that the bytes represent text with a certain encoding (e.g., ISO 8859-1, Windows-1252, or UTF-8). How do I decode the contents of this char array into a Python string?</p> <p>The Python string should in general be of type <code>unicode</code>—for instance, a <code>0x93</code> in Windows-1252 encoded input becomes a <code>u'\u0201c'</code>.</p> <p>I have attempted to use <code>PyString_Decode</code>, but it always fails when there are non-ASCII characters in the string. Here is an example that fails:</p> <pre><code>#include &lt;Python.h&gt; #include &lt;stdio.h&gt; int main(int argc, char *argv[]) { char c_string[] = { (char)0x93, 0 }; PyObject *py_string; Py_Initialize(); py_string = PyString_Decode(c_string, 1, "windows_1252", "replace"); if (!py_string) { PyErr_Print(); return 1; } return 0; } </code></pre> <p>The error message is <code>UnicodeEncodeError: 'ascii' codec can't encode character u'\u201c' in position 0: ordinal not in range(128)</code>, which indicates that the <code>ascii</code> encoding is used even though we specify <code>windows_1252</code> in the call to <code>PyString_Decode</code>.</p> <p>The following code works around the problem by using <code>PyString_FromString</code> to create a Python string of the undecoded bytes, then calling its <code>decode</code> method:</p> <pre><code>#include &lt;Python.h&gt; #include &lt;stdio.h&gt; int main(int argc, char *argv[]) { char c_string[] = { (char)0x93, 0 }; PyObject *raw, *decoded; Py_Initialize(); raw = PyString_FromString(c_string); printf("Undecoded: "); PyObject_Print(raw, stdout, 0); printf("\n"); decoded = PyObject_CallMethod(raw, "decode", "s", "windows_1252"); Py_DECREF(raw); printf("Decoded: "); PyObject_Print(decoded, stdout, 0); printf("\n"); return 0; } </code></pre>
[ { "answer_id": 213639, "author": "Dan Lenski", "author_id": 20789, "author_profile": "https://Stackoverflow.com/users/20789", "pm_score": 2, "selected": false, "text": "<p>You don't want to decode the string into a Unicode representation, you just want to treat it as an array of bytes, right?</p>\n\n<p>Just use <code>PyString_FromString</code>:</p>\n\n<pre><code>char *cstring;\nPyObject *pystring = PyString_FromString(cstring);\n</code></pre>\n\n<p>That's all. Now you have a Python <code>str()</code> object. See docs here: <a href=\"https://docs.python.org/2/c-api/string.html\" rel=\"nofollow noreferrer\">https://docs.python.org/2/c-api/string.html</a></p>\n\n<p>I'm a little bit confused about how to specify \"str\" or \"unicode.\" They are quite different if you have non-ASCII characters. If you want to decode a C string <strong>and</strong> you know exactly what character set it's in, then yes, <code>PyString_DecodeString</code> is a good place to start.</p>\n" }, { "answer_id": 213795, "author": "Alex Coventry", "author_id": 1941213, "author_profile": "https://Stackoverflow.com/users/1941213", "pm_score": 2, "selected": false, "text": "<p>Try calling <a href=\"https://docs.python.org/c-api/exceptions.html\" rel=\"nofollow noreferrer\"><code>PyErr_Print()</code></a> in the \"<code>if (!py_string)</code>\" clause. Perhaps the python exception will give you some more information.</p>\n" }, { "answer_id": 215507, "author": "Tony Meyer", "author_id": 4966, "author_profile": "https://Stackoverflow.com/users/4966", "pm_score": 4, "selected": true, "text": "<p>PyString_Decode does this:</p>\n\n<pre><code>PyObject *PyString_Decode(const char *s,\n Py_ssize_t size,\n const char *encoding,\n const char *errors)\n{\n PyObject *v, *str;\n\n str = PyString_FromStringAndSize(s, size);\n if (str == NULL)\n return NULL;\n v = PyString_AsDecodedString(str, encoding, errors);\n Py_DECREF(str);\n return v;\n}\n</code></pre>\n\n<p>IOW, it does basically what you're doing in your second example - converts to a string, then decode the string. The problem here arises from PyString_AsDecodedString, rather than PyString_AsDecodedObject. PyString_AsDecodedString does PyString_AsDecodedObject, but then tries to convert the resulting unicode object into a string object with the default encoding (for you, looks like that's ASCII). That's where it fails.</p>\n\n<p>I believe you'll need to do two calls - but you can use PyString_AsDecodedObject rather than calling the python \"decode\" method. Something like:</p>\n\n<pre><code>#include &lt;Python.h&gt;\n#include &lt;stdio.h&gt;\n\nint main(int argc, char *argv[])\n{\n char c_string[] = { (char)0x93, 0 };\n PyObject *py_string, *py_unicode;\n\n Py_Initialize();\n\n py_string = PyString_FromStringAndSize(c_string, 1);\n if (!py_string) {\n PyErr_Print();\n return 1;\n }\n py_unicode = PyString_AsDecodedObject(py_string, \"windows_1252\", \"replace\");\n Py_DECREF(py_string);\n\n return 0;\n}\n</code></pre>\n\n<p>I'm not entirely sure what the reasoning behind PyString_Decode working this way is. A <a href=\"http://mail.python.org/pipermail/python-dev/2001-May/014547.html\" rel=\"nofollow noreferrer\">very old thread on python-dev</a> seems to indicate that it has something to do with chaining the output, but since the Python methods don't do the same, I'm not sure if that's still relevant.</p>\n" } ]
2008/10/17
[ "https://Stackoverflow.com/questions/213628", "https://Stackoverflow.com", "https://Stackoverflow.com/users/17498/" ]
I have embedded a Python interpreter in a C program. Suppose the C program reads some bytes from a file into a char array and learns (somehow) that the bytes represent text with a certain encoding (e.g., ISO 8859-1, Windows-1252, or UTF-8). How do I decode the contents of this char array into a Python string? The Python string should in general be of type `unicode`—for instance, a `0x93` in Windows-1252 encoded input becomes a `u'\u0201c'`. I have attempted to use `PyString_Decode`, but it always fails when there are non-ASCII characters in the string. Here is an example that fails: ``` #include <Python.h> #include <stdio.h> int main(int argc, char *argv[]) { char c_string[] = { (char)0x93, 0 }; PyObject *py_string; Py_Initialize(); py_string = PyString_Decode(c_string, 1, "windows_1252", "replace"); if (!py_string) { PyErr_Print(); return 1; } return 0; } ``` The error message is `UnicodeEncodeError: 'ascii' codec can't encode character u'\u201c' in position 0: ordinal not in range(128)`, which indicates that the `ascii` encoding is used even though we specify `windows_1252` in the call to `PyString_Decode`. The following code works around the problem by using `PyString_FromString` to create a Python string of the undecoded bytes, then calling its `decode` method: ``` #include <Python.h> #include <stdio.h> int main(int argc, char *argv[]) { char c_string[] = { (char)0x93, 0 }; PyObject *raw, *decoded; Py_Initialize(); raw = PyString_FromString(c_string); printf("Undecoded: "); PyObject_Print(raw, stdout, 0); printf("\n"); decoded = PyObject_CallMethod(raw, "decode", "s", "windows_1252"); Py_DECREF(raw); printf("Decoded: "); PyObject_Print(decoded, stdout, 0); printf("\n"); return 0; } ```
PyString\_Decode does this: ``` PyObject *PyString_Decode(const char *s, Py_ssize_t size, const char *encoding, const char *errors) { PyObject *v, *str; str = PyString_FromStringAndSize(s, size); if (str == NULL) return NULL; v = PyString_AsDecodedString(str, encoding, errors); Py_DECREF(str); return v; } ``` IOW, it does basically what you're doing in your second example - converts to a string, then decode the string. The problem here arises from PyString\_AsDecodedString, rather than PyString\_AsDecodedObject. PyString\_AsDecodedString does PyString\_AsDecodedObject, but then tries to convert the resulting unicode object into a string object with the default encoding (for you, looks like that's ASCII). That's where it fails. I believe you'll need to do two calls - but you can use PyString\_AsDecodedObject rather than calling the python "decode" method. Something like: ``` #include <Python.h> #include <stdio.h> int main(int argc, char *argv[]) { char c_string[] = { (char)0x93, 0 }; PyObject *py_string, *py_unicode; Py_Initialize(); py_string = PyString_FromStringAndSize(c_string, 1); if (!py_string) { PyErr_Print(); return 1; } py_unicode = PyString_AsDecodedObject(py_string, "windows_1252", "replace"); Py_DECREF(py_string); return 0; } ``` I'm not entirely sure what the reasoning behind PyString\_Decode working this way is. A [very old thread on python-dev](http://mail.python.org/pipermail/python-dev/2001-May/014547.html) seems to indicate that it has something to do with chaining the output, but since the Python methods don't do the same, I'm not sure if that's still relevant.
213,630
<p>I'm writing a sample console service host and I want to plug into WCF stack to be able to print a message to console when new message arrives, even if it won't get processed by the service at the moment (because service is working on previous calls). This is based on my assumption that messages arriving get queued by the WCF, is that correct?</p> <p>Additionally, I'm using netTcpBinding if this is important. </p>
[ { "answer_id": 213639, "author": "Dan Lenski", "author_id": 20789, "author_profile": "https://Stackoverflow.com/users/20789", "pm_score": 2, "selected": false, "text": "<p>You don't want to decode the string into a Unicode representation, you just want to treat it as an array of bytes, right?</p>\n\n<p>Just use <code>PyString_FromString</code>:</p>\n\n<pre><code>char *cstring;\nPyObject *pystring = PyString_FromString(cstring);\n</code></pre>\n\n<p>That's all. Now you have a Python <code>str()</code> object. See docs here: <a href=\"https://docs.python.org/2/c-api/string.html\" rel=\"nofollow noreferrer\">https://docs.python.org/2/c-api/string.html</a></p>\n\n<p>I'm a little bit confused about how to specify \"str\" or \"unicode.\" They are quite different if you have non-ASCII characters. If you want to decode a C string <strong>and</strong> you know exactly what character set it's in, then yes, <code>PyString_DecodeString</code> is a good place to start.</p>\n" }, { "answer_id": 213795, "author": "Alex Coventry", "author_id": 1941213, "author_profile": "https://Stackoverflow.com/users/1941213", "pm_score": 2, "selected": false, "text": "<p>Try calling <a href=\"https://docs.python.org/c-api/exceptions.html\" rel=\"nofollow noreferrer\"><code>PyErr_Print()</code></a> in the \"<code>if (!py_string)</code>\" clause. Perhaps the python exception will give you some more information.</p>\n" }, { "answer_id": 215507, "author": "Tony Meyer", "author_id": 4966, "author_profile": "https://Stackoverflow.com/users/4966", "pm_score": 4, "selected": true, "text": "<p>PyString_Decode does this:</p>\n\n<pre><code>PyObject *PyString_Decode(const char *s,\n Py_ssize_t size,\n const char *encoding,\n const char *errors)\n{\n PyObject *v, *str;\n\n str = PyString_FromStringAndSize(s, size);\n if (str == NULL)\n return NULL;\n v = PyString_AsDecodedString(str, encoding, errors);\n Py_DECREF(str);\n return v;\n}\n</code></pre>\n\n<p>IOW, it does basically what you're doing in your second example - converts to a string, then decode the string. The problem here arises from PyString_AsDecodedString, rather than PyString_AsDecodedObject. PyString_AsDecodedString does PyString_AsDecodedObject, but then tries to convert the resulting unicode object into a string object with the default encoding (for you, looks like that's ASCII). That's where it fails.</p>\n\n<p>I believe you'll need to do two calls - but you can use PyString_AsDecodedObject rather than calling the python \"decode\" method. Something like:</p>\n\n<pre><code>#include &lt;Python.h&gt;\n#include &lt;stdio.h&gt;\n\nint main(int argc, char *argv[])\n{\n char c_string[] = { (char)0x93, 0 };\n PyObject *py_string, *py_unicode;\n\n Py_Initialize();\n\n py_string = PyString_FromStringAndSize(c_string, 1);\n if (!py_string) {\n PyErr_Print();\n return 1;\n }\n py_unicode = PyString_AsDecodedObject(py_string, \"windows_1252\", \"replace\");\n Py_DECREF(py_string);\n\n return 0;\n}\n</code></pre>\n\n<p>I'm not entirely sure what the reasoning behind PyString_Decode working this way is. A <a href=\"http://mail.python.org/pipermail/python-dev/2001-May/014547.html\" rel=\"nofollow noreferrer\">very old thread on python-dev</a> seems to indicate that it has something to do with chaining the output, but since the Python methods don't do the same, I'm not sure if that's still relevant.</p>\n" } ]
2008/10/17
[ "https://Stackoverflow.com/questions/213630", "https://Stackoverflow.com", "https://Stackoverflow.com/users/13163/" ]
I'm writing a sample console service host and I want to plug into WCF stack to be able to print a message to console when new message arrives, even if it won't get processed by the service at the moment (because service is working on previous calls). This is based on my assumption that messages arriving get queued by the WCF, is that correct? Additionally, I'm using netTcpBinding if this is important.
PyString\_Decode does this: ``` PyObject *PyString_Decode(const char *s, Py_ssize_t size, const char *encoding, const char *errors) { PyObject *v, *str; str = PyString_FromStringAndSize(s, size); if (str == NULL) return NULL; v = PyString_AsDecodedString(str, encoding, errors); Py_DECREF(str); return v; } ``` IOW, it does basically what you're doing in your second example - converts to a string, then decode the string. The problem here arises from PyString\_AsDecodedString, rather than PyString\_AsDecodedObject. PyString\_AsDecodedString does PyString\_AsDecodedObject, but then tries to convert the resulting unicode object into a string object with the default encoding (for you, looks like that's ASCII). That's where it fails. I believe you'll need to do two calls - but you can use PyString\_AsDecodedObject rather than calling the python "decode" method. Something like: ``` #include <Python.h> #include <stdio.h> int main(int argc, char *argv[]) { char c_string[] = { (char)0x93, 0 }; PyObject *py_string, *py_unicode; Py_Initialize(); py_string = PyString_FromStringAndSize(c_string, 1); if (!py_string) { PyErr_Print(); return 1; } py_unicode = PyString_AsDecodedObject(py_string, "windows_1252", "replace"); Py_DECREF(py_string); return 0; } ``` I'm not entirely sure what the reasoning behind PyString\_Decode working this way is. A [very old thread on python-dev](http://mail.python.org/pipermail/python-dev/2001-May/014547.html) seems to indicate that it has something to do with chaining the output, but since the Python methods don't do the same, I'm not sure if that's still relevant.
213,638
<p>I'm using C#, .NET 3.5. I understand how to utilize events, how to declare them in my class, how to hook them from somewhere else, etc. A contrived example:</p> <pre><code>public class MyList { private List&lt;string&gt; m_Strings = new List&lt;string&gt;(); public EventHandler&lt;EventArgs&gt; ElementAddedEvent; public void Add(string value) { m_Strings.Add(value); if (ElementAddedEvent != null) ElementAddedEvent(value, EventArgs.Empty); } } [TestClass] public class TestMyList { private bool m_Fired = false; [TestMethod] public void TestEvents() { MyList tmp = new MyList(); tmp.ElementAddedEvent += new EventHandler&lt;EventArgs&gt;(Fired); tmp.Add("test"); Assert.IsTrue(m_Fired); } private void Fired(object sender, EventArgs args) { m_Fired = true; } } </code></pre> <p>However, what I do <em>not</em> understand, is when one declares an event handler</p> <pre><code>public EventHandler&lt;EventArgs&gt; ElementAddedEvent; </code></pre> <p>It's never initialized - so what, exactly, is ElementAddedEvent? What does it point to? The following won't work, because the EventHandler is never initialized:</p> <pre><code>[TestClass] public class TestMyList { private bool m_Fired = false; [TestMethod] public void TestEvents() { EventHandler&lt;EventArgs&gt; somethingHappend; somethingHappend += new EventHandler&lt;EventArgs&gt;(Fired); somethingHappend(this, EventArgs.Empty); Assert.IsTrue(m_Fired); } private void Fired(object sender, EventArgs args) { m_Fired = true; } } </code></pre> <p>I notice that there is an EventHandler.CreateDelegate(...), but all the method signatures suggest this is only used for attaching Delegates to an already existing EventHandler through the typical ElementAddedEvent += new EventHandler(MyMethod).</p> <p>I'm not sure if <em>what</em> I am trying to do will help... but ultimately I'd like to come up with an abstract parent DataContext in LINQ whose children can register which table Types they want "observed" so I can have events such as BeforeUpdate and AfterUpdate, but specific to types. Something like this:</p> <pre><code>public class BaseDataContext : DataContext { private static Dictionary&lt;Type, Dictionary&lt;ChangeAction, EventHandler&gt;&gt; m_ObservedTypes = new Dictionary&lt;Type, Dictionary&lt;ChangeAction, EventHandler&gt;&gt;(); public static void Observe(Type type) { if (m_ObservedTypes.ContainsKey(type) == false) { m_ObservedTypes.Add(type, new Dictionary&lt;ChangeAction, EventHandler&gt;()); EventHandler eventHandler = EventHandler.CreateDelegate(typeof(EventHandler), null, null) as EventHandler; m_ObservedTypes[type].Add(ChangeAction.Insert, eventHandler); eventHandler = EventHandler.CreateDelegate(typeof(EventHandler), null, null) as EventHandler; m_ObservedTypes[type].Add(ChangeAction.Update, eventHandler); eventHandler = EventHandler.CreateDelegate(typeof(EventHandler), null, null) as EventHandler; m_ObservedTypes[type].Add(ChangeAction.Delete, eventHandler); } } public static Dictionary&lt;Type, Dictionary&lt;ChangeAction, EventHandler&gt;&gt; Events { get { return m_ObservedTypes; } } } public class MyClass { public MyClass() { BaseDataContext.Events[typeof(User)][ChangeAction.Update] += new EventHandler(OnUserUpdate); } public void OnUserUpdated(object sender, EventArgs args) { // do something } } </code></pre> <p>Thinking about this made me realize I don't really understand what's happening under the hod with events - and I would like to understand :)</p>
[ { "answer_id": 213651, "author": "Jon Skeet", "author_id": 22656, "author_profile": "https://Stackoverflow.com/users/22656", "pm_score": 7, "selected": true, "text": "<p>I've written this up in a fair amount of detail in <a href=\"http://pobox.com/~skeet/csharp/events.html\" rel=\"noreferrer\">an article</a>, but here's the summary, assuming you're reasonably happy with <a href=\"http://msdn.microsoft.com/en-us/library/ms173171.aspx\" rel=\"noreferrer\">delegates</a> themselves:</p>\n\n<ul>\n<li>An event is just an \"add\" method and a \"remove\" method, in the same way that a property is really just a \"get\" method and a \"set\" method. (In fact, the CLI allows a \"raise/fire\" method as well, but C# never generates this.) Metadata describes the event with references to the methods.</li>\n<li>When you declare a <em><a href=\"http://msdn.microsoft.com/en-us/library/aa664455.aspx\" rel=\"noreferrer\">field-like event</a></em> (like your ElementAddedEvent) the compiler generates the methods <em>and a private field</em> (of the same type as the delegate). Within the class, when you refer to ElementAddedEvent you're referring to the field. Outside the class, you're referring to the field.</li>\n<li>When anyone subscribes to an event (with the += operator) that calls the add method. When they unsubscribe (with the -= operator) that calls the remove.</li>\n<li><p>For field-like events, there's some synchronization but otherwise the add/remove just call Delegate.<a href=\"http://msdn.microsoft.com/en-us/library/system.delegate.combine.aspx\" rel=\"noreferrer\">Combine</a>/<a href=\"http://msdn.microsoft.com/en-us/library/system.delegate.remove.aspx\" rel=\"noreferrer\">Remove</a> to change the value of the auto-generated field. Both of these operations assign to the backing field - remember that delegates are immutable. In other words, the autogenerated code is very much like this:</p>\n\n<pre><code>// Backing field\n// The underscores just make it simpler to see what's going on here.\n// In the rest of your source code for this class, if you refer to\n// ElementAddedEvent, you're really referring to this field.\nprivate EventHandler&lt;EventArgs&gt; __ElementAddedEvent;\n\n// Actual event\npublic EventHandler&lt;EventArgs&gt; ElementAddedEvent\n{\n add\n {\n lock(this)\n {\n // Equivalent to __ElementAddedEvent += value;\n __ElementAddedEvent = Delegate.Combine(__ElementAddedEvent, value);\n }\n }\n remove\n {\n lock(this)\n {\n // Equivalent to __ElementAddedEvent -= value;\n __ElementAddedEvent = Delegate.Remove(__ElementAddedEvent, value);\n }\n }\n}\n</code></pre></li>\n<li><p>The initial value of the generated field in your case is <code>null</code> - and it will always become <code>null</code> again if all subscribers are removed, as that is the behaviour of Delegate.Remove.</p></li>\n<li><p>If you want a \"no-op\" handler to subscribe to your event, so as to avoid the nullity check, you can do:</p>\n\n<pre><code>public EventHandler&lt;EventArgs&gt; ElementAddedEvent = delegate {};\n</code></pre>\n\n<p>The <code>delegate {}</code> is just an anonymous method which doesn't care about its parameters and does nothing.</p></li>\n</ul>\n\n<p>If there's anything that's still unclear, please ask and I'll try to help!</p>\n" }, { "answer_id": 213660, "author": "Yes - that Jake.", "author_id": 5287, "author_profile": "https://Stackoverflow.com/users/5287", "pm_score": -1, "selected": false, "text": "<p>Under the hood, events are just delegates with special calling conventions. (For example, you don't have to check for nullity before raising an event.)</p>\n\n<p>In pseudocode, Event.Invoke() breaks down like this:</p>\n\n<p>If Event Has Listeners\n Call each listener synchronously on this thread in arbitrary order.</p>\n\n<p>Since events are multicast, they will have zero or more listeners, held in a collection. The CLR will loop through them, calling each in an arbitrary order.</p>\n\n<p>One big caveat to remember is that event handlers execute in the same thread as the event is raised in. It's a common mental error to think of them as spawning a new thread. They do not.</p>\n" } ]
2008/10/17
[ "https://Stackoverflow.com/questions/213638", "https://Stackoverflow.com", "https://Stackoverflow.com/users/17803/" ]
I'm using C#, .NET 3.5. I understand how to utilize events, how to declare them in my class, how to hook them from somewhere else, etc. A contrived example: ``` public class MyList { private List<string> m_Strings = new List<string>(); public EventHandler<EventArgs> ElementAddedEvent; public void Add(string value) { m_Strings.Add(value); if (ElementAddedEvent != null) ElementAddedEvent(value, EventArgs.Empty); } } [TestClass] public class TestMyList { private bool m_Fired = false; [TestMethod] public void TestEvents() { MyList tmp = new MyList(); tmp.ElementAddedEvent += new EventHandler<EventArgs>(Fired); tmp.Add("test"); Assert.IsTrue(m_Fired); } private void Fired(object sender, EventArgs args) { m_Fired = true; } } ``` However, what I do *not* understand, is when one declares an event handler ``` public EventHandler<EventArgs> ElementAddedEvent; ``` It's never initialized - so what, exactly, is ElementAddedEvent? What does it point to? The following won't work, because the EventHandler is never initialized: ``` [TestClass] public class TestMyList { private bool m_Fired = false; [TestMethod] public void TestEvents() { EventHandler<EventArgs> somethingHappend; somethingHappend += new EventHandler<EventArgs>(Fired); somethingHappend(this, EventArgs.Empty); Assert.IsTrue(m_Fired); } private void Fired(object sender, EventArgs args) { m_Fired = true; } } ``` I notice that there is an EventHandler.CreateDelegate(...), but all the method signatures suggest this is only used for attaching Delegates to an already existing EventHandler through the typical ElementAddedEvent += new EventHandler(MyMethod). I'm not sure if *what* I am trying to do will help... but ultimately I'd like to come up with an abstract parent DataContext in LINQ whose children can register which table Types they want "observed" so I can have events such as BeforeUpdate and AfterUpdate, but specific to types. Something like this: ``` public class BaseDataContext : DataContext { private static Dictionary<Type, Dictionary<ChangeAction, EventHandler>> m_ObservedTypes = new Dictionary<Type, Dictionary<ChangeAction, EventHandler>>(); public static void Observe(Type type) { if (m_ObservedTypes.ContainsKey(type) == false) { m_ObservedTypes.Add(type, new Dictionary<ChangeAction, EventHandler>()); EventHandler eventHandler = EventHandler.CreateDelegate(typeof(EventHandler), null, null) as EventHandler; m_ObservedTypes[type].Add(ChangeAction.Insert, eventHandler); eventHandler = EventHandler.CreateDelegate(typeof(EventHandler), null, null) as EventHandler; m_ObservedTypes[type].Add(ChangeAction.Update, eventHandler); eventHandler = EventHandler.CreateDelegate(typeof(EventHandler), null, null) as EventHandler; m_ObservedTypes[type].Add(ChangeAction.Delete, eventHandler); } } public static Dictionary<Type, Dictionary<ChangeAction, EventHandler>> Events { get { return m_ObservedTypes; } } } public class MyClass { public MyClass() { BaseDataContext.Events[typeof(User)][ChangeAction.Update] += new EventHandler(OnUserUpdate); } public void OnUserUpdated(object sender, EventArgs args) { // do something } } ``` Thinking about this made me realize I don't really understand what's happening under the hod with events - and I would like to understand :)
I've written this up in a fair amount of detail in [an article](http://pobox.com/~skeet/csharp/events.html), but here's the summary, assuming you're reasonably happy with [delegates](http://msdn.microsoft.com/en-us/library/ms173171.aspx) themselves: * An event is just an "add" method and a "remove" method, in the same way that a property is really just a "get" method and a "set" method. (In fact, the CLI allows a "raise/fire" method as well, but C# never generates this.) Metadata describes the event with references to the methods. * When you declare a *[field-like event](http://msdn.microsoft.com/en-us/library/aa664455.aspx)* (like your ElementAddedEvent) the compiler generates the methods *and a private field* (of the same type as the delegate). Within the class, when you refer to ElementAddedEvent you're referring to the field. Outside the class, you're referring to the field. * When anyone subscribes to an event (with the += operator) that calls the add method. When they unsubscribe (with the -= operator) that calls the remove. * For field-like events, there's some synchronization but otherwise the add/remove just call Delegate.[Combine](http://msdn.microsoft.com/en-us/library/system.delegate.combine.aspx)/[Remove](http://msdn.microsoft.com/en-us/library/system.delegate.remove.aspx) to change the value of the auto-generated field. Both of these operations assign to the backing field - remember that delegates are immutable. In other words, the autogenerated code is very much like this: ``` // Backing field // The underscores just make it simpler to see what's going on here. // In the rest of your source code for this class, if you refer to // ElementAddedEvent, you're really referring to this field. private EventHandler<EventArgs> __ElementAddedEvent; // Actual event public EventHandler<EventArgs> ElementAddedEvent { add { lock(this) { // Equivalent to __ElementAddedEvent += value; __ElementAddedEvent = Delegate.Combine(__ElementAddedEvent, value); } } remove { lock(this) { // Equivalent to __ElementAddedEvent -= value; __ElementAddedEvent = Delegate.Remove(__ElementAddedEvent, value); } } } ``` * The initial value of the generated field in your case is `null` - and it will always become `null` again if all subscribers are removed, as that is the behaviour of Delegate.Remove. * If you want a "no-op" handler to subscribe to your event, so as to avoid the nullity check, you can do: ``` public EventHandler<EventArgs> ElementAddedEvent = delegate {}; ``` The `delegate {}` is just an anonymous method which doesn't care about its parameters and does nothing. If there's anything that's still unclear, please ask and I'll try to help!
213,644
<p>How many can relate do this?</p> <blockquote> <h1>Server Error in / Application</h1> <hr> <h2><em>Object reference not set to an object</em></h2> <p><strong>Description:</strong> Object reference not set to an object.</p> <p><strong>Exception Details:</strong> <code>System.NullReferenceException</code>: Object reference not set to an object.</p> <p><strong>Source Error:</strong></p> <pre><code>Line 56: posts.Add(post); </code></pre> </blockquote> <p>On a more serious note, what are the first things you look for when you see the yellow screen of death? Half the time the debug trace isn't actually telling you what the problem is (understandable I guess).</p> <p>I must admit, I still use <code>Response.Write</code> more than I should. I just get lazy going through the debugger. What techniques do you use to debug the problem?</p>
[ { "answer_id": 213667, "author": "UnhipGlint", "author_id": 13010, "author_profile": "https://Stackoverflow.com/users/13010", "pm_score": 1, "selected": false, "text": "<p>If I'm unable to identify/resolve the issue using the error message that the page presents to me, I will typically try to use the Windows Event Viewer to help me identify what is causing the issue.</p>\n\n<p>For example, SharePoint errors are sometimes far less than descriptive. So, I'll combine what I'm seeing on the Y.S.O.D. with error messages from the Event Viewer to help me narrow down the cause.</p>\n\n<p>I will do my best to ask a co-worker or other associate that I think might have some experience that might help. If I'm still unable to identify the cause, I will resort to Google armed with all the information.</p>\n" }, { "answer_id": 213676, "author": "tvanfosson", "author_id": 12950, "author_profile": "https://Stackoverflow.com/users/12950", "pm_score": 0, "selected": false, "text": "<p>I usually do my debugging on my local machine with the Cassini web server (comes with VS 2005/2008). If I see an exception on my QA or, heaven forbid, my production box it's usually because I forgot to update my connection strings so that they point to the QA/production database instead of my local machine.</p>\n\n<p>In other cases, I've found the stack traces to be very helpful in determining where to provide breakpoints so I step through it in the debugger and examine the data at runtime. The only time I've written any debugging information on the page was when trying to find some performance issues that I couldn't replicate on my developer instance. In this case I wrote some hidden fields that contained timing information about various parts of the render process.</p>\n" }, { "answer_id": 213682, "author": "Levi Rosol", "author_id": 23458, "author_profile": "https://Stackoverflow.com/users/23458", "pm_score": 0, "selected": false, "text": "<p>the error info provided, assuming you are in debug mode, will give you information as to what line the error actually occurred on, along with the lines of code leading up to the error. This info should give you a good start on defining where to set your break points for debugging.</p>\n\n<p>I was once in your shoes many moons ago, using response.write for debugging. Once you start using the IDE and debugger as it's intended you'll find yourself pulling out less hair and getting to the solutions much faster. </p>\n\n<p>Also, opening up the immediate window while debugging is gonna make your life even more happy.</p>\n" }, { "answer_id": 213688, "author": "DOK", "author_id": 27637, "author_profile": "https://Stackoverflow.com/users/27637", "pm_score": 1, "selected": false, "text": "<p>Here's how I try to reduce the number of YSODs. One of the first things I do when starting work on an app is to create a custom exception class. </p>\n\n<ul>\n<li><p>Add properties such as the SQL\nstatement being run. Two display\nmessage text fields, one for display\nto users, one for display to\ndevelopers (in debug mode) Who is\nthe logged-in user. Get all the form\nvariables so you know what they were\ntrying to enter.</p></li>\n<li><p>Log the errors somewhere (event log\nis good, if you can access the web\nserver; logging to the database is\nless successful when so many\nexceptions are inability to access\nthe database).</p></li>\n<li><p>Create code in the MasterPage or web page base class Page Error events and Application Error events to do the logging.</p></li>\n<li><p>Create a custom error page. When in\ndebug mode, the custom error page\ndisplays everything. When not in\ndebug mode (production), display\nonly selected properties of the\ncustom exception.</p></li>\n</ul>\n\n<p>Investing the time up front to do this will save you many hours of anguish later.</p>\n" }, { "answer_id": 213722, "author": "Ian Nelson", "author_id": 2084, "author_profile": "https://Stackoverflow.com/users/2084", "pm_score": 0, "selected": false, "text": "<p>Use a decent logging framework such as <a href=\"http://logging.apache.org/log4net/index.html\" rel=\"nofollow noreferrer\">log4net</a>, and be liberal in your use of DEBUG-level logging.</p>\n\n<p>It's essentially a neater version of your Response.Write approach, which can be left in your production code and \"switched on\" when required.</p>\n" } ]
2008/10/17
[ "https://Stackoverflow.com/questions/213644", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
How many can relate do this? > > Server Error in / Application > ============================= > > > > > --- > > > *Object reference not set to an object* > --------------------------------------- > > > **Description:** Object reference not set to an object. > > > **Exception Details:** `System.NullReferenceException`: Object reference not set to an object. > > > **Source Error:** > > > > ``` > Line 56: posts.Add(post); > > ``` > > On a more serious note, what are the first things you look for when you see the yellow screen of death? Half the time the debug trace isn't actually telling you what the problem is (understandable I guess). I must admit, I still use `Response.Write` more than I should. I just get lazy going through the debugger. What techniques do you use to debug the problem?
If I'm unable to identify/resolve the issue using the error message that the page presents to me, I will typically try to use the Windows Event Viewer to help me identify what is causing the issue. For example, SharePoint errors are sometimes far less than descriptive. So, I'll combine what I'm seeing on the Y.S.O.D. with error messages from the Event Viewer to help me narrow down the cause. I will do my best to ask a co-worker or other associate that I think might have some experience that might help. If I'm still unable to identify the cause, I will resort to Google armed with all the information.
213,657
<p>I am using an ASP page where I have to read a CSV file and insert it into DB table "Employee". I am creating an object of TestReader. How can I write a loop to execute up to the number of rows/records of the CSV file which is being read?</p>
[ { "answer_id": 213739, "author": "jeff.willis", "author_id": 9829, "author_profile": "https://Stackoverflow.com/users/9829", "pm_score": 4, "selected": false, "text": "<p>Do not try to parse the file yourself, you'll just give yourself a headache. There's quite a bit more to it than splitting on newline and commas. </p>\n\n<p>You can use OLEDB to open up the file in a recordset and read it just as you would a db table. Something like this:</p>\n\n<pre><code>Dim strConn, conn, rs\n\nstrConn = \"Provider=Microsoft.Jet.OLEDB.4.0;Data Source=\" &amp; _\nServer.MapPath(\"path to folder\") &amp; \";Extended Properties='text;HDR=Yes;FMT-Delimited';\"\n\nSet conn = Server.CreateObject(\"ADODB.Connection\")\nconn.Open strConn\n\nSet rs = Server.CreateObject(\"ADODB.recordset\")\nrs.open \"SELECT * FROM myfile.csv\", conn\n\nwhile not rs.eof\n ...\n rs.movenext\nwend\n</code></pre>\n\n<p>My vbscript is rusty, so verify the syntax.</p>\n\n<p><strong>edit:</strong> harpo's comment brings up a good point about field definitions. Defining a schema.ini file allows you to define the number and datatypes of the expected fields. See: You can handle this by defining a schema.ini file. see: <a href=\"http://msdn.microsoft.com/en-us/library/ms709353.aspx\" rel=\"noreferrer\">http://msdn.microsoft.com/en-us/library/ms709353.aspx</a></p>\n" }, { "answer_id": 213756, "author": "Fionnuala", "author_id": 2548, "author_profile": "https://Stackoverflow.com/users/2548", "pm_score": 3, "selected": false, "text": "<p>Why not just insert the CSV? For example:</p>\n\n<pre><code>SELECT * INTO MyTable FROM OPENDATASOURCE('Microsoft.JET.OLEDB.4.0', \n'Data Source=F:\\MyDirectory;Extended Properties=\"text;HDR=No\"')...\n[MyCsvFile#csv]\n</code></pre>\n\n<p>From: <a href=\"http://coding.derkeiler.com/Archive/Delphi/borland.public.delphi.database.ado/2007-05/msg00057.html\" rel=\"noreferrer\">http://coding.derkeiler.com/Archive/Delphi/borland.public.delphi.database.ado/2007-05/msg00057.html</a></p>\n" } ]
2008/10/17
[ "https://Stackoverflow.com/questions/213657", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
I am using an ASP page where I have to read a CSV file and insert it into DB table "Employee". I am creating an object of TestReader. How can I write a loop to execute up to the number of rows/records of the CSV file which is being read?
Do not try to parse the file yourself, you'll just give yourself a headache. There's quite a bit more to it than splitting on newline and commas. You can use OLEDB to open up the file in a recordset and read it just as you would a db table. Something like this: ``` Dim strConn, conn, rs strConn = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" & _ Server.MapPath("path to folder") & ";Extended Properties='text;HDR=Yes;FMT-Delimited';" Set conn = Server.CreateObject("ADODB.Connection") conn.Open strConn Set rs = Server.CreateObject("ADODB.recordset") rs.open "SELECT * FROM myfile.csv", conn while not rs.eof ... rs.movenext wend ``` My vbscript is rusty, so verify the syntax. **edit:** harpo's comment brings up a good point about field definitions. Defining a schema.ini file allows you to define the number and datatypes of the expected fields. See: You can handle this by defining a schema.ini file. see: <http://msdn.microsoft.com/en-us/library/ms709353.aspx>
213,661
<p>My application is a vb6 executable, but some newer forms in the system are written in C#. I would like to be able to set the C# form's Owner property using a handle to the main application window, so that the dialogs remain on top when tabbing back and forth between my app and other apps.</p> <p>I can get the hwnd of the main application window. I'm not sure what I can do from there?</p> <hr> <p><strong>UPDATE Oct 20 '08 at 17:06:</strong> </p> <p>Scott,</p> <p>Thanks for the response. I had overlooked that the Show/ShowDialog method parameter was not of type Form - I was looking only at the Owner property.</p> <p>I slightly modified the code I'm using from the above - we have a component that generically loads our Forms and calls ShowDialog. My code looks like this:</p> <pre><code>Form launchTarget = FormFactory.GetForm(xxx); // psuedo-code for generic form loader launchTarget.StartPosition = FormStartPosition.CenterParent; IWin32Window parentWindow = GetWindowFromHwnd(hwnd); launchTarget.ShowDialog(parentWindow); </code></pre> <p><code>GetWindowFromHwnd</code> is a method-wrapped version of your code:</p> <pre><code>private IWin32Window GetWindowFromHost(int hwnd) { IWin32Window window = null; IntPtr handle = new IntPtr(hwnd); try { NativeWindow nativeWindow = new NativeWindow(); nativeWindow.AssignHandle(handle); window = nativeWindow; } finally { handle = IntPtr.Zero; } return window; } </code></pre> <p>Unfortunately this isn't doing what I'd hoped. The form does display modally, but it's not showing up in the correct position nor is it still on top when I tab away and back to the parent window. Our modals do not show a task in the taskbar, so the window seemingly "disappears" (although it is still present in the alt-tab window list). That to me indicates I might not have the right hwnd. If you have any other suggestions though, please reply back. Thanks again.</p> <hr> <p><strong>UPDATE Nov 10 '08 at 16:25</strong> </p> <p>One follow up remark - If you factor it out into a method call in a try/finally, as in Scott's 2nd post, the call in the finally block should be:</p> <pre><code>parentWindow.ReleaseHandle(); </code></pre>
[ { "answer_id": 213751, "author": "Scott Dorman", "author_id": 1559, "author_profile": "https://Stackoverflow.com/users/1559", "pm_score": 4, "selected": true, "text": "<p>So you are calling a C# Windows Form class from VB6, which means you are probably using either <code>Show()</code> or <code>ShowDialog()</code>, correct? Both of those methods also take an IWin32Window parameter, which simply defines an object that returns an IntPtr property named Handle.</p>\n\n<p>So...you need to add an overloaded constructor (or ShowDialog method) for your Windows Forms classes which take a <code>long</code> as a parameter so you can pass the VB6 hwnd to the form. Once inside the C# code, you need to create an IntPtr from the hwnd and assign it to a <code>NativeWindow</code> object and then pass that as the owner.</p>\n\n<p>Something like this <strong>should</strong> work, although it's untested:</p>\n\n<pre><code>public DialogResult ShowDialog(long hwnd)\n{\n IntPtr handle = new IntPtr(hwnd);\n try\n {\n NativeWindow nativeWindow = new NativeWindow();\n\n nativeWindow.AssignHandle(handle);\n return this.ShowDialog(nativeWindow);\n }\n finally\n {\n handle = IntPtr.Zero;\n }\n}\n</code></pre>\n" }, { "answer_id": 219228, "author": "Scott Dorman", "author_id": 1559, "author_profile": "https://Stackoverflow.com/users/1559", "pm_score": 2, "selected": false, "text": "<p>This is too long to post as a comment...</p>\n\n<p>I think the problem you are running in to is the way you wrapped the code I presented in the ShowDialog overload. If you follow what your <code>GetWindowFromHost</code> code is doing it goes through the following steps:</p>\n\n<ol>\n<li>Creates a new IntPtr from the hwnd given.</li>\n<li>Creates a new NativeWindow object and assigns it's handle to be the IntPtr.</li>\n<li>Sets the IntPtr (in the finally block) to be IntPtr.Zero.</li>\n</ol>\n\n<p>I think it's this finally block that is causing you problems. In my code, the finally block would run after the call to <code>this.ShowDialog(nativeWindow)</code> finished. At that point the handle (IntPtr) was no longer being used. In your code, you are returning an <code>IWin32Window</code> that should still be holding a reference to that IntPtr, which at the time you call <code>launchTarget.ShowDialog(parentWindow)</code> is IntPtr.Zero.</p>\n\n<p>Try changing your code to look like this:</p>\n\n<pre><code>private NativeWindow GetWindowFromHost(int hwnd)\n{\n IntPtr handle = new IntPtr(hwnd);\n NativeWindow nativeWindow = new NativeWindow();\n nativeWindow.AssignHandle(handle);\n return window;\n}\n</code></pre>\n\n<p>And then change your calling code to look like this:</p>\n\n<pre><code>Form launchTarget = FormFactory.GetForm(xxx); // psuedo-code for generic form \nloaderlaunchTarget.StartPosition = FormStartPosition.CenterParent;\nNativeWindow parentWindow = GetWindowFromHwnd(hwnd);\n\ntry\n{\n launchTarget.ShowDialog(parentWindow);\n}\nfinally\n{\n parentWindow.DestroyHandle();\n}\n</code></pre>\n\n<p>These changes should work, but again this is untested.</p>\n" } ]
2008/10/17
[ "https://Stackoverflow.com/questions/213661", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3782/" ]
My application is a vb6 executable, but some newer forms in the system are written in C#. I would like to be able to set the C# form's Owner property using a handle to the main application window, so that the dialogs remain on top when tabbing back and forth between my app and other apps. I can get the hwnd of the main application window. I'm not sure what I can do from there? --- **UPDATE Oct 20 '08 at 17:06:** Scott, Thanks for the response. I had overlooked that the Show/ShowDialog method parameter was not of type Form - I was looking only at the Owner property. I slightly modified the code I'm using from the above - we have a component that generically loads our Forms and calls ShowDialog. My code looks like this: ``` Form launchTarget = FormFactory.GetForm(xxx); // psuedo-code for generic form loader launchTarget.StartPosition = FormStartPosition.CenterParent; IWin32Window parentWindow = GetWindowFromHwnd(hwnd); launchTarget.ShowDialog(parentWindow); ``` `GetWindowFromHwnd` is a method-wrapped version of your code: ``` private IWin32Window GetWindowFromHost(int hwnd) { IWin32Window window = null; IntPtr handle = new IntPtr(hwnd); try { NativeWindow nativeWindow = new NativeWindow(); nativeWindow.AssignHandle(handle); window = nativeWindow; } finally { handle = IntPtr.Zero; } return window; } ``` Unfortunately this isn't doing what I'd hoped. The form does display modally, but it's not showing up in the correct position nor is it still on top when I tab away and back to the parent window. Our modals do not show a task in the taskbar, so the window seemingly "disappears" (although it is still present in the alt-tab window list). That to me indicates I might not have the right hwnd. If you have any other suggestions though, please reply back. Thanks again. --- **UPDATE Nov 10 '08 at 16:25** One follow up remark - If you factor it out into a method call in a try/finally, as in Scott's 2nd post, the call in the finally block should be: ``` parentWindow.ReleaseHandle(); ```
So you are calling a C# Windows Form class from VB6, which means you are probably using either `Show()` or `ShowDialog()`, correct? Both of those methods also take an IWin32Window parameter, which simply defines an object that returns an IntPtr property named Handle. So...you need to add an overloaded constructor (or ShowDialog method) for your Windows Forms classes which take a `long` as a parameter so you can pass the VB6 hwnd to the form. Once inside the C# code, you need to create an IntPtr from the hwnd and assign it to a `NativeWindow` object and then pass that as the owner. Something like this **should** work, although it's untested: ``` public DialogResult ShowDialog(long hwnd) { IntPtr handle = new IntPtr(hwnd); try { NativeWindow nativeWindow = new NativeWindow(); nativeWindow.AssignHandle(handle); return this.ShowDialog(nativeWindow); } finally { handle = IntPtr.Zero; } } ```
213,671
<p>Does anyone know of an easy way to import a legacy project, whose "version control system" is a series of dated folders, into SVN, so that the history of the revisions is preserved?</p> <p>The project I inherited was not under version control, and there are hundreds of folders, each dated like: 2006-11-26, 2006-11-27, etc... Thankfully it appears they did a pretty good job of diligently creating the folders, even when (for weeks) nothing changed.</p> <p>What I'd love is a script/tool that will create a new repository with the oldest folder, and then sequentially &amp; automatically apply all the subversion commands to transform each later folder into a new revision.</p> <p>I hope that makes sense. The old shell scripter in me is tempted to try to tackle this myself, but a) I'm sure it's more work than I'd initially imagine, b) it's not the best use of my time (I'm not an expert in writing shell scripts), and c) I bet someone's already done this.</p> <p>Extra Credit: have the script/tool also modify the timestamp properties, based on the folder names, so that the history in subversion was closer to reality.</p> <p>I hope that all makes sense.</p> <p>Thanks a lot for any help.</p> <p>P.S. I'd prefer to do this all under Linux, but if there is a (gasp!) Windows solution, beggars can't be choosers, can they?</p>
[ { "answer_id": 213753, "author": "Leigh Caldwell", "author_id": 3267, "author_profile": "https://Stackoverflow.com/users/3267", "pm_score": 2, "selected": false, "text": "<p>I think the shell script solution would not be too hard. Something like this:</p>\n\n<pre><code>for d in 200*\ndo\n cp -a $d/* svndir/\n cd svndir\n svn add *\n svn commit\n cd ..\ndone\n</code></pre>\n\n<p>Rather naive code I know, but I would think that something a bit like this would do the job (subject to there already being a repository checked out into svndir). Presumably there is an argument to svn commit which skips the requirement to enter comments, otherwise this would be pretty tedious.</p>\n\n<p>cp -a will retain timestamps but of course the svn history will show everything being committed on the current date. Perhaps you could use the 'date' command to actually set the server date according to the directory name (value of $d) each time you copy and commit. However that might be a bit over the top.</p>\n" }, { "answer_id": 215150, "author": "Peter Parker", "author_id": 23264, "author_profile": "https://Stackoverflow.com/users/23264", "pm_score": 2, "selected": false, "text": "<p>For this use case the <a href=\"http://svn.collab.net/repos/svn/trunk/contrib/client-side/svn_load_dirs/\" rel=\"nofollow noreferrer\"><strong>load-dirs.pl</strong></a> was created, it takes your directories and will import them into Subversion and can also maintain version history for renames and deletes. A good documentation is available inside the subversion repository(link above)</p>\n" } ]
2008/10/17
[ "https://Stackoverflow.com/questions/213671", "https://Stackoverflow.com", "https://Stackoverflow.com/users/28574/" ]
Does anyone know of an easy way to import a legacy project, whose "version control system" is a series of dated folders, into SVN, so that the history of the revisions is preserved? The project I inherited was not under version control, and there are hundreds of folders, each dated like: 2006-11-26, 2006-11-27, etc... Thankfully it appears they did a pretty good job of diligently creating the folders, even when (for weeks) nothing changed. What I'd love is a script/tool that will create a new repository with the oldest folder, and then sequentially & automatically apply all the subversion commands to transform each later folder into a new revision. I hope that makes sense. The old shell scripter in me is tempted to try to tackle this myself, but a) I'm sure it's more work than I'd initially imagine, b) it's not the best use of my time (I'm not an expert in writing shell scripts), and c) I bet someone's already done this. Extra Credit: have the script/tool also modify the timestamp properties, based on the folder names, so that the history in subversion was closer to reality. I hope that all makes sense. Thanks a lot for any help. P.S. I'd prefer to do this all under Linux, but if there is a (gasp!) Windows solution, beggars can't be choosers, can they?
I think the shell script solution would not be too hard. Something like this: ``` for d in 200* do cp -a $d/* svndir/ cd svndir svn add * svn commit cd .. done ``` Rather naive code I know, but I would think that something a bit like this would do the job (subject to there already being a repository checked out into svndir). Presumably there is an argument to svn commit which skips the requirement to enter comments, otherwise this would be pretty tedious. cp -a will retain timestamps but of course the svn history will show everything being committed on the current date. Perhaps you could use the 'date' command to actually set the server date according to the directory name (value of $d) each time you copy and commit. However that might be a bit over the top.
213,680
<p>I'm trying to use jcarousel to build a container with multiple rows, I've tried a few things but have had no luck. Can anyone make any suggestions on how to create it?</p>
[ { "answer_id": 242866, "author": "Sike", "author_id": 32025, "author_profile": "https://Stackoverflow.com/users/32025", "pm_score": 4, "selected": true, "text": "<p>We have had to make a similar modifiaction. We do this by extending the default options, to include a rows value, and the width of each item (we call them modules) then divide the width by the number of rows.</p>\n\n<p>Code added to jCarousel function...</p>\n\n<p>Add to default options: </p>\n\n<pre><code>moduleWidth: null,\nrows:null,\n</code></pre>\n\n<p>Then set when creating jCarousel:</p>\n\n<pre><code>$('.columns2.rows2 .mycarousel').jcarousel( {\n scroll: 1,\n moduleWidth: 290,\n rows:2,\n itemLoadCallback: tonyTest,\n animation: 'slow'\n });\n</code></pre>\n\n<p>The find and edit the lines in: </p>\n\n<pre><code>$.jcarousel = function(e, o) { \n\nif (li.size() &gt; 0) {\n...\nmoduleCount = li.size();\nwh = this.options.moduleWidth * Math.ceil( moduleCount / this.options.rows );\nwh = wh + this.options.moduleWidth;\n\nthis.list.css(this.wh, wh + 'px');\n\n// Only set if not explicitly passed as option\nif (!o || o.size === undefined)\n this.options.size = Math.ceil( li.size() / this.options.rows );\n</code></pre>\n\n<p>Hope this helps,</p>\n\n<p>Tony Dillon</p>\n" }, { "answer_id": 617660, "author": "Oscar M.", "author_id": 15008, "author_profile": "https://Stackoverflow.com/users/15008", "pm_score": 1, "selected": false, "text": "<p>you might want to look at <a href=\"http://flesler.blogspot.com/2008/02/jqueryserialscroll.html\" rel=\"nofollow noreferrer\">serialScroll</a> or <a href=\"http://flesler.blogspot.com/2007/10/jquerylocalscroll-10.html\" rel=\"nofollow noreferrer\">localScroll</a> instead of jcarousel.</p>\n" }, { "answer_id": 1302766, "author": "Tim Banks", "author_id": 113797, "author_profile": "https://Stackoverflow.com/users/113797", "pm_score": 1, "selected": false, "text": "<p>I found this post on Google Groups that has a working version for multiple rows. I have used this and it works great. <a href=\"http://groups.google.com/group/jquery-en/browse_thread/thread/2c7c4a86d19cadf9\" rel=\"nofollow noreferrer\">http://groups.google.com/group/jquery-en/browse_thread/thread/2c7c4a86d19cadf9</a></p>\n" }, { "answer_id": 6989454, "author": "Sanchitos", "author_id": 317832, "author_profile": "https://Stackoverflow.com/users/317832", "pm_score": 3, "selected": false, "text": "<p>This is .js code substitutions according to @Sike and a little additional of me, the height was not set dynamically, now it is.</p>\n\n<pre><code>var defaults = {\n vertical: false,\n rtl: false,\n start: 1,\n offset: 1,\n size: null,\n scroll: 3,\n visible: null,\n animation: 'normal',\n easing: 'swing',\n auto: 0,\n wrap: null,\n initCallback: null,\n setupCallback: null,\n reloadCallback: null,\n itemLoadCallback: null,\n itemFirstInCallback: null,\n itemFirstOutCallback: null,\n itemLastInCallback: null,\n itemLastOutCallback: null,\n itemVisibleInCallback: null,\n itemVisibleOutCallback: null,\n animationStepCallback: null,\n buttonNextHTML: '&lt;div&gt;&lt;/div&gt;',\n buttonPrevHTML: '&lt;div&gt;&lt;/div&gt;',\n buttonNextEvent: 'click',\n buttonPrevEvent: 'click',\n buttonNextCallback: null,\n buttonPrevCallback: null,\n moduleWidth: null,\n rows: null,\n itemFallbackDimension: null\n }, windowLoaded = false;\n\n\n this.clip.addClass(this.className('jcarousel-clip')).css({\n position: 'relative',\n height: this.options.rows * this.options.moduleWidth\n });\n\n this.container.addClass(this.className('jcarousel-container')).css({\n position: 'relative',\n height: this.options.rows * this.options.moduleWidth\n });\n\n if (li.size() &gt; 0) {\n var moduleCount = li.size();\n var wh = 0, j = this.options.offset;\n wh = this.options.moduleWidth * Math.ceil(moduleCount / this.options.rows);\n wh = wh + this.options.moduleWidth;\n\n li.each(function() {\n self.format(this, j++);\n //wh += self.dimension(this, di);\n });\n\n this.list.css(this.wh, wh + 'px');\n\n\n // Only set if not explicitly passed as option\n if (!o || o.size === undefined) {\n this.options.size = Math.ceil(li.size() / this.options.rows);\n }\n }\n</code></pre>\n\n<p>This is the call in using the static_sample.html of the code bundle in the download of jscarousel:</p>\n\n<pre><code>&lt;script type=\"text/javascript\"&gt;\n\njQuery(document).ready(function() {\n jQuery('#mycarousel').jcarousel( {\n scroll: 1,\n moduleWidth: 75,\n rows:2, \n animation: 'slow'\n });\n});\n\n&lt;/script&gt;\n</code></pre>\n\n<p>In case you need to change the content of the carousel and reload the carousel you need to do this:</p>\n\n<pre><code>// Destroy contents of wrapper\n$('.wrapper *').remove();\n// Create UL list\n$('.wrapper').append('&lt;ul id=\"carousellist\"&gt;&lt;/ul&gt;')\n// Load your items into the carousellist\nfor (var i = 0; i &lt; 10; i++)\n{\n$('#carouselist').append('&lt;li&gt;Item ' + i + '&lt;/li&gt;');\n}\n// Now apply carousel to list\njQuery('#carousellist').jcarousel({ // your config });\n</code></pre>\n\n<p>The carousel html definition needs to be like this:</p>\n\n<pre><code>&lt;div class=\"wrapper\"&gt;\n &lt;ul id=\"mycarousel0\" class=\"jcarousel-skin-tango\"&gt;\n ...&lt;li&gt;&lt;/li&gt;\n &lt;/ul&gt;\n&lt;/div&gt;\n</code></pre>\n\n<p>Thanks to <a href=\"http://www.cabezabomba.com/webcidentes/?p=308\">Webcidentes</a></p>\n" }, { "answer_id": 9464643, "author": "Joni", "author_id": 918269, "author_profile": "https://Stackoverflow.com/users/918269", "pm_score": 0, "selected": false, "text": "<p>I tried the above solutions and found changing the original jCarousel code to be troublesome - it introduced buggy behaviour for me because it didn't play nice with some of the features of jCarousel such as the continous looping etc.</p>\n\n<p>I used another approach which works great and I thought others may benefit from it as well. It is the JS code I use to create the li items to support a jCarousel with multiple rows with elegant flow of items, i.e. fill horizontally, then vertically, then scrollpages:</p>\n\n<p>123 | 789<br>\n456 | 0AB</p>\n\n<p>It will add (value of var carouselRows) items to a single li and as such allows jCarousel to support multiple rows without modifying the original jCarousel code.</p>\n\n<pre><code>// Populate Album photos with support for multiple rows filling first columns, then rows, then pages\nvar carouselRows=3; // number of rows in the carousel\nvar carouselColumns=5 // number of columns per carousel page\nvar numItems=25; // the total number of items to display in jcarousel\n\nfor (var indexpage=0; indexpage&lt;Math.ceil(numItems/(carouselRows*carouselColumns)); indexpage++) // for each carousel page\n{\n for (var indexcolumn = 0; indexcolumn&lt;carouselColumns; indexcolumn++) // for each column on that carousel page\n {\n // handle cases with less columns than value of carouselColumns\n if (indexcolumn&lt;numItems-(indexpage*carouselRows*carouselColumns))\n {\n var li = document.createElement('li');\n\n for (var indexrow = 0; indexrow &lt; carouselRows; indexrow++) // for each row in that column\n {\n var indexitem = (indexpage*carouselRows*carouselColumns)+(indexrow*carouselColumns)+indexcolumn;\n\n // handle cases where there is no item for the row below\n if (indexitem&lt;numItems) \n {\n var div = document.createElement('div'), img = document.createElement('img');\n img.src = imagesArray[indexitem]; // replace this by your images source\n div.appendChild(img);\n li.appendChild(div);\n }\n }\n $ul.append(li); // append to ul in the DOM\n }\n }\n}\n</code></pre>\n\n<p>After this code has filled the ul with the li items jCarousel should be invoked.</p>\n\n<p>Hope this helps someone.</p>\n\n<p>Jonathan</p>\n" }, { "answer_id": 11070122, "author": "eagle779", "author_id": 268008, "author_profile": "https://Stackoverflow.com/users/268008", "pm_score": 0, "selected": false, "text": "<p>If you need a quick solution for a fixed or one-off requirement that definitely doesn't involve changing core library code which may be updated from time to time, the following may suit. To turn the following six items into two rows on the carousel:</p>\n\n<pre><code>&lt;div class=\"item\"&gt;contents&lt;/div&gt;\n&lt;div class=\"item\"&gt;contents&lt;/div&gt;\n&lt;div class=\"item\"&gt;contents&lt;/div&gt;\n&lt;div class=\"item\"&gt;contents&lt;/div&gt;\n&lt;div class=\"item\"&gt;contents&lt;/div&gt;\n&lt;div class=\"item\"&gt;contents&lt;/div&gt;\n</code></pre>\n\n<p>you can use a little JS to wrap the divs into LI groups of two then initialise the carousel. your scenario may allow you to do the grouping on the server isn't always possible. obviously you can extend this to however many rows you need.</p>\n\n<pre><code>var $pArr = $('div.item');\nvar pArrLen = $pArr.length;\nfor (var i = 0;i &lt; pArrLen;i+=2){\n $pArr.filter(':eq('+i+'),:eq('+(i+1)+')').wrapAll('&lt;li /&gt;');\n}; \n</code></pre>\n" } ]
2008/10/17
[ "https://Stackoverflow.com/questions/213680", "https://Stackoverflow.com", "https://Stackoverflow.com/users/16195/" ]
I'm trying to use jcarousel to build a container with multiple rows, I've tried a few things but have had no luck. Can anyone make any suggestions on how to create it?
We have had to make a similar modifiaction. We do this by extending the default options, to include a rows value, and the width of each item (we call them modules) then divide the width by the number of rows. Code added to jCarousel function... Add to default options: ``` moduleWidth: null, rows:null, ``` Then set when creating jCarousel: ``` $('.columns2.rows2 .mycarousel').jcarousel( { scroll: 1, moduleWidth: 290, rows:2, itemLoadCallback: tonyTest, animation: 'slow' }); ``` The find and edit the lines in: ``` $.jcarousel = function(e, o) { if (li.size() > 0) { ... moduleCount = li.size(); wh = this.options.moduleWidth * Math.ceil( moduleCount / this.options.rows ); wh = wh + this.options.moduleWidth; this.list.css(this.wh, wh + 'px'); // Only set if not explicitly passed as option if (!o || o.size === undefined) this.options.size = Math.ceil( li.size() / this.options.rows ); ``` Hope this helps, Tony Dillon
213,683
<p>I'm doing something like the following:</p> <pre><code>SELECT * FROM table WHERE user='$user'; $myrow = fetchRow() // previously I inserted a pass to the db using base64_encode ex: WRM2gt3R= $somepass = base64_encode($_POST['password']); if($myrow[1] != $somepass) echo 'error'; else echo 'welcome'; </code></pre> <p>Im always getting error, I even echo $somepass and $myrow[1] they are the same, but still error. What Am I doing wrong? Thanks</p>
[ { "answer_id": 213696, "author": "Greg", "author_id": 24181, "author_profile": "https://Stackoverflow.com/users/24181", "pm_score": 3, "selected": true, "text": "<p>Try using <code>var_dump</code> instead of echo - maybe one of them has a space or newline at the start/end.</p>\n\n<p>Edit:</p>\n\n<p>You must be storing it as CHAR(40): <code>A fixed-length string that is always right-padded with spaces to the specified length when stored</code></p>\n\n<p>Use VARCHAR or <code>trim()</code></p>\n" }, { "answer_id": 213707, "author": "myplacedk", "author_id": 28683, "author_profile": "https://Stackoverflow.com/users/28683", "pm_score": 0, "selected": false, "text": "<p>If $myrow[1] is actually the correct password in base64-encoding, I don't see any errors.</p>\n\n<p>Try this ind the end:</p>\n\n<pre><code>echo \"&lt;br /&gt;$myrow[1] != $somepass\";\n</code></pre>\n\n<p>What does it say?</p>\n\n<p>And by the way: I don't see any reason to base64-encode the passwords. What are you trying to accomplish?</p>\n" }, { "answer_id": 213733, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 0, "selected": false, "text": "<p>I think somehow if I do a var_dump() I get:</p>\n\n<p>string(40) \"YWRraM2= \"\nstring(8) \"YWRraM2=\"</p>\n\n<p>seems like somehow if I insert the data into the db using the console its adding an extra space to the pass field.</p>\n\n<p>myplacedk: is there any reason why I should not be doing it? I thought it will add an extra leyer of security?</p>\n" }, { "answer_id": 213760, "author": "myplacedk", "author_id": 28683, "author_profile": "https://Stackoverflow.com/users/28683", "pm_score": 0, "selected": false, "text": "<p>This encoding does two things:</p>\n\n<ol>\n<li>It adds code, making it more complex and easier to make errors</li>\n<li>If you view your database on your screen, and someone looks over your shoulder, the passwords may be a bit harder to remember.</li>\n</ol>\n\n<p>So no, it doesn't really add any security. It's just an encoding, it's easy to decode.</p>\n\n<p>Maybe you are mistaking it for md5-hashing or something like that.</p>\n\n<p>Playing around is great, but when it comes to security, I really recommend not using something you don't understand. In the long run, it will do more damage than good.</p>\n" }, { "answer_id": 213779, "author": "gnud", "author_id": 27204, "author_profile": "https://Stackoverflow.com/users/27204", "pm_score": 0, "selected": false, "text": "<p>Some issues:</p>\n\n<ul>\n<li>\nFrom your comments elsewhere, I guess that the problem with the current code is that your database field is CHAR(40). A CHAR field always has a fixed size. Try changing the database field type to VARCHAR instead of CHAR.<br><br>\n</li>\n\n\n<li>\nUsing base64_encode before storing in a database is nowhere near secure. Good practice is storing only a one-way hash of the password in the database -- typically md5 or (better) sha1. Then, when the user wants to log in, use the same hash-function on the provided password, and then compare the two hashes. <br>\nThis has the added benefit of working with passwords longer than 40 characters too.<br>\nA sha1 or md5-hash always takes a fixed amount of space, so if you go this route, you don't have to switch your database column to VARCHAR :)<br><br>\n</li>\n</ul>\n" } ]
2008/10/17
[ "https://Stackoverflow.com/questions/213683", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
I'm doing something like the following: ``` SELECT * FROM table WHERE user='$user'; $myrow = fetchRow() // previously I inserted a pass to the db using base64_encode ex: WRM2gt3R= $somepass = base64_encode($_POST['password']); if($myrow[1] != $somepass) echo 'error'; else echo 'welcome'; ``` Im always getting error, I even echo $somepass and $myrow[1] they are the same, but still error. What Am I doing wrong? Thanks
Try using `var_dump` instead of echo - maybe one of them has a space or newline at the start/end. Edit: You must be storing it as CHAR(40): `A fixed-length string that is always right-padded with spaces to the specified length when stored` Use VARCHAR or `trim()`
213,691
<p>I intermittently get this in error in my .NET 1.1 C# Windows Forms application. Someone indicated that this is due to a bug in the 1.1 framework and suggests putting the following code into any custom controls.</p> <pre><code>protected override void OnParentChanged(EventArgs e) { if (this.Parent != null) { this.CreateParams.Parent = this.Parent.Handle; this.RecreateHandle(); } base.OnParentChanged(e); } </code></pre> <p>Has anyone else found that this solved the problem for them? Can anyone provide a way to consistently reproduce the error, so I can verify it is fixed after I apply the changes?</p> <p>If there is an alternative solution I'm open to that as well.</p>
[ { "answer_id": 213740, "author": "TimothyP", "author_id": 28149, "author_profile": "https://Stackoverflow.com/users/28149", "pm_score": 0, "selected": false, "text": "<p>Hey, I'm not sure about your problem as I haven't used .NET 1.1 in ages,\nand I hate to state the obvious... but what is stopping you from migrating\nto .NET 2.0 or even 3.5? (Please do not feel offended, I'm actually interested in knowing).</p>\n\n<p>I can understand .NET 3.5 might be early in some cases,\nbut .NET 2.0 should be a safe bet given the fact that most users have it\neither through windows updates or if they are using Vista they have it by default.</p>\n" }, { "answer_id": 213879, "author": "pero", "author_id": 21645, "author_profile": "https://Stackoverflow.com/users/21645", "pm_score": 1, "selected": false, "text": "<p>From the title it seems that your code is trying to access an already disposed object. This can happen in finalizer if you try to access a managed reference field. The order CLR finalizes managed objects is non-deterministic. </p>\n" } ]
2008/10/17
[ "https://Stackoverflow.com/questions/213691", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
I intermittently get this in error in my .NET 1.1 C# Windows Forms application. Someone indicated that this is due to a bug in the 1.1 framework and suggests putting the following code into any custom controls. ``` protected override void OnParentChanged(EventArgs e) { if (this.Parent != null) { this.CreateParams.Parent = this.Parent.Handle; this.RecreateHandle(); } base.OnParentChanged(e); } ``` Has anyone else found that this solved the problem for them? Can anyone provide a way to consistently reproduce the error, so I can verify it is fixed after I apply the changes? If there is an alternative solution I'm open to that as well.
From the title it seems that your code is trying to access an already disposed object. This can happen in finalizer if you try to access a managed reference field. The order CLR finalizes managed objects is non-deterministic.
213,702
<p>I am working with a set of data that looks something like the following.</p> <blockquote> <pre><code>StudentName | AssignmentName | Grade --------------------------------------- StudentA | Assignment 1 | 100 StudentA | Assignment 2 | 80 StudentA | Total | 180 StudentB | Assignment 1 | 100 StudentB | Assignment 2 | 80 StudentB | Assignment 3 | 100 StudentB | Total | 280 </code></pre> </blockquote> <p>The name and number of assignments are dynamic, I need to get results simlilar to the following.</p> <blockquote> <pre><code>Student | Assignment 1 | Assignment 2 | Assignment 3 | Total -------------------------------------------------------------------- Student A | 100 | 80 | null | 180 Student B | 100 | 80 | 100 | 280 </code></pre> </blockquote> <p>Now ideally I would like to sort the column based on a "due date" that could be included/associated with each assignment. The total should be at the end if possible (It can be calculated and removed from the query if possible.)</p> <p>I know how to do it for the 3 assignments using pivot with simply naming the columns, it is trying to do it in a dynamic fashion that I haven't found a GOOD solution for yet. I am trying to do this on SQL Server 2005</p> <p><strong>EDIT</strong></p> <p>Ideally I would like to implement this WITHOUT using Dynamic SQL, as that is against the policy. If it isn't possible...then a working example with Dynamic SQL will work.</p>
[ { "answer_id": 213713, "author": "BoltBait", "author_id": 20848, "author_profile": "https://Stackoverflow.com/users/20848", "pm_score": 1, "selected": false, "text": "<p>The only way I've found to do this is to use dynamic SQL and put the column labels into a variable.</p>\n" }, { "answer_id": 213715, "author": "tsilb", "author_id": 11112, "author_profile": "https://Stackoverflow.com/users/11112", "pm_score": 0, "selected": false, "text": "<p>you could query information_schema to get the column names and types, then use the result as a subquery when you build your result set. Note you'll likely have to change the login's access a bit.</p>\n" }, { "answer_id": 213850, "author": "Cade Roux", "author_id": 18255, "author_profile": "https://Stackoverflow.com/users/18255", "pm_score": 5, "selected": true, "text": "<p>I know you said no dynamic <code>SQL</code>, but I don't see any way to do it in straight <code>SQL</code>.</p>\n\n<p>If you check out my answers to similar problems at <a href=\"https://stackoverflow.com/questions/159456/pivot-table-and-concatenate-columns-sql-problem#159803\">Pivot Table and Concatenate Columns</a> and <a href=\"https://stackoverflow.com/questions/198716/pivot-in-sql-2005#199763\">PIVOT in sql 2005</a></p>\n\n<p>The dynamic <code>SQL</code> there is not vulnerable to injection, and there is no good reason to prohibit it. Another possibility (if the data is changing very infrequently) is to do code-generation - instead of dynamic <code>SQL</code>, the <code>SQL</code> is generated to a stored procedure on a regular basis.</p>\n" }, { "answer_id": 214173, "author": "Booji Boy", "author_id": 1433, "author_profile": "https://Stackoverflow.com/users/1433", "pm_score": 0, "selected": false, "text": "<p>This is the same as <a href=\"https://stackoverflow.com/questions/198716/pivot-in-sql-2005#198879\">PIVOT in sql 2005</a></p>\n\n<p>If this data is for consumption in a report you could use a SSRS matrix. It will generate columns dynamically from result set. I've used it many times - it works quite well for dynamic crosstab reports.</p>\n\n<p>Here's a good example w/ dynamic sql. \n<a href=\"http://www.simple-talk.com/community/blogs/andras/archive/2007/09/14/37265.aspx\" rel=\"nofollow noreferrer\">http://www.simple-talk.com/community/blogs/andras/archive/2007/09/14/37265.aspx</a></p>\n" }, { "answer_id": 2207626, "author": "Prasad", "author_id": 267120, "author_profile": "https://Stackoverflow.com/users/267120", "pm_score": -1, "selected": false, "text": "<pre><code>select studentname,[Assign1],[Assign2],[Assign3],[Total] \nfrom \n(\n select studentname, assignname, grade from student\n)s\npivot(sum(Grade) for assignname IN([Assign1],[Assign2],[Assign3],[Total])) as pvt\n</code></pre>\n" }, { "answer_id": 12581700, "author": "Chirag Patel", "author_id": 1697054, "author_profile": "https://Stackoverflow.com/users/1697054", "pm_score": -1, "selected": false, "text": "<pre><code>SELECT TrnType\nINTO #Temp1\nFROM\n(\n SELECT '[' + CAST(TransactionType AS VARCHAR(4)) + ']' AS TrnType FROM tblPaymentTransactionTypes\n) AS tbl1\n\nSELECT * FROM #Temp1\n\nSELECT * FROM\n(\n SELECT FirstName + ' ' + LastName AS Patient, TransactionType, ISNULL(PostedAmount, 0) AS PostedAmount\n FROM tblPaymentTransactions\n INNER JOIN emr_PatientDetails ON tblPaymentTransactions.PracticeID = emr_PatientDetails.PracticeId\n INNER JOIN tblPaymentTransactionDetails ON emr_PatientDetails.PatientId = tblPaymentTransactionDetails.PatientID\n AND tblPaymentTransactions.TransactionID = tblPaymentTransactionDetails.TransactionID\n WHERE emr_PatientDetails.PracticeID = 152\n) tbl\nPIVOT (SUM(PostedAmount) FOR [TransactionType] IN (SELECT * FROM #Temp1)\n) AS tbl4\n</code></pre>\n" }, { "answer_id": 13992000, "author": "Taryn", "author_id": 426671, "author_profile": "https://Stackoverflow.com/users/426671", "pm_score": 4, "selected": false, "text": "<p>To <code>PIVOT</code> this data using dynamic sql you can use the following code in SQL Server 2005+:</p>\n\n<p><strong>Create Table:</strong></p>\n\n<pre><code>CREATE TABLE yourtable\n ([StudentName] varchar(8), [AssignmentName] varchar(12), [Grade] int)\n;\n\nINSERT INTO yourtable\n ([StudentName], [AssignmentName], [Grade])\nVALUES\n ('StudentA', 'Assignment 1', 100),\n ('StudentA', 'Assignment 2', 80),\n ('StudentA', 'Total', 180),\n ('StudentB', 'Assignment 1', 100),\n ('StudentB', 'Assignment 2', 80),\n ('StudentB', 'Assignment 3', 100),\n ('StudentB', 'Total', 280)\n;\n</code></pre>\n\n<p><strong>Dynamic PIVOT:</strong></p>\n\n<pre><code>DECLARE @cols AS NVARCHAR(MAX),\n @query AS NVARCHAR(MAX)\n\nselect @cols = STUFF((SELECT distinct ',' + QUOTENAME(AssignmentName) \n from yourtable\n FOR XML PATH(''), TYPE\n ).value('.', 'NVARCHAR(MAX)') \n ,1,1,'')\n\nset @query = 'SELECT StudentName, ' + @cols + ' from \n (\n select StudentName, AssignmentName, grade\n from yourtable\n ) x\n pivot \n (\n min(grade)\n for assignmentname in (' + @cols + ')\n ) p '\n\nexecute(@query)\n</code></pre>\n\n<p>See <a href=\"http://sqlfiddle.com/#!3/42b01/2\" rel=\"noreferrer\">SQL Fiddle with Demo</a></p>\n\n<p>The result is:</p>\n\n<pre><code>| STUDENTNAME | ASSIGNMENT 1 | ASSIGNMENT 2 | ASSIGNMENT 3 | TOTAL |\n--------------------------------------------------------------------\n| StudentA | 100 | 80 | (null) | 180 |\n| StudentB | 100 | 80 | 100 | 280 |\n</code></pre>\n" } ]
2008/10/17
[ "https://Stackoverflow.com/questions/213702", "https://Stackoverflow.com", "https://Stackoverflow.com/users/13279/" ]
I am working with a set of data that looks something like the following. > > > ``` > StudentName | AssignmentName | Grade > --------------------------------------- > StudentA | Assignment 1 | 100 > StudentA | Assignment 2 | 80 > StudentA | Total | 180 > StudentB | Assignment 1 | 100 > StudentB | Assignment 2 | 80 > StudentB | Assignment 3 | 100 > StudentB | Total | 280 > > ``` > > The name and number of assignments are dynamic, I need to get results simlilar to the following. > > > ``` > Student | Assignment 1 | Assignment 2 | Assignment 3 | Total > -------------------------------------------------------------------- > Student A | 100 | 80 | null | 180 > Student B | 100 | 80 | 100 | 280 > > ``` > > Now ideally I would like to sort the column based on a "due date" that could be included/associated with each assignment. The total should be at the end if possible (It can be calculated and removed from the query if possible.) I know how to do it for the 3 assignments using pivot with simply naming the columns, it is trying to do it in a dynamic fashion that I haven't found a GOOD solution for yet. I am trying to do this on SQL Server 2005 **EDIT** Ideally I would like to implement this WITHOUT using Dynamic SQL, as that is against the policy. If it isn't possible...then a working example with Dynamic SQL will work.
I know you said no dynamic `SQL`, but I don't see any way to do it in straight `SQL`. If you check out my answers to similar problems at [Pivot Table and Concatenate Columns](https://stackoverflow.com/questions/159456/pivot-table-and-concatenate-columns-sql-problem#159803) and [PIVOT in sql 2005](https://stackoverflow.com/questions/198716/pivot-in-sql-2005#199763) The dynamic `SQL` there is not vulnerable to injection, and there is no good reason to prohibit it. Another possibility (if the data is changing very infrequently) is to do code-generation - instead of dynamic `SQL`, the `SQL` is generated to a stored procedure on a regular basis.
213,719
<p>I'm using VisualSVN client and server and one of the requirements for web projects to work as expected is to have the .sln in the same directory (root) as the other files.</p> <p>I thought it was as simple as removing all the extra parent paths ../ and other relative paths and saving it. However when I try to open it just locks up Visual Studio. </p> <p>Is there a standard way to create this type of solution file or a solution file tool to help make sure it is valid? Or am I just missing something very obvious?</p> <pre><code>/ /MyWebsite.org.sln /Images /App_Data /default.aspx /default.aspx.cs </code></pre> <p>So apparently the trick, at least the one I was seeking is that you must use ..\MyWebsite.org or whatever the folder that contains the website files.</p> <p>[EDIT] What I learned and my final .sln file for this particular project:</p> <p>Here is the final Solution file that allowed me to open the website and have the .sln in the root of the web folder.</p> <pre><code>Project("{E24C65DC-7377-472B-9ABA-BCSG3B73C61A}") = "MyWebsite.org", "\", "{F8F4E96F-40BF-4374-B8BA-968D0SGG4A9E}" ProjectSection(WebsiteProperties) = preProject TargetFramework = "3.5" Debug.AspNetCompiler.VirtualPath = "/MyWebsite.org" Debug.AspNetCompiler.PhysicalPath = "..\MyWebsite.org\" Debug.AspNetCompiler.TargetPath = "PrecompiledWeb\MyWebsite.org\" Debug.AspNetCompiler.Updateable = "true" Debug.AspNetCompiler.ForceOverwrite = "true" Debug.AspNetCompiler.FixedNames = "false" Debug.AspNetCompiler.Debug = "True" Release.AspNetCompiler.VirtualPath = "/MyWebsite.org" Release.AspNetCompiler.PhysicalPath = "..\MyWebsite.org\" Release.AspNetCompiler.TargetPath = "PrecompiledWeb\MyWebsite.org\" Release.AspNetCompiler.Updateable = "true" Release.AspNetCompiler.ForceOverwrite = "true" Release.AspNetCompiler.FixedNames = "false" Release.AspNetCompiler.Debug = "False" VWDPort = "1603" VWDDynamicPort = "false" VWDVirtualPath = "/" EndProjectSection EndProject </code></pre>
[ { "answer_id": 213741, "author": "Jeremy B.", "author_id": 28567, "author_profile": "https://Stackoverflow.com/users/28567", "pm_score": 3, "selected": false, "text": "<p>the following steps should work.</p>\n\n<ol>\n<li>make a blank solution, nothing in it.</li>\n<li>Move the solution to where you want the web project to live.</li>\n<li>Open the solution.</li>\n<li>Create the web project in the desired area.</li>\n</ol>\n\n<p>I often do this sort of moving around so that projects will sit nicely in svn. Don't forget to svn:ignore the *.suo files.</p>\n" }, { "answer_id": 213744, "author": "AJ.", "author_id": 27457, "author_profile": "https://Stackoverflow.com/users/27457", "pm_score": 4, "selected": false, "text": "<p>Generally what I do is start with a Blank Solution, which is under \"Other Project Types-->Visual Studio Solutions\" in the New Project dialog. Then, add the website and whatever other projects you need to the solution.</p>\n" }, { "answer_id": 213747, "author": "Mitchel Sellers", "author_id": 13279, "author_profile": "https://Stackoverflow.com/users/13279", "pm_score": 5, "selected": true, "text": "<p>THe other option is when you create the project simply uncheck the default box for \"create directory for solution\"</p>\n" }, { "answer_id": 213778, "author": "tsilb", "author_id": 11112, "author_profile": "https://Stackoverflow.com/users/11112", "pm_score": 2, "selected": false, "text": "<p>Create the solution, close it, put the files where you want them, and edit the sln.</p>\n" }, { "answer_id": 9266538, "author": "pmulimani", "author_id": 1207568, "author_profile": "https://Stackoverflow.com/users/1207568", "pm_score": 2, "selected": false, "text": "<p>Goto Tools->Options->Projects and Solutions then check the Always show solution.</p>\n" }, { "answer_id": 32617546, "author": "StanM", "author_id": 5343957, "author_profile": "https://Stackoverflow.com/users/5343957", "pm_score": 0, "selected": false, "text": "<p>I couldn't find a solution file for my project. I was able to run the project on one machine without a .sln in the project. The reason it worked on the machine I created it on was that that I keep my VS projects under C:\\Dev\\Projects but Visual Studio kept its .sln file c:\\users\\xyz\\documents\\VisualStudio2015\\projects directory. When I moved the files to a new computer the .sln wasn't in the same directory. I just found the project set up in the old computer in the c:\\users\\xyz\\documents\\VisualStudio2015\\projects directory and moved that to my new computer. I believe I could have avoided this by changing the Tools->Options->Projects and Solutions section</p>\n" }, { "answer_id": 39119854, "author": "parwaze", "author_id": 6751887, "author_profile": "https://Stackoverflow.com/users/6751887", "pm_score": 0, "selected": false, "text": "<p>Re-create a project from existing files in asp.net</p>\n\n<p>Copy the existing files to a location eg. F:\\Copy_webSite</p>\n\n<p>Open visual studio > file > new website.</p>\n\n<p>[enter image description here][1]\nSelect the folder where you copied the files\n[enter image description here][2]</p>\n\n<p>You will be prompted “web site already existed” select “open the existing web site”</p>\n\n<p>System will create the .sln file in folder C:\\Users\\user\\Documents\\Visual Studio 2005\\Projects\\WebSite\n[enter image description here][3]</p>\n\n<p>System will open the current project.\nYou can also copy the the .sln file in the same folder of the current project. It will open the project in the folder</p>\n" }, { "answer_id": 40273530, "author": "Kickass", "author_id": 5003475, "author_profile": "https://Stackoverflow.com/users/5003475", "pm_score": 0, "selected": false, "text": "<p>Just had to do this after a bad OS install resulted in partition damage and had to recover the data. Months later I needed to change code but the .sln file was gone. </p>\n\n<p>Using Visual Studio 2015\nGo to New -> Website -> Select the root directory of the website in need of a new .sln file -> Next -> It will ask to create new site in directory or open the website in directory, obviously select the latter. Opened no problem with zero errors and it was even fast at doing it -> Save project and you're good to go.</p>\n\n<p>Occam's Razor!</p>\n" } ]
2008/10/17
[ "https://Stackoverflow.com/questions/213719", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3747/" ]
I'm using VisualSVN client and server and one of the requirements for web projects to work as expected is to have the .sln in the same directory (root) as the other files. I thought it was as simple as removing all the extra parent paths ../ and other relative paths and saving it. However when I try to open it just locks up Visual Studio. Is there a standard way to create this type of solution file or a solution file tool to help make sure it is valid? Or am I just missing something very obvious? ``` / /MyWebsite.org.sln /Images /App_Data /default.aspx /default.aspx.cs ``` So apparently the trick, at least the one I was seeking is that you must use ..\MyWebsite.org or whatever the folder that contains the website files. [EDIT] What I learned and my final .sln file for this particular project: Here is the final Solution file that allowed me to open the website and have the .sln in the root of the web folder. ``` Project("{E24C65DC-7377-472B-9ABA-BCSG3B73C61A}") = "MyWebsite.org", "\", "{F8F4E96F-40BF-4374-B8BA-968D0SGG4A9E}" ProjectSection(WebsiteProperties) = preProject TargetFramework = "3.5" Debug.AspNetCompiler.VirtualPath = "/MyWebsite.org" Debug.AspNetCompiler.PhysicalPath = "..\MyWebsite.org\" Debug.AspNetCompiler.TargetPath = "PrecompiledWeb\MyWebsite.org\" Debug.AspNetCompiler.Updateable = "true" Debug.AspNetCompiler.ForceOverwrite = "true" Debug.AspNetCompiler.FixedNames = "false" Debug.AspNetCompiler.Debug = "True" Release.AspNetCompiler.VirtualPath = "/MyWebsite.org" Release.AspNetCompiler.PhysicalPath = "..\MyWebsite.org\" Release.AspNetCompiler.TargetPath = "PrecompiledWeb\MyWebsite.org\" Release.AspNetCompiler.Updateable = "true" Release.AspNetCompiler.ForceOverwrite = "true" Release.AspNetCompiler.FixedNames = "false" Release.AspNetCompiler.Debug = "False" VWDPort = "1603" VWDDynamicPort = "false" VWDVirtualPath = "/" EndProjectSection EndProject ```
THe other option is when you create the project simply uncheck the default box for "create directory for solution"
213,729
<p>For example:</p> <pre><code>from datetime import &lt;c-x&gt;&lt;c-o&gt;{list of modules inside datetime package} </code></pre>
[ { "answer_id": 213741, "author": "Jeremy B.", "author_id": 28567, "author_profile": "https://Stackoverflow.com/users/28567", "pm_score": 3, "selected": false, "text": "<p>the following steps should work.</p>\n\n<ol>\n<li>make a blank solution, nothing in it.</li>\n<li>Move the solution to where you want the web project to live.</li>\n<li>Open the solution.</li>\n<li>Create the web project in the desired area.</li>\n</ol>\n\n<p>I often do this sort of moving around so that projects will sit nicely in svn. Don't forget to svn:ignore the *.suo files.</p>\n" }, { "answer_id": 213744, "author": "AJ.", "author_id": 27457, "author_profile": "https://Stackoverflow.com/users/27457", "pm_score": 4, "selected": false, "text": "<p>Generally what I do is start with a Blank Solution, which is under \"Other Project Types-->Visual Studio Solutions\" in the New Project dialog. Then, add the website and whatever other projects you need to the solution.</p>\n" }, { "answer_id": 213747, "author": "Mitchel Sellers", "author_id": 13279, "author_profile": "https://Stackoverflow.com/users/13279", "pm_score": 5, "selected": true, "text": "<p>THe other option is when you create the project simply uncheck the default box for \"create directory for solution\"</p>\n" }, { "answer_id": 213778, "author": "tsilb", "author_id": 11112, "author_profile": "https://Stackoverflow.com/users/11112", "pm_score": 2, "selected": false, "text": "<p>Create the solution, close it, put the files where you want them, and edit the sln.</p>\n" }, { "answer_id": 9266538, "author": "pmulimani", "author_id": 1207568, "author_profile": "https://Stackoverflow.com/users/1207568", "pm_score": 2, "selected": false, "text": "<p>Goto Tools->Options->Projects and Solutions then check the Always show solution.</p>\n" }, { "answer_id": 32617546, "author": "StanM", "author_id": 5343957, "author_profile": "https://Stackoverflow.com/users/5343957", "pm_score": 0, "selected": false, "text": "<p>I couldn't find a solution file for my project. I was able to run the project on one machine without a .sln in the project. The reason it worked on the machine I created it on was that that I keep my VS projects under C:\\Dev\\Projects but Visual Studio kept its .sln file c:\\users\\xyz\\documents\\VisualStudio2015\\projects directory. When I moved the files to a new computer the .sln wasn't in the same directory. I just found the project set up in the old computer in the c:\\users\\xyz\\documents\\VisualStudio2015\\projects directory and moved that to my new computer. I believe I could have avoided this by changing the Tools->Options->Projects and Solutions section</p>\n" }, { "answer_id": 39119854, "author": "parwaze", "author_id": 6751887, "author_profile": "https://Stackoverflow.com/users/6751887", "pm_score": 0, "selected": false, "text": "<p>Re-create a project from existing files in asp.net</p>\n\n<p>Copy the existing files to a location eg. F:\\Copy_webSite</p>\n\n<p>Open visual studio > file > new website.</p>\n\n<p>[enter image description here][1]\nSelect the folder where you copied the files\n[enter image description here][2]</p>\n\n<p>You will be prompted “web site already existed” select “open the existing web site”</p>\n\n<p>System will create the .sln file in folder C:\\Users\\user\\Documents\\Visual Studio 2005\\Projects\\WebSite\n[enter image description here][3]</p>\n\n<p>System will open the current project.\nYou can also copy the the .sln file in the same folder of the current project. It will open the project in the folder</p>\n" }, { "answer_id": 40273530, "author": "Kickass", "author_id": 5003475, "author_profile": "https://Stackoverflow.com/users/5003475", "pm_score": 0, "selected": false, "text": "<p>Just had to do this after a bad OS install resulted in partition damage and had to recover the data. Months later I needed to change code but the .sln file was gone. </p>\n\n<p>Using Visual Studio 2015\nGo to New -> Website -> Select the root directory of the website in need of a new .sln file -> Next -> It will ask to create new site in directory or open the website in directory, obviously select the latter. Opened no problem with zero errors and it was even fast at doing it -> Save project and you're good to go.</p>\n\n<p>Occam's Razor!</p>\n" } ]
2008/10/17
[ "https://Stackoverflow.com/questions/213729", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1367022/" ]
For example: ``` from datetime import <c-x><c-o>{list of modules inside datetime package} ```
THe other option is when you create the project simply uncheck the default box for "create directory for solution"
213,761
<p>I've seen some examples of C++ using template template parameters (that is templates which take templates as parameters) to do policy-based class design. What other uses does this technique have?</p>
[ { "answer_id": 213811, "author": "Evan Teran", "author_id": 13430, "author_profile": "https://Stackoverflow.com/users/13430", "pm_score": 9, "selected": true, "text": "<p>I think you need to use template template syntax to pass a parameter whose type is a template dependent on another template like this:</p>\n\n<pre><code>template &lt;template&lt;class&gt; class H, class S&gt;\nvoid f(const H&lt;S&gt; &amp;value) {\n}\n</code></pre>\n\n<p>Here, <code>H</code> is a template, but I wanted this function to deal with all specializations of <code>H</code>.</p>\n\n<p><strong>NOTE</strong>: I've been programming c++ for many years and have only needed this once. I find that it is a rarely needed feature (of course handy when you need it!).</p>\n\n<p>I've been trying to think of good examples, and to be honest, most of the time this isn't necessary, but let's contrive an example. Let's pretend that <code>std::vector</code> <em>doesn't</em> have a <code>typedef value_type</code>. </p>\n\n<p>So how would you write a function which can create variables of the right type for the vectors elements? This would work.</p>\n\n<pre><code>template &lt;template&lt;class, class&gt; class V, class T, class A&gt;\nvoid f(V&lt;T, A&gt; &amp;v) {\n // This can be \"typename V&lt;T, A&gt;::value_type\",\n // but we are pretending we don't have it\n\n T temp = v.back();\n v.pop_back();\n // Do some work on temp\n\n std::cout &lt;&lt; temp &lt;&lt; std::endl;\n}\n</code></pre>\n\n<p><strong>NOTE</strong>: <code>std::vector</code> has two template parameters, type, and allocator, so we had to accept both of them. Fortunately, because of type deduction, we won't need to write out the exact type explicitly.</p>\n\n<p>which you can use like this:</p>\n\n<pre><code>f&lt;std::vector, int&gt;(v); // v is of type std::vector&lt;int&gt; using any allocator\n</code></pre>\n\n<p>or better yet, we can just use:</p>\n\n<pre><code>f(v); // everything is deduced, f can deal with a vector of any type!\n</code></pre>\n\n<p><strong>UPDATE</strong>: Even this contrived example, while illustrative, is no longer an amazing example due to c++11 introducing <code>auto</code>. Now the same function can be written as:</p>\n\n<pre><code>template &lt;class Cont&gt;\nvoid f(Cont &amp;v) {\n\n auto temp = v.back();\n v.pop_back();\n // Do some work on temp\n\n std::cout &lt;&lt; temp &lt;&lt; std::endl;\n}\n</code></pre>\n\n<p>which is how I'd prefer to write this type of code.</p>\n" }, { "answer_id": 214900, "author": "yoav.aviram", "author_id": 25287, "author_profile": "https://Stackoverflow.com/users/25287", "pm_score": 6, "selected": false, "text": "<p>Here is a simple example taken from <a href=\"https://rads.stackoverflow.com/amzn/click/com/0201704315\" rel=\"noreferrer\" rel=\"nofollow noreferrer\">'Modern C++ Design - Generic Programming and Design Patterns Applied'</a> by Andrei Alexandrescu:</p>\n\n<p>He uses a classes with template template parameters in order to implement the policy pattern:</p>\n\n<pre><code>// Library code\ntemplate &lt;template &lt;class&gt; class CreationPolicy&gt;\nclass WidgetManager : public CreationPolicy&lt;Widget&gt;\n{\n ...\n};\n</code></pre>\n\n<p>He explains:\n<em>Typically, the host class already knows, or can easily deduce, the template argument of the policy class. In the example above, WidgetManager always manages objects of type Widget, so requiring the user to specify Widget again in the instantiation of CreationPolicy is redundant and potentially dangerous.In this case, library code can use template template parameters for specifying policies.</em></p>\n\n<p>The effect is that the client code can use 'WidgetManager' in a more elegant way:</p>\n\n<pre><code>typedef WidgetManager&lt;MyCreationPolicy&gt; MyWidgetMgr;\n</code></pre>\n\n<p>Instead of the more cumbersome, and error prone way that a definition lacking template template arguments would have required:</p>\n\n<pre><code>typedef WidgetManager&lt; MyCreationPolicy&lt;Widget&gt; &gt; MyWidgetMgr;\n</code></pre>\n" }, { "answer_id": 6726127, "author": "Mikhail Sirotenko", "author_id": 460436, "author_profile": "https://Stackoverflow.com/users/460436", "pm_score": 4, "selected": false, "text": "<p>Here's another practical example from my <a href=\"https://github.com/sirotenko/cudacnn\" rel=\"noreferrer\">CUDA Convolutional neural network library</a>.\nI have the following class template:</p>\n\n<pre><code>template &lt;class T&gt; class Tensor\n</code></pre>\n\n<p>which is actually implements n-dimensional matrices manipulation.\nThere's also a child class template:</p>\n\n<pre><code>template &lt;class T&gt; class TensorGPU : public Tensor&lt;T&gt;\n</code></pre>\n\n<p>which implements the same functionality but in GPU.\nBoth templates can work with all basic types, like float, double, int, etc\nAnd I also have a class template (simplified):</p>\n\n<pre><code>template &lt;template &lt;class&gt; class TT, class T&gt; class CLayerT: public Layer&lt;TT&lt;T&gt; &gt;\n{\n TT&lt;T&gt; weights;\n TT&lt;T&gt; inputs;\n TT&lt;int&gt; connection_matrix;\n}\n</code></pre>\n\n<p>The reason here to have template template syntax is because I can declare implementation of the class</p>\n\n<pre><code>class CLayerCuda: public CLayerT&lt;TensorGPU, float&gt;\n</code></pre>\n\n<p>which will have both weights and inputs of type float and on GPU, but connection_matrix will always be int, either on CPU (by specifying TT = Tensor) or on GPU (by specifying TT=TensorGPU).</p>\n" }, { "answer_id": 12806463, "author": "Mark McKenna", "author_id": 584585, "author_profile": "https://Stackoverflow.com/users/584585", "pm_score": 4, "selected": false, "text": "<p>Say you're using CRTP to provide an \"interface\" for a set of child templates; and both the parent and the child are parametric in other template argument(s):</p>\n\n<pre><code>template &lt;typename DERIVED, typename VALUE&gt; class interface {\n void do_something(VALUE v) {\n static_cast&lt;DERIVED*&gt;(this)-&gt;do_something(v);\n }\n};\n\ntemplate &lt;typename VALUE&gt; class derived : public interface&lt;derived, VALUE&gt; {\n void do_something(VALUE v) { ... }\n};\n\ntypedef interface&lt;derived&lt;int&gt;, int&gt; derived_t;\n</code></pre>\n\n<p>Note the duplication of 'int', which is actually the same type parameter specified to both templates. You can use a template template for DERIVED to avoid this duplication:</p>\n\n<pre><code>template &lt;template &lt;typename&gt; class DERIVED, typename VALUE&gt; class interface {\n void do_something(VALUE v) {\n static_cast&lt;DERIVED&lt;VALUE&gt;*&gt;(this)-&gt;do_something(v);\n }\n};\n\ntemplate &lt;typename VALUE&gt; class derived : public interface&lt;derived, VALUE&gt; {\n void do_something(VALUE v) { ... }\n};\n\ntypedef interface&lt;derived, int&gt; derived_t;\n</code></pre>\n\n<p>Note that you are eliminating directly providing the other template parameter(s) to the <em>derived</em> template; the \"interface\" still receives them.</p>\n\n<p>This also lets you build up typedefs in the \"interface\" that depend on the type parameters, which will be accessible from the derived template.</p>\n\n<p>The above typedef doesn't work because you can't typedef to an unspecified template. This works, however (and C++11 has native support for template typedefs):</p>\n\n<pre><code>template &lt;typename VALUE&gt;\nstruct derived_interface_type {\n typedef typename interface&lt;derived, VALUE&gt; type;\n};\n\ntypedef typename derived_interface_type&lt;int&gt;::type derived_t;\n</code></pre>\n\n<p>You need one derived_interface_type for each instantiation of the derived template unfortunately, unless there's another trick I haven't learned yet.</p>\n" }, { "answer_id": 14311714, "author": "pfalcon", "author_id": 496009, "author_profile": "https://Stackoverflow.com/users/496009", "pm_score": 8, "selected": false, "text": "<p>Actually, usecase for template template parameters is rather obvious. Once you learn that C++ stdlib has gaping hole of not defining stream output operators for standard container types, you would proceed to write something like:</p>\n\n<pre><code>template&lt;typename T&gt;\nstatic inline std::ostream&amp; operator&lt;&lt;(std::ostream&amp; out, std::list&lt;T&gt; const&amp; v)\n{\n out &lt;&lt; '[';\n if (!v.empty()) {\n for (typename std::list&lt;T&gt;::const_iterator i = v.begin(); ;) {\n out &lt;&lt; *i;\n if (++i == v.end())\n break;\n out &lt;&lt; \", \";\n }\n }\n out &lt;&lt; ']';\n return out;\n}\n</code></pre>\n\n<p>Then you'd figure out that code for vector is just the same, for forward_list is the same, actually, even for multitude of map types it's still just the same. Those template classes don't have anything in common except for meta-interface/protocol, and using template template parameter allows to capture the commonality in all of them. Before proceeding to write a template though, it's worth to check a reference to recall that sequence containers accept 2 template arguments - for value type and allocator. While allocator is defaulted, we still should account for its existence in our template operator&lt;&lt;:</p>\n\n<pre><code>template&lt;template &lt;typename, typename&gt; class Container, class V, class A&gt;\nstd::ostream&amp; operator&lt;&lt;(std::ostream&amp; out, Container&lt;V, A&gt; const&amp; v)\n...\n</code></pre>\n\n<p>Voila, that will work automagically for all present and future sequence containers adhering to the standard protocol. To add maps to the mix, it would take a peek at reference to note that they accept 4 template params, so we'd need another version of the operator&lt;&lt; above with 4-arg template template param. We'd also see that std:pair tries to be rendered with 2-arg operator&lt;&lt; for sequence types we defined previously, so we would provide a specialization just for std::pair. </p>\n\n<p>Btw, with C+11 which allows variadic templates (and thus should allow variadic template template args), it would be possible to have single operator&lt;&lt; to rule them all. For example:</p>\n\n<pre><code>#include &lt;iostream&gt;\n#include &lt;vector&gt;\n#include &lt;deque&gt;\n#include &lt;list&gt;\n\ntemplate&lt;typename T, template&lt;class,class...&gt; class C, class... Args&gt;\nstd::ostream&amp; operator &lt;&lt;(std::ostream&amp; os, const C&lt;T,Args...&gt;&amp; objs)\n{\n os &lt;&lt; __PRETTY_FUNCTION__ &lt;&lt; '\\n';\n for (auto const&amp; obj : objs)\n os &lt;&lt; obj &lt;&lt; ' ';\n return os;\n}\n\nint main()\n{\n std::vector&lt;float&gt; vf { 1.1, 2.2, 3.3, 4.4 };\n std::cout &lt;&lt; vf &lt;&lt; '\\n';\n\n std::list&lt;char&gt; lc { 'a', 'b', 'c', 'd' };\n std::cout &lt;&lt; lc &lt;&lt; '\\n';\n\n std::deque&lt;int&gt; di { 1, 2, 3, 4 };\n std::cout &lt;&lt; di &lt;&lt; '\\n';\n\n return 0;\n}\n</code></pre>\n\n<p><strong>Output</strong></p>\n\n<pre><code>std::ostream &amp;operator&lt;&lt;(std::ostream &amp;, const C&lt;T, Args...&gt; &amp;) [T = float, C = vector, Args = &lt;std::__1::allocator&lt;float&gt;&gt;]\n1.1 2.2 3.3 4.4 \nstd::ostream &amp;operator&lt;&lt;(std::ostream &amp;, const C&lt;T, Args...&gt; &amp;) [T = char, C = list, Args = &lt;std::__1::allocator&lt;char&gt;&gt;]\na b c d \nstd::ostream &amp;operator&lt;&lt;(std::ostream &amp;, const C&lt;T, Args...&gt; &amp;) [T = int, C = deque, Args = &lt;std::__1::allocator&lt;int&gt;&gt;]\n1 2 3 4 \n</code></pre>\n" }, { "answer_id": 23930985, "author": "Cookie", "author_id": 698504, "author_profile": "https://Stackoverflow.com/users/698504", "pm_score": 4, "selected": false, "text": "<p>This is what I ran into:</p>\n\n<pre><code>template&lt;class A&gt;\nclass B\n{\n A&amp; a;\n};\n\ntemplate&lt;class B&gt;\nclass A\n{\n B b;\n};\n\nclass AInstance : A&lt;B&lt;A&lt;B&lt;A&lt;B&lt;A&lt;B&lt;... (oh oh)&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;\n{\n\n};\n</code></pre>\n\n<p>Can be solved to:</p>\n\n<pre><code>template&lt;class A&gt;\nclass B\n{\n A&amp; a;\n};\n\ntemplate&lt; template&lt;class&gt; class B&gt;\nclass A\n{\n B&lt;A&gt; b;\n};\n\nclass AInstance : A&lt;B&gt; //happy\n{\n\n};\n</code></pre>\n\n<p>or (working code):</p>\n\n<pre><code>template&lt;class A&gt;\nclass B\n{\npublic:\n A* a;\n int GetInt() { return a-&gt;dummy; }\n};\n\ntemplate&lt; template&lt;class&gt; class B&gt;\nclass A\n{\npublic:\n A() : dummy(3) { b.a = this; }\n B&lt;A&gt; b;\n int dummy;\n};\n\nclass AInstance : public A&lt;B&gt; //happy\n{\npublic:\n void Print() { std::cout &lt;&lt; b.GetInt(); }\n};\n\nint main()\n{\n std::cout &lt;&lt; \"hello\";\n AInstance test;\n test.Print();\n}\n</code></pre>\n" }, { "answer_id": 28597414, "author": "Kuberan Naganathan", "author_id": 3962477, "author_profile": "https://Stackoverflow.com/users/3962477", "pm_score": 2, "selected": false, "text": "<p>In the solution with variadic templates provided by pfalcon, I found it difficult to actually specialize the ostream operator for std::map due to the greedy nature of the variadic specialization. Here's a slight revision which worked for me:</p>\n\n<pre><code>#include &lt;iostream&gt;\n#include &lt;vector&gt;\n#include &lt;deque&gt;\n#include &lt;list&gt;\n#include &lt;map&gt;\n\nnamespace containerdisplay\n{\n template&lt;typename T, template&lt;class,class...&gt; class C, class... Args&gt;\n std::ostream&amp; operator &lt;&lt;(std::ostream&amp; os, const C&lt;T,Args...&gt;&amp; objs)\n {\n std::cout &lt;&lt; __PRETTY_FUNCTION__ &lt;&lt; '\\n';\n for (auto const&amp; obj : objs)\n os &lt;&lt; obj &lt;&lt; ' ';\n return os;\n } \n}\n\ntemplate&lt; typename K, typename V&gt;\nstd::ostream&amp; operator &lt;&lt; ( std::ostream&amp; os, \n const std::map&lt; K, V &gt; &amp; objs )\n{ \n\n std::cout &lt;&lt; __PRETTY_FUNCTION__ &lt;&lt; '\\n';\n for( auto&amp; obj : objs )\n { \n os &lt;&lt; obj.first &lt;&lt; \": \" &lt;&lt; obj.second &lt;&lt; std::endl;\n }\n\n return os;\n}\n\n\nint main()\n{\n\n {\n using namespace containerdisplay;\n std::vector&lt;float&gt; vf { 1.1, 2.2, 3.3, 4.4 };\n std::cout &lt;&lt; vf &lt;&lt; '\\n';\n\n std::list&lt;char&gt; lc { 'a', 'b', 'c', 'd' };\n std::cout &lt;&lt; lc &lt;&lt; '\\n';\n\n std::deque&lt;int&gt; di { 1, 2, 3, 4 };\n std::cout &lt;&lt; di &lt;&lt; '\\n';\n }\n\n std::map&lt; std::string, std::string &gt; m1 \n {\n { \"foo\", \"bar\" },\n { \"baz\", \"boo\" }\n };\n\n std::cout &lt;&lt; m1 &lt;&lt; std::endl;\n\n return 0;\n}\n</code></pre>\n" }, { "answer_id": 30337689, "author": "imallett", "author_id": 688624, "author_profile": "https://Stackoverflow.com/users/688624", "pm_score": 3, "selected": false, "text": "<p>Here's one generalized from something I just used. I'm posting it since it's a <em>very</em> simple example, and it demonstrates a practical use case along with default arguments:</p>\n\n<pre><code>#include &lt;vector&gt;\n\ntemplate &lt;class T&gt; class Alloc final { /*...*/ };\n\ntemplate &lt;template &lt;class T&gt; class allocator=Alloc&gt; class MyClass final {\n public:\n std::vector&lt;short,allocator&lt;short&gt;&gt; field0;\n std::vector&lt;float,allocator&lt;float&gt;&gt; field1;\n};\n</code></pre>\n" }, { "answer_id": 45967564, "author": "colin", "author_id": 3133205, "author_profile": "https://Stackoverflow.com/users/3133205", "pm_score": 2, "selected": false, "text": "<p>It improves readability of your code, provides extra type safety and save some compiler efforts.</p>\n\n<p>Say you want to print each element of a container, you can use the following code without template template parameter </p>\n\n<pre><code>template &lt;typename T&gt; void print_container(const T&amp; c)\n{\n for (const auto&amp; v : c)\n {\n std::cout &lt;&lt; v &lt;&lt; ' ';\n }\n std::cout &lt;&lt; '\\n';\n}\n</code></pre>\n\n<p>or with template template parameter</p>\n\n<pre><code>template&lt; template&lt;typename, typename&gt; class ContainerType, typename ValueType, typename AllocType&gt;\nvoid print_container(const ContainerType&lt;ValueType, AllocType&gt;&amp; c)\n{\n for (const auto&amp; v : c)\n {\n std::cout &lt;&lt; v &lt;&lt; ' ';\n }\n std::cout &lt;&lt; '\\n';\n}\n</code></pre>\n\n<p>Assume you pass in an integer say <code>print_container(3)</code>. For the former case, the template will be instantiated by the compiler which will complain about the usage of <code>c</code> in the for loop, the latter will not instantiate the template at all as no matching type can be found. </p>\n\n<p>Generally speaking, if your template class/function is designed to handle template class as template parameter, it is better to make it clear. </p>\n" }, { "answer_id": 58157563, "author": "cd127", "author_id": 2834727, "author_profile": "https://Stackoverflow.com/users/2834727", "pm_score": 2, "selected": false, "text": "<p>I use it for versioned types.</p>\n\n<p>If you have a type versioned through a template such as <code>MyType&lt;version&gt;</code>, you can write a function in which you can capture the version number:</p>\n\n<pre><code>template&lt;template&lt;uint8_t&gt; T, uint8_t Version&gt;\nFoo(const T&lt;Version&gt;&amp; obj)\n{\n assert(Version &gt; 2 &amp;&amp; \"Versions older than 2 are no longer handled\");\n ...\n switch (Version)\n {\n ...\n }\n}\n</code></pre>\n\n<p>So you can do different things depending on the version of the type being passed in instead of having an overload for each type.\nYou can also have conversion functions which take in <code>MyType&lt;Version&gt;</code> and return <code>MyType&lt;Version+1&gt;</code>, in a generic way, and even recurse them to have a <code>ToNewest()</code> function which returns the latest version of a type from any older version (very useful for logs that might have been stored a while back but need to be processed with today's newest tool).</p>\n" } ]
2008/10/17
[ "https://Stackoverflow.com/questions/213761", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4086/" ]
I've seen some examples of C++ using template template parameters (that is templates which take templates as parameters) to do policy-based class design. What other uses does this technique have?
I think you need to use template template syntax to pass a parameter whose type is a template dependent on another template like this: ``` template <template<class> class H, class S> void f(const H<S> &value) { } ``` Here, `H` is a template, but I wanted this function to deal with all specializations of `H`. **NOTE**: I've been programming c++ for many years and have only needed this once. I find that it is a rarely needed feature (of course handy when you need it!). I've been trying to think of good examples, and to be honest, most of the time this isn't necessary, but let's contrive an example. Let's pretend that `std::vector` *doesn't* have a `typedef value_type`. So how would you write a function which can create variables of the right type for the vectors elements? This would work. ``` template <template<class, class> class V, class T, class A> void f(V<T, A> &v) { // This can be "typename V<T, A>::value_type", // but we are pretending we don't have it T temp = v.back(); v.pop_back(); // Do some work on temp std::cout << temp << std::endl; } ``` **NOTE**: `std::vector` has two template parameters, type, and allocator, so we had to accept both of them. Fortunately, because of type deduction, we won't need to write out the exact type explicitly. which you can use like this: ``` f<std::vector, int>(v); // v is of type std::vector<int> using any allocator ``` or better yet, we can just use: ``` f(v); // everything is deduced, f can deal with a vector of any type! ``` **UPDATE**: Even this contrived example, while illustrative, is no longer an amazing example due to c++11 introducing `auto`. Now the same function can be written as: ``` template <class Cont> void f(Cont &v) { auto temp = v.back(); v.pop_back(); // Do some work on temp std::cout << temp << std::endl; } ``` which is how I'd prefer to write this type of code.
213,784
<p>I have the following in my web.config:</p> <pre><code>&lt;location path="RestrictedPage.aspx"&gt; &lt;system.web&gt; &lt;authorization&gt; &lt;allow roles="Group1Admin, Group3Admin, Group7Admin"/&gt; &lt;deny users="*"/&gt; &lt;/authorization&gt; &lt;/system.web&gt; &lt;/location&gt; </code></pre> <p>Within RestrictedPage.aspx.cs, how do I retrieve the allowed roles collection that contains Group1Admin, Group3Admin, and Group7Admin?</p> <p>Here's why I ask:</p> <p>The web.config is handling the authorization to the page. That works fine. But I'm going to have a couple of these pages (say RestrictedPage.aspx, RestrictedPage2.aspx, RestrictedPage3.aspx). Each of these pages is going to have my custom webcontrol on it. And each of these pages will have different allowed roles. My webcontrol has a dropdown list. The choices within the dropdown depend on the intersection of the user's roles and the page's allowed roles.</p> <p>As mentioned below, searching the web.config with XPath would probably work. I was just hoping for something more framework-y. Kind of like SiteMap. When I put roles in my web.sitemap, I can grab them using SiteMap.CurrentNode.Roles (my website is using Windows authentication, so I can't use web.sitemap for security trimming and I'd rather maintain roles in only one file).</p>
[ { "answer_id": 213815, "author": "Kolten", "author_id": 13959, "author_profile": "https://Stackoverflow.com/users/13959", "pm_score": 0, "selected": false, "text": "<pre><code>if {User.IsInRole(\"Group1Admin\"){//do stuff}\n</code></pre>\n\n<p>Is that what your asking?</p>\n" }, { "answer_id": 213828, "author": "dnolan", "author_id": 29086, "author_profile": "https://Stackoverflow.com/users/29086", "pm_score": 0, "selected": false, "text": "<p>I'm not sure for certain, but I would have thought that this is checked before your page is even processed, so if a user is not in a role they would never reach your page. Which ultimately would make the visibility of this redundant in the page.</p>\n" }, { "answer_id": 213853, "author": "Ed Altorfer", "author_id": 26552, "author_profile": "https://Stackoverflow.com/users/26552", "pm_score": 0, "selected": false, "text": "<p>I'm convinced that there is a better way to read this information, but here is a way that you can read the allow values from a web.config file.</p>\n\n<pre><code>XmlDocument webConfigReader = new XmlDocument(); \nwebConfigReader.Load(Server.MapPath(\"web.config\")); \n\nXmlNodeList root = webConfigReader.SelectNodes(\"//location[@path=\"RestrictedPage.aspx\"]//allow//@roles\"); \n\nforeach (XmlNode node in root) \n{ \n Response.Write(node.Value); \n} \n</code></pre>\n\n<p>Of course, the ASP.NET role provider will handle this for you, so reading these values is only really relevant if you plan to do something with them in the code-behind beside authorizing users, which you may be doing.</p>\n\n<p>Hope this helps--you may have to split your result using the , character. </p>\n" }, { "answer_id": 213979, "author": "Dillie-O", "author_id": 71, "author_profile": "https://Stackoverflow.com/users/71", "pm_score": 0, "selected": false, "text": "<p>What typically happens is this...</p>\n\n<p>When the user hits your page, if authentication/authorization is active, the Application_Authentication event is raised. Unless you are using Windows Authentication against something like Active Directory, the IPrincipal and Identity objects will not be available to you, so you can't access the User.IsInRole() method. However, you CAN do this by adding the following code into your Global.asax file:</p>\n\n<pre><code>Sub Application_AuthenticateRequest(ByVal sender As Object, ByVal e As EventArgs)\n\n Dim formsAuthTicket As FormsAuthenticationTicket\n Dim httpCook As HttpCookie\n Dim objGenericIdentity As GenericIdentity\n Dim objMyAppPrincipal As CustomPrincipal\n Dim strRoles As String()\n\n Log.Info(\"Starting Application AuthenticateRequest Method...\")\n\n httpCook = Context.Request.Cookies.Get(\"authCookieEAF\")\n formsAuthTicket = FormsAuthentication.Decrypt(httpCook.Value)\n objGenericIdentity = New GenericIdentity(formsAuthTicket.Name)\n strRoles = formsAuthTicket.UserData.Split(\"|\"c)\n objMyAppPrincipal = New CustomPrincipal(objGenericIdentity, strRoles)\n HttpContext.Current.User = objMyAppPrincipal\n\n Log.Info(\"Application AuthenticateRequest Method Complete.\")\n\nEnd Sub\n</code></pre>\n\n<p>This will put a cookie into the browser session with the proper user and role credentials you can access in the web app.</p>\n\n<p>Ideally, your user is only going to be in one role in an application, so I believe that is why you have the role check method available to you. It would be easy enough to write a helper method for you that would iterate through the list of roles in the application and test to see what role they are in.</p>\n" }, { "answer_id": 214264, "author": "makstaks", "author_id": 1100768, "author_profile": "https://Stackoverflow.com/users/1100768", "pm_score": 3, "selected": true, "text": "<pre><code>// set the configuration path to your config file\nstring configPath = \"??\";\n\nConfiguration config = WebConfigurationManager.OpenWebConfiguration(configPath);\n\n// Get the object related to the &lt;identity&gt; section.\nAuthorizationSection section = (AuthorizationSection)config.GetSection(\"system.web/authorization\");\n</code></pre>\n\n<p>from the section object get the AuthorizationRuleCollection object where you can then extract the Roles. </p>\n\n<p>Note: You'll probably need to modify the path to the section a bit since you start with \"location path=\"RestrictedPage.aspx\"\", I didn't try that scenario.</p>\n" } ]
2008/10/17
[ "https://Stackoverflow.com/questions/213784", "https://Stackoverflow.com", "https://Stackoverflow.com/users/27482/" ]
I have the following in my web.config: ``` <location path="RestrictedPage.aspx"> <system.web> <authorization> <allow roles="Group1Admin, Group3Admin, Group7Admin"/> <deny users="*"/> </authorization> </system.web> </location> ``` Within RestrictedPage.aspx.cs, how do I retrieve the allowed roles collection that contains Group1Admin, Group3Admin, and Group7Admin? Here's why I ask: The web.config is handling the authorization to the page. That works fine. But I'm going to have a couple of these pages (say RestrictedPage.aspx, RestrictedPage2.aspx, RestrictedPage3.aspx). Each of these pages is going to have my custom webcontrol on it. And each of these pages will have different allowed roles. My webcontrol has a dropdown list. The choices within the dropdown depend on the intersection of the user's roles and the page's allowed roles. As mentioned below, searching the web.config with XPath would probably work. I was just hoping for something more framework-y. Kind of like SiteMap. When I put roles in my web.sitemap, I can grab them using SiteMap.CurrentNode.Roles (my website is using Windows authentication, so I can't use web.sitemap for security trimming and I'd rather maintain roles in only one file).
``` // set the configuration path to your config file string configPath = "??"; Configuration config = WebConfigurationManager.OpenWebConfiguration(configPath); // Get the object related to the <identity> section. AuthorizationSection section = (AuthorizationSection)config.GetSection("system.web/authorization"); ``` from the section object get the AuthorizationRuleCollection object where you can then extract the Roles. Note: You'll probably need to modify the path to the section a bit since you start with "location path="RestrictedPage.aspx"", I didn't try that scenario.
213,801
<p>I need to get a list of all documents in a site collection, which I believe I can do with either the alldocs table or the alluserdata table (MOSS 2007 SP1) but do not see how I can get the author information for the document. I do not need the contents of the document (e.g. AllDocStreams content)</p> <p><strong>Something like this:</strong></p> <pre><code>SELECT tp_DirName, tp_LeafName, tp_Version, tp_Modified, tp_Created FROM AllUserData WHERE (tp_ContentType = 'Document') AND (tp_LeafName NOT LIKE '%.css') AND (tp_LeafName NOT LIKE '%.jpg') AND (tp_LeafName NOT LIKE '%.png') AND (tp_LeafName NOT LIKE '%.wmf') AND (tp_LeafName NOT LIKE '%.gif') AND (tp_DirName NOT LIKE '%Template%') AND (tp_IsCurrentVersion = 1) AND (tp_LeafName NOT LIKE '%.xsl') ORDER BY tp_SiteId, tp_ListId, tp_DirName, tp_LeafName, tp_IsCurrentVersion DESC </code></pre> <p><strong>Is there a better way to go about this?</strong></p>
[ { "answer_id": 213848, "author": "cciotti", "author_id": 16834, "author_profile": "https://Stackoverflow.com/users/16834", "pm_score": 0, "selected": false, "text": "<p>MOSS provides many <a href=\"http://www.infoq.com/articles/swanson-moss-web-services\" rel=\"nofollow noreferrer\">webservices</a> out of the box which make life a little easier. They are always worth exploring.</p>\n\n<p>For this particular instance, I think the article, <a href=\"http://sqlblogcasts.com/blogs/drjohn/archive/2007/11/02/Getting-a-list-of-files-from-a-moss-document-library-using-a-SharePoint-web-service.aspx\" rel=\"nofollow noreferrer\"><em>Getting a list of files from a MOSS document library using a SharePoint web service</em></a>, will be of assistance. If this isn't your exact scenario, it will get you on the right track.</p>\n\n<p>If the Document service doesn't help you, the Search service will I'm sure. Check the documentation for usage. </p>\n" }, { "answer_id": 214068, "author": "Cruiser", "author_id": 16971, "author_profile": "https://Stackoverflow.com/users/16971", "pm_score": 0, "selected": false, "text": "<p>You can get some of the information from the UserInfo table by joining AllUserData.tp_Author to UserInfo.tp_ID, but messing around in these tables is not recommended and can be very fragile, and also your queries are not guaranteed to work after applying any patches or service packs to SharePoint. I would use either webservices or the SharePoint object model to access the data.</p>\n" }, { "answer_id": 216794, "author": "Kasper", "author_id": 23499, "author_profile": "https://Stackoverflow.com/users/23499", "pm_score": 2, "selected": false, "text": "<p>Why not use the sharepoint object model rather then using the raw database approach? I know that the object model approach does have a performance penalty compared to the database, but MS could change the db schema with the next path. On the other hand the likelyhood of MS breaking their own object model is far less, and as far as I know the recommended way is to use either the object model or the web services.</p>\n" }, { "answer_id": 445134, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 2, "selected": false, "text": "<p>Don't ever query the SharePoint database directly. This is completely unsupported and can get you into trouble moving forward (for instance, if a service-pack or hotfix modifies schema, then you app is broken). </p>\n" }, { "answer_id": 726063, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 3, "selected": false, "text": "<p>People that claim that you cannot query SharePoint databases because it is not supported are wrong. From reading the documentation, it is fine to query the database as long as you use the 'With(NoLock)' clause. It is clearly not supported to update, delete, or insert records.</p>\n\n<p>The below query is supported:</p>\n\n<pre><code>Select * \nFrom your_content_database.dbo.AllDocs With (NoLock)\n</code></pre>\n\n<p>I will post a query that provides the desired result in a few minutes.</p>\n" }, { "answer_id": 726633, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 2, "selected": false, "text": "<p>The below would return the top 100 largest documents that were added in the last 24 hours to the content database. </p>\n\n<pre><code>Select Top 100 \n W.FullUrl, \n W.Title, \n L.tp_Title as ListTitle, \n A.tp_DirName, \n A.tp_LeafName, \n A.tp_id , \n DS.Content , \n DS.Size, \n D.DocLibRowID, \n D.TimeCreated, \n D.Size, \n D.MetaInfoTimeLastModified, \n D.ExtensionForFile \nFrom your_content_database.dbo.AllLists L With (NoLock) \njoin your_content_database.dbo.AllUserData A With (NoLock) \n On L.tp_ID=tp_ListId \njoin your_content_database.dbo.AllDocs D With (NoLock) \n On A.tp_ListID=D.ListID \n And A.tp_SiteID=D.SiteID \n And A.tp_DirName=D.DirName \n And A.tp_LeafName=D.LeafName \njoin your_content_database.dbo.AllDocStreams DS With (NoLock) \n On DS.SiteID=A.tp_SiteID \n And DS.ParentID=D.ParentID \n And DS.ID=D.ID \njoin your_content_database.dbo.Webs W With (NoLock) \n On W.ID=D.WebID \n And W.ID=L.Tp_WebID \n And W.SiteID=A.tp_SiteID \nWhere DS.DeleteTransactionID=0x \n And D.DeleteTransactionID=0x \n And D.IsCurrentVersion=1 \n And A.tp_DeleteTransactionID=0x \n And A.tp_IsCurrentVersion=1 \n And D.HasStream=1 \n And L.tp_DeleteTransactionId=0x \n And ExtensionForFile not in('webpart','dwp','aspx','xsn','master','rules','xoml') \n And D.MetaInfoTimeLastModified&gt;DateAdd(d,-1,GetDate()) \nOrder by DS.Size desc\n</code></pre>\n" }, { "answer_id": 1480270, "author": "ArjanP", "author_id": 114649, "author_profile": "https://Stackoverflow.com/users/114649", "pm_score": 1, "selected": false, "text": "<ul>\n<li>Why don't you use a <a href=\"http://msdn.microsoft.com/en-us/library/bb850574.aspx\" rel=\"nofollow noreferrer\">Content Query web part</a>? </li>\n<li>Why don't you use a <a href=\"http://msdn.microsoft.com/en-us/library/bb626127.aspx\" rel=\"nofollow noreferrer\">search object</a> to query the same? This would be my preferred solution. Search has most properties already and you can add more if you need them. Search is probably a lot quicker than querying content database(s). </li>\n</ul>\n\n<p>Whether it is supported or not, it is still bad form to query the Content Database directly and any developer who would suggest this as a solution should get a lecture ;). For instance, what happens if an admin creates a second content database to your webapp? If you query goes across site collections it will not return the desired results until you provide for this in code.</p>\n" }, { "answer_id": 6900546, "author": "Ulf", "author_id": 523618, "author_profile": "https://Stackoverflow.com/users/523618", "pm_score": 2, "selected": false, "text": "<p>I recommend that you have a look at the Camelot .NET Connector which allows you to query SharePoint 2007/2010 using standard SQL queries. Its a ADO.NET driver that can also be exposed through a simple WCF service and by that available through any programming language. Lets say one would like to select from \"shared documents\", you would write something like:</p>\n\n<pre><code>select * from `shared documents`\n</code></pre>\n\n<p>or with certain columns:</p>\n\n<pre><code>select id, title, filetype, filesize, created, createdby from `shared documents`\n</code></pre>\n\n<p>or with where statement:</p>\n\n<pre><code>select id, title, filetype, filesize, created, createdby from `shared documents` where filetype = '.gif'\n</code></pre>\n" } ]
2008/10/17
[ "https://Stackoverflow.com/questions/213801", "https://Stackoverflow.com", "https://Stackoverflow.com/users/25642/" ]
I need to get a list of all documents in a site collection, which I believe I can do with either the alldocs table or the alluserdata table (MOSS 2007 SP1) but do not see how I can get the author information for the document. I do not need the contents of the document (e.g. AllDocStreams content) **Something like this:** ``` SELECT tp_DirName, tp_LeafName, tp_Version, tp_Modified, tp_Created FROM AllUserData WHERE (tp_ContentType = 'Document') AND (tp_LeafName NOT LIKE '%.css') AND (tp_LeafName NOT LIKE '%.jpg') AND (tp_LeafName NOT LIKE '%.png') AND (tp_LeafName NOT LIKE '%.wmf') AND (tp_LeafName NOT LIKE '%.gif') AND (tp_DirName NOT LIKE '%Template%') AND (tp_IsCurrentVersion = 1) AND (tp_LeafName NOT LIKE '%.xsl') ORDER BY tp_SiteId, tp_ListId, tp_DirName, tp_LeafName, tp_IsCurrentVersion DESC ``` **Is there a better way to go about this?**
People that claim that you cannot query SharePoint databases because it is not supported are wrong. From reading the documentation, it is fine to query the database as long as you use the 'With(NoLock)' clause. It is clearly not supported to update, delete, or insert records. The below query is supported: ``` Select * From your_content_database.dbo.AllDocs With (NoLock) ``` I will post a query that provides the desired result in a few minutes.
213,814
<p>I'm writing an intranet application for a client and I want to give them the ability to configure through an admin interface, which users and user groups can access certain areas. What I'd like to know is the best way of storing the reference to the user or group that is assigned to an area of the intranet. </p> <p>Should I be using the <strong>domain\username</strong> and <strong>domain\groupname</strong> strings or should i perhaps be using the fully qualified ad name ie <strong>ou=computer room;cn=blah</strong> etc?</p> <p>I will be storing the reference in SQL.</p>
[ { "answer_id": 213848, "author": "cciotti", "author_id": 16834, "author_profile": "https://Stackoverflow.com/users/16834", "pm_score": 0, "selected": false, "text": "<p>MOSS provides many <a href=\"http://www.infoq.com/articles/swanson-moss-web-services\" rel=\"nofollow noreferrer\">webservices</a> out of the box which make life a little easier. They are always worth exploring.</p>\n\n<p>For this particular instance, I think the article, <a href=\"http://sqlblogcasts.com/blogs/drjohn/archive/2007/11/02/Getting-a-list-of-files-from-a-moss-document-library-using-a-SharePoint-web-service.aspx\" rel=\"nofollow noreferrer\"><em>Getting a list of files from a MOSS document library using a SharePoint web service</em></a>, will be of assistance. If this isn't your exact scenario, it will get you on the right track.</p>\n\n<p>If the Document service doesn't help you, the Search service will I'm sure. Check the documentation for usage. </p>\n" }, { "answer_id": 214068, "author": "Cruiser", "author_id": 16971, "author_profile": "https://Stackoverflow.com/users/16971", "pm_score": 0, "selected": false, "text": "<p>You can get some of the information from the UserInfo table by joining AllUserData.tp_Author to UserInfo.tp_ID, but messing around in these tables is not recommended and can be very fragile, and also your queries are not guaranteed to work after applying any patches or service packs to SharePoint. I would use either webservices or the SharePoint object model to access the data.</p>\n" }, { "answer_id": 216794, "author": "Kasper", "author_id": 23499, "author_profile": "https://Stackoverflow.com/users/23499", "pm_score": 2, "selected": false, "text": "<p>Why not use the sharepoint object model rather then using the raw database approach? I know that the object model approach does have a performance penalty compared to the database, but MS could change the db schema with the next path. On the other hand the likelyhood of MS breaking their own object model is far less, and as far as I know the recommended way is to use either the object model or the web services.</p>\n" }, { "answer_id": 445134, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 2, "selected": false, "text": "<p>Don't ever query the SharePoint database directly. This is completely unsupported and can get you into trouble moving forward (for instance, if a service-pack or hotfix modifies schema, then you app is broken). </p>\n" }, { "answer_id": 726063, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 3, "selected": false, "text": "<p>People that claim that you cannot query SharePoint databases because it is not supported are wrong. From reading the documentation, it is fine to query the database as long as you use the 'With(NoLock)' clause. It is clearly not supported to update, delete, or insert records.</p>\n\n<p>The below query is supported:</p>\n\n<pre><code>Select * \nFrom your_content_database.dbo.AllDocs With (NoLock)\n</code></pre>\n\n<p>I will post a query that provides the desired result in a few minutes.</p>\n" }, { "answer_id": 726633, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 2, "selected": false, "text": "<p>The below would return the top 100 largest documents that were added in the last 24 hours to the content database. </p>\n\n<pre><code>Select Top 100 \n W.FullUrl, \n W.Title, \n L.tp_Title as ListTitle, \n A.tp_DirName, \n A.tp_LeafName, \n A.tp_id , \n DS.Content , \n DS.Size, \n D.DocLibRowID, \n D.TimeCreated, \n D.Size, \n D.MetaInfoTimeLastModified, \n D.ExtensionForFile \nFrom your_content_database.dbo.AllLists L With (NoLock) \njoin your_content_database.dbo.AllUserData A With (NoLock) \n On L.tp_ID=tp_ListId \njoin your_content_database.dbo.AllDocs D With (NoLock) \n On A.tp_ListID=D.ListID \n And A.tp_SiteID=D.SiteID \n And A.tp_DirName=D.DirName \n And A.tp_LeafName=D.LeafName \njoin your_content_database.dbo.AllDocStreams DS With (NoLock) \n On DS.SiteID=A.tp_SiteID \n And DS.ParentID=D.ParentID \n And DS.ID=D.ID \njoin your_content_database.dbo.Webs W With (NoLock) \n On W.ID=D.WebID \n And W.ID=L.Tp_WebID \n And W.SiteID=A.tp_SiteID \nWhere DS.DeleteTransactionID=0x \n And D.DeleteTransactionID=0x \n And D.IsCurrentVersion=1 \n And A.tp_DeleteTransactionID=0x \n And A.tp_IsCurrentVersion=1 \n And D.HasStream=1 \n And L.tp_DeleteTransactionId=0x \n And ExtensionForFile not in('webpart','dwp','aspx','xsn','master','rules','xoml') \n And D.MetaInfoTimeLastModified&gt;DateAdd(d,-1,GetDate()) \nOrder by DS.Size desc\n</code></pre>\n" }, { "answer_id": 1480270, "author": "ArjanP", "author_id": 114649, "author_profile": "https://Stackoverflow.com/users/114649", "pm_score": 1, "selected": false, "text": "<ul>\n<li>Why don't you use a <a href=\"http://msdn.microsoft.com/en-us/library/bb850574.aspx\" rel=\"nofollow noreferrer\">Content Query web part</a>? </li>\n<li>Why don't you use a <a href=\"http://msdn.microsoft.com/en-us/library/bb626127.aspx\" rel=\"nofollow noreferrer\">search object</a> to query the same? This would be my preferred solution. Search has most properties already and you can add more if you need them. Search is probably a lot quicker than querying content database(s). </li>\n</ul>\n\n<p>Whether it is supported or not, it is still bad form to query the Content Database directly and any developer who would suggest this as a solution should get a lecture ;). For instance, what happens if an admin creates a second content database to your webapp? If you query goes across site collections it will not return the desired results until you provide for this in code.</p>\n" }, { "answer_id": 6900546, "author": "Ulf", "author_id": 523618, "author_profile": "https://Stackoverflow.com/users/523618", "pm_score": 2, "selected": false, "text": "<p>I recommend that you have a look at the Camelot .NET Connector which allows you to query SharePoint 2007/2010 using standard SQL queries. Its a ADO.NET driver that can also be exposed through a simple WCF service and by that available through any programming language. Lets say one would like to select from \"shared documents\", you would write something like:</p>\n\n<pre><code>select * from `shared documents`\n</code></pre>\n\n<p>or with certain columns:</p>\n\n<pre><code>select id, title, filetype, filesize, created, createdby from `shared documents`\n</code></pre>\n\n<p>or with where statement:</p>\n\n<pre><code>select id, title, filetype, filesize, created, createdby from `shared documents` where filetype = '.gif'\n</code></pre>\n" } ]
2008/10/17
[ "https://Stackoverflow.com/questions/213814", "https://Stackoverflow.com", "https://Stackoverflow.com/users/29086/" ]
I'm writing an intranet application for a client and I want to give them the ability to configure through an admin interface, which users and user groups can access certain areas. What I'd like to know is the best way of storing the reference to the user or group that is assigned to an area of the intranet. Should I be using the **domain\username** and **domain\groupname** strings or should i perhaps be using the fully qualified ad name ie **ou=computer room;cn=blah** etc? I will be storing the reference in SQL.
People that claim that you cannot query SharePoint databases because it is not supported are wrong. From reading the documentation, it is fine to query the database as long as you use the 'With(NoLock)' clause. It is clearly not supported to update, delete, or insert records. The below query is supported: ``` Select * From your_content_database.dbo.AllDocs With (NoLock) ``` I will post a query that provides the desired result in a few minutes.
213,816
<p>I want to check for duplicated words right next to each other, but even if there is punctuation in between.</p> <p>For example:</p> <pre><code>Vivamus Vivamus diam, diam, Vivamus Vivamus diam, diam Vivamus </code></pre> <p>There should be four distinct hits here.</p> <p>I can't figure out why this isn't working. Why? What should the correct code be?</p> <pre class="lang-none prettyprint-override"><code>(\w*(?:[ ,\.])*?)\1 </code></pre> <hr /> <p><em>PS: This is</em> <em><strong>not</strong></em> <em>necessarily for the Perl engine.</em></p>
[ { "answer_id": 213824, "author": "TJ L", "author_id": 12605, "author_profile": "https://Stackoverflow.com/users/12605", "pm_score": 4, "selected": true, "text": "<p>The <code>(?:</code> is a non-capturing parenthesis, meaning it won't store the matches. You will need to use capturing parentheses.</p>\n<pre><code>(\\w+)\\W+\\1\n</code></pre>\n" }, { "answer_id": 213922, "author": "Jonathan Leffler", "author_id": 15168, "author_profile": "https://Stackoverflow.com/users/15168", "pm_score": 0, "selected": false, "text": "<p>The original expression doesn't create a separate capture for the punctuation, but does include the captured punctuation in the first capture. That means it would spot things like:</p>\n<pre><code>diam, diam, really, really, twice.\n</code></pre>\n<p>But you aren't really interested in the punctuation, so <a href=\"https://stackoverflow.com/a/213824/63550\">TJ L's solution</a> works properly, even though the '(?: ) is a non-capturing parenthesis' explanation is somewhat ... incomplete? The comment quoted is accurate, but it isn't why the overall regex failed.</p>\n" }, { "answer_id": 46739362, "author": "Stunner", "author_id": 347339, "author_profile": "https://Stackoverflow.com/users/347339", "pm_score": 1, "selected": false, "text": "<p><code>[[\\w|\\W]+ ]+</code> worked for me. Breakdown:</p>\n<p><code>\\w</code>: word character</p>\n<p><code>\\W</code>: non-word character</p>\n<p><code>[\\w|\\W]+</code>: each character may be a word or non-word character and repeated one or more times</p>\n<p><code>[[\\w|\\W]+ ]+</code>: ...appended with a space at some point, all occurring one or more times</p>\n" } ]
2008/10/17
[ "https://Stackoverflow.com/questions/213816", "https://Stackoverflow.com", "https://Stackoverflow.com/users/730/" ]
I want to check for duplicated words right next to each other, but even if there is punctuation in between. For example: ``` Vivamus Vivamus diam, diam, Vivamus Vivamus diam, diam Vivamus ``` There should be four distinct hits here. I can't figure out why this isn't working. Why? What should the correct code be? ```none (\w*(?:[ ,\.])*?)\1 ``` --- *PS: This is* ***not*** *necessarily for the Perl engine.*
The `(?:` is a non-capturing parenthesis, meaning it won't store the matches. You will need to use capturing parentheses. ``` (\w+)\W+\1 ```
213,845
<p>I have a HTML file that has code similar to the following.</p> <pre><code>&lt;table&gt; &lt;tr&gt; &lt;td id="MyCell"&gt;Hello World&lt;/td&gt; &lt;/tr&gt; &lt;/table&gt; </code></pre> <p>I am using javascript like the following to get the value</p> <pre><code>document.getElementById(cell2.Element.id).innerText </code></pre> <p>This returns the text "Hello World" with only 1 space between hello and world. I MUST keep the same number of spaces, is there any way for that to be done?</p> <p>I've tried using innerHTML, outerHTML and similar items, but I'm having no luck.</p>
[ { "answer_id": 213854, "author": "Nick", "author_id": 26161, "author_profile": "https://Stackoverflow.com/users/26161", "pm_score": 4, "selected": true, "text": "<p>HTML is white space insensititive which means your DOM is too. Would wrapping your \"Hello World\" in <b>pre</b> block work at all?</p>\n" }, { "answer_id": 213858, "author": "TJ L", "author_id": 12605, "author_profile": "https://Stackoverflow.com/users/12605", "pm_score": 3, "selected": false, "text": "<p>In HTML,any spaces >1 are ignored, both in displaying text and in retrieving it via the DOM. The only guaranteed way to maintain spaces it to use a non-breaking space <code>&amp;nbsp;</code>.</p>\n" }, { "answer_id": 213861, "author": "Nick", "author_id": 26161, "author_profile": "https://Stackoverflow.com/users/26161", "pm_score": 0, "selected": false, "text": "<p>Just checked it and it looks like wrapping with the <strong>pre</strong> tag should do it.</p>\n" }, { "answer_id": 213868, "author": "Daniel Silveira", "author_id": 1100, "author_profile": "https://Stackoverflow.com/users/1100", "pm_score": 2, "selected": false, "text": "<p>Just a tip, innerText only works in Internet Explorer, while innerHTML works in every browser... so, use innerHTML instead of innerText</p>\n" }, { "answer_id": 213944, "author": "savetheclocktower", "author_id": 25720, "author_profile": "https://Stackoverflow.com/users/25720", "pm_score": 2, "selected": false, "text": "<p>The <code>pre</code> tag or <code>white-space: pre</code> in your CSS will treat all spaces as meaningful. This will also, however, turn newlines into line breaks, so be careful.</p>\n" }, { "answer_id": 213945, "author": "eyelidlessness", "author_id": 17964, "author_profile": "https://Stackoverflow.com/users/17964", "pm_score": 0, "selected": false, "text": "<p>Edit: I am wrong, ignore me.</p>\n\n<p>You can get a text node's nodeValue, which should correctly represent its whitespace.</p>\n\n<p>Here is a function to recursively get the text within a given element (and it's library-safe, won't fail if you use something that modifies Array.prototype or whatever):</p>\n\n<pre><code>var textValue = function(element) {\n if(!element.hasOwnProperty('childNodes')) {\n return '';\n }\n var childNodes = element.childNodes, text = '', childNode;\n for(var i in childNodes) {\n if(childNodes.hasOwnProperty(i)) {\n childNode = childNodes[i];\n if(childNode.nodeType == 3) {\n text += childNode.nodeValue;\n } else {\n text += textValue(childNode);\n }\n }\n }\n return text;\n};\n</code></pre>\n" }, { "answer_id": 215407, "author": "Alan Storm", "author_id": 4668, "author_profile": "https://Stackoverflow.com/users/4668", "pm_score": 1, "selected": false, "text": "<p>Just an opinion here and not canonical advice, but you're headed for a world or hurt if you're trying to extract <strong>exact</strong> text values from the DOM using the inner/outer HTML/TEXT properties via Javascript. Different browsers are going to return slightly different values, based on how the browser \"sees\" the internal document.</p>\n\n<p>If you can, I'd change the HTML you're rendering to include a hidden input, something like</p>\n\n<pre><code>&lt;table&gt;\n &lt;tr&gt;\n &lt;td id=\"MyCell\"&gt;Hello World&lt;input id=\"MyCell_VALUE\" type=\"hidden\" value=\"Hello World\" /&gt;&lt;/td&gt;\n &lt;/tr&gt;\n&lt;/table&gt;\n</code></pre>\n\n<p>And then grab your value in javascript something like</p>\n\n<pre><code>document.getElementById(cell2.Element.id+'_VALUE').value\n</code></pre>\n\n<p>The input tags were designed to hold values, and you'll be less likely to run into fidelity issues.</p>\n\n<p>Also, it sounds like you're using a .NET control of some kind. It might be worth looking through the documentation (ha) or asking a slightly different question to see if the control offers an official client-side API of some kind.</p>\n" }, { "answer_id": 215460, "author": "Leo", "author_id": 20689, "author_profile": "https://Stackoverflow.com/users/20689", "pm_score": 0, "selected": false, "text": "<p>This is a bit hacky, but it works on my IE.</p>\n\n<pre><code>&lt;!DOCTYPE html PUBLIC \"-//W3C//DTD XHTML 1.0 Transitional//EN\" \"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd\"&gt; \n&lt;html xmlns=\"http://www.w3.org/1999/xhtml\" lang=\"en\"&gt;\n&lt;head&gt;\n &lt;title&gt;&lt;/title&gt;\n&lt;/head&gt;\n&lt;body&gt;\n&lt;div id=\"a\"&gt;a b&lt;/div&gt;\n&lt;script&gt;\nvar a = document.getElementById(\"a\");\na.style.whiteSpace = \"pre\"\nwindow.onload = function() {\n alert(a.firstChild.nodeValue.length) // should show 4\n}\n&lt;/script&gt;\n&lt;/body&gt;\n&lt;/html&gt;\n</code></pre>\n\n<p>Some notes:</p>\n\n<ul>\n<li>You must have a doctype.</li>\n<li>You cannot query the DOM element before window.onload has fired</li>\n<li>You should use element.nodeValue instead of innerHTML et al to avoid bugs when the text contains things like &lt; > &amp; \"</li>\n<li>You cannot reset whiteSpace once IE finishes rendering the page due to what I assume is an ugly bug</li>\n</ul>\n" }, { "answer_id": 440980, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 0, "selected": false, "text": "<p>This following trick preserves white-space in innerText in IE</p>\n\n<pre><code>var cloned = element.cloneNode(true);\nvar pre = document.createElement(\"pre\");\npre.appendChild(cloned);\nvar textContent = pre.textContent\n ? pre.textContent\n : pre.innerText;\ndelete pre;\ndelete cloned;\n</code></pre>\n" }, { "answer_id": 440996, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 0, "selected": false, "text": "<p>If someone could format my last post correctly it would look more readable. Sorry, I messed that one up. Basically the trick is create create a throwaway pre element, then append a copy of your node to that. Then you can get innerText or textContent depending on the browser.</p>\n\n<p>All browsers except IE basically do the obvious thing correctly. IE requires this hack since it only preserves white-space in pre elements, and only when you access innerText.</p>\n" } ]
2008/10/17
[ "https://Stackoverflow.com/questions/213845", "https://Stackoverflow.com", "https://Stackoverflow.com/users/13279/" ]
I have a HTML file that has code similar to the following. ``` <table> <tr> <td id="MyCell">Hello World</td> </tr> </table> ``` I am using javascript like the following to get the value ``` document.getElementById(cell2.Element.id).innerText ``` This returns the text "Hello World" with only 1 space between hello and world. I MUST keep the same number of spaces, is there any way for that to be done? I've tried using innerHTML, outerHTML and similar items, but I'm having no luck.
HTML is white space insensititive which means your DOM is too. Would wrapping your "Hello World" in **pre** block work at all?
213,851
<p>How can one programmatically sort a union query when pulling data from two tables? For example,</p> <pre><code>SELECT table1.field1 FROM table1 ORDER BY table1.field1 UNION SELECT table2.field1 FROM table2 ORDER BY table2.field1 </code></pre> <p>Throws an exception</p> <p>Note: this is being attempted on MS Access Jet database engine</p>
[ { "answer_id": 213862, "author": "Curtis Inderwiesche", "author_id": 3155, "author_profile": "https://Stackoverflow.com/users/3155", "pm_score": 0, "selected": false, "text": "<p>The second table cannot include the table name in the <code>ORDER BY</code> clause.</p>\n\n<p>So...</p>\n\n<pre><code>SELECT table1.field1 FROM table1 ORDER BY table1.field1\nUNION\nSELECT table2.field1 FROM table2 ORDER BY field1\n</code></pre>\n\n<p>Does not throw an exception</p>\n" }, { "answer_id": 213872, "author": "Anne Porosoff", "author_id": 28701, "author_profile": "https://Stackoverflow.com/users/28701", "pm_score": 6, "selected": false, "text": "<pre><code>SELECT field1 FROM table1\nUNION\nSELECT field1 FROM table2\nORDER BY field1\n</code></pre>\n" }, { "answer_id": 213874, "author": "Nick", "author_id": 26161, "author_profile": "https://Stackoverflow.com/users/26161", "pm_score": 3, "selected": false, "text": "<pre><code>(SELECT table1.field1 FROM table1 \nUNION\nSELECT table2.field1 FROM table2) ORDER BY field1 \n</code></pre>\n\n<p>Work? Remember think sets. Get the set you want using a union and then perform your operations on it.</p>\n" }, { "answer_id": 213886, "author": "Todd Price", "author_id": 29107, "author_profile": "https://Stackoverflow.com/users/29107", "pm_score": 4, "selected": false, "text": "<p>Here's an example from Northwind 2007:</p>\n\n<pre><code>SELECT [Product ID], [Order Date], [Company Name], [Transaction], [Quantity]\nFROM [Product Orders]\nUNION SELECT [Product ID], [Creation Date], [Company Name], [Transaction], [Quantity]\nFROM [Product Purchases]\nORDER BY [Order Date] DESC;\n</code></pre>\n\n<p>The ORDER BY clause just needs to be the last statement, after you've done all your unioning. You can union several sets together, then put an ORDER BY clause after the last set.</p>\n" }, { "answer_id": 213891, "author": "Anson Smith", "author_id": 28685, "author_profile": "https://Stackoverflow.com/users/28685", "pm_score": 6, "selected": false, "text": "<p>I think this does a good job of explaining.</p>\n\n<p>The following is a UNION query that uses an ORDER BY clause:</p>\n\n<pre><code>select supplier_id, supplier_name\nfrom suppliers\nwhere supplier_id &gt; 2000\nUNION\nselect company_id, company_name\nfrom companies\nwhere company_id &gt; 1000\nORDER BY 2;\n</code></pre>\n\n<p>Since the column names are different between the two \"select\" statements, it is more advantageous to reference the columns in the ORDER BY clause by their position in the result set. </p>\n\n<p>In this example, we've sorted the results by <code>supplier_name</code> / <code>company_name</code> in ascending order, as denoted by the \"ORDER BY 2\".</p>\n\n<p>The <code>supplier_name</code> / <code>company_name</code> fields are in position #2 in the\nresult set.</p>\n\n<p>Taken from here: <a href=\"http://www.techonthenet.com/sql/union.php\" rel=\"noreferrer\">http://www.techonthenet.com/sql/union.php</a></p>\n" }, { "answer_id": 213921, "author": "JohnMcG", "author_id": 1674, "author_profile": "https://Stackoverflow.com/users/1674", "pm_score": 3, "selected": false, "text": "<pre><code>SELECT table1Column1 as col1,table1Column2 as col2\n FROM table1\nUNION\n( SELECT table2Column1 as col1, table1Column2 as col2\n FROM table2\n)\nORDER BY col1 ASC\n</code></pre>\n" }, { "answer_id": 3394454, "author": "ajgreyling", "author_id": 409401, "author_profile": "https://Stackoverflow.com/users/409401", "pm_score": 8, "selected": true, "text": "<p>Sometimes you need to have the <code>ORDER BY</code> in each of the sections that need to be combined with <code>UNION</code>.</p>\n\n<p>In this case</p>\n\n<pre><code>SELECT * FROM \n(\n SELECT table1.field1 FROM table1 ORDER BY table1.field1\n) DUMMY_ALIAS1\n\nUNION ALL\n\nSELECT * FROM\n( \n SELECT table2.field1 FROM table2 ORDER BY table2.field1\n) DUMMY_ALIAS2\n</code></pre>\n" }, { "answer_id": 6319891, "author": "MJ Latifi", "author_id": 794452, "author_profile": "https://Stackoverflow.com/users/794452", "pm_score": 2, "selected": false, "text": "<pre><code>SELECT field1\nFROM ( SELECT field1 FROM table1\n UNION\n SELECT field1 FROM table2\n ) AS TBL\nORDER BY TBL.field1\n</code></pre>\n\n<p>(use ALIAS)</p>\n" }, { "answer_id": 7445656, "author": "Ian Boyd", "author_id": 12597, "author_profile": "https://Stackoverflow.com/users/12597", "pm_score": 5, "selected": false, "text": "<p>Using a concrete example:</p>\n\n<pre><code>SELECT name FROM Folders ORDER BY name\nUNION\nSELECT name FROM Files ORDER BY name\n</code></pre>\n\n<p><strong>Files:</strong></p>\n\n<pre><code>name\n=============================\nRTS.exe\nthiny1.etl\nthing2.elt\nf.txt\ntcpdump_trial_license (1).zip\n</code></pre>\n\n<p><strong>Folders:</strong></p>\n\n<pre><code>name\n============================\nContacts\nDesktop\nDownloads\nLinks\nFavorites\nMy Documents\n</code></pre>\n\n<p><strong>Desired Output:</strong> (results of first select first, i.e. folders first)</p>\n\n<pre><code>Contacts\nDesktop\nDownloads\nFavorites\nLinks\nMy Documents\nf.txt\nRTMS.exe\ntcpdump_trial_license (1).zip\nthiny1.etl\nthing2.elt\n</code></pre>\n\n<p>SQL to achieve the desired results:</p>\n\n<pre><code>SELECT name \nFROM (\n SELECT 1 AS rank, name FROM Folders\n UNION \n SELECT 2 AS rank, name FROM Files) dt\nORDER BY rank, name\n</code></pre>\n" }, { "answer_id": 7700084, "author": "Prayut Parsekar", "author_id": 985855, "author_profile": "https://Stackoverflow.com/users/985855", "pm_score": 2, "selected": false, "text": "<p>This is how it is done</p>\n\n<pre><code>select * from \n (select top 100 percent pointx, pointy from point\n where pointtype = 1\n order by pointy) A\nunion all\nselect * from \n (select top 100 percent pointx, pointy from point\n where pointtype = 2\n order by pointy desc) B\n</code></pre>\n" }, { "answer_id": 8072225, "author": "tlang", "author_id": 1038625, "author_profile": "https://Stackoverflow.com/users/1038625", "pm_score": 2, "selected": false, "text": "<p>This is the stupidest thing I've ever seen, but it works, and you can't argue with results.</p>\n\n<pre><code>SELECT *\nFROM (\n SELECT table1.field1 FROM table1 ORDER BY table1.field1\n UNION\n SELECT table2.field1 FROM table2 ORDER BY table2.field1\n) derivedTable\n</code></pre>\n\n<p>The interior of the derived table will not execute on its own, but as a derived table works perfectly fine. I've tried this on SS 2000, SS 2005, SS 2008 R2, and all three work.</p>\n" }, { "answer_id": 8990971, "author": "Ernesto Morales", "author_id": 1167485, "author_profile": "https://Stackoverflow.com/users/1167485", "pm_score": 1, "selected": false, "text": "<p>By using order separately each subset gets order, but not the whole set, which is what you would want uniting two tables.</p>\n\n<p>You should use something like this to have <strong>one</strong> ordered set:</p>\n\n<pre><code>SELECT TOP (100) PERCENT field1, field2, field3, field4, field5 FROM \n(SELECT table1.field1, table1.field2, table1.field3, table1.field4, table1.field5 FROM table1\nUNION ALL \nSELECT table2.field1, table2.field2, table2.field3, table2.field4, table2.field5 FROM table2) \nAS unitedTables ORDER BY field5 DESC\n</code></pre>\n" }, { "answer_id": 29035538, "author": "user1795683", "author_id": 1795683, "author_profile": "https://Stackoverflow.com/users/1795683", "pm_score": 0, "selected": false, "text": "<p>If necessary to keep the inner sorting:</p>\n\n<pre><code>SELECT 1 as type, field1 FROM table1 \nUNION \nSELECT 2 as type, field1 FROM table2 \nORDER BY type, field1\n</code></pre>\n" }, { "answer_id": 31414350, "author": "mandroid", "author_id": 1392873, "author_profile": "https://Stackoverflow.com/users/1392873", "pm_score": 0, "selected": false, "text": "<pre><code>(SELECT FIELD1 AS NEWFIELD FROM TABLE1 ORDER BY FIELD1)\nUNION\n(SELECT FIELD2 FROM TABLE2 ORDER BY FIELD2)\nUNION\n(SELECT FIELD3 FROM TABLE3 ORDER BY FIELD3) ORDER BY NEWFIELD\n</code></pre>\n\n<p>Try this. It worked for me. </p>\n" }, { "answer_id": 33290596, "author": "Bubblesphere", "author_id": 2973533, "author_profile": "https://Stackoverflow.com/users/2973533", "pm_score": 2, "selected": false, "text": "<p>Browsing this comment section I came accross two different patterns answering the question. Sadly for SQL 2012, the second pattern doesn't work, so here's my \"work around\"</p>\n\n<hr>\n\n<h2>Order By on a Common Column</h2>\n\n<p>This is the easiest case you can encounter. Like many user pointed out, all you really need to do is add an <code>Order By</code> at the end of the query</p>\n\n<pre><code>SELECT a FROM table1\nUNION\nSELECT a FROM table2\nORDER BY field1\n</code></pre>\n\n<p>or</p>\n\n<pre><code>SELECT a FROM table1 ORDER BY field1\nUNION\nSELECT a FROM table2 ORDER BY field1\n</code></pre>\n\n<hr>\n\n<h2>Order By on Different Columns</h2>\n\n<p>Here's where it actually gets tricky. Using SQL 2012, I tried the top post and it doesn't work.</p>\n\n<pre><code>SELECT * FROM \n(\n SELECT table1.field1 FROM table1 ORDER BY table1.field1\n) DUMMY_ALIAS1\n\nUNION ALL\n\nSELECT * FROM\n( \n SELECT table2.field1 FROM table2 ORDER BY table2.field1\n) DUMMY_ALIAS2\n</code></pre>\n\n<p>Following the recommandation in the comment I tried this</p>\n\n<pre><code>SELECT * FROM \n(\n SELECT TOP 100 PERCENT table1.field1 FROM table1 ORDER BY table1.field1\n) DUMMY_ALIAS1\n\nUNION ALL\n\nSELECT * FROM\n( \n SELECT TOP 100 PERCENT table2.field1 FROM table2 ORDER BY table2.field1\n) DUMMY_ALIAS2\n</code></pre>\n\n<p>This code did compile but the <code>DUMMY_ALIAS1</code> and <code>DUMMY_ALIAS2</code> override the <code>Order By</code> established in the <code>Select</code> statement which makes this unusable.</p>\n\n<p>The only solution that I could think of, that worked for me was not using a union and instead making the queries run individually and then dealing with them. So basically, not using a <code>Union</code> when you want to <code>Order By</code></p>\n" }, { "answer_id": 37386909, "author": "Bimal Das", "author_id": 4586387, "author_profile": "https://Stackoverflow.com/users/4586387", "pm_score": 0, "selected": false, "text": "<p><strong>For Sql Server 2014/2012/Others(Not Checked) :</strong></p>\n\n<pre><code>SELECT * FROM \n(\n SELECT table1.field1 FROM table1 ORDER BY table1.field1\n) \nas DUMMY_ALIAS1\n\nUNION ALL\n\nSELECT * FROM\n( \n SELECT table2.field1 FROM table2 ORDER BY table2.field1\n) \nas DUMMY_ALIAS2\n</code></pre>\n" } ]
2008/10/17
[ "https://Stackoverflow.com/questions/213851", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3155/" ]
How can one programmatically sort a union query when pulling data from two tables? For example, ``` SELECT table1.field1 FROM table1 ORDER BY table1.field1 UNION SELECT table2.field1 FROM table2 ORDER BY table2.field1 ``` Throws an exception Note: this is being attempted on MS Access Jet database engine
Sometimes you need to have the `ORDER BY` in each of the sections that need to be combined with `UNION`. In this case ``` SELECT * FROM ( SELECT table1.field1 FROM table1 ORDER BY table1.field1 ) DUMMY_ALIAS1 UNION ALL SELECT * FROM ( SELECT table2.field1 FROM table2 ORDER BY table2.field1 ) DUMMY_ALIAS2 ```
213,855
<p>I have a file with fields separated by pipe characters and I want to print only the second field. This attempt fails:</p> <pre><code>$ cat file | awk -F| '{print $2}' awk: syntax error near line 1 awk: bailing out near line 1 bash: {print $2}: command not found </code></pre> <p>Is there a way to do this?</p>
[ { "answer_id": 213856, "author": "Jon Ericson", "author_id": 1438, "author_profile": "https://Stackoverflow.com/users/1438", "pm_score": 2, "selected": false, "text": "<p>The pipe character needs to be escaped so that the shell doesn't interpret it. A simple solution:</p>\n\n<pre><code>$ awk -F\\| '{print $2}' file\n</code></pre>\n\n<p>Another choice would be to quote the character:</p>\n\n<pre><code>$ awk -F'|' '{print $2}' file\n</code></pre>\n" }, { "answer_id": 213880, "author": "Zsolt Botykai", "author_id": 11621, "author_profile": "https://Stackoverflow.com/users/11621", "pm_score": 4, "selected": false, "text": "<p>Or just use one command:</p>\n\n<pre><code>cut -d '|' -f FIELDNUMBER\n</code></pre>\n" }, { "answer_id": 213904, "author": "Jonathan Leffler", "author_id": 15168, "author_profile": "https://Stackoverflow.com/users/15168", "pm_score": 0, "selected": false, "text": "<p>And 'file' contains no pipe symbols, so it prints nothing. You should either use 'cat file' or simply list the file after the awk program.</p>\n" }, { "answer_id": 213917, "author": "dmckee --- ex-moderator kitten", "author_id": 2509, "author_profile": "https://Stackoverflow.com/users/2509", "pm_score": 4, "selected": true, "text": "<p>The key point here is that the pipe character (<code>|</code>) must be escaped to the shell. Use \"<code>\\|</code>\" or \"<code>'|'</code>\" to protect it from shell interpertation and allow it to be passed to <code>awk</code> on the command line.</p>\n\n<hr>\n\n<p>Reading the comments I see that the original poster presents a simplified version of the original problem which involved filtering <code>file</code> before selecting and printing the fields. A pass through <code>grep</code> was used and the result piped into awk for field selection. That accounts for the wholly unnecessary <code>cat file</code> that appears in the question (it replaces the <code>grep &lt;pattern&gt; file</code>).</p>\n\n<p>Fine, that will work. However, awk is largely a pattern matching tool on its own, and can be trusted to find and work on the matching lines without needing to invoke <code>grep</code>. Use something like:</p>\n\n<pre><code>awk -F\\| '/&lt;pattern&gt;/{print $2;}{next;}' file\n</code></pre>\n\n<p>The <code>/&lt;pattern&gt;/</code> bit tells <code>awk</code> to perform the action that follows on lines that match <code>&lt;pattern&gt;</code>.</p>\n\n<p>The lost-looking <code>{next;}</code> is a default action skipping to the next line in the input. It does not seem to be necessary, but I have this habit from long ago... </p>\n" }, { "answer_id": 60556020, "author": "Mirage", "author_id": 767244, "author_profile": "https://Stackoverflow.com/users/767244", "pm_score": 1, "selected": false, "text": "<p>Another way using awk</p>\n\n<pre><code>awk 'BEGIN { FS = \"|\" } ; { print $2 }'\n</code></pre>\n" } ]
2008/10/17
[ "https://Stackoverflow.com/questions/213855", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1438/" ]
I have a file with fields separated by pipe characters and I want to print only the second field. This attempt fails: ``` $ cat file | awk -F| '{print $2}' awk: syntax error near line 1 awk: bailing out near line 1 bash: {print $2}: command not found ``` Is there a way to do this?
The key point here is that the pipe character (`|`) must be escaped to the shell. Use "`\|`" or "`'|'`" to protect it from shell interpertation and allow it to be passed to `awk` on the command line. --- Reading the comments I see that the original poster presents a simplified version of the original problem which involved filtering `file` before selecting and printing the fields. A pass through `grep` was used and the result piped into awk for field selection. That accounts for the wholly unnecessary `cat file` that appears in the question (it replaces the `grep <pattern> file`). Fine, that will work. However, awk is largely a pattern matching tool on its own, and can be trusted to find and work on the matching lines without needing to invoke `grep`. Use something like: ``` awk -F\| '/<pattern>/{print $2;}{next;}' file ``` The `/<pattern>/` bit tells `awk` to perform the action that follows on lines that match `<pattern>`. The lost-looking `{next;}` is a default action skipping to the next line in the input. It does not seem to be necessary, but I have this habit from long ago...
213,857
<p>We have seen the following exceptions very frequently on IBM AIX when attempting to make an SSL connection to our server:</p> <pre><code>java.net.SocketException: Socket closed at com.sun.net.ssl.internal.ssl.SSLSocketImpl.a(DashoA6275(Compiled Code)) at com.sun.net.ssl.internal.ssl.AppOutputStream.write(DashoA6275(Compiled Code)) at java.io.BufferedOutputStream.flushBuffer(BufferedOutputStream.java(Inlined Compiled Code)) at java.io.BufferedOutputStream.flush(BufferedOutputStream.java(Compiled Code)) at java.io.FilterOutputStream.flush(FilterOutputStream.java(Compiled Code)) at org.apache.commons.httpclient.methods.EntityEnclosingMethod.writeRequestBody(EntityEnclosingMethod.java(Compiled Code)) at org.apache.commons.httpclient.HttpMethodBase.writeRequest(HttpMethodBase.java(Compiled Code)) at org.apache.commons.httpclient.HttpMethodBase.execute(HttpMethodBase.java(Compiled Code)) at org.apache.commons.httpclient.HttpMethodDirector.executeWithRetry(HttpMethodDirector.java(Compiled Code)) at org.apache.commons.httpclient.HttpMethodDirector.executeMethod(HttpMethodDirector.java(Compiled Code)) at org.apache.commons.httpclient.HttpClient.executeMethod(HttpClient.java(Compiled Code)) at org.apache.commons.httpclient.HttpClient.executeMethod(HttpClient.java(Inlined Compiled Code)) at com.eximtechnologies.httptransport.client.ClientTransport.receiveMessages(ClientTransport.java(Compiled Code)) at com.eximtechnologies.httptransport.client.ClientTransport.receiveMessages(ClientTransport.java(Inlined Compiled Code)) at com.eximtechnologies.ecserver.connection.XMSHTTPConnection.checkForNewMessages(XMSHTTPConnection.java(Compiled Code)) at com.eximtechnologies.ecserver.connection.XMSHTTPConnection.timeoutExpired(XMSHTTPConnection.java(Compiled Code)) at com.eximtechnologies.xmd.timer.TimerEvent$1.run(TimerEvent.java(Compiled Code)) </code></pre> <p>From the error, you would think this was just a network problem, but the client had never experienced the problem before about 2 months ago, and AFAIK, there haven't been any changes to the network layout.</p> <p>We also receive this fairly frequently:</p> <pre><code>java.net.SocketException: Connection timed out:could be due to invalid address at java.net.PlainSocketImpl.socketConnect(Native Method) at java.net.PlainSocketImpl.doConnect(PlainSocketImpl.java:336) at java.net.PlainSocketImpl.connectToAddress(PlainSocketImpl.java:201) at java.net.PlainSocketImpl.connect(PlainSocketImpl.java:188) at java.net.Socket.connect(Socket.java:478) at java.net.Socket.connect(Socket.java:428) at java.net.Socket.&lt;init&gt;(Socket.java:335) at java.net.Socket.&lt;init&gt;(Socket.java:210) at javax.net.ssl.SSLSocket.&lt;init&gt;(Unknown Source) </code></pre> <p>I'm suspecting that this is an AIX problem, but I guess it could be a firewall issue? I also saw some people in google searches hinting at a problem with commons http, but I couldn't see how that would be related.</p> <p>Is this something that others have seen with AIX recently?</p>
[ { "answer_id": 213916, "author": "Steve B.", "author_id": 19479, "author_profile": "https://Stackoverflow.com/users/19479", "pm_score": 0, "selected": false, "text": "<p>I have had issues with http client that were corrected by using a multithreaded connection. We fixed it by moving from the first to the second of the configurations below:</p>\n\n<pre><code>&lt;bean id=\"httpClient\" class=\"org.springframework.remoting.httpinvoker.CommonsHttpInvokerRequestExecutor\"&gt;\n &lt;property name=\"httpClient\"&gt;\n &lt;bean class=\"org.apache.commons.httpclient.HttpClient\"&gt;\n &lt;property name=\"connectionTimeout\"&gt;&lt;value&gt;1000&lt;/value&gt;&lt;/property&gt;\n &lt;property name=\"timeout\"&gt;&lt;value&gt;3000&lt;/value&gt;&lt;/property&gt;\n &lt;/bean&gt;\n &lt;/property&gt;\n&lt;/bean&gt;\n\n&lt;bean id=\"httpClient\" class=\"org.springframework.remoting.httpinvoker.CommonsHttpInvokerRequestExecutor\"&gt;\n &lt;property name=\"httpClient\"&gt;\n &lt;bean class=\"org.apache.commons.httpclient.HttpClient\"&gt;\n &lt;property name=\"connectionTimeout\"&gt;&lt;value&gt;1000&lt;/value&gt;&lt;/property&gt;\n &lt;property name=\"timeout\"&gt;&lt;value&gt;3000&lt;/value&gt;&lt;/property&gt;\n &lt;property name=\"httpConnectionManager\"&gt;\n &lt;bean class=\"org.apache.commons.httpclient.MultiThreadedHttpConnectionManager\" destroy-method=\"shutdown\"&gt;\n &lt;property name=\"params\"&gt;\n &lt;bean class=\"org.apache.commons.httpclient.params.HttpConnectionManagerParams\"&gt;\n &lt;property name=\"defaultMaxConnectionsPerHost\" value=\"20\" /&gt;\n &lt;/bean&gt;\n &lt;/property&gt;\n &lt;/bean&gt;\n &lt;/property&gt;\n &lt;/bean&gt;\n &lt;/property&gt;\n&lt;/bean&gt;\n</code></pre>\n" }, { "answer_id": 214102, "author": "Alexander", "author_id": 16724, "author_profile": "https://Stackoverflow.com/users/16724", "pm_score": 2, "selected": false, "text": "<p>\"java.net.SocketException: Socket closed\" means that your side closed the socket. You say that this happens when you attempt to make an SSL connection to your server. However, the stack trace suggests that this happens when HTTPClient attempts to write an HTTP request over an already established connection.</p>\n\n<p>This could happen if, for example, you somehow managed to make HTTPClient send a request via a connection that was previously closed by HTTPClient, or, more likely, by some other code on your side. Check whether you are accessing the underlying socket somewhere. Or it could be that the socket is closed by the SSL/TLS protocol (if I'm not mistaken, SSL/TLS has its own higher-level protocol for closing the underlying connection), but HTTPClient somehow managed to not notice this (don't know whether it's possible, but, say, the remote side closed the SSL connection but was using HTTP/1.1 persistent connections and didn't set a Connection: close response).</p>\n\n<p>You can troubleshoot these issues by analyzing the TCP traffic using tcpdump/Wireshark. You could also start an stunnel on a machine to the server's HTTPS port, then make your code communicate with the server over plain HTTP via this tunnel. This should enable you to see the HTTP traffic in plaintext.</p>\n\n<p>\"java.net.SocketException: Connection timed out\" means that the TCP connection could not be established due to a timeout. Could be that the packets are dropped by a firewall. For example, it could be that you need to use an HTTP proxy to make HTTPS requests. It could also be that the server machine is really busy or the network is really busy. Again, I suggest you try tcpdump/Wireshark to see what's going on at the TCP level.</p>\n" }, { "answer_id": 4790243, "author": "shivarajan", "author_id": 588539, "author_profile": "https://Stackoverflow.com/users/588539", "pm_score": 0, "selected": false, "text": "<p>I won't be surprised if it doesn't work!</p>\n\n<p>the specified timeout is the timeout for getting connection from the specified connection manager and not actual socket or server timeout which needs different set of settings.</p>\n" } ]
2008/10/17
[ "https://Stackoverflow.com/questions/213857", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1432/" ]
We have seen the following exceptions very frequently on IBM AIX when attempting to make an SSL connection to our server: ``` java.net.SocketException: Socket closed at com.sun.net.ssl.internal.ssl.SSLSocketImpl.a(DashoA6275(Compiled Code)) at com.sun.net.ssl.internal.ssl.AppOutputStream.write(DashoA6275(Compiled Code)) at java.io.BufferedOutputStream.flushBuffer(BufferedOutputStream.java(Inlined Compiled Code)) at java.io.BufferedOutputStream.flush(BufferedOutputStream.java(Compiled Code)) at java.io.FilterOutputStream.flush(FilterOutputStream.java(Compiled Code)) at org.apache.commons.httpclient.methods.EntityEnclosingMethod.writeRequestBody(EntityEnclosingMethod.java(Compiled Code)) at org.apache.commons.httpclient.HttpMethodBase.writeRequest(HttpMethodBase.java(Compiled Code)) at org.apache.commons.httpclient.HttpMethodBase.execute(HttpMethodBase.java(Compiled Code)) at org.apache.commons.httpclient.HttpMethodDirector.executeWithRetry(HttpMethodDirector.java(Compiled Code)) at org.apache.commons.httpclient.HttpMethodDirector.executeMethod(HttpMethodDirector.java(Compiled Code)) at org.apache.commons.httpclient.HttpClient.executeMethod(HttpClient.java(Compiled Code)) at org.apache.commons.httpclient.HttpClient.executeMethod(HttpClient.java(Inlined Compiled Code)) at com.eximtechnologies.httptransport.client.ClientTransport.receiveMessages(ClientTransport.java(Compiled Code)) at com.eximtechnologies.httptransport.client.ClientTransport.receiveMessages(ClientTransport.java(Inlined Compiled Code)) at com.eximtechnologies.ecserver.connection.XMSHTTPConnection.checkForNewMessages(XMSHTTPConnection.java(Compiled Code)) at com.eximtechnologies.ecserver.connection.XMSHTTPConnection.timeoutExpired(XMSHTTPConnection.java(Compiled Code)) at com.eximtechnologies.xmd.timer.TimerEvent$1.run(TimerEvent.java(Compiled Code)) ``` From the error, you would think this was just a network problem, but the client had never experienced the problem before about 2 months ago, and AFAIK, there haven't been any changes to the network layout. We also receive this fairly frequently: ``` java.net.SocketException: Connection timed out:could be due to invalid address at java.net.PlainSocketImpl.socketConnect(Native Method) at java.net.PlainSocketImpl.doConnect(PlainSocketImpl.java:336) at java.net.PlainSocketImpl.connectToAddress(PlainSocketImpl.java:201) at java.net.PlainSocketImpl.connect(PlainSocketImpl.java:188) at java.net.Socket.connect(Socket.java:478) at java.net.Socket.connect(Socket.java:428) at java.net.Socket.<init>(Socket.java:335) at java.net.Socket.<init>(Socket.java:210) at javax.net.ssl.SSLSocket.<init>(Unknown Source) ``` I'm suspecting that this is an AIX problem, but I guess it could be a firewall issue? I also saw some people in google searches hinting at a problem with commons http, but I couldn't see how that would be related. Is this something that others have seen with AIX recently?
"java.net.SocketException: Socket closed" means that your side closed the socket. You say that this happens when you attempt to make an SSL connection to your server. However, the stack trace suggests that this happens when HTTPClient attempts to write an HTTP request over an already established connection. This could happen if, for example, you somehow managed to make HTTPClient send a request via a connection that was previously closed by HTTPClient, or, more likely, by some other code on your side. Check whether you are accessing the underlying socket somewhere. Or it could be that the socket is closed by the SSL/TLS protocol (if I'm not mistaken, SSL/TLS has its own higher-level protocol for closing the underlying connection), but HTTPClient somehow managed to not notice this (don't know whether it's possible, but, say, the remote side closed the SSL connection but was using HTTP/1.1 persistent connections and didn't set a Connection: close response). You can troubleshoot these issues by analyzing the TCP traffic using tcpdump/Wireshark. You could also start an stunnel on a machine to the server's HTTPS port, then make your code communicate with the server over plain HTTP via this tunnel. This should enable you to see the HTTP traffic in plaintext. "java.net.SocketException: Connection timed out" means that the TCP connection could not be established due to a timeout. Could be that the packets are dropped by a firewall. For example, it could be that you need to use an HTTP proxy to make HTTPS requests. It could also be that the server machine is really busy or the network is really busy. Again, I suggest you try tcpdump/Wireshark to see what's going on at the TCP level.
213,875
<p>using the Symbian S60 5th edition SDK released on October 2nd, I am compiling/running(on sim) the following code snippet:</p> <pre><code>void test(wchar_t *dest, int size, const wchar_t *fmt, ...) { va_list vl; va_start(vl, fmt); vswprintf(dest, size, fmt, vl); va_end(vl); } ... wchar_t str[1024]; // this crashes (2nd string 123 characters (+ \0) equals 248 bytes) test(str, 1024, L"msg: %S", L"this is a test messagethis is a test messagethis is a test messagethis is a test messagethis is a test messagethis is a tes"); // this works (2nd string 122 characters (+ \0) equals 246 bytes) test(str, 1024, L"msg: %S", L"this is a test messagethis is a test messagethis is a test messagethis is a test messagethis is a test messagethis is a te"); </code></pre> <p>For no reason obvious to me (even after having read the <a href="http://www.forum.nokia.com/document/CDL_Extension_S60_3rd_Ed_FP2/GUID-719955DA-415B-420E-9F9B-F6DB37615EC5/html/wprintf.html" rel="nofollow noreferrer">vswprintf</a> man page a hundred times) can I figure out why this code is crashing on me in the vswprintf call for long strings :-( The exact same code works fine on a Linux box. There is sufficient memory allocated for str, plus vswprintf is checking for buffer overruns anyway. Unfortunately the ... S60 debugger does not break on this crash, so I have no details :-(</p> <p>Does anybody have any ideas? </p> <p>Assuming a bug in Symbian's vswprintf routine, what would be possible replacement functions using POSIX compliant code? (this is supposed to be a cross-platform library)</p> <p>Thanks.</p>
[ { "answer_id": 213955, "author": "gbjbaanb", "author_id": 13744, "author_profile": "https://Stackoverflow.com/users/13744", "pm_score": 0, "selected": false, "text": "<p>Change the %S to a %s - uppercase to lowercase.</p>\n\n<p>In MS-based printfs, %S means unicode characters, so this is why the 123 character string fails, it expects 2 bytes per character. (note %S is not part of the standard, so Symbian may be different here)</p>\n\n<p>Actually, I think that still applies to <a href=\"http://www.symbian.com/developer/techlib/v70sdocs/doc_source/reference/cpp/Descriptors/FormatStringSyntax.guide.html#Descriptors.Format-string-syntax\" rel=\"nofollow noreferrer\">Symbian</a>.</p>\n" }, { "answer_id": 213982, "author": "Michael Burr", "author_id": 12711, "author_profile": "https://Stackoverflow.com/users/12711", "pm_score": 1, "selected": false, "text": "<p>To me this looks like a job for stepping into the <code>vswprintf()</code> call. Even if you can only do assembly-level debugging, it should be clear what's more or less going on by keeping a watch on what's going into the the <code>str[]</code> memory.</p>\n" }, { "answer_id": 213999, "author": "Adam Rosenfield", "author_id": 9530, "author_profile": "https://Stackoverflow.com/users/9530", "pm_score": 0, "selected": false, "text": "<p>You could try changing the <code>%S</code> format specifier to <code>%ls</code>. As mentioned in my earlier comment, they're supposed to be equivalent, but there could be a bug in the implementation. Note that the <code>vswprintf</code> function is defined in the C99 standard, and since there are not yet any fully conforming C99 compilers (I believe), it's very possible that any given implementation of <code>vswprintf</code> does not fully conform to the spec, or that it contains bugs (the former is more likely than the latter).</p>\n" }, { "answer_id": 214225, "author": "Lou Franco", "author_id": 3937, "author_profile": "https://Stackoverflow.com/users/3937", "pm_score": 0, "selected": false, "text": "<p>Can you try not calling test() and using swprintf instead -- in case the bug has to do with VARARGS handling?</p>\n" }, { "answer_id": 216121, "author": "Steven", "author_id": 27101, "author_profile": "https://Stackoverflow.com/users/27101", "pm_score": 0, "selected": false, "text": "<p>I've now \"solved\" this problem by using Symbian functions to perform this task:</p>\n\n<pre><code>void test(wchar_t *dest, int size, const wchar_t *fmt, ...) {\n VA_LIST args;\n VA_START(args, fmt);\n\n TPtrC16 fmtPtr((const TUint16*)fmt, wcslen(fmt) + 1); \n TPtr16 targetPtr((TUint16*)dest, size);\n\n targetPtr.FormatList(fmtPtr, args);\n targetPtr.ZeroTerminate();\n\n VA_END(args);\n}\n</code></pre>\n\n<p>(in which case you actually have to <a href=\"http://www.symbian.com/Developer/techlib/v9.1docs/doc_source/guide/Base-subsystem-guide/N10086/BuffersAndStrings/Descriptors/DescriptorsGuide3/FormatStringSyntax.guide.html\" rel=\"nofollow noreferrer\">use %s</a>)</p>\n" }, { "answer_id": 3523746, "author": "Gerald Naveen", "author_id": 425469, "author_profile": "https://Stackoverflow.com/users/425469", "pm_score": 1, "selected": false, "text": "<p>I happened to find an internal buffer inside vswprintf's implementation to be hard-coded to 128 bytes. This could very well cause such a crash on long strings. </p>\n" } ]
2008/10/17
[ "https://Stackoverflow.com/questions/213875", "https://Stackoverflow.com", "https://Stackoverflow.com/users/27101/" ]
using the Symbian S60 5th edition SDK released on October 2nd, I am compiling/running(on sim) the following code snippet: ``` void test(wchar_t *dest, int size, const wchar_t *fmt, ...) { va_list vl; va_start(vl, fmt); vswprintf(dest, size, fmt, vl); va_end(vl); } ... wchar_t str[1024]; // this crashes (2nd string 123 characters (+ \0) equals 248 bytes) test(str, 1024, L"msg: %S", L"this is a test messagethis is a test messagethis is a test messagethis is a test messagethis is a test messagethis is a tes"); // this works (2nd string 122 characters (+ \0) equals 246 bytes) test(str, 1024, L"msg: %S", L"this is a test messagethis is a test messagethis is a test messagethis is a test messagethis is a test messagethis is a te"); ``` For no reason obvious to me (even after having read the [vswprintf](http://www.forum.nokia.com/document/CDL_Extension_S60_3rd_Ed_FP2/GUID-719955DA-415B-420E-9F9B-F6DB37615EC5/html/wprintf.html) man page a hundred times) can I figure out why this code is crashing on me in the vswprintf call for long strings :-( The exact same code works fine on a Linux box. There is sufficient memory allocated for str, plus vswprintf is checking for buffer overruns anyway. Unfortunately the ... S60 debugger does not break on this crash, so I have no details :-( Does anybody have any ideas? Assuming a bug in Symbian's vswprintf routine, what would be possible replacement functions using POSIX compliant code? (this is supposed to be a cross-platform library) Thanks.
To me this looks like a job for stepping into the `vswprintf()` call. Even if you can only do assembly-level debugging, it should be clear what's more or less going on by keeping a watch on what's going into the the `str[]` memory.
213,882
<p>So far, in my research I have seen that it is unwise to set AllowUnsafeUpdates on GET request operation to avoid cross site scripting. But, if it is required to allow this, what is the proper way to handle the situation to mitigate any exposure? </p> <p>Here is my best first guess on a reliable pattern if you absolutely need to allow web or site updates on a GET request.</p> <p>Best Practice?</p> <pre><code>protected override void OnLoad(System.EventArgs e) { if(Request.HttpMethod == "POST") { SPUtility.ValidateFormDigest(); // will automatically set AllowSafeUpdates to true } // If not a POST then AllowUnsafeUpdates should be used only // at the point of update and reset immediately after finished // NOTE: Is this true? How is cross-site scripting used on GET // and what mitigates the vulnerability? } // Point of item update using(SPSite site = new SPSite(SPContext.Current.Site.Url, SPContext.Current.Site.SystemAccount.UserToken)) { using (SPWeb web = site.RootWeb) { bool allowUpdates = web.AllowUnsafeUpdates; //store original value web.AllowUnsafeUpdates = true; //... Do something and call Update() ... web.AllowUnsafeUpdates = allowUpdates; //restore original value } } </code></pre> <p>Feedback on the best pattern is appreciated.</p>
[ { "answer_id": 220182, "author": "Nat", "author_id": 13813, "author_profile": "https://Stackoverflow.com/users/13813", "pm_score": 1, "selected": false, "text": "<p>Not so sure it is worth remembering the previous value of allow unsafe updates.</p>\n\n<p>I would want to wrap the call around the minimum possible amount of code, so that nested calls to it would not occur. </p>\n\n<p>Then you can just turn it to false afterwards.</p>\n" }, { "answer_id": 379625, "author": "Yuliy", "author_id": 47527, "author_profile": "https://Stackoverflow.com/users/47527", "pm_score": 3, "selected": false, "text": "<p>If you're performing any operations which modify something, then anyone that can convince the user to click on a link can perform that operation. For instance, let's assume that you have a GET request to a page which lets the user add an administrator to a site, and the user clicks a link to a page which does a Response.Redirect(\"<a href=\"http://yourserver/_layouts/admin.aspx?operation=addAdministrator&amp;username=attackerNameHere\" rel=\"nofollow noreferrer\">http://yourserver/_layouts/admin.aspx?operation=addAdministrator&amp;username=attackerNameHere</a>\").</p>\n\n<p>While normally a POST does not offer much protection against this (nothing will stop someone from having a &lt;form method=\"post\" action=\"http://yourserver/_layouts/admin.aspx\">), SharePoint has a concept of form digests, which contain information about the previous request that is generating the post back (including the user's name). This reduces the footprint for this kind of attack significantly.</p>\n\n<p>The only time that it is not a security issue to AllowUnsafeUpdates on a GET is if you're not taking input from the user. For instance, if you have a web part which also logs visits to a list, then there's no security vulnerability exposed.</p>\n\n<p><strong>Edit</strong>: If you are going to use AllowUnsafeUpdates, there's no need to reset it to its previous value. It does not get persisted. It's just something you need to set on an SPWeb object before performing updates from a GET (or other cases)</p>\n" }, { "answer_id": 432820, "author": "Øyvind Skaar", "author_id": 49194, "author_profile": "https://Stackoverflow.com/users/49194", "pm_score": 1, "selected": false, "text": "<p>I use a wrapper class for handling most manipulation of SPWeb objects. This helps me remember to close the web, and it eases the problems of unsafeupdates setting. It is a bit bloated, as I have patched on new constructors and members. but, then again; so is the SPWeb class.</p>\n\n<p>Usage:</p>\n\n<pre><code>using (WebWrapper wrapper = new WebWrapper(\"http://localhost\"))\n {\n wrapper.AllowUnsafeUpdates();\n\n //Do work on wrapper.\n }\n</code></pre>\n\n<p>The class definition:</p>\n\n<pre><code>using System;\nusing System.Collections.Specialized;\nusing System.Data;\nusing System.Diagnostics;\nusing System.Globalization;\nusing System.Runtime.Serialization;\nusing Microsoft.SharePoint;\nusing Microsoft.SharePoint.Administration;\n\nnamespace Skaar.SharePoint.Customization\n{\n /// &lt;summary&gt;\n /// A wrapper for a &lt;see cref=\"SPWeb\"/&gt; object.\n /// &lt;remarks&gt;Closes web object on Dispose if applicable.&lt;/remarks&gt;\n /// &lt;/summary&gt;\n [Serializable]\n [DebuggerDisplay(\"{Uri} Unsafe:{AllowUnsafeUpdatesSetting} Update:{UpdatePending}\")]\n public sealed class WebWrapper : IDisposable, IDeserializationCallback, IEquatable&lt;WebWrapper&gt;\n {\n [NonSerialized] private bool unsafeUpdatesSetting;\n\n [NonSerialized] private SPWeb web;\n\n /// &lt;summary&gt;\n /// Determines if the inner web object should be closed.\n /// &lt;/summary&gt;\n [NonSerialized] private bool webShouldBeClosed;\n\n /// &lt;summary&gt;\n /// This value is used in serialization to restore &lt;see cref=\"Web\"/&gt;.\n /// &lt;/summary&gt;\n private string webUrl;\n\n /// &lt;summary&gt;\n /// Creates a new wrapper object.\n /// &lt;/summary&gt;\n /// &lt;param name=\"web\"&gt;A web that should be closed/disposed when done.&lt;/param&gt;\n public WebWrapper(SPWeb web) : this(web, true)\n {\n }\n\n /// &lt;summary&gt;\n /// Creates a new wrapper object.\n /// &lt;/summary&gt;\n /// &lt;param name=\"web\"&gt;An inner web object&lt;/param&gt;\n /// &lt;param name=\"webShouldBeClosed\"&gt;If true, the web object is closed in the &lt;see cref=\"Dispose()\"/&gt; method.&lt;/param&gt;\n public WebWrapper(SPWeb web, bool webShouldBeClosed)\n {\n setWeb(web, webShouldBeClosed);\n }\n\n /// &lt;summary&gt;\n /// Creates a new wrapper object.\n /// &lt;/summary&gt;\n /// &lt;param name=\"webAddress\"&gt;The address to a web.&lt;/param&gt;\n public WebWrapper(Uri webAddress)\n {\n using (SPSite site = new SPSite(webAddress.ToString()))\n {\n string relativeUrl = renderWebRootRelativeUrl(webAddress);\n if (relativeUrl == null)\n {\n setWeb(site.OpenWeb(), true);\n }\n else\n {\n setWeb(site.OpenWeb(relativeUrl), true);\n }\n }\n }\n\n private string renderWebRootRelativeUrl(Uri address)\n {\n for (int i = 0; i &lt; address.Segments.Length; i++)\n {\n string segment = address.Segments[i];\n if (string.Equals(segment, \"_layouts/\"))\n {\n string newUrl=string.Join(null, address.Segments, 0, i).Trim('/');\n return newUrl;\n }\n }\n return null;\n }\n\n /// &lt;summary&gt;\n /// If true, &lt;see cref=\"SPWeb.Update\"/&gt; will be called in &lt;see cref=\"Dispose()\"/&gt;.\n /// &lt;/summary&gt;\n public bool UpdatePending { get; private set; }\n\n /// &lt;summary&gt;\n /// The setting of the inner web (&lt;see cref=\"SPWeb.AllowUnsafeUpdates\"/&gt;)\n /// &lt;/summary&gt;\n public bool AllowUnsafeUpdatesSetting\n {\n get { return Web.AllowUnsafeUpdates; }\n }\n\n /// &lt;summary&gt;\n /// The inner object.\n /// &lt;/summary&gt;\n /// &lt;exception cref=\"ObjectDisposedException\"&gt;Exception is thrown if &lt;see cref=\"IsDisposed\"/&gt; is true.&lt;/exception&gt;\n public SPWeb Web\n {\n get\n {\n if(IsDisposed)\n {\n throw new ObjectDisposedException(\"Web wrapper is disposed.\");\n }\n return web;\n }\n }\n\n /// &lt;summary&gt;\n /// The address of the &lt;see cref=\"Web\"/&gt; wrapped as a &lt;see cref=\"Uri\"/&gt; object.\n /// &lt;/summary&gt;\n public Uri Uri\n {\n get { return new Uri(Web.Url); }\n }\n\n /// &lt;summary&gt;\n /// The address of the &lt;see cref=\"Web\"/&gt; wrapped as a &lt;see cref=\"Uri\"/&gt; object.\n /// &lt;/summary&gt;\n public Uri GetUri(SPUrlZone zone)\n {\n return Site.WebApplication.GetResponseUri(zone, Uri.AbsolutePath);\n }\n\n /// &lt;summary&gt;\n /// Creates a wrapper around the context web.\n /// &lt;remarks&gt;The web will not be closed when wrapper is disposed. Returns null if context is unavailable.&lt;/remarks&gt;\n /// &lt;/summary&gt;\n public static WebWrapper Context\n {\n get\n {\n return SPContext.Current==null?null:new WebWrapper(SPContext.Current.Web, false);\n }\n }\n\n /// &lt;summary&gt;\n /// This is a static property wrapping of\n /// the &lt;see cref=\"CloneOf(SPWeb)\"/&gt; method, using\n /// the &lt;see cref=\"SPContext\"/&gt; current web as\n /// parameter.\n /// &lt;remarks&gt;Returns null if context is unavailable.&lt;/remarks&gt;\n /// &lt;/summary&gt;\n public static WebWrapper CloneOfContext\n {\n get\n {\n if (SPContext.Current != null)\n {\n SPWeb contextWeb = SPContext.Current.Web;\n return CloneOf(contextWeb);\n }\n return null;\n }\n }\n\n /// &lt;summary&gt;\n /// Returns the &lt;see cref=\"SPWeb.Exists\"/&gt; property of the &lt;see cref=\"Web\"/&gt; object.\n /// &lt;/summary&gt;\n public bool Exists\n {\n get { return Web != null &amp;&amp; Web.Exists; }\n }\n\n /// &lt;summary&gt;\n /// Gets the &lt;see cref=\"SPSite\"/&gt; object of &lt;see cref=\"Web\"/&gt;.\n /// &lt;/summary&gt;\n /// &lt;remarks&gt;This object should not be closed by user code.&lt;/remarks&gt;\n public SPSite Site\n {\n get { return web.Site; }\n }\n\n /// &lt;summary&gt;\n /// Gets the owner defined in &lt;see cref=\"SPSite.Owner\"/&gt;.\n /// &lt;/summary&gt;\n public SPUser Owner\n {\n get\n {\n return Site.Owner;\n }\n }\n\n /// &lt;summary&gt;\n /// Returns a context of the inner &lt;see cref=\"Web\"/&gt;.\n /// &lt;/summary&gt;\n public SPContext ContextOfWeb\n {\n get { return SPContext.GetContext(web); }\n }\n\n /// &lt;summary&gt;\n /// Gets the language of &lt;see cref=\"Web\"/&gt;.\n /// &lt;/summary&gt;\n public CultureInfo Locale\n {\n get { return Web.Locale; }\n }\n\n /// &lt;summary&gt;\n /// Gets the language of the root web.\n /// &lt;/summary&gt;\n public CultureInfo LocaleOfRoot\n {\n get\n {\n using (WebWrapper root = Root)\n {\n return root.Locale;\n }\n }\n }\n\n /// &lt;summary&gt;\n /// Returns a new &lt;see cref=\"WebWrapper\"/&gt; wrapping the root &lt;see cref=\"SPWeb\"/&gt; of this.\n /// &lt;/summary&gt;\n public WebWrapper Root\n {\n get\n {\n if (webShouldBeClosed)\n using (SPSite site = Site)\n {\n return new WebWrapper(site.RootWeb);\n }\n return new WebWrapper(Site.RootWeb);\n }\n }\n\n /// &lt;summary&gt;\n /// A wrapper for &lt;see cref=\"SPWeb.Title\"/&gt;.\n /// &lt;/summary&gt;\n public string Title\n {\n get { return Web.Title; }\n set { Web.Title = value; }\n }\n\n /// &lt;summary&gt;\n /// A wrapper for &lt;see cref=\"SPWeb.ID\"/&gt;.\n /// &lt;/summary&gt;\n public Guid ID\n {\n get { return Web.ID; }\n }\n\n #region Web Properties\n\n [NonSerialized] private bool updatePropertiesPending;\n\n /// &lt;summary&gt;\n /// A wrapper method to &lt;see cref=\"Web\"/&gt; object's &lt;see cref=\"SPWeb.Properties\"/&gt; indexer.\n /// &lt;/summary&gt;\n /// &lt;param name=\"key\"&gt;The key to use when fetching property value.&lt;/param&gt;\n /// &lt;returns&gt;A string containing the value.&lt;/returns&gt;\n public string GetProperty(string key)\n {\n return Web.Properties[key];\n }\n\n /// &lt;summary&gt;\n /// Sets the value in the &lt;see cref=\"Web\"/&gt; object's &lt;see cref=\"SPWeb.Properties\"/&gt;. Creates a new key, or updates an existing as needed.\n /// &lt;/summary&gt;\n /// &lt;param name=\"key\"&gt;The key to use when storing the property value.&lt;/param&gt;\n /// &lt;param name=\"value\"&gt;The value to set in the key.&lt;/param&gt;\n /// &lt;remarks&gt;The property &lt;see cref=\"UpdatePending\"/&gt; is set to true.&lt;/remarks&gt;\n public void SetProperty(string key, string value)\n {\n if (!Web.Properties.ContainsKey(key))\n {\n Web.Properties.Add(key, value);\n }\n else\n {\n Web.Properties[key] = value;\n }\n updatePropertiesPending = true;\n }\n\n #endregion\n\n #region IDeserializationCallback Members\n\n ///&lt;summary&gt;\n ///Runs when the entire object graph has been deserialized.\n ///&lt;/summary&gt;\n ///\n ///&lt;param name=\"sender\"&gt;The object that initiated the callback. The functionality for this parameter is not currently implemented. &lt;/param&gt;\n public void OnDeserialization(object sender)\n {\n using (SPSite site = new SPSite(webUrl))\n {\n setWeb(site.OpenWeb(), true);\n }\n }\n\n #endregion\n\n #region IDisposable Members\n\n ///&lt;summary&gt;\n ///Closes inner web object if appropriate.\n ///&lt;/summary&gt;\n ///&lt;filterpriority&gt;2&lt;/filterpriority&gt;\n public void Dispose()\n {\n Dispose(true);\n GC.SuppressFinalize(this);\n }\n\n public void Dispose(bool isDisposing)\n {\n if (IsDisposed) return;\n if (isDisposing)\n {\n doDisposeOfWeb();\n IsDisposed = true;\n }\n }\n\n #endregion\n\n /// &lt;summary&gt;\n /// Value is true if &lt;see cref=\"Dispose()\"/&gt; method has been called. Object is not in a usable state.\n /// &lt;/summary&gt;\n internal bool IsDisposed\n {\n get; private set;\n }\n\n #region IEquatable&lt;WebWrapper&gt; Members\n\n /// &lt;summary&gt;\n /// This tests whether the two objects wraps the same web. It may however be two different instances of the same web.\n /// &lt;/summary&gt;\n /// &lt;param name=\"other\"&gt;Another wrapper object.&lt;/param&gt;\n /// &lt;returns&gt;True if &lt;see cref=\"Uri\"/&gt; equals, false otherwise.&lt;/returns&gt;\n public bool Equals(WebWrapper other)\n {\n if (other == null)\n {\n return false;\n }\n return Uri.Equals(other.Uri);\n }\n\n #endregion\n\n /// &lt;summary&gt;\n /// Reopens the inner &lt;see cref=\"SPWeb\"/&gt; object. May be used when web object needs to be rereferenced in a new security context.\n /// &lt;/summary&gt;\n public void ReOpen()\n {\n bool unsafeSetting = AllowUnsafeUpdatesSetting;\n using (SPSite site = new SPSite(Web.Url))\n {\n SPWeb newWeb = site.OpenWeb();\n doDisposeOfWeb();\n web = newWeb;\n web.AllowUnsafeUpdates = unsafeSetting;\n unsafeUpdatesSetting = false;\n webShouldBeClosed = true;\n }\n }\n\n private void doDisposeOfWeb()\n {\n if (Web == null) return;\n Update(true);\n if (webShouldBeClosed)\n {\n Web.Close();\n }\n else if (Web.Exists)\n {\n Web.AllowUnsafeUpdates = unsafeUpdatesSetting;\n }\n web = null;\n }\n\n /// &lt;summary&gt;\n /// Calls &lt;see cref=\"SPWeb.Update\"/&gt; on the &lt;see cref=\"Web\"/&gt; object.\n /// &lt;/summary&gt;\n public void Update()\n {\n Update(false);\n }\n\n /// &lt;summary&gt;\n /// Sets &lt;see cref=\"UpdatePending\"/&gt; to &lt;c&gt;true&lt;/c&gt;.\n /// &lt;/summary&gt;\n public void SetUpdatePending()\n {\n UpdatePending = true;\n }\n\n /// &lt;summary&gt;\n /// Calls &lt;see cref=\"SPWeb.Update\"/&gt; on the &lt;see cref=\"Web\"/&gt; object.\n /// &lt;param name=\"onlyIfPending\"&gt;If true, update will depend on state of the &lt;see cref=\"UpdatePending\"/&gt; property.&lt;/param&gt;\n /// &lt;/summary&gt;\n public void Update(bool onlyIfPending)\n {\n if (onlyIfPending)\n {\n if (updatePropertiesPending)\n {\n Web.Properties.Update();\n updatePropertiesPending = false;\n }\n if (UpdatePending)\n {\n Web.Update();\n UpdatePending = false;\n }\n }\n else\n {\n Web.Update();\n UpdatePending = false;\n }\n }\n\n /// &lt;summary&gt;\n /// Returns the list from &lt;see cref=\"Web\"/&gt; with &lt;see cref=\"SPList.Title\"/&gt; equal to &lt;see cref=\"title\"/&gt;.\n /// &lt;/summary&gt;\n /// &lt;param name=\"title\"&gt;The &lt;see cref=\"SPList.Title\"/&gt; of an existing list.&lt;/param&gt;\n /// &lt;returns&gt;The first list found with the given title, or null, if no list is found.&lt;/returns&gt;\n public SPList GetList(string title)\n {\n foreach (SPList list in Web.Lists)\n {\n if (list.Title == title)\n {\n return list;\n }\n }\n return null;\n }\n /// &lt;summary&gt;\n /// A wrapper method to the &lt;see cref=\"Web\"/&gt; object's &lt;see cref=\"SPWeb.Lists\"/&gt; indexer. \n /// &lt;/summary&gt;\n /// &lt;param name=\"id\"&gt;The id of the list to return.&lt;/param&gt;\n /// &lt;returns&gt;The list with the supplied id.&lt;/returns&gt;\n public SPList GetList(Guid id)\n {\n return Web.Lists[id];\n }\n\n private void setWeb(SPWeb innerWeb, bool shouldBeClosed)\n {\n if (innerWeb == null || !innerWeb.Exists)\n {\n throw new ArgumentException(\"Web does not exist\", \"innerWeb\");\n }\n web = innerWeb;\n webShouldBeClosed = shouldBeClosed;\n unsafeUpdatesSetting = innerWeb.AllowUnsafeUpdates;\n AllowUnsafeUpdates();\n webUrl = web.Url;\n }\n\n /// &lt;summary&gt;\n /// Creates a new &lt;see cref=\"SPWeb\"/&gt; object using the\n /// url of the &lt;see cref=\"web\"/&gt; parameter and wraps it\n /// in a new wrapper object. The web will be\n /// closed when the wrapper is disposed.\n /// The cloning is done using the &lt;see cref=\"SPWeb.Url\"/&gt;, thus no security context is transferred to the new web.\n /// &lt;/summary&gt;\n /// &lt;remarks&gt;Use this to create a clone of the context web.&lt;/remarks&gt;\n /// &lt;param name=\"web\"&gt;The web to clone.&lt;/param&gt;\n /// &lt;returns&gt;A new wrapper object.&lt;/returns&gt;\n public static WebWrapper CloneOf(SPWeb web)\n {\n using (SPSite site = new SPSite(web.Url))\n {\n return new WebWrapper(site.OpenWeb());\n }\n }\n\n\n /// &lt;summary&gt;\n /// Creates a new &lt;see cref=\"SPWeb\"/&gt; object using the\n /// &lt;see cref=\"Web\"/&gt; of the &lt;see cref=\"web\"/&gt; parameter and wraps it\n /// in a new wrapper object. The web will be\n /// closed when the wrapper is disposed.\n /// &lt;/summary&gt;\n /// &lt;remarks&gt;Use this to create a clone of the context web.&lt;/remarks&gt;\n /// &lt;param name=\"web\"&gt;The wrapper to clone.&lt;/param&gt;\n /// &lt;returns&gt;A new wrapper object.&lt;/returns&gt;\n public static WebWrapper CloneOf(WebWrapper web)\n {\n return CloneOf(web.Web);\n }\n\n /// &lt;summary&gt;\n /// Sets the AllowUnsafeUpdates property to true on the\n /// wrapped web object.\n /// &lt;remarks&gt;\n /// The setting is resat back in the dispose method, unless the\n /// web itself is closed.\n /// &lt;/remarks&gt;\n /// &lt;/summary&gt;\n public void AllowUnsafeUpdates()\n {\n Web.AllowUnsafeUpdates = true;\n }\n\n /// &lt;summary&gt;\n /// Returns the url of the inner web.\n /// &lt;/summary&gt;\n /// &lt;returns&gt;A value that equals &lt;see cref=\"Web\"/&gt; &lt;see cref=\"SPWeb.Url\"/&gt; property.&lt;/returns&gt;\n public override string ToString()\n {\n return webUrl;\n }\n\n /// &lt;summary&gt;\n /// Returns a new &lt;see cref=\"WebWrapper\"/&gt; object wrapping a new copy of the inner &lt;see cref=\"Web\"/&gt; object.\n /// The cloning is done using the &lt;see cref=\"SPWeb.Url\"/&gt;, thus no security context is transferred to the new web.\n /// &lt;/summary&gt;\n /// &lt;remarks&gt;The static method &lt;see cref=\"CloneOf(SPWeb)\"/&gt; is used on the &lt;see cref=\"Web\"/&gt; property.&lt;/remarks&gt;\n /// &lt;returns&gt;A new wrapper.&lt;/returns&gt;\n public WebWrapper Clone()\n {\n return CloneOf(Web);\n }\n\n /// &lt;summary&gt;\n /// Implicitly wraps the web object in a &lt;see cref=\"WebWrapper\"/&gt; object.\n /// &lt;/summary&gt;\n /// &lt;param name=\"web\"&gt;The web to wrap.&lt;/param&gt;\n /// &lt;returns&gt;A new wrapper object. The original web may be accessed through the &lt;see cref=\"Web\"/&gt; property.&lt;/returns&gt;\n public static implicit operator WebWrapper(SPWeb web)\n {\n return new WebWrapper(web, false);\n }\n\n /// &lt;summary&gt;\n /// Explicitly extracts the &lt;see cref=\"Web\"/&gt; value from the &lt;see cref=\"wrapper\"/&gt;.\n /// &lt;/summary&gt;\n /// &lt;param name=\"wrapper\"&gt;The object wrapping the &lt;see cref=\"SPWeb\"/&gt; to extract.&lt;/param&gt;\n /// &lt;returns&gt;The inner &lt;see cref=\"Web\"/&gt; of &lt;see cref=\"wrapper\"/&gt;.&lt;/returns&gt;\n /// &lt;remarks&gt;The returned &lt;see cref=\"SPWeb\"/&gt; object should be properly disposed after use.&lt;/remarks&gt;\n public static explicit operator SPWeb(WebWrapper wrapper)\n {\n wrapper.DoNotDisposeInnerWeb();\n return wrapper.Web;\n }\n\n /// &lt;summary&gt;\n /// Wrapper method for &lt;see cref=\"SPWeb.GetList\"/&gt; on &lt;see cref=\"Web\"/&gt; object.\n /// &lt;/summary&gt;\n /// &lt;param name=\"uri\"&gt;A site relative uri to the list.&lt;/param&gt;\n /// &lt;returns&gt;A list if found.&lt;/returns&gt;\n public SPList GetList(Uri uri)\n {\n return web.GetList(uri.ToString());\n }\n\n /// &lt;summary&gt;\n /// Wrapper method for &lt;see cref=\"SPWeb.GetSiteData\"/&gt; on &lt;see cref=\"Web\"/&gt; object.\n /// &lt;/summary&gt;\n /// &lt;returns&gt;The results of the query,&lt;/returns&gt;\n public DataTable GetSiteData(SPSiteDataQuery query)\n {\n return Web.GetSiteData(query);\n }\n\n /// &lt;summary&gt;\n /// Creates a new &lt;see cref=\"SPWeb\"/&gt; as a sub web to this.\n /// &lt;/summary&gt;\n /// &lt;param name=\"url\"&gt;The proposed local url of the new web. The nearest available is selected.&lt;/param&gt;\n /// &lt;param name=\"name\"&gt;The title of the new web.&lt;/param&gt;\n /// &lt;param name=\"description\"&gt;The description of the new web.&lt;/param&gt;\n /// &lt;param name=\"language\"&gt;The language of the new web. &lt;remarks&gt;If the language is not supported, the language of this is used.&lt;/remarks&gt;&lt;/param&gt;\n /// &lt;param name=\"template\"&gt;The site template to use.&lt;/param&gt;\n /// &lt;returns&gt;The new web wrapped in a new &lt;see cref=\"WebWrapper\"/&gt; object.&lt;/returns&gt;\n [DebuggerStepThrough]\n //debugger step through is to prevent this method to break when debugging, as it throws exceptions by [poor] design.\n public WebWrapper CreateSubWeb(string url, string name, string description, uint language,\n string template)\n {\n SPWeb newWeb;\n try\n {\n newWeb = Web.Webs.Add(findSuitableWebUrl(url), name, description, language, template, true, false);\n }\n catch (SPException err)\n {\n if (err.ErrorCode == -2130575266)\n {\n //language not supported. Fallback to parent web language\n newWeb = Web.Webs.Add(findSuitableWebUrl(url), name, description, Web.Language, template, true,\n false);\n }\n else\n throw;\n }\n return new WebWrapper(newWeb);\n }\n\n private string findSuitableWebUrl(string proposedName)\n {\n StringCollection names = new StringCollection();\n names.AddRange(Web.Webs.Names);\n int suffixIndex = 0;\n const int maxIterations = 100000;\n string name = proposedName;\n while (names.Contains(name) &amp;&amp; suffixIndex &lt; maxIterations)\n {\n name = string.Format(\"{0}_{1}\", proposedName, suffixIndex++);\n }\n return name;\n }\n\n /// &lt;summary&gt;\n /// Calling this method will inhibit the default behaviour of closing the web on disposal.\n /// &lt;/summary&gt;\n /// &lt;remarks&gt;Use with caution.&lt;/remarks&gt;\n internal void DoNotDisposeInnerWeb()\n {\n webShouldBeClosed = false;\n }\n\n }\n}\n</code></pre>\n" }, { "answer_id": 436123, "author": "Trent", "author_id": 35329, "author_profile": "https://Stackoverflow.com/users/35329", "pm_score": 2, "selected": false, "text": "<p>Another clean way to implement would be to use a combination of extension methods and anonymous delegates as such:</p>\n\n<pre><code>public static void DoUnsafeUpdate(this SPWeb web, Action action)\n{\n bool allowUnsafeUpdates = web.AllowUnsafeUpdates;\n web.AllowUnsafeUpdates = true;\n action();\n web.AllowUnsafeUpdates = allowUnsafeUpdates;\n}\n</code></pre>\n\n<p>Using the above extension method, you can then perform your \"unsafe update\" action as follows:</p>\n\n<pre><code>var web = SPContext.Current.Web;\nweb.DoUnsafeUpdate(delegate()\n{\n // Put your \"unsafe update\" code here\n});\n</code></pre>\n" }, { "answer_id": 436509, "author": "dahlbyk", "author_id": 54249, "author_profile": "https://Stackoverflow.com/users/54249", "pm_score": 3, "selected": false, "text": "<p>I would slightly modify Trent's delegate to accept the web to update:</p>\n\n<pre><code>public static void DoUnsafeUpdate(this SPWeb web, Action&lt;SPWeb&gt; action)\n{\n try\n {\n web.AllowUnsafeUpdates = true;\n action(web);\n }\n finally\n {\n web.AllowUnsafeUpdates = false;\n }\n}\n</code></pre>\n\n<p>And then extend HttpContext to encapsulate verification of the form digest, with an option to elevate using the <a href=\"http://solutionizing.net/2009/01/06/elegant-spsite-elevation/\" rel=\"noreferrer\">technique described here</a>:</p>\n\n<pre><code>public static void DoUnsafeUpdate(this HttpContext context, Action&lt;SPWeb&gt; action, bool elevated)\n{\n SPWeb web = SPControl.GetContextWeb(context);\n if (!context.Request.HttpMethod.Equals(\"POST\", StringComparison.Ordinal)\n || web.ValidateFormDigest())\n throw new SPException(\"Error validating postback digest\");\n\n if (elevated)\n web.RunAsSystem(w =&gt; w.DoUnsafeUpdate(action));\n else\n web.DoUnsafeUpdate(action);\n}\n</code></pre>\n\n<p>Usage:</p>\n\n<pre><code>protected override void OnLoad(System.EventArgs e)\n{\n Context.DoUnsafeUpdate(web =&gt;\n {\n // Update elevated web\n }, true);\n}\n</code></pre>\n" }, { "answer_id": 1052174, "author": "Ariel", "author_id": 118464, "author_profile": "https://Stackoverflow.com/users/118464", "pm_score": 2, "selected": false, "text": "<p>For AllowUnsafeUpdates, I follow this process:</p>\n\n<pre><code>if( HttpContext.Current is null )\n{\n Do nothing, no need to set AllowUnsafeUpdates to true nor\n to call ValidateFormDigest() because update will be carried out\n}\nelse // HttpContext.Current is NOT null\n{\n if( SPContext.Current is null )\n {\n Need to set AllowUnsafeUpdates to true\n }\n else // SPContext.Current is NOT null\n {\n Call ValidateFormDigest()\n }\n}\n</code></pre>\n" } ]
2008/10/17
[ "https://Stackoverflow.com/questions/213882", "https://Stackoverflow.com", "https://Stackoverflow.com/users/13135/" ]
So far, in my research I have seen that it is unwise to set AllowUnsafeUpdates on GET request operation to avoid cross site scripting. But, if it is required to allow this, what is the proper way to handle the situation to mitigate any exposure? Here is my best first guess on a reliable pattern if you absolutely need to allow web or site updates on a GET request. Best Practice? ``` protected override void OnLoad(System.EventArgs e) { if(Request.HttpMethod == "POST") { SPUtility.ValidateFormDigest(); // will automatically set AllowSafeUpdates to true } // If not a POST then AllowUnsafeUpdates should be used only // at the point of update and reset immediately after finished // NOTE: Is this true? How is cross-site scripting used on GET // and what mitigates the vulnerability? } // Point of item update using(SPSite site = new SPSite(SPContext.Current.Site.Url, SPContext.Current.Site.SystemAccount.UserToken)) { using (SPWeb web = site.RootWeb) { bool allowUpdates = web.AllowUnsafeUpdates; //store original value web.AllowUnsafeUpdates = true; //... Do something and call Update() ... web.AllowUnsafeUpdates = allowUpdates; //restore original value } } ``` Feedback on the best pattern is appreciated.
If you're performing any operations which modify something, then anyone that can convince the user to click on a link can perform that operation. For instance, let's assume that you have a GET request to a page which lets the user add an administrator to a site, and the user clicks a link to a page which does a Response.Redirect("<http://yourserver/_layouts/admin.aspx?operation=addAdministrator&username=attackerNameHere>"). While normally a POST does not offer much protection against this (nothing will stop someone from having a <form method="post" action="http://yourserver/\_layouts/admin.aspx">), SharePoint has a concept of form digests, which contain information about the previous request that is generating the post back (including the user's name). This reduces the footprint for this kind of attack significantly. The only time that it is not a security issue to AllowUnsafeUpdates on a GET is if you're not taking input from the user. For instance, if you have a web part which also logs visits to a list, then there's no security vulnerability exposed. **Edit**: If you are going to use AllowUnsafeUpdates, there's no need to reset it to its previous value. It does not get persisted. It's just something you need to set on an SPWeb object before performing updates from a GET (or other cases)
213,901
<p>I'd like to run a subcommand from Perl (or pipe it into a Perl script) and have the script process the command's output immediately, rather than waiting for a timeout, a newline, or a certain number of blocks. For example, let's say I want to surround each chunk of input with square brackets. When I run the script like this:</p> <pre><code>$ ( echo -n foo ; sleep 5 ; echo -n bar ; sleep 5; echo baz) | my_script.pl </code></pre> <p>I'd like the output to be this, with each line appearing five seconds after the previous one:</p> <pre><code>[foo] [bar] [baz] </code></pre> <p>How do I do that?</p> <p>This works, but is really ugly:</p> <pre><code>#! /usr/bin/perl -w use strict; use Fcntl; my $flags = ''; fcntl(STDIN, F_GETFL, $flags); $flags |= O_NONBLOCK; fcntl(STDIN, F_SETFL, $flags); my $rin = ''; vec($rin,fileno(STDIN),1) = 1; my $rout; while (1) { select($rout=$rin, undef, undef, undef); last if eof(); my $buffer = ''; while (my $c = getc()) { $buffer .= $c; } print "[$buffer]\n"; } </code></pre> <p>Is there a more elegant way to do it?</p>
[ { "answer_id": 213923, "author": "Greg Hewgill", "author_id": 893, "author_profile": "https://Stackoverflow.com/users/893", "pm_score": 0, "selected": false, "text": "<p>You didn't mention how you are reading input in your Perl script, but you might want to look at the <a href=\"http://perldoc.perl.org/functions/getc.html\" rel=\"nofollow noreferrer\"><code>getc</code></a> function:</p>\n\n<pre><code>$|++; # set autoflush on output\nwhile ($c = getc(STDIN)) {\n print $c;\n}\n</code></pre>\n" }, { "answer_id": 213929, "author": "Kyle", "author_id": 2237619, "author_profile": "https://Stackoverflow.com/users/2237619", "pm_score": 0, "selected": false, "text": "<p><p>See <a href=\"http://perlmonks.org/?node_id=300044\" rel=\"nofollow noreferrer\">How to change Open2 input buffering</a>. (Basically, you have to make the other program think it's talking to a tty.)</p>\n" }, { "answer_id": 213951, "author": "Adam Davis", "author_id": 2915, "author_profile": "https://Stackoverflow.com/users/2915", "pm_score": 1, "selected": false, "text": "<p>If there's time inbetween each character, you might be able to detect the pauses.</p>\n\n<p>Perl also does line input - if you don't use getc you should be able to add newlines to the end of foo, bar, etc and perl will give you each line.</p>\n\n<p>If you can't add newlines, and you can't depend on a pause, then what exactly do you expect the system to do to tell perl that it's started a new command? As far as perl is concerned, there's a stdin pipe, it's eating data from it, and there's nothing in the stdin pipe to tell you when you are executing a new command.</p>\n\n<p>You might consider the following instead:</p>\n\n<pre><code>$ echo \"( echo -n foo ; sleep 5 ; echo -n bar ; sleep 5; echo baz)\" | my_script.pl\n</code></pre>\n\n<p>or </p>\n\n<pre><code>$ my_script.pl$ \"echo -n foo ; sleep 5 ; echo -n bar ; sleep 5; echo baz\"\n</code></pre>\n\n<p>And modify your perl program to parse the input \"command line\" and execute each task, eating the stdout as needed.</p>\n\n<p>-Adam</p>\n" }, { "answer_id": 214005, "author": "brian d foy", "author_id": 2766176, "author_profile": "https://Stackoverflow.com/users/2766176", "pm_score": 3, "selected": false, "text": "<p>From perlfaq5: <a href=\"http://perldoc.perl.org/perlfaq5.html#How-can-I-read-a-single-character-from-a-file%3f--From-the-keyboard%3f\" rel=\"nofollow noreferrer\">How can I read a single character from a file? From the keyboard?</a>. You probably also want to read <a href=\"http://perldoc.perl.org/perlfaq5.html#How-can-I-tell-whether-there&#39;s-a-character-waiting-on-a-filehandle%3f\" rel=\"nofollow noreferrer\">How can I tell whether there's a character waiting on a filehandle?</a>. Poll the filehandle. If there is a character there, read it and reset a timer. If there is not character there, try again. If you've retried and passed a certain time, process the input.</p>\n\n<p>After you read the characters, it's up to you to decide what to do with them. With all the flexibility of reading single characters comes the extra work of handling them.</p>\n" }, { "answer_id": 215604, "author": "Schwern", "author_id": 14660, "author_profile": "https://Stackoverflow.com/users/14660", "pm_score": 2, "selected": false, "text": "<p><a href=\"http://search.cpan.org/perldoc?Term::ReadKey\" rel=\"nofollow noreferrer\">Term::ReadKey</a> can do this for you. In particular setting the ReadKey() mode to do the polling for you.</p>\n\n<pre><code>use Term::ReadKey;\n\n$| = 1;\nwhile( my $key = ReadKey(10) ) {\n print $key;\n}\n</code></pre>\n" } ]
2008/10/17
[ "https://Stackoverflow.com/questions/213901", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7598/" ]
I'd like to run a subcommand from Perl (or pipe it into a Perl script) and have the script process the command's output immediately, rather than waiting for a timeout, a newline, or a certain number of blocks. For example, let's say I want to surround each chunk of input with square brackets. When I run the script like this: ``` $ ( echo -n foo ; sleep 5 ; echo -n bar ; sleep 5; echo baz) | my_script.pl ``` I'd like the output to be this, with each line appearing five seconds after the previous one: ``` [foo] [bar] [baz] ``` How do I do that? This works, but is really ugly: ``` #! /usr/bin/perl -w use strict; use Fcntl; my $flags = ''; fcntl(STDIN, F_GETFL, $flags); $flags |= O_NONBLOCK; fcntl(STDIN, F_SETFL, $flags); my $rin = ''; vec($rin,fileno(STDIN),1) = 1; my $rout; while (1) { select($rout=$rin, undef, undef, undef); last if eof(); my $buffer = ''; while (my $c = getc()) { $buffer .= $c; } print "[$buffer]\n"; } ``` Is there a more elegant way to do it?
From perlfaq5: [How can I read a single character from a file? From the keyboard?](http://perldoc.perl.org/perlfaq5.html#How-can-I-read-a-single-character-from-a-file%3f--From-the-keyboard%3f). You probably also want to read [How can I tell whether there's a character waiting on a filehandle?](http://perldoc.perl.org/perlfaq5.html#How-can-I-tell-whether-there's-a-character-waiting-on-a-filehandle%3f). Poll the filehandle. If there is a character there, read it and reset a timer. If there is not character there, try again. If you've retried and passed a certain time, process the input. After you read the characters, it's up to you to decide what to do with them. With all the flexibility of reading single characters comes the extra work of handling them.
213,907
<p>Many C++ books contain example code like this...</p> <pre><code>std::cout &lt;&lt; "Test line" &lt;&lt; std::endl; </code></pre> <p>...so I've always done that too. But I've seen a lot of code from working developers like this instead:</p> <pre><code>std::cout &lt;&lt; "Test line\n"; </code></pre> <p>Is there a technical reason to prefer one over the other, or is it just a matter of coding style?</p>
[ { "answer_id": 213914, "author": "Martin Beckett", "author_id": 10897, "author_profile": "https://Stackoverflow.com/users/10897", "pm_score": 6, "selected": false, "text": "<p>There might be performance issues, <code>std::endl</code> forces a flush of the output stream.</p>\n" }, { "answer_id": 213926, "author": "Ferruccio", "author_id": 4086, "author_profile": "https://Stackoverflow.com/users/4086", "pm_score": 5, "selected": false, "text": "<p>They will both write the appropriate end-of-line character(s). In addition to that endl will cause the buffer to be committed. You usually don't want to use endl when doing file I/O because the unnecessary commits can impact performance.</p>\n" }, { "answer_id": 213977, "author": "David Thornley", "author_id": 14148, "author_profile": "https://Stackoverflow.com/users/14148", "pm_score": 10, "selected": true, "text": "<p>The varying line-ending characters don't matter, assuming the file is open in text mode, which is what you get unless you ask for binary. The compiled program will write out the correct thing for the system compiled for.</p>\n\n<p>The only difference is that <a href=\"http://en.cppreference.com/w/cpp/io/manip/endl\" rel=\"noreferrer\"><code>std::endl</code></a> flushes the output buffer, and <code>'\\n'</code> doesn't. If you don't want the buffer flushed frequently, use <code>'\\n'</code>. If you do (for example, if you want to get all the output, and the program is unstable), use <code>std::endl</code>.</p>\n" }, { "answer_id": 214076, "author": "Martin York", "author_id": 14065, "author_profile": "https://Stackoverflow.com/users/14065", "pm_score": 8, "selected": false, "text": "<p>The difference can be illustrated by the following:</p>\n\n<pre><code>std::cout &lt;&lt; std::endl;\n</code></pre>\n\n<p>is equivalent to</p>\n\n<pre><code>std::cout &lt;&lt; '\\n' &lt;&lt; std::flush;\n</code></pre>\n\n<p>So,</p>\n\n<ul>\n<li>Use <code>std::endl</code> If you want to force an immediate flush to the output.</li>\n<li>Use <code>\\n</code> if you are worried about performance (which is probably not the case if you are using the <code>&lt;&lt;</code> operator).</li>\n</ul>\n\n<p>I use <code>\\n</code> on most lines.<br>\nThen use <code>std::endl</code> at the end of a paragraph (but that is just a habit and not usually necessary).</p>\n\n<p>Contrary to other claims, the <code>\\n</code> character is mapped to the correct platform end of line sequence only if the stream is going to a file (<code>std::cin</code> and <code>std::cout</code> being special but still files (or file-like)).</p>\n" }, { "answer_id": 574153, "author": "Özgür", "author_id": 12652, "author_profile": "https://Stackoverflow.com/users/12652", "pm_score": 4, "selected": false, "text": "<p>Not a big deal, but <a href=\"http://www.crystalclearsoftware.com/cgi-bin/boost_wiki/wiki.pl?Suggestions_-_Lambda_Library\" rel=\"noreferrer\">endl won't work</a> in <a href=\"http://www.boost.org/doc/html/lambda.html\" rel=\"noreferrer\">boost::lambda</a>.</p>\n\n<pre><code>(cout&lt;&lt;_1&lt;&lt;endl)(3); //error\n\n(cout&lt;&lt;_1&lt;&lt;\"\\n\")(3); //OK , prints 3\n</code></pre>\n" }, { "answer_id": 1752330, "author": "Nathan", "author_id": 213325, "author_profile": "https://Stackoverflow.com/users/213325", "pm_score": 5, "selected": false, "text": "<p>There's another function call implied in there if you're going to use <code>std::endl</code></p>\n\n<pre><code>a) std::cout &lt;&lt; \"Hello\\n\";\nb) std::cout &lt;&lt; \"Hello\" &lt;&lt; std::endl;\n</code></pre>\n\n<p>a) calls operator <code>&lt;&lt;</code> once. <br>\nb) calls operator <code>&lt;&lt;</code> twice.</p>\n" }, { "answer_id": 2277698, "author": "smerlin", "author_id": 231717, "author_profile": "https://Stackoverflow.com/users/231717", "pm_score": 4, "selected": false, "text": "<p>If you use Qt and <code>endl</code>, you could accidentally end up using an incorrect <code>endl</code> which gives you very surprising results. See the following code snippet:</p>\n\n<pre><code>#include &lt;iostream&gt;\n#include &lt;QtCore/QtCore&gt; \n#include &lt;QtGui/QtGui&gt;\n\n// notice that there is no \"using namespace std;\"\nint main(int argc, char** argv)\n{\n QApplication qapp(argc,argv);\n QMainWindow mw;\n mw.show();\n std::cout &lt;&lt; \"Finished Execution!\" &lt;&lt; endl;\n // This prints something similar to: \"Finished Execution!67006AB4\"\n return qapp.exec();\n}\n</code></pre>\n\n<p>Note that I wrote <code>endl</code> instead of <code>std::endl</code> (which would have been correct) and apparently there is a <code>endl</code> function defined in <em>qtextstream.h</em> (which is part of QtCore).</p>\n\n<p>Using <code>\"\\n\"</code> instead of <code>endl</code> completely sidesteps any potential namespace issues.\nThis is also a good example why putting symbols into the global namespace (like Qt does by default) is a bad idea.</p>\n" }, { "answer_id": 25569849, "author": "Emily L.", "author_id": 2498188, "author_profile": "https://Stackoverflow.com/users/2498188", "pm_score": 5, "selected": false, "text": "<p>I recalled reading about this in the standard, so here goes:</p>\n\n<p>See C11 standard which defines how the standard streams behave, as C++ programs interface the CRT, the C11 standard should govern the flushing policy here.</p>\n\n<blockquote>\n <p>ISO/IEC 9899:201x</p>\n \n <p>7.21.3 §7</p>\n \n <p>At program startup, three text streams are predefined and need not be opened explicitly\n — standard input (for reading conventional input), standard output (for writing\n conventional output), and standard error (for writing diagnostic output). As initially\n opened, the standard error stream is not fully buffered; the standard input and standard\n output streams are fully buffered if and only if the stream can be determined not to refer\n to an interactive device.</p>\n \n <p>7.21.3 §3</p>\n \n <p>When a stream is unbuffered, characters are intended to appear from the source or at the\n destination as soon as possible. Otherwise characters may be accumulated and\n transmitted to or from the host environment as a block. When a stream is fully buffered,\n characters are intended to be transmitted to or from the host environment as a block when\n a buffer is filled. When a stream is line buffered, characters are intended to be\n transmitted to or from the host environment as a block when a new-line character is\n encountered. Furthermore, characters are intended to be transmitted as a block to the host\n environment when a buffer is filled, when input is requested on an unbuffered stream, or\n when input is requested on a line buffered stream that requires the transmission of\n characters from the host environment. Support for these characteristics is\n implementation-defined, and may be affected via the setbuf and setvbuf functions.</p>\n</blockquote>\n\n<p>This means that <code>std::cout</code> and <code>std::cin</code> are fully buffered <strong>if and only if</strong> they are referring to a non-interactive device. In other words, if stdout is attached to a terminal then there is no difference in behavior. </p>\n\n<p>However, if <code>std::cout.sync_with_stdio(false)</code> is called, then <code>'\\n'</code> will not cause a flush even to interactive devices. Otherwise <code>'\\n'</code> is equivalent to <code>std::endl</code> unless piping to files: <a href=\"http://en.cppreference.com/w/cpp/io/manip/endl\">c++ ref on std::endl</a>.</p>\n" }, { "answer_id": 49512278, "author": "Kaleem Ullah", "author_id": 2046817, "author_profile": "https://Stackoverflow.com/users/2046817", "pm_score": 2, "selected": false, "text": "<p>With <a href=\"http://en.cppreference.com/w/cpp/io/manip/endl\" rel=\"nofollow noreferrer\">reference</a> This is an <strong>output-only I/O manipulator</strong>.</p>\n\n<p><strong><code>std::endl</code></strong> Inserts a newline character into the output sequence os and flushes it as if by calling <code>os.put(os.widen('\\n'))</code> followed by <code>os.flush()</code>. </p>\n\n<p><strong>When to use:</strong></p>\n\n<p>This manipulator may be used to produce a line of <strong>output immediately</strong>, </p>\n\n<p><strong>e.g.</strong> </p>\n\n<blockquote>\n <p>when displaying output from a long-running process, logging activity of multiple threads or logging activity of a program that may crash unexpectedly. </p>\n</blockquote>\n\n<p><strong>Also</strong></p>\n\n<blockquote>\n <p>An explicit flush of std::cout is also necessary before a call to std::system, if the spawned process performs any screen I/O. In most other usual interactive I/O scenarios, std::endl is redundant when used with std::cout because any input from std::cin, output to std::cerr, or program termination forces a call to std::cout.flush(). Use of std::endl in place of '\\n', encouraged by some sources, may significantly degrade output performance. </p>\n</blockquote>\n" }, { "answer_id": 68692492, "author": "TheHardew", "author_id": 3982062, "author_profile": "https://Stackoverflow.com/users/3982062", "pm_score": 3, "selected": false, "text": "<p>Something that I've never seen anyone say is that <code>'\\n'</code> is affected by cout formatting:</p>\n<pre><code>#include &lt;iostream&gt;\n#include &lt;iomanip&gt;\n\nint main() {\n std::cout &lt;&lt; &quot;\\\\n:\\n&quot; &lt;&lt; std::setw(2) &lt;&lt; std::setfill('0') &lt;&lt; '\\n';\n std::cout &lt;&lt; &quot;std::endl:\\n&quot; &lt;&lt; std::setw(2) &lt;&lt; std::setfill('0') &lt;&lt; std::endl;\n}\n</code></pre>\n<p>Output:</p>\n<pre><code>\\n:\n0\nstd::endl:\n\n</code></pre>\n<p>Notice, how since <code>'\\n'</code> is one character and fill width is set to 2, only 1 zero gets printed before <code>'\\n'</code>.</p>\n<p>I can't find anything about it anywhere, but it reproduces with clang, gcc and msvc.</p>\n<p>I was super confused when I first saw it.</p>\n" } ]
2008/10/17
[ "https://Stackoverflow.com/questions/213907", "https://Stackoverflow.com", "https://Stackoverflow.com/users/12193/" ]
Many C++ books contain example code like this... ``` std::cout << "Test line" << std::endl; ``` ...so I've always done that too. But I've seen a lot of code from working developers like this instead: ``` std::cout << "Test line\n"; ``` Is there a technical reason to prefer one over the other, or is it just a matter of coding style?
The varying line-ending characters don't matter, assuming the file is open in text mode, which is what you get unless you ask for binary. The compiled program will write out the correct thing for the system compiled for. The only difference is that [`std::endl`](http://en.cppreference.com/w/cpp/io/manip/endl) flushes the output buffer, and `'\n'` doesn't. If you don't want the buffer flushed frequently, use `'\n'`. If you do (for example, if you want to get all the output, and the program is unstable), use `std::endl`.
213,912
<p>Why are inline closures so rarely used in Actionscript? They are very powerful and I think quite readable. I hardly ever see anyone using them so maybe I'm just looking at the wrong code. Google uses them in their Google Maps API for Flash samples, but I think thats the only place I've seen them.</p> <p>I favor them because you have access to local variables in the scope that defines them and you keep the logic in one method and dont end up with lots of functions for which you have to come up with a name.</p> <p>Are there any catches of using them? Do they work pretty much the same way as in C#.</p> <p>I actually only just discovered that AS3 supports them, and I'm quite annoyed becasue I had thought I read that they were deprecated in AS#. So I'm back to using them!</p> <pre><code>private function showPanel(index:int):void { _timer = new Timer(1000, 1); _timer.addEventListener(TimerEvent.TIMER, function(event:Event):void { // show the next panel showPanel(index++); }); </code></pre>
[ { "answer_id": 213928, "author": "Mitch Haile", "author_id": 28807, "author_profile": "https://Stackoverflow.com/users/28807", "pm_score": 3, "selected": true, "text": "<p>The biggest gotcha to watch out for is that often 'this' is not defined in the inline closure. Sometimes you can set a 'this', but it's not always the right 'this' that you would have available to set, depending on how you're using them.</p>\n\n<p>But I'd say most of the Flex code I've worked on has had inline closures rampantly throughout the code--since callbacks are the only way to get work done, and often you don't need the bring out a whole separate function.</p>\n\n<p>Sometimes when the function nested is getting to be too much, I'll break it out slightly with Function variables in the function; this helps me organize a bit by giving labels to the functions but keeping some of the characteristics of inline closures (access to the local variables, for example).</p>\n\n<p>Hope this helps.</p>\n" }, { "answer_id": 213946, "author": "Simon", "author_id": 24727, "author_profile": "https://Stackoverflow.com/users/24727", "pm_score": 1, "selected": false, "text": "<p>I found what originally made me NOT want to do this, but I had forgotten the details:</p>\n\n<p><a href=\"http://livedocs.adobe.com/flex/3/html/16_Event_handling_6.html#119539\" rel=\"nofollow noreferrer\">http://livedocs.adobe.com/flex/3/html/16_Event_handling_6.html#119539</a></p>\n\n<p>(This is what Mitch mentioned - as far as the 'this' keyword being out of scope)</p>\n\n<p>So thats Adobe's answer, however I am much more likely to need to refer to local variables than 'this'.</p>\n\n<p>How do others interpret Adobe's recommendation ?</p>\n" }, { "answer_id": 241596, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 2, "selected": false, "text": "<p>One additional problem is that garbage collection is broken when it comes to closures (at least in Flash 9). The first instance of a given closure (from a lexical standpoint) will never be garbage collected - along with anything else referenced by the closure in the scope chain.</p>\n" } ]
2008/10/17
[ "https://Stackoverflow.com/questions/213912", "https://Stackoverflow.com", "https://Stackoverflow.com/users/24727/" ]
Why are inline closures so rarely used in Actionscript? They are very powerful and I think quite readable. I hardly ever see anyone using them so maybe I'm just looking at the wrong code. Google uses them in their Google Maps API for Flash samples, but I think thats the only place I've seen them. I favor them because you have access to local variables in the scope that defines them and you keep the logic in one method and dont end up with lots of functions for which you have to come up with a name. Are there any catches of using them? Do they work pretty much the same way as in C#. I actually only just discovered that AS3 supports them, and I'm quite annoyed becasue I had thought I read that they were deprecated in AS#. So I'm back to using them! ``` private function showPanel(index:int):void { _timer = new Timer(1000, 1); _timer.addEventListener(TimerEvent.TIMER, function(event:Event):void { // show the next panel showPanel(index++); }); ```
The biggest gotcha to watch out for is that often 'this' is not defined in the inline closure. Sometimes you can set a 'this', but it's not always the right 'this' that you would have available to set, depending on how you're using them. But I'd say most of the Flex code I've worked on has had inline closures rampantly throughout the code--since callbacks are the only way to get work done, and often you don't need the bring out a whole separate function. Sometimes when the function nested is getting to be too much, I'll break it out slightly with Function variables in the function; this helps me organize a bit by giving labels to the functions but keeping some of the characteristics of inline closures (access to the local variables, for example). Hope this helps.
213,939
<p>Does anyone know how to initiate a POST request in a Grails applications using javascript. Specifically, I would like to be able to POST when a the selected item in a drop-down box is changed.</p> <p>I've tried using jQuery and the $.post() method. It successfully calls my controller action, but I'm not sure how to get the page to refresh with the response contents. The screen is not updated. Any ideas? This does not need to be asynchronous.</p> <p>I'm not tied to using jQuery, I'm just trying to figure out how to do a POST from a javascript.</p> <p>Andrew</p> <p>My client-side javascript</p> <pre><code>&lt;script type="text/javascript" language="javascript"&gt; $(document).ready( function() { $("#ownerId").change(function() { $.post("/holidayCards/clientContact/ownerSelected", {ownerId: this.value}); }); }); </code></pre>
[ { "answer_id": 213942, "author": "Nick", "author_id": 26161, "author_profile": "https://Stackoverflow.com/users/26161", "pm_score": 3, "selected": true, "text": "<p>Find the form object in the DOM you are looking for and cal .submit() on it. Do you have more than one form or multiples on your page?</p>\n" }, { "answer_id": 219217, "author": "Ed.T", "author_id": 3014, "author_profile": "https://Stackoverflow.com/users/3014", "pm_score": 0, "selected": false, "text": "<p>You mention it is calling your controller action so it is getting information back to the page that is the issue, right?</p>\n\n<p>Try something like this:</p>\n\n<pre><code> def ajaxRandom = {\n def randomQuote = quoteService.getRandomQuote()\n response.outputStream &lt;&lt; \"&lt;q&gt;${randomQuote.content}&lt;/q&gt;\" \n }\n</code></pre>\n\n<p>All your gsp page needs is:</p>\n\n<pre><code>&lt;q&gt;${quote.content}&lt;/q&gt;\n</code></pre>\n" } ]
2008/10/17
[ "https://Stackoverflow.com/questions/213939", "https://Stackoverflow.com", "https://Stackoverflow.com/users/21832/" ]
Does anyone know how to initiate a POST request in a Grails applications using javascript. Specifically, I would like to be able to POST when a the selected item in a drop-down box is changed. I've tried using jQuery and the $.post() method. It successfully calls my controller action, but I'm not sure how to get the page to refresh with the response contents. The screen is not updated. Any ideas? This does not need to be asynchronous. I'm not tied to using jQuery, I'm just trying to figure out how to do a POST from a javascript. Andrew My client-side javascript ``` <script type="text/javascript" language="javascript"> $(document).ready( function() { $("#ownerId").change(function() { $.post("/holidayCards/clientContact/ownerSelected", {ownerId: this.value}); }); }); ```
Find the form object in the DOM you are looking for and cal .submit() on it. Do you have more than one form or multiples on your page?
213,950
<p>I'm trying to compile a program called ngrep, and when I ran configure, things seemed to go well, but when I run make, I get:</p> <pre><code>ngrep.c: In function ‘process’: ngrep.c:544: error: ‘struct udphdr’ has no member named ‘source’ ngrep.c:545: error: ‘struct udphdr’ has no member named ‘dest’ make: *** [ngrep.o] Error 1 </code></pre> <p>What does that mean, and how do I fix it? There are no earlier warnings or errors that suggest the root of the problem.</p>
[ { "answer_id": 213981, "author": "Toon Krijthe", "author_id": 18061, "author_profile": "https://Stackoverflow.com/users/18061", "pm_score": 1, "selected": false, "text": "<p>Well, there is a struct called udphdr (probably short for udp header). And some part of the program assumes the struct has the members source and dest which it hasn't.</p>\n\n<p>Look at file ngrep.c line 544 and 545 to find the offending lines.</p>\n\n<p>Possible causes:</p>\n\n<ul>\n<li>type name type error.</li>\n<li>struct is not completely defined.</li>\n<li>using the wrong struct.</li>\n</ul>\n\n<p>Edit: probably related problem: <a href=\"http://ubuntuforums.org/showthread.php?t=371871\" rel=\"nofollow noreferrer\">http://ubuntuforums.org/showthread.php?t=371871</a></p>\n" }, { "answer_id": 214021, "author": "raldi", "author_id": 7598, "author_profile": "https://Stackoverflow.com/users/7598", "pm_score": 3, "selected": true, "text": "<p>Found the problem:</p>\n\n<pre><code>#ifdef HAVE_DUMB_UDPHDR\n printf(\"%s:%d -\", inet_ntoa(ip_packet-&gt;ip_src), ntohs(udp-&gt;source));\n printf(\"&gt; %s:%d\", inet_ntoa(ip_packet-&gt;ip_dst), ntohs(udp-&gt;dest));\n#else\n printf(\"%s:%d -\", inet_ntoa(ip_packet-&gt;ip_src), ntohs(udp-&gt;uh_sport));\n printf(\"&gt; %s:%d\", inet_ntoa(ip_packet-&gt;ip_dst), ntohs(udp-&gt;uh_dport));\n#endif\n</code></pre>\n\n<p>Apparently, configure has a bug in this test, and it thinks my system has the \"dumb\" udphdr, even though it doesn't. Changing the first line to \"#if 0\" fixes the problem.</p>\n" } ]
2008/10/17
[ "https://Stackoverflow.com/questions/213950", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7598/" ]
I'm trying to compile a program called ngrep, and when I ran configure, things seemed to go well, but when I run make, I get: ``` ngrep.c: In function ‘process’: ngrep.c:544: error: ‘struct udphdr’ has no member named ‘source’ ngrep.c:545: error: ‘struct udphdr’ has no member named ‘dest’ make: *** [ngrep.o] Error 1 ``` What does that mean, and how do I fix it? There are no earlier warnings or errors that suggest the root of the problem.
Found the problem: ``` #ifdef HAVE_DUMB_UDPHDR printf("%s:%d -", inet_ntoa(ip_packet->ip_src), ntohs(udp->source)); printf("> %s:%d", inet_ntoa(ip_packet->ip_dst), ntohs(udp->dest)); #else printf("%s:%d -", inet_ntoa(ip_packet->ip_src), ntohs(udp->uh_sport)); printf("> %s:%d", inet_ntoa(ip_packet->ip_dst), ntohs(udp->uh_dport)); #endif ``` Apparently, configure has a bug in this test, and it thinks my system has the "dumb" udphdr, even though it doesn't. Changing the first line to "#if 0" fixes the problem.
213,953
<p>I recently ran into a problem that I thought boost::lambda or boost::phoenix could help be solve, but I was not able to get the syntax right and so I did it another way. What I wanted to do was remove all the elements in "strings" that were less than a certain length and not in another container.</p> <p>This is my first try:</p> <pre><code>std::vector&lt;std::string&gt; strings = getstrings(); std::set&lt;std::string&gt; others = getothers(); strings.erase(std::remove_if(strings.begin(), strings.end(), (_1.length() &lt; 24 &amp;&amp; others.find(_1) == others.end())), strings.end()); </code></pre> <p>How I ended up doing it was this:</p> <pre><code>struct Discard { bool operator()(std::set&lt;std::string&gt; &amp;cont, const std::string &amp;s) { return cont.find(s) == cont.end() &amp;&amp; s.length() &lt; 24; } }; lines.erase(std::remove_if( lines.begin(), lines.end(), boost::bind&lt;bool&gt;(Discard(), old_samples, _1)), lines.end()); </code></pre>
[ { "answer_id": 214222, "author": "Adam Mitz", "author_id": 2574, "author_profile": "https://Stackoverflow.com/users/2574", "pm_score": 3, "selected": true, "text": "<p>You need boost::labmda::bind to lambda-ify function calls, for example the length &lt; 24 part becomes:</p>\n\n<pre><code>bind(&amp;string::length, _1) &lt; 24\n</code></pre>\n\n<p>EDIT</p>\n\n<p>See \"Head Geek\"'s post for why set::find is tricky. He got it to resolve the correct set::find overload (so I copied that part), but he missed an essential boost::ref() -- which is why the comparison with end() always failed (the container was copied).</p>\n\n<pre><code>int main()\n{\n vector&lt;string&gt; strings = getstrings();\n set&lt;string&gt; others = getothers();\n set&lt;string&gt;::const_iterator (set&lt;string&gt;::*findFn)(const std::string&amp;) const = &amp;set&lt;string&gt;::find;\n strings.erase(\n remove_if(strings.begin(), strings.end(),\n bind(&amp;string::length, _1) &lt; 24 &amp;&amp;\n bind(findFn, boost::ref(others), _1) == others.end()\n ), strings.end());\n copy(strings.begin(), strings.end(), ostream_iterator&lt;string&gt;(cout, \", \"));\n return 0;\n}\n</code></pre>\n" }, { "answer_id": 214273, "author": "Head Geek", "author_id": 12193, "author_profile": "https://Stackoverflow.com/users/12193", "pm_score": 2, "selected": false, "text": "<p>The main problem, other than the <code>bind</code> calls (Adam Mitz was correct on that part), is that <code>std::set&lt;std::string&gt;::find</code> is an overloaded function, so you can't specify it directly in the <code>bind</code> call. You need to tell the compiler <em>which</em> <code>find</code> to use, like so:</p>\n\n<pre><code>using namespace boost::lambda;\ntypedef std::vector&lt;std::string&gt; T1;\ntypedef std::set&lt;std::string&gt; T2;\n\nT1 strings = getstrings();\nT2 others = getothers();\n\nT2::const_iterator (T2::*findFn)(const std::string&amp;) const=&amp;T2::find;\nT2::const_iterator othersEnd=others.end();\n\nstrings.erase(std::remove_if(strings.begin(), strings.end(),\n (bind(&amp;std::string::length, _1) &lt; 24\n &amp;&amp; bind(findFn, boost::ref(others), _1) == othersEnd)),\n strings.end());\n</code></pre>\n\n<p>This compiles, but it doesn't work properly, for reasons I haven't yet figured out... the <code>find</code> function is never returning <code>others.end()</code>, so it's never deleting anything. Still working on that part.</p>\n\n<p>EDIT: Correction, the <code>find</code> function <em>is</em> returning <code>others.end()</code>, but the comparison isn't recognizing it. I don't know why.</p>\n\n<p>LATER EDIT: Thanks to Adam's comment, I see what was going wrong, and have corrected the problem. It now works as intended.</p>\n\n<p>(Look at the edit history if you want to see my full test program.)</p>\n" } ]
2008/10/17
[ "https://Stackoverflow.com/questions/213953", "https://Stackoverflow.com", "https://Stackoverflow.com/users/29049/" ]
I recently ran into a problem that I thought boost::lambda or boost::phoenix could help be solve, but I was not able to get the syntax right and so I did it another way. What I wanted to do was remove all the elements in "strings" that were less than a certain length and not in another container. This is my first try: ``` std::vector<std::string> strings = getstrings(); std::set<std::string> others = getothers(); strings.erase(std::remove_if(strings.begin(), strings.end(), (_1.length() < 24 && others.find(_1) == others.end())), strings.end()); ``` How I ended up doing it was this: ``` struct Discard { bool operator()(std::set<std::string> &cont, const std::string &s) { return cont.find(s) == cont.end() && s.length() < 24; } }; lines.erase(std::remove_if( lines.begin(), lines.end(), boost::bind<bool>(Discard(), old_samples, _1)), lines.end()); ```
You need boost::labmda::bind to lambda-ify function calls, for example the length < 24 part becomes: ``` bind(&string::length, _1) < 24 ``` EDIT See "Head Geek"'s post for why set::find is tricky. He got it to resolve the correct set::find overload (so I copied that part), but he missed an essential boost::ref() -- which is why the comparison with end() always failed (the container was copied). ``` int main() { vector<string> strings = getstrings(); set<string> others = getothers(); set<string>::const_iterator (set<string>::*findFn)(const std::string&) const = &set<string>::find; strings.erase( remove_if(strings.begin(), strings.end(), bind(&string::length, _1) < 24 && bind(findFn, boost::ref(others), _1) == others.end() ), strings.end()); copy(strings.begin(), strings.end(), ostream_iterator<string>(cout, ", ")); return 0; } ```
213,958
<p>What new features in java 7 is going to be implemented? And what are they doing now?</p>
[ { "answer_id": 213984, "author": "David G", "author_id": 3150, "author_profile": "https://Stackoverflow.com/users/3150", "pm_score": 2, "selected": false, "text": "<p>In addition to what John Skeet said, here's an <a href=\"http://openjdk.java.net/projects/jdk7/features/\" rel=\"nofollow noreferrer\">overview of the Java 7 project</a>. It includes a list and description of the features.</p>\n\n<p>Note: JDK 7 was released on July 28, 2011, so you should now go to the official <a href=\"http://www.oracle.com/technetwork/java/javase/downloads/index.html\" rel=\"nofollow noreferrer\">java SE site</a>.</p>\n" }, { "answer_id": 6640059, "author": "didxga", "author_id": 231010, "author_profile": "https://Stackoverflow.com/users/231010", "pm_score": 8, "selected": false, "text": "<h2>Java SE 7 <a href=\"http://www.oracle.com/technetwork/java/javase/jdk7-relnotes-418459.html\" rel=\"noreferrer\">Features and Enhancements</a> from JDK 7 Release Notes</h2>\n\n<p>This is the Java 7 new features summary from the <a href=\"http://openjdk.java.net/projects/jdk7/features/\" rel=\"noreferrer\">OpenJDK 7 features page</a>:</p>\n\n<blockquote>\n<pre>\nvm JSR 292: Support for dynamically-typed languages (InvokeDynamic)\n Strict class-file checking\nlang JSR 334: Small language enhancements (Project Coin)\ncore Upgrade class-loader architecture\n Method to close a URLClassLoader\n Concurrency and collections updates (jsr166y)\ni18n Unicode 6.0\n Locale enhancement\n Separate user locale and user-interface locale\nionet JSR 203: More new I/O APIs for the Java platform (NIO.2)\n NIO.2 filesystem provider for zip/jar archives\n SCTP (Stream Control Transmission Protocol)\n SDP (Sockets Direct Protocol)\n Use the Windows Vista IPv6 stack\n TLS 1.2\nsec Elliptic-curve cryptography (ECC)\njdbc JDBC 4.1\nclient XRender pipeline for Java 2D\n Create new platform APIs for 6u10 graphics features\n Nimbus look-and-feel for Swing\n Swing JLayer component\n Gervill sound synthesizer [NEW]\nweb Update the XML stack\nmgmt Enhanced MBeans [UPDATED]\n</pre>\n</blockquote>\n\n<h2>Code examples for new features in Java 1.7</h2>\n\n<h3>Try-with-resources statement</h3>\n\n<p>this:</p>\n\n<pre><code>BufferedReader br = new BufferedReader(new FileReader(path));\ntry {\n return br.readLine();\n} finally {\n br.close();\n}\n</code></pre>\n\n<p>becomes:</p>\n\n<pre><code>try (BufferedReader br = new BufferedReader(new FileReader(path)) {\n return br.readLine();\n}\n</code></pre>\n\n<p>You can declare more than one resource to close:</p>\n\n<pre><code>try (\n InputStream in = new FileInputStream(src);\n OutputStream out = new FileOutputStream(dest))\n{\n // code\n}\n</code></pre>\n\n<h3>Underscores in numeric literals</h3>\n\n<pre><code>int one_million = 1_000_000;\n</code></pre>\n\n<h3>Strings in switch</h3>\n\n<pre><code>String s = ...\nswitch(s) {\n case \"quux\":\n processQuux(s);\n // fall-through\n\n case \"foo\":\n case \"bar\":\n processFooOrBar(s);\n break;\n\n case \"baz\":\n processBaz(s);\n // fall-through\n\n default:\n processDefault(s);\n break;\n}\n</code></pre>\n\n<h3>Binary literals</h3>\n\n<pre><code>int binary = 0b1001_1001;\n</code></pre>\n\n<h3>Improved Type Inference for Generic Instance Creation</h3>\n\n<pre><code>Map&lt;String, List&lt;String&gt;&gt; anagrams = new HashMap&lt;String, List&lt;String&gt;&gt;();\n</code></pre>\n\n<p>becomes:</p>\n\n<pre><code>Map&lt;String, List&lt;String&gt;&gt; anagrams = new HashMap&lt;&gt;();\n</code></pre>\n\n<h3>Multiple exception catching</h3>\n\n<p>this:</p>\n\n<pre><code>} catch (FirstException ex) {\n logger.error(ex);\n throw ex;\n} catch (SecondException ex) {\n logger.error(ex);\n throw ex;\n}\n</code></pre>\n\n<p>becomes:</p>\n\n<pre><code>} catch (FirstException | SecondException ex) {\n logger.error(ex);\n throw ex;\n}\n</code></pre>\n\n<h3>SafeVarargs</h3>\n\n<p>this:</p>\n\n<pre><code>@SuppressWarnings({\"unchecked\", \"varargs\"})\npublic static void printAll(List&lt;String&gt;... lists){\n for(List&lt;String&gt; list : lists){\n System.out.println(list);\n }\n}\n</code></pre>\n\n<p>becomes:</p>\n\n<pre><code>@SafeVarargs\npublic static void printAll(List&lt;String&gt;... lists){\n for(List&lt;String&gt; list : lists){\n System.out.println(list);\n }\n}\n</code></pre>\n" }, { "answer_id": 8148022, "author": "Muhammad Imran Tariq", "author_id": 420613, "author_profile": "https://Stackoverflow.com/users/420613", "pm_score": -1, "selected": false, "text": "<p>The following list contains links to the the enhancements pages in the Java SE 7.</p>\n\n<pre><code>Swing\nIO and New IO\nNetworking\nSecurity\nConcurrency Utilities\nRich Internet Applications (RIA)/Deployment\n Requesting and Customizing Applet Decoration in Dragg able Applets\n Embedding JNLP File in Applet Tag\n Deploying without Codebase\n Handling Applet Initialization Status with Event Handlers\nJava 2D\nJava XML – JAXP, JAXB, and JAX-WS\nInternationalization\njava.lang Package\n Multithreaded Custom Class Loaders in Java SE 7\nJava Programming Language\n Binary Literals\n Strings in switch Statements\n The try-with-resources Statement\n Catching Multiple Exception Types and Rethrowing Exceptions with Improved Type Checking\n Underscores in Numeric Literals\n Type Inference for Generic Instance Creation\n Improved Compiler Warnings and Errors When Using Non-Reifiable Formal Parameters with Varargs Methods\nJava Virtual Machine (JVM)\n Java Virtual Machine Support for Non-Java Languages\n Garbage-First Collector\n Java HotSpot Virtual Machine Performance Enhancements\nJDBC\n</code></pre>\n\n<p><a href=\"http://www.oracle.com/technetwork/java/javase/jdk7-relnotes-418459.html\" rel=\"nofollow\">Reference 1</a> <a href=\"http://www.imrantariq.com/blog/?tag=java-7\" rel=\"nofollow\">Reference 2</a></p>\n" }, { "answer_id": 8456108, "author": "apresh", "author_id": 1091130, "author_profile": "https://Stackoverflow.com/users/1091130", "pm_score": 4, "selected": false, "text": "<h2>New Feature of Java Standard Edition (JSE 7)</h2>\n\n<ol>\n<li><p><strong>Decorate Components with the JLayer Class:</strong> </p>\n\n<p>The JLayer class is a flexible and powerful decorator for Swing components. The JLayer class in Java SE 7 is similar in spirit to the JxLayer project project at java.net. The JLayer class was initially based on the JXLayer project, but its API evolved separately.</p></li>\n<li><p><strong>Strings in switch Statement</strong>:</p>\n\n<p>In the JDK 7 , we can use a String object in the expression of a switch statement. The Java compiler generates generally more efficient bytecode from switch statements that use String objects than from chained if-then-else statements.</p></li>\n<li><p><strong>Type Inference for Generic Instance:</strong> </p>\n\n<p>We can replace the type arguments required to invoke the constructor of a generic class with an empty set of type parameters (&lt;>) as long as the compiler can infer the type arguments from the context. This pair of angle brackets is informally called the diamond.\nJava SE 7 supports limited type inference for generic instance creation; you can only use type inference if the parameterized type of the constructor is obvious from the context. For example, the following example does not compile:</p>\n\n<pre><code>List&lt;String&gt; l = new ArrayList&lt;&gt;();\nl.add(\"A\");\nl.addAll(new ArrayList&lt;&gt;());\n</code></pre>\n\n<p>In comparison, the following example compiles:</p>\n\n<pre><code>List&lt;? extends String&gt; list2 = new ArrayList&lt;&gt;();\nl.addAll(list2);\n</code></pre></li>\n<li><p><strong>Catching Multiple Exception Types and Rethrowing Exceptions with Improved Type Checking:</strong> </p>\n\n<p>In Java SE 7 and later, a single catch block can handle more than one type of exception. This feature can reduce code duplication. Consider the following code, which contains duplicate code in each of the catch blocks:</p>\n\n<pre><code>catch (IOException e) {\n logger.log(e);\n throw e;\n}\ncatch (SQLException e) {\n logger.log(e);\n throw e;\n}\n</code></pre>\n\n<p>In releases prior to Java SE 7, it is difficult to create a common method to eliminate the duplicated code because the variable e has different types.\nThe following example, which is valid in Java SE 7 and later, eliminates the duplicated code:</p>\n\n<pre><code>catch (IOException|SQLException e) {\n logger.log(e);\n throw e;\n}\n</code></pre>\n\n<p>The catch clause specifies the types of exceptions that the block can handle, and each exception type is separated with a vertical bar (|).</p></li>\n<li><p><strong>The java.nio.file package</strong></p>\n\n<p>The <code>java.nio.file</code> package and its related package, java.nio.file.attribute, provide comprehensive support for file I/O and for accessing the file system. A zip file system provider is also available in JDK 7.</p></li>\n</ol>\n\n<p>Source: <a href=\"http://ohmjavaclasses.blogspot.com/\" rel=\"noreferrer\">http://ohmjavaclasses.blogspot.com/</a></p>\n" }, { "answer_id": 24487649, "author": "Soumyaansh", "author_id": 1017917, "author_profile": "https://Stackoverflow.com/users/1017917", "pm_score": 1, "selected": false, "text": "<p><strong>Language changes</strong>:</p>\n\n<pre><code>-Project Coin (small changes)\n-switch on Strings\n-try-with-resources\n-diamond operator\n</code></pre>\n\n<p><strong>Library changes</strong>:</p>\n\n<pre><code>-new abstracted file-system API (NIO.2) (with support for virtual filesystems)\n-improved concurrency libraries\n-elliptic curve encryption\n-more incremental upgrades\n</code></pre>\n\n<p><strong>Platform changes</strong>:</p>\n\n<pre><code>-support for dynamic languages\n</code></pre>\n\n<p>Below is the link explaining the newly added features of JAVA 7 , the explanation is crystal clear with the possible small examples for each features :</p>\n\n<p><a href=\"http://radar.oreilly.com/2011/09/java7-features.html\" rel=\"nofollow\">http://radar.oreilly.com/2011/09/java7-features.html</a></p>\n" }, { "answer_id": 29255298, "author": "Premraj", "author_id": 1697099, "author_profile": "https://Stackoverflow.com/users/1697099", "pm_score": 3, "selected": false, "text": "<p><a href=\"http://docs.oracle.com/javase/7/docs/technotes/guides/language/enhancements.html\" rel=\"nofollow noreferrer\"><strong>Java Programming Language Enhancements @ Java7</strong></a></p>\n<ol>\n<li><a href=\"https://stackoverflow.com/a/10961101/1697099\">Binary Literals</a></li>\n<li><a href=\"https://stackoverflow.com/a/10240598/1697099\">Strings in switch Statement</a></li>\n<li><a href=\"https://stackoverflow.com/a/17739460/1697099\">Try with Resources</a> (<a href=\"https://stackoverflow.com/a/26366568/1697099\">How it works</a>) or ARM (<a href=\"http://javarevisited.blogspot.sg/2011/09/arm-automatic-resource-management-in.html\" rel=\"nofollow noreferrer\">Automatic Resource Management</a>)</li>\n<li><a href=\"https://stackoverflow.com/a/3495968/1697099\">Multiple Exception Handling</a></li>\n<li><a href=\"https://docs.oracle.com/javase/tutorial/essential/exceptions/tryResourceClose.html\" rel=\"nofollow noreferrer\">Suppressed Exceptions</a></li>\n<li><a href=\"https://stackoverflow.com/a/6212642/1697099\">underscore in literals</a></li>\n<li><a href=\"https://stackoverflow.com/q/14909875/1697099\">Type Inference for Generic Instance Creation using Diamond Syntax</a></li>\n<li><a href=\"http://docs.oracle.com/javase/7/docs/technotes/guides/language/non-reifiable-varargs.html\" rel=\"nofollow noreferrer\">Improved Compiler Warnings and Errors When Using Non-Reifiable Formal Parameters with Varargs Methods</a></li>\n</ol>\n<p><a href=\"http://www.oracle.com/technetwork/java/javase/jdk7-relnotes-418459.html\" rel=\"nofollow noreferrer\">Official reference</a><br />\n<a href=\"http://docs.oracle.com/javase/8/docs/technotes/guides/language/enhancements.html\" rel=\"nofollow noreferrer\">Official reference with java8</a><br />\n<a href=\"https://en.wikipedia.org/wiki/Java_version_history#Java_SE_7_.28July_28.2C_2011.29\" rel=\"nofollow noreferrer\">wiki reference</a></p>\n" }, { "answer_id": 50356666, "author": "Amit", "author_id": 540195, "author_profile": "https://Stackoverflow.com/users/540195", "pm_score": 0, "selected": false, "text": "<blockquote>\n <p>Using Diamond(&lt;>) operator for generic instance creation</p>\n</blockquote>\n\n<pre><code>Map&lt;String, List&lt;Trade&gt;&gt; trades = new TreeMap &lt;&gt; ();\n</code></pre>\n\n<blockquote>\n <p>Using strings in switch statements</p>\n</blockquote>\n\n<pre><code>String status= “something”;\n switch(statue){\n case1: \n case2: \n default:\n }\n</code></pre>\n\n<blockquote>\n <p>Underscore in numeric literals</p>\n</blockquote>\n\n<p>int val 12_15;\nlong phoneNo = 01917_999_720L;</p>\n\n<blockquote>\n <p>Using single catch statement for throwing multiple exception by using “|” operator</p>\n</blockquote>\n\n<pre><code>catch(IOException | NullPointerException ex){\n ex.printStackTrace(); \n }\n</code></pre>\n\n<blockquote>\n <p>No need to close() resources because Java 7 provides try-with-resources statement</p>\n</blockquote>\n\n<pre><code>try(FileOutputStream fos = new FileOutputStream(\"movies.txt\");\n DataOutputStream dos = new DataOutputStream(fos)) {\n dos.writeUTF(\"Java 7 Block Buster\");\n } catch(IOException e) {\n // log the exception\n }\n</code></pre>\n\n<blockquote>\n <p>binary literals with prefix “0b” or “0B”</p>\n</blockquote>\n" }, { "answer_id": 58596028, "author": "Dexter", "author_id": 1852693, "author_profile": "https://Stackoverflow.com/users/1852693", "pm_score": 0, "selected": false, "text": "<p>I think <strong>ForkJoinPool</strong> and related enhancement to Executor Framework is an important addition in Java 7.</p>\n" } ]
2008/10/17
[ "https://Stackoverflow.com/questions/213958", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
What new features in java 7 is going to be implemented? And what are they doing now?
Java SE 7 [Features and Enhancements](http://www.oracle.com/technetwork/java/javase/jdk7-relnotes-418459.html) from JDK 7 Release Notes --------------------------------------------------------------------------------------------------------------------------------------- This is the Java 7 new features summary from the [OpenJDK 7 features page](http://openjdk.java.net/projects/jdk7/features/): > > > ``` > > vm JSR 292: Support for dynamically-typed languages (InvokeDynamic) > Strict class-file checking > lang JSR 334: Small language enhancements (Project Coin) > core Upgrade class-loader architecture > Method to close a URLClassLoader > Concurrency and collections updates (jsr166y) > i18n Unicode 6.0 > Locale enhancement > Separate user locale and user-interface locale > ionet JSR 203: More new I/O APIs for the Java platform (NIO.2) > NIO.2 filesystem provider for zip/jar archives > SCTP (Stream Control Transmission Protocol) > SDP (Sockets Direct Protocol) > Use the Windows Vista IPv6 stack > TLS 1.2 > sec Elliptic-curve cryptography (ECC) > jdbc JDBC 4.1 > client XRender pipeline for Java 2D > Create new platform APIs for 6u10 graphics features > Nimbus look-and-feel for Swing > Swing JLayer component > Gervill sound synthesizer [NEW] > web Update the XML stack > mgmt Enhanced MBeans [UPDATED] > > ``` > > Code examples for new features in Java 1.7 ------------------------------------------ ### Try-with-resources statement this: ``` BufferedReader br = new BufferedReader(new FileReader(path)); try { return br.readLine(); } finally { br.close(); } ``` becomes: ``` try (BufferedReader br = new BufferedReader(new FileReader(path)) { return br.readLine(); } ``` You can declare more than one resource to close: ``` try ( InputStream in = new FileInputStream(src); OutputStream out = new FileOutputStream(dest)) { // code } ``` ### Underscores in numeric literals ``` int one_million = 1_000_000; ``` ### Strings in switch ``` String s = ... switch(s) { case "quux": processQuux(s); // fall-through case "foo": case "bar": processFooOrBar(s); break; case "baz": processBaz(s); // fall-through default: processDefault(s); break; } ``` ### Binary literals ``` int binary = 0b1001_1001; ``` ### Improved Type Inference for Generic Instance Creation ``` Map<String, List<String>> anagrams = new HashMap<String, List<String>>(); ``` becomes: ``` Map<String, List<String>> anagrams = new HashMap<>(); ``` ### Multiple exception catching this: ``` } catch (FirstException ex) { logger.error(ex); throw ex; } catch (SecondException ex) { logger.error(ex); throw ex; } ``` becomes: ``` } catch (FirstException | SecondException ex) { logger.error(ex); throw ex; } ``` ### SafeVarargs this: ``` @SuppressWarnings({"unchecked", "varargs"}) public static void printAll(List<String>... lists){ for(List<String> list : lists){ System.out.println(list); } } ``` becomes: ``` @SafeVarargs public static void printAll(List<String>... lists){ for(List<String> list : lists){ System.out.println(list); } } ```
213,978
<p>I was running my first Visual Studio 2008 Unit Test with a WCF Service and I received the following error:</p> <blockquote> <p>Test method UnitTest.ServiceUnitTest.TestMyService threw exception: System.ServiceModel.Security.MessageSecurityException: The HTTP request is unauthorized with client authentication scheme 'Anonymous'. The authentication header received from the server was 'Negotiate,NTLM'. ---> System.Net.WebException: The remote server returned an error: (401) Unauthorized..</p> </blockquote> <p>I am also getting the following failed audit in the security log:</p> <blockquote> <p>Logon Failure: Reason: The user has not been granted the requested logon type at this machine<br /> User Name: (Internet Guest Account)<br /> Domain: <br /> Logon Type: 3 <br /> Logon Process: IIS <br /> Authentication Package: <br /> MICROSOFT_AUTHENTICATION_PACKAGE_V1_0<br /> Workstation Name: </p> </blockquote> <p>I am hosting the WCF service in IIS 6.0 on a Windows XP SP3 machine. I have both the "Anonymous Access" and "Integrated Windows authentication" checked for the WCF service virtual directory.</p> <p>Here is my config file for the service:</p> <pre><code>&lt;system.serviceModel&gt; &lt;services&gt; &lt;bindings&gt; &lt;basicHttpBinding&gt; &lt;binding name="MyBinding"&gt; &lt;security mode="None" /&gt; &lt;/binding&gt; &lt;/basicHttpBinding&gt; &lt;customBinding&gt; &lt;binding name="MyBinding"&gt; &lt;transactionFlow /&gt; &lt;textMessageEncoding /&gt; &lt;httpsTransport authenticationScheme="Ntlm"/&gt; &lt;/binding&gt; &lt;/customBinding&gt; &lt;wsHttpBinding&gt; &lt;binding name="MyBinding"&gt; &lt;security mode="None" /&gt; &lt;/binding&gt; &lt;/wsHttpBinding&gt; &lt;/bindings&gt; &lt;service behaviorConfiguration="Service1Behavior" name="Service1" &gt; &lt;endpoint address="" binding="wsHttpBinding" bindingConfiguration="MyBinding" contract="IService1" &gt; &lt;identity&gt; &lt;dns value="localhost" /&gt; &lt;/identity&gt; &lt;/endpoint&gt; &lt;/service&gt; &lt;/services&gt; &lt;behaviors&gt; &lt;serviceBehaviors&gt; &lt;behavior name="Service1Behavior"&gt; &lt;serviceMetadata httpGetEnabled="true" /&gt; &lt;serviceDebug includeExceptionDetailInFaults="false" /&gt; &lt;/behavior&gt; &lt;/serviceBehaviors&gt; &lt;/behaviors&gt; &lt;/system.serviceModel&gt; </code></pre>
[ { "answer_id": 213989, "author": "Karg", "author_id": 12685, "author_profile": "https://Stackoverflow.com/users/12685", "pm_score": 1, "selected": false, "text": "<p>The default authentication is windows (or NTLM) so you'll need to specify that you don't want authentication in your config file.</p>\n\n<pre><code>&lt;system.serviceModel&gt;\n &lt;bindings&gt;\n &lt;wsHttpBinding&gt;\n &lt;binding name=\"myBinding\"&gt;\n &lt;security mode=\"None\" /&gt;\n &lt;/binding&gt;\n &lt;/bindings&gt;\n&lt;/system.serviceModel&gt;\n</code></pre>\n\n<p>also add this attribute to the endpoint</p>\n\n<pre><code>bindingConfiguration=\"myBinding\"\n</code></pre>\n\n<p>The binding element specifies modifications of the standard behavior of the wsHttpBinding.</p>\n\n<p>Then the \"bindingConfiguration=\"myBinding\" attribute on the endpoint says that that endpoint should use the modifications we specified.</p>\n" }, { "answer_id": 214319, "author": "jezell", "author_id": 27453, "author_profile": "https://Stackoverflow.com/users/27453", "pm_score": 2, "selected": false, "text": "<p>When you have securityMode=\"None\" in your binding, you should turn off integrated authentication.</p>\n" }, { "answer_id": 231253, "author": "Michael Kniskern", "author_id": 26327, "author_profile": "https://Stackoverflow.com/users/26327", "pm_score": 4, "selected": true, "text": "<p>I had to change the following IIS and WCF service configurations to get past the \"Negotiate,NTLM\" exception.</p>\n\n<p>IIS Configurations:</p>\n\n<blockquote>\n <p>-- Unchecked \"Anonymous Access\" checkbox and check the \"Integrated\n Windows authentication\" checkbox in\n the directory security setting for the\n WCF Service virtual directory.</p>\n</blockquote>\n\n<p>WCF Services:</p>\n\n<blockquote>\n <p>-- implemented basicHttpBinding and configured the basicSettingBinding\n security setting to\n \"TransportCredentialsOnly\" mode and\n TransportClientCredentialType to\n \"Windows\"</p>\n</blockquote>\n\n<p>Here is my updated wcf service configuration:</p>\n\n<pre><code>&lt;system.serviceModel&gt;\n &lt;bindings&gt;\n &lt;basicHttpBinding&gt;\n &lt;binding name=\"windowsBasicHttpBinding\"&gt;\n &lt;security mode=\"TransportCredentialOnly\"&gt;\n &lt;transport clientCredentialType=\"Windows\" /&gt;\n &lt;/security&gt;\n &lt;/binding&gt;\n &lt;/basicHttpBinding&gt;\n &lt;/bindings&gt;\n &lt;services&gt;\n &lt;service \n behaviorConfiguration=\"CityOfMesa.ApprovalRouting.WCFService.RoutingServiceBehavior\"\n name=\"CityOfMesa.ApprovalRouting.WCFService.RoutingService\"\n &gt;\n &lt;endpoint \n binding=\"basicHttpBinding\" bindingConfiguration=\"windowsBasicHttpBinding\"\n name=\"basicEndPoint\" \n contract=\"CityOfMesa.ApprovalRouting.WCFService.IRoutingService\" \n /&gt;\n &lt;/service&gt;\n &lt;/services&gt;\n &lt;behaviors&gt;\n &lt;serviceBehaviors&gt;\n &lt;behavior \n name=\"CityOfMesa.ApprovalRouting.WCFService.RoutingServiceBehavior\"\n &gt;\n &lt;serviceMetadata httpGetEnabled=\"true\" /&gt;\n &lt;serviceDebug includeExceptionDetailInFaults=\"true\" /&gt;\n &lt;/behavior&gt;\n &lt;/serviceBehaviors&gt;\n &lt;/behaviors&gt;\n&lt;/system.serviceModel&gt;\n</code></pre>\n" }, { "answer_id": 231293, "author": "Michael Kniskern", "author_id": 26327, "author_profile": "https://Stackoverflow.com/users/26327", "pm_score": 0, "selected": false, "text": "<p>As a side note.....There was a GPO setting \"NTLM Authentication Level\" that was controls authenication that was causing the unit test to generate the \"Negotiate,NTLM\" exception. </p>\n" } ]
2008/10/17
[ "https://Stackoverflow.com/questions/213978", "https://Stackoverflow.com", "https://Stackoverflow.com/users/26327/" ]
I was running my first Visual Studio 2008 Unit Test with a WCF Service and I received the following error: > > Test method > UnitTest.ServiceUnitTest.TestMyService > threw exception: > System.ServiceModel.Security.MessageSecurityException: > The HTTP request is unauthorized with > client authentication scheme > 'Anonymous'. The authentication header > received from the server was > 'Negotiate,NTLM'. ---> > System.Net.WebException: The remote > server returned an error: (401) > Unauthorized.. > > > I am also getting the following failed audit in the security log: > > Logon Failure: Reason: The user has > not been granted the requested logon > type at this machine > User > Name: (Internet Guest Account) > > Domain: > Logon Type: 3 > > Logon Process: IIS > > Authentication Package: > > MICROSOFT\_AUTHENTICATION\_PACKAGE\_V1\_0 > > Workstation Name: > > > I am hosting the WCF service in IIS 6.0 on a Windows XP SP3 machine. I have both the "Anonymous Access" and "Integrated Windows authentication" checked for the WCF service virtual directory. Here is my config file for the service: ``` <system.serviceModel> <services> <bindings> <basicHttpBinding> <binding name="MyBinding"> <security mode="None" /> </binding> </basicHttpBinding> <customBinding> <binding name="MyBinding"> <transactionFlow /> <textMessageEncoding /> <httpsTransport authenticationScheme="Ntlm"/> </binding> </customBinding> <wsHttpBinding> <binding name="MyBinding"> <security mode="None" /> </binding> </wsHttpBinding> </bindings> <service behaviorConfiguration="Service1Behavior" name="Service1" > <endpoint address="" binding="wsHttpBinding" bindingConfiguration="MyBinding" contract="IService1" > <identity> <dns value="localhost" /> </identity> </endpoint> </service> </services> <behaviors> <serviceBehaviors> <behavior name="Service1Behavior"> <serviceMetadata httpGetEnabled="true" /> <serviceDebug includeExceptionDetailInFaults="false" /> </behavior> </serviceBehaviors> </behaviors> </system.serviceModel> ```
I had to change the following IIS and WCF service configurations to get past the "Negotiate,NTLM" exception. IIS Configurations: > > -- Unchecked "Anonymous Access" checkbox and check the "Integrated > Windows authentication" checkbox in > the directory security setting for the > WCF Service virtual directory. > > > WCF Services: > > -- implemented basicHttpBinding and configured the basicSettingBinding > security setting to > "TransportCredentialsOnly" mode and > TransportClientCredentialType to > "Windows" > > > Here is my updated wcf service configuration: ``` <system.serviceModel> <bindings> <basicHttpBinding> <binding name="windowsBasicHttpBinding"> <security mode="TransportCredentialOnly"> <transport clientCredentialType="Windows" /> </security> </binding> </basicHttpBinding> </bindings> <services> <service behaviorConfiguration="CityOfMesa.ApprovalRouting.WCFService.RoutingServiceBehavior" name="CityOfMesa.ApprovalRouting.WCFService.RoutingService" > <endpoint binding="basicHttpBinding" bindingConfiguration="windowsBasicHttpBinding" name="basicEndPoint" contract="CityOfMesa.ApprovalRouting.WCFService.IRoutingService" /> </service> </services> <behaviors> <serviceBehaviors> <behavior name="CityOfMesa.ApprovalRouting.WCFService.RoutingServiceBehavior" > <serviceMetadata httpGetEnabled="true" /> <serviceDebug includeExceptionDetailInFaults="true" /> </behavior> </serviceBehaviors> </behaviors> </system.serviceModel> ```
213,985
<p>I have a co-worker that swears by</p> <pre><code>//in a singleton "Constants" class public static final String EMPTY_STRING = ""; </code></pre> <p>in a constants class available throughout the project. That way, we can write something like</p> <pre><code>if (Constants.EMPTY_STRING.equals(otherString)) { ... } </code></pre> <p>instead of </p> <pre><code>if ("".equals(otherString)) { ... } </code></pre> <p>I say it's </p> <ol> <li>not worth it--it doesn't save any space in the heap/stack/string pool,</li> <li>ugly</li> <li>abuse of a constants class.</li> </ol> <p>Who is the idiot here?</p>
[ { "answer_id": 213991, "author": "shelfoo", "author_id": 3444, "author_profile": "https://Stackoverflow.com/users/3444", "pm_score": 3, "selected": false, "text": "<p>I much prefer seeing EMPTY_STRING.</p>\n\n<p>It makes it english. \"\".equals 'reads' differently than EMPTY_STRING.equals.</p>\n" }, { "answer_id": 213992, "author": "Bill K", "author_id": 12943, "author_profile": "https://Stackoverflow.com/users/12943", "pm_score": 2, "selected": false, "text": "<ol>\n<li>yes--it offers no benefit.</li>\n<li>depends on what you're used to, I'm sure.</li>\n<li>No, it's just a constant--not an abuse.</li>\n</ol>\n" }, { "answer_id": 213997, "author": "David G", "author_id": 3150, "author_profile": "https://Stackoverflow.com/users/3150", "pm_score": 2, "selected": false, "text": "<p>I don't like either choice. Why not <code>if (otherString.length() == 0)</code></p>\n\n<p>Edit: I actually always code </p>\n\n<pre><code>if (otherString == null || otherString.length() == 0)\n</code></pre>\n" }, { "answer_id": 213998, "author": "Dan Dyer", "author_id": 5171, "author_profile": "https://Stackoverflow.com/users/5171", "pm_score": 7, "selected": true, "text": "<p>String literals are interned by default, so no matter how many times you refer to <strong>\"\"</strong> in code, there will only be one empty String object. I don't see any benefit in declaring EMPTY_STRING. Otherwise, you might as well declare ONE, TWO, THREE, FOUR, etc. for integer literals.</p>\n\n<p>Of course, if you want to change the value of EMPTY_STRING later, it's handy to have it in one place ;)</p>\n" }, { "answer_id": 214001, "author": "Douglas Squirrel", "author_id": 29121, "author_profile": "https://Stackoverflow.com/users/29121", "pm_score": 4, "selected": false, "text": "<p>Why on earth would you want a global variable in Java? James Gosling really tried to get rid of them; don't bring them back, please.</p>\n\n<p>Either</p>\n\n<pre><code>0 == possiblyEmptyString.length()\n</code></pre>\n\n<p>or </p>\n\n<pre><code>possiblyEmptyString.isEmpty() // Java 6 only\n</code></pre>\n\n<p>are just as clear.</p>\n" }, { "answer_id": 214008, "author": "David Arno", "author_id": 7122, "author_profile": "https://Stackoverflow.com/users/7122", "pm_score": 3, "selected": false, "text": "<p>Ironically the whole point of constants is to make them easily changeable. So unless your co-worker plans to redefine EMPTY_STRING to be something other than an empty string - which would be a really stupid thing to do - casting a genuine fixed construct such as \"\" to a constant is a bad thing.</p>\n\n<p>As Dan Dyer says, its like defining the constant ONE to be 1: it is completely pointless and would be utterly confusing - potentially risky - if someone redefined it.</p>\n" }, { "answer_id": 214010, "author": "Jon Skeet", "author_id": 22656, "author_profile": "https://Stackoverflow.com/users/22656", "pm_score": 2, "selected": false, "text": "<p>The same argument comes up in .NET from time to time (where there's already a readonly static field string.Empty). It's a matter of taste - but personally I find \"\" less obtrusive.</p>\n" }, { "answer_id": 214050, "author": "questzen", "author_id": 25210, "author_profile": "https://Stackoverflow.com/users/25210", "pm_score": 0, "selected": false, "text": "<p>Hmm, the rules are right but are being taken in a different sense! Lets look at the cause, firstly all object references in java are checked by equals(). Earlier on, in some languages it was done using '==' operator, if by accident someone used '=' for '==', a catastrophe. Now the question of magic numbers/constants, for a computer all constants/numbers are similar. Instead of 'int ONE=1' one can surely use 1, but will that hold true for double PI = 3.141...? What happens if someone tries to change the precision sometime later. </p>\n\n<p>If we were to come up with a check list, what would the rule be address the general guideline isn't it? All I mean to say is that rules are supposed to aid, we can surely bend the rules only when we know them very well. Common sense prevails. As suggested by a friend of mine, program constants like 0/1 which denote exit conditions can be hard coded and hence magic number principle doesn't apply. But for those which participate in logical checks/rules, better keep them as configurable constants.</p>\n" }, { "answer_id": 214069, "author": "John Nilsson", "author_id": 24243, "author_profile": "https://Stackoverflow.com/users/24243", "pm_score": 1, "selected": false, "text": "<p>We just do the following for situations like this:</p>\n\n<pre><code>public class StaticUtils\n{\n public static boolean empty(CharSequence cs)\n {\n return cs == null || cs.length() == 0;\n }\n\n public static boolean has(CharSequence cs)\n {\n return !empty(cs);\n }\n}\n</code></pre>\n\n<p>Then just <code>import static StaticUtils.*</code></p>\n" }, { "answer_id": 214081, "author": "tvanfosson", "author_id": 12950, "author_profile": "https://Stackoverflow.com/users/12950", "pm_score": 2, "selected": false, "text": "<p>I'm with your coworker. While the empty string is hard to mistype, you can accidentally put a space in there and it may be difficult to notice when scanning the code. More to the point it is a good practice to do this with all of your string constants that get used in more than one place -- although, I tend to do this at the class level rather than as global constants.</p>\n\n<p>FWIW, C# has a static property string.Empty for just this purpose and I find that it improves the readability of the code immensely.</p>\n" }, { "answer_id": 214502, "author": "ddimitrov", "author_id": 18187, "author_profile": "https://Stackoverflow.com/users/18187", "pm_score": 2, "selected": false, "text": "<p>One case where it does make sense to have a constant with value of empty string is when you the name captures the semantics of the value. For example:</p>\n\n<pre><code>if (Constants.FORM_FIELD_NOT_SET.equals(form.getField(\"foobar\"))) {\n ...\n}\n</code></pre>\n\n<p>This makes the code more self documenting (apart from the argument that a better design is to add the method checking whether a field is set to the form itself).</p>\n" }, { "answer_id": 218308, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 3, "selected": false, "text": "<p>Well, I could guess too, but I did a quick test... Almost like cheating...</p>\n\n<p>An arbitrary string is checked using various methods. (several iterations)</p>\n\n<p>The results suggests that isEmpty() is both faster and indeed more readable;\nIf isEmpty() is not available, length() is a good alternative.</p>\n\n<p>Using a constant is probably not worth it.</p>\n\n<pre>\n\"\".equals(someString()) :24735 ms\nt != null && t.equals(\"\") :23363 ms\nt != null && t.equals(EMPTY) :22561 ms\nEMPTY.equals(someString()) :22159 ms\nt != null && t.length() == 0 :18388 ms\nt != null && t.isEmpty() :18375 ms\nsomeString().length() == 0 :18171 ms\n\n</pre>\n\n<p>In this scenario;</p>\n\n<pre>\n\"IAmNotHardCoded\".equals(someString())\n</pre> \n\n<p>I would suggest defining a constant in a r e l e v a n t place, since a global class\nfor all constants really sucks. If there is no relevant place, you are probably doing something else wrong...</p>\n\n<pre>\nCustomer.FIELD_SHOE_SIZE //\"SHOE_SIZE\"\n</pre>\n\n<p>Might be considered a relevant place where as;</p>\n\n<pre>\nCommonConstants.I__AM__A__LAZY__PROGRAMMER // true\n</pre>\n\n<p>is not.</p>\n\n<p>For BigIntegers and similar thing, I tend to end up defining a final static locally; like:</p>\n\n<pre>\nprivate final static BigDecimal ZERO = new BigDecimal(0);\nprivate final static BigDecimal B100 = new BigDecimal(\"100.00\");\n</pre>\n\n<p>Thats bugs me and wouldn't it be nice with some sugar for BigInts and BigDecimals...</p>\n" }, { "answer_id": 224109, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 2, "selected": false, "text": "<p>Hehe, funny thing is: \nOnce it compiles, you wont see a difference (in the byte-code) between the \"static final\" thing and the string literal, as the Java-compiler always inlines \"static final String\" into the target class. Just change your empty string into something recognizable (like the LGPL-text) and look at the resulting *.class file of code that refernces that constant. You will find your text copied into that class-file.</p>\n" }, { "answer_id": 1589007, "author": "RHSeeger", "author_id": 26816, "author_profile": "https://Stackoverflow.com/users/26816", "pm_score": 2, "selected": false, "text": "<p>As a tangent to the question, I generally recommend using a utility function when what you're really checking for is \"no useful value\" rather than, specifically, the empty string. In general, I tend to use:</p>\n\n<pre><code>import org.apache.commons.lang.StringUtils;\n\n// Check if a String is whitespace, empty (\"\") or null.\nStringUtils.isBlank(mystr); \n// Check if a String is empty (\"\") or null.\nStringUtils.isEmpty(mystr); \n</code></pre>\n\n<p>The concept being that the above two:</p>\n\n<ul>\n<li>Check the various other cases, including being null safe, and (more importantly)</li>\n<li>Conveys what you are trying to test, rather than how to test it.</li>\n</ul>\n" }, { "answer_id": 4358045, "author": "Antony Booth", "author_id": 312957, "author_profile": "https://Stackoverflow.com/users/312957", "pm_score": 0, "selected": false, "text": "<p>Why it is preferable to use String.Empty in C# and therefore a public constant in other languages, is that constants are static, therefore only take up one instance in memory.</p>\n\n<p>Every time you do something like this: -</p>\n\n<pre><code>stringVariable = \"\";\n</code></pre>\n\n<p>you are creating a new instance of a null string, and pointing to it with stringVariable.</p>\n\n<p>So every time you make an assignment of \"\" to a variable (pointer), that \"\" null string is a new string instance until it no longer has any pointer assignments to it.</p>\n\n<p>initializing strings by pointing them all to the same constant, means only one \"\" is ever created and every initialized variable points to the same null string.</p>\n\n<p>It may sound trivial, but creating and destroying strings is much more resource intensive than creating pointers (variables) and pointing them to an existing string.</p>\n\n<p>As string initialization is common, it is good practice to do: -</p>\n\n<pre><code>const String EMPTY_STRING = \"\";\nString variable1 = EMPTY_STRING;\nString variable2 = EMPTY_STRING;\nString variable3 = EMPTY_STRING;\nString variable4 = EMPTY_STRING;\nString variable5 = EMPTY_STRING;\n</code></pre>\n\n<p>You have created 5 string pointers but only 1 string</p>\n\n<p>rather than: -</p>\n\n<pre><code>String variable1 = \"\";\nString variable2 = \"\";\nString variable3 = \"\";\nString variable4 = \"\";\nString variable5 = \"\";\n</code></pre>\n\n<p>You have created 5 string pointers and 5 separate null strings.</p>\n\n<p>Not a major issue in this case, but in thousands of lines of code in dozens of classes, it is unnecessary memory waste and processor use, creating another null string variable, when they can all point to the same one, making applications much more efficient.</p>\n\n<p><strong>Of course, compilers should be clever enough to determine several static strings and reuse duplicates, but why assume?</strong></p>\n\n<p>Also, it's less prone to introducing errors as \"\" and \" \" will both compile, yet you may miss the space you accidentally added which could produce spurious run time errors, for example conditional logic such as: -</p>\n\n<pre><code>myvariable = \" \";\nWhile (myVariable == \"\"){\n ...\n}\n</code></pre>\n\n<p>Code inside the while block is unreachable because myVariable will not satisfy the condition on the first iteration. The error of initializing with \" \" instead of \"\" is easy to miss, whereas: -</p>\n\n<pre><code>myvariable = EMPTY_STRING;\nWhile (myVariable == EMPTY_STRING){\n ...\n}\n</code></pre>\n\n<p>... is less likely to cause runtime errors, especially as misspelling EMPTY_STRING would generate a compile error instead of having to catch the error at run time.</p>\n\n<p>The cleanest solution, would be to create a static class that contains members of all kinds of string constants you need, should you require more than just an empty string.</p>\n\n<pre><code>public static class StringConstants{\n public static String Empty = \"\";\n public static String EMail = \"mailto:%s\";\n public static String http = \"http://%s\";\n public static String https = \"https://%s\";\n public static String LogEntry = \"TimeStamp:%tYmdHMSL | LogLevel:%s| Type:%s | Message: '%s'\";\n\n}\n\nString myVariable = StringConstants.Empty;\n</code></pre>\n\n<p>You may even be able to extend the native String object, depending on your language.</p>\n" }, { "answer_id": 4358133, "author": "Antony Booth", "author_id": 312957, "author_profile": "https://Stackoverflow.com/users/312957", "pm_score": 2, "selected": false, "text": "<p>David Arno states: -</p>\n\n<blockquote>\n <p>Ironically the whole point of\n constants is to make them easily\n changeable</p>\n</blockquote>\n\n<p>This is simply not true. The whole point of constants is reuse of the same value and for greater readability.</p>\n\n<p>It is very rare that constant values are changed (hence the name). It is more often that configuration values are changed, but persisted as data somewhere (like a config file or registry entry)</p>\n\n<p>Since early programming, constants have been used to turn things like cryptic hex values such as 0xff6d8da412 into something humanly readable without <strong>ever</strong> intending to change the values.</p>\n\n<pre><code>const int MODE_READ = 0x000000FF;\nconst int MODE_EXECUTE = 0x00FF0000;\nconst int MODE_WRITE = 0x0000FF00;\nconst int MODE_READ_WRITE = 0x0000FFFF;\n</code></pre>\n" }, { "answer_id": 5458791, "author": "Ian Ringrose", "author_id": 57159, "author_profile": "https://Stackoverflow.com/users/57159", "pm_score": 0, "selected": false, "text": "<p>If you every wish to store \"empty\" strings in a nullable string column in oracle, you will have to change the definition of EMPTY_STRING to be something other than \"\"! (I recall from the last time I was forced to use Oracle that it does not know the difference between an empty string and a null string).</p>\n\n<p>However this should be done in your data access layer so the rest of the app does not know about it, and/or sort out your data model so you don’t need to store empty string AND null strings in the same column.</p>\n" }, { "answer_id": 64368357, "author": "Gedion Otieno", "author_id": 10380096, "author_profile": "https://Stackoverflow.com/users/10380096", "pm_score": 0, "selected": false, "text": "<p>Or simply just have it as string.IsNullOrEmpty(otherString)</p>\n" } ]
2008/10/17
[ "https://Stackoverflow.com/questions/213985", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1318/" ]
I have a co-worker that swears by ``` //in a singleton "Constants" class public static final String EMPTY_STRING = ""; ``` in a constants class available throughout the project. That way, we can write something like ``` if (Constants.EMPTY_STRING.equals(otherString)) { ... } ``` instead of ``` if ("".equals(otherString)) { ... } ``` I say it's 1. not worth it--it doesn't save any space in the heap/stack/string pool, 2. ugly 3. abuse of a constants class. Who is the idiot here?
String literals are interned by default, so no matter how many times you refer to **""** in code, there will only be one empty String object. I don't see any benefit in declaring EMPTY\_STRING. Otherwise, you might as well declare ONE, TWO, THREE, FOUR, etc. for integer literals. Of course, if you want to change the value of EMPTY\_STRING later, it's handy to have it in one place ;)
214,009
<p>As kind of a followup to <a href="https://stackoverflow.com/questions/210446/what-is-the-best-way-for-a-client-app-to-find-a-server-on-a-local-network-in-c">this question</a> I've gotten a solution working on my local machine, but not on a machine on the network.</p> <p>I don't know too much about sockets other than that basics, so bear with me. The goal is for a client to look for a server on a local network, and this is the result of some cut/paste/edit code. </p> <p>This is the client code:</p> <pre><code>IPEndPoint ipep = new IPEndPoint(IPAddress.Parse("127.0.0.1"), 10294); byte[] data = new byte[1024]; public Form1() { InitializeComponent(); } private void button1_Click(object sender, EventArgs e) { Socket client = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp); client.SetSocketOption(SocketOptionLevel.IP, SocketOptionName.MulticastTimeToLive, 10); string welcome = "What's your IP?"; data = Encoding.ASCII.GetBytes(welcome); client.SendTo(data, data.Length, SocketFlags.None, ipep); IPEndPoint server = new IPEndPoint(IPAddress.Any, 0); EndPoint tmpRemote = (EndPoint)server; data = new byte[1024]; int recv = client.ReceiveFrom(data, ref tmpRemote); this.IP.Text = ((IPEndPoint)tmpRemote).Address.ToString(); //set textbox this.Port.Text = Encoding.ASCII.GetString(data, 0, recv); //set textbox client.Close(); } </code></pre> <p>This is the server code:</p> <pre><code>int recv; byte[] data = new byte[1024]; IPEndPoint ipep = new IPEndPoint(IPAddress.Any, 10294); Socket newsock = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp); newsock.Bind(ipep); newsock.SetSocketOption(SocketOptionLevel.IP, SocketOptionName.AddMembership, new MulticastOption(IPAddress.Any,IPAddress.Parse("127.0.0.1"))); while (true) { Console.WriteLine("Waiting for a client..."); IPEndPoint sender = new IPEndPoint(IPAddress.Any, 0); EndPoint tmpRemote = (EndPoint)(sender); data = new byte[1024]; recv = newsock.ReceiveFrom(data, ref tmpRemote); Console.WriteLine("Message received from {0}:", tmpRemote.ToString()); Console.WriteLine(Encoding.ASCII.GetString(data, 0, recv)); string welcome = "7010"; data = Encoding.ASCII.GetBytes(welcome); newsock.SendTo(data, data.Length, SocketFlags.None, tmpRemote); } </code></pre> <p>It works find on my local machine (both server and client) but when I try another machine on the same network I get "An existing connection was forcibly closed by the remote host"</p> <p>I realize I need to add a lot of try/catch but I'm just trying to get a handle on how this works first.</p>
[ { "answer_id": 214629, "author": "Andrew Edgecombe", "author_id": 11694, "author_profile": "https://Stackoverflow.com/users/11694", "pm_score": 3, "selected": true, "text": "<p>I have to start by saying that I know nothing about C#, but...</p>\n\n<p>Looking at the definition of the <code>ipep</code> in the client code, it looks like you're trying to send your data to yourself, rather than broadcast it (as has been suggested in your other question). The thing that caught my attention was that \"127.0.0.1\" is the address of \"localhost\".</p>\n\n<p>That would explain why it works nicely when you're running both the client and server on the one machine, as it <em>will</em> be sending to itself.</p>\n\n<p>I would expect that correct endpoint would be for a broadcast address (eg. \"255.255.255.255\") - although you could also choose the broadcast address of the local network that you're on, depending on how widely you wish to broadcast.</p>\n" }, { "answer_id": 2382669, "author": "ForbesLindesay", "author_id": 272958, "author_profile": "https://Stackoverflow.com/users/272958", "pm_score": -1, "selected": false, "text": "<pre><code>IPEndPoint ipep = new IPEndPoint(IPAddress.Parse(\"127.0.0.1\"), 10294);\n</code></pre>\n\n<p>Should become:</p>\n\n<pre><code>IPEndPoint ipep = new IPEndPoint(IPAddress.Parse(\"255.255.255.255\"), 10294);\n</code></pre>\n\n<p>And</p>\n\n<pre><code>newsock.SetSocketOption(SocketOptionLevel.IP, SocketOptionName.AddMembership, new MulticastOption(IPAddress.Any, IPAddress.Parse(\"127.0.0.1\")));\n</code></pre>\n\n<p>Should Become</p>\n\n<pre><code>newsock.SetSocketOption(SocketOptionLevel.IP, SocketOptionName.AddMembership, new MulticastOption(IPAddress.Any, IPAddress.Parse(\"255.255.255.255\")));\n</code></pre>\n\n<p>I think.</p>\n\n<p>OK, this doesn't work, so something's still wrong.</p>\n" } ]
2008/10/17
[ "https://Stackoverflow.com/questions/214009", "https://Stackoverflow.com", "https://Stackoverflow.com/users/23822/" ]
As kind of a followup to [this question](https://stackoverflow.com/questions/210446/what-is-the-best-way-for-a-client-app-to-find-a-server-on-a-local-network-in-c) I've gotten a solution working on my local machine, but not on a machine on the network. I don't know too much about sockets other than that basics, so bear with me. The goal is for a client to look for a server on a local network, and this is the result of some cut/paste/edit code. This is the client code: ``` IPEndPoint ipep = new IPEndPoint(IPAddress.Parse("127.0.0.1"), 10294); byte[] data = new byte[1024]; public Form1() { InitializeComponent(); } private void button1_Click(object sender, EventArgs e) { Socket client = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp); client.SetSocketOption(SocketOptionLevel.IP, SocketOptionName.MulticastTimeToLive, 10); string welcome = "What's your IP?"; data = Encoding.ASCII.GetBytes(welcome); client.SendTo(data, data.Length, SocketFlags.None, ipep); IPEndPoint server = new IPEndPoint(IPAddress.Any, 0); EndPoint tmpRemote = (EndPoint)server; data = new byte[1024]; int recv = client.ReceiveFrom(data, ref tmpRemote); this.IP.Text = ((IPEndPoint)tmpRemote).Address.ToString(); //set textbox this.Port.Text = Encoding.ASCII.GetString(data, 0, recv); //set textbox client.Close(); } ``` This is the server code: ``` int recv; byte[] data = new byte[1024]; IPEndPoint ipep = new IPEndPoint(IPAddress.Any, 10294); Socket newsock = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp); newsock.Bind(ipep); newsock.SetSocketOption(SocketOptionLevel.IP, SocketOptionName.AddMembership, new MulticastOption(IPAddress.Any,IPAddress.Parse("127.0.0.1"))); while (true) { Console.WriteLine("Waiting for a client..."); IPEndPoint sender = new IPEndPoint(IPAddress.Any, 0); EndPoint tmpRemote = (EndPoint)(sender); data = new byte[1024]; recv = newsock.ReceiveFrom(data, ref tmpRemote); Console.WriteLine("Message received from {0}:", tmpRemote.ToString()); Console.WriteLine(Encoding.ASCII.GetString(data, 0, recv)); string welcome = "7010"; data = Encoding.ASCII.GetBytes(welcome); newsock.SendTo(data, data.Length, SocketFlags.None, tmpRemote); } ``` It works find on my local machine (both server and client) but when I try another machine on the same network I get "An existing connection was forcibly closed by the remote host" I realize I need to add a lot of try/catch but I'm just trying to get a handle on how this works first.
I have to start by saying that I know nothing about C#, but... Looking at the definition of the `ipep` in the client code, it looks like you're trying to send your data to yourself, rather than broadcast it (as has been suggested in your other question). The thing that caught my attention was that "127.0.0.1" is the address of "localhost". That would explain why it works nicely when you're running both the client and server on the one machine, as it *will* be sending to itself. I would expect that correct endpoint would be for a broadcast address (eg. "255.255.255.255") - although you could also choose the broadcast address of the local network that you're on, depending on how widely you wish to broadcast.
214,017
<p>Consider I'm interfacing with an external system that will send a message (DB table, message queue, web service) in some format. In the "message header" there is the "MessageType" that is a number from 1 to 20. The MessageType defines what to do with the rest of the message. There are things like new, modified, deleted, canceled...</p> <p>My first inclination was to setup an enumeration and define all the types. Then parse the number into an enum type. With it as an enum I would setup the typical switch case system and call a particular method for each of the message types.</p> <p>One big concern is maintenance.<br> A switch / case system is bulky and teadious but, it's really simple.<br> Various table / configuration systems can be difficult for someone else to grok and add new messages or tweak existing messages.</p> <p>For 12 or so MessageTypes the switch/case system seems quite reasonable. What would be a reasonable cut-off point to switch to a table driven system?</p> <p>What kinds of systems are considered best for handling these types of problems?</p> <p>I'm setting a tag for both C# and Java here because it's definitly a common problem. There are many other languages with the same issue.</p>
[ { "answer_id": 214032, "author": "Jon Skeet", "author_id": 22656, "author_profile": "https://Stackoverflow.com/users/22656", "pm_score": 3, "selected": false, "text": "<p>In Java, you can make it an enum and give behaviour to the different values (although with 100 values, I'd hope that each type of behaviour is briefly, calling out to \"proper\" classes).</p>\n\n<p>In C#, you can have a map from value to some appropriate delegate type - then when you statically construct the map, you can either use lambda expressions or method group conversions as appropriate.</p>\n\n<p>Having said that, setting up the map is going to be just as ugly as a switch statement. If each switch statement is just a single method call, you might like to try this sort of format:</p>\n\n<pre><code>switch (messageType)\n{\n case 0: HandleLogin(message); break;\n case 50: SaveCurrentDocument(message); break;\n case 100: HandleLogout(message); break;\n}\n</code></pre>\n\n<p>(etc). I know it's against normal conventions, but it can be quite neat for the odd exceptional situation like this. If you only need the numbers in one place, then there's little point in introducing constants - basically the line containing the number effectively <em>is</em> the constant definition!</p>\n" }, { "answer_id": 214073, "author": "Vivek", "author_id": 7418, "author_profile": "https://Stackoverflow.com/users/7418", "pm_score": 1, "selected": false, "text": "<p>How about having a <code>Dictionary&lt;MessageType, ProcessMessageDelegate&gt;</code> to store those methods by their message types? During initialization of the class, register all the methods in this dictionary. Then call the appropriate method. Following is the pseudo code:</p>\n\n<pre><code> delegate void ProcessMessageDelegate(Message message)\n\n public class MyMessageProcessor\n {\n Dictionary&lt;int, ProcessMessageDelegate&gt; methods;\n\n public void Register( int messageType, \n ProcessMessageDelegate processMessage)\n {\n methods[messageType] = processMessage;\n }\n\n public void ProcessMessage(int messageType, Message message)\n {\n if(methods.ContainsKey(messageType))\n {\n methods[messageType](message);\n }\n }\n }\n</code></pre>\n\n<p>To register methods:</p>\n\n<pre><code> myProcessor.Register(0, ProcessMessageOfType0);\n myProcessor.Register(1, ProcessMessageOfType1);\n myProcessor.Register(2, ProcessMessageOfType2);\n ...\n</code></pre>\n\n<p><strong>Edit</strong>: I realized Jon already suggests having a map which now makes my answer redundant. But I don't understand why a statically constructed map is uglier than switch case?</p>\n" }, { "answer_id": 214206, "author": "Robert Rossney", "author_id": 19403, "author_profile": "https://Stackoverflow.com/users/19403", "pm_score": 0, "selected": false, "text": "<p>This is how I've done this in C#. </p>\n\n<p>I think this approach is actually not so ugly as all that, It gets less ugly as the number of message types increases: to implement a new message type, you just have to add a value to your Enum and mark the new message handler class with an attribute.</p>\n\n<p>And there are circumstances where being able to load your message handlers from an assembly at runtime is a very powerful feature; you can have a single executable that behaves differently based on which message-handler assembly is installed.</p>\n\n<p>Start by creating an interface for the message handler (we'll call it <code>IMessageHandler</code>) and an Enum for the message type (we'll call it <code>MessageType</code>).</p>\n\n<p>Next, create a class called <code>MessageHandlerAttribute</code>:</p>\n\n<pre><code>public class MessageHandlerAttribute : System.Attribute\n{\n public MessageType MessageType { get; set; }\n}\n</code></pre>\n\n<p>Now implement each message handler as a separate class, and mark each class with its message type attribute. If a message handler can handle multiple types of message, you can put multiple attributes on it:</p>\n\n<pre><code>[MessageHandler(MessageType=MessageType.Login)]\npublic class LoginMessageHandler : IMessageHandler\n{\n ...\n}\n</code></pre>\n\n<p>It's important that these message handlers all have parameterless constructors. I can't think of a good reason that you'd <em>want</em> a message handler's constructor to take parameters, but if any does, the code below can't handle it.</p>\n\n<p>Build all the message handlers into the same assembly, and be sure you have a way to know its path at runtime. (That's the big point of failure for this approach.)</p>\n\n<p>Now we can use Reflection to build a map of message handlers at runtime:</p>\n\n<pre><code>using System.Reflection;\n...\nAssembly mhAssembly = Assembly.LoadFrom(mhAssemblyPath);\nDictionary&lt;MessageType, IMessageHandler&gt; mhMap = new Dictionary&lt;MessageType, IMessageHandler&gt;();\nforeach (Type t in mhAssembly.GetExportedTypes())\n{\n if (t.GetInterface(\"IMessageHandler\") != null)\n {\n MessageHandlerAttribute list = (MessageHandlerAttribute[])t.GetCustomAttributes(\n typeof(MessageHandlerAttribute), false);\n foreach (MessageHandlerAttribute att in list)\n {\n MessageType mt = att.MessageType;\n Debug.Assert(!mhMap.ContainsKey(mt));\n IMessageHandler mh = mhAssembly.CreateInstance(\n t.FullName,\n true,\n BindingFlags.CreateInstance,\n null,\n new object[] { },\n null,\n null);\n mhMap.Add(mt, mh);\n }\n }\n // depending on your application, you might want to check mhMap now to make\n // sure that every MessageType value is in it.\n}\nreturn mhMap;\n</code></pre>\n\n<p>Now when you get a message, you can handle it like this:</p>\n\n<pre><code>Debug.Assert(MhMap.ContainsKey(Message.MessageType));\nIMessageHandler mh = MhMap[Message.MessageType];\nmh.HandleMessage(Message);\n</code></pre>\n\n<p>This code's all based on code I have in a production system right now; I've changed it slightly (so that the message handlers implement an interface instead of deriving from an abstract class, and that it handles multiple message handler attributes), which has probably introduced bugs into it.</p>\n" }, { "answer_id": 214603, "author": "ddimitrov", "author_id": 18187, "author_profile": "https://Stackoverflow.com/users/18187", "pm_score": 1, "selected": false, "text": "<p>Have a handler interface like this:</p>\n\n<pre><code>interface MessageHandler {\n void processMessage(Message msg) throws Exception;\n int[] queryInterestingMessageIds();\n int queryPriority(int messageId); // this one is optional\n}\n</code></pre>\n\n<p>Locate, instantiate and register your handlers. You might want to use some reflection-based mechanism like <a href=\"http://java.sun.com/javase/6/docs/api/java/util/ServiceLoader.html\" rel=\"nofollow noreferrer\">ServiceLoader</a>, Spring (explicit config or <a href=\"http://static.springframework.org/spring/docs/2.5.x/reference/beans.html#beans-classpath-scanning\" rel=\"nofollow noreferrer\">classpath scanning</a> amd possibly autowiring) or plain properties file</p>\n\n<p>The registration should pass each handler to a WhateverManager class which would hold internally a map (or arry indexed by message ID) of collections of handlers. If you expect to have multiple handlers, you can use the <em>queryPriority(int)</em> method to resolve the order of handling (otherwise you can treat it as an error and throw an exception at config time). It's a good practice to NOT use static map for registration.</p>\n\n<p>If you decide to support multiple handlers for a message, you might want to daisychain them. In such case one way is to change the signature as follows: </p>\n\n<pre><code> Message processMessage(Message msg, Message original) throws Exception;\n</code></pre>\n" } ]
2008/10/17
[ "https://Stackoverflow.com/questions/214017", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2862/" ]
Consider I'm interfacing with an external system that will send a message (DB table, message queue, web service) in some format. In the "message header" there is the "MessageType" that is a number from 1 to 20. The MessageType defines what to do with the rest of the message. There are things like new, modified, deleted, canceled... My first inclination was to setup an enumeration and define all the types. Then parse the number into an enum type. With it as an enum I would setup the typical switch case system and call a particular method for each of the message types. One big concern is maintenance. A switch / case system is bulky and teadious but, it's really simple. Various table / configuration systems can be difficult for someone else to grok and add new messages or tweak existing messages. For 12 or so MessageTypes the switch/case system seems quite reasonable. What would be a reasonable cut-off point to switch to a table driven system? What kinds of systems are considered best for handling these types of problems? I'm setting a tag for both C# and Java here because it's definitly a common problem. There are many other languages with the same issue.
In Java, you can make it an enum and give behaviour to the different values (although with 100 values, I'd hope that each type of behaviour is briefly, calling out to "proper" classes). In C#, you can have a map from value to some appropriate delegate type - then when you statically construct the map, you can either use lambda expressions or method group conversions as appropriate. Having said that, setting up the map is going to be just as ugly as a switch statement. If each switch statement is just a single method call, you might like to try this sort of format: ``` switch (messageType) { case 0: HandleLogin(message); break; case 50: SaveCurrentDocument(message); break; case 100: HandleLogout(message); break; } ``` (etc). I know it's against normal conventions, but it can be quite neat for the odd exceptional situation like this. If you only need the numbers in one place, then there's little point in introducing constants - basically the line containing the number effectively *is* the constant definition!
214,037
<p>I really like Entity Framework, but there are some key pieces that are a challenge to me. Can anyone tell me how to filter an EntityDataSource on an Association column? EF hides the FK values and instead has an Association property. Given an Entity, Person, with a PersonType association, I would have expected something like this to work if I want to filter my Person Entity by Type:</p> <pre><code>GridDataSource.EntityTypeFilter = "it.PersonType.PersonTypeID = 1"; </code></pre> <p>or</p> <pre><code>GridDataSource.Where = "it.PersonType.PersonTypeID = '1'"; </code></pre> <p>or even</p> <pre><code>GridDataSource.WhereParameters.Add(new Parameter("it.PersonType.PersonTypeID", DbType.Object, "1")); </code></pre> <p>but none of those work. Anybody know how to do this?</p>
[ { "answer_id": 639287, "author": "Davy Landman", "author_id": 11098, "author_profile": "https://Stackoverflow.com/users/11098", "pm_score": 0, "selected": false, "text": "<p>Have you tried applying the filter in memory using LINQ? (or Perhaps against the database?)</p>\n\n<pre><code>var personType = new PersonType { Id = 1 };\nvar query = PersonDataSource.Where(p =&gt; p.PersonType.Equals(personType));\n// use this query as the DataSource for your GridView\n</code></pre>\n\n<p>I must admit I haven't done anything like this, but I have used this trick to update/create an entity without loading the associated entities first. </p>\n" }, { "answer_id": 674782, "author": "Keck", "author_id": 78699, "author_profile": "https://Stackoverflow.com/users/78699", "pm_score": 2, "selected": true, "text": "<p>I think the answer you're looking for involves using the Include method, such as:</p>\n\n<pre><code>entities.it.Include(\"PersonType\").Where(a =&gt; a.PersonType.PersonTypeID = '1');\n</code></pre>\n" } ]
2008/10/17
[ "https://Stackoverflow.com/questions/214037", "https://Stackoverflow.com", "https://Stackoverflow.com/users/16426/" ]
I really like Entity Framework, but there are some key pieces that are a challenge to me. Can anyone tell me how to filter an EntityDataSource on an Association column? EF hides the FK values and instead has an Association property. Given an Entity, Person, with a PersonType association, I would have expected something like this to work if I want to filter my Person Entity by Type: ``` GridDataSource.EntityTypeFilter = "it.PersonType.PersonTypeID = 1"; ``` or ``` GridDataSource.Where = "it.PersonType.PersonTypeID = '1'"; ``` or even ``` GridDataSource.WhereParameters.Add(new Parameter("it.PersonType.PersonTypeID", DbType.Object, "1")); ``` but none of those work. Anybody know how to do this?
I think the answer you're looking for involves using the Include method, such as: ``` entities.it.Include("PersonType").Where(a => a.PersonType.PersonTypeID = '1'); ```