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
|
---|---|---|---|---|---|---|
150,522 | <p>Using Restlet I needed to serve some simple static content in the same context as my web service. I've configured the component with a <code>Directory</code>, but in testing, I've found it will only serve 'index.html', everything else results in a 404.</p>
<pre><code>router.attach("/", new Directory(context, new Reference(baseRef, "./content"));
</code></pre>
<p>So... <a href="http://service" rel="nofollow noreferrer">http://service</a> and <a href="http://service/index.html" rel="nofollow noreferrer">http://service/index.html</a> both work, </p>
<p>but <a href="http://service/other.html" rel="nofollow noreferrer">http://service/other.html</a> gives me a 404</p>
<p>Can anyone shed some light on this? I want any file within the ./content directory to be available.</p>
<p>PS: I eventually plan to use a reverse proxy and serve all static content off another web server, but for now I need this to work as is.</p>
| [
{
"answer_id": 151642,
"author": "Dan Lenski",
"author_id": 20789,
"author_profile": "https://Stackoverflow.com/users/20789",
"pm_score": 3,
"selected": false,
"text": "<p>Best thing I can think of is to encode it yourself. How about this subroutine?</p>\n\n<pre><code>from urllib2 import Request, urlopen\nfrom binascii import b2a_base64\n\ndef b64open(url, postdata):\n req = Request(url, b2a_base64(postdata), headers={'Content-Transfer-Encoding': 'base64'})\n return urlopen(req)\n\nconn = b64open(\"http://www.whatever.com/script.cgi\", u\"Liberté Égalité Fraternité\")\n# returns a file-like object\n</code></pre>\n\n<p>(Okay, so this code just sends POST-data. But you apparently want multipart-encoded data, as if you clicked an \"Upload File\" button, right? Well, it's a pretty straightforward combination of what I have here and the answers from the question you linked.)</p>\n"
},
{
"answer_id": 151670,
"author": "Chris",
"author_id": 15578,
"author_profile": "https://Stackoverflow.com/users/15578",
"pm_score": 1,
"selected": false,
"text": "<p>PyCURL provides an interface to CURL from Python.</p>\n\n<p><a href=\"http://curl.haxx.se/libcurl/python/\" rel=\"nofollow noreferrer\">http://curl.haxx.se/libcurl/python/</a></p>\n\n<p>Curl will do all you need. It can transfer binary files properly, and supports many encodings. However, you have to make sure that the proper character encoding as a custom header when POSTing files.</p>\n\n<p>Specifically, you may need to do a 'file upload' style POST:</p>\n\n<p><a href=\"http://curl.haxx.se/docs/httpscripting.html\" rel=\"nofollow noreferrer\">http://curl.haxx.se/docs/httpscripting.html</a> (Section 4.3)</p>\n\n<p>With curl (or any other HTTP client) you may have to set the content encoding:</p>\n\n<p>Content-Type: text/html; charset=UTF-8</p>\n\n<p>Also, be aware that the request headers must be ascii, and this includes the\nurl (so make sure you properly escape your possibly unicode URLs. There are\nunicode escapes for the HTTP headers) This was recently fixed in Python:</p>\n\n<p><a href=\"http://bugs.python.org/issue3300\" rel=\"nofollow noreferrer\">http://bugs.python.org/issue3300</a></p>\n\n<p>I hope this helps, there is more info on the topic, including setting your default character set on your server, etc.</p>\n"
},
{
"answer_id": 3786024,
"author": "Stattrav",
"author_id": 370682,
"author_profile": "https://Stackoverflow.com/users/370682",
"pm_score": 1,
"selected": false,
"text": "<p>Just use this library and send in files.</p>\n\n<p><a href=\"http://github.com/seisen/urllib2_file/\" rel=\"nofollow\">http://github.com/seisen/urllib2_file/</a></p>\n"
}
]
| 2008/09/29 | [
"https://Stackoverflow.com/questions/150522",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/758/"
]
| Using Restlet I needed to serve some simple static content in the same context as my web service. I've configured the component with a `Directory`, but in testing, I've found it will only serve 'index.html', everything else results in a 404.
```
router.attach("/", new Directory(context, new Reference(baseRef, "./content"));
```
So... <http://service> and <http://service/index.html> both work,
but <http://service/other.html> gives me a 404
Can anyone shed some light on this? I want any file within the ./content directory to be available.
PS: I eventually plan to use a reverse proxy and serve all static content off another web server, but for now I need this to work as is. | Best thing I can think of is to encode it yourself. How about this subroutine?
```
from urllib2 import Request, urlopen
from binascii import b2a_base64
def b64open(url, postdata):
req = Request(url, b2a_base64(postdata), headers={'Content-Transfer-Encoding': 'base64'})
return urlopen(req)
conn = b64open("http://www.whatever.com/script.cgi", u"Liberté Égalité Fraternité")
# returns a file-like object
```
(Okay, so this code just sends POST-data. But you apparently want multipart-encoded data, as if you clicked an "Upload File" button, right? Well, it's a pretty straightforward combination of what I have here and the answers from the question you linked.) |
150,532 | <p>Similar to <a href="https://stackoverflow.com/questions/5415/convert-bytes-to-floating-point-numbers-in-python">this</a> question, I am trying to read in an ID3v2 tag header and am having trouble figuring out how to get individual bytes in python.</p>
<p>I first read all ten bytes into a string. I then want to parse out the individual pieces of information.</p>
<p>I can grab the two version number chars in the string, but then I have no idea how to take those two chars and get an integer out of them.</p>
<p>The struct package seems to be what I want, but I can't get it to work.</p>
<p>Here is my code so-far (I am very new to python btw...so take it easy on me):</p>
<pre><code>def __init__(self, ten_byte_string):
self.whole_string = ten_byte_string
self.file_identifier = self.whole_string[:3]
self.major_version = struct.pack('x', self.whole_string[3:4]) #this
self.minor_version = struct.pack('x', self.whole_string[4:5]) # and this
self.flags = self.whole_string[5:6]
self.len = self.whole_string[6:10]
</code></pre>
<p>Printing out any value except is obviously crap because they are not formatted correctly.</p>
| [
{
"answer_id": 150541,
"author": "Greg Hewgill",
"author_id": 893,
"author_profile": "https://Stackoverflow.com/users/893",
"pm_score": 2,
"selected": false,
"text": "<p>I was going to recommend the <code>struct</code> package but then you said you had tried it. Try this:</p>\n\n<pre><code>self.major_version = struct.unpack('H', self.whole_string[3:5])\n</code></pre>\n\n<p>The <code>pack()</code> function convers Python data types to bits, and the <code>unpack()</code> function converts bits to Python data types.</p>\n"
},
{
"answer_id": 150584,
"author": "Brian",
"author_id": 9493,
"author_profile": "https://Stackoverflow.com/users/9493",
"pm_score": 5,
"selected": true,
"text": "<p>If you have a string, with 2 bytes that you wish to interpret as a 16 bit integer, you can do so by:</p>\n\n<pre><code>>>> s = '\\0\\x02'\n>>> struct.unpack('>H', s)\n(2,)\n</code></pre>\n\n<p>Note that the > is for big-endian (the largest part of the integer comes first). This is the format id3 tags use.</p>\n\n<p>For other sizes of integer, you use different format codes. eg. \"i\" for a signed 32 bit integer. See help(struct) for details.</p>\n\n<p>You can also unpack several elements at once. eg for 2 unsigned shorts, followed by a signed 32 bit value:</p>\n\n<pre><code>>>> a,b,c = struct.unpack('>HHi', some_string)\n</code></pre>\n\n<p>Going by your code, you are looking for (in order):</p>\n\n<ul>\n<li>a 3 char string</li>\n<li>2 single byte values (major and minor version)</li>\n<li>a 1 byte flags variable</li>\n<li>a 32 bit length quantity</li>\n</ul>\n\n<p>The format string for this would be:</p>\n\n<pre><code>ident, major, minor, flags, len = struct.unpack('>3sBBBI', ten_byte_string)\n</code></pre>\n"
},
{
"answer_id": 150586,
"author": "Owen",
"author_id": 2109,
"author_profile": "https://Stackoverflow.com/users/2109",
"pm_score": 2,
"selected": false,
"text": "<p>Why write your own? (Assuming you haven't checked out these other options.) There's a couple options out there for reading in ID3 tag info from MP3s in Python. Check out my <a href=\"https://stackoverflow.com/questions/8948/accessing-mp3-meta-data-with-python#102285\">answer</a> over at <a href=\"https://stackoverflow.com/questions/8948/accessing-mp3-meta-data-with-python\">this</a> question.</p>\n"
},
{
"answer_id": 150639,
"author": "Alex Coventry",
"author_id": 1941213,
"author_profile": "https://Stackoverflow.com/users/1941213",
"pm_score": 2,
"selected": false,
"text": "<blockquote>\n <p>I am trying to read in an ID3v2 tag header</p>\n</blockquote>\n\n<p>FWIW, there's <a href=\"http://id3-py.sourceforge.net/\" rel=\"nofollow noreferrer\">already a module</a> for this.</p>\n"
}
]
| 2008/09/29 | [
"https://Stackoverflow.com/questions/150532",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2598/"
]
| Similar to [this](https://stackoverflow.com/questions/5415/convert-bytes-to-floating-point-numbers-in-python) question, I am trying to read in an ID3v2 tag header and am having trouble figuring out how to get individual bytes in python.
I first read all ten bytes into a string. I then want to parse out the individual pieces of information.
I can grab the two version number chars in the string, but then I have no idea how to take those two chars and get an integer out of them.
The struct package seems to be what I want, but I can't get it to work.
Here is my code so-far (I am very new to python btw...so take it easy on me):
```
def __init__(self, ten_byte_string):
self.whole_string = ten_byte_string
self.file_identifier = self.whole_string[:3]
self.major_version = struct.pack('x', self.whole_string[3:4]) #this
self.minor_version = struct.pack('x', self.whole_string[4:5]) # and this
self.flags = self.whole_string[5:6]
self.len = self.whole_string[6:10]
```
Printing out any value except is obviously crap because they are not formatted correctly. | If you have a string, with 2 bytes that you wish to interpret as a 16 bit integer, you can do so by:
```
>>> s = '\0\x02'
>>> struct.unpack('>H', s)
(2,)
```
Note that the > is for big-endian (the largest part of the integer comes first). This is the format id3 tags use.
For other sizes of integer, you use different format codes. eg. "i" for a signed 32 bit integer. See help(struct) for details.
You can also unpack several elements at once. eg for 2 unsigned shorts, followed by a signed 32 bit value:
```
>>> a,b,c = struct.unpack('>HHi', some_string)
```
Going by your code, you are looking for (in order):
* a 3 char string
* 2 single byte values (major and minor version)
* a 1 byte flags variable
* a 32 bit length quantity
The format string for this would be:
```
ident, major, minor, flags, len = struct.unpack('>3sBBBI', ten_byte_string)
``` |
150,535 | <p>How do you remove the jagged edges from a wide button in internet explorer? For example:</p>
<p><img src="https://i.stack.imgur.com/em5K0.gif" alt="alt text"></p>
| [
{
"answer_id": 150545,
"author": "brad",
"author_id": 208,
"author_profile": "https://Stackoverflow.com/users/208",
"pm_score": 2,
"selected": false,
"text": "<p>As a workaround, you can remove the blank spaces on each end of the button, which has the effect of decreasing the jagged edges. This is accomplished with the following css and a bit of jQuery:</p>\n\n<pre class=\"lang-css prettyprint-override\"><code>input.button {\n padding: 0 .25em;\n width: 0; /* for IE only */\n overflow: visible;\n}\n\ninput.button[class] { /* IE ignores [class] */\n width: auto;\n}\n</code></pre>\n\n<hr>\n\n<pre><code>$(function(){\n $('input[type=button]').addClass('button');\n});\n</code></pre>\n\n<p>The jQuery is for adding the button class. A more in depth write up can be found <a href=\"http://latrine.dgx.cz/the-stretched-buttons-problem-in-ie\" rel=\"nofollow noreferrer\">here</a>.</p>\n"
},
{
"answer_id": 150557,
"author": "Ron Savage",
"author_id": 12476,
"author_profile": "https://Stackoverflow.com/users/12476",
"pm_score": 2,
"selected": false,
"text": "<p>You can change the border style of the button with CSS, like this:</p>\n\n<pre class=\"lang-css prettyprint-override\"><code>/**************************************************************************\n Nav Button format settings\n**************************************************************************/\n.navButtons\n{\n font-size: 9px;\n font-family: Verdana, sans-serif;\n width: 80;\n height: 20; \n position: relative; \n border-style: solid; \n border-width: 1;\n}\n</code></pre>\n"
},
{
"answer_id": 150617,
"author": "cllpse",
"author_id": 20946,
"author_profile": "https://Stackoverflow.com/users/20946",
"pm_score": 4,
"selected": true,
"text": "<p>You can also eliminate Windows XP's styling of buttons (and every other version of Windows) by setting the <code>background-color</code> and/or <code>border-color</code> on your buttons.</p>\n\n<p>Try the following styles:</p>\n\n<pre><code>background-color: black;\ncolor: white;\nborder-color: red green blue yellow;\n</code></pre>\n\n<p>You can of course make this much more pleasing to the eyes. But you get my point :)</p>\n\n<p>Stack Overflow uses this approach.</p>\n"
},
{
"answer_id": 151280,
"author": "scunliffe",
"author_id": 6144,
"author_profile": "https://Stackoverflow.com/users/6144",
"pm_score": 1,
"selected": false,
"text": "<p>Not too much you can do about it, but the good news is that it is fixed in IE8</p>\n\n<p><a href=\"http://webbugtrack.blogspot.com/2007/08/bug-101-buttons-render-stretched-and.html\" rel=\"nofollow noreferrer\">http://webbugtrack.blogspot.com/2007/08/bug-101-buttons-render-stretched-and.html</a></p>\n"
},
{
"answer_id": 541113,
"author": "Paul D. Waite",
"author_id": 20578,
"author_profile": "https://Stackoverflow.com/users/20578",
"pm_score": 2,
"selected": false,
"text": "<p>Setting <code>overflow: visible;</code> on the button will cure the issue in IE 6 and 7.</p>\n\n<p>(See <a href=\"http://jehiah.cz/archive/button-width-in-ie\" rel=\"nofollow noreferrer\">http://jehiah.cz/archive/button-width-in-ie</a>)</p>\n\n<h3>Exceptions</h3>\n\n<ul>\n<li><p>In IE 6, if <code>display:block;</code> is also applied to the button, the above fix won't work.</p>\n\n<p>Setting the button to <code>display:inline;</code> in IE 6 will make the fix work.</p></li>\n<li><p>If you have a button like this within a table cell, then the table cell won't contract to the new, smaller width of the button.</p>\n\n<p>You can fix this in IE 6 by setting <code>width: 0;</code> on the button. However, in IE 7 this will make everything but the text of the button disappear.</p>\n\n<p>(See <a href=\"http://latrine.dgx.cz/the-stretched-buttons-problem-in-ie\" rel=\"nofollow noreferrer\">http://latrine.dgx.cz/the-stretched-buttons-problem-in-ie</a>)</p></li>\n</ul>\n\n<h3>More info on styling buttons:</h3>\n\n<p><a href=\"http://natbat.net/2009/Jun/10/styling-buttons-as-links/\" rel=\"nofollow noreferrer\">http://natbat.net/2009/Jun/10/styling-buttons-as-links/</a></p>\n"
}
]
| 2008/09/29 | [
"https://Stackoverflow.com/questions/150535",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/208/"
]
| How do you remove the jagged edges from a wide button in internet explorer? For example:
 | You can also eliminate Windows XP's styling of buttons (and every other version of Windows) by setting the `background-color` and/or `border-color` on your buttons.
Try the following styles:
```
background-color: black;
color: white;
border-color: red green blue yellow;
```
You can of course make this much more pleasing to the eyes. But you get my point :)
Stack Overflow uses this approach. |
150,539 | <p>I've used asp.net profiles (using the AspNetSqlProfileProvider) for holding small bits of information about my users. I started to wonder how it would handle a robust profile for a large number of users. Does anyone have experience using this on a large website with large numbers of simultaneous users? What are the performance implications? How about maintenance?</p>
| [
{
"answer_id": 150545,
"author": "brad",
"author_id": 208,
"author_profile": "https://Stackoverflow.com/users/208",
"pm_score": 2,
"selected": false,
"text": "<p>As a workaround, you can remove the blank spaces on each end of the button, which has the effect of decreasing the jagged edges. This is accomplished with the following css and a bit of jQuery:</p>\n\n<pre class=\"lang-css prettyprint-override\"><code>input.button {\n padding: 0 .25em;\n width: 0; /* for IE only */\n overflow: visible;\n}\n\ninput.button[class] { /* IE ignores [class] */\n width: auto;\n}\n</code></pre>\n\n<hr>\n\n<pre><code>$(function(){\n $('input[type=button]').addClass('button');\n});\n</code></pre>\n\n<p>The jQuery is for adding the button class. A more in depth write up can be found <a href=\"http://latrine.dgx.cz/the-stretched-buttons-problem-in-ie\" rel=\"nofollow noreferrer\">here</a>.</p>\n"
},
{
"answer_id": 150557,
"author": "Ron Savage",
"author_id": 12476,
"author_profile": "https://Stackoverflow.com/users/12476",
"pm_score": 2,
"selected": false,
"text": "<p>You can change the border style of the button with CSS, like this:</p>\n\n<pre class=\"lang-css prettyprint-override\"><code>/**************************************************************************\n Nav Button format settings\n**************************************************************************/\n.navButtons\n{\n font-size: 9px;\n font-family: Verdana, sans-serif;\n width: 80;\n height: 20; \n position: relative; \n border-style: solid; \n border-width: 1;\n}\n</code></pre>\n"
},
{
"answer_id": 150617,
"author": "cllpse",
"author_id": 20946,
"author_profile": "https://Stackoverflow.com/users/20946",
"pm_score": 4,
"selected": true,
"text": "<p>You can also eliminate Windows XP's styling of buttons (and every other version of Windows) by setting the <code>background-color</code> and/or <code>border-color</code> on your buttons.</p>\n\n<p>Try the following styles:</p>\n\n<pre><code>background-color: black;\ncolor: white;\nborder-color: red green blue yellow;\n</code></pre>\n\n<p>You can of course make this much more pleasing to the eyes. But you get my point :)</p>\n\n<p>Stack Overflow uses this approach.</p>\n"
},
{
"answer_id": 151280,
"author": "scunliffe",
"author_id": 6144,
"author_profile": "https://Stackoverflow.com/users/6144",
"pm_score": 1,
"selected": false,
"text": "<p>Not too much you can do about it, but the good news is that it is fixed in IE8</p>\n\n<p><a href=\"http://webbugtrack.blogspot.com/2007/08/bug-101-buttons-render-stretched-and.html\" rel=\"nofollow noreferrer\">http://webbugtrack.blogspot.com/2007/08/bug-101-buttons-render-stretched-and.html</a></p>\n"
},
{
"answer_id": 541113,
"author": "Paul D. Waite",
"author_id": 20578,
"author_profile": "https://Stackoverflow.com/users/20578",
"pm_score": 2,
"selected": false,
"text": "<p>Setting <code>overflow: visible;</code> on the button will cure the issue in IE 6 and 7.</p>\n\n<p>(See <a href=\"http://jehiah.cz/archive/button-width-in-ie\" rel=\"nofollow noreferrer\">http://jehiah.cz/archive/button-width-in-ie</a>)</p>\n\n<h3>Exceptions</h3>\n\n<ul>\n<li><p>In IE 6, if <code>display:block;</code> is also applied to the button, the above fix won't work.</p>\n\n<p>Setting the button to <code>display:inline;</code> in IE 6 will make the fix work.</p></li>\n<li><p>If you have a button like this within a table cell, then the table cell won't contract to the new, smaller width of the button.</p>\n\n<p>You can fix this in IE 6 by setting <code>width: 0;</code> on the button. However, in IE 7 this will make everything but the text of the button disappear.</p>\n\n<p>(See <a href=\"http://latrine.dgx.cz/the-stretched-buttons-problem-in-ie\" rel=\"nofollow noreferrer\">http://latrine.dgx.cz/the-stretched-buttons-problem-in-ie</a>)</p></li>\n</ul>\n\n<h3>More info on styling buttons:</h3>\n\n<p><a href=\"http://natbat.net/2009/Jun/10/styling-buttons-as-links/\" rel=\"nofollow noreferrer\">http://natbat.net/2009/Jun/10/styling-buttons-as-links/</a></p>\n"
}
]
| 2008/09/29 | [
"https://Stackoverflow.com/questions/150539",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2757/"
]
| I've used asp.net profiles (using the AspNetSqlProfileProvider) for holding small bits of information about my users. I started to wonder how it would handle a robust profile for a large number of users. Does anyone have experience using this on a large website with large numbers of simultaneous users? What are the performance implications? How about maintenance? | You can also eliminate Windows XP's styling of buttons (and every other version of Windows) by setting the `background-color` and/or `border-color` on your buttons.
Try the following styles:
```
background-color: black;
color: white;
border-color: red green blue yellow;
```
You can of course make this much more pleasing to the eyes. But you get my point :)
Stack Overflow uses this approach. |
150,543 | <p>In C, is it possible to forward the invocation of a variadic function? As in,</p>
<pre><code>int my_printf(char *fmt, ...) {
fprintf(stderr, "Calling printf with fmt %s", fmt);
return SOMEHOW_INVOKE_LIBC_PRINTF;
}
</code></pre>
<p>Forwarding the invocation in the manner above obviously isn't strictly necessary in this case (since you could log invocations in other ways, or use vfprintf), but the codebase I'm working on requires the wrapper to do some actual work, and doesn't have (and can't have added) a helper function akin to vfprintf.</p>
<p>[Update: there seems to be some confusion based on the answers that have been supplied so far. To phrase the question another way: in general, can you wrap some arbitrary variadic function <i>without modifying that function's definition</i>.]</p>
| [
{
"answer_id": 150560,
"author": "Greg Rogers",
"author_id": 5963,
"author_profile": "https://Stackoverflow.com/users/5963",
"pm_score": 2,
"selected": false,
"text": "<p>Use vfprintf:</p>\n\n<pre><code>int my_printf(char *fmt, ...) {\n va_list va;\n int ret;\n\n va_start(va, fmt);\n ret = vfprintf(stderr, fmt, va);\n va_end(va);\n return ret;\n}\n</code></pre>\n"
},
{
"answer_id": 150571,
"author": "Greg Hewgill",
"author_id": 893,
"author_profile": "https://Stackoverflow.com/users/893",
"pm_score": 4,
"selected": false,
"text": "<p>Almost, using the facilities available in <code><stdarg.h></code>:</p>\n\n<pre><code>#include <stdarg.h>\nint my_printf(char *format, ...)\n{\n va_list args;\n va_start(args, format);\n int r = vprintf(format, args);\n va_end(args);\n return r;\n}\n</code></pre>\n\n<p>Note that you will need to use the <a href=\"http://www.cplusplus.com/reference/clibrary/cstdio/vprintf.html\" rel=\"noreferrer\"><code>vprintf</code></a> version rather than plain <code>printf</code>. There isn't a way to directly call a variadic function in this situation without using <code>va_list</code>.</p>\n"
},
{
"answer_id": 150578,
"author": "John Millikin",
"author_id": 3560,
"author_profile": "https://Stackoverflow.com/users/3560",
"pm_score": 2,
"selected": false,
"text": "<p>There's no way to forward such function calls because the only location where you can retrieve raw stack elements is in <code>my_print()</code>. The usual way to wrap calls like that is to have two functions, one that just converts the arguments into the various <code>varargs</code> structs, and another that actually operates upon those structs. Using such a double-function model, you can (for example) wrap <code>printf()</code> by initializing the structs in <code>my_printf()</code> with <code>va_start()</code>, and then pass them to <code>vfprintf()</code>.</p>\n"
},
{
"answer_id": 150616,
"author": "Adam Rosenfield",
"author_id": 9530,
"author_profile": "https://Stackoverflow.com/users/9530",
"pm_score": 8,
"selected": true,
"text": "<p>If you don't have a function analogous to <code>vfprintf</code> that takes a <code>va_list</code> instead of a variable number of arguments, <strong>you can't do it</strong>. See <a href=\"http://c-faq.com/varargs/handoff.html\" rel=\"noreferrer\"><a href=\"http://c-faq.com/varargs/handoff.html\" rel=\"noreferrer\">http://c-faq.com/varargs/handoff.html</a></a>.</p>\n\n<p>Example:</p>\n\n<pre class=\"lang-c prettyprint-override\"><code>void myfun(const char *fmt, va_list argp) {\n vfprintf(stderr, fmt, argp);\n}\n</code></pre>\n"
},
{
"answer_id": 150626,
"author": "CB Bailey",
"author_id": 19563,
"author_profile": "https://Stackoverflow.com/users/19563",
"pm_score": 6,
"selected": false,
"text": "<p>Not directly, however it is common (and you will find almost universally the case in the standard library) for variadic functions to come in pairs with a <code>varargs</code> style alternative function. e.g. <code>printf</code>/<code>vprintf</code></p>\n\n<p>The v... functions take a va_list parameter, the implementation of which is often done with compiler specific 'macro magic', but you are guaranteed that calling the v... style function from a variadic function like this will work:</p>\n\n<pre><code>#include <stdarg.h>\n\nint m_printf(char *fmt, ...)\n{\n int ret;\n\n /* Declare a va_list type variable */\n va_list myargs;\n\n /* Initialise the va_list variable with the ... after fmt */\n\n va_start(myargs, fmt);\n\n /* Forward the '...' to vprintf */\n ret = vprintf(fmt, myargs);\n\n /* Clean up the va_list */\n va_end(myargs);\n\n return ret;\n}\n</code></pre>\n\n<p>This should give you the effect that you are looking for.</p>\n\n<p>If you are considering writing a variadic library function you should also consider making a va_list style companion available as part of the library. As you can see from your question, it can be prove useful for your users.</p>\n"
},
{
"answer_id": 150633,
"author": "Commodore Jaeger",
"author_id": 4659,
"author_profile": "https://Stackoverflow.com/users/4659",
"pm_score": 6,
"selected": false,
"text": "<p>C99 supports <a href=\"http://gcc.gnu.org/onlinedocs/cpp/Variadic-Macros.html\" rel=\"noreferrer\">macros with variadic arguments</a>; depending on your compiler, you might be able to declare a macro that does what you want:</p>\n\n<pre><code>#define my_printf(format, ...) \\\n do { \\\n fprintf(stderr, \"Calling printf with fmt %s\\n\", format); \\\n some_other_variadac_function(format, ##__VA_ARGS__); \\\n } while(0)\n</code></pre>\n\n<p>In general, though, the best solution is to use the <strong>va_list</strong> form of the function you're trying to wrap, should one exist.</p>\n"
},
{
"answer_id": 150854,
"author": "user10146",
"author_id": 10146,
"author_profile": "https://Stackoverflow.com/users/10146",
"pm_score": 1,
"selected": false,
"text": "<p>Yes you can do it, but it is somewhat ugly and you have to know the maximal number of arguments. Furthermore if you are on an architecture where the arguments aren't passed on the stack like the x86 (for instance, PowerPC), you will have to know if \"special\" types (double, floats, altivec etc.) are used and if so, deal with them accordingly. It can be painful quickly but if you are on x86 or if the original function has a well defined and limited perimeter, it can work.\n<strong>It still will be a hack</strong>, use it for debugging purpose. Do not build you software around that.\nAnyway, here's a working example on x86:</p>\n\n<pre><code>#include <stdio.h>\n#include <stdarg.h>\n\nint old_variadic_function(int n, ...)\n{\n va_list args;\n int i = 0;\n\n va_start(args, n);\n\n if(i++<n) printf(\"arg %d is 0x%x\\n\", i, va_arg(args, int));\n if(i++<n) printf(\"arg %d is %g\\n\", i, va_arg(args, double));\n if(i++<n) printf(\"arg %d is %g\\n\", i, va_arg(args, double));\n\n va_end(args);\n\n return n;\n}\n\nint old_variadic_function_wrapper(int n, ...)\n{\n va_list args;\n int a1;\n int a2;\n int a3;\n int a4;\n int a5;\n int a6;\n int a7;\n int a8;\n\n /* Do some work, possibly with another va_list to access arguments */\n\n /* Work done */\n\n va_start(args, n);\n\n a1 = va_arg(args, int);\n a2 = va_arg(args, int);\n a3 = va_arg(args, int);\n a4 = va_arg(args, int);\n a5 = va_arg(args, int);\n a6 = va_arg(args, int);\n a7 = va_arg(args, int);\n\n va_end(args);\n\n return old_variadic_function(n, a1, a2, a3, a4, a5, a6, a7, a8);\n}\n\nint main(void)\n{\n printf(\"Call 1: 1, 0x123\\n\");\n old_variadic_function(1, 0x123);\n printf(\"Call 2: 2, 0x456, 1.234\\n\");\n old_variadic_function(2, 0x456, 1.234);\n printf(\"Call 3: 3, 0x456, 4.456, 7.789\\n\");\n old_variadic_function(3, 0x456, 4.456, 7.789);\n printf(\"Wrapped call 1: 1, 0x123\\n\");\n old_variadic_function_wrapper(1, 0x123);\n printf(\"Wrapped call 2: 2, 0x456, 1.234\\n\");\n old_variadic_function_wrapper(2, 0x456, 1.234);\n printf(\"Wrapped call 3: 3, 0x456, 4.456, 7.789\\n\");\n old_variadic_function_wrapper(3, 0x456, 4.456, 7.789);\n\n return 0;\n}\n</code></pre>\n\n<p>For some reason, you can't use floats with va_arg, gcc says they are converted to double but the program crashes. That alone demonstrates that this solution is a hack and that there is no general solution.\nIn my example I assumed that the maximum number of arguments was 8, but you can increase that number. The wrapped function also only used integers but it works the same way with other 'normal' parameters since they always cast to integers. The target function will know their types but your intermediary wrapper doesn't need to. The wrapper also doesn't need to know the right number of arguments since the target function will also know it.\nTo do useful work (except just logging the call), you probably will have to know both though.</p>\n"
},
{
"answer_id": 16777608,
"author": "coltox",
"author_id": 1147819,
"author_profile": "https://Stackoverflow.com/users/1147819",
"pm_score": 4,
"selected": false,
"text": "<p>As it is not really possible to forward such calls in a nice way, we worked around this by setting up a new stack frame with a copy of the original stack frame. However this is <em>highly unportable and makes all kinds of assumptions</em>, e.g. that the code uses frame pointers and the 'standard' calling conventions.</p>\n\n<p>This header file allows to wrap variadic functions for x86_64 and i386 (GCC). It doesn't work for floating-point arguments, but should be straight forward to extend for supporting those.</p>\n\n<pre><code>#ifndef _VA_ARGS_WRAPPER_H\n#define _VA_ARGS_WRAPPER_H\n#include <limits.h>\n#include <stdint.h>\n#include <alloca.h>\n#include <inttypes.h>\n#include <string.h>\n\n/* This macros allow wrapping variadic functions.\n * Currently we don't care about floating point arguments and\n * we assume that the standard calling conventions are used.\n *\n * The wrapper function has to start with VA_WRAP_PROLOGUE()\n * and the original function can be called by\n * VA_WRAP_CALL(function, ret), whereas the return value will\n * be stored in ret. The caller has to provide ret\n * even if the original function was returning void.\n */\n\n#define __VA_WRAP_CALL_FUNC __attribute__ ((noinline))\n\n#define VA_WRAP_CALL_COMMON() \\\n uintptr_t va_wrap_this_bp,va_wrap_old_bp; \\\n va_wrap_this_bp = va_wrap_get_bp(); \\\n va_wrap_old_bp = *(uintptr_t *) va_wrap_this_bp; \\\n va_wrap_this_bp += 2 * sizeof(uintptr_t); \\\n size_t volatile va_wrap_size = va_wrap_old_bp - va_wrap_this_bp; \\\n uintptr_t *va_wrap_stack = alloca(va_wrap_size); \\\n memcpy((void *) va_wrap_stack, \\\n (void *)(va_wrap_this_bp), va_wrap_size);\n\n\n#if ( __WORDSIZE == 64 )\n\n/* System V AMD64 AB calling convention */\n\nstatic inline uintptr_t __attribute__((always_inline)) \nva_wrap_get_bp()\n{\n uintptr_t ret;\n asm volatile (\"mov %%rbp, %0\":\"=r\"(ret));\n return ret;\n}\n\n\n#define VA_WRAP_PROLOGUE() \\\n uintptr_t va_wrap_ret; \\\n uintptr_t va_wrap_saved_args[7]; \\\n asm volatile ( \\\n \"mov %%rsi, (%%rax)\\n\\t\" \\\n \"mov %%rdi, 0x8(%%rax)\\n\\t\" \\\n \"mov %%rdx, 0x10(%%rax)\\n\\t\" \\\n \"mov %%rcx, 0x18(%%rax)\\n\\t\" \\\n \"mov %%r8, 0x20(%%rax)\\n\\t\" \\\n \"mov %%r9, 0x28(%%rax)\\n\\t\" \\\n : \\\n :\"a\"(va_wrap_saved_args) \\\n );\n\n#define VA_WRAP_CALL(func, ret) \\\n VA_WRAP_CALL_COMMON(); \\\n va_wrap_saved_args[6] = (uintptr_t)va_wrap_stack; \\\n asm volatile ( \\\n \"mov (%%rax), %%rsi \\n\\t\" \\\n \"mov 0x8(%%rax), %%rdi \\n\\t\" \\\n \"mov 0x10(%%rax), %%rdx \\n\\t\" \\\n \"mov 0x18(%%rax), %%rcx \\n\\t\" \\\n \"mov 0x20(%%rax), %%r8 \\n\\t\" \\\n \"mov 0x28(%%rax), %%r9 \\n\\t\" \\\n \"mov $0, %%rax \\n\\t\" \\\n \"call *%%rbx \\n\\t\" \\\n : \"=a\" (va_wrap_ret) \\\n : \"b\" (func), \"a\" (va_wrap_saved_args) \\\n : \"%rcx\", \"%rdx\", \\\n \"%rsi\", \"%rdi\", \"%r8\", \"%r9\", \\\n \"%r10\", \"%r11\", \"%r12\", \"%r14\", \\\n \"%r15\" \\\n ); \\\n ret = (typeof(ret)) va_wrap_ret;\n\n#else\n\n/* x86 stdcall */\n\nstatic inline uintptr_t __attribute__((always_inline))\nva_wrap_get_bp()\n{\n uintptr_t ret;\n asm volatile (\"mov %%ebp, %0\":\"=a\"(ret));\n return ret;\n}\n\n#define VA_WRAP_PROLOGUE() \\\n uintptr_t va_wrap_ret;\n\n#define VA_WRAP_CALL(func, ret) \\\n VA_WRAP_CALL_COMMON(); \\\n asm volatile ( \\\n \"mov %2, %%esp \\n\\t\" \\\n \"call *%1 \\n\\t\" \\\n : \"=a\"(va_wrap_ret) \\\n : \"r\" (func), \\\n \"r\"(va_wrap_stack) \\\n : \"%ebx\", \"%ecx\", \"%edx\" \\\n ); \\\n ret = (typeof(ret))va_wrap_ret;\n#endif\n\n#endif\n</code></pre>\n\n<p>In the end you can wrap calls like this:</p>\n\n<pre><code>int __VA_WRAP_CALL_FUNC wrap_printf(char *str, ...)\n{\n VA_WRAP_PROLOGUE();\n int ret;\n VA_WRAP_CALL(printf, ret);\n printf(\"printf returned with %d \\n\", ret);\n return ret;\n}\n</code></pre>\n"
},
{
"answer_id": 21741002,
"author": "Johannes",
"author_id": 536874,
"author_profile": "https://Stackoverflow.com/users/536874",
"pm_score": 1,
"selected": false,
"text": "<p>There are essentially three options.</p>\n\n<p>One is to not pass it on but to use the variadic implementation of your target function and not pass on the ellipses. The other one is to use a variadic macro. The third option is all the stuff i am missing.</p>\n\n<p>I usually go with option one since i feel like this is really easy to handle. Option two has a drawback because there are some limitations to calling variadic macros.</p>\n\n<p>Here is some example code:</p>\n\n<pre><code>#include <stdio.h>\n#include <stdarg.h>\n\n#define Option_VariadicMacro(f, ...)\\\n printf(\"printing using format: %s\", f);\\\n printf(f, __VA_ARGS__)\n\nint Option_ResolveVariadicAndPassOn(const char * f, ... )\n{\n int r;\n va_list args;\n\n printf(\"printing using format: %s\", f);\n va_start(args, f);\n r = vprintf(f, args);\n va_end(args);\n return r;\n}\n\nvoid main()\n{\n const char * f = \"%s %s %s\\n\";\n const char * a = \"One\";\n const char * b = \"Two\";\n const char * c = \"Three\";\n printf(\"---- Normal Print ----\\n\");\n printf(f, a, b, c);\n printf(\"\\n\");\n printf(\"---- Option_VariadicMacro ----\\n\");\n Option_VariadicMacro(f, a, b, c);\n printf(\"\\n\");\n printf(\"---- Option_ResolveVariadicAndPassOn ----\\n\");\n Option_ResolveVariadicAndPassOn(f, a, b, c);\n printf(\"\\n\");\n}\n</code></pre>\n"
},
{
"answer_id": 61545433,
"author": "SSpoke",
"author_id": 414521,
"author_profile": "https://Stackoverflow.com/users/414521",
"pm_score": 0,
"selected": false,
"text": "<p>The best way to do this is</p>\n\n<pre><code>static BOOL(__cdecl *OriginalVarArgsFunction)(BYTE variable1, char* format, ...)(0x12345678); //TODO: change address lolz\n\nBOOL __cdecl HookedVarArgsFunction(BYTE variable1, char* format, ...)\n{\n BOOL res;\n\n va_list vl;\n va_start(vl, format);\n\n // Get variable arguments count from disasm. -2 because of existing 'format', 'variable1'\n uint32_t argCount = *((uint8_t*)_ReturnAddress() + 2) / sizeof(void*) - 2;\n printf(\"arg count = %d\\n\", argCount);\n\n // ((int( __cdecl* )(const char*, ...))&oldCode)(fmt, ...);\n __asm\n {\n mov eax, argCount\n test eax, eax\n je noLoop\n mov edx, vl\n loop1 :\n push dword ptr[edx + eax * 4 - 4]\n sub eax, 1\n jnz loop1\n noLoop :\n push format\n push variable1\n //lea eax, [oldCode] // oldCode - original function pointer\n mov eax, OriginalVarArgsFunction\n call eax\n mov res, eax\n mov eax, argCount\n lea eax, [eax * 4 + 8] //+8 because 2 parameters (format and variable1)\n add esp, eax\n }\n return res;\n}\n</code></pre>\n"
},
{
"answer_id": 61545790,
"author": "Nate Eldredge",
"author_id": 634919,
"author_profile": "https://Stackoverflow.com/users/634919",
"pm_score": 4,
"selected": false,
"text": "<p>gcc offers an extension that can do this: <code>__builtin_apply</code> and relatives. See <a href=\"https://gcc.gnu.org/onlinedocs/gcc-4.1.2/gcc/Constructing-Calls.html\" rel=\"noreferrer\">Constructing Function Calls</a> in the gcc manual.</p>\n\n<p>An example:</p>\n\n<pre><code>#include <stdio.h>\n\nint my_printf(const char *fmt, ...) {\n void *args = __builtin_apply_args();\n printf(\"Hello there! Format string is %s\\n\", fmt);\n void *ret = __builtin_apply((void (*)())printf, args, 1000);\n __builtin_return(ret);\n}\n\nint main(void) {\n my_printf(\"%d %f %s\\n\", -37, 3.1415, \"spam\");\n return 0;\n}\n</code></pre>\n\n<p><a href=\"https://godbolt.org/z/R5qp35\" rel=\"noreferrer\">Try it on godbolt</a></p>\n\n<p>There are some cautions in the documentation that it might not work in more complicated situations. And you have to hardcode a maximum size for the arguments (here I used 1000). But it might be a reasonable alternative to the other approaches that involve dissecting the stack in either C or assembly language.</p>\n"
},
{
"answer_id": 62043871,
"author": "Bert Regelink",
"author_id": 1239858,
"author_profile": "https://Stackoverflow.com/users/1239858",
"pm_score": 1,
"selected": false,
"text": "<p>Not sure if this helps to answer OP's question since I do not know why the restriction for using a helper function akin to vfprintf in the wrapper function applies. I think the key problem here is that forwarding the variadic argument list without interpreting them is difficult. What is possible, is to perform the formatting (using a helper function akin to vfprintf: vsnprintf) and forward the formatted output to the wrapped function with variadic arguments (i.e. not modifying the definition of the wrapped function). So, here we go:</p>\n<pre><code>#include <stdio.h>\n#include <stdarg.h>\n\nint my_printf(char *fmt, ...)\n{\n if (fmt == NULL) {\n /* Invalid format pointer */\n return -1;\n } else {\n va_list args;\n int len;\n\n /* Initialize a variable argument list */\n va_start(args, fmt);\n\n /* Get length of format including arguments */\n len = vsnprintf(NULL, 0, fmt, args);\n\n /* End using variable argument list */\n va_end(args);\n \n if (len < 0) {\n /* vsnprintf failed */\n return -1;\n } else {\n /* Declare a character buffer for the formatted string */\n char formatted[len + 1];\n\n /* Initialize a variable argument list */\n va_start(args, fmt);\n \n /* Write the formatted output */\n vsnprintf(formatted, sizeof(formatted), fmt, args);\n \n /* End using variable argument list */\n va_end(args);\n\n /* Call the wrapped function using the formatted output and return */\n fprintf(stderr, "Calling printf with fmt %s", fmt);\n return printf("%s", formatted);\n }\n }\n}\n\nint main()\n{\n /* Expected output: Test\n * Expected error: Calling printf with fmt Test\n */\n my_printf("Test\\n");\n //printf("Test\\n");\n\n /* Expected output: Test\n * Expected error: Calling printf with fmt %s\n */\n my_printf("%s\\n", "Test");\n //printf("%s\\n", "Test");\n\n /* Expected output: %s\n * Expected error: Calling printf with fmt %s\n */\n my_printf("%s\\n", "%s");\n //printf("%s\\n", "%s");\n\n return 0;\n}\n</code></pre>\n<p>I came across this solution <a href=\"https://stackoverflow.com/questions/27252757/how-to-mock-variadic-functions-using-googlemock\">here</a>.</p>\n<p><strong>Editted: fixed mistakes pointed out by egmont</strong></p>\n"
}
]
| 2008/09/29 | [
"https://Stackoverflow.com/questions/150543",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/23600/"
]
| In C, is it possible to forward the invocation of a variadic function? As in,
```
int my_printf(char *fmt, ...) {
fprintf(stderr, "Calling printf with fmt %s", fmt);
return SOMEHOW_INVOKE_LIBC_PRINTF;
}
```
Forwarding the invocation in the manner above obviously isn't strictly necessary in this case (since you could log invocations in other ways, or use vfprintf), but the codebase I'm working on requires the wrapper to do some actual work, and doesn't have (and can't have added) a helper function akin to vfprintf.
[Update: there seems to be some confusion based on the answers that have been supplied so far. To phrase the question another way: in general, can you wrap some arbitrary variadic function *without modifying that function's definition*.] | If you don't have a function analogous to `vfprintf` that takes a `va_list` instead of a variable number of arguments, **you can't do it**. See [<http://c-faq.com/varargs/handoff.html>](http://c-faq.com/varargs/handoff.html).
Example:
```c
void myfun(const char *fmt, va_list argp) {
vfprintf(stderr, fmt, argp);
}
``` |
150,544 | <p>In C# code can you catch a native exception thrown from deep in some unmanaged library? If so do you need to do anything differently to catch it or does a standard try...catch get it?</p>
| [
{
"answer_id": 150550,
"author": "Mitchel Sellers",
"author_id": 13279,
"author_profile": "https://Stackoverflow.com/users/13279",
"pm_score": -1,
"selected": false,
"text": "<p>If you use a </p>\n\n<pre><code>try\n{\n\n}\ncatch(Exception ex)\n{\n\n}\n</code></pre>\n\n<p>it will catch ALL exceptions, depending on how you call the external libraries you might get a com related exception that encapsulates the error but it will catch the error.</p>\n"
},
{
"answer_id": 150551,
"author": "Curt Hagenlocher",
"author_id": 533,
"author_profile": "https://Stackoverflow.com/users/533",
"pm_score": 4,
"selected": false,
"text": "<p>The interop layer between C# and native code will convert the exception into a managed form, allowing it to be caught by your C# code. As of .NET 2.0, <code>catch (Exception)</code> should catch anything other than a nonrecoverable error.</p>\n"
},
{
"answer_id": 150555,
"author": "Dean",
"author_id": 11802,
"author_profile": "https://Stackoverflow.com/users/11802",
"pm_score": -1,
"selected": false,
"text": "<p>A standard try catch should do the trick i believe. </p>\n\n<p>I run into a similar problem with a System.data exception throwing a sqlClient exception which was uncaught, adding a try..catch into my code did the trick in the instance </p>\n"
},
{
"answer_id": 150596,
"author": "Vivek",
"author_id": 7418,
"author_profile": "https://Stackoverflow.com/users/7418",
"pm_score": 6,
"selected": true,
"text": "<p>You can use <a href=\"http://msdn.microsoft.com/en-us/library/system.componentmodel.win32exception.aspx\" rel=\"noreferrer\">Win32Exception</a> and use its NativeErrorCode property to handle it appropriately. </p>\n\n<pre><code>// http://support.microsoft.com/kb/186550\nconst int ERROR_FILE_NOT_FOUND = 2;\nconst int ERROR_ACCESS_DENIED = 5;\nconst int ERROR_NO_APP_ASSOCIATED = 1155; \n\nvoid OpenFile(string filePath)\n{\n Process process = new Process();\n\n try\n {\n // Calls native application registered for the file type\n // This may throw native exception\n process.StartInfo.FileName = filePath;\n process.StartInfo.Verb = \"Open\";\n process.StartInfo.CreateNoWindow = true;\n process.Start();\n }\n catch (Win32Exception e)\n {\n if (e.NativeErrorCode == ERROR_FILE_NOT_FOUND || \n e.NativeErrorCode == ERROR_ACCESS_DENIED ||\n e.NativeErrorCode == ERROR_NO_APP_ASSOCIATED)\n {\n MessageBox.Show(this, e.Message, \"Error\", \n MessageBoxButtons.OK, \n MessageBoxIcon.Exclamation);\n }\n }\n}\n</code></pre>\n"
},
{
"answer_id": 150602,
"author": "Michael Damatov",
"author_id": 23372,
"author_profile": "https://Stackoverflow.com/users/23372",
"pm_score": 3,
"selected": false,
"text": "<p>Somewhere using a .NET Reflector I've seen the following code:</p>\n\n<pre><code>try {\n ...\n} catch(Exception e) {\n ...\n} catch {\n ...\n}\n</code></pre>\n\n<p>Hmm, C# does not allow to throw an exception not deriving from the System.Exception class. And as far as I known any exception cautch by the interop marshaller is wrapped by the exception class that inherits the System.Exception.</p>\n\n<p>So my question is whether it's possible to catch an exception that is not a System.Exception.</p>\n"
},
{
"answer_id": 150675,
"author": "trampster",
"author_id": 78561,
"author_profile": "https://Stackoverflow.com/users/78561",
"pm_score": 4,
"selected": false,
"text": "<p>Catch without () will catch non-CLS compliant exceptions including native exceptions.</p>\n\n<pre><code>try\n{\n\n}\ncatch\n{\n\n}\n</code></pre>\n\n<p>See the following FxCop rule for more info\n<a href=\"http://msdn.microsoft.com/en-gb/bb264489.aspx\" rel=\"noreferrer\">http://msdn.microsoft.com/en-gb/bb264489.aspx</a></p>\n"
},
{
"answer_id": 151198,
"author": "JaredPar",
"author_id": 23283,
"author_profile": "https://Stackoverflow.com/users/23283",
"pm_score": 3,
"selected": false,
"text": "<p>This depends on what type of native exception you are talking about. If you're referring to an SEH exception then the CLR will do one of two things. </p>\n\n<ol>\n<li>In the case of a known SEH error code it will map it to the appropriate .Net exception (i.e. OutOfMemoryException)</li>\n<li>In the case of an un-mappable (E_FAIL) or unknown code it will just throw an <a href=\"http://msdn.microsoft.com/en-us/library/system.runtime.interopservices.sehexception.aspx\" rel=\"nofollow noreferrer\">SEHException</a> instance. </li>\n</ol>\n\n<p>Both of these will be caught with a simple \"catch (Exception)\" block. </p>\n\n<p>The other type of native exception which can cross the native/managed boundary are C++ exceptions. I'm not sure how they are mapped/handled. My guess is that since Windows implements C++ exceptions on top of SEH, they are just mapped the same way. </p>\n"
},
{
"answer_id": 151329,
"author": "nedruod",
"author_id": 5504,
"author_profile": "https://Stackoverflow.com/users/5504",
"pm_score": 2,
"selected": false,
"text": "<p>Almost, but not quite. You will catch the exception with </p>\n\n<pre><code>try \n{\n ...\n}\ncatch (Exception e)\n{\n ...\n}\n</code></pre>\n\n<p>but you will still have potential problems. According to <a href=\"http://msdn.microsoft.com/en-us/library/system.runtime.interopservices.sehexception.aspx\" rel=\"nofollow noreferrer\">MSDN</a>, in order to insure exception destructors are called you would have to catch like:</p>\n\n<pre><code>try\n{\n ...\n}\ncatch\n{\n ...\n}\n</code></pre>\n\n<p>This is the only way to insure an exception destructor is called (though I'm not sure why). But that leaves you with the tradeoff of brute force versus a possible memory leak.</p>\n\n<p>Incidentally, if you use the (Exception e) approach you should know the different types of exceptions you might come across. RuntimeWrappedException is what any managed non-exception type will be mapped to (for languages that can throw a string), and others will be mapped, such as OutOfMemoryException and AccessViolationException. COM Interop HRESULTS or exceptions other than E___FAIL will map to COMException, and finally at the end you have SEHException for E_FAIL or any other unmapped exception.</p>\n\n<p>So what should you do? Best choice is don't throw exceptions from your unamanaged code! Hah. Really though if you have a choice, put up barriers and failing that make the choice of which is worse, a chance of a memory leak during exception handling, or not knowing what type your exception is.</p>\n"
},
{
"answer_id": 70616409,
"author": "JumpingJezza",
"author_id": 345659,
"author_profile": "https://Stackoverflow.com/users/345659",
"pm_score": 2,
"selected": false,
"text": "<p>With .Net Framework 4.8 <strong>IF</strong> the exception is <a href=\"https://learn.microsoft.com/en-us/archive/msdn-magazine/2004/march/throwing-custom-exception-types-from-a-com-server-application\" rel=\"nofollow noreferrer\">handled nicely</a> within the native code then you can catch it with a standard try catch.</p>\n<pre><code>try \n{\n //call native code method\n} \ncatch (Exception ex) \n{\n //do stuff\n} \n</code></pre>\n<p><strong>HOWEVER</strong>, if the native code is in a 3rd party dll you have no control over, you may find that the developers are inadvertently throwing unhandled exceptions. I have found NOTHING will catch these, except a global error handler.</p>\n<pre><code>private static void Main()\n{\n AppDomain.CurrentDomain.UnhandledException += OnUnhandledException;\n try \n {\n //call native code method\n } \n catch (Exception ex) \n {\n //unhandled exception from native code WILL NOT BE CAUGHT HERE\n } \n}\n\nprivate static void OnUnhandledException(object sender, UnhandledExceptionEventArgs e)\n{\n var exception = e.ExceptionObject as Exception;\n //do stuff\n}\n</code></pre>\n<p>There is a reason for this. Unhandled native exceptions can indicate a corrupted state that you can't recover from (eg stack overflow or access violation). However, there are cases you still want to do stuff before terminating the process, like log the error that just tried to crash your windows service!!!</p>\n<h2>A bit of History</h2>\n<p>None of the following is required any more.<br />\nFrom .Net 2.0 - 3.5 you could use an empty catch:</p>\n<pre><code>try \n{\n //call native code method\n} \ncatch (Exception ex) \n{\n //do stuff\n} \ncatch \n{\n //do same stuff but without any exception detail\n}\n</code></pre>\n<p>From .Net 4 they <a href=\"https://learn.microsoft.com/en-us/archive/msdn-magazine/2009/february/clr-inside-out-handling-corrupted-state-exceptions\" rel=\"nofollow noreferrer\">turned off</a> native exceptions being abled to be caught by default and you needed to explicitly turn it back on by decorating your methods with attributes.</p>\n<pre><code>[HandleProcessCorruptedStateExceptions] \n[SecurityCritical]\nprivate static void Main() \n{ \n try \n {\n //call native code method\n } \n catch (Exception ex) \n {\n //do stuff\n } \n}\n</code></pre>\n<p>also required was a <a href=\"https://learn.microsoft.com/en-us/dotnet/framework/configure-apps/file-schema/runtime/legacycorruptedstateexceptionspolicy-element\" rel=\"nofollow noreferrer\">change</a> to the app.config file:</p>\n<pre><code><configuration> \n <runtime> \n <legacyCorruptedStateExceptionsPolicy enabled="true" /> \n </runtime> \n</configuration> \n</code></pre>\n"
}
]
| 2008/09/29 | [
"https://Stackoverflow.com/questions/150544",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/17693/"
]
| In C# code can you catch a native exception thrown from deep in some unmanaged library? If so do you need to do anything differently to catch it or does a standard try...catch get it? | You can use [Win32Exception](http://msdn.microsoft.com/en-us/library/system.componentmodel.win32exception.aspx) and use its NativeErrorCode property to handle it appropriately.
```
// http://support.microsoft.com/kb/186550
const int ERROR_FILE_NOT_FOUND = 2;
const int ERROR_ACCESS_DENIED = 5;
const int ERROR_NO_APP_ASSOCIATED = 1155;
void OpenFile(string filePath)
{
Process process = new Process();
try
{
// Calls native application registered for the file type
// This may throw native exception
process.StartInfo.FileName = filePath;
process.StartInfo.Verb = "Open";
process.StartInfo.CreateNoWindow = true;
process.Start();
}
catch (Win32Exception e)
{
if (e.NativeErrorCode == ERROR_FILE_NOT_FOUND ||
e.NativeErrorCode == ERROR_ACCESS_DENIED ||
e.NativeErrorCode == ERROR_NO_APP_ASSOCIATED)
{
MessageBox.Show(this, e.Message, "Error",
MessageBoxButtons.OK,
MessageBoxIcon.Exclamation);
}
}
}
``` |
150,548 | <p>Despite the rather clear <a href="http://www.adobe.com/support/flash/action_scripts/actionscript_dictionary/actionscript_dictionary620.html" rel="noreferrer">documentation</a> which says that <a href="http://livedocs.adobe.com/flash/9.0/ActionScriptLangRefV3/package.html#parseFloat()" rel="noreferrer">parseFloat()</a> can return NaN as a value, when I write a block like:</p>
<pre><code>if ( NaN == parseFloat(input.text) ) {
errorMessage.text = "Please enter a number."
}
</code></pre>
<p>I am warned that the comparison will always be false. And testing shows the warning to be correct.</p>
<p>Where is the corrected documentation, and how can I write this to work with AS3?</p>
| [
{
"answer_id": 150558,
"author": "Duncan Smart",
"author_id": 1278,
"author_profile": "https://Stackoverflow.com/users/1278",
"pm_score": 5,
"selected": true,
"text": "<p>Because comparing anything to NaN is always false. Use isNaN() instead.</p>\n"
},
{
"answer_id": 150559,
"author": "olle",
"author_id": 22422,
"author_profile": "https://Stackoverflow.com/users/22422",
"pm_score": 3,
"selected": false,
"text": "<p>isNaN(parseFloat(input.text))</p>\n"
},
{
"answer_id": 150938,
"author": "JustLogic",
"author_id": 21664,
"author_profile": "https://Stackoverflow.com/users/21664",
"pm_score": 0,
"selected": false,
"text": "<p>Documentation can be found in the Adobe Flex Language Reference <a href=\"http://livedocs.adobe.com/flex/2/langref/package.html#isNaN()\" rel=\"nofollow noreferrer\">Here</a> as well as other globally available functions.</p>\n"
},
{
"answer_id": 183596,
"author": "Matt W",
"author_id": 4969,
"author_profile": "https://Stackoverflow.com/users/4969",
"pm_score": 2,
"selected": false,
"text": "<p>BTW, if for some reason you don't have access to isNaN(), the traditional method is to compare the number to itself:</p>\n\n<pre><code>if( number != number )\n{\n //Is NaN \n}\n</code></pre>\n"
}
]
| 2008/09/29 | [
"https://Stackoverflow.com/questions/150548",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/459/"
]
| Despite the rather clear [documentation](http://www.adobe.com/support/flash/action_scripts/actionscript_dictionary/actionscript_dictionary620.html) which says that [parseFloat()](http://livedocs.adobe.com/flash/9.0/ActionScriptLangRefV3/package.html#parseFloat()) can return NaN as a value, when I write a block like:
```
if ( NaN == parseFloat(input.text) ) {
errorMessage.text = "Please enter a number."
}
```
I am warned that the comparison will always be false. And testing shows the warning to be correct.
Where is the corrected documentation, and how can I write this to work with AS3? | Because comparing anything to NaN is always false. Use isNaN() instead. |
150,552 | <p>I will preface this question by saying, I do not think it is solvable. I also have a workaround, I can create a stored procedure with an OUTPUT to accomplish this, it is just easier to code the sections where I need this checksum using a function.</p>
<p>This code will not work because of the <code>Exec SP_ExecuteSQL @SQL</code> calls. Anyone know how to execute dynamic SQL in a function? (and once again, I do not think it is possible. If it is though, I'd love to know how to get around it!)</p>
<pre><code>Create Function Get_Checksum
(
@DatabaseName varchar(100),
@TableName varchar(100)
)
RETURNS FLOAT
AS
BEGIN
Declare @SQL nvarchar(4000)
Declare @ColumnName varchar(100)
Declare @i int
Declare @Checksum float
Declare @intColumns table (idRecord int identity(1,1), ColumnName varchar(255))
Declare @CS table (MyCheckSum bigint)
Set @SQL =
'Insert Into @IntColumns(ColumnName)' + Char(13) +
'Select Column_Name' + Char(13) +
'From ' + @DatabaseName + '.Information_Schema.Columns (NOLOCK)' + Char(13) +
'Where Table_Name = ''' + @TableName + '''' + Char(13) +
' and Data_Type = ''int'''
-- print @SQL
exec sp_executeSql @SQL
Set @SQL =
'Insert Into @CS(MyChecksum)' + Char(13) +
'Select '
Set @i = 1
While Exists(
Select 1
From @IntColumns
Where IdRecord = @i)
begin
Select @ColumnName = ColumnName
From @IntColumns
Where IdRecord = @i
Set @SQL = @SQL + Char(13) +
CASE WHEN @i = 1 THEN
' Sum(Cast(IsNull(' + @ColumnName + ',0) as bigint))'
ELSE
' + Sum(Cast(IsNull(' + @ColumnName + ',0) as bigint))'
END
Set @i = @i + 1
end
Set @SQL = @SQL + Char(13) +
'From ' + @DatabaseName + '..' + @TableName + ' (NOLOCK)'
-- print @SQL
exec sp_executeSql @SQL
Set @Checksum = (Select Top 1 MyChecksum From @CS)
Return isnull(@Checksum,0)
END
GO
</code></pre>
| [
{
"answer_id": 150567,
"author": "Cade Roux",
"author_id": 18255,
"author_profile": "https://Stackoverflow.com/users/18255",
"pm_score": 2,
"selected": false,
"text": "<p>You can get around this by calling an extended stored procedure, with all the attendant hassle and security problems.</p>\n\n<p><a href=\"http://decipherinfosys.wordpress.com/2008/07/16/udf-limitations-in-sql-server/\" rel=\"nofollow noreferrer\">http://decipherinfosys.wordpress.com/2008/07/16/udf-limitations-in-sql-server/</a></p>\n\n<p><a href=\"http://decipherinfosys.wordpress.com/2007/02/27/using-getdate-in-a-udf/\" rel=\"nofollow noreferrer\">http://decipherinfosys.wordpress.com/2007/02/27/using-getdate-in-a-udf/</a></p>\n"
},
{
"answer_id": 150576,
"author": "ConcernedOfTunbridgeWells",
"author_id": 15401,
"author_profile": "https://Stackoverflow.com/users/15401",
"pm_score": 0,
"selected": false,
"text": "<p>Because functions have to play nicely with the query optimiser there are quite a few restrictions on them. <a href=\"http://blog.sqlauthority.com/2007/05/29/sql-server-user-defined-functions-udf-limitations/\" rel=\"nofollow noreferrer\">This link</a> refers to an article that discusses the limitations of UDF's in depth.</p>\n"
},
{
"answer_id": 150595,
"author": "Rob",
"author_id": 7872,
"author_profile": "https://Stackoverflow.com/users/7872",
"pm_score": 5,
"selected": true,
"text": "<p>It \"ordinarily\" can't be done as SQL Server treats functions as deterministic, which means that for a given set of inputs, it should always return the same outputs. A stored procedure or dynamic sql can be non-deterministic because it can change external state, such as a table, which is relied on.</p>\n\n<p>Given that in SQL server functions are always deterministic, it would be a bad idea from a future maintenance perspective to attempt to circumvent this as it could cause fairly major confusion for anyone who has to support the code in future.</p>\n"
},
{
"answer_id": 154325,
"author": "AJD",
"author_id": 23601,
"author_profile": "https://Stackoverflow.com/users/23601",
"pm_score": 0,
"selected": false,
"text": "<p>Thank you all for the replies.</p>\n\n<p>Ron: FYI, Using that will throw an error.</p>\n\n<p>I agree that not doing what I originally intended is the best solution, I decided to go a different route. My two choices were to use <code>sum(cast(BINARY_CHECKSUM(*) as float))</code> or an output parameter in a stored procedure. After unit testing speed of each, I decided to go with <code>sum(cast(BINARY_CHECKSUM(*) as float))</code> to get a comparable checksum value for each table's data.</p>\n"
},
{
"answer_id": 12434613,
"author": "Praveen Kumar G",
"author_id": 1672896,
"author_profile": "https://Stackoverflow.com/users/1672896",
"pm_score": 2,
"selected": false,
"text": "<p>Here is the solution</p>\n\n<p><strong>Solution 1:</strong>\nReturn the dynamic string from Function then </p>\n\n<pre><code>Declare @SQLStr varchar(max) \nDECLARE @tmptable table (<columns>)\nset @SQLStr=dbo.function(<parameters>)\ninsert into @tmptable\nExec (@SQLStr)\n\nselect * from @tmptable\n</code></pre>\n\n<p><strong>Solution 2:</strong>\ncall nested functions by passing parameters.</p>\n"
}
]
| 2008/09/29 | [
"https://Stackoverflow.com/questions/150552",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/23601/"
]
| I will preface this question by saying, I do not think it is solvable. I also have a workaround, I can create a stored procedure with an OUTPUT to accomplish this, it is just easier to code the sections where I need this checksum using a function.
This code will not work because of the `Exec SP_ExecuteSQL @SQL` calls. Anyone know how to execute dynamic SQL in a function? (and once again, I do not think it is possible. If it is though, I'd love to know how to get around it!)
```
Create Function Get_Checksum
(
@DatabaseName varchar(100),
@TableName varchar(100)
)
RETURNS FLOAT
AS
BEGIN
Declare @SQL nvarchar(4000)
Declare @ColumnName varchar(100)
Declare @i int
Declare @Checksum float
Declare @intColumns table (idRecord int identity(1,1), ColumnName varchar(255))
Declare @CS table (MyCheckSum bigint)
Set @SQL =
'Insert Into @IntColumns(ColumnName)' + Char(13) +
'Select Column_Name' + Char(13) +
'From ' + @DatabaseName + '.Information_Schema.Columns (NOLOCK)' + Char(13) +
'Where Table_Name = ''' + @TableName + '''' + Char(13) +
' and Data_Type = ''int'''
-- print @SQL
exec sp_executeSql @SQL
Set @SQL =
'Insert Into @CS(MyChecksum)' + Char(13) +
'Select '
Set @i = 1
While Exists(
Select 1
From @IntColumns
Where IdRecord = @i)
begin
Select @ColumnName = ColumnName
From @IntColumns
Where IdRecord = @i
Set @SQL = @SQL + Char(13) +
CASE WHEN @i = 1 THEN
' Sum(Cast(IsNull(' + @ColumnName + ',0) as bigint))'
ELSE
' + Sum(Cast(IsNull(' + @ColumnName + ',0) as bigint))'
END
Set @i = @i + 1
end
Set @SQL = @SQL + Char(13) +
'From ' + @DatabaseName + '..' + @TableName + ' (NOLOCK)'
-- print @SQL
exec sp_executeSql @SQL
Set @Checksum = (Select Top 1 MyChecksum From @CS)
Return isnull(@Checksum,0)
END
GO
``` | It "ordinarily" can't be done as SQL Server treats functions as deterministic, which means that for a given set of inputs, it should always return the same outputs. A stored procedure or dynamic sql can be non-deterministic because it can change external state, such as a table, which is relied on.
Given that in SQL server functions are always deterministic, it would be a bad idea from a future maintenance perspective to attempt to circumvent this as it could cause fairly major confusion for anyone who has to support the code in future. |
150,606 | <p>I have a website laid out in tables. (a long mortgage form)</p>
<p>in each table cell is one HTML object. (text box, radio buttons, etc)</p>
<p>What can I do so when each table cell is "tabbed" into it highlights the cell with a very light red (not to be obtrusive, but tell the user where they are)?</p>
| [
{
"answer_id": 150629,
"author": "roenving",
"author_id": 23142,
"author_profile": "https://Stackoverflow.com/users/23142",
"pm_score": 0,
"selected": false,
"text": "<p>Possibly:</p>\n\n<pre><code><script type=\"text/javascript\">\n//getParent(startElement,\"tagName\");\nfunction getParent(elm,tN){\n var parElm = elm.parentNode;\n while(parElm.tagName.toLowerCase() != tN.toLowerCase())\n parElm = parElm.parentNode;\n return parElm;\n}\n</script>\n\n<tr><td><input type=\"...\" onfocus=\"getParent(this,'td').style.backgroundColor='#400';\" onblur=\"getParent(this,'td').style.backgroundColor='';\"></td></tr>\n</code></pre>\n"
},
{
"answer_id": 150776,
"author": "Parand",
"author_id": 13055,
"author_profile": "https://Stackoverflow.com/users/13055",
"pm_score": 3,
"selected": false,
"text": "<p>Use jQuery to make your life easier, and you can do something like this:</p>\n\n<pre><code>$('#mytableid input').focus( function() { \n $(this).addClass('highlight'); \n}).blur( function() {\n $(this).removeClass('highlight'); \n});\n</code></pre>\n\n<p>This is basically saying when any input element in your table is under focus add the \"highlight\" class to it, and once it loses focus remove the class.</p>\n\n<p>Setup your css as:</p>\n\n<pre><code>input.highlight { background-color: red; }\n</code></pre>\n\n<p>and you should be set.</p>\n"
},
{
"answer_id": 150813,
"author": "Jason Bunting",
"author_id": 1790,
"author_profile": "https://Stackoverflow.com/users/1790",
"pm_score": 3,
"selected": true,
"text": "<p>This is the table I tested my code on:</p>\n\n<pre><code><table id=\"myTable\">\n <tr>\n <td><input type=\"text\" value=\"hello\" /></td>\n <td><input type=\"checkbox\" name=\"foo\" value=\"2\" /></td>\n <td><input type=\"button\" value=\"hi\" /></td>\n </tr>\n</table>\n</code></pre>\n\n<p>Here is the code that worked:</p>\n\n<pre><code>// here is a cross-browser compatible way of connecting \n// handlers to events, in case you don't have one\nfunction attachEventHandler(element, eventToHandle, eventHandler) {\n if(element.attachEvent) {\n element.attachEvent(eventToHandle, eventHandler);\n } else if(element.addEventListener) {\n element.addEventListener(eventToHandle.replace(\"on\", \"\"), eventHandler, false);\n } else {\n element[eventToHandle] = eventHandler;\n }\n}\nattachEventHandler(window, \"onload\", function() {\n var myTable = document.getElementById(\"myTable\");\n var myTableCells = myTable.getElementsByTagName(\"td\");\n for(var cellIndex = 0; cellIndex < myTableCells.length; cellIndex++) {\n var currentTableCell = myTableCells[cellIndex];\n var originalBackgroundColor = currentTableCell.style.backgroundColor;\n for(var childIndex = 0; childIndex < currentTableCell.childNodes.length; childIndex++) {\n var currentChildNode = currentTableCell.childNodes[childIndex];\n attachEventHandler(currentChildNode, \"onfocus\", function(e) {\n (e.srcElement || e.target).parentNode.style.backgroundColor = \"red\";\n });\n attachEventHandler(currentChildNode, \"onblur\", function(e) {\n (e.srcElement || e.target).parentNode.style.backgroundColor = originalBackgroundColor;\n });\n }\n }\n});\n</code></pre>\n\n<p>There are probably things here you could clean up, but I whipped this together quickly. This works even if there are multiple things in each cell.</p>\n\n<p>This would be much easier, it should go without saying, if you used a library to assist you in this work - <a href=\"http://jquery.com\" rel=\"nofollow noreferrer\"><strong>jQuery</strong></a> and <a href=\"http://MochiKit.com\" rel=\"nofollow noreferrer\"><strong>MochiKit</strong></a> are the two I favor, though there are others that would work just as well.</p>\n\n<hr>\n\n<p>Between the time I started writing this answer and the time I posted it, someone posted code that shows how you would do something like this in jQuery - as you can see, much shorter! Although I love libraries, I know some people either can't or will not use a library - in those cases my code should do the job.</p>\n"
}
]
| 2008/09/29 | [
"https://Stackoverflow.com/questions/150606",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
]
| I have a website laid out in tables. (a long mortgage form)
in each table cell is one HTML object. (text box, radio buttons, etc)
What can I do so when each table cell is "tabbed" into it highlights the cell with a very light red (not to be obtrusive, but tell the user where they are)? | This is the table I tested my code on:
```
<table id="myTable">
<tr>
<td><input type="text" value="hello" /></td>
<td><input type="checkbox" name="foo" value="2" /></td>
<td><input type="button" value="hi" /></td>
</tr>
</table>
```
Here is the code that worked:
```
// here is a cross-browser compatible way of connecting
// handlers to events, in case you don't have one
function attachEventHandler(element, eventToHandle, eventHandler) {
if(element.attachEvent) {
element.attachEvent(eventToHandle, eventHandler);
} else if(element.addEventListener) {
element.addEventListener(eventToHandle.replace("on", ""), eventHandler, false);
} else {
element[eventToHandle] = eventHandler;
}
}
attachEventHandler(window, "onload", function() {
var myTable = document.getElementById("myTable");
var myTableCells = myTable.getElementsByTagName("td");
for(var cellIndex = 0; cellIndex < myTableCells.length; cellIndex++) {
var currentTableCell = myTableCells[cellIndex];
var originalBackgroundColor = currentTableCell.style.backgroundColor;
for(var childIndex = 0; childIndex < currentTableCell.childNodes.length; childIndex++) {
var currentChildNode = currentTableCell.childNodes[childIndex];
attachEventHandler(currentChildNode, "onfocus", function(e) {
(e.srcElement || e.target).parentNode.style.backgroundColor = "red";
});
attachEventHandler(currentChildNode, "onblur", function(e) {
(e.srcElement || e.target).parentNode.style.backgroundColor = originalBackgroundColor;
});
}
}
});
```
There are probably things here you could clean up, but I whipped this together quickly. This works even if there are multiple things in each cell.
This would be much easier, it should go without saying, if you used a library to assist you in this work - [**jQuery**](http://jquery.com) and [**MochiKit**](http://MochiKit.com) are the two I favor, though there are others that would work just as well.
---
Between the time I started writing this answer and the time I posted it, someone posted code that shows how you would do something like this in jQuery - as you can see, much shorter! Although I love libraries, I know some people either can't or will not use a library - in those cases my code should do the job. |
150,610 | <p>The problem itself is simple, but I can't figure out a solution that does it in one query, and here's my "abstraction" of the problem to allow for a simpler explanation:</p>
<p><strong>I will let my original explenation stand, but here's a set of sample data and the result i expect:</strong></p>
<p>Ok, so here's some sample data, i separated pairs by a blank line</p>
<pre><code>-------------
| Key | Col | (Together they from a Unique Pair)
--------------
| 1 Foo |
| 1 Bar |
| |
| 2 Foo |
| |
| 3 Bar |
| |
| 4 Foo |
| 4 Bar |
--------------
</code></pre>
<p>And the result I would expect, <strong>after running the query once</strong>, it need to be able to select this result set in one query:</p>
<pre><code>1 - Foo
2 - Foo
3 - Bar
4 - Foo
</code></pre>
<p><em>Original explenation:</em></p>
<p>I have a table, call it <code>TABLE</code> where I have a two columns say <code>ID</code> and <code>NAME</code> which together form the primary key of the table. Now I want to select something where <code>ID=1</code> and then first checks if it can find a row where <code>NAME</code> has the value "John", if "John" does not exist it should look for a row where <code>NAME</code> is "Bruce" - but only return "John" if both "Bruce" and "John" exists or only "John" exists of course.</p>
<p>Also note that it should be able to return several rows per query that match the above criteria but with different ID/Name-combinations of course, and that the above explanation is just a simplification of the real problem.</p>
<p>I could be completely blinded by my own code and line of thought but I just can't figure this out. </p>
| [
{
"answer_id": 150624,
"author": "Cade Roux",
"author_id": 18255,
"author_profile": "https://Stackoverflow.com/users/18255",
"pm_score": -1,
"selected": false,
"text": "<p>You can use joins instead of the exists and this may improve the query plan in cases where the optimizer is not smart enough:</p>\n\n<pre><code>SELECT f1.id\n ,f1.col\nFROM foo f1 \nLEFT JOIN foo f2\n ON f1.id = f2.id\n AND f2.col = 'Foo'\nWHERE f1.col = 'Foo' \n OR ( f1.col = 'Bar' AND f2.id IS NULL )\n</code></pre>\n"
},
{
"answer_id": 150670,
"author": "Mladen",
"author_id": 21404,
"author_profile": "https://Stackoverflow.com/users/21404",
"pm_score": 0,
"selected": false,
"text": "<p>try this:</p>\n\n<pre><code>select top 1 * from (\nSELECT 1 as num, * FROM TABLE WHERE ID = 1 AND NAME = 'John'\nunion \nSELECT 2 as num, * FROM TABLE WHERE ID = 1 AND NAME = 'Bruce'\n) t\norder by num \n</code></pre>\n"
},
{
"answer_id": 150672,
"author": "Ron Savage",
"author_id": 12476,
"author_profile": "https://Stackoverflow.com/users/12476",
"pm_score": 1,
"selected": false,
"text": "<p>You can join the initial table to itself with an OUTER JOIN like this:</p>\n\n<pre><code>create table #mytest\n (\n id int,\n Name varchar(20)\n );\ngo\n\ninsert into #mytest values (1,'Foo');\ninsert into #mytest values (1,'Bar');\ninsert into #mytest values (2,'Foo');\ninsert into #mytest values (3,'Bar');\ninsert into #mytest values (4,'Foo');\ninsert into #mytest values (4,'Bar');\ngo\n\nselect distinct\n sc.id,\n isnull(fc.Name, sc.Name) sel_name\nfrom\n #mytest sc\n\n LEFT OUTER JOIN #mytest fc\n on (fc.id = sc.id\n and fc.Name = 'Foo')\n</code></pre>\n\n<p>like that.</p>\n"
},
{
"answer_id": 150682,
"author": "Neall",
"author_id": 619,
"author_profile": "https://Stackoverflow.com/users/619",
"pm_score": -1,
"selected": false,
"text": "<p>In PostgreSQL, I believe it would be this:</p>\n\n<pre><code>SELECT DISTINCT ON (id) id, name\nFROM mytable\nORDER BY id, name = 'John' DESC;\n</code></pre>\n\n<p>Update - false sorts before true - I had it backwards originally. Note that DISTINCT ON is a PostgreSQL feature and not part of standard SQL. What happens here is that it only shows you the first row for any given id that it comes across. Since we order by weather the name is John, rows named John will be selected over all other names.</p>\n\n<p>With your second example, it would be:</p>\n\n<pre><code>SELECT DISTINCT ON (key) key, col\nFROM mytable\nORDER BY key, col = 'Foo' DESC;\n</code></pre>\n\n<p>This will give you:</p>\n\n<pre><code>1 - Foo\n2 - Foo\n3 - Bar\n4 - Foo\n</code></pre>\n"
},
{
"answer_id": 150692,
"author": "thr",
"author_id": 452521,
"author_profile": "https://Stackoverflow.com/users/452521",
"pm_score": 0,
"selected": false,
"text": "<p>I came up with a solution myself, but it's kind of complex and slow - nor does it expand well to more advanced queries:</p>\n\n<pre><code>SELECT *\nFROM users\nWHERE name = \"bruce\"\nOR (\n name = \"john\"\n AND NOT id\n IN (\n SELECT id\n FROM posts\n WHERE name = \"bruce\"\n )\n)\n</code></pre>\n\n<p>No alternatives without heavy joins, etc. ?</p>\n"
},
{
"answer_id": 150723,
"author": "thr",
"author_id": 452521,
"author_profile": "https://Stackoverflow.com/users/452521",
"pm_score": 0,
"selected": false,
"text": "<p>Ok, so here's some sample data, i separated pairs by a blank line</p>\n\n<pre><code>-------------\n| Key | Col | (Together they from a Unique Pair)\n--------------\n| 1 Foo |\n| 1 Bar |\n| |\n| 2 Foo |\n| |\n| 3 Bar |\n| |\n| 4 Foo |\n| 4 Bar |\n--------------\n</code></pre>\n\n<p>And the result I would expect:</p>\n\n<pre><code>1 - Foo\n2 - Foo\n3 - Bar\n4 - Foo\n</code></pre>\n\n<p>I did solve it above, but that query is horribly inefficient for lager tables, any other way?</p>\n"
},
{
"answer_id": 150842,
"author": "Matt Rogish",
"author_id": 2590,
"author_profile": "https://Stackoverflow.com/users/2590",
"pm_score": 3,
"selected": true,
"text": "<p>This is fairly similar to what you wrote, but should be fairly speedy as NOT EXISTS is more efficient, in this case, than NOT IN...</p>\n\n<pre><code>mysql> select * from foo;\n+----+-----+\n| id | col |\n+----+-----+\n| 1 | Bar | \n| 1 | Foo | \n| 2 | Foo | \n| 3 | Bar | \n| 4 | Bar | \n| 4 | Foo | \n+----+-----+\n\nSELECT id\n , col\n FROM foo f1 \n WHERE col = 'Foo' \n OR ( col = 'Bar' AND NOT EXISTS( SELECT * \n FROM foo f2\n WHERE f1.id = f2.id \n AND f2.col = 'Foo' \n ) \n ); \n\n+----+-----+\n| id | col |\n+----+-----+\n| 1 | Foo | \n| 2 | Foo | \n| 3 | Bar | \n| 4 | Foo | \n+----+-----+\n</code></pre>\n"
},
{
"answer_id": 164759,
"author": "GilM",
"author_id": 10192,
"author_profile": "https://Stackoverflow.com/users/10192",
"pm_score": 0,
"selected": false,
"text": "<p>Here's an example that works in SQL Server 2005 and later. It's a useful pattern where you want to choose the top row (or top n rows) based on a custom ordering. This will let you not just choose among two values with custom priorities, but any number. You can use the ROW_NUMBER() function and a CASE expression:</p>\n\n<pre><code>CREATE TABLE T (id int, col varchar(10));\n\nINSERT T VALUES (1, 'Foo')\nINSERT T VALUES (1, 'Bar')\nINSERT T VALUES (2, 'Foo')\nINSERT T VALUES (3, 'Bar')\nINSERT T VALUES (4, 'Foo')\nINSERT T VALUES (4, 'Bar')\n\nSELECT id,col\nFROM \n(SELECT id, col,\n ROW_NUMBER() OVER (\n PARTITION BY id \n ORDER BY \n CASE col \n WHEN 'Foo' THEN 1\n WHEN 'Bar' THEN 2 \n ELSE 3 END\n ) AS RowNum \n FROM T\n) AS X\nWHERE RowNum = 1\nORDER BY id\n</code></pre>\n"
},
{
"answer_id": 3933626,
"author": "Brad",
"author_id": 475816,
"author_profile": "https://Stackoverflow.com/users/475816",
"pm_score": 1,
"selected": false,
"text": "<p>No need to make this overly complex, you can just use <code>MAX()</code> and <code>group by ...</code></p>\n\n<pre><code>select id, max(col) from foo group by id\n</code></pre>\n"
}
]
| 2008/09/29 | [
"https://Stackoverflow.com/questions/150610",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/452521/"
]
| The problem itself is simple, but I can't figure out a solution that does it in one query, and here's my "abstraction" of the problem to allow for a simpler explanation:
**I will let my original explenation stand, but here's a set of sample data and the result i expect:**
Ok, so here's some sample data, i separated pairs by a blank line
```
-------------
| Key | Col | (Together they from a Unique Pair)
--------------
| 1 Foo |
| 1 Bar |
| |
| 2 Foo |
| |
| 3 Bar |
| |
| 4 Foo |
| 4 Bar |
--------------
```
And the result I would expect, **after running the query once**, it need to be able to select this result set in one query:
```
1 - Foo
2 - Foo
3 - Bar
4 - Foo
```
*Original explenation:*
I have a table, call it `TABLE` where I have a two columns say `ID` and `NAME` which together form the primary key of the table. Now I want to select something where `ID=1` and then first checks if it can find a row where `NAME` has the value "John", if "John" does not exist it should look for a row where `NAME` is "Bruce" - but only return "John" if both "Bruce" and "John" exists or only "John" exists of course.
Also note that it should be able to return several rows per query that match the above criteria but with different ID/Name-combinations of course, and that the above explanation is just a simplification of the real problem.
I could be completely blinded by my own code and line of thought but I just can't figure this out. | This is fairly similar to what you wrote, but should be fairly speedy as NOT EXISTS is more efficient, in this case, than NOT IN...
```
mysql> select * from foo;
+----+-----+
| id | col |
+----+-----+
| 1 | Bar |
| 1 | Foo |
| 2 | Foo |
| 3 | Bar |
| 4 | Bar |
| 4 | Foo |
+----+-----+
SELECT id
, col
FROM foo f1
WHERE col = 'Foo'
OR ( col = 'Bar' AND NOT EXISTS( SELECT *
FROM foo f2
WHERE f1.id = f2.id
AND f2.col = 'Foo'
)
);
+----+-----+
| id | col |
+----+-----+
| 1 | Foo |
| 2 | Foo |
| 3 | Bar |
| 4 | Foo |
+----+-----+
``` |
150,622 | <p>I'm trying to do this</p>
<pre><code>SELECT `Name`,`Value` FROM `Constants`
WHERE `Name` NOT IN ('Do not get this one'|'or this one');
</code></pre>
<p>But it doesn't seem to work.</p>
<p>How do I get all the values, except for a select few, without doing this:</p>
<pre><code>SELECT `Name`,`Value` FROM `Constants`
WHERE `Name` != 'Do not get this one'
AND `Name` != 'or this one'
</code></pre>
<p>The first one works with int values, but doesn't work with varchar, is there a syntax like the first one, that performs like the second query?</p>
| [
{
"answer_id": 150627,
"author": "jkramer",
"author_id": 12523,
"author_profile": "https://Stackoverflow.com/users/12523",
"pm_score": 2,
"selected": false,
"text": "<p>It's <code>IN('foo', 'bar')</code>, with a comma, not a pipe.</p>\n"
},
{
"answer_id": 150628,
"author": "Orion Adrian",
"author_id": 7756,
"author_profile": "https://Stackoverflow.com/users/7756",
"pm_score": 4,
"selected": true,
"text": "<p>You should put the constants in a table and then do a select statement from that table. If you absolutely don't want a permanent table you can use a temp table. And if don't want to do that, you can use the IN syntax:</p>\n\n<p>NOT IN ('one', 'two')</p>\n"
},
{
"answer_id": 150631,
"author": "skaffman",
"author_id": 21234,
"author_profile": "https://Stackoverflow.com/users/21234",
"pm_score": 1,
"selected": false,
"text": "<p>The IN syntax uses comma-seperated lists</p>\n\n<pre><code>SELECT `Name`,`Value` FROM `Constants` WHERE `Name` NOT IN ('Do not get this one','or this one');\n</code></pre>\n"
}
]
| 2008/09/29 | [
"https://Stackoverflow.com/questions/150622",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/144/"
]
| I'm trying to do this
```
SELECT `Name`,`Value` FROM `Constants`
WHERE `Name` NOT IN ('Do not get this one'|'or this one');
```
But it doesn't seem to work.
How do I get all the values, except for a select few, without doing this:
```
SELECT `Name`,`Value` FROM `Constants`
WHERE `Name` != 'Do not get this one'
AND `Name` != 'or this one'
```
The first one works with int values, but doesn't work with varchar, is there a syntax like the first one, that performs like the second query? | You should put the constants in a table and then do a select statement from that table. If you absolutely don't want a permanent table you can use a temp table. And if don't want to do that, you can use the IN syntax:
NOT IN ('one', 'two') |
150,645 | <p>The MSDN states that the method returns</p>
<blockquote>
<p>true if the method is successfully
queued; NotSupportedException is
thrown if the work item is not queued.</p>
</blockquote>
<p>For testing purposes how to get the method to return <code>false</code>? Or it is just a "suboptimal" class design?</p>
| [
{
"answer_id": 150655,
"author": "Bob King",
"author_id": 6897,
"author_profile": "https://Stackoverflow.com/users/6897",
"pm_score": 1,
"selected": false,
"text": "<p>This is probably a case of \"reserved for future use\". You may want to treat it as failure, but it'll be hard to test.</p>\n\n<p>I pretty much treat this method as a void/Sub.</p>\n"
},
{
"answer_id": 150673,
"author": "Michael Damatov",
"author_id": 23372,
"author_profile": "https://Stackoverflow.com/users/23372",
"pm_score": 1,
"selected": false,
"text": "<p>It is imaginable that the entire API (thread-pools) becomes obsolete, when the Task Parallel Library (TPL) arrives.</p>\n"
},
{
"answer_id": 150688,
"author": "herbrandson",
"author_id": 13181,
"author_profile": "https://Stackoverflow.com/users/13181",
"pm_score": 4,
"selected": true,
"text": "<p>In looking at the source code in Reflector, it seems the only part of the code that could return \"false\" is a call to the following:</p>\n\n<pre><code>[MethodImpl(MethodImplOptions.InternalCall)]\nprivate static extern bool AdjustThreadsInPool(uint QueueLength);\n</code></pre>\n"
},
{
"answer_id": 150719,
"author": "Orion Edwards",
"author_id": 234,
"author_profile": "https://Stackoverflow.com/users/234",
"pm_score": 1,
"selected": false,
"text": "<blockquote>\n <p>true if the method is successfully queued; NotSupportedException is thrown if the work item is not queued.</p>\n</blockquote>\n\n<p>Treat a <code>return false</code> in the same way that you treat a <code>NotSupportedException</code>.</p>\n\n<p>To get it to return false, use a mock method or object.<br>\nYou want to be testing your own code that you wrote, not the underlying windows code. I'm sure microsoft have plenty of their own tests already for that.</p>\n"
}
]
| 2008/09/29 | [
"https://Stackoverflow.com/questions/150645",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/23372/"
]
| The MSDN states that the method returns
>
> true if the method is successfully
> queued; NotSupportedException is
> thrown if the work item is not queued.
>
>
>
For testing purposes how to get the method to return `false`? Or it is just a "suboptimal" class design? | In looking at the source code in Reflector, it seems the only part of the code that could return "false" is a call to the following:
```
[MethodImpl(MethodImplOptions.InternalCall)]
private static extern bool AdjustThreadsInPool(uint QueueLength);
``` |
150,646 | <p>I'm trying to create a new Excel file using jxl, but am having a hard time finding examples in their API documentation and online.</p>
| [
{
"answer_id": 150677,
"author": "kolrie",
"author_id": 14540,
"author_profile": "https://Stackoverflow.com/users/14540",
"pm_score": 0,
"selected": false,
"text": "<p>Not sure if you need to stick with JXL, but the best library for handling Excel files is <a href=\"http://poi.apache.org/hssf/index.html\" rel=\"nofollow noreferrer\">Apache's POI HSSF</a>.</p>\n\n<p>I think there are plenty of examples on the website I provided, but if you need further assistence, let me know. I may have a few examples laying around.</p>\n\n<p>Just out of curiosity, POI stands for Poor Obfuscation Interface and HSSF is Horrible SpreadSheet Format. You see how much Apache loves Microsoft Office formats :-)</p>\n"
},
{
"answer_id": 150713,
"author": "Aaron",
"author_id": 2628,
"author_profile": "https://Stackoverflow.com/users/2628",
"pm_score": 5,
"selected": true,
"text": "<p>After messing around awhile longer I finally found something that worked and saw there still wasn't a solution posted here yet, so here's what I found:</p>\n\n<pre><code>try {\n String fileName = \"file.xls\";\n WritableWorkbook workbook = Workbook.createWorkbook(new File(fileName));\n workbook.createSheet(\"Sheet1\", 0);\n workbook.createSheet(\"Sheet2\", 1);\n workbook.createSheet(\"Sheet3\", 2);\n workbook.write();\n workbook.close();\n} catch (WriteException e) {\n\n}\n</code></pre>\n"
},
{
"answer_id": 15957747,
"author": "Zaheer Astori",
"author_id": 2271921,
"author_profile": "https://Stackoverflow.com/users/2271921",
"pm_score": 2,
"selected": false,
"text": "<p>First of all you need to put Jxl Api into your java directory , download JXL api from <a href=\"http://www.andykhan.com/\" rel=\"nofollow\">http://www.andykhan.com/</a> extract it,copy jxl and paste like C:\\Program Files\\Java\\jre7\\lib\\ext.</p>\n\n<pre><code>try {\n String fileName = \"file.xls\";\n WritableWorkbook workbook = Workbook.createWorkbook(new File(fileName));\n WritableSheet writablesheet1 = workbook.createSheet(\"Sheet1\", 0);\n WritableSheet writablesheet2 = workbook.createSheet(\"Sheet2\", 1);\n WritableSheet writablesheet3 = workbook.createSheet(\"Sheet3\", 2);\n Label label1 = new Label(\"Emp_Name\");\n Label label2 = new Label(\"Emp_FName\");\n Label label3 = new Label(\"Emp_Salary\");\n writablesheet1.addCell(label1);\n writablesheet2.addCell(label2);\n writablesheet3.addCell(label3);\n workbook.write();\n workbook.close();\n} catch (WriteException e) {\n\n}\n</code></pre>\n"
},
{
"answer_id": 32281159,
"author": "Almir Campos",
"author_id": 2457251,
"author_profile": "https://Stackoverflow.com/users/2457251",
"pm_score": 2,
"selected": false,
"text": "<p>I know that it's a very old question. However, I think I can contribute with an example that also adds the cell values:</p>\n\n<pre><code>/**\n *\n * @author Almir Campos\n */\npublic class Write01\n{\n public void test01() throws IOException, WriteException\n {\n // Initial settings\n File file = new File( \"c:/tmp/genexcel.xls\" );\n WorkbookSettings wbs = new WorkbookSettings();\n wbs.setLocale( new Locale( \"en\", \"EN\" ) );\n // Creates the workbook\n WritableWorkbook wwb = Workbook.createWorkbook( file, wbs );\n // Creates the sheet inside the workbook\n wwb.createSheet( \"Report\", 0 );\n // Makes the sheet writable\n WritableSheet ws = wwb.getSheet( 0 );\n // Creates a cell inside the sheet\n //CellView cv = new CellView();\n Number n;\n Label l;\n Formula f;\n for ( int i = 0; i < 10; i++ )\n {\n // A\n n = new Number( 0, i, i );\n ws.addCell( n );\n // B\n l = new Label( 1, i, \"by\" );\n ws.addCell( l );\n // C\n n = new Number( 2, i, i + 1 );\n ws.addCell( n );\n // D\n l = new Label( 3, i, \"is\" );\n ws.addCell( l );\n // E\n f = new Formula(4, i, \"A\" + (i+1) + \"*C\" + (i+1) );\n ws.addCell( f );\n }\n wwb.write();\n wwb.close();\n }\n}\n</code></pre>\n"
},
{
"answer_id": 37732850,
"author": "Kavos Khajavi",
"author_id": 4433550,
"author_profile": "https://Stackoverflow.com/users/4433550",
"pm_score": -1,
"selected": false,
"text": "<pre><code>public void exportToExcel() {\n final String fileName = \"TodoList2.xls\";\n\n //Saving file in external storage\n File sdCard = Environment.getExternalStorageDirectory();\n File directory = new File(sdCard.getAbsolutePath() + \"/javatechig.todo\");\n\n //create directory if not exist\n if(!directory.isDirectory()){\n directory.mkdirs();\n }\n\n //file path\n File file = new File(directory, fileName);\n\n WorkbookSettings wbSettings = new WorkbookSettings();\n wbSettings.setLocale(new Locale(\"en\", \"EN\"));\n WritableWorkbook workbook;\n\n\n try {\n workbook = Workbook.createWorkbook(file, wbSettings);\n //Excel sheet name. 0 represents first sheet\n WritableSheet sheet = workbook.createSheet(\"MyShoppingList\", 0);\n\n\n\n Cursor cursor = mydb.rawQuery(\"select * from Contact\", null);\n\n try {\n sheet.addCell(new Label(0, 0, \"id\")); // column and row\n sheet.addCell(new Label(1, 0, \"name\"));\n sheet.addCell(new Label(2,0,\"ff \"));\n sheet.addCell(new Label(3,0,\"uu\"));\n if (cursor.moveToFirst()) {\n do {\n String title =cursor.getString(0) ;\n String desc = cursor.getString(1);\n String name=cursor.getString(2);\n String family=cursor.getString(3);\n\n int i = cursor.getPosition() + 1;\n sheet.addCell(new Label(0, i, title));\n sheet.addCell(new Label(1, i, desc));\n sheet.addCell(new Label(2,i,name));\n sheet.addCell(new Label(3,i,family));\n } while (cursor.moveToNext());\n }\n //closing cursor\n cursor.close();\n } catch (RowsExceededException e) {\n e.printStackTrace();\n } catch (WriteException e) {\n e.printStackTrace();\n }\n workbook.write();\n try {\n workbook.close();\n } catch (WriteException e) {\n e.printStackTrace();\n }\n } catch (IOException e) {\n e.printStackTrace();\n }\n}\n</code></pre>\n"
}
]
| 2008/09/29 | [
"https://Stackoverflow.com/questions/150646",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2628/"
]
| I'm trying to create a new Excel file using jxl, but am having a hard time finding examples in their API documentation and online. | After messing around awhile longer I finally found something that worked and saw there still wasn't a solution posted here yet, so here's what I found:
```
try {
String fileName = "file.xls";
WritableWorkbook workbook = Workbook.createWorkbook(new File(fileName));
workbook.createSheet("Sheet1", 0);
workbook.createSheet("Sheet2", 1);
workbook.createSheet("Sheet3", 2);
workbook.write();
workbook.close();
} catch (WriteException e) {
}
``` |
150,687 | <p>I would like to subscribe to the ItemCommand event of a Reorderlist I have on my page. The front end looks like this...</p>
<pre><code><cc1:ReorderList id="ReorderList1" runat="server" CssClass="Sortables" Width="400" OnItemReorder="ReorderList1_ItemReorder" OnItemCommand="ReorderList1_ItemCommand">
...
<asp:ImageButton ID="btnDelete" runat="server" ImageUrl="delete.jpg" CommandName="delete" CssClass="playClip" />
...
</cc1:ReorderList>
</code></pre>
<p>in the back-end I have this on Page_Load</p>
<pre><code>ReorderList1.ItemCommand += new EventHandler<AjaxControlToolkit.ReorderListCommandEventArgs>(ReorderList1_ItemCommand);
</code></pre>
<p>and this function defined</p>
<pre><code>protected void ReorderList1_ItemCommand(object sender, AjaxControlToolkit.ReorderListCommandEventArgs e)
{
if (e.Item.ItemType == ListItemType.Item || e.Item.ItemType == ListItemType.AlternatingItem)
{
if (e.CommandName == "delete")
{
//do something here that deletes the list item
}
}
}
</code></pre>
<p>Despite my best efforts though, I can't seem to get this event to fire off. How do you properly subscribe to this events in a ReorderList control?</p>
| [
{
"answer_id": 151417,
"author": "Fung",
"author_id": 8280,
"author_profile": "https://Stackoverflow.com/users/8280",
"pm_score": 1,
"selected": false,
"text": "<p>Since your ImageButton's <code>CommandName=\"delete\"</code> you should be hooking up to the DeleteCommand event instead of ItemCommand.</p>\n"
},
{
"answer_id": 467777,
"author": "roman m",
"author_id": 3661,
"author_profile": "https://Stackoverflow.com/users/3661",
"pm_score": 2,
"selected": false,
"text": "<p>this works:</p>\n\n<pre><code><cc2:ReorderList ID=\"rlEvents\" runat=\"server\" AllowReorder=\"True\" CssClass=\"reorderList\"\n DataKeyField=\"EventId\" DataSourceID=\"odsEvents\" PostBackOnReorder=\"False\"\n SortOrderField=\"EventOrder\" OnDeleteCommand=\"rlEvents_DeleteCommand\">\n...\n<asp:ImageButton ID=\"btnDeleteEvent\" runat=\"server\" CommandName=\"Delete\" CommandArgument='<%# Eval(\"EventId\") %>' ImageUrl=\"~/images/delete.gif\" />\n...\n</cc2:ReorderList>\n</code></pre>\n\n<p>code behind:</p>\n\n<pre><code>protected void rlEvents_DeleteCommand(object sender, AjaxControlToolkit.ReorderListCommandEventArgs e)\n{\n // delete the item\n // this will give you the DataKeyField for the current record -> int.Parse(e.CommandArgument.ToString());\n //rebind the ReorderList\n}\n</code></pre>\n"
}
]
| 2008/09/29 | [
"https://Stackoverflow.com/questions/150687",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
]
| I would like to subscribe to the ItemCommand event of a Reorderlist I have on my page. The front end looks like this...
```
<cc1:ReorderList id="ReorderList1" runat="server" CssClass="Sortables" Width="400" OnItemReorder="ReorderList1_ItemReorder" OnItemCommand="ReorderList1_ItemCommand">
...
<asp:ImageButton ID="btnDelete" runat="server" ImageUrl="delete.jpg" CommandName="delete" CssClass="playClip" />
...
</cc1:ReorderList>
```
in the back-end I have this on Page\_Load
```
ReorderList1.ItemCommand += new EventHandler<AjaxControlToolkit.ReorderListCommandEventArgs>(ReorderList1_ItemCommand);
```
and this function defined
```
protected void ReorderList1_ItemCommand(object sender, AjaxControlToolkit.ReorderListCommandEventArgs e)
{
if (e.Item.ItemType == ListItemType.Item || e.Item.ItemType == ListItemType.AlternatingItem)
{
if (e.CommandName == "delete")
{
//do something here that deletes the list item
}
}
}
```
Despite my best efforts though, I can't seem to get this event to fire off. How do you properly subscribe to this events in a ReorderList control? | this works:
```
<cc2:ReorderList ID="rlEvents" runat="server" AllowReorder="True" CssClass="reorderList"
DataKeyField="EventId" DataSourceID="odsEvents" PostBackOnReorder="False"
SortOrderField="EventOrder" OnDeleteCommand="rlEvents_DeleteCommand">
...
<asp:ImageButton ID="btnDeleteEvent" runat="server" CommandName="Delete" CommandArgument='<%# Eval("EventId") %>' ImageUrl="~/images/delete.gif" />
...
</cc2:ReorderList>
```
code behind:
```
protected void rlEvents_DeleteCommand(object sender, AjaxControlToolkit.ReorderListCommandEventArgs e)
{
// delete the item
// this will give you the DataKeyField for the current record -> int.Parse(e.CommandArgument.ToString());
//rebind the ReorderList
}
``` |
150,690 | <p><strong>Problem:</strong></p>
<p>Given a list of strings, find the substring which, if subtracted from the beginning of all strings where it matches and replaced by an escape byte, gives the shortest total length.</p>
<p><strong>Example:</strong></p>
<p><code>"foo"</code>, <code>"fool"</code>, <code>"bar"</code></p>
<p>The result is: "foo" as the base string with the strings <code>"\0"</code>, <code>"\0l"</code>, <code>"bar"</code> and a total length of 9 bytes. <code>"\0"</code> is the escape byte. The sum of the length of the original strings is 10, so in this case we only saved one byte.</p>
<p><strong>A naive algorithm would look like:</strong></p>
<pre><code>for string in list
for i = 1, i < length of string
calculate total length based on prefix of string[0..i]
if better than last best, save it
return the best prefix
</code></pre>
<p>That will give us the answer, but it's something like O((n*m)^2), which is too expensive.</p>
| [
{
"answer_id": 150709,
"author": "EBGreen",
"author_id": 1358,
"author_profile": "https://Stackoverflow.com/users/1358",
"pm_score": 1,
"selected": false,
"text": "<p>I would try starting by sorting the list. Then you simply go from string to string comparing the first character to the next string's first char. Once you have a match you would look at the next char. You would need to devise a way to track the best result so far.</p>\n"
},
{
"answer_id": 150729,
"author": "nlucaroni",
"author_id": 157,
"author_profile": "https://Stackoverflow.com/users/157",
"pm_score": 4,
"selected": true,
"text": "<p>Use a forest of prefix trees (trie)...</p>\n\n<pre><code> f_2 b_1\n / |\n o_2 a_1\n | |\n o_2 r_1\n |\n l_1\n</code></pre>\n\n<p>then, we can find the best result, and guarantee it, by maximizing <code>(depth * frequency)</code> which will be replaced with your escape character. You can optimize the search by doing a branch and bound depth first search for the maximum.</p>\n\n<p>On the complexity: O(C), as mentioned in comment, for building it, and for finding the optimal, it depends. If you order the first elements frequency (O(A) --where A is the size of the languages alphabet), then you'll be able to cut out more branches, and have a good chance of getting sub-linear time.</p>\n\n<p>I think this is clear, I am not going to write it up --what is this a homework assignment? ;)</p>\n"
},
{
"answer_id": 150730,
"author": "James Curran",
"author_id": 12725,
"author_profile": "https://Stackoverflow.com/users/12725",
"pm_score": 1,
"selected": false,
"text": "<p>Well, first step would be to sort the list. Then one pass through the list, comparing each element with the previous, keeping track of the longest 2-character, 3-character, 4-character etc runs. Then figure is the 20 3-character prefixes better than the 15 4-character prefixes.</p>\n"
}
]
| 2008/09/29 | [
"https://Stackoverflow.com/questions/150690",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/23423/"
]
| **Problem:**
Given a list of strings, find the substring which, if subtracted from the beginning of all strings where it matches and replaced by an escape byte, gives the shortest total length.
**Example:**
`"foo"`, `"fool"`, `"bar"`
The result is: "foo" as the base string with the strings `"\0"`, `"\0l"`, `"bar"` and a total length of 9 bytes. `"\0"` is the escape byte. The sum of the length of the original strings is 10, so in this case we only saved one byte.
**A naive algorithm would look like:**
```
for string in list
for i = 1, i < length of string
calculate total length based on prefix of string[0..i]
if better than last best, save it
return the best prefix
```
That will give us the answer, but it's something like O((n\*m)^2), which is too expensive. | Use a forest of prefix trees (trie)...
```
f_2 b_1
/ |
o_2 a_1
| |
o_2 r_1
|
l_1
```
then, we can find the best result, and guarantee it, by maximizing `(depth * frequency)` which will be replaced with your escape character. You can optimize the search by doing a branch and bound depth first search for the maximum.
On the complexity: O(C), as mentioned in comment, for building it, and for finding the optimal, it depends. If you order the first elements frequency (O(A) --where A is the size of the languages alphabet), then you'll be able to cut out more branches, and have a good chance of getting sub-linear time.
I think this is clear, I am not going to write it up --what is this a homework assignment? ;) |
150,695 | <p>It seems like Sql Reporting Services Server logs information in several places including web server logs and logging tables in the database. Where are all the locations SSRS logs to, and what type of errors are logged in each place?</p>
| [
{
"answer_id": 150896,
"author": "Tomas",
"author_id": 23360,
"author_profile": "https://Stackoverflow.com/users/23360",
"pm_score": 5,
"selected": true,
"text": "<p>As far as I know SSRS logs to the Event Log, the filesystem and its own database.</p>\n\n<p>The database is typically the most easily available one. You just login to the ReportServer database and execute </p>\n\n<pre><code>select * from executionlog\n</code></pre>\n\n<p>This only logs the executions though. If you want more information you can go to the Trace Log files, which are usually available at (location may of course vary):</p>\n\n<pre><code>C:\\Program Files\\Microsoft SQL Server\\MSSQL.3\\Reporting Services\\LogFiles\n</code></pre>\n\n<p>These are quite verbose and not really fun to look through. But they do log a lot of stuff.</p>\n\n<p>If you're searching for an error you can go to the Windows Application Log (Under Administrative Tools in your control panel)</p>\n\n<p><strong>Edit</strong> Found a nice link:<br>\n<a href=\"https://learn.microsoft.com/en-us/sql/reporting-services/report-server/reporting-services-log-files-and-sources\" rel=\"nofollow noreferrer\">https://learn.microsoft.com/en-us/sql/reporting-services/report-server/reporting-services-log-files-and-sources</a></p>\n"
},
{
"answer_id": 13257140,
"author": "demp",
"author_id": 875109,
"author_profile": "https://Stackoverflow.com/users/875109",
"pm_score": 3,
"selected": false,
"text": "<p>For SSRS 2008 R2:\nC:\\Program Files\\Microsoft SQL Server\\MSRS10_50.MSSQLSERVER\\Reporting Services\\LogFiles</p>\n"
}
]
| 2008/09/29 | [
"https://Stackoverflow.com/questions/150695",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1644/"
]
| It seems like Sql Reporting Services Server logs information in several places including web server logs and logging tables in the database. Where are all the locations SSRS logs to, and what type of errors are logged in each place? | As far as I know SSRS logs to the Event Log, the filesystem and its own database.
The database is typically the most easily available one. You just login to the ReportServer database and execute
```
select * from executionlog
```
This only logs the executions though. If you want more information you can go to the Trace Log files, which are usually available at (location may of course vary):
```
C:\Program Files\Microsoft SQL Server\MSSQL.3\Reporting Services\LogFiles
```
These are quite verbose and not really fun to look through. But they do log a lot of stuff.
If you're searching for an error you can go to the Windows Application Log (Under Administrative Tools in your control panel)
**Edit** Found a nice link:
<https://learn.microsoft.com/en-us/sql/reporting-services/report-server/reporting-services-log-files-and-sources> |
150,726 | <p>I was wondering how to use <code>cin</code> so that if the user does not enter in any value and just pushes <code>ENTER</code> that <code>cin</code> will recognize this as valid input.</p>
| [
{
"answer_id": 150749,
"author": "Thorsten79",
"author_id": 19734,
"author_profile": "https://Stackoverflow.com/users/19734",
"pm_score": 2,
"selected": false,
"text": "<p>Does cin.<a href=\"http://www.cplusplus.com/reference/iostream/istream/getline.html\" rel=\"nofollow noreferrer\">getline</a> solve your problem?</p>\n"
},
{
"answer_id": 150761,
"author": "CB Bailey",
"author_id": 19563,
"author_profile": "https://Stackoverflow.com/users/19563",
"pm_score": 3,
"selected": false,
"text": "<p>I find that for user input <code>std::getline</code> works very well.</p>\n\n<p>You can use it to read a line and just discard what it reads.</p>\n\n<p>The problem with doing things like this,</p>\n\n<pre><code>// Read a number:\nstd::cout << \"Enter a number:\";\nstd::cin >> my_double;\n\nstd::count << \"Hit enter to continue:\";\nstd::cin >> throwaway_char;\n// Hmmmm, does this work?\n</code></pre>\n\n<p>is that if the user enters other garbage e.g. \"4.5 - about\" it is all too easy to get out of sync and to read what the user wrote the last time before printing the prompt that he needs to see the next time.</p>\n\n<p>If you read every complete line with <code>std::getline( std::cin, a_string )</code> and then parse the returned string (e.g. using an istringstream or other technique) it is much easier to keep the printed prompts in sync with reading from std::cin, even in the face of garbled input.</p>\n"
},
{
"answer_id": 150768,
"author": "Martin Cote",
"author_id": 9936,
"author_profile": "https://Stackoverflow.com/users/9936",
"pm_score": 5,
"selected": true,
"text": "<p>You will probably want to try <code>std::getline</code>:</p>\n\n<pre><code>#include <iostream>\n#include <string>\n\nstd::string line;\nstd::getline( std::cin, line );\nif( line.empty() ) ...\n</code></pre>\n"
},
{
"answer_id": 150792,
"author": "Kasprzol",
"author_id": 5957,
"author_profile": "https://Stackoverflow.com/users/5957",
"pm_score": 0,
"selected": false,
"text": "<p>Try unbuffering cin (it's buffered by default).</p>\n"
},
{
"answer_id": 29024529,
"author": "BigAlMoho",
"author_id": 4621554,
"author_profile": "https://Stackoverflow.com/users/4621554",
"pm_score": 2,
"selected": false,
"text": "<p>To detect the user pressing the Enter Key rather than entering an integer:</p>\n\n<pre><code>char c;\nint num;\n\ncin.get(c); // get a single character\nif (c == 10) return 0; // 10 = ascii linefeed (Enter Key) so exit\nelse cin.putback(c); // else put the character back\ncin >> num; // get user input as expected\n</code></pre>\n\n<p>Alternatively:</p>\n\n<pre><code>char c;\nint num;\nc = cin.peek(); // read next character without extracting it\nif (c == '\\n') return 0; // linefeed (Enter Key) so exit\ncin >> num; // get user input as expected\n</code></pre>\n"
}
]
| 2008/09/29 | [
"https://Stackoverflow.com/questions/150726",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
]
| I was wondering how to use `cin` so that if the user does not enter in any value and just pushes `ENTER` that `cin` will recognize this as valid input. | You will probably want to try `std::getline`:
```
#include <iostream>
#include <string>
std::string line;
std::getline( std::cin, line );
if( line.empty() ) ...
``` |
150,731 | <p>I would like to write some data to a file in Ruby. What is the best way to do that?</p>
| [
{
"answer_id": 150740,
"author": "thesmallprint",
"author_id": 12765,
"author_profile": "https://Stackoverflow.com/users/12765",
"pm_score": -1,
"selected": false,
"text": "<pre><code>filey = File.new(\"/path/to/the/file\", APPEND)\nfiley.puts \"stuff to write\"\n</code></pre>\n"
},
{
"answer_id": 150745,
"author": "Alex M",
"author_id": 9652,
"author_profile": "https://Stackoverflow.com/users/9652",
"pm_score": 6,
"selected": true,
"text": "<pre><code>File.open(\"a_file\", \"w\") do |f|\n f.write \"some data\"\nend\n</code></pre>\n\n<p>You can also use <code>f << \"some data\"</code> or <code>f.puts \"some data\"</code> according to personal taste/necessity to have newlines. Change the <code>\"w\"</code> to <code>\"a\"</code> if you want to append to the file instead of truncating with each open.</p>\n"
},
{
"answer_id": 150795,
"author": "Mike Woodhouse",
"author_id": 1060,
"author_profile": "https://Stackoverflow.com/users/1060",
"pm_score": 2,
"selected": false,
"text": "<p>Beyond <a href=\"http://www.meshplex.org/wiki/Ruby/File_handling_Input_Output\" rel=\"nofollow noreferrer\">File.new</a> or <a href=\"http://www.ruby-doc.org/core/classes/File.html\" rel=\"nofollow noreferrer\">File.open</a> (and all the other fun IO stuff) you may wish, particularly if you're saving from and loading back into Ruby and your data is in objects, to look at using <a href=\"http://www.ruby-doc.org/core/classes/Marshal.html\" rel=\"nofollow noreferrer\">Marshal</a> to save and load your objects directly.</p>\n"
},
{
"answer_id": 151610,
"author": "jtbandes",
"author_id": 23649,
"author_profile": "https://Stackoverflow.com/users/23649",
"pm_score": 0,
"selected": false,
"text": "<p>Using File::open is the best way to go:</p>\n\n<pre><code>File.open(\"/path/to/file\", \"w\") do |file|\n file.puts \"Hello file!\"\nend\n</code></pre>\n\n<p>As previously stated, you can use \"a\" instead of \"w\" to append to the file. May other modes are available, listed under <code>ri IO</code>, or at the <a href=\"http://www.zenspider.com/Languages/Ruby/QuickRef.html\" rel=\"nofollow noreferrer\">Ruby Quickref</a>.</p>\n"
},
{
"answer_id": 560727,
"author": "alex2k8",
"author_id": 62192,
"author_profile": "https://Stackoverflow.com/users/62192",
"pm_score": 2,
"selected": false,
"text": "<pre><code>require 'rio'\nrio('foo.txt') < 'bar'\n</code></pre>\n\n<p><a href=\"http://rio.rubyforge.org/\" rel=\"nofollow noreferrer\">http://rio.rubyforge.org/</a></p>\n"
}
]
| 2008/09/29 | [
"https://Stackoverflow.com/questions/150731",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1681/"
]
| I would like to write some data to a file in Ruby. What is the best way to do that? | ```
File.open("a_file", "w") do |f|
f.write "some data"
end
```
You can also use `f << "some data"` or `f.puts "some data"` according to personal taste/necessity to have newlines. Change the `"w"` to `"a"` if you want to append to the file instead of truncating with each open. |
150,750 | <p>It's clear that a search performance of the generic <code>HashSet<T></code> class is higher than of the generic <code>List<T></code> class. Just compare the hash-based key with the linear approach in the <code>List<T></code> class.</p>
<p>However calculating a hash key may itself take some CPU cycles, so for a small amount of items the linear search can be a real alternative to the <code>HashSet<T></code>.</p>
<p>My question: where is the break-even?</p>
<p>To simplify the scenario (and to be fair) let's assume that the <code>List<T></code> class uses the element's <code>Equals()</code> method to identify an item.</p>
| [
{
"answer_id": 150766,
"author": "Adam Rosenfield",
"author_id": 9530,
"author_profile": "https://Stackoverflow.com/users/9530",
"pm_score": 2,
"selected": false,
"text": "<p>It depends. If the exact answer really matters, do some profiling and find out. If you're sure you'll never have more than a certain number of elements in the set, go with a List. If the number is unbounded, use a HashSet.</p>\n"
},
{
"answer_id": 150769,
"author": "Walden Leverich",
"author_id": 2673770,
"author_profile": "https://Stackoverflow.com/users/2673770",
"pm_score": 4,
"selected": false,
"text": "<p>The breakeven will depend on the cost of computing the hash. Hash computations can be trivial, or not... :-) There is always the <a href=\"https://learn.microsoft.com/en-us/dotnet/api/system.collections.specialized.hybriddictionary?view=net-6.0\" rel=\"nofollow noreferrer\">System.Collections.Specialized.HybridDictionary</a> class to help you not have to worry about the breakeven point.</p>\n"
},
{
"answer_id": 150772,
"author": "Kyle",
"author_id": 16379,
"author_profile": "https://Stackoverflow.com/users/16379",
"pm_score": 1,
"selected": false,
"text": "<p>Depends on a lot of factors... List implementation, CPU architecture, JVM, loop semantics, complexity of equals method, etc... By the time the list gets big enough to effectively benchmark (1000+ elements), Hash-based binary lookups beat linear searches hands-down, and the difference only scales up from there. </p>\n\n<p>Hope this helps!</p>\n"
},
{
"answer_id": 150783,
"author": "Peter",
"author_id": 22517,
"author_profile": "https://Stackoverflow.com/users/22517",
"pm_score": 2,
"selected": false,
"text": "<p>Depends on what you're hashing. If your keys are integers you probably don't need very many items before the HashSet is faster. If you're keying it on a string then it will be slower, and depends on the input string.</p>\n\n<p>Surely you could whip up a benchmark pretty easily?</p>\n"
},
{
"answer_id": 150794,
"author": "Robert P",
"author_id": 18097,
"author_profile": "https://Stackoverflow.com/users/18097",
"pm_score": 3,
"selected": false,
"text": "<p>The answer, as always, is \"<strong>It depends</strong>\". I assume from the tags you're talking about C#.</p>\n\n<p>Your best bet is to determine</p>\n\n<ol>\n<li>A Set of data</li>\n<li>Usage requirements</li>\n</ol>\n\n<p>and write some test cases.</p>\n\n<p>It also depends on how you sort the list (if it's sorted at all), what kind of comparisons need to be made, how long the \"Compare\" operation takes for the particular object in the list, or even how you intend to use the collection.</p>\n\n<p>Generally, the best one to choose isn't so much based on the size of data you're working with, but rather how you intend to access it. Do you have each piece of data associated with a particular string, or other data? A hash based collection would probably be best. Is the order of the data you're storing important, or are you going to need to access all of the data at the same time? A regular list may be better then.</p>\n\n<p>Additional:</p>\n\n<p>Of course, my above comments assume 'performance' means data access. Something else to consider: what are you looking for when you say \"performance\"? Is performance individual value look up? Is it management of large (10000, 100000 or more) value sets? Is it the performance of filling the data structure with data? Removing data? Accessing individual bits of data? Replacing values? Iterating over the values? Memory usage? Data copying speed? For example, If you access data by a string value, but your main performance requirement is minimal memory usage, you might have conflicting design issues.</p>\n"
},
{
"answer_id": 150840,
"author": "core",
"author_id": 11574,
"author_profile": "https://Stackoverflow.com/users/11574",
"pm_score": 6,
"selected": false,
"text": "<p>Whether to use a HashSet<> or List<> comes down to <i>how you need to access your collection</i>. If you need to guarantee the order of items, use a List. If you don't, use a HashSet. Let Microsoft worry about the implementation of their hashing algorithms and objects.</p>\n\n<p>A HashSet will access items without having to enumerate the collection (complexity of <a href=\"http://en.wikipedia.org/wiki/Big_O_notation\" rel=\"noreferrer\">O(1)</a> or near it), and because a List guarantees order, unlike a HashSet, some items will have to be enumerated (complexity of O(n)).</p>\n"
},
{
"answer_id": 151097,
"author": "JaredPar",
"author_id": 23283,
"author_profile": "https://Stackoverflow.com/users/23283",
"pm_score": 2,
"selected": false,
"text": "<p>One factor your not taking into account is the robustness of the GetHashcode() function. With a perfect hash function the HashSet will clearly have better searching performance. But as the hash function diminishes so will the HashSet search time. </p>\n"
},
{
"answer_id": 2778296,
"author": "Eloff",
"author_id": 152580,
"author_profile": "https://Stackoverflow.com/users/152580",
"pm_score": 6,
"selected": false,
"text": "<p>You're looking at this wrong. Yes a linear search of a List will beat a HashSet for a small number of items. But the performance difference usually doesn't matter for collections that small. It's generally the large collections you have to worry about, and that's where you <a href=\"http://geekswithblogs.net/BlackRabbitCoder/archive/2011/06/16/c.net-fundamentals-choosing-the-right-collection-class.aspx\" rel=\"noreferrer\">think in terms of Big-O</a>. However, if you've measured a real bottleneck on HashSet performance, then you can try to create a hybrid List/HashSet, but you'll do that by conducting lots of empirical performance tests - not asking questions on SO.</p>\n"
},
{
"answer_id": 7867618,
"author": "Maestro",
"author_id": 435733,
"author_profile": "https://Stackoverflow.com/users/435733",
"pm_score": 3,
"selected": false,
"text": "<p>You can use a HybridDictionary which automaticly detects the breaking point, and accepts null-values, making it essentialy the same as a HashSet.</p>\n"
},
{
"answer_id": 10762995,
"author": "innominate227",
"author_id": 1418484,
"author_profile": "https://Stackoverflow.com/users/1418484",
"pm_score": 11,
"selected": true,
"text": "<p>A lot of people are saying that once you get to the size where speed is actually a concern that <code>HashSet<T></code> will always beat <code>List<T></code>, but that depends on what you are doing.</p>\n<p>Let's say you have a <code>List<T></code> that will only ever have on average 5 items in it. Over a large number of cycles, if a single item is added or removed each cycle, you may well be better off using a <code>List<T></code>.</p>\n<p>I did a test for this on my machine, and, well, it has to be very very small to get an advantage from <code>List<T></code>. For a list of short strings, the advantage went away after size 5, for objects after size 20.</p>\n<pre><code>1 item LIST strs time: 617ms\n1 item HASHSET strs time: 1332ms\n\n2 item LIST strs time: 781ms\n2 item HASHSET strs time: 1354ms\n\n3 item LIST strs time: 950ms\n3 item HASHSET strs time: 1405ms\n\n4 item LIST strs time: 1126ms\n4 item HASHSET strs time: 1441ms\n\n5 item LIST strs time: 1370ms\n5 item HASHSET strs time: 1452ms\n\n6 item LIST strs time: 1481ms\n6 item HASHSET strs time: 1418ms\n\n7 item LIST strs time: 1581ms\n7 item HASHSET strs time: 1464ms\n\n8 item LIST strs time: 1726ms\n8 item HASHSET strs time: 1398ms\n\n9 item LIST strs time: 1901ms\n9 item HASHSET strs time: 1433ms\n\n1 item LIST objs time: 614ms\n1 item HASHSET objs time: 1993ms\n\n4 item LIST objs time: 837ms\n4 item HASHSET objs time: 1914ms\n\n7 item LIST objs time: 1070ms\n7 item HASHSET objs time: 1900ms\n\n10 item LIST objs time: 1267ms\n10 item HASHSET objs time: 1904ms\n\n13 item LIST objs time: 1494ms\n13 item HASHSET objs time: 1893ms\n\n16 item LIST objs time: 1695ms\n16 item HASHSET objs time: 1879ms\n\n19 item LIST objs time: 1902ms\n19 item HASHSET objs time: 1950ms\n\n22 item LIST objs time: 2136ms\n22 item HASHSET objs time: 1893ms\n\n25 item LIST objs time: 2357ms\n25 item HASHSET objs time: 1826ms\n\n28 item LIST objs time: 2555ms\n28 item HASHSET objs time: 1865ms\n\n31 item LIST objs time: 2755ms\n31 item HASHSET objs time: 1963ms\n\n34 item LIST objs time: 3025ms\n34 item HASHSET objs time: 1874ms\n\n37 item LIST objs time: 3195ms\n37 item HASHSET objs time: 1958ms\n\n40 item LIST objs time: 3401ms\n40 item HASHSET objs time: 1855ms\n\n43 item LIST objs time: 3618ms\n43 item HASHSET objs time: 1869ms\n\n46 item LIST objs time: 3883ms\n46 item HASHSET objs time: 2046ms\n\n49 item LIST objs time: 4218ms\n49 item HASHSET objs time: 1873ms\n</code></pre>\n<p>Here is that data displayed as a graph:</p>\n<p><img src=\"https://i.stack.imgur.com/O4ly9.png\" alt=\"enter image description here\" /></p>\n<p>Here's the code:</p>\n<pre><code>static void Main(string[] args)\n{\n int times = 10000000;\n\n for (int listSize = 1; listSize < 10; listSize++)\n {\n List<string> list = new List<string>();\n HashSet<string> hashset = new HashSet<string>();\n\n for (int i = 0; i < listSize; i++)\n {\n list.Add("string" + i.ToString());\n hashset.Add("string" + i.ToString());\n }\n\n Stopwatch timer = new Stopwatch();\n timer.Start();\n for (int i = 0; i < times; i++)\n {\n list.Remove("string0");\n list.Add("string0");\n }\n timer.Stop();\n Console.WriteLine(listSize.ToString() + " item LIST strs time: " + timer.ElapsedMilliseconds.ToString() + "ms");\n\n timer = new Stopwatch();\n timer.Start();\n for (int i = 0; i < times; i++)\n {\n hashset.Remove("string0");\n hashset.Add("string0");\n }\n timer.Stop();\n Console.WriteLine(listSize.ToString() + " item HASHSET strs time: " + timer.ElapsedMilliseconds.ToString() + "ms");\n Console.WriteLine();\n }\n\n for (int listSize = 1; listSize < 50; listSize+=3)\n {\n List<object> list = new List<object>();\n HashSet<object> hashset = new HashSet<object>();\n\n for (int i = 0; i < listSize; i++)\n {\n list.Add(new object());\n hashset.Add(new object());\n }\n\n object objToAddRem = list[0];\n \n Stopwatch timer = new Stopwatch();\n timer.Start();\n for (int i = 0; i < times; i++)\n {\n list.Remove(objToAddRem);\n list.Add(objToAddRem);\n }\n timer.Stop();\n Console.WriteLine(listSize.ToString() + " item LIST objs time: " + timer.ElapsedMilliseconds.ToString() + "ms");\n\n timer = new Stopwatch();\n timer.Start();\n for (int i = 0; i < times; i++)\n {\n hashset.Remove(objToAddRem);\n hashset.Add(objToAddRem);\n }\n timer.Stop();\n Console.WriteLine(listSize.ToString() + " item HASHSET objs time: " + timer.ElapsedMilliseconds.ToString() + "ms");\n Console.WriteLine();\n }\n\n Console.ReadLine();\n}\n</code></pre>\n"
},
{
"answer_id": 13089134,
"author": "drzaus",
"author_id": 1037948,
"author_profile": "https://Stackoverflow.com/users/1037948",
"pm_score": 5,
"selected": false,
"text": "<p>Just thought I'd chime in with some benchmarks for different scenarios to illustrate the previous answers:</p>\n\n<ol>\n<li>A few (12 - 20) small strings (length between 5 and 10 characters)</li>\n<li>Many (~10K) small strings</li>\n<li>A few long strings (length between 200 and 1000 characters)</li>\n<li>Many (~5K) long strings</li>\n<li>A few integers</li>\n<li>Many (~10K) integers</li>\n</ol>\n\n<p>And for each scenario, looking up values which appear:</p>\n\n<ol>\n<li>In the beginning of the list (\"start\", index 0)</li>\n<li>Near the beginning of the list (\"early\", index 1)</li>\n<li>In the middle of the list (\"middle\", index count/2)</li>\n<li>Near the end of the list (\"late\", index count-2)</li>\n<li>At the end of the list (\"end\", index count-1)</li>\n</ol>\n\n<p>Before each scenario I generated randomly sized lists of random strings, and then fed each list to a hashset. Each scenario ran 10,000 times, essentially:</p>\n\n<p><em>(test pseudocode)</em></p>\n\n<pre><code>stopwatch.start\nfor X times\n exists = list.Contains(lookup);\nstopwatch.stop\n\nstopwatch.start\nfor X times\n exists = hashset.Contains(lookup);\nstopwatch.stop\n</code></pre>\n\n<h2>Sample Output</h2>\n\n<p><em>Tested on Windows 7, 12GB Ram, 64 bit, Xeon 2.8GHz</em></p>\n\n<pre><code>---------- Testing few small strings ------------\nSample items: (16 total)\nvgnwaloqf diwfpxbv tdcdc grfch icsjwk\n...\n\nBenchmarks:\n1: hashset: late -- 100.00 % -- [Elapsed: 0.0018398 sec]\n2: hashset: middle -- 104.19 % -- [Elapsed: 0.0019169 sec]\n3: hashset: end -- 108.21 % -- [Elapsed: 0.0019908 sec]\n4: list: early -- 144.62 % -- [Elapsed: 0.0026607 sec]\n5: hashset: start -- 174.32 % -- [Elapsed: 0.0032071 sec]\n6: list: middle -- 187.72 % -- [Elapsed: 0.0034536 sec]\n7: list: late -- 192.66 % -- [Elapsed: 0.0035446 sec]\n8: list: end -- 215.42 % -- [Elapsed: 0.0039633 sec]\n9: hashset: early -- 217.95 % -- [Elapsed: 0.0040098 sec]\n10: list: start -- 576.55 % -- [Elapsed: 0.0106073 sec]\n\n\n---------- Testing many small strings ------------\nSample items: (10346 total)\ndmnowa yshtrxorj vthjk okrxegip vwpoltck\n...\n\nBenchmarks:\n1: hashset: end -- 100.00 % -- [Elapsed: 0.0017443 sec]\n2: hashset: late -- 102.91 % -- [Elapsed: 0.0017951 sec]\n3: hashset: middle -- 106.23 % -- [Elapsed: 0.0018529 sec]\n4: list: early -- 107.49 % -- [Elapsed: 0.0018749 sec]\n5: list: start -- 126.23 % -- [Elapsed: 0.0022018 sec]\n6: hashset: early -- 134.11 % -- [Elapsed: 0.0023393 sec]\n7: hashset: start -- 372.09 % -- [Elapsed: 0.0064903 sec]\n8: list: middle -- 48,593.79 % -- [Elapsed: 0.8476214 sec]\n9: list: end -- 99,020.73 % -- [Elapsed: 1.7272186 sec]\n10: list: late -- 99,089.36 % -- [Elapsed: 1.7284155 sec]\n\n\n---------- Testing few long strings ------------\nSample items: (19 total)\nhidfymjyjtffcjmlcaoivbylakmqgoiowbgxpyhnrreodxyleehkhsofjqenyrrtlphbcnvdrbqdvji...\n...\n\nBenchmarks:\n1: list: early -- 100.00 % -- [Elapsed: 0.0018266 sec]\n2: list: start -- 115.76 % -- [Elapsed: 0.0021144 sec]\n3: list: middle -- 143.44 % -- [Elapsed: 0.0026201 sec]\n4: list: late -- 190.05 % -- [Elapsed: 0.0034715 sec]\n5: list: end -- 193.78 % -- [Elapsed: 0.0035395 sec]\n6: hashset: early -- 215.00 % -- [Elapsed: 0.0039271 sec]\n7: hashset: end -- 248.47 % -- [Elapsed: 0.0045386 sec]\n8: hashset: start -- 298.04 % -- [Elapsed: 0.005444 sec]\n9: hashset: middle -- 325.63 % -- [Elapsed: 0.005948 sec]\n10: hashset: late -- 431.62 % -- [Elapsed: 0.0078839 sec]\n\n\n---------- Testing many long strings ------------\nSample items: (5000 total)\nyrpjccgxjbketcpmnvyqvghhlnjblhgimybdygumtijtrwaromwrajlsjhxoselbucqualmhbmwnvnpnm\n...\n\nBenchmarks:\n1: list: early -- 100.00 % -- [Elapsed: 0.0016211 sec]\n2: list: start -- 132.73 % -- [Elapsed: 0.0021517 sec]\n3: hashset: start -- 231.26 % -- [Elapsed: 0.003749 sec]\n4: hashset: end -- 368.74 % -- [Elapsed: 0.0059776 sec]\n5: hashset: middle -- 385.50 % -- [Elapsed: 0.0062493 sec]\n6: hashset: late -- 406.23 % -- [Elapsed: 0.0065854 sec]\n7: hashset: early -- 421.34 % -- [Elapsed: 0.0068304 sec]\n8: list: middle -- 18,619.12 % -- [Elapsed: 0.3018345 sec]\n9: list: end -- 40,942.82 % -- [Elapsed: 0.663724 sec]\n10: list: late -- 41,188.19 % -- [Elapsed: 0.6677017 sec]\n\n\n---------- Testing few ints ------------\nSample items: (16 total)\n7266092 60668895 159021363 216428460 28007724\n...\n\nBenchmarks:\n1: hashset: early -- 100.00 % -- [Elapsed: 0.0016211 sec]\n2: hashset: end -- 100.45 % -- [Elapsed: 0.0016284 sec]\n3: list: early -- 101.83 % -- [Elapsed: 0.0016507 sec]\n4: hashset: late -- 108.95 % -- [Elapsed: 0.0017662 sec]\n5: hashset: middle -- 112.29 % -- [Elapsed: 0.0018204 sec]\n6: hashset: start -- 120.33 % -- [Elapsed: 0.0019506 sec]\n7: list: late -- 134.45 % -- [Elapsed: 0.0021795 sec]\n8: list: start -- 136.43 % -- [Elapsed: 0.0022117 sec]\n9: list: end -- 169.77 % -- [Elapsed: 0.0027522 sec]\n10: list: middle -- 237.94 % -- [Elapsed: 0.0038573 sec]\n\n\n---------- Testing many ints ------------\nSample items: (10357 total)\n370826556 569127161 101235820 792075135 270823009\n...\n\nBenchmarks:\n1: list: early -- 100.00 % -- [Elapsed: 0.0015132 sec]\n2: hashset: end -- 101.79 % -- [Elapsed: 0.0015403 sec]\n3: hashset: early -- 102.08 % -- [Elapsed: 0.0015446 sec]\n4: hashset: middle -- 103.21 % -- [Elapsed: 0.0015618 sec]\n5: hashset: late -- 104.26 % -- [Elapsed: 0.0015776 sec]\n6: list: start -- 126.78 % -- [Elapsed: 0.0019184 sec]\n7: hashset: start -- 130.91 % -- [Elapsed: 0.0019809 sec]\n8: list: middle -- 16,497.89 % -- [Elapsed: 0.2496461 sec]\n9: list: end -- 32,715.52 % -- [Elapsed: 0.4950512 sec]\n10: list: late -- 33,698.87 % -- [Elapsed: 0.5099313 sec]\n</code></pre>\n"
},
{
"answer_id": 23949528,
"author": "nawfal",
"author_id": 661933,
"author_profile": "https://Stackoverflow.com/users/661933",
"pm_score": 7,
"selected": false,
"text": "<p>It's essentially pointless to compare two structures for <em>performance</em> that behave differently. Use the structure that conveys the intent. Even if you say your <code>List<T></code> wouldn't have duplicates and iteration order doesn't matter making it comparable to a <code>HashSet<T></code>, its still a poor choice to use <code>List<T></code> because its relatively less fault tolerant. </p>\n\n<p>That said, I will inspect <em>some other aspects</em> of performance, </p>\n\n<pre><code>+------------+--------+-------------+-----------+----------+----------+-----------+\n| Collection | Random | Containment | Insertion | Addition | Removal | Memory |\n| | access | | | | | |\n+------------+--------+-------------+-----------+----------+----------+-----------+\n| List<T> | O(1) | O(n) | O(n) | O(1)* | O(n) | Lesser |\n| HashSet<T> | O(n) | O(1) | n/a | O(1) | O(1) | Greater** |\n+------------+--------+-------------+-----------+----------+----------+-----------+\n</code></pre>\n\n<ul>\n<li><p>Even though addition is O(1) in both cases, it will be relatively slower in HashSet since it involves cost of precomputing hash code before storing it.</p></li>\n<li><p>The superior scalability of HashSet has a memory cost. Every entry is stored as a new object along with its hash code. <a href=\"http://codebetter.com/patricksmacchia/2008/10/29/collections-and-performances/\" rel=\"noreferrer\">This article</a> might give you an idea.</p></li>\n</ul>\n"
}
]
| 2008/09/29 | [
"https://Stackoverflow.com/questions/150750",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/23372/"
]
| It's clear that a search performance of the generic `HashSet<T>` class is higher than of the generic `List<T>` class. Just compare the hash-based key with the linear approach in the `List<T>` class.
However calculating a hash key may itself take some CPU cycles, so for a small amount of items the linear search can be a real alternative to the `HashSet<T>`.
My question: where is the break-even?
To simplify the scenario (and to be fair) let's assume that the `List<T>` class uses the element's `Equals()` method to identify an item. | A lot of people are saying that once you get to the size where speed is actually a concern that `HashSet<T>` will always beat `List<T>`, but that depends on what you are doing.
Let's say you have a `List<T>` that will only ever have on average 5 items in it. Over a large number of cycles, if a single item is added or removed each cycle, you may well be better off using a `List<T>`.
I did a test for this on my machine, and, well, it has to be very very small to get an advantage from `List<T>`. For a list of short strings, the advantage went away after size 5, for objects after size 20.
```
1 item LIST strs time: 617ms
1 item HASHSET strs time: 1332ms
2 item LIST strs time: 781ms
2 item HASHSET strs time: 1354ms
3 item LIST strs time: 950ms
3 item HASHSET strs time: 1405ms
4 item LIST strs time: 1126ms
4 item HASHSET strs time: 1441ms
5 item LIST strs time: 1370ms
5 item HASHSET strs time: 1452ms
6 item LIST strs time: 1481ms
6 item HASHSET strs time: 1418ms
7 item LIST strs time: 1581ms
7 item HASHSET strs time: 1464ms
8 item LIST strs time: 1726ms
8 item HASHSET strs time: 1398ms
9 item LIST strs time: 1901ms
9 item HASHSET strs time: 1433ms
1 item LIST objs time: 614ms
1 item HASHSET objs time: 1993ms
4 item LIST objs time: 837ms
4 item HASHSET objs time: 1914ms
7 item LIST objs time: 1070ms
7 item HASHSET objs time: 1900ms
10 item LIST objs time: 1267ms
10 item HASHSET objs time: 1904ms
13 item LIST objs time: 1494ms
13 item HASHSET objs time: 1893ms
16 item LIST objs time: 1695ms
16 item HASHSET objs time: 1879ms
19 item LIST objs time: 1902ms
19 item HASHSET objs time: 1950ms
22 item LIST objs time: 2136ms
22 item HASHSET objs time: 1893ms
25 item LIST objs time: 2357ms
25 item HASHSET objs time: 1826ms
28 item LIST objs time: 2555ms
28 item HASHSET objs time: 1865ms
31 item LIST objs time: 2755ms
31 item HASHSET objs time: 1963ms
34 item LIST objs time: 3025ms
34 item HASHSET objs time: 1874ms
37 item LIST objs time: 3195ms
37 item HASHSET objs time: 1958ms
40 item LIST objs time: 3401ms
40 item HASHSET objs time: 1855ms
43 item LIST objs time: 3618ms
43 item HASHSET objs time: 1869ms
46 item LIST objs time: 3883ms
46 item HASHSET objs time: 2046ms
49 item LIST objs time: 4218ms
49 item HASHSET objs time: 1873ms
```
Here is that data displayed as a graph:

Here's the code:
```
static void Main(string[] args)
{
int times = 10000000;
for (int listSize = 1; listSize < 10; listSize++)
{
List<string> list = new List<string>();
HashSet<string> hashset = new HashSet<string>();
for (int i = 0; i < listSize; i++)
{
list.Add("string" + i.ToString());
hashset.Add("string" + i.ToString());
}
Stopwatch timer = new Stopwatch();
timer.Start();
for (int i = 0; i < times; i++)
{
list.Remove("string0");
list.Add("string0");
}
timer.Stop();
Console.WriteLine(listSize.ToString() + " item LIST strs time: " + timer.ElapsedMilliseconds.ToString() + "ms");
timer = new Stopwatch();
timer.Start();
for (int i = 0; i < times; i++)
{
hashset.Remove("string0");
hashset.Add("string0");
}
timer.Stop();
Console.WriteLine(listSize.ToString() + " item HASHSET strs time: " + timer.ElapsedMilliseconds.ToString() + "ms");
Console.WriteLine();
}
for (int listSize = 1; listSize < 50; listSize+=3)
{
List<object> list = new List<object>();
HashSet<object> hashset = new HashSet<object>();
for (int i = 0; i < listSize; i++)
{
list.Add(new object());
hashset.Add(new object());
}
object objToAddRem = list[0];
Stopwatch timer = new Stopwatch();
timer.Start();
for (int i = 0; i < times; i++)
{
list.Remove(objToAddRem);
list.Add(objToAddRem);
}
timer.Stop();
Console.WriteLine(listSize.ToString() + " item LIST objs time: " + timer.ElapsedMilliseconds.ToString() + "ms");
timer = new Stopwatch();
timer.Start();
for (int i = 0; i < times; i++)
{
hashset.Remove(objToAddRem);
hashset.Add(objToAddRem);
}
timer.Stop();
Console.WriteLine(listSize.ToString() + " item HASHSET objs time: " + timer.ElapsedMilliseconds.ToString() + "ms");
Console.WriteLine();
}
Console.ReadLine();
}
``` |
150,760 | <p>Let me first say that being able to take 17 million records from a flat file, pushing to a DB on a remote box and having it take 7 minutes is amazing. SSIS truly is fantastic. But now that I have that data up there, how do I remove duplicates?</p>
<p>Better yet, I want to take the flat file, remove the duplicates from the flat file and put them back into another flat file.</p>
<p>I am thinking about a:</p>
<p><strong><code>Data Flow Task</code></strong></p>
<ul>
<li>File source (with an associated file connection)</li>
<li>A for loop container</li>
<li>A script container that contains some logic to tell if another row exists</li>
</ul>
<p>Thak you, and everyone on this site is incredibly knowledgeable.</p>
<p><strong><code>Update:</code></strong> <a href="http://rafael-salas.blogspot.com/2007/04/remove-duplicates-using-t-sql-rank.html" rel="noreferrer">I have found this link, might help in answering this question</a></p>
| [
{
"answer_id": 150872,
"author": "Timothy Lee Russell",
"author_id": 12919,
"author_profile": "https://Stackoverflow.com/users/12919",
"pm_score": 3,
"selected": false,
"text": "<p>I would suggest using SSIS to copy the records to a temporary table, then create a task that uses Select Distinct or Rank depending on your situation to select the duplicates which would funnel them to a flat file and delete them from the temporary table. The last step would be to copy the records from the temporary table into the destination table.</p>\n\n<p>Determining a duplicate is something SQL is good at but a flat file is not as well suited for. In the case you proposed, the script container would load a row and then would have to compare it against 17 million records, then load the next row and repeat...The performance might not be all that great.</p>\n"
},
{
"answer_id": 150951,
"author": "Hector Sosa Jr",
"author_id": 12829,
"author_profile": "https://Stackoverflow.com/users/12829",
"pm_score": 2,
"selected": false,
"text": "<p>The strategy will usually depend on how many columns the staging table has. The more columns, the more complex the solution. The article you linked has some very good advice.</p>\n\n<p>The only thing that I will add to what everybody else has said so far, is that columns with date and datetime values will give some of the solutions presented here fits.</p>\n\n<p>One solution that I came up with is this:</p>\n\n<pre><code>SET NOCOUNT ON\n\nDECLARE @email varchar(100)\n\nSET @email = ''\n\nSET @emailid = (SELECT min(email) from StagingTable WITH (NOLOCK) WHERE email > @email)\n\nWHILE @emailid IS NOT NULL\nBEGIN\n\n -- Do INSERT statement based on the email\n INSERT StagingTable2 (Email)\n FROM StagingTable WITH (NOLOCK) \n WHERE email = @email\n\n SET @emailid = (SELECT min(email) from StagingTable WITH (NOLOCK) WHERE email > @email)\n\nEND\n</code></pre>\n\n<p>This is a LOT faster when doing deduping, than a CURSOR and will not peg the server's CPU. To use this, separate each column that comes from the text file into their own variables. Use a separate SELECT statement before and inside the loop, then include them in the INSERT statement. This has worked really well for me.</p>\n"
},
{
"answer_id": 152833,
"author": "AJ.",
"author_id": 7211,
"author_profile": "https://Stackoverflow.com/users/7211",
"pm_score": 2,
"selected": false,
"text": "<p>To do this on the flat file, I use the unix command line tool, sort: </p>\n\n<pre><code>sort -u inputfile > outputfile\n</code></pre>\n\n<p>Unfortunately, the windows sort command does not have a unique option, but you could try downloading a sort utility from one of these: </p>\n\n<ul>\n<li><a href=\"http://unxutils.sourceforge.net/\" rel=\"nofollow noreferrer\">http://unxutils.sourceforge.net/</a> </li>\n<li><a href=\"http://www.highend3d.com/downloads/tools/os_utils/76.html\" rel=\"nofollow noreferrer\">http://www.highend3d.com/downloads/tools/os_utils/76.html</a>. </li>\n</ul>\n\n<p>(I haven't tried them, so no guarantees, I'm afraid). </p>\n\n<p>On the other hand, to do this as the records are loaded into the database, you could create a unique index on the key the database table whith ignore_dup_key. This will make the records unique very efficiently at load time. </p>\n\n<pre><code>CREATE UNIQUE INDEX idx1 ON TABLE (col1, col2, ...) WITH IGNORE_DUP_KEY\n</code></pre>\n"
},
{
"answer_id": 347284,
"author": "Christian Loris",
"author_id": 2574178,
"author_profile": "https://Stackoverflow.com/users/2574178",
"pm_score": 2,
"selected": false,
"text": "<p>A bit of a dirty solution is to set your target table up with a composite key that spans all columns. This will guarantee distint uniqueness. Then on the Data Destination shape, configure the task to ignore errors. All duplicate inserts will fall off into oblivion.</p>\n"
},
{
"answer_id": 618952,
"author": "Craig Warren",
"author_id": 74706,
"author_profile": "https://Stackoverflow.com/users/74706",
"pm_score": 5,
"selected": false,
"text": "<p>Use the Sort Component.</p>\n\n<p>Simply choose which fields you wish to sort your loaded rows by and in the bottom left corner you'll see a check box to remove duplicates. This box removes any rows which are duplicates based on the sort criteria only\nso in the example below the rows would be considered duplicate if we only sorted on the first field:</p>\n\n<pre><code>1 | sample A |\n1 | sample B |\n</code></pre>\n"
},
{
"answer_id": 978397,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 3,
"selected": false,
"text": "<p>Flat File Source --> Aggregate (Group By Columns you want unique) --> Flat File Destination</p>\n"
},
{
"answer_id": 1539283,
"author": "Registered User",
"author_id": 38332,
"author_profile": "https://Stackoverflow.com/users/38332",
"pm_score": 1,
"selected": false,
"text": "<p>I would recommend loading a staging table on the destination server and then merge the results into a target table on the destination server. If you need to run any hygiene rules, then you could do this via stored procedure since you are bound to get better performance than through SSIS data flow transformation tasks. Besides, deduping is generally a multi-step process. You may want to dedupe on:</p>\n\n<ol>\n<li>Distinct lines.</li>\n<li>Distinct groups of columns like First Name, Last Name, Email Address, etc.</li>\n<li>You may want to dedupe against an existing target table. If that's the case, then you may need to include NOT EXISTS or NOT IN statements. Or you may want to update the original row with new values. This usually is best served with a MERGE statement and a subquery for the source.</li>\n<li>Take the first or last row of a particular pattern. For instance, you may want the last row entered in the file for each occurrence of an email address or phone number. I usually rely on CTE's with ROW_NUMBER() to generate sequential order and reverse order columns like in the folling sample:</li>\n</ol>\n\n<p>.</p>\n\n<pre><code>WITH \n sample_records \n ( email_address\n , entry_date\n , row_identifier\n )\n AS\n (\n SELECT '[email protected]'\n , '2009-10-08 10:00:00'\n , 1\n UNION ALL\n\n SELECT '[email protected]'\n , '2009-10-08 10:00:01'\n , 2\n\n UNION ALL\n\n SELECT '[email protected]'\n , '2009-10-08 10:00:02'\n , 3\n\n UNION ALL\n\n SELECT '[email protected]'\n , '2009-10-08 10:00:00'\n , 4\n\n UNION ALL\n\n SELECT '[email protected]'\n , '2009-10-08 10:00:00'\n , 5\n )\n, filter_records \n ( email_address\n , entry_date\n , row_identifier\n , sequential_order\n , reverse_order\n )\n AS\n (\n SELECT email_address\n , entry_date\n , row_identifier\n , 'sequential_order' = ROW_NUMBER() OVER (\n PARTITION BY email_address \n ORDER BY row_identifier ASC)\n , 'reverse_order' = ROW_NUMBER() OVER (\n PARTITION BY email_address\n ORDER BY row_identifier DESC)\n FROM sample_records\n )\n SELECT email_address\n , entry_date\n , row_identifier\n FROM filter_records\n WHERE reverse_order = 1\n ORDER BY email_address;\n</code></pre>\n\n<p>There are lots of options for you on deduping files, but ultimately I recommend handling this in a stored procedure once you have loaded a staging table on the destination server. After you cleanse the data, then you can either MERGE or INSERT into your final destination.</p>\n"
},
{
"answer_id": 3362556,
"author": "SQLBobScot",
"author_id": 77198,
"author_profile": "https://Stackoverflow.com/users/77198",
"pm_score": 1,
"selected": false,
"text": "<p>Found this page <a href=\"http://www.sqllion.com/2010/01/ssis-package-to-remove-duplicates-from-any-database/\" rel=\"nofollow noreferrer\">link text</a> might be worth looking at, although with 17 million records might take a bit too long</p>\n"
},
{
"answer_id": 7724087,
"author": "Mohit",
"author_id": 989222,
"author_profile": "https://Stackoverflow.com/users/989222",
"pm_score": 2,
"selected": false,
"text": "<p>We can use look up tables for this. Like SSIS provides two DFS (Data Flow Transformations) i.e. Fuzzy Grouping and Fuzzy Lookup.</p>\n"
}
]
| 2008/09/29 | [
"https://Stackoverflow.com/questions/150760",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7952/"
]
| Let me first say that being able to take 17 million records from a flat file, pushing to a DB on a remote box and having it take 7 minutes is amazing. SSIS truly is fantastic. But now that I have that data up there, how do I remove duplicates?
Better yet, I want to take the flat file, remove the duplicates from the flat file and put them back into another flat file.
I am thinking about a:
**`Data Flow Task`**
* File source (with an associated file connection)
* A for loop container
* A script container that contains some logic to tell if another row exists
Thak you, and everyone on this site is incredibly knowledgeable.
**`Update:`** [I have found this link, might help in answering this question](http://rafael-salas.blogspot.com/2007/04/remove-duplicates-using-t-sql-rank.html) | Use the Sort Component.
Simply choose which fields you wish to sort your loaded rows by and in the bottom left corner you'll see a check box to remove duplicates. This box removes any rows which are duplicates based on the sort criteria only
so in the example below the rows would be considered duplicate if we only sorted on the first field:
```
1 | sample A |
1 | sample B |
``` |
150,762 | <p>I have a file that lists filenames, each on it's own line, and I want to test if each exists in a particular directory. For example, some sample lines of the file might be</p>
<pre><code>mshta.dll
foobar.dll
somethingelse.dll
</code></pre>
<p>The directory I'm interested in is <code>X:\Windows\System32\</code>, so I want to see if the following files exist:</p>
<pre><code>X:\Windows\System32\mshta.dll
X:\Windows\System32\foobar.dll
X:\Windows\System32\somethingelse.dll
</code></pre>
<p>How can I do this using the Windows command prompt? Also (out of curiosity) how would I do this using bash or another Unix shell?</p>
| [
{
"answer_id": 150807,
"author": "Adam Rosenfield",
"author_id": 9530,
"author_profile": "https://Stackoverflow.com/users/9530",
"pm_score": 1,
"selected": false,
"text": "<p>In Windows:</p>\n\n<pre><code>\ntype file.txt >NUL 2>NUL\nif ERRORLEVEL 1 then echo \"file doesn't exist\"\n</code></pre>\n\n<p>(This may not be the best way to do it; it is a way I know of; see also <a href=\"http://blogs.msdn.com/oldnewthing/archive/2008/09/26/8965755.aspx\" rel=\"nofollow noreferrer\"><a href=\"http://blogs.msdn.com/oldnewthing/archive/2008/09/26/8965755.aspx\" rel=\"nofollow noreferrer\">http://blogs.msdn.com/oldnewthing/archive/2008/09/26/8965755.aspx</a></a>)</p>\n\n<p>In Bash:</p>\n\n<pre><code>\nif ( test -e file.txt ); then echo \"file exists\"; fi\n</code></pre>\n"
},
{
"answer_id": 150829,
"author": "JesperE",
"author_id": 13051,
"author_profile": "https://Stackoverflow.com/users/13051",
"pm_score": 3,
"selected": false,
"text": "<p>Bash:</p>\n\n<pre><code>while read f; do \n [ -f \"$f\" ] && echo \"$f\" exists\ndone < file.txt\n</code></pre>\n"
},
{
"answer_id": 150835,
"author": "Mihai Limbășan",
"author_id": 14444,
"author_profile": "https://Stackoverflow.com/users/14444",
"pm_score": 1,
"selected": false,
"text": "<p>Please note, however, that using the default file systems under both Win32 and *nix there is no way to guarantee the atomicity of the operation, i.e. if you check for the existence of files A, B, and C, some other process or thread might have deleted file A after you passed it and while you were looking for B and C.</p>\n\n<p>File systems such as <a href=\"http://en.wikipedia.org/w/index.php?title=Transactional_NTFS&oldid=233375400\" rel=\"nofollow noreferrer\">Transactional NTFS</a> can overcome this limitation.</p>\n"
},
{
"answer_id": 150836,
"author": "tzot",
"author_id": 6899,
"author_profile": "https://Stackoverflow.com/users/6899",
"pm_score": 4,
"selected": true,
"text": "<p>In cmd.exe, the <strong>FOR /F %</strong><em>variable</em> <strong>IN (</strong> <em>filename</em> <b>) DO</b> <em>command</em> should give you what you want. This reads the contents of <em>filename</em> (and they could be more than one filenames) one line at a time, placing the line in %variable (more or less; do a HELP FOR in a command prompt). If no one else supplies a command script, I will attempt.</p>\n\n<p>EDIT: my attempt for a cmd.exe script that does the requested:</p>\n\n<pre><code>@echo off\nrem first arg is the file containing filenames\nrem second arg is the target directory\n\nFOR /F %%f IN (%1) DO IF EXIST %2\\%%f ECHO %%f exists in %2\n</code></pre>\n\n<p>Note, the script above <em>must</em> be a script; a FOR loop in a .cmd or .bat file, for some strange reason, must have double percent-signs before its variable.</p>\n\n<p>Now, for a script that works with bash|ash|dash|sh|ksh :</p>\n\n<pre><code>filename=\"${1:-please specify filename containing filenames}\"\ndirectory=\"${2:-please specify directory to check}\nfor fn in `cat \"$filename\"`\ndo\n [ -f \"$directory\"/\"$fn\" ] && echo \"$fn\" exists in \"$directory\"\ndone\n</code></pre>\n"
},
{
"answer_id": 151065,
"author": "JaredPar",
"author_id": 23283,
"author_profile": "https://Stackoverflow.com/users/23283",
"pm_score": 1,
"selected": false,
"text": "<p>I wanted to add one small comment to most of the above solutions. They are not actually testing if a particular file exists or not. They are checking to see if the file exists and you have access to it. It's entirely possible for a file to exist in a directory you do not have permission to in which case you won't be able to view the file even though it exists. </p>\n"
},
{
"answer_id": 154093,
"author": "Zorantula",
"author_id": 18108,
"author_profile": "https://Stackoverflow.com/users/18108",
"pm_score": 2,
"selected": false,
"text": "<pre><code>for /f %i in (files.txt) do @if exist \"%i\" (@echo Present: %i) else (@echo Missing: %i)\n</code></pre>\n"
}
]
| 2008/09/29 | [
"https://Stackoverflow.com/questions/150762",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5616/"
]
| I have a file that lists filenames, each on it's own line, and I want to test if each exists in a particular directory. For example, some sample lines of the file might be
```
mshta.dll
foobar.dll
somethingelse.dll
```
The directory I'm interested in is `X:\Windows\System32\`, so I want to see if the following files exist:
```
X:\Windows\System32\mshta.dll
X:\Windows\System32\foobar.dll
X:\Windows\System32\somethingelse.dll
```
How can I do this using the Windows command prompt? Also (out of curiosity) how would I do this using bash or another Unix shell? | In cmd.exe, the **FOR /F %***variable* **IN (** *filename* **) DO** *command* should give you what you want. This reads the contents of *filename* (and they could be more than one filenames) one line at a time, placing the line in %variable (more or less; do a HELP FOR in a command prompt). If no one else supplies a command script, I will attempt.
EDIT: my attempt for a cmd.exe script that does the requested:
```
@echo off
rem first arg is the file containing filenames
rem second arg is the target directory
FOR /F %%f IN (%1) DO IF EXIST %2\%%f ECHO %%f exists in %2
```
Note, the script above *must* be a script; a FOR loop in a .cmd or .bat file, for some strange reason, must have double percent-signs before its variable.
Now, for a script that works with bash|ash|dash|sh|ksh :
```
filename="${1:-please specify filename containing filenames}"
directory="${2:-please specify directory to check}
for fn in `cat "$filename"`
do
[ -f "$directory"/"$fn" ] && echo "$fn" exists in "$directory"
done
``` |
150,814 | <p>This is somewhat of a follow-up to an answer <a href="https://stackoverflow.com/questions/26536/active-x-control-javascript">here</a>.</p>
<p>I have a custom ActiveX control that is raising an event ("ReceiveMessage" with a "msg" parameter) that needs to be handled by Javascript in the web browser. Historically we've been able to use the following IE-only syntax to accomplish this on different projects:</p>
<pre><code>function MyControl::ReceiveMessage(msg)
{
alert(msg);
}
</code></pre>
<p>However, when inside a layout in which the control is buried, the Javascript cannot find the control. Specifically, if we put this into a plain HTML page it works fine, but if we put it into an ASPX page wrapped by the <code><Form></code> tag, we get a "MyControl is undefined" error. We've tried variations on the following:</p>
<pre><code>var GetControl = document.getElementById("MyControl");
function GetControl::ReceiveMessage(msg)
{
alert(msg);
}
</code></pre>
<p>... but it results in the Javascript error "GetControl is undefined."</p>
<p>What is the proper way to handle an event being sent from an ActiveX control? Right now we're only interested in getting this working in IE. This has to be a custom ActiveX control for what we're doing.</p>
<p>Thanks.</p>
| [
{
"answer_id": 152724,
"author": "Raelshark",
"author_id": 19678,
"author_profile": "https://Stackoverflow.com/users/19678",
"pm_score": 5,
"selected": true,
"text": "<p>I was able to get this working using the following script block format, but I'm still curious if this is the best way:</p>\n\n<pre><code><script for=\"MyControl\" event=\"ReceiveMessage(msg)\">\n alert(msg);\n</script>\n</code></pre>\n"
},
{
"answer_id": 176834,
"author": "J5.",
"author_id": 25380,
"author_profile": "https://Stackoverflow.com/users/25380",
"pm_score": 0,
"selected": false,
"text": "<p>I think that the MyControl::ReceiveMessage example does not work because the ActiveX control is being exposed with a different name or in a different scope.</p>\n\n<p>With the example GetControl::ReceiveMessage, I believe that the function definition is being parsed before the GetControl reference is being set, thus it does not refer to a valid object and cannot bind the function to the object.</p>\n\n<p>I would attack this problem by using the MS script debugger and trying to determine if a default reference for the control exists with a different name or in a different scope (possibly as a child of the form). If you can determine the correct reference for the control, you should be able to bind the function properly with the Automagic :: method that the MSDN article specifies.</p>\n\n<p>One more thought, the reference may be based on the name of the object and not the ID, so try setting both :)</p>\n"
},
{
"answer_id": 283053,
"author": "Adam",
"author_id": 1341,
"author_profile": "https://Stackoverflow.com/users/1341",
"pm_score": 1,
"selected": false,
"text": "<p>If you have an ActiveX element on your page that has an id of 'MyControl' then your javascript handler syntax is this:</p>\n\n<pre><code>function MyControl::ReceiveMessage(msg)\n{\n alert(msg);\n}\n</code></pre>\n"
},
{
"answer_id": 379872,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 3,
"selected": false,
"text": "<p>OK, but if you are using C# (.NET 2.0) with inherited UserControl (ActiveX)...\nThe only way to make it work is by \"Extending\" the event's handler functionality:\n<a href=\"http://www.codeproject.com/KB/dotnet/extend_events.aspx?display=Print\" rel=\"nofollow noreferrer\">http://www.codeproject.com/KB/dotnet/extend_events.aspx?display=Print</a></p>\n\n<p>The above project link from our friend Mr. Werner Willemsens has saved my project.\nIf you don't do that the javascript can't bind to the event handler.</p>\n\n<p>He used the \"extension\" in a complex way due to the example he chose but if you make it simple, attaching the handle directly to the event itself, it also works.\nThe C# ActiveX should support \"ScriptCallbackObject\" to bind the event to a javascript function like below:</p>\n\n<pre><code> var clock = new ActiveXObject(\"Clocks.clock\");\n var extendedClockEvents = clock.ExtendedClockEvents();\n // Here you assign (subscribe to) your callback method!\n extendedClockEvents.ScriptCallbackObject = clock_Callback; \n ...\n function clock_Callback(time)\n {\n document.getElementById(\"text_tag\").innerHTML = time;\n }\n</code></pre>\n\n<p>Of course you have to implement IObjectSafety and the other security stuff to make it work better.</p>\n"
},
{
"answer_id": 427024,
"author": "Frank Schwieterman",
"author_id": 32203,
"author_profile": "https://Stackoverflow.com/users/32203",
"pm_score": 1,
"selected": false,
"text": "<p>I found this code works within a form tag. In this example, callback is a function parameter passed in by javascript to the ActiveX control, and callbackparam is a parameter of the callback event generated within the activeX control. This way I use the same event handler for whatever types of events, rather than try to declare a bunch of separate event handlers.</p>\n\n<blockquote>\n <blockquote>\n <p><code><object id=\"ActivexObject\" name=\"ActivexObject\" classid=\"clsid:15C5A3F3-F8F7-4d5e-B87E-5084CC98A25A\"></object></code> </p>\n \n <p><code><script></code><br>\n <code>function document.ActivexObject::OnCallback(callback, callbackparam){</code><br>\n <code>callback(callbackparam);</code><br>\n <code>}</code><br>\n <code></script></code> </p>\n </blockquote>\n</blockquote>\n"
},
{
"answer_id": 3203444,
"author": "Zuhaib",
"author_id": 25138,
"author_profile": "https://Stackoverflow.com/users/25138",
"pm_score": 3,
"selected": false,
"text": "<p>I have used activex in my applications before. i place the object tags in the ASP.NET form and the following JavaScript works for me.</p>\n\n<pre><code>function onEventHandler(arg1, arg2){\n // do something\n}\n\nwindow.onload = function(){\n var yourActiveXObject = document.getElementById('YourObjectTagID');\n if(typeof(yourActiveXObject) === 'undefined' || yourActiveXObject === null){\n alert('Unable to load ActiveX');\n return;\n }\n\n // attach events\n var status = yourActiveXObject.attachEvent('EventName', onEventHandler);\n}\n</code></pre>\n"
},
{
"answer_id": 10557222,
"author": "Taudris",
"author_id": 108064,
"author_profile": "https://Stackoverflow.com/users/108064",
"pm_score": 1,
"selected": false,
"text": "<p>In my case, I needed a way to dynamically create ActiveX controls and listen to their events. I was able to get something like this to work:</p>\n\n<pre><code>//create the ActiveX\nvar ax = $(\"<object></object>\", {\n classid: \"clsid:\" + clsid,\n codebase: install ? cabfile : undefined,\n width: 0,\n height: 0,\n id: '__ax_'+idIncrement++\n})\n.appendTo('#someHost');\n</code></pre>\n\n<p>And then to register a handler for an event:</p>\n\n<pre><code>//this function registers an event listener for an ActiveX object (obviously for IE only)\n//the this argument for the handler is the ActiveX object.\nfunction registerAXEvent(control, name, handler) {\n control = jQuery(control);\n\n //can't use closures through the string due to the parameter renaming done by the JavaScript compressor\n //can't use jQuery.data() on ActiveX objects because it uses expando properties\n\n var id = control[0].id;\n\n var axe = registerAXEvent.axevents = registerAXEvent.axevents || {};\n axe[id] = axe[id] || {};\n axe[id][name] = handler;\n\n var script =\n \"(function(){\"+\n \"var f=registerAXEvent.axevents['\" + id + \"']['\" + name + \"'],e=jQuery('#\" + id + \"');\"+\n \"function document.\" + id + \"::\" + name + \"(){\"+\n \"f.apply(e,arguments);\"+\n \"}\"+\n \"})();\";\n eval(script);\n}\n</code></pre>\n\n<p>This code allows you to use closures and minimizes the scope of the eval().</p>\n\n<p>The ActiveX control's <code><object></code> element must already be added to the document; otherwise, IE will not find the element and you'll just get script errors.</p>\n"
}
]
| 2008/09/29 | [
"https://Stackoverflow.com/questions/150814",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/19678/"
]
| This is somewhat of a follow-up to an answer [here](https://stackoverflow.com/questions/26536/active-x-control-javascript).
I have a custom ActiveX control that is raising an event ("ReceiveMessage" with a "msg" parameter) that needs to be handled by Javascript in the web browser. Historically we've been able to use the following IE-only syntax to accomplish this on different projects:
```
function MyControl::ReceiveMessage(msg)
{
alert(msg);
}
```
However, when inside a layout in which the control is buried, the Javascript cannot find the control. Specifically, if we put this into a plain HTML page it works fine, but if we put it into an ASPX page wrapped by the `<Form>` tag, we get a "MyControl is undefined" error. We've tried variations on the following:
```
var GetControl = document.getElementById("MyControl");
function GetControl::ReceiveMessage(msg)
{
alert(msg);
}
```
... but it results in the Javascript error "GetControl is undefined."
What is the proper way to handle an event being sent from an ActiveX control? Right now we're only interested in getting this working in IE. This has to be a custom ActiveX control for what we're doing.
Thanks. | I was able to get this working using the following script block format, but I'm still curious if this is the best way:
```
<script for="MyControl" event="ReceiveMessage(msg)">
alert(msg);
</script>
``` |
150,845 | <p>I'm having issues creating an ActionLink using Preview 5. All the docs I can find describe the older generic version.</p>
<p>I'm constructing links on a list of jobs on the page /jobs. Each job has a guid, and I'd like to construct a link to /jobs/details/{guid} so I can show details about the job. My jobs controller has an Index controller and a Details controller. The Details controller takes a guid. I've tried this</p>
<pre><code><%= Html.ActionLink(job.Name, "Details", job.JobId); %>
</code></pre>
<p>However, that gives me the url "/jobs/details". What am I missing here?</p>
<hr>
<p>Solved, with your help.</p>
<p>Route (added before the catch-all route):</p>
<pre><code>routes.Add(new Route("Jobs/Details/{id}", new MvcRouteHandler())
{
Defaults = new RouteValueDictionary(new
{
controller = "Jobs",
action = "Details",
id = new Guid()
}
});
</code></pre>
<p>Action link:</p>
<pre><code><%= Html.ActionLink(job.Name, "Details", new { id = job.JobId }) %>
</code></pre>
<p>Results in the html anchor:</p>
<blockquote>
<p><a href="http://localhost:3570/WebsiteAdministration/Details?id=2db8cee5-3c56-4861-aae9-a34546ee2113" rel="nofollow noreferrer">http://localhost:3570/WebsiteAdministration/Details?id=2db8cee5-3c56-4861-aae9-a34546ee2113</a></p>
</blockquote>
<p>So, its confusing routes. I moved my jobs route definition before the website admin and it works now. Obviously, my route definitions SUCK. I need to read more examples.</p>
<p>A side note, my links weren't showing, and quickwatches weren't working (can't quickwatch an expression with an anonymous type), which made it much harder to figure out what was going on here. It turned out the action links weren't showing because of a very minor typo:</p>
<pre><code><% Html.ActionLink(job.Name, "Details", new { id = job.JobId })%>
</code></pre>
<p>That's gonna get me again.</p>
| [
{
"answer_id": 150871,
"author": "Kevin Pang",
"author_id": 1574,
"author_profile": "https://Stackoverflow.com/users/1574",
"pm_score": 1,
"selected": false,
"text": "<p>Have you defined a route to handle this in your Global.asax.cs file? The default route is {controller}/{action}/{id}. You are passing \"JobID\", which the framework won't map to \"id\" automatically. You either need to change this to be job.id or define a route to handle this case explicitly.</p>\n"
},
{
"answer_id": 150875,
"author": "Jonathan Carter",
"author_id": 6412,
"author_profile": "https://Stackoverflow.com/users/6412",
"pm_score": 3,
"selected": true,
"text": "<p>Give this a shot:</p>\n\n<pre><code><%= Html.ActionLink(job.Name, \"Details\", new { guid = job.JobId}); %>\n</code></pre>\n\n<p>Where \"guid\" is the actual name of the parameter in your route. This instructs the routing engine that you want to place the value of the job.JobId property into the route definition's guid parameter.</p>\n"
}
]
| 2008/09/29 | [
"https://Stackoverflow.com/questions/150845",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
]
| I'm having issues creating an ActionLink using Preview 5. All the docs I can find describe the older generic version.
I'm constructing links on a list of jobs on the page /jobs. Each job has a guid, and I'd like to construct a link to /jobs/details/{guid} so I can show details about the job. My jobs controller has an Index controller and a Details controller. The Details controller takes a guid. I've tried this
```
<%= Html.ActionLink(job.Name, "Details", job.JobId); %>
```
However, that gives me the url "/jobs/details". What am I missing here?
---
Solved, with your help.
Route (added before the catch-all route):
```
routes.Add(new Route("Jobs/Details/{id}", new MvcRouteHandler())
{
Defaults = new RouteValueDictionary(new
{
controller = "Jobs",
action = "Details",
id = new Guid()
}
});
```
Action link:
```
<%= Html.ActionLink(job.Name, "Details", new { id = job.JobId }) %>
```
Results in the html anchor:
>
> <http://localhost:3570/WebsiteAdministration/Details?id=2db8cee5-3c56-4861-aae9-a34546ee2113>
>
>
>
So, its confusing routes. I moved my jobs route definition before the website admin and it works now. Obviously, my route definitions SUCK. I need to read more examples.
A side note, my links weren't showing, and quickwatches weren't working (can't quickwatch an expression with an anonymous type), which made it much harder to figure out what was going on here. It turned out the action links weren't showing because of a very minor typo:
```
<% Html.ActionLink(job.Name, "Details", new { id = job.JobId })%>
```
That's gonna get me again. | Give this a shot:
```
<%= Html.ActionLink(job.Name, "Details", new { guid = job.JobId}); %>
```
Where "guid" is the actual name of the parameter in your route. This instructs the routing engine that you want to place the value of the job.JobId property into the route definition's guid parameter. |
150,881 | <p>We are sending out Word documents via email (automated system, not by hand). The email is sent to the user, and CC'd to me.</p>
<p>We are getting reports that some users are having the attachments come through corrupted, though when we open the copy that is CC'd to me, it opens fine.</p>
<p>When the user forwards us the copy they received, then we cannot open it.</p>
<p>Below is a hex comparison of the two files. Can anyone identity what is going on here?</p>
<p><a href="https://i.stack.imgur.com/8sSqA.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/8sSqA.png" width="680" height="692"></a></p>
<p>Message headers are below</p>
<pre><code>Return-Path: <[email protected]>
Received: from animal.hosts.net.nz (root@localhost) by example.co.nz
(8.12.11/8.12.11) with ESMTP id m8T52Mw6021168; Mon, 29 Sep 2008 18:02:22
+1300
X-Clientaddr: 210.48.108.196
Received: from marjory.hosts.net.nz (marjory.hosts.net.nz
[210.48.108.196]) by animal.hosts.net.nz (8.12.11/8.12.11) with ESMTP id
m8T52EvU028021; Mon, 29 Sep 2008 18:02:19 +1300
Received: from example.example.co.nz ([210.48.67.48]) by
marjory.hosts.net.nz with esmtp (Exim 4.63) (envelope-from
<[email protected]>) id 1KkAtd-0004Ch-I9; Mon, 29 Sep 2008 18:02:09 +1300
Received: from localhost ([127.0.0.1]) by example.example.co.nz with esmtp
(Exim 4.63) (envelope-from <[email protected]>) id 1KkAtV-0001C3-4s;
Mon, 29 Sep 2008 18:02:01 +1300
From: "XXX" <[email protected]>
To: "Sue" <[email protected]>
Reply-To: [email protected]
Subject: XXX: new application received
Date: Mon, 29 Sep 2008 18:02:01 +1300
Content-Type: multipart/mixed;
charset="utf-8";
boundary="=_5549133ca51ec83196e2cfd28dad40f7"
Content-Transfer-Encoding: quoted-printable
Content-Disposition: inline
MIME-Version: 1.0
Message-ID: <[email protected]>
</code></pre>
<hr>
<p>I think I know what it is, but not why it is happening.</p>
<p>"X-Mimeole: Produced By Microsoft Exchange V6.5" the client is using Exchange. Now, compare these lines.</p>
<p>The original:</p>
<pre><code>Content-Type: multipart/mixed;
charset="utf-8";
boundary="=_5549133ca51ec83196e2cfd28dad40f7"
</code></pre>
<p>What they get:</p>
<pre><code>Content-Type: multipart/mixed;
boundary="----_=_NextPart_001_01C92270.6BBA3EE6"
</code></pre>
<p>The missing charset="UTF-8" likely means that the client will fall back to Windows-1252, which I think (can someone confirm?) result in corrupted attachments.</p>
<p>Now the question is, why would the char-set be stripped?</p>
| [
{
"answer_id": 150898,
"author": "Asaf R",
"author_id": 6827,
"author_profile": "https://Stackoverflow.com/users/6827",
"pm_score": 1,
"selected": false,
"text": "<p>If you use Windows I suggest using Visual Studio. There's a free Express Edition <a href=\"http://www.microsoft.com/express/vc/\" rel=\"nofollow noreferrer\">here</a>, but there is a downside - Visual C++ has a lot of \"added functionality\" for Win32 and .Net development. </p>\n\n<p>These added features might be confusing when trying to focus on C.</p>\n\n<p>I learned using <a href=\"http://en.wikipedia.org/wiki/Turbo_C\" rel=\"nofollow noreferrer\">Borland's Turbo C</a>. It was a while back, though.</p>\n"
},
{
"answer_id": 150907,
"author": "Rayne",
"author_id": 21734,
"author_profile": "https://Stackoverflow.com/users/21734",
"pm_score": 3,
"selected": true,
"text": "<p>I have always been fond of <a href=\"http://www.codeblocks.org\" rel=\"nofollow noreferrer\">Code::Blocks</a> It's a wonderful C/C++ IDE, with several helpful addons. As for a compiler I've always used MingW but I hear <a href=\"http://www.digitalmars.com\" rel=\"nofollow noreferrer\">DigitalMars C/C++</a> compiler is good.</p>\n"
},
{
"answer_id": 150910,
"author": "Dark Shikari",
"author_id": 11206,
"author_profile": "https://Stackoverflow.com/users/11206",
"pm_score": 1,
"selected": false,
"text": "<p>I use Cygwin as my development environment and Notepad++ as an editor; I prefer sets of simple applications that each do one thing rather than massive complicated IDEs. Visual Studio is particularly problematic in this sense; not only is it very C++-oriented, but its completely overwhelming to newer programmers due to its sheer mass of features.</p>\n\n<p>MSVC also lacks support for most of the C99 standard, which can be very annoying when programming in C. For example, you have to declare all variables at the top of code blocks.</p>\n"
},
{
"answer_id": 150914,
"author": "Robert P",
"author_id": 18097,
"author_profile": "https://Stackoverflow.com/users/18097",
"pm_score": 1,
"selected": false,
"text": "<p>A favorite of mine is <a href=\"http://www.slickedit.com\" rel=\"nofollow noreferrer\">Slickedit</a>. A comprehensive IDE, one of the first apps to have C and C++ function hints (think, intellisense), works with GCC or almost every c/c++ compiler out there, will help you manage a make file or let you do it all yourself, fast, clean, and all in all slick. Integrates with almost any version control server as well. Fully configurable, has C/C++ refactoring, and will read/import almost any/every other project type out there.</p>\n\n<p>Of course, you have to pay for it, but if you want a good experience, you usually do.</p>\n\n<p>Alternatively, there's many many free code development tools out there like <a href=\"http://www.eclipse.org/\" rel=\"nofollow noreferrer\">Eclipse</a>, <a href=\"http://www.textpad.com/\" rel=\"nofollow noreferrer\">Textpad</a>, <a href=\"http://www.codeblocks.org/\" rel=\"nofollow noreferrer\">CodeBlocks</a>, <a href=\"http://www.editpadpro.com/editpadlite.html\" rel=\"nofollow noreferrer\">Editpad</a>, all with various levels of project integration. Most of Microsoft's development apps are available with their Visual Studio Express apps, if that's your cup of tea.</p>\n\n<p>Of course, lets not forget the classics: <a href=\"http://en.wikipedia.org/wiki/Vi\" rel=\"nofollow noreferrer\">Vi</a>, <a href=\"http://www.gnu.org/software/emacs/\" rel=\"nofollow noreferrer\">Emacs</a>. People have developed with these tools for a long, long time.</p>\n"
},
{
"answer_id": 150928,
"author": "James Schek",
"author_id": 17871,
"author_profile": "https://Stackoverflow.com/users/17871",
"pm_score": 0,
"selected": false,
"text": "<p><a href=\"http://www.netbeans.org/features/cpp/\" rel=\"nofollow noreferrer\">Netbeans</a> provides a fairly slick C/C++ development environment. Excellent for anyone who is already familiar with NB for Java, Ruby, or PHP development. Provides many of the same features as Visual Studio, Borland, or CodeWarrior (are they still around?) but without being tied to the proprietary libraries. It also provides for a portable development environment so you get a consistent workflow and toolset between platforms.</p>\n\n<p>Of course, a properly configured Vim with the GNU compiler tools can provide a pretty slick experience. You don't get popups and a gui, but it can automate the build process and even jump to errors in your code.</p>\n"
},
{
"answer_id": 150943,
"author": "el_eduardo",
"author_id": 13469,
"author_profile": "https://Stackoverflow.com/users/13469",
"pm_score": 2,
"selected": false,
"text": "<p>You can play with Eclipse, it is not the best one for C but it works. For a compiler I would use GNU gcc. for tools, look at CScope, gdb (debugger).</p>\n\n<p>If you don't care for extra baggage go with Microsoft Visual C++ Express edition but do keep in mind there is lots of extra stuff in there...</p>\n"
},
{
"answer_id": 151025,
"author": "skinp",
"author_id": 2907,
"author_profile": "https://Stackoverflow.com/users/2907",
"pm_score": 2,
"selected": false,
"text": "<p>I actually use Vim when editing C code, so I don't really know about C IDEs.</p>\n\n<p>I often use a couple of tools to help though:</p>\n\n<ul>\n<li>Ctags : Generate tag files for source code</li>\n<li>Make : Build automatisation</li>\n<li>GDB : The GNU debugger</li>\n<li>GCC : The GNU C Compiler</li>\n</ul>\n"
},
{
"answer_id": 151252,
"author": "jussij",
"author_id": 14738,
"author_profile": "https://Stackoverflow.com/users/14738",
"pm_score": 1,
"selected": false,
"text": "<p>If you develop on the <strong>Windows</strong> platform, the <a href=\"http://www.zeusedit.com/ccpp.html\" rel=\"nofollow noreferrer\">Zeus</a> editor has support for the C language.</p>\n\n<p><a href=\"https://i.stack.imgur.com/pj2wI.jpg\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/pj2wI.jpg\" alt=\"alt text\"></a><br>\n<sub>(source: <a href=\"http://www.zeusedit.com/images/_lookmain.jpg\" rel=\"nofollow noreferrer\">zeusedit.com</a>)</sub> </p>\n"
}
]
| 2008/09/29 | [
"https://Stackoverflow.com/questions/150881",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2192/"
]
| We are sending out Word documents via email (automated system, not by hand). The email is sent to the user, and CC'd to me.
We are getting reports that some users are having the attachments come through corrupted, though when we open the copy that is CC'd to me, it opens fine.
When the user forwards us the copy they received, then we cannot open it.
Below is a hex comparison of the two files. Can anyone identity what is going on here?
[](https://i.stack.imgur.com/8sSqA.png)
Message headers are below
```
Return-Path: <[email protected]>
Received: from animal.hosts.net.nz (root@localhost) by example.co.nz
(8.12.11/8.12.11) with ESMTP id m8T52Mw6021168; Mon, 29 Sep 2008 18:02:22
+1300
X-Clientaddr: 210.48.108.196
Received: from marjory.hosts.net.nz (marjory.hosts.net.nz
[210.48.108.196]) by animal.hosts.net.nz (8.12.11/8.12.11) with ESMTP id
m8T52EvU028021; Mon, 29 Sep 2008 18:02:19 +1300
Received: from example.example.co.nz ([210.48.67.48]) by
marjory.hosts.net.nz with esmtp (Exim 4.63) (envelope-from
<[email protected]>) id 1KkAtd-0004Ch-I9; Mon, 29 Sep 2008 18:02:09 +1300
Received: from localhost ([127.0.0.1]) by example.example.co.nz with esmtp
(Exim 4.63) (envelope-from <[email protected]>) id 1KkAtV-0001C3-4s;
Mon, 29 Sep 2008 18:02:01 +1300
From: "XXX" <[email protected]>
To: "Sue" <[email protected]>
Reply-To: [email protected]
Subject: XXX: new application received
Date: Mon, 29 Sep 2008 18:02:01 +1300
Content-Type: multipart/mixed;
charset="utf-8";
boundary="=_5549133ca51ec83196e2cfd28dad40f7"
Content-Transfer-Encoding: quoted-printable
Content-Disposition: inline
MIME-Version: 1.0
Message-ID: <[email protected]>
```
---
I think I know what it is, but not why it is happening.
"X-Mimeole: Produced By Microsoft Exchange V6.5" the client is using Exchange. Now, compare these lines.
The original:
```
Content-Type: multipart/mixed;
charset="utf-8";
boundary="=_5549133ca51ec83196e2cfd28dad40f7"
```
What they get:
```
Content-Type: multipart/mixed;
boundary="----_=_NextPart_001_01C92270.6BBA3EE6"
```
The missing charset="UTF-8" likely means that the client will fall back to Windows-1252, which I think (can someone confirm?) result in corrupted attachments.
Now the question is, why would the char-set be stripped? | I have always been fond of [Code::Blocks](http://www.codeblocks.org) It's a wonderful C/C++ IDE, with several helpful addons. As for a compiler I've always used MingW but I hear [DigitalMars C/C++](http://www.digitalmars.com) compiler is good. |
150,886 | <p>I'm currently trying to debug a customer's issue with an FTP upload feature in one of our products. The feature allows customers to upload files (< 1MB) to a central FTP server for further processing. The FTP client code was written in-house in VB.NET.</p>
<p>The customer reports that they receive "Connection forcibly closed by remote host" errors when they try to upload files in the range of 300KB to 500KB. However, we tested this in-house with much larger files (relatively speaking), i.e. 3MB and up, and never received this error. We uploaded to the same FTP server that the client connects to using the same FTP logon credentials, the only difference being that we did it from our office.</p>
<p>I know that the TCP protocol has flow-control built-in, so it shouldn't matter how much data is sent in a single Send call, since the protocol will throttle itself accordingly to match the server's internal limits (if I remember correctly...)</p>
<p>Therefore, the only thing I can think is that an intermediate host between the client and the router is artificially rate-limiting the client and disconnecting it (we send the file data in a loop in 512-byte chunks).</p>
<p>This is the loop that is used to send the data (buffer is a Byte array containing the file data):</p>
<pre><code> For i = 0 To buffer.Length - 1 Step 512
mDataSocket.Send(buffer, i, 512, SocketFlags.None)
OnTransferStatus(i, buffer.Length)
Next
</code></pre>
<p>Is it possible that the customer's ISP (or their own firewall) is imposing an artificial rate-limit on how much data our client code can send within a given period of time? If so, what is the best way to handle this situation? I guess the obvious solution would be to introduce a delay in our send loop, unless there is a way to do this at the socket level.</p>
<p>It seems really odd to me that an ISP would handle a rate-limit violation by killing the client connection. Why wouldn't they just rely on TCP/IP's internal flow-control/throttling mechanism?</p>
| [
{
"answer_id": 150894,
"author": "Mostlyharmless",
"author_id": 12881,
"author_profile": "https://Stackoverflow.com/users/12881",
"pm_score": 0,
"selected": false,
"text": "<p>I dont think the ISP would try to kill a 500KB file transfer. Im no expert in either socket thingy or on ISPs... just giving my thoughts on the matter.</p>\n"
},
{
"answer_id": 150932,
"author": "Mark Ransom",
"author_id": 5987,
"author_profile": "https://Stackoverflow.com/users/5987",
"pm_score": 3,
"selected": true,
"text": "<p>Do a search for Comcast and BitTorrent. Here's <a href=\"http://www.alternet.org/columnists/story/69779/\" rel=\"nofollow noreferrer\">one article</a>.</p>\n"
},
{
"answer_id": 150947,
"author": "xmjx",
"author_id": 15259,
"author_profile": "https://Stackoverflow.com/users/15259",
"pm_score": 1,
"selected": false,
"text": "<p>Try to isolate the issue:</p>\n\n<ul>\n<li>Let the customer upload the same file to a different server. Maybe the problem is with the client's ... FTP client.</li>\n<li>Get the file from the client and upload it yourself with your client and see if you can repro the issue.</li>\n</ul>\n\n<p>In the end, even if a 3MB file works fine, a 500KB file isn't guaranteed to work, because the issue could be state-depending and happening while ending the file transfer.</p>\n"
},
{
"answer_id": 150993,
"author": "Caerbanog",
"author_id": 23190,
"author_profile": "https://Stackoverflow.com/users/23190",
"pm_score": 1,
"selected": false,
"text": "<p>Yes, ISPs can impose limits to packets as they see fit (although it is ethically questionable). My ISP for example has no problem in cutting any P2P traffic its hardware manages to sniff out. Its called <a href=\"http://en.wikipedia.org/wiki/Traffic_shaping\" rel=\"nofollow noreferrer\">traffic shaping</a>.</p>\n\n<p>However for FTP traffic this is highly unlikelly, but you never know. The thing is, they never drop your sockets with traffic shaping, they only drop packets. The tcp protocol is handled on each pear side so you can drop all the packets in between and the socket keeps alive. In some instances if one of the computers crashes the socket remains alive if you dont try to use it.</p>\n\n<p>I think you best bet is a bad firewall/proxy configuration on the client side. Better explanations <a href=\"http://blogs.msdn.com/sql_protocols/archive/2008/04/08/understanding-connection-forcibly-closed-by-remote-host-errors-caused-by-toe-chimney.aspx\" rel=\"nofollow noreferrer\">here</a>.</p>\n\n<p>Either that or a faulty or badly configured router or cable on the client installations.</p>\n"
},
{
"answer_id": 151094,
"author": "Robert Paulson",
"author_id": 14033,
"author_profile": "https://Stackoverflow.com/users/14033",
"pm_score": 1,
"selected": false,
"text": "<p>500k is awefully small these days, so I'd be a little surprised if they throttle something that small. </p>\n\n<p>I know you're already chunking your request, but can you determine if any data is transferred? Does the code always fail at the same loop point? Are you able to look at the ftp server logs? What about an entire stack trace? Have you tried contacting the ISP and asking them what policies they have?</p>\n\n<p>That said, assuming that some data makes it through, one thought is that the ISP has traffic shaping and the rules engage after x bytes have been written. What could be happening is at data > x the socket timeout expires before the data is sent, throwing an exception.</p>\n\n<p>Keep in mind ftp clients create another connection for data transfer, but if the server detects the control connection is closed, it will typically kill the data transfer connection. So another thing to check is ensure the control connection is still alive.</p>\n\n<p>Lastly, ftp servers usually support resumable transfers, so if all other remedy's fail, resuming the failed transfer might be the easiest solution.</p>\n"
}
]
| 2008/09/29 | [
"https://Stackoverflow.com/questions/150886",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/17862/"
]
| I'm currently trying to debug a customer's issue with an FTP upload feature in one of our products. The feature allows customers to upload files (< 1MB) to a central FTP server for further processing. The FTP client code was written in-house in VB.NET.
The customer reports that they receive "Connection forcibly closed by remote host" errors when they try to upload files in the range of 300KB to 500KB. However, we tested this in-house with much larger files (relatively speaking), i.e. 3MB and up, and never received this error. We uploaded to the same FTP server that the client connects to using the same FTP logon credentials, the only difference being that we did it from our office.
I know that the TCP protocol has flow-control built-in, so it shouldn't matter how much data is sent in a single Send call, since the protocol will throttle itself accordingly to match the server's internal limits (if I remember correctly...)
Therefore, the only thing I can think is that an intermediate host between the client and the router is artificially rate-limiting the client and disconnecting it (we send the file data in a loop in 512-byte chunks).
This is the loop that is used to send the data (buffer is a Byte array containing the file data):
```
For i = 0 To buffer.Length - 1 Step 512
mDataSocket.Send(buffer, i, 512, SocketFlags.None)
OnTransferStatus(i, buffer.Length)
Next
```
Is it possible that the customer's ISP (or their own firewall) is imposing an artificial rate-limit on how much data our client code can send within a given period of time? If so, what is the best way to handle this situation? I guess the obvious solution would be to introduce a delay in our send loop, unless there is a way to do this at the socket level.
It seems really odd to me that an ISP would handle a rate-limit violation by killing the client connection. Why wouldn't they just rely on TCP/IP's internal flow-control/throttling mechanism? | Do a search for Comcast and BitTorrent. Here's [one article](http://www.alternet.org/columnists/story/69779/). |
150,891 | <p>I have a table with rowID, longitude, latitude, businessName, url, caption. This might look like:</p>
<pre><code>rowID | long | lat | businessName | url | caption
1 20 -20 Pizza Hut yum.com null
</code></pre>
<p>How do I delete all of the duplicates, but only keep the one that has a URL (first priority), or keep the one that has a caption if the other doesn't have a URL (second priority) and delete the rest?</p>
| [
{
"answer_id": 150967,
"author": "Amy B",
"author_id": 8155,
"author_profile": "https://Stackoverflow.com/users/8155",
"pm_score": 3,
"selected": true,
"text": "<p>Here's my looping technique. This will probably get voted down for not being mainstream - and I'm cool with that.</p>\n\n<pre><code>DECLARE @LoopVar int\n\nDECLARE\n @long int,\n @lat int,\n @businessname varchar(30),\n @winner int\n\nSET @LoopVar = (SELECT MIN(rowID) FROM Locations)\n\nWHILE @LoopVar is not null\nBEGIN\n --initialize the variables.\n SELECT \n @long = null,\n @lat = null,\n @businessname = null,\n @winner = null\n\n -- load data from the known good row. \n SELECT\n @long = long,\n @lat = lat,\n @businessname = businessname\n FROM Locations\n WHERE rowID = @LoopVar\n\n --find the winning row with that data\n SELECT top 1 @Winner = rowID\n FROM Locations\n WHERE @long = long\n AND @lat = lat\n AND @businessname = businessname\n ORDER BY\n CASE WHEN URL is not null THEN 1 ELSE 2 END,\n CASE WHEN Caption is not null THEN 1 ELSE 2 END,\n RowId\n\n --delete any losers.\n DELETE FROM Locations\n WHERE @long = long\n AND @lat = lat\n AND @businessname = businessname\n AND @winner != rowID\n\n -- prep the next loop value.\n SET @LoopVar = (SELECT MIN(rowID) FROM Locations WHERE @LoopVar < rowID)\nEND\n</code></pre>\n"
},
{
"answer_id": 150991,
"author": "Forgotten Semicolon",
"author_id": 1960,
"author_profile": "https://Stackoverflow.com/users/1960",
"pm_score": 0,
"selected": false,
"text": "<p>If possible, can you homogenize, then remove duplicates?</p>\n\n<p>Step 1:</p>\n\n<pre><code>UPDATE BusinessLocations\nSET BusinessLocations.url = LocationsWithUrl.url\nFROM BusinessLocations\nINNER JOIN (\n SELECT long, lat, businessName, url, caption\n FROM BusinessLocations \n WHERE url IS NOT NULL) LocationsWithUrl \n ON BusinessLocations.long = LocationsWithUrl.long\n AND BusinessLocations.lat = LocationsWithUrl.lat\n AND BusinessLocations.businessName = LocationsWithUrl.businessName\n\nUPDATE BusinessLocations\nSET BusinessLocations.caption = LocationsWithCaption.caption\nFROM BusinessLocations\nINNER JOIN (\n SELECT long, lat, businessName, url, caption\n FROM BusinessLocations \n WHERE caption IS NOT NULL) LocationsWithCaption \n ON BusinessLocations.long = LocationsWithCaption.long\n AND BusinessLocations.lat = LocationsWithCaption.lat\n AND BusinessLocations.businessName = LocationsWithCaption.businessName\n</code></pre>\n\n<p>Step 2:\n Remove duplicates.</p>\n"
},
{
"answer_id": 151015,
"author": "Constantin",
"author_id": 20310,
"author_profile": "https://Stackoverflow.com/users/20310",
"pm_score": 1,
"selected": false,
"text": "<p>Set-based solution:</p>\n\n<pre><code>delete from T as t1\nwhere /* delete if there is a \"better\" row\n with same long, lat and businessName */\n exists(\n select * from T as t2 where\n t1.rowID <> t2.rowID\n and t1.long = t2.long\n and t1.lat = t2.lat\n and t1.businessName = t2.businessName \n and\n case when t1.url is null then 0 else 4 end\n /* 4 points for non-null url */\n + case when t1.businessName is null then 0 else 2 end\n /* 2 points for non-null businessName */\n + case when t1.rowID > t2.rowId then 0 else 1 end\n /* 1 point for having smaller rowId */\n <\n case when t2.url is null then 0 else 4 end\n + case when t2.businessName is null then 0 else 2 end\n )\n</code></pre>\n"
},
{
"answer_id": 151057,
"author": "Todd Waldorf",
"author_id": 17894,
"author_profile": "https://Stackoverflow.com/users/17894",
"pm_score": 1,
"selected": false,
"text": "<pre><code>delete MyTable\nfrom MyTable\nleft outer join (\n select min(rowID) as rowID, long, lat, businessName\n from MyTable\n where url is not null\n group by long, lat, businessName\n ) as HasUrl\n on MyTable.long = HasUrl.long\n and MyTable.lat = HasUrl.lat\n and MyTable.businessName = HasUrl.businessName\nleft outer join (\n select min(rowID) as rowID, long, lat, businessName\n from MyTable\n where caption is not null\n group by long, lat, businessName\n ) HasCaption\n on MyTable.long = HasCaption.long\n and MyTable.lat = HasCaption.lat\n and MyTable.businessName = HasCaption.businessName\nleft outer join (\n select min(rowID) as rowID, long, lat, businessName\n from MyTable\n where url is null\n and caption is null\n group by long, lat, businessName\n ) HasNone \n on MyTable.long = HasNone.long\n and MyTable.lat = HasNone.lat\n and MyTable.businessName = HasNone.businessName\nwhere MyTable.rowID <> \n coalesce(HasUrl.rowID, HasCaption.rowID, HasNone.rowID)\n</code></pre>\n"
},
{
"answer_id": 151410,
"author": "Darrel Miller",
"author_id": 6819,
"author_profile": "https://Stackoverflow.com/users/6819",
"pm_score": 2,
"selected": false,
"text": "<p>This solution is brought to you by \"stuff I've learned on Stack Overflow\" in the last week:</p>\n\n<pre><code>DELETE restaurant\nWHERE rowID in \n(SELECT rowID\n FROM restaurant\n EXCEPT\n SELECT rowID \n FROM (\n SELECT rowID, Rank() over (Partition BY BusinessName, lat, long ORDER BY url DESC, caption DESC ) AS Rank\n FROM restaurant\n ) rs WHERE Rank = 1)\n</code></pre>\n\n<p>Warning: I have not tested this on a real database</p>\n"
},
{
"answer_id": 152388,
"author": "mancaus",
"author_id": 13797,
"author_profile": "https://Stackoverflow.com/users/13797",
"pm_score": 1,
"selected": false,
"text": "<p>Similar to another answer, but you want to delete based on row number rather than rank. Mix with common table expressions as well:</p>\n\n<pre><code>\n;WITH GroupedRows AS\n( SELECT rowID, Row_Number() OVER (Partition BY BusinessName, lat, long ORDER BY url DESC, caption DESC) rowNum \n FROM restaurant\n)\nDELETE r\nFROM restaurant r\nJOIN GroupedRows gr ON r.rowID = gr.rowID\nWHERE gr.rowNum > 1\n</code></pre>\n"
}
]
| 2008/09/29 | [
"https://Stackoverflow.com/questions/150891",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7952/"
]
| I have a table with rowID, longitude, latitude, businessName, url, caption. This might look like:
```
rowID | long | lat | businessName | url | caption
1 20 -20 Pizza Hut yum.com null
```
How do I delete all of the duplicates, but only keep the one that has a URL (first priority), or keep the one that has a caption if the other doesn't have a URL (second priority) and delete the rest? | Here's my looping technique. This will probably get voted down for not being mainstream - and I'm cool with that.
```
DECLARE @LoopVar int
DECLARE
@long int,
@lat int,
@businessname varchar(30),
@winner int
SET @LoopVar = (SELECT MIN(rowID) FROM Locations)
WHILE @LoopVar is not null
BEGIN
--initialize the variables.
SELECT
@long = null,
@lat = null,
@businessname = null,
@winner = null
-- load data from the known good row.
SELECT
@long = long,
@lat = lat,
@businessname = businessname
FROM Locations
WHERE rowID = @LoopVar
--find the winning row with that data
SELECT top 1 @Winner = rowID
FROM Locations
WHERE @long = long
AND @lat = lat
AND @businessname = businessname
ORDER BY
CASE WHEN URL is not null THEN 1 ELSE 2 END,
CASE WHEN Caption is not null THEN 1 ELSE 2 END,
RowId
--delete any losers.
DELETE FROM Locations
WHERE @long = long
AND @lat = lat
AND @businessname = businessname
AND @winner != rowID
-- prep the next loop value.
SET @LoopVar = (SELECT MIN(rowID) FROM Locations WHERE @LoopVar < rowID)
END
``` |
150,900 | <p>I am creating a Windows Forms control derived from UserControl to be embedded in a WPF app. I have generally followed the procedures given in <a href="http://www.codeproject.com/KB/WPF/WPFOpenGL.aspx?display=Print" rel="nofollow noreferrer">this link</a>.</p>
<pre><code>public ref class CTiledImgViewControl : public UserControl
{
...
virtual void OnPaint( PaintEventArgs^ e ) override;
...
};
</code></pre>
<p>And in my CPP file:</p>
<pre><code>void CTiledImgViewControl::OnPaint( PaintEventArgs^ e )
{
UserControl::OnPaint(e);
// do something interesting...
}
</code></pre>
<p>Everything compiles and runs, however the OnPaint method is never getting called.</p>
<p>Any ideas of things to look for? I've done a lot with C++, but am pretty new to WinForms and WPF, so it could well be something obvious...</p>
| [
{
"answer_id": 151143,
"author": "Jeff Yates",
"author_id": 23234,
"author_profile": "https://Stackoverflow.com/users/23234",
"pm_score": 3,
"selected": true,
"text": "<p>The <code>OnPaint</code> won't normally get called in a <code>UserControl</code> unless you set the appropriate style when it is constructed using the <code>SetStyle</code> method. You need to set the <code>UserPaint</code> style to true for the <code>OnPaint</code> to get called.</p>\n\n<pre><code>SetStyle(ControlStyles::UserPaint, true);\n</code></pre>\n\n<p><br/></p>\n\n<h3>Update</h3>\n\n<p>I recently encountered this issue myself and went digging for an answer. I wanted to perform some calculations during a paint (to leverage the unique handling of paint messages) but I wasn't always getting a call to <code>OnPaint</code>.</p>\n\n<p>After digging around with Reflector, I discovered that <code>OnPaint</code> is only called if the clipping rectangle of the corresponding <code>WM_PAINT</code> message is not empty. My <code>UserControl</code> instance had a child control that filled its entire client region and therefore, clipped it all. This meant that the clipping rectangle was empty and so no <code>OnPaint</code> call.</p>\n\n<p>I worked around this by overriding <code>WndProc</code> and adding a handler for <code>WM_PAINT</code> directly as I couldn't find another way to achieve what I wanted.</p>\n"
},
{
"answer_id": 153194,
"author": "Brian Stewart",
"author_id": 3114,
"author_profile": "https://Stackoverflow.com/users/3114",
"pm_score": 1,
"selected": false,
"text": "<p>I solved the issue, in case anyone is interested. It was because my WinForms control was embedded in a ViewBox. I changed it to a grid and immediately started getting paint events. I guess when asking questions about WPF, you should always include the XAML in the question!</p>\n"
}
]
| 2008/09/29 | [
"https://Stackoverflow.com/questions/150900",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3114/"
]
| I am creating a Windows Forms control derived from UserControl to be embedded in a WPF app. I have generally followed the procedures given in [this link](http://www.codeproject.com/KB/WPF/WPFOpenGL.aspx?display=Print).
```
public ref class CTiledImgViewControl : public UserControl
{
...
virtual void OnPaint( PaintEventArgs^ e ) override;
...
};
```
And in my CPP file:
```
void CTiledImgViewControl::OnPaint( PaintEventArgs^ e )
{
UserControl::OnPaint(e);
// do something interesting...
}
```
Everything compiles and runs, however the OnPaint method is never getting called.
Any ideas of things to look for? I've done a lot with C++, but am pretty new to WinForms and WPF, so it could well be something obvious... | The `OnPaint` won't normally get called in a `UserControl` unless you set the appropriate style when it is constructed using the `SetStyle` method. You need to set the `UserPaint` style to true for the `OnPaint` to get called.
```
SetStyle(ControlStyles::UserPaint, true);
```
### Update
I recently encountered this issue myself and went digging for an answer. I wanted to perform some calculations during a paint (to leverage the unique handling of paint messages) but I wasn't always getting a call to `OnPaint`.
After digging around with Reflector, I discovered that `OnPaint` is only called if the clipping rectangle of the corresponding `WM_PAINT` message is not empty. My `UserControl` instance had a child control that filled its entire client region and therefore, clipped it all. This meant that the clipping rectangle was empty and so no `OnPaint` call.
I worked around this by overriding `WndProc` and adding a handler for `WM_PAINT` directly as I couldn't find another way to achieve what I wanted. |
150,901 | <p>Anyone know a good Regex expression to drop in the ValidationExpression to be sure that my users are only entering ASCII characters? </p>
<pre><code><asp:RegularExpressionValidator id="myRegex" runat="server" ControlToValidate="txtName" ValidationExpression="???" ErrorMessage="Non-ASCII Characters" Display="Dynamic" />
</code></pre>
| [
{
"answer_id": 150925,
"author": "Jorge Ferreira",
"author_id": 6508,
"author_profile": "https://Stackoverflow.com/users/6508",
"pm_score": 0,
"selected": false,
"text": "<p>If you want to map the possible 0x00 - 0xff ASCII values you can use this regular expression (.NET).</p>\n\n<pre><code>^([\\x00-\\xff]*)$\n</code></pre>\n"
},
{
"answer_id": 153549,
"author": "Jon Biddle",
"author_id": 22895,
"author_profile": "https://Stackoverflow.com/users/22895",
"pm_score": 3,
"selected": true,
"text": "<p>One thing you may want to watch out for is the lower part of the ASCII table has a lot of control characters which can cause funky results. Here's the expression I use to only allow \"non-funky\" characters:</p>\n\n<pre><code>^([^\\x0d\\x0a\\x20-\\x7e\\t]*)$\n</code></pre>\n"
}
]
| 2008/09/29 | [
"https://Stackoverflow.com/questions/150901",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/13954/"
]
| Anyone know a good Regex expression to drop in the ValidationExpression to be sure that my users are only entering ASCII characters?
```
<asp:RegularExpressionValidator id="myRegex" runat="server" ControlToValidate="txtName" ValidationExpression="???" ErrorMessage="Non-ASCII Characters" Display="Dynamic" />
``` | One thing you may want to watch out for is the lower part of the ASCII table has a lot of control characters which can cause funky results. Here's the expression I use to only allow "non-funky" characters:
```
^([^\x0d\x0a\x20-\x7e\t]*)$
``` |
150,902 | <p>How can an object be loaded via Hibernate based on a field value of a member object? For example, suppose the following classes existed, with a one-to-one relationship between bar and foo:</p>
<pre><code>Foo {
Long id;
}
Bar {
Long id;
Foo aMember;
}
</code></pre>
<p>How could one use Hibernate Criteria to load Bar if you only had the id of Foo?</p>
<p>The first thing that leapt into my head was to load the Foo object and set that as a Criterion to load the Bar object, but that seems wasteful. Is there an effective way to do this with Criteria, or is HQL the way this should be handled?</p>
| [
{
"answer_id": 150973,
"author": "laz",
"author_id": 8753,
"author_profile": "https://Stackoverflow.com/users/8753",
"pm_score": 3,
"selected": true,
"text": "<p>You can absolutely use Criteria in an efficient manner to accomplish this:</p>\n\n<pre><code>session.createCriteria(Bar.class).\n createAlias(\"aMember\", \"a\").\n add(Restrictions.eq(\"a.id\", fooId));\n</code></pre>\n\n<p>ought to do the trick.</p>\n"
},
{
"answer_id": 152932,
"author": "kpirkkal",
"author_id": 15040,
"author_profile": "https://Stackoverflow.com/users/15040",
"pm_score": 0,
"selected": false,
"text": "<p>You can use Criteria or HQL.</p>\n\n<p>HQL example:</p>\n\n<p>Query query = session.createQuery(\"from Bar as bar where bar.aMember.id = :fooId\");</p>\n\n<p>query.setParameter(\"fooId\", fooId);</p>\n\n<p>List result = query.list();</p>\n"
}
]
| 2008/09/29 | [
"https://Stackoverflow.com/questions/150902",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
]
| How can an object be loaded via Hibernate based on a field value of a member object? For example, suppose the following classes existed, with a one-to-one relationship between bar and foo:
```
Foo {
Long id;
}
Bar {
Long id;
Foo aMember;
}
```
How could one use Hibernate Criteria to load Bar if you only had the id of Foo?
The first thing that leapt into my head was to load the Foo object and set that as a Criterion to load the Bar object, but that seems wasteful. Is there an effective way to do this with Criteria, or is HQL the way this should be handled? | You can absolutely use Criteria in an efficient manner to accomplish this:
```
session.createCriteria(Bar.class).
createAlias("aMember", "a").
add(Restrictions.eq("a.id", fooId));
```
ought to do the trick. |
150,941 | <p>Just found this out, so i am answering my own question :)</p>
<p>Use a comma where you would normally use a colon. This can be a problem for named instances, as you seem to need to specify the port even if it is the default port 1433.</p>
<p>Example:</p>
<pre><code>Provider=SQLOLEDB;Data Source=192.168.200.123,1433; Initial Catalog=Northwind; User Id=WebUser; Password=windy"
</code></pre>
| [
{
"answer_id": 150975,
"author": "BlackWasp",
"author_id": 21862,
"author_profile": "https://Stackoverflow.com/users/21862",
"pm_score": 4,
"selected": true,
"text": "<p>I always check out <a href=\"http://www.connectionstrings.com/\" rel=\"noreferrer\">http://www.connectionstrings.com/</a>. It is a brilliant resource for connection strings.</p>\n"
},
{
"answer_id": 150983,
"author": "mike nelson",
"author_id": 23616,
"author_profile": "https://Stackoverflow.com/users/23616",
"pm_score": 1,
"selected": false,
"text": "<p>Good call BlackWasp, actually that is where i found the answer! (But it was somewhat buried, so i wrote this one which is hopefully clearer)</p>\n"
}
]
| 2008/09/29 | [
"https://Stackoverflow.com/questions/150941",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/23616/"
]
| Just found this out, so i am answering my own question :)
Use a comma where you would normally use a colon. This can be a problem for named instances, as you seem to need to specify the port even if it is the default port 1433.
Example:
```
Provider=SQLOLEDB;Data Source=192.168.200.123,1433; Initial Catalog=Northwind; User Id=WebUser; Password=windy"
``` | I always check out <http://www.connectionstrings.com/>. It is a brilliant resource for connection strings. |
150,953 | <p>I get the following error when attempting to install <a href="http://docs.rubygems.org/" rel="nofollow noreferrer">RubyGems</a>. I've tried Googling but have had no luck there. Has anybody encountered and resolved this issue before?</p>
<pre><code>
C:\rubygems-1.3.0> ruby setup.rb
.
.
install -c -m 0644 rubygems/validator.rb C:/Ruby/lib/ruby/site_ruby/1.8/rubygems/validator.rb
install -c -m 0644 rubygems/version.rb C:/Ruby/lib/ruby/site_ruby/1.8/rubygems/version.rb
install -c -m 0644 rubygems/version_option.rb C:/Ruby/lib/ruby/site_ruby/1.8/rubygems/version_option.rb
install -c -m 0644 rubygems.rb C:/Ruby/lib/ruby/site_ruby/1.8/rubygems.rb
install -c -m 0644 ubygems.rb C:/Ruby/lib/ruby/site_ruby/1.8/ubygems.rb
cp gem C:/Users/brian/AppData/Local/Temp/gem
install -c -m 0755 C:/Users/brian/AppData/Local/Temp/gem C:/Ruby/bin/gem
rm C:/Users/brian/AppData/Local/Temp/gem
install -c -m 0755 C:/Users/brian/AppData/Local/Temp/gem.bat C:/Ruby/bin/gem.bat
rm C:/Users/brian/AppData/Local/Temp/gem.bat
Removing old RubyGems RDoc and ri
Installing rubygems-1.3.0 ri into C:/Ruby/lib/ruby/gems/1.8/doc/rubygems-1.3.0/ri
./lib/rubygems.rb:713:in `set_paths': undefined method `uid' for nil:NilClass (NoMethodError)
from ./lib/rubygems.rb:711:in `each'
from ./lib/rubygems.rb:711:in `set_paths'
from ./lib/rubygems.rb:518:in `path'
from ./lib/rubygems/source_index.rb:66:in `installed_spec_directories'
from ./lib/rubygems/source_index.rb:56:in `from_installed_gems'
from ./lib/rubygems.rb:726:in `source_index'
from ./lib/rubygems.rb:138:in `activate'
from ./lib/rubygems.rb:49:in `gem'
from setup.rb:279:in `run_rdoc'
from setup.rb:296
C:\rubygems-1.3.0></code></pre>
<p>I have Ruby 1.8.6 installed on my laptop running Windows Vista.</p>
| [
{
"answer_id": 150976,
"author": "JasonTrue",
"author_id": 13433,
"author_profile": "https://Stackoverflow.com/users/13433",
"pm_score": 3,
"selected": true,
"text": "<p>I assume you're not trying to install under cygwin; that install is meant for unix-like operating systems. Edit: (Actually, from the log above it looks like there is some Windows-specific stuff being run... perhaps you're running into a UAC protection issue?)</p>\n\n<p>If you just use the <a href=\"http://rubyforge.org/projects/rubyinstaller/\" rel=\"nofollow noreferrer\">Windows ruby one-click installer</a>, it includes rubygems. If you're not getting the rubygems functionality, you may need to\n<code>require \"rubygems\"</code> in your script, or add -rubygems to your RUBYOPT environment variable. (You can also require rubygems from the command line with <code>ruby -rubygems myscript.rb</code>.</p>\n\n<p>Are you trying to install it separately for some other reason?</p>\n"
},
{
"answer_id": 151004,
"author": "hectorsq",
"author_id": 14755,
"author_profile": "https://Stackoverflow.com/users/14755",
"pm_score": 0,
"selected": false,
"text": "<p>I have rubygems 1.2.0 installed on Vista and it works fine. I have no tested rubygems 1.3.0 yet.</p>\n"
},
{
"answer_id": 154682,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 0,
"selected": false,
"text": "<p>I found the same error with rubygems 1.3 on Vista. I downgraded to 1.2 and it seems to have fixed it</p>\n"
},
{
"answer_id": 195592,
"author": "Hik",
"author_id": 1716,
"author_profile": "https://Stackoverflow.com/users/1716",
"pm_score": 0,
"selected": false,
"text": "<p>I can confirm also, rubygems 1.3.0 on windows for some strange reason doesn't work at all.</p>\n\n<p>Downgrade, by re-installing 1.2.0 on top of the 1.3.0.</p>\n"
}
]
| 2008/09/29 | [
"https://Stackoverflow.com/questions/150953",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1969/"
]
| I get the following error when attempting to install [RubyGems](http://docs.rubygems.org/). I've tried Googling but have had no luck there. Has anybody encountered and resolved this issue before?
```
C:\rubygems-1.3.0> ruby setup.rb
.
.
install -c -m 0644 rubygems/validator.rb C:/Ruby/lib/ruby/site_ruby/1.8/rubygems/validator.rb
install -c -m 0644 rubygems/version.rb C:/Ruby/lib/ruby/site_ruby/1.8/rubygems/version.rb
install -c -m 0644 rubygems/version_option.rb C:/Ruby/lib/ruby/site_ruby/1.8/rubygems/version_option.rb
install -c -m 0644 rubygems.rb C:/Ruby/lib/ruby/site_ruby/1.8/rubygems.rb
install -c -m 0644 ubygems.rb C:/Ruby/lib/ruby/site_ruby/1.8/ubygems.rb
cp gem C:/Users/brian/AppData/Local/Temp/gem
install -c -m 0755 C:/Users/brian/AppData/Local/Temp/gem C:/Ruby/bin/gem
rm C:/Users/brian/AppData/Local/Temp/gem
install -c -m 0755 C:/Users/brian/AppData/Local/Temp/gem.bat C:/Ruby/bin/gem.bat
rm C:/Users/brian/AppData/Local/Temp/gem.bat
Removing old RubyGems RDoc and ri
Installing rubygems-1.3.0 ri into C:/Ruby/lib/ruby/gems/1.8/doc/rubygems-1.3.0/ri
./lib/rubygems.rb:713:in `set_paths': undefined method `uid' for nil:NilClass (NoMethodError)
from ./lib/rubygems.rb:711:in `each'
from ./lib/rubygems.rb:711:in `set_paths'
from ./lib/rubygems.rb:518:in `path'
from ./lib/rubygems/source_index.rb:66:in `installed_spec_directories'
from ./lib/rubygems/source_index.rb:56:in `from_installed_gems'
from ./lib/rubygems.rb:726:in `source_index'
from ./lib/rubygems.rb:138:in `activate'
from ./lib/rubygems.rb:49:in `gem'
from setup.rb:279:in `run_rdoc'
from setup.rb:296
C:\rubygems-1.3.0>
```
I have Ruby 1.8.6 installed on my laptop running Windows Vista. | I assume you're not trying to install under cygwin; that install is meant for unix-like operating systems. Edit: (Actually, from the log above it looks like there is some Windows-specific stuff being run... perhaps you're running into a UAC protection issue?)
If you just use the [Windows ruby one-click installer](http://rubyforge.org/projects/rubyinstaller/), it includes rubygems. If you're not getting the rubygems functionality, you may need to
`require "rubygems"` in your script, or add -rubygems to your RUBYOPT environment variable. (You can also require rubygems from the command line with `ruby -rubygems myscript.rb`.
Are you trying to install it separately for some other reason? |
150,977 | <p>What is the best way to replace all '&lt' with <code>&lt;</code> in a given database column? Basically perform <code>s/&lt[^;]/&lt;/gi</code></p>
<p>Notes:</p>
<ul>
<li>must work in <a href="http://en.wikipedia.org/wiki/Microsoft_SQL_Server#SQL_Server_2005" rel="noreferrer">MS SQL Server</a> 2000</li>
<li>Must be repeatable (and not end up with <code>&lt;;;;;;;;;;</code>)</li>
</ul>
| [
{
"answer_id": 151072,
"author": "Jorge Ferreira",
"author_id": 6508,
"author_profile": "https://Stackoverflow.com/users/6508",
"pm_score": 5,
"selected": true,
"text": "<p>Some hacking required but we can do this with <strong>LIKE</strong>, <strong>PATINDEX</strong>, <strong>LEFT</strong> AND <strong>RIGHT</strong> and good old string concatenation.</p>\n\n<pre><code>create table test\n(\n id int identity(1, 1) not null,\n val varchar(25) not null\n)\n\ninsert into test values ('&lt; <- ok, &lt <- nok')\n\nwhile 1 = 1\nbegin\n update test\n set val = left(val, patindex('%&lt[^;]%', val) - 1) +\n '&lt;' +\n right(val, len(val) - patindex('%&lt[^;]%', val) - 2)\n from test\n where val like '%&lt[^;]%'\n\n IF @@ROWCOUNT = 0 BREAK\nend\n\nselect * from test\n</code></pre>\n\n<p>Better is that this is SQL Server version agnostic and should work just fine.</p>\n"
},
{
"answer_id": 153669,
"author": "leoinfo",
"author_id": 6948,
"author_profile": "https://Stackoverflow.com/users/6948",
"pm_score": 4,
"selected": false,
"text": "<p>I think this can be done much cleaner if you use different STUFF :)</p>\n\n<pre><code>create table test\n(\n id int identity(1, 1) not null,\n val varchar(25) not null\n)\n\ninsert into test values ('&lt; <- ok, &lt <- nok')\n\nWHILE 1 = 1\nBEGIN\n UPDATE test SET\n val = STUFF( val , PATINDEX('%&lt[^;]%', val) + 3 , 0 , ';' )\n FROM test\n WHERE val LIKE '%&lt[^;]%'\n\n IF @@ROWCOUNT = 0 BREAK\nEND\n\nselect * from test\n</code></pre>\n"
},
{
"answer_id": 153746,
"author": "ilitirit",
"author_id": 9825,
"author_profile": "https://Stackoverflow.com/users/9825",
"pm_score": 3,
"selected": false,
"text": "<p>How about:</p>\n\n<pre><code> UPDATE tableName\n SET columName = REPLACE(columName , '&lt', '&lt;')\n WHERE columnName LIKE '%lt%'\n AND columnName NOT LIKE '%lt;%'\n</code></pre>\n\n<p>Edit:</p>\n\n<p>I just realized this will ignore columns with partially correct <code>&lt;</code> strings.</p>\n\n<p>In that case you can ignore the second part of the where clause and call this afterward:</p>\n\n<pre><code> UPDATE tableName\n SET columName = REPLACE(columName , '&lt;;', '&lt;')\n</code></pre>\n"
},
{
"answer_id": 153845,
"author": "Dave Sherohman",
"author_id": 18914,
"author_profile": "https://Stackoverflow.com/users/18914",
"pm_score": 1,
"selected": false,
"text": "<p>If MSSQL's regex flavor supports negative lookahead, that would be The Right Way to approach this.</p>\n\n<pre><code>s/&lt(?!;)/&lt;/gi\n</code></pre>\n\n<p>will catch all instances of <strong>&lt</strong> which are not followed by a <strong>;</strong> (even if they're followed by nothing, which <strong>[^;]</strong> would miss) and does not capture the following non-<strong>;</strong> character as part of the match, eliminating the issue mentioned in the comments on the original question of that character being lost in the replacement.</p>\n\n<p>Unfortunately, I don't use MSSQL, so I have no idea whether it supports negative lookahead or not...</p>\n"
},
{
"answer_id": 48076851,
"author": "Kristen",
"author_id": 65703,
"author_profile": "https://Stackoverflow.com/users/65703",
"pm_score": 1,
"selected": false,
"text": "<p>Very specific to this pattern, but I have done similar to this in the past:</p>\n\n<p><code>REPLACE(REPLACE(columName, '&lt;', '&lt'), '&lt', '&lt;')</code></p>\n\n<p>broader example (encode characters which may be inappropriate in a TITLE attribute)</p>\n\n<pre><code>REPLACE(REPLACE(REPLACE(REPLACE(\nREPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(\n columName\n -- Remove existing encoding:\n , '&amp;', '&')\n , '&#34;', '\"')\n , '&#39;', '''')\n -- Reinstate/Encode:\n , '&', '&amp;')\n -- Encode:\n , '\"', '&#34;')\n , '''', '&#39;')\n , ' ', '%20')\n , '<', '%3C')\n , '>', '%3E')\n , '/', '%2F')\n , '\\', '%5C')\n</code></pre>\n"
}
]
| 2008/09/29 | [
"https://Stackoverflow.com/questions/150977",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/80/"
]
| What is the best way to replace all '<' with `<` in a given database column? Basically perform `s/<[^;]/</gi`
Notes:
* must work in [MS SQL Server](http://en.wikipedia.org/wiki/Microsoft_SQL_Server#SQL_Server_2005) 2000
* Must be repeatable (and not end up with `<;;;;;;;;;`) | Some hacking required but we can do this with **LIKE**, **PATINDEX**, **LEFT** AND **RIGHT** and good old string concatenation.
```
create table test
(
id int identity(1, 1) not null,
val varchar(25) not null
)
insert into test values ('< <- ok, < <- nok')
while 1 = 1
begin
update test
set val = left(val, patindex('%<[^;]%', val) - 1) +
'<' +
right(val, len(val) - patindex('%<[^;]%', val) - 2)
from test
where val like '%<[^;]%'
IF @@ROWCOUNT = 0 BREAK
end
select * from test
```
Better is that this is SQL Server version agnostic and should work just fine. |
150,998 | <p>In my ActionScript3 class, can I have a property with a getter and setter?</p>
| [
{
"answer_id": 151108,
"author": "Max Stewart",
"author_id": 18338,
"author_profile": "https://Stackoverflow.com/users/18338",
"pm_score": 5,
"selected": true,
"text": "<p>Ok, well you can just use the basic getter/setter syntax for any property of your AS3 class. For example</p>\n\n<pre><code>package {\n\n public class PropEG {\n\n private var _prop:String;\n\n public function get prop():String {\n return _prop;\n }\n\n public function set prop(value:String):void {\n _prop = value;\n }\n }\n}\n</code></pre>\n"
},
{
"answer_id": 151115,
"author": "JustLogic",
"author_id": 21664,
"author_profile": "https://Stackoverflow.com/users/21664",
"pm_score": 2,
"selected": false,
"text": "<p>Yes you can create getter and setter functions inside an AS3 class.</p>\n\n<p>Example:</p>\n\n<pre><code>\nprivate var _foo:String = \"\";\n\npublic function get foo():String{\n return _foo;\n}\n\npublic function set foo(value:String):void {\n _foo= value;\n}\n</code></pre>\n\n<p>more information about getters and setters can be found <a href=\"http://livedocs.adobe.com/flex/201/html/wwhelp/wwhimpl/common/html/wwhelp.htm?context=LiveDocs_Book_Parts&file=basic_as_139_08.html\" rel=\"nofollow noreferrer\">here</a></p>\n"
},
{
"answer_id": 6558835,
"author": "Swati Singh",
"author_id": 822792,
"author_profile": "https://Stackoverflow.com/users/822792",
"pm_score": 0,
"selected": false,
"text": "<p>A getter is a function with a return value depending on what we return.\nA setter has always one parameter, since we give a variable a new value through the parameter.</p>\n\n<p>We first create an instance of the class containing the getter and setter, in our case it is \"a\". Then we call the setter, if we want to change the variable and using the dot syntax we call the setter function and with the = operator we fill the parameter. To retieve the value for a variable we use the getter in a similar way as shown in the example (a.myVar). Unlike a regular function call we omit the parentheses. Do not forget to add the return type, otherwise there will be an error. </p>\n\n<p>package \n{</p>\n\n<pre><code>import flash.display.Sprite;\nimport flash.text.TextField;\n\npublic class App extends Sprite \n{\n private var tsecField:TextField;\n private var tField:TextField;\n\n public function App() \n {\n myTest();\n }\n\n private function myTest():void \n {\n var a:Testvar = new Testvar();\n\n tField = new TextField();\n tField.autoSize = \"left\";\n tField.background = true;\n tField.border = true;\n a.mynewVar = \"This is the new var.\";\n tField.text = \"Test is: \"+a.myVar;\n addChild(tField);\n }\n}\n</code></pre>\n\n<p>}</p>\n\n<p>import flash.display.Sprite;</p>\n\n<p>import flash.text.TextField;</p>\n\n<p>class Testvar extends Sprite \n{\n public var test:String;</p>\n\n<pre><code>public function Testvar() \n{\n}\npublic function set mynewVar(newTest:String):void \n{\n test = newTest;\n}\npublic function get myVar():String \n{\n return test;\n}\n</code></pre>\n\n<p>}</p>\n"
}
]
| 2008/09/29 | [
"https://Stackoverflow.com/questions/150998",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/14131/"
]
| In my ActionScript3 class, can I have a property with a getter and setter? | Ok, well you can just use the basic getter/setter syntax for any property of your AS3 class. For example
```
package {
public class PropEG {
private var _prop:String;
public function get prop():String {
return _prop;
}
public function set prop(value:String):void {
_prop = value;
}
}
}
``` |
151,000 | <p>I've got a class named <code>BackgroundWorker</code> that has a thread constantly running. To turn this thread off, an instance variable named <code>stop</code> to needs to be <code>true</code>. </p>
<p>To make sure the thread is freed when the class is done being used, I've added <code>IDisposable</code> and a finalizer that invokes <code>Dispose()</code>. Assuming that <code>stop = true</code> does indeed cause this thread to exit, is this sippet correct? It's fine to invoke <code>Dispose</code> from a finalizer, right?</p>
<p>Finalizers should always call <code>Dispose</code> if the <code>object</code> inherits <code>IDisposable</code>, right?</p>
<pre><code>/// <summary>
/// Force the background thread to exit.
/// </summary>
public void Dispose()
{
lock (this.locker)
{
this.stop = true;
}
}
~BackgroundWorker()
{
this.Dispose();
}
</code></pre>
| [
{
"answer_id": 151022,
"author": "Michael Burr",
"author_id": 12711,
"author_profile": "https://Stackoverflow.com/users/12711",
"pm_score": 0,
"selected": false,
"text": "<p>Is the \"stop\" instance variable a property? If not, there's no particular point in setting it during the finalizer - nothing is referencing the object anymore, so nothing can query the member.</p>\n\n<p>If you're actually releasing a resource, then having Dispose() and the finalizer perform the same work (first testing whether the work still needs to be done) is a good pattern.</p>\n"
},
{
"answer_id": 151129,
"author": "Jeff Yates",
"author_id": 23234,
"author_profile": "https://Stackoverflow.com/users/23234",
"pm_score": 0,
"selected": false,
"text": "<p>You need the full disposable pattern but the stop has to be something the thread can access. If it is a member variable of the class being disposed, that's no good because it can't reference a disposed class. Consider having an event that the thread owns and signaling that on dispose instead.</p>\n"
},
{
"answer_id": 151207,
"author": "nedruod",
"author_id": 5504,
"author_profile": "https://Stackoverflow.com/users/5504",
"pm_score": 4,
"selected": false,
"text": "<p>First off, a <strong>severe warning</strong>. Don't use a finalizer like you are. You are setting yourself up for some very bad effects if you take locks within a finalizer. Short story is don't do it. Now to the original question.</p>\n\n<pre><code>public void Dispose()\n{\n Dispose(true);\n GC.SuppressFinalize(this);\n}\n\n/// <summary>\n/// Force the background thread to exit.\n/// </summary>\nprotected virtual void Dispose(bool disposing)\n{\n if (disposing)\n {\n lock (this.locker)\n {\n this.stop = true;\n }\n }\n}\n\n~BackgroundWorker()\n{\n Dispose(false);\n}\n</code></pre>\n\n<p>The only reason to have a finalizer at all is to allow sub-classes to extend and release <strong>unmanaged resources</strong>. If you don't have subclasses then seal your class and drop the finalizer completely.</p>\n"
},
{
"answer_id": 152033,
"author": "Marc Gravell",
"author_id": 23354,
"author_profile": "https://Stackoverflow.com/users/23354",
"pm_score": 2,
"selected": false,
"text": "<p>Out of interest, any reason this couldn't use the regular <a href=\"http://msdn.microsoft.com/en-us/library/system.componentmodel.backgroundworker.aspx\" rel=\"nofollow noreferrer\">BackgroundWorker</a>, which has full support for cancellation?</p>\n\n<p>Re the lock - a volatile bool field might be less troublesome.</p>\n\n<p>However, in this case your finalizer isn't doing anything interesting, especially given the \"if(disposing)\" - i.e. it only runs the interesting code during Dispose(). Personally I'd be tempted to stick with just IDisposable, and not provide a finalizer: you should be cleaning it up with Dispose().</p>\n"
},
{
"answer_id": 152086,
"author": "Sander",
"author_id": 2928,
"author_profile": "https://Stackoverflow.com/users/2928",
"pm_score": 3,
"selected": true,
"text": "<p>Your code is fine, although locking in a finalizer is somewhat \"scary\" and I would avoid it - if you get a deadlock... I am not 100% certain what would happen but it would not be good. However, if you are safe this should not be a problem. Mostly. The internals of garbage collection are painful and I hope you never have to see them ;)</p>\n\n<p>As Marc Gravell points out, a volatile bool would allow you to get rid of the lock, which would mitigate this issue. Implement this change if you can.</p>\n\n<p>nedruod's code puts the assignment inside the if (disposing) check, which is completely wrong - the thread is an unmanaged resource and must be stopped even if not explicitly disposing. Your code is fine, I am just pointing out that you should not take the advice given in that code snippet.</p>\n\n<p>Yes, you almost always should call Dispose() from the finalizer if implementing the IDisposable pattern. The full IDisposable pattern is a bit bigger than what you have but you do not always need it - it merely provides two extra possibilities:</p>\n\n<ol>\n<li>detecting whether Dispose() was called or the finalizer is executing (you are not allowed to touch any managed resources in the finalizer, outside of the object being finalized);</li>\n<li>enabling subclasses to override the Dispose() method.</li>\n</ol>\n"
},
{
"answer_id": 4332720,
"author": "supercat",
"author_id": 363751,
"author_profile": "https://Stackoverflow.com/users/363751",
"pm_score": 0,
"selected": false,
"text": "<p>The object that implements the finalizer needs a reference to a flag--stored <i>in another object</i>--which the thread will be able to see; the thread must <i>not</i> have any strong reference, direct or indirect, to the object that implements the finalizer. The finalizer should set the flag using something like a CompareExchange, and the thread should use a similar means to test it. Note that if the finalizer of one object accesses another object, the other object may have been finalized but it will still exist. It's fine for a finalizer to reference other objects if it does so in a way that won't be bothered by their finalization. If all you're doing is setting a flag, you're fine.</p>\n"
}
]
| 2008/09/29 | [
"https://Stackoverflow.com/questions/151000",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11574/"
]
| I've got a class named `BackgroundWorker` that has a thread constantly running. To turn this thread off, an instance variable named `stop` to needs to be `true`.
To make sure the thread is freed when the class is done being used, I've added `IDisposable` and a finalizer that invokes `Dispose()`. Assuming that `stop = true` does indeed cause this thread to exit, is this sippet correct? It's fine to invoke `Dispose` from a finalizer, right?
Finalizers should always call `Dispose` if the `object` inherits `IDisposable`, right?
```
/// <summary>
/// Force the background thread to exit.
/// </summary>
public void Dispose()
{
lock (this.locker)
{
this.stop = true;
}
}
~BackgroundWorker()
{
this.Dispose();
}
``` | Your code is fine, although locking in a finalizer is somewhat "scary" and I would avoid it - if you get a deadlock... I am not 100% certain what would happen but it would not be good. However, if you are safe this should not be a problem. Mostly. The internals of garbage collection are painful and I hope you never have to see them ;)
As Marc Gravell points out, a volatile bool would allow you to get rid of the lock, which would mitigate this issue. Implement this change if you can.
nedruod's code puts the assignment inside the if (disposing) check, which is completely wrong - the thread is an unmanaged resource and must be stopped even if not explicitly disposing. Your code is fine, I am just pointing out that you should not take the advice given in that code snippet.
Yes, you almost always should call Dispose() from the finalizer if implementing the IDisposable pattern. The full IDisposable pattern is a bit bigger than what you have but you do not always need it - it merely provides two extra possibilities:
1. detecting whether Dispose() was called or the finalizer is executing (you are not allowed to touch any managed resources in the finalizer, outside of the object being finalized);
2. enabling subclasses to override the Dispose() method. |
151,005 | <p>How can I create an Excel spreadsheet with C# without requiring Excel to be installed on the machine that's running the code?</p>
| [
{
"answer_id": 151014,
"author": "GEOCHET",
"author_id": 5640,
"author_profile": "https://Stackoverflow.com/users/5640",
"pm_score": 6,
"selected": false,
"text": "<p>You actually might want to check out the interop classes available in C# (e.g. <code>Microsoft.Office.Interop.Excel</code>. You say no OLE (which this isn't), but the interop classes are very easy to use. Check out the <a href=\"http://msdn.microsoft.com/en-us/library/ms173186(VS.80).aspx\" rel=\"noreferrer\">C# Documentation here</a> (Interop for Excel starts on page 1072 of the C# PDF).</p>\n\n<p>You might be impressed if you haven't tried them.</p>\n\n<p>Please be warned of Microsoft's <a href=\"https://support.microsoft.com/en-in/help/257757/considerations-for-server-side-automation-of-office\" rel=\"noreferrer\">stance</a> on this:</p>\n\n<blockquote>\n <p>Microsoft does not currently recommend, and does not support,\n Automation of Microsoft Office applications from any unattended,\n non-interactive client application or component (including ASP,\n ASP.NET, DCOM, and NT Services), because Office may exhibit unstable\n behavior and/or deadlock when Office is run in this environment.</p>\n</blockquote>\n"
},
{
"answer_id": 151035,
"author": "Forgotten Semicolon",
"author_id": 1960,
"author_profile": "https://Stackoverflow.com/users/1960",
"pm_score": 6,
"selected": false,
"text": "<p>An extremely lightweight option may be to use HTML tables. Just create head, body, and table tags in a file, and save it as a file with an .xls extension. There are Microsoft specific attributes that you can use to style the output, including formulas.</p>\n\n<p>I realize that you may not be coding this in a web application, but here is an <a href=\"https://web.archive.org/web/20051122071945/http://jasonhaley.com/blog/archive/2004/03/20/9583.aspx\" rel=\"noreferrer\">example</a> of the composition of an Excel file via an HTML table. This technique could be used if you were coding a console app, desktop app, or service.</p>\n"
},
{
"answer_id": 151043,
"author": "MagicKat",
"author_id": 8505,
"author_profile": "https://Stackoverflow.com/users/8505",
"pm_score": 4,
"selected": false,
"text": "<p><a href=\"http://www.ikvm.net/\" rel=\"noreferrer\">IKVM</a> + <a href=\"http://poi.apache.org/\" rel=\"noreferrer\">POI</a></p>\n\n<p>Or, you could use the Interop ...</p>\n"
},
{
"answer_id": 151048,
"author": "Panos",
"author_id": 8049,
"author_profile": "https://Stackoverflow.com/users/8049",
"pm_score": 7,
"selected": false,
"text": "<p>You can use OLEDB to create and manipulate Excel files. Check this: <a href=\"https://www.codeproject.com/Articles/8500/Reading-and-Writing-Excel-using-OLEDB\" rel=\"nofollow noreferrer\">Reading and Writing Excel using OLEDB</a>.</p>\n<p>Typical example:</p>\n<pre><code>using (OleDbConnection conn = new OleDbConnection("Provider=Microsoft.Jet.OLEDB.4.0;Data Source=C:\\\\temp\\\\test.xls;Extended Properties='Excel 8.0;HDR=Yes'"))\n{\n conn.Open();\n OleDbCommand cmd = new OleDbCommand("CREATE TABLE [Sheet1] ([Column1] string, [Column2] string)", conn);\n cmd.ExecuteNonQuery();\n}\n</code></pre>\n<p>EDIT - Some more links:</p>\n<ul>\n<li><a href=\"https://devblogs.microsoft.com/scripting/hey-scripting-guy-how-can-i-read-from-excel-without-using-excel/\" rel=\"nofollow noreferrer\">Hey, Scripting Guy! How Can I Read from Excel Without Using Excel?</a></li>\n<li><a href=\"http://support.microsoft.com/kb/316934\" rel=\"nofollow noreferrer\">How To Use ADO.NET to Retrieve and Modify Records in an Excel Workbook With Visual Basic .NET</a></li>\n<li><a href=\"http://davidhayden.com/blog/dave/archive/2006/05/26/2973.aspx\" rel=\"nofollow noreferrer\">Reading and Writing Excel Spreadsheets Using ADO.NET C# DbProviderFactory</a></li>\n</ul>\n"
},
{
"answer_id": 151075,
"author": "ManiacZX",
"author_id": 18148,
"author_profile": "https://Stackoverflow.com/users/18148",
"pm_score": 5,
"selected": false,
"text": "<p>You may want to take a look at <a href=\"https://www.gemboxsoftware.com/spreadsheet/free-version\" rel=\"noreferrer\">GemBox.Spreadsheet</a>.</p>\n\n<p>They have a free version with all features but limited to 150 rows per sheet and 5 sheets per workbook, if that falls within your needs.</p>\n\n<p>I haven't had need to use it myself yet, but does look interesting.</p>\n"
},
{
"answer_id": 151358,
"author": "Nick",
"author_id": 1490,
"author_profile": "https://Stackoverflow.com/users/1490",
"pm_score": 3,
"selected": false,
"text": "<p>The Java open source solution is <a href=\"https://poi.apache.org/\" rel=\"noreferrer\">Apache POI</a>. Maybe there is a way to setup interop here, but I don't know enough about Java to answer that.</p>\n\n<p>When I explored this problem I ended up using the Interop assemblies.</p>\n"
},
{
"answer_id": 151397,
"author": "Sam Warwick",
"author_id": 3873,
"author_profile": "https://Stackoverflow.com/users/3873",
"pm_score": 5,
"selected": false,
"text": "<p>You could consider creating your files using the <a href=\"https://en.wikipedia.org/wiki/Microsoft_Office_XML_formats#Excel_XML_Spreadsheet_example\" rel=\"noreferrer\">XML Spreadsheet 2003</a> format. This is a simple XML format using a <a href=\"https://learn.microsoft.com/en-us/previous-versions/office/developer/office-xp/aa140066(v=office.10)#odc_xmlss_ss:Workbook\" rel=\"noreferrer\">well documented schema</a>.</p>\n"
},
{
"answer_id": 151432,
"author": "Ryan Lundy",
"author_id": 5486,
"author_profile": "https://Stackoverflow.com/users/5486",
"pm_score": 4,
"selected": false,
"text": "<p>Here's a way to do it with LINQ to XML, complete with sample code:</p>\n\n<p><a href=\"http://blogs.msdn.com/bethmassi/archive/2007/10/30/quickly-import-and-export-excel-data-with-linq-to-xml.aspx\" rel=\"noreferrer\">Quickly Import and Export Excel Data with LINQ to XML</a></p>\n\n<p>It's a little complex, since you have to import namespaces and so forth, but it does let you avoid any external dependencies.</p>\n\n<p>(Also, of course, it's VB .NET, not C#, but you can always isolate the VB .NET stuff in its own project to use XML Literals, and do everything else in C#.)</p>\n"
},
{
"answer_id": 151694,
"author": "Aaron Powell",
"author_id": 11388,
"author_profile": "https://Stackoverflow.com/users/11388",
"pm_score": 4,
"selected": false,
"text": "<p>I agree about generating XML Spreadsheets, here's an example on how to do it for C# 3 (everyone just blogs about it in VB 9 :P) <a href=\"http://www.aaron-powell.com/linq-to-xml-to-excel\" rel=\"noreferrer\">http://www.aaron-powell.com/linq-to-xml-to-excel</a></p>\n"
},
{
"answer_id": 263272,
"author": "Stefan Koelle",
"author_id": 25233,
"author_profile": "https://Stackoverflow.com/users/25233",
"pm_score": 3,
"selected": false,
"text": "<p>Have you ever tried sylk?</p>\n\n<p>We used to generate excelsheets in classic asp as sylk and right now we're searching for an excelgenerater too.</p>\n\n<p>The advantages for sylk are, you can format the cells. </p>\n"
},
{
"answer_id": 313648,
"author": "biozinc",
"author_id": 30698,
"author_profile": "https://Stackoverflow.com/users/30698",
"pm_score": 4,
"selected": false,
"text": "<p>The various Office 2003 XML libraries avaliable work pretty well for smaller excel files. However, I find the sheer size of a large workbook saved in the XML format to be a problem. For example, a workbook I work with that would be 40MB in the new (and admittedly more tightly packed) XLSX format becomes a 360MB XML file.</p>\n\n<p>As far as my research has taken me, there are two commercial packages that allow output to the older binary file formats. They are:</p>\n\n<ul>\n<li><a href=\"https://www.gemboxsoftware.com/\" rel=\"noreferrer\">Gembox</a></li>\n<li><a href=\"http://www.componentone.com/SuperProducts/ExcelNET/\" rel=\"noreferrer\">ComponentOne Excel</a></li>\n</ul>\n\n<p>Neither are cheap (500USD and 800USD respectively, I think). but both work independant of Excel itself.</p>\n\n<p>What I would be curious about is the Excel output module for the likes of OpenOffice.org. I wonder if they can be ported from Java to .Net.</p>\n"
},
{
"answer_id": 476458,
"author": "Joe Erickson",
"author_id": 56710,
"author_profile": "https://Stackoverflow.com/users/56710",
"pm_score": 6,
"selected": false,
"text": "<p>The commercial solution, <a href=\"https://www.spreadsheetgear.com/\" rel=\"noreferrer\">SpreadsheetGear for .NET</a> will do it.</p>\n\n<p>You can see live ASP.NET (C# and VB) samples <a href=\"https://www.spreadsheetgear.com/support/samples/\" rel=\"noreferrer\">here</a> and download an evaluation version <a href=\"https://www.spreadsheetgear.com/downloads/register.aspx\" rel=\"noreferrer\">here</a>.</p>\n\n<p>Disclaimer: I own SpreadsheetGear LLC</p>\n"
},
{
"answer_id": 541661,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 6,
"selected": false,
"text": "<p>You can use <a href=\"https://www.carlosag.net/Tools/ExcelXmlWriter/\" rel=\"noreferrer\">ExcelXmlWriter</a>.</p>\n\n<p>It works fine.</p>\n"
},
{
"answer_id": 550521,
"author": "EMP",
"author_id": 20336,
"author_profile": "https://Stackoverflow.com/users/20336",
"pm_score": 4,
"selected": false,
"text": "<p>I've just recently used <strong><a href=\"https://www.tmssoftware.com/site/flexcelnet.asp\" rel=\"nofollow noreferrer\">FlexCel.NET</a></strong> and found it to be an excellent library! I don't say that about too many software products. No point in giving the whole sales pitch here, you can read all the features on their website.</p>\n<p>It is a commercial product, but you get the full source if you buy it. So I suppose you could compile it into your assembly if you really wanted to. Otherwise it's just one extra assembly to xcopy - no configuration or installation or anything like that.</p>\n<p>I don't think you'll find any way to do this without third-party libraries as .NET framework, obviously, does not have built in support for it and OLE Automation is just a whole world of pain.</p>\n"
},
{
"answer_id": 935392,
"author": "Nate",
"author_id": 98180,
"author_profile": "https://Stackoverflow.com/users/98180",
"pm_score": 6,
"selected": false,
"text": "<p>A few options I have used:</p>\n\n<p>If XLSX is a must: <a href=\"https://archive.codeplex.com/?p=ExcelPackage\" rel=\"noreferrer\">ExcelPackage</a> is a good start but died off when the developer quit working on it. ExML picked up from there and added a few features. <a href=\"https://archive.codeplex.com/?p=exml\" rel=\"noreferrer\">ExML</a> isn't a bad option, I'm still using it in a couple of production websites.</p>\n\n<p>For all of my new projects, though, I'm using <a href=\"https://github.com/tonyqus/npoi\" rel=\"noreferrer\">NPOI</a>, the .NET port of <a href=\"https://poi.apache.org/\" rel=\"noreferrer\">Apache POI</a>. \n<a href=\"https://github.com/tonyqus/npoi\" rel=\"noreferrer\">NPOI 2.0 (Alpha)</a> also supports XLSX.</p>\n"
},
{
"answer_id": 1022518,
"author": "Leniel Maccaferri",
"author_id": 114029,
"author_profile": "https://Stackoverflow.com/users/114029",
"pm_score": 7,
"selected": false,
"text": "<p>I've used with success the following open source projects:</p>\n\n<ul>\n<li><p>ExcelPackage for OOXML formats (Office 2007)</p></li>\n<li><p>NPOI for .XLS format (Office 2003). <a href=\"https://github.com/tonyqus/npoi\" rel=\"noreferrer\">NPOI 2.0</a> (Beta) also supports XLSX.</p></li>\n</ul>\n\n<p>Take a look at my blog posts:</p>\n\n<p><a href=\"https://www.leniel.net/2009/07/creating-excel-spreadsheets-xls-xlsx-c.html\" rel=\"noreferrer\">Creating Excel spreadsheets .XLS and .XLSX in C#</a></p>\n\n<p><a href=\"https://www.leniel.net/2009/10/npoi-with-excel-table-and-dynamic-chart.html\" rel=\"noreferrer\">NPOI with Excel Table and dynamic Chart</a></p>\n"
},
{
"answer_id": 1607981,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 3,
"selected": false,
"text": "<p>I also vote for <a href=\"https://www.gemboxsoftware.com/spreadsheet\" rel=\"nofollow noreferrer\">GemBox.Spreadsheet</a>.</p>\n\n<p>Very fast and easy to use, with tons of examples on their site.</p>\n\n<p>Took my reporting tasks on a whole new level of execution speed.</p>\n"
},
{
"answer_id": 1705725,
"author": "Dimi Takis",
"author_id": 52039,
"author_profile": "https://Stackoverflow.com/users/52039",
"pm_score": 4,
"selected": false,
"text": "<p>Well,</p>\n\n<p>you can also use a third party library like <a href=\"http://aspose.com\" rel=\"noreferrer\">Aspose</a>.</p>\n\n<p>This library has the benefit that it does not require Excel to be installed on your machine which would be ideal in your case.</p>\n"
},
{
"answer_id": 2537778,
"author": "Jan Källman",
"author_id": 304193,
"author_profile": "https://Stackoverflow.com/users/304193",
"pm_score": 9,
"selected": false,
"text": "<p>If you are happy with the xlsx format, try my library, EPPlus. It started with the source from ExcelPackage, but since became a total rewrite.</p>\n<p>It supports ranges, cell styling, charts, shapes, pictures, named ranges, AutoFilter, and a lot of other stuff.</p>\n<p>You have two options:</p>\n<ul>\n<li><p><a href=\"https://github.com/JanKallman/EPPlus\" rel=\"noreferrer\">EPPlus 4</a>, licensed under LGPL (original branch, developed until 2020)</p>\n</li>\n<li><p><a href=\"https://github.com/EPPlusSoftware/EPPlus\" rel=\"noreferrer\">EPPlus 5</a>, licensed under Polyform Noncommercial 1.0.0 (since 2020).</p>\n</li>\n</ul>\n<p>From the EPPlus 5 readme.md:</p>\n<blockquote>\n<p>With the new license EPPlus is still free to use in some cases, but will require a commercial license to be used in a commercial business.</p>\n</blockquote>\n<p>EPPlus website: <a href=\"https://www.epplussoftware.com/\" rel=\"noreferrer\">https://www.epplussoftware.com/</a></p>\n"
},
{
"answer_id": 2603625,
"author": "Mike Webb",
"author_id": 273723,
"author_profile": "https://Stackoverflow.com/users/273723",
"pm_score": 11,
"selected": true,
"text": "<p>You can use a library called ExcelLibrary. It's a free, open source library posted on Google Code:</p>\n\n<p><a href=\"https://code.google.com/archive/p/excellibrary/\" rel=\"noreferrer\">ExcelLibrary</a></p>\n\n<p>This looks to be a port of the PHP ExcelWriter that you mentioned above. It will not write to the new .xlsx format yet, but they are working on adding that functionality in.</p>\n\n<p>It's very simple, small and easy to use. Plus it has a DataSetHelper that lets you use DataSets and DataTables to easily work with Excel data.</p>\n\n<p>ExcelLibrary seems to still only work for the older Excel format (.xls files), but may be adding support in the future for newer 2007/2010 formats. </p>\n\n<p>You can also use <a href=\"https://github.com/JanKallman/EPPlus\" rel=\"noreferrer\">EPPlus</a>, which works only for Excel 2007/2010 format files (.xlsx files). There's also <a href=\"https://github.com/tonyqus/npoi\" rel=\"noreferrer\">NPOI</a> which works with both.</p>\n\n<p>There are a few known bugs with each library as noted in the comments. In all, EPPlus seems to be the best choice as time goes on. It seems to be more actively updated and documented as well.</p>\n\n<p>Also, as noted by @АртёмЦарионов below, EPPlus has support for Pivot Tables and ExcelLibrary may have some support (<a href=\"https://code.google.com/archive/p/excellibrary/issues/98\" rel=\"noreferrer\">Pivot table issue in ExcelLibrary</a>)</p>\n\n<p>Here are a couple links for quick reference:<br/>\n<a href=\"https://code.google.com/archive/p/excellibrary/\" rel=\"noreferrer\">ExcelLibrary</a> - <a href=\"https://www.gnu.org/licenses/lgpl.html\" rel=\"noreferrer\">GNU Lesser GPL</a><br/>\n<a href=\"https://github.com/JanKallman/EPPlus\" rel=\"noreferrer\">EPPlus</a> - <a href=\"https://github.com/JanKallman/EPPlus#license\" rel=\"noreferrer\">GNU (LGPL) - No longer maintained</a><br/>\n<a href=\"https://www.epplussoftware.com/\" rel=\"noreferrer\">EPPlus 5</a> - <a href=\"https://www.epplussoftware.com/en/LicenseOverview\" rel=\"noreferrer\">Polyform Noncommercial - Starting May 2020</a><br/>\n<a href=\"https://github.com/tonyqus/npoi\" rel=\"noreferrer\">NPOI</a> - <a href=\"https://github.com/tonyqus/npoi/blob/master/LICENSE\" rel=\"noreferrer\">Apache License</a></p>\n\n<p><b>Here some example code for ExcelLibrary:</b></p>\n\n<p>Here is an example taking data from a database and creating a workbook from it. Note that the ExcelLibrary code is the single line at the bottom:</p>\n\n<pre><code>//Create the data set and table\nDataSet ds = new DataSet(\"New_DataSet\");\nDataTable dt = new DataTable(\"New_DataTable\");\n\n//Set the locale for each\nds.Locale = System.Threading.Thread.CurrentThread.CurrentCulture;\ndt.Locale = System.Threading.Thread.CurrentThread.CurrentCulture;\n\n//Open a DB connection (in this example with OleDB)\nOleDbConnection con = new OleDbConnection(dbConnectionString);\ncon.Open();\n\n//Create a query and fill the data table with the data from the DB\nstring sql = \"SELECT Whatever FROM MyDBTable;\";\nOleDbCommand cmd = new OleDbCommand(sql, con);\nOleDbDataAdapter adptr = new OleDbDataAdapter();\n\nadptr.SelectCommand = cmd;\nadptr.Fill(dt);\ncon.Close();\n\n//Add the table to the data set\nds.Tables.Add(dt);\n\n//Here's the easy part. Create the Excel worksheet from the data set\nExcelLibrary.DataSetHelper.CreateWorkbook(\"MyExcelFile.xls\", ds);\n</code></pre>\n\n<p>Creating the Excel file is as easy as that. You can also manually create Excel files, but the above functionality is what really impressed me.</p>\n"
},
{
"answer_id": 3215860,
"author": "ScaleOvenStove",
"author_id": 12268,
"author_profile": "https://Stackoverflow.com/users/12268",
"pm_score": 3,
"selected": false,
"text": "<p>You can just write it out to XML using the Excel XML format and name it with .XLS extension and it will open with excel. You can control all the formatting (bold, widths, etc) in your XML file heading.</p>\n\n<p>There is an <a href=\"https://en.wikipedia.org/wiki/Microsoft_Office_XML_formats#Excel_XML_Spreadsheet_example\" rel=\"noreferrer\">example XML from Wikipedia</a>.</p>\n"
},
{
"answer_id": 4258376,
"author": "Manuel",
"author_id": 335911,
"author_profile": "https://Stackoverflow.com/users/335911",
"pm_score": 6,
"selected": false,
"text": "<p>If you're creating Excel 2007/2010 files give this open source project a try: <a href=\"https://github.com/closedxml/closedxml\" rel=\"noreferrer\">https://github.com/closedxml/closedxml</a></p>\n\n<blockquote>\n <p>It provides an object oriented way to manipulate the files (similar to\n VBA) without dealing with the hassles of XML Documents. It can be used\n by any .NET language like C# and Visual Basic (VB).</p>\n \n <p>ClosedXML allows you to create Excel 2007/2010 files without the Excel\n application. The typical example is creating Excel reports on a web\n server:</p>\n\n<pre><code>var workbook = new XLWorkbook();\nvar worksheet = workbook.Worksheets.Add(\"Sample Sheet\");\nworksheet.Cell(\"A1\").Value = \"Hello World!\";\nworkbook.SaveAs(\"HelloWorld.xlsx\");\n</code></pre>\n</blockquote>\n"
},
{
"answer_id": 4349343,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 4,
"selected": false,
"text": "<p>You can create nicely formatted Excel files using this library:\n<a href=\"http://officehelper.codeplex.com/documentation\" rel=\"noreferrer\">http://officehelper.codeplex.com/documentation</a>\n<br>\nSee below sample:</p>\n\n<pre><code>using (ExcelHelper helper = new ExcelHelper(TEMPLATE_FILE_NAME, GENERATED_FILE_NAME))\n{\n helper.Direction = ExcelHelper.DirectionType.TOP_TO_DOWN;\n helper.CurrentSheetName = \"Sheet1\";\n helper.CurrentPosition = new CellRef(\"C3\");\n\n //the template xlsx should contains the named range \"header\"; use the command \"insert\"/\"name\".\n helper.InsertRange(\"header\");\n\n //the template xlsx should contains the named range \"sample1\";\n //inside this range you should have cells with these values:\n //<name> , <value> and <comment>, which will be replaced by the values from the getSample()\n CellRangeTemplate sample1 = helper.CreateCellRangeTemplate(\"sample1\", new List<string> {\"name\", \"value\", \"comment\"}); \n helper.InsertRange(sample1, getSample());\n\n //you could use here other named ranges to insert new cells and call InsertRange as many times you want, \n //it will be copied one after another;\n //even you can change direction or the current cell/sheet before you insert\n\n //typically you put all your \"template ranges\" (the names) on the same sheet and then you just delete it\n helper.DeleteSheet(\"Sheet3\");\n} \n</code></pre>\n\n<p>where sample look like this:</p>\n\n<pre><code>private IEnumerable<List<object>> getSample()\n{\n var random = new Random();\n\n for (int loop = 0; loop < 3000; loop++)\n {\n yield return new List<object> {\"test\", DateTime.Now.AddDays(random.NextDouble()*100 - 50), loop};\n }\n}\n</code></pre>\n"
},
{
"answer_id": 4943712,
"author": "Craig Mc",
"author_id": 379972,
"author_profile": "https://Stackoverflow.com/users/379972",
"pm_score": 2,
"selected": false,
"text": "<p><a href=\"http://www.codeproject.com/KB/cs/Excel_and_C_.aspx\" rel=\"nofollow\">http://www.codeproject.com/KB/cs/Excel_and_C_.aspx</a> <= why not just use the built in power of windows, just install office on the server, any application that you install can be automated.</p>\n\n<p>So much easier just use the native methods.</p>\n\n<p>If it installed you can use it, this is the most awesome and under used feature in windows it was Dubbed COM back in the good old days, and it saves you tons of time and pain.</p>\n\n<p>Or even easier just use the ref lib MS supplies - <a href=\"http://csharp.net-informations.com/excel/csharp-create-excel.htm\" rel=\"nofollow\">http://csharp.net-informations.com/excel/csharp-create-excel.htm</a></p>\n"
},
{
"answer_id": 5016019,
"author": "Simen S",
"author_id": 619275,
"author_profile": "https://Stackoverflow.com/users/619275",
"pm_score": 4,
"selected": false,
"text": "<p>Some 3rd party component vendors like Infragistics or Syncfusion provide very good Excel export capabilities that do not require Microsoft Excel to be installed. </p>\n\n<p>Since these vendors also provide advanced UI grid components, these components are particularly handy if you want the style and layout of an excel export to mimic the current state of a grid in the user interface of your application.</p>\n\n<p>If your export is intended to be executed server side with emphasis on the data to be exported and with no link to the UI, then I would go for one of the free open source options (e.g. ExcelLibrary). </p>\n\n<p>I have previously been involved with projects that attempted to use server side automation on the Microsoft Office suite. Based on this experience I would strongly recommend against that approach. </p>\n"
},
{
"answer_id": 5817310,
"author": "Gaurav",
"author_id": 729122,
"author_profile": "https://Stackoverflow.com/users/729122",
"pm_score": 4,
"selected": false,
"text": "<pre><code>public class GridViewExportUtil\n{\n public static void Export(string fileName, GridView gv)\n {\n HttpContext.Current.Response.Clear();\n HttpContext.Current.Response.AddHeader(\n \"content-disposition\", string.Format(\"attachment; filename={0}\", fileName));\n HttpContext.Current.Response.ContentType = \"application/ms-excel\";\n\n using (StringWriter sw = new StringWriter())\n {\n using (HtmlTextWriter htw = new HtmlTextWriter(sw))\n {\n // Create a form to contain the grid\n Table table = new Table();\n\n // add the header row to the table\n if (gv.HeaderRow != null)\n {\n GridViewExportUtil.PrepareControlForExport(gv.HeaderRow);\n table.Rows.Add(gv.HeaderRow);\n }\n\n // add each of the data rows to the table\n foreach (GridViewRow row in gv.Rows)\n {\n GridViewExportUtil.PrepareControlForExport(row);\n table.Rows.Add(row);\n }\n\n // add the footer row to the table\n if (gv.FooterRow != null)\n {\n GridViewExportUtil.PrepareControlForExport(gv.FooterRow);\n table.Rows.Add(gv.FooterRow);\n }\n\n // render the table into the htmlwriter\n table.RenderControl(htw);\n\n // render the htmlwriter into the response\n HttpContext.Current.Response.Write(sw.ToString());\n HttpContext.Current.Response.End();\n }\n }\n }\n\n /// <summary>\n /// Replace any of the contained controls with literals\n /// </summary>\n /// <param name=\"control\"></param>\n private static void PrepareControlForExport(Control control)\n {\n for (int i = 0; i < control.Controls.Count; i++)\n {\n Control current = control.Controls[i];\n if (current is LinkButton)\n {\n control.Controls.Remove(current);\n control.Controls.AddAt(i, new LiteralControl((current as LinkButton).Text));\n }\n else if (current is ImageButton)\n {\n control.Controls.Remove(current);\n control.Controls.AddAt(i, new LiteralControl((current as ImageButton).AlternateText));\n }\n else if (current is HyperLink)\n {\n control.Controls.Remove(current);\n control.Controls.AddAt(i, new LiteralControl((current as HyperLink).Text));\n }\n else if (current is DropDownList)\n {\n control.Controls.Remove(current);\n control.Controls.AddAt(i, new LiteralControl((current as DropDownList).SelectedItem.Text));\n }\n else if (current is CheckBox)\n {\n control.Controls.Remove(current);\n control.Controls.AddAt(i, new LiteralControl((current as CheckBox).Checked ? \"True\" : \"False\"));\n }\n\n if (current.HasControls())\n {\n GridViewExportUtil.PrepareControlForExport(current);\n }\n }\n }\n}\n</code></pre>\n\n<p>Hi this solution is to export your grid view to your excel file it might help you out</p>\n"
},
{
"answer_id": 7076092,
"author": "Pellared",
"author_id": 859275,
"author_profile": "https://Stackoverflow.com/users/859275",
"pm_score": 8,
"selected": false,
"text": "<p>And what about using Open XML SDK 2.0 for Microsoft Office?</p>\n\n<p>A few benefits:</p>\n\n<ul>\n<li>Doesn't require Office installed</li>\n<li>Made by Microsoft = decent MSDN documentation</li>\n<li>Just one .Net dll to use in project</li>\n<li>SDK comes with many tools like diff, validator, etc</li>\n</ul>\n\n<p>Links:</p>\n\n<ul>\n<li><a href=\"https://github.com/officedev/open-xml-sdk\" rel=\"noreferrer\">Github</a></li>\n<li><a href=\"https://learn.microsoft.com/en-us/office/open-xml/open-xml-sdk\" rel=\"noreferrer\">Main MSDN Landing</a></li>\n<li><a href=\"https://learn.microsoft.com/en-us/office/open-xml/how-do-i\" rel=\"noreferrer\">\"How Do I...\" starter page</a></li>\n<li>blogs.MSDN brian_jones <a href=\"https://blogs.msdn.microsoft.com/brian_jones/2010/03/12/announcing-the-release-of-the-open-xml-sdk-2-0/\" rel=\"noreferrer\">announcing SDK</a></li>\n<li>blogs.MSDN brian_jones <a href=\"https://blogs.msdn.microsoft.com/brian_jones/2010/06/22/writing-large-excel-files-with-the-open-xml-sdk/\" rel=\"noreferrer\">describing SDK handling large files without crashing (unlike DOM method)</a></li>\n</ul>\n"
},
{
"answer_id": 7164605,
"author": "Eisbaer",
"author_id": 847001,
"author_profile": "https://Stackoverflow.com/users/847001",
"pm_score": 4,
"selected": false,
"text": "<p>Just want to add another reference to a third party solution that directly addresses your issue: <a href=\"http://www.officewriter.com\">http://www.officewriter.com</a></p>\n\n<p>(Disclaimer: I work for SoftArtisans, the company that makes OfficeWriter)</p>\n"
},
{
"answer_id": 8385077,
"author": "Mike Gledhill",
"author_id": 391605,
"author_profile": "https://Stackoverflow.com/users/391605",
"pm_score": 5,
"selected": false,
"text": "<p>Here's a completely free C# library, which lets you export from a <code>DataSet</code>, <code>DataTable</code> or <code>List<></code> into a genuine Excel 2007 .xlsx file, using the OpenXML libraries:</p>\n\n<p><a href=\"http://mikesknowledgebase.com/pages/CSharp/ExportToExcel.htm\" rel=\"noreferrer\">http://mikesknowledgebase.com/pages/CSharp/ExportToExcel.htm</a></p>\n\n<p>Full source code is provided - free of charge - along with instructions, and a demo application.</p>\n\n<p>After adding this class to your application, you can export your DataSet to Excel in just one line of code:</p>\n\n<pre><code>CreateExcelFile.CreateExcelDocument(myDataSet, \"C:\\\\Sample.xlsx\");\n</code></pre>\n\n<p>It doesn't get much simpler than that...</p>\n\n<p>And it doesn't even require Excel to be present on your server.</p>\n"
},
{
"answer_id": 27577733,
"author": "saurabh27",
"author_id": 3847777,
"author_profile": "https://Stackoverflow.com/users/3847777",
"pm_score": -1,
"selected": false,
"text": "<p>I am using following code for create excel 2007 file which create the file and write in that file but when i open the file but it give me error that\nexel cannot open the file bcz file might be coruupted or extension of the file is not compatible.\nbut if i used .xls for file it work fines</p>\n\n<pre><code>for (int i = 0; i < TotalFile; i++)\n{\n Contact.Clear();\n if (innerloop == SplitSize)\n {\n for (int j = 0; j < SplitSize; j++)\n {\n string strContact = DSt.Tables[0].Rows[i * SplitSize + j][0].ToString();\n Contact.Add(strContact);\n }\n string strExcel = strFileName + \"_\" + i.ToString() + \".xlsx\";\n File.WriteAllLines(strExcel, Contact.ToArray());\n }\n}\n</code></pre>\n\n<p>also refer link</p>\n\n<p><a href=\"http://dotnet-magic.blogspot.in/2011/10/createformat-excel-file-from-cnet.html\" rel=\"nofollow\">http://dotnet-magic.blogspot.in/2011/10/createformat-excel-file-from-cnet.html</a></p>\n"
},
{
"answer_id": 31581330,
"author": "Vihana Kewalramani",
"author_id": 2082715,
"author_profile": "https://Stackoverflow.com/users/2082715",
"pm_score": 4,
"selected": false,
"text": "<p>I have written a simple code to export dataset to excel without using excel object by using System.IO.StreamWriter.</p>\n\n<p>Below is the code which will read all tables from dataset and write them to sheets one by one. I took help from <a href=\"https://www.codeproject.com/Articles/9380/Export-a-DataSet-to-Microsoft-Excel-without-the-us\" rel=\"noreferrer\">this article</a>.</p>\n\n<pre><code>public static void exportToExcel(DataSet source, string fileName)\n{\n const string endExcelXML = \"</Workbook>\";\n const string startExcelXML = \"<xml version>\\r\\n<Workbook \" +\n \"xmlns=\\\"urn:schemas-microsoft-com:office:spreadsheet\\\"\\r\\n\" +\n \" xmlns:o=\\\"urn:schemas-microsoft-com:office:office\\\"\\r\\n \" +\n \"xmlns:x=\\\"urn:schemas- microsoft-com:office:\" +\n \"excel\\\"\\r\\n xmlns:ss=\\\"urn:schemas-microsoft-com:\" +\n \"office:spreadsheet\\\">\\r\\n <Styles>\\r\\n \" +\n \"<Style ss:ID=\\\"Default\\\" ss:Name=\\\"Normal\\\">\\r\\n \" +\n \"<Alignment ss:Vertical=\\\"Bottom\\\"/>\\r\\n <Borders/>\" +\n \"\\r\\n <Font/>\\r\\n <Interior/>\\r\\n <NumberFormat/>\" +\n \"\\r\\n <Protection/>\\r\\n </Style>\\r\\n \" +\n \"<Style ss:ID=\\\"BoldColumn\\\">\\r\\n <Font \" +\n \"x:Family=\\\"Swiss\\\" ss:Bold=\\\"1\\\"/>\\r\\n </Style>\\r\\n \" +\n \"<Style ss:ID=\\\"StringLiteral\\\">\\r\\n <NumberFormat\" +\n \" ss:Format=\\\"@\\\"/>\\r\\n </Style>\\r\\n <Style \" +\n \"ss:ID=\\\"Decimal\\\">\\r\\n <NumberFormat \" +\n \"ss:Format=\\\"0.0000\\\"/>\\r\\n </Style>\\r\\n \" +\n \"<Style ss:ID=\\\"Integer\\\">\\r\\n <NumberFormat \" +\n \"ss:Format=\\\"0\\\"/>\\r\\n </Style>\\r\\n <Style \" +\n \"ss:ID=\\\"DateLiteral\\\">\\r\\n <NumberFormat \" +\n \"ss:Format=\\\"mm/dd/yyyy;@\\\"/>\\r\\n </Style>\\r\\n \" +\n \"</Styles>\\r\\n \";\n System.IO.StreamWriter excelDoc = null;\n excelDoc = new System.IO.StreamWriter(fileName);\n\n int sheetCount = 1;\n excelDoc.Write(startExcelXML);\n foreach (DataTable table in source.Tables)\n {\n int rowCount = 0;\n excelDoc.Write(\"<Worksheet ss:Name=\\\"\" + table.TableName + \"\\\">\");\n excelDoc.Write(\"<Table>\");\n excelDoc.Write(\"<Row>\");\n for (int x = 0; x < table.Columns.Count; x++)\n {\n excelDoc.Write(\"<Cell ss:StyleID=\\\"BoldColumn\\\"><Data ss:Type=\\\"String\\\">\");\n excelDoc.Write(table.Columns[x].ColumnName);\n excelDoc.Write(\"</Data></Cell>\");\n }\n excelDoc.Write(\"</Row>\");\n foreach (DataRow x in table.Rows)\n {\n rowCount++;\n //if the number of rows is > 64000 create a new page to continue output\n if (rowCount == 64000)\n {\n rowCount = 0;\n sheetCount++;\n excelDoc.Write(\"</Table>\");\n excelDoc.Write(\" </Worksheet>\");\n excelDoc.Write(\"<Worksheet ss:Name=\\\"\" + table.TableName + \"\\\">\");\n excelDoc.Write(\"<Table>\");\n }\n excelDoc.Write(\"<Row>\"); //ID=\" + rowCount + \"\n for (int y = 0; y < table.Columns.Count; y++)\n {\n System.Type rowType;\n rowType = x[y].GetType();\n switch (rowType.ToString())\n {\n case \"System.String\":\n string XMLstring = x[y].ToString();\n XMLstring = XMLstring.Trim();\n XMLstring = XMLstring.Replace(\"&\", \"&\");\n XMLstring = XMLstring.Replace(\">\", \">\");\n XMLstring = XMLstring.Replace(\"<\", \"<\");\n excelDoc.Write(\"<Cell ss:StyleID=\\\"StringLiteral\\\">\" +\n \"<Data ss:Type=\\\"String\\\">\");\n excelDoc.Write(XMLstring);\n excelDoc.Write(\"</Data></Cell>\");\n break;\n case \"System.DateTime\":\n //Excel has a specific Date Format of YYYY-MM-DD followed by \n //the letter 'T' then hh:mm:sss.lll Example 2005-01-31T24:01:21.000\n //The Following Code puts the date stored in XMLDate \n //to the format above\n DateTime XMLDate = (DateTime)x[y];\n string XMLDatetoString = \"\"; //Excel Converted Date\n XMLDatetoString = XMLDate.Year.ToString() +\n \"-\" +\n (XMLDate.Month < 10 ? \"0\" +\n XMLDate.Month.ToString() : XMLDate.Month.ToString()) +\n \"-\" +\n (XMLDate.Day < 10 ? \"0\" +\n XMLDate.Day.ToString() : XMLDate.Day.ToString()) +\n \"T\" +\n (XMLDate.Hour < 10 ? \"0\" +\n XMLDate.Hour.ToString() : XMLDate.Hour.ToString()) +\n \":\" +\n (XMLDate.Minute < 10 ? \"0\" +\n XMLDate.Minute.ToString() : XMLDate.Minute.ToString()) +\n \":\" +\n (XMLDate.Second < 10 ? \"0\" +\n XMLDate.Second.ToString() : XMLDate.Second.ToString()) +\n \".000\";\n excelDoc.Write(\"<Cell ss:StyleID=\\\"DateLiteral\\\">\" +\n \"<Data ss:Type=\\\"DateTime\\\">\");\n excelDoc.Write(XMLDatetoString);\n excelDoc.Write(\"</Data></Cell>\");\n break;\n case \"System.Boolean\":\n excelDoc.Write(\"<Cell ss:StyleID=\\\"StringLiteral\\\">\" +\n \"<Data ss:Type=\\\"String\\\">\");\n excelDoc.Write(x[y].ToString());\n excelDoc.Write(\"</Data></Cell>\");\n break;\n case \"System.Int16\":\n case \"System.Int32\":\n case \"System.Int64\":\n case \"System.Byte\":\n excelDoc.Write(\"<Cell ss:StyleID=\\\"Integer\\\">\" +\n \"<Data ss:Type=\\\"Number\\\">\");\n excelDoc.Write(x[y].ToString());\n excelDoc.Write(\"</Data></Cell>\");\n break;\n case \"System.Decimal\":\n case \"System.Double\":\n excelDoc.Write(\"<Cell ss:StyleID=\\\"Decimal\\\">\" +\n \"<Data ss:Type=\\\"Number\\\">\");\n excelDoc.Write(x[y].ToString());\n excelDoc.Write(\"</Data></Cell>\");\n break;\n case \"System.DBNull\":\n excelDoc.Write(\"<Cell ss:StyleID=\\\"StringLiteral\\\">\" +\n \"<Data ss:Type=\\\"String\\\">\");\n excelDoc.Write(\"\");\n excelDoc.Write(\"</Data></Cell>\");\n break;\n default:\n throw (new Exception(rowType.ToString() + \" not handled.\"));\n }\n }\n excelDoc.Write(\"</Row>\");\n }\n excelDoc.Write(\"</Table>\");\n excelDoc.Write(\" </Worksheet>\");\n sheetCount++;\n }\n\n\n excelDoc.Write(endExcelXML);\n excelDoc.Close();\n }\n</code></pre>\n"
},
{
"answer_id": 34043997,
"author": "Sachin Dhir",
"author_id": 1884669,
"author_profile": "https://Stackoverflow.com/users/1884669",
"pm_score": 4,
"selected": false,
"text": "<p>OpenXML is also a good alternative that helps avoid installing MS Excel on Server.The Open XML SDK 2.0 provided by Microsoft simplifies the task of manipulating Open XML packages and the underlying Open XML schema elements within a package. The Open XML Application Programming Interface (API) encapsulates many common tasks that developers perform on Open XML packages.</p>\n\n<p>Check this out <a href=\"http://technowide.net/2015/11/03/openxml-alternative-helps-avoid-ms-excel-server/\" rel=\"noreferrer\">OpenXML: Alternative that helps avoid installing MS Excel on Server</a></p>\n"
},
{
"answer_id": 39923371,
"author": "Davis Jebaraj",
"author_id": 1628533,
"author_profile": "https://Stackoverflow.com/users/1628533",
"pm_score": 5,
"selected": false,
"text": "<p><a href=\"https://www.syncfusion.com/products/file-formats/xlsio\" rel=\"noreferrer\">Syncfusion Essential XlsIO</a> can do this. It has no dependency on Microsoft office and also has specific support for different platforms.</p>\n\n<ul>\n<li><a href=\"https://help.syncfusion.com/file-formats/xlsio/asp-net\" rel=\"noreferrer\">ASP.NET</a></li>\n<li><a href=\"https://help.syncfusion.com/file-formats/xlsio/asp-net-mvc\" rel=\"noreferrer\">ASP.NET MVC</a></li>\n<li><a href=\"https://help.syncfusion.com/file-formats/xlsio/uwp\" rel=\"noreferrer\">UWP</a></li>\n<li><a href=\"https://help.syncfusion.com/file-formats/xlsio/xamarin\" rel=\"noreferrer\">Xamarin</a></li>\n<li>WPF and Windows Forms</li>\n<li>Windows Service and batch based operations</li>\n</ul>\n\n<p>Code sample:</p>\n\n<pre><code>//Creates a new instance for ExcelEngine.\nExcelEngine excelEngine = new ExcelEngine();\n//Loads or open an existing workbook through Open method of IWorkbooks\nIWorkbook workbook = excelEngine.Excel.Workbooks.Open(fileName);\n//To-Do some manipulation|\n//To-Do some manipulation\n//Set the version of the workbook.\nworkbook.Version = ExcelVersion.Excel2013;\n//Save the workbook in file system as xlsx format\nworkbook.SaveAs(outputFileName);\n</code></pre>\n\n<p>The whole suite of controls is available for free through the <a href=\"https://www.syncfusion.com/products/communitylicense\" rel=\"noreferrer\">community license</a> program if you qualify (less than 1 million USD in revenue). Note: I work for Syncfusion.</p>\n"
},
{
"answer_id": 42497697,
"author": "Taterhead",
"author_id": 819019,
"author_profile": "https://Stackoverflow.com/users/819019",
"pm_score": 4,
"selected": false,
"text": "<p>The simplest and fastest way to create an Excel file from C# is to use the Open XML Productivity Tool. The Open XML Productivity Tool comes with the Open XML SDK installation. The tool reverse engineers any Excel file into C# code. The C# code can then be used to re-generate that file.</p>\n\n<p>An overview of the process involved is:</p>\n\n<ol>\n<li>Install the Open XML SDK with the tool.</li>\n<li>Create an Excel file using the latest Excel client with desired look. Name it <code>DesiredLook.xlsx</code>.</li>\n<li>With the tool open <code>DesiredLook.xlsx</code> and click the Reflect Code button near the top.\n<a href=\"https://i.stack.imgur.com/gB30w.png\" rel=\"noreferrer\"><img src=\"https://i.stack.imgur.com/gB30w.png\" alt=\"enter image description here\"></a> </li>\n<li>The C# code for your file will be generated in the right pane of the tool. Add this to your C# solution and generate files with that desired look.</li>\n</ol>\n\n<p>As a bonus, this method works for any Word and PowerPoint files. As the C# developer, you will then make changes to the code to fit your needs.</p>\n\n<p>I have developed a <a href=\"https://github.com/thomasbtatum/GenerateAnyExcelFileWithCSharp\" rel=\"noreferrer\">simple WPF app on github</a> which will run on Windows for this purpose. There is a placeholder class called <code>GeneratedClass</code> where you can paste the generated code. If you go back one version of the file, it will generate an excel file like this:</p>\n\n<p><a href=\"https://github.com/thomasbtatum/GenerateAnyExcelFileWithCSharp\" rel=\"noreferrer\"><img src=\"https://i.stack.imgur.com/w7Pcg.png\" alt=\"enter image description here\"></a></p>\n"
},
{
"answer_id": 43226517,
"author": "Gayan Chinthaka Dharmarathna",
"author_id": 6863414,
"author_profile": "https://Stackoverflow.com/users/6863414",
"pm_score": 1,
"selected": false,
"text": "<p>If you make data table or datagridview from the code you can save all data using this simple method.this method not recomended but its working 100%, even you are not install MS Excel in your computer.</p>\n\n<pre><code>try\n {\n SaveFileDialog saveFileDialog1 = new SaveFileDialog();\n saveFileDialog1.Filter = \"Excel Documents (*.xls)|*.xls\";\n saveFileDialog1.FileName = \"Employee Details.xls\";\n if (saveFileDialog1.ShowDialog() == DialogResult.OK)\n {\n string fname = saveFileDialog1.FileName;\n StreamWriter wr = new StreamWriter(fname);\n for (int i = 0; i <DataTable.Columns.Count; i++)\n {\n wr.Write(DataTable.Columns[i].ToString().ToUpper() + \"\\t\");\n }\n wr.WriteLine();\n\n //write rows to excel file\n for (int i = 0; i < (DataTable.Rows.Count); i++)\n {\n for (int j = 0; j < DataTable.Columns.Count; j++)\n {\n if (DataTable.Rows[i][j] != null)\n {\n wr.Write(Convert.ToString(getallData.Rows[i][j]) + \"\\t\");\n }\n else\n {\n wr.Write(\"\\t\");\n }\n }\n //go to next line\n wr.WriteLine();\n }\n //close file\n wr.Close();\n }\n }\n catch (Exception)\n {\n MessageBox.Show(\"Error Create Excel Sheet!\");\n }\n</code></pre>\n"
},
{
"answer_id": 46451589,
"author": "Vladimir Venegas",
"author_id": 4216714,
"author_profile": "https://Stackoverflow.com/users/4216714",
"pm_score": 1,
"selected": false,
"text": "<p>Some time ago, I created a DLL on top of NPOI. It's very simple to use it:</p>\n\n<pre><code>IList<DummyPerson> dummyPeople = new List<DummyPerson>();\n//Add data to dummyPeople...\nIExportEngine engine = new ExcelExportEngine();\nengine.AddData(dummyPeople); \nMemoryStream memory = engine.Export();\n</code></pre>\n\n<p>You could read more about it on <a href=\"https://github.com/vvenegasv/exportable\" rel=\"nofollow noreferrer\">here</a>. </p>\n\n<p>By the way, is 100% open source. Feel free to use, edit and share ;)</p>\n"
},
{
"answer_id": 47703396,
"author": "AlexDev",
"author_id": 733760,
"author_profile": "https://Stackoverflow.com/users/733760",
"pm_score": 3,
"selected": false,
"text": "<p>One really easy option which is often overlooked is to create a .rdlc report using <a href=\"https://msdn.microsoft.com/en-us/library/bb885185.aspx?f=255&MSPPError=-2147217396\" rel=\"noreferrer\">Microsoft Reporting</a> and export it to excel format. You can design it in visual studio and generate the file using: </p>\n\n<pre><code>localReport.Render(\"EXCELOPENXML\", null, ((name, ext, encoding, mimeType, willSeek) => stream = new FileStream(name, FileMode.CreateNew)), out warnings);\n</code></pre>\n\n<p>You can also export it do .doc or .pdf, using <code>\"WORDOPENXML\"</code> and <code>\"PDF\"</code> respectively, and it's supported on many different platforms such as ASP.NET and SSRS.</p>\n\n<p>It's much easier to make changes in a visual designer where you can see the results, and trust me, once you start grouping data, formatting group headers, adding new sections, you don't want to mess with dozens of XML nodes.</p>\n"
},
{
"answer_id": 53150223,
"author": "Vijay Dodamani",
"author_id": 3433702,
"author_profile": "https://Stackoverflow.com/users/3433702",
"pm_score": 1,
"selected": false,
"text": "<p>To save xls into xlsx format, we just need to call <code>SaveAs</code> method from <code>Microsoft.Office.Interop.Excel</code> library. This method will take around 16 parameters and one of them is file format as well.</p>\n\n<p>Microsoft document: Here \n<a href=\"https://learn.microsoft.com/en-us/dotnet/api/microsoft.office.interop.excel._workbook.saveas?view=excel-pia\" rel=\"nofollow noreferrer\">SaveAs Method Arguments</a></p>\n\n<p>The object we need to pass is like </p>\n\n<pre><code>wb.SaveAs(filename, 51, System.Reflection.Missing.Value,\nSystem.Reflection.Missing.Value, false, false, 1,1, true, \nSystem.Reflection.Missing.Value, System.Reflection.Missing.Value, System.Reflection.Missing.Value)\n</code></pre>\n\n<p>Here, 51 is is enumeration value for XLSX</p>\n\n<p>For SaveAs in different file formats you can refer the <a href=\"https://learn.microsoft.com/en-us/dotnet/api/microsoft.office.interop.excel.xlfileformat?view=excel-pia\" rel=\"nofollow noreferrer\">xlFileFormat</a></p>\n"
},
{
"answer_id": 54033422,
"author": "Shubham",
"author_id": 8743724,
"author_profile": "https://Stackoverflow.com/users/8743724",
"pm_score": -1,
"selected": false,
"text": "<p>check this out no need for third party libraries you can simply export datatable data to excel file using this</p>\n\n<pre><code>var dt = \"your code for getting data into datatable\";\n Response.ClearContent();\n Response.AddHeader(\"content-disposition\", string.Format(\"attachment;filename={0}.xls\", DateTime.Now.ToString(\"yyyy-MM-dd\")));\n Response.ContentType = \"application/vnd.ms-excel\";\n string tab = \"\";\n foreach (DataColumn dataColumn in dt.Columns)\n {\n Response.Write(tab + dataColumn.ColumnName);\n tab = \"\\t\";\n }\n Response.Write(\"\\n\");\n int i;\n foreach (DataRow dataRow in dt.Rows)\n {\n tab = \"\";\n for (i = 0; i < dt.Columns.Count; i++)\n {\n Response.Write(tab + dataRow[i].ToString());\n tab = \"\\t\";\n }\n Response.Write(\"\\n\");\n }\n Response.End();\n</code></pre>\n"
},
{
"answer_id": 59203370,
"author": "Michael Mainer",
"author_id": 2917277,
"author_profile": "https://Stackoverflow.com/users/2917277",
"pm_score": 2,
"selected": false,
"text": "<h2>How to create an Excel (.xslx) file using C# on OneDrive without installing Microsoft Office</h2>\n\n<p>The <a href=\"https://developer.microsoft.com/en-us/graph\" rel=\"nofollow noreferrer\">Microsoft Graph API</a> provides File and Excel APIs for creating and modifying Excel files stored in OneDrive for both enterprise and consumer accounts. The <a href=\"https://www.nuget.org/packages/Microsoft.Graph\" rel=\"nofollow noreferrer\">Microsoft.Graph</a> NuGet package provides many interfaces for working with the File and Excel APIs.</p>\n\n<pre class=\"lang-cs prettyprint-override\"><code>{\n Name = \"myExcelFile.xslx\",\n File = new Microsoft.Graph.File()\n};\n\n// Create an empty file in the user's OneDrive.\nvar excelWorkbookDriveItem = await graphClient.Me.Drive.Root.Children.Request().AddAsync(excelWorkbook);\n\n// Add the contents of a template Excel file.\nDriveItem excelDriveItem;\nusing (Stream ms = ResourceHelper.GetResourceAsStream(ResourceHelper.ExcelTestResource))\n{\n //Upload content to the file. ExcelTestResource is an empty template Excel file.\n //https://graph.microsoft.io/en-us/docs/api-reference/v1.0/api/item_uploadcontent\n excelDriveItem = await graphClient.Me.Drive.Items[excelWorkbookDriveItem.Id].Content.Request().PutAsync<DriveItem>(ms);\n}\n\n</code></pre>\n\n<p>At this point, you now have an Excel file created in the user (enterprise or consumer) or group's OneDrive. You can now use the <a href=\"https://learn.microsoft.com/en-us/graph/api/resources/excel?view=graph-rest-1.0\" rel=\"nofollow noreferrer\">Excel APIs</a> to <strong>make changes to the Excel file without using Excel and without needing to understand the Excel XML format</strong>.</p>\n"
},
{
"answer_id": 59430197,
"author": "Roman.Pavelko",
"author_id": 1847554,
"author_profile": "https://Stackoverflow.com/users/1847554",
"pm_score": 3,
"selected": false,
"text": "<p>You can try my <a href=\"https://github.com/RomanPavelko/SwiftExcel\" rel=\"noreferrer\">SwiftExcel</a> library. This library writes directly to the file, so it is very efficient. For example you can write 100k rows in few seconds without any memory usage.</p>\n\n<p>Here is a simple example of usage:</p>\n\n<pre><code>using (var ew = new ExcelWriter(\"C:\\\\temp\\\\test.xlsx\"))\n{\n for (var row = 1; row <= 10; row++)\n {\n for (var col = 1; col <= 5; col++)\n {\n ew.Write($\"row:{row}-col:{col}\", col, row);\n }\n }\n}\n</code></pre>\n"
},
{
"answer_id": 62656775,
"author": "Miguel Tomás",
"author_id": 13794189,
"author_profile": "https://Stackoverflow.com/users/13794189",
"pm_score": 2,
"selected": false,
"text": "<p>You can install OpenXml nuget package on Visual Studio.\nHere is a bit of code to export a data table to an excel file:</p>\n<pre><code>Imports DocumentFormat.OpenXml\nImports DocumentFormat.OpenXml.Packaging\nImports DocumentFormat.OpenXml.Spreadsheet\n\nPublic Class ExportExcelClass\n Public Sub New()\n\n End Sub\n\n Public Sub ExportDataTable(ByVal table As DataTable, ByVal exportFile As String)\n ' Create a spreadsheet document by supplying the filepath.\n ' By default, AutoSave = true, Editable = true, and Type = xlsx.\n Dim spreadsheetDocument As SpreadsheetDocument = spreadsheetDocument.Create(exportFile, SpreadsheetDocumentType.Workbook)\n\n ' Add a WorkbookPart to the document.\n Dim workbook As WorkbookPart = spreadsheetDocument.AddWorkbookPart\n workbook.Workbook = New Workbook\n\n ' Add a WorksheetPart to the WorkbookPart.\n Dim Worksheet As WorksheetPart = workbook.AddNewPart(Of WorksheetPart)()\n Worksheet.Worksheet = New Worksheet(New SheetData())\n\n ' Add Sheets to the Workbook.\n Dim sheets As Sheets = spreadsheetDocument.WorkbookPart.Workbook.AppendChild(Of Sheets)(New Sheets())\n\n Dim data As SheetData = Worksheet.Worksheet.GetFirstChild(Of SheetData)()\n Dim Header As Row = New Row()\n Header.RowIndex = CType(1, UInt32)\n\n For Each column As DataColumn In table.Columns\n Dim headerCell As Cell = createTextCell(table.Columns.IndexOf(column) + 1, 1, column.ColumnName)\n Header.AppendChild(headerCell)\n Next\n\n data.AppendChild(Header)\n\n Dim contentRow As DataRow\n For i As Integer = 0 To table.Rows.Count - 1\n contentRow = table.Rows(i)\n data.AppendChild(createContentRow(contentRow, i + 2))\n Next\n\n End Sub\n\n Private Function createTextCell(ByVal columnIndex As Integer, ByVal rowIndex As Integer, ByVal cellValue As Object) As Cell\n Dim cell As Cell = New Cell()\n cell.DataType = CellValues.InlineString\n\n cell.CellReference = getColumnName(columnIndex) + rowIndex.ToString\n\n Dim inlineString As InlineString = New InlineString()\n Dim t As Text = New Text()\n t.Text = cellValue.ToString()\n inlineString.AppendChild(t)\n cell.AppendChild(inlineString)\n Return cell\n End Function\n\n Private Function createContentRow(ByVal dataRow As DataRow, ByVal rowIndex As Integer) As Row\n Dim row As Row = New Row With {\n .rowIndex = CType(rowIndex, UInt32)\n }\n\n For i As Integer = 0 To dataRow.Table.Columns.Count - 1\n Dim dataCell As Cell = createTextCell(i + 1, rowIndex, dataRow(i))\n row.AppendChild(dataCell)\n Next\n\n Return row\n End Function\n\n Private Function getColumnName(ByVal columnIndex As Integer) As String\n Dim dividend As Integer = columnIndex\n Dim columnName As String = String.Empty\n Dim modifier As Integer\n\n While dividend > 0\n modifier = (dividend - 1) Mod 26\n columnName = Convert.ToChar(65 + modifier).ToString() & columnName\n dividend = CInt(((dividend - modifier) / 26))\n End While\n\n Return columnName\n End Function\nEnd Class\n</code></pre>\n"
},
{
"answer_id": 64846374,
"author": "Klaus Oberdalhoff",
"author_id": 2785361,
"author_profile": "https://Stackoverflow.com/users/2785361",
"pm_score": 1,
"selected": false,
"text": "<p>I wonder why nobody suggested PowerShell with the free ImportExcel Module; it creates XML-Excel files (xlsx) with ease.</p>\n<p>Especially easy when creating Excel-sheets coming from Databases like SQL Server...</p>\n"
},
{
"answer_id": 65206374,
"author": "Mauricio Kenny",
"author_id": 6227493,
"author_profile": "https://Stackoverflow.com/users/6227493",
"pm_score": 2,
"selected": false,
"text": "<p>I recode again the code and now you can create an .xls file, later you can convert to Excel 2003 Open XML Format.</p>\n<pre><code>private static void exportToExcel(DataSet source, string fileName)\n {\n // Documentacion en:\n // https://en.wikipedia.org/wiki/Microsoft_Office_XML_formats\n // https://answers.microsoft.com/en-us/msoffice/forum/all/how-to-save-office-ms-xml-as-xlsx-file/4a77dae5-6855-457d-8359-e7b537beb1db\n // https://riptutorial.com/es/openxml\n\n const string startExcelXML = "<?xml version=\\"1.0\\" encoding=\\"UTF-8\\"?>\\r\\n"+\n "<?mso-application progid=\\"Excel.Sheet\\"?>\\r\\n" +\n "<Workbook xmlns=\\"urn:schemas-microsoft-com:office:spreadsheet\\"\\r\\n" +\n "xmlns:o=\\"urn:schemas-microsoft-com:office:office\\"\\r\\n " +\n "xmlns:x=\\"urn:schemas-microsoft-com:office:excel\\"\\r\\n " +\n "xmlns:ss=\\"urn:schemas-microsoft-com:office:spreadsheet\\"\\r\\n " +\n "xmlns:html=\\"http://www.w3.org/TR/REC-html40\\">\\r\\n " +\n "xmlns:html=\\"https://www.w3.org/TR/html401/\\">\\r\\n " +\n\n "<DocumentProperties xmlns=\\"urn:schemas-microsoft-com:office:office\\">\\r\\n " +\n " <Version>16.00</Version>\\r\\n " +\n "</DocumentProperties>\\r\\n " +\n " <OfficeDocumentSettings xmlns=\\"urn:schemas-microsoft-com:office:office\\">\\r\\n " +\n " <AllowPNG/>\\r\\n " +\n " </OfficeDocumentSettings>\\r\\n " +\n\n " <ExcelWorkbook xmlns=\\"urn:schemas-microsoft-com:office:excel\\">\\r\\n " +\n " <WindowHeight>9750</WindowHeight>\\r\\n " +\n " <WindowWidth>24000</WindowWidth>\\r\\n " +\n " <WindowTopX>0</WindowTopX>\\r\\n " +\n " <WindowTopY>0</WindowTopY>\\r\\n " +\n " <RefModeR1C1/>\\r\\n " +\n " <ProtectStructure>False</ProtectStructure>\\r\\n " +\n " <ProtectWindows>False</ProtectWindows>\\r\\n " +\n " </ExcelWorkbook>\\r\\n " +\n\n "<Styles>\\r\\n " +\n "<Style ss:ID=\\"Default\\" ss:Name=\\"Normal\\">\\r\\n " +\n "<Alignment ss:Vertical=\\"Bottom\\"/>\\r\\n <Borders/>" +\n "\\r\\n <Font/>\\r\\n <Interior/>\\r\\n <NumberFormat/>" +\n "\\r\\n <Protection/>\\r\\n </Style>\\r\\n " +\n "<Style ss:ID=\\"BoldColumn\\">\\r\\n <Font " +\n "x:Family=\\"Swiss\\" ss:Bold=\\"1\\"/>\\r\\n </Style>\\r\\n " +\n "<Style ss:ID=\\"StringLiteral\\">\\r\\n <NumberFormat" +\n " ss:Format=\\"@\\"/>\\r\\n </Style>\\r\\n <Style " +\n "ss:ID=\\"Decimal\\">\\r\\n <NumberFormat " +\n "ss:Format=\\"0.0000\\"/>\\r\\n </Style>\\r\\n " +\n "<Style ss:ID=\\"Integer\\">\\r\\n <NumberFormat/>" +\n "ss:Format=\\"0\\"/>\\r\\n </Style>\\r\\n <Style " +\n "ss:ID=\\"DateLiteral\\">\\r\\n <NumberFormat " +\n "ss:Format=\\"dd/mm/yyyy;@\\"/>\\r\\n </Style>\\r\\n " +\n "</Styles>\\r\\n ";\n System.IO.StreamWriter excelDoc = null;\n excelDoc = new System.IO.StreamWriter(fileName,false);\n\n int sheetCount = 1;\n excelDoc.Write(startExcelXML);\n foreach (DataTable table in source.Tables)\n {\n int rowCount = 0;\n excelDoc.Write("<Worksheet ss:Name=\\"" + table.TableName + "\\">");\n excelDoc.Write("<Table>");\n excelDoc.Write("<Row>");\n for (int x = 0; x < table.Columns.Count; x++)\n {\n excelDoc.Write("<Cell ss:StyleID=\\"BoldColumn\\"><Data ss:Type=\\"String\\">");\n excelDoc.Write(table.Columns[x].ColumnName);\n excelDoc.Write("</Data></Cell>");\n }\n excelDoc.Write("</Row>");\n foreach (DataRow x in table.Rows)\n {\n rowCount++;\n //if the number of rows is > 64000 create a new page to continue output\n if (rowCount == 1048576)\n {\n rowCount = 0;\n sheetCount++;\n excelDoc.Write("</Table>");\n excelDoc.Write(" </Worksheet>");\n excelDoc.Write("<Worksheet ss:Name=\\"" + table.TableName + "\\">");\n excelDoc.Write("<Table>");\n }\n excelDoc.Write("<Row>"); //ID=" + rowCount + "\n for (int y = 0; y < table.Columns.Count; y++)\n {\n System.Type rowType;\n rowType = x[y].GetType();\n switch (rowType.ToString())\n {\n case "System.String":\n string XMLstring = x[y].ToString();\n XMLstring = XMLstring.Trim();\n XMLstring = XMLstring.Replace("&", "&");\n XMLstring = XMLstring.Replace(">", ">");\n XMLstring = XMLstring.Replace("<", "<");\n excelDoc.Write("<Cell ss:StyleID=\\"StringLiteral\\">" +\n "<Data ss:Type=\\"String\\">");\n excelDoc.Write(XMLstring);\n excelDoc.Write("</Data></Cell>");\n break;\n case "System.DateTime":\n //Excel has a specific Date Format of YYYY-MM-DD followed by \n //the letter 'T' then hh:mm:sss.lll Example 2005-01-31T24:01:21.000\n //The Following Code puts the date stored in XMLDate \n //to the format above\n DateTime XMLDate = (DateTime)x[y];\n string XMLDatetoString = ""; //Excel Converted Date\n XMLDatetoString = XMLDate.Year.ToString() +\n "-" +\n (XMLDate.Month < 10 ? "0" +\n XMLDate.Month.ToString() : XMLDate.Month.ToString()) +\n "-" +\n (XMLDate.Day < 10 ? "0" +\n XMLDate.Day.ToString() : XMLDate.Day.ToString()) +\n "T" +\n (XMLDate.Hour < 10 ? "0" +\n XMLDate.Hour.ToString() : XMLDate.Hour.ToString()) +\n ":" +\n (XMLDate.Minute < 10 ? "0" +\n XMLDate.Minute.ToString() : XMLDate.Minute.ToString()) +\n ":" +\n (XMLDate.Second < 10 ? "0" +\n XMLDate.Second.ToString() : XMLDate.Second.ToString()) +\n ".000";\n excelDoc.Write("<Cell ss:StyleID=\\"DateLiteral\\">" +\n "<Data ss:Type=\\"DateTime\\">");\n excelDoc.Write(XMLDatetoString);\n excelDoc.Write("</Data></Cell>");\n break;\n case "System.Boolean":\n excelDoc.Write("<Cell ss:StyleID=\\"StringLiteral\\">" +\n "<Data ss:Type=\\"String\\">");\n excelDoc.Write(x[y].ToString());\n excelDoc.Write("</Data></Cell>");\n break;\n case "System.Int16":\n case "System.Int32":\n case "System.Int64":\n case "System.Byte":\n excelDoc.Write("<Cell ss:StyleID=\\"Integer\\">" +\n "<Data ss:Type=\\"Number\\">");\n excelDoc.Write(x[y].ToString());\n excelDoc.Write("</Data></Cell>");\n break;\n case "System.Decimal":\n case "System.Double":\n excelDoc.Write("<Cell ss:StyleID=\\"Decimal\\">" +\n "<Data ss:Type=\\"Number\\">");\n excelDoc.Write(x[y].ToString());\n excelDoc.Write("</Data></Cell>");\n break;\n case "System.DBNull":\n excelDoc.Write("<Cell ss:StyleID=\\"StringLiteral\\">" +\n "<Data ss:Type=\\"String\\">");\n excelDoc.Write("");\n excelDoc.Write("</Data></Cell>");\n break;\n default:\n throw (new Exception(rowType.ToString() + " not handled."));\n }\n }\n excelDoc.Write("</Row>");\n }\n excelDoc.Write("</Table>");\n excelDoc.Write("</Worksheet>"); \n sheetCount++;\n }\n\n const string endExcelOptions1 = "\\r\\n<WorksheetOptions xmlns=\\"urn:schemas-microsoft-com:office:excel\\">\\r\\n" +\n "<Selected/>\\r\\n" +\n "<ProtectObjects>False</ProtectObjects>\\r\\n" +\n "<ProtectScenarios>False</ProtectScenarios>\\r\\n" +\n "</WorksheetOptions>\\r\\n";\n\n excelDoc.Write(endExcelOptions1);\n excelDoc.Write("</Workbook>");\n excelDoc.Close();\n }\n</code></pre>\n"
},
{
"answer_id": 69366171,
"author": "toha",
"author_id": 1084742,
"author_profile": "https://Stackoverflow.com/users/1084742",
"pm_score": 0,
"selected": false,
"text": "<p>In my projects, I use some several .net libraries to extract Excel File (both .xls and .xlsx)</p>\n<p>To Export data, I frequently use <a href=\"https://www.aspsnippets.com/Articles/Export-RDLC-Report-to-Excel-programmatically-in-ASPNet.aspx\" rel=\"nofollow noreferrer\">rdlc</a>.</p>\n<p>To modify excel files I use (Sample code when I try to set blank Cell A15):</p>\n<p><a href=\"https://www.nuget.org/packages/ClosedXML/\" rel=\"nofollow noreferrer\">ClosedXML</a></p>\n<pre><code> //Closed XML\n var workbook = new XLWorkbook(sUrlFile); // load the existing excel file\n var worksheet = workbook.Worksheets.Worksheet(1);\n worksheet.Cell("A15").SetValue("");\n workbook.Save();\n</code></pre>\n<p><a href=\"https://www.nuget.org/packages/IronXL.Excel\" rel=\"nofollow noreferrer\">IronXL</a></p>\n<pre><code> string sUrlFile = "G:\\\\ReportAmortizedDetail.xls";\n WorkBook workbook = WorkBook.Load(sUrlFile);\n WorkSheet sheet = workbook.WorkSheets.First();\n //Select cells easily in Excel notation and return the calculated value\n sheet["A15"].First().Value = "";\n sheet["A15"].First().FormatString = "";\n\n workbook.Save();\n workbook.Close();\n workbook = null;\n</code></pre>\n<p><a href=\"https://www.e-iceblue.com/Tutorials/Spire.XLS/Getting-started/Spire.XLS-Quick-Start.html\" rel=\"nofollow noreferrer\">SpireXLS</a> (When I try, the library print additional sheet to give information that we use the trial library</p>\n<pre><code> string sUrlFile = "G:\\\\ReportAmortizedDetail.xls";\n Workbook workbook = new Workbook();\n workbook.LoadFromFile(sUrlFile);\n //Get the 1st sheet\n Worksheet sheet = workbook.Worksheets[0];\n //Specify the cell range\n CellRange range = sheet.Range["A15"];\n //Find all matched text in the range\n CellRange[] cells = range.FindAllString("hi", false, false);\n //Replace text\n foreach (CellRange cell in range)\n {\n cell.Text = "";\n }\n //Save\n workbook.Save();\n</code></pre>\n<p><strong>Jet Oledb</strong></p>\n<pre><code> //ExcelTool Class\n public static int ExcelUpdateSheets(string path, string sWorksheetName, string sCellLocation, string sValue)\n {\n int iResult = -99;\n String sConnectionString = @"Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + path + ";Extended Properties='Excel 8.0;HDR=NO'";\n OleDbConnection objConn = new OleDbConnection(sConnectionString);\n objConn.Open();\n OleDbCommand objCmdSelect = new OleDbCommand("UPDATE [" + sWorksheetName + "$" + sCellLocation + "] SET F1=" + UtilityClass.ValueSQL(sValue), objConn);\n objCmdSelect.ExecuteNonQuery();\n objConn.Close();\n\n return iResult;\n }\n</code></pre>\n<p>Usage :</p>\n<pre><code> ExcelTool.ExcelUpdateSheets(sUrlFile, "ReportAmortizedDetail", "A15:A15", "");\n</code></pre>\n<p><strong>Aspose</strong></p>\n<pre><code> var workbook = new Aspose.Cells.Workbook(sUrlFile);\n // access first (default) worksheet\n var sheet = workbook.Worksheets[0];\n // access CellsCollection of first worksheet\n var cells = sheet.Cells;\n // write HelloWorld to cells A1\n cells["A15"].Value = "";\n // save spreadsheet to disc\n workbook.Save(sUrlFile);\n workbook.Dispose();\n workbook = null;\n</code></pre>\n"
},
{
"answer_id": 69945347,
"author": "user10186832",
"author_id": 10186832,
"author_profile": "https://Stackoverflow.com/users/10186832",
"pm_score": 1,
"selected": false,
"text": "<p>Here is the simplest way to create an Excel file.</p>\n<p>Excel files with extension .xlsx are compressed folders containing .XML files - but complicated.</p>\n<p>First create the folder structure as follows -</p>\n<pre><code>public class CreateFileOrFolder\n{\n static void Main()\n {\n //\n // https://learn.microsoft.com/en-us/dotnet/csharp/programming-guide/file-system/how-to-create-a-file-or-folder\n //\n // https://learn.microsoft.com/en-us/dotnet/csharp/programming-guide/file-system/how-to-write-to-a-text-file\n //\n // .NET Framework 4.7.2\n //\n // Specify a name for your top-level folder.\n string folderName = @"C:\\Users\\david\\Desktop\\Book3";\n\n // To create a string that specifies the path to a subfolder under your\n // top-level folder, add a name for the subfolder to folderName.\n\n string pathString = System.IO.Path.Combine(folderName, "_rels");\n System.IO.Directory.CreateDirectory(pathString);\n pathString = System.IO.Path.Combine(folderName, "docProps");\n System.IO.Directory.CreateDirectory(pathString);\n pathString = System.IO.Path.Combine(folderName, "xl");\n System.IO.Directory.CreateDirectory(pathString);\n\n string subPathString = System.IO.Path.Combine(pathString, "_rels");\n System.IO.Directory.CreateDirectory(subPathString);\n subPathString = System.IO.Path.Combine(pathString, "theme");\n System.IO.Directory.CreateDirectory(subPathString);\n subPathString = System.IO.Path.Combine(pathString, "worksheets");\n System.IO.Directory.CreateDirectory(subPathString);\n // Keep the console window open in debug mode.\n System.Console.WriteLine("Press any key to exit.");\n System.Console.ReadKey();\n }\n}\n</code></pre>\n<p>Next, create text files to hold the XML needed to describe the Excel spreadsheet.</p>\n<pre><code>namespace MakeFiles3\n{\n class Program\n {\n static void Main(string[] args)\n {\n //\n // https://learn.microsoft.com/en-us/dotnet/csharp/programming-guide/file-system/how-to-write-to-a-text-file\n //\n // .NET Framework 4.7.2\n //\n string fileName = @"C:\\Users\\david\\Desktop\\Book3\\_rels\\.rels";\n fnWriteFile(fileName);\n fileName = @"C:\\Users\\david\\Desktop\\Book3\\docProps\\app.xml";\n fnWriteFile(fileName);\n fileName = @"C:\\Users\\david\\Desktop\\Book3\\docProps\\core.xml";\n fnWriteFile(fileName);\n fileName = @"C:\\Users\\david\\Desktop\\Book3\\xl\\_rels\\workbook.xml.rels";\n fnWriteFile(fileName);\n fileName = @"C:\\Users\\david\\Desktop\\Book3\\xl\\theme\\theme1.xml";\n fnWriteFile(fileName);\n fileName = @"C:\\Users\\david\\Desktop\\Book3\\xl\\worksheets\\sheet1.xml";\n fnWriteFile(fileName);\n fileName = @"C:\\Users\\david\\Desktop\\Book3\\xl\\styles.xml";\n fnWriteFile(fileName);\n fileName = @"C:\\Users\\david\\Desktop\\Book3\\xl\\workbook.xml";\n fnWriteFile(fileName);\n fileName = @"C:\\Users\\david\\Desktop\\Book3\\[Content_Types].xml";\n fnWriteFile(fileName);\n // Keep the console window open in debug mode.\n System.Console.WriteLine("Press any key to exit.");\n System.Console.ReadKey();\n\n bool fnWriteFile(string strFilePath)\n {\n if (!System.IO.File.Exists(strFilePath))\n {\n using (System.IO.FileStream fs = System.IO.File.Create(strFilePath))\n {\n return true;\n }\n }\n else\n {\n System.Console.WriteLine("File \\"{0}\\" already exists.", strFilePath);\n return false;\n }\n }\n }\n }\n}\n</code></pre>\n<p>Next populate the text files with XML.</p>\n<p>The XML required is fairly verbose so you may need to use this github repository.</p>\n<p><a href=\"https://github.com/DaveTallett26/MakeFiles4/blob/master/MakeFiles4/Program.cs\" rel=\"nofollow noreferrer\">https://github.com/DaveTallett26/MakeFiles4/blob/master/MakeFiles4/Program.cs</a></p>\n<pre><code>//\n// https://learn.microsoft.com/en-us/dotnet/standard/io/how-to-write-text-to-a-file\n// .NET Framework 4.7.2\n//\nusing System.IO;\n\nnamespace MakeFiles4\n{\n class Program\n {\n static void Main(string[] args)\n {\n string xContents = @"a";\n string xFilename = @"a";\n xFilename = @"C:\\Users\\david\\Desktop\\Book3\\[Content_Types].xml";\n xContents = @"<?xml version=""1.0"" encoding=""UTF-8"" standalone=""yes""?><Types xmlns=""http://schemas.openxmlformats.org/package/2006/content-types""><Default Extension=""rels"" ContentType=""application/vnd.openxmlformats-package.relationships+xml""/><Default Extension=""xml"" ContentType=""application/xml""/><Override PartName=""/xl/workbook.xml"" ContentType=""application/vnd.openxmlformats-officedocument.spreadsheetml.sheet.main+xml""/><Override PartName=""/xl/worksheets/sheet1.xml"" ContentType=""application/vnd.openxmlformats-officedocument.spreadsheetml.worksheet+xml""/><Override PartName=""/xl/theme/theme1.xml"" ContentType=""application/vnd.openxmlformats-officedocument.theme+xml""/><Override PartName=""/xl/styles.xml"" ContentType=""application/vnd.openxmlformats-officedocument.spreadsheetml.styles+xml""/><Override PartName=""/docProps/core.xml"" ContentType=""application/vnd.openxmlformats-package.core-properties+xml""/><Override PartName=""/docProps/app.xml"" ContentType=""application/vnd.openxmlformats-officedocument.extended-properties+xml""/></Types>";\n StartExstream(xContents, xFilename);\n\n xFilename = @"C:\\Users\\david\\Desktop\\Book3\\_rels\\.rels";\n xContents = @"<?xml version=""1.0"" encoding=""UTF-8"" standalone=""yes""?><Relationships xmlns=""http://schemas.openxmlformats.org/package/2006/relationships""><Relationship Id=""rId3"" Type=""http://schemas.openxmlformats.org/officeDocument/2006/relationships/extended-properties"" Target=""docProps/app.xml""/><Relationship Id=""rId2"" Type=""http://schemas.openxmlformats.org/package/2006/relationships/metadata/core-properties"" Target=""docProps/core.xml""/><Relationship Id=""rId1"" Type=""http://schemas.openxmlformats.org/officeDocument/2006/relationships/officeDocument"" Target=""xl/workbook.xml""/></Relationships>";\n StartExstream(xContents, xFilename);\n\n xFilename = @"C:\\Users\\david\\Desktop\\Book3\\docProps\\app.xml";\n xContents = @"<?xml version=""1.0"" encoding=""UTF-8"" standalone=""yes""?><Properties xmlns=""http://schemas.openxmlformats.org/officeDocument/2006/extended-properties"" xmlns:vt=""http://schemas.openxmlformats.org/officeDocument/2006/docPropsVTypes""><Application>Microsoft Excel</Application><DocSecurity>0</DocSecurity><ScaleCrop>false</ScaleCrop><HeadingPairs><vt:vector size=""2"" baseType=""variant""><vt:variant><vt:lpstr>Worksheets</vt:lpstr></vt:variant><vt:variant><vt:i4>1</vt:i4></vt:variant></vt:vector></HeadingPairs><TitlesOfParts><vt:vector size=""1"" baseType=""lpstr""><vt:lpstr>Sheet1</vt:lpstr></vt:vector></TitlesOfParts><Company></Company><LinksUpToDate>false</LinksUpToDate><SharedDoc>false</SharedDoc><HyperlinksChanged>false</HyperlinksChanged><AppVersion>16.0300</AppVersion></Properties>";\n StartExstream(xContents, xFilename);\n\n xFilename = @"C:\\Users\\david\\Desktop\\Book3\\docProps\\core.xml";\n xContents = @"<?xml version=""1.0"" encoding=""UTF-8"" standalone=""yes""?><cp:coreProperties xmlns:cp=""http://schemas.openxmlformats.org/package/2006/metadata/core-properties"" xmlns:dc=""http://purl.org/dc/elements/1.1/"" xmlns:dcterms=""http://purl.org/dc/terms/"" xmlns:dcmitype=""http://purl.org/dc/dcmitype/"" xmlns:xsi=""http://www.w3.org/2001/XMLSchema-instance""><dc:creator>David Tallett</dc:creator><cp:lastModifiedBy>David Tallett</cp:lastModifiedBy><dcterms:created xsi:type=""dcterms:W3CDTF"">2021-10-26T15:47:15Z</dcterms:created><dcterms:modified xsi:type=""dcterms:W3CDTF"">2021-10-26T15:47:35Z</dcterms:modified></cp:coreProperties>";\n StartExstream(xContents, xFilename);\n\n xFilename = @"C:\\Users\\david\\Desktop\\Book3\\xl\\styles.xml";\n xContents = @"<?xml version=""1.0"" encoding=""UTF-8"" standalone=""yes""?><styleSheet xmlns=""http://schemas.openxmlformats.org/spreadsheetml/2006/main"" xmlns:mc=""http://schemas.openxmlformats.org/markup-compatibility/2006"" mc:Ignorable=""x14ac x16r2 xr"" xmlns:x14ac=""http://schemas.microsoft.com/office/spreadsheetml/2009/9/ac"" xmlns:x16r2=""http://schemas.microsoft.com/office/spreadsheetml/2015/02/main"" xmlns:xr=""http://schemas.microsoft.com/office/spreadsheetml/2014/revision""><fonts count=""1"" x14ac:knownFonts=""1""><font><sz val=""11""/><color theme=""1""/><name val=""Calibri""/><family val=""2""/><scheme val=""minor""/></font></fonts><fills count=""2""><fill><patternFill patternType=""none""/></fill><fill><patternFill patternType=""gray125""/></fill></fills><borders count=""1""><border><left/><right/><top/><bottom/><diagonal/></border></borders><cellStyleXfs count=""1""><xf numFmtId=""0"" fontId=""0"" fillId=""0"" borderId=""0""/></cellStyleXfs><cellXfs count=""1""><xf numFmtId=""0"" fontId=""0"" fillId=""0"" borderId=""0"" xfId=""0""/></cellXfs><cellStyles count=""1""><cellStyle name=""Normal"" xfId=""0"" builtinId=""0""/></cellStyles><dxfs count=""0""/><tableStyles count=""0"" defaultTableStyle=""TableStyleMedium2"" defaultPivotStyle=""PivotStyleLight16""/><extLst><ext uri=""{EB79DEF2-80B8-43e5-95BD-54CBDDF9020C}"" xmlns:x14=""http://schemas.microsoft.com/office/spreadsheetml/2009/9/main""><x14:slicerStyles defaultSlicerStyle=""SlicerStyleLight1""/></ext><ext uri=""{9260A510-F301-46a8-8635-F512D64BE5F5}"" xmlns:x15=""http://schemas.microsoft.com/office/spreadsheetml/2010/11/main""><x15:timelineStyles defaultTimelineStyle=""TimeSlicerStyleLight1""/></ext></extLst></styleSheet>";\n StartExstream(xContents, xFilename);\n\n xFilename = @"C:\\Users\\david\\Desktop\\Book3\\xl\\workbook.xml";\n xContents = @"<?xml version=""1.0"" encoding=""UTF-8"" standalone=""yes""?><workbook xmlns=""http://schemas.openxmlformats.org/spreadsheetml/2006/main"" xmlns:r=""http://schemas.openxmlformats.org/officeDocument/2006/relationships"" xmlns:mc=""http://schemas.openxmlformats.org/markup-compatibility/2006"" mc:Ignorable=""x15 xr xr6 xr10 xr2"" xmlns:x15=""http://schemas.microsoft.com/office/spreadsheetml/2010/11/main"" xmlns:xr=""http://schemas.microsoft.com/office/spreadsheetml/2014/revision"" xmlns:xr6=""http://schemas.microsoft.com/office/spreadsheetml/2016/revision6"" xmlns:xr10=""http://schemas.microsoft.com/office/spreadsheetml/2016/revision10"" xmlns:xr2=""http://schemas.microsoft.com/office/spreadsheetml/2015/revision2""><fileVersion appName=""xl"" lastEdited=""7"" lowestEdited=""7"" rupBuild=""24430""/><workbookPr defaultThemeVersion=""166925""/><mc:AlternateContent xmlns:mc=""http://schemas.openxmlformats.org/markup-compatibility/2006""><mc:Choice Requires=""x15""><x15ac:absPath url=""C:\\Users\\david\\Desktop\\"" xmlns:x15ac=""http://schemas.microsoft.com/office/spreadsheetml/2010/11/ac""/></mc:Choice></mc:AlternateContent><xr:revisionPtr revIDLastSave=""0"" documentId=""8_{C633700D-2D40-49EE-8C5E-2561E28A6758}"" xr6:coauthVersionLast=""47"" xr6:coauthVersionMax=""47"" xr10:uidLastSave=""{00000000-0000-0000-0000-000000000000}""/><bookViews><workbookView xWindow=""-120"" yWindow=""-120"" windowWidth=""29040"" windowHeight=""15840"" xr2:uid=""{934C5B62-1DC1-4322-BAE8-00D615BD2FB3}""/></bookViews><sheets><sheet name=""Sheet1"" sheetId=""1"" r:id=""rId1""/></sheets><calcPr calcId=""191029""/><extLst><ext uri=""{140A7094-0E35-4892-8432-C4D2E57EDEB5}"" xmlns:x15=""http://schemas.microsoft.com/office/spreadsheetml/2010/11/main""><x15:workbookPr chartTrackingRefBase=""1""/></ext><ext uri=""{B58B0392-4F1F-4190-BB64-5DF3571DCE5F}"" xmlns:xcalcf=""http://schemas.microsoft.com/office/spreadsheetml/2018/calcfeatures""><xcalcf:calcFeatures><xcalcf:feature name=""microsoft.com:RD""/><xcalcf:feature name=""microsoft.com:Single""/><xcalcf:feature name=""microsoft.com:FV""/><xcalcf:feature name=""microsoft.com:CNMTM""/><xcalcf:feature name=""microsoft.com:LET_WF""/></xcalcf:calcFeatures></ext></extLst></workbook>";\n StartExstream(xContents, xFilename);\n\n xFilename = @"C:\\Users\\david\\Desktop\\Book3\\xl\\_rels\\workbook.xml.rels";\n xContents = @"<?xml version=""1.0"" encoding=""UTF-8"" standalone=""yes""?><Relationships xmlns=""http://schemas.openxmlformats.org/package/2006/relationships""><Relationship Id=""rId3"" Type=""http://schemas.openxmlformats.org/officeDocument/2006/relationships/styles"" Target=""styles.xml""/><Relationship Id=""rId2"" Type=""http://schemas.openxmlformats.org/officeDocument/2006/relationships/theme"" Target=""theme/theme1.xml""/><Relationship Id=""rId1"" Type=""http://schemas.openxmlformats.org/officeDocument/2006/relationships/worksheet"" Target=""worksheets/sheet1.xml""/></Relationships>";\n StartExstream(xContents, xFilename);\n\n xFilename = @"C:\\Users\\david\\Desktop\\Book3\\xl\\theme\\theme1.xml";\n xContents = @"<?xml version=""1.0"" encoding=""UTF-8"" standalone=""yes""?><a:theme xmlns:a=""http://schemas.openxmlformats.org/drawingml/2006/main"" name=""Office Theme""><a:themeElements><a:clrScheme name=""Office""><a:dk1><a:sysClr val=""windowText"" lastClr=""000000""/></a:dk1><a:lt1><a:sysClr val=""window"" lastClr=""FFFFFF""/></a:lt1><a:dk2><a:srgbClr val=""44546A""/></a:dk2><a:lt2><a:srgbClr val=""E7E6E6""/></a:lt2><a:accent1><a:srgbClr val=""4472C4""/></a:accent1><a:accent2><a:srgbClr val=""ED7D31""/></a:accent2><a:accent3><a:srgbClr val=""A5A5A5""/></a:accent3><a:accent4><a:srgbClr val=""FFC000""/></a:accent4><a:accent5><a:srgbClr val=""5B9BD5""/></a:accent5><a:accent6><a:srgbClr val=""70AD47""/></a:accent6><a:hlink><a:srgbClr val=""0563C1""/></a:hlink><a:folHlink><a:srgbClr val=""954F72""/></a:folHlink></a:clrScheme><a:fontScheme name=""Office""><a:majorFont><a:latin typeface=""Calibri Light"" panose=""020F0302020204030204""/><a:ea typeface=""""/><a:cs typeface=""""/><a:font script=""Jpan"" typeface=""游ゴシック Light""/><a:font script=""Hang"" typeface=""맑은 고딕""/><a:font script=""Hans"" typeface=""等线 Light""/><a:font script=""Hant"" typeface=""新細明體""/><a:font script=""Arab"" typeface=""Times New Roman""/><a:font script=""Hebr"" typeface=""Times New Roman""/><a:font script=""Thai"" typeface=""Tahoma""/><a:font script=""Ethi"" typeface=""Nyala""/><a:font script=""Beng"" typeface=""Vrinda""/><a:font script=""Gujr"" typeface=""Shruti""/><a:font script=""Khmr"" typeface=""MoolBoran""/><a:font script=""Knda"" typeface=""Tunga""/><a:font script=""Guru"" typeface=""Raavi""/><a:font script=""Cans"" typeface=""Euphemia""/><a:font script=""Cher"" typeface=""Plantagenet Cherokee""/><a:font script=""Yiii"" typeface=""Microsoft Yi Baiti""/><a:font script=""Tibt"" typeface=""Microsoft Himalaya""/><a:font script=""Thaa"" typeface=""MV Boli""/><a:font script=""Deva"" typeface=""Mangal""/><a:font script=""Telu"" typeface=""Gautami""/><a:font script=""Taml"" typeface=""Latha""/><a:font script=""Syrc"" typeface=""Estrangelo Edessa""/><a:font script=""Orya"" typeface=""Kalinga""/><a:font script=""Mlym"" typeface=""Kartika""/><a:font script=""Laoo"" typeface=""DokChampa""/><a:font script=""Sinh"" typeface=""Iskoola Pota""/><a:font script=""Mong"" typeface=""Mongolian Baiti""/><a:font script=""Viet"" typeface=""Times New Roman""/><a:font script=""Uigh"" typeface=""Microsoft Uighur""/><a:font script=""Geor"" typeface=""Sylfaen""/><a:font script=""Armn"" typeface=""Arial""/><a:font script=""Bugi"" typeface=""Leelawadee UI""/><a:font script=""Bopo"" typeface=""Microsoft JhengHei""/><a:font script=""Java"" typeface=""Javanese Text""/><a:font script=""Lisu"" typeface=""Segoe UI""/><a:font script=""Mymr"" typeface=""Myanmar Text""/><a:font script=""Nkoo"" typeface=""Ebrima""/><a:font script=""Olck"" typeface=""Nirmala UI""/><a:font script=""Osma"" typeface=""Ebrima""/><a:font script=""Phag"" typeface=""Phagspa""/><a:font script=""Syrn"" typeface=""Estrangelo Edessa""/><a:font script=""Syrj"" typeface=""Estrangelo Edessa""/><a:font script=""Syre"" typeface=""Estrangelo Edessa""/><a:font script=""Sora"" typeface=""Nirmala UI""/><a:font script=""Tale"" typeface=""Microsoft Tai Le""/><a:font script=""Talu"" typeface=""Microsoft New Tai Lue""/><a:font script=""Tfng"" typeface=""Ebrima""/></a:majorFont><a:minorFont><a:latin typeface=""Calibri"" panose=""020F0502020204030204""/><a:ea typeface=""""/><a:cs typeface=""""/><a:font script=""Jpan"" typeface=""游ゴシック""/><a:font script=""Hang"" typeface=""맑은 고딕""/><a:font script=""Hans"" typeface=""等线""/><a:font script=""Hant"" typeface=""新細明體""/><a:font script=""Arab"" typeface=""Arial""/><a:font script=""Hebr"" typeface=""Arial""/><a:font script=""Thai"" typeface=""Tahoma""/><a:font script=""Ethi"" typeface=""Nyala""/><a:font script=""Beng"" typeface=""Vrinda""/><a:font script=""Gujr"" typeface=""Shruti""/><a:font script=""Khmr"" typeface=""DaunPenh""/><a:font script=""Knda"" typeface=""Tunga""/><a:font script=""Guru"" typeface=""Raavi""/><a:font script=""Cans"" typeface=""Euphemia""/><a:font script=""Cher"" typeface=""Plantagenet Cherokee""/><a:font script=""Yiii"" typeface=""Microsoft Yi Baiti""/><a:font script=""Tibt"" typeface=""Microsoft Himalaya""/><a:font script=""Thaa"" typeface=""MV Boli""/><a:font script=""Deva"" typeface=""Mangal""/><a:font script=""Telu"" typeface=""Gautami""/><a:font script=""Taml"" typeface=""Latha""/><a:font script=""Syrc"" typeface=""Estrangelo Edessa""/><a:font script=""Orya"" typeface=""Kalinga""/><a:font script=""Mlym"" typeface=""Kartika""/><a:font script=""Laoo"" typeface=""DokChampa""/><a:font script=""Sinh"" typeface=""Iskoola Pota""/><a:font script=""Mong"" typeface=""Mongolian Baiti""/><a:font script=""Viet"" typeface=""Arial""/><a:font script=""Uigh"" typeface=""Microsoft Uighur""/><a:font script=""Geor"" typeface=""Sylfaen""/><a:font script=""Armn"" typeface=""Arial""/><a:font script=""Bugi"" typeface=""Leelawadee UI""/><a:font script=""Bopo"" typeface=""Microsoft JhengHei""/><a:font script=""Java"" typeface=""Javanese Text""/><a:font script=""Lisu"" typeface=""Segoe UI""/><a:font script=""Mymr"" typeface=""Myanmar Text""/><a:font script=""Nkoo"" typeface=""Ebrima""/><a:font script=""Olck"" typeface=""Nirmala UI""/><a:font script=""Osma"" typeface=""Ebrima""/><a:font script=""Phag"" typeface=""Phagspa""/><a:font script=""Syrn"" typeface=""Estrangelo Edessa""/><a:font script=""Syrj"" typeface=""Estrangelo Edessa""/><a:font script=""Syre"" typeface=""Estrangelo Edessa""/><a:font script=""Sora"" typeface=""Nirmala UI""/><a:font script=""Tale"" typeface=""Microsoft Tai Le""/><a:font script=""Talu"" typeface=""Microsoft New Tai Lue""/><a:font script=""Tfng"" typeface=""Ebrima""/></a:minorFont></a:fontScheme><a:fmtScheme name=""Office""><a:fillStyleLst><a:solidFill><a:schemeClr val=""phClr""/></a:solidFill><a:gradFill rotWithShape=""1""><a:gsLst><a:gs pos=""0""><a:schemeClr val=""phClr""><a:lumMod val=""110000""/><a:satMod val=""105000""/><a:tint val=""67000""/></a:schemeClr></a:gs><a:gs pos=""50000""><a:schemeClr val=""phClr""><a:lumMod val=""105000""/><a:satMod val=""103000""/><a:tint val=""73000""/></a:schemeClr></a:gs><a:gs pos=""100000""><a:schemeClr val=""phClr""><a:lumMod val=""105000""/><a:satMod val=""109000""/><a:tint val=""81000""/></a:schemeClr></a:gs></a:gsLst><a:lin ang=""5400000"" scaled=""0""/></a:gradFill><a:gradFill rotWithShape=""1""><a:gsLst><a:gs pos=""0""><a:schemeClr val=""phClr""><a:satMod val=""103000""/><a:lumMod val=""102000""/><a:tint val=""94000""/></a:schemeClr></a:gs><a:gs pos=""50000""><a:schemeClr val=""phClr""><a:satMod val=""110000""/><a:lumMod val=""100000""/><a:shade val=""100000""/></a:schemeClr></a:gs><a:gs pos=""100000""><a:schemeClr val=""phClr""><a:lumMod val=""99000""/><a:satMod val=""120000""/><a:shade val=""78000""/></a:schemeClr></a:gs></a:gsLst><a:lin ang=""5400000"" scaled=""0""/></a:gradFill></a:fillStyleLst><a:lnStyleLst><a:ln w=""6350"" cap=""flat"" cmpd=""sng"" algn=""ctr""><a:solidFill><a:schemeClr val=""phClr""/></a:solidFill><a:prstDash val=""solid""/><a:miter lim=""800000""/></a:ln><a:ln w=""12700"" cap=""flat"" cmpd=""sng"" algn=""ctr""><a:solidFill><a:schemeClr val=""phClr""/></a:solidFill><a:prstDash val=""solid""/><a:miter lim=""800000""/></a:ln><a:ln w=""19050"" cap=""flat"" cmpd=""sng"" algn=""ctr""><a:solidFill><a:schemeClr val=""phClr""/></a:solidFill><a:prstDash val=""solid""/><a:miter lim=""800000""/></a:ln></a:lnStyleLst><a:effectStyleLst><a:effectStyle><a:effectLst/></a:effectStyle><a:effectStyle><a:effectLst/></a:effectStyle><a:effectStyle><a:effectLst><a:outerShdw blurRad=""57150"" dist=""19050"" dir=""5400000"" algn=""ctr"" rotWithShape=""0""><a:srgbClr val=""000000""><a:alpha val=""63000""/></a:srgbClr></a:outerShdw></a:effectLst></a:effectStyle></a:effectStyleLst><a:bgFillStyleLst><a:solidFill><a:schemeClr val=""phClr""/></a:solidFill><a:solidFill><a:schemeClr val=""phClr""><a:tint val=""95000""/><a:satMod val=""170000""/></a:schemeClr></a:solidFill><a:gradFill rotWithShape=""1""><a:gsLst><a:gs pos=""0""><a:schemeClr val=""phClr""><a:tint val=""93000""/><a:satMod val=""150000""/><a:shade val=""98000""/><a:lumMod val=""102000""/></a:schemeClr></a:gs><a:gs pos=""50000""><a:schemeClr val=""phClr""><a:tint val=""98000""/><a:satMod val=""130000""/><a:shade val=""90000""/><a:lumMod val=""103000""/></a:schemeClr></a:gs><a:gs pos=""100000""><a:schemeClr val=""phClr""><a:shade val=""63000""/><a:satMod val=""120000""/></a:schemeClr></a:gs></a:gsLst><a:lin ang=""5400000"" scaled=""0""/></a:gradFill></a:bgFillStyleLst></a:fmtScheme></a:themeElements><a:objectDefaults/><a:extraClrSchemeLst/><a:extLst><a:ext uri=""{05A4C25C-085E-4340-85A3-A5531E510DB2}""><thm15:themeFamily xmlns:thm15=""http://schemas.microsoft.com/office/thememl/2012/main"" name=""Office Theme"" id=""{62F939B6-93AF-4DB8-9C6B-D6C7DFDC589F}"" vid=""{4A3C46E8-61CC-4603-A589-7422A47A8E4A}""/></a:ext></a:extLst></a:theme>";\n StartExstream(xContents, xFilename);\n\n xFilename = @"C:\\Users\\david\\Desktop\\Book3\\xl\\worksheets\\sheet1.xml";\n xContents = @"<?xml version=""1.0"" encoding=""UTF-8"" standalone=""yes""?><worksheet xmlns=""http://schemas.openxmlformats.org/spreadsheetml/2006/main"" xmlns:r=""http://schemas.openxmlformats.org/officeDocument/2006/relationships"" xmlns:mc=""http://schemas.openxmlformats.org/markup-compatibility/2006"" mc:Ignorable=""x14ac xr xr2 xr3"" xmlns:x14ac=""http://schemas.microsoft.com/office/spreadsheetml/2009/9/ac"" xmlns:xr=""http://schemas.microsoft.com/office/spreadsheetml/2014/revision"" xmlns:xr2=""http://schemas.microsoft.com/office/spreadsheetml/2015/revision2"" xmlns:xr3=""http://schemas.microsoft.com/office/spreadsheetml/2016/revision3"" xr:uid=""{54E3D330-4E78-4755-89E0-1AADACAC4953}""><dimension ref=""A1:A3""/><sheetViews><sheetView tabSelected=""1"" workbookViewId=""0""><selection activeCell=""A4"" sqref=""A4""/></sheetView></sheetViews><sheetFormatPr defaultRowHeight=""15"" x14ac:dyDescent=""0.25""/><sheetData><row r=""1"" spans=""1:1"" x14ac:dyDescent=""0.25""><c r=""A1""><v>1</v></c></row><row r=""2"" spans=""1:1"" x14ac:dyDescent=""0.25""><c r=""A2""><v>2</v></c></row><row r=""3"" spans=""1:1"" x14ac:dyDescent=""0.25""><c r=""A3""><v>3</v></c></row></sheetData><pageMargins left=""0.7"" right=""0.7"" top=""0.75"" bottom=""0.75"" header=""0.3"" footer=""0.3""/></worksheet>";\n StartExstream(xContents, xFilename);\n\n // Keep the console window open in debug mode.\n System.Console.WriteLine("Press any key to exit.");\n System.Console.ReadKey();\n\n bool StartExstream(string strLine, string strFileName)\n {\n // Write the string to a file.\n using (StreamWriter outputFile = new StreamWriter(strFileName))\n {\n outputFile.WriteLine(strLine);\n return true;\n }\n }\n }\n }\n}\n</code></pre>\n<p>Finally ZIP the folder structure containing the XML -</p>\n<pre><code>namespace ZipFolder\n// .NET Framework 4.7.2\n// https://stackoverflow.com/questions/15241889/i-didnt-find-zipfile-class-in-the-system-io-compression-namespace?answertab=votes#tab-top\n{\n class Program\n {\n static void Main(string[] args)\n {\n string xlPath = @"C:\\Users\\david\\Desktop\\Book3.xlsx";\n string folderPath = @"C:\\Users\\david\\Desktop\\Book3";\n\n System.IO.Compression.ZipFile.CreateFromDirectory(folderPath, xlPath);\n\n // Keep the console window open in debug mode.\n System.Console.WriteLine("Press any key to exit.");\n System.Console.ReadKey();\n }\n }\n}\n</code></pre>\n<p>This produces an Excel file named Book3.xlsx which is valid and opens cleanly in Excel 365 on Windows 11.</p>\n<p>The result is a very simple Excel spreadsheet but you may need to reverse engineer a more complex version. Here is the code to unzip a .xlsx file.</p>\n<pre><code>namespace UnZipXL\n// .NET Framework 4.7.2\n// https://stackoverflow.com/questions/15241889/i-didnt-find-zipfile-class-in-the-system-io-compression-namespace?answertab=votes#tab-top\n{\n class Program\n {\n static void Main(string[] args)\n {\n string XLPath = @"C:\\Users\\david\\Desktop\\Book2.xlsx";\n string extractPath = @"C:\\Users\\david\\Desktop\\extract";\n\n System.IO.Compression.ZipFile.ExtractToDirectory(XLPath, extractPath);\n\n // Keep the console window open in debug mode.\n System.Console.WriteLine("Press any key to exit.");\n System.Console.ReadKey();\n }\n }\n}\n</code></pre>\n<p>Update:</p>\n<p>Here is a code fragment to update the Excel file. This is very simple again.</p>\n<pre><code>//\n// https://learn.microsoft.com/en-us/dotnet/standard/io/how-to-write-text-to-a-file\n// .NET Framework 4.7.2\n//\nusing System.IO;\n\nnamespace UpdateWorksheet5\n{\n class Program\n {\n static void Main(string[] args)\n {\n string xContents = @"a";\n string xFilename = @"a";\n\n xFilename = @"C:\\Users\\david\\Desktop\\Book3\\xl\\worksheets\\sheet1.xml";\n xContents = @"<?xml version=""1.0"" encoding=""UTF-8"" standalone=""yes""?><worksheet xmlns=""http://schemas.openxmlformats.org/spreadsheetml/2006/main"" xmlns:r=""http://schemas.openxmlformats.org/officeDocument/2006/relationships"" xmlns:mc=""http://schemas.openxmlformats.org/markup-compatibility/2006"" mc:Ignorable=""x14ac xr xr2 xr3"" xmlns:x14ac=""http://schemas.microsoft.com/office/spreadsheetml/2009/9/ac"" xmlns:xr=""http://schemas.microsoft.com/office/spreadsheetml/2014/revision"" xmlns:xr2=""http://schemas.microsoft.com/office/spreadsheetml/2015/revision2"" xmlns:xr3=""http://schemas.microsoft.com/office/spreadsheetml/2016/revision3"" xr:uid=""{54E3D330-4E78-4755-89E0-1AADACAC4953}""><dimension ref=""A1:A3""/><sheetViews><sheetView tabSelected=""1"" workbookViewId=""0""><selection activeCell=""A4"" sqref=""A4""/></sheetView></sheetViews><sheetFormatPr defaultRowHeight=""15"" x14ac:dyDescent=""0.25""/><sheetData><row r=""1"" spans=""1:1"" x14ac:dyDescent=""0.25""><c r=""A1""><v>1</v></c></row><row r=""2"" spans=""1:1"" x14ac:dyDescent=""0.25""><c r=""A2""><v>2</v></c></row><row r=""3"" spans=""1:1"" x14ac:dyDescent=""0.25""><c r=""A3""><v>3</v></c></row></sheetData><pageMargins left=""0.7"" right=""0.7"" top=""0.75"" bottom=""0.75"" header=""0.3"" footer=""0.3""/></worksheet>";\n xContents = xContents.Remove(941, 1).Insert(941, "0"); // character to replace is at 942 => index 941\n StartExstream(xContents, xFilename);\n\n // Keep the console window open in debug mode.\n System.Console.WriteLine("Press any key to exit.");\n System.Console.ReadKey();\n\n bool StartExstream(string strLine, string strFileName)\n {\n // Write the string to a file.\n using (StreamWriter outputFile = new StreamWriter(strFileName))\n {\n outputFile.WriteLine(strLine);\n return true;\n }\n }\n }\n }\n}\n</code></pre>\n<p>Update 2 - This code works almost unchanged except for the folder paths on a Mac. Using Microsoft Excel Online, .NET Framework 3.1, Visual Studio 2019 for Mac, MacOS Monterey 12.1.</p>\n"
},
{
"answer_id": 73911370,
"author": "Fabian",
"author_id": 4226080,
"author_profile": "https://Stackoverflow.com/users/4226080",
"pm_score": 1,
"selected": false,
"text": "<p>I found another library that does it without much dependencies: <a href=\"https://github.com/mini-software/MiniExcel\" rel=\"nofollow noreferrer\">MiniExcel</a>.</p>\n<p>You can create a <code>DataSet</code> with <code>DataTable</code>s as spreadsheets (the name of the table being the name of the spreadsheet) and save it to <code>.xlsx</code> file by</p>\n<pre><code>using var stream = File.Create(filePath);\nstream.SaveAs(dataSet);\n</code></pre>\n<p>or</p>\n<pre><code>MiniExcel.SaveAs(filePath, dataSet);\n</code></pre>\n<p>It offers also reading of Excel files and does support reading and writing of CSV files.</p>\n"
}
]
| 2008/09/29 | [
"https://Stackoverflow.com/questions/151005",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/19242/"
]
| How can I create an Excel spreadsheet with C# without requiring Excel to be installed on the machine that's running the code? | You can use a library called ExcelLibrary. It's a free, open source library posted on Google Code:
[ExcelLibrary](https://code.google.com/archive/p/excellibrary/)
This looks to be a port of the PHP ExcelWriter that you mentioned above. It will not write to the new .xlsx format yet, but they are working on adding that functionality in.
It's very simple, small and easy to use. Plus it has a DataSetHelper that lets you use DataSets and DataTables to easily work with Excel data.
ExcelLibrary seems to still only work for the older Excel format (.xls files), but may be adding support in the future for newer 2007/2010 formats.
You can also use [EPPlus](https://github.com/JanKallman/EPPlus), which works only for Excel 2007/2010 format files (.xlsx files). There's also [NPOI](https://github.com/tonyqus/npoi) which works with both.
There are a few known bugs with each library as noted in the comments. In all, EPPlus seems to be the best choice as time goes on. It seems to be more actively updated and documented as well.
Also, as noted by @АртёмЦарионов below, EPPlus has support for Pivot Tables and ExcelLibrary may have some support ([Pivot table issue in ExcelLibrary](https://code.google.com/archive/p/excellibrary/issues/98))
Here are a couple links for quick reference:
[ExcelLibrary](https://code.google.com/archive/p/excellibrary/) - [GNU Lesser GPL](https://www.gnu.org/licenses/lgpl.html)
[EPPlus](https://github.com/JanKallman/EPPlus) - [GNU (LGPL) - No longer maintained](https://github.com/JanKallman/EPPlus#license)
[EPPlus 5](https://www.epplussoftware.com/) - [Polyform Noncommercial - Starting May 2020](https://www.epplussoftware.com/en/LicenseOverview)
[NPOI](https://github.com/tonyqus/npoi) - [Apache License](https://github.com/tonyqus/npoi/blob/master/LICENSE)
**Here some example code for ExcelLibrary:**
Here is an example taking data from a database and creating a workbook from it. Note that the ExcelLibrary code is the single line at the bottom:
```
//Create the data set and table
DataSet ds = new DataSet("New_DataSet");
DataTable dt = new DataTable("New_DataTable");
//Set the locale for each
ds.Locale = System.Threading.Thread.CurrentThread.CurrentCulture;
dt.Locale = System.Threading.Thread.CurrentThread.CurrentCulture;
//Open a DB connection (in this example with OleDB)
OleDbConnection con = new OleDbConnection(dbConnectionString);
con.Open();
//Create a query and fill the data table with the data from the DB
string sql = "SELECT Whatever FROM MyDBTable;";
OleDbCommand cmd = new OleDbCommand(sql, con);
OleDbDataAdapter adptr = new OleDbDataAdapter();
adptr.SelectCommand = cmd;
adptr.Fill(dt);
con.Close();
//Add the table to the data set
ds.Tables.Add(dt);
//Here's the easy part. Create the Excel worksheet from the data set
ExcelLibrary.DataSetHelper.CreateWorkbook("MyExcelFile.xls", ds);
```
Creating the Excel file is as easy as that. You can also manually create Excel files, but the above functionality is what really impressed me. |
151,026 | <pre><code>sqlite> DELETE FROM mails WHERE (`id` = 71);
SQL error: database is locked
</code></pre>
<p>How do I unlock the database so this will work?</p>
| [
{
"answer_id": 151040,
"author": "Heat Miser",
"author_id": 3484,
"author_profile": "https://Stackoverflow.com/users/3484",
"pm_score": 4,
"selected": false,
"text": "<p>the SQLite db files are just files, so the first step would be to make sure it isn't read-only. The other thing to do is to make sure that you don't have some sort of GUI SQLite DB viewer with the DB open. You could have the DB open in another shell, or your code may have the DB open. Typically you would see this if a different thread, or application such as SQLite Database Browser has the DB open for writing.</p>\n"
},
{
"answer_id": 218622,
"author": "converter42",
"author_id": 28974,
"author_profile": "https://Stackoverflow.com/users/28974",
"pm_score": 6,
"selected": false,
"text": "<p>The SQLite wiki <a href=\"https://www2.sqlite.org/cvstrac/wiki?p=DatabaseIsLocked\" rel=\"nofollow noreferrer\">DatabaseIsLocked</a> page offers an explanation of this error message. It states, in part, that the source of contention is internal (to the process emitting the error). What this page doesn't explain is how SQLite decides that something in your process holds a lock and what conditions could lead to a false positive.</p>\n<blockquote>\n<p>This error code occurs when you try to do two incompatible things with a database at the same time from the same database connection.</p>\n</blockquote>\n<hr />\n<p>Changes related to file locking introduced in v3 and may be useful for future readers and can be found here: <a href=\"https://www.sqlite.org/lockingv3.html\" rel=\"nofollow noreferrer\">File Locking And Concurrency In SQLite Version 3</a></p>\n"
},
{
"answer_id": 290972,
"author": "Michael Cox",
"author_id": 372698,
"author_profile": "https://Stackoverflow.com/users/372698",
"pm_score": 2,
"selected": false,
"text": "<p>I just had something similar happen to me - my web application was able to read from the database, but could not perform any inserts or updates. A reboot of Apache solved the issue at least temporarily.</p>\n\n<p>It'd be nice, however, to be able to track down the root cause.</p>\n"
},
{
"answer_id": 290985,
"author": "Kyle Cronin",
"author_id": 658,
"author_profile": "https://Stackoverflow.com/users/658",
"pm_score": 3,
"selected": false,
"text": "<p>I found the <a href=\"http://www.sqlite.org/lockingv3.html\" rel=\"noreferrer\">documentation</a> of the various states of locking in SQLite to be very helpful. Michael, if you can perform reads but can't perform writes to the database, that means that a process has gotten a RESERVED lock on your database but hasn't executed the write yet. If you're using SQLite3, there's a new lock called PENDING where no more processes are allowed to connect but existing connections can sill perform reads, so if this is the issue you should look at that instead.</p>\n"
},
{
"answer_id": 396967,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 0,
"selected": false,
"text": "<p>From your previous comments you said a -journal file was present. </p>\n\n<p>This could mean that you have opened and (EXCLUSIVE?) transaction and have not yet committed the data. Did your program or some other process leave the -journal behind??</p>\n\n<p>Restarting the sqlite process will look at the journal file and clean up any uncommitted actions and remove the -journal file.</p>\n"
},
{
"answer_id": 493870,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 4,
"selected": false,
"text": "<p>If a process has a lock on an SQLite DB and crashes, the DB stays locked permanently. That's the problem. It's not that some other process has a lock.</p>\n"
},
{
"answer_id": 988853,
"author": "Shawn Swaner",
"author_id": 50609,
"author_profile": "https://Stackoverflow.com/users/50609",
"pm_score": 1,
"selected": false,
"text": "<p>I ran into this same problem on Mac OS X 10.5.7 running Python scripts from a terminal session. Even though I had stopped the scripts and the terminal window was sitting at the command prompt, it would give this error the next time it ran. The solution was to close the terminal window and then open it up again. Doesn't make sense to me, but it worked.</p>\n"
},
{
"answer_id": 1027493,
"author": "Aaron",
"author_id": 126851,
"author_profile": "https://Stackoverflow.com/users/126851",
"pm_score": 5,
"selected": false,
"text": "<p>Deleting the -journal file sounds like a terrible idea. It's there to allow sqlite to roll back the database to a consistent state after a crash. If you delete it while the database is in an inconsistent state, then you're left with a corrupted database. Citing a page from the <a href=\"http://www.sqlite.org/atomiccommit.html\" rel=\"noreferrer\">sqlite site</a>:</p>\n<blockquote>\n<p>If a crash or power loss does occur and a hot journal is left on the disk, it is essential that the original database file and the hot journal remain on disk with their original names until the database file is opened by another SQLite process and rolled back. [...]</p>\n<p>We suspect that a common failure mode for SQLite recovery happens like this: A power failure occurs. After power is restored, a well-meaning user or system administrator begins looking around on the disk for damage. They see their database file named "important.data". This file is perhaps familiar to them. But after the crash, there is also a hot journal named "important.data-journal". The user then deletes the hot journal, thinking that they are helping to cleanup the system. We know of no way to prevent this other than user education.</p>\n</blockquote>\n<p>The rollback is supposed to happen automatically the next time the database is opened, but it will fail if the process can't lock the database. As others have said, one possible reason for this is that another process currently has it open. Another possibility is a stale NFS lock, if the database is on an NFS volume. In that case, a workaround is to replace the database file with a fresh copy that isn't locked on the NFS server (mv database.db original.db; cp original.db database.db). Note that the sqlite FAQ recommends caution regarding concurrent access to databases on NFS volumes, because of buggy implementations of NFS file locking.</p>\n<p>I can't explain why deleting a -journal file would let you lock a database that you couldn't before. Is that reproducible?</p>\n<p>By the way, the presence of a -journal file doesn't necessarily mean that there was a crash or that there are changes to be rolled back. Sqlite has a few different journal modes, and in PERSIST or TRUNCATE modes it leaves the -journal file in place always, and changes the contents to indicate whether or not there are partial transactions to roll back.</p>\n"
},
{
"answer_id": 1226850,
"author": "Ben L",
"author_id": 22185,
"author_profile": "https://Stackoverflow.com/users/22185",
"pm_score": 4,
"selected": false,
"text": "<p>My lock was caused by the system crashing and not by a hanging process. To resolve this, I simply renamed the file then copied it back to its original name and location.</p>\n<p>Using a Linux shell that would be:</p>\n<pre><code>mv mydata.db temp.db\ncp temp.db mydata.db\n</code></pre>\n"
},
{
"answer_id": 2018488,
"author": "wisty",
"author_id": 207028,
"author_profile": "https://Stackoverflow.com/users/207028",
"pm_score": 0,
"selected": false,
"text": "<p>As Seun Osewa has said, sometimes a zombie process will sit in the terminal with a lock aquired, even if you don't think it possible. Your script runs, crashes, and you go back to the prompt, but there's a zombie process spawned somewhere by a library call, and that process has the lock.</p>\n\n<p>Closing the terminal you were in (on OSX) might work. Rebooting will work. You could look for \"python\" processes (for example) that are not doing anything, and kill them.</p>\n"
},
{
"answer_id": 3083942,
"author": "Philip Clarke",
"author_id": 265155,
"author_profile": "https://Stackoverflow.com/users/265155",
"pm_score": 1,
"selected": false,
"text": "<p>Before going down the reboot option, it is worthwhile to see if you can find the user of the sqlite database.</p>\n\n<p>On Linux, one can employ <code>fuser</code> to this end:</p>\n\n<pre><code>$ fuser database.db\n\n$ fuser database.db-journal\n</code></pre>\n\n<p>In my case I got the following response:</p>\n\n<pre><code>philip 3556 4700 0 10:24 pts/3 00:00:01 /usr/bin/python manage.py shell\n</code></pre>\n\n<p>Which showed that I had another Python program with pid 3556 (manage.py) using the database.</p>\n"
},
{
"answer_id": 3127201,
"author": "Dzung Nguyen",
"author_id": 195727,
"author_profile": "https://Stackoverflow.com/users/195727",
"pm_score": 0,
"selected": false,
"text": "<p>you can try this: <code>.timeout 100</code> to set timeout . \nI don't know what happen in command line but in C# .Net when I do this: <code>\"UPDATE table-name SET column-name = value;\"</code> I get Database is locked but this <code>\"UPDATE table-name SET column-name = value\"</code> it goes fine. </p>\n\n<p>It looks like when you add ;, sqlite'll look for further command.</p>\n"
},
{
"answer_id": 3481134,
"author": "noneno",
"author_id": 395169,
"author_profile": "https://Stackoverflow.com/users/395169",
"pm_score": 9,
"selected": true,
"text": "<p>In windows you can try this program <a href=\"http://www.nirsoft.net/utils/opened_files_view.html\" rel=\"noreferrer\">http://www.nirsoft.net/utils/opened_files_view.html</a> to find out the process is handling db file. Try closed that program for unlock database</p>\n\n<p>In Linux and macOS you can do something similar, for example, if your locked file is development.db:</p>\n\n<blockquote>\n <p>$ fuser development.db</p>\n</blockquote>\n\n<p>This command will show what process is locking the file:</p>\n\n<blockquote>\n <p>> development.db: 5430</p>\n</blockquote>\n\n<p>Just kill the process...</p>\n\n<blockquote>\n <p>kill -9 5430</p>\n</blockquote>\n\n<p>...And your database will be unlocked.</p>\n"
},
{
"answer_id": 5529397,
"author": "Davide Ganz",
"author_id": 689765,
"author_profile": "https://Stackoverflow.com/users/689765",
"pm_score": 2,
"selected": false,
"text": "<p>Should be a database's internal problem...<br>\nFor me it has been manifested after trying to browse database with \"SQLite manager\"...<br>\nSo, if you can't find another process connect to database and you just can't fix it,\njust try this radical solution:</p>\n\n<ol>\n<li>Provide to export your tables (You can use \"SQLite manager\" on Firefox)</li>\n<li>If the migration alter your database scheme delete the last failed migration</li>\n<li>Rename your \"database.sqlite\" file</li>\n<li>Execute \"rake db:migrate\" to make a new working database</li>\n<li>Provide to give the right permissions to database for table's importing</li>\n<li>Import your backed up tables</li>\n<li>Write the new migration</li>\n<li>Execute it with \"<code>rake db:migrate</code>\"</li>\n</ol>\n"
},
{
"answer_id": 6366752,
"author": "jogojapan",
"author_id": 777186,
"author_profile": "https://Stackoverflow.com/users/777186",
"pm_score": 4,
"selected": false,
"text": "<p>I had this problem just now, using an SQLite database on a remote server, stored on an NFS mount. SQLite was unable to obtain a lock after the remote shell session I used had crashed while the database was open.</p>\n\n<p>The recipes for recovery suggested above did not work for me (including the idea to first move and then copy the database back). But after copying it to a non-NFS system, the database became usable and not data appears to have been lost.</p>\n"
},
{
"answer_id": 7450049,
"author": "PinkSheep",
"author_id": 302829,
"author_profile": "https://Stackoverflow.com/users/302829",
"pm_score": 2,
"selected": false,
"text": "<p><strong>lsof</strong> command on my Linux environment helped me to figure it out that a process was hanging keeping the file open.<br/>\nKilled the process and problem was solved.</p>\n"
},
{
"answer_id": 7740613,
"author": "robert",
"author_id": 255345,
"author_profile": "https://Stackoverflow.com/users/255345",
"pm_score": 7,
"selected": false,
"text": "<p>I caused my sqlite db to become locked by crashing an app during a write. Here is how i fixed it:</p>\n\n<pre><code>echo \".dump\" | sqlite old.db | sqlite new.db\n</code></pre>\n\n<p>Taken from: <a href=\"http://random.kakaopor.hu/how-to-repair-an-sqlite-database\">http://random.kakaopor.hu/how-to-repair-an-sqlite-database</a></p>\n"
},
{
"answer_id": 8517596,
"author": "MightyPixel",
"author_id": 801031,
"author_profile": "https://Stackoverflow.com/users/801031",
"pm_score": 1,
"selected": false,
"text": "<p>I just had the same error.\nAfter 5 minets google-ing I found that I didun't closed one shell witch were using the db.\nJust close it and try again ;)</p>\n"
},
{
"answer_id": 9327800,
"author": "Jay",
"author_id": 779135,
"author_profile": "https://Stackoverflow.com/users/779135",
"pm_score": 1,
"selected": false,
"text": "<p>I had the same problem. Apparently the rollback function seems to overwrite the db file with the journal which is the same as the db file but without the most recent change. I've implemented this in my code below and it's been working fine since then, whereas before my code would just get stuck in the loop as the database stayed locked.</p>\n\n<p>Hope this helps</p>\n\n<h3>my python code</h3>\n\n<pre><code>##############\n#### Defs ####\n##############\ndef conn_exec( connection , cursor , cmd_str ):\n done = False\n try_count = 0.0\n while not done:\n try:\n cursor.execute( cmd_str )\n done = True\n except sqlite.IntegrityError:\n # Ignore this error because it means the item already exists in the database\n done = True\n except Exception, error:\n if try_count%60.0 == 0.0: # print error every minute\n print \"\\t\" , \"Error executing command\" , cmd_str\n print \"Message:\" , error\n\n if try_count%120.0 == 0.0: # if waited for 2 miutes, roll back\n print \"Forcing Unlock\"\n connection.rollback()\n\n time.sleep(0.05) \n try_count += 0.05\n\n\ndef conn_comit( connection ):\n done = False\n try_count = 0.0\n while not done:\n try:\n connection.commit()\n done = True\n except sqlite.IntegrityError:\n # Ignore this error because it means the item already exists in the database\n done = True\n except Exception, error:\n if try_count%60.0 == 0.0: # print error every minute\n print \"\\t\" , \"Error executing command\" , cmd_str\n print \"Message:\" , error\n\n if try_count%120.0 == 0.0: # if waited for 2 miutes, roll back\n print \"Forcing Unlock\"\n connection.rollback()\n\n time.sleep(0.05) \n try_count += 0.05 \n\n\n\n\n##################\n#### Run Code ####\n##################\nconnection = sqlite.connect( db_path )\ncursor = connection.cursor()\n# Create tables if database does not exist\nconn_exec( connection , cursor , '''CREATE TABLE IF NOT EXISTS fix (path TEXT PRIMARY KEY);''')\nconn_exec( connection , cursor , '''CREATE TABLE IF NOT EXISTS tx (path TEXT PRIMARY KEY);''')\nconn_exec( connection , cursor , '''CREATE TABLE IF NOT EXISTS completed (fix DATE, tx DATE);''')\nconn_comit( connection )\n</code></pre>\n"
},
{
"answer_id": 9333604,
"author": "Mike Keskinov",
"author_id": 817767,
"author_profile": "https://Stackoverflow.com/users/817767",
"pm_score": 2,
"selected": false,
"text": "<p>I have such problem within the app, which access to SQLite from 2 connections - one was read-only and second for writing and reading. It looks like that read-only connection blocked writing from second connection. Finally, it is turns out that it is required to finalize or, at least, reset prepared statements IMMEDIATELY after use. Until prepared statement is opened, it caused to database was blocked for writing.</p>\n\n<p><strong>DON'T FORGET CALL:</strong></p>\n\n<pre><code>sqlite_reset(xxx);\n</code></pre>\n\n<p>or</p>\n\n<pre><code>sqlite_finalize(xxx);\n</code></pre>\n"
},
{
"answer_id": 12395765,
"author": "Zequez",
"author_id": 887194,
"author_profile": "https://Stackoverflow.com/users/887194",
"pm_score": 3,
"selected": false,
"text": "<p>This error can be thrown if the file is in a remote folder, like a shared folder. I changed the database to a local directory and it worked perfectly.</p>\n"
},
{
"answer_id": 13054611,
"author": "Martin",
"author_id": 1021426,
"author_profile": "https://Stackoverflow.com/users/1021426",
"pm_score": 1,
"selected": false,
"text": "<p>One common reason for getting this exception is when you are trying to do a write operation while still holding resources for a read operation. For example, if you SELECT from a table, and then try to UPDATE something you've selected without closing your ResultSet first.</p>\n"
},
{
"answer_id": 15271260,
"author": "vinayak jadi",
"author_id": 1656762,
"author_profile": "https://Stackoverflow.com/users/1656762",
"pm_score": 5,
"selected": false,
"text": "<p>If you want to remove a \"database is locked\" error then follow these steps:</p>\n\n<ol>\n<li>Copy your database file to some other location. </li>\n<li>Replace the database with the copied database. This will dereference all processes which were accessing your database file.</li>\n</ol>\n"
},
{
"answer_id": 16579869,
"author": "shreeji",
"author_id": 2265003,
"author_profile": "https://Stackoverflow.com/users/2265003",
"pm_score": 2,
"selected": false,
"text": "<p>This link solve the problem. : <a href=\"https://stackoverflow.com/questions/8853954/sqlite-error-database-is-locked\">When Sqlite gives : Database locked error</a>\nIt solved my problem may be useful to you.</p>\n\n<p>And you can use begin transaction and end transaction to not make database locked in future.</p>\n"
},
{
"answer_id": 22415203,
"author": "TheSteven",
"author_id": 140858,
"author_profile": "https://Stackoverflow.com/users/140858",
"pm_score": 0,
"selected": false,
"text": "<p>I got this error when using Delphi with the LiteDAC components.\nTurned out it only happened while running my app from the Delphi IDE if the Connected property was set True for the SQLite connection component (in this case TLiteConnection). </p>\n"
},
{
"answer_id": 23845990,
"author": "Mohsin",
"author_id": 3537274,
"author_profile": "https://Stackoverflow.com/users/3537274",
"pm_score": 0,
"selected": false,
"text": "<p>For some reason the database got locked. Here is how I fixed it.</p>\n\n<ol>\n<li>I downloaded the sqlite file to my system (FTP)</li>\n<li>Deleted the online sqlite file</li>\n<li>Uploaded the file back to the hosting provider</li>\n</ol>\n\n<p>It works fine now.</p>\n"
},
{
"answer_id": 28611052,
"author": "J.J",
"author_id": 3329564,
"author_profile": "https://Stackoverflow.com/users/3329564",
"pm_score": 3,
"selected": false,
"text": "<p>Some functions, like INDEX'ing, can take a very long time - and it locks the whole database while it runs. In instances like that, it might not even use the journal file!</p>\n\n<p>So the best/only way to check if your database is locked because a process is ACTIVELY writing to it (and thus you should leave it the hell alone until its completed its operation) is to md5 (or md5sum on some systems) the file twice. \nIf you get a different checksum, the database is being written, and you really really REALLY don't want to kill -9 that process because you can easily end up with a corrupt table/database if you do.</p>\n\n<p>I'll reiterate, because it's important - the solution is NOT to find the locking program and kill it - it's to find if the database has a write lock for a good reason, and go from there. Sometimes the correct solution is just a coffee break.</p>\n\n<p>The only way to create this locked-but-not-being-written-to situation is if your program runs <code>BEGIN EXCLUSIVE</code>, because it wanted to do some table alterations or something, then for whatever reason never sends an <code>END</code> afterwards, <strong>and the process never terminates</strong>. All three conditions being met is highly unlikely in any properly-written code, and as such 99 times out of 100 when someone wants to kill -9 their locking process, the locking process is actually locking your database for a good reason. Programmers don't typically add the <code>BEGIN EXCLUSIVE</code> condition unless they really need to, because it prevents concurrency and increases user complaints. SQLite itself only adds it when it really needs to (like when indexing).</p>\n\n<p>Finally, the 'locked' status does not exist INSIDE the file as several answers have stated - it resides in the Operating System's kernel. The process which ran <code>BEGIN EXCLUSIVE</code> has requested from the OS a lock be placed on the file. Even if your exclusive process has crashed, your OS will be able to figure out if it should maintain the file lock or not!! It is not possible to end up with a database which is locked but no process is actively locking it!!\nWhen it comes to seeing which process is locking the file, it's typically better to use lsof rather than fuser (this is a good demonstration of why: <a href=\"https://unix.stackexchange.com/questions/94316/fuser-vs-lsof-to-check-files-in-use\">https://unix.stackexchange.com/questions/94316/fuser-vs-lsof-to-check-files-in-use</a>). Alternatively if you have DTrace (OSX) you can use iosnoop on the file.</p>\n"
},
{
"answer_id": 35759613,
"author": "Stijn Sanders",
"author_id": 87971,
"author_profile": "https://Stackoverflow.com/users/87971",
"pm_score": 1,
"selected": false,
"text": "<p>I was having \"database is locked\" errors in a multi-threaded application as well, which appears to be the <a href=\"http://sqlite.org/rescode.html#busy\" rel=\"nofollow\">SQLITE_BUSY</a> result code, and I solved it with setting <a href=\"http://sqlite.org/c3ref/busy_timeout.html\" rel=\"nofollow\">sqlite3_busy_timeout</a> to something suitably long like 30000.</p>\n\n<p>(On a side-note, how odd that on a 7 year old question nobody found this out already! SQLite really is a peculiar and amazing project...)</p>\n"
},
{
"answer_id": 35864013,
"author": "user1900210",
"author_id": 1900210,
"author_profile": "https://Stackoverflow.com/users/1900210",
"pm_score": 3,
"selected": false,
"text": "<p>I added \"<code>Pooling=true</code>\" to connection string and it worked.</p>\n"
},
{
"answer_id": 36741074,
"author": "kothvandir",
"author_id": 1297972,
"author_profile": "https://Stackoverflow.com/users/1297972",
"pm_score": 1,
"selected": false,
"text": "<p>An old question, with a lot of answers, here's the steps I've recently followed reading the answers above, but in my case the problem was due to cifs resource sharing. This case is not reported previously, so hope it helps someone.</p>\n\n<ul>\n<li>Check no connections are left open in your java code. </li>\n<li>Check no other processes are using your SQLite db file with lsof. </li>\n<li>Check the user owner of your running jvm process has r/w permissions over the file.</li>\n<li><p>Try to force the lock mode on the connection opening with</p>\n\n<pre><code>final SQLiteConfig config = new SQLiteConfig();\n\nconfig.setReadOnly(false);\n\nconfig.setLockingMode(LockingMode.NORMAL);\n\nconnection = DriverManager.getConnection(url, config.toProperties());\n</code></pre></li>\n</ul>\n\n<p>If your using your SQLite db file over a NFS shared folder, check <a href=\"https://www.sqlite.org/faq.html#q5\" rel=\"nofollow noreferrer\">this point</a> of the SQLite faq, and review your mounting configuration options to make sure your avoiding locks, as described <a href=\"https://support.shotgunsoftware.com/entries/95443658-Getting-database-is-locked-on-NFS-and-CIFS-setup\" rel=\"nofollow noreferrer\">here</a>:</p>\n\n<pre><code>//myserver /mymount cifs username=*****,password=*****,iocharset=utf8,sec=ntlm,file,nolock,file_mode=0700,dir_mode=0700,uid=0500,gid=0500 0 0\n</code></pre>\n"
},
{
"answer_id": 36800388,
"author": "Wennie",
"author_id": 5354986,
"author_profile": "https://Stackoverflow.com/users/5354986",
"pm_score": 0,
"selected": false,
"text": "<p>In my case, I also got this error.</p>\n\n<p>I already checked for other processes that might be the cause of locked database such as (SQLite Manager, other programs that connects to my database). But there's no other program that connects to it, it's just another active <strong>SQLConnection</strong> in the same application that stays <strong>connected</strong>.</p>\n\n<blockquote>\n <p>Try checking your previous <strong>active SQLConnection</strong> that might be still connected (disconnect it first) before you establish a <strong>new SQLConnection</strong> and <strong>new command</strong>.</p>\n</blockquote>\n"
},
{
"answer_id": 37521042,
"author": "Alok Kumar Singh",
"author_id": 6247045,
"author_profile": "https://Stackoverflow.com/users/6247045",
"pm_score": 0,
"selected": false,
"text": "<p>This is because some other query is running on that database. SQLite is a database where query execute synchronously. So if some one else is using that database then if you perform a query or transaction it will give this error.</p>\n\n<p>So stop that process which is using the particular database and then execute your query.</p>\n"
},
{
"answer_id": 38841507,
"author": "ederribeiro",
"author_id": 576854,
"author_profile": "https://Stackoverflow.com/users/576854",
"pm_score": 1,
"selected": false,
"text": "<p>I got this error in a scenario a little different from the ones describe here.</p>\n\n<p>The SQLite database rested on a NFS filesystem shared by 3 servers. On 2 of the servers I was able do run queries on the database successfully, on the third one thought I was getting the \"database is locked\" message.</p>\n\n<p>The thing with this 3rd machine was that it had no space left on <code>/var</code>. Everytime I tried to run a query in ANY SQLite database located in this filesystem I got the \"database is locked\" message and also this error over the logs:</p>\n\n<blockquote>\n <p>Aug 8 10:33:38 server01 kernel: lockd: cannot monitor 172.22.84.87</p>\n</blockquote>\n\n<p>And this one also:</p>\n\n<blockquote>\n <p>Aug 8 10:33:38 server01 rpc.statd[7430]: Failed to insert: writing /var/lib/nfs/statd/sm/other.server.name.com: No space left on device\n Aug 8 10:33:38 server01 rpc.statd[7430]: STAT_FAIL to server01 for SM_MON of 172.22.84.87</p>\n</blockquote>\n\n<p>After the space situation was handled everything got back to normal.</p>\n"
},
{
"answer_id": 48978331,
"author": "Bob Stein",
"author_id": 673991,
"author_profile": "https://Stackoverflow.com/users/673991",
"pm_score": 1,
"selected": false,
"text": "<p>If you're trying to unlock the <strong>Chrome database</strong> to <a href=\"https://superuser.com/a/224318/139292\">view it with SQLite</a>, then just shut down Chrome.</p>\n\n<p>Windows</p>\n\n<pre class=\"lang-none prettyprint-override\"><code>%userprofile%\\Local Settings\\Application Data\\Google\\Chrome\\User Data\\Default\\Web Data\n\nor\n\n%userprofile%\\Local Settings\\Application Data\\Google\\Chrome\\User Data\\Default\\Chrome Web Data\n</code></pre>\n\n<p>Mac</p>\n\n<pre class=\"lang-none prettyprint-override\"><code>~/Library/Application Support/Google/Chrome/Default/Web Data\n</code></pre>\n"
},
{
"answer_id": 53760324,
"author": "Mr Rowe",
"author_id": 1713986,
"author_profile": "https://Stackoverflow.com/users/1713986",
"pm_score": 0,
"selected": false,
"text": "<p>I was receiving sqlite locks as well in a C# .NET 4.6.1 app I built when it was trying to write data, but not when running the app in Visual Studio on my dev machine. Instead it was only happening when the app was installed and running on a remote Windows 10 machine. </p>\n\n<p>Initially I thought it was file system permissions, however it turns out that the System.Data.SQLite package drivers (v1.0.109.2) I installed in the project using Nuget were causing the problem. I removed the NuGet package, and manually referenced an older version of the drivers in the project, and once the app was reinstalled on the remote machine the locking issues magically disappeared. Can only think there was a bug with the latest drivers or the Nuget package.</p>\n"
},
{
"answer_id": 64716546,
"author": "BertC",
"author_id": 1379184,
"author_profile": "https://Stackoverflow.com/users/1379184",
"pm_score": 0,
"selected": false,
"text": "<p>I had the tool "DB Browser for SQLite" running and was also working in there. Obviously that tool also puts locks on things.\nAfter clicking on "Write Changes" or "Revert Changes", the lock was gone and the other process (A React-Native script) did not give that error anymore.</p>\n<p><a href=\"https://i.stack.imgur.com/mX4kd.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/mX4kd.png\" alt=\"DB Browser for SQLite - Write Changes\" /></a></p>\n"
},
{
"answer_id": 67146972,
"author": "Siwei",
"author_id": 445908,
"author_profile": "https://Stackoverflow.com/users/445908",
"pm_score": 2,
"selected": false,
"text": "<p>In my experience, this error is caused by: You opened multiple connections.</p>\n<p>e.g.:</p>\n<ol>\n<li>1 or more sqlitebrowser (GUI)</li>\n<li>1 or more electron thread</li>\n<li>rails thread</li>\n</ol>\n<p>I am nore sure about the details of SQLITE3 how to handle the multiple thread/request, but when I close the sqlitebrowser and electron thread, then rails is running well and won't block any more.</p>\n"
},
{
"answer_id": 69419768,
"author": "Ярослав Рахматуллин",
"author_id": 657703,
"author_profile": "https://Stackoverflow.com/users/657703",
"pm_score": 0,
"selected": false,
"text": "<p>I encountered this error while looking at stored passwords in Google Chrome.</p>\n<pre><code># ~/.config/google-chrome/Default\n$ sqlite3 Login\\ Data\nSQLite version 3.35.5 2021-04-19 18:32:05\nsqlite> .tables\nError: database is locked\n</code></pre>\n<p>If you don't particularly care about the parent process or if you don't want to stop the current chrome process which is using the database, simply copy the file somewhere else.</p>\n<pre><code>$ cp Login\\ Data ~/tmp/ld.sql\n$ sqlite3 ~/tmp/ld.sql .tables\nfield_info meta sync_model_metadata \ninsecure_credentials stats \nlogins sync_entities_metadata\n</code></pre>\n<p>Doing so will allow you to read the contents of the database without disturbing or stopping the main chrome process.</p>\n"
}
]
| 2008/09/29 | [
"https://Stackoverflow.com/questions/151026",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/823/"
]
| ```
sqlite> DELETE FROM mails WHERE (`id` = 71);
SQL error: database is locked
```
How do I unlock the database so this will work? | In windows you can try this program <http://www.nirsoft.net/utils/opened_files_view.html> to find out the process is handling db file. Try closed that program for unlock database
In Linux and macOS you can do something similar, for example, if your locked file is development.db:
>
> $ fuser development.db
>
>
>
This command will show what process is locking the file:
>
> > development.db: 5430
>
>
>
Just kill the process...
>
> kill -9 5430
>
>
>
...And your database will be unlocked. |
151,030 | <p>When I load <code>script/console</code>, sometimes I want to play with the output of a controller or a view helper method.</p>
<p>Are there ways to:</p>
<ul>
<li>simulate a request?</li>
<li>call methods from a controller instance on said request?</li>
<li>test helper methods, either via said controller instance or another way?</li>
</ul>
| [
{
"answer_id": 151285,
"author": "Gordon Wilson",
"author_id": 23071,
"author_profile": "https://Stackoverflow.com/users/23071",
"pm_score": 6,
"selected": false,
"text": "<p>Here's one way to do this through the console:</p>\n\n<pre><code>>> foo = ActionView::Base.new\n=> #<ActionView::Base:0x2aaab0ac2af8 @assigns_added=nil, @assigns={}, @helpers=#<ActionView::Base::ProxyModule:0x2aaab0ac2a58>, @controller=nil, @view_paths=[]>\n\n>> foo.extend YourHelperModule\n=> #<ActionView::Base:0x2aaab0ac2af8 @assigns_added=nil, @assigns={}, @helpers=#<ActionView::Base::ProxyModule:0x2aaab0ac2a58>, @controller=nil, @view_paths=[]>\n\n>> foo.your_helper_method(args)\n=> \"<html>created by your helper</html>\"\n</code></pre>\n\n<p>Creating a new instance of <code>ActionView::Base</code> gives you access to the normal view methods that your helper likely uses. Then extending <code>YourHelperModule</code> mixes its methods into your object letting you view their return values.</p>\n"
},
{
"answer_id": 498899,
"author": "Dan McNevin",
"author_id": 50924,
"author_profile": "https://Stackoverflow.com/users/50924",
"pm_score": 4,
"selected": false,
"text": "<p>Another way to do this is to use the Ruby on Rails debugger. There's a Ruby on Rails guide about debugging at <a href=\"http://guides.rubyonrails.org/debugging_rails_applications.html\" rel=\"nofollow noreferrer\">http://guides.rubyonrails.org/debugging_rails_applications.html</a></p>\n\n<p>Basically, start the server with the -u option:</p>\n\n<pre><code>./script/server -u\n</code></pre>\n\n<p>And then insert a breakpoint into your script where you would like to have access to the controllers, helpers, etc.</p>\n\n<pre><code>class EventsController < ApplicationController\n def index\n debugger\n end\nend\n</code></pre>\n\n<p>And when you make a request and hit that part in the code, the server console will return a prompt where you can then make requests, view objects, etc. from a command prompt. When finished, just type 'cont' to continue execution. There are also options for extended debugging, but this should at least get you started.</p>\n"
},
{
"answer_id": 1161163,
"author": "kch",
"author_id": 13989,
"author_profile": "https://Stackoverflow.com/users/13989",
"pm_score": 10,
"selected": true,
"text": "<p>To call helpers, use the <code>helper</code> object:</p>\n\n<pre><code>$ ./script/console\n>> helper.number_to_currency('123.45')\n=> \"R$ 123,45\"\n</code></pre>\n\n<p>If you want to use a helper that's not included by default (say, because you removed <code>helper :all</code> from <code>ApplicationController</code>), just include the helper.</p>\n\n<pre><code>>> include BogusHelper\n>> helper.bogus\n=> \"bogus output\"\n</code></pre>\n\n<p>As for dealing with <strong>controllers</strong>, I quote <a href=\"https://stackoverflow.com/questions/151030/how-do-i-call-controller-view-methods-from-the-console-in-rails/1436342#1436342\">Nick's</a> answer:</p>\n\n<blockquote>\n<pre><code>> app.get '/posts/1'\n> response = app.response\n# you now have a rails response object much like the integration tests\n\n> response.body # get you the HTML\n> response.cookies # hash of the cookies\n\n# etc, etc\n</code></pre>\n</blockquote>\n"
},
{
"answer_id": 1183393,
"author": "David Knight",
"author_id": 145136,
"author_profile": "https://Stackoverflow.com/users/145136",
"pm_score": 3,
"selected": false,
"text": "<p>The earlier answers are calling helpers, but the following will help for calling controller methods. I have used this on Ruby on Rails 2.3.2.</p>\n\n<p>First add the following code to your .irbrc file (which can be in your home directory)</p>\n\n<pre><code>class Object\n def request(options = {})\n url=app.url_for(options)\n app.get(url)\n puts app.html_document.root.to_s\n end\nend\n</code></pre>\n\n<p>Then in the Ruby on Rails console you can type something like...</p>\n\n<pre><code>request(:controller => :show, :action => :show_frontpage)\n</code></pre>\n\n<p>...and the HTML will be dumped to the console.</p>\n"
},
{
"answer_id": 1436342,
"author": "Nick B",
"author_id": 37460,
"author_profile": "https://Stackoverflow.com/users/37460",
"pm_score": 7,
"selected": false,
"text": "<p>An easy way to call a controller action from a script/console and view/manipulate the response object is:</p>\n\n<pre><code>> app.get '/posts/1'\n> response = app.response\n# You now have a Ruby on Rails response object much like the integration tests\n\n> response.body # Get you the HTML\n> response.cookies # Hash of the cookies\n\n# etc., etc.\n</code></pre>\n\n<p>The app object is an instance of <a href=\"http://api.rubyonrails.org/classes/ActionDispatch/Integration/Session.html\" rel=\"noreferrer\">ActionController::Integration::Session</a></p>\n\n<p>This works for me using Ruby on Rails 2.1 and 2.3, and I did not try earlier versions.</p>\n"
},
{
"answer_id": 6436124,
"author": "Swapnil Chincholkar",
"author_id": 617631,
"author_profile": "https://Stackoverflow.com/users/617631",
"pm_score": 4,
"selected": false,
"text": "<p>If the method is the <code>POST</code> method then:</p>\n\n<pre><code>app.post 'controller/action?parameter1=value1&parameter2=value2'\n</code></pre>\n\n<p>(Here parameters will be as per your applicability.)</p>\n\n<p>Else if it is the <code>GET</code> method then:</p>\n\n<pre><code>app.get 'controller/action'\n</code></pre>\n"
},
{
"answer_id": 9159853,
"author": "Fernando Fabreti",
"author_id": 873650,
"author_profile": "https://Stackoverflow.com/users/873650",
"pm_score": 7,
"selected": false,
"text": "<p>If you need to test from the console (tested on Ruby on Rails 3.1 and 4.1):</p>\n\n<p>Call Controller Actions:</p>\n\n<pre><code>app.get '/'\n app.response\n app.response.headers # => { \"Content-Type\"=>\"text/html\", ... }\n app.response.body # => \"<!DOCTYPE html>\\n<html>\\n\\n<head>\\n...\"\n</code></pre>\n\n<p>ApplicationController methods:</p>\n\n<pre><code>foo = ActionController::Base::ApplicationController.new\nfoo.public_methods(true||false).sort\nfoo.some_method\n</code></pre>\n\n<p>Route Helpers:</p>\n\n<pre><code>app.myresource_path # => \"/myresource\"\napp.myresource_url # => \"http://www.example.com/myresource\"\n</code></pre>\n\n<p>View Helpers:</p>\n\n<pre><code>foo = ActionView::Base.new\n\nfoo.javascript_include_tag 'myscript' #=> \"<script src=\\\"/javascripts/myscript.js\\\"></script>\"\n\nhelper.link_to \"foo\", \"bar\" #=> \"<a href=\\\"bar\\\">foo</a>\"\n\nActionController::Base.helpers.image_tag('logo.png') #=> \"<img alt=\\\"Logo\\\" src=\\\"/images/logo.png\\\" />\"\n</code></pre>\n\n<p>Render:</p>\n\n<pre><code>views = Rails::Application::Configuration.new(Rails.root).paths[\"app/views\"]\nviews_helper = ActionView::Base.new views\nviews_helper.render 'myview/mytemplate'\nviews_helper.render file: 'myview/_mypartial', locals: {my_var: \"display:block;\"}\nviews_helper.assets_prefix #=> '/assets'\n</code></pre>\n\n<p>ActiveSupport methods:</p>\n\n<pre><code>require 'active_support/all'\n1.week.ago\n=> 2013-08-31 10:07:26 -0300\na = {'a'=>123}\na.symbolize_keys\n=> {:a=>123}\n</code></pre>\n\n<p>Lib modules:</p>\n\n<pre><code>> require 'my_utils'\n => true\n> include MyUtils\n => Object\n> MyUtils.say \"hi\"\nevaluate: hi\n => true\n</code></pre>\n"
},
{
"answer_id": 15709071,
"author": "Tbabs",
"author_id": 665215,
"author_profile": "https://Stackoverflow.com/users/665215",
"pm_score": 3,
"selected": false,
"text": "<p>In Ruby on Rails 3, try this:</p>\n\n<pre><code>session = ActionDispatch::Integration::Session.new(Rails.application)\nsession.get(url)\nbody = session.response.body\n</code></pre>\n\n<p>The body will contain the HTML of the URL.</p>\n\n<p><em><a href=\"https://stackoverflow.com/questions/7770119/how-to-route-and-render-dispatch-from-a-model-in-rails-3\">How to route and render (dispatch) from a model in Ruby on Rails 3</a></em></p>\n"
},
{
"answer_id": 19680853,
"author": "Jyothu",
"author_id": 1852370,
"author_profile": "https://Stackoverflow.com/users/1852370",
"pm_score": 4,
"selected": false,
"text": "<p>You can access your methods in the Ruby on Rails console like the following:</p>\n\n<pre><code>controller.method_name\nhelper.method_name\n</code></pre>\n"
},
{
"answer_id": 23899701,
"author": "Chloe",
"author_id": 148844,
"author_profile": "https://Stackoverflow.com/users/148844",
"pm_score": 4,
"selected": false,
"text": "<p>Here is how to make an authenticated POST request, using Refinery as an example:</p>\n\n<pre><code># Start Rails console\nrails console\n# Get the login form\napp.get '/community_members/sign_in'\n# View the session\napp.session.to_hash\n# Copy the CSRF token \"_csrf_token\" and place it in the login request.\n# Log in from the console to create a session\napp.post '/community_members/login', {\"authenticity_token\"=>\"gT7G17RNFaWUDLC6PJGapwHk/OEyYfI1V8yrlg0lHpM=\", \"refinery_user[login]\"=>'chloe', 'refinery_user[password]'=>'test'}\n# View the session to verify CSRF token is the same\napp.session.to_hash\n# Copy the CSRF token \"_csrf_token\" and place it in the request. It's best to edit this in Notepad++\napp.post '/refinery/blog/posts', {\"authenticity_token\"=>\"gT7G17RNFaWUDLC6PJGapwHk/OEyYfI1V8yrlg0lHpM=\", \"switch_locale\"=>\"en\", \"post\"=>{\"title\"=>\"Test\", \"homepage\"=>\"0\", \"featured\"=>\"0\", \"magazine\"=>\"0\", \"refinery_category_ids\"=>[\"1282\"], \"body\"=>\"Tests do a body good.\", \"custom_teaser\"=>\"\", \"draft\"=>\"0\", \"tag_list\"=>\"\", \"published_at(1i)\"=>\"2014\", \"published_at(2i)\"=>\"5\", \"published_at(3i)\"=>\"27\", \"published_at(4i)\"=>\"21\", \"published_at(5i)\"=>\"20\", \"custom_url\"=>\"\", \"source_url_title\"=>\"\", \"source_url\"=>\"\", \"user_id\"=>\"56\", \"browser_title\"=>\"\", \"meta_description\"=>\"\"}, \"continue_editing\"=>\"false\", \"locale\"=>:en}\n</code></pre>\n\n<p>You might find these useful too if you get an error:</p>\n\n<pre><code>app.cookies.to_hash\napp.flash.to_hash\napp.response # long, raw, HTML\n</code></pre>\n"
},
{
"answer_id": 37830674,
"author": "Dino Reic",
"author_id": 254915,
"author_profile": "https://Stackoverflow.com/users/254915",
"pm_score": 2,
"selected": false,
"text": "<p>One possible approach for Helper method testing in the Ruby on Rails console is:</p>\n\n<pre><code>Struct.new(:t).extend(YourHelper).your_method(*arg)\n</code></pre>\n\n<p>And for reload do:</p>\n\n<pre><code>reload!; Struct.new(:t).extend(YourHelper).your_method(*arg)\n</code></pre>\n"
},
{
"answer_id": 47958804,
"author": "Gayan",
"author_id": 3647002,
"author_profile": "https://Stackoverflow.com/users/3647002",
"pm_score": 2,
"selected": false,
"text": "<p>Inside any controller action or view, you can invoke the console by calling the <strong>console</strong> method.</p>\n\n<p>For example, in a controller:</p>\n\n<pre><code>class PostsController < ApplicationController\n def new\n console\n @post = Post.new\n end\nend\n</code></pre>\n\n<p>Or in a view:</p>\n\n<pre><code><% console %>\n\n<h2>New Post</h2>\n</code></pre>\n\n<p>This will render a console inside your view. You don't need to care about the location of the console call; it won't be rendered on the spot of its invocation but next to your HTML content.</p>\n\n<p>See: <a href=\"http://guides.rubyonrails.org/debugging_rails_applications.html\" rel=\"nofollow noreferrer\">http://guides.rubyonrails.org/debugging_rails_applications.html</a></p>\n"
},
{
"answer_id": 48145780,
"author": "Developer Marius Žilėnas",
"author_id": 1737819,
"author_profile": "https://Stackoverflow.com/users/1737819",
"pm_score": 2,
"selected": false,
"text": "<p>If you have added your own helper and you want its methods to be available in console, do:</p>\n\n<ol>\n<li>In the console execute <code>include YourHelperName</code></li>\n<li>Your helper methods are now available in console, and use them calling <code>method_name(args)</code> in the console.</li>\n</ol>\n\n<p>Example: say you have MyHelper (with a method <code>my_method</code>) in 'app/helpers/my_helper.rb`, then in the console do:</p>\n\n<ol>\n<li><code>include MyHelper</code></li>\n<li><code>my_helper.my_method</code></li>\n</ol>\n"
},
{
"answer_id": 54476954,
"author": "Dyaniyal Wilson",
"author_id": 8728218,
"author_profile": "https://Stackoverflow.com/users/8728218",
"pm_score": 3,
"selected": false,
"text": "<p>For controllers, you can instantiate a controller object in the Ruby on Rails console.</p>\n\n<p>For example,</p>\n\n<pre><code>class CustomPagesController < ApplicationController\n\n def index\n @customs = CustomPage.all\n end\n\n def get_number\n puts \"Got the Number\"\n end\n\n protected\n\n def get_private_number\n puts 'Got private Number'\n end\n\nend\n\ncustom = CustomPagesController.new\n2.1.5 :011 > custom = CustomPagesController.new\n => #<CustomPagesController:0xb594f77c @_action_has_layout=true, @_routes=nil, @_headers={\"Content-Type\"=>\"text/html\"}, @_status=200, @_request=nil, @_response=nil>\n2.1.5 :014 > custom.get_number\nGot the Number\n => nil\n\n# For calling private or protected methods,\n2.1.5 :048 > custom.send(:get_private_number)\nGot private Number\n => nil\n</code></pre>\n"
}
]
| 2008/09/29 | [
"https://Stackoverflow.com/questions/151030",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/13989/"
]
| When I load `script/console`, sometimes I want to play with the output of a controller or a view helper method.
Are there ways to:
* simulate a request?
* call methods from a controller instance on said request?
* test helper methods, either via said controller instance or another way? | To call helpers, use the `helper` object:
```
$ ./script/console
>> helper.number_to_currency('123.45')
=> "R$ 123,45"
```
If you want to use a helper that's not included by default (say, because you removed `helper :all` from `ApplicationController`), just include the helper.
```
>> include BogusHelper
>> helper.bogus
=> "bogus output"
```
As for dealing with **controllers**, I quote [Nick's](https://stackoverflow.com/questions/151030/how-do-i-call-controller-view-methods-from-the-console-in-rails/1436342#1436342) answer:
>
>
> ```
> > app.get '/posts/1'
> > response = app.response
> # you now have a rails response object much like the integration tests
>
> > response.body # get you the HTML
> > response.cookies # hash of the cookies
>
> # etc, etc
>
> ```
>
> |
151,034 | <p>I've been using Eclipse pretty regularly for several years now, but I admit to not having explored all the esoterica it has to offer, particularly in the areas of what formatting features the editors offer.</p>
<p>The main thing I miss from (X)emacs is the "align-regex" command, which let me take several lines into a region and then format them so that some common pattern in all lines was aligned. The simplest example of this is a series of variable assignments:</p>
<pre><code>var str = new String('aString');
var index = 0;
var longCamelCaseObjectName = new LongNameObject();
</code></pre>
<p>After doing align-regex on "=", that would become:</p>
<pre><code>var str = new String('aString');
var index = 0;
var longCamelCaseObjectName = new LongNameObject();
</code></pre>
<p>Now, you may have your own thoughts on stylistic (ab)use of white space and alignment, etc., but that's just an example (I'm actually trying to align a different kind of mess entirely).</p>
<p>Can anyone tell me off-hand if there's an easy key-combo-shortcut for this in Eclipse? Or even a moderately-tricky one?</p>
| [
{
"answer_id": 151134,
"author": "SCdF",
"author_id": 1666,
"author_profile": "https://Stackoverflow.com/users/1666",
"pm_score": 4,
"selected": true,
"text": "<p>You can set the formatter to do this:</p>\n\n<p>Preferences -> Java -> Code Style -> Formatter. Click 'Edit' on the profile (you may need to make a new one since you can't edit the default).</p>\n\n<p>In the indentation section select 'Align fields with columns'.</p>\n\n<p>Then, in your code <kbd>CTRL</kbd>+<kbd>SHIFT</kbd>+<kbd>F</kbd> will run that formatter.</p>\n\n<p>That will of course run all the other rules, so you may want to peruse the various options here.</p>\n"
},
{
"answer_id": 151148,
"author": "SCdF",
"author_id": 1666,
"author_profile": "https://Stackoverflow.com/users/1666",
"pm_score": 2,
"selected": false,
"text": "<p>If you wish to do something more complex than just aligning fields (or anything else the Eclipse code formatter offers you) you are pretty much left with having to write your own plugin.</p>\n"
},
{
"answer_id": 2444095,
"author": "mfeber",
"author_id": 293605,
"author_profile": "https://Stackoverflow.com/users/293605",
"pm_score": 2,
"selected": false,
"text": "<p>Version 2.8.7 of the Emacs+ plugin now supplies a fairly complete align-regexp implementation in Eclipse</p>\n"
},
{
"answer_id": 16956971,
"author": "Tibi",
"author_id": 4717,
"author_profile": "https://Stackoverflow.com/users/4717",
"pm_score": 0,
"selected": false,
"text": "<p>This plug-in does exactly what you want: <a href=\"https://github.com/eduardp/OCDFormat/\" rel=\"nofollow\">OCDFormat</a></p>\n\n<p>It works in all text files, not only Java.</p>\n"
},
{
"answer_id": 33067937,
"author": "Franck Dernoncourt",
"author_id": 395857,
"author_profile": "https://Stackoverflow.com/users/395857",
"pm_score": 1,
"selected": false,
"text": "<p><a href=\"http://columns4eclipse.sourceforge.net/\" rel=\"nofollow noreferrer\">columns4eclipse</a> is a nice option. It is an Eclipse plugin that allow you to do the alignments you mention in your question. I use it with Eclipse 4.3 and 4.5, it works well. I had made a gif video showing its use but my answer got deleted by a mod, so I let you try and see by yourself.</p>\n\n<p><a href=\"https://i.stack.imgur.com/opbUf.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/opbUf.png\" alt=\"enter image description here\"></a></p>\n"
}
]
| 2008/09/29 | [
"https://Stackoverflow.com/questions/151034",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6421/"
]
| I've been using Eclipse pretty regularly for several years now, but I admit to not having explored all the esoterica it has to offer, particularly in the areas of what formatting features the editors offer.
The main thing I miss from (X)emacs is the "align-regex" command, which let me take several lines into a region and then format them so that some common pattern in all lines was aligned. The simplest example of this is a series of variable assignments:
```
var str = new String('aString');
var index = 0;
var longCamelCaseObjectName = new LongNameObject();
```
After doing align-regex on "=", that would become:
```
var str = new String('aString');
var index = 0;
var longCamelCaseObjectName = new LongNameObject();
```
Now, you may have your own thoughts on stylistic (ab)use of white space and alignment, etc., but that's just an example (I'm actually trying to align a different kind of mess entirely).
Can anyone tell me off-hand if there's an easy key-combo-shortcut for this in Eclipse? Or even a moderately-tricky one? | You can set the formatter to do this:
Preferences -> Java -> Code Style -> Formatter. Click 'Edit' on the profile (you may need to make a new one since you can't edit the default).
In the indentation section select 'Align fields with columns'.
Then, in your code `CTRL`+`SHIFT`+`F` will run that formatter.
That will of course run all the other rules, so you may want to peruse the various options here. |
151,046 | <p>I'm trying to figure out the best way to determine whether I'm in the last iteration of a loop over a map in order to do something like the following:</p>
<pre><code>for (iter = someMap.begin(); iter != someMap.end(); ++iter) {
bool last_iteration;
// do something for all iterations
if (!last_iteration) {
// do something for all but the last iteration
}
}
</code></pre>
<p>There seem to be several ways of doing this: random access iterators, the <code>distance</code> function, etc. What's the canonical method?</p>
<p>Edit: no random access iterators for maps!</p>
| [
{
"answer_id": 151073,
"author": "Torlack",
"author_id": 5243,
"author_profile": "https://Stackoverflow.com/users/5243",
"pm_score": 4,
"selected": false,
"text": "<p>This seems like the simplest:</p>\n\n<pre><code>bool last_iteration = iter == (--someMap.end());\n</code></pre>\n"
},
{
"answer_id": 151074,
"author": "Daniel Spiewak",
"author_id": 9815,
"author_profile": "https://Stackoverflow.com/users/9815",
"pm_score": -1,
"selected": false,
"text": "<p>You can just pull an element out of the map prior to iteration, then perform your \"last iteration\" work out of the loop and then put the element back <em>into</em> the map. This is horribly bad for asynchronous code, but considering how bad the rest of C++ is for concurrency, I don't think it'll be an issue. :-)</p>\n"
},
{
"answer_id": 151078,
"author": "Mark Ransom",
"author_id": 5987,
"author_profile": "https://Stackoverflow.com/users/5987",
"pm_score": 6,
"selected": true,
"text": "<p>Canonical? I can't claim that, but I'd suggest </p>\n\n<pre><code>final_iter = someMap.end();\n--final_iter;\nif (iter != final_iter) ...\n</code></pre>\n\n<p><strong>Edited</strong> to correct as suggested by <strong><a href=\"https://stackoverflow.com/questions/151046/c-last-loop-iteration-stl-map-iterator#151104\">KTC</a>.</strong> (Thanks! Sometimes you go too quick and mess up on the simplest things...)</p>\n"
},
{
"answer_id": 151104,
"author": "KTC",
"author_id": 12868,
"author_profile": "https://Stackoverflow.com/users/12868",
"pm_score": 3,
"selected": false,
"text": "<p>Modified Mark Ransom's so it actually work as intended.</p>\n\n<pre><code>finalIter = someMap.end();\n--finalIter;\nif (iter != final_iter)\n</code></pre>\n"
},
{
"answer_id": 151112,
"author": "Jason Etheridge",
"author_id": 2193,
"author_profile": "https://Stackoverflow.com/users/2193",
"pm_score": 0,
"selected": false,
"text": "<p>A simple, yet effective, approach:</p>\n\n<pre><code> size_t items_remaining = someMap.size();\n\n for (iter = someMap.begin(); iter != someMap.end(); iter++) {\n bool last_iteration = items_remaining-- == 1;\n }\n</code></pre>\n"
},
{
"answer_id": 151165,
"author": "florin",
"author_id": 18308,
"author_profile": "https://Stackoverflow.com/users/18308",
"pm_score": -1,
"selected": false,
"text": "<p>Full program:</p>\n\n<pre><code>#include <iostream>\n#include <list>\n\nvoid process(int ii)\n{\n std::cout << \" \" << ii;\n}\n\nint main(void)\n{\n std::list<int> ll;\n\n ll.push_back(1);\n ll.push_back(2);\n ll.push_back(3);\n ll.push_back(4);\n ll.push_back(5);\n ll.push_back(6);\n\n std::list<int>::iterator iter = ll.begin();\n if (iter != ll.end())\n {\n std::list<int>::iterator lastIter = iter;\n ++ iter;\n while (iter != ll.end())\n {\n process(*lastIter);\n lastIter = iter;\n ++ iter;\n }\n // todo: think if you need to process *lastIter\n std::cout << \" | last:\";\n process(*lastIter);\n }\n\n std::cout << std::endl;\n\n return 0;\n}\n</code></pre>\n\n<p>This program yields:</p>\n\n<pre><code> 1 2 3 4 5 | last: 6\n</code></pre>\n"
},
{
"answer_id": 151497,
"author": "oz10",
"author_id": 14069,
"author_profile": "https://Stackoverflow.com/users/14069",
"pm_score": 1,
"selected": false,
"text": "<pre><code>#include <boost/lambda/lambda.hpp>\n#include <boost/lambda/bind.hpp>\n#include <algorithm>\n\nusing namespace boost::lambda;\n\n// call the function foo on each element but the last...\nif( !someMap.empty() )\n{\n std::for_each( someMap.begin(), --someMap.end(), bind( &Foo, _1 ) );\n}\n</code></pre>\n\n<p>Using std::for_each will ensure that the loop is tight and accurate... Note the introduction of the function foo() which takes a single argument (the type should match what is contained in someMap). This approach has the added addition of being 1 line. Of course, if Foo is really small, you can use a lambda function and get rid of the call to &Foo.</p>\n"
},
{
"answer_id": 152707,
"author": "camh",
"author_id": 23744,
"author_profile": "https://Stackoverflow.com/users/23744",
"pm_score": 3,
"selected": false,
"text": "<p>If you just want to use a ForwardIterator, this should work:</p>\n\n<pre><code>for ( i = c.begin(); i != c.end(); ) {\n iterator cur = i++;\n // do something, using cur\n if ( i != c.end() ) {\n // do something using cur for all but the last iteration\n }\n}\n</code></pre>\n"
},
{
"answer_id": 156310,
"author": "Ates Goral",
"author_id": 23501,
"author_profile": "https://Stackoverflow.com/users/23501",
"pm_score": -1,
"selected": false,
"text": "<p>Here's my optimized take:</p>\n\n<pre><code>iter = someMap.begin();\n\ndo {\n // Note that curr = iter++ may involve up to three copy operations\n curr = iter;\n\n // Do stuff with curr\n\n if (++iter == someMap.end()) {\n // Oh, this was the last iteration\n break;\n }\n\n // Do more stuff with curr\n\n} while (true);\n</code></pre>\n"
},
{
"answer_id": 495065,
"author": "Pieter",
"author_id": 5822,
"author_profile": "https://Stackoverflow.com/users/5822",
"pm_score": 3,
"selected": false,
"text": "<p>Surprised no one mentioned it yet, but of course boost has something ;)</p>\n\n<p><a href=\"http://www.boost.org/doc/libs/1_37_0/libs/utility/utility.htm#functions_next_prior\" rel=\"noreferrer\">Boost.Next</a> (and the equivalent Boost.Prior)</p>\n\n<p>Your example would look like:</p>\n\n<pre><code>for (iter = someMap.begin(); iter != someMap.end(); ++iter) {\n // do something for all iterations\n if (boost::next(iter) != someMap.end()) {\n // do something for all but the last iteration\n }\n}\n</code></pre>\n"
},
{
"answer_id": 8431209,
"author": "mpoleg",
"author_id": 1087757,
"author_profile": "https://Stackoverflow.com/users/1087757",
"pm_score": 2,
"selected": false,
"text": "<p>The following code would be optimized by a compiler so that to be the best solution for this task by performance as well as by OOP rules:</p>\n\n<pre><code>if (&*it == &*someMap.rbegin()) {\n //the last iteration\n}\n</code></pre>\n\n<p>This is the best code by OOP rules because std::map has got a special member function rbegin for the code like:</p>\n\n<pre><code>final_iter = someMap.end();\n--final_iter;\n</code></pre>\n"
},
{
"answer_id": 15847509,
"author": "Angelin Nadar",
"author_id": 412591,
"author_profile": "https://Stackoverflow.com/users/412591",
"pm_score": 2,
"selected": false,
"text": "<p>Why to work to find the EOF so that you dont give something to it.</p>\n\n<p><strong>Simply, exclude it;</strong></p>\n\n<pre><code>for (iter = someMap.begin(); someMap.end() - 1; ++iter) {\n //apply to all from begin to second last element\n}\n</code></pre>\n\n<p><strong>KISS (KEEP IT SIMPLY SIMPLE)</strong></p>\n"
},
{
"answer_id": 33475580,
"author": "Todoroki",
"author_id": 4145123,
"author_profile": "https://Stackoverflow.com/users/4145123",
"pm_score": 1,
"selected": false,
"text": "<p>How about this, no one mentioning but...</p>\n\n<pre><code>for (iter = someMap.begin(); iter != someMap.end(); ++iter) {\n // do something for all iterations\n if (iter != --someMap.end()) {\n // do something for all but the last iteration\n }\n}\n</code></pre>\n\n<p>this seems simple, mm...</p>\n"
},
{
"answer_id": 34222218,
"author": "dutchdukes",
"author_id": 2392704,
"author_profile": "https://Stackoverflow.com/users/2392704",
"pm_score": 5,
"selected": false,
"text": "<p>Since C++11, you can also use std::next()</p>\n\n<pre><code> for (auto iter = someMap.begin(); iter != someMap.end(); ++iter) { \n // do something for all iterations\n if (std::next(iter) != someMap.end()) {\n // do something for all but the last iteration\n }\n }\n</code></pre>\n\n<p>Although the question was asked a while ago, I thought it would be worth sharing.</p>\n"
},
{
"answer_id": 59188201,
"author": "alfred",
"author_id": 12483466,
"author_profile": "https://Stackoverflow.com/users/12483466",
"pm_score": 1,
"selected": false,
"text": "<p>For someone who likes C++11 range-based loop:</p>\n\n<pre><code> for (const auto& pair : someMap) {\n if (&pair != &*someMap.rbegin()) ...\n }\n</code></pre>\n\n<p>Notice only reference type works here, not <code>auto pair</code></p>\n"
}
]
| 2008/09/29 | [
"https://Stackoverflow.com/questions/151046",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3594/"
]
| I'm trying to figure out the best way to determine whether I'm in the last iteration of a loop over a map in order to do something like the following:
```
for (iter = someMap.begin(); iter != someMap.end(); ++iter) {
bool last_iteration;
// do something for all iterations
if (!last_iteration) {
// do something for all but the last iteration
}
}
```
There seem to be several ways of doing this: random access iterators, the `distance` function, etc. What's the canonical method?
Edit: no random access iterators for maps! | Canonical? I can't claim that, but I'd suggest
```
final_iter = someMap.end();
--final_iter;
if (iter != final_iter) ...
```
**Edited** to correct as suggested by **[KTC](https://stackoverflow.com/questions/151046/c-last-loop-iteration-stl-map-iterator#151104).** (Thanks! Sometimes you go too quick and mess up on the simplest things...) |
151,051 | <p>In .NET, under which circumstances should I use <code>GC.SuppressFinalize()</code>?</p>
<p>What advantage(s) does using this method give me?</p>
| [
{
"answer_id": 151058,
"author": "albertein",
"author_id": 23020,
"author_profile": "https://Stackoverflow.com/users/23020",
"pm_score": -1,
"selected": false,
"text": "<p>That method must be called on the <code>Dispose</code> method of objects that implements the <code>IDisposable</code>, in this way the GC wouldn't call the finalizer another time if someones calls the <code>Dispose</code> method.</p>\n\n<p>See: <a href=\"https://learn.microsoft.com/en-us/dotnet/api/system.gc.suppressfinalize\" rel=\"nofollow noreferrer\">GC.SuppressFinalize(Object) Method - Microsoft Docs</a></p>\n"
},
{
"answer_id": 151059,
"author": "Michael Burr",
"author_id": 12711,
"author_profile": "https://Stackoverflow.com/users/12711",
"pm_score": 6,
"selected": false,
"text": "<p><code>SupressFinalize</code> tells the system that whatever work would have been done in the finalizer has already been done, so the finalizer doesn't need to be called. From the .NET docs:</p>\n\n<blockquote>\n <p>Objects that implement the IDisposable\n interface can call this method from\n the IDisposable.Dispose method to\n prevent the garbage collector from\n calling Object.Finalize on an\n object that does not require it.</p>\n</blockquote>\n\n<p>In general, most any <code>Dispose()</code> method should be able to call <code>GC.SupressFinalize()</code>, because it should clean up everything that would be cleaned up in the finalizer.</p>\n\n<p><code>SupressFinalize</code> is just something that provides an optimization that allows the system to not bother queuing the object to the finalizer thread. A properly written <code>Dispose()</code>/finalizer should work properly with or without a call to <code>GC.SupressFinalize()</code>.</p>\n"
},
{
"answer_id": 151244,
"author": "Robert Paulson",
"author_id": 14033,
"author_profile": "https://Stackoverflow.com/users/14033",
"pm_score": 10,
"selected": true,
"text": "<p><code>SuppressFinalize</code> should only be called by a class that has a finalizer. It's informing the Garbage Collector (GC) that <code>this</code> object was cleaned up fully.</p>\n\n<p>The recommended <code>IDisposable</code> pattern when you have a finalizer is:</p>\n\n<pre><code>public class MyClass : IDisposable\n{\n private bool disposed = false;\n\n protected virtual void Dispose(bool disposing)\n {\n if (!disposed)\n {\n if (disposing)\n {\n // called via myClass.Dispose(). \n // OK to use any private object references\n }\n // Release unmanaged resources.\n // Set large fields to null. \n disposed = true;\n }\n }\n\n public void Dispose() // Implement IDisposable\n {\n Dispose(true);\n GC.SuppressFinalize(this);\n }\n\n ~MyClass() // the finalizer\n {\n Dispose(false);\n }\n}\n</code></pre>\n\n<p>Normally, the CLR keeps tabs on objects with a finalizer when they are created (making them more expensive to create). <code>SuppressFinalize</code> tells the GC that the object was cleaned up properly and doesn't need to go onto the finalizer queue. It looks like a C++ destructor, but doesn't act anything like one.</p>\n\n<p>The <code>SuppressFinalize</code> optimization is not trivial, as your objects can live a long time waiting on the finalizer queue. Don't be tempted to call <code>SuppressFinalize</code> on other objects mind you. That's a serious defect waiting to happen.</p>\n\n<p>Design guidelines inform us that a finalizer isn't necessary if your object implements <code>IDisposable</code>, but if you have a finalizer you should implement <code>IDisposable</code> to allow deterministic cleanup of your class.</p>\n\n<p>Most of the time you should be able to get away with <code>IDisposable</code> to clean up resources. You should only need a finalizer when your object holds onto unmanaged resources and you need to guarantee those resources are cleaned up. </p>\n\n<p>Note: Sometimes coders will add a finalizer to debug builds of their own <code>IDisposable</code> classes in order to test that code has disposed their <code>IDisposable</code> object properly. </p>\n\n<pre><code>public void Dispose() // Implement IDisposable\n{\n Dispose(true);\n#if DEBUG\n GC.SuppressFinalize(this);\n#endif\n}\n\n#if DEBUG\n~MyClass() // the finalizer\n{\n Dispose(false);\n}\n#endif\n</code></pre>\n"
},
{
"answer_id": 49848638,
"author": "Max CHien",
"author_id": 3350329,
"author_profile": "https://Stackoverflow.com/users/3350329",
"pm_score": 2,
"selected": false,
"text": "<pre><code>Dispose(true);\nGC.SuppressFinalize(this);\n</code></pre>\n<p>If object has finalizer, .net put a reference in finalization queue.</p>\n<p>Since we have call <code>Dispose(true)</code>, it clear object, so we don't need finalization queue to do this job.</p>\n<p>So call <code>GC.SuppressFinalize(this)</code> remove reference in finalization queue.</p>\n"
},
{
"answer_id": 50053055,
"author": "supercat",
"author_id": 363751,
"author_profile": "https://Stackoverflow.com/users/363751",
"pm_score": 1,
"selected": false,
"text": "<p>If a class, or anything derived from it, might hold the last live reference to an object with a finalizer, then either <code>GC.SuppressFinalize(this)</code> or <code>GC.KeepAlive(this)</code> should be called on the object after any operation that might be adversely affected by that finalizer, thus ensuring that the finalizer won't run until after that operation is complete.</p>\n\n<p>The cost of <code>GC.KeepAlive()</code> and <code>GC.SuppressFinalize(this)</code> are essentially the same in any class that doesn't have a finalizer, and classes that do have finalizers should generally call <code>GC.SuppressFinalize(this)</code>, so using the latter function as the last step of <code>Dispose()</code> may not always be necessary, but it won't be wrong.</p>\n"
}
]
| 2008/09/29 | [
"https://Stackoverflow.com/questions/151051",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/17174/"
]
| In .NET, under which circumstances should I use `GC.SuppressFinalize()`?
What advantage(s) does using this method give me? | `SuppressFinalize` should only be called by a class that has a finalizer. It's informing the Garbage Collector (GC) that `this` object was cleaned up fully.
The recommended `IDisposable` pattern when you have a finalizer is:
```
public class MyClass : IDisposable
{
private bool disposed = false;
protected virtual void Dispose(bool disposing)
{
if (!disposed)
{
if (disposing)
{
// called via myClass.Dispose().
// OK to use any private object references
}
// Release unmanaged resources.
// Set large fields to null.
disposed = true;
}
}
public void Dispose() // Implement IDisposable
{
Dispose(true);
GC.SuppressFinalize(this);
}
~MyClass() // the finalizer
{
Dispose(false);
}
}
```
Normally, the CLR keeps tabs on objects with a finalizer when they are created (making them more expensive to create). `SuppressFinalize` tells the GC that the object was cleaned up properly and doesn't need to go onto the finalizer queue. It looks like a C++ destructor, but doesn't act anything like one.
The `SuppressFinalize` optimization is not trivial, as your objects can live a long time waiting on the finalizer queue. Don't be tempted to call `SuppressFinalize` on other objects mind you. That's a serious defect waiting to happen.
Design guidelines inform us that a finalizer isn't necessary if your object implements `IDisposable`, but if you have a finalizer you should implement `IDisposable` to allow deterministic cleanup of your class.
Most of the time you should be able to get away with `IDisposable` to clean up resources. You should only need a finalizer when your object holds onto unmanaged resources and you need to guarantee those resources are cleaned up.
Note: Sometimes coders will add a finalizer to debug builds of their own `IDisposable` classes in order to test that code has disposed their `IDisposable` object properly.
```
public void Dispose() // Implement IDisposable
{
Dispose(true);
#if DEBUG
GC.SuppressFinalize(this);
#endif
}
#if DEBUG
~MyClass() // the finalizer
{
Dispose(false);
}
#endif
``` |
151,066 | <p>I have a Ruby/Rails app that has two or three main "sections". When a user visits that section, I wish to display some sub-navigation. All three sections use the same layout, so I can't "hard code" the navigation into the layout.</p>
<p>I can think of a few different methods to do this. I guess in order to help people vote I'll put them as answers.</p>
<p>Any other ideas? Or what do you vote for?</p>
| [
{
"answer_id": 151071,
"author": "Matt Rogish",
"author_id": 2590,
"author_profile": "https://Stackoverflow.com/users/2590",
"pm_score": 3,
"selected": false,
"text": "<ol start=\"3\">\n<li><strong>Partial render</strong>. This is very similar to the helper method except perhaps the layout would have some if statements, or pass that off to a helper...</li>\n</ol>\n"
},
{
"answer_id": 151266,
"author": "madlep",
"author_id": 14160,
"author_profile": "https://Stackoverflow.com/users/14160",
"pm_score": 1,
"selected": false,
"text": "<p>You could use something like the navigation plugin at <a href=\"http://rpheath.com/posts/309-rails-plugin-navigation-helper\" rel=\"nofollow noreferrer\">http://rpheath.com/posts/309-rails-plugin-navigation-helper</a></p>\n\n<p>It doesn't do sub-section navigation out of the box, but with a little tweaking you could probably set it up to do something similar.</p>\n"
},
{
"answer_id": 151289,
"author": "webmat",
"author_id": 6349,
"author_profile": "https://Stackoverflow.com/users/6349",
"pm_score": 1,
"selected": false,
"text": "<p>I suggest you use partials. There are a few ways you can go about it. When I create partials that are a bit picky in that they need specific variables, I also create a helper method for it.</p>\n\n<pre><code>module RenderHelper\n #options: a nested array of menu names and their corresponding url\n def render_submenu(menu_items=[[]])\n render :partial => 'shared/submenu', :locals => {:menu_items => menu_items}\n end\nend\n</code></pre>\n\n<p>Now the partial has a local variable named menu_items over which you can iterate to create your submenu. Note that I suggest a nested array instead of a hash because a hash's order is unpredictable.</p>\n\n<p>Note that the logic deciding what items should be displayed in the menu could also be inside render_submenu if that makes more sense to you.</p>\n"
},
{
"answer_id": 151311,
"author": "webmat",
"author_id": 6349,
"author_profile": "https://Stackoverflow.com/users/6349",
"pm_score": 3,
"selected": false,
"text": "<p>As for the content of your submenus, you can go at it in a declarative manner in each controller.</p>\n\n<pre><code>class PostsController < ApplicationController\n#...\nprotected\n helper_method :menu_items\n def menu_items\n [\n ['Submenu 1', url_for(me)],\n ['Submenu 2', url_for(you)]\n ]\n end\nend\n</code></pre>\n\n<p>Now whenever you call menu_items from a view, you'll have the right list to iterate over for the specific controller.</p>\n\n<p>This strikes me as a cleaner solution than putting this logic inside view templates.</p>\n\n<p>Note that you may also want to declare a default (empty?) menu_items inside ApplicationController as well.</p>\n"
},
{
"answer_id": 152189,
"author": "Patrick McKenzie",
"author_id": 15046,
"author_profile": "https://Stackoverflow.com/users/15046",
"pm_score": 2,
"selected": false,
"text": "<p><strong>Warning: Advanced Tricks ahead!</strong></p>\n\n<p><em>Render them all</em>. Hide the ones that you don't need using CSS/Javascript, which can be trivially initialized in any number of ways. (Javascript can read the URL used, query parameters, something in a cookie, etc etc.) This has the advantage of potentially playing much better with your cache (why cache three views and then have to expire them all simultaneously when you can cache one?), and can be used to present a better user experience. </p>\n\n<p><strong>For example</strong>, let's pretend you have a common tab bar interface with sub navigation. If you render the content of all three tabs (i.e. its written in the HTML) and hide two of them, switching between two tabs is trivial Javascript and <strong>doesn't even hit your server</strong>. Big win! No latency for the user. No server load for you.</p>\n\n<p>Want <strong>another big win</strong>? You can use a variation on this technique to cheat on pages which might but 99% common across users but still contain user state. For example, you might have a front page of a site which is relatively common across all users but say \"Hiya Bob\" when they're logged in. Put the non-common part (\"Hiya, Bob\") in a cookie. Have that part of the page be read in via Javascript reading the cookie. <strong>Cache the entire page for <em>all users regardless of login status</em> in page caching.</strong> This is literally capable of slicing 70% of the accesses off from the entire Rails stack on some sites.</p>\n\n<p>Who cares if Rails can scale or not when your site is really Nginx serving static assets with new HTML pages occasionally getting delivered by some Ruby running on every thousandth access or so ;)</p>\n"
},
{
"answer_id": 156971,
"author": "Christoph Schiessl",
"author_id": 20467,
"author_profile": "https://Stackoverflow.com/users/20467",
"pm_score": 1,
"selected": false,
"text": "<p>I asked pretty much the same question myself: <a href=\"https://stackoverflow.com/questions/126238/need-advice-structure-of-rails-views-for-submenus\">Need advice: Structure of Rails views for submenus?</a> The best solution was probably to use partials.</p>\n"
},
{
"answer_id": 157410,
"author": "Jason Miesionczek",
"author_id": 18811,
"author_profile": "https://Stackoverflow.com/users/18811",
"pm_score": 1,
"selected": false,
"text": "<p>There is another possible way to do this: Nested Layouts</p>\n\n<p>i don't remember where i found this code so apologies to the original author.</p>\n\n<p>create a file called nested_layouts.rb in your lib folder and include the following code:</p>\n\n<pre><code>module NestedLayouts\n def render(options = nil, &block)\n if options\n if options[:layout].is_a?(Array)\n layouts = options.delete(:layout)\n options[:layout] = layouts.pop\n inner_layout = layouts.shift\n options[:text] = layouts.inject(render_to_string(options.merge({:layout=>inner_layout}))) do |output,layout|\n render_to_string(options.merge({:text => output, :layout => layout}))\n end\n end\n end\n super\n end\nend\n</code></pre>\n\n<p>then, create your various layouts in the layouts folder, (for example 'admin.rhtml' and 'application.rhtml').</p>\n\n<p>Now in your controllers add this just inside the class:</p>\n\n<pre><code>include NestedLayouts\n</code></pre>\n\n<p>And finally at the end of your actions do this:</p>\n\n<pre><code>def show\n ...\n render :layout => ['admin','application']\nend\n</code></pre>\n\n<p>the order of the layouts in the array is important. The admin layout will be rendered inside the application layout wherever the 'yeild' is.</p>\n\n<p>this method can work really well depending on the design of the site and how the various elements are organized. for instance one of the included layouts could just contain a series of divs that contain the content that needs to be shown for a particular action, and the CSS on a higher layout could control where they are positioned.</p>\n"
},
{
"answer_id": 157469,
"author": "Olly",
"author_id": 1174,
"author_profile": "https://Stackoverflow.com/users/1174",
"pm_score": 4,
"selected": true,
"text": "<p>You can easily do this using partials, assuming each section has it's own controller.</p>\n\n<p>Let's say you have three sections called <strong>Posts</strong>, <strong>Users</strong> and <strong>Admin</strong>, each with it's own controller: <code>PostsController</code>, <code>UsersController</code> and <code>AdminController</code>.</p>\n\n<p>In each corresponding <code>views</code> directory, you declare a <code>_subnav.html.erb</code> partial:</p>\n\n<pre>\n/app/views/users/_subnav.html.erb\n/app/views/posts/_subnav.html.erb\n/app/views/admin/_subnav.html.erb\n</pre>\n\n<p>In each of these subnav partials you declare the options specific to that section, so <code>/users/_subnav.html.erb</code> might contain:</p>\n\n<pre><code><ul id=\"subnav\">\n <li><%= link_to 'All Users', users_path %></li>\n <li><%= link_to 'New User', new_user_path %></li>\n</ul>\n</code></pre>\n\n<p>Whilst <code>/posts/_subnav.html.erb</code> might contain:</p>\n\n<pre><code><ul id=\"subnav\">\n <li><%= link_to 'All Posts', posts_path %></li>\n <li><%= link_to 'New Post', new_post_path %></li>\n</ul>\n</code></pre>\n\n<p>Finally, once you've done this, you just need to include the subnav partial in the layout:</p>\n\n<pre><code><div id=\"header\">...</div> \n<%= render :partial => \"subnav\" %>\n<div id=\"content\"><%= yield %></div>\n<div id=\"footer\">...</div>\n</code></pre>\n"
},
{
"answer_id": 394212,
"author": "maurycy",
"author_id": 48541,
"author_profile": "https://Stackoverflow.com/users/48541",
"pm_score": 0,
"selected": false,
"text": "<p>There are few approaches to this problem.</p>\n\n<p>You might want to use different layouts for each section.</p>\n\n<p>You might want to use a partial included by all views in a given directory. </p>\n\n<p>You might want to use <code>content_for</code> that is filled by either a view or a partial, and called in the global layout, if you have one.</p>\n\n<p>Personally I believe that you should avoid more abstraction in this case. </p>\n"
}
]
| 2008/09/29 | [
"https://Stackoverflow.com/questions/151066",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2590/"
]
| I have a Ruby/Rails app that has two or three main "sections". When a user visits that section, I wish to display some sub-navigation. All three sections use the same layout, so I can't "hard code" the navigation into the layout.
I can think of a few different methods to do this. I guess in order to help people vote I'll put them as answers.
Any other ideas? Or what do you vote for? | You can easily do this using partials, assuming each section has it's own controller.
Let's say you have three sections called **Posts**, **Users** and **Admin**, each with it's own controller: `PostsController`, `UsersController` and `AdminController`.
In each corresponding `views` directory, you declare a `_subnav.html.erb` partial:
```
/app/views/users/_subnav.html.erb
/app/views/posts/_subnav.html.erb
/app/views/admin/_subnav.html.erb
```
In each of these subnav partials you declare the options specific to that section, so `/users/_subnav.html.erb` might contain:
```
<ul id="subnav">
<li><%= link_to 'All Users', users_path %></li>
<li><%= link_to 'New User', new_user_path %></li>
</ul>
```
Whilst `/posts/_subnav.html.erb` might contain:
```
<ul id="subnav">
<li><%= link_to 'All Posts', posts_path %></li>
<li><%= link_to 'New Post', new_post_path %></li>
</ul>
```
Finally, once you've done this, you just need to include the subnav partial in the layout:
```
<div id="header">...</div>
<%= render :partial => "subnav" %>
<div id="content"><%= yield %></div>
<div id="footer">...</div>
``` |
151,079 | <p>My app generates PDFs for user consumption. The "Content-Disposition" http header is set as mentioned <a href="https://stackoverflow.com/questions/74019/specifying-filename-for-dynamic-pdf-in-aspnet">here</a>. This is set to "inline; filename=foo.pdf", which should be enough for Acrobat to give "foo.pdf" as the filename when saving the pdf.</p>
<p>However, upon clicking the "Save" button in the browser-embedded Acrobat, the default name to save is not that filename but instead the URL with slashes changed to underscores. Huge and ugly. Is there a way to affect this default filename in Adobe?</p>
<p>There IS a query string in the URLs, and this is non-negotiable. This may be significant, but adding a "&foo=/title.pdf" to the end of the URL doesn't affect the default filename.</p>
<p>Update 2: I've tried both</p>
<pre><code>content-disposition inline; filename=foo.pdf
Content-Type application/pdf; filename=foo.pdf
</code></pre>
<p>and</p>
<pre><code>content-disposition inline; filename=foo.pdf
Content-Type application/pdf; name=foo.pdf
</code></pre>
<p>(as verified through Firebug) Sadly, neither worked.</p>
<p>A sample url is</p>
<pre>/bar/sessions/958d8a22-0/views/1493881172/export?format=application/pdf&no-attachment=true</pre>
<p>which translates to a default Acrobat save as filename of</p>
<pre>http___localhost_bar_sessions_958d8a22-0_views_1493881172_export_format=application_pdf&no-attachment=true.pdf</pre>
<p>Update 3: Julian Reschke brings actual insight and rigor to this case. Please upvote his answer.
This seems to be broken in FF (<a href="https://bugzilla.mozilla.org/show_bug.cgi?id=433613" rel="nofollow noreferrer">https://bugzilla.mozilla.org/show_bug.cgi?id=433613</a>) and IE but work in Opera, Safari, and Chrome. <a href="http://greenbytes.de/tech/tc2231/#inlwithasciifilenamepdf" rel="nofollow noreferrer">http://greenbytes.de/tech/tc2231/#inlwithasciifilenamepdf</a></p>
| [
{
"answer_id": 151196,
"author": "Vincent McNabb",
"author_id": 16299,
"author_profile": "https://Stackoverflow.com/users/16299",
"pm_score": 0,
"selected": false,
"text": "<p>You could always have two links. One that opens the document inside the browser, and another to download it (using an incorrect content type). This is what Gmail does.</p>\n"
},
{
"answer_id": 151302,
"author": "Vivek",
"author_id": 7418,
"author_profile": "https://Stackoverflow.com/users/7418",
"pm_score": 4,
"selected": false,
"text": "<p>Set the <strong>file name</strong> in <strong>ContentType</strong> as well. This should solve the problem.</p>\n\n<pre><code>context.Response.ContentType = \"application/pdf; name=\" + fileName;\n// the usual stuff\ncontext.Response.AddHeader(\"content-disposition\", \"inline; filename=\" + fileName);\n</code></pre>\n\n<p>After you set content-disposition header, also add content-length header, then use binarywrite to stream the PDF.</p>\n\n<pre><code>context.Response.AddHeader(\"Content-Length\", fileBytes.Length.ToString());\ncontext.Response.BinaryWrite(fileBytes);\n</code></pre>\n"
},
{
"answer_id": 151458,
"author": "ManiacZX",
"author_id": 18148,
"author_profile": "https://Stackoverflow.com/users/18148",
"pm_score": 1,
"selected": false,
"text": "<p>Instead of attachment you can try inline:</p>\n\n<pre><code>Response.AddHeader(\"content-disposition\", \"inline;filename=MyFile.pdf\");\n</code></pre>\n\n<p>I used inline in a previous web application that generated Crystal Reports output into PDF and sent that in browser to the user.</p>\n"
},
{
"answer_id": 339025,
"author": "Troy Howard",
"author_id": 19258,
"author_profile": "https://Stackoverflow.com/users/19258",
"pm_score": 3,
"selected": false,
"text": "<p>Like you, I tried and tried to get this to work. Finally I gave up on this idea, and just opted for a workaround. </p>\n\n<p>I'm using ASP.NET MVC Framework, so I modified my routes for that controller/action to make sure that the served up PDF file is the last part of the location portion of the URI (before the query string), and pass everything else in the query string. </p>\n\n<p>Eg: </p>\n\n<p>Old URI: </p>\n\n<p><a href=\"http://server/app/report/showpdf?param1=foo&param2=bar&filename=myreport.pdf\" rel=\"noreferrer\">http://server/app/report/showpdf?param1=foo&param2=bar&filename=myreport.pdf</a></p>\n\n<p>New URI: </p>\n\n<p><a href=\"http://server/app/report/showpdf/myreport.pdf?param1=foo&param2=bar\" rel=\"noreferrer\">http://server/app/report/showpdf/myreport.pdf?param1=foo&param2=bar</a></p>\n\n<p>The resulting header looks exactly like what you've described (content-type is application/pdf, disposition is inline, filename is uselessly part of the header). Acrobat shows it in the browser window (no save as dialog) and the filename that is auto-populated if a user clicks the Acrobat Save button is the report filename.</p>\n\n<p>A few considerations:</p>\n\n<p>In order for the filenames to look decent, they shouldn't have any escaped characters (ie, no spaces, etc)... which is a bit limiting. My filenames are auto-generated in this case, and before had spaces in them, which were showing up as '%20's in the resulting save dialog filename. I just replaced the spaces with underscores, and that worked out.</p>\n\n<p>This is by no names the best solution, but it does work. It also means that you have to have the filename available to make it part of the original URI, which might mess with your program's workflow. If it's currently being generated or retrieved from a database during the server-side call that generates the PDF, you might need to move the code that generates the filename to javascript as part of a form submission or if it comes from a database make it a quick ajax call to get the filename when building the URL that results in the inlined PDF.</p>\n\n<p>If you're taking the filename from a user input on a form, then that should be validated not to contain escaped characters, which will annoy users.</p>\n\n<p>Hope that helps.</p>\n"
},
{
"answer_id": 441634,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 0,
"selected": false,
"text": "<p>I was redirected here because i have the same problem. I also tried Troy Howard's workaround but it is doesn't seem to work.</p>\n\n<p>The approach I did on this one is to NO LONGER use response object to write the file on the fly. Since the PDF is already existing on the server, what i did was to redirect my page pointing to that PDF file. Works great.</p>\n\n<p><a href=\"http://forums.asp.net/t/143631.aspx\" rel=\"nofollow noreferrer\">http://forums.asp.net/t/143631.aspx</a></p>\n\n<p>I hope my vague explanation gave you an idea.</p>\n"
},
{
"answer_id": 669145,
"author": "Julian Reschke",
"author_id": 50543,
"author_profile": "https://Stackoverflow.com/users/50543",
"pm_score": 5,
"selected": true,
"text": "<p>Part of the problem is that the relevant <a href=\"http://greenbytes.de/tech/webdav/rfc2183.html\" rel=\"noreferrer\">RFC 2183</a> doesn't really state what to do with a disposition type of \"inline\" and a filename.</p>\n\n<p>Also, as far as I can tell, the only UA that actually uses the filename for type=inline is Firefox (see <a href=\"http://greenbytes.de/tech/tc2231/#inlwithasciifilename\" rel=\"noreferrer\">test case</a>).</p>\n\n<p>Finally, it's not obvious that the plugin API actually makes that information available (maybe someboy familiar with the API can elaborate).</p>\n\n<p>That being said, I have sent a pointer to this question to an Adobe person; maybe the right people will have a look.</p>\n\n<p>Related: see attempt to clarify Content-Disposition in HTTP in <a href=\"http://greenbytes.de/tech/webdav/draft-reschke-rfc2183-in-http-latest.html\" rel=\"noreferrer\">draft-reschke-rfc2183-in-http</a> -- this is early work in progress, feedback appreciated.</p>\n\n<p>Update: I have added a <a href=\"http://greenbytes.de/tech/tc2231/#inlwithasciifilenamepdf\" rel=\"noreferrer\">test case</a>, which seems to indicate that the Acrobat reader plugin doesn't use the response headers (in Firefox), although the plugin API provides access to them.</p>\n"
},
{
"answer_id": 723528,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": -1,
"selected": false,
"text": "<p>Try this, if your executable is \"get.cgi\"</p>\n\n<p><a href=\"http://server,org/get.cgi/filename.pdf?file=filename.pdf\" rel=\"nofollow noreferrer\">http://server,org/get.cgi/filename.pdf?file=filename.pdf</a></p>\n\n<p>Yes, it's completely insane. There is no file called \"filename.pdf\" on the server, there is directory at all under the executable get.cgi. </p>\n\n<p>But it seems to work. The server ignores the filename.pdf and the pdf reader ignores the \"get.cgi\" </p>\n\n<p>Dan</p>\n"
},
{
"answer_id": 864492,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 1,
"selected": false,
"text": "<p>I believe this has already been mentioned in one flavor or another but I'll try and state it in my own words.</p>\n\n<p>Rather than this:</p>\n\n<pre><code>/bar/sessions/958d8a22-0/views/1493881172/export?format=application/pdf&no-attachment=true\n</code></pre>\n\n<p>I use this:</p>\n\n<pre><code>/bar/sessions/958d8a22-0/views/1493881172/NameThatIWantPDFToBe.pdf?GeneratePDF=1\n</code></pre>\n\n<p>Rather than having \"export\" process the request, when a request comes in, I look in the URL for GeneratePDF=1. If found, I run whatever code was running in \"export\" rather than allowing my system to attempt to search and serve a PDF in the location <code>/bar/sessions/958d8a22-0/views/1493881172/NameThatIWantPDFToBe.pdf</code>. If GeneratePDF is not found in the URL, I simply transmit the file requested. (note that I can't simply redirect to the file requested - or else I'd end up in an endless loop)</p>\n"
},
{
"answer_id": 898179,
"author": "Fabrizio Accatino",
"author_id": 21145,
"author_profile": "https://Stackoverflow.com/users/21145",
"pm_score": 2,
"selected": false,
"text": "<p>If you use asp.net, you can control pdf filename through page (url) file name.\nAs other users wrote, Acrobat is a bit s... when it choose the pdf file name when you press \"save\" button: it takes the page name, removes the extension and add \".pdf\". \nSo /foo/bar/GetMyPdf.aspx gives GetMyPdf.pdf.</p>\n\n<p>The only solution I found is to manage \"dynamic\" page names through an asp.net handler: </p>\n\n<ul>\n<li>create a class that implements IHttpHandler </li>\n<li>map an handler in web.config bounded to the class</li>\n</ul>\n\n<p>Mapping1: all pages have a common radix (MyDocument_):</p>\n\n<pre><code><httpHandlers> \n<add verb=\"*\" path=\"MyDocument_*.ashx\" type=\"ITextMiscWeb.MyDocumentHandler\"/>\n</code></pre>\n\n<p>Mapping2: completely free file name (need a folder in path): </p>\n\n<pre><code><add verb=\"*\" path=\"/CustomName/*.ashx\" type=\"ITextMiscWeb.MyDocumentHandler\"/>\n</code></pre>\n\n<p>Some tips here (the pdf is dynamically created using iTextSharp):<br>\n<a href=\"http://fhtino.blogspot.com/2006/11/how-to-show-or-download-pdf-file-from.html\" rel=\"nofollow noreferrer\">http://fhtino.blogspot.com/2006/11/how-to-show-or-download-pdf-file-from.html</a></p>\n"
},
{
"answer_id": 1805495,
"author": "Rick Cooper",
"author_id": 219673,
"author_profile": "https://Stackoverflow.com/users/219673",
"pm_score": 0,
"selected": false,
"text": "<p>The way I solved this (with PHP) is as follows:</p>\n\n<p>Suppose your URL is <code>SomeScript.php?id=ID&data=DATA</code> and the file you want to use is <code>TEST.pdf</code>.</p>\n\n<p>Change the URL to <code>SomeScript.php/id/ID/data/DATA/EXT/TEST.pdf</code>.</p>\n\n<p>It's important that the last parameter is the file name you want Adobe to use (the 'EXT' can be about anything). Make sure there are no special chars in the above string, BTW.</p>\n\n<p>Now, at the top of <code>SomeScript.php</code>, add:</p>\n\n<pre><code>$_REQUEST = MakeFriendlyURI( $_SERVER['PHP\\_SELF'], $_SERVER['SCRIPT_FILENAME']);\n</code></pre>\n\n<p>Then add this function to <code>SomeScript.php</code> (or your function library):</p>\n\n<pre><code>function MakeFriendlyURI($URI, $ScriptName) {\n\n/* Need to remove everything up to the script name */\n$MyName = '/^.*'.preg_quote(basename($ScriptName).\"/\", '/').'/';\n$Str = preg_replace($MyName,'',$URI);\n$RequestArray = array();\n\n/* Breaks down like this\n 0 1 2 3 4 5\n PARAM1/VAL1/PARAM2/VAL2/PARAM3/VAL3\n*/\n\n$tmp = explode('/',$Str); \n/* Ok so build an associative array with Key->value\n This way it can be returned back to $_REQUEST or $_GET\n */\nfor ($i=0;$i < count($tmp); $i = $i+2){\n $RequestArray[$tmp[$i]] = $tmp[$i+1];\n}\nreturn $RequestArray; \n}//EO MakeFriendlyURI\n</code></pre>\n\n<p>Now <code>$_REQUEST</code> (or <code>$_GET</code> if you prefer) is accessed like normal <code>$_REQUEST['id']</code>, <code>$_REQUEST['data']</code>, etc.</p>\n\n<p>And Adobe will use your desired file name as the default save as or email info when you send it inline.</p>\n"
},
{
"answer_id": 2015651,
"author": "Brian",
"author_id": 245007,
"author_profile": "https://Stackoverflow.com/users/245007",
"pm_score": 0,
"selected": false,
"text": "<p>For anyone still looking at this, I used the solution found <a href=\"http://docs.google.com/View?docid=dchmct9k_9dxkdwk\" rel=\"nofollow noreferrer\">here</a> and it worked wonderfully. Thanks Fabrizio!</p>\n"
},
{
"answer_id": 4477176,
"author": "Sunder Chhokar",
"author_id": 546858,
"author_profile": "https://Stackoverflow.com/users/546858",
"pm_score": 1,
"selected": false,
"text": "<p>File download dialog (PDF) with save and open option</p>\n\n<p>Points To Remember:</p>\n\n<ol>\n<li>Return Stream with correct array size from service</li>\n<li>Read the byte arrary from stream with correct byte length on the basis of stream length.</li>\n<li>set correct contenttype</li>\n</ol>\n\n<p>Here is the code for read stream and open the File download dialog for PDF file</p>\n\n<pre><code>private void DownloadSharePointDocument()\n{\n Uri uriAddress = new Uri(\"http://hyddlf5187:900/SharePointDownloadService/FulfillmentDownload.svc/GetDocumentByID/1/drmfree/\");\n HttpWebRequest req = WebRequest.Create(uriAddress) as HttpWebRequest;\n // Get response \n using (HttpWebResponse httpWebResponse = req.GetResponse() as HttpWebResponse)\n {\n Stream stream = httpWebResponse.GetResponseStream();\n int byteCount = Convert.ToInt32(httpWebResponse.ContentLength);\n byte[] Buffer1 = new byte[byteCount];\n using (BinaryReader reader = new BinaryReader(stream))\n {\n Buffer1 = reader.ReadBytes(byteCount);\n }\n Response.Clear();\n Response.ClearHeaders();\n // set the content type to PDF \n Response.ContentType = \"application/pdf\";\n Response.AddHeader(\"Content-Disposition\", \"attachment;filename=Filename.pdf\");\n Response.Buffer = true;\n Response.BinaryWrite(Buffer1);\n Response.Flush();\n // Response.End();\n }\n}\n</code></pre>\n"
},
{
"answer_id": 4534492,
"author": "Karsten",
"author_id": 554378,
"author_profile": "https://Stackoverflow.com/users/554378",
"pm_score": 2,
"selected": false,
"text": "<p>In ASP.NET 2.0 change the URL from </p>\n\n<pre><code>http://www. server.com/DocServe.aspx?DocId=XXXXXXX\n</code></pre>\n\n<p>to </p>\n\n<pre><code>http://www. server.com/DocServe.aspx/MySaveAsFileName?DocId=XXXXXXX\n</code></pre>\n\n<p>This works for Acrobat 8 and the default SaveAs filename is now <code>MySaveAsFileName.pdf</code>. </p>\n\n<p>However, you have to restrict the allowed characters in <code>MySaveAsFileName</code> (no periods, etc.).</p>\n"
},
{
"answer_id": 6852514,
"author": "Mark Nettle",
"author_id": 866460,
"author_profile": "https://Stackoverflow.com/users/866460",
"pm_score": 2,
"selected": false,
"text": "<p>Apache's <code>mod_rewrite</code> can solve this.</p>\n\n<p>I have a web service with an endpoint at <code>/foo/getDoc.service</code>. Of course Acrobat will save files as <code>getDoc.pdf</code>. I added the following lines in <code>apache.conf</code>:</p>\n\n<pre><code>LoadModule RewriteModule modules/mod_rewrite.so\nRewriteEngine on\nRewriteRule ^/foo/getDoc/(.*)$ /foo/getDoc.service [P,NE]\n</code></pre>\n\n<p>Now when I request <code>/foo/getDoc/filename.pdf?bar&qux</code>, it gets internally rewritten to <code>/foo/getDoc.service?bar&qux</code>, so I'm hitting the correct endpoint of the web service, but Acrobat thinks it will save my file as <code>filename.pdf</code>.</p>\n"
},
{
"answer_id": 8361359,
"author": "tekkgurrl",
"author_id": 1078074,
"author_profile": "https://Stackoverflow.com/users/1078074",
"pm_score": 3,
"selected": false,
"text": "<p>Try placing the file name at the end of the URL, before any other parameters. This worked for me.\n<a href=\"http://www.setasign.de/support/tips-and-tricks/filename-in-browser-plugin/\" rel=\"noreferrer\">http://www.setasign.de/support/tips-and-tricks/filename-in-browser-plugin/</a></p>\n"
},
{
"answer_id": 51303129,
"author": "qräbnö",
"author_id": 1707015,
"author_profile": "https://Stackoverflow.com/users/1707015",
"pm_score": 0,
"selected": false,
"text": "<p>Credits to <a href=\"https://stackoverflow.com/users/7418/vivek\">Vivek</a>.</p>\n\n<hr>\n\n<h1>Nginx</h1>\n\n<pre><code>location /file.pdf\n{\n # more_set_headers \"Content-Type: application/pdf; name=save_as_file.pdf\";\n add_header Content-Disposition \"inline; filename=save_as_file.pdf\";\n alias /var/www/file.pdf;\n}\n</code></pre>\n\n<p>Check with</p>\n\n<pre><code>curl -I https://example.com/file.pdf\n</code></pre>\n\n<p>Firefox 62.0b5 (64-bit): OK.</p>\n\n<p>Chrome 67.0.3396.99 (64-Bit): OK.</p>\n\n<p>IE 11: No comment.</p>\n"
}
]
| 2008/09/29 | [
"https://Stackoverflow.com/questions/151079",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9365/"
]
| My app generates PDFs for user consumption. The "Content-Disposition" http header is set as mentioned [here](https://stackoverflow.com/questions/74019/specifying-filename-for-dynamic-pdf-in-aspnet). This is set to "inline; filename=foo.pdf", which should be enough for Acrobat to give "foo.pdf" as the filename when saving the pdf.
However, upon clicking the "Save" button in the browser-embedded Acrobat, the default name to save is not that filename but instead the URL with slashes changed to underscores. Huge and ugly. Is there a way to affect this default filename in Adobe?
There IS a query string in the URLs, and this is non-negotiable. This may be significant, but adding a "&foo=/title.pdf" to the end of the URL doesn't affect the default filename.
Update 2: I've tried both
```
content-disposition inline; filename=foo.pdf
Content-Type application/pdf; filename=foo.pdf
```
and
```
content-disposition inline; filename=foo.pdf
Content-Type application/pdf; name=foo.pdf
```
(as verified through Firebug) Sadly, neither worked.
A sample url is
```
/bar/sessions/958d8a22-0/views/1493881172/export?format=application/pdf&no-attachment=true
```
which translates to a default Acrobat save as filename of
```
http___localhost_bar_sessions_958d8a22-0_views_1493881172_export_format=application_pdf&no-attachment=true.pdf
```
Update 3: Julian Reschke brings actual insight and rigor to this case. Please upvote his answer.
This seems to be broken in FF (<https://bugzilla.mozilla.org/show_bug.cgi?id=433613>) and IE but work in Opera, Safari, and Chrome. <http://greenbytes.de/tech/tc2231/#inlwithasciifilenamepdf> | Part of the problem is that the relevant [RFC 2183](http://greenbytes.de/tech/webdav/rfc2183.html) doesn't really state what to do with a disposition type of "inline" and a filename.
Also, as far as I can tell, the only UA that actually uses the filename for type=inline is Firefox (see [test case](http://greenbytes.de/tech/tc2231/#inlwithasciifilename)).
Finally, it's not obvious that the plugin API actually makes that information available (maybe someboy familiar with the API can elaborate).
That being said, I have sent a pointer to this question to an Adobe person; maybe the right people will have a look.
Related: see attempt to clarify Content-Disposition in HTTP in [draft-reschke-rfc2183-in-http](http://greenbytes.de/tech/webdav/draft-reschke-rfc2183-in-http-latest.html) -- this is early work in progress, feedback appreciated.
Update: I have added a [test case](http://greenbytes.de/tech/tc2231/#inlwithasciifilenamepdf), which seems to indicate that the Acrobat reader plugin doesn't use the response headers (in Firefox), although the plugin API provides access to them. |
151,083 | <p>Having this route:</p>
<pre><code>map.foo 'foo/*path', :controller => 'foo', :action => 'index'
</code></pre>
<p>I have the following results for the <code>link_to</code> call</p>
<pre><code>link_to "Foo", :controller => 'foo', :path => 'bar/baz'
# <a href="/foo/bar%2Fbaz">Foo</a>
</code></pre>
<p>Calling <code>url_for</code> or <code>foo_url</code> directly, even with <code>:escape => false</code>, give me the same url:</p>
<pre><code>foo_url(:path => 'bar/baz', :escape => false, :only_path => true)
# /foo/bar%2Fbaz
</code></pre>
<p>I want the resulting url to be: <code>/foo/bar/baz</code></p>
<p>Is there a way around this without patching rails?</p>
| [
{
"answer_id": 151239,
"author": "Gordon Wilson",
"author_id": 23071,
"author_profile": "https://Stackoverflow.com/users/23071",
"pm_score": 3,
"selected": true,
"text": "<p>Instead of passing path a string, give it an array.</p>\n\n<pre><code>link_to \"Foo\", :controller => 'foo', :path => %w(bar baz)\n# <a href=\"/foo/bar/baz\">Foo</a>\n</code></pre>\n\n<p>If you didn't have the route in your routes file, this same link_to would instead create this:</p>\n\n<pre><code># <a href=\"/foo?path[]=bar&path[]=baz\">Foo</a>\n</code></pre>\n\n<p>The only place I could find this documented is in <a href=\"http://dev.rubyonrails.org/ticket/7047\" rel=\"nofollow noreferrer\">this ticket</a>.</p>\n"
},
{
"answer_id": 151279,
"author": "madlep",
"author_id": 14160,
"author_profile": "https://Stackoverflow.com/users/14160",
"pm_score": -1,
"selected": false,
"text": "<p>Any reason why you're needing to generate the URL with that path though?</p>\n\n<p>It would be cleaner to just define an extra route to cover that URL.</p>\n"
}
]
| 2008/09/29 | [
"https://Stackoverflow.com/questions/151083",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/13989/"
]
| Having this route:
```
map.foo 'foo/*path', :controller => 'foo', :action => 'index'
```
I have the following results for the `link_to` call
```
link_to "Foo", :controller => 'foo', :path => 'bar/baz'
# <a href="/foo/bar%2Fbaz">Foo</a>
```
Calling `url_for` or `foo_url` directly, even with `:escape => false`, give me the same url:
```
foo_url(:path => 'bar/baz', :escape => false, :only_path => true)
# /foo/bar%2Fbaz
```
I want the resulting url to be: `/foo/bar/baz`
Is there a way around this without patching rails? | Instead of passing path a string, give it an array.
```
link_to "Foo", :controller => 'foo', :path => %w(bar baz)
# <a href="/foo/bar/baz">Foo</a>
```
If you didn't have the route in your routes file, this same link\_to would instead create this:
```
# <a href="/foo?path[]=bar&path[]=baz">Foo</a>
```
The only place I could find this documented is in [this ticket](http://dev.rubyonrails.org/ticket/7047). |
151,099 | <p>I have two tables that are joined together. </p>
<p>A has many B</p>
<p>Normally you would do: </p>
<pre><code>select * from a,b where b.a_id = a.id
</code></pre>
<p>To get all of the records from a that has a record in b. </p>
<p>How do I get just the records in a that does not have anything in b?</p>
| [
{
"answer_id": 151102,
"author": "albertein",
"author_id": 23020,
"author_profile": "https://Stackoverflow.com/users/23020",
"pm_score": 8,
"selected": true,
"text": "<pre><code>select * from a where id not in (select a_id from b)\n</code></pre>\n\n<p>Or like some other people on this thread says:</p>\n\n<pre><code>select a.* from a\nleft outer join b on a.id = b.a_id\nwhere b.a_id is null\n</code></pre>\n"
},
{
"answer_id": 151103,
"author": "BlackWasp",
"author_id": 21862,
"author_profile": "https://Stackoverflow.com/users/21862",
"pm_score": 1,
"selected": false,
"text": "<pre><code>SELECT <columnns>\nFROM a WHERE id NOT IN (SELECT a_id FROM b)\n</code></pre>\n"
},
{
"answer_id": 151110,
"author": "Joseph Anderson",
"author_id": 18102,
"author_profile": "https://Stackoverflow.com/users/18102",
"pm_score": 5,
"selected": false,
"text": "<pre><code>select * from a\nleft outer join b on a.id = b.a_id\nwhere b.a_id is null\n</code></pre>\n"
},
{
"answer_id": 151113,
"author": "Matt Hamilton",
"author_id": 615,
"author_profile": "https://Stackoverflow.com/users/615",
"pm_score": 3,
"selected": false,
"text": "<p>Another approach:</p>\n\n<pre><code>select * from a where not exists (select * from b where b.a_id = a.id)\n</code></pre>\n\n<p>The \"exists\" approach is useful if there is some other \"where\" clause you need to attach to the inner query.</p>\n"
},
{
"answer_id": 151119,
"author": "nathan",
"author_id": 16430,
"author_profile": "https://Stackoverflow.com/users/16430",
"pm_score": 2,
"selected": false,
"text": "<p>You will probably get a lot better performance (than using 'not in') if you use an outer join:</p>\n\n<pre><code>select * from a left outer join b on a.id = b.a_id where b.a_id is null;\n</code></pre>\n"
},
{
"answer_id": 151120,
"author": "shahkalpesh",
"author_id": 23574,
"author_profile": "https://Stackoverflow.com/users/23574",
"pm_score": 1,
"selected": false,
"text": "<p>Another way of writing it</p>\n\n<pre><code>select a.*\nfrom a \nleft outer join b\non a.id = b.id\nwhere b.id is null\n</code></pre>\n\n<p>Ouch, beaten by Nathan :)</p>\n"
},
{
"answer_id": 151150,
"author": "Amy B",
"author_id": 8155,
"author_profile": "https://Stackoverflow.com/users/8155",
"pm_score": 0,
"selected": false,
"text": "<p>This will protect you from nulls in the IN clause, which can cause unexpected behavior.</p>\n\n<p>select * from a where id not in (select [a id] from b where <strong>[a id] is not null</strong>)</p>\n"
},
{
"answer_id": 9682494,
"author": "onedaywhen",
"author_id": 15354,
"author_profile": "https://Stackoverflow.com/users/15354",
"pm_score": 3,
"selected": false,
"text": "<pre><code>SELECT id FROM a\nEXCEPT\nSELECT a_id FROM b;\n</code></pre>\n"
},
{
"answer_id": 48116779,
"author": "Petr Štipek",
"author_id": 8517134,
"author_profile": "https://Stackoverflow.com/users/8517134",
"pm_score": 1,
"selected": false,
"text": "<p>In case of one join it is pretty fast, but when we are removing records from database which has about 50 milions records and 4 and more joins due to foreign keys, it takes a few minutes to do it.\nMuch faster to use WHERE NOT IN condition like this:</p>\n\n<pre><code>select a.* from a\nwhere a.id NOT IN(SELECT DISTINCT a_id FROM b where a_id IS NOT NULL)\n//And for more joins\nAND a.id NOT IN(SELECT DISTINCT a_id FROM c where a_id IS NOT NULL)\n</code></pre>\n\n<p>I can also recommended this approach for deleting in case we don't have configured cascade delete.\nThis query takes only a few seconds.</p>\n"
},
{
"answer_id": 48278755,
"author": "Daniele Licitra",
"author_id": 5580181,
"author_profile": "https://Stackoverflow.com/users/5580181",
"pm_score": 0,
"selected": false,
"text": "<p>The first approach is</p>\n\n<pre><code>select a.* from a where a.id not in (select b.ida from b)\n</code></pre>\n\n<p>the second approach is </p>\n\n<pre><code>select a.*\n from a left outer join b on a.id = b.ida\n where b.ida is null\n</code></pre>\n\n<p>The first approach is very expensive. The second approach is better.</p>\n\n<p>With PostgreSql 9.4, I did the \"explain query\" function and the first query as a cost of <em>cost=0.00..1982043603.32</em>.\nInstead the join query as a cost of <em>cost=45946.77..45946.78</em></p>\n\n<p>For example, I search for all products that are not compatible with no vehicles. I've 100k products and more than 1m compatibilities.</p>\n\n<pre><code>select count(*) from product a left outer join compatible c on a.id=c.idprod where c.idprod is null\n</code></pre>\n\n<p>The join query spent about 5 seconds, instead the subquery version has never ended after 3 minutes.</p>\n"
},
{
"answer_id": 61749387,
"author": "Monsif EL AISSOUSSI",
"author_id": 4988179,
"author_profile": "https://Stackoverflow.com/users/4988179",
"pm_score": 3,
"selected": false,
"text": "<p>The following image will help to understand SQL <strong>LET JOIN</strong> : </p>\n\n<p><a href=\"https://i.stack.imgur.com/Ja30P.png\" rel=\"noreferrer\"><img src=\"https://i.stack.imgur.com/Ja30P.png\" alt=\"enter image description here\"></a></p>\n"
}
]
| 2008/09/29 | [
"https://Stackoverflow.com/questions/151099",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1681/"
]
| I have two tables that are joined together.
A has many B
Normally you would do:
```
select * from a,b where b.a_id = a.id
```
To get all of the records from a that has a record in b.
How do I get just the records in a that does not have anything in b? | ```
select * from a where id not in (select a_id from b)
```
Or like some other people on this thread says:
```
select a.* from a
left outer join b on a.id = b.a_id
where b.a_id is null
``` |
151,100 | <p>I am developing a web application using Struts 2.1.2 and Hibernate 3.2.6.GA. I have an entity, <code>User</code>, which I have mapped to a table <code>USERS</code> in the DB using Hibernate. I want to have an image associated with this entity, which I plan to store as a <code>BLOB</code> in the DB. I also want to display the image on a webpage along with other attributes of the <code>User</code>.</p>
<p>The solution I could think of was to have a table <code>IMAGES(ID, IMAGE)</code> where <code>IMAGE</code> is a <code>BLOB</code> column. <code>USERS</code> will have an <code>FK</code> column called <code>IMAGEID</code>, which points to the <code>IMAGES</code> table. I will then map a property on <code>User</code> entity, called <code>imageId</code> mapped to this <code>IMAGEID</code> as a Long. When rendering the page with a JSP, I would add images as <code><img src="images.action?id=1"/></code> etc, and have an Action which reads the image and streams the content to the browser, with the headers set to cache the image for a long time.</p>
<p>Will this work? Is there a better approach for rendering images stored in a DB? Is storing such images in the DB the right approach in the first place?</p>
| [
{
"answer_id": 151136,
"author": "Jorge Ferreira",
"author_id": 6508,
"author_profile": "https://Stackoverflow.com/users/6508",
"pm_score": 0,
"selected": false,
"text": "<p>If you want to display the user image directly with their properties perhaps you can consider embedding the image data directly in the HTML.</p>\n\n<p>Using a special data: URL scheme you are able to embed any mime data inside a HTML page, the format is as follows:</p>\n\n<blockquote>\n<pre><code>data:<mimetype>;base64,<data>\n</code></pre>\n</blockquote>\n\n<p><strong></strong> needs to be replaced by the mime-type of your data (image/png for instance) and\n<strong></strong> is the base64 encoded string of the actual bytes of the file.</p>\n\n<p>See <a href=\"http://www.ietf.org/rfc/rfc2557.txt\" rel=\"nofollow noreferrer\">RFC 2557</a>.</p>\n\n<p><a href=\"http://rifers.org/blogs/gbevin/2005/4/11/embedding_images_inside_html\" rel=\"nofollow noreferrer\">Example</a>:</p>\n\n<pre><code><img src=\"data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAEYAAAAmCAYAAAB52u3eAAAABmJLR0QA/wD/AP+gvaeTAAAACXBIWXMAAAsSAAALEgHS3X78AAAAB3RJTUUH1AkICzQgAc6C2QAACrxJREFUeNrtmnl0VdUVxn/3vnnIPBKmJECYkoAEERArgxGqCDIUkKVoqRZKUVREnC1SXXWJlKo4VrEi4EAUEARUtM5oVcAwZhZIyEySlzfe4fSPlzwSEzGUuLpa2Gu9te49Z99zzvvu3vt8e58rCSEAUBWNoyV1wZtzVHokR0pGkwEASQhB2bF6sX/vCZxhFjzuwDkJSlWFm4LDVYyf1I9ho3pKRiWg8f23ZfTPTCQ+0XkuGwzPr/qCZ1Z8zsDBXTCWFNYKq81EVIwNm910TgNzwbBufPlxCR9uzxMyQEO9j/MSlLpaLwDyeSjal3MOmBunb/gvABNQoepku12qqrVpUxTtjKdQVY1mivFTY7Wn09x/rKSuQ/MYOwsTUViKOn0RxifvRYqLAuDw/goeuO1dIiJtVJa7+PWUAcy//WJUVWPhdTl43AFqqz0sXT4utDOOndCHS/r/jb88fRUjLk1mRvbLbNw1FyEEdy14h9Kj9TS6/MyZfyEDMhP50+LtGI0GMrOSWLJsbBudSTPSmTfzDVRVJyrG1uGX0SnAiGPlKBfPhIp6pAG9Wrw5nfJSF6/tvB6AsYNWM/OGC/j0g0Ji4uw8u2EGleUuZmS/zCNPTmT7pkN07R5Ot56RfLSzAGe4hR4pQZB3bjmMxWrk1W3XoSgaEy58llVrplBZ3sgHexYgyzI7Nh9qo2M0yvRIieLBFRMoKaxl6ugXfxlgPn6vgEaXnyunDQy1abPvRVQUIPfMgghHK/0BgxKR5aDH9ktP4GjxSQrzasjM6gpAfGIYHneArBHdWb50J8m9orlx0QjWrP6K6Bgbo8amhqxv3zel3HJ9DkIIEpPC8HlVBrYYvz2d/XvLSb+gCwDJvaIJj7R2PjB+v8q82a+zbMUVoTZ966fon+1CIgoMMhgMrZ4pyqtudZ3ULYJuPSM5cqAyuD2e9GKxGLFYjERG2di6cT/rts8h59V9bM05yMubZof+VGZWV5avOjX3/r0nkGUpdN+ezptr94bWUHHChauD1OSMgHl4yXvU1LhbWYu+ZjMgBeO4xwdeP9gsp6xJE9w8ZyMN9X4uvbw3cQlOrvrNQN5ev49b575FcX4Ndz+SDcCosal8sO0IdruZkaNTOLD3BPGJYQBMnD6Q9945wtyp64mJc+DzKsy7/eJW62tP57HnJ3PdxFdZMm8zXo9CWETHLIa8g5Vi8+u5or7OK04ne746JszcJn7V/4lTjQFFBLqNF376Cz8Zwm+4QOiFx0PduXvKxC3XbxQeT0DUVLvbjFlZ7hJeb0CcidSd9IiqCtcZ6ei6LsrLGoSmaad97uP3C8T4oc+ILW/kig5ZjM+rMP/aN9EReNwBVFXHaJQRpZWI8uomwzOAVof4OhcpNRg/TGYD0bEObDYTNlvbdCMu4cxzs4hI2xnrSJJEQpewM5qnQ8DcOW8L3+QfJRYHxcdqKThcRb/0BHC5QQ00uRKAhL5+J/KsCQD0HRDPgyuC17ouePetgxQX1+JtCODxBBCAxWIgLSOecdlpRMXaQ3OWHq1n08bvkZGwWc1cM3cIFquRb3cf47PPi7DJrYEWgCo0ps0cRGLXcHLW7aO8ogGT1Drm+XWVPr3imHB1/7MDZlvOQZ5b+wWxOJGABuFh82u59PtzAiTFg8MJblcTV3Sgb9+FOFKC1De51TiapnPLDTkUu6uxYMKPH9AAMyYMJMVE8OTT07hqRnqzi7Nw8euAgXicTJ6ZjsVqZMemQ9z3aA5mnE2AnCJyCl769I4jsWs4j96/i38VF2HG8iMdH9lDMn4WmNMyX0XRePiu9zBjCNmEAwuvvfQdXo+CFBOBPDwD8DT1GkB1oT3wTLvjRUbZiMSBAzNTRw9h0Q3ZpMd1wYmFkzUefjdrAyUFtUE3NBkIw0E0dqIi7UhScAU2uwlTU3skNpxYQj+wUF/na3InK2E4iMFORAs9Ezb8PvXsXCnvQBWHCspxYA61WTGSd6KK3Z+WMGZ8H+SbpqHv2tniqXD0NzYhbr4GadTgdsd1E+Dmu37F6PG9OV5Sx5ispzhZ66FGePhwRx5zFw7/2YV7CHDRkJ489txkmtm/puskp0a30qvHx9LFlzF5VgZCCHQhsNtMZx9jNFrnHBLgR6XgUFUQmKljkVLSEcWFgLXJCHXUBY9g2vNakNv8SCQkGl1+ALolR9KvTwL//CofCfC4lY7lTGhERdsZNLTr6dM3NNIHd2HQ0KTOC7590+MZc3Eftnz+PTE4kZHwoiAh0T8zMahkMiIvmIG25IEmYACciNzd6C9tRr5pStsUAoHDGbTC/XtO8P2BUkwYUNAYfknPDma/Mu7GAOVlLhDBKCJJEvGJzlakz46JbW8foK7Oi6bp+ITCyOEpZA3v/p8DYzTKrNk0m6W3OPloZz5+j0pKagyLbrs0RNUB5EmXot0ZCUJvEbasaE9tQL7xapCkVuM6sbBi2UesWf0Vn35YhMvjJ4DG0lsvY+jIHh0CxomFPV8fZ3ivlUELEjp2q5kv8xcRE+dspffGW3v4x1tfIwEqHpbdMeXsgAGIjrXzwvpZNPh0PPUeEtvjHj4/COVHw9kQ+/MRxWUhXtMsFozs2H0QkIjGhkDw1FPTuOGPF3XY1CUk/LpKua8hSAfQsfstaFpr19cR2DFjx4xAUAtYOyPGhEJqVTnh3dv3U23VOsAHhLeORroXyirhR8D4UZkyZhBF+dUUHa/BgMQLT+9m0swMoltwmdPmbSik9IhhyZxxoaBqMhlwhlnaBN/77x7PtGsHAQJNEx0q+ncYGPXxdYj9uRiX34E0dACYjIii4+grX0Ffsx5oj1kawNGWqTbiZ8mysST3jubCtMfxNip8ebCYh+7YwaqXp3ZoPT4UeqXFsnT5uNPqKWik9okhbUDcL1PalC/KQN+1DWXkNSi9rkJJm4zS92q01X8HHC3Y76n9QIpLaEP0mt2gsryRhC5hLL5rDHV4icXBhrXf8UNRbYdd6XRFJ10PupQJmd2fleD1KPh9Kj6vis+nInTRScBkD0dypAX3lGM/IPLzmtKBiHZAkYB65N9PA3v72WxzPL7+D8PoER6FjqBGd7Nx7b5OqSiaTAY0dCKw8epL3zAs5XEuSl3J0NQVjOj9V8qO13dSzTc2EsOdvwXqAHPT1mz4CeVqpCGXYLjvxlatrnof9Xjx4Q297choG5df0Zca6tDQWP/itwgBQghceKnHS0O9L1TD9ftUFLy48eJu/OlT04nTB+LBSx1eGvFzqLKC3BMnOFBeRnFpNRarsfPqMYYHbkLk/YC+7pUmYGwtsBWAH2hEGp2NaeMqsJ4KhLIkMWlmBhXVjShCpXvPqFDfnPnDqPG6sUtmZCQ87gBJ3SO4ZvJQjJJMuMOK2RJc6sDBXZg+aRhGSWZw+k+Tu4VLL8HuMPHJJ4VIASlkoQo6MZF2nGHWzqnHtBRt7VYRGDFb+K1Zwk9f4SdN+MkUgfRJQn1infhflTOux7Txv2uvRL72SkRZJZSUgaJC13ik3j34f5GzOiWQkuKDpYfzJ5Hnj2jPAwNQUdZwHolmolHZGAwTAb/KPTdvFWHhVkaNTTmnQVkybwtVFY0cqrlHMprMBq6elcnKhz7i689+CJUGzzWpq/VQW+1h5YtTcDjNwW/wABpdft7feuSc/jgxe2JfqTk7/zeNpiqnFESz8wAAAABJRU5ErkJggg==\">\n</code></pre>\n"
},
{
"answer_id": 151155,
"author": "Thomas R",
"author_id": 2192,
"author_profile": "https://Stackoverflow.com/users/2192",
"pm_score": 0,
"selected": false,
"text": "<p>Internet Explorer does not support that style of image embedding. </p>\n"
},
{
"answer_id": 151194,
"author": "Craig Wohlfeil",
"author_id": 22767,
"author_profile": "https://Stackoverflow.com/users/22767",
"pm_score": 3,
"selected": true,
"text": "<p>Yes your suggested solution will work. Given that you are working in a Java environment storing the images in the database is the best way to go. If you are running in a single server environment with an application server that will let you deploy in an exploded format technically you could store the images on disk but that wouldn't be the best practice. One suggestion would be to use a servlet instead of a JSP. To get good browser behavior you want the browser to think that the file type that it is displaying matches the file type that it is expecting. Despite the existence of mime type headers the file extension is still really important. So you want a link that looks like this:</p>\n\n<pre><code><a href=\"foo.jsp\"><img src=\"imageservlet/123456789.png\"></a>\n</code></pre>\n\n<p>Where 123456789 is the primary key of your image in the database. Your servlet mapping would look like this:</p>\n\n<pre><code><servlet>\n <servlet-name>ImageServlet</servlet-name>\n <servlet-class>com.example.ImageServlet</servlet-class>\n</servlet>\n<servlet-mapping>\n <servlet-name>ImageServlet</servlet-name>\n <url-pattern>/imageservlet/*</url-pattern>\n</servlet-mapping>\n</code></pre>\n\n<p>Then in your servlet simply parse the request URL for the image ID rather than using the query string as the query string will confuse some browsers. Using the query string won't break browsers outright but you'll get odd behavior with regards to caching and some browsers may report the content as unsafe.</p>\n"
},
{
"answer_id": 495690,
"author": "kazanaki",
"author_id": 60593,
"author_profile": "https://Stackoverflow.com/users/60593",
"pm_score": 0,
"selected": false,
"text": "<p>Your suggested solution would work perfectly. I have done the same thing.</p>\n\n<p>But you don't need a servlet for this.\nStruts2 has already a stream result.</p>\n\n<p>See this <a href=\"http://cwiki.apache.org/WW/stream-result.html\" rel=\"nofollow noreferrer\">Struts 2 Example</a> which describes exactly what you want.</p>\n"
}
]
| 2008/09/29 | [
"https://Stackoverflow.com/questions/151100",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3973/"
]
| I am developing a web application using Struts 2.1.2 and Hibernate 3.2.6.GA. I have an entity, `User`, which I have mapped to a table `USERS` in the DB using Hibernate. I want to have an image associated with this entity, which I plan to store as a `BLOB` in the DB. I also want to display the image on a webpage along with other attributes of the `User`.
The solution I could think of was to have a table `IMAGES(ID, IMAGE)` where `IMAGE` is a `BLOB` column. `USERS` will have an `FK` column called `IMAGEID`, which points to the `IMAGES` table. I will then map a property on `User` entity, called `imageId` mapped to this `IMAGEID` as a Long. When rendering the page with a JSP, I would add images as `<img src="images.action?id=1"/>` etc, and have an Action which reads the image and streams the content to the browser, with the headers set to cache the image for a long time.
Will this work? Is there a better approach for rendering images stored in a DB? Is storing such images in the DB the right approach in the first place? | Yes your suggested solution will work. Given that you are working in a Java environment storing the images in the database is the best way to go. If you are running in a single server environment with an application server that will let you deploy in an exploded format technically you could store the images on disk but that wouldn't be the best practice. One suggestion would be to use a servlet instead of a JSP. To get good browser behavior you want the browser to think that the file type that it is displaying matches the file type that it is expecting. Despite the existence of mime type headers the file extension is still really important. So you want a link that looks like this:
```
<a href="foo.jsp"><img src="imageservlet/123456789.png"></a>
```
Where 123456789 is the primary key of your image in the database. Your servlet mapping would look like this:
```
<servlet>
<servlet-name>ImageServlet</servlet-name>
<servlet-class>com.example.ImageServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>ImageServlet</servlet-name>
<url-pattern>/imageservlet/*</url-pattern>
</servlet-mapping>
```
Then in your servlet simply parse the request URL for the image ID rather than using the query string as the query string will confuse some browsers. Using the query string won't break browsers outright but you'll get odd behavior with regards to caching and some browsers may report the content as unsafe. |
151,124 | <p>Which one should I use?</p>
<pre><code>catch (_com_error e)
</code></pre>
<p>or </p>
<pre><code>catch (_com_error& e)
</code></pre>
| [
{
"answer_id": 151126,
"author": "JaredPar",
"author_id": 23283,
"author_profile": "https://Stackoverflow.com/users/23283",
"pm_score": 6,
"selected": true,
"text": "<p>The second. Here is my attempt at quoting Sutter</p>\n\n<p>\"Throw by value, catch by reference\"</p>\n\n<blockquote>\n <p>Learn to <code>catch</code> properly: Throw exceptions by value (not pointer) and\n catch them by reference (usually to <code>const</code>). This is the combination\n that meshes best with exception semantics. When rethrowing the same\n exception, prefer just <code>throw;</code> to <code>throw e;</code>.</p>\n</blockquote>\n\n<p>Here's the full <a href=\"http://www.informit.com/content/images/0321113586/items/sutter_item73.pdf\" rel=\"nofollow noreferrer\">Item 73. Throw by value, catch by reference.</a></p>\n\n<hr>\n\n<p>The reason to avoid catching exceptions by value is that it implicitly makes a copy of the exception. If the exception is of a subclass, then information about it will be lost. </p>\n\n<pre><code>try { throw MyException (\"error\") } \ncatch (Exception e) {\n /* Implies: Exception e (MyException (\"error\")) */\n /* e is an instance of Exception, but not MyException */\n}\n</code></pre>\n\n<p>Catching by reference avoids this issue by not copying the exception.</p>\n\n<pre><code>try { throw MyException (\"error\") } \ncatch (Exception& e) {\n /* Implies: Exception &e = MyException (\"error\"); */\n /* e is an instance of MyException */\n}\n</code></pre>\n"
},
{
"answer_id": 151141,
"author": "1800 INFORMATION",
"author_id": 3146,
"author_profile": "https://Stackoverflow.com/users/3146",
"pm_score": 2,
"selected": false,
"text": "<p>Definitely the second. If you had the following:</p>\n\n<pre><code>class my_exception : public exception\n{\n int my_exception_data;\n};\n\nvoid foo()\n{\n throw my_exception;\n}\n\nvoid bar()\n{\n try\n {\n foo();\n }\n catch (exception e)\n {\n // e is \"sliced off\" - you lose the \"my_exception-ness\" of the exception object\n }\n}\n</code></pre>\n"
},
{
"answer_id": 151149,
"author": "Kris Kumler",
"author_id": 4281,
"author_profile": "https://Stackoverflow.com/users/4281",
"pm_score": 3,
"selected": false,
"text": "<p>Also, note that, when using MFC, you may have to <a href=\"http://www.parashift.com/c++-faq-lite/exceptions.html#faq-17.8\" rel=\"nofollow noreferrer\">catch by pointer</a>. Otherwise, @JaredPar's answer is the way you should normally go (and hopefully never have to deal with things that throw a pointer).</p>\n"
},
{
"answer_id": 151451,
"author": "jonner",
"author_id": 78437,
"author_profile": "https://Stackoverflow.com/users/78437",
"pm_score": 4,
"selected": false,
"text": "<p>Personally, I would go for the third option:</p>\n\n<pre><code>catch (const _com_error& e)\n</code></pre>\n"
}
]
| 2008/09/29 | [
"https://Stackoverflow.com/questions/151124",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9328/"
]
| Which one should I use?
```
catch (_com_error e)
```
or
```
catch (_com_error& e)
``` | The second. Here is my attempt at quoting Sutter
"Throw by value, catch by reference"
>
> Learn to `catch` properly: Throw exceptions by value (not pointer) and
> catch them by reference (usually to `const`). This is the combination
> that meshes best with exception semantics. When rethrowing the same
> exception, prefer just `throw;` to `throw e;`.
>
>
>
Here's the full [Item 73. Throw by value, catch by reference.](http://www.informit.com/content/images/0321113586/items/sutter_item73.pdf)
---
The reason to avoid catching exceptions by value is that it implicitly makes a copy of the exception. If the exception is of a subclass, then information about it will be lost.
```
try { throw MyException ("error") }
catch (Exception e) {
/* Implies: Exception e (MyException ("error")) */
/* e is an instance of Exception, but not MyException */
}
```
Catching by reference avoids this issue by not copying the exception.
```
try { throw MyException ("error") }
catch (Exception& e) {
/* Implies: Exception &e = MyException ("error"); */
/* e is an instance of MyException */
}
``` |
151,152 | <p>I'm using spring 2.5, and am using annotations to configure my controllers. My controller works fine if I do not implement any additional interfaces, but the spring container doesn't recognize the controller/request mapping when I add interface implementations.</p>
<p>I can't figure out why adding an interface implementation messes up the configuration of the controller and the request mappings. Any ideas?</p>
<p>So, this works:</p>
<pre><code>package com.shaneleopard.web.controller;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.providers.encoding.Md5PasswordEncoder;
import org.springframework.stereotype.Controller;
import org.springframework.validation.Errors;
import org.springframework.validation.Validator;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import com.shaneleopard.model.User;
import com.shaneleopard.service.UserService;
import com.shaneleopard.validator.RegistrationValidator;
import com.shaneleopard.web.command.RegisterCommand;
@Controller
public class RegistrationController {
@Autowired
private UserService userService;
@Autowired
private Md5PasswordEncoder passwordEncoder;
@Autowired
private RegistrationValidator registrationValidator;
@RequestMapping( method = RequestMethod.GET, value = "/register.html" )
public void registerForm(@ModelAttribute RegisterCommand registerCommand) {
// no op
}
@RequestMapping( method = RequestMethod.POST, value = "/register.html" )
public String registerNewUser( @ModelAttribute RegisterCommand command,
Errors errors ) {
String returnView = "redirect:index.html";
if ( errors.hasErrors() ) {
returnView = "register";
} else {
User newUser = new User();
newUser.setUsername( command.getUsername() );
newUser.setPassword( passwordEncoder.encodePassword( command
.getPassword(), null ) );
newUser.setEmailAddress( command.getEmailAddress() );
newUser.setFirstName( command.getFirstName() );
newUser.setLastName( command.getLastName() );
userService.registerNewUser( newUser );
}
return returnView;
}
public Validator getValidator() {
return registrationValidator;
}
}
</code></pre>
<p>but this doesn't:</p>
<pre><code>package com.shaneleopard.web.controller;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.providers.encoding.Md5PasswordEncoder;
import org.springframework.stereotype.Controller;
import org.springframework.validation.Errors;
import org.springframework.validation.Validator;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import com.shaneleopard.model.User;
import com.shaneleopard.service.UserService;
import com.shaneleopard.validator.RegistrationValidator;
import com.shaneleopard.web.command.RegisterCommand;
@Controller
public class RegistrationController extends ValidatingController {
@Autowired
private UserService userService;
@Autowired
private Md5PasswordEncoder passwordEncoder;
@Autowired
private RegistrationValidator registrationValidator;
@RequestMapping( method = RequestMethod.GET, value = "/register.html" )
public void registerForm(@ModelAttribute RegisterCommand registerCommand) {
// no op
}
@RequestMapping( method = RequestMethod.POST, value = "/register.html" )
public String registerNewUser( @ModelAttribute RegisterCommand command,
Errors errors ) {
String returnView = "redirect:index.html";
if ( errors.hasErrors() ) {
returnView = "register";
} else {
User newUser = new User();
newUser.setUsername( command.getUsername() );
newUser.setPassword( passwordEncoder.encodePassword( command
.getPassword(), null ) );
newUser.setEmailAddress( command.getEmailAddress() );
newUser.setFirstName( command.getFirstName() );
newUser.setLastName( command.getLastName() );
userService.registerNewUser( newUser );
}
return returnView;
}
public Validator getValidator() {
return registrationValidator;
}
}
</code></pre>
| [
{
"answer_id": 185587,
"author": "abarax",
"author_id": 24390,
"author_profile": "https://Stackoverflow.com/users/24390",
"pm_score": 0,
"selected": false,
"text": "<p>I think you'll find that the problem is to do with inheritance and using annotations, they do not mix well. </p>\n\n<p>Have you tried to implement the above using inheritance and SimpleFormController with all other details configured in your application context? This will at least narrow down the problem to an annotations and inheritance issue.</p>\n"
},
{
"answer_id": 196647,
"author": "Dov Wasserman",
"author_id": 26010,
"author_profile": "https://Stackoverflow.com/users/26010",
"pm_score": 2,
"selected": false,
"text": "<p><em>layne</em>, you described the problem as happening when your controller class implements an interface, but in the code sample you provided, the problem occurs when your controller class extends another class of yours, <code>ValidatingController</code>.</p>\n\n<p>Perhaps the parent class also defines some Spring annotations, and the Spring container noticed them first and classified the controller class as that type of managed object and did not bother to check for the <code>@Controller</code> annotation you also defined in the subclass. Just a guess, but if that pans out, I'd suggest reporting it to the Spring team, as it sounds like a bug.</p>\n"
},
{
"answer_id": 16970812,
"author": "user979051",
"author_id": 979051,
"author_profile": "https://Stackoverflow.com/users/979051",
"pm_score": 1,
"selected": false,
"text": "<p>By default JDK proxy are created using interface and if controller implements an interface the RequestMapping annotation gets ignored as the targetClass is not being used</p>\n\n<p>Add this in your servlet context config:</p>\n\n<pre><code><aop:aspectj-autoproxy proxy-target-class=\"true\"/>\n</code></pre>\n"
}
]
| 2008/09/29 | [
"https://Stackoverflow.com/questions/151152",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9955/"
]
| I'm using spring 2.5, and am using annotations to configure my controllers. My controller works fine if I do not implement any additional interfaces, but the spring container doesn't recognize the controller/request mapping when I add interface implementations.
I can't figure out why adding an interface implementation messes up the configuration of the controller and the request mappings. Any ideas?
So, this works:
```
package com.shaneleopard.web.controller;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.providers.encoding.Md5PasswordEncoder;
import org.springframework.stereotype.Controller;
import org.springframework.validation.Errors;
import org.springframework.validation.Validator;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import com.shaneleopard.model.User;
import com.shaneleopard.service.UserService;
import com.shaneleopard.validator.RegistrationValidator;
import com.shaneleopard.web.command.RegisterCommand;
@Controller
public class RegistrationController {
@Autowired
private UserService userService;
@Autowired
private Md5PasswordEncoder passwordEncoder;
@Autowired
private RegistrationValidator registrationValidator;
@RequestMapping( method = RequestMethod.GET, value = "/register.html" )
public void registerForm(@ModelAttribute RegisterCommand registerCommand) {
// no op
}
@RequestMapping( method = RequestMethod.POST, value = "/register.html" )
public String registerNewUser( @ModelAttribute RegisterCommand command,
Errors errors ) {
String returnView = "redirect:index.html";
if ( errors.hasErrors() ) {
returnView = "register";
} else {
User newUser = new User();
newUser.setUsername( command.getUsername() );
newUser.setPassword( passwordEncoder.encodePassword( command
.getPassword(), null ) );
newUser.setEmailAddress( command.getEmailAddress() );
newUser.setFirstName( command.getFirstName() );
newUser.setLastName( command.getLastName() );
userService.registerNewUser( newUser );
}
return returnView;
}
public Validator getValidator() {
return registrationValidator;
}
}
```
but this doesn't:
```
package com.shaneleopard.web.controller;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.providers.encoding.Md5PasswordEncoder;
import org.springframework.stereotype.Controller;
import org.springframework.validation.Errors;
import org.springframework.validation.Validator;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import com.shaneleopard.model.User;
import com.shaneleopard.service.UserService;
import com.shaneleopard.validator.RegistrationValidator;
import com.shaneleopard.web.command.RegisterCommand;
@Controller
public class RegistrationController extends ValidatingController {
@Autowired
private UserService userService;
@Autowired
private Md5PasswordEncoder passwordEncoder;
@Autowired
private RegistrationValidator registrationValidator;
@RequestMapping( method = RequestMethod.GET, value = "/register.html" )
public void registerForm(@ModelAttribute RegisterCommand registerCommand) {
// no op
}
@RequestMapping( method = RequestMethod.POST, value = "/register.html" )
public String registerNewUser( @ModelAttribute RegisterCommand command,
Errors errors ) {
String returnView = "redirect:index.html";
if ( errors.hasErrors() ) {
returnView = "register";
} else {
User newUser = new User();
newUser.setUsername( command.getUsername() );
newUser.setPassword( passwordEncoder.encodePassword( command
.getPassword(), null ) );
newUser.setEmailAddress( command.getEmailAddress() );
newUser.setFirstName( command.getFirstName() );
newUser.setLastName( command.getLastName() );
userService.registerNewUser( newUser );
}
return returnView;
}
public Validator getValidator() {
return registrationValidator;
}
}
``` | *layne*, you described the problem as happening when your controller class implements an interface, but in the code sample you provided, the problem occurs when your controller class extends another class of yours, `ValidatingController`.
Perhaps the parent class also defines some Spring annotations, and the Spring container noticed them first and classified the controller class as that type of managed object and did not bother to check for the `@Controller` annotation you also defined in the subclass. Just a guess, but if that pans out, I'd suggest reporting it to the Spring team, as it sounds like a bug. |
151,195 | <p>I have a bunch of tasks in a MySQL database, and one of the fields is "deadline date". Not every task has to have to a deadline date.</p>
<p>I'd like to use SQL to sort the tasks by deadline date, but put the ones without a deadline date in the back of the result set. As it is now, the null dates show up first, then the rest are sorted by deadline date earliest to latest.</p>
<p>Any ideas on how to do this with SQL alone? (I can do it with PHP if needed, but an SQL-only solution would be great.)</p>
<p>Thanks!</p>
| [
{
"answer_id": 151202,
"author": "Danimal",
"author_id": 2757,
"author_profile": "https://Stackoverflow.com/users/2757",
"pm_score": 2,
"selected": false,
"text": "<pre><code>SELECT foo, bar, due_date FROM tablename\nORDER BY CASE ISNULL(due_date, 0)\nWHEN 0 THEN 1 ELSE 0 END, due_date\n</code></pre>\n\n<p>So you have 2 order by clauses. The first puts all non-nulls in front, then sorts by due date after that</p>\n"
},
{
"answer_id": 151203,
"author": "nickf",
"author_id": 9021,
"author_profile": "https://Stackoverflow.com/users/9021",
"pm_score": 5,
"selected": false,
"text": "<pre><code>SELECT * FROM myTable\nWHERE ...\nORDER BY ISNULL(myDate), myDate\n</code></pre>\n"
},
{
"answer_id": 151343,
"author": "Bill Karwin",
"author_id": 20860,
"author_profile": "https://Stackoverflow.com/users/20860",
"pm_score": 7,
"selected": true,
"text": "<p>Here's a solution using only standard SQL, not ISNULL(). That function is not standard SQL, and may not work on other brands of RDBMS.</p>\n\n<pre><code>SELECT * FROM myTable\nWHERE ...\nORDER BY CASE WHEN myDate IS NULL THEN 1 ELSE 0 END, myDate;\n</code></pre>\n"
},
{
"answer_id": 57891284,
"author": "luke",
"author_id": 11204120,
"author_profile": "https://Stackoverflow.com/users/11204120",
"pm_score": 2,
"selected": false,
"text": "<p>The easiest way is using the minus operator with DESC. </p>\n\n<p><code>SELECT * FROM request ORDER BY -date DESC</code></p>\n\n<p>In MySQL, NULL values are considered lower in order than any non-NULL value, so sorting in ascending (ASC) order NULLs are listed first, and if descending (DESC) they are listed last.</p>\n\n<p>When a - (minus) sign is added before the column name, NULL become -NULL.</p>\n\n<p>Since -NULL == NULL, adding DESC make all the rows sort by date in ascending order followed by NULLs at last.</p>\n"
}
]
| 2008/09/29 | [
"https://Stackoverflow.com/questions/151195",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
]
| I have a bunch of tasks in a MySQL database, and one of the fields is "deadline date". Not every task has to have to a deadline date.
I'd like to use SQL to sort the tasks by deadline date, but put the ones without a deadline date in the back of the result set. As it is now, the null dates show up first, then the rest are sorted by deadline date earliest to latest.
Any ideas on how to do this with SQL alone? (I can do it with PHP if needed, but an SQL-only solution would be great.)
Thanks! | Here's a solution using only standard SQL, not ISNULL(). That function is not standard SQL, and may not work on other brands of RDBMS.
```
SELECT * FROM myTable
WHERE ...
ORDER BY CASE WHEN myDate IS NULL THEN 1 ELSE 0 END, myDate;
``` |
151,199 | <p>If I have two dates (ex. <code>'8/18/2008'</code> and <code>'9/26/2008'</code>), what is the best way to get the number of days between these two dates?</p>
| [
{
"answer_id": 151211,
"author": "Dana",
"author_id": 7856,
"author_profile": "https://Stackoverflow.com/users/7856",
"pm_score": 11,
"selected": true,
"text": "<p>If you have two date objects, you can just subtract them, which computes a <a href=\"https://docs.python.org/3/library/datetime.html#datetime.timedelta\" rel=\"noreferrer\"><code>timedelta</code></a> object.</p>\n\n<pre><code>from datetime import date\n\nd0 = date(2008, 8, 18)\nd1 = date(2008, 9, 26)\ndelta = d1 - d0\nprint(delta.days)\n</code></pre>\n\n<p>The relevant section of the docs:\n<a href=\"https://docs.python.org/library/datetime.html\" rel=\"noreferrer\">https://docs.python.org/library/datetime.html</a>.</p>\n\n<p>See <a href=\"https://stackoverflow.com/a/8258465\">this answer</a> for another example.</p>\n"
},
{
"answer_id": 151212,
"author": "dguaraglia",
"author_id": 2384,
"author_profile": "https://Stackoverflow.com/users/2384",
"pm_score": 8,
"selected": false,
"text": "<p>Using the power of datetime:</p>\n\n<pre><code>from datetime import datetime\ndate_format = \"%m/%d/%Y\"\na = datetime.strptime('8/18/2008', date_format)\nb = datetime.strptime('9/26/2008', date_format)\ndelta = b - a\nprint delta.days # that's it\n</code></pre>\n"
},
{
"answer_id": 151214,
"author": "Harley Holcombe",
"author_id": 1057,
"author_profile": "https://Stackoverflow.com/users/1057",
"pm_score": 6,
"selected": false,
"text": "<p>Days until Christmas:</p>\n\n<pre><code>>>> import datetime\n>>> today = datetime.date.today()\n>>> someday = datetime.date(2008, 12, 25)\n>>> diff = someday - today\n>>> diff.days\n86\n</code></pre>\n\n<p>More arithmetic <a href=\"https://web.archive.org/web/20061007015511/http://www.daniweb.com/code/snippet236.html\" rel=\"noreferrer\">here</a>.</p>\n"
},
{
"answer_id": 151215,
"author": "kolrie",
"author_id": 14540,
"author_profile": "https://Stackoverflow.com/users/14540",
"pm_score": 4,
"selected": false,
"text": "<p>You want the datetime module. </p>\n\n<pre><code>>>> from datetime import datetime, timedelta \n>>> datetime(2008,08,18) - datetime(2008,09,26) \ndatetime.timedelta(4) \n</code></pre>\n\n<p>Another example:</p>\n\n<pre><code>>>> import datetime \n>>> today = datetime.date.today() \n>>> print(today)\n2008-09-01 \n>>> last_year = datetime.date(2007, 9, 1) \n>>> print(today - last_year)\n366 days, 0:00:00 \n</code></pre>\n\n<p>As pointed out <a href=\"http://python.6.x6.nabble.com/How-Compute-of-Days-between-Two-Dates-tp1711833p1711841.html\" rel=\"noreferrer\">here</a></p>\n"
},
{
"answer_id": 10332036,
"author": "Prasanna Ranganathan",
"author_id": 1358487,
"author_profile": "https://Stackoverflow.com/users/1358487",
"pm_score": 4,
"selected": false,
"text": "<pre><code>from datetime import datetime\nstart_date = datetime.strptime('8/18/2008', \"%m/%d/%Y\")\nend_date = datetime.strptime('9/26/2008', \"%m/%d/%Y\")\nprint abs((end_date-start_date).days)\n</code></pre>\n"
},
{
"answer_id": 36650398,
"author": "Parthian Shot",
"author_id": 3680301,
"author_profile": "https://Stackoverflow.com/users/3680301",
"pm_score": 3,
"selected": false,
"text": "<p></p>\n\n<pre><code>from datetime import date\ndef d(s):\n [month, day, year] = map(int, s.split('/'))\n return date(year, month, day)\ndef days(start, end):\n return (d(end) - d(start)).days\nprint days('8/18/2008', '9/26/2008')\n</code></pre>\n\n<p>This assumes, of course, that you've already verified that your dates are in the format <code>r'\\d+/\\d+/\\d+'</code>.</p>\n"
},
{
"answer_id": 43923193,
"author": "cimarie",
"author_id": 6492656,
"author_profile": "https://Stackoverflow.com/users/6492656",
"pm_score": 4,
"selected": false,
"text": "<p>It also can be easily done with <code>arrow</code>:</p>\n\n<pre><code>import arrow\n\na = arrow.get('2017-05-09')\nb = arrow.get('2017-05-11')\n\ndelta = (b-a)\nprint delta.days\n</code></pre>\n\n<p>For reference: <a href=\"http://arrow.readthedocs.io/en/latest/\" rel=\"noreferrer\">http://arrow.readthedocs.io/en/latest/</a></p>\n"
},
{
"answer_id": 48540389,
"author": "Gavriel Cohen",
"author_id": 5770004,
"author_profile": "https://Stackoverflow.com/users/5770004",
"pm_score": 3,
"selected": false,
"text": "<p>For calculating dates and times, there are several options but I will write the simple way:</p>\n<pre><code>from datetime import timedelta, datetime, date\nimport dateutil.relativedelta\n\n# current time\ndate_and_time = datetime.now()\ndate_only = date.today()\ntime_only = datetime.now().time()\n\n# calculate date and time\nresult = date_and_time - timedelta(hours=26, minutes=25, seconds=10)\n\n# calculate dates: years (-/+)\nresult = date_only - dateutil.relativedelta.relativedelta(years=10)\n\n# months\nresult = date_only - dateutil.relativedelta.relativedelta(months=10)\n\n# days\nresult = date_only - dateutil.relativedelta.relativedelta(days=10)\n\n# calculate time \nresult = date_and_time - timedelta(hours=26, minutes=25, seconds=10)\nresult.time()\n</code></pre>\n<p>Hope it helps</p>\n"
},
{
"answer_id": 48632627,
"author": "Muhammad Elsayeh",
"author_id": 9312964,
"author_profile": "https://Stackoverflow.com/users/9312964",
"pm_score": 3,
"selected": false,
"text": "<p>without using Lib just pure code:</p>\n\n<pre><code>#Calculate the Days between Two Date\n\ndaysOfMonths = [ 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31]\n\ndef isLeapYear(year):\n\n # Pseudo code for this algorithm is found at\n # http://en.wikipedia.org/wiki/Leap_year#Algorithm\n ## if (year is not divisible by 4) then (it is a common Year)\n #else if (year is not divisable by 100) then (ut us a leap year)\n #else if (year is not disible by 400) then (it is a common year)\n #else(it is aleap year)\n return (year % 4 == 0 and year % 100 != 0) or year % 400 == 0\n\ndef Count_Days(year1, month1, day1):\n if month1 ==2:\n if isLeapYear(year1):\n if day1 < daysOfMonths[month1-1]+1:\n return year1, month1, day1+1\n else:\n if month1 ==12:\n return year1+1,1,1\n else:\n return year1, month1 +1 , 1\n else: \n if day1 < daysOfMonths[month1-1]:\n return year1, month1, day1+1\n else:\n if month1 ==12:\n return year1+1,1,1\n else:\n return year1, month1 +1 , 1\n else:\n if day1 < daysOfMonths[month1-1]:\n return year1, month1, day1+1\n else:\n if month1 ==12:\n return year1+1,1,1\n else:\n return year1, month1 +1 , 1\n\n\ndef daysBetweenDates(y1, m1, d1, y2, m2, d2,end_day):\n\n if y1 > y2:\n m1,m2 = m2,m1\n y1,y2 = y2,y1\n d1,d2 = d2,d1\n days=0\n while(not(m1==m2 and y1==y2 and d1==d2)):\n y1,m1,d1 = Count_Days(y1,m1,d1)\n days+=1\n if end_day:\n days+=1\n return days\n\n\n# Test Case\n\ndef test():\n test_cases = [((2012,1,1,2012,2,28,False), 58), \n ((2012,1,1,2012,3,1,False), 60),\n ((2011,6,30,2012,6,30,False), 366),\n ((2011,1,1,2012,8,8,False), 585 ),\n ((1994,5,15,2019,8,31,False), 9239),\n ((1999,3,24,2018,2,4,False), 6892),\n ((1999,6,24,2018,8,4,False),6981),\n ((1995,5,24,2018,12,15,False),8606),\n ((1994,8,24,2019,12,15,True),9245),\n ((2019,12,15,1994,8,24,True),9245),\n ((2019,5,15,1994,10,24,True),8970),\n ((1994,11,24,2019,8,15,True),9031)]\n\n for (args, answer) in test_cases:\n result = daysBetweenDates(*args)\n if result != answer:\n print \"Test with data:\", args, \"failed\"\n else:\n print \"Test case passed!\"\n\ntest()\n</code></pre>\n"
},
{
"answer_id": 49385575,
"author": "Antoine Thiry",
"author_id": 6020412,
"author_profile": "https://Stackoverflow.com/users/6020412",
"pm_score": 2,
"selected": false,
"text": "<p>Here are three ways to go with this problem :</p>\n\n<pre><code>from datetime import datetime\n\nNow = datetime.now()\nStartDate = datetime.strptime(str(Now.year) +'-01-01', '%Y-%m-%d')\nNumberOfDays = (Now - StartDate)\n\nprint(NumberOfDays.days) # Starts at 0\nprint(datetime.now().timetuple().tm_yday) # Starts at 1\nprint(Now.strftime('%j')) # Starts at 1\n</code></pre>\n"
},
{
"answer_id": 56515237,
"author": "Dmitriy Work",
"author_id": 7204581,
"author_profile": "https://Stackoverflow.com/users/7204581",
"pm_score": 3,
"selected": false,
"text": "<p>There is also a <code>datetime.toordinal()</code> method that was not mentioned yet:</p>\n\n<pre class=\"lang-py prettyprint-override\"><code>import datetime\nprint(datetime.date(2008,9,26).toordinal() - datetime.date(2008,8,18).toordinal()) # 39\n</code></pre>\n\n<p><a href=\"https://docs.python.org/3/library/datetime.html#datetime.date.toordinal\" rel=\"noreferrer\">https://docs.python.org/3/library/datetime.html#datetime.date.toordinal</a></p>\n\n<blockquote>\n <p><code>date.</code><strong>toordinal()</strong></p>\n \n <p>Return the proleptic Gregorian ordinal of the date, where January 1 of year 1 has ordinal 1. For any <code>date</code> object <em>d</em>,\n <code>date.fromordinal(d.toordinal()) == d</code>.</p>\n</blockquote>\n\n<p>Seems well suited for calculating days difference, though not as readable as <code>timedelta.days</code>.</p>\n"
},
{
"answer_id": 58831380,
"author": "Amit Gupta",
"author_id": 8884381,
"author_profile": "https://Stackoverflow.com/users/8884381",
"pm_score": 5,
"selected": false,
"text": "<p>everyone has answered excellently using the date,\nlet me try to answer it using pandas</p>\n\n<pre><code>dt = pd.to_datetime('2008/08/18', format='%Y/%m/%d')\ndt1 = pd.to_datetime('2008/09/26', format='%Y/%m/%d')\n\n(dt1-dt).days\n</code></pre>\n\n<p>This will give the answer.\nIn case one of the input is dataframe column. simply use <strong>dt.days</strong> in place of <strong>days</strong></p>\n\n<pre><code>(dt1-dt).dt.days\n</code></pre>\n"
},
{
"answer_id": 63095653,
"author": "Abhishek Kulkarni",
"author_id": 1532338,
"author_profile": "https://Stackoverflow.com/users/1532338",
"pm_score": 0,
"selected": false,
"text": "<p>Without using datetime object in python.</p>\n<pre><code># A date has day 'd', month 'm' and year 'y' \nclass Date:\n def __init__(self, d, m, y):\n self.d = d\n self.m = m\n self.y = y\n\n# To store number of days in all months from \n# January to Dec. \nmonthDays = [31, 28, 31, 30, 31, 30,\n 31, 31, 30, 31, 30, 31 ]\n\n# This function counts number of leap years \n# before the given date \ndef countLeapYears(d):\n\n years = d.y\n\n # Check if the current year needs to be considered \n # for the count of leap years or not \n if (d.m <= 2) :\n years-= 1\n\n # An year is a leap year if it is a multiple of 4, \n # multiple of 400 and not a multiple of 100. \n return int(years / 4 - years / 100 + years / 400 )\n\n\n# This function returns number of days between two \n# given dates \ndef getDifference(dt1, dt2) :\n\n # COUNT TOTAL NUMBER OF DAYS BEFORE FIRST DATE 'dt1' \n\n # initialize count using years and day \n n1 = dt1.y * 365 + dt1.d\n\n # Add days for months in given date \n for i in range(0, dt1.m - 1) :\n n1 += monthDays[i]\n\n # Since every leap year is of 366 days, \n # Add a day for every leap year \n n1 += countLeapYears(dt1)\n\n # SIMILARLY, COUNT TOTAL NUMBER OF DAYS BEFORE 'dt2' \n\n n2 = dt2.y * 365 + dt2.d\n for i in range(0, dt2.m - 1) :\n n2 += monthDays[i]\n n2 += countLeapYears(dt2)\n\n # return difference between two counts \n return (n2 - n1)\n\n\n# Driver program \ndt1 = Date(31, 12, 2018 )\ndt2 = Date(1, 1, 2019 )\n\nprint(getDifference(dt1, dt2), "days")\n</code></pre>\n"
},
{
"answer_id": 67474227,
"author": "trincot",
"author_id": 5459839,
"author_profile": "https://Stackoverflow.com/users/5459839",
"pm_score": 1,
"selected": false,
"text": "<p>If you want to code the calculation yourself, then here is a function that will return the ordinal for a given year, month and day:</p>\n<pre><code>def ordinal(year, month, day):\n return ((year-1)*365 + (year-1)//4 - (year-1)//100 + (year-1)//400\n + [ 0,31,59,90,120,151,181,212,243,273,304,334][month - 1]\n + day\n + int(((year%4==0 and year%100!=0) or year%400==0) and month > 2))\n</code></pre>\n<p>This function is compatible with the <a href=\"https://docs.python.org/3/library/datetime.html#datetime.date.toordinal\" rel=\"nofollow noreferrer\"><code>date.toordinal</code></a> method in the datetime module.</p>\n<p>You can get the number of days of difference between two dates as follows:</p>\n<pre><code>print(ordinal(2021, 5, 10) - ordinal(2001, 9, 11))\n</code></pre>\n"
},
{
"answer_id": 72822403,
"author": "Martin Kealey",
"author_id": 5781773,
"author_profile": "https://Stackoverflow.com/users/5781773",
"pm_score": 0,
"selected": false,
"text": "<p>If you don't have a date handling library (or you suspect it has bugs in it), here's an abstract algorithm that should be easily translatable into most languages.</p>\n<p>Perform the following calculation on each date, and then simply subtract the two results. All quotients and remainders are positive integers.</p>\n<p>Step A. Start by identifying the parts of the date as <strong>Y</strong> (year), <strong>M</strong> (month) and <strong>D</strong> (day). These are variables that will change as we go along.</p>\n<p>Step B. Subtract 3 from M</p>\n<blockquote>\n<p>(so that January is -2 and December is 9).</p>\n</blockquote>\n<p>Step C. If M is negative, add 12 to M and subtract 1 from the year Y.</p>\n<blockquote>\n<p>(This changes the "start of the year" to 1 March, with months numbered 0 (March) through 11 (February). The reason to do this is so that the "day number within a year" doesn't change between leap years and ordinary years, and so that the "short" month is at the end of the year, so there's no following month needing special treatment.)</p>\n</blockquote>\n<p>Step D.\nDivide M by 5 to get a quotient Q₁ and remainder R₁. <strong>Add Q₁ × 153 to D.</strong> Use R₁ in the next step.</p>\n<blockquote>\n<p>(There are 153 days in every 5 months starting from 1 March.)</p>\n</blockquote>\n<p>Step E. Divide R₁ by 2 to get a quotient Q₂ and ignore the remainder. <strong>Add R₁ × 31 - Q₂ to D.</strong></p>\n<blockquote>\n<p>(Within each group of 5 months, there are 61 days in every 2 months, and within that the first of each pair of months is 31 days. It's safe to ignore the fact that Feb is shorter than 30 days because at this point you only care about the day number of 1-Feb, not of 1-Mar the following year.)</p>\n</blockquote>\n<p>Steps D & E combined - alternative method</p>\n<p>Before the first use, set L=[0,31,61,92,122,153,184,214,245,275,306,337]</p>\n<blockquote>\n<p>(This is a tabulation of the cumulative number of days in the (adjusted) year before the first day of each month.)</p>\n</blockquote>\n<p><strong>Add L[M] to D.</strong></p>\n<p>Step F\nSkip this step if you use Julian calendar dates rather than Gregorian calendar dates; the change-over varies between countries, but is taken as 3 Sep 1752 in most English-speaking countries, and 4 Oct 1582 in most of Europe.</p>\n<blockquote>\n<p>You can also skip this step if you're certain that you'll never have to deal with dates outside the range 1-Mar-1900 to 28-Feb-2100, but then you must make the same choice for all dates that you process.</p>\n</blockquote>\n<p>Divide Y by 100 to get a quotient Q₃ and remainder R₃. Divide Q₃ by 4 to get another quotient Q₄ and ignore the remainder. <strong>Add Q₄ + 36524 × Q₃ to D.</strong></p>\n<p><strong>Assign R₃ to Y.</strong></p>\n<p>Step G.\nDivide the Y by 4 to get a quotient Q₅ and ignore the remainder. <strong>Add Q₅ + 365 × Y to D.</strong></p>\n<p>Step H. (Optional)\nYou can add a constant of your choosing to D, to force a particular date to have a particular day-number.</p>\n<p>Do the steps A~G for each date, getting D₁ and D₂.</p>\n<p>Step I.\nSubtract D₁ from D₂ to get the number of days by which D₂ is after D₁.</p>\n<p>Lastly, a comment: exercise extreme caution dealing with dates prior to about 1760, as there was not agreement on which month was the start of the year; many places counted 1 March as the new year.</p>\n"
}
]
| 2008/09/29 | [
"https://Stackoverflow.com/questions/151199",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4872/"
]
| If I have two dates (ex. `'8/18/2008'` and `'9/26/2008'`), what is the best way to get the number of days between these two dates? | If you have two date objects, you can just subtract them, which computes a [`timedelta`](https://docs.python.org/3/library/datetime.html#datetime.timedelta) object.
```
from datetime import date
d0 = date(2008, 8, 18)
d1 = date(2008, 9, 26)
delta = d1 - d0
print(delta.days)
```
The relevant section of the docs:
<https://docs.python.org/library/datetime.html>.
See [this answer](https://stackoverflow.com/a/8258465) for another example. |
151,204 | <p>I have a folder, '/var/unity/conf' with some properties files in it, and I'd like the Caucho's Resin JVM to have that directory on the classpath.</p>
<p>What is the best way to modifiy resin.conf so that Resin knows to add this directory to the classpath?</p>
| [
{
"answer_id": 151663,
"author": "Vugluskr",
"author_id": 16826,
"author_profile": "https://Stackoverflow.com/users/16826",
"pm_score": 1,
"selected": false,
"text": "<p>cd %RESIN_HOME%/lib | \nln -s /var/unity/conf/....</p>\n"
},
{
"answer_id": 1176542,
"author": "Mike",
"author_id": 54376,
"author_profile": "https://Stackoverflow.com/users/54376",
"pm_score": 2,
"selected": false,
"text": "<p>With Resin 3.1.6 and above, use</p>\n\n<pre><code><server-default>\n ...\n <jvm-classpath>/var/unity/conf/...</jvm-classpath>\n ...\n</server-default>\n</code></pre>\n\n<p>(I know, very late to the game, I was searching for the answer to this myself and found this post here, as well as the solution, so thought I'd add back to the collective).</p>\n"
}
]
| 2008/09/29 | [
"https://Stackoverflow.com/questions/151204",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/18320/"
]
| I have a folder, '/var/unity/conf' with some properties files in it, and I'd like the Caucho's Resin JVM to have that directory on the classpath.
What is the best way to modifiy resin.conf so that Resin knows to add this directory to the classpath? | With Resin 3.1.6 and above, use
```
<server-default>
...
<jvm-classpath>/var/unity/conf/...</jvm-classpath>
...
</server-default>
```
(I know, very late to the game, I was searching for the answer to this myself and found this post here, as well as the solution, so thought I'd add back to the collective). |
151,210 | <p>So I just interviewed two people today, and gave them "tests" to see what their skills were like. Both are entry level applicants, one of which is actually still in college. Neither applicant saw anything wrong with the following code.</p>
<p>I do, obviously or I wouldn't have picked those examples. <strong>Do you think these questions are too harsh for newbie programmers?</strong></p>
<p>I guess I should also note neither of them had much experience with C#... but I don't think the issues with these are language dependent. </p>
<pre><code>//For the following functions, evaluate the code for quality and discuss. E.g.
//E.g. could it be done more efficiently? could it cause bugs?
public void Question1()
{
int active = 0;
CheckBox chkactive = (CheckBox)item.FindControl("chkactive");
if (chkactive.Checked == true)
{
active = 1;
}
dmxdevice.Active = Convert.ToBoolean(active);
}
public void Question2(bool IsPostBack)
{
if (!IsPostBack)
{
BindlistviewNotification();
}
if (lsvnotificationList.Items.Count == 0)
{
BindlistviewNotification();
}
}
//Question 3
protected void lsvnotificationList_ItemUpdating(object sender, ListViewUpdateEventArgs e)
{
ListViewDataItem item = lsvnotificationList.Items[e.ItemIndex];
string Email = ((TextBox)item.FindControl("txtEmailAddress")).Text;
int id = Convert.ToInt32(((HiddenField)item.FindControl("hfID")).Value);
ESLinq.ESLinqDataContext db = new ESLinq.ESLinqDataContext();
var compare = from N in db.NotificationLists
where N.ID == id
select N;
if (compare.Count() > 0)
{
lblmessage.Text = "Record Already Exists";
}
else
{
ESLinq.NotificationList Notice = db.NotificationLists.Where(N => N.ID == id).Single();
Notice.EmailAddress = Email;
db.SubmitChanges();
}
lsvnotificationList.EditIndex = -1;
BindlistviewNotification();
}
</code></pre>
| [
{
"answer_id": 151221,
"author": "jussij",
"author_id": 14738,
"author_profile": "https://Stackoverflow.com/users/14738",
"pm_score": 0,
"selected": false,
"text": "<p><strong>Question #1</strong> </p>\n\n<pre><code> boolean active = true;\n</code></pre>\n\n<p><strong>Question #2</strong> </p>\n\n<pre><code> if ((!IsPostBack) || (lsvnotificationList.Items.Count == 0)) \n</code></pre>\n\n<p><strong>Question #3:</strong></p>\n\n<p>Do a total re-write and add comments. After a 30 second read I still can't tell what the code is trying todo.</p>\n"
},
{
"answer_id": 151225,
"author": "Jason Baker",
"author_id": 2147,
"author_profile": "https://Stackoverflow.com/users/2147",
"pm_score": 3,
"selected": false,
"text": "<p>As a newbie, I would expect employers to care more about what my thought processes were rather than whether the answer was \"correct\" or not. I could come up with some answers to these questions, but they probably wouldn't be right. :)</p>\n\n<p>So with that said, I think you could get by with these questions, but you should definitely be a bit more liberal with what the \"correct\" answer is.</p>\n\n<p>As long as those conditions were made clear, I think that it's a bad thing to get a blank sheet with no thoughts. This means that they either genuinely think the code is perfect (which we know is almost never true) or are too sheepish to share their thoughts (which is also a bad thing).</p>\n"
},
{
"answer_id": 151232,
"author": "Ed S.",
"author_id": 1053,
"author_profile": "https://Stackoverflow.com/users/1053",
"pm_score": 4,
"selected": false,
"text": "<p>I am a junior programmer, so I can give it a try:</p>\n\n<ol>\n<li><p>\"active\" is unnecessary:</p>\n\n<pre><code>CheckBox chkactive = (CheckBox)item.FindControl(\"chkactive\");\ndmxdevice.Active = chkactive.Checked\n</code></pre></li>\n<li><p>You should use safe casting to cast to a CheckBox object. Of course, you should be able to find the checkbox through its variable name anyway.:</p>\n\n<pre><code>CheckBox chkactive = item.FindControl(\"chkactive\") as CheckBox;\n</code></pre></li>\n<li><p>The second function could be more concise:</p>\n\n<pre><code>public void Question2(bool IsPostBack)\n{\n if (!IsPostBack || lsvnotificationList.Items.Count == 0)\n {\n BindlistviewNotification();\n }\n}\n</code></pre></li>\n</ol>\n\n<p>Only have time for those two, work is calling!</p>\n\n<p>EDIT: I just realized that I didn't answer your question. I don't think this is complicated at all. I am no expert by any means and I can easily see the inefficiencies here. I do however think that this is the wrong approach in general. These language specific tests are not very useful in my opinion. Try to get a feeling for how they would attack and solve a problem. Anyone who can get past that test will be able to easily pick up a language and learn from their mistakes.</p>\n"
},
{
"answer_id": 151242,
"author": "Gary Kephart",
"author_id": 17967,
"author_profile": "https://Stackoverflow.com/users/17967",
"pm_score": 1,
"selected": false,
"text": "<p>Not knowing C#, it took me a bit longer, but I'm assuming #1 could be expressed as </p>\n\n<p>dmxdevice.Active = ((CheckBox)item.FindControl(\"chkactive\")).Checked == true</p>\n\n<p>And in #2 the two conditions could be joined as an A OR B statement?</p>\n\n<p>If that's what you're looking for, then no, those aren't too hard. I think #1 is something you might learn only after programming for a little while, but #2 seems easier.\nAre you looking for them to catch null pointer exceptions also?</p>\n"
},
{
"answer_id": 151243,
"author": "Glenn Slaven",
"author_id": 2975,
"author_profile": "https://Stackoverflow.com/users/2975",
"pm_score": 1,
"selected": false,
"text": "<p>I think the first two are fine. The third may be a wee bit complicated for a graduate level interview, but maybe not, it depends whether they've done any .net coding before.</p>\n\n<p>It has LINQ statements in there, and that's pretty new. Especially since many unis/colleges are a bit behind in teaching the latest technology. So I would say run with 1 & 2 and either simplify 3 or heavily comment it as others have mentioned </p>\n"
},
{
"answer_id": 151247,
"author": "Matthew Scharley",
"author_id": 15537,
"author_profile": "https://Stackoverflow.com/users/15537",
"pm_score": -1,
"selected": false,
"text": "<p>Q1 also has a potential InvalidCastException on the <code>item.FindControl()</code> line.</p>\n\n<p>I don't think Q1 or Q2 are outside the realms of being too hard, even for non C# users. Any level code should be able to see that you should be using a boolean for active, and only using one if statement.</p>\n\n<p>Q3 though atleast needs comments as someone else noted. That's not basic code, especially if you're targeting non-C# users with it too.</p>\n"
},
{
"answer_id": 151251,
"author": "Jonathan Leffler",
"author_id": 15168,
"author_profile": "https://Stackoverflow.com/users/15168",
"pm_score": 0,
"selected": false,
"text": "<p>I'm not a C# programmer. On Q1, there seem to be undeclared objects dmxdevice and item, which confuses me. However, there does seem to be a lot of obfuscation in the rest of the code. On Q2, lsvnotificationList is not declared, and it not clear to me why one test is abbreviated with ! and the other with == 0 -- but the tests could be combined with ||, it seems. In Q3, lsvnotificationList is not self-evidently declared, again. For the rest, it seems to be doing a database lookup using LINQ. I'd at least expect that to be factored into a function that validates the hidden field ID more transparently. But if you have other ideas, well...I'm still not a C# programmer.</p>\n"
},
{
"answer_id": 151257,
"author": "Jack Bolding",
"author_id": 5882,
"author_profile": "https://Stackoverflow.com/users/5882",
"pm_score": 1,
"selected": false,
"text": "<p>The first two appear to be more a test to see if a person can follow logically and realize that there is extra code. I'm not convinced that an entry level developer would understand that 'less is more' yet. However, if you explained the answer to Question 1 and they did not then extraplolate that answer to #2, I would be worried.</p>\n"
},
{
"answer_id": 151259,
"author": "Jack Bolding",
"author_id": 5882,
"author_profile": "https://Stackoverflow.com/users/5882",
"pm_score": 1,
"selected": false,
"text": "<p>Question 3 appears to be a big ball of mud type of implementation. This is almost expected to be the style of a junior developer straight from college. I remember most of my profs/TAs in college never read my code -- they only ran the executable and then put in test sets. I would not expect a new developer to understand what was wrong with it...</p>\n"
},
{
"answer_id": 151262,
"author": "itsmatt",
"author_id": 7862,
"author_profile": "https://Stackoverflow.com/users/7862",
"pm_score": 5,
"selected": false,
"text": "<p>I don't typically throw code at someone interviewing for a position and say \"what's wrong?\", mainly because I'm not convinced it really finds me the best candidate. Interviews are sometimes stressful and a bit overwhelming and coders aren't always on their A-game.</p>\n\n<p>Regarding the questions, honestly I think that if I didn't know C#, I'd have a hard time with question 3. Question #2 is a bit funky too. Yes, I get what you're going for there but what if the idea was that BindlistviewNotification() was supposed to be called twice? It isn't clear and one could argue there isn't enough info. Question 1 is easy enough to clean up, but I'm not convinced even it proves anything for an entry-level developer without a background in C#.</p>\n\n<p>I think I'd rather have something talk me through how they'd attack a problem (in pseudo-code or whatever language they are comfortable with) and assess them from that. Just a personal opinion, though.</p>\n"
},
{
"answer_id": 151267,
"author": "Aaron Fischer",
"author_id": 5618,
"author_profile": "https://Stackoverflow.com/users/5618",
"pm_score": 2,
"selected": false,
"text": "<p>So you asked this to someone with no c#, .net, asp.net or linq knowledge? I wouldn't expected anything on the paper?</p>\n"
},
{
"answer_id": 151275,
"author": "Tony BenBrahim",
"author_id": 80075,
"author_profile": "https://Stackoverflow.com/users/80075",
"pm_score": 4,
"selected": false,
"text": "<p>I think you are testing the wrong thing. You are obviously looking for a C# programmer, rather than a talented programmer (not that you cannot be a talented C# programmer). The guys might be great C++ programmers, for example. C# can be learned, smarts cannot. I prefer to ask for code during an interview, rather than presenting code in a specific language (example: implement an ArrayList and a LinkedList in any language).<br>\nWhen I was looking for 3 programmers earlier this year, to work mostly in C#, Java, PL/SQL, Javascript and Delphi, I looked for C/C++ programmers, and have not been disappointed. Any one can learn Java, not everyone has a sense of good arachitecture, data strutures and a grasp of new complex problems. C++ is hard, so it acts as a good filter. If I had asked find errors in this Java code, I would have lost them.<br>\nBTW, I am a team lead, been programming for 20 years with dozens of large projects developed on time and on budget, and I had no clue with what was wrong with question 2 or 3, having only a passing familiarity with C#, and certainly not with Linq, Not that I could not learn it.... I figured it out after a couple minutes, but would not expect a recent graduate to grasp it, all the LINQ code in question 3 is a distraction that hides the real problems.</p>\n"
},
{
"answer_id": 151278,
"author": "FlySwat",
"author_id": 1965,
"author_profile": "https://Stackoverflow.com/users/1965",
"pm_score": 3,
"selected": false,
"text": "<p>I don't think 1 and 2 are too difficult, #3 requires a decent understanding on how databinding and LINQ works in .NET, so it may be somewhat hard for an entry level person. I think these are fairly good questions for junior level developers who have some .NET experience. </p>\n\n<p>For what its worth, my notes:</p>\n\n<h1>Question 1:</h1>\n\n<ul>\n<li>Using an integer as boolean</li>\n<li>No null check on findControl</li>\n<li>Excessive verbosity</li>\n</ul>\n\n<p>My revision:</p>\n\n<pre><code>public void Question1()\n{ \n CheckBox chkactive = item.FindControl(\"chkactive\") as CheckBox;\n if (chkActive != null) \n dmxdevice.Active = chkActive.Checked;\n else\n dmxdevice.Active = false;\n}\n</code></pre>\n\n<h1>Question 2:</h1>\n\n<ul>\n<li>Excessive verbosity</li>\n<li>Databinding will happen twice if its not a postback, and there are no items to bind.</li>\n</ul>\n\n<p>My revision:</p>\n\n<pre><code>public void Question2(bool IsPostBack)\n{\n if (!IsPostBack || lsnotificationList.Items.Count == 0)\n {\n BindlistviewNotification();\n }\n}\n</code></pre>\n\n<h1>Question 3:</h1>\n\n<ul>\n<li>Replace indexed loopup with getting e.Item.DataItem;</li>\n<li>Add nullchecks to findControl calls.</li>\n<li>Switch to TryParse and add a default id value.</li>\n<li>Added better error handling</li>\n<li>Document some major architectural issues, why are you querying the database from the frontend? Those LINQ queries could be optimized too.</li>\n<li>Why not check for duplicates within the list items collection, and why not batch all updates with a single submit later?</li>\n</ul>\n"
},
{
"answer_id": 151282,
"author": "the happy moron",
"author_id": 22987,
"author_profile": "https://Stackoverflow.com/users/22987",
"pm_score": 0,
"selected": false,
"text": "<p>Disclaimer: I come from a 4 year degree and a year's worth of professional Java experience.</p>\n\n<p>The first two questions are quite straightforward and if a candidate doesn't see a better approach I would suspect it's because they haven't been paying attention in class ;-)</p>\n\n<p>Most of the answers to the second question presented so far alter the functions behaviour. The function could very well be evaluated twice in the original code, although I can't say if that is the intent of the function. Side effects are important.</p>\n\n<p>I would probably one-line the first function, myself.</p>\n\n<p>The questions are fairly language agnostic, but they're not library agnostic, which I would argue is equally as important. If you're specifically looking for .NET knowledge, well and good, but without Google I couldn't tell you what an ESLinq.DataContext is, and my answer to the third question suffers accordingly. As it is, it's nearly incomprehensible to me.</p>\n\n<p>I think you also have to be careful how you present the questions. There's nothing <em>incorrect</em> about the first two methods, per se. They're just a little more verbose than they should be. </p>\n\n<p>I would just present them with the sheet and say, \"What do you think of this code?\"\nMake it open ended, that way if they want to bring up error-handling/logging/commenting or other things, it doesn't limit the discussion.</p>\n"
},
{
"answer_id": 151340,
"author": "Kyle Cronin",
"author_id": 658,
"author_profile": "https://Stackoverflow.com/users/658",
"pm_score": 3,
"selected": false,
"text": "<p>I am not a C# programmer so I don't know what BindlistviewNotification does, but changing</p>\n\n<pre><code>public void Question2(bool IsPostBack)\n{\n if (!IsPostBack)\n {\n foo();\n }\n\n if (lsvnotificationList.Items.Count == 0)\n {\n foo();\n }\n}\n</code></pre>\n\n<p>to</p>\n\n<pre><code>public void Question2(bool IsPostBack)\n{\n if (!IsPostBack || lsvnotificationList.Items.Count == 0)\n {\n foo();\n }\n}\n</code></pre>\n\n<p><strong>changes the function</strong>! If IsPostBack is false, foo is executed. If lsvnotificationList.Items.Count == 0 then foo is executed <strong>again</strong>. The revised code will only execute foo <strong>once</strong>.</p>\n\n<p>You could argue that BindlistviewNotification can be executed several times without side effects or that IsPostBack can never be false and lsvnotificationList.Items.Count equal 0 at the same time, but those are language dependent and implementation dependent issues that cannot be resolved with the given code snippet.</p>\n\n<p>Also, if this is a bug that's \"supposed\" to be caught in the interview, this isn't language agnostic at all. There's nothing that would tell me that this is supposed to be a bug.</p>\n"
},
{
"answer_id": 151366,
"author": "Justin R.",
"author_id": 4593,
"author_profile": "https://Stackoverflow.com/users/4593",
"pm_score": 1,
"selected": false,
"text": "<p>What did you expect to get out of this interview? Do your employees have to debug code without a debugger or something? Are you hiring somebody who will be doing only maintenance programming? </p>\n\n<p>In my opinion these questions do little to enlighten you as to the abilities of the candidates. </p>\n"
},
{
"answer_id": 151372,
"author": "ilitirit",
"author_id": 9825,
"author_profile": "https://Stackoverflow.com/users/9825",
"pm_score": 0,
"selected": false,
"text": "<p>A cursory glance indicates that most of the rest of the code suffers from poor structure and unnecessary conditionals etc. There's nothing inherently \"wrong\" with that, especially if the program runs as expected. Maybe you should change the question?</p>\n\n<p>On the other hand, the casting doesn't look like it's being done correctly at all eg. (cast)object.Method() vs (cast)(object.Method()) vs ((cast)object).Method(). In the first case, it's not a language agnostic problem though - it depends on rules of precedence.</p>\n\n<p>I don't think it was that hard, but it all depends on what you wanted to test. IMO, the smart candidate should have asked a lot of questions about the function of the program and the structure of the classes before attempting to answer. eg. How are they supposed to know if \"item\" is a global/member var if they don't ask? How do they know it's type? Do they even know if it supports a FindControl method? What about FindControl's return type?</p>\n\n<p>I'm not sure how many colleges teach Linq yet though, so maybe you should remove that part.</p>\n"
},
{
"answer_id": 151401,
"author": "Orion Edwards",
"author_id": 234,
"author_profile": "https://Stackoverflow.com/users/234",
"pm_score": 3,
"selected": false,
"text": "<blockquote>\n <p>Do you think these questions are too harsh for newbie programmers?</p>\n</blockquote>\n\n<p>Yes, IMO they are too harsh.</p>\n\n<blockquote>\n <p>Neither applicant saw anything wrong with the following code.</p>\n</blockquote>\n\n<ol>\n<li><p>While there are plenty of 'possible problems', like not checking for null pointers, casting, etc, there don't appear to be any 'actual problems.' (eg: given sane input, the program looks like it will actually run).<br>\nI'd guess that a newbie programmer will get hung up on that.</p></li>\n<li><p>As linq is pretty new, and still not in wide use, it's going to go <em>way</em> over the head of your newbies.</p></li>\n<li><p>What is an <code>ESLinqDataContext</code>? If people have no idea what your object is or how it behaves, how are they supposed to know if it is being used correctly or not?</p></li>\n<li><blockquote>\n <p>evaluate the code for quality and discuss </p>\n</blockquote></li>\n</ol>\n\n<p>You only really learn to pick up stuff like invalid cast exceptions (let alone being able to judge and comment on 'code quality') from reasonable experience working with code similar to what's in front of you.</p>\n\n<p>Perhaps I'm misunderstanding, but to me, an \"entry level\" position pretty much by definition has no expectation of prior experience, so it doesn't seem fair to grade them on criteria which require experience.</p>\n"
},
{
"answer_id": 151415,
"author": "Adam Davis",
"author_id": 2915,
"author_profile": "https://Stackoverflow.com/users/2915",
"pm_score": 1,
"selected": false,
"text": "<h2>This is a fine question if you're looking for a maintenance programmer, or tester.</h2>\n\n<p>However, this isn't a good test to detect a good programmer. A good programmer will pass this test, certainly, but many programmers that are not good will also pass it.</p>\n\n<p>If you want a good programmer, you need to define a test that only a good programmer would pass. A good programmer has excellent problem solving skills, and knows how to ask questions to get to the kernel of a problem before they start working - saving both them and you time.</p>\n\n<p>A good programmer can program in many different languages with only a little learning curve, so your 'code' test can consist of pseudo code. Tell them you want them to solve a problem and have them write the solution in pseudo code - which means they don't have access to all those nifty libraries. A good programmer knows how the libraries function and can re-create them if needed.</p>\n\n<p>So... yeah, you're essentially asking textbook knowledge questions - items that show memorization and language knowledge, but not skills necessary to solve a problem.</p>\n\n<p>-Adam</p>\n"
},
{
"answer_id": 151450,
"author": "Marcel",
"author_id": 131,
"author_profile": "https://Stackoverflow.com/users/131",
"pm_score": -1,
"selected": false,
"text": "<p>In question 2 for better modularity I would suggest passing the count of lsvnotificationList.Items as a parameter:</p>\n\n<pre><code>public void Question2(bool IsPostBack, int listItemsCount)\n{\n if (!IsPostBack || listItemsCount == 0)\n BindlistviewNotification();\n}\n</code></pre>\n"
},
{
"answer_id": 151456,
"author": "Jim Burger",
"author_id": 20164,
"author_profile": "https://Stackoverflow.com/users/20164",
"pm_score": 2,
"selected": false,
"text": "<p>My only advice is to make sure your test questions actually compile. </p>\n\n<p>I think the value in FizzBuzz type questions is watching HOW somebody solves your problems. </p>\n\n<p>Watching them load the solution in to the IDE, compile it, step through the code with a step through debugger, write tests for the apparent intended behavior and then refactoring the code such that it is more correct/maintainable is more valuable than knowing that they can read code and comprehend it.</p>\n"
},
{
"answer_id": 151499,
"author": "Amy B",
"author_id": 8155,
"author_profile": "https://Stackoverflow.com/users/8155",
"pm_score": 0,
"selected": false,
"text": "<p>No one's answering #3 with code. That should indicate how people feel about it. Usually stackoverflowers meet these head-first.</p>\n\n<p>Here's my stab at it. I had to look up the EventArgs on msdn to know the properties. I know LINQ because I've studied it closely for the past 8 months. I don't have much UI experience, so I can't tell if the call to bind in the event handler is bad (or other such things that would be obvious to a UI coder).</p>\n\n<pre><code>protected void lsvnotificationList_ItemUpdating(object sender, ListViewUpdateEventArgs e)\n{\n string Email = e.NewValues[\"EmailAddress\"].ToString();\n int id = Convert.ToInt32(e.NewValues[\"ID\"]);\n\n using (ESLinq.ESLinqDataContext db = new ESLinq.ESLinqDataContext(connectionString))\n {\n List<NotificationList> compare = db.NotificationLists.Where(n => n.ID = id).ToList();\n\n if (!compare.Any())\n {\n lblmessage.Text = \"Record Does Not Exist\";\n }\n else\n {\n NotificationList Notice = compare.First();\n Notice.EmailAddress = Email;\n db.SubmitChanges();\n }\n }\n lsvnotificationList.EditIndex = -1;\n BindlistviewNotification();\n\n}\n</code></pre>\n"
},
{
"answer_id": 151599,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 0,
"selected": false,
"text": "<p>While people here obviously have no trouble hitting this code in their spare time, as someone who went through the whole job search/interviewing process fresh out of collage about a year ago I think you have to remember how stressful questions like these can be. I understand you were just looking for thought process, but I think you would get more out of people if you brought questions like this up casually and conversationally after you calm the interviewee down. This may sound like a cop out, but questions about code that will technically work, but needs some pruning, can be much more difficult then correcting code that doesn't compile, because people will assume that the examples are suppose to not compile, and will drive themselves up a wall trying to figure out the trick to your questions. Some people never get stressed by interview questions, but alot do, even some talented programmers that you probably don't want to rule out, unless you are preparing them for a situation where they have to program with a loaded gun to their head.</p>\n\n<p>The code itself in question 3 seems very C# specific. I only know that as LINQ because someone pointed it out in the answers here, but coming in as a Java developer, I would not recognize that at all. I mean do you really expect colleges to teach a feature that was only recently introduced in .net 3.5?</p>\n\n<p>I'd also liked to point out how many people here were tripped up by question 2, by streamlining the code, they accidentally changed the behavior of the code. That should tell you alot about the difficulty of your questions.</p>\n"
},
{
"answer_id": 151692,
"author": "CodeRedick",
"author_id": 17145,
"author_profile": "https://Stackoverflow.com/users/17145",
"pm_score": 0,
"selected": false,
"text": "<p>Ok, so after staying up well past my bedtime to read all the answers and comment on most of them...</p>\n\n<p>General concensus seems to be that the questions aren't too bad but, especially for Q3, could be better served by using pseudo-code or some other technique to hide some of the language specific stuff.</p>\n\n<p>I guess for now I'll just not weigh these questions in too heavily.</p>\n\n<p>(Of course, their lack of SQL knowledge is still disturbing... if only because they both had SQL on their resume. :( )</p>\n"
},
{
"answer_id": 153620,
"author": "Mark T",
"author_id": 10722,
"author_profile": "https://Stackoverflow.com/users/10722",
"pm_score": 0,
"selected": false,
"text": "<p>I'll have to say that my answer to these problems is that without comments (or documentation) explaining what the code is MEANT to do, there is little reason to even look at the code. The code does EXACTLY what it does. If you change it to do something else, even change it to prevent throwing an exception, you may make it do something unintended and break the larger program.</p>\n\n<p>The problem with all three questions is that there is no intent. If you modify the code, you are assuming that you know the intent of the original coder. And that assumption will often be wrong.</p>\n\n<p>And to answer the question: Yes, this is too difficult for most junior programmers, because documenting code is never taught.</p>\n"
},
{
"answer_id": 342871,
"author": "daduffer",
"author_id": 43473,
"author_profile": "https://Stackoverflow.com/users/43473",
"pm_score": 1,
"selected": false,
"text": "<p>It's funny to see everyone jumping to change or fix the code. The questions targeted \"efficiently? could it cause bugs?\" Answers: Given enough time and money, sure each one could probably be made more efficient. Bugs, please try to avoid casting and writing difficult to read code (code should be self-documenting). If it doesn't have bugs it might after the next junior programmer tries to change it... Also, avoid writing code that appears to rely on state contained outside the scope of the method/function, those nasty global variables. If I got some insightful comments like this it might be appropriate to use this as a tool to create some good conversation. But, I think some better ice-breakers exist to determine if a persons critical thinking skills are appropriate and if they will fit in with the rest of the team. I don't think playing stump the programmer is very effective.</p>\n"
},
{
"answer_id": 1162072,
"author": "Yvo",
"author_id": 136819,
"author_profile": "https://Stackoverflow.com/users/136819",
"pm_score": 0,
"selected": false,
"text": "<p>Okey I'm not going to answer the C# questions from what I see here you have enough candidates that would do fine in a job interview with you.</p>\n\n<p>I do think that the tests won't give you a good view of a persons programming skills. Have a look at Joel's interviewing Guide:<br>\n<a href=\"http://www.joelonsoftware.com/articles/fog0000000073.html\" rel=\"nofollow noreferrer\">http://www.joelonsoftware.com/articles/fog0000000073.html</a></p>\n\n<p>He talks about two things when it comes to possible candidates: are they smart AND do they get the job done (now that's a powerful combination).Let your candidates talk a bit about projects they did or what they're toying around with at home. Find out if they are passionate about programming. Some experience is nice of course, just don't ask them to do tricks.</p>\n"
}
]
| 2008/09/29 | [
"https://Stackoverflow.com/questions/151210",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/17145/"
]
| So I just interviewed two people today, and gave them "tests" to see what their skills were like. Both are entry level applicants, one of which is actually still in college. Neither applicant saw anything wrong with the following code.
I do, obviously or I wouldn't have picked those examples. **Do you think these questions are too harsh for newbie programmers?**
I guess I should also note neither of them had much experience with C#... but I don't think the issues with these are language dependent.
```
//For the following functions, evaluate the code for quality and discuss. E.g.
//E.g. could it be done more efficiently? could it cause bugs?
public void Question1()
{
int active = 0;
CheckBox chkactive = (CheckBox)item.FindControl("chkactive");
if (chkactive.Checked == true)
{
active = 1;
}
dmxdevice.Active = Convert.ToBoolean(active);
}
public void Question2(bool IsPostBack)
{
if (!IsPostBack)
{
BindlistviewNotification();
}
if (lsvnotificationList.Items.Count == 0)
{
BindlistviewNotification();
}
}
//Question 3
protected void lsvnotificationList_ItemUpdating(object sender, ListViewUpdateEventArgs e)
{
ListViewDataItem item = lsvnotificationList.Items[e.ItemIndex];
string Email = ((TextBox)item.FindControl("txtEmailAddress")).Text;
int id = Convert.ToInt32(((HiddenField)item.FindControl("hfID")).Value);
ESLinq.ESLinqDataContext db = new ESLinq.ESLinqDataContext();
var compare = from N in db.NotificationLists
where N.ID == id
select N;
if (compare.Count() > 0)
{
lblmessage.Text = "Record Already Exists";
}
else
{
ESLinq.NotificationList Notice = db.NotificationLists.Where(N => N.ID == id).Single();
Notice.EmailAddress = Email;
db.SubmitChanges();
}
lsvnotificationList.EditIndex = -1;
BindlistviewNotification();
}
``` | I don't typically throw code at someone interviewing for a position and say "what's wrong?", mainly because I'm not convinced it really finds me the best candidate. Interviews are sometimes stressful and a bit overwhelming and coders aren't always on their A-game.
Regarding the questions, honestly I think that if I didn't know C#, I'd have a hard time with question 3. Question #2 is a bit funky too. Yes, I get what you're going for there but what if the idea was that BindlistviewNotification() was supposed to be called twice? It isn't clear and one could argue there isn't enough info. Question 1 is easy enough to clean up, but I'm not convinced even it proves anything for an entry-level developer without a background in C#.
I think I'd rather have something talk me through how they'd attack a problem (in pseudo-code or whatever language they are comfortable with) and assess them from that. Just a personal opinion, though. |
151,231 | <p>I need to get the actual local network IP address of the computer (e.g. 192.168.0.220) from my program using C# and .NET 3.5. I can't just use 127.0.0.1 in this case.</p>
<p>How can I accomplish this?</p>
| [
{
"answer_id": 151237,
"author": "PostMan",
"author_id": 18405,
"author_profile": "https://Stackoverflow.com/users/18405",
"pm_score": 6,
"selected": true,
"text": "<p>In <a href=\"http://www.devcity.net/Articles/62/1/gethostbyname.aspx\" rel=\"nofollow noreferrer\" title=\"Article by John Spano, Published 1 Dec 2002\"><em>How to get IP addresses in .NET with a host name</em></a> by John Spano, it says to add the <code>System.Net</code> namespace, and use the following code:</p>\n<blockquote>\n<pre><code>//To get the local IP address \nstring sHostName = Dns.GetHostName (); \nIPHostEntry ipE = Dns.GetHostByName (sHostName); \nIPAddress [] IpA = ipE.AddressList; \nfor (int i = 0; i < IpA.Length; i++) \n{ \n Console.WriteLine ("IP Address {0}: {1} ", i, IpA[i].ToString ()); \n}\n</code></pre>\n</blockquote>\n"
},
{
"answer_id": 151258,
"author": "Jerub",
"author_id": 14648,
"author_profile": "https://Stackoverflow.com/users/14648",
"pm_score": 4,
"selected": false,
"text": "<p>As a machine can have multiple ip addresses, the correct way to figure out your ip address that you're going to be using to route to the general internet is to open a socket to a host on the internet, then inspect the socket connection to see what the local address that is being used in that connection is.</p>\n\n<p>By inspecting the socket connection, you will be able to take into account weird routing tables, multiple ip addresses and whacky hostnames. The trick with the hostname above can work, but I wouldn't consider it entirely reliable.</p>\n"
},
{
"answer_id": 151313,
"author": "GBegen",
"author_id": 10223,
"author_profile": "https://Stackoverflow.com/users/10223",
"pm_score": 5,
"selected": false,
"text": "<p>If you are looking for the sort of information that the command line utility, ipconfig, can provide, you should probably be using the System.Net.NetworkInformation namespace.</p>\n\n<p>This sample code will enumerate all of the network interfaces and dump the addresses known for each adapter.</p>\n\n<pre><code>using System;\nusing System.Net;\nusing System.Net.NetworkInformation;\n\nclass Program\n{\n static void Main(string[] args)\n {\n foreach ( NetworkInterface netif in NetworkInterface.GetAllNetworkInterfaces() )\n {\n Console.WriteLine(\"Network Interface: {0}\", netif.Name);\n IPInterfaceProperties properties = netif.GetIPProperties();\n foreach ( IPAddress dns in properties.DnsAddresses )\n Console.WriteLine(\"\\tDNS: {0}\", dns);\n foreach ( IPAddressInformation anycast in properties.AnycastAddresses )\n Console.WriteLine(\"\\tAnyCast: {0}\", anycast.Address);\n foreach ( IPAddressInformation multicast in properties.MulticastAddresses )\n Console.WriteLine(\"\\tMultiCast: {0}\", multicast.Address);\n foreach ( IPAddressInformation unicast in properties.UnicastAddresses )\n Console.WriteLine(\"\\tUniCast: {0}\", unicast.Address);\n }\n }\n}\n</code></pre>\n\n<p>You are probably most interested in the UnicastAddresses.</p>\n"
},
{
"answer_id": 151349,
"author": "James Curran",
"author_id": 12725,
"author_profile": "https://Stackoverflow.com/users/12725",
"pm_score": 5,
"selected": false,
"text": "<p>Using Dns requires that your computer be registered with the local DNS server, which is not necessarily true if you're on a intranet, and even less likely if you're at home with an ISP. It also requires a network roundtrip -- all to find out info about your own computer.</p>\n\n<p>The proper way:</p>\n\n<pre><code>NetworkInterface[] nics = NetworkInterface.GetAllNetworkInterfaces();\nforeach(NetworkInterface adapter in nics)\n{\n foreach(var x in adapter.GetIPProperties().UnicastAddresses)\n {\n if (x.Address.AddressFamily == AddressFamily.InterNetwork && x.IsDnsEligible)\n {\n Console.WriteLine(\" IPAddress ........ : {0:x}\", x.Address.ToString());\n }\n }\n}\n</code></pre>\n\n<p>(UPDATE 31-Jul-2015: Fixed some problems with the code)</p>\n\n<p>Or for those who like just a line of Linq:</p>\n\n<pre><code>NetworkInterface.GetAllNetworkInterfaces()\n .SelectMany(adapter=> adapter.GetIPProperties().UnicastAddresses)\n .Where(adr=>adr.Address.AddressFamily == AddressFamily.InterNetwork && adr.IsDnsEligible)\n .Select (adr => adr.Address.ToString());\n</code></pre>\n"
},
{
"answer_id": 19432629,
"author": "Edward Brey",
"author_id": 145173,
"author_profile": "https://Stackoverflow.com/users/145173",
"pm_score": 1,
"selected": false,
"text": "<p>If you know there are one or more IPv4 addresses for your computer, this will provide one of them:</p>\n\n<pre><code>Dns.GetHostAddresses(Dns.GetHostName())\n .First(a => a.AddressFamily == AddressFamily.InterNetwork).ToString()\n</code></pre>\n\n<p><code>GetHostAddresses</code> normally blocks the calling thread while it queries the DNS server, and throws a <code>SocketException</code> if the query fails. I don't know whether it skips the network call when looking up your own host name.</p>\n"
}
]
| 2008/09/29 | [
"https://Stackoverflow.com/questions/151231",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1512/"
]
| I need to get the actual local network IP address of the computer (e.g. 192.168.0.220) from my program using C# and .NET 3.5. I can't just use 127.0.0.1 in this case.
How can I accomplish this? | In [*How to get IP addresses in .NET with a host name*](http://www.devcity.net/Articles/62/1/gethostbyname.aspx "Article by John Spano, Published 1 Dec 2002") by John Spano, it says to add the `System.Net` namespace, and use the following code:
>
>
> ```
> //To get the local IP address
> string sHostName = Dns.GetHostName ();
> IPHostEntry ipE = Dns.GetHostByName (sHostName);
> IPAddress [] IpA = ipE.AddressList;
> for (int i = 0; i < IpA.Length; i++)
> {
> Console.WriteLine ("IP Address {0}: {1} ", i, IpA[i].ToString ());
> }
>
> ```
>
> |
151,238 | <p>It seems that I've never got this to work in the past. Currently, I KNOW it doesn't work.</p>
<p>But we start up our Java process:</p>
<pre><code>-Dcom.sun.management.jmxremote
-Dcom.sun.management.jmxremote.port=6002
-Dcom.sun.management.jmxremote.authenticate=false
-Dcom.sun.management.jmxremote.ssl=false
</code></pre>
<p>I can telnet to the port, and "something is there" (that is, if I don't start the process, nothing answers, but if I do, it does), but I can not get JConsole to work filling in the IP and port.</p>
<p>Seems like it should be so simple, but no errors, no noise, no nothing. Just doesn't work.</p>
<p>Anyone know the hot tip for this?</p>
| [
{
"answer_id": 151626,
"author": "Craig Day",
"author_id": 5193,
"author_profile": "https://Stackoverflow.com/users/5193",
"pm_score": 4,
"selected": false,
"text": "<p>Are you running on Linux? Perhaps the management agent is binding to localhost:</p>\n\n<p><a href=\"http://java.sun.com/j2se/1.5.0/docs/guide/management/faq.html#linux1\" rel=\"noreferrer\">http://java.sun.com/j2se/1.5.0/docs/guide/management/faq.html#linux1</a></p>\n"
},
{
"answer_id": 362878,
"author": "eljenso",
"author_id": 30316,
"author_profile": "https://Stackoverflow.com/users/30316",
"pm_score": 2,
"selected": false,
"text": "<p>When testing/debugging/diagnosing <em>remote</em> JMX problems, first always try to connect on the same host that contains the MBeanServer (i.e. localhost), to rule out network and other non-JMX specific problems.</p>\n"
},
{
"answer_id": 362947,
"author": "Simon Groenewolt",
"author_id": 31884,
"author_profile": "https://Stackoverflow.com/users/31884",
"pm_score": 4,
"selected": false,
"text": "<p>You are probably experiencing an issue with a firewall. The 'problem' is that the port you specify is not the only port used, it uses 1 or maybe even 2 more ports for RMI, and those are probably blocked by a firewall.</p>\n\n<p>One of the extra ports will not be know up front if you use the default RMI configuration, so you have to open up a big range of ports - which might not amuse the server administrator.</p>\n\n<p>There is a solution that does not require opening up a lot of ports however, I've gotten it to work using the combined source snippets and tips from</p>\n\n<p><s><a href=\"http://forums.sun.com/thread.jspa?threadID=5267091\" rel=\"nofollow noreferrer\">http://forums.sun.com/thread.jspa?threadID=5267091</a></s> - link doesn't work anymore</p>\n\n<p><a href=\"http://blogs.oracle.com/jmxetc/entry/connecting_through_firewall_using_jmx\" rel=\"nofollow noreferrer\">http://blogs.oracle.com/jmxetc/entry/connecting_through_firewall_using_jmx</a></p>\n\n<p><a href=\"http://java.sun.com/javase/6/docs/technotes/guides/management/agent.html\" rel=\"nofollow noreferrer\">http://java.sun.com/javase/6/docs/technotes/guides/management/agent.html</a></p>\n\n<p>It's even possible to setup an ssh tunnel and still get it to work :-)</p>\n"
},
{
"answer_id": 900006,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 6,
"selected": false,
"text": "<p>Adding <code>-Djava.rmi.server.hostname='<host ip>'</code> resolved this problem for me.</p>\n"
},
{
"answer_id": 3256207,
"author": "kishore",
"author_id": 392775,
"author_profile": "https://Stackoverflow.com/users/392775",
"pm_score": 1,
"selected": false,
"text": "<p>I am running JConsole/JVisualVm on windows hooking to tomcat running Linux Redhat ES3.</p>\n\n<p>Disabling packet filtering using the following command did the trick for me:</p>\n\n<pre><code>/usr/sbin/iptables -I INPUT -s jconsole-host -p tcp --destination-port jmxremote-port -j ACCEPT\n</code></pre>\n\n<p>where jconsole-host is either the hostname or the host address on which JConsole runs on and jmxremote-port is the port number set for com.sun.management.jmxremote.port for remote management. </p>\n"
},
{
"answer_id": 15686258,
"author": "Joseph",
"author_id": 2220472,
"author_profile": "https://Stackoverflow.com/users/2220472",
"pm_score": 0,
"selected": false,
"text": "<p>You need to also make sure that your machine name resolves to the IP that JMX is binding to; NOT localhost nor 127.0.0.1. For me, it has helped to put an entry into hosts that explicitly defines this.</p>\n"
},
{
"answer_id": 17142474,
"author": "user85155",
"author_id": 85155,
"author_profile": "https://Stackoverflow.com/users/85155",
"pm_score": 2,
"selected": false,
"text": "<p>Getting JMX through the Firewall is really hard. The Problem is that standard RMI uses a second random assigned port (beside the RMI registry).</p>\n\n<p>We have three solution that work, but every case needs a different one:</p>\n\n<ol>\n<li><p>JMX over SSH Tunnel with Socks proxy, uses standard RMI with SSH magic\n<a href=\"http://simplygenius.com/2010/08/jconsole-via-socks-ssh-tunnel.html\" rel=\"nofollow\">http://simplygenius.com/2010/08/jconsole-via-socks-ssh-tunnel.html</a></p></li>\n<li><p>JMX MP (alternative to standard RMI), uses only one fixed port, but needs a special jar on server and client\n<a href=\"http://meteatamel.wordpress.com/2012/02/13/jmx-rmi-vs-jmxmp/\" rel=\"nofollow\">http://meteatamel.wordpress.com/2012/02/13/jmx-rmi-vs-jmxmp/</a></p></li>\n<li><p>Start JMX Server form code, there it is possible to use standard RMI and use a fixed second port:\n<a href=\"https://issues.apache.org/bugzilla/show_bug.cgi?id=39055\" rel=\"nofollow\">https://issues.apache.org/bugzilla/show_bug.cgi?id=39055</a></p></li>\n</ol>\n"
},
{
"answer_id": 17457394,
"author": "sushicutta",
"author_id": 1531271,
"author_profile": "https://Stackoverflow.com/users/1531271",
"pm_score": 7,
"selected": false,
"text": "<p>I have a solution for this:</p>\n\n<p>If your <strong>Java process is running on Linux behind a firewall</strong> and you want to start <strong>JConsole / Java VisualVM / Java Mission Control</strong> on Windows on your local machine to connect it to the <strong>JMX Port of your Java process</strong>.</p>\n\n<p>You need access to your linux machine via SSH login. All Communication will be tunneled over the SSH connection.</p>\n\n<p><strong>TIP:</strong> This Solution works no matter if there is a firewall or not.</p>\n\n<p><strong>Disadvantage:</strong> Everytime you <strong>restart</strong> your java process, you will need to do all steps from 4 - 9 again.</p>\n\n<p><br> </p>\n\n<h1>1. You need the putty-suite for your Windows machine from here:</h1>\n\n<blockquote>\n <p><a href=\"http://www.chiark.greenend.org.uk/~sgtatham/putty/download.html\" rel=\"noreferrer\">http://www.chiark.greenend.org.uk/~sgtatham/putty/download.html</a></p>\n \n <p>At least the <strong>putty.exe</strong></p>\n</blockquote>\n\n<p><br> </p>\n\n<h1>2. Define one free Port on your linux machine:</h1>\n\n<pre><code><jmx-remote-port>\n</code></pre>\n\n<h3>Example:</h3>\n\n<pre><code>jmx-remote-port = 15666 \n</code></pre>\n\n<p><br> </p>\n\n<h1>3. Add arguments to java process on the linux machine</h1>\n\n<p>This must be done exactly like this. If its done like below, it works for linux Machines behind firewalls (It works cause of the <code>-Djava.rmi.server.hostname=localhost</code> argument).</p>\n\n<pre><code>-Dcom.sun.management.jmxremote\n-Dcom.sun.management.jmxremote.port=<jmx-remote-port>\n-Dcom.sun.management.jmxremote.ssl=false\n-Dcom.sun.management.jmxremote.authenticate=false\n-Dcom.sun.management.jmxremote.local.only=false\n-Djava.rmi.server.hostname=localhost\n</code></pre>\n\n<h3>Example:</h3>\n\n<pre><code>java -Dcom.sun.management.jmxremote -Dcom.sun.management.jmxremote.port=15666 -Dcom.sun.management.jmxremote.ssl=false -Dcom.sun.management.jmxremote.authenticate=false -Dcom.sun.management.jmxremote.local.only=false -Djava.rmi.server.hostname=localhost ch.sushicutta.jmxremote.Main\n</code></pre>\n\n<p><br> </p>\n\n<h1>4. Get Process-Id of your Java Process</h1>\n\n<pre><code>ps -ef | grep <java-processname>\n\nresult ---> <process-id>\n</code></pre>\n\n<h3>Example:</h3>\n\n<pre><code>ps -ef | grep ch.sushicutta.jmxremote.Main\n\nresult ---> 24321\n</code></pre>\n\n<p><br> </p>\n\n<h1>5. Find arbitrary Port for RMIServer stubs download</h1>\n\n<p>The java process opens a new TCP Port on the linux machine, where the RMI Server-Stubs will be available for download. This port also needs to be available via SSH Tunnel to get a connection to the Java Virtual Machine.</p>\n\n<p>With <code>netstat -lp</code> this port can be found also the <code>lsof -i</code> gives hints what port has been opened form the java process.</p>\n\n<p><strong>NOTE: This port always changes when java process is started.</strong></p>\n\n<pre><code>netstat -lp | grep <process-id>\n\ntcp 0 0 *:<jmx-remote-port> *:* LISTEN 24321/java\ntcp 0 0 *:<rmi-server-port> *:* LISTEN 24321/java\n\n\nresult ---> <rmi-server-port>\n</code></pre>\n\n<h3>Example:</h3>\n\n<pre><code>netstat -lp | grep 24321\n\ntcp 0 0 *:15666 *:* LISTEN 24321/java\ntcp 0 0 *:37123 *:* LISTEN 24321/java\n\n\nresult ---> 37123\n</code></pre>\n\n<p><br></p>\n\n<h1>6. Enable two SSH-Tunnels from your Windows machine with putty</h1>\n\n<pre><code>Source port: <jmx-remote-port>\nDestination: localhost:<jmx-remote-port>\n[x] Local \n[x] Auto \n\nSource port: <rmi-server-port>\nDestination: localhost:<rmi-server-port>\n[x] Local \n[x] Auto\n</code></pre>\n\n<h3>Example:</h3>\n\n<pre><code>Source port: 15666\nDestination: localhost:15666\n[x] Local \n[x] Auto \n\nSource port: 37123\nDestination: localhost:37123\n[x] Local \n[x] Auto\n</code></pre>\n\n<p><br> </p>\n\n<p><img src=\"https://i.stack.imgur.com/CHa4j.jpg\" alt=\"Settings to open an SSL tunnel via Putty\"></p>\n\n<p><br> </p>\n\n<h1>7. Login to your Linux machine with Putty with this SSH-Tunnel enabled.</h1>\n\n<p><strong>Leave the putty session open.</strong> </p>\n\n<p>When you are logged in, Putty will tunnel all TCP-Connections to the linux machine over the SSH port 22.</p>\n\n<p>JMX-Port:</p>\n\n<pre><code>Windows machine: localhost:15666 >>> SSH >>> linux machine: localhost:15666\n</code></pre>\n\n<p>RMIServer-Stub-Port:</p>\n\n<pre><code>Windows Machine: localhost:37123 >>> SSH >>> linux machine: localhost:37123\n</code></pre>\n\n<p><br> </p>\n\n<h1>8. Start JConsole / Java VisualVM / Java Mission Control to connect to your Java Process using the following URL</h1>\n\n<p>This works, cause JConsole / Java VisualVM / Java Mission Control thinks you connect to a Port on your local Windows machine. but Putty send all payload to the port 15666 to your linux machine.</p>\n\n<p>On the linux machine first the java process gives answer and send back the RMIServer Port. In this example 37123.</p>\n\n<p>Then JConsole / Java VisualVM / Java Mission Control thinks it connects to localhost:37123 and putty will send the whole payload forward to the linux machine</p>\n\n<p>The java Process answers and the connection is open.</p>\n\n<pre><code>[x] Remote Process:\nservice:jmx:rmi:///jndi/rmi://localhost:<jndi-remote-port>/jmxrmi\n</code></pre>\n\n<h3>Example:</h3>\n\n<pre><code>[x] Remote Process:\nservice:jmx:rmi:///jndi/rmi://localhost:15666/jmxrmi\n</code></pre>\n\n<p><br></p>\n\n<p><img src=\"https://i.stack.imgur.com/QnfvI.jpg\" alt=\"Connect via jmx service url\"> </p>\n\n<p><br> </p>\n\n<h1>9. ENJOY #8-]</h1>\n"
},
{
"answer_id": 18454794,
"author": "Lukasz",
"author_id": 363282,
"author_profile": "https://Stackoverflow.com/users/363282",
"pm_score": 0,
"selected": false,
"text": "<p>Getting JMX through the firewall isn't that hard at all. There is one small catch. You have to forward both your JMX configured port ie. 9010 and one of dynamic ports its listens to on my machine it was > 30000</p>\n"
},
{
"answer_id": 19315119,
"author": "supdog",
"author_id": 2870472,
"author_profile": "https://Stackoverflow.com/users/2870472",
"pm_score": 3,
"selected": false,
"text": "<p>PROTIP: </p>\n\n<p>The RMI port are opened at arbitrary portnr's. If you have a firewall and don't want to open ports 1024-65535 (or use vpn) then you need to do the following.</p>\n\n<p>You need to fix (as in having a known number) the RMI Registry and JMX/RMI Server ports. You do this by putting a jar-file (catalina-jmx-remote.jar it's in the extra's) in the lib-dir and configuring a special listener under server:</p>\n\n<pre><code><Listener className=\"org.apache.catalina.mbeans.JmxRemoteLifecycleListener\"\n rmiRegistryPortPlatform=\"10001\" rmiServerPortPlatform=\"10002\" />\n</code></pre>\n\n<p>(And ofcourse the usual flags for activating JMX</p>\n\n<pre><code> -Dcom.sun.management.jmxremote \\\n -Dcom.sun.management.jmxremote.ssl=false \\\n -Dcom.sun.management.jmxremote.authenticate=false \\\n -Djava.rmi.server.hostname=<HOSTNAME> \\\n</code></pre>\n\n<p>See: JMX Remote Lifecycle Listener at <a href=\"http://tomcat.apache.org/tomcat-6.0-doc/config/listeners.html\" rel=\"noreferrer\">http://tomcat.apache.org/tomcat-6.0-doc/config/listeners.html</a></p>\n\n<p>Then you can connect using this horrific URL: </p>\n\n<pre><code>service:jmx:rmi://<hostname>:10002/jndi/rmi://<hostname>:10001/jmxrmi\n</code></pre>\n"
},
{
"answer_id": 27512104,
"author": "Sergio",
"author_id": 1750869,
"author_profile": "https://Stackoverflow.com/users/1750869",
"pm_score": 4,
"selected": false,
"text": "<p>After putting my Google-fu to the test for the last couple of days, I was finally able to get this to work after compiling answers from Stack Overflow and this page <a href=\"http://help.boomi.com/atomsphere/GUID-F787998C-53C8-4662-AA06-8B1D32F9D55B.html\" rel=\"nofollow noreferrer\">http://help.boomi.com/atomsphere/GUID-F787998C-53C8-4662-AA06-8B1D32F9D55B.html</a>.</p>\n<p>Reposting from the Dell Boomi page:</p>\n<pre><code>To Enable Remote JMX on an Atom\n\nIf you want to monitor the status of an Atom, you need to turn on Remote JMX (Java Management Extensions) for the Atom.\n\nUse a text editor to open the <atom_installation_directory>\\bin\\atom.vmoptions file.\n\nAdd the following lines to the file:\n\n-Dcom.sun.management.jmxremote.port=5002\n-Dcom.sun.management.jmxremote.rmi.port=5002\n-Dcom.sun.management.jmxremote.authenticate=false\n-Dcom.sun.management.jmxremote.ssl=false\n</code></pre>\n<p>The one line that I haven't seen any Stack Overflow answer cover is</p>\n<pre><code>-Dcom.sun.management.jmxremote.rmi.port=5002\n</code></pre>\n<p>In my case, I was attempting to retrieve Kafka metrics, so I simply changed the above option to match the <code>-Dcom.sun.management.jmxremote.port</code> value. So, without authentication of any kind, the bare minimum config should look like this:</p>\n<pre><code>-Dcom.sun.management.jmxremote\n-Dcom.sun.management.jmxremote.authenticate=false\n-Dcom.sun.management.jmxremote.ssl=false\n-Dcom.sun.management.jmxremote.port=(jmx remote port)\n\n-Dcom.sun.management.jmxremote.local.only=false\n-Dcom.sun.management.jmxremote.rmi.port=(jmx remote port)\n-Djava.rmi.server.hostname=(CNAME|IP Address)\n</code></pre>\n"
},
{
"answer_id": 28167086,
"author": "RichS",
"author_id": 6247,
"author_profile": "https://Stackoverflow.com/users/6247",
"pm_score": 2,
"selected": false,
"text": "<p>There are already some great answers here, but, there is a slightly simpler approach that I think it is worth sharing.</p>\n\n<p>sushicutta's approach is good, but is very manual as you have to get the RMI Port every time. Thankfully, we can work around that by using a SOCKS proxy rather than explicitly opening the port tunnels. The downside of this approach is JMX app you run on your machine needs to be able to be configured to use a Proxy. Most processes you can do this from adding java properties, but, some apps don't support this.</p>\n\n<p>Steps:</p>\n\n<ol>\n<li><p>Add the JMX options to the startup script for your remote Java service:</p>\n\n<pre><code>-Dcom.sun.management.jmxremote=true\n-Dcom.sun.management.jmxremote.port=8090\n-Dcom.sun.management.jmxremote.ssl=false\n-Dcom.sun.management.jmxremote.authenticate=false\n</code></pre></li>\n<li><p>Set up a SOCKS proxy connection to your remote machine:</p>\n\n<pre><code>ssh -D 9696 [email protected]\n</code></pre></li>\n<li><p>Configure your local Java monitoring app to use the SOCKS proxy (localhost:9696). Note: You can <em>sometimes</em> do this from the command line, i.e.:</p>\n\n<pre><code>jconsole -J-DsocksProxyHost=localhost -J-DsocksProxyPort=9696\n</code></pre></li>\n</ol>\n"
},
{
"answer_id": 28441044,
"author": "Mariusz",
"author_id": 1291727,
"author_profile": "https://Stackoverflow.com/users/1291727",
"pm_score": 0,
"selected": false,
"text": "<p>These are the steps that worked for me (debian behind firewall on the server side, reached over VPN from my local Mac):</p>\n\n<p>check server ip</p>\n\n<pre><code>hostname -i\n</code></pre>\n\n<p>use JVM params:</p>\n\n<pre><code>-Dcom.sun.management.jmxremote\n-Dcom.sun.management.jmxremote.port=[jmx port]\n-Dcom.sun.management.jmxremote.local.only=false\n-Dcom.sun.management.jmxremote.authenticate=false\n-Dcom.sun.management.jmxremote.ssl=false\n-Djava.rmi.server.hostname=[server ip from step 1]\n</code></pre>\n\n<p>run application</p>\n\n<p>find pid of the running java process</p>\n\n<p>check all ports used by JMX/RMI</p>\n\n<pre><code>netstat -lp | grep [pid from step 4]\n</code></pre>\n\n<p>open all ports from step 5 on the firewall</p>\n\n<p>Voila.</p>\n"
},
{
"answer_id": 30524467,
"author": "smallo",
"author_id": 3006519,
"author_profile": "https://Stackoverflow.com/users/3006519",
"pm_score": 1,
"selected": false,
"text": "<p>I'm using boot2docker to run docker containers with Tomcat inside and I've got the same problem, the solution was to:</p>\n\n<ul>\n<li>Add <code>-Djava.rmi.server.hostname=192.168.59.103</code></li>\n<li>Use the same JMX port in host and docker container, for instance: <code>docker run ... -p 9999:9999 ...</code>. Using different ports does not work.</li>\n</ul>\n"
},
{
"answer_id": 30636640,
"author": "arganzheng",
"author_id": 2423557,
"author_profile": "https://Stackoverflow.com/users/2423557",
"pm_score": 3,
"selected": false,
"text": "<p>Check if your server is behind the firewall. JMX is base on RMI, which open two port when it start. One is the register port, default is 1099, and can be specified by the <code>com.sun.management.jmxremote.port</code> option. The other is for data communication, and is random, which is what cause problem. A good news is that, from JDK6, this random port can be specified by the <code>com.sun.management.jmxremote.rmi.port</code> option. </p>\n\n<pre><code>export CATALINA_OPTS=\"-Dcom.sun.management.jmxremote -Dcom.sun.management.jmxremote.port=8991 -Dcom.sun.management.jmxremote.rmi.port=8991 -Dcom.sun.management.jmxremote.authenticate=false -Dcom.sun.management.jmxremote.ssl=false\"\n</code></pre>\n"
},
{
"answer_id": 32748795,
"author": "Andrés S.",
"author_id": 3469015,
"author_profile": "https://Stackoverflow.com/users/3469015",
"pm_score": 0,
"selected": false,
"text": "<p>In order to make a contribution, this is what I did on CentOS 6.4 for Tomcat 6.</p>\n\n<ol>\n<li><p>Shutdown iptables service</p>\n\n<pre><code>service iptables stop\n</code></pre></li>\n<li><p>Add the following line to tomcat6.conf</p>\n\n<pre><code>CATALINA_OPTS=\"${CATALINA_OPTS} -Dcom.sun.management.jmxremote -Dcom.sun.management.jmxremote.port=8085 -Dcom.sun.management.jmxremote.ssl=false -Dcom.sun.management.jmxremote.authenticate=false -Djava.rmi.server.hostname=[host_ip]\"\n</code></pre></li>\n</ol>\n\n<p>This way I was able to connect from another PC using JConsole.</p>\n"
},
{
"answer_id": 33892861,
"author": "freedev",
"author_id": 336827,
"author_profile": "https://Stackoverflow.com/users/336827",
"pm_score": 6,
"selected": false,
"text": "<h2>Tried with Java 8 and newer versions</h2>\n\n<p>This solution works well also with firewalls</p>\n\n<h3>1. Add this to your java startup script on remote-host:</h3>\n\n<pre><code>-Dcom.sun.management.jmxremote.port=1616\n-Dcom.sun.management.jmxremote.rmi.port=1616\n-Dcom.sun.management.jmxremote.ssl=false\n-Dcom.sun.management.jmxremote.authenticate=false\n-Dcom.sun.management.jmxremote.local.only=false\n-Djava.rmi.server.hostname=localhost\n</code></pre>\n\n<h3>2. Execute this on your computer.</h3>\n\n<ul>\n<li><p><em>Windows users</em>:</p>\n\n<p><code>putty.exe -ssh user@remote-host -L 1616:remote-host:1616</code></p></li>\n<li><p><em>Linux and Mac Users</em>:</p>\n\n<p><code>ssh user@remote-host -L 1616:remote-host:1616</code></p></li>\n</ul>\n\n<h3>3. Start <code>jconsole</code> on your computer</h3>\n\n<pre><code>jconsole localhost:1616\n</code></pre>\n\n<h3>4. Have fun!</h3>\n\n<p>P.S.: during step 2, using <code>ssh</code> and <code>-L</code> you specify that the port 1616 on the local (client) host must be forwarded to the remote side. This is an ssh tunnel and helps to avoids firewalls or various networks problems.</p>\n"
},
{
"answer_id": 36499387,
"author": "user2412906",
"author_id": 2412906,
"author_profile": "https://Stackoverflow.com/users/2412906",
"pm_score": 3,
"selected": false,
"text": "<p>Sushicutta's steps 4-7 can be skipped by adding the following line to step 3:</p>\n\n<pre><code>-Dcom.sun.management.jmxremote.rmi.port=<same port as jmx-remote-port>\n</code></pre>\n\n<p>e.g.\nAdd to start up parameters:</p>\n\n<pre><code>-Dcom.sun.management.jmxremote\n-Dcom.sun.management.jmxremote.port=12345\n-Dcom.sun.management.jmxremote.rmi.port=12345\n-Dcom.sun.management.jmxremote.ssl=false\n-Dcom.sun.management.jmxremote.authenticate=false\n-Dcom.sun.management.jmxremote.local.only=false\n-Djava.rmi.server.hostname=localhost\n</code></pre>\n\n<p>For the port forwarding, connect using:</p>\n\n<pre><code>ssh -L 12345:localhost:12345 <username>@<host>\n</code></pre>\n\n<p>if your host is a stepping stone, simply chain the port forward by running the following on the step stone after the above:</p>\n\n<pre><code>ssh -L 12345:localhost:12345 <username>@<host2>\n</code></pre>\n\n<p>Mind that the <strong>hostname=localhost</strong> is needed to make sure the jmxremote is telling the rmi connection to use the tunnel. Otherwise it might try to connect directy and hit the firewall.</p>\n"
},
{
"answer_id": 41274022,
"author": "Russ Bateman",
"author_id": 339736,
"author_profile": "https://Stackoverflow.com/users/339736",
"pm_score": 0,
"selected": false,
"text": "<p>I'm trying to JMC to run the Flight Recorder (JFR) to profile NiFi on a remote server that doesn't offer a graphical environment on which to run JMC.</p>\n\n<p>Based on the other answers given here, and upon much trial and error, here is what I'm supplying to the JVM (<em>conf/bootstrap.conf</em>)when I launch NiFi:</p>\n\n<pre><code>java.arg.90=-Dcom.sun.management.jmxremote=true\njava.arg.91=-Dcom.sun.management.jmxremote.port=9098\njava.arg.92=-Dcom.sun.management.jmxremote.rmi.port=9098\njava.arg.93=-Dcom.sun.management.jmxremote.authenticate=false\njava.arg.94=-Dcom.sun.management.jmxremote.ssl=false\njava.arg.95=-Dcom.sun.management.jmxremote.local.only=false\njava.arg.96=-Djava.rmi.server.hostname=10.10.10.92 (the IP address of my server running NiFi)\n</code></pre>\n\n<p>I did put this in <em>/etc/hosts</em>, though I doubt it's needed:</p>\n\n<pre><code>10.10.10.92 localhost\n</code></pre>\n\n<p>Then, upon launching JMC, I create a remote connection with these properties:</p>\n\n<pre><code>Host: 10.10.10.92\nPort: 9098\nUser: (nothing)\nPassword: (ibid)\n</code></pre>\n\n<p>Incidentally, if I click the Custom JMX service URL, I see:</p>\n\n<pre><code>service:jmx:rmi:///jndi/rmi://10.10.10.92:9098/jmxrmi\n</code></pre>\n\n<p>This finally did it for me.</p>\n"
},
{
"answer_id": 52735308,
"author": "Andi M.",
"author_id": 6919547,
"author_profile": "https://Stackoverflow.com/users/6919547",
"pm_score": 2,
"selected": false,
"text": "<p>The following worked for me (though I think port 2101 did not really contribute to this):</p>\n\n<pre><code>-Dcom.sun.management.jmxremote.port=2100\n-Dcom.sun.management.jmxremote.authenticate=false\n-Dcom.sun.management.jmxremote.ssl=false\n-Dcom.sun.management.jmxremote.local.only=false\n-Dcom.sun.management.jmxremote.rmi.port=2101\n-Djava.rmi.server.hostname=<IP_ADDRESS>OR<HOSTNAME>\n</code></pre>\n\n<p>I am connecting from a remote machine to a server which has Docker running and the process is inside the container. Also, I stopped firewallD but I don't think that was the issue as I could telnet to 2100 even with the firewall open.\nHope it helps.</p>\n"
}
]
| 2008/09/29 | [
"https://Stackoverflow.com/questions/151238",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/13663/"
]
| It seems that I've never got this to work in the past. Currently, I KNOW it doesn't work.
But we start up our Java process:
```
-Dcom.sun.management.jmxremote
-Dcom.sun.management.jmxremote.port=6002
-Dcom.sun.management.jmxremote.authenticate=false
-Dcom.sun.management.jmxremote.ssl=false
```
I can telnet to the port, and "something is there" (that is, if I don't start the process, nothing answers, but if I do, it does), but I can not get JConsole to work filling in the IP and port.
Seems like it should be so simple, but no errors, no noise, no nothing. Just doesn't work.
Anyone know the hot tip for this? | I have a solution for this:
If your **Java process is running on Linux behind a firewall** and you want to start **JConsole / Java VisualVM / Java Mission Control** on Windows on your local machine to connect it to the **JMX Port of your Java process**.
You need access to your linux machine via SSH login. All Communication will be tunneled over the SSH connection.
**TIP:** This Solution works no matter if there is a firewall or not.
**Disadvantage:** Everytime you **restart** your java process, you will need to do all steps from 4 - 9 again.
1. You need the putty-suite for your Windows machine from here:
===============================================================
>
> <http://www.chiark.greenend.org.uk/~sgtatham/putty/download.html>
>
>
> At least the **putty.exe**
>
>
>
2. Define one free Port on your linux machine:
==============================================
```
<jmx-remote-port>
```
### Example:
```
jmx-remote-port = 15666
```
3. Add arguments to java process on the linux machine
=====================================================
This must be done exactly like this. If its done like below, it works for linux Machines behind firewalls (It works cause of the `-Djava.rmi.server.hostname=localhost` argument).
```
-Dcom.sun.management.jmxremote
-Dcom.sun.management.jmxremote.port=<jmx-remote-port>
-Dcom.sun.management.jmxremote.ssl=false
-Dcom.sun.management.jmxremote.authenticate=false
-Dcom.sun.management.jmxremote.local.only=false
-Djava.rmi.server.hostname=localhost
```
### Example:
```
java -Dcom.sun.management.jmxremote -Dcom.sun.management.jmxremote.port=15666 -Dcom.sun.management.jmxremote.ssl=false -Dcom.sun.management.jmxremote.authenticate=false -Dcom.sun.management.jmxremote.local.only=false -Djava.rmi.server.hostname=localhost ch.sushicutta.jmxremote.Main
```
4. Get Process-Id of your Java Process
======================================
```
ps -ef | grep <java-processname>
result ---> <process-id>
```
### Example:
```
ps -ef | grep ch.sushicutta.jmxremote.Main
result ---> 24321
```
5. Find arbitrary Port for RMIServer stubs download
===================================================
The java process opens a new TCP Port on the linux machine, where the RMI Server-Stubs will be available for download. This port also needs to be available via SSH Tunnel to get a connection to the Java Virtual Machine.
With `netstat -lp` this port can be found also the `lsof -i` gives hints what port has been opened form the java process.
**NOTE: This port always changes when java process is started.**
```
netstat -lp | grep <process-id>
tcp 0 0 *:<jmx-remote-port> *:* LISTEN 24321/java
tcp 0 0 *:<rmi-server-port> *:* LISTEN 24321/java
result ---> <rmi-server-port>
```
### Example:
```
netstat -lp | grep 24321
tcp 0 0 *:15666 *:* LISTEN 24321/java
tcp 0 0 *:37123 *:* LISTEN 24321/java
result ---> 37123
```
6. Enable two SSH-Tunnels from your Windows machine with putty
==============================================================
```
Source port: <jmx-remote-port>
Destination: localhost:<jmx-remote-port>
[x] Local
[x] Auto
Source port: <rmi-server-port>
Destination: localhost:<rmi-server-port>
[x] Local
[x] Auto
```
### Example:
```
Source port: 15666
Destination: localhost:15666
[x] Local
[x] Auto
Source port: 37123
Destination: localhost:37123
[x] Local
[x] Auto
```

7. Login to your Linux machine with Putty with this SSH-Tunnel enabled.
=======================================================================
**Leave the putty session open.**
When you are logged in, Putty will tunnel all TCP-Connections to the linux machine over the SSH port 22.
JMX-Port:
```
Windows machine: localhost:15666 >>> SSH >>> linux machine: localhost:15666
```
RMIServer-Stub-Port:
```
Windows Machine: localhost:37123 >>> SSH >>> linux machine: localhost:37123
```
8. Start JConsole / Java VisualVM / Java Mission Control to connect to your Java Process using the following URL
================================================================================================================
This works, cause JConsole / Java VisualVM / Java Mission Control thinks you connect to a Port on your local Windows machine. but Putty send all payload to the port 15666 to your linux machine.
On the linux machine first the java process gives answer and send back the RMIServer Port. In this example 37123.
Then JConsole / Java VisualVM / Java Mission Control thinks it connects to localhost:37123 and putty will send the whole payload forward to the linux machine
The java Process answers and the connection is open.
```
[x] Remote Process:
service:jmx:rmi:///jndi/rmi://localhost:<jndi-remote-port>/jmxrmi
```
### Example:
```
[x] Remote Process:
service:jmx:rmi:///jndi/rmi://localhost:15666/jmxrmi
```

9. ENJOY #8-]
============= |
151,303 | <p>Using the <code>AddHandler</code> method, if I never use <code>RemoveHandler</code>, will that lead to memory leaks in some conditions and situations? I'm not so sure about the truth of this.</p>
<p>And are there other causes to memory leaks that are solely available in VB as opposed to C#?</p>
| [
{
"answer_id": 151306,
"author": "albertein",
"author_id": 23020,
"author_profile": "https://Stackoverflow.com/users/23020",
"pm_score": 1,
"selected": false,
"text": "<p>If object a is suscribed to the object b event then object b will not be collected until object a is collected.</p>\n\n<p>An event suscription counts as a reference to the publisher object.</p>\n\n<p>And yes, this happens on C# too, i has nothing to do with the language.</p>\n"
},
{
"answer_id": 151430,
"author": "Gishu",
"author_id": 1695,
"author_profile": "https://Stackoverflow.com/users/1695",
"pm_score": 4,
"selected": false,
"text": "<p><em>Well usually it doesn't.. but the possibility exists.</em><br>\nWhen you subscribe to an event, you basically give a delegate (a func pointer if you will) to your method to the event publisher, who holds on to it as long as you do not unsubscribe with the -= operator.</p>\n\n<p>So take for example, the case where you spawn a child form and the form subscribes to the Click button event on the form. </p>\n\n<pre><code>button1.Click += new EventHandler(Form_Click_Handler);\n</code></pre>\n\n<p>Now the button object will hold on to the form reference.. When the form is closed/disposed/set to null both form and button are not needed anymore; memory is reclaimed. </p>\n\n<p>The trouble happens when you have a global structure or object which has a bigger lifetime. Lets say the Application object maintains a list of open child windows. So whenever a child form is created, the application object subscribes to a Form event so that it can keep tabs on it. In this case, even when the form is closed/disposed the application object keeps it alive (a non-garbage object holds a ref to the form) and doesn't allow its memory to be reclaimed. As you keep creating and closing windows, you have a leak with your app hogging more and more memory. Hence you need to explicitly unsubscribe to remove the form reference from the application.</p>\n\n<pre><code>childForm.Event -= new EventHandler(Form_Handler)\n</code></pre>\n\n<p><strong>So its recommended that you have a unsubscribe block (-=) complementing your subscribe routine (+=)... however you could manage without it for the stock scenarios.</strong></p>\n"
}
]
| 2008/09/30 | [
"https://Stackoverflow.com/questions/151303",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/8505/"
]
| Using the `AddHandler` method, if I never use `RemoveHandler`, will that lead to memory leaks in some conditions and situations? I'm not so sure about the truth of this.
And are there other causes to memory leaks that are solely available in VB as opposed to C#? | *Well usually it doesn't.. but the possibility exists.*
When you subscribe to an event, you basically give a delegate (a func pointer if you will) to your method to the event publisher, who holds on to it as long as you do not unsubscribe with the -= operator.
So take for example, the case where you spawn a child form and the form subscribes to the Click button event on the form.
```
button1.Click += new EventHandler(Form_Click_Handler);
```
Now the button object will hold on to the form reference.. When the form is closed/disposed/set to null both form and button are not needed anymore; memory is reclaimed.
The trouble happens when you have a global structure or object which has a bigger lifetime. Lets say the Application object maintains a list of open child windows. So whenever a child form is created, the application object subscribes to a Form event so that it can keep tabs on it. In this case, even when the form is closed/disposed the application object keeps it alive (a non-garbage object holds a ref to the form) and doesn't allow its memory to be reclaimed. As you keep creating and closing windows, you have a leak with your app hogging more and more memory. Hence you need to explicitly unsubscribe to remove the form reference from the application.
```
childForm.Event -= new EventHandler(Form_Handler)
```
**So its recommended that you have a unsubscribe block (-=) complementing your subscribe routine (+=)... however you could manage without it for the stock scenarios.** |
151,338 | <p>How can I add an instance variable to a defined class at <b>runtime</b>, and later get and set its value from outside of the class?</p>
<p>I'm looking for a metaprogramming solution that allows me to modify the class instance at runtime instead of modifying the source code that originally defined the class. A few of the solutions explain how to declare instance variables in the class definitions, but that is not what I am asking about. </p>
| [
{
"answer_id": 151354,
"author": "Gordon Wilson",
"author_id": 23071,
"author_profile": "https://Stackoverflow.com/users/23071",
"pm_score": 6,
"selected": false,
"text": "<p>Ruby provides methods for this, <code>instance_variable_get</code> and <code>instance_variable_set</code>. (<a href=\"http://www.ruby-doc.org/core/classes/Object.html\" rel=\"noreferrer\">docs</a>)</p>\n\n<p>You can create and assign a new instance variables like this:</p>\n\n<pre><code>>> foo = Object.new\n=> #<Object:0x2aaaaaacc400>\n\n>> foo.instance_variable_set(:@bar, \"baz\")\n=> \"baz\"\n\n>> foo.inspect\n=> #<Object:0x2aaaaaacc400 @bar=\\\"baz\\\">\n</code></pre>\n"
},
{
"answer_id": 151359,
"author": "Mike Stone",
"author_id": 122,
"author_profile": "https://Stackoverflow.com/users/122",
"pm_score": 5,
"selected": true,
"text": "<p>You can use attribute accessors:</p>\n\n<pre><code>class Array\n attr_accessor :var\nend\n</code></pre>\n\n<p>Now you can access it via:</p>\n\n<pre><code>array = []\narray.var = 123\nputs array.var\n</code></pre>\n\n<hr>\n\n<p>Note that you can also use <code>attr_reader</code> or <code>attr_writer</code> to define just getters or setters or you can define them manually as such:</p>\n\n<pre><code>class Array\n attr_reader :getter_only_method\n attr_writer :setter_only_method\n\n # Manual definitions equivalent to using attr_reader/writer/accessor\n def var\n @var\n end\n\n def var=(value)\n @var = value\n end\nend\n</code></pre>\n\n<hr>\n\n<p>You can also use singleton methods if you just want it defined on a single instance:</p>\n\n<pre><code>array = []\n\ndef array.var\n @var\nend\n\ndef array.var=(value)\n @var = value\nend\n\narray.var = 123\nputs array.var\n</code></pre>\n\n<hr>\n\n<p>FYI, in response to the comment on this answer, the singleton method works fine, and the following is proof:</p>\n\n<pre><code>irb(main):001:0> class A\nirb(main):002:1> attr_accessor :b\nirb(main):003:1> end\n=> nil\nirb(main):004:0> a = A.new\n=> #<A:0x7fbb4b0efe58>\nirb(main):005:0> a.b = 1\n=> 1\nirb(main):006:0> a.b\n=> 1\nirb(main):007:0> def a.setit=(value)\nirb(main):008:1> @b = value\nirb(main):009:1> end\n=> nil\nirb(main):010:0> a.setit = 2\n=> 2\nirb(main):011:0> a.b\n=> 2\nirb(main):012:0> \n</code></pre>\n\n<p>As you can see, the singleton method <code>setit</code> will set the same field, <code>@b</code>, as the one defined using the attr_accessor... so a singleton method is a perfectly valid approach to this question.</p>\n"
},
{
"answer_id": 151398,
"author": "webmat",
"author_id": 6349,
"author_profile": "https://Stackoverflow.com/users/6349",
"pm_score": 2,
"selected": false,
"text": "<p><a href=\"https://stackoverflow.com/questions/151338/adding-an-instance-variable-to-a-class-in-ruby#151359\">Mike Stone's answer</a> is already quite comprehensive, but I'd like to add a little detail.</p>\n\n<p>You can modify your class at any moment, even after some instance have been created, and get the results you desire. You can try it out in your console:</p>\n\n<pre><code>s1 = 'string 1'\ns2 = 'string 2'\n\nclass String\n attr_accessor :my_var\nend\n\ns1.my_var = 'comment #1'\ns2.my_var = 'comment 2'\n\nputs s1.my_var, s2.my_var\n</code></pre>\n"
},
{
"answer_id": 151440,
"author": "Mike Stone",
"author_id": 122,
"author_profile": "https://Stackoverflow.com/users/122",
"pm_score": 0,
"selected": false,
"text": "<p>Readonly, in response to your edit:</p>\n\n<blockquote>\n <p>Edit: It looks like I need to clarify\n that I'm looking for a metaprogramming\n solution that allows me to modify the\n class instance at runtime instead of\n modifying the source code that\n originally defined the class. A few of\n the solutions explain how to declare\n instance variables in the class\n definitions, but that is not what I am\n asking about. Sorry for the confusion.</p>\n</blockquote>\n\n<p>I think you don't quite understand the concept of \"open classes\", which means you can open up a class at any time. For example:</p>\n\n<pre><code>class A\n def hello\n print \"hello \"\n end\nend\n\nclass A\n def world\n puts \"world!\"\n end\nend\n\na = A.new\na.hello\na.world\n</code></pre>\n\n<p>The above is perfectly valid Ruby code, and the 2 class definitions can be spread across multiple Ruby files. You could use the \"define_method\" method in the Module object to define a new method on a class instance, but it is equivalent to using open classes.</p>\n\n<p>\"Open classes\" in Ruby means you can redefine ANY class at ANY point in time... which means add new methods, redefine existing methods, or whatever you want really. It sounds like the \"open class\" solution really is what you are looking for...</p>\n"
},
{
"answer_id": 151477,
"author": "Mike Stone",
"author_id": 122,
"author_profile": "https://Stackoverflow.com/users/122",
"pm_score": 2,
"selected": false,
"text": "<p>The other solutions will work perfectly too, but here is an example using define_method, if you are hell bent on not using open classes... it will define the \"var\" variable for the array class... but note that it is EQUIVALENT to using an open class... the benefit is you can do it for an unknown class (so any object's class, rather than opening a specific class)... also define_method will work inside a method, whereas you cannot open a class within a method.</p>\n\n<pre><code>array = []\narray.class.send(:define_method, :var) { @var }\narray.class.send(:define_method, :var=) { |value| @var = value }\n</code></pre>\n\n<p>And here is an example of it's use... note that array2, a <strong>DIFFERENT</strong> array also has the methods, so if this is not what you want, you probably want singleton methods which I explained in another post.</p>\n\n<pre><code>irb(main):001:0> array = []\n=> []\nirb(main):002:0> array.class.send(:define_method, :var) { @var }\n=> #<Proc:0x00007f289ccb62b0@(irb):2>\nirb(main):003:0> array.class.send(:define_method, :var=) { |value| @var = value }\n=> #<Proc:0x00007f289cc9fa88@(irb):3>\nirb(main):004:0> array.var = 123\n=> 123\nirb(main):005:0> array.var\n=> 123\nirb(main):006:0> array2 = []\n=> []\nirb(main):007:0> array2.var = 321\n=> 321\nirb(main):008:0> array2.var\n=> 321\nirb(main):009:0> array.var\n=> 123\n</code></pre>\n"
},
{
"answer_id": 152193,
"author": "Mike Stone",
"author_id": 122,
"author_profile": "https://Stackoverflow.com/users/122",
"pm_score": 4,
"selected": false,
"text": "<p>@<a href=\"https://stackoverflow.com/questions/151338/adding-an-instance-variable-to-a-class-in-ruby#151797\">Readonly</a></p>\n\n<p>If your usage of \"class MyObject\" is a usage of an open class, then please note you are redefining the initialize method.</p>\n\n<p>In Ruby, there is no such thing as overloading... only overriding, or redefinition... in other words there can only be 1 instance of any given method, so if you redefine it, it is redefined... and the initialize method is no different (even though it is what the new method of Class objects use).</p>\n\n<p>Thus, never redefine an existing method without aliasing it first... at least if you want access to the original definition. And redefining the initialize method of an unknown class may be quite risky.</p>\n\n<p>At any rate, I think I have a much simpler solution for you, which uses the actual metaclass to define singleton methods:</p>\n\n<pre><code>m = MyObject.new\nmetaclass = class << m; self; end\nmetaclass.send :attr_accessor, :first, :second\nm.first = \"first\"\nm.second = \"second\"\nputs m.first, m.second\n</code></pre>\n\n<p>You can use both the metaclass and open classes to get even trickier and do something like:</p>\n\n<pre><code>class MyObject\n def metaclass\n class << self\n self\n end\n end\n\n def define_attributes(hash)\n hash.each_pair { |key, value|\n metaclass.send :attr_accessor, key\n send \"#{key}=\".to_sym, value\n }\n end\nend\n\nm = MyObject.new\nm.define_attributes({ :first => \"first\", :second => \"second\" })\n</code></pre>\n\n<p>The above is basically exposing the metaclass via the \"metaclass\" method, then using it in define_attributes to dynamically define a bunch of attributes with attr_accessor, and then invoking the attribute setter afterwards with the associated value in the hash.</p>\n\n<p>With Ruby you can get creative and do the same thing many different ways ;-)</p>\n\n<hr>\n\n<p>FYI, in case you didn't know, using the metaclass as I have done means you are only acting on the given instance of the object. Thus, invoking define_attributes will only define those attributes for that particular instance.</p>\n\n<p>Example:</p>\n\n<pre><code>m1 = MyObject.new\nm2 = MyObject.new\nm1.define_attributes({:a => 123, :b => 321})\nm2.define_attributes({:c => \"abc\", :d => \"zxy\"})\nputs m1.a, m1.b, m2.c, m2.d # this will work\nm1.c = 5 # this will fail because c= is not defined on m1!\nm2.a = 5 # this will fail because a= is not defined on m2!\n</code></pre>\n"
},
{
"answer_id": 13335121,
"author": "musicmatze",
"author_id": 1391026,
"author_profile": "https://Stackoverflow.com/users/1391026",
"pm_score": 0,
"selected": false,
"text": "<p>I wrote a gem for this some time ago. It's called \"Flexible\" and not available via rubygems, but was available via github until yesterday. I deleted it because it was useless for me.</p>\n\n<p>You can do</p>\n\n<pre><code>class Foo\n include Flexible\nend\nf = Foo.new\nf.bar = 1\n</code></pre>\n\n<p>with it without getting any error. So you can set and get instance variables from an object on the fly.\nIf you are interessted... I could upload the source code to github again. It needs some modification to enable</p>\n\n<pre><code>f.bar?\n#=> true\n</code></pre>\n\n<p>as method for asking the object if a instance variable \"bar\" is defined or not, but anything else is running.</p>\n\n<p>Kind regards, musicmatze</p>\n"
},
{
"answer_id": 33244256,
"author": "Huliax",
"author_id": 1025695,
"author_profile": "https://Stackoverflow.com/users/1025695",
"pm_score": 0,
"selected": false,
"text": "<p>It looks like all of the previous answers assume that you know what the name of the class that you want to tweak is when you are writing your code. Well, that isn't always true (at least, not for me). I might be iterating over a pile of classes that I want to bestow some variable on (say, to hold some metadata or something). In that case something like this will do the job,</p>\n\n<pre><code># example classes that we want to tweak\nclass Foo;end\nclass Bar;end\nklasses = [Foo, Bar]\n\n# iterating over a collection of klasses\nklasses.each do |klass|\n # #class_eval gets it done\n klass.class_eval do\n attr_accessor :baz\n end\nend\n\n# it works\nf = Foo.new\nf.baz # => nil\nf.baz = 'it works' # => \"it works\"\nb = Bar.new\nb.baz # => nil\nb.baz = 'it still works' # => \"it still works\"\n</code></pre>\n"
}
]
| 2008/09/30 | [
"https://Stackoverflow.com/questions/151338",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4883/"
]
| How can I add an instance variable to a defined class at **runtime**, and later get and set its value from outside of the class?
I'm looking for a metaprogramming solution that allows me to modify the class instance at runtime instead of modifying the source code that originally defined the class. A few of the solutions explain how to declare instance variables in the class definitions, but that is not what I am asking about. | You can use attribute accessors:
```
class Array
attr_accessor :var
end
```
Now you can access it via:
```
array = []
array.var = 123
puts array.var
```
---
Note that you can also use `attr_reader` or `attr_writer` to define just getters or setters or you can define them manually as such:
```
class Array
attr_reader :getter_only_method
attr_writer :setter_only_method
# Manual definitions equivalent to using attr_reader/writer/accessor
def var
@var
end
def var=(value)
@var = value
end
end
```
---
You can also use singleton methods if you just want it defined on a single instance:
```
array = []
def array.var
@var
end
def array.var=(value)
@var = value
end
array.var = 123
puts array.var
```
---
FYI, in response to the comment on this answer, the singleton method works fine, and the following is proof:
```
irb(main):001:0> class A
irb(main):002:1> attr_accessor :b
irb(main):003:1> end
=> nil
irb(main):004:0> a = A.new
=> #<A:0x7fbb4b0efe58>
irb(main):005:0> a.b = 1
=> 1
irb(main):006:0> a.b
=> 1
irb(main):007:0> def a.setit=(value)
irb(main):008:1> @b = value
irb(main):009:1> end
=> nil
irb(main):010:0> a.setit = 2
=> 2
irb(main):011:0> a.b
=> 2
irb(main):012:0>
```
As you can see, the singleton method `setit` will set the same field, `@b`, as the one defined using the attr\_accessor... so a singleton method is a perfectly valid approach to this question. |
151,348 | <p>Why is NodeList undefined in IE6/7?</p>
<pre><code><form action="/" method="post" id="testform">
<input type="checkbox" name="foobar[]" value="1" id="" />
<input type="checkbox" name="foobar[]" value="2" id="" />
<input type="checkbox" name="foobar[]" value="3" id="" />
</form>
<script type="text/javascript" charset="utf-8">
(function () {
var el = document.getElementById('testform')['foobar[]']
if (el instanceof NodeList) {
alert("I'm a NodeList");
}
})();
</script>
</code></pre>
<p>This works in FF3/Safari 3.1 but doesn't work in IE6/7. Anyone have any ideas how to check if el is an instance of NodeList across all browsers?</p>
| [
{
"answer_id": 151412,
"author": "Jeremy DeGroot",
"author_id": 20820,
"author_profile": "https://Stackoverflow.com/users/20820",
"pm_score": 0,
"selected": false,
"text": "<p>I would just use something that always evaluates to a certain type. Then you just do a true/false type check to see if you got a valid object. In your case, I would get a reference to the select item like you are now, and then use its getOptions() method to get an HTMLCollection that represents the options. This object type is very similar to a NodeList, so you should have no problem working with it.</p>\n"
},
{
"answer_id": 151631,
"author": "Adam Franco",
"author_id": 15872,
"author_profile": "https://Stackoverflow.com/users/15872",
"pm_score": 4,
"selected": false,
"text": "<p>\"<a href=\"http://en.wikipedia.org/wiki/Duck_typing\" rel=\"noreferrer\">Duck Typing</a>\" should always work:</p>\n\n<pre><code>...\n\nif (typeof el.length == 'number' \n && typeof el.item == 'function'\n && typeof el.nextNode == 'function'\n && typeof el.reset == 'function')\n{\n alert(\"I'm a NodeList\");\n}\n</code></pre>\n"
},
{
"answer_id": 8452783,
"author": "Andrew Banks",
"author_id": 448801,
"author_profile": "https://Stackoverflow.com/users/448801",
"pm_score": 0,
"selected": false,
"text": "<p>With <strong>jQuery</strong>:</p>\n\n<pre><code>if (1 < $(el).length) {\n alert(\"I'm a NodeList\");\n}\n</code></pre>\n"
},
{
"answer_id": 10740835,
"author": "craigpatik",
"author_id": 348995,
"author_profile": "https://Stackoverflow.com/users/348995",
"pm_score": 2,
"selected": false,
"text": "<p>Adam Franco's answer <em>almost</em> works. Unfortunately, <code>typeof el.item</code> returns different things in different version of IE (7: string, 8: object, 9: function). So I am using his code, but I changed the line to <code>typeof el.item !== \"undefined\"</code> and changed <code>==</code> to <code>===</code> throughout.</p>\n\n<pre><code>if (typeof el.length === 'number' \n && typeof el.item !== 'undefined'\n && typeof el.nextNode === 'function'\n && typeof el.reset === 'function')\n{\n alert(\"I'm a NodeList\");\n}\n</code></pre>\n"
}
]
| 2008/09/30 | [
"https://Stackoverflow.com/questions/151348",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/8369/"
]
| Why is NodeList undefined in IE6/7?
```
<form action="/" method="post" id="testform">
<input type="checkbox" name="foobar[]" value="1" id="" />
<input type="checkbox" name="foobar[]" value="2" id="" />
<input type="checkbox" name="foobar[]" value="3" id="" />
</form>
<script type="text/javascript" charset="utf-8">
(function () {
var el = document.getElementById('testform')['foobar[]']
if (el instanceof NodeList) {
alert("I'm a NodeList");
}
})();
</script>
```
This works in FF3/Safari 3.1 but doesn't work in IE6/7. Anyone have any ideas how to check if el is an instance of NodeList across all browsers? | "[Duck Typing](http://en.wikipedia.org/wiki/Duck_typing)" should always work:
```
...
if (typeof el.length == 'number'
&& typeof el.item == 'function'
&& typeof el.nextNode == 'function'
&& typeof el.reset == 'function')
{
alert("I'm a NodeList");
}
``` |
151,362 | <p>For posting AJAX forms in a form with many parameters, I am using a solution of creating an <code>iframe</code>, posting the form to it by POST, and then accessing the <code>iframe</code>'s content.
specifically, I am accessing the content like this:</p>
<pre><code>$("some_iframe_id").get(0).contentWindow.document
</code></pre>
<p>I tested it and it worked. </p>
<p>On some of the pages, I started getting an "Access is denied" error. As far as I know, this shouldn't happen if the iframe is served from the same domain. </p>
<p>I'm pretty sure it was working before. Anybody have a clue? </p>
<p>If I'm not being clear enough: I'm posting to the <em>same domain</em>. So this is not a cross-domain request. I am testing on IE only.</p>
<p>P.S. I can't use simple ajax POST queries (don't ask...)</p>
| [
{
"answer_id": 151374,
"author": "dimarzionist",
"author_id": 10778,
"author_profile": "https://Stackoverflow.com/users/10778",
"pm_score": 0,
"selected": false,
"text": "<p>Basically, this error occurs when the document in frame and outside of ii have different domains. So to prevent cross-side scripting browsers disable such execution.</p>\n"
},
{
"answer_id": 151395,
"author": "Ris Adams",
"author_id": 15683,
"author_profile": "https://Stackoverflow.com/users/15683",
"pm_score": 0,
"selected": false,
"text": "<p>if it is a domain issue (or subdomain) such as www.foo.com sending a request to www.api.foo.com</p>\n\n<p>on each page you can set the </p>\n\n<pre><code>document.domain = www.foo.com\n</code></pre>\n\n<p>to allow for \"cross-domain\" permissions</p>\n"
},
{
"answer_id": 151404,
"author": "Ovesh",
"author_id": 3751,
"author_profile": "https://Stackoverflow.com/users/3751",
"pm_score": 7,
"selected": true,
"text": "<p>Solved it by myself!</p>\n\n<p>The problem was, that even though the correct response was being sent (verified with Fiddler), it was being sent with an HTTP 500 error code (instead of 200).</p>\n\n<p>So it turns out, that if a response is sent with an error code, IE replaces the content of the <code>iframe</code> with an error message loaded from the disk (<code>res://ieframe.dll/http_500.htm</code>), and that causes the cross-domain access denied error.</p>\n"
},
{
"answer_id": 2781810,
"author": "Groovetrain",
"author_id": 258722,
"author_profile": "https://Stackoverflow.com/users/258722",
"pm_score": 2,
"selected": false,
"text": "<p>I know this question is super-old, but I wanted to mention that the above answer worked for me: setting the document.domain to be the same on each of the pages-- the parent page and the iframe page. However in my search, I did find this interesting article:</p>\n\n<p><a href=\"http://softwareas.com/cross-domain-communication-with-iframes\" rel=\"nofollow noreferrer\">http://softwareas.com/cross-domain-communication-with-iframes</a></p>\n"
},
{
"answer_id": 5530496,
"author": "Gal Blank",
"author_id": 662469,
"author_profile": "https://Stackoverflow.com/users/662469",
"pm_score": 3,
"selected": false,
"text": "<p>Beware of security limitations associated to <strong>iFrames</strong>, like <em>Cross domain</em> restriction (aka CORS). Below are 3 common errors related to CORS :</p>\n\n<ol>\n<li><p>Load an iFrame with a different domain. (Ex: opening \"<em>www.foo.com</em>\" while top frame is \"<em>www.ooof.com</em>\")</p></li>\n<li><p>Load an iFrame with a different port: iFrame's URL <em>port</em> differs from the one of the top frame.</p></li>\n<li><p>Different protocols : loading iFrame resource via HTTPS while parent Frame uses HTTP.</p></li>\n</ol>\n"
},
{
"answer_id": 14805501,
"author": "gak",
"author_id": 11125,
"author_profile": "https://Stackoverflow.com/users/11125",
"pm_score": 2,
"selected": false,
"text": "<p>My issue was the <code>X-Frame-Options</code> HTTP header. My Apache configuration has it set to:</p>\n\n<pre><code>Header always append X-Frame-Options DENY\n</code></pre>\n\n<p>Removing it allowed it to work. Specifically in my case I was using iframe transport for jQuery with the jQuery file upload plugin to upload files in IE 9 and IE 10.</p>\n"
},
{
"answer_id": 18017982,
"author": "AaronLS",
"author_id": 84206,
"author_profile": "https://Stackoverflow.com/users/84206",
"pm_score": 2,
"selected": false,
"text": "<p>Note if you have a iframe with <code>src='javascript:void(0)'</code> then javascript like <code>frame.document.location =...</code> will fail with Access Denied error in IE. Was using a javascript library that interacts with a target frame. Even though the location it was trying to change the frame to was on the same domain as parent, the iframe was initially set to javascript:void which triggered the cross domain access denied error.</p>\n\n<p>To solve this I created a blank.html page in my site and if I need to declare an iframe in advance that will initially be blank until changed via javascript, then I point it to the blank page so that <code>src='/content/blank.html'</code> is in the same domain.</p>\n\n<p>Alternatively you could create the iframe completely through javascript so that you can set the src when it is created, but in my case I was using a library which reqired an iframe already be declared on the page.</p>\n"
}
]
| 2008/09/30 | [
"https://Stackoverflow.com/questions/151362",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3751/"
]
| For posting AJAX forms in a form with many parameters, I am using a solution of creating an `iframe`, posting the form to it by POST, and then accessing the `iframe`'s content.
specifically, I am accessing the content like this:
```
$("some_iframe_id").get(0).contentWindow.document
```
I tested it and it worked.
On some of the pages, I started getting an "Access is denied" error. As far as I know, this shouldn't happen if the iframe is served from the same domain.
I'm pretty sure it was working before. Anybody have a clue?
If I'm not being clear enough: I'm posting to the *same domain*. So this is not a cross-domain request. I am testing on IE only.
P.S. I can't use simple ajax POST queries (don't ask...) | Solved it by myself!
The problem was, that even though the correct response was being sent (verified with Fiddler), it was being sent with an HTTP 500 error code (instead of 200).
So it turns out, that if a response is sent with an error code, IE replaces the content of the `iframe` with an error message loaded from the disk (`res://ieframe.dll/http_500.htm`), and that causes the cross-domain access denied error. |
151,369 | <p>Given an HTML page that has a complex table-based layout and many tags that are duplicated and wasteful, e.g.:</p>
<pre><code>td align="left" class="tableformat" width="65%" style="border-bottom:1px solid #ff9600; border-right:1px solid #ff9600; background-color:#FDD69E" nowrap etc.
</code></pre>
<p>Are there tools to aide the task of refactoring the page into a more compact form? For instance, a tool that automatically generates CSS styles and selectors? That converts tables into div layouts? </p>
<p>Just to give a sense of the order of the problem, the page I'm looking at is >8000 lines of HTML and JavaScript, which is 500Kb <em>not counting</em> images! </p>
<hr>
<p>Update: In re. "give up and start from scratch" comments. What does that mean, in the real world? Print out the page, scan it, set it as the background image in Dreamweaver, and start with that? Seriously? Would that really be more efficient than refactoring? </p>
<hr>
<p>Update: I'm not denigrating "trace it from scratch" nor did I mean to imply that Dreamweaver is by any means my tool of choice. I'm just very surprised that refactoring a layout is considered to be an intractable problem. </p>
| [
{
"answer_id": 151466,
"author": "TimB",
"author_id": 4193,
"author_profile": "https://Stackoverflow.com/users/4193",
"pm_score": 2,
"selected": false,
"text": "<p>I'm not aware of specific tools, only the generic ones of caffeine and <a href=\"http://getfirebug.com/\" rel=\"nofollow noreferrer\">Firebug</a>, which anyone doing CSS work should be aware of.</p>\n\n<p>I think that the problem is sufficiently hard that automated tools would struggle to produce good, maintainable markup and CSS.</p>\n"
},
{
"answer_id": 151492,
"author": "Jeremy DeGroot",
"author_id": 20820,
"author_profile": "https://Stackoverflow.com/users/20820",
"pm_score": 0,
"selected": false,
"text": "<p>You denigrate this approach in your question, but I'd recommend taking a screen shot of your page in the browser whose rendering you like the best, declare that to be your reference, and start trying to recreate it. It's easier than you think. I've had to take skanky old table-based layouts and turn them into CMS templates done with modern techniques and it's not that bad a job.</p>\n"
},
{
"answer_id": 151517,
"author": "leek",
"author_id": 3765,
"author_profile": "https://Stackoverflow.com/users/3765",
"pm_score": 2,
"selected": false,
"text": "<p>It seems as if you are looking for more automated means of re-factoring an old table-based layout to CSS standards. However, I agree with some of the other comments to \"start from scratch\".</p>\n\n<p>What this means to you is that you should try to rebuild (using CSS) the look that was achieved using an HTML table. If this concept escapes you, then I would suggest Googling for some beginner CSS tutorials, maybe even some focusing on teaching the concept of Table->CSS layouts..</p>\n\n<p>Another tool to consider (that could possibly aid you even further) would be some sort of CSS \"framework\". I recommend <a href=\"http://code.google.com/p/blueprintcss/\" rel=\"nofollow noreferrer\">Blueprint CSS</a> for this, as it helps in the creation of grid/table-like layouts with minimal effort. Another good one is <a href=\"http://www.yaml.de/en/\" rel=\"nofollow noreferrer\">Yet-Another-Multicolumn-Layout</a>, which has a really neat <a href=\"http://builder.yaml.de/\" rel=\"nofollow noreferrer\">multi-column layout builder</a>.</p>\n"
},
{
"answer_id": 151549,
"author": "gregmac",
"author_id": 7913,
"author_profile": "https://Stackoverflow.com/users/7913",
"pm_score": 1,
"selected": false,
"text": "<p>Don't just throw it in dreamweaver or whatever tool of choice and slice it up. Write the HTML first, in purely semantic style. eg, a very common layout would end up being:</p>\n\n<pre><code><body>\n <div id=\"header\">\n <img id=\"logo\"/>\n <h1 id=\"title\">\n My Site\n </h1>\n <div id=\"subtitle\">Playing with css</div>\n </div>\n <div id=\"content\">\n <h2>Page 1</h2>\n <p>Blah blah blah..</p>\n </div>\n <div id=\"menu\">\n <ul>\n <li><a>Some link</a></li>\n ...\n </ul>\n </div>\n</body>\n</code></pre>\n\n<p>Do the HTML in a way that makes sense with your content. It should be usable if you have no CSS at all. After that, add in the CSS to make it look the way you want. With the state of browsers/CSS now, you still probably have to add some decorators to the HTML - eg, wrap some things in extra divs, just to be able to get the content the way you want.</p>\n\n<p>Once you're done though, you'll have a very flexible layout that can be modified easily with CSS, and you'll have a page that is accessible, to both disabled people and search engines. </p>\n\n<p>It does take quite a bit of learning before you get the knack of it, but it is worthwhile. Resist the temptation to give up and go back to table based layouts, and just work your way through. Everything can be done with semantic HTML and CSS.</p>\n"
},
{
"answer_id": 151580,
"author": "garrow",
"author_id": 21095,
"author_profile": "https://Stackoverflow.com/users/21095",
"pm_score": 3,
"selected": true,
"text": "<p>I agree with <a href=\"https://stackoverflow.com/questions/151369/tools-for-refactoring-table-based-html-layouts-to-css#151466\">TimB</a> in that automated tools are going to have trouble doing this, in particular making the relational jumps to combine and abstract CSS in the most efficient way.</p>\n\n<p>If you are presenting tabular data, it <strong>may</strong> be reasonable to attempt to refactor the inline CSS to reusable classes.</p>\n\n<p>If you have a lot of similar tables with inline styles you can gradually refactor the CSS by simple search and replace. \nThis will give you lots of classes that match a subset of similar tables and lots of somewhat similar classes. \nBreaking this up into layout and presentation would be a good start, then overriding these with specific classes for each theme or semantically related item.</p>\n\n<p>I would still recommend <strong>starting from scratch</strong>, it's probably going to be quicker, and you can recreate only what you need to present the page, and can reuse elements or collections of elements at a later date.</p>\n\n<p>The time spent will also pay off <strong>significantly</strong> if the page is ever needed to be modified again. </p>\n\n<p>But that's <strong>not at all</strong> likely is it? :D</p>\n"
},
{
"answer_id": 151627,
"author": "seanb",
"author_id": 3354,
"author_profile": "https://Stackoverflow.com/users/3354",
"pm_score": 0,
"selected": false,
"text": "<p>I am tackling a similar problem at the moment, not quite as messy as what this sounds, but the product of really bad asp.net web forms, overblown view state, and deeply nested server controls that format search results from a database. Resulting in ~300 - 400K of markup for 50 DB rows - yeek.</p>\n\n<p>I have not found any automated tools that will do a half way reasonable job of refactoring it. </p>\n\n<p>Starting with a tool like visual studio that you can use to reformat the code to a consistent manner helps. You can then use combinations of regexs and rectangular selecting to start weeding out the junk, and stripping back the redundant markup, to start to sort out what is important and what is not, and then start defining, by hand, an efficient pattern to present the information. </p>\n\n<p>The trick is to break into manageable chunks, and build it up from there.</p>\n\n<p>If you have a lot of actual \"tabular data\" to format, and is only a once off, I have found excel to be my saviour on a few occasions, paste the data into a sheet, and then use a combination of concatenate and fill to generate the markup for the tabular data. </p>\n"
},
{
"answer_id": 151630,
"author": "Jonathan Arkell",
"author_id": 11052,
"author_profile": "https://Stackoverflow.com/users/11052",
"pm_score": 0,
"selected": false,
"text": "<p>Starting from scratch means going back to the design drawing board. If you need to refactor such a monstrosity, then for all the time you will spend making it better, you might as well have done a full redesign.</p>\n\n<p>If you want to get away from duplicated and wasteful tags, you need to escape Dreamewaver. A good text editor (jedit, emacs, vim, eclipse, etc.) is really all you need. If you customize your editor properly, you won't even miss Dreamweaver. (Emacs with nXhtml and yasnippets is my favorite.)</p>\n"
}
]
| 2008/09/30 | [
"https://Stackoverflow.com/questions/151369",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/10116/"
]
| Given an HTML page that has a complex table-based layout and many tags that are duplicated and wasteful, e.g.:
```
td align="left" class="tableformat" width="65%" style="border-bottom:1px solid #ff9600; border-right:1px solid #ff9600; background-color:#FDD69E" nowrap etc.
```
Are there tools to aide the task of refactoring the page into a more compact form? For instance, a tool that automatically generates CSS styles and selectors? That converts tables into div layouts?
Just to give a sense of the order of the problem, the page I'm looking at is >8000 lines of HTML and JavaScript, which is 500Kb *not counting* images!
---
Update: In re. "give up and start from scratch" comments. What does that mean, in the real world? Print out the page, scan it, set it as the background image in Dreamweaver, and start with that? Seriously? Would that really be more efficient than refactoring?
---
Update: I'm not denigrating "trace it from scratch" nor did I mean to imply that Dreamweaver is by any means my tool of choice. I'm just very surprised that refactoring a layout is considered to be an intractable problem. | I agree with [TimB](https://stackoverflow.com/questions/151369/tools-for-refactoring-table-based-html-layouts-to-css#151466) in that automated tools are going to have trouble doing this, in particular making the relational jumps to combine and abstract CSS in the most efficient way.
If you are presenting tabular data, it **may** be reasonable to attempt to refactor the inline CSS to reusable classes.
If you have a lot of similar tables with inline styles you can gradually refactor the CSS by simple search and replace.
This will give you lots of classes that match a subset of similar tables and lots of somewhat similar classes.
Breaking this up into layout and presentation would be a good start, then overriding these with specific classes for each theme or semantically related item.
I would still recommend **starting from scratch**, it's probably going to be quicker, and you can recreate only what you need to present the page, and can reuse elements or collections of elements at a later date.
The time spent will also pay off **significantly** if the page is ever needed to be modified again.
But that's **not at all** likely is it? :D |
151,392 | <p>Does anyone know any good tool that I can use to perform stress tests on a video streaming server? I need to test how well my server handles 5,000+ connections. </p>
| [
{
"answer_id": 151571,
"author": "Nick Berardi",
"author_id": 17,
"author_profile": "https://Stackoverflow.com/users/17",
"pm_score": 2,
"selected": false,
"text": "<p>start downloading 5000+ files of the same type with different connections. Don't really need to play them, because essentially the client video player, flash, windows media player, etc. will just be doing a download. So if you server can handle 5000+ downloads you will be fine. My bet is your bandwidth gives out before you server.</p>\n"
},
{
"answer_id": 151650,
"author": "Andrew Edgecombe",
"author_id": 11694,
"author_profile": "https://Stackoverflow.com/users/11694",
"pm_score": 4,
"selected": true,
"text": "<p>One option is to use VLC. You can specify a url on the command line. (see <a href=\"http://wiki.videolan.org/VLC_command-line_help\" rel=\"nofollow noreferrer\">here</a> for details). You could then write a brief shell script to open up all 5000 connections.</p>\n\n<p>eg. the following perl script (very quick hack - check before running, might cause explosions etc.)</p>\n\n<pre class=\"lang-perl prettyprint-override\"><code>$i = 0;\n$myurl = \"udp://someurl\";\n@cmdline = (\"/usr/bin/vlc\", \"\");\nfor( $i = 1; $i <= 5000; $i++ )\n{\n if( $pid = fork )\n {\n # parent - ignore\n }\n elsif( defined $pid )\n {\n $cmdline[1] = sprintf \"%s:%d\", $myurl, $i;\n exec(@cmdline);\n }\n # elseif - do more error checking here\n}\n</code></pre>\n\n<p>If your video streaming server is doing multicast it should be sufficient to open sockets and make them members of your 5000 multicast groups (without necessarily doing anything with the stream. By not actually decoding the stream you will reduce performance issues on the client end).</p>\n\n<p>I'm not aware of any tools that will do this for you, but if you're up for writing your own utility you can start <a href=\"http://tldp.org/HOWTO/Multicast-HOWTO-6.html\" rel=\"nofollow noreferrer\">here</a> for details.</p>\n\n<p>edit: The second option assumes that the OS on your client machine has multicast capability. I mention that because (from memory) the linux kernel doesn't by default, and I'd like to save you that pain. :-)</p>\n\n<p>Easy way to tell (again on Linux) is to check for the presence of <code>/proc/net/igmp</code></p>\n"
},
{
"answer_id": 12190204,
"author": "Dilip Rajkumar",
"author_id": 763747,
"author_profile": "https://Stackoverflow.com/users/763747",
"pm_score": 0,
"selected": false,
"text": "<p>I am also searching for the same answer, I come across with following tool may be it helps someone <a href=\"http://www.radview.com/Solutions/multimedia-load-testing.aspx\" rel=\"nofollow\">http://www.radview.com/Solutions/multimedia-load-testing.aspx</a></p>\n\n<p>This tool is used to test video streaming. Hope it helps someone. I will update the answer if I get a better one .</p>\n\n<p>Thanks.</p>\n"
},
{
"answer_id": 17100692,
"author": "Shen",
"author_id": 2484590,
"author_profile": "https://Stackoverflow.com/users/2484590",
"pm_score": -1,
"selected": false,
"text": "<p>This <a href=\"http://www.mocomsoft.com/en-US/products/HLSAnalyzer.aspx\" rel=\"nofollow\">HLS Analyzer</a> software can be used for stress testing HTTP Live Streaming server and monitoring downloading performance. </p>\n"
},
{
"answer_id": 27952786,
"author": "UBIK LOAD PACK",
"author_id": 460802,
"author_profile": "https://Stackoverflow.com/users/460802",
"pm_score": 1,
"selected": false,
"text": "<p>For infrastructure, you can use either a JMeter SAAS or your own Cloud server to overcome possible network issues from your injector.</p>\n\n<p>To reproduce user experience and have precious metrics about user experience, you can use <a href=\"https://jmeter.apache.org/\" rel=\"nofollow noreferrer\">Apache JMeter</a> + this <a href=\"https://ubikloadpack.com/\" rel=\"nofollow noreferrer\">commercial plugin</a> which simulates realistically the Players behavior without any scripting:</p>\n\n<ul>\n<li><a href=\"https://www.ubik-ingenierie.com/blog/easy-and-realistic-load-testing-of-http-live-streaming-hls-with-apache-jmeter/\" rel=\"nofollow noreferrer\">Apple HTTP Live Streaming</a></li>\n<li><a href=\"https://www.ubik-ingenierie.com/blog/load-testing-mpeg-dash-jmeter-ubik-videostreaming-plugin/\" rel=\"nofollow noreferrer\">MPEG-DASH</a> Streaming</li>\n<li><a href=\"https://www.ubik-ingenierie.com/blog/load-testing-smooth-streaming-video-with-jmeter/\" rel=\"nofollow noreferrer\">Smooth Video Streaming</a></li>\n</ul>\n\n<p>This plugin also provide the ability to simulate <a href=\"https://www.ubik-ingenierie.com/blog/videostreaming-plugin-with-live-and-abr-streaming/\" rel=\"nofollow noreferrer\">Adaptive Bitrate Streaming</a></p>\n\n<p>Disclaimer : We are behind the development of this solution</p>\n"
},
{
"answer_id": 58740081,
"author": "Kalei White",
"author_id": 12334945,
"author_profile": "https://Stackoverflow.com/users/12334945",
"pm_score": 1,
"selected": false,
"text": "<p>A new plugin for JMeter has been released to help simulate a HLS scenario by using only one custom Sampler. Now, you don’t need multiple HTTP Request Samplers, ForEach Controllers or RegEx PostProcessors. This makes the whole process much simpler than before.</p>\n\n<p>Instead, the complete logic is seamlessly encapsulated so you only have to care about the use case: the media type, playback time and network conditions. That’s it! The plugin is brand new and it can be installed via the JMeter Plugins Manager.</p>\n\n<p>Here you can learn more about it:</p>\n\n<p><a href=\"https://abstracta.us/blog/performance-testing/how-to-run-video-streaming-performance-tests-on-hls/\" rel=\"nofollow noreferrer\">https://abstracta.us/blog/performance-testing/how-to-run-video-streaming-performance-tests-on-hls/</a></p>\n"
}
]
| 2008/09/30 | [
"https://Stackoverflow.com/questions/151392",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/23637/"
]
| Does anyone know any good tool that I can use to perform stress tests on a video streaming server? I need to test how well my server handles 5,000+ connections. | One option is to use VLC. You can specify a url on the command line. (see [here](http://wiki.videolan.org/VLC_command-line_help) for details). You could then write a brief shell script to open up all 5000 connections.
eg. the following perl script (very quick hack - check before running, might cause explosions etc.)
```perl
$i = 0;
$myurl = "udp://someurl";
@cmdline = ("/usr/bin/vlc", "");
for( $i = 1; $i <= 5000; $i++ )
{
if( $pid = fork )
{
# parent - ignore
}
elsif( defined $pid )
{
$cmdline[1] = sprintf "%s:%d", $myurl, $i;
exec(@cmdline);
}
# elseif - do more error checking here
}
```
If your video streaming server is doing multicast it should be sufficient to open sockets and make them members of your 5000 multicast groups (without necessarily doing anything with the stream. By not actually decoding the stream you will reduce performance issues on the client end).
I'm not aware of any tools that will do this for you, but if you're up for writing your own utility you can start [here](http://tldp.org/HOWTO/Multicast-HOWTO-6.html) for details.
edit: The second option assumes that the OS on your client machine has multicast capability. I mention that because (from memory) the linux kernel doesn't by default, and I'd like to save you that pain. :-)
Easy way to tell (again on Linux) is to check for the presence of `/proc/net/igmp` |
151,407 | <p>Under Linux, my C++ application is using fork() and execv() to launch multiple instances of OpenOffice so as to view some powerpoint slide shows. This part works.</p>
<p>Next I want to be able to move the OpenOffice windows to specific locations on the display. I can do that with the XMoveResizeWindow() function but I need to find the Window for each instance.</p>
<p>I have the process ID of each instance, how can I find the X11 Window from that ?</p>
<hr>
<p><strong>UPDATE</strong> - Thanks to Andy's suggestion, I have pulled this off. I'm posting the code here to share it with the Stack Overflow community.</p>
<p>Unfortunately Open Office does not seem to set the _NET_WM_PID property so this doesn't ultimately solve my problem but it does answer the question.</p>
<pre><code>// Attempt to identify a window by name or attribute.
// by Adam Pierce <[email protected]>
#include <X11/Xlib.h>
#include <X11/Xatom.h>
#include <iostream>
#include <list>
using namespace std;
class WindowsMatchingPid
{
public:
WindowsMatchingPid(Display *display, Window wRoot, unsigned long pid)
: _display(display)
, _pid(pid)
{
// Get the PID property atom.
_atomPID = XInternAtom(display, "_NET_WM_PID", True);
if(_atomPID == None)
{
cout << "No such atom" << endl;
return;
}
search(wRoot);
}
const list<Window> &result() const { return _result; }
private:
unsigned long _pid;
Atom _atomPID;
Display *_display;
list<Window> _result;
void search(Window w)
{
// Get the PID for the current Window.
Atom type;
int format;
unsigned long nItems;
unsigned long bytesAfter;
unsigned char *propPID = 0;
if(Success == XGetWindowProperty(_display, w, _atomPID, 0, 1, False, XA_CARDINAL,
&type, &format, &nItems, &bytesAfter, &propPID))
{
if(propPID != 0)
{
// If the PID matches, add this window to the result set.
if(_pid == *((unsigned long *)propPID))
_result.push_back(w);
XFree(propPID);
}
}
// Recurse into child windows.
Window wRoot;
Window wParent;
Window *wChild;
unsigned nChildren;
if(0 != XQueryTree(_display, w, &wRoot, &wParent, &wChild, &nChildren))
{
for(unsigned i = 0; i < nChildren; i++)
search(wChild[i]);
}
}
};
int main(int argc, char **argv)
{
if(argc < 2)
return 1;
int pid = atoi(argv[1]);
cout << "Searching for windows associated with PID " << pid << endl;
// Start with the root window.
Display *display = XOpenDisplay(0);
WindowsMatchingPid match(display, XDefaultRootWindow(display), pid);
// Print the result.
const list<Window> &result = match.result();
for(list<Window>::const_iterator it = result.begin(); it != result.end(); it++)
cout << "Window #" << (unsigned long)(*it) << endl;
return 0;
}
</code></pre>
| [
{
"answer_id": 151512,
"author": "Tanktalus",
"author_id": 23512,
"author_profile": "https://Stackoverflow.com/users/23512",
"pm_score": 1,
"selected": false,
"text": "<p>Are you sure you have the process ID of each instance? My experience with OOo has been that trying to run a second instance of OOo merely converses with the first instance of OOo, and tells that to open the additional file.</p>\n\n<p>I think you're going to need to use the message-sending capabilities of X to ask it nicely for its window. I would hope that OOo documents its coversations somewhere.</p>\n"
},
{
"answer_id": 151531,
"author": "wnoise",
"author_id": 15464,
"author_profile": "https://Stackoverflow.com/users/15464",
"pm_score": 2,
"selected": false,
"text": "<p>There is no good way. The only real options I see, are:</p>\n\n<ol>\n<li>You could look around in the process's address space to find the connection information and window ID.</li>\n<li>You could try to use netstat or lsof or ipcs to map the connections to the Xserver, and then (somehow! you'll need root at least) look at its connection info to find them.</li>\n<li>When spawning an instance you can wait until another window is mapped, assume it's the right one, and `move on.</li>\n</ol>\n"
},
{
"answer_id": 151542,
"author": "andy",
"author_id": 6152,
"author_profile": "https://Stackoverflow.com/users/6152",
"pm_score": 6,
"selected": true,
"text": "<p>The only way I know to do this is to traverse the tree of windows until you find what you're looking for. Traversing isn't hard (just see what xwininfo -root -tree does by looking at xwininfo.c if you need an example).\n<p>\nBut how do you identify the window you are looking for? <b>Some</b> applications set a window property called _NET_WM_PID.\n<p>\nI believe that OpenOffice <em>is</em> one of the applications that sets that property (as do most Gnome apps), so you're in luck.</p>\n"
},
{
"answer_id": 2754512,
"author": "hoho",
"author_id": 330935,
"author_profile": "https://Stackoverflow.com/users/330935",
"pm_score": 4,
"selected": false,
"text": "<p>Check if /proc/PID/environ contains a variable called WINDOWID</p>\n"
},
{
"answer_id": 13482052,
"author": "Raphael Wimmer",
"author_id": 1840141,
"author_profile": "https://Stackoverflow.com/users/1840141",
"pm_score": 4,
"selected": false,
"text": "<p>Bit late to the party. However: \nBack in 2004, Harald Welte posted a code snippet that wraps the XCreateWindow() call via LD_PRELOAD and stores the process id in _NET_WM_PID. This makes sure that each window created has a PID entry.</p>\n\n<p><a href=\"http://www.mail-archive.com/[email protected]/msg05806.html\">http://www.mail-archive.com/[email protected]/msg05806.html</a></p>\n"
},
{
"answer_id": 27486173,
"author": "Gauthier",
"author_id": 108802,
"author_profile": "https://Stackoverflow.com/users/108802",
"pm_score": 3,
"selected": false,
"text": "<p>Try installing <code>xdotool</code>, then:</p>\n\n<pre><code>#!/bin/bash\n# --any and --name present only as a work-around, see: https://github.com/jordansissel/xdotool/issues/14\nids=$(xdotool search --any --pid \"$1\" --name \"dummy\")\n</code></pre>\n\n<p>I do get a lot of ids. I use this to set a terminal window as urgent when it is done with a long command, with the program <code>seturgent</code>. I just loop through all the ids I get from <code>xdotool</code> and run <code>seturgent</code> on them.</p>\n"
},
{
"answer_id": 43566150,
"author": "Shuman",
"author_id": 2052889,
"author_profile": "https://Stackoverflow.com/users/2052889",
"pm_score": 0,
"selected": false,
"text": "<p>If you use python, I found a way <a href=\"https://bbs.archlinux.org/viewtopic.php?id=113346\" rel=\"nofollow noreferrer\">here</a>, the idea is from <a href=\"https://github.com/BurntSushi/\" rel=\"nofollow noreferrer\">BurntSushi</a></p>\n\n<p>If you launched the application, then you should know its cmd string, with which you can reduce calls to <code>xprop</code>, you can always loop through all the xids and check if the pid is the same as the pid you want</p>\n\n<pre><code>import subprocess\nimport re\n\nimport struct\nimport xcffib as xcb\nimport xcffib.xproto\n\ndef get_property_value(property_reply):\n assert isinstance(property_reply, xcb.xproto.GetPropertyReply)\n\n if property_reply.format == 8:\n if 0 in property_reply.value:\n ret = []\n s = ''\n for o in property_reply.value:\n if o == 0:\n ret.append(s)\n s = ''\n else:\n s += chr(o)\n else:\n ret = str(property_reply.value.buf())\n\n return ret\n elif property_reply.format in (16, 32):\n return list(struct.unpack('I' * property_reply.value_len,\n property_reply.value.buf()))\n\n return None\n\ndef getProperty(connection, ident, propertyName):\n\n propertyType = eval(' xcb.xproto.Atom.%s' % propertyName)\n\n try:\n return connection.core.GetProperty(False, ident, propertyType,\n xcb.xproto.GetPropertyType.Any,\n 0, 2 ** 32 - 1)\n except:\n return None\n\n\nc = xcb.connect()\nroot = c.get_setup().roots[0].root\n\n_NET_CLIENT_LIST = c.core.InternAtom(True, len('_NET_CLIENT_LIST'),\n '_NET_CLIENT_LIST').reply().atom\n\n\nraw_clientlist = c.core.GetProperty(False, root, _NET_CLIENT_LIST,\n xcb.xproto.GetPropertyType.Any,\n 0, 2 ** 32 - 1).reply()\n\nclientlist = get_property_value(raw_clientlist)\n\ncookies = {}\n\nfor ident in clientlist:\n wm_command = getProperty(c, ident, 'WM_COMMAND')\n cookies[ident] = (wm_command)\n\nxids=[]\n\nfor ident in cookies:\n cmd = get_property_value(cookies[ident].reply())\n if cmd and spref in cmd:\n xids.append(ident)\n\nfor xid in xids:\n pid = subprocess.check_output('xprop -id %s _NET_WM_PID' % xid, shell=True)\n pid = re.search('(?<=\\s=\\s)\\d+', pid).group()\n\n if int(pid) == self.pid:\n print 'found pid:', pid\n break\n\nprint 'your xid:', xid\n</code></pre>\n"
},
{
"answer_id": 55921742,
"author": "DarioP",
"author_id": 2140449,
"author_profile": "https://Stackoverflow.com/users/2140449",
"pm_score": 2,
"selected": false,
"text": "<p>I took the freedom to re-implement the OP's code using some modern C++ features. It maintains the same functionalities but I think that it reads a bit better. Also it does not leak even if the vector insertion happens to throw.</p>\n\n<pre><code>// Attempt to identify a window by name or attribute.\n// originally written by Adam Pierce <[email protected]>\n// revised by Dario Pellegrini <[email protected]>\n\n#include <X11/Xlib.h>\n#include <X11/Xatom.h>\n#include <iostream>\n#include <vector>\n\n\nstd::vector<Window> pid2windows(pid_t pid, Display* display, Window w) {\n struct implementation {\n struct FreeWrapRAII {\n void * data;\n FreeWrapRAII(void * data): data(data) {}\n ~FreeWrapRAII(){ XFree(data); }\n };\n\n std::vector<Window> result;\n pid_t pid;\n Display* display;\n Atom atomPID;\n\n implementation(pid_t pid, Display* display): pid(pid), display(display) {\n // Get the PID property atom\n atomPID = XInternAtom(display, \"_NET_WM_PID\", True);\n if(atomPID == None) {\n throw std::runtime_error(\"pid2windows: no such atom\");\n }\n }\n\n std::vector<Window> getChildren(Window w) {\n Window wRoot;\n Window wParent;\n Window *wChild;\n unsigned nChildren;\n std::vector<Window> children;\n if(0 != XQueryTree(display, w, &wRoot, &wParent, &wChild, &nChildren)) {\n FreeWrapRAII tmp( wChild );\n children.insert(children.end(), wChild, wChild+nChildren);\n }\n return children;\n }\n\n void emplaceIfMatches(Window w) {\n // Get the PID for the given Window\n Atom type;\n int format;\n unsigned long nItems;\n unsigned long bytesAfter;\n unsigned char *propPID = 0;\n if(Success == XGetWindowProperty(display, w, atomPID, 0, 1, False, XA_CARDINAL,\n &type, &format, &nItems, &bytesAfter, &propPID)) {\n if(propPID != 0) {\n FreeWrapRAII tmp( propPID );\n if(pid == *reinterpret_cast<pid_t*>(propPID)) {\n result.emplace_back(w);\n }\n }\n }\n }\n\n void recurse( Window w) {\n emplaceIfMatches(w);\n for (auto & child: getChildren(w)) {\n recurse(child);\n }\n }\n\n std::vector<Window> operator()( Window w ) {\n result.clear();\n recurse(w);\n return result;\n }\n };\n //back to pid2windows function\n return implementation{pid, display}(w);\n}\n\nstd::vector<Window> pid2windows(const size_t pid, Display* display) {\n return pid2windows(pid, display, XDefaultRootWindow(display));\n}\n\n\nint main(int argc, char **argv) {\n if(argc < 2)\n return 1;\n\n int pid = atoi(argv[1]);\n std::cout << \"Searching for windows associated with PID \" << pid << std::endl;\n\n // Start with the root window.\n Display *display = XOpenDisplay(0);\n auto res = pid2windows(pid, display);\n\n // Print the result.\n for( auto & w: res) {\n std::cout << \"Window #\" << static_cast<unsigned long>(w) << std::endl;\n }\n\n XCloseDisplay(display);\n return 0;\n}\n</code></pre>\n"
}
]
| 2008/09/30 | [
"https://Stackoverflow.com/questions/151407",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5324/"
]
| Under Linux, my C++ application is using fork() and execv() to launch multiple instances of OpenOffice so as to view some powerpoint slide shows. This part works.
Next I want to be able to move the OpenOffice windows to specific locations on the display. I can do that with the XMoveResizeWindow() function but I need to find the Window for each instance.
I have the process ID of each instance, how can I find the X11 Window from that ?
---
**UPDATE** - Thanks to Andy's suggestion, I have pulled this off. I'm posting the code here to share it with the Stack Overflow community.
Unfortunately Open Office does not seem to set the \_NET\_WM\_PID property so this doesn't ultimately solve my problem but it does answer the question.
```
// Attempt to identify a window by name or attribute.
// by Adam Pierce <[email protected]>
#include <X11/Xlib.h>
#include <X11/Xatom.h>
#include <iostream>
#include <list>
using namespace std;
class WindowsMatchingPid
{
public:
WindowsMatchingPid(Display *display, Window wRoot, unsigned long pid)
: _display(display)
, _pid(pid)
{
// Get the PID property atom.
_atomPID = XInternAtom(display, "_NET_WM_PID", True);
if(_atomPID == None)
{
cout << "No such atom" << endl;
return;
}
search(wRoot);
}
const list<Window> &result() const { return _result; }
private:
unsigned long _pid;
Atom _atomPID;
Display *_display;
list<Window> _result;
void search(Window w)
{
// Get the PID for the current Window.
Atom type;
int format;
unsigned long nItems;
unsigned long bytesAfter;
unsigned char *propPID = 0;
if(Success == XGetWindowProperty(_display, w, _atomPID, 0, 1, False, XA_CARDINAL,
&type, &format, &nItems, &bytesAfter, &propPID))
{
if(propPID != 0)
{
// If the PID matches, add this window to the result set.
if(_pid == *((unsigned long *)propPID))
_result.push_back(w);
XFree(propPID);
}
}
// Recurse into child windows.
Window wRoot;
Window wParent;
Window *wChild;
unsigned nChildren;
if(0 != XQueryTree(_display, w, &wRoot, &wParent, &wChild, &nChildren))
{
for(unsigned i = 0; i < nChildren; i++)
search(wChild[i]);
}
}
};
int main(int argc, char **argv)
{
if(argc < 2)
return 1;
int pid = atoi(argv[1]);
cout << "Searching for windows associated with PID " << pid << endl;
// Start with the root window.
Display *display = XOpenDisplay(0);
WindowsMatchingPid match(display, XDefaultRootWindow(display), pid);
// Print the result.
const list<Window> &result = match.result();
for(list<Window>::const_iterator it = result.begin(); it != result.end(); it++)
cout << "Window #" << (unsigned long)(*it) << endl;
return 0;
}
``` | The only way I know to do this is to traverse the tree of windows until you find what you're looking for. Traversing isn't hard (just see what xwininfo -root -tree does by looking at xwininfo.c if you need an example).
But how do you identify the window you are looking for? **Some** applications set a window property called \_NET\_WM\_PID.
I believe that OpenOffice *is* one of the applications that sets that property (as do most Gnome apps), so you're in luck. |
151,413 | <p>I've got a siluation where i need to access a SOAP web service with WSE 2.0 security. I've got all the generated c# proxies (which are derived from Microsoft.Web.Services2.WebServicesClientProtocol), i'm applying the certificate but when i call a method i get an error:</p>
<pre><code>System.Net.WebException : The request failed with HTTP status 405: Method Not Allowed.
at System.Web.Services.Protocols.SoapHttpClientProtocol.ReadResponse(SoapClientMessage message, WebResponse response, Stream responseStream, Boolean asyncCall)
at System.Web.Services.Protocols.SoapHttpClientProtocol.Invoke(String methodName, Object[] parameters)
</code></pre>
<p>I've done some googling and it appears that this is a server configuration issue.
However this web service is used many clients without any problem (the web service is provided by a Telecom New Zealand, so it's bound to be configured correctly. I believe it's written in Java)</p>
<p>Can anyone shed some light on this issue?</p>
| [
{
"answer_id": 151416,
"author": "cruizer",
"author_id": 6441,
"author_profile": "https://Stackoverflow.com/users/6441",
"pm_score": 0,
"selected": false,
"text": "<p>hmm are those other clients also using C#/.NET?</p>\n\n<p>Method not allowed --> could this be a REST service, instead of a SOAP web service?</p>\n"
},
{
"answer_id": 172902,
"author": "Muxa",
"author_id": 10793,
"author_profile": "https://Stackoverflow.com/users/10793",
"pm_score": 5,
"selected": true,
"text": "<p>Ok, found what the problem was. I was trying to call a .wsdl url instead of .asmx url.\nDoh!</p>\n"
},
{
"answer_id": 2594215,
"author": "Juan Calero",
"author_id": 134898,
"author_profile": "https://Stackoverflow.com/users/134898",
"pm_score": 2,
"selected": false,
"text": "<p>I had the same problem, but the details were different:</p>\n\n<p>The Url we were using didn't have the file (.asmx) part. Calling the Url in a browser was OK. It also worked in a simple client setting the URL through Visual Studio. \nBut it didn't worked setting the Url dynamically! It gave the same 405 error.</p>\n\n<p>Finally we found that adding the file part to the Web Service Url solved the problem.\nMaybe a .Net framework bug?</p>\n"
},
{
"answer_id": 5173045,
"author": "A-Dubb",
"author_id": 389103,
"author_profile": "https://Stackoverflow.com/users/389103",
"pm_score": 3,
"selected": false,
"text": "<p>I found this was due to WCF not being installed on IIS. The main thing is that the .svc extension has to be mapped in IIS <a href=\"http://msdn.microsoft.com/en-us/library/ms752252%28v=vs.90%29.aspx\" rel=\"noreferrer\">See MSDN here.</a> Use the ServiceModelReg tool to complete the installation. You'll always want to verify that WCF is installed and .svc is mapped in IIS anytime you get a new machine or reinstall IIS.</p>\n"
},
{
"answer_id": 16852492,
"author": "user1551704",
"author_id": 1551704,
"author_profile": "https://Stackoverflow.com/users/1551704",
"pm_score": 0,
"selected": false,
"text": "<p>MethodNotAllowedEquivalent to HTTP status 405. MethodNotAllowed indicates that the request method (POST or GET) is not allowed on the requested resource.</p>\n\n<p>The problem is in your enpoint uri is not full or correct addres to wcf - .scv\nCheck your proxy.enpoint or wcf client.enpoint uri is correct.</p>\n"
},
{
"answer_id": 34814835,
"author": "StanT.",
"author_id": 4278971,
"author_profile": "https://Stackoverflow.com/users/4278971",
"pm_score": 0,
"selected": false,
"text": "<p>In my case the problem was that the app config was incorrectly formed/called:\nin config the service url was using \"localhost\" as domain name, but real hostname differed from the URL I called :( so I changed the \"localhost\" in config to domainname thah I use in URL. That`s all!</p>\n"
},
{
"answer_id": 55223151,
"author": "Diego Elizondo",
"author_id": 10296547,
"author_profile": "https://Stackoverflow.com/users/10296547",
"pm_score": 2,
"selected": false,
"text": "<p>You needto enable HTTP Activation</p>\n\n<p>Go to Control Panel > Windows Features > .NET Framework 4.5 Advanced Services > WCF Services > HTTP Activation</p>\n"
}
]
| 2008/09/30 | [
"https://Stackoverflow.com/questions/151413",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/10793/"
]
| I've got a siluation where i need to access a SOAP web service with WSE 2.0 security. I've got all the generated c# proxies (which are derived from Microsoft.Web.Services2.WebServicesClientProtocol), i'm applying the certificate but when i call a method i get an error:
```
System.Net.WebException : The request failed with HTTP status 405: Method Not Allowed.
at System.Web.Services.Protocols.SoapHttpClientProtocol.ReadResponse(SoapClientMessage message, WebResponse response, Stream responseStream, Boolean asyncCall)
at System.Web.Services.Protocols.SoapHttpClientProtocol.Invoke(String methodName, Object[] parameters)
```
I've done some googling and it appears that this is a server configuration issue.
However this web service is used many clients without any problem (the web service is provided by a Telecom New Zealand, so it's bound to be configured correctly. I believe it's written in Java)
Can anyone shed some light on this issue? | Ok, found what the problem was. I was trying to call a .wsdl url instead of .asmx url.
Doh! |
151,414 | <p>Here is the directory layout that was installed with Leopard. What is the "A" directory and why the "Current" directory in addition to the "CurrentJDK"?</p>
<p>It seems like you can easily switch the current JDK by move the CurrentJDK link, but then the contents under Current and A will be out of sync.</p>
<pre>
lrwxr-xr-x 1 root wheel 5 Jun 14 15:49 1.3 -> 1.3.1
drwxr-xr-x 3 root wheel 102 Jan 14 2008 1.3.1
lrwxr-xr-x 1 root wheel 5 Feb 21 2008 1.4 -> 1.4.2
lrwxr-xr-x 1 root wheel 3 Jun 14 15:49 1.4.1 -> 1.4
drwxr-xr-x 8 root wheel 272 Feb 21 2008 1.4.2
lrwxr-xr-x 1 root wheel 5 Feb 21 2008 1.5 -> 1.5.0
drwxr-xr-x 8 root wheel 272 Feb 21 2008 1.5.0
lrwxr-xr-x 1 root wheel 5 Jun 14 15:49 1.6 -> 1.6.0
drwxr-xr-x 8 root wheel 272 Jun 14 15:49 1.6.0
drwxr-xr-x 8 root wheel 272 Jun 14 15:49 A
lrwxr-xr-x 1 root wheel 1 Jun 14 15:49 Current -> A
lrwxr-xr-x 1 root wheel 3 Jun 14 15:49 CurrentJDK -> 1.5
steve-mbp /System/Library/Frameworks/JavaVM.framework/Versions $
</pre>
<p>and the contents of A</p>
<pre>
-rw-r--r-- 1 root wheel 1925 Feb 29 2008 CodeResources
drwxr-xr-x 34 root wheel 1156 Jun 14 15:49 Commands
drwxr-xr-x 3 root wheel 102 Mar 6 2008 Frameworks
drwxr-xr-x 16 root wheel 544 Jun 14 15:49 Headers
-rwxr-xr-x 1 root wheel 236080 Feb 29 2008 JavaVM
drwxr-xr-x 29 root wheel 986 Jun 14 15:49 Resources
steve-mbp /System/Library/Frameworks/JavaVM.framework/Versions/A $
</pre>
| [
{
"answer_id": 151463,
"author": "Chris Hanson",
"author_id": 714,
"author_profile": "https://Stackoverflow.com/users/714",
"pm_score": 4,
"selected": true,
"text": "<p>The (<code>A</code>, <code>Current</code> symbolic-linked to <code>A</code>) is part of the structure of a Mac OS X framework, which <code>JavaVM.framework</code> is. This framework may have C or Objective-C code in it, in addition to the actual JVM installations. Thus it could potentially be linked against from some C or Objective-C code in addition to containing the JVM alongside that.</p>\n\n<p>Note that you <strong>should not</strong> change the <code>CurrentJDK</code> link to point at anything but what it is set to by Mac OS X. Unlike on other platforms, the Java virtual machine is an operating system service on Mac OS X, and changing it in this way would put you in an unsupported (and potentially untested, unstable, etc.) configuration.</p>\n"
},
{
"answer_id": 151515,
"author": "Joe Liversedge",
"author_id": 4552,
"author_profile": "https://Stackoverflow.com/users/4552",
"pm_score": 2,
"selected": false,
"text": "<p>If you want to revert to an older JVM (here, 1.5), you can put the following in your <code>~/.profile</code> (or paste it into a specific Terminal window):</p>\n\n<pre><code>export JAVA_HOME=\"/System/Library/Frameworks/JavaVM.framework/Versions/1.5.0/Home/\"\nexport PATH=$JAVA_HOME/bin/:$PATH\n</code></pre>\n"
},
{
"answer_id": 151526,
"author": "Milhous",
"author_id": 17712,
"author_profile": "https://Stackoverflow.com/users/17712",
"pm_score": 3,
"selected": false,
"text": "<p>You should use the Java Preferences command to change the jvm version.</p>\n\n<p>If you have spotlight on your Harddisk, you can just spotlight \"Java Preferences\"</p>\n"
}
]
| 2008/09/30 | [
"https://Stackoverflow.com/questions/151414",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/21176/"
]
| Here is the directory layout that was installed with Leopard. What is the "A" directory and why the "Current" directory in addition to the "CurrentJDK"?
It seems like you can easily switch the current JDK by move the CurrentJDK link, but then the contents under Current and A will be out of sync.
```
lrwxr-xr-x 1 root wheel 5 Jun 14 15:49 1.3 -> 1.3.1
drwxr-xr-x 3 root wheel 102 Jan 14 2008 1.3.1
lrwxr-xr-x 1 root wheel 5 Feb 21 2008 1.4 -> 1.4.2
lrwxr-xr-x 1 root wheel 3 Jun 14 15:49 1.4.1 -> 1.4
drwxr-xr-x 8 root wheel 272 Feb 21 2008 1.4.2
lrwxr-xr-x 1 root wheel 5 Feb 21 2008 1.5 -> 1.5.0
drwxr-xr-x 8 root wheel 272 Feb 21 2008 1.5.0
lrwxr-xr-x 1 root wheel 5 Jun 14 15:49 1.6 -> 1.6.0
drwxr-xr-x 8 root wheel 272 Jun 14 15:49 1.6.0
drwxr-xr-x 8 root wheel 272 Jun 14 15:49 A
lrwxr-xr-x 1 root wheel 1 Jun 14 15:49 Current -> A
lrwxr-xr-x 1 root wheel 3 Jun 14 15:49 CurrentJDK -> 1.5
steve-mbp /System/Library/Frameworks/JavaVM.framework/Versions $
```
and the contents of A
```
-rw-r--r-- 1 root wheel 1925 Feb 29 2008 CodeResources
drwxr-xr-x 34 root wheel 1156 Jun 14 15:49 Commands
drwxr-xr-x 3 root wheel 102 Mar 6 2008 Frameworks
drwxr-xr-x 16 root wheel 544 Jun 14 15:49 Headers
-rwxr-xr-x 1 root wheel 236080 Feb 29 2008 JavaVM
drwxr-xr-x 29 root wheel 986 Jun 14 15:49 Resources
steve-mbp /System/Library/Frameworks/JavaVM.framework/Versions/A $
``` | The (`A`, `Current` symbolic-linked to `A`) is part of the structure of a Mac OS X framework, which `JavaVM.framework` is. This framework may have C or Objective-C code in it, in addition to the actual JVM installations. Thus it could potentially be linked against from some C or Objective-C code in addition to containing the JVM alongside that.
Note that you **should not** change the `CurrentJDK` link to point at anything but what it is set to by Mac OS X. Unlike on other platforms, the Java virtual machine is an operating system service on Mac OS X, and changing it in this way would put you in an unsupported (and potentially untested, unstable, etc.) configuration. |
151,418 | <p>I have a function pointer defined by:</p>
<pre><code>typedef void (*EventFunction)(int nEvent);
</code></pre>
<p>Is there a way to handle that function with a specific instance of a C++ object?</p>
<pre><code>class A
{
private:
EventFunction handler;
public:
void SetEvent(EventFunction func) { handler = func; }
void EventOne() { handler(1); }
};
class B
{
private:
A a;
public:
B() { a.SetEvent(EventFromA); } // What do I do here?
void EventFromA(int nEvent) { // do stuff }
};
</code></pre>
<p><strong>Edit:</strong> Orion pointed out the options that Boost offers such as:</p>
<pre><code>boost::function<int (int)> f;
X x;
f = std::bind1st(
std::mem_fun(&X::foo), &x);
f(5); // Call x.foo(5)
</code></pre>
<p>Unfortunately Boost is not an option for me. Is there some sort of "currying" function that can be written in C++ that will do this kind of wrapping of a pointer to a member function in to a normal function pointer?</p>
| [
{
"answer_id": 151427,
"author": "markets",
"author_id": 4662,
"author_profile": "https://Stackoverflow.com/users/4662",
"pm_score": 1,
"selected": false,
"text": "<p>Unfortunately, the EventFunction type cannot point to a function of B, because it is not the correct type. You could make it the correct type, but that probably isn't really the solution you want:</p>\n\n<p><code>typedef void (*B::EventFunction)(int nEvent);</code></p>\n\n<p>... and then everything works once you call the callback with an obhect of B. But you probably want to be able to call functions outside of B, in other classes that do other things. That is sort of the point of a callback. But now this type points to something definitely in B. More attractive solutions are:</p>\n\n<ul>\n<li>Make B a base class, then override a virtual function for each other class that might be called. A then stores a pointer to B instead of a function pointer. Much cleaner.</li>\n<li>If you don't want to bind the function to a specific class type, even a base class (and I wouldn't blame you), then I suggest you make the function that gets called a static function: \"<code>static void EventFrom A(int nEvent);</code>\". Then you can call it directly, without an object of B. But you probably want it to call a specific instance of B (unless B is a singleton).</li>\n<li>So if you want to be able to call a specific instance of B, but be able to call non-B's, too, then you need to pass something else to your callback function so that the callback function can call the right object. Make your function a static, as above, and add a void* parameter which you will make a pointer to B.</li>\n</ul>\n\n<p>In practice you see two solutions to this problem: ad hoc systems where you pass a void* and the event, and hierarchies with virtual functions in a base class, like windowing systems</p>\n"
},
{
"answer_id": 151429,
"author": "Onorio Catenacci",
"author_id": 2820,
"author_profile": "https://Stackoverflow.com/users/2820",
"pm_score": 2,
"selected": false,
"text": "<p>You may find <a href=\"http://www.parashift.com/c++-faq/pointers-to-members.html\" rel=\"nofollow noreferrer\">C++ FAQ by Marshall Cline</a> helpful to what you're trying to accomplish.</p>\n"
},
{
"answer_id": 151435,
"author": "Franci Penov",
"author_id": 17028,
"author_profile": "https://Stackoverflow.com/users/17028",
"pm_score": 2,
"selected": false,
"text": "<p>Read about <a href=\"http://msdn.microsoft.com/en-us/library/f2wbycwh.aspx\" rel=\"nofollow noreferrer\">pointers to members</a>.\nTo call a method on the derived class, the method has to be declared in the base class as virtual and overriden in the base class and your pointer should point to the base class method. More about <a href=\"http://msdn.microsoft.com/en-us/library/fa0207h3.aspx\" rel=\"nofollow noreferrer\">pointers to virtual members</a>.</p>\n"
},
{
"answer_id": 151436,
"author": "shoosh",
"author_id": 9611,
"author_profile": "https://Stackoverflow.com/users/9611",
"pm_score": 0,
"selected": false,
"text": "<p>It's somewhat unclear what you're trying to accomplish here. what is clear is that function pointers is not the way. </p>\n\n<p>maybe what you're looking for is pointer to method.</p>\n"
},
{
"answer_id": 151439,
"author": "Orion Edwards",
"author_id": 234,
"author_profile": "https://Stackoverflow.com/users/234",
"pm_score": 4,
"selected": false,
"text": "<p>Run away from raw C++ function pointers, and use <a href=\"http://msdn.microsoft.com/en-us/library/bb982519.aspx\" rel=\"nofollow noreferrer\"><code>std::function</code></a> instead.</p>\n\n<p>You can use <a href=\"http://www.boost.org/doc/libs/1_36_0/doc/html/function/tutorial.html#id2903300\" rel=\"nofollow noreferrer\"><code>boost::function</code></a> if you are using an old compiler such as visual studio 2008 which has no support for C++11.<br>\n<code>boost:function</code> and <code>std::function</code> are the same thing - they pulled quite a bit of boost stuff into the std library for C++11.</p>\n\n<p>Note: you may want to read the boost function documentation instead of the microsoft one as it's easier to understand</p>\n"
},
{
"answer_id": 151449,
"author": "David Citron",
"author_id": 5309,
"author_profile": "https://Stackoverflow.com/users/5309",
"pm_score": 4,
"selected": false,
"text": "<p>You can use function pointers to index into the vtable of a given object instance. This is called a <a href=\"http://www.parashift.com/c++-faq-lite/pointers-to-members.html\" rel=\"noreferrer\">member function pointer</a>. Your syntax would need to change to use the \".*\" and the \"&::\" operators:</p>\n\n<pre><code>class A;\nclass B;\ntypedef void (B::*EventFunction)(int nEvent)\n</code></pre>\n\n<p>and then:</p>\n\n<pre><code>class A\n{\nprivate:\n EventFunction handler;\n\npublic:\n void SetEvent(EventFunction func) { handler = func; }\n\n void EventOne(B* delegate) { ((*delegate).*handler)(1); } // note: \".*\"\n};\n\nclass B\n{\nprivate:\n A a;\npublic:\n B() { a.SetEvent(&B::EventFromA); } // note: \"&::\"\n\n void EventFromA(int nEvent) { /* do stuff */ }\n};\n</code></pre>\n"
},
{
"answer_id": 151712,
"author": "KPexEA",
"author_id": 13676,
"author_profile": "https://Stackoverflow.com/users/13676",
"pm_score": 0,
"selected": false,
"text": "<p>I have a set of classes for this exact thing that I use in my c++ framework.</p>\n\n<p><a href=\"http://code.google.com/p/kgui/source/browse/trunk/kgui.h\" rel=\"nofollow noreferrer\">http://code.google.com/p/kgui/source/browse/trunk/kgui.h</a></p>\n\n<p>How I handle it is each class function that can be used as a callback needs a static function that binds the object type to it. I have a set of macros that do it automatically. It makes a static function with the same name except with a \"CB_\" prefix and an extra first parameter which is the class object pointer.</p>\n\n<p>Checkout the Class types kGUICallBack and various template versions thereof for handling different parameters combinations.</p>\n\n<pre><code>#define CALLBACKGLUE(classname , func) static void CB_ ## func(void *obj) {static_cast< classname *>(obj)->func();}\n#define CALLBACKGLUEPTR(classname , func, type) static void CB_ ## func(void *obj,type *name) {static_cast< classname *>(obj)->func(name);}\n#define CALLBACKGLUEPTRPTR(classname , func, type,type2) static void CB_ ## func(void *obj,type *name,type2 *name2) {static_cast< classname *>(obj)->func(name,name2);}\n#define CALLBACKGLUEPTRPTRPTR(classname , func, type,type2,type3) static void CB_ ## func(void *obj,type *name,type2 *name2,type3 *name3) {static_cast< classname *>(obj)->func(name,name2,name3);}\n#define CALLBACKGLUEVAL(classname , func, type) static void CB_ ## func(void *obj,type val) {static_cast< classname *>(obj)->func(val);}\n</code></pre>\n"
},
{
"answer_id": 151733,
"author": "Adam Rosenfield",
"author_id": 9530,
"author_profile": "https://Stackoverflow.com/users/9530",
"pm_score": 2,
"selected": false,
"text": "<p>If you're interfacing with a C library, then you can't use a class member function without using something like <code>boost::bind</code>. Most C libraries that take a callback function usually also allow you to pass an extra argument of your choosing (usually of type <code>void*</code>), which you can use to bootstrap your class, as so:</p>\n\n<pre><code>\nclass C\n{\npublic:\n int Method1(void) { return 3; }\n int Method2(void) { return x; }\n\n int x;\n};\n\n// This structure will hold a thunk to\nstruct CCallback\n{\n C *obj; // Instance to callback on\n int (C::*callback)(void); // Class callback method, taking no arguments and returning int\n};\n\nint CBootstrapper(CCallback *pThunk)\n{\n // Call the thunk\n return ((pThunk->obj) ->* (pThunk->callback))( /* args go here */ );\n}\n\nvoid DoIt(C *obj, int (C::*callback)(void))\n{\n // foobar() is some C library function that takes a function which takes no arguments and returns int, and it also takes a void*, and we can't change it\n struct CCallback thunk = {obj, callback};\n foobar(&CBootstrapper, &thunk);\n}\n\nint main(void)\n{\n C c;\n DoIt(&c, &C::Method1); // Essentially calls foobar() with a callback of C::Method1 on c\n DoIt(&c, &C::Method2); // Ditto for C::Method2\n}\n</code></pre>\n"
},
{
"answer_id": 151758,
"author": "Ron Warholic",
"author_id": 22780,
"author_profile": "https://Stackoverflow.com/users/22780",
"pm_score": 4,
"selected": true,
"text": "<p>I highly recommend Don Clugston's excellent FastDelegate library. It provides all the things you'd expect of a real delegate and compiles down to a few ASM instructions in most cases. The accompanying article is a good read on member function pointers as well.</p>\n\n<p><a href=\"http://www.codeproject.com/KB/cpp/FastDelegate.aspx\" rel=\"noreferrer\">http://www.codeproject.com/KB/cpp/FastDelegate.aspx</a></p>\n"
},
{
"answer_id": 151793,
"author": "Corey Ross",
"author_id": 5927,
"author_profile": "https://Stackoverflow.com/users/5927",
"pm_score": 1,
"selected": false,
"text": "<p>You mention that boost isn't an option for you, but do you have TR1 available to you?</p>\n\n<p>TR1 offers function, bind, and mem_fn objects based on the boost library, and you may already have it bundled with your compiler. It isn't standard yet, but at least two compilers that I've used recently have had it.</p>\n\n<p><a href=\"http://en.wikipedia.org/wiki/Technical_Report_1\" rel=\"nofollow noreferrer\">http://en.wikipedia.org/wiki/Technical_Report_1</a><br>\n<a href=\"http://msdn.microsoft.com/en-us/library/bb982702.aspx\" rel=\"nofollow noreferrer\">http://msdn.microsoft.com/en-us/library/bb982702.aspx</a> </p>\n"
}
]
| 2008/09/30 | [
"https://Stackoverflow.com/questions/151418",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4592/"
]
| I have a function pointer defined by:
```
typedef void (*EventFunction)(int nEvent);
```
Is there a way to handle that function with a specific instance of a C++ object?
```
class A
{
private:
EventFunction handler;
public:
void SetEvent(EventFunction func) { handler = func; }
void EventOne() { handler(1); }
};
class B
{
private:
A a;
public:
B() { a.SetEvent(EventFromA); } // What do I do here?
void EventFromA(int nEvent) { // do stuff }
};
```
**Edit:** Orion pointed out the options that Boost offers such as:
```
boost::function<int (int)> f;
X x;
f = std::bind1st(
std::mem_fun(&X::foo), &x);
f(5); // Call x.foo(5)
```
Unfortunately Boost is not an option for me. Is there some sort of "currying" function that can be written in C++ that will do this kind of wrapping of a pointer to a member function in to a normal function pointer? | I highly recommend Don Clugston's excellent FastDelegate library. It provides all the things you'd expect of a real delegate and compiles down to a few ASM instructions in most cases. The accompanying article is a good read on member function pointers as well.
<http://www.codeproject.com/KB/cpp/FastDelegate.aspx> |
151,448 | <p>Bearing in mind this is for <strong>classic asp</strong></p>
<p>Which is better, all HTML contained within Response.Write Statements or inserting variables into HTML via <%= %>.<br>
Eg </p>
<pre><code>Response.Write "<table>" & vbCrlf
Response.Write "<tr>" &vbCrLf
Response.Write "<td class=""someClass"">" & someVariable & "</td>" & vbCrLf
Response.Write "</tr>" & vbCrLf
Response.Write "</table>" & vbCrLf
</code></pre>
<p>VS</p>
<pre><code><table>
<tr>
<td class="someClass"><%= someVariable %></td>
</tr>
</table>
</code></pre>
<p>I am mainly asking from a performance point of view in which will have the least server impact when there multiple variables to insert?</p>
<p>If there are no technical differences what are the arguments for one over the other?</p>
| [
{
"answer_id": 151454,
"author": "Jon P",
"author_id": 4665,
"author_profile": "https://Stackoverflow.com/users/4665",
"pm_score": 4,
"selected": false,
"text": "<p>From a personal preference point of view I prefer the <%= %> method as I feel it provides a better separation variable content from static content.</p>\n"
},
{
"answer_id": 151455,
"author": "Mark Cidade",
"author_id": 1659,
"author_profile": "https://Stackoverflow.com/users/1659",
"pm_score": 1,
"selected": false,
"text": "<p><code><%= %></code> and the rest get expanded to <code>Response.Write()</code> so it's the same in the end.</p>\n"
},
{
"answer_id": 151464,
"author": "Cade Roux",
"author_id": 18255,
"author_profile": "https://Stackoverflow.com/users/18255",
"pm_score": 1,
"selected": false,
"text": "<p>There is no performance improvement switching to Response.Write, and it can be faster to read and maintain using the shortcut notation.</p>\n"
},
{
"answer_id": 151522,
"author": "Jason Jackson",
"author_id": 13103,
"author_profile": "https://Stackoverflow.com/users/13103",
"pm_score": 1,
"selected": false,
"text": "<p>You should frame this questions in terms of code reuse and code maintainability (aka readability). There is really no performance gain either way.</p>\n"
},
{
"answer_id": 151536,
"author": "Russell Myers",
"author_id": 18194,
"author_profile": "https://Stackoverflow.com/users/18194",
"pm_score": 2,
"selected": false,
"text": "<p>The response format will render HTML like so:</p>\n\n<pre><code><table>\n<tr>\n<td class=\"someClass\">variable value</td>\n</tr>\n</table>\n</code></pre>\n\n<p>As a result, not only will the means to produce your code be unreadable, but the result will also be tabbed inappropriately. Stick with the other option.</p>\n"
},
{
"answer_id": 151592,
"author": "Euro Micelli",
"author_id": 2230,
"author_profile": "https://Stackoverflow.com/users/2230",
"pm_score": 6,
"selected": true,
"text": "<p>First, The most important factor you should be looking at is ease of maintenance. You could buy a server farm with the money and time you would otherwise waste by having to decipher a messy web site to maintain it.</p>\n\n<p>In any case, it doesn't matter. At the end of the day, all ASP does is just execute a script! The ASP parser takes the page, and transforms <code><%= expression %></code> into direct script calls, and every contiguous block of HTML becomes one giant call to <code>Response.Write</code>. The resulting script is cached and reused unless the page changes on disk, which causes the cached script to be recalculated.</p>\n\n<p>Now, too much use of <code><%= %></code> leads to the modern version of \"spaghetti code\": the dreaded \"Tag soup\". You won't be able to make heads or tails of the logic. On the other hand, too much use of Response.Write means you will never be able to see the page at all until it renders. Use <code><%= %></code> when appropriate to get the best of both worlds.</p>\n\n<p>My first rule is to pay attention at the proportion of \"variable text\" to \"static text\".</p>\n\n<p>If you have just a few places with variable text to replace, the <code><%= %></code> syntax is very compact and readable. However, as the <code><%= %></code> start to accumulate, they obscure more and more of the HTML and at the same time the HTML obscures more and more of your logic. As a general rule, once you start taking about loops, you need to stop and switch to Response.Write`.</p>\n\n<p>There aren't many other hard and fast rules. You need to decide for your particular page (or section of the page) which one is more important, or naturally harder to understand, or easier to break: your logic or your HTML? It's usually one or the other (I've seen hundreds of cases of both)</p>\n\n<p>If you logic is more critical, you should weight more towards <code>Response.Write</code>; it will make the logic stand out. If you HTML is more critical, favor <code><%= %></code>, which will make the page structure more visible.</p>\n\n<p>Sometimes I've had to write both versions and compare them side-by-side to decide which one is more readable; it's a last resort, but do it while the code is fresh in your mind and you will be glad three months later when you have to make changes.</p>\n"
},
{
"answer_id": 151616,
"author": "Jacob Krall",
"author_id": 3140,
"author_profile": "https://Stackoverflow.com/users/3140",
"pm_score": 1,
"selected": false,
"text": "<p><strong><%=Bazify()%></strong> is useful when you are generating HTML from a <strong>short expression inline with some HTML</strong>.</p>\n\n<p><strong>Response.Write \"foo\"</strong> is better when you need to do some <strong>HTML inline with a lot of code</strong>.</p>\n\n<p>Technically, they are the same.</p>\n\n<p>Speaking about your example, though, the Response.Write code does a lot of string concatenation with &, which is <a href=\"http://www.asp101.com/articles/john/outputperf/default.asp\" rel=\"nofollow noreferrer\">very slow in VBScript</a>. Also, like <a href=\"https://stackoverflow.com/questions/151448/responsewrite-vs#151536\">Russell Myers said</a>, it's not tabbed the same way as your other code, which might be unintentional.</p>\n"
},
{
"answer_id": 151646,
"author": "ManiacZX",
"author_id": 18148,
"author_profile": "https://Stackoverflow.com/users/18148",
"pm_score": 2,
"selected": false,
"text": "<p>I prefer the <%= %> method in most situations for several reasons.</p>\n\n<ol>\n<li>The HTML is exposed to the IDE so\nthat it can be processed giving you\ntooltips, tag closing, etc.</li>\n<li>Maintaining indentation in the\noutput HTML is easier which can be\nvery helpful with reworking layout.</li>\n<li>New lines without appending vbCrLf\non everything and again for reviewing output source.</li>\n</ol>\n"
},
{
"answer_id": 151657,
"author": "Dan Herbert",
"author_id": 392,
"author_profile": "https://Stackoverflow.com/users/392",
"pm_score": 2,
"selected": false,
"text": "<p>I prefer <code><%= %></code> solely because it makes Javascript development easier. You can write code that references your controls like this </p>\n\n<pre><code>var myControl = document.getElementById('<%= myControl.ClientID %>');\n</code></pre>\n\n<p>I can then use that control any way I'd like in my javascript code without having to worry about the hard coded IDs.</p>\n\n<p>Response.Write can break some ASP.NET AJAX code on some occasions so I try to avoid it unless using it for rendering specific things in custom controls.</p>\n"
},
{
"answer_id": 151672,
"author": "Simon Forrest",
"author_id": 4733,
"author_profile": "https://Stackoverflow.com/users/4733",
"pm_score": 3,
"selected": false,
"text": "<p>Leaving aside issues of code readibility/maintainibility which others have addressed, your question was specifically about performance when you have multiple variables to insert - so I assume you're going to be repeating something like your code fragment multiple times. In that case, you should get the best performance by using a single Response.Write without concatenating all of the newlines:</p>\n\n<pre><code>Response.Write \"<table><tr><td class=\"\"someClass\"\">\" & someVar & \"</td></tr></table>\"\n</code></pre>\n\n<p>The browser doesn't need the newlines or the tabs or any other pretty formatting to parse the HTML. If you're going for performance, you can remove all of these. You'll also make your HTML output smaller, which will give you faster page load times.</p>\n\n<p>In the case of a single variable, it doesn't really make a lot of difference. But for multiple variables, you want to minimise the context switching between HTML and ASP - you'll take a hit for every jump from one to the other.</p>\n\n<p>To help with readibility when building a longer statement, you can use the VBScript line continuation charcter and tabs in your source code (but not the output) to represent the structure without hitting your performance:</p>\n\n<pre><code>Response.Write \"<table>\" _\n & \"<tr>\" _\n & \"<td class=\"\"someClass\"\">\" & someVar & \"</td>\" _\n & \"</tr>\" _\n & \"<tr>\" _\n & \"<td class=\"\"anotherClass\"\">\" & anotherVar & \"</td>\" _\n & \"</tr>\" _\n & \"<tr>\" _\n & \"<td class=\"\"etc\"\">\" & andSoOn & \"</td>\" _\n & \"</tr>\" _\n & \"</table>\"\n</code></pre>\n\n<p>It's not as legible as the HTML version but if you're dropping a lot of variables into the output (ie a lot of context switching between HTML and ASP), you'll see better performance.</p>\n\n<p>Whether the performance gains are worth it or whether you would be better off scaling your hardware is a separate question - and, of course, it's not always an option.</p>\n\n<p><strong>Update:</strong> see tips 14 and 15 in this MSDN article by Len Cardinal for information on improving performance with Response.Buffer and avoiding context switching: <a href=\"http://msdn.microsoft.com/en-us/library/ms972335.aspx#asptips_topic15\" rel=\"noreferrer\">http://msdn.microsoft.com/en-us/library/ms972335.aspx#asptips_topic15</a>.</p>\n"
},
{
"answer_id": 151704,
"author": "Jason Dufair",
"author_id": 20540,
"author_profile": "https://Stackoverflow.com/users/20540",
"pm_score": 2,
"selected": false,
"text": "<p>I try to use the MVC paradigm when doing ASP/PHP. It makes things easiest to maintain, re-architect, expand upon. In that regard, I tend to have a page that represents the model. It's mostly VB/PHP and sets vars for later use in the view. It also generates hunks of HTML when looping for later inclusion in the view. Then I have a page that represents the view. That's mostly HTML peppered with <%= %> tags. The model is #include -d in the view and away you go. Controller logic is typically done in JavaScript in a third page or server-side.</p>\n"
},
{
"answer_id": 152126,
"author": "AnthonyWJones",
"author_id": 17516,
"author_profile": "https://Stackoverflow.com/users/17516",
"pm_score": 4,
"selected": false,
"text": "<p>Many of the answers here indicate that the two approaches produce the same output and that the choice is one of coding style and performance. Its seems its believed that static content outside of <% %> becomes a single Response.Write.</p>\n\n<p>However it would be more accurate to say the code outside <% %> gets sent with BinaryWrite.</p>\n\n<p>Response.Write takes a Unicode string and encodes it to the current Response.CodePage before placing it in the buffer. No such encoding takes place for the static content in an ASP file. The characters outside <% %> are dumped verbatim byte for byte into the buffer.</p>\n\n<p>Hence where the Response.CodePage is different than the CodePage that was used to save the ASP file the results of the two approaches may differ.</p>\n\n<p>For example lets say I have this content saved in a standard 1252 code page:-</p>\n\n<pre><code><%\n Response.CodePage = 65001\n Response.CharSet = \"UTF-8\"\n %>\n<p> The British £</p>\n<%Response.Write(\"<p> The British £</p>\")%>\n</code></pre>\n\n<p>The first paragraph is garbled, since the £ will not be sent using UTF-8 encoding, the second is fine because the Unicode string supplied is encoded to UTF-8.</p>\n\n<p>Hence from a perfomance point of view using static content is preferable since it doesn't need encoding but care is needed if the saved code page differs from the output codepage. For this reason I prefer to save as UTF-8, include <%@ codepage=65001 and set Response.Charset = \"UTF-8\".</p>\n"
},
{
"answer_id": 156756,
"author": "Sprogz",
"author_id": 7508,
"author_profile": "https://Stackoverflow.com/users/7508",
"pm_score": 1,
"selected": false,
"text": "<p>I agree with <a href=\"https://stackoverflow.com/users/20540/jason-dufair\">Jason</a>, more so now that .NET is offering an MVC framework as an alternative to that awful Web Form/Postback/ViewState .NET started out with.</p>\n\n<p>Maybe it's because I was old-school classic ASP/HTML/JavaScript and not a VB desktop application programmer that caused me to just not grokk \"The Way of the Web Form?\" but I'm so pleased we seem to be going full circle and back to a methodology like <a href=\"https://stackoverflow.com/users/20540/jason-dufair\">Jason</a> refers to.</p>\n\n<p>With that in mind, I'd always choose an included page containing your model/logic and <%= %> tokens within your, effectively template HTML \"view.\" Your HTML will be more \"readable\" and your logic separated as much as classic ASP allows; you're killing a couple of birds with that stone.</p>\n"
},
{
"answer_id": 230697,
"author": "Nic Wise",
"author_id": 2947,
"author_profile": "https://Stackoverflow.com/users/2947",
"pm_score": 2,
"selected": false,
"text": "<p>My classic ASP is rusty, but:</p>\n\n<pre><code>Response.Write \"<table>\" & vbCrlf\nResponse.Write \"<tr>\" &vbCrLf\nResponse.Write \"<tdclass=\"\"someClass\"\">\" & someVariable & \"</td>\" & vbCrLf \nResponse.Write \"</tr>\" & vbCrLf \nResponse.Write \"</table>\" & vbCrLf\n</code></pre>\n\n<p>this is run as-is. This, however:</p>\n\n<pre><code><table>\n <tr>\n <td class=\"someClass\"><%= someVariable %></td>\n </tr>\n</table>\n</code></pre>\n\n<p>results in:</p>\n\n<pre><code>Response.Write\"<table>\\r\\n<tr>\\r\\n<td class=\"someClass\">\"\nResponse.Write someVariable\nResponse.Write \"</td>\\r\\n</tr>\\r\\n</table>\"\n</code></pre>\n\n<p>Where \\r\\n is a vbCrLf</p>\n\n<p>So technically, the second one is quicker. HOWEVER, the difference would be measured in single milliseconds, so I wouldn't worry about it. I'd be more concerned that the top one is pretty much unmaintainable (esp by a HTML-UI developer), where as the second one is trivial to maintain.</p>\n\n<p>props to @Euro Micelli - maintenance is the key (which is also why languages like Ruby, Python, and in the past (tho still....) C# and Java kicked butt over C, C++ and Assembly- humans could maintain the code, which is way more important than shaving a few ms off a page load.</p>\n\n<p>Of course, C/C++ etc have their place.... but this isn't it. :)</p>\n"
},
{
"answer_id": 28197584,
"author": "Andrew",
"author_id": 2494935,
"author_profile": "https://Stackoverflow.com/users/2494935",
"pm_score": 1,
"selected": false,
"text": "<p>If you are required to write and maintain a Classic ASP application you should check out the free KudzuASP template engine.</p>\n\n<p>It is capable of 100% code and HTML separation and allows for conditional content, variable substitution, template level control of the original asp page. If-Then-Else, Try-Catch-Finally, Switch-Case, and other structural tags are available as well as custom tags based in the asp page or in dynamically loadable libraries (asp code files) Structural tags can be embedded within other structural tags to any desired level. </p>\n\n<p>Custom tags and tag libraries are easy to write and can be included at the asp page's code level or by using an include tag at the template level.</p>\n\n<p>Master pages can be written by invoking a template engine at the master page level and leveraging a second child template engine for any internal content.</p>\n\n<p>In KudzuASP your asp page contains only code, creates the template engine, sets up initial conditions and invokes the template. The template contains HTML layout. Once the asp page invokes the template it then becomes an event driven resource fully driven by the evaluation of the template and the structure that it contains.</p>\n"
}
]
| 2008/09/30 | [
"https://Stackoverflow.com/questions/151448",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4665/"
]
| Bearing in mind this is for **classic asp**
Which is better, all HTML contained within Response.Write Statements or inserting variables into HTML via <%= %>.
Eg
```
Response.Write "<table>" & vbCrlf
Response.Write "<tr>" &vbCrLf
Response.Write "<td class=""someClass"">" & someVariable & "</td>" & vbCrLf
Response.Write "</tr>" & vbCrLf
Response.Write "</table>" & vbCrLf
```
VS
```
<table>
<tr>
<td class="someClass"><%= someVariable %></td>
</tr>
</table>
```
I am mainly asking from a performance point of view in which will have the least server impact when there multiple variables to insert?
If there are no technical differences what are the arguments for one over the other? | First, The most important factor you should be looking at is ease of maintenance. You could buy a server farm with the money and time you would otherwise waste by having to decipher a messy web site to maintain it.
In any case, it doesn't matter. At the end of the day, all ASP does is just execute a script! The ASP parser takes the page, and transforms `<%= expression %>` into direct script calls, and every contiguous block of HTML becomes one giant call to `Response.Write`. The resulting script is cached and reused unless the page changes on disk, which causes the cached script to be recalculated.
Now, too much use of `<%= %>` leads to the modern version of "spaghetti code": the dreaded "Tag soup". You won't be able to make heads or tails of the logic. On the other hand, too much use of Response.Write means you will never be able to see the page at all until it renders. Use `<%= %>` when appropriate to get the best of both worlds.
My first rule is to pay attention at the proportion of "variable text" to "static text".
If you have just a few places with variable text to replace, the `<%= %>` syntax is very compact and readable. However, as the `<%= %>` start to accumulate, they obscure more and more of the HTML and at the same time the HTML obscures more and more of your logic. As a general rule, once you start taking about loops, you need to stop and switch to Response.Write`.
There aren't many other hard and fast rules. You need to decide for your particular page (or section of the page) which one is more important, or naturally harder to understand, or easier to break: your logic or your HTML? It's usually one or the other (I've seen hundreds of cases of both)
If you logic is more critical, you should weight more towards `Response.Write`; it will make the logic stand out. If you HTML is more critical, favor `<%= %>`, which will make the page structure more visible.
Sometimes I've had to write both versions and compare them side-by-side to decide which one is more readable; it's a last resort, but do it while the code is fresh in your mind and you will be glad three months later when you have to make changes. |
151,521 | <p>I'm a LINQ to XML newbie, and a KML newbie as well; so bear with me. </p>
<p>My goal is to extract individual Placemarks from a KML file. My KML begins thusly:</p>
<pre class="lang-xml prettyprint-override"><code><?xml version="1.0" encoding="utf-8"?>
<Document xmlns="http://earth.google.com/kml/2.0">
<name>Concessions</name>
<visibility>1</visibility>
<Folder>
<visibility>1</visibility>
<Placemark>
<name>IN920211</name>
<Style>
<PolyStyle>
<color>80000000</color>
</PolyStyle>
</Style>
<Polygon>
<altitudeMode>relativeToGround</altitudeMode>
<outerBoundaryIs>
<LinearRing>
<coordinates>11.728374,1.976421,0 11.732967,1.965322,0 11.737225,1.953161,0 11.635858,1.940812,0 11.658102,1.976874,0 11.728374,1.976421,0 </coordinates>
</LinearRing>
</outerBoundaryIs>
</Polygon>
</Placemark>
<Placemark>
...
</code></pre>
<p>This is as far as I've gotten:</p>
<pre class="lang-vb prettyprint-override"><code> Dim Kml As XDocument = XDocument.Load(Server.MapPath("../kmlimport/ga.kml"))
Dim Placemarks = From Placemark In Kml.Descendants("Placemark") _
Select Name = Placemark.Element("Name").Value
</code></pre>
<p>So far no good - Kml.Descendants("Placemark") gives me an empty enumeration. The document is loaded properly - because KML.Descendants contains every node. For what it's worth these queries come up empty as well:</p>
<pre><code>Dim foo = Kml.Descendants("Document")
Dim foo = Kml.Descendants("Folder")
</code></pre>
<p>Can someone point me in the right direction? Bonus points for links to good Linq to XML tutorials - the ones I've found online stop at very simple scenarios. </p>
| [
{
"answer_id": 151561,
"author": "Bruce Murdock",
"author_id": 23650,
"author_profile": "https://Stackoverflow.com/users/23650",
"pm_score": 0,
"selected": false,
"text": "<p>You may need to add a namespace to the XElement name</p>\n\n<pre><code>Dim ns as string = \"http://earth.google.com/kml/2.0\"\ndim foo = Kml.Descendants(ns + \"Document\") \n</code></pre>\n\n<p>ignore any syntax errors, I work in c#</p>\n\n<p>You'll find there can be a difference in the <code>XElement.Name</code> vs <code>XElement.Name.LocalName/</code></p>\n\n<p>I usually <code>foreach</code> through all the <code>XElements</code> in the doc to as a first step to make sure I'm using the right naming.</p>\n\n<p>C# \nHere is an excerpt of my usage, looks like I forgot the {}</p>\n\n<pre><code> private string GpNamespace = \n \"{http://schemas.microsoft.com/GroupPolicy/2006/07/PolicyDefinitions}\";\n\n var results = admldoc.Descendants(GpNamespace + \n \"presentationTable\").Descendants().Select(\n p => new dcPolicyPresentation(p));\n</code></pre>\n"
},
{
"answer_id": 153139,
"author": "Herb Caudill",
"author_id": 239663,
"author_profile": "https://Stackoverflow.com/users/239663",
"pm_score": 0,
"selected": false,
"text": "<p>Neither of the above fixes did the job; see my comments for details. I believe both spoon16 and Bruce Murdock are on the right track, since the namespace is definitely the issue. </p>\n\n<p>After further Googling I came across some code on <a href=\"http://www.scip.be/index.php?Page=ArticlesNET21&Lang=NL\" rel=\"nofollow noreferrer\">this page</a> that suggested a workaround: just strip the xmlns attribute from the original XML.</p>\n\n<pre><code> ' Read raw XML\n Dim RawXml As String = ReadFile(\"../kmlimport/ga.kml\")\n ' HACK: Linq to XML choking on the namespace, just get rid of it\n RawXml = RawXml.Replace(\"xmlns=\"\"http://earth.google.com/kml/2.0\"\"\", \"\")\n ' Parse XML\n Dim Kml As XDocument = XDocument.Parse(RawXml)\n ' Loop through placemarks\n Dim Placemarks = From Placemark In Kml.<Document>.<Folder>.Descendants(\"Placemark\")\n For Each Placemark As XElement In Placemarks\n Dim Name As String = Placemark.<name>.Value\n ...\n Next\n</code></pre>\n\n<p>If anyone can post working code that works with the namespace instead of nuking it, I'll gladly give them the answer.</p>\n"
},
{
"answer_id": 153282,
"author": "Herb Caudill",
"author_id": 239663,
"author_profile": "https://Stackoverflow.com/users/239663",
"pm_score": 2,
"selected": true,
"text": "<p>Thanks to spoon16 and Bruce Murdock for pointing me in the right direction. The code that spoon16 posted works, but forces you to concatenate the namespace with every single element name, which isn't as clean as I'd like.</p>\n\n<p>I've done a bit more searching and I've figured out how this is supposed to be done - this is super concise, and I love the new <...> bracket syntax for referring to XML elements.</p>\n\n<pre><code>Imports <xmlns:g='http://earth.google.com/kml/2.0'>\nImports System.Xml.Linq\n\n ...\n\n Dim Kml As XDocument = XDocument.Load(Server.MapPath(\"../kmlimport/ga.kml\"))\n For Each Placemark As XElement In Kml.<g:Document>.<g:Folder>.<g:Placemark>\n Dim Name As String = Placemark.<g:name>.Value\n Next\n</code></pre>\n\n<p>Note the <strong>:g</strong> following the xmlns in the first line. This gives you a shortcut to refer to this namespace elsewhere. </p>\n\n<p>For more about the XNamespace class, see the <a href=\"http://msdn.microsoft.com/en-us/library/system.xml.linq.xnamespace.aspx\" rel=\"nofollow noreferrer\">MSDN documentation</a>. </p>\n"
},
{
"answer_id": 223422,
"author": "Matthew Ruston",
"author_id": 506,
"author_profile": "https://Stackoverflow.com/users/506",
"pm_score": 1,
"selected": false,
"text": "<p>Scott Hanselman has a concise solution for those looking for a C# based solution.</p>\n\n<p><a href=\"http://www.hanselman.com/blog/XLINQToXMLSupportInVB9.aspx\" rel=\"nofollow noreferrer\">XLINQ to XML support in VB9</a></p>\n\n<p>Also, using XNamespace comes in handy, rather than just appending a string. This is a bit more formal.</p>\n\n<pre class=\"lang-cs prettyprint-override\"><code>// This code should get all Placemarks from a KML file \nvar xdoc = XDocument.Parse(kmlContent);\nXNamespace ns = XNamespace.Get(\"http://earth.google.com/kml/2.0\");\nvar ele = xdoc.Element(ns + \"kml\").Element(ns + \"Document\").Elements(ns + \"Placemark\");\n</code></pre>\n"
},
{
"answer_id": 1494001,
"author": "Jacob",
"author_id": 181298,
"author_profile": "https://Stackoverflow.com/users/181298",
"pm_score": 3,
"selected": false,
"text": "<p>This works for me in C#:</p>\n\n<pre class=\"lang-cs prettyprint-override\"><code>XDocument doc = XDocument.Load(@\"TheFile.kml\");\n\nvar q = doc.Descendants().Where(x => x.Name.LocalName == \"Placemark\"); \n</code></pre>\n"
}
]
| 2008/09/30 | [
"https://Stackoverflow.com/questions/151521",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/239663/"
]
| I'm a LINQ to XML newbie, and a KML newbie as well; so bear with me.
My goal is to extract individual Placemarks from a KML file. My KML begins thusly:
```xml
<?xml version="1.0" encoding="utf-8"?>
<Document xmlns="http://earth.google.com/kml/2.0">
<name>Concessions</name>
<visibility>1</visibility>
<Folder>
<visibility>1</visibility>
<Placemark>
<name>IN920211</name>
<Style>
<PolyStyle>
<color>80000000</color>
</PolyStyle>
</Style>
<Polygon>
<altitudeMode>relativeToGround</altitudeMode>
<outerBoundaryIs>
<LinearRing>
<coordinates>11.728374,1.976421,0 11.732967,1.965322,0 11.737225,1.953161,0 11.635858,1.940812,0 11.658102,1.976874,0 11.728374,1.976421,0 </coordinates>
</LinearRing>
</outerBoundaryIs>
</Polygon>
</Placemark>
<Placemark>
...
```
This is as far as I've gotten:
```vb
Dim Kml As XDocument = XDocument.Load(Server.MapPath("../kmlimport/ga.kml"))
Dim Placemarks = From Placemark In Kml.Descendants("Placemark") _
Select Name = Placemark.Element("Name").Value
```
So far no good - Kml.Descendants("Placemark") gives me an empty enumeration. The document is loaded properly - because KML.Descendants contains every node. For what it's worth these queries come up empty as well:
```
Dim foo = Kml.Descendants("Document")
Dim foo = Kml.Descendants("Folder")
```
Can someone point me in the right direction? Bonus points for links to good Linq to XML tutorials - the ones I've found online stop at very simple scenarios. | Thanks to spoon16 and Bruce Murdock for pointing me in the right direction. The code that spoon16 posted works, but forces you to concatenate the namespace with every single element name, which isn't as clean as I'd like.
I've done a bit more searching and I've figured out how this is supposed to be done - this is super concise, and I love the new <...> bracket syntax for referring to XML elements.
```
Imports <xmlns:g='http://earth.google.com/kml/2.0'>
Imports System.Xml.Linq
...
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
```
Note the **:g** following the xmlns in the first line. This gives you a shortcut to refer to this namespace elsewhere.
For more about the XNamespace class, see the [MSDN documentation](http://msdn.microsoft.com/en-us/library/system.xml.linq.xnamespace.aspx). |
151,545 | <p>I need to get the fully expanded hostname of the host that my Ruby script is running on. In Perl I've used Sys::Hostname::Long with good results. Google seems to suggest I should use Socket.hostname in ruby, but that's returning just the nodename, not the full hostname.</p>
| [
{
"answer_id": 151570,
"author": "dvorak",
"author_id": 19235,
"author_profile": "https://Stackoverflow.com/users/19235",
"pm_score": 4,
"selected": false,
"text": "<p>This seems to work:</p>\n\n<pre><code>hostname = Socket.gethostbyname(Socket.gethostname).first \n</code></pre>\n"
},
{
"answer_id": 1824647,
"author": "charley hine",
"author_id": 221918,
"author_profile": "https://Stackoverflow.com/users/221918",
"pm_score": -1,
"selected": false,
"text": "<p>Could be a tad simpler => hostname = Socket.gethostname </p>\n"
},
{
"answer_id": 12046321,
"author": "Alexis Lê-Quôc",
"author_id": 318497,
"author_profile": "https://Stackoverflow.com/users/318497",
"pm_score": 3,
"selected": false,
"text": "<pre><code>hostname = Socket.gethostbyname(Socket.gethostname).first\n</code></pre>\n\n<p>is not recommended and will only work if your reverse DNS resolution is properly set up. <a href=\"https://projects.puppetlabs.com/issues/3898\">This Facter bug</a> has a longer explanation if needed.</p>\n\n<p>If you read the facter code, you'll notice that they somewhat <a href=\"https://github.com/puppetlabs/facter/blob/master/lib/facter/fqdn.rb\">sidestep the issue altogether by saying</a>:</p>\n\n<pre><code>fqdn = hostname + domainname\n</code></pre>\n\n<p>where:</p>\n\n<pre><code>hostname = %[hostname]\ndomainname = %[hostname -f] # minus the first element\n</code></pre>\n\n<p>This is a reasonable assumption that does not depend on the setup of DNS (which may be external to the box).</p>\n"
}
]
| 2008/09/30 | [
"https://Stackoverflow.com/questions/151545",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/19235/"
]
| I need to get the fully expanded hostname of the host that my Ruby script is running on. In Perl I've used Sys::Hostname::Long with good results. Google seems to suggest I should use Socket.hostname in ruby, but that's returning just the nodename, not the full hostname. | This seems to work:
```
hostname = Socket.gethostbyname(Socket.gethostname).first
``` |
151,555 | <p>I'm creating a Firefox extension for demo purposes.
I to call a specific JavaScript function in the document from the extension.
I wrote this in my HTML document (not inside extension, but a page that is loaded by Firefox):</p>
<pre><code>document.funcToBeCalled = function() {
// function body
};
</code></pre>
<p>Then, the extension will run this on some event:</p>
<pre><code>var document = Application.activeWindow.activeTab.document;
document.funcToBeCalled();
</code></pre>
<p>However it raises an error saying that <code>funcToBeCalled</code> is not defined.</p>
<p>Note: I could get an element on the document by calling <code>document.getElementById(id);</code></p>
| [
{
"answer_id": 151786,
"author": "scottru",
"author_id": 8192,
"author_profile": "https://Stackoverflow.com/users/8192",
"pm_score": 0,
"selected": false,
"text": "<p>You can do it, but you need to have control over the page and be able to raise the privilege level for the script. <a href=\"http://developer.mozilla.org/en/How_to_Build_an_XPCOM_Component_in_Javascript\" rel=\"nofollow noreferrer\">Mozilla Documentation gives an example</a> - search for \"Privilege\" on the page.</p>\n"
},
{
"answer_id": 168185,
"author": "Nickolay",
"author_id": 1026,
"author_profile": "https://Stackoverflow.com/users/1026",
"pm_score": 4,
"selected": true,
"text": "<p>It is for security reasons that you have limited access to the content page from extension. See <a href=\"http://developer.mozilla.org/en/docs/XPCNativeWrapper\" rel=\"noreferrer\">XPCNativeWrapper</a> and <a href=\"http://developer.mozilla.org/en/Safely_accessing_content_DOM_from_chrome\" rel=\"noreferrer\">Safely accessing content DOM from chrome</a>,</p>\n\n<p>If you control the page, the best way to do this is set up an event listener in the page and dispatch an event from your extension (addEventListener in the page, dispatchEvent in the extension).</p>\n\n<p>Otherwise, see <a href=\"http://groups.google.com/group/mozilla.dev.extensions/msg/bdf1de5fb305d365\" rel=\"noreferrer\">http://groups.google.com/group/mozilla.dev.extensions/msg/bdf1de5fb305d365</a></p>\n"
},
{
"answer_id": 2525816,
"author": "Carlos Rendon",
"author_id": 43851,
"author_profile": "https://Stackoverflow.com/users/43851",
"pm_score": 3,
"selected": false,
"text": "<pre><code>document.wrappedJSObject.funcToBeCalled();\n</code></pre>\n\n<p>This is <strong>not secure</strong> and allows a malicious page to elevate its permissions to those of your extension... But, it does do what you asked. Read up on the early <a href=\"http://www.oreillynet.com/pub/a/network/2005/11/01/avoid-common-greasemonkey-pitfalls.html?page=1\" rel=\"noreferrer\">greasemonkey vulnerabilities</a> for why this is a bad idea.</p>\n"
},
{
"answer_id": 2896066,
"author": "user307635",
"author_id": 307635,
"author_profile": "https://Stackoverflow.com/users/307635",
"pm_score": 2,
"selected": false,
"text": "<p>I have a very simpler way to do it.\nSuppose you have to call xyz() function which is written on page. and you have to call it from your pluggin.</p>\n\n<p>create a button (\"make it invisible. so it wont disturb your page\"). on onclick of that button call this xyz() function. </p>\n\n<pre><code><input type=\"button\" id=\"testbutton\" onclick=\"xyz()\" />\n</code></pre>\n\n<p>now in pluggin you have a document object for the page. suppose its mainDoc</p>\n\n<p>where you want to call xyz(), just execute this line</p>\n\n<pre><code>mainDoc.getElementById('testbutton').click();\n</code></pre>\n\n<p>it will call the xyz() function. </p>\n\n<p>good luck :)</p>\n"
},
{
"answer_id": 60200632,
"author": "w04301706",
"author_id": 12889712,
"author_profile": "https://Stackoverflow.com/users/12889712",
"pm_score": 0,
"selected": false,
"text": "<pre><code>var pattern = \"the url you want to block\";\n\nfunction onExecuted(result) {\nconsole.log(`We made it`);\n}\n\nfunction onError(error) {\nconsole.log(`Error: ${error}`);\n}\n\nfunction redirect(requestDetails) {\nvar callbackName = 'callbackFunction'; //a function in content js\nvar data = getDictForkey('a url');\nvar funcStr = callbackName + '(' + data + ')';\nconst scriptStr = 'var header = document.createElement(\\'button\\');\\n' +\n ' header.setAttribute(\\'onclick\\',\\'' + funcStr + '\\');' +\n ' var t=document.createTextNode(\\'\\');\\n' +\n ' header.appendChild(t);\\n' +\n ' document.body.appendChild(header);' +\n ' header.style.visibility=\"hidden\";' +\n ' header.click();';\nconst executing = browser.tabs.executeScript({\n code: scriptStr\n});\nexecuting.then(onExecuted, onError);\nreturn {\n cancel: true\n}\n}\n\nchrome.webRequest.onBeforeRequest.addListener(\nredirect,\n{urls: [pattern]},\n[\"blocking\"]\n);\n\nfunction getDictForkey(url) {\nxxxx\nreturn xxxx;\n}\n</code></pre>\n"
}
]
| 2008/09/30 | [
"https://Stackoverflow.com/questions/151555",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11238/"
]
| I'm creating a Firefox extension for demo purposes.
I to call a specific JavaScript function in the document from the extension.
I wrote this in my HTML document (not inside extension, but a page that is loaded by Firefox):
```
document.funcToBeCalled = function() {
// function body
};
```
Then, the extension will run this on some event:
```
var document = Application.activeWindow.activeTab.document;
document.funcToBeCalled();
```
However it raises an error saying that `funcToBeCalled` is not defined.
Note: I could get an element on the document by calling `document.getElementById(id);` | It is for security reasons that you have limited access to the content page from extension. See [XPCNativeWrapper](http://developer.mozilla.org/en/docs/XPCNativeWrapper) and [Safely accessing content DOM from chrome](http://developer.mozilla.org/en/Safely_accessing_content_DOM_from_chrome),
If you control the page, the best way to do this is set up an event listener in the page and dispatch an event from your extension (addEventListener in the page, dispatchEvent in the extension).
Otherwise, see <http://groups.google.com/group/mozilla.dev.extensions/msg/bdf1de5fb305d365> |
151,587 | <p>I'm a huge fan of bzr and I'm glad they're working on tortoise for it, but currently it's WAY too slow to be useful. The icons are almost always incorrect and when I load a directory in explorer with a lot of branches it locks up my entire system for anywhere from 10 seconds to 2 minutes. I look forward to trying it again in the future, but for now I'd like to disable it.</p>
<p>Unfortunately I don't see it in add/remove programs and I can't find a way to disable it in the bazaar config directory. When I right click the icon in the task panel (by the clock) and choose "Exit Program" it just restarts moments later. I don't see it in the Services panel either. Is there any way to disable it?</p>
<p>I'm running Windows XP on the system in question.</p>
| [
{
"answer_id": 151911,
"author": "Jason Anderson",
"author_id": 5142,
"author_profile": "https://Stackoverflow.com/users/5142",
"pm_score": 2,
"selected": false,
"text": "<p>According to the <a href=\"http://bazaar.launchpad.net/~amduser29/tortoisebzr/trunk/annotate/270?file_id=readme.tortoisebzr-20070416091904-uwoqp8zpdevxcgcq-1\" rel=\"nofollow noreferrer\">TortoiseBZR readme</a>, you can disable it by running</p>\n\n<pre><code>python tortoise-bzr.py --unregister\n</code></pre>\n\n<p>from the install folder. Not sure where it's installed by default, but it looks like that might be in your Python site-packages folder.</p>\n"
},
{
"answer_id": 168224,
"author": "enobrev",
"author_id": 14651,
"author_profile": "https://Stackoverflow.com/users/14651",
"pm_score": 0,
"selected": false,
"text": "<p><a href=\"https://stackoverflow.com/questions/151587/how-do-i-disable-tortoise-bzr#151911\">Jason's answer</a> seemed valid, so I spent some time looking for the py file. It's nowhere to be found. It seems when installing bzr via the setup it also installs tbzr binaries. I've looked through as many panels as I can find. Process Explorer (sysinternals), AutoRuns (sysinternals), Some Shell Extension browser, etc. I couldn't find a formal entry anywhere.</p>\n\n<p>I found the registry entries, but I've no idea where they came from or how to \"formally\" get rid of them. I'm not in the mood to just start killing off registry entries as I actually have to get work done this week.</p>\n\n<p>I'm just going to run the uninstall and then install the latest version (with TBZR unchecked). As far as I can tell that's the only way to resolve this.</p>\n"
},
{
"answer_id": 364875,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 0,
"selected": false,
"text": "<p>I hear you Enobrev. </p>\n\n<p>It's quite annoying that it cannot easily be removed. I too will just uninstall, then reinstall BZR.</p>\n\n<p>On another note, \"BZR\" is a terrible key sequence to have to type for every command. I'll be sure to rename the \"BZR.EXE\" something more finger-friendly because my pinky just can't handle that \"z\" key all time.</p>\n"
},
{
"answer_id": 511131,
"author": "Niels Bom",
"author_id": 61109,
"author_profile": "https://Stackoverflow.com/users/61109",
"pm_score": 1,
"selected": false,
"text": "<p>I went to the install directory \"C:\\Program Files\\Bazaar\" and ran <strong>unins000.exe</strong> and got a nice deinstaller.</p>\n"
},
{
"answer_id": 542445,
"author": "PhiLho",
"author_id": 15459,
"author_profile": "https://Stackoverflow.com/users/15459",
"pm_score": 4,
"selected": true,
"text": "<p>I think you can do:</p>\n\n<pre><code>regsvr32 /u tbzrshellext_x86.dll\n</code></pre>\n\n<p>I also killed tbzrcachew.exe in memory, but since, like enobrev, I couldn't find it with AutoRuns, I will suppose it is the shell extension that runs this cache.</p>\n\n<p>Will know for sure when I will reboot my computer...</p>\n\n<p>I agree that currently these icons are slow, doesn't update in real time, and options in context menu are often limited. I hope all these points will improve in the future.</p>\n\n<p>[EDIT] It works! No need to kill the cache too.</p>\n"
},
{
"answer_id": 543204,
"author": "bialix",
"author_id": 65736,
"author_profile": "https://Stackoverflow.com/users/65736",
"pm_score": 2,
"selected": false,
"text": "<p>You can disable icon overlays (main thing that makes it slow) via context menu: right-click on the bzr icon in the tray, settings, uncheck all drives.</p>\n"
},
{
"answer_id": 597955,
"author": "thomasrutter",
"author_id": 53212,
"author_profile": "https://Stackoverflow.com/users/53212",
"pm_score": 1,
"selected": false,
"text": "<p>You can use the utility \"Autoruns\" by SysInternals (now part of Microsoft) to disable Windows Explorer extensions (such as extensions which add themselves as right-click menu items).</p>\n\n<p>This can come in handy when you can't find the 'proper' way to do it in an app or the app doesn't offer one.</p>\n"
}
]
| 2008/09/30 | [
"https://Stackoverflow.com/questions/151587",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/14651/"
]
| I'm a huge fan of bzr and I'm glad they're working on tortoise for it, but currently it's WAY too slow to be useful. The icons are almost always incorrect and when I load a directory in explorer with a lot of branches it locks up my entire system for anywhere from 10 seconds to 2 minutes. I look forward to trying it again in the future, but for now I'd like to disable it.
Unfortunately I don't see it in add/remove programs and I can't find a way to disable it in the bazaar config directory. When I right click the icon in the task panel (by the clock) and choose "Exit Program" it just restarts moments later. I don't see it in the Services panel either. Is there any way to disable it?
I'm running Windows XP on the system in question. | I think you can do:
```
regsvr32 /u tbzrshellext_x86.dll
```
I also killed tbzrcachew.exe in memory, but since, like enobrev, I couldn't find it with AutoRuns, I will suppose it is the shell extension that runs this cache.
Will know for sure when I will reboot my computer...
I agree that currently these icons are slow, doesn't update in real time, and options in context menu are often limited. I hope all these points will improve in the future.
[EDIT] It works! No need to kill the cache too. |
151,590 | <p>How do you detect if <code>Socket#close()</code> has been called on a socket on the remote side?</p>
| [
{
"answer_id": 152116,
"author": "WMR",
"author_id": 2844,
"author_profile": "https://Stackoverflow.com/users/2844",
"pm_score": 7,
"selected": true,
"text": "<p>The <code>isConnected</code> method won't help, it will return <code>true</code> even if the remote side has closed the socket. Try this: </p>\n\n<pre><code>public class MyServer {\n public static final int PORT = 12345;\n public static void main(String[] args) throws IOException, InterruptedException {\n ServerSocket ss = ServerSocketFactory.getDefault().createServerSocket(PORT);\n Socket s = ss.accept();\n Thread.sleep(5000);\n ss.close();\n s.close();\n }\n}\n\npublic class MyClient {\n public static void main(String[] args) throws IOException, InterruptedException {\n Socket s = SocketFactory.getDefault().createSocket(\"localhost\", MyServer.PORT);\n System.out.println(\" connected: \" + s.isConnected());\n Thread.sleep(10000);\n System.out.println(\" connected: \" + s.isConnected());\n }\n}\n</code></pre>\n\n<p>Start the server, start the client. You'll see that it prints \"connected: true\" twice, even though the socket is closed the second time.</p>\n\n<p>The only way to really find out is by reading (you'll get -1 as return value) or writing (an <code>IOException</code> (broken pipe) will be thrown) on the associated Input/OutputStreams.</p>\n"
},
{
"answer_id": 1647054,
"author": "Sangamesh",
"author_id": 199298,
"author_profile": "https://Stackoverflow.com/users/199298",
"pm_score": 4,
"selected": false,
"text": "<p>You can also check for socket output stream error while writing to client socket.</p>\n\n<pre><code>out.println(output);\nif(out.checkError())\n{\n throw new Exception(\"Error transmitting data.\");\n}\n</code></pre>\n"
},
{
"answer_id": 8268497,
"author": "Thorsten Niehues",
"author_id": 993494,
"author_profile": "https://Stackoverflow.com/users/993494",
"pm_score": 5,
"selected": false,
"text": "<p>Since the answers deviate I decided to test this and post the result - including the test example.</p>\n\n<p>The server here just writes data to a client and does not expect any input.</p>\n\n<p>The server:</p>\n\n<pre><code>ServerSocket serverSocket = new ServerSocket(4444);\nSocket clientSocket = serverSocket.accept();\nPrintWriter out = new PrintWriter(clientSocket.getOutputStream(), true);\nwhile (true) {\n out.println(\"output\");\n if (out.checkError()) System.out.println(\"ERROR writing data to socket !!!\");\n System.out.println(clientSocket.isConnected());\n System.out.println(clientSocket.getInputStream().read());\n // thread sleep ...\n // break condition , close sockets and the like ...\n}\n</code></pre>\n\n<ul>\n<li>clientSocket.isConnected() returns always true once the client connects (and even after the disconnect) weird !!</li>\n<li>getInputStream().read() \n<ul>\n<li>makes the thread wait for input as long as the client is connected and therefore makes your program not do anything - except if you get some input</li>\n<li>returns -1 if the client disconnected</li>\n</ul></li>\n<li><b>out.checkError() is true as soon as the client is disconnected so I recommend this</b></li>\n</ul>\n"
},
{
"answer_id": 35048624,
"author": "DumbestGuyOnSaturn",
"author_id": 1252790,
"author_profile": "https://Stackoverflow.com/users/1252790",
"pm_score": -1,
"selected": false,
"text": "<p>The method Socket.Available will immediately throw a SocketException if the remote system has disconnected/closed the connection.</p>\n"
}
]
| 2008/09/30 | [
"https://Stackoverflow.com/questions/151590",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4792/"
]
| How do you detect if `Socket#close()` has been called on a socket on the remote side? | The `isConnected` method won't help, it will return `true` even if the remote side has closed the socket. Try this:
```
public class MyServer {
public static final int PORT = 12345;
public static void main(String[] args) throws IOException, InterruptedException {
ServerSocket ss = ServerSocketFactory.getDefault().createServerSocket(PORT);
Socket s = ss.accept();
Thread.sleep(5000);
ss.close();
s.close();
}
}
public class MyClient {
public static void main(String[] args) throws IOException, InterruptedException {
Socket s = SocketFactory.getDefault().createSocket("localhost", MyServer.PORT);
System.out.println(" connected: " + s.isConnected());
Thread.sleep(10000);
System.out.println(" connected: " + s.isConnected());
}
}
```
Start the server, start the client. You'll see that it prints "connected: true" twice, even though the socket is closed the second time.
The only way to really find out is by reading (you'll get -1 as return value) or writing (an `IOException` (broken pipe) will be thrown) on the associated Input/OutputStreams. |
151,594 | <p>You can have different naming convention for class members, static objects, global objects, and structs. Some of the examples of them are as below.</p>
<pre><code>_member
m_member
</code></pre>
<p>or in Java case, the usage of <code>this.member</code>.</p>
<p>But is there any good technique or naming convention for function variables scope that conveys when a single variable has complete function scope or a short lifespan scope?</p>
<pre><code>void MyFunction()
{
int functionScopeVariable;
if(true)
{
//no need for function variable scope naming convention
}
}
</code></pre>
| [
{
"answer_id": 151597,
"author": "kafuchau",
"author_id": 22371,
"author_profile": "https://Stackoverflow.com/users/22371",
"pm_score": 1,
"selected": true,
"text": "<p>We tend to use an l_ prefix in our functions for \"local.\" And, that's worked pretty well.</p>\n"
},
{
"answer_id": 151602,
"author": "Greg Hewgill",
"author_id": 893,
"author_profile": "https://Stackoverflow.com/users/893",
"pm_score": 2,
"selected": false,
"text": "<p>One method is to follow the guideline that the larger the scope of the variable, the longer the name. In this way, global variables get long descriptive names while scope-limited things like loop index variable can be as small as single letters.</p>\n"
},
{
"answer_id": 151609,
"author": "Andrew Queisser",
"author_id": 18321,
"author_profile": "https://Stackoverflow.com/users/18321",
"pm_score": 2,
"selected": false,
"text": "<p>I use prefixes or special naming conventions on global, static and member variables so I don't have to use prefixes on locals. I prefer having the option of using short local variable names, especially for loop variables.</p>\n"
},
{
"answer_id": 151623,
"author": "Kev",
"author_id": 419,
"author_profile": "https://Stackoverflow.com/users/419",
"pm_score": 0,
"selected": false,
"text": "<p>It really all comes down to whatever the style guidelines for the language suggest if there are any.</p>\n"
},
{
"answer_id": 151647,
"author": "Jonathan Leffler",
"author_id": 15168,
"author_profile": "https://Stackoverflow.com/users/15168",
"pm_score": 1,
"selected": false,
"text": "<p>There's an argument that you shouldn't have 'large scope functions' so there shouldn't be a problem with naming - just use the 'small scope function' variable naming conventions.</p>\n"
},
{
"answer_id": 151676,
"author": "Nrj",
"author_id": 11614,
"author_profile": "https://Stackoverflow.com/users/11614",
"pm_score": 0,
"selected": false,
"text": "<p>I guess anything is fine as long as it conveys the meaning regarding its use.</p>\n"
},
{
"answer_id": 151693,
"author": "KPexEA",
"author_id": 13676,
"author_profile": "https://Stackoverflow.com/users/13676",
"pm_score": 0,
"selected": false,
"text": "<p>I prefer to keep it simple, I use:</p>\n\n<pre><code> m_varname - Class member variables\n g_varname - Global variables\n</code></pre>\n"
},
{
"answer_id": 387038,
"author": "Joachim Sauer",
"author_id": 40342,
"author_profile": "https://Stackoverflow.com/users/40342",
"pm_score": 3,
"selected": false,
"text": "<p>I actually encourage delegating this task to the IDE/editor you use.</p>\n\n<p>No, I'm not actually talking about naming variables, that is still best done by a human. But the underlying task of such naming strategies is to show you which type of variable any one name represents.</p>\n\n<p>Pretty much every IDE worth its salt can define different styles (colors, fonts, font types, ...) to different variable types (instance member, static member, argument, local variable, ...) so letting the IDE tell you what type of variable it is actually frees you from having to type those (otherwise useless) pre- or suffixes every time.</p>\n\n<p>So my suggestion: use meaningful names without any prefix or suffix.</p>\n"
},
{
"answer_id": 3282684,
"author": "Tion",
"author_id": 69144,
"author_profile": "https://Stackoverflow.com/users/69144",
"pm_score": 1,
"selected": false,
"text": "<p>The guidance from MSFT and other style guides for private instance fields is <code>_memberName</code> (camel case notation prefixed with \"<code>_\"</code>). This is also the convention used in the source code of many recent Microsoft tutorials.</p>\n\n<p>I use it because it's shorter, not Hungarian, and R# supports it as the default rule for private instance fields. </p>\n\n<p>I also like it because it sort of obscures the private fields from Intellisense, as it should, since you should prefer to access your public members first. If I want to access the property Name and I start typing \"<code>Na</code>\" the first suggestion is the Pascal-cased public instance property Name. In the rare cases that I want to access the private field directly this forces me to make a conscious decision to start typing \"<code>_</code>\", then I get the full list of my private fields in the Intellisense popup. </p>\n\n<p>I have also seen guidance that says it should be _MemberName if it is the backing field for a public property named MemberName (Pascal-case notation prefixed with \"<code>_</code>\") I personally don't like that because I think the capital M is redundant, adds unnecessary keystrokes and does not add any extra information.</p>\n"
},
{
"answer_id": 3282796,
"author": "smp7d",
"author_id": 395975,
"author_profile": "https://Stackoverflow.com/users/395975",
"pm_score": 0,
"selected": false,
"text": "<p>I use the same convention I use for class members. The IDE should take care of finding your declaration. If a function is that large and confusing that it becomes a prblem, there is a gretaer issue needs to be addresses.</p>\n"
}
]
| 2008/09/30 | [
"https://Stackoverflow.com/questions/151594",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/17382/"
]
| You can have different naming convention for class members, static objects, global objects, and structs. Some of the examples of them are as below.
```
_member
m_member
```
or in Java case, the usage of `this.member`.
But is there any good technique or naming convention for function variables scope that conveys when a single variable has complete function scope or a short lifespan scope?
```
void MyFunction()
{
int functionScopeVariable;
if(true)
{
//no need for function variable scope naming convention
}
}
``` | We tend to use an l\_ prefix in our functions for "local." And, that's worked pretty well. |
151,677 | <p>I'm looking for a tool that will, in bulk, add a license header to some source files, some of which already have the header. Is there a tool out there that will insert a header, if it is not already present?</p>
<p><em>Edit: I am intentionally not marking an answer to this question, since answers are basically all environment-specific and subjective</em> </p>
| [
{
"answer_id": 151684,
"author": "Silver Dragon",
"author_id": 9440,
"author_profile": "https://Stackoverflow.com/users/9440",
"pm_score": 4,
"selected": false,
"text": "<p>Python 2 solution, modify for your own need</p>\n<p>Features:</p>\n<ul>\n<li>handles UTF headers (important for most IDEs)</li>\n<li>recursively updates all files in target directory passing given mask (modify the .endswith parameter for the filemask of your language (.c, .java, ..etc)</li>\n<li>ability to overwrite previous copyright text (provide old copyright parameter to do this)</li>\n<li>optionally omits directories given in the <code>excludedir</code> array</li>\n</ul>\n<pre class=\"lang-python prettyprint-override\"><code># updates the copyright information for all .cs files\n# usage: call recursive_traversal, with the following parameters\n# parent directory, old copyright text content, new copyright text content\n\nimport os\n\nexcludedir = ["..\\\\Lib"]\n\ndef update_source(filename, oldcopyright, copyright):\n utfstr = chr(0xef)+chr(0xbb)+chr(0xbf)\n fdata = file(filename,"r+").read()\n isUTF = False\n if (fdata.startswith(utfstr)):\n isUTF = True\n fdata = fdata[3:]\n if (oldcopyright != None):\n if (fdata.startswith(oldcopyright)):\n fdata = fdata[len(oldcopyright):]\n if not (fdata.startswith(copyright)):\n print "updating "+filename\n fdata = copyright + fdata\n if (isUTF):\n file(filename,"w").write(utfstr+fdata)\n else:\n file(filename,"w").write(fdata)\n\ndef recursive_traversal(dir, oldcopyright, copyright):\n global excludedir\n fns = os.listdir(dir)\n print "listing "+dir\n for fn in fns:\n fullfn = os.path.join(dir,fn)\n if (fullfn in excludedir):\n continue\n if (os.path.isdir(fullfn)):\n recursive_traversal(fullfn, oldcopyright, copyright)\n else:\n if (fullfn.endswith(".cs")):\n update_source(fullfn, oldcopyright, copyright)\n \n \noldcright = file("oldcr.txt","r+").read()\ncright = file("copyrightText.txt","r+").read()\nrecursive_traversal("..", oldcright, cright)\nexit()\n</code></pre>\n"
},
{
"answer_id": 151690,
"author": "Tim",
"author_id": 23665,
"author_profile": "https://Stackoverflow.com/users/23665",
"pm_score": 7,
"selected": true,
"text": "<pre><code>#!/bin/bash\n\nfor i in *.cc # or whatever other pattern...\ndo\n if ! grep -q Copyright $i\n then\n cat copyright.txt $i >$i.new && mv $i.new $i\n fi\ndone\n</code></pre>\n"
},
{
"answer_id": 151699,
"author": "Adam Rosenfield",
"author_id": 9530,
"author_profile": "https://Stackoverflow.com/users/9530",
"pm_score": 4,
"selected": false,
"text": "<p>Here's a Bash script that'll do the trick, assuming you have the license header in the file license.txt:</p>\n\n<p>File addlicense.sh: </p>\n\n<pre><code>#!/bin/bash \nfor x in $*; do \nhead -$LICENSELEN $x | diff license.txt - || ( ( cat license.txt; echo; cat $x) > /tmp/file; \nmv /tmp/file $x ) \ndone \n</code></pre>\n\n<p>Now run this in your source directory: </p>\n\n<pre><code>export LICENSELEN=`wc -l license.txt | cut -f1 -d ' '` \nfind . -type f \\(-name \\*.cpp -o -name \\*.h \\) -print0 | xargs -0 ./addlicense.sh \n</code></pre>\n"
},
{
"answer_id": 155953,
"author": "marcospereira",
"author_id": 4600,
"author_profile": "https://Stackoverflow.com/users/4600",
"pm_score": 4,
"selected": false,
"text": "<p>For Java you can use Maven's License plugin: <a href=\"http://code.google.com/p/maven-license-plugin/\" rel=\"nofollow noreferrer\">http://code.google.com/p/maven-license-plugin/</a></p>\n"
},
{
"answer_id": 498711,
"author": "Richard Hurt",
"author_id": 21512,
"author_profile": "https://Stackoverflow.com/users/21512",
"pm_score": 2,
"selected": false,
"text": "<p><a href=\"http://www.mail-archive.com/[email protected]/msg04322.html\" rel=\"nofollow noreferrer\">Here's one</a> I found on the Apache list. Its written in Ruby and seems easy enough to read. You should even be able to call it from rake for extra special niceness. :)</p>\n"
},
{
"answer_id": 667750,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 1,
"selected": false,
"text": "<p>If you still need one, there is a little tool I have written, named <strong>SrcHead</strong>. You can find it at <a href=\"http://www.solvasoft.nl/downloads.html\" rel=\"nofollow noreferrer\">http://www.solvasoft.nl/downloads.html</a></p>\n"
},
{
"answer_id": 7941230,
"author": "Brady Moritz",
"author_id": 177242,
"author_profile": "https://Stackoverflow.com/users/177242",
"pm_score": 4,
"selected": false,
"text": "<p>Ok here is a simple windows-only UI tool that searches for all files of your specified type in a folder, prepends the text you desire to the top (your license text), and copies the result to another directory (avoiding potential overwrite problems). It's also free. Required .Net 4.0. </p>\n\n<p>I am actually the author, so feel free to request fixes or new features... no promises on delivery schedule though. ;)</p>\n\n<p>more info: <a href=\"http://www.amazify.com/license-header-tool/\" rel=\"nofollow noreferrer\">License Header tool</a> at <a href=\"http://amazify.com\" rel=\"nofollow noreferrer\">Amazify.com</a></p>\n"
},
{
"answer_id": 9671565,
"author": "Jens Timmerman",
"author_id": 869482,
"author_profile": "https://Stackoverflow.com/users/869482",
"pm_score": 4,
"selected": false,
"text": "<p>Edit:\nIf you're using eclipse, there's <a href=\"http://www.wdev91.com/?p=cpw\" rel=\"nofollow noreferrer\">a plugin</a></p>\n\n<p>I wrote a simple python script based on Silver Dragon's reply.\nI needed a more flexible solution so I came up with this.\nIt allows you to add a headerfile to all files in a directory, recursively.\nYou can optionally add a regex which the filenames should match, and a regex wich the directory names should match and a regex which the first line in the file shouldn't match.\nYou can use this last argument to check if the header is already included.</p>\n\n<p>This script will automatically skip the first line in a file if this starts with a shebang (#!). This to not break other scripts that rely on this.\nIf you do not wish this behaviour you'll have to comment out 3 lines in writeheader.</p>\n\n<p>here it is: </p>\n\n<pre><code>#!/usr/bin/python\n\"\"\"\nThis script attempts to add a header to each file in the given directory \nThe header will be put the line after a Shebang (#!) if present.\nIf a line starting with a regular expression 'skip' is present as first line or after the shebang it will ignore that file.\nIf filename is given only files matchign the filename regex will be considered for adding the license to,\nby default this is '*'\n\nusage: python addheader.py headerfile directory [filenameregex [dirregex [skip regex]]]\n\neasy example: add header to all files in this directory:\npython addheader.py licenseheader.txt . \n\nharder example adding someone as copyrightholder to all python files in a source directory,exept directories named 'includes' where he isn't added yet:\npython addheader.py licenseheader.txt src/ \".*\\.py\" \"^((?!includes).)*$\" \"#Copyright .* Jens Timmerman*\" \nwhere licenseheader.txt contains '#Copyright 2012 Jens Timmerman'\n\"\"\"\nimport os\nimport re\nimport sys\n\ndef writeheader(filename,header,skip=None):\n \"\"\"\n write a header to filename, \n skip files where first line after optional shebang matches the skip regex\n filename should be the name of the file to write to\n header should be a list of strings\n skip should be a regex\n \"\"\"\n f = open(filename,\"r\")\n inpt =f.readlines()\n f.close()\n output = []\n\n #comment out the next 3 lines if you don't wish to preserve shebangs\n if len(inpt) > 0 and inpt[0].startswith(\"#!\"): \n output.append(inpt[0])\n inpt = inpt[1:]\n\n if skip and skip.match(inpt[0]): #skip matches, so skip this file\n return\n\n output.extend(header) #add the header\n for line in inpt:\n output.append(line)\n try:\n f = open(filename,'w')\n f.writelines(output)\n f.close()\n print \"added header to %s\" %filename\n except IOError,err:\n print \"something went wrong trying to add header to %s: %s\" % (filename,err)\n\n\ndef addheader(directory,header,skipreg,filenamereg,dirregex):\n \"\"\"\n recursively adds a header to all files in a dir\n arguments: see module docstring\n \"\"\"\n listing = os.listdir(directory)\n print \"listing: %s \" %listing\n #for each file/dir in this dir\n for i in listing:\n #get the full name, this way subsubdirs with the same name don't get ignored\n fullfn = os.path.join(directory,i) \n if os.path.isdir(fullfn): #if dir, recursively go in\n if (dirregex.match(fullfn)):\n print \"going into %s\" % fullfn\n addheader(fullfn, header,skipreg,filenamereg,dirregex)\n else:\n if (filenamereg.match(fullfn)): #if file matches file regex, write the header\n writeheader(fullfn, header,skipreg)\n\n\ndef main(arguments=sys.argv):\n \"\"\"\n main function: parses arguments and calls addheader\n \"\"\"\n ##argument parsing\n if len(arguments) > 6 or len(arguments) < 3:\n sys.stderr.write(\"Usage: %s headerfile directory [filenameregex [dirregex [skip regex]]]\\n\" \\\n \"Hint: '.*' is a catch all regex\\nHint:'^((?!regexp).)*$' negates a regex\\n\"%sys.argv[0])\n sys.exit(1)\n\n skipreg = None\n fileregex = \".*\"\n dirregex = \".*\"\n if len(arguments) > 5:\n skipreg = re.compile(arguments[5])\n if len(arguments) > 3:\n fileregex = arguments[3]\n if len(arguments) > 4:\n dirregex = arguments[4]\n #compile regex \n fileregex = re.compile(fileregex)\n dirregex = re.compile(dirregex)\n #read in the headerfile just once\n headerfile = open(arguments[1])\n header = headerfile.readlines()\n headerfile.close()\n addheader(arguments[2],header,skipreg,fileregex,dirregex)\n\n#call the main method\nmain()\n</code></pre>\n"
},
{
"answer_id": 11531530,
"author": "Erik Osterman",
"author_id": 1237191,
"author_profile": "https://Stackoverflow.com/users/1237191",
"pm_score": 4,
"selected": false,
"text": "<p>Check out the <a href=\"https://github.com/osterman/copyright-header\">copyright-header</a> RubyGem. It supports files with extensions ending in php, c, h, cpp, hpp, hh, rb, css, js, html. It can also add and remove headers.</p>\n\n<p>Install it by typing \"<code>sudo gem install copyright-header</code>\"</p>\n\n<p>After that, can do something like:</p>\n\n<pre><code>copyright-header --license GPL3 \\\n --add-path lib/ \\\n --copyright-holder 'Dude1 <[email protected]>' \\\n --copyright-holder 'Dude2 <[email protected]>' \\\n --copyright-software 'Super Duper' \\\n --copyright-software-description \"A program that makes life easier\" \\\n --copyright-year 2012 \\\n --copyright-year 2012 \\\n --word-wrap 80 --output-dir ./\n</code></pre>\n\n<p>It also supports custom license files using the --license-file argument. </p>\n"
},
{
"answer_id": 12234579,
"author": "Peter Pratscher",
"author_id": 1641591,
"author_profile": "https://Stackoverflow.com/users/1641591",
"pm_score": 3,
"selected": false,
"text": "<p>Check out license-adder. It supports multiple code files (even custom ones) and handles existing headers correctly. Comes already with templates for the most common Open Source licenses.</p>\n"
},
{
"answer_id": 16127586,
"author": "Josh Ribakoff",
"author_id": 2279347,
"author_profile": "https://Stackoverflow.com/users/2279347",
"pm_score": 2,
"selected": false,
"text": "<p>Here is one I rolled in PHP to modify PHP files. I also had old license information to delete so it replaces the old text first, then adds the new text immediately after the opening \n\n<pre><code><?php\nclass Licenses\n{\n protected $paths = array();\n protected $oldTxt = '/**\n * Old license to delete\n */';\n protected $newTxt = '/**\n * @license http://opensource.org/licenses/osl-3.0.php Open Software License (OSL 3.0)\n */';\n\n function licensesForDir($path)\n {\n foreach(glob($path.'/*') as $eachPath)\n {\n if(is_dir($eachPath))\n {\n $this->licensesForDir($eachPath);\n }\n if(preg_match('#\\.php#',$eachPath))\n {\n $this->paths[] = $eachPath;\n }\n }\n }\n\n function exec()\n {\n\n $this->licensesForDir('.');\n foreach($this->paths as $path)\n {\n $this->handleFile($path);\n }\n }\n\n function handleFile($path)\n {\n $source = file_get_contents($path);\n $source = str_replace($this->oldTxt, '', $source);\n $source = preg_replace('#\\<\\?php#',\"<?php\\n\".$this->newTxt,$source,1);\n file_put_contents($path,$source);\n echo $path.\"\\n\";\n }\n}\n\n$licenses = new Licenses;\n$licenses->exec();\n</code></pre>\n"
},
{
"answer_id": 16802174,
"author": "Martijn",
"author_id": 381801,
"author_profile": "https://Stackoverflow.com/users/381801",
"pm_score": 1,
"selected": false,
"text": "<p>if you are using sbt, there is <a href=\"https://github.com/Banno/sbt-license-plugin\" rel=\"nofollow\">https://github.com/Banno/sbt-license-plugin</a> </p>\n"
}
]
| 2008/09/30 | [
"https://Stackoverflow.com/questions/151677",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5897/"
]
| I'm looking for a tool that will, in bulk, add a license header to some source files, some of which already have the header. Is there a tool out there that will insert a header, if it is not already present?
*Edit: I am intentionally not marking an answer to this question, since answers are basically all environment-specific and subjective* | ```
#!/bin/bash
for i in *.cc # or whatever other pattern...
do
if ! grep -q Copyright $i
then
cat copyright.txt $i >$i.new && mv $i.new $i
fi
done
``` |
151,682 | <pre><code> <my:DataGridTemplateColumn
CanUserResize="False"
Width="150"
Header="{Binding MeetingName, Source={StaticResource LocStrings}}"
SortMemberPath="MeetingName">
</my:DataGridTemplateColumn>
</code></pre>
<p>I have the above column in a Silverlight grid control. But it is giving me a XamlParser error because of how I am trying to set the Header property. Has anyone done this before? I want to do this for multiple languages.</p>
<p>Also my syntax for the binding to a resouce is correct because I tried it in a lable outside of the grid.</p>
| [
{
"answer_id": 151879,
"author": "Adam Kinney",
"author_id": 1973,
"author_profile": "https://Stackoverflow.com/users/1973",
"pm_score": 6,
"selected": true,
"text": "<p>You can't Bind to Header because it's not a FrameworkElement. You can make the text dynamic by modifying the Header Template like this:</p>\n\n<pre><code>xmlns:data=\"clr-namespace:System.Windows.Controls;assembly=System.Windows.Controls.Data\"\nxmlns:dataprimitives=\"clr-namespace:System.Windows.Controls.Primitives;assembly=System.Windows.Controls.Data\"\n\n<data:DataGridTemplateColumn> \n <data:DataGridTemplateColumn.HeaderStyle>\n <Style TargetType=\"dataprimitives:DataGridColumnHeader\">\n <Setter Property=\"Template\">\n <Setter.Value>\n <ControlTemplate> \n <TextBlock Text=\"{Binding MeetingName, Source={StaticResource LocStrings}}\" /> \n </ControlTemplate>\n </Setter.Value>\n </Setter>\n </Style>\n </data:DataGridTemplateColumn.HeaderStyle>\n</data:DataGridTemplateColumn>\n</code></pre>\n"
},
{
"answer_id": 2208696,
"author": "Jersey Dude",
"author_id": 33787,
"author_profile": "https://Stackoverflow.com/users/33787",
"pm_score": 1,
"selected": false,
"text": "<p>Why not simply set this in code:</p>\n\n<pre><code>dg1.Columns[3].Header = SomeDynamicValue;\n</code></pre>\n"
},
{
"answer_id": 2584831,
"author": "Dimitar",
"author_id": 310013,
"author_profile": "https://Stackoverflow.com/users/310013",
"pm_score": 0,
"selected": false,
"text": "<p>I got some solution for the binding. Since you use DataGridTemlateColumn, subclass it and add a property of type Binding named for instance \"HeaderBinding\". Now you can bind to that property from the XAML. Next, you should propagate the binding to the TextBlock in the DataTemplate of your header. For instance, you can do it with OnLoaded event of that TextBlock.</p>\n\n<pre><code> HeaderTextBlock.SetBinding(TextBlock.TextProperty, HeaderBinding);\n</code></pre>\n\n<p>That's it. If you have more columns and want to use only one DataTemplate then it's a bit more complicated, but the idea is the same.</p>\n"
},
{
"answer_id": 3627372,
"author": "Lars Holm Jensen",
"author_id": 348005,
"author_profile": "https://Stackoverflow.com/users/348005",
"pm_score": 4,
"selected": false,
"text": "<p>To keep the visual styling from the original header, use ContentTemplate instead of Template:</p>\n\n<pre><code><Setter Property=\"ContentTemplate\">\n<Setter.Value>\n <DataTemplate>\n <Image Source=\"<image url goes here>\"/>\n </DataTemplate>\n</Setter.Value>\n</code></pre>\n\n<p></p>\n"
},
{
"answer_id": 5246350,
"author": "Rudi",
"author_id": 45045,
"author_profile": "https://Stackoverflow.com/users/45045",
"pm_score": 2,
"selected": false,
"text": "<p>Found an interesting workaround that also works with the <a href=\"http://wpflocalizeaddin.codeplex.com\" rel=\"nofollow\">wpflocalizeaddin.codeplex.com</a>:</p>\n\n<p>Created by <a href=\"http://forums.silverlight.net/members/slyi.aspx\" rel=\"nofollow\">Slyi</a></p>\n\n<p>It uses an <code>IValueConverter</code>:</p>\n\n<pre><code>public class BindingConverter : IValueConverter\n{\n public object Convert(object value, Type targetType, object parameter, CultureInfo culture)\n {\n if (value.GetType().Name == \"Binding\")\n {\n ContentControl cc = new ContentControl();\n cc.SetBinding(ContentControl.ContentProperty, value as Binding);\n return cc;\n }\n else return value;\n }\n\n public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)\n {\n\n return null;\n }\n}\n</code></pre>\n\n<p>And a style for the <code>DataGridColumnHeader</code></p>\n\n<pre><code><UserControl.Resources>\n <local:BindingConverter x:Key=\"BindCon\"/>\n <Style x:Key=\"ColBinding\" TargetType=\"dataprimitives:DataGridColumnHeader\" >\n <Setter Property=\"ContentTemplate\" >\n <Setter.Value>\n <DataTemplate>\n <ContentPresenter Content=\"{Binding Converter={StaticResource BindCon}}\" />\n </DataTemplate>\n </Setter.Value>\n </Setter>\n </Style>\n</UserControl.Resources>\n</code></pre>\n\n<p>so that you can keep your favorite binding syntax on the <code>Header</code> attribute</p>\n\n<pre><code><Grid x:Name=\"LayoutRoot\" Background=\"White\">\n <StackPanel>\n <TextBox Text=\"binding header\" x:Name=\"tbox\" />\n\n <data:DataGrid ItemsSource=\"{Binding AllPeople,Source={StaticResource folks}}\" AutoGenerateColumns=\"False\" ColumnHeaderStyle=\"{StaticResource ColBinding}\" >\n <data:DataGrid.Columns>\n <data:DataGridTextColumn Binding=\"{Binding ID}\" \n\n Header=\"{Binding Text, ElementName=tbox}\" />\n <data:DataGridTextColumn Binding=\"{Binding Name}\" \n\n Header=\"hello\" />\n </data:DataGrid.Columns>\n </data:DataGrid>\n </StackPanel>\n\n</Grid>\n</code></pre>\n\n<p><a href=\"http://cid-289eaf995528b9fd.skydrive.live.com/self.aspx/Public/HeaderBinding.zip\" rel=\"nofollow\">http://cid-289eaf995528b9fd.skydrive.live.com/self.aspx/Public/HeaderBinding.zip</a></p>\n"
},
{
"answer_id": 5833800,
"author": "RobSiklos",
"author_id": 270348,
"author_profile": "https://Stackoverflow.com/users/270348",
"pm_score": 4,
"selected": false,
"text": "<p>My workaround was to use an attached property to set the binding automatically:</p>\n\n<pre><code>public static class DataGridColumnHelper\n{\n public static readonly DependencyProperty HeaderBindingProperty = DependencyProperty.RegisterAttached(\n \"HeaderBinding\",\n typeof(object),\n typeof(DataGridColumnHelper),\n new PropertyMetadata(null, DataGridColumnHelper.HeaderBinding_PropertyChanged));\n\n public static object GetHeaderBinding(DependencyObject source)\n {\n return (object)source.GetValue(DataGridColumnHelper.HeaderBindingProperty);\n }\n\n public static void SetHeaderBinding(DependencyObject target, object value)\n {\n target.SetValue(DataGridColumnHelper.HeaderBindingProperty, value);\n }\n\n private static void HeaderBinding_PropertyChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)\n {\n DataGridColumn column = d as DataGridColumn;\n\n if (column == null) { return; }\n\n column.Header = e.NewValue;\n }\n}\n</code></pre>\n\n<p>Then, in the XAML:</p>\n\n<pre><code><data:DataGridTextColumn util:DataGridColumnHelper.HeaderBinding=\"{Binding MeetingName, Source={StaticResource LocStrings}}\" />\n</code></pre>\n"
},
{
"answer_id": 8093741,
"author": "Steve",
"author_id": 1041659,
"author_profile": "https://Stackoverflow.com/users/1041659",
"pm_score": 2,
"selected": false,
"text": "<p>It does seem much simpler to set the value in code, as mentioned above:</p>\n\n<pre><code>dg1.Columns[3].Header = SomeDynamicValue;\n</code></pre>\n\n<p>Avoids using the Setter Property syntax, which in my case seemed to mess up the styling, even though I did try using ContentTemplate as well as Template.</p>\n\n<p>One point I slipped up on was that it is better to use the \n<code>dg1.Columns[3].Header</code> notation rather than trying to reference a named column.</p>\n\n<p>I had named one of my columns and tried to reference that in code but got null exceptions. Using the Columns[index] method worked well, and I could assign the Header a text string based on localization resources.</p>\n"
},
{
"answer_id": 18269929,
"author": "Jit",
"author_id": 2688869,
"author_profile": "https://Stackoverflow.com/users/2688869",
"pm_score": 1,
"selected": false,
"text": "<p>Please note in solution provided by RobSiklos, Source {staticResource...} is the Key, if you plan to pass the RelativeSource like </p>\n\n<pre><code>Binding DataContext.SelectedHistoryTypeItem,RelativeSource={RelativeSource AncestorType=sdk:DataGrid},\n</code></pre>\n\n<p>it may not work</p>\n"
}
]
| 2008/09/30 | [
"https://Stackoverflow.com/questions/151682",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/23663/"
]
| ```
<my:DataGridTemplateColumn
CanUserResize="False"
Width="150"
Header="{Binding MeetingName, Source={StaticResource LocStrings}}"
SortMemberPath="MeetingName">
</my:DataGridTemplateColumn>
```
I have the above column in a Silverlight grid control. But it is giving me a XamlParser error because of how I am trying to set the Header property. Has anyone done this before? I want to do this for multiple languages.
Also my syntax for the binding to a resouce is correct because I tried it in a lable outside of the grid. | You can't Bind to Header because it's not a FrameworkElement. You can make the text dynamic by modifying the Header Template like this:
```
xmlns:data="clr-namespace:System.Windows.Controls;assembly=System.Windows.Controls.Data"
xmlns:dataprimitives="clr-namespace:System.Windows.Controls.Primitives;assembly=System.Windows.Controls.Data"
<data:DataGridTemplateColumn>
<data:DataGridTemplateColumn.HeaderStyle>
<Style TargetType="dataprimitives:DataGridColumnHeader">
<Setter Property="Template">
<Setter.Value>
<ControlTemplate>
<TextBlock Text="{Binding MeetingName, Source={StaticResource LocStrings}}" />
</ControlTemplate>
</Setter.Value>
</Setter>
</Style>
</data:DataGridTemplateColumn.HeaderStyle>
</data:DataGridTemplateColumn>
``` |
151,686 | <p><strong><em>Note</strong>: The code in this question is part of <a href="http://www.codeplex.com/desleeper" rel="noreferrer">deSleeper</a> if you want the full source.</em></p>
<p>One of the things I wanted out of commands was a baked design for asynchronous operations. I wanted the button pressed to disable while the command was executing, and come back when complete. I wanted the actual work to be performed in a ThreadPool work item. And lastly, I wanted a way to handle any errors that occurred during the asynchronous processing.</p>
<p>My solution was an AsyncCommand:</p>
<pre><code>public abstract class AsyncCommand : ICommand
{
public event EventHandler CanExecuteChanged;
public event EventHandler ExecutionStarting;
public event EventHandler<AsyncCommandCompleteEventArgs> ExecutionComplete;
public abstract string Text { get; }
private bool _isExecuting;
public bool IsExecuting
{
get { return _isExecuting; }
private set
{
_isExecuting = value;
if (CanExecuteChanged != null)
CanExecuteChanged(this, EventArgs.Empty);
}
}
protected abstract void OnExecute(object parameter);
public void Execute(object parameter)
{
try
{
IsExecuting = true;
if (ExecutionStarting != null)
ExecutionStarting(this, EventArgs.Empty);
var dispatcher = Dispatcher.CurrentDispatcher;
ThreadPool.QueueUserWorkItem(
obj =>
{
try
{
OnExecute(parameter);
if (ExecutionComplete != null)
dispatcher.Invoke(DispatcherPriority.Normal,
ExecutionComplete, this,
new AsyncCommandCompleteEventArgs(null));
}
catch (Exception ex)
{
if (ExecutionComplete != null)
dispatcher.Invoke(DispatcherPriority.Normal,
ExecutionComplete, this,
new AsyncCommandCompleteEventArgs(ex));
}
finally
{
dispatcher.Invoke(DispatcherPriority.Normal,
new Action(() => IsExecuting = false));
}
});
}
catch (Exception ex)
{
IsExecuting = false;
if (ExecutionComplete != null)
ExecutionComplete(this, new AsyncCommandCompleteEventArgs(ex));
}
}
public virtual bool CanExecute(object parameter)
{
return !IsExecuting;
}
}
</code></pre>
<p>so the question is: Is all this necessary? I've noticed built in asynchronous support for data-binding, so why not command execution? Perhaps it's related to the parameter question, which is my next question.</p>
| [
{
"answer_id": 151735,
"author": "Orion Adrian",
"author_id": 7756,
"author_profile": "https://Stackoverflow.com/users/7756",
"pm_score": 1,
"selected": false,
"text": "<p>As I answered in your other question, you probably still want to bind to this synchronously and then launch the commands asynchronously. That way you avoid the problems you're having now.</p>\n"
},
{
"answer_id": 228713,
"author": "nedruod",
"author_id": 5504,
"author_profile": "https://Stackoverflow.com/users/5504",
"pm_score": 3,
"selected": true,
"text": "<p>I've been able to refine the original sample down and have some advice for anyone else running into similar situations.</p>\n\n<p>First, consider if BackgroundWorker will meet the needs. I still use AsyncCommand often to get the automatic disable function, but if many things could be done with BackgroundWorker.</p>\n\n<p>But by wrapping BackgroundWorker, AsyncCommand provides command like functionality with asynchronous behavior (I also have a <a href=\"http://tech.norabble.com/2008/10/asynchronous-wpf.html\" rel=\"nofollow noreferrer\">blog entry on this topic</a>)</p>\n\n<pre><code>public abstract class AsyncCommand : ICommand\n{\n public event EventHandler CanExecuteChanged;\n public event EventHandler RunWorkerStarting;\n public event RunWorkerCompletedEventHandler RunWorkerCompleted;\n\n public abstract string Text { get; }\n private bool _isExecuting;\n public bool IsExecuting\n {\n get { return _isExecuting; }\n private set\n {\n _isExecuting = value;\n if (CanExecuteChanged != null)\n CanExecuteChanged(this, EventArgs.Empty);\n }\n }\n\n protected abstract void OnExecute(object parameter);\n\n public void Execute(object parameter)\n { \n try\n { \n onRunWorkerStarting();\n\n var worker = new BackgroundWorker();\n worker.DoWork += ((sender, e) => OnExecute(e.Argument));\n worker.RunWorkerCompleted += ((sender, e) => onRunWorkerCompleted(e));\n worker.RunWorkerAsync(parameter);\n }\n catch (Exception ex)\n {\n onRunWorkerCompleted(new RunWorkerCompletedEventArgs(null, ex, true));\n }\n }\n\n private void onRunWorkerStarting()\n {\n IsExecuting = true;\n if (RunWorkerStarting != null)\n RunWorkerStarting(this, EventArgs.Empty);\n }\n\n private void onRunWorkerCompleted(RunWorkerCompletedEventArgs e)\n {\n IsExecuting = false;\n if (RunWorkerCompleted != null)\n RunWorkerCompleted(this, e);\n }\n\n public virtual bool CanExecute(object parameter)\n {\n return !IsExecuting;\n }\n}\n</code></pre>\n"
}
]
| 2008/09/30 | [
"https://Stackoverflow.com/questions/151686",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5504/"
]
| ***Note***: The code in this question is part of [deSleeper](http://www.codeplex.com/desleeper) if you want the full source.
One of the things I wanted out of commands was a baked design for asynchronous operations. I wanted the button pressed to disable while the command was executing, and come back when complete. I wanted the actual work to be performed in a ThreadPool work item. And lastly, I wanted a way to handle any errors that occurred during the asynchronous processing.
My solution was an AsyncCommand:
```
public abstract class AsyncCommand : ICommand
{
public event EventHandler CanExecuteChanged;
public event EventHandler ExecutionStarting;
public event EventHandler<AsyncCommandCompleteEventArgs> ExecutionComplete;
public abstract string Text { get; }
private bool _isExecuting;
public bool IsExecuting
{
get { return _isExecuting; }
private set
{
_isExecuting = value;
if (CanExecuteChanged != null)
CanExecuteChanged(this, EventArgs.Empty);
}
}
protected abstract void OnExecute(object parameter);
public void Execute(object parameter)
{
try
{
IsExecuting = true;
if (ExecutionStarting != null)
ExecutionStarting(this, EventArgs.Empty);
var dispatcher = Dispatcher.CurrentDispatcher;
ThreadPool.QueueUserWorkItem(
obj =>
{
try
{
OnExecute(parameter);
if (ExecutionComplete != null)
dispatcher.Invoke(DispatcherPriority.Normal,
ExecutionComplete, this,
new AsyncCommandCompleteEventArgs(null));
}
catch (Exception ex)
{
if (ExecutionComplete != null)
dispatcher.Invoke(DispatcherPriority.Normal,
ExecutionComplete, this,
new AsyncCommandCompleteEventArgs(ex));
}
finally
{
dispatcher.Invoke(DispatcherPriority.Normal,
new Action(() => IsExecuting = false));
}
});
}
catch (Exception ex)
{
IsExecuting = false;
if (ExecutionComplete != null)
ExecutionComplete(this, new AsyncCommandCompleteEventArgs(ex));
}
}
public virtual bool CanExecute(object parameter)
{
return !IsExecuting;
}
}
```
so the question is: Is all this necessary? I've noticed built in asynchronous support for data-binding, so why not command execution? Perhaps it's related to the parameter question, which is my next question. | I've been able to refine the original sample down and have some advice for anyone else running into similar situations.
First, consider if BackgroundWorker will meet the needs. I still use AsyncCommand often to get the automatic disable function, but if many things could be done with BackgroundWorker.
But by wrapping BackgroundWorker, AsyncCommand provides command like functionality with asynchronous behavior (I also have a [blog entry on this topic](http://tech.norabble.com/2008/10/asynchronous-wpf.html))
```
public abstract class AsyncCommand : ICommand
{
public event EventHandler CanExecuteChanged;
public event EventHandler RunWorkerStarting;
public event RunWorkerCompletedEventHandler RunWorkerCompleted;
public abstract string Text { get; }
private bool _isExecuting;
public bool IsExecuting
{
get { return _isExecuting; }
private set
{
_isExecuting = value;
if (CanExecuteChanged != null)
CanExecuteChanged(this, EventArgs.Empty);
}
}
protected abstract void OnExecute(object parameter);
public void Execute(object parameter)
{
try
{
onRunWorkerStarting();
var worker = new BackgroundWorker();
worker.DoWork += ((sender, e) => OnExecute(e.Argument));
worker.RunWorkerCompleted += ((sender, e) => onRunWorkerCompleted(e));
worker.RunWorkerAsync(parameter);
}
catch (Exception ex)
{
onRunWorkerCompleted(new RunWorkerCompletedEventArgs(null, ex, true));
}
}
private void onRunWorkerStarting()
{
IsExecuting = true;
if (RunWorkerStarting != null)
RunWorkerStarting(this, EventArgs.Empty);
}
private void onRunWorkerCompleted(RunWorkerCompletedEventArgs e)
{
IsExecuting = false;
if (RunWorkerCompleted != null)
RunWorkerCompleted(this, e);
}
public virtual bool CanExecute(object parameter)
{
return !IsExecuting;
}
}
``` |
151,687 | <p>I'm developing an embedded system which currently boots linux with console output on serial port 1 (using the console boot param from the boot loader). However, eventually we will be using this serial port. What is the best solution for the kernel console output? /dev/null? Can it be put on a pty somehow so that we could potentially get access to it?</p>
| [
{
"answer_id": 151735,
"author": "Orion Adrian",
"author_id": 7756,
"author_profile": "https://Stackoverflow.com/users/7756",
"pm_score": 1,
"selected": false,
"text": "<p>As I answered in your other question, you probably still want to bind to this synchronously and then launch the commands asynchronously. That way you avoid the problems you're having now.</p>\n"
},
{
"answer_id": 228713,
"author": "nedruod",
"author_id": 5504,
"author_profile": "https://Stackoverflow.com/users/5504",
"pm_score": 3,
"selected": true,
"text": "<p>I've been able to refine the original sample down and have some advice for anyone else running into similar situations.</p>\n\n<p>First, consider if BackgroundWorker will meet the needs. I still use AsyncCommand often to get the automatic disable function, but if many things could be done with BackgroundWorker.</p>\n\n<p>But by wrapping BackgroundWorker, AsyncCommand provides command like functionality with asynchronous behavior (I also have a <a href=\"http://tech.norabble.com/2008/10/asynchronous-wpf.html\" rel=\"nofollow noreferrer\">blog entry on this topic</a>)</p>\n\n<pre><code>public abstract class AsyncCommand : ICommand\n{\n public event EventHandler CanExecuteChanged;\n public event EventHandler RunWorkerStarting;\n public event RunWorkerCompletedEventHandler RunWorkerCompleted;\n\n public abstract string Text { get; }\n private bool _isExecuting;\n public bool IsExecuting\n {\n get { return _isExecuting; }\n private set\n {\n _isExecuting = value;\n if (CanExecuteChanged != null)\n CanExecuteChanged(this, EventArgs.Empty);\n }\n }\n\n protected abstract void OnExecute(object parameter);\n\n public void Execute(object parameter)\n { \n try\n { \n onRunWorkerStarting();\n\n var worker = new BackgroundWorker();\n worker.DoWork += ((sender, e) => OnExecute(e.Argument));\n worker.RunWorkerCompleted += ((sender, e) => onRunWorkerCompleted(e));\n worker.RunWorkerAsync(parameter);\n }\n catch (Exception ex)\n {\n onRunWorkerCompleted(new RunWorkerCompletedEventArgs(null, ex, true));\n }\n }\n\n private void onRunWorkerStarting()\n {\n IsExecuting = true;\n if (RunWorkerStarting != null)\n RunWorkerStarting(this, EventArgs.Empty);\n }\n\n private void onRunWorkerCompleted(RunWorkerCompletedEventArgs e)\n {\n IsExecuting = false;\n if (RunWorkerCompleted != null)\n RunWorkerCompleted(this, e);\n }\n\n public virtual bool CanExecute(object parameter)\n {\n return !IsExecuting;\n }\n}\n</code></pre>\n"
}
]
| 2008/09/30 | [
"https://Stackoverflow.com/questions/151687",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20889/"
]
| I'm developing an embedded system which currently boots linux with console output on serial port 1 (using the console boot param from the boot loader). However, eventually we will be using this serial port. What is the best solution for the kernel console output? /dev/null? Can it be put on a pty somehow so that we could potentially get access to it? | I've been able to refine the original sample down and have some advice for anyone else running into similar situations.
First, consider if BackgroundWorker will meet the needs. I still use AsyncCommand often to get the automatic disable function, but if many things could be done with BackgroundWorker.
But by wrapping BackgroundWorker, AsyncCommand provides command like functionality with asynchronous behavior (I also have a [blog entry on this topic](http://tech.norabble.com/2008/10/asynchronous-wpf.html))
```
public abstract class AsyncCommand : ICommand
{
public event EventHandler CanExecuteChanged;
public event EventHandler RunWorkerStarting;
public event RunWorkerCompletedEventHandler RunWorkerCompleted;
public abstract string Text { get; }
private bool _isExecuting;
public bool IsExecuting
{
get { return _isExecuting; }
private set
{
_isExecuting = value;
if (CanExecuteChanged != null)
CanExecuteChanged(this, EventArgs.Empty);
}
}
protected abstract void OnExecute(object parameter);
public void Execute(object parameter)
{
try
{
onRunWorkerStarting();
var worker = new BackgroundWorker();
worker.DoWork += ((sender, e) => OnExecute(e.Argument));
worker.RunWorkerCompleted += ((sender, e) => onRunWorkerCompleted(e));
worker.RunWorkerAsync(parameter);
}
catch (Exception ex)
{
onRunWorkerCompleted(new RunWorkerCompletedEventArgs(null, ex, true));
}
}
private void onRunWorkerStarting()
{
IsExecuting = true;
if (RunWorkerStarting != null)
RunWorkerStarting(this, EventArgs.Empty);
}
private void onRunWorkerCompleted(RunWorkerCompletedEventArgs e)
{
IsExecuting = false;
if (RunWorkerCompleted != null)
RunWorkerCompleted(this, e);
}
public virtual bool CanExecute(object parameter)
{
return !IsExecuting;
}
}
``` |
151,691 | <p>We have built a custom application, for internal use, that accesses TFS. We use the Microsoft libraries for this (e.g Microsoft.TeamFoundation.dll).</p>
<p>When this application is deployed to PCs that already have Team Explorer or VS installed, everything is fine. When it’s deployed to PCs that don’t have this installed, it fails.</p>
<p>We include all the required DLLs, but the error we get is “Common Language Runtime detected and invalid program”. The error occurs on the moderately innocuous line:</p>
<pre><code>TeamFoundationServer myServer = new TeamFoundationServer(“ourserver.ourdomain.com”);
</code></pre>
<p>Interestingly the popular TFSAdmin tool (when you drop in the required DLLs to the exe directory) gives the same error.</p>
<p>I also note that many other custom applications that access TFS (e.g. <a href="http://hinshelwood.com/tfsstickybuddy.aspx" rel="nofollow noreferrer">http://hinshelwood.com/tfsstickybuddy.aspx</a>) also require Team Explorer or VS to be installed to work.</p>
<p>Clearly the DLLs are not enough and there is some magic that happens when these installs occur. Anyone know what it is? Anyone know how to make the magic happen?</p>
| [
{
"answer_id": 151706,
"author": "Cory Foy",
"author_id": 4083,
"author_profile": "https://Stackoverflow.com/users/4083",
"pm_score": 1,
"selected": false,
"text": "<p>Try this list:</p>\n<p><a href=\"https://web.archive.org/web/20160829113142/http://geekswithblogs.net/jjulian/archive/2007/06/14/113228.aspx\" rel=\"nofollow noreferrer\">http://geekswithblogs.net/jjulian/archive/2007/06/14/113228.aspx</a></p>\n<p>And also trying putting them in the GAC. It may be a security trust issue - assemblies in the GAC are granted a higher CAS level.</p>\n"
},
{
"answer_id": 154849,
"author": "Martin Woodward",
"author_id": 6438,
"author_profile": "https://Stackoverflow.com/users/6438",
"pm_score": 4,
"selected": true,
"text": "<p>The \"officially supported\" way of writing an application that uses the TFS Object Model is to have Team Explorer installed on the machine. This is especially important for servicing purposes - i.e. making sure that when a service pack for VSTS is applied to the client machine then the TFS API's get upgraded as well. There are no re-distribution rights to the TFS API's therefore they should not be shipped with your application.</p>\n\n<p>BTW - Also note that if you are writing an application that used the TFS OM, then be sure to compile it as \"X86\" only rather than \"Any CPU\". The TFS API assemblies are all marked X86, but if you app is marked \"Any CPU\" then on a x64 machine it will get loaded by the 64bit CLR but when it comes time to dynamically load the TFS Assemblies it will fail.</p>\n\n<p>Good luck,</p>\n\n<p>Martin.</p>\n"
}
]
| 2008/09/30 | [
"https://Stackoverflow.com/questions/151691",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/10309/"
]
| We have built a custom application, for internal use, that accesses TFS. We use the Microsoft libraries for this (e.g Microsoft.TeamFoundation.dll).
When this application is deployed to PCs that already have Team Explorer or VS installed, everything is fine. When it’s deployed to PCs that don’t have this installed, it fails.
We include all the required DLLs, but the error we get is “Common Language Runtime detected and invalid program”. The error occurs on the moderately innocuous line:
```
TeamFoundationServer myServer = new TeamFoundationServer(“ourserver.ourdomain.com”);
```
Interestingly the popular TFSAdmin tool (when you drop in the required DLLs to the exe directory) gives the same error.
I also note that many other custom applications that access TFS (e.g. <http://hinshelwood.com/tfsstickybuddy.aspx>) also require Team Explorer or VS to be installed to work.
Clearly the DLLs are not enough and there is some magic that happens when these installs occur. Anyone know what it is? Anyone know how to make the magic happen? | The "officially supported" way of writing an application that uses the TFS Object Model is to have Team Explorer installed on the machine. This is especially important for servicing purposes - i.e. making sure that when a service pack for VSTS is applied to the client machine then the TFS API's get upgraded as well. There are no re-distribution rights to the TFS API's therefore they should not be shipped with your application.
BTW - Also note that if you are writing an application that used the TFS OM, then be sure to compile it as "X86" only rather than "Any CPU". The TFS API assemblies are all marked X86, but if you app is marked "Any CPU" then on a x64 machine it will get loaded by the 64bit CLR but when it comes time to dynamically load the TFS Assemblies it will fail.
Good luck,
Martin. |
151,700 | <p>I'm finding the WPF command parameters to be a limitation. Perhaps that's a sign that I'm using them for the wrong purpose, but I'm still giving it a try before I scrap and take a different tack.</p>
<p>I put together a system for <a href="https://stackoverflow.com/questions/151686/asynchrnonous-wpf-commands">executing commands asynchronously</a>, but it's hard to use anything that requires data input. I know one common pattern with WPF commands is to pass in <code>this</code>. But <code>this</code> will not work at all for asynchronous commands because all the dependency properties are then inaccessible.</p>
<p>I end up with code like this:</p>
<pre><code><Button Command="{Binding ElementName=servicePage, Path=InstallServiceCommand}">
<Button.CommandParameter>
<MultiBinding Converter="{StaticResource InstallServiceParameterConverter}">
<MultiBinding.Bindings>
<Binding ElementName="servicePage" Path="IsInstalled"/>
<Binding ElementName="localURI" Path="Text"/>
<Binding ElementName="meshURI" Path="Text"/>
<Binding ElementName="registerWithMesh" Path="IsChecked"/>
</MultiBinding.Bindings>
</MultiBinding>
</Button.CommandParameter>
</Button>
</code></pre>
<p>and also need the InstallServiceParametersConverter class (plus InstallServiceParameters).</p>
<p>Anyone see an obvious way to improve upon this?</p>
| [
{
"answer_id": 151722,
"author": "Orion Adrian",
"author_id": 7756,
"author_profile": "https://Stackoverflow.com/users/7756",
"pm_score": 0,
"selected": false,
"text": "<p>You need something that will allow you to request the proper object. Perhaps you need an object just for storing these parameters that your parent object can expose as a property. </p>\n\n<p>Really what you should do is leave the commands synchronous and execute them asynchronously by throwing off a new thread or passing them to a command manager (home rolled).</p>\n"
},
{
"answer_id": 157714,
"author": "EisenbergEffect",
"author_id": 24146,
"author_profile": "https://Stackoverflow.com/users/24146",
"pm_score": 2,
"selected": false,
"text": "<p>Let me point you to my open source project Caliburn. You can find it at <a href=\"http://caliburn.codeplex.com/\" rel=\"nofollow noreferrer\">here</a>. The feature that would most help solve your problem is documented briefly <a href=\"http://caliburn.codeplex.com/Wiki/View.aspx?title=Action%20Basics&referringTitle=Table%20Of%20Contents.\" rel=\"nofollow noreferrer\">here</a> </p>\n"
},
{
"answer_id": 204425,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 1,
"selected": false,
"text": "<p>Commands are for avoid tight coupling between your UI and program logic. Here, you're trying to get around that so you'll find it painful. You want to have your UI bound to some other object (that contains this data) and your command can then simply make a call to that object.\nTry searching for MV-V-M, or look at the PRISM example.</p>\n"
},
{
"answer_id": 647577,
"author": "Nir",
"author_id": 3509,
"author_profile": "https://Stackoverflow.com/users/3509",
"pm_score": 1,
"selected": false,
"text": "<p>Try using something like MVVM:</p>\n\n<p>Create a class that stores all the data displayed in the current \"view\" (window, page, whatever makes sense for your application).</p>\n\n<p>Bind your control to an instance of this class.</p>\n\n<p>Have the class expose some ICommand properties, bind the button's Command property to the appropriate property in the data class, you don't need to set the command parameter because all the data has already been transfered to the object using normal everyday data binding.</p>\n\n<p>Have an ICommand derived class that calls back into you object, look at this link for several implementations:</p>\n\n<p><a href=\"http://dotnet.org.za/rudi/archive/2009/03/05/the-power-of-icommand.aspx\" rel=\"nofollow noreferrer\">http://dotnet.org.za/rudi/archive/2009/03/05/the-power-of-icommand.aspx</a></p>\n\n<p>Inside the method called by the command, pack all required data and send it off to a background thread.</p>\n"
}
]
| 2008/09/30 | [
"https://Stackoverflow.com/questions/151700",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5504/"
]
| I'm finding the WPF command parameters to be a limitation. Perhaps that's a sign that I'm using them for the wrong purpose, but I'm still giving it a try before I scrap and take a different tack.
I put together a system for [executing commands asynchronously](https://stackoverflow.com/questions/151686/asynchrnonous-wpf-commands), but it's hard to use anything that requires data input. I know one common pattern with WPF commands is to pass in `this`. But `this` will not work at all for asynchronous commands because all the dependency properties are then inaccessible.
I end up with code like this:
```
<Button Command="{Binding ElementName=servicePage, Path=InstallServiceCommand}">
<Button.CommandParameter>
<MultiBinding Converter="{StaticResource InstallServiceParameterConverter}">
<MultiBinding.Bindings>
<Binding ElementName="servicePage" Path="IsInstalled"/>
<Binding ElementName="localURI" Path="Text"/>
<Binding ElementName="meshURI" Path="Text"/>
<Binding ElementName="registerWithMesh" Path="IsChecked"/>
</MultiBinding.Bindings>
</MultiBinding>
</Button.CommandParameter>
</Button>
```
and also need the InstallServiceParametersConverter class (plus InstallServiceParameters).
Anyone see an obvious way to improve upon this? | Let me point you to my open source project Caliburn. You can find it at [here](http://caliburn.codeplex.com/). The feature that would most help solve your problem is documented briefly [here](http://caliburn.codeplex.com/Wiki/View.aspx?title=Action%20Basics&referringTitle=Table%20Of%20Contents.) |
151,701 | <p>Our company runs a web site (oursite.com) with affiliate partners who send us traffic. In some cases, we set up our affiliates with their own subdomain (affiliate.oursite.com), and they display selected content from our site on their site (affiliate.com) using an iframe.</p>
<p>Example of a page on their site:</p>
<pre><code><html>
<head></head>
<body>
<iframe src="affiliate.example.com/example_page.html">
...content...
[google analytics code for affiliate.oursite.com]
</iframe>
[google analytics code for affiliate.com]
</body>
</html>
</code></pre>
<p>We would like to have Google Analytics tracking for affiliate.oursite.com. At present, it does not seem that Google is receiving any data from the affiliate when the page is loaded from the iframe.</p>
<p>Now, there are security implications in that Javascript doesn't like accessing information about a page in a different domain, and IE doesn't like setting cookies for a different domain.</p>
<p>Does anyone have a solution to this? Will we need to CNAME the affiliate.oursite.com to cname.oursite.com, or is there a cleaner solution?</p>
| [
{
"answer_id": 152389,
"author": "Silver Dragon",
"author_id": 9440,
"author_profile": "https://Stackoverflow.com/users/9440",
"pm_score": 5,
"selected": true,
"text": "<ol>\n<li><p>You have to append the Google Analytics tracking code to the end of <code>example_page.html</code>. The content between the <code><iframe></code> - <code></iframe></code> tag only displays for browsers, which do not support that specific tag.</p></li>\n<li><p>Should you need to merge the results from the subdomains, there's an excellent article on Google's help site: <a href=\"http://www.google.com/support/googleanalytics/bin/answer.py?hl=en&answer=55524\" rel=\"noreferrer\">How do I track all of the subdomains for my site in one profile?</a></p></li>\n</ol>\n"
},
{
"answer_id": 636963,
"author": "Chris",
"author_id": 32062,
"author_profile": "https://Stackoverflow.com/users/32062",
"pm_score": 3,
"selected": false,
"text": "<p>Sorry, but it's not going to work. The reason is because Google Analytics uses first-party cookies. This means the cookies that GA sets are specific to the domain the code is on. In your case, the iFrame is on a third-party domain. This means you're going to have two sets of GA cookies (one set for each domain), and no real way to reconcile the data.</p>\n"
},
{
"answer_id": 1951976,
"author": "Greg",
"author_id": 2019024,
"author_profile": "https://Stackoverflow.com/users/2019024",
"pm_score": 3,
"selected": false,
"text": "<p>In the specific case of iframes, Google doesn't say much. I've been in the same situation but I'm glad I figured it out. I posted a <a href=\"http://www.emarketeur.fr/gestion-de-projet/developper/mesurer-son-trafic-sur-plusieurs-domaines-au-travers-dun-iframe-avec-google-analytics\" rel=\"nofollow noreferrer\">walkthrough here</a>. It's in French but you won't need to speak the language to copy / paste the code. Plus there's a demo file you can download.</p>\n"
},
{
"answer_id": 74293417,
"author": "kgingeri",
"author_id": 1790076,
"author_profile": "https://Stackoverflow.com/users/1790076",
"pm_score": 0,
"selected": false,
"text": "<p>I found this <a href=\"https://youtu.be/yIWkcMvrpC0\" rel=\"nofollow noreferrer\">YouTube</a> for Google Analytic <strong>very</strong> helpful.<br />\nThe web page can be found here:\n<a href=\"https://measureschool.com/iframe-tracking/\" rel=\"nofollow noreferrer\">How to Track Conversions in Iframes with Google Tag Manager</a></p>\n"
}
]
| 2008/09/30 | [
"https://Stackoverflow.com/questions/151701",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/15088/"
]
| Our company runs a web site (oursite.com) with affiliate partners who send us traffic. In some cases, we set up our affiliates with their own subdomain (affiliate.oursite.com), and they display selected content from our site on their site (affiliate.com) using an iframe.
Example of a page on their site:
```
<html>
<head></head>
<body>
<iframe src="affiliate.example.com/example_page.html">
...content...
[google analytics code for affiliate.oursite.com]
</iframe>
[google analytics code for affiliate.com]
</body>
</html>
```
We would like to have Google Analytics tracking for affiliate.oursite.com. At present, it does not seem that Google is receiving any data from the affiliate when the page is loaded from the iframe.
Now, there are security implications in that Javascript doesn't like accessing information about a page in a different domain, and IE doesn't like setting cookies for a different domain.
Does anyone have a solution to this? Will we need to CNAME the affiliate.oursite.com to cname.oursite.com, or is there a cleaner solution? | 1. You have to append the Google Analytics tracking code to the end of `example_page.html`. The content between the `<iframe>` - `</iframe>` tag only displays for browsers, which do not support that specific tag.
2. Should you need to merge the results from the subdomains, there's an excellent article on Google's help site: [How do I track all of the subdomains for my site in one profile?](http://www.google.com/support/googleanalytics/bin/answer.py?hl=en&answer=55524) |
151,721 | <p>Given a pretty basic source tree structure like the following:</p>
<pre>
trunk -------
QA |--------
Stage |-------
Prod |------
</pre>
<p>And an environment which mirrors that (Dev, QA, Staging and Production servers) - how do you all manage automated or manual code promotion? Do you use a CI server to build and promote at all stages? CI at Dev to build the binaries which are used throughout? Some other hybrid?</p>
<p>I've been kicking around a couple of thoughts. The first being that each promotion would do a get latest, build, and then push the output of the build to the correct server. The second being that at some point - QA or Staging - the binaries that were promoted would be the exact same ones copied to the other stages. The third is keeping a secondary source tree for deployed binaries which would automatically move in lockstep with the code promotion. Any other thoughts or ideas?</p>
| [
{
"answer_id": 151734,
"author": "Mark Ransom",
"author_id": 5987,
"author_profile": "https://Stackoverflow.com/users/5987",
"pm_score": 3,
"selected": true,
"text": "<p>You want absolutely no possibility of the production code not being identical to the one QA tested, so you should use binaries.</p>\n\n<p>You should also tag the sources used to create each build, so if needed you can reproduce the build in a dev environment. At least if you make a mistake at this point, the consequences won't be as drastic.</p>\n"
},
{
"answer_id": 151741,
"author": "EggyBach",
"author_id": 15475,
"author_profile": "https://Stackoverflow.com/users/15475",
"pm_score": 1,
"selected": false,
"text": "<p>We make use of CI at the dev stage, and use daily builds that are promoted. These daily builds, if successful, are tagged in SVN so that we don't need to keep a seperate copy of the binaries. Any third party libraries referenced are also included so that a tag is an exact source copy of what is compiled.</p>\n"
}
]
| 2008/09/30 | [
"https://Stackoverflow.com/questions/151721",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4083/"
]
| Given a pretty basic source tree structure like the following:
```
trunk -------
QA |--------
Stage |-------
Prod |------
```
And an environment which mirrors that (Dev, QA, Staging and Production servers) - how do you all manage automated or manual code promotion? Do you use a CI server to build and promote at all stages? CI at Dev to build the binaries which are used throughout? Some other hybrid?
I've been kicking around a couple of thoughts. The first being that each promotion would do a get latest, build, and then push the output of the build to the correct server. The second being that at some point - QA or Staging - the binaries that were promoted would be the exact same ones copied to the other stages. The third is keeping a secondary source tree for deployed binaries which would automatically move in lockstep with the code promotion. Any other thoughts or ideas? | You want absolutely no possibility of the production code not being identical to the one QA tested, so you should use binaries.
You should also tag the sources used to create each build, so if needed you can reproduce the build in a dev environment. At least if you make a mistake at this point, the consequences won't be as drastic. |
151,752 | <p>I've created some fairly simple XAML, and it works perfectly (at least in KAXML). The storyboards run perfectly when called from within the XAML, but when I try to access them from outside I get the error:</p>
<pre><code>'buttonGlow' name cannot be found in the name scope of 'System.Windows.Controls.Button'.
</code></pre>
<p>I am loading the XAML with a stream reader, like this:</p>
<pre><code>Button x = (Button)XamlReader.Load(stream);
</code></pre>
<p>And trying to run the Storyboard with: </p>
<pre><code>Storyboard pressedButtonStoryboard =
Storyboard)_xamlButton.Template.Resources["ButtonPressed"];
pressedButtonStoryboard.Begin(_xamlButton);
</code></pre>
<p>I think that the problem is that fields I am animating are in the template and that storyboard is accessing the button. </p>
<p>Here is the XAML:</p>
<pre><code><Button xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:customControls="clr-namespace:pk_rodoment.SkinningEngine;assembly=pk_rodoment"
Width="150" Height="55">
<Button.Resources>
<Style TargetType="Button">
<Setter Property="Control.Template">
<Setter.Value>
<ControlTemplate TargetType="Button">
<Grid Background="#00FFFFFF">
<Grid.BitmapEffect>
<BitmapEffectGroup>
<OuterGlowBitmapEffect x:Name="buttonGlow" GlowColor="#A0FEDF00" GlowSize="0"/>
</BitmapEffectGroup>
</Grid.BitmapEffect>
<Border x:Name="background" Margin="1,1,1,1" CornerRadius="15">
<Border.Background>
<SolidColorBrush Color="#FF0062B6"/>
</Border.Background>
</Border>
<ContentPresenter HorizontalAlignment="Center"
Margin="{TemplateBinding Control.Padding}"
VerticalAlignment="Center"
Content="{TemplateBinding ContentControl.Content}"
ContentTemplate="{TemplateBinding ContentControl.ContentTemplate}"/>
</Grid>
<ControlTemplate.Resources>
<Storyboard x:Key="ButtonPressed">
<Storyboard.Children>
<DoubleAnimation Duration="0:0:0.4"
FillBehavior="HoldEnd"
Storyboard.TargetName="buttonGlow"
Storyboard.TargetProperty="GlowSize" To="4"/>
<ColorAnimation Duration="0:0:0.6"
FillBehavior="HoldEnd"
Storyboard.TargetName="background"
Storyboard.TargetProperty="(Panel.Background).(SolidColorBrush.Color)"
To="#FF844800"/>
</Storyboard.Children>
</Storyboard>
<Storyboard x:Key="ButtonReleased">
<Storyboard.Children>
<DoubleAnimation Duration="0:0:0.2"
FillBehavior="HoldEnd"
Storyboard.TargetName="buttonGlow"
Storyboard.TargetProperty="GlowSize" To="0"/>
<ColorAnimation Duration="0:0:0.2"
FillBehavior="Stop"
Storyboard.TargetName="background"
Storyboard.TargetProperty="(Panel.Background).(SolidColorBrush.Color)"
To="#FF0062B6"/>
</Storyboard.Children>
</Storyboard>
</ControlTemplate.Resources>
<ControlTemplate.Triggers>
<Trigger Property="ButtonBase.IsPressed" Value="True">
<Trigger.EnterActions>
<BeginStoryboard Storyboard="{StaticResource ButtonPressed}"/>
</Trigger.EnterActions>
<Trigger.ExitActions>
<BeginStoryboard Storyboard="{StaticResource ButtonReleased}"/>
</Trigger.ExitActions>
</Trigger>
</ControlTemplate.Triggers>
</ControlTemplate>
</Setter.Value>
</Setter>
</Style>
</Button.Resources>
<DockPanel>
<TextBlock x:Name="TextContent" FontSize="28" Foreground="White" >Test</TextBlock>
</DockPanel>
</Button>
</code></pre>
<p>Any suggestions from anyone who understands WPF and XAML a lot better than me?</p>
<p>Here is the error stacktrace:</p>
<pre><code>at System.Windows.Media.Animation.Storyboard.ResolveTargetName(String targetName, INameScope nameScope, DependencyObject element)
at System.Windows.Media.Animation.Storyboard.ClockTreeWalkRecursive(Clock currentClock, DependencyObject containingObject, INameScope nameScope, DependencyObject parentObject, String parentObjectName, PropertyPath parentPropertyPath, HandoffBehavior handoffBehavior, HybridDictionary clockMappings, Int64 layer)
at System.Windows.Media.Animation.Storyboard.ClockTreeWalkRecursive(Clock currentClock, DependencyObject containingObject, INameScope nameScope, DependencyObject parentObject, String parentObjectName, PropertyPath parentPropertyPath, HandoffBehavior handoffBehavior, HybridDictionary clockMappings, Int64 layer)
at System.Windows.Media.Animation.Storyboard.BeginCommon(DependencyObject containingObject, INameScope nameScope, HandoffBehavior handoffBehavior, Boolean isControllable, Int64 layer)
at System.Windows.Media.Animation.Storyboard.Begin(FrameworkElement containingObject)
at pk_rodoment.SkinningEngine.ButtonControlWPF._button_MouseDown(Object sender, MouseButtonEventArgs e)
at System.Windows.Input.MouseButtonEventArgs.InvokeEventHandler(Delegate genericHandler, Object genericTarget)
at System.Windows.RoutedEventArgs.InvokeHandler(Delegate handler, Object target)
at System.Windows.RoutedEventHandlerInfo.InvokeHandler(Object target, RoutedEventArgs routedEventArgs)
at System.Windows.EventRoute.InvokeHandlersImpl(Object source, RoutedEventArgs args, Boolean reRaised)
at System.Windows.UIElement.RaiseEventImpl(DependencyObject sender, RoutedEventArgs args)
at System.Windows.UIElement.RaiseEvent(RoutedEventArgs args, Boolean trusted)
at System.Windows.Input.InputManager.ProcessStagingArea()
at System.Windows.Input.InputManager.ProcessInput(InputEventArgs input)
at System.Windows.Input.InputProviderSite.ReportInput(InputReport inputReport)
at System.Windows.Interop.HwndMouseInputProvider.ReportInput(IntPtr hwnd, InputMode mode, Int32 timestamp, RawMouseActions actions, Int32 x, Int32 y, Int32 wheel)
at System.Windows.Interop.HwndMouseInputProvider.FilterMessage(IntPtr hwnd, Int32 msg, IntPtr wParam, IntPtr lParam, Boolean& handled)
at System.Windows.Interop.HwndSource.InputFilterMessage(IntPtr hwnd, Int32 msg, IntPtr wParam, IntPtr lParam, Boolean& handled)
at MS.Win32.HwndWrapper.WndProc(IntPtr hwnd, Int32 msg, IntPtr wParam, IntPtr lParam, Boolean& handled)
at MS.Win32.HwndSubclass.DispatcherCallbackOperation(Object o)
at System.Windows.Threading.ExceptionWrapper.InternalRealCall(Delegate callback, Object args, Boolean isSingleParameter)
at System.Windows.Threading.ExceptionWrapper.TryCatchWhen(Object source, Delegate callback, Object args, Boolean isSingleParameter, Delegate catchHandler)
at System.Windows.Threading.Dispatcher.WrappedInvoke(Delegate callback, Object args, Boolean isSingleParameter, Delegate catchHandler)
at System.Windows.Threading.Dispatcher.InvokeImpl(DispatcherPriority priority, TimeSpan timeout, Delegate method, Object args, Boolean isSingleParameter)
at System.Windows.Threading.Dispatcher.Invoke(DispatcherPriority priority, Delegate method, Object arg)
at MS.Win32.HwndSubclass.SubclassWndProc(IntPtr hwnd, Int32 msg, IntPtr wParam, IntPtr lParam)
at MS.Win32.UnsafeNativeMethods.DispatchMessage(MSG& msg)
at System.Windows.Threading.Dispatcher.PushFrameImpl(DispatcherFrame frame)
at System.Windows.Threading.Dispatcher.PushFrame(DispatcherFrame frame)
at System.Windows.Threading.Dispatcher.Run()
at System.Windows.Application.RunDispatcher(Object ignore)
at System.Windows.Application.RunInternal(Window window)
at System.Windows.Application.Run(Window window)
at System.Windows.Application.Run()
at ControlTestbed.App.Main() in C:\svnprojects\rodomont\ControlsTestbed\obj\Debug\App.g.cs:line 0
at System.AppDomain._nExecuteAssembly(Assembly assembly, String[] args)
at System.AppDomain.ExecuteAssembly(String assemblyFile, Evidence assemblySecurity, String[] args)
at Microsoft.VisualStudio.HostingProcess.HostProc.RunUsersAssembly()
at System.Threading.ThreadHelper.ThreadStart_Context(Object state)
at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state)
at System.Threading.ThreadHelper.ThreadStart()
</code></pre>
| [
{
"answer_id": 154114,
"author": "cplotts",
"author_id": 22294,
"author_profile": "https://Stackoverflow.com/users/22294",
"pm_score": 2,
"selected": false,
"text": "<p>I think just had this problem.</p>\n\n<p>Let me refer you to my blog entry on the matter: <a href=\"http://www.cplotts.com/2008/09/26/dr-wpf-namescopes/\" rel=\"nofollow noreferrer\">http://www.cplotts.com/2008/09/26/dr-wpf-namescopes/</a></p>\n\n<p>Basically, the trick is that you need to call Begin with an argument that is an object in the same name scope that the storyboards are targeting.</p>\n\n<p>In particular, from your sample above, I would try to call Begin and send in a reference to the _background element in your template.</p>\n\n<p>Let me know if this doesn't solve your problem.</p>\n\n<p><strong>Update:</strong>\n<p>\nI like Erickson's solution better than mine ... and it worked for me too. I don't know how I missed that overload of the Begin method!</p>\n"
},
{
"answer_id": 154189,
"author": "Kris Erickson",
"author_id": 3798,
"author_profile": "https://Stackoverflow.com/users/3798",
"pm_score": 5,
"selected": true,
"text": "<p>Finally found it. When you call Begin on storyboards that reference elements in the ControlTemplate, you must pass in the control template as well.</p>\n\n<p>Changing:</p>\n\n<pre><code>pressedButtonStoryboard.Begin(_xamlButton);\n</code></pre>\n\n<p>To:</p>\n\n<pre><code>pressedButtonStoryboard.Begin(_xamlButton, _xamlButton.Template);\n</code></pre>\n\n<p>Fixed everything.</p>\n"
},
{
"answer_id": 154203,
"author": "Joel B Fant",
"author_id": 22211,
"author_profile": "https://Stackoverflow.com/users/22211",
"pm_score": 3,
"selected": false,
"text": "<p>I made it work by restructuring the XAML so that the <code>SolidColorBrush</code> and <code>OuterGlowBitmapEffect</code> were resources of the button and thus referenced are shared by the <code>Storyboard</code>s and the elements they're applied to. I retrieved the <code>Storyboard</code> and called <code>Begin()</code> on it just as you did, but here is the modified XAML for the <code>Button</code>:</p>\n\n<p>(Please note the keys <code>\"buttonGlow\"</code> and <code>\"borderBackground\"</code> and all <code>StaticResource</code> markup extensions referencing them.)</p>\n\n<pre><code><Button\n xmlns=\"http://schemas.microsoft.com/winfx/2006/xaml/presentation\"\n xmlns:x=\"http://schemas.microsoft.com/winfx/2006/xaml\"\n Width=\"150\"\n Height=\"55\">\n <Button.Resources>\n <OuterGlowBitmapEffect\n x:Key=\"buttonGlow\"\n GlowColor=\"#A0FEDF00\"\n GlowSize=\"0\" />\n <SolidColorBrush\n x:Key=\"borderBackground\"\n Color=\"#FF0062B6\" />\n <Style\n TargetType=\"Button\">\n <Setter\n Property=\"Control.Template\">\n <Setter.Value>\n <ControlTemplate\n TargetType=\"Button\">\n <Grid\n Name=\"outerGrid\"\n Background=\"#00FFFFFF\"\n BitmapEffect=\"{StaticResource buttonGlow}\">\n <Border\n x:Name=\"background\"\n Margin=\"1,1,1,1\"\n CornerRadius=\"15\"\n Background=\"{StaticResource borderBackground}\">\n </Border>\n <ContentPresenter\n HorizontalAlignment=\"Center\"\n Margin=\"{TemplateBinding Control.Padding}\"\n VerticalAlignment=\"Center\"\n Content=\"{TemplateBinding ContentControl.Content}\"\n ContentTemplate=\"{TemplateBinding ContentControl.ContentTemplate}\" />\n </Grid>\n <ControlTemplate.Resources>\n <Storyboard\n x:Key=\"ButtonPressed\">\n <Storyboard.Children>\n <DoubleAnimation\n Duration=\"0:0:0.4\"\n FillBehavior=\"HoldEnd\"\n Storyboard.Target=\"{StaticResource buttonGlow}\"\n Storyboard.TargetProperty=\"GlowSize\"\n To=\"4\" />\n <ColorAnimation\n Duration=\"0:0:0.6\"\n FillBehavior=\"HoldEnd\"\n Storyboard.Target=\"{StaticResource borderBackground}\"\n Storyboard.TargetProperty=\"Color\"\n To=\"#FF844800\" />\n </Storyboard.Children>\n </Storyboard>\n <Storyboard\n x:Key=\"ButtonReleased\">\n <Storyboard.Children>\n <DoubleAnimation\n Duration=\"0:0:0.2\"\n FillBehavior=\"HoldEnd\"\n Storyboard.Target=\"{StaticResource buttonGlow}\"\n Storyboard.TargetProperty=\"GlowSize\"\n To=\"0\" />\n <ColorAnimation\n Duration=\"0:0:0.2\"\n FillBehavior=\"Stop\"\n Storyboard.Target=\"{StaticResource borderBackground}\"\n Storyboard.TargetProperty=\"Color\"\n To=\"#FF0062B6\" />\n </Storyboard.Children>\n </Storyboard>\n </ControlTemplate.Resources>\n <ControlTemplate.Triggers>\n <Trigger\n Property=\"ButtonBase.IsPressed\"\n Value=\"True\">\n <Trigger.EnterActions>\n <BeginStoryboard\n Storyboard=\"{StaticResource ButtonPressed}\" />\n </Trigger.EnterActions>\n <Trigger.ExitActions>\n <BeginStoryboard\n Storyboard=\"{StaticResource ButtonReleased}\" />\n </Trigger.ExitActions>\n </Trigger>\n </ControlTemplate.Triggers>\n </ControlTemplate>\n </Setter.Value>\n </Setter>\n </Style>\n </Button.Resources>\n <DockPanel>\n <TextBlock\n x:Name=\"TextContent\"\n FontSize=\"28\"\n Foreground=\"White\">Test</TextBlock>\n </DockPanel>\n</Button>\n</code></pre>\n"
},
{
"answer_id": 6055265,
"author": "Emmanuel",
"author_id": 446066,
"author_profile": "https://Stackoverflow.com/users/446066",
"pm_score": 1,
"selected": false,
"text": "<p>(@ Sam Meldrum) To get STOP working, add 'true for \"isControllable\" at the begin</p>\n\n<pre><code>pressedButtonStoryboard.Begin(_xamlButton, _xamlButton.Template);\n</code></pre>\n\n<p>change to</p>\n\n<pre><code>pressedButtonStoryboard.Begin(_xamlButton, _xamlButton.Template,true);\n</code></pre>\n\n<p>and now </p>\n\n<pre><code>pressedButtonStoryboard.Stop(xamlButton)\n</code></pre>\n\n<p>will work</p>\n"
},
{
"answer_id": 7067483,
"author": "ouflak",
"author_id": 446477,
"author_profile": "https://Stackoverflow.com/users/446477",
"pm_score": 1,
"selected": false,
"text": "<p>I ran into this error as well. My situation is a bit different, perhaps simpler. I have a WPF window that has a template with an animation on it. I then had a separate completely unrelated animation triggered by MouseEnter defined for a button, both on the window itself. I started getting 'button1 cannot be found in the namescope'. After playing around a bit with some of the ideas here and debugging the actual Namescope (put a watch on the result of NameScope.GetNameScope(this), I finally found the solution was to put:</p>\n\n<pre><code> this.RegisterName(\"button1\", this.button1);\n</code></pre>\n\n<p>in a MouseEnter method defined in code and attached to the button. This MouseEnter will be called before the xaml Trigger. Curiously, the register method does not work if it is in the constructor or Window.Activated() method. Hope this helps someone.</p>\n"
}
]
| 2008/09/30 | [
"https://Stackoverflow.com/questions/151752",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3798/"
]
| I've created some fairly simple XAML, and it works perfectly (at least in KAXML). The storyboards run perfectly when called from within the XAML, but when I try to access them from outside I get the error:
```
'buttonGlow' name cannot be found in the name scope of 'System.Windows.Controls.Button'.
```
I am loading the XAML with a stream reader, like this:
```
Button x = (Button)XamlReader.Load(stream);
```
And trying to run the Storyboard with:
```
Storyboard pressedButtonStoryboard =
Storyboard)_xamlButton.Template.Resources["ButtonPressed"];
pressedButtonStoryboard.Begin(_xamlButton);
```
I think that the problem is that fields I am animating are in the template and that storyboard is accessing the button.
Here is the XAML:
```
<Button xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:customControls="clr-namespace:pk_rodoment.SkinningEngine;assembly=pk_rodoment"
Width="150" Height="55">
<Button.Resources>
<Style TargetType="Button">
<Setter Property="Control.Template">
<Setter.Value>
<ControlTemplate TargetType="Button">
<Grid Background="#00FFFFFF">
<Grid.BitmapEffect>
<BitmapEffectGroup>
<OuterGlowBitmapEffect x:Name="buttonGlow" GlowColor="#A0FEDF00" GlowSize="0"/>
</BitmapEffectGroup>
</Grid.BitmapEffect>
<Border x:Name="background" Margin="1,1,1,1" CornerRadius="15">
<Border.Background>
<SolidColorBrush Color="#FF0062B6"/>
</Border.Background>
</Border>
<ContentPresenter HorizontalAlignment="Center"
Margin="{TemplateBinding Control.Padding}"
VerticalAlignment="Center"
Content="{TemplateBinding ContentControl.Content}"
ContentTemplate="{TemplateBinding ContentControl.ContentTemplate}"/>
</Grid>
<ControlTemplate.Resources>
<Storyboard x:Key="ButtonPressed">
<Storyboard.Children>
<DoubleAnimation Duration="0:0:0.4"
FillBehavior="HoldEnd"
Storyboard.TargetName="buttonGlow"
Storyboard.TargetProperty="GlowSize" To="4"/>
<ColorAnimation Duration="0:0:0.6"
FillBehavior="HoldEnd"
Storyboard.TargetName="background"
Storyboard.TargetProperty="(Panel.Background).(SolidColorBrush.Color)"
To="#FF844800"/>
</Storyboard.Children>
</Storyboard>
<Storyboard x:Key="ButtonReleased">
<Storyboard.Children>
<DoubleAnimation Duration="0:0:0.2"
FillBehavior="HoldEnd"
Storyboard.TargetName="buttonGlow"
Storyboard.TargetProperty="GlowSize" To="0"/>
<ColorAnimation Duration="0:0:0.2"
FillBehavior="Stop"
Storyboard.TargetName="background"
Storyboard.TargetProperty="(Panel.Background).(SolidColorBrush.Color)"
To="#FF0062B6"/>
</Storyboard.Children>
</Storyboard>
</ControlTemplate.Resources>
<ControlTemplate.Triggers>
<Trigger Property="ButtonBase.IsPressed" Value="True">
<Trigger.EnterActions>
<BeginStoryboard Storyboard="{StaticResource ButtonPressed}"/>
</Trigger.EnterActions>
<Trigger.ExitActions>
<BeginStoryboard Storyboard="{StaticResource ButtonReleased}"/>
</Trigger.ExitActions>
</Trigger>
</ControlTemplate.Triggers>
</ControlTemplate>
</Setter.Value>
</Setter>
</Style>
</Button.Resources>
<DockPanel>
<TextBlock x:Name="TextContent" FontSize="28" Foreground="White" >Test</TextBlock>
</DockPanel>
</Button>
```
Any suggestions from anyone who understands WPF and XAML a lot better than me?
Here is the error stacktrace:
```
at System.Windows.Media.Animation.Storyboard.ResolveTargetName(String targetName, INameScope nameScope, DependencyObject element)
at System.Windows.Media.Animation.Storyboard.ClockTreeWalkRecursive(Clock currentClock, DependencyObject containingObject, INameScope nameScope, DependencyObject parentObject, String parentObjectName, PropertyPath parentPropertyPath, HandoffBehavior handoffBehavior, HybridDictionary clockMappings, Int64 layer)
at System.Windows.Media.Animation.Storyboard.ClockTreeWalkRecursive(Clock currentClock, DependencyObject containingObject, INameScope nameScope, DependencyObject parentObject, String parentObjectName, PropertyPath parentPropertyPath, HandoffBehavior handoffBehavior, HybridDictionary clockMappings, Int64 layer)
at System.Windows.Media.Animation.Storyboard.BeginCommon(DependencyObject containingObject, INameScope nameScope, HandoffBehavior handoffBehavior, Boolean isControllable, Int64 layer)
at System.Windows.Media.Animation.Storyboard.Begin(FrameworkElement containingObject)
at pk_rodoment.SkinningEngine.ButtonControlWPF._button_MouseDown(Object sender, MouseButtonEventArgs e)
at System.Windows.Input.MouseButtonEventArgs.InvokeEventHandler(Delegate genericHandler, Object genericTarget)
at System.Windows.RoutedEventArgs.InvokeHandler(Delegate handler, Object target)
at System.Windows.RoutedEventHandlerInfo.InvokeHandler(Object target, RoutedEventArgs routedEventArgs)
at System.Windows.EventRoute.InvokeHandlersImpl(Object source, RoutedEventArgs args, Boolean reRaised)
at System.Windows.UIElement.RaiseEventImpl(DependencyObject sender, RoutedEventArgs args)
at System.Windows.UIElement.RaiseEvent(RoutedEventArgs args, Boolean trusted)
at System.Windows.Input.InputManager.ProcessStagingArea()
at System.Windows.Input.InputManager.ProcessInput(InputEventArgs input)
at System.Windows.Input.InputProviderSite.ReportInput(InputReport inputReport)
at System.Windows.Interop.HwndMouseInputProvider.ReportInput(IntPtr hwnd, InputMode mode, Int32 timestamp, RawMouseActions actions, Int32 x, Int32 y, Int32 wheel)
at System.Windows.Interop.HwndMouseInputProvider.FilterMessage(IntPtr hwnd, Int32 msg, IntPtr wParam, IntPtr lParam, Boolean& handled)
at System.Windows.Interop.HwndSource.InputFilterMessage(IntPtr hwnd, Int32 msg, IntPtr wParam, IntPtr lParam, Boolean& handled)
at MS.Win32.HwndWrapper.WndProc(IntPtr hwnd, Int32 msg, IntPtr wParam, IntPtr lParam, Boolean& handled)
at MS.Win32.HwndSubclass.DispatcherCallbackOperation(Object o)
at System.Windows.Threading.ExceptionWrapper.InternalRealCall(Delegate callback, Object args, Boolean isSingleParameter)
at System.Windows.Threading.ExceptionWrapper.TryCatchWhen(Object source, Delegate callback, Object args, Boolean isSingleParameter, Delegate catchHandler)
at System.Windows.Threading.Dispatcher.WrappedInvoke(Delegate callback, Object args, Boolean isSingleParameter, Delegate catchHandler)
at System.Windows.Threading.Dispatcher.InvokeImpl(DispatcherPriority priority, TimeSpan timeout, Delegate method, Object args, Boolean isSingleParameter)
at System.Windows.Threading.Dispatcher.Invoke(DispatcherPriority priority, Delegate method, Object arg)
at MS.Win32.HwndSubclass.SubclassWndProc(IntPtr hwnd, Int32 msg, IntPtr wParam, IntPtr lParam)
at MS.Win32.UnsafeNativeMethods.DispatchMessage(MSG& msg)
at System.Windows.Threading.Dispatcher.PushFrameImpl(DispatcherFrame frame)
at System.Windows.Threading.Dispatcher.PushFrame(DispatcherFrame frame)
at System.Windows.Threading.Dispatcher.Run()
at System.Windows.Application.RunDispatcher(Object ignore)
at System.Windows.Application.RunInternal(Window window)
at System.Windows.Application.Run(Window window)
at System.Windows.Application.Run()
at ControlTestbed.App.Main() in C:\svnprojects\rodomont\ControlsTestbed\obj\Debug\App.g.cs:line 0
at System.AppDomain._nExecuteAssembly(Assembly assembly, String[] args)
at System.AppDomain.ExecuteAssembly(String assemblyFile, Evidence assemblySecurity, String[] args)
at Microsoft.VisualStudio.HostingProcess.HostProc.RunUsersAssembly()
at System.Threading.ThreadHelper.ThreadStart_Context(Object state)
at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state)
at System.Threading.ThreadHelper.ThreadStart()
``` | Finally found it. When you call Begin on storyboards that reference elements in the ControlTemplate, you must pass in the control template as well.
Changing:
```
pressedButtonStoryboard.Begin(_xamlButton);
```
To:
```
pressedButtonStoryboard.Begin(_xamlButton, _xamlButton.Template);
```
Fixed everything. |
151,769 | <p>Originally there was the DAL object which my BO's called for info and then passed to UI. Then I started noticing reduced code in UI and there were Controller classes. What's the decent recomendation.</p>
<p>I currently structure mine</p>
<pre><code>Public Class OrderDAL
Private _id Integer
Private _order as Order
Public Function GetOrder(id as Integer) as Order
...return Order
End Function
End Class
</code></pre>
<p>then I have controller classes (recently implemented this style)</p>
<pre><code>Public Class OrderController
Private Shared _orderDAL as new OrderDAL
Public Shared Function GetOrder(id) As Order
Return _orderDAL.GetOrder(id)
End Function
End Class
</code></pre>
<p>Then in my application</p>
<pre><code>My app Sub
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
msgbox(OrderController.GetOrder(12345).Customer.Name)
End Sub
End app
</code></pre>
<p>I originally found that with the Shared Class I didn't have to keep creating a new instance of the DAL whenever I need to fetch data</p>
<pre><code>Dim _orderDAL as New OrderDal
_orderDAL.GetOrder(1234)
.....
</code></pre>
<p>What's your take?</p>
<p>Thanks</p>
| [
{
"answer_id": 151799,
"author": "Dan Blair",
"author_id": 1327,
"author_profile": "https://Stackoverflow.com/users/1327",
"pm_score": 0,
"selected": false,
"text": "<p>Well your application shouldn't be instantiating seperate versions of the data acces layer, so you have that under control. The Psuedo code you posted is really hard to read though.</p>\n\n<p>The question is, what is your data access layer, and how much is there? That's going to dictate a good bit of what you do. If your persiting to a file then I think what you have written is fine, and if you need to share it with other controllers in your system, it's possible to wrap the item into a singelton(shudder). </p>\n\n<p>If you really are doing order processing and persisting back to a database, I personaly think it's time to look at an ORM. These packages will handle the CRUM aspects for you and reduce the number of items that you have to maintain. </p>\n\n<p>My $.02, and I reserve the right to revise my answer once I see a better example.</p>\n"
},
{
"answer_id": 151807,
"author": "casademora",
"author_id": 5619,
"author_profile": "https://Stackoverflow.com/users/5619",
"pm_score": 2,
"selected": false,
"text": "<p>I think there are several alternatives listed in this excellent book: <a href=\"https://rads.stackoverflow.com/amzn/click/com/0321127420\" rel=\"nofollow noreferrer\" rel=\"nofollow noreferrer\">Patterns of Enterprise Application Architecture</a>. Some patterns that may be of interest to you:</p>\n\n<ul>\n<li><a href=\"http://martinfowler.com/eaaCatalog/activeRecord.html\" rel=\"nofollow noreferrer\">Active Record</a></li>\n<li><a href=\"http://martinfowler.com/eaaCatalog/tableDataGateway.html\" rel=\"nofollow noreferrer\">Table Data Gateway</a></li>\n<li><a href=\"http://martinfowler.com/eaaCatalog/rowDataGateway.html\" rel=\"nofollow noreferrer\">Row Data Gateway</a></li>\n<li><a href=\"http://martinfowler.com/eaaCatalog/dataMapper.html\" rel=\"nofollow noreferrer\">Data Mapper</a></li>\n</ul>\n"
},
{
"answer_id": 151828,
"author": "Thorsten79",
"author_id": 19734,
"author_profile": "https://Stackoverflow.com/users/19734",
"pm_score": 0,
"selected": false,
"text": "<p>I can't speak to the VB details because I'm not a VB developer, but:</p>\n\n<p>What you are doing is a well-established good practice, separating the GUI/presentation layer from the data layer. Including real application code in GUI event methods is a (sadly also well-established) bad practice.</p>\n\n<p>Your controller class resembles the <a href=\"http://en.wikipedia.org/wiki/Bridge_pattern\" rel=\"nofollow noreferrer\">bridge pattern</a> which is also a good idea if both layers shall be able to change their form without the other knowing about it. </p>\n\n<p>Go ahead!</p>\n"
},
{
"answer_id": 152159,
"author": "Phil Bennett",
"author_id": 2995,
"author_profile": "https://Stackoverflow.com/users/2995",
"pm_score": 0,
"selected": false,
"text": "<p>Its a good practice -- especially when you get to a point where the Controller will need to do more than simple delegation to the underlying DAL. </p>\n"
},
{
"answer_id": 152228,
"author": "Sklivvz",
"author_id": 7028,
"author_profile": "https://Stackoverflow.com/users/7028",
"pm_score": 1,
"selected": true,
"text": "<p>I've used your solution in the past, and the only problem I faced is that \"Shared\" or \"static\" methods don't support inheritance. When your application grows, you might very well need to support different types of \"OrderControllers\".</p>\n\n<p>The estabilished way of supporting different OrderControllers would be, in theory, to create a factory:</p>\n\n<pre><code>OrderControllerFactory.ConfiguredOrderController().GetOrder(42);\n</code></pre>\n\n<p>The problem here is: what type is returned by \"ConfiguredOrderController()\"? Because it must have the static \"GetOrder(int id)\" method -- and static methods are not supported by inheritance or interfaces. The way around this is not to use static methods in the OrderController class.</p>\n\n<pre><code>public interface IOrderController\n{\n Order GetOrder(int Id)\n}\n\npublic class OrderController: IOrderController\n{\n public Order GetOrder(int Id)\n {}\n}\n</code></pre>\n\n<p>and</p>\n\n<pre><code>public class OrderControllerFactory()\n{\n public IOrderController ConfiguredOrderController()\n {}\n}\n</code></pre>\n\n<p>Hence, you will probably be better off by using non-static methods for the controller.</p>\n"
}
]
| 2008/09/30 | [
"https://Stackoverflow.com/questions/151769",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/23667/"
]
| Originally there was the DAL object which my BO's called for info and then passed to UI. Then I started noticing reduced code in UI and there were Controller classes. What's the decent recomendation.
I currently structure mine
```
Public Class OrderDAL
Private _id Integer
Private _order as Order
Public Function GetOrder(id as Integer) as Order
...return Order
End Function
End Class
```
then I have controller classes (recently implemented this style)
```
Public Class OrderController
Private Shared _orderDAL as new OrderDAL
Public Shared Function GetOrder(id) As Order
Return _orderDAL.GetOrder(id)
End Function
End Class
```
Then in my application
```
My app Sub
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
msgbox(OrderController.GetOrder(12345).Customer.Name)
End Sub
End app
```
I originally found that with the Shared Class I didn't have to keep creating a new instance of the DAL whenever I need to fetch data
```
Dim _orderDAL as New OrderDal
_orderDAL.GetOrder(1234)
.....
```
What's your take?
Thanks | I've used your solution in the past, and the only problem I faced is that "Shared" or "static" methods don't support inheritance. When your application grows, you might very well need to support different types of "OrderControllers".
The estabilished way of supporting different OrderControllers would be, in theory, to create a factory:
```
OrderControllerFactory.ConfiguredOrderController().GetOrder(42);
```
The problem here is: what type is returned by "ConfiguredOrderController()"? Because it must have the static "GetOrder(int id)" method -- and static methods are not supported by inheritance or interfaces. The way around this is not to use static methods in the OrderController class.
```
public interface IOrderController
{
Order GetOrder(int Id)
}
public class OrderController: IOrderController
{
public Order GetOrder(int Id)
{}
}
```
and
```
public class OrderControllerFactory()
{
public IOrderController ConfiguredOrderController()
{}
}
```
Hence, you will probably be better off by using non-static methods for the controller. |
151,777 | <p>I've been working on the Android SDK platform, and it is a little unclear how to save an application's state. So given this minor re-tooling of the 'Hello, Android' example:</p>
<pre class="lang-java prettyprint-override"><code>package com.android.hello;
import android.app.Activity;
import android.os.Bundle;
import android.widget.TextView;
public class HelloAndroid extends Activity {
private TextView mTextView = null;
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
mTextView = new TextView(this);
if (savedInstanceState == null) {
mTextView.setText("Welcome to HelloAndroid!");
} else {
mTextView.setText("Welcome back.");
}
setContentView(mTextView);
}
}
</code></pre>
<p>I thought it would be enough for the simplest case, but it always responds with the first message, no matter how I navigate away from the app.</p>
<p>I'm sure the solution is as simple as overriding <code>onPause</code> or something like that, but I've been poking away in the documentation for 30 minutes or so and haven't found anything obvious.</p>
| [
{
"answer_id": 151822,
"author": "Dave L.",
"author_id": 3093,
"author_profile": "https://Stackoverflow.com/users/3093",
"pm_score": 9,
"selected": false,
"text": "<p>The <code>savedInstanceState</code> is only for saving state associated with a current instance of an Activity, for example current navigation or selection info, so that if Android destroys and recreates an Activity, it can come back as it was before. See the documentation for <a href=\"http://developer.android.com/reference/android/app/Activity.html#onCreate(android.os.Bundle)\" rel=\"noreferrer\"><code>onCreate</code></a> and <a href=\"http://developer.android.com/reference/android/app/Activity.html#onSaveInstanceState(android.os.Bundle)\" rel=\"noreferrer\"><code>onSaveInstanceState</code></a></p>\n\n<p>For more long lived state, consider using a SQLite database, a file, or preferences. See <a href=\"http://developer.android.com/reference/android/app/Activity.html#SavingPersistentState\" rel=\"noreferrer\">Saving Persistent State</a>.</p>\n"
},
{
"answer_id": 151940,
"author": "Reto Meier",
"author_id": 822,
"author_profile": "https://Stackoverflow.com/users/822",
"pm_score": 12,
"selected": true,
"text": "<p>You need to override <code>onSaveInstanceState(Bundle savedInstanceState)</code> and write the application state values you want to change to the <code>Bundle</code> parameter like this:</p>\n<pre><code>@Override\npublic void onSaveInstanceState(Bundle savedInstanceState) {\n super.onSaveInstanceState(savedInstanceState);\n // Save UI state changes to the savedInstanceState.\n // This bundle will be passed to onCreate if the process is\n // killed and restarted.\n savedInstanceState.putBoolean("MyBoolean", true);\n savedInstanceState.putDouble("myDouble", 1.9);\n savedInstanceState.putInt("MyInt", 1);\n savedInstanceState.putString("MyString", "Welcome back to Android");\n // etc.\n}\n</code></pre>\n<p>The Bundle is essentially a way of storing a NVP ("Name-Value Pair") map, and it will get passed in to <code>onCreate()</code> and also <code>onRestoreInstanceState()</code> where you would then extract the values from activity like this:</p>\n<pre><code>@Override\npublic void onRestoreInstanceState(Bundle savedInstanceState) {\n super.onRestoreInstanceState(savedInstanceState);\n // Restore UI state from the savedInstanceState.\n // This bundle has also been passed to onCreate.\n boolean myBoolean = savedInstanceState.getBoolean("MyBoolean");\n double myDouble = savedInstanceState.getDouble("myDouble");\n int myInt = savedInstanceState.getInt("MyInt");\n String myString = savedInstanceState.getString("MyString");\n}\n</code></pre>\n<p>Or from a fragment.</p>\n<pre><code>@Override\npublic void onViewStateRestored(@Nullable Bundle savedInstanceState) {\n super.onViewStateRestored(savedInstanceState);\n // Restore UI state from the savedInstanceState.\n // This bundle has also been passed to onCreate.\n boolean myBoolean = savedInstanceState.getBoolean("MyBoolean");\n double myDouble = savedInstanceState.getDouble("myDouble");\n int myInt = savedInstanceState.getInt("MyInt");\n String myString = savedInstanceState.getString("MyString");\n}\n</code></pre>\n<p>You would usually use this technique to store instance values for your application (selections, unsaved text, etc.).</p>\n"
},
{
"answer_id": 2785419,
"author": "Fedor",
"author_id": 95313,
"author_profile": "https://Stackoverflow.com/users/95313",
"pm_score": 7,
"selected": false,
"text": "<p><code>onSaveInstanceState</code> is called when the system needs memory and kills an application. It is not called when the user just closes the application. So I think application state should also be saved in <code>onPause</code>.</p>\n<p>It should be saved to some persistent storage like <code>Preferences</code> or SQLite.</p>\n"
},
{
"answer_id": 2893765,
"author": "u-foka",
"author_id": 347184,
"author_profile": "https://Stackoverflow.com/users/347184",
"pm_score": 6,
"selected": false,
"text": "<p>Really <code>onSaveInstanceState()</code> is called when the Activity goes to background.</p>\n<p>Quote from the docs:\n"This method is called before an activity may be killed so that when it comes back sometime in the future it can restore its state."\n<a href=\"https://developer.android.com/reference/android/app/Activity.html#onSaveInstanceState(android.os.Bundle)\" rel=\"nofollow noreferrer\">Source</a></p>\n"
},
{
"answer_id": 2909211,
"author": "Steve Moseley",
"author_id": 299472,
"author_profile": "https://Stackoverflow.com/users/299472",
"pm_score": 9,
"selected": false,
"text": "<p>Note that it is <em><strong>not</strong></em> safe to use <code>onSaveInstanceState</code> and <code>onRestoreInstanceState</code> <strong>for persistent data</strong>, according to <em><a href=\"http://developer.android.com/reference/android/app/Activity.html\" rel=\"noreferrer\">the documentation on Activity</a></em>.</p>\n<p>The document states (in the 'Activity Lifecycle' section):</p>\n<blockquote>\n<p>Note that it is important to save\npersistent data in <code>onPause()</code> instead\nof <code>onSaveInstanceState(Bundle)</code>\nbecause the later is not part of the\nlifecycle callbacks, so will not be\ncalled in every situation as described\nin its documentation.</p>\n</blockquote>\n<p>In other words, put your save/restore code for persistent data in <code>onPause()</code> and <code>onResume()</code>!</p>\n<p>For further clarification, here's the <code>onSaveInstanceState()</code> documentation:</p>\n<blockquote>\n<p>This method is called before an activity may be killed so that when it\ncomes back some time in the future it can restore its state. For\nexample, if activity B is launched in front of activity A, and at some\npoint activity A is killed to reclaim resources, activity A will have\na chance to save the current state of its user interface via this\nmethod so that when the user returns to activity A, the state of the\nuser interface can be restored via <code>onCreate(Bundle)</code> or\n<code>onRestoreInstanceState(Bundle)</code>.</p>\n</blockquote>\n"
},
{
"answer_id": 3584836,
"author": "Martin Belcher - AtWrk",
"author_id": 379115,
"author_profile": "https://Stackoverflow.com/users/379115",
"pm_score": 8,
"selected": false,
"text": "<p>My colleague wrote an article explaining application state on Android devices, including explanations on activity lifecycle and state information, how to store state information, and saving to state <code>Bundle</code> and <code>SharedPreferences</code>. <a href=\"http://www.eigo.co.uk/Managing-State-in-an-Android-Activity.aspx\" rel=\"noreferrer\">Take a look at it here</a>.</p>\n<p>The article covers three approaches:</p>\n<h2 id=\"store-local-variableui-control-data-for-application-lifetime-i.e.temporarily-using-an-instance-state-bundle-cq9v\">Store local variable/UI control data for application lifetime (i.e. temporarily) using an instance state bundle</h2>\n<pre><code>[Code sample – Store state in state bundle]\n@Override\npublic void onSaveInstanceState(Bundle savedInstanceState)\n{\n // Store UI state to the savedInstanceState.\n // This bundle will be passed to onCreate on next call. EditText txtName = (EditText)findViewById(R.id.txtName);\n String strName = txtName.getText().toString();\n\n EditText txtEmail = (EditText)findViewById(R.id.txtEmail);\n String strEmail = txtEmail.getText().toString();\n\n CheckBox chkTandC = (CheckBox)findViewById(R.id.chkTandC);\n boolean blnTandC = chkTandC.isChecked();\n\n savedInstanceState.putString(“Name”, strName);\n savedInstanceState.putString(“Email”, strEmail);\n savedInstanceState.putBoolean(“TandC”, blnTandC);\n\n super.onSaveInstanceState(savedInstanceState);\n}\n</code></pre>\n<h2 id=\"store-local-variableui-control-data-between-application-instances-i.e.permanently-using-shared-preferences-9sl9\">Store local variable/UI control data between application instances (i.e. permanently) using shared preferences</h2>\n<pre><code>[Code sample – store state in SharedPreferences]\n@Override\nprotected void onPause()\n{\n super.onPause();\n\n // Store values between instances here\n SharedPreferences preferences = getPreferences(MODE_PRIVATE);\n SharedPreferences.Editor editor = preferences.edit(); // Put the values from the UI\n EditText txtName = (EditText)findViewById(R.id.txtName);\n String strName = txtName.getText().toString();\n\n EditText txtEmail = (EditText)findViewById(R.id.txtEmail);\n String strEmail = txtEmail.getText().toString();\n\n CheckBox chkTandC = (CheckBox)findViewById(R.id.chkTandC);\n boolean blnTandC = chkTandC.isChecked();\n\n editor.putString(“Name”, strName); // value to store\n editor.putString(“Email”, strEmail); // value to store\n editor.putBoolean(“TandC”, blnTandC); // value to store\n // Commit to storage\n editor.commit();\n}\n</code></pre>\n<h2 id=\"keeping-object-instances-alive-in-memory-between-activities-within-application-lifetime-using-a-retained-non-configuration-instance-qv67\">Keeping object instances alive in memory between activities within application lifetime using a retained non-configuration instance</h2>\n<pre><code>[Code sample – store object instance]\nprivate cMyClassType moInstanceOfAClass; // Store the instance of an object\n@Override\npublic Object onRetainNonConfigurationInstance()\n{\n if (moInstanceOfAClass != null) // Check that the object exists\n return(moInstanceOfAClass);\n return super.onRetainNonConfigurationInstance();\n}\n</code></pre>\n"
},
{
"answer_id": 6457934,
"author": "Mike A.",
"author_id": 782695,
"author_profile": "https://Stackoverflow.com/users/782695",
"pm_score": 6,
"selected": false,
"text": "<p>Saving state is a kludge at best as far as I'm concerned. If you need to save persistent data, just use an <a href=\"http://en.wikipedia.org/wiki/SQLite\" rel=\"noreferrer\">SQLite</a> database. Android makes it <strong><em>SOOO</em></strong> easy.</p>\n\n<p>Something like this:</p>\n\n<pre><code>import java.util.Date;\nimport android.content.Context;\nimport android.database.Cursor;\nimport android.database.sqlite.SQLiteDatabase;\nimport android.database.sqlite.SQLiteOpenHelper;\n\npublic class dataHelper {\n\n private static final String DATABASE_NAME = \"autoMate.db\";\n private static final int DATABASE_VERSION = 1;\n\n private Context context;\n private SQLiteDatabase db;\n private OpenHelper oh ;\n\n public dataHelper(Context context) {\n this.context = context;\n this.oh = new OpenHelper(this.context);\n this.db = oh.getWritableDatabase();\n }\n\n public void close() {\n db.close();\n oh.close();\n db = null;\n oh = null;\n SQLiteDatabase.releaseMemory();\n }\n\n\n public void setCode(String codeName, Object codeValue, String codeDataType) {\n Cursor codeRow = db.rawQuery(\"SELECT * FROM code WHERE codeName = '\"+ codeName + \"'\", null);\n String cv = \"\" ;\n\n if (codeDataType.toLowerCase().trim().equals(\"long\") == true){\n cv = String.valueOf(codeValue);\n }\n else if (codeDataType.toLowerCase().trim().equals(\"int\") == true)\n {\n cv = String.valueOf(codeValue);\n }\n else if (codeDataType.toLowerCase().trim().equals(\"date\") == true)\n {\n cv = String.valueOf(((Date)codeValue).getTime());\n }\n else if (codeDataType.toLowerCase().trim().equals(\"boolean\") == true)\n {\n String.valueOf(codeValue);\n }\n else\n {\n cv = String.valueOf(codeValue);\n }\n\n if(codeRow.getCount() > 0) //exists-- update\n {\n db.execSQL(\"update code set codeValue = '\" + cv +\n \"' where codeName = '\" + codeName + \"'\");\n }\n else // does not exist, insert\n {\n db.execSQL(\"INSERT INTO code (codeName, codeValue, codeDataType) VALUES(\" +\n \"'\" + codeName + \"',\" +\n \"'\" + cv + \"',\" +\n \"'\" + codeDataType + \"')\" );\n }\n }\n\n public Object getCode(String codeName, Object defaultValue){\n\n //Check to see if it already exists\n String codeValue = \"\";\n String codeDataType = \"\";\n boolean found = false;\n Cursor codeRow = db.rawQuery(\"SELECT * FROM code WHERE codeName = '\"+ codeName + \"'\", null);\n if (codeRow.moveToFirst())\n {\n codeValue = codeRow.getString(codeRow.getColumnIndex(\"codeValue\"));\n codeDataType = codeRow.getString(codeRow.getColumnIndex(\"codeDataType\"));\n found = true;\n }\n\n if (found == false)\n {\n return defaultValue;\n }\n else if (codeDataType.toLowerCase().trim().equals(\"long\") == true)\n {\n if (codeValue.equals(\"\") == true)\n {\n return (long)0;\n }\n return Long.parseLong(codeValue);\n }\n else if (codeDataType.toLowerCase().trim().equals(\"int\") == true)\n {\n if (codeValue.equals(\"\") == true)\n {\n return (int)0;\n }\n return Integer.parseInt(codeValue);\n }\n else if (codeDataType.toLowerCase().trim().equals(\"date\") == true)\n {\n if (codeValue.equals(\"\") == true)\n {\n return null;\n }\n return new Date(Long.parseLong(codeValue));\n }\n else if (codeDataType.toLowerCase().trim().equals(\"boolean\") == true)\n {\n if (codeValue.equals(\"\") == true)\n {\n return false;\n }\n return Boolean.parseBoolean(codeValue);\n }\n else\n {\n return (String)codeValue;\n }\n }\n\n\n private static class OpenHelper extends SQLiteOpenHelper {\n\n OpenHelper(Context context) {\n super(context, DATABASE_NAME, null, DATABASE_VERSION);\n }\n\n @Override\n public void onCreate(SQLiteDatabase db) {\n db.execSQL(\"CREATE TABLE IF NOT EXISTS code\" +\n \"(id INTEGER PRIMARY KEY, codeName TEXT, codeValue TEXT, codeDataType TEXT)\");\n }\n\n @Override\n public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {\n }\n }\n}\n</code></pre>\n\n<p>A simple call after that</p>\n\n<pre><code>dataHelper dh = new dataHelper(getBaseContext());\nString status = (String) dh.getCode(\"appState\", \"safetyDisabled\");\nDate serviceStart = (Date) dh.getCode(\"serviceStartTime\", null);\ndh.close();\ndh = null;\n</code></pre>\n"
},
{
"answer_id": 6495812,
"author": "David",
"author_id": 817751,
"author_profile": "https://Stackoverflow.com/users/817751",
"pm_score": 6,
"selected": false,
"text": "<p>Both methods are useful and valid and both are best suited for different scenarios:</p>\n\n<ol>\n<li>The user terminates the application and re-opens it at a later date, but the application needs to reload data from the last session – this requires a persistent storage approach such as using SQLite.</li>\n<li>The user switches application and then comes back to the original and wants to pick up where they left off - save and restore bundle data (such as application state data) in <code>onSaveInstanceState()</code> and <code>onRestoreInstanceState()</code> is usually adequate.</li>\n</ol>\n\n<p>If you save the state data in a persistent manner, it can be reloaded in an <code>onResume()</code> or <code>onCreate()</code> (or actually on any lifecycle call). This may or may not be desired behaviour. If you store it in a bundle in an <code>InstanceState</code>, then it is transient and is only suitable for storing data for use in the same user ‘session’ (I use the term session loosely) but not between ‘sessions’.</p>\n\n<p>It is not that one approach is better than the other, like everything, it is just important to understand what behaviour you require and to select the most appropriate approach.</p>\n"
},
{
"answer_id": 8899745,
"author": "User",
"author_id": 930450,
"author_profile": "https://Stackoverflow.com/users/930450",
"pm_score": 6,
"selected": false,
"text": "<p><code>onSaveInstanceState()</code> for transient data (restored in <code>onCreate()</code>/<code>onRestoreInstanceState()</code>), <code>onPause()</code> for persistent data (restored in <code>onResume()</code>).\nFrom Android technical resources:</p>\n<blockquote>\n<p><strong>onSaveInstanceState()</strong> is called by Android if the Activity is being stopped and may be killed before it is resumed! This means it should store any state necessary to re-initialize to the same condition when the Activity is restarted. It is the counterpart to the onCreate() method, and in fact the savedInstanceState Bundle passed in to onCreate() is the same Bundle that you construct as outState in the onSaveInstanceState() method.</p>\n<p><strong>onPause()</strong> and <strong>onResume()</strong> are also complimentary methods. onPause() is always called when the Activity ends, even if we instigated that (with a finish() call for example). We will use this to save the current note back to the database. Good practice is to release any resources that can be released during an onPause() as well, to take up less resources when in the passive state.</p>\n</blockquote>\n"
},
{
"answer_id": 9148893,
"author": "roy mathew",
"author_id": 1052709,
"author_profile": "https://Stackoverflow.com/users/1052709",
"pm_score": 6,
"selected": false,
"text": "<p>I think I found the answer. Let me tell what I have done in simple words:</p>\n\n<p>Suppose I have two activities, activity1 and activity2 and I am navigating from activity1 to activity2 (I have done some works in activity2) and again back to activity 1 by clicking on a button in activity1. Now at this stage I wanted to go back to activity2 and I want to see my activity2 in the same condition when I last left activity2.</p>\n\n<p>For the above scenario what I have done is that in the manifest I made some changes like this:</p>\n\n<pre><code><activity android:name=\".activity2\"\n android:alwaysRetainTaskState=\"true\" \n android:launchMode=\"singleInstance\">\n</activity>\n</code></pre>\n\n<p>And in the activity1 on the button click event I have done like this:</p>\n\n<pre><code>Intent intent = new Intent();\nintent.setFlags(Intent.FLAG_ACTIVITY_REORDER_TO_FRONT);\nintent.setClassName(this,\"com.mainscreen.activity2\");\nstartActivity(intent);\n</code></pre>\n\n<p>And in activity2 on button click event I have done like this:</p>\n\n<pre><code>Intent intent=new Intent();\nintent.setClassName(this,\"com.mainscreen.activity1\");\nstartActivity(intent);\n</code></pre>\n\n<p>Now what will happen is that whatever the changes we have made in the activity2 will not be lost, and we can view activity2 in the same state as we left previously.</p>\n\n<p>I believe this is the answer and this works fine for me. Correct me if I am wrong.</p>\n"
},
{
"answer_id": 9956341,
"author": "stefan bachert",
"author_id": 732454,
"author_profile": "https://Stackoverflow.com/users/732454",
"pm_score": 5,
"selected": false,
"text": "<p>Meanwhile I do in general no more use</p>\n\n<pre><code>Bundle savedInstanceState & Co\n</code></pre>\n\n<p>The life cycle is for most activities too complicated and not necessary.</p>\n\n<p>And Google states itself, it is NOT even reliable.</p>\n\n<p>My way is to save any changes immediately in the preferences:</p>\n\n<pre><code> SharedPreferences p;\n p.edit().put(..).commit()\n</code></pre>\n\n<p>In some way SharedPreferences work similar like Bundles.\nAnd naturally and at first such values have to be read from preferences.</p>\n\n<p>In the case of complex data you may use SQLite instead of using preferences.</p>\n\n<p>When applying this concept, the activity just continues to use the last saved state, regardless of whether it was an initial open with reboots in between or a reopen due to the back stack.</p>\n"
},
{
"answer_id": 12277349,
"author": "Mahorad",
"author_id": 659326,
"author_profile": "https://Stackoverflow.com/users/659326",
"pm_score": 5,
"selected": false,
"text": "<p>The <code>onSaveInstanceState(bundle)</code> and <code>onRestoreInstanceState(bundle)</code> methods are useful for data persistence merely while rotating the screen (orientation change).<br>\nThey are not even good while switching between applications (since the <code>onSaveInstanceState()</code> method is called but <code>onCreate(bundle)</code> and <code>onRestoreInstanceState(bundle)</code> is not invoked again.<br>\nFor more persistence use shared preferences. <a href=\"http://www.eigo.co.uk/Managing-State-in-an-Android-Activity.aspx\">read this article</a> </p>\n"
},
{
"answer_id": 12983901,
"author": "Mike Repass",
"author_id": 614880,
"author_profile": "https://Stackoverflow.com/users/614880",
"pm_score": 7,
"selected": false,
"text": "<p>This is a classic 'gotcha' of Android development. There are two issues here:</p>\n<ul>\n<li>There is a subtle Android Framework bug which greatly complicates application stack management during development, at least on legacy versions (not entirely sure if/when/how it was fixed). I'll discuss this bug below.</li>\n<li>The 'normal' or intended way to manage this issue is, itself, rather complicated with the duality of onPause/onResume and onSaveInstanceState/onRestoreInstanceState</li>\n</ul>\n<p>Browsing across all these threads, I suspect that much of the time developers are talking about these two different issues simultaneously ... hence all the confusion and reports of "this doesn't work for me".</p>\n<p>First, to clarify the 'intended' behavior: onSaveInstance and onRestoreInstance are fragile and only for transient state. The intended usage (as far as I can tell) is to handle Activity recreation when the phone is rotated (orientation change). In other words, the intended usage is when your Activity is still logically 'on top', but still must be reinstantiated by the system. The saved Bundle is not persisted outside of the process/memory/<a href=\"https://en.wikipedia.org/wiki/Garbage_collection_%28computer_science%29\" rel=\"noreferrer\">GC</a>, so you cannot really rely on this if your activity goes to the background. Yes, perhaps your Activity's memory will survive its trip to the background and escape GC, but this is not reliable (nor is it predictable).</p>\n<p>So if you have a scenario where there is meaningful 'user progress' or state that should be persisted between 'launches' of your application, the guidance is to use onPause and onResume. You must choose and prepare a persistent store yourself.</p>\n<p><em>But</em> - there is a very confusing bug which complicates all of this. Details are here:</p>\n<ul>\n<li><p><em><a href=\"http://code.google.com/p/android/issues/detail?id=2373\" rel=\"noreferrer\">Activity stack behaves incorrectly during the first run of an app when started from Eclipse</a></em> (#36907463)</p>\n</li>\n<li><p><em><a href=\"https://issuetracker.google.com/issues/36911210\" rel=\"noreferrer\">Marketplace / browser app installer allows second instance off app</a></em> (#36911210)</p>\n</li>\n</ul>\n<p>Basically, if your application is launched with the SingleTask flag, and then later on you launch it from the home screen or launcher menu, then that subsequent invocation will create a NEW task ... you'll effectively have two different instances of your app inhabiting the same stack ... which gets very strange very fast. This seems to happen when you launch your app during development (i.e. from <a href=\"https://en.wikipedia.org/wiki/Eclipse_%28software%29\" rel=\"noreferrer\">Eclipse</a> or <a href=\"https://en.wikipedia.org/wiki/IntelliJ_IDEA\" rel=\"noreferrer\">IntelliJ</a>), so developers run into this a lot. But also through some of the app store update mechanisms (so it impacts your users as well).</p>\n<p>I battled through these threads for hours before I realized that my main issue was this bug, not the intended framework behavior. A great write-up and <del>workaround</del> (UPDATE: see below) seems to be from user @kaciula in this answer:</p>\n<p><em><a href=\"https://stackoverflow.com/questions/3042420/home-key-press-behaviour/4782423#4782423\">Home key press behaviour</a></em></p>\n<p><strong>UPDATE June 2013</strong>: Months later, I have finally found the 'correct' solution. You don't need to manage any stateful startedApp flags yourself. You can detect this from the framework and bail appropriately. I use this near the beginning of my LauncherActivity.onCreate:</p>\n<pre><code>if (!isTaskRoot()) {\n Intent intent = getIntent();\n String action = intent.getAction();\n if (intent.hasCategory(Intent.CATEGORY_LAUNCHER) && action != null && action.equals(Intent.ACTION_MAIN)) {\n finish();\n return;\n }\n}\n</code></pre>\n"
},
{
"answer_id": 23115933,
"author": "torwalker",
"author_id": 3501046,
"author_profile": "https://Stackoverflow.com/users/3501046",
"pm_score": 5,
"selected": false,
"text": "<p>My problem was that I needed persistence only during the application lifetime (i.e. a single execution including starting other sub-activities within the same app and rotating the device etc). I tried various combinations of the above answers but did not get what I wanted in all situations. In the end what worked for me was to obtain a reference to the savedInstanceState during onCreate:</p>\n\n<pre><code>mySavedInstanceState=savedInstanceState;\n</code></pre>\n\n<p>and use that to obtain the contents of my variable when I needed it, along the lines of:</p>\n\n<pre><code>if (mySavedInstanceState !=null) {\n boolean myVariable = mySavedInstanceState.getBoolean(\"MyVariable\");\n}\n</code></pre>\n\n<p>I use <code>onSaveInstanceState</code>and <code>onRestoreInstanceState</code> as suggested above but I guess i could also or alternatively use my method to save the variable when it changes (e.g. using <code>putBoolean</code>)</p>\n"
},
{
"answer_id": 28058539,
"author": "Jared Kells",
"author_id": 209249,
"author_profile": "https://Stackoverflow.com/users/209249",
"pm_score": 5,
"selected": false,
"text": "<p>To answer the original question directly. savedInstancestate is null because your Activity is never being re-created.</p>\n\n<p>Your Activity will only be re-created with a state bundle when:</p>\n\n<ul>\n<li>Configuration changes such as changing the orientation or phone language which may requires a new activity instance to be created.</li>\n<li>You return to the app from the background after the OS has destroyed the activity. </li>\n</ul>\n\n<p>Android will destroy background activities when under memory pressure or after they've been in the background for an extended period of time.</p>\n\n<p>When testing your hello world example there are a few ways to leave and return to the Activity.</p>\n\n<ul>\n<li>When you press the back button the Activity is finished. Re-launching the app is a brand new instance. You aren't resuming from the background at all.</li>\n<li>When you press the home button or use the task switcher the Activity will go into the background. When navigating back to the application onCreate will only be called if the Activity had to be destroyed. </li>\n</ul>\n\n<p>In most cases if you're just pressing home and then launching the app again the activity won't need to be re-created. It already exists in memory so onCreate() won't be called.</p>\n\n<p>There is an option under Settings -> Developer Options called \"Don't keep activities\". When it's enabled Android will always destroy activities and recreate them when they're backgrounded. This is a great option to leave enabled when developing because it simulates the worst case scenario. ( A low memory device recycling your activities all the time ).</p>\n\n<p>The other answers are valuable in that they teach you the correct ways to store state but I didn't feel they really answered WHY your code wasn't working in the way you expected.</p>\n"
},
{
"answer_id": 32108444,
"author": "Jared Rummler",
"author_id": 1048340,
"author_profile": "https://Stackoverflow.com/users/1048340",
"pm_score": 5,
"selected": false,
"text": "<p>To help reduce boilerplate I use the following <code>interface</code> and <code>class</code> to read/write to a <code>Bundle</code> for saving instance state.</p>\n\n<hr>\n\n<p>First, create an interface that will be used to annotate your instance variables:</p>\n\n<pre><code>import java.lang.annotation.Documented;\nimport java.lang.annotation.ElementType;\nimport java.lang.annotation.Retention;\nimport java.lang.annotation.RetentionPolicy;\nimport java.lang.annotation.Target;\n\n@Documented\n@Retention(RetentionPolicy.RUNTIME)\n@Target({\n ElementType.FIELD\n})\npublic @interface SaveInstance {\n\n}\n</code></pre>\n\n<p>Then, create a class where reflection will be used to save values to the bundle:</p>\n\n<pre><code>import android.app.Activity;\nimport android.app.Fragment;\nimport android.os.Bundle;\nimport android.os.Parcelable;\nimport android.util.Log;\n\nimport java.io.Serializable;\nimport java.lang.reflect.Field;\n\n/**\n * Save and load fields to/from a {@link Bundle}. All fields should be annotated with {@link\n * SaveInstance}.</p>\n */\npublic class Icicle {\n\n private static final String TAG = \"Icicle\";\n\n /**\n * Find all fields with the {@link SaveInstance} annotation and add them to the {@link Bundle}.\n *\n * @param outState\n * The bundle from {@link Activity#onSaveInstanceState(Bundle)} or {@link\n * Fragment#onSaveInstanceState(Bundle)}\n * @param classInstance\n * The object to access the fields which have the {@link SaveInstance} annotation.\n * @see #load(Bundle, Object)\n */\n public static void save(Bundle outState, Object classInstance) {\n save(outState, classInstance, classInstance.getClass());\n }\n\n /**\n * Find all fields with the {@link SaveInstance} annotation and add them to the {@link Bundle}.\n *\n * @param outState\n * The bundle from {@link Activity#onSaveInstanceState(Bundle)} or {@link\n * Fragment#onSaveInstanceState(Bundle)}\n * @param classInstance\n * The object to access the fields which have the {@link SaveInstance} annotation.\n * @param baseClass\n * Base class, used to get all superclasses of the instance.\n * @see #load(Bundle, Object, Class)\n */\n public static void save(Bundle outState, Object classInstance, Class<?> baseClass) {\n if (outState == null) {\n return;\n }\n Class<?> clazz = classInstance.getClass();\n while (baseClass.isAssignableFrom(clazz)) {\n String className = clazz.getName();\n for (Field field : clazz.getDeclaredFields()) {\n if (field.isAnnotationPresent(SaveInstance.class)) {\n field.setAccessible(true);\n String key = className + \"#\" + field.getName();\n try {\n Object value = field.get(classInstance);\n if (value instanceof Parcelable) {\n outState.putParcelable(key, (Parcelable) value);\n } else if (value instanceof Serializable) {\n outState.putSerializable(key, (Serializable) value);\n }\n } catch (Throwable t) {\n Log.d(TAG, \"The field '\" + key + \"' was not added to the bundle\");\n }\n }\n }\n clazz = clazz.getSuperclass();\n }\n }\n\n /**\n * Load all saved fields that have the {@link SaveInstance} annotation.\n *\n * @param savedInstanceState\n * The saved-instance {@link Bundle} from an {@link Activity} or {@link Fragment}.\n * @param classInstance\n * The object to access the fields which have the {@link SaveInstance} annotation.\n * @see #save(Bundle, Object)\n */\n public static void load(Bundle savedInstanceState, Object classInstance) {\n load(savedInstanceState, classInstance, classInstance.getClass());\n }\n\n /**\n * Load all saved fields that have the {@link SaveInstance} annotation.\n *\n * @param savedInstanceState\n * The saved-instance {@link Bundle} from an {@link Activity} or {@link Fragment}.\n * @param classInstance\n * The object to access the fields which have the {@link SaveInstance} annotation.\n * @param baseClass\n * Base class, used to get all superclasses of the instance.\n * @see #save(Bundle, Object, Class)\n */\n public static void load(Bundle savedInstanceState, Object classInstance, Class<?> baseClass) {\n if (savedInstanceState == null) {\n return;\n }\n Class<?> clazz = classInstance.getClass();\n while (baseClass.isAssignableFrom(clazz)) {\n String className = clazz.getName();\n for (Field field : clazz.getDeclaredFields()) {\n if (field.isAnnotationPresent(SaveInstance.class)) {\n String key = className + \"#\" + field.getName();\n field.setAccessible(true);\n try {\n Object fieldVal = savedInstanceState.get(key);\n if (fieldVal != null) {\n field.set(classInstance, fieldVal);\n }\n } catch (Throwable t) {\n Log.d(TAG, \"The field '\" + key + \"' was not retrieved from the bundle\");\n }\n }\n }\n clazz = clazz.getSuperclass();\n }\n }\n\n}\n</code></pre>\n\n<hr>\n\n<h2>Example usage:</h2>\n\n<pre><code>public class MainActivity extends Activity {\n\n @SaveInstance\n private String foo;\n\n @SaveInstance\n private int bar;\n\n @SaveInstance\n private Intent baz;\n\n @SaveInstance\n private boolean qux;\n\n @Override\n public void onCreate(Bundle savedInstanceState) {\n super.onCreate(savedInstanceState);\n Icicle.load(savedInstanceState, this);\n }\n\n @Override\n public void onSaveInstanceState(Bundle outState) {\n super.onSaveInstanceState(outState);\n Icicle.save(outState, this);\n }\n\n}\n</code></pre>\n\n<hr>\n\n<p><strong>Note:</strong> This code was adapted from a library project named <a href=\"https://github.com/CardinalNow/AndroidAutowire\">AndroidAutowire</a> which is licensed under the <a href=\"https://raw.githubusercontent.com/CardinalNow/AndroidAutowire/master/LICENSE\">MIT license</a>.</p>\n"
},
{
"answer_id": 34354935,
"author": "Krishna Satwaji Khandagale",
"author_id": 4549000,
"author_profile": "https://Stackoverflow.com/users/4549000",
"pm_score": 4,
"selected": false,
"text": "<p>There are basically two ways to implement this change.</p>\n\n<ol>\n<li>using <code>onSaveInstanceState()</code> and <code>onRestoreInstanceState()</code>.</li>\n<li>In manifest <code>android:configChanges=\"orientation|screenSize\"</code>.</li>\n</ol>\n\n<p>I really do not recommend to use second method. Since in one of my experience it was causing half of the device screen black while rotating from portrait to landscape and vice versa. </p>\n\n<p>Using first method mentioned above , we can persist data when orientation is changed or any config change happens.\nI know a way in which you can store any type of data inside savedInstance state object.</p>\n\n<p><em>Example: Consider a case if you want to persist Json object.\ncreate a model class with getters and setters .</em></p>\n\n<pre><code>class MyModel extends Serializable{\nJSONObject obj;\n\nsetJsonObject(JsonObject obj)\n{\nthis.obj=obj;\n}\n\nJSONObject getJsonObject()\nreturn this.obj;\n} \n}\n</code></pre>\n\n<p><em>Now in your activity in onCreate and onSaveInstanceState method do the following. It will look something like this:</em></p>\n\n<pre><code>@override\nonCreate(Bundle savedInstaceState){\nMyModel data= (MyModel)savedInstaceState.getSerializable(\"yourkey\")\nJSONObject obj=data.getJsonObject();\n//Here you have retained JSONObject and can use.\n}\n\n\n@Override\nprotected void onSaveInstanceState(Bundle outState) {\nsuper.onSaveInstanceState(outState);\n//Obj is some json object \nMyModel dataToSave= new MyModel();\ndataToSave.setJsonObject(obj);\noustate.putSerializable(\"yourkey\",dataToSave); \n\n}\n</code></pre>\n"
},
{
"answer_id": 35006431,
"author": "Kevin Cronly",
"author_id": 2559202,
"author_profile": "https://Stackoverflow.com/users/2559202",
"pm_score": 4,
"selected": false,
"text": "<p>Although the accepted answer is correct, there is a faster and easier method to save the Activity state on Android using a library called <a href=\"https://github.com/frankiesardo/icepick\">Icepick</a>. Icepick is an annotation processor that takes care of all the boilerplate code used in saving and restoring state for you. </p>\n\n<p>Doing something like this with Icepick:</p>\n\n<pre><code>class MainActivity extends Activity {\n @State String username; // These will be automatically saved and restored\n @State String password;\n @State int age;\n\n @Override public void onCreate(Bundle savedInstanceState) {\n super.onCreate(savedInstanceState);\n Icepick.restoreInstanceState(this, savedInstanceState);\n }\n\n @Override public void onSaveInstanceState(Bundle outState) {\n super.onSaveInstanceState(outState);\n Icepick.saveInstanceState(this, outState);\n }\n}\n</code></pre>\n\n<p>Is the same as doing this:</p>\n\n<pre><code>class MainActivity extends Activity {\n String username;\n String password;\n int age;\n\n @Override\n public void onSaveInstanceState(Bundle savedInstanceState) {\n super.onSaveInstanceState(savedInstanceState);\n savedInstanceState.putString(\"MyString\", username);\n savedInstanceState.putString(\"MyPassword\", password);\n savedInstanceState.putInt(\"MyAge\", age); \n /* remember you would need to actually initialize these variables before putting it in the\n Bundle */\n }\n\n @Override\n public void onRestoreInstanceState(Bundle savedInstanceState) {\n super.onRestoreInstanceState(savedInstanceState);\n username = savedInstanceState.getString(\"MyString\");\n password = savedInstanceState.getString(\"MyPassword\");\n age = savedInstanceState.getInt(\"MyAge\");\n }\n}\n</code></pre>\n\n<p>Icepick will work with any object that saves its state with a <code>Bundle</code>.</p>\n"
},
{
"answer_id": 38820371,
"author": "THANN Phearum",
"author_id": 1863510,
"author_profile": "https://Stackoverflow.com/users/1863510",
"pm_score": 3,
"selected": false,
"text": "<p>Simple quick to solve this problem is using <a href=\"https://github.com/frankiesardo/icepick\" rel=\"noreferrer\">IcePick</a></p>\n\n<p>First, setup the library in <code>app/build.gradle</code></p>\n\n<pre><code>repositories {\n maven {url \"https://clojars.org/repo/\"}\n}\ndependencies {\n compile 'frankiesardo:icepick:3.2.0'\n provided 'frankiesardo:icepick-processor:3.2.0'\n}\n</code></pre>\n\n<p>Now, let's check this example below how to save state in Activity</p>\n\n<pre><code>public class ExampleActivity extends Activity {\n @State String username; // This will be automatically saved and restored\n\n @Override public void onCreate(Bundle savedInstanceState) {\n super.onCreate(savedInstanceState);\n Icepick.restoreInstanceState(this, savedInstanceState);\n }\n\n @Override public void onSaveInstanceState(Bundle outState) {\n super.onSaveInstanceState(outState);\n Icepick.saveInstanceState(this, outState);\n }\n}\n</code></pre>\n\n<p>It works for Activities, Fragments or any object that needs to serialize its state on a Bundle (e.g. mortar's ViewPresenters)</p>\n\n<p>Icepick can also generate the instance state code for custom Views:</p>\n\n<pre><code>class CustomView extends View {\n @State int selectedPosition; // This will be automatically saved and restored\n\n @Override public Parcelable onSaveInstanceState() {\n return Icepick.saveInstanceState(this, super.onSaveInstanceState());\n }\n\n @Override public void onRestoreInstanceState(Parcelable state) {\n super.onRestoreInstanceState(Icepick.restoreInstanceState(this, state));\n }\n\n // You can put the calls to Icepick into a BaseCustomView and inherit from it\n // All Views extending this CustomView automatically have state saved/restored\n}\n</code></pre>\n"
},
{
"answer_id": 38851416,
"author": "ComeIn",
"author_id": 909122,
"author_profile": "https://Stackoverflow.com/users/909122",
"pm_score": 3,
"selected": false,
"text": "<p>Not sure if my solution is frowned upon or not, but I use a bound service to persist ViewModel state. Whether you store it in memory in the service or persist and retrieve it from a SQLite database depends on your requirements. This is what services of any flavor do, they provide services such as maintaining application state and abstract common business logic. </p>\n\n<p>Because of memory and processing constraints inherent on mobile devices, I treat Android views in a similar way to a web page. The page does not maintain state, it is purely a presentation layer component whose only purpose is to present application state and accept user input. Recent trends in web app architecture employ the use of the age-old Model, View, Controller (MVC) pattern, where the page is the View, domain data is the model, and the controller sits behind a web service. The same pattern can be employed in Android with the View being, well ... the View, the model is your domain data, and the Controller is implemented as an Android bound service. Whenever you want a view to interact with the controller, bind to it on start/resume and unbind on stop/pause.</p>\n\n<p>This approach gives you the added bonus of enforcing the Separation of Concern design principle in that all of you application business logic can be moved into your service which reduces duplicated logic across multiple views and allows the view to enforce another important design principle, Single Responsibility.</p>\n"
},
{
"answer_id": 39746554,
"author": "iamabhaykmr",
"author_id": 5800969,
"author_profile": "https://Stackoverflow.com/users/5800969",
"pm_score": 3,
"selected": false,
"text": "<p>To get activity state data stored in <code>onCreate()</code>, first you have to save data in savedInstanceState by overriding <code>SaveInstanceState(Bundle savedInstanceState)</code> method.</p>\n\n<p>When activity destroy <code>SaveInstanceState(Bundle savedInstanceState)</code> method gets called and there you save data you want to save. And you get same in <code>onCreate()</code> when activity restart.(savedInstanceState wont be null since you have saved some data in it before activity get destroyed)</p>\n"
},
{
"answer_id": 41804128,
"author": "Mansuu....",
"author_id": 3578677,
"author_profile": "https://Stackoverflow.com/users/3578677",
"pm_score": 4,
"selected": false,
"text": "<p>When an activity is created it's onCreate() method is called.</p>\n\n<pre><code> @Override\n protected void onCreate(Bundle savedInstanceState) {\n super.onCreate(savedInstanceState);\n }\n</code></pre>\n\n<p>savedInstanceState is an object of Bundle class which is null for the first time, but it contains values when it is recreated. To save Activity's state you have to override onSaveInstanceState().</p>\n\n<pre><code> @Override\n protected void onSaveInstanceState(Bundle outState) {\n outState.putString(\"key\",\"Welcome Back\")\n super.onSaveInstanceState(outState); //save state\n }\n</code></pre>\n\n<p>put your values in \"outState\" Bundle object like outState.putString(\"key\",\"Welcome Back\") and save by calling super.\nWhen activity will be destroyed it's state get saved in Bundle object and can be restored after recreation in onCreate() or onRestoreInstanceState(). Bundle received in onCreate() and onRestoreInstanceState() are same.</p>\n\n<pre><code> @Override\n protected void onCreate(Bundle savedInstanceState) {\n super.onCreate(savedInstanceState);\n setContentView(R.layout.activity_main);\n\n //restore activity's state\n if(savedInstanceState!=null){\n String reStoredString=savedInstanceState.getString(\"key\");\n }\n }\n</code></pre>\n\n<p>or</p>\n\n<pre><code> //restores activity's saved state\n @Override\n protected void onRestoreInstanceState(Bundle savedInstanceState) {\n String restoredMessage=savedInstanceState.getString(\"key\");\n }\n</code></pre>\n"
},
{
"answer_id": 42094343,
"author": "samus",
"author_id": 1105214,
"author_profile": "https://Stackoverflow.com/users/1105214",
"pm_score": 4,
"selected": false,
"text": "<p>Here is a comment from <strong>Steve Moseley</strong>'s answer (by <strong>ToolmakerSteve</strong>) that puts things into perspective (in the whole onSaveInstanceState vs onPause, east cost vs west cost saga)</p>\n\n<blockquote>\n <p>@VVK - I partially disagree. Some ways of exiting an app don't trigger\n onSaveInstanceState (oSIS). This limits the usefulness of oSIS. Its\n worth supporting, for minimal OS resources, but if an app wants to\n return the user to the state they were in, no matter how the app was\n exited, it is necessary to use a persistent storage approach instead.\n <strong>I use onCreate to check for bundle, and if it is missing, then check</strong>\n <strong>persistent storage.</strong> This centralizes the decision making. I can\n recover from a crash, or back button exit or custom menu item Exit, or\n get back to screen user was on many days later. – ToolmakerSteve Sep\n 19 '15 at 10:38</p>\n</blockquote>\n"
},
{
"answer_id": 48754303,
"author": "Rafols",
"author_id": 4765832,
"author_profile": "https://Stackoverflow.com/users/4765832",
"pm_score": 4,
"selected": false,
"text": "<p>Kotlin code:</p>\n\n<p>save:</p>\n\n<pre><code>override fun onSaveInstanceState(outState: Bundle) {\n super.onSaveInstanceState(outState.apply {\n putInt(\"intKey\", 1)\n putString(\"stringKey\", \"String Value\")\n putParcelable(\"parcelableKey\", parcelableObject)\n })\n}\n</code></pre>\n\n<p>and then in <code>onCreate()</code> or <code>onRestoreInstanceState()</code> </p>\n\n<pre><code> val restoredInt = savedInstanceState?.getInt(\"intKey\") ?: 1 //default int\n val restoredString = savedInstanceState?.getString(\"stringKey\") ?: \"default string\"\n val restoredParcelable = savedInstanceState?.getParcelable<ParcelableClass>(\"parcelableKey\") ?: ParcelableClass() //default parcelable\n</code></pre>\n\n<p>Add default values if you don't want to have Optionals</p>\n"
},
{
"answer_id": 52038707,
"author": "M Abdul Sami",
"author_id": 3185090,
"author_profile": "https://Stackoverflow.com/users/3185090",
"pm_score": 3,
"selected": false,
"text": "<p>Now Android provides <a href=\"https://developer.android.com/topic/libraries/architecture/saving-states\" rel=\"noreferrer\">ViewModels</a> for saving state, you should try to use that instead of saveInstanceState.</p>\n"
},
{
"answer_id": 54124841,
"author": "Rohit Singh",
"author_id": 4700156,
"author_profile": "https://Stackoverflow.com/users/4700156",
"pm_score": 2,
"selected": false,
"text": "<h2>What to save and what not to?</h2>\n\n<p>Ever wondered why the text in the <code>EditText</code> gets saved automatically while an orientation change? Well, this answer is for you.</p>\n\n<p>When an instance of an Activity gets destroyed and the System recreates a new instance (for example, configuration change). It tries to recreate it using a set of saved data of old Activity State (<strong>instance state</strong>).</p>\n\n<p>Instance state is a collection of <strong>key-value</strong> pairs stored in a <code>Bundle</code> object.</p>\n\n<blockquote>\n <p>By default System saves the View objects in the Bundle for example.</p>\n</blockquote>\n\n<ul>\n<li>Text in <code>EditText</code></li>\n<li>Scroll position in a <code>ListView</code>, etc.</li>\n</ul>\n\n<p>If you need another variable to be saved as a part of instance state you should <strong>OVERRIDE</strong> <code>onSavedInstanceState(Bundle savedinstaneState)</code> method.</p>\n\n<p>For example, <code>int currentScore</code> in a GameActivity</p>\n\n<h3>More detail about the onSavedInstanceState(Bundle savedinstaneState) while saving data</h3>\n\n<pre><code>@Override\npublic void onSaveInstanceState(Bundle savedInstanceState) {\n // Save the user's current game state\n savedInstanceState.putInt(STATE_SCORE, mCurrentScore);\n\n // Always call the superclass so it can save the view hierarchy state\n super.onSaveInstanceState(savedInstanceState);\n}\n</code></pre>\n\n<blockquote>\n <p>So by mistake if you forget to call\n <code>super.onSaveInstanceState(savedInstanceState);</code>the default behavior\n will not work ie Text in EditText will not save.</p>\n</blockquote>\n\n<h3>Which to choose for restoring Activity state?</h3>\n\n<pre><code> onCreate(Bundle savedInstanceState)\n</code></pre>\n\n<p><em>OR</em></p>\n\n<pre><code>onRestoreInstanceState(Bundle savedInstanceState)\n</code></pre>\n\n<p>Both methods get the same Bundle object, so it does not really matter where you write your restoring logic. The only difference is that in <code>onCreate(Bundle savedInstanceState)</code> method you will have to give a null check while it is not needed in the latter case. Other answers have already code snippets. You can refer them.</p>\n\n<h3>More detail about the onRestoreInstanceState(Bundle savedinstaneState)</h3>\n\n<pre><code>@Override\npublic void onRestoreInstanceState(Bundle savedInstanceState) {\n // Always call the superclass so it can restore the view hierarchy\n super.onRestoreInstanceState(savedInstanceState);\n\n // Restore state members from the saved instance\n mCurrentScore = savedInstanceState.getInt(STATE_SCORE);\n}\n</code></pre>\n\n<blockquote>\n <p>Always call <code>super.onRestoreInstanceState(savedInstanceState);</code> so that System restore the View hierarchy by default</p>\n</blockquote>\n\n<h2>Bonus</h2>\n\n<p>The <code>onSaveInstanceState(Bundle savedInstanceState)</code> is invoked by the system only when the user intends to come back to the Activity. For example, you are using App X and suddenly you get a call. You move to the caller app and come back to the app X. In this case the <code>onSaveInstanceState(Bundle savedInstanceState)</code> method will be invoked.</p>\n\n<p>But consider this if a user presses the back button. It is assumed that the user does not intend to come back to the Activity, hence in this case <code>onSaveInstanceState(Bundle savedInstanceState)</code> will not be invoked by the system.\nPoint being you should consider all the scenarios while saving data.</p>\n\n<h1>Relevant links:</h1>\n\n<p><a href=\"https://github.com/rohitksingh/My_Android_Garage/blob/master/Activity%20Related%20Stuff/app/src/main/java/rohitksingh/com/activityrelatedstuff/FirstActivity.java\" rel=\"nofollow noreferrer\">Demo on default behavior</a><br>\n<a href=\"https://developer.android.com/guide/components/activities/activity-lifecycle#saras\" rel=\"nofollow noreferrer\">Android Official Documentation</a>.</p>\n"
},
{
"answer_id": 56404590,
"author": "Sazzad Hissain Khan",
"author_id": 1084174,
"author_profile": "https://Stackoverflow.com/users/1084174",
"pm_score": 3,
"selected": false,
"text": "<h1>Kotlin</h1>\n\n<p>You must override <code>onSaveInstanceState</code> and <code>onRestoreInstanceState</code> to store and retrieve your variables you want to be persistent</p>\n\n<h3>Life cycle graph</h3>\n\n<p><img src=\"https://i.stack.imgur.com/Ts2F1.png\"></p>\n\n<h3>Store variables</h3>\n\n<pre><code>public override fun onSaveInstanceState(savedInstanceState: Bundle) {\n super.onSaveInstanceState(savedInstanceState)\n\n // prepare variables here\n savedInstanceState.putInt(\"kInt\", 10)\n savedInstanceState.putBoolean(\"kBool\", true)\n savedInstanceState.putDouble(\"kDouble\", 4.5)\n savedInstanceState.putString(\"kString\", \"Hello Kotlin\")\n}\n</code></pre>\n\n<h3>Retrieve variables</h3>\n\n<pre><code>public override fun onRestoreInstanceState(savedInstanceState: Bundle) {\n super.onRestoreInstanceState(savedInstanceState)\n\n val myInt = savedInstanceState.getInt(\"kInt\")\n val myBoolean = savedInstanceState.getBoolean(\"kBool\")\n val myDouble = savedInstanceState.getDouble(\"kDouble\")\n val myString = savedInstanceState.getString(\"kString\")\n // use variables here\n}\n</code></pre>\n"
},
{
"answer_id": 58032458,
"author": "Sana Ebadi",
"author_id": 10699119,
"author_profile": "https://Stackoverflow.com/users/10699119",
"pm_score": 2,
"selected": false,
"text": "<p>you can use the <code>Live Data</code> and <code>View Model</code> For L<code>ifecycle Handel</code> From <code>JetPack</code>. see this Reference :</p>\n\n<p><a href=\"https://developer.android.com/topic/libraries/architecture/livedata\" rel=\"nofollow noreferrer\">https://developer.android.com/topic/libraries/architecture/livedata</a></p>\n"
},
{
"answer_id": 58303964,
"author": "neelkanth_vyas",
"author_id": 9567585,
"author_profile": "https://Stackoverflow.com/users/9567585",
"pm_score": 2,
"selected": false,
"text": "<p>Instead of that, you should use ViewModel, which will retain the data until the activity life cycle.</p>\n"
},
{
"answer_id": 58485428,
"author": "IgniteCoders",
"author_id": 2835520,
"author_profile": "https://Stackoverflow.com/users/2835520",
"pm_score": 2,
"selected": false,
"text": "<p>There is a way to make Android save the states without implementing any method. Just add this line to your Manifest in Activity declaration:</p>\n\n<pre><code>android:configChanges=\"orientation|screenSize\"\n</code></pre>\n\n<p>It should look like this:</p>\n\n<pre><code><activity\n android:name=\".activities.MyActivity\"\n android:configChanges=\"orientation|screenSize\">\n</activity>\n</code></pre>\n\n<p><a href=\"https://developer.android.com/guide/topics/resources/runtime-changes\" rel=\"nofollow noreferrer\">Here</a> you can find more information about this property. </p>\n\n<p>It's recommended to let Android handle this for you than the manually handling.</p>\n"
},
{
"answer_id": 59262445,
"author": "Umut ADALI",
"author_id": 4300071,
"author_profile": "https://Stackoverflow.com/users/4300071",
"pm_score": 2,
"selected": false,
"text": "<p>Now it makes sense to do 2 ways in the view model.\nif you want to save the first as a saved instance:\nYou can add state parameter in view model like this\n<a href=\"https://developer.android.com/topic/libraries/architecture/viewmodel-savedstate#java\" rel=\"nofollow noreferrer\">https://developer.android.com/topic/libraries/architecture/viewmodel-savedstate#java</a></p>\n\n<p>or you can save variables or object in view model, in this case the view model will hold the life cycle until the activity is destroyed.</p>\n\n<pre><code>public class HelloAndroidViewModel extends ViewModel {\n public Booelan firstInit = false;\n\n public HelloAndroidViewModel() {\n firstInit = false;\n }\n ...\n}\n\npublic class HelloAndroid extends Activity {\n\n private TextView mTextView = null;\n HelloAndroidViewModel viewModel = ViewModelProviders.of(this).get(HelloAndroidViewModel.class);\n /** Called when the activity is first created. */\n @Override\n public void onCreate(Bundle savedInstanceState) {\n super.onCreate(savedInstanceState);\n\n mTextView = new TextView(this);\n\n //Because even if the state is deleted, the data in the viewmodel will be kept because the activity does not destroy\n if(!viewModel.firstInit){\n viewModel.firstInit = true\n mTextView.setText(\"Welcome to HelloAndroid!\");\n }else{\n mTextView.setText(\"Welcome back.\");\n }\n\n setContentView(mTextView);\n }\n}\n</code></pre>\n"
},
{
"answer_id": 62368924,
"author": "Jamil Hasnine Tamim",
"author_id": 6160172,
"author_profile": "https://Stackoverflow.com/users/6160172",
"pm_score": 2,
"selected": false,
"text": "<p><strong>Kotlin Solution:</strong>\nFor custom class save in <code>onSaveInstanceState</code> you can be converted your class to <code>JSON</code> string and restore it with <code>Gson</code> convertion and for single <code>String, Double, Int, Long</code> value save and restore as following. The following example is for <code>Fragment</code> and <code>Activity</code>:</p>\n\n<p><strong>For Activity:</strong></p>\n\n<p>For put data in <code>saveInstanceState</code>:</p>\n\n<pre><code>override fun onSaveInstanceState(outState: Bundle) {\n super.onSaveInstanceState(outState)\n\n //for custom class-----\n val gson = Gson()\n val json = gson.toJson(your_custom_class)\n outState.putString(\"CUSTOM_CLASS\", json)\n\n //for single value------\n outState.putString(\"MyString\", stringValue)\n outState.putBoolean(\"MyBoolean\", true)\n outState.putDouble(\"myDouble\", doubleValue)\n outState.putInt(\"MyInt\", intValue)\n }\n</code></pre>\n\n<p>Restore data:</p>\n\n<pre><code> override fun onRestoreInstanceState(savedInstanceState: Bundle) {\n super.onRestoreInstanceState(savedInstanceState)\n\n //for custom class restore\n val json = savedInstanceState?.getString(\"CUSTOM_CLASS\")\n if (!json!!.isEmpty()) {\n val gson = Gson()\n testBundle = gson.fromJson(json, Session::class.java)\n }\n\n //for single value restore\n\n val myBoolean: Boolean = savedInstanceState?.getBoolean(\"MyBoolean\")\n val myDouble: Double = savedInstanceState?.getDouble(\"myDouble\")\n val myInt: Int = savedInstanceState?.getInt(\"MyInt\")\n val myString: String = savedInstanceState?.getString(\"MyString\")\n }\n</code></pre>\n\n<p>You can restore it on Activity <code>onCreate</code> also.</p>\n\n<p><strong>For fragment:</strong></p>\n\n<p>For put class in <code>saveInstanceState</code>:</p>\n\n<pre><code> override fun onSaveInstanceState(outState: Bundle) {\n super.onSaveInstanceState(outState)\n val gson = Gson()\n val json = gson.toJson(customClass)\n outState.putString(\"CUSTOM_CLASS\", json)\n }\n</code></pre>\n\n<p>Restore data:</p>\n\n<pre><code> override fun onActivityCreated(savedInstanceState: Bundle?) {\n super.onActivityCreated(savedInstanceState)\n\n //for custom class restore\n if (savedInstanceState != null) {\n val json = savedInstanceState.getString(\"CUSTOM_CLASS\")\n if (!json!!.isEmpty()) {\n val gson = Gson()\n val customClass: CustomClass = gson.fromJson(json, CustomClass::class.java)\n }\n }\n\n // for single value restore\n val myBoolean: Boolean = savedInstanceState.getBoolean(\"MyBoolean\")\n val myDouble: Double = savedInstanceState.getDouble(\"myDouble\")\n val myInt: Int = savedInstanceState.getInt(\"MyInt\")\n val myString: String = savedInstanceState.getString(\"MyString\")\n }\n</code></pre>\n"
},
{
"answer_id": 64619764,
"author": "i30mb1",
"author_id": 9674249,
"author_profile": "https://Stackoverflow.com/users/9674249",
"pm_score": 2,
"selected": false,
"text": "<p>In 2020 we have some changes :</p>\n<p>If you want your <code>Activity</code> to restore its state after the process is killed and started again, you may want to use the “saved state” functionality. Previously, you needed to override two methods in the <code>Activity</code>: <code>onSaveInstanceState</code> and <code>onRestoreInstanceState</code>. You can also access the restored state in the <code>onCreate</code> method. Similarly, in <code>Fragment</code>, you have <code>onSaveInstanceState</code> method available (and the restored state is available in the <code>onCreate</code>, <code>onCreateView</code>, and <code>onActivityCreated</code> methods).</p>\n<p>Starting with <a href=\"https://developer.android.com/jetpack/androidx/releases/savedstate\" rel=\"nofollow noreferrer\">AndroidX SavedState 1.0.0</a>, which is the dependency of the <a href=\"https://developer.android.com/jetpack/androidx/releases/activity\" rel=\"nofollow noreferrer\">AndroidX Activity</a> and the <a href=\"https://developer.android.com/jetpack/androidx/releases/fragment\" rel=\"nofollow noreferrer\">AndroidX Fragment</a>, you get access to the <code>SavedStateRegistry</code>. You can obtain the <code>SavedStateRegistry</code> from the Activity/Fragment and then register your <code>SavedStateProvider</code> :</p>\n<pre><code>class MyActivity : AppCompatActivity() {\n\n companion object {\n private const val MY_SAVED_STATE_KEY = "MY_SAVED_STATE_KEY "\n private const val SOME_VALUE_KEY = "SOME_VALUE_KEY "\n }\n \n private lateinit var someValue: String\n private val savedStateProvider = SavedStateRegistry.SavedStateProvider { \n Bundle().apply {\n putString(SOME_VALUE_KEY, someValue)\n }\n }\n \n override fun onCreate(savedInstanceState: Bundle?) { \n super.onCreate(savedInstanceState)\n savedStateRegistry.registerSavedStateProvider(MY_SAVED_STATE_KEY, savedStateProvider)\n someValue = savedStateRegistry.consumeRestoredStateForKey(MY_SAVED_STATE_KEY)?.getString(SOME_VALUE_KEY) ?: ""\n }\n \n}\n</code></pre>\n<p>As you can see, <code>SavedStateRegistry</code> enforces you to use the key for your data. This can prevent your data from being corrupted by another <code>SavedStateProvider</code> attached to the same <code>Activity/Fragment</code>.Also you can extract your <code>SavedStateProvider</code> to another class to make it work with your data by using whatever abstraction you want and in such a way achieve the clean saved state behavior in your application.</p>\n"
},
{
"answer_id": 65560389,
"author": "Yessy",
"author_id": 6456129,
"author_profile": "https://Stackoverflow.com/users/6456129",
"pm_score": 2,
"selected": false,
"text": "<p>using Android ViewModel & SavedStateHandle to persist the serializable data</p>\n<pre><code>public class MainActivity extends AppCompatActivity {\n @Override\n protected void onCreate(Bundle savedInstanceState) {\n super.onCreate(savedInstanceState);\n ActivityMainBinding binding = ActivityMainBinding.inflate(getLayoutInflater());\n binding.setViewModel(new ViewModelProvider(this).get(ViewModel.class));\n binding.setLifecycleOwner(this);\n setContentView(binding.getRoot());\n }\n\n public static class ViewModel extends AndroidViewModel {\n\n //This field SURVIVE the background process reclaim/killing & the configuration change\n public final SavedStateHandle savedStateHandle;\n\n //This field NOT SURVIVE the background process reclaim/killing but SURVIVE the configuration change\n public final MutableLiveData<String> inputText2 = new MutableLiveData<>();\n\n\n public ViewModel(@NonNull Application application, SavedStateHandle savedStateHandle) {\n super(application);\n this.savedStateHandle = savedStateHandle;\n }\n }\n}\n</code></pre>\n<p>in layout file</p>\n<pre><code><?xml version="1.0" encoding="utf-8"?>\n<layout xmlns:android="http://schemas.android.com/apk/res/android">\n\n <data>\n\n <variable\n name="viewModel"\n type="com.xxx.viewmodelsavedstatetest.MainActivity.ViewModel" />\n </data>\n\n <LinearLayout xmlns:tools="http://schemas.android.com/tools"\n android:layout_width="match_parent"\n android:layout_height="match_parent"\n android:orientation="vertical"\n tools:context=".MainActivity">\n\n\n <EditText\n android:layout_width="match_parent"\n android:layout_height="wrap_content"\n android:autofillHints=""\n android:hint="This field SURVIVE the background process reclaim/killing &amp; the configuration change"\n android:text='@={(String)viewModel.savedStateHandle.getLiveData("activity_main/inputText", "")}' />\n\n <SeekBar\n android:layout_width="match_parent"\n android:layout_height="wrap_content"\n android:max="100"\n android:progress='@={(Integer)viewModel.savedStateHandle.getLiveData("activity_main/progress", 50)}' />\n\n <EditText\n android:layout_width="match_parent"\n android:layout_height="wrap_content"\n android:hint="This field SURVIVE the background process reclaim/killing &amp; the configuration change"\n android:text='@={(String)viewModel.savedStateHandle.getLiveData("activity_main/inputText", "")}' />\n\n <SeekBar\n android:layout_width="match_parent"\n android:layout_height="wrap_content"\n android:max="100"\n android:progress='@={(Integer)viewModel.savedStateHandle.getLiveData("activity_main/progress", 50)}' />\n\n <EditText\n android:layout_width="match_parent"\n android:layout_height="wrap_content"\n android:hint="This field NOT SURVIVE the background process reclaim/killing but SURVIVE the configuration change"\n android:text='@={viewModel.inputText2}' />\n\n </LinearLayout>\n</layout>\n</code></pre>\n<p>Test:</p>\n<pre><code>1. start the test activity\n2. press home key to go home\n3. adb shell kill <the test activity process>\n4. open recent app list and restart the test activity\n</code></pre>\n"
},
{
"answer_id": 70150508,
"author": "Mala Rupareliya",
"author_id": 6932387,
"author_profile": "https://Stackoverflow.com/users/6932387",
"pm_score": 2,
"selected": false,
"text": "<p>Now a days you can use live data and Life-cycle-Aware Components</p>\n<p><a href=\"https://developer.android.com/topic/libraries/architecture/lifecycle\" rel=\"nofollow noreferrer\">https://developer.android.com/topic/libraries/architecture/lifecycle</a></p>\n"
}
]
| 2008/09/30 | [
"https://Stackoverflow.com/questions/151777",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/61/"
]
| I've been working on the Android SDK platform, and it is a little unclear how to save an application's state. So given this minor re-tooling of the 'Hello, Android' example:
```java
package com.android.hello;
import android.app.Activity;
import android.os.Bundle;
import android.widget.TextView;
public class HelloAndroid extends Activity {
private TextView mTextView = null;
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
mTextView = new TextView(this);
if (savedInstanceState == null) {
mTextView.setText("Welcome to HelloAndroid!");
} else {
mTextView.setText("Welcome back.");
}
setContentView(mTextView);
}
}
```
I thought it would be enough for the simplest case, but it always responds with the first message, no matter how I navigate away from the app.
I'm sure the solution is as simple as overriding `onPause` or something like that, but I've been poking away in the documentation for 30 minutes or so and haven't found anything obvious. | You need to override `onSaveInstanceState(Bundle savedInstanceState)` and write the application state values you want to change to the `Bundle` parameter like this:
```
@Override
public void onSaveInstanceState(Bundle savedInstanceState) {
super.onSaveInstanceState(savedInstanceState);
// Save UI state changes to the savedInstanceState.
// This bundle will be passed to onCreate if the process is
// killed and restarted.
savedInstanceState.putBoolean("MyBoolean", true);
savedInstanceState.putDouble("myDouble", 1.9);
savedInstanceState.putInt("MyInt", 1);
savedInstanceState.putString("MyString", "Welcome back to Android");
// etc.
}
```
The Bundle is essentially a way of storing a NVP ("Name-Value Pair") map, and it will get passed in to `onCreate()` and also `onRestoreInstanceState()` where you would then extract the values from activity like this:
```
@Override
public void onRestoreInstanceState(Bundle savedInstanceState) {
super.onRestoreInstanceState(savedInstanceState);
// Restore UI state from the savedInstanceState.
// This bundle has also been passed to onCreate.
boolean myBoolean = savedInstanceState.getBoolean("MyBoolean");
double myDouble = savedInstanceState.getDouble("myDouble");
int myInt = savedInstanceState.getInt("MyInt");
String myString = savedInstanceState.getString("MyString");
}
```
Or from a fragment.
```
@Override
public void onViewStateRestored(@Nullable Bundle savedInstanceState) {
super.onViewStateRestored(savedInstanceState);
// Restore UI state from the savedInstanceState.
// This bundle has also been passed to onCreate.
boolean myBoolean = savedInstanceState.getBoolean("MyBoolean");
double myDouble = savedInstanceState.getDouble("myDouble");
int myInt = savedInstanceState.getInt("MyInt");
String myString = savedInstanceState.getString("MyString");
}
```
You would usually use this technique to store instance values for your application (selections, unsaved text, etc.). |
151,778 | <p>I'm making a mini ORM for a Java program I'm writing... there is a class for each table in my db, all inheriting from <code>ModelBase</code>.</p>
<p><code>ModelBase</code> is abstract & provides a bunch of static methods for finding & binding objects from the db, for example:</p>
<pre><code>public static ArrayList findAll(Class cast_to_class) {
//build the sql query & execute it
}
</code></pre>
<p>So you can do things like <code>ModelBase.findAll(Albums.class)</code> to get a list of all persisted albums.
My problem is that in this static context, I need to get the appropriate sql string from the concrete class Album. I can't have a static method like </p>
<pre><code>public class Album extends ModelBase {
public static String getSelectSQL() { return "select * from albums.....";}
}
</code></pre>
<p>because there is no polymorphism for static methods in Java. But I don't want to make <code>getSelectSQL()</code> an instance method in <code>Album</code> because then I need to create an instance of it just to get a string that is really static in behavior.</p>
<p>At the moment, <code>findAll()</code> uses reflection to get the appropriate sql for the class in question:</p>
<pre><code>select_sql = (String)cast_to_class.getDeclaredMethod("getSelectSql", new Class[]{} ).invoke(null, null);
</code></pre>
<p>But that's pretty gross. </p>
<p>So any ideas? It's a general problem I'm having time and time again - the inability to specify abstract static methods in classes or interfaces. I know <em>why</em> static method polymorphism doesn't and can't work, but that doesn't stop me from wanting to use it time again!</p>
<p>Is there any pattern/construct that allows me to ensure that concrete subclasses X and Y implement a class method(or failing that, a class constant!)?</p>
| [
{
"answer_id": 151791,
"author": "asterite",
"author_id": 20459,
"author_profile": "https://Stackoverflow.com/users/20459",
"pm_score": 0,
"selected": false,
"text": "<p>If you are passing a Class to findAll, why can't you pass a class to getSelectSQL in ModelBase?</p>\n"
},
{
"answer_id": 151796,
"author": "gizmo",
"author_id": 9396,
"author_profile": "https://Stackoverflow.com/users/9396",
"pm_score": 1,
"selected": false,
"text": "<p>Why not using annotations? They fitpretty well what you're doing: to add meta-information (here an SQL query) to a class.</p>\n"
},
{
"answer_id": 151854,
"author": "dalyons",
"author_id": 16925,
"author_profile": "https://Stackoverflow.com/users/16925",
"pm_score": 0,
"selected": false,
"text": "<p>asterite: do you mean that getSelectSQL exists only in ModelBase, and it uses the passed in class to make a tablename or something like that? \nI cant do that, because some of the Models have wildy differeing select constructs, so I cant use a universal \"select * from \" + classToTableName();. And any attempt to get information from the Models about their select construct runs into the same problem from the original question - you need an instance of the Model or some fancy reflection.</p>\n\n<p>gizmo: I will definatly have a look into annotations. Although I cant help but wonder what people did with these problems before there was reflection? </p>\n"
},
{
"answer_id": 151893,
"author": "Darren Greaves",
"author_id": 151,
"author_profile": "https://Stackoverflow.com/users/151",
"pm_score": 0,
"selected": false,
"text": "<p>You could have your SQL methods as instance methods in a separate class.<br>\nThen pass the model object into the constructor of this new class and call its methods for getting SQL.</p>\n"
},
{
"answer_id": 151944,
"author": "Tim Mooney",
"author_id": 15178,
"author_profile": "https://Stackoverflow.com/users/15178",
"pm_score": -1,
"selected": false,
"text": "<p>I agree with Gizmo: you're either looking at annotations or some sort of configuration file. I'd take a look at Hibernate and other ORM frameworks (and maybe even libraries like log4j!) to see how they handle loading of class-level meta-information.</p>\n\n<p>Not everything can or should be done programmatically, I feel this may be one of those cases.</p>\n"
},
{
"answer_id": 152108,
"author": "Ewan Makepeace",
"author_id": 9731,
"author_profile": "https://Stackoverflow.com/users/9731",
"pm_score": 0,
"selected": false,
"text": "<p>Wow - this is a far better example of something I asked previously in more general terms - how to implement properties or methods that are Static to each implementing class in a way that avoids duplication, provides Static access without needing to instantiate the class concerned and feels 'Right'.</p>\n\n<p>Short answer (Java or .NET): You can't.\nLonger answer - you can if you don't mind to use a Class level annotation (reflection) or instantiating an object (instance method) but neither are truly 'clean'.</p>\n\n<p>See my previous (related) question here: <a href=\"https://stackoverflow.com/questions/66505/how-to-handle-static-fields-that-vary-by-implementing-class\">How to handle static fields that vary by implementing class</a>\nI thought the answers were all really lame and missed the point. Your question is much better worded.</p>\n"
},
{
"answer_id": 152170,
"author": "Bruno De Fraine",
"author_id": 6918,
"author_profile": "https://Stackoverflow.com/users/6918",
"pm_score": 1,
"selected": false,
"text": "<p>As suggested, you could use annotations, or you could move the static methods to factory objects:</p>\n\n<pre><code>public abstract class BaseFactory<E> {\n public abstract String getSelectSQL();\n public List<E> findAll(Class<E> clazz) {\n // Use getSelectSQL();\n }\n}\n\npublic class AlbumFactory extends BaseFactory<Album> {\n public String getSelectSQL() { return \"select * from albums.....\"; }\n}\n</code></pre>\n\n<p>But it is not a very good smell to have objects without any state.</p>\n"
},
{
"answer_id": 153138,
"author": "DJClayworth",
"author_id": 19276,
"author_profile": "https://Stackoverflow.com/users/19276",
"pm_score": 2,
"selected": false,
"text": "<p>Static is the wrong thing to be using here. </p>\n\n<p>Conceptually static is wrong because it's only for services that don't correspond to an an actual object, physical or conceptual. You have a number of tables, and each should be represented by an actual object in the system, not just be a class. That sounds like it's a bit theoretical but it has actual consequences, as we'll see.</p>\n\n<p>Each table is of a different class, and that's OK. Since you can only ever have one of each table, limit the number of instances of each class to one (use a flag - don't make it a Singleton). Make the program create an instance of the class before it accesses the table. </p>\n\n<p>Now you have a couple of advantages. You can use the full power of inheritance and overriding since your methods are no longer static. You can use the constructor to do any initialisation, including associating SQL with the table (SQL that your methods can use later). This should make all your problems above go away, or at least get much simpler.</p>\n\n<p>It seems like there is extra work in having to create the object, and extra memory, but it's really trivial compared with the advantages. A few bytes of memory for the object won't be noticed, and a handful of constructor calls will take maybe ten minutes to add. Against that is the advantage that code to initialise any tables doesn't need to be run if the table isn't used (the constructor shouldn't be called). You will find it simplifies things a lot.</p>\n"
},
{
"answer_id": 154057,
"author": "OscarRyz",
"author_id": 20654,
"author_profile": "https://Stackoverflow.com/users/20654",
"pm_score": 3,
"selected": true,
"text": "<p>Albeit, I totally agree in the point of \"Static is the wrong thing to be using here\", I kind of understand what you're trying to address here. Still instance behavior should be the way to work, but if you insist this is what I would do:</p>\n\n<p>Starting from your comment \"I need to create an instance of it just to get a string that is really static in behaviour\" </p>\n\n<p>It is not completely correct. If you look well, you are not changing the behavior of your base class, just changing the parameter for a method. In other words you're changing the data, not the algorithm.</p>\n\n<p>Inheritance is more useful when a new subclass wants to change the way a method works, if you just need to change the \"data\" the class uses to work probably an approach like this would do the trick.</p>\n\n<pre><code>class ModelBase {\n // Initialize the queries\n private static Map<String,String> selectMap = new HashMap<String,String>(); static {\n selectMap.put( \"Album\", \"select field_1, field_2 from album\");\n selectMap.put( \"Artist\", \"select field_1, field_2 from artist\");\n selectMap.put( \"Track\", \"select field_1, field_2 from track\");\n }\n\n // Finds all the objects for the specified class...\n // Note: it is better to use \"List\" rather than \"ArrayList\" I'll explain this later.\n public static List findAll(Class classToFind ) {\n String sql = getSelectSQL( classToFind );\n results = execute( sql );\n //etc...\n return ....\n }\n\n // Return the correct select sql..\n private static String getSelectSQL( Class classToFind ){\n String statement = tableMap.get( classToFind.getSimpleName() );\n if( statement == null ) {\n throw new IllegalArgumentException(\"Class \" + \n classToFind.getSimpleName + \" is not mapped\");\n }\n return statement;\n\n }\n}\n</code></pre>\n\n<p>That is, map all the statements with a Map. The \"obvious\" next step to this is to load the map from an external resource, such as a properties file, or a xml or even ( why not ) a database table, for extra flexibility.</p>\n\n<p>This way you can keep your class clients ( and your self ) happy, because you don't needed \"creating an instance\" to do the work.</p>\n\n<pre><code>// Client usage:\n\n...\nList albums = ModelBase.findAll( Album.class );\n</code></pre>\n\n<p>...</p>\n\n<p>Another approach is to create the instances from behind, and keep your client interface intact while using instance methods, the methods are marked as \"protected\" to avoid having external invocation. In a similar fashion of the previous sample you can also do this</p>\n\n<pre><code>// Second option, instance used under the hood.\nclass ModelBase {\n // Initialize the queries\n private static Map<String,ModelBase> daoMap = new HashMap<String,ModelBase>(); static {\n selectMap.put( \"Album\", new AlbumModel() );\n selectMap.put( \"Artist\", new ArtistModel());\n selectMap.put( \"Track\", new TrackModel());\n }\n\n // Finds all the objects for the specified class...\n // Note: it is better to use \"List\" rather than \"ArrayList\" I'll explain this later.\n public static List findAll(Class classToFind ) {\n String sql = getSelectSQL( classToFind );\n results = execute( sql );\n //etc...\n return ....\n }\n\n // Return the correct select sql..\n private static String getSelectSQL( Class classToFind ){\n ModelBase dao = tableMap.get( classToFind.getSimpleName() );\n if( statement == null ) {\n throw new IllegalArgumentException(\"Class \" + \n classToFind.getSimpleName + \" is not mapped\");\n }\n return dao.selectSql();\n }\n // Instance class to be overrided... \n // this is \"protected\" ... \n protected abstract String selectSql();\n}\nclass AlbumModel extends ModelBase {\n public String selectSql(){\n return \"select ... from album\";\n }\n}\nclass ArtistModel extends ModelBase {\n public String selectSql(){\n return \"select ... from artist\";\n }\n}\nclass TrackModel extends ModelBase {\n public String selectSql(){\n return \"select ... from track\";\n }\n}\n</code></pre>\n\n<p>And you don't need to change the client code, and still have the power of polymorphism.</p>\n\n<pre><code>// Client usage:\n\n...\nList albums = ModelBase.findAll( Album.class ); // Does not know , behind the scenes you use instances.\n</code></pre>\n\n<p>...</p>\n\n<p>I hope this helps.</p>\n\n<p>A final note on using List vs. ArrayList. It is always better to program to the interface than to the implementation, this way you make your code more flexible. You can use another List implementation that is faster, or does something else, without changing your client code.</p>\n"
}
]
| 2008/09/30 | [
"https://Stackoverflow.com/questions/151778",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/16925/"
]
| I'm making a mini ORM for a Java program I'm writing... there is a class for each table in my db, all inheriting from `ModelBase`.
`ModelBase` is abstract & provides a bunch of static methods for finding & binding objects from the db, for example:
```
public static ArrayList findAll(Class cast_to_class) {
//build the sql query & execute it
}
```
So you can do things like `ModelBase.findAll(Albums.class)` to get a list of all persisted albums.
My problem is that in this static context, I need to get the appropriate sql string from the concrete class Album. I can't have a static method like
```
public class Album extends ModelBase {
public static String getSelectSQL() { return "select * from albums.....";}
}
```
because there is no polymorphism for static methods in Java. But I don't want to make `getSelectSQL()` an instance method in `Album` because then I need to create an instance of it just to get a string that is really static in behavior.
At the moment, `findAll()` uses reflection to get the appropriate sql for the class in question:
```
select_sql = (String)cast_to_class.getDeclaredMethod("getSelectSql", new Class[]{} ).invoke(null, null);
```
But that's pretty gross.
So any ideas? It's a general problem I'm having time and time again - the inability to specify abstract static methods in classes or interfaces. I know *why* static method polymorphism doesn't and can't work, but that doesn't stop me from wanting to use it time again!
Is there any pattern/construct that allows me to ensure that concrete subclasses X and Y implement a class method(or failing that, a class constant!)? | Albeit, I totally agree in the point of "Static is the wrong thing to be using here", I kind of understand what you're trying to address here. Still instance behavior should be the way to work, but if you insist this is what I would do:
Starting from your comment "I need to create an instance of it just to get a string that is really static in behaviour"
It is not completely correct. If you look well, you are not changing the behavior of your base class, just changing the parameter for a method. In other words you're changing the data, not the algorithm.
Inheritance is more useful when a new subclass wants to change the way a method works, if you just need to change the "data" the class uses to work probably an approach like this would do the trick.
```
class ModelBase {
// Initialize the queries
private static Map<String,String> selectMap = new HashMap<String,String>(); static {
selectMap.put( "Album", "select field_1, field_2 from album");
selectMap.put( "Artist", "select field_1, field_2 from artist");
selectMap.put( "Track", "select field_1, field_2 from track");
}
// Finds all the objects for the specified class...
// Note: it is better to use "List" rather than "ArrayList" I'll explain this later.
public static List findAll(Class classToFind ) {
String sql = getSelectSQL( classToFind );
results = execute( sql );
//etc...
return ....
}
// Return the correct select sql..
private static String getSelectSQL( Class classToFind ){
String statement = tableMap.get( classToFind.getSimpleName() );
if( statement == null ) {
throw new IllegalArgumentException("Class " +
classToFind.getSimpleName + " is not mapped");
}
return statement;
}
}
```
That is, map all the statements with a Map. The "obvious" next step to this is to load the map from an external resource, such as a properties file, or a xml or even ( why not ) a database table, for extra flexibility.
This way you can keep your class clients ( and your self ) happy, because you don't needed "creating an instance" to do the work.
```
// Client usage:
...
List albums = ModelBase.findAll( Album.class );
```
...
Another approach is to create the instances from behind, and keep your client interface intact while using instance methods, the methods are marked as "protected" to avoid having external invocation. In a similar fashion of the previous sample you can also do this
```
// Second option, instance used under the hood.
class ModelBase {
// Initialize the queries
private static Map<String,ModelBase> daoMap = new HashMap<String,ModelBase>(); static {
selectMap.put( "Album", new AlbumModel() );
selectMap.put( "Artist", new ArtistModel());
selectMap.put( "Track", new TrackModel());
}
// Finds all the objects for the specified class...
// Note: it is better to use "List" rather than "ArrayList" I'll explain this later.
public static List findAll(Class classToFind ) {
String sql = getSelectSQL( classToFind );
results = execute( sql );
//etc...
return ....
}
// Return the correct select sql..
private static String getSelectSQL( Class classToFind ){
ModelBase dao = tableMap.get( classToFind.getSimpleName() );
if( statement == null ) {
throw new IllegalArgumentException("Class " +
classToFind.getSimpleName + " is not mapped");
}
return dao.selectSql();
}
// Instance class to be overrided...
// this is "protected" ...
protected abstract String selectSql();
}
class AlbumModel extends ModelBase {
public String selectSql(){
return "select ... from album";
}
}
class ArtistModel extends ModelBase {
public String selectSql(){
return "select ... from artist";
}
}
class TrackModel extends ModelBase {
public String selectSql(){
return "select ... from track";
}
}
```
And you don't need to change the client code, and still have the power of polymorphism.
```
// Client usage:
...
List albums = ModelBase.findAll( Album.class ); // Does not know , behind the scenes you use instances.
```
...
I hope this helps.
A final note on using List vs. ArrayList. It is always better to program to the interface than to the implementation, this way you make your code more flexible. You can use another List implementation that is faster, or does something else, without changing your client code. |
151,800 | <p>Given a database field named "widget_ids", containing data like "67/797/124/" or "45/", where the numbers are slash separated widget_ids... how would you make an update statement with SQL that would say:
"if the widget_ids of the row with id X contains the text "somenumber/" do nothing, otherwise append "somenumber/" to it's current value"</p>
<p>Can you do something like that with SQL, or more specifically, sqlite? Is that something that is better done in the program for some reason or is there support for "if-then" like syntax in SQL?</p>
| [
{
"answer_id": 151829,
"author": "Logan",
"author_id": 3518,
"author_profile": "https://Stackoverflow.com/users/3518",
"pm_score": 4,
"selected": true,
"text": "<p>Updates are kind of like if-thens themselves, and there is also if-then support of some sort in most SQL implementations. A simple solution might be:</p>\n\n<pre><code>update <tablename>\n set widget_id = widget_id + \"somenumber/\"\n where row_id = X\n and widget_id not like \"%/somenumber/%\"\n and widget_id not like \"somenumber/%\";\n</code></pre>\n"
},
{
"answer_id": 151949,
"author": "Bill Karwin",
"author_id": 20860,
"author_profile": "https://Stackoverflow.com/users/20860",
"pm_score": 2,
"selected": false,
"text": "<p>First, get rid of the symbol-separated list. Use another table, with one widget id per row.</p>\n\n<pre><code>CREATE TABLE ThingieWidgets (\n thingie_id INT REFERENCES Thingies,\n widget_id INT REFERENCES Widgets,\n PRIMARY KEY(thingie_id, widget_id)\n);\n</code></pre>\n\n<p>Fill the table with values from the slash-separated list:</p>\n\n<pre><code>INSERT INTO ThingieWidgets (thingie_id, widget_id)\n VALUES (1234, 67), (1234, 797), (1234, 124);\n</code></pre>\n\n<p>Now you can test if Thingie 1234 references Widget 45:</p>\n\n<pre><code>SELECT * FROM ThingieWidgets\nWHERE thingie_id = 1234 AND widget_id = 45;\n</code></pre>\n\n<p>You can try to insert and recover if there's a duplicate key error:</p>\n\n<pre><code>INSERT INTO ThingieWidgets (thingie_id, widget_id)\n VALUES (1234, 45);\n</code></pre>\n"
}
]
| 2008/09/30 | [
"https://Stackoverflow.com/questions/151800",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/14278/"
]
| Given a database field named "widget\_ids", containing data like "67/797/124/" or "45/", where the numbers are slash separated widget\_ids... how would you make an update statement with SQL that would say:
"if the widget\_ids of the row with id X contains the text "somenumber/" do nothing, otherwise append "somenumber/" to it's current value"
Can you do something like that with SQL, or more specifically, sqlite? Is that something that is better done in the program for some reason or is there support for "if-then" like syntax in SQL? | Updates are kind of like if-thens themselves, and there is also if-then support of some sort in most SQL implementations. A simple solution might be:
```
update <tablename>
set widget_id = widget_id + "somenumber/"
where row_id = X
and widget_id not like "%/somenumber/%"
and widget_id not like "somenumber/%";
``` |
151,841 | <p>I'd like to document what high-level (i.e. C++ not inline assembler ) functions or macros are available for Compare And Swap (CAS) atomic primitives... </p>
<p>E.g., WIN32 on x86 has a family of functions <code>_InterlockedCompareExchange</code> in the <code><_intrin.h></code> header.</p>
| [
{
"answer_id": 151847,
"author": "Michael Burr",
"author_id": 12711,
"author_profile": "https://Stackoverflow.com/users/12711",
"pm_score": 5,
"selected": true,
"text": "<p>I'll let others list the various platform-specific APIs, but for future reference in C++09 you'll get the </p>\n\n<pre><code>atomic_compare_exchange() \n</code></pre>\n\n<p>operation in the new \"Atomic operations library\".</p>\n"
},
{
"answer_id": 151859,
"author": "Christian.K",
"author_id": 21567,
"author_profile": "https://Stackoverflow.com/users/21567",
"pm_score": 2,
"selected": false,
"text": "<p>On Solaris there is \"atomic.h\" (i.e. <a href=\"http://src.opensolaris.org/source/xref/onnv/onnv-gate/usr/src/uts/common/sys/atomic.h\" rel=\"nofollow noreferrer\"><sys/atomic.h></a>).</p>\n"
},
{
"answer_id": 151924,
"author": "Don Neufeld",
"author_id": 13097,
"author_profile": "https://Stackoverflow.com/users/13097",
"pm_score": 2,
"selected": false,
"text": "<p>MacOS X has <a href=\"http://developer.apple.com/documentation/Darwin/Reference/KernelIOKitFramework/OSAtomic/CompositePage.html\" rel=\"nofollow noreferrer\">OSAtomic.h</a></p>\n"
},
{
"answer_id": 151970,
"author": "C. K. Young",
"author_id": 13,
"author_profile": "https://Stackoverflow.com/users/13",
"pm_score": 3,
"selected": false,
"text": "<p>GCC has some <a href=\"http://gcc.gnu.org/onlinedocs/gcc-4.3.0/gcc/Atomic-Builtins.html\" rel=\"nofollow noreferrer\">built-ins for atomic accesses</a>, too.</p>\n"
},
{
"answer_id": 151988,
"author": "Andreas Petersson",
"author_id": 16542,
"author_profile": "https://Stackoverflow.com/users/16542",
"pm_score": 1,
"selected": false,
"text": "<p>java has this CAS operation, too</p>\n\n<p>see <a href=\"http://java.sun.com/javase/6/docs/api/java/util/concurrent/atomic/AtomicReferenceFieldUpdater.html#compareAndSet(java.lang.Object,java.lang.Object,java.lang.Object)\" rel=\"nofollow noreferrer\">here</a></p>\n\n<p>there are practical uses for this, like a <a href=\"http://video.google.com/videoplay?docid=2139967204534450862&ei=h8jhSM61N6Ky2gKK2LydCw&q=hashtable&emb=1\" rel=\"nofollow noreferrer\">lock-free hashtable</a> used in multiprocessor system</p>\n"
},
{
"answer_id": 152204,
"author": "Ben Combee",
"author_id": 1323,
"author_profile": "https://Stackoverflow.com/users/1323",
"pm_score": 3,
"selected": false,
"text": "<p>glib, a common system library on Linux and Unix systems (but also supported on Windows and Mac OS X), defines <a href=\"http://library.gnome.org/devel/glib/2.16/glib-Atomic-Operations.html\" rel=\"noreferrer\">several atomic operations</a>, including <strong>g_atomic_int_compare_and_exchange</strong> and <strong>g_atomic_pointer_compare_and_exchange</strong>.</p>\n"
},
{
"answer_id": 1694776,
"author": "seh",
"author_id": 31818,
"author_profile": "https://Stackoverflow.com/users/31818",
"pm_score": 2,
"selected": false,
"text": "<p>There have been a series of working group papers on this subject proposing changes to the C++ Standard Library. <a href=\"http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2007/n2427.html\" rel=\"nofollow noreferrer\">WG N2427</a> (<em>C++ Atomic Types and Operations</em>) is the most recent, which contributes to section 29 -- <em>Atomic operations library</em> -- of the pending standard.</p>\n"
}
]
| 2008/09/30 | [
"https://Stackoverflow.com/questions/151841",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/14069/"
]
| I'd like to document what high-level (i.e. C++ not inline assembler ) functions or macros are available for Compare And Swap (CAS) atomic primitives...
E.g., WIN32 on x86 has a family of functions `_InterlockedCompareExchange` in the `<_intrin.h>` header. | I'll let others list the various platform-specific APIs, but for future reference in C++09 you'll get the
```
atomic_compare_exchange()
```
operation in the new "Atomic operations library". |
151,846 | <p>This isn't as malicious as it sounds, I want to get the current size of their windows, not look at what is in them. The purpose is to figure out that if every other window is fullscreen then I should start up like that too. Or if all the other processes are only 800x600 despite there being a huge resolution then that is probably what the user wants. Why make them waste time and energy resizing my window to match all the others they have? I am primarily a Windows devoloper but it wouldn't upset me in the least if there was a cross platform way to do this.</p>
| [
{
"answer_id": 152094,
"author": "Swaroop C H",
"author_id": 4869,
"author_profile": "https://Stackoverflow.com/users/4869",
"pm_score": 2,
"selected": false,
"text": "<p>Check out the <a href=\"http://www.devx.com/opensource/Article/37773/1954\" rel=\"nofollow noreferrer\"><code>win32gui</code> module</a> in the Windows extensions for Python. It may provide some of the functionality you're looking for.</p>\n"
},
{
"answer_id": 152454,
"author": "DzinX",
"author_id": 18745,
"author_profile": "https://Stackoverflow.com/users/18745",
"pm_score": 5,
"selected": true,
"text": "<p>Using hints from <a href=\"http://www.devx.com/opensource/Article/37773/1954\" rel=\"noreferrer\">WindowMover article</a> and <a href=\"http://our.obor.us/?q=node/42\" rel=\"noreferrer\">Nattee Niparnan's blog post</a> I managed to create this:</p>\n\n<pre><code>import win32con\nimport win32gui\n\ndef isRealWindow(hWnd):\n '''Return True iff given window is a real Windows application window.'''\n if not win32gui.IsWindowVisible(hWnd):\n return False\n if win32gui.GetParent(hWnd) != 0:\n return False\n hasNoOwner = win32gui.GetWindow(hWnd, win32con.GW_OWNER) == 0\n lExStyle = win32gui.GetWindowLong(hWnd, win32con.GWL_EXSTYLE)\n if (((lExStyle & win32con.WS_EX_TOOLWINDOW) == 0 and hasNoOwner)\n or ((lExStyle & win32con.WS_EX_APPWINDOW != 0) and not hasNoOwner)):\n if win32gui.GetWindowText(hWnd):\n return True\n return False\n\ndef getWindowSizes():\n '''\n Return a list of tuples (handler, (width, height)) for each real window.\n '''\n def callback(hWnd, windows):\n if not isRealWindow(hWnd):\n return\n rect = win32gui.GetWindowRect(hWnd)\n windows.append((hWnd, (rect[2] - rect[0], rect[3] - rect[1])))\n windows = []\n win32gui.EnumWindows(callback, windows)\n return windows\n\nfor win in getWindowSizes():\n print win\n</code></pre>\n\n<p>You need the <a href=\"http://python.net/crew/mhammond/win32/Downloads.html\" rel=\"noreferrer\">Win32 Extensions for Python module</a> for this to work.</p>\n\n<p>EDIT: I discovered that <code>GetWindowRect</code> gives more correct results than <code>GetClientRect</code>. Source has been updated.</p>\n"
},
{
"answer_id": 155587,
"author": "Dustin Wyatt",
"author_id": 23972,
"author_profile": "https://Stackoverflow.com/users/23972",
"pm_score": 3,
"selected": false,
"text": "<p>I'm a big fan of <a href=\"http://www.autoitscript.com/autoit3/\" rel=\"noreferrer\">AutoIt</a>. They have a COM version which allows you to use most of their functions from Python.</p>\n\n<pre><code>import win32com.client\noAutoItX = win32com.client.Dispatch( \"AutoItX3.Control\" )\n\noAutoItX.Opt(\"WinTitleMatchMode\", 2) #Match text anywhere in a window title\n\nwidth = oAutoItX.WinGetClientSizeWidth(\"Firefox\")\nheight = oAutoItX.WinGetClientSizeHeight(\"Firefox\")\n\nprint width, height\n</code></pre>\n"
},
{
"answer_id": 60392234,
"author": "user3881450",
"author_id": 3881450,
"author_profile": "https://Stackoverflow.com/users/3881450",
"pm_score": 0,
"selected": false,
"text": "<p>I updated the GREAT @DZinX code adding the title/text of the windows:</p>\n\n<pre><code>import win32con\nimport win32gui\n\ndef isRealWindow(hWnd):\n #'''Return True iff given window is a real Windows application window.'''\n if not win32gui.IsWindowVisible(hWnd):\n return False\n if win32gui.GetParent(hWnd) != 0:\n return False\n hasNoOwner = win32gui.GetWindow(hWnd, win32con.GW_OWNER) == 0\nlExStyle = win32gui.GetWindowLong(hWnd, win32con.GWL_EXSTYLE)\nif (((lExStyle & win32con.WS_EX_TOOLWINDOW) == 0 and hasNoOwner)\n or ((lExStyle & win32con.WS_EX_APPWINDOW != 0) and not hasNoOwner)):\n if win32gui.GetWindowText(hWnd):\n return True\nreturn False\n\ndef getWindowSizes():\n\nReturn a list of tuples (handler, (width, height)) for each real window.\n'''\ndef callback(hWnd, windows):\n if not isRealWindow(hWnd):\n return\n rect = win32gui.GetWindowRect(hWnd)\n text = win32gui.GetWindowText(hWnd)\n windows.append((hWnd, (rect[2] - rect[0], rect[3] - rect[1]), text ))\nwindows = []\nwin32gui.EnumWindows(callback, windows)\nreturn windows\n\nfor win in getWindowSizes():\nprint(win)\n</code></pre>\n"
},
{
"answer_id": 69610455,
"author": "kalopseeia",
"author_id": 12622913,
"author_profile": "https://Stackoverflow.com/users/12622913",
"pm_score": 0,
"selected": false,
"text": "<p>I Modify someone code ,</p>\n<p>This well help to run other application and get PID ,</p>\n<pre><code>import win32process\nimport subprocess\nimport win32gui\nimport time \n \ndef get_hwnds_for_pid (pid):\n def callback (hwnd, hwnds):\n if win32gui.IsWindowVisible (hwnd) and win32gui.IsWindowEnabled (hwnd):\n _, found_pid = win32process.GetWindowThreadProcessId (hwnd)\n if found_pid == pid:\n hwnds.append (hwnd)\n return True\n \n hwnds = []\n win32gui.EnumWindows (callback, hwnds)\n return hwnds\n\n# This the process I want to get windows size. \nnotepad = subprocess.Popen ([r"C:\\\\Users\\\\dniwa\\\\Adb\\\\scrcpy.exe"]) \ntime.sleep (2.0)\n\nwhile True: \n for hwnd in get_hwnds_for_pid (notepad.pid):\n rect = win32gui.GetWindowRect(hwnd)\n print(hwnd, "=>", win32gui.GetWindowText (hwnd))\n\n # You need to test if your resolution really get exactly because mine is doesn't . \n # I use . 16:9 Monitor , Calculate the percent using this calculations , , (x * .0204082) and (y * .0115774)\n print((hwnd, (rect[2] - rect[0], rect[3] - rect[1])))\n x = rect[2] - rect[0]\n y = rect[3] - rect[1]\n print(type(x), type(y))\n time.sleep(1)\n</code></pre>\n"
}
]
| 2008/09/30 | [
"https://Stackoverflow.com/questions/151846",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3176/"
]
| This isn't as malicious as it sounds, I want to get the current size of their windows, not look at what is in them. The purpose is to figure out that if every other window is fullscreen then I should start up like that too. Or if all the other processes are only 800x600 despite there being a huge resolution then that is probably what the user wants. Why make them waste time and energy resizing my window to match all the others they have? I am primarily a Windows devoloper but it wouldn't upset me in the least if there was a cross platform way to do this. | Using hints from [WindowMover article](http://www.devx.com/opensource/Article/37773/1954) and [Nattee Niparnan's blog post](http://our.obor.us/?q=node/42) I managed to create this:
```
import win32con
import win32gui
def isRealWindow(hWnd):
'''Return True iff given window is a real Windows application window.'''
if not win32gui.IsWindowVisible(hWnd):
return False
if win32gui.GetParent(hWnd) != 0:
return False
hasNoOwner = win32gui.GetWindow(hWnd, win32con.GW_OWNER) == 0
lExStyle = win32gui.GetWindowLong(hWnd, win32con.GWL_EXSTYLE)
if (((lExStyle & win32con.WS_EX_TOOLWINDOW) == 0 and hasNoOwner)
or ((lExStyle & win32con.WS_EX_APPWINDOW != 0) and not hasNoOwner)):
if win32gui.GetWindowText(hWnd):
return True
return False
def getWindowSizes():
'''
Return a list of tuples (handler, (width, height)) for each real window.
'''
def callback(hWnd, windows):
if not isRealWindow(hWnd):
return
rect = win32gui.GetWindowRect(hWnd)
windows.append((hWnd, (rect[2] - rect[0], rect[3] - rect[1])))
windows = []
win32gui.EnumWindows(callback, windows)
return windows
for win in getWindowSizes():
print win
```
You need the [Win32 Extensions for Python module](http://python.net/crew/mhammond/win32/Downloads.html) for this to work.
EDIT: I discovered that `GetWindowRect` gives more correct results than `GetClientRect`. Source has been updated. |
151,850 | <p>In many languages, assignments are legal in conditions. I never understood the reason behind this. Why would you write:</p>
<pre><code>if (var1 = var2) {
...
}
</code></pre>
<p>instead of:</p>
<pre><code>var1 = var2;
if (var1) {
...
}
</code></pre>
<p>?</p>
| [
{
"answer_id": 151855,
"author": "Michael Burr",
"author_id": 12711,
"author_profile": "https://Stackoverflow.com/users/12711",
"pm_score": 5,
"selected": false,
"text": "<p>It can be useful if you're calling a function that returns either data to work on or a flag to indicate an error (or that you're done).</p>\n\n<p>Something like:</p>\n\n<pre><code>while ((c = getchar()) != EOF) {\n // process the character\n}\n\n// end of file reached...\n</code></pre>\n\n<p>Personally it's an idiom I'm not hugely fond of, but sometimes the alternative is uglier.</p>\n"
},
{
"answer_id": 151856,
"author": "Chris Young",
"author_id": 9417,
"author_profile": "https://Stackoverflow.com/users/9417",
"pm_score": 5,
"selected": false,
"text": "<p>It's more useful if you are calling a function:</p>\n\n<pre><code>if (n = foo())\n{\n /* foo returned a non-zero value, do something with the return value */\n} else {\n /* foo returned zero, do something else */\n}\n</code></pre>\n\n<p>Sure, you can just put the n = foo(); on a separate statement then if (n), but I think the above is a fairly readable idiom.</p>\n"
},
{
"answer_id": 151868,
"author": "Greg Hewgill",
"author_id": 893,
"author_profile": "https://Stackoverflow.com/users/893",
"pm_score": 3,
"selected": false,
"text": "<p>The idiom is more useful when you're writing a <code>while</code> loop instead of an <code>if</code> statement. For an <code>if</code> statement, you can break it up as you describe. But without this construct, you would either have to repeat yourself:</p>\n\n<pre><code>c = getchar();\nwhile (c != EOF) {\n // ...\n c = getchar();\n}\n</code></pre>\n\n<p>or use a loop-and-a-half structure:</p>\n\n<pre><code>while (true) {\n c = getchar();\n if (c == EOF) break;\n // ...\n}\n</code></pre>\n\n<p>I would usually prefer the loop-and-a-half form.</p>\n"
},
{
"answer_id": 151869,
"author": "JesperE",
"author_id": 13051,
"author_profile": "https://Stackoverflow.com/users/13051",
"pm_score": 4,
"selected": false,
"text": "<p>GCC can help you detect (with -Wall) if you unintentionally try to use an assignment as a truth value, in case it recommends you write</p>\n\n<pre><code>if ((n = foo())) {\n ...\n}\n</code></pre>\n\n<p>I.e. use extra parenthesis to indicate that this is really what you want.</p>\n"
},
{
"answer_id": 151870,
"author": "Gerald",
"author_id": 19404,
"author_profile": "https://Stackoverflow.com/users/19404",
"pm_score": 8,
"selected": true,
"text": "<p>It's more useful for loops than <em>if</em> statements.</p>\n<pre><code>while(var = GetNext())\n{\n ...do something with 'var' \n}\n</code></pre>\n<p>Which would otherwise have to be written</p>\n<pre><code>var = GetNext();\nwhile(var)\n{\n ...do something\n var = GetNext();\n}\n</code></pre>\n"
},
{
"answer_id": 151871,
"author": "Paige Ruten",
"author_id": 813,
"author_profile": "https://Stackoverflow.com/users/813",
"pm_score": 2,
"selected": false,
"text": "<p>In PHP, for example, it's useful for looping through SQL database results:</p>\n\n<pre><code>while ($row = mysql_fetch_assoc($result)) {\n // Display row\n}\n</code></pre>\n\n<p>This looks much better than:</p>\n\n<pre><code>$row = mysql_fetch_assoc($result);\nwhile ($row) {\n // Display row\n $row = mysql_fetch_assoc($result);\n}\n</code></pre>\n"
},
{
"answer_id": 151920,
"author": "Jonathan Leffler",
"author_id": 15168,
"author_profile": "https://Stackoverflow.com/users/15168",
"pm_score": 5,
"selected": false,
"text": "<p>I find it most useful in chains of actions which often involve error detection, etc.</p>\n\n<pre><code>if ((rc = first_check(arg1, arg2)) != 0)\n{\n report error based on rc\n}\nelse if ((rc = second_check(arg2, arg3)) != 0)\n{\n report error based on new rc\n}\nelse if ((rc = third_check(arg3, arg4)) != 0)\n{\n report error based on new rc\n}\nelse\n{\n do what you really wanted to do\n}\n</code></pre>\n\n<p>The alternative (not using the assignment in the condition) is:</p>\n\n<pre><code>rc = first_check(arg1, arg2);\nif (rc != 0)\n{\n report error based on rc\n}\nelse\n{\n rc = second_check(arg2, arg3);\n if (rc != 0)\n {\n report error based on new rc\n }\n else\n {\n rc = third_check(arg3, arg4);\n if (rc != 0)\n {\n report error based on new rc\n }\n else\n {\n do what you really wanted to do\n }\n }\n}\n</code></pre>\n\n<p>With protracted error checking, the alternative can run off the RHS of the page whereas the assignment-in-conditional version does not do that.</p>\n\n<p>The error checks could also be 'actions' — <code>first_action()</code>, <code>second_action()</code>, <code>third_action()</code> — of course, rather than just checks. That is, they could be checked steps in the process that the function is managing. (Most often in the code I work with, the functions are along the lines of pre-condition checks, or memory allocations needed for the function to work, or along similar lines).</p>\n"
},
{
"answer_id": 151990,
"author": "Hugh Allen",
"author_id": 15069,
"author_profile": "https://Stackoverflow.com/users/15069",
"pm_score": 2,
"selected": false,
"text": "<p>The short answer is that <a href=\"http://en.wikipedia.org/wiki/Expression-oriented_programming_languages\" rel=\"nofollow noreferrer\">expression-oriented</a> programming languages allow more succinct code. They don't force you to <a href=\"http://en.wikipedia.org/wiki/Command-query_separation\" rel=\"nofollow noreferrer\">separate commands from queries</a>.</p>\n"
},
{
"answer_id": 19288770,
"author": "plasmixs",
"author_id": 2648143,
"author_profile": "https://Stackoverflow.com/users/2648143",
"pm_score": 2,
"selected": false,
"text": "<p>The other advantage comes during the usage of <a href=\"https://en.wikipedia.org/wiki/GNU_Debugger\" rel=\"nofollow noreferrer\">GDB</a>.</p>\n<p>In the following code, the error code is not known if we were to single step.</p>\n<pre><code>while (checkstatus() != -1) {\n // Process\n}\n</code></pre>\n<p>Rather</p>\n<pre><code>while (true) {\n int error = checkstatus();\n if (error != -1)\n // Process\n else\n // Fail\n}\n</code></pre>\n<p>Now during single stepping, we can know what was the return error code from the checkstatus().</p>\n"
},
{
"answer_id": 40677085,
"author": "Gangadhar",
"author_id": 7178124,
"author_profile": "https://Stackoverflow.com/users/7178124",
"pm_score": -1,
"selected": false,
"text": "<p>The reason is:</p>\n<ol>\n<li><p>Performance improvement (sometimes)</p>\n</li>\n<li><p>Less code (always)</p>\n</li>\n</ol>\n<p>Take an example: There is a method <code>someMethod()</code> and in an <code>if</code> condition you want to check whether the return value of the method is <code>null</code>. If not, you are going to use the return value again.</p>\n<pre><code>If(null != someMethod()){\n String s = someMethod();\n ......\n //Use s\n}\n</code></pre>\n<p>It will hamper the performance since you are calling the same method twice. Instead use:</p>\n<pre><code>String s;\nIf(null != (s = someMethod())) {\n ......\n //Use s\n}\n</code></pre>\n"
},
{
"answer_id": 58999988,
"author": "Julien-L",
"author_id": 143504,
"author_profile": "https://Stackoverflow.com/users/143504",
"pm_score": 0,
"selected": false,
"text": "<p>I find it very useful with functions returning optionals (<code>boost::optional</code> or <code>std::optional</code> in C++17):</p>\n\n<pre><code>std::optional<int> maybe_int(); // function maybe returns an int\n\nif (auto i = maybe_int()) {\n use_int(*i);\n}\n</code></pre>\n\n<p>This reduces the scope of my variable, makes code more compact and does not hinder readability (I find).</p>\n\n<p>Same with pointers:</p>\n\n<pre><code>int* ptr_int();\n\nif (int* i = ptr_int()) {\n use_int(*i);\n}\n</code></pre>\n"
},
{
"answer_id": 67721528,
"author": "Priteem",
"author_id": 5160364,
"author_profile": "https://Stackoverflow.com/users/5160364",
"pm_score": 0,
"selected": false,
"text": "<p>I used it today while programing in Arduino (Subset of C++ language).</p>\n<h2>Case</h2>\n<p>I have a transmitter and a receiver.\nThe transmitter wants to send the data until it is received. I want to set a flag when the process is done.</p>\n<pre><code>while (!(newtork_joined = transmitter.send(data))) {\nSerial.println("Not Joined");\n}\n</code></pre>\n<p>Here:</p>\n<ul>\n<li>"transmitter.send" - returns true when the transmission is successful</li>\n<li>"newtork_joined " - is the flag I set when successful</li>\n</ul>\n<h2>Result</h2>\n<ol>\n<li><p>When the transmission is not successful, the flag is not set, while loop is true, it keeps executing</p>\n</li>\n<li><p>When successful, the flag is set, while loop is false, we exit</p>\n</li>\n</ol>\n<blockquote>\n<p>Isn't beautiful?</p>\n</blockquote>\n"
}
]
| 2008/09/30 | [
"https://Stackoverflow.com/questions/151850",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3740/"
]
| In many languages, assignments are legal in conditions. I never understood the reason behind this. Why would you write:
```
if (var1 = var2) {
...
}
```
instead of:
```
var1 = var2;
if (var1) {
...
}
```
? | It's more useful for loops than *if* statements.
```
while(var = GetNext())
{
...do something with 'var'
}
```
Which would otherwise have to be written
```
var = GetNext();
while(var)
{
...do something
var = GetNext();
}
``` |
151,872 | <p>I have a form where i have used Infragistics windows grid control to display the data.
In this, i have placed a button on one of the cell. I want to set its visibility either True or False based on the row condition.
I have handled the <strong>InitializeRow</strong> event of <strong>UltraWinGrid</strong> control and able to disable the button. But i am unable to set the button's visible to False.</p>
| [
{
"answer_id": 152634,
"author": "Christoffer Lette",
"author_id": 11808,
"author_profile": "https://Stackoverflow.com/users/11808",
"pm_score": 2,
"selected": false,
"text": "<pre><code>UltraGridRow row = ...\n\nrow.Cells[buttonCellIndex].Hidden = true;\n</code></pre>\n\n<p>(I'm using the <code>UltraGrid</code> in Infragistics NetAdvantage for Windows Forms 2008 Vol. 2 CLR 2.0.)</p>\n"
},
{
"answer_id": 404732,
"author": "LastBye",
"author_id": 50506,
"author_profile": "https://Stackoverflow.com/users/50506",
"pm_score": -1,
"selected": false,
"text": "<p>At first yo must achieve the row and cell ,\nthen use findControl method and assign that to a button ,\nnow the button is in your hand . you can set the visibility :)</p>\n"
}
]
| 2008/09/30 | [
"https://Stackoverflow.com/questions/151872",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
]
| I have a form where i have used Infragistics windows grid control to display the data.
In this, i have placed a button on one of the cell. I want to set its visibility either True or False based on the row condition.
I have handled the **InitializeRow** event of **UltraWinGrid** control and able to disable the button. But i am unable to set the button's visible to False. | ```
UltraGridRow row = ...
row.Cells[buttonCellIndex].Hidden = true;
```
(I'm using the `UltraGrid` in Infragistics NetAdvantage for Windows Forms 2008 Vol. 2 CLR 2.0.) |
151,874 | <p>I am working with web Dynpro java..
I have created a stateless session bean wherein I have created business methods for inserting and retrieving records from my dictionary table.
My table has two fields of <code>java.sql.Date</code> type
The web service that i have created is working fine for <code>insertRecords()</code>,
but for <code>showRecords()</code> I am not able to fetch the dates..</p>
<p>This is the following code I have applied..</p>
<pre><code>public WrapperClass[] showRecords()
{
ArrayList arr = new ArrayList();
WrapperClass model;
WrapperClass[] modelArr = null;
try {
InitialContext ctx = new InitialContext();
DataSource ds = (DataSource)ctx.lookup("jdbc/SAPSR3DB");
Connection conn = ds.getConnection();
PreparedStatement stmt = conn.prepareStatement("select * from TMP_DIC");
ResultSet rs = stmt.executeQuery();
while(rs.next())
{
model = new WrapperClass();
model.setTitle(rs.getString("TITLE"));
model.setStatus(rs.getString("STATUS"));
model.setSt_date(rs.getDate("START_DATE"));
model.setEnd_date(rs.getDate("END_DATE"));
arr.add(model);
//arr.add(rs.getString(2));
//arr.add(rs.getString(3));
}
modelArr = new WrapperClass[arr.size()];
for(int j=0;j<arr.size();j++)
{
model = (WrapperClass)arr.get(j);
modelArr[j] = model;
}
stmt.close();
conn.close();
} catch (NamingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
arr.toArray(modelArr);
return modelArr;
}
</code></pre>
<p>Can anybody please help..
Thanks
Ankita</p>
| [
{
"answer_id": 152645,
"author": "kolrie",
"author_id": 14540,
"author_profile": "https://Stackoverflow.com/users/14540",
"pm_score": 2,
"selected": false,
"text": "<p>Did you try getTimestamp() instead of getDate()? What is the error you get when you attempt to get it as a date?</p>\n"
},
{
"answer_id": 22613604,
"author": "sharkbait",
"author_id": 1353274,
"author_profile": "https://Stackoverflow.com/users/1353274",
"pm_score": 0,
"selected": false,
"text": "<p>I use another approach.</p>\n\n<p>I create in addition to the bean, also the services, where I create functions that contains the query to manipulate the DB tables.</p>\n\n<p>Now, in the Java Wb Dynpro I put something like this:</p>\n\n<pre><code>try {\n ctx = new InitialContext();\n\n Object o = ctx\n .lookup(\"sc.fiat.com/um~pers_app/LOCAL/UserServices/com.fiat.sc.um.pers.services.UserServicesLocal\");\n userServices = (UserServicesLocal) o;\n\n} catch (Exception e) {\n logger.traceThrowableT(Severity.ERROR, e.getMessage(), e);\n msgMgr.reportException(e);\n }\n</code></pre>\n\n<p>in the wdDoInit method. I also declare like this</p>\n\n<pre><code>private UserServicesLocal userServices;\n</code></pre>\n\n<p>the object.</p>\n\n<p>Now I will able to manipulate my DB tables calling methods of the services classes...</p>\n"
}
]
| 2008/09/30 | [
"https://Stackoverflow.com/questions/151874",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
]
| I am working with web Dynpro java..
I have created a stateless session bean wherein I have created business methods for inserting and retrieving records from my dictionary table.
My table has two fields of `java.sql.Date` type
The web service that i have created is working fine for `insertRecords()`,
but for `showRecords()` I am not able to fetch the dates..
This is the following code I have applied..
```
public WrapperClass[] showRecords()
{
ArrayList arr = new ArrayList();
WrapperClass model;
WrapperClass[] modelArr = null;
try {
InitialContext ctx = new InitialContext();
DataSource ds = (DataSource)ctx.lookup("jdbc/SAPSR3DB");
Connection conn = ds.getConnection();
PreparedStatement stmt = conn.prepareStatement("select * from TMP_DIC");
ResultSet rs = stmt.executeQuery();
while(rs.next())
{
model = new WrapperClass();
model.setTitle(rs.getString("TITLE"));
model.setStatus(rs.getString("STATUS"));
model.setSt_date(rs.getDate("START_DATE"));
model.setEnd_date(rs.getDate("END_DATE"));
arr.add(model);
//arr.add(rs.getString(2));
//arr.add(rs.getString(3));
}
modelArr = new WrapperClass[arr.size()];
for(int j=0;j<arr.size();j++)
{
model = (WrapperClass)arr.get(j);
modelArr[j] = model;
}
stmt.close();
conn.close();
} catch (NamingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
arr.toArray(modelArr);
return modelArr;
}
```
Can anybody please help..
Thanks
Ankita | Did you try getTimestamp() instead of getDate()? What is the error you get when you attempt to get it as a date? |
151,917 | <p>What is the best way to free resources (in this case unlock the ReadWriteLock) when leaving the scope ? How to cover all possible ways (return, break, exceptions etc)?</p>
| [
{
"answer_id": 151932,
"author": "Michael Barker",
"author_id": 6365,
"author_profile": "https://Stackoverflow.com/users/6365",
"pm_score": 5,
"selected": true,
"text": "<p>A try/finally block is the closest thing that you can get to this behaviour:</p>\n\n<pre><code>Lock l = new Lock();\nl.lock(); // Call the lock before calling try.\ntry {\n // Do some processing.\n // All code must go in here including break, return etc.\n return something;\n} finally {\n l.unlock();\n}\n</code></pre>\n"
},
{
"answer_id": 151962,
"author": "Daniel Hiller",
"author_id": 16193,
"author_profile": "https://Stackoverflow.com/users/16193",
"pm_score": 2,
"selected": false,
"text": "<p>Like mike said, a finally block should be your choice. see the <a href=\"http://java.sun.com/docs/books/tutorial/essential/exceptions/finally.html\" rel=\"nofollow noreferrer\">finally block tutorial</a>, where it is stated:</p>\n\n<blockquote>\n <p>The finally block <strong>always</strong> executes when\n the try block exits. This ensures that\n the finally block is executed even if\n an unexpected exception occurs.</p>\n</blockquote>\n"
},
{
"answer_id": 47512211,
"author": "Raúl Salinas-Monteagudo",
"author_id": 1691599,
"author_profile": "https://Stackoverflow.com/users/1691599",
"pm_score": 1,
"selected": false,
"text": "<p>A nicer way to do it is to use the try-with-resources statement, which lets you mimick C++'s <a href=\"https://en.wikipedia.org/wiki/Resource_acquisition_is_initialization\" rel=\"nofollow noreferrer\">RAII mechanism</a>:</p>\n\n<pre><code>public class MutexTests {\n\n static class Autolock implements AutoCloseable {\n Autolock(ReentrantLock lock) {\n this.mLock = lock;\n mLock.lock();\n }\n\n @Override\n public void close() {\n mLock.unlock();\n }\n\n private final ReentrantLock mLock;\n }\n\n public static void main(String[] args) throws InterruptedException {\n final ReentrantLock lock = new ReentrantLock();\n\n try (Autolock alock = new Autolock(lock)) {\n // Whatever you need to do while you own the lock\n }\n // Here, you have already released the lock, regardless of exceptions\n\n }\n\n}\n</code></pre>\n"
}
]
| 2008/09/30 | [
"https://Stackoverflow.com/questions/151917",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/18174/"
]
| What is the best way to free resources (in this case unlock the ReadWriteLock) when leaving the scope ? How to cover all possible ways (return, break, exceptions etc)? | A try/finally block is the closest thing that you can get to this behaviour:
```
Lock l = new Lock();
l.lock(); // Call the lock before calling try.
try {
// Do some processing.
// All code must go in here including break, return etc.
return something;
} finally {
l.unlock();
}
``` |
151,929 | <p>I'm using the <code>mechanize</code> module to execute some web queries from Python. I want my program to be error-resilient and handle all kinds of errors (wrong URLs, 403/404 responsese) gracefully. However, I can't find in mechanize's documentation the errors / exceptions it throws for various errors.</p>
<p>I just call it with:</p>
<pre><code> self.browser = mechanize.Browser()
self.browser.addheaders = [('User-agent', browser_header)]
self.browser.open(query_url)
self.result_page = self.browser.response().read()
</code></pre>
<p>How can I know what errors / exceptions can be thrown here and handle them ?</p>
| [
{
"answer_id": 151935,
"author": "Alexander Kojevnikov",
"author_id": 712,
"author_profile": "https://Stackoverflow.com/users/712",
"pm_score": 1,
"selected": false,
"text": "<p>I found this in their docs:</p>\n\n<blockquote>\n <p>One final thing to note is that there\n are some catch-all bare except:\n statements in the module, which are\n there to handle unexpected bad input\n without crashing your program. If this\n happens, it's a bug in mechanize, so\n please mail me the warning text.</p>\n</blockquote>\n\n<p>So I guess they don't raise any exceptions. You can also search the source code for Exception subclasses and see how they are used.</p>\n"
},
{
"answer_id": 155127,
"author": "jfs",
"author_id": 4279,
"author_profile": "https://Stackoverflow.com/users/4279",
"pm_score": 4,
"selected": true,
"text": "<pre><code>$ perl -0777 -ne'print qq($1) if /__all__ = \\[(.*?)\\]/s' __init__.py | grep Error \n\n'BrowserStateError',\n'ContentTooShortError',\n'FormNotFoundError',\n'GopherError',\n'HTTPDefaultErrorHandler',\n'HTTPError',\n'HTTPErrorProcessor',\n'LinkNotFoundError',\n'LoadError',\n'ParseError',\n'RobotExclusionError',\n'URLError',\n</code></pre>\n\n<p>Or:</p>\n\n<pre><code>>>> import mechanize\n>>> filter(lambda s: \"Error\" in s, dir(mechanize))\n['BrowserStateError', 'ContentTooShortError', 'FormNotFoundError', 'GopherError'\n, 'HTTPDefaultErrorHandler', 'HTTPError', 'HTTPErrorProcessor', 'LinkNotFoundErr\nor', 'LoadError', 'ParseError', 'RobotExclusionError', 'URLError']\n</code></pre>\n"
},
{
"answer_id": 4648973,
"author": "remote",
"author_id": 186467,
"author_profile": "https://Stackoverflow.com/users/186467",
"pm_score": 2,
"selected": false,
"text": "<p>While this has been posted a long time ago, I think there is still a need to answer the question correctly since it comes up in Google's search results for this very question.</p>\n\n<p>As I write this, mechanize (<strong>version</strong> = (0, 1, 11, None, None)) in Python 265 raises urllib2.HTTPError and so the http status is available through catching this exception, eg:</p>\n\n<pre><code>import urllib2\ntry:\n... br.open(\"http://www.example.org/invalid-page\")\n... except urllib2.HTTPError, e:\n... print e.code\n... \n404\n</code></pre>\n"
}
]
| 2008/09/30 | [
"https://Stackoverflow.com/questions/151929",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/8206/"
]
| I'm using the `mechanize` module to execute some web queries from Python. I want my program to be error-resilient and handle all kinds of errors (wrong URLs, 403/404 responsese) gracefully. However, I can't find in mechanize's documentation the errors / exceptions it throws for various errors.
I just call it with:
```
self.browser = mechanize.Browser()
self.browser.addheaders = [('User-agent', browser_header)]
self.browser.open(query_url)
self.result_page = self.browser.response().read()
```
How can I know what errors / exceptions can be thrown here and handle them ? | ```
$ perl -0777 -ne'print qq($1) if /__all__ = \[(.*?)\]/s' __init__.py | grep Error
'BrowserStateError',
'ContentTooShortError',
'FormNotFoundError',
'GopherError',
'HTTPDefaultErrorHandler',
'HTTPError',
'HTTPErrorProcessor',
'LinkNotFoundError',
'LoadError',
'ParseError',
'RobotExclusionError',
'URLError',
```
Or:
```
>>> import mechanize
>>> filter(lambda s: "Error" in s, dir(mechanize))
['BrowserStateError', 'ContentTooShortError', 'FormNotFoundError', 'GopherError'
, 'HTTPDefaultErrorHandler', 'HTTPError', 'HTTPErrorProcessor', 'LinkNotFoundErr
or', 'LoadError', 'ParseError', 'RobotExclusionError', 'URLError']
``` |
151,936 | <p>I have some code where I'm returning an array of objects.</p>
<p>Here's a simplified example:</p>
<pre><code>string[] GetTheStuff() {
List<string> s = null;
if( somePredicate() ) {
s = new List<string>(); // imagine we load some data or something
}
return (s == null) ?
new string[0] :
s.ToArray();
}
</code></pre>
<p>The question is, how expensive is the <code>new string[0]</code> ?<br />
Should I just return null and make the caller accept null as a valid way of indicating "nothing was found"?</p>
<p>NB: This is being called in a loop which gets run hundreds and hundreds of times, so it's one of the few cases where I think this kind of optimiziation is not actually 'premature'.</p>
<p>PS: And even if it was premature, I'd still like to know how it works :-)</p>
<h3>Update:</h3>
<p>Initially when I asked if it used any space, I was thinking of things from the 'C/C++' point of view, kind of like how in C, writing <code>char a[5];</code> will allocate 5 bytes of space on the stack, and <code>char b[0];</code> will allocate 0 bytes.</p>
<p>I realise this is not a good fit for the .NET world, but I was curious if this was something that the compiler or CLR would detect and optimize out, as a non-resizeable array of size zero really shouldn't (as far as I can see?) require any storage space.</p>
| [
{
"answer_id": 151939,
"author": "Matt Hamilton",
"author_id": 615,
"author_profile": "https://Stackoverflow.com/users/615",
"pm_score": 2,
"selected": false,
"text": "<p>I would guess that an empty array uses only the space needed to allocate the object pointer itself.</p>\n\n<p>From memory the API guidelines say that you should always return an empty array from a method that returns an array rather than returning null, so I'd leave your code the way it is regardless. That way the caller knows he's guaranteed to get an array (even an empty one) and need not check for null with each call.</p>\n\n<p>Edit: A link about returning empty arrays:</p>\n\n<p><a href=\"http://wesnerm.blogs.com/net_undocumented/2004/02/empty_arrays.html\" rel=\"nofollow noreferrer\">http://wesnerm.blogs.com/net_undocumented/2004/02/empty_arrays.html</a></p>\n"
},
{
"answer_id": 151941,
"author": "Jon Limjap",
"author_id": 372,
"author_profile": "https://Stackoverflow.com/users/372",
"pm_score": 3,
"selected": false,
"text": "<p>Declared arrays will always have to contain the following information:</p>\n\n<ul>\n<li>Rank (number of dimensions)</li>\n<li>Type to be contained</li>\n<li>Length of each dimension</li>\n</ul>\n\n<p>This would most likely be trivial, but for higher numbers of dimensions and higher lengths it <em>will</em> have a performance impact on loops.</p>\n\n<p>As for return types, I agree that an empty array should be returned instead of null.</p>\n\n<p>More information here: <a href=\"http://msdn.microsoft.com/en-us/magazine/cc301755.aspx\" rel=\"noreferrer\">Array Types in .NET</a></p>\n"
},
{
"answer_id": 151947,
"author": "Dr8k",
"author_id": 6014,
"author_profile": "https://Stackoverflow.com/users/6014",
"pm_score": 0,
"selected": false,
"text": "<p>If I understand correctly, a small amount of memory will be allocated for the string arrays. You code essentially requires a generic list to be created anyway, so why not just return that?</p>\n\n<p>[EDIT]Removed the version of the code that returned a null value. The other answers advising against null return values in this circumstance appear to be the better advice[/EDIT]</p>\n\n<pre><code>List<string> GetTheStuff()\n{\n List<string> s = new List<string();\n if (somePredicarte())\n {\n // more code\n }\n return s;\n}\n</code></pre>\n"
},
{
"answer_id": 151950,
"author": "Jon Skeet",
"author_id": 22656,
"author_profile": "https://Stackoverflow.com/users/22656",
"pm_score": 7,
"selected": true,
"text": "<p>Even if it's being called \"hundreds and hundreds\" of times, I'd say it's a premature optimization. If the result is clearer as an empty array, use that.</p>\n\n<p>Now for the actual answer: yes, an empty array takes some memory. It has the normal object overhead (8 bytes on x86, I believe) and 4 bytes for the count. I don't know whether there's anything beyond that, but it's not entirely free. (It <em>is</em> incredibly cheap though...)</p>\n\n<p>Fortunately, there's an optimization you can make without compromising the API itself: have a \"constant\" of an empty array. I've made another small change to make the code clearer, if you'll permit...</p>\n\n<pre><code>private static readonly string[] EmptyStringArray = new string[0];\n\nstring[] GetTheStuff() {\n if( somePredicate() ) {\n List<string> s = new List<string>(); \n // imagine we load some data or something\n return s.ToArray();\n } else {\n return EmptyStringArray;\n }\n}\n</code></pre>\n\n<p>If you find yourself needing this frequently, you could even create a generic class with a static member to return an empty array of the right type. The way .NET generics work makes this trivial:</p>\n\n<pre><code>public static class Arrays<T> {\n public static readonly Empty = new T[0];\n}\n</code></pre>\n\n<p>(You could wrap it in a property, of course.)</p>\n\n<p>Then just use: Arrays<string>.Empty;</p>\n\n<p>EDIT: I've just remembered <a href=\"http://blogs.msdn.com/ericlippert/archive/2008/09/22/arrays-considered-somewhat-harmful.aspx\" rel=\"noreferrer\">Eric Lippert's post on arrays</a>. Are you sure that an array is the most appropriate type to return?</p>\n"
},
{
"answer_id": 151958,
"author": "VVS",
"author_id": 21038,
"author_profile": "https://Stackoverflow.com/users/21038",
"pm_score": 2,
"selected": false,
"text": "<p>This is not a direct answer to your question.</p>\n\n<p>Read why <a href=\"http://blogs.msdn.com/ericlippert/archive/2008/09/22/arrays-considered-somewhat-harmful.aspx\" rel=\"nofollow noreferrer\">arrays are considered somewhat harmful</a>. I would suggest you to return an IList<string> in this case and restructure the code a little bit:</p>\n\n<pre><code>IList<string> GetTheStuff() {\n List<string> s = new List<string>();\n if( somePredicate() ) {\n // imagine we load some data or something\n }\n return s;\n}\n</code></pre>\n\n<p>In this way the caller doesn't have to care about empty return values.</p>\n\n<hr>\n\n<p><strong>EDIT</strong>: If the returned list should not be editable you can wrap the List inside a <a href=\"http://msdn.microsoft.com/en-us/library/ms132476.aspx\" rel=\"nofollow noreferrer\">ReadOnlyCollection</a>. Simply change the last line to. I also would consider this best practice.</p>\n\n<pre><code> return new ReadOnlyCollection(s);\n</code></pre>\n"
},
{
"answer_id": 152141,
"author": "Greg Beech",
"author_id": 13552,
"author_profile": "https://Stackoverflow.com/users/13552",
"pm_score": 2,
"selected": false,
"text": "<p>Yes, as others have said, the empty array takes up a few bytes for the object header and the length field.</p>\n\n<p>But if you're worried about performance you're focusing on the wrong branch of execution in this method. I'd be much more concerned about the <em>ToArray</em> call on the populated list which will result in a memory allocation equal to its internal size and a memory copy of the contents of the list into it.</p>\n\n<p>If you really want to improve performance then (if possible) return the list directly by making the return type one of: <code>List<T>, IList<T>, ICollection<T>, IEnumerable<T></code> depending on what facilities you need from it (note that less specific is better in the general case).</p>\n"
},
{
"answer_id": 553975,
"author": "Drew Noakes",
"author_id": 24874,
"author_profile": "https://Stackoverflow.com/users/24874",
"pm_score": 2,
"selected": false,
"text": "<p>Others have answered your question nicely. So just a simple point to make...</p>\n\n<p>I'd avoid returning an array (unless you can't). Stick with IEnumerable and then you can use <code>Enumerable.Empty<T>()</code> from the LINQ APIs. Obviously Microsoft have optimised this scenario for you.</p>\n\n<pre><code>IEnumerable<string> GetTheStuff()\n{\n List<string> s = null;\n if (somePredicate())\n {\n var stuff = new List<string>();\n // load data\n return stuff;\n }\n\n return Enumerable.Empty<string>();\n}\n</code></pre>\n"
},
{
"answer_id": 30405133,
"author": "Jeppe Stig Nielsen",
"author_id": 1336654,
"author_profile": "https://Stackoverflow.com/users/1336654",
"pm_score": 3,
"selected": false,
"text": "<p>The upcoming version 4.6 of .NET (later in 2015) contains <a href=\"https://msdn.microsoft.com/en-us/library/dn906179.aspx\" rel=\"noreferrer\">a static method</a> returning a length-zero <code>string[]</code>:</p>\n\n<pre><code>Array.Empty<string>()\n</code></pre>\n\n<p>I suppose it returns the same instance if called many times.</p>\n"
},
{
"answer_id": 51593741,
"author": "Yitzchak",
"author_id": 2830676,
"author_profile": "https://Stackoverflow.com/users/2830676",
"pm_score": 2,
"selected": false,
"text": "<p>I know this is old question, but it's a basic question and I needed a detailed answer.</p>\n\n<p>So I explored this and got results:</p>\n\n<p>In .Net when you create an array (for this example I use <code>int[]</code>) you take <strong>6 bytes</strong> before any memory is allocated for your data.</p>\n\n<p>Consider this code [In a <strong>32 bit</strong> application!]:</p>\n\n<pre><code>int[] myArray = new int[0];\nint[] myArray2 = new int[1];\nchar[] myArray3 = new char[0];\n</code></pre>\n\n<p>And look at the memory:</p>\n\n<pre><code>myArray: a8 1a 8f 70 00 00 00 00 00 00 00 00\nmyArray2: a8 1a 8f 70 01 00 00 00 00 00 00 00 00 00 00 00\nmyArray3: 50 06 8f 70 00 00 00 00 00 00 00 00\n</code></pre>\n\n<hr>\n\n<h2>Lets explain that memory:</h2>\n\n<ul>\n<li>Looks like the first 2 bytes are some kind of metadata, as you can see it changes between <code>int[]</code> and <code>char[]</code> <strong>(</strong><code>a8 1a 8f 70</code> <strong>vs</strong> <code>50 06 8f 70</code><strong>)</strong></li>\n<li>Then it holds the size of the array in integer variable (little endian). so it's <code>00 00 00 00</code> for <code>myArray</code> and <code>01 00 00 00</code> for <code>myArray2</code></li>\n<li><strong>Now it's our precious Data</strong> [I tested with <strong>Immediate Window</strong>]</li>\n<li>After that we see a constant (<code>00 00 00 00</code>). I don't know what its meaning.</li>\n</ul>\n\n<hr>\n\n<blockquote>\n <p><strong>Now I feel a lot better about zero length array, I know how it works</strong>\n <strong>=]</strong></p>\n</blockquote>\n"
}
]
| 2008/09/30 | [
"https://Stackoverflow.com/questions/151936",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/234/"
]
| I have some code where I'm returning an array of objects.
Here's a simplified example:
```
string[] GetTheStuff() {
List<string> s = null;
if( somePredicate() ) {
s = new List<string>(); // imagine we load some data or something
}
return (s == null) ?
new string[0] :
s.ToArray();
}
```
The question is, how expensive is the `new string[0]` ?
Should I just return null and make the caller accept null as a valid way of indicating "nothing was found"?
NB: This is being called in a loop which gets run hundreds and hundreds of times, so it's one of the few cases where I think this kind of optimiziation is not actually 'premature'.
PS: And even if it was premature, I'd still like to know how it works :-)
### Update:
Initially when I asked if it used any space, I was thinking of things from the 'C/C++' point of view, kind of like how in C, writing `char a[5];` will allocate 5 bytes of space on the stack, and `char b[0];` will allocate 0 bytes.
I realise this is not a good fit for the .NET world, but I was curious if this was something that the compiler or CLR would detect and optimize out, as a non-resizeable array of size zero really shouldn't (as far as I can see?) require any storage space. | Even if it's being called "hundreds and hundreds" of times, I'd say it's a premature optimization. If the result is clearer as an empty array, use that.
Now for the actual answer: yes, an empty array takes some memory. It has the normal object overhead (8 bytes on x86, I believe) and 4 bytes for the count. I don't know whether there's anything beyond that, but it's not entirely free. (It *is* incredibly cheap though...)
Fortunately, there's an optimization you can make without compromising the API itself: have a "constant" of an empty array. I've made another small change to make the code clearer, if you'll permit...
```
private static readonly string[] EmptyStringArray = new string[0];
string[] GetTheStuff() {
if( somePredicate() ) {
List<string> s = new List<string>();
// imagine we load some data or something
return s.ToArray();
} else {
return EmptyStringArray;
}
}
```
If you find yourself needing this frequently, you could even create a generic class with a static member to return an empty array of the right type. The way .NET generics work makes this trivial:
```
public static class Arrays<T> {
public static readonly Empty = new T[0];
}
```
(You could wrap it in a property, of course.)
Then just use: Arrays<string>.Empty;
EDIT: I've just remembered [Eric Lippert's post on arrays](http://blogs.msdn.com/ericlippert/archive/2008/09/22/arrays-considered-somewhat-harmful.aspx). Are you sure that an array is the most appropriate type to return? |
151,945 | <p>Emacs puts backup files named <code>foo~</code> everywhere and I don't like having to remember to delete them. Also, if I edit a file that has a hard link somewhere else in the file system, the hard link points to the backup when I'm done editing, and that's confusing and awful. How can I either eliminate these backup files, or have them go somewhere other than the same directory?</p>
| [
{
"answer_id": 151946,
"author": "jfm3",
"author_id": 11138,
"author_profile": "https://Stackoverflow.com/users/11138",
"pm_score": 10,
"selected": true,
"text": "<p>If you've ever been saved by an Emacs backup file, you\nprobably want more of them, not less of them. It is annoying\nthat they go in the same directory as the file you're editing,\nbut that is easy to change. You can make all backup files go\ninto a directory by putting something like the following in your\n<code>.emacs</code>.</p>\n\n<pre class=\"lang-lisp prettyprint-override\"><code>(setq backup-directory-alist `((\".\" . \"~/.saves\")))\n</code></pre>\n\n<p>There are a number of arcane details associated with how Emacs\nmight create your backup files. Should it rename the original\nand write out the edited buffer? What if the original is linked?\nIn general, the safest but slowest bet is to always make backups\nby copying.</p>\n\n<pre class=\"lang-lisp prettyprint-override\"><code>(setq backup-by-copying t)\n</code></pre>\n\n<p>If that's too slow for some reason you might also have a look at\n<code>backup-by-copying-when-linked</code>.</p>\n\n<p>Since your backups are all in their own place now, you might want\nmore of them, rather than less of them. Have a look at the Emacs\ndocumentation for these variables (with <code>C-h v</code>).</p>\n\n<pre class=\"lang-lisp prettyprint-override\"><code>(setq delete-old-versions t\n kept-new-versions 6\n kept-old-versions 2\n version-control t)\n</code></pre>\n\n<p>Finally, if you absolutely must have no backup files:</p>\n\n<pre class=\"lang-lisp prettyprint-override\"><code>(setq make-backup-files nil)\n</code></pre>\n\n<p>It makes me sick to think of it though.</p>\n"
},
{
"answer_id": 152192,
"author": "David Webb",
"author_id": 3171,
"author_profile": "https://Stackoverflow.com/users/3171",
"pm_score": 5,
"selected": false,
"text": "<p>Another way of configuring backup options is via the Customize interface. Enter:</p>\n\n<pre><code>M-x customize-group\n</code></pre>\n\n<p>And then at the <code>Customize group:</code> prompt enter <code>backup</code>.</p>\n\n<p>If you scroll to the bottom of the buffer you'll see <strong>Backup Directory Alist</strong>. Click <strong>Show Value</strong> and set the first entry of the list as follows:</p>\n\n<pre><code>Regexp matching filename: .*\nBackup directory name: /path/to/your/backup/dir\n</code></pre>\n\n<p>Alternatively, you can turn backups off my setting <strong>Make Backup Files</strong> to <code>off</code>.</p>\n\n<p>If you don't want Emacs to automatically edit your <code>.emacs</code> file you'll want to <a href=\"http://www.gnu.org/software/emacs/manual/html_node/emacs/Saving-Customizations.html\" rel=\"noreferrer\">set up a customisations file</a>.</p>\n"
},
{
"answer_id": 467083,
"author": "Paweł Hajdan",
"author_id": 9403,
"author_profile": "https://Stackoverflow.com/users/9403",
"pm_score": 5,
"selected": false,
"text": "<p>You can disable them altogether by</p>\n\n<pre><code>(setq make-backup-files nil)\n</code></pre>\n"
},
{
"answer_id": 18330742,
"author": "Andreas Spindler",
"author_id": 887771,
"author_profile": "https://Stackoverflow.com/users/887771",
"pm_score": 6,
"selected": false,
"text": "<p>Emacs backup/auto-save files can be very helpful. But these features are confusing. </p>\n\n<p><strong>Backup files</strong></p>\n\n<p>Backup files have tildes (<code>~</code> or <code>~9~</code>) at the end and shall be written to the user home directory. When <code>make-backup-files</code> is non-nil Emacs automatically creates a backup of the original file the first time the file is saved from a buffer. If you're editing a new file Emacs will create a backup the second time you save the file. </p>\n\n<p>No matter how many times you save the file the backup remains unchanged. If you kill the buffer and then visit the file again, or the next time you start a new Emacs session, a new backup file will be made. The new backup reflects the file's content after reopened, or at the start of editing sessions. But an existing backup is never touched again. Therefore I find it useful to created numbered backups (see the configuration below). </p>\n\n<p>To create backups explicitly use <code>save-buffer</code> (<code>C-x C-s</code>) with prefix arguments. </p>\n\n<p><code>diff-backup</code> and <code>dired-diff-backup</code> compares a file with its backup or vice versa. But there is no function to restore backup files. For example, under Windows, to restore a backup file</p>\n\n<pre><code>C:\\Users\\USERNAME\\.emacs.d\\backups\\!drive_c!Users!USERNAME!.emacs.el.~7~\n</code></pre>\n\n<p>it has to be manually copied as</p>\n\n<pre><code>C:\\Users\\USERNAME\\.emacs.el\n</code></pre>\n\n<p><strong>Auto-save files</strong></p>\n\n<p>Auto-save files use hashmarks (<code>#</code>) and shall be written locally within the project directory (along with the actual files). The reason is that auto-save files are just temporary files that Emacs creates until a file is saved again (like with hurrying obedience). </p>\n\n<ul>\n<li>Before the user presses <code>C-x C-s</code> (<code>save-buffer</code>) to save a file Emacs auto-saves files - based on counting keystrokes (<code>auto-save-interval</code>) or when you stop typing (<code>auto-save-timeout</code>). </li>\n<li>Emacs also auto-saves whenever it crashes, including killing the Emacs job with a shell command. </li>\n</ul>\n\n<p>When the user saves the file, the auto-saved version is deleted. But when the user exits the file without saving it, Emacs or the X session crashes, the auto-saved files still exist. </p>\n\n<p>Use <code>revert-buffer</code> or <code>recover-file</code> to restore auto-save files. Note that Emacs records interrupted sessions for later recovery in files named <em>~/.emacs.d/auto-save-list</em>. The <code>recover-session</code> function will use this information.</p>\n\n<p>The preferred method to recover from an auto-saved filed is <code>M-x revert-buffer RET</code>. Emacs will ask either \"Buffer has been auto-saved recently. Revert from auto-save file?\" or \"Revert buffer from file FILENAME?\". In case of the latter there is no auto-save file. For example, because you have saved before typing another <code>auto-save-intervall</code> keystrokes, in which case Emacs had deleted the auto-save file.</p>\n\n<p>Auto-save is nowadays disabled by default because it can slow down editing when connected to a slow machine, and because many files contain sensitive data.</p>\n\n<p><strong>Configuration</strong></p>\n\n<p>Here is a configuration that IMHO works best:</p>\n\n<pre class=\"lang-lisp prettyprint-override\"><code>(defvar --backup-directory (concat user-emacs-directory \"backups\"))\n(if (not (file-exists-p --backup-directory))\n (make-directory --backup-directory t))\n(setq backup-directory-alist `((\".\" . ,--backup-directory)))\n(setq make-backup-files t ; backup of a file the first time it is saved.\n backup-by-copying t ; don't clobber symlinks\n version-control t ; version numbers for backup files\n delete-old-versions t ; delete excess backup files silently\n delete-by-moving-to-trash t\n kept-old-versions 6 ; oldest versions to keep when a new numbered backup is made (default: 2)\n kept-new-versions 9 ; newest versions to keep when a new numbered backup is made (default: 2)\n auto-save-default t ; auto-save every buffer that visits a file\n auto-save-timeout 20 ; number of seconds idle time before auto-save (default: 30)\n auto-save-interval 200 ; number of keystrokes between auto-saves (default: 300)\n )\n</code></pre>\n\n<p><strong>Sensitive data</strong></p>\n\n<p>Another problem is that you don't want to have Emacs spread copies of files with sensitive data. Use <a href=\"http://anirudhsasikumar.net/blog/2005.01.21.html\">this mode</a> on a per-file basis. As this is a minor mode, for my purposes I renamed it <code>sensitive-minor-mode</code>.</p>\n\n<p>To enable it for all <em>.vcf</em> and <em>.gpg</em> files, in your .emacs use something like:</p>\n\n<pre class=\"lang-lisp prettyprint-override\"><code>(setq auto-mode-alist\n (append\n (list\n '(\"\\\\.\\\\(vcf\\\\|gpg\\\\)$\" . sensitive-minor-mode)\n )\n auto-mode-alist))\n</code></pre>\n\n<p>Alternatively, to protect only some files, like some <em>.txt</em> files, use a line like</p>\n\n<pre><code>// -*-mode:asciidoc; mode:sensitive-minor; fill-column:132-*-\n</code></pre>\n\n<p>in the file.</p>\n"
},
{
"answer_id": 20824625,
"author": "ntc2",
"author_id": 470844,
"author_profile": "https://Stackoverflow.com/users/470844",
"pm_score": 6,
"selected": false,
"text": "<p>The <a href=\"https://stackoverflow.com/a/151946/470844\">accepted answer</a> is\ngood, but it can be greatly improved by additionally <strong>backing up on\n<em>every</em> save and backing up <em>versioned</em> files</strong>.</p>\n\n<p>First, basic settings as described in the <a href=\"https://stackoverflow.com/a/151946/470844\">accepted\nanswer</a>:</p>\n\n<pre><code>(setq version-control t ;; Use version numbers for backups.\n kept-new-versions 10 ;; Number of newest versions to keep.\n kept-old-versions 0 ;; Number of oldest versions to keep.\n delete-old-versions t ;; Don't ask to delete excess backup versions.\n backup-by-copying t) ;; Copy all files, don't rename them.\n</code></pre>\n\n<p>Next, also backup versioned files, which Emacs does not do by default\n(you don't commit on every save, right?):</p>\n\n<pre><code>(setq vc-make-backup-files t)\n</code></pre>\n\n<p>Finally, make a backup on each save, not just the first. We make two\nkinds of backups:</p>\n\n<ol>\n<li><p>per-session backups: once on the <em>first</em> save of the buffer in each\nEmacs session. These simulate Emac's default backup behavior.</p></li>\n<li><p>per-save backups: once on <em>every</em> save. Emacs does not do this by\ndefault, but it's very useful if you leave Emacs running for a long\ntime.</p></li>\n</ol>\n\n<p>The <a href=\"http://www.emacswiki.org/emacs/BackupDirectory\" rel=\"noreferrer\">backups go in different\nplaces</a> and Emacs\ncreates the backup dirs automatically if they don't exist:</p>\n\n<pre><code>;; Default and per-save backups go here:\n(setq backup-directory-alist '((\"\" . \"~/.emacs.d/backup/per-save\")))\n\n(defun force-backup-of-buffer ()\n ;; Make a special \"per session\" backup at the first save of each\n ;; emacs session.\n (when (not buffer-backed-up)\n ;; Override the default parameters for per-session backups.\n (let ((backup-directory-alist '((\"\" . \"~/.emacs.d/backup/per-session\")))\n (kept-new-versions 3))\n (backup-buffer)))\n ;; Make a \"per save\" backup on each save. The first save results in\n ;; both a per-session and a per-save backup, to keep the numbering\n ;; of per-save backups consistent.\n (let ((buffer-backed-up nil))\n (backup-buffer)))\n\n(add-hook 'before-save-hook 'force-backup-of-buffer)\n</code></pre>\n\n<p>I became very interested in this topic after I wrote <code>$<</code> instead of\n<code>$@</code> in my <code>Makefile</code>, about three hours after my previous commit :P</p>\n\n<p>The above is based on an <a href=\"http://www.emacswiki.org/emacs/ForceBackups\" rel=\"noreferrer\">Emacs Wiki page I heavily\nedited</a>.</p>\n"
},
{
"answer_id": 71820260,
"author": "FeralWhippet",
"author_id": 3342122,
"author_profile": "https://Stackoverflow.com/users/3342122",
"pm_score": 0,
"selected": false,
"text": "<p><code>(setq delete-auto-save-files t)</code></p>\n<p>deletes buffer's auto save file when it is saved or when killed with no changes in it. thus you still get some of the safety of auto save files, since they are only left around when a buffer is killed with unsaved changes or if emacs exits unexpectedly. if you want to do this, but really need history on some of your files, consider putting them under source control.</p>\n"
}
]
| 2008/09/30 | [
"https://Stackoverflow.com/questions/151945",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11138/"
]
| Emacs puts backup files named `foo~` everywhere and I don't like having to remember to delete them. Also, if I edit a file that has a hard link somewhere else in the file system, the hard link points to the backup when I'm done editing, and that's confusing and awful. How can I either eliminate these backup files, or have them go somewhere other than the same directory? | If you've ever been saved by an Emacs backup file, you
probably want more of them, not less of them. It is annoying
that they go in the same directory as the file you're editing,
but that is easy to change. You can make all backup files go
into a directory by putting something like the following in your
`.emacs`.
```lisp
(setq backup-directory-alist `(("." . "~/.saves")))
```
There are a number of arcane details associated with how Emacs
might create your backup files. Should it rename the original
and write out the edited buffer? What if the original is linked?
In general, the safest but slowest bet is to always make backups
by copying.
```lisp
(setq backup-by-copying t)
```
If that's too slow for some reason you might also have a look at
`backup-by-copying-when-linked`.
Since your backups are all in their own place now, you might want
more of them, rather than less of them. Have a look at the Emacs
documentation for these variables (with `C-h v`).
```lisp
(setq delete-old-versions t
kept-new-versions 6
kept-old-versions 2
version-control t)
```
Finally, if you absolutely must have no backup files:
```lisp
(setq make-backup-files nil)
```
It makes me sick to think of it though. |
151,963 | <p>Is it possible to get the route/virtual url associated with a controller action or on a view? I saw that Preview 4 added LinkBuilder.BuildUrlFromExpression helper, but it's not very useful if you want to use it on the master, since the controller type can be different. Any thoughts are appreciated.</p>
| [
{
"answer_id": 153199,
"author": "Ben Scheirman",
"author_id": 3381,
"author_profile": "https://Stackoverflow.com/users/3381",
"pm_score": 2,
"selected": false,
"text": "<p>You can use <%= Url.Action(action, controller, values) %> to build the URL from within the master page.</p>\n\n<p>Are you doing this to maybe highlight a tab for the current page or something?</p>\n\n<p>If so you can use ViewContext from the view and get the values you need.</p>\n"
},
{
"answer_id": 598791,
"author": "Jim Geurts",
"author_id": 3085,
"author_profile": "https://Stackoverflow.com/users/3085",
"pm_score": 1,
"selected": false,
"text": "<p>I wrote <a href=\"http://biasecurities.com/blog/2009/helper-to-access-route-parameters/\" rel=\"nofollow noreferrer\">a helper class</a> that allows me to access the route parameters. With this helper, you can get the controller, action, and all parameters passed to the action.</p>\n"
},
{
"answer_id": 691985,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 4,
"selected": false,
"text": "<p>This worked for me:</p>\n\n<p><code><%= this.Url.RouteUrl(this.ViewContext.RouteData.Values) %></code></p>\n\n<p>It returns the current Url as such; <code>/Home/About</code></p>\n\n<p>Maybe there is a simpler way to return the actual route string?</p>\n"
},
{
"answer_id": 1268335,
"author": "Jim Geurts",
"author_id": 3085,
"author_profile": "https://Stackoverflow.com/users/3085",
"pm_score": 5,
"selected": true,
"text": "<p>You can get that data from ViewContext.RouteData. Below are some examples for how to access (and use) that information:</p>\n\n<p>/// These are added to my viewmasterpage, viewpage, and viewusercontrol base classes:</p>\n\n<pre><code>public bool IsController(string controller)\n{\n if (ViewContext.RouteData.Values[\"controller\"] != null)\n {\n return ViewContext.RouteData.Values[\"controller\"].ToString().Equals(controller, StringComparison.OrdinalIgnoreCase);\n }\n return false;\n}\npublic bool IsAction(string action)\n{\n if (ViewContext.RouteData.Values[\"action\"] != null)\n {\n return ViewContext.RouteData.Values[\"action\"].ToString().Equals(action, StringComparison.OrdinalIgnoreCase);\n }\n return false;\n}\npublic bool IsAction(string action, string controller)\n{\n return IsController(controller) && IsAction(action);\n}\n</code></pre>\n\n<p>/// Some extension methods that I added to the UrlHelper class.</p>\n\n<pre><code>public static class UrlHelperExtensions\n{\n /// <summary>\n /// Determines if the current view equals the specified action\n /// </summary>\n /// <typeparam name=\"TController\">The type of the controller.</typeparam>\n /// <param name=\"helper\">Url Helper</param>\n /// <param name=\"action\">The action to check.</param>\n /// <returns>\n /// <c>true</c> if the specified action is the current view; otherwise, <c>false</c>.\n /// </returns>\n public static bool IsAction<TController>(this UrlHelper helper, LambdaExpression action) where TController : Controller\n {\n MethodCallExpression call = action.Body as MethodCallExpression;\n if (call == null)\n {\n throw new ArgumentException(\"Expression must be a method call\", \"action\");\n }\n\n return (call.Method.Name.Equals(helper.ViewContext.ViewName, StringComparison.OrdinalIgnoreCase) &&\n typeof(TController) == helper.ViewContext.Controller.GetType());\n }\n\n /// <summary>\n /// Determines if the current view equals the specified action\n /// </summary>\n /// <param name=\"helper\">Url Helper</param>\n /// <param name=\"actionName\">Name of the action.</param>\n /// <returns>\n /// <c>true</c> if the specified action is the current view; otherwise, <c>false</c>.\n /// </returns>\n public static bool IsAction(this UrlHelper helper, string actionName)\n {\n if (String.IsNullOrEmpty(actionName))\n {\n throw new ArgumentException(\"Please specify the name of the action\", \"actionName\");\n }\n string controllerName = helper.ViewContext.RouteData.GetRequiredString(\"controller\");\n return IsAction(helper, actionName, controllerName);\n }\n\n /// <summary>\n /// Determines if the current view equals the specified action\n /// </summary>\n /// <param name=\"helper\">Url Helper</param>\n /// <param name=\"actionName\">Name of the action.</param>\n /// <param name=\"controllerName\">Name of the controller.</param>\n /// <returns>\n /// <c>true</c> if the specified action is the current view; otherwise, <c>false</c>.\n /// </returns>\n public static bool IsAction(this UrlHelper helper, string actionName, string controllerName)\n {\n if (String.IsNullOrEmpty(actionName))\n {\n throw new ArgumentException(\"Please specify the name of the action\", \"actionName\");\n }\n if (String.IsNullOrEmpty(controllerName))\n {\n throw new ArgumentException(\"Please specify the name of the controller\", \"controllerName\");\n }\n\n if (!controllerName.EndsWith(\"Controller\", StringComparison.OrdinalIgnoreCase))\n {\n controllerName = controllerName + \"Controller\";\n }\n\n bool isOnView = helper.ViewContext.ViewName.SafeEquals(actionName, StringComparison.OrdinalIgnoreCase);\n return isOnView && helper.ViewContext.Controller.GetType().Name.Equals(controllerName, StringComparison.OrdinalIgnoreCase);\n }\n\n /// <summary>\n /// Determines if the current request is on the specified controller\n /// </summary>\n /// <param name=\"helper\">The helper.</param>\n /// <param name=\"controllerName\">Name of the controller.</param>\n /// <returns>\n /// <c>true</c> if the current view is on the specified controller; otherwise, <c>false</c>.\n /// </returns>\n public static bool IsController(this UrlHelper helper, string controllerName)\n {\n if (String.IsNullOrEmpty(controllerName))\n {\n throw new ArgumentException(\"Please specify the name of the controller\", \"controllerName\");\n }\n\n if (!controllerName.EndsWith(\"Controller\", StringComparison.OrdinalIgnoreCase))\n {\n controllerName = controllerName + \"Controller\";\n }\n\n return helper.ViewContext.Controller.GetType().Name.Equals(controllerName, StringComparison.OrdinalIgnoreCase);\n }\n\n /// <summary>\n /// Determines if the current request is on the specified controller\n /// </summary>\n /// <typeparam name=\"TController\">The type of the controller.</typeparam>\n /// <param name=\"helper\">The helper.</param>\n /// <returns>\n /// <c>true</c> if the current view is on the specified controller; otherwise, <c>false</c>.\n /// </returns>\n public static bool IsController<TController>(this UrlHelper helper) where TController : Controller\n {\n return (typeof(TController) == helper.ViewContext.Controller.GetType());\n }\n}\n</code></pre>\n"
},
{
"answer_id": 4790073,
"author": "Tarzan",
"author_id": 152118,
"author_profile": "https://Stackoverflow.com/users/152118",
"pm_score": 5,
"selected": false,
"text": "<p>I always try to implement the simplest solution that meets the project requirements. As Enstein said, \"Make things as simple as possible, but not simpler.\" Try this. </p>\n\n<pre><code><%: Request.Path %>\n</code></pre>\n"
}
]
| 2008/09/30 | [
"https://Stackoverflow.com/questions/151963",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3085/"
]
| Is it possible to get the route/virtual url associated with a controller action or on a view? I saw that Preview 4 added LinkBuilder.BuildUrlFromExpression helper, but it's not very useful if you want to use it on the master, since the controller type can be different. Any thoughts are appreciated. | You can get that data from ViewContext.RouteData. Below are some examples for how to access (and use) that information:
/// These are added to my viewmasterpage, viewpage, and viewusercontrol base classes:
```
public bool IsController(string controller)
{
if (ViewContext.RouteData.Values["controller"] != null)
{
return ViewContext.RouteData.Values["controller"].ToString().Equals(controller, StringComparison.OrdinalIgnoreCase);
}
return false;
}
public bool IsAction(string action)
{
if (ViewContext.RouteData.Values["action"] != null)
{
return ViewContext.RouteData.Values["action"].ToString().Equals(action, StringComparison.OrdinalIgnoreCase);
}
return false;
}
public bool IsAction(string action, string controller)
{
return IsController(controller) && IsAction(action);
}
```
/// Some extension methods that I added to the UrlHelper class.
```
public static class UrlHelperExtensions
{
/// <summary>
/// Determines if the current view equals the specified action
/// </summary>
/// <typeparam name="TController">The type of the controller.</typeparam>
/// <param name="helper">Url Helper</param>
/// <param name="action">The action to check.</param>
/// <returns>
/// <c>true</c> if the specified action is the current view; otherwise, <c>false</c>.
/// </returns>
public static bool IsAction<TController>(this UrlHelper helper, LambdaExpression action) where TController : Controller
{
MethodCallExpression call = action.Body as MethodCallExpression;
if (call == null)
{
throw new ArgumentException("Expression must be a method call", "action");
}
return (call.Method.Name.Equals(helper.ViewContext.ViewName, StringComparison.OrdinalIgnoreCase) &&
typeof(TController) == helper.ViewContext.Controller.GetType());
}
/// <summary>
/// Determines if the current view equals the specified action
/// </summary>
/// <param name="helper">Url Helper</param>
/// <param name="actionName">Name of the action.</param>
/// <returns>
/// <c>true</c> if the specified action is the current view; otherwise, <c>false</c>.
/// </returns>
public static bool IsAction(this UrlHelper helper, string actionName)
{
if (String.IsNullOrEmpty(actionName))
{
throw new ArgumentException("Please specify the name of the action", "actionName");
}
string controllerName = helper.ViewContext.RouteData.GetRequiredString("controller");
return IsAction(helper, actionName, controllerName);
}
/// <summary>
/// Determines if the current view equals the specified action
/// </summary>
/// <param name="helper">Url Helper</param>
/// <param name="actionName">Name of the action.</param>
/// <param name="controllerName">Name of the controller.</param>
/// <returns>
/// <c>true</c> if the specified action is the current view; otherwise, <c>false</c>.
/// </returns>
public static bool IsAction(this UrlHelper helper, string actionName, string controllerName)
{
if (String.IsNullOrEmpty(actionName))
{
throw new ArgumentException("Please specify the name of the action", "actionName");
}
if (String.IsNullOrEmpty(controllerName))
{
throw new ArgumentException("Please specify the name of the controller", "controllerName");
}
if (!controllerName.EndsWith("Controller", StringComparison.OrdinalIgnoreCase))
{
controllerName = controllerName + "Controller";
}
bool isOnView = helper.ViewContext.ViewName.SafeEquals(actionName, StringComparison.OrdinalIgnoreCase);
return isOnView && helper.ViewContext.Controller.GetType().Name.Equals(controllerName, StringComparison.OrdinalIgnoreCase);
}
/// <summary>
/// Determines if the current request is on the specified controller
/// </summary>
/// <param name="helper">The helper.</param>
/// <param name="controllerName">Name of the controller.</param>
/// <returns>
/// <c>true</c> if the current view is on the specified controller; otherwise, <c>false</c>.
/// </returns>
public static bool IsController(this UrlHelper helper, string controllerName)
{
if (String.IsNullOrEmpty(controllerName))
{
throw new ArgumentException("Please specify the name of the controller", "controllerName");
}
if (!controllerName.EndsWith("Controller", StringComparison.OrdinalIgnoreCase))
{
controllerName = controllerName + "Controller";
}
return helper.ViewContext.Controller.GetType().Name.Equals(controllerName, StringComparison.OrdinalIgnoreCase);
}
/// <summary>
/// Determines if the current request is on the specified controller
/// </summary>
/// <typeparam name="TController">The type of the controller.</typeparam>
/// <param name="helper">The helper.</param>
/// <returns>
/// <c>true</c> if the current view is on the specified controller; otherwise, <c>false</c>.
/// </returns>
public static bool IsController<TController>(this UrlHelper helper) where TController : Controller
{
return (typeof(TController) == helper.ViewContext.Controller.GetType());
}
}
``` |
151,969 | <p>In PHP 5, what is the difference between using <code>self</code> and <code>$this</code>?</p>
<p>When is each appropriate?</p>
| [
{
"answer_id": 151975,
"author": "cruizer",
"author_id": 6441,
"author_profile": "https://Stackoverflow.com/users/6441",
"pm_score": 4,
"selected": false,
"text": "<p>According to <em><a href=\"http://www.php.net/manual/en/language.oop5.static.php\" rel=\"nofollow noreferrer\">Static Keyword</a></em>, there isn't any <code>$self</code>. There is only <code>$this</code>, for referring to the current instance of the class (the object), and <code>self</code>, which can be used to refer to static members of a class. The difference between an object instance and a class comes into play here.</p>\n"
},
{
"answer_id": 151976,
"author": "John Millikin",
"author_id": 3560,
"author_profile": "https://Stackoverflow.com/users/3560",
"pm_score": 12,
"selected": true,
"text": "<h1>Short Answer</h1>\n\n<blockquote>\n <p>Use <code>$this</code> to refer to the current\n object. Use <code>self</code> to refer to the\n current class. In other words, use\n <code>$this->member</code> for non-static members,\n use <code>self::$member</code> for static members.</p>\n</blockquote>\n\n<h1>Full Answer</h1>\n\n<p>Here is an example of <strong>correct</strong> usage of <code>$this</code> and <code>self</code> for non-static and static member variables:</p>\n\n<pre><code><?php\nclass X {\n private $non_static_member = 1;\n private static $static_member = 2;\n\n function __construct() {\n echo $this->non_static_member . ' '\n . self::$static_member;\n }\n}\n\nnew X();\n?>\n</code></pre>\n\n<p>Here is an example of <strong>incorrect</strong> usage of <code>$this</code> and <code>self</code> for non-static and static member variables:</p>\n\n<pre><code><?php\nclass X {\n private $non_static_member = 1;\n private static $static_member = 2;\n\n function __construct() {\n echo self::$non_static_member . ' '\n . $this->static_member;\n }\n}\n\nnew X();\n?>\n</code></pre>\n\n<p>Here is an example of <strong>polymorphism</strong> with <code>$this</code> for member functions:</p>\n\n<pre><code><?php\nclass X {\n function foo() {\n echo 'X::foo()';\n }\n\n function bar() {\n $this->foo();\n }\n}\n\nclass Y extends X {\n function foo() {\n echo 'Y::foo()';\n }\n}\n\n$x = new Y();\n$x->bar();\n?>\n</code></pre>\n\n<p>Here is an example of <strong>suppressing polymorphic behaviour</strong> by using <code>self</code> for member functions:</p>\n\n<pre><code><?php\nclass X {\n function foo() {\n echo 'X::foo()';\n }\n\n function bar() {\n self::foo();\n }\n}\n\nclass Y extends X {\n function foo() {\n echo 'Y::foo()';\n }\n}\n\n$x = new Y();\n$x->bar();\n?>\n</code></pre>\n\n<blockquote>\n <p>The idea is that <code>$this->foo()</code> calls the <code>foo()</code> member function of whatever is the exact type of the current object. If the object is of <code>type X</code>, it thus calls <code>X::foo()</code>. If the object is of <code>type Y</code>, it calls <code>Y::foo()</code>. But with self::foo(), <code>X::foo()</code> is always called.</p>\n</blockquote>\n\n<p>From <a href=\"http://www.phpbuilder.com/board/showthread.php?t=10354489\" rel=\"noreferrer\">http://www.phpbuilder.com/board/showthread.php?t=10354489</a>:</p>\n\n<p>By <a href=\"http://board.phpbuilder.com/member.php?145249-laserlight\" rel=\"noreferrer\">http://board.phpbuilder.com/member.php?145249-laserlight</a></p>\n"
},
{
"answer_id": 152073,
"author": "Zebra North",
"author_id": 17440,
"author_profile": "https://Stackoverflow.com/users/17440",
"pm_score": 7,
"selected": false,
"text": "<p><code>self</code> (not $self) refers to the <em>type</em> of class, whereas <code>$this</code> refers to the current <em>instance</em> of the class. <code>self</code> is for use in static member functions to allow you to access static member variables. <code>$this</code> is used in non-static member functions, and is a reference to the instance of the class on which the member function was called.</p>\n<p>Because <code>this</code> is an object, you use it like: <code>$this->member</code></p>\n<p>Because <code>self</code> is not an object, it's basically a type that automatically refers to the current class. You use it like: <code>self::member</code></p>\n"
},
{
"answer_id": 226844,
"author": "lo_fye",
"author_id": 3407,
"author_profile": "https://Stackoverflow.com/users/3407",
"pm_score": 7,
"selected": false,
"text": "<p><code>$this-></code> is used to refer to a specific instance of a class's variables (member variables) or methods.</p>\n\n<pre><code>Example: \n$derek = new Person();\n</code></pre>\n\n<p>$derek is now a specific instance of Person.\nEvery Person has a first_name and a last_name, but $derek has a specific first_name and last_name (Derek Martin). Inside the $derek instance, we can refer to those as $this->first_name and $this->last_name</p>\n\n<p>ClassName:: is used to refer to that type of class, and its static variables, static methods. If it helps, you can mentally replace the word \"static\" with \"shared\". Because they are shared, they cannot refer to $this, which refers to a specific instance (not shared). Static Variables (i.e. static $db_connection) can be shared among all instances of a type of object. For example, all database objects share a single connection (static $connection).</p>\n\n<p><strong>Static Variables Example:</strong>\nPretend we have a database class with a single member variable: static $num_connections;\nNow, put this in the constructor:</p>\n\n<pre><code>function __construct()\n{\n if(!isset $num_connections || $num_connections==null)\n {\n $num_connections=0;\n }\n else\n {\n $num_connections++;\n }\n}\n</code></pre>\n\n<p>Just as objects have constructors, they also have destructors, which are executed when the object dies or is unset:</p>\n\n<pre><code>function __destruct()\n{\n $num_connections--;\n}\n</code></pre>\n\n<p>Every time we create a new instance, it will increase our connection counter by one. Every time we destroy or stop using an instance, it will decrease the connection counter by one. In this way, we can monitor the number of instances of the database object we have in use with:</p>\n\n<pre><code>echo DB::num_connections;\n</code></pre>\n\n<p>Because $num_connections is static (shared), it will reflect the total number of active database objects. You may have seen this technique used to share database connections among all instances of a database class. This is done because creating the database connection takes a long time, so it's best to create just one, and share it (this is called a Singleton Pattern).</p>\n\n<p>Static Methods (i.e. public static View::format_phone_number($digits)) can be used WITHOUT first instantiating one of those objects (i.e. They do not internally refer to $this).</p>\n\n<p><strong>Static Method Example:</strong></p>\n\n<pre><code>public static function prettyName($first_name, $last_name)\n{\n echo ucfirst($first_name).' '.ucfirst($last_name);\n}\n\necho Person::prettyName($derek->first_name, $derek->last_name);\n</code></pre>\n\n<p>As you can see, public static function prettyName knows nothing about the object. It's just working with the parameters you pass in, like a normal function that's not part of an object. Why bother, then, if we could just have it not as part of the object?</p>\n\n<ol>\n<li>First, attaching functions to objects helps you keep things organized, so you know where to find them.</li>\n<li>Second, it prevents naming conflicts. In a big project, you're likely to have two developers create getName() functions. If one creates a ClassName1::getName(), and the other creates ClassName2::getName(), it's no problem at all. No conflict. Yay static methods!</li>\n</ol>\n\n<p><strong>SELF::</strong>\nIf you are coding <em>outside</em> the object that has the static method you want to refer to, you must call it using the object's name View::format_phone_number($phone_number);\nIf you are coding <em>inside</em> the object that has the static method you want to refer to, you can <em>either</em> use the object's name View::format_phone_number($pn), OR you can use the self::format_phone_number($pn) shortcut</p>\n\n<p>The same goes for static variables:\n<strong>Example:</strong> View::templates_path versus self::templates_path</p>\n\n<p>Inside the DB class, if we were referring to a static method of some other object, we would use the object's name:\n<strong>Example:</strong> Session::getUsersOnline();</p>\n\n<p>But if the DB class wanted to refer to its own static variable, it would just say self:\n<strong>Example:</strong> self::connection;</p>\n\n<p>Hope that helps clear things up :)</p>\n"
},
{
"answer_id": 879425,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 4,
"selected": false,
"text": "<p>I believe the question was not whether you can call the static member of the class by calling <code>ClassName::staticMember</code>. The question was what's the difference between using <code>self::classmember</code> and <code>$this->classmember</code>.</p>\n<p>For example, both of the following examples work without any errors, whether you use <code>self::</code> or <code>$this-></code></p>\n<pre><code>class Person{\n private $name;\n private $address;\n\n public function __construct($new_name,$new_address){\n $this->name = $new_name;\n $this->address = $new_address;\n }\n}\n\nclass Person{\n private $name;\n private $address;\n public function __construct($new_name,$new_address){\n self::$name = $new_name;\n self::$address = $new_address;\n }\n}\n</code></pre>\n"
},
{
"answer_id": 1189663,
"author": "nbeagle",
"author_id": 145910,
"author_profile": "https://Stackoverflow.com/users/145910",
"pm_score": 10,
"selected": false,
"text": "<p>The keyword self does <strong>NOT</strong> refer merely to the 'current class', at least not in a way that restricts you to static members. Within the context of a non-static member, <code>self</code> also provides a way of bypassing the vtable (<a href=\"https://en.wikipedia.org/wiki/Virtual_method_table\" rel=\"noreferrer\">see wiki on vtable</a>) for the current object. Just as you can use <code>parent::methodName()</code> to call the parents version of a function, so you can call <code>self::methodName()</code> to call the current classes implementation of a method.</p>\n\n<pre><code>class Person {\n private $name;\n\n public function __construct($name) {\n $this->name = $name;\n }\n\n public function getName() {\n return $this->name;\n }\n\n public function getTitle() {\n return $this->getName().\" the person\";\n }\n\n public function sayHello() {\n echo \"Hello, I'm \".$this->getTitle().\"<br/>\";\n }\n\n public function sayGoodbye() {\n echo \"Goodbye from \".self::getTitle().\"<br/>\";\n }\n}\n\nclass Geek extends Person {\n public function __construct($name) {\n parent::__construct($name);\n }\n\n public function getTitle() {\n return $this->getName().\" the geek\";\n }\n}\n\n$geekObj = new Geek(\"Ludwig\");\n$geekObj->sayHello();\n$geekObj->sayGoodbye();\n</code></pre>\n\n<p>This will output:</p>\n\n<blockquote>\n <p>Hello, I'm Ludwig the geek<br>\n Goodbye from Ludwig the person</p>\n</blockquote>\n\n<p><code>sayHello()</code> uses the <code>$this</code> pointer, so the vtable is invoked to call <code>Geek::getTitle()</code>.\n<code>sayGoodbye()</code> uses <code>self::getTitle()</code>, so the vtable is not used, and <code>Person::getTitle()</code> is called. In both cases, we are dealing with the method of an instantiated object, and have access to the <code>$this</code> pointer within the called functions.</p>\n"
},
{
"answer_id": 6807615,
"author": "Sqoo",
"author_id": 199687,
"author_profile": "https://Stackoverflow.com/users/199687",
"pm_score": 9,
"selected": false,
"text": "<p><em><strong>Do not use</strong></em> <em><code>self::</code>. Use <code>static::</code></em>*</p>\n<p>There is another aspect of self:: that is worth mentioning. Annoyingly, <strong><code>self::</code> refers to the scope at the point of definition, not at the point of execution</strong>. Consider this simple class with two methods:</p>\n<pre><code>class Person\n{\n\n public static function status()\n {\n self::getStatus();\n }\n\n protected static function getStatus()\n {\n echo "Person is alive";\n }\n\n}\n</code></pre>\n<p>If we call <code>Person::status()</code> we will see "Person is alive" . Now consider what happens when we make a class that inherits from this:</p>\n<pre><code>class Deceased extends Person\n{\n\n protected static function getStatus()\n {\n echo "Person is deceased";\n }\n\n}\n</code></pre>\n<p>Calling <code>Deceased::status()</code> we would expect to see "Person is deceased". However, we see "Person is alive" as the scope contains the original method definition when the call to <code>self::getStatus()</code> was defined.</p>\n<p>PHP 5.3 has a solution. The <strong><code>static::</code></strong> resolution operator implements "late static binding" which is a fancy way of saying that it's bound to the scope of the class called. Change the line in <code>status()</code> to <code>static::getStatus()</code> and the results are what you would expect. In older versions of PHP you will have to find a kludge to do this.</p>\n<p>See <a href=\"http://php.net/manual/en/language.oop5.late-static-bindings.php\" rel=\"noreferrer\">PHP Documentation</a></p>\n<p>So to answer the question not as asked...</p>\n<p><code>$this-></code> refers to the current object (an instance of a class), whereas <code>static::</code> refers to a class.</p>\n"
},
{
"answer_id": 8399151,
"author": "Mohit Bumb",
"author_id": 1470999,
"author_profile": "https://Stackoverflow.com/users/1470999",
"pm_score": 4,
"selected": false,
"text": "<blockquote>\n <p>Here is an example of correct usage of $this and self for non-static\n and static member variables:</p>\n</blockquote>\n\n<pre><code><?php\nclass X {\n private $non_static_member = 1;\n private static $static_member = 2;\n\n function __construct() {\n echo $this->non_static_member . ' '\n . self::$static_member;\n }\n}\n\nnew X();\n?> \n</code></pre>\n"
},
{
"answer_id": 15573773,
"author": "mrDjouk",
"author_id": 2199125,
"author_profile": "https://Stackoverflow.com/users/2199125",
"pm_score": 4,
"selected": false,
"text": "<p>When <code>self</code> is used with the <code>::</code> operator it refers to the current class, which can be done both in static and non-static contexts. <code>$this</code> refers to the object itself. In addition, it is perfectly legal to use <code>$this</code> to call static methods (but not to refer to fields).</p>\n"
},
{
"answer_id": 15573992,
"author": "Xeoncross",
"author_id": 99923,
"author_profile": "https://Stackoverflow.com/users/99923",
"pm_score": 4,
"selected": false,
"text": "<ul>\n<li>The object pointer <code>$this</code> to refers to the current object.</li>\n<li>The class value <code>static</code> refers to the current object.</li>\n<li>The class value <code>self</code> refers to the exact class it was defined in.</li>\n<li>The class value <code>parent</code> refers to the parent of the exact class it was defined in.</li>\n</ul>\n\n<p>See the following example which shows overloading.</p>\n\n<pre><code><?php\n\nclass A {\n\n public static function newStaticClass()\n {\n return new static;\n }\n\n public static function newSelfClass()\n {\n return new self;\n }\n\n public function newThisClass()\n {\n return new $this;\n }\n}\n\nclass B extends A\n{\n public function newParentClass()\n {\n return new parent;\n }\n}\n\n\n$b = new B;\n\nvar_dump($b::newStaticClass()); // B\nvar_dump($b::newSelfClass()); // A because self belongs to \"A\"\nvar_dump($b->newThisClass()); // B\nvar_dump($b->newParentClass()); // A\n\n\nclass C extends B\n{\n public static function newSelfClass()\n {\n return new self;\n }\n}\n\n\n$c = new C;\n\nvar_dump($c::newStaticClass()); // C\nvar_dump($c::newSelfClass()); // C because self now points to \"C\" class\nvar_dump($c->newThisClass()); // C\nvar_dump($b->newParentClass()); // A because parent was defined *way back* in class \"B\"\n</code></pre>\n\n<p>Most of the time you want to refer to the current class which is why you use <code>static</code> or <code>$this</code>. However, there are times when you <em>need</em> <code>self</code> because you want the original class regardless of what extends it. (Very, Very seldom)</p>\n"
},
{
"answer_id": 15929796,
"author": "Minhaj",
"author_id": 2162092,
"author_profile": "https://Stackoverflow.com/users/2162092",
"pm_score": 3,
"selected": false,
"text": "<p>Use <code>self</code> if you want to call a method of a class without creating an object/instance of that class, thus saving <a href=\"http://en.wikipedia.org/wiki/Random-access_memory\" rel=\"nofollow noreferrer\">RAM</a> (sometimes use self for that purpose). In other words, it is actually calling a method statically. Use <code>this</code> for object perspective.</p>\n"
},
{
"answer_id": 16434516,
"author": "Tarun Singhal",
"author_id": 1719634,
"author_profile": "https://Stackoverflow.com/users/1719634",
"pm_score": 5,
"selected": false,
"text": "<p>Inside a class definition, <code>$this</code> refers to the current object, while <code>self</code> refers to the current class.</p>\n\n<p>It is necessary to refer to a class element using <code>self</code>, and refer to an object element using <code>$this</code>.</p>\n\n<pre><code>self::STAT // refer to a constant value\nself::$stat // static variable\n$this->stat // refer to an object variable \n</code></pre>\n"
},
{
"answer_id": 16481781,
"author": "okconfused",
"author_id": 1541177,
"author_profile": "https://Stackoverflow.com/users/1541177",
"pm_score": 5,
"selected": false,
"text": "<p>From <a href=\"http://www.programmerinterview.com/index.php/php-questions/php-self-vs-this/\">this blog post</a>:</p>\n\n<blockquote>\n <ul>\n <li><code>self</code> refers to the current class </li>\n <li><code>self</code> can be used to call static functions and reference static member variables </li>\n <li><code>self</code> can be used inside static functions</li>\n <li><code>self</code> can also turn off polymorphic behavior by bypassing the vtable</li>\n <li><code>$this</code> refers to the current object</li>\n <li><code>$this</code> can be used to call static functions</li>\n <li><code>$this</code> should not be used to call static member variables. Use <code>self</code> instead.</li>\n <li><code>$this</code> can not be used inside static functions</li>\n </ul>\n</blockquote>\n"
},
{
"answer_id": 17027307,
"author": "ircmaxell",
"author_id": 338665,
"author_profile": "https://Stackoverflow.com/users/338665",
"pm_score": 8,
"selected": false,
"text": "<p>To really understand what we're talking about when we talk about <code>self</code> versus <code>$this</code>, we need to actually dig into what's going on at a conceptual and a practical level. I don't really feel any of the answers do this appropriately, so here's my attempt.</p>\n\n<p>Let's start off by talking about what a <em>class</em> and an <em>object</em> is.</p>\n\n<h1>Classes And Objects, Conceptually</h1>\n\n<p>So, what <strong>is</strong> a <em>class</em>? A lot of people define it as a <em>blueprint</em> or a <em>template</em> for an object. In fact, you can read more <a href=\"https://stackoverflow.com/questions/2206387/what-is-a-class-in-php/2206835#2206835\">About Classes In PHP Here</a>. And to some extent that's what it really is. Let's look at a class:</p>\n\n<pre><code>class Person {\n public $name = 'my name';\n public function sayHello() {\n echo \"Hello\";\n }\n}\n</code></pre>\n\n<p>As you can tell, there is a property on that class called <code>$name</code> and a method (function) called <code>sayHello()</code>. </p>\n\n<p>It's <em>very</em> important to note that the <em>class</em> is a static structure. Which means that the class <code>Person</code>, once defined, is always the same everywhere you look at it. </p>\n\n<p>An object on the other hand is what's called an <em>instance</em> of a Class. What that means is that we take the \"blueprint\" of the class, and use it to make a dynamic copy. This copy is now specifically tied to the variable it's stored in. Therefore, any changes to an <em>instance</em> is local to that instance.</p>\n\n<pre><code>$bob = new Person;\n$adam = new Person;\n$bob->name = 'Bob';\necho $adam->name; // \"my name\"\n</code></pre>\n\n<p>We create new <em>instances</em> of a class using the <code>new</code> operator.</p>\n\n<p>Therefore, we say that a Class is a global structure, and an Object is a local structure. Don't worry about that funny <code>-></code> syntax, we're going to go into that in a little bit. </p>\n\n<p>One other thing we should talk about, is that we can <em>check</em> if an instance is an <code>instanceof</code> a particular class: <code>$bob instanceof Person</code> which returns a boolean if the <code>$bob</code> instance was made using the <code>Person</code> class, <em>or</em> a child of <code>Person</code>.</p>\n\n<h1>Defining State</h1>\n\n<p>So let's dig a bit into what a class actually contains. There are 5 types of \"things\" that a class contains:</p>\n\n<ol>\n<li><p><em>Properties</em> - Think of these as variables that each instance will contain.</p>\n\n<pre><code>class Foo {\n public $bar = 1;\n}\n</code></pre></li>\n<li><p><em>Static Properties</em> - Think of these as variables that are shared at the class level. Meaning that they are never copied by each instance.</p>\n\n<pre><code>class Foo {\n public static $bar = 1;\n}\n</code></pre></li>\n<li><p><em>Methods</em> - These are functions which each instance will contain (and operate on instances).</p>\n\n<pre><code>class Foo {\n public function bar() {}\n}\n</code></pre></li>\n<li><p><em>Static Methods</em> - These are functions which are shared across the entire class. They do <strong>not</strong> operate on instances, but instead on the static properties only.</p>\n\n<pre><code>class Foo {\n public static function bar() {}\n}\n</code></pre></li>\n<li><p><em>Constants</em> - Class resolved constants. Not going any deeper here, but adding for completeness:</p>\n\n<pre><code>class Foo {\n const BAR = 1;\n}\n</code></pre></li>\n</ol>\n\n<p>So basically, we're storing information on the class and object container using \"hints\" about <em>static</em> which identify whether the information is shared (and hence static) or not (and hence dynamic).</p>\n\n<h1>State and Methods</h1>\n\n<p>Inside of a method, an object's instance is represented by the <code>$this</code> variable. The current state of that object is there, and mutating (changing) any property will result in a change to that instance (but not others).</p>\n\n<p>If a method is called statically, the <code>$this</code> variable <em>is not defined</em>. This is because there's no instance associated with a static call.</p>\n\n<p>The interesting thing here is how static calls are made. So let's talk about how we access the state:</p>\n\n<h1>Accessing State</h1>\n\n<p>So now that we have stored that state, we need to access it. This can get a bit tricky (or <strong>way</strong> more than a bit), so let's split this into two viewpoints: from outside of an instance/class (say from a normal function call, or from the global scope), and inside of an instance/class (from within a method on the object).</p>\n\n<h2>From Outside Of An Instance/Class</h2>\n\n<p>From the outside of an instance/class, our rules are quite simple and predictable. We have two operators, and each tells us immediately if we're dealing with an instance or a class static:</p>\n\n<ul>\n<li><p><code>-></code> - <em>object-operator</em> - This is always used when we're accessing an instance.</p>\n\n<pre><code>$bob = new Person;\necho $bob->name;\n</code></pre>\n\n<p>It's important to note that calling <code>Person->foo</code> does not make sense (since <code>Person</code> is a class, not an instance). Therefore, that is a parse error.</p></li>\n<li><p><code>::</code> - <em>scope-resolution-operator</em> - This is always used to access a Class static property or method.</p>\n\n<pre><code>echo Foo::bar()\n</code></pre>\n\n<p>Additionally, we can call a static method on an object in the same way:</p>\n\n<pre><code>echo $foo::bar()\n</code></pre>\n\n<p>It's <em>extremely</em> important to note that when we do this <strong>from outside</strong>, the object's instance is hidden from the <code>bar()</code> method. Meaning that it's the exact same as running:</p>\n\n<pre><code>$class = get_class($foo);\n$class::bar();\n</code></pre></li>\n</ul>\n\n<p>Therefore, <code>$this</code> is not defined in the static call.</p>\n\n<h2>From Inside Of An Instance/Class</h2>\n\n<p>Things change a bit here. The same operators are used, but their meaning becomes significantly blurred. </p>\n\n<p>The <em>object-operator</em> <code>-></code> is still used to make calls to the object's instance state.</p>\n\n<pre><code>class Foo {\n public $a = 1;\n public function bar() {\n return $this->a;\n }\n}\n</code></pre>\n\n<p>Calling the <code>bar()</code> method on <code>$foo</code> (an instance of <code>Foo</code>) using the object-operator: <code>$foo->bar()</code> will result in the instance's version of <code>$a</code>.</p>\n\n<p>So that's how we expect.</p>\n\n<p>The meaning of the <code>::</code> operator though changes. It depends on the context of the call to the current function:</p>\n\n<ul>\n<li><p>Within a static context</p>\n\n<p>Within a static context, any calls made using <code>::</code> will also be static. Let's look at an example:</p>\n\n<pre><code>class Foo {\n public function bar() {\n return Foo::baz();\n }\n public function baz() {\n return isset($this);\n }\n}\n</code></pre>\n\n<p>Calling <code>Foo::bar()</code> will call the <code>baz()</code> method statically, and hence <code>$this</code> will <strong>not</strong> be populated. It's worth noting that in recent versions of PHP (5.3+) this will trigger an <code>E_STRICT</code> error, because we're calling non-static methods statically.</p></li>\n<li><p>Within an instance context</p>\n\n<p>Within an instance context on the other hand, calls made using <code>::</code> depend on the receiver of the call (the method we're calling). If the method is defined as <code>static</code>, then it will use a static call. If it's not, it will forward the instance information.</p>\n\n<p>So, looking at the above code, calling <code>$foo->bar()</code> will return <code>true</code>, since the \"static\" call happens inside of an instance context.</p></li>\n</ul>\n\n<p>Make sense? Didn't think so. It's confusing.</p>\n\n<h1>Short-Cut Keywords</h1>\n\n<p>Because tying everything together using class names is rather dirty, PHP provides 3 basic \"shortcut\" keywords to make scope resolving easier.</p>\n\n<ul>\n<li><p><code>self</code> - This refers to the current class name. So <code>self::baz()</code> is the same as <code>Foo::baz()</code> within the <code>Foo</code> class (any method on it).</p></li>\n<li><p><code>parent</code> - This refers to the parent of the current class. </p></li>\n<li><p><code>static</code> - This refers to the called class. Thanks to inheritance, child classes can override methods and static properties. So calling them using <code>static</code> instead of a class name allows us to resolve where the call came from, rather than the current level. </p></li>\n</ul>\n\n<h1>Examples</h1>\n\n<p>The easiest way to understand this is to start looking at some examples. Let's pick a class:</p>\n\n<pre><code>class Person {\n public static $number = 0;\n public $id = 0;\n public function __construct() {\n self::$number++;\n $this->id = self::$number;\n }\n public $name = \"\";\n public function getName() {\n return $this->name;\n }\n public function getId() {\n return $this->id;\n }\n}\n\nclass Child extends Person {\n public $age = 0;\n public function __construct($age) {\n $this->age = $age;\n parent::__construct();\n }\n public function getName() {\n return 'child: ' . parent::getName();\n }\n}\n</code></pre>\n\n<p>Now, we're also looking at inheritance here. Ignore for a moment that this is a bad object model, but let's look at what happens when we play with this:</p>\n\n<pre><code>$bob = new Person;\n$bob->name = \"Bob\";\n$adam = new Person;\n$adam->name = \"Adam\";\n$billy = new Child;\n$billy->name = \"Billy\";\nvar_dump($bob->getId()); // 1\nvar_dump($adam->getId()); // 2\nvar_dump($billy->getId()); // 3\n</code></pre>\n\n<p>So the ID counter is shared across both instances and the children (because we're using <code>self</code> to access it. If we used <code>static</code>, we could override it in a child class).</p>\n\n<pre><code>var_dump($bob->getName()); // Bob\nvar_dump($adam->getName()); // Adam\nvar_dump($billy->getName()); // child: Billy\n</code></pre>\n\n<p>Note that we're executing the <code>Person::getName()</code> <em>instance</em> method every time. But we're using the <code>parent::getName()</code> to do it in one of the cases (the child case). This is what makes this approach powerful.</p>\n\n<h1>Word Of Caution #1</h1>\n\n<p>Note that the calling context is what determines if an instance is used. Therefore:</p>\n\n<pre><code>class Foo {\n public function isFoo() {\n return $this instanceof Foo;\n }\n}\n</code></pre>\n\n<p>Is not <strong>always</strong> true.</p>\n\n<pre><code>class Bar {\n public function doSomething() {\n return Foo::isFoo();\n }\n}\n$b = new Bar;\nvar_dump($b->doSomething()); // bool(false)\n</code></pre>\n\n<p>Now it is <em>really</em> weird here. We're calling a different class, but the <code>$this</code> that gets passed to the <code>Foo::isFoo()</code> method is the instance of <code>$bar</code>. </p>\n\n<p>This can cause all sorts of bugs and conceptual WTF-ery. So I'd highly suggest avoiding the <code>::</code> operator from within instance methods on anything except those three virtual \"short-cut\" keywords (<code>static</code>, <code>self</code>, and <code>parent</code>).</p>\n\n<h1>Word Of Caution #2</h1>\n\n<p>Note that static methods and properties are shared by everyone. That makes them basically global variables. With all the same problems that come with globals. So I would be really hesitant to store information in static methods/properties unless you're comfortable with it being truly global.</p>\n\n<h1>Word Of Caution #3</h1>\n\n<p>In general you'll want to use what's known as Late-Static-Binding by using <code>static</code> instead of <code>self</code>. But note that they are not the same thing, so saying \"always use <code>static</code> instead of <code>self</code> is really short-sighted. Instead, stop and think about the call you want to make and think if you want child classes to be able to override that <em>static resolved</em> call.</p>\n\n<h1>TL/DR</h1>\n\n<p>Too bad, go back and read it. It may be too long, but it's that long because this is a complex topic</p>\n\n<h1>TL/DR #2</h1>\n\n<p>Ok, fine. In short, <code>self</code> is used to reference <em>the current class name</em> within a class, where as <code>$this</code> refers to the current object <em>instance</em>. Note that <code>self</code> is a copy/paste short-cut. You can safely replace it with your class name, and it'll work fine. But <code>$this</code> is a dynamic variable that can't be determined ahead of time (and may not even be your class).</p>\n\n<h1>TL/DR #3</h1>\n\n<p>If the object-operator is used (<code>-></code>), then you <em>always</em> know you're dealing with an instance. If the scope-resolution-operator is used (<code>::</code>), you need more information about the context (are we in an object-context already? Are we outside of an object? etc).</p>\n"
},
{
"answer_id": 25842131,
"author": "Rakesh Singh",
"author_id": 1855621,
"author_profile": "https://Stackoverflow.com/users/1855621",
"pm_score": 3,
"selected": false,
"text": "<p><code>$this</code> refers to the current class object, and <code>self</code> refers to the current class (Not object). The class is the blueprint of the object. So you define a class, but you construct objects.</p>\n<p>So in other words, use <code>self for static</code> and <code>this for none-static members or methods</code>.</p>\n<p>Also in a child/parent scenario, <code>self / parent</code> is mostly used to identify child and parent class members and methods.</p>\n"
},
{
"answer_id": 26107386,
"author": "Will B.",
"author_id": 1144627,
"author_profile": "https://Stackoverflow.com/users/1144627",
"pm_score": 3,
"selected": false,
"text": "<p>Additionally since <code>$this::</code> has not been discussed yet.</p>\n\n<p>For informational purposes only, as of PHP 5.3 when dealing with instantiated objects to get the current scope value, as opposed to using <code>static::</code>, one can alternatively use <code>$this::</code> like so.</p>\n\n<p><a href=\"http://ideone.com/7etRHy\" rel=\"noreferrer\">http://ideone.com/7etRHy</a></p>\n\n<pre><code>class Foo\n{\n const NAME = 'Foo';\n\n //Always Foo::NAME (Foo) due to self\n protected static $staticName = self::NAME;\n\n public function __construct()\n {\n echo $this::NAME;\n }\n\n public function getStaticName()\n {\n echo $this::$staticName;\n }\n}\n\nclass Bar extends Foo\n{\n const NAME = 'FooBar';\n\n /**\n * override getStaticName to output Bar::NAME\n */\n public function getStaticName()\n {\n $this::$staticName = $this::NAME;\n parent::getStaticName();\n }\n}\n\n$foo = new Foo; //outputs Foo\n$bar = new Bar; //outputs FooBar\n$foo->getStaticName(); //outputs Foo\n$bar->getStaticName(); //outputs FooBar\n$foo->getStaticName(); //outputs FooBar\n</code></pre>\n\n<p>Using the code above is not common or recommended practice, but is simply to illustrate its usage, and is to act as more of a \"Did you know?\" in reference to the original poster's question.</p>\n\n<p>It also represents the usage of <code>$object::CONSTANT</code> for example <code>echo $foo::NAME;</code> as opposed to <code>$this::NAME;</code></p>\n"
},
{
"answer_id": 27689715,
"author": "ramin rostami",
"author_id": 1512065,
"author_profile": "https://Stackoverflow.com/users/1512065",
"pm_score": 5,
"selected": false,
"text": "<p>In PHP, you use the self keyword to access static properties and methods.</p>\n\n<p>The problem is that you can replace <code>$this->method()</code> with <code>self::method()</code>anywhere, regardless if <code>method()</code> is declared static or not. So which one should you use?</p>\n\n<p>Consider this code:</p>\n\n<pre><code>class ParentClass {\n function test() {\n self::who(); // will output 'parent'\n $this->who(); // will output 'child'\n }\n\n function who() {\n echo 'parent';\n }\n}\n\nclass ChildClass extends ParentClass {\n function who() {\n echo 'child';\n }\n}\n\n$obj = new ChildClass();\n$obj->test();\n</code></pre>\n\n<p>In this example, <code>self::who()</code> will always output ‘parent’, while <code>$this->who()</code> will depend on what class the object has.</p>\n\n<p>Now we can see that self refers to the class in which it is called, while <code>$this</code> refers to the <strong>class of the current object</strong>.</p>\n\n<p>So, you should use self only when <code>$this</code> is not available, or when you don’t want to allow descendant classes to overwrite the current method.</p>\n"
},
{
"answer_id": 30554801,
"author": "tleb",
"author_id": 4255615,
"author_profile": "https://Stackoverflow.com/users/4255615",
"pm_score": 4,
"selected": false,
"text": "<p>Here is a small benchmark (7.2.24 on <a href=\"https://repl.it/repls/FewUnacceptableObservatory\" rel=\"nofollow noreferrer\">repl.it</a>):</p>\n<pre><code> Speed (in seconds) Percentage\n$this-> 0.91760206222534 100\nself:: 1.0047659873962 109.49909865716\nstatic:: 0.98066782951355 106.87288857386\n</code></pre>\n<p>Results for 4 000 000 runs. Conclusion: it doesn't matter. And here is the code I used:</p>\n<pre><code><?php\n\nclass Foo\n{\n public function calling_this() { $this->called(); }\n public function calling_self() { self::called(); }\n public function calling_static() { static::called(); }\n public static function called() {}\n}\n\n$foo = new Foo();\n$n = 4000000;\n$times = [];\n\n// warmup\nfor ($i = 0; $i < $n; $i++) { $foo->calling_this(); }\nfor ($i = 0; $i < $n; $i++) { $foo->calling_self(); }\nfor ($i = 0; $i < $n; $i++) { $foo->calling_static(); }\n\n$start = microtime(true);\nfor ($i = 0; $i < $n; $i++) { $foo->calling_this(); }\n$times["this"] = microtime(true)-$start;\n\n$start = microtime(true);\nfor ($i = 0; $i < $n; $i++) { $foo->calling_self(); }\n$times["self"] = microtime(true)-$start;\n\n$start = microtime(true);\nfor ($i = 0; $i < $n; $i++) { $foo->calling_static(); }\n$times["static"] = microtime(true)-$start;\n\n$min = min($times);\necho $times["this"] . "\\t" . ($times["this"] / $min)*100 . "\\n";\necho $times["self"] . "\\t" . ($times["self"] / $min)*100 . "\\n";\necho $times["static"] . "\\t" . ($times["static"] / $min)*100 . "\\n";\n</code></pre>\n"
},
{
"answer_id": 34131217,
"author": "Fil",
"author_id": 3721034,
"author_profile": "https://Stackoverflow.com/users/3721034",
"pm_score": 1,
"selected": false,
"text": "<p>According to php.net there are three special keywords in this context: <code>self</code>, <code>parent</code> and <code>static</code>. They are used to access properties or methods from inside the class definition.</p>\n\n<p><code>$this</code>, on the other hand, is used to call an instance and methods of any class as long as that class is accessible.</p>\n"
},
{
"answer_id": 34554103,
"author": "Kabir Hossain",
"author_id": 3173328,
"author_profile": "https://Stackoverflow.com/users/3173328",
"pm_score": 5,
"selected": false,
"text": "<p><code>self</code> refers to the current class (in which it is called),</p>\n<p><code>$this</code> refers to the current object.\nYou can use static instead of self.</p>\n<p>See the example:</p>\n<pre><code>class ParentClass {\n function test() {\n self::which(); // Outputs 'parent'\n $this->which(); // Outputs 'child'\n }\n\n function which() {\n echo 'parent';\n }\n}\n\nclass ChildClass extends ParentClass {\n function which() {\n echo 'child';\n }\n}\n\n$obj = new ChildClass();\n$obj->test();\n</code></pre>\n<p>Output:</p>\n<pre><code> parent\n child\n</code></pre>\n"
},
{
"answer_id": 35163551,
"author": "li bing zhao",
"author_id": 4637840,
"author_profile": "https://Stackoverflow.com/users/4637840",
"pm_score": 2,
"selected": false,
"text": "<p>Case 1: Use <code>self</code> can be used for class constants</p>\n\n<pre> class classA { \n const FIXED_NUMBER = 4; \n self::POUNDS_TO_KILOGRAMS\n}\n</pre>\n\n<p>If you want to call it outside of the class, use <code>classA::POUNDS_TO_KILOGRAMS</code> to access the constants</p>\n\n<p>Case 2: For static properties </p>\n\n<pre>\nclass classC {\n public function __construct() { \n self::$_counter++; $this->num = self::$_counter;\n }\n}\n</pre>\n"
},
{
"answer_id": 50426807,
"author": "Mike",
"author_id": 8243442,
"author_profile": "https://Stackoverflow.com/users/8243442",
"pm_score": 4,
"selected": false,
"text": "<p>I ran into the same question and the simple answer was:</p>\n<ul>\n<li><code>$this</code> requires an instance of the class</li>\n<li><code>self::</code> doesn't</li>\n</ul>\n<p>Whenever you are using <strong>static methods</strong> or <strong>static attributes</strong> and want to call them without having an object of the class instantiated, you need to use <code>self:</code> to call them, because <code>$this</code> always requires an object to be created.</p>\n"
},
{
"answer_id": 61258357,
"author": "Deepak Syal",
"author_id": 5371637,
"author_profile": "https://Stackoverflow.com/users/5371637",
"pm_score": 3,
"selected": false,
"text": "<p><strong>self::</strong> A keyword used for the current class and basically it is used to access static members, methods, and constants. But in case of <strong>$this</strong>, you cannot call the static member, method, and functions.</p>\n<p>You can use the <strong>self::</strong> keyword in another class and access the static members, method, and constants. When it will be extended from the parent class and the same in case of the <strong>$this</strong> keyword. You can access the non-static members, method and function in another class when it will be extended from the parent class.</p>\n<p>The code given below is an example of the <strong>self::</strong> and <strong>$this</strong> keywords. Just copy and paste the code in your code file and see the output.</p>\n<pre><code>class cars{\n var $doors = 4;\n static $car_wheel = 4;\n\n public function car_features(){\n echo $this->doors . " Doors <br>";\n echo self::$car_wheel . " Wheels <br>";\n }\n}\n\nclass spec extends cars{\n function car_spec(){\n print(self::$car_wheel . " Doors <br>");\n print($this->doors . " Wheels <br>");\n }\n}\n\n/********Parent class output*********/\n\n$car = new cars;\nprint_r($car->car_features());\n\necho "------------------------<br>";\n\n/********Extend class from another class output**********/\n\n\n$car_spec_show = new spec;\n\nprint($car_spec_show->car_spec());\n</code></pre>\n"
}
]
| 2008/09/30 | [
"https://Stackoverflow.com/questions/151969",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4682/"
]
| In PHP 5, what is the difference between using `self` and `$this`?
When is each appropriate? | Short Answer
============
>
> Use `$this` to refer to the current
> object. Use `self` to refer to the
> current class. In other words, use
> `$this->member` for non-static members,
> use `self::$member` for static members.
>
>
>
Full Answer
===========
Here is an example of **correct** usage of `$this` and `self` for non-static and static member variables:
```
<?php
class X {
private $non_static_member = 1;
private static $static_member = 2;
function __construct() {
echo $this->non_static_member . ' '
. self::$static_member;
}
}
new X();
?>
```
Here is an example of **incorrect** usage of `$this` and `self` for non-static and static member variables:
```
<?php
class X {
private $non_static_member = 1;
private static $static_member = 2;
function __construct() {
echo self::$non_static_member . ' '
. $this->static_member;
}
}
new X();
?>
```
Here is an example of **polymorphism** with `$this` for member functions:
```
<?php
class X {
function foo() {
echo 'X::foo()';
}
function bar() {
$this->foo();
}
}
class Y extends X {
function foo() {
echo 'Y::foo()';
}
}
$x = new Y();
$x->bar();
?>
```
Here is an example of **suppressing polymorphic behaviour** by using `self` for member functions:
```
<?php
class X {
function foo() {
echo 'X::foo()';
}
function bar() {
self::foo();
}
}
class Y extends X {
function foo() {
echo 'Y::foo()';
}
}
$x = new Y();
$x->bar();
?>
```
>
> The idea is that `$this->foo()` calls the `foo()` member function of whatever is the exact type of the current object. If the object is of `type X`, it thus calls `X::foo()`. If the object is of `type Y`, it calls `Y::foo()`. But with self::foo(), `X::foo()` is always called.
>
>
>
From <http://www.phpbuilder.com/board/showthread.php?t=10354489>:
By <http://board.phpbuilder.com/member.php?145249-laserlight> |
151,979 | <p>Have a look at this very simple example WPF program:</p>
<pre><code><Window x:Class="WpfApplication1.Window1"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="Window1" Height="300" Width="300">
<GroupBox>
<GroupBox.Header>
<CheckBox Content="Click Here"/>
</GroupBox.Header>
</GroupBox>
</Window>
</code></pre>
<p>So I have a GroupBox whose header is a CheckBox. We've all done something like this - typically you bind the content of the GroupBox in such a way that it's disabled when the CheckBox is unchecked.</p>
<p>However, when I run this application and click on the CheckBox, I've found that sometimes my mouse clicks are swallowed and the CheckBox's status doesn't change. If I'm right, it's when I click on the exact row of pixels that the GroupBox's top border sits on.</p>
<p>Can someone duplicate this? Why would this occur, and is there a way around it?</p>
<p>Edit: Setting the GroupBox's BorderThickness to 0 solves the problem, but obviously it removes the border, so it doesn't look like a GroupBox anymore.</p>
| [
{
"answer_id": 151999,
"author": "rudigrobler",
"author_id": 5147,
"author_profile": "https://Stackoverflow.com/users/5147",
"pm_score": 2,
"selected": false,
"text": "<p>If you change the GroupBox's BorderBrush, it works!</p>\n\n<pre><code><GroupBox BorderBrush=\"{x:Null}\">\n</code></pre>\n\n<p>I know this defeats the objective but it does prove where the problem lies!</p>\n"
},
{
"answer_id": 152562,
"author": "Ian Oakes",
"author_id": 21606,
"author_profile": "https://Stackoverflow.com/users/21606",
"pm_score": 5,
"selected": true,
"text": "<p>It appears to be a subtle bug in the control template for the GroupBox. I found by editing the default template for the GroupBox and moving the Border named 'Header' to the last item in the control templates Grid element, the issue resolves itself. </p>\n\n<p>The reason is that the one of the other Border elements with a TemplateBinding of BorderBrush was further down in the visual tree and was capturing the mouse click, that's why setting the BorderBrush to null allowed the CheckBox to correctly receive the mouse click.</p>\n\n<p>Below is resulting style for the GroupBox. It is nearly identical to the default template for the control, except for the Border element named 'Header', which is now the last child of the Grid, rather than the second.</p>\n\n<pre><code><BorderGapMaskConverter x:Key=\"BorderGapMaskConverter\"/>\n\n<Style x:Key=\"GroupBoxStyle1\" TargetType=\"{x:Type GroupBox}\">\n <Setter Property=\"BorderBrush\" Value=\"#D5DFE5\"/>\n <Setter Property=\"BorderThickness\" Value=\"1\"/>\n <Setter Property=\"Template\">\n <Setter.Value>\n <ControlTemplate TargetType=\"{x:Type GroupBox}\">\n <Grid SnapsToDevicePixels=\"true\">\n <Grid.RowDefinitions>\n <RowDefinition Height=\"Auto\"/>\n <RowDefinition Height=\"Auto\"/>\n <RowDefinition Height=\"*\"/>\n <RowDefinition Height=\"6\"/>\n </Grid.RowDefinitions>\n <Grid.ColumnDefinitions>\n <ColumnDefinition Width=\"6\"/>\n <ColumnDefinition Width=\"Auto\"/>\n <ColumnDefinition Width=\"*\"/>\n <ColumnDefinition Width=\"6\"/>\n </Grid.ColumnDefinitions>\n <Border Grid.Column=\"0\" Grid.ColumnSpan=\"4\" Grid.Row=\"1\" Grid.RowSpan=\"3\" Background=\"{TemplateBinding Background}\" BorderBrush=\"Transparent\" BorderThickness=\"{TemplateBinding BorderThickness}\" CornerRadius=\"4\"/>\n <ContentPresenter Margin=\"{TemplateBinding Padding}\" SnapsToDevicePixels=\"{TemplateBinding SnapsToDevicePixels}\" Grid.Column=\"1\" Grid.ColumnSpan=\"2\" Grid.Row=\"2\"/>\n <Border Grid.ColumnSpan=\"4\" Grid.Row=\"1\" Grid.RowSpan=\"3\" BorderBrush=\"White\" BorderThickness=\"{TemplateBinding BorderThickness}\" CornerRadius=\"4\">\n <Border.OpacityMask>\n <MultiBinding Converter=\"{StaticResource BorderGapMaskConverter}\" ConverterParameter=\"7\">\n <Binding Path=\"ActualWidth\" ElementName=\"Header\"/>\n <Binding Path=\"ActualWidth\" RelativeSource=\"{RelativeSource Self}\"/>\n <Binding Path=\"ActualHeight\" RelativeSource=\"{RelativeSource Self}\"/>\n </MultiBinding>\n </Border.OpacityMask>\n <Border BorderBrush=\"{TemplateBinding BorderBrush}\" BorderThickness=\"{TemplateBinding BorderThickness}\" CornerRadius=\"3\">\n <Border BorderBrush=\"White\" BorderThickness=\"{TemplateBinding BorderThickness}\" CornerRadius=\"2\"/>\n </Border>\n </Border>\n <Border x:Name=\"Header\" Grid.Column=\"1\" Grid.Row=\"0\" Grid.RowSpan=\"2\" Padding=\"3,1,3,0\">\n <ContentPresenter SnapsToDevicePixels=\"{TemplateBinding SnapsToDevicePixels}\" ContentSource=\"Header\" RecognizesAccessKey=\"True\"/>\n </Border>\n </Grid>\n </ControlTemplate>\n </Setter.Value>\n </Setter>\n</Style>\n</code></pre>\n"
},
{
"answer_id": 3709904,
"author": "Rune Andersen",
"author_id": 447453,
"author_profile": "https://Stackoverflow.com/users/447453",
"pm_score": 4,
"selected": false,
"text": "<p>An alternative solution I made is implementing OnApplyTemplate in a derived GroupBox:</p>\n\n<pre><code>public override void OnApplyTemplate()\n{\n base.OnApplyTemplate();\n if (Children.Count == 0) return;\n\n var grid = GetVisualChild(0) as Grid;\n if (grid != null && grid.Children.Count > 3)\n {\n var bd = grid.Children[3] as Border;\n if (bd != null)\n {\n bd.IsHitTestVisible = false;\n }\n }\n}\n</code></pre>\n"
},
{
"answer_id": 4014508,
"author": "Ray",
"author_id": 233,
"author_profile": "https://Stackoverflow.com/users/233",
"pm_score": 5,
"selected": false,
"text": "<p>Ian Oakes answer stuffs up the tab order such that the header comes after the content. It's possible to modify the control template such that the border can't receive focus.</p>\n\n<p>To do this, modify the template so that the 2nd and 3rd borders (both in Grid Row 1) have <code>IsHitTestVisible=false</code></p>\n\n<p>Complete template below</p>\n\n<pre><code><BorderGapMaskConverter x:Key=\"GroupBoxBorderGapMaskConverter\" />\n\n<Style x:Key=\"{x:Type GroupBox}\" TargetType=\"{x:Type GroupBox}\">\n <Setter Property=\"Control.BorderBrush\" Value=\"#FFD5DFE5\" />\n <Setter Property=\"Control.BorderThickness\" Value=\"1\" />\n <Setter Property=\"Control.Template\">\n <Setter.Value>\n <ControlTemplate TargetType=\"{x:Type GroupBox}\">\n <Grid SnapsToDevicePixels=\"True\">\n <Grid.ColumnDefinitions>\n <ColumnDefinition Width=\"6\" />\n <ColumnDefinition Width=\"Auto\" />\n <ColumnDefinition Width=\"*\" />\n <ColumnDefinition Width=\"6\" />\n </Grid.ColumnDefinitions>\n <Grid.RowDefinitions>\n <RowDefinition Height=\"Auto\" />\n <RowDefinition Height=\"Auto\" />\n <RowDefinition Height=\"*\" />\n <RowDefinition Height=\"6\" />\n </Grid.RowDefinitions>\n <Border Name=\"Header\" Padding=\"3,1,3,0\" Grid.Row=\"0\" Grid.RowSpan=\"2\" Grid.Column=\"1\">\n <ContentPresenter ContentSource=\"Header\" RecognizesAccessKey=\"True\" SnapsToDevicePixels=\"{TemplateBinding UIElement.SnapsToDevicePixels}\" />\n </Border>\n <Border CornerRadius=\"4\" Grid.Row=\"1\" Grid.RowSpan=\"3\" Grid.Column=\"0\" Grid.ColumnSpan=\"4\" BorderThickness=\"{TemplateBinding Control.BorderThickness}\" BorderBrush=\"#00FFFFFF\" Background=\"{TemplateBinding Control.Background}\" IsHitTestVisible=\"False\" />\n <ContentPresenter Grid.Row=\"2\" Grid.Column=\"1\" Grid.ColumnSpan=\"2\" Margin=\"{TemplateBinding Control.Padding}\" SnapsToDevicePixels=\"{TemplateBinding UIElement.SnapsToDevicePixels}\"/>\n <Border CornerRadius=\"4\" Grid.Row=\"1\" Grid.RowSpan=\"3\" Grid.ColumnSpan=\"4\" BorderThickness=\"{TemplateBinding Control.BorderThickness}\" BorderBrush=\"#FFFFFFFF\" IsHitTestVisible=\"False\">\n <UIElement.OpacityMask>\n <MultiBinding Converter=\"{StaticResource GroupBoxBorderGapMaskConverter}\" ConverterParameter=\"7\">\n <Binding ElementName=\"Header\" Path=\"ActualWidth\" />\n <Binding Path=\"ActualWidth\" RelativeSource=\"{RelativeSource Self}\" />\n <Binding Path=\"ActualHeight\" RelativeSource=\"{RelativeSource Self}\" />\n </MultiBinding>\n </UIElement.OpacityMask>\n <Border BorderThickness=\"{TemplateBinding Control.BorderThickness}\" BorderBrush=\"{TemplateBinding Control.BorderBrush}\" CornerRadius=\"3\">\n <Border BorderThickness=\"{TemplateBinding Control.BorderThickness}\" BorderBrush=\"#FFFFFFFF\" CornerRadius=\"2\" />\n </Border>\n </Border> \n </Grid>\n </ControlTemplate>\n </Setter.Value>\n </Setter>\n</Style>\n</code></pre>\n"
}
]
| 2008/09/30 | [
"https://Stackoverflow.com/questions/151979",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/615/"
]
| Have a look at this very simple example WPF program:
```
<Window x:Class="WpfApplication1.Window1"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="Window1" Height="300" Width="300">
<GroupBox>
<GroupBox.Header>
<CheckBox Content="Click Here"/>
</GroupBox.Header>
</GroupBox>
</Window>
```
So I have a GroupBox whose header is a CheckBox. We've all done something like this - typically you bind the content of the GroupBox in such a way that it's disabled when the CheckBox is unchecked.
However, when I run this application and click on the CheckBox, I've found that sometimes my mouse clicks are swallowed and the CheckBox's status doesn't change. If I'm right, it's when I click on the exact row of pixels that the GroupBox's top border sits on.
Can someone duplicate this? Why would this occur, and is there a way around it?
Edit: Setting the GroupBox's BorderThickness to 0 solves the problem, but obviously it removes the border, so it doesn't look like a GroupBox anymore. | It appears to be a subtle bug in the control template for the GroupBox. I found by editing the default template for the GroupBox and moving the Border named 'Header' to the last item in the control templates Grid element, the issue resolves itself.
The reason is that the one of the other Border elements with a TemplateBinding of BorderBrush was further down in the visual tree and was capturing the mouse click, that's why setting the BorderBrush to null allowed the CheckBox to correctly receive the mouse click.
Below is resulting style for the GroupBox. It is nearly identical to the default template for the control, except for the Border element named 'Header', which is now the last child of the Grid, rather than the second.
```
<BorderGapMaskConverter x:Key="BorderGapMaskConverter"/>
<Style x:Key="GroupBoxStyle1" TargetType="{x:Type GroupBox}">
<Setter Property="BorderBrush" Value="#D5DFE5"/>
<Setter Property="BorderThickness" Value="1"/>
<Setter Property="Template">
<Setter.Value>
<ControlTemplate TargetType="{x:Type GroupBox}">
<Grid SnapsToDevicePixels="true">
<Grid.RowDefinitions>
<RowDefinition Height="Auto"/>
<RowDefinition Height="Auto"/>
<RowDefinition Height="*"/>
<RowDefinition Height="6"/>
</Grid.RowDefinitions>
<Grid.ColumnDefinitions>
<ColumnDefinition Width="6"/>
<ColumnDefinition Width="Auto"/>
<ColumnDefinition Width="*"/>
<ColumnDefinition Width="6"/>
</Grid.ColumnDefinitions>
<Border Grid.Column="0" Grid.ColumnSpan="4" Grid.Row="1" Grid.RowSpan="3" Background="{TemplateBinding Background}" BorderBrush="Transparent" BorderThickness="{TemplateBinding BorderThickness}" CornerRadius="4"/>
<ContentPresenter Margin="{TemplateBinding Padding}" SnapsToDevicePixels="{TemplateBinding SnapsToDevicePixels}" Grid.Column="1" Grid.ColumnSpan="2" Grid.Row="2"/>
<Border Grid.ColumnSpan="4" Grid.Row="1" Grid.RowSpan="3" BorderBrush="White" BorderThickness="{TemplateBinding BorderThickness}" CornerRadius="4">
<Border.OpacityMask>
<MultiBinding Converter="{StaticResource BorderGapMaskConverter}" ConverterParameter="7">
<Binding Path="ActualWidth" ElementName="Header"/>
<Binding Path="ActualWidth" RelativeSource="{RelativeSource Self}"/>
<Binding Path="ActualHeight" RelativeSource="{RelativeSource Self}"/>
</MultiBinding>
</Border.OpacityMask>
<Border BorderBrush="{TemplateBinding BorderBrush}" BorderThickness="{TemplateBinding BorderThickness}" CornerRadius="3">
<Border BorderBrush="White" BorderThickness="{TemplateBinding BorderThickness}" CornerRadius="2"/>
</Border>
</Border>
<Border x:Name="Header" Grid.Column="1" Grid.Row="0" Grid.RowSpan="2" Padding="3,1,3,0">
<ContentPresenter SnapsToDevicePixels="{TemplateBinding SnapsToDevicePixels}" ContentSource="Header" RecognizesAccessKey="True"/>
</Border>
</Grid>
</ControlTemplate>
</Setter.Value>
</Setter>
</Style>
``` |
152,005 | <p>What is currying?</p>
<p>How can currying be done in C++?</p>
<p>Please Explain binders in STL container?</p>
| [
{
"answer_id": 152020,
"author": "Greg Hewgill",
"author_id": 893,
"author_profile": "https://Stackoverflow.com/users/893",
"pm_score": 6,
"selected": true,
"text": "<p>In short, currying takes a function <code>f(x, y)</code> and given a fixed <code>Y</code>, gives a new function <code>g(x)</code> where</p>\n\n<pre><code>g(x) == f(x, Y)\n</code></pre>\n\n<p>This new function may be called in situations where only one argument is supplied, and passes the call on to the original <code>f</code> function with the fixed <code>Y</code> argument.</p>\n\n<p>The binders in the STL allow you to do this for C++ functions. For example:</p>\n\n<pre><code>#include <functional>\n#include <iostream>\n#include <vector>\n\nusing namespace std;\n\n// declare a binary function object\nclass adder: public binary_function<int, int, int> {\npublic:\n int operator()(int x, int y) const\n {\n return x + y;\n }\n};\n\nint main()\n{\n // initialise some sample data\n vector<int> a, b;\n a.push_back(1);\n a.push_back(2);\n a.push_back(3);\n\n // here we declare a function object f and try it out\n adder f;\n cout << \"f(2, 3) = \" << f(2, 3) << endl;\n\n // transform() expects a function with one argument, so we use\n // bind2nd to make a new function based on f, that takes one\n // argument and adds 5 to it\n transform(a.begin(), a.end(), back_inserter(b), bind2nd(f, 5));\n\n // output b to see what we got\n cout << \"b = [\" << endl;\n for (vector<int>::iterator i = b.begin(); i != b.end(); ++i) {\n cout << \" \" << *i << endl;\n }\n cout << \"]\" << endl;\n\n return 0;\n}\n</code></pre>\n"
},
{
"answer_id": 152021,
"author": "John Millikin",
"author_id": 3560,
"author_profile": "https://Stackoverflow.com/users/3560",
"pm_score": 3,
"selected": false,
"text": "<p>Currying is a way of reducing a function that takes multiple arguments into a sequence of nested functions with one argument each:</p>\n\n<pre><code>full = (lambda a, b, c: (a + b + c))\nprint full (1, 2, 3) # print 6\n\n# Curried style\ncurried = (lambda a: (lambda b: (lambda c: (a + b + c))))\nprint curried (1)(2)(3) # print 6\n</code></pre>\n\n<p>Currying is nice because you can define functions that are simply wrappers around other functions with pre-defined values, and then pass around the simplified functions. C++ STL binders provide an implementation of this in C++.</p>\n"
},
{
"answer_id": 152268,
"author": "Konrad Rudolph",
"author_id": 1968,
"author_profile": "https://Stackoverflow.com/users/1968",
"pm_score": 4,
"selected": false,
"text": "<p>Have a look at <a href=\"http://www.boost.org/doc/libs/1_36_0/libs/bind/bind.html\" rel=\"nofollow noreferrer\">Boost.Bind</a> which makes the process shown by Greg more versatile:</p>\n\n<pre><code>transform(a.begin(), a.end(), back_inserter(b), bind(f, _1, 5));\n</code></pre>\n\n<p>This binds <code>5</code> to <code>f</code>'s second argument.</p>\n\n<p>It’s worth noting that this is <em>not</em> currying (instead, it’s partial application). However, using currying in a general way is hard in C++ (in fact, it only recently became possible at all) and partial application is often used instead.</p>\n"
},
{
"answer_id": 160286,
"author": "Aaron",
"author_id": 14153,
"author_profile": "https://Stackoverflow.com/users/14153",
"pm_score": 4,
"selected": false,
"text": "<p>Simplifying Gregg's example, using tr1:</p>\n\n<pre><code>#include <functional> \nusing namespace std;\nusing namespace std::tr1;\nusing namespace std::tr1::placeholders;\n\nint f(int, int);\n..\nint main(){\n function<int(int)> g = bind(f, _1, 5); // g(x) == f(x, 5)\n function<int(int)> h = bind(f, 2, _1); // h(x) == f(2, x)\n function<int(int,int)> j = bind(g, _2); // j(x,y) == g(y)\n}\n</code></pre>\n\n<p>Tr1 functional components allow you to write rich functional-style code in C++. As well, C++0x will allow for in-line lambda functions to do this as well:</p>\n\n<pre><code>int f(int, int);\n..\nint main(){\n auto g = [](int x){ return f(x,5); }; // g(x) == f(x, 5)\n auto h = [](int x){ return f(2,x); }; // h(x) == f(2, x)\n auto j = [](int x, int y){ return g(y); }; // j(x,y) == g(y)\n}\n</code></pre>\n\n<p>And while C++ doesn't provide the rich side-effect analysis that some functional-oriented programming languages perform, const analysis and C++0x lambda syntax can help:</p>\n\n<pre><code>struct foo{\n int x;\n int operator()(int y) const {\n x = 42; // error! const function can't modify members\n }\n};\n..\nint main(){\n int x;\n auto f = [](int y){ x = 42; }; // error! lambdas don't capture by default.\n}\n</code></pre>\n\n<p>Hope that helps.</p>\n"
},
{
"answer_id": 6137984,
"author": "missingfaktor",
"author_id": 192247,
"author_profile": "https://Stackoverflow.com/users/192247",
"pm_score": 4,
"selected": false,
"text": "<p>Other answers nicely explain binders, so I won't repeat that part here. I will only demonstrate how currying and partial application can be done with lambdas in C++0x.</p>\n\n<p><strong>Code example:</strong> (Explanation in comments)</p>\n\n<pre><code>#include <iostream>\n#include <functional>\n\nusing namespace std;\n\nconst function<int(int, int)> & simple_add = \n [](int a, int b) -> int {\n return a + b;\n };\n\nconst function<function<int(int)>(int)> & curried_add = \n [](int a) -> function<int(int)> {\n return [a](int b) -> int {\n return a + b;\n };\n };\n\nint main() {\n // Demonstrating simple_add\n cout << simple_add(4, 5) << endl; // prints 9\n\n // Demonstrating curried_add\n cout << curried_add(4)(5) << endl; // prints 9\n\n // Create a partially applied function from curried_add\n const auto & add_4 = curried_add(4);\n cout << add_4(5) << endl; // prints 9\n}\n</code></pre>\n"
},
{
"answer_id": 7940773,
"author": "Rolf",
"author_id": 370786,
"author_profile": "https://Stackoverflow.com/users/370786",
"pm_score": 2,
"selected": false,
"text": "<p>These Links are relevant:</p>\n\n<p>The Lambda Calculus page on Wikipedia has a clear example of currying<br/>\n<a href=\"http://en.wikipedia.org/wiki/Lambda_calculus#Motivation\" rel=\"nofollow\">http://en.wikipedia.org/wiki/Lambda_calculus#Motivation</a></p>\n\n<p>This paper treats currying in C/C++<br/>\n<a href=\"http://asg.unige.ch/site/papers/Dami91a.pdf\" rel=\"nofollow\">http://asg.unige.ch/site/papers/Dami91a.pdf</a></p>\n"
},
{
"answer_id": 26213996,
"author": "kasoki",
"author_id": 2292096,
"author_profile": "https://Stackoverflow.com/users/2292096",
"pm_score": 4,
"selected": false,
"text": "<p>If you're using C++14 it's very easy:</p>\n\n<pre><code>template<typename Function, typename... Arguments>\nauto curry(Function function, Arguments... args) {\n return [=](auto... rest) {\n return function(args..., rest...);\n }; // don't forget semicolumn\n}\n</code></pre>\n\n<p>You can then use it like this:</p>\n\n<pre><code>auto add = [](auto x, auto y) { return x + y; }\n\n// curry 4 into add\nauto add4 = curry(add, 4);\n\nadd4(6); // 10\n</code></pre>\n"
},
{
"answer_id": 26768388,
"author": "Julian",
"author_id": 2622629,
"author_profile": "https://Stackoverflow.com/users/2622629",
"pm_score": 6,
"selected": false,
"text": "<h1>1. What is currying?</h1>\n<p>Currying simply means a transformation of a function of several arguments to a function of a single argument. This is most easily illustrated using an example:</p>\n<p>Take a function <code>f</code> that accepts three arguments:</p>\n<pre><code>int\nf(int a,std::string b,float c)\n{\n // do something with a, b, and c\n return 0;\n}\n</code></pre>\n<p>If we want to call <code>f</code>, we have to provide all of its arguments <code>f(1,"some string",19.7f)</code>.</p>\n<p>Then a curried version of <code>f</code>, let's call it <code>curried_f=curry(f)</code> only expects a single argument, that corresponds to the first argument of <code>f</code>, namely the argument <code>a</code>. Additionally, <code>f(1,"some string",19.7f)</code> can also be written using the curried version as <code>curried_f(1)("some string")(19.7f)</code>. The return value of <code>curried_f(1)</code> on the other hand is just another function, that handles the next argument of <code>f</code>. In the end, we end up with a function or callable <code>curried_f</code> that fulfills the following equality:</p>\n<pre><code>curried_f(first_arg)(second_arg)...(last_arg) == f(first_arg,second_arg,...,last_arg).\n</code></pre>\n<h1>2. How can currying be achieved in C++?</h1>\n<p>The following is a little bit more complicated, but works very well for me (using c++11)... It also allows currying of arbitrary degree like so: <code>auto curried=curry(f)(arg1)(arg2)(arg3)</code> and later <code>auto result=curried(arg4)(arg5)</code>. Here it goes:</p>\n<pre><code>#include <functional>\n\nnamespace _dtl {\n\n template <typename FUNCTION> struct\n _curry;\n\n // specialization for functions with a single argument\n template <typename R,typename T> struct\n _curry<std::function<R(T)>> {\n using\n type = std::function<R(T)>;\n \n const type\n result;\n \n _curry(type fun) : result(fun) {}\n \n };\n\n // recursive specialization for functions with more arguments\n template <typename R,typename T,typename...Ts> struct\n _curry<std::function<R(T,Ts...)>> {\n using\n remaining_type = typename _curry<std::function<R(Ts...)> >::type;\n \n using\n type = std::function<remaining_type(T)>;\n \n const type\n result;\n \n _curry(std::function<R(T,Ts...)> fun)\n : result (\n [=](const T& t) {\n return _curry<std::function<R(Ts...)>>(\n [=](const Ts&...ts){ \n return fun(t, ts...); \n }\n ).result;\n }\n ) {}\n };\n}\n\ntemplate <typename R,typename...Ts> auto\ncurry(const std::function<R(Ts...)> fun)\n-> typename _dtl::_curry<std::function<R(Ts...)>>::type\n{\n return _dtl::_curry<std::function<R(Ts...)>>(fun).result;\n}\n\ntemplate <typename R,typename...Ts> auto\ncurry(R(* const fun)(Ts...))\n-> typename _dtl::_curry<std::function<R(Ts...)>>::type\n{\n return _dtl::_curry<std::function<R(Ts...)>>(fun).result;\n}\n\n#include <iostream>\n\nvoid \nf(std::string a,std::string b,std::string c)\n{\n std::cout << a << b << c;\n}\n\nint \nmain() {\n curry(f)("Hello ")("functional ")("world!");\n return 0;\n}\n</code></pre>\n<p><a href=\"http://ideone.com/CQ8ELv\" rel=\"noreferrer\">View output</a></p>\n<p>OK, as Samer commented, I should add some explanations as to how this works. The actual implementation is done in the <code>_dtl::_curry</code>, while the template functions <code>curry</code> are only convenience wrappers. The implementation is recursive over the arguments of the <code>std::function</code> template argument <code>FUNCTION</code>.</p>\n<p>For a function with only a single argument, the result is identical to the original function.</p>\n<pre><code> _curry(std::function<R(T,Ts...)> fun)\n : result (\n [=](const T& t) {\n return _curry<std::function<R(Ts...)>>(\n [=](const Ts&...ts){ \n return fun(t, ts...); \n }\n ).result;\n }\n ) {}\n</code></pre>\n<p>Here the tricky thing: For a function with more arguments, we return a lambda whose argument is bound to the first argument to the call to <code>fun</code>. Finally, the remaining currying for the remaining <code>N-1</code> arguments is delegated to the implementation of <code>_curry<Ts...></code> with one less template argument.</p>\n<h1>Update for c++14 / 17:</h1>\n<p>A new idea to approach the problem of currying just came to me... With the introduction of <code>if constexpr</code> into c++17 (and with the help of <code>void_t</code> to determine if a function is fully curried), things seem to get a lot easier:</p>\n<pre><code>template< class, class = std::void_t<> > struct \nneeds_unapply : std::true_type { };\n \ntemplate< class T > struct \nneeds_unapply<T, std::void_t<decltype(std::declval<T>()())>> : std::false_type { };\n\ntemplate <typename F> auto\ncurry(F&& f) {\n /// Check if f() is a valid function call. If not we need \n /// to curry at least one argument:\n if constexpr (needs_unapply<decltype(f)>::value) {\n return [=](auto&& x) {\n return curry(\n [=](auto&&...xs) -> decltype(f(x,xs...)) {\n return f(x,xs...);\n }\n );\n }; \n }\n else { \n /// If 'f()' is a valid call, just call it, we are done.\n return f();\n }\n}\n\nint \nmain()\n{\n auto f = [](auto a, auto b, auto c, auto d) {\n return a * b * c * d;\n };\n \n return curry(f)(1)(2)(3)(4);\n}\n</code></pre>\n<p>See code in action on <a href=\"https://godbolt.org/g/wrli32\" rel=\"noreferrer\">here</a>. With a similar approach, <a href=\"https://godbolt.org/g/mp8OD1\" rel=\"noreferrer\">here</a> is how to curry functions with arbitrary number of arguments.</p>\n<p>The same idea seems to work out also in C++14, if we exchange the <code>constexpr if</code> with a template selection depending on the test <code>needs_unapply<decltype(f)>::value</code>:</p>\n<pre><code>template <typename F> auto\ncurry(F&& f);\n\ntemplate <bool> struct\ncurry_on;\n\ntemplate <> struct\ncurry_on<false> {\n template <typename F> static auto\n apply(F&& f) {\n return f();\n }\n};\n\ntemplate <> struct\ncurry_on<true> {\n template <typename F> static auto \n apply(F&& f) {\n return [=](auto&& x) {\n return curry(\n [=](auto&&...xs) -> decltype(f(x,xs...)) {\n return f(x,xs...);\n }\n );\n };\n }\n};\n\ntemplate <typename F> auto\ncurry(F&& f) {\n return curry_on<needs_unapply<decltype(f)>::value>::template apply(f);\n}\n</code></pre>\n"
},
{
"answer_id": 27736361,
"author": "Gabriel Garcia",
"author_id": 612169,
"author_profile": "https://Stackoverflow.com/users/612169",
"pm_score": 2,
"selected": false,
"text": "<p>I implemented currying with variadic templates as well (see Julian's answer). However, I did not make use of recursion or <code>std::function</code>. Note: It uses a number of <strong>C++14</strong> features.</p>\n\n<p>The provided example (<code>main</code> function) actually runs at compile time, proving that the currying method does not trump essential optimizations by the compiler.</p>\n\n<p>The code can be found here: <a href=\"https://gist.github.com/Garciat/c7e4bef299ee5c607948\" rel=\"nofollow\">https://gist.github.com/Garciat/c7e4bef299ee5c607948</a></p>\n\n<p>with this helper file: <a href=\"https://gist.github.com/Garciat/cafe27d04cfdff0e891e\" rel=\"nofollow\">https://gist.github.com/Garciat/cafe27d04cfdff0e891e</a></p>\n\n<p>The code still needs (a lot of) work, which I may or may not complete soon. Either way, I'm posting this here for future reference.</p>\n\n<p>Posting code in case links die (though they shouldn't):</p>\n\n<pre><code>#include <type_traits>\n#include <tuple>\n#include <functional>\n#include <iostream>\n\n// ---\n\ntemplate <typename FType>\nstruct function_traits;\n\ntemplate <typename RType, typename... ArgTypes>\nstruct function_traits<RType(ArgTypes...)> {\n using arity = std::integral_constant<size_t, sizeof...(ArgTypes)>;\n\n using result_type = RType;\n\n template <size_t Index>\n using arg_type = typename std::tuple_element<Index, std::tuple<ArgTypes...>>::type;\n};\n\n// ---\n\nnamespace details {\n template <typename T>\n struct function_type_impl\n : function_type_impl<decltype(&T::operator())>\n { };\n\n template <typename RType, typename... ArgTypes>\n struct function_type_impl<RType(ArgTypes...)> {\n using type = RType(ArgTypes...);\n };\n\n template <typename RType, typename... ArgTypes>\n struct function_type_impl<RType(*)(ArgTypes...)> {\n using type = RType(ArgTypes...);\n };\n\n template <typename RType, typename... ArgTypes>\n struct function_type_impl<std::function<RType(ArgTypes...)>> {\n using type = RType(ArgTypes...);\n };\n\n template <typename T, typename RType, typename... ArgTypes>\n struct function_type_impl<RType(T::*)(ArgTypes...)> {\n using type = RType(ArgTypes...);\n };\n\n template <typename T, typename RType, typename... ArgTypes>\n struct function_type_impl<RType(T::*)(ArgTypes...) const> {\n using type = RType(ArgTypes...);\n };\n}\n\ntemplate <typename T>\nstruct function_type\n : details::function_type_impl<typename std::remove_cv<typename std::remove_reference<T>::type>::type>\n{ };\n\n// ---\n\ntemplate <typename Args, typename Params>\nstruct apply_args;\n\ntemplate <typename HeadArgs, typename... Args, typename HeadParams, typename... Params>\nstruct apply_args<std::tuple<HeadArgs, Args...>, std::tuple<HeadParams, Params...>>\n : std::enable_if<\n std::is_constructible<HeadParams, HeadArgs>::value,\n apply_args<std::tuple<Args...>, std::tuple<Params...>>\n >::type\n{ };\n\ntemplate <typename... Params>\nstruct apply_args<std::tuple<>, std::tuple<Params...>> {\n using type = std::tuple<Params...>;\n};\n\n// ---\n\ntemplate <typename TupleType>\nstruct is_empty_tuple : std::false_type { };\n\ntemplate <>\nstruct is_empty_tuple<std::tuple<>> : std::true_type { };\n\n// ----\n\ntemplate <typename FType, typename GivenArgs, typename RestArgs>\nstruct currying;\n\ntemplate <typename FType, typename... GivenArgs, typename... RestArgs>\nstruct currying<FType, std::tuple<GivenArgs...>, std::tuple<RestArgs...>> {\n std::tuple<GivenArgs...> given_args;\n\n FType func;\n\n template <typename Func, typename... GivenArgsReal>\n constexpr\n currying(Func&& func, GivenArgsReal&&... args) :\n given_args(std::forward<GivenArgsReal>(args)...),\n func(std::move(func))\n { }\n\n template <typename... Args>\n constexpr\n auto operator() (Args&&... args) const& {\n using ParamsTuple = std::tuple<RestArgs...>;\n using ArgsTuple = std::tuple<Args...>;\n\n using RestArgsPrime = typename apply_args<ArgsTuple, ParamsTuple>::type;\n\n using CanExecute = is_empty_tuple<RestArgsPrime>;\n\n return apply(CanExecute{}, std::make_index_sequence<sizeof...(GivenArgs)>{}, std::forward<Args>(args)...);\n }\n\n template <typename... Args>\n constexpr\n auto operator() (Args&&... args) && {\n using ParamsTuple = std::tuple<RestArgs...>;\n using ArgsTuple = std::tuple<Args...>;\n\n using RestArgsPrime = typename apply_args<ArgsTuple, ParamsTuple>::type;\n\n using CanExecute = is_empty_tuple<RestArgsPrime>;\n\n return std::move(*this).apply(CanExecute{}, std::make_index_sequence<sizeof...(GivenArgs)>{}, std::forward<Args>(args)...);\n }\n\nprivate:\n template <typename... Args, size_t... Indices>\n constexpr\n auto apply(std::false_type, std::index_sequence<Indices...>, Args&&... args) const& {\n using ParamsTuple = std::tuple<RestArgs...>;\n using ArgsTuple = std::tuple<Args...>;\n\n using RestArgsPrime = typename apply_args<ArgsTuple, ParamsTuple>::type;\n\n using CurryType = currying<FType, std::tuple<GivenArgs..., Args...>, RestArgsPrime>;\n\n return CurryType{ func, std::get<Indices>(given_args)..., std::forward<Args>(args)... };\n }\n\n template <typename... Args, size_t... Indices>\n constexpr\n auto apply(std::false_type, std::index_sequence<Indices...>, Args&&... args) && {\n using ParamsTuple = std::tuple<RestArgs...>;\n using ArgsTuple = std::tuple<Args...>;\n\n using RestArgsPrime = typename apply_args<ArgsTuple, ParamsTuple>::type;\n\n using CurryType = currying<FType, std::tuple<GivenArgs..., Args...>, RestArgsPrime>;\n\n return CurryType{ std::move(func), std::get<Indices>(std::move(given_args))..., std::forward<Args>(args)... };\n }\n\n template <typename... Args, size_t... Indices>\n constexpr\n auto apply(std::true_type, std::index_sequence<Indices...>, Args&&... args) const& {\n return func(std::get<Indices>(given_args)..., std::forward<Args>(args)...);\n }\n\n template <typename... Args, size_t... Indices>\n constexpr\n auto apply(std::true_type, std::index_sequence<Indices...>, Args&&... args) && {\n return func(std::get<Indices>(std::move(given_args))..., std::forward<Args>(args)...);\n }\n};\n\n// ---\n\ntemplate <typename FType, size_t... Indices>\nconstexpr\nauto curry(FType&& func, std::index_sequence<Indices...>) {\n using RealFType = typename function_type<FType>::type;\n using FTypeTraits = function_traits<RealFType>;\n\n using CurryType = currying<FType, std::tuple<>, std::tuple<typename FTypeTraits::template arg_type<Indices>...>>;\n\n return CurryType{ std::move(func) };\n}\n\ntemplate <typename FType>\nconstexpr\nauto curry(FType&& func) {\n using RealFType = typename function_type<FType>::type;\n using FTypeArity = typename function_traits<RealFType>::arity;\n\n return curry(std::move(func), std::make_index_sequence<FTypeArity::value>{});\n}\n\n// ---\n\nint main() {\n auto add = curry([](int a, int b) { return a + b; });\n\n std::cout << add(5)(10) << std::endl;\n}\n</code></pre>\n"
},
{
"answer_id": 43131224,
"author": "AndyG",
"author_id": 27678,
"author_profile": "https://Stackoverflow.com/users/27678",
"pm_score": 3,
"selected": false,
"text": "<p>Some great answers here. I thought I would add my own because it was fun to play around with the concept.</p>\n\n<p><strong>Partial function application</strong>: The process of \"binding\" a function with only some of its parameters, deferring the rest to be filled in later. The result is another function with fewer parameters.</p>\n\n<p><strong>Currying</strong>: Is a special form of partial function application where you can only \"bind\" a single argument at a time. The result is another function with exactly 1 fewer parameter.</p>\n\n<p>The code I'm about to present is <strong>partial function application</strong> from which currying is possible, but not the only possibility. It offers a few benefits over the above currying implementations (mainly because it's partial function application and not currying, heh).</p>\n\n<ul>\n<li><p>Applying over an empty function:</p>\n\n<pre><code>auto sum0 = [](){return 0;};\nstd::cout << partial_apply(sum0)() << std::endl;\n</code></pre></li>\n<li><p>Applying multiple arguments at a time:</p>\n\n<pre><code>auto sum10 = [](int a, int b, int c, int d, int e, int f, int g, int h, int i, int j){return a+b+c+d+e+f+g+h+i+j;};\nstd::cout << partial_apply(sum10)(1)(1,1)(1,1,1)(1,1,1,1) << std::endl; // 10\n</code></pre></li>\n<li><p><code>constexpr</code> support that allows for compile-time <code>static_assert</code>:</p>\n\n<pre><code>static_assert(partial_apply(sum0)() == 0);\n</code></pre></li>\n<li><p>A useful error message if you accidentally go too far in providing arguments:</p>\n\n<pre><code>auto sum1 = [](int x){ return x;};\npartial_apply(sum1)(1)(1);\n</code></pre>\n\n<blockquote>\n <p>error: static_assert failed \"Attempting to apply too many arguments!\"</p>\n</blockquote></li>\n</ul>\n\n<p>Other answers above return lambdas that bind an argument and then return further lambdas. This approach wraps that essential functionality into a callable object. Definitions for <code>operator()</code> allow the internal lambda to be called. Variadic templates allow us to check for someone going too far, and an implicit conversion function to the result type of the function call allows us to print the result or compare the object to a primitive.</p>\n\n<p>Code:</p>\n\n<pre><code>namespace detail{\ntemplate<class F>\nusing is_zero_callable = decltype(std::declval<F>()());\n\ntemplate<class F>\nconstexpr bool is_zero_callable_v = std::experimental::is_detected_v<is_zero_callable, F>;\n}\n\ntemplate<class F>\nstruct partial_apply_t\n{\n template<class... Args>\n constexpr auto operator()(Args... args)\n {\n static_assert(sizeof...(args) == 0 || !is_zero_callable, \"Attempting to apply too many arguments!\");\n auto bind_some = [=](auto... rest) -> decltype(myFun(args..., rest...))\n {\n return myFun(args..., rest...);\n };\n using bind_t = decltype(bind_some);\n\n return partial_apply_t<bind_t>{bind_some};\n }\n explicit constexpr partial_apply_t(F fun) : myFun(fun){}\n\n constexpr operator auto()\n {\n if constexpr (is_zero_callable)\n return myFun();\n else\n return *this; // a callable\n }\n static constexpr bool is_zero_callable = detail::is_zero_callable_v<F>;\n F myFun;\n};\n</code></pre>\n\n<h2><a href=\"https://wandbox.org/permlink/74D7CxNUggiJjCjG\" rel=\"noreferrer\">Live Demo</a></h2>\n\n<p>A few more notes:</p>\n\n<ul>\n<li>I chose to use <a href=\"http://en.cppreference.com/w/cpp/experimental/is_detected\" rel=\"noreferrer\">is_detected</a> mainly for enjoyment and practice; it serves the same as a normal type trait would here.</li>\n<li>There could definitely be more work done to support perfect forwarding for performance reasons</li>\n<li>The code is C++17 because it requires for <code>constexpr</code> lambda support <a href=\"http://en.cppreference.com/w/cpp/language/lambda\" rel=\"noreferrer\">in C++17</a>\n\n<ul>\n<li>And it seems that GCC 7.0.1 is not quite there yet, either, so I used Clang 5.0.0</li>\n</ul></li>\n</ul>\n\n<p>Some tests:</p>\n\n<pre><code>auto sum0 = [](){return 0;};\nauto sum1 = [](int x){ return x;};\nauto sum2 = [](int x, int y){ return x + y;};\nauto sum3 = [](int x, int y, int z){ return x + y + z; };\nauto sum10 = [](int a, int b, int c, int d, int e, int f, int g, int h, int i, int j){return a+b+c+d+e+f+g+h+i+j;};\n\nstd::cout << partial_apply(sum0)() << std::endl; //0\nstatic_assert(partial_apply(sum0)() == 0, \"sum0 should return 0\");\nstd::cout << partial_apply(sum1)(1) << std::endl; // 1\nstd::cout << partial_apply(sum2)(1)(1) << std::endl; // 2\nstd::cout << partial_apply(sum3)(1)(1)(1) << std::endl; // 3\nstatic_assert(partial_apply(sum3)(1)(1)(1) == 3, \"sum3 should return 3\");\nstd::cout << partial_apply(sum10)(1)(1,1)(1,1,1)(1,1,1,1) << std::endl; // 10\n//partial_apply(sum1)(1)(1); // fails static assert\nauto partiallyApplied = partial_apply(sum3)(1)(1);\nstd::function<int(int)> finish_applying = partiallyApplied;\nstd::cout << std::boolalpha << (finish_applying(1) == 3) << std::endl; // true\n\nauto plus2 = partial_apply(sum3)(1)(1);\nstd::cout << std::boolalpha << (plus2(1) == 3) << std::endl; // true\nstd::cout << std::boolalpha << (plus2(3) == 5) << std::endl; // true\n</code></pre>\n"
},
{
"answer_id": 72160331,
"author": "anton_rh",
"author_id": 5447906,
"author_profile": "https://Stackoverflow.com/users/5447906",
"pm_score": 0,
"selected": false,
"text": "<p>C++20 provides <a href=\"https://en.cppreference.com/w/cpp/utility/functional/bind_front\" rel=\"nofollow noreferrer\">bind_front</a> for doing currying.</p>\n<p>For older C++ version it can be implemented (for single argument) as follows:</p>\n<pre><code>template <typename TFunc, typename TArg>\nclass CurryT\n{\nprivate:\n TFunc func;\n TArg arg ;\n\npublic:\n template <typename TFunc_, typename TArg_>\n CurryT(TFunc_ &&func, TArg_ &&arg)\n : func(std::forward<TFunc_>(func))\n , arg (std::forward<TArg_ >(arg ))\n {}\n\n template <typename... TArgs>\n auto operator()(TArgs &&...args) const\n -> decltype( func(arg, std::forward<TArgs>(args)...) )\n { return func(arg, std::forward<TArgs>(args)...); }\n};\n\ntemplate <typename TFunc, typename TArg>\nCurryT<std::decay_t<TFunc>, std::remove_cv_t<TArg>> Curry(TFunc &&func, TArg &&arg)\n { return {std::forward<TFunc>(func), std::forward<TArg>(arg)}; }\n</code></pre>\n<p><a href=\"https://coliru.stacked-crooked.com/a/82856e39da5fa50d\" rel=\"nofollow noreferrer\">https://coliru.stacked-crooked.com/a/82856e39da5fa50d</a></p>\n<pre><code>void Abc(std::string a, int b, int c)\n{\n std::cerr << a << b << c << std::endl;\n}\n\nint main()\n{\n std::string str = "Hey";\n auto c1 = Curry(Abc, str);\n std::cerr << "str: " << str << std::endl;\n c1(1, 2);\n auto c2 = Curry(std::move(c1), 3);\n c2(4);\n auto c3 = Curry(c2, 5);\n c3();\n}\n</code></pre>\n<p>Output:</p>\n<pre><code>str: \nHey12\nHey34\nHey35\n</code></pre>\n<p>If you use long chains of currying then <code>std::shared_ptr</code> optimization can be used to avoid copying all previous curried parameters to each new carried function.</p>\n<pre><code>template <typename TFunc>\nclass SharedFunc\n{\npublic:\n struct Tag{}; // For avoiding shadowing copy/move constructors with the\n // templated constructor below which accepts any parameters.\n\n template <typename... TArgs>\n SharedFunc(Tag, TArgs &&...args)\n : p_func( std::make_shared<TFunc>(std::forward<TArgs>(args)...) )\n {}\n\n template <typename... TArgs>\n auto operator()(TArgs &&...args) const\n -> decltype( (*p_func)(std::forward<TArgs>(args)...) )\n { return (*p_func)(std::forward<TArgs>(args)...); }\n\nprivate:\n std::shared_ptr<TFunc> p_func;\n};\n\ntemplate <typename TFunc, typename TArg>\nSharedFunc<\n CurryT<std::decay_t<TFunc>, std::remove_cv_t<TArg>>\n>\nCurryShared(TFunc &&func, TArg &&arg)\n{\n return { {}, std::forward<TFunc>(func), std::forward<TArg>(arg) };\n}\n</code></pre>\n<p><a href=\"https://coliru.stacked-crooked.com/a/6e71f41e1cc5fd5c\" rel=\"nofollow noreferrer\">https://coliru.stacked-crooked.com/a/6e71f41e1cc5fd5c</a></p>\n"
}
]
| 2008/09/30 | [
"https://Stackoverflow.com/questions/152005",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/22076/"
]
| What is currying?
How can currying be done in C++?
Please Explain binders in STL container? | In short, currying takes a function `f(x, y)` and given a fixed `Y`, gives a new function `g(x)` where
```
g(x) == f(x, Y)
```
This new function may be called in situations where only one argument is supplied, and passes the call on to the original `f` function with the fixed `Y` argument.
The binders in the STL allow you to do this for C++ functions. For example:
```
#include <functional>
#include <iostream>
#include <vector>
using namespace std;
// declare a binary function object
class adder: public binary_function<int, int, int> {
public:
int operator()(int x, int y) const
{
return x + y;
}
};
int main()
{
// initialise some sample data
vector<int> a, b;
a.push_back(1);
a.push_back(2);
a.push_back(3);
// here we declare a function object f and try it out
adder f;
cout << "f(2, 3) = " << f(2, 3) << endl;
// transform() expects a function with one argument, so we use
// bind2nd to make a new function based on f, that takes one
// argument and adds 5 to it
transform(a.begin(), a.end(), back_inserter(b), bind2nd(f, 5));
// output b to see what we got
cout << "b = [" << endl;
for (vector<int>::iterator i = b.begin(); i != b.end(); ++i) {
cout << " " << *i << endl;
}
cout << "]" << endl;
return 0;
}
``` |
152,006 | <p>I've got a php script. Most of the time the script returns html, which is working fine, but on one occasion (parameter ?Format=XML) the script returns XML instead of HTML.</p>
<p>Is there any way to change the returned mime type of the php output on the fly from text/html to text/xml or application/xml?</p>
| [
{
"answer_id": 152009,
"author": "nickf",
"author_id": 9021,
"author_profile": "https://Stackoverflow.com/users/9021",
"pm_score": 8,
"selected": true,
"text": "<pre><code>header('Content-type: application/xml');\n</code></pre>\n\n<p>More information available at the PHP documentation for <a href=\"http://php.net/manual/en/function.header.php\" rel=\"noreferrer\"><code>header()</code></a></p>\n"
},
{
"answer_id": 152010,
"author": "John Millikin",
"author_id": 3560,
"author_profile": "https://Stackoverflow.com/users/3560",
"pm_score": 4,
"selected": false,
"text": "<p>Set the <code>Content-Type</code> header:</p>\n\n<pre><code>header('Content-Type: text/xml');\n</code></pre>\n\n<p>Though you should probably use \"application/xml\" instead.</p>\n"
},
{
"answer_id": 152011,
"author": "andy.gurin",
"author_id": 22388,
"author_profile": "https://Stackoverflow.com/users/22388",
"pm_score": 2,
"selected": false,
"text": "<p>You should send a <code>Content-Type</code> header <strong>before</strong> you send any output.</p>\n\n<pre><code>header('Content-Type: text/xml');\n</code></pre>\n"
},
{
"answer_id": 152304,
"author": "PhiLho",
"author_id": 15459,
"author_profile": "https://Stackoverflow.com/users/15459",
"pm_score": 2,
"selected": false,
"text": "<p>I will answer to the update, since the previous answers are good.<br>\nI have read that Internet Explorer is well known for ignoring Mime type headers (most of the time?) to rely on content of the file (which can cause problems in some cases).</p>\n\n<p>Mmm, I did a simple test:</p>\n\n<pre><code><?php\nheader('Content-Type: text/xml');\necho '<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"yes\"?>\n<root><foo a=\"b\">Tada</foo></root>';\n?>\n</code></pre>\n\n<p>Internet Explorer 6 displays it correctly as XML. Even if I remove the xml declaration.<br>\nYou should indicate which version is problematic.</p>\n\n<p>Actually, as I wrote above, with IE (6 at least), you don't even need a content-type, it recognize XML data and display it as a tree. Is your XML correct?</p>\n\n<p>[Update] Tried with IE7 as well, adding ?format=xml too, still displaying XML correctly. If I send malformed XML, IE displays an error. Tested on WinXP Pro SP2+</p>\n"
},
{
"answer_id": 45046861,
"author": "Thomas",
"author_id": 8212246,
"author_profile": "https://Stackoverflow.com/users/8212246",
"pm_score": 1,
"selected": false,
"text": "<p>I just used the following:<br>\nNOTE: I am using \"i\" for sql improved extension. </p>\n\n<pre><code>Start XML file, echo parent node\nheader(\"Content-type: text/xml\");\necho \"<?xml version='1.0' encoding='UTF-8'?>\";\necho \"<marker>\";\n</code></pre>\n\n<p>Iterate through the rows, printing XML nodes for each</p>\n\n<pre><code>while ($row = @mysqli_fetch_assoc($results)){\n // Add to XML document node\n echo '<marker ';\n echo 'id=\"' . $ind . '\" ';\n echo 'name=\"' . parseToXML($row['name']) . '\" ';\n echo 'address=\"' . parseToXML($row['address']) . '\" ';\n echo 'lat=\"' . $row['lat'] . '\" ';\n echo 'lng=\"' . $row['lng'] . '\" ';\n echo 'type=\"' . $row['type'] . '\" ';\n echo '/>';\n}\n\n// End XML file\necho \"</marker>\";\n</code></pre>\n"
},
{
"answer_id": 48734864,
"author": "Usman Ahmed",
"author_id": 2243776,
"author_profile": "https://Stackoverflow.com/users/2243776",
"pm_score": 2,
"selected": false,
"text": "<pre><code>header('Content-Type: application/xml; charset=utf-8');\n</code></pre>\n\n<p>You can add encoding as well in the same line. I added utf-8, which is most common.</p>\n"
}
]
| 2008/09/30 | [
"https://Stackoverflow.com/questions/152006",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7021/"
]
| I've got a php script. Most of the time the script returns html, which is working fine, but on one occasion (parameter ?Format=XML) the script returns XML instead of HTML.
Is there any way to change the returned mime type of the php output on the fly from text/html to text/xml or application/xml? | ```
header('Content-type: application/xml');
```
More information available at the PHP documentation for [`header()`](http://php.net/manual/en/function.header.php) |
152,016 | <p>What is the most reliable way to find out CPU architecture when compiling C or C++ code? As far as I can tell, different compilers have their own set of non-standard preprocessor definitions (<code>_M_X86</code> in MSVS, <code>__i386__</code>, <code>__arm__</code> in GCC, etc).</p>
<p>Is there a <em>standard</em> way to detect the architecture I'm building for? If not, is there a source for a comprehensive list of such definitions for various compilers, such as a header with all the boilerplate <code>#ifdef</code>s?</p>
| [
{
"answer_id": 152032,
"author": "Michael Burr",
"author_id": 12711,
"author_profile": "https://Stackoverflow.com/users/12711",
"pm_score": 2,
"selected": false,
"text": "<p>There's nothing standard. Brian Hook documented a bunch of these in his \"Portable Open Source Harness\", and even tries to make them into something coherent and usable (ymmv regarding that). See the posh.h header on this site:</p>\n\n<ul>\n<li><a href=\"http://hookatooka.com/poshlib/\" rel=\"noreferrer\">http://hookatooka.com/poshlib/</a></li>\n</ul>\n\n<p>Note, the link above may require you to enter some bogus userid/password due to a DOS attack some time ago.</p>\n"
},
{
"answer_id": 152034,
"author": "John Millikin",
"author_id": 3560,
"author_profile": "https://Stackoverflow.com/users/3560",
"pm_score": 4,
"selected": false,
"text": "<p>There's no inter-compiler standard, but each compiler tends to be quite consistent. You can build a header for yourself that's something like this:</p>\n\n<pre><code>#if MSVC\n#ifdef _M_X86\n#define ARCH_X86\n#endif\n#endif\n\n#if GCC\n#ifdef __i386__\n#define ARCH_X86\n#endif\n#endif\n</code></pre>\n\n<p>There's not much point to a comprehensive list, because there are thousands of compilers but only 3-4 in widespread use (Microsoft C++, GCC, Intel CC, maybe TenDRA?). Just decide which compilers your application will support, list their #defines, and update your header as needed.</p>\n"
},
{
"answer_id": 153360,
"author": "zvrba",
"author_id": 2583,
"author_profile": "https://Stackoverflow.com/users/2583",
"pm_score": -1,
"selected": false,
"text": "<p>If you need a fine-grained detection of CPU features, the best approach is to ship also a CPUID program which outputs to stdout or some \"cpu_config.h\" file the set of features supported by the CPU. Then you integrate that program with your build process.</p>\n"
},
{
"answer_id": 37018251,
"author": "Wei Shen",
"author_id": 1657877,
"author_profile": "https://Stackoverflow.com/users/1657877",
"pm_score": 4,
"selected": false,
"text": "<p>If you would like to dump all available features on a particular platform, you could run GCC like:</p>\n\n<pre><code>gcc -march=native -dM -E - </dev/null\n</code></pre>\n\n<p>It would dump macros like <code>#define __SSE3__ 1</code>, <code>#define __AES__ 1</code>, etc.</p>\n"
},
{
"answer_id": 52867605,
"author": "phuclv",
"author_id": 995714,
"author_profile": "https://Stackoverflow.com/users/995714",
"pm_score": 3,
"selected": false,
"text": "<p>If you want a cross-compiler solution then just use <a href=\"https://www.boost.org/doc/libs/1_79_0/libs/predef/doc/index.html\" rel=\"nofollow noreferrer\"><code>Boost.Predef</code></a> which contains</p>\n<ul>\n<li><code>BOOST_ARCH_</code> for system/CPU architecture one is compiling for.</li>\n<li><code>BOOST_COMP_</code> for the compiler one is using.</li>\n<li><code>BOOST_LANG_</code> for language standards one is compiling against.</li>\n<li><code>BOOST_LIB_C_</code> and <code>BOOST_LIB_STD_</code> for the C and C++ standard library in use.</li>\n<li><code>BOOST_OS_</code> for the operating system we are compiling to.</li>\n<li><code>BOOST_PLAT_</code> for platforms on top of operating system or compilers.</li>\n<li><code>BOOST_ENDIAN_</code> for endianness of the os and architecture combination.</li>\n<li><code>BOOST_HW_</code> for hardware specific features.</li>\n<li><code>BOOST_HW_SIMD</code> for SIMD (Single Instruction Multiple Data) detection.</li>\n</ul>\n<p>Note that although Boost is usually thought of as a C++ library, <strong><code>Boost.Predef</code> is pure header-only</strong> and works for C</p>\n<p>For example</p>\n<pre><code>#include <boost/predef.h>\n// or just include the necessary headers\n// #include <boost/predef/architecture.h>\n// #include <boost/predef/other.h>\n\n#if BOOST_ARCH_X86\n #if BOOST_ARCH_X86_64\n std::cout << "x86-64\\n";\n #elif BOOST_ARCH_X86_32\n std::cout << "x86-32\\n";\n #else\n std::cout << "x86-" << BOOST_ARCH_WORD_BITS << '\\n'; // Probably x86-16\n #endif\n#elif BOOST_ARCH_ARM\n #if BOOST_ARCH_ARM >= BOOST_VERSION_NUMBER(8, 0, 0)\n #if BOOST_ARCH_WORD_BITS == 64\n std::cout << "ARMv8+ Aarch64\\n";\n #elif BOOST_ARCH_WORD_BITS == 32\n std::cout << "ARMv8+ Aarch32\\n";\n #else\n std::cout << "Unexpected ARMv8+ " << BOOST_ARCH_WORD_BITS << "bit\\n";\n #endif\n #elif BOOST_ARCH_ARM >= BOOST_VERSION_NUMBER(7, 0, 0)\n std::cout << "ARMv7 (ARM32)\\n";\n #elif BOOST_ARCH_ARM >= BOOST_VERSION_NUMBER(6, 0, 0)\n std::cout << "ARMv6 (ARM32)\\n";\n #else\n std::cout << "ARMv5 or older\\n";\n #endif\n#elif BOOST_ARCH_MIPS\n #if BOOST_ARCH_WORD_BITS == 64\n std::cout << "MIPS64\\n";\n #else\n std::cout << "MIPS32\\n";\n #endif\n#elif BOOST_ARCH_PPC_64\n std::cout << "PPC64\\n";\n#elif BOOST_ARCH_PPC\n std::cout << "PPC32\\n";\n#else\n std::cout << "Unknown " << BOOST_ARCH_WORD_BITS << "-bit arch\\n";\n#endif\n</code></pre>\n<p>You can find out more on how to use it <a href=\"https://www.boost.org/doc/libs/1_79_0/libs/predef/doc/index.html#_using_the_predefs\" rel=\"nofollow noreferrer\">here</a></p>\n<p><a href=\"https://godbolt.org/#z:OYLghAFBqd5QCxAYwPYBMCmBRdBLAF1QCcAaPECAMzwBtMA7AQwFtMQByARg9KtQYEAysib0QXACx8BBAKoBnTAAUAHpwAMvAFYTStJg1DIApACYAQuYukl9ZATwDKjdAGFUtAK4sGIM6SuADJ4DJgAcj4ARpjEIADspAAOqAqETgwe3r7%2ByanpAiFhkSwxcYl2mA4ZQgRMxARZPn4BldUCtfUERRHRsQm2dQ1NOa1D3aG9pf3xAJS2qF7EyOwc5gDMocjeWADUJutuUaipBAD0ScSYWFQAdAgH2CYaAIJnZ7sku9peCgS7Wx2mF2BAQwLCKwUCnqAE9dmCmFhiApnm8PhtAV49gcjic/hcrjczvVkAhCFUCEtMPdHqj3vszJsGNsscCccdTgTrpgqGdUKDYjT1k9XqjQv9gJgCC9lggILNUSZ4lZRYy8FRdhYAPJaoQAFQA%2Bi8AEpuAASBoAGgAOABsqN2joZmw12t1hpN5qtdoNtskDqdgcDV0pxAYuy4XAOKpegY2mFo6s1Ov1RtNFpttoN6zMAaDQZDS3DXFz6xjccZCaUefzTsLYYj612ACpk%2B6016AOpa40AEQNFgAknqhNHdvTlMRUFEmFFaHDVHaALRce2vCvrVzqxWVxOulMe9NpgCyNYx%2B/bnotJuP%2B2FB17bdTADVsMahIOteEDeE5MeLG%2BEDWqQuwaCBGgKuutbnk%2Bh5dj2/ZDiOd69g%2Bux%2BjWta7PW4ZmFGZbjh8N4AG7WtYuwvCSCAYVB%2BbxnusEdha3Z9gOw5CChaE5phtY4bsZilhYhEUcax6keRlGytxtFBvR1YyVhfGMi2jFXgaLGIexY70nIYSqEkFLXDxjrxgw%2BBUGeu5Jm6qZqTed5POsj42Yar7vp%2B36/v%2BgGJKB4GQbGWF1lKRb8f6BH0iR8S7BAN45gFG4JtZB5MSeDloS5BpuR%2BX4/n%2BAHGhAtrgf5xkFiFDZmAArNpRGicRtoxXFZgJU6cmYGVwYVbh9oRXVYlVZ8xCfLQSKWZuZnbqqm4MZlanHoOyijjJMFzUeGlschD5oTRgVBdh3W7Os%2BFCfSC1LbtiW0PJe1BXx3F9bs51CNJt2meZO4zcll5HsoyhuL6/oKbxh2SCdn1JRetm/f9nXBaG4aSIJEPXR1wP5nxS5rfBrFIaOj26QA1gwqAAO7hgwS5RIQuxURDk0WaK8Soa8HDzLQnBVbwfgcFopCoJwbjWORCiLMsbKMjwpAEJobPzIT/jxLc6waGYYO2vEeEaAAnPEObrPonCSNzsv85wvAKCAYEy7zbOkHAsAwIgKCoCwSR0LE5CUGgbse3EwAllwfB0AQsSWxAUSm9TzDEDCnBSz7bCCFqDDzqbWAsIYwDiLbpD4Fc1TEZglu55gqhVF4ofx7w4oJqbiZRMQsIeFgpsEMQeAsNX8xUAYwAKM%2BeCYKTWoGTzUv8IIIhiOwUgyIIigqOoue6AEBhGCgwuWPoeBRJbsDMGwIAcn8pBF3E3DxNrcv80kjgCCXS5alwuxLp2Yi0K/nZl%2B3TC8EkhgIisHYIuW0S4/S2ATBSDILgzIjD8CWQIZkeglDKCAA2KQ0j30yJ4ZoEgAiYIKAwFBfQ4gGzaNgzowxcE5EQRQmo4wSHTDIYMLo8D8GsIaEwtB6x5iiyWCsPQ7dMCrB4OzTmJtc4C1AeA6QNstDzAgEgH27t6BkAoBAFRfsUDr2AAaduXgGCE2DrQUOyJKCR1ztHWE1dSCJ0YAQFOadc4ZyzjnPm%2BdoFFxLnzMuFcq7cBroIOuucG5N1ji3VYfN26d27nwPuA8h4jzHrYyewhRDiDnmkxeahTa6ANrozelhrA7z3vACAh92AnwIGffol9r6zHmKgO%2BGRH5ajMK/FgOYv4fy/j/Ju/9AHhGASAGROZIH2GwbA9wNCEEBGCJMVB/QMH5GwewxBhDsHcOWRM6BHRxjrNaFA9oDAqETGKKQ9BnDGizI4X8Lo2yyF8LFoIoOwjRF2w5hwLmpAeZ82kcucZ8i7ZKJdr7NRXtNGu1Uf0eoLBSJLm2FnSMGgg40FMWHCxUdQg2MCXY12SdHGpzji4zAmcjDuN4J4wuxdTZ%2BOQJXD55BglfL5mE5uGAom8BiV3QJPcEmD2HqPRgqTZDT0ydIbJShckrxANIQpphinbwbvvKAlTj54hqefeOV8b7NOwW0jpb9elv36X/ZIQyRlwoRRA%2BhzgICuEOUg9AjyrmbIyE691hRFmXPIccyhBzbl0P9Qwh5PrmFXPudQ7Iczrmut4QsARs9pZXA%2BeI75kj/kgGtdaWR0tZaKOUdCv2kKtFqOzcQFggcwLorMeHSxfNrGx1sfY5OxL05krcVyvOeAC6OG8XS8uDKAlS1rqy3g7KImcrbh3XlYj4lMH7oK5JIq8VpPFbPSVsgcnLz5robW%2Bgs5FKsMq3eqqKkjOqbUi%2BXBdWNNvgazgT8jXv1oJ/U1qhf6DOKFaytxEKghvtY6oNzrXVBy9TgmNegINgd2Scs56y4MBrDRciNQco03Kg%2Bhxh4a0FcGeUmoRqa4lfJ%2BX83gAtrWJGBYWsFML1He2LeWuFCAqDACqpKkOmKI7YpjiShOBKHFOJJR4ztFLu3Uv7bS0uQ7GW2LHfXXe4SYSRJnbEvlC6l1JOFePXg66MmbvnvIaVu6dASCDgqreNgVXlPVVe7V9S9UtIfk%2B9pPS319M/U3TpdMnLWttN%2BoBR9/NIZgQ6uBQaD0LNQzwvIWCPWRbi0Q%2BNoX9lsMS3a05OGYs7Iw%2Bsg9GH40EfFkRkRJGJG/NNpRv9xUaP2yLeCz2Giy2wsrcASQHGTF1qxVYnFza8WtqJc40T5Ls4Sd7V46TvjZMjqCaHcdpTlOqdzjyuJvdF2JKFSktdYqDMSC3QvEzeSJBgUs0q6zZ7bOXs1denVDSmnOYYIa9z77v5eaYD52UD5rU/IAT%2B4Lf6qqpb8OFmZWGovINwzsiD%2BWktbKhywzLCGMuAayyhqYsW8sZeyxj5ZxXXkprKxp0jmaKMVvhUDmj8wERIkoPLOVXBbjqzMNaKqtoqpmA0FfaqhsODG1IF3KqYFyNmw4BbXIdWHbOxawxqFjW4hJCSMgP09BgAHtrdxhtvAm38d4IN4THbRuUp7X2vAA6ZP%2BKZQp0JSmOWtxW7OtbArtPbYnrtme%2B2jM7uO4kM7J6LtlIPtd04t3HP3v1a01zL9jUeY/V%2Bi1/32B/TcLa1H0zEPRdx3EcDqyEtYbhxkWDSPA35%2BL%2BjpZ2frmIcKwjiQ%2BPk3vPKxmyrUiQDJ4gZLhr9HS1Mf6Ir5AAcSw1q4%2BYnjvW%2BMtsE224bVKxNjfThNmlPjeD0rk3i63bLbdTvt9Ex3Gn1taa26ut3U89tZO3Ud2VwE/clJs0Ho%2B9m6m3vuw%2ByPHAn7R9fa9s1gXhlH2T%2BMpluniBpnhXtBrngIIhjBrXuhqjsjqXnATjmAdhulqXkgZcvhomiVm8sRsThViLgLAAQEJ3nRiWs1r3nECwHgEkAoGzpIAmF1prrxrigJiwISgbqSkbuNqbubtNpbqbBvhOlviptOg7upvOgfptiurpkZhup7lKkvMdsVDfqeoHmqsHqfA5s/k5o%2Bu/s/C9p5vHn9kFuwM9KnpMmFsBvnqARgQXpASBtATlpXmXtGngrARYWllwjAVXiBjXk4XXlgQTo3ngc3gQSAGYXIgWvVqQRCuQfLiAFQTQZGJzowaPlrqQDrpPmwUJu2pwV2gvjwVNivjNt2oIYtnbt2qtvvs7kfjIfph7ufodoobKkDioQHuenZjdloXeg9roR/gYXHgMgniYeEYtC9Ech4SDlYXgh1qBrXisvFvYVBrMY4VnpGogagTMUDi4ecmseQiXlsXGvMfXqVmmrzmRlVqMUtEClEaCjLj3vEcRMgIrgaMRFwNrNmGYAaKoBAhrmkcwf1qwewbkSNvkS4ovlJsvoECUfJiyopo3BUWpnOnbJIcujpqKqfg0QdsZs0XunoG0aUqqr0ZHmcM/MMX/iAuYXslMRFtYZDv4TnosZBm4XYcQt4TsdXhsV4QyT4WgeXhgScTgUTvOiTi3lmj8ZEbbLRvcXEfRiAMQA1JIEuMAMgMgNrJIMPhiv8ePiwXrlPkNiJrPlwQUZNlCavrNsyvNvCUtqIbvuISiTUdIRiekliV7pfniYggSXfuoQ/l0U/j0a/i5noZ/iam9kYZakfMaIOEIG4EuM%2BMDsAVhvMvSXsayZ6hAWyf4X6pMfAW4RMdSWcilljkmUcVmYKYTmcaKWEVGTGXGfmlKdTpgIiP0PKLzvzoLsLpcWLrYFbPWQovTprLcLaLrFVNaDmPENaNrKrLaNfpwOsKTqLtygWummYAuQLN2VTtemkM4JIEAA%3D%3D\" rel=\"nofollow noreferrer\">Demo on Godbolt</a></p>\n"
},
{
"answer_id": 66249936,
"author": "FreakAnon",
"author_id": 14804593,
"author_profile": "https://Stackoverflow.com/users/14804593",
"pm_score": 4,
"selected": false,
"text": "<p>Enjoy, I was the original author of this.</p>\n<pre><code>extern "C" {\n const char *getBuild() { //Get current architecture, detectx nearly every architecture. Coded by Freak\n #if defined(__x86_64__) || defined(_M_X64)\n return "x86_64";\n #elif defined(i386) || defined(__i386__) || defined(__i386) || defined(_M_IX86)\n return "x86_32";\n #elif defined(__ARM_ARCH_2__)\n return "ARM2";\n #elif defined(__ARM_ARCH_3__) || defined(__ARM_ARCH_3M__)\n return "ARM3";\n #elif defined(__ARM_ARCH_4T__) || defined(__TARGET_ARM_4T)\n return "ARM4T";\n #elif defined(__ARM_ARCH_5_) || defined(__ARM_ARCH_5E_)\n return "ARM5"\n #elif defined(__ARM_ARCH_6T2_) || defined(__ARM_ARCH_6T2_)\n return "ARM6T2";\n #elif defined(__ARM_ARCH_6__) || defined(__ARM_ARCH_6J__) || defined(__ARM_ARCH_6K__) || defined(__ARM_ARCH_6Z__) || defined(__ARM_ARCH_6ZK__)\n return "ARM6";\n #elif defined(__ARM_ARCH_7__) || defined(__ARM_ARCH_7A__) || defined(__ARM_ARCH_7R__) || defined(__ARM_ARCH_7M__) || defined(__ARM_ARCH_7S__)\n return "ARM7";\n #elif defined(__ARM_ARCH_7A__) || defined(__ARM_ARCH_7R__) || defined(__ARM_ARCH_7M__) || defined(__ARM_ARCH_7S__)\n return "ARM7A";\n #elif defined(__ARM_ARCH_7R__) || defined(__ARM_ARCH_7M__) || defined(__ARM_ARCH_7S__)\n return "ARM7R";\n #elif defined(__ARM_ARCH_7M__)\n return "ARM7M";\n #elif defined(__ARM_ARCH_7S__)\n return "ARM7S";\n #elif defined(__aarch64__) || defined(_M_ARM64)\n return "ARM64";\n #elif defined(mips) || defined(__mips__) || defined(__mips)\n return "MIPS";\n #elif defined(__sh__)\n return "SUPERH";\n #elif defined(__powerpc) || defined(__powerpc__) || defined(__powerpc64__) || defined(__POWERPC__) || defined(__ppc__) || defined(__PPC__) || defined(_ARCH_PPC)\n return "POWERPC";\n #elif defined(__PPC64__) || defined(__ppc64__) || defined(_ARCH_PPC64)\n return "POWERPC64";\n #elif defined(__sparc__) || defined(__sparc)\n return "SPARC";\n #elif defined(__m68k__)\n return "M68K";\n #else\n return "UNKNOWN";\n #endif\n }\n}\n</code></pre>\n"
},
{
"answer_id": 69856463,
"author": "Timmmm",
"author_id": 265521,
"author_profile": "https://Stackoverflow.com/users/265521",
"pm_score": 2,
"selected": false,
"text": "<p>There's a list of the <code>#define</code>s <a href=\"https://sourceforge.net/p/predef/wiki/Architectures/\" rel=\"nofollow noreferrer\">here</a>. There was a previous highly voted answer that included this link but it was deleted by a mod presumably due to SO's "answers must have code" rule. So here's a random sample. Follow the link for the full list.</p>\n<h1>AMD64</h1>\n<div class=\"s-table-container\">\n<table class=\"s-table\">\n<thead>\n<tr>\n<th>Type</th>\n<th>Macro</th>\n<th>Description</th>\n</tr>\n</thead>\n<tbody>\n<tr>\n<td>Identification</td>\n<td><code>__amd64__</code> <code>__amd64</code> <code>__x86_64__</code> <code>__x86_64</code></td>\n<td>Defined by GNU C and Sun Studio</td>\n</tr>\n<tr>\n<td>Identification</td>\n<td><code>_M_X64</code> <code>_M_AMD64</code></td>\n<td>Defined by Visual Studio</td>\n</tr>\n</tbody>\n</table>\n</div>"
}
]
| 2008/09/30 | [
"https://Stackoverflow.com/questions/152016",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/23643/"
]
| What is the most reliable way to find out CPU architecture when compiling C or C++ code? As far as I can tell, different compilers have their own set of non-standard preprocessor definitions (`_M_X86` in MSVS, `__i386__`, `__arm__` in GCC, etc).
Is there a *standard* way to detect the architecture I'm building for? If not, is there a source for a comprehensive list of such definitions for various compilers, such as a header with all the boilerplate `#ifdef`s? | There's no inter-compiler standard, but each compiler tends to be quite consistent. You can build a header for yourself that's something like this:
```
#if MSVC
#ifdef _M_X86
#define ARCH_X86
#endif
#endif
#if GCC
#ifdef __i386__
#define ARCH_X86
#endif
#endif
```
There's not much point to a comprehensive list, because there are thousands of compilers but only 3-4 in widespread use (Microsoft C++, GCC, Intel CC, maybe TenDRA?). Just decide which compilers your application will support, list their #defines, and update your header as needed. |
152,019 | <p>.Net 3.5 doesn't support tuples. Too bad, But not sure whether the future version of .net will support tuples or not? </p>
| [
{
"answer_id": 152026,
"author": "dimarzionist",
"author_id": 10778,
"author_profile": "https://Stackoverflow.com/users/10778",
"pm_score": 6,
"selected": false,
"text": "<pre><code>#region tuples\n\n public class Tuple<T>\n {\n public Tuple(T first)\n {\n First = first;\n }\n\n public T First { get; set; }\n }\n\n public class Tuple<T, T2> : Tuple<T>\n {\n public Tuple(T first, T2 second)\n : base(first)\n {\n Second = second;\n }\n\n public T2 Second { get; set; }\n }\n\n public class Tuple<T, T2, T3> : Tuple<T, T2>\n {\n public Tuple(T first, T2 second, T3 third)\n : base(first, second)\n {\n Third = third;\n }\n\n public T3 Third { get; set; }\n }\n\n public class Tuple<T, T2, T3, T4> : Tuple<T, T2, T3>\n {\n public Tuple(T first, T2 second, T3 third, T4 fourth)\n : base(first, second, third)\n {\n Fourth = fourth;\n }\n\n public T4 Fourth { get; set; }\n }\n\n #endregion\n</code></pre>\n\n<p>And to make declarations prettier:</p>\n\n<pre><code>public static class Tuple\n{\n //Allows Tuple.New(1, \"2\") instead of new Tuple<int, string>(1, \"2\")\n public static Tuple<T1, T2> New<T1, T2>(T1 t1, T2 t2)\n {\n return new Tuple<T1, T2>(t1, t2);\n }\n //etc...\n}\n</code></pre>\n"
},
{
"answer_id": 152029,
"author": "Tigraine",
"author_id": 21699,
"author_profile": "https://Stackoverflow.com/users/21699",
"pm_score": 1,
"selected": false,
"text": "<p>If I remember my Computer Science classes correctly tuples are just data.</p>\n\n<p>If you want grouped data - create classes that contain properties. \nIf you need something like the <a href=\"http://msdn.microsoft.com/en-us/library/5tbh8a42.aspx\" rel=\"nofollow noreferrer\">KeyValuePair</a> then there it is.</p>\n"
},
{
"answer_id": 152041,
"author": "Merus",
"author_id": 5133,
"author_profile": "https://Stackoverflow.com/users/5133",
"pm_score": 0,
"selected": false,
"text": "<p>I'd be surprised - C# is a strongly-typed language, whereas tuples are suited for more dynamically typed languages. C# has been drifting more dynamic as time goes on, but that's syntactic sugar, not a real shift in the underlying data types.</p>\n\n<p>If you want two values in one instance, a KeyValuePair<> is a decent substitute, albeit clumsy. You can also make a struct or a class that'll do the same thing, and is expandable.</p>\n"
},
{
"answer_id": 152054,
"author": "ChaosSpeeder",
"author_id": 205962,
"author_profile": "https://Stackoverflow.com/users/205962",
"pm_score": 4,
"selected": false,
"text": "<p>In my opinion, the anonymous types feature is not a tuple, but a very similar construct. The output of some LINQ Queries are collections of anonymous types, which behave like tuples.</p>\n\n<p>Here is a statement, which creates a typed tuple :-) on the fly:</p>\n\n<pre><code>var p1 = new {a = \"A\", b = 3};\n</code></pre>\n\n<p>see: <a href=\"http://www.developer.com/net/csharp/article.php/3589916\" rel=\"noreferrer\">http://www.developer.com/net/csharp/article.php/3589916</a></p>\n"
},
{
"answer_id": 152078,
"author": "Marc Gravell",
"author_id": 23354,
"author_profile": "https://Stackoverflow.com/users/23354",
"pm_score": 2,
"selected": false,
"text": "<p>C# supports simple tuples via generics quite easily (as per an earlier answer), and with \"mumble typing\" (one of many possible C# language enhancements) to improve type inference they could be very, very powerful.</p>\n\n<p>For what it is worth, F# supports tuples natively, and having played with it, I'm not sure that (anonymous) tuples add much... what you gain in brevity you lose <em>very</em> quickly in code clarity.</p>\n\n<p>For code within a single method, there are anonymous types; for code going outside of a method, I think I'll stick to simple named types. Of course, if a future C# makes it easier to make these immutable (while still easy to work with) I'll be happy.</p>\n"
},
{
"answer_id": 152785,
"author": "Chris Ballard",
"author_id": 18782,
"author_profile": "https://Stackoverflow.com/users/18782",
"pm_score": 4,
"selected": false,
"text": "<p>Implementing Tuple classes or reusing F# classes within C# is only half the story - these give you the ability to create tuples with relative ease, but not really the syntactic sugar which makes them so nice to use in languages like F#.</p>\n\n<p>For example in F# you can use pattern matching to extract both parts of a tuple within a let statment, eg</p>\n\n<pre><code>let (a, b) = someTupleFunc\n</code></pre>\n\n<p>Unfortunately to do the same using the F# classes from C# would be much less elegant:</p>\n\n<pre><code>Tuple<int,int> x = someTupleFunc();\nint a = x.get_Item1();\nint b = x.get_Item2();\n</code></pre>\n\n<p>Tuples represent a powerful method for returning multiple values from a function call without the need to litter your code with throwaway classes, or resorting to ugly ref or out parameters. However, in my opinion, without some syntactic sugar to make their creation and access more elegant, they are of limited use.</p>\n"
},
{
"answer_id": 417418,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 0,
"selected": false,
"text": "<p>To make these useful in a hashtable or dictionary, you will likely want to provide overloads for GetHashCode and Equals.</p>\n"
},
{
"answer_id": 417454,
"author": "Lasse V. Karlsen",
"author_id": 267,
"author_profile": "https://Stackoverflow.com/users/267",
"pm_score": 2,
"selected": false,
"text": "<p>Here's my set of tuples, they're autogenerated by a Python script, so I've perhaps gone a bit overboard:</p>\n\n<p><a href=\"http://code.google.com/p/lvknet/source/browse/#svn/trunk/LVK/GenericTypes\" rel=\"nofollow noreferrer\">Link to Subversion repository</a></p>\n\n<p>You'll need a username/password, they're both <strong>guest</strong></p>\n\n<p>They are based on inheritance, but <code>Tuple<Int32,String></code> will not compare equal to <code>Tuple<Int32,String,Boolean></code> even if they happen to have the same values for the two first members.</p>\n\n<p>They also implement GetHashCode and ToString and so forth, and lots of smallish helper methods.</p>\n\n<p>Example of usage:</p>\n\n<pre><code>Tuple<Int32, String> t1 = new Tuple<Int32, String>(10, \"a\");\nTuple<Int32, String, Boolean> t2 = new Tuple<Int32, String, Boolean>(10, \"a\", true);\nif (t1.Equals(t2))\n Console.Out.WriteLine(t1 + \" == \" + t2);\nelse\n Console.Out.WriteLine(t1 + \" != \" + t2);\n</code></pre>\n\n<p>Will output:</p>\n\n<pre><code>10, a != 10, a, True\n</code></pre>\n"
},
{
"answer_id": 428664,
"author": "Rinat Abdullin",
"author_id": 47366,
"author_profile": "https://Stackoverflow.com/users/47366",
"pm_score": 4,
"selected": false,
"text": "<p>There is a <strong>proper</strong> (not quick) <strong>C# Tuple</strong> implementation in <a href=\"http://rabdullin.com/journal/2008/9/30/using-tuples-in-c-functions-and-dictionaries.html\" rel=\"nofollow noreferrer\">Lokad Shared Libraries</a> (Open-source, of course) that includes following required features:</p>\n\n<ul>\n<li>2-5 immutable tuple implementations</li>\n<li>Proper DebuggerDisplayAttribute</li>\n<li>Proper hashing and equality checks</li>\n<li>Helpers for generating tuples from the provided parameters (generics are inferred by compiler) and extensions for collection-based operations.</li>\n<li>production-tested.</li>\n</ul>\n"
},
{
"answer_id": 1047961,
"author": "Andreas Grech",
"author_id": 44084,
"author_profile": "https://Stackoverflow.com/users/44084",
"pm_score": 7,
"selected": true,
"text": "<p>I've just read this article from the MSDN Magazine: <a href=\"http://msdn.microsoft.com/en-us/magazine/dd942829.aspx\" rel=\"noreferrer\">Building Tuple</a></p>\n\n<p>Here are excerpts:</p>\n\n<blockquote>\n <p>The upcoming 4.0 release of Microsoft\n .NET Framework introduces a new type\n called System.Tuple. System.Tuple is a\n fixed-size collection of\n heterogeneously typed data.\n \n </p>\n</blockquote>\n\n<p> </p>\n\n<blockquote>\n <p>Like an array, a tuple has a fixed\n size that can't be changed once it has\n been created. Unlike an array, each\n element in a tuple may be a different\n type, and a tuple is able to guarantee\n strong typing for each element.</p>\n</blockquote>\n\n<p> </p>\n\n<blockquote>\n <p>There is already one example of a\n tuple floating around the Microsoft\n .NET Framework, in the\n System.Collections.Generic namespace:\n KeyValuePair. While KeyValuePair can be thought of as the same\n as Tuple, since they are both\n types that hold two things,\n KeyValuePair feels different from\n Tuple because it evokes a relationship\n between the two values it stores (and\n with good reason, as it supports the\n Dictionary class). </p>\n \n <p>Furthermore, tuples can be arbitrarily\n sized, whereas KeyValuePair holds only\n two things: a key and a value.</p>\n</blockquote>\n\n<hr>\n\n<p>While some languages like F# have special syntax for tuples, you can use the new common tuple type from any language. Revisiting the first example, we can see that while useful, tuples can be overly verbose in languages without syntax for a tuple:</p>\n\n<pre><code>class Program {\n static void Main(string[] args) {\n Tuple<string, int> t = new Tuple<string, int>(\"Hello\", 4);\n PrintStringAndInt(t.Item1, t.Item2);\n }\n static void PrintStringAndInt(string s, int i) {\n Console.WriteLine(\"{0} {1}\", s, i);\n }\n}\n</code></pre>\n\n<p>Using the var keyword from C# 3.0, we can remove the type signature on the tuple variable, which allows for somewhat more readable code.</p>\n\n<pre><code>var t = new Tuple<string, int>(\"Hello\", 4);\n</code></pre>\n\n<p>We've also added some factory methods to a static Tuple class which makes it easier to build tuples in a language that supports type inference, like C#.</p>\n\n<pre><code>var t = Tuple.Create(\"Hello\", 4);\n</code></pre>\n"
},
{
"answer_id": 1824010,
"author": "naasking",
"author_id": 144873,
"author_profile": "https://Stackoverflow.com/users/144873",
"pm_score": 2,
"selected": false,
"text": "<p>My open source .NET <a href=\"http://sf.net/projects/sasa\" rel=\"nofollow noreferrer\">Sasa library</a> has had tuples for years (along with plenty of other functionality, like full MIME parsing). I've been using it in production code for a good few years now.</p>\n"
},
{
"answer_id": 42646341,
"author": "Tim Pohlmann",
"author_id": 4961688,
"author_profile": "https://Stackoverflow.com/users/4961688",
"pm_score": 3,
"selected": false,
"text": "<p>C# 7 supports tuples natively:</p>\n\n<pre><code>var unnamedTuple = (\"Peter\", 29);\nvar namedTuple = (Name: \"Peter\", Age: 29);\n(string Name, double Age) typedTuple = (\"Peter\", 29);\n</code></pre>\n"
}
]
| 2008/09/30 | [
"https://Stackoverflow.com/questions/152019",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3834/"
]
| .Net 3.5 doesn't support tuples. Too bad, But not sure whether the future version of .net will support tuples or not? | I've just read this article from the MSDN Magazine: [Building Tuple](http://msdn.microsoft.com/en-us/magazine/dd942829.aspx)
Here are excerpts:
>
> The upcoming 4.0 release of Microsoft
> .NET Framework introduces a new type
> called System.Tuple. System.Tuple is a
> fixed-size collection of
> heterogeneously typed data.
>
>
>
>
>
>
> Like an array, a tuple has a fixed
> size that can't be changed once it has
> been created. Unlike an array, each
> element in a tuple may be a different
> type, and a tuple is able to guarantee
> strong typing for each element.
>
>
>
>
> There is already one example of a
> tuple floating around the Microsoft
> .NET Framework, in the
> System.Collections.Generic namespace:
> KeyValuePair. While KeyValuePair can be thought of as the same
> as Tuple, since they are both
> types that hold two things,
> KeyValuePair feels different from
> Tuple because it evokes a relationship
> between the two values it stores (and
> with good reason, as it supports the
> Dictionary class).
>
>
> Furthermore, tuples can be arbitrarily
> sized, whereas KeyValuePair holds only
> two things: a key and a value.
>
>
>
---
While some languages like F# have special syntax for tuples, you can use the new common tuple type from any language. Revisiting the first example, we can see that while useful, tuples can be overly verbose in languages without syntax for a tuple:
```
class Program {
static void Main(string[] args) {
Tuple<string, int> t = new Tuple<string, int>("Hello", 4);
PrintStringAndInt(t.Item1, t.Item2);
}
static void PrintStringAndInt(string s, int i) {
Console.WriteLine("{0} {1}", s, i);
}
}
```
Using the var keyword from C# 3.0, we can remove the type signature on the tuple variable, which allows for somewhat more readable code.
```
var t = new Tuple<string, int>("Hello", 4);
```
We've also added some factory methods to a static Tuple class which makes it easier to build tuples in a language that supports type inference, like C#.
```
var t = Tuple.Create("Hello", 4);
``` |
152,022 | <p>Any time I try to publish my Portal project on a Websphere Portal 6.1 Server, I get the following error message:</p>
<pre><code>Portal project publishing is not supported on WebSphere Portal v6.1 Server
</code></pre>
<p>Is that really true or have I done something wrong?</p>
<p>I'm trying to deploy a portal project, with the underlying goal of publishing a new theme.</p>
<p>Unfortunately, any time I try to deploy, I get the error message listed above from the IDE and no errors in the console.</p>
<p>The RAD version is 7.0.0.7.</p>
| [
{
"answer_id": 160715,
"author": "olore",
"author_id": 1691,
"author_profile": "https://Stackoverflow.com/users/1691",
"pm_score": 2,
"selected": true,
"text": "<p>Not sure this will help, but:</p>\n\n<blockquote>\n <p>Limitation: Although the WebSphere\n Portal installer contains an advanced\n option to install an empty portal,\n Portal Designer relies on\n administration portlets for setting\n access control; therefore, publishing\n a portal project to an empty portal is\n not supported.</p>\n</blockquote>\n\n<p>Are you trying to deploy a portlet or an entire portal project? What version of RAD are you using? Any other information in the error log? (Both within RAD & on WP server) Is the error message posted verbatim?</p>\n"
},
{
"answer_id": 4662320,
"author": "Dmitry",
"author_id": 459886,
"author_profile": "https://Stackoverflow.com/users/459886",
"pm_score": 0,
"selected": false,
"text": "<p>It is possible to deploy such a project to a WebSphere Portal. I use v6.2 and deploy portlets, which are parts of a big Portal project, every day. I'm only a starter in such a stuff, but I can say that WebSphere is really buggy. You know, it is a big difference to run a deployed app \"locally, in a workspace\" or \"on a server\". I suggest you to work out with server options - administrative console.</p>\n"
}
]
| 2008/09/30 | [
"https://Stackoverflow.com/questions/152022",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7966/"
]
| Any time I try to publish my Portal project on a Websphere Portal 6.1 Server, I get the following error message:
```
Portal project publishing is not supported on WebSphere Portal v6.1 Server
```
Is that really true or have I done something wrong?
I'm trying to deploy a portal project, with the underlying goal of publishing a new theme.
Unfortunately, any time I try to deploy, I get the error message listed above from the IDE and no errors in the console.
The RAD version is 7.0.0.7. | Not sure this will help, but:
>
> Limitation: Although the WebSphere
> Portal installer contains an advanced
> option to install an empty portal,
> Portal Designer relies on
> administration portlets for setting
> access control; therefore, publishing
> a portal project to an empty portal is
> not supported.
>
>
>
Are you trying to deploy a portlet or an entire portal project? What version of RAD are you using? Any other information in the error log? (Both within RAD & on WP server) Is the error message posted verbatim? |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.