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
|
---|---|---|---|---|---|---|
153,372 |
<p>I am trying to create a StringNameSpaceBinding using the wsadmin tool of Websphere 6.1</p>
<p>Here are the steps i take
set cell [$AdminConfig getid /Cell:cell/]
$AdminConfig create StringNameSpaceBinding $cell { {name bindname} {nameInNameSpace Bindings/string} {stringToBind "This is the String value that gets bound"} }</p>
<p>But when i run this last step i get an error like this:
WASX7015E: Exception running command: "$AdminConfig create StringNameSpaceBinding $cell { {name bindname} {nameInNameSpace Bindings/string} {stringToBind "This is the String value that gets bound"} }"; exception information:
com.ibm.ws.scripting.ScriptingException: WASX7444E: Invalid parameter value "" for parameter "parent config id" on command "create"</p>
<p>Any idea what could be up with this?</p>
<p>Thanks
Damien</p>
|
[
{
"answer_id": 3836682,
"author": "Isaac",
"author_id": 443716,
"author_profile": "https://Stackoverflow.com/users/443716",
"pm_score": 3,
"selected": true,
"text": "<p>I'm betting that the following command:</p>\n\n<pre><code>set cell [$AdminConfig getid /Cell:cell/]\n</code></pre>\n\n<p>Doesn't work. Most likely, <code>cell</code> is not the name of your cell.\nYou don't need to specify a cell name; there's only one cell in the WAS topology. I would change this to:</p>\n\n<pre><code>set cell [$AdminConfig getid /Cell:/]\n</code></pre>\n\n<p>Good luck.</p>\n"
},
{
"answer_id": 4406507,
"author": "jitendra",
"author_id": 537509,
"author_profile": "https://Stackoverflow.com/users/537509",
"pm_score": 1,
"selected": false,
"text": "<p>I have faced a similar issue and it is now resolved after removing both node and cell name from the following line:</p>\n\n<pre><code>cell = AdminConfig.getid('/Cell:/Node:/Server:WebSphere_Portal/')\n</code></pre>\n"
}
] |
2008/09/30
|
[
"https://Stackoverflow.com/questions/153372",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11612/"
] |
I am trying to create a StringNameSpaceBinding using the wsadmin tool of Websphere 6.1
Here are the steps i take
set cell [$AdminConfig getid /Cell:cell/]
$AdminConfig create StringNameSpaceBinding $cell { {name bindname} {nameInNameSpace Bindings/string} {stringToBind "This is the String value that gets bound"} }
But when i run this last step i get an error like this:
WASX7015E: Exception running command: "$AdminConfig create StringNameSpaceBinding $cell { {name bindname} {nameInNameSpace Bindings/string} {stringToBind "This is the String value that gets bound"} }"; exception information:
com.ibm.ws.scripting.ScriptingException: WASX7444E: Invalid parameter value "" for parameter "parent config id" on command "create"
Any idea what could be up with this?
Thanks
Damien
|
I'm betting that the following command:
```
set cell [$AdminConfig getid /Cell:cell/]
```
Doesn't work. Most likely, `cell` is not the name of your cell.
You don't need to specify a cell name; there's only one cell in the WAS topology. I would change this to:
```
set cell [$AdminConfig getid /Cell:/]
```
Good luck.
|
153,376 |
<p>We have similar code to the following in one of our projects. Can anyone explain (in simple English) why the fixed statement is needed here?</p>
<pre><code>class TestClass
{
int iMyVariable;
static void Main()
{
TestClass oTestClass = new TestClass();
unsafe
{
fixed (int* p = &oTestClasst.iMyVariable)
{
*p = 9;
}
}
}
}
</code></pre>
|
[
{
"answer_id": 153382,
"author": "Joel Coehoorn",
"author_id": 3043,
"author_profile": "https://Stackoverflow.com/users/3043",
"pm_score": 3,
"selected": false,
"text": "<p>You need it anywhere you do pointer arithmetic, to prevent the garbage collector from moving it around on you.</p>\n"
},
{
"answer_id": 153387,
"author": "Blair Conrad",
"author_id": 1199,
"author_profile": "https://Stackoverflow.com/users/1199",
"pm_score": 3,
"selected": false,
"text": "<p>The <a href=\"http://msdn.microsoft.com/en-us/library/f58wzh21(VS.80).aspx\" rel=\"noreferrer\">fixed statement</a> will \"pin\" the variable in memory so that the garbage collector doesn't move it around when collecting. If it did move the variable, the pointer would become useless and when you used it you'd be trying to access or modify something that you didn't intend to.</p>\n"
},
{
"answer_id": 153389,
"author": "David",
"author_id": 352116,
"author_profile": "https://Stackoverflow.com/users/352116",
"pm_score": 2,
"selected": false,
"text": "<p>Because you are running in unsafe mode (pointer), the fixed instruction allocate a specific memory space to that variable. If you didn't put the fixed instruction, the garbage collector could move in memory the variable anywhere, when he want.</p>\n\n<p>Hope this help.</p>\n"
},
{
"answer_id": 153390,
"author": "ilitirit",
"author_id": 9825,
"author_profile": "https://Stackoverflow.com/users/9825",
"pm_score": 5,
"selected": true,
"text": "<p>It fixes the pointer in memory. Garbage collected languages have the freedom to move objects around memory for efficiency. This is all transparent to the programmer because they don't really use pointers in \"normal\" CLR code. However, when you do require pointers, then you need to fix it in memory if you want to work with them.</p>\n"
},
{
"answer_id": 153442,
"author": "cgreeno",
"author_id": 6088,
"author_profile": "https://Stackoverflow.com/users/6088",
"pm_score": 2,
"selected": false,
"text": "<p><a href=\"http://msdn.microsoft.com/en-us/library/f58wzh21.aspx\" rel=\"nofollow noreferrer\">MSDN</a> has a very similar example. The fixed statement basically blocks garbage collection. In .Net if you use a pointer to a memory location the runtime can reallocate the object to a \"better\" location at any time. SO if you want to access memory directly you need to fix it in place.</p>\n"
}
] |
2008/09/30
|
[
"https://Stackoverflow.com/questions/153376",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/23790/"
] |
We have similar code to the following in one of our projects. Can anyone explain (in simple English) why the fixed statement is needed here?
```
class TestClass
{
int iMyVariable;
static void Main()
{
TestClass oTestClass = new TestClass();
unsafe
{
fixed (int* p = &oTestClasst.iMyVariable)
{
*p = 9;
}
}
}
}
```
|
It fixes the pointer in memory. Garbage collected languages have the freedom to move objects around memory for efficiency. This is all transparent to the programmer because they don't really use pointers in "normal" CLR code. However, when you do require pointers, then you need to fix it in memory if you want to work with them.
|
153,381 |
<p>I have to concatenate a bunch of Strings in Javascript and am searching for the fastest way to do so. Let's assume that the Javascript has to create a large XML-"file" that, naturally, consists of many small Strings. So I came up with:</p>
<pre><code> var sbuffer = [];
for (var idx=0; idx<10000; idx=idx+1) {
sbuffer.push(‘<xmltag>Data comes here... bla... </xmltag>’);
}
// Now we "send" it to the browser...
alert(sbuffer.join(”));
</code></pre>
<p>Do not pay any attention to the loop or the other "sophisticated" code which builds the example. </p>
<p>My question is: For an unknown number of Strings, do you have a faster algorithm / method / idea to concatenate many small Strings to a huge one?</p>
|
[
{
"answer_id": 153395,
"author": "Tomalak",
"author_id": 18771,
"author_profile": "https://Stackoverflow.com/users/18771",
"pm_score": 1,
"selected": false,
"text": "<p>I think you are quite close to the optimum. YMMV, a great deal of speed is gained or lost within the JavaScript engine of the host process (e.g. browser).</p>\n"
},
{
"answer_id": 153402,
"author": "Sam Hasler",
"author_id": 2541,
"author_profile": "https://Stackoverflow.com/users/2541",
"pm_score": 4,
"selected": false,
"text": "<p>The question <a href=\"https://stackoverflow.com/questions/112158/javascript-string-concatenation\">JavaScript string concatenation</a> has an accepted answer that links to a <a href=\"http://www.sitepen.com/blog/2008/05/09/string-performance-an-analysis/\" rel=\"nofollow noreferrer\">very good comparison of JavaScript string concatenation performance</a>.</p>\n\n<p><strong>Edit:</strong>\nI would have thought that you could eek out a little more performance by using Duff's device as the article suggests.</p>\n"
},
{
"answer_id": 153403,
"author": "John Topley",
"author_id": 1450,
"author_profile": "https://Stackoverflow.com/users/1450",
"pm_score": 1,
"selected": false,
"text": "<p>I think that pushing the strings onto an array and then joining the array is the fastest technique for string concatenation in JavaScript. There is some supporting evidence in this <a href=\"http://www.quirksmode.org/dom/innerhtml.html\" rel=\"nofollow noreferrer\">discussion about W3C DOM vs. innerHTML</a>. Note the difference between the innerHTML 1 and innerHTML 2 results.</p>\n"
},
{
"answer_id": 153417,
"author": "Barth",
"author_id": 20986,
"author_profile": "https://Stackoverflow.com/users/20986",
"pm_score": 1,
"selected": false,
"text": "<p>As far as I know, your algorithm is good and known as a performant solution to the string concatenation problem.</p>\n"
},
{
"answer_id": 153646,
"author": "Sergey Ilinsky",
"author_id": 23815,
"author_profile": "https://Stackoverflow.com/users/23815",
"pm_score": 5,
"selected": true,
"text": "<p>Changing the line:</p>\n\n<p><code>sbuffer.push(‘Data comes here... bla... ’); </code></p>\n\n<p>to </p>\n\n<p><code>sbuffer[sbuffer.length] = ‘Data comes here... bla... ’; </code></p>\n\n<p>will give you 5-50% speed gain (depending on browser, in IE - gain will be highest)</p>\n\n<p>Regards.</p>\n"
},
{
"answer_id": 154393,
"author": "Thevs",
"author_id": 8559,
"author_profile": "https://Stackoverflow.com/users/8559",
"pm_score": 0,
"selected": false,
"text": "<p>Beware of IE bad garbage collector! What do you suppose to do with your array after using? Probably it will get GC'd?</p>\n\n<p>You can gain perfornace on concatenating with joins, and then lose on post-GC'ing. On the other hand if you leave an array in scope all the time, and NOT reuse it, that can be a good solution. </p>\n\n<p>Personally I'd like the simpliest solution: just to use += operator.</p>\n"
},
{
"answer_id": 156407,
"author": "Andrew Hedges",
"author_id": 11577,
"author_profile": "https://Stackoverflow.com/users/11577",
"pm_score": 0,
"selected": false,
"text": "<p>You might get a little more speed by <a href=\"https://stackoverflow.com/questions/137534/\">buffering</a>.</p>\n"
}
] |
2008/09/30
|
[
"https://Stackoverflow.com/questions/153381",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/13209/"
] |
I have to concatenate a bunch of Strings in Javascript and am searching for the fastest way to do so. Let's assume that the Javascript has to create a large XML-"file" that, naturally, consists of many small Strings. So I came up with:
```
var sbuffer = [];
for (var idx=0; idx<10000; idx=idx+1) {
sbuffer.push(‘<xmltag>Data comes here... bla... </xmltag>’);
}
// Now we "send" it to the browser...
alert(sbuffer.join(”));
```
Do not pay any attention to the loop or the other "sophisticated" code which builds the example.
My question is: For an unknown number of Strings, do you have a faster algorithm / method / idea to concatenate many small Strings to a huge one?
|
Changing the line:
`sbuffer.push(‘Data comes here... bla... ’);`
to
`sbuffer[sbuffer.length] = ‘Data comes here... bla... ’;`
will give you 5-50% speed gain (depending on browser, in IE - gain will be highest)
Regards.
|
153,388 |
<p>I'm really sick of this problem. Google searches always seem to suggest "delete all bpls for the package", "delete all dcus". Sometimes this just-does-not-work. Hopefully I can get some other ideas here.</p>
<p>I have a package written in-house, which had been installed without issue a few months ago. Having made a few changes to the source, I figured it was time to recompile/reinstall the package. Now I get two errors, the first if I choose "install" is</p>
<p><em>Access violation at address 02422108 in module 'dcc100.dll'. Read of address 00000000.</em></p>
<p>...or if I try to build/compile the package, I get</p>
<p><em>[Pascal Fatal Error] F2084 Internal Error: LA33</em></p>
<p>This is one of those Delphi problems that seems to occur time and time again for many of us. Would be great if we could collate a response something along the lines of "any one or combination of these steps <em>might</em> fix it, but if you do <em>all</em> these steps it <em>will</em> fix it...."</p>
<p>At the moment, I've removed all references to the bpl/dcp files for this package, but still getting the same error...</p>
<p>Using BDS2006 (Delphi)</p>
<p><em>Update 01-Oct-2008: I managed to solve this - see my post below. As I can't accept my own answer, I'm not entirely sure what to do here. Obviously these types of issues occur frequently for some people, so I'll leave it open for a while to get other suggestions. Then I guess if someone collates all the info into a super-post, I can accept the answer</em></p>
|
[
{
"answer_id": 153435,
"author": "Lars Truijens",
"author_id": 1242,
"author_profile": "https://Stackoverflow.com/users/1242",
"pm_score": 3,
"selected": false,
"text": "<p>These are bugs in the compiler/linker. You can find many references of these bugs on the internet in different Delphi versions, but they are not always the same bugs. That makes it difficult to give one solution for all those different kind of problems.</p>\n\n<p>General solutions that might fix it are, as you noted:</p>\n\n<ul>\n<li>Remove *.dcp *.dcpil *.dcu *.dcuil *.bpl *.dll </li>\n<li>Rewrite your code in another way </li>\n<li>Tinker with compiler options </li>\n<li>Get the latest Delphi version</li>\n</ul>\n\n<p>I personally found one of such bugs to be resolved if I turned off Range Checking. Others are solved if you don't use generics from another unit. And one was solved if the unit name and class name was renamed to be smaller.</p>\n\n<p>And of course you should report any problem you have on <a href=\"http://qc.codegear.com\" rel=\"noreferrer\">http://qc.codegear.com</a></p>\n"
},
{
"answer_id": 156746,
"author": "Graza",
"author_id": 11820,
"author_profile": "https://Stackoverflow.com/users/11820",
"pm_score": 5,
"selected": true,
"text": "<p>I managed to solve this, following the below procedure</p>\n\n<ol>\n<li>Create a new package</li>\n<li>One by one, add the components to the package, compile & install, until it failed.</li>\n<li>Investigate the unit causing the failure.</li>\n</ol>\n\n<p>As it turns out, the unit in question had a class constant array, eg</p>\n\n<pre><code>TMyClass = class(TComponent)\nprivate\n const ErrStrs: array[TErrEnum] of string\n = ('', //erOK\n 'Invalid user name or password', //erInvUserPass\n 'Trial Period has Expired'); //erTrialExp\nprotected\n ...\npublic\n ...\nend;\n</code></pre>\n\n<p>So it appears that Delphi does not like class constants (or perhaps class constant arrays) in package components</p>\n\n<p><em>Update: and yes, this has been reported to codegear</em></p>\n"
},
{
"answer_id": 3699377,
"author": "bjaastad_e",
"author_id": 446105,
"author_profile": "https://Stackoverflow.com/users/446105",
"pm_score": 1,
"selected": false,
"text": "<p>I had a similar case, where the solution was to remove the file urlmon.dcu from /lib/debug.</p>\n\n<p>It also worked to turn off \"use debug .dcus\" altogether. This of course is not desirable, but you can use it to check whether the problem lies with any of your own units, or with any of delphi's units.</p>\n"
},
{
"answer_id": 4734548,
"author": "Biz",
"author_id": 581317,
"author_profile": "https://Stackoverflow.com/users/581317",
"pm_score": 2,
"selected": false,
"text": "<p>Maybe the following step will be a better solution:<br>\nDeclare the array as a type and just define the class constant with this type, eg.</p>\n\n<pre><code>TMyArray = array[TErrEnum] of string;\n\nTMyClass = class(TComponent)\nprivate\n const ErrStrs: TMyArray\n = ('', //erOK\n 'Invalid user name or password', //erInvUserPass\n 'Trial Period has Expired'); //erTrialExp\nprotected\n ...\npublic\n ...\nend;\n</code></pre>\n\n<p>This makes the array declaration explicit.</p>\n"
},
{
"answer_id": 5492270,
"author": "Pete",
"author_id": 684716,
"author_profile": "https://Stackoverflow.com/users/684716",
"pm_score": 2,
"selected": false,
"text": "<p>I wasted several hours on this issue, deleting dcu's, etc to no avail. </p>\n\n<p>Finally, what worked for me was to uncheck Overflow Checking in Compiler Options, rebuilding the project, re-checking Overflow Checking, and rebuilding again. Voila! the problem has gone away. Go figure. (still using D7).</p>\n"
},
{
"answer_id": 14460535,
"author": "Riccardo Zorn",
"author_id": 1498906,
"author_profile": "https://Stackoverflow.com/users/1498906",
"pm_score": 0,
"selected": false,
"text": "<p>For me, in D2010 disabling the compiler option \"Emit runtime type information\" did the trick.</p>\n"
},
{
"answer_id": 21092689,
"author": "Marco",
"author_id": 138137,
"author_profile": "https://Stackoverflow.com/users/138137",
"pm_score": 1,
"selected": false,
"text": "<p>Try cleaning up the \"Output Directory\" so Delphi cannot fine dirty .DCUs and it is forced to bould the .PAS.\nSometimes this helps.\nIn case you didn't configure an \"output directory\", try deleting (or better moving in a backup folder) all the .DCU files.</p>\n"
},
{
"answer_id": 22510951,
"author": "user3310694",
"author_id": 3310694,
"author_profile": "https://Stackoverflow.com/users/3310694",
"pm_score": 1,
"selected": false,
"text": "<p>Disabling \"Include remote debug symbols\" from the Linker Options fixed the issue for me Delphi 2007, dll project</p>\n"
},
{
"answer_id": 24932745,
"author": "TmTron",
"author_id": 1041641,
"author_profile": "https://Stackoverflow.com/users/1041641",
"pm_score": 1,
"selected": false,
"text": "<p>Delphi XE3 Update 2</p>\n\n<blockquote>\n <p>F2084 Internal Error: URW1147</p>\n</blockquote>\n\n<p><strong>CASE 1:</strong></p>\n\n<p>problem was that a type was declared in a procedure of a generic class.</p>\n\n<pre><code>procedure TMyClass<TContainerItem, TTarget>.Foo();\ntype\n TCacheInfo = record\n UniqueList: TStringList;\n UniqueInfo: TUniqueInfo;\n end;\nvar\n CacheInfo: TCacheInfo;\n</code></pre>\n\n<p>moving the type declaration to the private part of the class declaration solved this issue.</p>\n\n<p><strong>CASE 2:</strong></p>\n\n<p>problem in this case was related to an optional parameter:</p>\n\n<pre><code>unit A.pas;\ninterface\ntype\n TTest<T> = class\n public\n type\n TTestProc = procedure (X: T) of object;\n constructor Create(TestProc_: TTestProc = nil);\n end;\n...\n</code></pre>\n\n<p>the internal compile error occurred as soon as a variable of the TTest class was declared in another unit: e.g. </p>\n\n<pre><code>unit B.pas:\n\nuses A;\nvar\n Test: TTest<TObject>;\n</code></pre>\n\n<p>solution was to make the constructor argument of <code>TestProc_</code> non-optional.</p>\n"
},
{
"answer_id": 27182471,
"author": "SeeMoreGain",
"author_id": 1793348,
"author_profile": "https://Stackoverflow.com/users/1793348",
"pm_score": 0,
"selected": false,
"text": "<p>From the various answers this error looks to be a generic unhandled exception by the compiler.</p>\n\n<p>My issue was caused by mistakenly calling <code>function X(someString:String) : Boolean;</code> which altered the string and returned a boolean, using <code>someString := X(someString);</code></p>\n"
},
{
"answer_id": 37021664,
"author": "Ash",
"author_id": 2462453,
"author_profile": "https://Stackoverflow.com/users/2462453",
"pm_score": 0,
"selected": false,
"text": "<p>As my experience of Internal Error is that, I re-wrote line by line and compile again and realized that some if else statement does not work like </p>\n\n<p>Internal Error Occurs </p>\n\n<pre><code> if (DataType in ASet) \n begin\n //do work\n end\n else if (DataType = B)\n begin\n //do work\n end\n else \n begin\n //do work\n end;\n</code></pre>\n\n<p>How I solved :</p>\n\n<pre><code>if (DataType = B)\n begin\n //do work\n end\n else if (DataType in ASet) \n begin\n //do work\n end\n else \n begin\n //do work\n end;\n</code></pre>\n\n<p>Just switched the conditions as example.Hope it helps.</p>\n"
},
{
"answer_id": 52420271,
"author": "Christian",
"author_id": 5935208,
"author_profile": "https://Stackoverflow.com/users/5935208",
"pm_score": 0,
"selected": false,
"text": "<p>I just experienced a similar behaviour, resulting in internal error LA30. \nThe reason were newly added string constants.\nAfter changing from\n <code>const cLogFileName : string = 'logfilename.log';</code></p>\n\n<p>to\n <code>const cLogFileName = 'logfilename.log';</code></p>\n\n<p>(and of course restarting of Delphi IDE) the error was not showing up anymore.</p>\n"
}
] |
2008/09/30
|
[
"https://Stackoverflow.com/questions/153388",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11820/"
] |
I'm really sick of this problem. Google searches always seem to suggest "delete all bpls for the package", "delete all dcus". Sometimes this just-does-not-work. Hopefully I can get some other ideas here.
I have a package written in-house, which had been installed without issue a few months ago. Having made a few changes to the source, I figured it was time to recompile/reinstall the package. Now I get two errors, the first if I choose "install" is
*Access violation at address 02422108 in module 'dcc100.dll'. Read of address 00000000.*
...or if I try to build/compile the package, I get
*[Pascal Fatal Error] F2084 Internal Error: LA33*
This is one of those Delphi problems that seems to occur time and time again for many of us. Would be great if we could collate a response something along the lines of "any one or combination of these steps *might* fix it, but if you do *all* these steps it *will* fix it...."
At the moment, I've removed all references to the bpl/dcp files for this package, but still getting the same error...
Using BDS2006 (Delphi)
*Update 01-Oct-2008: I managed to solve this - see my post below. As I can't accept my own answer, I'm not entirely sure what to do here. Obviously these types of issues occur frequently for some people, so I'll leave it open for a while to get other suggestions. Then I guess if someone collates all the info into a super-post, I can accept the answer*
|
I managed to solve this, following the below procedure
1. Create a new package
2. One by one, add the components to the package, compile & install, until it failed.
3. Investigate the unit causing the failure.
As it turns out, the unit in question had a class constant array, eg
```
TMyClass = class(TComponent)
private
const ErrStrs: array[TErrEnum] of string
= ('', //erOK
'Invalid user name or password', //erInvUserPass
'Trial Period has Expired'); //erTrialExp
protected
...
public
...
end;
```
So it appears that Delphi does not like class constants (or perhaps class constant arrays) in package components
*Update: and yes, this has been reported to codegear*
|
153,394 |
<p>I believe in OO, but not to the point where inappropriate designs/implementations should be used just to be "OO Compliant".</p>
<p>So, how to deal with the Serlvet/EJB/DataContainer layered architecture:</p>
<ul>
<li>Servlets receive requests and call a "business layer" (e.g. session EJBs)</li>
<li>The business layer locates DataContainers from the database and manipulates them to implement the business logic</li>
<li>DataContainers contain no real code, just get/set corresponding to the database.</li>
</ul>
<p>This approach has appeal; the DataContainers are clear in what they do and it's very easy to know where data comes from.</p>
<p>Aside from not being OO, this leads to unclear Business Layer classes that can be hard to name and hard to organize.</p>
<p>Even if we <strong>were</strong> trying to be more "OO" (e.g. putting some of these methods in the DataConatiners), some of these operations operate on more than one set of data.</p>
<p>How do you keep your Business Layer from getting confusingly procedural, but without polluting your DataContainers with business logic?</p>
<h3>Example</h3>
<pre><code>class UserServlet {
handleRequest() {
String id = request.get("id");
String name = request.get("name");
if (UserBizLayer.updateUserName(id,name))
response.setStatus(OK);
else
response.setStatus(BAD_REQUEST);
}
}
class UseBizLayer {
updateUserName(String id, String name) {
long key = toLong(id);
user = userDAO.find(key);
if user == null
return false;
if (!validateUserName(name))
return false;
user.setName(name);
userDAO.update(user);
return true;
}
validateUserName(String name) {
// do some validations and return
}
}
class User {
long key;
String name;
String email;
// imagine getters/setters here
}
</code></pre>
<ul>
<li>We don't want <code>validateUserName</code> on the user, since it only operates on a name; I guess it could go into another class, but then we have <strong>another</strong> procedural "uti" type class</li>
<li>We don't want persistence methods on the User, since there's value in decoupling data structures from their persistence strategy</li>
<li>We don't want business logic in our Servlet, since we may need to re-use that logic elsewhere</li>
<li>We don't want our business logic in our User, as this draws in way too much to the User class, making re-use of the business logic difficult and coupling the user with its persistence strategy</li>
</ul>
<p>I realize this example isn't that bad, but imagine 10 DataContainers and 20 BizLayer objects with several methods each. Imagine that some of those operations aren't "centered" on a particular data container.</p>
<p>How do we keep this from being a procedural mess?</p>
|
[
{
"answer_id": 153434,
"author": "xtofl",
"author_id": 6610,
"author_profile": "https://Stackoverflow.com/users/6610",
"pm_score": -1,
"selected": false,
"text": "<p>Crudely, the \"We don't want\" section has to go. Either you want it to be right, or you want it to stay as it is. There's no point in <em>not</em> creating a class when you need one. \"We have plenty\" is a bad excuse.</p>\n\n<p>Indeed, it <em>is</em> bad to <em>expose</em> all the internal classes, but in my experience, creating a class per concept (i.e. a User, an ID, a Database concept...) always helps.</p>\n\n<p>Next to that, isn't a Facade pattern something to solve the existence of loads of BizRules classes, hidden behind one well-organized and clean interface?</p>\n"
},
{
"answer_id": 153497,
"author": "Steven A. Lowe",
"author_id": 9345,
"author_profile": "https://Stackoverflow.com/users/9345",
"pm_score": 1,
"selected": false,
"text": "<p>since you're implementing classes and objects, your solution is going to be OO regardless of how you layer things - it just may not be very well-structured depending on your situation/needs! ;-)</p>\n\n<p>as to your specific question, it would in some cases make sense for validateUserName to belong to the User class, since every User would like to have a valid name. Or you can have a validation utility class assuming that other things have names that use the same validation rules. The same goes for email. You could split these into NameValidator and EmailValidator classes, which would be a fine solution if they will be used a lot. You could also still provide a validateUserName function on the User object that just called the utility class method. All of these are valid solutions.</p>\n\n<p>One of the great joys about OOD/OOP is that when the design is right, you <em>know</em> that it is right, because a lot of things just fall out of the model that you can do that you couldn't do before.</p>\n\n<p>In this case I would make NameValidator and EmailValidator classes, because it seems likely that other entities will have names and email addresses in future, but I would provide validateName and validateEmailAddress functions on the User class because that makes for a more convenient interface for the biz objects to use.</p>\n\n<p>the rest of the 'we-don't-want' bullets are correct; they are not only necessary for proper layering, but they are also necessary for a clean OO design.</p>\n\n<p>layering and OO go hand-in-glove based on a separation of concerns between the layers. I think you've got the right idea, but will need some utility classes for common validations as presented</p>\n"
},
{
"answer_id": 153501,
"author": "Illandril",
"author_id": 17887,
"author_profile": "https://Stackoverflow.com/users/17887",
"pm_score": 1,
"selected": false,
"text": "<p>Think about how these tasks would be done if there was no computer, and model your system that way.</p>\n\n<p>Simple example... Client fills out a form to request a widget, hands it to an employee, the employee verifies the client's identity, processes the form, obtains a widget, gives the widget and a record of the transaction to the client and keeps a record of the transaction somewhere for the company.</p>\n\n<p>Does the client store their data? No, the employee does. What role is the employee taking when he's storing the client data? Client Records Keeper.</p>\n\n<p>Does the form verify that it was filled out correctly? No, the employee does. What role is the employee taking when he's doing that? Form Processor.</p>\n\n<p>Who gives the client the widget? The employee acting as a Widget Distributor</p>\n\n<p>And so on...</p>\n\n<p>To push this into a Java EE implementation...</p>\n\n<p>The Servlet is acting on behalf of the Client, filling out the form (pulling data from the HTTP request and making the appropriate Java object) and passing it to the appropriate employee (EJB), who then does with the form what needs to be done. While processing the request, the EJB might need to pass it along to another EJB that specializes in different tasks, part of which would include accessing/putting information from/to storage (your data layer). The only thing that shouldn't map directly to the analogy should be the specifics on how your objects communicate with each other, and how your data layer communicates with your storage.</p>\n"
},
{
"answer_id": 153510,
"author": "JeeBee",
"author_id": 17832,
"author_profile": "https://Stackoverflow.com/users/17832",
"pm_score": 0,
"selected": false,
"text": "<p>I've had the same thoughts myself.</p>\n\n<p>In the traditional MVC the most important thing is separating the View from the Model and Controller portions. It seems to be a good idea to separate the controller and the model simply because you can end up with bloated model objects:</p>\n\n<pre>\n<code>\npublic class UserModel extends DatabaseModel implements XMLable, CRUDdy, Serializable, Fooable, Barloney, Baznatchy, Wibbling, Validating {\n // member fields\n // getters and setters\n // 100 interface methods\n}\n</code>\n</pre>\n\n<p>Whereas you can have separate controllers (or entire patterns) for many of the interfaces above, and yes, it's rather procedural in nature but I guess that's how things work these days. Alternatively you can realise that some of the interfaces are doing the same thing (CRUDdy - database storage and retrieval, Serializable - the same to a binary format, XMLable, the same to XML) so you should create a single system to handle this, with each potential backend being a separate implementation that the system handles. God, that's really badly written.</p>\n\n<p>Maybe there's something like \"co-classes\" that let you have separate source files for controller implementation that act as if they're a member of the model class they act on.</p>\n\n<p>As for business rules, they often work on multiple models at the same time, and thus they should be separate.</p>\n"
},
{
"answer_id": 153564,
"author": "Daniel Honig",
"author_id": 1129162,
"author_profile": "https://Stackoverflow.com/users/1129162",
"pm_score": 3,
"selected": true,
"text": "<p>So I'll address my thoughts on this in a few bullet points:</p>\n\n<ol>\n<li>It seems in a Java EE system at some point you have to deal with the plumbing of Java EE, the plumbing doesn't always benefit from OO concepts, but it certainly can with a bit of creativity and work. For example you could might take advantage of things such as AbstractFactory, etc to help commonize as much of this Infrastructure as possible.</li>\n<li>Alot of what you are looking into is discussed in Eric Evans excellent book called Domain Driven Design. I highly reccomend you look at it as he does address the problem of expressing the knowledge of the domain and dealing with the technical infrastructure to support it.</li>\n<li>Having read and GROKD some of DDD, I would encapsulate my technical infrastructure in repositories. The repositories would all be written to use a strategy for persistence that is based on your session EJBs. You would write a default implementation for that knows how to talk to your session EJBS. To make this work, you would need to add a little bit of convention and specify that convention/contract in your interfaces. The repositories do all of the CRUD and should only do more than that if absolutely needed. If you said \"My DAOS are my repositories\", then I would agree. </li>\n<li>So to continue with this. You need something to encapsulate the unit of work that is expressed in UseBizLayer. At this level I think the nature of it is that you are stuck writing code that is all going to be transaction script. You are creating a seperation of responsibility and state. This is typically how I've seen it done within Java EE systems as a default sort of architecture. But it isn't Object Oriented. I would try to explore the model and see if I could at least try to commonize some of the behaviours that are written into the BizClasses.</li>\n<li>Another approach I've used before is to get rid of the BizLayer classes and then proxy the calls from the Domain to the actual Repositories/DAO's doing the operation. However this might require some investment in building infrastructure. But you could do alot with a framework like Spring and using some AOP concept's to make this work well and cut down the amount of custom infrastructure that is needed. </li>\n</ol>\n"
},
{
"answer_id": 1569184,
"author": "richj",
"author_id": 38031,
"author_profile": "https://Stackoverflow.com/users/38031",
"pm_score": 0,
"selected": false,
"text": "<p>I think this is a question about \"separation of concerns\". You seem to be a long way down the right track with your layered architecture, but maybe you need to do more of the same - i.e. create architectural layers within your Java EE layers?</p>\n\n<p>A DataContainer looks a lot like the Data Transfer Objects (DTO) pattern.</p>\n\n<p>A modern OO design has a lot of small classes, each one related to a small number of \"friends\", e.g. via composition. This might produce a lot more classes and Java boiler-plate than you're really comfortable with, but it should lead to a design that is better layered and easier to unit test and maintain.</p>\n\n<p>(+1 for the question, +1 for the answer about when you know you have the layering right)</p>\n"
}
] |
2008/09/30
|
[
"https://Stackoverflow.com/questions/153394",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3029/"
] |
I believe in OO, but not to the point where inappropriate designs/implementations should be used just to be "OO Compliant".
So, how to deal with the Serlvet/EJB/DataContainer layered architecture:
* Servlets receive requests and call a "business layer" (e.g. session EJBs)
* The business layer locates DataContainers from the database and manipulates them to implement the business logic
* DataContainers contain no real code, just get/set corresponding to the database.
This approach has appeal; the DataContainers are clear in what they do and it's very easy to know where data comes from.
Aside from not being OO, this leads to unclear Business Layer classes that can be hard to name and hard to organize.
Even if we **were** trying to be more "OO" (e.g. putting some of these methods in the DataConatiners), some of these operations operate on more than one set of data.
How do you keep your Business Layer from getting confusingly procedural, but without polluting your DataContainers with business logic?
### Example
```
class UserServlet {
handleRequest() {
String id = request.get("id");
String name = request.get("name");
if (UserBizLayer.updateUserName(id,name))
response.setStatus(OK);
else
response.setStatus(BAD_REQUEST);
}
}
class UseBizLayer {
updateUserName(String id, String name) {
long key = toLong(id);
user = userDAO.find(key);
if user == null
return false;
if (!validateUserName(name))
return false;
user.setName(name);
userDAO.update(user);
return true;
}
validateUserName(String name) {
// do some validations and return
}
}
class User {
long key;
String name;
String email;
// imagine getters/setters here
}
```
* We don't want `validateUserName` on the user, since it only operates on a name; I guess it could go into another class, but then we have **another** procedural "uti" type class
* We don't want persistence methods on the User, since there's value in decoupling data structures from their persistence strategy
* We don't want business logic in our Servlet, since we may need to re-use that logic elsewhere
* We don't want our business logic in our User, as this draws in way too much to the User class, making re-use of the business logic difficult and coupling the user with its persistence strategy
I realize this example isn't that bad, but imagine 10 DataContainers and 20 BizLayer objects with several methods each. Imagine that some of those operations aren't "centered" on a particular data container.
How do we keep this from being a procedural mess?
|
So I'll address my thoughts on this in a few bullet points:
1. It seems in a Java EE system at some point you have to deal with the plumbing of Java EE, the plumbing doesn't always benefit from OO concepts, but it certainly can with a bit of creativity and work. For example you could might take advantage of things such as AbstractFactory, etc to help commonize as much of this Infrastructure as possible.
2. Alot of what you are looking into is discussed in Eric Evans excellent book called Domain Driven Design. I highly reccomend you look at it as he does address the problem of expressing the knowledge of the domain and dealing with the technical infrastructure to support it.
3. Having read and GROKD some of DDD, I would encapsulate my technical infrastructure in repositories. The repositories would all be written to use a strategy for persistence that is based on your session EJBs. You would write a default implementation for that knows how to talk to your session EJBS. To make this work, you would need to add a little bit of convention and specify that convention/contract in your interfaces. The repositories do all of the CRUD and should only do more than that if absolutely needed. If you said "My DAOS are my repositories", then I would agree.
4. So to continue with this. You need something to encapsulate the unit of work that is expressed in UseBizLayer. At this level I think the nature of it is that you are stuck writing code that is all going to be transaction script. You are creating a seperation of responsibility and state. This is typically how I've seen it done within Java EE systems as a default sort of architecture. But it isn't Object Oriented. I would try to explore the model and see if I could at least try to commonize some of the behaviours that are written into the BizClasses.
5. Another approach I've used before is to get rid of the BizLayer classes and then proxy the calls from the Domain to the actual Repositories/DAO's doing the operation. However this might require some investment in building infrastructure. But you could do alot with a framework like Spring and using some AOP concept's to make this work well and cut down the amount of custom infrastructure that is needed.
|
153,407 |
<p>I am upgrading a silverlight beta 2 app to RC0 and have a function that translates a point from a child element to it's parent. The purpose of the function is to ensure that an element appears exactly on top of the child even though they are not on the same canvas and don't share a parent.</p>
<p>Here is the current function:</p>
<pre><code> protected Point TranslatePosition(Point current, Panel from, Panel to, MouseEventArgs e)
{
Point rtn = new Point(-1, -1);
// get point relative to existing parent
Point fromPoint = e.GetPosition(from);
// get point relative to new parent
Point toPoint = e.GetPosition(to);
// calculate delta
double deltaX = fromPoint.X - toPoint.X;
double deltaY = fromPoint.Y - toPoint.Y;
// calculate new position
rtn = new Point(current.X - deltaX, current.Y - deltaY);
return rtn;
}
</code></pre>
<p>Notice that it relies on the MouseEventArgs.GetPosition function to get the position relative to existing and new parent. In cases where there is no MouseEventArgs available, we were creating a new instance and passing it in. This was a hack but seemed to work. Now, in RC0, the MouseEventArgs constructor is internal so this hack no longer works.</p>
<p>Any ideas on how to write a method to do the translation of a point in RC0 that doesn't rely on MouseEventArgs.GetPosition? </p>
|
[
{
"answer_id": 154150,
"author": "Santiago Palladino",
"author_id": 12791,
"author_profile": "https://Stackoverflow.com/users/12791",
"pm_score": 3,
"selected": true,
"text": "<p>See TransformToVisual method of framework element. It does exactly what you want: given another control, it generates a new transform that maps the coordinates of a point relative to the current control, to coordinates relative to the passed in control.</p>\n\n<pre><code>var transform = from.TransformToVisual(to);\nreturn transform.Transform(current);\n</code></pre>\n"
},
{
"answer_id": 525411,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 0,
"selected": false,
"text": "<p>Yet but... There appears to be a problem with how the rendering transform pipeline accepts updates which is different to how it works in WPF.</p>\n\n<p>I've created a wiki entry at <a href=\"http://support.daisley-harrison.com/wiki/DeveloperNotes.ashx\" rel=\"nofollow noreferrer\">daisley-harrison.com</a> then talks about this. I'll turn it into a blog entry at <a href=\"http://blog.daisley-harrison.com/blog\" rel=\"nofollow noreferrer\">blog.daisley-harrison.com</a> when I get around to it later.</p>\n"
}
] |
2008/09/30
|
[
"https://Stackoverflow.com/questions/153407",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/21818/"
] |
I am upgrading a silverlight beta 2 app to RC0 and have a function that translates a point from a child element to it's parent. The purpose of the function is to ensure that an element appears exactly on top of the child even though they are not on the same canvas and don't share a parent.
Here is the current function:
```
protected Point TranslatePosition(Point current, Panel from, Panel to, MouseEventArgs e)
{
Point rtn = new Point(-1, -1);
// get point relative to existing parent
Point fromPoint = e.GetPosition(from);
// get point relative to new parent
Point toPoint = e.GetPosition(to);
// calculate delta
double deltaX = fromPoint.X - toPoint.X;
double deltaY = fromPoint.Y - toPoint.Y;
// calculate new position
rtn = new Point(current.X - deltaX, current.Y - deltaY);
return rtn;
}
```
Notice that it relies on the MouseEventArgs.GetPosition function to get the position relative to existing and new parent. In cases where there is no MouseEventArgs available, we were creating a new instance and passing it in. This was a hack but seemed to work. Now, in RC0, the MouseEventArgs constructor is internal so this hack no longer works.
Any ideas on how to write a method to do the translation of a point in RC0 that doesn't rely on MouseEventArgs.GetPosition?
|
See TransformToVisual method of framework element. It does exactly what you want: given another control, it generates a new transform that maps the coordinates of a point relative to the current control, to coordinates relative to the passed in control.
```
var transform = from.TransformToVisual(to);
return transform.Transform(current);
```
|
153,413 |
<p>I'm trying to extract the polygons from placemarks in a KML file. So far so good:</p>
<pre><code>Imports <xmlns:g='http://earth.google.com/kml/2.0'>
Imports System.Xml.Linq
Partial Class Test_ImportPolygons
Inherits System.Web.UI.Page
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
Dim Kml As XDocument = XDocument.Load(Server.MapPath("../kmlimport/ga.kml"))
For Each Placemark As XElement In Kml.<g:Document>.<g:Folder>.<g:Placemark>
Dim Name As String = Placemark.<g:name>.Value
...
Next
End Sub
End Class
</code></pre>
<p>I'd like to capture the entire <code><polygon>...</polygon></code> block as a string. I tried something like this (where the ... is above):</p>
<pre><code> Dim Polygon as String = Placemark.<g:Polygon>.InnerText
</code></pre>
<p>but the XElement object doesn't have an InnerText property, or any equivalent as far as I can tell. How do I grab the raw XML that defines an XElement?</p>
|
[
{
"answer_id": 153486,
"author": "tbrownell",
"author_id": 1981,
"author_profile": "https://Stackoverflow.com/users/1981",
"pm_score": 1,
"selected": false,
"text": "<p>Have you tried:</p>\n\n<pre><code>Placemark.ToString()\n</code></pre>\n"
},
{
"answer_id": 153519,
"author": "Herb Caudill",
"author_id": 239663,
"author_profile": "https://Stackoverflow.com/users/239663",
"pm_score": 2,
"selected": true,
"text": "<p>What I was missing was that <code>Placemark.<g:Polygon></code> is a collection of XElements, not a single XElement. This works:</p>\n\n<pre><code> For Each Placemark As XElement In Kml.<g:Document>.<g:Folder>.<g:Placemark>\n Dim Name As String = Placemark.<g:name>.Value\n Dim PolygonsXml As String = \"\"\n For Each Polygon As XElement In Placemark.<g:Polygon>\n PolygonsXml &= Polygon.ToString\n Next\n Next\n</code></pre>\n\n<p>XElement.ToString is the equivalent of InnerText, as tbrownell suggested.</p>\n"
},
{
"answer_id": 153597,
"author": "tbrownell",
"author_id": 1981,
"author_profile": "https://Stackoverflow.com/users/1981",
"pm_score": 0,
"selected": false,
"text": "<p>I missed the Enumeration also. When using .Value it is possible to receive a null exception. Try the equivelent of this instead:</p>\n\n<pre><code>(string)Placemark.<g:name>\n</code></pre>\n\n<p>Sorry not sure of the VB syntax,,,it has been a while since I have coded in VB.</p>\n"
}
] |
2008/09/30
|
[
"https://Stackoverflow.com/questions/153413",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/239663/"
] |
I'm trying to extract the polygons from placemarks in a KML file. So far so good:
```
Imports <xmlns:g='http://earth.google.com/kml/2.0'>
Imports System.Xml.Linq
Partial Class Test_ImportPolygons
Inherits System.Web.UI.Page
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
Dim Kml As XDocument = XDocument.Load(Server.MapPath("../kmlimport/ga.kml"))
For Each Placemark As XElement In Kml.<g:Document>.<g:Folder>.<g:Placemark>
Dim Name As String = Placemark.<g:name>.Value
...
Next
End Sub
End Class
```
I'd like to capture the entire `<polygon>...</polygon>` block as a string. I tried something like this (where the ... is above):
```
Dim Polygon as String = Placemark.<g:Polygon>.InnerText
```
but the XElement object doesn't have an InnerText property, or any equivalent as far as I can tell. How do I grab the raw XML that defines an XElement?
|
What I was missing was that `Placemark.<g:Polygon>` is a collection of XElements, not a single XElement. This works:
```
For Each Placemark As XElement In Kml.<g:Document>.<g:Folder>.<g:Placemark>
Dim Name As String = Placemark.<g:name>.Value
Dim PolygonsXml As String = ""
For Each Polygon As XElement In Placemark.<g:Polygon>
PolygonsXml &= Polygon.ToString
Next
Next
```
XElement.ToString is the equivalent of InnerText, as tbrownell suggested.
|
153,420 |
<p>I'm starting a project using a Restful architecture implemented in Java (using the new JAX-RS standard)</p>
<p>We are planning to develop the GUI with a Flex application. I have already found some problems with this implementation using the HTTPService component (the response error codes, headers access...).</p>
<p>Any of you guys have some experience in a similar project. Is it feasible?</p>
|
[
{
"answer_id": 153504,
"author": "mbrevoort",
"author_id": 18228,
"author_profile": "https://Stackoverflow.com/users/18228",
"pm_score": 3,
"selected": false,
"text": "<p>There are definite shortcomings of Flex's ability to act as a pure RESTful client.</p>\n\n<p>The comments below are from this <a href=\"http://fantastic.wordpress.com/2007/12/26/flex-is-not-friendly-to-rest/#comments\" rel=\"noreferrer\">blog</a>:</p>\n\n<blockquote>\n <p>The problem is HTTPService class has\n several major limitations:</p>\n \n <ol>\n <li>Only GET and POST methods are supported out of the box (unless you\n use FDS and set useProxy attribute to\n true)</li>\n <li>Not able to set request headers and there is no access to response\n headers. Therefore I am not able to\n access the response body in the case\n of an error.</li>\n <li>It HTTPService gets a status code anything other 200, it consider\n an error. (event 201, ouch!!). The\n FaultEvent doesn’t provide information\n about the status code any response\n body. The Flex client will have no\n idea what went wrong.</li>\n </ol>\n</blockquote>\n\n<p><a href=\"http://raibledesigns.com\" rel=\"noreferrer\">Matt Raible</a> also gave a <a href=\"http://raibledesigns.com/rd/entry/oscon_2008_web_frameworks_of\" rel=\"noreferrer\">nice presentation on REST with Rails, Grails, GWT and Flex</a> that have some good references linked from it.</p>\n\n<p>Whether it's feasible or not really depends on how much your willing to work around by proxying, etc.</p>\n"
},
{
"answer_id": 153570,
"author": "Yaba",
"author_id": 7524,
"author_profile": "https://Stackoverflow.com/users/7524",
"pm_score": 0,
"selected": false,
"text": "<p>Actually were are already using Flex with a Rest-Style Framework. As mbrevort already mentioned PUT and DELETE methods cannot be directly used. Instead we are doing PUT via a POST and for DELETE we are using a GET on a resource with an URL parameter like ?action=delete.</p>\n\n<p>This is not 100% Rest style, so I am not sure, if this works with a JSR 311 implementation. You will need some flexbility on the server side to workaround the PUT and DELETE restrictions.</p>\n\n<p>With regards to error handling, we have implemented an error service. In case of an server side error, the Flex application can query this error service to get the actual error message. This is also much more flexible than just mapping HTTP return codes to static messages.</p>\n\n<p>However thanks To ECMA scripting of Flex working with XML based REST services is very easy.</p>\n"
},
{
"answer_id": 153589,
"author": "Brandon",
"author_id": 23133,
"author_profile": "https://Stackoverflow.com/users/23133",
"pm_score": 1,
"selected": false,
"text": "<p>Yes, I was able to use POST and access headers with this component:</p>\n\n<p><a href=\"http://code.google.com/p/as3httpclient/wiki/Links\" rel=\"nofollow noreferrer\">http://code.google.com/p/as3httpclient/wiki/Links</a></p>\n\n<p><a href=\"http://www.abdulqabiz.com/blog/archives/flash_and_actionscript/http_authentica.php\" rel=\"nofollow noreferrer\">Example</a></p>\n"
},
{
"answer_id": 154578,
"author": "dj_segfault",
"author_id": 14924,
"author_profile": "https://Stackoverflow.com/users/14924",
"pm_score": 1,
"selected": false,
"text": "<p>I'm working right now on an application that relies heavily on REST calls between Flex and JavaScript and Java Servlets. We get around the response error code problem by establishing a convention of a <status id=\"XXX\" name=\"YYYYYY\"> block that gets returned upon error, with error IDs that roughly map to HTTP error codes.</p>\n\n<p>We get around the cross-site scripting limitations by using a Java Servlet as an HTTP proxy. Calls to the proxy (which runs on the same server that serves the rest of the content, including the Flex content, sends the request to the other server, then sends the response back to the original caller.</p>\n"
},
{
"answer_id": 157532,
"author": "Theo",
"author_id": 1109,
"author_profile": "https://Stackoverflow.com/users/1109",
"pm_score": 3,
"selected": false,
"text": "<p>As many have pointed out <code>HTTPService</code> is a bit simplistic and doesn't do all that you want to do. However, <code>HTTPService</code> is just sugar on top of the <code>flash.net.*</code> classes like <code>URLLoader</code>, <code>URLRequest</code> and <code>URLRequestHeader</code>. Using these you can assemble most HTTP requests.</p>\n\n<p>When it comes to support for other methods than GET and POST the problem mostly lies in that some browsers (for example Safari) don't support these, and Flash Player relies on the browser for all it's networking.</p>\n"
},
{
"answer_id": 163228,
"author": "Guerry",
"author_id": 9190,
"author_profile": "https://Stackoverflow.com/users/9190",
"pm_score": 6,
"selected": true,
"text": "<p>The problem here is that a lot of the web discussions around this issue are a year or more old. I'm working through this same research right now, and this is what I've learned today.</p>\n\n<p>This <a href=\"http://www.ibm.com/developerworks/websphere/library/techarticles/0808_rasillo/0808_rasillo.html\" rel=\"noreferrer\">IBM Developer Works article from August 2008</a> by Jorge Rasillo and Mike Burr shows how to do a Flex front-end / RESTful back-end app (examples in PHP and Groovy). Nice article. Anyway, here's the take away:</p>\n\n<ul>\n<li>Their PHP/Groovy code <em>uses and expects</em> PUT and DELETE.</li>\n<li>But the Flex code has to use POST, but sets the HTTP header X-Method-Override to DELETE (you can do the same for PUT I presume).</li>\n<li>Note that this is <em>not</em> the Proxy method discussed above.</li>\n</ul>\n\n<p><code><pre>\n// Flex doesn't know how to generate an HTTP DELETE.\n// Fortunately, sMash/Zero will interpret an HTTP POST with\n// an X-Method-Override: DELETE header as a DELETE.\ndeleteTodoHS.headers['X-Method-Override'] = 'DELETE';</pre></code></p>\n\n<p>What's happening here? the IBM web server intercepts and interprets the \"POST with DELETE\" as a DELETE.</p>\n\n<p>So, I dug further and found this <a href=\"http://www.pluralsight.com/community/blogs/dbox/archive/2007/01/16/45725.aspx\" rel=\"noreferrer\">post and discussion with Don Box</a> (one of the original SOAP guys). Apparently this is a fairly standard behavior since some browsers, etc. do not support PUT and DELETE, and is a work-around that has been around a while. Here's a snippet, but there's much more discussion.</p>\n\n<blockquote>\n <p>\"If I were building a GData client, I honestly wonder why I'd bother using DELETE and PUT methods at all given that X-HTTP-Method-Override is going to work in more cases/deployments.\"</p>\n</blockquote>\n\n<p>My take away from this is that if your web side supports this X-Method-Override header, then you can use this approach. The Don Box comments make me think it's fairly well supported, but I've not confirmed that yet.</p>\n\n<p>Another issue arises around being able to read the HTTP response headers. Again, from <a href=\"http://www.atnan.com/2007/6/11/can-as3-do-rest-or-not\" rel=\"noreferrer\">a blog post in 2007 by Nathan de Vries</a>, we see this discussed. He followed up that blog post and discussion with his own comment:</p>\n\n<blockquote>\n <p>\"The only change on the web front is that newer versions of the Flash Player (certainly those supplied with the Flex 3 beta) now support the responseHeaders property on instances of HTTPStatusEvent.\"</p>\n</blockquote>\n\n<p>I'm hoping that means it is a non-issue now.</p>\n"
},
{
"answer_id": 392229,
"author": "RogerV",
"author_id": 48048,
"author_profile": "https://Stackoverflow.com/users/48048",
"pm_score": 0,
"selected": false,
"text": "<p>REST is more of an ideology than anything. You go to the REST presentations and they have coolaide dispensers.</p>\n\n<p>For Flex apps, rolling a stack in conjunction to BlazeDS and AMF data marshalling is more convenient and more performant.</p>\n"
},
{
"answer_id": 392269,
"author": "Scott Evernden",
"author_id": 11397,
"author_profile": "https://Stackoverflow.com/users/11397",
"pm_score": 0,
"selected": false,
"text": "<p>The way I've managed this in the past is to utilize a PHP proxy that deals with the remote web service calls and returns RTU JSON to the client .. </p>\n"
},
{
"answer_id": 426669,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 2,
"selected": false,
"text": "<p>I've been working on an open source replacement for the HTTPService component that fully supports REST. If interested, you can find the beta version (source code and/or compiled Flex shared runtime library) and instructions here:</p>\n\n<p><a href=\"http://code.google.com/p/resthttpservice/\" rel=\"nofollow noreferrer\">http://code.google.com/p/resthttpservice/</a></p>\n"
},
{
"answer_id": 1268688,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 0,
"selected": false,
"text": "<p>May be the new flex 4 is the answer <a href=\"http://labs.adobe.com/technologies/flex4sdk/\" rel=\"nofollow noreferrer\">http://labs.adobe.com/technologies/flex4sdk/</a></p>\n"
},
{
"answer_id": 1518707,
"author": "Lance",
"author_id": 169992,
"author_profile": "https://Stackoverflow.com/users/169992",
"pm_score": 1,
"selected": false,
"text": "<p><a href=\"http://wiki.github.com/dima/restfulx_framework/working-with-restfulx-service-providers\" rel=\"nofollow noreferrer\">RestfulX</a> has solved most/all of the REST problems with Flex. It has support for Rails/GAE/Merb/CouchDB/AIR/WebKit, and I'm sure it would be a snap to connect it to your Java implementation.</p>\n\n<p>Dima's integrated the AS3HTTPClient Library into it also.</p>\n\n<p>Check it out!</p>\n"
},
{
"answer_id": 2061802,
"author": "verveguy",
"author_id": 66753,
"author_profile": "https://Stackoverflow.com/users/66753",
"pm_score": 2,
"selected": false,
"text": "<p>The short answer is yes, you can do RESTful with Flex. You just have to work around the limitations of the Flash player (better with latest versions) and the containing browser's HTTP stack limitations.</p>\n\n<p>We've been doing RESTful client development in Flex for more than a year after solving the basic HTTP request header and lack of PUT and DELETE via the rails-esque ?_method= approach. Tacky perhaps, but it gets the job done.</p>\n\n<p>I noted some of the headers pain in an old blog post at <a href=\"http://verveguy.blogspot.com/2008/07/truth-about-flex-httpservice.html\" rel=\"nofollow noreferrer\">http://verveguy.blogspot.com/2008/07/truth-about-flex-httpservice.html</a></p>\n"
},
{
"answer_id": 2238785,
"author": "jamz",
"author_id": 3734,
"author_profile": "https://Stackoverflow.com/users/3734",
"pm_score": 0,
"selected": false,
"text": "<p>The book <a href=\"http://www.manning.com/armstrong/\" rel=\"nofollow noreferrer\">Flexible Rails</a> may be helpful -- It is an excellent resource on how to use Flex as a RESTful client. Although it focuses on using Flex with the Rails framework, I believe the concepts apply to any RESTful framework. I used this book to get up to speed quickly on using Flex with REST.</p>\n"
},
{
"answer_id": 2420779,
"author": "Phil",
"author_id": 290956,
"author_profile": "https://Stackoverflow.com/users/290956",
"pm_score": 2,
"selected": false,
"text": "<p>Flex support for REST is weak at best. I spent a lot of time building a prototype so I know most of the issues. As mentioned previously , out of the box there is only support for GET and POST. At first glance it appears that you can use the proxy config in LiveCycle Data Services or Blaze to get support for PUT and DELETE. However, its a sham. The request coming from your Flex app will still be a POST. The proxy converts it to PUT or DELETE on the server side to trick your server side code. There are other issues as well. It's heard to believe that this is the best that Adobe could come up with. After my evaluation we decided to go in another direction.</p>\n"
},
{
"answer_id": 13072570,
"author": "Sean Thayne",
"author_id": 503724,
"author_profile": "https://Stackoverflow.com/users/503724",
"pm_score": 0,
"selected": false,
"text": "<p>I work on a big flex project for Franklin Covey. We use REST services. In order to support this. We created a XMLHttpRequest wrapper. By using external interface with some event handlers. We opensourced the library. You can check it out at <a href=\"https://github.com/FranklinCovey/AS3-XMLHttpRequest\" rel=\"nofollow\">https://github.com/FranklinCovey/AS3-XMLHttpRequest</a></p>\n"
}
] |
2008/09/30
|
[
"https://Stackoverflow.com/questions/153420",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2937/"
] |
I'm starting a project using a Restful architecture implemented in Java (using the new JAX-RS standard)
We are planning to develop the GUI with a Flex application. I have already found some problems with this implementation using the HTTPService component (the response error codes, headers access...).
Any of you guys have some experience in a similar project. Is it feasible?
|
The problem here is that a lot of the web discussions around this issue are a year or more old. I'm working through this same research right now, and this is what I've learned today.
This [IBM Developer Works article from August 2008](http://www.ibm.com/developerworks/websphere/library/techarticles/0808_rasillo/0808_rasillo.html) by Jorge Rasillo and Mike Burr shows how to do a Flex front-end / RESTful back-end app (examples in PHP and Groovy). Nice article. Anyway, here's the take away:
* Their PHP/Groovy code *uses and expects* PUT and DELETE.
* But the Flex code has to use POST, but sets the HTTP header X-Method-Override to DELETE (you can do the same for PUT I presume).
* Note that this is *not* the Proxy method discussed above.
````
// Flex doesn't know how to generate an HTTP DELETE.
// Fortunately, sMash/Zero will interpret an HTTP POST with
// an X-Method-Override: DELETE header as a DELETE.
deleteTodoHS.headers['X-Method-Override'] = 'DELETE';
````
What's happening here? the IBM web server intercepts and interprets the "POST with DELETE" as a DELETE.
So, I dug further and found this [post and discussion with Don Box](http://www.pluralsight.com/community/blogs/dbox/archive/2007/01/16/45725.aspx) (one of the original SOAP guys). Apparently this is a fairly standard behavior since some browsers, etc. do not support PUT and DELETE, and is a work-around that has been around a while. Here's a snippet, but there's much more discussion.
>
> "If I were building a GData client, I honestly wonder why I'd bother using DELETE and PUT methods at all given that X-HTTP-Method-Override is going to work in more cases/deployments."
>
>
>
My take away from this is that if your web side supports this X-Method-Override header, then you can use this approach. The Don Box comments make me think it's fairly well supported, but I've not confirmed that yet.
Another issue arises around being able to read the HTTP response headers. Again, from [a blog post in 2007 by Nathan de Vries](http://www.atnan.com/2007/6/11/can-as3-do-rest-or-not), we see this discussed. He followed up that blog post and discussion with his own comment:
>
> "The only change on the web front is that newer versions of the Flash Player (certainly those supplied with the Flex 3 beta) now support the responseHeaders property on instances of HTTPStatusEvent."
>
>
>
I'm hoping that means it is a non-issue now.
|
153,427 |
<p>I am currently using JUnit 4 and have a need to divide my tests into groups that can be run selectively in any combination. I know TestNG has a feature to annotate tests to assign them to groups, but I can't migrate to TestNG right now. It seems this could easily be accomplished in JUnit with some custom annotations and a custom JUnit TestRunner. I've checked both the JUnit docs and searched the web but couldn't find such a thing. Is anyone aware of such a TestRunner?</p>
<p>Update: Thanks for your replies regarding test suites. I should have addressed these in my original question. Here we go: I don't want to use test suites because they would require me to manually create and manage them, which means touching ALL my tests and arranging them into suites manually (too much work and a maintenance nightmare). All I need to do is run all unit tests, except a few that are really integration tests. So I want to annotate these, and run all others. At other times, I want to just run the integration tests. I also have the need to put a unit test into multiple groups, which is not possible with suites. Hope this helps to clear things up.</p>
<p>Update 2: If JUnit doesn't have this OOB, I'm looking for an Open Source library that adds this to JUnit (annotations + custom JUnit Test Runner).</p>
|
[
{
"answer_id": 153447,
"author": "Tom",
"author_id": 22850,
"author_profile": "https://Stackoverflow.com/users/22850",
"pm_score": 0,
"selected": false,
"text": "<p>You can create suites, although that puts all the configuration in the suite, and not in annotations.</p>\n"
},
{
"answer_id": 153449,
"author": "JesperE",
"author_id": 13051,
"author_profile": "https://Stackoverflow.com/users/13051",
"pm_score": 0,
"selected": false,
"text": "<p>JUnit 3 allows you to create test-suites which can be run like any other test. Doesn't JUnit 4 have a similar concept?</p>\n"
},
{
"answer_id": 153509,
"author": "sblundy",
"author_id": 4893,
"author_profile": "https://Stackoverflow.com/users/4893",
"pm_score": 0,
"selected": false,
"text": "<p>If you're using ANT or maven, you can control which tests are run by filtering the tests by name. A bit awkward, but it might work for you. </p>\n"
},
{
"answer_id": 153521,
"author": "gizmo",
"author_id": 9396,
"author_profile": "https://Stackoverflow.com/users/9396",
"pm_score": 1,
"selected": false,
"text": "<p>No, there is no similar concept to TestNG groups, unfortunately. It was planned for JUnit4, but for some unclear reason, it was dropped from the planning.</p>\n"
},
{
"answer_id": 153528,
"author": "Kent Beck",
"author_id": 13842,
"author_profile": "https://Stackoverflow.com/users/13842",
"pm_score": 4,
"selected": false,
"text": "<p>JUnit has no such runner at the moment. Addressing the underlying issue, the need to get reasonable assurance from a test suite in a limited amount of time, is our highest development priority for the next release. In the meantime, implementing a Filter that works through annotations seems like it wouldn't be a big project, although I'm biased.</p>\n"
},
{
"answer_id": 153538,
"author": "flicken",
"author_id": 12880,
"author_profile": "https://Stackoverflow.com/users/12880",
"pm_score": 4,
"selected": true,
"text": "<p>Check out Spring's <a href=\"http://static.springframework.org/spring/docs/2.5.x/api/org/springframework/test/context/junit4/SpringJUnit4ClassRunner.html\" rel=\"noreferrer\">SpringJUnit4ClassRunner</a>. I've used it to optionally run tests based on a System property, using the <a href=\"http://static.springframework.org/spring/docs/2.5.x/api/org/springframework/test/annotation/IfProfileValue.html\" rel=\"noreferrer\">IfProfileValue</a> annotation. </p>\n\n<p>This:</p>\n\n<pre><code>@IfProfileValue(name=\"test-groups\", values={\"unit-tests\", \"integration-tests\"})\n public void testWhichRunsForUnitOrIntegrationTestGroups() {\n // ...\n }\n</code></pre>\n\n<p>Will run if the System property 'test-groups' is set to either 'unit-tests' or 'integration-tests'.</p>\n\n<p>Update: <a href=\"http://junitext.sourceforge.net/\" rel=\"noreferrer\">JUnitExt</a> has <code>@Category</code> and <code>@Prerequisite</code> annotations and looks like it should do what you need. However, I've never used it myself, so I can't vouch for it. </p>\n"
},
{
"answer_id": 153625,
"author": "krakatoa",
"author_id": 12223,
"author_profile": "https://Stackoverflow.com/users/12223",
"pm_score": 2,
"selected": false,
"text": "<p>First, you are addressing two problems - unit tests (often in the same package as the unit under test) and integration tests. I usually keep my integration tests in a separate package, something like com.example.project.tests. In eclipse, my projects look like:</p>\n\n<pre><code>project/\n src/\n com.example.project/\n tsrc/\n com.example.project/\n com.example.project.tests/\n</code></pre>\n\n<p>Right-clicking on a package and selecting 'run' runs the tests in the package; doing the same on the source folder runs all the tests. </p>\n\n<p>You can acheive a similar effect, although you expressed a disinterest in it, by using the <a href=\"http://junit.sourceforge.net/javadoc_40/org/junit/runners/Suite.html\" rel=\"nofollow noreferrer\">Suite runner</a>. However, this violates DRY - you have to keep copies of the test names up to date in the suite classes. However, you can easily put the same test in multiple suites.</p>\n\n<pre><code>@RunWith(Suite.class)\[email protected]( { \n TestAlpha.class, \n TestBeta.class })\npublic class GreekLetterUnitTests {\n}\n</code></pre>\n\n<p>Of course, I really should be keeping these things automated. A good method for doing that is to use <a href=\"http://ant.apache.org/manual/Tasks/junit.html\" rel=\"nofollow noreferrer\">the Ant task</a>. </p>\n\n<pre><code><target name=\"tests.unit\">\n <junit>\n <batchtest>\n <fileset dir=\"tsrc\">\n <include name=\"**/Test*.java\"/>\n <exclude name=\"**/tests/*.java\"/>\n </fileset>\n </batchtest>\n </junit>\n</target>\n<target name=\"tests.integration\">\n <junit>\n <batchtest>\n <fileset dir=\"tsrc\">\n <include name=\"**/tests/Test*.java\"/>\n </fileset>\n </batchtest>\n </junit>\n</target>\n</code></pre>\n"
},
{
"answer_id": 154589,
"author": "Spencer Kormos",
"author_id": 8528,
"author_profile": "https://Stackoverflow.com/users/8528",
"pm_score": 0,
"selected": false,
"text": "<p>TestNG has my vote. It's annotation based, can run as Groups, single Tests, etc, can be linked into Maven, and can run all JUnit tests as part of it's test runs.</p>\n\n<p>I highly recommend it over JUnit.</p>\n"
},
{
"answer_id": 435427,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 0,
"selected": false,
"text": "<p>my advice is simply ditch JUnit and use TestNG. Once you get used to TestNG, Junit looks like Stone Age.</p>\n"
}
] |
2008/09/30
|
[
"https://Stackoverflow.com/questions/153427",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/13041/"
] |
I am currently using JUnit 4 and have a need to divide my tests into groups that can be run selectively in any combination. I know TestNG has a feature to annotate tests to assign them to groups, but I can't migrate to TestNG right now. It seems this could easily be accomplished in JUnit with some custom annotations and a custom JUnit TestRunner. I've checked both the JUnit docs and searched the web but couldn't find such a thing. Is anyone aware of such a TestRunner?
Update: Thanks for your replies regarding test suites. I should have addressed these in my original question. Here we go: I don't want to use test suites because they would require me to manually create and manage them, which means touching ALL my tests and arranging them into suites manually (too much work and a maintenance nightmare). All I need to do is run all unit tests, except a few that are really integration tests. So I want to annotate these, and run all others. At other times, I want to just run the integration tests. I also have the need to put a unit test into multiple groups, which is not possible with suites. Hope this helps to clear things up.
Update 2: If JUnit doesn't have this OOB, I'm looking for an Open Source library that adds this to JUnit (annotations + custom JUnit Test Runner).
|
Check out Spring's [SpringJUnit4ClassRunner](http://static.springframework.org/spring/docs/2.5.x/api/org/springframework/test/context/junit4/SpringJUnit4ClassRunner.html). I've used it to optionally run tests based on a System property, using the [IfProfileValue](http://static.springframework.org/spring/docs/2.5.x/api/org/springframework/test/annotation/IfProfileValue.html) annotation.
This:
```
@IfProfileValue(name="test-groups", values={"unit-tests", "integration-tests"})
public void testWhichRunsForUnitOrIntegrationTestGroups() {
// ...
}
```
Will run if the System property 'test-groups' is set to either 'unit-tests' or 'integration-tests'.
Update: [JUnitExt](http://junitext.sourceforge.net/) has `@Category` and `@Prerequisite` annotations and looks like it should do what you need. However, I've never used it myself, so I can't vouch for it.
|
153,438 |
<p>I have a VB6 COM component which I need to call from my .Net method. I use reflection to create an instance of the COM object and activate it in the following manner:</p>
<pre><code>f_oType = Type.GetTypeFromProgID(MyProgId);
f_oInstance = Activator.CreateInstance(f_oType);
</code></pre>
<p>I need to use GetTypeFromProgID rather than using tlbimp to create a library against the COM DLL as the ProgId of the type I need to instantiate can vary. I then use Type.InvokeMember to call the COM method in my code like:</p>
<pre><code>f_oType.InvokeMember("Process", BindingFlags.InvokeMethod, null, f_oInstance, new object[] { param1, param2, param3, param4 });
</code></pre>
<p>I catch any raised TargetInvocationException's for logging and can get the detailed error description from the TargetInvocationException.InnerException field. However, I know that the COM component uses Error.Raise to generate an error number and I need to somehow get hold of this in my calling .Net application.</p>
<p>The problem seems to stem from the TargetInvocationException not containing the error number as I'd expect if it were a normal COMException so:</p>
<p><em><strong>How can I get the Error Number from the COM object in my .Net code?</strong></em></p>
<p>or</p>
<p><em><strong>Can I make this same call in a way that would cause a COMException (containing the error number) rather than a TargetInvocationException when the COM component fails?</strong></em></p>
<p>Please also note that the target platform is .Net 2.0 and I do have access to the VB6 source code but would regard altering the error message raised from VB6 to contain the error code as part of the text to be a bit of a hack.</p>
|
[
{
"answer_id": 153447,
"author": "Tom",
"author_id": 22850,
"author_profile": "https://Stackoverflow.com/users/22850",
"pm_score": 0,
"selected": false,
"text": "<p>You can create suites, although that puts all the configuration in the suite, and not in annotations.</p>\n"
},
{
"answer_id": 153449,
"author": "JesperE",
"author_id": 13051,
"author_profile": "https://Stackoverflow.com/users/13051",
"pm_score": 0,
"selected": false,
"text": "<p>JUnit 3 allows you to create test-suites which can be run like any other test. Doesn't JUnit 4 have a similar concept?</p>\n"
},
{
"answer_id": 153509,
"author": "sblundy",
"author_id": 4893,
"author_profile": "https://Stackoverflow.com/users/4893",
"pm_score": 0,
"selected": false,
"text": "<p>If you're using ANT or maven, you can control which tests are run by filtering the tests by name. A bit awkward, but it might work for you. </p>\n"
},
{
"answer_id": 153521,
"author": "gizmo",
"author_id": 9396,
"author_profile": "https://Stackoverflow.com/users/9396",
"pm_score": 1,
"selected": false,
"text": "<p>No, there is no similar concept to TestNG groups, unfortunately. It was planned for JUnit4, but for some unclear reason, it was dropped from the planning.</p>\n"
},
{
"answer_id": 153528,
"author": "Kent Beck",
"author_id": 13842,
"author_profile": "https://Stackoverflow.com/users/13842",
"pm_score": 4,
"selected": false,
"text": "<p>JUnit has no such runner at the moment. Addressing the underlying issue, the need to get reasonable assurance from a test suite in a limited amount of time, is our highest development priority for the next release. In the meantime, implementing a Filter that works through annotations seems like it wouldn't be a big project, although I'm biased.</p>\n"
},
{
"answer_id": 153538,
"author": "flicken",
"author_id": 12880,
"author_profile": "https://Stackoverflow.com/users/12880",
"pm_score": 4,
"selected": true,
"text": "<p>Check out Spring's <a href=\"http://static.springframework.org/spring/docs/2.5.x/api/org/springframework/test/context/junit4/SpringJUnit4ClassRunner.html\" rel=\"noreferrer\">SpringJUnit4ClassRunner</a>. I've used it to optionally run tests based on a System property, using the <a href=\"http://static.springframework.org/spring/docs/2.5.x/api/org/springframework/test/annotation/IfProfileValue.html\" rel=\"noreferrer\">IfProfileValue</a> annotation. </p>\n\n<p>This:</p>\n\n<pre><code>@IfProfileValue(name=\"test-groups\", values={\"unit-tests\", \"integration-tests\"})\n public void testWhichRunsForUnitOrIntegrationTestGroups() {\n // ...\n }\n</code></pre>\n\n<p>Will run if the System property 'test-groups' is set to either 'unit-tests' or 'integration-tests'.</p>\n\n<p>Update: <a href=\"http://junitext.sourceforge.net/\" rel=\"noreferrer\">JUnitExt</a> has <code>@Category</code> and <code>@Prerequisite</code> annotations and looks like it should do what you need. However, I've never used it myself, so I can't vouch for it. </p>\n"
},
{
"answer_id": 153625,
"author": "krakatoa",
"author_id": 12223,
"author_profile": "https://Stackoverflow.com/users/12223",
"pm_score": 2,
"selected": false,
"text": "<p>First, you are addressing two problems - unit tests (often in the same package as the unit under test) and integration tests. I usually keep my integration tests in a separate package, something like com.example.project.tests. In eclipse, my projects look like:</p>\n\n<pre><code>project/\n src/\n com.example.project/\n tsrc/\n com.example.project/\n com.example.project.tests/\n</code></pre>\n\n<p>Right-clicking on a package and selecting 'run' runs the tests in the package; doing the same on the source folder runs all the tests. </p>\n\n<p>You can acheive a similar effect, although you expressed a disinterest in it, by using the <a href=\"http://junit.sourceforge.net/javadoc_40/org/junit/runners/Suite.html\" rel=\"nofollow noreferrer\">Suite runner</a>. However, this violates DRY - you have to keep copies of the test names up to date in the suite classes. However, you can easily put the same test in multiple suites.</p>\n\n<pre><code>@RunWith(Suite.class)\[email protected]( { \n TestAlpha.class, \n TestBeta.class })\npublic class GreekLetterUnitTests {\n}\n</code></pre>\n\n<p>Of course, I really should be keeping these things automated. A good method for doing that is to use <a href=\"http://ant.apache.org/manual/Tasks/junit.html\" rel=\"nofollow noreferrer\">the Ant task</a>. </p>\n\n<pre><code><target name=\"tests.unit\">\n <junit>\n <batchtest>\n <fileset dir=\"tsrc\">\n <include name=\"**/Test*.java\"/>\n <exclude name=\"**/tests/*.java\"/>\n </fileset>\n </batchtest>\n </junit>\n</target>\n<target name=\"tests.integration\">\n <junit>\n <batchtest>\n <fileset dir=\"tsrc\">\n <include name=\"**/tests/Test*.java\"/>\n </fileset>\n </batchtest>\n </junit>\n</target>\n</code></pre>\n"
},
{
"answer_id": 154589,
"author": "Spencer Kormos",
"author_id": 8528,
"author_profile": "https://Stackoverflow.com/users/8528",
"pm_score": 0,
"selected": false,
"text": "<p>TestNG has my vote. It's annotation based, can run as Groups, single Tests, etc, can be linked into Maven, and can run all JUnit tests as part of it's test runs.</p>\n\n<p>I highly recommend it over JUnit.</p>\n"
},
{
"answer_id": 435427,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 0,
"selected": false,
"text": "<p>my advice is simply ditch JUnit and use TestNG. Once you get used to TestNG, Junit looks like Stone Age.</p>\n"
}
] |
2008/09/30
|
[
"https://Stackoverflow.com/questions/153438",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/15570/"
] |
I have a VB6 COM component which I need to call from my .Net method. I use reflection to create an instance of the COM object and activate it in the following manner:
```
f_oType = Type.GetTypeFromProgID(MyProgId);
f_oInstance = Activator.CreateInstance(f_oType);
```
I need to use GetTypeFromProgID rather than using tlbimp to create a library against the COM DLL as the ProgId of the type I need to instantiate can vary. I then use Type.InvokeMember to call the COM method in my code like:
```
f_oType.InvokeMember("Process", BindingFlags.InvokeMethod, null, f_oInstance, new object[] { param1, param2, param3, param4 });
```
I catch any raised TargetInvocationException's for logging and can get the detailed error description from the TargetInvocationException.InnerException field. However, I know that the COM component uses Error.Raise to generate an error number and I need to somehow get hold of this in my calling .Net application.
The problem seems to stem from the TargetInvocationException not containing the error number as I'd expect if it were a normal COMException so:
***How can I get the Error Number from the COM object in my .Net code?***
or
***Can I make this same call in a way that would cause a COMException (containing the error number) rather than a TargetInvocationException when the COM component fails?***
Please also note that the target platform is .Net 2.0 and I do have access to the VB6 source code but would regard altering the error message raised from VB6 to contain the error code as part of the text to be a bit of a hack.
|
Check out Spring's [SpringJUnit4ClassRunner](http://static.springframework.org/spring/docs/2.5.x/api/org/springframework/test/context/junit4/SpringJUnit4ClassRunner.html). I've used it to optionally run tests based on a System property, using the [IfProfileValue](http://static.springframework.org/spring/docs/2.5.x/api/org/springframework/test/annotation/IfProfileValue.html) annotation.
This:
```
@IfProfileValue(name="test-groups", values={"unit-tests", "integration-tests"})
public void testWhichRunsForUnitOrIntegrationTestGroups() {
// ...
}
```
Will run if the System property 'test-groups' is set to either 'unit-tests' or 'integration-tests'.
Update: [JUnitExt](http://junitext.sourceforge.net/) has `@Category` and `@Prerequisite` annotations and looks like it should do what you need. However, I've never used it myself, so I can't vouch for it.
|
153,439 |
<p>I'm trying to place 4 of my image containers into a new pane, having a total of 16 images. The jQuery below is what I came up with to do it. The first pane comes out correctly with 4 images in it. But the second has 4 images, plus the 3rd pane. And the 3rd pane has 4 images plus the 4th pane. I don't know exactly why the nesting is occurring. My wrapping can't be causing their index to change. I added css borders to them and it appears to be indexed correctly. How should I be going about this? What I want is to have 1-4 in one pane, 5-8 in another, 9-12, and 13-16. It needs to be dynamic so that I can change the number in each pane, so just doing it in the HTML isn't an option.</p>
<p>A demo of the issue can be seen here: <a href="http://beta.whipplehill.com/mygal/rotate.html" rel="noreferrer">http://beta.whipplehill.com/mygal/rotate.html</a>. I'm using firebug to view the DOM.</p>
<p>Any help would be splentabulous!</p>
<p>The jQuery Code</p>
<pre><code>$(function() {
$(".digi_image:gt(-1):lt(4)").wrapAll("<div class=\"digi_pane\"></div>").css("border", "2px solid red");
$(".digi_image:gt(3):lt(8)").wrapAll("<div class=\"digi_pane\"></div>").css("border", "2px solid blue");
$(".digi_image:gt(7):lt(12)").wrapAll("<div class=\"digi_pane\"></div>").css("border", "2px solid green");
$(".digi_image:gt(11):lt(16)").wrapAll("<div class=\"digi_pane\"></div>").css("border", "2px solid orange");
$(".digi_pane").append("<div style=\"clear: both;\"></div>");
});
</code></pre>
<p>The HTML (abbreviated), but essentially repeated 16 times.</p>
<pre><code><div class="digi_image">
<div class="space_holder"><img src="images/n883470064_4126667_9320.jpg" width="100" /></div>
</div>
</code></pre>
|
[
{
"answer_id": 153562,
"author": "Per Hornshøj-Schierbeck",
"author_id": 11619,
"author_profile": "https://Stackoverflow.com/users/11619",
"pm_score": 4,
"selected": true,
"text": "<p>I think your problem is your use of the gt() and lt() selectors. You should look up slice() instead. </p>\n\n<p>Check out this post:\n<a href=\"http://docs.jquery.com/Traversing/slice\" rel=\"nofollow noreferrer\">http://docs.jquery.com/Traversing/slice</a></p>\n"
},
{
"answer_id": 153624,
"author": "Wes P",
"author_id": 13611,
"author_profile": "https://Stackoverflow.com/users/13611",
"pm_score": 1,
"selected": false,
"text": "<p>For those who are curious... this is what I did.</p>\n\n<pre><code>$(\".digi_image\").slice(0, 4).wrapAll(\"<div class=\\\"digi_pane\\\"></div>\").css(\"border\", \"2px solid red\");\n$(\".digi_image\").slice(4, 8).wrapAll(\"<div class=\\\"digi_pane\\\"></div>\").css(\"border\", \"2px solid blue\");\n$(\".digi_image\").slice(8, 12).wrapAll(\"<div class=\\\"digi_pane\\\"></div>\").css(\"border\", \"2px solid green\");\n$(\".digi_image\").slice(12, 16).wrapAll(\"<div class=\\\"digi_pane\\\"></div>\").css(\"border\", \"2px solid orange\");\n$(\".digi_pane\").append(\"<div style=\\\"clear: both;\\\"></div>\");\n</code></pre>\n\n<p>And it works precisely how I need it to. Could probably be made a bit more efficient, but it works.</p>\n"
}
] |
2008/09/30
|
[
"https://Stackoverflow.com/questions/153439",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/13611/"
] |
I'm trying to place 4 of my image containers into a new pane, having a total of 16 images. The jQuery below is what I came up with to do it. The first pane comes out correctly with 4 images in it. But the second has 4 images, plus the 3rd pane. And the 3rd pane has 4 images plus the 4th pane. I don't know exactly why the nesting is occurring. My wrapping can't be causing their index to change. I added css borders to them and it appears to be indexed correctly. How should I be going about this? What I want is to have 1-4 in one pane, 5-8 in another, 9-12, and 13-16. It needs to be dynamic so that I can change the number in each pane, so just doing it in the HTML isn't an option.
A demo of the issue can be seen here: <http://beta.whipplehill.com/mygal/rotate.html>. I'm using firebug to view the DOM.
Any help would be splentabulous!
The jQuery Code
```
$(function() {
$(".digi_image:gt(-1):lt(4)").wrapAll("<div class=\"digi_pane\"></div>").css("border", "2px solid red");
$(".digi_image:gt(3):lt(8)").wrapAll("<div class=\"digi_pane\"></div>").css("border", "2px solid blue");
$(".digi_image:gt(7):lt(12)").wrapAll("<div class=\"digi_pane\"></div>").css("border", "2px solid green");
$(".digi_image:gt(11):lt(16)").wrapAll("<div class=\"digi_pane\"></div>").css("border", "2px solid orange");
$(".digi_pane").append("<div style=\"clear: both;\"></div>");
});
```
The HTML (abbreviated), but essentially repeated 16 times.
```
<div class="digi_image">
<div class="space_holder"><img src="images/n883470064_4126667_9320.jpg" width="100" /></div>
</div>
```
|
I think your problem is your use of the gt() and lt() selectors. You should look up slice() instead.
Check out this post:
<http://docs.jquery.com/Traversing/slice>
|
153,451 |
<p>I am trying to use <code>WebClient</code> to download a file from web using a WinForms application. However, I really only want to download HTML file. Any other type I will want to ignore.</p>
<p>I checked the <code>WebResponse.ContentType</code>, but its value is always <code>null</code>. </p>
<p>Anyone have any idea what could be the cause?</p>
|
[
{
"answer_id": 153457,
"author": "Marc Gravell",
"author_id": 23354,
"author_profile": "https://Stackoverflow.com/users/23354",
"pm_score": 0,
"selected": false,
"text": "<p>You could issue the first request with the HEAD verb, and check the content-type response header? [edit] It looks like you'll have to use HttpWebRequest for this, though.</p>\n"
},
{
"answer_id": 153477,
"author": "Micah",
"author_id": 17744,
"author_profile": "https://Stackoverflow.com/users/17744",
"pm_score": 1,
"selected": false,
"text": "<p>WebResponse is an abstract class and the ContentType property is defined in inheriting classes. For instance in the HttpWebRequest object this method is overloaded to provide the content-type header. I'm not sure what instance of WebResponse the WebClient is using. If you ONLY want HTML files, your best of using the HttpWebRequest object directly.</p>\n"
},
{
"answer_id": 153694,
"author": "mdb",
"author_id": 8562,
"author_profile": "https://Stackoverflow.com/users/8562",
"pm_score": 0,
"selected": false,
"text": "<p>Your question is a bit confusing: if you're using an instance of the Net.WebClient class, the Net.WebResponse doesn't enter into the equation (apart from the fact that it's indeed an abstract class, and you'd be using a concrete implementation such as HttpWebResponse, as pointed out in another response).</p>\n\n<p>Anyway, when using WebClient, you can achieve what you want by doing something like this:</p>\n\n<pre><code>Dim wc As New Net.WebClient()\nDim LocalFile As String = IO.Path.Combine(Environment.GetEnvironmentVariable(\"TEMP\"), Guid.NewGuid.ToString)\nwc.DownloadFile(\"http://example.com/somefile\", LocalFile)\nIf Not wc.ResponseHeaders(\"Content-Type\") Is Nothing AndAlso wc.ResponseHeaders(\"Content-Type\") <> \"text/html\" Then\n IO.File.Delete(LocalFile)\nElse\n '//Process the file\nEnd If\n</code></pre>\n\n<p>Note that you do have to check for the existence of the Content-Type header, as the server is not guaranteed to return it (although most modern HTTP servers will always include it). If no Content-Type header is present, you can fall back to another HTML detection method, for example opening the file, reading the first 1K characters or so into a string, and seeing if that contains the substring <html></p>\n\n<p>Also note that this is a bit wasteful, as you'll always transfer the full file, prior to deciding whether you want it or not. To work around that, switching to the Net.HttpWebRequest/Response classes might help, but whether the extra code is worth it depends on your application...</p>\n"
},
{
"answer_id": 156101,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 0,
"selected": false,
"text": "<p>I apologize for not been very clear. I wrote a wrapper class that extends WebClient. In this wrapper class, I added cookie container and exposed the timeout property for the WebRequest.</p>\n\n<p>I was using DownloadDataAsync() from this wrapper class and I wasn't able to retrieve content-type from WebResponse of this wrapper class. My main intention is to intercept the response and determine if its of text/html nature. If it isn't, I will abort this request.</p>\n\n<p>I managed to obtain the content-type after overriding WebClient.GetWebResponse(WebRequest, IAsyncResult) method.</p>\n\n<p>The following is a sample of my wrapper class:</p>\n\n<pre><code>public class MyWebClient : WebClient\n{\n private CookieContainer _cookieContainer;\n private string _userAgent;\n private int _timeout;\n private WebReponse _response;\n\n public MyWebClient()\n {\n this._cookieContainer = new CookieContainer();\n this.SetTimeout(60 * 1000);\n }\n\n public MyWebClient SetTimeout(int timeout)\n {\n this.Timeout = timeout;\n return this;\n }\n\n public WebResponse Response\n {\n get { return this._response; }\n }\n\n protected override WebRequest GetWebRequest(Uri address)\n {\n WebRequest request = base.GetWebRequest(address);\n\n if (request.GetType() == typeof(HttpWebRequest))\n {\n ((HttpWebRequest)request).CookieContainer = this._cookieContainer;\n ((HttpWebRequest)request).UserAgent = this._userAgent;\n ((HttpWebRequest)request).Timeout = this._timeout;\n }\n\n this._request = request;\n return request;\n }\n\n protected override WebResponse GetWebResponse(WebRequest request)\n {\n this._response = base.GetWebResponse(request);\n return this._response;\n }\n\n protected override WebResponse GetWebResponse(WebRequest request, IAsyncResult result)\n {\n this._response = base.GetWebResponse(request, result);\n return this._response;\n }\n\n public MyWebClient ServerCertValidation(bool validate)\n {\n if (!validate) ServicePointManager.ServerCertificateValidationCallback += delegate(object sender, X509Certificate certificate, X509Chain chain, SslPolicyErrors sslPolicyErrors) { return true; };\n return this;\n }\n}\n</code></pre>\n"
},
{
"answer_id": 156750,
"author": "Marc Gravell",
"author_id": 23354,
"author_profile": "https://Stackoverflow.com/users/23354",
"pm_score": 7,
"selected": true,
"text": "<p>Given your update, you can do this by changing the .Method in GetWebRequest:</p>\n\n<pre><code>using System;\nusing System.Net;\nstatic class Program\n{\n static void Main()\n {\n using (MyClient client = new MyClient())\n {\n client.HeadOnly = true;\n string uri = \"http://www.google.com\";\n byte[] body = client.DownloadData(uri); // note should be 0-length\n string type = client.ResponseHeaders[\"content-type\"];\n client.HeadOnly = false;\n // check 'tis not binary... we'll use text/, but could\n // check for text/html\n if (type.StartsWith(@\"text/\"))\n {\n string text = client.DownloadString(uri);\n Console.WriteLine(text);\n }\n }\n }\n\n}\n\nclass MyClient : WebClient\n{\n public bool HeadOnly { get; set; }\n protected override WebRequest GetWebRequest(Uri address)\n {\n WebRequest req = base.GetWebRequest(address);\n if (HeadOnly && req.Method == \"GET\")\n {\n req.Method = \"HEAD\";\n }\n return req;\n }\n}\n</code></pre>\n\n<p>Alternatively, you can check the header when overriding GetWebRespons(), perhaps throwing an exception if it isn't what you wanted:</p>\n\n<pre><code>protected override WebResponse GetWebResponse(WebRequest request)\n{\n WebResponse resp = base.GetWebResponse(request);\n string type = resp.Headers[\"content-type\"];\n // do something with type\n return resp;\n}\n</code></pre>\n"
},
{
"answer_id": 8377701,
"author": "RandomInsano",
"author_id": 187769,
"author_profile": "https://Stackoverflow.com/users/187769",
"pm_score": 2,
"selected": false,
"text": "<p>I'm not sure the cause, but perhaps you hadn't downloaded anything yet. This is the lazy way to get the content type of a remote file/page (I haven't checked if this is efficient on the wire. For all I know, it may download huge chunks of content)</p>\n\n<pre><code> Stream connection = new MemoryStream(\"\"); // Just a placeholder\n WebClient wc = new WebClient();\n string contentType;\n try\n {\n connection = wc.OpenRead(current.Url);\n contentType = wc.ResponseHeaders[\"content-type\"];\n }\n catch (Exception)\n {\n // 404 or what have you\n }\n finally\n {\n connection.Close();\n }\n</code></pre>\n"
},
{
"answer_id": 51447120,
"author": "Greg",
"author_id": 3934764,
"author_profile": "https://Stackoverflow.com/users/3934764",
"pm_score": 1,
"selected": false,
"text": "<p>Here is a method using TCP, which http is built on top of. It will return when connected or after the timeout (milliseconds), so the value may need to be changed depending on your situation</p>\n\n<pre><code>var result = false;\ntry {\n using (var socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp)) {\n var asyncResult = socket.BeginConnect(yourUri.AbsoluteUri, 80, null, null);\n result = asyncResult.AsyncWaitHandle.WaitOne(100, true);\n socket.Close();\n }\n}\ncatch { }\nreturn result;\n</code></pre>\n"
}
] |
2008/09/30
|
[
"https://Stackoverflow.com/questions/153451",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] |
I am trying to use `WebClient` to download a file from web using a WinForms application. However, I really only want to download HTML file. Any other type I will want to ignore.
I checked the `WebResponse.ContentType`, but its value is always `null`.
Anyone have any idea what could be the cause?
|
Given your update, you can do this by changing the .Method in GetWebRequest:
```
using System;
using System.Net;
static class Program
{
static void Main()
{
using (MyClient client = new MyClient())
{
client.HeadOnly = true;
string uri = "http://www.google.com";
byte[] body = client.DownloadData(uri); // note should be 0-length
string type = client.ResponseHeaders["content-type"];
client.HeadOnly = false;
// check 'tis not binary... we'll use text/, but could
// check for text/html
if (type.StartsWith(@"text/"))
{
string text = client.DownloadString(uri);
Console.WriteLine(text);
}
}
}
}
class MyClient : WebClient
{
public bool HeadOnly { get; set; }
protected override WebRequest GetWebRequest(Uri address)
{
WebRequest req = base.GetWebRequest(address);
if (HeadOnly && req.Method == "GET")
{
req.Method = "HEAD";
}
return req;
}
}
```
Alternatively, you can check the header when overriding GetWebRespons(), perhaps throwing an exception if it isn't what you wanted:
```
protected override WebResponse GetWebResponse(WebRequest request)
{
WebResponse resp = base.GetWebResponse(request);
string type = resp.Headers["content-type"];
// do something with type
return resp;
}
```
|
153,460 |
<p>Most applications only have "Restore, Move, Size, Minimize, Maximize and Close", however <i>MS SQL</i> offers extra options "Help, Customize view". Along those lines, is it possible to add to the right click menu of an application in the task bar? </p>
<p>Note: I'm <b>not</b> referring to an icon in the notification area next to the clock.</p>
|
[
{
"answer_id": 153568,
"author": "C. Ross",
"author_id": 16487,
"author_profile": "https://Stackoverflow.com/users/16487",
"pm_score": 1,
"selected": false,
"text": "<p>This is a simpler <a href=\"http://bytes.com/forum/thread529258.html\" rel=\"nofollow noreferrer\">answer</a> I found. I quickly tested it and it works. </p>\n\n<p>My code:</p>\n\n<pre><code> private const int WMTaskbarRClick = 0x0313;\n\n protected override void WndProc(ref Message m)\n {\n switch (m.Msg)\n {\n case WMTaskbarRClick:\n {\n // Show your own context menu here, i do it like this\n // there's a context menu present on my main form so i use it\n\n MessageBox.Show(\"I see that.\");\n\n break;\n }\n default:\n {\n base.WndProc(ref m);\n break;\n }\n }\n }\n</code></pre>\n"
},
{
"answer_id": 58160366,
"author": "Mitch",
"author_id": 138200,
"author_profile": "https://Stackoverflow.com/users/138200",
"pm_score": 0,
"selected": false,
"text": "<p>The menu on right click of the minimized program or Alt+Space or right click of the window icon in the title bar is called the SysMenu.</p>\n\n<p>Here's an option for WPF:</p>\n\n<pre><code>// License MIT 2019 Mitch Gaffigan\n// https://stackoverflow.com/a/58160366/138200\npublic class SysMenu\n{\n private readonly Window Window;\n private readonly List<MenuItem> Items;\n private bool isInitialized;\n private IntPtr NextID = (IntPtr)1000;\n private int StartPosition = 5;\n\n public SysMenu(Window window)\n {\n this.Items = new List<MenuItem>();\n this.Window = window ?? throw new ArgumentNullException(nameof(window));\n this.Window.SourceInitialized += this.Window_SourceInitialized;\n }\n\n class MenuItem\n {\n public IntPtr ID;\n public string Text;\n public Action OnClick;\n }\n\n public void AddSysMenuItem(string text, Action onClick)\n {\n if (string.IsNullOrWhiteSpace(text))\n {\n throw new ArgumentNullException(nameof(text));\n }\n if (onClick == null)\n {\n throw new ArgumentNullException(nameof(onClick));\n }\n\n var thisId = NextID;\n NextID += 1;\n\n var newItem = new MenuItem()\n {\n ID = thisId,\n Text = text,\n OnClick = onClick\n };\n Items.Add(newItem);\n var thisPosition = StartPosition + Items.Count;\n\n if (isInitialized)\n {\n var hwndSource = PresentationSource.FromVisual(Window) as HwndSource;\n if (hwndSource == null)\n {\n return;\n }\n var hSysMenu = GetSystemMenu(hwndSource.Handle, false);\n InsertMenu(hSysMenu, thisPosition, MF_BYPOSITION, thisId, text);\n }\n }\n\n private void Window_SourceInitialized(object sender, EventArgs e)\n {\n var hwndSource = PresentationSource.FromVisual(Window) as HwndSource;\n if (hwndSource == null)\n {\n return;\n }\n\n hwndSource.AddHook(WndProc);\n\n var hSysMenu = GetSystemMenu(hwndSource.Handle, false);\n\n /// Create our new System Menu items just before the Close menu item\n InsertMenu(hSysMenu, StartPosition, MF_BYPOSITION | MF_SEPARATOR, IntPtr.Zero, string.Empty);\n int pos = StartPosition + 1;\n foreach (var item in Items)\n {\n InsertMenu(hSysMenu, pos, MF_BYPOSITION, item.ID, item.Text);\n pos += 1;\n }\n\n isInitialized = true;\n }\n\n private IntPtr WndProc(IntPtr hwnd, int msg, IntPtr wParam, IntPtr lParam, ref bool handled)\n {\n if (msg == WM_SYSCOMMAND)\n {\n var item = Items.FirstOrDefault(d => d.ID == wParam);\n if (item != null)\n {\n item.OnClick();\n handled = true;\n return IntPtr.Zero;\n }\n }\n\n return IntPtr.Zero;\n }\n\n #region Win32\n\n private const Int32 WM_SYSCOMMAND = 0x112;\n private const Int32 MF_SEPARATOR = 0x800;\n private const Int32 MF_BYPOSITION = 0x400;\n private const Int32 MF_STRING = 0x0;\n\n [DllImport(\"user32.dll\")]\n private static extern IntPtr GetSystemMenu(IntPtr hWnd, bool bRevert);\n\n [DllImport(\"user32.dll\")]\n private static extern bool InsertMenu(IntPtr hMenu, int wPosition, int wFlags, IntPtr wIDNewItem, string lpNewItem);\n\n #endregion\n}\n</code></pre>\n\n<p>Example of use:</p>\n\n<pre><code>internal partial class MainWindow : Window\n{\n public MainWindow()\n {\n var sysMenu = new SysMenu(this);\n sysMenu.AddSysMenuItem(\"Quit\", miQuit_Click);\n sysMenu.AddSysMenuItem(\"Show debug tools\", miShowDebug_Click);\n }\n\n private void miQuit_Click()\n {\n // \"On-Click\" logic here\n }\n\n private void miShowDebug_Click()\n {\n // \"On-Click\" logic here\n }\n}\n</code></pre>\n"
}
] |
2008/09/30
|
[
"https://Stackoverflow.com/questions/153460",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1484/"
] |
Most applications only have "Restore, Move, Size, Minimize, Maximize and Close", however *MS SQL* offers extra options "Help, Customize view". Along those lines, is it possible to add to the right click menu of an application in the task bar?
Note: I'm **not** referring to an icon in the notification area next to the clock.
|
This is a simpler [answer](http://bytes.com/forum/thread529258.html) I found. I quickly tested it and it works.
My code:
```
private const int WMTaskbarRClick = 0x0313;
protected override void WndProc(ref Message m)
{
switch (m.Msg)
{
case WMTaskbarRClick:
{
// Show your own context menu here, i do it like this
// there's a context menu present on my main form so i use it
MessageBox.Show("I see that.");
break;
}
default:
{
base.WndProc(ref m);
break;
}
}
}
```
|
153,482 |
<p>I have a Tapestry application that is serving its page as UTF-8. That is, server responses have header:</p>
<pre><code>Content-type: text/html;charset=UTF-8
</code></pre>
<p>Now within this application there is a single page that should be served with ISO-8859-1 encoding. That is, server response should have this header:</p>
<pre><code>Content-type: text/html;charset=ISO-8859-1
</code></pre>
<p>How to do this? I don't want to change default encoding for whole application.</p>
<p>Based on google searching I have tried following:</p>
<pre><code> @Meta({ "org.apache.tapestry.output-encoding=ISO-8859-1",
"org.apache.tapestry.response-encoding=ISO-8859-1",
"org.apache.tapestry.template-encoding=ISO-8859-1",
"tapestry.response-encoding=ISO-8859-1"})
abstract class MyPage extends BasePage {
@Override
protected String getOutputEncoding() {
return "ISO-8859-1";
}
}
</code></pre>
<p>But neither setting those values with @Meta annotation or overriding getOutputEncoding method works.</p>
<p>I am using Tapestry 4.0.2.</p>
<p>EDIT: I ended up doing this with a Servlet filter with subclassed HttpServletResposeWrapper. The wrapper overrides setContentType() to force required encoding for the response.</p>
|
[
{
"answer_id": 160706,
"author": "Brian",
"author_id": 700,
"author_profile": "https://Stackoverflow.com/users/700",
"pm_score": 3,
"selected": true,
"text": "<p>Have you considered a Filter? Maybe not as elegant as something within Tapestry, but using a plain Filter, that registers the url mapping(s) of interest. One of its init parameters would be the encoding your after. Example:</p>\n\n<pre><code>public class EncodingFilter implements Filter {\nprivate String encoding;\nprivate FilterConfig filterConfig;\n\n/**\n* @see javax.servlet.Filter#init(javax.servlet.FilterConfig)\n*/\npublic void init(FilterConfig fc) throws ServletException {\nthis.filterConfig = fc;\nthis.encoding = filterConfig.getInitParameter(\"encoding\");\n}\n\n/**\n* @see javax.servlet.Filter#doFilter(javax.servlet.ServletRequest, javax.servlet.ServletResponse, javax.servlet.FilterChain)\n*/\npublic void doFilter(ServletRequest req, ServletResponse resp,\nFilterChain chain) throws IOException, ServletException {\nreq.setCharacterEncoding(encoding);\nchain.doFilter(req, resp);\n}\n\n/**\n* @see javax.servlet.Filter#destroy()\n*/\npublic void destroy() {\n}\n\n}\n</code></pre>\n"
},
{
"answer_id": 162889,
"author": "Paul Croarkin",
"author_id": 18995,
"author_profile": "https://Stackoverflow.com/users/18995",
"pm_score": 1,
"selected": false,
"text": "<p>The filter suggestion is good. You can also mix servlets with Tapestry. For instance, we have servlets for serving displaying XML documents and dynamically generated Excel files. Just make sure that correctly set the mappings in web.xml so that that the servlets do not go through Tapestry.</p>\n"
},
{
"answer_id": 498822,
"author": "Joel",
"author_id": 60956,
"author_profile": "https://Stackoverflow.com/users/60956",
"pm_score": 1,
"selected": false,
"text": "<p>Tapestry has the concept of filters that can be applied to the request/response pipeline, but with the advantage that you can access the T5 IoC Container & Services.</p>\n\n<p><a href=\"http://tapestry.apache.org/tapestry5/tapestry-core/guide/request.html\" rel=\"nofollow noreferrer\">http://tapestry.apache.org/tapestry5/tapestry-core/guide/request.html</a></p>\n"
},
{
"answer_id": 4038022,
"author": "Andreas Andreou",
"author_id": 145404,
"author_profile": "https://Stackoverflow.com/users/145404",
"pm_score": 2,
"selected": false,
"text": "<p>You could have done:</p>\n\n<pre><code> @Override\npublic ContentType getResponseContentType() {\n return new ContentType(\"text/html;charset=\" + someCharEncoding);\n}\n</code></pre>\n"
}
] |
2008/09/30
|
[
"https://Stackoverflow.com/questions/153482",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1431/"
] |
I have a Tapestry application that is serving its page as UTF-8. That is, server responses have header:
```
Content-type: text/html;charset=UTF-8
```
Now within this application there is a single page that should be served with ISO-8859-1 encoding. That is, server response should have this header:
```
Content-type: text/html;charset=ISO-8859-1
```
How to do this? I don't want to change default encoding for whole application.
Based on google searching I have tried following:
```
@Meta({ "org.apache.tapestry.output-encoding=ISO-8859-1",
"org.apache.tapestry.response-encoding=ISO-8859-1",
"org.apache.tapestry.template-encoding=ISO-8859-1",
"tapestry.response-encoding=ISO-8859-1"})
abstract class MyPage extends BasePage {
@Override
protected String getOutputEncoding() {
return "ISO-8859-1";
}
}
```
But neither setting those values with @Meta annotation or overriding getOutputEncoding method works.
I am using Tapestry 4.0.2.
EDIT: I ended up doing this with a Servlet filter with subclassed HttpServletResposeWrapper. The wrapper overrides setContentType() to force required encoding for the response.
|
Have you considered a Filter? Maybe not as elegant as something within Tapestry, but using a plain Filter, that registers the url mapping(s) of interest. One of its init parameters would be the encoding your after. Example:
```
public class EncodingFilter implements Filter {
private String encoding;
private FilterConfig filterConfig;
/**
* @see javax.servlet.Filter#init(javax.servlet.FilterConfig)
*/
public void init(FilterConfig fc) throws ServletException {
this.filterConfig = fc;
this.encoding = filterConfig.getInitParameter("encoding");
}
/**
* @see javax.servlet.Filter#doFilter(javax.servlet.ServletRequest, javax.servlet.ServletResponse, javax.servlet.FilterChain)
*/
public void doFilter(ServletRequest req, ServletResponse resp,
FilterChain chain) throws IOException, ServletException {
req.setCharacterEncoding(encoding);
chain.doFilter(req, resp);
}
/**
* @see javax.servlet.Filter#destroy()
*/
public void destroy() {
}
}
```
|
153,507 |
<p>How do I calculate the position of an accelerating body (e.g. a car) after a certain time (e.g. 1 second)?</p>
<p>For a moving body that it not accelerating, it is a linear relationship, so I presume for an accelerating body it involves a square somewhere.</p>
<p>Any ideas? </p>
|
[
{
"answer_id": 153517,
"author": "Chris Johnson",
"author_id": 23732,
"author_profile": "https://Stackoverflow.com/users/23732",
"pm_score": 6,
"selected": true,
"text": "<p>The equation is: s = ut + (1/2)a t^2</p>\n\n<p>where s is position, u is velocity at t=0, t is time and a is a constant acceleration.</p>\n\n<p>For example, if a car starts off stationary, and accelerates for two seconds with an acceleration of 3m/s^2, it moves (1/2) * 3 * 2^2 = 6m</p>\n\n<p>This equation comes from integrating analytically the equations stating that velocity is the rate-of-change of position, and acceleration is the rate-of-change of velocity.</p>\n\n<p>Usually in a game-programming situation, one would use a slightly different formulation: at every frame, the variables for velocity and position are integrated not analytically, but numerically:</p>\n\n<pre><code>s = s + u * dt;\nu = u + a * dt;\n</code></pre>\n\n<p>where dt is the length of a frame (measured using a timer: 1/60th second or so). This method has the advantage that the acceleration can vary in time.</p>\n\n<p><strong>Edit</strong> A couple of people have noted that the Euler method of numerical integration (as shown here), though the simplest to demonstrate with, has fairly poor accuracy. See <a href=\"http://en.wikipedia.org/wiki/Verlet_integration\" rel=\"noreferrer\">Velocity Verlet</a> (often used in games), and <a href=\"http://en.wikipedia.org/wiki/Runge_kutta\" rel=\"noreferrer\">4th order Runge Kutta</a> (a 'standard' method for scientific applications) for improved algorithms.</p>\n"
},
{
"answer_id": 153526,
"author": "asterite",
"author_id": 20459,
"author_profile": "https://Stackoverflow.com/users/20459",
"pm_score": 2,
"selected": false,
"text": "<p>You can google it. I've found this: <a href=\"http://www.ugrad.math.ubc.ca/coursedoc/math101/notes/applications/velocity.html\" rel=\"nofollow noreferrer\">http://www.ugrad.math.ubc.ca/coursedoc/math101/notes/applications/velocity.html</a></p>\n\n<p>But if you don't want to read, it's:</p>\n\n<blockquote>\n <p>p(t) = x(0) + v(0)*t + (1/2)<em>a</em>t^2</p>\n</blockquote>\n\n<p>where</p>\n\n<ul>\n<li>p(t) = position at time t</li>\n<li>x(0) = the position at time zero</li>\n<li>v(0) = velocity at time zero (if you don't have a velocity, you can ignore this term)</li>\n<li>a = the acceleration</li>\n<li>t = your current itme</li>\n</ul>\n"
},
{
"answer_id": 153531,
"author": "Mihai Limbășan",
"author_id": 14444,
"author_profile": "https://Stackoverflow.com/users/14444",
"pm_score": 1,
"selected": false,
"text": "<p>Assuming you're dealing with constant acceleration, the formula is:</p>\n\n<p>distance = (initial_velocity * time) + (acceleration * time * time) / 2</p>\n\n<p>where</p>\n\n<p><i>distance</i> is the distance traveled</p>\n\n<p><i>initial_velocity</i> is the initial velocity (zero if the body is intially at rest, so you can drop this term in that case)</p>\n\n<p><i>time</i> is the time</p>\n\n<p><i>acceleration</i> is the (constant) acceleration</p>\n\n<p>Make sure to use the proper units when calculating, i.e. meters, seconds and so on.</p>\n\n<p>A very good book on the topic is <a href=\"http://oreilly.com/catalog/9780596000066/\" rel=\"nofollow noreferrer\">Physics for Game Developers</a>.</p>\n"
},
{
"answer_id": 153551,
"author": "freespace",
"author_id": 8297,
"author_profile": "https://Stackoverflow.com/users/8297",
"pm_score": 3,
"selected": false,
"text": "<p>Well, it depends on whether or not acceleration is constant. If it is it is simply</p>\n\n<pre><code>s = ut+1/2 at^2\n</code></pre>\n\n<p>If a is not constant, you need to numerically integrated. Now there is a variety of methods and none of them will beat doing this by hand for accuracy, as they are all ultimately approximate solutions.</p>\n\n<p>The easiest and least accurate is <a href=\"http://en.wikipedia.org/wiki/Eulers_method\" rel=\"noreferrer\">Euler's method</a> . Here you divide time into discrete chunks called time steps, and perform</p>\n\n<pre><code>v[n] = v[n-1] * t * a[t]\n</code></pre>\n\n<p><code>n</code> is index, <code>t</code> is size of a time step. Position is similarly updated. This is only really good for those cases where accuracy is not all that important. A special version of Euler's method will yield an exact solution for projectile motion (see wiki), so while this method is crude, it can be perfect for some suituations.</p>\n\n<p>The most common numerical integration method used in games and in some chemistry simulations is <a href=\"http://en.wikipedia.org/wiki/Velocity_Verlet#Velocity_Verlet\" rel=\"noreferrer\">Velocity Verlet</a>, which is a special form of the more generic Verlet method. I would recommend this one if Euler's is too crude.</p>\n"
},
{
"answer_id": 153557,
"author": "jholl",
"author_id": 5065,
"author_profile": "https://Stackoverflow.com/users/5065",
"pm_score": 1,
"selected": false,
"text": "<p>Assuming constant acceleration and initial velocity v0,</p>\n\n<pre><code>x(t) = (1/2 * a * t^2) + (v0 * t)\n</code></pre>\n"
}
] |
2008/09/30
|
[
"https://Stackoverflow.com/questions/153507",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11911/"
] |
How do I calculate the position of an accelerating body (e.g. a car) after a certain time (e.g. 1 second)?
For a moving body that it not accelerating, it is a linear relationship, so I presume for an accelerating body it involves a square somewhere.
Any ideas?
|
The equation is: s = ut + (1/2)a t^2
where s is position, u is velocity at t=0, t is time and a is a constant acceleration.
For example, if a car starts off stationary, and accelerates for two seconds with an acceleration of 3m/s^2, it moves (1/2) \* 3 \* 2^2 = 6m
This equation comes from integrating analytically the equations stating that velocity is the rate-of-change of position, and acceleration is the rate-of-change of velocity.
Usually in a game-programming situation, one would use a slightly different formulation: at every frame, the variables for velocity and position are integrated not analytically, but numerically:
```
s = s + u * dt;
u = u + a * dt;
```
where dt is the length of a frame (measured using a timer: 1/60th second or so). This method has the advantage that the acceleration can vary in time.
**Edit** A couple of people have noted that the Euler method of numerical integration (as shown here), though the simplest to demonstrate with, has fairly poor accuracy. See [Velocity Verlet](http://en.wikipedia.org/wiki/Verlet_integration) (often used in games), and [4th order Runge Kutta](http://en.wikipedia.org/wiki/Runge_kutta) (a 'standard' method for scientific applications) for improved algorithms.
|
153,527 |
<p>I have a page that contains a form. This page is served with content type text/html;charset=utf-8. I need to submit this form to server using ISO-8859-1 character encoding. Is this possible with Internet Explorer?</p>
<p>Setting accept-charset attribute to form element, like this, works for Firefox, Opera etc. but not for IE.</p>
<pre><code><form accept-charset="ISO-8859-1">
...
</form>
</code></pre>
<p>Edit: This form is created by server A and will be submitted to server B. I have no control over server B.</p>
<p>If I set server A to serve content with charset ISO-8859-1 everything works, but I am looking a way to make this work without changes to server A's encoding. I have another question <a href="https://stackoverflow.com/questions/153482/setting-iso-8859-1-encoding-for-a-single-tapestry-4-page-in-application-that-is">about setting the encoding in server A.</a></p>
|
[
{
"answer_id": 153578,
"author": "pdc",
"author_id": 8925,
"author_profile": "https://Stackoverflow.com/users/8925",
"pm_score": -1,
"selected": false,
"text": "<p>I am pretty sure it won't be possible with older versions of IE. Before the <code>accept-charset</code> attribute was devised, there was no way for <code>form</code> elements to specify which character encoding they accepted, and the best that browsers could do is assume the encoding of the page the form is in will do.</p>\n\n<p>It is a bit sad that you need to know which encoding was used -- nowadays we would expect our web frameworks to take care of such details invisibly and expose the text data to the application as Unicode strings, already decoded...</p>\n"
},
{
"answer_id": 153619,
"author": "PhiLho",
"author_id": 15459,
"author_profile": "https://Stackoverflow.com/users/15459",
"pm_score": 0,
"selected": false,
"text": "<p>Looks like Microsoft knows <a href=\"http://msdn.microsoft.com/en-us/library/ms533061%28VS.85%29.aspx\" rel=\"nofollow noreferrer\" title=\"acceptCharset Property (FORM)\">accept-charset</a>, but their doc doesn't tell for which version it starts to work...<br>\nYou don't tell either in which versions of browser you tested it.</p>\n"
},
{
"answer_id": 155133,
"author": "warp",
"author_id": 7700,
"author_profile": "https://Stackoverflow.com/users/7700",
"pm_score": 0,
"selected": false,
"text": "<p>I seem to remember that Internet Explorer gets confused if the accept-charset encoding doesn't match the encoding specified in the content-type header. In your example, you claim the document is sent as UTF-8, but want form submits in ISO-8859-1. Try matching those and see if that solves your problem.</p>\n"
},
{
"answer_id": 155140,
"author": "Edward Z. Yang",
"author_id": 23845,
"author_profile": "https://Stackoverflow.com/users/23845",
"pm_score": 2,
"selected": false,
"text": "<p>If you have any access to the server at all, convert its processing to UTF-8. The art of submitting non-UTF-8 forms is a long and sorry story; this <a href=\"http://web.archive.org/web/20060427015200/ppewww.ph.gla.ac.uk/~flavell/charset/form-i18n.html\" rel=\"nofollow noreferrer\">document about forms and i18n</a> may be of interest. I understand you do not seem to care about international support; you can always convert the UTF-8 data to html entities to make sure it stays Latin-1.</p>\n"
},
{
"answer_id": 182862,
"author": "Juha Syrjälä",
"author_id": 1431,
"author_profile": "https://Stackoverflow.com/users/1431",
"pm_score": 3,
"selected": false,
"text": "<p>It seems that this can't be done, not at least with current versions of IE (6 and 7).</p>\n\n<p>IE supports form attribute accept-charset, but only if its value is 'utf-8'. </p>\n\n<p>The solution is to modify server A to produce encoding 'ISO-8859-1' for page that contains the form.</p>\n"
},
{
"answer_id": 1213849,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": -1,
"selected": false,
"text": "<pre><code><meta http-equiv=\"Content-Type\" content=\"text/html; charset=iso-8859-1\">\n</code></pre>\n"
},
{
"answer_id": 1367468,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 5,
"selected": false,
"text": "<p>There is a simple hack to this:</p>\n\n<p>Insert a hidden input field in the form with an entity which only occur in the character set the server your posting (or doing a GET) to accepts.</p>\n\n<p>Example: If the form is located on a server serving ISO-8859-1 and the form will post to a server expecting UTF-8 insert something like this in the form:</p>\n\n<pre><code><input name=\"iehack\" type=\"hidden\" value=\"&#9760;\" />\n</code></pre>\n\n<p>IE will then \"detect\" that the form contains a UTF-8 character and use UTF-8 when you POST or GET. Strange, but it does work.</p>\n"
},
{
"answer_id": 3322237,
"author": "David Mongeau-Petitpas",
"author_id": 400666,
"author_profile": "https://Stackoverflow.com/users/400666",
"pm_score": 1,
"selected": false,
"text": "<p>Just got the same problem and I have a relatively simple solution that does not require any change in the page character encoding(wich is a pain in the ass).</p>\n\n<p>For example, your site is in utf-8 and you want to post a form to a site in iso-8859-1. Just change the action of the post to a page on your site that will convert the posted values from utf-8 to iso-8859-1.</p>\n\n<p>this could be done easily in php with something like this:</p>\n\n<pre><code><?php\n$params = array();\nforeach($_POST as $key=>$value) {\n $params[] = $key.\"=\".rawurlencode(utf8_decode($value));\n}\n$params = implode(\"&\",$params);\n\n//then you redirect to the final page in iso-8859-1\n?>\n</code></pre>\n"
},
{
"answer_id": 5633163,
"author": "Christian",
"author_id": 703762,
"author_profile": "https://Stackoverflow.com/users/703762",
"pm_score": 3,
"selected": false,
"text": "<p>I've got the same problem here. I have an UTF-8 Page an need to post to an ISO-8859-1 server.</p>\n\n<p>Looks like IE can't handle ISO-8859-1. <strong>But</strong> it can handle ISO-8859-<strong>15</strong>.</p>\n\n<pre><code><form accept-charset=\"ISO-8859-15\">\n ...\n</form>\n</code></pre>\n\n<p>So this worked for me, since ISO-8859-1 and ISO-8859-15 are almost the same.</p>\n"
},
{
"answer_id": 10067631,
"author": "dr.dimitru",
"author_id": 1320932,
"author_profile": "https://Stackoverflow.com/users/1320932",
"pm_score": 1,
"selected": false,
"text": "<p>For Russian symbols 'windows-1251'</p>\n\n<pre><code><form action=\"yourProcessPage.php\" method=\"POST\" accept-charset=\"utf-8\">\n<input name=\"string\" value=\"string\" />\n...\n</form>\n</code></pre>\n\n<p>When simply convert string to cp1251</p>\n\n<pre><code>$string = $_POST['string'];\n$string = mb_convert_encoding($string, \"CP1251\", \"UTF-8\");\n</code></pre>\n"
},
{
"answer_id": 11863480,
"author": "dgaspar",
"author_id": 198080,
"author_profile": "https://Stackoverflow.com/users/198080",
"pm_score": 5,
"selected": false,
"text": "<p>With decent browsers:</p>\n\n<pre><code><form accept-charset=\"ISO-8859-1\" .... >\n</code></pre>\n\n<p>With IE (any):</p>\n\n<pre><code>document.charset = 'ISO-8859-1'; // do this before submitting your non-utf8 <form>!\n</code></pre>\n"
}
] |
2008/09/30
|
[
"https://Stackoverflow.com/questions/153527",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1431/"
] |
I have a page that contains a form. This page is served with content type text/html;charset=utf-8. I need to submit this form to server using ISO-8859-1 character encoding. Is this possible with Internet Explorer?
Setting accept-charset attribute to form element, like this, works for Firefox, Opera etc. but not for IE.
```
<form accept-charset="ISO-8859-1">
...
</form>
```
Edit: This form is created by server A and will be submitted to server B. I have no control over server B.
If I set server A to serve content with charset ISO-8859-1 everything works, but I am looking a way to make this work without changes to server A's encoding. I have another question [about setting the encoding in server A.](https://stackoverflow.com/questions/153482/setting-iso-8859-1-encoding-for-a-single-tapestry-4-page-in-application-that-is)
|
There is a simple hack to this:
Insert a hidden input field in the form with an entity which only occur in the character set the server your posting (or doing a GET) to accepts.
Example: If the form is located on a server serving ISO-8859-1 and the form will post to a server expecting UTF-8 insert something like this in the form:
```
<input name="iehack" type="hidden" value="☠" />
```
IE will then "detect" that the form contains a UTF-8 character and use UTF-8 when you POST or GET. Strange, but it does work.
|
153,573 |
<p>Take the following C# class:</p>
<pre><code>c1 {
event EventHandler someEvent;
}
</code></pre>
<p>If there are a lot of subscriptions to <code>c1</code>'s <code>someEvent</code> event and I want to clear them all, what is the best way to achieve this? <strong>Also consider that subscriptions to this event could be/are lambdas/anonymous delegates.</strong></p>
<p>Currently my solution is to add a <code>ResetSubscriptions()</code> method to <code>c1</code> that sets <code>someEvent</code> to null. I don't know if this has any unseen consequences.</p>
|
[
{
"answer_id": 153577,
"author": "programmer",
"author_id": 5289,
"author_profile": "https://Stackoverflow.com/users/5289",
"pm_score": 5,
"selected": false,
"text": "<p>Add a method to c1 that will set 'someEvent' to null.</p>\n<pre><code>public class c1\n{\n event EventHandler someEvent;\n public ResetSubscriptions() => someEvent = null; \n}\n</code></pre>\n"
},
{
"answer_id": 153594,
"author": "Micah",
"author_id": 17744,
"author_profile": "https://Stackoverflow.com/users/17744",
"pm_score": 3,
"selected": false,
"text": "<p>You can achieve this by using the Delegate.Remove or Delegate.RemoveAll methods.</p>\n"
},
{
"answer_id": 153744,
"author": "Jon Skeet",
"author_id": 22656,
"author_profile": "https://Stackoverflow.com/users/22656",
"pm_score": 9,
"selected": true,
"text": "<p>From within the class, you can set the (hidden) variable to null. A null reference is the canonical way of representing an empty invocation list, effectively.</p>\n\n<p>From outside the class, you can't do this - events basically expose \"subscribe\" and \"unsubscribe\" and that's it.</p>\n\n<p>It's worth being aware of what field-like events are actually doing - they're creating a variable <em>and</em> an event at the same time. Within the class, you end up referencing the variable. From outside, you reference the event.</p>\n\n<p>See my <a href=\"http://csharpindepth.com/Articles/Chapter2/Events.aspx\" rel=\"noreferrer\">article on events and delegates</a> for more information.</p>\n"
},
{
"answer_id": 157162,
"author": "Jonathan C Dickinson",
"author_id": 24064,
"author_profile": "https://Stackoverflow.com/users/24064",
"pm_score": 3,
"selected": false,
"text": "<p>Setting the event to null inside the class works. When you dispose a class you should always set the event to null, the GC has problems with events and may not clean up the disposed class if it has dangling events.</p>\n"
},
{
"answer_id": 5423873,
"author": "umlcat",
"author_id": 535724,
"author_profile": "https://Stackoverflow.com/users/535724",
"pm_score": 2,
"selected": false,
"text": "<p><strong>Conceptual extended boring comment.</strong></p>\n\n<p>I rather use the word \"event handler\" instead of \"event\" or \"delegate\". And used the word \"event\" for other stuff. In some programming languages (VB.NET, Object Pascal, Objective-C), \"event\" is called a \"message\" or \"signal\", and even have a \"message\" keyword, and specific sugar syntax.</p>\n\n<pre><code>const\n WM_Paint = 998; // <-- \"question\" can be done by several talkers\n WM_Clear = 546;\n\ntype\n MyWindowClass = class(Window)\n procedure NotEventHandlerMethod_1;\n procedure NotEventHandlerMethod_17;\n\n procedure DoPaintEventHandler; message WM_Paint; // <-- \"answer\" by this listener\n procedure DoClearEventHandler; message WM_Clear;\n end;\n</code></pre>\n\n<p>And, in order to respond to that \"message\", a \"event handler\" respond, whether is a single delegate or multiple delegates.</p>\n\n<p>Summary:\n\"Event\" is the \"question\", \"event handler (s)\" are the answer (s).</p>\n"
},
{
"answer_id": 12914223,
"author": "Cary",
"author_id": 250428,
"author_profile": "https://Stackoverflow.com/users/250428",
"pm_score": 3,
"selected": false,
"text": "<p>The best practice to clear all subscribers is to set the someEvent to null by adding another public method if you want to expose this functionality to outside. This has no unseen consequences. The precondition is to remember to declare SomeEvent with the keyword 'event'.</p>\n<p>Please see the book - C# 4.0 in the nutshell, page 125.</p>\n<p>Some one here proposed to use <code>Delegate.RemoveAll</code> method. If you use it, the sample code could follow the below form. But it is really stupid. Why not just <code>SomeEvent=null</code> inside the <code>ClearSubscribers()</code> function?</p>\n<pre><code>public void ClearSubscribers ()\n{\n SomeEvent = (EventHandler) Delegate.RemoveAll(SomeEvent, SomeEvent);\n // Then you will find SomeEvent is set to null.\n}\n</code></pre>\n"
},
{
"answer_id": 20711094,
"author": "Googol",
"author_id": 3123953,
"author_profile": "https://Stackoverflow.com/users/3123953",
"pm_score": 1,
"selected": false,
"text": "<h1>Remove all events, assume the event is an \"Action\" type:</h1>\n\n<pre><code>Delegate[] dary = TermCheckScore.GetInvocationList();\n\nif ( dary != null )\n{\n foreach ( Delegate del in dary )\n {\n TermCheckScore -= ( Action ) del;\n }\n}\n</code></pre>\n"
},
{
"answer_id": 23393492,
"author": "Feng",
"author_id": 3590189,
"author_profile": "https://Stackoverflow.com/users/3590189",
"pm_score": 3,
"selected": false,
"text": "<pre><code>class c1\n{\n event EventHandler someEvent;\n ResetSubscriptions() => someEvent = delegate { };\n}\n</code></pre>\n<p>It is better to use <code>delegate { }</code> than <code>null</code> to avoid the null ref exception.</p>\n"
},
{
"answer_id": 49105203,
"author": "Jalal",
"author_id": 375958,
"author_profile": "https://Stackoverflow.com/users/375958",
"pm_score": 0,
"selected": false,
"text": "<p>This is my solution:</p>\n\n<pre><code>public class Foo : IDisposable\n{\n private event EventHandler _statusChanged;\n public event EventHandler StatusChanged\n {\n add\n {\n _statusChanged += value;\n }\n remove\n {\n _statusChanged -= value;\n }\n }\n\n public void Dispose()\n {\n _statusChanged = null;\n }\n}\n</code></pre>\n\n<p>You need to call <code>Dispose()</code> or use <code>using(new Foo()){/*...*/}</code> pattern to unsubscribe all members of invocation list.</p>\n"
},
{
"answer_id": 59970512,
"author": "barthdamon",
"author_id": 4530616,
"author_profile": "https://Stackoverflow.com/users/4530616",
"pm_score": -1,
"selected": false,
"text": "<p>Instead of adding and removing callbacks manually and having a bunch of delegate types declared everywhere:</p>\n<pre><code>// The hard way\npublic delegate void ObjectCallback(ObjectType broadcaster);\n\npublic class Object\n{\n public event ObjectCallback m_ObjectCallback;\n \n void SetupListener()\n {\n ObjectCallback callback = null;\n callback = (ObjectType broadcaster) =>\n {\n // one time logic here\n broadcaster.m_ObjectCallback -= callback;\n };\n m_ObjectCallback += callback;\n\n }\n \n void BroadcastEvent()\n {\n m_ObjectCallback?.Invoke(this);\n }\n}\n</code></pre>\n<p>You could try this generic approach:</p>\n<pre><code>public class Object\n{\n public Broadcast<Object> m_EventToBroadcast = new Broadcast<Object>();\n\n void SetupListener()\n {\n m_EventToBroadcast.SubscribeOnce((ObjectType broadcaster) => {\n // one time logic here\n });\n }\n\n ~Object()\n {\n m_EventToBroadcast.Dispose();\n m_EventToBroadcast = null;\n }\n\n void BroadcastEvent()\n {\n m_EventToBroadcast.Broadcast(this);\n }\n}\n\n\npublic delegate void ObjectDelegate<T>(T broadcaster);\npublic class Broadcast<T> : IDisposable\n{\n private event ObjectDelegate<T> m_Event;\n private List<ObjectDelegate<T>> m_SingleSubscribers = new List<ObjectDelegate<T>>();\n\n ~Broadcast()\n {\n Dispose();\n }\n\n public void Dispose()\n {\n Clear();\n System.GC.SuppressFinalize(this);\n }\n\n public void Clear()\n {\n m_SingleSubscribers.Clear();\n m_Event = delegate { };\n }\n\n // add a one shot to this delegate that is removed after first broadcast\n public void SubscribeOnce(ObjectDelegate<T> del)\n {\n m_Event += del;\n m_SingleSubscribers.Add(del);\n }\n\n // add a recurring delegate that gets called each time\n public void Subscribe(ObjectDelegate<T> del)\n {\n m_Event += del;\n }\n\n public void Unsubscribe(ObjectDelegate<T> del)\n {\n m_Event -= del;\n }\n\n public void Broadcast(T broadcaster)\n {\n m_Event?.Invoke(broadcaster);\n for (int i = 0; i < m_SingleSubscribers.Count; ++i)\n {\n Unsubscribe(m_SingleSubscribers[i]);\n }\n m_SingleSubscribers.Clear();\n }\n}\n</code></pre>\n"
}
] |
2008/09/30
|
[
"https://Stackoverflow.com/questions/153573",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5289/"
] |
Take the following C# class:
```
c1 {
event EventHandler someEvent;
}
```
If there are a lot of subscriptions to `c1`'s `someEvent` event and I want to clear them all, what is the best way to achieve this? **Also consider that subscriptions to this event could be/are lambdas/anonymous delegates.**
Currently my solution is to add a `ResetSubscriptions()` method to `c1` that sets `someEvent` to null. I don't know if this has any unseen consequences.
|
From within the class, you can set the (hidden) variable to null. A null reference is the canonical way of representing an empty invocation list, effectively.
From outside the class, you can't do this - events basically expose "subscribe" and "unsubscribe" and that's it.
It's worth being aware of what field-like events are actually doing - they're creating a variable *and* an event at the same time. Within the class, you end up referencing the variable. From outside, you reference the event.
See my [article on events and delegates](http://csharpindepth.com/Articles/Chapter2/Events.aspx) for more information.
|
153,584 |
<p>How do I iterate over a timespan after days, hours, weeks or months?</p>
<p>Something like:</p>
<pre><code>for date in foo(from_date, to_date, delta=HOURS):
print date
</code></pre>
<p>Where foo is a function, returning an iterator. I've been looking at the calendar module, but that only works for one specific year or month, not between dates.</p>
|
[
{
"answer_id": 153640,
"author": "dguaraglia",
"author_id": 2384,
"author_profile": "https://Stackoverflow.com/users/2384",
"pm_score": -1,
"selected": false,
"text": "<p>This library provides a handy calendar tool: <a href=\"http://www.egenix.com/products/python/mxBase/mxDateTime/\" rel=\"nofollow noreferrer\">mxDateTime</a>, that should be enough :)</p>\n"
},
{
"answer_id": 153667,
"author": "DzinX",
"author_id": 18745,
"author_profile": "https://Stackoverflow.com/users/18745",
"pm_score": 6,
"selected": false,
"text": "<p>I don't think there is a method in Python library, but you can easily create one yourself using <a href=\"http://docs.python.org/lib/module-datetime.html\" rel=\"noreferrer\">datetime</a> module:</p>\n\n<pre><code>from datetime import date, datetime, timedelta\n\ndef datespan(startDate, endDate, delta=timedelta(days=1)):\n currentDate = startDate\n while currentDate < endDate:\n yield currentDate\n currentDate += delta\n</code></pre>\n\n<p>Then you could use it like this:</p>\n\n<pre><code>>>> for day in datespan(date(2007, 3, 30), date(2007, 4, 3), \n>>> delta=timedelta(days=1)):\n>>> print day\n2007-03-30\n2007-03-31\n2007-04-01\n2007-04-02\n</code></pre>\n\n<p>Or, if you wish to make your delta smaller:</p>\n\n<pre><code>>>> for timestamp in datespan(datetime(2007, 3, 30, 15, 30), \n>>> datetime(2007, 3, 30, 18, 35), \n>>> delta=timedelta(hours=1)):\n>>> print timestamp\n2007-03-30 15:30:00\n2007-03-30 16:30:00\n2007-03-30 17:30:00\n2007-03-30 18:30:00\n</code></pre>\n"
},
{
"answer_id": 154055,
"author": "giltay",
"author_id": 21106,
"author_profile": "https://Stackoverflow.com/users/21106",
"pm_score": 3,
"selected": false,
"text": "<p>For iterating over months you need a different recipe, since timedeltas can't express \"one month\".</p>\n\n<pre><code>from datetime import date\n\ndef jump_by_month(start_date, end_date, month_step=1):\n current_date = start_date\n while current_date < end_date:\n yield current_date\n carry, new_month = divmod(current_date.month - 1 + month_step, 12)\n new_month += 1\n current_date = current_date.replace(year=current_date.year + carry,\n month=new_month)\n</code></pre>\n\n<p>(NB: you have to subtract 1 from the month for the modulus operation then add it back to <code>new_month</code>, since months in <code>datetime.date</code>s start at 1.)</p>\n"
},
{
"answer_id": 155172,
"author": "Thomas Vander Stichele",
"author_id": 2900,
"author_profile": "https://Stackoverflow.com/users/2900",
"pm_score": 8,
"selected": true,
"text": "<p>Use <a href=\"http://labix.org/python-dateutil\" rel=\"noreferrer\">dateutil</a> and its rrule implementation, like so:</p>\n\n<pre><code>from dateutil import rrule\nfrom datetime import datetime, timedelta\n\nnow = datetime.now()\nhundredDaysLater = now + timedelta(days=100)\n\nfor dt in rrule.rrule(rrule.MONTHLY, dtstart=now, until=hundredDaysLater):\n print dt\n</code></pre>\n\n<p>Output is</p>\n\n<pre><code>2008-09-30 23:29:54\n2008-10-30 23:29:54\n2008-11-30 23:29:54\n2008-12-30 23:29:54\n</code></pre>\n\n<p>Replace MONTHLY with any of YEARLY, MONTHLY, WEEKLY, DAILY, HOURLY, MINUTELY, or SECONDLY. Replace dtstart and until with whatever datetime object you want.</p>\n\n<p>This recipe has the advantage for working in all cases, including MONTHLY. Only caveat I could find is that if you pass a day number that doesn't exist for all months, it skips those months.</p>\n"
},
{
"answer_id": 751595,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": -1,
"selected": false,
"text": "<p>You should modify this line to make this work correctly:</p>\n\n<p>current_date = current_date.replace(year=current_date.year + carry,month=new_month,day=1)</p>\n\n<p>;)</p>\n"
},
{
"answer_id": 39471227,
"author": "Rafa He So",
"author_id": 4480002,
"author_profile": "https://Stackoverflow.com/users/4480002",
"pm_score": 0,
"selected": false,
"text": "<p>Month iteration approach:</p>\n\n<pre><code>def months_between(date_start, date_end):\n months = []\n\n # Make sure start_date is smaller than end_date\n if date_start > date_end:\n tmp = date_start\n date_start = date_end\n date_end = tmp\n\n tmp_date = date_start\n while tmp_date.month <= date_end.month or tmp_date.year < date_end.year:\n months.append(tmp_date) # Here you could do for example: months.append(datetime.datetime.strftime(tmp_date, \"%b '%y\"))\n\n if tmp_date.month == 12: # New year\n tmp_date = datetime.date(tmp_date.year + 1, 1, 1)\n else:\n tmp_date = datetime.date(tmp_date.year, tmp_date.month + 1, 1)\n return months\n</code></pre>\n\n<p>More code but it will do fine dealing with long periods of time checking that the given dates are in order...</p>\n"
},
{
"answer_id": 50484799,
"author": "Thilina Madumal",
"author_id": 9814901,
"author_profile": "https://Stackoverflow.com/users/9814901",
"pm_score": 3,
"selected": false,
"text": "<p>I achieved this using pandas and datetime libraries as follows. It was much more convenient for me.</p>\n\n<pre><code>import pandas as pd\nfrom datetime import datetime\n\n\nDATE_TIME_FORMAT = '%Y-%m-%d %H:%M:%S'\n\nstart_datetime = datetime.strptime('2018-05-18 00:00:00', DATE_TIME_FORMAT)\nend_datetime = datetime.strptime('2018-05-23 13:00:00', DATE_TIME_FORMAT)\n\ntimedelta_index = pd.date_range(start=start_datetime, end=end_datetime, freq='H').to_series()\nfor index, value in timedelta_index.iteritems():\n dt = index.to_pydatetime()\n print(dt)\n</code></pre>\n"
}
] |
2008/09/30
|
[
"https://Stackoverflow.com/questions/153584",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/473/"
] |
How do I iterate over a timespan after days, hours, weeks or months?
Something like:
```
for date in foo(from_date, to_date, delta=HOURS):
print date
```
Where foo is a function, returning an iterator. I've been looking at the calendar module, but that only works for one specific year or month, not between dates.
|
Use [dateutil](http://labix.org/python-dateutil) and its rrule implementation, like so:
```
from dateutil import rrule
from datetime import datetime, timedelta
now = datetime.now()
hundredDaysLater = now + timedelta(days=100)
for dt in rrule.rrule(rrule.MONTHLY, dtstart=now, until=hundredDaysLater):
print dt
```
Output is
```
2008-09-30 23:29:54
2008-10-30 23:29:54
2008-11-30 23:29:54
2008-12-30 23:29:54
```
Replace MONTHLY with any of YEARLY, MONTHLY, WEEKLY, DAILY, HOURLY, MINUTELY, or SECONDLY. Replace dtstart and until with whatever datetime object you want.
This recipe has the advantage for working in all cases, including MONTHLY. Only caveat I could find is that if you pass a day number that doesn't exist for all months, it skips those months.
|
153,585 |
<p>In MS Transact SQL, let's say I have a table (Orders) like this:</p>
<pre><code> Order Date Order Total Customer #
09/30/2008 8.00 1
09/15/2008 6.00 1
09/01/2008 9.50 1
09/01/2008 1.45 2
09/16/2008 4.50 2
09/17/2008 8.75 3
09/18/2008 2.50 3
</code></pre>
<p>What I need out of this is: for each customer the average order amount for the most recent two orders. So for Customer #1, I should get 7.00 (and not 7.83).</p>
<p>I've been staring at this for an hour now (inside a larger problem, which I've solved) and I think my brain has frozen. Help for a simple problem?</p>
|
[
{
"answer_id": 153601,
"author": "albertein",
"author_id": 23020,
"author_profile": "https://Stackoverflow.com/users/23020",
"pm_score": 4,
"selected": true,
"text": "<p>This should make it</p>\n\n<pre><code>select avg(total), customer \nfrom orders o1 \nwhere orderdate in \n ( select top 2 date \n from orders o2 \n where o2.customer = o1.customer \n order by date desc )\ngroup by customer\n</code></pre>\n"
},
{
"answer_id": 153612,
"author": "Sklivvz",
"author_id": 7028,
"author_profile": "https://Stackoverflow.com/users/7028",
"pm_score": 0,
"selected": false,
"text": "<p>In SQL Server 2005 you have the RANK function, used with partition:</p>\n\n<pre><code>USE AdventureWorks;\nGO\nSELECT i.ProductID, p.Name, i.LocationID, i.Quantity\n ,RANK() OVER \n (PARTITION BY i.LocationID ORDER BY i.Quantity DESC) AS 'RANK'\nFROM Production.ProductInventory i \n INNER JOIN Production.Product p \n ON i.ProductID = p.ProductID\nORDER BY p.Name;\nGO\n</code></pre>\n\n<p><a href=\"http://msdn.microsoft.com/en-us/library/ms176102.aspx\" rel=\"nofollow noreferrer\">Link</a></p>\n"
},
{
"answer_id": 153621,
"author": "Ian Jacobs",
"author_id": 22818,
"author_profile": "https://Stackoverflow.com/users/22818",
"pm_score": 0,
"selected": false,
"text": "<p>One option would be for you to use a cursor to loop through all the customer Id's, then do the averages as several subqueries.</p>\n\n<p>Fair warning though, for large datasets, queries are not very efficient and can take a long time to process.</p>\n"
}
] |
2008/09/30
|
[
"https://Stackoverflow.com/questions/153585",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/8173/"
] |
In MS Transact SQL, let's say I have a table (Orders) like this:
```
Order Date Order Total Customer #
09/30/2008 8.00 1
09/15/2008 6.00 1
09/01/2008 9.50 1
09/01/2008 1.45 2
09/16/2008 4.50 2
09/17/2008 8.75 3
09/18/2008 2.50 3
```
What I need out of this is: for each customer the average order amount for the most recent two orders. So for Customer #1, I should get 7.00 (and not 7.83).
I've been staring at this for an hour now (inside a larger problem, which I've solved) and I think my brain has frozen. Help for a simple problem?
|
This should make it
```
select avg(total), customer
from orders o1
where orderdate in
( select top 2 date
from orders o2
where o2.customer = o1.customer
order by date desc )
group by customer
```
|
153,592 |
<p>I'm using .NET to make an application with a drawing surface, similar to Visio. The UI connects two objects on the screen with Graphics.DrawLine. This simple implementation works fine, but as the surface gets more complex, I need a more robust way to represent the objects. One of these robust requirements is determining the intersection point for two lines so I can indicate separation via some kind of graphic.</p>
<p>So my question is, can anyone suggest a way to do this? Perhaps with a different technique (maybe GraphViz) or an algorithm?</p>
|
[
{
"answer_id": 153631,
"author": "Steven A. Lowe",
"author_id": 9345,
"author_profile": "https://Stackoverflow.com/users/9345",
"pm_score": 2,
"selected": false,
"text": "<p>You can ask Dr. Math, see <a href=\"https://web.archive.org/web/20180211083203/http://mathforum.org/library/drmath/view/53254.html\" rel=\"nofollow noreferrer\">this link</a>.</p>\n"
},
{
"answer_id": 153780,
"author": "Chris Johnson",
"author_id": 23732,
"author_profile": "https://Stackoverflow.com/users/23732",
"pm_score": 4,
"selected": true,
"text": "<p>The representation of lines by y = mx + c is problematic for computer graphics, because vertical lines require m to be infinite.</p>\n\n<p>Furthermore, lines in computer graphics have a start and end point, unlike mathematical lines which are infinite in extent. One is usually only interested in a crossing of lines if the crossing point lies on both the line segments in question.</p>\n\n<p>If you have two line segments, one from vectors x1 to x1+v1, and one from vectors x2 to x2+v2, then define:</p>\n\n<pre><code>a = (v2.v2 v1.(x2-x1) - v1.v2 v2.(x2-x1)) / ((v1.v1)(v2.v2) - (v1.v2)^2)\nb = (v1.v2 v1.(x2-x1) - v1.v1 v2.(x2-x1)) / ((v1.v1)(v2.v2) - (v1.v2)^2)\n</code></pre>\n\n<p>where for the vectors p=(px,py), q=(qx,qy), p.q is the dot product (px * qx + py * qy). First check if (v1.v1)(v2.v2) = (v1.v2)^2 - if so, the lines are parallel and do not cross.</p>\n\n<p>If they are not parallel, then if 0<=a<=1 and 0<=b<=1, the intersection point lies on both of the line segments, and is given by the point</p>\n\n<pre><code>x1 + a * v1\n</code></pre>\n\n<p><strong>Edit</strong> The derivation of the equations for a and b is as follows. The intersection point satisfies the vector equation</p>\n\n<pre><code>x1 + a*v1 = x2 + b*v2\n</code></pre>\n\n<p>By taking the dot product of this equation with <code>v1</code>, and with <code>v2</code>, we get two equations:</p>\n\n<pre><code>v1.v1*a - v2.v1*b = v1.(x2-x1)\nv1.v2*a - v2.v2*b = v2.(x2-x1)\n</code></pre>\n\n<p>which form two linear equations for a and b. Solving this system (by multiplying the first equation by v2.v2 and the second by v1.v1 and subtracting, or otherwise) gives the equations for a and b. </p>\n"
},
{
"answer_id": 154257,
"author": "fryguybob",
"author_id": 4592,
"author_profile": "https://Stackoverflow.com/users/4592",
"pm_score": 2,
"selected": false,
"text": "<p>If you rotate your frame of reference to align with the first line segment (so the origin is now the start of the first line, and the vector for the first line extends along the X-axis) the question becomes, where does the second line hit the X-axis in the new coordinate system. This is a much easier question to answer. If the first line is called <code>A</code> and it is defined by <code>A.O</code> as the origin of the line and 'A.V' being the vector of the line so that <code>A.O + A.V</code> is the end point of the line. The frame of reference can be defined by the matrix:</p>\n\n<pre><code> | A.V.X A.V.Y A.O.X |\nM = | A.V.Y -A.V.X A.O.Y |\n | 0 0 1 |\n</code></pre>\n\n<p>In homogeneous coordinates this matrix provides a basis for the frame of reference that maps the line <code>A</code> to 0 to 1 on the X-axis. We can now define the transformed line <code>B</code> as:</p>\n\n<pre><code>C.O = M*(B.O)\nC.V = M*(B.O + B.V) - C.O\n</code></pre>\n\n<p>Where the <code>*</code> operator properly defined for homogeneous coordinates (a projection from 3 space onto 2 space in this case). Now all that remains is to check and see where <code>C</code> hits the X-axis which is the same as solving <code>Y</code> side of the parametric equation of <code>C</code> for <code>t</code>:</p>\n\n<pre><code>C.O.Y + t * C.V.Y = 0\n -C.O.Y\nt = --------\n C.V.Y\n</code></pre>\n\n<p>If <code>t</code> is in the range 0 to 1, then <code>C</code> hits the X-axis inside the line segment. The place it lands on the X-axis is given by the X side of the parametric equation for <code>C</code>:</p>\n\n<pre><code>x = C.O.X + t * C.V.X\n</code></pre>\n\n<p>If <code>x</code> is in the range 0 to 1 then the intersection is on the <code>A</code> line segment. We can then find the point in the original coordinate system with:</p>\n\n<pre><code>p = A.O + A.V * x\n</code></pre>\n\n<p>You would of course have to check first to see if either line segment is zero length. Also if <code>C.V.Y = 0</code> you have parallel line segments. If <code>C.V.X</code> is also zero you have colinear line segments.</p>\n"
}
] |
2008/09/30
|
[
"https://Stackoverflow.com/questions/153592",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7565/"
] |
I'm using .NET to make an application with a drawing surface, similar to Visio. The UI connects two objects on the screen with Graphics.DrawLine. This simple implementation works fine, but as the surface gets more complex, I need a more robust way to represent the objects. One of these robust requirements is determining the intersection point for two lines so I can indicate separation via some kind of graphic.
So my question is, can anyone suggest a way to do this? Perhaps with a different technique (maybe GraphViz) or an algorithm?
|
The representation of lines by y = mx + c is problematic for computer graphics, because vertical lines require m to be infinite.
Furthermore, lines in computer graphics have a start and end point, unlike mathematical lines which are infinite in extent. One is usually only interested in a crossing of lines if the crossing point lies on both the line segments in question.
If you have two line segments, one from vectors x1 to x1+v1, and one from vectors x2 to x2+v2, then define:
```
a = (v2.v2 v1.(x2-x1) - v1.v2 v2.(x2-x1)) / ((v1.v1)(v2.v2) - (v1.v2)^2)
b = (v1.v2 v1.(x2-x1) - v1.v1 v2.(x2-x1)) / ((v1.v1)(v2.v2) - (v1.v2)^2)
```
where for the vectors p=(px,py), q=(qx,qy), p.q is the dot product (px \* qx + py \* qy). First check if (v1.v1)(v2.v2) = (v1.v2)^2 - if so, the lines are parallel and do not cross.
If they are not parallel, then if 0<=a<=1 and 0<=b<=1, the intersection point lies on both of the line segments, and is given by the point
```
x1 + a * v1
```
**Edit** The derivation of the equations for a and b is as follows. The intersection point satisfies the vector equation
```
x1 + a*v1 = x2 + b*v2
```
By taking the dot product of this equation with `v1`, and with `v2`, we get two equations:
```
v1.v1*a - v2.v1*b = v1.(x2-x1)
v1.v2*a - v2.v2*b = v2.(x2-x1)
```
which form two linear equations for a and b. Solving this system (by multiplying the first equation by v2.v2 and the second by v1.v1 and subtracting, or otherwise) gives the equations for a and b.
|
153,596 |
<p>What would be the most efficient way of recording to a log (.txt) from a console program on C# and .NET 2.2? My program loops multiple times always outputting different data based on what the user wants, so I'm searching for the most efficient way to achieve this.</p>
<p>I know I can always reopen a stream and then close it, but everytime I do that it would be writing just one line, then next time around (seconds later) the program reloops and needs tor write again. In my opinion, that doesn't seem very resourse friendly.</p>
<p>I'm using multiple threads that all have output data that I want to log (opening/closing the same file or accessing the same file on different threads might be bad). The "holds a reference to a stream writer that auto-flushes" sounds like a good idea, however I don't know how to do that.</p>
|
[
{
"answer_id": 153610,
"author": "Jorge Ferreira",
"author_id": 6508,
"author_profile": "https://Stackoverflow.com/users/6508",
"pm_score": 4,
"selected": false,
"text": "<p>Consider using <a href=\"http://logging.apache.org/log4net/index.html\" rel=\"nofollow noreferrer\">log4net</a>:</p>\n\n<blockquote>\n <p>a tool to help the programmer output log statements to a variety of output targets... We have kept the framework similar in spirit to the original log4j while taking advantage of new features in the .NET runtime. For more information on log4net see the <a href=\"http://logging.apache.org/log4net/release/features.html\" rel=\"nofollow noreferrer\">features</a> document...</p>\n</blockquote>\n"
},
{
"answer_id": 153635,
"author": "EBGreen",
"author_id": 1358,
"author_profile": "https://Stackoverflow.com/users/1358",
"pm_score": 2,
"selected": false,
"text": "<p>I accept the performance hit that comes with opening and closing every time I write a line. It is a reliability decision. If you are holding everything in memory and you have a hard crash, you have no log information at all to help troubleshoot. If this is not a concern for you, then holding it in memory will definitely provide better performance.</p>\n"
},
{
"answer_id": 153656,
"author": "Mats",
"author_id": 16440,
"author_profile": "https://Stackoverflow.com/users/16440",
"pm_score": 0,
"selected": false,
"text": "<p>A simple approach would be to provide a TextWriterTraceListener and add it to the collection of TraceListeners on the Trace class. This will automatically write all your Trace.Write... calls to the corresponding file.</p>\n"
},
{
"answer_id": 153661,
"author": "Tigraine",
"author_id": 21699,
"author_profile": "https://Stackoverflow.com/users/21699",
"pm_score": 2,
"selected": false,
"text": "<p>I agree with using log4net. </p>\n\n<p>But if you really need something simple consider just having a singleton that holds a reference to a StreamWriter that auto-flushes on every WriteLine.</p>\n\n<p>So you keep the file open throughout the Session avoiding the close/open overhead while not risking to loose log data in case of a hard crash.</p>\n"
},
{
"answer_id": 153672,
"author": "Wolfwyrd",
"author_id": 15570,
"author_profile": "https://Stackoverflow.com/users/15570",
"pm_score": 3,
"selected": true,
"text": "<p>You could hook into the tracing framework that forms part of the CLR. Using a simple class like: <a href=\"http://www.chaosink.co.uk/files/tracing.zip\" rel=\"nofollow noreferrer\">http://www.chaosink.co.uk/files/tracing.zip</a> you can selectively log diagnostic information. To use it add the class to your application. Create an inistance of the tracer in your class like:</p>\n\n<pre><code>private Tracing trace = new Tracing(\"My.Namespace.Class\");\n</code></pre>\n\n<p>and call it using: </p>\n\n<pre><code>MyClass()\n{\n trace.Verbose(\"Entered MyClass\");\n int x = 12;\n trace.Information(\"X is: {0}\", x);\n trace.Verbose(\"Leaving MyClass\");\n}\n</code></pre>\n\n<p>There are 4 levels of information in the inbuilt tracing framework:</p>\n\n<p>Verbose - To log program flow</p>\n\n<p>Information - To log specific information of interest to monitors</p>\n\n<p>Warning - To log an invalid state or recoverable exception</p>\n\n<p>Error - To log an unrecoverable exception or state</p>\n\n<p>To access the information from your application then add into the app.config (or web.config) the following:</p>\n\n<pre><code><system.diagnostics>\n <trace autoflush=\"false\" indentsize=\"4\">\n <listeners>\n <add name=\"myListener\" type=\"System.Diagnostics.TextWriterTraceListener\" initializeData=\"c:\\mylogfile.log\" />\n </listeners>\n </trace>\n <switches>\n <add name=\"My.Namespace.Class\" value=\"4\"/> \n </switches>\n</system.diagnostics>\n</code></pre>\n\n<p>You can also attach listeners for publishing to the eventlog or anywhere else that interests you. More information on the tracing framework can be found at:</p>\n\n<p><a href=\"http://msdn.microsoft.com/en-us/library/ms733025.aspx\" rel=\"nofollow noreferrer\">http://msdn.microsoft.com/en-us/library/ms733025.aspx</a></p>\n"
},
{
"answer_id": 156379,
"author": "Petr Macek",
"author_id": 15045,
"author_profile": "https://Stackoverflow.com/users/15045",
"pm_score": 0,
"selected": false,
"text": "<p>The logging frameworks like log4net should handle multi-threading correctly. </p>\n\n<p>There might be also a useful hint: the logging significantly pollutes the code making it less readable. Did you consider using aspect for injecting logging functionality to the code at the compile time? See this article for an <a href=\"http://www.developerfusion.com/article/5307/aspect-oriented-programming-using-net/\" rel=\"nofollow noreferrer\">example</a>.</p>\n"
}
] |
2008/09/30
|
[
"https://Stackoverflow.com/questions/153596",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/22582/"
] |
What would be the most efficient way of recording to a log (.txt) from a console program on C# and .NET 2.2? My program loops multiple times always outputting different data based on what the user wants, so I'm searching for the most efficient way to achieve this.
I know I can always reopen a stream and then close it, but everytime I do that it would be writing just one line, then next time around (seconds later) the program reloops and needs tor write again. In my opinion, that doesn't seem very resourse friendly.
I'm using multiple threads that all have output data that I want to log (opening/closing the same file or accessing the same file on different threads might be bad). The "holds a reference to a stream writer that auto-flushes" sounds like a good idea, however I don't know how to do that.
|
You could hook into the tracing framework that forms part of the CLR. Using a simple class like: <http://www.chaosink.co.uk/files/tracing.zip> you can selectively log diagnostic information. To use it add the class to your application. Create an inistance of the tracer in your class like:
```
private Tracing trace = new Tracing("My.Namespace.Class");
```
and call it using:
```
MyClass()
{
trace.Verbose("Entered MyClass");
int x = 12;
trace.Information("X is: {0}", x);
trace.Verbose("Leaving MyClass");
}
```
There are 4 levels of information in the inbuilt tracing framework:
Verbose - To log program flow
Information - To log specific information of interest to monitors
Warning - To log an invalid state or recoverable exception
Error - To log an unrecoverable exception or state
To access the information from your application then add into the app.config (or web.config) the following:
```
<system.diagnostics>
<trace autoflush="false" indentsize="4">
<listeners>
<add name="myListener" type="System.Diagnostics.TextWriterTraceListener" initializeData="c:\mylogfile.log" />
</listeners>
</trace>
<switches>
<add name="My.Namespace.Class" value="4"/>
</switches>
</system.diagnostics>
```
You can also attach listeners for publishing to the eventlog or anywhere else that interests you. More information on the tracing framework can be found at:
<http://msdn.microsoft.com/en-us/library/ms733025.aspx>
|
153,598 |
<p>I have a simple query:</p>
<pre><code>SELECT u_name AS user_name FROM users WHERE user_name = "john";
</code></pre>
<p>I get <code>Unknown Column 'user_name' in where clause</code>. Can I not refer to <code>'user_name'</code> in other parts of the statement even after <code>select 'u_name as user_name'</code>?</p>
|
[
{
"answer_id": 153603,
"author": "Jarrett Meyer",
"author_id": 5834,
"author_profile": "https://Stackoverflow.com/users/5834",
"pm_score": 2,
"selected": false,
"text": "<p>No you cannot. user_name is doesn't exist until return time.</p>\n"
},
{
"answer_id": 153608,
"author": "Per Hornshøj-Schierbeck",
"author_id": 11619,
"author_profile": "https://Stackoverflow.com/users/11619",
"pm_score": 3,
"selected": false,
"text": "<p>No you need to select it with correct name. If you gave the table you select from an alias you can use that though.</p>\n"
},
{
"answer_id": 153614,
"author": "Steven A. Lowe",
"author_id": 9345,
"author_profile": "https://Stackoverflow.com/users/9345",
"pm_score": 3,
"selected": false,
"text": "<p>corrected:</p>\n\n<pre><code>SELECT u_name AS user_name FROM users WHERE u_name = 'john';\n</code></pre>\n"
},
{
"answer_id": 153622,
"author": "dacracot",
"author_id": 13930,
"author_profile": "https://Stackoverflow.com/users/13930",
"pm_score": 7,
"selected": false,
"text": "<p>SQL is evaluated backwards, from right to left. So the where clause is parsed and evaluate prior to the select clause. Because of this the aliasing of u_name to user_name has not yet occurred.</p>\n"
},
{
"answer_id": 153626,
"author": "David Aldridge",
"author_id": 6742,
"author_profile": "https://Stackoverflow.com/users/6742",
"pm_score": 3,
"selected": false,
"text": "<p>Either:</p>\n\n<pre><code>SELECT u_name AS user_name\nFROM users\nWHERE u_name = \"john\";\n</code></pre>\n\n<p>or:</p>\n\n<pre><code>SELECT user_name\nfrom\n(\nSELECT u_name AS user_name\nFROM users\n)\nWHERE u_name = \"john\";\n</code></pre>\n\n<p>The latter ought to be the same as the former if the RDBMS supports predicate pushing into the in-line view.</p>\n"
},
{
"answer_id": 153627,
"author": "Mark S.",
"author_id": 13968,
"author_profile": "https://Stackoverflow.com/users/13968",
"pm_score": 4,
"selected": false,
"text": "<pre><code>select u_name as user_name from users where u_name = \"john\";\n</code></pre>\n\n<p>Think of it like this, your where clause evaluates first, to determine which rows (or joined rows) need to be returned. Once the where clause is executed, the select clause runs for it.</p>\n\n<p>To put it a better way, imagine this:</p>\n\n<pre><code>select distinct(u_name) as user_name from users where u_name = \"john\";\n</code></pre>\n\n<p>You can't reference the first half without the second. Where always gets evaluated first, then the select clause.</p>\n"
},
{
"answer_id": 153628,
"author": "Blumer",
"author_id": 8117,
"author_profile": "https://Stackoverflow.com/users/8117",
"pm_score": 0,
"selected": false,
"text": "<p>While you can alias your tables within your query (i.e., \"SELECT u.username FROM users u;\"), you have to use the actual names of the columns you're referencing. AS only impacts how the fields are returned.</p>\n"
},
{
"answer_id": 153641,
"author": "Paul Dixon",
"author_id": 6521,
"author_profile": "https://Stackoverflow.com/users/6521",
"pm_score": 5,
"selected": false,
"text": "<p>See the following MySQL manual page: <a href=\"http://dev.mysql.com/doc/refman/5.0/en/select.html\" rel=\"noreferrer\">http://dev.mysql.com/doc/refman/5.0/en/select.html</a></p>\n\n<blockquote>\n <p>\"A select_expr can be given an alias\n using AS alias_name. The alias is used\n as the expression's column name and\n can be used in GROUP BY, ORDER BY, or\n HAVING clauses.\"</p>\n</blockquote>\n\n<p>(...)</p>\n\n<blockquote>\n <p>It is not permissible to refer to a column alias in a WHERE clause,\n because the column value might not yet be determined when the WHERE\n clause is executed. See Section B.5.4.4, “Problems with Column\n Aliases”.</p>\n</blockquote>\n"
},
{
"answer_id": 780821,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 1,
"selected": false,
"text": "<pre><code>SELECT user_name\nFROM\n(\nSELECT name AS user_name\nFROM users\n) AS test\nWHERE user_name = \"john\"\n</code></pre>\n"
},
{
"answer_id": 2158701,
"author": "oliyide",
"author_id": 261431,
"author_profile": "https://Stackoverflow.com/users/261431",
"pm_score": 1,
"selected": false,
"text": "<p>Unknown column in <code>WHERE</code> clause caused by lines 1 and 2 and resolved by line 3:</p>\n\n<ol>\n<li><code>$sql = \"SELECT * FROM users WHERE username =\".$userName;</code></li>\n<li><code>$sql = \"SELECT * FROM users WHERE username =\".$userName.\"\";</code></li>\n<li><code>$sql = \"SELECT * FROM users WHERE username ='\".$userName.\"'\";</code></li>\n</ol>\n"
},
{
"answer_id": 3856473,
"author": "Septimus",
"author_id": 465945,
"author_profile": "https://Stackoverflow.com/users/465945",
"pm_score": 6,
"selected": false,
"text": "<p>What about:</p>\n\n<pre><code>SELECT u_name AS user_name FROM users HAVING user_name = \"john\";\n</code></pre>\n"
},
{
"answer_id": 6137496,
"author": "Jon",
"author_id": 762647,
"author_profile": "https://Stackoverflow.com/users/762647",
"pm_score": 4,
"selected": false,
"text": "<p>If you're trying to perform a query like the following (find all the nodes with at least one attachment) where you've used a SELECT statement to create a new field which doesn't actually exist in the database, and try to use the alias for that result you'll run into the same problem:</p>\n\n<pre><code>SELECT nodes.*, (SELECT (COUNT(*) FROM attachments \nWHERE attachments.nodeid = nodes.id) AS attachmentcount \nFROM nodes\nWHERE attachmentcount > 0;\n</code></pre>\n\n<p>You'll get an error \"Unknown column 'attachmentcount' in WHERE clause\".</p>\n\n<p>Solution is actually fairly simple - just replace the alias with the statement which produces the alias, eg:</p>\n\n<pre><code>SELECT nodes.*, (SELECT (COUNT(*) FROM attachments \nWHERE attachments.nodeid = nodes.id) AS attachmentcount \nFROM nodes \nWHERE (SELECT (COUNT(*) FROM attachments WHERE attachments.nodeid = nodes.id) > 0;\n</code></pre>\n\n<p>You'll still get the alias returned, but now SQL shouldn't bork at the unknown alias.</p>\n"
},
{
"answer_id": 8225681,
"author": "F_S",
"author_id": 1059620,
"author_profile": "https://Stackoverflow.com/users/1059620",
"pm_score": 1,
"selected": false,
"text": "<p>May be it helps.</p>\n\n<p>You can</p>\n\n<pre><code>SET @somevar := '';\nSELECT @somevar AS user_name FROM users WHERE (@somevar := `u_name`) = \"john\";\n</code></pre>\n\n<p>It works.</p>\n\n<p>BUT MAKE SURE WHAT YOU DO!</p>\n\n<ul>\n<li>Indexes are NOT USED here</li>\n<li>There will be scanned FULL TABLE - you hasn't specified the LIMIT 1 part</li>\n<li>So, - THIS QUERY WILL BE SLLLOOOOOOW on huge tables.</li>\n</ul>\n\n<p>But, may be it helps in some cases</p>\n"
},
{
"answer_id": 14170718,
"author": "devWaleed",
"author_id": 1560907,
"author_profile": "https://Stackoverflow.com/users/1560907",
"pm_score": -1,
"selected": false,
"text": "<p>I had the same problem, I found this useful.</p>\n\n<pre><code>mysql_query(\"SELECT * FROM `users` WHERE `user_name`='$user'\");\n</code></pre>\n\n<p>remember to put $user in ' ' single quotes.</p>\n"
},
{
"answer_id": 17953521,
"author": "M Khalid Junaid",
"author_id": 853360,
"author_profile": "https://Stackoverflow.com/users/853360",
"pm_score": 3,
"selected": false,
"text": "<p>Your defined <code>alias</code> are not welcomed by the <code>WHERE</code> clause you have to use the <code>HAVING</code> clause for this </p>\n\n<pre><code>SELECT u_name AS user_name FROM users HAVING user_name = \"john\";\n</code></pre>\n\n<p>OR you can directly use the original column name with the <code>WHERE</code></p>\n\n<pre><code>SELECT u_name AS user_name FROM users WHERE u_name = \"john\";\n</code></pre>\n\n<p>Same as you have the result in user defined alias as a result of subquery or any calculation it will be accessed by the <code>HAVING</code> clause not by the <code>WHERE</code></p>\n\n<pre><code>SELECT u_name AS user_name ,\n(SELECT last_name FROM users2 WHERE id=users.id) as user_last_name\nFROM users WHERE u_name = \"john\" HAVING user_last_name ='smith'\n</code></pre>\n"
},
{
"answer_id": 29416495,
"author": "user3103155",
"author_id": 3103155,
"author_profile": "https://Stackoverflow.com/users/3103155",
"pm_score": 0,
"selected": false,
"text": "<p>Just had this problem.</p>\n\n<p>Make sure there is no space in the name of the entity in the database.</p>\n\n<p>e.g. ' user_name' instead of 'user_name' </p>\n"
}
] |
2008/09/30
|
[
"https://Stackoverflow.com/questions/153598",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] |
I have a simple query:
```
SELECT u_name AS user_name FROM users WHERE user_name = "john";
```
I get `Unknown Column 'user_name' in where clause`. Can I not refer to `'user_name'` in other parts of the statement even after `select 'u_name as user_name'`?
|
SQL is evaluated backwards, from right to left. So the where clause is parsed and evaluate prior to the select clause. Because of this the aliasing of u\_name to user\_name has not yet occurred.
|
153,630 |
<p>Unfortunately, I need to do this. I'm using ELMAH for my error log. Before I route to my error.aspx view, I have to grab the default ELMAH error log so I can log the exception. You used to be able to use </p>
<pre><code>Elmah.ErrorLog.Default
</code></pre>
<p>However, this is now marked as obsolete. The compiler directs me to use the method</p>
<pre><code>Elmah.ErrorLog.GetDefault(HttpContext context)
</code></pre>
<p>MVC's context is of type HttpContextBase, which enables us to mock it (YAY!). How can we deal with MVC-unaware libraries that require the old style HttpContext?</p>
|
[
{
"answer_id": 153683,
"author": "SHODAN",
"author_id": 2622,
"author_profile": "https://Stackoverflow.com/users/2622",
"pm_score": 8,
"selected": true,
"text": "<p>Try <code>System.Web.HttpContext.Current</code>. It should do the trick.</p>\n\n<p>Gets HTTP-specific information about an individual HTTP request.</p>\n\n<p><a href=\"https://msdn.microsoft.com/en-us/library/system.web.httpcontext.current%28v=vs.110%29.aspx\" rel=\"noreferrer\">MSDN</a></p>\n"
},
{
"answer_id": 1469734,
"author": "rodrigo caballero",
"author_id": 178234,
"author_profile": "https://Stackoverflow.com/users/178234",
"pm_score": 5,
"selected": false,
"text": "<pre><code>this.HttpContext.ApplicationInstance.Context\n</code></pre>\n"
}
] |
2008/09/30
|
[
"https://Stackoverflow.com/questions/153630",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] |
Unfortunately, I need to do this. I'm using ELMAH for my error log. Before I route to my error.aspx view, I have to grab the default ELMAH error log so I can log the exception. You used to be able to use
```
Elmah.ErrorLog.Default
```
However, this is now marked as obsolete. The compiler directs me to use the method
```
Elmah.ErrorLog.GetDefault(HttpContext context)
```
MVC's context is of type HttpContextBase, which enables us to mock it (YAY!). How can we deal with MVC-unaware libraries that require the old style HttpContext?
|
Try `System.Web.HttpContext.Current`. It should do the trick.
Gets HTTP-specific information about an individual HTTP request.
[MSDN](https://msdn.microsoft.com/en-us/library/system.web.httpcontext.current%28v=vs.110%29.aspx)
|
153,639 |
<p>Greetings!</p>
<p>I have a WebService that contains a WebMethod that does some work and returns a boolean value. The work that it does may or may not take some time, so I'd like to call it asynchronously.</p>
<pre><code>[WebService(Namespace = "http://tempuri.com/")]
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
[System.ComponentModel.ToolboxItem(false)]
public class MyWebSvc : System.Web.Services.WebService
{
[WebMethod]
public bool DoWork()
{
bool succ = false;
try
{
// do some work, which might take a while
}
catch (Exception ex)
{
// handle
succ = false;
}
return succ;
}
}
</code></pre>
<p>This WebService exists on each server in a web farm. So to call the DoWork() method on each server, I have a class library to do so, based on a list of server URLs:</p>
<pre><code>static public class WebSvcsMgr
{
static public void DoAllWork(ICollection<string> servers)
{
MyWebSvc myWebSvc = new MyWebSvc();
foreach (string svr_url in servers)
{
myWebSvc.Url = svr_url;
myWebSvc.DoWork();
}
}
}
</code></pre>
<p>Finally, this is called from the Web interface in an asp:Button click event like so:</p>
<pre><code>WebSvcsMgr.DoAllWork(server_list);
</code></pre>
<p>For the static DoAllWork() method called by the Web Form, I plan to make this an asynchronous call via IAsyncResult. However, I'd like to report a success/fail of the DoWork() WebMethod for each server in the farm as the results are returned. What would be the best approach to this in conjuction with an UpdatePanel? A GridView? Labels? And how could this be returned by the static helper class to the Web Form?</p>
|
[
{
"answer_id": 153854,
"author": "craigmoliver",
"author_id": 12252,
"author_profile": "https://Stackoverflow.com/users/12252",
"pm_score": 0,
"selected": false,
"text": "<p>A Literal in a conditional Update Panel would be fine.</p>\n\n<pre><code><asp:UpdatePanel ID=\"up\" runat=\"server\" UpdateMode=\"Conditional\">\n <ContentTemplate>\n <asp:Literal ID=\"litUpdateMe\" runat=\"server\" />\n </ContentTemplate>\n</asp:UpdatePanel>\n</code></pre>\n"
},
{
"answer_id": 163710,
"author": "Atanas Korchev",
"author_id": 10141,
"author_profile": "https://Stackoverflow.com/users/10141",
"pm_score": 1,
"selected": false,
"text": "<p><a href=\"http://msdn.microsoft.com/en-us/magazine/cc163725.aspx\" rel=\"nofollow noreferrer\">Asynchronous pages</a> are helpful in scenarios when you need to asynchronously call web service methods.</p>\n"
}
] |
2008/09/30
|
[
"https://Stackoverflow.com/questions/153639",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/27870/"
] |
Greetings!
I have a WebService that contains a WebMethod that does some work and returns a boolean value. The work that it does may or may not take some time, so I'd like to call it asynchronously.
```
[WebService(Namespace = "http://tempuri.com/")]
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
[System.ComponentModel.ToolboxItem(false)]
public class MyWebSvc : System.Web.Services.WebService
{
[WebMethod]
public bool DoWork()
{
bool succ = false;
try
{
// do some work, which might take a while
}
catch (Exception ex)
{
// handle
succ = false;
}
return succ;
}
}
```
This WebService exists on each server in a web farm. So to call the DoWork() method on each server, I have a class library to do so, based on a list of server URLs:
```
static public class WebSvcsMgr
{
static public void DoAllWork(ICollection<string> servers)
{
MyWebSvc myWebSvc = new MyWebSvc();
foreach (string svr_url in servers)
{
myWebSvc.Url = svr_url;
myWebSvc.DoWork();
}
}
}
```
Finally, this is called from the Web interface in an asp:Button click event like so:
```
WebSvcsMgr.DoAllWork(server_list);
```
For the static DoAllWork() method called by the Web Form, I plan to make this an asynchronous call via IAsyncResult. However, I'd like to report a success/fail of the DoWork() WebMethod for each server in the farm as the results are returned. What would be the best approach to this in conjuction with an UpdatePanel? A GridView? Labels? And how could this be returned by the static helper class to the Web Form?
|
[Asynchronous pages](http://msdn.microsoft.com/en-us/magazine/cc163725.aspx) are helpful in scenarios when you need to asynchronously call web service methods.
|
153,644 |
<p>Since arrays and hashes can only contain scalars in Perl, why do you have to use the $ to tell the interpreter that the value is a scalar when accessing array or hash elements? In other words, assuming you have an array <code>@myarray</code> and a hash <code>%myhash</code>, why do you need to do:</p>
<pre><code>$x = $myarray[1];
$y = $myhash{'foo'};
</code></pre>
<p>instead of just doing :</p>
<pre><code>$x = myarray[1];
$y = myhash{'foo'};
</code></pre>
<p>Why are the above ambiguous? </p>
<p>Wouldn't it be illegal Perl code if it was anything but a $ in that place? For example, aren't all of the following illegal in Perl?</p>
<pre><code>@var[0];
@var{'key'};
%var[0];
%var{'key'};
</code></pre>
|
[
{
"answer_id": 153668,
"author": "Paul Dixon",
"author_id": 6521,
"author_profile": "https://Stackoverflow.com/users/6521",
"pm_score": 3,
"selected": false,
"text": "<p>I can think of one way that </p>\n\n<pre><code>$x = myarray[1];\n</code></pre>\n\n<p>is ambiguous - what if you wanted a array called m?</p>\n\n<pre><code>$x = m[1];\n</code></pre>\n\n<p>How can you tell that apart from a regex match?</p>\n\n<p>In other words, the syntax is there to help the Perl interpreter, well, interpret!</p>\n"
},
{
"answer_id": 153692,
"author": "zigdon",
"author_id": 4913,
"author_profile": "https://Stackoverflow.com/users/4913",
"pm_score": 5,
"selected": true,
"text": "<p>Slices aren't illegal:</p>\n\n<pre><code>@slice = @myarray[1, 2, 5];\n@slice = @myhash{qw/foo bar baz/};\n</code></pre>\n\n<p>And I suspect that's part of the reason why you need to specify if you want to get a single value out of the hash/array or not. </p>\n"
},
{
"answer_id": 153715,
"author": "nohat",
"author_id": 3101,
"author_profile": "https://Stackoverflow.com/users/3101",
"pm_score": 3,
"selected": false,
"text": "<p>This is valid Perl: <code>@var[0]</code>. It is an array slice of length one. <code>@var[0,1]</code> would be an array slice of length two.</p>\n\n<p><code>@var['key']</code> is not valid Perl because arrays can only be indexed by numbers, and \nthe other two (<code>%var[0] and %var['key']</code>) are not valid Perl because hash slices use the {} to index the hash.</p>\n\n<p><code>@var{'key'}</code> and <code>@var{0}</code> are both valid hash slices, though. Obviously it isn't normal to take slices of length one, but it is certainly valid.</p>\n\n<p>See <a href=\"http://perldoc.perl.org/perldata.html#Slices\" rel=\"noreferrer\">the slice section of perldata perldoc</a>for more information about slicing in Perl.</p>\n"
},
{
"answer_id": 153725,
"author": "moritz",
"author_id": 14132,
"author_profile": "https://Stackoverflow.com/users/14132",
"pm_score": 4,
"selected": false,
"text": "<p>The sigil give you the return type of the container. So if something starts with <code>@</code>, you know that it returns a list. If it starts with <code>$</code>, it returns a scalar.</p>\n\n<p>Now if there is only an identifier after the sigil (like <code>$foo</code> or <code>@foo</code>, then it's a simple variable access. If it's followed by a <code>[</code>, it is an access on an array, if it's followed by a <code>{</code>, it's an access on a hash.</p>\n\n<pre><code># variables\n$foo\n@foo\n\n# accesses\n$stuff{blubb} # accesses %stuff, returns a scalar\n@stuff{@list} # accesses %stuff, returns an array\n$stuff[blubb] # accesses @stuff, returns a scalar\n # (and calls the blubb() function)\n@stuff[blubb] # accesses @stuff, returns an array\n</code></pre>\n\n<p>Some human languages have very similar concepts.</p>\n\n<p>However many programmers found that confusing, so Perl 6 uses an invariant sigil.</p>\n\n<p>In general the Perl 5 compiler wants to know at compile time if something is in list or in scalar context, so without the leading sigil some terms would become ambiguous.</p>\n"
},
{
"answer_id": 153824,
"author": "Michael Carman",
"author_id": 8233,
"author_profile": "https://Stackoverflow.com/users/8233",
"pm_score": 2,
"selected": false,
"text": "<p>The sigil provides the context for the access:</p>\n\n<ul>\n<li><code>$</code> means scalar context (a scalar\nvariable or a single element of a hash or an array)</li>\n<li><code>@</code> means list context (a whole array or a slice of\na hash or an array)</li>\n<li><code>%</code> is an entire hash</li>\n</ul>\n"
},
{
"answer_id": 153929,
"author": "hexten",
"author_id": 10032,
"author_profile": "https://Stackoverflow.com/users/10032",
"pm_score": 5,
"selected": false,
"text": "<p>I've just used</p>\n\n<pre><code>my $x = myarray[1];\n</code></pre>\n\n<p>in a program and, to my surprise, here's what happened when I ran it:</p>\n\n<pre><code>$ perl foo.pl \nFlying Butt Monkeys!\n</code></pre>\n\n<p>That's because the whole program looks like this:</p>\n\n<pre><code>$ cat foo.pl \n#!/usr/bin/env perl\n\nuse strict;\nuse warnings;\n\nsub myarray {\n print \"Flying Butt Monkeys!\\n\";\n}\n\nmy $x = myarray[1];\n</code></pre>\n\n<p>So myarray calls a subroutine passing it a reference to an anonymous array containing a single element, 1.</p>\n\n<p>That's another reason you need the sigil on an array access.</p>\n"
},
{
"answer_id": 154039,
"author": "Axeman",
"author_id": 11289,
"author_profile": "https://Stackoverflow.com/users/11289",
"pm_score": 3,
"selected": false,
"text": "<p>In Perl 5 (to be changed in Perl 6) a sigil indicates the <em>context</em> of your expression. </p>\n\n<ul>\n<li>You want a particular scalar out of a hash so it's <code>$hash{key}</code>. </li>\n<li>You want the value of a particular slot out of an array, so it's <code>$array[0]</code>. </li>\n</ul>\n\n<p>However, as pointed out by zigdon, <em>slices</em> are legal. They interpret the those expressions in a <em>list</em> context. </p>\n\n<ul>\n<li>You want a lists of 1 value in a hash <code>@hash{key}</code> works</li>\n<li><p>But also larger lists work as well, like <code>@hash{qw<key1 key2 ... key_n>}</code>. </p></li>\n<li><p>You want a couple of slots out of an array <code>@array[0,3,5..7,$n..$n+5]</code> works</p></li>\n<li><code>@array[0]</code> is a list of size 1. </li>\n</ul>\n\n<p>There is no \"hash context\", so neither <code>%hash{@keys}</code> nor <code>%hash{key}</code> has meaning. </p>\n\n<p>So you have <code>\"@\"</code> + <code>\"array[0]\"</code> <=> < sigil = context > + < indexing expression > as the complete expression. </p>\n"
},
{
"answer_id": 154086,
"author": "brian d foy",
"author_id": 2766176,
"author_profile": "https://Stackoverflow.com/users/2766176",
"pm_score": 3,
"selected": false,
"text": "<p>People have already pointed out that you can have slices and contexts, but sigils are there to separate the things that are variables from everything else. You don't have to know all of the keywords or subroutine names to choose a sensible variable name. It's one of the big things I miss about Perl in other languages.</p>\n"
},
{
"answer_id": 154421,
"author": "kixx",
"author_id": 11260,
"author_profile": "https://Stackoverflow.com/users/11260",
"pm_score": 2,
"selected": false,
"text": "<p>In Perl 5 you need the sigils ($ and @) because the default interpretation of bareword identifier is that of a subroutine call (thus eliminating the need to use & in most cases ).</p>\n"
}
] |
2008/09/30
|
[
"https://Stackoverflow.com/questions/153644",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/742/"
] |
Since arrays and hashes can only contain scalars in Perl, why do you have to use the $ to tell the interpreter that the value is a scalar when accessing array or hash elements? In other words, assuming you have an array `@myarray` and a hash `%myhash`, why do you need to do:
```
$x = $myarray[1];
$y = $myhash{'foo'};
```
instead of just doing :
```
$x = myarray[1];
$y = myhash{'foo'};
```
Why are the above ambiguous?
Wouldn't it be illegal Perl code if it was anything but a $ in that place? For example, aren't all of the following illegal in Perl?
```
@var[0];
@var{'key'};
%var[0];
%var{'key'};
```
|
Slices aren't illegal:
```
@slice = @myarray[1, 2, 5];
@slice = @myhash{qw/foo bar baz/};
```
And I suspect that's part of the reason why you need to specify if you want to get a single value out of the hash/array or not.
|
153,666 |
<p>I'm having a problem with some mail merge code that is supposed to produce letters within our application. I'm aware that this code is a bit rough at the moment, but we're in the "Get something working" phase before we tidy it up.</p>
<p>Now the way this is supposed to work, and the way it works when we do it manually, is we have a file (the fileOut variable + ".template") which is a template for the letter. We open that template, merge it, and then save it as the filename in the fileOut variable.</p>
<p>However, what it is doing is saving a copy of the template file to the fileout filename, instead of the output of the merge.</p>
<p>I've searched, and I seem to be banging my head against a brick wall.</p>
<p>datafile is the datafile that contains the merge data.</p>
<p>Using the same files, it all works if you do it manually.</p>
<pre><code>Public Function processFile(ByVal datafile As String, ByVal fileOut As String) As String
Dim ans As String = String.Empty
errorLog = "C:\Temp\Template_error.log"
If (File.Exists(datafile)) Then
Try
' Create an instance of Word and make it invisible.'
wrdApp = CreateObject("Word.Application")
wrdApp.Visible = False
' Add a new document.'
wrdDoc = wrdApp.Documents.Add(fileOut & ".template")
wrdDoc.Select()
Dim wrdSelection As Word.Selection
Dim wrdMailMerge As Word.MailMerge
wrdDoc.MailMerge.OpenDataSource(datafile)
wrdSelection = wrdApp.Selection()
wrdMailMerge = wrdDoc.MailMerge()
With wrdMailMerge
.Execute()
End With
wrdDoc.SaveAs(fileOut)
wrdApp.Quit(False)
' Release References.'
wrdSelection = Nothing
wrdMailMerge = Nothing
wrdDoc = Nothing
wrdApp = Nothing
ans = "Merged OK"
Call writeToLogFile(errorLog, "This worked, written to " & fileOut)
Catch ex As Exception
ans = "error : exception thrown " & ex.ToString
Call writeToLogFile(errorLog, ans)
End Try
Else
ans = "error ; unable to open Date File : " & datafile
If (logErrors) Then
Call writeToLogFile(errorLog, "The specified source csv file does not exist. Unable " & _
"to process it. Filename provided: " & datafile)
End If
End If
Return ans
End Function
</code></pre>
|
[
{
"answer_id": 153793,
"author": "micahwittman",
"author_id": 11181,
"author_profile": "https://Stackoverflow.com/users/11181",
"pm_score": 0,
"selected": false,
"text": "<p>I think the problem is this line:</p>\n\n<pre><code>wrdDoc.MailMerge.OpenDataSource(templateName)\n</code></pre>\n\n<p>So <em>templateName</em> is something like 'C:\\My Template.doc', right?</p>\n\n<p>It looks like you are supplying the file path of a the Word document itself instead of a data source (the Excel or CSV file, Access Table, etc.) linked to the \".template\" document.</p>\n\n<p><strong>Try</strong>:</p>\n\n<pre><code>data = \"C:\\My Data.xls\"\nwrdDoc.MailMerge.OpenDataSource(data)\n</code></pre>\n"
},
{
"answer_id": 153883,
"author": "Casper",
"author_id": 18729,
"author_profile": "https://Stackoverflow.com/users/18729",
"pm_score": 0,
"selected": false,
"text": "<p>One way to cheat is to record a macro while manually doing all the steps you mention. Once you're done, adjust the macro to be more flexible.</p>\n\n<p>That's what I did last time I couldn't figure it out while writing my own macro's :)</p>\n"
},
{
"answer_id": 156509,
"author": "hulver",
"author_id": 11496,
"author_profile": "https://Stackoverflow.com/users/11496",
"pm_score": 3,
"selected": true,
"text": "<p>I've found the solution. When you merge a document, it creates a new document with the merge results in it. Code fragment below explains.</p>\n\n<pre><code>wrdDoc = wrdApp.Documents.Add(TemplateFileName)\nwrdDoc.Select()\nDim wrdSelection As Word.Selection\nDim wrdMailMerge As Word.MailMerge\n\n\nwrdDoc.MailMerge.OpenDataSource(DataFileName)\n\nwrdSelection = wrdApp.Selection()\nwrdMailMerge = wrdDoc.MailMerge()\nWith wrdMailMerge\n .Execute()\nEnd With\n\n' This is the wrong thing to do. It just re-saves the template file you opened. '\n'wrdDoc.SaveAs(OutputFileName) '\n\n' The resulting merged document is actually stored '\n' in the MailMerge object, so you have to save that '\nwrdMailMerge.Application.ActiveDocument.SaveAs(OutputFileName)\n\nwrdApp.Quit(False)\n</code></pre>\n"
}
] |
2008/09/30
|
[
"https://Stackoverflow.com/questions/153666",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11496/"
] |
I'm having a problem with some mail merge code that is supposed to produce letters within our application. I'm aware that this code is a bit rough at the moment, but we're in the "Get something working" phase before we tidy it up.
Now the way this is supposed to work, and the way it works when we do it manually, is we have a file (the fileOut variable + ".template") which is a template for the letter. We open that template, merge it, and then save it as the filename in the fileOut variable.
However, what it is doing is saving a copy of the template file to the fileout filename, instead of the output of the merge.
I've searched, and I seem to be banging my head against a brick wall.
datafile is the datafile that contains the merge data.
Using the same files, it all works if you do it manually.
```
Public Function processFile(ByVal datafile As String, ByVal fileOut As String) As String
Dim ans As String = String.Empty
errorLog = "C:\Temp\Template_error.log"
If (File.Exists(datafile)) Then
Try
' Create an instance of Word and make it invisible.'
wrdApp = CreateObject("Word.Application")
wrdApp.Visible = False
' Add a new document.'
wrdDoc = wrdApp.Documents.Add(fileOut & ".template")
wrdDoc.Select()
Dim wrdSelection As Word.Selection
Dim wrdMailMerge As Word.MailMerge
wrdDoc.MailMerge.OpenDataSource(datafile)
wrdSelection = wrdApp.Selection()
wrdMailMerge = wrdDoc.MailMerge()
With wrdMailMerge
.Execute()
End With
wrdDoc.SaveAs(fileOut)
wrdApp.Quit(False)
' Release References.'
wrdSelection = Nothing
wrdMailMerge = Nothing
wrdDoc = Nothing
wrdApp = Nothing
ans = "Merged OK"
Call writeToLogFile(errorLog, "This worked, written to " & fileOut)
Catch ex As Exception
ans = "error : exception thrown " & ex.ToString
Call writeToLogFile(errorLog, ans)
End Try
Else
ans = "error ; unable to open Date File : " & datafile
If (logErrors) Then
Call writeToLogFile(errorLog, "The specified source csv file does not exist. Unable " & _
"to process it. Filename provided: " & datafile)
End If
End If
Return ans
End Function
```
|
I've found the solution. When you merge a document, it creates a new document with the merge results in it. Code fragment below explains.
```
wrdDoc = wrdApp.Documents.Add(TemplateFileName)
wrdDoc.Select()
Dim wrdSelection As Word.Selection
Dim wrdMailMerge As Word.MailMerge
wrdDoc.MailMerge.OpenDataSource(DataFileName)
wrdSelection = wrdApp.Selection()
wrdMailMerge = wrdDoc.MailMerge()
With wrdMailMerge
.Execute()
End With
' This is the wrong thing to do. It just re-saves the template file you opened. '
'wrdDoc.SaveAs(OutputFileName) '
' The resulting merged document is actually stored '
' in the MailMerge object, so you have to save that '
wrdMailMerge.Application.ActiveDocument.SaveAs(OutputFileName)
wrdApp.Quit(False)
```
|
153,689 |
<p>I'm designing an application which deals with two sets of data - Users and Areas. The data is read from files produced by a third party. I have a User class and an Area class, and the data is read into a Users array and an Areas array (or other appropriate memory structure, depending on the technology we go with).</p>
<p>Both classes have a unique ID member which is read from the file, and the User class contains an array of Area IDs, giving a relationship where one user is associated with many Areas.</p>
<p>The requirements are quite straightforward:</p>
<ul>
<li>List of Users</li>
<li>List of Areas</li>
<li>List of Users for Specified Area</li>
<li>List of Areas for Specified Users</li>
</ul>
<p>My first thought was to leave the data in the two arrays, then for each of the requirements, have a seperate method which would interrogate one or both arrays as required. This would be easy to implement, but I'm not convinced it's necessarily the best way.</p>
<p>Then I thought about having a 'Get Areas' method on the User class and a 'Get Users' member on the Area class which would be more useful if for example I'm at a stage where I have an Area object, I could find it's users by a property, but then how would a 'Get Users' method on the Area class be aware of/have access to the Users array.</p>
<p>I've had this problem a number of times before, but never really came up with a definitive solution. Maybe I'm just making it more complicated than it actually is. Can anyone provide any tips, URLs or books that would help me with this sort of design?</p>
<p>UPDATE:
Thank you all for taking your time to leave some tips. Your comments are very much appreciated.</p>
<p>I agree that the root of this problem is a many-to-many relationship. I understand how that would be modelled in a relational database, that's pretty simple.</p>
<p>The data I receive is in the form of binary files from a third party, so I have no control over the structure of these, but I can store it whichever way is best when I read it in. It is a bit square pegs in round holes, but I thought reading it in then storing it in a database, the program would then have to query the database to get to the results. It's not a massive amount of data, so I thought it would be possible to get out what I need by storing it in memory structures.</p>
|
[
{
"answer_id": 153698,
"author": "Saif Khan",
"author_id": 23667,
"author_profile": "https://Stackoverflow.com/users/23667",
"pm_score": 0,
"selected": false,
"text": "<p>Why not use DataTables with relations, if .NET is involved? You may want to look into Generics as well, again, if .NET is involved.</p>\n"
},
{
"answer_id": 153708,
"author": "Steven A. Lowe",
"author_id": 9345,
"author_profile": "https://Stackoverflow.com/users/9345",
"pm_score": 3,
"selected": false,
"text": "<p>this is really a many-to-many relationship,</p>\n\n<pre><code>User <<--->> Area\n</code></pre>\n\n<p>break it up into 3 objects, User, Area, and UserArea:</p>\n\n<pre><code>User: Id, name, etc.\nArea: Id, name, etc.\nUserArea: UserId, AreaId\n</code></pre>\n"
},
{
"answer_id": 153714,
"author": "Matthias Winkelmann",
"author_id": 4494,
"author_profile": "https://Stackoverflow.com/users/4494",
"pm_score": 2,
"selected": false,
"text": "<p>Does an area belong to multiple users? If yes, it's a technically a many-to-many relationship. If you were to transform the data into a relational database, you'd create a table with all the relationships. I guess if you want to work with arrays, you could create a third array. Or if you actually want to do this in an OO way, both classes should have arrays of pointers to the associated areas/users. </p>\n"
},
{
"answer_id": 153719,
"author": "chessguy",
"author_id": 1908025,
"author_profile": "https://Stackoverflow.com/users/1908025",
"pm_score": 0,
"selected": false,
"text": "<p>One option is to use a dictionary for each of the last 2 requirements. That is, a <code>Dictionary<Area, List<User>></code> and a <code>Dictionary<User, List<Area>></code>. You could build these up as you read in the data. You might even wrap a class around these 2 dictionaries, and just have a method on that class for each of the requirements. That would allow you to make sure the dictionaries stay in sync.</p>\n"
},
{
"answer_id": 153736,
"author": "Chris Cudmore",
"author_id": 18907,
"author_profile": "https://Stackoverflow.com/users/18907",
"pm_score": 2,
"selected": false,
"text": "<p>Very basic, but the idea is:</p>\n\n<pre><code>struct/class Membership\n{\n int MemberID;\n int userID;\n int areaID;\n}\n</code></pre>\n\n<p>This class implements the \"user belongs to area\" membership concept.\nStick one of these for each membership in a collection, and query that collection for subsets that meet your requirements. </p>\n\n<p>EDIT: Another option</p>\n\n<p>You could store in each Member a list of Areas, and in each Area, a list of Members.</p>\n\n<p>in Area:</p>\n\n<pre><code>public bool addMember(Member m)\n{\n if (/*eligibility Requirements*/)\n {\n memberList.add(m);\n m.addArea(this);\n return true;\n }\n return false;\n}\n</code></pre>\n\n<p>and a similar implementation in Member (without the callback)</p>\n\n<p>The advantage of this is that it's pretty easy to return an iterator to walk through an Area and find Members (and vice versa)</p>\n\n<p>The disadvantage is that it's very tightly coupled, which could cause future problems.</p>\n\n<p>I think the first implementation is more LINQ friendly.</p>\n"
},
{
"answer_id": 153977,
"author": "dacracot",
"author_id": 13930,
"author_profile": "https://Stackoverflow.com/users/13930",
"pm_score": 1,
"selected": false,
"text": "<p>I'm sorry, but this is not an object-oriented problem. It is a relational problem. Hence all the references to cardinality (many-to-many). This is relational database modeling 101. I don't mean to criticize Gavin, just to point out a new perspective. </p>\n\n<p>So what good is my rant. The answer should be to integrate with a relational data store, not to pound it into a object oriented paradigm. This is the classic square peg, round hole issue.</p>\n"
},
{
"answer_id": 154678,
"author": "Saif Khan",
"author_id": 23667,
"author_profile": "https://Stackoverflow.com/users/23667",
"pm_score": 0,
"selected": false,
"text": "<p>Agree with dacracot</p>\n\n<p>Also look at DevExpress XPO</p>\n"
}
] |
2008/09/30
|
[
"https://Stackoverflow.com/questions/153689",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/8354/"
] |
I'm designing an application which deals with two sets of data - Users and Areas. The data is read from files produced by a third party. I have a User class and an Area class, and the data is read into a Users array and an Areas array (or other appropriate memory structure, depending on the technology we go with).
Both classes have a unique ID member which is read from the file, and the User class contains an array of Area IDs, giving a relationship where one user is associated with many Areas.
The requirements are quite straightforward:
* List of Users
* List of Areas
* List of Users for Specified Area
* List of Areas for Specified Users
My first thought was to leave the data in the two arrays, then for each of the requirements, have a seperate method which would interrogate one or both arrays as required. This would be easy to implement, but I'm not convinced it's necessarily the best way.
Then I thought about having a 'Get Areas' method on the User class and a 'Get Users' member on the Area class which would be more useful if for example I'm at a stage where I have an Area object, I could find it's users by a property, but then how would a 'Get Users' method on the Area class be aware of/have access to the Users array.
I've had this problem a number of times before, but never really came up with a definitive solution. Maybe I'm just making it more complicated than it actually is. Can anyone provide any tips, URLs or books that would help me with this sort of design?
UPDATE:
Thank you all for taking your time to leave some tips. Your comments are very much appreciated.
I agree that the root of this problem is a many-to-many relationship. I understand how that would be modelled in a relational database, that's pretty simple.
The data I receive is in the form of binary files from a third party, so I have no control over the structure of these, but I can store it whichever way is best when I read it in. It is a bit square pegs in round holes, but I thought reading it in then storing it in a database, the program would then have to query the database to get to the results. It's not a massive amount of data, so I thought it would be possible to get out what I need by storing it in memory structures.
|
this is really a many-to-many relationship,
```
User <<--->> Area
```
break it up into 3 objects, User, Area, and UserArea:
```
User: Id, name, etc.
Area: Id, name, etc.
UserArea: UserId, AreaId
```
|
153,706 |
<p>It seems to me that phpMyAdmin imports tables by default with collation latin1_swedish_ci, how i change this?</p>
|
[
{
"answer_id": 153765,
"author": "Tomalak",
"author_id": 18771,
"author_profile": "https://Stackoverflow.com/users/18771",
"pm_score": 4,
"selected": false,
"text": "<p>This is not a phpMyAdmin question.</p>\n\n<p>Collations are part of recent MySQL releases, you must set the default collation of the server (or at least of the database) to change that behaviour.</p>\n\n<p>To convert already imported tables to UTF-8 you can do (in PHP):</p>\n\n<pre><code>$dbname = 'my_databaseName';\nmysql_connect('127.0.0.1', 'root', '');\nmysql_query(\"ALTER DATABASE `$dbname` DEFAULT CHARACTER SET utf8 COLLATE utf8_general_ci\");\n$res = mysql_query(\"SHOW TABLES FROM `$dbname`\");\nwhile($row = mysql_fetch_row($res)) {\n $query = \"ALTER TABLE {$dbname}.`{$row[0]}` CONVERT TO CHARACTER SET utf8 COLLATE utf8_general_ci\";\n mysql_query($query);\n $query = \"ALTER TABLE {$dbname}.`{$row[0]}` DEFAULT CHARACTER SET utf8 COLLATE utf8_general_ci\";\n mysql_query($query);\n}\necho 'all tables converted';\n</code></pre>\n\n<p>Code snippet taken from <a href=\"http://jonas.elunic.de/blog/index.php/2006/07/26/mysql-datenbank-zu-utf8-konventieren/\" rel=\"noreferrer\">here</a>.</p>\n"
},
{
"answer_id": 153802,
"author": "Eran Galperin",
"author_id": 10585,
"author_profile": "https://Stackoverflow.com/users/10585",
"pm_score": 6,
"selected": true,
"text": "<p>In your Mysql configuration change the default-character-set operative under the [mysqld] tab. For example:</p>\n\n<pre><code>[mysqld]\ndefault-character-set=utf8\n</code></pre>\n\n<p>Don't forget to restart your Mysql server afterwards for the changes to take effect.</p>\n"
},
{
"answer_id": 11374158,
"author": "Yasen",
"author_id": 662780,
"author_profile": "https://Stackoverflow.com/users/662780",
"pm_score": 4,
"selected": false,
"text": "<p><strong>For Linux:</strong></p>\n\n<ol>\n<li><p>You need to have access to the MySQL config file.<br>\nThe location can vary from <code>/etc/mysql/my.cnf</code> to <code>~/my.cnf</code> (user directory).</p></li>\n<li><p>Add the following lines in the section <code>[mysqld]</code>:</p>\n\n<pre><code>collation_server = utf8_unicode_ci\ncharacter_set_server=utf8\n</code></pre></li>\n<li><p>Restart the server:</p>\n\n<pre><code>service mysqld restart\n</code></pre></li>\n</ol>\n"
},
{
"answer_id": 18568958,
"author": "Thor A. Pedersen",
"author_id": 900774,
"author_profile": "https://Stackoverflow.com/users/900774",
"pm_score": 3,
"selected": false,
"text": "<p>know this is an old post. But the way i changed the default charset through phpMyAdmin was:</p>\n\n<p>phpMyadmin main page > Variables tab (Server variables and settings) > searched for \"character\" and changed all variables from \"latin1\" to \"utf8\".\n(on a MAMP installation with phpMyAdmin v. 3.5.7)</p>\n\n<p>And as the others said, this is the variables for MySQL and not some phpMyAdmin specific ones.</p>\n"
},
{
"answer_id": 48437982,
"author": "Yash",
"author_id": 5081877,
"author_profile": "https://Stackoverflow.com/users/5081877",
"pm_score": 2,
"selected": false,
"text": "<p>MySQL DB « change <a href=\"https://dev.mysql.com/doc/refman/5.7/en/charset-unicode-sets.html\" rel=\"nofollow noreferrer\">Collation</a> Name of a Database|Table to <code>utf8_general_ci</code> inorder to support Unicode.</p>\n\n<p>Change <strong>Configuration settings</strong> file also</p>\n\n<hr>\n\n<p>XAMPP: \nuncomment <code>UTF 8 Settings</code> from the Configuration settings file « <code>D:\\xampp\\mysql\\bin\\my.ini</code></p>\n\n\n\n<pre class=\"lang-config prettyprint-override\"><code>## UTF 8 Settings\n#init-connect=\\'SET NAMES utf8\\'\ncollation_server=utf8_unicode_ci\ncharacter_set_server=utf8\nskip-character-set-client-handshake\ncharacter_sets-dir=\"D:/xampp/mysql/share/charsets\"\n</code></pre>\n\n\n\n<hr>\n\n<p>For MySQL server to support UTF8 and the below line of code in file <code>my.cnf</code></p>\n\n\n\n<pre class=\"lang-config prettyprint-override\"><code>## UTF 8 Settings\ncollation_server=utf8_unicode_ci\ncharacter_set_server=utf8\n</code></pre>\n\n\n\n<hr>\n\n<p>@see</p>\n\n<ul>\n<li><a href=\"https://stackoverflow.com/a/48404726/5081877\">XAMPP - Apache Virtual Host Setting</a></li>\n<li><a href=\"https://stackoverflow.com/a/48380154/5081877\">XAMPP security concept - Error 403,404</a></li>\n</ul>\n"
},
{
"answer_id": 51503914,
"author": "MAX POWER",
"author_id": 372630,
"author_profile": "https://Stackoverflow.com/users/372630",
"pm_score": 4,
"selected": false,
"text": "<p>For <code>utf8mb4</code>, add/change the following in the <code>[mysqld]</code> section:</p>\n\n<pre><code>collation_server = utf8mb4_unicode_ci\ncharacter_set_server = utf8mb4\n</code></pre>\n\n<p>Then restart the <code>mysql</code> service (for Ubuntu the command is <code>sudo service mysql restart</code>)</p>\n"
},
{
"answer_id": 57761067,
"author": "user251433",
"author_id": 10002582,
"author_profile": "https://Stackoverflow.com/users/10002582",
"pm_score": 2,
"selected": false,
"text": "<ol>\n<li>Insert this strings into <code>my.ini</code> (or <code>my.cnf</code>)</li>\n</ol>\n\n<pre><code>[mysqld]\ncollation_server = utf8_unicode_ci\ncharacter_set_server=utf8\n</code></pre>\n\n<ol start=\"2\">\n<li>Add into <code>config.inc.php</code></li>\n</ol>\n\n<pre class=\"lang-php prettyprint-override\"><code>$cfg['DefaultConnectionCollation'] = 'utf8_general_ci';\n</code></pre>\n\n<ol start=\"3\">\n<li><p>You need to restart <strong>MySQL</strong> server and remove cookies,data for domain where is located <strong>PhpMyAdmin</strong></p></li>\n<li><p>Reload page with <strong>PhpMyAmdin</strong> and at look the result</p></li>\n</ol>\n\n<p><a href=\"https://i.stack.imgur.com/hCHVF.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/hCHVF.png\" alt=\"enter image description here\"></a></p>\n"
},
{
"answer_id": 59666073,
"author": "Nelson",
"author_id": 3715973,
"author_profile": "https://Stackoverflow.com/users/3715973",
"pm_score": 0,
"selected": false,
"text": "<p>I wanted to use utf8mb4 instead, and the configuration had to be the following:</p>\n\n<pre><code>collation_server = utf8mb4_general_ci\ncharacter_set_server=utf8mb4\n</code></pre>\n\n<p>the server would not start if the character_set was set to <code>utf8</code></p>\n"
},
{
"answer_id": 74413120,
"author": "ChrisH",
"author_id": 1210149,
"author_profile": "https://Stackoverflow.com/users/1210149",
"pm_score": 0,
"selected": false,
"text": "<p>The original question was for the <strong>default setting in phpMyAdmin.</strong>\nI think the question relates to creating a NEW database in phpMyAdmin - when the page shows utf8mb4...\nThis IS a phpMyAdmin setting!\nIf you want the default for creating new databases to show utf8_general_ci.\nAdd the following 2 line to your config.inc.php file:</p>\n<p><code>$cfg['DefaultCharset'] = 'utf8';</code></p>\n<p><code>$cfg['DefaultConnectionCollation'] = 'utf8_general_ci';</code></p>\n<p>See phpMyAdmin docs <a href=\"https://docs.phpmyadmin.net/en/latest/config.html\" rel=\"nofollow noreferrer\">https://docs.phpmyadmin.net/en/latest/config.html</a> and\n<a href=\"https://docs.phpmyadmin.net/en/latest/config.html#cfg_DefaultConnectionCollation\" rel=\"nofollow noreferrer\">https://docs.phpmyadmin.net/en/latest/config.html#cfg_DefaultConnectionCollation</a></p>\n"
}
] |
2008/09/30
|
[
"https://Stackoverflow.com/questions/153706",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2138/"
] |
It seems to me that phpMyAdmin imports tables by default with collation latin1\_swedish\_ci, how i change this?
|
In your Mysql configuration change the default-character-set operative under the [mysqld] tab. For example:
```
[mysqld]
default-character-set=utf8
```
Don't forget to restart your Mysql server afterwards for the changes to take effect.
|
153,707 |
<p>Suppose I have the following declaration:</p>
<pre><code>class Over1
{
protected:
class Under1
{
};
};
</code></pre>
<p>I know that I could do the following:</p>
<pre><code>class Over2 : public Over1
{
protected:
class Under2 : public Under1
{
};
};
</code></pre>
<p>But is there a way to declare Under2 without Over2? </p>
<p>Since you would have to extend Over1 to use any derivative of Under1 this may seem silly, but in this situation there might be 30 different flavors of Under. I can either:</p>
<ul>
<li>Put them all inside Over1 : Not
attractive since Over2 may only use
1 or 2 of them </li>
<li>Put them each in
their own version of Over : Not
attractive since then you will have
to multiply inherit from almost the
same class. </li>
<li>Find a way to create
children of Under1 without creating
children of Over1</li>
</ul>
<p>So is this possible?</p>
<p>Thanks.</p>
|
[
{
"answer_id": 153766,
"author": "Douglas Mayle",
"author_id": 8458,
"author_profile": "https://Stackoverflow.com/users/8458",
"pm_score": 1,
"selected": false,
"text": "<p>Better than creating nested classes, you might want to look at embedding those closses into a namespace. That way, you don't need the outer class in order to get the inner class. There are some great arguments for and against in the <a href=\"http://google-styleguide.googlecode.com/svn/trunk/cppguide.xml\" rel=\"nofollow noreferrer\">Google C++ Style Guide</a>.</p>\n"
},
{
"answer_id": 153830,
"author": "Richard Corden",
"author_id": 11698,
"author_profile": "https://Stackoverflow.com/users/11698",
"pm_score": 2,
"selected": true,
"text": "<p>Using templates and explicit specializations you can do this with just one additional class declaration in Over1.</p>\n\n<pre><code>class Over1\n{\nprotected:\n class Under1\n {\n };\n\n template <typename T>\n class UnderImplementor;\n};\n\nstruct Under2Tag;\nstruct Under3Tag;\nstruct Under4Tag;\n\ntemplate <>\nclass Over1::UnderImplementor<Under2Tag> : public Over1::Under1\n{\n};\n\ntemplate <>\nclass Over1::UnderImplementor<Under3Tag> : public Over1::Under1\n{\n};\n\ntemplate <>\nclass Over1::UnderImplementor<Under4Tag> : public Over1::Under1\n{\n};\n</code></pre>\n\n<p>Hope this helps.</p>\n"
},
{
"answer_id": 153843,
"author": "Eclipse",
"author_id": 8701,
"author_profile": "https://Stackoverflow.com/users/8701",
"pm_score": 0,
"selected": false,
"text": "<p>If you want to keep Under1 protected, then by definition, you need to inherit from Over1 to access it. I would suggest making Under1 public, or using namespaces as Douglas suggested.</p>\n\n<p>I don't have the compiler to test these out right now, so I'm not at all sure that these would work, but you could try this:</p>\n\n<pre><code>class Over1\n{\n protected:\n class Under1\n {\n };\n\n public:\n class Under1Interface : public Under1 \n {\n };\n};\n\nclass Under2 : public Over1::Under1Interface\n{\n};\n</code></pre>\n\n<p>Or perhaps something like this:</p>\n\n<pre><code>class Over1\n{\n protected:\n class Under1\n {\n };\n};\n\nclass Under2 : private Over1, public Over1::Under1\n{\n};\n</code></pre>\n\n<p>Or even:</p>\n\n<pre><code>class Under2;\n\nclass Over1\n{\n friend class Under2;\n\n protected:\n class Under1\n {\n };\n};\n\nclass Under2 : public Over1::Under1\n{\n};\n</code></pre>\n\n<p>Although that would expose all of Over1s privates to Under2 - not likely something you'd want.</p>\n"
},
{
"answer_id": 967437,
"author": "jhufford",
"author_id": 105594,
"author_profile": "https://Stackoverflow.com/users/105594",
"pm_score": 0,
"selected": false,
"text": "<p>Sounds like a bit of a funky design to me. Why not try structuring your code differently. I think this could possibly be a good candidate for the decorator pattern, where you could wrap your base class in various decorators to achieve the desired functionality, the various flavors of 'under' could be decorators. Just a thought, hard to tell without knowing more about the intentions of your code.</p>\n"
}
] |
2008/09/30
|
[
"https://Stackoverflow.com/questions/153707",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/23829/"
] |
Suppose I have the following declaration:
```
class Over1
{
protected:
class Under1
{
};
};
```
I know that I could do the following:
```
class Over2 : public Over1
{
protected:
class Under2 : public Under1
{
};
};
```
But is there a way to declare Under2 without Over2?
Since you would have to extend Over1 to use any derivative of Under1 this may seem silly, but in this situation there might be 30 different flavors of Under. I can either:
* Put them all inside Over1 : Not
attractive since Over2 may only use
1 or 2 of them
* Put them each in
their own version of Over : Not
attractive since then you will have
to multiply inherit from almost the
same class.
* Find a way to create
children of Under1 without creating
children of Over1
So is this possible?
Thanks.
|
Using templates and explicit specializations you can do this with just one additional class declaration in Over1.
```
class Over1
{
protected:
class Under1
{
};
template <typename T>
class UnderImplementor;
};
struct Under2Tag;
struct Under3Tag;
struct Under4Tag;
template <>
class Over1::UnderImplementor<Under2Tag> : public Over1::Under1
{
};
template <>
class Over1::UnderImplementor<Under3Tag> : public Over1::Under1
{
};
template <>
class Over1::UnderImplementor<Under4Tag> : public Over1::Under1
{
};
```
Hope this helps.
|
153,716 |
<p>Is there any way to verify in Java code that an e-mail address is valid. By valid, I don't just mean that it's in the correct format ([email protected]), but that's it's a real active e-mail address.</p>
<p>I'm almost certain that there's no 100% reliable way to do this, because such a technique would be the stuff of spammer's dreams. But perhaps there's some technique that gives some useful indication about whether an address is 'real' or not.</p>
|
[
{
"answer_id": 153727,
"author": "Joe Skora",
"author_id": 14057,
"author_profile": "https://Stackoverflow.com/users/14057",
"pm_score": 2,
"selected": false,
"text": "<p>Without sending an email, it could be hard to get 100%, but if you <strong>do a DNS lookup on the host</strong> that should at least tell you that it is a viable destination system.</p>\n"
},
{
"answer_id": 153743,
"author": "Lasar",
"author_id": 9438,
"author_profile": "https://Stackoverflow.com/users/9438",
"pm_score": 1,
"selected": false,
"text": "<p>Do a DNS lookup on the hostname to see if that exists. You could theoretically also initiate a connection to the mailserver and see if it tells you whether the recipient exists, but I think many servers pretend they know an address, then reject the email anyway.</p>\n"
},
{
"answer_id": 153751,
"author": "MBCook",
"author_id": 18189,
"author_profile": "https://Stackoverflow.com/users/18189",
"pm_score": 6,
"selected": false,
"text": "<p>Here is what I have around. To check that the address is a valid format, here is a regex that verifies that it's nearly rfc2822 (it doesn't catch some weird corner cases). I found it on the 'net last year.</p>\n\n<pre><code>private static final Pattern rfc2822 = Pattern.compile(\n \"^[a-z0-9!#$%&'*+/=?^_`{|}~-]+(?:\\\\.[a-z0-9!#$%&'*+/=?^_`{|}~-]+)*@(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\\\\.)+[a-z0-9](?:[a-z0-9-]*[a-z0-9])?$\"\n);\n\nif (!rfc2822.matcher(email).matches()) {\n throw new Exception(\"Invalid address\");\n}\n</code></pre>\n\n<p>That will take care of simple syntax (for the most part). The other check I know of will let you check if the domain has an MX record. It looks like this:</p>\n\n<pre><code>Hashtable<String, String> env = new Hashtable<String, String>();\n\nenv.put(\"java.naming.factory.initial\", \"com.sun.jndi.dns.DnsContextFactory\");\n\nDirContext ictx = new InitialDirContext(env);\n\nAttributes attrs = ictx.getAttributes(domainName, new String[] {\"MX\"});\n\nAttribute attr = attrs.get(\"MX\");\n\nif (attr == null)\n // No MX record\nelse\n // If attr.size() > 0, there is an MX record\n</code></pre>\n\n<p>This, I also found on the 'net. It came from <a href=\"http://www.rgagnon.com/javadetails/java-0452.html\" rel=\"noreferrer\">this link</a>.</p>\n\n<p>If these both pass, you have a good chance at having a valid address. As for if the address it's self (not just the domain), it's not full, etc... you really can't check that.</p>\n\n<p>Note that the second check is <strong>time intensive</strong>. It can take anywhere from milliseconds to >30 seconds (if the DNS does not respond and times out). It's not something to try and run real-time for large numbers of people.</p>\n\n<p>Hope this helps.</p>\n\n<p><strong>EDIT</strong></p>\n\n<p>I'd like to point out that, at least instead of the regex, there are better ways to check basic validity. Don and Michael point out that Apache Commons has something, and I recently found out you can use .validate() on InternetAddress to have Java check that the address is really RFC-8222, which is certainly more accurate than my regex.</p>\n"
},
{
"answer_id": 154969,
"author": "WMR",
"author_id": 2844,
"author_profile": "https://Stackoverflow.com/users/2844",
"pm_score": 2,
"selected": false,
"text": "<p>You cannot really verify that an email exists, see my answer to a very similar question here: <a href=\"https://stackoverflow.com/questions/27474/email-smtp-validator#27491\">Email SMTP validator</a></p>\n"
},
{
"answer_id": 7502732,
"author": "Ashkan Aryan",
"author_id": 906184,
"author_profile": "https://Stackoverflow.com/users/906184",
"pm_score": 2,
"selected": false,
"text": "<p>Apache commons provides an <a href=\"http://commons.apache.org/validator/api-1.3.1/org/apache/commons/validator/EmailValidator.html\" rel=\"nofollow\">email validator class</a> too, which you can use. Simply pass your email address as an argument to isValid method.</p>\n"
},
{
"answer_id": 8873642,
"author": "Aquarelle",
"author_id": 1150915,
"author_profile": "https://Stackoverflow.com/users/1150915",
"pm_score": 0,
"selected": false,
"text": "<p>I'm not 100% sure, but isn't it possible to send an <strong>RCPT</strong> SMTP command to a mail server to determine if the recipient is valid? It would be even more expensive than the suggestion above to check for a valid MX host, but it would also be the most accurate.</p>\n"
},
{
"answer_id": 12032525,
"author": "Craigo",
"author_id": 418057,
"author_profile": "https://Stackoverflow.com/users/418057",
"pm_score": -1,
"selected": false,
"text": "<p>If you're using GWT, you can't use InternetAddress, and the pattern supplied by MBCook is pretty scary.</p>\n\n<p>Here is a less scary regex (might not be as accurate):</p>\n\n<pre><code>public static boolean isValidEmail(String emailAddress) {\n return emailAddress.contains(\" \") == false && emailAddress.matches(\".+@.+\\\\.[a-z]+\");\n}\n</code></pre>\n"
},
{
"answer_id": 12033019,
"author": "Thorbjørn Ravn Andersen",
"author_id": 53897,
"author_profile": "https://Stackoverflow.com/users/53897",
"pm_score": 1,
"selected": false,
"text": "<p>The only way you can be certain is by actually sending a mail and have it read.</p>\n\n<p>Let your registration process have a step that requires responding to information found only in the email. This is what others do.</p>\n"
},
{
"answer_id": 13283772,
"author": "asa",
"author_id": 1808359,
"author_profile": "https://Stackoverflow.com/users/1808359",
"pm_score": -1,
"selected": false,
"text": "<pre><code>public static boolean isValidEmail(String emailAddress) {\n return emailAddress.contains(\" \") == false && emailAddress.matches(\".+@.+\\\\.[a-z]+\");\n} \n</code></pre>\n"
}
] |
2008/09/30
|
[
"https://Stackoverflow.com/questions/153716",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2648/"
] |
Is there any way to verify in Java code that an e-mail address is valid. By valid, I don't just mean that it's in the correct format ([email protected]), but that's it's a real active e-mail address.
I'm almost certain that there's no 100% reliable way to do this, because such a technique would be the stuff of spammer's dreams. But perhaps there's some technique that gives some useful indication about whether an address is 'real' or not.
|
Here is what I have around. To check that the address is a valid format, here is a regex that verifies that it's nearly rfc2822 (it doesn't catch some weird corner cases). I found it on the 'net last year.
```
private static final Pattern rfc2822 = Pattern.compile(
"^[a-z0-9!#$%&'*+/=?^_`{|}~-]+(?:\\.[a-z0-9!#$%&'*+/=?^_`{|}~-]+)*@(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\\.)+[a-z0-9](?:[a-z0-9-]*[a-z0-9])?$"
);
if (!rfc2822.matcher(email).matches()) {
throw new Exception("Invalid address");
}
```
That will take care of simple syntax (for the most part). The other check I know of will let you check if the domain has an MX record. It looks like this:
```
Hashtable<String, String> env = new Hashtable<String, String>();
env.put("java.naming.factory.initial", "com.sun.jndi.dns.DnsContextFactory");
DirContext ictx = new InitialDirContext(env);
Attributes attrs = ictx.getAttributes(domainName, new String[] {"MX"});
Attribute attr = attrs.get("MX");
if (attr == null)
// No MX record
else
// If attr.size() > 0, there is an MX record
```
This, I also found on the 'net. It came from [this link](http://www.rgagnon.com/javadetails/java-0452.html).
If these both pass, you have a good chance at having a valid address. As for if the address it's self (not just the domain), it's not full, etc... you really can't check that.
Note that the second check is **time intensive**. It can take anywhere from milliseconds to >30 seconds (if the DNS does not respond and times out). It's not something to try and run real-time for large numbers of people.
Hope this helps.
**EDIT**
I'd like to point out that, at least instead of the regex, there are better ways to check basic validity. Don and Michael point out that Apache Commons has something, and I recently found out you can use .validate() on InternetAddress to have Java check that the address is really RFC-8222, which is certainly more accurate than my regex.
|
153,724 |
<p>What I would like is a method to convert a double to a string which rounds using the half-up method - i.e. if the decimal to be rounded is 5, it always rounds up to the next number. This is the standard method of rounding most people expect in most situations.</p>
<p>I also would like only significant digits to be displayed - i.e. there should not be any trailing zeroes.</p>
<p>I know one method of doing this is to use the <code>String.format</code> method:</p>
<pre><code>String.format("%.5g%n", 0.912385);
</code></pre>
<p>returns:</p>
<pre><code>0.91239
</code></pre>
<p>which is great, however it always displays numbers with 5 decimal places even if they are not significant: </p>
<pre><code>String.format("%.5g%n", 0.912300);
</code></pre>
<p>returns:</p>
<pre><code>0.91230
</code></pre>
<p>Another method is to use the <code>DecimalFormatter</code>:</p>
<pre><code>DecimalFormat df = new DecimalFormat("#.#####");
df.format(0.912385);
</code></pre>
<p>returns:</p>
<pre><code>0.91238
</code></pre>
<p>However as you can see this uses half-even rounding. That is it will round down if the previous digit is even. What I'd like is this:</p>
<pre><code>0.912385 -> 0.91239
0.912300 -> 0.9123
</code></pre>
<p>What is the best way to achieve this in Java?</p>
|
[
{
"answer_id": 153753,
"author": "asterite",
"author_id": 20459,
"author_profile": "https://Stackoverflow.com/users/20459",
"pm_score": 9,
"selected": false,
"text": "<p>Assuming <code>value</code> is a <code>double</code>, you can do:</p>\n\n<pre><code>(double)Math.round(value * 100000d) / 100000d\n</code></pre>\n\n<p>That's for 5 digits precision. The number of zeros indicate the number of decimals.</p>\n"
},
{
"answer_id": 153764,
"author": "Chris Cudmore",
"author_id": 18907,
"author_profile": "https://Stackoverflow.com/users/18907",
"pm_score": 5,
"selected": false,
"text": "<pre><code>double myNum = .912385;\nint precision = 10000; //keep 4 digits\nmyNum= Math.floor(myNum * precision +.5)/precision;\n</code></pre>\n"
},
{
"answer_id": 153785,
"author": "curtisk",
"author_id": 17651,
"author_profile": "https://Stackoverflow.com/users/17651",
"pm_score": 11,
"selected": true,
"text": "<p>Use <a href=\"http://docs.oracle.com/javase/8/docs/api/java/text/DecimalFormat.html#setRoundingMode(java.math.RoundingMode)\" rel=\"noreferrer\"><code>setRoundingMode</code></a>, set the <a href=\"http://docs.oracle.com/javase/8/docs/api/java/math/RoundingMode.html\" rel=\"noreferrer\"><code>RoundingMode</code></a> explicitly to handle your issue with the half-even round, then use the format pattern for your required output.</p>\n\n<p>Example:</p>\n\n<pre><code>DecimalFormat df = new DecimalFormat(\"#.####\");\ndf.setRoundingMode(RoundingMode.CEILING);\nfor (Number n : Arrays.asList(12, 123.12345, 0.23, 0.1, 2341234.212431324)) {\n Double d = n.doubleValue();\n System.out.println(df.format(d));\n}\n</code></pre>\n\n<p>gives the output:</p>\n\n<pre><code>12\n123.1235\n0.23\n0.1\n2341234.2125\n</code></pre>\n\n<hr>\n\n<p><strong>EDIT</strong>: The original answer does not address the accuracy of the double values. That is fine if you don't care much whether it rounds up or down. But if you want accurate rounding, then you need to take the expected accuracy of the values into account. Floating point values have a binary representation internally. That means that a value like 2.7735 does not actually have that exact value internally. It can be slightly larger or slightly smaller. If the internal value is slightly smaller, then it will not round up to 2.7740. To remedy that situation, you need to be aware of the accuracy of the values that you are working with, and add or subtract that value before rounding. For example, when you know that your values are accurate up to 6 digits, then to round half-way values up, add that accuracy to the value:</p>\n\n<pre><code>Double d = n.doubleValue() + 1e-6;\n</code></pre>\n\n<p>To round down, subtract the accuracy. </p>\n"
},
{
"answer_id": 153982,
"author": "Milhous",
"author_id": 17712,
"author_profile": "https://Stackoverflow.com/users/17712",
"pm_score": 7,
"selected": false,
"text": "<p>You can also use the </p>\n\n<pre><code>DecimalFormat df = new DecimalFormat(\"#.00000\");\ndf.format(0.912385);\n</code></pre>\n\n<p>to make sure you have the trailing 0's.</p>\n"
},
{
"answer_id": 154354,
"author": "MetroidFan2002",
"author_id": 8026,
"author_profile": "https://Stackoverflow.com/users/8026",
"pm_score": 8,
"selected": false,
"text": "<pre><code>new BigDecimal(String.valueOf(double)).setScale(yourScale, BigDecimal.ROUND_HALF_UP);\n</code></pre>\n\n<p>will get you a <code>BigDecimal</code>. To get the string out of it, just call that <code>BigDecimal</code>'s <code>toString</code> method, or the <code>toPlainString</code> method for Java 5+ for a plain format string. </p>\n\n<p>Sample program: </p>\n\n<pre><code>package trials;\nimport java.math.BigDecimal;\n\npublic class Trials {\n\n public static void main(String[] args) {\n int yourScale = 10;\n System.out.println(BigDecimal.valueOf(0.42344534534553453453-0.42324534524553453453).setScale(yourScale, BigDecimal.ROUND_HALF_UP));\n }\n</code></pre>\n"
},
{
"answer_id": 1361874,
"author": "Ovesh",
"author_id": 3751,
"author_profile": "https://Stackoverflow.com/users/3751",
"pm_score": 6,
"selected": false,
"text": "<p>Real's Java How-to <a href=\"http://www.rgagnon.com/javadetails/java-0016.html\" rel=\"noreferrer\">posts</a> this solution, which is also compatible for versions before Java 1.6.</p>\n<pre><code>BigDecimal bd = new BigDecimal(Double.toString(d));\nbd = bd.setScale(decimalPlace, BigDecimal.ROUND_HALF_UP);\nreturn bd.doubleValue();\n</code></pre>\n<h3>UPDATE: BigDecimal.ROUND_HALF_UP is deprecated - Use RoundingMode</h3>\n<pre><code>BigDecimal bd = new BigDecimal(Double.toString(number));\nbd = bd.setScale(decimalPlaces, RoundingMode.HALF_UP);\nreturn bd.doubleValue();\n</code></pre>\n"
},
{
"answer_id": 4826827,
"author": "user593581",
"author_id": 593581,
"author_profile": "https://Stackoverflow.com/users/593581",
"pm_score": 7,
"selected": false,
"text": "<p>Suppose you have</p>\n\n<pre><code>double d = 9232.129394d;\n</code></pre>\n\n<p>you can use <a href=\"http://docs.oracle.com/javase/8/docs/api/java/math/BigDecimal.html\" rel=\"noreferrer\"><code>BigDecimal</code></a></p>\n\n<pre><code>BigDecimal bd = new BigDecimal(d).setScale(2, RoundingMode.HALF_EVEN);\nd = bd.doubleValue();\n</code></pre>\n\n<p>or without BigDecimal </p>\n\n<pre><code>d = Math.round(d*100)/100.0d;\n</code></pre>\n\n<p>with both solutions <code>d == 9232.13</code></p>\n"
},
{
"answer_id": 5806991,
"author": "Amit",
"author_id": 706282,
"author_profile": "https://Stackoverflow.com/users/706282",
"pm_score": 4,
"selected": false,
"text": "<p>You could use the following utility method-</p>\n\n<pre><code>public static double round(double valueToRound, int numberOfDecimalPlaces)\n{\n double multipicationFactor = Math.pow(10, numberOfDecimalPlaces);\n double interestedInZeroDPs = valueToRound * multipicationFactor;\n return Math.round(interestedInZeroDPs) / multipicationFactor;\n}\n</code></pre>\n"
},
{
"answer_id": 6563862,
"author": "Ivan",
"author_id": 827031,
"author_profile": "https://Stackoverflow.com/users/827031",
"pm_score": 5,
"selected": false,
"text": "<p>@Milhous: the decimal format for rounding is excellent:</p>\n\n<blockquote>\n <p>You can also use the </p>\n\n<pre><code>DecimalFormat df = new DecimalFormat(\"#.00000\");\ndf.format(0.912385);\n</code></pre>\n \n <p>to make sure you have the trailing 0's.</p>\n</blockquote>\n\n<p>I would add that this method is very good at providing an actual\nnumeric, rounding mechanism - not only visually, but also when processing.</p>\n\n<p>Hypothetical: you have to implement a rounding mechanism into a GUI\nprogram. To alter the accuracy / precision of a result output simply \nchange the caret format (i.e. within the brackets). So that:</p>\n\n<pre><code>DecimalFormat df = new DecimalFormat(\"#0.######\");\ndf.format(0.912385);\n</code></pre>\n\n<p>would return as output: <code>0.912385</code></p>\n\n<pre><code>DecimalFormat df = new DecimalFormat(\"#0.#####\");\ndf.format(0.912385);\n</code></pre>\n\n<p>would return as output: <code>0.91239</code></p>\n\n<pre><code>DecimalFormat df = new DecimalFormat(\"#0.####\");\ndf.format(0.912385);\n</code></pre>\n\n<p>would return as output: <code>0.9124</code></p>\n\n<p>[EDIT: also if the caret format is like so (\"#0.############\") and you\nenter a decimal, e.g. 3.1415926, for argument's sake, DecimalFormat\ndoes not produce any garbage (e.g. trailing zeroes) and will return:\n<code>3.1415926</code> .. if you're that way inclined. Granted, it's a little verbose\nfor the liking of some dev's - but hey, it's got a low memory footprint\nduring processing and is very easy to implement.]</p>\n\n<p>So essentially, the beauty of DecimalFormat is that it simultaneously handles the string \nappearance - as well as the level of rounding precision set. Ergo: you \nget two benefits for the price of one code implementation. ;)</p>\n"
},
{
"answer_id": 6569383,
"author": "Ivan",
"author_id": 827811,
"author_profile": "https://Stackoverflow.com/users/827811",
"pm_score": 3,
"selected": false,
"text": "<p>If you really want decimal numbers for calculation (and not only for output), do not use a binary-based floating point format like double.</p>\n\n<pre><code>Use BigDecimal or any other decimal-based format.\n</code></pre>\n\n<p>I do use BigDecimal for calculations, but bear in mind it is dependent on the size of\nnumbers you're dealing with. In most of my implementations, I find parsing from double or\ninteger to Long is sufficient enough for very large number calculations.</p>\n\n<p>In fact, I've\nrecently used parsed-to-Long to get accurate representations (as opposed to hex results)\nin a GUI for numbers as big as ################################# characters (as an \nexample).</p>\n"
},
{
"answer_id": 7347099,
"author": "Jasdeep Singh",
"author_id": 934649,
"author_profile": "https://Stackoverflow.com/users/934649",
"pm_score": 2,
"selected": false,
"text": "<p>The code snippet below shows how to display n digits. The trick is to set variable pp to 1 followed by n zeros. In the example below, variable pp value has 5 zeros, so 5 digits will be displayed.</p>\n\n<pre><code>double pp = 10000;\n\ndouble myVal = 22.268699999999967;\nString needVal = \"22.2687\";\n\ndouble i = (5.0/pp);\n\nString format = \"%10.4f\";\nString getVal = String.format(format,(Math.round((myVal +i)*pp)/pp)-i).trim();\n</code></pre>\n"
},
{
"answer_id": 7593617,
"author": "JibW",
"author_id": 824751,
"author_profile": "https://Stackoverflow.com/users/824751",
"pm_score": 6,
"selected": false,
"text": "<p>You can use the DecimalFormat class.</p>\n\n<pre><code>double d = 3.76628729;\n\nDecimalFormat newFormat = new DecimalFormat(\"#.##\");\ndouble twoDecimal = Double.valueOf(newFormat.format(d));\n</code></pre>\n"
},
{
"answer_id": 12684082,
"author": "user207421",
"author_id": 207421,
"author_profile": "https://Stackoverflow.com/users/207421",
"pm_score": 7,
"selected": false,
"text": "<p>As some others have noted, the correct answer is to use either <code>DecimalFormat</code> or <code>BigDecimal</code>. Floating-point doesn't <em>have</em> decimal places so you cannot possibly round/truncate to a specific number of them in the first place. You have to work in a decimal radix, and that is what those two classes do.</p>\n\n<p>I am posting the following code as a counter-example to all the answers in this thread and indeed all over StackOverflow (and elsewhere) that recommend multiplication followed by truncation followed by division. It is incumbent on advocates of this technique to explain why the following code produces the wrong output in over 92% of cases.</p>\n\n<pre><code>public class RoundingCounterExample\n{\n\n static float roundOff(float x, int position)\n {\n float a = x;\n double temp = Math.pow(10.0, position);\n a *= temp;\n a = Math.round(a);\n return (a / (float)temp);\n }\n\n public static void main(String[] args)\n {\n float a = roundOff(0.0009434f,3);\n System.out.println(\"a=\"+a+\" (a % .001)=\"+(a % 0.001));\n int count = 0, errors = 0;\n for (double x = 0.0; x < 1; x += 0.0001)\n {\n count++;\n double d = x;\n int scale = 2;\n double factor = Math.pow(10, scale);\n d = Math.round(d * factor) / factor;\n if ((d % 0.01) != 0.0)\n {\n System.out.println(d + \" \" + (d % 0.01));\n errors++;\n }\n }\n System.out.println(count + \" trials \" + errors + \" errors\");\n }\n}\n</code></pre>\n\n<p>Output of this program:</p>\n\n<pre><code>10001 trials 9251 errors\n</code></pre>\n\n<p><strong>EDIT:</strong> To address some comments below I redid the modulus part of the test loop using <code>BigDecimal</code> and <code>new MathContext(16)</code> for the modulus operation as follows:</p>\n\n<pre><code>public static void main(String[] args)\n{\n int count = 0, errors = 0;\n int scale = 2;\n double factor = Math.pow(10, scale);\n MathContext mc = new MathContext(16, RoundingMode.DOWN);\n for (double x = 0.0; x < 1; x += 0.0001)\n {\n count++;\n double d = x;\n d = Math.round(d * factor) / factor;\n BigDecimal bd = new BigDecimal(d, mc);\n bd = bd.remainder(new BigDecimal(\"0.01\"), mc);\n if (bd.multiply(BigDecimal.valueOf(100)).remainder(BigDecimal.ONE, mc).compareTo(BigDecimal.ZERO) != 0)\n {\n System.out.println(d + \" \" + bd);\n errors++;\n }\n }\n System.out.println(count + \" trials \" + errors + \" errors\");\n}\n</code></pre>\n\n<p>Result:</p>\n\n<pre><code>10001 trials 4401 errors\n</code></pre>\n"
},
{
"answer_id": 21898592,
"author": "Li Ying",
"author_id": 958160,
"author_profile": "https://Stackoverflow.com/users/958160",
"pm_score": 3,
"selected": false,
"text": "<p>Try this: org.apache.commons.math3.util.Precision.round(double x, int scale)</p>\n\n<p>See: <a href=\"http://commons.apache.org/proper/commons-math/apidocs/org/apache/commons/math3/util/Precision.html\">http://commons.apache.org/proper/commons-math/apidocs/org/apache/commons/math3/util/Precision.html</a></p>\n\n<p>Apache Commons Mathematics Library homepage is: <a href=\"http://commons.apache.org/proper/commons-math/index.html\">http://commons.apache.org/proper/commons-math/index.html</a></p>\n\n<p>The internal implemetation of this method is:</p>\n\n<pre><code>public static double round(double x, int scale) {\n return round(x, scale, BigDecimal.ROUND_HALF_UP);\n}\n\npublic static double round(double x, int scale, int roundingMethod) {\n try {\n return (new BigDecimal\n (Double.toString(x))\n .setScale(scale, roundingMethod))\n .doubleValue();\n } catch (NumberFormatException ex) {\n if (Double.isInfinite(x)) {\n return x;\n } else {\n return Double.NaN;\n }\n }\n}\n</code></pre>\n"
},
{
"answer_id": 23207932,
"author": "aim",
"author_id": 1107862,
"author_profile": "https://Stackoverflow.com/users/1107862",
"pm_score": 0,
"selected": false,
"text": "<p>Where <em>dp</em> = decimal place you want,\nand <em>value</em> is a double.</p>\n\n<pre><code> double p = Math.pow(10d, dp);\n\n double result = Math.round(value * p)/p;\n</code></pre>\n"
},
{
"answer_id": 24884082,
"author": "Easwaramoorthy K",
"author_id": 1954390,
"author_profile": "https://Stackoverflow.com/users/1954390",
"pm_score": 3,
"selected": false,
"text": "<p>You can use BigDecimal</p>\n\n<pre><code>BigDecimal value = new BigDecimal(\"2.3\");\nvalue = value.setScale(0, RoundingMode.UP);\nBigDecimal value1 = new BigDecimal(\"-2.3\");\nvalue1 = value1.setScale(0, RoundingMode.UP);\nSystem.out.println(value + \"n\" + value1);\n</code></pre>\n\n<p>Refer: <a href=\"http://www.javabeat.net/precise-rounding-of-decimals-using-rounding-mode-enumeration/\">http://www.javabeat.net/precise-rounding-of-decimals-using-rounding-mode-enumeration/</a></p>\n"
},
{
"answer_id": 31099485,
"author": "Drew Noakes",
"author_id": 24874,
"author_profile": "https://Stackoverflow.com/users/24874",
"pm_score": 2,
"selected": false,
"text": "<p>If you're using <code>DecimalFormat</code> to convert <code>double</code> to <code>String</code>, it's very straightforward:</p>\n\n<pre><code>DecimalFormat formatter = new DecimalFormat(\"0.0##\");\nformatter.setRoundingMode(RoundingMode.HALF_UP);\n\ndouble num = 1.234567;\nreturn formatter.format(num);\n</code></pre>\n\n<p>There are several <code>RoundingMode</code> enum values to select from, depending upon the behaviour you require.</p>\n"
},
{
"answer_id": 32026036,
"author": "Mifeet",
"author_id": 2032064,
"author_profile": "https://Stackoverflow.com/users/2032064",
"pm_score": 4,
"selected": false,
"text": "<p>Here is a summary of what you can use if you want the result as String:</p>\n\n<ol>\n<li><p><a href=\"http://docs.oracle.com/javase/6/docs/api/java/text/DecimalFormat.html#setRoundingMode%28java.math.RoundingMode%29\" rel=\"noreferrer\">DecimalFormat#setRoundingMode()</a>:</p>\n\n<pre><code>DecimalFormat df = new DecimalFormat(\"#.#####\");\ndf.setRoundingMode(RoundingMode.HALF_UP);\nString str1 = df.format(0.912385)); // 0.91239\n</code></pre></li>\n<li><p><a href=\"http://docs.oracle.com/javase/7/docs/api/java/math/BigDecimal.html#setScale(int,%20java.math.RoundingMode)\" rel=\"noreferrer\">BigDecimal#setScale()</a></p>\n\n<pre><code>String str2 = new BigDecimal(0.912385)\n .setScale(5, BigDecimal.ROUND_HALF_UP)\n .toString();\n</code></pre></li>\n</ol>\n\n<p>Here is a suggestion of what libraries you can use if you want <code>double</code> as a result. I wouldn't recommend it for string conversion, though, as double may not be able to represent what you want exactly (see e.g. <a href=\"https://stackoverflow.com/q/3730019/2032064\">here</a>):</p>\n\n<ol>\n<li><p><a href=\"http://commons.apache.org/proper/commons-math/javadocs/api-3.5/org/apache/commons/math3/util/Precision.html\" rel=\"noreferrer\">Precision</a> from Apache Commons Math </p>\n\n<pre><code>double rounded = Precision.round(0.912385, 5, BigDecimal.ROUND_HALF_UP);\n</code></pre></li>\n<li><p><a href=\"http://dst.lbl.gov/ACSSoftware/colt/api/cern/jet/math/Functions.html\" rel=\"noreferrer\">Functions</a> from Colt</p>\n\n<pre><code>double rounded = Functions.round(0.00001).apply(0.912385)\n</code></pre></li>\n<li><p><a href=\"http://weka.sourceforge.net/doc.stable/weka/core/Utils.html#roundDouble(double,%20int)\" rel=\"noreferrer\">Utils</a> from Weka</p>\n\n<pre><code>double rounded = Utils.roundDouble(0.912385, 5)\n</code></pre></li>\n</ol>\n"
},
{
"answer_id": 33545114,
"author": "marco",
"author_id": 2526021,
"author_profile": "https://Stackoverflow.com/users/2526021",
"pm_score": 3,
"selected": false,
"text": "<p>I agree with the chosen answer to use <code>DecimalFormat</code> --- or alternatively <code>BigDecimal</code>.</p>\n<p>Please read <strong>Update</strong> below first!</p>\n<p><s>However if you <em>do</em> want to round the double value and get a <code>double</code> value result, you can use <code>org.apache.commons.math3.util.Precision.round(..)</code> as mentioned above. The implementation uses <code>BigDecimal</code>, is slow and creates garbage.</p>\n<p>A similar but fast and garbage-free method is provided by the <code>DoubleRounder</code> utility in the decimal4j library:</s></p>\n<pre><code> double a = DoubleRounder.round(2.0/3.0, 3);\n double b = DoubleRounder.round(2.0/3.0, 3, RoundingMode.DOWN);\n double c = DoubleRounder.round(1000.0d, 17);\n double d = DoubleRounder.round(90080070060.1d, 9);\n System.out.println(a);\n System.out.println(b);\n System.out.println(c);\n System.out.println(d);\n</code></pre>\n<p>Will output</p>\n<pre><code> 0.667\n 0.666\n 1000.0\n 9.00800700601E10\n</code></pre>\n<p>See\n<a href=\"https://github.com/tools4j/decimal4j/wiki/DoubleRounder-Utility\" rel=\"nofollow noreferrer\">https://github.com/tools4j/decimal4j/wiki/DoubleRounder-Utility</a></p>\n<p><em>Disclosure:</em> I am involved in the decimal4j project.</p>\n<p><strong>Update:</strong>\nAs @iaforek pointed out DoubleRounder sometimes returns counterintuitive results. The reason is that it performs mathematically correct rounding. For instance <code>DoubleRounder.round(256.025d, 2)</code> will be rounded down to 256.02 because the double value represented as 256.025d is somewhat smaller than the rational value 256.025 and hence will be rounded down.</p>\n<p><strong>Notes:</strong></p>\n<ul>\n<li>This behaviour is very similar to that of the <code>BigDecimal(double)</code> constructor (but not to <code>valueOf(double)</code> which uses the string constructor).</li>\n<li>The problem can be circumvented with a double rounding step to a higher precision first, but it is complicated and I am not going into the details here</li>\n</ul>\n<p>For those reasons and everything mentioned above in this post I <strong>cannot recommend to use DoubleRounder</strong>.</p>\n"
},
{
"answer_id": 35771257,
"author": "ashr",
"author_id": 3745505,
"author_profile": "https://Stackoverflow.com/users/3745505",
"pm_score": 3,
"selected": false,
"text": "<p>Just in case someone still needs help with this. This solution works perfectly for me.</p>\n\n<pre><code>private String withNoTrailingZeros(final double value, final int nrOfDecimals) {\nreturn new BigDecimal(String.valueOf(value)).setScale(nrOfDecimals, BigDecimal.ROUND_HALF_UP).stripTrailingZeros().toPlainString();\n\n}\n</code></pre>\n\n<p>returns a <code> String </code> with the desired output.</p>\n"
},
{
"answer_id": 40522406,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 3,
"selected": false,
"text": "<p>Since I found no complete answer on this theme I've put together a class that should handle this properly, with support for:</p>\n\n<ul>\n<li><strong>Formatting</strong>: Easily format a double to string with a certain number of decimal places</li>\n<li><strong>Parsing</strong>: Parse the formatted value back to double</li>\n<li><strong>Locale</strong>: Format and parse using the default locale</li>\n<li><strong>Exponential notation</strong>: Start using exponential notation after a certain threshold</li>\n</ul>\n\n<p><strong>Usage is pretty simple</strong>:</p>\n\n<p>(For the sake of this example I am using a custom locale)</p>\n\n<pre><code>public static final int DECIMAL_PLACES = 2;\n\nNumberFormatter formatter = new NumberFormatter(DECIMAL_PLACES);\n\nString value = formatter.format(9.319); // \"9,32\"\nString value2 = formatter.format(0.0000005); // \"5,00E-7\"\nString value3 = formatter.format(1324134123); // \"1,32E9\"\n\ndouble parsedValue1 = formatter.parse(\"0,4E-2\", 0); // 0.004\ndouble parsedValue2 = formatter.parse(\"0,002\", 0); // 0.002\ndouble parsedValue3 = formatter.parse(\"3423,12345\", 0); // 3423.12345\n</code></pre>\n\n<p><strong>Here is the class</strong>:</p>\n\n<pre><code>import java.math.RoundingMode;\nimport java.text.DecimalFormat;\nimport java.text.DecimalFormatSymbols;\nimport java.text.ParseException;\nimport java.util.Locale;\n\npublic class NumberFormatter {\n\n private static final String SYMBOL_INFINITE = \"\\u221e\";\n private static final char SYMBOL_MINUS = '-';\n private static final char SYMBOL_ZERO = '0';\n private static final int DECIMAL_LEADING_GROUPS = 10;\n private static final int EXPONENTIAL_INT_THRESHOLD = 1000000000; // After this value switch to exponential notation\n private static final double EXPONENTIAL_DEC_THRESHOLD = 0.0001; // Below this value switch to exponential notation\n\n private DecimalFormat decimalFormat;\n private DecimalFormat decimalFormatLong;\n private DecimalFormat exponentialFormat;\n\n private char groupSeparator;\n\n public NumberFormatter(int decimalPlaces) {\n configureDecimalPlaces(decimalPlaces);\n }\n\n public void configureDecimalPlaces(int decimalPlaces) {\n if (decimalPlaces <= 0) {\n throw new IllegalArgumentException(\"Invalid decimal places\");\n }\n\n DecimalFormatSymbols separators = new DecimalFormatSymbols(Locale.getDefault());\n separators.setMinusSign(SYMBOL_MINUS);\n separators.setZeroDigit(SYMBOL_ZERO);\n\n groupSeparator = separators.getGroupingSeparator();\n\n StringBuilder decimal = new StringBuilder();\n StringBuilder exponential = new StringBuilder(\"0.\");\n\n for (int i = 0; i < DECIMAL_LEADING_GROUPS; i++) {\n decimal.append(\"###\").append(i == DECIMAL_LEADING_GROUPS - 1 ? \".\" : \",\");\n }\n\n for (int i = 0; i < decimalPlaces; i++) {\n decimal.append(\"#\");\n exponential.append(\"0\");\n }\n\n exponential.append(\"E0\");\n\n decimalFormat = new DecimalFormat(decimal.toString(), separators);\n decimalFormatLong = new DecimalFormat(decimal.append(\"####\").toString(), separators);\n exponentialFormat = new DecimalFormat(exponential.toString(), separators);\n\n decimalFormat.setRoundingMode(RoundingMode.HALF_UP);\n decimalFormatLong.setRoundingMode(RoundingMode.HALF_UP);\n exponentialFormat.setRoundingMode(RoundingMode.HALF_UP);\n }\n\n public String format(double value) {\n String result;\n if (Double.isNaN(value)) {\n result = \"\";\n } else if (Double.isInfinite(value)) {\n result = String.valueOf(SYMBOL_INFINITE);\n } else {\n double absValue = Math.abs(value);\n if (absValue >= 1) {\n if (absValue >= EXPONENTIAL_INT_THRESHOLD) {\n value = Math.floor(value);\n result = exponentialFormat.format(value);\n } else {\n result = decimalFormat.format(value);\n }\n } else if (absValue < 1 && absValue > 0) {\n if (absValue >= EXPONENTIAL_DEC_THRESHOLD) {\n result = decimalFormat.format(value);\n if (result.equalsIgnoreCase(\"0\")) {\n result = decimalFormatLong.format(value);\n }\n } else {\n result = exponentialFormat.format(value);\n }\n } else {\n result = \"0\";\n }\n }\n return result;\n }\n\n public String formatWithoutGroupSeparators(double value) {\n return removeGroupSeparators(format(value));\n }\n\n public double parse(String value, double defValue) {\n try {\n return decimalFormat.parse(value).doubleValue();\n } catch (ParseException e) {\n e.printStackTrace();\n }\n return defValue;\n }\n\n private String removeGroupSeparators(String number) {\n return number.replace(String.valueOf(groupSeparator), \"\");\n }\n\n}\n</code></pre>\n"
},
{
"answer_id": 40538095,
"author": "pwojnowski",
"author_id": 3348552,
"author_profile": "https://Stackoverflow.com/users/3348552",
"pm_score": 0,
"selected": false,
"text": "<p>Keep in mind that String.format() and DecimalFormat produce string using default Locale. So they may write formatted number with dot or comma as a separator between integer and decimal parts. To make sure that rounded String is in the format you want use java.text.NumberFormat as so:</p>\n\n<pre><code> Locale locale = Locale.ENGLISH;\n NumberFormat nf = NumberFormat.getNumberInstance(locale);\n // for trailing zeros:\n nf.setMinimumFractionDigits(2);\n // round to 2 digits:\n nf.setMaximumFractionDigits(2);\n\n System.out.println(nf.format(.99));\n System.out.println(nf.format(123.567));\n System.out.println(nf.format(123.0));\n</code></pre>\n\n<p>Will print in English locale (no matter what your locale is):\n 0.99\n 123.57\n 123.00</p>\n\n<p>The example is taken from Farenda - <a href=\"http://farenda.com/java/java-format-double-2-decimal-places/\" rel=\"nofollow noreferrer\">how to convert double to String correctly</a>.</p>\n"
},
{
"answer_id": 40736192,
"author": "Qamar",
"author_id": 5710872,
"author_profile": "https://Stackoverflow.com/users/5710872",
"pm_score": -1,
"selected": false,
"text": "<p>If you Consider 5 or n number of decimal.\nMay be this answer solve your prob.</p>\n\n<pre><code> double a = 123.00449;\n double roundOff1 = Math.round(a*10000)/10000.00;\n double roundOff2 = Math.round(roundOff1*1000)/1000.00;\n double roundOff = Math.round(roundOff2*100)/100.00;\n\n System.out.println(\"result:\"+roundOff);\n</code></pre>\n\n<p><strong>Output will be:</strong> 123.0<strong>1</strong>\n<br/>this can be solve with loop and recursive function.</p>\n"
},
{
"answer_id": 40801184,
"author": "Se Song",
"author_id": 3458608,
"author_profile": "https://Stackoverflow.com/users/3458608",
"pm_score": 2,
"selected": false,
"text": "<p>DecimalFormat is the best ways to output, but I don't prefer it. I always do this all the time, because it return the double value. So I can use it more than just output.</p>\n\n<pre><code>Math.round(selfEvaluate*100000d.0)/100000d.0;\n</code></pre>\n\n<p>OR</p>\n\n<pre><code>Math.round(selfEvaluate*100000d.0)*0.00000d1;\n</code></pre>\n\n<p>If you need large decimal places value, you can use BigDecimal instead. Anyways <code>.0</code> is important. Without it the rounding of 0.33333d5 return 0.33333 and only 9 digits are allows. The second function without <code>.0</code> has problems with 0.30000 return 0.30000000000000004.</p>\n"
},
{
"answer_id": 42347442,
"author": "Suragch",
"author_id": 3681880,
"author_profile": "https://Stackoverflow.com/users/3681880",
"pm_score": 2,
"selected": false,
"text": "<p>I came here just wanting a simple answer on how to round a number. This is a supplemental answer to provide that.</p>\n\n<h1>How to round a number in Java</h1>\n\n<p>The most common case is to use <code>Math.round()</code>.</p>\n\n<pre><code>Math.round(3.7) // 4\n</code></pre>\n\n<p>Numbers are rounded to the nearest whole number. A <code>.5</code> value is rounded up. If you need different rounding behavior than that, you can use one of the other <a href=\"http://docs.oracle.com/javase/6/docs/api/java/lang/Math.html\" rel=\"nofollow noreferrer\">Math</a> functions. See the comparison below.</p>\n\n<h1><a href=\"http://docs.oracle.com/javase/6/docs/api/java/lang/Math.html#round(float)\" rel=\"nofollow noreferrer\">round</a></h1>\n\n<p>As stated above, this rounds to the nearest whole number. <code>.5</code> decimals round up. This method returns an <code>int</code>.</p>\n\n<pre><code>Math.round(3.0); // 3\nMath.round(3.1); // 3\nMath.round(3.5); // 4\nMath.round(3.9); // 4\n\nMath.round(-3.0); // -3\nMath.round(-3.1); // -3\nMath.round(-3.5); // -3 *** careful here ***\nMath.round(-3.9); // -4\n</code></pre>\n\n<h1><a href=\"http://docs.oracle.com/javase/6/docs/api/java/lang/Math.html#ceil(double)\" rel=\"nofollow noreferrer\">ceil</a></h1>\n\n<p>Any decimal value is rounded up to the next integer. It goes to the <strong>ceil</strong>ing. This method returns a <code>double</code>.</p>\n\n<pre><code>Math.ceil(3.0); // 3.0\nMath.ceil(3.1); // 4.0\nMath.ceil(3.5); // 4.0\nMath.ceil(3.9); // 4.0\n\nMath.ceil(-3.0); // -3.0\nMath.ceil(-3.1); // -3.0\nMath.ceil(-3.5); // -3.0\nMath.ceil(-3.9); // -3.0\n</code></pre>\n\n<h1><a href=\"http://docs.oracle.com/javase/6/docs/api/java/lang/Math.html#floor(double)\" rel=\"nofollow noreferrer\">floor</a></h1>\n\n<p>Any decimal value is rounded down to the next integer. This method returns a <code>double</code>.</p>\n\n<pre><code>Math.floor(3.0); // 3.0\nMath.floor(3.1); // 3.0\nMath.floor(3.5); // 3.0\nMath.floor(3.9); // 3.0\n\nMath.floor(-3.0); // -3.0\nMath.floor(-3.1); // -4.0\nMath.floor(-3.5); // -4.0\nMath.floor(-3.9); // -4.0\n</code></pre>\n\n<h1><a href=\"http://docs.oracle.com/javase/6/docs/api/java/lang/Math.html#rint(double)\" rel=\"nofollow noreferrer\">rint</a></h1>\n\n<p>This is similar to round in that decimal values round to the closest integer. However, unlike <code>round</code>, <code>.5</code> values round to the even integer. This method returns a <code>double</code>.</p>\n\n<pre><code>Math.rint(3.0); // 3.0\nMath.rint(3.1); // 3.0\nMath.rint(3.5); // 4.0 ***\nMath.rint(3.9); // 4.0\nMath.rint(4.5); // 4.0 ***\nMath.rint(5.5); // 6.0 ***\n\nMath.rint(-3.0); // -3.0\nMath.rint(-3.1); // -3.0\nMath.rint(-3.5); // -4.0 ***\nMath.rint(-3.9); // -4.0\nMath.rint(-4.5); // -4.0 ***\nMath.rint(-5.5); // -6.0 ***\n</code></pre>\n"
},
{
"answer_id": 45352433,
"author": "MAbraham1",
"author_id": 212950,
"author_profile": "https://Stackoverflow.com/users/212950",
"pm_score": 4,
"selected": false,
"text": "<p>A succinct solution:</p>\n<pre><code> public static double round(double value, int precision) {\n int scale = (int) Math.pow(10, precision);\n return (double) (Math.round(value * scale) / scale);\n }\n</code></pre>\n<p>See also, <a href=\"https://stackoverflow.com/a/22186845/212950\">https://stackoverflow.com/a/22186845/212950</a>\nThanks to <a href=\"https://stackoverflow.com/users/2984077/jpdymond\">jpdymond</a> for offering this.</p>\n<p><strong>Edit</strong>: Added round brackets. Casts the whole result to double, not the first argument only!</p>\n"
},
{
"answer_id": 48135104,
"author": "Craigo",
"author_id": 418057,
"author_profile": "https://Stackoverflow.com/users/418057",
"pm_score": 2,
"selected": false,
"text": "<p>If you're using a technology that has a minimal JDK. Here's a way without any Java libs:</p>\n\n<pre><code>double scale = 100000; \ndouble myVal = 0.912385;\ndouble rounded = (int)((myVal * scale) + 0.5d) / scale;\n</code></pre>\n"
},
{
"answer_id": 48764733,
"author": "Amr Ali",
"author_id": 4208440,
"author_profile": "https://Stackoverflow.com/users/4208440",
"pm_score": 2,
"selected": false,
"text": "<p>Here is a better function that rounds edge cases like <code>1.005</code> correctly.</p>\n<p>Simply, we add the smallest possible float value (= 1 ulp; unit in the last place) to the number before rounding. This moves to the next representable value after the number, away from zero.</p>\n<p>This is a little program to test it: <a href=\"https://ideone.com/TnTOic\" rel=\"nofollow noreferrer\">ideone.com</a></p>\n<pre><code>/**\n * Round half away from zero ('commercial' rounding)\n * Uses correction to offset floating-point inaccuracies.\n * Works symmetrically for positive and negative numbers.\n */\npublic static double round(double num, int digits) {\n\n // epsilon correction\n double n = Double.longBitsToDouble(Double.doubleToLongBits(num) + 1);\n double p = Math.pow(10, digits);\n return Math.round(n * p) / p;\n}\n\n// test rounding of half\nSystem.out.println(round(0.5, 0)); // 1\nSystem.out.println(round(-0.5, 0)); // -1\n\n// testing edge cases\nSystem.out.println(round(1.005, 2)); // 1.01\nSystem.out.println(round(2.175, 2)); // 2.18\nSystem.out.println(round(5.015, 2)); // 5.02\n\nSystem.out.println(round(-1.005, 2)); // -1.01\nSystem.out.println(round(-2.175, 2)); // -2.18\nSystem.out.println(round(-5.015, 2)); // -5.02\n</code></pre>\n"
},
{
"answer_id": 49284415,
"author": "Jorgesys",
"author_id": 250260,
"author_profile": "https://Stackoverflow.com/users/250260",
"pm_score": 3,
"selected": false,
"text": "<p>To achieve this we can use this formatter:</p>\n\n<pre><code> DecimalFormat df = new DecimalFormat(\"#.00\");\n String resultado = df.format(valor)\n</code></pre>\n\n<p>or:</p>\n\n<pre><code>DecimalFormat df = new DecimalFormat(\"0.00\"); :\n</code></pre>\n\n<p>Use this method to get always two decimals:</p>\n\n<pre><code> private static String getTwoDecimals(double value){\n DecimalFormat df = new DecimalFormat(\"0.00\"); \n return df.format(value);\n }\n</code></pre>\n\n<hr>\n\n<p>Defining this values:</p>\n\n<pre><code>91.32\n5.22\n11.5\n1.2\n2.6\n</code></pre>\n\n<p>Using the method we can get this results:</p>\n\n<pre><code>91.32\n5.22\n11.50\n1.20\n2.60\n</code></pre>\n\n<p><a href=\"https://www.ideone.com/jJGyRa\" rel=\"noreferrer\"><strong>demo online.</strong></a></p>\n"
},
{
"answer_id": 57584089,
"author": "Md. Jamal Uddin",
"author_id": 6542943,
"author_profile": "https://Stackoverflow.com/users/6542943",
"pm_score": 2,
"selected": false,
"text": "<p>here is my answer:</p>\n\n<pre><code>double num = 4.898979485566356;\nDecimalFormat df = new DecimalFormat(\"#.##\"); \ntime = Double.valueOf(df.format(num));\n\nSystem.out.println(num); // 4.89\n</code></pre>\n"
},
{
"answer_id": 58565101,
"author": "Alain Cruz",
"author_id": 4259032,
"author_profile": "https://Stackoverflow.com/users/4259032",
"pm_score": 3,
"selected": false,
"text": "<p>So after reading most of the answers, I realized most of them won't be precise, in fact using <code>BigDecimal</code> seems like the best choice, but if you don't understand how the <code>RoundingMode</code> works, you will inevitable lose precision. I figured this out when working with big numbers in a project and thought it could help others having trouble rounding numbers. For example.</p>\n\n<pre><code>BigDecimal bd = new BigDecimal(\"1363.2749\");\nbd = bd.setScale(2, RoundingMode.HALF_UP);\nSystem.out.println(bd.doubleValue());\n</code></pre>\n\n<p>You would expect to get <code>1363.28</code> as an output, but you will end up with <code>1363.27</code>, which is not expected, if you don't know what the <code>RoundingMode</code> is doing. So looking into the <a href=\"https://docs.oracle.com/javase/7/docs/api/java/math/RoundingMode.html\" rel=\"nofollow noreferrer\">Oracle Docs</a>, you will find the following description for <code>RoundingMode.HALF_UP</code>.</p>\n\n<blockquote>\n <p>Rounding mode to round towards \"nearest neighbor\" unless both\n neighbors are equidistant, in which case round up.</p>\n</blockquote>\n\n<p>So knowing this, we realized that we won't be getting an exact rounding, unless we want to round towards <em>nearest neighbor</em>. So, to accomplish an adequate round, we would need to loop from the <code>n-1</code> decimal towards the desired decimals digits. For example.</p>\n\n<pre><code>private double round(double value, int places) throws IllegalArgumentException {\n\n if (places < 0) throw new IllegalArgumentException();\n\n // Cast the number to a String and then separate the decimals.\n String stringValue = Double.toString(value);\n String decimals = stringValue.split(\"\\\\.\")[1];\n\n // Round all the way to the desired number.\n BigDecimal bd = new BigDecimal(stringValue);\n for (int i = decimals.length()-1; i >= places; i--) {\n bd = bd.setScale(i, RoundingMode.HALF_UP);\n }\n\n return bd.doubleValue();\n}\n</code></pre>\n\n<p>This will end up giving us the expected output, which would be <code>1363.28</code>.</p>\n"
},
{
"answer_id": 61691949,
"author": "Enamul Haque",
"author_id": 3972291,
"author_profile": "https://Stackoverflow.com/users/3972291",
"pm_score": 2,
"selected": false,
"text": "<p><strong>I have used bellow like in java 8. it is working for me</strong></p>\n\n<pre><code> double amount = 1000.431; \n NumberFormat formatter = new DecimalFormat(\"##.00\");\n String output = formatter.format(amount);\n System.out.println(\"output = \" + output);\n</code></pre>\n\n<p><strong>Output:</strong></p>\n\n<pre><code>output = 1000.43\n</code></pre>\n"
},
{
"answer_id": 62555681,
"author": "Dmitry Fisenko",
"author_id": 723411,
"author_profile": "https://Stackoverflow.com/users/723411",
"pm_score": 1,
"selected": false,
"text": "<p>the following method could be used if need <code>double</code></p>\n<pre class=\"lang-java prettyprint-override\"><code>double getRandom(int decimalPoints) {\n double a = Math.random();\n int multiplier = (int) Math.pow(10, decimalPoints);\n int b = (int) (a * multiplier);\n return b / (double) multiplier;\n}\n</code></pre>\n<p>for example <code>getRandom(2)</code></p>\n"
},
{
"answer_id": 63607720,
"author": "Niraj",
"author_id": 3580786,
"author_profile": "https://Stackoverflow.com/users/3580786",
"pm_score": 1,
"selected": false,
"text": "<ol>\n<li>In order to have trailing 0s up to 5th position</li>\n</ol>\n<blockquote>\n<pre><code>DecimalFormat decimalFormatter = new DecimalFormat("#.00000");\ndecimalFormatter.format(0.350500); // result 0.350500\n</code></pre>\n</blockquote>\n<ol start=\"2\">\n<li>In order to avoid trailing 0s up to 5th position</li>\n</ol>\n<blockquote>\n<pre><code>DecimalFormat decimalFormatter= new DecimalFormat("#.#####");\ndecimalFormatter.format(0.350500); // result o.3505\n</code></pre>\n</blockquote>\n"
},
{
"answer_id": 64401405,
"author": "Harisudha",
"author_id": 13302453,
"author_profile": "https://Stackoverflow.com/users/13302453",
"pm_score": 0,
"selected": false,
"text": "<p>A simple way to compare if it is limited number of decimal places.\nInstead of DecimalFormat, Math or BigDecimal, we can use Casting!</p>\n<p>Here is the sample,</p>\n<pre><code>public static boolean threeDecimalPlaces(double value1, double value2){\n boolean isEqual = false;\n // value1 = 3.1756 \n // value2 = 3.17\n //(int) (value1 * 1000) = 3175\n //(int) (value2 * 1000) = 3170\n\n if ((int) (value1 * 1000) == (int) (value2 * 1000)){\n areEqual = true;\n }\n\n return isEqual;\n}\n</code></pre>\n"
},
{
"answer_id": 65786718,
"author": "Milan Paudyal",
"author_id": 6770146,
"author_profile": "https://Stackoverflow.com/users/6770146",
"pm_score": 1,
"selected": false,
"text": "<pre><code>public static double formatDecimal(double amount) {\n BigDecimal amt = new BigDecimal(amount);\n amt = amt.divide(new BigDecimal(1), 2, BigDecimal.ROUND_HALF_EVEN);\n return amt.doubleValue();\n}\n</code></pre>\n<p>Test using Junit</p>\n<pre><code>@RunWith(Parameterized.class)\npublic class DecimalValueParameterizedTest {\n\n @Parameterized.Parameter\n public double amount;\n\n @Parameterized.Parameter(1)\n public double expectedValue;\n\[email protected]\npublic static List<Object[]> dataSets() {\n return Arrays.asList(new Object[][]{\n {1000.0, 1000.0},\n {1000, 1000.0},\n {1000.00000, 1000.0},\n {1000.01, 1000.01},\n {1000.1, 1000.10},\n {1000.001, 1000.0},\n {1000.005, 1000.0},\n {1000.007, 1000.01},\n {1000.999, 1001.0},\n {1000.111, 1000.11}\n });\n}\n\n@Test\npublic void testDecimalFormat() {\n Assert.assertEquals(expectedValue, formatDecimal(amount), 0.00);\n}\n</code></pre>\n"
},
{
"answer_id": 69056857,
"author": "Nur Alam",
"author_id": 10379931,
"author_profile": "https://Stackoverflow.com/users/10379931",
"pm_score": 0,
"selected": false,
"text": "<p>Very simple method</p>\n<pre><code>public static double round(double value, int places) {\n if (places < 0) throw new IllegalArgumentException();\n\n DecimalFormat deciFormat = new DecimalFormat();\n deciFormat.setMaximumFractionDigits(places);\n String newValue = deciFormat.format(value);\n\n return Double.parseDouble(newValue);\n\n}\n\ndouble a = round(12.36545, 2);\n</code></pre>\n"
},
{
"answer_id": 72950324,
"author": "Salix alba",
"author_id": 865481,
"author_profile": "https://Stackoverflow.com/users/865481",
"pm_score": 0,
"selected": false,
"text": "<p>There is a problem with the <code>Math.round</code> solution when trying to round to a negative number of decimal places. Consider the code</p>\n<pre><code>long l = 10;\nfor(int dp = -1; dp > -10; --dp) {\n double mul = Math.pow(10,dp);\n double res = Math.round(l * mul) / mul;\n System.out.println(""+l+" rounded to "+dp+" dp = "+res);\n l *=10;\n}\n</code></pre>\n<p>this has the results</p>\n<pre><code>10 rounded to -1 dp = 10.0\n100 rounded to -2 dp = 100.0\n1000 rounded to -3 dp = 1000.0\n10000 rounded to -4 dp = 10000.0\n100000 rounded to -5 dp = 99999.99999999999\n1000000 rounded to -6 dp = 1000000.0\n10000000 rounded to -7 dp = 1.0E7\n100000000 rounded to -8 dp = 1.0E8\n1000000000 rounded to -9 dp = 9.999999999999999E8\n</code></pre>\n<p>The problem with -5 decimal places occur when dividing 1 by 1.0E-5 which is inexact.</p>\n<p>This can be fixed using</p>\n<pre><code>double mul = Math.pow(10,dp);\ndouble res;\nif(dp < 0 ) {\n double div = Math.pow(10,-dp);\n res = Math.round(l * mul) *div;\n} else {\n res = Math.round(l * mul) / mul;\n}\n</code></pre>\n<p>But this is another reason to use the BigDecimal methods.</p>\n"
},
{
"answer_id": 73609506,
"author": "Jackson Meires",
"author_id": 4906873,
"author_profile": "https://Stackoverflow.com/users/4906873",
"pm_score": 0,
"selected": false,
"text": "<p>This was the simplest way I found to display only two decimal places.</p>\n<pre><code>double x = 123.123;\nSystem.out.printf( "%.2f", x );\n</code></pre>\n"
}
] |
2008/09/30
|
[
"https://Stackoverflow.com/questions/153724",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/12149/"
] |
What I would like is a method to convert a double to a string which rounds using the half-up method - i.e. if the decimal to be rounded is 5, it always rounds up to the next number. This is the standard method of rounding most people expect in most situations.
I also would like only significant digits to be displayed - i.e. there should not be any trailing zeroes.
I know one method of doing this is to use the `String.format` method:
```
String.format("%.5g%n", 0.912385);
```
returns:
```
0.91239
```
which is great, however it always displays numbers with 5 decimal places even if they are not significant:
```
String.format("%.5g%n", 0.912300);
```
returns:
```
0.91230
```
Another method is to use the `DecimalFormatter`:
```
DecimalFormat df = new DecimalFormat("#.#####");
df.format(0.912385);
```
returns:
```
0.91238
```
However as you can see this uses half-even rounding. That is it will round down if the previous digit is even. What I'd like is this:
```
0.912385 -> 0.91239
0.912300 -> 0.9123
```
What is the best way to achieve this in Java?
|
Use [`setRoundingMode`](http://docs.oracle.com/javase/8/docs/api/java/text/DecimalFormat.html#setRoundingMode(java.math.RoundingMode)), set the [`RoundingMode`](http://docs.oracle.com/javase/8/docs/api/java/math/RoundingMode.html) explicitly to handle your issue with the half-even round, then use the format pattern for your required output.
Example:
```
DecimalFormat df = new DecimalFormat("#.####");
df.setRoundingMode(RoundingMode.CEILING);
for (Number n : Arrays.asList(12, 123.12345, 0.23, 0.1, 2341234.212431324)) {
Double d = n.doubleValue();
System.out.println(df.format(d));
}
```
gives the output:
```
12
123.1235
0.23
0.1
2341234.2125
```
---
**EDIT**: The original answer does not address the accuracy of the double values. That is fine if you don't care much whether it rounds up or down. But if you want accurate rounding, then you need to take the expected accuracy of the values into account. Floating point values have a binary representation internally. That means that a value like 2.7735 does not actually have that exact value internally. It can be slightly larger or slightly smaller. If the internal value is slightly smaller, then it will not round up to 2.7740. To remedy that situation, you need to be aware of the accuracy of the values that you are working with, and add or subtract that value before rounding. For example, when you know that your values are accurate up to 6 digits, then to round half-way values up, add that accuracy to the value:
```
Double d = n.doubleValue() + 1e-6;
```
To round down, subtract the accuracy.
|
153,731 |
<p>I am looking for validation framework and while I am already using NHibernate I am thinking of using NHibernate.validator from contrib project however I also look at MS Validation Block which seem to be robust but i am not yet get into detail of each one yet so I wonder has anyone had step into these two frameworks and how is the experience like?</p>
|
[
{
"answer_id": 153839,
"author": "Daniel Honig",
"author_id": 1129162,
"author_profile": "https://Stackoverflow.com/users/1129162",
"pm_score": -1,
"selected": false,
"text": "<p>How about D) None of the above.\nI remember evaluating this last year and decided on going with Spring.NET's validation framework.</p>\n\n<p>If your using NHibernate your probably want to use Spring.NET's facilities for using NHibernate as well.</p>\n"
},
{
"answer_id": 154092,
"author": "Daniel Honig",
"author_id": 1129162,
"author_profile": "https://Stackoverflow.com/users/1129162",
"pm_score": 0,
"selected": false,
"text": "<p>For the most part I would say that Spring.NET is pretty independent. Meaning it should not force you to re-architect. You can use as much or as little as you want. It should be pretty easy to write an object that you can inject into classes needing validation using spring. You would then wire this object up in castle to take the name of the \"Validation Group\" or \"Validators\" you needed and then have spring inject the validators into that object where your form/business object/service would then use the validators.</p>\n\n<p>Here is a link to the doc,Validation is section 12:</p>\n\n<p><a href=\"http://www.springframework.net/docs/1.2.0-M1/reference/html/index.html\" rel=\"nofollow noreferrer\">http://www.springframework.net/docs/1.2.0-M1/reference/html/index.html</a></p>\n\n<p>Are you just using Castle or are you using Monorail?</p>\n"
},
{
"answer_id": 787580,
"author": "mookid8000",
"author_id": 6560,
"author_profile": "https://Stackoverflow.com/users/6560",
"pm_score": 4,
"selected": true,
"text": "<p>NHibernate Validator does not require you to use NHibernate for persistence. Usage can be as simple as:</p>\n\n<pre><code>var engine = new ValidatorEngine();\nInvalidValue[] errors = engine.Validate(someModelObjectWithAttributes);\n\nforeach(var error in errors)\n{\n Console.WriteLine(error.Message);\n}\n</code></pre>\n\n<p>Of course it can hook into NHibernate and prevent persistence of invalid objects, but you may use it to validate non-persistent objects as well.</p>\n"
},
{
"answer_id": 1027203,
"author": "dariol",
"author_id": 3644960,
"author_profile": "https://Stackoverflow.com/users/3644960",
"pm_score": 0,
"selected": false,
"text": "<p>Of course you can try to write your own validation framework. For eg. Karl Seguin will help you:</p>\n\n<p><a href=\"http://codebetter.com/blogs/karlseguin/archive/2009/04/26/validation-part-1-getting-started.aspx\" rel=\"nofollow noreferrer\">http://codebetter.com/blogs/karlseguin/archive/2009/04/26/validation-part-1-getting-started.aspx</a></p>\n\n<p><a href=\"http://codebetter.com/blogs/karlseguin/archive/2009/04/27/validation-part-2-client-side.aspx\" rel=\"nofollow noreferrer\">http://codebetter.com/blogs/karlseguin/archive/2009/04/27/validation-part-2-client-side.aspx</a></p>\n\n<p><a href=\"http://codebetter.com/blogs/karlseguin/archive/2009/04/28/validation-part-3-server-side.aspx\" rel=\"nofollow noreferrer\">http://codebetter.com/blogs/karlseguin/archive/2009/04/28/validation-part-3-server-side.aspx</a></p>\n\n<p>It's really nice solution :)</p>\n"
}
] |
2008/09/30
|
[
"https://Stackoverflow.com/questions/153731",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/15396/"
] |
I am looking for validation framework and while I am already using NHibernate I am thinking of using NHibernate.validator from contrib project however I also look at MS Validation Block which seem to be robust but i am not yet get into detail of each one yet so I wonder has anyone had step into these two frameworks and how is the experience like?
|
NHibernate Validator does not require you to use NHibernate for persistence. Usage can be as simple as:
```
var engine = new ValidatorEngine();
InvalidValue[] errors = engine.Validate(someModelObjectWithAttributes);
foreach(var error in errors)
{
Console.WriteLine(error.Message);
}
```
Of course it can hook into NHibernate and prevent persistence of invalid objects, but you may use it to validate non-persistent objects as well.
|
153,748 |
<p>I've tried this:</p>
<pre><code>string newScript = textBox1.Text;
HtmlElement head = browserCtrl.Document.GetElementsByTagName("head")[0];
HtmlElement scriptEl = browserCtrl.Document.CreateElement("script");
lblStatus.Text = scriptEl.GetType().ToString();
scriptEl.SetAttribute("type", "text/javascript");
head.AppendChild(scriptEl);
scriptEl.InnerHtml = "function sayHello() { alert('hello') }";
</code></pre>
<p>scriptEl.InnerHtml and scriptEl.InnerText both give errors:</p>
<pre><code>System.NotSupportedException: Property is not supported on this type of HtmlElement.
at System.Windows.Forms.HtmlElement.set_InnerHtml(String value)
at SForceApp.Form1.button1_Click(Object sender, EventArgs e) in d:\jsight\installs\SForceApp\SForceApp\Form1.cs:line 31
at System.Windows.Forms.Control.OnClick(EventArgs e)
at System.Windows.Forms.Button.OnClick(EventArgs e)
at System.Windows.Forms.Button.OnMouseUp(MouseEventArgs mevent)
at System.Windows.Forms.Control.WmMouseUp(Message& m, MouseButtons button, Int32 clicks)
at System.Windows.Forms.Control.WndProc(Message& m)
at System.Windows.Forms.ButtonBase.WndProc(Message& m)
at System.Windows.Forms.Button.WndProc(Message& m)
at System.Windows.Forms.Control.ControlNativeWindow.OnMessage(Message& m)
at System.Windows.Forms.Control.ControlNativeWindow.WndProc(Message& m)
at System.Windows.Forms.NativeWindow.Callback(IntPtr hWnd, Int32 msg, IntPtr wparam, IntPtr lparam)
</code></pre>
<p>Is there an easy way to inject a script into the dom?</p>
|
[
{
"answer_id": 153756,
"author": "mattlant",
"author_id": 14642,
"author_profile": "https://Stackoverflow.com/users/14642",
"pm_score": 0,
"selected": false,
"text": "<p>What you want to do is use Page.RegisterStartupScript(key, script) \n:</p>\n\n<p>See here for more details: <a href=\"http://msdn.microsoft.com/en-us/library/aa478975.aspx\" rel=\"nofollow noreferrer\">http://msdn.microsoft.com/en-us/library/aa478975.aspx</a></p>\n\n<p>What you basically do is build your javascript string, pass it to that method and give it a unique id( in case you try to register it twice on a page.)</p>\n\n<p>EDIT: This is what you call trigger happy. Feel free to down it. :)</p>\n"
},
{
"answer_id": 153761,
"author": "TcKs",
"author_id": 20382,
"author_profile": "https://Stackoverflow.com/users/20382",
"pm_score": 1,
"selected": false,
"text": "<p>You can always use a \"DocumentStream\" or \"DocumentText\" property.\nFor working with HTML documents I recommend a <a href=\"http://www.codeplex.com/htmlagilitypack\" rel=\"nofollow noreferrer\">HTML Agility Pack</a>.</p>\n"
},
{
"answer_id": 154330,
"author": "ZeroBugBounce",
"author_id": 11314,
"author_profile": "https://Stackoverflow.com/users/11314",
"pm_score": 3,
"selected": false,
"text": "<p>The managed wrapper for the HTML document doesn't completely implement the functionality you need, so you need to dip into the MSHTML API to accomplish what you want:</p>\n\n<p>1) Add a reference to MSHTML, which will probalby be called \"Microsoft HTML Object Library\" under <em>COM</em> references.</p>\n\n<p>2) Add 'using mshtml;' to your namespaces.</p>\n\n<p>3) Get a reference to your script element's IHTMLElement:</p>\n\n<pre><code>IHTMLElement iScriptEl = (IHTMLElement)scriptEl.DomElement;\n</code></pre>\n\n<p>4) Call the insertAdjacentText method, with the first parameter value of \"afterBegin\". All the possible values are listed <a href=\"http://msdn.microsoft.com/en-us/library/aa170712(office.11).aspx\" rel=\"noreferrer\">here</a>:</p>\n\n<pre><code>iScriptEl.insertAdjacentText(\"afterBegin\", \"function sayHello() { alert('hello') }\");\n</code></pre>\n\n<p>5) Now you'll be able to see the code in the scriptEl.InnerText property.</p>\n\n<p>Hth,\nRichard</p>\n"
},
{
"answer_id": 154496,
"author": "Atanas Korchev",
"author_id": 10141,
"author_profile": "https://Stackoverflow.com/users/10141",
"pm_score": 8,
"selected": true,
"text": "<p>For some reason Richard's solution didn't work on my end (insertAdjacentText failed with an exception). This however seems to work:</p>\n\n<pre><code>HtmlElement head = webBrowser1.Document.GetElementsByTagName(\"head\")[0];\nHtmlElement scriptEl = webBrowser1.Document.CreateElement(\"script\");\nIHTMLScriptElement element = (IHTMLScriptElement)scriptEl.DomElement;\nelement.text = \"function sayHello() { alert('hello') }\";\nhead.AppendChild(scriptEl);\nwebBrowser1.Document.InvokeScript(\"sayHello\");\n</code></pre>\n\n<p><a href=\"https://stackoverflow.com/a/5216255/157247\">This answer</a> explains how to get the <code>IHTMLScriptElement</code> interface into your project.</p>\n"
},
{
"answer_id": 2268843,
"author": "Eyal",
"author_id": 4454,
"author_profile": "https://Stackoverflow.com/users/4454",
"pm_score": 4,
"selected": false,
"text": "<p>If all you really want is to run javascript, this would be easiest (VB .Net):</p>\n\n<pre><code>MyWebBrowser.Navigate(\"javascript:function foo(){alert('hello');}foo();\")\n</code></pre>\n\n<p>I guess that this wouldn't \"inject\" it but it'll run your function, if that's what you're after. (Just in case you've over-complicated the problem.) And if you can figure out how to inject in javascript, put that into the body of the function \"foo\" and let the javascript do the injection for you.</p>\n"
},
{
"answer_id": 3057506,
"author": "justin.m.chase",
"author_id": 12958,
"author_profile": "https://Stackoverflow.com/users/12958",
"pm_score": 5,
"selected": false,
"text": "<p>Also, in .NET 4 this is even easier if you use the dynamic keyword:</p>\n\n<pre><code>dynamic document = this.browser.Document;\ndynamic head = document.GetElementsByTagName(\"head\")[0];\ndynamic scriptEl = document.CreateElement(\"script\");\nscriptEl.text = ...;\nhead.AppendChild(scriptEl);\n</code></pre>\n"
},
{
"answer_id": 3506531,
"author": "Camilo Sanchez",
"author_id": 247328,
"author_profile": "https://Stackoverflow.com/users/247328",
"pm_score": 3,
"selected": false,
"text": "<p>this is a solution using mshtml</p>\n\n<pre><code>IHTMLDocument2 doc = new HTMLDocumentClass();\ndoc.write(new object[] { File.ReadAllText(filePath) });\ndoc.close();\n\nIHTMLElement head = (IHTMLElement)((IHTMLElementCollection)doc.all.tags(\"head\")).item(null, 0);\nIHTMLScriptElement scriptObject = (IHTMLScriptElement)doc.createElement(\"script\");\nscriptObject.type = @\"text/javascript\";\nscriptObject.text = @\"function btn1_OnClick(str){\n alert('you clicked' + str);\n}\";\n((HTMLHeadElementClass)head).appendChild((IHTMLDOMNode)scriptObject);\n</code></pre>\n"
},
{
"answer_id": 6222430,
"author": "typpo",
"author_id": 782100,
"author_profile": "https://Stackoverflow.com/users/782100",
"pm_score": 6,
"selected": false,
"text": "<pre><code>HtmlDocument doc = browser.Document;\nHtmlElement head = doc.GetElementsByTagName(\"head\")[0];\nHtmlElement s = doc.CreateElement(\"script\");\ns.SetAttribute(\"text\",\"function sayHello() { alert('hello'); }\");\nhead.AppendChild(s);\nbrowser.Document.InvokeScript(\"sayHello\");\n</code></pre>\n\n<p>(tested in .NET 4 / Windows Forms App)</p>\n\n<p>Edit: Fixed case issue in function set. </p>\n"
},
{
"answer_id": 7801574,
"author": "Santiago",
"author_id": 1000163,
"author_profile": "https://Stackoverflow.com/users/1000163",
"pm_score": 3,
"selected": false,
"text": "<p>I believe the most simple method to inject Javascript in a WebBrowser Control HTML Document from c# is to invoke the \"execScript\" method with the code to be injected as argument.</p>\n\n<p>In this example the javascript code is injected and executed at global scope:</p>\n\n<pre><code>var jsCode=\"alert('hello world from injected code');\";\nWebBrowser.Document.InvokeScript(\"execScript\", new Object[] { jsCode, \"JavaScript\" });\n</code></pre>\n\n<p>If you want to delay execution, inject functions and call them after:</p>\n\n<pre><code>var jsCode=\"function greet(msg){alert(msg);};\";\nWebBrowser.Document.InvokeScript(\"execScript\", new Object[] { jsCode, \"JavaScript\" });\n...............\nWebBrowser.Document.InvokeScript(\"greet\",new object[] {\"hello world\"});\n</code></pre>\n\n<p>This is valid for Windows Forms and WPF WebBrowser controls.</p>\n\n<p>This solution is not cross browser because \"execScript\" is defined only in IE and Chrome. But the question is about Microsoft WebBrowser controls and IE is the only one supported.</p>\n\n<p>For a valid cross browser method to inject javascript code, create a Function object with the new Keyword. This example creates an anonymous function with injected code and executes it (javascript implements closures and the function has access to global space without local variable pollution).</p>\n\n<pre><code>var jsCode=\"alert('hello world');\";\n(new Function(code))();\n</code></pre>\n\n<p>Of course, you can delay execution:</p>\n\n<pre><code>var jsCode=\"alert('hello world');\";\nvar inserted=new Function(code);\n.................\ninserted();\n</code></pre>\n\n<p>Hope it helps</p>\n"
},
{
"answer_id": 8157159,
"author": "sh0ber",
"author_id": 1050347,
"author_profile": "https://Stackoverflow.com/users/1050347",
"pm_score": 2,
"selected": false,
"text": "<p>Here is a VB.Net example if you are trying to retrieve the value of a variable from within a page loaded in a WebBrowser control.</p>\n\n<p>Step 1) Add a COM reference in your project to Microsoft HTML Object Library</p>\n\n<p>Step 2) Next, add this VB.Net code to your Form1 to import the mshtml library:<br />\n Imports mshtml</p>\n\n<p>Step 3) Add this VB.Net code above your \"Public Class Form1\" line:<br />\n <System.Runtime.InteropServices.ComVisibleAttribute(True)></p>\n\n<p>Step 4) Add a WebBrowser control to your project</p>\n\n<p>Step 5) Add this VB.Net code to your Form1_Load function:<br />\n WebBrowser1.ObjectForScripting = Me</p>\n\n<p>Step 6) Add this VB.Net sub which will inject a function \"CallbackGetVar\" into the web page's Javascript:</p>\n\n\n\n<pre class=\"lang-vb prettyprint-override\"><code>Public Sub InjectCallbackGetVar(ByRef wb As WebBrowser)\n Dim head As HtmlElement\n Dim script As HtmlElement\n Dim domElement As IHTMLScriptElement\n\n head = wb.Document.GetElementsByTagName(\"head\")(0)\n script = wb.Document.CreateElement(\"script\")\n domElement = script.DomElement\n domElement.type = \"text/javascript\"\n domElement.text = \"function CallbackGetVar(myVar) { window.external.Callback_GetVar(eval(myVar)); }\"\n head.AppendChild(script)\nEnd Sub\n</code></pre>\n\n<p>Step 7) Add the following VB.Net sub which the Javascript will then look for when invoked:</p>\n\n<pre class=\"lang-vb prettyprint-override\"><code>Public Sub Callback_GetVar(ByVal vVar As String)\n Debug.Print(vVar)\nEnd Sub\n</code></pre>\n\n<p>Step 8) Finally, to invoke the Javascript callback, add this VB.Net code when a button is pressed, or wherever you like:</p>\n\n<pre class=\"lang-vb prettyprint-override\"><code>Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click\n WebBrowser1.Document.InvokeScript(\"CallbackGetVar\", New Object() {\"NameOfVarToRetrieve\"})\nEnd Sub\n</code></pre>\n\n<p>Step 9) If it surprises you that this works, you may want to read up on the Javascript \"eval\" function, used in Step 6, which is what makes this possible. It will take a string and determine whether a variable exists with that name and, if so, returns the value of that variable.</p>\n"
},
{
"answer_id": 8687037,
"author": "Ilya Rosikhin",
"author_id": 1124105,
"author_profile": "https://Stackoverflow.com/users/1124105",
"pm_score": 5,
"selected": false,
"text": "<p>Here is the easiest way that I found after working on this:</p>\n\n<pre><code>string javascript = \"alert('Hello');\";\n// or any combination of your JavaScript commands\n// (including function calls, variables... etc)\n\n// WebBrowser webBrowser1 is what you are using for your web browser\nwebBrowser1.Document.InvokeScript(\"eval\", new object[] { javascript });\n</code></pre>\n\n<p>What global JavaScript function <code>eval(str)</code> does is parses and executes whatever is written in str.\nCheck <a href=\"http://www.w3schools.com/jsref/jsref_eval.asp\" rel=\"noreferrer\">w3schools ref here</a>.</p>\n"
},
{
"answer_id": 10153977,
"author": "Uwe Keim",
"author_id": 107625,
"author_profile": "https://Stackoverflow.com/users/107625",
"pm_score": 3,
"selected": false,
"text": "<p>As a follow-up to the <a href=\"https://stackoverflow.com/a/154496/107625\">accepted answer</a>, this is a minimal definition of the <a href=\"http://msdn.microsoft.com/en-us/library/aa768904%28v=vs.85%29.aspx\" rel=\"nofollow noreferrer\"><code>IHTMLScriptElement</code> interface</a> which does not require to include additional type libraries:</p>\n\n<pre><code>[ComImport, ComVisible(true), Guid(@\"3050f28b-98b5-11cf-bb82-00aa00bdce0b\")]\n[InterfaceTypeAttribute(ComInterfaceType.InterfaceIsIDispatch)]\n[TypeLibType(TypeLibTypeFlags.FDispatchable)]\npublic interface IHTMLScriptElement\n{\n [DispId(1006)]\n string text { set; [return: MarshalAs(UnmanagedType.BStr)] get; }\n}\n</code></pre>\n\n<p>So a full code inside a WebBrowser control derived class would look like:</p>\n\n<pre><code>protected override void OnDocumentCompleted(\n WebBrowserDocumentCompletedEventArgs e)\n{\n base.OnDocumentCompleted(e);\n\n // Disable text selection.\n var doc = Document;\n if (doc != null)\n {\n var heads = doc.GetElementsByTagName(@\"head\");\n if (heads.Count > 0)\n {\n var scriptEl = doc.CreateElement(@\"script\");\n if (scriptEl != null)\n {\n var element = (IHTMLScriptElement)scriptEl.DomElement;\n element.text =\n @\"function disableSelection()\n { \n document.body.onselectstart=function(){ return false; }; \n document.body.ondragstart=function() { return false; };\n }\";\n heads[0].AppendChild(scriptEl);\n doc.InvokeScript(@\"disableSelection\");\n }\n }\n }\n}\n</code></pre>\n"
},
{
"answer_id": 26813233,
"author": "pablo",
"author_id": 4229231,
"author_profile": "https://Stackoverflow.com/users/4229231",
"pm_score": 0,
"selected": false,
"text": "<p>If you need to inject a whole file then you can use this:</p>\n\n<pre class=\"lang-vb prettyprint-override\"><code>With Browser.Document\n Dim Head As HtmlElement = .GetElementsByTagName(\"head\")(0)\n Dim Script As HtmlElement = .CreateElement(\"script\")\n Dim Streamer As New StreamReader(<Here goes path to file as String>)\n Using Streamer\n Script.SetAttribute(\"text\", Streamer.ReadToEnd())\n End Using\n Head.AppendChild(Script)\n .InvokeScript(<Here goes a method name as String and without parentheses>)\nEnd With\n</code></pre>\n\n<p>Remember to import <code>System.IO</code> in order to use the <code>StreamReader</code>. I hope this helps.</p>\n"
},
{
"answer_id": 38459070,
"author": "Oscar David Diaz Fortaleché",
"author_id": 5025091,
"author_profile": "https://Stackoverflow.com/users/5025091",
"pm_score": 2,
"selected": false,
"text": "<p>I used this :D</p>\n\n<pre><code>HtmlElement script = this.WebNavegador.Document.CreateElement(\"SCRIPT\");\nscript.SetAttribute(\"TEXT\", \"function GetNameFromBrowser() {\" + \n\"return 'My name is David';\" + \n\"}\");\n\nthis.WebNavegador.Document.Body.AppendChild(script);\n</code></pre>\n\n<p>Then you can execute and get the result with:</p>\n\n<pre><code>string myNameIs = (string)this.WebNavegador.Document.InvokeScript(\"GetNameFromBrowser\");\n</code></pre>\n\n<p>I hope to be helpful</p>\n"
},
{
"answer_id": 50558487,
"author": "Z.R.T.",
"author_id": 7060504,
"author_profile": "https://Stackoverflow.com/users/7060504",
"pm_score": 1,
"selected": false,
"text": "<p>i use this:</p>\n\n<pre><code>webBrowser.Document.InvokeScript(\"execScript\", new object[] { \"alert(123)\", \"JavaScript\" })\n</code></pre>\n"
},
{
"answer_id": 74093844,
"author": "painful mindset",
"author_id": 20260899,
"author_profile": "https://Stackoverflow.com/users/20260899",
"pm_score": 0,
"selected": false,
"text": "<p>bibki.js</p>\n<pre><code>webBrowser1.DocumentText =\n "<html><head><script>" +\n "function test(message) { alert(message); }" +\n "</script></head><body><button " +\n "onclick=\\"window.external.Test('called from script code')\\">" +\n "call client code from script code</button>" +\n "</body></html>";\n</code></pre>\n"
}
] |
2008/09/30
|
[
"https://Stackoverflow.com/questions/153748",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1432/"
] |
I've tried this:
```
string newScript = textBox1.Text;
HtmlElement head = browserCtrl.Document.GetElementsByTagName("head")[0];
HtmlElement scriptEl = browserCtrl.Document.CreateElement("script");
lblStatus.Text = scriptEl.GetType().ToString();
scriptEl.SetAttribute("type", "text/javascript");
head.AppendChild(scriptEl);
scriptEl.InnerHtml = "function sayHello() { alert('hello') }";
```
scriptEl.InnerHtml and scriptEl.InnerText both give errors:
```
System.NotSupportedException: Property is not supported on this type of HtmlElement.
at System.Windows.Forms.HtmlElement.set_InnerHtml(String value)
at SForceApp.Form1.button1_Click(Object sender, EventArgs e) in d:\jsight\installs\SForceApp\SForceApp\Form1.cs:line 31
at System.Windows.Forms.Control.OnClick(EventArgs e)
at System.Windows.Forms.Button.OnClick(EventArgs e)
at System.Windows.Forms.Button.OnMouseUp(MouseEventArgs mevent)
at System.Windows.Forms.Control.WmMouseUp(Message& m, MouseButtons button, Int32 clicks)
at System.Windows.Forms.Control.WndProc(Message& m)
at System.Windows.Forms.ButtonBase.WndProc(Message& m)
at System.Windows.Forms.Button.WndProc(Message& m)
at System.Windows.Forms.Control.ControlNativeWindow.OnMessage(Message& m)
at System.Windows.Forms.Control.ControlNativeWindow.WndProc(Message& m)
at System.Windows.Forms.NativeWindow.Callback(IntPtr hWnd, Int32 msg, IntPtr wparam, IntPtr lparam)
```
Is there an easy way to inject a script into the dom?
|
For some reason Richard's solution didn't work on my end (insertAdjacentText failed with an exception). This however seems to work:
```
HtmlElement head = webBrowser1.Document.GetElementsByTagName("head")[0];
HtmlElement scriptEl = webBrowser1.Document.CreateElement("script");
IHTMLScriptElement element = (IHTMLScriptElement)scriptEl.DomElement;
element.text = "function sayHello() { alert('hello') }";
head.AppendChild(scriptEl);
webBrowser1.Document.InvokeScript("sayHello");
```
[This answer](https://stackoverflow.com/a/5216255/157247) explains how to get the `IHTMLScriptElement` interface into your project.
|
153,759 |
<p>How do I use the jQuery Datepicker with a textbox input:</p>
<pre><code>$("#my_txtbox").datepicker({
// options
});
</code></pre>
<p>that doesn't allow the user to input random text in the textbox.
I want the Datepicker to pop up when the textbox gains focus or the user clicks on it, but I want the textbox to ignore any user input using the keyboard (copy & paste, or any other). I want to fill the textbox exclusively from the Datepicker calendar.</p>
<p>Is this possible?</p>
<p>jQuery 1.2.6<br/>
Datepicker 1.5.2</p>
|
[
{
"answer_id": 153804,
"author": "Adam Bellaire",
"author_id": 21632,
"author_profile": "https://Stackoverflow.com/users/21632",
"pm_score": 9,
"selected": true,
"text": "<p>You should be able to use the <strong>readonly</strong> attribute on the text input, and jQuery will still be able to edit its contents.</p>\n\n<pre><code><input type='text' id='foo' readonly='true'>\n</code></pre>\n"
},
{
"answer_id": 153817,
"author": "Eduardo Molteni",
"author_id": 2385,
"author_profile": "https://Stackoverflow.com/users/2385",
"pm_score": 2,
"selected": false,
"text": "<p>To datepicker to popup on gain focus:</p>\n\n<pre><code>$(\".selector\").datepicker({ showOn: 'both' })\n</code></pre>\n\n<p>If you don't want user input, add this to the input field</p>\n\n<pre><code><input type=\"text\" name=\"date\" readonly=\"readonly\" />\n</code></pre>\n"
},
{
"answer_id": 153821,
"author": "Brad8118",
"author_id": 7617,
"author_profile": "https://Stackoverflow.com/users/7617",
"pm_score": 4,
"selected": false,
"text": "<p>try</p>\n\n<pre><code>$(\"#my_txtbox\").keypress(function(event) {event.preventDefault();});\n</code></pre>\n"
},
{
"answer_id": 153826,
"author": "Zach",
"author_id": 9128,
"author_profile": "https://Stackoverflow.com/users/9128",
"pm_score": 1,
"selected": false,
"text": "<p>This <a href=\"http://www.kelvinluck.com/assets/jquery/datePicker/v2/demo/datePickerClickInput.html\" rel=\"nofollow noreferrer\">demo</a> sort of does that by putting the calendar over the text field so you can't type in it. You can also set the input field to read only in the HTML to be sure.</p>\n\n<pre><code><input type=\"text\" readonly=\"true\" />\n</code></pre>\n"
},
{
"answer_id": 153827,
"author": "James Curran",
"author_id": 12725,
"author_profile": "https://Stackoverflow.com/users/12725",
"pm_score": 0,
"selected": false,
"text": "<p>I've found that the jQuery Calendar plugin, for me at least, in general just works better for selecting dates.</p>\n"
},
{
"answer_id": 1748170,
"author": "Adhip Gupta",
"author_id": 384,
"author_profile": "https://Stackoverflow.com/users/384",
"pm_score": 3,
"selected": false,
"text": "<p>If you are reusing the date-picker at multiple places then it would be apt to modify the textbox also via JavaScript by using something like:</p>\n\n<pre><code>$(\"#my_txtbox\").attr( 'readOnly' , 'true' );\n</code></pre>\n\n<p>right after/before the place where you initialize your datepicker.</p>\n"
},
{
"answer_id": 1754234,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 3,
"selected": false,
"text": "<pre><code><input type=\"text\" readonly=\"true\" />\n</code></pre>\n\n<p>causes the textbox to lose its value after postback. </p>\n\n<p>You rather should use Brad8118's suggestion which is working perfectly.</p>\n\n<pre><code>$(\"#my_txtbox\").keypress(function(event) {event.preventDefault();});\n</code></pre>\n\n<p>EDIT:\nto get it working for IE use 'keydown' instead of 'keypress'</p>\n"
},
{
"answer_id": 7625106,
"author": "2046",
"author_id": 975201,
"author_profile": "https://Stackoverflow.com/users/975201",
"pm_score": 6,
"selected": false,
"text": "<p>Based on my experience I would recommend the solution suggested by Adhip Gupta:</p>\n\n<pre><code>$(\"#my_txtbox\").attr( 'readOnly' , 'true' );\n</code></pre>\n\n<p>The following code won't let the user type new characters, but <strong>will</strong> allow them to delete characters:</p>\n\n<pre><code>$(\"#my_txtbox\").keypress(function(event) {event.preventDefault();});\n</code></pre>\n\n<p>Additionally, this will render the form useless to those who have JavaScript disabled:</p>\n\n<pre><code><input type=\"text\" readonly=\"true\" />\n</code></pre>\n"
},
{
"answer_id": 12943978,
"author": "Steinwolfe",
"author_id": 1736818,
"author_profile": "https://Stackoverflow.com/users/1736818",
"pm_score": -1,
"selected": false,
"text": "<p>Or you could, for example, use a hidden field to store the value...</p>\n\n<pre><code> <asp:HiddenField ID=\"hfDay\" runat=\"server\" />\n</code></pre>\n\n<p>and in the $(\"#my_txtbox\").datepicker({ options:</p>\n\n<pre><code> onSelect: function (dateText, inst) {\n $(\"#<% =hfDay.ClientID %>\").val(dateText);\n }\n</code></pre>\n"
},
{
"answer_id": 15088455,
"author": "Shabbir.A.Hussain",
"author_id": 2111125,
"author_profile": "https://Stackoverflow.com/users/2111125",
"pm_score": -1,
"selected": false,
"text": "<p>If you want the user to select a date from the datepicker but you dont want the user to type inside the textbox then use the following code :</p>\n\n<pre><code><script type=\"text/javascript\">\n$(function () {\n $(\"#datepicker\").datepicker({ maxDate: \"-1D\" }).attr('readonly', 'readonly');\n $(\"#datepicker\").readonlyDatepicker(true);\n\n});\n</code></pre>\n\n<p></p>\n"
},
{
"answer_id": 20072084,
"author": "LithiumD",
"author_id": 3008859,
"author_profile": "https://Stackoverflow.com/users/3008859",
"pm_score": 0,
"selected": false,
"text": "<pre><code>$('.date').each(function (e) {\n if ($(this).attr('disabled') != 'disabled') {\n $(this).attr('readOnly', 'true');\n $(this).css('cursor', 'pointer');\n $(this).css('color', '#5f5f5f');\n }\n});\n</code></pre>\n"
},
{
"answer_id": 27057395,
"author": "user2182143",
"author_id": 2182143,
"author_profile": "https://Stackoverflow.com/users/2182143",
"pm_score": 2,
"selected": false,
"text": "<p>You have two options to get this done. (As far as i know)</p>\n\n<ol>\n<li><p><strong>Option A:</strong> Make your text field read only. It can be done as follows.</p>\n\n<p></p></li>\n<li><p><strong>Option B:</strong> Change the curser onfocus. Set ti to blur. it can be done by setting up the attribute <code>onfocus=\"this.blur()\"</code> to your date picker text field. </p></li>\n</ol>\n\n<p>Ex: <code><input type=\"text\" name=\"currentDate\" id=\"currentDate\" onfocus=\"this.blur()\" readonly/></code></p>\n\n \n"
},
{
"answer_id": 28625057,
"author": "kayz1",
"author_id": 1127843,
"author_profile": "https://Stackoverflow.com/users/1127843",
"pm_score": 1,
"selected": false,
"text": "<p><strong>HTML</strong> </p>\n\n<pre><code><input class=\"date-input\" type=\"text\" readonly=\"readonly\" />\n</code></pre>\n\n<p><strong>CSS</strong></p>\n\n<pre><code>.date-input {\n background-color: white;\n cursor: pointer;\n}\n</code></pre>\n"
},
{
"answer_id": 31738303,
"author": "johnkhadka",
"author_id": 5109531,
"author_profile": "https://Stackoverflow.com/users/5109531",
"pm_score": 0,
"selected": false,
"text": "<p>Here is your answer which is way to solve.You do not want to use jquery when you restricted the user input in textbox control.</p>\n\n<pre><code><input type=\"text\" id=\"my_txtbox\" readonly /> <!--HTML5-->\n\n<input type=\"text\" id=\"my_txtbox\" readonly=\"true\"/>\n</code></pre>\n"
},
{
"answer_id": 32649509,
"author": "Chenthil",
"author_id": 3181178,
"author_profile": "https://Stackoverflow.com/users/3181178",
"pm_score": 2,
"selected": false,
"text": "<pre><code>$(\"#txtfromdate\").datepicker({ \n numberOfMonths: 2,\n maxDate: 0, \n dateFormat: 'dd-M-yy' \n}).attr('readonly', 'readonly');\n</code></pre>\n\n<p>add the readonly attribute in the jquery.</p>\n"
},
{
"answer_id": 38409525,
"author": "Prakash Singh",
"author_id": 3661687,
"author_profile": "https://Stackoverflow.com/users/3661687",
"pm_score": 0,
"selected": false,
"text": "<p>$(\"#my_txtbox\").prop('readonly', true) </p>\n\n<p>worked like a charm..</p>\n"
},
{
"answer_id": 40778974,
"author": "Ajjay Arora",
"author_id": 2585917,
"author_profile": "https://Stackoverflow.com/users/2585917",
"pm_score": 0,
"selected": false,
"text": "<p>Instead of using textbox you can use button also. Works best for me, where I don't want users to write date manually.</p>\n\n<p><a href=\"https://i.stack.imgur.com/h7zpq.gif\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/h7zpq.gif\" alt=\"enter image description here\"></a></p>\n"
},
{
"answer_id": 41892415,
"author": "umutesen",
"author_id": 2093029,
"author_profile": "https://Stackoverflow.com/users/2093029",
"pm_score": 3,
"selected": false,
"text": "<p>After initialising the date picker:</p>\n<pre><code>$(".project-date").datepicker({\n dateFormat: 'd M yy'\n});\n\n$(".project-date").keydown(false);\n</code></pre>\n"
},
{
"answer_id": 42645439,
"author": "Matija",
"author_id": 779965,
"author_profile": "https://Stackoverflow.com/users/779965",
"pm_score": 2,
"selected": false,
"text": "<p>I just came across this so I am sharing here. Here is the option</p>\n\n<p><a href=\"https://eonasdan.github.io/bootstrap-datetimepicker/Options/#ignorereadonly\" rel=\"nofollow noreferrer\">https://eonasdan.github.io/bootstrap-datetimepicker/Options/#ignorereadonly</a></p>\n\n<p>Here is the code.</p>\n\n<p><strong>HTML</strong></p>\n\n<pre><code><br/>\n<!-- padding for jsfiddle -->\n<div class=\"input-group date\" id=\"arrival_date_div\">\n <input type=\"text\" class=\"form-control\" id=\"arrival_date\" name=\"arrival_date\" required readonly=\"readonly\" />\n <span class=\"input-group-addon\">\n <span class=\"glyphicon-calendar glyphicon\"></span>\n </span>\n</div>\n</code></pre>\n\n<p><strong>JS</strong></p>\n\n<pre><code>$('#arrival_date_div').datetimepicker({\n format: \"YYYY-MM-DD\",\n ignoreReadonly: true\n});\n</code></pre>\n\n<p>Here is the fiddle:</p>\n\n<p><a href=\"http://jsfiddle.net/matbaric/wh1cb6cy/\" rel=\"nofollow noreferrer\">http://jsfiddle.net/matbaric/wh1cb6cy/</a></p>\n\n<p>My version of bootstrap-datetimepicker.js is 4.17.45</p>\n"
},
{
"answer_id": 44586882,
"author": "Shantaram Tupe",
"author_id": 3425489,
"author_profile": "https://Stackoverflow.com/users/3425489",
"pm_score": 0,
"selected": false,
"text": "<p>I know this question is already answered, and most suggested to use <strong><code>readonly</code></strong> attribure.<br>\nI just want to share my scenario and answer.</p>\n\n<p>After adding <strong><code>readonly</code></strong> attribute to my <strong>HTML Element</strong>, I faced issue that I am not able to make <strong>this</strong> attribute as <strong><code>required</code></strong> dynamically.<br>\nEven tried setting as both <strong><code>readonly</code></strong> and <strong><code>required</code></strong> at HTML creation time.</p>\n\n<p>So I will suggest do not use <strong><code>readonly</code></strong> if you want to set it as <strong><code>required</code></strong> also. </p>\n\n<p>Instead use </p>\n\n<pre><code>$(\"#my_txtbox\").datepicker({\n // options\n});\n\n$(\"#my_txtbox\").keypress(function(event) {\n return ( ( event.keyCode || event.which ) === 9 ? true : false );\n});\n</code></pre>\n\n<p>This allow to press <strong><code>tab</code></strong> key only.<br>\nYou can add more <strong>keycodes</strong> which you want to bypass.</p>\n\n<p>I below code since I have added both <strong><code>readonly</code></strong> and <strong><code>required</code></strong> it still submits the form.<br>\nAfter removing <strong><code>readonly</code></strong> it works properly. </p>\n\n<p><a href=\"https://jsfiddle.net/shantaram/hd9o7eor/\" rel=\"nofollow noreferrer\">https://jsfiddle.net/shantaram/hd9o7eor/</a></p>\n\n<p><div class=\"snippet\" data-lang=\"js\" data-hide=\"false\" data-console=\"true\" data-babel=\"false\">\r\n<div class=\"snippet-code\">\r\n<pre class=\"snippet-code-js lang-js prettyprint-override\"><code>$(function() {\r\n $('#id-checkbox').change( function(){\r\n $('#id-input3').prop('required', $(this).is(':checked'));\r\n });\r\n $('#id-input3').datepicker();\r\n $(\"#id-input3\").keypress(function(event) {\r\n return ( ( event.keyCode || event.which ) === 9 ? true : false );\r\n});\r\n});</code></pre>\r\n<pre class=\"snippet-code-html lang-html prettyprint-override\"><code><script src=\"https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js\"></script>\r\n\r\n<script src=\"https://code.jquery.com/ui/1.12.1/jquery-ui.js\"></script>\r\n\r\n<link href=\"https://code.jquery.com/ui/jquery-ui-git.css\" rel=\"stylesheet\"/>\r\n\r\n<form action='https://jsfiddle.net/'>\r\nName: <input type=\"text\" name='xyz' id='id-input3' readonly='true' required='true'> \r\n <input type='checkbox' id='id-checkbox'> Required <br>\r\n <br>\r\n <input type='submit' value='Submit'>\r\n</form></code></pre>\r\n</div>\r\n</div>\r\n</p>\n"
},
{
"answer_id": 46330554,
"author": "Mohan",
"author_id": 2033553,
"author_profile": "https://Stackoverflow.com/users/2033553",
"pm_score": 0,
"selected": false,
"text": "<p>replace the ID of time picker:\nIDofDatetimePicker to your id.</p>\n\n<p>This will prevent the user from entering any further keyboard inputs but still, the user will be able to access the time popup.</p>\n\n<p>$(\"#my_txtbox\").keypress(function(event) {event.preventDefault();});</p>\n\n<p>Try this\nsource:\n<a href=\"https://github.com/jonthornton/jquery-timepicker/issues/109\" rel=\"nofollow noreferrer\">https://github.com/jonthornton/jquery-timepicker/issues/109</a></p>\n"
},
{
"answer_id": 55106037,
"author": "Mariana Marica",
"author_id": 3771721,
"author_profile": "https://Stackoverflow.com/users/3771721",
"pm_score": 2,
"selected": false,
"text": "<p>I know this thread is old, but for others who encounter the same problem, that implement @Brad8118 solution (which i prefer, because if you choose to make the input readonly then the user will not be able to delete the date value inserted from datepicker if he chooses) and also need to prevent the user from pasting a value (as @ErikPhilips suggested to be needed), I let this addition here, which worked for me: \n<code>$(\"#my_txtbox\").bind('paste',function(e) { e.preventDefault(); //disable paste });</code> from here <a href=\"https://www.dotnettricks.com/learn/jquery/disable-cut-copy-and-paste-in-textbox-using-jquery-javascript\" rel=\"nofollow noreferrer\">https://www.dotnettricks.com/learn/jquery/disable-cut-copy-and-paste-in-textbox-using-jquery-javascript</a>\nand the whole specific script used by me (using fengyuanchen/datepicker plugin instead):</p>\n\n<pre><code>$('[data-toggle=\"datepicker\"]').datepicker({\n autoHide: true,\n pick: function (e) {\n e.preventDefault();\n $(this).val($(this).datepicker('getDate', true));\n }\n}).keypress(function(event) {\n event.preventDefault(); // prevent keyboard writing but allowing value deletion\n}).bind('paste',function(e) {\n e.preventDefault()\n}); //disable paste;\n</code></pre>\n"
},
{
"answer_id": 55492178,
"author": "Peter Bowers",
"author_id": 4282342,
"author_profile": "https://Stackoverflow.com/users/4282342",
"pm_score": 0,
"selected": false,
"text": "<p>This question has a lot of older answers and readonly seems to be the generally accepted solution. I believe the better approach in modern browsers is to use the <code>inputmode=\"none\"</code> in the HTML input tag:</p>\n\n<pre><code><input type=\"text\" ... inputmode=\"none\" />\n</code></pre>\n\n<p>or, if you prefer to do it in script:</p>\n\n<pre><code>$(selector).attr('inputmode', 'none');\n</code></pre>\n\n<p>I haven't tested it extensively, but it is working well on the Android setups I have used it with.</p>\n"
},
{
"answer_id": 57354241,
"author": "Krishnan KK",
"author_id": 6587910,
"author_profile": "https://Stackoverflow.com/users/6587910",
"pm_score": 2,
"selected": false,
"text": "<p>Instead of adding <a href=\"https://www.w3schools.com/tags/att_input_readonly.asp\" rel=\"nofollow noreferrer\">readonly</a> you can also use <a href=\"https://www.w3schools.com/jsref/event_onkeypress.asp\" rel=\"nofollow noreferrer\">onkeypress=\"return false;\"</a></p>\n"
},
{
"answer_id": 67671155,
"author": "Ahmed Awan",
"author_id": 1076775,
"author_profile": "https://Stackoverflow.com/users/1076775",
"pm_score": 0,
"selected": false,
"text": "<p>In my case i have use <code>disableTextInput</code> property</p>\n<pre><code>$( ".datepicker" ).datepicker({'dateFormat' : 'd-m-y', 'disableTextInput':true });\n</code></pre>\n"
}
] |
2008/09/30
|
[
"https://Stackoverflow.com/questions/153759",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2024/"
] |
How do I use the jQuery Datepicker with a textbox input:
```
$("#my_txtbox").datepicker({
// options
});
```
that doesn't allow the user to input random text in the textbox.
I want the Datepicker to pop up when the textbox gains focus or the user clicks on it, but I want the textbox to ignore any user input using the keyboard (copy & paste, or any other). I want to fill the textbox exclusively from the Datepicker calendar.
Is this possible?
jQuery 1.2.6
Datepicker 1.5.2
|
You should be able to use the **readonly** attribute on the text input, and jQuery will still be able to edit its contents.
```
<input type='text' id='foo' readonly='true'>
```
|
153,762 |
<p>Our graphics person uses Adobe Illustrator and we'd like to use her images inside our WPF application as paths. Is there a way to do this?</p>
|
[
{
"answer_id": 153875,
"author": "ConcernedOfTunbridgeWells",
"author_id": 15401,
"author_profile": "https://Stackoverflow.com/users/15401",
"pm_score": 0,
"selected": false,
"text": "<p>Get her to export the illustrations as some other format (recent versions of Illustrator support SVG) that you can use or convert to something that will work.</p>\n"
},
{
"answer_id": 26541828,
"author": "DuckMaestro",
"author_id": 29152,
"author_profile": "https://Stackoverflow.com/users/29152",
"pm_score": 2,
"selected": false,
"text": "<p>You can go from AI to SVG to XAML.</p>\n\n<ol>\n<li><p>From Adobe Illustrator: File -> Save As -> *.SVG.</p>\n\n<ul>\n<li><p>SVG \"Profile 1.1\" seems to be sufficient.</p></li>\n<li><p>Note that to preserve path/group names in XAML you should enable \"Preserve Illustrator Editing Capabilities\" (or at least as it's called in CS4).</p></li>\n</ul></li>\n<li><p><a href=\"https://sharpvectors.codeplex.com/\" rel=\"nofollow noreferrer\">SharpVectors</a> can convert SVG data to XAML data. This will produce a fragment of XAML with root <code><DrawingGroup></code>.</p></li>\n<li><p>Do what you need to do to copy-paste and otherwise use the XAML, such as placing it into an Image like below. Named objects or groups in the AI file should still have their names in the XAML i.e. via <code>x:Name=\"...\"</code>.</p></li>\n</ol>\n\n\n\n<pre><code><Image>\n <Image.Source>\n <DrawingImage>\n <DrawingImage.Drawing>\n <DrawingGroup ... the output from step #2 ...>...</DrawingGroup>\n </DrawingImage.Drawing>\n </DrawingImage>\n </Image.Source>\n</Image>\n</code></pre>\n\n<ol start=\"4\">\n<li>Coordinate systems can be a pain if you want to be animating things. There are some other posts such as <a href=\"https://graphicdesign.stackexchange.com/questions/15401/change-viewbox-attribute-in-svg-exported-by-illustrator\">this</a> which may have insights.</li>\n</ol>\n"
},
{
"answer_id": 72294052,
"author": "Jan",
"author_id": 13241545,
"author_profile": "https://Stackoverflow.com/users/13241545",
"pm_score": 0,
"selected": false,
"text": "<p>The detour suggested by @ConcernedOfTunbridgeWells is starting to make sense now. Other solutions are not being maintained and do not work anymore.</p>\n<p>Hence, you can use this option as workaround:</p>\n<ol>\n<li>Save files as svg.</li>\n<li>Convert them to XAML using Inkscape.</li>\n</ol>\n<p>This solution even has the advantage of text will stay text and is not converted to a path.</p>\n<p><strong>How to convert many files?</strong></p>\n<p>Inkscape also supports a batch mode to convert many files at once. I took <a href=\"https://gist.github.com/JohannesDeml/779b29128cdd7f216ab5000466404f11\" rel=\"nofollow noreferrer\">a great script (by Johannes Deml)</a> for batch conversions on Windows that takes vectors files and converts them to various other formats using Inkscapes batch mode. I adapted it to convert to XAML, too.</p>\n<p>You can find the <a href=\"https://gist.github.com/SigurdJanson/ddccf14d41ecbd490fd9070dd1ec13d6\" rel=\"nofollow noreferrer\">script that includes XAML on Github</a>. Some <a href=\"https://gist.github.com/JohannesDeml/779b29128cdd7f216ab5000466404f11\" rel=\"nofollow noreferrer\">instructions on how to use the script are provided by the original author</a>.</p>\n"
}
] |
2008/09/30
|
[
"https://Stackoverflow.com/questions/153762",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3047/"
] |
Our graphics person uses Adobe Illustrator and we'd like to use her images inside our WPF application as paths. Is there a way to do this?
|
You can go from AI to SVG to XAML.
1. From Adobe Illustrator: File -> Save As -> \*.SVG.
* SVG "Profile 1.1" seems to be sufficient.
* Note that to preserve path/group names in XAML you should enable "Preserve Illustrator Editing Capabilities" (or at least as it's called in CS4).
2. [SharpVectors](https://sharpvectors.codeplex.com/) can convert SVG data to XAML data. This will produce a fragment of XAML with root `<DrawingGroup>`.
3. Do what you need to do to copy-paste and otherwise use the XAML, such as placing it into an Image like below. Named objects or groups in the AI file should still have their names in the XAML i.e. via `x:Name="..."`.
```
<Image>
<Image.Source>
<DrawingImage>
<DrawingImage.Drawing>
<DrawingGroup ... the output from step #2 ...>...</DrawingGroup>
</DrawingImage.Drawing>
</DrawingImage>
</Image.Source>
</Image>
```
4. Coordinate systems can be a pain if you want to be animating things. There are some other posts such as [this](https://graphicdesign.stackexchange.com/questions/15401/change-viewbox-attribute-in-svg-exported-by-illustrator) which may have insights.
|
153,769 |
<p>As in subject... is there a way of looking at an empty table schema without inserting any rows and issuing a SELECT?</p>
|
[
{
"answer_id": 153779,
"author": "Plasmer",
"author_id": 397314,
"author_profile": "https://Stackoverflow.com/users/397314",
"pm_score": 4,
"selected": true,
"text": "<p>Are you looking for <a href=\"http://publib.boulder.ibm.com/infocenter/db2luw/v8/index.jsp?topic=/com.ibm.db2.udb.doc/core/r0002019.htm\" rel=\"nofollow noreferrer\">DESCRIBE</a>?</p>\n\n<p><code>db2 describe table user1.department</code> </p>\n\n<pre><code>Table: USER1.DEPARTMENT\n\nColumn Type Type\nname schema name Length Scale Nulls\n------------------ ----------- ------------------ -------- -------- --------\nAREA SYSIBM SMALLINT 2 0 No\nDEPT SYSIBM CHARACTER 3 0 No\nDEPTNAME SYSIBM CHARACTER 20 0 Yes\n</code></pre>\n"
},
{
"answer_id": 154224,
"author": "Mike Wills",
"author_id": 2535,
"author_profile": "https://Stackoverflow.com/users/2535",
"pm_score": 1,
"selected": false,
"text": "<p>Looking at your <a href=\"https://stackoverflow.com/questions/153920/php-unixodbc-db2-describe-token-not-valid\">other question</a>, DESCRIBE may not work. I believe there is a system table that stores all of the field information.</p>\n\n<p>Perhaps <a href=\"http://www.code400.com/ffd.php\" rel=\"nofollow noreferrer\">this will help you out</a>. A bit more coding but far more accurate. </p>\n"
},
{
"answer_id": 5348256,
"author": "Amit",
"author_id": 665523,
"author_profile": "https://Stackoverflow.com/users/665523",
"pm_score": 3,
"selected": false,
"text": "<pre><code>SELECT * \nFROM SYSIBM.SYSCOLUMNS \nWHERE \nTBNAME = 'tablename'; \n</code></pre>\n"
},
{
"answer_id": 6833895,
"author": "brandon k",
"author_id": 168125,
"author_profile": "https://Stackoverflow.com/users/168125",
"pm_score": 3,
"selected": false,
"text": "<p>For DB2 AS/400 (V5R4 here) I used the following queries to examine for database / table / column metadata:</p>\n\n<p>SELECT * FROM SYSIBM.TABLES -- Provides all tables</p>\n\n<p>SELECT * FROM SYSIBM.VIEWS -- Provides all views and their source (!!) definition </p>\n\n<p>SELECT * FROM SYSIBM.COLUMNS -- Provides all columns, their data types & sizes, default values, etc.</p>\n\n<p>SELECT * FROM SYSIBM.SQLPRIMARYKEYS -- Provides a list of primary keys and their order</p>\n"
}
] |
2008/09/30
|
[
"https://Stackoverflow.com/questions/153769",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/8437/"
] |
As in subject... is there a way of looking at an empty table schema without inserting any rows and issuing a SELECT?
|
Are you looking for [DESCRIBE](http://publib.boulder.ibm.com/infocenter/db2luw/v8/index.jsp?topic=/com.ibm.db2.udb.doc/core/r0002019.htm)?
`db2 describe table user1.department`
```
Table: USER1.DEPARTMENT
Column Type Type
name schema name Length Scale Nulls
------------------ ----------- ------------------ -------- -------- --------
AREA SYSIBM SMALLINT 2 0 No
DEPT SYSIBM CHARACTER 3 0 No
DEPTNAME SYSIBM CHARACTER 20 0 Yes
```
|
153,776 |
<p>I am inside of...</p>
<pre><code>public class bgchange : IMapServerDropDownBoxAction
{
void IServerAction.ServerAction(ToolbarItemInfo info)
{
Some code...
</code></pre>
<p>and after "some code" I want to trigger</p>
<pre><code>[WebMethod]
public static void DoSome()
{
}
</code></pre>
<p>Which triggers some javascript. Is this possible?</p>
<p>Ok, switch methods here. I was able to call dosome(); which fired but did not trigger the javascript. I have tried to use the registerstartupscript method but don't fully understand how to implement it. Here's what I tried:</p>
<pre><code>public class bgchange : IMapServerDropDownBoxAction
{
void IServerAction.ServerAction(ToolbarItemInfo info)
{
...my C# code to perform on dropdown selection...
//now I want to trigger some javascript...
// Define the name and type of the client scripts on the page.
String csname1 = "PopupScript";
Type cstype = this.GetType();
// Get a ClientScriptManager reference from the Page class.
ClientScriptManager cs = Page.ClientScript;
// Check to see if the startup script is already registered.
if (!cs.IsStartupScriptRegistered(cstype, csname1))
{
String cstext1 = "alert('Hello World');";
cs.RegisterStartupScript(cstype, csname1, cstext1, true);
}
}
</code></pre>
<p>}</p>
<p>I got the registerstartupscript code from an msdn example. Clearly I am not implementing it correctly. Currently vs says "An object reference is required for the non-static field, method, or property 'System.Web.UI.Page.ClientScript.get' refering to the piece of code "Page.Clientscript;" Thanks.</p>
|
[
{
"answer_id": 153847,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 1,
"selected": false,
"text": "<p>hmmm... the question changed dramatically since my original answer.</p>\n\n<p>Now I think the answer is no. But I might be wrong.</p>\n"
},
{
"answer_id": 153873,
"author": "Scott Nichols",
"author_id": 4299,
"author_profile": "https://Stackoverflow.com/users/4299",
"pm_score": 3,
"selected": true,
"text": "<p>I'm not sure I fully understand the sequence of what you are trying to do, what's client-side and what's not....</p>\n\n<p>However, you could add a Start-up javascript method to the page which would then call the WebMethod. When calling a WebMethod via javascript, you can add a call-back function, which would then be called when the WebMethod returns.</p>\n\n<p>If you add a ScriptManager tag on your page, you can call WebMethods defined in the page via Javascript. </p>\n\n<pre><code><asp:ScriptManager ID=\"scriptManager1\" \n runat=\"server\" EnablePageMethods=\"true\" />\n</code></pre>\n\n<p>From the Page_Load function you can add a call to your WebMethod..</p>\n\n<pre><code>Page.ClientScript.RegisterStartupScript(\n this.GetType(), \n \"callDoSome\",\n \"PageMethods.DoSome(Callback_Function, null)\", \n true);\n</code></pre>\n\n<p>Callback_Function represents a javascript function that will be executed after the WebMethod is called... </p>\n\n<pre><code><script language=\"javascript\" type=\"text/javascript\">\n function Callback_Function(result, context) {\n alert('WebMethod was called');\n }\n</script>\n</code></pre>\n\n<p><b>EDIT:</b></p>\n\n<p>Found this link for <a href=\"http://edndoc.esri.com/arcobjects/9.2/NET_Server_Doc/developer/ADF/custom_tools_commands.htm\" rel=\"nofollow noreferrer\">Web ADF controls</a>. Is this what you are using??</p>\n\n<p>From that page, it looks like something like this will do a javascript callback.</p>\n\n<pre><code>public void ServerAction(ToolbarItemInfo info) {\n string jsfunction = \"alert('Hello');\";\n Map mapctrl = (Map)info.BuddyControls[0];\n CallbackResult cr = new CallbackResult(null, null, \"javascript\", jsfunction);\n mapctrl.CallbackResults.Add(cr);\n}\n</code></pre>\n"
},
{
"answer_id": 153876,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 2,
"selected": false,
"text": "<p>You cannot call methods within a browser directly from the server. You can, however, add javascript functions to the response that will execute methods within the browser.</p>\n\n<p>Within the ServerAction method, do the following</p>\n\n<pre><code>string script = \"<script language='javascript'>\\n\";\nscript += \"javascriptFunctionHere();\\n\";\nscript += \"</script>\";\n\nPage.RegisterStartupScript(\"ForceClientToCallServerMethod\", script);\n</code></pre>\n\n<p><a href=\"http://msdn.microsoft.com/en-us/library/system.web.ui.page.registerstartupscript.aspx\" rel=\"nofollow noreferrer\">More info here</a></p>\n"
},
{
"answer_id": 154022,
"author": "Scott Nichols",
"author_id": 4299,
"author_profile": "https://Stackoverflow.com/users/4299",
"pm_score": 2,
"selected": false,
"text": "<p>If the above is how you are calling RegisterStartupScript, it won't work because you don't have a reference to the \"Page\" object. </p>\n\n<p>bgchange in your example extends Object (assuming IMapServerDropDownBoxAction is an interface), which means that there is no Page instance for you to reference.</p>\n\n<p>This you did the exact same thing from a Asp.Net Page or UserControl, it would work, because Page would be a valid reference.</p>\n\n<pre><code>public partial class _Default : System.Web.UI.Page\n{\n protected void Page_Load(object sender, EventArgs e)\n {\n Page.ClientScript.RegisterStartupScript(\n this.GetType(),\n \"helloworldpopup\",\n \"alert('hello world');\",\n true); \n }\n}\n</code></pre>\n"
}
] |
2008/09/30
|
[
"https://Stackoverflow.com/questions/153776",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5234/"
] |
I am inside of...
```
public class bgchange : IMapServerDropDownBoxAction
{
void IServerAction.ServerAction(ToolbarItemInfo info)
{
Some code...
```
and after "some code" I want to trigger
```
[WebMethod]
public static void DoSome()
{
}
```
Which triggers some javascript. Is this possible?
Ok, switch methods here. I was able to call dosome(); which fired but did not trigger the javascript. I have tried to use the registerstartupscript method but don't fully understand how to implement it. Here's what I tried:
```
public class bgchange : IMapServerDropDownBoxAction
{
void IServerAction.ServerAction(ToolbarItemInfo info)
{
...my C# code to perform on dropdown selection...
//now I want to trigger some javascript...
// Define the name and type of the client scripts on the page.
String csname1 = "PopupScript";
Type cstype = this.GetType();
// Get a ClientScriptManager reference from the Page class.
ClientScriptManager cs = Page.ClientScript;
// Check to see if the startup script is already registered.
if (!cs.IsStartupScriptRegistered(cstype, csname1))
{
String cstext1 = "alert('Hello World');";
cs.RegisterStartupScript(cstype, csname1, cstext1, true);
}
}
```
}
I got the registerstartupscript code from an msdn example. Clearly I am not implementing it correctly. Currently vs says "An object reference is required for the non-static field, method, or property 'System.Web.UI.Page.ClientScript.get' refering to the piece of code "Page.Clientscript;" Thanks.
|
I'm not sure I fully understand the sequence of what you are trying to do, what's client-side and what's not....
However, you could add a Start-up javascript method to the page which would then call the WebMethod. When calling a WebMethod via javascript, you can add a call-back function, which would then be called when the WebMethod returns.
If you add a ScriptManager tag on your page, you can call WebMethods defined in the page via Javascript.
```
<asp:ScriptManager ID="scriptManager1"
runat="server" EnablePageMethods="true" />
```
From the Page\_Load function you can add a call to your WebMethod..
```
Page.ClientScript.RegisterStartupScript(
this.GetType(),
"callDoSome",
"PageMethods.DoSome(Callback_Function, null)",
true);
```
Callback\_Function represents a javascript function that will be executed after the WebMethod is called...
```
<script language="javascript" type="text/javascript">
function Callback_Function(result, context) {
alert('WebMethod was called');
}
</script>
```
**EDIT:**
Found this link for [Web ADF controls](http://edndoc.esri.com/arcobjects/9.2/NET_Server_Doc/developer/ADF/custom_tools_commands.htm). Is this what you are using??
From that page, it looks like something like this will do a javascript callback.
```
public void ServerAction(ToolbarItemInfo info) {
string jsfunction = "alert('Hello');";
Map mapctrl = (Map)info.BuddyControls[0];
CallbackResult cr = new CallbackResult(null, null, "javascript", jsfunction);
mapctrl.CallbackResults.Add(cr);
}
```
|
153,782 |
<p>I am using a codebehind page in ASP.NET to perform a SQL query. The query is loaded into a string, the connection is established (To Oracle), and we get it started by having the connection perform .ExecuteReader into a OleDBDataReader (We'll call it DataRead). I'll try to hammer out an example below. (Consider Drop as an ASP DropDownList control)</p>
<pre><code>Dim LookFor as String = "Fuzzy Bunnies"
While DataRead.Read
If LookFor = DataRead.Item("Kinds of Bunnies") Then
'Meets special critera, do secondary function'
Drop.Items.Add(DataRead.Item("Subgroup of Bunnies"))
...
End if
...
End While
</code></pre>
<p>This is the only way I know of doing a dynamic add to a DropDownList. However, each item in a DropDownList has a .text property and a .value property. How can we define the .value as being different from the .text in code?</p>
|
[
{
"answer_id": 153788,
"author": "John Sheehan",
"author_id": 1786,
"author_profile": "https://Stackoverflow.com/users/1786",
"pm_score": 1,
"selected": false,
"text": "<p>Pardon my possibly faulty VB</p>\n\n<pre><code>Dim item as New ListItem()\nitem.Value = \"foo\"\nitem.Text = \"bar\"\n\nDrop.Items.Add(item)\n</code></pre>\n\n<p>You can also use the ListItem constructor (e.g. new ListItem(\"text\", \"value\"))</p>\n"
},
{
"answer_id": 153792,
"author": "AaronSieb",
"author_id": 16911,
"author_profile": "https://Stackoverflow.com/users/16911",
"pm_score": 2,
"selected": false,
"text": "<p>Add should have an overload that accepts a ListItem object. Using that, you can usually do something like this:</p>\n\n<pre><code>\nDrop.Items.Add(New ListItem(\"Text\", \"Value\"))\n</code></pre>\n"
},
{
"answer_id": 153794,
"author": "bdukes",
"author_id": 2688,
"author_profile": "https://Stackoverflow.com/users/2688",
"pm_score": 4,
"selected": true,
"text": "<p>The <a href=\"http://msdn.microsoft.com/en-us/library/system.web.ui.webcontrols.listitemcollection.add.aspx\" rel=\"nofollow noreferrer\">Add</a> function can take a <a href=\"http://msdn.microsoft.com/en-us/library/system.web.ui.webcontrols.listitem.aspx\" rel=\"nofollow noreferrer\">ListItem</a>, so you can do</p>\n\n<pre><code>Dim li as new ListItem(DataRead.Item(\"Subgroup of Bunnies\"), \"myValue\")\nDrop.Items.Add(li)\n</code></pre>\n"
},
{
"answer_id": 153798,
"author": "Stephen Wrighton",
"author_id": 7516,
"author_profile": "https://Stackoverflow.com/users/7516",
"pm_score": 0,
"selected": false,
"text": "<p>you'd select a second column into your datareader (such as an IDENTITY field) and then assign do your Item generation like this:</p>\n\n<pre><code>Dim item as new listitem\nitem.text = DataRead.Item(\"SubGroup Of Bunnies\")\nitem.value = DataRead.Item(\"ID\")\nDrop.Items.Add(item)\n</code></pre>\n\n<p>You may also want to look into the DATABIND functionality, and filtering out \"FUZZY BUNNIES\" in the SQL statement itself.</p>\n"
},
{
"answer_id": 153800,
"author": "Grank",
"author_id": 12975,
"author_profile": "https://Stackoverflow.com/users/12975",
"pm_score": 2,
"selected": false,
"text": "<p>If I understand the question, Items.Add has an overload that takes a ListItem, so you could create a new ListItem object in that line:</p>\n\n<pre><code>Drop.Items.Add(new ListItem(\"text\", \"value\"))\n</code></pre>\n"
}
] |
2008/09/30
|
[
"https://Stackoverflow.com/questions/153782",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/12545/"
] |
I am using a codebehind page in ASP.NET to perform a SQL query. The query is loaded into a string, the connection is established (To Oracle), and we get it started by having the connection perform .ExecuteReader into a OleDBDataReader (We'll call it DataRead). I'll try to hammer out an example below. (Consider Drop as an ASP DropDownList control)
```
Dim LookFor as String = "Fuzzy Bunnies"
While DataRead.Read
If LookFor = DataRead.Item("Kinds of Bunnies") Then
'Meets special critera, do secondary function'
Drop.Items.Add(DataRead.Item("Subgroup of Bunnies"))
...
End if
...
End While
```
This is the only way I know of doing a dynamic add to a DropDownList. However, each item in a DropDownList has a .text property and a .value property. How can we define the .value as being different from the .text in code?
|
The [Add](http://msdn.microsoft.com/en-us/library/system.web.ui.webcontrols.listitemcollection.add.aspx) function can take a [ListItem](http://msdn.microsoft.com/en-us/library/system.web.ui.webcontrols.listitem.aspx), so you can do
```
Dim li as new ListItem(DataRead.Item("Subgroup of Bunnies"), "myValue")
Drop.Items.Add(li)
```
|
153,796 |
<p>I'm trying to loop through all the controls on a sharepoint page, for the purposes of testing i just want to output the control ID</p>
<p>this is the code i'm using</p>
<p>Public Shared Sub SubstituteValues3(ByVal CurrentPage As Page, ByRef s As StringBuilder)</p>
<pre><code> 'Page()
'- MasterPage
'- HtmlForm
'- ContentPlaceHolder
'- The TextBoxes, etc.
For Each ctlMaster As Control In CurrentPage.Controls
If TypeOf ctlMaster Is MasterPage Then
HttpContext.Current.Response.Output.Write("Master Page <br/>")
For Each ctlForm As Control In ctlMaster.Controls
If TypeOf ctlForm Is HtmlForm Then
HttpContext.Current.Response.Output.Write("HTML Form <br/>")
For Each ctlContent As Control In ctlForm.Controls
If TypeOf ctlContent Is ContentPlaceHolder Then
HttpContext.Current.Response.Output.Write("Content Placeholder <br/>")
For Each ctlChild As Control In ctlContent.Controls
HttpContext.Current.Response.Output.Write(ctlChild.ID.ToString & "<br />")
Next
End If
Next
End If
Next
End If
Next
HttpContext.Current.Response.Output.Write("--------------")
HttpContext.Current.Response.End()
</code></pre>
<p>however it's not getting past the 'MasterPage' output.</p>
<p>I would expect to see the names of all the controls i have inside my content placeholder but i find it all a bit confusing.</p>
|
[
{
"answer_id": 155868,
"author": "Aaron Powell",
"author_id": 11388,
"author_profile": "https://Stackoverflow.com/users/11388",
"pm_score": 0,
"selected": false,
"text": "<p>A MasterPage isn't a control of the current page, it's a property of it, in <strong>Page.MasterPage</strong></p>\n"
},
{
"answer_id": 160539,
"author": "Cruiser",
"author_id": 16971,
"author_profile": "https://Stackoverflow.com/users/16971",
"pm_score": 1,
"selected": false,
"text": "<p>Start with Page.Master.Controls</p>\n\n<p>From there what you have should basically work</p>\n\n<pre><code> For Each ctlForm As Control In Page.Master.Controls\n\n If TypeOf ctlForm Is HtmlForm Then\n HttpContext.Current.Response.Output.Write(\"HTML Form <br/>\")\n\n For Each ctlContent As Control In ctlForm.Controls\n If TypeOf ctlContent Is ContentPlaceHolder Then\n HttpContext.Current.Response.Output.Write(\"Content Placeholder <br/>\")\n\n For Each ctlChild As Control In ctlContent.Controls\n HttpContext.Current.Response.Output.Write(ctlChild.ID.ToString & \"<br />\")\n Next\n End If\n Next\n End If\n Next\n</code></pre>\n"
},
{
"answer_id": 161489,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 0,
"selected": false,
"text": "<p>i found this piece of code which seems list the controls I need, i think it's more of a hack though.</p>\n\n<pre><code>For i = 0 To CurrentPage.Request.Form.AllKeys.Length - 1\n If CurrentPage.Request.Form.GetKey(i).Contains(\"ctl00$PlaceHolderMain$\") Then\n\n\n Dim key As String = CurrentPage.Request.Form.GetKey(i).Substring(22)\n Dim keyText As String = String.Format(\"[{0}]\", key)\n\n HttpContext.Current.Response.Output.Write(keyText & \"<br/>\")\n\n 'Text.Replace(keyText, CurrentPage.Request.Form(\"ctl00$PlaceHolderMain$\" & key))\n End If\n Next\n</code></pre>\n"
},
{
"answer_id": 215061,
"author": "naspinski",
"author_id": 14777,
"author_profile": "https://Stackoverflow.com/users/14777",
"pm_score": 0,
"selected": false,
"text": "<p>you can do this simply with recursion, not efficent, but it is simple... try this method:\npublic void getControls(Control input)</p>\n\n<pre><code>{\n foreach (Control c in input.Controls)\n {\n Response.Write(c.GetType().ToString() + \" - \" + c.ID + \"<br />\");\n getControls(c);\n }\n}\n</code></pre>\n\n<p>And call it like this:</p>\n\n<pre><code>getControls(Page);\n</code></pre>\n\n<p>That will cycle trough all controls on your page and output the <strong>type - ID</strong> of them and print it out to the top of the page... you could also use the code to construct a list or whatever you want to do.</p>\n"
}
] |
2008/09/30
|
[
"https://Stackoverflow.com/questions/153796",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] |
I'm trying to loop through all the controls on a sharepoint page, for the purposes of testing i just want to output the control ID
this is the code i'm using
Public Shared Sub SubstituteValues3(ByVal CurrentPage As Page, ByRef s As StringBuilder)
```
'Page()
'- MasterPage
'- HtmlForm
'- ContentPlaceHolder
'- The TextBoxes, etc.
For Each ctlMaster As Control In CurrentPage.Controls
If TypeOf ctlMaster Is MasterPage Then
HttpContext.Current.Response.Output.Write("Master Page <br/>")
For Each ctlForm As Control In ctlMaster.Controls
If TypeOf ctlForm Is HtmlForm Then
HttpContext.Current.Response.Output.Write("HTML Form <br/>")
For Each ctlContent As Control In ctlForm.Controls
If TypeOf ctlContent Is ContentPlaceHolder Then
HttpContext.Current.Response.Output.Write("Content Placeholder <br/>")
For Each ctlChild As Control In ctlContent.Controls
HttpContext.Current.Response.Output.Write(ctlChild.ID.ToString & "<br />")
Next
End If
Next
End If
Next
End If
Next
HttpContext.Current.Response.Output.Write("--------------")
HttpContext.Current.Response.End()
```
however it's not getting past the 'MasterPage' output.
I would expect to see the names of all the controls i have inside my content placeholder but i find it all a bit confusing.
|
Start with Page.Master.Controls
From there what you have should basically work
```
For Each ctlForm As Control In Page.Master.Controls
If TypeOf ctlForm Is HtmlForm Then
HttpContext.Current.Response.Output.Write("HTML Form <br/>")
For Each ctlContent As Control In ctlForm.Controls
If TypeOf ctlContent Is ContentPlaceHolder Then
HttpContext.Current.Response.Output.Write("Content Placeholder <br/>")
For Each ctlChild As Control In ctlContent.Controls
HttpContext.Current.Response.Output.Write(ctlChild.ID.ToString & "<br />")
Next
End If
Next
End If
Next
```
|
153,801 |
<p>I've got a script that takes a user uploaded RTF document and merges in some person data into the letter (name, address, etc), and does this for multiple people. I merge the letter contents, then combine that with the next merge letter contents, for all people records.</p>
<p>Affectively I'm combining a single RTF document into itself for as many people records to which I need to merge the letter. However, I need to first remove the closing RTF markup and opening of the RTF markup of each merge or else the RTF won't render correctly. This sounds like a job for regular expressions.</p>
<p>Essentially I need a regex that will remove the entire string:</p>
<p>}\n\page ANYTHING \par</p>
<p>Example, this regex would match this:</p>
<pre><code>crap
}
\page{\rtf1\ansi\ansicpg1252\deff0\deflang1033{\fonttbl{\f0\fswiss\fcharset0 Arial;}}
{\*\generator Msftedit 5.41.15.1515;}\viewkind4\uc1\pard\f0\fs20 September 30, 2008\par
more crap
</code></pre>
<p>So I could make it just:</p>
<pre><code>crap
\page
more crap
</code></pre>
<p>Is RegEx the best approach here?</p>
<p>UPDATE: Why do I have to use RTF?</p>
<p>I want to enable the user to upload a form letter that the system will then use to create the merged letters. Since RTF is plain text, I can do this pretty easily in code. I know, RTF is a disaster of a spec, but I don't know any other good alternative.</p>
|
[
{
"answer_id": 155094,
"author": "Randy",
"author_id": 9361,
"author_profile": "https://Stackoverflow.com/users/9361",
"pm_score": 3,
"selected": true,
"text": "<p>I would question the use of RTF in this case. It's not entirely clear to me what you're trying to do overall, so I can't necessarily suggest anything better, but if you can try to explain your project more broadly, maybe I can help.</p>\n\n<p>If this is really the way you want to go though, this regex gave me the correct output given your input:</p>\n\n<pre><code>$output = preg_replace(\"/}\\s?\\n\\\\\\\\page.*?\\\\\\\\par\\s?\\n/ms\", \"\\\\page\\n\", $input);\n</code></pre>\n"
},
{
"answer_id": 155130,
"author": "Edward Z. Yang",
"author_id": 23845,
"author_profile": "https://Stackoverflow.com/users/23845",
"pm_score": 1,
"selected": false,
"text": "<p>To this I can say ick ick ick. Nevertheless, rcar's cludge probably will work, barring some weird edge-case where RTF doesn't actually end in that form, or the document-wide styles include important information that utterly messes up the formatting, or any other of the many failure modes.</p>\n"
}
] |
2008/09/30
|
[
"https://Stackoverflow.com/questions/153801",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/43/"
] |
I've got a script that takes a user uploaded RTF document and merges in some person data into the letter (name, address, etc), and does this for multiple people. I merge the letter contents, then combine that with the next merge letter contents, for all people records.
Affectively I'm combining a single RTF document into itself for as many people records to which I need to merge the letter. However, I need to first remove the closing RTF markup and opening of the RTF markup of each merge or else the RTF won't render correctly. This sounds like a job for regular expressions.
Essentially I need a regex that will remove the entire string:
}\n\page ANYTHING \par
Example, this regex would match this:
```
crap
}
\page{\rtf1\ansi\ansicpg1252\deff0\deflang1033{\fonttbl{\f0\fswiss\fcharset0 Arial;}}
{\*\generator Msftedit 5.41.15.1515;}\viewkind4\uc1\pard\f0\fs20 September 30, 2008\par
more crap
```
So I could make it just:
```
crap
\page
more crap
```
Is RegEx the best approach here?
UPDATE: Why do I have to use RTF?
I want to enable the user to upload a form letter that the system will then use to create the merged letters. Since RTF is plain text, I can do this pretty easily in code. I know, RTF is a disaster of a spec, but I don't know any other good alternative.
|
I would question the use of RTF in this case. It's not entirely clear to me what you're trying to do overall, so I can't necessarily suggest anything better, but if you can try to explain your project more broadly, maybe I can help.
If this is really the way you want to go though, this regex gave me the correct output given your input:
```
$output = preg_replace("/}\s?\n\\\\page.*?\\\\par\s?\n/ms", "\\page\n", $input);
```
|
153,815 |
<p>I am coming from the SQL server world where we had uniqueidentifier. Is there an equivalent in oracle? This column will be frequently queried so performance is the key.</p>
<p>I am generating the GUID in .Net and will be passing it to Oracle. For a couple reasons it cannot be generated by oracle so I cannot use sequence. </p>
|
[
{
"answer_id": 153836,
"author": "MusiGenesis",
"author_id": 14606,
"author_profile": "https://Stackoverflow.com/users/14606",
"pm_score": 1,
"selected": false,
"text": "<p>There is no uniqueidentifier in Oracle.</p>\n\n<p>You can implement one yourself by using RAW (kind of a pain) or CHAR. Performance on queries that JOIN on a CHAR field will suffer (maybe as much as 40%) in comparison with using an integer.</p>\n\n<p>If you're doing distributed/replicated databases, the performance hit is worth it. Otherwise, just use an integer.</p>\n"
},
{
"answer_id": 153837,
"author": "dacracot",
"author_id": 13930,
"author_profile": "https://Stackoverflow.com/users/13930",
"pm_score": 0,
"selected": false,
"text": "<p>The general practice using Oracle is to create an artificial key. This is a column defined as a number. It is populated via a sequence. It is indexed/constrained via a primary key definition.</p>\n"
},
{
"answer_id": 153849,
"author": "Turnkey",
"author_id": 13144,
"author_profile": "https://Stackoverflow.com/users/13144",
"pm_score": 7,
"selected": true,
"text": "<pre><code>CREATE table test (testguid RAW(16) default SYS_GUID() ) \n</code></pre>\n\n<p><a href=\"http://preferisco.blogspot.com/2007/02/unique-ids-for-multi-master-replication.html\" rel=\"noreferrer\">This blog</a> studied the relative performance.</p>\n"
},
{
"answer_id": 153851,
"author": "hamishmcn",
"author_id": 3590,
"author_profile": "https://Stackoverflow.com/users/3590",
"pm_score": 2,
"selected": false,
"text": "<p>If I understand the question properly, you want to generate a unique id when you insert a row in the db.<br>\nYou could use a <em>sequence</em> to do this. <a href=\"http://download.oracle.com/docs/cd/B28359_01/server.111/b28310/views002.htm\" rel=\"nofollow noreferrer\">link here</a><br>\nOnce you have created your sequence you can use it like this:</p>\n\n<pre><code>INSERT INTO mytable (col1, col2) VALUES (myseq.NEXTVAL, 'some other data');\n</code></pre>\n"
},
{
"answer_id": 175840,
"author": "Osama Al-Maadeed",
"author_id": 25544,
"author_profile": "https://Stackoverflow.com/users/25544",
"pm_score": 2,
"selected": false,
"text": "<p>GUIDs are not as used in Oracle as in MSSQL, we tend to have a NUMBER field (not null & primary key) , a sequence, and a trigger on insert to populate it (for every table).</p>\n"
},
{
"answer_id": 1534261,
"author": "Erik Anderson",
"author_id": 130614,
"author_profile": "https://Stackoverflow.com/users/130614",
"pm_score": 3,
"selected": false,
"text": "<p>As others have stated, there is a performance hit using GUIDs compared to numeric sequences. That said, there is a function named "<a href=\"http://download.oracle.com/docs/cd/B14117_01/server.101/b10759/functions153.htm\" rel=\"nofollow noreferrer\">SYS_GUID()</a>" available since Oracle 8i that provides the raw equivalent:</p>\n<pre><code>SQL> SELECT SYS_GUID() FROM DUAL;\n\nSYS_GUID()\n--------------------------------\n248AACE7F7DE424E8B9E1F31A9F101D5\n</code></pre>\n<p>A function could be created to return a formatted GUID:</p>\n<pre><code>CREATE OR REPLACE FUNCTION GET_FORMATTED_GUID RETURN VARCHAR2 IS guid VARCHAR2(38) ;\nBEGIN\n SELECT SYS_GUID() INTO guid FROM DUAL ;\n \n guid :=\n '{' || SUBSTR(guid, 1, 8) ||\n '-' || SUBSTR(guid, 9, 4) ||\n '-' || SUBSTR(guid, 13, 4) ||\n '-' || SUBSTR(guid, 17, 4) ||\n '-' || SUBSTR(guid, 21) || '}' ;\n\n RETURN guid ;\nEND GET_FORMATTED_GUID ;\n/\n</code></pre>\n<p>Thus returning an interchangeable string:</p>\n<pre><code>SQL> SELECT GET_FORMATTED_GUID() FROM DUAL ;\n\nGET_FORMATTED_GUID()\n--------------------------------------\n{15417950-9197-4ADD-BD49-BA043F262180}\n</code></pre>\n<p>A note of caution should be made that some Oracle platforms return similar but still unique values of GUIDs <a href=\"http://feuerthoughts.blogspot.com/2006/02/watch-out-for-sequential-oracle-guids.html\" rel=\"nofollow noreferrer\">as noted</a> by Steven Feuerstein.</p>\n<p><strong>Update 11/3/2020</strong>: With 10g, Oracle added support for regular expression functions which means the concatenation can be simplified using the <code>REGEXP_REPLACE()</code> function.</p>\n<pre><code>REGEXP_REPLACE(\n SYS_GUID(),\n '([0-9A-F]{8})([0-9A-F]{4})([0-9A-F]{4})([0-9A-F]{4})([0-9A-F]{12})',\n '{\\1-\\2-\\3-\\4-\\5}'\n)\n</code></pre>\n<p>The expression breaks out the string value returned by <code>SYS_GUID()</code> into 5 groups of hexadecimal values and rebuilds it, inserting a "-" between each group.</p>\n"
},
{
"answer_id": 9474253,
"author": "stolsvik",
"author_id": 39334,
"author_profile": "https://Stackoverflow.com/users/39334",
"pm_score": 2,
"selected": false,
"text": "<p>RAW(16) is apparently the preferred equivalent for the uniqueidentifier MS SQL type.</p>\n"
}
] |
2008/09/30
|
[
"https://Stackoverflow.com/questions/153815",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1514/"
] |
I am coming from the SQL server world where we had uniqueidentifier. Is there an equivalent in oracle? This column will be frequently queried so performance is the key.
I am generating the GUID in .Net and will be passing it to Oracle. For a couple reasons it cannot be generated by oracle so I cannot use sequence.
|
```
CREATE table test (testguid RAW(16) default SYS_GUID() )
```
[This blog](http://preferisco.blogspot.com/2007/02/unique-ids-for-multi-master-replication.html) studied the relative performance.
|
153,825 |
<p>I've got the following query to determine how many votes a story has received:</p>
<pre><code>SELECT s_id, s_title, s_time, (s_time-now()) AS s_timediff,
(
(SELECT COUNT(*) FROM s_ups WHERE stories.q_id=s_ups.s_id) -
(SELECT COUNT(*) FROM s_downs WHERE stories.s_id=s_downs.s_id)
) AS votes
FROM stories
</code></pre>
<p>I'd like to apply the following mathematical function to it for upcoming stories (I think it's what reddit uses) -
<a href="http://redflavor.com/reddit.cf.algorithm.png" rel="noreferrer">http://redflavor.com/reddit.cf.algorithm.png</a></p>
<p>I can perform the function on the application side (which I'm doing now), but I can't sort it by the ranking which the function provides.</p>
<p>Any advise?</p>
|
[
{
"answer_id": 154094,
"author": "J.J.",
"author_id": 21204,
"author_profile": "https://Stackoverflow.com/users/21204",
"pm_score": 2,
"selected": false,
"text": "<p>y and z are the tricky ones. You want a specific return based on x's value. That sounds like a good reason to make a function.</p>\n\n<p><a href=\"http://dev.mysql.com/doc/refman/5.0/en/if-statement.html\" rel=\"nofollow noreferrer\">http://dev.mysql.com/doc/refman/5.0/en/if-statement.html</a></p>\n\n<p>You should make 1 function for y and one for z. pass in x, and expect a number back out.</p>\n\n<pre><code>DELIMINATOR //\n\nCREATE FUNCTION y_element(x INT) \n RETURNS INT\n\nBEGIN\n DECLARE y INT;\n\nIF x > 0 SET y = 1;\nELSEIF x = 0 SET y = 0;\nELSEIF x < 0 SET y = -1;\nEND IF;\n\nRETURN y;\n\nEND //;\n\nDELIMINATOR;\n</code></pre>\n\n<p>There is y. I did it by hand without checking so you may have to fix a few typo's.\nDo z the same way, and then you have all of the values for your final function.</p>\n"
},
{
"answer_id": 155645,
"author": "Jonathan",
"author_id": 19272,
"author_profile": "https://Stackoverflow.com/users/19272",
"pm_score": 3,
"selected": true,
"text": "<p>Try this:</p>\n\n<pre><code> SELECT s_id, s_title, log10(Z) + (Y * s_timediff)/45000 AS redditfunction \n FROM (\n SELECT stories.s_id, stories.s_title, stories.s_time, \n stories.s_time - now() AS s_timediff, \n count(s_ups.s_id) - count(s_downs.s_id) as X, \n if(X>0,1,if(x<0,-1,0)) as Y, \n if(abs(x)>=1,abs(x),1) as Z\n FROM stories \n LEFT JOIN s_ups ON stories.q_id=s_ups.s_id\n LEFT JOIN s_downs ON stories.s_id=s_downs.s_id\n GROUP BY stories.s_id\n ) as derived_table1\n</code></pre>\n\n<p>You might need to check this statement if it works with your datasets.</p>\n"
}
] |
2008/09/30
|
[
"https://Stackoverflow.com/questions/153825",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] |
I've got the following query to determine how many votes a story has received:
```
SELECT s_id, s_title, s_time, (s_time-now()) AS s_timediff,
(
(SELECT COUNT(*) FROM s_ups WHERE stories.q_id=s_ups.s_id) -
(SELECT COUNT(*) FROM s_downs WHERE stories.s_id=s_downs.s_id)
) AS votes
FROM stories
```
I'd like to apply the following mathematical function to it for upcoming stories (I think it's what reddit uses) -
<http://redflavor.com/reddit.cf.algorithm.png>
I can perform the function on the application side (which I'm doing now), but I can't sort it by the ranking which the function provides.
Any advise?
|
Try this:
```
SELECT s_id, s_title, log10(Z) + (Y * s_timediff)/45000 AS redditfunction
FROM (
SELECT stories.s_id, stories.s_title, stories.s_time,
stories.s_time - now() AS s_timediff,
count(s_ups.s_id) - count(s_downs.s_id) as X,
if(X>0,1,if(x<0,-1,0)) as Y,
if(abs(x)>=1,abs(x),1) as Z
FROM stories
LEFT JOIN s_ups ON stories.q_id=s_ups.s_id
LEFT JOIN s_downs ON stories.s_id=s_downs.s_id
GROUP BY stories.s_id
) as derived_table1
```
You might need to check this statement if it works with your datasets.
|
153,835 |
<p>When I want to validate my XML docuemnts against a schema in my server-side Java, I use the built-in JRE Xerces implementation and javax.xml.validation.Schema. It works fine, but when validation fails, Xerces gives error messages that are very close to useless, for example:</p>
<pre><code>cvc-minLength-valid: Value '' with length = '0' is not facet-valid with respect to minLength '1' for type 'PopulatedStringType'
</code></pre>
<p>These can take an age to diagnose and track down to the particular part of the XML document that fails validation, and all because of a poor error message.</p>
<p>So my question is, do you use an alternative means of validating XML against Schema, that gives a more useful output on validation failure? </p>
<p>Please not that this is server-side Java, so please don't say "use XML Spy" or similar.</p>
|
[
{
"answer_id": 153891,
"author": "dacracot",
"author_id": 13930,
"author_profile": "https://Stackoverflow.com/users/13930",
"pm_score": 0,
"selected": false,
"text": "<p>We use <a href=\"http://www.oracle.com/technology/tech/xml/xdkhome.html\" rel=\"nofollow noreferrer\">Oracle's XDK (XML Development Kit)</a> which includes xmlparserv2.jar with a validating parser and XSLT 2.0. It uses the JAXB API so you should only have to add it to your classpath and change your imports. It throws errors that aren't perfect, but I would say more easily understood than your example.</p>\n"
},
{
"answer_id": 153968,
"author": "anjanb",
"author_id": 11142,
"author_profile": "https://Stackoverflow.com/users/11142",
"pm_score": 0,
"selected": false,
"text": "<p>xmlstarlet(xmlstar.sourceforge.net/) is a command line toolkit. you could run it using Runtime.exec() for a given xml (as long as the xml is in a file).</p>\n"
},
{
"answer_id": 162968,
"author": "Paul Croarkin",
"author_id": 18995,
"author_profile": "https://Stackoverflow.com/users/18995",
"pm_score": 0,
"selected": false,
"text": "<p>We use <a href=\"http://www.castor.org\" rel=\"nofollow noreferrer\">Castor</a>.</p>\n\n<blockquote>\n <p>Castor is an Open Source data binding framework for Java[tm]. It's the shortest path between Java objects, XML documents and relational tables. Castor provides Java-to-XML binding, Java-to-SQL persistence, and more.</p>\n</blockquote>\n"
},
{
"answer_id": 169475,
"author": "Damien B",
"author_id": 3069,
"author_profile": "https://Stackoverflow.com/users/3069",
"pm_score": 3,
"selected": true,
"text": "<p>In your handler for the validation, you should receive a SAXParseException with that message, as well as the <a href=\"http://xerces.apache.org/xerces2-j/javadocs/api/org/xml/sax/SAXParseException.html#method_summary\" rel=\"nofollow noreferrer\">column number and the line number</a> in the XML file. Isnt't it the case? </p>\n"
},
{
"answer_id": 930899,
"author": "Mads Hansen",
"author_id": 14419,
"author_profile": "https://Stackoverflow.com/users/14419",
"pm_score": 0,
"selected": false,
"text": "<p>If you are having trouble interpreting the Xerces errors and would like something that helps to highlight where in your document you have violated the rules, check out some of the XML authoring tools such as <a href=\"http://www.oxygenxml.com/validation.html\" rel=\"nofollow noreferrer\">oXygen</a>.</p>\n\n<p><a href=\"https://i.stack.imgur.com/peeVR.gif\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/peeVR.gif\" alt=\"alt text\"></a><br>\n<sub>(source: <a href=\"http://www.oxygenxml.com/img/errorsOverviewRuler.gif\" rel=\"nofollow noreferrer\">oxygenxml.com</a>)</sub> </p>\n\n<p>Once you associate the schema with your instance XML document the editor will highlight the offending area of the document and provide you with a description of the violation.</p>\n\n<p>Plus, you can use different engines to perform the validation: </p>\n\n<blockquote>\n <p>oXygen has built-in support for:\n Xerces, LIBXML, XSV, Saxon SA,\n MSXML4.0, MSXML .NET and SQC.</p>\n</blockquote>\n"
}
] |
2008/09/30
|
[
"https://Stackoverflow.com/questions/153835",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/21234/"
] |
When I want to validate my XML docuemnts against a schema in my server-side Java, I use the built-in JRE Xerces implementation and javax.xml.validation.Schema. It works fine, but when validation fails, Xerces gives error messages that are very close to useless, for example:
```
cvc-minLength-valid: Value '' with length = '0' is not facet-valid with respect to minLength '1' for type 'PopulatedStringType'
```
These can take an age to diagnose and track down to the particular part of the XML document that fails validation, and all because of a poor error message.
So my question is, do you use an alternative means of validating XML against Schema, that gives a more useful output on validation failure?
Please not that this is server-side Java, so please don't say "use XML Spy" or similar.
|
In your handler for the validation, you should receive a SAXParseException with that message, as well as the [column number and the line number](http://xerces.apache.org/xerces2-j/javadocs/api/org/xml/sax/SAXParseException.html#method_summary) in the XML file. Isnt't it the case?
|
153,846 |
<p>We have a WCF service deployed on a Windows 2003 server that is exhibiting some problems. The configuration is using <code>wsHttpBinding</code> and we are specifying the IP address. The services is being hosted by a Windows Service.</p>
<p>When we start the service up, most of the time it grabs the wrong IP address. A few times it bound to the correct address only to drop that binding and go to the other address (there are 2) bound to the NIC after processing for a short while.</p>
<p>It is currently using port 80 (we've configured IIS to bind to only 1 address via <code>httpcfg</code>) although we have tried it using different ports with the same results.</p>
<p>When the Windows Service starts hosting the WCF service, the properties show that it is being bound to the correct address; however, tcpview shows that it is indeed listening on the incorrect address.</p>
<p>Here is the portion of the config that sets up tehe baseAddress. The one that gets bound to ends up being .4 instead of .9</p>
<pre><code><services>
<service name="Service.MyService"
behaviorConfiguration="serviceBehavior">
<host>
<baseAddresses>
<add baseAddress="http://xx.xx.xx.9:80/" />
</baseAddresses>
</host>
<endpoint address="MyService"
binding="wsHttpBinding"
bindingConfiguration="WSHttpBinding_IMyService"
contract="Service.IMyService" />
<endpoint address="mex"
binding="mexHttpBinding"
contract="IMetadataExchange" />
</service>
</services>
</code></pre>
<ul>
<li>Is there some other configuration that needs to be set? </li>
<li>Is there a tool that can help track down where this is getting bound to the wrong address?</li>
</ul>
|
[
{
"answer_id": 154658,
"author": "aogan",
"author_id": 4795,
"author_profile": "https://Stackoverflow.com/users/4795",
"pm_score": 1,
"selected": false,
"text": "<p>Your WCF configuration looks OK to me. This might be an issue with the binding order of your NIC cards. Make sure that the NIC with correct address is first. Here is an article that discuss how to set and view nic binding orders: </p>\n\n<p><a href=\"http://theregime.wordpress.com/2008/03/04/how-to-setview-the-nic-bind-order-in-windows/\" rel=\"nofollow noreferrer\">http://theregime.wordpress.com/2008/03/04/how-to-setview-the-nic-bind-order-in-windows/</a></p>\n"
},
{
"answer_id": 155083,
"author": "palehorse",
"author_id": 312,
"author_profile": "https://Stackoverflow.com/users/312",
"pm_score": 0,
"selected": false,
"text": "<p>More information: I removed the xx.xx.xx.4 IP address from the NIC altogether and turned off IIS. Now when I try to start the service it fails and I find this in the System event log.</p>\n\n<pre><code>Description:\nUnable to bind to the underlying transport for xx.xx.xx.4:80. The IP Listen-Only list may contain a reference to an interface which may not exist on this machine. The data field contains the error number.\n</code></pre>\n\n<p>My configuration file still has the xx.xx.xx.9 baseAddress setting.</p>\n"
},
{
"answer_id": 155568,
"author": "palehorse",
"author_id": 312,
"author_profile": "https://Stackoverflow.com/users/312",
"pm_score": 0,
"selected": false,
"text": "<p>One more piece of informatoin. If we change the binding to use NetTcp instead of WsHttp it binds to the correct address on port 80. Changing it back to WsHttp it goes back to the incorrect IP address.</p>\n"
},
{
"answer_id": 157060,
"author": "aogan",
"author_id": 4795,
"author_profile": "https://Stackoverflow.com/users/4795",
"pm_score": 1,
"selected": false,
"text": "<p>The issue seems to be ISS related. Here is the description about the error your getting from <a href=\"http://www.microsoft.com/technet/prodtechnol/WindowsServer2003/Library/IIS/ddf72ae0-aa1e-48c9-88d1-10bae1e87e4f.mspx?mfr=true\" rel=\"nofollow noreferrer\">http://www.microsoft.com/technet/prodtechnol/WindowsServer2003/Library/IIS/ddf72ae0-aa1e-48c9-88d1-10bae1e87e4f.mspx?mfr=true</a></p>\n\n<p><em>This error is logged to the event log when HTTP.sys parses the IP inclusion list and finds that all of the entries in the list are invalid. If this happens, as the description in Table 11.15 notes, HTTP.sys listens to all IP addresses.</em></p>\n\n<p>You can also check the following thread which talks about a similiar issue\n<a href=\"http://www.webhostingtalk.com/showthread.php?t=534174\" rel=\"nofollow noreferrer\">http://www.webhostingtalk.com/showthread.php?t=534174</a></p>\n\n<p>Hope this helps.</p>\n"
},
{
"answer_id": 802545,
"author": "A. M.",
"author_id": 80839,
"author_profile": "https://Stackoverflow.com/users/80839",
"pm_score": 1,
"selected": false,
"text": "<p>We had the same issue and this feature helped us to solve our problem :</p>\n\n<p><a href=\"http://msdn.microsoft.com/fr-fr/library/system.servicemodel.hostnamecomparisonmode.aspx\" rel=\"nofollow noreferrer\">http://msdn.microsoft.com/en-us/library/system.servicemodel.hostnamecomparisonmode.aspx</a></p>\n\n<p>Hope this help.</p>\n"
},
{
"answer_id": 3862873,
"author": "Rebecca",
"author_id": 119624,
"author_profile": "https://Stackoverflow.com/users/119624",
"pm_score": 0,
"selected": false,
"text": "<p>BaseAddress is ignored. You need to <a href=\"http://gavinmckay.wordpress.com/2009/03/24/howto-fix-wcf-host-name-on-iis/\" rel=\"nofollow\">set a host header under IIS</a>.</p>\n"
}
] |
2008/09/30
|
[
"https://Stackoverflow.com/questions/153846",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/312/"
] |
We have a WCF service deployed on a Windows 2003 server that is exhibiting some problems. The configuration is using `wsHttpBinding` and we are specifying the IP address. The services is being hosted by a Windows Service.
When we start the service up, most of the time it grabs the wrong IP address. A few times it bound to the correct address only to drop that binding and go to the other address (there are 2) bound to the NIC after processing for a short while.
It is currently using port 80 (we've configured IIS to bind to only 1 address via `httpcfg`) although we have tried it using different ports with the same results.
When the Windows Service starts hosting the WCF service, the properties show that it is being bound to the correct address; however, tcpview shows that it is indeed listening on the incorrect address.
Here is the portion of the config that sets up tehe baseAddress. The one that gets bound to ends up being .4 instead of .9
```
<services>
<service name="Service.MyService"
behaviorConfiguration="serviceBehavior">
<host>
<baseAddresses>
<add baseAddress="http://xx.xx.xx.9:80/" />
</baseAddresses>
</host>
<endpoint address="MyService"
binding="wsHttpBinding"
bindingConfiguration="WSHttpBinding_IMyService"
contract="Service.IMyService" />
<endpoint address="mex"
binding="mexHttpBinding"
contract="IMetadataExchange" />
</service>
</services>
```
* Is there some other configuration that needs to be set?
* Is there a tool that can help track down where this is getting bound to the wrong address?
|
Your WCF configuration looks OK to me. This might be an issue with the binding order of your NIC cards. Make sure that the NIC with correct address is first. Here is an article that discuss how to set and view nic binding orders:
<http://theregime.wordpress.com/2008/03/04/how-to-setview-the-nic-bind-order-in-windows/>
|
153,861 |
<p>What do the brackets do in a sql statement?</p>
<p>For example, in the statement: </p>
<pre>insert into table1 ([columnname1], columnname2) values (val1, val2)</pre>
<p>Also, what does it do if the table name is in brackets?</p>
|
[
{
"answer_id": 153870,
"author": "Jorge Ferreira",
"author_id": 6508,
"author_profile": "https://Stackoverflow.com/users/6508",
"pm_score": 3,
"selected": false,
"text": "<p>They are meant to escape reserved keywords or invalid column identifiers.</p>\n\n<pre><code>CREATE TABLE test\n(\n [select] varchar(15)\n)\n\nINSERT INTO test VALUES('abc')\n\nSELECT [select] FROM test\n</code></pre>\n"
},
{
"answer_id": 153871,
"author": "albertein",
"author_id": 23020,
"author_profile": "https://Stackoverflow.com/users/23020",
"pm_score": 7,
"selected": true,
"text": "<p>The [] marks the delimitation of a identifier, so if you have a column whose name contains spaces like Order Qty you need to enclose it with [] like:</p>\n\n<pre><code>select [Order qty] from [Client sales]\n</code></pre>\n\n<p>They are also to escape reserved keywords used as identifiers</p>\n"
},
{
"answer_id": 153878,
"author": "Darrel Miller",
"author_id": 6819,
"author_profile": "https://Stackoverflow.com/users/6819",
"pm_score": 0,
"selected": false,
"text": "<p>They are simply delimiters that allow you to put special characters (like spaces) in the column or table name\ne.g. </p>\n\n<pre><code>insert into [Table One] ([Column Name 1], columnname2) values (val1, val2)\n</code></pre>\n"
},
{
"answer_id": 153888,
"author": "Orion Adrian",
"author_id": 7756,
"author_profile": "https://Stackoverflow.com/users/7756",
"pm_score": 2,
"selected": false,
"text": "<p>Anything inside the brackets is considered a single identifier (e.g. [test machine]. This can be used to enclose names with spaces or to escape reserve words (e.g. [order], [select], [group]).</p>\n"
},
{
"answer_id": 153915,
"author": "Ty.",
"author_id": 8873,
"author_profile": "https://Stackoverflow.com/users/8873",
"pm_score": 2,
"selected": false,
"text": "<p>They allow you to use keywords (such as <strong>date</strong>) in the name of the column, table, etc...</p>\n\n<p>Since this is a bad practice to begin with, they are generally not included. The only place you should see them being used is by people starting out with sql queries that don't know any better. Other than that they just clutter up your query.</p>\n"
},
{
"answer_id": 154416,
"author": "Bill Karwin",
"author_id": 20860,
"author_profile": "https://Stackoverflow.com/users/20860",
"pm_score": 4,
"selected": false,
"text": "<p>This is Microsoft SQL Server nonstandard syntax for \"delimited identifiers.\" SQL supports delimiters for identifiers to allow table names, column names, or other metadata objects to contain the following:</p>\n\n<ul>\n<li>SQL reserved words: \"Order\"</li>\n<li>Words containing spaces: \"Order qty\"</li>\n<li>Words containing punctuation: \n\"Order-qty\"</li>\n<li>Words containing international\ncharacters</li>\n<li>Column names that are\ncase-sensitive: \"Order\" vs. \"order\"</li>\n</ul>\n\n<p>Microsoft SQL Server uses the square brackets, but this is not the syntax standard SQL uses for delimited identifiers. Standardly, double-quotes should be used for delimiters.</p>\n\n<p>In Microsoft SQL Server, you can enable a mode to use standard double-quotes for delimiters as follows:</p>\n\n<pre><code>SET QUOTED_IDENTIFIER ON;\n</code></pre>\n"
},
{
"answer_id": 15370794,
"author": "sumon",
"author_id": 2162651,
"author_profile": "https://Stackoverflow.com/users/2162651",
"pm_score": 1,
"selected": false,
"text": "<p>if you use any column name which is same as any reserved keyword in sql, in that case you can put the column name in square bracket to distinguish between your custom column name and existing reserved keyword.</p>\n"
},
{
"answer_id": 35031981,
"author": "juFo",
"author_id": 187650,
"author_profile": "https://Stackoverflow.com/users/187650",
"pm_score": 1,
"selected": false,
"text": "<p>When having table names or filenames with spaces or dashes (-) etc... you can receive \"Systax error in FROM clause\".\nUse [] brackets to solve this. </p>\n\n<p>See: <a href=\"https://msdn.microsoft.com/en-us/library/ms175874.aspx\" rel=\"nofollow\">https://msdn.microsoft.com/en-us/library/ms175874.aspx</a></p>\n"
}
] |
2008/09/30
|
[
"https://Stackoverflow.com/questions/153861",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/673/"
] |
What do the brackets do in a sql statement?
For example, in the statement:
```
insert into table1 ([columnname1], columnname2) values (val1, val2)
```
Also, what does it do if the table name is in brackets?
|
The [] marks the delimitation of a identifier, so if you have a column whose name contains spaces like Order Qty you need to enclose it with [] like:
```
select [Order qty] from [Client sales]
```
They are also to escape reserved keywords used as identifiers
|
153,863 |
<p>I have a large 'Manager' class which I think is doing too much but I am unsure on how to divide it into more logical units. </p>
<p>Generally speaking the class basically consists of the following methods:</p>
<pre>
class FooBarManager
{
GetFooEntities();
AddFooEntity(..);
UpdateFooEntity(..);
SubmitFooEntity(..);
GetFooTypes();
GetBarEntities();
}
</pre>
<p>The Manager class is part of my business logic and constains an instance of another "Manager" class on the data access level which contains all CRUD operations for all entities.</p>
<p>I have different entities coming from the data access layer and therefore have a converter in place outside of the Manager class to convert data entities to business entities.</p>
<p>The reason for the manager classes was that I wanted to be able to mock out each of the "Manager" classes when I do unittesting. Each of the manager classes is now over 1000 loc and contain 40-50 methods each. I consider them to be quite bloated and find it awkward to put all of the data access logic into a single class. What should I be doing differently?</p>
<p>How would I go about splitting them and is there any specific design-pattern should I be using?</p>
|
[
{
"answer_id": 153901,
"author": "Jamie Ide",
"author_id": 12752,
"author_profile": "https://Stackoverflow.com/users/12752",
"pm_score": 1,
"selected": false,
"text": "<p>You really shouldn't put all data access into one class unless it's generic. I would start by splitting out your data access classes into one manager per object or related groups of objects, i.e. CompanyManager, CustomerManager, etc. If your need to access the manager through one \"god class\" you could have an instance of each manager available in your one true Manager class.</p>\n"
},
{
"answer_id": 153917,
"author": "scable",
"author_id": 8942,
"author_profile": "https://Stackoverflow.com/users/8942",
"pm_score": 0,
"selected": false,
"text": "<pre><code> / FooManager\nManager (derive from Manager)\n \\ BarManager\n</code></pre>\n\n<p>Should be self-explaining</p>\n"
},
{
"answer_id": 153926,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 0,
"selected": false,
"text": "<p>I'd suggest using composition. Think about the functions the manager is doing. Split them along the lines of single responsibility. It appears most of FooBarManager is a collection of Foo and bar entities. So, at a minimum, break out the collection logic from FooBarManager</p>\n\n<pre><code>public class EntityCollection<T> : IList<T> \n where T : BaseEntity\n{ /* all management logic here */}\npublic class FooCollection : EntityCollection<foo> {}\npublic class BarCollection : EntityCollection<bar> {}\npublic class FooBarManager \n{ \npublic FooCollection { /*...*/ } \npublic BarCollection { /*...*/ } \npublic FooBarManager() : this(new FooCollection(), new BarCollection()){}\npublic FooBarManager(FooCollection fc, BarCollection bc) { /*...*/ } \n}\n</code></pre>\n"
},
{
"answer_id": 153935,
"author": "Mac",
"author_id": 8696,
"author_profile": "https://Stackoverflow.com/users/8696",
"pm_score": 1,
"selected": false,
"text": "<p>Your <code>FooBarManager</code> looks a lot like a <a href=\"http://en.wikipedia.org/wiki/God_object\" rel=\"nofollow noreferrer\">God Object</a> anti pattern.</p>\n\n<p>In a situation like yours, consider delving into <a href=\"http://martinfowler.com/books.html#eaa\" rel=\"nofollow noreferrer\">Patterns of Enterprise Application Architecture</a>, by Martin Fowler. At first sight, it looks like you want to create a <a href=\"http://martinfowler.com/eaaCatalog/dataMapper.html\" rel=\"nofollow noreferrer\">Data Mapper</a>. But consider alternatives like <a href=\"http://martinfowler.com/eaaCatalog/activeRecord.html\" rel=\"nofollow noreferrer\">Active Record</a>s, that might be enough for your needs.</p>\n\n<p>Also consider using an <a href=\"http://en.wikipedia.org/wiki/List_of_object-relational_mapping_software\" rel=\"nofollow noreferrer\">ORM library/software</a> for your platform. Building your own without a good reason will only confront you to the many problems that have already been more or less solved by these tools.</p>\n"
}
] |
2008/09/30
|
[
"https://Stackoverflow.com/questions/153863",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/15771/"
] |
I have a large 'Manager' class which I think is doing too much but I am unsure on how to divide it into more logical units.
Generally speaking the class basically consists of the following methods:
```
class FooBarManager
{
GetFooEntities();
AddFooEntity(..);
UpdateFooEntity(..);
SubmitFooEntity(..);
GetFooTypes();
GetBarEntities();
}
```
The Manager class is part of my business logic and constains an instance of another "Manager" class on the data access level which contains all CRUD operations for all entities.
I have different entities coming from the data access layer and therefore have a converter in place outside of the Manager class to convert data entities to business entities.
The reason for the manager classes was that I wanted to be able to mock out each of the "Manager" classes when I do unittesting. Each of the manager classes is now over 1000 loc and contain 40-50 methods each. I consider them to be quite bloated and find it awkward to put all of the data access logic into a single class. What should I be doing differently?
How would I go about splitting them and is there any specific design-pattern should I be using?
|
You really shouldn't put all data access into one class unless it's generic. I would start by splitting out your data access classes into one manager per object or related groups of objects, i.e. CompanyManager, CustomerManager, etc. If your need to access the manager through one "god class" you could have an instance of each manager available in your one true Manager class.
|
153,879 |
<p>As part of a build setup on a windows machine I need to add a registry entry and I'd like to do it from a simple batch file.</p>
<p>The entry is for a third party app so the format is fixed.</p>
<p>The entry takes the form of a REG_SZ string but needs to contain newlines ie. 0xOA characters as separators.</p>
<p>I've hit a few problems.</p>
<p>First attempt used regedit to load a generated .reg file. This failed as it did not seem to like either either long strings or strings with newlines. I discovered that export works fine import fails. I was able to test export as the third party app adds similar entries directly through the win32 api.</p>
<p>Second attempt used the command REG ADD but I can't find anyway to add the newline characters everything I try just ends up with a literal string being added.</p>
|
[
{
"answer_id": 153952,
"author": "tloach",
"author_id": 14092,
"author_profile": "https://Stackoverflow.com/users/14092",
"pm_score": 3,
"selected": true,
"text": "<p>You could create a VBScript(.vbs) file and just call it from a batch file, assuming you're doing other things in the batch other than this registry change. In vbscript you would be looking at something like:</p>\n\n<pre><code>set WSHShell = CreateObject(\"WScript.Shell\") \nWSHShell.RegWrite \"HKEY_LOCAL_MACHINE\\SOMEKEY\", \"value\", \"type\"\n</code></pre>\n\n<p>You should be able to find the possible type values using Google.</p>\n"
},
{
"answer_id": 154062,
"author": "Factor Mystic",
"author_id": 1569,
"author_profile": "https://Stackoverflow.com/users/1569",
"pm_score": 2,
"selected": false,
"text": "<p>If you're not constrained to a scripting language, you can do it in C# with</p>\n\n<pre><code>Registry.CurrentUser.OpenSubKey(@\"software\\classes\\something\", true).SetValue(\"some key\", \"sometext\\nothertext\", RegistryValueKind.String);\n</code></pre>\n"
},
{
"answer_id": 13255189,
"author": "kbulgrien",
"author_id": 856172,
"author_profile": "https://Stackoverflow.com/users/856172",
"pm_score": 2,
"selected": false,
"text": "<p>You can import multiline REG_SZ strings containing carriage return (CR) and linefeed (LF) end-of-line (EOL) breaks into the registry using .reg files as long as you do not mind translating the text as UTF-16LE hexadecimal encoded data. To import a REG_SZ with this text:</p>\n\n<pre>\n1st Line\n2nd Line\n\n</pre>\n\n<p>You might create a file called MULTILINETEXT.REG that contains this:</p>\n\n<pre>\nWindows Registry Editor Version 5.00\n\n[HKEY_CURRENT_USER\\Environment]\n\"MULTILINETEXT\"=hex(1):31,00,73,00,74,00,20,00,4c,00,69,00,6e,00,65,00,0d,00,0a,00,\\\n32,00,6e,00,64,00,20,00,4c,00,69,00,6e,00,65,00,0d,00,0a,00,\\\n00,00\n\n</pre>\n\n<p>To encode ASCII into UTF-16LE, simply add a null byte following each ASCII code value. REG_SZ values must terminate with a null character (<code>,00,00</code>) in UTF-16LE notation.</p>\n\n<p>Import the registry change in the batch file <code>REG.EXE IMPORT MULTILINETEXT.REG</code>.</p>\n\n<p>The example uses the Environment key because it is convenient, not because it is particularly useful to add such data to environment variables. One may use RegEdit to verify that the imported REG_SZ data contains the CRLF characters.</p>\n"
},
{
"answer_id": 73128110,
"author": "Tom A",
"author_id": 10226,
"author_profile": "https://Stackoverflow.com/users/10226",
"pm_score": 0,
"selected": false,
"text": "<p>Another approach -- that is much easier to read and maintain -- is to use a PowerShell script. Run PowerShell as Admin.</p>\n<hr />\n<p># SetLegalNotice_AsAdmin.ps1</p>\n<p># Define multi-line legal notice registry entry</p>\n<p>Push-Location</p>\n<p>Set-Location -Path Registry::HKEY_LOCAL_MACHINE\\SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Policies\\System\\</p>\n<p>$contentCaption="Legal Notice"</p>\n<p>$contentNotice= @"</p>\n<p>This is a very long string that runs to many lines.</p>\n<p>You are accessing a U.S. Government (USG) Information System (IS) that is provided for USG-authorized use only.</p>\n<p>By using this IS (which includes any device attached to this IS), you consent to the following conditions:</p>\n<p>-The USG routinely intercepts and monitors communications on this IS for purposes including, but not limited to, penetration testing, COMSEC monitoring, network operations and defense, personnel misconduct (PM), law enforcement (LE), and counterintelligence (CI) investigations.</p>\n<p>etc...</p>\n<p>"@</p>\n<p># Caption</p>\n<p>New-ItemProperty -Path . -Name legalnoticetext -PropertyType MultiString -Value $contentCaption -Force</p>\n<p># Notice</p>\n<p>New-ItemProperty -Path . -Name legalnoticetext -PropertyType MultiString -Value $contentNotice -Force</p>\n<p>Pop-Location</p>\n<p><a href=\"https://i.stack.imgur.com/dE6i3.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/dE6i3.png\" alt=\"enter image description here\" /></a></p>\n"
}
] |
2008/09/30
|
[
"https://Stackoverflow.com/questions/153879",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5427/"
] |
As part of a build setup on a windows machine I need to add a registry entry and I'd like to do it from a simple batch file.
The entry is for a third party app so the format is fixed.
The entry takes the form of a REG\_SZ string but needs to contain newlines ie. 0xOA characters as separators.
I've hit a few problems.
First attempt used regedit to load a generated .reg file. This failed as it did not seem to like either either long strings or strings with newlines. I discovered that export works fine import fails. I was able to test export as the third party app adds similar entries directly through the win32 api.
Second attempt used the command REG ADD but I can't find anyway to add the newline characters everything I try just ends up with a literal string being added.
|
You could create a VBScript(.vbs) file and just call it from a batch file, assuming you're doing other things in the batch other than this registry change. In vbscript you would be looking at something like:
```
set WSHShell = CreateObject("WScript.Shell")
WSHShell.RegWrite "HKEY_LOCAL_MACHINE\SOMEKEY", "value", "type"
```
You should be able to find the possible type values using Google.
|
153,890 |
<p>I'm trying to find a good way to print leading <code>0</code>, such as <code>01001</code> for a <a href="https://en.wikipedia.org/wiki/ZIP_Code" rel="noreferrer">ZIP Code</a>. While the number would be stored as <code>1001</code>, what is a good way to do it?</p>
<p>I thought of using either <code>case</code> statements or <code>if</code> to figure out how many digits the number is and then convert it to an <code>char</code> array with extra <code>0</code>'s for printing, but I can't help but think there may be a way to do this with the <code>printf</code> format syntax that is eluding me.</p>
|
[
{
"answer_id": 153895,
"author": "EvilTeach",
"author_id": 7734,
"author_profile": "https://Stackoverflow.com/users/7734",
"pm_score": 10,
"selected": true,
"text": "<pre><code>printf("%05d", zipCode);\n</code></pre>\n<p>The <code>0</code> indicates what you are padding with and the <code>5</code> shows the width of the integer number.</p>\n<p>Example 1: If you use <code>"%02d"</code> (useful for dates) this would only pad zeros for numbers in the ones column. E.g., <code>06</code> instead of <code>6</code>.</p>\n<p>Example 2: <code>"%03d"</code> would pad 2 zeros for one number in the ones column and pad 1 zero for a number in the tens column. E.g., number 7 padded to <code>007</code> and number 17 padded to <code>017</code>.</p>\n"
},
{
"answer_id": 153898,
"author": "Trent",
"author_id": 9083,
"author_profile": "https://Stackoverflow.com/users/9083",
"pm_score": 3,
"selected": false,
"text": "<p><em>printf</em> allows various formatting options.</p>\n<p>Example:</p>\n<pre><code>printf("leading zeros %05d", 123);\n</code></pre>\n"
},
{
"answer_id": 153899,
"author": "Adam Bellaire",
"author_id": 21632,
"author_profile": "https://Stackoverflow.com/users/21632",
"pm_score": 6,
"selected": false,
"text": "<p>You place a zero before the minimum field width:</p>\n<pre><code>printf("%05d", zipcode);\n</code></pre>\n"
},
{
"answer_id": 153904,
"author": "Paul Tomblin",
"author_id": 3333,
"author_profile": "https://Stackoverflow.com/users/3333",
"pm_score": 4,
"selected": false,
"text": "<p>If you are on a *nix machine:</p>\n<pre class=\"lang-none prettyprint-override\"><code>man 3 printf\n</code></pre>\n<p>This will show a manual page, similar to:</p>\n<blockquote>\n<p>0 The value should be zero padded. For d, i, o, u, x, X, a, A, e,\nE, f, F, g, and G conversions, the converted value is padded on\nthe left with zeros rather than blanks. If the 0 and - flags\nboth appear, the 0 flag is ignored. If a precision is given\nwith a numeric conversion (d, i, o, u, x, and X), the 0 flag is\nignored. For other conversions, the behavior is undefined.</p>\n</blockquote>\n<p>Even though the question is for C, <a href=\"http://www.cplusplus.com/reference/cstdio/printf/\" rel=\"nofollow noreferrer\">this</a> page may be of aid.</p>\n"
},
{
"answer_id": 153907,
"author": "Dan Hewett",
"author_id": 17975,
"author_profile": "https://Stackoverflow.com/users/17975",
"pm_score": 4,
"selected": false,
"text": "<pre><code>sprintf(mystring, \"%05d\", myInt);\n</code></pre>\n\n<p>Here, \"05\" says \"use 5 digits with leading zeros\".</p>\n"
},
{
"answer_id": 153911,
"author": "James Curran",
"author_id": 12725,
"author_profile": "https://Stackoverflow.com/users/12725",
"pm_score": 7,
"selected": false,
"text": "<p>The correct solution is to store the ZIP Code in the database as a STRING. Despite the fact that it may look like a number, it isn't. It's a code, where each part has meaning.</p>\n<p>A number is a thing you do arithmetic on. A ZIP Code is not that.</p>\n"
},
{
"answer_id": 153924,
"author": "JeeBee",
"author_id": 17832,
"author_profile": "https://Stackoverflow.com/users/17832",
"pm_score": 4,
"selected": false,
"text": "<p>ZIP Code is a highly localised field, and many countries have characters in their postcodes, e.g., UK, Canada. Therefore, in this example, you should use a string / varchar field to store it if at any point you would be shipping or getting users, customers, clients, etc. from other countries.</p>\n<p>However, in the general case, you should use the recommended answer (<code>printf("%05d", number);</code>).</p>\n"
},
{
"answer_id": 154123,
"author": "pro3carp3",
"author_id": 7899,
"author_profile": "https://Stackoverflow.com/users/7899",
"pm_score": 2,
"selected": false,
"text": "<p>You will save yourself a heap of trouble (long term) if you store a ZIP Code as a character string, which it is, rather than a number, which it is not.</p>\n"
},
{
"answer_id": 23167000,
"author": "rch",
"author_id": 3551091,
"author_profile": "https://Stackoverflow.com/users/3551091",
"pm_score": 0,
"selected": false,
"text": "<p>More flexible.. \nHere's an example printing rows of right-justified numbers with fixed widths, and space-padding.</p>\n\n<pre><code>//---- Header\nstd::string getFmt ( int wid, long val )\n{ \n char buf[64];\n sprintf ( buf, \"% *ld\", wid, val );\n return buf;\n}\n#define FMT (getFmt(8,x).c_str())\n\n//---- Put to use\nprintf ( \" COUNT USED FREE\\n\" );\nprintf ( \"A: %s %s %s\\n\", FMT(C[0]), FMT(U[0]), FMT(F[0]) );\nprintf ( \"B: %s %s %s\\n\", FMT(C[1]), FMT(U[1]), FMT(F[1]) );\nprintf ( \"C: %s %s %s\\n\", FMT(C[2]), FMT(U[2]), FMT(F[2]) );\n\n//-------- Output\n COUNT USED FREE\nA: 354 148523 3283\nB: 54138259 12392759 200391\nC: 91239 3281 61423\n</code></pre>\n\n<p>The function and macro are designed so the printfs are more readable.</p>\n"
},
{
"answer_id": 30940716,
"author": "Brad Jennings",
"author_id": 1668928,
"author_profile": "https://Stackoverflow.com/users/1668928",
"pm_score": 0,
"selected": false,
"text": "<p>If you need to store the ZIP Code in a character array, <code>zipcode[]</code>, you can use this:</p>\n<pre><code>snprintf(zipcode, 6, "%05.5d", atoi(zipcode));\n</code></pre>\n"
},
{
"answer_id": 66082660,
"author": "chqrlie",
"author_id": 4593267,
"author_profile": "https://Stackoverflow.com/users/4593267",
"pm_score": 3,
"selected": false,
"text": "<p>There are two ways to output your number with leading zeroes:</p>\n<p>Using the <code>0</code> flag and the width specifier:</p>\n<pre><code>int zipcode = 123;\nprintf("%05d\\n", zipcode); // Outputs 00123\n</code></pre>\n<p>Using the precision specifier:</p>\n<pre><code>int zipcode = 123;\nprintf("%.5d\\n", zipcode); // Outputs 00123\n</code></pre>\n<p>The difference between these is the handling of negative numbers:</p>\n<pre><code>printf("%05d\\n", -123); // Outputs -0123 (pad to 5 characters)\nprintf("%.5d\\n", -123); // Outputs -00123 (pad to 5 digits)\n</code></pre>\n<p>ZIP Codes are unlikely to be negative, so it should not matter.</p>\n<p>Note however that ZIP Codes may actually contain letters and dashes, so they should be stored as strings. Including the leading zeroes in the string is straightforward so it solves your problem in a much simpler way.</p>\n<p>Note that in both examples above, the <code>5</code> width or precision values can be specified as an <code>int</code> argument:</p>\n<pre><code>int width = 5;\nprintf("%0*d\\n", width, 123); // Outputs 00123\nprintf("%.*d\\n", width, 123); // Outputs 00123\n</code></pre>\n<p>There is one more trick to know: a precision of <code>0</code> causes no output for the value <code>0</code>:</p>\n<pre><code>printf("|%0d|%0d|\\n", 0, 1); // Outputs |0|1|\nprintf("|%.0d|%.0d|\\n", 0, 1); // Outputs ||1|\n</code></pre>\n"
}
] |
2008/09/30
|
[
"https://Stackoverflow.com/questions/153890",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9628/"
] |
I'm trying to find a good way to print leading `0`, such as `01001` for a [ZIP Code](https://en.wikipedia.org/wiki/ZIP_Code). While the number would be stored as `1001`, what is a good way to do it?
I thought of using either `case` statements or `if` to figure out how many digits the number is and then convert it to an `char` array with extra `0`'s for printing, but I can't help but think there may be a way to do this with the `printf` format syntax that is eluding me.
|
```
printf("%05d", zipCode);
```
The `0` indicates what you are padding with and the `5` shows the width of the integer number.
Example 1: If you use `"%02d"` (useful for dates) this would only pad zeros for numbers in the ones column. E.g., `06` instead of `6`.
Example 2: `"%03d"` would pad 2 zeros for one number in the ones column and pad 1 zero for a number in the tens column. E.g., number 7 padded to `007` and number 17 padded to `017`.
|
153,909 |
<p>I call my JavaScript function. Why do I <em>sometimes</em> get the error 'myFunction is not defined' when it <em>is</em> defined?</p>
<p>For example. I'll occasionally get 'copyArray is not defined' even in this example:</p>
<pre><code>function copyArray( pa ) {
var la = [];
for (var i=0; i < pa.length; i++)
la.push( pa[i] );
return la;
}
Function.prototype.bind = function( po ) {
var __method = this;
var __args = [];
// Sometimes errors -- in practice I inline the function as a workaround.
__args = copyArray( arguments );
return function() {
/* bind logic omitted for brevity */
}
}
</code></pre>
<p>As you can see, copyArray is defined <em>right there</em>, so this can't be about the order in which script files load.</p>
<p>I've been getting this in situations that are harder to work around, where the calling function is located in another file that <em>should</em> be loaded after the called function. But this was the simplest case I could present, and appears to be the same problem.</p>
<p>It doesn't happen 100% of the time, so I do suspect some kind of load-timing-related problem. But I have no idea what.</p>
<p>@Hojou: That's part of the problem. The function in which I'm now getting this error is itself my addLoadEvent, which is basically a standard version of the common library function.</p>
<p>@James: I understand that, and there is no syntax error in the function. When that is the case, the syntax error is reported as well. In this case, I am getting only the 'not defined' error.</p>
<p>@David: The script in this case resides in an external file that is referenced using the normal <script src="file.js"></script> method in the page's head section.</p>
<p>@Douglas: Interesting idea, but if this were the case, how could we <em>ever</em> call a user-defined function with confidence? In any event, I tried this and it didn't work.</p>
<p>@sk: This technique has been tested across browsers and is basically copied from the <a href="http://en.wikipedia.org/wiki/Prototype_JavaScript_Framework" rel="noreferrer">Prototype</a> library.</p>
|
[
{
"answer_id": 153925,
"author": "Per Hornshøj-Schierbeck",
"author_id": 11619,
"author_profile": "https://Stackoverflow.com/users/11619",
"pm_score": 2,
"selected": false,
"text": "<p>My guess is, somehow the document is not fully loaded by the time the method is called. Have your code executing after the document is ready event.</p>\n"
},
{
"answer_id": 153931,
"author": "James Curran",
"author_id": 12725,
"author_profile": "https://Stackoverflow.com/users/12725",
"pm_score": 2,
"selected": false,
"text": "<p>A syntax error in the function -- or in the code above it -- may cause it to be undefined.</p>\n"
},
{
"answer_id": 153937,
"author": "David McLaughlin",
"author_id": 3404,
"author_profile": "https://Stackoverflow.com/users/3404",
"pm_score": 4,
"selected": true,
"text": "<p>It shouldn't be possible for this to happen if you're just including the scripts on the page. </p>\n\n<p>The \"copyArray\" function should always be available when the JavaScript code starts executing no matter if it is declared before or after it -- unless you're loading the JavaScript files in dynamically with a dependency library. There are all sorts of problems with timing if that's the case.</p>\n"
},
{
"answer_id": 153951,
"author": "Douglas Mayle",
"author_id": 8458,
"author_profile": "https://Stackoverflow.com/users/8458",
"pm_score": 0,
"selected": false,
"text": "<p>Use an anonymous function to protect your local symbol table. Something like:</p>\n\n<pre><code>(function() {\n function copyArray(pa) {\n // Details\n }\n\n Function.prototype.bind = function ( po ) {\n __args = copyArray( arguments );\n }\n})();\n</code></pre>\n\n<p>This will create a closure that includes your function in the local symbol table, and you won't have to depend on it being available in the global namespace when you call the function.</p>\n"
},
{
"answer_id": 153972,
"author": "sk.",
"author_id": 16399,
"author_profile": "https://Stackoverflow.com/users/16399",
"pm_score": 2,
"selected": false,
"text": "<p>If you're changing the prototype of the built-in 'function' object it's possible you're running into a browser bug or race condition by modifying a fundamental built-in object. </p>\n\n<p>Test it in multiple browsers to find out.</p>\n"
},
{
"answer_id": 154337,
"author": "Thevs",
"author_id": 8559,
"author_profile": "https://Stackoverflow.com/users/8559",
"pm_score": 0,
"selected": false,
"text": "<p>I'm afraid, when you add a new method to a Function class (by prtotyping), you are actually adding it to all declared functions, AS WELL AS to your copyArray(). In result your copyArray() function gets recursivelly self-referenced. I.e. there should exist copyArray().bind() method, which is calling itself.</p>\n\n<p>In this case some browsers might prevent you from creating such reference loops and fire \"function not defined\" error.</p>\n\n<p>Inline code would be better solution in such case.</p>\n"
},
{
"answer_id": 154356,
"author": "Grant Wagner",
"author_id": 9254,
"author_profile": "https://Stackoverflow.com/users/9254",
"pm_score": 2,
"selected": false,
"text": "<p>This doesn't solve your original problem, but you could always replace the call to <code>copyArray()</code> with:</p>\n\n<pre><code>__args = Array.prototype.slice.call(arguments);\n</code></pre>\n\n<p>More information available from <a href=\"http://www.google.com/search?q=array.prototype.slice.call\" rel=\"nofollow noreferrer\">Google</a>.</p>\n\n<p>I've tested the above in the following browsers: IE6, 7 & 8B2, Firefox 2.0.0.17 & 3.0.3, Opera 9.52, Safari for Windows 3.1.2 and Google Chrome (whatever the latest version was at the time of this post) and it works across all browsers.</p>\n"
},
{
"answer_id": 336800,
"author": "Jan Aagaard",
"author_id": 37147,
"author_profile": "https://Stackoverflow.com/users/37147",
"pm_score": 2,
"selected": false,
"text": "<p>Verify your code with <a href=\"http://www.jslint.com/\" rel=\"nofollow noreferrer\">JSLint</a>. It will usually find a ton of small errors, so the warning \"JSLint may hurt your feelings\" is pretty spot on. =)</p>\n"
},
{
"answer_id": 2485994,
"author": "Niloct",
"author_id": 152016,
"author_profile": "https://Stackoverflow.com/users/152016",
"pm_score": 5,
"selected": false,
"text": "<p>I had this function not being recognized as defined in latest Firefox for Linux, though Chromium was dealing fine with it.</p>\n\n<p>What happened in my case was that I had a former <code>SCRIPT</code> block, before the block that defined the function with problem, stated in the following way:</p>\n\n<pre><code><SCRIPT src=\"mycode.js\"/>\n</code></pre>\n\n<p>(That is, without the closing tag.)</p>\n\n<p>I had to redeclare this block in the following way.</p>\n\n<pre><code><SCRIPT src=\"mycode.js\"></SCRIPT>\n</code></pre>\n\n<p>And then what followed worked fine... weird huh?</p>\n"
},
{
"answer_id": 6389064,
"author": "Andy V",
"author_id": 446878,
"author_profile": "https://Stackoverflow.com/users/446878",
"pm_score": 0,
"selected": false,
"text": "<p>This can happen when using framesets. In one frame, my variables and methods were defined. In another, they were not. It was especially confusing when using the debugger and seeing my variable defined, then undefined at a breakpoint inside a frame.</p>\n"
},
{
"answer_id": 11089069,
"author": "Bridget",
"author_id": 1405798,
"author_profile": "https://Stackoverflow.com/users/1405798",
"pm_score": 2,
"selected": false,
"text": "<p>This has probably been corrected, but... apparently firefox has a caching problem which is the cause of javascript functions not being recognized.. I really don't know the specifics, but if you clear your cache that will fix the problem (until your cache is full again... not a good solution).. I've been looking around to see if firefox has a real solution to this, but so far nothing... oh not all versions, I think it may be only in some 3.6.x versions, not sure...</p>\n"
},
{
"answer_id": 18888858,
"author": "kaushik0033",
"author_id": 2786080,
"author_profile": "https://Stackoverflow.com/users/2786080",
"pm_score": 0,
"selected": false,
"text": "<p>I think your javascript code should be placed between tag,there is need of document load</p>\n"
},
{
"answer_id": 45927016,
"author": "juan Isaza",
"author_id": 2394901,
"author_profile": "https://Stackoverflow.com/users/2394901",
"pm_score": 2,
"selected": false,
"text": "<p>Solved by removing a \"async\" load:</p>\n\n<pre><code> <script type=\"text/javascript\" src=\"{% static 'js/my_js_file.js' %}\" async></script>\n</code></pre>\n\n<p>changed for:</p>\n\n<pre><code> <script type=\"text/javascript\" src=\"{% static 'js/my_js_file.js' %}\"></script>\n</code></pre>\n"
}
] |
2008/09/30
|
[
"https://Stackoverflow.com/questions/153909",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4525/"
] |
I call my JavaScript function. Why do I *sometimes* get the error 'myFunction is not defined' when it *is* defined?
For example. I'll occasionally get 'copyArray is not defined' even in this example:
```
function copyArray( pa ) {
var la = [];
for (var i=0; i < pa.length; i++)
la.push( pa[i] );
return la;
}
Function.prototype.bind = function( po ) {
var __method = this;
var __args = [];
// Sometimes errors -- in practice I inline the function as a workaround.
__args = copyArray( arguments );
return function() {
/* bind logic omitted for brevity */
}
}
```
As you can see, copyArray is defined *right there*, so this can't be about the order in which script files load.
I've been getting this in situations that are harder to work around, where the calling function is located in another file that *should* be loaded after the called function. But this was the simplest case I could present, and appears to be the same problem.
It doesn't happen 100% of the time, so I do suspect some kind of load-timing-related problem. But I have no idea what.
@Hojou: That's part of the problem. The function in which I'm now getting this error is itself my addLoadEvent, which is basically a standard version of the common library function.
@James: I understand that, and there is no syntax error in the function. When that is the case, the syntax error is reported as well. In this case, I am getting only the 'not defined' error.
@David: The script in this case resides in an external file that is referenced using the normal <script src="file.js"></script> method in the page's head section.
@Douglas: Interesting idea, but if this were the case, how could we *ever* call a user-defined function with confidence? In any event, I tried this and it didn't work.
@sk: This technique has been tested across browsers and is basically copied from the [Prototype](http://en.wikipedia.org/wiki/Prototype_JavaScript_Framework) library.
|
It shouldn't be possible for this to happen if you're just including the scripts on the page.
The "copyArray" function should always be available when the JavaScript code starts executing no matter if it is declared before or after it -- unless you're loading the JavaScript files in dynamically with a dependency library. There are all sorts of problems with timing if that's the case.
|
153,920 |
<p>Code I am trying to run:</p>
<pre><code>$query = "DESCRIBE TABLE TABLENAME";
$result = odbc_exec($h, $query);
</code></pre>
<p>The result:</p>
<blockquote>
<p>PHP Warning: odbc_exec(): SQL error: [unixODBC][IBM][iSeries Access
ODBC Driver][DB2 UDB]SQL0104 - Token TABLENAME was not valid. Valid
tokens: INTO., SQL state 37000 in SQLExecDirect in ...</p>
</blockquote>
<p>There were no other problems with SELECT, INSERT, UPDATE or DELETE queries on the same connection. Is this a syntax error?</p>
|
[
{
"answer_id": 154182,
"author": "Mike Wills",
"author_id": 2535,
"author_profile": "https://Stackoverflow.com/users/2535",
"pm_score": 0,
"selected": false,
"text": "<p>To me it looks like you need to provide a way for the statement to return a value \"Valid tokens: INTO\" tells me that. I haven't used DESCRIBE before, but I would imagine that it returns something.</p>\n\n<p>Interactive SQL doesn't allow the command so I can't really help you much further than that.</p>\n\n<p>BTW, add the iSeries tag to your question. You might get a few more answers that way.</p>\n"
},
{
"answer_id": 173865,
"author": "pmg",
"author_id": 25324,
"author_profile": "https://Stackoverflow.com/users/25324",
"pm_score": 0,
"selected": false,
"text": "<p>If you just need the column names try</p>\n\n<pre><code>select * from <TABLE> where 0 = 1\n</code></pre>\n\n<p>I don't know how to get the column types, indexes, keys, &c</p>\n"
},
{
"answer_id": 184474,
"author": "Ian McLaird",
"author_id": 18796,
"author_profile": "https://Stackoverflow.com/users/18796",
"pm_score": 3,
"selected": false,
"text": "<p>The iSeries flavor of DB2 does not support the SQL DESCRIBE statement. Instead, you have to query the system table:</p>\n\n<pre><code>select * from qsys2.columns where table_schema = 'my_schema' and table_name = 'my_table'\n</code></pre>\n"
},
{
"answer_id": 259854,
"author": "Paul Morgan",
"author_id": 16322,
"author_profile": "https://Stackoverflow.com/users/16322",
"pm_score": 1,
"selected": false,
"text": "<blockquote>\n <p>This statement can only be embedded in an application program. It is an executable statement that cannot be dynamically prepared. It must not be specified in Java.</p>\n</blockquote>\n\n<p>From the iSeries DB2 SQL Reference.</p>\n"
}
] |
2008/09/30
|
[
"https://Stackoverflow.com/questions/153920",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/8437/"
] |
Code I am trying to run:
```
$query = "DESCRIBE TABLE TABLENAME";
$result = odbc_exec($h, $query);
```
The result:
>
> PHP Warning: odbc\_exec(): SQL error: [unixODBC][IBM][iSeries Access
> ODBC Driver][DB2 UDB]SQL0104 - Token TABLENAME was not valid. Valid
> tokens: INTO., SQL state 37000 in SQLExecDirect in ...
>
>
>
There were no other problems with SELECT, INSERT, UPDATE or DELETE queries on the same connection. Is this a syntax error?
|
The iSeries flavor of DB2 does not support the SQL DESCRIBE statement. Instead, you have to query the system table:
```
select * from qsys2.columns where table_schema = 'my_schema' and table_name = 'my_table'
```
|
153,934 |
<p>I'm trying to modify the class of an element if an ajax call based on that element is successful</p>
<pre><code><script type='text/javascript'>
$("#a.toggle").click(function(e){
$.ajax({
url: '/changeItem.php',
dataType: 'json',
type: 'POST',
success: function(data,text){
if(data.error=='')
{
if($(this).hasClass('class1'))
{
$(this).removeClass('class1');
$(this).addClass('class2');
}
else if($(this).hasClass('class2'))
{
$(this).removeClass('class2');
$(this).addClass('class1');
}
}
else(alert(data.error));
}
});
return false;
});
</script>
<a class="toggle class1" title='toggle-this'>Item</a>
</code></pre>
<p>My understanding of the problem is that in the success function <em>this</em> references the ajax object parameters, NOT the calling dom element like it does within other places of the click function. So, how do I reference the calling dom element and check / add / remove classes?</p>
|
[
{
"answer_id": 153948,
"author": "Dan Goldstein",
"author_id": 23427,
"author_profile": "https://Stackoverflow.com/users/23427",
"pm_score": 5,
"selected": true,
"text": "<p>You can just store it in a variable. Example:</p>\n\n<pre><code>$(\"#a.toggle\").click(function(e)\n{\n var target = $(this);\n $.ajax({\n url: '/changeItem.php',\n dataType: 'json',\n type: 'POST',\n success: function(data,text)\n {\n if(data.error=='')\n {\n if(target.hasClass('class1'))\n {\n target\n .removeClass('class1')\n .addClass('class2');\n }\n else if(target.hasClass('class2'))\n {\n target\n .removeClass('class2')\n .addClass('class1');\n }\n }\n else(alert(data.error));\n } \n });\n return false;\n});\n</code></pre>\n"
},
{
"answer_id": 153958,
"author": "Ellen Teapot",
"author_id": 1914,
"author_profile": "https://Stackoverflow.com/users/1914",
"pm_score": 3,
"selected": false,
"text": "<p>jQuery passes the target of the event, along with some other information about it, to your handler function. See <a href=\"http://docs.jquery.com/Events_%28Guide%29\" rel=\"nofollow noreferrer\">http://docs.jquery.com/Events_%28Guide%29</a> for more info about this.</p>\n\n<p>In your code, it'd be referenced like $(e.target).</p>\n"
},
{
"answer_id": 2900824,
"author": "Jesse",
"author_id": 346723,
"author_profile": "https://Stackoverflow.com/users/346723",
"pm_score": 2,
"selected": false,
"text": "<p>I know it's old but you can use the 'e' parameter from the click function.</p>\n"
},
{
"answer_id": 25442621,
"author": "Mikhail Korolev",
"author_id": 3920854,
"author_profile": "https://Stackoverflow.com/users/3920854",
"pm_score": 2,
"selected": false,
"text": "<p>Better set ajax parameter : <code>context: this</code>. Example:</p>\n\n<pre><code> $.ajax({\n url: '/changeItem.php',\n dataType: 'json',\n type: 'POST',\n context: this,\n success: function(data,text){\n if(data.error=='')\n {\n if($(this).hasClass('class1'))\n {\n $(this).removeClass('class1');\n $(this).addClass('class2');\n }\n else if($(this).hasClass('class2'))\n {\n $(this).removeClass('class2');\n $(this).addClass('class1');\n }\n }\n else(alert(data.error));\n } \n});\n</code></pre>\n"
}
] |
2008/09/30
|
[
"https://Stackoverflow.com/questions/153934",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/144/"
] |
I'm trying to modify the class of an element if an ajax call based on that element is successful
```
<script type='text/javascript'>
$("#a.toggle").click(function(e){
$.ajax({
url: '/changeItem.php',
dataType: 'json',
type: 'POST',
success: function(data,text){
if(data.error=='')
{
if($(this).hasClass('class1'))
{
$(this).removeClass('class1');
$(this).addClass('class2');
}
else if($(this).hasClass('class2'))
{
$(this).removeClass('class2');
$(this).addClass('class1');
}
}
else(alert(data.error));
}
});
return false;
});
</script>
<a class="toggle class1" title='toggle-this'>Item</a>
```
My understanding of the problem is that in the success function *this* references the ajax object parameters, NOT the calling dom element like it does within other places of the click function. So, how do I reference the calling dom element and check / add / remove classes?
|
You can just store it in a variable. Example:
```
$("#a.toggle").click(function(e)
{
var target = $(this);
$.ajax({
url: '/changeItem.php',
dataType: 'json',
type: 'POST',
success: function(data,text)
{
if(data.error=='')
{
if(target.hasClass('class1'))
{
target
.removeClass('class1')
.addClass('class2');
}
else if(target.hasClass('class2'))
{
target
.removeClass('class2')
.addClass('class1');
}
}
else(alert(data.error));
}
});
return false;
});
```
|
153,953 |
<p>I’m trying to debug a memory leak problem. I’m using <a href="http://www.gnu.org/software/libc/manual/html_node/Tracing-malloc.html#Tracing-malloc" rel="noreferrer">mtrace()</a> to get a malloc/free/realloc trace. I’ve ran my prog and have now a huge log file. So far so good. But I have problems interpreting the file. Look at these lines:</p>
<pre><code>@ /usr/java/ibm-java2-x86_64-50/jre/bin/libj9prt23.so:[0x2b270a384a34] + 0x1502570 0x68
@ /usr/java/ibm-java2-x86_64-50/jre/bin/libj9prt23.so:[0x2b270a384a34] + 0x1502620 0x30
@ /usr/java/ibm-java2-x86_64-50/jre/bin/libj9prt23.so:[0x2b270a384a34] + 0x2aaab43a1700 0xa80
@ /usr/java/ibm-java2-x86_64-50/jre/bin/libj9prt23.so:[0x2b270a384a34] + 0x1501460 0xa64
</code></pre>
<p>The strange about this is that one call (same return address) is responsible for 4 allocations.</p>
<p>Even stranger:</p>
<pre><code>@ /usr/java/ibm-java2-x86_64-50/jre/bin/libj9prt23.so:[0x2b270a384a34] + 0x2aaab43a1700 0xa2c
…
@ /usr/java/ibm-java2-x86_64-50/jre/bin/libj9prt23.so:[0x2b270a384a34] + 0x2aaab43a1700 0xa80
</code></pre>
<p>Between those two lines the block 0x2aaab43a1700 is never being freed.</p>
<p>Does anyone know how to explain this? How could one call result in 4 allocations? And how could malloc return an address which was already allocated previously?</p>
<p>edit 2008/09/30:
The script to analyze the mtrace() output provided by GLIBC (mtrace.pl) isn't of any help here. It will just say: Alloc 0x2aaab43a1700 duplicate. But how could this happen?</p>
|
[
{
"answer_id": 154019,
"author": "florin",
"author_id": 18308,
"author_profile": "https://Stackoverflow.com/users/18308",
"pm_score": 0,
"selected": false,
"text": "<p>One possible explanation is that the same function is allocating different buffer sizes? One such example is strdup.</p>\n\n<p>For the second question, it is possible that the runtime is allocating some \"static\" scratch area which is not intended to be freed until the process is terminated. And at that point, the OS will clean-up after the process anyway.</p>\n\n<p>Think about it this way: in Java, there are no destructors, and no guarantees that finalization will be ever called for any object.</p>\n"
},
{
"answer_id": 154046,
"author": "twk",
"author_id": 23524,
"author_profile": "https://Stackoverflow.com/users/23524",
"pm_score": 0,
"selected": false,
"text": "<p>Try running your app under valgrind. It might give you a better view about what is actually being leaked.</p>\n"
},
{
"answer_id": 154419,
"author": "Sufian",
"author_id": 9241,
"author_profile": "https://Stackoverflow.com/users/9241",
"pm_score": 3,
"selected": false,
"text": "<p>You're looking at the direct output of mtrace, which is extremely confusing and counterintuitive. Luckily, there is a perl script (called mtrace, found within glibc-utils) which can very easily help the parsing of this output.</p>\n\n<p>Compile your build with debugging on, and run mtrace like such:</p>\n\n<pre><code>$ gcc -g -o test test.c\n$ MALLOC_TRACE=mtrace.out ./test\n$ mtrace test mtrace.out\n\nMemory not freed:\n-----------------\n Address Size Caller\n0x094d9378 0x400 at test.c:6\n</code></pre>\n\n<p>The output should be a <em>lot</em> easier to digest.</p>\n"
},
{
"answer_id": 168915,
"author": "Andrew Johnson",
"author_id": 5109,
"author_profile": "https://Stackoverflow.com/users/5109",
"pm_score": 4,
"selected": true,
"text": "<p>The function that is allocating the memory is being called more than once. The caller address points to the code that did the allocation, and that code is simply being run more than once.</p>\n\n<p>Here is an example in C:</p>\n\n<pre><code>void *allocate (void)\n{\n return (malloc(1000));\n}\n\nint main()\n{\n mtrace();\n allocate();\n allocate();\n}\n</code></pre>\n\n<p>The output from mtrace is:</p>\n\n<pre>\nMemory not freed:\n-----------------\n Address Size Caller\n0x0000000000601460 0x3e8 at 0x4004f6\n0x0000000000601850 0x3e8 at 0x4004f6\n</pre>\n\n<p>Note how the caller address is identical? This is why the mtrace analysing script is saying they are identical, because the same bug is being seen more that once, resulting in several memory leaks.</p>\n\n<p>Compiling with debugs flags (-g) is helpful if you can:</p>\n\n<pre>\nMemory not freed:\n-----------------\n Address Size Caller\n0x0000000000601460 0x3e8 at /home/andrjohn/development/playground/test.c:6\n0x0000000000601850 0x3e8 at /home/andrjohn/development/playground/test.c:6\n</pre>\n"
}
] |
2008/09/30
|
[
"https://Stackoverflow.com/questions/153953",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/17428/"
] |
I’m trying to debug a memory leak problem. I’m using [mtrace()](http://www.gnu.org/software/libc/manual/html_node/Tracing-malloc.html#Tracing-malloc) to get a malloc/free/realloc trace. I’ve ran my prog and have now a huge log file. So far so good. But I have problems interpreting the file. Look at these lines:
```
@ /usr/java/ibm-java2-x86_64-50/jre/bin/libj9prt23.so:[0x2b270a384a34] + 0x1502570 0x68
@ /usr/java/ibm-java2-x86_64-50/jre/bin/libj9prt23.so:[0x2b270a384a34] + 0x1502620 0x30
@ /usr/java/ibm-java2-x86_64-50/jre/bin/libj9prt23.so:[0x2b270a384a34] + 0x2aaab43a1700 0xa80
@ /usr/java/ibm-java2-x86_64-50/jre/bin/libj9prt23.so:[0x2b270a384a34] + 0x1501460 0xa64
```
The strange about this is that one call (same return address) is responsible for 4 allocations.
Even stranger:
```
@ /usr/java/ibm-java2-x86_64-50/jre/bin/libj9prt23.so:[0x2b270a384a34] + 0x2aaab43a1700 0xa2c
…
@ /usr/java/ibm-java2-x86_64-50/jre/bin/libj9prt23.so:[0x2b270a384a34] + 0x2aaab43a1700 0xa80
```
Between those two lines the block 0x2aaab43a1700 is never being freed.
Does anyone know how to explain this? How could one call result in 4 allocations? And how could malloc return an address which was already allocated previously?
edit 2008/09/30:
The script to analyze the mtrace() output provided by GLIBC (mtrace.pl) isn't of any help here. It will just say: Alloc 0x2aaab43a1700 duplicate. But how could this happen?
|
The function that is allocating the memory is being called more than once. The caller address points to the code that did the allocation, and that code is simply being run more than once.
Here is an example in C:
```
void *allocate (void)
{
return (malloc(1000));
}
int main()
{
mtrace();
allocate();
allocate();
}
```
The output from mtrace is:
```
Memory not freed:
-----------------
Address Size Caller
0x0000000000601460 0x3e8 at 0x4004f6
0x0000000000601850 0x3e8 at 0x4004f6
```
Note how the caller address is identical? This is why the mtrace analysing script is saying they are identical, because the same bug is being seen more that once, resulting in several memory leaks.
Compiling with debugs flags (-g) is helpful if you can:
```
Memory not freed:
-----------------
Address Size Caller
0x0000000000601460 0x3e8 at /home/andrjohn/development/playground/test.c:6
0x0000000000601850 0x3e8 at /home/andrjohn/development/playground/test.c:6
```
|
153,974 |
<p>I'm wondering how (un)common it is to encapsulate an algorithm into a class? More concretely, instead of having a number of separate functions that forward common parameters between each other:</p>
<pre><code>void f(int common1, int param1, int *out1);
void g(int common1, int common2, int param1, int *out2)
{
f(common1, param1, ..);
}
</code></pre>
<p>to encapsulate common parameters into a class and do all of the work in the constructor:</p>
<pre><code>struct Algo
{
int common1;
int common2;
Algo(int common1, int common2, int param)
{ // do most of the work }
void f(int param1, int *out1);
void g(int param1, int *out2);
};
</code></pre>
<p>It seems very practical not having to forward common parameters and intermediate results through function arguments.. But I haven't seen this "pattern" being widely used.. What are the possible downsides?</p>
|
[
{
"answer_id": 153984,
"author": "ctrlShiftBryan",
"author_id": 6161,
"author_profile": "https://Stackoverflow.com/users/6161",
"pm_score": 0,
"selected": false,
"text": "<p>If you would ever need to call both methods with the constructor parameters then i would do it.</p>\n\n<p>If you would never need to call both methods with the same parameters then I wouldn't.</p>\n"
},
{
"answer_id": 153990,
"author": "Esteban Araya",
"author_id": 781,
"author_profile": "https://Stackoverflow.com/users/781",
"pm_score": 3,
"selected": false,
"text": "<p>There's a design pattern that addresses the issue; it's called \"Strategy Design Pattern\" - you can find some good info on it <a href=\"http://www.dofactory.com/Patterns/PatternStrategy.aspx\" rel=\"nofollow noreferrer\">here</a>.</p>\n\n<p>The nice thing about \"Strategy\" is that it lets you define a family of algorithms and then use them interchangeably without having to modify the clients that use the algorithms.</p>\n"
},
{
"answer_id": 154001,
"author": "David Segonds",
"author_id": 13673,
"author_profile": "https://Stackoverflow.com/users/13673",
"pm_score": 1,
"selected": false,
"text": "<p>I usually create a functor or <a href=\"http://en.wikipedia.org/wiki/Function_object\" rel=\"nofollow noreferrer\">Function Object</a> to encapsulate my algorithms.</p>\n\n<p>I usually use the following template</p>\n\n<pre><code>class MyFunctor {\n public:\n MyFunctor( /* List of Parameters */ );\n bool execute();\n private:\n /* Local storage for parameters and intermediary data structures */\n}\n</code></pre>\n\n<p>Then I used my functors this way:</p>\n\n<pre><code> bool success = MyFunctor( /*Parameter*/ ).execute();\n</code></pre>\n"
},
{
"answer_id": 154025,
"author": "rpj",
"author_id": 23498,
"author_profile": "https://Stackoverflow.com/users/23498",
"pm_score": 4,
"selected": true,
"text": "<p>It's not a bad strategy at all. In fact, if you have the ability in your language (which you do in C++) to define some type of abstract superclass which defines an opaque interface to the underlying functionality, you can swap different algorithms in and out at runtime (think sorting algorithms, for example). If your chosen language has reflection, you can even have code that is infinitely extensible, allowing algorithms to be loaded and used that may not have even existed when the consumer of said algorithms was written. This also allows you to loosely couple your other functional classes and algorithmic classes, which is helpful in refactoring and in keeping your sanity intact when working on large projects.</p>\n\n<p>Of course, anytime you start to build a complex class structure, there will be extra architecture - and therefore code - that will need to be built and maintained. However, in my opinion the benefits in the long run outweigh this minor inconvenience.</p>\n\n<p>One final suggestion: <em>do not</em> do your work in the constructor. Constructors should only be used to initialize a classes internal structure to reasonable defaults. Yes, this may include calling other methods to finish initialization, but initialization is <em>not</em> operation. The two should be separate, even if it requires one more call in your code to run the particular algorithm you were looking for.</p>\n"
},
{
"answer_id": 154028,
"author": "Micah",
"author_id": 17744,
"author_profile": "https://Stackoverflow.com/users/17744",
"pm_score": 1,
"selected": false,
"text": "<p>Perhaps a better approach (unless I'm missing something) is to ecapsualte the algorithm in a class and have it execute through a method call. You can either pass in all the parameters to public properties, through a constructor, or create a struct that ecapsulates all the parameters that gets passed in to a class that contains the algorithm. But typically it's not a good idea to execute things in the constructor like that. First and foremost because it's not intuitive. </p>\n\n<pre><code>public class MyFooConfigurator\n{\n public MyFooConfigurator(string Param1, int, Param2) //Etc...\n {\n //Set all the internal properties here\n //Another option would also be to expose public properties that the user could\n //set from outside, or you could create a struct that ecapsulates all the\n //parameters.\n _Param1 = Param1; //etc...\n }\n\n Public ConfigureFoo()\n {\n If(!FooIsConfigured)\n return;\n Else\n //Process algorithm here.\n }\n}\n</code></pre>\n"
},
{
"answer_id": 154035,
"author": "Baltimark",
"author_id": 1179,
"author_profile": "https://Stackoverflow.com/users/1179",
"pm_score": 2,
"selected": false,
"text": "<p>Could your question be more generally phrased like, \"how do we use object oriented design when the main idea of the software is just running an algorithm?\"</p>\n\n<p>In that case, I think that a design like you offered is a good first step, but these things are often problem-dependent. </p>\n\n<p>I think a good general design is like what you have there. . .</p>\n\n<pre><code>class InputData {};\nclass OutputData {};\n\nclass TheAlgorithm \n{\nprivate:\n //functions and common data\n\npublic:\n TheAlgorithm(InputData); \n //other functions\n Run();\n ReturnOutputData();\n};\n</code></pre>\n\n<p>Then, let that interact with the main() or your GUI however you want. </p>\n"
}
] |
2008/09/30
|
[
"https://Stackoverflow.com/questions/153974",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2583/"
] |
I'm wondering how (un)common it is to encapsulate an algorithm into a class? More concretely, instead of having a number of separate functions that forward common parameters between each other:
```
void f(int common1, int param1, int *out1);
void g(int common1, int common2, int param1, int *out2)
{
f(common1, param1, ..);
}
```
to encapsulate common parameters into a class and do all of the work in the constructor:
```
struct Algo
{
int common1;
int common2;
Algo(int common1, int common2, int param)
{ // do most of the work }
void f(int param1, int *out1);
void g(int param1, int *out2);
};
```
It seems very practical not having to forward common parameters and intermediate results through function arguments.. But I haven't seen this "pattern" being widely used.. What are the possible downsides?
|
It's not a bad strategy at all. In fact, if you have the ability in your language (which you do in C++) to define some type of abstract superclass which defines an opaque interface to the underlying functionality, you can swap different algorithms in and out at runtime (think sorting algorithms, for example). If your chosen language has reflection, you can even have code that is infinitely extensible, allowing algorithms to be loaded and used that may not have even existed when the consumer of said algorithms was written. This also allows you to loosely couple your other functional classes and algorithmic classes, which is helpful in refactoring and in keeping your sanity intact when working on large projects.
Of course, anytime you start to build a complex class structure, there will be extra architecture - and therefore code - that will need to be built and maintained. However, in my opinion the benefits in the long run outweigh this minor inconvenience.
One final suggestion: *do not* do your work in the constructor. Constructors should only be used to initialize a classes internal structure to reasonable defaults. Yes, this may include calling other methods to finish initialization, but initialization is *not* operation. The two should be separate, even if it requires one more call in your code to run the particular algorithm you were looking for.
|
153,988 |
<p>I need to copy some records from our SQLServer 2005 test server to our live server. It's a flat lookup table, so no foreign keys or other referential integrity to worry about.</p>
<p>I could key-in the records again on the live server, but this is tiresome. I could export the test server records and table data in its entirety into an SQL script and run that, but I don't want to overwrite the records present on the live system, only add to them.</p>
<p>How can I select just the records I want and get them transferred or otherwise into the live server? We don't have Sharepoint, which I understand would allow me to copy them directly between the two instances.</p>
|
[
{
"answer_id": 154011,
"author": "Mitchel Sellers",
"author_id": 13279,
"author_profile": "https://Stackoverflow.com/users/13279",
"pm_score": 2,
"selected": false,
"text": "<p>An SSIS package would be best suited to do the transfer, it would take literally seconds to setup!</p>\n"
},
{
"answer_id": 154020,
"author": "Stephen Pellicer",
"author_id": 360,
"author_profile": "https://Stackoverflow.com/users/360",
"pm_score": 1,
"selected": false,
"text": "<p>I would just script to sql and run on the other server for quick and dirty transferring. If this is something that you will be doing often and you need to set up a mechanism, SQL Server Integration Services (SSIS) which is similar to the older Data Transformation Services (DTS) are designed for this sort of thing. You develop the solution in a mini-Visual Studio environment and can build very complex solutions for moving and transforming data.</p>\n"
},
{
"answer_id": 154026,
"author": "Joe Phillips",
"author_id": 20471,
"author_profile": "https://Stackoverflow.com/users/20471",
"pm_score": 4,
"selected": false,
"text": "<p>I use SQL Server Management Studio and do an Export Task by right-clicking the database and going to Task>Export. I think it works across servers as well as databases but I'm not sure.</p>\n"
},
{
"answer_id": 154071,
"author": "Kwirk",
"author_id": 21879,
"author_profile": "https://Stackoverflow.com/users/21879",
"pm_score": 7,
"selected": true,
"text": "<p>If your production SQL server and test SQL server can talk, you could just do in with a SQL insert statement.</p>\n\n<p>first run the following on your test server:</p>\n\n<pre><code>Execute sp_addlinkedserver PRODUCTION_SERVER_NAME\n</code></pre>\n\n<p>Then just create the insert statement:</p>\n\n<pre><code>INSERT INTO [PRODUCTION_SERVER_NAME].DATABASE_NAME.dbo.TABLE_NAME (Names_of_Columns_to_be_inserted)\nSELECT Names_of_Columns_to_be_inserted\nFROM TABLE_NAME\n</code></pre>\n"
}
] |
2008/09/30
|
[
"https://Stackoverflow.com/questions/153988",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7703/"
] |
I need to copy some records from our SQLServer 2005 test server to our live server. It's a flat lookup table, so no foreign keys or other referential integrity to worry about.
I could key-in the records again on the live server, but this is tiresome. I could export the test server records and table data in its entirety into an SQL script and run that, but I don't want to overwrite the records present on the live system, only add to them.
How can I select just the records I want and get them transferred or otherwise into the live server? We don't have Sharepoint, which I understand would allow me to copy them directly between the two instances.
|
If your production SQL server and test SQL server can talk, you could just do in with a SQL insert statement.
first run the following on your test server:
```
Execute sp_addlinkedserver PRODUCTION_SERVER_NAME
```
Then just create the insert statement:
```
INSERT INTO [PRODUCTION_SERVER_NAME].DATABASE_NAME.dbo.TABLE_NAME (Names_of_Columns_to_be_inserted)
SELECT Names_of_Columns_to_be_inserted
FROM TABLE_NAME
```
|
153,989 |
<p>I have a little logging app (written in wxPython) that receives data from a bit of kit we're developing, and I want to display the text in a scrolling window. As it stands I'm using a wx.TextCtrl for the text display, but I'm having some issues with the scrolling behaviour.</p>
<p>Basically, I'd like it so that if the scrollbar is at the bottom of the window (i.e. the end of the incoming data), adding more data should scroll the view onwards. If, however the view has been scrolled up a little (i.e. the user is looking at something interesting like an error message), the app should just add the text on the end without scrolling any more.</p>
<p>I've got two problems at the moment:</p>
<ol>
<li>I can't work out how to retrieve the current scroll position (calls to GetScrollPos() don't seem to work - they just return 0).</li>
<li>I can't work out how to retrieve the current range of the scroll bar (calls to GetScrollRange() just return 1).</li>
</ol>
<p>I've googled a bit and there seem to be a few hints that suggest GetScrollPos and GetScrollRange won't work for a wx.TextCtrl? Has anyone else had any experience in this area? Is there a nice easy way to solve the problem or am I going to have to roll my own wx.TextCtrl?</p>
|
[
{
"answer_id": 154225,
"author": "DzinX",
"author_id": 18745,
"author_profile": "https://Stackoverflow.com/users/18745",
"pm_score": 2,
"selected": true,
"text": "<p>I just tested a simple example (checking <code>GetScrollPos(0)</code> and <code>GetScrollRange(0)</code> in <code>EVT_TEXT</code> event handler for <code>wx.TextCtrl</code>) and it works fine for me - they return index of currently shown line and total number of lines, respectively.</p>\n\n<p>Maybe the problem is your wxPython version? I used:</p>\n\n<pre><code>>>> import wx\n>>> wx.version()\n'2.8.9.1 (msw-unicode)'\n</code></pre>\n"
},
{
"answer_id": 155781,
"author": "Jon Cage",
"author_id": 15369,
"author_profile": "https://Stackoverflow.com/users/15369",
"pm_score": 2,
"selected": false,
"text": "<p>Okay, so here's where I've got to:</p>\n\n<pre><code>import wx\nfrom threading import Timer\nimport time\n\nclass Form1(wx.Panel):\n def __init__(self, parent):\n wx.Panel.__init__(self, parent)\n\n self.logger = wx.TextCtrl(self,5, \"\",wx.Point(20,20), wx.Size(200,200), \\\n wx.TE_MULTILINE | wx.TE_READONLY)# | wx.TE_RICH2)\n\n t = Timer(0.1, self.AddText)\n t.start()\n\n def AddText(self):\n # Resart the timer\n t = Timer(0.25, self.AddText)\n t.start() \n\n # Work out if we're at the end of the file\n currentCaretPosition = self.logger.GetInsertionPoint()\n currentLengthOfText = self.logger.GetLastPosition()\n if currentCaretPosition != currentLengthOfText:\n self.holdingBack = True\n else:\n self.holdingBack = False\n\n timeStamp = str(time.time())\n\n # If we're not at the end of the file, we're holding back\n if self.holdingBack:\n print \"%s FROZEN\"%(timeStamp)\n self.logger.Freeze()\n (currentSelectionStart, currentSelectionEnd) = self.logger.GetSelection()\n self.logger.AppendText(timeStamp+\"\\n\")\n self.logger.SetInsertionPoint(currentCaretPosition)\n self.logger.SetSelection(currentSelectionStart, currentSelectionEnd)\n self.logger.Thaw()\n else:\n print \"%s THAWED\"%(timeStamp)\n self.logger.AppendText(timeStamp+\"\\n\")\n\napp = wx.PySimpleApp()\nframe = wx.Frame(None, size=(550,425))\nForm1(frame)\nframe.Show(1)\napp.MainLoop()\n</code></pre>\n\n<p>This simple demo app works almost perfectly. It scrolls neatly unless the user clicks a line which isn't at the end of the text. Thereafter it stays nice and still so you can select text (note: there's still a bug there in that if you select up not down it clears your selection).</p>\n\n<p>The biggest annoyance is that if I try and enable the \"| wx.TE_RICH2\" option, it all goes a bit pear-shaped. I really need this to do syntax highlighting of errors, but if I can't enable that option, I'm doomed to monochrome - boo!</p>\n\n<p>Any more ideas on how to hold back scrolling on the rich edit control?</p>\n"
}
] |
2008/09/30
|
[
"https://Stackoverflow.com/questions/153989",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/15369/"
] |
I have a little logging app (written in wxPython) that receives data from a bit of kit we're developing, and I want to display the text in a scrolling window. As it stands I'm using a wx.TextCtrl for the text display, but I'm having some issues with the scrolling behaviour.
Basically, I'd like it so that if the scrollbar is at the bottom of the window (i.e. the end of the incoming data), adding more data should scroll the view onwards. If, however the view has been scrolled up a little (i.e. the user is looking at something interesting like an error message), the app should just add the text on the end without scrolling any more.
I've got two problems at the moment:
1. I can't work out how to retrieve the current scroll position (calls to GetScrollPos() don't seem to work - they just return 0).
2. I can't work out how to retrieve the current range of the scroll bar (calls to GetScrollRange() just return 1).
I've googled a bit and there seem to be a few hints that suggest GetScrollPos and GetScrollRange won't work for a wx.TextCtrl? Has anyone else had any experience in this area? Is there a nice easy way to solve the problem or am I going to have to roll my own wx.TextCtrl?
|
I just tested a simple example (checking `GetScrollPos(0)` and `GetScrollRange(0)` in `EVT_TEXT` event handler for `wx.TextCtrl`) and it works fine for me - they return index of currently shown line and total number of lines, respectively.
Maybe the problem is your wxPython version? I used:
```
>>> import wx
>>> wx.version()
'2.8.9.1 (msw-unicode)'
```
|
153,994 |
<p>I want to have a class which implements an interface, which specifies the specific subclass as a parameter.</p>
<pre><code>public abstract Task implements TaskStatus<Task> {
TaskStatus<T> listener;
protected complete() {
// ugly, unsafe cast
callback.complete((T) this);
}
}
public interface TaskStatus<T> {
public void complete(T task);
}
</code></pre>
<p>But instead of just task, or , I want to guarantee the type-arg used is that of the specific class extending this one.</p>
<p>So the best I've come up with is:</p>
<pre><code>public abstract Task<T extends Task> implements TaskStatus<T> {
}
</code></pre>
<p>You'd extend that by writing:</p>
<pre><code>public class MyTask extends Task<MyTask> {
}
</code></pre>
<p>But this would also be valid:</p>
<pre><code>public class MyTask extends Task<SomeOtherTask> {
}
</code></pre>
<p>And the invocation of callback will blow up with ClassCastException. So, is this approach just wrong and broken, or is there a right way to do this I've somehow missed?</p>
|
[
{
"answer_id": 154340,
"author": "Bruno De Fraine",
"author_id": 6918,
"author_profile": "https://Stackoverflow.com/users/6918",
"pm_score": 3,
"selected": true,
"text": "<p>It is not clear what you are trying to do inside of <code>Task</code>. However, if you define the generic class <code>Task<T></code> as follows:</p>\n\n<pre><code>class Task<T extends Task<T>> { ... }\n</code></pre>\n\n<p>The following two are possible:</p>\n\n<pre><code>class MyTask extends Task<MyTask> { ... }\nclass YourTask extends Task<MyTask> { ... }\n</code></pre>\n\n<p>But the following is prohibited:</p>\n\n<pre><code>class MyTask extends Task<String> { ... }\n</code></pre>\n\n<p>The above definition of <code>Task</code> uses F-bounded polymorphism, a rather advanced feature. You can check the research paper \"<a href=\"http://www.cs.utexas.edu/~wcook/papers/FBound89/CookFBound89.pdf\" rel=\"nofollow noreferrer\">F-bounded polymorphism for object-oriented programming</a>\" for more information.</p>\n"
},
{
"answer_id": 154361,
"author": "David Smith",
"author_id": 17201,
"author_profile": "https://Stackoverflow.com/users/17201",
"pm_score": 0,
"selected": false,
"text": "<p>I'm having a little trouble understanding what you're trying to accomplish through this. Could you provide some more details?</p>\n\n<p>My read of the code says you have these tasks which will be sub-classed and after the tasks are complete, the executing thread will call complete() on the task. At this point you want to call a callback and pass it the sub-class object. I think this is the problem. You are trying to put knowledge of the potential sub-classes into your abstract class which is a no-no.</p>\n\n<p>This also raises the question of, if you could make this call, what is the callback going to do with the sub-class that would be different from the superclass?</p>\n"
},
{
"answer_id": 154363,
"author": "Tom Hawtin - tackline",
"author_id": 4725,
"author_profile": "https://Stackoverflow.com/users/4725",
"pm_score": 1,
"selected": false,
"text": "<p>I suggest adding a getThis which should return this appropriately typed. Sure a subclas could misbehave, but that's always true. What you avoid is the cast and the possibility of a ClassCastException.</p>\n\n<pre><code>public abstract class Task<THIS extends Task<THIS>> {\n private TaskStatus<THIS> callback;\n\n public void setCallback(TaskStatus<THIS> callback) {\n this.callback = callback==null ? NullCallback.INSTANCE : callback;\n }\n\n protected void complete() {\n // ugly, unsafe cast\n callback.complete(getThis());\n }\n\n protected abstract THIS getThis();\n}\n\npublic interface TaskStatus<T/* extends Task<T>*/> {\n void complete(T task);\n}\n\npublic class MyTask extends Task<MyTask> {\n @Override protected MyTask getThis() {\n return this;\n }\n}\n</code></pre>\n\n<p>This problem often comes up with builders.</p>\n"
},
{
"answer_id": 154367,
"author": "Staale",
"author_id": 3355,
"author_profile": "https://Stackoverflow.com/users/3355",
"pm_score": 0,
"selected": false,
"text": "<p>I can really only see this working if you in the constructor enforce the type arg. Via. introspection and the Class.getSuperType() you can inspect the type args, and verify that the type arg matches this class.</p>\n\n<p>Somthing along the lines of:</p>\n\n<pre><code>assert getClass() == ((ParameterizedType) getSuperType()).getTypeArguments()[0];\n</code></pre>\n\n<p>(This is from the top off my head, check JavaDocs to verify).</p>\n\n<p>I am not sure where callback is created though in your code. You have omitted it's declaration in the top.</p>\n\n<p>A different route would be to remove the unsafe cast, as atm. I can't see the full flow to spot why you need the unsafe cast.</p>\n"
}
] |
2008/09/30
|
[
"https://Stackoverflow.com/questions/153994",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/758/"
] |
I want to have a class which implements an interface, which specifies the specific subclass as a parameter.
```
public abstract Task implements TaskStatus<Task> {
TaskStatus<T> listener;
protected complete() {
// ugly, unsafe cast
callback.complete((T) this);
}
}
public interface TaskStatus<T> {
public void complete(T task);
}
```
But instead of just task, or , I want to guarantee the type-arg used is that of the specific class extending this one.
So the best I've come up with is:
```
public abstract Task<T extends Task> implements TaskStatus<T> {
}
```
You'd extend that by writing:
```
public class MyTask extends Task<MyTask> {
}
```
But this would also be valid:
```
public class MyTask extends Task<SomeOtherTask> {
}
```
And the invocation of callback will blow up with ClassCastException. So, is this approach just wrong and broken, or is there a right way to do this I've somehow missed?
|
It is not clear what you are trying to do inside of `Task`. However, if you define the generic class `Task<T>` as follows:
```
class Task<T extends Task<T>> { ... }
```
The following two are possible:
```
class MyTask extends Task<MyTask> { ... }
class YourTask extends Task<MyTask> { ... }
```
But the following is prohibited:
```
class MyTask extends Task<String> { ... }
```
The above definition of `Task` uses F-bounded polymorphism, a rather advanced feature. You can check the research paper "[F-bounded polymorphism for object-oriented programming](http://www.cs.utexas.edu/~wcook/papers/FBound89/CookFBound89.pdf)" for more information.
|
154,004 |
<p>I have a link that I dynamically create which looks something like the following:</p>
<pre><code><a onclick="Edit('value from a text column here')" href="javascript:void(null);">Edit</a>
</code></pre>
<p>with the Edit function then taking the passed in value and putting it into a Yahoo Rich Text Editor. This works well except for when there is a single quote in the text being passed. The obvious problem being that the link then looks something like:</p>
<pre><code><a onclick="Edit('I'm a jelly donut')" href="javascript:void(null);">Edit</a>
</code></pre>
<p>Any suggestions on what I can do? I'd rather not stray too far from the structure I am currently using because it is something of a standard (and maybe the standard sucks, but that's another question altogether).</p>
<p>Note: I am using ASP as my server side language.</p>
|
[
{
"answer_id": 154018,
"author": "Chris Johnson",
"author_id": 23732,
"author_profile": "https://Stackoverflow.com/users/23732",
"pm_score": 5,
"selected": true,
"text": "<p>Convert quote charaters to their HTML equivalents, <code>&quot;</code> etc. before you insert them into the HTML. There's a <a href=\"http://en.wikipedia.org/wiki/List_of_XML_and_HTML_character_entity_references\" rel=\"noreferrer\">long list</a> of HTML/XML character codes on wikipedia. </p>\n\n<p>There may well be a function to do this for you, depending on how you're dynamically generating the code: PHP has <a href=\"http://uk.php.net/htmlspecialchars\" rel=\"noreferrer\">htmlspecialchars</a>, and though I'm not familiar with ASP etc, I'm sure there are similar routines.</p>\n"
},
{
"answer_id": 154044,
"author": "Anthony Potts",
"author_id": 22777,
"author_profile": "https://Stackoverflow.com/users/22777",
"pm_score": 0,
"selected": false,
"text": "<p>So it seems there was more going on, most of these would probably work under most circumstances, but in the interest of posterity here's what I had to do. </p>\n\n<p>The information being pulled into the Rich Text Editor was in a YUI datatable and I am creating a link using the custom formatter prototype for said control. </p>\n\n<p>The problem with using the \"Replace ' with \\' \" method was that I need to still view the text being displayed in the datatable the same way. </p>\n\n<p>The problem with using the ASP equivalent of htmlspecialchars (Server.HTMLEncode) was that it still had a problem in the javascript that was being generated from the custom formatter function. I don't know why exactly, but I did try it and it didn't work. That answer was closest to the answer that I came up with (and pushed me in the right direction) so I accepted that answer. </p>\n\n<p>What I did instead was used the javascript function 'escape' to pass into my edit function, and then unescape to set the inner HTML for the Rich Text Editor.</p>\n"
},
{
"answer_id": 154070,
"author": "Peter Wildani",
"author_id": 23825,
"author_profile": "https://Stackoverflow.com/users/23825",
"pm_score": 1,
"selected": false,
"text": "<p>Run the text through an escape function to put a \\ before the '. If you're generating the link on the server, we would need to know what server-side language you're using to give more specific advice.</p>\n\n<p>If you're generating the tag client-side as a string in javascript (don't do that, use document.createElement), use the <a href=\"http://www.w3schools.com/jsref/jsref_replace.asp\" rel=\"nofollow noreferrer\" >String.replace</a> method on the argument string to pick out characters that will break the syntax you're generating and replace them with escaped versions.</p>\n"
},
{
"answer_id": 154072,
"author": "Lasar",
"author_id": 9438,
"author_profile": "https://Stackoverflow.com/users/9438",
"pm_score": 2,
"selected": false,
"text": "<p>You could just replace the ' with \\'</p>\n"
},
{
"answer_id": 155095,
"author": "paercebal",
"author_id": 14089,
"author_profile": "https://Stackoverflow.com/users/14089",
"pm_score": 1,
"selected": false,
"text": "<p>I see at least three additional possibilities:</p>\n<h3>JavaScript Unicode escape</h3>\n<pre><code><a onclick="Edit('I\\u0027m a jelly donut')" href="javascript:void(null);">Edit</a>\n</code></pre>\n<p>as \\u0027 is the javascript espace character for the quote. The others being less practical:</p>\n<h3>JavaScript function</h3>\n<pre><code><script>function getQuote() { return "'" }</script>\n<a onclick="Edit('I' + getQuote() + 'm a jelly donut')" href="javascript:void(null);">Edit</a>\n</code></pre>\n<p>and:</p>\n<h3>JavaScript global variable</h3>\n<pre><code><script>var g_strJellyText = "I\\u0027m a jelly donut"</script>\n<a onclick="Edit(g_strJellyText)" href="javascript:void(null);">Edit</a>\n</code></pre>\n<p>But I believe you already considered theses solution (or their variants, or the HTML entity escape mentionned by Chris Johnson).</p>\n<p>Still, it's worth mentioning.</p>\n"
}
] |
2008/09/30
|
[
"https://Stackoverflow.com/questions/154004",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/22777/"
] |
I have a link that I dynamically create which looks something like the following:
```
<a onclick="Edit('value from a text column here')" href="javascript:void(null);">Edit</a>
```
with the Edit function then taking the passed in value and putting it into a Yahoo Rich Text Editor. This works well except for when there is a single quote in the text being passed. The obvious problem being that the link then looks something like:
```
<a onclick="Edit('I'm a jelly donut')" href="javascript:void(null);">Edit</a>
```
Any suggestions on what I can do? I'd rather not stray too far from the structure I am currently using because it is something of a standard (and maybe the standard sucks, but that's another question altogether).
Note: I am using ASP as my server side language.
|
Convert quote charaters to their HTML equivalents, `"` etc. before you insert them into the HTML. There's a [long list](http://en.wikipedia.org/wiki/List_of_XML_and_HTML_character_entity_references) of HTML/XML character codes on wikipedia.
There may well be a function to do this for you, depending on how you're dynamically generating the code: PHP has [htmlspecialchars](http://uk.php.net/htmlspecialchars), and though I'm not familiar with ASP etc, I'm sure there are similar routines.
|
154,013 |
<p>My Django app has a Person table, which contains the following text in a field named <code>details</code>:</p>
<p><code><script>alert('Hello');</script></code></p>
<p>When I call <code>PersonForm.details</code> in my template, the page renders the script accordingly (a.k.a., an alert with the word "Hello" is displayed). I'm confused by this behavior because I always thought <a href="http://docs.djangoproject.com/en/dev/ref/templates/builtins/?from=olddocs" rel="nofollow noreferrer">Django 1.0 autoescaped</a> template content by default.</p>
<p>Any idea what may be going on here?</p>
<p><strong>UPDATE:</strong> Here's the snippet from my template. Nothing terribly sexy:</p>
<pre><code>{{ person_form.details }}
</code></pre>
<p><strong>UPDATE 2:</strong> I have tried <code>escape</code>, <code>force-escape</code>, and <code>escapejs</code>. None of these work.</p>
|
[
{
"answer_id": 154027,
"author": "Jon Cage",
"author_id": 15369,
"author_profile": "https://Stackoverflow.com/users/15369",
"pm_score": 4,
"selected": true,
"text": "<p>You need to mark the values as | safe I think (I'm guessing that you're filling in the value from the database here(?)):</p>\n\n<pre><code>{{ value|safe }}\n</code></pre>\n\n<p>Could you post a sample of the template? Might make it easier to see what's wrong</p>\n\n<p><strong>[Edit]</strong> ..or are you saying that you <em>want</em> it to escape the values (make them safe)? Have you tried manually escaping the field:</p>\n\n<pre><code>{{ value|escape }}\n</code></pre>\n\n<p><strong>[Edit2]</strong> Maybe <a href=\"http://docs.djangoproject.com/en/dev/ref/templates/builtins/?from=olddocs#escapejs\" rel=\"noreferrer\">escapejs from the Django Project docs</a> is relevent:</p>\n\n<pre><code>escapejs\n\nNew in Django 1.0.\n\nEscapes characters for use in JavaScript strings. This does not make the string safe for use in HTML, but does protect you from syntax errors when using templates to generate JavaScript/JSON.\n</code></pre>\n\n<p><strong>[Edit3]</strong> What about force_escape:</p>\n\n<pre><code> {{ value|force_escape }}\n</code></pre>\n\n<p>...and I know it's an obvious one, but you're absolutely certain you've not got any caching going on in your browser? I've tripped over that one a few times myself ;-)</p>\n"
},
{
"answer_id": 154095,
"author": "Huuuze",
"author_id": 10040,
"author_profile": "https://Stackoverflow.com/users/10040",
"pm_score": 0,
"selected": false,
"text": "<p>Found the problem. The JSON string I'm using to render data to some Ext widgets is the culprit. Big thanks to Jon Cage. Answer accepted despite the problem being caused by another source.</p>\n"
}
] |
2008/09/30
|
[
"https://Stackoverflow.com/questions/154013",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/10040/"
] |
My Django app has a Person table, which contains the following text in a field named `details`:
`<script>alert('Hello');</script>`
When I call `PersonForm.details` in my template, the page renders the script accordingly (a.k.a., an alert with the word "Hello" is displayed). I'm confused by this behavior because I always thought [Django 1.0 autoescaped](http://docs.djangoproject.com/en/dev/ref/templates/builtins/?from=olddocs) template content by default.
Any idea what may be going on here?
**UPDATE:** Here's the snippet from my template. Nothing terribly sexy:
```
{{ person_form.details }}
```
**UPDATE 2:** I have tried `escape`, `force-escape`, and `escapejs`. None of these work.
|
You need to mark the values as | safe I think (I'm guessing that you're filling in the value from the database here(?)):
```
{{ value|safe }}
```
Could you post a sample of the template? Might make it easier to see what's wrong
**[Edit]** ..or are you saying that you *want* it to escape the values (make them safe)? Have you tried manually escaping the field:
```
{{ value|escape }}
```
**[Edit2]** Maybe [escapejs from the Django Project docs](http://docs.djangoproject.com/en/dev/ref/templates/builtins/?from=olddocs#escapejs) is relevent:
```
escapejs
New in Django 1.0.
Escapes characters for use in JavaScript strings. This does not make the string safe for use in HTML, but does protect you from syntax errors when using templates to generate JavaScript/JSON.
```
**[Edit3]** What about force\_escape:
```
{{ value|force_escape }}
```
...and I know it's an obvious one, but you're absolutely certain you've not got any caching going on in your browser? I've tripped over that one a few times myself ;-)
|
154,031 |
<pre><code>Pattern pattern = Pattern.compile("^[a-z]+$");
String string = "abc-def";
assertTrue( pattern.matcher(string).matches() ); // obviously fails
</code></pre>
<p>Is it possible to have the character class match a "-" ?</p>
|
[
{
"answer_id": 154037,
"author": "albertein",
"author_id": 23020,
"author_profile": "https://Stackoverflow.com/users/23020",
"pm_score": 3,
"selected": false,
"text": "<p>Escape the minus sign</p>\n\n<pre><code>[a-z\\\\-]\n</code></pre>\n"
},
{
"answer_id": 154040,
"author": "Tomalak",
"author_id": 18771,
"author_profile": "https://Stackoverflow.com/users/18771",
"pm_score": 6,
"selected": true,
"text": "<p>Don't put the minus sign between characters.</p>\n\n<pre><code>\"[a-z-]\"\n</code></pre>\n"
},
{
"answer_id": 154061,
"author": "Michael Easter",
"author_id": 12704,
"author_profile": "https://Stackoverflow.com/users/12704",
"pm_score": 2,
"selected": false,
"text": "<p>This works for me</p>\n\n<pre><code> Pattern p = Pattern.compile(\"^[a-z\\\\-]+$\");\n String line = \"abc-def\";\n Matcher matcher = p.matcher(line);\n System.out.println(matcher.matches()); // true\n</code></pre>\n"
},
{
"answer_id": 154274,
"author": "John M",
"author_id": 20734,
"author_profile": "https://Stackoverflow.com/users/20734",
"pm_score": 2,
"selected": false,
"text": "<p>I'd rephrase the \"don't put it between characters\" a little more concretely.</p>\n\n<p>Make the dash the first or last character in the character class. For example \"[-a-z1-9]\" matches lower-case characters, digits or dash.</p>\n"
},
{
"answer_id": 4223458,
"author": "codaddict",
"author_id": 227665,
"author_profile": "https://Stackoverflow.com/users/227665",
"pm_score": 3,
"selected": false,
"text": "<p>Inside a character class <code>[...]</code> a <code>-</code> is treated specially(as a range operator) <strong>if</strong> it's surrounded by characters on both sides. That means if you include the <code>-</code> at the beginning or at the end of the character class it will be treated literally(non-special). </p>\n\n<p>So you can use the regex:</p>\n\n<pre><code>^[a-z-]+$\n</code></pre>\n\n<p>or</p>\n\n<pre><code>^[-a-z]+$\n</code></pre>\n\n<p>Since the <code>-</code> that we added is being treated literally there is no need to escape it. Although it's not an error if you do it.</p>\n\n<p>Another (less recommended) way is to not include the <code>-</code> in the character class:</p>\n\n<pre><code>^(?:[a-z]|-)+$\n</code></pre>\n\n<p>Note that the parenthesis are not optional in this case as <code>|</code> has a very low precedence, so with the parenthesis:</p>\n\n<pre><code>^[a-z]|-+$\n</code></pre>\n\n<p>Will match a lowercase alphabet at the beginning of the string and one or more <code>-</code> at the end.</p>\n"
}
] |
2008/09/30
|
[
"https://Stackoverflow.com/questions/154031",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11858/"
] |
```
Pattern pattern = Pattern.compile("^[a-z]+$");
String string = "abc-def";
assertTrue( pattern.matcher(string).matches() ); // obviously fails
```
Is it possible to have the character class match a "-" ?
|
Don't put the minus sign between characters.
```
"[a-z-]"
```
|
154,042 |
<p>I'm using spring 2.5 and annotations to configure my spring-mvc web context. Unfortunately, I am unable to get the following to work. I'm not sure if this is a bug (seems like it) or if there is a basic misunderstanding on how the annotations and interface implementation subclassing works.</p>
<p>For example,</p>
<pre><code>@Controller
@RequestMapping("url-mapping-here")
public class Foo {
@RequestMapping(method=RequestMethod.GET)
public void showForm() {
...
}
@RequestMapping(method=RequestMethod.POST)
public String processForm() {
...
}
}
</code></pre>
<p>works fine. When the context starts up, the urls this handler deals with are discovered, and everything works great. </p>
<p>This however does not:</p>
<pre><code>@Controller
@RequestMapping("url-mapping-here")
public class Foo implements Bar {
@RequestMapping(method=RequestMethod.GET)
public void showForm() {
...
}
@RequestMapping(method=RequestMethod.POST)
public String processForm() {
...
}
}
</code></pre>
<p>When I try to pull up the url, I get the following nasty stack trace:</p>
<pre><code>javax.servlet.ServletException: No adapter for handler [com.shaneleopard.web.controller.RegistrationController@e973e3]: Does your handler implement a supported interface like Controller?
org.springframework.web.servlet.DispatcherServlet.getHandlerAdapter(DispatcherServlet.java:1091)
org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:874)
org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:809)
org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:571)
org.springframework.web.servlet.FrameworkServlet.doGet(FrameworkServlet.java:501)
javax.servlet.http.HttpServlet.service(HttpServlet.java:627)
</code></pre>
<p>However, if I change Bar to be an abstract superclass and have Foo extend it, then it works again.</p>
<pre><code>@Controller
@RequestMapping("url-mapping-here")
public class Foo extends Bar {
@RequestMapping(method=RequestMethod.GET)
public void showForm() {
...
}
@RequestMapping(method=RequestMethod.POST)
public String processForm() {
...
}
}
</code></pre>
<p>This seems like a bug. The @Controller annotation should be sufficient to mark this as a controller, and I should be able to implement one or more interfaces in my controller without having to do anything else. Any ideas?</p>
|
[
{
"answer_id": 355234,
"author": "Ed Thomas",
"author_id": 8256,
"author_profile": "https://Stackoverflow.com/users/8256",
"pm_score": 3,
"selected": false,
"text": "<p>There's no doubt that annotations and inheritance can get a little tricky, but I think that should work. Try explicitly adding the AnnotationMethodHandlerAdapter to your servlet context.</p>\n\n<p><a href=\"http://static.springframework.org/spring/docs/2.5.x/reference/mvc.html#mvc-ann-setup\" rel=\"nofollow noreferrer\">http://static.springframework.org/spring/docs/2.5.x/reference/mvc.html#mvc-ann-setup</a></p>\n\n<p>If that doesn't work, a little more information would be helpful. Specifically, are the two annotated controller methods from the interface? Is Foo supposed to be RegistrationController?</p>\n"
},
{
"answer_id": 2358726,
"author": "Michal Bachman",
"author_id": 220912,
"author_profile": "https://Stackoverflow.com/users/220912",
"pm_score": 4,
"selected": false,
"text": "<p>Ed is right, adding</p>\n\n<pre><code><bean class=\"org.springframework.web.servlet.mvc.annotation.DefaultAnnotationHandlerMapping\"/>\n<bean class=\"org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter\"/>\n</code></pre>\n\n<p>works fine</p>\n"
},
{
"answer_id": 3190630,
"author": "James Kingsbery",
"author_id": 72908,
"author_profile": "https://Stackoverflow.com/users/72908",
"pm_score": 4,
"selected": false,
"text": "<p>What I needed to do was replace</p>\n\n<pre><code> <tx:annotation-driven/>\n</code></pre>\n\n<p>with</p>\n\n<pre><code> <tx:annotation-driven proxy-target-class=\"true\"/>\n</code></pre>\n\n<p>This forces aspectj to use CGLIB for doing aspects instead of dynamic proxies - CGLIB doesn't lose the annotation since it extends the class, whereas dynamic proxies just expose the implemented interface.</p>\n"
},
{
"answer_id": 3645511,
"author": "Boris Kirzner",
"author_id": 421113,
"author_profile": "https://Stackoverflow.com/users/421113",
"pm_score": 0,
"selected": false,
"text": "<p>The true reason you need to use 'proxy-target-class=\"true\"' is in <code>DefaultAnnotationHandlerMapping#determineUrlsForHandler()</code> method: though it uses <code>ListableBeanFactory#findAnnotationOnBean</code> for looking up a <code>@RequestMapping</code> annotation (and this takes care about any proxy issues), the additional lookup for <code>@Controller</code> annotation is done using <code>AnnotationUtils#findAnnotation</code> (which does not handles proxy issues)</p>\n"
},
{
"answer_id": 13029177,
"author": "Kieran",
"author_id": 314901,
"author_profile": "https://Stackoverflow.com/users/314901",
"pm_score": 3,
"selected": false,
"text": "<p>If you wish to use interfaces for your Spring MVC controllers then you need to move the annotations around a bit, as mentioned in the Spring docs: <a href=\"http://static.springsource.org/spring/docs/3.1.x/spring-framework-reference/html/mvc.html#mvc-ann-requestmapping\" rel=\"noreferrer\">http://static.springsource.org/spring/docs/3.1.x/spring-framework-reference/html/mvc.html#mvc-ann-requestmapping</a></p>\n\n<blockquote>\n <p>Using @RequestMapping On Interface Methods A common pitfall when\n working with annotated controller classes happens when applying\n functionality that requires creating a proxy for the controller object\n (e.g. @Transactional methods). Usually you will introduce an interface\n for the controller in order to use JDK dynamic proxies. To make this\n work you must move the @RequestMapping annotations to the interface as\n well as the mapping mechanism can only \"see\" the interface exposed by\n the proxy. Alternatively, you could activate proxy-target-class=\"true\"\n in the configuration for the functionality applied to the controller\n (in our transaction scenario in ). Doing so\n indicates that CGLIB-based subclass proxies should be used instead of\n interface-based JDK proxies. For more information on various proxying\n mechanisms see Section 8.6, “Proxying mechanisms”.</p>\n</blockquote>\n\n<p>Unfortunately it doesn't give a concrete example of this. I have found a setup like this works:</p>\n\n<pre><code>@Controller\n@RequestMapping(value = \"/secure/exhibitor\")\npublic interface ExhibitorController {\n\n @RequestMapping(value = \"/{id}\")\n void exhibitor(@PathVariable(\"id\") Long id);\n}\n\n@Controller\npublic class ExhibitorControllerImpl implements ExhibitorController {\n\n @Secured({\"ROLE_EXHIBITOR\"})\n @Transactional(readOnly = true)\n @Override\n public void exhibitor(final Long id) {\n\n }\n}\n</code></pre>\n\n<p>So what you have here is an interface that declares the @Controller, @PathVariable and @RequestMapping annotations (the Spring MVC annotations) and then you can either put your @Transactional or @Secured annotations for instance on the concrete class. It is only the @Controller type annotations that you need to put on the interface because of the way Spring does its mappings.</p>\n\n<p>Note that you only need to do this if you use an interface. You don't necessarily need to do it if you are happy with CGLib proxies, but if for some reason you want to use JDK dynamic proxies, this might be the way to go.</p>\n"
},
{
"answer_id": 36590758,
"author": "Amir",
"author_id": 2260172,
"author_profile": "https://Stackoverflow.com/users/2260172",
"pm_score": 3,
"selected": false,
"text": "<p>I know it is too late but i'm writing this for anyone have this problem \nif you are using annotation based configuration... the solution might be like this:</p>\n\n<pre><code>@Configuration\n@ComponentScan(\"org.foo.controller.*\")\n@EnableAspectJAutoProxy(proxyTargetClass=true)\npublic class AppConfig { ...}\n</code></pre>\n"
}
] |
2008/09/30
|
[
"https://Stackoverflow.com/questions/154042",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9955/"
] |
I'm using spring 2.5 and annotations to configure my spring-mvc web context. Unfortunately, I am unable to get the following to work. I'm not sure if this is a bug (seems like it) or if there is a basic misunderstanding on how the annotations and interface implementation subclassing works.
For example,
```
@Controller
@RequestMapping("url-mapping-here")
public class Foo {
@RequestMapping(method=RequestMethod.GET)
public void showForm() {
...
}
@RequestMapping(method=RequestMethod.POST)
public String processForm() {
...
}
}
```
works fine. When the context starts up, the urls this handler deals with are discovered, and everything works great.
This however does not:
```
@Controller
@RequestMapping("url-mapping-here")
public class Foo implements Bar {
@RequestMapping(method=RequestMethod.GET)
public void showForm() {
...
}
@RequestMapping(method=RequestMethod.POST)
public String processForm() {
...
}
}
```
When I try to pull up the url, I get the following nasty stack trace:
```
javax.servlet.ServletException: No adapter for handler [com.shaneleopard.web.controller.RegistrationController@e973e3]: Does your handler implement a supported interface like Controller?
org.springframework.web.servlet.DispatcherServlet.getHandlerAdapter(DispatcherServlet.java:1091)
org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:874)
org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:809)
org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:571)
org.springframework.web.servlet.FrameworkServlet.doGet(FrameworkServlet.java:501)
javax.servlet.http.HttpServlet.service(HttpServlet.java:627)
```
However, if I change Bar to be an abstract superclass and have Foo extend it, then it works again.
```
@Controller
@RequestMapping("url-mapping-here")
public class Foo extends Bar {
@RequestMapping(method=RequestMethod.GET)
public void showForm() {
...
}
@RequestMapping(method=RequestMethod.POST)
public String processForm() {
...
}
}
```
This seems like a bug. The @Controller annotation should be sufficient to mark this as a controller, and I should be able to implement one or more interfaces in my controller without having to do anything else. Any ideas?
|
Ed is right, adding
```
<bean class="org.springframework.web.servlet.mvc.annotation.DefaultAnnotationHandlerMapping"/>
<bean class="org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter"/>
```
works fine
|
154,059 |
<p>Is there a <code>string.Empty</code> in JavaScript, or is it just a case of checking for <code>""</code>?</p>
|
[
{
"answer_id": 154068,
"author": "bdukes",
"author_id": 2688,
"author_profile": "https://Stackoverflow.com/users/2688",
"pm_score": 13,
"selected": true,
"text": "<h3>Empty string, undefined, null, ...</h3>\n<p>To check for a <a href=\"https://developer.mozilla.org/en-US/docs/Glossary/Truthy\" rel=\"noreferrer\">truthy value</a>:</p>\n<pre><code>if (strValue) {\n // strValue was non-empty string, true, 42, Infinity, [], ...\n}\n</code></pre>\n<p>To check for a <a href=\"https://developer.mozilla.org/en-US/docs/Glossary/Falsy\" rel=\"noreferrer\">falsy value</a>:</p>\n<pre><code>if (!strValue) {\n // strValue was empty string, false, 0, null, undefined, ...\n}\n</code></pre>\n<hr />\n<h3>Empty string (only!)</h3>\n<p>To check for exactly an empty string, compare for strict equality against <code>""</code> using the <a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Strict_equality\" rel=\"noreferrer\"><code>===</code> operator</a>:</p>\n<pre><code>if (strValue === "") {\n // strValue was empty string\n}\n</code></pre>\n<p>To check for not an empty string strictly, use the <a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Strict_inequality\" rel=\"noreferrer\"><code>!==</code> operator</a>:</p>\n<pre><code>if (strValue !== "") {\n // strValue was not an empty string\n}\n</code></pre>\n"
},
{
"answer_id": 154073,
"author": "Chris Noe",
"author_id": 14749,
"author_profile": "https://Stackoverflow.com/users/14749",
"pm_score": 5,
"selected": false,
"text": "<p>I would not worry too much about the most <strong>efficient</strong> method. Use what is most clear to your intention. For me that's usually <code>strVar == \"\"</code>.</p>\n\n<p>As per the comment from <a href=\"https://stackoverflow.com/users/20310/constantin\">Constantin</a>, if strVar could some how end up containing an integer 0 value, then that would indeed be one of those intention-clarifying situations.</p>\n"
},
{
"answer_id": 154161,
"author": "cllpse",
"author_id": 20946,
"author_profile": "https://Stackoverflow.com/users/20946",
"pm_score": 5,
"selected": false,
"text": "<pre><code>var s; // undefined\nvar s = \"\"; // \"\"\ns.length // 0\n</code></pre>\n\n<p>There's nothing representing an empty string in JavaScript. Do a check against either <code>length</code> (if you know that the var will always be a string) or against <code>\"\"</code></p>\n"
},
{
"answer_id": 154520,
"author": "Ates Goral",
"author_id": 23501,
"author_profile": "https://Stackoverflow.com/users/23501",
"pm_score": 7,
"selected": false,
"text": "<p>The closest thing you can get to <code>str.Empty</code> (with the precondition that str is a String) is:</p>\n\n<pre><code>if (!str.length) { ...\n</code></pre>\n"
},
{
"answer_id": 155525,
"author": "Sugendran",
"author_id": 22466,
"author_profile": "https://Stackoverflow.com/users/22466",
"pm_score": 7,
"selected": false,
"text": "<p>If you need to make sure that the string is not just a bunch of empty spaces (I'm assuming this is for form validation) you need to do a replace on the spaces.</p>\n\n<pre><code>if(str.replace(/\\s/g,\"\") == \"\"){\n}\n</code></pre>\n"
},
{
"answer_id": 2263817,
"author": "jmc734",
"author_id": 273208,
"author_profile": "https://Stackoverflow.com/users/273208",
"pm_score": 3,
"selected": false,
"text": "<p>I usually use something like:</p>\n\n<pre><code>if (str == \"\") {\n //Do Something\n}\nelse {\n //Do Something Else\n}\n</code></pre>\n"
},
{
"answer_id": 2944306,
"author": "oem",
"author_id": 354687,
"author_profile": "https://Stackoverflow.com/users/354687",
"pm_score": 4,
"selected": false,
"text": "<p>You could also go with regular expressions:</p>\n\n<pre><code>if((/^\\s*$/).test(str)) { }\n</code></pre>\n\n<p>Checks for strings that are either empty or filled with whitespace.</p>\n"
},
{
"answer_id": 3215653,
"author": "Jet",
"author_id": 348008,
"author_profile": "https://Stackoverflow.com/users/348008",
"pm_score": 6,
"selected": false,
"text": "<p>I use:</p>\n<pre class=\"lang-js prettyprint-override\"><code>function empty(e) {\n switch (e) {\n case "":\n case 0:\n case "0":\n case null:\n case false:\n case undefined:\n return true;\n default:\n return false;\n }\n}\n\nempty(null) // true\nempty(0) // true\nempty(7) // false\nempty("") // true\nempty((function() {\n return ""\n})) // false\n</code></pre>\n"
},
{
"answer_id": 3261380,
"author": "Jano González",
"author_id": 389026,
"author_profile": "https://Stackoverflow.com/users/389026",
"pm_score": 10,
"selected": false,
"text": "<p>For checking if a variable is <a href=\"https://developer.mozilla.org/en-US/docs/Glossary/Falsy\" rel=\"noreferrer\">falsey</a> or if it has length attribute equal to zero (which for a string, means it is empty), I use:</p>\n<pre><code>function isEmpty(str) {\n return (!str || str.length === 0 );\n}\n</code></pre>\n<p><sub>(Note that strings aren't the only variables with a <code>length</code> attribute, arrays have them as well, for example.)</sub></p>\n<p>Alternativaly, you can use the (not so) newly optional chaining and arrow functions to simplify:</p>\n<pre><code>const isEmpty = (str) => (!str?.length);\n</code></pre>\n<p>It will check the length, returning <code>undefined</code> in case of a nullish value, without throwing an error. In the case of an empty value, zero is falsy and the result is still valid.</p>\n<p>For checking if a variable is falsey or if the string only contains whitespace or is empty, I use:</p>\n<pre><code>function isBlank(str) {\n return (!str || /^\\s*$/.test(str));\n}\n</code></pre>\n<p>If you want, you can <a href=\"https://www.audero.it/blog/2016/12/05/monkey-patching-javascript/\" rel=\"noreferrer\">monkey-patch</a> the <code>String</code> prototype like this:</p>\n<pre><code>String.prototype.isEmpty = function() {\n // This doesn't work the same way as the isEmpty function used \n // in the first example, it will return true for strings containing only whitespace\n return (this.length === 0 || !this.trim());\n};\nconsole.log("example".isEmpty());\n</code></pre>\n<p><sub>Note that monkey-patching built-in types are controversial, as it can break code that depends on the existing structure of built-in types, for whatever reason.</sub></p>\n"
},
{
"answer_id": 3310585,
"author": "Doug",
"author_id": 399277,
"author_profile": "https://Stackoverflow.com/users/399277",
"pm_score": 3,
"selected": false,
"text": "<p>Try this</p>\n\n<pre><code>str.value.length == 0\n</code></pre>\n"
},
{
"answer_id": 3425761,
"author": "Muhammad Salman",
"author_id": 413269,
"author_profile": "https://Stackoverflow.com/users/413269",
"pm_score": 2,
"selected": false,
"text": "<pre><code>function tell()\n{\n var pass = document.getElementById('pasword').value;\n var plen = pass.length;\n\n // Now you can check if your string is empty as like\n if(plen==0)\n {\n alert('empty');\n }\n else\n {\n alert('you entered something');\n }\n}\n\n<input type='text' id='pasword' />\n</code></pre>\n\n<p>This is also a generic way to check if field is empty.</p>\n"
},
{
"answer_id": 5487027,
"author": "karthick.sk",
"author_id": 683996,
"author_profile": "https://Stackoverflow.com/users/683996",
"pm_score": 9,
"selected": false,
"text": "<p>All the previous answers are good, but this will be even better. Use dual NOT operators (<code>!!</code>):</p>\n<pre class=\"lang-js prettyprint-override\"><code>if (!!str) {\n // Some code here\n}\n</code></pre>\n<p>Or use type casting:</p>\n<pre class=\"lang-js prettyprint-override\"><code>if (Boolean(str)) {\n // Code here\n}\n</code></pre>\n<p>Both do the same function. Typecast the variable to Boolean, where <code>str</code> is a variable.</p>\n<ul>\n<li><p>It returns <code>false</code> for <code>null</code>, <code>undefined</code>, <code>0</code>, <code>000</code>, <code>""</code>, <code>false</code>.</p>\n</li>\n<li><p>It returns <code>true</code> for all string values other than the empty string (including strings like <code>"0"</code> and <code>" "</code>)</p>\n</li>\n</ul>\n"
},
{
"answer_id": 6203869,
"author": "Will",
"author_id": 557117,
"author_profile": "https://Stackoverflow.com/users/557117",
"pm_score": 4,
"selected": false,
"text": "<p>I use a combination, and the fastest checks are first.</p>\n<pre><code>function isBlank(pString) {\n if (!pString) {\n return true;\n }\n // Checks for a non-white space character\n // which I think [citation needed] is faster\n // than removing all the whitespace and checking\n // against an empty string\n return !/[^\\s]+/.test(pString);\n}\n</code></pre>\n"
},
{
"answer_id": 11552927,
"author": "mricci",
"author_id": 1452807,
"author_profile": "https://Stackoverflow.com/users/1452807",
"pm_score": 3,
"selected": false,
"text": "<p>Ignoring whitespace strings, you could use this to check for null, empty and undefined:</p>\n\n<pre><code>var obj = {};\n(!!obj.str) // Returns false\n\nobj.str = \"\";\n(!!obj.str) // Returns false\n\nobj.str = null;\n(!!obj.str) // Returns false\n</code></pre>\n\n<p>It is concise and it works for undefined properties, although it's not the most readable.</p>\n"
},
{
"answer_id": 11741988,
"author": "Bikush",
"author_id": 1565905,
"author_profile": "https://Stackoverflow.com/users/1565905",
"pm_score": 4,
"selected": false,
"text": "<p>I have not noticed an answer that takes into account the possibility of null characters in a string. For example, if we have a null character string:</p>\n\n<pre><code>var y = \"\\0\"; // an empty string, but has a null character\n(y === \"\") // false, testing against an empty string does not work\n(y.length === 0) // false\n(y) // true, this is also not expected\n(y.match(/^[\\s]*$/)) // false, again not wanted\n</code></pre>\n\n<p>To test its nullness one could do something like this:</p>\n\n<pre><code>String.prototype.isNull = function(){ \n return Boolean(this.match(/^[\\0]*$/)); \n}\n...\n\"\\0\".isNull() // true\n</code></pre>\n\n<p>It works on a null string, and on an empty string and it is accessible for all strings. In addition, it could be expanded to contain other JavaScript empty or whitespace characters (i.e. nonbreaking space, byte order mark, line/paragraph separator, etc.).</p>\n"
},
{
"answer_id": 13942574,
"author": "dkinzer",
"author_id": 256854,
"author_profile": "https://Stackoverflow.com/users/256854",
"pm_score": 2,
"selected": false,
"text": "<p>It's a good idea too to check that you are not trying to pass an undefined term.</p>\n\n<pre><code>function TestMe() {\n if((typeof str != 'undefined') && str) {\n alert(str);\n }\n };\n\nTestMe();\n\nvar str = 'hello';\n\nTestMe();\n</code></pre>\n\n<p>I usually run into the case where I want to do something when a string attribute for an object instance is not empty. Which is fine, except that attribute is not always present.</p>\n"
},
{
"answer_id": 14227612,
"author": "Yang Dong",
"author_id": 1129221,
"author_profile": "https://Stackoverflow.com/users/1129221",
"pm_score": 5,
"selected": false,
"text": "<p>Try:</p>\n\n<pre><code>if (str && str.trim().length) { \n //...\n}\n</code></pre>\n"
},
{
"answer_id": 14796708,
"author": "GibboK",
"author_id": 379008,
"author_profile": "https://Stackoverflow.com/users/379008",
"pm_score": 2,
"selected": false,
"text": "<p>An alternative way, but I believe <a href=\"https://stackoverflow.com/questions/154059/how-can-i-check-for-an-empty-undefined-null-string-in-javascript/154068#154068\">bdukes's answer</a> is best.</p>\n\n<pre><code>var myString = 'hello'; \nif(myString.charAt(0)){\n alert('no empty');\n}\nalert('empty');\n</code></pre>\n"
},
{
"answer_id": 16446530,
"author": "Andron",
"author_id": 284602,
"author_profile": "https://Stackoverflow.com/users/284602",
"pm_score": 3,
"selected": false,
"text": "<p>All these answers are nice.</p>\n\n<p>But I cannot be sure that variable is a string, doesn't contain only spaces (this is important for me), and can contain '0' (string).</p>\n\n<p>My version:</p>\n\n<pre><code>function empty(str){\n return !str || !/[^\\s]+/.test(str);\n}\n\nempty(null); // true\nempty(0); // true\nempty(7); // false\nempty(\"\"); // true\nempty(\"0\"); // false\nempty(\" \"); // true\n</code></pre>\n\n<p>Sample on <a href=\"http://jsfiddle.net/YZfGs/\" rel=\"nofollow noreferrer\">jsfiddle</a>.</p>\n"
},
{
"answer_id": 16540602,
"author": "JHM",
"author_id": 1894107,
"author_profile": "https://Stackoverflow.com/users/1894107",
"pm_score": 4,
"selected": false,
"text": "<p>I did some research on what happens if you pass a non-string and non-empty/null value to a tester function. As many know, (0 == \"\") is true in JavaScript, but since 0 is a value and not empty or null, you may want to test for it.</p>\n\n<p>The following two functions return true only for undefined, null, empty/whitespace values and false for everything else, such as numbers, Boolean, objects, expressions, etc.</p>\n\n<pre><code>function IsNullOrEmpty(value)\n{\n return (value == null || value === \"\");\n}\nfunction IsNullOrWhiteSpace(value)\n{\n return (value == null || !/\\S/.test(value));\n}\n</code></pre>\n\n<p>More complicated examples exists, but these are simple and give consistent results. There is no need to test for undefined, since it's included in (value == null) check. You may also mimic <a href=\"https://en.wikipedia.org/wiki/C_Sharp_%28programming_language%29\" rel=\"nofollow noreferrer\">C#</a> behaviour by adding them to String like this:</p>\n\n<pre><code>String.IsNullOrEmpty = function (value) { ... }\n</code></pre>\n\n<p>You do not want to put it in Strings prototype, because if the instance of the String-class is null, it will error:</p>\n\n<pre><code>String.prototype.IsNullOrEmpty = function (value) { ... }\nvar myvar = null;\nif (1 == 2) { myvar = \"OK\"; } // Could be set\nmyvar.IsNullOrEmpty(); // Throws error\n</code></pre>\n\n<p>I tested with the following value array. You can loop it through to test your functions if in doubt.</p>\n\n<pre><code>// Helper items\nvar MyClass = function (b) { this.a = \"Hello World!\"; this.b = b; };\nMyClass.prototype.hello = function () { if (this.b == null) { alert(this.a); } else { alert(this.b); } };\nvar z;\nvar arr = [\n// 0: Explanation for printing, 1: actual value\n ['undefined', undefined],\n ['(var) z', z],\n ['null', null],\n ['empty', ''],\n ['space', ' '],\n ['tab', '\\t'],\n ['newline', '\\n'],\n ['carriage return', '\\r'],\n ['\"\\\\r\\\\n\"', '\\r\\n'],\n ['\"\\\\n\\\\r\"', '\\n\\r'],\n ['\" \\\\t \\\\n \"', ' \\t \\n '],\n ['\" txt \\\\t test \\\\n\"', ' txt \\t test \\n'],\n ['\"txt\"', \"txt\"],\n ['\"undefined\"', 'undefined'],\n ['\"null\"', 'null'],\n ['\"0\"', '0'],\n ['\"1\"', '1'],\n ['\"1.5\"', '1.5'],\n ['\"1,5\"', '1,5'], // Valid number in some locales, not in JavaScript\n ['comma', ','],\n ['dot', '.'],\n ['\".5\"', '.5'],\n ['0', 0],\n ['0.0', 0.0],\n ['1', 1],\n ['1.5', 1.5],\n ['NaN', NaN],\n ['/\\S/', /\\S/],\n ['true', true],\n ['false', false],\n ['function, returns true', function () { return true; } ],\n ['function, returns false', function () { return false; } ],\n ['function, returns null', function () { return null; } ],\n ['function, returns string', function () { return \"test\"; } ],\n ['function, returns undefined', function () { } ],\n ['MyClass', MyClass],\n ['new MyClass', new MyClass()],\n ['empty object', {}],\n ['non-empty object', { a: \"a\", match: \"bogus\", test: \"bogus\"}],\n ['object with toString: string', { a: \"a\", match: \"bogus\", test: \"bogus\", toString: function () { return \"test\"; } }],\n ['object with toString: null', { a: \"a\", match: \"bogus\", test: \"bogus\", toString: function () { return null; } }]\n];\n</code></pre>\n"
},
{
"answer_id": 16568401,
"author": "Wab_Z",
"author_id": 1215159,
"author_profile": "https://Stackoverflow.com/users/1215159",
"pm_score": 4,
"selected": false,
"text": "<p>Also, in case you consider a whitespace filled string as \"empty\".</p>\n\n<p>You can test it with this regular expression:</p>\n\n<pre><code>!/\\S/.test(string); // Returns true if blank.\n</code></pre>\n"
},
{
"answer_id": 17439572,
"author": "Mubashar",
"author_id": 806076,
"author_profile": "https://Stackoverflow.com/users/806076",
"pm_score": 2,
"selected": false,
"text": "<p>I prefer to use not blank test instead of blank </p>\n\n<pre><code>function isNotBlank(str) {\n return (str && /^\\s*$/.test(str));\n}\n</code></pre>\n"
},
{
"answer_id": 17652575,
"author": "Kev",
"author_id": 741657,
"author_profile": "https://Stackoverflow.com/users/741657",
"pm_score": 3,
"selected": false,
"text": "<p>Don't assume that the variable you check is a string. Don't assume that if this var has a length, then it's a string.</p>\n\n<p>The thing is: think carefully about what your app must do and can accept. Build something robust.</p>\n\n<p>If your method / function should only process a non empty string then test if the argument is a non empty string and don't do some 'trick'.</p>\n\n<p>As an example of something that will explode if you follow some advices here not carefully.</p>\n\n<pre><code>\nvar getLastChar = function (str) {\n if (str.length > 0)\n return str.charAt(str.length - 1)\n}\n\ngetLastChar('hello')\n=> \"o\"\n\ngetLastChar([0,1,2,3])\n=> TypeError: Object [object Array] has no method 'charAt'\n</code>\n</pre>\n\n<p>So, I'd stick with</p>\n\n<pre><code>\nif (myVar === '')\n ...\n</code>\n</pre>\n"
},
{
"answer_id": 18144362,
"author": "user2086641",
"author_id": 2086641,
"author_profile": "https://Stackoverflow.com/users/2086641",
"pm_score": 4,
"selected": false,
"text": "<p>I usually use something like this,</p>\n\n<pre><code>if (!str.length) {\n // Do something\n}\n</code></pre>\n"
},
{
"answer_id": 22079686,
"author": "T.Todua",
"author_id": 2377343,
"author_profile": "https://Stackoverflow.com/users/2377343",
"pm_score": 5,
"selected": false,
"text": "<p>Very generic "All-In-One" Function (<em>not recommended though</em>):</p>\n<pre><code>function is_empty(x)\n{\n return ( //don't put newline after return\n (typeof x == 'undefined')\n ||\n (x == null)\n ||\n (x == false) //same as: !x\n ||\n (x.length == 0)\n ||\n (x == 0) // note this line, you might not need this. \n ||\n (x == "")\n ||\n (x.replace(/\\s/g,"") == "")\n ||\n (!/[^\\s]/.test(x))\n ||\n (/^\\s*$/.test(x))\n );\n}\n</code></pre>\n<p>However, I don't recommend to use that, because your target variable should be of specific type (i.e. string, or numeric, or object?), so apply the checks that are relative to that variable.</p>\n"
},
{
"answer_id": 22933119,
"author": "Gaurav",
"author_id": 3297388,
"author_profile": "https://Stackoverflow.com/users/3297388",
"pm_score": -1,
"selected": false,
"text": "<pre><code>var x =\" \";\nvar patt = /^\\s*$/g;\nisBlank = patt.test(x);\nalert(isBlank); // Is it blank or not??\nx = x.replace(/\\s*/g, \"\"); // Another way of replacing blanks with \"\"\nif (x===\"\"){\n alert(\"ya it is blank\")\n}\n</code></pre>\n"
},
{
"answer_id": 23487540,
"author": "Sazid",
"author_id": 1941132,
"author_profile": "https://Stackoverflow.com/users/1941132",
"pm_score": 3,
"selected": false,
"text": "<p>You should always check for the type too, since JavaScript is a duck typed language, so you may not know when and how the data changed in the middle of the process. So, here's the better solution:</p>\n<p><div class=\"snippet\" data-lang=\"js\" data-hide=\"false\" data-console=\"true\" data-babel=\"false\">\r\n<div class=\"snippet-code\">\r\n<pre class=\"snippet-code-js lang-js prettyprint-override\"><code> let undefinedStr;\n if (!undefinedStr) {\n console.log(\"String is undefined\");\n }\n \n let emptyStr = \"\";\n if (!emptyStr) {\n console.log(\"String is empty\");\n }\n \n let nullStr = null;\n if (!nullStr) {\n console.log(\"String is null\");\n }</code></pre>\r\n</div>\r\n</div>\r\n</p>\n"
},
{
"answer_id": 24843517,
"author": "Alban Kaperi",
"author_id": 3527794,
"author_profile": "https://Stackoverflow.com/users/3527794",
"pm_score": -1,
"selected": false,
"text": "<p>To check if it is empty:</p>\n<pre><code>var str = "Hello World!";\nif(str === ''){alert("THE string str is EMPTY");}\n</code></pre>\n<p>To check if it is of type string:</p>\n<pre><code>var str = "Hello World!";\nif(typeof(str) === 'string'){alert("This is a String");}\n</code></pre>\n"
},
{
"answer_id": 26135702,
"author": "Josef.B",
"author_id": 1149606,
"author_profile": "https://Stackoverflow.com/users/1149606",
"pm_score": 4,
"selected": false,
"text": "<p>If one needs to detect not only empty but also blank strings, I'll add to Goral's answer:</p>\n\n<pre><code>function isEmpty(s){\n return !s.length; \n}\n\nfunction isBlank(s){\n return isEmpty(s.trim()); \n}\n</code></pre>\n"
},
{
"answer_id": 28699962,
"author": "Timothy Nwanwene",
"author_id": 2258599,
"author_profile": "https://Stackoverflow.com/users/2258599",
"pm_score": 4,
"selected": false,
"text": "<ol>\n<li>check that <code>var a;</code> exist</li>\n<li><p>trim out the <code>false spaces</code> in the value, then test for <code>emptiness</code></p>\n\n<pre><code>if ((a)&&(a.trim()!=''))\n{\n // if variable a is not empty do this \n}\n</code></pre></li>\n</ol>\n"
},
{
"answer_id": 30751362,
"author": "Thaddeus Albers",
"author_id": 1684480,
"author_profile": "https://Stackoverflow.com/users/1684480",
"pm_score": 2,
"selected": false,
"text": "<p>The <a href=\"https://en.wikipedia.org/wiki/Underscore.js\" rel=\"nofollow noreferrer\">Underscore.js</a> JavaScript library, <a href=\"http://underscorejs.org/\" rel=\"nofollow noreferrer\">http://underscorejs.org/</a>, provides a very useful <code>_.isEmpty()</code> function for checking for empty strings and other empty objects.</p>\n\n<p>Reference: <a href=\"http://underscorejs.org/#isEmpty\" rel=\"nofollow noreferrer\">http://underscorejs.org/#isEmpty</a></p>\n\n<blockquote>\n <p><strong>isEmpty</strong> <code>_.isEmpty(object)</code> <br/>\n Returns true if an enumerable object contains no values (no enumerable own-properties). For strings and array-like objects _.isEmpty checks if the length property is 0.</p>\n \n <p><code>_.isEmpty([1, 2, 3]);</code> <br/>\n => false</p>\n \n <p><code>_.isEmpty({});</code> <br/>\n => true</p>\n</blockquote>\n\n<p>Other very useful Underscore.js functions include:</p>\n\n<ul>\n<li><a href=\"http://underscorejs.org/#isNull\" rel=\"nofollow noreferrer\">http://underscorejs.org/#isNull</a> <code>_.isNull(object)</code></li>\n<li><a href=\"http://underscorejs.org/#isUndefined\" rel=\"nofollow noreferrer\">http://underscorejs.org/#isUndefined</a></li>\n<li><code>_.isUndefined(value)</code></li>\n<li><a href=\"http://underscorejs.org/#has\" rel=\"nofollow noreferrer\">http://underscorejs.org/#has</a> <code>_.has(object, key)</code></li>\n</ul>\n"
},
{
"answer_id": 36328062,
"author": "tfont",
"author_id": 1804013,
"author_profile": "https://Stackoverflow.com/users/1804013",
"pm_score": 4,
"selected": false,
"text": "<p>A lot of answers, and a lot of different possibilities!</p>\n<p>Without a doubt for quick and simple implementation the winner is: <code>if (!str.length) {...}</code></p>\n<p>However, as many other examples are available. The best functional method to go about this, I would suggest:</p>\n<p><div class=\"snippet\" data-lang=\"js\" data-hide=\"false\" data-console=\"false\" data-babel=\"false\">\r\n<div class=\"snippet-code\">\r\n<pre class=\"snippet-code-js lang-js prettyprint-override\"><code>function empty(str)\n{\n if (typeof str == 'undefined' || !str || str.length === 0 || str === \"\" || !/[^\\s]/.test(str) || /^\\s*$/.test(str) || str.replace(/\\s/g,\"\") === \"\")\n return true;\n else\n return false;\n}</code></pre>\r\n</div>\r\n</div>\r\n</p>\n<p>A bit excessive, I know.</p>\n"
},
{
"answer_id": 40432585,
"author": "Agustí Sánchez",
"author_id": 791694,
"author_profile": "https://Stackoverflow.com/users/791694",
"pm_score": 3,
"selected": false,
"text": "<p>There's no <code>isEmpty()</code> method, you have to check for the type and the length:</p>\n\n<pre><code>if (typeof test === 'string' && test.length === 0){\n ...\n</code></pre>\n\n<p>The type check is needed in order to avoid runtime errors when <code>test</code> is <code>undefined</code> or <code>null</code>.</p>\n"
},
{
"answer_id": 45728354,
"author": "Moshi",
"author_id": 1349365,
"author_profile": "https://Stackoverflow.com/users/1349365",
"pm_score": 6,
"selected": false,
"text": "<p>You can use <a href=\"https://lodash.com/\" rel=\"noreferrer\">lodash</a>:\n_.isEmpty(value).</p>\n\n<p>It covers a lot of cases like <code>{}</code>, <code>''</code>, <code>null</code>, <code>undefined</code>, etc.</p>\n\n<p>But it always returns <code>true</code> for <code>Number</code> type of <a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures\" rel=\"noreferrer\">JavaScript primitive data types</a> like <code>_.isEmpty(10)</code> or <code>_.isEmpty(Number.MAX_VALUE)</code> both returns <code>true</code>.</p>\n"
},
{
"answer_id": 46616110,
"author": "Alireza",
"author_id": 5423108,
"author_profile": "https://Stackoverflow.com/users/5423108",
"pm_score": 3,
"selected": false,
"text": "<p>You can easily add it to native <strong>String</strong> object in <strong>JavaScript</strong> and reuse it over and over...<br>\nSomething simple like below code can do the job for you if you want to check <code>''</code> empty strings:</p>\n\n<pre><code>String.prototype.isEmpty = String.prototype.isEmpty || function() {\n return !(!!this.length);\n}\n</code></pre>\n\n<p>Otherwise if you'd like to check both <code>''</code> empty string and <code>' '</code> with space, you can do that by just adding <code>trim()</code>, something like the code below:</p>\n\n<pre><code>String.prototype.isEmpty = String.prototype.isEmpty || function() {\n return !(!!this.trim().length);\n}\n</code></pre>\n\n<p>and you can call it this way:</p>\n\n<pre><code>''.isEmpty(); //return true\n'alireza'.isEmpty(); //return false\n</code></pre>\n"
},
{
"answer_id": 47567144,
"author": "KARTHIKEYAN.A",
"author_id": 4652706,
"author_profile": "https://Stackoverflow.com/users/4652706",
"pm_score": 3,
"selected": false,
"text": "<p>You can able to validate following ways and understand the difference.</p>\n\n<p><div class=\"snippet\" data-lang=\"js\" data-hide=\"false\" data-console=\"true\" data-babel=\"false\">\r\n<div class=\"snippet-code\">\r\n<pre class=\"snippet-code-js lang-js prettyprint-override\"><code>var j = undefined;\r\nconsole.log((typeof j == 'undefined') ? \"true\":\"false\");\r\nvar j = null; \r\nconsole.log((j == null) ? \"true\":\"false\");\r\nvar j = \"\";\r\nconsole.log((!j) ? \"true\":\"false\");\r\nvar j = \"Hi\";\r\nconsole.log((!j) ? \"true\":\"false\");</code></pre>\r\n</div>\r\n</div>\r\n</p>\n"
},
{
"answer_id": 49231174,
"author": "Imran Ahmad",
"author_id": 9908141,
"author_profile": "https://Stackoverflow.com/users/9908141",
"pm_score": 4,
"selected": false,
"text": "<p>Meanwhile we can have one function that checks for all 'empties' like <strong>null, undefined, '', ' ', {}, []</strong>.\nSo I just wrote this.</p>\n\n<pre><code>var isEmpty = function(data) {\n if(typeof(data) === 'object'){\n if(JSON.stringify(data) === '{}' || JSON.stringify(data) === '[]'){\n return true;\n }else if(!data){\n return true;\n }\n return false;\n }else if(typeof(data) === 'string'){\n if(!data.trim()){\n return true;\n }\n return false;\n }else if(typeof(data) === 'undefined'){\n return true;\n }else{\n return false;\n }\n}\n</code></pre>\n\n<p>Use cases and results.</p>\n\n<pre><code>console.log(isEmpty()); // true\nconsole.log(isEmpty(null)); // true\nconsole.log(isEmpty('')); // true\nconsole.log(isEmpty(' ')); // true\nconsole.log(isEmpty(undefined)); // true\nconsole.log(isEmpty({})); // true\nconsole.log(isEmpty([])); // true\nconsole.log(isEmpty(0)); // false\nconsole.log(isEmpty('Hey')); // false\n</code></pre>\n"
},
{
"answer_id": 56085096,
"author": "oviniciusfeitosa",
"author_id": 1330323,
"author_profile": "https://Stackoverflow.com/users/1330323",
"pm_score": 3,
"selected": false,
"text": "<p>Try this:</p>\n\n<pre><code>export const isEmpty = string => (!string || !string.length);\n</code></pre>\n"
},
{
"answer_id": 58447444,
"author": "Japesh",
"author_id": 9247582,
"author_profile": "https://Stackoverflow.com/users/9247582",
"pm_score": 2,
"selected": false,
"text": "<p>The following regular expression is another solution, that can be used for null, empty or undefined string.</p>\n\n<pre><code>(/(null|undefined|^$)/).test(null)\n</code></pre>\n\n<p>I added this solution, because it can be extended further to check empty or some value like as follow. The following regular expression is checking either string can be empty null undefined or it has integers only.</p>\n\n<pre><code>(/(null|undefined|^$|^\\d+$)/).test()\n</code></pre>\n"
},
{
"answer_id": 58531070,
"author": "Davi Daniel Siepmann",
"author_id": 5535130,
"author_profile": "https://Stackoverflow.com/users/5535130",
"pm_score": 4,
"selected": false,
"text": "<p>I didn't see a good answer here (at least not an answer that fits for me)</p>\n\n<p>So I decided to answer myself:</p>\n\n<p><code>value === undefined || value === null || value === \"\";</code></p>\n\n<p>You need to start checking if it's undefined. Otherwise your method can explode, and then you can check if it equals null or is equal to an empty string.</p>\n\n<p>You cannot have !! or only <code>if(value)</code> since if you check <code>0</code> it's going to give you a false answer (0 is false).</p>\n\n<p>With that said, wrap it up in a method like:</p>\n\n<p><code>public static isEmpty(value: any): boolean {\n return value === undefined || value === null || value === \"\";\n}</code></p>\n\n<p>PS.: <strong>You don't need to check typeof</strong>, since it would explode and throw even before it enters the method</p>\n"
},
{
"answer_id": 59547575,
"author": "Kamil Kiełczewski",
"author_id": 860099,
"author_profile": "https://Stackoverflow.com/users/860099",
"pm_score": 6,
"selected": false,
"text": "<h2>Performance</h2>\n\n<p>I perform tests on <a href=\"https://en.wikipedia.org/wiki/MacOS_High_Sierra\" rel=\"noreferrer\">macOS v10.13.6</a> (High Sierra) for 18 chosen solutions. Solutions works slightly different (for corner-case input data) which was presented in the snippet below.</p>\n\n<p><strong>Conclusions</strong></p>\n\n<ul>\n<li>the simple solutions based on <code>!str</code>,<code>==</code>,<code>===</code> and <code>length</code> are fast for all browsers (A,B,C,G,I,J)</li>\n<li>the solutions based on the regular expression (<code>test</code>,<code>replace</code>) and <code>charAt</code> are slowest for all browsers (H,L,M,P)</li>\n<li>the solutions marked as fastest was fastest only for one test run - but in many runs it changes inside 'fast' solutions group</li>\n</ul>\n\n<p><a href=\"https://i.stack.imgur.com/bFeGV.png\" rel=\"noreferrer\"><img src=\"https://i.stack.imgur.com/bFeGV.png\" alt=\"Enter image description here\"></a></p>\n\n<h2>Details</h2>\n\n<p>In the below snippet I compare results of chosen 18 methods by use different input parameters</p>\n\n<ul>\n<li><code>\"\"</code> <code>\"a\"</code> <code>\" \"</code>- empty string, string with letter and string with space</li>\n<li><code>[]</code> <code>{}</code> <code>f</code>- array, object and function</li>\n<li><code>0</code> <code>1</code> <code>NaN</code> <code>Infinity</code> - numbers</li>\n<li><code>true</code> <code>false</code> - Boolean</li>\n<li><code>null</code> <code>undefined</code></li>\n</ul>\n\n<p>Not all tested methods support all input cases.</p>\n\n<p><div class=\"snippet\" data-lang=\"js\" data-hide=\"true\" data-console=\"true\" data-babel=\"false\">\r\n<div class=\"snippet-code snippet-currently-hidden\">\r\n<pre class=\"snippet-code-js lang-js prettyprint-override\"><code>function A(str) {\r\n let r=1;\r\n if (!str)\r\n r=0;\r\n return r;\r\n}\r\n\r\nfunction B(str) {\r\n let r=1;\r\n if (str == \"\")\r\n r=0;\r\n return r;\r\n}\r\n\r\nfunction C(str) {\r\n let r=1;\r\n if (str === \"\")\r\n r=0;\r\n return r;\r\n}\r\n\r\nfunction D(str) {\r\n let r=1;\r\n if(!str || 0 === str.length)\r\n r=0;\r\n return r;\r\n}\r\n\r\nfunction E(str) {\r\n let r=1;\r\n if(!str || /^\\s*$/.test(str))\r\n r=0;\r\n return r;\r\n}\r\n\r\nfunction F(str) {\r\n let r=1;\r\n if(!Boolean(str))\r\n r=0;\r\n return r;\r\n}\r\n\r\nfunction G(str) {\r\n let r=1;\r\n if(! ((typeof str != 'undefined') && str) )\r\n r=0;\r\n return r;\r\n}\r\n\r\nfunction H(str) {\r\n let r=1;\r\n if(!/\\S/.test(str))\r\n r=0;\r\n return r;\r\n}\r\n\r\nfunction I(str) {\r\n let r=1;\r\n if (!str.length)\r\n r=0;\r\n return r;\r\n}\r\n\r\nfunction J(str) {\r\n let r=1;\r\n if(str.length <= 0)\r\n r=0;\r\n return r;\r\n}\r\n\r\nfunction K(str) {\r\n let r=1;\r\n if(str.length === 0 || !str.trim())\r\n r=0;\r\n return r;\r\n}\r\n\r\nfunction L(str) {\r\n let r=1;\r\n if ( str.replace(/\\s/g,\"\") == \"\")\r\n r=0;\r\n return r;\r\n}\r\n\r\nfunction M(str) {\r\n let r=1;\r\n if((/^\\s*$/).test(str))\r\n r=0;\r\n return r;\r\n}\r\n\r\n\r\nfunction N(str) {\r\n let r=1;\r\n if(!str || !str.trim().length)\r\n r=0;\r\n return r;\r\n}\r\n\r\nfunction O(str) {\r\n let r=1;\r\n if(!str || !str.trim())\r\n r=0;\r\n return r;\r\n}\r\n\r\nfunction P(str) {\r\n let r=1;\r\n if(!str.charAt(0))\r\n r=0;\r\n return r;\r\n}\r\n\r\nfunction Q(str) {\r\n let r=1;\r\n if(!str || (str.trim()==''))\r\n r=0;\r\n return r;\r\n}\r\n\r\nfunction R(str) {\r\n let r=1;\r\n if (typeof str == 'undefined' ||\r\n !str ||\r\n str.length === 0 ||\r\n str === \"\" ||\r\n !/[^\\s]/.test(str) ||\r\n /^\\s*$/.test(str) ||\r\n str.replace(/\\s/g,\"\") === \"\")\r\n\r\n r=0;\r\n return r;\r\n}\r\n\r\n\r\n\r\n\r\n// --- TEST ---\r\n\r\nconsole.log( ' \"\" \"a\" \" \" [] {} 0 1 NaN Infinity f true false null undefined ');\r\nlet log1 = (s,f)=> console.log(`${s}: ${f(\"\")} ${f(\"a\")} ${f(\" \")} ${f([])} ${f({})} ${f(0)} ${f(1)} ${f(NaN)} ${f(Infinity)} ${f(f)} ${f(true)} ${f(false)} ${f(null)} ${f(undefined)}`);\r\nlet log2 = (s,f)=> console.log(`${s}: ${f(\"\")} ${f(\"a\")} ${f(\" \")} ${f([])} ${f({})} ${f(0)} ${f(1)} ${f(NaN)} ${f(Infinity)} ${f(f)} ${f(true)} ${f(false)}`);\r\nlet log3 = (s,f)=> console.log(`${s}: ${f(\"\")} ${f(\"a\")} ${f(\" \")}`);\r\n\r\nlog1('A', A);\r\nlog1('B', B);\r\nlog1('C', C);\r\nlog1('D', D);\r\nlog1('E', E);\r\nlog1('F', F);\r\nlog1('G', G);\r\nlog1('H', H);\r\n\r\nlog2('I', I);\r\nlog2('J', J);\r\n\r\nlog3('K', K);\r\nlog3('L', L);\r\nlog3('M', M);\r\nlog3('N', N);\r\nlog3('O', O);\r\nlog3('P', P);\r\nlog3('Q', Q);\r\nlog3('R', R);</code></pre>\r\n</div>\r\n</div>\r\n</p>\n\n<p>And then for all methods I perform speed test case <code>str = \"\"</code> for browsers Chrome v78.0.0, Safari v13.0.4, and Firefox v71.0.0 - you can run tests on your machine <a href=\"https://jsperf.com/empty-string-checking/1\" rel=\"noreferrer\">here</a></p>\n\n<p><a href=\"https://i.stack.imgur.com/IxaPG.png\" rel=\"noreferrer\"><img src=\"https://i.stack.imgur.com/IxaPG.png\" alt=\"Enter image description here\"></a></p>\n"
},
{
"answer_id": 60146663,
"author": "Abhishek Luthra",
"author_id": 9494420,
"author_profile": "https://Stackoverflow.com/users/9494420",
"pm_score": 4,
"selected": false,
"text": "<p>Starting with:</p>\n\n<pre><code>return (!value || value == undefined || value == \"\" || value.length == 0);\n</code></pre>\n\n<p>Looking at the last condition, if value == \"\", its length <em>must</em> be 0. Therefore drop it:</p>\n\n<pre><code>return (!value || value == undefined || value == \"\");\n</code></pre>\n\n<p>But wait! In JavaScript, an empty string is false. Therefore, drop value == \"\":</p>\n\n<pre><code>return (!value || value == undefined);\n</code></pre>\n\n<p>And !undefined is true, so that check isn't needed. So we have:</p>\n\n<pre><code>return (!value);\n</code></pre>\n\n<p>And we don't need parentheses:</p>\n\n<pre><code>return !value\n</code></pre>\n"
},
{
"answer_id": 63558697,
"author": "Ibraheem",
"author_id": 1525751,
"author_profile": "https://Stackoverflow.com/users/1525751",
"pm_score": 4,
"selected": false,
"text": "<pre><code>if ((str?.trim()?.length || 0) > 0) {\n // str must not be any of:\n // undefined\n // null\n // ""\n // " " or just whitespace\n}\n</code></pre>\n<p>Or in function form:</p>\n<pre><code>const isNotNilOrWhitespace = input => (input?.trim()?.length || 0) > 0;\n\nconst isNilOrWhitespace = input => (input?.trim()?.length || 0) === 0;\n</code></pre>\n"
},
{
"answer_id": 64704021,
"author": "trn450",
"author_id": 1833999,
"author_profile": "https://Stackoverflow.com/users/1833999",
"pm_score": 3,
"selected": false,
"text": "<p>There is a lot of useful information here, but in my opinion, one of the most important elements was not addressed.</p>\n<p><code>null</code>, <code>undefined</code>, and <code>""</code> are all <em>falsy</em>.</p>\n<p>When evaluating for an empty string, it's often because you need to replace it with something else.</p>\n<p>In which case, you can expect the following behavior.</p>\n<pre><code>var a = ""\nvar b = null\nvar c = undefined\n\nconsole.log(a || "falsy string provided") // prints ->"falsy string provided"\nconsole.log(b || "falsy string provided") // prints ->"falsy string provided"\nconsole.log(c || "falsy string provided") // prints ->"falsy string provided"\n</code></pre>\n<p>With that in mind, a method or function that can return whether or not a string is <code>""</code>, <code>null</code>, or <code>undefined</code> (an invalid string) versus a valid string is as simple as this:</p>\n<pre><code>const validStr = (str) => str ? true : false\n\nvalidStr(undefined) // returns false\nvalidStr(null) // returns false\nvalidStr("") // returns false\nvalidStr("My String") // returns true\n</code></pre>\n"
},
{
"answer_id": 65141412,
"author": "sean",
"author_id": 1149962,
"author_profile": "https://Stackoverflow.com/users/1149962",
"pm_score": 3,
"selected": false,
"text": "<p>Trimming whitespace with the null-coalescing operator:</p>\n<pre class=\"lang-js prettyprint-override\"><code>if (!str?.trim()) {\n // do something...\n}\n</code></pre>\n"
},
{
"answer_id": 65723526,
"author": "Tasos Tsournos",
"author_id": 11572155,
"author_profile": "https://Stackoverflow.com/users/11572155",
"pm_score": 2,
"selected": false,
"text": "<p>You can check this using the typeof operator along with the length method.</p>\n<pre><code>const isNonEmptyString = (value) => typeof(value) == 'string' && value.length > 0\n</code></pre>\n"
},
{
"answer_id": 68242211,
"author": "Labham Jain",
"author_id": 12009979,
"author_profile": "https://Stackoverflow.com/users/12009979",
"pm_score": 0,
"selected": false,
"text": "<p>Well, the simplest function to check this is...</p>\n<p><code>const checkEmpty = string => (string.trim() === "") || !string.trim();</code></p>\n<p>Usage:</p>\n<pre><code>checkEmpty(""); // returns true.\ncheckEmpty("mystr"); // returns false.\n</code></pre>\n<p>It's that dead simple. :)</p>\n"
},
{
"answer_id": 68880332,
"author": "CrazyStack",
"author_id": 1274273,
"author_profile": "https://Stackoverflow.com/users/1274273",
"pm_score": 2,
"selected": false,
"text": "<p>The <strong>ultimate and shortest</strong> variant of the <em>isBlank</em> function:</p>\n<p><div class=\"snippet\" data-lang=\"js\" data-hide=\"false\" data-console=\"true\" data-babel=\"false\">\r\n<div class=\"snippet-code\">\r\n<pre class=\"snippet-code-js lang-js prettyprint-override\"><code>/**\n * Will return:\n * False for: for all strings with chars\n * True for: false, null, undefined, 0, 0.0, \"\", \" \".\n *\n * @param str\n * @returns {boolean}\n */\nfunction isBlank(str){\n return (!!!str || /^\\s*$/.test(str));\n}\n\n// tests\nconsole.log(\"isBlank TRUE variants:\");\nconsole.log(isBlank(false));\nconsole.log(isBlank(undefined));\nconsole.log(isBlank(null));\nconsole.log(isBlank(0));\nconsole.log(isBlank(0.0));\nconsole.log(isBlank(\"\"));\nconsole.log(isBlank(\" \"));\n\nconsole.log(\"isBlank FALSE variants:\");\nconsole.log(isBlank(\"0\"));\nconsole.log(isBlank(\"0.0\"));\nconsole.log(isBlank(\" 0\"));\nconsole.log(isBlank(\"0 \"));\nconsole.log(isBlank(\"Test string\"));\nconsole.log(isBlank(\"true\"));\nconsole.log(isBlank(\"false\"));\nconsole.log(isBlank(\"null\"));\nconsole.log(isBlank(\"undefined\"));</code></pre>\r\n</div>\r\n</div>\r\n</p>\n"
},
{
"answer_id": 69492416,
"author": "Anis KCHAOU",
"author_id": 12553922,
"author_profile": "https://Stackoverflow.com/users/12553922",
"pm_score": 3,
"selected": false,
"text": "<p>Try this code:</p>\n<pre><code>function isEmpty(strValue)\n{\n // Test whether strValue is empty\n if (!strValue || strValue.trim() === "" ||\n (strValue.trim()).length === 0) {\n // Do something\n }\n}\n</code></pre>\n"
},
{
"answer_id": 69560397,
"author": "Ali Yaghoubi",
"author_id": 11662335,
"author_profile": "https://Stackoverflow.com/users/11662335",
"pm_score": 2,
"selected": false,
"text": "<p>This is a <a href=\"https://developer.mozilla.org/en-US/docs/Glossary/Falsy\" rel=\"nofollow noreferrer\"><em>falsy</em> value</a>.</p>\n<p>The first solution:</p>\n<pre><code>const str = "";\nreturn str || "Hello"\n</code></pre>\n<p>The second solution:</p>\n<pre><code>const str = "";\nreturn (!!str) || "Hello"; // !!str is Boolean\n</code></pre>\n<p>The third solution:</p>\n<pre><code>const str = "";\nreturn (+str) || "Hello"; // !!str is Boolean\n</code></pre>\n"
},
{
"answer_id": 69905074,
"author": "sMyles",
"author_id": 378506,
"author_profile": "https://Stackoverflow.com/users/378506",
"pm_score": 0,
"selected": false,
"text": "<p>Here are some custom functions I use for handling this. Along with examples of how the code runs.</p>\n<p><div class=\"snippet\" data-lang=\"js\" data-hide=\"false\" data-console=\"true\" data-babel=\"true\">\r\n<div class=\"snippet-code\">\r\n<pre class=\"snippet-code-js lang-js prettyprint-override\"><code>const v1 = 0\nconst v2 = '4'\nconst v2e = undefined\nconst v2e2 = null\nconst v3 = [1, 2, 3, 4]\nconst v3e = []\nconst v4 = true\nconst v4e = false\nconst v5 = {\n test: 'value'\n}\nconst v5e = {}\nconst v6 = 'NotEmpty'\nconst v6e = ''\n\nfunction isNumeric(n) {\n return !isNaN(parseFloat(n)) && isFinite(n)\n}\n\nfunction isEmpty(v, zeroIsEmpty = false) {\n /**\n * When doing a typeof check, null will always return \"object\" so we filter that out first\n * @see https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/typeof#typeof_null\n */\n if (v === null) {\n return true\n }\n\n if (v === true) {\n return false\n }\n\n if (typeof v === 'object') {\n return !Object.keys(v).length\n }\n\n if (isNumeric(v)) {\n return zeroIsEmpty ? parseFloat(v) === 0 : false\n }\n\n return !v || !v.length || v.length < 1\n}\n\nconsole.log(isEmpty(v1), isEmpty(v1, true))\nconsole.log(isEmpty(v2), isEmpty(v2e), isEmpty(v2e))\nconsole.log(isEmpty(v3), isEmpty(v3e))\nconsole.log(isEmpty(v4), isEmpty(v4e))\nconsole.log(isEmpty(v5), isEmpty(v5e))\nconsole.log(isEmpty(v6), isEmpty(v6e))</code></pre>\r\n</div>\r\n</div>\r\n</p>\n<p>Also for reference, here's <a href=\"https://github.com/lodash/lodash/blob/master/isEmpty.js\" rel=\"nofollow noreferrer\">the source for Lodash isEmpty</a>:</p>\n"
}
] |
2008/09/30
|
[
"https://Stackoverflow.com/questions/154059",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5619/"
] |
Is there a `string.Empty` in JavaScript, or is it just a case of checking for `""`?
|
### Empty string, undefined, null, ...
To check for a [truthy value](https://developer.mozilla.org/en-US/docs/Glossary/Truthy):
```
if (strValue) {
// strValue was non-empty string, true, 42, Infinity, [], ...
}
```
To check for a [falsy value](https://developer.mozilla.org/en-US/docs/Glossary/Falsy):
```
if (!strValue) {
// strValue was empty string, false, 0, null, undefined, ...
}
```
---
### Empty string (only!)
To check for exactly an empty string, compare for strict equality against `""` using the [`===` operator](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Strict_equality):
```
if (strValue === "") {
// strValue was empty string
}
```
To check for not an empty string strictly, use the [`!==` operator](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Strict_inequality):
```
if (strValue !== "") {
// strValue was not an empty string
}
```
|
154,075 |
<p>I have a Virtual Machine in Virtual PC 2007.</p>
<p>To start it from the desktop, I have the following command in a batch file:</p>
<pre><code>"c:\program files\Microsoft Virtual PC\Virtual PC.exe" -pc "MY-PC" -launch
</code></pre>
<p>But that leaves a dos prompt on the host machine until the virtual machine shuts down, and I exit out of the Virtual PC console. That's annoying.</p>
<p>So I changed my command to use the START command, instead:</p>
<pre><code>start "c:\program files\Microsoft Virtual PC\Virtual PC.exe" -pc MY-PC -launch
</code></pre>
<p>But it chokes on the parameters passed into Virtual PC.</p>
<p><code>START /?</code> indicates that parameters do indeed go in that location. Has anyone used START to launch a program with multiple command-line arguments?</p>
|
[
{
"answer_id": 154083,
"author": "albertein",
"author_id": 23020,
"author_profile": "https://Stackoverflow.com/users/23020",
"pm_score": -1,
"selected": false,
"text": "<p>have you tried:</p>\n\n<pre><code>start \"c:\\program files\\Microsoft Virtual PC\\Virtual PC.exe\" \"-pc MY-PC -launch\"\n</code></pre>\n\n<p>?</p>\n"
},
{
"answer_id": 154087,
"author": "Mark Allen",
"author_id": 5948,
"author_profile": "https://Stackoverflow.com/users/5948",
"pm_score": -1,
"selected": false,
"text": "<p>Put the command inside a batch file, and call that with the parameters. </p>\n\n<p>Also, did you try this yet? (Move end quote to encapsulate parameters)</p>\n\n<pre><code>start \"c:\\program files\\Microsoft Virtual PC\\Virtual PC.exe -pc MY-PC -launch\"\n</code></pre>\n"
},
{
"answer_id": 154090,
"author": "Tim Farley",
"author_id": 4425,
"author_profile": "https://Stackoverflow.com/users/4425",
"pm_score": 10,
"selected": true,
"text": "<p>START has a peculiarity involving double quotes around the first parameter. If the first parameter has double quotes it uses that as the optional TITLE for the new window. </p>\n\n<p>I believe what you want is:</p>\n\n<pre><code>start \"\" \"c:\\program files\\Microsoft Virtual PC\\Virtual PC.exe\" -pc MY-PC -launch\n</code></pre>\n\n<p>In other words, give it an empty title before the name of the program to fake it out.</p>\n"
},
{
"answer_id": 154104,
"author": "Ferruccio",
"author_id": 4086,
"author_profile": "https://Stackoverflow.com/users/4086",
"pm_score": 4,
"selected": false,
"text": "<p>Instead of a batch file, you can create a shortcut on the desktop.</p>\n\n<p>Set the target to:</p>\n\n<pre><code>\"c:\\program files\\Microsoft Virtual PC\\Virtual PC.exe\" -pc \"MY-PC\" -launch\n</code></pre>\n\n<p>and you're all set. Since you're not starting up a command prompt to launch it, there will be no DOS Box.</p>\n"
},
{
"answer_id": 11274735,
"author": "ghostdog21",
"author_id": 1493094,
"author_profile": "https://Stackoverflow.com/users/1493094",
"pm_score": 2,
"selected": false,
"text": "<p>The spaces are DOSs/CMDs Problems so you should go to the Path via:</p>\n\n<pre><code>cd \"c:\\program files\\Microsoft Virtual PC\"\n</code></pre>\n\n<p>and then simply start VPC via:</p>\n\n<pre><code>start Virtual~1.exe -pc MY-PC -launch\n</code></pre>\n\n<p><code>~1</code> means the first <code>exe</code> with <code>\"Virtual\"</code> at the beginning. So if there is a <code>\"Virtual PC.exe\"</code> and a <code>\"Virtual PC1.exe\"</code> the first would be the <code>Virtual~1.exe</code> and the second <code>Virtual~2.exe</code> and so on.</p>\n\n<p>Or use a VNC-Client like VirtualBox.</p>\n"
},
{
"answer_id": 14842307,
"author": "Mrbios",
"author_id": 2066341,
"author_profile": "https://Stackoverflow.com/users/2066341",
"pm_score": 3,
"selected": false,
"text": "<p>You can use quotes by using the [<code>/D\"Path\"</code>] use <code>/D</code> <strong>only</strong> for specifying the path and not the path+program. It appears that all code on the same line that follows goes back to normal meaning you don't need to separate path and file.</p>\n\n<pre><code> start /D \"C:\\Program Files\\Internet Explorer\\\" IEXPLORE.EXE\n</code></pre>\n\n<p>or:</p>\n\n<pre><code> start /D \"TITLE\" \"C:\\Program Files\\Internet Explorer\\\" IEXPLORE.EXE\n</code></pre>\n\n<p>will start IE with default web page.</p>\n\n<pre><code> start /D \"TITLE\" \"C:\\Program Files\\Internet Explorer\\\" IEXPLORE.EXE www.bing.com\n</code></pre>\n\n<p>starts with Bing, but does not reset your home page.</p>\n\n<p><code>/D</code> stands for \"directory\" and using quotes is OK!</p>\n\n<p><strong>WRONG EXAMPLE:</strong> </p>\n\n<pre><code> start /D \"TITLE\" \"C:\\Program Files\\Internet Explorer\\IEXPLORE.EXE\"\n</code></pre>\n\n<p>gives:</p>\n\n<blockquote>\n <p>ERROR \"<em>The current directory is invalid.</em>\" </p>\n</blockquote>\n\n<p><code>/D</code> must only be followed by a directory path. Then space and the batchfile or program you wish to start/run</p>\n\n<p>Tested and works under XP but windows Vista/7/8 may need some adjustments to UAC.</p>\n\n<p>-Mrbios</p>\n"
},
{
"answer_id": 17140965,
"author": "Rafael Pereira",
"author_id": 2492168,
"author_profile": "https://Stackoverflow.com/users/2492168",
"pm_score": -1,
"selected": false,
"text": "<p>Change The \"Virtual PC.exe\" to a name without space like \"VirtualPC.exe\" in the folder.\nWhen you write <code>start \"path\"</code> with \"\" the CMD starts a new cmd window with the path as the title.\nChange the name to a name without space,write this on Notepad and after this save like Name.cmd or Name.bat:</p>\n\n<pre><code>CD\\\nCD Program Files\nCD Microsoft Virtual PC\nstart VirtualPC.exe\ntimeout 2\nexit\n</code></pre>\n\n<p>This command will redirect the CMD to the folder,start the VirualPC.exe,wait 2 seconds and exit.</p>\n"
},
{
"answer_id": 30354779,
"author": "BitDreamer",
"author_id": 4921154,
"author_profile": "https://Stackoverflow.com/users/4921154",
"pm_score": 0,
"selected": false,
"text": "<p>The answer in \"peculiarity\" is correct and directly answers the question. As TimF answered, since the first parameter is in quotes, it is treated as a window title. </p>\n\n<p>Also note that the Virtual PC options are being treated as options to the 'start' command itself, and are not valid for 'start'. This is true for all versions of Windows that have the 'start' command.</p>\n\n<p>This problem with 'start' treating the quoted parameter as a title is even more annoying that just the posted problem. If you run this:</p>\n\n<pre><code>start \"some valid command with spaces\"\n</code></pre>\n\n<p>You get a new command prompt window, with the obvious result for a window title.\nEven more annoying, this new window doesn't inherit customized font, colors or window size, it's just the default for cmd.exe.</p>\n"
},
{
"answer_id": 35458436,
"author": "Mack",
"author_id": 2429821,
"author_profile": "https://Stackoverflow.com/users/2429821",
"pm_score": 1,
"selected": false,
"text": "<p>If you want passing parameter and your .exe file in test folder of c: drive </p>\n\n<p><code>start \"parameter\" \"C:\\test\\test1.exe\" -pc My Name-PC -launch</code></p>\n\n<p>If you won't want passing parameter and your .exe file in test folder of c: drive</p>\n\n<p><code>start \"\" \"C:\\test\\test1.exe\" -pc My Name-PC -launch</code></p>\n\n<p>If you won't want passing parameter and your .exe file in test folder of H: (Any Other)drive </p>\n\n<p><code>start \"\" \"H:\\test\\test1.exe\" -pc My Name-PC -launch</code></p>\n"
},
{
"answer_id": 37229957,
"author": "T.Todua",
"author_id": 2377343,
"author_profile": "https://Stackoverflow.com/users/2377343",
"pm_score": -1,
"selected": false,
"text": "<h1><code>/b</code> parameter</h1>\n\n<pre><code>start /b \"\" \"c:\\program files\\Microsoft Virtual PC\\Virtual PC.exe\" -pc \"MY-PC\" -launch\n</code></pre>\n"
},
{
"answer_id": 43467321,
"author": "Mustafa Kemal",
"author_id": 3835640,
"author_profile": "https://Stackoverflow.com/users/3835640",
"pm_score": 0,
"selected": false,
"text": "<p>If you must use double quotation mark at any parameter, you can get error \"'c:\\somepath' is not recognized a an internal or external command, operable program or batch file\". \nI suggest below solution when using double qoutation mark:\n<a href=\"https://stackoverflow.com/a/43467194/3835640\">https://stackoverflow.com/a/43467194/3835640</a></p>\n"
},
{
"answer_id": 56447305,
"author": "JustAnotherMikhail",
"author_id": 11599952,
"author_profile": "https://Stackoverflow.com/users/11599952",
"pm_score": 2,
"selected": false,
"text": "<p>None of these answers worked for me.</p>\n\n<p>Instead, I had to use the Call command:</p>\n\n<pre><code>Call \"\\\\Path To Program\\Program.exe\" <parameters>\n</code></pre>\n\n<p>I'm not sure this actually waits for completion... the C++ Redistributable I was installing went fast enough that it didn't matter</p>\n"
}
] |
2008/09/30
|
[
"https://Stackoverflow.com/questions/154075",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/672/"
] |
I have a Virtual Machine in Virtual PC 2007.
To start it from the desktop, I have the following command in a batch file:
```
"c:\program files\Microsoft Virtual PC\Virtual PC.exe" -pc "MY-PC" -launch
```
But that leaves a dos prompt on the host machine until the virtual machine shuts down, and I exit out of the Virtual PC console. That's annoying.
So I changed my command to use the START command, instead:
```
start "c:\program files\Microsoft Virtual PC\Virtual PC.exe" -pc MY-PC -launch
```
But it chokes on the parameters passed into Virtual PC.
`START /?` indicates that parameters do indeed go in that location. Has anyone used START to launch a program with multiple command-line arguments?
|
START has a peculiarity involving double quotes around the first parameter. If the first parameter has double quotes it uses that as the optional TITLE for the new window.
I believe what you want is:
```
start "" "c:\program files\Microsoft Virtual PC\Virtual PC.exe" -pc MY-PC -launch
```
In other words, give it an empty title before the name of the program to fake it out.
|
154,089 |
<p>Anyone know how to programmatically mute the Windows XP Volume using C#?</p>
|
[
{
"answer_id": 154128,
"author": "Jorge Ferreira",
"author_id": 6508,
"author_profile": "https://Stackoverflow.com/users/6508",
"pm_score": 4,
"selected": false,
"text": "<p>Declare this for P/Invoke:</p>\n\n<pre><code>private const int APPCOMMAND_VOLUME_MUTE = 0x80000;\nprivate const int WM_APPCOMMAND = 0x319;\n\n[DllImport(\"user32.dll\")]\npublic static extern IntPtr SendMessageW(IntPtr hWnd, int Msg, IntPtr wParam, IntPtr lParam);\n</code></pre>\n\n<p>And then use this line to mute/unmute the sound.</p>\n\n<pre><code>SendMessageW(this.Handle, WM_APPCOMMAND, this.Handle, (IntPtr) APPCOMMAND_VOLUME_MUTE);\n</code></pre>\n"
},
{
"answer_id": 12534509,
"author": "Mike de Klerk",
"author_id": 1567665,
"author_profile": "https://Stackoverflow.com/users/1567665",
"pm_score": 3,
"selected": false,
"text": "<p>What you can use for Windows Vista/7 and probably 8 too:</p>\n\n<p>You can use <a href=\"https://github.com/naudio/NAudio\" rel=\"nofollow noreferrer\">NAudio</a>.<br>\nDownload the latest version. Extract the DLLs and reference the DLL NAudio in your C# project.</p>\n\n<p>Then add the following code to iterate through all available audio devices and mute it if possible.</p>\n\n<pre><code>try\n{\n //Instantiate an Enumerator to find audio devices\n NAudio.CoreAudioApi.MMDeviceEnumerator MMDE = new NAudio.CoreAudioApi.MMDeviceEnumerator();\n //Get all the devices, no matter what condition or status\n NAudio.CoreAudioApi.MMDeviceCollection DevCol = MMDE.EnumerateAudioEndPoints(NAudio.CoreAudioApi.DataFlow.All, NAudio.CoreAudioApi.DeviceState.All);\n //Loop through all devices\n foreach (NAudio.CoreAudioApi.MMDevice dev in DevCol)\n {\n try\n {\n //Show us the human understandable name of the device\n System.Diagnostics.Debug.Print(dev.FriendlyName);\n //Mute it\n dev.AudioEndpointVolume.Mute = true;\n }\n catch (Exception ex)\n {\n //Do something with exception when an audio endpoint could not be muted\n }\n }\n}\ncatch (Exception ex)\n{\n //When something happend that prevent us to iterate through the devices\n}\n</code></pre>\n"
},
{
"answer_id": 21510757,
"author": "Aleks",
"author_id": 3258422,
"author_profile": "https://Stackoverflow.com/users/3258422",
"pm_score": 2,
"selected": false,
"text": "<p>See <a href=\"http://alvas.net/alvas.audio,tips.aspx#tip115\" rel=\"nofollow noreferrer\" title=\"How to programmatically mute the Windows XP Volume using C#?\">How to programmatically mute the Windows XP Volume using C#?</a></p>\n\n<pre><code>void SetPlayerMute(int playerMixerNo, bool value)\n{\n Mixer mx = new Mixer();\n mx.MixerNo = playerMixerNo;\n DestinationLine dl = mx.GetDestination(Mixer.Playback);\n if (dl != null)\n {\n foreach (MixerControl ctrl in dl.Controls)\n {\n if (ctrl is MixerMuteControl)\n {\n ((MixerMuteControl)ctrl).Value = (value) ? 1 : 0;\n break;\n }\n }\n }\n}\n</code></pre>\n"
},
{
"answer_id": 64412819,
"author": "J. Andersen",
"author_id": 7048651,
"author_profile": "https://Stackoverflow.com/users/7048651",
"pm_score": 0,
"selected": false,
"text": "<p>This is a slightly improved version of Mike de Klerks answer that doesn't require "on error resume next" code.</p>\n<p>Step 1: Add the NAudio NuGet-package to your project (<a href=\"https://www.nuget.org/packages/NAudio/\" rel=\"nofollow noreferrer\">https://www.nuget.org/packages/NAudio/</a>)</p>\n<p>Step 2: Use this code:</p>\n<pre><code>using (var enumerator = new NAudio.CoreAudioApi.MMDeviceEnumerator())\n{\n foreach (var device in enumerator.EnumerateAudioEndPoints(NAudio.CoreAudioApi.DataFlow.Render, NAudio.CoreAudioApi.DeviceState.Active))\n {\n if (device.AudioEndpointVolume?.HardwareSupport.HasFlag(NAudio.CoreAudioApi.EEndpointHardwareSupport.Mute) == true)\n {\n Console.WriteLine(device.FriendlyName);\n device.AudioEndpointVolume.Mute = false;\n }\n }\n}\n</code></pre>\n"
},
{
"answer_id": 70971045,
"author": "Guest",
"author_id": 18109606,
"author_profile": "https://Stackoverflow.com/users/18109606",
"pm_score": -1,
"selected": false,
"text": "<pre><code>CoreAudioDevice defaultPlaybackDevice = new \nCoreAudioController().DefaultPlaybackDevice; \n if (!defaultPlaybackDevice.IsMuted)\n defaultPlaybackDevice.ToggleMute();\n</code></pre>\n"
}
] |
2008/09/30
|
[
"https://Stackoverflow.com/questions/154089",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1316/"
] |
Anyone know how to programmatically mute the Windows XP Volume using C#?
|
Declare this for P/Invoke:
```
private const int APPCOMMAND_VOLUME_MUTE = 0x80000;
private const int WM_APPCOMMAND = 0x319;
[DllImport("user32.dll")]
public static extern IntPtr SendMessageW(IntPtr hWnd, int Msg, IntPtr wParam, IntPtr lParam);
```
And then use this line to mute/unmute the sound.
```
SendMessageW(this.Handle, WM_APPCOMMAND, this.Handle, (IntPtr) APPCOMMAND_VOLUME_MUTE);
```
|
154,109 |
<p>When using the ObsoleteAtribute in .Net it gives you compiler warnings telling you that the object/method/property is obsolete and somthing else should be used. I'm currently working on a project that requires a lot of refactoring an ex-employees code. I want to write a custom attribute that I can use to mark methods or properties that will generate compiler warnings that give messages that I write. Something like this</p>
<pre class="lang-cs prettyprint-override"><code>[MyAttribute("This code sux and should be looked at")]
public void DoEverything()
{
}
</code></pre>
<pre class="lang-vb prettyprint-override"><code><MyAttribute("This code sux and should be looked at")>
Public Sub DoEverything()
End Sub
</code></pre>
<p>I want this to generate a compiler warning that says, "This code sux and should be looked at". I know how to create a custom attribute, the question is how do I cause it to generate compiler warnings in visual studio.</p>
|
[
{
"answer_id": 154120,
"author": "Douglas Mayle",
"author_id": 8458,
"author_profile": "https://Stackoverflow.com/users/8458",
"pm_score": 6,
"selected": false,
"text": "<p>In some compilers you can use #warning to issue a warning:</p>\n\n<pre><code>#warning \"Do not use ABC, which is deprecated. Use XYZ instead.\"\n</code></pre>\n\n<p>In Microsoft compilers, you can typically use the message pragma:</p>\n\n<pre><code>#pragma message ( \"text\" )\n</code></pre>\n\n<p>You mentioned .Net, but didn't specify whether you were programming with C/C++ or C#. If you're programming in C#, than you should know that <a href=\"http://msdn.microsoft.com/en-us/library/963th5x3(VS.71).aspx\" rel=\"noreferrer\">C# supports the #warning format</a>.</p>\n"
},
{
"answer_id": 154221,
"author": "technophile",
"author_id": 23029,
"author_profile": "https://Stackoverflow.com/users/23029",
"pm_score": 2,
"selected": false,
"text": "<p>I don't think you can. As far as I know support for ObsoleteAttribute is essentially hardcoded into the C# compiler; you can't do anything similar directly.</p>\n\n<p>What you might be able to do is use an MSBuild task (or a post-build event) that executes a custom tool against the just-compiled assembly. The custom tool would reflect over all types/methods in the assembly and consume your custom attribute, at which point it could print to System.Console's default or error TextWriters.</p>\n"
},
{
"answer_id": 154254,
"author": "Pablo Fernandez",
"author_id": 7595,
"author_profile": "https://Stackoverflow.com/users/7595",
"pm_score": 7,
"selected": false,
"text": "<p>This is worth a try.</p>\n\n<p>You can't extend Obsolete, because it's final, but maybe you can create your own attribute, and mark that class as obsolete like this:</p>\n\n<pre><code>[Obsolete(\"Should be refactored\")]\npublic class MustRefactor: System.Attribute{}\n</code></pre>\n\n<p>Then when you mark your methods with the \"MustRefactor\" attribute, the compile warnings will show. It generates a compile time warning, but the error message looks funny, you should see it for yourself and choose. This is very close to what you wanted to achieve. </p>\n\n<p><strong>UPDATE:\nWith <a href=\"http://pastie.org/282556\" rel=\"noreferrer\">this code</a> It generates a warning (not very nice, but I don't think there's something better).</strong></p>\n\n<pre><code>public class User\n{\n private String userName;\n\n [TooManyArgs] // Will show warning: Try removing some arguments\n public User(String userName)\n {\n this.userName = userName; \n }\n\n public String UserName\n {\n get { return userName; }\n }\n [MustRefactor] // will show warning: Refactor is needed Here\n public override string ToString()\n {\n return \"User: \" + userName;\n }\n}\n[Obsolete(\"Refactor is needed Here\")]\npublic class MustRefactor : System.Attribute\n{\n\n}\n[Obsolete(\"Try removing some arguments\")]\npublic class TooManyArgs : System.Attribute\n{\n\n}\n</code></pre>\n"
},
{
"answer_id": 154260,
"author": "bdukes",
"author_id": 2688,
"author_profile": "https://Stackoverflow.com/users/2688",
"pm_score": 2,
"selected": false,
"text": "<p>Looking at the source for <a href=\"http://msdn.microsoft.com/en-us/library/system.obsoleteattribute.aspx\" rel=\"nofollow noreferrer\">ObsoleteAttribute</a>, it doesn't look like it's doing anything special to generate a compiler warning, so I would tend to go with @<a href=\"https://stackoverflow.com/questions/154109/custom-compiler-warnings#154221\">technophile</a> and say that it is hard-coded into the compiler. Is there a reason you don't want to just use <a href=\"http://msdn.microsoft.com/en-us/library/system.obsoleteattribute.aspx\" rel=\"nofollow noreferrer\">ObsoleteAttribute</a> to generate your warning messages?</p>\n"
},
{
"answer_id": 154296,
"author": "ljs",
"author_id": 3394,
"author_profile": "https://Stackoverflow.com/users/3394",
"pm_score": 6,
"selected": true,
"text": "<h2>Update</h2>\n<p>This is now possible with Roslyn (Visual Studio 2015). You can <a href=\"https://johnkoerner.com/csharp/creating-your-first-code-analyzer/\" rel=\"nofollow noreferrer\">build</a> a <a href=\"https://github.com/dotnet/roslyn/wiki/How-To-Write-a-C%23-Analyzer-and-Code-Fix\" rel=\"nofollow noreferrer\">code analyzer</a> to check for a custom attribute</p>\n<hr />\n<p><em>Original outdated answer:</em></p>\n<p>I don't believe it's possible. ObsoleteAttribute is treated specially by the compiler and is defined in the C# standard. Why on earth is ObsoleteAttribute not acceptable? It seems to me like this is precisely the situation it was designed for, and achieves precisely what you require!</p>\n<p>Also note that Visual Studio picks up the warnings generated by ObsoleteAttribute on the fly too, which is very useful.</p>\n<p>Don't mean to be unhelpful, just wondering why you're not keen on using it...</p>\n<p>Unfortunately ObsoleteAttribute is sealed (probably partly due to the special treatment) hence you can't subclass your own attribute from it.</p>\n<p>From the C# standard:-</p>\n<blockquote>\n<p>The attribute Obsolete is used to mark\ntypes and members of types that should\nno longer be used.</p>\n<p>If a program uses a type or member\nthat is decorated with the Obsolete\nattribute, the compiler issues a\nwarning or an error. Specifically, the\ncompiler issues a warning if no error\nparameter is provided, or if the error\nparameter is provided and has the\nvalue false. The compiler issues an\nerror if the error parameter is\nspecified and has the value true.</p>\n</blockquote>\n<p>Doesn't that sum up your needs?... you're not going to do better than that I don't think.</p>\n"
},
{
"answer_id": 154622,
"author": "Ted Elliott",
"author_id": 16501,
"author_profile": "https://Stackoverflow.com/users/16501",
"pm_score": 6,
"selected": false,
"text": "<p>We're currently in the middle of a lot of refactoring where we couldn't fix everything right away. We just use the #warning preproc command where we need to go back and look at code. It shows up in the compiler output. I don't think you can put it on a method, but you could put it just inside the method, and it's still easy to find.</p>\n\n<pre><code>public void DoEverything() {\n #warning \"This code sucks\"\n}\n</code></pre>\n"
},
{
"answer_id": 2038833,
"author": "Tomasz Modelski",
"author_id": 195922,
"author_profile": "https://Stackoverflow.com/users/195922",
"pm_score": 3,
"selected": false,
"text": "<p>In VS 2008 (+sp1) #warnings don't show properly in Error List after Clean Soultion & Rebuild Solution, no all of them. \nSome Warnings are showed in the Error List only after I open particular class file. \nSo I was forced to use custom attribute: </p>\n\n<pre><code>[Obsolete(\"Mapping ToDo\")]\n[AttributeUsage(AttributeTargets.Class | AttributeTargets.Property)]\npublic class MappingToDo : System.Attribute\n{\n public string Comment = \"\";\n\n public MappingToDo(string comment)\n {\n Comment = comment;\n }\n\n public MappingToDo()\n {}\n}\n</code></pre>\n\n<p>So when I flag some code with it</p>\n\n<pre><code>[MappingToDo(\"Some comment\")]\npublic class MembershipHour : Entity\n{\n // .....\n}\n</code></pre>\n\n<p>It produces warnings like this: </p>\n\n<blockquote>\n <p>Namespace.MappingToDo is obsolete:\n 'Mapping ToDo'.</p>\n</blockquote>\n\n<p>I can't change the text of the warning, 'Some comment' is not showed it Error List. \nBut it will jump to proper place in file. \nSo if you need to vary such warning messages, create various attributes.</p>\n"
},
{
"answer_id": 26089913,
"author": "user4089256",
"author_id": 4089256,
"author_profile": "https://Stackoverflow.com/users/4089256",
"pm_score": 3,
"selected": false,
"text": "<p>What you are trying to do is a misuse of attributes. Instead use the Visual Studio Task List. You can enter a comment in your code like this:</p>\n\n<pre><code>//TODO: This code sux and should be looked at\npublic class SuckyClass(){\n //TODO: Do something really sucky here!\n}\n</code></pre>\n\n<p>Then open View / Task List from the menu. The task list has two categories, user tasks and Comments. Switch to Comments and you will see all of your //Todo:'s there. Double clicking on a TODO will jump to the comment in your code.</p>\n\n<p>Al</p>\n"
},
{
"answer_id": 26892393,
"author": "bubi",
"author_id": 3464614,
"author_profile": "https://Stackoverflow.com/users/3464614",
"pm_score": 1,
"selected": false,
"text": "<p>There are several comments that suggest to insert warnings or pragma.\nObsolete works in a very different way!\nMarking obsolete a function of a library L, the obsolete message raises when a program calls the function even if the caller program is not in the library L. Warning raises the message ONLY when L is compiled.</p>\n"
},
{
"answer_id": 45419471,
"author": "johnny 5",
"author_id": 1938988,
"author_profile": "https://Stackoverflow.com/users/1938988",
"pm_score": 2,
"selected": false,
"text": "<p>Here is the Roslyn Implementation, so you can create your own attributes that give warnings or errors on the fly. </p>\n\n<p>I've create an attribute Type Called <code>IdeMessage</code> which will be the attribute which generates warnings:</p>\n\n<pre><code>[AttributeUsage(AttributeTargets.Method, AllowMultiple = true, Inherited = true)]\npublic class IDEMessageAttribute : Attribute\n{\n public string Message;\n\n public IDEMessageAttribute(string message);\n}\n</code></pre>\n\n<p>In order to do this you need to install the Roslyn SDK first and start a new VSIX project with analyzer. I've omitted some of the less relevant piece like the messages, you can figure out how to do that. In your analyzer you do this</p>\n\n<pre><code>public override void Initialize(AnalysisContext context)\n{\n context.RegisterSyntaxNodeAction(AnalyzerInvocation, SyntaxKind.InvocationExpression);\n}\n\nprivate static void AnalyzerInvocation(SyntaxNodeAnalysisContext context)\n{\n var invocation = (InvocationExpressionSyntax)context.Node;\n\n var methodDeclaration = (context.SemanticModel.GetSymbolInfo(invocation, context.CancellationToken).Symbol as IMethodSymbol);\n\n //There are several reason why this may be null e.g invoking a delegate\n if (null == methodDeclaration)\n {\n return;\n }\n\n var methodAttributes = methodDeclaration.GetAttributes();\n var attributeData = methodAttributes.FirstOrDefault(attr => IsIDEMessageAttribute(context.SemanticModel, attr, typeof(IDEMessageAttribute)));\n if(null == attributeData)\n {\n return;\n }\n\n var message = GetMessage(attributeData); \n var diagnostic = Diagnostic.Create(Rule, invocation.GetLocation(), methodDeclaration.Name, message);\n context.ReportDiagnostic(diagnostic);\n}\n\nstatic bool IsIDEMessageAttribute(SemanticModel semanticModel, AttributeData attribute, Type desiredAttributeType)\n{\n var desiredTypeNamedSymbol = semanticModel.Compilation.GetTypeByMetadataName(desiredAttributeType.FullName);\n\n var result = attribute.AttributeClass.Equals(desiredTypeNamedSymbol);\n return result;\n}\n\nstatic string GetMessage(AttributeData attribute)\n{\n if (attribute.ConstructorArguments.Length < 1)\n {\n return \"This method is obsolete\";\n }\n\n return (attribute.ConstructorArguments[0].Value as string);\n}\n</code></pre>\n\n<p>There are no CodeFixProvider for this you can remove it from the solution.</p>\n"
}
] |
2008/09/30
|
[
"https://Stackoverflow.com/questions/154109",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/17744/"
] |
When using the ObsoleteAtribute in .Net it gives you compiler warnings telling you that the object/method/property is obsolete and somthing else should be used. I'm currently working on a project that requires a lot of refactoring an ex-employees code. I want to write a custom attribute that I can use to mark methods or properties that will generate compiler warnings that give messages that I write. Something like this
```cs
[MyAttribute("This code sux and should be looked at")]
public void DoEverything()
{
}
```
```vb
<MyAttribute("This code sux and should be looked at")>
Public Sub DoEverything()
End Sub
```
I want this to generate a compiler warning that says, "This code sux and should be looked at". I know how to create a custom attribute, the question is how do I cause it to generate compiler warnings in visual studio.
|
Update
------
This is now possible with Roslyn (Visual Studio 2015). You can [build](https://johnkoerner.com/csharp/creating-your-first-code-analyzer/) a [code analyzer](https://github.com/dotnet/roslyn/wiki/How-To-Write-a-C%23-Analyzer-and-Code-Fix) to check for a custom attribute
---
*Original outdated answer:*
I don't believe it's possible. ObsoleteAttribute is treated specially by the compiler and is defined in the C# standard. Why on earth is ObsoleteAttribute not acceptable? It seems to me like this is precisely the situation it was designed for, and achieves precisely what you require!
Also note that Visual Studio picks up the warnings generated by ObsoleteAttribute on the fly too, which is very useful.
Don't mean to be unhelpful, just wondering why you're not keen on using it...
Unfortunately ObsoleteAttribute is sealed (probably partly due to the special treatment) hence you can't subclass your own attribute from it.
From the C# standard:-
>
> The attribute Obsolete is used to mark
> types and members of types that should
> no longer be used.
>
>
> If a program uses a type or member
> that is decorated with the Obsolete
> attribute, the compiler issues a
> warning or an error. Specifically, the
> compiler issues a warning if no error
> parameter is provided, or if the error
> parameter is provided and has the
> value false. The compiler issues an
> error if the error parameter is
> specified and has the value true.
>
>
>
Doesn't that sum up your needs?... you're not going to do better than that I don't think.
|
154,112 |
<p>Without running this code, identify which <code>Foo</code> method will be called:</p>
<pre><code>class A
{
public void Foo( int n )
{
Console.WriteLine( "A::Foo" );
}
}
class B : A
{
/* note that A::Foo and B::Foo are not related at all */
public void Foo( double n )
{
Console.WriteLine( "B::Foo" );
}
}
static void Main( string[] args )
{
B b = new B();
/* which Foo is chosen? */
b.Foo( 5 );
}
</code></pre>
<p>Which method? And why? No cheating by running the code.</p>
<p>I found this puzzle on the web; I like it and I think I'm going to use it as an interview question...Opinions?</p>
<p>EDIT: I wouldn't judge a candidate on getting this wrong, I'd use it as a way to open a fuller discussion about the C# and CLR itself, so I can get a good understanding of the candidates abilities.</p>
<p><strong>Source:</strong> <a href="http://netpl.blogspot.com/2008/06/c-puzzle-no8-beginner.html" rel="noreferrer">http://netpl.blogspot.com/2008/06/c-puzzle-no8-beginner.html</a></p>
|
[
{
"answer_id": 154139,
"author": "Patrick Desjardins",
"author_id": 13913,
"author_profile": "https://Stackoverflow.com/users/13913",
"pm_score": 3,
"selected": false,
"text": "<p>Console.WriteLine( \"B::Foo\");</p>\n\n<p>Because it will cast automatictly and use the first without going further in the inheritance.</p>\n\n<p>I do not think it's a good interview question but it can be funny to try to solve without compiling the code.</p>\n"
},
{
"answer_id": 154145,
"author": "Jon Skeet",
"author_id": 22656,
"author_profile": "https://Stackoverflow.com/users/22656",
"pm_score": 6,
"selected": false,
"text": "<p>I really wouldn't use this as an interview question. I know the answer and the reasoning behind it, but something like this should come up so rarely that it shouldn't be a problem. Knowing the answer really doesn't show much about a candidate's ability to code.</p>\n\n<p>Note that you'll get the same behaviour even if A.Foo is virtual and B overrides it.</p>\n\n<p>If you like C# puzzles and oddities, <a href=\"http://pobox.com/~skeet/csharp/teasers.html\" rel=\"noreferrer\">I've got a few too (including this one)</a>.</p>\n"
},
{
"answer_id": 154286,
"author": "Joel Coehoorn",
"author_id": 3043,
"author_profile": "https://Stackoverflow.com/users/3043",
"pm_score": 3,
"selected": false,
"text": "<p>Another vote against using it, but for a different reason. </p>\n\n<p>When put on the spot like this, a lot of really good programmers would come up with the wrong answer, but not because they don't know the concepts or couldn't figure it out. What happens is that they'll see something like this and think, \"Aha, trick question!\", and then proceed to out-think themselves in the response. This is especially true in an interview setting where they don't have the benefit of the IDE or Google or any other of the other helps a programmer takes for granted in their day to day programming.</p>\n"
},
{
"answer_id": 154385,
"author": "plinth",
"author_id": 20481,
"author_profile": "https://Stackoverflow.com/users/20481",
"pm_score": 5,
"selected": false,
"text": "<p>Too hard? No, but what is your goal in the question? What are you expecting to get from your interviewee? That they know this particular syntactic quirk? That either means that they've studied the spec/language well (good for them) or that they've run into this problem (hopefully not from what they wrote, but if they did - yikes). Neither case really indicates that you've got a solid programmer/engineer/architect on your hand. I believe that what's important is not the question but the discussion surrounding the question.</p>\n\n<p>When I interview candidates, I usually ask one deceptively simple question which is based on a language semantic quirk - but I don't care if my interviewee knows it because that semantic quirk allows me to open up a lot of avenues that allow me to find out if my candidate is methodical, their communication style, if they're willing to say \"I don't know\", are they capable of thinking on their feet, do they understand language design and machine architecture, do they understand platform and portability issues - in short, I'm looking for a lot of ingredients that all add up to \"do they get it?\". This process takes an hour or more.</p>\n\n<p>In the end, I don't actually care about whether they know the answer to my question - the question is a ruse to let me get all the rest of that information indirectly without ever having to ask. If you don't have a valuable ulterior in this question, don't bother even asking it - you're wasting your time and your candidate's time.</p>\n"
},
{
"answer_id": 154391,
"author": "Bill",
"author_id": 14547,
"author_profile": "https://Stackoverflow.com/users/14547",
"pm_score": 4,
"selected": false,
"text": "<p>Couldn't agree more with Joel there. I have 20+ years experience design and coding, and the first thing I thought of when I saw that was: It won't even compile. </p>\n\n<p>I made that assumption because I try to avoid overloads that differ by only a single datatype, and in looking at the code didn't even pick up on the int/double difference; I assumed there needed to be a new operator to allow a redefinition in B.</p>\n\n<p>In point of fact I had used a library a fellow programmer created for handling some text file generation that was a bit confusing because one of the methods had 8 different overloads and two of them differed only by datatype on the last argument. One was string and one was char. The likelihood that the value needed for the string version of the parameter was one character long was pretty good so hopefully you can see where this is headed. We had a devil of a time debugging problems because the consumer of the library inadvertently triggered the wrong call because of quoting differences, single versus double. </p>\n\n<p>Moral of the story, be grateful that the candidate doesn't know the answer because it may indicate good coding habits.</p>\n"
},
{
"answer_id": 154460,
"author": "Mark Ransom",
"author_id": 5987,
"author_profile": "https://Stackoverflow.com/users/5987",
"pm_score": 2,
"selected": false,
"text": "<p>This smacks of a trick question to me. If you've been using the language for long enough, you've probably run into the problem and know the answer; but how long is long enough?</p>\n\n<p>It's also a question where your background might work against you. I know in C++ the definition in B would hide the definition in A, but I have no idea if it works the same in C#. In real life, I'd know it was a questionable area and try to look it up. In an interview I might try to guess, having been put on the spot. And I'd probably get it wrong.</p>\n"
},
{
"answer_id": 154484,
"author": "gbjbaanb",
"author_id": 13744,
"author_profile": "https://Stackoverflow.com/users/13744",
"pm_score": 2,
"selected": false,
"text": "<p>use it as a question only as long as you expect the candidate to tell you his thought processes as he describes what he thinks should be happening. Who cares about the right and wrongness of actual code in question - in the real world, the candidate would find code like this, find it not working and debug it with a combination of debugger and writeline calls, so its a useless question if you want candidates who know (or guess) the right answer.</p>\n\n<p>But those who can explain what they think would happen, that's a different matter. Hire them even if they get it wrong.</p>\n"
},
{
"answer_id": 155251,
"author": "Ryan Lundy",
"author_id": 5486,
"author_profile": "https://Stackoverflow.com/users/5486",
"pm_score": 2,
"selected": false,
"text": "<p>I think it's a terrible question. I think any question is a terrible question when the real answer is \"Run it and see!\"</p>\n\n<p>If I needed to know this in real life, that's exactly what I'd do: Create a test project, key it in, and find out. Then I don't have to worry about abstract reasoning or the finer points in the C# spec.</p>\n\n<p>Just today I ran into such a question: If I fill the same typed DataTable twice with the same row, what will happen? One copy of the row, or two? And will it overwrite the first row even if I've changed it? I thought about asking someone, but I realized I could easily fire up a test project I already had that used DataSets, write a small method, and test it out.</p>\n\n<p>Answer:</p>\n\n<p>...ah, but if I tell you, you'll miss the point. :) The point is, in programming you don't have to leave these things as hypotheticals, and you <em>shouldn't</em> if they can be reasonably tested.</p>\n\n<p>So I think it's a terrible question. Wouldn't you prefer to hire a developer who'll try it out and then <em>know</em> what happens, rather than a developer who'll try to dredge it up from his fading memory, or who'll ask someone else and accept an answer that might be wrong?</p>\n"
},
{
"answer_id": 155771,
"author": "Mike Rosenblum",
"author_id": 10429,
"author_profile": "https://Stackoverflow.com/users/10429",
"pm_score": 3,
"selected": false,
"text": "<p>This actually is a trick question.</p>\n\n<p>The answer is ambiguous as to what \"should\" happen. Sure, the C# compiler takes it out of the realm of ambiguity to the concrete; however, since these methods are overloading one another, and are neither overriding nor shadowing, it is reasonable to assume that the \"best argument fit\" should apply here, and therefore conclude that it is A::Foo(int n) that should be called when provided an integer as an argument.</p>\n\n<p>To prove that what \"should\" happen is unclear, the exact same code when run in VB.NET has the opposite result:</p>\n\n<pre><code>Public Class Form1\n Private Sub Button1_Click(ByVal sender As System.Object, _\n ByVal e As System.EventArgs) _\n Handles Button1.Click\n Dim b As New B\n b.Foo(5) ' A::Foo\n b.Foo(5.0) ' B::Foo\n End Sub\nEnd Class\n\nClass A\n Sub Foo(ByVal n As Integer)\n MessageBox.Show(\"A::Foo\")\n End Sub\nEnd Class\n\nClass B\n Inherits A\n\n Overloads Sub Foo(ByVal n As Double)\n MessageBox.Show(\"B::Foo\")\n End Sub\nEnd Class\n</code></pre>\n\n<p>I realize that I am opening up the opportunity for the C# programmers to \"bash\" VB.NET for not complying with C# . But I think one could make a very strong argument that it is VB.NET that is making the proper interpretation here.</p>\n\n<p>Further, IntelliSense within the C# IDE suggests that there are two overloads for the class B (because there are, or at least should be!), but the B.Foo(int n) version actually can't be called (not without first explicitly casting to a class A). The result is that the C# IDE is not actually in synch with the C# compiler. </p>\n\n<p>Another way of looking at this is that the C# compiler is taking an intended overloads and turning it into a shadowed method. (This doesn't seem to be the right choice to me, but this is obviously just an opinion.)</p>\n\n<p>As an interview question, I think that it can be ok if you are interested in getting a discussion about the issues here. As for getting it \"right\" or \"wrong\", I think that the question verges on a trick question that could be easily missed, or even gotten right, for the wrong reasons. In fact, what the answer to the question \"should be\" is actually very debatable.</p>\n"
},
{
"answer_id": 156160,
"author": "Mark Brackett",
"author_id": 2199,
"author_profile": "https://Stackoverflow.com/users/2199",
"pm_score": 2,
"selected": false,
"text": "<p>That's a ridiculous question to ask - I could answer it in < 60 seconds with Snippet Compiler, and if I ever worked in a code base that depended on the functionality - it'd be quickly refactored out of existence.</p>\n\n<p>The best answer is \"that's a stupid design, don't do that and you won't have to parse the language spec to know what it's going to do\".</p>\n\n<p>If I was the interviewee, I'd think very highly of your geek trivia cred, and would perhaps invite you to the next game of Geek Trivial Pursuit. But, I'm not so sure I'd want to work with/for you. If that's your goal, by all means ask away.</p>\n\n<ul>\n<li>Note that in an informal situation, geek trivia like this can be fun and entertaining. But, to an interviewee, an interview is anything but fun or informal - why further agitate it with trivial questions that the interviewee doesn't know if you take seriously or not?</li>\n</ul>\n"
},
{
"answer_id": 161996,
"author": "Keith",
"author_id": 905,
"author_profile": "https://Stackoverflow.com/users/905",
"pm_score": 3,
"selected": false,
"text": "<p>Not really fair as an interview question, as it's a bit of a trick question. The good answer I'd want from an interviewee would be more along the lines of <em>\"That needs refactoring\"</em>.</p>\n\n<p>Unless you're looking to hire someone to work on compilers I'm not sure that you need to go that much in depth into the CLR.</p>\n\n<p>For interview questions I look for things that show the coder's level of understanding in their answer. This is more of an oddity/puzzle.</p>\n"
},
{
"answer_id": 216116,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 0,
"selected": false,
"text": "<p>Try a similar sample given below:</p>\n\n<pre><code>class Program\n{\n class P\n {}\n class Q : P\n {}\n\n class A \n { \n public void Fee(Q q)\n {\n Console.WriteLine(\"A::Fee\");\n }\n }\n\n class B : A \n { \n public void Fee(P p)\n {\n Console.WriteLine(\"B::Fee\");\n }\n }\n\n static void Main(string[] args) \n { \n B b = new B(); \n /* which Fee is chosen? */ \n\n b.Fee(new Q());\n Console.ReadKey();\n }\n}\n</code></pre>\n\n<p>The compiler seems to prefer linking the \"b.Fee()\" call to an available method of the type rather than an inherited method (method of a base type) if the parameter can be implicitly cast to match any such method. I.e. implicit casting of the parameter takes precedence over base class method linking.</p>\n\n<p>Though honestly I find the opposite as more intuitive, because for me an inherited method is just as good as a directly introduced method.</p>\n"
},
{
"answer_id": 1612066,
"author": "Anwar",
"author_id": 195163,
"author_profile": "https://Stackoverflow.com/users/195163",
"pm_score": 0,
"selected": false,
"text": "<p>Code given in question will print <code>B::Foo</code>.</p>\n"
},
{
"answer_id": 9006838,
"author": "Lee Louviere",
"author_id": 491837,
"author_profile": "https://Stackoverflow.com/users/491837",
"pm_score": 2,
"selected": false,
"text": "<p>It takes all of 5 seconds in a real work situation to figure out what went wrong. Compile, test, oops.</p>\n\n<p>I'm far more concerned on if someone can build good and maintainable code. Ask questions like </p>\n\n<ul>\n<li>How would you design for this, write simple abstract design, no code.</li>\n<li>Here's an object design. The customer came and said they wanted this. Formulate a new design -or- discuss reasons why the requirements don't fulfill actual customer needs.</li>\n</ul>\n"
},
{
"answer_id": 13208754,
"author": "beltry",
"author_id": 338967,
"author_profile": "https://Stackoverflow.com/users/338967",
"pm_score": 0,
"selected": false,
"text": "<p>As many have already stated, when I interview someone I want to find out if the candidate is capable of communicating, capable of writing code which makes sense and it can be easily understood by others, code which can be maintained and so forth.\nI personally don't like to spend time in exercises like the one proposed.\nInstead I'd rather give an exercise where the candidate will write code him/herself - even in a regular text editor - and from there opening a discussion based on code review, improvements as so forth. No need the code to compile: compiler will do its job, eventually.\nI know many people may disagree on this approach, but so far I have found this the best way of finding good candidates.</p>\n"
}
] |
2008/09/30
|
[
"https://Stackoverflow.com/questions/154112",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1965/"
] |
Without running this code, identify which `Foo` method will be called:
```
class A
{
public void Foo( int n )
{
Console.WriteLine( "A::Foo" );
}
}
class B : A
{
/* note that A::Foo and B::Foo are not related at all */
public void Foo( double n )
{
Console.WriteLine( "B::Foo" );
}
}
static void Main( string[] args )
{
B b = new B();
/* which Foo is chosen? */
b.Foo( 5 );
}
```
Which method? And why? No cheating by running the code.
I found this puzzle on the web; I like it and I think I'm going to use it as an interview question...Opinions?
EDIT: I wouldn't judge a candidate on getting this wrong, I'd use it as a way to open a fuller discussion about the C# and CLR itself, so I can get a good understanding of the candidates abilities.
**Source:** <http://netpl.blogspot.com/2008/06/c-puzzle-no8-beginner.html>
|
I really wouldn't use this as an interview question. I know the answer and the reasoning behind it, but something like this should come up so rarely that it shouldn't be a problem. Knowing the answer really doesn't show much about a candidate's ability to code.
Note that you'll get the same behaviour even if A.Foo is virtual and B overrides it.
If you like C# puzzles and oddities, [I've got a few too (including this one)](http://pobox.com/~skeet/csharp/teasers.html).
|
154,117 |
<p>Is there a way to execute a full ASPX source file where the page source is from a string/database/resource and not a file on the file system? It's straightfoward to render dynamic content/images/etc using HTTP Handlers and Modules and writing to the Response, but there doesn't seem to be a way to execute/compile ASPX source without a file on the file system. For example:</p>
<ul>
<li>HttpContext.Current.Server.Execute() overloads require a path to a file </li>
<li>System.Web.Compilation.BuildManager can only create from a virtual path </li>
</ul>
<p>The goal is to be able to execute a string source like the following from a Handler/Module/ViewEngine and not require a file on the file system (but get the source from another location):</p>
<pre><code><%@ Page language="C#" MasterPageFile="~/Shared/Site.Master" Inherits="System.Web.UI.Page" %>
<!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 id="Head1" runat="server">
<title>ListView Example</title>
</head>
<body>
<form id="form1" runat="server">
<h3>ListView Example</h3>
<asp:ListView ID="List" runat="server" DataSourceID="ProductDataSource">
<LayoutTemplate><ol><asp:PlaceHolder runat="server" ID="itemPlaceholder"></asp:PlaceHolder></ol></LayoutTemplate>
<ItemTemplate><li><%# Eval("ProductName") %></li></ItemTemplate>
</asp:ListView>
<asp:AccessDataSource ID="ProductDataSource" runat="server"DataFile="~/App_Data/Northwind.mdb"SelectCommand="SELECT [ProductName], [QuantityPerUnit], [UnitPrice], [CategoryName] FROM [Alphabetical List of Products]"></asp:AccessDataSource>
</form>
</body>
</html>
</code></pre>
<p>(NOTE: The sample above is just a simple example, but shows using server controls, data binding syntax, a master page and possible user control declarations in page directives, etc...) </p>
<p>I hope this makes sense!</p>
|
[
{
"answer_id": 154240,
"author": "Gulzar Nazim",
"author_id": 4337,
"author_profile": "https://Stackoverflow.com/users/4337",
"pm_score": 1,
"selected": false,
"text": "<p>Update: Check the post by <a href=\"https://stackoverflow.com/questions/154117#154279\">korchev</a> using virtualpathprovider, which is more suited for this scenario.</p>\n\n<p>Can you use a dummy file with a place holder <strong>literal</strong> control and replace the literal control with the actual source?</p>\n\n<p>These might not be useful but posting couple of links I found:</p>\n\n<p><a href=\"http://www.west-wind.com/weblog/posts/120530.aspx\" rel=\"nofollow noreferrer\">Loading an ASP.NET Page Class dynamically in an HttpHandler</a></p>\n\n<p><a href=\"http://weblogs.asp.net/palermo4/archive/2007/07/06/how-to-dynamically-load-a-page-for-processing.aspx\" rel=\"nofollow noreferrer\">How To: Dynamically Load A Page For Processing</a> </p>\n"
},
{
"answer_id": 154279,
"author": "Atanas Korchev",
"author_id": 10141,
"author_profile": "https://Stackoverflow.com/users/10141",
"pm_score": 4,
"selected": true,
"text": "<p>Perhaps you need a <a href=\"http://msdn.microsoft.com/en-us/library/system.web.hosting.virtualpathprovider.aspx\" rel=\"noreferrer\">virtual path provider</a>. It allows you to store the ASPX and codebehind in different media - RDBMS, xml file etc.</p>\n"
},
{
"answer_id": 155382,
"author": "Andrei Rînea",
"author_id": 1796,
"author_profile": "https://Stackoverflow.com/users/1796",
"pm_score": 0,
"selected": false,
"text": "<p>I knew that SharePoint Server used to keep the ASPX pages in the database and not on the file system. Details, however, I do not hold.</p>\n"
}
] |
2008/09/30
|
[
"https://Stackoverflow.com/questions/154117",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] |
Is there a way to execute a full ASPX source file where the page source is from a string/database/resource and not a file on the file system? It's straightfoward to render dynamic content/images/etc using HTTP Handlers and Modules and writing to the Response, but there doesn't seem to be a way to execute/compile ASPX source without a file on the file system. For example:
* HttpContext.Current.Server.Execute() overloads require a path to a file
* System.Web.Compilation.BuildManager can only create from a virtual path
The goal is to be able to execute a string source like the following from a Handler/Module/ViewEngine and not require a file on the file system (but get the source from another location):
```
<%@ Page language="C#" MasterPageFile="~/Shared/Site.Master" Inherits="System.Web.UI.Page" %>
<!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 id="Head1" runat="server">
<title>ListView Example</title>
</head>
<body>
<form id="form1" runat="server">
<h3>ListView Example</h3>
<asp:ListView ID="List" runat="server" DataSourceID="ProductDataSource">
<LayoutTemplate><ol><asp:PlaceHolder runat="server" ID="itemPlaceholder"></asp:PlaceHolder></ol></LayoutTemplate>
<ItemTemplate><li><%# Eval("ProductName") %></li></ItemTemplate>
</asp:ListView>
<asp:AccessDataSource ID="ProductDataSource" runat="server"DataFile="~/App_Data/Northwind.mdb"SelectCommand="SELECT [ProductName], [QuantityPerUnit], [UnitPrice], [CategoryName] FROM [Alphabetical List of Products]"></asp:AccessDataSource>
</form>
</body>
</html>
```
(NOTE: The sample above is just a simple example, but shows using server controls, data binding syntax, a master page and possible user control declarations in page directives, etc...)
I hope this makes sense!
|
Perhaps you need a [virtual path provider](http://msdn.microsoft.com/en-us/library/system.web.hosting.virtualpathprovider.aspx). It allows you to store the ASPX and codebehind in different media - RDBMS, xml file etc.
|
154,119 |
<p>This was an interview question. Given Visual Studio 2008 and an icon saved as a .PNG file, they required the image as an embedded resource and to be used as the icon within the title bar of a form.</p>
<p>I'm looking for what would have been the model answer to this question, Both (working!) code and any Visual Studio tricks. (Model answer is one that should get me the job if I meet it next time around.)</p>
<p>Specifically I don't know how to load the image once it is an embedded resource nor how to get it as the icon for the title bar.</p>
<p>As a part solution, ignoring the embedded bit, I copied the resource to the ouput directory and tried the following:-</p>
<pre><code>public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
this.Icon = new Icon("Resources\\IconImage.png");
}
}
</code></pre>
<p>This failed with the error "Argument 'picture' must be a picture that can be used as a Icon."</p>
<p>I presuming that the .PNG file actually needed to be a .ICO, but I couldn't see how to make the conversion. Is this presumption correct or is there a different issue?</p>
|
[
{
"answer_id": 154127,
"author": "Patrik Svensson",
"author_id": 936,
"author_profile": "https://Stackoverflow.com/users/936",
"pm_score": 1,
"selected": false,
"text": "<p>A good resource on the subject in <em><a href=\"http://social.msdn.microsoft.com/Forums/en-US/netfxbcl/thread/4a10d440-707f-48d7-865b-1d8804faf649/\" rel=\"nofollow noreferrer\">C# 2.0 Convert Bitmap to Icon</a></em>.</p>\n"
},
{
"answer_id": 156118,
"author": "Silver Dragon",
"author_id": 9440,
"author_profile": "https://Stackoverflow.com/users/9440",
"pm_score": 7,
"selected": true,
"text": "<p>Fire up VS, start new Windows Application. Open the properties sheet, add the .png file as a resource (in this example: glider.png ). From hereon, you can access the resource as a Bitmap file as WindowsFormsApplication10.Properties.Resources.glider</p>\n\n<p>Code for using it as an application icon:</p>\n\n<pre><code> public Form1()\n {\n InitializeComponent();\n Bitmap bmp = WindowsFormsApplication10.Properties.Resources.glider;\n this.Icon = Icon.FromHandle(bmp.GetHicon());\n }\n</code></pre>\n"
},
{
"answer_id": 157151,
"author": "Jonathan C Dickinson",
"author_id": 24064,
"author_profile": "https://Stackoverflow.com/users/24064",
"pm_score": 5,
"selected": false,
"text": "<p><code>Icon.FromHandle</code> will cause problems with a PNG, because PNGs have more than one bit of transparency. This type of issue can be solved with a library like <a href=\"http://www.codeproject.com/KB/cs/IconLib.aspx\" rel=\"nofollow noreferrer\" title=\"IconLib\">IconLib</a>.</p>\n<p>Chances are they didn't know how to do it and they were trying to squeeze the answer out of potential employees. Furthermore, setting the icon of the form from a PNG is an unnecessary performance hit, it should have been an ICO in the first place.</p>\n"
},
{
"answer_id": 2472571,
"author": "Kelly",
"author_id": 85802,
"author_profile": "https://Stackoverflow.com/users/85802",
"pm_score": 4,
"selected": false,
"text": "<p>Go here:</p>\n\n<p><a href=\"http://www.getpaint.net/\" rel=\"nofollow noreferrer\">http://www.getpaint.net/</a> (free)</p>\n\n<p>And here:</p>\n\n<p><a href=\"http://forums.getpaint.net/index.php?/topic/927-icon-cursor-and-animated-cursor-format-v37-may-2010/\" rel=\"nofollow noreferrer\">Paint.NET ico Plugin</a> (free)</p>\n\n<p>Install Paint.NET. Put the ico plugin (second link) into the Paint.NET\\FileTypes folder. Start up Paint.NET. Open your .png and save it as an .ico.</p>\n\n<p>Free and easy.</p>\n"
},
{
"answer_id": 22994531,
"author": "dizzy.stackoverflow",
"author_id": 2506209,
"author_profile": "https://Stackoverflow.com/users/2506209",
"pm_score": 1,
"selected": false,
"text": "<p>This worked for my purposes since all of my resources were PNG files:</p>\n\n<pre><code>[System.Runtime.InteropServices.DllImport(\"user32.dll\", CharSet = CharSet.Auto)]\nextern static bool DestroyIcon(IntPtr handle);\n\n// From http://msdn.microsoft.com/en-us/library/system.drawing.bitmap.gethicon.aspx\nprivate Icon bitmapToIcon(Bitmap myBitmap)\n{\n // Get an Hicon for myBitmap.\n IntPtr Hicon = myBitmap.GetHicon();\n\n // Create a new icon from the handle.\n Icon newIcon = Icon.FromHandle(Hicon);\n\n return newIcon;\n}\n</code></pre>\n"
}
] |
2008/09/30
|
[
"https://Stackoverflow.com/questions/154119",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/22284/"
] |
This was an interview question. Given Visual Studio 2008 and an icon saved as a .PNG file, they required the image as an embedded resource and to be used as the icon within the title bar of a form.
I'm looking for what would have been the model answer to this question, Both (working!) code and any Visual Studio tricks. (Model answer is one that should get me the job if I meet it next time around.)
Specifically I don't know how to load the image once it is an embedded resource nor how to get it as the icon for the title bar.
As a part solution, ignoring the embedded bit, I copied the resource to the ouput directory and tried the following:-
```
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
this.Icon = new Icon("Resources\\IconImage.png");
}
}
```
This failed with the error "Argument 'picture' must be a picture that can be used as a Icon."
I presuming that the .PNG file actually needed to be a .ICO, but I couldn't see how to make the conversion. Is this presumption correct or is there a different issue?
|
Fire up VS, start new Windows Application. Open the properties sheet, add the .png file as a resource (in this example: glider.png ). From hereon, you can access the resource as a Bitmap file as WindowsFormsApplication10.Properties.Resources.glider
Code for using it as an application icon:
```
public Form1()
{
InitializeComponent();
Bitmap bmp = WindowsFormsApplication10.Properties.Resources.glider;
this.Icon = Icon.FromHandle(bmp.GetHicon());
}
```
|
154,136 |
<p>In many C/C++ macros I'm seeing the code of the macro wrapped in what seems like a meaningless <code>do while</code> loop. Here are examples.</p>
<pre><code>#define FOO(X) do { f(X); g(X); } while (0)
#define FOO(X) if (1) { f(X); g(X); } else
</code></pre>
<p>I can't see what the <code>do while</code> is doing. Why not just write this without it?</p>
<pre><code>#define FOO(X) f(X); g(X)
</code></pre>
|
[
{
"answer_id": 154138,
"author": "jfm3",
"author_id": 11138,
"author_profile": "https://Stackoverflow.com/users/11138",
"pm_score": 11,
"selected": true,
"text": "<p>The <code>do ... while</code> and <code>if ... else</code> are there to make it so that a\nsemicolon after your macro always means the same thing. Let's say you\nhad something like your second macro.</p>\n\n<pre><code>#define BAR(X) f(x); g(x)\n</code></pre>\n\n<p>Now if you were to use <code>BAR(X);</code> in an <code>if ... else</code> statement, where the bodies of the if statement were not wrapped in curly brackets, you'd get a bad surprise.</p>\n\n<pre><code>if (corge)\n BAR(corge);\nelse\n gralt();\n</code></pre>\n\n<p>The above code would expand into</p>\n\n<pre><code>if (corge)\n f(corge); g(corge);\nelse\n gralt();\n</code></pre>\n\n<p>which is syntactically incorrect, as the else is no longer associated with the if. It doesn't help to wrap things in curly braces within the macro, because a semicolon after the braces is syntactically incorrect.</p>\n\n<pre><code>if (corge)\n {f(corge); g(corge);};\nelse\n gralt();\n</code></pre>\n\n<p>There are two ways of fixing the problem. The first is to use a comma to sequence statements within the macro without robbing it of its ability to act like an expression.</p>\n\n<pre><code>#define BAR(X) f(X), g(X)\n</code></pre>\n\n<p>The above version of bar <code>BAR</code> expands the above code into what follows, which is syntactically correct.</p>\n\n<pre><code>if (corge)\n f(corge), g(corge);\nelse\n gralt();\n</code></pre>\n\n<p>This doesn't work if instead of <code>f(X)</code> you have a more complicated body of code that needs to go in its own block, say for example to declare local variables. In the most general case the solution is to use something like <code>do ... while</code> to cause the macro to be a single statement that takes a semicolon without confusion.</p>\n\n<pre><code>#define BAR(X) do { \\\n int i = f(X); \\\n if (i > 4) g(i); \\\n} while (0)\n</code></pre>\n\n<p>You don't have to use <code>do ... while</code>, you could cook up something with <code>if ... else</code> as well, although when <code>if ... else</code> expands inside of an <code>if ... else</code> it leads to a \"<a href=\"http://en.wikipedia.org/wiki/Dangling_else\" rel=\"noreferrer\">dangling else</a>\", which could make an existing dangling else problem even harder to find, as in the following code.</p>\n\n<pre><code>if (corge)\n if (1) { f(corge); g(corge); } else;\nelse\n gralt();\n</code></pre>\n\n<p>The point is to use up the semicolon in contexts where a dangling semicolon is erroneous. Of course, it could (and probably should) be argued at this point that it would be better to declare <code>BAR</code> as an actual function, not a macro.</p>\n\n<p>In summary, the <code>do ... while</code> is there to work around the shortcomings of the C preprocessor. When those C style guides tell you to lay off the C preprocessor, this is the kind of thing they're worried about.</p>\n"
},
{
"answer_id": 154239,
"author": "Michael Burr",
"author_id": 12711,
"author_profile": "https://Stackoverflow.com/users/12711",
"pm_score": 6,
"selected": false,
"text": "<p>@jfm3 - You have a nice answer to the question. You might also want to add that the macro idiom also prevents the possibly more dangerous (because there's no error) unintended behavior with simple 'if' statements:</p>\n\n<pre><code>#define FOO(x) f(x); g(x)\n\nif (test) FOO( baz);\n</code></pre>\n\n<p>expands to:</p>\n\n<pre><code>if (test) f(baz); g(baz);\n</code></pre>\n\n<p>which is syntactically correct so there's no compiler error, but has the probably unintended consequence that g() will always be called.</p>\n"
},
{
"answer_id": 154264,
"author": "paercebal",
"author_id": 14089,
"author_profile": "https://Stackoverflow.com/users/14089",
"pm_score": 7,
"selected": false,
"text": "<p>Macros are copy/pasted pieces of text the pre-processor will put in the genuine code; the macro's author hopes the replacement will produce valid code.</p>\n\n<p>There are three good \"tips\" to succeed in that:</p>\n\n<h2>Help the macro behave like genuine code</h2>\n\n<p>Normal code is usually ended by a semi-colon. Should the user view code not needing one...</p>\n\n<pre><code>doSomething(1) ;\nDO_SOMETHING_ELSE(2) // <== Hey? What's this?\ndoSomethingElseAgain(3) ;\n</code></pre>\n\n<p>This means the user expects the compiler to produce an error if the semi-colon is absent.</p>\n\n<p>But the real real good reason is that at some time, the macro's author will perhaps need to replace the macro with a genuine function (perhaps inlined). So the macro should <strong>really</strong> behave like one.</p>\n\n<p>So we should have a macro needing semi-colon.</p>\n\n<h2>Produce a valid code</h2>\n\n<p>As shown in jfm3's answer, sometimes the macro contains more than one instruction. And if the macro is used inside a if statement, this will be problematic:</p>\n\n<pre><code>if(bIsOk)\n MY_MACRO(42) ;\n</code></pre>\n\n<p>This macro could be expanded as:</p>\n\n<pre><code>#define MY_MACRO(x) f(x) ; g(x)\n\nif(bIsOk)\n f(42) ; g(42) ; // was MY_MACRO(42) ;\n</code></pre>\n\n<p>The <code>g</code> function will be executed regardless of the value of <code>bIsOk</code>.</p>\n\n<p>This means that we must have to add a scope to the macro:</p>\n\n<pre><code>#define MY_MACRO(x) { f(x) ; g(x) ; }\n\nif(bIsOk)\n { f(42) ; g(42) ; } ; // was MY_MACRO(42) ;\n</code></pre>\n\n<h2>Produce a valid code 2</h2>\n\n<p>If the macro is something like:</p>\n\n<pre><code>#define MY_MACRO(x) int i = x + 1 ; f(i) ;\n</code></pre>\n\n<p>We could have another problem in the following code:</p>\n\n<pre><code>void doSomething()\n{\n int i = 25 ;\n MY_MACRO(32) ;\n}\n</code></pre>\n\n<p>Because it would expand as:</p>\n\n<pre><code>void doSomething()\n{\n int i = 25 ;\n int i = 32 + 1 ; f(i) ; ; // was MY_MACRO(32) ;\n}\n</code></pre>\n\n<p>This code won't compile, of course. So, again, the solution is using a scope:</p>\n\n<pre><code>#define MY_MACRO(x) { int i = x + 1 ; f(i) ; }\n\nvoid doSomething()\n{\n int i = 25 ;\n { int i = 32 + 1 ; f(i) ; } ; // was MY_MACRO(32) ;\n}\n</code></pre>\n\n<p>The code behaves correctly again.</p>\n\n<h2>Combining semi-colon + scope effects?</h2>\n\n<p>There is one C/C++ idiom that produces this effect: The do/while loop:</p>\n\n<pre><code>do\n{\n // code\n}\nwhile(false) ;\n</code></pre>\n\n<p>The do/while can create a scope, thus encapsulating the macro's code, and needs a semi-colon in the end, thus expanding into code needing one.</p>\n\n<p>The bonus?</p>\n\n<p>The C++ compiler will optimize away the do/while loop, as the fact its post-condition is false is known at compile time. This means that a macro like:</p>\n\n<pre><code>#define MY_MACRO(x) \\\ndo \\\n{ \\\n const int i = x + 1 ; \\\n f(i) ; g(i) ; \\\n} \\\nwhile(false)\n\nvoid doSomething(bool bIsOk)\n{\n int i = 25 ;\n\n if(bIsOk)\n MY_MACRO(42) ;\n\n // Etc.\n}\n</code></pre>\n\n<p>will expand correctly as</p>\n\n<pre><code>void doSomething(bool bIsOk)\n{\n int i = 25 ;\n\n if(bIsOk)\n do\n {\n const int i = 42 + 1 ; // was MY_MACRO(42) ;\n f(i) ; g(i) ;\n }\n while(false) ;\n\n // Etc.\n}\n</code></pre>\n\n<p>and is then compiled and optimized away as</p>\n\n<pre><code>void doSomething(bool bIsOk)\n{\n int i = 25 ;\n\n if(bIsOk)\n {\n f(43) ; g(43) ;\n }\n\n // Etc.\n}\n</code></pre>\n"
},
{
"answer_id": 215633,
"author": "John Nilsson",
"author_id": 24243,
"author_profile": "https://Stackoverflow.com/users/24243",
"pm_score": 2,
"selected": false,
"text": "<p>I don't think it was mentioned so consider this</p>\n\n<pre><code>while(i<100)\n FOO(i++);\n</code></pre>\n\n<p>would be translated into</p>\n\n<pre><code>while(i<100)\n do { f(i++); g(i++); } while (0)\n</code></pre>\n\n<p>notice how <code>i++</code> is evaluated twice by the macro. This can lead to some interesting errors.</p>\n"
},
{
"answer_id": 1547389,
"author": "Marius",
"author_id": 174650,
"author_profile": "https://Stackoverflow.com/users/174650",
"pm_score": 4,
"selected": false,
"text": "<p>While it is expected that compilers optimize away the <code>do { ... } while(false);</code> loops, there is another solution which would not require that construct. The solution is to use the comma operator:</p>\n\n<pre><code>#define FOO(X) (f(X),g(X))\n</code></pre>\n\n<p>or even more exotically:</p>\n\n<pre><code>#define FOO(X) g((f(X),(X)))\n</code></pre>\n\n<p>While this will work well with separate instructions, it will not work with cases where variables are constructed and used as part of the <code>#define</code> :</p>\n\n<pre><code>#define FOO(X) (int s=5,f((X)+s),g((X)+s))\n</code></pre>\n\n<p>With this one would be forced to use the do/while construct.</p>\n"
},
{
"answer_id": 8594736,
"author": "Mike Meyer",
"author_id": 1003027,
"author_profile": "https://Stackoverflow.com/users/1003027",
"pm_score": 3,
"selected": false,
"text": "<p>For some reasons I can't comment on the first answer...</p>\n\n<p>Some of you showed macros with local variables, but nobody mentioned that you can't just use any name in a macro! It will bite the user some day! Why? Because the input arguments are substituted into your macro template. And in your macro examples you've use the probably most commonly used variabled name <strong>i</strong>.</p>\n\n<p>For example when the following macro</p>\n\n<pre><code>#define FOO(X) do { int i; for (i = 0; i < (X); ++i) do_something(i); } while (0)\n</code></pre>\n\n<p>is used in the following function</p>\n\n<pre><code>void some_func(void) {\n int i;\n for (i = 0; i < 10; ++i)\n FOO(i);\n}\n</code></pre>\n\n<p>the macro will not use the intended variable i, that is declared at the beginning of some_func, but the local variable, that is declared in the do ... while loop of the macro.</p>\n\n<p>Thus, never use common variable names in a macro!</p>\n"
},
{
"answer_id": 11798599,
"author": "Yakov Galka",
"author_id": 277176,
"author_profile": "https://Stackoverflow.com/users/277176",
"pm_score": 5,
"selected": false,
"text": "<p>The above answers explain the meaning of these constructs, but there is a significant difference between the two that was not mentioned. In fact, there is a reason to prefer the <code>do ... while</code> to the <code>if ... else</code> construct.</p>\n\n<p>The problem of the <code>if ... else</code> construct is that it does not <em>force</em> you to put the semicolon. Like in this code:</p>\n\n<pre><code>FOO(1)\nprintf(\"abc\");\n</code></pre>\n\n<p>Although we left out the semicolon (by mistake), the code will expand to</p>\n\n<pre><code>if (1) { f(X); g(X); } else\nprintf(\"abc\");\n</code></pre>\n\n<p>and will silently compile (although some compilers may issue a warning for unreachable code). But the <code>printf</code> statement will never be executed.</p>\n\n<p><code>do ... while</code> construct does not have such problem, since the only valid token after the <code>while(0)</code> is a semicolon.</p>\n"
},
{
"answer_id": 22590644,
"author": "Cœur",
"author_id": 1033581,
"author_profile": "https://Stackoverflow.com/users/1033581",
"pm_score": 4,
"selected": false,
"text": "<h3>Explanation</h3>\n<p><code>do {} while (0)</code> and <code>if (1) {} else</code> are to make sure that the macro is expanded to only 1 instruction. Otherwise:</p>\n<pre><code>if (something)\n FOO(X); \n</code></pre>\n<p>would expand to:</p>\n<pre><code>if (something)\n f(X); g(X); \n</code></pre>\n<p>And <code>g(X)</code> would be executed outside the <code>if</code> control statement. This is avoided when using <code>do {} while (0)</code> and <code>if (1) {} else</code>.</p>\n<hr />\n<h3>Better alternative</h3>\n<p>With a GNU <a href=\"https://gcc.gnu.org/onlinedocs/gcc-6.2.0/gcc/Statement-Exprs.html#Statement-Exprs\" rel=\"noreferrer\">statement expression</a> (not a part of standard C), you have a better way than <code>do {} while (0)</code> and <code>if (1) {} else</code> to solve this, by simply using <code>({})</code>:</p>\n<pre><code>#define FOO(X) ({f(X); g(X);})\n</code></pre>\n<p>And this syntax is compatible with return values (note that <code>do {} while (0)</code> isn't), as in:</p>\n<pre><code>return FOO("X");\n</code></pre>\n"
},
{
"answer_id": 27021741,
"author": "Isaac Schwabacher",
"author_id": 4270855,
"author_profile": "https://Stackoverflow.com/users/4270855",
"pm_score": 4,
"selected": false,
"text": "<p>Jens Gustedt's <a href=\"http://p99.gforge.inria.fr/p99-html/index.html\">P99 preprocessor library</a> (yes, the fact that such a thing exists blew my mind too!) improves on the <code>if(1) { ... } else</code> construct in a small but significant way by defining the following:</p>\n\n<pre class=\"lang-c prettyprint-override\"><code>#define P99_NOP ((void)0)\n#define P99_PREFER(...) if (1) { __VA_ARGS__ } else\n#define P99_BLOCK(...) P99_PREFER(__VA_ARGS__) P99_NOP\n</code></pre>\n\n<p>The rationale for this is that, unlike the <code>do { ... } while(0)</code> construct, <code>break</code> and <code>continue</code> still work inside the given block, but the <code>((void)0)</code> creates a syntax error if the semicolon is omitted after the macro call, which would otherwise skip the next block. (There isn't actually a \"dangling else\" problem here, since the <code>else</code> binds to the nearest <code>if</code>, which is the one in the macro.) </p>\n\n<p>If you are interested in the sorts of things that can be done more-or-less safely with the C preprocessor, check out that library.</p>\n"
}
] |
2008/09/30
|
[
"https://Stackoverflow.com/questions/154136",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11138/"
] |
In many C/C++ macros I'm seeing the code of the macro wrapped in what seems like a meaningless `do while` loop. Here are examples.
```
#define FOO(X) do { f(X); g(X); } while (0)
#define FOO(X) if (1) { f(X); g(X); } else
```
I can't see what the `do while` is doing. Why not just write this without it?
```
#define FOO(X) f(X); g(X)
```
|
The `do ... while` and `if ... else` are there to make it so that a
semicolon after your macro always means the same thing. Let's say you
had something like your second macro.
```
#define BAR(X) f(x); g(x)
```
Now if you were to use `BAR(X);` in an `if ... else` statement, where the bodies of the if statement were not wrapped in curly brackets, you'd get a bad surprise.
```
if (corge)
BAR(corge);
else
gralt();
```
The above code would expand into
```
if (corge)
f(corge); g(corge);
else
gralt();
```
which is syntactically incorrect, as the else is no longer associated with the if. It doesn't help to wrap things in curly braces within the macro, because a semicolon after the braces is syntactically incorrect.
```
if (corge)
{f(corge); g(corge);};
else
gralt();
```
There are two ways of fixing the problem. The first is to use a comma to sequence statements within the macro without robbing it of its ability to act like an expression.
```
#define BAR(X) f(X), g(X)
```
The above version of bar `BAR` expands the above code into what follows, which is syntactically correct.
```
if (corge)
f(corge), g(corge);
else
gralt();
```
This doesn't work if instead of `f(X)` you have a more complicated body of code that needs to go in its own block, say for example to declare local variables. In the most general case the solution is to use something like `do ... while` to cause the macro to be a single statement that takes a semicolon without confusion.
```
#define BAR(X) do { \
int i = f(X); \
if (i > 4) g(i); \
} while (0)
```
You don't have to use `do ... while`, you could cook up something with `if ... else` as well, although when `if ... else` expands inside of an `if ... else` it leads to a "[dangling else](http://en.wikipedia.org/wiki/Dangling_else)", which could make an existing dangling else problem even harder to find, as in the following code.
```
if (corge)
if (1) { f(corge); g(corge); } else;
else
gralt();
```
The point is to use up the semicolon in contexts where a dangling semicolon is erroneous. Of course, it could (and probably should) be argued at this point that it would be better to declare `BAR` as an actual function, not a macro.
In summary, the `do ... while` is there to work around the shortcomings of the C preprocessor. When those C style guides tell you to lay off the C preprocessor, this is the kind of thing they're worried about.
|
154,163 |
<p>I need to detect whether my application is running within a virtualized OS instance or not.</p>
<p>I've found <A HREF="http://www.codeproject.com/KB/system/VmDetect.aspx" rel="noreferrer">an article</A> with some useful information on the topic. The same article appears in multiple places, I'm unsure of the original source. <A HREF="http://www.vmware.com/" rel="noreferrer">VMware</A> implements a particular invalid x86 instruction to return information about itself, while <A HREF="http://www.microsoft.com/windows/products/winfamily/virtualpc/default.mspx" rel="noreferrer">VirtualPC</A> uses a magic number and I/O port with an IN instruction.</p>
<p>This is workable, but appears to be undocumented behavior in both cases. I suppose a future release of VMWare or VirtualPC might change the mechanism. Is there a better way? Is there a supported mechanism for either product?</p>
<p>Similarly, is there a way to detect <A HREF="http://www.xen.org/" rel="noreferrer">Xen</A> or <A HREF="http://www.virtualbox.org/" rel="noreferrer">VirtualBox</A>?</p>
<p>I'm not concerned about cases where the platform is deliberately trying to hide itself. For example, honeypots use virtualization but sometimes obscure the mechanisms that malware would use to detect it. I don't care that my app would think it is not virtualized in these honeypots, I'm just looking for a "best effort" solution.</p>
<p>The application is mostly Java, though I'm expecting to use native code plus JNI for this particular function. Windows XP/Vista support is most important, though the mechanisms described in the referenced article are generic features of x86 and don't rely on any particular OS facility.</p>
|
[
{
"answer_id": 154168,
"author": "warren",
"author_id": 4418,
"author_profile": "https://Stackoverflow.com/users/4418",
"pm_score": 3,
"selected": false,
"text": "<p>Under Linux, you can report on /proc/cpuinfo. If it's in VMware, it usually comes-up differently than if it is on bare metal, but not always. Virtuozzo shows a pass-through to the underlying hardware.</p>\n"
},
{
"answer_id": 154183,
"author": "Jonas Engström",
"author_id": 7634,
"author_profile": "https://Stackoverflow.com/users/7634",
"pm_score": 3,
"selected": false,
"text": "<p>Try by reading the <a href=\"http://www.dmtf.org/standards/smbios/\" rel=\"noreferrer\">SMBIOS</a> structures, especially the structs with the <a href=\"http://www.dmtf.org/standards/published_documents/DSP0134_2.6.0.pdf\" rel=\"noreferrer\">BIOS</a> information.</p>\n\n<p>In Linux you can use the <a href=\"http://www.nongnu.org/dmidecode/\" rel=\"noreferrer\">dmidecode</a> utility to browse the information.</p>\n"
},
{
"answer_id": 154202,
"author": "Kirk Strauser",
"author_id": 32538,
"author_profile": "https://Stackoverflow.com/users/32538",
"pm_score": 4,
"selected": false,
"text": "<p>No. This is impossible to detect with complete accuracy. Some virtualization systems, like <a href=\"http://www.qemu.org/\" rel=\"noreferrer\">QEMU</a>, emulate an entire machine down to the hardware registers. Let's turn this around: what is it you're trying to do? Maybe we can help with that.</p>\n"
},
{
"answer_id": 154222,
"author": "sven",
"author_id": 46,
"author_profile": "https://Stackoverflow.com/users/46",
"pm_score": 7,
"selected": true,
"text": "<p>Have you heard about <a href=\"http://web.archive.org/web/20100725003848/http://www.redlightsecurity.com/2008/04/virtualization-red-pill-or-blue.html\" rel=\"nofollow noreferrer\">blue pill, red pill?</a>. It's a technique used to see if you are running inside a virtual machine or not. The origin of the term stems from <a href=\"http://www.imdb.com/title/tt0133093/\" rel=\"nofollow noreferrer\">the matrix movie</a> where Neo is offered a blue or a red pill (to stay inside the matrix = blue, or to enter the 'real' world = red).</p>\n<p>The following is some code that will detect whether you are running inside 'the matrix' or not:<br />\n(code borrowed from <a href=\"http://web.archive.org/web/20110929075510/http://invisiblethings.org/papers/redpill.html\" rel=\"nofollow noreferrer\">this site</a> which also contains some nice information about the topic at hand):</p>\n<pre><code> int swallow_redpill () {\n unsigned char m[2+4], rpill[] = "\\x0f\\x01\\x0d\\x00\\x00\\x00\\x00\\xc3";\n *((unsigned*)&rpill[3]) = (unsigned)m;\n ((void(*)())&rpill)();\n return (m[5]>0xd0) ? 1 : 0;\n } \n</code></pre>\n<p>The function will return 1 when you are running inside a virutal machine, and 0 otherwise.</p>\n"
},
{
"answer_id": 161157,
"author": "jakobengblom2",
"author_id": 23054,
"author_profile": "https://Stackoverflow.com/users/23054",
"pm_score": 4,
"selected": false,
"text": "<p>I think that going forward, relying on tricks like the broken SIDT virtualization is not really going to help as the hardware plugs all the holes that the weird and messy x86 architecture have left. The best would be to lobby the Vm providers for a standard way to tell that you are on a VM -- at least for the case when the user has explicitly allowed that. But if we assume that we are explicitly allowing the VM to be detected, we can just as well place visible markers in there, right? I would suggest just updating the disk on your VMs with a file telling you that you are on a VM -- a small text file in the root of the file system, for example. Or inspect the MAC of ETH0, and set that to a given known string. </p>\n"
},
{
"answer_id": 920813,
"author": "ZelluX",
"author_id": 111896,
"author_profile": "https://Stackoverflow.com/users/111896",
"pm_score": 3,
"selected": false,
"text": "<p>I'd like to recommend a paper posted on Usenix HotOS '07, <em>Comptibility is Not Transparency: VMM Detection Myths and Realities</em>, which concludes several techniques to tell whether the application is running in a virtualized environment. </p>\n\n<p>For example, use sidt instruction as redpill does(but this instruction can also be made transparent by dynamic translation), or compare the runtime of cpuid against other non-virtualized instructions.</p>\n"
},
{
"answer_id": 2068342,
"author": "Pavlo Svirin",
"author_id": 169622,
"author_profile": "https://Stackoverflow.com/users/169622",
"pm_score": 3,
"selected": false,
"text": "<p>While installing the newes Ubuntu I discovered the package called imvirt. Have a look at it at <a href=\"http://micky.ibh.net/~liske/imvirt.html\" rel=\"noreferrer\">http://micky.ibh.net/~liske/imvirt.html</a></p>\n"
},
{
"answer_id": 3496130,
"author": "David",
"author_id": 373852,
"author_profile": "https://Stackoverflow.com/users/373852",
"pm_score": 4,
"selected": false,
"text": "<p>VMware has a <a href=\"http://kb.vmware.com/kb/1009458\" rel=\"noreferrer\">Mechanisms to determine if software is running in a VMware virtual machine</a> Knowledge base article which has some source code.</p>\n\n<p>Microsoft also has a page on <a href=\"http://msdn.microsoft.com/en-us/library/ff538624%28VS.85%29.aspx\" rel=\"noreferrer\">\"Determining If Hypervisor Is Installed\"</a>. MS spells out this requirement of a hypervisor in the IsVM TEST\" section of their <a href=\"http://msdn.microsoft.com/en-us/library/dd871279%28v=MSDN.10%29.aspx\" rel=\"noreferrer\">\"Server Virtualization Validation Test\"</a> document</p>\n\n<p>The VMware and MS docs both mention using the CPUID instruction to check the hypervisor-present bit (bit 31 of register ECX)</p>\n\n<p>The RHEL bugtracker has one for <a href=\"https://bugzilla.redhat.com/show_bug.cgi?id=573771\" rel=\"noreferrer\">\"should set ISVM bit (ECX:31) for CPUID leaf 0x00000001\"</a> to set bit 31 of register ECX under the Xen kernel.</p>\n\n<p>So without getting into vendor specifics it looks like you could use the CPUID check to know if you're running virtually or not.</p>\n"
},
{
"answer_id": 4299531,
"author": "michaelbn",
"author_id": 434792,
"author_profile": "https://Stackoverflow.com/users/434792",
"pm_score": 5,
"selected": false,
"text": "<p>Under Linux I used the command: <strong>dmidecode</strong> ( I have it both on CentOS and Ubuntu )</p>\n\n<p>from the man:</p>\n\n<blockquote>\n <p>dmidecode is a tool for dumping a\n computer's DMI (some say SMBIOS) table\n contents in a human-readable format.</p>\n</blockquote>\n\n<p>So I searched the output and found out its probably Microsoft Hyper-V</p>\n\n<pre><code>Handle 0x0001, DMI type 1, 25 bytes\nSystem Information\n Manufacturer: Microsoft Corporation\n Product Name: Virtual Machine\n Version: 5.0\n Serial Number: some-strings\n UUID: some-strings\n Wake-up Type: Power Switch\n\n\nHandle 0x0002, DMI type 2, 8 bytes\nBase Board Information\n Manufacturer: Microsoft Corporation\n Product Name: Virtual Machine\n Version: 5.0\n Serial Number: some-strings\n</code></pre>\n\n<p>Another way is to search to which manufacturer the MAC address of eth0 is related to: <a href=\"http://www.coffer.com/mac_find/\">http://www.coffer.com/mac_find/</a></p>\n\n<p>If it return Microsoft, vmware & etc.. then its probably a virtual server.</p>\n"
},
{
"answer_id": 11879704,
"author": "Rickard von Essen",
"author_id": 226174,
"author_profile": "https://Stackoverflow.com/users/226174",
"pm_score": 2,
"selected": false,
"text": "<p>Check the tool <a href=\"http://linux.die.net/man/1/virt-what\" rel=\"nofollow\">virt-what</a>. It uses previously mentioned dmidecode to determine if you are on a virtualized host and the type. </p>\n"
},
{
"answer_id": 23392455,
"author": "icasimpan",
"author_id": 579516,
"author_profile": "https://Stackoverflow.com/users/579516",
"pm_score": 3,
"selected": false,
"text": "<p>On virtualbox, assuming you have control over the VM guest and you have dmidecode, you can use this command:</p>\n\n<pre><code>dmidecode -s bios-version\n</code></pre>\n\n<p>and it will return</p>\n\n<pre><code>VirtualBox\n</code></pre>\n"
},
{
"answer_id": 32012696,
"author": "user2242746",
"author_id": 2242746,
"author_profile": "https://Stackoverflow.com/users/2242746",
"pm_score": 3,
"selected": false,
"text": "<p>This C function will detect VM Guest OS:</p>\n\n<p>(Tested on Windows, compiled with Visual Studio)</p>\n\n<pre><code>#include <intrin.h>\n\n bool isGuestOSVM()\n {\n unsigned int cpuInfo[4];\n __cpuid((int*)cpuInfo,1);\n return ((cpuInfo[2] >> 31) & 1) == 1;\n }\n</code></pre>\n"
},
{
"answer_id": 32430301,
"author": "Pedro Lobito",
"author_id": 797495,
"author_profile": "https://Stackoverflow.com/users/797495",
"pm_score": 2,
"selected": false,
"text": "<p>I use this <code>C#</code> class to detect if the Guest OS is running inside a virtual environment (<strong>windows only</strong>):</p>\n\n<p><strong>sysInfo.cs</strong></p>\n\n<pre><code>using System;\nusing System.Management;\nusing System.Text.RegularExpressions;\n\nnamespace ConsoleApplication1\n{\n public class sysInfo\n {\n public static Boolean isVM()\n {\n bool foundMatch = false;\n ManagementObjectSearcher search1 = new ManagementObjectSearcher(\"select * from Win32_BIOS\");\n var enu = search1.Get().GetEnumerator();\n if (!enu.MoveNext()) throw new Exception(\"Unexpected WMI query failure\");\n string biosVersion = enu.Current[\"version\"].ToString();\n string biosSerialNumber = enu.Current[\"SerialNumber\"].ToString();\n\n try\n {\n foundMatch = Regex.IsMatch(biosVersion + \" \" + biosSerialNumber, \"VMware|VIRTUAL|A M I|Xen\", RegexOptions.IgnoreCase);\n }\n catch (ArgumentException ex)\n {\n // Syntax error in the regular expression\n }\n\n ManagementObjectSearcher search2 = new ManagementObjectSearcher(\"select * from Win32_ComputerSystem\");\n var enu2 = search2.Get().GetEnumerator();\n if (!enu2.MoveNext()) throw new Exception(\"Unexpected WMI query failure\");\n string manufacturer = enu2.Current[\"manufacturer\"].ToString();\n string model = enu2.Current[\"model\"].ToString();\n\n try\n {\n foundMatch = Regex.IsMatch(manufacturer + \" \" + model, \"Microsoft|VMWare|Virtual\", RegexOptions.IgnoreCase);\n }\n catch (ArgumentException ex)\n {\n // Syntax error in the regular expression\n }\n\n return foundMatch;\n }\n }\n\n}\n</code></pre>\n\n<hr>\n\n<p><strong>Usage:</strong></p>\n\n<pre><code> if (sysInfo.isVM()) { \n Console.WriteLine(\"VM FOUND\");\n }\n</code></pre>\n"
},
{
"answer_id": 39994934,
"author": "Mohit Dabas",
"author_id": 1485906,
"author_profile": "https://Stackoverflow.com/users/1485906",
"pm_score": 2,
"selected": false,
"text": "<p>I Tried A Different approach suggested by my friend.Virtual Machines run on VMWARE doesnt have CPU TEMPERATURE property. i.e They Dont Show The Temperature of the CPU. I am using CPU Thermometer Application For Checking The CPU Temperature.</p>\n\n<p><strong>(Windows Running In VMWARE)</strong>\n<a href=\"https://i.stack.imgur.com/YILzM.jpg\" rel=\"nofollow\"><img src=\"https://i.stack.imgur.com/YILzM.jpg\" alt=\"enter image description here\"></a></p>\n\n<p><strong>(Windows Running On A Real CPU)</strong>\n<a href=\"https://i.stack.imgur.com/XpKhV.png\" rel=\"nofollow\"><img src=\"https://i.stack.imgur.com/XpKhV.png\" alt=\"enter image description here\"></a></p>\n\n<p>So I Code a Small C Programme to detect the temperature Senser</p>\n\n<pre><code>#include \"stdafx.h\"\n\n#define _WIN32_DCOM\n#include <iostream>\nusing namespace std;\n#include <comdef.h>\n#include <Wbemidl.h>\n\n#pragma comment(lib, \"wbemuuid.lib\")\n\nint main(int argc, char **argv)\n{\n HRESULT hres;\n\n // Step 1: --------------------------------------------------\n // Initialize COM. ------------------------------------------\n\n hres = CoInitializeEx(0, COINIT_MULTITHREADED);\n if (FAILED(hres))\n {\n cout << \"Failed to initialize COM library. Error code = 0x\"\n << hex << hres << endl;\n return 1; // Program has failed.\n }\n\n // Step 2: --------------------------------------------------\n // Set general COM security levels --------------------------\n\n hres = CoInitializeSecurity(\n NULL,\n -1, // COM authentication\n NULL, // Authentication services\n NULL, // Reserved\n RPC_C_AUTHN_LEVEL_DEFAULT, // Default authentication \n RPC_C_IMP_LEVEL_IMPERSONATE, // Default Impersonation \n NULL, // Authentication info\n EOAC_NONE, // Additional capabilities \n NULL // Reserved\n );\n\n\n if (FAILED(hres))\n {\n cout << \"Failed to initialize security. Error code = 0x\"\n << hex << hres << endl;\n CoUninitialize();\n return 1; // Program has failed.\n }\n\n // Step 3: ---------------------------------------------------\n // Obtain the initial locator to WMI -------------------------\n\n IWbemLocator *pLoc = NULL;\n\n hres = CoCreateInstance(\n CLSID_WbemLocator,\n 0,\n CLSCTX_INPROC_SERVER,\n IID_IWbemLocator, (LPVOID *)&pLoc);\n\n if (FAILED(hres))\n {\n cout << \"Failed to create IWbemLocator object.\"\n << \" Err code = 0x\"\n << hex << hres << endl;\n CoUninitialize();\n return 1; // Program has failed.\n }\n\n // Step 4: -----------------------------------------------------\n // Connect to WMI through the IWbemLocator::ConnectServer method\n\n IWbemServices *pSvc = NULL;\n\n // Connect to the root\\cimv2 namespace with\n // the current user and obtain pointer pSvc\n // to make IWbemServices calls.\n hres = pLoc->ConnectServer(\n _bstr_t(L\"ROOT\\\\CIMV2\"), // Object path of WMI namespace\n NULL, // User name. NULL = current user\n NULL, // User password. NULL = current\n 0, // Locale. NULL indicates current\n NULL, // Security flags.\n 0, // Authority (for example, Kerberos)\n 0, // Context object \n &pSvc // pointer to IWbemServices proxy\n );\n\n if (FAILED(hres))\n {\n cout << \"Could not connect. Error code = 0x\"\n << hex << hres << endl;\n pLoc->Release();\n CoUninitialize();\n return 1; // Program has failed.\n }\n\n cout << \"Connected to ROOT\\\\CIMV2 WMI namespace\" << endl;\n\n\n // Step 5: --------------------------------------------------\n // Set security levels on the proxy -------------------------\n\n hres = CoSetProxyBlanket(\n pSvc, // Indicates the proxy to set\n RPC_C_AUTHN_WINNT, // RPC_C_AUTHN_xxx\n RPC_C_AUTHZ_NONE, // RPC_C_AUTHZ_xxx\n NULL, // Server principal name \n RPC_C_AUTHN_LEVEL_CALL, // RPC_C_AUTHN_LEVEL_xxx \n RPC_C_IMP_LEVEL_IMPERSONATE, // RPC_C_IMP_LEVEL_xxx\n NULL, // client identity\n EOAC_NONE // proxy capabilities \n );\n\n if (FAILED(hres))\n {\n cout << \"Could not set proxy blanket. Error code = 0x\"\n << hex << hres << endl;\n pSvc->Release();\n pLoc->Release();\n CoUninitialize();\n return 1; // Program has failed.\n }\n\n // Step 6: --------------------------------------------------\n // Use the IWbemServices pointer to make requests of WMI ----\n\n // For example, get the name of the operating system\n IEnumWbemClassObject* pEnumerator = NULL;\n hres = pSvc->ExecQuery(\n bstr_t(\"WQL\"),\n bstr_t(L\"SELECT * FROM Win32_TemperatureProbe\"),\n WBEM_FLAG_FORWARD_ONLY | WBEM_FLAG_RETURN_IMMEDIATELY,\n NULL,\n &pEnumerator);\n\n if (FAILED(hres))\n {\n cout << \"Query for operating system name failed.\"\n << \" Error code = 0x\"\n << hex << hres << endl;\n pSvc->Release();\n pLoc->Release();\n CoUninitialize();\n return 1; // Program has failed.\n }\n\n // Step 7: -------------------------------------------------\n // Get the data from the query in step 6 -------------------\n\n IWbemClassObject *pclsObj = NULL;\n ULONG uReturn = 0;\n\n while (pEnumerator)\n {\n HRESULT hr = pEnumerator->Next(WBEM_INFINITE, 1,\n &pclsObj, &uReturn);\n\n if (0 == uReturn)\n {\n break;\n }\n\n VARIANT vtProp;\n\n // Get the value of the Name property\n hr = pclsObj->Get(L\"SystemName\", 0, &vtProp, 0, 0);\n wcout << \" OS Name : \" << vtProp.bstrVal << endl;\n VariantClear(&vtProp);\n VARIANT vtProp1;\n VariantInit(&vtProp1);\n pclsObj->Get(L\"Caption\", 0, &vtProp1, 0, 0);\n wcout << \"Caption: \" << vtProp1.bstrVal << endl;\n VariantClear(&vtProp1);\n\n pclsObj->Release();\n }\n\n // Cleanup\n // ========\n\n pSvc->Release();\n pLoc->Release();\n pEnumerator->Release();\n CoUninitialize();\n\n return 0; // Program successfully completed.\n\n}\n</code></pre>\n\n<p><strong>Output On a Vmware Machine</strong>\n<a href=\"https://i.stack.imgur.com/JXhOK.jpg\" rel=\"nofollow\"><img src=\"https://i.stack.imgur.com/JXhOK.jpg\" alt=\"enter image description here\"></a></p>\n\n<p><strong>Output On A Real Cpu</strong>\n<a href=\"https://i.stack.imgur.com/5SNFn.png\" rel=\"nofollow\"><img src=\"https://i.stack.imgur.com/5SNFn.png\" alt=\"enter image description here\"></a></p>\n"
},
{
"answer_id": 55015480,
"author": "AVX-42",
"author_id": 10669139,
"author_profile": "https://Stackoverflow.com/users/10669139",
"pm_score": 3,
"selected": false,
"text": "<p>On linux systemd provides a command for detecting if the system is running as a virtual machine or not.</p>\n<p>Command:<br />\n<code>$ systemd-detect-virt</code></p>\n<p>If the system is virtualized then it outputs name of the virtualization softwarwe/technology.\nIf not then it outputs <code>none</code></p>\n<p>For instance if the system is running KVM then:</p>\n<pre><code>$ systemd-detect-virt\nkvm\n</code></pre>\n<p>You don't need to run it as sudo.</p>\n"
},
{
"answer_id": 66616314,
"author": "Gray Programmerz",
"author_id": 14919621,
"author_profile": "https://Stackoverflow.com/users/14919621",
"pm_score": 2,
"selected": false,
"text": "<p>I came up with universal way to detect every type of windows virtual machine with just 1 line of code. It supports win7--10 (xp not tested yet).</p>\n<h2>Why we need universal way ?</h2>\n<p>Most common used way is to search and match vendor values from win32. But what if there are 1000+ VM manufacturers ? then you would have to write a code to match 1000+ VM signatures. But its time waste. Even after sometime, there would be new other VMs launched and your script would be wasted.</p>\n<h2>Background</h2>\n<p>I worked on it for many months. I done many tests upon which I observed that:\n<strong>win32_portconnector</strong> always null and empty on VMs. Please see full report</p>\n<pre><code>//asked at: https://stackoverflow.com/q/64846900/14919621\nwhat win32_portconnector is used for ? This question have 3 parts.\n1) What is the use case of win32_portconnector ? //https://learn.microsoft.com/en-us/windows/win32/cimwin32prov/win32-portconnector\n2) Can I get state of ports using it like Mouse cable, charger, HDMI cables etc ?\n3) Why VM have null results on this query : Get-WmiObject Win32_PortConnector ?\n</code></pre>\n<p><strong>On VM:</strong></p>\n<pre><code>PS C:\\Users\\Administrator> Get-WmiObject Win32_PortConnector\n</code></pre>\n<p><strong>On Real environment:</strong></p>\n<pre><code>PS C:\\Users\\Administrator> Get-WmiObject Win32_PortConnector\nTag : Port Connector 0\nConnectorType : {23, 3}\nSerialNumber :\nExternalReferenceDesignator :\nPortType : 2\n\nTag : Port Connector 1\nConnectorType : {21, 2}\nSerialNumber :\nExternalReferenceDesignator :\nPortType : 9\n\nTag : Port Connector 2\nConnectorType : {64}\nSerialNumber :\nExternalReferenceDesignator :\nPortType : 16\n\nTag : Port Connector 3\nConnectorType : {22, 3}\nSerialNumber :\nExternalReferenceDesignator :\nPortType : 28\n\nTag : Port Connector 4\nConnectorType : {54}\nSerialNumber :\nExternalReferenceDesignator :\nPortType : 17\n\nTag : Port Connector 5\nConnectorType : {38}\nSerialNumber :\nExternalReferenceDesignator :\nPortType : 30\n\nTag : Port Connector 6\nConnectorType : {39}\nSerialNumber :\nExternalReferenceDesignator :\nPortType : 31\n</code></pre>\n<h2>Show me Code</h2>\n<p>Based upon these tests, I have made an tiny program which can detect windows VMs.</p>\n<pre class=\"lang-cs prettyprint-override\"><code>//@graysuit\n//https://graysuit.github.io\n//https://github.com/Back-X/anti-vm\nusing System;\nusing System.Windows.Forms;\n\npublic class Universal_VM_Detector\n{\n static void Main()\n {\n if((new System.Management.ManagementObjectSearcher("SELECT * FROM Win32_PortConnector")).Get().Count == 0)\n {\n MessageBox.Show("VM detected !");\n }\n else\n {\n MessageBox.Show("VM NOT detected !");\n }\n }\n}\n</code></pre>\n<p>You can <a href=\"https://github.com/Back-X/anti-vm/blob/main/anti-vm.cs#L11\" rel=\"nofollow noreferrer\">read code</a> or get <a href=\"https://github.com/Back-X/anti-vm/actions\" rel=\"nofollow noreferrer\">compiled executable</a>.</p>\n<h2>Stability</h2>\n<p>It is tested on many environments and is very stable.</p>\n<ul>\n<li>Detects Visrtualbox</li>\n<li>Detects Vmware</li>\n<li>Detects Windows Server</li>\n<li>Detects RDP</li>\n<li>Detects Virustotal</li>\n<li>Detects <a href=\"https://app.any.run/tasks/874cd411-5996-4e93-83d8-fdc72e95215a\" rel=\"nofollow noreferrer\">any.run</a>\netc...</li>\n</ul>\n"
}
] |
2008/09/30
|
[
"https://Stackoverflow.com/questions/154163",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4761/"
] |
I need to detect whether my application is running within a virtualized OS instance or not.
I've found [an article](http://www.codeproject.com/KB/system/VmDetect.aspx) with some useful information on the topic. The same article appears in multiple places, I'm unsure of the original source. [VMware](http://www.vmware.com/) implements a particular invalid x86 instruction to return information about itself, while [VirtualPC](http://www.microsoft.com/windows/products/winfamily/virtualpc/default.mspx) uses a magic number and I/O port with an IN instruction.
This is workable, but appears to be undocumented behavior in both cases. I suppose a future release of VMWare or VirtualPC might change the mechanism. Is there a better way? Is there a supported mechanism for either product?
Similarly, is there a way to detect [Xen](http://www.xen.org/) or [VirtualBox](http://www.virtualbox.org/)?
I'm not concerned about cases where the platform is deliberately trying to hide itself. For example, honeypots use virtualization but sometimes obscure the mechanisms that malware would use to detect it. I don't care that my app would think it is not virtualized in these honeypots, I'm just looking for a "best effort" solution.
The application is mostly Java, though I'm expecting to use native code plus JNI for this particular function. Windows XP/Vista support is most important, though the mechanisms described in the referenced article are generic features of x86 and don't rely on any particular OS facility.
|
Have you heard about [blue pill, red pill?](http://web.archive.org/web/20100725003848/http://www.redlightsecurity.com/2008/04/virtualization-red-pill-or-blue.html). It's a technique used to see if you are running inside a virtual machine or not. The origin of the term stems from [the matrix movie](http://www.imdb.com/title/tt0133093/) where Neo is offered a blue or a red pill (to stay inside the matrix = blue, or to enter the 'real' world = red).
The following is some code that will detect whether you are running inside 'the matrix' or not:
(code borrowed from [this site](http://web.archive.org/web/20110929075510/http://invisiblethings.org/papers/redpill.html) which also contains some nice information about the topic at hand):
```
int swallow_redpill () {
unsigned char m[2+4], rpill[] = "\x0f\x01\x0d\x00\x00\x00\x00\xc3";
*((unsigned*)&rpill[3]) = (unsigned)m;
((void(*)())&rpill)();
return (m[5]>0xd0) ? 1 : 0;
}
```
The function will return 1 when you are running inside a virutal machine, and 0 otherwise.
|
154,204 |
<p>Is there any way to change the default tab size in a .NET RichTextBox?
It currently seems to be set to the equivalent of 8 spaces which is kinda large for my taste.</p>
<p>Edit: To clarify, I want to set the global default of "\t" displays as 4 spaces for the control. From what I can understand, the SelectionTabs property requires you to select all the text first and then the the tab widths via the array. I will do this if I have to, but I would rather just change the global default once, if possible, sot that I don't have to do that every time.</p>
|
[
{
"answer_id": 154255,
"author": "Scott Nichols",
"author_id": 4299,
"author_profile": "https://Stackoverflow.com/users/4299",
"pm_score": 6,
"selected": true,
"text": "<p>You can set it by setting the <a href=\"http://msdn.microsoft.com/en-us/library/system.windows.forms.richtextbox.selectiontabs.aspx\" rel=\"noreferrer\">SelectionTabs</a> property.</p>\n\n<pre><code>private void Form1_Load(object sender, EventArgs e)\n{\n richTextBox1.SelectionTabs = new int[] { 100, 200, 300, 400 };\n}\n</code></pre>\n\n<p>UPDATE:<br>\nThe sequence matters....</p>\n\n<p>If you set the tabs prior to the control's text being initialized, then you don't have to select the text prior to setting the tabs. </p>\n\n<p>For example, in the above code, this will keep the text with the original 8 spaces tab stops:</p>\n\n<pre><code>richTextBox1.Text = \"\\t1\\t2\\t3\\t4\";\nrichTextBox1.SelectionTabs = new int[] { 100, 200, 300, 400 };\n</code></pre>\n\n<p>But this will use the new ones:</p>\n\n<pre><code>richTextBox1.SelectionTabs = new int[] { 100, 200, 300, 400 };\nrichTextBox1.Text = \"\\t1\\t2\\t3\\t4\";\n</code></pre>\n"
},
{
"answer_id": 8787004,
"author": "Dan W",
"author_id": 848344,
"author_profile": "https://Stackoverflow.com/users/848344",
"pm_score": 3,
"selected": false,
"text": "<p>Winforms doesn't have a property to set the default tab size of a RichTexBox with a single number, but if you're prepared to dig into the Rtf of the rich text box, and modify that, there's a setting you can use called: \"\\deftab\". The number afterwards indicates the number of twips (1 point = 1/72 inch = 20 twips). The resulting Rtf with the standard tab size of 720 twips could look something like:</p>\n\n<pre><code>{\\rtf1\\ansi\\ansicpg1252\\deff0\\deflang2057\\deftab720{\\fonttbl{\\f0\\fnil\\fcharset0 Microsoft Sans Serif;}}\n\\viewkind4\\uc1\\pard\\f0\\fs41\n1\\tab 2\\tab 3\\tab 4\\tab 5\\par\n}\n</code></pre>\n\n<p>If you need to convert twips into pixels, use this code inspired from <a href=\"https://stackoverflow.com/questions/139655/how-to-convert-pixels-to-points-px-to-pt-in-net-c\">Convert Pixels to Points</a>:</p>\n\n<pre><code>int tabSize=720;\nGraphics g = this.CreateGraphics();\nint pixels = (int)Math.Round(((double)tabSize) / 1440.0 * g.DpiX);\ng.Dispose();\n</code></pre>\n"
},
{
"answer_id": 18399551,
"author": "Elmue",
"author_id": 1487529,
"author_profile": "https://Stackoverflow.com/users/1487529",
"pm_score": 1,
"selected": false,
"text": "<p>If you have a RTF box that is only used to display (read only) fixed pitch text, the easiest thing would be not to mess around with Tab stops. Simply replace them stuff with spaces.</p>\n\n<p>If you want that the user can enter something and use that Tab key to advance you could also capture the Tab key by overriding <code>OnKeyDown()</code> and print spaces instead.</p>\n"
},
{
"answer_id": 52122625,
"author": "Kir_Antipov",
"author_id": 7959772,
"author_profile": "https://Stackoverflow.com/users/7959772",
"pm_score": 2,
"selected": false,
"text": "<p>It's strange that no one has proposed this method for all this time)</p>\n<p>We can inherit from the <code>RichTextBox</code> and rewrite the CmdKey handler (<a href=\"https://msdn.microsoft.com/ru-ru/library/system.windows.forms.control.processcmdkey(v=vs.110).aspx\" rel=\"nofollow noreferrer\">ProcessCmdKey</a>)<br>It will look like this:</p>\n<pre><code>public class TabRichTextBox : RichTextBox\n{\n [Browsable(true), Category("Settings")]\n public int TabSize { get; set; } = 4;\n\n protected override bool ProcessCmdKey(ref Message Msg, Keys KeyData)\n {\n \n const int WM_KEYDOWN = 0x100; // https://learn.microsoft.com/en-us/windows/desktop/inputdev/wm-keydown\n const int WM_SYSKEYDOWN = 0x104; // https://learn.microsoft.com/en-us/windows/desktop/inputdev/wm-syskeydown\n // Tab has been pressed\n if ((Msg.Msg == WM_KEYDOWN || Msg.Msg == WM_SYSKEYDOWN) && KeyData.HasFlag(Keys.Tab))\n {\n // Let's create a string of spaces, which length == TabSize\n // And then assign it to the current position\n SelectedText += new string(' ', TabSize);\n\n // Tab processed\n return true;\n }\n return base.ProcessCmdKey(ref Msg, KeyData);\n }\n}\n</code></pre>\n<p>Now, when you'll press <kbd>Tab</kbd>, a specified number of spaces will be inserted into the control area instead of <code>\\t</code></p>\n"
},
{
"answer_id": 58225802,
"author": "sɐunıɔןɐqɐp",
"author_id": 823321,
"author_profile": "https://Stackoverflow.com/users/823321",
"pm_score": 0,
"selected": false,
"text": "<p>I'm using this class with monospaced fonts; it replaces all TABs with spaces.</p>\n<p>All you have to do is to set the following designer properties according to your requirements:</p>\n<ul>\n<li>AcceptsTab = True\nTabSize</li>\n<li>ConvertTabToSpaces = True</li>\n<li>TabSize = 4</li>\n</ul>\n<p><strong>PS</strong>: As @ToolmakerSteve pointed out, obviously the tab size logic here is very simple: it just replaces tabs with 4 spaces, which only works well for tabs at the beginning of each line. Just extend the logic if you need improved tab treatment.</p>\n<p><strong>Code</strong></p>\n<pre><code>using System.ComponentModel;\nusing System.Windows.Forms;\n\nnamespace MyNamespace\n{\n public partial class MyRichTextBox : RichTextBox\n {\n public MyRichTextBox() : base() =>\n KeyDown += new KeyEventHandler(RichTextBox_KeyDown);\n\n [Browsable(true), Category("Settings"), Description("Convert all tabs into spaces."), EditorBrowsable(EditorBrowsableState.Always), DesignerSerializationVisibility(DesignerSerializationVisibility.Visible)]\n public bool ConvertTabToSpaces { get; set; } = false;\n\n [Browsable(true), Category("Settings"), Description("The number os spaces used for replacing a tab character."), EditorBrowsable(EditorBrowsableState.Always), DesignerSerializationVisibility(DesignerSerializationVisibility.Visible)]\n public int TabSize { get; set; } = 4;\n\n [Browsable(true), Category("Settings"), Description("The text associated with the control."), Bindable(true), EditorBrowsable(EditorBrowsableState.Always), DesignerSerializationVisibility(DesignerSerializationVisibility.Visible)]\n public new string Text\n {\n get => base.Text;\n set => base.Text = ConvertTabToSpaces ? value.Replace("\\t", new string(' ', TabSize)) : value;\n }\n\n protected override bool ProcessCmdKey(ref Message Msg, Keys KeyData)\n {\n const int WM_KEYDOWN = 0x100; // https://learn.microsoft.com/en-us/windows/desktop/inputdev/wm-keydown\n const int WM_SYSKEYDOWN = 0x104; // https://learn.microsoft.com/en-us/windows/desktop/inputdev/wm-syskeydown\n\n if (ConvertTabToSpaces && KeyData == Keys.Tab && (Msg.Msg == WM_KEYDOWN || Msg.Msg == WM_SYSKEYDOWN))\n {\n SelectedText += new string(' ', TabSize);\n return true;\n }\n return base.ProcessCmdKey(ref Msg, KeyData);\n }\n\n public new void AppendText(string text)\n {\n if (ConvertTabToSpaces)\n text = text.Replace("\\t", new string(' ', TabSize));\n base.AppendText(text);\n }\n\n private void RichTextBox_KeyDown(object sender, KeyEventArgs e)\n {\n if ((e.Shift && e.KeyCode == Keys.Insert) || (e.Control && e.KeyCode == Keys.V))\n {\n SuspendLayout();\n int start = SelectionStart;\n string end = Text.Substring(start);\n Text = Text.Substring(0, start);\n Text += (string)Clipboard.GetData("Text") + end;\n SelectionStart = TextLength - end.Length;\n ResumeLayout();\n e.Handled = true;\n }\n }\n\n } // class\n} // namespace\n</code></pre>\n"
}
] |
2008/09/30
|
[
"https://Stackoverflow.com/questions/154204",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/194/"
] |
Is there any way to change the default tab size in a .NET RichTextBox?
It currently seems to be set to the equivalent of 8 spaces which is kinda large for my taste.
Edit: To clarify, I want to set the global default of "\t" displays as 4 spaces for the control. From what I can understand, the SelectionTabs property requires you to select all the text first and then the the tab widths via the array. I will do this if I have to, but I would rather just change the global default once, if possible, sot that I don't have to do that every time.
|
You can set it by setting the [SelectionTabs](http://msdn.microsoft.com/en-us/library/system.windows.forms.richtextbox.selectiontabs.aspx) property.
```
private void Form1_Load(object sender, EventArgs e)
{
richTextBox1.SelectionTabs = new int[] { 100, 200, 300, 400 };
}
```
UPDATE:
The sequence matters....
If you set the tabs prior to the control's text being initialized, then you don't have to select the text prior to setting the tabs.
For example, in the above code, this will keep the text with the original 8 spaces tab stops:
```
richTextBox1.Text = "\t1\t2\t3\t4";
richTextBox1.SelectionTabs = new int[] { 100, 200, 300, 400 };
```
But this will use the new ones:
```
richTextBox1.SelectionTabs = new int[] { 100, 200, 300, 400 };
richTextBox1.Text = "\t1\t2\t3\t4";
```
|
154,209 |
<p>In Ruby-on-Rails, this is called a "polymorphic association."</p>
<p>I have several <code>Commentable</code> things in my application, the tables for each are below:</p>
<pre><code>Post
id | title | text | author (FK:Person.id) | ...
Person
id | name | ...
Photo
id | title | owner (FK:Person.id) | path | ...
</code></pre>
<p>I'd like to add a <code>Comments</code> table as follows:</p>
<pre><code>Comments
id | commentable_type | commentable_id | text | author (FK:Person.id)
</code></pre>
<p>I understand that I lose the database's referential integrity this way, but the only other option is to have multiple <code>Comments</code> tables: <code>PostComments</code>, <code>PersonComments</code>, <code>PhotoComments</code>, ...</p>
<p><strong>And now for the question:</strong></p>
<p>How can I build a form that will grok how to do the lookup, first by getting the table name from <code>Comments.commentable_type</code> and then the id from <code>Comments.commentable_id</code>?</p>
|
[
{
"answer_id": 154237,
"author": "Joe Phillips",
"author_id": 20471,
"author_profile": "https://Stackoverflow.com/users/20471",
"pm_score": 0,
"selected": false,
"text": "<p>I believe many people make meta-tables for that sort of thing. Pretty much exactly as you described it.</p>\n"
},
{
"answer_id": 156708,
"author": "onedaywhen",
"author_id": 15354,
"author_profile": "https://Stackoverflow.com/users/15354",
"pm_score": 3,
"selected": true,
"text": "<p>This technique is known colloquially in the SQL world as 'subclassing'. For a worked example (SQL Server syntax but is easily adapted for MS Access), see <a href=\"http://web.archive.org/web/20100309034643/http://consultingblogs.emc.com/davidportas/archive/2007/01/08/Distributed-Keys-and-Disjoint-Subtypes.aspx\" rel=\"nofollow noreferrer\">David Porta's blog.</a>.</p>\n\n<p>In your scenario, the data items common to all comments would be in your Comments table; anything specific to each type would be in specialized tables such as PhotoComments, etc. Note the FK should be the two-column compound of the ID plus the type, something which is often overlooked but is essential to referential integrity here e.g. you don’t want something typed as a photo comment appearing in the PersonComments table. </p>\n"
}
] |
2008/09/30
|
[
"https://Stackoverflow.com/questions/154209",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1190/"
] |
In Ruby-on-Rails, this is called a "polymorphic association."
I have several `Commentable` things in my application, the tables for each are below:
```
Post
id | title | text | author (FK:Person.id) | ...
Person
id | name | ...
Photo
id | title | owner (FK:Person.id) | path | ...
```
I'd like to add a `Comments` table as follows:
```
Comments
id | commentable_type | commentable_id | text | author (FK:Person.id)
```
I understand that I lose the database's referential integrity this way, but the only other option is to have multiple `Comments` tables: `PostComments`, `PersonComments`, `PhotoComments`, ...
**And now for the question:**
How can I build a form that will grok how to do the lookup, first by getting the table name from `Comments.commentable_type` and then the id from `Comments.commentable_id`?
|
This technique is known colloquially in the SQL world as 'subclassing'. For a worked example (SQL Server syntax but is easily adapted for MS Access), see [David Porta's blog.](http://web.archive.org/web/20100309034643/http://consultingblogs.emc.com/davidportas/archive/2007/01/08/Distributed-Keys-and-Disjoint-Subtypes.aspx).
In your scenario, the data items common to all comments would be in your Comments table; anything specific to each type would be in specialized tables such as PhotoComments, etc. Note the FK should be the two-column compound of the ID plus the type, something which is often overlooked but is essential to referential integrity here e.g. you don’t want something typed as a photo comment appearing in the PersonComments table.
|
154,232 |
<p>The app uses DLLImport to call a legacy unmanaged dll. Let's call this dll Unmanaged.dll for the sake of this question. Unmanaged.dll has dependencies on 5 other legacy dll's. All of the legacy dll's are placed in the WebApp/bin/ directory of my ASP.NET application.</p>
<p>When IIS is running in 5.0 isolation mode, the app works fine - calls to the legacy dll are processed without error.</p>
<p>When IIS is running in the default 6.0 mode, the app is able to initiate the Unmanaged.dll (InitMe()), but dies during a later call to it (ProcessString()).</p>
<p>I'm pulling my hair out here. I've moved the unmanaged dll's to various locations, tried all kinds of security settings and searched long and hard for a solution. Help!</p>
<p>Sample code:</p>
<pre><code>[DllImport("Unmanaged.dll", EntryPoint="initME", CharSet=System.Runtime.InteropServices.CharSet.Ansi, CallingConvention=CallingConvention.Cdecl)]
internal static extern int InitME();
//Calls to InitMe work fine - Unmanaged.dll initiates and writes some entries in a dedicated log file
[DllImport("Unmanaged.dll", EntryPoint="processString", CharSet=System.Runtime.InteropServices.CharSet.Ansi, CallingConvention=CallingConvention.Cdecl)]
internal static extern int ProcessString(string inStream, int inLen, StringBuilder outStream, ref int outLen, int maxLen);
//Calls to ProcessString cause the app to crash, without leaving much of a trace that I can find so far
</code></pre>
<h3>Update:</h3>
<p>Back with a stack, taken from a mini dump. Seems to be a stack overflow, but I'd like to know more if someone can help me out. Results of "kb" in WinDbg with sos.dll loaded:</p>
<pre><code>1beb51fc 7c947cfb 7c82202c 00000002 1beb524c ntdll!KiFastSystemCallRet
1beb5200 7c82202c 00000002 1beb524c 00000001 ntdll!NtWaitForMultipleObjects+0xc
WARNING: Stack unwind information not available. Following frames may be wrong.
1beb52a8 7c822fbe 00000002 1beb52ec 00000000 kernel32!WaitForMultipleObjectsEx+0xd2
1beb52c4 7a2e1468 00000002 1beb52ec 00000000 kernel32!WaitForMultipleObjects+0x18
1beb5308 7a2d00c4 7a0c3077 1bc4ffd8 1bc4ffd8 mscorwks!CreateHistoryReader+0x19e9d
1beb531c 7a0c312f 7a0c3077 1bc4ffd8 888d9fd9 mscorwks!CreateHistoryReader+0x8af9
1beb5350 7a106b2d 1b2733a0 00000001 1b2733a0 mscorwks!GetCompileInfo+0x345ed
1beb5378 7a105b91 1b272ff8 1b2733a0 00000001 mscorwks!GetAddrOfContractShutoffFlag+0x93a8
1beb53e0 7a105d46 1beb5388 1b272ff8 1beb5520 mscorwks!GetAddrOfContractShutoffFlag+0x840c
1beb5404 79fe29c5 00000001 00000000 00000000 mscorwks!GetAddrOfContractShutoffFlag+0x85c1
1beb5420 7c948752 1beb5504 1beef9b8 1beb5520 mscorwks!NGenCreateNGenWorker+0x4d52
1beb5444 7c948723 1beb5504 1beef9b8 1beb5520 ntdll!ExecuteHandler2+0x26
1beb54ec 7c94855e 1beb1000 1beb5520 1beb5504 ntdll!ExecuteHandler+0x24
1beb54ec 1c9f2264 1beb1000 1beb5520 1beb5504 ntdll!KiUserExceptionDispatcher+0xe
1beb57f4 1c92992d 1beb6e28 1db84d70 1db90e28 Unmanaged1!UMgetMaxSmth+0x1200ad
1beb5860 1c929cfe 00000000 1db84d70 1beb6e28 Unmanaged1!UMgetMaxSmth+0x57776
1beb58c0 1c930b04 00000000 1db84d70 1beb6e28 Unmanaged1!UMgetMaxSmth+0x57b47
1beb5924 1c99d088 00000000 1db84d70 1beb6e28 Unmanaged1!UMgetMaxSmth+0x5e94d
1beb5990 1c99c955 00000000 1beb6e28 1beb6590 Unmanaged1!UMgetMaxSmth+0xcaed1
1beb5a44 1c99e9ae 00000000 40977000 1db90e28 Unmanaged1!UMgetMaxSmth+0xca79e
</code></pre>
|
[
{
"answer_id": 154360,
"author": "Mitchel Sellers",
"author_id": 13279,
"author_profile": "https://Stackoverflow.com/users/13279",
"pm_score": 0,
"selected": false,
"text": "<p>What is the error given? if the application truly crashed you might have to go into the Windows Event Log to get the stack trace of the error.</p>\n"
},
{
"answer_id": 154424,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 0,
"selected": false,
"text": "<p>I've run procmon, debugdiag, tried to work with microsoft debugging tools. Each time the app crashes, Dr. Watson creates a pair of files - .dmp and .tmp (which I have tried to debug without success).</p>\n\n<p>Here's the error from the Event Log:</p>\n\n<p>Event Type: Error<br>\nEvent Source: .NET Runtime 2.0 Error Reporting<br>\nEvent Category: None<br>\nEvent Code: 1000<br>\nDate: 30.09.2008<br>\nTime: 16:13:38<br>\nUser: Not Applicable<br>\nComputer: APPLICATIONTEST010<br>\nDescription:<br>\nFaulting application w3wp.exe, version 6.0.3790.3959, stamp 45d6968e, faulting module Unmanaged1.dll, version 0.0.0.0, stamp 48b6bfb8, debug? 0, fault address 0x00122264.</p>\n"
},
{
"answer_id": 208180,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 1,
"selected": false,
"text": "<p>Solution:\nCreate a new thread in which to run the imported dll, assign more memory to its stack.</p>\n"
},
{
"answer_id": 2488713,
"author": "Alexander Frost",
"author_id": 253553,
"author_profile": "https://Stackoverflow.com/users/253553",
"pm_score": 0,
"selected": false,
"text": "<p>I think a potential problem to look for here is that your DLL could be unloaded by runtime between calls to InitME and ProcessString - so if ProcessString depends on InitME being called first, it might go \"boom\".</p>\n\n<p>The solution to that would be using good old LoadLibrary and FreeLibrary to force runtime to keep the library loaded between calls to those two functions. GetProcAddress is not needed (as far as I can tell).</p>\n"
}
] |
2008/09/30
|
[
"https://Stackoverflow.com/questions/154232",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] |
The app uses DLLImport to call a legacy unmanaged dll. Let's call this dll Unmanaged.dll for the sake of this question. Unmanaged.dll has dependencies on 5 other legacy dll's. All of the legacy dll's are placed in the WebApp/bin/ directory of my ASP.NET application.
When IIS is running in 5.0 isolation mode, the app works fine - calls to the legacy dll are processed without error.
When IIS is running in the default 6.0 mode, the app is able to initiate the Unmanaged.dll (InitMe()), but dies during a later call to it (ProcessString()).
I'm pulling my hair out here. I've moved the unmanaged dll's to various locations, tried all kinds of security settings and searched long and hard for a solution. Help!
Sample code:
```
[DllImport("Unmanaged.dll", EntryPoint="initME", CharSet=System.Runtime.InteropServices.CharSet.Ansi, CallingConvention=CallingConvention.Cdecl)]
internal static extern int InitME();
//Calls to InitMe work fine - Unmanaged.dll initiates and writes some entries in a dedicated log file
[DllImport("Unmanaged.dll", EntryPoint="processString", CharSet=System.Runtime.InteropServices.CharSet.Ansi, CallingConvention=CallingConvention.Cdecl)]
internal static extern int ProcessString(string inStream, int inLen, StringBuilder outStream, ref int outLen, int maxLen);
//Calls to ProcessString cause the app to crash, without leaving much of a trace that I can find so far
```
### Update:
Back with a stack, taken from a mini dump. Seems to be a stack overflow, but I'd like to know more if someone can help me out. Results of "kb" in WinDbg with sos.dll loaded:
```
1beb51fc 7c947cfb 7c82202c 00000002 1beb524c ntdll!KiFastSystemCallRet
1beb5200 7c82202c 00000002 1beb524c 00000001 ntdll!NtWaitForMultipleObjects+0xc
WARNING: Stack unwind information not available. Following frames may be wrong.
1beb52a8 7c822fbe 00000002 1beb52ec 00000000 kernel32!WaitForMultipleObjectsEx+0xd2
1beb52c4 7a2e1468 00000002 1beb52ec 00000000 kernel32!WaitForMultipleObjects+0x18
1beb5308 7a2d00c4 7a0c3077 1bc4ffd8 1bc4ffd8 mscorwks!CreateHistoryReader+0x19e9d
1beb531c 7a0c312f 7a0c3077 1bc4ffd8 888d9fd9 mscorwks!CreateHistoryReader+0x8af9
1beb5350 7a106b2d 1b2733a0 00000001 1b2733a0 mscorwks!GetCompileInfo+0x345ed
1beb5378 7a105b91 1b272ff8 1b2733a0 00000001 mscorwks!GetAddrOfContractShutoffFlag+0x93a8
1beb53e0 7a105d46 1beb5388 1b272ff8 1beb5520 mscorwks!GetAddrOfContractShutoffFlag+0x840c
1beb5404 79fe29c5 00000001 00000000 00000000 mscorwks!GetAddrOfContractShutoffFlag+0x85c1
1beb5420 7c948752 1beb5504 1beef9b8 1beb5520 mscorwks!NGenCreateNGenWorker+0x4d52
1beb5444 7c948723 1beb5504 1beef9b8 1beb5520 ntdll!ExecuteHandler2+0x26
1beb54ec 7c94855e 1beb1000 1beb5520 1beb5504 ntdll!ExecuteHandler+0x24
1beb54ec 1c9f2264 1beb1000 1beb5520 1beb5504 ntdll!KiUserExceptionDispatcher+0xe
1beb57f4 1c92992d 1beb6e28 1db84d70 1db90e28 Unmanaged1!UMgetMaxSmth+0x1200ad
1beb5860 1c929cfe 00000000 1db84d70 1beb6e28 Unmanaged1!UMgetMaxSmth+0x57776
1beb58c0 1c930b04 00000000 1db84d70 1beb6e28 Unmanaged1!UMgetMaxSmth+0x57b47
1beb5924 1c99d088 00000000 1db84d70 1beb6e28 Unmanaged1!UMgetMaxSmth+0x5e94d
1beb5990 1c99c955 00000000 1beb6e28 1beb6590 Unmanaged1!UMgetMaxSmth+0xcaed1
1beb5a44 1c99e9ae 00000000 40977000 1db90e28 Unmanaged1!UMgetMaxSmth+0xca79e
```
|
Solution:
Create a new thread in which to run the imported dll, assign more memory to its stack.
|
154,248 |
<p>I tried:</p>
<pre><code>DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
DocumentBuilder db = dbf.newDocumentBuilder();
Document doc = db.parse(f);
Node mapNode = getMapNode(doc);
System.out.print("\r\n elementName "+ mapNode.getNodeName());//This works fine.
Element e = (Element) mapNode; //This is where the error occurs
//it seems to work on my machine, but not on the server.
e.setAttribute("objectId", "OBJ123");
</code></pre>
<p>But this throws a java.lang.ClassCastException error on the line that casts it to Element. <strong>mapNode is a valid node.</strong> I already have it printing out </p>
<p>I think maybe this code does not work in Java 1.4. What I really need is an alternative to using Element. I tried doing</p>
<pre><code>NamedNodeMap atts = mapNode.getAttributes();
Attr att = doc.createAttribute("objId");
att.setValue(docId);
atts.setNamedItem(att);
</code></pre>
<p>But getAttributes() returns null on the server. Even though its not and I am using the same document locally as on the server. And it can print out the getNodeName() its just that the getAttributes() does not work.</p>
|
[
{
"answer_id": 154297,
"author": "Garth Gilmour",
"author_id": 2635682,
"author_profile": "https://Stackoverflow.com/users/2635682",
"pm_score": 0,
"selected": false,
"text": "<p>Might the first child be a whitespace only text node or suchlike?</p>\n\n<p>Try:</p>\n\n<pre><code>System.out.println(doc.getFirstChild().getClass().getName());\n</code></pre>\n\n<p>EDIT:</p>\n\n<p>Just looked it up in my own code, you need:</p>\n\n<pre><code>doc.getDocumentElement().getChildNodes();\n</code></pre>\n\n<p>Or:</p>\n\n<pre><code>NodeList nodes = doc.getElementsByTagName(\"MyTag\");\n</code></pre>\n"
},
{
"answer_id": 154315,
"author": "John M",
"author_id": 20734,
"author_profile": "https://Stackoverflow.com/users/20734",
"pm_score": 0,
"selected": false,
"text": "<p>I think your cast of the output of doc.getFirstChild() is where you're getting your exception -- you're getting some non-Element Node object. Does the line number on the stack trace point to that line? You might need to do a doc.getChildNodes() and iterate to find the first Element child (doc root), skipping non-Element Nodes.</p>\n\n<p>Your e.setAttribute() call looks sensible. Assuming e is an Element and you actually get to that line...</p>\n"
},
{
"answer_id": 154370,
"author": "Brandon DuRette",
"author_id": 17834,
"author_profile": "https://Stackoverflow.com/users/17834",
"pm_score": 0,
"selected": false,
"text": "<p>As already noted, the <code>ClassCastException</code> is probably not being thrown in <code>setAttribute</code>. Check the line number in the stack. My guess is that <code>getFirstChild()</code> is returning a <code>DocumentType</code>, not an <code>Element</code>.</p>\n\n<p>Try this:</p>\n\n<pre><code>DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();\n\nDocumentBuilder db = dbf.newDocumentBuilder();\nDocument doc = db.parse(f);\n\nElement e = (Element) doc.getDocumentElement().getFirstChild();\ne.setAttribute(\"objectId\", \"OBJ123\");\n</code></pre>\n\n<p>Update: </p>\n\n<p>It seems like you are confusing <code>Node</code> and <code>Element</code>. <code>Element</code> is an implementation of <code>Node</code>, but certainly not the only one. So, not all <code>Node</code>'s are castable to <code>Element</code>. If the cast is working on one machine and not on another, it's because you're getting something else back from <code>getMapNode()</code> because the parsers are behaving differently. The XML parser is pluggable in Java 1.4, so you could be getting an entirely different implementation, from a different vendor, with different bugs even. </p>\n\n<p>Since you're not posting <code>getMapNode()</code> we cannot see what it's doing, but you should be explicit about what node you want it to return (using <code>getElementsByTagName</code> or otherwise). </p>\n"
},
{
"answer_id": 154734,
"author": "joe",
"author_id": 5653,
"author_profile": "https://Stackoverflow.com/users/5653",
"pm_score": 2,
"selected": true,
"text": "<p>I was using a different dtd file on the server. That was causing the issue.</p>\n"
}
] |
2008/09/30
|
[
"https://Stackoverflow.com/questions/154248",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5653/"
] |
I tried:
```
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
DocumentBuilder db = dbf.newDocumentBuilder();
Document doc = db.parse(f);
Node mapNode = getMapNode(doc);
System.out.print("\r\n elementName "+ mapNode.getNodeName());//This works fine.
Element e = (Element) mapNode; //This is where the error occurs
//it seems to work on my machine, but not on the server.
e.setAttribute("objectId", "OBJ123");
```
But this throws a java.lang.ClassCastException error on the line that casts it to Element. **mapNode is a valid node.** I already have it printing out
I think maybe this code does not work in Java 1.4. What I really need is an alternative to using Element. I tried doing
```
NamedNodeMap atts = mapNode.getAttributes();
Attr att = doc.createAttribute("objId");
att.setValue(docId);
atts.setNamedItem(att);
```
But getAttributes() returns null on the server. Even though its not and I am using the same document locally as on the server. And it can print out the getNodeName() its just that the getAttributes() does not work.
|
I was using a different dtd file on the server. That was causing the issue.
|
154,256 |
<blockquote>
<p><strong>Possible Duplicate:</strong><br>
<a href="https://stackoverflow.com/questions/105372/c-how-to-enumerate-an-enum">C#: How to enumerate an enum?</a> </p>
</blockquote>
<p>The subject says all. I want to use that to add the values of an enum in a combobox.</p>
<p>Thanks</p>
<p>vIceBerg</p>
|
[
{
"answer_id": 154263,
"author": "albertein",
"author_id": 23020,
"author_profile": "https://Stackoverflow.com/users/23020",
"pm_score": 6,
"selected": true,
"text": "<pre><code>string[] names = Enum.GetNames (typeof(MyEnum));\n</code></pre>\n\n<p>Then just populate the dropdown withe the array</p>\n"
},
{
"answer_id": 154266,
"author": "JosephStyons",
"author_id": 672,
"author_profile": "https://Stackoverflow.com/users/672",
"pm_score": 0,
"selected": false,
"text": "<p>It is often useful to define a Min and Max inside your enum, which will always be the first and last items. Here is a very simple example using Delphi syntax:</p>\n\n<pre><code>procedure TForm1.Button1Click(Sender: TObject);\ntype\n TEmployeeTypes = (etMin, etHourly, etSalary, etContractor, etMax);\nvar\n i : TEmployeeTypes;\nbegin\n for i := etMin to etMax do begin\n //do something\n end;\nend;\n</code></pre>\n"
},
{
"answer_id": 154269,
"author": "Firas Assaad",
"author_id": 23153,
"author_profile": "https://Stackoverflow.com/users/23153",
"pm_score": 3,
"selected": false,
"text": "<p>You could iterate through the array returned by the <a href=\"http://msdn.microsoft.com/en-us/library/system.enum.getnames(VS.80).aspx\" rel=\"nofollow noreferrer\">Enum.GetNames method</a> instead.</p>\n\n<pre><code>public class GetNamesTest {\n enum Colors { Red, Green, Blue, Yellow };\n enum Styles { Plaid, Striped, Tartan, Corduroy };\n\n public static void Main() {\n\n Console.WriteLine(\"The values of the Colors Enum are:\");\n foreach(string s in Enum.GetNames(typeof(Colors)))\n Console.WriteLine(s);\n\n Console.WriteLine();\n\n Console.WriteLine(\"The values of the Styles Enum are:\");\n foreach(string s in Enum.GetNames(typeof(Styles)))\n Console.WriteLine(s);\n }\n}\n</code></pre>\n"
},
{
"answer_id": 154302,
"author": "Lasse V. Karlsen",
"author_id": 267,
"author_profile": "https://Stackoverflow.com/users/267",
"pm_score": 3,
"selected": false,
"text": "<p>Use the Enum.GetValues method:</p>\n\n<pre><code>foreach (TestEnum en in Enum.GetValues(typeof(TestEnum)))\n{\n ...\n}\n</code></pre>\n\n<p>You don't need to cast them to a string, and that way you can just retrieve them back by casting the SelectedItem property to a TestEnum value directly as well.</p>\n"
},
{
"answer_id": 154306,
"author": "rslite",
"author_id": 15682,
"author_profile": "https://Stackoverflow.com/users/15682",
"pm_score": 3,
"selected": false,
"text": "<p>If you need the values of the combo to correspond to the values of the enum you can also use something like this:</p>\n\n<pre><code>foreach (TheEnum value in Enum.GetValues(typeof(TheEnum)))\n dropDown.Items.Add(new ListItem(\n value.ToString(), ((int)value).ToString()\n );\n</code></pre>\n\n<p>In this way you can show the texts in the dropdown and obtain back the value (in SelectedValue property)</p>\n"
},
{
"answer_id": 154335,
"author": "Ray Hayes",
"author_id": 7093,
"author_profile": "https://Stackoverflow.com/users/7093",
"pm_score": 5,
"selected": false,
"text": "<p>I know others have already answered with a correct answer, however, if you're wanting to use the enumerations in a combo box, you may want to go the extra yard and associate strings to the enum so that you can provide more detail in the displayed string (such as spaces between words or display strings using casing that doesn't match your coding standards)</p>\n\n<p>This blog entry may be useful - <a href=\"http://blog.spontaneouspublicity.com/2008/01/17/associating-strings-with-enums-in-c/\" rel=\"noreferrer\">Associating Strings with enums in c#</a></p>\n\n<pre><code>public enum States\n{\n California,\n [Description(\"New Mexico\")]\n NewMexico,\n [Description(\"New York\")]\n NewYork,\n [Description(\"South Carolina\")]\n SouthCarolina,\n Tennessee,\n Washington\n}\n</code></pre>\n\n<p>As a bonus, he also supplied a utility method for enumerating the enumeration that I've now updated with Jon Skeet's comments</p>\n\n<pre><code>public static IEnumerable<T> EnumToList<T>()\n where T : struct\n{\n Type enumType = typeof(T);\n\n // Can't use generic type constraints on value types,\n // so have to do check like this\n if (enumType.BaseType != typeof(Enum))\n throw new ArgumentException(\"T must be of type System.Enum\");\n\n Array enumValArray = Enum.GetValues(enumType);\n List<T> enumValList = new List<T>();\n\n foreach (T val in enumValArray)\n {\n enumValList.Add(val.ToString());\n }\n\n return enumValList;\n}\n</code></pre>\n\n<p>Jon also pointed out that in C# 3.0 it can be simplified to something like this (which is now getting so light-weight that I'd imagine you could just do it in-line):</p>\n\n<pre><code>public static IEnumerable<T> EnumToList<T>()\n where T : struct\n{\n return Enum.GetValues(typeof(T)).Cast<T>();\n}\n\n// Using above method\nstatesComboBox.Items = EnumToList<States>();\n\n// Inline\nstatesComboBox.Items = Enum.GetValues(typeof(States)).Cast<States>();\n</code></pre>\n"
},
{
"answer_id": 154350,
"author": "Programmin Tool",
"author_id": 21691,
"author_profile": "https://Stackoverflow.com/users/21691",
"pm_score": 0,
"selected": false,
"text": "<p>Little more \"complicated\" (maybe overkill) but I use these two methods to return dictionaries to use as datasources. The first one returns the name as key and the second value as key. </p>\n\n<pre>\npublic static IDictionary<string, int> ConvertEnumToDictionaryNameFirst<K>()\n{\n if (typeof(K).BaseType != typeof(Enum))\n {\n throw new InvalidCastException();\n }\n\n return Enum.GetValues(typeof(K)).Cast<int>().ToDictionary(currentItem \n => Enum.GetName(typeof(K), currentItem));\n}\n</pre>\n\n<p>Or you could do </p>\n\n<pre>\n\npublic static IDictionary<int, string> ConvertEnumToDictionaryValueFirst<K>()\n{\n if (typeof(K).BaseType != typeof(Enum))\n {\n throw new InvalidCastException();\n }\n\n return Enum.GetNames(typeof(K)).Cast<string>().ToDictionary(currentItem \n => (int)Enum.Parse(typeof(K), currentItem));\n}\n</pre>\n\n<p>This assumes you are using 3.5 though. You'd have to replace the lambda expressions if not.</p>\n\n<p>Use:</p>\n\n<pre>\n\n Dictionary list = ConvertEnumToDictionaryValueFirst<SomeEnum>();\n\n</pre>\n\n<pre>\n using System;\n using System.Collections.Generic;\n using System.Linq;\n</pre>\n"
},
{
"answer_id": 154383,
"author": "Donny V.",
"author_id": 1231,
"author_profile": "https://Stackoverflow.com/users/1231",
"pm_score": 1,
"selected": false,
"text": "<p>The problem with using enums to populate pull downs is that you cann't have weird characters or spaces in enums. I have some code that extends enums so that you can add any character you want.</p>\n\n<p>Use it like this..</p>\n\n<pre><code>public enum eCarType\n{\n [StringValue(\"Saloon / Sedan\")] Saloon = 5,\n [StringValue(\"Coupe\")] Coupe = 4,\n [StringValue(\"Estate / Wagon\")] Estate = 6,\n [StringValue(\"Hatchback\")] Hatchback = 8,\n [StringValue(\"Utility\")] Ute = 1,\n}\n</code></pre>\n\n<p>Bind data like so..</p>\n\n<pre><code>StringEnum CarTypes = new StringEnum(typeof(eCarTypes));\ncmbCarTypes.DataSource = CarTypes.GetGenericListValues();\n</code></pre>\n\n<p>Here is the class that extends the enum.</p>\n\n<pre><code>// Author: Donny V.\n// blog: http://donnyvblog.blogspot.com\n\nusing System;\nusing System.Collections;\nusing System.Collections.Generic;\nusing System.Reflection;\n\nnamespace xEnums\n{\n\n #region Class StringEnum\n\n /// <summary>\n /// Helper class for working with 'extended' enums using <see cref=\"StringValueAttribute\"/> attributes.\n /// </summary>\n public class StringEnum\n {\n #region Instance implementation\n\n private Type _enumType;\n private static Hashtable _stringValues = new Hashtable();\n\n /// <summary>\n /// Creates a new <see cref=\"StringEnum\"/> instance.\n /// </summary>\n /// <param name=\"enumType\">Enum type.</param>\n public StringEnum(Type enumType)\n {\n if (!enumType.IsEnum)\n throw new ArgumentException(String.Format(\"Supplied type must be an Enum. Type was {0}\", enumType.ToString()));\n\n _enumType = enumType;\n }\n\n /// <summary>\n /// Gets the string value associated with the given enum value.\n /// </summary>\n /// <param name=\"valueName\">Name of the enum value.</param>\n /// <returns>String Value</returns>\n public string GetStringValue(string valueName)\n {\n Enum enumType;\n string stringValue = null;\n try\n {\n enumType = (Enum) Enum.Parse(_enumType, valueName);\n stringValue = GetStringValue(enumType);\n }\n catch (Exception) { }//Swallow!\n\n return stringValue;\n }\n\n /// <summary>\n /// Gets the string values associated with the enum.\n /// </summary>\n /// <returns>String value array</returns>\n public Array GetStringValues()\n {\n ArrayList values = new ArrayList();\n //Look for our string value associated with fields in this enum\n foreach (FieldInfo fi in _enumType.GetFields())\n {\n //Check for our custom attribute\n StringValueAttribute[] attrs = fi.GetCustomAttributes(typeof (StringValueAttribute), false) as StringValueAttribute[];\n if (attrs.Length > 0)\n values.Add(attrs[0].Value);\n\n }\n\n return values.ToArray();\n }\n\n /// <summary>\n /// Gets the values as a 'bindable' list datasource.\n /// </summary>\n /// <returns>IList for data binding</returns>\n public IList GetListValues()\n {\n Type underlyingType = Enum.GetUnderlyingType(_enumType);\n ArrayList values = new ArrayList();\n //List<string> values = new List<string>();\n\n //Look for our string value associated with fields in this enum\n foreach (FieldInfo fi in _enumType.GetFields())\n {\n //Check for our custom attribute\n StringValueAttribute[] attrs = fi.GetCustomAttributes(typeof (StringValueAttribute), false) as StringValueAttribute[];\n if (attrs.Length > 0)\n values.Add(new DictionaryEntry(Convert.ChangeType(Enum.Parse(_enumType, fi.Name), underlyingType), attrs[0].Value));\n\n }\n\n return values;\n\n }\n\n /// <summary>\n /// Gets the values as a 'bindable' list<string> datasource.\n ///This is a newer version of 'GetListValues()'\n /// </summary>\n /// <returns>IList<string> for data binding</returns>\n public IList<string> GetGenericListValues()\n {\n Type underlyingType = Enum.GetUnderlyingType(_enumType);\n List<string> values = new List<string>();\n\n //Look for our string value associated with fields in this enum\n foreach (FieldInfo fi in _enumType.GetFields())\n {\n //Check for our custom attribute\n StringValueAttribute[] attrs = fi.GetCustomAttributes(typeof(StringValueAttribute), false) as StringValueAttribute[];\n if (attrs.Length > 0)\n values.Add(attrs[0].Value);\n }\n\n return values;\n\n }\n\n /// <summary>\n /// Return the existence of the given string value within the enum.\n /// </summary>\n /// <param name=\"stringValue\">String value.</param>\n /// <returns>Existence of the string value</returns>\n public bool IsStringDefined(string stringValue)\n {\n return Parse(_enumType, stringValue) != null;\n }\n\n /// <summary>\n /// Return the existence of the given string value within the enum.\n /// </summary>\n /// <param name=\"stringValue\">String value.</param>\n /// <param name=\"ignoreCase\">Denotes whether to conduct a case-insensitive match on the supplied string value</param>\n /// <returns>Existence of the string value</returns>\n public bool IsStringDefined(string stringValue, bool ignoreCase)\n {\n return Parse(_enumType, stringValue, ignoreCase) != null;\n }\n\n /// <summary>\n /// Gets the underlying enum type for this instance.\n /// </summary>\n /// <value></value>\n public Type EnumType\n {\n get { return _enumType; }\n }\n\n #endregion\n\n #region Static implementation\n\n /// <summary>\n /// Gets a string value for a particular enum value.\n /// </summary>\n /// <param name=\"value\">Value.</param>\n /// <returns>String Value associated via a <see cref=\"StringValueAttribute\"/> attribute, or null if not found.</returns>\n public static string GetStringValue(Enum value)\n {\n string output = null;\n Type type = value.GetType();\n\n if (_stringValues.ContainsKey(value))\n output = (_stringValues[value] as StringValueAttribute).Value;\n else \n {\n //Look for our 'StringValueAttribute' in the field's custom attributes\n FieldInfo fi = type.GetField(value.ToString());\n StringValueAttribute[] attrs = fi.GetCustomAttributes(typeof (StringValueAttribute), false) as StringValueAttribute[];\n if (attrs.Length > 0)\n {\n _stringValues.Add(value, attrs[0]);\n output = attrs[0].Value;\n }\n\n }\n return output;\n\n }\n\n /// <summary>\n /// Parses the supplied enum and string value to find an associated enum value (case sensitive).\n /// </summary>\n /// <param name=\"type\">Type.</param>\n /// <param name=\"stringValue\">String value.</param>\n /// <returns>Enum value associated with the string value, or null if not found.</returns>\n public static object Parse(Type type, string stringValue)\n {\n return Parse(type, stringValue, false);\n }\n\n /// <summary>\n /// Parses the supplied enum and string value to find an associated enum value.\n /// </summary>\n /// <param name=\"type\">Type.</param>\n /// <param name=\"stringValue\">String value.</param>\n /// <param name=\"ignoreCase\">Denotes whether to conduct a case-insensitive match on the supplied string value</param>\n /// <returns>Enum value associated with the string value, or null if not found.</returns>\n public static object Parse(Type type, string stringValue, bool ignoreCase)\n {\n object output = null;\n string enumStringValue = null;\n\n if (!type.IsEnum)\n throw new ArgumentException(String.Format(\"Supplied type must be an Enum. Type was {0}\", type.ToString()));\n\n //Look for our string value associated with fields in this enum\n foreach (FieldInfo fi in type.GetFields())\n {\n //Check for our custom attribute\n StringValueAttribute[] attrs = fi.GetCustomAttributes(typeof (StringValueAttribute), false) as StringValueAttribute[];\n if (attrs.Length > 0)\n enumStringValue = attrs[0].Value;\n\n //Check for equality then select actual enum value.\n if (string.Compare(enumStringValue, stringValue, ignoreCase) == 0)\n {\n output = Enum.Parse(type, fi.Name);\n break;\n }\n }\n\n return output;\n }\n\n /// <summary>\n /// Return the existence of the given string value within the enum.\n /// </summary>\n /// <param name=\"stringValue\">String value.</param>\n /// <param name=\"enumType\">Type of enum</param>\n /// <returns>Existence of the string value</returns>\n public static bool IsStringDefined(Type enumType, string stringValue)\n {\n return Parse(enumType, stringValue) != null;\n }\n\n /// <summary>\n /// Return the existence of the given string value within the enum.\n /// </summary>\n /// <param name=\"stringValue\">String value.</param>\n /// <param name=\"enumType\">Type of enum</param>\n /// <param name=\"ignoreCase\">Denotes whether to conduct a case-insensitive match on the supplied string value</param>\n /// <returns>Existence of the string value</returns>\n public static bool IsStringDefined(Type enumType, string stringValue, bool ignoreCase)\n {\n return Parse(enumType, stringValue, ignoreCase) != null;\n }\n\n #endregion\n }\n\n #endregion\n\n #region Class StringValueAttribute\n\n /// <summary>\n /// Simple attribute class for storing String Values\n /// </summary>\n public class StringValueAttribute : Attribute\n {\n private string _value;\n\n /// <summary>\n /// Creates a new <see cref=\"StringValueAttribute\"/> instance.\n /// </summary>\n /// <param name=\"value\">Value.</param>\n public StringValueAttribute(string value)\n {\n _value = value;\n }\n\n /// <summary>\n /// Gets the value.\n /// </summary>\n /// <value></value>\n public string Value\n {\n get { return _value; }\n }\n }\n\n #endregion\n}\n</code></pre>\n"
},
{
"answer_id": 154513,
"author": "Michael Damatov",
"author_id": 23372,
"author_profile": "https://Stackoverflow.com/users/23372",
"pm_score": 1,
"selected": false,
"text": "<p>.NET 3.5 makes it simple by using extension methods:</p>\n\n<pre><code>enum Color {Red, Green, Blue}\n</code></pre>\n\n<p>Can be iterated with</p>\n\n<pre><code>Enum.GetValues(typeof(Color)).Cast<Color>()\n</code></pre>\n\n<p>or define a new static generic method:</p>\n\n<pre><code>static IEnumerable<T> GetValues<T>() {\n return Enum.GetValues(typeof(T)).Cast<T>();\n}\n</code></pre>\n\n<p>Keep in mind that iterating with the Enum.GetValues() method uses reflection and thus has performance penalties.</p>\n"
}
] |
2008/09/30
|
[
"https://Stackoverflow.com/questions/154256",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/17766/"
] |
>
> **Possible Duplicate:**
>
> [C#: How to enumerate an enum?](https://stackoverflow.com/questions/105372/c-how-to-enumerate-an-enum)
>
>
>
The subject says all. I want to use that to add the values of an enum in a combobox.
Thanks
vIceBerg
|
```
string[] names = Enum.GetNames (typeof(MyEnum));
```
Then just populate the dropdown withe the array
|
154,261 |
<p>I frequently run into problems of this form and haven't found a good solution yet:</p>
<p>Assume we have two database tables representing an e-commerce system.</p>
<pre><code>userData (userId, name, ...)
orderData (orderId, userId, orderType, createDate, ...)
</code></pre>
<p>For all users in the system, select their user information, their most recent order information with type = '1', and their most recent order information with type = '2'. I want to do this in one query. Here is an example result:</p>
<pre><code>(userId, name, ..., orderId1, orderType1, createDate1, ..., orderId2, orderType2, createDate2, ...)
(101, 'Bob', ..., 472, '1', '4/25/2008', ..., 382, '2', '3/2/2008', ...)
</code></pre>
|
[
{
"answer_id": 154272,
"author": "Patrick Desjardins",
"author_id": 13913,
"author_profile": "https://Stackoverflow.com/users/13913",
"pm_score": 0,
"selected": false,
"text": "<p>Their newest you mean all new in the current day? You can always check with your createDate and get all user and order data if the createDate >= current day.</p>\n\n<pre><code>SELECT * FROM\n\"orderData\", \"userData\"\nWHERE\n\"userData\".\"userId\" =\"orderData\".\"userId\"\nAND \"orderData\".createDate >= current_date;\n</code></pre>\n\n<p><strong>UPDATED</strong></p>\n\n<p>Here is what you want after your comment here:</p>\n\n<pre><code>SELECT * FROM\n\"orderData\", \"userData\"\nWHERE\n\"userData\".\"userId\" =\"orderData\".\"userId\"\nAND \"orderData\".type = '1'\nAND \"orderData\".\"orderId\" = (\nSELECT \"orderId\" FROM \"orderData\"\nWHERE \n\"orderType\" = '1'\nORDER \"orderId\" DESC\nLIMIT 1\n</code></pre>\n\n<p>)</p>\n"
},
{
"answer_id": 154300,
"author": "Kevin Lamb",
"author_id": 3149,
"author_profile": "https://Stackoverflow.com/users/3149",
"pm_score": 0,
"selected": false,
"text": "<p>You might be able to do a union query for this. The exact syntax needs some work, especially the group by section, but the union should be able to do it.</p>\n\n<p>For example:</p>\n\n<pre><code>SELECT orderId, orderType, createDate\nFROM orderData\nWHERE type=1 AND MAX(createDate)\nGROUP BY orderId, orderType, createDate\n\nUNION\n\nSELECT orderId, orderType, createDate\nFROM orderData\nWHERE type=2 AND MAX(createDate)\nGROUP BY orderId, orderType, createDate\n</code></pre>\n"
},
{
"answer_id": 154317,
"author": "hamishmcn",
"author_id": 3590,
"author_profile": "https://Stackoverflow.com/users/3590",
"pm_score": 1,
"selected": false,
"text": "<p>Sorry I don't have oracle in front of me, but this is the basic structure of what I would do in oracle: </p>\n\n<pre><code>SELECT b.user_id, b.orderid, b.orderType, b.createDate, <etc>,\n a.name\nFROM orderData b, userData a\nWHERE a.userid = b.userid\nAND (b.userid, b.orderType, b.createDate) IN (\n SELECT userid, orderType, max(createDate) \n FROM orderData \n WHERE orderType IN (1,2)\n GROUP BY userid, orderType) \n</code></pre>\n"
},
{
"answer_id": 154334,
"author": "Bartek Szabat",
"author_id": 23774,
"author_profile": "https://Stackoverflow.com/users/23774",
"pm_score": 1,
"selected": false,
"text": "<p>T-SQL sample solution (MS SQL):</p>\n\n<pre><code>SELECT\n u.*\n , o1.*\n , o2.* \nFROM\n(\n SELECT\n , userData.*\n , (SELECT TOP 1 orderId.url FROM orderData WHERE orderData.userId=userData.userId AND orderType=1 ORDER BY createDate DESC)\n AS order1Id\n , (SELECT TOP 1 orderId.url FROM orderData WHERE orderData.userId=userData.userId AND orderType=2 ORDER BY createDate DESC)\n AS order2Id\n FROM userData\n) AS u\nLEFT JOIN orderData o1 ON (u.order1Id=o1.orderId)\nLEFT JOIN orderData o2 ON (u.order2Id=o2.orderId)\n</code></pre>\n\n<p>In SQL 2005 you could also use RANK ( ) OVER function. (But AFAIK its completely MSSQL-specific feature)</p>\n"
},
{
"answer_id": 154336,
"author": "Javier",
"author_id": 11649,
"author_profile": "https://Stackoverflow.com/users/11649",
"pm_score": 0,
"selected": false,
"text": "<p>i use things like this in MySQL:</p>\n\n<pre><code>SELECT\n u.*,\n SUBSTRING_INDEX( MAX( CONCAT( o1.createDate, '##', o1.otherfield)), '##', -1) as o2_orderfield,\n SUBSTRING_INDEX( MAX( CONCAT( o2.createDate, '##', o2.otherfield)), '##', -1) as o2_orderfield\nFROM\n userData as u\n LEFT JOIN orderData AS o1 ON (o1.userId=u.userId AND o1.orderType=1)\n LEFT JOIN orderData AS o2 ON (o1.userId=u.userId AND o2.orderType=2)\nGROUP BY u.userId\n</code></pre>\n\n<p>In short, use MAX() to get the newest, by prepending the criteria field (createDate) to the interesting field(s) (otherfield). SUBSTRING_INDEX() then strips off the date.</p>\n\n<p>OTOH, if you need an arbitrary number of orders (if userType can be any number, and not a limited ENUM); it's better to handle with a separate query, something like this:</p>\n\n<pre><code>select * from orderData where userId=XXX order by orderType, date desc group by orderType\n</code></pre>\n\n<p>for each user.</p>\n"
},
{
"answer_id": 154366,
"author": "Cade Roux",
"author_id": 18255,
"author_profile": "https://Stackoverflow.com/users/18255",
"pm_score": 0,
"selected": false,
"text": "<p>Assuming orderId is monotonic increasing with time:</p>\n\n<pre><code>SELECT *\nFROM userData u\nINNER JOIN orderData o\n ON o.userId = u.userId\nINNER JOIN ( -- This subquery gives the last order of each type for each customer\n SELECT MAX(o2.orderId)\n --, o2.userId -- optional - include if joining for a particular customer\n --, o2.orderType -- optional - include if joining for a particular type\n FROM orderData o2\n GROUP BY o2.userId\n ,o2.orderType\n) AS LastOrders\n ON LastOrders.orderId = o.orderId -- expand join to include customer or type if desired\n</code></pre>\n\n<p>Then pivot at the client or if using SQL Server, there is a PIVOT functionality</p>\n"
},
{
"answer_id": 154433,
"author": "Steve K",
"author_id": 739,
"author_profile": "https://Stackoverflow.com/users/739",
"pm_score": 3,
"selected": true,
"text": "<p>This should work, you'll have to adjust the table / column names:</p>\n\n<pre><code>select ud.name,\n order1.order_id,\n order1.order_type,\n order1.create_date,\n order2.order_id,\n order2.order_type,\n order2.create_date\n from user_data ud,\n order_data order1,\n order_data order2\n where ud.user_id = order1.user_id\n and ud.user_id = order2.user_id\n and order1.order_id = (select max(order_id)\n from order_data od1\n where od1.user_id = ud.user_id\n and od1.order_type = 'Type1')\n and order2.order_id = (select max(order_id)\n from order_data od2\n where od2.user_id = ud.user_id\n and od2.order_type = 'Type2')\n</code></pre>\n\n<p>Denormalizing your data might also be a good idea. This type of thing will be fairly expensive to do. So you might add a <code>last_order_date</code> to your userData.</p>\n"
},
{
"answer_id": 154450,
"author": "hamishmcn",
"author_id": 3590,
"author_profile": "https://Stackoverflow.com/users/3590",
"pm_score": 0,
"selected": false,
"text": "<p>Here is one way to move the type 1 and 2 data on to the same row:<br>\n(by placing the type 1 and type 2 information into their own selects that then get used in the from clause.)</p>\n\n<pre><code>SELECT\n a.name, ud1.*, ud2.*\nFROM\n userData a,\n (SELECT user_id, orderid, orderType, reateDate, <etc>,\n FROM orderData b\n WHERE (userid, orderType, createDate) IN (\n SELECT userid, orderType, max(createDate) \n FROM orderData \n WHERE orderType = 1\n GROUP BY userid, orderType) ud1,\n (SELECT user_id, orderid, orderType, createDate, <etc>,\n FROM orderData \n WHERE (userid, orderType, createDate) IN (\n SELECT userid, orderType, max(createDate) \n FROM orderData \n WHERE orderType = 2\n GROUP BY userid, orderType) ud2\n</code></pre>\n"
},
{
"answer_id": 154486,
"author": "Bill Karwin",
"author_id": 20860,
"author_profile": "https://Stackoverflow.com/users/20860",
"pm_score": 0,
"selected": false,
"text": "<p>Here's how I do it. This is standard SQL and works in any brand of database.</p>\n\n<pre><code>SELECT u.userId, u.name, o1.orderId, o1.orderType, o1.createDate,\n o2.orderId, o2.orderType, o2.createDate\nFROM userData AS u\n LEFT OUTER JOIN (\n SELECT o1a.orderId, o1a.userId, o1a.orderType, o1a.createDate\n FROM orderData AS o1a \n LEFT OUTER JOIN orderData AS o1b ON (o1a.userId = o1b.userId \n AND o1a.orderType = o1b.orderType AND o1a.createDate < o1b.createDate)\n WHERE o1a.orderType = 1 AND o1b.orderId IS NULL) AS o1 ON (u.userId = o1.userId)\n LEFT OUTER JOIN (\n SELECT o2a.orderId, o2a.userId, o2a.orderType, o2a.createDate\n FROM orderData AS o2a \n LEFT OUTER JOIN orderData AS o2b ON (o2a.userId = o2b.userId \n AND o2a.orderType = o2b.orderType AND o2a.createDate < o2b.createDate)\n WHERE o2a.orderType = 2 AND o2b.orderId IS NULL) o2 ON (u.userId = o2.userId);\n</code></pre>\n\n<p>Note that if you have multiple orders of either type whose dates are equal to the latest date, you'll get multiple rows in the result set. If you have multiple orders of both types, you'll get N x M rows in the result set. So I would recommend that you fetch the rows of each type in separate queries.</p>\n"
},
{
"answer_id": 154548,
"author": "JavadocMD",
"author_id": 9304,
"author_profile": "https://Stackoverflow.com/users/9304",
"pm_score": 0,
"selected": false,
"text": "<p>Steve K is absolutely right, thanks! I did rewrite his answer a little to account for the fact that there might be no order for a particular type (which I failed to mention, so I can't fault Steve K.)</p>\n\n<p>Here's what I wound up using:</p>\n\n<pre><code>select ud.name,\n order1.orderId,\n order1.orderType,\n order1.createDate,\n order2.orderId,\n order2.orderType,\n order2.createDate\n from userData ud\n left join orderData order1\n on order1.orderId = (select max(orderId)\n from orderData od1\n where od1.userId = ud.userId\n and od1.orderType = '1')\n left join orderData order2\n on order2.orderId = (select max(orderId)\n from orderData od2\n where od2.userId = ud.userId\n and od2.orderType = '2')\n where ...[some limiting factors on the selection of users]...;\n</code></pre>\n"
},
{
"answer_id": 155282,
"author": "Mario",
"author_id": 472,
"author_profile": "https://Stackoverflow.com/users/472",
"pm_score": 2,
"selected": false,
"text": "<p>I have provided three different approaches for solving this problem:</p>\n\n<ol>\n<li>Using Pivots</li>\n<li>Using Case Statements</li>\n<li>Using inline queries in the where clause</li>\n</ol>\n\n<p>All of the solutions assume we are determining the \"most recent\" order based on the <code>orderId</code> column. Using the <code>createDate</code> column would add complexity due to timestamp collisions and seriously hinder performance since <code>createDate</code> is probably not part of the indexed key. I have only tested these queries using MS SQL Server 2005, so I have no idea if they will work on your server.</p>\n\n<p>Solutions (1) and (2) perform almost identically. In fact, they both result in the same number of reads from the database. </p>\n\n<p>Solution (3) is <strong>not</strong> the preferred approach when working with large data sets. It consistently makes hundreds of logical reads more than (1) and (2). When filtering for one specific user, approach (3) is comparable to the other methods. In the single user case, a drop in the cpu time helps to counter the significantly higher number of reads; however, as the disk drive becomes busier and cache misses occur, this slight advantage will disappear.</p>\n\n<h2>Conclusion</h2>\n\n<p>For the presented scenario, use the pivot approach if it is supported by your DBMS. It requires less code than the case statement and simplifies adding order types in the future.</p>\n\n<p>Please note, in some cases, PIVOT is not flexible enough and characteristic value functions using case statements are the way to go.</p>\n\n<h2>Code</h2>\n\n<p>Approach (1) using PIVOT:</p>\n\n<pre><code>select \n ud.userId, ud.fullname, \n od1.orderId as orderId1, od1.createDate as createDate1, od1.orderType as orderType1,\n od2.orderId as orderId2, od2.createDate as createDate2, od2.orderType as orderType2\n\nfrom userData ud\n inner join (\n select userId, [1] as typeOne, [2] as typeTwo\n from (select\n userId, orderType, orderId\n from orderData) as orders\n PIVOT\n (\n max(orderId)\n FOR orderType in ([1], [2])\n ) as LatestOrders) as LatestOrders on\n LatestOrders.userId = ud.userId \n inner join orderData od1 on\n od1.orderId = LatestOrders.typeOne\n inner join orderData od2 on\n od2.orderId = LatestOrders.typeTwo\n</code></pre>\n\n<p>Approach (2) using Case Statements:</p>\n\n<pre><code>select \n ud.userId, ud.fullname, \n od1.orderId as orderId1, od1.createDate as createDate1, od1.orderType as orderType1,\n od2.orderId as orderId2, od2.createDate as createDate2, od2.orderType as orderType2\n\nfrom userData ud \n -- assuming not all users will have orders use outer join\n inner join (\n select \n od.userId,\n -- can be null if no orders for type\n max (case when orderType = 1 \n then ORDERID\n else null\n end) as maxTypeOneOrderId,\n\n -- can be null if no orders for type\n max (case when orderType = 2\n then ORDERID \n else null\n end) as maxTypeTwoOrderId\n from orderData od\n group by userId) as maxOrderKeys on\n maxOrderKeys.userId = ud.userId\n inner join orderData od1 on\n od1.ORDERID = maxTypeTwoOrderId\n inner join orderData od2 on\n OD2.ORDERID = maxTypeTwoOrderId\n</code></pre>\n\n<p>Approach (3) using inline queries in the where clause (based on Steve K.'s response):</p>\n\n<pre><code>select ud.userId,ud.fullname, \n order1.orderId, order1.orderType, order1.createDate, \n order2.orderId, order2.orderType, order2.createDate\n from userData ud,\n orderData order1,\n orderData order2\n where ud.userId = order1.userId\n and ud.userId = order2.userId\n and order1.orderId = (select max(orderId)\n from orderData od1\n where od1.userId = ud.userId\n and od1.orderType = 1)\n and order2.orderId = (select max(orderId)\n from orderData od2\n where od2.userId = ud.userId\n and od2.orderType = 2)\n</code></pre>\n\n<p>Script to generate tables and 1000 users with 100 orders each:</p>\n\n<pre><code>CREATE TABLE [dbo].[orderData](\n [orderId] [int] IDENTITY(1,1) NOT NULL,\n [createDate] [datetime] NOT NULL,\n [orderType] [tinyint] NOT NULL, \n [userId] [int] NOT NULL\n) \n\nCREATE TABLE [dbo].[userData](\n [userId] [int] IDENTITY(1,1) NOT NULL,\n [fullname] [nvarchar](50) NOT NULL\n) \n\n-- Create 1000 users with 100 order each\ndeclare @userId int\ndeclare @usersAdded int\nset @usersAdded = 0\n\nwhile @usersAdded < 1000\nbegin\n insert into userData (fullname) values ('Mario' + ltrim(str(@usersAdded)))\n set @userId = @@identity\n\n declare @orderSetsAdded int\n set @orderSetsAdded = 0\n while @orderSetsAdded < 10\n begin\n insert into orderData (userId, createDate, orderType) \n values ( @userId, '01-06-08', 1)\n insert into orderData (userId, createDate, orderType) \n values ( @userId, '01-02-08', 1)\n insert into orderData (userId, createDate, orderType) \n values ( @userId, '01-08-08', 1)\n insert into orderData (userId, createDate, orderType) \n values ( @userId, '01-09-08', 1)\n insert into orderData (userId, createDate, orderType) \n values ( @userId, '01-01-08', 1)\n insert into orderData (userId, createDate, orderType) \n values ( @userId, '01-06-06', 2)\n insert into orderData (userId, createDate, orderType) \n values ( @userId, '01-02-02', 2)\n insert into orderData (userId, createDate, orderType) \n values ( @userId, '01-08-09', 2)\n insert into orderData (userId, createDate, orderType) \n values ( @userId, '01-09-01', 2)\n insert into orderData (userId, createDate, orderType) \n values ( @userId, '01-01-04', 2)\n\n set @orderSetsAdded = @orderSetsAdded + 1\n end\n set @usersAdded = @usersAdded + 1\nend\n</code></pre>\n\n<p>Small snippet for testing query performance on MS SQL Server in addition to SQL Profiler:</p>\n\n<pre><code>-- Uncomment these to clear some caches\n--DBCC DROPCLEANBUFFERS\n--DBCC FREEPROCCACHE\n\nset statistics io on\nset statistics time on\n\n-- INSERT TEST QUERY HERE\n\nset statistics time off\nset statistics io off\n</code></pre>\n"
}
] |
2008/09/30
|
[
"https://Stackoverflow.com/questions/154261",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9304/"
] |
I frequently run into problems of this form and haven't found a good solution yet:
Assume we have two database tables representing an e-commerce system.
```
userData (userId, name, ...)
orderData (orderId, userId, orderType, createDate, ...)
```
For all users in the system, select their user information, their most recent order information with type = '1', and their most recent order information with type = '2'. I want to do this in one query. Here is an example result:
```
(userId, name, ..., orderId1, orderType1, createDate1, ..., orderId2, orderType2, createDate2, ...)
(101, 'Bob', ..., 472, '1', '4/25/2008', ..., 382, '2', '3/2/2008', ...)
```
|
This should work, you'll have to adjust the table / column names:
```
select ud.name,
order1.order_id,
order1.order_type,
order1.create_date,
order2.order_id,
order2.order_type,
order2.create_date
from user_data ud,
order_data order1,
order_data order2
where ud.user_id = order1.user_id
and ud.user_id = order2.user_id
and order1.order_id = (select max(order_id)
from order_data od1
where od1.user_id = ud.user_id
and od1.order_type = 'Type1')
and order2.order_id = (select max(order_id)
from order_data od2
where od2.user_id = ud.user_id
and od2.order_type = 'Type2')
```
Denormalizing your data might also be a good idea. This type of thing will be fairly expensive to do. So you might add a `last_order_date` to your userData.
|
154,262 |
<p>It's very easy to mark an image file to become an embedded resource however how does one access the image thereafter. Please can I have some example code?</p>
|
[
{
"answer_id": 154271,
"author": "Franci Penov",
"author_id": 17028,
"author_profile": "https://Stackoverflow.com/users/17028",
"pm_score": 1,
"selected": false,
"text": "<p>Look at the third code snippet at <a href=\"http://msdn.microsoft.com/en-us/library/aa309403(VS.71).aspx\" rel=\"nofollow noreferrer\">http://msdn.microsoft.com/en-us/library/aa309403(VS.71).aspx</a></p>\n"
},
{
"answer_id": 154276,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 4,
"selected": false,
"text": "<p>The most direct method:</p>\n\n<pre><code>YourProjectsBaseNamespace.Properties.Resources.YourImageResourceName\n</code></pre>\n"
},
{
"answer_id": 154278,
"author": "Gulzar Nazim",
"author_id": 4337,
"author_profile": "https://Stackoverflow.com/users/4337",
"pm_score": 3,
"selected": false,
"text": "<p>1) <a href=\"http://msdn.microsoft.com/en-us/library/7k989cfy(VS.80).aspx\" rel=\"noreferrer\">Adding and Editing Resources (Visual C#)</a> </p>\n\n<pre><code>System.Drawing.Bitmap bitmap1 = myProject.Properties.Resources.Image01; \n</code></pre>\n\n<p>2) <a href=\"http://www.attilan.com/2006/08/accessing-embedded-resources-u.php\" rel=\"noreferrer\">Accessing Embedded Resources using GetManifestResourceStream</a></p>\n\n<pre><code>Assembly _assembly = Assembly.GetExecutingAssembly();\n\nStream _imageStream = \n _assembly.GetManifestResourceStream(\n \"ThumbnailPictureViewer.resources.Image1.bmp\");\nBitmap theDefaultImage = new Bitmap(_imageStream);\n</code></pre>\n"
},
{
"answer_id": 154285,
"author": "Leahn Novash",
"author_id": 5954,
"author_profile": "https://Stackoverflow.com/users/5954",
"pm_score": 0,
"selected": false,
"text": "<pre><code>//Get the names of the embedded resource files;\n\nList<string> resources = new List<string>(AssemblyBuilder.GetExecutingAssembly().GetManifestResourceNames());\n\n//Get the stream\n\nStreamReader sr = new StreamReader(\n AssemblyBuilder.GetExecutingAssembly().GetManifestResourceStream(\n resources.Find(target => target.ToLower().Contains(\"insert name here\"))\n</code></pre>\n\n<p>You can convert from bitmap from the stream. The Bitmap class has a method that does this. LoadFromStream if my memory serves.</p>\n"
},
{
"answer_id": 68335887,
"author": "Andrei15193",
"author_id": 2788501,
"author_profile": "https://Stackoverflow.com/users/2788501",
"pm_score": 0,
"selected": false,
"text": "<p>You can try using <a href=\"https://www.nuget.org/packages/EmbeddedResourceBrowser/\" rel=\"nofollow noreferrer\">https://www.nuget.org/packages/EmbeddedResourceBrowser/</a> library, there are code samples on the project page (<a href=\"https://andrei15193.github.io/EmbeddedResourceBrowser/\" rel=\"nofollow noreferrer\">https://andrei15193.github.io/EmbeddedResourceBrowser/</a>). It's just to help access embedded resources in .NET applications. You can get a <code>Stream</code> to read the contents, it makes browsing resources a lot more easier.</p>\n"
}
] |
2008/09/30
|
[
"https://Stackoverflow.com/questions/154262",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/22284/"
] |
It's very easy to mark an image file to become an embedded resource however how does one access the image thereafter. Please can I have some example code?
|
The most direct method:
```
YourProjectsBaseNamespace.Properties.Resources.YourImageResourceName
```
|
154,295 |
<p>In the latest MVC preview, I'm using this route for a legacy URL:</p>
<pre><code>routes.MapRoute(
"Legacy-Firefox", // Route name
"Firefox-Extension/", // URL with parameters
new { controller = "Home", action = "Firefox", id = "" } // Parameter defaults
);
</code></pre>
<p>The problem is that both of these URL's work:
<a href="http://example.com/Firefox-Extension" rel="nofollow noreferrer">http://example.com/Firefox-Extension</a>
<a href="http://example.com/Firefox-Extension/" rel="nofollow noreferrer">http://example.com/Firefox-Extension/</a></p>
<p>I only want the second to work (for SEO). Also, when I create a link to that page, the routing engine gives me back a URL without a trailing slash.</p>
<p>This is the code I'm using to generate the link:</p>
<pre><code><%= Html.ActionLink("Firefox Extension", "Firefox", "Home")%>
</code></pre>
<p>I believe can fix the first problem by using an HTTP handler to do a 301 redirect to the URL with the trailing slash. However, I want to link to the URL with the trailing slash, and I'm hoping to not have to hard-code the version with the slash.</p>
<p>Anyone know how to force the route to use a trailing slash?</p>
|
[
{
"answer_id": 274431,
"author": "Armstrongest",
"author_id": 26931,
"author_profile": "https://Stackoverflow.com/users/26931",
"pm_score": 2,
"selected": false,
"text": "<p>When you write your links, you should always include the final slash. I don't know if this applies to the mvc framework (or URL Routing in general), but I know that for static resources, if you don't put the slash in you add a slight overhead as the request gets done twice. </p>\n\n<p>The slash immediately identifies the url as pointing to a directory. No need to parse files.</p>\n\n<p>Again, I don't believe this applies when you use URL routing, but I haven't looked into it.</p>\n\n<p>Check <a href=\"http://dmiessler.com/study/hyperlink_trailing_slash/\" rel=\"nofollow noreferrer\">HERE for an article about the trailing slash</a></p>\n\n<p>edit:\nUpon thinking about this... I think it's probably better to leave off the slash, instead of trying to include it. When you're using url routing, you're using the URL to route directly to a resource. As opposed to pointing to a directory with an index.html or default.aspx, you're pointing to a specific file.</p>\n\n<p>I know the difference is subtle, but it may be better to stick to the non-slash for Routed Urls, rather than fight with the framework.</p>\n\n<p>Use a trailing slash strictly when you're actually pointing to a directory. Thought I guess you could just append a slash to the end every time if you really didn't like it.</p>\n"
},
{
"answer_id": 955620,
"author": "Murad X",
"author_id": 68294,
"author_profile": "https://Stackoverflow.com/users/68294",
"pm_score": 2,
"selected": false,
"text": "<p>If you have a wrapper over RouteLink than there is an easy solution of the problem.\nFor example, I had a wrapper method RouteLinkEx:</p>\n\n<pre><code>public static string RouteLinkEx(this HtmlHelper helper,string text,string routeName,RouteValueDictionary rvd,object htmlAttributes)\n {\n\n UrlHelper uh = new UrlHelper(helper.ViewContext.RequestContext,helper.RouteCollection);\n // Add trailing slash to the url of the link\n string url = uh.RouteUrl(routeName,rvd) + \"/\";\n TagBuilder builder = new TagBuilder(\"a\")\n {\n InnerHtml = !string.IsNullOrEmpty(text) ? HttpUtility.HtmlEncode(text) : string.Empty\n };\n builder.MergeAttributes(new RouteValueDictionary(htmlAttributes));\n builder.MergeAttribute(\"href\",url);\n return builder.ToString(TagRenderMode.Normal);\n //--- \n }\n</code></pre>\n\n<p>As you see I used parameters to generate URL first. Then I added \"/\" at the end of the URL. and then I generated complete link using those URL.</p>\n"
},
{
"answer_id": 2174618,
"author": "Sky",
"author_id": 263223,
"author_profile": "https://Stackoverflow.com/users/263223",
"pm_score": 1,
"selected": false,
"text": "<p>Here a overload for RouteLinkEx(HtmlHelper, string,string, object)</p>\n\n<pre><code> public static string RouteLinkEx(this HtmlHelper helper, string text, string routeName, object routeValues)\n {\n\n UrlHelper uh = new UrlHelper(helper.ViewContext.RequestContext);\n\n // Add trailing slash to the url of the link \n string url = uh.RouteUrl(routeName, routeValues) + \"/\";\n TagBuilder builder = new TagBuilder(\"a\")\n {\n InnerHtml = !string.IsNullOrEmpty(text) ? HttpUtility.HtmlEncode(text) : string.Empty\n };\n //builder.MergeAttributes(new RouteValueDictionary(htmlAttributes));\n builder.MergeAttribute(\"href\", url);\n return builder.ToString(TagRenderMode.Normal);\n //--- \n }\n</code></pre>\n"
},
{
"answer_id": 2781256,
"author": "Michael Maddox",
"author_id": 12712,
"author_profile": "https://Stackoverflow.com/users/12712",
"pm_score": 2,
"selected": false,
"text": "<p>I happened across this blog post:</p>\n\n<p><a href=\"http://www.ytechie.com/2008/10/aspnet-mvc-what-about-seo.html\" rel=\"nofollow noreferrer\">http://www.ytechie.com/2008/10/aspnet-mvc-what-about-seo.html</a></p>\n\n<p>this morning before running into this question on StackOverflow. That blog post (from the author of this question) has a trackback to this blog post from Scott Hanselman with an answer to this question:</p>\n\n<p><a href=\"http://www.hanselman.com/blog/ASPNETMVCAndTheNewIIS7RewriteModule.aspx\" rel=\"nofollow noreferrer\">http://www.hanselman.com/blog/ASPNETMVCAndTheNewIIS7RewriteModule.aspx</a></p>\n\n<p>I was surprised to find no link from here to there yet, so I just added it. :)</p>\n\n<p>Scott's answer suggests using URL Rewriting.</p>\n"
},
{
"answer_id": 3544941,
"author": "Sergey",
"author_id": 65214,
"author_profile": "https://Stackoverflow.com/users/65214",
"pm_score": 1,
"selected": false,
"text": "<p>Here is my version for ASP.NET MVC 2</p>\n\n<pre><code> public static MvcHtmlString RouteLinkEx(this HtmlHelper helper, string text, RouteValueDictionary routeValues)\n {\n return RouteLinkEx(helper, text, null, routeValues, null);\n }\n\n public static MvcHtmlString RouteLinkEx(this HtmlHelper htmlHelper, string text, string routeName, RouteValueDictionary routeValues, object htmlAttributes)\n {\n string url = UrlHelper.GenerateUrl(routeName, null, null, null, null, null, routeValues, htmlHelper.RouteCollection, htmlHelper.ViewContext.RequestContext, false);\n\n var builder = new TagBuilder(\"a\")\n {\n InnerHtml = !string.IsNullOrEmpty(text) ? HttpUtility.HtmlEncode(text) : string.Empty\n };\n builder.MergeAttributes(new RouteValueDictionary(htmlAttributes));\n // Add trailing slash to the url of the link\n builder.MergeAttribute(\"href\", url + \"/\");\n return MvcHtmlString.Create(builder.ToString(TagRenderMode.Normal));\n }\n</code></pre>\n"
},
{
"answer_id": 28395395,
"author": "DavidJBerman",
"author_id": 231304,
"author_profile": "https://Stackoverflow.com/users/231304",
"pm_score": 1,
"selected": false,
"text": "<p>I think you are solving the problem from the wrong angle. The reason given for wanting to force the single url is for SEO. I believe this refers to getting a duplicate content penalty because search engines consider this two URLs with the same content.</p>\n\n<p>Another solution to this problem then is to add a CANONICAL tag to your page which tells the search engines which is the \"official\" url for the page. Once you do that you no longer need to force the URLs and search engines will not penalize you and will route search results to your official url.</p>\n\n<p><a href=\"https://support.google.com/webmasters/answer/139066?hl=en\" rel=\"nofollow\">https://support.google.com/webmasters/answer/139066?hl=en</a></p>\n"
},
{
"answer_id": 31582416,
"author": "Muhammad Rehan Saeed",
"author_id": 1212017,
"author_profile": "https://Stackoverflow.com/users/1212017",
"pm_score": 2,
"selected": false,
"text": "<p>MVC 5 and 6 has the option of generating lower case URL's for your routes. My route config is shown below: </p>\n\n<pre><code>public static class RouteConfig\n{\n public static void RegisterRoutes(RouteCollection routes)\n {\n // Imprive SEO by stopping duplicate URL's due to case or trailing slashes.\n routes.AppendTrailingSlash = true;\n routes.LowercaseUrls = true;\n\n routes.IgnoreRoute(\"{resource}.axd/{*pathInfo}\");\n\n routes.MapRoute(\n name: \"Default\",\n url: \"{controller}/{action}/{id}\",\n defaults: new { controller = \"Home\", action = \"Index\", id = UrlParameter.Optional });\n }\n}\n</code></pre>\n\n<p>With this code, you should no longer need the canonicalize the URL's as this is done for you. One problem that can occur if you are using HTTP and HTTPS URL's and want a canonical URL for this. In this case, it's pretty easy to use the above approaches and replace HTTP with HTTPS or vice versa. </p>\n\n<p>Another problem is external websites that link to your site may omit the trailing slash or add upper-case characters and for this you should perform a 301 permanent redirect to the correct URL with the trailing slash. For full usage and source code, refer to my <a href=\"http://rehansaeed.com/canonical-urls-for-asp-net-mvc/\" rel=\"nofollow\">blog post</a> and the <code>RedirectToCanonicalUrlAttribute</code> filter:</p>\n\n<pre><code>/// <summary>\n/// To improve Search Engine Optimization SEO, there should only be a single URL for each resource. Case \n/// differences and/or URL's with/without trailing slashes are treated as different URL's by search engines. This \n/// filter redirects all non-canonical URL's based on the settings specified to their canonical equivalent. \n/// Note: Non-canonical URL's are not generated by this site template, it is usually external sites which are \n/// linking to your site but have changed the URL case or added/removed trailing slashes.\n/// (See Google's comments at http://googlewebmastercentral.blogspot.co.uk/2010/04/to-slash-or-not-to-slash.html\n/// and Bing's at http://blogs.bing.com/webmaster/2012/01/26/moving-content-think-301-not-relcanonical).\n/// </summary>\n[AttributeUsage(AttributeTargets.Method | AttributeTargets.Class, Inherited = true, AllowMultiple = false)]\npublic class RedirectToCanonicalUrlAttribute : FilterAttribute, IAuthorizationFilter\n{\n private readonly bool appendTrailingSlash;\n private readonly bool lowercaseUrls;\n\n #region Constructors\n\n /// <summary>\n /// Initializes a new instance of the <see cref=\"RedirectToCanonicalUrlAttribute\" /> class.\n /// </summary>\n /// <param name=\"appendTrailingSlash\">If set to <c>true</c> append trailing slashes, otherwise strip trailing \n /// slashes.</param>\n /// <param name=\"lowercaseUrls\">If set to <c>true</c> lower-case all URL's.</param>\n public RedirectToCanonicalUrlAttribute(\n bool appendTrailingSlash, \n bool lowercaseUrls)\n {\n this.appendTrailingSlash = appendTrailingSlash;\n this.lowercaseUrls = lowercaseUrls;\n } \n\n #endregion\n\n #region Public Methods\n\n /// <summary>\n /// Determines whether the HTTP request contains a non-canonical URL using <see cref=\"TryGetCanonicalUrl\"/>, \n /// if it doesn't calls the <see cref=\"HandleNonCanonicalRequest\"/> method.\n /// </summary>\n /// <param name=\"filterContext\">An object that encapsulates information that is required in order to use the \n /// <see cref=\"RedirectToCanonicalUrlAttribute\"/> attribute.</param>\n /// <exception cref=\"ArgumentNullException\">The <paramref name=\"filterContext\"/> parameter is <c>null</c>.</exception>\n public virtual void OnAuthorization(AuthorizationContext filterContext)\n {\n if (filterContext == null)\n {\n throw new ArgumentNullException(\"filterContext\");\n }\n\n if (string.Equals(filterContext.HttpContext.Request.HttpMethod, \"GET\", StringComparison.Ordinal))\n {\n string canonicalUrl;\n if (!this.TryGetCanonicalUrl(filterContext, out canonicalUrl))\n {\n this.HandleNonCanonicalRequest(filterContext, canonicalUrl);\n }\n }\n }\n\n #endregion\n\n #region Protected Methods\n\n /// <summary>\n /// Determines whether the specified URl is canonical and if it is not, outputs the canonical URL.\n /// </summary>\n /// <param name=\"filterContext\">An object that encapsulates information that is required in order to use the \n /// <see cref=\"RedirectToCanonicalUrlAttribute\" /> attribute.</param>\n /// <param name=\"canonicalUrl\">The canonical URL.</param>\n /// <returns><c>true</c> if the URL is canonical, otherwise <c>false</c>.</returns>\n protected virtual bool TryGetCanonicalUrl(AuthorizationContext filterContext, out string canonicalUrl)\n {\n bool isCanonical = true;\n\n canonicalUrl = filterContext.HttpContext.Request.Url.ToString();\n int queryIndex = canonicalUrl.IndexOf(QueryCharacter);\n\n if (queryIndex == -1)\n {\n bool hasTrailingSlash = canonicalUrl[canonicalUrl.Length - 1] == SlashCharacter;\n\n if (this.appendTrailingSlash)\n {\n // Append a trailing slash to the end of the URL.\n if (!hasTrailingSlash)\n {\n canonicalUrl += SlashCharacter;\n isCanonical = false;\n }\n }\n else\n {\n // Trim a trailing slash from the end of the URL.\n if (hasTrailingSlash)\n {\n canonicalUrl = canonicalUrl.TrimEnd(SlashCharacter);\n isCanonical = false;\n }\n }\n }\n else\n {\n bool hasTrailingSlash = canonicalUrl[queryIndex - 1] == SlashCharacter;\n\n if (this.appendTrailingSlash)\n {\n // Append a trailing slash to the end of the URL but before the query string.\n if (!hasTrailingSlash)\n {\n canonicalUrl = canonicalUrl.Insert(queryIndex, SlashCharacter.ToString());\n isCanonical = false;\n }\n }\n else\n {\n // Trim a trailing slash to the end of the URL but before the query string.\n if (hasTrailingSlash)\n {\n canonicalUrl = canonicalUrl.Remove(queryIndex - 1, 1);\n isCanonical = false;\n }\n }\n }\n\n if (this.lowercaseUrls)\n {\n foreach (char character in canonicalUrl)\n {\n if (char.IsUpper(character))\n {\n canonicalUrl = canonicalUrl.ToLower();\n isCanonical = false;\n break;\n }\n }\n }\n\n return isCanonical;\n }\n\n /// <summary>\n /// Handles HTTP requests for URL's that are not canonical. Performs a 301 Permanent Redirect to the canonical URL.\n /// </summary>\n /// <param name=\"filterContext\">An object that encapsulates information that is required in order to use the \n /// <see cref=\"RedirectToCanonicalUrlAttribute\" /> attribute.</param>\n /// <param name=\"canonicalUrl\">The canonical URL.</param>\n protected virtual void HandleNonCanonicalRequest(AuthorizationContext filterContext, string canonicalUrl)\n {\n filterContext.Result = new RedirectResult(canonicalUrl, true);\n }\n\n #endregion\n}\n</code></pre>\n\n<p>Usage example to ensure all requests are 301 redirected to the correct canonical URL:</p>\n\n<pre><code>filters.Add(new RedirectToCanonicalUrlAttribute(\n RouteTable.Routes.AppendTrailingSlash, \n RouteTable.Routes.LowercaseUrls));\n</code></pre>\n"
}
] |
2008/09/30
|
[
"https://Stackoverflow.com/questions/154295",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/23837/"
] |
In the latest MVC preview, I'm using this route for a legacy URL:
```
routes.MapRoute(
"Legacy-Firefox", // Route name
"Firefox-Extension/", // URL with parameters
new { controller = "Home", action = "Firefox", id = "" } // Parameter defaults
);
```
The problem is that both of these URL's work:
<http://example.com/Firefox-Extension>
<http://example.com/Firefox-Extension/>
I only want the second to work (for SEO). Also, when I create a link to that page, the routing engine gives me back a URL without a trailing slash.
This is the code I'm using to generate the link:
```
<%= Html.ActionLink("Firefox Extension", "Firefox", "Home")%>
```
I believe can fix the first problem by using an HTTP handler to do a 301 redirect to the URL with the trailing slash. However, I want to link to the URL with the trailing slash, and I'm hoping to not have to hard-code the version with the slash.
Anyone know how to force the route to use a trailing slash?
|
When you write your links, you should always include the final slash. I don't know if this applies to the mvc framework (or URL Routing in general), but I know that for static resources, if you don't put the slash in you add a slight overhead as the request gets done twice.
The slash immediately identifies the url as pointing to a directory. No need to parse files.
Again, I don't believe this applies when you use URL routing, but I haven't looked into it.
Check [HERE for an article about the trailing slash](http://dmiessler.com/study/hyperlink_trailing_slash/)
edit:
Upon thinking about this... I think it's probably better to leave off the slash, instead of trying to include it. When you're using url routing, you're using the URL to route directly to a resource. As opposed to pointing to a directory with an index.html or default.aspx, you're pointing to a specific file.
I know the difference is subtle, but it may be better to stick to the non-slash for Routed Urls, rather than fight with the framework.
Use a trailing slash strictly when you're actually pointing to a directory. Thought I guess you could just append a slash to the end every time if you really didn't like it.
|
154,299 |
<p>I am debugging a VB6 executable. The executable loads dlls and files from it's current directory, when running. When run in debugger, the current directory seems to be VB6's dir. </p>
<p>How do I set working directory for VB6?</p>
|
[
{
"answer_id": 154327,
"author": "Gulzar Nazim",
"author_id": 4337,
"author_profile": "https://Stackoverflow.com/users/4337",
"pm_score": 2,
"selected": false,
"text": "<p><a href=\"http://sintaks.blogspot.com/2006/07/vb6-set-current-working-directory.html\" rel=\"nofollow noreferrer\">Will this work?</a></p>\n\n<pre><code>'Declaration\nPrivate Declare Function SetCurrentDirectory Lib \"kernel32\" _\nAlias \"SetCurrentDirectoryA\" (ByVal lpPathName As String) As Long\n\n'syntax to set current dir\nSetCurrentDirectory App.Path\n</code></pre>\n"
},
{
"answer_id": 154343,
"author": "Pascal Paradis",
"author_id": 1291,
"author_profile": "https://Stackoverflow.com/users/1291",
"pm_score": 5,
"selected": true,
"text": "<p>It doesn't seems to be a \"out of the box\" solution for this thing.</p>\n\n<p>Taken from <a href=\"http://discuss.fogcreek.com/joelonsoftware1/default.asp?cmd=show&ixPost=19026&ixReplies=5\" rel=\"noreferrer\">The Old Joel On Software Forums</a> </p>\n\n<blockquote>\n <p>Anyways.. to put this topic to rest..\n the following was my VB6 solution: I\n define 2 symbols in my VB project\n \"MPDEBUG\" and \"MPRELEASE\" and call the\n following function as the first\n operation in my apps entry point\n function.</p>\n</blockquote>\n\n<pre><code>Public Sub ChangeDirToApp()\n#If MPDEBUG = 0 And MPRELEASE = 1 Then\n ' assume that in final release builds the current dir will be the location\n ' of where the .exe was installed; paths are relative to the install dir\n ChDrive App.path\n ChDir App.path\n#Else\n ' in all debug/IDE related builds, we need to switch to the \"bin\" dir\n ChDrive App.path\n ChDir App.path & BackSlash(App.path) & \"..\\bin\"\n#End If\nEnd Sub\n</code></pre>\n"
},
{
"answer_id": 154572,
"author": "Kris Erickson",
"author_id": 3798,
"author_profile": "https://Stackoverflow.com/users/3798",
"pm_score": 3,
"selected": false,
"text": "<p>Solution that I have found that works uses a <code>Sub Main</code>, and checks if the program is running in the IDE.</p>\n\n<pre><code>Dim gISIDE as Boolean\n\nSub Main()\n If IsIDE Then\n ChDrive App.Path\n ChDir App.Path\n End If\n\n ' The rest of the code goes here...\n\nEnd Sub\n\nPublic Function IsIDE() As Boolean '\n IsIDE = False\n 'This line is only executed if running in the IDE and then returns True\n Debug.Assert CheckIDE \n If gISIDE Then \n IsIDE = True\n End If\nEnd Function\n\nPrivate Function CheckIDE() As Boolean ' this is a helper function for Public Function IsIDE() \n gISIDE = True 'set global flag \n CheckIDE = True \nEnd Function\n</code></pre>\n"
},
{
"answer_id": 154595,
"author": "GSerg",
"author_id": 11683,
"author_profile": "https://Stackoverflow.com/users/11683",
"pm_score": 3,
"selected": false,
"text": "<p>\"The current directory seems to be VB6's dir\" only when you open a project using File-Open.</p>\n\n<p>Open it by double clicking the .vbp file while having the IDE closed.</p>\n"
},
{
"answer_id": 164037,
"author": "Kaniu",
"author_id": 3236,
"author_profile": "https://Stackoverflow.com/users/3236",
"pm_score": 1,
"selected": false,
"text": "<p>Current directory for any program - including vb6 - can be changed in the properties of the shortcut. I've changed it to the root of my source tree, it makes using File-Open quicker.</p>\n"
}
] |
2008/09/30
|
[
"https://Stackoverflow.com/questions/154299",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/814/"
] |
I am debugging a VB6 executable. The executable loads dlls and files from it's current directory, when running. When run in debugger, the current directory seems to be VB6's dir.
How do I set working directory for VB6?
|
It doesn't seems to be a "out of the box" solution for this thing.
Taken from [The Old Joel On Software Forums](http://discuss.fogcreek.com/joelonsoftware1/default.asp?cmd=show&ixPost=19026&ixReplies=5)
>
> Anyways.. to put this topic to rest..
> the following was my VB6 solution: I
> define 2 symbols in my VB project
> "MPDEBUG" and "MPRELEASE" and call the
> following function as the first
> operation in my apps entry point
> function.
>
>
>
```
Public Sub ChangeDirToApp()
#If MPDEBUG = 0 And MPRELEASE = 1 Then
' assume that in final release builds the current dir will be the location
' of where the .exe was installed; paths are relative to the install dir
ChDrive App.path
ChDir App.path
#Else
' in all debug/IDE related builds, we need to switch to the "bin" dir
ChDrive App.path
ChDir App.path & BackSlash(App.path) & "..\bin"
#End If
End Sub
```
|
154,305 |
<p>Given the following canvas:</p>
<pre><code><Canvas>
<Canvas.LayoutTransform>
<ScaleTransform ScaleX="1" ScaleY="1" CenterX=".5" CenterY=".5" />
</Canvas.LayoutTransform>
<Button x:Name="scaleButton" Content="Scale Me" Canvas.Top="10" Canvas.Left="10" />
<Button x:Name="dontScaleButton" Content="DON'T Scale Me" Canvas.Top="10" Canvas.Left="50" />
</Canvas>
</code></pre>
<p>Is it possible to scale 1 button, but not the other when ScaleX and ScaleY changes?</p>
|
[
{
"answer_id": 154380,
"author": "Franci Penov",
"author_id": 17028,
"author_profile": "https://Stackoverflow.com/users/17028",
"pm_score": 4,
"selected": true,
"text": "<p>Not in XAML. You can do this in code by building the reverse transform and applying it to the object you don't want transformed.</p>\n\n<p>If you want to go fancy, you can build a dependency property that you can attach in XAML to any object you don't want to be transformed by any parent transforms. This dependency property will take the transform of the parent, build a reverse transform and apply it to the object it's attached to.</p>\n"
},
{
"answer_id": 154500,
"author": "Joel B Fant",
"author_id": 22211,
"author_profile": "https://Stackoverflow.com/users/22211",
"pm_score": 2,
"selected": false,
"text": "<p>You could also restructure the elements so that the elements you don't want to scale with the <code>Canvas</code> are not actually children of that <code>Canvas</code>.</p>\n\n<pre><code><Canvas>\n <Canvas>\n <Canvas.LayoutTransform>\n <ScaleTransform ScaleX=\"1\" ScaleY=\"1\" CenterX=\".5\" CenterY=\".5\" />\n </Canvas.LayoutTransform>\n <Button x:Name=\"scaleButton\" Content=\"Scale Me\" Canvas.Top=\"10\" Canvas.Left=\"10\" />\n </Canvas>\n <Button x:Name=\"dontScaleButton\" Content=\"DON'T Scale Me\" Canvas.Top=\"10\" Canvas.Left=\"50\" />\n</Canvas>\n</code></pre>\n"
},
{
"answer_id": 5671474,
"author": "H.B.",
"author_id": 546730,
"author_profile": "https://Stackoverflow.com/users/546730",
"pm_score": 3,
"selected": false,
"text": "<p>Not sure if this was impossible when you asked the question but i would approach it like this:</p>\n\n<pre><code><Button x:Name=\"dontScaleButton\" Content=\"DON'T Scale Me\" Canvas.Top=\"10\" Canvas.Left=\"50\"\n LayoutTransform=\"{Binding LayoutTransform.Inverse,\n RelativeSource={RelativeSource AncestorType=Canvas}}\"/>\n</code></pre>\n\n<p>The original transform still seems to have a translative effect on the button though.</p>\n"
}
] |
2008/09/30
|
[
"https://Stackoverflow.com/questions/154305",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4580/"
] |
Given the following canvas:
```
<Canvas>
<Canvas.LayoutTransform>
<ScaleTransform ScaleX="1" ScaleY="1" CenterX=".5" CenterY=".5" />
</Canvas.LayoutTransform>
<Button x:Name="scaleButton" Content="Scale Me" Canvas.Top="10" Canvas.Left="10" />
<Button x:Name="dontScaleButton" Content="DON'T Scale Me" Canvas.Top="10" Canvas.Left="50" />
</Canvas>
```
Is it possible to scale 1 button, but not the other when ScaleX and ScaleY changes?
|
Not in XAML. You can do this in code by building the reverse transform and applying it to the object you don't want transformed.
If you want to go fancy, you can build a dependency property that you can attach in XAML to any object you don't want to be transformed by any parent transforms. This dependency property will take the transform of the parent, build a reverse transform and apply it to the object it's attached to.
|
154,307 |
<p>I just saw this behaviour and I'm a bit surprised by it...</p>
<p>If I add 3 or 4 elements to a Dictionary, and then do a "For Each" to get all the keys, they appear in the same order I added them.</p>
<p>The reason this surprises me is that a Dictionary is supposed to be a HashTable internally, so I expected things to come out in ANY order (ordered by the hash of the key, right?)</p>
<p>What am I missing here?
Is this a behaviour I can count on?</p>
<p>EDIT: OK, I thought already of many of the reasons why this <em>might</em> happen (like the separate list to entries, whether this is a coincidence, etc).
My question is, does anyone <strong>know</strong> how this really works?</p>
|
[
{
"answer_id": 154313,
"author": "Brad Wilson",
"author_id": 1554,
"author_profile": "https://Stackoverflow.com/users/1554",
"pm_score": 3,
"selected": false,
"text": "<p>A dictionary retrieves items in hashed order. The fact that they came out in insertion order was a total coincidence.</p>\n\n<p>The MSDN documentation says:</p>\n\n<blockquote>\n <p>The order of the keys in the KeyCollection is unspecified, but it is the same order as the associated values in the ValueCollection returned by the Values property.</p>\n</blockquote>\n"
},
{
"answer_id": 154321,
"author": "rslite",
"author_id": 15682,
"author_profile": "https://Stackoverflow.com/users/15682",
"pm_score": 0,
"selected": false,
"text": "<p>From what I know this shouldn't be a behavior to rely on. To check it quickly use the same elements and change the order in which you add them to the dictionary. You'll see if you get them back in the order they were added, or it was just a coincidence.</p>\n"
},
{
"answer_id": 154328,
"author": "Atanas Korchev",
"author_id": 10141,
"author_profile": "https://Stackoverflow.com/users/10141",
"pm_score": 1,
"selected": false,
"text": "<p>A quote from <a href=\"http://msdn.microsoft.com/en-us/library/3fcwy8h6.aspx\" rel=\"nofollow noreferrer\">MSDN</a> :</p>\n\n<blockquote>\n <p>The order of the keys in the\n Dictionary<(Of <(TKey,\n TValue>)>).KeyCollection is\n unspecified, but it is the same order\n as the associated values in the\n Dictionary<(Of <(TKey,\n TValue>)>).ValueCollection\n returned by the Dictionary<(Of <(TKey,\n TValue>)>).Values property.</p>\n</blockquote>\n"
},
{
"answer_id": 154333,
"author": "Lasse V. Karlsen",
"author_id": 267,
"author_profile": "https://Stackoverflow.com/users/267",
"pm_score": 1,
"selected": false,
"text": "<p>What keys did you add with in your test, and in what order?</p>\n"
},
{
"answer_id": 154345,
"author": "Eric",
"author_id": 4540,
"author_profile": "https://Stackoverflow.com/users/4540",
"pm_score": 3,
"selected": false,
"text": "<p>You cannot count on this behavior, but it's not surprising.</p>\n\n<p>Consider how you would implement key iteration for a simple hash table. You would need to iterate over all the hash buckets, whether or not they had anything in them. Getting a small data set from a big hashtable could be inefficient.</p>\n\n<p>Therefore it might be a good optimization to keep a separate, duplicate list of keys. Using a double-linked list you still get constant-time insert/delete. (You would keep a pointer from the hashtable bucket back to this list.) That way iterating through the list of keys depends only on the number of entries, not on the number of buckets.</p>\n"
},
{
"answer_id": 154357,
"author": "dguaraglia",
"author_id": 2384,
"author_profile": "https://Stackoverflow.com/users/2384",
"pm_score": 2,
"selected": false,
"text": "<p>I think this comes from the old .NET 1.1 times where you had two kinds of dictionaries \"ListDictionary\" and \"HybridDictionary\". <a href=\"http://msdn.microsoft.com/en-us/library/system.collections.specialized.listdictionary.aspx\" rel=\"nofollow noreferrer\">ListDictionary</a> was a dictionary implemented internally as an ordered list and was recommended for \"small sets of entries\". Then you had <a href=\"http://msdn.microsoft.com/en-us/library/system.collections.specialized.hybriddictionary.aspx\" rel=\"nofollow noreferrer\">HybridDictionary</a>, that was initially organized internally as a list, but if it grew bigger than a configurable threshold would become a hash table. This was done because historically proper hash-based dictionaries were considered expensive. Now a days that doesn't make much sense, but I suppose .NET just based it's new Dictionary generic class on the old HybridDictionary.</p>\n\n<p><strong>Note</strong>: Anyway, as someone else already pointed out, you should <em>never</em> count on the dictionary order for anything</p>\n"
},
{
"answer_id": 154473,
"author": "Laplie Anderson",
"author_id": 14204,
"author_profile": "https://Stackoverflow.com/users/14204",
"pm_score": 1,
"selected": false,
"text": "<p>Your entries might all be in the same hash bucket in the dictionary. Each bucket is probably a list of entries in the bucket. This would explain the entries coming back in order. </p>\n"
},
{
"answer_id": 354491,
"author": "Zan Lynx",
"author_id": 13422,
"author_profile": "https://Stackoverflow.com/users/13422",
"pm_score": 0,
"selected": false,
"text": "<p>Up to a certain list size it is cheaper to just check every entry instead of hashing. That is probably what is happening.</p>\n\n<p>Add 100 or 1000 items and see if they are still in the same order.</p>\n"
},
{
"answer_id": 825240,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": -1,
"selected": false,
"text": "<p>The question and many of the answers seem to misunderstand the purpose of a hashtable or dictionary. These data structures have no specified behaviors with respect to the enumeration of the values (or in fact the keys) of the items contained in the data structure. </p>\n\n<p>The purpose of a dictionary or hashtable is to be able to efficiently lookup a specific value given a known key. The internal implementation of any dictionary or hashtable should provide for this efficiency in lookups but need not provide any specific behavior with respect to enumerations or \"for each\" type iterations on the values or keys. </p>\n\n<p>In short, the internal data structure can store and enumerate these values in any manner that it wishes, including the order that they were inserted.</p>\n"
},
{
"answer_id": 976871,
"author": "Dolphin",
"author_id": 110672,
"author_profile": "https://Stackoverflow.com/users/110672",
"pm_score": 6,
"selected": true,
"text": "<p>If you use .NET Reflector on the 3.5 class libraries you can see that the implementation of Dictionary actually stores the items in an array (which is resized as needed), and hashes indexes into that array. When getting the keys, it completely ignores the hashtable and iterates over the array of items. For this reason, you will see the behavior you have described since new items are added at the end of the array. It looks like if you do the following:</p>\n\n<pre><code>add 1\nadd 2\nadd 3\nadd 4\nremove 2\nadd 5\n</code></pre>\n\n<p>you will get back 1 5 3 4 because it reuses empty slots.</p>\n\n<p>It is important to note, like many others have, you cannot count on this behavior in future (or past) releases. If you want your dictionary to be sorted then there is a <a href=\"http://msdn.microsoft.com/en-us/library/f7fta44c.aspx\" rel=\"noreferrer\">SortedDictionary</a> class for this purpose.</p>\n"
},
{
"answer_id": 3456260,
"author": "AareP",
"author_id": 11741,
"author_profile": "https://Stackoverflow.com/users/11741",
"pm_score": 0,
"selected": false,
"text": "<p>I hate this kind of \"by design\" functionalities. I think when giving your class such a generic name as \"Dictionary\", it should also behave \"as generally expected\". For example std::map always keeps it's key-values sorted. </p>\n\n<p>Edit: apparently solution is to use SortedDictionary, which behaves similarly to std::map.</p>\n"
}
] |
2008/09/30
|
[
"https://Stackoverflow.com/questions/154307",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3314/"
] |
I just saw this behaviour and I'm a bit surprised by it...
If I add 3 or 4 elements to a Dictionary, and then do a "For Each" to get all the keys, they appear in the same order I added them.
The reason this surprises me is that a Dictionary is supposed to be a HashTable internally, so I expected things to come out in ANY order (ordered by the hash of the key, right?)
What am I missing here?
Is this a behaviour I can count on?
EDIT: OK, I thought already of many of the reasons why this *might* happen (like the separate list to entries, whether this is a coincidence, etc).
My question is, does anyone **know** how this really works?
|
If you use .NET Reflector on the 3.5 class libraries you can see that the implementation of Dictionary actually stores the items in an array (which is resized as needed), and hashes indexes into that array. When getting the keys, it completely ignores the hashtable and iterates over the array of items. For this reason, you will see the behavior you have described since new items are added at the end of the array. It looks like if you do the following:
```
add 1
add 2
add 3
add 4
remove 2
add 5
```
you will get back 1 5 3 4 because it reuses empty slots.
It is important to note, like many others have, you cannot count on this behavior in future (or past) releases. If you want your dictionary to be sorted then there is a [SortedDictionary](http://msdn.microsoft.com/en-us/library/f7fta44c.aspx) class for this purpose.
|
154,309 |
<p>One of our programs is sometimes getting an <code>OutOfMemory</code> error on one user's machine, but of course not when I'm testing it. I just ran it with JProfiler (on a 10 day evaluation license because I've never used it before), and filtering on our code prefix, the biggest chunk both in total size and number of instances is 8000+ instances of a particular simple class. </p>
<p>I clicked the "Garbage Collect" button on JProfiler, and most instances of other classes of ours went away, but not these particular ones. I ran the test again, still in the same instance, and it created 4000+ more instances of the class, but when I clicked "Garbage Collect", those went away leaving the 8000+ original ones.</p>
<p>These instances do get stuck into various Collections at various stages. I assume that the fact that they're not garbage collected must mean that something is holding onto a reference to one of the collections so that's holding onto a reference to the objects.</p>
<p>Any suggestions how I can figure out what is holding onto the reference? I'm looking for suggestions of what to look for in the code, as well as ways to find this out in JProfiler if there are.</p>
|
[
{
"answer_id": 154362,
"author": "JesperE",
"author_id": 13051,
"author_profile": "https://Stackoverflow.com/users/13051",
"pm_score": 2,
"selected": false,
"text": "<p>Keep an eye out for static containers. Any objects in a static container will remain as long as the class is loaded.</p>\n\n<p>Edit: removed incorrect remark on WeakReference.</p>\n"
},
{
"answer_id": 154371,
"author": "Javier",
"author_id": 11649,
"author_profile": "https://Stackoverflow.com/users/11649",
"pm_score": 0,
"selected": false,
"text": "<p>If you're getting OOM errors in a garbage collected language, it usually means that there's some memory not being accounted by the collector. Maybe your objects hold non-java resources? if so, then they should have some kind of 'close' method to make sure that resource is released even if the Java object isn't collected soon enough.</p>\n"
},
{
"answer_id": 154394,
"author": "Tom Hawtin - tackline",
"author_id": 4725,
"author_profile": "https://Stackoverflow.com/users/4725",
"pm_score": 2,
"selected": false,
"text": "<p>One obvious candidate is objects with finalisers. They can linger while their finalize method is called. They need to be collected, then finalised (usually with just a single finaliser thread) and then collected again.</p>\n\n<p>Also be aware that you can get an OOME because the gc failed to collect enough memory, despite there actually being enough for the object request to be created. Otherwise performance would grind into the ground.</p>\n"
},
{
"answer_id": 154395,
"author": "Jacek Szymański",
"author_id": 23242,
"author_profile": "https://Stackoverflow.com/users/23242",
"pm_score": 2,
"selected": false,
"text": "<p>No silver bullet there, you have to use the profiler to identify collections that hold those unneeded objects and find the place in code where they should have been removed. As JesperE said, static collections are the first place to look at.</p>\n"
},
{
"answer_id": 154454,
"author": "18Rabbit",
"author_id": 12662,
"author_profile": "https://Stackoverflow.com/users/12662",
"pm_score": 3,
"selected": false,
"text": "<p>I would look at Collections (especially static ones) in your classes (HashMaps are a good place to start). Take this code for example:</p>\n\n<pre><code>Map<String, Object> map = new HashMap<String, Object>(); // 1 Object\nString name = \"test\"; // 2 Objects\nObject o = new Object(); // 3 Objects\nmap.put(name, o); // 3 Objects, 2 of which have 2 references to them\n\no = null; // The objects are still being\nname = null; // referenced by the HashMap and won't be GC'd\n\nSystem.gc(); // Nothing is deleted.\n\nObject test = map.get(\"test\"); // Returns o\ntest = null;\n\nmap.remove(\"test\"); // Now we're down to just the HashMap in memory\n // o, name and test can all be GC'd\n</code></pre>\n\n<p>As long as the HashMap or some other collection has a reference to that object it won't be garbage collected.</p>\n"
},
{
"answer_id": 154532,
"author": "dj_segfault",
"author_id": 14924,
"author_profile": "https://Stackoverflow.com/users/14924",
"pm_score": 1,
"selected": false,
"text": "<p>I just read an article on this, but I'm sorry I can't remember where. I think it might have been in the book \"Effective Java\". If I find the reference, I'll update my answer.</p>\n\n<p>The two important lessons it outlined are:</p>\n\n<p>1) Final methods tell the gc what to do when it culls the object, but it doesn't ask it to do so, nor is there a way to demand that it does. </p>\n\n<p>2) The modern-day equivalent of the \"memory leak\" in unmanaged memory environments, is the forgotten references. If you don't set all references to an object to <em>null</em> when you're done with it, the object will <em>never</em> be culled. This is most important when implementing your own kind of Collection, or your own wrapper that manages a Collection. If you have a pool or a stack or a queue, and you don't set the bucket to <em>null</em> when you \"remove\" an object from the collection, the bucket that object was in will keep that object alive until that bucket is set to refer to another object.</p>\n\n<p>disclaimer: I know other answers mentioned this, but I'm trying to offer more detail.</p>\n"
},
{
"answer_id": 154558,
"author": "Tom",
"author_id": 22850,
"author_profile": "https://Stackoverflow.com/users/22850",
"pm_score": 3,
"selected": false,
"text": "<p>Try Eclipse Memory Analyzer. It will show you for each object how it is connected to a GC root - an object that is not garbage collected because it is held by the JVM.</p>\n\n<p>See <a href=\"http://dev.eclipse.org/blogs/memoryanalyzer/2008/05/27/automated-heap-dump-analysis-finding-memory-leaks-with-one-click/\" rel=\"noreferrer\">http://dev.eclipse.org/blogs/memoryanalyzer/2008/05/27/automated-heap-dump-analysis-finding-memory-leaks-with-one-click/</a> for more information on how Eclipse MAT works.</p>\n"
},
{
"answer_id": 154570,
"author": "McDowell",
"author_id": 304,
"author_profile": "https://Stackoverflow.com/users/304",
"pm_score": 5,
"selected": true,
"text": "<p>Dump the heap and inspect it.</p>\n\n<p>I'm sure there's more than one way to do this, but here is a simple one. This description is for MS Windows, but similar steps can be taken on other operating systems.</p>\n\n<ol>\n<li>Install the JDK if you don't already have it. <a href=\"http://java.sun.com/javase/6/docs/technotes/tools/index.html\" rel=\"noreferrer\">It comes with a bunch of neat tools.</a></li>\n<li>Start the application.</li>\n<li>Open task manager and find the process id (PID) for java.exe (or whatever executable you are using). If the PID's aren't shown by default, use View > Select Columns... to add them.</li>\n<li>Dump the heap using <em>jmap</em>.</li>\n<li>Start the <em>jhat</em> server on the file you generated and open your browser to <em><a href=\"http://localhost:7000\" rel=\"noreferrer\">http://localhost:7000</a></em> (the default port is 7000). Now you can browse the type you're interested in and information like the number of instances, what has references to them, etcetera.</li>\n</ol>\n\n<p>Here is an example:</p>\n\n<pre><code>C:\\dump>jmap -dump:format=b,file=heap.bin 3552\n\nC:\\dump>jhat heap.bin\nReading from heap.bin...\nDump file created Tue Sep 30 19:46:23 BST 2008\nSnapshot read, resolving...\nResolving 35484 objects...\nChasing references, expect 7 dots.......\nEliminating duplicate references.......\nSnapshot resolved.\nStarted HTTP server on port 7000\nServer is ready.\n</code></pre>\n\n<p>To interpret this, it is useful to understand some of the <a href=\"http://java.sun.com/javase/6/docs/api/java/lang/Class.html#getName()\" rel=\"noreferrer\">array type nomenclature</a> Java uses - like knowing that <strong>class [Ljava.lang.Object;</strong> really means an object of type <strong>Object[]</strong>.</p>\n"
},
{
"answer_id": 154584,
"author": "anjanb",
"author_id": 11142,
"author_profile": "https://Stackoverflow.com/users/11142",
"pm_score": 1,
"selected": false,
"text": "<p>I've used the Yourkit Java profiler(<a href=\"http://www.yourkit.com\" rel=\"nofollow noreferrer\">http://www.yourkit.com</a>) for performance optimizations on java 1.5. It has a section on how to work on memory leaks. I find it useful.</p>\n\n<p><a href=\"http://www.yourkit.com/docs/75/help/performance_problems/memory_leaks/index.jsp\" rel=\"nofollow noreferrer\">http://www.yourkit.com/docs/75/help/performance_problems/memory_leaks/index.jsp</a></p>\n\n<p>You can get a 15 day eval : <a href=\"http://www.yourkit.com/download/yjp-7.5.7.exe\" rel=\"nofollow noreferrer\">http://www.yourkit.com/download/yjp-7.5.7.exe</a></p>\n\n<p>BR,<BR>\n~A</p>\n"
},
{
"answer_id": 527338,
"author": "Thorbjørn Ravn Andersen",
"author_id": 53897,
"author_profile": "https://Stackoverflow.com/users/53897",
"pm_score": 1,
"selected": false,
"text": "<p>Collections was already mentioned. Another hard-to-find location is if you use multiple ClassLoaders, as the old classloader may be unable to be garbage collected until all references have gone.</p>\n\n<p>Also check statics - these are nasty. Logging frameworks can keep things open which may keep references in custom appenders.</p>\n\n<p>Did you resolve the problem?</p>\n"
},
{
"answer_id": 699740,
"author": "ReneS",
"author_id": 33229,
"author_profile": "https://Stackoverflow.com/users/33229",
"pm_score": 1,
"selected": false,
"text": "<p>Some suggestions:</p>\n\n<ul>\n<li>Unlimited maps used as caches, especially when static</li>\n<li>ThreadLocals in server apps, because the threads usually do not die, so the ThreadLocal is not freed</li>\n<li>Interning strings (Strings.intern()), which results in a pile of Strings in the PermSpace</li>\n</ul>\n"
}
] |
2008/09/30
|
[
"https://Stackoverflow.com/questions/154309",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3333/"
] |
One of our programs is sometimes getting an `OutOfMemory` error on one user's machine, but of course not when I'm testing it. I just ran it with JProfiler (on a 10 day evaluation license because I've never used it before), and filtering on our code prefix, the biggest chunk both in total size and number of instances is 8000+ instances of a particular simple class.
I clicked the "Garbage Collect" button on JProfiler, and most instances of other classes of ours went away, but not these particular ones. I ran the test again, still in the same instance, and it created 4000+ more instances of the class, but when I clicked "Garbage Collect", those went away leaving the 8000+ original ones.
These instances do get stuck into various Collections at various stages. I assume that the fact that they're not garbage collected must mean that something is holding onto a reference to one of the collections so that's holding onto a reference to the objects.
Any suggestions how I can figure out what is holding onto the reference? I'm looking for suggestions of what to look for in the code, as well as ways to find this out in JProfiler if there are.
|
Dump the heap and inspect it.
I'm sure there's more than one way to do this, but here is a simple one. This description is for MS Windows, but similar steps can be taken on other operating systems.
1. Install the JDK if you don't already have it. [It comes with a bunch of neat tools.](http://java.sun.com/javase/6/docs/technotes/tools/index.html)
2. Start the application.
3. Open task manager and find the process id (PID) for java.exe (or whatever executable you are using). If the PID's aren't shown by default, use View > Select Columns... to add them.
4. Dump the heap using *jmap*.
5. Start the *jhat* server on the file you generated and open your browser to *<http://localhost:7000>* (the default port is 7000). Now you can browse the type you're interested in and information like the number of instances, what has references to them, etcetera.
Here is an example:
```
C:\dump>jmap -dump:format=b,file=heap.bin 3552
C:\dump>jhat heap.bin
Reading from heap.bin...
Dump file created Tue Sep 30 19:46:23 BST 2008
Snapshot read, resolving...
Resolving 35484 objects...
Chasing references, expect 7 dots.......
Eliminating duplicate references.......
Snapshot resolved.
Started HTTP server on port 7000
Server is ready.
```
To interpret this, it is useful to understand some of the [array type nomenclature](http://java.sun.com/javase/6/docs/api/java/lang/Class.html#getName()) Java uses - like knowing that **class [Ljava.lang.Object;** really means an object of type **Object[]**.
|
154,332 |
<p>I'm using <strong>mysqldump</strong> to replicate a database between accounts on a particular machine. Everything works just great, except when we get to our defined views. Because the dump includes a line like the following ...</p>
<pre><code>/*!50013 DEFINER=`user_a`@`localhost` SQL SECURITY DEFINER */
</code></pre>
<p>... when loading the dump into mysql on user_b we receive an error: </p>
<pre><code>ERROR 1227 (42000) at line 657: Access denied; you need the SUPER privilege for this operation
</code></pre>
<p>Needless to say, I don't have SUPER privilege on this mysql instance. Is there a way to convince <strong>mysqldump</strong> to dump the views in a user-agnostic way? I can't find anything in the manual on this point. Do I have to actually parse the dumpfile to replace the usernames? Or am I missing something?</p>
|
[
{
"answer_id": 154574,
"author": "Max Stewart",
"author_id": 18338,
"author_profile": "https://Stackoverflow.com/users/18338",
"pm_score": 2,
"selected": false,
"text": "<p>The SQL SECURITY clauses determine which MySQL account to use when checking access privileges for the view (as you have probably figured out).</p>\n\n<p>When you create a view you can define a couple of options for security for that view. You can read more <a href=\"http://dev.mysql.com/doc/refman/5.0/en/create-view.html\" rel=\"nofollow noreferrer\">here</a>, but essentially by default access is restricted to the 'definer' of the view, i.e. the user who created it.</p>\n"
},
{
"answer_id": 313854,
"author": "user40237",
"author_id": 40237,
"author_profile": "https://Stackoverflow.com/users/40237",
"pm_score": 6,
"selected": true,
"text": "<p>same problem. I solved it that way:</p>\n\n<pre><code>mysqldump -uuser1 -ppassword1 database1 > backup.sql\n\nsed '/^\\/\\*\\!50013 DEFINER/d' backup.sql > backup_without_50013.sql\n\nmysql -u user2 -ppassword2 -D database2 < backup_without_50013.sql\n</code></pre>\n\n<p>The interesting thing is the <a href=\"http://soft.zoneo.net/Linux/remove_comment_lines.php\" rel=\"noreferrer\">sed</a> command which, here, removes all lines beginning with /*!50013.</p>\n\n<p>Heidy</p>\n"
},
{
"answer_id": 1751162,
"author": "Sander",
"author_id": 213184,
"author_profile": "https://Stackoverflow.com/users/213184",
"pm_score": 0,
"selected": false,
"text": "<p>Run <code>mysqldump</code> with the option <code>\"--skip-triggers\"</code></p>\n"
},
{
"answer_id": 1931022,
"author": "johnk",
"author_id": 234870,
"author_profile": "https://Stackoverflow.com/users/234870",
"pm_score": 4,
"selected": false,
"text": "<p>You will need to process the backup file and change the DEFINER:</p>\n\n<p>DEFINER=<code>user_a</code>@<code>localhost</code></p>\n\n<p>I like to change it to :</p>\n\n<p>DEFINER=CURRENT_USER</p>\n\n<p>It will then be automatically associated to the account that loads it.</p>\n"
}
] |
2008/09/30
|
[
"https://Stackoverflow.com/questions/154332",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/21632/"
] |
I'm using **mysqldump** to replicate a database between accounts on a particular machine. Everything works just great, except when we get to our defined views. Because the dump includes a line like the following ...
```
/*!50013 DEFINER=`user_a`@`localhost` SQL SECURITY DEFINER */
```
... when loading the dump into mysql on user\_b we receive an error:
```
ERROR 1227 (42000) at line 657: Access denied; you need the SUPER privilege for this operation
```
Needless to say, I don't have SUPER privilege on this mysql instance. Is there a way to convince **mysqldump** to dump the views in a user-agnostic way? I can't find anything in the manual on this point. Do I have to actually parse the dumpfile to replace the usernames? Or am I missing something?
|
same problem. I solved it that way:
```
mysqldump -uuser1 -ppassword1 database1 > backup.sql
sed '/^\/\*\!50013 DEFINER/d' backup.sql > backup_without_50013.sql
mysql -u user2 -ppassword2 -D database2 < backup_without_50013.sql
```
The interesting thing is the [sed](http://soft.zoneo.net/Linux/remove_comment_lines.php) command which, here, removes all lines beginning with /\*!50013.
Heidy
|
154,372 |
<p>How do I get a list of all the tables defined for the database when using active record?</p>
|
[
{
"answer_id": 154449,
"author": "Kon",
"author_id": 22303,
"author_profile": "https://Stackoverflow.com/users/22303",
"pm_score": 0,
"selected": false,
"text": "<p>Don't know about active record, but here's a simple query:</p>\n\n<p>select table_name \nfrom INFORMATION_SCHEMA.Tables \nwhere TABLE_TYPE = 'BASE TABLE'</p>\n"
},
{
"answer_id": 155524,
"author": "Jay Stramel",
"author_id": 3547,
"author_profile": "https://Stackoverflow.com/users/3547",
"pm_score": 2,
"selected": false,
"text": "<p>It seems like there should be a better way, but here is how I solved my problem:</p>\n\n<pre><code>Dir[\"app/models/*.rb\"].each do |file_path|\n require file_path # Make sure that the model has been loaded.\n\n basename = File.basename(file_path, File.extname(file_path))\n clazz = basename.camelize.constantize\n\n clazz.find(:all).each do |rec|\n # Important code here...\n end\nend\n</code></pre>\n\n<p>This code assumes that you are following the standard model naming conventions for classes and source code files.</p>\n"
},
{
"answer_id": 155723,
"author": "François Beausoleil",
"author_id": 7355,
"author_profile": "https://Stackoverflow.com/users/7355",
"pm_score": 9,
"selected": true,
"text": "<p>Call <a href=\"http://github.com/rails/rails/tree/master/activerecord/lib/active_record/connection_adapters/abstract/schema_statements.rb#L21\" rel=\"noreferrer\"><code>ActiveRecord::ConnectionAdapters::SchemaStatements#tables</code></a>. This method is undocumented in the MySQL adapter, but is documented in the PostgreSQL adapter. SQLite/SQLite3 also has the method implemented, but undocumented.</p>\n\n<pre><code>>> ActiveRecord::Base.connection.tables\n=> [\"accounts\", \"assets\", ...]\n</code></pre>\n\n<p>See <a href=\"http://github.com/rails/rails/tree/master/activerecord/lib/active_record/connection_adapters/abstract/schema_statements.rb#L21\" rel=\"noreferrer\"><code>activerecord/lib/active_record/connection_adapters/abstract/schema_statements.rb:21</code></a>, as well as the implementations here:</p>\n\n<ul>\n<li><a href=\"http://github.com/rails/rails/tree/master/activerecord/lib/active_record/connection_adapters/mysql_adapter.rb#L412\" rel=\"noreferrer\"><code>activerecord/lib/active_record/connection_adapters/mysql_adapter.rb:412</code></a></li>\n<li><a href=\"http://github.com/rails/rails/tree/master/activerecord/lib/active_record/connection_adapters/postgresql_adapter.rb#L615\" rel=\"noreferrer\"><code>activerecord/lib/active_record/connection_adapters/postgresql_adapter.rb:615</code></a></li>\n<li><a href=\"http://github.com/rails/rails/tree/master/activerecord/lib/active_record/connection_adapters/sqlite_adapter.rb#L176\" rel=\"noreferrer\"><code>activerecord/lib/active_record/connection_adapters/sqlite_adapter.rb:176</code></a></li>\n</ul>\n"
},
{
"answer_id": 14276740,
"author": "Thomas E",
"author_id": 1208895,
"author_profile": "https://Stackoverflow.com/users/1208895",
"pm_score": 4,
"selected": false,
"text": "<p>Based on the two previous answers, you could do:</p>\n\n<pre><code>ActiveRecord::Base.connection.tables.each do |table|\n next if table.match(/\\Aschema_migrations\\Z/)\n klass = table.singularize.camelize.constantize \n puts \"#{klass.name} has #{klass.count} records\"\nend\n</code></pre>\n\n<p>to list every model that abstracts a table, with the number of records.</p>\n"
},
{
"answer_id": 50990734,
"author": "Horacio",
"author_id": 3043906,
"author_profile": "https://Stackoverflow.com/users/3043906",
"pm_score": 4,
"selected": false,
"text": "<blockquote>\n<p>An update for <strong>Rails 5.2</strong></p>\n</blockquote>\n<p>For Rails 5.2 you can also use <code>ApplicationRecord</code> to get an <code>Array</code> with your table' names. Just, as imechemi mentioned, be aware that this method will also return <strong><code>ar_internal_metadata</code></strong> and <strong><code>schema_migrations</code></strong> in that array.</p>\n<pre><code>ApplicationRecord.connection.tables\n</code></pre>\n<p>Keep in mind that you can remove <strong><code>ar_internal_metadata</code></strong> and <strong><code>schema_migrations</code></strong> from the array by calling:</p>\n<pre><code>ApplicationRecord.connection.tables - %w[ar_internal_metadata schema_migrations]\n</code></pre>\n"
}
] |
2008/09/30
|
[
"https://Stackoverflow.com/questions/154372",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3547/"
] |
How do I get a list of all the tables defined for the database when using active record?
|
Call [`ActiveRecord::ConnectionAdapters::SchemaStatements#tables`](http://github.com/rails/rails/tree/master/activerecord/lib/active_record/connection_adapters/abstract/schema_statements.rb#L21). This method is undocumented in the MySQL adapter, but is documented in the PostgreSQL adapter. SQLite/SQLite3 also has the method implemented, but undocumented.
```
>> ActiveRecord::Base.connection.tables
=> ["accounts", "assets", ...]
```
See [`activerecord/lib/active_record/connection_adapters/abstract/schema_statements.rb:21`](http://github.com/rails/rails/tree/master/activerecord/lib/active_record/connection_adapters/abstract/schema_statements.rb#L21), as well as the implementations here:
* [`activerecord/lib/active_record/connection_adapters/mysql_adapter.rb:412`](http://github.com/rails/rails/tree/master/activerecord/lib/active_record/connection_adapters/mysql_adapter.rb#L412)
* [`activerecord/lib/active_record/connection_adapters/postgresql_adapter.rb:615`](http://github.com/rails/rails/tree/master/activerecord/lib/active_record/connection_adapters/postgresql_adapter.rb#L615)
* [`activerecord/lib/active_record/connection_adapters/sqlite_adapter.rb:176`](http://github.com/rails/rails/tree/master/activerecord/lib/active_record/connection_adapters/sqlite_adapter.rb#L176)
|
154,387 |
<p>I'm trying to get something very subtle to work, it looks pretty awful right now. I'm trying to paint the background of a TGroupBox which I have overloaded the paint function of so that the corners are show through to their parent object. I've got a bunch of nested group boxes that look very decent without XPThemes. </p>
<p>Is there a way to paint part of a background transparent at runtime. I'm programming the form generator, not using Delphi design view.</p>
|
[
{
"answer_id": 154470,
"author": "JosephStyons",
"author_id": 672,
"author_profile": "https://Stackoverflow.com/users/672",
"pm_score": 2,
"selected": true,
"text": "<p>I'm trying to duplicate this problem with the following steps:</p>\n\n<p>1 - Set theme to Windows XP default</p>\n\n<p>2 - Drop a TGroupBox on an empty form (align = alNone)</p>\n\n<p>3 - Drop two TGroupBoxes inside the first one, with align = alBottom and align = alClient</p>\n\n<p>But visually it looks just fine for me.</p>\n\n<p>Can you provide some more info on exactly how you've designed the form? Some code pasted from the .DFM would be fine.</p>\n\n<p>Here's the relevant part of my DFM:</p>\n\n<pre><code> object GroupBox1: TGroupBox\n Left = 64\n Top = 56\n Width = 481\n Height = 361\n Margins.Left = 10\n Caption = 'GroupBox1'\n ParentBackground = False\n TabOrder = 0\n object GroupBox2: TGroupBox\n Left = 2\n Top = 254\n Width = 477\n Height = 105\n Align = alBottom\n Caption = 'GroupBox2'\n TabOrder = 0\n end\n object GroupBox3: TGroupBox\n Left = 2\n Top = 15\n Width = 477\n Height = 239\n Align = alClient\n Caption = 'GroupBox3'\n TabOrder = 1\n end\n end\n</code></pre>\n"
},
{
"answer_id": 154855,
"author": "X-Ray",
"author_id": 14031,
"author_profile": "https://Stackoverflow.com/users/14031",
"pm_score": 2,
"selected": false,
"text": "<p>when i had a situation like that, i worked with TGroupBox initially but then decided to use TPaintBox (called pb in this sample) and simulate the graphical part of the TGroupBox instead.</p>\n\n<pre><code>procedure TfraNewRTMDisplay.pbPaint(Sender: TObject);\nconst\n icMarginPixels=0;\n icCornerElipsisDiameterPixels=10;\nbegin\n pb.Canvas.Pen.Color:=clDkGray;\n pb.Canvas.Pen.Width:=1;\n pb.Canvas.Pen.Style:=psSolid;\n pb.Canvas.Brush.Color:=m_iDisplayColor;\n pb.Canvas.Brush.Style:=bsSolid;\n pb.Canvas.RoundRect(icMarginPixels,\n icMarginPixels,\n pb.Width-icMarginPixels*2,\n pb.Height-icMarginPixels*2,\n icCornerElipsisDiameterPixels,\n icCornerElipsisDiameterPixels);\nend;\n</code></pre>\n"
},
{
"answer_id": 162545,
"author": "Peter Turner",
"author_id": 1765,
"author_profile": "https://Stackoverflow.com/users/1765",
"pm_score": 1,
"selected": false,
"text": "<p>Ha, that was lame, I just needed to not set <code>ParentBackground := false</code> in my constructor and paint the interior of the group box when appropriate. </p>\n"
},
{
"answer_id": 163132,
"author": "X-Ray",
"author_id": 14031,
"author_profile": "https://Stackoverflow.com/users/14031",
"pm_score": 1,
"selected": false,
"text": "<blockquote>\n <p>Ha, that was lame, I just needed to not set ParentBackground := false in my constructor and paint the interior of the group box when appropriate.</p>\n</blockquote>\n\n<p>maybe there's something i don't know but in my recent experience, it's not as simple as it sounds because of themes & knowing exactly what area to paint. even TCanvas.FloodFill doesn't work reliably for this work probably because at times, the OS doesn't need to repaint everything.</p>\n"
}
] |
2008/09/30
|
[
"https://Stackoverflow.com/questions/154387",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1765/"
] |
I'm trying to get something very subtle to work, it looks pretty awful right now. I'm trying to paint the background of a TGroupBox which I have overloaded the paint function of so that the corners are show through to their parent object. I've got a bunch of nested group boxes that look very decent without XPThemes.
Is there a way to paint part of a background transparent at runtime. I'm programming the form generator, not using Delphi design view.
|
I'm trying to duplicate this problem with the following steps:
1 - Set theme to Windows XP default
2 - Drop a TGroupBox on an empty form (align = alNone)
3 - Drop two TGroupBoxes inside the first one, with align = alBottom and align = alClient
But visually it looks just fine for me.
Can you provide some more info on exactly how you've designed the form? Some code pasted from the .DFM would be fine.
Here's the relevant part of my DFM:
```
object GroupBox1: TGroupBox
Left = 64
Top = 56
Width = 481
Height = 361
Margins.Left = 10
Caption = 'GroupBox1'
ParentBackground = False
TabOrder = 0
object GroupBox2: TGroupBox
Left = 2
Top = 254
Width = 477
Height = 105
Align = alBottom
Caption = 'GroupBox2'
TabOrder = 0
end
object GroupBox3: TGroupBox
Left = 2
Top = 15
Width = 477
Height = 239
Align = alClient
Caption = 'GroupBox3'
TabOrder = 1
end
end
```
|
154,411 |
<p>I am having trouble getting Team Build to execute my MbUnit unit tests. I have tried to edit TFSBuild.proj and added the following parts:</p>
<pre><code><Project ...>
<UsingTask TaskName="MbUnit.MSBuild.Tasks.MbUnit" AssemblyFile="path_to_MbUnit.MSBuild.Tasks.dll" />
...
...
<ItemGroup>
<TestAssemblies Include="$(OutDir)\Project1.dll" />
<TestAssemblies Include="$(OutDir)\Project2.dll" />
</ItemGroup>
<Target Name="Tests">
<MbUnit
Assemblies="@(TestAssemblies)"
ReportTypes="html"
ReportFileNameFormat="buildreport{0}{1}"
ReportOutputDirectory="." />
</Target>
...
</Project>
</code></pre>
<p>But I have yet to get the tests to run.</p>
|
[
{
"answer_id": 154807,
"author": "Martin Woodward",
"author_id": 6438,
"author_profile": "https://Stackoverflow.com/users/6438",
"pm_score": 0,
"selected": false,
"text": "<p>The way ItemGroups in MSBuild work is that they are evaluated at the very start of the MSBuild scripts, before any targets are ran. Therefore if the assemblies don't exist yet (which they will not because they have not been built yet) then the ItemGroups will not find any files.</p>\n\n<p>The usual pattern in MSBuild to work around this is to re-call MSBuild again at this point so that when the item groups get evaluated in the inner MSBuild execution, the assemblies will exist.</p>\n\n<p>For example, something like:</p>\n\n<pre><code> <PropertyGroup>\n <TestDependsOn>\n $(TestDependsOn);\n CallMbUnitTests;\n </TestDependsOn>\n </PropertyGroup>\n\n <Target Name=\"CallMbUnitTests\">\n <MSBuild Projects=\"$(MSBuildProjectFile)\"\n Properties=\"BuildAgentName=$(BuildAgentName);BuildAgentUri=$(BuildAgentUri);BuildDefinitionName=$(BuildDefinitionName);BuildDefinitionUri=$(BuildDefinitionUri);\n BuildDirectory=$(BuildDirectory);BuildNumber=$(BuildNumber);CompilationStatus=$(CompilationStatus);CompilationSuccess=$(CompilationSuccess);\n ConfigurationFolderUri=$(ConfigurationFolderUri);DropLocation=$(DropLocation);\n FullLabelName=$(FullLabelName);LastChangedBy=$(LastChangedBy);LastChangedOn=$(LastChangedOn);LogLocation=$(LogLocation);\n MachineName=$(MachineName);MaxProcesses=$(MaxProcesses);Port=$(Port);Quality=$(Quality);Reason=$(Reason);RequestedBy=$(RequestedBy);RequestedFor=$(RequestedFor);\n SourceGetVersion=$(SourceGetVersion);StartTime=$(StartTime);Status=$(Status);TeamProject=$(TeamProject);TestStatus=$(TestStatus);\n TestSuccess=$(TestSuccess);WorkspaceName=$(WorkspaceName);WorkspaceOwner=$(WorkspaceOwner);\n SolutionRoot=$(SolutionRoot);BinariesRoot=$(BinariesRoot);TestResultsRoot=$(TestResultsRoot)\"\n Targets=\"RunMbUnitTests\"/>\n </Target>\n\n <ItemGroup>\n <TestAssemblies Include=\"$(OutDir)\\Project1.dll\" />\n <TestAssemblies Include=\"$(OutDir)\\Project2.dll\" />\n </ItemGroup>\n <Target Name=\"RunMbUnitTests\">\n <MbUnit\n Assemblies=\"@(TestAssemblies)\"\n ReportTypes=\"html\"\n ReportFileNameFormat=\"buildreport{0}{1}\"\n ReportOutputDirectory=\".\" />\n </Target>\n</code></pre>\n\n<p>Hope that helps, good luck.</p>\n\n<p>Martin.</p>\n"
},
{
"answer_id": 157129,
"author": "Geir-Tore Lindsve",
"author_id": 4582,
"author_profile": "https://Stackoverflow.com/users/4582",
"pm_score": 2,
"selected": true,
"text": "<p>Above suggestion didn't help me a lot, but I found some documentation for Team Build and adjusted my build script to override the AfterCompile target:</p>\n\n<p><em>(EDIT: Now that I have a better understanding of Team Build, I have added some more to the test runner. It will now update the Build Explorer/Build monitor with build steps with details about the test run)</em></p>\n\n<pre><code><Project ...>\n <UsingTask TaskName=\"MbUnit.MSBuild.Tasks.MbUnit\" AssemblyFile=\"path_to_MbUnit.MSBuild.Tasks.dll\" />\n ...\n ...\n <Target Name=\"AfterCompile\">\n <ItemGroup>\n <TestAssemblies Include=\"$(OutDir)\\Project1.dll\" />\n <TestAssemblies Include=\"$(OutDir)\\Project2.dll\" />\n </ItemGroup>\n\n <BuildStep\n TeamFoundationServerUrl=\"$(TeamFoundationServerUrl)\"\n BuildUri=\"$(BuildUri)\"\n Message=\"Running tests (cross your fingers)...\">\n <Output TaskParameter=\"Id\" PropertyName=\"StepId\" />\n </BuildStep>\n\n <MbUnit\n Assemblies=\"@(TestAssemblies)\"\n ReportTypes=\"html\"\n ReportFileNameFormat=\"buildreport{0}{1}\"\n ReportOutputDirectory=\".\" />\n\n <BuildStep\n TeamFoundationServerUrl=\"$(TeamFoundationServerUrl)\"\n BuildUri=\"$(BuildUri)\"\n Id=\"$(StepId)\"\n Message=\"Yay! All tests succeded!\"\n Status=\"Succeeded\" />\n <OnError ExecuteTargets=\"MarkBuildStepAsFailed\" />\n </Target>\n\n <Target Name=\"MarkBuildStepAsFailed\">\n <BuildStep\n TeamFoundationServerUrl=\"$(TeamFoundationServerUrl)\"\n BuildUri=\"$(BuildUri)\"\n Id=\"$(StepId)\"\n Message=\"Oh no! Some tests have failed. See test report in drop folder for details.\"\n Status=\"Failed\" />\n </Target>\n ...\n</Project>\n</code></pre>\n"
},
{
"answer_id": 707951,
"author": "Erling Paulsen",
"author_id": 85925,
"author_profile": "https://Stackoverflow.com/users/85925",
"pm_score": 1,
"selected": false,
"text": "<p>You don't need to call MSBuild again to have your ItemGroup populated, there is a easier way. Re-calling MSBuild has its downsides, like passing all Teambuild-parameters on to make TeamBuild-tasks work. We use the CreateItem task from MSBuild to dynamically generate a ItemGroup with all our Test DLLs:</p>\n\n<pre><code><Target Name=\"AfterCompile\">\n<CreateItem Include=\"$(OutDir)\\*.Test.dll\">\n <Output\n TaskParameter=\"Include\"\n ItemName=\"TestBinaries\"/>\n</CreateItem>\n</Target><!--Test run happens in a later target in our case, we use MSTest -->\n</code></pre>\n"
}
] |
2008/09/30
|
[
"https://Stackoverflow.com/questions/154411",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4582/"
] |
I am having trouble getting Team Build to execute my MbUnit unit tests. I have tried to edit TFSBuild.proj and added the following parts:
```
<Project ...>
<UsingTask TaskName="MbUnit.MSBuild.Tasks.MbUnit" AssemblyFile="path_to_MbUnit.MSBuild.Tasks.dll" />
...
...
<ItemGroup>
<TestAssemblies Include="$(OutDir)\Project1.dll" />
<TestAssemblies Include="$(OutDir)\Project2.dll" />
</ItemGroup>
<Target Name="Tests">
<MbUnit
Assemblies="@(TestAssemblies)"
ReportTypes="html"
ReportFileNameFormat="buildreport{0}{1}"
ReportOutputDirectory="." />
</Target>
...
</Project>
```
But I have yet to get the tests to run.
|
Above suggestion didn't help me a lot, but I found some documentation for Team Build and adjusted my build script to override the AfterCompile target:
*(EDIT: Now that I have a better understanding of Team Build, I have added some more to the test runner. It will now update the Build Explorer/Build monitor with build steps with details about the test run)*
```
<Project ...>
<UsingTask TaskName="MbUnit.MSBuild.Tasks.MbUnit" AssemblyFile="path_to_MbUnit.MSBuild.Tasks.dll" />
...
...
<Target Name="AfterCompile">
<ItemGroup>
<TestAssemblies Include="$(OutDir)\Project1.dll" />
<TestAssemblies Include="$(OutDir)\Project2.dll" />
</ItemGroup>
<BuildStep
TeamFoundationServerUrl="$(TeamFoundationServerUrl)"
BuildUri="$(BuildUri)"
Message="Running tests (cross your fingers)...">
<Output TaskParameter="Id" PropertyName="StepId" />
</BuildStep>
<MbUnit
Assemblies="@(TestAssemblies)"
ReportTypes="html"
ReportFileNameFormat="buildreport{0}{1}"
ReportOutputDirectory="." />
<BuildStep
TeamFoundationServerUrl="$(TeamFoundationServerUrl)"
BuildUri="$(BuildUri)"
Id="$(StepId)"
Message="Yay! All tests succeded!"
Status="Succeeded" />
<OnError ExecuteTargets="MarkBuildStepAsFailed" />
</Target>
<Target Name="MarkBuildStepAsFailed">
<BuildStep
TeamFoundationServerUrl="$(TeamFoundationServerUrl)"
BuildUri="$(BuildUri)"
Id="$(StepId)"
Message="Oh no! Some tests have failed. See test report in drop folder for details."
Status="Failed" />
</Target>
...
</Project>
```
|
154,427 |
<p>What's the object type returned by Datepicker?
Supposing I have the following:</p>
<pre><code>$("#txtbox").datepicker({
onClose: function(date){
//something
}
});
</code></pre>
<p>What is <code>date</code>? I'm interested in reading the date object from another Datepicker for comparison, something like:</p>
<pre><code> function(date){
oDate = $("#oDP").datepicker("getDate");
if(oDate == date)
//do one
else if(oDate > date)
//do two
}
</code></pre>
<p>However, this kind of comparison is not working. I'm guessing there is some sort of comparison method for Date object, but I don't know. I also tried comparing the String representation of the dates like <code>oDate.toString() > date.toString()</code> to no avail.</p>
|
[
{
"answer_id": 154448,
"author": "Javier",
"author_id": 11649,
"author_profile": "https://Stackoverflow.com/users/11649",
"pm_score": -1,
"selected": false,
"text": "<blockquote>\n <p>What is date?</p>\n</blockquote>\n\n<p>it's the $(\"#txtbox\") object</p>\n"
},
{
"answer_id": 157441,
"author": "ConroyP",
"author_id": 2287,
"author_profile": "https://Stackoverflow.com/users/2287",
"pm_score": 3,
"selected": false,
"text": "<p>A <code>Date</code> object is returned by the <code>datePicker</code>.</p>\n\n<p>Your method for comparing dates is valid - from <a href=\"http://www.w3schools.com/js/js_obj_date.asp\" rel=\"noreferrer\">W3schools</a>:</p>\n\n<pre><code>var myDate=new Date();\nmyDate.setFullYear(2010,0,14);\nvar today = new Date();\n\nif (myDate>today)\n{\n alert(\"Today is before 14th January 2010\");\n}\n</code></pre>\n\n<p>Are you getting a value in <code>oDate</code> from this line?</p>\n\n<pre><code>oDate = $(\"#oDP\").datepicker(\"getDate\");\n</code></pre>\n\n<p>Your comparison method seems valid - so I'm wondering if <code>datePicker</code> is successfully pulling a value from <code>#oDP</code>?</p>\n\n<p><strong>Edit</strong> - <code>oDate</code> confirmed to contain a valid date. This may be a very silly question, but have you confirmed that <code>date</code> contains a valid date? I'm wondering if there may be some issue with naming it the same as the keyword <code>Date</code> (<a href=\"http://www.quackit.com/javascript/javascript_reserved_words.cfm\" rel=\"noreferrer\">Javascript keywords and reserved words</a>). Perhaps try renaming it to <code>tDate</code> or the like in your function to be doubly-clear this isn't causing your problems.</p>\n"
},
{
"answer_id": 234380,
"author": "Pat",
"author_id": 238,
"author_profile": "https://Stackoverflow.com/users/238",
"pm_score": 4,
"selected": true,
"text": "<p>I just downloaded the source from <a href=\"http://www.kelvinluck.com/assets/jquery/datePicker/v2/demo/scripts/jquery.datePicker.js\" rel=\"nofollow noreferrer\">here</a> and noticed (ex line 600) the author is using .getTime() to compare dates, have you tried that?</p>\n\n<pre><code>if (oDate.getTime() > date.getTime()) {\n ...\n}\n</code></pre>\n\n<p>Also this is tangential but you mention you tried oDate.toString() while I noticed in the <a href=\"http://www.kelvinluck.com/assets/jquery/datePicker/v2/demo/datePickerDefaultToday.html\" rel=\"nofollow noreferrer\">examples</a> the author is using .asString()</p>\n"
},
{
"answer_id": 4226945,
"author": "Youssef",
"author_id": 513729,
"author_profile": "https://Stackoverflow.com/users/513729",
"pm_score": 0,
"selected": false,
"text": "<p>Use this to compare dates, it works:\n$(\"#datepickerfrom\").datepicker(\"getDate\") < $(\"#datepickerto\").datepicker(\"getDate\")</p>\n"
}
] |
2008/09/30
|
[
"https://Stackoverflow.com/questions/154427",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2024/"
] |
What's the object type returned by Datepicker?
Supposing I have the following:
```
$("#txtbox").datepicker({
onClose: function(date){
//something
}
});
```
What is `date`? I'm interested in reading the date object from another Datepicker for comparison, something like:
```
function(date){
oDate = $("#oDP").datepicker("getDate");
if(oDate == date)
//do one
else if(oDate > date)
//do two
}
```
However, this kind of comparison is not working. I'm guessing there is some sort of comparison method for Date object, but I don't know. I also tried comparing the String representation of the dates like `oDate.toString() > date.toString()` to no avail.
|
I just downloaded the source from [here](http://www.kelvinluck.com/assets/jquery/datePicker/v2/demo/scripts/jquery.datePicker.js) and noticed (ex line 600) the author is using .getTime() to compare dates, have you tried that?
```
if (oDate.getTime() > date.getTime()) {
...
}
```
Also this is tangential but you mention you tried oDate.toString() while I noticed in the [examples](http://www.kelvinluck.com/assets/jquery/datePicker/v2/demo/datePickerDefaultToday.html) the author is using .asString()
|
154,430 |
<p>I need to store encrypted data (few small strings) between application runs. I do not want the user to provide a passphrase every time (s)he launches the application. I.e. after all it goes down to storing securely the encryption key(s).</p>
<p>I was looking into RSACryptoServiceProvider and using PersistentKeyInCsp, but I'm not sure how it works. Is the key container persistent between application runs or machine restarts? If yes, is it user specific, or machine specific. I.e. if I store my encrypted data in user's roaming profile, can I decrypt the data if the user logs on a different machine?</p>
<p>If the above does not work, what are my options (I need to deal with roaming profiles).</p>
|
[
{
"answer_id": 154687,
"author": "Michael Petrotta",
"author_id": 23897,
"author_profile": "https://Stackoverflow.com/users/23897",
"pm_score": 6,
"selected": true,
"text": "<p>The Data Protection API (DPAPI) does exactly what you want. It provides symmetric encryption of arbitrary data, using the credentials of the machine or (better) the user, as the encryption key. You don't have to worry about managing the keys; Windows takes care of that for you. If the user changes his password, Windows will re-encrypt the data using the user's new password.</p>\n\n<p>DPAPI is exposed in .NET with the System.Security.Cryptography.ProtectedData class:</p>\n\n<pre><code>byte[] plaintextBytes = GetDataToProtect();\nbyte[] encodedBytes = ProtectedData.Protect(plaintextBytes, null, DataProtectionScope.CurrentUser);\n</code></pre>\n\n<p>The second parameter of the Protect method is an optional entropy byte array, which can be used as an additional application-specific \"secret\".</p>\n\n<p>To decrypt, use the ProtectedData.Unprotect call:</p>\n\n<pre><code>byte[] encodedBytes = GetDataToUnprotect();\nbyte[] plaintextBytes = ProtectedData.Unprotect(encodedBytes, null, DataProtectionScope.CurrentUser);\n</code></pre>\n\n<p>DPAPI works correctly with roaming profiles (as described <a href=\"http://support.microsoft.com/kb/309408\" rel=\"noreferrer\">here</a>), though you'll need to store the encrypted data in a place (network share, IsolatedStorage with <a href=\"http://msdn.microsoft.com/en-us/library/zzdt0e7f(VS.71).aspx\" rel=\"noreferrer\">IsolatedStorageScope.Roaming</a>, etc.) that your various machines can access.</p>\n\n<p>See the ProtectedData class in MSDN for more information. There's a DPAPI white paper <a href=\"http://msdn.microsoft.com/en-us/library/ms995355.aspx\" rel=\"noreferrer\">here</a>, with more information than you'd ever want.</p>\n"
},
{
"answer_id": 154727,
"author": "Ray Li",
"author_id": 28952,
"author_profile": "https://Stackoverflow.com/users/28952",
"pm_score": 0,
"selected": false,
"text": "<p>I'd like to add to the DPAPI approach.</p>\n\n<p>Although I haven't implemented the user-store approach myself, there is Microsoft documentation for a user-store approach which encrypts and decrypts data for a specific user.</p>\n\n<p>I used the DPAPI using machine store. I'll describe it in case it fits with what you're looking to do. I used a Windows service to load a Windows user profile and that user's password is used to encrypt data.</p>\n\n<p>As a side note, DPAPI uses Triple-DES which may be slightly weaker (than AES), but then I'm not sure what type of protection you're looking for.</p>\n\n<p>Windows Data Protection\n<a href=\"http://msdn.microsoft.com/en-us/library/ms995355.aspx\" rel=\"nofollow noreferrer\">http://msdn.microsoft.com/en-us/library/ms995355.aspx</a></p>\n"
}
] |
2008/09/30
|
[
"https://Stackoverflow.com/questions/154430",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/8220/"
] |
I need to store encrypted data (few small strings) between application runs. I do not want the user to provide a passphrase every time (s)he launches the application. I.e. after all it goes down to storing securely the encryption key(s).
I was looking into RSACryptoServiceProvider and using PersistentKeyInCsp, but I'm not sure how it works. Is the key container persistent between application runs or machine restarts? If yes, is it user specific, or machine specific. I.e. if I store my encrypted data in user's roaming profile, can I decrypt the data if the user logs on a different machine?
If the above does not work, what are my options (I need to deal with roaming profiles).
|
The Data Protection API (DPAPI) does exactly what you want. It provides symmetric encryption of arbitrary data, using the credentials of the machine or (better) the user, as the encryption key. You don't have to worry about managing the keys; Windows takes care of that for you. If the user changes his password, Windows will re-encrypt the data using the user's new password.
DPAPI is exposed in .NET with the System.Security.Cryptography.ProtectedData class:
```
byte[] plaintextBytes = GetDataToProtect();
byte[] encodedBytes = ProtectedData.Protect(plaintextBytes, null, DataProtectionScope.CurrentUser);
```
The second parameter of the Protect method is an optional entropy byte array, which can be used as an additional application-specific "secret".
To decrypt, use the ProtectedData.Unprotect call:
```
byte[] encodedBytes = GetDataToUnprotect();
byte[] plaintextBytes = ProtectedData.Unprotect(encodedBytes, null, DataProtectionScope.CurrentUser);
```
DPAPI works correctly with roaming profiles (as described [here](http://support.microsoft.com/kb/309408)), though you'll need to store the encrypted data in a place (network share, IsolatedStorage with [IsolatedStorageScope.Roaming](http://msdn.microsoft.com/en-us/library/zzdt0e7f(VS.71).aspx), etc.) that your various machines can access.
See the ProtectedData class in MSDN for more information. There's a DPAPI white paper [here](http://msdn.microsoft.com/en-us/library/ms995355.aspx), with more information than you'd ever want.
|
154,434 |
<p>How do you get spreadsheet data in Excel to recalculate itself from within VBA, without the kluge of just changing a cell value?</p>
|
[
{
"answer_id": 154439,
"author": "Lance Roberts",
"author_id": 13295,
"author_profile": "https://Stackoverflow.com/users/13295",
"pm_score": 7,
"selected": true,
"text": "<p>The following lines will do the trick:</p>\n\n<pre><code>ActiveSheet.EnableCalculation = False \nActiveSheet.EnableCalculation = True \n</code></pre>\n\n<p><strong>Edit:</strong> The <code>.Calculate()</code> method will not work for all functions. I tested it on a sheet with add-in array functions. The production sheet I'm using is complex enough that I don't want to test the <code>.CalculateFull()</code> method, but it may work.</p>\n"
},
{
"answer_id": 154562,
"author": "Graham",
"author_id": 1826,
"author_profile": "https://Stackoverflow.com/users/1826",
"pm_score": 4,
"selected": false,
"text": "<p>This should do the trick...</p>\n\n<pre><code>'recalculate all open workbooks\nApplication.Calculate\n\n'recalculate a specific worksheet\nWorksheets(1).Calculate\n\n' recalculate a specific range\nWorksheets(1).Columns(1).Calculate\n</code></pre>\n"
},
{
"answer_id": 154679,
"author": "Dave DuPlantis",
"author_id": 8174,
"author_profile": "https://Stackoverflow.com/users/8174",
"pm_score": 3,
"selected": false,
"text": "<p>You might also try </p>\n\n<pre><code>Application.CalculateFull\n</code></pre>\n\n<p>or</p>\n\n<pre><code>Application.CalculateFullRebuild\n</code></pre>\n\n<p>if you don't mind rebuilding all open workbooks, rather than just the active worksheet. (<code>CalculateFullRebuild</code> rebuilds dependencies as well.)</p>\n"
},
{
"answer_id": 18621896,
"author": "kambeeks",
"author_id": 2748213,
"author_profile": "https://Stackoverflow.com/users/2748213",
"pm_score": 3,
"selected": false,
"text": "<p>Sometimes Excel will hiccup and needs a kick-start to reapply an equation. This happens in some cases when you are using custom formulas.</p>\n\n<p>Make sure that you have the following script</p>\n\n<pre><code>ActiveSheet.EnableCalculation = True\n</code></pre>\n\n<p>Reapply the equation of choice.</p>\n\n<pre><code>Cells(RowA,ColB).Formula = Cells(RowA,ColB).Formula\n</code></pre>\n\n<p>This can then be looped as needed.</p>\n"
},
{
"answer_id": 27255401,
"author": "AjV Jsy",
"author_id": 2078245,
"author_profile": "https://Stackoverflow.com/users/2078245",
"pm_score": 2,
"selected": false,
"text": "<p>I had an issue with turning off a background image <em>(a DRAFT watermark)</em> in VBA. My change wasn't showing up (which was performed with the <code>Sheets(1).PageSetup.CenterHeader = \"\"</code> method) - so I needed a way to refresh. The <code>ActiveSheet.EnableCalculation</code> approach partly did the trick, but didn't cover unused cells.</p>\n\n<p>In the end I found what I needed with a one liner that made the image vanish when it was no longer set :-</p>\n\n<p><code>Application.ScreenUpdating = True</code></p>\n"
},
{
"answer_id": 56744685,
"author": "pghcpa",
"author_id": 149572,
"author_profile": "https://Stackoverflow.com/users/149572",
"pm_score": 1,
"selected": false,
"text": "<p>After a data connection update, some UDF's were not executing. Using a subroutine, I was trying to recalcuate a single column with:</p>\n\n<pre><code>Sheets(\"mysheet\").Columns(\"D\").Calculate\n</code></pre>\n\n<p>But above statement had no effect. None of above solutions helped, except kambeeks suggestion to replace formulas worked and was fast if manual recalc turned on during update. Below code solved my problem, even if not exactly responsible to OP \"kluge\" comment, it provided a fast/reliable solution to force recalculation of user-specified cells.</p>\n\n<pre><code>Application.Calculation = xlManual\nDoEvents\nFor Each mycell In Sheets(\"mysheet\").Range(\"D9:D750\").Cells\n mycell.Formula = mycell.Formula\nNext\nDoEvents\nApplication.Calculation = xlAutomatic\n</code></pre>\n"
}
] |
2008/09/30
|
[
"https://Stackoverflow.com/questions/154434",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/13295/"
] |
How do you get spreadsheet data in Excel to recalculate itself from within VBA, without the kluge of just changing a cell value?
|
The following lines will do the trick:
```
ActiveSheet.EnableCalculation = False
ActiveSheet.EnableCalculation = True
```
**Edit:** The `.Calculate()` method will not work for all functions. I tested it on a sheet with add-in array functions. The production sheet I'm using is complex enough that I don't want to test the `.CalculateFull()` method, but it may work.
|
154,441 |
<p>I need to test some HTTP interaction with a client I'd rather not modify. What I need to test is the behavior of the server when the client's requests include a certain, static header.</p>
<p>I'm thinking the easiest way to run this test is to set up an HTTP proxy that inserts the header on every request. What would be the simplest way to set this up?</p>
|
[
{
"answer_id": 154475,
"author": "Javier",
"author_id": 11649,
"author_profile": "https://Stackoverflow.com/users/11649",
"pm_score": 2,
"selected": false,
"text": "<p>i'd try <a href=\"http://www.banu.com/tinyproxy/\" rel=\"nofollow noreferrer\">tinyproxy</a>. in fact, the vey best would be to embedd a scripting language there... sounds like a perfect job for <a href=\"http://www.lua.org/\" rel=\"nofollow noreferrer\">Lua</a>, especially after seeing how well it worked for <a href=\"http://forge.mysql.com/wiki/MySQL_Proxy\" rel=\"nofollow noreferrer\">mysqlproxy</a></p>\n"
},
{
"answer_id": 154515,
"author": "Kevin Hakanson",
"author_id": 22514,
"author_profile": "https://Stackoverflow.com/users/22514",
"pm_score": 2,
"selected": false,
"text": "<p>I have had co-workers that have used <a href=\"http://www.portswigger.net/burp/\" rel=\"nofollow noreferrer\">Burp</a> (\"an interactive HTTP/S proxy server for attacking and testing web applications\") for this. You also may be able to use <a href=\"http://www.fiddlertool.com/fiddler/\" rel=\"nofollow noreferrer\">Fiddler</a> (\"a HTTP Debugging Proxy\").</p>\n"
},
{
"answer_id": 154552,
"author": "Eduardo",
"author_id": 9823,
"author_profile": "https://Stackoverflow.com/users/9823",
"pm_score": 1,
"selected": false,
"text": "<p>Use <a href=\"http://www.proxomitron.info\" rel=\"nofollow noreferrer\">http://www.proxomitron.info</a> and set up the header you want, etc.</p>\n"
},
{
"answer_id": 154641,
"author": "Peter Hilton",
"author_id": 2670,
"author_profile": "https://Stackoverflow.com/users/2670",
"pm_score": 7,
"selected": true,
"text": "<p>I do something like this in my development environment by configuring Apache on port 80 as a proxy for my application server on port 8080, with the following Apache config:</p>\n\n<pre><code>NameVirtualHost *\n<VirtualHost *>\n <Proxy http://127.0.0.1:8080/*>\n Allow from all\n </Proxy>\n <LocationMatch \"/myapp\">\n ProxyPass http://127.0.0.1:8080/myapp\n ProxyPassReverse http://127.0.0.1:8080/myapp\n Header add myheader \"myvalue\"\n RequestHeader set myheader \"myvalue\" \n </LocationMatch>\n</VirtualHost>\n</code></pre>\n\n<p>See <a href=\"http://httpd.apache.org/docs/current/mod/core.html#locationmatch\" rel=\"noreferrer\">LocationMatch</a> and <a href=\"http://httpd.apache.org/docs/current/mod/mod_headers.html#requestheader\" rel=\"noreferrer\">RequestHeader</a> documentation.</p>\n\n<p>This adds the header <em>myheader: myvalue</em> to requests going to the application server.</p>\n"
},
{
"answer_id": 157775,
"author": "Nico",
"author_id": 22970,
"author_profile": "https://Stackoverflow.com/users/22970",
"pm_score": 4,
"selected": false,
"text": "<p>You can also install Fiddler (<a href=\"http://www.fiddler2.com/fiddler2/\" rel=\"nofollow noreferrer\">http://www.fiddler2.com/fiddler2/</a>) which is very easy to install (easier than Apache for example).</p>\n\n<p>After launching it, it will register itself as system proxy. Then open the \"Rules\" menu, and choose \"Customize Rules...\" to open a JScript file which allow you to customize requests.</p>\n\n<p>To add a custom header, just add a line in the <code>OnBeforeRequest</code> function:</p>\n\n<pre><code>oSession.oRequest.headers.Add(\"MyHeader\", \"MyValue\");\n</code></pre>\n"
},
{
"answer_id": 16970682,
"author": "Paul Tomblin",
"author_id": 3333,
"author_profile": "https://Stackoverflow.com/users/3333",
"pm_score": 1,
"selected": false,
"text": "<p>Rather than using a proxy, I'm using the Firefox plugin <a href=\"https://addons.mozilla.org/en-US/firefox/addon/modify-headers/\" rel=\"nofollow\">\"Modify Headers\"</a> to insert headers (in my case, to fake a login using the Single Sign On so I can test as different people).</p>\n"
},
{
"answer_id": 31622792,
"author": "John Bowers",
"author_id": 1244603,
"author_profile": "https://Stackoverflow.com/users/1244603",
"pm_score": 0,
"selected": false,
"text": "<p>If you have ruby on your system, how about a small Ruby Proxy using Sinatra (make sure to install the Sinatra Gem). This should be easier than setting up apache. The code can be found <a href=\"http://thecoderslife.blogspot.com/2015/07/a-http-proxy-using-sinatra.html\" rel=\"nofollow\">here.</a></p>\n"
}
] |
2008/09/30
|
[
"https://Stackoverflow.com/questions/154441",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3518/"
] |
I need to test some HTTP interaction with a client I'd rather not modify. What I need to test is the behavior of the server when the client's requests include a certain, static header.
I'm thinking the easiest way to run this test is to set up an HTTP proxy that inserts the header on every request. What would be the simplest way to set this up?
|
I do something like this in my development environment by configuring Apache on port 80 as a proxy for my application server on port 8080, with the following Apache config:
```
NameVirtualHost *
<VirtualHost *>
<Proxy http://127.0.0.1:8080/*>
Allow from all
</Proxy>
<LocationMatch "/myapp">
ProxyPass http://127.0.0.1:8080/myapp
ProxyPassReverse http://127.0.0.1:8080/myapp
Header add myheader "myvalue"
RequestHeader set myheader "myvalue"
</LocationMatch>
</VirtualHost>
```
See [LocationMatch](http://httpd.apache.org/docs/current/mod/core.html#locationmatch) and [RequestHeader](http://httpd.apache.org/docs/current/mod/mod_headers.html#requestheader) documentation.
This adds the header *myheader: myvalue* to requests going to the application server.
|
154,446 |
<p>I am trying to save data to a database on a button push, but the variables seem to be private by the nature of where they are defined. I have tried to move where they are defined, but this seems to produce other errors.</p>
<p>Given a fix, why was it fixed that way?</p>
<p>The code follows.</p>
<pre><code>namespace enable
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
OleDbConnection favouriteConnection = new System.Data.OleDb.OleDbConnection("Provider=Microsoft.Jet.OLEDB.4.0;Data Source=\\\\192.168.123.5\\Share\\Matt\\BugTypes.mdb");
string strSQL = "SELECT CategoryName, Show " + "FROM [Categories] WHERE Show = 'Yes' " + "ORDER BY CategoryName";
OleDbDataAdapter adapter = new OleDbDataAdapter(strSQL, favouriteConnection);
OleDbCommandBuilder cBuilder = new OleDbCommandBuilder(adapter);
DataTable dTable = new DataTable();
adapter.Fill(dTable);
BindingSource bSource = new BindingSource();
bSource.DataSource = dTable;
dataGridView1.DataSource = bSource;
adapter.Update(dTable);
}
private void button1_Click(object sender, EventArgs e)
{
adapter.Update(dTable);//this is the button that needs to do the save, but can't see the variables.
}
}
}
</code></pre>
|
[
{
"answer_id": 154458,
"author": "Franci Penov",
"author_id": 17028,
"author_profile": "https://Stackoverflow.com/users/17028",
"pm_score": 0,
"selected": false,
"text": "<p>Update: [sigh] I forgot to move dTable to the class cope as well...</p>\n\n<pre><code>namespace enable\n{ \n public partial class Form1 : Form\n {\n public Form1()\n {\n InitializeComponent();\n OleDbConnection favouriteConnection = new System.Data.OleDb.OleDbConnection(\"Provider=Microsoft.Jet.OLEDB.4.0;Data Source=\\\\\\\\192.168.123.5\\\\Share\\\\Matt\\\\BugTypes.mdb\");\n string strSQL = \"SELECT CategoryName, Show \" + \"FROM [Categories] WHERE Show = 'Yes' \" + \"ORDER BY CategoryName\";\n m_Adapter = new OleDbDataAdapter(strSQL, favouriteConnection)l\n OleDbCommandBuilder cBuilder = new OleDbCommandBuilder(m_Adapter);\n dTable = new DataTable();\n m_Adapter.Fill(dTable);\n BindingSource bSource = new BindingSource();\n bSource.DataSource = dTable;\n dataGridView1.DataSource = bSource;\n m_Adapter.Update(dTable); \n }\n\n private void button1_Click(object sender, EventArgs e)\n {\n m_Adapter.Update(dTable);//this is the button that needs to do the save, but can't see the variables.\n }\n\n OleDbDataAdapter m_Adapter;\n DataTable dTable;\n }\n}\n</code></pre>\n"
},
{
"answer_id": 154461,
"author": "Chris Wenham",
"author_id": 5548,
"author_profile": "https://Stackoverflow.com/users/5548",
"pm_score": 4,
"selected": true,
"text": "<p>You're declaring <code>dTable</code> and <code>adapter</code> in the constructor, so it goes out of scope as soon as the constructor is completed.</p>\n\n<p>You want to move the variable declarations out into the main class, like:</p>\n\n<pre><code>public partial class Form1 : Form\n{\n private DataTable dTable;\n private OleDbDataAdapter adapter;\n\n Public Form1()\n {\n ... your setup here ...\n dTable = new DataTable();\n ... etc ...\n }\n}\n</code></pre>\n"
},
{
"answer_id": 154462,
"author": "FlySwat",
"author_id": 1965,
"author_profile": "https://Stackoverflow.com/users/1965",
"pm_score": 1,
"selected": false,
"text": "<p>adapter is scoped to the constructor of Form1, not to the class itself.</p>\n\n<p>Move adapter and dtable to be private members of the class.</p>\n"
},
{
"answer_id": 154464,
"author": "albertein",
"author_id": 23020,
"author_profile": "https://Stackoverflow.com/users/23020",
"pm_score": 2,
"selected": false,
"text": "<pre><code>namespace enable\n{ \n public partial class Form1 : Form\n {\n\n OleDbDataAdapter adapter;\n DataTable dTable = new DataTable();\n\n public Form1()\n {\n InitializeComponent();\n OleDbConnection favouriteConnection = new System.Data.OleDb.OleDbConnection(\"Provider=Microsoft.Jet.OLEDB.4.0;Data Source=\\\\\\\\192.168.123.5\\\\Share\\\\Matt\\\\BugTypes.mdb\");\n string strSQL = \"SELECT CategoryName, Show \" + \"FROM [Categories] WHERE Show = 'Yes' \" + \"ORDER BY CategoryName\";\n adapter = new OleDbDataAdapter(strSQL, favouriteConnection);\n OleDbCommandBuilder cBuilder = new OleDbCommandBuilder(adapter);\n adapter.Fill(dTable);\n BindingSource bSource = new BindingSource();\n bSource.DataSource = dTable;\n dataGridView1.DataSource = bSource;\n adapter.Update(dTable); \n }\n private void button1_Click(object sender, EventArgs e)\n {\n adapter.Update(dTable);//this is the button that needs to do the save, but can't see the variables.\n }\n }\n}\n</code></pre>\n\n<p>You need to change DataAdapter and the dataTable scope to be accesible to the button click method event. If you declare them on the constructor they cannot be acceced on other methods, you need to declare them as object fields to be \"global\" to your object instance.</p>\n\n<p>You need to find out what scope need each variable, you can have a local scope, that is, declared inside a method or a class scope, declared outside a method.</p>\n"
},
{
"answer_id": 154480,
"author": "idstam",
"author_id": 21761,
"author_profile": "https://Stackoverflow.com/users/21761",
"pm_score": -1,
"selected": false,
"text": "<p>adapter and dTable is declared within your constructor. They should both be 'moved out' of the constructor to get class wide scoop. Just as Franci did with the adapter.</p>\n\n<p>There might be other errors but it is hard to guess when you haven't posted your compiler error.</p>\n\n<p>/johan/</p>\n"
}
] |
2008/09/30
|
[
"https://Stackoverflow.com/questions/154446",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/19802/"
] |
I am trying to save data to a database on a button push, but the variables seem to be private by the nature of where they are defined. I have tried to move where they are defined, but this seems to produce other errors.
Given a fix, why was it fixed that way?
The code follows.
```
namespace enable
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
OleDbConnection favouriteConnection = new System.Data.OleDb.OleDbConnection("Provider=Microsoft.Jet.OLEDB.4.0;Data Source=\\\\192.168.123.5\\Share\\Matt\\BugTypes.mdb");
string strSQL = "SELECT CategoryName, Show " + "FROM [Categories] WHERE Show = 'Yes' " + "ORDER BY CategoryName";
OleDbDataAdapter adapter = new OleDbDataAdapter(strSQL, favouriteConnection);
OleDbCommandBuilder cBuilder = new OleDbCommandBuilder(adapter);
DataTable dTable = new DataTable();
adapter.Fill(dTable);
BindingSource bSource = new BindingSource();
bSource.DataSource = dTable;
dataGridView1.DataSource = bSource;
adapter.Update(dTable);
}
private void button1_Click(object sender, EventArgs e)
{
adapter.Update(dTable);//this is the button that needs to do the save, but can't see the variables.
}
}
}
```
|
You're declaring `dTable` and `adapter` in the constructor, so it goes out of scope as soon as the constructor is completed.
You want to move the variable declarations out into the main class, like:
```
public partial class Form1 : Form
{
private DataTable dTable;
private OleDbDataAdapter adapter;
Public Form1()
{
... your setup here ...
dTable = new DataTable();
... etc ...
}
}
```
|
154,463 |
<p>I'm using SharpZipLib version 0.85.5 to unzip files. My code has been working nicely for a couple of months until I found a ZIP file that it doesn't like.</p>
<pre><code>ICSharpCode.SharpZipLib.Zip.ZipException: End of extra data
at ICSharpCode.SharpZipLib.Zip.ZipExtraData.ReadCheck(Int32 length) in C:\C#\SharpZLib\Zip\ZipExtraData.cs:line 933
at ICSharpCode.SharpZipLib.Zip.ZipExtraData.Skip(Int32 amount) in C:\C#\SharpZLib\Zip\ZipExtraData.cs:line 921
at ICSharpCode.SharpZipLib.Zip.ZipEntry.ProcessExtraData(Boolean localHeader) in C:\C#\SharpZLib\Zip\ZipEntry.cs:line 925
at ICSharpCode.SharpZipLib.Zip.ZipInputStream.GetNextEntry() in C:\C#\SharpZLib\Zip\ZipInputStream.cs:line 269
at Constellation.Utils.Tools.UnzipFile(String sourcePath, String targetDirectory) in C:\C#\Constellation2\Utils\Tools.cs:line 90
--- End of inner exception stack trace ---
</code></pre>
<p>Here is my unzip method:</p>
<pre><code> public static void UnzipFile(string sourcePath, string targetDirectory)
{
try
{
using (ZipInputStream s = new ZipInputStream(File.OpenRead(sourcePath)))
{
ZipEntry theEntry;
while ((theEntry = s.GetNextEntry()) != null)
{
//string directoryName = Path.GetDirectoryName(theEntry.Name);
string fileName = Path.GetFileName(theEntry.Name);
if (targetDirectory.Length > 0)
{
Directory.CreateDirectory(targetDirectory);
}
if (fileName != String.Empty)
{
using (FileStream streamWriter = File.Create(targetDirectory + fileName))
{
int size = 2048;
byte[] data = new byte[2048];
while (true)
{
size = s.Read(data, 0, data.Length);
if (size > 0)
{
streamWriter.Write(data, 0, size);
}
else
{
break;
}
}
}
}
}
}
}
catch (Exception ex)
{
throw new Exception("Error unzipping file \"" + sourcePath + "\"", ex);
}
}
</code></pre>
<p>The file unzips fine using XP's built-in ZIP support, WinZIP, and 7-Zip. The exception is being thrown at <code>s.GetNextEntry()</code>. </p>
|
[
{
"answer_id": 154545,
"author": "Jon Skeet",
"author_id": 22656,
"author_profile": "https://Stackoverflow.com/users/22656",
"pm_score": 1,
"selected": false,
"text": "<p>It's possible that the other zip tools are ignoring extra data which is corrupt - or it's equally possible that there's a bug in #ZipLib. (I found one a while ago - a certain file that wouldn't compress and then decompress cleanly with certain options.)</p>\n\n<p>In this particular case, I suggest you post on the #ZipLib forum to get the attention of the developers. If your file doesn't contain any sensitive data and you can get them a short but complete program along with it, I suspect that will help enormously.</p>\n"
},
{
"answer_id": 155204,
"author": "Vivek",
"author_id": 7418,
"author_profile": "https://Stackoverflow.com/users/7418",
"pm_score": 0,
"selected": false,
"text": "<p>I agree with Jon. Couldn't fit following in the comment:</p>\n\n<p>(Though this doesn't answer your question)\nIsn't it easier to use something like this:</p>\n\n<pre><code>public static void UnzipFile(string sourcePath, string targetDirectory)\n{\n try\n {\n FastZip fastZip = new FastZip();\n fastZip.CreateEmptyDirectories = false;\n fastZip.ExtractZip(sourcePath, targetDirectory,\"\");\n }\n catch(Exception ex)\n {\n throw new Exception(\"Error unzipping file \\\"\" + sourcePath + \"\\\"\", ex);\n }\n}\n</code></pre>\n"
},
{
"answer_id": 155564,
"author": "Mike Dimmick",
"author_id": 6970,
"author_profile": "https://Stackoverflow.com/users/6970",
"pm_score": 0,
"selected": false,
"text": "<p>See the <a href=\"http://www.pkzip.com/support/zip-application-note\" rel=\"nofollow noreferrer\">official ZIP specification</a>.</p>\n\n<p>Each file in a ZIP archive can have an 'extra' field associated with it. I think #ZipLib is telling you that the 'extra' field length given was longer than the amount of data that was available to read; in other words, the ZIP file has most likely been truncated.</p>\n"
},
{
"answer_id": 30934297,
"author": "Barmaley A",
"author_id": 5027568,
"author_profile": "https://Stackoverflow.com/users/5027568",
"pm_score": 0,
"selected": false,
"text": "<p>According to 4.5.3 of <a href=\"https://pkware.cachefly.net/webdocs/casestudies/APPNOTE.TXT\" rel=\"nofollow\">official ZIP specification</a>, fields Size & CompressedSize of extra data \"MUST only appear if the corresponding Local or Central directory record field is set to 0xFFFF or 0xFFFFFFFF\". </p>\n\n<p>But <code>SharpZipLib</code> writes its at method ZipFile.WriteCentralDirectoryHeader only if \"useZip64_ == UseZip64.On\". I added <code>entry.IsZip64Forced()</code> condition and bug dissapears)</p>\n\n<pre><code> if ( entry.CentralHeaderRequiresZip64 ) {\n ed.StartNewEntry();\n\n if ((entry.Size >= 0xffffffff) || (useZip64_ == UseZip64.On) || entry.IsZip64Forced())\n {\n ed.AddLeLong(entry.Size);\n }\n\n if ((entry.CompressedSize >= 0xffffffff) || (useZip64_ == UseZip64.On) || entry.IsZip64Forced())\n {\n ed.AddLeLong(entry.CompressedSize);\n }\n</code></pre>\n"
}
] |
2008/09/30
|
[
"https://Stackoverflow.com/questions/154463",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/357/"
] |
I'm using SharpZipLib version 0.85.5 to unzip files. My code has been working nicely for a couple of months until I found a ZIP file that it doesn't like.
```
ICSharpCode.SharpZipLib.Zip.ZipException: End of extra data
at ICSharpCode.SharpZipLib.Zip.ZipExtraData.ReadCheck(Int32 length) in C:\C#\SharpZLib\Zip\ZipExtraData.cs:line 933
at ICSharpCode.SharpZipLib.Zip.ZipExtraData.Skip(Int32 amount) in C:\C#\SharpZLib\Zip\ZipExtraData.cs:line 921
at ICSharpCode.SharpZipLib.Zip.ZipEntry.ProcessExtraData(Boolean localHeader) in C:\C#\SharpZLib\Zip\ZipEntry.cs:line 925
at ICSharpCode.SharpZipLib.Zip.ZipInputStream.GetNextEntry() in C:\C#\SharpZLib\Zip\ZipInputStream.cs:line 269
at Constellation.Utils.Tools.UnzipFile(String sourcePath, String targetDirectory) in C:\C#\Constellation2\Utils\Tools.cs:line 90
--- End of inner exception stack trace ---
```
Here is my unzip method:
```
public static void UnzipFile(string sourcePath, string targetDirectory)
{
try
{
using (ZipInputStream s = new ZipInputStream(File.OpenRead(sourcePath)))
{
ZipEntry theEntry;
while ((theEntry = s.GetNextEntry()) != null)
{
//string directoryName = Path.GetDirectoryName(theEntry.Name);
string fileName = Path.GetFileName(theEntry.Name);
if (targetDirectory.Length > 0)
{
Directory.CreateDirectory(targetDirectory);
}
if (fileName != String.Empty)
{
using (FileStream streamWriter = File.Create(targetDirectory + fileName))
{
int size = 2048;
byte[] data = new byte[2048];
while (true)
{
size = s.Read(data, 0, data.Length);
if (size > 0)
{
streamWriter.Write(data, 0, size);
}
else
{
break;
}
}
}
}
}
}
}
catch (Exception ex)
{
throw new Exception("Error unzipping file \"" + sourcePath + "\"", ex);
}
}
```
The file unzips fine using XP's built-in ZIP support, WinZIP, and 7-Zip. The exception is being thrown at `s.GetNextEntry()`.
|
It's possible that the other zip tools are ignoring extra data which is corrupt - or it's equally possible that there's a bug in #ZipLib. (I found one a while ago - a certain file that wouldn't compress and then decompress cleanly with certain options.)
In this particular case, I suggest you post on the #ZipLib forum to get the attention of the developers. If your file doesn't contain any sensitive data and you can get them a short but complete program along with it, I suspect that will help enormously.
|
154,469 |
<p>A feature of C++ is the ability to create unnamed (anonymous) namespaces, like so:</p>
<pre><code>namespace {
int cannotAccessOutsideThisFile() { ... }
} // namespace
</code></pre>
<p>You would think that such a feature would be useless -- since you can't specify the name of the namespace, it's impossible to access anything within it from outside. But these unnamed namespaces <em>are</em> accessible within the file they're created in, as if you had an implicit using-clause to them.</p>
<p>My question is, why or when would this be preferable to using static functions? Or are they essentially two ways of doing the exact same thing?</p>
|
[
{
"answer_id": 154482,
"author": "luke",
"author_id": 16434,
"author_profile": "https://Stackoverflow.com/users/16434",
"pm_score": 10,
"selected": true,
"text": "<p><s>The C++ Standard reads in section 7.3.1.1 Unnamed namespaces, paragraph 2:</s>\n<s></p>\n<blockquote>\n<p>The use of the static keyword is\ndeprecated when declaring objects in a\nnamespace scope, the unnamed-namespace\nprovides a superior alternative.\n</s></p>\n</blockquote>\n<p>Static only applies to names of objects, functions, and anonymous unions, not to type declarations.</p>\n<h2>Edit:</h2>\n<p>The decision to deprecate this use of the <code>static</code> keyword (affecting visibility of a variable declaration in a translation unit) has been reversed (<a href=\"http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_defects.html#1012\" rel=\"noreferrer\">ref</a>). In this case using a <code>static</code> or an unnamed <code>namespace</code> are back to being essentially two ways of doing the exact same thing. For more discussion please see <a href=\"https://stackoverflow.com/questions/4726570/deprecation-of-the-static-keyword-no-more\">this</a> SO question.</p>\n<p>Unnamed <code>namespace</code>'s still have the advantage of allowing you to define translation-unit-local types. Please see <a href=\"https://stackoverflow.com/questions/4422507/superiority-of-unnamed-namespace-over-static\">this</a> SO question for more details.</p>\n<p>Credit goes to <a href=\"https://stackoverflow.com/users/1220179/mike-percy\">Mike Percy</a> for bringing this to my attention.</p>\n"
},
{
"answer_id": 154488,
"author": "Commodore Jaeger",
"author_id": 4659,
"author_profile": "https://Stackoverflow.com/users/4659",
"pm_score": -1,
"selected": false,
"text": "<p>Having learned of this feature only just now while reading your question, I can only speculate. This seems to provide several advantages over a file-level static variable:</p>\n\n<ul>\n<li>Anonymous namespaces can be nested within one another, providing multiple levels of protection from which symbols can not escape.</li>\n<li>Several anonymous namespaces could be placed in the same source file, creating in effect different static-level scopes within the same file.</li>\n</ul>\n\n<p>I'd be interested in learning if anyone has used anonymous namespaces in real code.</p>\n"
},
{
"answer_id": 154508,
"author": "Firas Assaad",
"author_id": 23153,
"author_profile": "https://Stackoverflow.com/users/23153",
"pm_score": 3,
"selected": false,
"text": "<p>Use of static keyword for that purpose is deprecated by the C++98 standard. The problem with static is that it doesn't apply to type definition. It's also an overloaded keyword used in different ways in different contexts, so unnamed namespaces simplify things a bit.</p>\n"
},
{
"answer_id": 155556,
"author": "hazzen",
"author_id": 5066,
"author_profile": "https://Stackoverflow.com/users/5066",
"pm_score": 6,
"selected": false,
"text": "<p>Putting methods in an anonymous namespace prevents you from accidentally violating the <a href=\"http://en.wikipedia.org/wiki/One_Definition_Rule\" rel=\"nofollow noreferrer\">One Definition Rule</a>, allowing you to never worry about naming your helper methods the same as some other method you may link in.</p>\n<p>And, as pointed out by <a href=\"https://stackoverflow.com/a/154482/913098\">luke</a>, anonymous namespaces are preferred by the standard over static members.</p>\n"
},
{
"answer_id": 155734,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 4,
"selected": false,
"text": "<p>I recently began replacing static keywords with anonymous namespaces in my code but immediately ran into a problem where the variables in the namespace were no longer available for inspection in my debugger. I was using VC60, so I don't know if that is a non-issue with other debuggers. My workaround was to define a 'module' namespace, where I gave it the name of my cpp file.</p>\n\n<p>For example, in my XmlUtil.cpp file, I define a namespace <code>XmlUtil_I { ... }</code> for all of my module variables and functions. That way I can apply the <code>XmlUtil_I::</code> qualification in the debugger to access the variables. In this case, the <code>_I</code> distinguishes it from a public namespace such as <code>XmlUtil</code> that I may want to use elsewhere.</p>\n\n<p>I suppose a potential disadvantage of this approach compared to a truly anonymous one is that someone could violate the desired static scope by using the namespace qualifier in other modules. I don't know if that is a major concern though.</p>\n"
},
{
"answer_id": 156834,
"author": "Richard Corden",
"author_id": 11698,
"author_profile": "https://Stackoverflow.com/users/11698",
"pm_score": 5,
"selected": false,
"text": "<p>There is one edge case where static has a surprising effect(at least it was to me). The C++03 Standard states in 14.6.4.2/1:</p>\n\n<blockquote>\n <p>For a function call that depends on a template parameter, if the function name is an <em>unqualified-id</em> but not a <em>template-id</em>, the candidate functions are found using the usual lookup rules (3.4.1, 3.4.2) except that:</p>\n \n <ul>\n <li>For the part of the lookup using unqualified name lookup (3.4.1), only function declarations with external linkage from the template definition context are found.</li>\n <li>For the part of the lookup using associated namespaces (3.4.2), only function declarations with external linkage found in either the template definition context or the template instantiation context are found.</li>\n </ul>\n \n <p>...</p>\n</blockquote>\n\n<p>The below code will call <code>foo(void*)</code> and not <code>foo(S const &)</code> as you might expect.</p>\n\n<pre><code>template <typename T>\nint b1 (T const & t)\n{\n foo(t);\n}\n\nnamespace NS\n{\n namespace\n {\n struct S\n {\n public:\n operator void * () const;\n };\n\n void foo (void*);\n static void foo (S const &); // Not considered 14.6.4.2(b1)\n }\n\n}\n\nvoid b2()\n{\n NS::S s;\n b1 (s);\n}\n</code></pre>\n\n<p>In itself this is probably not that big a deal, but it does highlight that for a fully compliant C++ compiler (i.e. one with support for <code>export</code>) the <code>static</code> keyword will still have functionality that is not available in any other way.</p>\n\n<pre><code>// bar.h\nexport template <typename T>\nint b1 (T const & t);\n\n// bar.cc\n#include \"bar.h\"\ntemplate <typename T>\nint b1 (T const & t)\n{\n foo(t);\n}\n\n// foo.cc\n#include \"bar.h\"\nnamespace NS\n{\n namespace\n {\n struct S\n {\n };\n\n void foo (S const & s); // Will be found by different TU 'bar.cc'\n }\n}\n\nvoid b2()\n{\n NS::S s;\n b1 (s);\n}\n</code></pre>\n\n<p>The only way to ensure that the function in our unnamed namespace will not be found in templates using ADL is to make it <code>static</code>.</p>\n\n<p><strong>Update for Modern C++</strong></p>\n\n<p>As of C++ '11, members of an unnamed namespace have internal linkage implicitly (3.5/4):</p>\n\n<blockquote>\n <p>An unnamed namespace or a namespace declared directly or indirectly within an unnamed namespace has internal linkage.</p>\n</blockquote>\n\n<p>But at the same time, 14.6.4.2/1 was updated to remove mention of linkage (this taken from C++ '14):</p>\n\n<blockquote>\n <p>For a function call where the postfix-expression is a dependent name, the candidate functions are found using\n the usual lookup rules (3.4.1, 3.4.2) except that:</p>\n \n <ul>\n <li><p>For the part of the lookup using unqualified name lookup (3.4.1), only function declarations from the template definition context are found.</p></li>\n <li><p>For the part of the lookup using associated namespaces (3.4.2), only function declarations found in either the template definition context or the template instantiation context are found.</p></li>\n </ul>\n</blockquote>\n\n<p>The result is that this particular difference between static and unnamed namespace members no longer exists.</p>\n"
},
{
"answer_id": 238584,
"author": "Don Wakefield",
"author_id": 3778,
"author_profile": "https://Stackoverflow.com/users/3778",
"pm_score": 3,
"selected": false,
"text": "<p>From experience I'll just note that while it is the C++ way to put formerly-static functions into the anonymous namespace, older compilers can sometimes have problems with this. I currently work with a few compilers for our target platforms, and the more modern Linux compiler is fine with placing functions into the anonymous namespace.</p>\n\n<p>But an older compiler running on Solaris, which we are wed to until an unspecified future release, will sometimes accept it, and other times flag it as an error. The error is not what worries me, it's what it <em>might</em> be doing when it <em>accepts</em> it. So until we go modern across the board, we are still using static (usually class-scoped) functions where we'd prefer the anonymous namespace.</p>\n"
},
{
"answer_id": 8436207,
"author": "Chris",
"author_id": 1009377,
"author_profile": "https://Stackoverflow.com/users/1009377",
"pm_score": 2,
"selected": false,
"text": "<p>In addition if one uses static keyword on a variable like this example:</p>\n\n<pre><code>namespace {\n static int flag;\n}\n</code></pre>\n\n<p>It would not be seen in the mapping file</p>\n"
},
{
"answer_id": 43464911,
"author": "masrtis",
"author_id": 1181561,
"author_profile": "https://Stackoverflow.com/users/1181561",
"pm_score": 2,
"selected": false,
"text": "<p>A compiler specific difference between anonymous namespaces and static functions can be seen compiling the following code.</p>\n\n<pre><code>#include <iostream>\n\nnamespace\n{\n void unreferenced()\n {\n std::cout << \"Unreferenced\";\n }\n\n void referenced()\n {\n std::cout << \"Referenced\";\n }\n}\n\nstatic void static_unreferenced()\n{\n std::cout << \"Unreferenced\";\n}\n\nstatic void static_referenced()\n{\n std::cout << \"Referenced\";\n}\n\nint main()\n{\n referenced();\n static_referenced();\n return 0;\n}\n</code></pre>\n\n<p>Compiling this code with VS 2017 (specifying the level 4 warning flag /W4 to enable <a href=\"https://learn.microsoft.com/en-us/cpp/error-messages/compiler-warnings/compiler-warning-level-4-c4505\" rel=\"nofollow noreferrer\">warning C4505: unreferenced local function has been removed</a>) and gcc 4.9 with the -Wunused-function or -Wall flag shows that VS 2017 will only produce a warning for the unused static function. gcc 4.9 and higher, as well as clang 3.3 and higher, will produce warnings for the unreferenced function in the namespace and also a warning for the unused static function.</p>\n\n<p><a href=\"https://godbolt.org/g/53ubwO\" rel=\"nofollow noreferrer\">Live demo of gcc 4.9 and MSVC 2017</a></p>\n"
},
{
"answer_id": 49679073,
"author": "Pavel P",
"author_id": 468725,
"author_profile": "https://Stackoverflow.com/users/468725",
"pm_score": 3,
"selected": false,
"text": "<p>Personally I prefer static functions over nameless namespaces for the following reasons:</p>\n\n<ul>\n<li><p>It's obvious and clear from function definition alone that it's private to the translation unit where it's compiled. With nameless namespace you might need to scroll and search to see if a function is in a namespace.</p></li>\n<li><p>Functions in namespaces might be treated as extern by some (older) compilers. In VS2017 they are still extern. For this reason even if a function is in nameless namespace you might still want to mark them static.</p></li>\n<li><p>Static functions behave very similar in C or C++, while nameless namespaces are obviously C++ only. nameless namespaces also add extra level in indentation and I don't like that :)</p></li>\n</ul>\n\n<p>So, I'm happy to see that use of static for functions <a href=\"http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_defects.html#1012\" rel=\"noreferrer\">isn't deprecated anymore</a>.</p>\n"
},
{
"answer_id": 62176221,
"author": "Lewis Kelsey",
"author_id": 7194773,
"author_profile": "https://Stackoverflow.com/users/7194773",
"pm_score": 3,
"selected": false,
"text": "<p>The difference is the name of the mangled identifier (<code>_ZN12_GLOBAL__N_11bE</code> vs <code>_ZL1b</code> , which doesn't really matter, but both of them are assembled to local symbols in the symbol table (absence of <code>.global</code> asm directive).</p>\n<pre><code>#include<iostream>\nnamespace {\n int a = 3;\n}\n\nstatic int b = 4;\nint c = 5;\n\nint main (){\n std::cout << a << b << c;\n}\n\n .data\n .align 4\n .type _ZN12_GLOBAL__N_11aE, @object\n .size _ZN12_GLOBAL__N_11aE, 4\n_ZN12_GLOBAL__N_11aE:\n .long 3\n .align 4\n .type _ZL1b, @object\n .size _ZL1b, 4\n_ZL1b:\n .long 4\n .globl c\n .align 4\n .type c, @object\n .size c, 4\nc:\n .long 5\n .text\n</code></pre>\n<p>As for a nested anonymous namespace:</p>\n<pre><code>namespace {\n namespace {\n int a = 3;\n }\n}\n\n .data\n .align 4\n .type _ZN12_GLOBAL__N_112_GLOBAL__N_11aE, @object\n .size _ZN12_GLOBAL__N_112_GLOBAL__N_11aE, 4\n_ZN12_GLOBAL__N_112_GLOBAL__N_11aE:\n .long 3\n</code></pre>\n<p>All 1st level anonymous namespaces in the translation unit are combined with each other, All 2nd level nested anonymous namespaces in the translation unit are combined with each other</p>\n<p>You can also have a nested namespace or nested inline namespace in an anonymous namespace</p>\n<pre><code>namespace {\n namespace A {\n int a = 3;\n }\n}\n\n .data\n .align 4\n .type _ZN12_GLOBAL__N_11A1aE, @object\n .size _ZN12_GLOBAL__N_11A1aE, 4\n_ZN12_GLOBAL__N_11A1aE:\n .long 3\n\nwhich for the record demangles as:\n .data\n .align 4\n .type (anonymous namespace)::A::a, @object\n .size (anonymous namespace)::A::a, 4\n(anonymous namespace)::A::a:\n .long 3\n\n//inline has the same output\n</code></pre>\n<p>You can also have anonymous inline namespaces, but as far as I can tell, <code>inline</code> on an anonymous namespace has 0 effect</p>\n<pre><code>inline namespace {\n inline namespace {\n int a = 3;\n }\n}\n</code></pre>\n<p><code>_ZL1b</code>: <code>_Z</code> means this is a mangled identifier. <code>L</code> means it is a local symbol through <code>static</code>. <code>1</code> is the length of the identifier <code>b</code> and then the identifier <code>b</code></p>\n<p><code>_ZN12_GLOBAL__N_11aE</code> <code>_Z</code> means this is a mangled identifier. <code>N</code> means this is a namespace <code>12</code> is the length of the anonymous namespace name <code>_GLOBAL__N_1</code>, then the anonymous namespace name <code>_GLOBAL__N_1</code>, then <code>1</code> is the length of the identifier <code>a</code>, <code>a</code> is the identifier <code>a</code> and <code>E</code> closes the identifier that resides in a namespace.</p>\n<p><code>_ZN12_GLOBAL__N_11A1aE</code> is the same as above except there's another namespace (<code>1A</code>) in it called <code>A</code>, prefixed with the length of <code>A</code> which is 1. Anonymous namespaces all have the name <code>_GLOBAL__N_1</code></p>\n"
}
] |
2008/09/30
|
[
"https://Stackoverflow.com/questions/154469",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/12193/"
] |
A feature of C++ is the ability to create unnamed (anonymous) namespaces, like so:
```
namespace {
int cannotAccessOutsideThisFile() { ... }
} // namespace
```
You would think that such a feature would be useless -- since you can't specify the name of the namespace, it's impossible to access anything within it from outside. But these unnamed namespaces *are* accessible within the file they're created in, as if you had an implicit using-clause to them.
My question is, why or when would this be preferable to using static functions? Or are they essentially two ways of doing the exact same thing?
|
~~The C++ Standard reads in section 7.3.1.1 Unnamed namespaces, paragraph 2:~~
>
> The use of the static keyword is
> deprecated when declaring objects in a
> namespace scope, the unnamed-namespace
> provides a superior alternative.
>
>
>
>
Static only applies to names of objects, functions, and anonymous unions, not to type declarations.
Edit:
-----
The decision to deprecate this use of the `static` keyword (affecting visibility of a variable declaration in a translation unit) has been reversed ([ref](http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_defects.html#1012)). In this case using a `static` or an unnamed `namespace` are back to being essentially two ways of doing the exact same thing. For more discussion please see [this](https://stackoverflow.com/questions/4726570/deprecation-of-the-static-keyword-no-more) SO question.
Unnamed `namespace`'s still have the advantage of allowing you to define translation-unit-local types. Please see [this](https://stackoverflow.com/questions/4422507/superiority-of-unnamed-namespace-over-static) SO question for more details.
Credit goes to [Mike Percy](https://stackoverflow.com/users/1220179/mike-percy) for bringing this to my attention.
|
154,483 |
<p>I would like to do some condition formatting of strings. I know that you can do some conditional formatting of integers and floats as follows:</p>
<pre><code>Int32 i = 0;
i.ToString("$#,##0.00;($#,##0.00);Zero");
</code></pre>
<p>The above code would result in one of three formats if the variable is positive, negative, or zero.</p>
<p>I would like to know if there is any way to use sections on string arguments. For a concrete, but <strong>contrived</strong> example, I would be looking to replace the "if" check in the following code:</p>
<pre><code>string MyFormatString(List<String> items, List<String> values)
{
string itemList = String.Join(", " items.ToArray());
string valueList = String.Join(", " values.ToArray());
string formatString;
if (items.Count > 0)
//this could easily be:
//if (!String.IsNullOrEmpty(itemList))
{
formatString = "Items: {0}; Values: {1}";
}
else
{
formatString = "Values: {1}";
}
return String.Format(formatString, itemList, valueList);
}
</code></pre>
|
[
{
"answer_id": 154487,
"author": "Kon",
"author_id": 22303,
"author_profile": "https://Stackoverflow.com/users/22303",
"pm_score": 1,
"selected": false,
"text": "<p>This is probably not what you're looking for, but how about...</p>\n\n<pre><code>formatString = (items.Count > 0) ? \"Items: {0}; Values: {1}\" : \"Values: {1}\";\n</code></pre>\n"
},
{
"answer_id": 154492,
"author": "Chris Wenham",
"author_id": 5548,
"author_profile": "https://Stackoverflow.com/users/5548",
"pm_score": 3,
"selected": false,
"text": "<p>Not within String.Format(), but you could use C#'s inline operators, such as:</p>\n\n<pre><code>return items.Count > 0 \n ? String.Format(\"Items: {0}; Values: {1}\", itemList, valueList)\n : String.Format(\"Values: {0}\", valueList); \n</code></pre>\n\n<p>This would help tidy-up the code.</p>\n"
},
{
"answer_id": 154493,
"author": "Jon Skeet",
"author_id": 22656,
"author_profile": "https://Stackoverflow.com/users/22656",
"pm_score": 5,
"selected": false,
"text": "<p>Well, you can simplify it a bit with the conditional operator:</p>\n\n<pre><code>string formatString = items.Count > 0 ? \"Items: {0}; Values: {1}\" : \"Values: {1}\";\nreturn string.Format(formatString, itemList, valueList);\n</code></pre>\n\n<p>Or even include it in the same statement:</p>\n\n<pre><code>return string.Format(items.Count > 0 ? \"Items: {0}; Values: {1}\" : \"Values: {1}\",\n itemList, valueList);\n</code></pre>\n\n<p>Is that what you're after? I don't think you can have a single format string which sometimes includes bits and sometimes it doesn't.</p>\n"
},
{
"answer_id": 154550,
"author": "Joel Coehoorn",
"author_id": 3043,
"author_profile": "https://Stackoverflow.com/users/3043",
"pm_score": 0,
"selected": false,
"text": "<p>I hoped this could do it:</p>\n\n<pre><code>return String.Format(items.ToString(itemList + \" ;;\") + \"Values: {0}\", valueList);\n</code></pre>\n\n<p>Unfortunately, it seems that the .ToString() method doesn't like the blank negative and zero options or not having a # or 0 anywhere. I'll leave it up here in case it points someone else to a better answer.</p>\n"
},
{
"answer_id": 154674,
"author": "Mark Cidade",
"author_id": 1659,
"author_profile": "https://Stackoverflow.com/users/1659",
"pm_score": 2,
"selected": false,
"text": "<pre><code>string.Format( (items.Count > 0 ? \"Items: {0}; \" : \"\") + \"Values {1}\"\n , itemList\n , valueList); \n</code></pre>\n"
},
{
"answer_id": 7014583,
"author": "Andrey Agibalov",
"author_id": 852604,
"author_profile": "https://Stackoverflow.com/users/852604",
"pm_score": 1,
"selected": false,
"text": "<p>Just don't. I have no idea what are both the items and values in your code, but I believe, this pair could be treated as an entity of some kind. Define this entity as a class and override its <code>ToString()</code> method to return whatever you want. There's absolutely nothing wrong with having <code>if</code> for deciding how to format this string depending on some context.</p>\n"
},
{
"answer_id": 8526840,
"author": "JYelton",
"author_id": 161052,
"author_profile": "https://Stackoverflow.com/users/161052",
"pm_score": 3,
"selected": false,
"text": "<p><em>While not addressing the OP directly, this does fall under the question title as well.</em></p>\n\n<p>I frequently need to format strings with some custom unit, but in cases where I don't have data, I don't want to output anything at all. I use this with various nullable types:</p>\n\n<pre><code>/// <summary>\n/// Like String.Format, but if any parameter is null, the nullOutput string is returned.\n/// </summary>\npublic static string StringFormatNull(string format, string nullOutput, params object[] args)\n{\n return args.Any(o => o == null) ? nullOutput : String.Format(format, args);\n}\n</code></pre>\n\n<p>For example, if I am formatting temperatures like \"20°C\", but encounter a null value, it will print an alternate string instead of \"°C\".</p>\n\n<pre><code>double? temp1 = 20.0;\ndouble? temp2 = null;\n\nstring out1 = StringFormatNull(\"{0}°C\", \"N/A\", temp1); // \"20°C\"\nstring out2 = StringFormatNull(\"{0}°C\", \"N/A\", temp2); // \"N/A\"\n</code></pre>\n"
}
] |
2008/09/30
|
[
"https://Stackoverflow.com/questions/154483",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4066/"
] |
I would like to do some condition formatting of strings. I know that you can do some conditional formatting of integers and floats as follows:
```
Int32 i = 0;
i.ToString("$#,##0.00;($#,##0.00);Zero");
```
The above code would result in one of three formats if the variable is positive, negative, or zero.
I would like to know if there is any way to use sections on string arguments. For a concrete, but **contrived** example, I would be looking to replace the "if" check in the following code:
```
string MyFormatString(List<String> items, List<String> values)
{
string itemList = String.Join(", " items.ToArray());
string valueList = String.Join(", " values.ToArray());
string formatString;
if (items.Count > 0)
//this could easily be:
//if (!String.IsNullOrEmpty(itemList))
{
formatString = "Items: {0}; Values: {1}";
}
else
{
formatString = "Values: {1}";
}
return String.Format(formatString, itemList, valueList);
}
```
|
Well, you can simplify it a bit with the conditional operator:
```
string formatString = items.Count > 0 ? "Items: {0}; Values: {1}" : "Values: {1}";
return string.Format(formatString, itemList, valueList);
```
Or even include it in the same statement:
```
return string.Format(items.Count > 0 ? "Items: {0}; Values: {1}" : "Values: {1}",
itemList, valueList);
```
Is that what you're after? I don't think you can have a single format string which sometimes includes bits and sometimes it doesn't.
|
154,489 |
<p>I've been trying this a few different ways, but I'm reaching the conclusion that it can't be done. It's a language feature I've enjoyed from other languages in the past. Is it just something I should just write off?</p>
|
[
{
"answer_id": 154524,
"author": "Jon Skeet",
"author_id": 22656,
"author_profile": "https://Stackoverflow.com/users/22656",
"pm_score": 7,
"selected": true,
"text": "<p>No, static indexers aren't supported in C#. Unlike other answers, however, I see how there could easily be point in having them. Consider:</p>\n\n<pre><code>Encoding x = Encoding[28591]; // Equivalent to Encoding.GetEncoding(28591)\nEncoding y = Encoding[\"Foo\"]; // Equivalent to Encoding.GetEncoding(\"Foo\")\n</code></pre>\n\n<p>It would be relatively rarely used, I suspect, but I think it's odd that it's prohibited - it gives asymmetry for no particular reason as far as I can see.</p>\n"
},
{
"answer_id": 3510465,
"author": "Giorgi Chakhidze",
"author_id": 96009,
"author_profile": "https://Stackoverflow.com/users/96009",
"pm_score": 4,
"selected": false,
"text": "<p>You can simulate static indexers using static indexed properties:</p>\n\n<pre><code>public class MyEncoding\n{\n public sealed class EncodingIndexer\n {\n public Encoding this[string name]\n {\n get { return Encoding.GetEncoding(name); }\n }\n\n public Encoding this[int codepage]\n {\n get { return Encoding.GetEncoding(codepage); }\n }\n }\n\n private static EncodingIndexer StaticIndexer;\n\n public static EncodingIndexer Items\n {\n get { return StaticIndexer ?? (StaticIndexer = new EncodingIndexer()); }\n }\n}\n</code></pre>\n\n<p>Usage:</p>\n\n<pre><code>Encoding x = MyEncoding.Items[28591]; // Equivalent to Encoding.GetEncoding(28591) \nEncoding y = MyEncoding.Items[\"Foo\"]; // Equivalent to Encoding.GetEncoding(\"Foo\") \n</code></pre>\n"
},
{
"answer_id": 35398508,
"author": "dynamichael",
"author_id": 1148881,
"author_profile": "https://Stackoverflow.com/users/1148881",
"pm_score": 0,
"selected": false,
"text": "<p>No, but it is possible to create a static field that holds an instance of a class that uses an indexer...</p>\n\n<pre><code>namespace MyExample {\n\n public class Memory {\n public static readonly MemoryRegister Register = new MemoryRegister();\n\n public class MemoryRegister {\n private int[] _values = new int[100];\n\n public int this[int index] {\n get { return _values[index]; }\n set { _values[index] = value; }\n }\n }\n }\n}\n</code></pre>\n\n<p>...Which could be accessed in the way you are intending. This can be tested in the Immediate Window...</p>\n\n<pre><code>Memory.Register[0] = 12 * 12;\n?Memory.Register[0]\n144\n</code></pre>\n"
}
] |
2008/09/30
|
[
"https://Stackoverflow.com/questions/154489",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5469/"
] |
I've been trying this a few different ways, but I'm reaching the conclusion that it can't be done. It's a language feature I've enjoyed from other languages in the past. Is it just something I should just write off?
|
No, static indexers aren't supported in C#. Unlike other answers, however, I see how there could easily be point in having them. Consider:
```
Encoding x = Encoding[28591]; // Equivalent to Encoding.GetEncoding(28591)
Encoding y = Encoding["Foo"]; // Equivalent to Encoding.GetEncoding("Foo")
```
It would be relatively rarely used, I suspect, but I think it's odd that it's prohibited - it gives asymmetry for no particular reason as far as I can see.
|
154,533 |
<p>What is the best way to bind WPF properties to ApplicationSettings in C#? Is there an automatic way like in a Windows Forms Application? Similar to <a href="https://stackoverflow.com/questions/18421/best-way-to-bind-windows-forms-properties-to-applicationsettings-in-c">this question</a>, how (and is it possible to) do you do the same thing in WPF?</p>
|
[
{
"answer_id": 155585,
"author": "Alan Le",
"author_id": 1133,
"author_profile": "https://Stackoverflow.com/users/1133",
"pm_score": 2,
"selected": false,
"text": "<p>Kris, I'm not sure this is the best way to bind ApplicationSettings, but this is how I did it in <a href=\"http://code.google.com/p/wittytwitter/\" rel=\"nofollow noreferrer\">Witty</a>.</p>\n\n<p>1) Create a dependency property for the setting that you want to bind in the window/page/usercontrol/container. This is case I have an user setting to play sounds.</p>\n\n<pre><code> public bool PlaySounds\n {\n get { return (bool)GetValue(PlaySoundsProperty); }\n set { SetValue(PlaySoundsProperty, value); }\n }\n\n public static readonly DependencyProperty PlaySoundsProperty =\n DependencyProperty.Register(\"PlaySounds\", typeof(bool), typeof(Options),\n new FrameworkPropertyMetadata(false, new PropertyChangedCallback(OnPlaySoundsChanged)));\n\n private static void OnPlaySoundsChanged(DependencyObject obj, DependencyPropertyChangedEventArgs args)\n {\n Properties.Settings.Default.PlaySounds = (bool)args.NewValue;\n Properties.Settings.Default.Save();\n }\n</code></pre>\n\n<p>2) In the constructor, initialize the property value to match the application settings</p>\n\n<pre><code> PlaySounds = Properties.Settings.Default.PlaySounds;\n</code></pre>\n\n<p>3) Bind the property in XAML</p>\n\n<pre><code> <CheckBox Content=\"Play Sounds on new Tweets\" x:Name=\"PlaySoundsCheckBox\" IsChecked=\"{Binding Path=PlaySounds, ElementName=Window, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}\" />\n</code></pre>\n\n<p>You can download the full <a href=\"http://code.google.com/p/wittytwitter/\" rel=\"nofollow noreferrer\">Witty source</a> to see it in action or browse just the <a href=\"http://code.google.com/p/wittytwitter/source/browse/trunk/Witty/Witty/Options.xaml.cs\" rel=\"nofollow noreferrer\">code for options window</a>.</p>\n"
},
{
"answer_id": 156494,
"author": "rudigrobler",
"author_id": 5147,
"author_profile": "https://Stackoverflow.com/users/5147",
"pm_score": 0,
"selected": false,
"text": "<p>Also read <a href=\"http://www.hanselman.com/blog/LearningWPFWithBabySmashConfigurationWithDataBinding.aspx\" rel=\"nofollow noreferrer\">this</a> article on how it is done in BabySmash</p>\n\n<p>You only need to back the Settings with DO (Like Alan's example) if you need the change notification! binding to the POCO Settings class will also work!</p>\n"
},
{
"answer_id": 156856,
"author": "Richard Szalay",
"author_id": 3603,
"author_profile": "https://Stackoverflow.com/users/3603",
"pm_score": 3,
"selected": false,
"text": "<p>The easiest way would be to bind to an object that exposes your application settings as properties or to include that object as a StaticResource and bind to that.</p>\n\n<p>Another direction you could take is creation your own <a href=\"http://msdn.microsoft.com/en-us/library/ms747254.aspx\" rel=\"noreferrer\">Markup Extension</a> so you can simply use PropertyName=\"{ApplicationSetting SomeSettingName}\". To create a custom markup extension you need to inherit <a href=\"http://msdn.microsoft.com/en-us/library/system.windows.markup.markupextension.aspx\" rel=\"noreferrer\">MarkupExtension</a> and decorate the class with a <a href=\"http://msdn.microsoft.com/en-us/library/system.windows.markup.markupextensionreturntypeattribute.aspx\" rel=\"noreferrer\">MarkupExtensionReturnType</a> attribute. <a href=\"http://blogs.interknowlogy.com/johnbowen\" rel=\"noreferrer\">John Bowen</a> has a <a href=\"http://blogs.interknowlogy.com/johnbowen/archive/2007/05/16/13445.aspx\" rel=\"noreferrer\">post on creating a custom MarkupExtension</a> that might make the process a little clearer.</p>\n"
},
{
"answer_id": 263956,
"author": "Sacha Bruttin",
"author_id": 20761,
"author_profile": "https://Stackoverflow.com/users/20761",
"pm_score": 8,
"selected": true,
"text": "<p>You can directly bind to the static object created by Visual Studio.</p>\n\n<p>In your windows declaration add:</p>\n\n<pre><code>xmlns:p=\"clr-namespace:UserSettings.Properties\"\n</code></pre>\n\n<p>where <code>UserSettings</code> is the application namespace.</p>\n\n<p>Then you can add a binding to the correct setting:</p>\n\n<pre><code><TextBlock Height=\"{Binding Source={x:Static p:Settings.Default}, \n Path=Height, Mode=TwoWay}\" ....... />\n</code></pre>\n\n<p>Now you can save the settings, per example when you close your application:</p>\n\n<pre><code>protected override void OnClosing(System.ComponentModel.CancelEventArgs e)\n{\n Properties.Settings.Default.Save();\n base.OnClosing(e); \n}\n</code></pre>\n"
},
{
"answer_id": 3972435,
"author": "Remus",
"author_id": 318854,
"author_profile": "https://Stackoverflow.com/users/318854",
"pm_score": 3,
"selected": false,
"text": "<p>I like the accepted answer, I ran into a special case though. I had my text box set as \"read only\" so that I can change the value of it only in the code. I couldn't understand why the value wasn't propagated back to the Settings although I had the Mode as \"TwoWay\".</p>\n\n<p>Then, I found this: <a href=\"http://msdn.microsoft.com/en-us/library/system.windows.data.binding.updatesourcetrigger.aspx\" rel=\"noreferrer\">http://msdn.microsoft.com/en-us/library/system.windows.data.binding.updatesourcetrigger.aspx</a></p>\n\n<blockquote>\n <p>The default is Default, which returns the default UpdateSourceTrigger value of the target dependency property. However, the default value for most dependency properties is PropertyChanged, while <strong>the Text property has a default value of LostFocus</strong>.</p>\n</blockquote>\n\n<p>Thus, if you have the text box with IsReadOnly=\"True\" property, you have to add a UpdateSourceTrigger=PropertyChanged value to the Binding statement:</p>\n\n<pre><code><TextBox Text={Binding Source={x:Static p:Settings.Default}, Path=myTextSetting, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged} ... />\n</code></pre>\n"
},
{
"answer_id": 9232225,
"author": "TknoSpz",
"author_id": 1202594,
"author_profile": "https://Stackoverflow.com/users/1202594",
"pm_score": 3,
"selected": false,
"text": "<p>In case you are a <strong>VB.Net</strong> developer attempting this, the answer is a smidge different.</p>\n\n<pre><code>xmlns:p=\"clr-namespace:ThisApplication\"\n</code></pre>\n\n<p>Notice the .Properties isn't there.</p>\n\n<hr>\n\n<p>In your binding it's MySettings.Default, instead of Settings.Default - since the app.config stores it differently.</p>\n\n<pre><code><TextBlock Height={Binding Source={x:Static p:MySettings.Default}, Path=Height, ...\n</code></pre>\n\n<p>After a bit of pulling out my hair, I discovered this. Hope it helps</p>\n"
},
{
"answer_id": 17407961,
"author": "NathofGod",
"author_id": 985273,
"author_profile": "https://Stackoverflow.com/users/985273",
"pm_score": 2,
"selected": false,
"text": "<p>I like to do it through the ViewModel and just do the binding as normal in the XAML</p>\n\n<pre><code> public Boolean Value\n {\n get\n {\n return Settings.Default.Value;\n\n }\n set\n {\n Settings.Default.SomeValue= value;\n Settings.Default.Save();\n Notify(\"SomeValue\");\n }\n }\n</code></pre>\n"
}
] |
2008/09/30
|
[
"https://Stackoverflow.com/questions/154533",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3798/"
] |
What is the best way to bind WPF properties to ApplicationSettings in C#? Is there an automatic way like in a Windows Forms Application? Similar to [this question](https://stackoverflow.com/questions/18421/best-way-to-bind-windows-forms-properties-to-applicationsettings-in-c), how (and is it possible to) do you do the same thing in WPF?
|
You can directly bind to the static object created by Visual Studio.
In your windows declaration add:
```
xmlns:p="clr-namespace:UserSettings.Properties"
```
where `UserSettings` is the application namespace.
Then you can add a binding to the correct setting:
```
<TextBlock Height="{Binding Source={x:Static p:Settings.Default},
Path=Height, Mode=TwoWay}" ....... />
```
Now you can save the settings, per example when you close your application:
```
protected override void OnClosing(System.ComponentModel.CancelEventArgs e)
{
Properties.Settings.Default.Save();
base.OnClosing(e);
}
```
|
154,535 |
<p>I have used Photoshop CS2's "Save for Web" feature to create a table of images for my site layout.</p>
<p>This HTML appears fine in a web browser, however when imported into Visual Studio and viewed in the site designer, the metrics are wrong and there are horizontal gaps between images (table cells).</p>
<p>The output from Photoshop does not refer to any stylesheets.<br>
The table attributes set border, cellpadding and cellspacing to 0.</p>
<p>Here is how it looks in the Designer:</p>
<p><img src="https://sites.google.com/site/sizerfx/Home/layout1.png?attredirects=0" alt="alt text"></p>
<p>And here is how it looks in the browser:</p>
<p><img src="https://sites.google.com/site/sizerfx/Home/layout2.png?attredirects=0" alt="alt text"></p>
<p>Is Visual Studio picky about layout of tables and images? Is this a bug in Visual Studio 2005?</p>
|
[
{
"answer_id": 155585,
"author": "Alan Le",
"author_id": 1133,
"author_profile": "https://Stackoverflow.com/users/1133",
"pm_score": 2,
"selected": false,
"text": "<p>Kris, I'm not sure this is the best way to bind ApplicationSettings, but this is how I did it in <a href=\"http://code.google.com/p/wittytwitter/\" rel=\"nofollow noreferrer\">Witty</a>.</p>\n\n<p>1) Create a dependency property for the setting that you want to bind in the window/page/usercontrol/container. This is case I have an user setting to play sounds.</p>\n\n<pre><code> public bool PlaySounds\n {\n get { return (bool)GetValue(PlaySoundsProperty); }\n set { SetValue(PlaySoundsProperty, value); }\n }\n\n public static readonly DependencyProperty PlaySoundsProperty =\n DependencyProperty.Register(\"PlaySounds\", typeof(bool), typeof(Options),\n new FrameworkPropertyMetadata(false, new PropertyChangedCallback(OnPlaySoundsChanged)));\n\n private static void OnPlaySoundsChanged(DependencyObject obj, DependencyPropertyChangedEventArgs args)\n {\n Properties.Settings.Default.PlaySounds = (bool)args.NewValue;\n Properties.Settings.Default.Save();\n }\n</code></pre>\n\n<p>2) In the constructor, initialize the property value to match the application settings</p>\n\n<pre><code> PlaySounds = Properties.Settings.Default.PlaySounds;\n</code></pre>\n\n<p>3) Bind the property in XAML</p>\n\n<pre><code> <CheckBox Content=\"Play Sounds on new Tweets\" x:Name=\"PlaySoundsCheckBox\" IsChecked=\"{Binding Path=PlaySounds, ElementName=Window, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}\" />\n</code></pre>\n\n<p>You can download the full <a href=\"http://code.google.com/p/wittytwitter/\" rel=\"nofollow noreferrer\">Witty source</a> to see it in action or browse just the <a href=\"http://code.google.com/p/wittytwitter/source/browse/trunk/Witty/Witty/Options.xaml.cs\" rel=\"nofollow noreferrer\">code for options window</a>.</p>\n"
},
{
"answer_id": 156494,
"author": "rudigrobler",
"author_id": 5147,
"author_profile": "https://Stackoverflow.com/users/5147",
"pm_score": 0,
"selected": false,
"text": "<p>Also read <a href=\"http://www.hanselman.com/blog/LearningWPFWithBabySmashConfigurationWithDataBinding.aspx\" rel=\"nofollow noreferrer\">this</a> article on how it is done in BabySmash</p>\n\n<p>You only need to back the Settings with DO (Like Alan's example) if you need the change notification! binding to the POCO Settings class will also work!</p>\n"
},
{
"answer_id": 156856,
"author": "Richard Szalay",
"author_id": 3603,
"author_profile": "https://Stackoverflow.com/users/3603",
"pm_score": 3,
"selected": false,
"text": "<p>The easiest way would be to bind to an object that exposes your application settings as properties or to include that object as a StaticResource and bind to that.</p>\n\n<p>Another direction you could take is creation your own <a href=\"http://msdn.microsoft.com/en-us/library/ms747254.aspx\" rel=\"noreferrer\">Markup Extension</a> so you can simply use PropertyName=\"{ApplicationSetting SomeSettingName}\". To create a custom markup extension you need to inherit <a href=\"http://msdn.microsoft.com/en-us/library/system.windows.markup.markupextension.aspx\" rel=\"noreferrer\">MarkupExtension</a> and decorate the class with a <a href=\"http://msdn.microsoft.com/en-us/library/system.windows.markup.markupextensionreturntypeattribute.aspx\" rel=\"noreferrer\">MarkupExtensionReturnType</a> attribute. <a href=\"http://blogs.interknowlogy.com/johnbowen\" rel=\"noreferrer\">John Bowen</a> has a <a href=\"http://blogs.interknowlogy.com/johnbowen/archive/2007/05/16/13445.aspx\" rel=\"noreferrer\">post on creating a custom MarkupExtension</a> that might make the process a little clearer.</p>\n"
},
{
"answer_id": 263956,
"author": "Sacha Bruttin",
"author_id": 20761,
"author_profile": "https://Stackoverflow.com/users/20761",
"pm_score": 8,
"selected": true,
"text": "<p>You can directly bind to the static object created by Visual Studio.</p>\n\n<p>In your windows declaration add:</p>\n\n<pre><code>xmlns:p=\"clr-namespace:UserSettings.Properties\"\n</code></pre>\n\n<p>where <code>UserSettings</code> is the application namespace.</p>\n\n<p>Then you can add a binding to the correct setting:</p>\n\n<pre><code><TextBlock Height=\"{Binding Source={x:Static p:Settings.Default}, \n Path=Height, Mode=TwoWay}\" ....... />\n</code></pre>\n\n<p>Now you can save the settings, per example when you close your application:</p>\n\n<pre><code>protected override void OnClosing(System.ComponentModel.CancelEventArgs e)\n{\n Properties.Settings.Default.Save();\n base.OnClosing(e); \n}\n</code></pre>\n"
},
{
"answer_id": 3972435,
"author": "Remus",
"author_id": 318854,
"author_profile": "https://Stackoverflow.com/users/318854",
"pm_score": 3,
"selected": false,
"text": "<p>I like the accepted answer, I ran into a special case though. I had my text box set as \"read only\" so that I can change the value of it only in the code. I couldn't understand why the value wasn't propagated back to the Settings although I had the Mode as \"TwoWay\".</p>\n\n<p>Then, I found this: <a href=\"http://msdn.microsoft.com/en-us/library/system.windows.data.binding.updatesourcetrigger.aspx\" rel=\"noreferrer\">http://msdn.microsoft.com/en-us/library/system.windows.data.binding.updatesourcetrigger.aspx</a></p>\n\n<blockquote>\n <p>The default is Default, which returns the default UpdateSourceTrigger value of the target dependency property. However, the default value for most dependency properties is PropertyChanged, while <strong>the Text property has a default value of LostFocus</strong>.</p>\n</blockquote>\n\n<p>Thus, if you have the text box with IsReadOnly=\"True\" property, you have to add a UpdateSourceTrigger=PropertyChanged value to the Binding statement:</p>\n\n<pre><code><TextBox Text={Binding Source={x:Static p:Settings.Default}, Path=myTextSetting, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged} ... />\n</code></pre>\n"
},
{
"answer_id": 9232225,
"author": "TknoSpz",
"author_id": 1202594,
"author_profile": "https://Stackoverflow.com/users/1202594",
"pm_score": 3,
"selected": false,
"text": "<p>In case you are a <strong>VB.Net</strong> developer attempting this, the answer is a smidge different.</p>\n\n<pre><code>xmlns:p=\"clr-namespace:ThisApplication\"\n</code></pre>\n\n<p>Notice the .Properties isn't there.</p>\n\n<hr>\n\n<p>In your binding it's MySettings.Default, instead of Settings.Default - since the app.config stores it differently.</p>\n\n<pre><code><TextBlock Height={Binding Source={x:Static p:MySettings.Default}, Path=Height, ...\n</code></pre>\n\n<p>After a bit of pulling out my hair, I discovered this. Hope it helps</p>\n"
},
{
"answer_id": 17407961,
"author": "NathofGod",
"author_id": 985273,
"author_profile": "https://Stackoverflow.com/users/985273",
"pm_score": 2,
"selected": false,
"text": "<p>I like to do it through the ViewModel and just do the binding as normal in the XAML</p>\n\n<pre><code> public Boolean Value\n {\n get\n {\n return Settings.Default.Value;\n\n }\n set\n {\n Settings.Default.SomeValue= value;\n Settings.Default.Save();\n Notify(\"SomeValue\");\n }\n }\n</code></pre>\n"
}
] |
2008/09/30
|
[
"https://Stackoverflow.com/questions/154535",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/414107/"
] |
I have used Photoshop CS2's "Save for Web" feature to create a table of images for my site layout.
This HTML appears fine in a web browser, however when imported into Visual Studio and viewed in the site designer, the metrics are wrong and there are horizontal gaps between images (table cells).
The output from Photoshop does not refer to any stylesheets.
The table attributes set border, cellpadding and cellspacing to 0.
Here is how it looks in the Designer:

And here is how it looks in the browser:

Is Visual Studio picky about layout of tables and images? Is this a bug in Visual Studio 2005?
|
You can directly bind to the static object created by Visual Studio.
In your windows declaration add:
```
xmlns:p="clr-namespace:UserSettings.Properties"
```
where `UserSettings` is the application namespace.
Then you can add a binding to the correct setting:
```
<TextBlock Height="{Binding Source={x:Static p:Settings.Default},
Path=Height, Mode=TwoWay}" ....... />
```
Now you can save the settings, per example when you close your application:
```
protected override void OnClosing(System.ComponentModel.CancelEventArgs e)
{
Properties.Settings.Default.Save();
base.OnClosing(e);
}
```
|
154,536 |
<p>Does anyone know of any good C++ code that does this?</p>
|
[
{
"answer_id": 154564,
"author": "alanc10n",
"author_id": 14059,
"author_profile": "https://Stackoverflow.com/users/14059",
"pm_score": 3,
"selected": false,
"text": "<p><a href=\"http://www.gnu.org/software/cgicc/\" rel=\"noreferrer\">CGICC</a> includes methods to do url encode and decode. <a href=\"http://www.gnu.org/software/cgicc/doc/namespacecgicc.html#90356a1f522eeb502bb68e7d87a1f848\" rel=\"noreferrer\">form_urlencode and form_urldecode</a></p>\n"
},
{
"answer_id": 154627,
"author": "user126593",
"author_id": 2033811,
"author_profile": "https://Stackoverflow.com/users/2033811",
"pm_score": 6,
"selected": false,
"text": "<p>Answering my own question...</p>\n\n<p>libcurl has <a href=\"http://curl.haxx.se/libcurl/c/curl_easy_escape.html\" rel=\"noreferrer\">curl_easy_escape</a> for encoding.</p>\n\n<p>For decoding, <a href=\"https://curl.haxx.se/libcurl/c/curl_easy_unescape.html\" rel=\"noreferrer\">curl_easy_unescape</a></p>\n"
},
{
"answer_id": 4823686,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 4,
"selected": false,
"text": "<pre><code>string urlDecode(string &SRC) {\n string ret;\n char ch;\n int i, ii;\n for (i=0; i<SRC.length(); i++) {\n if (SRC[i]=='%') {\n sscanf(SRC.substr(i+1,2).c_str(), "%x", &ii);\n ch=static_cast<char>(ii);\n ret+=ch;\n i=i+2;\n } else {\n ret+=SRC[i];\n }\n }\n return (ret);\n}\n</code></pre>\n<p>not the best, but working fine ;-)</p>\n"
},
{
"answer_id": 6513697,
"author": "Bagelzone Ha'bonè",
"author_id": 738862,
"author_profile": "https://Stackoverflow.com/users/738862",
"pm_score": 3,
"selected": false,
"text": "<p>Adding a follow-up to Bill's recommendation for using libcurl: great suggestion, and to be updated:<br>\nafter 3 years, the <a href=\"http://curl.haxx.se/libcurl/c/curl_escape.html\" rel=\"noreferrer\">curl_escape</a> function is deprecated, so for future use it's better to use <a href=\"http://curl.haxx.se/libcurl/c/curl_easy_escape.html\" rel=\"noreferrer\">curl_easy_escape</a>.</p>\n"
},
{
"answer_id": 8732830,
"author": "moonlightdock",
"author_id": 117161,
"author_profile": "https://Stackoverflow.com/users/117161",
"pm_score": 3,
"selected": false,
"text": "<p>I ended up on this question when searching for an api to decode url in a win32 c++ app. Since the question doesn't quite specify platform assuming windows isn't a bad thing.</p>\n\n<p>InternetCanonicalizeUrl is the API for windows programs. More info <a href=\"http://msdn.microsoft.com/en-us/library/windows/desktop/aa384342%28v=vs.85%29.aspx\" rel=\"noreferrer\">here</a></p>\n\n<pre><code> LPTSTR lpOutputBuffer = new TCHAR[1];\n DWORD dwSize = 1;\n BOOL fRes = ::InternetCanonicalizeUrl(strUrl, lpOutputBuffer, &dwSize, ICU_DECODE | ICU_NO_ENCODE);\n DWORD dwError = ::GetLastError();\n if (!fRes && dwError == ERROR_INSUFFICIENT_BUFFER)\n {\n delete lpOutputBuffer;\n lpOutputBuffer = new TCHAR[dwSize];\n fRes = ::InternetCanonicalizeUrl(strUrl, lpOutputBuffer, &dwSize, ICU_DECODE | ICU_NO_ENCODE);\n if (fRes)\n {\n //lpOutputBuffer has decoded url\n }\n else\n {\n //failed to decode\n }\n if (lpOutputBuffer !=NULL)\n {\n delete [] lpOutputBuffer;\n lpOutputBuffer = NULL;\n }\n }\n else\n {\n //some other error OR the input string url is just 1 char and was successfully decoded\n }\n</code></pre>\n\n<p>InternetCrackUrl (<a href=\"http://msdn.microsoft.com/en-us/library/windows/desktop/aa384376%28v=vs.85%29.aspx\" rel=\"noreferrer\">here</a>) also seems to have flags to specify whether to decode url</p>\n"
},
{
"answer_id": 17708801,
"author": "xperroni",
"author_id": 476920,
"author_profile": "https://Stackoverflow.com/users/476920",
"pm_score": 7,
"selected": false,
"text": "<p>I faced the encoding half of this problem the other day. Unhappy with the available options, and after taking a look at <a href=\"http://www.geekhideout.com/urlcode.shtml\" rel=\"nofollow noreferrer\">this C sample code</a>, i decided to roll my own C++ url-encode function:</p>\n<pre><code>#include <cctype>\n#include <iomanip>\n#include <sstream>\n#include <string>\n\nusing namespace std;\n\nstring url_encode(const string &value) {\n ostringstream escaped;\n escaped.fill('0');\n escaped << hex;\n\n for (string::const_iterator i = value.begin(), n = value.end(); i != n; ++i) {\n string::value_type c = (*i);\n\n // Keep alphanumeric and other accepted characters intact\n if (isalnum(c) || c == '-' || c == '_' || c == '.' || c == '~') {\n escaped << c;\n continue;\n }\n\n // Any other characters are percent-encoded\n escaped << uppercase;\n escaped << '%' << setw(2) << int((unsigned char) c);\n escaped << nouppercase;\n }\n\n return escaped.str();\n}\n</code></pre>\n<p>The implementation of the decode function is left as an exercise to the reader. :P</p>\n"
},
{
"answer_id": 19875024,
"author": "Johan",
"author_id": 1405259,
"author_profile": "https://Stackoverflow.com/users/1405259",
"pm_score": 1,
"selected": false,
"text": "<p>This version is pure C and can optionally normalize the resource path. Using it with C++ is trivial:</p>\n\n<pre><code>#include <string>\n#include <iostream>\n\nint main(int argc, char** argv)\n{\n const std::string src(\"/some.url/foo/../bar/%2e/\");\n std::cout << \"src=\\\"\" << src << \"\\\"\" << std::endl;\n\n // either do it the C++ conformant way:\n char* dst_buf = new char[src.size() + 1];\n urldecode(dst_buf, src.c_str(), 1);\n std::string dst1(dst_buf);\n delete[] dst_buf;\n std::cout << \"dst1=\\\"\" << dst1 << \"\\\"\" << std::endl;\n\n // or in-place with the &[0] trick to skip the new/delete\n std::string dst2;\n dst2.resize(src.size() + 1);\n dst2.resize(urldecode(&dst2[0], src.c_str(), 1));\n std::cout << \"dst2=\\\"\" << dst2 << \"\\\"\" << std::endl;\n}\n</code></pre>\n\n<p>Outputs:</p>\n\n<pre><code>src=\"/some.url/foo/../bar/%2e/\"\ndst1=\"/some.url/bar/\"\ndst2=\"/some.url/bar/\"\n</code></pre>\n\n<p>And the actual function:</p>\n\n<pre><code>#include <stddef.h>\n#include <ctype.h>\n\n/**\n * decode a percent-encoded C string with optional path normalization\n *\n * The buffer pointed to by @dst must be at least strlen(@src) bytes.\n * Decoding stops at the first character from @src that decodes to null.\n * Path normalization will remove redundant slashes and slash+dot sequences,\n * as well as removing path components when slash+dot+dot is found. It will\n * keep the root slash (if one was present) and will stop normalization\n * at the first questionmark found (so query parameters won't be normalized).\n *\n * @param dst destination buffer\n * @param src source buffer\n * @param normalize perform path normalization if nonzero\n * @return number of valid characters in @dst\n * @author Johan Lindh <[email protected]>\n * @legalese BSD licensed (http://opensource.org/licenses/BSD-2-Clause)\n */\nptrdiff_t urldecode(char* dst, const char* src, int normalize)\n{\n char* org_dst = dst;\n int slash_dot_dot = 0;\n char ch, a, b;\n do {\n ch = *src++;\n if (ch == '%' && isxdigit(a = src[0]) && isxdigit(b = src[1])) {\n if (a < 'A') a -= '0';\n else if(a < 'a') a -= 'A' - 10;\n else a -= 'a' - 10;\n if (b < 'A') b -= '0';\n else if(b < 'a') b -= 'A' - 10;\n else b -= 'a' - 10;\n ch = 16 * a + b;\n src += 2;\n }\n if (normalize) {\n switch (ch) {\n case '/':\n if (slash_dot_dot < 3) {\n /* compress consecutive slashes and remove slash-dot */\n dst -= slash_dot_dot;\n slash_dot_dot = 1;\n break;\n }\n /* fall-through */\n case '?':\n /* at start of query, stop normalizing */\n if (ch == '?')\n normalize = 0;\n /* fall-through */\n case '\\0':\n if (slash_dot_dot > 1) {\n /* remove trailing slash-dot-(dot) */\n dst -= slash_dot_dot;\n /* remove parent directory if it was two dots */\n if (slash_dot_dot == 3)\n while (dst > org_dst && *--dst != '/')\n /* empty body */;\n slash_dot_dot = (ch == '/') ? 1 : 0;\n /* keep the root slash if any */\n if (!slash_dot_dot && dst == org_dst && *dst == '/')\n ++dst;\n }\n break;\n case '.':\n if (slash_dot_dot == 1 || slash_dot_dot == 2) {\n ++slash_dot_dot;\n break;\n }\n /* fall-through */\n default:\n slash_dot_dot = 0;\n }\n }\n *dst++ = ch;\n } while(ch);\n return (dst - org_dst) - 1;\n}\n</code></pre>\n"
},
{
"answer_id": 25335173,
"author": "Yuriy Petrovskiy",
"author_id": 614735,
"author_profile": "https://Stackoverflow.com/users/614735",
"pm_score": 4,
"selected": false,
"text": "<p><a href=\"http://cpp-netlib.org/\">cpp-netlib</a> has functions</p>\n\n<pre><code>namespace boost {\n namespace network {\n namespace uri { \n inline std::string decoded(const std::string &input);\n inline std::string encoded(const std::string &input);\n }\n }\n}\n</code></pre>\n\n<p>they allow to encode and decode URL strings very easy.</p>\n"
},
{
"answer_id": 26519533,
"author": "deltanine",
"author_id": 112428,
"author_profile": "https://Stackoverflow.com/users/112428",
"pm_score": 3,
"selected": false,
"text": "<p>The Windows API has the functions <a href=\"http://msdn.microsoft.com/en-us/library/windows/desktop/bb773774(v=vs.85).aspx\" rel=\"nofollow noreferrer\">UrlEscape</a>/<a href=\"https://msdn.microsoft.com/en-us/library/windows/desktop/bb773791(v=vs.85).aspx\" rel=\"nofollow noreferrer\">UrlUnescape</a>, exported by shlwapi.dll, for this task.</p>\n"
},
{
"answer_id": 28326411,
"author": "Sergey K.",
"author_id": 1065190,
"author_profile": "https://Stackoverflow.com/users/1065190",
"pm_score": -1,
"selected": false,
"text": "<p>Had to do it in a project without Boost. So, ended up writing my own. I will just put it on GitHub: <a href=\"https://github.com/corporateshark/LUrlParser\" rel=\"nofollow\">https://github.com/corporateshark/LUrlParser</a></p>\n\n<pre><code>clParseURL URL = clParseURL::ParseURL( \"https://name:[email protected]:80/path/res\" );\n\nif ( URL.IsValid() )\n{\n cout << \"Scheme : \" << URL.m_Scheme << endl;\n cout << \"Host : \" << URL.m_Host << endl;\n cout << \"Port : \" << URL.m_Port << endl;\n cout << \"Path : \" << URL.m_Path << endl;\n cout << \"Query : \" << URL.m_Query << endl;\n cout << \"Fragment : \" << URL.m_Fragment << endl;\n cout << \"User name : \" << URL.m_UserName << endl;\n cout << \"Password : \" << URL.m_Password << endl;\n}\n</code></pre>\n"
},
{
"answer_id": 29674916,
"author": "kreuzerkrieg",
"author_id": 1530018,
"author_profile": "https://Stackoverflow.com/users/1530018",
"pm_score": 3,
"selected": false,
"text": "<p>[Necromancer mode on]<br>\nStumbled upon this question when was looking for fast, modern, platform independent and elegant solution. Didnt like any of above, cpp-netlib would be the winner but it has horrific memory vulnerability in \"decoded\" function. So I came up with boost's spirit qi/karma solution.<br></p>\n\n<pre><code>namespace bsq = boost::spirit::qi;\nnamespace bk = boost::spirit::karma;\nbsq::int_parser<unsigned char, 16, 2, 2> hex_byte;\ntemplate <typename InputIterator>\nstruct unescaped_string\n : bsq::grammar<InputIterator, std::string(char const *)> {\n unescaped_string() : unescaped_string::base_type(unesc_str) {\n unesc_char.add(\"+\", ' ');\n\n unesc_str = *(unesc_char | \"%\" >> hex_byte | bsq::char_);\n }\n\n bsq::rule<InputIterator, std::string(char const *)> unesc_str;\n bsq::symbols<char const, char const> unesc_char;\n};\n\ntemplate <typename OutputIterator>\nstruct escaped_string : bk::grammar<OutputIterator, std::string(char const *)> {\n escaped_string() : escaped_string::base_type(esc_str) {\n\n esc_str = *(bk::char_(\"a-zA-Z0-9_.~-\") | \"%\" << bk::right_align(2,0)[bk::hex]);\n }\n bk::rule<OutputIterator, std::string(char const *)> esc_str;\n};\n</code></pre>\n\n<p>The usage of above as following:<br></p>\n\n<pre><code>std::string unescape(const std::string &input) {\n std::string retVal;\n retVal.reserve(input.size());\n typedef std::string::const_iterator iterator_type;\n\n char const *start = \"\";\n iterator_type beg = input.begin();\n iterator_type end = input.end();\n unescaped_string<iterator_type> p;\n\n if (!bsq::parse(beg, end, p(start), retVal))\n retVal = input;\n return retVal;\n}\n\nstd::string escape(const std::string &input) {\n typedef std::back_insert_iterator<std::string> sink_type;\n std::string retVal;\n retVal.reserve(input.size() * 3);\n sink_type sink(retVal);\n char const *start = \"\";\n\n escaped_string<sink_type> g;\n if (!bk::generate(sink, g(start), input))\n retVal = input;\n return retVal;\n}\n</code></pre>\n\n<p>[Necromancer mode off]</p>\n\n<p>EDIT01: fixed the zero padding stuff - special thanks to Hartmut Kaiser<br>EDIT02: <a href=\"http://coliru.stacked-crooked.com/a/a697f0864ef3b09d\" rel=\"noreferrer\">Live on CoLiRu</a></p>\n"
},
{
"answer_id": 29962178,
"author": "tormuto",
"author_id": 2298136,
"author_profile": "https://Stackoverflow.com/users/2298136",
"pm_score": 4,
"selected": false,
"text": "<p>Ordinarily adding '%' to the int value of a char will not work when encoding, the value is supposed to the the hex equivalent. e.g '/' is '%2F' not '%47'.</p>\n\n<p>I think this is the best and concise solutions for both url encoding and decoding (No much header dependencies).</p>\n\n<pre><code>string urlEncode(string str){\n string new_str = \"\";\n char c;\n int ic;\n const char* chars = str.c_str();\n char bufHex[10];\n int len = strlen(chars);\n\n for(int i=0;i<len;i++){\n c = chars[i];\n ic = c;\n // uncomment this if you want to encode spaces with +\n /*if (c==' ') new_str += '+'; \n else */if (isalnum(c) || c == '-' || c == '_' || c == '.' || c == '~') new_str += c;\n else {\n sprintf(bufHex,\"%X\",c);\n if(ic < 16) \n new_str += \"%0\"; \n else\n new_str += \"%\";\n new_str += bufHex;\n }\n }\n return new_str;\n }\n\nstring urlDecode(string str){\n string ret;\n char ch;\n int i, ii, len = str.length();\n\n for (i=0; i < len; i++){\n if(str[i] != '%'){\n if(str[i] == '+')\n ret += ' ';\n else\n ret += str[i];\n }else{\n sscanf(str.substr(i + 1, 2).c_str(), \"%x\", &ii);\n ch = static_cast<char>(ii);\n ret += ch;\n i = i + 2;\n }\n }\n return ret;\n}\n</code></pre>\n"
},
{
"answer_id": 30499405,
"author": "Gabe Rainbow",
"author_id": 1869322,
"author_profile": "https://Stackoverflow.com/users/1869322",
"pm_score": 1,
"selected": false,
"text": "<p>the juicy bits</p>\n\n<pre><code>#include <ctype.h> // isdigit, tolower\n\nfrom_hex(char ch) {\n return isdigit(ch) ? ch - '0' : tolower(ch) - 'a' + 10;\n}\n\nchar to_hex(char code) {\n static char hex[] = \"0123456789abcdef\";\n return hex[code & 15];\n}\n</code></pre>\n\n<p>noting that </p>\n\n<pre><code>char d = from_hex(hex[0]) << 4 | from_hex(hex[1]);\n</code></pre>\n\n<p>as in</p>\n\n<pre><code>// %7B = '{'\n\nchar d = from_hex('7') << 4 | from_hex('B');\n</code></pre>\n"
},
{
"answer_id": 32595923,
"author": "kometen",
"author_id": 319826,
"author_profile": "https://Stackoverflow.com/users/319826",
"pm_score": 3,
"selected": false,
"text": "<p>Inspired by xperroni I wrote a decoder. Thank you for the pointer.</p>\n\n<pre><code>#include <iostream>\n#include <sstream>\n#include <string>\n\nusing namespace std;\n\nchar from_hex(char ch) {\n return isdigit(ch) ? ch - '0' : tolower(ch) - 'a' + 10;\n}\n\nstring url_decode(string text) {\n char h;\n ostringstream escaped;\n escaped.fill('0');\n\n for (auto i = text.begin(), n = text.end(); i != n; ++i) {\n string::value_type c = (*i);\n\n if (c == '%') {\n if (i[1] && i[2]) {\n h = from_hex(i[1]) << 4 | from_hex(i[2]);\n escaped << h;\n i += 2;\n }\n } else if (c == '+') {\n escaped << ' ';\n } else {\n escaped << c;\n }\n }\n\n return escaped.str();\n}\n\nint main(int argc, char** argv) {\n string msg = \"J%C3%B8rn!\";\n cout << msg << endl;\n string decodemsg = url_decode(msg);\n cout << decodemsg << endl;\n\n return 0;\n}\n</code></pre>\n\n<p>edit: Removed unneeded cctype and iomainip includes.</p>\n"
},
{
"answer_id": 33639602,
"author": "Alfredo Meraz",
"author_id": 3171390,
"author_profile": "https://Stackoverflow.com/users/3171390",
"pm_score": 0,
"selected": false,
"text": "<p>I know the question asks for a C++ method, but for those who might need it, I came up with a very short function in plain C to encode a string. It doesn't create a new string, rather it alters the existing one, meaning that it must have enough size to hold the new string. Very easy to keep up.</p>\n\n<pre><code>void urlEncode(char *string)\n{\n char charToEncode;\n int posToEncode;\n while (((posToEncode=strspn(string,\"1234567890ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz-_.~\"))!=0) &&(posToEncode<strlen(string)))\n {\n charToEncode=string[posToEncode];\n memmove(string+posToEncode+3,string+posToEncode+1,strlen(string+posToEncode));\n string[posToEncode]='%';\n string[posToEncode+1]=\"0123456789ABCDEF\"[charToEncode>>4];\n string[posToEncode+2]=\"0123456789ABCDEF\"[charToEncode&0xf];\n string+=posToEncode+3;\n }\n}\n</code></pre>\n"
},
{
"answer_id": 35941730,
"author": "Vineet Mimrot",
"author_id": 1400558,
"author_profile": "https://Stackoverflow.com/users/1400558",
"pm_score": 1,
"selected": false,
"text": "<p>You can use \"g_uri_escape_string()\" function provided glib.h.\n<a href=\"https://developer.gnome.org/glib/stable/glib-URI-Functions.html\" rel=\"nofollow\">https://developer.gnome.org/glib/stable/glib-URI-Functions.html</a></p>\n\n<pre><code>#include <stdio.h>\n#include <stdlib.h>\n#include <glib.h>\nint main() {\n char *uri = \"http://www.example.com?hello world\";\n char *encoded_uri = NULL;\n //as per wiki (https://en.wikipedia.org/wiki/Percent-encoding)\n char *escape_char_str = \"!*'();:@&=+$,/?#[]\"; \n encoded_uri = g_uri_escape_string(uri, escape_char_str, TRUE);\n printf(\"[%s]\\n\", encoded_uri);\n free(encoded_uri);\n\n return 0;\n}\n</code></pre>\n\n<p>compile it with:</p>\n\n<pre><code>gcc encoding_URI.c `pkg-config --cflags --libs glib-2.0`\n</code></pre>\n"
},
{
"answer_id": 36432189,
"author": "Dalzhim",
"author_id": 1279096,
"author_profile": "https://Stackoverflow.com/users/1279096",
"pm_score": 2,
"selected": false,
"text": "<p>Another solution is available using <a href=\"https://github.com/facebook/folly\" rel=\"nofollow\">Facebook's folly library</a> : <code>folly::uriEscape</code> and <code>folly::uriUnescape</code>.</p>\n"
},
{
"answer_id": 41434414,
"author": "jamacoe",
"author_id": 4335480,
"author_profile": "https://Stackoverflow.com/users/4335480",
"pm_score": 2,
"selected": false,
"text": "<p>I couldn't find a URI decode/unescape here that also decodes 2 and 3 byte sequences. Contributing my own version, that on-the-fly converts the c sting input to a wstring:</p>\n<pre><code>#include <string>\n\nconst char HEX2DEC[55] =\n{\n 0, 1, 2, 3, 4, 5, 6, 7, 8, 9,-1,-1, -1,-1,-1,-1,\n -1,10,11,12, 13,14,15,-1, -1,-1,-1,-1, -1,-1,-1,-1,\n -1,-1,-1,-1, -1,-1,-1,-1, -1,-1,-1,-1, -1,-1,-1,-1,\n -1,10,11,12, 13,14,15\n};\n\n#define __x2d__(s) HEX2DEC[*(s)-48]\n#define __x2d2__(s) __x2d__(s) << 4 | __x2d__(s+1)\n\nstd::wstring decodeURI(const char * s) {\n unsigned char b;\n std::wstring ws;\n while (*s) {\n if (*s == '%')\n if ((b = __x2d2__(s + 1)) >= 0x80) {\n if (b >= 0xE0) { // three byte codepoint\n ws += ((b & 0b00001111) << 12) | ((__x2d2__(s + 4) & 0b00111111) << 6) | (__x2d2__(s + 7) & 0b00111111);\n s += 9;\n }\n else { // two byte codepoint\n ws += (__x2d2__(s + 4) & 0b00111111) | (b & 0b00000011) << 6;\n s += 6;\n }\n }\n else { // one byte codepoints\n ws += b;\n s += 3;\n }\n else { // no %\n ws += *s;\n s++;\n }\n }\n return ws;\n}\n</code></pre>\n"
},
{
"answer_id": 48379192,
"author": "Pratik",
"author_id": 8642268,
"author_profile": "https://Stackoverflow.com/users/8642268",
"pm_score": 1,
"selected": false,
"text": "<p>you can simply use function AtlEscapeUrl() from atlutil.h, just go through its documentation on how to use it.</p>\n"
}
] |
2008/09/30
|
[
"https://Stackoverflow.com/questions/154536",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2033811/"
] |
Does anyone know of any good C++ code that does this?
|
I faced the encoding half of this problem the other day. Unhappy with the available options, and after taking a look at [this C sample code](http://www.geekhideout.com/urlcode.shtml), i decided to roll my own C++ url-encode function:
```
#include <cctype>
#include <iomanip>
#include <sstream>
#include <string>
using namespace std;
string url_encode(const string &value) {
ostringstream escaped;
escaped.fill('0');
escaped << hex;
for (string::const_iterator i = value.begin(), n = value.end(); i != n; ++i) {
string::value_type c = (*i);
// Keep alphanumeric and other accepted characters intact
if (isalnum(c) || c == '-' || c == '_' || c == '.' || c == '~') {
escaped << c;
continue;
}
// Any other characters are percent-encoded
escaped << uppercase;
escaped << '%' << setw(2) << int((unsigned char) c);
escaped << nouppercase;
}
return escaped.str();
}
```
The implementation of the decode function is left as an exercise to the reader. :P
|
154,538 |
<p>Long story short, I need to put some text in my Flex application and I don't want users to be able to copy. I was going to use a label, but apparently labels do not support text wrapping. Can I make it so that users cannot select text in a Flex Text control?</p>
<p>Thanks.</p>
|
[
{
"answer_id": 154848,
"author": "Brandon",
"author_id": 23133,
"author_profile": "https://Stackoverflow.com/users/23133",
"pm_score": 0,
"selected": false,
"text": "<p>You can set the enabled property to \"false\" which disables user interaction. You may want to also change the disabledcolor property to your choice.</p>\n\n<pre><code>print(\"\n <mx:Text enabled=\"false\" disabledColor=\"0x000000\" text=Text\"/>\n\");\n</code></pre>\n"
},
{
"answer_id": 155055,
"author": "Paul Mignard",
"author_id": 3435,
"author_profile": "https://Stackoverflow.com/users/3435",
"pm_score": 4,
"selected": true,
"text": "<p>You could use the Text control and set the selectable property to false...</p>\n\n<pre><code> <mx:Text width=\"175\" selectable=\"false\" text=\"This is an example of a multiline text string in a Text control.\" />\n</code></pre>\n"
},
{
"answer_id": 2168175,
"author": "bugmenot",
"author_id": 262496,
"author_profile": "https://Stackoverflow.com/users/262496",
"pm_score": 2,
"selected": false,
"text": "<p>You can disable paste of more than 1 character by trapping the textInput event:</p>\n\n<pre>\n<code>\nprivate function onTextInput(e:flash.events.TextEvent):void\n{\n if (e.text.length > 1) \n e.preventDefault();\n}\n</code>\n</pre>\n"
}
] |
2008/09/30
|
[
"https://Stackoverflow.com/questions/154538",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1638/"
] |
Long story short, I need to put some text in my Flex application and I don't want users to be able to copy. I was going to use a label, but apparently labels do not support text wrapping. Can I make it so that users cannot select text in a Flex Text control?
Thanks.
|
You could use the Text control and set the selectable property to false...
```
<mx:Text width="175" selectable="false" text="This is an example of a multiline text string in a Text control." />
```
|
154,554 |
<p>I'm writing a simple web service using Microsoft Visual Web Developer 2005 (Express Edition), and the dynamically generated WSDL has a minOccurs="0" for all the parameters. </p>
<p>How do I get minOccurs="1" for the required parameters without resorting to creating a static WSDL file?</p>
<p>I need to do this <strong>using a ASP.NET Web Service</strong> (.NET v2). So, no WCF.</p>
|
[
{
"answer_id": 154650,
"author": "Jack B Nimble",
"author_id": 3800,
"author_profile": "https://Stackoverflow.com/users/3800",
"pm_score": 1,
"selected": false,
"text": "<p>from an msdn forum \n\"If you are creating a new web service, I highly recommend building the web service using the Windows Communication Foundation (WCF) instead of using ASP.NET Web Services.\nIn WCF, when you specify the data contract for your service you can speicfy that a given data member is required using the IsRequired property on the DataMemberAttribute.\n\"</p>\n\n<p>source - \n<a href=\"http://social.msdn.microsoft.com/forums/en-US/asmxandxml/thread/40ab5748-d32c-42a6-a47f-984ba18a1fe2/\" rel=\"nofollow noreferrer\">http://social.msdn.microsoft.com/forums/en-US/asmxandxml/thread/40ab5748-d32c-42a6-a47f-984ba18a1fe2/</a></p>\n"
},
{
"answer_id": 189317,
"author": "Panos",
"author_id": 8049,
"author_profile": "https://Stackoverflow.com/users/8049",
"pm_score": 2,
"selected": false,
"text": "<p>I think that the <code>XmlElement(IsNullable = true)</code> attribute will do the job:</p>\n\n<pre><code>using System.Xml.Serialization;\n\n[WebMethod]\npublic string MyService([XmlElement(IsNullable = true)] string arg)\n{\n return \"1\";\n}\n</code></pre>\n"
}
] |
2008/09/30
|
[
"https://Stackoverflow.com/questions/154554",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/23899/"
] |
I'm writing a simple web service using Microsoft Visual Web Developer 2005 (Express Edition), and the dynamically generated WSDL has a minOccurs="0" for all the parameters.
How do I get minOccurs="1" for the required parameters without resorting to creating a static WSDL file?
I need to do this **using a ASP.NET Web Service** (.NET v2). So, no WCF.
|
I think that the `XmlElement(IsNullable = true)` attribute will do the job:
```
using System.Xml.Serialization;
[WebMethod]
public string MyService([XmlElement(IsNullable = true)] string arg)
{
return "1";
}
```
|
154,577 |
<p>In terms of Java, when someone asks: </p>
<blockquote>
<p>what is polymorphism?</p>
</blockquote>
<p>Would <strong>overloading</strong> or <strong>overriding</strong> be an acceptable answer?</p>
<p>I think there is a bit more to it than that. </p>
<p><em>IF you had a abstract base class that defined a method with no implementation, and you defined that method in the sub class, is that still overridding?</em></p>
<p>I think <strong>overloading</strong> is not the right answer for sure.</p>
|
[
{
"answer_id": 154594,
"author": "Clyde",
"author_id": 945,
"author_profile": "https://Stackoverflow.com/users/945",
"pm_score": 2,
"selected": false,
"text": "<p>The term overloading refers to having multiple versions of something with the same name, usually methods with different parameter lists</p>\n\n<pre><code>public int DoSomething(int objectId) { ... }\npublic int DoSomething(string objectName) { ... }\n</code></pre>\n\n<p>So these functions might do the same thing but you have the option to call it with an ID, or a name. Has nothing to do with inheritance, abstract classes, etc.</p>\n\n<p>Overriding usually refers to polymorphism, as you described in your question</p>\n"
},
{
"answer_id": 154601,
"author": "Alex B",
"author_id": 6180,
"author_profile": "https://Stackoverflow.com/users/6180",
"pm_score": 4,
"selected": false,
"text": "<p>You are correct that overloading is not the answer.</p>\n\n<p>Neither is overriding. Overriding is the means by which you get polymorphism. Polymorphism is the ability for an object to vary behavior based on its type. This is best demonstrated when the caller of an object that exhibits polymorphism is unaware of what specific type the object is.</p>\n"
},
{
"answer_id": 154603,
"author": "Matt",
"author_id": 20630,
"author_profile": "https://Stackoverflow.com/users/20630",
"pm_score": 3,
"selected": false,
"text": "<p>overloading is when you define 2 methods with the same name but different parameters</p>\n\n<p>overriding is where you change the behavior of the base class via a function with the same name in a subclass.</p>\n\n<p>So Polymorphism is related to overriding but not really overloading.</p>\n\n<p>However if someone gave me a simple answer of \"overriding\" for the question \"What is polymorphism?\" I would ask for further explanation.</p>\n"
},
{
"answer_id": 154607,
"author": "mxg",
"author_id": 11157,
"author_profile": "https://Stackoverflow.com/users/11157",
"pm_score": 3,
"selected": false,
"text": "<p>Polymorphism is the ability for an object to appear in multiple forms. This involves using inheritance and virtual functions to build a family of objects which can be interchanged. The base class contains the prototypes of the virtual functions, possibly unimplemented or with default implementations as the application dictates, and the various derived classes each implements them differently to affect different behaviors.</p>\n"
},
{
"answer_id": 154615,
"author": "Brian G",
"author_id": 3208,
"author_profile": "https://Stackoverflow.com/users/3208",
"pm_score": 3,
"selected": false,
"text": "<p>The classic example, Dogs and cats are animals, animals have the method makeNoise. I can iterate through an array of animals calling makeNoise on them and expect that they would do there respective implementation.</p>\n\n<p>The calling code does not have to know what specific animal they are.</p>\n\n<p>Thats what I think of as polymorphism.</p>\n"
},
{
"answer_id": 154628,
"author": "Mark A. Nicolosi",
"author_id": 1103052,
"author_profile": "https://Stackoverflow.com/users/1103052",
"pm_score": 5,
"selected": false,
"text": "<p>Here's an example of polymorphism in pseudo-C#/Java:</p>\n\n<pre><code>class Animal\n{\n abstract string MakeNoise ();\n}\n\nclass Cat : Animal {\n string MakeNoise () {\n return \"Meow\";\n }\n}\n\nclass Dog : Animal {\n string MakeNoise () {\n return \"Bark\";\n }\n}\n\nMain () {\n Animal animal = Zoo.GetAnimal ();\n Console.WriteLine (animal.MakeNoise ());\n}\n</code></pre>\n\n<p>The Main function doesn't know the type of the animal and depends on a particular implementation's behavior of the MakeNoise() method.</p>\n\n<p>Edit: Looks like Brian beat me to the punch. Funny we used the same example. But the above code should help clarify the concepts.</p>\n"
},
{
"answer_id": 154631,
"author": "Patrick McElhaney",
"author_id": 437,
"author_profile": "https://Stackoverflow.com/users/437",
"pm_score": 6,
"selected": false,
"text": "<p>Both overriding and overloading are used to achieve polymorphism. </p>\n\n<p>You could have a method in a class\n that is <strong>overridden</strong> in one or\n more subclasses. The method does\n different things depending on which\n class was used to instantiate an object.</p>\n\n<pre><code> abstract class Beverage {\n boolean isAcceptableTemperature();\n }\n\n class Coffee extends Beverage {\n boolean isAcceptableTemperature() { \n return temperature > 70;\n }\n }\n\n class Wine extends Beverage {\n boolean isAcceptableTemperature() { \n return temperature < 10;\n }\n }\n</code></pre>\n\n<p>You could also have a method that is\n <strong>overloaded</strong> with two or more sets of arguments. The method does\n different things based on the\n type(s) of argument(s) passed.</p>\n\n<pre><code> class Server {\n public void pour (Coffee liquid) {\n new Cup().fillToTopWith(liquid);\n }\n\n public void pour (Wine liquid) {\n new WineGlass().fillHalfwayWith(liquid);\n }\n\n public void pour (Lemonade liquid, boolean ice) {\n Glass glass = new Glass();\n if (ice) {\n glass.fillToTopWith(new Ice());\n }\n glass.fillToTopWith(liquid);\n }\n }\n</code></pre>\n"
},
{
"answer_id": 154646,
"author": "Jason Peacock",
"author_id": 18381,
"author_profile": "https://Stackoverflow.com/users/18381",
"pm_score": 2,
"selected": false,
"text": "<p>Neither:</p>\n\n<p>Overloading is when you have the same function name that takes different parameters.</p>\n\n<p>Overriding is when a child class replaces a parent's method with one of its own (this in iteself does not constitute polymorphism).</p>\n\n<p>Polymorphism is late binding, e.g. the base class (parent) methods are being called but not until runtime does the application know what the actual object is - it may be a child class whose methods are different. This is because any child class can be used where a base class is defined.</p>\n\n<p>In Java you see polymorphism a lot with the collections library:</p>\n\n<pre><code>int countStuff(List stuff) {\n return stuff.size();\n}\n</code></pre>\n\n<p>List is the base class, the compiler has no clue if you're counting a linked list, vector, array, or a custom list implementation, as long as it acts like a List:</p>\n\n<pre><code>List myStuff = new MyTotallyAwesomeList();\nint result = countStuff(myStuff);\n</code></pre>\n\n<p>If you were overloading you'd have:</p>\n\n<pre><code>int countStuff(LinkedList stuff) {...}\nint countStuff(ArrayList stuff) {...}\nint countStuff(MyTotallyAwesomeList stuff) {...}\netc...\n</code></pre>\n\n<p>and the correct version of countStuff() would be picked by the compiler to match the parameters.</p>\n"
},
{
"answer_id": 154668,
"author": "Lorenzo Boccaccia",
"author_id": 2273540,
"author_profile": "https://Stackoverflow.com/users/2273540",
"pm_score": 0,
"selected": false,
"text": "<p>Polymorphism relates to the ability of a language to have different object treated uniformly by using a single interfaces; as such it is related to overriding, so the interface (or the base class) is polymorphic, the implementor is the object which overrides (two faces of the same medal)</p>\n\n<p>anyway, the difference between the two terms is better explained using other languages, such as c++: a polymorphic object in c++ behaves as the java counterpart if the base function is virtual, but if the method is not virtual the code jump is resolved <em>statically</em>, and the true type not checked at runtime so, polymorphism include the ability for an object to behave differently depending on the interface used to access it; let me make an example in pseudocode:</p>\n\n<pre><code>class animal {\n public void makeRumor(){\n print(\"thump\");\n }\n}\nclass dog extends animal {\n public void makeRumor(){\n print(\"woff\");\n }\n}\n\nanimal a = new dog();\ndog b = new dog();\n\na.makeRumor() -> prints thump\nb.makeRumor() -> prints woff\n</code></pre>\n\n<p>(supposing that makeRumor is NOT virtual)</p>\n\n<p>java doesn't truly offer this level of polymorphism (called also object slicing). </p>\n\n<p>animal a = new dog();\n dog b = new dog();</p>\n\n<pre><code>a.makeRumor() -> prints thump\nb.makeRumor() -> prints woff\n</code></pre>\n\n<p>on both case it will only print woff..\nsince a and b is refering to class dog</p>\n"
},
{
"answer_id": 154673,
"author": "The Digital Gabeg",
"author_id": 12782,
"author_profile": "https://Stackoverflow.com/users/12782",
"pm_score": 7,
"selected": false,
"text": "<p><strong>Polymorphism</strong> is the ability of a class instance to behave as if it were an instance of another class in its inheritance tree, most often one of its ancestor classes. For example, in Java all classes inherit from Object. Therefore, you can create a variable of type Object and assign to it an instance of any class.</p>\n\n<p>An <strong>override</strong> is a type of function which occurs in a class which inherits from another class. An override function \"replaces\" a function inherited from the base class, but does so in such a way that it is called even when an instance of its class is pretending to be a different type through polymorphism. Referring to the previous example, you could define your own class and override the toString() function. Because this function is inherited from Object, it will still be available if you copy an instance of this class into an Object-type variable. Normally, if you call toString() on your class while it is pretending to be an Object, the version of toString which will actually fire is the one defined on Object itself. However, because the function is an override, the definition of toString() from your class is used even when the class instance's true type is hidden behind polymorphism.</p>\n\n<p><strong>Overloading</strong> is the action of defining multiple methods with the same name, but with different parameters. It is unrelated to either overriding or polymorphism.</p>\n"
},
{
"answer_id": 154675,
"author": "Peter Meyer",
"author_id": 1875,
"author_profile": "https://Stackoverflow.com/users/1875",
"pm_score": 4,
"selected": false,
"text": "<p>Specifically saying overloading or overriding doesn't give the full picture. Polymorphism is simply the ability of an object to specialize its behavior based on its type. </p>\n\n<p>I would disagree with some of the answers here in that overloading is a form of polymorphism (parametric polymorphism) in the case that a method with the same name can behave differently give different parameter types. A good example is operator overloading. You can define \"+\" to accept different types of parameters -- say strings or int's -- and based on those types, \"+\" will behave differently.</p>\n\n<p>Polymorphism also includes inheritance and overriding methods, though they can be abstract or virtual in the base type. In terms of inheritance-based polymorphism, Java only supports single class inheritance limiting it polymorphic behavior to that of a single chain of base types. Java does support implementation of multiple interfaces which is yet another form of polymorphic behavior.</p>\n"
},
{
"answer_id": 154939,
"author": "Chris Cudmore",
"author_id": 18907,
"author_profile": "https://Stackoverflow.com/users/18907",
"pm_score": 11,
"selected": true,
"text": "<p>The clearest way to express polymorphism is via an abstract base class (or interface)</p>\n\n<pre><code>public abstract class Human{\n ...\n public abstract void goPee();\n}\n</code></pre>\n\n<p>This class is abstract because the <code>goPee()</code> method is not definable for Humans. It is only definable for the subclasses Male and Female. Also, Human is an abstract concept — You cannot create a human that is neither Male nor Female. It’s got to be one or the other.</p>\n\n<p>So we defer the implementation by using the abstract class.</p>\n\n<pre><code>public class Male extends Human{\n...\n @Override\n public void goPee(){\n System.out.println(\"Stand Up\");\n }\n}\n</code></pre>\n\n<p>and</p>\n\n<pre><code>public class Female extends Human{\n...\n @Override\n public void goPee(){\n System.out.println(\"Sit Down\");\n }\n}\n</code></pre>\n\n<p>Now we can tell an entire room full of Humans to go pee.</p>\n\n<pre><code>public static void main(String[] args){\n ArrayList<Human> group = new ArrayList<Human>();\n group.add(new Male());\n group.add(new Female());\n // ... add more...\n\n // tell the class to take a pee break\n for (Human person : group) person.goPee();\n}\n</code></pre>\n\n<p>Running this would yield:</p>\n\n<pre><code>Stand Up\nSit Down\n...\n</code></pre>\n"
},
{
"answer_id": 4487013,
"author": "BillC",
"author_id": 548221,
"author_profile": "https://Stackoverflow.com/users/548221",
"pm_score": 3,
"selected": false,
"text": "<p>Polymorphism simply means \"Many Forms\".</p>\n\n<p>It does not REQUIRE inheritance to achieve...as interface implementation, which is not inheritance at all, serves polymorphic needs. Arguably, interface implementation serves polymorphic needs \"Better\" than inheritance.</p>\n\n<p>For example, would you create a super-class to describe all things that can fly? I should think not. You would be be best served to create an interface that describes flight and leave it at that.</p>\n\n<p>So, since interfaces describe behavior, and method names describe behavior (to the programmer), it is not too far of a stretch to consider method overloading as a lesser form of polymorphism.</p>\n"
},
{
"answer_id": 9431105,
"author": "user1154840",
"author_id": 1154840,
"author_profile": "https://Stackoverflow.com/users/1154840",
"pm_score": 2,
"selected": false,
"text": "<p>I think guys your are mixing concepts. <em>Polymorphism</em> is the ability of an object to behave differently at run time. For achieving this, you need two requisites:</p>\n\n<ol>\n<li><em>Late Binding</em></li>\n<li><em>Inheritance.</em></li>\n</ol>\n\n<p>Having said that <em>overloading</em> means something different to <em>overriding</em> depending on the language you are using. For example in Java does not exist <em>overriding</em> but <em>overloading</em>. <em>Overloaded</em> methods with different signature to its base class are available in the subclass. Otherwise they would be <em>overridden</em> (please, see that I mean now the fact of there is no way to call your base class method from outside the object).</p>\n\n<p>However in C++ that is not so. Any <em>overloaded</em> method, independently whether the signature is the same or not (diffrrent amount, different type) is as well <em>overridden</em>. That is to day, the base class' method is no longer available in the subclass when being called from outside the subclass object, obviously.</p>\n\n<p>So the answer is when talking about Java use <em>overloading</em>. In any other language may be different as it happens in c++</p>\n"
},
{
"answer_id": 12371564,
"author": "Rajan",
"author_id": 1506709,
"author_profile": "https://Stackoverflow.com/users/1506709",
"pm_score": 2,
"selected": false,
"text": "<p>Polymorphism is more likely as far as it's <em>meaning</em> is concerned ... to OVERRIDING in java</p>\n\n<p>It's all about different behavior of the SAME object in different situations(In programming way ... you can call different ARGUMENTS) </p>\n\n<p>I think the example below will help you to understand ... Though it's not PURE java code ...</p>\n\n<pre><code> public void See(Friend)\n {\n System.out.println(\"Talk\");\n }\n</code></pre>\n\n<p>But if we change the ARGUMENT ... the BEHAVIOR will be changed ...</p>\n\n<pre><code> public void See(Enemy)\n {\n System.out.println(\"Run\");\n }\n</code></pre>\n\n<p>The Person(here the \"Object\") is same ...</p>\n"
},
{
"answer_id": 12995156,
"author": "manoj",
"author_id": 1762604,
"author_profile": "https://Stackoverflow.com/users/1762604",
"pm_score": 6,
"selected": false,
"text": "<p>Polymorphism means more than one form, same object performing different operations according to the requirement.</p>\n\n<p>Polymorphism can be achieved by using two ways, those are</p>\n\n<ol>\n<li>Method overriding</li>\n<li>Method overloading</li>\n</ol>\n\n<p><em>Method overloading</em> means writing two or more methods in the same class by using same method name, but the passing parameters is different.</p>\n\n<p><em>Method overriding</em> means we use the method names in the different classes,that means parent class method is used in the child class.</p>\n\n<p>In Java to achieve polymorphism a super class reference variable can hold the sub class object.</p>\n\n<p>To achieve the polymorphism every developer must use the same method names in the project.</p>\n"
},
{
"answer_id": 16236028,
"author": "Genjuro",
"author_id": 978769,
"author_profile": "https://Stackoverflow.com/users/978769",
"pm_score": 2,
"selected": false,
"text": "<p>overriding is more like hiding an inherited method by declaring a method with the same name and signature as the upper level method (super method), this adds a polymorphic behaviour to the class .\nin other words the decision to choose wich level method to be called will be made at run time not on compile time .\nthis leads to the concept of interface and implementation .</p>\n"
},
{
"answer_id": 18818192,
"author": "Desolator",
"author_id": 326904,
"author_profile": "https://Stackoverflow.com/users/326904",
"pm_score": 2,
"selected": false,
"text": "<p>Polymorphism is a multiple implementations of an object or you could say multiple forms of an object. lets say you have class <code>Animals</code> as the abstract base class and it has a method called <code>movement()</code> which defines the way that the animal moves. Now in reality we have different kinds of animals and they move differently as well some of them with 2 legs, others with 4 and some with no legs, etc.. To define different <code>movement()</code> of each animal on earth, we need to apply polymorphism. However, you need to define more classes i.e. class <code>Dogs</code> <code>Cats</code> <code>Fish</code> etc. Then you need to extend those classes from the base class <code>Animals</code> and override its method <code>movement()</code> with a new movement functionality based on each animal you have. You can also use <code>Interfaces</code> to achieve that. The keyword in here is overriding, overloading is different and is not considered as polymorphism. with overloading you can define multiple methods \"with same name\" but with different parameters on same object or class.</p>\n"
},
{
"answer_id": 31455175,
"author": "bharanitharan",
"author_id": 358099,
"author_profile": "https://Stackoverflow.com/users/358099",
"pm_score": 1,
"selected": false,
"text": "<pre><code>import java.io.IOException;\n\nclass Super {\n\n protected Super getClassName(Super s) throws IOException {\n System.out.println(this.getClass().getSimpleName() + \" - I'm parent\");\n return null;\n }\n\n}\n\nclass SubOne extends Super {\n\n @Override\n protected Super getClassName(Super s) {\n System.out.println(this.getClass().getSimpleName() + \" - I'm Perfect Overriding\");\n return null;\n }\n\n}\n\nclass SubTwo extends Super {\n\n @Override\n protected Super getClassName(Super s) throws NullPointerException {\n System.out.println(this.getClass().getSimpleName() + \" - I'm Overriding and Throwing Runtime Exception\");\n return null;\n }\n\n}\n\nclass SubThree extends Super {\n\n @Override\n protected SubThree getClassName(Super s) {\n System.out.println(this.getClass().getSimpleName()+ \" - I'm Overriding and Returning SubClass Type\");\n return null;\n }\n\n}\n\nclass SubFour extends Super {\n\n @Override\n protected Super getClassName(Super s) throws IOException {\n System.out.println(this.getClass().getSimpleName()+ \" - I'm Overriding and Throwing Narrower Exception \");\n return null;\n }\n\n}\n\nclass SubFive extends Super {\n\n @Override\n public Super getClassName(Super s) {\n System.out.println(this.getClass().getSimpleName()+ \" - I'm Overriding and have broader Access \");\n return null;\n }\n\n}\n\nclass SubSix extends Super {\n\n public Super getClassName(Super s, String ol) {\n System.out.println(this.getClass().getSimpleName()+ \" - I'm Perfect Overloading \");\n return null;\n }\n\n}\n\nclass SubSeven extends Super {\n\n public Super getClassName(SubSeven s) {\n System.out.println(this.getClass().getSimpleName()+ \" - I'm Perfect Overloading because Method signature (Argument) changed.\");\n return null;\n }\n\n}\n\npublic class Test{\n\n public static void main(String[] args) throws Exception {\n\n System.out.println(\"Overriding\\n\");\n\n Super s1 = new SubOne(); s1.getClassName(null);\n\n Super s2 = new SubTwo(); s2.getClassName(null);\n\n Super s3 = new SubThree(); s3.getClassName(null);\n\n Super s4 = new SubFour(); s4.getClassName(null);\n\n Super s5 = new SubFive(); s5.getClassName(null);\n\n System.out.println(\"Overloading\\n\");\n\n SubSix s6 = new SubSix(); s6.getClassName(null, null);\n\n s6 = new SubSix(); s6.getClassName(null);\n\n SubSeven s7 = new SubSeven(); s7.getClassName(s7);\n\n s7 = new SubSeven(); s7.getClassName(new Super());\n\n }\n}\n</code></pre>\n"
},
{
"answer_id": 39532917,
"author": "Ravindra babu",
"author_id": 4999394,
"author_profile": "https://Stackoverflow.com/users/4999394",
"pm_score": 2,
"selected": false,
"text": "<blockquote>\n <p>what is polymorphism?</p>\n</blockquote>\n\n<p>From java <a href=\"https://docs.oracle.com/javase/tutorial/java/IandI/polymorphism.html\" rel=\"nofollow\">tutorial</a></p>\n\n<p>The dictionary definition of polymorphism refers to a principle in biology in which an organism or species can have many different forms or stages. This principle can also be applied to object-oriented programming and languages like the Java language. <strong><em>Subclasses of a class can define their own unique behaviors and yet share some of the same functionality of the parent class.</em></strong></p>\n\n<p>By considering the examples and definition, <strong><em>overriding</em></strong> should be accepted answer. </p>\n\n<p>Regarding your second query:</p>\n\n<blockquote>\n <p>IF you had a abstract base class that defined a method with no implementation, and you defined that method in the sub class, is that still overridding?</p>\n</blockquote>\n\n<p>It should be called overriding. </p>\n\n<p>Have a look at this example to understand different types of overriding. </p>\n\n<ol>\n<li>Base class provides no implementation and sub-class has to override complete method - (abstract)</li>\n<li>Base class provides default implementation and sub-class can change the behaviour</li>\n<li>Sub-class adds extension to base class implementation by calling <code>super.methodName()</code> as first statement</li>\n<li>Base class defines structure of the algorithm (Template method) and sub-class will override a part of algorithm</li>\n</ol>\n\n<p>code snippet:</p>\n\n<pre><code>import java.util.HashMap;\n\nabstract class Game implements Runnable{\n\n protected boolean runGame = true;\n protected Player player1 = null;\n protected Player player2 = null;\n protected Player currentPlayer = null;\n\n public Game(){\n player1 = new Player(\"Player 1\");\n player2 = new Player(\"Player 2\");\n currentPlayer = player1;\n initializeGame();\n }\n\n /* Type 1: Let subclass define own implementation. Base class defines abstract method to force\n sub-classes to define implementation \n */\n\n protected abstract void initializeGame();\n\n /* Type 2: Sub-class can change the behaviour. If not, base class behaviour is applicable */\n protected void logTimeBetweenMoves(Player player){\n System.out.println(\"Base class: Move Duration: player.PlayerActTime - player.MoveShownTime\");\n }\n\n /* Type 3: Base class provides implementation. Sub-class can enhance base class implementation by calling\n super.methodName() in first line of the child class method and specific implementation later */\n protected void logGameStatistics(){\n System.out.println(\"Base class: logGameStatistics:\");\n }\n /* Type 4: Template method: Structure of base class can't be changed but sub-class can some part of behaviour */\n protected void runGame() throws Exception{\n System.out.println(\"Base class: Defining the flow for Game:\"); \n while ( runGame) {\n /*\n 1. Set current player\n 2. Get Player Move\n */\n validatePlayerMove(currentPlayer); \n logTimeBetweenMoves(currentPlayer);\n Thread.sleep(500);\n setNextPlayer();\n }\n logGameStatistics();\n }\n /* sub-part of the template method, which define child class behaviour */\n protected abstract void validatePlayerMove(Player p);\n\n protected void setRunGame(boolean status){\n this.runGame = status;\n }\n public void setCurrentPlayer(Player p){\n this.currentPlayer = p;\n }\n public void setNextPlayer(){\n if ( currentPlayer == player1) {\n currentPlayer = player2;\n }else{\n currentPlayer = player1;\n }\n }\n public void run(){\n try{\n runGame();\n }catch(Exception err){\n err.printStackTrace();\n }\n }\n}\n\nclass Player{\n String name;\n Player(String name){\n this.name = name;\n }\n public String getName(){\n return name;\n }\n}\n\n/* Concrete Game implementation */\nclass Chess extends Game{\n public Chess(){\n super();\n }\n public void initializeGame(){\n System.out.println(\"Child class: Initialized Chess game\");\n }\n protected void validatePlayerMove(Player p){\n System.out.println(\"Child class: Validate Chess move:\"+p.getName());\n }\n protected void logGameStatistics(){\n super.logGameStatistics();\n System.out.println(\"Child class: Add Chess specific logGameStatistics:\");\n }\n}\nclass TicTacToe extends Game{\n public TicTacToe(){\n super();\n }\n public void initializeGame(){\n System.out.println(\"Child class: Initialized TicTacToe game\");\n }\n protected void validatePlayerMove(Player p){\n System.out.println(\"Child class: Validate TicTacToe move:\"+p.getName());\n }\n}\n\npublic class Polymorphism{\n public static void main(String args[]){\n try{\n\n Game game = new Chess();\n Thread t1 = new Thread(game);\n t1.start();\n Thread.sleep(1000);\n game.setRunGame(false);\n Thread.sleep(1000);\n\n game = new TicTacToe();\n Thread t2 = new Thread(game);\n t2.start();\n Thread.sleep(1000);\n game.setRunGame(false);\n\n }catch(Exception err){\n err.printStackTrace();\n } \n }\n}\n</code></pre>\n\n<p>output:</p>\n\n<pre><code>Child class: Initialized Chess game\nBase class: Defining the flow for Game:\nChild class: Validate Chess move:Player 1\nBase class: Move Duration: player.PlayerActTime - player.MoveShownTime\nChild class: Validate Chess move:Player 2\nBase class: Move Duration: player.PlayerActTime - player.MoveShownTime\nBase class: logGameStatistics:\nChild class: Add Chess specific logGameStatistics:\nChild class: Initialized TicTacToe game\nBase class: Defining the flow for Game:\nChild class: Validate TicTacToe move:Player 1\nBase class: Move Duration: player.PlayerActTime - player.MoveShownTime\nChild class: Validate TicTacToe move:Player 2\nBase class: Move Duration: player.PlayerActTime - player.MoveShownTime\nBase class: logGameStatistics:\n</code></pre>\n"
},
{
"answer_id": 50202481,
"author": "Developer",
"author_id": 5465732,
"author_profile": "https://Stackoverflow.com/users/5465732",
"pm_score": 3,
"selected": false,
"text": "<p>Although, Polymorphism is already explained in great details in this post but I would like put more emphasis on why part of it. </p>\n\n<blockquote>\n <p>Why Polymorphism is so important in any OOP language.</p>\n</blockquote>\n\n<p>Let’s try to build a simple application for a TV with and without Inheritance/Polymorphism. Post each version of the application, we do a small retrospective.</p>\n\n<p>Supposing, you are a software engineer at a TV company and you are asked to write software for Volume, Brightness and Colour controllers to increase and decrease their values on user command.</p>\n\n<p>You start with writing classes for each of these features by adding</p>\n\n<ol>\n<li>set:- To set a value of a controller.(Supposing this has controller specific code)</li>\n<li>get:- To get a value of a controller.(Supposing this has controller specific code)</li>\n<li>adjust:- To validate the input and setting a controller.(Generic validations.. independent of controllers)</li>\n<li>user input mapping with controllers :- To get user input and invoking controllers accordingly.</li>\n</ol>\n\n<blockquote>\n <p>Application Version 1</p>\n</blockquote>\n\n<pre><code>import java.util.Scanner; \nclass VolumeControllerV1 {\n private int value;\n int get() {\n return value;\n }\n void set(int value) {\n System.out.println(\"Old value of VolumeController \\t\"+this.value);\n this.value = value;\n System.out.println(\"New value of VolumeController \\t\"+this.value);\n }\n void adjust(int value) {\n int temp = this.get();\n if(((value > 0) && (temp >= 100)) || ((value < 0) && (temp <= 0))) {\n System.out.println(\"Can not adjust any further\");\n return;\n }\n this.set(temp + value);\n }\n}\nclass BrightnessControllerV1 {\n private int value;\n int get() {\n return value;\n }\n void set(int value) {\n System.out.println(\"Old value of BrightnessController \\t\"+this.value);\n this.value = value;\n System.out.println(\"New value of BrightnessController \\t\"+this.value);\n }\n void adjust(int value) {\n int temp = this.get();\n if(((value > 0) && (temp >= 100)) || ((value < 0) && (temp <= 0))) {\n System.out.println(\"Can not adjust any further\");\n return;\n }\n this.set(temp + value);\n }\n}\nclass ColourControllerV1 {\n private int value;\n int get() {\n return value;\n }\n void set(int value) {\n System.out.println(\"Old value of ColourController \\t\"+this.value);\n this.value = value;\n System.out.println(\"New value of ColourController \\t\"+this.value);\n }\n void adjust(int value) {\n int temp = this.get();\n if(((value > 0) && (temp >= 100)) || ((value < 0) && (temp <= 0))) {\n System.out.println(\"Can not adjust any further\");\n return;\n }\n this.set(temp + value);\n }\n}\n\n/*\n * There can be n number of controllers\n * */\npublic class TvApplicationV1 {\n public static void main(String[] args) {\n VolumeControllerV1 volumeControllerV1 = new VolumeControllerV1();\n BrightnessControllerV1 brightnessControllerV1 = new BrightnessControllerV1();\n ColourControllerV1 colourControllerV1 = new ColourControllerV1();\n\n\n OUTER: while(true) {\n Scanner sc=new Scanner(System.in);\n System.out.println(\" Enter your option \\n Press 1 to increase volume \\n Press 2 to decrease volume\");\n System.out.println(\" Press 3 to increase brightness \\n Press 4 to decrease brightness\");\n System.out.println(\" Press 5 to increase color \\n Press 6 to decrease color\");\n System.out.println(\"Press any other Button to shutdown\");\n int button = sc.nextInt();\n switch (button) {\n case 1: {\n volumeControllerV1.adjust(5);\n break;\n }\n case 2: {\n volumeControllerV1.adjust(-5);\n break;\n }\n case 3: {\n brightnessControllerV1.adjust(5);\n break;\n }\n case 4: {\n brightnessControllerV1.adjust(-5);\n break;\n }\n case 5: {\n colourControllerV1.adjust(5);\n break;\n }\n case 6: {\n colourControllerV1.adjust(-5);\n break;\n }\n default:\n System.out.println(\"Shutting down...........\");\n break OUTER;\n }\n\n }\n }\n}\n</code></pre>\n\n<p>Now you have our first version of working application ready to be deployed. Time to analyze the work done so far.</p>\n\n<blockquote>\n <p>Issues in TV Application Version 1</p>\n</blockquote>\n\n<ol>\n<li>Adjust(int value) code is duplicate in all three classes. You would like to minimize the code duplicity. (But you did not think of common code and moving it to some super class to avoid duplicate code)</li>\n</ol>\n\n<p>You decide to live with that as long as your application works as expected.</p>\n\n<blockquote>\n <p>After sometimes, your Boss comes back to you and asks you to add reset functionality to the existing application. Reset would set all 3 three controller to their respective default values.</p>\n</blockquote>\n\n<p>You start writing a new class (ResetFunctionV2) for the new functionality and map the user input mapping code for this new feature.</p>\n\n<blockquote>\n <p>Application Version 2</p>\n</blockquote>\n\n<pre><code>import java.util.Scanner;\nclass VolumeControllerV2 {\n\n private int defaultValue = 25;\n private int value;\n\n int getDefaultValue() {\n return defaultValue;\n }\n int get() {\n return value;\n }\n void set(int value) {\n System.out.println(\"Old value of VolumeController \\t\"+this.value);\n this.value = value;\n System.out.println(\"New value of VolumeController \\t\"+this.value);\n }\n void adjust(int value) {\n int temp = this.get();\n if(((value > 0) && (temp >= 100)) || ((value < 0) && (temp <= 0))) {\n System.out.println(\"Can not adjust any further\");\n return;\n }\n this.set(temp + value);\n }\n}\nclass BrightnessControllerV2 {\n\n private int defaultValue = 50;\n private int value;\n int get() {\n return value;\n }\n int getDefaultValue() {\n return defaultValue;\n }\n void set(int value) {\n System.out.println(\"Old value of BrightnessController \\t\"+this.value);\n this.value = value;\n System.out.println(\"New value of BrightnessController \\t\"+this.value);\n }\n void adjust(int value) {\n int temp = this.get();\n if(((value > 0) && (temp >= 100)) || ((value < 0) && (temp <= 0))) {\n System.out.println(\"Can not adjust any further\");\n return;\n }\n this.set(temp + value);\n }\n}\nclass ColourControllerV2 {\n\n private int defaultValue = 40;\n private int value;\n int get() {\n return value;\n }\n int getDefaultValue() {\n return defaultValue;\n }\n void set(int value) {\n System.out.println(\"Old value of ColourController \\t\"+this.value);\n this.value = value;\n System.out.println(\"New value of ColourController \\t\"+this.value);\n }\n void adjust(int value) {\n int temp = this.get();\n if(((value > 0) && (temp >= 100)) || ((value < 0) && (temp <= 0))) {\n System.out.println(\"Can not adjust any further\");\n return;\n }\n this.set(temp + value);\n }\n}\n\nclass ResetFunctionV2 {\n\n private VolumeControllerV2 volumeControllerV2 ;\n private BrightnessControllerV2 brightnessControllerV2;\n private ColourControllerV2 colourControllerV2;\n\n ResetFunctionV2(VolumeControllerV2 volumeControllerV2, BrightnessControllerV2 brightnessControllerV2, ColourControllerV2 colourControllerV2) {\n this.volumeControllerV2 = volumeControllerV2;\n this.brightnessControllerV2 = brightnessControllerV2;\n this.colourControllerV2 = colourControllerV2;\n }\n void onReset() {\n volumeControllerV2.set(volumeControllerV2.getDefaultValue());\n brightnessControllerV2.set(brightnessControllerV2.getDefaultValue());\n colourControllerV2.set(colourControllerV2.getDefaultValue());\n }\n}\n/*\n * so on\n * There can be n number of controllers\n *\n * */\npublic class TvApplicationV2 {\n public static void main(String[] args) {\n VolumeControllerV2 volumeControllerV2 = new VolumeControllerV2();\n BrightnessControllerV2 brightnessControllerV2 = new BrightnessControllerV2();\n ColourControllerV2 colourControllerV2 = new ColourControllerV2();\n\n ResetFunctionV2 resetFunctionV2 = new ResetFunctionV2(volumeControllerV2, brightnessControllerV2, colourControllerV2);\n\n OUTER: while(true) {\n Scanner sc=new Scanner(System.in);\n System.out.println(\" Enter your option \\n Press 1 to increase volume \\n Press 2 to decrease volume\");\n System.out.println(\" Press 3 to increase brightness \\n Press 4 to decrease brightness\");\n System.out.println(\" Press 5 to increase color \\n Press 6 to decrease color\");\n System.out.println(\" Press 7 to reset TV \\n Press any other Button to shutdown\");\n int button = sc.nextInt();\n switch (button) {\n case 1: {\n volumeControllerV2.adjust(5);\n break;\n }\n case 2: {\n volumeControllerV2.adjust(-5);\n break;\n }\n case 3: {\n brightnessControllerV2.adjust(5);\n break;\n }\n case 4: {\n brightnessControllerV2.adjust(-5);\n break;\n }\n case 5: {\n colourControllerV2.adjust(5);\n break;\n }\n case 6: {\n colourControllerV2.adjust(-5);\n break;\n }\n case 7: {\n resetFunctionV2.onReset();\n break;\n }\n default:\n System.out.println(\"Shutting down...........\");\n break OUTER;\n }\n\n }\n }\n}\n</code></pre>\n\n<p>So you have your application ready with Reset feature. But, now you start realizing that </p>\n\n<blockquote>\n <p>Issues in TV Application Version 2</p>\n</blockquote>\n\n<ol>\n<li>If a new controller is introduced to the product, you have to change Reset feature code.</li>\n<li>If the count of the controller grows very high, you would have issue in holding the references of the controllers.</li>\n<li>Reset feature code is tightly coupled with all the controllers Class’s code(to get and set default values).</li>\n<li>Reset feature class (ResetFunctionV2) can access other method of the Controller class’s (adjust) which is undesirable.</li>\n</ol>\n\n<blockquote>\n <p>At the same time, You hear from you Boss that you might have to add a feature wherein each of controllers, on start-up, needs to check for the latest version of driver from company’s hosted driver repository via internet.</p>\n</blockquote>\n\n<p>Now you start thinking that this new feature to be added resembles with Reset feature and Issues of Application (V2) will be multiplied if you don’t re-factor your application.</p>\n\n<p>You start thinking of using inheritance so that you can take advantage from polymorphic ability of JAVA and you add a new abstract class (ControllerV3) to</p>\n\n<ol>\n<li>Declare the signature of get and set method.</li>\n<li>Contain adjust method implementation which was earlier replicated among all the controllers.</li>\n<li>Declare setDefault method so that reset feature can be easily implemented leveraging Polymorphism.</li>\n</ol>\n\n<p>With these improvements, you have version 3 of your TV application ready with you.</p>\n\n<blockquote>\n <p>Application Version 3</p>\n</blockquote>\n\n<pre><code>import java.util.ArrayList;\nimport java.util.List;\nimport java.util.Scanner;\n\nabstract class ControllerV3 {\n abstract void set(int value);\n abstract int get();\n void adjust(int value) {\n int temp = this.get();\n if(((value > 0) && (temp >= 100)) || ((value < 0) && (temp <= 0))) {\n System.out.println(\"Can not adjust any further\");\n return;\n }\n this.set(temp + value);\n }\n abstract void setDefault();\n}\nclass VolumeControllerV3 extends ControllerV3 {\n\n private int defaultValue = 25;\n private int value;\n\n public void setDefault() {\n set(defaultValue);\n }\n int get() {\n return value;\n }\n void set(int value) {\n System.out.println(\"Old value of VolumeController \\t\"+this.value);\n this.value = value;\n System.out.println(\"New value of VolumeController \\t\"+this.value);\n }\n}\nclass BrightnessControllerV3 extends ControllerV3 {\n\n private int defaultValue = 50;\n private int value;\n\n public void setDefault() {\n set(defaultValue);\n }\n int get() {\n return value;\n }\n void set(int value) {\n System.out.println(\"Old value of BrightnessController \\t\"+this.value);\n this.value = value;\n System.out.println(\"New value of BrightnessController \\t\"+this.value);\n }\n}\nclass ColourControllerV3 extends ControllerV3 {\n\n private int defaultValue = 40;\n private int value;\n\n public void setDefault() {\n set(defaultValue);\n }\n int get() {\n return value;\n }\n void set(int value) {\n System.out.println(\"Old value of ColourController \\t\"+this.value);\n this.value = value;\n System.out.println(\"New value of ColourController \\t\"+this.value);\n }\n}\n\nclass ResetFunctionV3 {\n\n private List<ControllerV3> controllers = null;\n\n ResetFunctionV3(List<ControllerV3> controllers) {\n this.controllers = controllers;\n }\n void onReset() {\n for (ControllerV3 controllerV3 :this.controllers) {\n controllerV3.setDefault();\n }\n }\n}\n/*\n * so on\n * There can be n number of controllers\n *\n * */\npublic class TvApplicationV3 {\n public static void main(String[] args) {\n VolumeControllerV3 volumeControllerV3 = new VolumeControllerV3();\n BrightnessControllerV3 brightnessControllerV3 = new BrightnessControllerV3();\n ColourControllerV3 colourControllerV3 = new ColourControllerV3();\n\n List<ControllerV3> controllerV3s = new ArrayList<>();\n controllerV3s.add(volumeControllerV3);\n controllerV3s.add(brightnessControllerV3);\n controllerV3s.add(colourControllerV3);\n\n ResetFunctionV3 resetFunctionV3 = new ResetFunctionV3(controllerV3s);\n\n OUTER: while(true) {\n Scanner sc=new Scanner(System.in);\n System.out.println(\" Enter your option \\n Press 1 to increase volume \\n Press 2 to decrease volume\");\n System.out.println(\" Press 3 to increase brightness \\n Press 4 to decrease brightness\");\n System.out.println(\" Press 5 to increase color \\n Press 6 to decrease color\");\n System.out.println(\" Press 7 to reset TV \\n Press any other Button to shutdown\");\n int button = sc.nextInt();\n switch (button) {\n case 1: {\n volumeControllerV3.adjust(5);\n break;\n }\n case 2: {\n volumeControllerV3.adjust(-5);\n break;\n }\n case 3: {\n brightnessControllerV3.adjust(5);\n break;\n }\n case 4: {\n brightnessControllerV3.adjust(-5);\n break;\n }\n case 5: {\n colourControllerV3.adjust(5);\n break;\n }\n case 6: {\n colourControllerV3.adjust(-5);\n break;\n }\n case 7: {\n resetFunctionV3.onReset();\n break;\n }\n default:\n System.out.println(\"Shutting down...........\");\n break OUTER;\n }\n\n }\n }\n}\n</code></pre>\n\n<p>Although most of the Issue listed in issue list of V2 were addressed except</p>\n\n<blockquote>\n <p>Issues in TV Application Version 3</p>\n</blockquote>\n\n<ol>\n<li>Reset feature class (ResetFunctionV3) can access other method of the Controller class’s (adjust) which is undesirable.</li>\n</ol>\n\n<p>Again, you think of solving this problem, as now you have another feature (driver update at startup) to implement as well. If you don’t fix it, it will get replicated to new features as well.</p>\n\n<p>So you divide the contract defined in abstract class and write 2 interfaces for</p>\n\n<ol>\n<li>Reset feature.</li>\n<li>Driver Update.</li>\n</ol>\n\n<p>And have your 1st concrete class implement them as below</p>\n\n<blockquote>\n <p>Application Version 4</p>\n</blockquote>\n\n<pre><code>import java.util.ArrayList;\nimport java.util.List;\nimport java.util.Scanner;\n\ninterface OnReset {\n void setDefault();\n}\ninterface OnStart {\n void checkForDriverUpdate();\n}\nabstract class ControllerV4 implements OnReset,OnStart {\n abstract void set(int value);\n abstract int get();\n void adjust(int value) {\n int temp = this.get();\n if(((value > 0) && (temp >= 100)) || ((value < 0) && (temp <= 0))) {\n System.out.println(\"Can not adjust any further\");\n return;\n }\n this.set(temp + value);\n }\n}\n\nclass VolumeControllerV4 extends ControllerV4 {\n\n private int defaultValue = 25;\n private int value;\n @Override\n int get() {\n return value;\n }\n void set(int value) {\n System.out.println(\"Old value of VolumeController \\t\"+this.value);\n this.value = value;\n System.out.println(\"New value of VolumeController \\t\"+this.value);\n }\n @Override\n public void setDefault() {\n set(defaultValue);\n }\n\n @Override\n public void checkForDriverUpdate() {\n System.out.println(\"Checking driver update for VolumeController .... Done\");\n }\n}\nclass BrightnessControllerV4 extends ControllerV4 {\n\n private int defaultValue = 50;\n private int value;\n @Override\n int get() {\n return value;\n }\n @Override\n void set(int value) {\n System.out.println(\"Old value of BrightnessController \\t\"+this.value);\n this.value = value;\n System.out.println(\"New value of BrightnessController \\t\"+this.value);\n }\n\n @Override\n public void setDefault() {\n set(defaultValue);\n }\n\n @Override\n public void checkForDriverUpdate() {\n System.out.println(\"Checking driver update for BrightnessController .... Done\");\n }\n}\nclass ColourControllerV4 extends ControllerV4 {\n\n private int defaultValue = 40;\n private int value;\n @Override\n int get() {\n return value;\n }\n void set(int value) {\n System.out.println(\"Old value of ColourController \\t\"+this.value);\n this.value = value;\n System.out.println(\"New value of ColourController \\t\"+this.value);\n }\n @Override\n public void setDefault() {\n set(defaultValue);\n }\n\n @Override\n public void checkForDriverUpdate() {\n System.out.println(\"Checking driver update for ColourController .... Done\");\n }\n}\nclass ResetFunctionV4 {\n\n private List<OnReset> controllers = null;\n\n ResetFunctionV4(List<OnReset> controllers) {\n this.controllers = controllers;\n }\n void onReset() {\n for (OnReset onreset :this.controllers) {\n onreset.setDefault();\n }\n }\n}\nclass InitializeDeviceV4 {\n\n private List<OnStart> controllers = null;\n\n InitializeDeviceV4(List<OnStart> controllers) {\n this.controllers = controllers;\n }\n void initialize() {\n for (OnStart onStart :this.controllers) {\n onStart.checkForDriverUpdate();\n }\n }\n}\n/*\n* so on\n* There can be n number of controllers\n*\n* */\npublic class TvApplicationV4 {\n public static void main(String[] args) {\n VolumeControllerV4 volumeControllerV4 = new VolumeControllerV4();\n BrightnessControllerV4 brightnessControllerV4 = new BrightnessControllerV4();\n ColourControllerV4 colourControllerV4 = new ColourControllerV4();\n List<ControllerV4> controllerV4s = new ArrayList<>();\n controllerV4s.add(brightnessControllerV4);\n controllerV4s.add(volumeControllerV4);\n controllerV4s.add(colourControllerV4);\n\n List<OnStart> controllersToInitialize = new ArrayList<>();\n controllersToInitialize.addAll(controllerV4s);\n InitializeDeviceV4 initializeDeviceV4 = new InitializeDeviceV4(controllersToInitialize);\n initializeDeviceV4.initialize();\n\n List<OnReset> controllersToReset = new ArrayList<>();\n controllersToReset.addAll(controllerV4s);\n ResetFunctionV4 resetFunctionV4 = new ResetFunctionV4(controllersToReset);\n\n OUTER: while(true) {\n Scanner sc=new Scanner(System.in);\n System.out.println(\" Enter your option \\n Press 1 to increase volume \\n Press 2 to decrease volume\");\n System.out.println(\" Press 3 to increase brightness \\n Press 4 to decrease brightness\");\n System.out.println(\" Press 5 to increase color \\n Press 6 to decrease color\");\n System.out.println(\" Press 7 to reset TV \\n Press any other Button to shutdown\");\n int button = sc.nextInt();\n switch (button) {\n case 1: {\n volumeControllerV4.adjust(5);\n break;\n }\n case 2: {\n volumeControllerV4.adjust(-5);\n break;\n }\n case 3: {\n brightnessControllerV4.adjust(5);\n break;\n }\n case 4: {\n brightnessControllerV4.adjust(-5);\n break;\n }\n case 5: {\n colourControllerV4.adjust(5);\n break;\n }\n case 6: {\n colourControllerV4.adjust(-5);\n break;\n }\n case 7: {\n resetFunctionV4.onReset();\n break;\n }\n default:\n System.out.println(\"Shutting down...........\");\n break OUTER;\n }\n\n }\n }\n}\n</code></pre>\n\n<blockquote>\n <p>Now all of the issue faced by you got addressed and you realized that with the use of Inheritance and Polymorphism you could</p>\n</blockquote>\n\n<ol>\n<li>Keep various part of application loosely coupled.( Reset or Driver Update feature components don’t need to be made aware of actual controller classes(Volume, Brightness and Colour), any class implementing OnReset or OnStart will be acceptable to Reset or Driver Update feature components respectively).</li>\n<li>Application enhancement becomes easier.(New addition of controller wont impact reset or driver update feature component, and it is now really easy for you to add new ones)</li>\n<li>Keep layer of abstraction.(Now Reset feature can see only setDefault method of controllers and Reset feature can see only checkForDriverUpdate method of controllers)</li>\n</ol>\n\n<p>Hope, this helps :-)</p>\n"
}
] |
2008/09/30
|
[
"https://Stackoverflow.com/questions/154577",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3208/"
] |
In terms of Java, when someone asks:
>
> what is polymorphism?
>
>
>
Would **overloading** or **overriding** be an acceptable answer?
I think there is a bit more to it than that.
*IF you had a abstract base class that defined a method with no implementation, and you defined that method in the sub class, is that still overridding?*
I think **overloading** is not the right answer for sure.
|
The clearest way to express polymorphism is via an abstract base class (or interface)
```
public abstract class Human{
...
public abstract void goPee();
}
```
This class is abstract because the `goPee()` method is not definable for Humans. It is only definable for the subclasses Male and Female. Also, Human is an abstract concept — You cannot create a human that is neither Male nor Female. It’s got to be one or the other.
So we defer the implementation by using the abstract class.
```
public class Male extends Human{
...
@Override
public void goPee(){
System.out.println("Stand Up");
}
}
```
and
```
public class Female extends Human{
...
@Override
public void goPee(){
System.out.println("Sit Down");
}
}
```
Now we can tell an entire room full of Humans to go pee.
```
public static void main(String[] args){
ArrayList<Human> group = new ArrayList<Human>();
group.add(new Male());
group.add(new Female());
// ... add more...
// tell the class to take a pee break
for (Human person : group) person.goPee();
}
```
Running this would yield:
```
Stand Up
Sit Down
...
```
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.