qid
int64 4
8.14M
| question
stringlengths 20
48.3k
| answers
list | date
stringlengths 10
10
| metadata
sequence | input
stringlengths 12
45k
| output
stringlengths 2
31.8k
|
---|---|---|---|---|---|---|
45,600 | <p>The <a href="http://dev.jquery.com/view/trunk/ui/demos/functional/#ui.dialog" rel="nofollow noreferrer">demos</a> for the jquery ui dialog all use the "flora" theme. I wanted a customized theme, so I used the themeroller to generate a css file. When I used it, everything seemed to be working fine, but later I found that I can't control any input element contained in the dialog (i.e, can't type into a text field, can't check checkboxes). Further investigation revealed that this happens if I set the dialog attribute "modal" to true. This doesn't happen when I use the flora theme. </p>
<p>Here is the js file:</p>
<pre><code>topMenu = {
init: function(){
$("#my_button").bind("click", function(){
$("#SERVICE03_DLG").dialog("open");
$("#something").focus();
});
$("#SERVICE03_DLG").dialog({
autoOpen: false,
modal: true,
resizable: false,
title: "my title",
overlay: {
opacity: 0.5,
background: "black"
},
buttons: {
"OK": function() {
alert("hi!");
},
"cancel": function() {
$(this).dialog("close");
}
},
close: function(){
$("#something").val("");
}
});
}
}
$(document).ready(topMenu.init);
</code></pre>
<p>Here is the html that uses the flora theme:</p>
<pre><code><!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=Shift_JIS">
<title>sample</title>
<script src="jquery-1.2.6.min.js" language="JavaScript"></script>
<link rel="stylesheet" href="flora/flora.all.css" type="text/css">
<script src="jquery-ui-personalized-1.5.2.min.js" language="JavaScript"></script>
<script src="TopMenu.js" language="JavaScript"></script>
</head>
<body>
<input type="button" value="click me!" id="my_button">
<div id="SERVICE03_DLG" class="flora">please enter something<br><br>
<label for="something">somthing:</label>&nbsp;<input name="something" id="something" type="text" maxlength="20" size="24">
</div>
</body>
</html>
</code></pre>
<p>Here is the html that uses the downloaded themeroller theme:</p>
<pre><code><!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=Shift_JIS">
<title>sample</title>
<script src="jquery-1.2.6.min.js" language="JavaScript"></script>
<link rel="stylesheet" href="jquery-ui-themeroller.css" type="text/css">
<script src="jquery-ui-personalized-1.5.2.min.js" language="JavaScript"></script>
<script src="TopMenu.js" language="JavaScript"></script>
</head>
<body>
<input type="button" value="click me!" id="my_button">
<div id="SERVICE03_DLG" class="ui-dialog">please enter something<br><br>
<label for="something">somthing:</label>&nbsp;<input name="something" id="something" type="text" maxlength="20" size="24">
</div>
</body>
</html>
</code></pre>
<p>As you can see, only the referenced css file and class names are different.
Anybody have a clue as to what could be wrong?</p>
<p>@David: I tried it, and it doesn't seem to work (neither on FF or IE). I tried inline css:</p>
<pre class="lang-none prettyprint-override"><code>style="z-index:5000"
</code></pre>
<p>and I've also tried it referencing an external css file:</p>
<pre class="lang-none prettyprint-override"><code>#SERVICE03_DLG{z-index:5000;}
</code></pre>
<p>But neither of these work. Am I missing something in what you suggested?</p>
<p><strong>Edit:</strong><br>
Solve by brostbeef!<br>
Since I was originally using flora, I had mistakenly assumed that I have to specify a class attribute. Turns out, this is only true when you actually use the flora theme (as in the samples). If you use the customized theme, specifying a class attribute causes that strange behaviour.</p>
| [
{
"answer_id": 45752,
"author": "David McLaughlin",
"author_id": 3404,
"author_profile": "https://Stackoverflow.com/users/3404",
"pm_score": 1,
"selected": false,
"text": "<p>After playing with this in Firebug, if you add a z-index attribute greater than 1004 to your default div, id of \"SERVICE03_DLG\", then it will work. I'd give it something extremely high, like 5000, just to be sure.</p>\n\n<p>I'm not sure what it is in the themeroller CSS that causes this. They've probably changed or neglected the position attribute of the target div that it turns into a dialog.</p>\n"
},
{
"answer_id": 46061,
"author": "Brock Boland",
"author_id": 2185,
"author_profile": "https://Stackoverflow.com/users/2185",
"pm_score": 0,
"selected": false,
"text": "<p>Man, this is a good one. I've tried doing a bunch of things on these two pages. Have you tried just leaving the CSS out altogether and trying both pages then? I used Firebug to remove the CSS from the header on both pages, and the input still worked on one and not on the other - but, I'm inclined to believe that Firebug doesn't completely remove the CSS from the rendering, and you'll get different results if you actually remove it from the code.</p>\n\n<p>I also found that you can paste text into the text box using the mouse - it just won't accept keyboard input. There doesn't seem to be any event handler on it that would interfere with this, though.</p>\n"
},
{
"answer_id": 177894,
"author": "MDCore",
"author_id": 1896,
"author_profile": "https://Stackoverflow.com/users/1896",
"pm_score": 1,
"selected": false,
"text": "<p>I tried implementing a themeroller theme with a dialog and tabs and it turns out that <strong>the themeroller CSS doesn't work with official jQuery</strong>! Especially for dialog and tabs, they modified the element classes from the official jquery ones. See here:\n<a href=\"http://filamentgroup.com/lab/introducing_themeroller_design_download_custom_themes_for_jquery_ui/\" rel=\"nofollow noreferrer\"><a href=\"http://filamentgroup.com/lab/introducing_themeroller_design_download_custom_themes_for_jquery_ui/\" rel=\"nofollow noreferrer\">http://filamentgroup.com/lab/introducing_themeroller_design_download_custom_themes_for_jquery_ui/</a></a></p>\n\n<p>A user's comment:</p>\n\n<blockquote>\n <p>3) the generated theme that I\n downloaded seems to be incomplete -\n when I attempt to use it my tabs\n (which work with the flora theme, code\n identical to the documentation\n example) do not get styled as tabs</p>\n \n <p>Having run into 3 I thought I was\n stuck and would have to revert using\n “flora\"… I have since discovered by\n reading the source code of the “demo”\n file that if I adjust my html and give\n the < li> items I’m using for my tabs\n the “ui-tabs-nav-item” class then it\n will work.</p>\n \n <p>The theme generated by themeroller is\n thus unfortunately incomplete. If the\n tabs stuff is incomplete, it makes me\n wonder what else is incomplete. It\n was rather frustrating. :(</p>\n</blockquote>\n\n<p>followed by the themeroller developers comment:</p>\n\n<blockquote>\n <p>3) We’ll take a look at that. You’re right that those classes\n should be added by the plugin. For now though, it probably\n wouldn’t hurt much to just add them to your markup so you \n can use themeroller themes.\n We’ll check it out, though. I think our selectors could be \n based off of the parent ui-tabs selector instead, but I think \n we were trying not to use elements in our selectors. Consider\n it on the to-do list</p>\n</blockquote>\n"
},
{
"answer_id": 231357,
"author": "brostbeef",
"author_id": 16437,
"author_profile": "https://Stackoverflow.com/users/16437",
"pm_score": 3,
"selected": true,
"text": "<p>I think it is because you have the classes different.<br/>\n<code><div id=\"SERVICE03_DLG\" class=\"flora\"></code> (flora)<br/>\n<code><div id=\"SERVICE03_DLG\" class=\"ui-dialog\"></code> (custom)</p>\n\n<p>Even with the flora theme, you would still use the ui-dialog class to define it as a dialog.</p>\n\n<p>I've done modals before and I've never even defined a class in the tag. jQueryUI should take care of that for you.</p>\n\n<p>Try getting rid of the class attribute or using the \"ui-dialog\" class.</p>\n"
}
] | 2008/09/05 | [
"https://Stackoverflow.com/questions/45600",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3751/"
] | The [demos](http://dev.jquery.com/view/trunk/ui/demos/functional/#ui.dialog) for the jquery ui dialog all use the "flora" theme. I wanted a customized theme, so I used the themeroller to generate a css file. When I used it, everything seemed to be working fine, but later I found that I can't control any input element contained in the dialog (i.e, can't type into a text field, can't check checkboxes). Further investigation revealed that this happens if I set the dialog attribute "modal" to true. This doesn't happen when I use the flora theme.
Here is the js file:
```
topMenu = {
init: function(){
$("#my_button").bind("click", function(){
$("#SERVICE03_DLG").dialog("open");
$("#something").focus();
});
$("#SERVICE03_DLG").dialog({
autoOpen: false,
modal: true,
resizable: false,
title: "my title",
overlay: {
opacity: 0.5,
background: "black"
},
buttons: {
"OK": function() {
alert("hi!");
},
"cancel": function() {
$(this).dialog("close");
}
},
close: function(){
$("#something").val("");
}
});
}
}
$(document).ready(topMenu.init);
```
Here is the html that uses the flora theme:
```
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=Shift_JIS">
<title>sample</title>
<script src="jquery-1.2.6.min.js" language="JavaScript"></script>
<link rel="stylesheet" href="flora/flora.all.css" type="text/css">
<script src="jquery-ui-personalized-1.5.2.min.js" language="JavaScript"></script>
<script src="TopMenu.js" language="JavaScript"></script>
</head>
<body>
<input type="button" value="click me!" id="my_button">
<div id="SERVICE03_DLG" class="flora">please enter something<br><br>
<label for="something">somthing:</label> <input name="something" id="something" type="text" maxlength="20" size="24">
</div>
</body>
</html>
```
Here is the html that uses the downloaded themeroller theme:
```
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=Shift_JIS">
<title>sample</title>
<script src="jquery-1.2.6.min.js" language="JavaScript"></script>
<link rel="stylesheet" href="jquery-ui-themeroller.css" type="text/css">
<script src="jquery-ui-personalized-1.5.2.min.js" language="JavaScript"></script>
<script src="TopMenu.js" language="JavaScript"></script>
</head>
<body>
<input type="button" value="click me!" id="my_button">
<div id="SERVICE03_DLG" class="ui-dialog">please enter something<br><br>
<label for="something">somthing:</label> <input name="something" id="something" type="text" maxlength="20" size="24">
</div>
</body>
</html>
```
As you can see, only the referenced css file and class names are different.
Anybody have a clue as to what could be wrong?
@David: I tried it, and it doesn't seem to work (neither on FF or IE). I tried inline css:
```none
style="z-index:5000"
```
and I've also tried it referencing an external css file:
```none
#SERVICE03_DLG{z-index:5000;}
```
But neither of these work. Am I missing something in what you suggested?
**Edit:**
Solve by brostbeef!
Since I was originally using flora, I had mistakenly assumed that I have to specify a class attribute. Turns out, this is only true when you actually use the flora theme (as in the samples). If you use the customized theme, specifying a class attribute causes that strange behaviour. | I think it is because you have the classes different.
`<div id="SERVICE03_DLG" class="flora">` (flora)
`<div id="SERVICE03_DLG" class="ui-dialog">` (custom)
Even with the flora theme, you would still use the ui-dialog class to define it as a dialog.
I've done modals before and I've never even defined a class in the tag. jQueryUI should take care of that for you.
Try getting rid of the class attribute or using the "ui-dialog" class. |
45,604 | <p>C# doesn't require you to specify a generic type parameter if the compiler can infer it, for instance:</p>
<pre><code>List<int> myInts = new List<int> {0,1,1,
2,3,5,8,13,21,34,55,89,144,233,377,
610,987,1597,2584,4181,6765};
//this statement is clunky
List<string> myStrings = myInts.
Select<int,string>( i => i.ToString() ).
ToList<string>();
//the type is inferred from the lambda expression
//the compiler knows that it's taking an int and
//returning a string
List<string> myStrings = myInts.
Select( i => i.ToString() ).
ToList();
</code></pre>
<p>This is needed for anonymous types where you don't know what the type parameter would be (in intellisense it shows up as <code>'a</code>) because it's added by the compiler.</p>
<p>Class-level type parameters don't let you do this:</p>
<pre><code>//sample generic class
public class GenericDemo<T>
{
public GenericDemo ( T value )
{
GenericTypedProperty = value;
}
public T GenericTypedProperty {get; set;}
}
//why can't I do:
int anIntValue = 4181;
var item = new GenericDemo( anIntValue ); //type inference fails
//however I can create a wrapper like this:
public static GenericDemo<T> Create<T> ( T value )
{
return new GenericDemo<T> ( value );
}
//then this works - type inference on the method compiles
var item = Create( anIntValue );
</code></pre>
<p>Why doesn't C# support this class level generic type inference?</p>
| [
{
"answer_id": 45612,
"author": "Konrad Rudolph",
"author_id": 1968,
"author_profile": "https://Stackoverflow.com/users/1968",
"pm_score": 3,
"selected": false,
"text": "<blockquote>\n <p>Why doesn't C# support this class level generic type inference?</p>\n</blockquote>\n\n<p>Because they're generally ambiguous. By contrast, type inference is trivial for function calls (if all types appear in arguments). But in the case of constructor calls (glorified functions, for the sake of discussion), the compiler has to resolve multiple levels at the same time. One level is the class level and the other is the constructor arguments level. I believe solving this is algorithmically non-trivial. Intuitively, I'd say it's even NP-complete.</p>\n\n<p>To illustrate an extreme case where resolution is impossible, imagine the following class and tell me what the compiler should do:</p>\n\n<pre><code>class Foo<T> {\n public Foo<U>(U x) { }\n}\n\nvar x = new Foo(1);\n</code></pre>\n"
},
{
"answer_id": 45706,
"author": "Keith",
"author_id": 905,
"author_profile": "https://Stackoverflow.com/users/905",
"pm_score": 2,
"selected": false,
"text": "<p>Thanks Konrad, that's a good response (+1), but just to expand on it.</p>\n\n<p>Let's pretend that C# has an explicit constructor function:</p>\n\n<pre><code>//your example\nvar x = new Foo( 1 );\n\n//becomes\nvar x = Foo.ctor( 1 );\n\n//your problem is valid because this would be\nvar x = Foo<T>.ctor<int>( 1 );\n//and T can't be inferred\n</code></pre>\n\n<p>You're quite right that the first constructor can't be inferred.</p>\n\n<p>Now let's go back to the class</p>\n\n<pre><code>class Foo<T> \n{\n //<T> can't mean anything else in this context\n public Foo(T x) { }\n}\n\n//this would now throw an exception unless the\n//typeparam matches the parameter\nvar x = Foo<int>.ctor( 1 );\n\n//so why wouldn't this work?\nvar x = Foo.ctor( 1 );\n</code></pre>\n\n<p>Of course, if I add your constructor back in (with its alternate type) we have an ambiguous call - exactly as if a normal method overload couldn't be resolved.</p>\n"
},
{
"answer_id": 45728,
"author": "Konrad Rudolph",
"author_id": 1968,
"author_profile": "https://Stackoverflow.com/users/1968",
"pm_score": 6,
"selected": true,
"text": "<p>Actually, your question isn't bad. I've been toying with a generic programming language for last few years and although I've never come around to actually develop it (and probably never will), I've thought a lot about generic type inference and one of my top priorities has always been to allow the construction of classes without having to specify the generic type.</p>\n\n<p>C# simply lacks the set of rules to make this possible. I think the developers never saw the neccesity to include this. Actually, the following code would be very near to your proposition and solve the problem. All C# needs is an added syntax support.</p>\n\n<pre><code>class Foo<T> {\n public Foo(T x) { … }\n}\n\n// Notice: non-generic class overload. Possible in C#!\nclass Foo {\n public static Foo<T> ctor<T>(T x) { return new Foo<T>(x); }\n}\n\nvar x = Foo.ctor(42);\n</code></pre>\n\n<p>Since this code actually works, we've shown that the problem is not one of semantics but simply one of lacking support. I guess I have to take back my previous posting. ;-)</p>\n"
}
] | 2008/09/05 | [
"https://Stackoverflow.com/questions/45604",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/905/"
] | C# doesn't require you to specify a generic type parameter if the compiler can infer it, for instance:
```
List<int> myInts = new List<int> {0,1,1,
2,3,5,8,13,21,34,55,89,144,233,377,
610,987,1597,2584,4181,6765};
//this statement is clunky
List<string> myStrings = myInts.
Select<int,string>( i => i.ToString() ).
ToList<string>();
//the type is inferred from the lambda expression
//the compiler knows that it's taking an int and
//returning a string
List<string> myStrings = myInts.
Select( i => i.ToString() ).
ToList();
```
This is needed for anonymous types where you don't know what the type parameter would be (in intellisense it shows up as `'a`) because it's added by the compiler.
Class-level type parameters don't let you do this:
```
//sample generic class
public class GenericDemo<T>
{
public GenericDemo ( T value )
{
GenericTypedProperty = value;
}
public T GenericTypedProperty {get; set;}
}
//why can't I do:
int anIntValue = 4181;
var item = new GenericDemo( anIntValue ); //type inference fails
//however I can create a wrapper like this:
public static GenericDemo<T> Create<T> ( T value )
{
return new GenericDemo<T> ( value );
}
//then this works - type inference on the method compiles
var item = Create( anIntValue );
```
Why doesn't C# support this class level generic type inference? | Actually, your question isn't bad. I've been toying with a generic programming language for last few years and although I've never come around to actually develop it (and probably never will), I've thought a lot about generic type inference and one of my top priorities has always been to allow the construction of classes without having to specify the generic type.
C# simply lacks the set of rules to make this possible. I think the developers never saw the neccesity to include this. Actually, the following code would be very near to your proposition and solve the problem. All C# needs is an added syntax support.
```
class Foo<T> {
public Foo(T x) { … }
}
// Notice: non-generic class overload. Possible in C#!
class Foo {
public static Foo<T> ctor<T>(T x) { return new Foo<T>(x); }
}
var x = Foo.ctor(42);
```
Since this code actually works, we've shown that the problem is not one of semantics but simply one of lacking support. I guess I have to take back my previous posting. ;-) |
45,611 | <p>I have a database with a few dozen tables interlinked with foreign keys. Under normal circumstances, I want the default <code>ON DELETE RESTRICT</code> behavior for those constraints. But when trying to share a snapshot of the database with a consultant, I needed to remove some sensitive data. I wish that my memory of a <code>DELETE FROM Table CASCADE</code> command hadn't been pure hallucination.</p>
<p>What I ended out doing was dumping the database, writing a script to process the dump by adding <code>ON DELETE CASCADE</code> clauses too all the foreign key constraints, restoring from that, performing my deletes, dumping again, removing the <code>ON DELETE CASCADE</code>, and finally restoring again. That was easier than writing the deletion query I'd have needed to do this in SQL -- removing whole slices of the database isn't a normal operation, so the schema isn't exactly adapted to it.</p>
<p>Does anyone have a better solution for the next time something like this comes up?</p>
| [
{
"answer_id": 45893,
"author": "Tony Lenzi",
"author_id": 4513,
"author_profile": "https://Stackoverflow.com/users/4513",
"pm_score": 0,
"selected": false,
"text": "<p>You may want to look into using <a href=\"http://www.postgresql.org/docs/8.2/static/ddl-schemas.html\" rel=\"nofollow noreferrer\">schemas</a> with PostgreSQL. I've done this in past projects to allow different groups of people or developers to have their own data. Then you can use your scripts to create multiple copies of your database for just such situations.</p>\n"
},
{
"answer_id": 47635,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 0,
"selected": false,
"text": "<p>@Tony: No, schemas can be useful, and indeed, we use them to partition data in our database. But I'm talking about trying to scrub sensitive data before letting a consultant have a copy of the db. I want that data gone.</p>\n"
},
{
"answer_id": 56978,
"author": "angch",
"author_id": 5386,
"author_profile": "https://Stackoverflow.com/users/5386",
"pm_score": 0,
"selected": false,
"text": "<p>I don't think you'd need to process the dump file like that. Do a streaming dump/restore, and process that. Something like:</p>\n\n<pre><code>createdb -h scratchserver scratchdb\ncreatedb -h scratchserver sanitizeddb\n\npg_dump -h liveserver livedb --schema-only | psql -h scratchserver sanitizeddb\npg_dump -h scratchserver sanitizeddb | sed -e \"s/RESTRICT/CASCADE/\" | psql -h scratchserver scratchdb\n\npg_dump -h liveserver livedb --data-only | psql -h scratchserver scratchdb\npsql -h scrachserver scratchdb -f delete-sensitive.sql\n\npg_dump -h scratchserver scratchdb --data-only | psql -h scratchserver sanitizeddb\npg_dump -Fc -Z9 -h scratchserver sanitizedb > sanitizeddb.pgdump\n</code></pre>\n\n<p>where you store all your DELETE sqls in delete-sensitive.sql. The sanitizeddb database/steps can be removed if you don't mind the consultant getting a db with CASCADE foreign keys instead of RESTRICT foreign keys.</p>\n\n<p>There might also be better ways depending on how often you need to do this, how big the database is, and what percentage of data is sensitive, but I can't think of a simpler way to do it <strong>once or twice</strong> for a <strong>reasonably sized</strong> database. You'd need a different database after all, so unless you already have a slony cluster, can't avoid the dump/restore cycle, which might be time consuming.</p>\n"
},
{
"answer_id": 155396,
"author": "Grant Johnson",
"author_id": 12518,
"author_profile": "https://Stackoverflow.com/users/12518",
"pm_score": 2,
"selected": false,
"text": "<p>You do not need to dump and restore. You should be able to just drop the constraint, rebuild it with cascade, do your deletes, drop it again, and the rebuild it with restrict.</p>\n\n<pre><code>CREATE TABLE \"header\"\n(\n header_id serial NOT NULL,\n CONSTRAINT header_pkey PRIMARY KEY (header_id)\n);\n\nCREATE TABLE detail\n(\n header_id integer,\n stuff text,\n CONSTRAINT detail_header_id_fkey FOREIGN KEY (header_id)\n REFERENCES \"header\" (header_id) MATCH SIMPLE\n ON UPDATE NO ACTION ON DELETE NO ACTION\n);\ninsert into header values(1);\ninsert into detail values(1,'stuff');\ndelete from header where header_id=1;\nalter table detail drop constraint detail_header_id_fkey;\nalter table detail add constraint detail_header_id_fkey FOREIGN KEY (header_id)\n REFERENCES \"header\" (header_id) on delete cascade;\ndelete from header where header_id=1;\nalter table detail add constraint detail_header_id_fkey FOREIGN KEY (header_id)\n REFERENCES \"header\" (header_id) on delete restrict;\n</code></pre>\n"
},
{
"answer_id": 158446,
"author": "agnul",
"author_id": 6069,
"author_profile": "https://Stackoverflow.com/users/6069",
"pm_score": 1,
"selected": false,
"text": "<p>You could create the foreign key constraints as DEFERRABLE. Then you would be able to temporarily disable them while you scrub the data and re-enable them when you are done. Have a look at <a href=\"https://stackoverflow.com/questions/139884/how-do-i-disable-referential-integrity-in-postgres-82\">this question</a>.</p>\n"
},
{
"answer_id": 3010204,
"author": "user362911",
"author_id": 362911,
"author_profile": "https://Stackoverflow.com/users/362911",
"pm_score": 1,
"selected": false,
"text": "<pre><code>TRUNCATE table CASCADE;\n</code></pre>\n\n<p>I'm a Postgres novice, so I'm not sure what the trade-off is for TRUNCATE vs. DROP.</p>\n"
},
{
"answer_id": 3320975,
"author": "Tim Davis",
"author_id": 400534,
"author_profile": "https://Stackoverflow.com/users/400534",
"pm_score": 0,
"selected": false,
"text": "<p>TRUNCATE just removes the data from table and leaves the structure</p>\n"
}
] | 2008/09/05 | [
"https://Stackoverflow.com/questions/45611",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] | I have a database with a few dozen tables interlinked with foreign keys. Under normal circumstances, I want the default `ON DELETE RESTRICT` behavior for those constraints. But when trying to share a snapshot of the database with a consultant, I needed to remove some sensitive data. I wish that my memory of a `DELETE FROM Table CASCADE` command hadn't been pure hallucination.
What I ended out doing was dumping the database, writing a script to process the dump by adding `ON DELETE CASCADE` clauses too all the foreign key constraints, restoring from that, performing my deletes, dumping again, removing the `ON DELETE CASCADE`, and finally restoring again. That was easier than writing the deletion query I'd have needed to do this in SQL -- removing whole slices of the database isn't a normal operation, so the schema isn't exactly adapted to it.
Does anyone have a better solution for the next time something like this comes up? | You do not need to dump and restore. You should be able to just drop the constraint, rebuild it with cascade, do your deletes, drop it again, and the rebuild it with restrict.
```
CREATE TABLE "header"
(
header_id serial NOT NULL,
CONSTRAINT header_pkey PRIMARY KEY (header_id)
);
CREATE TABLE detail
(
header_id integer,
stuff text,
CONSTRAINT detail_header_id_fkey FOREIGN KEY (header_id)
REFERENCES "header" (header_id) MATCH SIMPLE
ON UPDATE NO ACTION ON DELETE NO ACTION
);
insert into header values(1);
insert into detail values(1,'stuff');
delete from header where header_id=1;
alter table detail drop constraint detail_header_id_fkey;
alter table detail add constraint detail_header_id_fkey FOREIGN KEY (header_id)
REFERENCES "header" (header_id) on delete cascade;
delete from header where header_id=1;
alter table detail add constraint detail_header_id_fkey FOREIGN KEY (header_id)
REFERENCES "header" (header_id) on delete restrict;
``` |
45,613 | <p>What could be the problem with reversing the array of DOM objects as in the following code:</p>
<pre><code>var imagesArr = new Array();
imagesArr = document.getElementById("myDivHolderId").getElementsByTagName("img");
imagesArr.reverse();
</code></pre>
<p>In Firefox 3, when I call the <code>reverse()</code> method the script stops executing and shows the following error in the console of the Web Developer Toolbar:</p>
<pre class="lang-none prettyprint-override"><code>imagesArr.reverse is not a function
</code></pre>
<p>The <code>imagesArr</code> variable can be iterated through with a for loop and elements like <code>imagesArr[i]</code> can be accessed, so why is it not seen as an array when calling the <code>reverse()</code> method?</p>
| [
{
"answer_id": 45622,
"author": "DevelopingChris",
"author_id": 1220,
"author_profile": "https://Stackoverflow.com/users/1220",
"pm_score": 1,
"selected": false,
"text": "<p>Your first line is irrelevant, since it doesn't coerce the assignment to the variable, javascript works the other way. imagesArr, is not of Type Array(), its of whatever the return type of getElementsByTagName(\"img\") is. In this case, its an HtmlCollection in Firefox 3.</p>\n\n<p>The only methods on this object, are the indexers, and length. In order to work in reverse, just iterate backwards.</p>\n"
},
{
"answer_id": 45625,
"author": "Adam Wright",
"author_id": 1200,
"author_profile": "https://Stackoverflow.com/users/1200",
"pm_score": 5,
"selected": true,
"text": "<p>Because getElementsByTag name actually returns a NodeList structure. It has similar array like indexing properties for syntactic convenience, but it is <em>not</em> an array. For example, the set of entries is actually constantly being dynamically updated - if you add a new img tag under myDivHolderId, it will automatically appear in imagesArr.</p>\n\n<p>See <a href=\"http://www.w3.org/TR/DOM-Level-2-Core/core.html#ID-536297177\" rel=\"noreferrer\">http://www.w3.org/TR/DOM-Level-2-Core/core.html#ID-536297177</a> for more.</p>\n"
},
{
"answer_id": 45740,
"author": "Vincent Robert",
"author_id": 268,
"author_profile": "https://Stackoverflow.com/users/268",
"pm_score": 3,
"selected": false,
"text": "<p><code>getElementsByTag()</code> returns a NodeList instead of an Array. You can convert a NodeList to an Array but note that the array will be another object, so reversing it will not affect the DOM nodes position.</p>\n\n<pre><code>var listNodes = document.getElementById(\"myDivHolderId\").getElementsByTagName(\"img\");\nvar arrayNodes = Array.slice.call(listNodes, 0);\narrayNodes.reverse();\n</code></pre>\n\n<p>In order to change the position, you will have to remove the DOM nodes and add them all again at the right position.</p>\n\n<p><code>Array.prototype.slice.call(arrayLike, 0)</code> is a great way to convert an array-like to an array, but if you are using a JavaScript library, it may actually provide a even better/faster way to do it. For example, jQuery has <code>$.makeArray(arrayLike)</code>.</p>\n\n<p>You can also use the Array methods directly on the NodeList:</p>\n\n<pre><code>Array.prototype.reverse.call(listNodes);\n</code></pre>\n"
},
{
"answer_id": 28211790,
"author": "iProDev",
"author_id": 4506730,
"author_profile": "https://Stackoverflow.com/users/4506730",
"pm_score": 3,
"selected": false,
"text": "<p><code>getElementsByTag()</code> returns a NodeList instead of an Array. You need to convert the NodeList to an array then reverse it.</p>\n\n<pre><code>var imagesArr = [].slice.call(document.getElementById(\"myDivHolderId\").getElementsByTagName(\"img\"), 0).reverse();\n</code></pre>\n"
},
{
"answer_id": 29168307,
"author": "Mr. X",
"author_id": 4388578,
"author_profile": "https://Stackoverflow.com/users/4388578",
"pm_score": 2,
"selected": false,
"text": "<p>I know this question is old but I think it needs a bit of clarification as some of the answers here are outdated as W3C changed the definition, and consequently the return value of these methods <code>getElementsByTagName()</code> and <code>getElementsByClassName()</code></p>\n\n<p>These methods <strong>as of the time of writing this answer</strong> return an object - empty or not - of type <code>HTMLCollection</code> and <strong>not</strong> <code>NodeList</code>.</p>\n\n<p>It's like the difference between the properties <code>children</code> which returns an object of type <code>HTMLCollection</code> since it's only composed of elements and excluding text or comment nodes, and <code>childNodes</code> which returns an object of type <code>NodeList</code> since it could contain other node types like text and comments as well. </p>\n\n<p>Note: I'd go on tangent here and express my lack of insight on why <code>querySelectorAll()</code> method currently returns a <code>NodeList</code> and not an <code>HTMLCollection</code> since it exclusively works on element nodes in the document and nothing else. </p>\n\n<p>Probably it has something to do with potential coverage of other node types in the future and they went for a more future proof solution, who knows really? :)</p>\n\n<p>EDIT: I think I got the rationale behind this decision to opt for a <code>NodeList</code> and not an <code>HTMLCollection</code> for the <code>querySelectorAll()</code>. </p>\n\n<p>Since they constructed <code>HTMLCollection</code> to be exclusively and entirely live and since this method doesn't need this live functionality, they decided for a <code>NodeList</code> implementation instead to best serve its purpose economically and efficiently. </p>\n"
},
{
"answer_id": 68064201,
"author": "Muhammad Fahim",
"author_id": 12581164,
"author_profile": "https://Stackoverflow.com/users/12581164",
"pm_score": 3,
"selected": false,
"text": "<p>this problem can Actually be solved easily with array spread operator.</p>\n<p><div class=\"snippet\" data-lang=\"js\" data-hide=\"false\" data-console=\"true\" data-babel=\"false\">\r\n<div class=\"snippet-code\">\r\n<pre class=\"snippet-code-js lang-js prettyprint-override\"><code>let elements = document.querySelectorAll('button');\nelements = [...elements];\nconsole.log(elements) // Before reverse\nelements = elements.reverse(); // Now the reverse function will work\nconsole.log(elements) // After reverse</code></pre>\r\n<pre class=\"snippet-code-html lang-html prettyprint-override\"><code><html>\n<body>\n<button>button1</button>\n<button>button2</button>\n<button>button3</button>\n<button>button4</button>\n<button>button5</button>\n</body>\n</html></code></pre>\r\n</div>\r\n</div>\r\n</p>\n"
},
{
"answer_id": 73631405,
"author": "Baz Love",
"author_id": 2845079,
"author_profile": "https://Stackoverflow.com/users/2845079",
"pm_score": 0,
"selected": false,
"text": "<p>This worked for me, I did a reverse for loop and allocated the nodes to an array</p>\n<pre><code>var Slides = document.getElementById("slideshow").querySelectorAll('li');\nvar TempArr = [];\nfor (var x = Slides.length; x--;) {\n TempArr.push(Slides[x]);\n}\nSlides = TempArr;\n</code></pre>\n"
}
] | 2008/09/05 | [
"https://Stackoverflow.com/questions/45613",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4723/"
] | What could be the problem with reversing the array of DOM objects as in the following code:
```
var imagesArr = new Array();
imagesArr = document.getElementById("myDivHolderId").getElementsByTagName("img");
imagesArr.reverse();
```
In Firefox 3, when I call the `reverse()` method the script stops executing and shows the following error in the console of the Web Developer Toolbar:
```none
imagesArr.reverse is not a function
```
The `imagesArr` variable can be iterated through with a for loop and elements like `imagesArr[i]` can be accessed, so why is it not seen as an array when calling the `reverse()` method? | Because getElementsByTag name actually returns a NodeList structure. It has similar array like indexing properties for syntactic convenience, but it is *not* an array. For example, the set of entries is actually constantly being dynamically updated - if you add a new img tag under myDivHolderId, it will automatically appear in imagesArr.
See <http://www.w3.org/TR/DOM-Level-2-Core/core.html#ID-536297177> for more. |
45,623 | <p>In Java, what would the best way be to have a constantly listening port open, and still send upon receipt of a packet. I am not particularly savvy with network programming at the moment, so the tutorials I have found on the net aren't particularly helpful.</p>
<p>Would it make sense to have the listening socket as a serversocket and run it in a separate thread to the socket I'm using to send data to the server?</p>
<p>In a loosely related question. Does anyone know if programming simply for java, in netbeans then exporting it for use on a blackberry (using a plugin) the sockets would still work ?</p>
| [
{
"answer_id": 45630,
"author": "basszero",
"author_id": 287,
"author_profile": "https://Stackoverflow.com/users/287",
"pm_score": 5,
"selected": true,
"text": "<p>If you can afford the threading, try this (keep in mind I've left out some details like exception handling and playing nice with threads). You may want to look into <code>SocketChannels</code> and/or NIO async sockets / selectors. This should get you started.</p>\n\n<pre><code>boolean finished = false;\nint port = 10000;\nServerSocket server = new ServerSocket(port);\n\nwhile (!finished) {\n // This will block until a connection is made\n Socket s = server.accept();\n // Spawn off some thread (or use a thread pool) to handle this socket\n // Server will continue to listen\n}\n</code></pre>\n"
},
{
"answer_id": 45678,
"author": "Joe Liversedge",
"author_id": 4552,
"author_profile": "https://Stackoverflow.com/users/4552",
"pm_score": 1,
"selected": false,
"text": "<p>I'd need to go back to the basics for this one too. I'd recommend O'Reilly's excellent <em>Java in a Nutshell</em> that includes code examples for just such a case (available <a href=\"http://oreilly.com/catalog/javanut/examples/\" rel=\"nofollow noreferrer\">online</a> as well). See Chapter 7 for a pretty good overview of the decisions you'd want to make early on.</p>\n"
},
{
"answer_id": 83460,
"author": "Richard",
"author_id": 7740,
"author_profile": "https://Stackoverflow.com/users/7740",
"pm_score": 2,
"selected": false,
"text": "<p>As for connecting to a Blackberry, this is problematic since in most cases the Blackberry won't have a public IP address and will instead be behind a WAP gateway or wireless provider access point server. RIM provides the Mobile Data Server (MDS) to get around this and provide \"Push\" data which uses ServerSocket semantics on the Blackberry. The MDS is available with the Blackberry Enterprise Server (BES) and the Unite Server.</p>\n\n<p>Once set up data can be sent to a particular unit via the MDS using the HTTP protocol. There is an excellent description of the Push protocol <a href=\"http://blog.fupps.com/documents/blackberry/real-world-blackberry-mds-push-applications-an-extensible-framework/\" rel=\"nofollow noreferrer\">here</a> with LAMP source code. The parameter PORT=7874 in <a href=\"http://fupps.com/code/bberry/push/pushout.pl\" rel=\"nofollow noreferrer\">pushout.pl</a> connects to the Blackberry Browser Push server socket. By changing that parameter the payload can be sent to an arbitrary port where your own ServerSocket is accepting connections. </p>\n"
},
{
"answer_id": 88354,
"author": "Alexander",
"author_id": 16724,
"author_profile": "https://Stackoverflow.com/users/16724",
"pm_score": 2,
"selected": false,
"text": "<p>If your socket code has to run on a BlackBerry, you cannot using standard Java sockets. You have to use the J2ME Connector.open API for creating both types of sockets (those that initiate connections from the BlackBerry, and those that listen for connections/pushes on the BlackBerry). Have a look at the examples that come with RIM's JDE.</p>\n"
}
] | 2008/09/05 | [
"https://Stackoverflow.com/questions/45623",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4739/"
] | In Java, what would the best way be to have a constantly listening port open, and still send upon receipt of a packet. I am not particularly savvy with network programming at the moment, so the tutorials I have found on the net aren't particularly helpful.
Would it make sense to have the listening socket as a serversocket and run it in a separate thread to the socket I'm using to send data to the server?
In a loosely related question. Does anyone know if programming simply for java, in netbeans then exporting it for use on a blackberry (using a plugin) the sockets would still work ? | If you can afford the threading, try this (keep in mind I've left out some details like exception handling and playing nice with threads). You may want to look into `SocketChannels` and/or NIO async sockets / selectors. This should get you started.
```
boolean finished = false;
int port = 10000;
ServerSocket server = new ServerSocket(port);
while (!finished) {
// This will block until a connection is made
Socket s = server.accept();
// Spawn off some thread (or use a thread pool) to handle this socket
// Server will continue to listen
}
``` |
45,624 | <p>I use TortoiseSVN to access file based local repo. In all my commits an author is my Windows login name. Is it possible to use different name?</p>
<p>I know how to change author after commit but how to change before? Installing apache/svnserver is not an option. </p>
| [
{
"answer_id": 45668,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 0,
"selected": false,
"text": "<p>As far as I know, TortoiseSVN does not offer any way to do this.</p>\n\n<p>Presumably it's not seen as a big issue, since file based access is not practical for multi-user scenarios, and for single-user the author-name is of lesser importance.</p>\n\n<p>A possible workaround would be to create another Windows username with the author name you want and connect with this.</p>\n"
},
{
"answer_id": 45673,
"author": "Brock Boland",
"author_id": 2185,
"author_profile": "https://Stackoverflow.com/users/2185",
"pm_score": 0,
"selected": false,
"text": "<p>I've never hosted svn on a Windows machine, so this is a shot in the dark. You might be able to create a new Windows user and specify that user when browsing, checking out, committing, etc. Let's say you want to make changes as <code>msznajder</code>. Create a user with that name in Windows, then try browsing the repository using TortoiseSVN's Repo-browser and specify the username in the URL - something like <code>file:///msznajder@localhost/some/file/path</code>.</p>\n"
},
{
"answer_id": 242598,
"author": "JXG",
"author_id": 15456,
"author_profile": "https://Stackoverflow.com/users/15456",
"pm_score": 1,
"selected": false,
"text": "<p>Another possible workaround (but I am <strong>NOT</strong> advocating it) is to use a client-side hook script before commit, in order to change the username.</p>\n\n<p>Hook scripts are discussed in the Subversion book, and local hooks are discussed in \"Client Side Hook Scripts\" in TortoiseSVN help.</p>\n"
},
{
"answer_id": 265268,
"author": "Rômulo Ceccon",
"author_id": 23193,
"author_profile": "https://Stackoverflow.com/users/23193",
"pm_score": 5,
"selected": true,
"text": "<p>Yes, it's possible.</p>\n\n<p><em>TortoiseSVN</em> and the <a href=\"http://subversion.tigris.org/\" rel=\"noreferrer\"><em>svn</em></a> command line client share the same settings location in your profile folder. So you may simply checkout one version using <em>svn.exe</em>:</p>\n\n<pre><code>$ svn co --username different_user_name file:///C:/path/to/your/repo\n</code></pre>\n\n<p>... and Subversion will happily replace the associated username for that repository. New commits from TortoiseSVN will then always use that username, no matter with what program you make the new checkouts.</p>\n\n<p>The procedure should work with TortoiseSVN 1.5.5. If it doesn't, try emptying svn's authentication cache (<code>%APPDATA%\\Subversion\\auth\\svn.username</code>) first.</p>\n"
},
{
"answer_id": 779224,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 0,
"selected": false,
"text": "<p>I suggest setting a post-commit-hook (in your repo's hooks folder - just copy the post-commit-hook.tmpl to post-commit-hook.bat and empty it [1]</p>\n\n<p><code>svn propset svn:author --revprop -r HEAD <author> file:///<path-to-repo></code> [2]</p>\n\n<p>[1] provided SlikSvn or similar is installed, i.e. commandline svn access is possible)</p>\n\n<p>[2] (or .sh if on linux, with the #!/bin/bash preamble) with the same content </p>\n"
}
] | 2008/09/05 | [
"https://Stackoverflow.com/questions/45624",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/501/"
] | I use TortoiseSVN to access file based local repo. In all my commits an author is my Windows login name. Is it possible to use different name?
I know how to change author after commit but how to change before? Installing apache/svnserver is not an option. | Yes, it's possible.
*TortoiseSVN* and the [*svn*](http://subversion.tigris.org/) command line client share the same settings location in your profile folder. So you may simply checkout one version using *svn.exe*:
```
$ svn co --username different_user_name file:///C:/path/to/your/repo
```
... and Subversion will happily replace the associated username for that repository. New commits from TortoiseSVN will then always use that username, no matter with what program you make the new checkouts.
The procedure should work with TortoiseSVN 1.5.5. If it doesn't, try emptying svn's authentication cache (`%APPDATA%\Subversion\auth\svn.username`) first. |
45,626 | <p>I have a basic CRUD form that uses PageMethods to update the user details, however the Validators don't fire off, I think I need to manually initialize the validators and check whether the validation has passed in my javascript save method. Any ideas on how to do this?</p>
| [
{
"answer_id": 45892,
"author": "Sara Chipps",
"author_id": 4140,
"author_profile": "https://Stackoverflow.com/users/4140",
"pm_score": 0,
"selected": false,
"text": "<p>what are you using for development? VS 2008 supposedly has better JS debugging, haven't tried it yet. </p>\n\n<p>For Ajax you can use the Sys.Debug obj</p>\n"
},
{
"answer_id": 45897,
"author": "Dale Ragan",
"author_id": 1117,
"author_profile": "https://Stackoverflow.com/users/1117",
"pm_score": 0,
"selected": false,
"text": "<p>If you use <a href=\"http://www.mozilla.com/en-US/firefox/\" rel=\"nofollow noreferrer\">Firefox</a>, you can use the <a href=\"https://addons.mozilla.org/en-US/firefox/addon/1843\" rel=\"nofollow noreferrer\">FireBug</a> plugin. It has great <a href=\"http://getfirebug.com/js.html\" rel=\"nofollow noreferrer\">javascript debugging support</a>.</p>\n"
},
{
"answer_id": 49371,
"author": "Nicholas",
"author_id": 2808,
"author_profile": "https://Stackoverflow.com/users/2808",
"pm_score": 2,
"selected": true,
"text": "<p>Ok so I finally solved this: You need to call <code>Page_ClientValidate()</code> in your Save javascript method and If it returns true continue with the save, the <code>Page_ClientValidate()</code> initiates the client side validators, See code below:</p>\n\n<pre><code> function Save()\n {\n var clientValidationPassed =Page_ClientValidate();\n if(clientValidationPassed)\n {\n //Save Data\n PageMethods.SaveUser(UserName,Role,SaveCustomerRequestComplete, RequestError);\n $find('editPopupExtender').hide();\n }\n else\n {\n //Do Nothing as CLient Validation messages are now displayed\n }\n return false;\n }\n</code></pre>\n"
}
] | 2008/09/05 | [
"https://Stackoverflow.com/questions/45626",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2808/"
] | I have a basic CRUD form that uses PageMethods to update the user details, however the Validators don't fire off, I think I need to manually initialize the validators and check whether the validation has passed in my javascript save method. Any ideas on how to do this? | Ok so I finally solved this: You need to call `Page_ClientValidate()` in your Save javascript method and If it returns true continue with the save, the `Page_ClientValidate()` initiates the client side validators, See code below:
```
function Save()
{
var clientValidationPassed =Page_ClientValidate();
if(clientValidationPassed)
{
//Save Data
PageMethods.SaveUser(UserName,Role,SaveCustomerRequestComplete, RequestError);
$find('editPopupExtender').hide();
}
else
{
//Do Nothing as CLient Validation messages are now displayed
}
return false;
}
``` |
45,634 | <p>How do you rewrite this in Linq?</p>
<pre><code>SELECT Id, Name FROM TableA WHERE TableA.Id IN (SELECT xx from TableB INNER JOIN Table C....)
</code></pre>
<p>So in plain english, I want to select Id and Name from TableA where TableA's Id is in a result set from a second query.</p>
| [
{
"answer_id": 45648,
"author": "John Boker",
"author_id": 2847,
"author_profile": "https://Stackoverflow.com/users/2847",
"pm_score": 4,
"selected": true,
"text": "<pre><code>from a in TableA \nwhere (from b in TableB \n join c in TableC on b.id equals c.id\n where .. select b.id)\n.Contains(a.Id) \nselect new { a.Id, a.Name }\n</code></pre>\n"
},
{
"answer_id": 45649,
"author": "aku",
"author_id": 1196,
"author_profile": "https://Stackoverflow.com/users/1196",
"pm_score": 1,
"selected": false,
"text": "<p>There is no out of box support for IN in LINQ. You need to join 2 queries.</p>\n"
},
{
"answer_id": 86213,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 2,
"selected": false,
"text": "<p>LINQ supports IN in the form of contains. Think \"collection.Contains(id)\" instead of \"id IN (collection)\".</p>\n\n<pre><code>from a in TableA\nwhere (\n from b in TableB\n join c in TableC\n on b.id equals c.id\n select b.id\n).Contains(TableA.Id)\nselect new { a.Id, a.Name }\n</code></pre>\n\n<p>See also this blog <a href=\"http://blog.wekeroad.com/2008/02/27/creating-in-queries-with-linq-to-sql/\" rel=\"nofollow noreferrer\">post</a>.</p>\n"
}
] | 2008/09/05 | [
"https://Stackoverflow.com/questions/45634",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3047/"
] | How do you rewrite this in Linq?
```
SELECT Id, Name FROM TableA WHERE TableA.Id IN (SELECT xx from TableB INNER JOIN Table C....)
```
So in plain english, I want to select Id and Name from TableA where TableA's Id is in a result set from a second query. | ```
from a in TableA
where (from b in TableB
join c in TableC on b.id equals c.id
where .. select b.id)
.Contains(a.Id)
select new { a.Id, a.Name }
``` |
45,642 | <p>I was wondering if there is an open source library or algorithm that can expand a non-numeric range. For example, if you have <code>1A</code> to <code>9A</code> you should get </p>
<pre><code>1A, 2A, 3A, 4A, 5A, 6A, 7A, 8A, 9A.
</code></pre>
<p>I've tried Googling for this and the best I could come up with were Regex that would expand numerics with dashes (1-3 becoming 1,2,3).</p>
| [
{
"answer_id": 45701,
"author": "Gariig",
"author_id": 1210,
"author_profile": "https://Stackoverflow.com/users/1210",
"pm_score": 0,
"selected": false,
"text": "<p>I was trying to leave it somewhat open because the number of possibilities is staggering. I believe this one of those questions that could not be answered 100% here without going through a lot of technical detail about is considered a \"good\" or \"bad\" range. I'm just trying to find a jumping point for ideas on how other people have tackled this problem. I was hoping that someone wrote a blog post explaining how they went about it solving this problem or created a whole library to handle this.</p>\n"
},
{
"answer_id": 45748,
"author": "Ian",
"author_id": 4396,
"author_profile": "https://Stackoverflow.com/users/4396",
"pm_score": 0,
"selected": false,
"text": "<p>I would say the first step in the solution will be to define how characters and numbers interact and form a sequence. The given example isn't clear, as you would at least assume it to run 1A, 1B .... 8Y, 8Z, 9A - that's assuming your input is restricted to decimal followed by a single character.</p>\n\n<p>If you can define a continuous sequence for characters and decimals, then you it will simply be a matter of some recursion / looping to generate part of that sequence.</p>\n\n<p>For example, you could assume that each character in the input is one of (1-9A-Z), therefore you could easily make that continuous by grabbing the decimal ascii value of the alpha characters and subtracting 55, in effect giving you the range (1-35)</p>\n"
},
{
"answer_id": 47126,
"author": "Emperor XLII",
"author_id": 2495,
"author_profile": "https://Stackoverflow.com/users/2495",
"pm_score": 0,
"selected": false,
"text": "<p>If we assume that the start and end ranges will follow the same alternating pattern, and limit the range of digits to <code>0-9</code> and <code>A-Z</code>, we can think of each group of digits as a component in a multi-dimensonal coordinate. For example, <code>1A</code> would correspond to the two-dimensional coordinate <code>(1,A)</code> (which is what Excel uses to label its two-dimensional grid of rows and columns); whereas <code>AA1BB2</code> would be a four-dimensional coordinate <code>(AA,1,BB,2)</code>.</p>\n\n<p>Because each component is independent, to expand the range between two coordinates we just return all combinations of the expansion of each component. Below is a quick implementation I cooked up this afternoon. It works for an arbitrary number of alternations of normal and alphabetic numbers, and handles large alphabetic ranges (i.e. from <code>AB</code> to <code>CDE</code>, not just <code>AB</code> to <code>CD</code>).</p>\n\n<p><strong>Note:</strong> This is intended as a rough draft of an actual implementation (I'm taking off tomorrow, so it is even less polished than usual ;). All the usual caveats regarding error handling, robustness, (readability ;), etc, apply.</p>\n\n<pre><code>IEnumerable<string> ExpandRange( string start, string end ) {\n // Split coordinates into component parts.\n string[] startParts = GetRangeParts( start );\n string[] endParts = GetRangeParts( end );\n\n // Expand range between parts \n // (i.e. 1->3 becomes 1,2,3; A->C becomes A,B,C).\n int length = startParts.Length;\n int[] lengths = new int[length];\n string[][] expandedParts = new string[length][];\n for( int i = 0; i < length; ++i ) {\n expandedParts[i] = ExpandRangeParts( startParts[i], endParts[i] );\n lengths[i] = expandedParts[i].Length;\n }\n\n // Return all combinations of expanded parts.\n int[] indexes = new int[length];\n do {\n var sb = new StringBuilder( );\n for( int i = 0; i < length; ++i ) {\n int partIndex = indexes[i];\n sb.Append( expandedParts[i][partIndex] );\n }\n yield return sb.ToString( );\n } while( IncrementIndexes( indexes, lengths ) );\n}\n\nreadonly Regex RangeRegex = new Regex( \"([0-9]*)([A-Z]*)\" );\nstring[] GetRangeParts( string range ) {\n // Match all alternating digit-letter components of coordinate.\n var matches = RangeRegex.Matches( range );\n var parts =\n from match in matches.Cast<Match>( )\n from matchGroup in match.Groups.Cast<Group>( ).Skip( 1 )\n let value = matchGroup.Value\n where value.Length > 0\n select value;\n return parts.ToArray( );\n}\n\nstring[] ExpandRangeParts( string startPart, string endPart ) {\n int start, end;\n Func<int, string> toString;\n\n bool isNumeric = char.IsDigit( startPart, 0 );\n if( isNumeric ) {\n // Parse regular integers directly.\n start = int.Parse( startPart );\n end = int.Parse( endPart );\n toString = ( i ) => i.ToString( );\n }\n else {\n // Convert alphabetic numbers to integers for expansion,\n // then convert back for display.\n start = AlphaNumberToInt( startPart );\n end = AlphaNumberToInt( endPart );\n toString = IntToAlphaNumber;\n }\n\n int count = end - start + 1;\n return Enumerable.Range( start, count )\n .Select( toString )\n .Where( s => s.Length > 0 )\n .ToArray( );\n}\n\nbool IncrementIndexes( int[] indexes, int[] lengths ) {\n // Increment indexes from right to left (i.e. Arabic numeral order).\n bool carry = true;\n for( int i = lengths.Length; carry && i > 0; --i ) {\n int index = i - 1;\n int incrementedValue = (indexes[index] + 1) % lengths[index];\n indexes[index] = incrementedValue;\n carry = (incrementedValue == 0);\n }\n return !carry;\n}\n\n// Alphabetic numbers are 1-based (i.e. A = 1, AA = 11, etc, mod base-26).\nconst char AlphaDigitZero = (char)('A' - 1);\nconst int AlphaNumberBase = 'Z' - AlphaDigitZero + 1;\nint AlphaNumberToInt( string number ) {\n int sum = 0;\n int place = 1;\n foreach( char c in number.Cast<char>( ).Reverse( ) ) {\n int digit = c - AlphaDigitZero;\n sum += digit * place;\n place *= AlphaNumberBase;\n }\n return sum;\n}\n\nstring IntToAlphaNumber( int number ) {\n List<char> digits = new List<char>( );\n while( number > 0 ) {\n int digit = number % AlphaNumberBase;\n if( digit == 0 ) // Compensate for 1-based alphabetic numbers.\n return \"\";\n\n char c = (char)(AlphaDigitZero + digit);\n digits.Add( c );\n number /= AlphaNumberBase;\n }\n\n digits.Reverse( );\n return new string( digits.ToArray( ) );\n}\n</code></pre>\n"
},
{
"answer_id": 47373,
"author": "mweerden",
"author_id": 4285,
"author_profile": "https://Stackoverflow.com/users/4285",
"pm_score": 1,
"selected": false,
"text": "<p>As noted by others, it would be useful to be more specific. I don't think you can expect there to be a library that will generate ranges according to any arbitrary order on string you can come up with.</p>\n\n<p>If you can simply define what the successor of any given string is, then the solutions is quite easy. That is, if you have a successor function <code>S</code> on strings (e.g. with <code>S('3A') = '4A'</code>), then something like the following can be used:</p>\n\n<pre><code>s = initial_string\nwhile s != final_string do\n output s\n s = S(s)\noutput s\n</code></pre>\n\n<p>Something I have used in the past to generate all strings of a given length <code>l</code> and with given range <code>b</code> to <code>e</code> of characters, is the following piece of (pseudo-)code. It can be easily adapted to a wide range of variations.</p>\n\n<pre><code>// initialise s with b at every position\nfor i in [0..l) do\n s[i] = b\ndone = false\nwhile not done do\n output s\n j = 0\n // if s[j] is e, reset it to b and \"add carry\"\n while j < l and s[j] == e do\n s[j] = b\n j = j + 1\n if j == l then\n done = true\n if not done then\n s[j] = s[j] + 1\n</code></pre>\n\n<p>For example, to start at a specific string you need only the change the initialisation. To set the end you only need to change the behaviour for the inner while to separately handle position <code>l</code> (limiting to the character in the end string on that position and if reached decrementing <code>l</code>).</p>\n"
}
] | 2008/09/05 | [
"https://Stackoverflow.com/questions/45642",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1210/"
] | I was wondering if there is an open source library or algorithm that can expand a non-numeric range. For example, if you have `1A` to `9A` you should get
```
1A, 2A, 3A, 4A, 5A, 6A, 7A, 8A, 9A.
```
I've tried Googling for this and the best I could come up with were Regex that would expand numerics with dashes (1-3 becoming 1,2,3). | As noted by others, it would be useful to be more specific. I don't think you can expect there to be a library that will generate ranges according to any arbitrary order on string you can come up with.
If you can simply define what the successor of any given string is, then the solutions is quite easy. That is, if you have a successor function `S` on strings (e.g. with `S('3A') = '4A'`), then something like the following can be used:
```
s = initial_string
while s != final_string do
output s
s = S(s)
output s
```
Something I have used in the past to generate all strings of a given length `l` and with given range `b` to `e` of characters, is the following piece of (pseudo-)code. It can be easily adapted to a wide range of variations.
```
// initialise s with b at every position
for i in [0..l) do
s[i] = b
done = false
while not done do
output s
j = 0
// if s[j] is e, reset it to b and "add carry"
while j < l and s[j] == e do
s[j] = b
j = j + 1
if j == l then
done = true
if not done then
s[j] = s[j] + 1
```
For example, to start at a specific string you need only the change the initialisation. To set the end you only need to change the behaviour for the inner while to separately handle position `l` (limiting to the character in the end string on that position and if reached decrementing `l`). |
45,653 | <p>We use QuickBooks for financial management, and feed it from a variety of sources. I now need to hook it up to BizTalk, and I'd hate to reinvent the wheel. I've done searches, and as far as I can tell there's no QuickBooks adapter for BizTalk. Does anyone know of anything that'll do the job, preferably something that doesn't suck? </p>
<hr>
<p>Doesn't the QB SDK require that Quickbooks be running on the client machine? Is there any way around it?</p>
| [
{
"answer_id": 45735,
"author": "seanyboy",
"author_id": 1726,
"author_profile": "https://Stackoverflow.com/users/1726",
"pm_score": 2,
"selected": true,
"text": "<p>Quickbooks talks .NET quite easily. You'll need the QuickBooks SDK 7.0 and a copy of Visual Studio.NET, but after that it's very easy to do anything with Quickbooks. </p>\n\n<pre><code>Imports QBFC7Lib\n\nSub AttachToDB()\n If isAttachedtoQB Then Exit Sub\n\n Lasterror = \"Unknown QuickBooks Error\"\n Try\n QbSession = New QBSessionManager\n QbSession.OpenConnection(\"\", \"Your Company Name\")\n QbSession.BeginSession(\"\", ENOpenMode.omDontCare)\n MsgReq = QbSession.CreateMsgSetRequest(\"UK\", 6, 0)\n MsgReq.Attributes.OnError = ENRqOnError.roeStop\n\n Lasterror = \"\"\n isAttachedtoQB = True\n Catch e As Exception\n If Not QbSession Is Nothing Then\n QbSession.CloseConnection()\n QbSession = Nothing\n End If\n isAttachedtoQB = False\n Lasterror = \"QuickBooks Connection Error. - \" + e.Message + \".\"\n End Try\nEnd Sub\n</code></pre>\n\n<p>See <a href=\"http://developer.intuit.com/\" rel=\"nofollow noreferrer\">http://developer.intuit.com/</a> for more information. </p>\n"
},
{
"answer_id": 45915,
"author": "seanyboy",
"author_id": 1726,
"author_profile": "https://Stackoverflow.com/users/1726",
"pm_score": 0,
"selected": false,
"text": "<p>Unfortunately it does. It also asks you to authorise any application you've built. (at least once.) </p>\n\n<p>I don't know any way around it. </p>\n"
},
{
"answer_id": 67747,
"author": "Chris Romp",
"author_id": 10372,
"author_profile": "https://Stackoverflow.com/users/10372",
"pm_score": 1,
"selected": false,
"text": "<p>If you do build the integration code using .NET, you may want to consider leveraging the WCF Line-of-Business SDK:</p>\n\n<p><a href=\"http://www.microsoft.com/biztalk/technologies/wcflobadaptersdk.mspx\" rel=\"nofollow noreferrer\">http://www.microsoft.com/biztalk/technologies/wcflobadaptersdk.mspx</a></p>\n\n<p>It's not a BizTalk-only technology, despite its categorization. The SDK is designed to make it easier to create a WCF channel to a LOB application, which can be consumed from almost any other platform.</p>\n"
},
{
"answer_id": 337042,
"author": "Keith Palmer Jr.",
"author_id": 26133,
"author_profile": "https://Stackoverflow.com/users/26133",
"pm_score": 0,
"selected": false,
"text": "<p>The QB SDK <em>does not</em> require that QuickBooks be running on the client machine. It <em>does</em> require that QuickBooks is <em>installed</em> on the client machine. You can access QuickBooks company files even if QuickBooks is not running though. </p>\n\n<p>Have a look through the SDK docs. Additionally, when QuickBooks first prompts you to authorize the application, you need to make sure to tell it to allow access to the company file, even when QuickBooks isn't open/the company file isn't open. </p>\n"
}
] | 2008/09/05 | [
"https://Stackoverflow.com/questions/45653",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2757/"
] | We use QuickBooks for financial management, and feed it from a variety of sources. I now need to hook it up to BizTalk, and I'd hate to reinvent the wheel. I've done searches, and as far as I can tell there's no QuickBooks adapter for BizTalk. Does anyone know of anything that'll do the job, preferably something that doesn't suck?
---
Doesn't the QB SDK require that Quickbooks be running on the client machine? Is there any way around it? | Quickbooks talks .NET quite easily. You'll need the QuickBooks SDK 7.0 and a copy of Visual Studio.NET, but after that it's very easy to do anything with Quickbooks.
```
Imports QBFC7Lib
Sub AttachToDB()
If isAttachedtoQB Then Exit Sub
Lasterror = "Unknown QuickBooks Error"
Try
QbSession = New QBSessionManager
QbSession.OpenConnection("", "Your Company Name")
QbSession.BeginSession("", ENOpenMode.omDontCare)
MsgReq = QbSession.CreateMsgSetRequest("UK", 6, 0)
MsgReq.Attributes.OnError = ENRqOnError.roeStop
Lasterror = ""
isAttachedtoQB = True
Catch e As Exception
If Not QbSession Is Nothing Then
QbSession.CloseConnection()
QbSession = Nothing
End If
isAttachedtoQB = False
Lasterror = "QuickBooks Connection Error. - " + e.Message + "."
End Try
End Sub
```
See <http://developer.intuit.com/> for more information. |
45,658 | <p>I wrote an Active X plugin for IE7 which implements IObjectWithSite besides some other necessary interfaces (note no IOleClient). This interface is queried and called by IE7. During the SetSite() call I retrieve a pointer to IE7's site interface which I can use to retrieve the IHTMLDocument2 interface using the following approach:</p>
<pre><code>IUnknown *site = pUnkSite; /* retrieved from IE7 during SetSite() call */
IServiceProvider *sp = NULL;
IHTMLWindow2 *win = NULL;
IHTMLDocument2 *doc = NULL;
if(site) {
site->QueryInterface(IID_IServiceProvider, (void **)&sp);
if(sp) {
sp->QueryService(IID_IHTMLWindow2, IID_IHTMLWindow2, (void **)&win);
if(win) {
win->get_document(&doc);
}
}
}
if(doc) {
/* found */
}
</code></pre>
<p>I tried a similiar approach on PIE as well using the following code, however, even the IPIEHTMLWindow2 interface cannot be acquired, so I'm stuck:</p>
<pre><code>IUnknown *site = pUnkSite; /* retrieved from PIE during SetSite() call */
IPIEHTMLWindow2 *win = NULL;
IPIEHTMLDocument1 *tmp = NULL;
IPIEHTMLDocument2 *doc = NULL;
if(site) {
site->QueryInterface(__uuidof(*win), (void **)&win);
if(win) { /* never the case */
win->get_document(&tmp);
if(tmp) {
tmp->QueryInterface(__uuidof(*doc), (void **)&doc);
}
}
}
if(doc) {
/* found */
}
</code></pre>
<p>Using the IServiceProvider interface doesn't work either, so I already tested this.</p>
<p>Any ideas?</p>
| [
{
"answer_id": 63430,
"author": "gnobal",
"author_id": 7748,
"author_profile": "https://Stackoverflow.com/users/7748",
"pm_score": 3,
"selected": true,
"text": "<p>I found the following code in the Google Gears code, <a href=\"http://code.google.com/p/gears/source/browse/trunk/gears/base/ie/activex_utils.cc?r=2157\" rel=\"nofollow noreferrer\">here</a>. I copied the functions I think you need to here. The one you need is at the bottom (GetHtmlWindow2), but the other two are needed as well. Hopefully I didn't miss anything, but if I did the stuff you need is probably at the link.</p>\n\n<pre><code>#ifdef WINCE\n// We can't get IWebBrowser2 for WinCE.\n#else\nHRESULT ActiveXUtils::GetWebBrowser2(IUnknown *site, IWebBrowser2 **browser2) {\n CComQIPtr<IServiceProvider> service_provider = site;\n if (!service_provider) { return E_FAIL; }\n\n return service_provider->QueryService(SID_SWebBrowserApp,\n IID_IWebBrowser2,\n reinterpret_cast<void**>(browser2));\n}\n#endif\n\n\nHRESULT ActiveXUtils::GetHtmlDocument2(IUnknown *site,\n IHTMLDocument2 **document2) {\n HRESULT hr;\n\n#ifdef WINCE\n // Follow path Window2 -> Window -> Document -> Document2\n CComPtr<IPIEHTMLWindow2> window2;\n hr = GetHtmlWindow2(site, &window2);\n if (FAILED(hr) || !window2) { return false; }\n CComQIPtr<IPIEHTMLWindow> window = window2;\n CComPtr<IHTMLDocument> document;\n hr = window->get_document(&document);\n if (FAILED(hr) || !document) { return E_FAIL; }\n return document->QueryInterface(__uuidof(*document2),\n reinterpret_cast<void**>(document2));\n#else\n CComPtr<IWebBrowser2> web_browser2;\n hr = GetWebBrowser2(site, &web_browser2);\n if (FAILED(hr) || !web_browser2) { return E_FAIL; }\n\n CComPtr<IDispatch> doc_dispatch;\n hr = web_browser2->get_Document(&doc_dispatch);\n if (FAILED(hr) || !doc_dispatch) { return E_FAIL; }\n\n return doc_dispatch->QueryInterface(document2);\n#endif\n}\n\n\nHRESULT ActiveXUtils::GetHtmlWindow2(IUnknown *site,\n#ifdef WINCE\n IPIEHTMLWindow2 **window2) {\n // site is javascript IDispatch pointer.\n return site->QueryInterface(__uuidof(*window2),\n reinterpret_cast<void**>(window2));\n#else\n IHTMLWindow2 **window2) {\n CComPtr<IHTMLDocument2> html_document2;\n // To hook an event on a page's window object, follow the path\n // IWebBrowser2->document->parentWindow->IHTMLWindow2\n\n HRESULT hr = GetHtmlDocument2(site, &html_document2);\n if (FAILED(hr) || !html_document2) { return E_FAIL; }\n\n return html_document2->get_parentWindow(window2);\n#endif\n}\n</code></pre>\n"
},
{
"answer_id": 71281,
"author": "anselm",
"author_id": 4735,
"author_profile": "https://Stackoverflow.com/users/4735",
"pm_score": 2,
"selected": false,
"text": "<p>Well I was aware of the gears code already. The mechanism gears uses is based on a workaround through performing an explicit method call into the gears plugin from the gears loader to set the window object and use that as site interface instead of the IUnknown provided by IE Mobile in the SetSite call. Regarding to the gears code the Google engineers are aware of the same problem I'm asking and came up with this workaround I described.</p>\n\n<p>However, I believe there must be another more \"official\" way of dealing with this issue since explicitely setting the site on an Active X control/plugin isn't very great. I'm going to ask the MS IE Mobile team directly now and will keep you informed once I get a solution. It might be a bug in IE Mobile which is the most likely thing I can imagine of, but who knows...</p>\n\n<p>But thanks anyways for your response ;))</p>\n"
}
] | 2008/09/05 | [
"https://Stackoverflow.com/questions/45658",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4735/"
] | I wrote an Active X plugin for IE7 which implements IObjectWithSite besides some other necessary interfaces (note no IOleClient). This interface is queried and called by IE7. During the SetSite() call I retrieve a pointer to IE7's site interface which I can use to retrieve the IHTMLDocument2 interface using the following approach:
```
IUnknown *site = pUnkSite; /* retrieved from IE7 during SetSite() call */
IServiceProvider *sp = NULL;
IHTMLWindow2 *win = NULL;
IHTMLDocument2 *doc = NULL;
if(site) {
site->QueryInterface(IID_IServiceProvider, (void **)&sp);
if(sp) {
sp->QueryService(IID_IHTMLWindow2, IID_IHTMLWindow2, (void **)&win);
if(win) {
win->get_document(&doc);
}
}
}
if(doc) {
/* found */
}
```
I tried a similiar approach on PIE as well using the following code, however, even the IPIEHTMLWindow2 interface cannot be acquired, so I'm stuck:
```
IUnknown *site = pUnkSite; /* retrieved from PIE during SetSite() call */
IPIEHTMLWindow2 *win = NULL;
IPIEHTMLDocument1 *tmp = NULL;
IPIEHTMLDocument2 *doc = NULL;
if(site) {
site->QueryInterface(__uuidof(*win), (void **)&win);
if(win) { /* never the case */
win->get_document(&tmp);
if(tmp) {
tmp->QueryInterface(__uuidof(*doc), (void **)&doc);
}
}
}
if(doc) {
/* found */
}
```
Using the IServiceProvider interface doesn't work either, so I already tested this.
Any ideas? | I found the following code in the Google Gears code, [here](http://code.google.com/p/gears/source/browse/trunk/gears/base/ie/activex_utils.cc?r=2157). I copied the functions I think you need to here. The one you need is at the bottom (GetHtmlWindow2), but the other two are needed as well. Hopefully I didn't miss anything, but if I did the stuff you need is probably at the link.
```
#ifdef WINCE
// We can't get IWebBrowser2 for WinCE.
#else
HRESULT ActiveXUtils::GetWebBrowser2(IUnknown *site, IWebBrowser2 **browser2) {
CComQIPtr<IServiceProvider> service_provider = site;
if (!service_provider) { return E_FAIL; }
return service_provider->QueryService(SID_SWebBrowserApp,
IID_IWebBrowser2,
reinterpret_cast<void**>(browser2));
}
#endif
HRESULT ActiveXUtils::GetHtmlDocument2(IUnknown *site,
IHTMLDocument2 **document2) {
HRESULT hr;
#ifdef WINCE
// Follow path Window2 -> Window -> Document -> Document2
CComPtr<IPIEHTMLWindow2> window2;
hr = GetHtmlWindow2(site, &window2);
if (FAILED(hr) || !window2) { return false; }
CComQIPtr<IPIEHTMLWindow> window = window2;
CComPtr<IHTMLDocument> document;
hr = window->get_document(&document);
if (FAILED(hr) || !document) { return E_FAIL; }
return document->QueryInterface(__uuidof(*document2),
reinterpret_cast<void**>(document2));
#else
CComPtr<IWebBrowser2> web_browser2;
hr = GetWebBrowser2(site, &web_browser2);
if (FAILED(hr) || !web_browser2) { return E_FAIL; }
CComPtr<IDispatch> doc_dispatch;
hr = web_browser2->get_Document(&doc_dispatch);
if (FAILED(hr) || !doc_dispatch) { return E_FAIL; }
return doc_dispatch->QueryInterface(document2);
#endif
}
HRESULT ActiveXUtils::GetHtmlWindow2(IUnknown *site,
#ifdef WINCE
IPIEHTMLWindow2 **window2) {
// site is javascript IDispatch pointer.
return site->QueryInterface(__uuidof(*window2),
reinterpret_cast<void**>(window2));
#else
IHTMLWindow2 **window2) {
CComPtr<IHTMLDocument2> html_document2;
// To hook an event on a page's window object, follow the path
// IWebBrowser2->document->parentWindow->IHTMLWindow2
HRESULT hr = GetHtmlDocument2(site, &html_document2);
if (FAILED(hr) || !html_document2) { return E_FAIL; }
return html_document2->get_parentWindow(window2);
#endif
}
``` |
45,732 | <p>I have an object graph serialized to xaml. A rough sample of what it looks like is:</p>
<pre><code><MyObject xmlns.... >
<MyObject.TheCollection>
<PolymorphicObjectOne .../>
<HiImPolymorphic ... />
</MyObject.TheCollection>
</MyObject>
</code></pre>
<p>I want to use Linq to XML in order to extract the serialized objects within the TheCollection.</p>
<p><strong>Note</strong>: <code>MyObject</code> may be named differently at runtime; I'm interested in any object that implements the same interface, which has a public collection called <code>TheCollection</code> that contains types of <code>IPolymorphicLol</code>.</p>
<p>The only things I know at runtime are the depth at which I will find the collection and that the collection element is named ``*.TheCollection`. Everything else will change.</p>
<p>The xml will be retrieved from a database using Linq; if I could combine both queries so instead of getting the entire serialized graph and then extracting the collection objects I would just get back the collection that would be sweet.</p>
| [
{
"answer_id": 45745,
"author": "hakan",
"author_id": 3993,
"author_profile": "https://Stackoverflow.com/users/3993",
"pm_score": 1,
"selected": false,
"text": "<p>I am not exactly sure about it but I believe GacRemove should do the same thing as gacutil /u. So, it should be the path of your DLL. However it doesn't have to be the same DLL file. Copy of the original should suffice since what counts is the uniqueID of the DLL.</p>\n"
},
{
"answer_id": 45747,
"author": "Espo",
"author_id": 2257,
"author_profile": "https://Stackoverflow.com/users/2257",
"pm_score": 3,
"selected": true,
"text": "<p>I am using the <code>GacInstall</code> to publish my assemblies, however once installed into the gac, I sometimes delete my ‘temporary’ copy of the assemblies.</p>\n\n<p>And then, if I ever wanted to uninstall the assemblies from the gac I do not have the files at the original path. This is causing a problem since I cannot seem to get the <code>GacRemove</code> method to uninstall the assemblies unless I keep the original files.</p>\n\n<p>Conclusion: Yes, you need to specify the path to the original DLL. (And try to not move/delete it later). If you delete it, try to copy the file from the GAC to your original path and you should be able to uninstall it using <code>GacRemove</code>.</p>\n"
}
] | 2008/09/05 | [
"https://Stackoverflow.com/questions/45732",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] | I have an object graph serialized to xaml. A rough sample of what it looks like is:
```
<MyObject xmlns.... >
<MyObject.TheCollection>
<PolymorphicObjectOne .../>
<HiImPolymorphic ... />
</MyObject.TheCollection>
</MyObject>
```
I want to use Linq to XML in order to extract the serialized objects within the TheCollection.
**Note**: `MyObject` may be named differently at runtime; I'm interested in any object that implements the same interface, which has a public collection called `TheCollection` that contains types of `IPolymorphicLol`.
The only things I know at runtime are the depth at which I will find the collection and that the collection element is named ``\*.TheCollection`. Everything else will change.
The xml will be retrieved from a database using Linq; if I could combine both queries so instead of getting the entire serialized graph and then extracting the collection objects I would just get back the collection that would be sweet. | I am using the `GacInstall` to publish my assemblies, however once installed into the gac, I sometimes delete my ‘temporary’ copy of the assemblies.
And then, if I ever wanted to uninstall the assemblies from the gac I do not have the files at the original path. This is causing a problem since I cannot seem to get the `GacRemove` method to uninstall the assemblies unless I keep the original files.
Conclusion: Yes, you need to specify the path to the original DLL. (And try to not move/delete it later). If you delete it, try to copy the file from the GAC to your original path and you should be able to uninstall it using `GacRemove`. |
45,769 | <p>I'm curious about everyones practices when it comes to using or distributing libraries for an application that you write.</p>
<p>First of all, when developing your application do you link the debug or release version of the libraries? (For when you run your application in debug mode)</p>
<p>Then when you run your app in release mode just before deploying, which build of the libraries do you use?</p>
<p>How do you perform the switch between your debug and release version of the libraries? Do you do it manually, do you use macros, or whatever else is it that you do?</p>
| [
{
"answer_id": 46120,
"author": "Henk",
"author_id": 4613,
"author_profile": "https://Stackoverflow.com/users/4613",
"pm_score": 2,
"selected": false,
"text": "<p>I would first determine what requirements are needed from the library:</p>\n\n<ol>\n<li>Debug/Release</li>\n<li>Unicode support</li>\n<li>And so on..</li>\n</ol>\n\n<p>With that determined you can then create configurations for each combination required by yourself or other library users.</p>\n\n<p>When compiling and linking it is very important that you keep that libraries and executable consistent with respect to configurations used i.e. don't mix release & debug when linking.\nI know on the Windows/VS platform this can cause subtle memory issues if debug & release libs are mixed within an executable.</p>\n\n<p>As Brian has mentioned to Visual Studio it's best to use the Configuration Manager to setup how you want each configuration you require to be built.</p>\n\n<p>For example our projects require the following configurations to be available depending on the executable being built.</p>\n\n<ol>\n<li>Debug+Unicode</li>\n<li>Debug+ASCII</li>\n<li>Release+Unicode</li>\n<li>Release+ASCII</li>\n</ol>\n\n<p>The users of this particular project use the Configuration Manager to match their executable requirements with the project's available configurations.</p>\n\n<p>Regarding the use of macros, they are used extensively in implementing compile time decisions for requirements like if the debug or release version of a function is to be linked. If you're using VS you can view the pre-processor definitions attribute to see how the various macros are defined e.g. _DEBUG _RELEASE, this is how the configuration controls whats compiled.</p>\n\n<p>What platform are you using to compile/link your projects?</p>\n\n<p>EDIT: Expanding on your updated comment..</p>\n\n<p>If the <strong>Configuration Manager</strong> option is not available to you then I recommend using the following properties from the project:</p>\n\n<ul>\n<li><strong>Linker</strong>-><strong>Additional Library Directories</strong> or <strong>Linker</strong>-><strong>Input</strong></li>\n</ul>\n\n<p>Use the macro <code>$(ConfigurationName)</code> to link with the appropriate library configuration e.g. Debug/Release.</p>\n\n<pre><code>$(ProjectDir)\\..\\third-party-prj\\$(ConfigurationName)\\third-party.lib\n</code></pre>\n\n<ul>\n<li><strong>Build Events</strong> or <strong>Custom Build Step</strong> configuration property</li>\n</ul>\n\n<p>Execute a copy of the required library file(s) from the dependent project prior (or after) to the build occurring.</p>\n\n<pre><code>xcopy $(ProjectDir)\\..\\third-party-prj\\$(ConfigurationName)\\third-party.dll $(IntDir)\n</code></pre>\n\n<p>The macro <code>$(ProjectDir)</code> will be substituted for the current project's location and causes the operation to occur relative to the current project.\nThe macro <code>$(ConfigurationName)</code> will be substituted for the currently selected configuration (default is <code>Debug</code> or <code>Release</code>) which allows the correct items to be copied depending on what configuration is being built currently.</p>\n\n<p>If you use a regular naming convention for your project configurations it will help, as you can use the <code>$(ConfigurationName)</code> macro, otherwise you can simply use a fixed string.</p>\n"
},
{
"answer_id": 51725,
"author": "Dewm Solo",
"author_id": 4225,
"author_profile": "https://Stackoverflow.com/users/4225",
"pm_score": 0,
"selected": false,
"text": "<p>I use VS. The way that I do it is that the libraries I need through the references of the project. Which basically just says in what folder to look for a specific library at project load time. I develop my libraries to be as project independent or reusable as possible. Therefore they are all projects of their own. So of the libraries that I need for a specific project, I create a \"3rdParty\" or \"libs\" folder at the same level as my \"src\" folder in my svn folder tree. I tend to only use released libraries, but when I get some unknown issues and want to switch to debug, I manually copy a debug version of the files in the \"lib\" folder and reload the project.</p>\n\n<p>I am unsure wether I should be keeping both debug and released versions in my svn tree. Although since they are projects of their own, keeping them in the svn tree of another project doesn't right. They can be built again without an hitch at any moment.</p>\n\n<p>And then I wanted to find a way of making the switch more...hmmm...well basically automatic if you while, but that's not what I really mean. It just feels that switching the files manually between released and debug isn't right. Maybe I haven't found it yet, but what I would like is an option that would do like:\nFor library \"stack.dll\" look in \"......\\3rdParty\\\" for release and \"......\\3rdPartyD\\\" for debug.</p>\n\n<p>Anything that those something like I don't know. What do you suggest?\nRemember libraries are external projects. There the built files are totally elsewhere. In fact think of it as you have to check out another project, build it, and copy the built library if you want another copy. How would you set that up?</p>\n"
}
] | 2008/09/05 | [
"https://Stackoverflow.com/questions/45769",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4225/"
] | I'm curious about everyones practices when it comes to using or distributing libraries for an application that you write.
First of all, when developing your application do you link the debug or release version of the libraries? (For when you run your application in debug mode)
Then when you run your app in release mode just before deploying, which build of the libraries do you use?
How do you perform the switch between your debug and release version of the libraries? Do you do it manually, do you use macros, or whatever else is it that you do? | I would first determine what requirements are needed from the library:
1. Debug/Release
2. Unicode support
3. And so on..
With that determined you can then create configurations for each combination required by yourself or other library users.
When compiling and linking it is very important that you keep that libraries and executable consistent with respect to configurations used i.e. don't mix release & debug when linking.
I know on the Windows/VS platform this can cause subtle memory issues if debug & release libs are mixed within an executable.
As Brian has mentioned to Visual Studio it's best to use the Configuration Manager to setup how you want each configuration you require to be built.
For example our projects require the following configurations to be available depending on the executable being built.
1. Debug+Unicode
2. Debug+ASCII
3. Release+Unicode
4. Release+ASCII
The users of this particular project use the Configuration Manager to match their executable requirements with the project's available configurations.
Regarding the use of macros, they are used extensively in implementing compile time decisions for requirements like if the debug or release version of a function is to be linked. If you're using VS you can view the pre-processor definitions attribute to see how the various macros are defined e.g. \_DEBUG \_RELEASE, this is how the configuration controls whats compiled.
What platform are you using to compile/link your projects?
EDIT: Expanding on your updated comment..
If the **Configuration Manager** option is not available to you then I recommend using the following properties from the project:
* **Linker**->**Additional Library Directories** or **Linker**->**Input**
Use the macro `$(ConfigurationName)` to link with the appropriate library configuration e.g. Debug/Release.
```
$(ProjectDir)\..\third-party-prj\$(ConfigurationName)\third-party.lib
```
* **Build Events** or **Custom Build Step** configuration property
Execute a copy of the required library file(s) from the dependent project prior (or after) to the build occurring.
```
xcopy $(ProjectDir)\..\third-party-prj\$(ConfigurationName)\third-party.dll $(IntDir)
```
The macro `$(ProjectDir)` will be substituted for the current project's location and causes the operation to occur relative to the current project.
The macro `$(ConfigurationName)` will be substituted for the currently selected configuration (default is `Debug` or `Release`) which allows the correct items to be copied depending on what configuration is being built currently.
If you use a regular naming convention for your project configurations it will help, as you can use the `$(ConfigurationName)` macro, otherwise you can simply use a fixed string. |
45,779 | <p>How would you dynamically subscribe to a C# event so that given a Object instance and a String name containing the name of the event, you subscribe to that event and do something (write to the console for example) when that event has been fired?</p>
<p>It would seem using Reflection this isn't possible and I would like to avoid having to use Reflection.Emit if possible, as this currently (to me) seems like the only way of doing it.</p>
<p><strong>/EDIT:</strong> I do not know the signature of the delegate needed for the event, this is the core of the problem</p>
<p><strong>/EDIT 2:</strong> Although delegate contravariance seems like a good plan, I can not make the assumption necessary to use this solution</p>
| [
{
"answer_id": 45795,
"author": "aku",
"author_id": 1196,
"author_profile": "https://Stackoverflow.com/users/1196",
"pm_score": 0,
"selected": false,
"text": "<p>What you want can be achieved using dependency injection. For example <a href=\"http://msdn.microsoft.com/en-us/library/aa480450.aspx\" rel=\"nofollow noreferrer\">Microsoft Composite UI app block</a> does exactly what you described</p>\n"
},
{
"answer_id": 45797,
"author": "Nick Berardi",
"author_id": 17,
"author_profile": "https://Stackoverflow.com/users/17",
"pm_score": 2,
"selected": false,
"text": "<p>It is possible to subscribe to an event using Reflection</p>\n\n<pre><code>var o = new SomeObjectWithEvent;\no.GetType().GetEvent(\"SomeEvent\").AddEventHandler(...);\n</code></pre>\n\n<p><a href=\"http://msdn.microsoft.com/en-us/library/system.reflection.eventinfo.addeventhandler.aspx\" rel=\"nofollow noreferrer\">http://msdn.microsoft.com/en-us/library/system.reflection.eventinfo.addeventhandler.aspx</a></p>\n\n<p>Now here is going to be the problem that you are going to have to solve. The delegates required for each event handler will have different signatures. You are going to have to find away to create these methods dynamically, which probably means Reflection.Emit, or you are going to have to limit your self to a certain delegate so that you can handle it with compiled code.</p>\n\n<p>Hope this helps.</p>\n"
},
{
"answer_id": 45804,
"author": "Keith",
"author_id": 905,
"author_profile": "https://Stackoverflow.com/users/905",
"pm_score": -1,
"selected": false,
"text": "<p>Do you mean something like:</p>\n\n<pre><code>//reflect out the method to fire as a delegate\nEventHandler eventDelegate = \n ( EventHandler ) Delegate.CreateDelegate(\n typeof( EventHandler ), //type of event delegate\n objectWithEventSubscriber, //instance of the object with the matching method\n eventSubscriberMethodName, //the name of the method\n true );\n</code></pre>\n\n<p>This doesn't do the subscription, but will give to the method to call.</p>\n\n<p>Edit: </p>\n\n<p>Post was clarified after this answer, my example won't help if you don't know the type. </p>\n\n<p>However all events in .Net should follow the default event pattern, so as long as you've followed it this will work with the basic EventHandler.</p>\n"
},
{
"answer_id": 45806,
"author": "Erick Sgarbi",
"author_id": 4171,
"author_profile": "https://Stackoverflow.com/users/4171",
"pm_score": 2,
"selected": false,
"text": "<pre><code>public TestForm()\n{\n Button b = new Button();\n\n this.Controls.Add(b);\n\n MethodInfo method = typeof(TestForm).GetMethod(\"Clickbutton\",\n BindingFlags.NonPublic | BindingFlags.Instance);\n Type type = typeof(EventHandler);\n\n Delegate handler = Delegate.CreateDelegate(type, this, method);\n\n EventInfo eventInfo = cbo.GetType().GetEvent(\"Click\");\n\n eventInfo.AddEventHandler(b, handler);\n\n}\n\nvoid Clickbutton(object sender, System.EventArgs e)\n{\n // Code here\n}\n</code></pre>\n"
},
{
"answer_id": 45901,
"author": "Mark Cidade",
"author_id": 1659,
"author_profile": "https://Stackoverflow.com/users/1659",
"pm_score": 6,
"selected": true,
"text": "<p>You can compile expression trees to use void methods without any arguments as event handlers for events of any type. To accommodate other event handler types, you have to map the event handler's parameters to the events somehow. </p>\n\n<pre><code> using System;\n using System.Linq;\n using System.Linq.Expressions;\n using System.Reflection;\n\n class ExampleEventArgs : EventArgs\n {\n public int IntArg {get; set;}\n }\n\n class EventRaiser\n { \n public event EventHandler SomethingHappened;\n public event EventHandler<ExampleEventArgs> SomethingHappenedWithArg;\n\n public void RaiseEvents()\n {\n if (SomethingHappened!=null) SomethingHappened(this, EventArgs.Empty);\n\n if (SomethingHappenedWithArg!=null) \n {\n SomethingHappenedWithArg(this, new ExampleEventArgs{IntArg = 5});\n }\n }\n }\n\n class Handler\n { \n public void HandleEvent() { Console.WriteLine(\"Handler.HandleEvent() called.\");}\n public void HandleEventWithArg(int arg) { Console.WriteLine(\"Arg: {0}\",arg); }\n }\n\n static class EventProxy\n { \n //void delegates with no parameters\n static public Delegate Create(EventInfo evt, Action d)\n { \n var handlerType = evt.EventHandlerType;\n var eventParams = handlerType.GetMethod(\"Invoke\").GetParameters();\n\n //lambda: (object x0, EventArgs x1) => d()\n var parameters = eventParams.Select(p=>Expression.Parameter(p.ParameterType,\"x\"));\n var body = Expression.Call(Expression.Constant(d),d.GetType().GetMethod(\"Invoke\"));\n var lambda = Expression.Lambda(body,parameters.ToArray());\n return Delegate.CreateDelegate(handlerType, lambda.Compile(), \"Invoke\", false);\n }\n\n //void delegate with one parameter\n static public Delegate Create<T>(EventInfo evt, Action<T> d)\n {\n var handlerType = evt.EventHandlerType;\n var eventParams = handlerType.GetMethod(\"Invoke\").GetParameters();\n\n //lambda: (object x0, ExampleEventArgs x1) => d(x1.IntArg)\n var parameters = eventParams.Select(p=>Expression.Parameter(p.ParameterType,\"x\")).ToArray();\n var arg = getArgExpression(parameters[1], typeof(T));\n var body = Expression.Call(Expression.Constant(d),d.GetType().GetMethod(\"Invoke\"), arg);\n var lambda = Expression.Lambda(body,parameters);\n return Delegate.CreateDelegate(handlerType, lambda.Compile(), \"Invoke\", false);\n }\n\n //returns an expression that represents an argument to be passed to the delegate\n static Expression getArgExpression(ParameterExpression eventArgs, Type handlerArgType)\n {\n if (eventArgs.Type==typeof(ExampleEventArgs) && handlerArgType==typeof(int))\n {\n //\"x1.IntArg\"\n var memberInfo = eventArgs.Type.GetMember(\"IntArg\")[0];\n return Expression.MakeMemberAccess(eventArgs,memberInfo);\n }\n\n throw new NotSupportedException(eventArgs+\"->\"+handlerArgType);\n }\n }\n\n\n static class Test\n {\n public static void Main()\n { \n var raiser = new EventRaiser();\n var handler = new Handler();\n\n //void delegate with no parameters\n string eventName = \"SomethingHappened\";\n var eventinfo = raiser.GetType().GetEvent(eventName);\n eventinfo.AddEventHandler(raiser,EventProxy.Create(eventinfo,handler.HandleEvent));\n\n //void delegate with one parameter\n string eventName2 = \"SomethingHappenedWithArg\";\n var eventInfo2 = raiser.GetType().GetEvent(eventName2);\n eventInfo2.AddEventHandler(raiser,EventProxy.Create<int>(eventInfo2,handler.HandleEventWithArg));\n\n //or even just:\n eventinfo.AddEventHandler(raiser,EventProxy.Create(eventinfo,()=>Console.WriteLine(\"!\"))); \n eventInfo2.AddEventHandler(raiser,EventProxy.Create<int>(eventInfo2,i=>Console.WriteLine(i+\"!\")));\n\n raiser.RaiseEvents();\n }\n }\n</code></pre>\n"
},
{
"answer_id": 45913,
"author": "Matt Bishop",
"author_id": 4301,
"author_profile": "https://Stackoverflow.com/users/4301",
"pm_score": 3,
"selected": false,
"text": "<p>It's not a completely general solution, but if all your events are of the form \nvoid Foo(object o, T args) , where T derives from EventArgs, then you can use delegate contravariance to get away with it. Like this (where the signature of KeyDown is not the same as that of Click) :</p>\n\n<pre><code> public Form1()\n {\n Button b = new Button();\n TextBox tb = new TextBox();\n\n this.Controls.Add(b);\n this.Controls.Add(tb);\n WireUp(b, \"Click\", \"Clickbutton\");\n WireUp(tb, \"KeyDown\", \"Clickbutton\");\n }\n\n void WireUp(object o, string eventname, string methodname)\n {\n EventInfo ei = o.GetType().GetEvent(eventname);\n\n MethodInfo mi = this.GetType().GetMethod(methodname, BindingFlags.Public | BindingFlags.Instance | BindingFlags.NonPublic);\n\n Delegate del = Delegate.CreateDelegate(ei.EventHandlerType, this, mi);\n\n ei.AddEventHandler(o, del);\n\n }\n void Clickbutton(object sender, System.EventArgs e)\n {\n MessageBox.Show(\"hello!\");\n }\n</code></pre>\n"
},
{
"answer_id": 376958,
"author": "plaureano",
"author_id": 46265,
"author_profile": "https://Stackoverflow.com/users/46265",
"pm_score": 2,
"selected": false,
"text": "<p>Try LinFu--it has a universal event handler that lets you bind to any event at runtime. For example, here's you you can bind a handler to the Click event of a dynamic button:</p>\n\n<pre>\n// Note: The CustomDelegate signature is defined as:\n// public delegate object CustomDelegate(params object[] args);\nCustomDelegate handler = delegate\n {\n Console.WriteLine(\"Button Clicked!\");\n return null;\n };\n\nButton myButton = new Button();\n// Connect the handler to the event\nEventBinder.BindToEvent(\"Click\", myButton, handler);\n</pre>\n\n<p>LinFu lets you bind your handlers to any event, regardless of the delegate signature. Enjoy!</p>\n\n<p>You can find it here: \n<a href=\"http://www.codeproject.com/KB/cs/LinFuPart3.aspx\" rel=\"nofollow noreferrer\">http://www.codeproject.com/KB/cs/LinFuPart3.aspx</a></p>\n"
},
{
"answer_id": 2693383,
"author": "Tim Lloyd",
"author_id": 189516,
"author_profile": "https://Stackoverflow.com/users/189516",
"pm_score": 1,
"selected": false,
"text": "<p>I recently wrote a series of blog posts describing unit testing events, and one of the techniques I discuss describes dynamic event subscription. I used reflection and MSIL (code emitting) for the dynamic aspects, but this is all wrapped up nicely. Using the DynamicEvent class, events can be subscribed to dynamically like so:</p>\n\n<pre><code>EventPublisher publisher = new EventPublisher();\n\nforeach (EventInfo eventInfo in publisher.GetType().GetEvents())\n{\n DynamicEvent.Subscribe(eventInfo, publisher, (sender, e, eventName) =>\n {\n Console.WriteLine(\"Event raised: \" + eventName);\n });\n}\n</code></pre>\n\n<p>One of the features of the pattern I implemented was that it injects the event name into the call to the event handler so you know which event has been raised. Very useful for unit testing.</p>\n\n<p>The blog article is quite lengthy as it is describing an event unit testing technique, but full source code and tests are provided, and a detailed description of how dynamic event subscription was implemented is detailed in the last post.</p>\n\n<p><a href=\"http://gojisoft.com/blog/2010/04/22/event-sequence-unit-testing-part-1/\" rel=\"nofollow noreferrer\">http://gojisoft.com/blog/2010/04/22/event-sequence-unit-testing-part-1/</a> </p>\n"
},
{
"answer_id": 49780888,
"author": "Edward Brey",
"author_id": 145173,
"author_profile": "https://Stackoverflow.com/users/145173",
"pm_score": 0,
"selected": false,
"text": "<p>\nThis method adds to an event, a dynamic handler that calls a method <code>OnRaised</code>, passing the event parameters as an object array:</p>\n\n<pre class=\"lang-cs prettyprint-override\"><code>void Subscribe(object source, EventInfo ev)\n{\n var eventParams = ev.EventHandlerType.GetMethod(\"Invoke\").GetParameters().Select(p => Expression.Parameter(p.ParameterType)).ToArray();\n var eventHandler = Expression.Lambda(ev.EventHandlerType,\n Expression.Call(\n instance: Expression.Constant(this),\n method: typeof(EventSubscriber).GetMethod(nameof(OnRaised), BindingFlags.NonPublic | BindingFlags.Instance),\n arg0: Expression.Constant(ev.Name),\n arg1: Expression.NewArrayInit(typeof(object), eventParams.Select(p => Expression.Convert(p, typeof(object))))),\n eventParams);\n ev.AddEventHandler(source, eventHandler.Compile());\n}\n</code></pre>\n\n<p><code>OnRaised</code> has this signature:</p>\n\n<pre class=\"lang-cs prettyprint-override\"><code>void OnRaised(string name, object[] parameters);\n</code></pre>\n"
}
] | 2008/09/05 | [
"https://Stackoverflow.com/questions/45779",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1111/"
] | How would you dynamically subscribe to a C# event so that given a Object instance and a String name containing the name of the event, you subscribe to that event and do something (write to the console for example) when that event has been fired?
It would seem using Reflection this isn't possible and I would like to avoid having to use Reflection.Emit if possible, as this currently (to me) seems like the only way of doing it.
**/EDIT:** I do not know the signature of the delegate needed for the event, this is the core of the problem
**/EDIT 2:** Although delegate contravariance seems like a good plan, I can not make the assumption necessary to use this solution | You can compile expression trees to use void methods without any arguments as event handlers for events of any type. To accommodate other event handler types, you have to map the event handler's parameters to the events somehow.
```
using System;
using System.Linq;
using System.Linq.Expressions;
using System.Reflection;
class ExampleEventArgs : EventArgs
{
public int IntArg {get; set;}
}
class EventRaiser
{
public event EventHandler SomethingHappened;
public event EventHandler<ExampleEventArgs> SomethingHappenedWithArg;
public void RaiseEvents()
{
if (SomethingHappened!=null) SomethingHappened(this, EventArgs.Empty);
if (SomethingHappenedWithArg!=null)
{
SomethingHappenedWithArg(this, new ExampleEventArgs{IntArg = 5});
}
}
}
class Handler
{
public void HandleEvent() { Console.WriteLine("Handler.HandleEvent() called.");}
public void HandleEventWithArg(int arg) { Console.WriteLine("Arg: {0}",arg); }
}
static class EventProxy
{
//void delegates with no parameters
static public Delegate Create(EventInfo evt, Action d)
{
var handlerType = evt.EventHandlerType;
var eventParams = handlerType.GetMethod("Invoke").GetParameters();
//lambda: (object x0, EventArgs x1) => d()
var parameters = eventParams.Select(p=>Expression.Parameter(p.ParameterType,"x"));
var body = Expression.Call(Expression.Constant(d),d.GetType().GetMethod("Invoke"));
var lambda = Expression.Lambda(body,parameters.ToArray());
return Delegate.CreateDelegate(handlerType, lambda.Compile(), "Invoke", false);
}
//void delegate with one parameter
static public Delegate Create<T>(EventInfo evt, Action<T> d)
{
var handlerType = evt.EventHandlerType;
var eventParams = handlerType.GetMethod("Invoke").GetParameters();
//lambda: (object x0, ExampleEventArgs x1) => d(x1.IntArg)
var parameters = eventParams.Select(p=>Expression.Parameter(p.ParameterType,"x")).ToArray();
var arg = getArgExpression(parameters[1], typeof(T));
var body = Expression.Call(Expression.Constant(d),d.GetType().GetMethod("Invoke"), arg);
var lambda = Expression.Lambda(body,parameters);
return Delegate.CreateDelegate(handlerType, lambda.Compile(), "Invoke", false);
}
//returns an expression that represents an argument to be passed to the delegate
static Expression getArgExpression(ParameterExpression eventArgs, Type handlerArgType)
{
if (eventArgs.Type==typeof(ExampleEventArgs) && handlerArgType==typeof(int))
{
//"x1.IntArg"
var memberInfo = eventArgs.Type.GetMember("IntArg")[0];
return Expression.MakeMemberAccess(eventArgs,memberInfo);
}
throw new NotSupportedException(eventArgs+"->"+handlerArgType);
}
}
static class Test
{
public static void Main()
{
var raiser = new EventRaiser();
var handler = new Handler();
//void delegate with no parameters
string eventName = "SomethingHappened";
var eventinfo = raiser.GetType().GetEvent(eventName);
eventinfo.AddEventHandler(raiser,EventProxy.Create(eventinfo,handler.HandleEvent));
//void delegate with one parameter
string eventName2 = "SomethingHappenedWithArg";
var eventInfo2 = raiser.GetType().GetEvent(eventName2);
eventInfo2.AddEventHandler(raiser,EventProxy.Create<int>(eventInfo2,handler.HandleEventWithArg));
//or even just:
eventinfo.AddEventHandler(raiser,EventProxy.Create(eventinfo,()=>Console.WriteLine("!")));
eventInfo2.AddEventHandler(raiser,EventProxy.Create<int>(eventInfo2,i=>Console.WriteLine(i+"!")));
raiser.RaiseEvents();
}
}
``` |
45,783 | <p>My team is currently trying to automate the deployment of our .Net and PHP web applications. We want to streamline deployments, and to avoid the hassle and many of the headaches caused by doing it manually.</p>
<p>We require a solution that will enable us to:</p>
<pre><code>- Compile the application
- Version the application with the SVN version number
- Backup the existing site
- Deploy to a web farm
</code></pre>
<p>All our apps are source controlled using SVN and our .Net apps use CruiseControl.
We have been trying to use MSBuild and NAnt deployment scripts with limited success. We have also used Capistrano in the past, but wish to avoid using Ruby if possible.</p>
<p>Are there any other deployment tools out there that would help us?</p>
| [
{
"answer_id": 45799,
"author": "Jordi Bunster",
"author_id": 4272,
"author_profile": "https://Stackoverflow.com/users/4272",
"pm_score": 0,
"selected": false,
"text": "<p><a href=\"http://www.nongnu.org/fab/\" rel=\"nofollow noreferrer\">Fabric</a>. Seems small, simple, procedural. Written in Python, since Ruby is a no-no (why?).</p>\n"
},
{
"answer_id": 45809,
"author": "kemiller2002",
"author_id": 1942,
"author_profile": "https://Stackoverflow.com/users/1942",
"pm_score": 0,
"selected": false,
"text": "<p>Check out Setup Factory (from indigo rose). It's pretty robust in what it can do. It uses the Windows installer API. It can probably do what you need. </p>\n"
},
{
"answer_id": 45868,
"author": "jeremcc",
"author_id": 1436,
"author_profile": "https://Stackoverflow.com/users/1436",
"pm_score": 2,
"selected": false,
"text": "<p>I have used <a href=\"http://www.kinook.com/VisBuildPro/\" rel=\"nofollow noreferrer\">Visual Build Pro</a> for years, It's quite slick and easy to use and has many standard operations (like the ones you mentioned) built in.</p>\n"
},
{
"answer_id": 45997,
"author": "Gary Richardson",
"author_id": 2506,
"author_profile": "https://Stackoverflow.com/users/2506",
"pm_score": 2,
"selected": false,
"text": "<p>I use <a href=\"http://reductivelabs.com/trac/puppet/\" rel=\"nofollow noreferrer\">Puppet</a>, Makefiles to build RPMs and <a href=\"http://www.atlassian.com/software/bamboo/\" rel=\"nofollow noreferrer\">Bamboo</a> to do this for me. My system doesn't directly apply, and I'm not to familiar with the Windows world, but there are some transferable patterns.</p>\n\n<p>My make setup allows me to build RPM's for everything (php libs, php websites, perl modules, C apps, etc) that make up my app. This can be called manually, or through Bamboo. I transfer these RPM's into a yum repo and puppet handles making sure the latest (or correct) versions of software are installed in the cluster.</p>\n\n<p>Could you automate building software packages into MSI's? I think Puppet can manage installation of software packages and versions in Windows.</p>\n"
},
{
"answer_id": 56109,
"author": "Sam Wessel",
"author_id": 4734,
"author_profile": "https://Stackoverflow.com/users/4734",
"pm_score": 6,
"selected": true,
"text": "<p>Thank you all for your kind suggestions. We checked them all out, but after careful consideration we decided to roll our own with a combination of CruiseControl, NAnt, MSBuild and MSDeploy.</p>\n\n<p>This article has some great information:\n<a href=\"http://dougrohm.com/blog/post/2006/01/29/Integrating-MSBuild-with-CruiseControlNET.aspx\" rel=\"noreferrer\">Integrating MSBuild with CruiseControl.NET </a></p>\n\n<p>Here's roughly how our solution works:</p>\n\n<ul>\n<li>Developers build the 'debug' version of the app and run unit tests, then check in to SVN.</li>\n<li>CruiseControl sees the updates and calls our build script...\n\n<ul>\n<li>Runs any new migrations on the build database</li>\n<li>Replaces the config files with the build server config</li>\n<li>Builds the 'debug' configuration of the app</li>\n<li>Runs all unit and integration tests</li>\n<li>Builds the 'deploy' configuration of the app\n\n<ul>\n<li>Versions the DLLs with the current major/minor version and SVN revision, e.g. 1.2.0.423</li>\n<li>Moves this new build to a 'release' folder on our build server</li>\n<li>Removes unneeded files</li>\n</ul></li>\n<li>Updates IIS on the build server if required</li>\n</ul></li>\n</ul>\n\n<p>Then when we have verified everything is ready to go up to live/staging we run another script to:</p>\n\n<ul>\n<li>Run migrations on live/staging server</li>\n<li>MSDeploy: archive current live/staging site</li>\n<li>MSDeploy: sync site from build to live/staging</li>\n</ul>\n\n<p>It wasn't pretty getting to this stage, but it's mostly working like a charm now :D</p>\n\n<p>I'm going to try and keep this answer updated as we make changes to our process, as there seem to be several similar questions on SA now.</p>\n"
},
{
"answer_id": 70621,
"author": "Paul Shannon",
"author_id": 11503,
"author_profile": "https://Stackoverflow.com/users/11503",
"pm_score": 1,
"selected": false,
"text": "<p>Rather than using xcopy we managed to use the -source:dirpath command with UNC addresses to the servers with msdeploy. The key was the ignoreAcls=true and removing calls to username and password in the msdeploy string:</p>\n\n<pre><code>msdeploy -verb:sync -source:dirpath=\\\\build\\e$\\app -dest:dirpath=\\\\live\\d$\\app,ignoreAcls=true\n</code></pre>\n\n<p>The example deploys the site from our build server's E drive to the D drive on our live server. There are some security considerations with exposing shares or this level of disk access on a live server. We're currently looking into using a limited access shared folder.</p>\n\n<p>We then pipe this output to a log file which is then moved to the backup archive for reference. The log file records which files were moved and when.Continuing the example above with the output pipe command:</p>\n\n<pre><code>... > E:\\archive\\msdeploy.log\n</code></pre>\n"
},
{
"answer_id": 3125942,
"author": "S P",
"author_id": 359508,
"author_profile": "https://Stackoverflow.com/users/359508",
"pm_score": 2,
"selected": false,
"text": "<p>I use msdeploy for this. It works perfect. </p>\n\n<p>About Ant; for the .NET platform we have NAnt and you can use it in combination with MSDeploy; you have the possibility to call MSDeploy from your Nant-script. </p>\n\n<p>Edited:\nJust to make things clear; you can do everything with msdeploy. Using Nant is not a requirement. </p>\n"
},
{
"answer_id": 3125965,
"author": "pdr",
"author_id": 176703,
"author_profile": "https://Stackoverflow.com/users/176703",
"pm_score": 0,
"selected": false,
"text": "<p>The only reason Nant should exist is so that you have a framework similar to Ant in which we can write Tasks using the .NET set of languages. If you don't want to get a pure .NET developer to write custom Tasks, I can't see any reason you can't use Ant. Just because you write your application in a .NET language, doesn't mean you have to use a .NET build tool.</p>\n"
},
{
"answer_id": 3661674,
"author": "BozoJoe",
"author_id": 38461,
"author_profile": "https://Stackoverflow.com/users/38461",
"pm_score": 1,
"selected": false,
"text": "<p>No one mentioned Final Builder <a href=\"http://www.finalbuilder.com\" rel=\"nofollow noreferrer\">http://www.finalbuilder.com</a>. Its on par with Visual build Pro. Good GUI for creating automated build deployment harnesses</p>\n"
}
] | 2008/09/05 | [
"https://Stackoverflow.com/questions/45783",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4734/"
] | My team is currently trying to automate the deployment of our .Net and PHP web applications. We want to streamline deployments, and to avoid the hassle and many of the headaches caused by doing it manually.
We require a solution that will enable us to:
```
- Compile the application
- Version the application with the SVN version number
- Backup the existing site
- Deploy to a web farm
```
All our apps are source controlled using SVN and our .Net apps use CruiseControl.
We have been trying to use MSBuild and NAnt deployment scripts with limited success. We have also used Capistrano in the past, but wish to avoid using Ruby if possible.
Are there any other deployment tools out there that would help us? | Thank you all for your kind suggestions. We checked them all out, but after careful consideration we decided to roll our own with a combination of CruiseControl, NAnt, MSBuild and MSDeploy.
This article has some great information:
[Integrating MSBuild with CruiseControl.NET](http://dougrohm.com/blog/post/2006/01/29/Integrating-MSBuild-with-CruiseControlNET.aspx)
Here's roughly how our solution works:
* Developers build the 'debug' version of the app and run unit tests, then check in to SVN.
* CruiseControl sees the updates and calls our build script...
+ Runs any new migrations on the build database
+ Replaces the config files with the build server config
+ Builds the 'debug' configuration of the app
+ Runs all unit and integration tests
+ Builds the 'deploy' configuration of the app
- Versions the DLLs with the current major/minor version and SVN revision, e.g. 1.2.0.423
- Moves this new build to a 'release' folder on our build server
- Removes unneeded files
+ Updates IIS on the build server if required
Then when we have verified everything is ready to go up to live/staging we run another script to:
* Run migrations on live/staging server
* MSDeploy: archive current live/staging site
* MSDeploy: sync site from build to live/staging
It wasn't pretty getting to this stage, but it's mostly working like a charm now :D
I'm going to try and keep this answer updated as we make changes to our process, as there seem to be several similar questions on SA now. |
45,796 | <p>Our ASP.NET 3.5 website running on IIS 6 has two teams that are adding content: </p>
<ul>
<li>Development team adding code. </li>
<li>Business team adding simple web pages. </li>
</ul>
<p>For sanity and organization, we would like for the business team to add their web pages to a sub-folder in the project: </p>
<blockquote>
<p>Root: for pages of development team </p>
<p>Content: for pages of business team </p>
</blockquote>
<p><strong>But</strong> </p>
<p>We would like for users to be able to navigate to the business team content without having to append "Content" in their URLs, as described below:</p>
<blockquote>
<p><strong>Root</strong>: Default.aspx (<em>Available at: www.oursite.com/default.aspx</em>)</p>
<p><strong>Content</strong>: Popcorn.aspx (<em>Available at: www.oursite.com/popcorn.aspx</em>)</p>
</blockquote>
<p>Is there a way we can accomplish for making a config entry in an ISAPI rewrite tool for every one of these pages?</p>
| [
{
"answer_id": 45808,
"author": "Ben Scheirman",
"author_id": 3381,
"author_profile": "https://Stackoverflow.com/users/3381",
"pm_score": 2,
"selected": false,
"text": "<p>Since the extensions will be ASPX, ASP.NET will pick up the request... you can write an HttpModule that checks for pages that yield a 404 and then check the subfolder also.</p>\n\n<p>If you know that all pages with a certain format will be coming from that folder, then you can just rewrite the URL in ASP.NET (either in Global.asax or an HttpModule).</p>\n"
},
{
"answer_id": 45926,
"author": "Adam Cuzzort",
"author_id": 4760,
"author_profile": "https://Stackoverflow.com/users/4760",
"pm_score": 2,
"selected": true,
"text": "<p>I don't have any way to test this right now, but I think you can use the -f flag on RewriteCond to check if a file exists, in either directory.</p>\n\n<pre><code>RewriteCond %{REQUEST_FILENAME} -!f\nRewriteCond Content/%{REQUEST_FILENAME} -f\nRewriteRule (.*) Content/(.*)\n</code></pre>\n\n<p>Something like that might do what you're after, too.</p>\n"
}
] | 2008/09/05 | [
"https://Stackoverflow.com/questions/45796",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/308/"
] | Our ASP.NET 3.5 website running on IIS 6 has two teams that are adding content:
* Development team adding code.
* Business team adding simple web pages.
For sanity and organization, we would like for the business team to add their web pages to a sub-folder in the project:
>
> Root: for pages of development team
>
>
> Content: for pages of business team
>
>
>
**But**
We would like for users to be able to navigate to the business team content without having to append "Content" in their URLs, as described below:
>
> **Root**: Default.aspx (*Available at: www.oursite.com/default.aspx*)
>
>
> **Content**: Popcorn.aspx (*Available at: www.oursite.com/popcorn.aspx*)
>
>
>
Is there a way we can accomplish for making a config entry in an ISAPI rewrite tool for every one of these pages? | I don't have any way to test this right now, but I think you can use the -f flag on RewriteCond to check if a file exists, in either directory.
```
RewriteCond %{REQUEST_FILENAME} -!f
RewriteCond Content/%{REQUEST_FILENAME} -f
RewriteRule (.*) Content/(.*)
```
Something like that might do what you're after, too. |
45,803 | <ol>
<li>Video podcast</li>
<li>???</li>
<li>Audio only mp3 player</li>
</ol>
<p>I'm looking for somewhere which will extract audio from video, but instead of a single file, for an on going video podcast.</p>
<p>I would most like a website which would suck in the RSS and spit out an RSS (I'm thinking of something like Feedburner), though would settle for something on my own machine.</p>
<p>If it must be on my machine, it should be quick, transparent, and automatic when I download each episode. </p>
<p>What would you use?</p>
<p><b>Edit:</b> I'm on an Ubuntu 8.04 machine; so running ffmpeg is no problem; however, I'm looking for automation and feed awareness.</p>
<p>Here's my use case: I want to listen to <a href="http://video.google.com/videosearch?q=google+techtalks&so=1&output=rss" rel="nofollow noreferrer">lectures</a> at Google Video, or <a href="http://groups.csail.mit.edu/mac/classes/6.001/abelson-sussman-lectures/" rel="nofollow noreferrer">Structure and Interpretation of Computer Programs</a>. These videos come out fairly often, so anything that's needed to be done manually will also be done fairly often. </p>
<p>Here's one approach I'd thought of:</p>
<ul>
<li>download the RSS</li>
<li>parse the RSS for enclosures, </li>
<li>download the enclosures, keeping a track what has already been downloaded previously</li>
<li>transcode the files, but not the ones done already</li>
<li>reconstruct an RSS with the audio files, remembering to change the metadata.</li>
<li>schedule to be run periodically</li>
<li>point podcatcher at new RSS feed.</li>
</ul>
<p>I also liked the approach of gPodder of using a <a href="http://wiki.gpodder.org/wiki/Time_stretching#Using_the_post-download_script_hook" rel="nofollow noreferrer">post-download script</a>.</p>
<p>I wish the <a href="http://www.openp2p.com/pub/a/p2p/2003/01/07/lazyweb.html" rel="nofollow noreferrer">Lazy Web</a> still worked.</p>
| [
{
"answer_id": 45810,
"author": "Espo",
"author_id": 2257,
"author_profile": "https://Stackoverflow.com/users/2257",
"pm_score": 0,
"selected": false,
"text": "<p>How to extract audio from video to MP3:</p>\n\n<p><a href=\"http://www.dvdvideosoft.com/guides/dvd/extract-audio-from-video-to-mp3.htm\" rel=\"nofollow noreferrer\">http://www.dvdvideosoft.com/guides/dvd/extract-audio-from-video-to-mp3.htm</a></p>\n\n<p>How to Convert a Video Podcast to Audio Only:</p>\n\n<p><a href=\"http://www.legalandrew.com/2007/03/10/how-to-convert-a-video-podcast-to-audio-only/\" rel=\"nofollow noreferrer\">http://www.legalandrew.com/2007/03/10/how-to-convert-a-video-podcast-to-audio-only/</a></p>\n"
},
{
"answer_id": 45812,
"author": "Mike Wills",
"author_id": 2535,
"author_profile": "https://Stackoverflow.com/users/2535",
"pm_score": 0,
"selected": false,
"text": "<p>When you edit your video, doesn't your editor provide you an option to split out the audio?</p>\n"
},
{
"answer_id": 45814,
"author": "robsoft",
"author_id": 3897,
"author_profile": "https://Stackoverflow.com/users/3897",
"pm_score": 0,
"selected": false,
"text": "<p>What platform is your own machine? What format is the video podcast?</p>\n\n<p>You could possibly get <a href=\"http://handbrake.fr/?article=details\" rel=\"nofollow noreferrer\">Handbrake</a> to do this (Windows, Linux and Mac), I don't know if it's scriptable at all but I think it can be used to separate audio and video.</p>\n\n<p>edit: There <em>is</em> a commandline interface for Handbrake, but it appears I was <em>wrong</em> about it accepting non-DVD input. \nOn the Mac I'd probably rig up something with Applescript and QuickTime - what platform are you on?</p>\n"
},
{
"answer_id": 45823,
"author": "Tim Farley",
"author_id": 4425,
"author_profile": "https://Stackoverflow.com/users/4425",
"pm_score": 4,
"selected": true,
"text": "<p>You could automate this using the open source command line tool ffmpeg. Parse the RSS to get the video files, fetch them over the net if needed, then spit each one out to a command line like this:</p>\n\n<pre><code>ffmpeg -i episode1.mov -ab 128000 episode1.mp3\n</code></pre>\n\n<p>The -ab switch sets the output bit rate to 128 kbits/s on the audio file, adjust as needed. </p>\n\n<p>Once you have the audio files you can reconstruct the RSS feed to link to the audio files if so desired.</p>\n"
}
] | 2008/09/05 | [
"https://Stackoverflow.com/questions/45803",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4737/"
] | 1. Video podcast
2. ???
3. Audio only mp3 player
I'm looking for somewhere which will extract audio from video, but instead of a single file, for an on going video podcast.
I would most like a website which would suck in the RSS and spit out an RSS (I'm thinking of something like Feedburner), though would settle for something on my own machine.
If it must be on my machine, it should be quick, transparent, and automatic when I download each episode.
What would you use?
**Edit:** I'm on an Ubuntu 8.04 machine; so running ffmpeg is no problem; however, I'm looking for automation and feed awareness.
Here's my use case: I want to listen to [lectures](http://video.google.com/videosearch?q=google+techtalks&so=1&output=rss) at Google Video, or [Structure and Interpretation of Computer Programs](http://groups.csail.mit.edu/mac/classes/6.001/abelson-sussman-lectures/). These videos come out fairly often, so anything that's needed to be done manually will also be done fairly often.
Here's one approach I'd thought of:
* download the RSS
* parse the RSS for enclosures,
* download the enclosures, keeping a track what has already been downloaded previously
* transcode the files, but not the ones done already
* reconstruct an RSS with the audio files, remembering to change the metadata.
* schedule to be run periodically
* point podcatcher at new RSS feed.
I also liked the approach of gPodder of using a [post-download script](http://wiki.gpodder.org/wiki/Time_stretching#Using_the_post-download_script_hook).
I wish the [Lazy Web](http://www.openp2p.com/pub/a/p2p/2003/01/07/lazyweb.html) still worked. | You could automate this using the open source command line tool ffmpeg. Parse the RSS to get the video files, fetch them over the net if needed, then spit each one out to a command line like this:
```
ffmpeg -i episode1.mov -ab 128000 episode1.mp3
```
The -ab switch sets the output bit rate to 128 kbits/s on the audio file, adjust as needed.
Once you have the audio files you can reconstruct the RSS feed to link to the audio files if so desired. |
45,813 | <p>Is there a way with WPF to get an array of elements under the mouse on a MouseMove event?</p>
| [
{
"answer_id": 45817,
"author": "Espo",
"author_id": 2257,
"author_profile": "https://Stackoverflow.com/users/2257",
"pm_score": 2,
"selected": false,
"text": "<p>Can you use the <a href=\"http://msdn.microsoft.com/en-us/library/system.windows.media.visualtreehelper.hittest.aspx\" rel=\"nofollow noreferrer\">VisualTreeHelper.HitTest</a> ?</p>\n\n<p><a href=\"http://lukieb.blogspot.com/2008/07/visualtreehelperhittest.html\" rel=\"nofollow noreferrer\">http://lukieb.blogspot.com/2008/07/visualtreehelperhittest.html</a></p>\n"
},
{
"answer_id": 46920,
"author": "Andy",
"author_id": 3857,
"author_profile": "https://Stackoverflow.com/users/3857",
"pm_score": 6,
"selected": false,
"text": "<p>You can also try using the Mouse.DirectlyOver property to get the top-most element that is under the mouse.</p>\n"
},
{
"answer_id": 182363,
"author": "David Schmitt",
"author_id": 4918,
"author_profile": "https://Stackoverflow.com/users/4918",
"pm_score": 6,
"selected": true,
"text": "<p>From "<a href=\"https://web.archive.org/web/20081205070201/http://adamnathan.net/wpf/\" rel=\"nofollow noreferrer\">WPF Unleashed</a>", page 383:</p>\n<blockquote>\n<p>Visual hit testing can inform you\nabout <em>all</em> <code>Visual</code>s that intersect a\nlocation, [...] you must use [...] the\n<code>[VisualTreeHelper.]HitTest</code> method that accepts a\n<code>HitTestResultCallback</code> delegate. Before\nthis version of <code>HitTest</code> returns, the\ndelegate is invoked once for each\nrelevant <code>Visual</code>, starting from the\ntopmost and ending at the bottommost.</p>\n</blockquote>\n<p>The signature of such a callback is</p>\n<pre><code>HitTestResultBehavior Callback(HitTestResult result)\n</code></pre>\n<p>and it has to return <code>HitTestResultBehaviour.Continue</code> to receive further hits, as shown below (from the linked page on MSDN):</p>\n<pre><code>// Return the result of the hit test to the callback.\npublic HitTestResultBehavior MyHitTestResult(HitTestResult result)\n{\n // Add the hit test result to the list that will be processed after the enumeration.\n hitResultsList.Add(result.VisualHit);\n\n // Set the behavior to return visuals at all z-order levels.\n return HitTestResultBehavior.Continue;\n}\n</code></pre>\n<p>For further information, please consult the <a href=\"https://msdn.microsoft.com/en-us/library/ms608753(v=vs.110).aspx\" rel=\"nofollow noreferrer\">MSDN documentation for <code>VisualTreeHelper.HitTest</code></a>.</p>\n"
}
] | 2008/09/05 | [
"https://Stackoverflow.com/questions/45813",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3291/"
] | Is there a way with WPF to get an array of elements under the mouse on a MouseMove event? | From "[WPF Unleashed](https://web.archive.org/web/20081205070201/http://adamnathan.net/wpf/)", page 383:
>
> Visual hit testing can inform you
> about *all* `Visual`s that intersect a
> location, [...] you must use [...] the
> `[VisualTreeHelper.]HitTest` method that accepts a
> `HitTestResultCallback` delegate. Before
> this version of `HitTest` returns, the
> delegate is invoked once for each
> relevant `Visual`, starting from the
> topmost and ending at the bottommost.
>
>
>
The signature of such a callback is
```
HitTestResultBehavior Callback(HitTestResult result)
```
and it has to return `HitTestResultBehaviour.Continue` to receive further hits, as shown below (from the linked page on MSDN):
```
// Return the result of the hit test to the callback.
public HitTestResultBehavior MyHitTestResult(HitTestResult result)
{
// Add the hit test result to the list that will be processed after the enumeration.
hitResultsList.Add(result.VisualHit);
// Set the behavior to return visuals at all z-order levels.
return HitTestResultBehavior.Continue;
}
```
For further information, please consult the [MSDN documentation for `VisualTreeHelper.HitTest`](https://msdn.microsoft.com/en-us/library/ms608753(v=vs.110).aspx). |
45,824 | <p>I notice that StackOverflow has a views count for each question and that these view numbers are fairly low and accurate. </p>
<p>I have a similar thing on one of my sites. It basically logs a "hit" whenever the page is loaded in the backend code. Unfortunately it also does this for search engine hits giving bloated and inaccurate numbers.</p>
<p>I guess one way to not count a robot would be to do the view counting with an AJAX call once the page has loaded, but I'm sure there's other, better ways to ignore search engines in your hit counters whilst still letting them in to crawl your site. Do you know any?</p>
| [
{
"answer_id": 45825,
"author": "Espo",
"author_id": 2257,
"author_profile": "https://Stackoverflow.com/users/2257",
"pm_score": 0,
"selected": false,
"text": "<p>The reason Stack Overflow has accurate view counts is that it only count each view/user once.</p>\n\n<p>Third-party hit counter (and web statistics) application often filter out search engines and display them in a separate window/tab/section. </p>\n"
},
{
"answer_id": 45830,
"author": "Nick Berardi",
"author_id": 17,
"author_profile": "https://Stackoverflow.com/users/17",
"pm_score": 0,
"selected": false,
"text": "<p>You are either going to have to do what you said in your question with AJAX. Or exclude out User-Agent strings that are known search engines. The only sure way to stop bots are with AJAX.</p>\n"
},
{
"answer_id": 45835,
"author": "Matt Sheppard",
"author_id": 797,
"author_profile": "https://Stackoverflow.com/users/797",
"pm_score": 4,
"selected": true,
"text": "<p>An AJAX call will do it, but usually search engines will not load images, javascript or CSS files, so it may be easier to include one of those files in the page, and pass the URL of the page you want to log a request against as a parameter in the file request.</p>\n\n<p>For example, in the page...</p>\n\n<p><a href=\"http://www.example.com/example.html\" rel=\"noreferrer\">http://www.example.com/example.html</a></p>\n\n<p>You might include in the head section</p>\n\n<pre><code><link href=\"empty.css?log=example.html\" rel=\"stylesheet\" type=\"text/css\" />\n</code></pre>\n\n<p>And have your server side log the request, then return an empty css file. The same approach would apply to JavaScript or and image file, though in all cases you'll want to look carefully at what caching might take place.</p>\n\n<p>Another option would be to eliminate the search engines based on their <a href=\"http://en.wikipedia.org/wiki/User_agent\" rel=\"noreferrer\">user agent</a>. There's a big list of possible user agents at <a href=\"http://user-agents.org/\" rel=\"noreferrer\">http://user-agents.org/</a> to get you started. Of course, you could go the other way, and only count requests from things you know are web browsers (covering IE, Firefox, Safari, Opera and this newfangled Chrome thing would get you 99% of the way there).</p>\n\n<p>Even easier would be to use a log analytics tool like <a href=\"http://awstats.sourceforge.net/\" rel=\"noreferrer\">awstats</a> or a service like <a href=\"http://www.google.com/analytics/\" rel=\"noreferrer\">Google analytics</a>, both of which have already solved this problem.</p>\n"
},
{
"answer_id": 45844,
"author": "UnkwnTech",
"author_id": 115,
"author_profile": "https://Stackoverflow.com/users/115",
"pm_score": 1,
"selected": false,
"text": "<p>You don't really need to use AJAX, just use JavaScript to add an iFrame off screen. KEEP IT SIMPLE<br/></p>\n\n<pre><code><script type=\"javascript\">\ndocument.write('<iframe src=\"myLogScript.php\" style=\"visibility:hidden\" width=\"1\" height=\"1\" frameborder=\"0\">');\n</script>\n</code></pre>\n"
},
{
"answer_id": 45923,
"author": "Anders Sandvig",
"author_id": 1709,
"author_profile": "https://Stackoverflow.com/users/1709",
"pm_score": 2,
"selected": false,
"text": "<p>To solve this problem I implemented a simple filter that would look at the User-Agent header in the HTTP request and compare it to a list of known robots. </p>\n\n<p>I got the robot list from <a href=\"http://www.robotstxt.org/dbexport.html\" rel=\"nofollow noreferrer\">www.robotstxt.org</a>. It's downloadable in a simple text-format that can easily be parsed to auto-generate the \"blacklist\".</p>\n"
},
{
"answer_id": 61076,
"author": "TomG",
"author_id": 6315,
"author_profile": "https://Stackoverflow.com/users/6315",
"pm_score": 1,
"selected": false,
"text": "<p>An extension to Matt Sheppard's answer might be something like the following:</p>\n\n<pre><code> <script type=\"text/javascript\">\n var thePg=window.location.pathname;\n var theSite=window.location.hostname;\n var theImage=new Image;\n theImage.src=\"/test/hitcounter.php?pg=\" + thePg + \"?site=\" + theSite;\n </script>\n</code></pre>\n\n<p>which can be plugged into a page header or footer template without needing to substitute the page name server-side. Note that if you include the query string (window.location.search), a robust version of this should encode the string to prevent evildoers from crafting page requests that exploit vulnerabilities based on weird stuff in URLs. The nice thing about this vs. a regular <code><img></code> tag or <code><iframe></code> is that the user won't see a red x if there is a problem with the hitcounter script.\nIn some cases, it's also important to know the URL that was seen by the browser, before rewrites, etc. that happen server-side, and this give you that. If you want it both ways, then add another parameter server-side that inserts that version of the page name into the query string as well.</p>\n\n<p>An example of the log files from a test of this page:</p>\n\n<pre><code>10.1.1.17 - - [13/Sep/2008:22:21:00 -0400] \"GET /test/testpage.html HTTP/1.1\" 200 306 \"-\" \"Mozilla/5.0 (Windows; U; Windows NT 6.0; en-US; rv:1.8.1.16) Gecko/20080702 Firefox/2.0.0.16\"\n10.1.1.17 - - [13/Sep/2008:22:21:00 -0400] \"GET /test/hitcounter.php?pg=/test/testpage.html?site=www.home.***.com HTTP/1.1\" 301 - \"http://www.home.***.com/test/testpage.html\" \"Mozilla/5.0 (Windows; U; Windows NT 6.0; en-US; rv:1.8.1.16) Gecko/20080702 Firefox/2.0.0.16\"\n</code></pre>\n"
}
] | 2008/09/05 | [
"https://Stackoverflow.com/questions/45824",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3404/"
] | I notice that StackOverflow has a views count for each question and that these view numbers are fairly low and accurate.
I have a similar thing on one of my sites. It basically logs a "hit" whenever the page is loaded in the backend code. Unfortunately it also does this for search engine hits giving bloated and inaccurate numbers.
I guess one way to not count a robot would be to do the view counting with an AJAX call once the page has loaded, but I'm sure there's other, better ways to ignore search engines in your hit counters whilst still letting them in to crawl your site. Do you know any? | An AJAX call will do it, but usually search engines will not load images, javascript or CSS files, so it may be easier to include one of those files in the page, and pass the URL of the page you want to log a request against as a parameter in the file request.
For example, in the page...
<http://www.example.com/example.html>
You might include in the head section
```
<link href="empty.css?log=example.html" rel="stylesheet" type="text/css" />
```
And have your server side log the request, then return an empty css file. The same approach would apply to JavaScript or and image file, though in all cases you'll want to look carefully at what caching might take place.
Another option would be to eliminate the search engines based on their [user agent](http://en.wikipedia.org/wiki/User_agent). There's a big list of possible user agents at <http://user-agents.org/> to get you started. Of course, you could go the other way, and only count requests from things you know are web browsers (covering IE, Firefox, Safari, Opera and this newfangled Chrome thing would get you 99% of the way there).
Even easier would be to use a log analytics tool like [awstats](http://awstats.sourceforge.net/) or a service like [Google analytics](http://www.google.com/analytics/), both of which have already solved this problem. |
45,827 | <p>How do you automatically set the focus to a textbox when a web page loads?</p>
<p>Is there an HTML tag to do it or does it have to be done via Javascript?</p>
| [
{
"answer_id": 45833,
"author": "Espo",
"author_id": 2257,
"author_profile": "https://Stackoverflow.com/users/2257",
"pm_score": 4,
"selected": false,
"text": "<p>You need to use javascript:</p>\n\n<pre><code><BODY onLoad=\"document.getElementById('myButton').focus();\">\n</code></pre>\n\n<hr>\n\n<p>@Ben notes that you should not add event handlers like this. While that is another question, he recommends that you use this function:</p>\n\n<pre><code>function addLoadEvent(func) {\n var oldonload = window.onload;\n if (typeof window.onload != 'function') {\n window.onload = func;\n } else {\n window.onload = function() {\n if (oldonload) {\n oldonload();\n }\n func();\n }\n }\n}\n</code></pre>\n\n<p>And then put a call to addLoadEvent on your page and reference a function the sets the focus to you desired textbox.</p>\n"
},
{
"answer_id": 45843,
"author": "Joel Coehoorn",
"author_id": 3043,
"author_profile": "https://Stackoverflow.com/users/3043",
"pm_score": 3,
"selected": false,
"text": "<pre><code><html> \n<head> \n<script language=\"javascript\" type=\"text/javascript\"> \nfunction SetFocus(InputID) \n{ \n document.getElementById(InputID).focus(); \n} \n</script> \n</head> \n<body onload=\"SetFocus('Box2')\"> \n<input id=\"Box1\" size=\"30\" /><br/> \n<input id=\"Box2\" size=\"30\" /> \n</body> \n</html> \n</code></pre>\n"
},
{
"answer_id": 45863,
"author": "Ben Scheirman",
"author_id": 3381,
"author_profile": "https://Stackoverflow.com/users/3381",
"pm_score": 9,
"selected": true,
"text": "<p>If you're using jquery:</p>\n\n<pre><code>$(function() {\n $(\"#Box1\").focus();\n});\n</code></pre>\n\n<p>or prototype:</p>\n\n<pre><code>Event.observe(window, 'load', function() {\n $(\"Box1\").focus();\n});\n</code></pre>\n\n<p>or plain javascript:</p>\n\n<pre><code>window.onload = function() {\n document.getElementById(\"Box1\").focus();\n};\n</code></pre>\n\n<p>though keep in mind that this will replace other on load handlers, so look up addLoadEvent() in google for a safe way to append onload handlers rather than replacing.</p>\n"
},
{
"answer_id": 45887,
"author": "Jon",
"author_id": 4764,
"author_profile": "https://Stackoverflow.com/users/4764",
"pm_score": 4,
"selected": false,
"text": "<p>Using plain vanilla html and javascript</p>\n\n<pre><code><input type='text' id='txtMyInputBox' />\n\n\n<script language='javascript' type='text/javascript'>\nfunction SetFocus()\n{\n // safety check, make sure its a post 1999 browser\n if (!document.getElementById)\n {\n return;\n }\n\n var txtMyInputBoxElement = document.getElementById(\"txtMyInputBox\");\n\n if (txtMyInputBoxElement != null)\n {\n txtMyInputBoxElement.focus();\n }\n}\nSetFocus();\n</script>\n</code></pre>\n\n<p>For those out there using the .net framework and asp.net 2.0 or above, its trivial. If you are using older versions of the framework, you'd need to write some javascript similar to above.</p>\n\n<p>In your OnLoad handler (generally page_load if you are using the stock page template supplied with visual studio) you can use:</p>\n\n<p>C#</p>\n\n<pre><code>protected void PageLoad(object sender, EventArgs e)\n{\n Page.SetFocus(txtMyInputBox);\n}\n</code></pre>\n\n<p>VB.NET</p>\n\n<pre><code>Protected Sub PageLoad(sender as Object, e as EventArgs)\n\n Page.SetFocus(txtMyInputBox)\n\nEnd Sub\n</code></pre>\n\n<p>(* Note I removed the underscore character from the function name that is generally Page_Load since in a code block it refused to render properly! I could not see in the markup documentation how to get underscores to render unescaped.)</p>\n\n<p>Hope this helps.</p>\n"
},
{
"answer_id": 47470,
"author": "Vincent Robert",
"author_id": 268,
"author_profile": "https://Stackoverflow.com/users/268",
"pm_score": 3,
"selected": false,
"text": "<p>As a general advice, I would recommend not stealing the focus from the address bar. (<a href=\"http://www.codinghorror.com/blog/archives/001011.html\" rel=\"noreferrer\">Jeff already talked about that.</a>)</p>\n\n<p>Web page can take some time to load, which means that your focus change can occur some long time after the user typed the pae URL. Then he could have changed his mind and be back to url typing while you will be loading your page and stealing the focus to put it in your textbox.</p>\n\n<p>That's the one and only reason that made me remove Google as my start page.</p>\n\n<p>Of course, if you control the network (local network) or if the focus change is to solve an important usability issue, forget all I just said :)</p>\n"
},
{
"answer_id": 3043784,
"author": "dave1010",
"author_id": 315435,
"author_profile": "https://Stackoverflow.com/users/315435",
"pm_score": 7,
"selected": false,
"text": "<p>In HTML there's an <a href=\"http://www.whatwg.org/specs/web-apps/current-work/multipage/forms.html#autofocusing-a-form-control\" rel=\"noreferrer\"><code>autofocus</code> attribute</a> to all form fields. There's a good tutorial on it in <a href=\"http://diveintohtml5.info/forms.html#autofocus\" rel=\"noreferrer\">Dive Into HTML 5</a>. Unfortunately it's currently not <a href=\"http://www.wufoo.com/html5/attributes/02-autofocus.html\" rel=\"noreferrer\">supported</a> by IE versions less than 10.</p>\n\n<p>To use the HTML 5 attribute and fall back to a JS option:</p>\n\n<pre><code><input id=\"my-input\" autofocus=\"autofocus\" />\n<script>\n if (!(\"autofocus\" in document.createElement(\"input\"))) {\n document.getElementById(\"my-input\").focus();\n }\n</script>\n</code></pre>\n\n<p>No jQuery, onload or event handlers are required, because the JS is below the HTML element.</p>\n\n<p>Edit: another advantage is that it works with JavaScript off in some browsers and you can remove the JavaScript when you don't want to support older browsers.</p>\n\n<p>Edit 2: Firefox 4 now supports the <code>autofocus</code> attribute, just leaving IE without support.</p>\n"
},
{
"answer_id": 3316361,
"author": "revive",
"author_id": 225230,
"author_profile": "https://Stackoverflow.com/users/225230",
"pm_score": 3,
"selected": false,
"text": "<p>IMHO, the 'cleanest' way to select the First, visible, enabled text field on the page, is to use jQuery and do something like this:</p>\n\n<pre><code>$(document).ready(function() {\n $('input:text[value=\"\"]:visible:enabled:first').focus();\n});\n</code></pre>\n\n<p>Hope that helps...</p>\n\n<p>Thanks...</p>\n"
},
{
"answer_id": 7265423,
"author": "Amir Chatrbahr",
"author_id": 922713,
"author_profile": "https://Stackoverflow.com/users/922713",
"pm_score": 4,
"selected": false,
"text": "<p>You can do it easily by using jquery in this way:</p>\n\n<pre><code><script type=\"text/javascript\">\n\n $(document).ready(function () {\n $(\"#myTextBoxId\").focus();\n });\n\n</script>\n</code></pre>\n\n<p>by calling this function in <code>$(document).ready()</code>. </p>\n\n<p>It means this function will execute when the DOM is ready.</p>\n\n<p>For more information about the READY function, refer to : <a href=\"http://api.jquery.com/ready/\" rel=\"noreferrer\">http://api.jquery.com/ready/</a></p>\n"
},
{
"answer_id": 12821915,
"author": "srikanth",
"author_id": 1735238,
"author_profile": "https://Stackoverflow.com/users/1735238",
"pm_score": -1,
"selected": false,
"text": "<p>Use the below code. For me it is working</p>\n\n<pre><code>jQuery(\"[id$='hfSpecialty_ids']\").focus()\n</code></pre>\n"
},
{
"answer_id": 40920357,
"author": "Chris Moschini",
"author_id": 176877,
"author_profile": "https://Stackoverflow.com/users/176877",
"pm_score": 2,
"selected": false,
"text": "<p>I had a slightly different problem. I wanted <code>autofocus</code>, but, wanted the <code>placeholder</code> text to remain, cross-browser. Some browsers would hide the <code>placeholder</code> text as soon as the field focused, some would keep it. I had to either get placeholders staying cross-browser, which has weird side effects, or stop using <code>autofocus</code>.</p>\n\n<p>So I listened for the first key typed against the body tag, and redirected that key into the target input field. Then all the event handlers involved get killed off to keep things clean.</p>\n\n<pre><code>var urlInput = $('#Url');\n\nfunction bodyFirstKey(ev) {\n $('body').off('keydown', bodyFirstKey);\n urlInput.off('focus', urlInputFirstFocus);\n\n if (ev.target == document.body) {\n urlInput.focus();\n if (!ev.ctrlKey && !ev.metaKey && !ev.altKey) {\n urlInput.val(ev.key);\n return false;\n }\n }\n};\nfunction urlInputFirstFocus() {\n $('body').off('keydown', bodyFirstKey);\n urlInput.off('focus', urlInputFirstFocus);\n};\n\n$('body').keydown(bodyFirstKey);\nurlInput.focus(urlInputFirstFocus);\n</code></pre>\n\n<p><a href=\"https://jsfiddle.net/b9chris/qLrrb93w/\" rel=\"nofollow noreferrer\">https://jsfiddle.net/b9chris/qLrrb93w/</a></p>\n"
},
{
"answer_id": 40920516,
"author": "Andrew Morton",
"author_id": 1115360,
"author_profile": "https://Stackoverflow.com/users/1115360",
"pm_score": -1,
"selected": false,
"text": "<p>If you are using ASP.NET then you can use</p>\n\n<pre><code>yourControlName.Focus()\n</code></pre>\n\n<p>in the code on the server, which will add appropriate JavaScript into the page.</p>\n\n<p>Other server-side frameworks may have an equivalent method.</p>\n"
},
{
"answer_id": 41675311,
"author": "Arjun",
"author_id": 7409227,
"author_profile": "https://Stackoverflow.com/users/7409227",
"pm_score": 4,
"selected": false,
"text": "<p>Simply write autofocus in the textfield. This is simple and it works like this:</p>\n\n<pre><code> <input name=\"abc\" autofocus></input>\n</code></pre>\n\n<p>Hope this helps.</p>\n"
},
{
"answer_id": 58286168,
"author": "oscar castellon",
"author_id": 1283517,
"author_profile": "https://Stackoverflow.com/users/1283517",
"pm_score": 2,
"selected": false,
"text": "<p>It is possible to set <code>autofocus</code> on input elements</p>\n\n<pre><code><input type=\"text\" class=\"b_calle\" id=\"b_calle\" placeholder=\"Buscar por nombre de calle\" autofocus=\"autofocus\">\n</code></pre>\n"
},
{
"answer_id": 70608454,
"author": "tdahman1325",
"author_id": 11580142,
"author_profile": "https://Stackoverflow.com/users/11580142",
"pm_score": 0,
"selected": false,
"text": "<p>Adjusted my answer from Dave1010 above as JavaScript backup didn't work for me.</p>\n<pre><code><input type="text" id="my-input" />\n</code></pre>\n<p>And the Javascipt backup check:</p>\n<pre><code>if (!(document.getElementById("my-input").hasAttribute("autofocus"))) {\n document.getElementById("my-input").focus();\n}\n</code></pre>\n"
}
] | 2008/09/05 | [
"https://Stackoverflow.com/questions/45827",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/305/"
] | How do you automatically set the focus to a textbox when a web page loads?
Is there an HTML tag to do it or does it have to be done via Javascript? | If you're using jquery:
```
$(function() {
$("#Box1").focus();
});
```
or prototype:
```
Event.observe(window, 'load', function() {
$("Box1").focus();
});
```
or plain javascript:
```
window.onload = function() {
document.getElementById("Box1").focus();
};
```
though keep in mind that this will replace other on load handlers, so look up addLoadEvent() in google for a safe way to append onload handlers rather than replacing. |
45,861 | <p>I am using <a href="http://code.google.com/p/js2-mode/" rel="noreferrer">js2-mode</a> to edit Javascript in Emacs, but I can't seem to get it to stop using tabs instead of spaces for indentation. My other modes work fine, just having issues w/ js2.</p>
| [
{
"answer_id": 46174,
"author": "Peter S. Housel",
"author_id": 949,
"author_profile": "https://Stackoverflow.com/users/949",
"pm_score": 6,
"selected": true,
"text": "<p>Do you have</p>\n\n<pre>\n(setq-default indent-tabs-mode nil)\n</pre>\n\n<p>in your .emacs? It works fine for me in emacs 23.0.60.1 when I do that. js2-mode uses the standard emacs function indent-to, which respects indent-tabs-mode, to do its indenting.</p>\n"
},
{
"answer_id": 7957258,
"author": "john_fries",
"author_id": 998684,
"author_profile": "https://Stackoverflow.com/users/998684",
"pm_score": 3,
"selected": false,
"text": "<p>Add this to your <code>.emacs</code> file somewhere after you load js2 mode:</p>\n\n<pre><code>(setq js2-mode-hook\n '(lambda () (progn\n (set-variable 'indent-tabs-mode nil))))\n</code></pre>\n"
},
{
"answer_id": 30416044,
"author": "user1629060",
"author_id": 1629060,
"author_profile": "https://Stackoverflow.com/users/1629060",
"pm_score": 3,
"selected": false,
"text": "<p>On my copy of GNU Emacs 24.2.1, setting:</p>\n\n<pre><code>(setq-default indent-tabs-mode nil)\n</code></pre>\n\n<p>in .emacs is not sufficient for javascript mode, presumably because the setting is somehow being over-ridden in a per-buffer context. The following change is sufficient:</p>\n\n<pre><code>(custom-set-variables\n ;; custom-set-variables was added by Custom.\n ;; If you edit it by hand, you could mess it up, so be careful.\n ;; Your init file should contain only one such instance.\n ;; If there is more than one, they won't work right.\n '(indent-tabs-mode nil))\n</code></pre>\n"
}
] | 2008/09/05 | [
"https://Stackoverflow.com/questions/45861",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4748/"
] | I am using [js2-mode](http://code.google.com/p/js2-mode/) to edit Javascript in Emacs, but I can't seem to get it to stop using tabs instead of spaces for indentation. My other modes work fine, just having issues w/ js2. | Do you have
```
(setq-default indent-tabs-mode nil)
```
in your .emacs? It works fine for me in emacs 23.0.60.1 when I do that. js2-mode uses the standard emacs function indent-to, which respects indent-tabs-mode, to do its indenting. |
45,888 | <p>I have jQuery but I'm not sure if it has any built-in sorting helpers. I could make a 2d array of each item's <code>text</code>, <code>value</code>, and <code>selected</code> properties, but I don't think that javascript's built in <code>Array.sort()</code> would work correctly.</p>
| [
{
"answer_id": 45890,
"author": "travis",
"author_id": 1414,
"author_profile": "https://Stackoverflow.com/users/1414",
"pm_score": 3,
"selected": false,
"text": "<p>Well, in IE6 it seems to sort on the nested array's [0] item:</p>\n\n<pre><code>function sortSelect(selectToSort) {\n var arrOptions = [];\n\n for (var i = 0; i < selectToSort.options.length; i++) {\n arrOptions[i] = [];\n arrOptions[i][0] = selectToSort.options[i].value;\n arrOptions[i][1] = selectToSort.options[i].text;\n arrOptions[i][2] = selectToSort.options[i].selected;\n }\n\n arrOptions.sort();\n\n for (var i = 0; i < selectToSort.options.length; i++) {\n selectToSort.options[i].value = arrOptions[i][0];\n selectToSort.options[i].text = arrOptions[i][1];\n selectToSort.options[i].selected = arrOptions[i][2];\n }\n}\n</code></pre>\n\n<p>I'll see if this works in other browsers...</p>\n\n<p>Edit: it works in Firefox too, woo hoo!</p>\n\n<p>Is there an easier way than this though? is there some method built into javascript or jQuery that sorts selects that I am missing, or is this the best way?</p>\n"
},
{
"answer_id": 45971,
"author": "Shog9",
"author_id": 811,
"author_profile": "https://Stackoverflow.com/users/811",
"pm_score": 2,
"selected": false,
"text": "<p><code>Array.sort()</code> defaults to converting each element to a string, and comparing those values. So <code>[\"value\", \"text\", \"selected\"]</code> gets sorted as <code>\"value, text, selected\"</code>. Which will probably work fine, most of the time. </p>\n\n<p>If you do want to sort on value alone, or interpret value as a number, then you can pass a comparison function into sort():</p>\n\n<pre><code>arrOptions.sort(function(a,b) { return new Number(a[0]) - new Number(b[0]); });\n</code></pre>\n"
},
{
"answer_id": 45974,
"author": "bdukes",
"author_id": 2688,
"author_profile": "https://Stackoverflow.com/users/2688",
"pm_score": 3,
"selected": false,
"text": "<p>There's <a href=\"http://dev.jquery.com/ticket/255\" rel=\"noreferrer\">a closed jQuery ticket</a> for a sort that should work, but just wasn't included in the core.</p>\n\n<pre><code>jQuery.fn.sort = function() {\n return this.pushStack( [].sort.apply( this, arguments ), []);\n};\n</code></pre>\n\n<p>Referenced from <a href=\"http://groups.google.com/group/jquery-en/browse_thread/thread/e0d6c199552dd1f7/2f05ad6d400dd962?lnk=gst&q=array+sorting\" rel=\"noreferrer\">a Google Groups thread</a>, I think you just pass in a function that is used to sort, like so</p>\n\n<pre><code>function sortSelect(selectToSort) {\n jQuery(selectToSort.options).sort(function(a,b){ \n return a.value > b.value ? 1 : -1; \n });\n}\n</code></pre>\n\n<p>Hope it helps!</p>\n"
},
{
"answer_id": 1885355,
"author": "Mark",
"author_id": 3915,
"author_profile": "https://Stackoverflow.com/users/3915",
"pm_score": 8,
"selected": true,
"text": "<p>Extract options into a temporary array, sort, then rebuild the list:</p>\n\n<pre><code>var my_options = $(\"#my_select option\");\nvar selected = $(\"#my_select\").val();\n\nmy_options.sort(function(a,b) {\n if (a.text > b.text) return 1;\n if (a.text < b.text) return -1;\n return 0\n})\n\n$(\"#my_select\").empty().append( my_options );\n$(\"#my_select\").val(selected);\n</code></pre>\n\n<p><a href=\"https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Array/sort\" rel=\"noreferrer\" title=\"Mozilla's sort documentation\">Mozilla's sort documentation</a> (specifically the compareFunction) and <a href=\"http://en.wikipedia.org/wiki/Sorting_algorithm\" rel=\"noreferrer\">Wikipedia's Sorting Algorithm page</a> are relevant.</p>\n\n<p>If you want to make the sort case insensitive, replace <code>text</code> with <code>text.toLowerCase()</code></p>\n\n<p>The sort function shown above illustrates how to sort. Sorting non-english languages accurately can be complex (see the <a href=\"http://www.unicode.org/reports/tr10/\" rel=\"noreferrer\">unicode collation algorithm</a>). Using <a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/localeCompare\" rel=\"noreferrer\">localeCompare</a> in the sort function is a good solution, eg:</p>\n\n<pre><code>my_options.sort(function(a,b) {\n return a.text.localeCompare(b.text);\n});\n</code></pre>\n"
},
{
"answer_id": 4745818,
"author": "Tom Maeckelberghe",
"author_id": 1421542,
"author_profile": "https://Stackoverflow.com/users/1421542",
"pm_score": 4,
"selected": false,
"text": "<p>I've just wrapped Mark's idea in a jquery function</p>\n\n<pre><code>$('#your_select_box').sort_select_box();\n</code></pre>\n\n<p>JQuery function: </p>\n\n<pre><code>$.fn.sort_select_box = function(){\n var my_options = $(\"#\" + this.attr('id') + ' option');\n my_options.sort(function(a,b) {\n if (a.text > b.text) return 1;\n else if (a.text < b.text) return -1;\n else return 0\n })\n return my_options;\n}\n</code></pre>\n"
},
{
"answer_id": 5432746,
"author": "JaredC",
"author_id": 339532,
"author_profile": "https://Stackoverflow.com/users/339532",
"pm_score": 4,
"selected": false,
"text": "<p>Modified Tom's answer above slightly so that it actually modifies the contents of the select box to be sorted, rather than just returning the sorted elements.</p>\n\n<pre><code>$('#your_select_box').sort_select_box();\n</code></pre>\n\n<p>jQuery function:</p>\n\n<pre><code>$.fn.sort_select_box = function(){\n // Get options from select box\n var my_options = $(\"#\" + this.attr('id') + ' option');\n // sort alphabetically\n my_options.sort(function(a,b) {\n if (a.text > b.text) return 1;\n else if (a.text < b.text) return -1;\n else return 0\n })\n //replace with sorted my_options;\n $(this).empty().append( my_options );\n\n // clearing any selections\n $(\"#\"+this.attr('id')+\" option\").attr('selected', false);\n}\n</code></pre>\n"
},
{
"answer_id": 7236274,
"author": "João",
"author_id": 711756,
"author_profile": "https://Stackoverflow.com/users/711756",
"pm_score": 1,
"selected": false,
"text": "<p>Remember: if you want to use context selector, just concatenate the ID will not work</p>\n\n<pre><code>$.fn.sort_select_box = function(){\n var my_options = $(\"option\", $(this));\n my_options.sort(function(a,b) {\n if (a.text > b.text) return 1;\n else if (a.text < b.text) return -1;\n else return 0\n });\n $(this).empty().append(my_options);\n}\n\n// Usando:\n$(\"select#ProdutoFornecedorId\", $($context)).sort_select_box();\n</code></pre>\n"
},
{
"answer_id": 11196096,
"author": "Juan Perez",
"author_id": 1480913,
"author_profile": "https://Stackoverflow.com/users/1480913",
"pm_score": 2,
"selected": false,
"text": "<p>This is a better solution.\nDeclare a global function to JQuery</p>\n\n<pre><code>$.fn.sortSelect = function() {\n var op = this.children(\"option\");\n op.sort(function(a, b) {\n return a.text > b.text ? 1 : -1;\n })\n return this.empty().append(op);\n}\n</code></pre>\n\n<p>And call the function from the code.</p>\n\n<pre><code>$(\"#my_select\").sortSelect();\n</code></pre>\n"
},
{
"answer_id": 12307006,
"author": "Tom Pietrosanti",
"author_id": 412074,
"author_profile": "https://Stackoverflow.com/users/412074",
"pm_score": 4,
"selected": false,
"text": "<p>The solution I mentioned in my comment to @Juan Perez</p>\n\n<pre><code>$.fn.sortOptions = function(){\n $(this).each(function(){\n var op = $(this).children(\"option\");\n op.sort(function(a, b) {\n return a.text > b.text ? 1 : -1;\n })\n return $(this).empty().append(op);\n });\n}\n</code></pre>\n\n<p>Usage:</p>\n\n<pre><code>$(\"select\").sortOptions();\n</code></pre>\n\n<p>This can still be improved on, but I didn't need to add any more bells or whistles :)</p>\n"
},
{
"answer_id": 59665960,
"author": "Adambean",
"author_id": 1372355,
"author_profile": "https://Stackoverflow.com/users/1372355",
"pm_score": 1,
"selected": false,
"text": "<p>A bit late but for what it's worth I've implemented a more complex function you can include generically. It has a few options for varied output. It can also recurse into <code><OPTGROUP></code> tags based on their label.</p>\n\n<pre><code>$.fn.sortSelect = function(options){\n\n const OPTIONS_DEFAULT = {\n recursive: true, // Recurse into <optgroup>\n reverse: false, // Reverse order\n useValues: false, // Use values instead of text for <option> (<optgruop> is always label based)\n blankFirst: true, // Force placeholder <option> with empty value first, ignores reverse\n }\n\n if (typeof options != \"object\" || null === options) {\n options = OPTIONS_DEFAULT;\n }\n\n var sortOptions = function($root, $node, options){\n\n if ($node.length != 1) {\n return false;\n }\n\n if ($node[0].tagName != \"SELECT\" && $node[0].tagName != \"OPTGROUP\") {\n return false;\n }\n\n if (options.recursive) {\n $node.children('optgroup').each(function(k, v){\n return sortOptions($root, $(v), options);\n });\n }\n\n var $options = $node.children('option, optgroup');\n var $optionsSorted = $options.sort(function(a, b){\n\n if (options.blankFirst) {\n if (a.tagName == \"OPTION\" && a.value == \"\") {\n return -1;\n }\n\n if (b.tagName == \"OPTION\" && b.value == \"\") {\n return 1;\n }\n }\n\n var textA = (a.tagName == \"OPTION\" ? (options.useValues ? a.value : a.text) : a.label);\n var textB = (b.tagName == \"OPTION\" ? (options.useValues ? a.value : b.text) : b.label);\n\n if (textA > textB) {\n return options.reverse ? -1 : 1;\n }\n\n if (textA < textB) {\n return options.reverse ? 1 : -1;\n }\n\n return 0;\n\n });\n\n $options.remove();\n $optionsSorted.appendTo($node);\n\n return true;\n\n };\n\n var selected = $(this).val();\n var sorted = sortOptions($(this), $(this), {...OPTIONS_DEFAULT, ...options});\n $(this).val(selected);\n\n return sorted;\n\n};\n</code></pre>\n\n<p>You can then call the <code>sortSelect()</code> function on any <code><SELECT></code> tag, or just a single <code><OPTGROUP></code> to only sort a group's options.</p>\n\n<p>Example:</p>\n\n<pre><code>$('select').sortSelect();\n</code></pre>\n\n<p>Reverse order using the \"reverse\" option:</p>\n\n<pre><code>$('select').sortSelect({\n reverse: true\n});\n</code></pre>\n\n<p>You could apply this to all selects automatically, perhaps only if they include an important class (e.g. \"js-sort\") with this:</p>\n\n<pre><code>$('select.js-sort').each(function(k, v){\n $(v).sortSelect();\n});\n</code></pre>\n"
},
{
"answer_id": 68092097,
"author": "CARLOS AGUIRRE",
"author_id": 10980978,
"author_profile": "https://Stackoverflow.com/users/10980978",
"pm_score": 0,
"selected": false,
"text": "<p>Seems jquery still is not particularly helpful enough for sorting options in a html select element.\nHere is some plain-plain javascript code for sorting options:</p>\n<p><div class=\"snippet\" data-lang=\"js\" data-hide=\"false\" data-console=\"true\" data-babel=\"false\">\r\n<div class=\"snippet-code\">\r\n<pre class=\"snippet-code-js lang-js prettyprint-override\"><code>function sortOptionsByText(a,b) {\n // I keep an empty value option on top, b.value comparison to 0 might not be necessary if empty value is always on top...\n if (a.value.length==0 || (b.value.length>0 && a.text <= b.text)) return -1; // no sort: a, b\n return 1; // sort switches places: b, a\n}\nfunction sortOptionsByValue(a,b) {\n if (a.value <= b.value) return -1; // a, b\n return 1; // b, a\n}\nfunction clearChildren(elem) {\n if (elem) {\n while (elem.firstChild) {\n elem.removeChild(elem.firstChild);\n }\n }\n}\nfunction sortSelectElem(sel,byText) {\n const val=sel.value;\n const tmp=[...sel.options];\n tmp.sort(byText?sortOptionsByText:sortOptionsByValue);\n clearChildren(sel);\n sel.append(...tmp);\n sel.value=val;\n}</code></pre>\r\n<pre class=\"snippet-code-html lang-html prettyprint-override\"><code>RACE: <select id=\"list\" size=\"6\">\n <option value=\"\">--PICK ONE--</option>\n <option value=\"1\">HUMANOID</option>\n <option value=\"2\">AMPHIBIAN</option>\n <option value=\"3\">REPTILE</option>\n <option value=\"4\">INSECTOID</option>\n</select><br>\n<button type=\"button\" onclick=\"sortSelectElem(document.getElementById('list'));\">SORT LIST BY VALUE</button><br>\n<button type=\"button\" onclick=\"sortSelectElem(document.getElementById('list'),true);\">SORT LIST BY TEXT</button></code></pre>\r\n</div>\r\n</div>\r\n</p>\n"
},
{
"answer_id": 69577409,
"author": "lisandro",
"author_id": 2363940,
"author_profile": "https://Stackoverflow.com/users/2363940",
"pm_score": 0,
"selected": false,
"text": "<p>With jquery this worked for me in Chrome in order to sort a select made from database unsorted elements.</p>\n<pre><code>$(document).ready(function(){\n \n var $list = $("#my_select");\n var selected = $("#my_select").val(); //save selected value\n \n $list.children().detach().sort(function(a, b) {\n return $(a).text().localeCompare($(b).text());\n }).appendTo($list); //do the sorting locale for latin chars\n \n $("#my_select").val(selected); //select previous selected value\n\n});\n</code></pre>\n"
}
] | 2008/09/05 | [
"https://Stackoverflow.com/questions/45888",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1414/"
] | I have jQuery but I'm not sure if it has any built-in sorting helpers. I could make a 2d array of each item's `text`, `value`, and `selected` properties, but I don't think that javascript's built in `Array.sort()` would work correctly. | Extract options into a temporary array, sort, then rebuild the list:
```
var my_options = $("#my_select option");
var selected = $("#my_select").val();
my_options.sort(function(a,b) {
if (a.text > b.text) return 1;
if (a.text < b.text) return -1;
return 0
})
$("#my_select").empty().append( my_options );
$("#my_select").val(selected);
```
[Mozilla's sort documentation](https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Array/sort "Mozilla's sort documentation") (specifically the compareFunction) and [Wikipedia's Sorting Algorithm page](http://en.wikipedia.org/wiki/Sorting_algorithm) are relevant.
If you want to make the sort case insensitive, replace `text` with `text.toLowerCase()`
The sort function shown above illustrates how to sort. Sorting non-english languages accurately can be complex (see the [unicode collation algorithm](http://www.unicode.org/reports/tr10/)). Using [localeCompare](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/localeCompare) in the sort function is a good solution, eg:
```
my_options.sort(function(a,b) {
return a.text.localeCompare(b.text);
});
``` |
45,898 | <p>In an application that I'm writing I have some code like this:</p>
<pre><code>NSWorkspace* ws = [NSWorkspace sharedWorkspace];
NSString* myurl = @"http://www.somewebsite.com/method?a=%d";
NSURL* url = [NSURL URLWithString:myurl];
[ws openURL:url];
</code></pre>
<p>The main difference being that <em>myurl</em> comes from somewhere outside my control. Note the %d in the URL which isn't entirely correct and means that URLWithString fails, returning <em>nil</em>.</p>
<p>What is the "correct" way of handling this? Do I need to parse the string and properly encode the arguments? Or is there some clever method in Cocoa that does all the hard work for me?</p>
| [
{
"answer_id": 45905,
"author": "Matt Sheppard",
"author_id": 797,
"author_profile": "https://Stackoverflow.com/users/797",
"pm_score": 2,
"selected": false,
"text": "<p>I think the behaviour here is correct, because %d is not a valid component of a URL (% is the escape, but expects two hex characters to follow it).</p>\n\n<p>You can't just URL encode the URL as given to you, because that would encode the /s and ?s as well, which you don't want.</p>\n\n<p>So, the question is, what's the correct behaviour here?</p>\n\n<p>Perhaps you would want it to be turned into...</p>\n\n<pre><code>http://www.somewebsite.com/method?a=%25d\n</code></pre>\n\n<p>(i.e. the % is encode to the encoded version of % in a URL, so when method gets the input, it sees a as being set to %d)</p>\n\n<p>I don't think there's any library function which will do that sort of thing for you, since there's no 'correct' way to do it. About he only correct thing you can do is return an error message saying the URL you were given is invalid (just as URLWithString is)</p>\n\n<hr>\n\n<p>If you wanted to try to handle the input, I guess you would need to search the URL for any % symbols which are not immediately followed by two hex characters, and then replace the % with %25 in that case. That should be quite possible with a regular expression, though I suspect there may be some additional complexities if your URLs start containing encoded versions of characters outside the ASCII character set.</p>\n"
},
{
"answer_id": 46212,
"author": "amrox",
"author_id": 4468,
"author_profile": "https://Stackoverflow.com/users/4468",
"pm_score": 4,
"selected": true,
"text": "<p>I'm not sure if this is exactly what you're looking for, but there is a method in NSString that will sanitize a URL:</p>\n\n<p><a href=\"https://developer.apple.com/documentation/foundation/nsstring/1415058-stringbyaddingpercentescapesusin\" rel=\"nofollow noreferrer\">stringByAddingPercentEscapesUsingEncoding:</a></p>\n"
},
{
"answer_id": 8665933,
"author": "nverinaud",
"author_id": 855846,
"author_profile": "https://Stackoverflow.com/users/855846",
"pm_score": 1,
"selected": false,
"text": "<p>Unfortunately you need to be smarter than what is provided by Apple :</p>\n\n<pre><code>stringByAddingPercentEscapesUsingEncoding:\n</code></pre>\n\n<p>This will escape all invalid URL characters so that \"http://foo.com/hey%20dude/\", which is valid, becomes \"http://foo.com/hey%2520dud/\", which is not what we want. </p>\n\n<p>According to apple documentation : <a href=\"http://developer.apple.com/library/mac/documentation/CoreFOundation/Reference/CFURLRef/Reference/reference.html#//apple_ref/c/func/CFURLCreateStringByAddingPercentEscapes\" rel=\"nofollow\">http://developer.apple.com/library/mac/documentation/CoreFOundation/Reference/CFURLRef/Reference/reference.html#//apple_ref/c/func/CFURLCreateStringByAddingPercentEscapes</a></p>\n\n<p>I made an NSURL category which does the right thing and works with odd string such as ones with partial encoding (i.e. \"http://foo.com/hey dude/i%20do%20it/\").</p>\n\n<p>Here is the code:</p>\n\n<pre><code>@interface NSURL (SmartEncoding)\n+ (NSURL *)smartURLWithString:(NSString *)str;\n@end\n\n@implementation NSURL (SmartEncoding)\n\n+ (NSURL *)smartURLWithString:(NSString *)str\n{\n CFStringRef preprocessed = CFURLCreateStringByReplacingPercentEscapesUsingEncoding(NULL, (CFStringRef)str, CFSTR(\"\"), kCFStringEncodingUTF8);\n if (!preprocessed) \n preprocessed = CFURLCreateStringByReplacingPercentEscapesUsingEncoding(NULL, (CFStringRef)str, CFSTR(\"\"), kCFStringEncodingASCII);\n\n if (!preprocessed)\n return [NSURL URLWithString:str];\n\n CFStringRef sanitized = CFURLCreateStringByAddingPercentEscapes(NULL, preprocessed, NULL, NULL, kCFStringEncodingUTF8);\n CFRelease(preprocessed);\n NSURL *result = (NSURL*)CFURLCreateWithString(NULL, sanitized, NULL);\n CFRelease(sanitized);\n return [result autorelease];\n}\n\n@end\n</code></pre>\n\n<p>It works fine with UTF8 string encoded and ASCII ones.</p>\n"
}
] | 2008/09/05 | [
"https://Stackoverflow.com/questions/45898",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2998/"
] | In an application that I'm writing I have some code like this:
```
NSWorkspace* ws = [NSWorkspace sharedWorkspace];
NSString* myurl = @"http://www.somewebsite.com/method?a=%d";
NSURL* url = [NSURL URLWithString:myurl];
[ws openURL:url];
```
The main difference being that *myurl* comes from somewhere outside my control. Note the %d in the URL which isn't entirely correct and means that URLWithString fails, returning *nil*.
What is the "correct" way of handling this? Do I need to parse the string and properly encode the arguments? Or is there some clever method in Cocoa that does all the hard work for me? | I'm not sure if this is exactly what you're looking for, but there is a method in NSString that will sanitize a URL:
[stringByAddingPercentEscapesUsingEncoding:](https://developer.apple.com/documentation/foundation/nsstring/1415058-stringbyaddingpercentescapesusin) |
45,904 | <p><strong>Situation:</strong></p>
<p>I have a simple <em>XML</em> document that contains image information. I need to transform it into <em>HTML</em>. However, I can't see where the open tag is and when I use the <em>XSL</em> code below, it shows the following error message: </p>
<blockquote>
<p>"Cannot write an attribute node when no element start tag is open."</p>
</blockquote>
<p><strong>XML content:</strong></p>
<pre><code><root>
<HeaderText>
<HeaderText>Dan Testing</HeaderText>
</HeaderText>
<Image>
<img width="100" height="100" alt="FPO lady" src="/uploadedImages/temp_photo_small.jpg"/>
</Image>
<BodyText>
<p>This is a test of the body text<br /></p>
</BodyText>
<ShowLinkArrow>false</ShowLinkArrow>
</root>
</code></pre>
<p><strong>XSL code:</strong></p>
<pre><code><xsl:stylesheet version="1.0" extension-element-prefixes="msxsl"
exclude-result-prefixes="msxsl js dl" xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
xmlns:js="urn:custom-javascript" xmlns:msxsl="urn:schemas-microsoft-com:xslt"
xmlns:dl="urn:datalist">
<xsl:output method="xml" version="1.0" omit-xml-declaration="yes" indent="yes" encoding="utf-8"/>
<xsl:template match="/" xml:space="preserve">
<img>
<xsl:attribute name="width">
100
</xsl:attribute>
<xsl:attribute name="height">
100
</xsl:attribute>
<xsl:attribute name="class">
CalloutRightPhoto
</xsl:attribute>
<xsl:attribute name="src">
<xsl:copy-of select="/root/Image/node()"/>
</xsl:attribute>
</img>
</xsl:template>
</xsl:stylesheet>
</code></pre>
| [
{
"answer_id": 45909,
"author": "Danimal",
"author_id": 2757,
"author_profile": "https://Stackoverflow.com/users/2757",
"pm_score": 2,
"selected": false,
"text": "<p>Never mind -- I'm an idiot. I just needed <b>\n<xsl:value-of select=\"/root/Image/node()\"/></b></p>\n"
},
{
"answer_id": 45912,
"author": "Cory Foy",
"author_id": 4083,
"author_profile": "https://Stackoverflow.com/users/4083",
"pm_score": 2,
"selected": false,
"text": "<p>Shouldn't that be:</p>\n\n<pre><code><xsl:value-of select=\"/root/Image/img/@src\"/>\n</code></pre>\n\n<p>? It looks like you are trying to copy the entire Image/img node to the attribute @src</p>\n"
},
{
"answer_id": 45917,
"author": "harpo",
"author_id": 4525,
"author_profile": "https://Stackoverflow.com/users/4525",
"pm_score": 2,
"selected": false,
"text": "<p>In order to add attributes, XSL wants</p>\n\n<pre>\n<xsl:element name=\"img\">\n (attributes)\n</xsl:element>\n</pre>\n\n<p>instead of just</p>\n\n<pre>\n<img>\n (attributes)\n</img>\n</pre>\n\n<p>Although, yes, if you're just copying the element as-is, you don't need any of that.</p>\n"
},
{
"answer_id": 45955,
"author": "samjudson",
"author_id": 1908,
"author_profile": "https://Stackoverflow.com/users/1908",
"pm_score": 6,
"selected": true,
"text": "<p>Just to clarify the problem here - the error is in the following bit of code:</p>\n\n<pre><code><xsl:attribute name=\"src\">\n <xsl:copy-of select=\"/root/Image/node()\"/>\n</xsl:attribute>\n</code></pre>\n\n<p>The instruction xsl:copy-of takes a node or node-set and makes a copy of it - outputting a node or node-set. However an attribute cannot contain a node, only a textual value, so xsl:value-of would be a possible solution (as this returns the textual value of a node or nodeset).</p>\n\n<p>A MUCH shorter solution (and perhaps more elegant) would be the following:</p>\n\n<pre><code><img width=\"100\" height=\"100\" src=\"{/root/Image/node()}\" class=\"CalloutRightPhoto\"/>\n</code></pre>\n\n<p>The use of the {} in the attribute is called an Attribute Value Template, and can contain any XPATH expression.</p>\n\n<p>Note, the same XPath can be used here as you have used in the xsl_copy-of as it knows to take the textual value when used in a Attribute Value Template.</p>\n"
},
{
"answer_id": 12581814,
"author": "m_cheung",
"author_id": 582032,
"author_profile": "https://Stackoverflow.com/users/582032",
"pm_score": 0,
"selected": false,
"text": "<p>The other option to try is a straightforward </p>\n\n<pre><code><img width=\"100\" height=\"100\" src=\"/root/Image/image.jpeg\" class=\"CalloutRightPhoto\"/>\n</code></pre>\n\n<p>i.e. without {} but instead giving the direct image path</p>\n"
}
] | 2008/09/05 | [
"https://Stackoverflow.com/questions/45904",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2757/"
] | **Situation:**
I have a simple *XML* document that contains image information. I need to transform it into *HTML*. However, I can't see where the open tag is and when I use the *XSL* code below, it shows the following error message:
>
> "Cannot write an attribute node when no element start tag is open."
>
>
>
**XML content:**
```
<root>
<HeaderText>
<HeaderText>Dan Testing</HeaderText>
</HeaderText>
<Image>
<img width="100" height="100" alt="FPO lady" src="/uploadedImages/temp_photo_small.jpg"/>
</Image>
<BodyText>
<p>This is a test of the body text<br /></p>
</BodyText>
<ShowLinkArrow>false</ShowLinkArrow>
</root>
```
**XSL code:**
```
<xsl:stylesheet version="1.0" extension-element-prefixes="msxsl"
exclude-result-prefixes="msxsl js dl" xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
xmlns:js="urn:custom-javascript" xmlns:msxsl="urn:schemas-microsoft-com:xslt"
xmlns:dl="urn:datalist">
<xsl:output method="xml" version="1.0" omit-xml-declaration="yes" indent="yes" encoding="utf-8"/>
<xsl:template match="/" xml:space="preserve">
<img>
<xsl:attribute name="width">
100
</xsl:attribute>
<xsl:attribute name="height">
100
</xsl:attribute>
<xsl:attribute name="class">
CalloutRightPhoto
</xsl:attribute>
<xsl:attribute name="src">
<xsl:copy-of select="/root/Image/node()"/>
</xsl:attribute>
</img>
</xsl:template>
</xsl:stylesheet>
``` | Just to clarify the problem here - the error is in the following bit of code:
```
<xsl:attribute name="src">
<xsl:copy-of select="/root/Image/node()"/>
</xsl:attribute>
```
The instruction xsl:copy-of takes a node or node-set and makes a copy of it - outputting a node or node-set. However an attribute cannot contain a node, only a textual value, so xsl:value-of would be a possible solution (as this returns the textual value of a node or nodeset).
A MUCH shorter solution (and perhaps more elegant) would be the following:
```
<img width="100" height="100" src="{/root/Image/node()}" class="CalloutRightPhoto"/>
```
The use of the {} in the attribute is called an Attribute Value Template, and can contain any XPATH expression.
Note, the same XPath can be used here as you have used in the xsl\_copy-of as it knows to take the textual value when used in a Attribute Value Template. |
45,908 | <p>After answering on <a href="https://stackoverflow.com/questions/45650/common-files-in-visual-studio-solution#45664">this question</a> I thought it would be nice to collect some tips & tricks for working with MSVS solutions and projects. </p>
<p>Here is my list: </p>
<ul>
<li><p>How to avoid saving new projects
automatically to reduce garbage in
file system.</p>
<p>Uncheck <strong>Tools->Options->Projects and Solutions->Save new projects when created</strong></p></li>
<li><p>How to add common file to multiple
projects without copying it to
project’s directory.</p>
<p>Right click on a project, select <strong>Add->Existing Item->Add as link</strong> (press on small arrow on Add button)</p></li>
<li><p>How to add project to solution
without including it in the build
process</p>
<p>Right click on solution, select <strong>Add->New solution folder</strong>.<br>
Right click on created folder, <strong>select Add->Add existing project</strong></p></li>
<li><p>How to edit project file from Visual
Studio?</p>
<p>Right click on project and select <strong>Unload Project</strong>, right click on unloaded project and select <strong>Edit</strong>.
Or install <a href="http://code.msdn.microsoft.com/PowerCommands" rel="nofollow noreferrer">Power Commands</a> and select <strong>Edit Project File</strong></p></li>
<li><p>How to group files in the project
tree (like auto-generated files for
WinForms controls)</p>
<p>Open project file for editing. </p></li>
</ul>
<pre> Change</pre>
<pre><code><Compile Include="MainFile.cs" />
<Compile Include="SecondaryFile.cs" />
To
<Compile Include="SecondaryFile.cs ">
<DependentUpon> MainFile.cs </DependentUpon>
</Compile>
</code></pre>
<p>Do you have anything else to add?</p>
| [
{
"answer_id": 45995,
"author": "Craig",
"author_id": 2894,
"author_profile": "https://Stackoverflow.com/users/2894",
"pm_score": 2,
"selected": false,
"text": "<p>I like changing the default location that new projects are saved to. </p>\n\n<p>Tools->Options (Select Projects and Solutions tab) </p>\n\n<p>This \"tab\" has all sorts of goodness. Not just the ability to change the default locations and avoid saving new projects automatically but other nice things as well. For example:</p>\n\n<p>Track Active Item - Selects the file in the solution explorer when you change windows.</p>\n\n<p>Show Output window when build starts - Toggle to show or not. I like it on, your mileage will vary.</p>\n"
},
{
"answer_id": 46275,
"author": "Owen",
"author_id": 4790,
"author_profile": "https://Stackoverflow.com/users/4790",
"pm_score": 1,
"selected": false,
"text": "<p>I have a tip regarding the \"Track Active Item\" option mentioned above, for when working with big projects. It's posted here:</p>\n\n<p><a href=\"https://stackoverflow.com/questions/31163/forcing-the-solution-explorer-to-select-the-file-in-the-editor-in-visual-studio#46193\">Forcing the Solution Explorer to select the file in the editor in visual studio 2005</a></p>\n"
},
{
"answer_id": 46300,
"author": "David Mohundro",
"author_id": 4570,
"author_profile": "https://Stackoverflow.com/users/4570",
"pm_score": 3,
"selected": false,
"text": "<p>I'm a huge fan of using msbuild to build my solutions with the /m option so that it builds using multiple cores. It can drastically decrease your build time.</p>\n\n<p>Scott Hanselman posted on how to add it to your tools list at <a href=\"http://www.hanselman.com/blog/HackParallelMSBuildsFromWithinTheVisualStudioIDE.aspx\" rel=\"nofollow noreferrer\"><a href=\"http://www.hanselman.com/blog/HackParallelMSBuildsFromWithinTheVisualStudioIDE.aspx\" rel=\"nofollow noreferrer\">http://www.hanselman.com/blog/HackParallelMSBuildsFromWithinTheVisualStudioIDE.aspx</a></a>.</p>\n\n<p>I usually just run 'msbuild /m' from the command prompt or PowerShell, though.</p>\n\n<p>Another tip that is sometimes useful is taking advantage of the pre- and post-build events to add additional logic before or after a build. To see these, go to the Properties for a Project, click on the Compile tab, and then choose \"Build Events...\"</p>\n"
},
{
"answer_id": 54112,
"author": "Gulzar Nazim",
"author_id": 4337,
"author_profile": "https://Stackoverflow.com/users/4337",
"pm_score": 2,
"selected": false,
"text": "<p>I love debugging with the <a href=\"http://blogs.msdn.com/saraford/archive/2008/07/28/did-you-know-you-can-start-debugging-multiple-projects-268.aspx\" rel=\"nofollow noreferrer\">Multiple startup projects option</a></p>\n"
},
{
"answer_id": 156311,
"author": "Mario",
"author_id": 472,
"author_profile": "https://Stackoverflow.com/users/472",
"pm_score": 2,
"selected": false,
"text": "<p>Using the command window to quickly open files in your solution:</p>\n<ol>\n<li>Bring up the Command Window (<kbd>CTRL</kbd>-<kbd>ALT</kbd>-<kbd>A</kbd>)</li>\n<li>Type <code>open <filename></code></li>\n</ol>\n<p>I create an alias for <code>open</code> by executing the following at the Command Window: <code>alias o open</code>. Visual Studio will remember the alias from then on, so I only ever need to type <code>o <filename></code>.</p>\n<p>It even searches database projects unlike some third-party plugins!</p>\n<p>Unfortunately, there is a bug in the filename completion when searching for nested files. A simple workaround is to type the beginning of the filename, hit the <kbd>ESC</kbd> key and then type the rest of the name. To search for login.aspx.cs, type <code>login.aspx</code>, hit <kbd>ESCP</kbd> and then type <code>.cs</code>.</p>\n"
},
{
"answer_id": 157179,
"author": "Rinat Abdullin",
"author_id": 47366,
"author_profile": "https://Stackoverflow.com/users/47366",
"pm_score": 4,
"selected": false,
"text": "<p>First rule of working with Visual Studio:</p>\n\n<ul>\n<li><strong>Install <a href=\"http://www.jetbrains.com/resharper/\" rel=\"noreferrer\">ReSharper</a></strong></li>\n</ul>\n"
}
] | 2008/09/05 | [
"https://Stackoverflow.com/questions/45908",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1196/"
] | After answering on [this question](https://stackoverflow.com/questions/45650/common-files-in-visual-studio-solution#45664) I thought it would be nice to collect some tips & tricks for working with MSVS solutions and projects.
Here is my list:
* How to avoid saving new projects
automatically to reduce garbage in
file system.
Uncheck **Tools->Options->Projects and Solutions->Save new projects when created**
* How to add common file to multiple
projects without copying it to
project’s directory.
Right click on a project, select **Add->Existing Item->Add as link** (press on small arrow on Add button)
* How to add project to solution
without including it in the build
process
Right click on solution, select **Add->New solution folder**.
Right click on created folder, **select Add->Add existing project**
* How to edit project file from Visual
Studio?
Right click on project and select **Unload Project**, right click on unloaded project and select **Edit**.
Or install [Power Commands](http://code.msdn.microsoft.com/PowerCommands) and select **Edit Project File**
* How to group files in the project
tree (like auto-generated files for
WinForms controls)
Open project file for editing.
```
Change
```
```
<Compile Include="MainFile.cs" />
<Compile Include="SecondaryFile.cs" />
To
<Compile Include="SecondaryFile.cs ">
<DependentUpon> MainFile.cs </DependentUpon>
</Compile>
```
Do you have anything else to add? | First rule of working with Visual Studio:
* **Install [ReSharper](http://www.jetbrains.com/resharper/)** |
45,924 | <p>My users are having an intermittent error when using a Windows Forms application built in VB.NET 3.5. Apparently when they click on the form and the form re-paints, a red 'X' will be painted over the MenuStrip control and the app will crash with the following error. </p>
<p>Has anyone seen this before? Can someone point me in the right direction? </p>
<pre><code> System.ArgumentOutOfRangeException: Index was out of range. Must be non-negative and less than the size of the collection.
Parameter name: index
at System.Collections.ArrayList.get_Item(Int32 index)
at System.Windows.Forms.ToolStripItemCollection.get_Item(Int32 index)
at System.Windows.Forms.ToolStrip.OnPaint(PaintEventArgs e)
at System.Windows.Forms.Control.PaintWithErrorHandling(PaintEventArgs e, Int16 layer, Boolean disposeEventArgs)
at System.Windows.Forms.Control.WmPaint(Message& m)
at System.Windows.Forms.Control.WndProc(Message& m)
at System.Windows.Forms.ScrollableControl.WndProc(Message& m)
at System.Windows.Forms.ToolStrip.WndProc(Message& m)
at System.Windows.Forms.MenuStrip.WndProc(Message& m)
at System.Windows.Forms.Control.ControlNativeWindow.OnMessage(Message& m)
at System.Windows.Forms.Control.ControlNativeWindow.WndProc(Message& m)
at System.Windows.Forms.NativeWindow.Callback(IntPtr hWnd, Int32 msg, IntPtr wparam, IntPtr lparam)
</code></pre>
| [
{
"answer_id": 45995,
"author": "Craig",
"author_id": 2894,
"author_profile": "https://Stackoverflow.com/users/2894",
"pm_score": 2,
"selected": false,
"text": "<p>I like changing the default location that new projects are saved to. </p>\n\n<p>Tools->Options (Select Projects and Solutions tab) </p>\n\n<p>This \"tab\" has all sorts of goodness. Not just the ability to change the default locations and avoid saving new projects automatically but other nice things as well. For example:</p>\n\n<p>Track Active Item - Selects the file in the solution explorer when you change windows.</p>\n\n<p>Show Output window when build starts - Toggle to show or not. I like it on, your mileage will vary.</p>\n"
},
{
"answer_id": 46275,
"author": "Owen",
"author_id": 4790,
"author_profile": "https://Stackoverflow.com/users/4790",
"pm_score": 1,
"selected": false,
"text": "<p>I have a tip regarding the \"Track Active Item\" option mentioned above, for when working with big projects. It's posted here:</p>\n\n<p><a href=\"https://stackoverflow.com/questions/31163/forcing-the-solution-explorer-to-select-the-file-in-the-editor-in-visual-studio#46193\">Forcing the Solution Explorer to select the file in the editor in visual studio 2005</a></p>\n"
},
{
"answer_id": 46300,
"author": "David Mohundro",
"author_id": 4570,
"author_profile": "https://Stackoverflow.com/users/4570",
"pm_score": 3,
"selected": false,
"text": "<p>I'm a huge fan of using msbuild to build my solutions with the /m option so that it builds using multiple cores. It can drastically decrease your build time.</p>\n\n<p>Scott Hanselman posted on how to add it to your tools list at <a href=\"http://www.hanselman.com/blog/HackParallelMSBuildsFromWithinTheVisualStudioIDE.aspx\" rel=\"nofollow noreferrer\"><a href=\"http://www.hanselman.com/blog/HackParallelMSBuildsFromWithinTheVisualStudioIDE.aspx\" rel=\"nofollow noreferrer\">http://www.hanselman.com/blog/HackParallelMSBuildsFromWithinTheVisualStudioIDE.aspx</a></a>.</p>\n\n<p>I usually just run 'msbuild /m' from the command prompt or PowerShell, though.</p>\n\n<p>Another tip that is sometimes useful is taking advantage of the pre- and post-build events to add additional logic before or after a build. To see these, go to the Properties for a Project, click on the Compile tab, and then choose \"Build Events...\"</p>\n"
},
{
"answer_id": 54112,
"author": "Gulzar Nazim",
"author_id": 4337,
"author_profile": "https://Stackoverflow.com/users/4337",
"pm_score": 2,
"selected": false,
"text": "<p>I love debugging with the <a href=\"http://blogs.msdn.com/saraford/archive/2008/07/28/did-you-know-you-can-start-debugging-multiple-projects-268.aspx\" rel=\"nofollow noreferrer\">Multiple startup projects option</a></p>\n"
},
{
"answer_id": 156311,
"author": "Mario",
"author_id": 472,
"author_profile": "https://Stackoverflow.com/users/472",
"pm_score": 2,
"selected": false,
"text": "<p>Using the command window to quickly open files in your solution:</p>\n<ol>\n<li>Bring up the Command Window (<kbd>CTRL</kbd>-<kbd>ALT</kbd>-<kbd>A</kbd>)</li>\n<li>Type <code>open <filename></code></li>\n</ol>\n<p>I create an alias for <code>open</code> by executing the following at the Command Window: <code>alias o open</code>. Visual Studio will remember the alias from then on, so I only ever need to type <code>o <filename></code>.</p>\n<p>It even searches database projects unlike some third-party plugins!</p>\n<p>Unfortunately, there is a bug in the filename completion when searching for nested files. A simple workaround is to type the beginning of the filename, hit the <kbd>ESC</kbd> key and then type the rest of the name. To search for login.aspx.cs, type <code>login.aspx</code>, hit <kbd>ESCP</kbd> and then type <code>.cs</code>.</p>\n"
},
{
"answer_id": 157179,
"author": "Rinat Abdullin",
"author_id": 47366,
"author_profile": "https://Stackoverflow.com/users/47366",
"pm_score": 4,
"selected": false,
"text": "<p>First rule of working with Visual Studio:</p>\n\n<ul>\n<li><strong>Install <a href=\"http://www.jetbrains.com/resharper/\" rel=\"noreferrer\">ReSharper</a></strong></li>\n</ul>\n"
}
] | 2008/09/05 | [
"https://Stackoverflow.com/questions/45924",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4770/"
] | My users are having an intermittent error when using a Windows Forms application built in VB.NET 3.5. Apparently when they click on the form and the form re-paints, a red 'X' will be painted over the MenuStrip control and the app will crash with the following error.
Has anyone seen this before? Can someone point me in the right direction?
```
System.ArgumentOutOfRangeException: Index was out of range. Must be non-negative and less than the size of the collection.
Parameter name: index
at System.Collections.ArrayList.get_Item(Int32 index)
at System.Windows.Forms.ToolStripItemCollection.get_Item(Int32 index)
at System.Windows.Forms.ToolStrip.OnPaint(PaintEventArgs e)
at System.Windows.Forms.Control.PaintWithErrorHandling(PaintEventArgs e, Int16 layer, Boolean disposeEventArgs)
at System.Windows.Forms.Control.WmPaint(Message& m)
at System.Windows.Forms.Control.WndProc(Message& m)
at System.Windows.Forms.ScrollableControl.WndProc(Message& m)
at System.Windows.Forms.ToolStrip.WndProc(Message& m)
at System.Windows.Forms.MenuStrip.WndProc(Message& m)
at System.Windows.Forms.Control.ControlNativeWindow.OnMessage(Message& m)
at System.Windows.Forms.Control.ControlNativeWindow.WndProc(Message& m)
at System.Windows.Forms.NativeWindow.Callback(IntPtr hWnd, Int32 msg, IntPtr wparam, IntPtr lparam)
``` | First rule of working with Visual Studio:
* **Install [ReSharper](http://www.jetbrains.com/resharper/)** |
45,941 | <p>I've used subversion for a while, and used the svnmerge.py script for a while in my old job to manage merges between branches. I believe Subversion 1.5 is now out, and was supposed to have some branch / merge management system integrated with it.</p>
<p>So, can someone give me a quick overview of how to track merges in a branch with Subversion 1.5? Are there any pitfalls with using this support? Do I need to ensure all the team upgrades to 1.5 before using this support?</p>
| [
{
"answer_id": 45978,
"author": "Chris Zwiryk",
"author_id": 734,
"author_profile": "https://Stackoverflow.com/users/734",
"pm_score": 3,
"selected": true,
"text": "<h3>Usage</h3>\n\n<p>Merge tracking is managed by the client and stored in a property (<a href=\"http://subversion.tigris.org/merge-tracking/design.html\" rel=\"nofollow noreferrer\">svn:mergeinfo</a>).</p>\n\n<p>To use merge tracking you just merge as usual but without the revision range:</p>\n\n<pre><code>svn merge trunkURL\n</code></pre>\n\n<p>The client will take care of reading the properties to see what revision(s) need to be merged in and then update the properties with the newly-merged revision(s).</p>\n\n<p><a href=\"http://blog.red-bean.com/sussman/?p=92\" rel=\"nofollow noreferrer\">Here</a> is a pretty basic overview of the process.</p>\n\n<h3>Pitfalls, etc.</h3>\n\n<p>I personally haven't run into any problems with merge tracking, but my usage of the feature has been pretty light.</p>\n\n<h3>Upgrading</h3>\n\n<p>There are two upgrades you'll need to do to get merge tracking:</p>\n\n<ol>\n<li>Server: Your server <strong>must</strong> be running 1.5 to get merge tracking support.</li>\n<li>Client: You can use a 1.x client against a 1.5 server, <strong>but you won't get merge tracking.</strong></li>\n</ol>\n\n<p>Just upgrade everyone.</p>\n"
},
{
"answer_id": 46154,
"author": "Ishmaeel",
"author_id": 227,
"author_profile": "https://Stackoverflow.com/users/227",
"pm_score": 1,
"selected": false,
"text": "<p>An addition to Chris's post:</p>\n\n<p>You may also have to upgrade the repository itself, if you run into \"Retrieval of mergeinfo unsupported\" messages. The command to run on the server to do this is,</p>\n\n<pre><code>svnadmin upgrade REPOS_PATH\n</code></pre>\n\n<p>where REPOS_PATH is the local path to your repository of course.</p>\n"
},
{
"answer_id": 240410,
"author": "Hugo",
"author_id": 972,
"author_profile": "https://Stackoverflow.com/users/972",
"pm_score": 0,
"selected": false,
"text": "<p>If you've built your repository with the ~ svn-merge.py command you can upgrade your repository to use svn native merge tracking with the XXX command.</p>\n"
}
] | 2008/09/05 | [
"https://Stackoverflow.com/questions/45941",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/797/"
] | I've used subversion for a while, and used the svnmerge.py script for a while in my old job to manage merges between branches. I believe Subversion 1.5 is now out, and was supposed to have some branch / merge management system integrated with it.
So, can someone give me a quick overview of how to track merges in a branch with Subversion 1.5? Are there any pitfalls with using this support? Do I need to ensure all the team upgrades to 1.5 before using this support? | ### Usage
Merge tracking is managed by the client and stored in a property ([svn:mergeinfo](http://subversion.tigris.org/merge-tracking/design.html)).
To use merge tracking you just merge as usual but without the revision range:
```
svn merge trunkURL
```
The client will take care of reading the properties to see what revision(s) need to be merged in and then update the properties with the newly-merged revision(s).
[Here](http://blog.red-bean.com/sussman/?p=92) is a pretty basic overview of the process.
### Pitfalls, etc.
I personally haven't run into any problems with merge tracking, but my usage of the feature has been pretty light.
### Upgrading
There are two upgrades you'll need to do to get merge tracking:
1. Server: Your server **must** be running 1.5 to get merge tracking support.
2. Client: You can use a 1.x client against a 1.5 server, **but you won't get merge tracking.**
Just upgrade everyone. |
45,953 | <p>I need to execute a directory copy upon a user action, but the directories are quite large, so I would like to be able to perform such an action without the user being aware of the time it takes for the copy to complete.</p>
<p>Any suggestions would be much appreciated.</p>
| [
{
"answer_id": 45962,
"author": "Matt Sheppard",
"author_id": 797,
"author_profile": "https://Stackoverflow.com/users/797",
"pm_score": 2,
"selected": false,
"text": "<p>Can you arrange to fork off a separate process, and then run your copy in the background? It's been a while since I did any PHP, but the function <a href=\"http://au2.php.net/manual/en/function.pcntl-fork.php\" rel=\"nofollow noreferrer\">pcntl-fork</a> looks promising. </p>\n"
},
{
"answer_id": 45966,
"author": "Mark Biek",
"author_id": 305,
"author_profile": "https://Stackoverflow.com/users/305",
"pm_score": 10,
"selected": true,
"text": "<p>Assuming this is running on a Linux machine, I've always handled it like this:</p>\n\n<pre><code>exec(sprintf(\"%s > %s 2>&1 & echo $! >> %s\", $cmd, $outputfile, $pidfile));\n</code></pre>\n\n<p>This launches the command <code>$cmd</code>, redirects the command output to <code>$outputfile</code>, and writes the process id to <code>$pidfile</code>.</p>\n\n<p>That lets you easily monitor what the process is doing and if it's still running.</p>\n\n<pre><code>function isRunning($pid){\n try{\n $result = shell_exec(sprintf(\"ps %d\", $pid));\n if( count(preg_split(\"/\\n/\", $result)) > 2){\n return true;\n }\n }catch(Exception $e){}\n\n return false;\n}\n</code></pre>\n"
},
{
"answer_id": 46008,
"author": "Eric Goodwin",
"author_id": 1430,
"author_profile": "https://Stackoverflow.com/users/1430",
"pm_score": 5,
"selected": false,
"text": "<p>Write the process as a server-side script in whatever language (php/bash/perl/etc) is handy and then call it from the process control functions in your php script.</p>\n\n<p>The function probably detects if standard io is used as the output stream and if it is then that will set the return value..if not then it ends </p>\n\n<pre><code>proc_close( proc_open( \"./command --foo=1 &\", array(), $foo ) );\n</code></pre>\n\n<p>I tested this quickly from the command line using \"sleep 25s\" as the command and it worked like a charm.</p>\n\n<p>(<a href=\"http://ca.php.net/manual/en/function.exec.php\" rel=\"noreferrer\">Answer found here</a>)</p>\n"
},
{
"answer_id": 2254982,
"author": "Captain Obvious",
"author_id": 172166,
"author_profile": "https://Stackoverflow.com/users/172166",
"pm_score": 4,
"selected": false,
"text": "<p>I'd just like to add a very simple example for testing this functionality on Windows:</p>\n\n<p>Create the following two files and save them to a web directory:</p>\n\n<p>foreground.php:</p>\n\n<pre><code><?php\n\nini_set(\"display_errors\",1);\nerror_reporting(E_ALL);\n\necho \"<pre>loading page</pre>\";\n\nfunction run_background_process()\n{\n file_put_contents(\"testprocesses.php\",\"foreground start time = \" . time() . \"\\n\");\n echo \"<pre> foreground start time = \" . time() . \"</pre>\";\n\n // output from the command must be redirected to a file or another output stream \n // http://ca.php.net/manual/en/function.exec.php\n\n exec(\"php background.php > testoutput.php 2>&1 & echo $!\", $output);\n\n echo \"<pre> foreground end time = \" . time() . \"</pre>\";\n file_put_contents(\"testprocesses.php\",\"foreground end time = \" . time() . \"\\n\", FILE_APPEND);\n return $output;\n}\n\necho \"<pre>calling run_background_process</pre>\";\n\n$output = run_background_process();\n\necho \"<pre>output = \"; print_r($output); echo \"</pre>\";\necho \"<pre>end of page</pre>\";\n?>\n</code></pre>\n\n<p>background.php:</p>\n\n<pre><code><?\nfile_put_contents(\"testprocesses.php\",\"background start time = \" . time() . \"\\n\", FILE_APPEND);\nsleep(10);\nfile_put_contents(\"testprocesses.php\",\"background end time = \" . time() . \"\\n\", FILE_APPEND);\n?>\n</code></pre>\n\n<p>Give IUSR permission to write to the directory in which you created the above files</p>\n\n<p>Give IUSR permission to READ and EXECUTE C:\\Windows\\System32\\cmd.exe</p>\n\n<p>Hit foreground.php from a web browser</p>\n\n<p>The following should be rendered to the browser w/the current timestamps and local resource # in the output array:</p>\n\n<pre><code>loading page\ncalling run_background_process\n foreground start time = 1266003600\n foreground end time = 1266003600\noutput = Array\n(\n [0] => 15010\n)\nend of page\n</code></pre>\n\n<p>You should see testoutput.php in the same directory as the above files were saved, and it should be empty</p>\n\n<p>You should see testprocesses.php in the same directory as the above files were saved, and it should contain the following text w/the current timestamps:</p>\n\n<pre><code>foreground start time = 1266003600\nforeground end time = 1266003600\nbackground start time = 1266003600\nbackground end time = 1266003610\n</code></pre>\n"
},
{
"answer_id": 4832703,
"author": "Neven Boyanov",
"author_id": 594345,
"author_profile": "https://Stackoverflow.com/users/594345",
"pm_score": 3,
"selected": false,
"text": "<p>If you need to just do something in background without the PHP page waiting for it to complete, you could use another (background) PHP script that is \"invoked\" with wget command. This background PHP script will be executed with privileges, of course, as any other PHP script on your system.</p>\n\n<p>Here is an example on Windows using wget from gnuwin32 packages.</p>\n\n<p>The background code (file test-proc-bg.php) as an exmple ...</p>\n\n<pre><code>sleep(5); // some delay\nfile_put_contents('test.txt', date('Y-m-d/H:i:s.u')); // writes time in a file\n</code></pre>\n\n<p>The foreground script, the one invoking ...</p>\n\n<pre><code>$proc_command = \"wget.exe http://localhost/test-proc-bg.php -q -O - -b\";\n$proc = popen($proc_command, \"r\");\npclose($proc);\n</code></pre>\n\n<p>You must use the popen/pclose for this to work properly.</p>\n\n<p>The wget options:</p>\n\n<pre><code>-q keeps wget quiet.\n-O - outputs to stdout.\n-b works on background\n</code></pre>\n"
},
{
"answer_id": 7035131,
"author": "Alex",
"author_id": 891051,
"author_profile": "https://Stackoverflow.com/users/891051",
"pm_score": -1,
"selected": false,
"text": "<p>I know it is a 100 year old post, but anyway, thought it might be useful to someone. You can put an invisible image somewhere on the page pointing to the url that needs to run in the background, like this:</p>\n\n<p><code><img src=\"run-in-background.php\" border=\"0\" alt=\"\" width=\"1\" height=\"1\" /></code></p>\n"
},
{
"answer_id": 10332392,
"author": "Brian Warshaw",
"author_id": 1344,
"author_profile": "https://Stackoverflow.com/users/1344",
"pm_score": 1,
"selected": false,
"text": "<p>Instead of initiating a background process, what about creating a trigger file and having a scheduler like cron or autosys periodically execute a script that looks for and acts on the trigger files? The triggers could contain instructions or even raw commands (better yet, just make it a shell script).</p>\n"
},
{
"answer_id": 11954827,
"author": "wlf",
"author_id": 1595154,
"author_profile": "https://Stackoverflow.com/users/1595154",
"pm_score": 5,
"selected": false,
"text": "<p>You might want to try to append this to your command</p>\n\n<pre><code>>/dev/null 2>/dev/null &\n</code></pre>\n\n<p>eg.</p>\n\n<pre><code>shell_exec('service named reload >/dev/null 2>/dev/null &');\n</code></pre>\n"
},
{
"answer_id": 14886239,
"author": "scones",
"author_id": 2004683,
"author_profile": "https://Stackoverflow.com/users/2004683",
"pm_score": 2,
"selected": false,
"text": "<p>You might try a queuing system like <a href=\"https://github.com/chrisboulton/php-resque\" rel=\"nofollow\">Resque</a>. You then can generate a job, that processes the information and quite fast return with the \"processing\" image. With this approach you won't know when it is finished though.</p>\n\n<p>This solution is intended for larger scale applications, where you don't want your front machines to do the heavy lifting, so they can process user requests.\nTherefore it might or might not work with physical data like files and folders, but for processing more complicated logic or other asynchronous tasks (ie new registrations mails) it is nice to have and very scalable.</p>\n"
},
{
"answer_id": 24025322,
"author": "Morfidon",
"author_id": 2393593,
"author_profile": "https://Stackoverflow.com/users/2393593",
"pm_score": 3,
"selected": false,
"text": "<p>Well i found a bit faster and easier version to use</p>\n\n<pre><code>shell_exec('screen -dmS $name_of_screen $command'); \n</code></pre>\n\n<p>and it works.</p>\n"
},
{
"answer_id": 24535424,
"author": "John Foley",
"author_id": 1775336,
"author_profile": "https://Stackoverflow.com/users/1775336",
"pm_score": 1,
"selected": false,
"text": "<p>If using PHP there is a much easier way to do this using pcntl_fork:</p>\n\n<p><a href=\"http://www.php.net/manual/en/function.pcntl-fork.php\" rel=\"nofollow\">http://www.php.net/manual/en/function.pcntl-fork.php</a></p>\n"
},
{
"answer_id": 25104811,
"author": "shihab mm",
"author_id": 3024401,
"author_profile": "https://Stackoverflow.com/users/3024401",
"pm_score": 0,
"selected": false,
"text": "<p>PHP scripting is not like other desktop application developing language. In desktop application languages we can set daemon threads to run a background process but in PHP a process is occuring when user request for a page. However It is possible to set a background job using server's cron job functionality which php script runs.</p>\n"
},
{
"answer_id": 26170949,
"author": "sgotre",
"author_id": 2859620,
"author_profile": "https://Stackoverflow.com/users/2859620",
"pm_score": 1,
"selected": false,
"text": "<p>I am heavily using <code>fast_cgi_finish_request()</code></p>\n\n<p>In combination with a closure and register_shutdown_function()</p>\n\n<pre><code>$message ='job executed';\n$backgroundJob = function() use ($message) {\n //do some work here\n echo $message;\n}\n</code></pre>\n\n<p>Then register this closure to be executed before shutdown. </p>\n\n<pre><code>register_shutdown_function($backgroundJob);\n</code></pre>\n\n<p>Finally when the response was sent to the client you can close the connection to the client and continue working with the PHP process:</p>\n\n<pre><code>fast_cgi_finish_request();\n</code></pre>\n\n<p>The closure will be executed after fast_cgi_finish_request. </p>\n\n<p>The $message will not be visible at any time. And you can register as much closures as you want, but take care about script execution time. \nThis will only work if PHP is running as a Fast CGI module (was that right?!)</p>\n"
},
{
"answer_id": 30672118,
"author": "Jimmy Ilenloa",
"author_id": 2259400,
"author_profile": "https://Stackoverflow.com/users/2259400",
"pm_score": 0,
"selected": false,
"text": "<p>For those of us using <strong>Windows</strong>, look at this:</p>\n\n<p>Reference: <a href=\"http://php.net/manual/en/function.exec.php#43917\" rel=\"nofollow noreferrer\">http://php.net/manual/en/function.exec.php#43917</a></p>\n\n<blockquote>\n <p>I too wrestled with getting a program to run in the background in\n Windows while the script continues to execute. This method unlike the\n other solutions allows you to start any program minimized, maximized,\n or with no window at all. llbra@phpbrasil's solution does work but it\n sometimes produces an unwanted window on the desktop when you really\n want the task to run hidden.</p>\n</blockquote>\n\n<p>start Notepad.exe minimized in the background: </p>\n\n<pre><code><?php \n$WshShell = new COM(\"WScript.Shell\"); \n$oExec = $WshShell->Run(\"notepad.exe\", 7, false); \n?> \n</code></pre>\n\n<p>start a shell command invisible in the background: </p>\n\n<pre><code><?php \n$WshShell = new COM(\"WScript.Shell\"); \n$oExec = $WshShell->Run(\"cmd /C dir /S %windir%\", 0, false); \n?> \n</code></pre>\n\n<p>start MSPaint maximized and wait for you to close it before continuing the script: </p>\n\n<pre><code><?php \n$WshShell = new COM(\"WScript.Shell\"); \n$oExec = $WshShell->Run(\"mspaint.exe\", 3, true); \n?> \n</code></pre>\n\n<p>For more info on the Run() method go to: \n<a href=\"http://msdn.microsoft.com/library/en-us/script56/html/wsMthRun.asp\" rel=\"nofollow noreferrer\">http://msdn.microsoft.com/library/en-us/script56/html/wsMthRun.asp</a></p>\n\n<p><strong>Edited URL:</strong></p>\n\n<p>Go to <a href=\"https://technet.microsoft.com/en-us/library/ee156605.aspx\" rel=\"nofollow noreferrer\">https://technet.microsoft.com/en-us/library/ee156605.aspx</a> instead as the link above no longer exists.</p>\n"
},
{
"answer_id": 34612967,
"author": "Slava",
"author_id": 1709903,
"author_profile": "https://Stackoverflow.com/users/1709903",
"pm_score": 3,
"selected": false,
"text": "<p>Here is a function to launch a background process in PHP. Finally created one that actually works on Windows too, after a lot of reading and testing different approaches and parameters.</p>\n\n<pre><code>function LaunchBackgroundProcess($command){\n // Run command Asynchroniously (in a separate thread)\n if(PHP_OS=='WINNT' || PHP_OS=='WIN32' || PHP_OS=='Windows'){\n // Windows\n $command = 'start \"\" '. $command;\n } else {\n // Linux/UNIX\n $command = $command .' /dev/null &';\n }\n $handle = popen($command, 'r');\n if($handle!==false){\n pclose($handle);\n return true;\n } else {\n return false;\n }\n}\n</code></pre>\n\n<p>Note 1: On windows, do not use <code>/B</code> parameter as suggested elsewhere. It forces process to run the same console window as <code>start</code> command itself, resulting in the process being processed synchronously. To run the process in a separate thread (asynchronously), do not use <code>/B</code>.</p>\n\n<p>Note 2: The empty double quotes after <code>start \"\"</code> are required if the command is a quoted path. <code>start</code> command interprets the first quoted parameter as window title.</p>\n"
},
{
"answer_id": 38179655,
"author": "Pascal9x",
"author_id": 2782340,
"author_profile": "https://Stackoverflow.com/users/2782340",
"pm_score": 2,
"selected": false,
"text": "<p>Use this function to run your program in background. It cross-platform and fully customizable.</p>\n\n<pre><code><?php\nfunction startBackgroundProcess(\n $command,\n $stdin = null,\n $redirectStdout = null,\n $redirectStderr = null,\n $cwd = null,\n $env = null,\n $other_options = null\n) {\n $descriptorspec = array(\n 1 => is_string($redirectStdout) ? array('file', $redirectStdout, 'w') : array('pipe', 'w'),\n 2 => is_string($redirectStderr) ? array('file', $redirectStderr, 'w') : array('pipe', 'w'),\n );\n if (is_string($stdin)) {\n $descriptorspec[0] = array('pipe', 'r');\n }\n $proc = proc_open($command, $descriptorspec, $pipes, $cwd, $env, $other_options);\n if (!is_resource($proc)) {\n throw new \\Exception(\"Failed to start background process by command: $command\");\n }\n if (is_string($stdin)) {\n fwrite($pipes[0], $stdin);\n fclose($pipes[0]);\n }\n if (!is_string($redirectStdout)) {\n fclose($pipes[1]);\n }\n if (!is_string($redirectStderr)) {\n fclose($pipes[2]);\n }\n return $proc;\n}\n</code></pre>\n\n<p>Note that after command started, by default this function closes the stdin and stdout of running process. You can redirect process output into some file via $redirectStdout and $redirectStderr arguments.</p>\n\n<p><strong>Note for windows users:</strong><br>\nYou cannot redirect stdout/stderr to <code>nul</code> in the following manner:</p>\n\n<pre><code>startBackgroundProcess('ping yandex.com', null, 'nul', 'nul');\n</code></pre>\n\n<p>However, you can do this:</p>\n\n<pre><code>startBackgroundProcess('ping yandex.com >nul 2>&1');\n</code></pre>\n\n<p><strong>Notes for *nix users:</strong></p>\n\n<p>1) Use exec shell command if you want get actual PID:</p>\n\n<pre><code>$proc = startBackgroundProcess('exec ping yandex.com -c 15', null, '/dev/null', '/dev/null');\nprint_r(proc_get_status($proc));\n</code></pre>\n\n<p>2) Use $stdin argument if you want to pass some data to the input of your program:</p>\n\n<pre><code>startBackgroundProcess('cat > input.txt', \"Hello world!\\n\");\n</code></pre>\n"
},
{
"answer_id": 46617107,
"author": "Joshy Francis",
"author_id": 6417678,
"author_profile": "https://Stackoverflow.com/users/6417678",
"pm_score": 2,
"selected": false,
"text": "<p>A working solution for both Windows and Linux. Find more on <a href=\"https://github.com/JoshyFrancis/php_background_process\" rel=\"nofollow noreferrer\">My github page</a>.</p>\n\n<pre><code>function run_process($cmd,$outputFile = '/dev/null', $append = false){\n $pid=0;\n if (strtoupper(substr(PHP_OS, 0, 3)) === 'WIN') {//'This is a server using Windows!';\n $cmd = 'wmic process call create \"'.$cmd.'\" | find \"ProcessId\"';\n $handle = popen(\"start /B \". $cmd, \"r\");\n $read = fread($handle, 200); //Read the output \n $pid=substr($read,strpos($read,'=')+1);\n $pid=substr($pid,0,strpos($pid,';') );\n $pid = (int)$pid;\n pclose($handle); //Close\n }else{\n $pid = (int)shell_exec(sprintf('%s %s %s 2>&1 & echo $!', $cmd, ($append) ? '>>' : '>', $outputFile));\n }\n return $pid;\n }\n function is_process_running($pid){\n if (strtoupper(substr(PHP_OS, 0, 3)) === 'WIN') {//'This is a server using Windows!';\n //tasklist /FI \"PID eq 6480\"\n $result = shell_exec('tasklist /FI \"PID eq '.$pid.'\"' );\n if (count(preg_split(\"/\\n/\", $result)) > 0 && !preg_match('/No tasks/', $result)) {\n return true;\n }\n }else{\n $result = shell_exec(sprintf('ps %d 2>&1', $pid));\n if (count(preg_split(\"/\\n/\", $result)) > 2 && !preg_match('/ERROR: Process ID out of range/', $result)) {\n return true;\n }\n }\n return false;\n }\n function stop_process($pid){\n if (strtoupper(substr(PHP_OS, 0, 3)) === 'WIN') {//'This is a server using Windows!';\n $result = shell_exec('taskkill /PID '.$pid );\n if (count(preg_split(\"/\\n/\", $result)) > 0 && !preg_match('/No tasks/', $result)) {\n return true;\n }\n }else{\n $result = shell_exec(sprintf('kill %d 2>&1', $pid));\n if (!preg_match('/No such process/', $result)) {\n return true;\n }\n }\n }\n</code></pre>\n"
},
{
"answer_id": 54409868,
"author": "MAChitgarha",
"author_id": 4215651,
"author_profile": "https://Stackoverflow.com/users/4215651",
"pm_score": 2,
"selected": false,
"text": "<p>Thanks to <a href=\"https://stackoverflow.com/a/46677126/4215651\">this answer</a>: A perfect tool to run a background process would be <a href=\"https://github.com/symfony/process\" rel=\"nofollow noreferrer\">Symfony Process Component</a>, which is based on <code>proc_*</code> functions, but it's much easier to use. See <a href=\"https://symfony.com/doc/current/components/process.html\" rel=\"nofollow noreferrer\">its documentation</a> for more information.</p>\n"
},
{
"answer_id": 64778230,
"author": "TheKarateKid",
"author_id": 1692693,
"author_profile": "https://Stackoverflow.com/users/1692693",
"pm_score": 1,
"selected": false,
"text": "<p>If you are looking to execute a background process via PHP, pipe the command's output to <code>/dev/null</code> and add <code>&</code> to the end of the command.</p>\n<pre><code>exec("bg_process > /dev/null &");\n</code></pre>\n<p>Note that you can <strong>not</strong> utilize the <code>$output</code> parameter of <code>exec()</code> or else PHP will hang (probably until the process completes).</p>\n"
},
{
"answer_id": 71655444,
"author": "Justin Jack",
"author_id": 1678210,
"author_profile": "https://Stackoverflow.com/users/1678210",
"pm_score": 0,
"selected": false,
"text": "<p>New answer to an old question. Using <a href=\"https://github.com/justincjack/phpthreads\" rel=\"nofollow noreferrer\">this library</a>, the following code would spawn an asynchronous/parallel PHPThread to do background work.</p>\n<ul>\n<li>Must have pcntl, posix, and socket extensions</li>\n<li>Designed for/tested in CLI mode.</li>\n</ul>\n<p>EZ code sample:</p>\n<pre><code> function threadproc($thread, $param) {\n \n echo "\\tI'm a PHPThread. In this example, I was given only one parameter: \\"". print_r($param, true) ."\\" to work with, but I can accept as many as you'd like!\\n";\n \n for ($i = 0; $i < 10; $i++) {\n usleep(1000000);\n echo "\\tPHPThread working, very busy...\\n";\n }\n \n return "I'm a return value!";\n}\n \n\n$thread_id = phpthread_create($thread, array(), "threadproc", null, array("123456"));\n \necho "I'm the main thread doing very important work!\\n";\n \nfor ($n = 0; $n < 5; $n++) {\n usleep(1000000);\n echo "Main thread...working!\\n";\n}\n \necho "\\nMain thread done working. Waiting on our PHPThread...\\n";\n \nphpthread_join($thread_id, $retval);\n \necho "\\n\\nOur PHPThread returned: " . print_r($retval, true) . "!\\n";\n</code></pre>\n"
},
{
"answer_id": 73118719,
"author": "Dev Matee",
"author_id": 3743412,
"author_profile": "https://Stackoverflow.com/users/3743412",
"pm_score": 0,
"selected": false,
"text": "<h2>From PHP official documentation(php.net)</h2>\n<pre><code><?php\nfunction execInBackground($cmd) {\n if (substr(php_uname(), 0, 7) == "Windows"){\n pclose(popen("start /B ". $cmd, "r")); \n }\n else {\n exec($cmd . " > /dev/null &"); \n }\n}\n?>\n</code></pre>\n"
}
] | 2008/09/05 | [
"https://Stackoverflow.com/questions/45953",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1071/"
] | I need to execute a directory copy upon a user action, but the directories are quite large, so I would like to be able to perform such an action without the user being aware of the time it takes for the copy to complete.
Any suggestions would be much appreciated. | Assuming this is running on a Linux machine, I've always handled it like this:
```
exec(sprintf("%s > %s 2>&1 & echo $! >> %s", $cmd, $outputfile, $pidfile));
```
This launches the command `$cmd`, redirects the command output to `$outputfile`, and writes the process id to `$pidfile`.
That lets you easily monitor what the process is doing and if it's still running.
```
function isRunning($pid){
try{
$result = shell_exec(sprintf("ps %d", $pid));
if( count(preg_split("/\n/", $result)) > 2){
return true;
}
}catch(Exception $e){}
return false;
}
``` |
45,964 | <p>How do I multiply 10 to an <code>Integer</code> object and get back the <code>Integer</code> object?</p>
<p>I am looking for the neatest way of doing this.</p>
<p>I would probably do it this way:
Get int from <code>Integer</code> object, multiply it with the other int and create another Integer object with this int value.</p>
<p>Code will be something like ... </p>
<pre><code>integerObj = new Integer(integerObj.intValue() * 10);
</code></pre>
<p>But, I saw a code where the author is doing it this way: Get the <code>String</code> from the <code>Integer</code> object, concatenate "0" at the end and then get <code>Integer</code> object back by using <code>Integer.parseInt</code></p>
<p>The code is something like this:</p>
<pre><code>String s = integerObj + "0";
integerObj = Integer.parseInt(s);
</code></pre>
<p>Is there any merit in doing it either way?</p>
<p>And what would be the most efficient/neatest way in general and in this case?</p>
| [
{
"answer_id": 45973,
"author": "Matt Sheppard",
"author_id": 797,
"author_profile": "https://Stackoverflow.com/users/797",
"pm_score": 3,
"selected": false,
"text": "<p>The string approach is amusing, but almost certainly a bad way to do it.</p>\n\n<p>Getting the int value of an Integer, and creating a new one will be very fast, where as parseInt would be fairly expensive to call.</p>\n\n<p>Overall, I'd agree with your original approach (which, as others have pointed out, can be done without so much clutter if you have autoboxing as introduced in Java 5).</p>\n"
},
{
"answer_id": 45975,
"author": "toolkit",
"author_id": 3295,
"author_profile": "https://Stackoverflow.com/users/3295",
"pm_score": 6,
"selected": true,
"text": "<p>With Java 5's <a href=\"http://java.sun.com/j2se/1.5.0/docs/guide/language/autoboxing.html\" rel=\"nofollow noreferrer\">autoboxing</a>, you can simply do:</p>\n\n<pre><code>Integer a = new Integer(2); // or even just Integer a = 2;\na *= 10;\nSystem.out.println(a);\n</code></pre>\n"
},
{
"answer_id": 45980,
"author": "Galbrezu",
"author_id": 1419,
"author_profile": "https://Stackoverflow.com/users/1419",
"pm_score": 1,
"selected": false,
"text": "<p>Keep away from the second approach, best bet would be the autoboxing if you're using java 1.5, anything earlier your first example would be best.</p>\n"
},
{
"answer_id": 45981,
"author": "Clokey",
"author_id": 2438,
"author_profile": "https://Stackoverflow.com/users/2438",
"pm_score": 1,
"selected": false,
"text": "<p>The solution using the String method is not so good for a variety of reasons. Some are aesthetic reasons others are practical. </p>\n\n<p>On a practical front more objects get created by the String version than the more normal form (as you have expressed in your first example).</p>\n\n<p>On an aesthetic note, I think that the second version obscures the intent of the code and that is nearly as important as getting it to produce the result you want.</p>\n"
},
{
"answer_id": 46424,
"author": "ckpwong",
"author_id": 2551,
"author_profile": "https://Stackoverflow.com/users/2551",
"pm_score": 2,
"selected": false,
"text": "<p>The problem with the second way is the way Strings are handled in Java:</p>\n\n<ul>\n<li><code>\"0\"</code> is converted into a constant String object at compile time.</li>\n<li><p>Each time this code is called, <code>s</code> is constructed as a new String object, and <code>javac</code> converts that code to <code>String s = new StringBuilder().append(integerObj.toString()).append(\"0\").toString()</code> (StringBuffer for older versions). Even if you use the same <code>integerObj</code>, i.e.,</p>\n\n<p><code>String s1 = integerObj + \"0\";\n String s2 = integerObj + \"0\";</code></p>\n\n<p><code>(s1 == s2)</code> would be <code>false</code>, while <code>s1.equals(s2)</code> would be <code>true</code>.</p></li>\n<li><p><code>Integer.parseInt</code> internally calls <code>new Integer()</code> anyway, because <code>Integer</code> is immutable.</p></li>\n</ul>\n\n<p>BTW, autoboxing/unboxing is internally the same as the first method.</p>\n"
},
{
"answer_id": 24281194,
"author": "Chris",
"author_id": 1460848,
"author_profile": "https://Stackoverflow.com/users/1460848",
"pm_score": 0,
"selected": false,
"text": "<p>toolkit's answer above is correct and the best way, but it doesn't give a full explanation of what is happening.\nAssuming Java 5 or later:</p>\n\n<pre><code>Integer a = new Integer(2); // or even just Integer a = 2;\na *= 10;\nSystem.out.println(a); // will output 20\n</code></pre>\n\n<p>What you need to know is that this is the exact same as doing:</p>\n\n<pre><code>Integer a = new Integer(2); // or even just Integer a = 2;\na = a.intValue() * 10;\nSystem.out.println(a.intValue()); // will output 20\n</code></pre>\n\n<p>By performing the operation (in this case *=) on the object 'a', you are not changing the int value inside the 'a' object, but actually assigning a new object to 'a'.\nThis is because 'a' gets auto-unboxed in order to perform the multiplication, and then the result of the multiplication gets auto-boxed and assigned to 'a'.</p>\n\n<p>Integer is an immutable object. (All wrapper classes are immutable.)</p>\n\n<p>Take for example this piece of code:</p>\n\n<pre><code>static void test() {\n Integer i = new Integer(10);\n System.out.println(\"StartingMemory: \" + System.identityHashCode(i));\n changeInteger(i);\n System.out.println(\"Step1: \" + i);\n changeInteger(++i);\n System.out.println(\"Step2: \" + i.intValue());\n System.out.println(\"MiddleMemory: \" + System.identityHashCode(i));\n}\n\nstatic void changeInteger(Integer i) {\n System.out.println(\"ChangeStartMemory: \" + System.identityHashCode(i));\n System.out.println(\"ChangeStartValue: \" + i);\n i++;\n System.out.println(\"ChangeEnd: \" + i);\n System.out.println(\"ChangeEndMemory: \" + System.identityHashCode(i));\n}\n</code></pre>\n\n<p>The output will be:</p>\n\n<pre><code>StartingMemory: 1373539035\nChangeStartMemory: 1373539035\nChangeStartValue: 10\nChangeEnd: 11\nChangeEndMemory: 190331520\nStep1: 10\nChangeStartMemory: 190331520\nChangeStartValue: 11\nChangeEnd: 12\nChangeEndMemory: 1298706257\nStep2: 11\nMiddleMemory: 190331520\n</code></pre>\n\n<p>You can see the memory address for 'i' is changing (your memory addresses will be different).</p>\n\n<p>Now lets do a little test with reflection, add this onto the end of the test() method:</p>\n\n<pre><code>System.out.println(\"MiddleMemory: \" + System.identityHashCode(i));\ntry {\n final Field f = i.getClass().getDeclaredField(\"value\");\n f.setAccessible(true);\n f.setInt(i, 15);\n System.out.println(\"Step3: \" + i.intValue());\n System.out.println(\"EndingMemory: \" + System.identityHashCode(i));\n} catch (final Exception e) {\n e.printStackTrace();\n}\n</code></pre>\n\n<p>The additional output will be:</p>\n\n<pre><code>MiddleMemory: 190331520\nStep2: 15\nMiddleMemory: 190331520\n</code></pre>\n\n<p>You can see that the memory address for 'i' did not change, even though we changed its value using reflection.<br>\n(DO NOT USE REFLECTION THIS WAY IN REAL LIFE!!)</p>\n"
}
] | 2008/09/05 | [
"https://Stackoverflow.com/questions/45964",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4406/"
] | How do I multiply 10 to an `Integer` object and get back the `Integer` object?
I am looking for the neatest way of doing this.
I would probably do it this way:
Get int from `Integer` object, multiply it with the other int and create another Integer object with this int value.
Code will be something like ...
```
integerObj = new Integer(integerObj.intValue() * 10);
```
But, I saw a code where the author is doing it this way: Get the `String` from the `Integer` object, concatenate "0" at the end and then get `Integer` object back by using `Integer.parseInt`
The code is something like this:
```
String s = integerObj + "0";
integerObj = Integer.parseInt(s);
```
Is there any merit in doing it either way?
And what would be the most efficient/neatest way in general and in this case? | With Java 5's [autoboxing](http://java.sun.com/j2se/1.5.0/docs/guide/language/autoboxing.html), you can simply do:
```
Integer a = new Integer(2); // or even just Integer a = 2;
a *= 10;
System.out.println(a);
``` |
45,988 | <p>In a C# .NET 3.5 app (a mix of WinForms and WPF) I want to let the user select a folder to import a load of data from. At the moment, it's using <code>System.Windows.Forms.FolderBrowserDialog</code> but that's a bit lame. Mainly because you can't type the path into it (so you need to map a network drive, instead of typing a UNC path).</p>
<p>I'd like something more like the <code>System.Windows.Forms.OpenFileDialog</code>, but for folders instead of files. </p>
<p>What can I use instead? A WinForms or WPF solution is fine, but I'd prefer not to PInvoke into the Windows API if I can avoid it.</p>
| [
{
"answer_id": 45994,
"author": "aku",
"author_id": 1196,
"author_profile": "https://Stackoverflow.com/users/1196",
"pm_score": 1,
"selected": false,
"text": "<p>Unfortunately there are no dialogs other than FolderBrowserDialog for folder selection. You need to create this dialog yourself or use PInvoke.</p>\n"
},
{
"answer_id": 46150,
"author": "OwenP",
"author_id": 2547,
"author_profile": "https://Stackoverflow.com/users/2547",
"pm_score": 0,
"selected": false,
"text": "<p>So far, based on the lack of responses to <a href=\"https://stackoverflow.com/questions/31059/how-do-you-configure-an-openfiledialog-to-select-folders\">my identical question</a>, I'd assume the answer is to roll your own dialog from scratch.</p>\n\n<p>I've seen things here and there about subclassing the common dialogs from VB6 and I think this might be part of the solution, but I've never seen anything about modifying what the dialog thinks it's selecting. It'd be possible through .NET via PInvoke and some other tricks, but I have yet to see code that does it.</p>\n\n<p>I <em>know</em> it's possible and it's not Vista-specific because Visual Studio has done it since VS 2003.</p>\n\n<p>Here's hoping someone answers either yours or mine!</p>\n"
},
{
"answer_id": 625057,
"author": "Cheeso",
"author_id": 48082,
"author_profile": "https://Stackoverflow.com/users/48082",
"pm_score": 6,
"selected": true,
"text": "<p>Don't create it yourself! It's been done. You can use <a href=\"http://dotnetzip.codeplex.com/SourceControl/changeset/view/29832#432677\" rel=\"nofollow noreferrer\">FolderBrowserDialogEx</a> - \na re-usable derivative of the built-in FolderBrowserDialog. This one allows you to type in a path, even a UNC path. You can also browse for computers or printers with it. Works just like the built-in FBD, but ... better. </p>\n\n<p>Full Source code. Free. MS-Public license.</p>\n\n<p><img src=\"https://i.stack.imgur.com/V1caf.png\" alt=\"FolderBrowserDialogEx\"></p>\n\n<p>Code to use it: </p>\n\n<pre><code>var dlg1 = new Ionic.Utils.FolderBrowserDialogEx();\ndlg1.Description = \"Select a folder to extract to:\";\ndlg1.ShowNewFolderButton = true;\ndlg1.ShowEditBox = true;\n//dlg1.NewStyle = false;\ndlg1.SelectedPath = txtExtractDirectory.Text;\ndlg1.ShowFullPathInEditBox = true;\ndlg1.RootFolder = System.Environment.SpecialFolder.MyComputer;\n\n// Show the FolderBrowserDialog.\nDialogResult result = dlg1.ShowDialog();\nif (result == DialogResult.OK)\n{\n txtExtractDirectory.Text = dlg1.SelectedPath;\n}\n</code></pre>\n"
},
{
"answer_id": 17010941,
"author": "Alex Essilfie",
"author_id": 117870,
"author_profile": "https://Stackoverflow.com/users/117870",
"pm_score": 0,
"selected": false,
"text": "<p>After hours of searching for a similar solution I found <a href=\"https://stackoverflow.com/a/15456640/117870\">this answer</a> by <a href=\"https://stackoverflow.com/users/353094/leetnightshade\">leetNightShade</a> to <a href=\"http://www.lyquidity.com/devblog/?p=136\" rel=\"nofollow noreferrer\" title=\".NET Win 7-style folder select dialog\">a working solution</a>.</p>\n\n<p>There are three things I believe make this solution much better than all the others.</p>\n\n<ol>\n<li><strong>It is simple to use.</strong> \nIt only requires you include two files (which can be combined to one anyway) in your project.</li>\n<li>It falls back to the standard <a href=\"http://msdn.microsoft.com/en-us/library/system.windows.forms.folderbrowserdialog.aspx\" rel=\"nofollow noreferrer\" title=\"FolderBrowserDialog Class (System.Windows.Forms)\">FolderBrowserDialog</a> when used on XP or older systems.</li>\n<li>The author grants permission to use the code for any purpose you deem fit.\n\n<blockquote>\n <p>There’s no license as such as you are free to take and do with the code what you will.</p>\n</blockquote></li>\n</ol>\n\n<p>Download the code <a href=\"http://www.lyquidity.com/devblog/?p=136\" rel=\"nofollow noreferrer\" title=\".NET Win 7-style folder select dialog\">here</a>.</p>\n"
}
] | 2008/09/05 | [
"https://Stackoverflow.com/questions/45988",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1367/"
] | In a C# .NET 3.5 app (a mix of WinForms and WPF) I want to let the user select a folder to import a load of data from. At the moment, it's using `System.Windows.Forms.FolderBrowserDialog` but that's a bit lame. Mainly because you can't type the path into it (so you need to map a network drive, instead of typing a UNC path).
I'd like something more like the `System.Windows.Forms.OpenFileDialog`, but for folders instead of files.
What can I use instead? A WinForms or WPF solution is fine, but I'd prefer not to PInvoke into the Windows API if I can avoid it. | Don't create it yourself! It's been done. You can use [FolderBrowserDialogEx](http://dotnetzip.codeplex.com/SourceControl/changeset/view/29832#432677) -
a re-usable derivative of the built-in FolderBrowserDialog. This one allows you to type in a path, even a UNC path. You can also browse for computers or printers with it. Works just like the built-in FBD, but ... better.
Full Source code. Free. MS-Public license.

Code to use it:
```
var dlg1 = new Ionic.Utils.FolderBrowserDialogEx();
dlg1.Description = "Select a folder to extract to:";
dlg1.ShowNewFolderButton = true;
dlg1.ShowEditBox = true;
//dlg1.NewStyle = false;
dlg1.SelectedPath = txtExtractDirectory.Text;
dlg1.ShowFullPathInEditBox = true;
dlg1.RootFolder = System.Environment.SpecialFolder.MyComputer;
// Show the FolderBrowserDialog.
DialogResult result = dlg1.ShowDialog();
if (result == DialogResult.OK)
{
txtExtractDirectory.Text = dlg1.SelectedPath;
}
``` |
45,991 | <p>I'm building a website that requires very basic markup capabilities. I can't use any 3rd party plugins, so I just need a simple way to convert markup to HTML. I might have a total of 3 tags that I'll allow.</p>
<p>What is the best way to convert <code>==Heading==</code> to <code><h2>Heading</h2></code>, or <code>--bold--</code> to <code><b>bold</b></code>? Can this be done simply with Regex, or does somebody have a simple function?</p>
<p>I'm writing this in C#, but examples from other languages would probably work.</p>
| [
{
"answer_id": 45998,
"author": "Matt Sheppard",
"author_id": 797,
"author_profile": "https://Stackoverflow.com/users/797",
"pm_score": 3,
"selected": true,
"text": "<p>It's not really a simple problem, because if you're going to display things back to the user, you'll need to also sanitise the input to ensure you don't create any <a href=\"http://en.wikipedia.org/wiki/Cross-site_scripting\" rel=\"nofollow noreferrer\">cross site scripting</a> vulnerabilities.</p>\n\n<p>That said, you could probably do something pretty simple as you describe most easily with a regular expression replacement.</p>\n\n<p>For example</p>\n\n<pre><code>replace the pattern ==([^=]*)== with <h2>\\1</h2>\n</code></pre>\n"
},
{
"answer_id": 46006,
"author": "pix0r",
"author_id": 72,
"author_profile": "https://Stackoverflow.com/users/72",
"pm_score": 1,
"selected": false,
"text": "<p>This really depends on the Wiki syntax you're using as there are several different ones. Obviously the wiki software has this functionality somewhere; if you can't find a software package that does this for you, you could start looking for the relevant code in your wiki software.</p>\n"
},
{
"answer_id": 20462306,
"author": "wener",
"author_id": 1870054,
"author_profile": "https://Stackoverflow.com/users/1870054",
"pm_score": 1,
"selected": false,
"text": "<p>Maybe <a href=\"http://www.mediawiki.org/wiki/Alternative_parsers\" rel=\"nofollow\">this</a> is what you need.</p>\n\n<blockquote>\n <p>This page is a compilation of links, descriptions, and status reports of the various alternative MediaWiki parsers — that is, programs and projects, other than MediaWiki itself, which are able or intended to translate MediaWiki's text markup syntax into something else.</p>\n</blockquote>\n"
}
] | 2008/09/05 | [
"https://Stackoverflow.com/questions/45991",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/681/"
] | I'm building a website that requires very basic markup capabilities. I can't use any 3rd party plugins, so I just need a simple way to convert markup to HTML. I might have a total of 3 tags that I'll allow.
What is the best way to convert `==Heading==` to `<h2>Heading</h2>`, or `--bold--` to `<b>bold</b>`? Can this be done simply with Regex, or does somebody have a simple function?
I'm writing this in C#, but examples from other languages would probably work. | It's not really a simple problem, because if you're going to display things back to the user, you'll need to also sanitise the input to ensure you don't create any [cross site scripting](http://en.wikipedia.org/wiki/Cross-site_scripting) vulnerabilities.
That said, you could probably do something pretty simple as you describe most easily with a regular expression replacement.
For example
```
replace the pattern ==([^=]*)== with <h2>\1</h2>
``` |
46,003 | <p>How can I change default <a href="http://msdn.microsoft.com/en-us/library/3a7hkh29.aspx" rel="nofollow noreferrer">Generate Method Stub</a> behavior in Visaul Studio to generate method with body</p>
<pre><code>throw new NotImplementedException();
</code></pre>
<p>instead of </p>
<pre><code>throw new Exception("The method or operation is not implemented.");
</code></pre>
| [
{
"answer_id": 46016,
"author": "Sam Wessel",
"author_id": 4734,
"author_profile": "https://Stackoverflow.com/users/4734",
"pm_score": 4,
"selected": true,
"text": "<p>Taken from: <a href=\"http://blogs.msdn.com/ansonh/archive/2005/12/08/501763.aspx\" rel=\"noreferrer\">http://blogs.msdn.com/ansonh/archive/2005/12/08/501763.aspx</a></p>\n\n<blockquote>\n <p>Visual Studio 2005 supports targeting the 1.0 version of the compact framework. In order to keep the size of the compact framework small, it does not include all of the same types that exist in the desktop framework. One of the types that is not included is NotImplementedException. </p>\n</blockquote>\n\n<p>You can change the generated code by editing the code snippet file:\n<strong>C:\\Program Files\\Microsoft Visual Studio 8\\VC#\\Snippets\\1033\\Refactoring\\MethodStub.snippet</strong> and changing the Declarations section to the following:</p>\n\n<pre><code> <Declarations>\n <Literal Editable=\"true\">\n <ID>signature</ID>\n <Default>signature</Default>\n </Literal>\n <Literal>\n <ID>Exception</ID>\n <Function>SimpleTypeName(global::System.NotImplementedException)</Function>\n </Literal>\n </Declarations>\n</code></pre>\n"
},
{
"answer_id": 46070,
"author": "Brad Wilson",
"author_id": 1554,
"author_profile": "https://Stackoverflow.com/users/1554",
"pm_score": 1,
"selected": false,
"text": "<p>There's another reason: FxCop catches instances of anybody throwing 'Exception' and flags it, but throwing instances of 'NotImplementedException' is acceptable.</p>\n\n<p>I actually like the default behavior, because it does have this differentiation. NotImplementedException is not a temporary exception to be thrown while you're working your way through your code. It implies \"I mean it, I'm <em>really</em> not going to implement this thing\". If you leave the codegen the way it is, it's easy for you to differentiate in the code the \"I will come back to this later\" bits from \"I've decided not to do this\" bits.</p>\n"
}
] | 2008/09/05 | [
"https://Stackoverflow.com/questions/46003",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2361/"
] | How can I change default [Generate Method Stub](http://msdn.microsoft.com/en-us/library/3a7hkh29.aspx) behavior in Visaul Studio to generate method with body
```
throw new NotImplementedException();
```
instead of
```
throw new Exception("The method or operation is not implemented.");
``` | Taken from: <http://blogs.msdn.com/ansonh/archive/2005/12/08/501763.aspx>
>
> Visual Studio 2005 supports targeting the 1.0 version of the compact framework. In order to keep the size of the compact framework small, it does not include all of the same types that exist in the desktop framework. One of the types that is not included is NotImplementedException.
>
>
>
You can change the generated code by editing the code snippet file:
**C:\Program Files\Microsoft Visual Studio 8\VC#\Snippets\1033\Refactoring\MethodStub.snippet** and changing the Declarations section to the following:
```
<Declarations>
<Literal Editable="true">
<ID>signature</ID>
<Default>signature</Default>
</Literal>
<Literal>
<ID>Exception</ID>
<Function>SimpleTypeName(global::System.NotImplementedException)</Function>
</Literal>
</Declarations>
``` |
46,004 | <p>We are trying to implement a REST API for an application we have now. We want to expose read/write capabilities for various resources using the REST API. How do we implement the "form" part of this? I get how to expose "read" of our data by creating RESTful URLs that essentially function as method calls and return the data:</p>
<pre><code>GET /restapi/myobject?param=object-id-maybe
</code></pre>
<p>...and an XML document representing some data structure is returned. Fine.</p>
<p>But, normally, in a web application, an "edit" would involve two requests: one to load the current version of the resources and populate the form with that data, and one to post the modified data back. </p>
<p>But I don't get how you would do the same thing with HTTP methods that REST is sort of mapped to. It's a PUT, right? Can someone explain this?</p>
<p>(Additional consideration: The UI would be primarily done with AJAX)</p>
<p>--
Update: That definitely helps. But, I am still a bit confused about the server side? Obviously, I am not simply dealing with files here. On the server, the code that answers the requests should be filtering the request method to determine what to do with it? Is that the "switch" between reads and writes?</p>
| [
{
"answer_id": 46014,
"author": "Matt Sheppard",
"author_id": 797,
"author_profile": "https://Stackoverflow.com/users/797",
"pm_score": 0,
"selected": false,
"text": "<p>The load should just be a normal GET request, and the saving of new data should be a POST to the URL which currently has the data...</p>\n\n<p>For example, load the current data from <a href=\"http://www.example.com/record/matt-s-example\" rel=\"nofollow noreferrer\">http://www.example.com/record/matt-s-example</a> and then, change the data, and POST back to the same URL with the new data.</p>\n\n<p>A PUT request could be used when creating a new record (i.e. PUT the data at a URL which doesn't currently exist), but in practice just POSTing is probably a better approach to get started with.</p>\n"
},
{
"answer_id": 46015,
"author": "Mark Cidade",
"author_id": 1659,
"author_profile": "https://Stackoverflow.com/users/1659",
"pm_score": 3,
"selected": true,
"text": "<p>If you're submitting the data via plain HTML, you're restricted to doing a POST based form. The URI that the POST request is sent to <strong>should not</strong> be the URI for the resource being modified. You should either POST to a collection resource that ADDs a newly created resource each time (with the URI for the new resource in the <em>Location</em> header and a <strong>202</strong> status code) or POST to an updater resource that updates a resource with a supplied URI in the request's content (or custom header).</p>\n\n<p>If you're using an XmlHttpRequest object, you can set the method to PUT and submit the data to the resource's URI. This can also work with empty forms if the server supplies a valid URI for the yet-nonexistent resource. The first PUT would create the resource (returning <strong>202</strong>). Subsequent PUTs will either do nothing if it's the same data or modify the existing resource (in either case a <strong>200</strong> is returned unless an error occurs).</p>\n"
},
{
"answer_id": 46056,
"author": "Brad Wilson",
"author_id": 1554,
"author_profile": "https://Stackoverflow.com/users/1554",
"pm_score": 2,
"selected": false,
"text": "<p>I think you need to separate data services from web UI. When providing data services, a RESTful system is entirely appropriate, including the use of verbs that browsers can't support (like PUT and DELETE).</p>\n\n<p>When describing a UI, I think most people confuse \"RESTful\" with \"nice, predictable URLs\". I wouldn't be all that worried about a purely RESTful URL syntax when you're describing web UI.</p>\n"
},
{
"answer_id": 176639,
"author": "Alexandros Marinos",
"author_id": 24461,
"author_profile": "https://Stackoverflow.com/users/24461",
"pm_score": 4,
"selected": false,
"text": "<p>There are many different alternatives you can use. A good solution is provided at the <a href=\"http://microformats.org/wiki/rest/urls\" rel=\"nofollow noreferrer\">microformats wiki</a> and has also been referenced by the RESTful JSON crew. As close as you can get to a standard, really.</p>\n\n<pre><code> Operate on a Record\n\nGET /people/1\n return the first record \nDELETE /people/1\n destroy the first record \nPOST /people/1?_method=DELETE\n alias for DELETE, to compensate for browser limitations \n\nGET /people/1/edit\n return a form to edit the first record \nPUT /people/1\n submit fields for updating the first record \nPOST /people/1?_method=PUT\n alias for PUT, to compensate for browser limitations \n</code></pre>\n"
}
] | 2008/09/05 | [
"https://Stackoverflow.com/questions/46004",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/577/"
] | We are trying to implement a REST API for an application we have now. We want to expose read/write capabilities for various resources using the REST API. How do we implement the "form" part of this? I get how to expose "read" of our data by creating RESTful URLs that essentially function as method calls and return the data:
```
GET /restapi/myobject?param=object-id-maybe
```
...and an XML document representing some data structure is returned. Fine.
But, normally, in a web application, an "edit" would involve two requests: one to load the current version of the resources and populate the form with that data, and one to post the modified data back.
But I don't get how you would do the same thing with HTTP methods that REST is sort of mapped to. It's a PUT, right? Can someone explain this?
(Additional consideration: The UI would be primarily done with AJAX)
--
Update: That definitely helps. But, I am still a bit confused about the server side? Obviously, I am not simply dealing with files here. On the server, the code that answers the requests should be filtering the request method to determine what to do with it? Is that the "switch" between reads and writes? | If you're submitting the data via plain HTML, you're restricted to doing a POST based form. The URI that the POST request is sent to **should not** be the URI for the resource being modified. You should either POST to a collection resource that ADDs a newly created resource each time (with the URI for the new resource in the *Location* header and a **202** status code) or POST to an updater resource that updates a resource with a supplied URI in the request's content (or custom header).
If you're using an XmlHttpRequest object, you can set the method to PUT and submit the data to the resource's URI. This can also work with empty forms if the server supplies a valid URI for the yet-nonexistent resource. The first PUT would create the resource (returning **202**). Subsequent PUTs will either do nothing if it's the same data or modify the existing resource (in either case a **200** is returned unless an error occurs). |
46,029 | <p>If I have a collection of database tables (in an Access file, for example) and need to validate each table in this collection against a rule set that has both common rules across all tables as well as individual rules specific to one or a subset of tables, can someone recommend a good design pattern to look into?</p>
<p>Specifically, I would like to avoid code similar to:</p>
<pre><code>void Main()
{
ValidateTable1();
ValidateTable2();
ValidateTable3();
}
private void ValidateTable1()
{
//Table1 validation code goes here
}
private void ValidateTable2()
{
//Table2 validation code goes here
}
private void ValidateTable3()
{
//Table3 validation code goes here
}
</code></pre>
<p>Also, I've decided to use log4net to log all of the errors and warnings, so that each method can be declared <code>void</code> and doesn't need to return anything. Is this a good idea or would it be better to create some sort of <code>ValidationException</code> that catches all exceptions and stores them in a <code>List<ValidationException></code> before printing them all out at the end?</p>
<p>I did find <a href="http://www.hickorysystems.com/sw_validation.html" rel="noreferrer">this</a>, which looks like it may work, but I'm hoping to actually find some code samples to work off of. Any suggestions? Has anyone done something similar in the past?</p>
<p>For some background, the program will be written in either C# or VB.NET and the tables will more than likely be stored in either Access or SQL Server CE.</p>
| [
{
"answer_id": 46035,
"author": "Ben Scheirman",
"author_id": 3381,
"author_profile": "https://Stackoverflow.com/users/3381",
"pm_score": 3,
"selected": false,
"text": "<p>I'd return some type of ValidationSummary for each one... or an IList depending on how you want to structure it.</p>\n\n<p>you could also opt to do some magic like this:</p>\n\n<pre><code>using(var validation = new ValidationScope())\n{\n ValidateTable1();\n ValidateTable2();\n ValidateTable3();\n\n if(validation.Haserrors)\n {\n MessageBox.Show(validation.ValidationSummary);\n return;\n }\n\n DoSomethingElse();\n}\n</code></pre>\n\n<p>then the ValidateTable would just reach into the current scope, like this:</p>\n\n<pre><code>ValidationScope.Current.AddError(\"col1\", \"Col1 should not be NULL\");\n</code></pre>\n\n<p>something to that effect.</p>\n"
},
{
"answer_id": 72421,
"author": "jerhinesmith",
"author_id": 1108,
"author_profile": "https://Stackoverflow.com/users/1108",
"pm_score": 5,
"selected": true,
"text": "<p>Just an update on this: I decided to go with the <a href=\"http://en.wikipedia.org/wiki/Decorator_pattern\" rel=\"noreferrer\">Decorator pattern</a>. That is, I have one 'generic' table class that implements an <code>IValidateableTable</code> interface (which contains <code>validate()</code> method). Then, I created several validation decorators (that also <code>implement IValidateableTable</code>) which I can wrap around each table that I'm trying to validate.</p>\n\n<p>So, the code ends up looking like this:</p>\n\n<pre><code>IValidateableTable table1 = new GenericTable(myDataSet);\ntable1 = new NonNullNonEmptyColumnValidator(table1, \"ColumnA\");\ntable1 = new ColumnValueValidator(table1, \"ColumnB\", \"ExpectedValue\");\n</code></pre>\n\n<p>Then, all I need to do is call <code>table1.Validate()</code> which unwinds through the decorators calling all of the needed validations. So far, it seems to work really well, though I am still open to suggestions.</p>\n"
},
{
"answer_id": 111392,
"author": "David Robbins",
"author_id": 19799,
"author_profile": "https://Stackoverflow.com/users/19799",
"pm_score": 2,
"selected": false,
"text": "<p>Two approaches: </p>\n\n<ol>\n<li><a href=\"http://www.lhotka.net/cslanet/Default.aspx#\" rel=\"nofollow noreferrer\">CSLA</a> where anonymous methods on business objects are used for validation.</li>\n<li>Read <a href=\"http://blog.jpboodhoo.com/HandlingDynamicRulesAPrecursor.aspx\" rel=\"nofollow noreferrer\">JP Boodhoo's</a> blog where he has implemented a rules engine and has very detailed posts and sample code published. You can also see him at work on <a href=\"http://www.dnrtv.com/default.aspx?showNum=71\" rel=\"nofollow noreferrer\">DNR Tv</a> episode that's well worth watching.</li>\n</ol>\n"
},
{
"answer_id": 190640,
"author": "Galghamon",
"author_id": 26511,
"author_profile": "https://Stackoverflow.com/users/26511",
"pm_score": 1,
"selected": false,
"text": "<p>I think you are really talking about a concept called <a href=\"http://en.wikipedia.org/wiki/Database_constraints\" rel=\"nofollow noreferrer\">constraints</a> in the world of databases. Constraints are how a database guarantees the integrity of the data it contains. It makes much more sense to put this sort of logic in the database, rather than the application (even Access offers rudimentary forms of constraints, such as requiring uniqueness of values in a column, or values from a list, etc.).<br>\nInput validation (of individual fields) is of course a different matter, and any application should still perform that (to provide nice feedback to the user in case of problems), even if the DB has well-defined constraints of the table columns.</p>\n"
},
{
"answer_id": 44581032,
"author": "Andres A.",
"author_id": 170945,
"author_profile": "https://Stackoverflow.com/users/170945",
"pm_score": 2,
"selected": false,
"text": "<p>I would try with a combination of the Factory and Visitor patterns:</p>\n\n<pre><code>using System;\nusing System.Collections.Generic;\n\nnamespace Example2\n{\n interface IVisitor\n {\n void Visit(Table1 table1);\n void Visit(Table2 table2);\n }\n\n interface IVisitable\n {\n void Accept(IVisitor visitor);\n }\n\n interface ILog\n {\n void Verbose(string message);\n void Debug(string messsage);\n void Info(string message);\n void Error(string message);\n void Fatal(string message);\n }\n\n class Error\n {\n public string Message { get; set; }\n }\n\n class Table1 : IVisitable\n {\n public int Id { get; set; }\n public string Data { get; set; }\n private IList<Table2> InnerElements { get; } = new List<Table2>();\n\n public void Accept(IVisitor visitor)\n {\n visitor.Visit(this);\n\n foreach(var innerElement in InnerElements)\n visitor.Visit(innerElement);\n }\n }\n\n class Table2 : IVisitable\n {\n public int Id { get; set; }\n public int Data { get; set; }\n\n public void Accept(IVisitor visitor)\n {\n visitor.Visit(this);\n }\n }\n\n class Validator : IVisitor\n {\n private readonly ILog log;\n private readonly IRuleSet<Table1> table1Rules;\n private readonly IRuleSet<Table2> table2Rules;\n\n public Validator(ILog log, IRuleSet<Table1> table1Rules, IRuleSet<Table2> table2Rules)\n {\n this.log = log;\n this.table1Rules = table1Rules;\n this.table2Rules = table2Rules;\n }\n\n public void Visit(Table1 table1)\n {\n IEnumerable<Error> errors = table1Rules.EnforceOn(table1);\n\n foreach (var error in errors)\n log.Error(error.Message);\n }\n\n public void Visit(Table2 table2)\n {\n IEnumerable<Error> errors = table2Rules.EnforceOn(table2);\n\n foreach (var error in errors)\n log.Error(error.Message);\n }\n }\n\n class RuleSets\n {\n private readonly IRuleSetFactory factory;\n\n public RuleSets(IRuleSetFactory factory)\n {\n this.factory = factory;\n }\n\n public IRuleSet<Table1> RulesForTable1 =>\n factory.For<Table1>()\n .AddRule(o => string.IsNullOrEmpty(o.Data), \"Data1 is null or empty\")\n .AddRule(o => o.Data.Length < 10, \"Data1 is too short\")\n .AddRule(o => o.Data.Length > 26, \"Data1 is too long\");\n\n public IRuleSet<Table2> RulesForTable2 =>\n factory.For<Table2>()\n .AddRule(o => o.Data < 0, \"Data2 is negative\")\n .AddRule(o => o.Data > 10, \"Data2 is too big\");\n }\n\n interface IRuleSetFactory\n {\n IRuleSet<T> For<T>();\n }\n\n interface IRuleSet<T>\n {\n IEnumerable<Error> EnforceOn(T obj);\n IRuleSet<T> AddRule(Func<T, bool> rule, string description);\n }\n\n class Program\n {\n void Run()\n {\n var log = new ConsoleLogger();\n var factory = new SimpleRules();\n var rules = new RuleSets(factory);\n var validator = new Validator(log, rules.RulesForTable1, rules.RulesForTable2);\n\n var toValidate = new List<IVisitable>();\n toValidate.Add(new Table1());\n toValidate.Add(new Table2());\n\n foreach (var validatable in toValidate)\n validatable.Accept(validator);\n }\n }\n}\n</code></pre>\n"
}
] | 2008/09/05 | [
"https://Stackoverflow.com/questions/46029",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1108/"
] | If I have a collection of database tables (in an Access file, for example) and need to validate each table in this collection against a rule set that has both common rules across all tables as well as individual rules specific to one or a subset of tables, can someone recommend a good design pattern to look into?
Specifically, I would like to avoid code similar to:
```
void Main()
{
ValidateTable1();
ValidateTable2();
ValidateTable3();
}
private void ValidateTable1()
{
//Table1 validation code goes here
}
private void ValidateTable2()
{
//Table2 validation code goes here
}
private void ValidateTable3()
{
//Table3 validation code goes here
}
```
Also, I've decided to use log4net to log all of the errors and warnings, so that each method can be declared `void` and doesn't need to return anything. Is this a good idea or would it be better to create some sort of `ValidationException` that catches all exceptions and stores them in a `List<ValidationException>` before printing them all out at the end?
I did find [this](http://www.hickorysystems.com/sw_validation.html), which looks like it may work, but I'm hoping to actually find some code samples to work off of. Any suggestions? Has anyone done something similar in the past?
For some background, the program will be written in either C# or VB.NET and the tables will more than likely be stored in either Access or SQL Server CE. | Just an update on this: I decided to go with the [Decorator pattern](http://en.wikipedia.org/wiki/Decorator_pattern). That is, I have one 'generic' table class that implements an `IValidateableTable` interface (which contains `validate()` method). Then, I created several validation decorators (that also `implement IValidateableTable`) which I can wrap around each table that I'm trying to validate.
So, the code ends up looking like this:
```
IValidateableTable table1 = new GenericTable(myDataSet);
table1 = new NonNullNonEmptyColumnValidator(table1, "ColumnA");
table1 = new ColumnValueValidator(table1, "ColumnB", "ExpectedValue");
```
Then, all I need to do is call `table1.Validate()` which unwinds through the decorators calling all of the needed validations. So far, it seems to work really well, though I am still open to suggestions. |
46,030 | <p>So, I did search google and SO prior to asking this question. Basically I have a DLL that has a form compiled into it. The form will be used to display information to the screen. Eventually it will be asynchronous and expose a lot of customization in the dll. For now I just want it to display properly. The problem that I am having is that I use the dll by loading it in a Powershell session. So when I try to display the form and get it to come to the top and have focus, It has no problem with displaying over all the other apps, but I can't for the life of me get it to display over the Powershell window. Here is the code that I am currently using to try and get it to display. I am sure that the majority of it won't be required once I figure it out, this just represents all the things that I found via google.</p>
<pre><code>CLass Blah
{
[DllImport("user32.dll", EntryPoint = "SystemParametersInfo")]
public static extern bool SystemParametersInfo(uint uiAction, uint uiParam, uint pvParam, uint fWinIni);
[DllImport("user32.dll", EntryPoint = "SetForegroundWindow")]
public static extern bool SetForegroundWindow(IntPtr hWnd);
[DllImport("User32.dll", EntryPoint = "ShowWindowAsync")]
private static extern bool ShowWindowAsync(IntPtr hWnd, int cmdShow);
private const int WS_SHOWNORMAL = 1;
public void ShowMessage(string msg)
{
MessageForm msgFrm = new MessageForm();
msgFrm.lblMessage.Text = "FOO";
msgFrm.ShowDialog();
msgFrm.BringToFront();
msgFrm.TopMost = true;
msgFrm.Activate();
SystemParametersInfo((uint)0x2001, 0, 0, 0x0002 | 0x0001);
ShowWindowAsync(msgFrm.Handle, WS_SHOWNORMAL);
SetForegroundWindow(msgFrm.Handle);
SystemParametersInfo((uint)0x2001, 200000, 200000, 0x0002 | 0x0001);
}
}
</code></pre>
<p>As I say I'm sure that most of that is either not needed or even flat out wrong, I just wanted to show the things that I had tried. Also, as I mentioned, I plan to have this be asynchronously displayed at some point which I suspect will wind up requiring a separate thread. Would splitting the form out into it's own thread make it easier to cause it to get focus over the Powershell session? </p>
<hr>
<p>@Joel, thanks for the info. Here is what I tried based on your suggestion:</p>
<pre><code>msgFrm.ShowDialog();
msgFrm.BringToFront();
msgFrm.Focus();
Application.DoEvents();
</code></pre>
<p>The form still comes up <em>under</em> the Powershell session. I'll proceed with working out the threading. I've spawned threads before but never where the parent thread needed to talk to the child thread, so we'll see how it goes.</p>
<p>Thnks for all the ideas so far folks.</p>
<hr>
<p>Ok, threading it took care of the problem. @Quarrelsome, I did try both of those. Neither (nor both together) worked. I am curious as to what is evil about using threading? I am not using Application.Run and I have yet to have a problem. I am using a mediator class that both the parent thread and the child thread have access to. In that object I am using a ReaderWriterLock to lock one property that represents the message that I want displayed on the form that the child thread creates. The parent locks the property then writes what should be displayed. The child thread locks the property and reads what it should change the label on the form to. The child has to do this on a polling interval (I default it to 500ms) which I'm not real happy about, but I could not find an event driven way to let the child thread know that the proerty had changed, so I'm stuck with polling.</p>
| [
{
"answer_id": 46092,
"author": "Dean Hill",
"author_id": 3106,
"author_profile": "https://Stackoverflow.com/users/3106",
"pm_score": 5,
"selected": true,
"text": "<p>I also had trouble activating and bringing a window to the foreground. Here is the code that eventually worked for me. I'm not sure if it will solve your problem.</p>\n\n<p>Basically, call ShowWindow() then SetForegroundWindow().</p>\n\n<pre><code>using System.Diagnostics;\nusing System.Runtime.InteropServices;\n\n// Sets the window to be foreground\n[DllImport(\"User32\")]\nprivate static extern int SetForegroundWindow(IntPtr hwnd);\n\n// Activate or minimize a window\n[DllImportAttribute(\"User32.DLL\")]\nprivate static extern bool ShowWindow(IntPtr hWnd, int nCmdShow);\nprivate const int SW_SHOW = 5;\nprivate const int SW_MINIMIZE = 6;\nprivate const int SW_RESTORE = 9;\n\nprivate void ActivateApplication(string briefAppName)\n{\n Process[] procList = Process.GetProcessesByName(briefAppName);\n\n if (procList.Length > 0)\n {\n ShowWindow(procList[0].MainWindowHandle, SW_RESTORE);\n SetForegroundWindow(procList[0].MainWindowHandle);\n }\n}\n</code></pre>\n"
},
{
"answer_id": 46187,
"author": "Joel Coehoorn",
"author_id": 3043,
"author_profile": "https://Stackoverflow.com/users/3043",
"pm_score": 0,
"selected": false,
"text": "<p>You shouldn't need to import any win32 functions for this. If .Focus() isn't enough the form should also have a .BringToFront() method you can use. If that fails, you can set it's .TopMost property to true. You don't want to <em>leave</em> it true forever, so then call Application.DoEvents so the form can process that message and set it back to false.</p>\n"
},
{
"answer_id": 46467,
"author": "sieben",
"author_id": 1147,
"author_profile": "https://Stackoverflow.com/users/1147",
"pm_score": 2,
"selected": false,
"text": "<p>Doesn't <strong>ShowDialog()</strong> have different window behavior than just <strong>Show()</strong>?</p>\n\n<p>What if you tried:</p>\n\n<pre><code>msgFrm.Show();\nmsgFrm.BringToFront();\nmsgFrm.Focus();\n</code></pre>\n"
},
{
"answer_id": 46470,
"author": "Quibblesome",
"author_id": 1143,
"author_profile": "https://Stackoverflow.com/users/1143",
"pm_score": 2,
"selected": false,
"text": "<p>TopMost = true;\n.Activate() ?</p>\n\n<p>Either of those any good?</p>\n\n<p>Splitting it out into its own thread is a bit evil as it wont work properly if you don't call it with Application.Run and that will swallow up the thread. In the worst case scenario I guess you could separate it out into a different process and communicate via the disk or WCF.</p>\n"
},
{
"answer_id": 94642,
"author": "Kevin Gale",
"author_id": 7176,
"author_profile": "https://Stackoverflow.com/users/7176",
"pm_score": 4,
"selected": false,
"text": "<p>Here is some code that I've used on one form or another for a few years. There are a few gotchas to making a window in another app pop up. Once you have the window handle do this:</p>\n\n<pre><code> if (IsIconic(hWnd))\n ShowWindowAsync(hWnd, SW_RESTORE);\n\n ShowWindowAsync(hWnd, SW_SHOW);\n\n SetForegroundWindow(hWnd);\n\n // Code from Karl E. Peterson, www.mvps.org/vb/sample.htm\n // Converted to Delphi by Ray Lischner\n // Published in The Delphi Magazine 55, page 16\n // Converted to C# by Kevin Gale\n IntPtr foregroundWindow = GetForegroundWindow();\n IntPtr Dummy = IntPtr.Zero;\n\n uint foregroundThreadId = GetWindowThreadProcessId(foregroundWindow, Dummy);\n uint thisThreadId = GetWindowThreadProcessId(hWnd, Dummy);\n\n if (AttachThreadInput(thisThreadId, foregroundThreadId, true))\n {\n BringWindowToTop(hWnd); // IE 5.5 related hack\n SetForegroundWindow(hWnd);\n AttachThreadInput(thisThreadId, foregroundThreadId, false);\n }\n\n if (GetForegroundWindow() != hWnd)\n {\n // Code by Daniel P. Stasinski\n // Converted to C# by Kevin Gale\n IntPtr Timeout = IntPtr.Zero;\n SystemParametersInfo(SPI_GETFOREGROUNDLOCKTIMEOUT, 0, Timeout, 0);\n SystemParametersInfo(SPI_SETFOREGROUNDLOCKTIMEOUT, 0, Dummy, SPIF_SENDCHANGE);\n BringWindowToTop(hWnd); // IE 5.5 related hack\n SetForegroundWindow(hWnd);\n SystemParametersInfo(SPI_SETFOREGROUNDLOCKTIMEOUT, 0, Timeout, SPIF_SENDCHANGE);\n }\n</code></pre>\n\n<p>I won't post the whole unit since since it does other things that aren't relevant\nbut here are the constants and imports for the above code. </p>\n\n<pre><code>//Win32 API calls necesary to raise an unowned processs main window\n\n[DllImport(\"user32.dll\")]\n\nprivate static extern bool SetForegroundWindow(IntPtr hWnd);\n[DllImport(\"user32.dll\")]\nprivate static extern bool ShowWindowAsync(IntPtr hWnd, int nCmdShow);\n[DllImport(\"user32.dll\")]\nprivate static extern bool IsIconic(IntPtr hWnd);\n[DllImport(\"user32.dll\", SetLastError = true)]\nprivate static extern bool SystemParametersInfo(uint uiAction, uint uiParam, IntPtr pvParam, uint fWinIni);\n[DllImport(\"user32.dll\", SetLastError = true)]\nprivate static extern uint GetWindowThreadProcessId(IntPtr hWnd, IntPtr lpdwProcessId);\n[DllImport(\"user32.dll\")]\nprivate static extern IntPtr GetForegroundWindow();\n[DllImport(\"user32.dll\")]\nprivate static extern bool AttachThreadInput(uint idAttach, uint idAttachTo, bool fAttach);\n[DllImport(\"user32.dll\")]\nstatic extern bool BringWindowToTop(IntPtr hWnd);\n\n[DllImport(\"user32.dll\")] \nprivate static extern int GetWindowText(IntPtr hWnd, StringBuilder lpString, Int32 nMaxCount);\n[DllImport(\"user32.dll\")]\nprivate static extern int GetWindowThreadProcessId(IntPtr hWnd, ref Int32 lpdwProcessId);\n[DllImport(\"User32.dll\")]\npublic static extern IntPtr GetParent(IntPtr hWnd); \n\nprivate const int SW_HIDE = 0;\nprivate const int SW_SHOWNORMAL = 1;\nprivate const int SW_NORMAL = 1;\nprivate const int SW_SHOWMINIMIZED = 2;\nprivate const int SW_SHOWMAXIMIZED = 3;\nprivate const int SW_MAXIMIZE = 3;\nprivate const int SW_SHOWNOACTIVATE = 4;\nprivate const int SW_SHOW = 5;\nprivate const int SW_MINIMIZE = 6;\nprivate const int SW_SHOWMINNOACTIVE = 7;\nprivate const int SW_SHOWNA = 8;\nprivate const int SW_RESTORE = 9;\nprivate const int SW_SHOWDEFAULT = 10;\nprivate const int SW_MAX = 10;\n\nprivate const uint SPI_GETFOREGROUNDLOCKTIMEOUT = 0x2000;\nprivate const uint SPI_SETFOREGROUNDLOCKTIMEOUT = 0x2001;\nprivate const int SPIF_SENDCHANGE = 0x2;\n</code></pre>\n"
},
{
"answer_id": 155351,
"author": "jyoung",
"author_id": 14841,
"author_profile": "https://Stackoverflow.com/users/14841",
"pm_score": 0,
"selected": false,
"text": "<p>Don't you just want the dialog to be a child of the calling form?</p>\n\n<p>To do that you'll need the pass in the calling window and \nuse the ShowDialog( IWin32Window owner ) method.</p>\n"
},
{
"answer_id": 438971,
"author": "Milan Gardian",
"author_id": 23843,
"author_profile": "https://Stackoverflow.com/users/23843",
"pm_score": 2,
"selected": false,
"text": "<p>The following solution should meet your requirements:</p>\n\n<ol>\n<li>Assembly can be loaded into PowerShell and main class instantiated</li>\n<li>When ShowMessage method on this instance is called, a new window is shown and activated</li>\n<li>If you call ShowMessage multiple times, this same window updates its title text and is activated</li>\n<li>To stop using the window, call Dispose method</li>\n</ol>\n\n<p><strong>Step 1</strong>: Let's create a temporary working directory (you can naturally use your own dir)</p>\n\n<pre><code>(powershell.exe)\nmkdir C:\\TEMP\\PshWindow\ncd C:\\TEMP\\PshWindow\n</code></pre>\n\n<p><strong>Step 2</strong>: Now let's define class that we will be interacting with in PowerShell:</p>\n\n<pre><code>// file 'InfoProvider.cs' in C:\\TEMP\\PshWindow\nusing System;\nusing System.Threading;\nusing System.Windows.Forms;\n\nnamespace PshWindow\n{\n public sealed class InfoProvider : IDisposable\n {\n public void Dispose()\n {\n GC.SuppressFinalize(this);\n lock (this._sync)\n {\n if (!this._disposed)\n {\n this._disposed = true;\n if (null != this._worker)\n {\n if (null != this._form)\n {\n this._form.Invoke(new Action(() => this._form.Close()));\n }\n this._worker.Join();\n this._form = null;\n this._worker = null;\n }\n }\n }\n }\n\n public void ShowMessage(string msg)\n {\n lock (this._sync)\n {\n // make sure worker is up and running\n if (this._disposed) { throw new ObjectDisposedException(\"InfoProvider\"); }\n if (null == this._worker)\n {\n this._worker = new Thread(() => (this._form = new MyForm(this._sync)).ShowDialog()) { IsBackground = true };\n this._worker.Start();\n while (this._form == null || !this._form.Created)\n {\n Monitor.Wait(this._sync);\n }\n }\n\n // update the text\n this._form.Invoke(new Action(delegate\n {\n this._form.Text = msg;\n this._form.Activate();\n }));\n }\n }\n\n private bool _disposed;\n private Form _form;\n private Thread _worker;\n private readonly object _sync = new object();\n }\n}\n</code></pre>\n\n<p>As well as the Form that will be shown:</p>\n\n<pre><code>// file 'MyForm.cs' in C:\\TEMP\\PshWindow\nusing System;\nusing System.Drawing;\nusing System.Threading;\nusing System.Windows.Forms;\n\nnamespace PshWindow\n{\n internal sealed class MyForm : Form\n {\n public MyForm(object sync)\n {\n this._sync = sync;\n this.BackColor = Color.LightGreen;\n this.Width = 200;\n this.Height = 80;\n this.FormBorderStyle = FormBorderStyle.SizableToolWindow;\n }\n\n protected override void OnShown(EventArgs e)\n {\n base.OnShown(e);\n this.TopMost = true;\n\n lock (this._sync)\n {\n Monitor.PulseAll(this._sync);\n }\n }\n\n private readonly object _sync;\n }\n}\n</code></pre>\n\n<p><strong>Step 3</strong>: Let's compile the assembly...</p>\n\n<pre><code>(powershell.exe)\ncsc /out:PshWindow.dll /target:library InfoProvider.cs MyForm.cs\n</code></pre>\n\n<p><strong>Step 4</strong>: ... and load the assembly in PowerShell to have fun with it:</p>\n\n<pre><code>(powershell.exe)\n[System.Reflection.Assembly]::LoadFile('C:\\TEMP\\PshWindow\\PshWindow.dll')\n$a = New-Object PshWindow.InfoProvider\n$a.ShowMessage('Hello, world')\n</code></pre>\n\n<p>A green-ish window with title 'Hello, world' should now pop-up and be active. If you reactivate the PowerShell window and enter:</p>\n\n<pre><code>$a.ShowMessage('Stack overflow')\n</code></pre>\n\n<p>The Window's title should change to 'Stack overflow' and the window should be active again.</p>\n\n<p>To stop working with our window, dispose the object:</p>\n\n<pre><code>$a.Dispose()\n</code></pre>\n\n<p>This solution works as expected in both Windows XP SP3, x86 and Windows Vista SP1, x64. If there are question about how this solution works I can update this entry with detailed discussion. For now I'm hoping the code if self-explanatory.</p>\n"
},
{
"answer_id": 717431,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 1,
"selected": false,
"text": "<p>Huge thanks people.<br>\nI think I've made it a bit shorter, here's what I put on a seperate thread and seems to be working ok.</p>\n\n<pre><code>private static void StatusChecking()\n{\n IntPtr iActiveForm = IntPtr.Zero, iCurrentACtiveApp = IntPtr.Zero;\n Int32 iMyProcID = Process.GetCurrentProcess().Id, iCurrentProcID = 0;\n IntPtr iTmp = (IntPtr)1;\n\n while (bIsRunning)\n {\n try\n {\n Thread.Sleep(45);\n if (Form.ActiveForm != null)\n {\n iActiveForm = Form.ActiveForm.Handle;\n }\n iTmp = GetForegroundWindow();\n if (iTmp == IntPtr.Zero) continue;\n GetWindowThreadProcessId(iTmp, ref iCurrentProcID);\n if (iCurrentProcID == 0)\n {\n iCurrentProcID = 1;\n continue;\n }\n if (iCurrentProcID != iMyProcID)\n {\n SystemParametersInfo(SPI_GETFOREGROUNDLOCKTIMEOUT, 0, IntPtr.Zero, 0);\n SystemParametersInfo(SPI_SETFOREGROUNDLOCKTIMEOUT, 0, IntPtr.Zero, SPIF_SENDCHANGE);\n BringWindowToTop(iActiveForm);\n SetForegroundWindow(iActiveForm);\n }\n else iActiveForm = iTmp;\n }\n catch (Exception ex)\n {\n Definitions.UnhandledExceptionHandler(ex, 103106);\n }\n }\n}\n</code></pre>\n\n<p>I don`t bother repasting the definitions...</p>\n"
}
] | 2008/09/05 | [
"https://Stackoverflow.com/questions/46030",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1358/"
] | So, I did search google and SO prior to asking this question. Basically I have a DLL that has a form compiled into it. The form will be used to display information to the screen. Eventually it will be asynchronous and expose a lot of customization in the dll. For now I just want it to display properly. The problem that I am having is that I use the dll by loading it in a Powershell session. So when I try to display the form and get it to come to the top and have focus, It has no problem with displaying over all the other apps, but I can't for the life of me get it to display over the Powershell window. Here is the code that I am currently using to try and get it to display. I am sure that the majority of it won't be required once I figure it out, this just represents all the things that I found via google.
```
CLass Blah
{
[DllImport("user32.dll", EntryPoint = "SystemParametersInfo")]
public static extern bool SystemParametersInfo(uint uiAction, uint uiParam, uint pvParam, uint fWinIni);
[DllImport("user32.dll", EntryPoint = "SetForegroundWindow")]
public static extern bool SetForegroundWindow(IntPtr hWnd);
[DllImport("User32.dll", EntryPoint = "ShowWindowAsync")]
private static extern bool ShowWindowAsync(IntPtr hWnd, int cmdShow);
private const int WS_SHOWNORMAL = 1;
public void ShowMessage(string msg)
{
MessageForm msgFrm = new MessageForm();
msgFrm.lblMessage.Text = "FOO";
msgFrm.ShowDialog();
msgFrm.BringToFront();
msgFrm.TopMost = true;
msgFrm.Activate();
SystemParametersInfo((uint)0x2001, 0, 0, 0x0002 | 0x0001);
ShowWindowAsync(msgFrm.Handle, WS_SHOWNORMAL);
SetForegroundWindow(msgFrm.Handle);
SystemParametersInfo((uint)0x2001, 200000, 200000, 0x0002 | 0x0001);
}
}
```
As I say I'm sure that most of that is either not needed or even flat out wrong, I just wanted to show the things that I had tried. Also, as I mentioned, I plan to have this be asynchronously displayed at some point which I suspect will wind up requiring a separate thread. Would splitting the form out into it's own thread make it easier to cause it to get focus over the Powershell session?
---
@Joel, thanks for the info. Here is what I tried based on your suggestion:
```
msgFrm.ShowDialog();
msgFrm.BringToFront();
msgFrm.Focus();
Application.DoEvents();
```
The form still comes up *under* the Powershell session. I'll proceed with working out the threading. I've spawned threads before but never where the parent thread needed to talk to the child thread, so we'll see how it goes.
Thnks for all the ideas so far folks.
---
Ok, threading it took care of the problem. @Quarrelsome, I did try both of those. Neither (nor both together) worked. I am curious as to what is evil about using threading? I am not using Application.Run and I have yet to have a problem. I am using a mediator class that both the parent thread and the child thread have access to. In that object I am using a ReaderWriterLock to lock one property that represents the message that I want displayed on the form that the child thread creates. The parent locks the property then writes what should be displayed. The child thread locks the property and reads what it should change the label on the form to. The child has to do this on a polling interval (I default it to 500ms) which I'm not real happy about, but I could not find an event driven way to let the child thread know that the proerty had changed, so I'm stuck with polling. | I also had trouble activating and bringing a window to the foreground. Here is the code that eventually worked for me. I'm not sure if it will solve your problem.
Basically, call ShowWindow() then SetForegroundWindow().
```
using System.Diagnostics;
using System.Runtime.InteropServices;
// Sets the window to be foreground
[DllImport("User32")]
private static extern int SetForegroundWindow(IntPtr hwnd);
// Activate or minimize a window
[DllImportAttribute("User32.DLL")]
private static extern bool ShowWindow(IntPtr hWnd, int nCmdShow);
private const int SW_SHOW = 5;
private const int SW_MINIMIZE = 6;
private const int SW_RESTORE = 9;
private void ActivateApplication(string briefAppName)
{
Process[] procList = Process.GetProcessesByName(briefAppName);
if (procList.Length > 0)
{
ShowWindow(procList[0].MainWindowHandle, SW_RESTORE);
SetForegroundWindow(procList[0].MainWindowHandle);
}
}
``` |
46,034 | <p>My work has a financial application, written in <code>VB.NET</code> with <code>SQL</code>, that several users can be working on at the same time.</p>
<p>At some point, one user might decide to Post the batch of entries that they (and possibly other people) are currently working on.</p>
<p>Obviously, I no longer want any other users to <strong>add</strong>, <strong>edit</strong>, or <strong>delete</strong> entries in that batch <strong>after</strong> the <strong>Post process</strong> has been initiated.</p>
<p>I have already seen that I can lock <strong>all</strong> data by opening the SQL transaction the moment the Post process starts, but the process can be fairly lengthy and I would prefer not to have the Transaction open for the several minutes it might take to complete the function.</p>
<p>Is there a way to lock just the records that I know need to be operated on from VB.NET code?</p>
| [
{
"answer_id": 46054,
"author": "Jimmy",
"author_id": 4435,
"author_profile": "https://Stackoverflow.com/users/4435",
"pm_score": 0,
"selected": false,
"text": "<p>add </p>\n\n<pre><code>with (rowlock)\n</code></pre>\n\n<p>to your SQL query</p>\n\n<p><a href=\"http://www.sql-server-performance.com/articles/per/lock_contention_nolock_rowlock_p1.aspx\" rel=\"nofollow noreferrer\">SQL Server Performance article</a></p>\n\n<p><strong>EDIT:</strong> ok, I misunderstood the question. What you want is transaction isolation. +1 to Joel :) </p>\n"
},
{
"answer_id": 46089,
"author": "minty",
"author_id": 4491,
"author_profile": "https://Stackoverflow.com/users/4491",
"pm_score": 2,
"selected": false,
"text": "<p>If you are using Oracle you would <strong>Select for update</strong> on the rows you are locking.</p>\n\n<p>here is an example</p>\n\n<pre><code>SELECT address1 , city, country\nFROM location\nFOR UPDATE;\n</code></pre>\n"
},
{
"answer_id": 46127,
"author": "Joel Coehoorn",
"author_id": 3043,
"author_profile": "https://Stackoverflow.com/users/3043",
"pm_score": 1,
"selected": false,
"text": "<p>You probably want to set an isolation level for the entire transaction rather than using <em>with (rowlock)</em> on specific tables. </p>\n\n<p>Look at this page:<br>\n<a href=\"http://msdn.microsoft.com/en-us/library/ms173763.aspx\" rel=\"nofollow noreferrer\">http://msdn.microsoft.com/en-us/library/ms173763.aspx</a></p>\n\n<p>Specifically, search within it for 'row lock', and I think you'll find that READ COMMITTED or REPEATABLE READ are what you want. READ COMMITTED is the SQL Server default. If READ COMMITTED doesn't seem strong enough to you, then go for REPEATABLE READ.</p>\n\n<p><strong>Update:</strong> After reading one of your follow up posts, you definitely want repeatable read. That will hold the lock until you either commit or rollback the transaction.</p>\n"
},
{
"answer_id": 52304,
"author": "SQLMenace",
"author_id": 740,
"author_profile": "https://Stackoverflow.com/users/740",
"pm_score": 0,
"selected": false,
"text": "<p>wrap it in a tran use an holdlock + updlock in the select</p>\n\n<p>example</p>\n\n<pre><code>begin tran\nselect * from\nSomeTable (holdlock,updlock)\nwhere ....\n\n\nprocessing here\n\ncommit\n</code></pre>\n"
}
] | 2008/09/05 | [
"https://Stackoverflow.com/questions/46034",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] | My work has a financial application, written in `VB.NET` with `SQL`, that several users can be working on at the same time.
At some point, one user might decide to Post the batch of entries that they (and possibly other people) are currently working on.
Obviously, I no longer want any other users to **add**, **edit**, or **delete** entries in that batch **after** the **Post process** has been initiated.
I have already seen that I can lock **all** data by opening the SQL transaction the moment the Post process starts, but the process can be fairly lengthy and I would prefer not to have the Transaction open for the several minutes it might take to complete the function.
Is there a way to lock just the records that I know need to be operated on from VB.NET code? | If you are using Oracle you would **Select for update** on the rows you are locking.
here is an example
```
SELECT address1 , city, country
FROM location
FOR UPDATE;
``` |
46,079 | <p>Details:</p>
<ul>
<li>Only disable after user clicks the submit button, but before the posting back to the server</li>
<li>ASP.NET Webforms (.NET 1.1)</li>
<li>Prefer jQuery (if any library at all)</li>
<li>Must be enabled if form reloads (i.e. credit card failed)</li>
</ul>
<p>This isn't a necessity that I do this, but if there is a simple way to do it without having to change too much, I'll do it. (i.e. if there isn't a simple solution, I probably won't do it, so don't worry about digging too deep)</p>
| [
{
"answer_id": 46082,
"author": "Jimmy",
"author_id": 4435,
"author_profile": "https://Stackoverflow.com/users/4435",
"pm_score": 1,
"selected": false,
"text": "<p>in JQuery:</p>\n\n<pre><code>$('#SubmitButtonID').click(function() { this.disabled = true; });\n</code></pre>\n"
},
{
"answer_id": 46138,
"author": "SpoonMeiser",
"author_id": 1577190,
"author_profile": "https://Stackoverflow.com/users/1577190",
"pm_score": 5,
"selected": true,
"text": "<p>For all submit buttons, via JQuery, it'd be:</p>\n\n<pre><code>$('input[type=submit]').click(function() { this.disabled = true; });\n</code></pre>\n\n<p>Or it might be more useful to do so on form submission:</p>\n\n<pre><code>$('form').submit(function() {\n $('input[type=submit]', this).attr(\"disabled\",\"disabled\");\n});\n</code></pre>\n\n<p>But I think we could give a better answer to your question if we knew a bit more about the context.</p>\n\n<p>If this is an ajax request, then you'll need to make sure you enable submit buttons again on either success or failure.</p>\n\n<p>If this is a standard HTTP form submission (aside from disabling the button with javascript) and you're doing this to safe guard from multiple submissions of the same form, then you ought to have some sort of control in the code that deals with the submitted data, because disabling a button with javascript might not prevent multiple submissions.</p>\n"
},
{
"answer_id": 46139,
"author": "spoulson",
"author_id": 3347,
"author_profile": "https://Stackoverflow.com/users/3347",
"pm_score": 0,
"selected": false,
"text": "<p>There are three ways to submit a form that should be covered. Use both David McLaughlin's and Jimmy's suggestions. One will disable the submit button form element while the other disables the basic HTML form submit.</p>\n\n<p>For the third, these won't disable Javascript from doing a form.submit(). The <code>OnSubmit=\"return false\"</code> method only applies when a user clicks the submit button or presses Enter in a input form element. Client side scripting will need to be handled as well.</p>\n"
},
{
"answer_id": 46148,
"author": "Mark Biek",
"author_id": 305,
"author_profile": "https://Stackoverflow.com/users/305",
"pm_score": 3,
"selected": false,
"text": "<p>I'm guessing that you don't want them to hit the submit button more than once while the submit is processing.</p>\n\n<p>My approach has been to just hide the button entirely and display some sort of status indicator (animated gif, etc) instead.</p>\n\n<p>Here's a very contrived example (it's technically in prototype but I think a jquery version would be very similar):</p>\n\n<pre><code><html>\n <head>\n <script type=\"text/javascript\" src=\"include/js/prototype.js\"></script>\n\n <script type=\"text/javascript\">\n function handleSubmit()\n {\n $('submit').hide();\n $('progressWheel').show();\n return true;\n }\n </script>\n </head>\n <body>\n <img src=\"include/images/progress-wheel_lg.gif\" id=\"progressWheel\" style=\"display:none;\"/>\n <input type=\"submit\" name=\"submit\" id=\"submit\" value=\"Submit\" onclick=\"handleSubmit();\"/>\n </body>\n</html>\n</code></pre>\n"
},
{
"answer_id": 249428,
"author": "Simon_Weaver",
"author_id": 16940,
"author_profile": "https://Stackoverflow.com/users/16940",
"pm_score": 0,
"selected": false,
"text": "<p>How about</p>\n\n<p><strong>Code behind</strong>:</p>\n\n<p>btnContinue3.Attributes.Item(\"onclick\") = \"disableSubmit()\" </p>\n\n<p><strong>Javascript</strong>:</p>\n\n<pre><code>function disableSubmit() {\n document.getElementById('btnContinue3').onclick = function() { \n alert('Please only click once on the submit button!'); return false;\n };\n}\n</code></pre>\n\n<p>This doesnt solve the problem of what happens if the postback times out, but other than that it worked for me.</p>\n"
},
{
"answer_id": 249480,
"author": "Rune Grimstad",
"author_id": 30366,
"author_profile": "https://Stackoverflow.com/users/30366",
"pm_score": 1,
"selected": false,
"text": "<p>On thing to be aware of is that you should not disable the button before the form is submitted. If you disable the button using javascript in the OnClick event you may lose the form submit.</p>\n\n<p>So I would suggest you hide the button using javascript by placing an image above it or by moving the button out of the visible range. That should allow the form submit to proceed normally.</p>\n"
},
{
"answer_id": 249530,
"author": "nickf",
"author_id": 9021,
"author_profile": "https://Stackoverflow.com/users/9021",
"pm_score": 3,
"selected": false,
"text": "<p>You could do something like this:</p>\n\n<pre><code>$('form').submit(function() {\n $(this)\n .find(\":submit,:image\") // get all the submit buttons\n .attr({ disabled : 'disabled' }) // disable them\n .end() // go back to this form\n .submit(function() { // change the onsubmit to always reject.\n return false;\n })\n ;\n});\n</code></pre>\n\n<p>Benefits of this:</p>\n\n<ul>\n<li>It will work with all your forms, with all methods of submission:\n\n<ul>\n<li>clicking a submit element</li>\n<li>pressing enter, or</li>\n<li>calling <code>form.submit()</code> from some other code</li>\n</ul></li>\n<li>It will disable all submit elements:\n\n<ul>\n<li><code><input type=\"submit\"/></code></li>\n<li><code><button type=\"submit\"></button></code></li>\n<li><code><input type=\"image\" /></code></li>\n</ul></li>\n<li>it's really short.</li>\n</ul>\n"
}
] | 2008/09/05 | [
"https://Stackoverflow.com/questions/46079",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1446/"
] | Details:
* Only disable after user clicks the submit button, but before the posting back to the server
* ASP.NET Webforms (.NET 1.1)
* Prefer jQuery (if any library at all)
* Must be enabled if form reloads (i.e. credit card failed)
This isn't a necessity that I do this, but if there is a simple way to do it without having to change too much, I'll do it. (i.e. if there isn't a simple solution, I probably won't do it, so don't worry about digging too deep) | For all submit buttons, via JQuery, it'd be:
```
$('input[type=submit]').click(function() { this.disabled = true; });
```
Or it might be more useful to do so on form submission:
```
$('form').submit(function() {
$('input[type=submit]', this).attr("disabled","disabled");
});
```
But I think we could give a better answer to your question if we knew a bit more about the context.
If this is an ajax request, then you'll need to make sure you enable submit buttons again on either success or failure.
If this is a standard HTTP form submission (aside from disabling the button with javascript) and you're doing this to safe guard from multiple submissions of the same form, then you ought to have some sort of control in the code that deals with the submitted data, because disabling a button with javascript might not prevent multiple submissions. |
46,080 | <p>I'm using TortoiseSVN against the SourceForge SVN repository. I'd like to move a file from one folder to another in order to maintain its revision history. Is this possible? If so, how do you do it?</p>
<p>(My current strategy has been to copy the file into the new folder and check it in and then delete the file from the current folder.)</p>
| [
{
"answer_id": 46083,
"author": "Commodore Jaeger",
"author_id": 4659,
"author_profile": "https://Stackoverflow.com/users/4659",
"pm_score": 8,
"selected": true,
"text": "<p>Subversion has native support for moving files.</p>\n\n<pre><code>svn move SOURCE DESTINATION\n</code></pre>\n\n<p>See the online help (svn help move) for more information.</p>\n"
},
{
"answer_id": 46085,
"author": "John Boker",
"author_id": 2847,
"author_profile": "https://Stackoverflow.com/users/2847",
"pm_score": 2,
"selected": false,
"text": "<p>i think in the svn browser in tortoisesvn you can just drag it from one place to another.</p>\n"
},
{
"answer_id": 46087,
"author": "aku",
"author_id": 1196,
"author_profile": "https://Stackoverflow.com/users/1196",
"pm_score": 1,
"selected": false,
"text": "<p>If I'm not wrong starting from version 1.5 SVN can track moved files\\folders. In TortoiseSVN use can move file via drag&drop.</p>\n"
},
{
"answer_id": 46088,
"author": "DevelopingChris",
"author_id": 1220,
"author_profile": "https://Stackoverflow.com/users/1220",
"pm_score": 1,
"selected": false,
"text": "<p>May also be called, \"rename\" by tortoise, but svn move, is the command in the barebones svn client.</p>\n"
},
{
"answer_id": 46093,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 5,
"selected": false,
"text": "<p>Using TortoiseSVN I just right-click and drag the folder from one location to another. When you release the right-click you'll have the option to \"SVN Move Version File.\" However, I believe that SVN doesn't do anything \"fancy\" there, but simply deletes the file in the previous location and Adds it to the new location.</p>\n"
},
{
"answer_id": 46095,
"author": "Ryan Lanciaux",
"author_id": 1385358,
"author_profile": "https://Stackoverflow.com/users/1385358",
"pm_score": 2,
"selected": false,
"text": "<p>Since you're using Tortoise you may want to check out this link on LosTechies. It should be almost exactly what you are looking for. </p>\n\n<p><a href=\"http://www.lostechies.com/blogs/joshua_lockwood/archive/2007/09/12/subversion-tip-of-the-day-moving-files.aspx\" rel=\"nofollow noreferrer\">http://www.lostechies.com/blogs/joshua_lockwood/archive/2007/09/12/subversion-tip-of-the-day-moving-files.aspx</a></p>\n"
},
{
"answer_id": 46100,
"author": "crashmstr",
"author_id": 1441,
"author_profile": "https://Stackoverflow.com/users/1441",
"pm_score": 8,
"selected": false,
"text": "<p>Check out section <b><a href=\"http://tortoisesvn.net/docs/release/TortoiseSVN_en/tsvn-dug-rename.html#tsvn-dug-rename-move\" rel=\"noreferrer\">5.14.2. Moving files and folders</a></b> (or check out \"move\" in the Index of the help) of the TortoiseSVN help. You do a move via right-dragging. It also mentions that you need to commit from the parent folder to make it \"one\" revision. This works for doing the change in a working copy.</p>\n\n<p>(Note that the SVN items in the following image will only show up if the destination folder has already been added to the repository.)</p>\n\n<p><img src=\"https://i.stack.imgur.com/3YzW2.png\" alt=\"tortoise move menu\"></p>\n\n<p>You can also do the move via the Repo Browser (section <b><a href=\"http://tortoisesvn.net/docs/release/TortoiseSVN_en/tsvn-dug-repobrowser.html\" rel=\"noreferrer\">5.23. The Repository Browser</a>\n</b> of the help).</p>\n"
},
{
"answer_id": 46102,
"author": "RedWolves",
"author_id": 648,
"author_profile": "https://Stackoverflow.com/users/648",
"pm_score": 5,
"selected": false,
"text": "<p>In TortoiseSVN right click somewhere and go TortoiseSVN > Repo Browser open the repository.</p>\n\n<p>All you then have to do is drag and drop the file from one folder to the where you want it. It'll ask you to add a commit message and it defaults it to \"Moved file/folder remotely\"</p>\n"
},
{
"answer_id": 46129,
"author": "Keith",
"author_id": 905,
"author_profile": "https://Stackoverflow.com/users/905",
"pm_score": 6,
"selected": false,
"text": "<p>With TortoiseSVN I just move the file on disk.</p>\n\n<p>When I come to commit my changes I select the missing file and the new one and select \"<a href=\"http://tortoisesvn.net/repairmoves.html\" rel=\"noreferrer\">Repair move</a>\" from the right click menu:</p>\n\n<p><a href=\"https://i.stack.imgur.com/cGWVO.png\" rel=\"noreferrer\"><img src=\"https://i.stack.imgur.com/cGWVO.png\" alt=\"enter image description here\"></a></p>\n\n<p>This means I can let my IDE move round files and use it refactoring tools without losing history.</p>\n"
},
{
"answer_id": 3811089,
"author": "Martin",
"author_id": 338547,
"author_profile": "https://Stackoverflow.com/users/338547",
"pm_score": 4,
"selected": false,
"text": "<p>For TortoiseSVN client:</p>\n\n<ol>\n<li>Select the files you wish to move,</li>\n<li><strong>Right</strong> click and drag the files to the folder you wish to move them to,</li>\n<li>A window will popup after you release the drag and drop on a folder. Click <em>\"SVN Move versioned item(s) here\"</em>,</li>\n<li>After you click the above the commit window message box will appear. Enter a message and submit. </li>\n</ol>\n\n<p>Now you are done.</p>\n"
},
{
"answer_id": 11454596,
"author": "Danijel",
"author_id": 1202172,
"author_profile": "https://Stackoverflow.com/users/1202172",
"pm_score": 0,
"selected": false,
"text": "<p>If you are moving folders via Repository Browser, then there is no Move option on right-click; the only way is to drag and drop. </p>\n"
},
{
"answer_id": 25660319,
"author": "BornToCode",
"author_id": 1057791,
"author_profile": "https://Stackoverflow.com/users/1057791",
"pm_score": 3,
"selected": false,
"text": "<p>Cut file via operating system context menu as you usually do, then instead of doing regular paste, right click to bring context menu, then choose <code>TortoiseSVN -> Paste</code> (make sure you commit from root to include both old and new files in the commit).</p>\n"
},
{
"answer_id": 56579359,
"author": "Anzar Ansari",
"author_id": 3976635,
"author_profile": "https://Stackoverflow.com/users/3976635",
"pm_score": 1,
"selected": false,
"text": "<p>Transferring a file using TortoiseSVN:</p>\n\n<p><strong>Step:1</strong>\nPlease Select the files which you want to move,\nRight-click and drag the files to the folder which you to move them to,\nA window will popup after follow the below instruction </p>\n\n<p><a href=\"https://i.stack.imgur.com/tf2tB.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/tf2tB.png\" alt=\"SVN option \"></a></p>\n\n<p><strong>Step 2:</strong>\nAfter you click the above the commit the file as below mention </p>\n\n<p><a href=\"https://i.stack.imgur.com/VIMUC.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/VIMUC.png\" alt=\"SVN Commit\"></a></p>\n"
}
] | 2008/09/05 | [
"https://Stackoverflow.com/questions/46080",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1463/"
] | I'm using TortoiseSVN against the SourceForge SVN repository. I'd like to move a file from one folder to another in order to maintain its revision history. Is this possible? If so, how do you do it?
(My current strategy has been to copy the file into the new folder and check it in and then delete the file from the current folder.) | Subversion has native support for moving files.
```
svn move SOURCE DESTINATION
```
See the online help (svn help move) for more information. |
46,096 | <p>I'm trying to find the correct names for these 2 "types" of coding expressions in LINQ so that I can refer to them correctly. I want to say that the first is called "Fluent Style"?</p>
<pre><code>var selectVar = arrayVar.Select( (a,i) => new { Line = a });
var selectVar =
from s in arrayVar
select new { Line = s };
</code></pre>
| [
{
"answer_id": 46104,
"author": "aku",
"author_id": 1196,
"author_profile": "https://Stackoverflow.com/users/1196",
"pm_score": 3,
"selected": true,
"text": "<ul>\n<li>First - calling an extension method. \nThis style of coding is called \"<a href=\"http://www.martinfowler.com/bliki/FluentInterface.html\" rel=\"nofollow noreferrer\">fluent interface</a>\" as you mentioned.</li>\n<li>Second method is called <a href=\"http://en.wikipedia.org/wiki/Language_Integrated_Query\" rel=\"nofollow noreferrer\">language integrated query</a></li>\n</ul>\n"
},
{
"answer_id": 46108,
"author": "DevelopingChris",
"author_id": 1220,
"author_profile": "https://Stackoverflow.com/users/1220",
"pm_score": 1,
"selected": false,
"text": "<p>The first isn't even really LINQ, it's a lambda expression, with a type invariant object created. </p>\n\n<pre><code>(a) => new { blah = b}\n</code></pre>\n\n<p>The second is a LINQ query filling an on the fly class that has a property Line.<br>\n There is no hashrocket operator in this one, so this one is just plain old linq.</p>\n"
},
{
"answer_id": 72293,
"author": "Amy B",
"author_id": 8155,
"author_profile": "https://Stackoverflow.com/users/8155",
"pm_score": 1,
"selected": false,
"text": "<p>The name of the second form is \"query comprehesion syntax\", which the compiler translates into the first form.</p>\n"
}
] | 2008/09/05 | [
"https://Stackoverflow.com/questions/46096",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1463/"
] | I'm trying to find the correct names for these 2 "types" of coding expressions in LINQ so that I can refer to them correctly. I want to say that the first is called "Fluent Style"?
```
var selectVar = arrayVar.Select( (a,i) => new { Line = a });
var selectVar =
from s in arrayVar
select new { Line = s };
``` | * First - calling an extension method.
This style of coding is called "[fluent interface](http://www.martinfowler.com/bliki/FluentInterface.html)" as you mentioned.
* Second method is called [language integrated query](http://en.wikipedia.org/wiki/Language_Integrated_Query) |
46,124 | <p>I've seen people doing things like this in their HTML:</p>
<pre><code><!--[if IE]>
<link rel="stylesheet" href="ie.css" type="text/css" />
<![endif]-->
</code></pre>
<p>Does this work across all modern browsers and is there a list of browser types that will work with that kind of if statement?</p>
<p><strong>Edit</strong></p>
<p>Thanks <a href="https://stackoverflow.com/questions/46124/is-there-a-list-of-browser-conditionals-for-use-including-stylesheets#46126">Ross</a>. Interesting to find out about <strong>gt, lt, gte, & lte</strong>.</p>
| [
{
"answer_id": 46126,
"author": "Ross",
"author_id": 2025,
"author_profile": "https://Stackoverflow.com/users/2025",
"pm_score": 5,
"selected": true,
"text": "<p>This works across all browsers because anything except IE sees <code><!--IGNORED COMMENT--></code>. Only IE reads the comment if it contains a conditional clause. Have a look at <a href=\"http://www.quirksmode.org/css/condcom.html\" rel=\"noreferrer\">this article</a></p>\n\n<p>You can also specify which version of IE. For example:</p>\n\n<pre><code><!--[if IE 8]>\n<link rel=\"stylesheet type=\"text/css\" href=\"ie8.css\" />\n<![endif]-->\n</code></pre>\n"
},
{
"answer_id": 46163,
"author": "Simon Johnson",
"author_id": 854,
"author_profile": "https://Stackoverflow.com/users/854",
"pm_score": 1,
"selected": false,
"text": "<p>Further to Ross' answer, you can only target the Internet Explorer rendering engine with conditional comments; there is no similar construct for other browsers. For example, you can't write conditional comments that target Firefox, but are ignored by Internet Explorer. </p>\n\n<p>The way I achieve the same effect as your example above is to sniff the user agent string. I then deliver a suitable CSS file for that browser. This isn't perfect because sometimes people change their user-agent string for compatibility. </p>\n\n<p>The other way to target different browsers is to utilise browser specific hacks. These are particularly nasty because they usually rely on bugs in the browser and bugs are liable to be fixed!</p>\n\n<p>User-agent sniffing is the best all-round solution in my opinion.</p>\n"
},
{
"answer_id": 46244,
"author": "sock",
"author_id": 4028,
"author_profile": "https://Stackoverflow.com/users/4028",
"pm_score": 2,
"selected": false,
"text": "<p>If you can use Javascript, there are several options:</p>\n\n<pre><code>navigator.appName\nnavigator.appVersion \n</code></pre>\n\n<p><a href=\"http://www.w3schools.com/js/js_browser.asp\" rel=\"nofollow noreferrer\">link</a></p>\n\n<p>Or something more robust by using a library such as <a href=\"http://docs.jquery.com/Utilities/jQuery.browser\" rel=\"nofollow noreferrer\">jQuery</a>.</p>\n\n<p>Finally, you could use the <a href=\"http://www.quirksmode.org/js/detect.html\" rel=\"nofollow noreferrer\">BrowserDetect</a> object from QuirksMode.</p>\n\n<p>Once you have the browser name and version, you can then insert HTML to link to a style sheet or include other tags.</p>\n"
},
{
"answer_id": 134964,
"author": "domgblackwell",
"author_id": 16954,
"author_profile": "https://Stackoverflow.com/users/16954",
"pm_score": 2,
"selected": false,
"text": "<p>Conditional comments are purely for IE (version 5 and later). The official Microsoft documentation is <a href=\"http://msdn.microsoft.com/en-us/library/ms537512.aspx\" rel=\"nofollow noreferrer\">here</a>. If you are going to use them the best strategy is to conditionally include external stylesheets or javascript files after your normal includes. This means that on IE your IE-specific code will override everything else. On any other browser the code will be treated as comments and ignored by the parser.</p>\n"
}
] | 2008/09/05 | [
"https://Stackoverflow.com/questions/46124",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/305/"
] | I've seen people doing things like this in their HTML:
```
<!--[if IE]>
<link rel="stylesheet" href="ie.css" type="text/css" />
<![endif]-->
```
Does this work across all modern browsers and is there a list of browser types that will work with that kind of if statement?
**Edit**
Thanks [Ross](https://stackoverflow.com/questions/46124/is-there-a-list-of-browser-conditionals-for-use-including-stylesheets#46126). Interesting to find out about **gt, lt, gte, & lte**. | This works across all browsers because anything except IE sees `<!--IGNORED COMMENT-->`. Only IE reads the comment if it contains a conditional clause. Have a look at [this article](http://www.quirksmode.org/css/condcom.html)
You can also specify which version of IE. For example:
```
<!--[if IE 8]>
<link rel="stylesheet type="text/css" href="ie8.css" />
<![endif]-->
``` |
46,125 | <p>I want to do this: </p>
<blockquote>
<p>//*fu</p>
</blockquote>
<p>which returns all nodes whose name ends in <strong>fu</strong>, such as <code><tarfu /></code> and <code><snafu /></code>, but not <code><fubar /></code></p>
| [
{
"answer_id": 46141,
"author": "Chris Marasti-Georg",
"author_id": 96,
"author_profile": "https://Stackoverflow.com/users/96",
"pm_score": 6,
"selected": true,
"text": "<p>Do something like:</p>\n\n<pre><code>//*[ends-with(name(), 'fu')]\n</code></pre>\n\n<p>For a good XPath reference, check out <a href=\"http://www.w3schools.com/xml/xsl_functions.asp\" rel=\"noreferrer\">W3Schools</a>.</p>\n"
},
{
"answer_id": 288865,
"author": "Dimitre Novatchev",
"author_id": 36305,
"author_profile": "https://Stackoverflow.com/users/36305",
"pm_score": 6,
"selected": false,
"text": "<p><strong>This answer is for <a href=\"http://www.w3.org/TR/xpath#section-String-Functions\" rel=\"noreferrer\">XPath 1.0</a></strong> where there is no equivalent of the <a href=\"http://www.w3.org/TR/xpath-functions/#func-ends-with\" rel=\"noreferrer\">XPath 2.0 standard ends-with() function</a>.</p>\n\n<p>The following XPath 1.0 expression selects all elements in the xml document, whose names end with the string \"fu\":</p>\n\n<pre><code>//*[substring(name(),string-length(name())-1) = 'fu']\n</code></pre>\n"
},
{
"answer_id": 44435539,
"author": "Identity1",
"author_id": 3741717,
"author_profile": "https://Stackoverflow.com/users/3741717",
"pm_score": 2,
"selected": false,
"text": "<p>I struggled with Dimitre Novatchev's answer, it wouldn't return matches. I knew your XPath must have a section telling that \"fu\" has length 2. </p>\n\n<p>It's advised to have a string-length('fu') to determine what to substring.</p>\n\n<p>For those who aren't able to get results with his answer and they require solution with xpath 1.0:</p>\n\n<p><code>//*[substring(name(), string-length(name()) - string-length('fu') +1) = 'fu']</code></p>\n\n<blockquote>\n <p>Finds matches of elements ending with \"fu\"</p>\n</blockquote>\n\n<p>or</p>\n\n<p><code>//*[substring(name(), string-length(name()) - string-length('Position') +1) = 'Position']</code></p>\n\n<blockquote>\n <p>Finds matches to elements ending with \"Position\"</p>\n</blockquote>\n"
}
] | 2008/09/05 | [
"https://Stackoverflow.com/questions/46125",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] | I want to do this:
>
> //\*fu
>
>
>
which returns all nodes whose name ends in **fu**, such as `<tarfu />` and `<snafu />`, but not `<fubar />` | Do something like:
```
//*[ends-with(name(), 'fu')]
```
For a good XPath reference, check out [W3Schools](http://www.w3schools.com/xml/xsl_functions.asp). |
46,130 | <p>I have a list of <code>Foo</code>. Foo has properties <code>Bar</code> and <code>Lum</code>. Some <code>Foo</code>s have identical values for <code>Bar</code>. How can I use lambda/linq to group my <code>Foo</code>s by <code>Bar</code> so I can iterate over each grouping's <code>Lum</code>s?</p>
| [
{
"answer_id": 46142,
"author": "aku",
"author_id": 1196,
"author_profile": "https://Stackoverflow.com/users/1196",
"pm_score": 2,
"selected": false,
"text": "<pre><code>var q = from x in list\n group x by x.Bar into g\n select g;\n\nforeach (var group in q)\n{\n Console.WriteLine(\"Group \" + group.Key);\n foreach (var item in group)\n {\n Console.WriteLine(item.Bar);\n }\n}\n</code></pre>\n"
},
{
"answer_id": 47308,
"author": "aku",
"author_id": 1196,
"author_profile": "https://Stackoverflow.com/users/1196",
"pm_score": 3,
"selected": true,
"text": "<p><a href=\"https://stackoverflow.com/questions/46130/how-do-i-group-in-memory-lists#46317\">Deeno</a>,</p>\n\n<p>Enjoy:</p>\n\n<pre><code>var foos = new List<Foo> {\n new Foo{Bar = 1,Lum = 1},\n new Foo{Bar = 1,Lum = 2},\n new Foo{Bar = 2,Lum = 3},\n};\n\n// Using language integrated queries:\n\nvar q = from foo in foos\n group foo by foo.Bar into groupedFoos\n let lums = from fooGroup in groupedFoos\n select fooGroup.Lum\n select new { Bar = groupedFoos.Key, Lums = lums };\n\n// Using lambdas\n\nvar q = foos.GroupBy(x => x.Bar).\n Select(y => new {Bar = y.Key, Lums = y.Select(z => z.Lum)});\n\n\nforeach (var group in q)\n{\n Console.WriteLine(\"Lums for Bar#\" + group.Bar);\n foreach (var lum in group.Lums)\n {\n Console.WriteLine(lum);\n }\n}\n</code></pre>\n\n<p>To learn more about LINQ read <a href=\"http://msdn.microsoft.com/en-us/vcsharp/aa336746.aspx\" rel=\"nofollow noreferrer\">101 LINQ Samples</a></p>\n"
}
] | 2008/09/05 | [
"https://Stackoverflow.com/questions/46130",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1946/"
] | I have a list of `Foo`. Foo has properties `Bar` and `Lum`. Some `Foo`s have identical values for `Bar`. How can I use lambda/linq to group my `Foo`s by `Bar` so I can iterate over each grouping's `Lum`s? | [Deeno](https://stackoverflow.com/questions/46130/how-do-i-group-in-memory-lists#46317),
Enjoy:
```
var foos = new List<Foo> {
new Foo{Bar = 1,Lum = 1},
new Foo{Bar = 1,Lum = 2},
new Foo{Bar = 2,Lum = 3},
};
// Using language integrated queries:
var q = from foo in foos
group foo by foo.Bar into groupedFoos
let lums = from fooGroup in groupedFoos
select fooGroup.Lum
select new { Bar = groupedFoos.Key, Lums = lums };
// Using lambdas
var q = foos.GroupBy(x => x.Bar).
Select(y => new {Bar = y.Key, Lums = y.Select(z => z.Lum)});
foreach (var group in q)
{
Console.WriteLine("Lums for Bar#" + group.Bar);
foreach (var lum in group.Lums)
{
Console.WriteLine(lum);
}
}
```
To learn more about LINQ read [101 LINQ Samples](http://msdn.microsoft.com/en-us/vcsharp/aa336746.aspx) |
46,136 | <p>I have a large codebase that targetted Flash 7, with a <em>lot</em> of AS2 classes. I'm hoping that I'll be able to use Flex for any new projects, but a lot of new stuff in our roadmap is additions to the old code.</p>
<p>The syntax for AS2 and AS3 is generally the same, so I'm starting to wonder how hard it would be to port the current codebase to Flex/AS3. I know all the UI-related stuff would be iffy (currently the UI is generated at runtime with a lot of createEmptyMovieClip() and attachMovie() stuff), but the UI and controller/model stuff is mostly separated.</p>
<p>Has anyone tried porting a large codebase of AS2 code to AS3? How difficult is it? What kinds of pitfalls did you run into? Any recommendations for approaches to doing this kind of project?</p>
| [
{
"answer_id": 46184,
"author": "lilserf",
"author_id": 4545,
"author_profile": "https://Stackoverflow.com/users/4545",
"pm_score": 4,
"selected": true,
"text": "<p>Some notable problems I saw when attempting to convert a large number of AS2 classes to AS3:</p>\n\n<h3>Package naming</h3>\n\n<pre><code>class your.package.YourClass\n{\n}\n</code></pre>\n\n<p>becomes</p>\n\n<pre><code>package your.package\n{\n class YourClass\n {\n }\n}\n</code></pre>\n\n<h3>Imports are required</h3>\n\n<p>You must explicitly import any outside classes used -- referring to them by their fully qualified name is no longer enough.</p>\n\n<h3>Interface methods can't be labelled 'public'</h3>\n\n<p>This makes total sense, but AS2 will let you do it so if you have any they'll need to be removed.</p>\n\n<h3>Explicit 'override' keyword</h3>\n\n<p>Any functions that override a parent class function must be declared with the <em>override</em> keyword, much like C#. Along the same lines, if you have interfaces that extend other interfaces and redeclare functions, those overrides must be removed (again, as with <em>public,</em> this notation didn't make sense anyway but AS2 let you do it).</p>\n\n<h3>All the Flash builtin stuff changed</h3>\n\n<p>You alluded to this above, but it's now <em>flash.display.MovieClip</em> instead of just <em>MovieClip,</em> for example. There are a lot of specifics in this category, and I didn't get far enough to find them all, but there's going to be a lot of annoyance here.</p>\n\n<h3>Conclusion</h3>\n\n<p>I didn't get to work on this conversion to the point of success, but I was able in a matter of hours to write a quick C# tool that handled every aspect of this except the <em>override</em> keyword. Automating the imports can be tricky -- in my case the packages we use all start with a few root-level packages so they're easy to detect.</p>\n"
},
{
"answer_id": 50840,
"author": "hasseg",
"author_id": 4111,
"author_profile": "https://Stackoverflow.com/users/4111",
"pm_score": 1,
"selected": false,
"text": "<p>First off, I hope you're not using <code>eval()</code> in your projects, since there is no equivalent in AS3.</p>\n\n<p>One of the things I would do is go through <a href=\"http://livedocs.adobe.com/flex/3/langref/migration.html\" rel=\"nofollow noreferrer\">Adobe's migration guide</a> (which is basically just an itemized list of what has changed) item by item and try to figure out if each item can be changed via a simple search and replace operation (possibly using a regex) or whether it's easier to just manually edit the occurrences to correspond to AS3. Probably in a lot of cases (especially if, as you said, the amount of code to be migrated is quite high) you'll be best off scripting the changes (i.e. using regex search & replace) and manually fixing any border cases where the automated changes have failed.</p>\n\n<p>Be prepared to set some time aside for a bit of debugging and running through some test cases as well.</p>\n\n<p>Also, as others have already mentioned, trying to combine AS2 SWFs with AS3 SWFs is not a good idea and doesn't really even work, so you'll definitely have to migrate all of the code in one project at once.</p>\n"
},
{
"answer_id": 58218,
"author": "Antti",
"author_id": 6037,
"author_profile": "https://Stackoverflow.com/users/6037",
"pm_score": 0,
"selected": false,
"text": "<p>Migrating a bigger project like this from as2 will be more than a simple search and replace. The new syntax is fairly similar and simple to adapt (as lilserf mentioned) but if nothing else the fact that as3 is more strict and the new event model will mostly likely cause a lot of problems. You'll probably be better off by more or less rewriting almost everything from scratch, possibly using the old code as a guide.</p>\n\n<p>Migrating from as2 -> as3 in terms of knowledge is fairly simple though. If you know object oriented as2, moving on to as3 won't be a problem at all.</p>\n\n<p>You still don't have to use mxml for your UI unless you specifically want to. Mxml just provides a quick way to build the UI (etc) but if you want to do it yourself with actionscript there's nothing stopping you (this would also probably be easier if you already have that UI in as2 code). Flex (Builder) is just a quick way to do stuff you may not want to do yourself, such as building the UI and binding data but essentially it's just creating a part of the .swf for you -- there's no magic to it ;)</p>\n"
},
{
"answer_id": 67571,
"author": "mikechambers",
"author_id": 10232,
"author_profile": "https://Stackoverflow.com/users/10232",
"pm_score": 1,
"selected": false,
"text": "<p>Here are some additional references for moving from AS2 to AS3:</p>\n\n<p>Grant Skinners Introductory AS3 Workshop slidedeck\n<a href=\"http://gskinner.com/talks/as3workshop/\" rel=\"nofollow noreferrer\">http://gskinner.com/talks/as3workshop/</a></p>\n\n<p>Lee Brimelow : 6 Reasons to learn ActionScript 3\n<a href=\"http://www.adobe.com/devnet/actionscript/articles/six_reasons_as3.html\" rel=\"nofollow noreferrer\">http://www.adobe.com/devnet/actionscript/articles/six_reasons_as3.html</a></p>\n\n<p>Colin Moock : Essential ActionScript 3 (considered the \"bible\" for ActionScript developers):\n<a href=\"https://rads.stackoverflow.com/amzn/click/com/0596526946\" rel=\"nofollow noreferrer\" rel=\"nofollow noreferrer\">http://www.amazon.com/Essential-ActionScript-3-0/dp/0596526946</a></p>\n\n<p>mike chambers</p>\n\n<p>[email protected]</p>\n"
},
{
"answer_id": 68871,
"author": "fenomas",
"author_id": 10651,
"author_profile": "https://Stackoverflow.com/users/10651",
"pm_score": 1,
"selected": false,
"text": "<p>My experience has been that the best way to migrate to AS3 is in two phases - first structurally, and second syntactically.</p>\n\n<p>First, do rounds of refactoring where you stay in AS2, but get as close to AS3 architecture as you can. Naturally this includes moving all your frame scripts and #include scripts into packages and classes, but you can do more subtle things like changing all your event listeners and dispatchers to follow the AS3 flow (using static class properties for event types, and registering by method rather than by object). You'll also want to get rid of all your \"built-in\" events (such as onEnterFrame), and you'll want to take a close look at nontrivial mouse interaction (such as dragging) and keyboard interaction (such as detecting whether a key is pressed). This phase can be done incrementally.</p>\n\n<p>The second phase is to convert from AS2 to AS3 - changing \"_x\" to \"x\", and all the APIs, and so on. This can't be done incrementally, you have to just do as much as you can in one fell swoop and then start fixing all the compile errors. For this reason, the more you can do in the first phase, the more pain you avoid in the second phase.</p>\n\n<p>This process has worked for me on a reasonably large project, but I should note that the first phase requires a solid understanding of how AS3 is structured. If you're new to AS3, then you'll probably need to try building some of the functionality you'll need to be porting. For example, if your legacy code uses dragging and drop targets, you'll want to try implementing that in AS3 to understand how your code will have to change structurally. If you then refactor your AS2 with that in mind, the final syntax changes should go smoothly.</p>\n\n<p>The biggest pitfalls for me were the parts that involved a lot of attaching, duplicating and moving MovieClips, changing their depths, and so on. All that stuff can't really be rearchitected to look like AS3; you have to just mash it all into the newer way of thinking and then start fixing the bugs.</p>\n\n<p>One final note - I really wouldn't worry about stuff like import and override statements, at least not to the point of automating it. If you miss any, it will be caught by the compiler. But if you miss structural problems, you'll have a lot more pain.</p>\n"
}
] | 2008/09/05 | [
"https://Stackoverflow.com/questions/46136",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1409/"
] | I have a large codebase that targetted Flash 7, with a *lot* of AS2 classes. I'm hoping that I'll be able to use Flex for any new projects, but a lot of new stuff in our roadmap is additions to the old code.
The syntax for AS2 and AS3 is generally the same, so I'm starting to wonder how hard it would be to port the current codebase to Flex/AS3. I know all the UI-related stuff would be iffy (currently the UI is generated at runtime with a lot of createEmptyMovieClip() and attachMovie() stuff), but the UI and controller/model stuff is mostly separated.
Has anyone tried porting a large codebase of AS2 code to AS3? How difficult is it? What kinds of pitfalls did you run into? Any recommendations for approaches to doing this kind of project? | Some notable problems I saw when attempting to convert a large number of AS2 classes to AS3:
### Package naming
```
class your.package.YourClass
{
}
```
becomes
```
package your.package
{
class YourClass
{
}
}
```
### Imports are required
You must explicitly import any outside classes used -- referring to them by their fully qualified name is no longer enough.
### Interface methods can't be labelled 'public'
This makes total sense, but AS2 will let you do it so if you have any they'll need to be removed.
### Explicit 'override' keyword
Any functions that override a parent class function must be declared with the *override* keyword, much like C#. Along the same lines, if you have interfaces that extend other interfaces and redeclare functions, those overrides must be removed (again, as with *public,* this notation didn't make sense anyway but AS2 let you do it).
### All the Flash builtin stuff changed
You alluded to this above, but it's now *flash.display.MovieClip* instead of just *MovieClip,* for example. There are a lot of specifics in this category, and I didn't get far enough to find them all, but there's going to be a lot of annoyance here.
### Conclusion
I didn't get to work on this conversion to the point of success, but I was able in a matter of hours to write a quick C# tool that handled every aspect of this except the *override* keyword. Automating the imports can be tricky -- in my case the packages we use all start with a few root-level packages so they're easy to detect. |
46,146 | <p>Looking for a string to pass to String#matches(String) that will match IPv4, and another to match IPv6.</p>
| [
{
"answer_id": 46168,
"author": "Kevin Wong",
"author_id": 4792,
"author_profile": "https://Stackoverflow.com/users/4792",
"pm_score": 4,
"selected": false,
"text": "<pre><code>public static final String IPV4_REGEX = \"\\\\A(25[0-5]|2[0-4]\\\\d|[0-1]?\\\\d?\\\\d)(\\\\.(25[0-5]|2[0-4]\\\\d|[0-1]?\\\\d?\\\\d)){3}\\\\z\";\npublic static final String IPV6_HEX4DECCOMPRESSED_REGEX = \"\\\\A((?:[0-9A-Fa-f]{1,4}(?::[0-9A-Fa-f]{1,4})*)?) ::((?:[0-9A-Fa-f]{1,4}:)*)(25[0-5]|2[0-4]\\\\d|[0-1]?\\\\d?\\\\d)(\\\\.(25[0-5]|2[0-4]\\\\d|[0-1]?\\\\d?\\\\d)){3}\\\\z\";\npublic static final String IPV6_6HEX4DEC_REGEX = \"\\\\A((?:[0-9A-Fa-f]{1,4}:){6,6})(25[0-5]|2[0-4]\\\\d|[0-1]?\\\\d?\\\\d)(\\\\.(25[0-5]|2[0-4]\\\\d|[0-1]?\\\\d?\\\\d)){3}\\\\z\";\npublic static final String IPV6_HEXCOMPRESSED_REGEX = \"\\\\A((?:[0-9A-Fa-f]{1,4}(?::[0-9A-Fa-f]{1,4})*)?)::((?:[0-9A-Fa-f]{1,4}(?::[0-9A-Fa-f]{1,4})*)?)\\\\z\";\npublic static final String IPV6_REGEX = \"\\\\A(?:[0-9a-fA-F]{1,4}:){7}[0-9a-fA-F]{1,4}\\\\z\";\n</code></pre>\n\n<p>Got these from some blog. Someone good w/ regexes should be able to come up with a single regex for all IPv6 address types. Actually, I guess you could have a single regex that matches both IPv4 and IPv6.</p>\n"
},
{
"answer_id": 46171,
"author": "hasseg",
"author_id": 4111,
"author_profile": "https://Stackoverflow.com/users/4111",
"pm_score": 2,
"selected": false,
"text": "<p>Here's a regex to match IPv4 addresses:</p>\n\n<pre><code>\\b(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\\.){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\\b\n</code></pre>\n\n<p>You'll need to escape the backslashes when you specify it as a string literal in Java:</p>\n\n<pre><code>\"\\\\b(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\\\\.){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\\\\b\"\n</code></pre>\n"
},
{
"answer_id": 1210965,
"author": "Yuval",
"author_id": 2819,
"author_profile": "https://Stackoverflow.com/users/2819",
"pm_score": 3,
"selected": false,
"text": "<p>Another good option for processing IPs is to use Java's classes <a href=\"http://java.sun.com/javase/6/docs/api/java/net/Inet4Address.html\" rel=\"noreferrer\">Inet4Address</a> and <a href=\"http://java.sun.com/javase/6/docs/api/java/net/Inet6Address.html\" rel=\"noreferrer\">Inet6Address</a>, which can be useful in a number of ways, one of which is to determine the validity of the IP address.</p>\n\n<p>I know this doesn't answer the question directly, but just thought it's worth mentioning.</p>\n"
},
{
"answer_id": 1573032,
"author": "Aeron",
"author_id": 190680,
"author_profile": "https://Stackoverflow.com/users/190680",
"pm_score": 0,
"selected": false,
"text": "<p>The regex allows the use of leading zeros in the IPv4 parts.</p>\n\n<p>Some Unix and Mac distros convert those segments into octals.</p>\n\n<p>I suggest using <code>25[0-5]|2[0-4]\\d|1\\d\\d|[1-9]?\\d</code> as an IPv4 segment.</p>\n"
},
{
"answer_id": 42605542,
"author": "Sean F",
"author_id": 6801443,
"author_profile": "https://Stackoverflow.com/users/6801443",
"pm_score": 0,
"selected": false,
"text": "<p>Regexes for ipv6 can get really tricky when you consider addresses with embedded ipv4 and addresses that are compressed.</p>\n\n<p><a href=\"https://seancfoley.github.io/IPAddress/\" rel=\"nofollow noreferrer\">The open-source IPAddress Java library</a> will validate all standard representations of IPv6 and IPv4 and also supports prefix-length (and validation of such). Disclaimer: I am the project manager of that library.</p>\n\n<p>Code example:</p>\n\n<pre><code>try {\n IPAddressString str = new IPAddressString(\"::1\");\n IPAddress addr = str.toAddress();\n} catch(AddressStringException e) {\n //e.getMessage has validation error\n}\n</code></pre>\n"
},
{
"answer_id": 60502882,
"author": "Bodhiswatta Mukherjee",
"author_id": 12998124,
"author_profile": "https://Stackoverflow.com/users/12998124",
"pm_score": 1,
"selected": false,
"text": "<pre><code>package com.capgemini.basics;\n\nimport java.util.*;\nimport java.util.regex.Matcher;\nimport java.util.regex.Pattern;\nimport java.util.regex.PatternSyntaxException;\n\npublic class Main {\n private static Pattern VALID_IPV4_PATTERN = null;\n private static Pattern VALID_IPV6_PATTERN1 = null;\n private static Pattern VALID_IPV6_PATTERN2 = null;\n private static final String ipv4Pattern = \"(([01]?\\\\d\\\\d?|2[0-4]\\\\d|25[0-5])\\\\.){3}([01]?\\\\d\\\\d?|2[0-4]\\\\d|25[0-5])\";\n private static final String ipv6Pattern1 = \"([0-9a-f]{1,4}:){7}([0-9a-f]){1,4}\";\n private static final String ipv6Pattern2 = \"^((?:[0-9A-Fa-f]{1,4}(?::[0-9A-Fa-f]{1,4})*)?)::((?:[0-9A-Fa-f]{1,4}(?::[0-9A-Fa-f]{1,4})*)?)$\";\n\n\n static {\n try {\n VALID_IPV4_PATTERN = Pattern.compile(ipv4Pattern, Pattern.CASE_INSENSITIVE);\n VALID_IPV6_PATTERN1 = Pattern.compile(ipv6Pattern1, Pattern.CASE_INSENSITIVE);\n VALID_IPV6_PATTERN2 = Pattern.compile(ipv6Pattern2, Pattern.CASE_INSENSITIVE);\n } catch (PatternSyntaxException e) {\n System.out.println(\"Neither\");\n }\n }\n\n public static List<String> validateAddresses(List<String> ipAddress) {\n final List<String> validity= new ArrayList<String>();\n int len = ipAddress.size();\n for(int i=0; i<len; i++){\n Matcher m1 = Main.VALID_IPV4_PATTERN.matcher(ipAddress.get(i));\n Matcher m12 = Main.VALID_IPV6_PATTERN1.matcher(ipAddress.get(i));\n Matcher m22 = Main.VALID_IPV6_PATTERN2.matcher(ipAddress.get(i));\n if (m1.matches()) {\n validity.add(\"IPv4\");\n }\n else if(m12.matches() || m22.matches()){\n validity.add(\"IPv6\");\n }\n else{\n validity.add(\"Neither\");\n }\n }\n return validity;\n\n }\n\n public static void main(String[] args)\n {\n final List<String> IPAddress = new ArrayList<String>();\n //Test Case 0\n /*IPAddress.add(\"121.18.19.20\");\n IPAddress.add(\"0.12.12.34\");\n IPAddress.add(\"121.234.12.12\");\n IPAddress.add(\"23.45.12.56\");\n IPAddress.add(\"0.1.2.3\");*/\n\n //Test Case 1\n /*IPAddress.add(\"2001:0db8:0000:0000:0000:ff00:0042:8329\");\n IPAddress.add(\"2001:0db8:0:0:0:ff00:42:8329\");\n IPAddress.add(\"::1\");\n IPAddress.add(\"2001:0db8::ff00:42:8329\");\n IPAddress.add(\"0000:0000:0000:0000:0000:0000:0000:0001\");*/\n\n //Test Case 2\n /*IPAddress.add(\"000.012.234.23\");\n IPAddress.add(\"666.666.23.23\");\n IPAddress.add(\".213.123.23.32\");\n IPAddress.add(\"23.45.22.32.\");\n IPAddress.add(\"272:2624:235e:3bc2:c46d:682:5d46:638g\");\n IPAddress.add(\"1:22:333:4444\");*/\n\n final List<String> result = validateAddresses(IPAddress);\n\n for (int i=0; i<result.size(); i++)\n System.out.println(result.get(i)+\" \");\n\n }\n\n}\n</code></pre>\n"
}
] | 2008/09/05 | [
"https://Stackoverflow.com/questions/46146",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4792/"
] | Looking for a string to pass to String#matches(String) that will match IPv4, and another to match IPv6. | ```
public static final String IPV4_REGEX = "\\A(25[0-5]|2[0-4]\\d|[0-1]?\\d?\\d)(\\.(25[0-5]|2[0-4]\\d|[0-1]?\\d?\\d)){3}\\z";
public static final String IPV6_HEX4DECCOMPRESSED_REGEX = "\\A((?:[0-9A-Fa-f]{1,4}(?::[0-9A-Fa-f]{1,4})*)?) ::((?:[0-9A-Fa-f]{1,4}:)*)(25[0-5]|2[0-4]\\d|[0-1]?\\d?\\d)(\\.(25[0-5]|2[0-4]\\d|[0-1]?\\d?\\d)){3}\\z";
public static final String IPV6_6HEX4DEC_REGEX = "\\A((?:[0-9A-Fa-f]{1,4}:){6,6})(25[0-5]|2[0-4]\\d|[0-1]?\\d?\\d)(\\.(25[0-5]|2[0-4]\\d|[0-1]?\\d?\\d)){3}\\z";
public static final String IPV6_HEXCOMPRESSED_REGEX = "\\A((?:[0-9A-Fa-f]{1,4}(?::[0-9A-Fa-f]{1,4})*)?)::((?:[0-9A-Fa-f]{1,4}(?::[0-9A-Fa-f]{1,4})*)?)\\z";
public static final String IPV6_REGEX = "\\A(?:[0-9a-fA-F]{1,4}:){7}[0-9a-fA-F]{1,4}\\z";
```
Got these from some blog. Someone good w/ regexes should be able to come up with a single regex for all IPv6 address types. Actually, I guess you could have a single regex that matches both IPv4 and IPv6. |
46,155 | <p>I'd like to check if the user input is an email address in JavaScript, before sending it to a server or attempting to send an email to it, to prevent the most basic mistyping. How could I achieve this?</p>
| [
{
"answer_id": 46170,
"author": "Ben Scheirman",
"author_id": 3381,
"author_profile": "https://Stackoverflow.com/users/3381",
"pm_score": 7,
"selected": false,
"text": "<p>JavaScript can match a regular expression:</p>\n<pre><code>emailAddress.match( / some_regex /);\n</code></pre>\n<p>Here's an <a href=\"https://www.rfc-editor.org/rfc/rfc22\" rel=\"noreferrer\">RFC22</a> regular expression for emails:</p>\n<pre><code>^((?>[a-zA-Z\\d!#$%&'*+\\-/=?^_`{|}~]+\\x20*|"((?=[\\x01-\\x7f])[^"\\\\]|\\\\[\\x01-\\x7f])*\n"\\x20*)*(?<angle><))?((?!\\.)(?>\\.?[a-zA-Z\\d!#$%&'*+\\-/=?^_`{|}~]+)+|"((?=[\\x01-\\x\n7f])[^"\\\\]|\\\\[\\x01-\\x7f])*")@(((?!-)[a-zA-Z\\d\\-]+(?<!-)\\.)+[a-zA-Z]{2,}|\\[(((?(?<\n!\\[)\\.)(25[0-5]|2[0-4]\\d|[01]?\\d?\\d)){4}|[a-zA-Z\\d\\-]*[a-zA-Z\\d]:((?=[\\x01-\\x7f])\n[^\\\\\\[\\]]|\\\\[\\x01-\\x7f])+)\\])(?(angle)>)$\n</code></pre>\n"
},
{
"answer_id": 46181,
"author": "John Rutherford",
"author_id": 3880,
"author_profile": "https://Stackoverflow.com/users/3880",
"pm_score": 14,
"selected": true,
"text": "<p>Using <a href=\"http://en.wikipedia.org/wiki/Regular_expression\" rel=\"noreferrer\">regular expressions</a> is probably the best way. You can see a bunch of tests <a href=\"http://jsfiddle.net/ghvj4gy9/embedded/result,js/\" rel=\"noreferrer\">here</a> (taken from <a href=\"https://cs.chromium.org/chromium/src/third_party/blink/web_tests/fast/forms/resources/ValidityState-typeMismatch-email.js?q=ValidityState-typeMismatch-email.js&sq=package:chromium&dr\" rel=\"noreferrer\">chromium</a>)</p>\n<pre class=\"lang-js prettyprint-override\"><code>const validateEmail = (email) => {\n return String(email)\n .toLowerCase()\n .match(\n /^(([^<>()[\\]\\\\.,;:\\s@"]+(\\.[^<>()[\\]\\\\.,;:\\s@"]+)*)|(".+"))@((\\[[0-9]{1,3}\\.[0-9]{1,3}\\.[0-9]{1,3}\\.[0-9]{1,3}\\])|(([a-zA-Z\\-0-9]+\\.)+[a-zA-Z]{2,}))$/\n );\n};\n</code></pre>\n<p>Here's the example of a regular expression that accepts unicode:</p>\n<pre class=\"lang-js prettyprint-override\"><code>const re =\n /^(([^<>()[\\]\\.,;:\\s@\\"]+(\\.[^<>()[\\]\\.,;:\\s@\\"]+)*)|(\\".+\\"))@(([^<>()[\\]\\.,;:\\s@\\"]+\\.)+[^<>()[\\]\\.,;:\\s@\\"]{2,})$/i;\n</code></pre>\n<p>But keep in mind that one should not rely only upon JavaScript validation. JavaScript can easily be disabled. This should be validated on the server side as well.</p>\n<p>Here's an example of the above in action:</p>\n<p><div class=\"snippet\" data-lang=\"js\" data-hide=\"false\" data-console=\"true\" data-babel=\"false\">\r\n<div class=\"snippet-code\">\r\n<pre class=\"snippet-code-js lang-js prettyprint-override\"><code>const validateEmail = (email) => {\n return email.match(\n /^(([^<>()[\\]\\\\.,;:\\s@\\\"]+(\\.[^<>()[\\]\\\\.,;:\\s@\\\"]+)*)|(\\\".+\\\"))@((\\[[0-9]{1,3}\\.[0-9]{1,3}\\.[0-9]{1,3}\\.[0-9]{1,3}\\])|(([a-zA-Z\\-0-9]+\\.)+[a-zA-Z]{2,}))$/\n );\n};\n\nconst validate = () => {\n const $result = $('#result');\n const email = $('#email').val();\n $result.text('');\n\n if (validateEmail(email)) {\n $result.text(email + ' is valid :)');\n $result.css('color', 'green');\n } else {\n $result.text(email + ' is not valid :(');\n $result.css('color', 'red');\n }\n return false;\n}\n\n$('#email').on('input', validate);</code></pre>\r\n<pre class=\"snippet-code-html lang-html prettyprint-override\"><code><script src=\"https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js\"></script>\n\n<label for=\"email\">Enter an email address: </label>\n<input id=\"email\" />\n<h2 id=\"result\"></h2></code></pre>\r\n</div>\r\n</div>\r\n</p>\n"
},
{
"answer_id": 48800,
"author": "Jaymon",
"author_id": 5006,
"author_profile": "https://Stackoverflow.com/users/5006",
"pm_score": 9,
"selected": false,
"text": "<p>Wow, there are lots of complexity here. If all you want to do is just catch the most obvious syntax errors, I would do something like this:</p>\n<pre><code>^\\S+@\\S+$\n</code></pre>\n<p>It usually catches the most obvious errors that the user makes and assures that the form is mostly right, which is what JavaScript validation is all about.</p>\n<p>EDIT:\nWe can also check for '.' in the email using</p>\n<pre><code>/^\\S+@\\S+\\.\\S+$/\n</code></pre>\n"
},
{
"answer_id": 815232,
"author": "Paolo Bergantino",
"author_id": 16417,
"author_profile": "https://Stackoverflow.com/users/16417",
"pm_score": 9,
"selected": false,
"text": "<p>There's something you have to understand the second you decide to use a regular expression to validate emails: <a href=\"http://ex-parrot.com/~pdw/Mail-RFC822-Address.html\" rel=\"noreferrer\">It's probably not a good idea</a>. Once you have come to terms with that, there are many implementations out there that can get you halfway there, <a href=\"http://www.regular-expressions.info/email.html\" rel=\"noreferrer\">this article sums them up nicely.</a></p>\n\n<p>In short, however, the only way to be absolutely, positively sure that what the user entered is in fact an email is to actually send an email and see what happens. Other than that it's all just guesses.</p>\n"
},
{
"answer_id": 815235,
"author": "Adam McKee",
"author_id": 98601,
"author_profile": "https://Stackoverflow.com/users/98601",
"pm_score": 6,
"selected": false,
"text": "<p>This was stolen from <a href=\"http://codesnippets.joyent.com/posts/show/1917\" rel=\"noreferrer\">http://codesnippets.joyent.com/posts/show/1917</a></p>\n\n<pre><code>email = $('email');\nfilter = /^([a-zA-Z0-9_\\.\\-])+\\@(([a-zA-Z0-9\\-])+\\.)+([a-zA-Z0-9]{2,4})+$/;\nif (filter.test(email.value)) {\n // Yay! valid\n return true;\n}\nelse\n {return false;}\n</code></pre>\n"
},
{
"answer_id": 815242,
"author": "jacobangel",
"author_id": 31318,
"author_profile": "https://Stackoverflow.com/users/31318",
"pm_score": 5,
"selected": false,
"text": "<p>It's hard to get an email validator 100% correct. The only real way to get it correct would be to send a test email to the account. That said, there are a few basic checks that can help make sure that you're getting something reasonable.</p>\n\n<p>Some things to improve:</p>\n\n<p>Instead of new <code>RegExp</code>, just try writing the <code>regexp</code> out like this:</p>\n\n<pre><code>if (reg.test(/@/))\n</code></pre>\n\n<p>Second, check to make sure that a period comes after the <code>@</code> sign, and make sure that there are characters between the <code>@</code>s and periods. </p>\n"
},
{
"answer_id": 1373724,
"author": "Esteban Küber",
"author_id": 34813,
"author_profile": "https://Stackoverflow.com/users/34813",
"pm_score": 10,
"selected": false,
"text": "<p>Just for completeness, <a href=\"http://www.regular-expressions.info/email.html\" rel=\"noreferrer\">here you have another RFC 2822 compliant regex</a></p>\n<blockquote>\n<p>The official standard is known as <a href=\"https://www.rfc-editor.org/rfc/rfc2822#section-3.4.1\" rel=\"noreferrer\">RFC 2822</a>. It describes the syntax that valid email addresses must adhere to. You can (<strong>but you shouldn't</strong> — <a href=\"http://www.regular-expressions.info/email.html\" rel=\"noreferrer\">read on</a>) implement it with this regular expression:</p>\n<p><code>(?:[a-z0-9!#$%&'*+/=?^_`{|}~-]+(?:\\.[a-z0-9!#$%&'*+/=?^_`{|}~-]+)*|"(?:[\\x01-\\x08\\x0b\\x0c\\x0e-\\x1f\\x21\\x23-\\x5b\\x5d-\\x7f]|\\\\[\\x01-\\x09\\x0b\\x0c\\x0e-\\x7f])*")@(?:(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\\.)+[a-z0-9](?:[a-z0-9-]*[a-z0-9])?|\\[(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\\.){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?|[a-z0-9-]*[a-z0-9]:(?:[\\x01-\\x08\\x0b\\x0c\\x0e-\\x1f\\x21-\\x5a\\x53-\\x7f]|\\\\[\\x01-\\x09\\x0b\\x0c\\x0e-\\x7f])+)\\])</code></p>\n<p>(...) We get a more practical implementation of RFC 2822 if we omit the syntax using double quotes and square brackets. <strong>It will still match 99.99% of all email addresses in actual use today.</strong></p>\n<p><code>[a-z0-9!#$%&'*+/=?^_`{|}~-]+(?:\\.[a-z0-9!#$%&'*+/=?^_`{|}~-]+)*@(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\\.)+[a-z0-9](?:[a-z0-9-]*[a-z0-9])?</code></p>\n<p>A further change you could make is to allow any two-letter country code top level domain, and only specific generic top level domains. <strong>This regex filters dummy email addresses like <code>[email protected]</code></strong>. You <strong>will need to update it as new top-level domains are added</strong>.</p>\n<p><code>[a-z0-9!#$%&'*+/=?^_`{|}~-]+(?:\\.[a-z0-9!#$%&'*+/=?^_`{|}~-]+)*@(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\\.)+(?:[A-Z]{2}|com|org|net|gov|mil|biz|info|mobi|name|aero|jobs|museum)\\b</code></p>\n<p>So even when following official standards, there are still trade-offs to be made. <em><strong>Don't blindly copy regular expressions from online libraries or discussion forums. Always test them on your own data and with your own applications.</strong></em></p>\n</blockquote>\n<p><sub>Emphasis mine</sub></p>\n"
},
{
"answer_id": 2932827,
"author": "Eric Schoonover",
"author_id": 3957,
"author_profile": "https://Stackoverflow.com/users/3957",
"pm_score": 4,
"selected": false,
"text": "<p>Here is a very good discussion about using regular expressions to validate email addresses; \"<a href=\"http://fightingforalostcause.net/misc/2006/compare-email-regex.php\" rel=\"noreferrer\">Comparing E-mail Address Validating Regular Expressions</a>\"</p>\n\n<p>Here is the current top expression, that is JavaScript compatible, for reference purposes:</p>\n\n<pre><code>/^[-a-z0-9~!$%^&*_=+}{\\'?]+(\\.[-a-z0-9~!$%^&*_=+}{\\'?]+)*@([a-z0-9_][-a-z0-9_]*(\\.[-a-z0-9_]+)*\\.(aero|arpa|biz|com|coop|edu|gov|info|int|mil|museum|name|net|org|pro|travel|mobi|[a-z][a-z])|([0-9]{1,3}\\.[0-9]{1,3}\\.[0-9]{1,3}\\.[0-9]{1,3}))(:[0-9]{1,5})?$/i\n</code></pre>\n"
},
{
"answer_id": 3838001,
"author": "Félix Saparelli",
"author_id": 231788,
"author_profile": "https://Stackoverflow.com/users/231788",
"pm_score": 4,
"selected": false,
"text": "<p>Apparently, that's it:</p>\n\n<pre><code>/^([\\w\\!\\#$\\%\\&\\'\\*\\+\\-\\/\\=\\?\\^\\`{\\|\\}\\~]+\\.)*[\\w\\!\\#$\\%\\&\\'\\*\\+\\-\\/\\=\\?\\^\\`{\\|\\}\\~]+@((((([a-z0-9]{1}[a-z0-9\\-]{0,62}[a-z0-9]{1})|[a-z])\\.)+[a-z]{2,6})|(\\d{1,3}\\.){3}\\d{1,3}(\\:\\d{1,5})?)$/i\n</code></pre>\n\n<p>Taken from <a href=\"http://fightingforalostcause.net/misc/2006/compare-email-regex.php\" rel=\"noreferrer\">http://fightingforalostcause.net/misc/2006/compare-email-regex.php</a> on Oct 1 '10.</p>\n\n<p>But, of course, that's ignoring internationalization.</p>\n"
},
{
"answer_id": 5166806,
"author": "Miloš Rašić",
"author_id": 590569,
"author_profile": "https://Stackoverflow.com/users/590569",
"pm_score": 6,
"selected": false,
"text": "<p>Correct validation of email address in compliance with the RFCs is not something that can be achieved with a one-liner regular expression. An article with the best solution I've found in PHP is <em><a href=\"http://www.dominicsayers.com/isemail/\" rel=\"noreferrer\">What is a valid email address?</a></em>. Obviously, it has been ported to Java. <strike>I think the function is too complex to be ported and used in JavaScript.</strike> JavaScript/node.js port: <a href=\"https://www.npmjs.com/package/email-addresses\" rel=\"noreferrer\">https://www.npmjs.com/package/email-addresses</a>.</p>\n\n<p>A good practice is to validate your data on the client, but double-check the validation on the server. With this in mind, you can simply check whether a string looks like a valid email address on the client and perform the strict check on the server.</p>\n\n<p>Here's the JavaScript function I use to check if a string looks like a valid mail address:</p>\n\n<pre><code>function looksLikeMail(str) {\n var lastAtPos = str.lastIndexOf('@');\n var lastDotPos = str.lastIndexOf('.');\n return (lastAtPos < lastDotPos && lastAtPos > 0 && str.indexOf('@@') == -1 && lastDotPos > 2 && (str.length - lastDotPos) > 2);\n}\n</code></pre>\n\n<p>Explanation:</p>\n\n<ul>\n<li><p><code>lastAtPos < lastDotPos</code>: Last <code>@</code> should be before last <code>.</code> since <code>@</code> cannot be part of server name (as far as I know).</p></li>\n<li><p><code>lastAtPos > 0</code>: There should be something (the email username) before the last <code>@</code>.</p></li>\n<li><p><code>str.indexOf('@@') == -1</code>: There should be no <code>@@</code> in the address. Even if <code>@</code> appears as the last character in email username, it has to be quoted so <code>\"</code> would be between that <code>@</code> and the last <code>@</code> in the address.</p></li>\n<li><p><code>lastDotPos > 2</code>: There should be at least three characters before the last dot, for example <code>[email protected]</code>.</p></li>\n<li><p><code>(str.length - lastDotPos) > 2</code>: There should be enough characters after the last dot to form a two-character domain. I'm not sure if the brackets are necessary.</p></li>\n</ul>\n"
},
{
"answer_id": 7791100,
"author": "Anoop",
"author_id": 460942,
"author_profile": "https://Stackoverflow.com/users/460942",
"pm_score": 8,
"selected": false,
"text": "<p>HTML5 itself has email validation. If your browser supports HTML5 then you can use the following code.</p>\n<pre class=\"lang-html prettyprint-override\"><code><form>\n <label>Email Address\n <input type="email" placeholder="[email protected]" required>\n </label>\n <input type="submit">\n</form>\n</code></pre>\n<p><a href=\"http://jsfiddle.net/edwinthomas25/z6wev5L0/\" rel=\"noreferrer\">jsFiddle</a> link</p>\n<p>From the <a href=\"http://www.w3.org/TR/html5/forms.html#valid-e-mail-address\" rel=\"noreferrer\">HTML5 spec</a>:</p>\n<blockquote>\n<p>A <strong>valid e-mail address</strong> is a string that matches the <code>email</code> production of the following ABNF, the character set for which is Unicode.</p>\n<pre><code>email = 1*( atext / "." ) "@" label *( "." label )\nlabel = let-dig [ [ ldh-str ] let-dig ] ; limited to a length of 63 characters by RFC 1034 section 3.5\natext = < as defined in RFC 5322 section 3.2.3 >\nlet-dig = < as defined in RFC 1034 section 3.5 >\nldh-str = < as defined in RFC 1034 section 3.5 >\n</code></pre>\n<p>This requirement is a <a href=\"http://www.w3.org/TR/html5/introduction.html#willful-violation\" rel=\"noreferrer\">willful violation</a> of RFC 5322, which defines a syntax for e-mail addresses that is simultaneously too strict (before the "@" character), too vague (after the "@" character), and too lax (allowing comments, whitespace characters, and quoted strings in manners unfamiliar to most users) to be of practical use here.</p>\n<p>The following JavaScript- and Perl-compatible regular expression is an implementation of the above definition.</p>\n<pre><code>/^[a-zA-Z0-9.!#$%&'*+\\/=?^_`{|}~-]+@[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\\.[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)*$/\n</code></pre>\n</blockquote>\n"
},
{
"answer_id": 8565823,
"author": "Zo72",
"author_id": 246394,
"author_profile": "https://Stackoverflow.com/users/246394",
"pm_score": 5,
"selected": false,
"text": "<p>You should not use regular expressions to validate an input string to check if it's an email. It's too complicated and would not cover all the cases.</p>\n\n<p>Now since you can only cover 90% of the cases, write something like:</p>\n\n<pre><code>function isPossiblyValidEmail(txt) {\n return txt.length > 5 && txt.indexOf('@')>0;\n}\n</code></pre>\n\n<p>You can refine it. For instance, 'aaa@' is valid. But overall you get the gist. And don't get carried away... A simple 90% solution is better than 100% solution that does not work. </p>\n\n<p>The world needs simpler code...</p>\n"
},
{
"answer_id": 9204568,
"author": "C. Lee",
"author_id": 270821,
"author_profile": "https://Stackoverflow.com/users/270821",
"pm_score": 10,
"selected": false,
"text": "<p>I've slightly modified <a href=\"https://stackoverflow.com/a/48800/4832311\">Jaymon's answer</a> for people who want really simple validation in the form of:</p>\n<pre><code>[email protected]\n</code></pre>\n<p>The regular expression:</p>\n<pre><code>/^\\S+@\\S+\\.\\S+$/\n</code></pre>\n<p>To prevent matching multiple @ signs:</p>\n<pre><code>/^[^\\s@]+@[^\\s@]+\\.[^\\s@]+$/\n</code></pre>\n<p>The above regexes match the whole string, remove the leading and <code>^</code> and trailing <code>$</code> if you want to match anywhere in the string. The example below matches <em>anywhere</em> in the string.</p>\n<p>If you do want to match the whole sring, you may want to <code>trim()</code> the string first.</p>\n<p>Example JavaScript function:</p>\n<p><div class=\"snippet\" data-lang=\"js\" data-hide=\"false\" data-console=\"true\" data-babel=\"false\">\r\n<div class=\"snippet-code\">\r\n<pre class=\"snippet-code-js lang-js prettyprint-override\"><code>function validateEmail(email) {\n var re = /\\S+@\\S+\\.\\S+/;\n return re.test(email);\n}\n \nconsole.log(validateEmail('my email is [email protected]')); // true\n \nconsole.log(validateEmail('my email is anystring@anystring .any')); // false</code></pre>\r\n</div>\r\n</div>\r\n</p>\n"
},
{
"answer_id": 10906478,
"author": "Steve C",
"author_id": 587543,
"author_profile": "https://Stackoverflow.com/users/587543",
"pm_score": 4,
"selected": false,
"text": "<p>In contrast to <em>squirtle</em>, here is a complex solution, but it does a mighty fine job of validating emails properly:</p>\n\n<pre><code>function isEmail(email) { \n return /^((([a-z]|\\d|[!#\\$%&'\\*\\+\\-\\/=\\?\\^_`{\\|}~]|[\\u00A0-\\uD7FF\\uF900-\\uFDCF\\uFDF0-\\uFFEF])+(\\.([a-z]|\\d|[!#\\$%&'\\*\\+\\-\\/=\\?\\^_`{\\|}~]|[\\u00A0-\\uD7FF\\uF900-\\uFDCF\\uFDF0-\\uFFEF])+)*)|((\\x22)((((\\x20|\\x09)*(\\x0d\\x0a))?(\\x20|\\x09)+)?(([\\x01-\\x08\\x0b\\x0c\\x0e-\\x1f\\x7f]|\\x21|[\\x23-\\x5b]|[\\x5d-\\x7e]|[\\u00A0-\\uD7FF\\uF900-\\uFDCF\\uFDF0-\\uFFEF])|(\\\\([\\x01-\\x09\\x0b\\x0c\\x0d-\\x7f]|[\\u00A0-\\uD7FF\\uF900-\\uFDCF\\uFDF0-\\uFFEF]))))*(((\\x20|\\x09)*(\\x0d\\x0a))?(\\x20|\\x09)+)?(\\x22)))@((([a-z]|\\d|[\\u00A0-\\uD7FF\\uF900-\\uFDCF\\uFDF0-\\uFFEF])|(([a-z]|\\d|[\\u00A0-\\uD7FF\\uF900-\\uFDCF\\uFDF0-\\uFFEF])([a-z]|\\d|-|\\.|_|~|[\\u00A0-\\uD7FF\\uF900-\\uFDCF\\uFDF0-\\uFFEF])*([a-z]|\\d|[\\u00A0-\\uD7FF\\uF900-\\uFDCF\\uFDF0-\\uFFEF])))\\.)+(([a-z]|[\\u00A0-\\uD7FF\\uF900-\\uFDCF\\uFDF0-\\uFFEF])|(([a-z]|[\\u00A0-\\uD7FF\\uF900-\\uFDCF\\uFDF0-\\uFFEF])([a-z]|\\d|-|\\.|_|~|[\\u00A0-\\uD7FF\\uF900-\\uFDCF\\uFDF0-\\uFFEF])*([a-z]|[\\u00A0-\\uD7FF\\uF900-\\uFDCF\\uFDF0-\\uFFEF])))$/i.test(email);\n} \n</code></pre>\n\n<p>Use like so:<br><br></p>\n\n<pre><code>if (isEmail('[email protected]')){ console.log('This is email is valid'); }\n</code></pre>\n"
},
{
"answer_id": 12199843,
"author": "Darren Cato",
"author_id": 111291,
"author_profile": "https://Stackoverflow.com/users/111291",
"pm_score": 3,
"selected": false,
"text": "<p>Sectrean's solution works great, but it was failing my <a href=\"https://en.wikipedia.org/wiki/Lint_%28software%29\" rel=\"nofollow\">linter</a>. So I added some escapes:</p>\n\n<pre><code>function validateEmail(email){ \n var re = /^(([^<>()[]\\\\.,;:\\s@\\\"]+(\\.[^<>()[]\\\\.,;:\\s@\\\"]+)*)|(\\\".+\\\"))@(([[0-9]{1,3}\\.[0-9]{1,3}\\.[0-9]{1,3}\\.[0-9]{1,3}])|(([a-zA-Z\\-0-9]+\\.)+[a-zA-Z]{2,}))$/; \n return re.test(email); \n}\n</code></pre>\n"
},
{
"answer_id": 13178771,
"author": "Ryan Taylor",
"author_id": 845413,
"author_profile": "https://Stackoverflow.com/users/845413",
"pm_score": 6,
"selected": false,
"text": "<p>Do this:</p>\n<pre><code>^([a-zA-Z0-9!#$%&'*+\\/=?^_`{|}~-]+(?:\\.[a-zA-Z0-9!#$%&'*+\\/=?^_`{|}~-]+)*@(?:[a-zA-Z0-9](?:[a-zA-Z0-9-]*[a-zA-Z0-9])?\\.)+[a-zA-Z0-9](?:[a-zA-Z0-9-]*[a-zA-Z0-9])?)$\n</code></pre>\n<p><strong>It's based on <a href=\"https://www.ietf.org/rfc/rfc2822.txt\" rel=\"noreferrer\">RFC 2822</a></strong></p>\n<p>Test it at <a href=\"https://regex101.com/r/857lzc/1\" rel=\"noreferrer\">https://regex101.com/r/857lzc/1</a></p>\n<p>Often when storing email addresses in the database I make them lowercase and, in practice, regexs can usually be marked case insensitive. In those cases this is slightly shorter:</p>\n<pre><code>[a-z0-9!#$%&'*+/=?^_`{|}~-]+(?:\\.[a-z0-9!#$%&'*+/=?^_`{|}~-]+)*@(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\\.)+[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\n</code></pre>\n<p>Here's an example of it being used in JavaScript (with the case insensitive flag <code>i</code> at the end).</p>\n<pre><code>var emailCheck=/^[a-z0-9!#$%&'*+/=?^_`{|}~-]+(?:\\.[a-z0-9!#$%&'*+/=?^_`{|}~-]+)*@(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\\.)+[a-z0-9](?:[a-z0-9-]*[a-z0-9])?$/i;\nconsole.log( emailCheck.test('[email protected]') );\n</code></pre>\n<p><strong>Note</strong>:<br />\nTechnically some emails can include quotes in the section before the <code>@</code> symbol with escape characters inside the quotes (so your email user can be obnoxious and contain stuff like <code>@</code> and <code>"..."</code> as long as it's written in quotes). NOBODY DOES THIS EVER! It's obsolete. But, it IS included in the true <a href=\"https://www.ietf.org/rfc/rfc2822.txt\" rel=\"noreferrer\">RFC 2822</a> standard and omitted here.</p>\n<p><strong>Note 2</strong>:\nThe beginning of an email (before the @ sign) <em>can</em> be case sensitive (via the spec). However, anyone with a case-sensitive email is probably used to having issues, and, in practice, case insensitive is a safe assumption. More info: <a href=\"https://stackoverflow.com/questions/9807909/are-email-addresses-case-sensitive\">Are email addresses case sensitive?</a></p>\n<p>More info: <a href=\"http://www.regular-expressions.info/email.html\" rel=\"noreferrer\">http://www.regular-expressions.info/email.html</a></p>\n"
},
{
"answer_id": 13975255,
"author": "Boldewyn",
"author_id": 113195,
"author_profile": "https://Stackoverflow.com/users/113195",
"pm_score": 7,
"selected": false,
"text": "<p>In modern browsers you can build on top of @Sushil's answer with pure JavaScript and the <a href=\"http://en.wikipedia.org/wiki/Document_Object_Model\" rel=\"noreferrer\">DOM</a>:</p>\n\n<pre><code>function validateEmail(value) {\n var input = document.createElement('input');\n\n input.type = 'email';\n input.required = true;\n input.value = value;\n\n return typeof input.checkValidity === 'function' ? input.checkValidity() : /\\S+@\\S+\\.\\S+/.test(value);\n}\n</code></pre>\n\n<p>I've put together an example in the fiddle <a href=\"http://jsfiddle.net/boldewyn/2b6d5/\" rel=\"noreferrer\">http://jsfiddle.net/boldewyn/2b6d5/</a>. Combined with feature detection and the bare-bones validation from <a href=\"https://stackoverflow.com/a/9204568/324094\">Squirtle's Answer</a>, it frees you from the regular expression massacre and does not bork on old browsers.</p>\n"
},
{
"answer_id": 14622590,
"author": "Tugrul",
"author_id": 1172945,
"author_profile": "https://Stackoverflow.com/users/1172945",
"pm_score": 4,
"selected": false,
"text": "<p><div class=\"snippet\" data-lang=\"js\" data-hide=\"false\" data-console=\"true\" data-babel=\"false\">\r\n<div class=\"snippet-code\">\r\n<pre class=\"snippet-code-js lang-js prettyprint-override\"><code>var testresults\n\nfunction checkemail() {\n var str = document.validation.emailcheck.value\n var filter = /^([\\w-]+(?:\\.[\\w-]+)*)@((?:[\\w-]+\\.)*\\w[\\w-]{0,66})\\.([a-z]{2,6}(?:\\.[a-z]{2})?)$/i\n if (filter.test(str))\n testresults = true\n else {\n alert(\"Please input a valid email address!\")\n testresults = false\n }\n return (testresults)\n}\n\nfunction checkbae() {\n if (document.layers || document.getElementById || document.all)\n return checkemail()\n else\n return true\n}</code></pre>\r\n<pre class=\"snippet-code-html lang-html prettyprint-override\"><code><form name=\"validation\" onSubmit=\"return checkbae()\">\n Please input a valid email address:<br />\n\n <input type=\"text\" size=18 name=\"emailcheck\">\n <input type=\"submit\" value=\"Submit\">\n</form></code></pre>\r\n</div>\r\n</div>\r\n</p>\n"
},
{
"answer_id": 16014483,
"author": "Linkmichiel",
"author_id": 738331,
"author_profile": "https://Stackoverflow.com/users/738331",
"pm_score": 4,
"selected": false,
"text": "<p>My knowledge of <a href=\"http://en.wikipedia.org/wiki/Regular_expression\" rel=\"noreferrer\">regular expressions</a> is not that good. That's why I check the general syntax with a simple regular expression first and check more specific options with other functions afterwards. This may not be not the best technical solution, but this way I'm way more flexible and faster.</p>\n\n<p>The most common errors I've come across are spaces (especially at the beginning and end) and occasionally a double dot.</p>\n\n<pre><code>function check_email(val){\n if(!val.match(/\\S+@\\S+\\.\\S+/)){ // Jaymon's / Squirtle's solution\n // Do something\n return false;\n }\n if( val.indexOf(' ')!=-1 || val.indexOf('..')!=-1){\n // Do something\n return false;\n }\n return true;\n}\n\ncheck_email('check@thiscom'); // Returns false\ncheck_email('[email protected]'); // Returns false\ncheck_email(' [email protected]'); // Returns false\ncheck_email('[email protected]'); // Returns true\n</code></pre>\n"
},
{
"answer_id": 16016476,
"author": "Bob van Luijt",
"author_id": 1501285,
"author_profile": "https://Stackoverflow.com/users/1501285",
"pm_score": 6,
"selected": false,
"text": "<p>This is the correct RFC822 version.</p>\n\n<pre><code>function checkEmail(emailAddress) {\n var sQtext = '[^\\\\x0d\\\\x22\\\\x5c\\\\x80-\\\\xff]';\n var sDtext = '[^\\\\x0d\\\\x5b-\\\\x5d\\\\x80-\\\\xff]';\n var sAtom = '[^\\\\x00-\\\\x20\\\\x22\\\\x28\\\\x29\\\\x2c\\\\x2e\\\\x3a-\\\\x3c\\\\x3e\\\\x40\\\\x5b-\\\\x5d\\\\x7f-\\\\xff]+';\n var sQuotedPair = '\\\\x5c[\\\\x00-\\\\x7f]';\n var sDomainLiteral = '\\\\x5b(' + sDtext + '|' + sQuotedPair + ')*\\\\x5d';\n var sQuotedString = '\\\\x22(' + sQtext + '|' + sQuotedPair + ')*\\\\x22';\n var sDomain_ref = sAtom;\n var sSubDomain = '(' + sDomain_ref + '|' + sDomainLiteral + ')';\n var sWord = '(' + sAtom + '|' + sQuotedString + ')';\n var sDomain = sSubDomain + '(\\\\x2e' + sSubDomain + ')*';\n var sLocalPart = sWord + '(\\\\x2e' + sWord + ')*';\n var sAddrSpec = sLocalPart + '\\\\x40' + sDomain; // complete RFC822 email address spec\n var sValidEmail = '^' + sAddrSpec + '$'; // as whole string\n\n var reValidEmail = new RegExp(sValidEmail);\n\n return reValidEmail.test(emailAddress);\n}\n</code></pre>\n"
},
{
"answer_id": 17290569,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 5,
"selected": false,
"text": "<p>Simply check out if the entered email address is valid or not using HTML.</p>\n\n<pre><code><input type=\"email\"/>\n</code></pre>\n\n<p>There isn't any need to write a function for validation.</p>\n"
},
{
"answer_id": 17642237,
"author": "Colonel Panic",
"author_id": 284795,
"author_profile": "https://Stackoverflow.com/users/284795",
"pm_score": 6,
"selected": false,
"text": "<p>All email addresses contain an 'at' (i.e. @) symbol. Test that necessary condition:</p>\n<pre><code>email.includes('@')\n</code></pre>\n<p>Or, if you need to support IE/older browsers:</p>\n<pre><code>email.indexOf('@') > 0\n</code></pre>\n<p>Don't bother with anything more complicated. Even if you could perfectly determine whether an email is RFC-syntactically valid, that wouldn't tell you whether it belongs to the person who supplied it. That's what really matters.</p>\n<p>To test that, send a validation message.</p>\n"
},
{
"answer_id": 18719180,
"author": "Simon Steele",
"author_id": 4591,
"author_profile": "https://Stackoverflow.com/users/4591",
"pm_score": 2,
"selected": false,
"text": "<p>If you're using Closure you can use the built-in <code>goog.format.EmailAddress</code> type:</p>\n\n<blockquote>\n <p><a href=\"http://web.archive.org/web/20140130083649/http://docs.closure-library.googlecode.com/git/class_goog_format_EmailAddress.html\" rel=\"nofollow\">http://docs.closure-library.googlecode.com/git/class_goog_format_EmailAddress.html</a></p>\n</blockquote>\n\n<p>For example:</p>\n\n<pre><code>goog.format.EmailAddress.isValidAddrSpec(\"[email protected]\")\n</code></pre>\n\n<p>Note that by reading the source (linked above) you can see the comments state that IDN are not supported and that it only aims to cover <em>most</em> addresses:</p>\n\n<pre><code>// This is a fairly naive implementation, but it covers 99% of use cases.\n// For more details, see http://en.wikipedia.org/wiki/Email_address#Syntax\n// TODO(mariakhomenko): we should also be handling i18n domain names as per\n// http://en.wikipedia.org/wiki/Internationalized_domain_name\n</code></pre>\n"
},
{
"answer_id": 18731676,
"author": "pera",
"author_id": 79497,
"author_profile": "https://Stackoverflow.com/users/79497",
"pm_score": 4,
"selected": false,
"text": "<p>This is how <a href=\"https://github.com/chriso/validator.js\" rel=\"noreferrer\">node-validator</a> does it:</p>\n\n<pre><code>/^(?:[\\w\\!\\#\\$\\%\\&\\'\\*\\+\\-\\/\\=\\?\\^\\`\\{\\|\\}\\~]+\\.)*[\\w\\!\\#\\$\\%\\&\\'\\*\\+\\-\\/\\=\\?\\^\\`\\{\\|\\}\\~]+@(?:(?:(?:[a-zA-Z0-9](?:[a-zA-Z0-9\\-](?!\\.)){0,61}[a-zA-Z0-9]?\\.)+[a-zA-Z0-9](?:[a-zA-Z0-9\\-](?!$)){0,61}[a-zA-Z0-9]?)|(?:\\[(?:(?:[01]?\\d{1,2}|2[0-4]\\d|25[0-5])\\.){3}(?:[01]?\\d{1,2}|2[0-4]\\d|25[0-5])\\]))$/\n</code></pre>\n"
},
{
"answer_id": 20285787,
"author": "Orchid",
"author_id": 2845463,
"author_profile": "https://Stackoverflow.com/users/2845463",
"pm_score": 4,
"selected": false,
"text": "<p>Use this code inside your validator function:</p>\n\n<pre><code>var emailID = document.forms[\"formName\"][\"form element id\"].value;\natpos = emailID.indexOf(\"@\");\ndotpos = emailID.lastIndexOf(\".\");\nif (atpos < 1 || ( dotpos - atpos < 2 ))\n{\n alert(\"Please enter correct email ID\")\n return false;\n}\n</code></pre>\n\n<p>Else you can use <a href=\"http://en.wikipedia.org/wiki/JQuery\" rel=\"noreferrer\">jQuery</a>. Inside rules define:</p>\n\n<pre><code>eMailId: {\n required: true,\n email: true\n}\n</code></pre>\n"
},
{
"answer_id": 20373180,
"author": "Neil Thompson",
"author_id": 932833,
"author_profile": "https://Stackoverflow.com/users/932833",
"pm_score": 3,
"selected": false,
"text": "<p>The regular expression provided by Microsoft within <a href=\"http://en.wikipedia.org/wiki/ASP.NET_MVC_Framework\" rel=\"noreferrer\">ASP.NET MVC</a> is</p>\n\n<pre><code>/^[\\w-]+(\\.[\\w-]+)*@([a-z0-9-]+(\\.[a-z0-9-]+)*?\\.[a-z]{2,6}|(\\d{1,3}\\.){3}\\d{1,3})(:\\d{4})?$/\n</code></pre>\n\n<p>Which I post here in case it's flawed - though it's always been perfect for my needs.</p>\n"
},
{
"answer_id": 21397719,
"author": "Ferrakkem Bhuiyan",
"author_id": 3231139,
"author_profile": "https://Stackoverflow.com/users/3231139",
"pm_score": 2,
"selected": false,
"text": "<pre><code><pre>\n**The personal_info part contains the following ASCII characters.\n1.Uppercase (A-Z) and lowercase (a-z) English letters.\n2.Digits (0-9).\n3.Characters ! # $ % & ' * + - / = ? ^ _ ` { | } ~\n4.Character . ( period, dot or fullstop) provided that it is not the first or last character and it will not come one after the other.**\n</pre>\n*Example of valid email id*\n<pre>\[email protected]\[email protected]\[email protected]\[email protected]\[email protected]\n</pre>\n<pre>\nxxxx.ourearth.com [@ is not present] \[email protected] [ tld (Top Level domain) can not start with dot \".\" ]\[email protected] [ No character before @ ]\[email protected] [ \".b\" is not a valid tld ]\[email protected] [ tld can not start with dot \".\" ]\[email protected] [ an email should not be start with \".\" ]\nxxxxx()*@gmail.com [ here the regular expression only allows character, digit, underscore and dash ]\[email protected] [double dots are not allowed\n</pre>\n**javascript mail code**\n\n function ValidateEmail(inputText)\n {\n var mailformat = /^\\w+([\\.-]?\\w+)*@\\w+([\\.-]?\\w+)*(\\.\\w{2,3})+$/;\n if(inputText.value.match(mailformat))\n {\n document.form1.text1.focus();\n return true;\n }\n else\n {\n alert(\"You have entered an invalid email address!\");\n document.form1.text1.focus();\n return false;\n }\n }\n</code></pre>\n"
},
{
"answer_id": 24704328,
"author": "Yogesh Jindal",
"author_id": 197586,
"author_profile": "https://Stackoverflow.com/users/197586",
"pm_score": 0,
"selected": false,
"text": "<p>One of my coworker shared this regex with me. I like it a lot.</p>\n\n<pre><code>function isValidEmailAddress (email) {\n var validEmail = false;\n if (email) {\n email = email.trim().toLowerCase();\n var pattern = /^[\\w-']+(\\.[\\w-']+)*@([a-zA-Z0-9]+[a-zA-Z0-9-]+(\\.[a-zA-Z0-9-]+)*?\\.[a-zA-Z]{2,6}|(\\d{1,3}\\.){3}\\d{1,3})(:\\d{4})?$/;\n validEmail = pattern.exec(email);\n }\n\n return validEmail;\n}\n\nif (typeof String.prototype.trim !== 'function') {\n String.prototype.trim = function() {\n return this.replace(/^\\s+|\\s+$/g, '');\n };\n}\n</code></pre>\n"
},
{
"answer_id": 25125279,
"author": "zeros-and-ones",
"author_id": 2094495,
"author_profile": "https://Stackoverflow.com/users/2094495",
"pm_score": 3,
"selected": false,
"text": "<p>Here is a function I use for front end email validation. (The Regular Expression came from parsley.js)</p>\n\n<pre><code><!DOCTYPE html>\n<html>\n<head>\n <title>Our Company</title>\n <style>\n .form-style {\n color: #ccc;\n }\n </style>\n</head>\n<body>\n <h1>Email Validation Form Example</h1>\n <input type=\"text\" name=\"email\" id=\"emailInput\" class=\"form-style\">\n <script>\n function validateEmail(emailAddress) {\n var regularExpression = /^((([a-z]|\\d|[!#\\$%&'\\*\\+\\-\\/=\\?\\^_`{\\|}~]|[\\u00A0-\\uD7FF\\uF900-\\uFDCF\\uFDF0-\\uFFEF])+(\\.([a-z]|\\d|[!#\\$%&'\\*\\+\\-\\/=\\?\\^_`{\\|}~]|[\\u00A0-\\uD7FF\\uF900-\\uFDCF\\uFDF0-\\uFFEF])+)*)|((\\x22)((((\\x20|\\x09)*(\\x0d\\x0a))?(\\x20|\\x09)+)?(([\\x01-\\x08\\x0b\\x0c\\x0e-\\x1f\\x7f]|\\x21|[\\x23-\\x5b]|[\\x5d-\\x7e]|[\\u00A0-\\uD7FF\\uF900-\\uFDCF\\uFDF0-\\uFFEF])|(\\\\([\\x01-\\x09\\x0b\\x0c\\x0d-\\x7f]|[\\u00A0-\\uD7FF\\uF900-\\uFDCF\\uFDF0-\\uFFEF]))))*(((\\x20|\\x09)*(\\x0d\\x0a))?(\\x20|\\x09)+)?(\\x22)))@((([a-z]|\\d|[\\u00A0-\\uD7FF\\uF900-\\uFDCF\\uFDF0-\\uFFEF])|(([a-z]|\\d|[\\u00A0-\\uD7FF\\uF900-\\uFDCF\\uFDF0-\\uFFEF])([a-z]|\\d|-|\\.|_|~|[\\u00A0-\\uD7FF\\uF900-\\uFDCF\\uFDF0-\\uFFEF])*([a-z]|\\d|[\\u00A0-\\uD7FF\\uF900-\\uFDCF\\uFDF0-\\uFFEF])))\\.)+(([a-z]|[\\u00A0-\\uD7FF\\uF900-\\uFDCF\\uFDF0-\\uFFEF])|(([a-z]|[\\u00A0-\\uD7FF\\uF900-\\uFDCF\\uFDF0-\\uFFEF])([a-z]|\\d|-|\\.|_|~|[\\u00A0-\\uD7FF\\uF900-\\uFDCF\\uFDF0-\\uFFEF])*([a-z]|[\\u00A0-\\uD7FF\\uF900-\\uFDCF\\uFDF0-\\uFFEF]))){2,6}$/i;\n return regularExpression.test(emailAddress);\n }\n\n function showEmailValidationState(event) {\n if (validateEmail(event.target.value)) {\n document.getElementById(\"emailInput\").style.color = 'black';\n }\n }\n document.getElementById(\"emailInput\").addEventListener(\"keyup\", showEmailValidationState);\n </script>\n</body>\n</html>\n</code></pre>\n"
},
{
"answer_id": 27476145,
"author": "Vitalii Fedorenko",
"author_id": 288671,
"author_profile": "https://Stackoverflow.com/users/288671",
"pm_score": 1,
"selected": false,
"text": "<p>If you are using AngularJS, just add <code>type=\"email\"</code> to the input element: </p>\n\n<blockquote>\n <p><a href=\"https://docs.angularjs.org/api/ng/input/input%5Bemail%5D\" rel=\"nofollow\">https://docs.angularjs.org/api/ng/input/input%5Bemail%5D</a></p>\n</blockquote>\n\n<p>In case there is no input element, it can be created dynamically:</p>\n\n<pre><code>var isEmail = $compile('<input ng-model=\"m\" type=\"email\">')($rootScope.$new()).\n controller('ngModel').$validators[\"email\"];\n\nif (isEmail('[email protected]')) {\n console.log('valid');\n} \n</code></pre>\n"
},
{
"answer_id": 28579110,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 1,
"selected": false,
"text": "<p>I know its not regex but any way...</p>\n\n<p>This is example with node and npm package <a href=\"https://www.npmjs.com/package/email-existence\" rel=\"nofollow\">email-existence</a> this is ultimate checking if email exist and if its in the right form :)</p>\n\n<p>This will ping the email if its responding if it got no response it will return false or else true.</p>\n\n<pre><code>function doesEmailExist(email) {\n var emailExistence = require('email-existence');\n return emailExistence.check(email,function (err,status) {\n if (status) {\n return status;\n }\n else {\n throw new Error('Email does not exist');\n }\n });\n}\n</code></pre>\n"
},
{
"answer_id": 28804496,
"author": "Code Spy",
"author_id": 1045296,
"author_profile": "https://Stackoverflow.com/users/1045296",
"pm_score": 2,
"selected": false,
"text": "<p><strong><em>Following Regex validations:</em></strong></p>\n\n<ul>\n<li>No spacial characters before @ </li>\n<li>(-) and (.) should not be together\nafter @ No special characters after @ 2 characters must before @\nEmail length should be less 128 characters</li>\n</ul>\n\n\n\n<pre><code>function validateEmail(email) {\nvar chrbeforAt = email.substr(0, email.indexOf('@'));\nif (!($.trim(email).length > 127)) {\n if (chrbeforAt.length >= 2) {\n var re = /^(([^<>()[\\]{}'^?\\\\.,!|//#%*-+=&;:\\s@\\\"]+(\\.[^<>()[\\]\\\\.,;:\\s@\\\"]+)*)|(\\\".+\\\"))@(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\\.)+[a-z0-9](?:[a-z0-9-]*[a-z0-9])?/;\n //var re = /[a-z0-9!#$%&'*+/=?^_`{|}~-]+(?:\\.[a-z0-9!#$%&'*+/=?^_`{|}~-]+)*@(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\\.)+[a-z0-9](?:[a-z0-9-]*[a-z0-9])?/;\n return re.test(email);\n } else {\n return false;\n }\n} else {\n return false;\n}\n}\n</code></pre>\n"
},
{
"answer_id": 28804516,
"author": "Code Spy",
"author_id": 1045296,
"author_profile": "https://Stackoverflow.com/users/1045296",
"pm_score": 2,
"selected": false,
"text": "<p><strong><em>Following Regex validations:</em></strong></p>\n\n<ul>\n<li>No spacial characters before @ </li>\n<li>(-) and (.) should not be together after @ </li>\n<li>No special characters after @ 2 characters must before @</li>\n<li><p>Email length should be less 128 characters</p>\n\n<pre><code>function validateEmail(email) {\n var chrbeforAt = email.substr(0, email.indexOf('@'));\n if (!($.trim(email).length > 127)) {\n if (chrbeforAt.length >= 2) {\n var re = /^(([^<>()[\\]{}'^?\\\\.,!|//#%*-+=&;:\\s@\\\"]+(\\.[^<>()[\\]\\\\.,;:\\s@\\\"]+)*)|(\\\".+\\\"))@(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\\.)+[a-z0-9](?:[a-z0-9-]*[a-z0-9])?/;\n return re.test(email);\n } else {\n return false;\n }\n } else {\n return false;\n }\n}\n</code></pre></li>\n</ul>\n"
},
{
"answer_id": 31311899,
"author": "jaydev thakkar",
"author_id": 5003158,
"author_profile": "https://Stackoverflow.com/users/5003158",
"pm_score": 0,
"selected": false,
"text": "<pre><code>\\b[a-z][\\w\\d_\\.]+@\\w+\\.[a-z]{2}[a-z]?\\.?[a-z]{,2}\\s\n</code></pre>\n\n<p>It allows:</p>\n\n<pre><code>[email protected] \[email protected] \[email protected] \[email protected]\n</code></pre>\n"
},
{
"answer_id": 31971270,
"author": "DestyNova",
"author_id": 1528682,
"author_profile": "https://Stackoverflow.com/users/1528682",
"pm_score": 2,
"selected": false,
"text": "<p>the best one :D (RFC-friendly & no error \"too complex\") :</p>\n\n<pre><code>function isMail(mail)\n{\n pattuser = /^([A-Z0-9_%+\\-!#$&'*\\/=?^`{|}~]+\\.?)*[A-Z0-9_%+\\-!#$&'*\\/=?^`{|}~]+$/i;\n pattdomain = /^([A-Z0-9-]+\\.?)*[A-Z0-9-]+(\\.[A-Z]{2,9})+$/i;\n\n tab = mail.split(\"@\");\n if (tab.length != 2)\n return false;\n return (pattuser.test(tab[0]) && pattdomain.test(tab[1]));\n}\n</code></pre>\n"
},
{
"answer_id": 32206684,
"author": "Dinesh Devkota",
"author_id": 2008447,
"author_profile": "https://Stackoverflow.com/users/2008447",
"pm_score": 1,
"selected": false,
"text": "<p>If you want to use Jquery and want to have modern approach then use JQuery input mask with validation. </p>\n\n<p><a href=\"http://bseth99.github.io/projects/jquery-ui/5-jquery-masks.html\" rel=\"nofollow\">http://bseth99.github.io/projects/jquery-ui/5-jquery-masks.html</a> </p>\n\n<p>Demo on how simple jquery input mask is here: <a href=\"http://codepen.io/anon/pen/gpRyBp\" rel=\"nofollow\">http://codepen.io/anon/pen/gpRyBp</a></p>\n\n<p><strong>Example of simple input mask for date forexample NOT full validation</strong></p>\n\n<pre><code> <input id=\"date\" type=\"text\" placeholder=\"YYYY-MM-DD\"/>\n</code></pre>\n\n<p>and the script:</p>\n\n<pre><code> $(\"#date\").mask(\"9999-99-99\",{placeholder:\"YYYY-MM-DD\"});\n</code></pre>\n"
},
{
"answer_id": 32420732,
"author": "cyberrspiritt",
"author_id": 2303664,
"author_profile": "https://Stackoverflow.com/users/2303664",
"pm_score": 3,
"selected": false,
"text": "<p>The best practice is to either use HTML5 built-in email tag.</p>\n\n<pre><code><input type=\"email\" name=\"email\">\n</code></pre>\n\n<p>or the common email syntax as recognizing @ and . from the string is given below. </p>\n\n<pre><code>^[a-zA-Z0-9_\\-.]+@[a-zA-Z0-9\\-]+\\.[a-zA-Z0-9\\-.]+$\n</code></pre>\n\n<blockquote>\n <p>Note that this would still produce <strong>invalid email</strong> that will still match\n the regex, its almost impossible to catch them all but this will\n improve the situation a little.</p>\n</blockquote>\n"
},
{
"answer_id": 32686261,
"author": "Andrew",
"author_id": 1200649,
"author_profile": "https://Stackoverflow.com/users/1200649",
"pm_score": 8,
"selected": false,
"text": "<p>I have found this to be the best solution:</p>\n\n<pre><code>/^[^\\s@]+@[^\\s@]+\\.[^\\s@]+$/\n</code></pre>\n\n<p>It allows the following formats:</p>\n\n<pre>\n1. [email protected]\n2. [email protected]\n3. [email protected]\n4. [email protected]\n9. #!$%&'*+-/=?^_`{}|[email protected]\n6. \"()[]:,;@\\\\\\\"!#$%&'*+-/=?^_`{}| ~.a\"@example.org\n7. \" \"@example.org (space between the quotes)\n8. üñîçøðé@example.com (Unicode characters in local part)\n9. üñîçøðé@üñîçøðé.com (Unicode characters in domain part)\n10. Pelé@example.com (Latin)\n11. δοκιμή@παράδειγμα.δοκιμή (Greek)\n12. 我買@屋企.香港 (Chinese)\n13. 甲斐@黒川.日本 (Japanese)\n14. чебурашка@ящик-с-апельсинами.рф (Cyrillic)\n</pre>\n\n<p>It's clearly versatile and allows the all-important international characters, while still enforcing the basic [email protected] format. It will block spaces which are technically allowed by RFC, but they are so rare that I'm happy to do this.</p>\n"
},
{
"answer_id": 37540637,
"author": "Priya",
"author_id": 4424022,
"author_profile": "https://Stackoverflow.com/users/4424022",
"pm_score": 2,
"selected": false,
"text": "<p>Use the regular expression:</p>\n\n<pre class=\"lang-none prettyprint-override\"><code> /^[a-z][a-zA-Z0-9_.]*(\\.[a-zA-Z][a-zA-Z0-9_.]*)?@[a-z][a-zA-Z-0-9]*\\.[a-z]+(\\.[a-z]+)?$/\n</code></pre>\n\n<p>Example:</p>\n\n<pre><code>function validateEmail(email) {\n var re = /^[a-z][a-zA-Z0-9_.]*(\\.[a-zA-Z][a-zA-Z0-9_.]*)?@[a-z][a-zA-Z-0-9]*\\.[a-z]+(\\.[a-z]+)?$/;\n return re.test(email);\n}\n</code></pre>\n\n<p>It should allow only @ , . , _</p>\n"
},
{
"answer_id": 38137215,
"author": "CVE-RICK",
"author_id": 2381320,
"author_profile": "https://Stackoverflow.com/users/2381320",
"pm_score": 6,
"selected": false,
"text": "<p>I'm really looking forward to solve this problem.\nSo I modified email validation regular expression above </p>\n\n<ul>\n<li><p>Original<br>\n<code>/^(([^<>()\\[\\]\\\\.,;:\\s@\"]+(\\.[^<>()\\[\\]\\\\.,;:\\s@\"]+)*)|(\".+\"))@((\\[[0-9]{1,3}\\.[0-9]{1,3}\\.[0-9]{1,3}\\.[0-9]{1,3}])|(([a-zA-Z\\-0-9]+\\.)+[a-zA-Z]{2,}))$/</code></p></li>\n<li><p>Modified<br>\n<code>/^(([^<>()\\[\\]\\.,;:\\s@\\\"]+(\\.[^<>()\\[\\]\\.,;:\\s@\\\"]+)*)|(\\\".+\\\"))@(([^<>()\\.,;\\s@\\\"]+\\.{0,1})+[^<>()\\.,;:\\s@\\\"]{2,})$/</code></p></li>\n</ul>\n\n<p>to pass the examples in <a href=\"https://en.wikipedia.org/wiki/Email_address#cite_note-20/syntax\">Wikipedia Email Address</a>.</p>\n\n<p>And you can see the result in <a href=\"http://regexr.com/3dnsr\">here</a>.</p>\n\n<p><a href=\"https://i.stack.imgur.com/m2YBr.png\"><img src=\"https://i.stack.imgur.com/m2YBr.png\" alt=\"enter image description here\"></a></p>\n"
},
{
"answer_id": 38544440,
"author": "Kentonbmax",
"author_id": 5414462,
"author_profile": "https://Stackoverflow.com/users/5414462",
"pm_score": 2,
"selected": false,
"text": "<p>If you are using ng-pattern and material this does the job. </p>\n\n<pre><code>vm.validateEmail = '([a-zA-Z0-9_.]{1,})((@[a-zA-Z]{2,})[\\\\\\.]([a-zA-Z]{2}|[a-zA-Z]{3}))';\n</code></pre>\n"
},
{
"answer_id": 40474862,
"author": "chemic",
"author_id": 2903210,
"author_profile": "https://Stackoverflow.com/users/2903210",
"pm_score": 2,
"selected": false,
"text": "<p>Whoever is using @pvl solution and wants it to pass <a href=\"http://eslint.org/docs/rules/prefer-template\" rel=\"nofollow noreferrer\">ESLint Prefer-template</a> then here's a version where I used template literals instead of string concatenation.</p>\n\n<pre><code>validateEmail(email) {\n let sQtext = '[^\\\\x0d\\\\x22\\\\x5c\\\\x80-\\\\xff]';\n let sDtext = '[^\\\\x0d\\\\x5b-\\\\x5d\\\\x80-\\\\xff]';\n let sAtom = '[^\\\\x00-\\\\x20\\\\x22\\\\x28\\\\x29\\\\x2c\\\\x2e\\\\x3a-\\\\x3c\\\\x3e\\\\x40\\\\x5b-\\\\x5d\\\\x7f-\\\\xff]+';\n let sQuotedPair = '\\\\x5c[\\\\x00-\\\\x7f]';\n let sDomainLiteral = `\\\\x5b(${sDtext}|${sQuotedPair})*\\\\x5d`;\n let sQuotedString = `\\\\x22(${sQtext}|${sQuotedPair})*\\\\x22`;\n let sDomainRef = sAtom;\n let sSubDomain = `(${sDomainRef}|${sDomainLiteral})`;\n let sWord = `(${sAtom}|${sQuotedString})`;\n let sDomain = `${sSubDomain}(\\\\x2e${sSubDomain})*`;\n let sLocalPart = `${sWord}(\\\\x2e${sWord})*`;\n let sAddrSpec = `${sLocalPart}\\\\x40${sDomain}`; // complete RFC822 email address spec\n let sValidEmail = `^${sAddrSpec}$`; // as whole string\n\n let reValidEmail = new RegExp(sValidEmail);\n\n return reValidEmail.test(email);\n}\n</code></pre>\n"
},
{
"answer_id": 41278091,
"author": "Prabhat Kasera",
"author_id": 1167772,
"author_profile": "https://Stackoverflow.com/users/1167772",
"pm_score": 4,
"selected": false,
"text": "<p>Regex for validating email address</p>\n\n<pre><code>[a-z0-9!#$%&'*+/=?^_`{|}~-]+(?:\\.[a-z0-9!#$%&'*+/=?^_`{|}~-]+)*@(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\\.)+[a-z0-9](?:[a-z0-9-]*[a-z0-9])+\n</code></pre>\n"
},
{
"answer_id": 41354731,
"author": "bman",
"author_id": 177006,
"author_profile": "https://Stackoverflow.com/users/177006",
"pm_score": 4,
"selected": false,
"text": "<h2>A solution that does not check the existence of the TLD is incomplete.</h2>\n\n<p>Almost all answers to this questions suggest using Regex to validate emails addresses. I think Regex is only good for a rudimentary validation. It seems that the checking validation of email addresses is actually two separate problems:</p>\n\n<p><strong>1- Validation of email format:</strong> Making sure if the email complies with the format and pattern of emails in RFC 5322 and if the TLD actually exists. A list of all valid TLDs can be found <a href=\"http://data.iana.org/TLD/tlds-alpha-by-domain.txt\" rel=\"noreferrer\">here</a>.</p>\n\n<p>For example, although the address <code>[email protected]</code> will pass the regex, it is not a valid email, because <code>ccc</code> is not a top-level domain by IANA.</p>\n\n<p><strong>2- Making sure the email actually exists:</strong> For doing this, <strong>the only option</strong> is <a href=\"https://davidcel.is/posts/stop-validating-email-addresses-with-regex/#just-send-them-an-email-already\" rel=\"noreferrer\">to send the users an email</a>.</p>\n"
},
{
"answer_id": 41437076,
"author": "Negin",
"author_id": 5611484,
"author_profile": "https://Stackoverflow.com/users/5611484",
"pm_score": 4,
"selected": false,
"text": "<p>I was looking for a Regex in JS that passes all Email Address test cases:</p>\n\n<ul>\n<li><p><code>[email protected]</code> Valid email</p></li>\n<li><p><code>[email protected]</code> Email contains dot in the address field</p></li>\n<li><p><code>[email protected]</code> Email contains dot with subdomain</p></li>\n<li><p><code>[email protected]</code> Plus sign is considered valid character</p></li>\n<li><p><code>[email protected]</code> Domain is valid IP address</p></li>\n<li><p><code>email@[192.0.2.123]</code> Square bracket around IP address is considered valid</p></li>\n<li><p><code>“email”@example.com</code> Quotes around email is considered valid</p></li>\n<li><p><code>[email protected]</code> Digits in address are valid</p></li>\n<li><p><code>[email protected]</code> Dash in domain name is valid</p></li>\n<li><p><code>[email protected]</code> Underscore in the address field is valid</p></li>\n<li><p><code>[email protected]</code> <code>.name</code> is valid Top Level Domain name</p></li>\n<li><p><code>[email protected]</code> Dot in Top Level Domain name also considered valid (using <code>co.jp</code> as example here)</p></li>\n<li><p><code>[email protected]</code> Dash in address field is valid</p></li>\n</ul>\n\n<p>Here we go :</p>\n\n<p><a href=\"http://regexr.com/3f07j\" rel=\"noreferrer\">http://regexr.com/3f07j</a></p>\n\n<p>OR regex:</p>\n\n<pre><code>Regex = /(([^<>()\\[\\]\\\\.,;:\\s@\"]+(\\.[^<>()\\[\\]\\\\.,;:\\s@\"]+)*)|(\".+\"))@[*[a-zA-Z0-9-]+.[a-zA-Z0-9-.]+]*/\n</code></pre>\n"
},
{
"answer_id": 42197579,
"author": "Himanshu Teotia",
"author_id": 5031009,
"author_profile": "https://Stackoverflow.com/users/5031009",
"pm_score": 2,
"selected": false,
"text": "<p>In nodeJS you can also use validator node module and simply use like that </p>\n\n<p>Install the library with npm install validator</p>\n\n<pre><code>var validator = require('validator');\n\nvalidator.isEmail('[email protected]'); //=> true \n</code></pre>\n"
},
{
"answer_id": 42871920,
"author": "Jangli Coder",
"author_id": 4247829,
"author_profile": "https://Stackoverflow.com/users/4247829",
"pm_score": 0,
"selected": false,
"text": "<p>If you define your regular expression as a string then all backslashes need to be escaped, so instead of '\\w' you should have '\\w'.</p>\n\n<p>Alternatively, define it as a regular expression:</p>\n\n<pre><code>var pattern = /^\\w+@[a-zA-Z_]+?\\.[a-zA-Z]{2,3}$/; \n</code></pre>\n"
},
{
"answer_id": 43245721,
"author": "Abhay Shiro",
"author_id": 6775407,
"author_profile": "https://Stackoverflow.com/users/6775407",
"pm_score": 2,
"selected": false,
"text": "<p>There are some complex RegEx written here, that also works.</p>\n\n<p>I tested this one and it works too:</p>\n\n<pre><code>[a-zA-Z0-9._]+[@]+[a-zA-Z0-9]+[.]+[a-zA-Z]{2,6}\n</code></pre>\n\n<p>Please test this here : <a href=\"http://www.regextester.com/?fam=97334\" rel=\"nofollow noreferrer\">http://www.regextester.com/?fam=97334</a></p>\n\n<p>Hope this helps.</p>\n"
},
{
"answer_id": 44323593,
"author": "takatan",
"author_id": 4228476,
"author_profile": "https://Stackoverflow.com/users/4228476",
"pm_score": 1,
"selected": false,
"text": "<p>I'd like to add a short note about non-ASCII characters. Rnevius's (and co.) solution is brilliant, but it allows to add Cyrillic, Japanese, Emoticons and other unicode symbols which may be restricted by some servers.</p>\n\n<p>The code below will print <code>true</code> though it contains UTF-8 character <code>Ё</code>.</p>\n\n<p><div class=\"snippet\" data-lang=\"js\" data-hide=\"false\" data-console=\"true\" data-babel=\"false\">\r\n<div class=\"snippet-code\">\r\n<pre class=\"snippet-code-js lang-js prettyprint-override\"><code>console.log (/^(([^<>()\\[\\]\\\\.,;:\\s@\"]+(\\.[^<>()\\[\\]\\\\.,;:\\s@\"]+)*)|(\".+\"))@((\\[[0-9]{1,3}\\.[0-9]{1,3}\\.[0-9]{1,3}\\.[0-9]{1,3}])|(([a-zA-Z\\-0-9]+\\.)+[a-zA-Z]{2,}))$/.test ('Ё@example.org'))</code></pre>\r\n</div>\r\n</div>\r\n</p>\n\n<p>In my case all non-ASCII symbols are prohibited so I have modified the original expression to exclude all characters above U+007F:</p>\n\n<p><div class=\"snippet\" data-lang=\"js\" data-hide=\"false\" data-console=\"true\" data-babel=\"false\">\r\n<div class=\"snippet-code\">\r\n<pre class=\"snippet-code-js lang-js prettyprint-override\"><code>/^(([^\\u0080-\\uffff<>()\\[\\]\\\\.,;:\\s@\"]+(\\.[^\\u0080-\\uffff<>()\\[\\]\\\\.,;:\\s@\"]+)*)|(\".+\"))@((\\[[0-9]{1,3}\\.[0-9]{1,3}\\.[0-9]{1,3}\\.[0-9]{1,3}])|(([a-zA-Z\\-0-9]+\\.)+[a-zA-Z]{2,}))$/</code></pre>\r\n</div>\r\n</div>\r\n</p>\n\n<p>Maybe this will help someone to prevent undesired behaviour.</p>\n"
},
{
"answer_id": 44601723,
"author": "Alireza",
"author_id": 5423108,
"author_profile": "https://Stackoverflow.com/users/5423108",
"pm_score": 2,
"selected": false,
"text": "<p>How about creating a function which will test any string against emails' pattern using regular expression in JavaScript, as we know email addresses can be quite different in different regions, like in UK and Australia it usually ends up with <code>.co.uk</code> or <code>.com.au</code>, so I tried to cover those as well, also check if the string passed to the function, something like this:</p>\n\n<pre><code>var isEmail = function(str) {\n return typeof str==='string' && /^[\\w+\\d+._]+\\@[\\w+\\d+_+]+\\.[\\w+\\d+._]{2,8}$/.test(str);\n}\n</code></pre>\n\n<p>and check if it's email like below:</p>\n\n<pre><code>isEmail('[email protected]'); //true\nisEmail('[email protected]'); //true\nisEmail('[email protected]'); //true\nisEmail('[email protected]'); //true\nisEmail('[email protected]'); //true\nisEmail('[email protected]'); //true\nisEmail('[email protected]'); //true\nisEmail('[email protected]#sswzazaaaa'); //false\nisEmail('[email protected]'); //false\n</code></pre>\n"
},
{
"answer_id": 44671643,
"author": "Liberateur",
"author_id": 3933634,
"author_profile": "https://Stackoverflow.com/users/3933634",
"pm_score": 5,
"selected": false,
"text": "<p><strong>Wikipedia standard mail syntax :</strong></p>\n<p><a href=\"https://en.wikipedia.org/wiki/Email_address#Examples\" rel=\"noreferrer\">https://en.wikipedia.org/wiki/Email_address#Examples</a>\n<a href=\"https://fr.wikipedia.org/wiki/Adresse_%C3%A9lectronique#Syntaxe_exacte\" rel=\"noreferrer\">https://fr.wikipedia.org/wiki/Adresse_%C3%A9lectronique#Syntaxe_exacte</a></p>\n<p><strong>Function :</strong></p>\n<pre><code>function validMail(mail)\n{\n return /^(([^<>()\\[\\]\\.,;:\\s@\\"]+(\\.[^<>()\\[\\]\\.,;:\\s@\\"]+)*)|(\\".+\\"))@(([^<>()\\.,;\\s@\\"]+\\.{0,1})+([^<>()\\.,;:\\s@\\"]{2,}|[\\d\\.]+))$/.test(mail);\n}\n</code></pre>\n<p><strong>Valid emails :</strong></p>\n<pre><code>validMail('[email protected]') // Return true\nvalidMail('[email protected].') // Return true\nvalidMail('[email protected]') // Return true\nvalidMail('user@localserver') // Return true\nvalidMail('[email protected]') // Return true\nvalidMail('user+mailbox/[email protected]') // Return true\nvalidMail('"very.(),:;<>[]\\".VERY.\\"very@\\\\ \\"very\\".unusual"@strange.example.com') // Return true\nvalidMail('!#$%&\\'*+-/=?^_`.{|}[email protected]') // Return true\nvalidMail('"()<>[]:,;@\\\\\\"!#$%&\\'-/=?^_`{}| ~.a"@example.org') // Return true\nvalidMail('"Abc@def"@example.com') // Return true\nvalidMail('"Fred Bloggs"@example.com') // Return true\nvalidMail('"Joe.\\\\Blow"@example.com') // Return true\nvalidMail('Loïc.Accentué@voilà.fr') // Return true\nvalidMail('" "@example.org') // Return true\nvalidMail('user@[IPv6:2001:DB8::1]') // Return true\n</code></pre>\n<p><strong>Invalid emails :</strong></p>\n<pre><code>validMail('Abc.example.com') // Return false\nvalidMail('A@b@[email protected]') // Return false\nvalidMail('a"b(c)d,e:f;g<h>i[j\\k][email protected]') // Return false\nvalidMail('just"not"[email protected]') // Return false\nvalidMail('this is"not\\[email protected]') // Return false\nvalidMail('this\\ still\\"not\\\\[email protected]') // Return false\nvalidMail('[email protected]') // Return false\nvalidMail('[email protected]') // Return false\n</code></pre>\n<p><strong>Show this test : <a href=\"https://regex101.com/r/LHJ9gU/1\" rel=\"noreferrer\">https://regex101.com/r/LHJ9gU/1</a></strong></p>\n"
},
{
"answer_id": 44996725,
"author": "Behnam",
"author_id": 3243488,
"author_profile": "https://Stackoverflow.com/users/3243488",
"pm_score": 2,
"selected": false,
"text": "<p>ES6 sample</p>\n\n<pre><code>const validateEmail=(email)=> /^(([^<>()\\[\\]\\\\.,;:\\s@\"]+(\\.[^<>()\\[\\]\\\\.,;:\\s@\"]+)*)|(\".+\"))@((\\[[0-9]{1,3}\\.[0-9]{1,3}\\.[0-9]{1,3}\\.[0-9]{1,3}])|(([a-zA-Z\\-0-9]+\\.)+[a-zA-Z]{2,}))$/.test(email);\n</code></pre>\n"
},
{
"answer_id": 45250371,
"author": "hmharsh3",
"author_id": 3386952,
"author_profile": "https://Stackoverflow.com/users/3386952",
"pm_score": 2,
"selected": false,
"text": "<p>You can also try</p>\n\n<pre><code>var string = \"[email protected]\"\nvar exp = /(\\w(=?@)\\w+\\.{1}[a-zA-Z]{2,})/i\nalert(exp.test(string))\n</code></pre>\n"
},
{
"answer_id": 48651640,
"author": "Juan Pablo",
"author_id": 4187847,
"author_profile": "https://Stackoverflow.com/users/4187847",
"pm_score": 5,
"selected": false,
"text": "<p>Regex updated! try this</p>\n<pre><code>let val = '[email protected]';\nif(/^[a-z0-9][a-z0-9-_\\.]+@([a-z]|[a-z0-9]?[a-z0-9-]+[a-z0-9])\\.[a-z0-9]{2,10}(?:\\.[a-z]{2,10})?$/.test(val)) {\n console.log('passed');\n}\n</code></pre>\n<p>typscript version complete</p>\n<pre><code>//\nexport const emailValid = (val:string):boolean => /^[a-z0-9][a-z0-9-_\\.]+@([a-z]|[a-z0-9]?[a-z0-9-]+[a-z0-9])\\.[a-z0-9]{2,10}(?:\\.[a-z]{2,10})?$/.test(val);\n</code></pre>\n<p>more info <a href=\"https://git.io/vhEfc\" rel=\"noreferrer\">https://git.io/vhEfc</a></p>\n<p><a href=\"https://i.stack.imgur.com/uwNgO.png\" rel=\"noreferrer\"><img src=\"https://i.stack.imgur.com/uwNgO.png\" alt=\"regex test case\" /></a></p>\n"
},
{
"answer_id": 49005817,
"author": "Mizanur Rahaman",
"author_id": 8522458,
"author_profile": "https://Stackoverflow.com/users/8522458",
"pm_score": 1,
"selected": false,
"text": "<pre><code> <input type=\"email\" class=\"form-control\" required=\"required\" placeholder=\"Email Address\" name=\"Email\" id=\"Email\" autocomplete=\"Email\">\n <button class=\"btn-1 shadow-0 full-width\" type=\"button\" id=\"register\">Register account</button>\n</code></pre>\n\n<p> </p>\n\n<pre><code> $(\"#register\").click(function(){ \n var rea = /^[a-zA-Z0-9.!#$%&'*+/=?^_`{|}~-]+@[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\\.[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)*$/;\n var Email = $(\"#Email\").val();\n var x = rea.test(Email);\n if (!x) {\n alert('Type Your valid Email');\n return false;\n } \n </script>\n</code></pre>\n"
},
{
"answer_id": 49020064,
"author": "Menelaos Kotsollaris",
"author_id": 1373465,
"author_profile": "https://Stackoverflow.com/users/1373465",
"pm_score": 2,
"selected": false,
"text": "<p>Here's a simple regex that would just check for the basic format of an email e.g., <code>[email protected]</code>:</p>\n\n<p><code>\\S+@\\S+\\.\\S+</code></p>\n"
},
{
"answer_id": 50570037,
"author": "JoelBonetR",
"author_id": 6479108,
"author_profile": "https://Stackoverflow.com/users/6479108",
"pm_score": 2,
"selected": false,
"text": "<p>This question is more dificult to answer than seems at first sight.</p>\n\n<p>There were loads of people around the world looking for \"the regex to rule them all\" but the truth is that there are tones of email providers.</p>\n\n<p>What's the problem? Well, \"a_z%@gmail.com cannot exists but it may exists an address like that through another provider \"[email protected].</p>\n\n<p>Why? \nAccording to the RFC:\n<a href=\"https://en.wikipedia.org/wiki/Email_address#RFC_specification\" rel=\"nofollow noreferrer\">https://en.wikipedia.org/wiki/Email_address#RFC_specification</a>.</p>\n\n<p>I'll take an excerpt to facilitate the lecture:</p>\n\n<pre><code>The local-part of the email address may use any of these ASCII characters:\n\n- uppercase and lowercase Latin letters A to Z and a to z;\n- digits 0 to 9;\n- special characters !#$%&'*+-/=?^_`{|}~;\n- dot ., provided that it is not the first or last character unless quoted, and provided also that it does not appear consecutively unless quoted (e.g. [email protected] is not allowed but \"John..Doe\"@example.com is allowed);[6]\nNote that some mail servers wildcard local parts, typically the characters following a plus and less often the characters following a minus, so fred+bah@domain and fred+foo@domain might end up in the same inbox as fred+@domain or even as fred@domain. This can be useful for tagging emails for sorting, see below, and for spam control. Braces { and } are also used in that fashion, although less often.\n- space and \"(),:;<>@[\\] characters are allowed with restrictions (they are only allowed inside a quoted string, as described in the paragraph below, and in addition, a backslash or double-quote must be preceded by a backslash);\n- comments are allowed with parentheses at either end of the local-part; e.g. john.smith(comment)@example.com and (comment)[email protected] are both equivalent to [email protected].\n</code></pre>\n\n<p>So, i can own an email address like that:</p>\n\n<pre><code>A__z/J0hn.sm{it!}[email protected]\n</code></pre>\n\n<p>If you try this address i bet it will fail in all or the major part of regex posted all across the net. But remember this address follows the RFC rules so it's fair valid.</p>\n\n<p>Imagine my frustration at not being able to register anywhere checked with those regex!!</p>\n\n<p><strong>The only one who really can validate an email address is the provider of the email address.</strong></p>\n\n<p>How to deal with, so?</p>\n\n<p>It doesn't matter if a user adds a non-valid e-mail in almost all cases. You can rely on HTML 5 input type=\"email\" that is running <strong>near</strong> to RFC, little chance to fail.\nHTML5 input type=\"email\" info: <a href=\"https://www.w3.org/TR/2012/WD-html-markup-20121011/input.email.html\" rel=\"nofollow noreferrer\">https://www.w3.org/TR/2012/WD-html-markup-20121011/input.email.html</a></p>\n\n<p>For example, this is an RFC valid email:</p>\n\n<pre><code>\"very.(),:;<>[]\\\".VERY.\\\"very@\\\\ \\\"very\\\".unusual\"@strange.example.com\n</code></pre>\n\n<p>But the html5 validation will tell you that the text before @ must not contain \" or () chars for example, which is actually incorrect.</p>\n\n<p>Anyway, you should do this by accepting the email address and sending an email message to that email address, with a code/link the user must visit to confirm validity.</p>\n\n<p>A good practice while doing this is the \"enter your e-mail again\" input to avoid user typing errors. If this is not enough for you, add a pre-submit modal-window with a title \"is this your current e-mail?\", then the mail entered by the user inside an h2 tag, you know, to show clearly which e-mail they entered, then a \"yes, submit\" button.</p>\n"
},
{
"answer_id": 50968324,
"author": "Sbbs",
"author_id": 1851294,
"author_profile": "https://Stackoverflow.com/users/1851294",
"pm_score": 3,
"selected": false,
"text": "<p>This is a JavaScript translation of the validation suggested by the official Rails guide used by thousands of websites:</p>\n\n<pre><code>/^([^@\\s]+)@((?:[-a-z0-9]+\\.)+[a-z]{2,})$/i\n</code></pre>\n\n<p>Relatively simple but tests against most common errors.</p>\n\n<p>Tested on a dataset of thousands of emails and it had zero false negatives/positives.</p>\n\n<p>Example usage:</p>\n\n<pre><code>const emailRegex = /^([^@\\s]+)@((?:[-a-z0-9]+\\.)+[a-z]{2,})$/i;\n\nemailRegex.test('[email protected]'); // true\n\n// Multi-word domains\nemailRegex.test('[email protected]'); // true\nemailRegex.test('[email protected]'); // true\n\n// Valid special characters\nemailRegex.test('unusual+but+valid+email1900=/!#$%&\\'*+-/=?^_`.{|}[email protected]') // true\n\n// Trailing dots\nemailRegex.test('[email protected].'); // false\n\n// No domain\nemailRegex.test('email@example'); // false\n\n// Leading space\nemailRegex.test(' [email protected]'); // false\n\n// Trailing space\nemailRegex.test('[email protected] '); // false\n\n// Incorrect domains\nemailRegex.test('email@example,com '); // false\n\n// Other invalid emails\nemailRegex.test('invalid.email.com') // false\nemailRegex.test('invalid@[email protected]') // false\nemailRegex.test('[email protected]') // false\n</code></pre>\n"
},
{
"answer_id": 51399417,
"author": "aabiro",
"author_id": 7848529,
"author_profile": "https://Stackoverflow.com/users/7848529",
"pm_score": 1,
"selected": false,
"text": "<p>Here is a solution that works and includes validation/notification fuctionality in a form:</p>\n\n<p>You can run it <a href=\"https://codepen.io/aabiro/pen/eyGJMV\" rel=\"nofollow noreferrer\">at this link</a></p>\n\n<p><strong><em>JAVASCRIPT</em></strong></p>\n\n<pre><code>(function() {\n 'use strict';\n\n window.addEventListener('load', function() {\n var form = document.getElementById('needs-validation');\n form.addEventListener('submit', function(event) {\n if (form.checkValidity() === false) {\n event.preventDefault();\n }\n form.classList.add('was-validated');\n event.preventDefault(); \n }, false);\n }, false);\n})();\n</code></pre>\n\n<p><strong><em>HTML</em></strong></p>\n\n<pre><code><p class='title'>\n <b>Email validation</b>\n <hr size=\"30px;\">\n</p>\n<br>\n\n<form id=\"needs-validation\" novalidate>\n <p class='form_text'>Try it out!</p>\n <div class=\"form-row\">\n <div class=\"col-12\">\n <input type=\"email\" class=\"form-control\" placeholder=\"Email Address\" required>\n <div class=\"invalid-feedback\">\n Please enter a valid email address.\n </div>\n </div>\n <div class=\"row\">\n <div class=\"col-12\">\n <button type=\"submit\" \n class=\"btn btn-default btn-block\">Sign up now\n </button>\n </div>\n </div>\n</form>\n</code></pre>\n\n\n"
},
{
"answer_id": 51464343,
"author": "mpyw",
"author_id": 1846562,
"author_profile": "https://Stackoverflow.com/users/1846562",
"pm_score": 1,
"selected": false,
"text": "<p>I wrote a JavaScript email validator which is fully compatile with PHP's <code>filter_var($value, FILTER_VALIDATE_EMAIL)</code> implementation.</p>\n\n<p><a href=\"https://github.com/mpyw/FILTER_VALIDATE_EMAIL.js\" rel=\"nofollow noreferrer\">https://github.com/mpyw/FILTER_VALIDATE_EMAIL.js</a></p>\n\n<pre><code>import validateEmail from 'filter-validate-email'\n\nconst value = '...'\nconst result = validateEmail(value)\n</code></pre>\n\n<p>is equivalent to:</p>\n\n<pre><code><?php\n\n$value = '...';\n$result = (bool)filter_var($value, FILTER_VALIDATE_EMAIL, FILTER_FLAG_EMAIL_UNICODE);\n</code></pre>\n"
},
{
"answer_id": 54153341,
"author": "isapir",
"author_id": 968244,
"author_profile": "https://Stackoverflow.com/users/968244",
"pm_score": 2,
"selected": false,
"text": "<p>Here is the recommended Regex pattern for HTML5 on MDN:</p>\n\n<blockquote>\n <p>Browsers that support the email input type automatically provide validation to ensure that only text that matches the standard format for Internet e-mail addresses is entered into the input box. Browsers that implement the specification should be using an algorithm equivalent to the following regular expression:</p>\n</blockquote>\n\n<pre><code>/^[a-zA-Z0-9.!#$%&'*+\\/=?^_`{|}~-]+@[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}\n[a-zA-Z0-9])?(?:\\.[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)*$/\n</code></pre>\n\n<p><a href=\"https://developer.mozilla.org/en-US/docs/Web/HTML/Element/input/email#Validation\" rel=\"nofollow noreferrer\">https://developer.mozilla.org/en-US/docs/Web/HTML/Element/input/email#Validation</a></p>\n"
},
{
"answer_id": 54845819,
"author": "karlzafiris",
"author_id": 4141689,
"author_profile": "https://Stackoverflow.com/users/4141689",
"pm_score": 1,
"selected": false,
"text": "<p>Here's how I do it. I'm using match() to check for the standard email pattern and I'm adding a class to the input text to notify the user accordingly. Hope that helps!</p>\n\n<p><div class=\"snippet\" data-lang=\"js\" data-hide=\"false\" data-console=\"true\" data-babel=\"false\">\r\n<div class=\"snippet-code\">\r\n<pre class=\"snippet-code-js lang-js prettyprint-override\"><code>$(document).ready(function(){\r\n $('#submit').on('click', function(){\r\n var email = $('#email').val();\r\n var pat = /^\\w+([\\.-]?\\w+)*@\\w+([\\.-]?\\w+)*(\\.\\w{2,3})+$/;\r\n if (email.match(pat)){\r\n $('#email')\r\n .addClass('input-valid');\r\n return false;\r\n } else {\r\n $('#email')\r\n .addClass('input-error')\r\n .val('');\r\n return false;\r\n }\r\n });\r\n});</code></pre>\r\n<pre class=\"snippet-code-css lang-css prettyprint-override\"><code>.input-error {\r\n border: 1px solid red;\r\n color: red;\r\n}\r\n\r\n.input-valid {\r\n border: 1px solid green;\r\n color: green;\r\n}</code></pre>\r\n<pre class=\"snippet-code-html lang-html prettyprint-override\"><code><script src=\"https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js\"></script>\r\n<form>\r\n <input type=\"text\" id=\"email\" placeholder=\"[email protected]\" class=\"\">\r\n <input type=\"submit\" id=\"submit\" value=\"Send\"/>\r\n</form></code></pre>\r\n</div>\r\n</div>\r\n</p>\n"
},
{
"answer_id": 54948659,
"author": "B. Bohdan",
"author_id": 8097218,
"author_profile": "https://Stackoverflow.com/users/8097218",
"pm_score": 0,
"selected": false,
"text": "<p>There is my version of an email validator. This code is done with object-oriented programming and realized as a class with static methods. You will find two versions of the validators: strict(<code>EmailValidator.validate</code>) and kind(<code>EmailValidator.validateKind</code>).</p>\n\n<p>The first throws an error if an email is invalid and returns email otherwise. The second returns Boolean value that says if an email is valid. I prefer the strict version in most of the cases.</p>\n\n<pre><code>export class EmailValidator {\n /**\n * @param {string} email\n * @return {string}\n * @throws {Error}\n */\n static validate(email) {\n email = this.prepareEmail(email);\n\n const isValid = this.validateKind(email);\n\n if (isValid)\n return email;\n\n throw new Error(`Got invalid email: ${email}.`);\n }\n\n /**\n * @param {string} email\n * @return {boolean}\n */\n static validateKind(email) {\n email = this.prepareEmail(email);\n\n const regex = this.getRegex();\n\n return regex.test(email);\n }\n\n /**\n * @return {RegExp}\n * @private\n */\n static getRegex() {\n return /^(([^<>()\\[\\]\\\\.,;:\\s@\"]+(\\.[^<>()\\[\\]\\\\.,;:\\s@\"]+)*)|(\".+\"))@((\\[[0-9]{1,3}\\.[0-9]{1,3}\\.[0-9]{1,3}\\.[0-9]{1,3}\\])|(([a-zA-Z\\-0-9]+\\.)+[a-zA-Z]{2,}))$/;\n }\n\n /**\n * @param {string} email\n * @return {string}\n * @private\n */\n static prepareEmail(email) {\n return String(email).toLowerCase();\n }\n}\n</code></pre>\n\n<p>To validate an email you can follow these ways:</p>\n\n<pre><code>// First way.\n\ntry {\n EmailValidator.validate('[email protected]');\n} catch (e) {\n console.error(e.message);\n}\n</code></pre>\n\n<pre><code>// Second way.\n\nconst email = '[email protected]';\nconst isValid = EmailValidator.validateKind(email);\n\nif (isValid)\n console.log(`Email is valid: ${email}.`);\nelse\n console.log(`Email is invalid: ${email}.`);\n</code></pre>\n"
},
{
"answer_id": 55807372,
"author": "Raheel",
"author_id": 2812955,
"author_profile": "https://Stackoverflow.com/users/2812955",
"pm_score": 0,
"selected": false,
"text": "<p>I am using this function </p>\n\n<pre><code>/**\n * @param {*} email\n */\nexport const validateEmail = email => {\n return new RegExp(/[\\w-]+@([\\w-]+\\.)+[\\w-]+/gm).test(email);\n};\n</code></pre>\n"
},
{
"answer_id": 55852057,
"author": "Antonio",
"author_id": 1282278,
"author_profile": "https://Stackoverflow.com/users/1282278",
"pm_score": 2,
"selected": false,
"text": "<p>General email regex (RFC 5322 Official Standard): <a href=\"https://emailregex.com/\" rel=\"nofollow noreferrer\">https://emailregex.com/</a></p>\n\n<p>JavaScript:</p>\n\n<pre><code>/^(([^<>()\\[\\]\\\\.,;:\\s@\"]+(\\.[^<>()\\[\\]\\\\.,;:\\s@\"]+)*)|(\".+\"))@((\\[[0-9]{1,3}\\.[0-9]{1,3}\\.[0-9]{1,3}\\.[0-9]{1,3}])|(([a-zA-Z\\-0-9]+\\.)+[a-zA-Z]{2,}))$/\n</code></pre>\n"
},
{
"answer_id": 56458505,
"author": "Nicolas Zozol",
"author_id": 968988,
"author_profile": "https://Stackoverflow.com/users/968988",
"pm_score": 1,
"selected": false,
"text": "<p>If you want something a human can read and <strong>maintain</strong>, I would recommend <a href=\"https://github.com/masala-oss/masala-parser\" rel=\"nofollow noreferrer\">Masala Parser</a> (I'm one of the creators of it).</p>\n\n<pre class=\"lang-js prettyprint-override\"><code>import {C,Streams} from '@masala/parser'\n\nconst illegalCharset = ' @\\u00A0\\n\\t';\nconst extendedIllegalCharset = illegalCharset + '.';\n\n\n// Assume '[email protected]'\nexport function simpleEmail() {\n\n return C.charNotIn(illegalCharset).rep() // 'nicolas'\n .then(C.char('@'))\n .then(subDns()) //'internal.masala.co.'\n .then(C.charNotIn(extendedIllegalCharset).rep()) //'uk'\n .eos(); // Must be end of the char stream\n}\n\n// [email protected] => extract 'internal.masala.co.'\nfunction subDns() {\n return C.charNotIn(extendedIllegalCharset).rep().then(C.char('.')).rep()\n}\n\nfunction validateEmail(email:string) {\n console.log(email + ': ' + (simpleEmail().parse(Streams.ofString(email)).isAccepted()));\n}\n\n\nvalidateEmail('[email protected]'); // True\nvalidateEmail('nz@co.'); // False, trailing \".\"\n</code></pre>\n\n<p>If you want to accept the ultimate ugly email version, you can add in quotes in the first part:</p>\n\n<pre class=\"lang-js prettyprint-override\"><code>\nfunction inQuote() {\n return C.char('\"')\n .then(C.notChar('\"').rep())\n .then(C.char('\"'))\n}\n\nfunction allEmail() {\n\n return inQuote().or(C.charNotIn(illegalCharset))\n .rep() // repeat (inQuote or anyCharacter)\n .then(C.char('@'))\n .then(subDns())\n .then(C.charNotIn(extendedIllegalCharset).rep())\n .eos() // Must be end of the character stream\n // Create a structure\n .map(function (characters) { return ({ email: characters.join('') }); });\n}\n</code></pre>\n\n<p><code>'\"nicolas\"\"love-quotes\"@masala.co.uk'</code> is officially valid, but should it be in your system?</p>\n\n<p>At least with Masala, you give yourself a chance to understand it. And so for the next year, colleague.</p>\n"
},
{
"answer_id": 57966778,
"author": "jimmont",
"author_id": 965666,
"author_profile": "https://Stackoverflow.com/users/965666",
"pm_score": 2,
"selected": false,
"text": "<p>Use the browser/runtime to handle parsing the input by prepending a protocol and pass it to the <code>URL</code> API, trapping any errors and check the resulting <code>username</code> and <code>hostname</code> properties of the result. It will handle basically all transformations and possibilities (<a href=\"https://en.wikipedia.org/wiki/Punycode\" rel=\"nofollow noreferrer\">punycode</a> of character sets, etc). This only establishes that the input is parsable, not that is valid--that is only possible through checking if the destination machine receives messages for that alias. This provides a close (imo reasonable) guess though, and can be expanded to be more specific and realistic if you're comfortable both maintaining it and also risking invalid rejections. (Note it doesn't attempt to address IPv4 or IPv6 addresses, simply the broad range of customer-facing scenarios using a domain.)</p>\n\n<pre><code>function validEmail(email=''){\n var $0, url, isValid = false, emailPatternInput = /^[^@]{1,64}@[^@]{4,253}$/, emailPatternUrl = /^[^@]{1,64}@[a-z][a-z0-9\\.-]{3,252}$/i;\n email = email.trim();\n try{\n url = new URL('http://'+email);\n $0 = `${url.username}@${url.hostname}`;\n isValid = emailPatternInput.test( email );\n if(!isValid) throw 'invalid email pattern on input:' + email;\n isValid = emailPatternUrl.test( $0 );\n if(!isValid) throw 'invalid email pattern on url:' + $0;\n console.log(`email looks legit \"${email}\" checking url-parts: \"${$0 === email ? '-SAME-':$0}\"`);\n }catch(err){\n console.error(`probably not an email address: \"${email}\"`, err);\n };\n return isValid;\n}\n\n['user+this@はじめよう.みんな', 'stuff@things', '[email protected]', 'Jean+Franç[email protected]','هيا@יאללה', '试@例子.测试.مثال.آزمایشی', 'not@@really', 'no'].forEach(email=>console.log(validEmail(email), email));\n</code></pre>\n\n<p>This is the both the simplest and most generally permissive example I can come up with. Please edit it in cases where it can be made to be more accurate while maintain its simplicity and reasonable generally permissive validity.</p>\n\n<p>Also see MDN URL docs <a href=\"https://developer.mozilla.org/en-US/docs/Web/API/URL/URL\" rel=\"nofollow noreferrer\">URL</a>, <a href=\"https://developer.mozilla.org/en-US/docs/Web/API/URL\" rel=\"nofollow noreferrer\">window.URL</a> and Nodejs for <a href=\"https://nodejs.org/api/url.html\" rel=\"nofollow noreferrer\">URL</a> APIs.</p>\n"
},
{
"answer_id": 58905771,
"author": "Eboubaker",
"author_id": 10387008,
"author_profile": "https://Stackoverflow.com/users/10387008",
"pm_score": 1,
"selected": false,
"text": "<p>These will work with the top used emails(<strong>they match exactly the rules of each one</strong>).\n<br><br>\n<strong>Gmail</strong>\n<br>\n<code>/^[a-z]((?!\\.\\.)([a-z\\.])){4,28}[a-z0-9]@gmail.com$/i</code>\n<br><br>\n<strong>Yahoo</strong>\n<br>\n<code>/^[a-z]((?!\\.\\.)([\\w\\.])){3,30}[\\w]@yahoo.com$/i</code>\n<br><br>\n<strong>Outlook</strong>/<strong>Hotmail</strong>\n<br>\n<code>/[a-z]((?!\\.\\.)([\\w\\.])){0,62}[\\w]@(outlook.com|hotmail.com)$/i</code></p>\n"
},
{
"answer_id": 59498223,
"author": "Renish Gotecha",
"author_id": 8274534,
"author_profile": "https://Stackoverflow.com/users/8274534",
"pm_score": 3,
"selected": false,
"text": "<p>In my case, I wanted to avoid <code>~</code> and <code>#</code> that's why I have used <a href=\"https://regex101.com/r/SOgUIV/1\" rel=\"noreferrer\">another solution</a>:</p>\n<pre><code>function validEmail(email){\n const regex = /^((?!\\.)[\\w\\-_.]*[^.])(@\\w+)(\\.\\w+(\\.\\w+)?[^.\\W])$/;\n return regex.test(email);\n}\n</code></pre>\n<p><div class=\"snippet\" data-lang=\"js\" data-hide=\"false\" data-console=\"true\" data-babel=\"false\">\r\n<div class=\"snippet-code\">\r\n<pre class=\"snippet-code-js lang-js prettyprint-override\"><code>function validEmail(email){\n const regex = /^((?!\\.)[\\w\\-_.]*[^.])(@\\w+)(\\.\\w+(\\.\\w+)?[^.\\W])$/;\n return regex.test(email);\n}\n\nconst emails = [\n'[email protected]',\n'[email protected]',\n'[email protected]',\n'pio_#[email protected]',\n'pio_pio@#factory.com',\n'[email protected]#om',\n'[email protected]*om',\n'pio^[email protected]'\n]\n\nfor(const email of emails){\n document.write(email+' : '+validEmail(email)+'</br>');\n}</code></pre>\r\n</div>\r\n</div>\r\n</p>\n"
},
{
"answer_id": 59901196,
"author": "Mattia Rasulo",
"author_id": 10626207,
"author_profile": "https://Stackoverflow.com/users/10626207",
"pm_score": 2,
"selected": false,
"text": "<p>You can use this regex (from <a href=\"https://www.w3resource.com/javascript/form/email-validation.php\" rel=\"nofollow noreferrer\">w3resource (*not related to W3C)</a>):</p>\n<pre><code>/^\\w+([\\.-]?\\w+)*@\\w+([\\.-]?\\w+)*(\\.\\w{2,3})+$/.test(emailValue)\n</code></pre>\n<p>If you use Node you can use this in the back-end as well as the front-end.</p>\n<p>I don't know other back-end languages so I cannot evaluate for other use cases.</p>\n"
},
{
"answer_id": 59922013,
"author": "endyourif",
"author_id": 913166,
"author_profile": "https://Stackoverflow.com/users/913166",
"pm_score": 4,
"selected": false,
"text": "<p>Wow, there are a lot of answers that contain slightly different regular expressions. I've tried many that I've got different results and a variety of different issues with all of them.</p>\n<p>For UI validation, I'm good with the most basic check of <a href=\"https://www.endyourif.com/validate-an-email-address-in-javascript/\" rel=\"noreferrer\">looking for an @ sign</a>. It's important to note, that I always do server-side validation with a standard "validate email" that contains a unique link for the user to confirm their email address.</p>\n<pre><code>if (email.indexOf('@') > 0)\n</code></pre>\n<p>I have purposely chosen 0 even with zero-based as it also ensures there is a single character before the @.</p>\n"
},
{
"answer_id": 60042450,
"author": "user1843640",
"author_id": 1843640,
"author_profile": "https://Stackoverflow.com/users/1843640",
"pm_score": 3,
"selected": false,
"text": "<p>I prefer to keep it simple and keep my users happy. I also prefer code which is easy to understand. RegEx is not.</p>\n\n<pre><code>function isValidEmail(value) {\n const atLocation = value.lastIndexOf(\"@\");\n const dotLocation = value.lastIndexOf(\".\"); \n return (\n atLocation > 0 &&\n dotLocation > atLocation + 1 &&\n dotLocation < value.length - 1\n );\n};\n</code></pre>\n\n<ul>\n<li>Get the location of the last \"@\" and the last \".\"</li>\n<li>Make sure the \"@\" is not the first char (there is something before it) </li>\n<li>Make sure the \".\" is after the \"@\" and that there is at least one char between them</li>\n<li>Make sure there is at least a single char after the \".\"</li>\n</ul>\n\n<p>Will this allow invalid email addresses to pass? Sure, but I don't think you need much more for a good user experience that allows you to enable/disable a button, display an error message, etc. You only know for sure that an email address is valid when you attempt to send an email to that address.</p>\n"
},
{
"answer_id": 61180079,
"author": "Jaskaran Singh",
"author_id": 5162083,
"author_profile": "https://Stackoverflow.com/users/5162083",
"pm_score": 2,
"selected": false,
"text": "<p>If you get this error: Using regular expressions is security-sensitive.</p>\n<p>Then here is what you are looking for. This solution is free from " Regular expression Denial of Service (ReDoS) "</p>\n<p>Regex to validate emails without (ReDoS):</p>\n<pre><code>/^[a-z0-9](?!.*?[^\\na-z0-9]{2})[^\\s@]+@[^\\s@]+\\.[^\\s@]+[a-z0-9]$/\n</code></pre>\n<p>Please let me know if this solution works for you.\nThanks.</p>\n"
},
{
"answer_id": 62778080,
"author": "Ebrahim",
"author_id": 1007945,
"author_profile": "https://Stackoverflow.com/users/1007945",
"pm_score": 3,
"selected": false,
"text": "<p>Most of the answers here are not linter friendly, it's a mess! Some of them are also outdated!\nAfter a lot of time spending, I decided to use an external library named <code>email-validator</code>, install it easily by npm for example and import/require it in your own project:</p>\n<p><a href=\"https://www.npmjs.com/package/email-validator\" rel=\"nofollow noreferrer\">https://www.npmjs.com/package/email-validator</a></p>\n<pre><code>//NodeJs\nconst validator = require("email-validator");\nvalidator.validate("[email protected]"); // true\n\n//TypeScript/JavaScript\nimport * as EmailValidator from 'email-validator';\nEmailValidator.validate("[email protected]"); // true\n</code></pre>\n"
},
{
"answer_id": 64735657,
"author": "Nazmul Haque",
"author_id": 5689349,
"author_profile": "https://Stackoverflow.com/users/5689349",
"pm_score": 1,
"selected": false,
"text": "<pre><code> // Html form call function name at submit button\n\n <form name="form1" action="#"> \n <input type='text' name='text1'/>\n <input type="submit" name="submit" value="Submit" \n onclick="ValidateEmail(document.form1.text1)"/>\n </from>\n\n // Write the function name ValidateEmail below\n\n <script>\n function ValidateEmail(inputText)\n {\n var mailformat = /^[a-zA-Z0-9.!#$%&'*+/=?^_`{|}~-]+@[a-zA-Z0-9-]+(?:\\.[a-zA-Z0-9-]+)*$/;\n if(inputText.value.match(mailformat))\n {\n alert("Valid email address!");\n document.form1.text1.focus();\n return true;\n }\n else\n {\n alert("You have entered an invalid email address!");\n document.form1.text1.focus();\n return false;\n }\n }\n </script>\n</code></pre>\n"
},
{
"answer_id": 67089282,
"author": "FDisk",
"author_id": 175404,
"author_profile": "https://Stackoverflow.com/users/175404",
"pm_score": 1,
"selected": false,
"text": "<p>Yet another perfect regexp for email validation</p>\n<pre class=\"lang-js prettyprint-override\"><code>/^([^\\s\\@])+\\@(([^\\s\\@\\.])+\\.)+([^\\s\\.]{2,})+$/\n</code></pre>\n<p>You can test it here <a href=\"https://regex101.com/r/FV3pUI/2\" rel=\"nofollow noreferrer\">https://regex101.com/r/FV3pUI/2</a></p>\n"
},
{
"answer_id": 67295040,
"author": "Force Bolt",
"author_id": 15478252,
"author_profile": "https://Stackoverflow.com/users/15478252",
"pm_score": 1,
"selected": false,
"text": "<pre><code>// Try this regular Expression by ES6 function\n\nconst emailValidate = (email) => {\n const regexp= /^[\\w.%+-]+@[\\w.-]+\\.[\\w]{2,6}$/;\n return regexp.test(email);\n}\n</code></pre>\n"
},
{
"answer_id": 72018404,
"author": "jimmont",
"author_id": 965666,
"author_profile": "https://Stackoverflow.com/users/965666",
"pm_score": 1,
"selected": false,
"text": "<p>Use the <code>URL</code> interface in JavaScript to parse the address in the minimum practical expected format <code>user@host</code> then check that it looks reasonable. Next send a message to it and see if that works (for example require the recipient validate a one-time token via the address). Note that this handles punycode, internationalization, as shown in the samples below.</p>\n<p><a href=\"https://developer.mozilla.org/en-US/docs/Web/API/URL\" rel=\"nofollow noreferrer\">https://developer.mozilla.org/en-US/docs/Web/API/URL</a></p>\n<p>an example with simple tests:</p>\n<pre><code>function validEmail(input=''){\n const emailPatternInput = /^[^@]{1,64}@[^@]{4,253}$/, emailPatternUrl = /^[^@]{1,64}@[a-z][a-z0-9\\.-]{3,252}$/i;\n let email, url, valid = false, error, same = false;\n try{\n email = input.trim();\n // handles punycode, etc using browser's own maintained implementation\n url = new URL('http://'+email);\n let urlderived = `${url.username}@${url.hostname}`;\n same = urlderived === email;\n valid = emailPatternInput.test( email );\n if(!valid) throw new Error('invalid email pattern on input:' + email);\n valid = emailPatternUrl.test( urlderived );\n if(!valid) throw new Error('invalid email pattern on url:' + urlderived);\n }catch(err){\n error = err;\n };\n return {email, url, same, valid, error};\n}\n\n[\n 'user+this@はじめよう.みんな'\n, '[email protected]'\n, 'stuff@things'\n, '[email protected]'\n, 'Jean+Franç[email protected]','هيا@יאללה'\n, '试@例子.测试.مثال.آزمایشی'\n, 'not@@really'\n, 'no'\n].forEach(email=>console.log(validEmail(email), email));\n</code></pre>\n"
},
{
"answer_id": 73457425,
"author": "Adam Whateverson",
"author_id": 6730421,
"author_profile": "https://Stackoverflow.com/users/6730421",
"pm_score": 2,
"selected": false,
"text": "<p>The answer to this question (if you stood back and really thought about it) is that you can't really prevent a user from mistyping their e-mail. Everybody is providing answers that match all the possible letters but nobody has really taken into account the full myriad of characters that can be used.</p>\n<p>I refer you to this post and the answer explaining the amount of characters that can be accepted:-\n<a href=\"https://stackoverflow.com/questions/26855757/remove-invalid-characters-from-email\">Remove invalid characters from e-mail</a></p>\n<p>You can't predict if the letters are the exact way the user intended them to be - which is the most common mistake.. missing a letter out or typing the wrong letter.</p>\n<p>All we are doing here is stopping them from typing really odd characters that e-mail addresses wouldn't accept and the likelyhood of them accidently inserting a question mark is just as likely as them accidently getting the letters 'a' and 's' the wrong way around.</p>\n<p>Ultimately, no matter what you do in Javascript you will always need your backend script to check if the e-mail was sent successfully too and it will probably have a validation process in place too.</p>\n<p>So if you wanted to ensure it was some sort of e-mail address and not their username you only really need to check if there's an @ symbol in there and at least 1 dot and leave all the rest to your backend code.</p>\n<pre><code>var email = '[email protected]'\nif(email.split('@').length == 2 && email.indexOf('.') > 0){\n // The split ensures there's only 1 @\n // The indexOf ensures there's at least 1 dot.\n}\n</code></pre>\n<p>It would be better to avoid stopping the user entering a valid e-mail than to apply so many restrictions that it becomes complicated.</p>\n<p>This is just my opinion!</p>\n"
}
] | 2008/09/05 | [
"https://Stackoverflow.com/questions/46155",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/72/"
] | I'd like to check if the user input is an email address in JavaScript, before sending it to a server or attempting to send an email to it, to prevent the most basic mistyping. How could I achieve this? | Using [regular expressions](http://en.wikipedia.org/wiki/Regular_expression) is probably the best way. You can see a bunch of tests [here](http://jsfiddle.net/ghvj4gy9/embedded/result,js/) (taken from [chromium](https://cs.chromium.org/chromium/src/third_party/blink/web_tests/fast/forms/resources/ValidityState-typeMismatch-email.js?q=ValidityState-typeMismatch-email.js&sq=package:chromium&dr))
```js
const validateEmail = (email) => {
return String(email)
.toLowerCase()
.match(
/^(([^<>()[\]\\.,;:\s@"]+(\.[^<>()[\]\\.,;:\s@"]+)*)|(".+"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/
);
};
```
Here's the example of a regular expression that accepts unicode:
```js
const re =
/^(([^<>()[\]\.,;:\s@\"]+(\.[^<>()[\]\.,;:\s@\"]+)*)|(\".+\"))@(([^<>()[\]\.,;:\s@\"]+\.)+[^<>()[\]\.,;:\s@\"]{2,})$/i;
```
But keep in mind that one should not rely only upon JavaScript validation. JavaScript can easily be disabled. This should be validated on the server side as well.
Here's an example of the above in action:
```js
const validateEmail = (email) => {
return email.match(
/^(([^<>()[\]\\.,;:\s@\"]+(\.[^<>()[\]\\.,;:\s@\"]+)*)|(\".+\"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/
);
};
const validate = () => {
const $result = $('#result');
const email = $('#email').val();
$result.text('');
if (validateEmail(email)) {
$result.text(email + ' is valid :)');
$result.css('color', 'green');
} else {
$result.text(email + ' is not valid :(');
$result.css('color', 'red');
}
return false;
}
$('#email').on('input', validate);
```
```html
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<label for="email">Enter an email address: </label>
<input id="email" />
<h2 id="result"></h2>
``` |
46,189 | <p>I have a collection of objects to which I'd like to just add a new property. How do I do that with LINQ?</p>
| [
{
"answer_id": 46206,
"author": "John Boker",
"author_id": 2847,
"author_profile": "https://Stackoverflow.com/users/2847",
"pm_score": 3,
"selected": true,
"text": "<pre><code>var a = from i in ObjectCollection select new {i.prop1, i.prop2, i.prop3, ..., newprop = newProperty}\n</code></pre>\n"
},
{
"answer_id": 46234,
"author": "Guy",
"author_id": 1463,
"author_profile": "https://Stackoverflow.com/users/1463",
"pm_score": 0,
"selected": false,
"text": "<p>I don't think that you can using pure LINQ. However, if you're doing this sort of thing a lot in your code you may be able to make this work with reflection.</p>\n"
},
{
"answer_id": 46533,
"author": "Lasse V. Karlsen",
"author_id": 267,
"author_profile": "https://Stackoverflow.com/users/267",
"pm_score": 0,
"selected": false,
"text": "<p>Why do you want to add the extra property? Or, put a different way, what do you intend to do with the property once you have it in your new IEnumerable source?</p>\n\n<p>If you need it for data binding, I have a helper class that might help you.</p>\n"
}
] | 2008/09/05 | [
"https://Stackoverflow.com/questions/46189",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/781/"
] | I have a collection of objects to which I'd like to just add a new property. How do I do that with LINQ? | ```
var a = from i in ObjectCollection select new {i.prop1, i.prop2, i.prop3, ..., newprop = newProperty}
``` |
46,219 | <p>If I have a </p>
<pre><code><input id="uploadFile" type="file" />
</code></pre>
<p>tag, and a submit button, how do I determine, in IE6 (and above) if a file has been selected by the user.</p>
<p>In FF, I just do:</p>
<pre><code>var selected = document.getElementById("uploadBox").files.length > 0;
</code></pre>
<p>But that doesn't work in IE.</p>
| [
{
"answer_id": 46242,
"author": "Jason Bunting",
"author_id": 1790,
"author_profile": "https://Stackoverflow.com/users/1790",
"pm_score": 8,
"selected": true,
"text": "<p>This works in IE (and FF, I believe):</p>\n\n<pre><code>if(document.getElementById(\"uploadBox\").value != \"\") {\n // you have a file\n}\n</code></pre>\n"
},
{
"answer_id": 22152474,
"author": "Atiqur",
"author_id": 2804202,
"author_profile": "https://Stackoverflow.com/users/2804202",
"pm_score": 3,
"selected": false,
"text": "<pre><code>var nme = document.getElementById("uploadFile");\nif(nme.value.length < 4) {\n alert('Must Select any of your photo for upload!');\n nme.focus();\n return false;\n}\n</code></pre>\n"
},
{
"answer_id": 42990754,
"author": "Ashu",
"author_id": 1874707,
"author_profile": "https://Stackoverflow.com/users/1874707",
"pm_score": 2,
"selected": false,
"text": "<pre><code>function validateAndUpload(input){\n var URL = window.URL || window.webkitURL;\n var file = input.files[0];\n\n if (file) {\n var image = new Image();\n\n image.onload = function() {\n if (this.width) {\n console.log('Image has width, I think it is real image');\n //TODO: upload to backend\n }\n };\n\n image.src = URL.createObjectURL(file);\n }\n};\n\n<input type=\"file\" name=\"uploadPicture\" accept=\"image/*\" onChange=\"validateAndUpload(this);\"/>\n</code></pre>\n\n<p>Call this function on change . </p>\n"
},
{
"answer_id": 50415093,
"author": "Elion Limanaj",
"author_id": 9807638,
"author_profile": "https://Stackoverflow.com/users/9807638",
"pm_score": 2,
"selected": false,
"text": "<p>You can use:</p>\n\n<pre><code> var files = uploadFile.files;\n\n if (files.length == 0) { console.log(true) } else { console.log(false) }\n if (files[0] == undefined) { console.log(true) } else { console.log(false) }\n if (files[0] == null) { console.log(true) } else { console.log(false) }\n</code></pre>\n\n<p>All three give the same result.</p>\n"
},
{
"answer_id": 74571436,
"author": "sifr_dot_in",
"author_id": 2173890,
"author_profile": "https://Stackoverflow.com/users/2173890",
"pm_score": 0,
"selected": false,
"text": "<p>The accepted answer is correct to check with "ID"</p>\n<p>But, those who are here to check file with <strong>class-name</strong>,</p>\n<p>here is the code:</p>\n<pre><code>var elements = document.getElementsByClassName('uploadFile_ClassName');\nfor (var i = 0; i < elements.length; ++i) {\n if(elements[i].value != "") {\n // file is selected here;\n }\n}\n</code></pre>\n"
}
] | 2008/09/05 | [
"https://Stackoverflow.com/questions/46219",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/698/"
] | If I have a
```
<input id="uploadFile" type="file" />
```
tag, and a submit button, how do I determine, in IE6 (and above) if a file has been selected by the user.
In FF, I just do:
```
var selected = document.getElementById("uploadBox").files.length > 0;
```
But that doesn't work in IE. | This works in IE (and FF, I believe):
```
if(document.getElementById("uploadBox").value != "") {
// you have a file
}
``` |
46,220 | <p>I'm writing my first iPhone app, so I haven't gotten around to figuring out much in the way of debugging.
Essentially my app displays an image and when touched plays a short sound.
When compiling and building the project in XCode, everything builds successfully, but when the app is run in the iPhone simulator, it crashes.</p>
<p>I get the following error:</p>
<pre><code>Application Specific Information:
iPhone Simulator 1.0 (70), iPhone OS 2.0 (5A331)
*** Terminating app due to uncaught exception 'NSUnknownKeyException',
reason: '[<UIView 0x34efd0> setValue:forUndefinedKey:]: this class is not key value
coding-compliant for the key kramerImage.'
</code></pre>
<p>kramerImage here is the image I'm using for the background.</p>
<p>I'm not sure what NSUnknownKeyException means or why the class is not key value coding-compliant for the key.</p>
| [
{
"answer_id": 46357,
"author": "amrox",
"author_id": 4468,
"author_profile": "https://Stackoverflow.com/users/4468",
"pm_score": 6,
"selected": true,
"text": "<p>(This isn't really iPhone specific - the same thing will happen in regular Cocoa).</p>\n\n<p>NSUnknownKeyException is a common error when using <a href=\"https://developer.apple.com/library/mac/#documentation/Cocoa/Conceptual/KeyValueCoding/Articles/KeyValueCoding.html\" rel=\"nofollow noreferrer\">Key-Value Coding</a> to access a key that the object doesn't have.</p>\n\n<p>The properties of most Cocoa objects can be accessing directly:</p>\n\n<pre><code>[@\"hello world\" length] // Objective-C 1.0\n@\"hello world\".length // Objective-C 2.0\n</code></pre>\n\n<p>Or via Key-Value Coding:</p>\n\n<pre><code>[@\"hello world\" valueForKey:@\"length\"]\n</code></pre>\n\n<p>I would get an NSUnknownKeyException if I used the following line:</p>\n\n<pre><code>[@\"hello world\" valueForKey:@\"purpleMonkeyDishwasher\"]\n</code></pre>\n\n<p>because NSString does not have a property (key) called 'purpleMonkeyDishwasher'.</p>\n\n<p>Something in your code is trying to set a value for the key 'kramerImage' on an UIView, which (apparently) doesn't support that key. If you're using Interface Builder, it might be something in your nib.</p>\n\n<p>Find where 'kramerImage' is being used, and try to track it down from there.</p>\n"
},
{
"answer_id": 2538217,
"author": "Ozkan Altuner",
"author_id": 178473,
"author_profile": "https://Stackoverflow.com/users/178473",
"pm_score": 3,
"selected": false,
"text": "<p>Also when you rename a view, don't forget to delete the reference on File's Owner. It may also raise this error.</p>\n"
},
{
"answer_id": 3899224,
"author": "Owen Hartnett",
"author_id": 69724,
"author_profile": "https://Stackoverflow.com/users/69724",
"pm_score": 3,
"selected": false,
"text": "<p>Here's one where you'll get this error - and how to fix it. I was getting it when loading a nib that just had a custom TableViewCell. I used IB to build a xib that just had the File's Owner, First Responder, and the TableViewCell. The TableViewCell just had 4 UILabels which matched up to a class with 4 IBOutlet UILabels called rootCell. I changed the class of the TableViewCell to be rootCell. It worked fine until a made a couple of changes and suddenly I was getting the setValue:forUndefinedKey: when I was just instantiating the class after loading it from a nib:</p>\n\n<pre><code> NSArray * nib = [[NSBundle mainBundle] loadNibNamed:@\"rootCell-iPad\" owner:self options:nil];\n\n cell = [nib objectAtIndex:0];\n</code></pre>\n\n<p>It failed at the first line, when the nib was trying to load. After a while, I noticed that it was trying to match the IBOutlet Labels to the root controller, NOT the rootCell class! That was my tipoff. What I did wrong was to inadvertently change the File's Owner to rootCell class. When I changed it back to NSObject, then it didn't try to match up to the delegate (rootController) when loading. So, if you're doing the above, make File's Owner an NSObject, but make the UITableCell your desired class.</p>\n"
},
{
"answer_id": 4143957,
"author": "Vipul Parmar",
"author_id": 496955,
"author_profile": "https://Stackoverflow.com/users/496955",
"pm_score": 0,
"selected": false,
"text": "<p>It seems you are doing</p>\n\n<pre><code>@interface MyFirstIphoneAppViewController : UIViewController<> {\n UIImageView *InitialkramerImage;\n}\n@property(nonatomic,retain) IBOutlet UIImageView *InitialkramerImage;\n</code></pre>\n\n<p>Then after synthesizing that imageview, When you open \"MyFirstIphoneAppViewController.xib\" in Interface Builder, you are taking an Image View from Tool(menu)/Library den linking that outlet to the 'InitialkramerImage' from the Files Owner of \"MyFirstIphoneAppViewController.xib\". Then you saved the project. But after that you might change the name of the outlet variable \"InitialkramerImage\" to \"kramerImage\". So, after doing this </p>\n\n<pre><code>@interface MyFirstIphoneAppViewController : UIViewController<> {\n UIImageView *kramerImage;\n}\n@property(nonatomic,retain) IBOutlet UIImageView *kramerImage;\n</code></pre>\n\n<p>and saving the project when you run it, There is no existance of the outlet of \"InitialkramerImage\" in the \"MyFirstIphoneAppViewController.xib\". So, when you run the project there will be no outlet referencing from Imageview to the 'kramerImage' and </p>\n\n<blockquote>\n <p>\"For displaying the view,\n UIViewController will try to find the\n outlet to \"InitialkramerImage\" which\n is not existing.\"</p>\n</blockquote>\n\n<p>So, It will throw the \"NSUnknownKeyException\". </p>\n\n<blockquote>\n <p>You can check the missing outlet by\n opening the nib(.xib) file then right\n clicking on the 'Files Owner' of that.</p>\n</blockquote>\n"
},
{
"answer_id": 6600238,
"author": "gonzobrains",
"author_id": 267702,
"author_profile": "https://Stackoverflow.com/users/267702",
"pm_score": 2,
"selected": false,
"text": "<p>I had this same problem today. I didn't have the right class specified for the View Controller in my Navigation Controller. This will happen often if you fail to specify the correct class for your views in Interface Builder.</p>\n\n<p>You'll also get invalid selector issues as well. Always check your Interface Builder classes and connections!</p>\n"
},
{
"answer_id": 10509814,
"author": "KETAN",
"author_id": 608227,
"author_profile": "https://Stackoverflow.com/users/608227",
"pm_score": 0,
"selected": false,
"text": "<p>If you have done this code somewhere else and had a zip/compressed file, try to extract it again. It may work I dont know why but I feel like it is an extraction issue.</p>\n\n<p>or you can try to change the IBOutlet to kramerImage and bind it again in NIB.</p>\n"
},
{
"answer_id": 11380108,
"author": "Leon",
"author_id": 1509483,
"author_profile": "https://Stackoverflow.com/users/1509483",
"pm_score": 2,
"selected": false,
"text": "<p>I had this situation and it turns out even after finding all instances of the variable and deleting them my app still crashed. Heres what happened... I created another instance of a variable from a textfield from my XIB into my viewController.h but I realized I didnt need it anymore and deleted it. It turns out my program saw that and kept trying to use it in the program so in the future if this happens to anywhere else just go into you XIB right-click on the button or textfield etc and delete any extra unused variables.</p>\n"
},
{
"answer_id": 11543751,
"author": "Joseph",
"author_id": 1535134,
"author_profile": "https://Stackoverflow.com/users/1535134",
"pm_score": 2,
"selected": false,
"text": "<p>This is how i solved mine, in Interface builder right-click the View Controller, there should be an exclamation mark on the missing outlet or action method. Find and remove all the references and that solved it.</p>\n\n<p>This happened because i deleted the action method in the .m file.</p>\n"
}
] | 2008/09/05 | [
"https://Stackoverflow.com/questions/46220",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2293/"
] | I'm writing my first iPhone app, so I haven't gotten around to figuring out much in the way of debugging.
Essentially my app displays an image and when touched plays a short sound.
When compiling and building the project in XCode, everything builds successfully, but when the app is run in the iPhone simulator, it crashes.
I get the following error:
```
Application Specific Information:
iPhone Simulator 1.0 (70), iPhone OS 2.0 (5A331)
*** Terminating app due to uncaught exception 'NSUnknownKeyException',
reason: '[<UIView 0x34efd0> setValue:forUndefinedKey:]: this class is not key value
coding-compliant for the key kramerImage.'
```
kramerImage here is the image I'm using for the background.
I'm not sure what NSUnknownKeyException means or why the class is not key value coding-compliant for the key. | (This isn't really iPhone specific - the same thing will happen in regular Cocoa).
NSUnknownKeyException is a common error when using [Key-Value Coding](https://developer.apple.com/library/mac/#documentation/Cocoa/Conceptual/KeyValueCoding/Articles/KeyValueCoding.html) to access a key that the object doesn't have.
The properties of most Cocoa objects can be accessing directly:
```
[@"hello world" length] // Objective-C 1.0
@"hello world".length // Objective-C 2.0
```
Or via Key-Value Coding:
```
[@"hello world" valueForKey:@"length"]
```
I would get an NSUnknownKeyException if I used the following line:
```
[@"hello world" valueForKey:@"purpleMonkeyDishwasher"]
```
because NSString does not have a property (key) called 'purpleMonkeyDishwasher'.
Something in your code is trying to set a value for the key 'kramerImage' on an UIView, which (apparently) doesn't support that key. If you're using Interface Builder, it might be something in your nib.
Find where 'kramerImage' is being used, and try to track it down from there. |
46,282 | <p>I am using a class library which represents some of its configuration in .xml. The configuration is read in using the <code>XmlSerializer</code>. Fortunately, the classes which represent the .xml use the <code>XmlAnyElement</code> attribute at which allows me to extend the configuration data for my own purposes without modifying the original class library.</p>
<pre><code><?xml version="1.0" encoding="utf-8"?>
<Config>
<data>This is some data</data>
<MyConfig>
<data>This is my data</data>
</MyConfig>
</Config>
</code></pre>
<p>This works well for deserialization. I am able to allow the class library to deserialize the .xml as normal and the I can use my own <code>XmlSerializer</code> instances with a <code>XmlNodeReader</code> against the internal <code>XmlNode</code>.</p>
<pre><code>public class Config
{
[XmlElement]
public string data;
[XmlAnyElement]
public XmlNode element;
}
public class MyConfig
{
[XmlElement]
public string data;
}
class Program
{
static void Main(string[] args)
{
using (Stream fs = new FileStream(@"c:\temp\xmltest.xml", FileMode.Open))
{
XmlSerializer xser1 = new XmlSerializer(typeof(Config));
Config config = (Config)xser1.Deserialize(fs);
if (config.element != null)
{
XmlSerializer xser2 = new XmlSerializer(typeof(MyConfig));
MyConfig myConfig = (MyConfig)xser2.Deserialize(new XmlNodeReader(config.element));
}
}
}
</code></pre>
<p>I need to create a utility which will allow the user to generate a new configuration file that includes both the class library configuration as well my own configuration, so new objects will be created which were not read from the .xml file. The question is how can I serialize the data back into .xml? </p>
<p>I realize that I have to initially call <code>XmlSerializer.Serialize</code> on my data before calling the same method on the class library configuration. However, this requires that my data is represented by an <code>XmlNode</code> after calling <code>Serialize</code>. What is the best way to serialize an object into an <code>XmlNode</code> using the <code>XmlSerializer</code>?</p>
<p>Thanks,</p>
<p>-kevin</p>
<p>btw-- It looks like an <code>XmlNodeWriter</code> class written by Chris Lovett was available at one time from Microsoft, but the links are now broken. Does anyone know of an alternative location to get this class?</p>
| [
{
"answer_id": 46378,
"author": "Ed Schwehm",
"author_id": 1206,
"author_profile": "https://Stackoverflow.com/users/1206",
"pm_score": 5,
"selected": true,
"text": "<p>So you need to have your class contain custom configuration information, then serialize that class to XML, then make that serialized XML into an XML node: is that right?</p>\n\n<p>Could you just take the string created by the XMLSerializer and wrap that in it's own XML tags?</p>\n\n<pre><code>XmlSerializer xs = new XmlSerializer(typeof(MyConfig));\nStringWriter xout = new StringWriter();\nxs.Serialize(xout, myConfig);\nXmlDocument x = new XmlDocument();\nx.LoadXml(\"<myConfig>\" + xout.ToString() + \"</myConfig>\");\n</code></pre>\n\n<p>Now x is an XmlDocument containing one element, \"<myconfig>\", which has your serialized custom configuration in it.</p>\n\n<p>Is that at all what you're looking for? </p>\n"
},
{
"answer_id": 46401,
"author": "Kevin",
"author_id": 4599,
"author_profile": "https://Stackoverflow.com/users/4599",
"pm_score": 0,
"selected": false,
"text": "<p>One solution is to serialize the inner object to a string and then load the string into a XmlDocument where you can find the XmlNode representing your data and attach it to the outer object. </p>\n\n<pre><code>XmlSerializer xser1 = new XmlSerializer(typeof(Config));\nXmlSerializer xser2 = new XmlSerializer(typeof(MyConfig));\n\nMyConfig myConfig = new MyConfig();\nmyConfig.data = \"My special data\";\n\nStringBuilder sb = new StringBuilder();\nStringWriter sw = new StringWriter(sb);\nXmlWriter xw = new XmlTextWriter(sw);\nxser2.Serialize(xw, myConfig);\n\nXmlDocument doc = new XmlDocument();\ndoc.LoadXml(sb.ToString());\n\nConfig config = new Config();\nconfig.data = \"some new info\";\nconfig.element = doc.LastChild;\n\nxser1.Serialize(fs, config);\n</code></pre>\n\n<p>However, this solution is cumbersome and I would hope there is a better way, but it resolves my problem for now.</p>\n\n<p>Now if I could just find the mythical XmlNodeWriter referred to on several blogs!</p>\n"
},
{
"answer_id": 46457,
"author": "Ed Schwehm",
"author_id": 1206,
"author_profile": "https://Stackoverflow.com/users/1206",
"pm_score": 0,
"selected": false,
"text": "<p>At least one resource points to this as an alternative to XmlNodeWriter: <a href=\"http://msdn.microsoft.com/en-us/library/5x8bxy86.aspx\" rel=\"nofollow noreferrer\">http://msdn.microsoft.com/en-us/library/5x8bxy86.aspx</a>. Otherwise, you could write MS using that form they have on the new MSDN Code Library replacement for GotDotNet looking for XmlNodeWriter.</p>\n"
},
{
"answer_id": 307707,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 2,
"selected": false,
"text": "<p>It took a bit of work, but the XPathNavigator route does work... just remember to call .Close on the XmlWriter, .Flush() doesn't do anything:</p>\n\n<pre><code>//DataContractSerializer serializer = new DataContractSerializer(typeof(foo));\nXmlSerializer serializer = new XmlSerializer(typeof(foo));\n\nXmlDocument doc = new XmlDocument();\nXPathNavigator nav = doc.CreateNavigator();\nXmlWriter writer = nav.AppendChild();\nwriter.WriteStartDocument();\n//serializer.WriteObject(writer, new foo { bar = 42 });\nserializer.Serialize(writer, new foo { bar = 42 });\nwriter.WriteEndDocument();\nwriter.Flush();\nwriter.Close();\n\nConsole.WriteLine(doc.OuterXml);\n</code></pre>\n"
}
] | 2008/09/05 | [
"https://Stackoverflow.com/questions/46282",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4599/"
] | I am using a class library which represents some of its configuration in .xml. The configuration is read in using the `XmlSerializer`. Fortunately, the classes which represent the .xml use the `XmlAnyElement` attribute at which allows me to extend the configuration data for my own purposes without modifying the original class library.
```
<?xml version="1.0" encoding="utf-8"?>
<Config>
<data>This is some data</data>
<MyConfig>
<data>This is my data</data>
</MyConfig>
</Config>
```
This works well for deserialization. I am able to allow the class library to deserialize the .xml as normal and the I can use my own `XmlSerializer` instances with a `XmlNodeReader` against the internal `XmlNode`.
```
public class Config
{
[XmlElement]
public string data;
[XmlAnyElement]
public XmlNode element;
}
public class MyConfig
{
[XmlElement]
public string data;
}
class Program
{
static void Main(string[] args)
{
using (Stream fs = new FileStream(@"c:\temp\xmltest.xml", FileMode.Open))
{
XmlSerializer xser1 = new XmlSerializer(typeof(Config));
Config config = (Config)xser1.Deserialize(fs);
if (config.element != null)
{
XmlSerializer xser2 = new XmlSerializer(typeof(MyConfig));
MyConfig myConfig = (MyConfig)xser2.Deserialize(new XmlNodeReader(config.element));
}
}
}
```
I need to create a utility which will allow the user to generate a new configuration file that includes both the class library configuration as well my own configuration, so new objects will be created which were not read from the .xml file. The question is how can I serialize the data back into .xml?
I realize that I have to initially call `XmlSerializer.Serialize` on my data before calling the same method on the class library configuration. However, this requires that my data is represented by an `XmlNode` after calling `Serialize`. What is the best way to serialize an object into an `XmlNode` using the `XmlSerializer`?
Thanks,
-kevin
btw-- It looks like an `XmlNodeWriter` class written by Chris Lovett was available at one time from Microsoft, but the links are now broken. Does anyone know of an alternative location to get this class? | So you need to have your class contain custom configuration information, then serialize that class to XML, then make that serialized XML into an XML node: is that right?
Could you just take the string created by the XMLSerializer and wrap that in it's own XML tags?
```
XmlSerializer xs = new XmlSerializer(typeof(MyConfig));
StringWriter xout = new StringWriter();
xs.Serialize(xout, myConfig);
XmlDocument x = new XmlDocument();
x.LoadXml("<myConfig>" + xout.ToString() + "</myConfig>");
```
Now x is an XmlDocument containing one element, "<myconfig>", which has your serialized custom configuration in it.
Is that at all what you're looking for? |
46,324 | <p>I'm going to guess that the answer is "no" based on the below error message (and <a href="http://archives.postgresql.org/pgsql-sql/2004-08/msg00076.php" rel="noreferrer">this Google result</a>), but is there anyway to perform a cross-database query using PostgreSQL?</p>
<pre><code>databaseA=# select * from databaseB.public.someTableName;
ERROR: cross-database references are not implemented:
"databaseB.public.someTableName"
</code></pre>
<p>I'm working with some data that is partitioned across two databases although data is really shared between the two (userid columns in one database come from the <code>users</code> table in the other database). I have no idea why these are two separate databases instead of schema, but c'est la vie...</p>
| [
{
"answer_id": 46336,
"author": "stimms",
"author_id": 361,
"author_profile": "https://Stackoverflow.com/users/361",
"pm_score": 5,
"selected": false,
"text": "<p>I have run into this before an came to the same conclusion about cross database queries as you. What I ended up doing was using schemas to divide the table space that way I could keep the tables grouped but still query them all. </p>\n"
},
{
"answer_id": 46448,
"author": "Neall",
"author_id": 619,
"author_profile": "https://Stackoverflow.com/users/619",
"pm_score": 8,
"selected": true,
"text": "<p><em>Note: As the original asker implied, if you are setting up two databases on the same machine you probably want to make two <a href=\"https://www.postgresql.org/docs/current/static/ddl-schemas.html\" rel=\"noreferrer\">schemas</a> instead - in that case you don't need anything special to query across them.</em></p>\n\n<h2><code>postgres_fdw</code></h2>\n\n<p>Use <a href=\"https://www.postgresql.org/docs/current/postgres-fdw.html\" rel=\"noreferrer\"><code>postgres_fdw</code></a> (foreign data wrapper) to connect to tables in any Postgres database - local or remote.</p>\n\n<p>Note that there are <a href=\"http://wiki.postgresql.org/wiki/Foreign_data_wrappers\" rel=\"noreferrer\">foreign data wrappers for other popular data sources</a>. At this time, only <code>postgres_fdw</code> and <code>file_fdw</code> are part of the official Postgres distribution.</p>\n\n<h3>For Postgres versions before 9.3</h3>\n\n<p>Versions this old are no longer supported, but if you need to do this in a pre-2013 Postgres installation, there is a function called <a href=\"https://www.postgresql.org/docs/current/dblink.html\" rel=\"noreferrer\"><code>dblink</code></a>.</p>\n\n<p>I've never used it, but it is maintained and distributed with the rest of PostgreSQL. If you're using the version of PostgreSQL that came with your Linux distro, you might need to install a package called postgresql-contrib.</p>\n"
},
{
"answer_id": 59389,
"author": "dpavlin",
"author_id": 1081,
"author_profile": "https://Stackoverflow.com/users/1081",
"pm_score": 2,
"selected": false,
"text": "<p>If performance is important and most queries are read-only, I would suggest to replicate data over to another database. While this seems like unneeded duplication of data, it might help if indexes are required.</p>\n\n<p>This can be done with simple on insert triggers which in turn call dblink to update another copy. There are also full-blown replication options (like Slony) but that's off-topic.</p>\n"
},
{
"answer_id": 113337,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 3,
"selected": false,
"text": "<p>Yes, you can by using DBlink (postgresql only) and DBI-Link (allows foreign cross database queriers) and TDS_LInk which allows queries to be run against MS SQL server.</p>\n\n<p>I have used DB-Link and TDS-link before with great success.</p>\n"
},
{
"answer_id": 2784520,
"author": "Esteban Küber",
"author_id": 34813,
"author_profile": "https://Stackoverflow.com/users/34813",
"pm_score": 4,
"selected": false,
"text": "<p><sub>Just to add a bit more information.</sub></p>\n<blockquote>\n<p>There is no way to query a database other than the current one. Because PostgreSQL loads database-specific system catalogs, it is uncertain how a cross-database query should even behave.</p>\n<p>contrib/dblink allows cross-database queries using function calls. Of course, a client can also make simultaneous connections to different databases and merge the results on the client side.</p>\n</blockquote>\n<p><a href=\"http://wiki.postgresql.org/wiki/FAQ#How_do_I_perform_queries_using_multiple_databases.3F\" rel=\"noreferrer\">PostgreSQL FAQ</a></p>\n"
},
{
"answer_id": 27054140,
"author": "Manwal",
"author_id": 2236219,
"author_profile": "https://Stackoverflow.com/users/2236219",
"pm_score": 6,
"selected": false,
"text": "<h1><a href=\"http://www.postgresql.org/docs/current/interactive/dblink.html\" rel=\"nofollow noreferrer\">dblink()</a> -- executes a query in a remote database</h1>\n<blockquote>\n<p>dblink executes a query (usually a SELECT, but it can be any SQL\nstatement that returns rows) in a remote database.</p>\n<p>When two text arguments are given, the first one is first looked up as\na persistent connection's name; if found, the command is executed on\nthat connection. If not found, the first argument is treated as a\nconnection info string as for dblink_connect, and the indicated\nconnection is made just for the duration of this command.</p>\n</blockquote>\n<p>one of the good example:</p>\n<pre><code>SELECT * \nFROM table1 tb1 \nLEFT JOIN (\n SELECT *\n FROM dblink('dbname=db2','SELECT id, code FROM table2')\n AS tb2(id int, code text);\n) AS tb2 ON tb2.column = tb1.column;\n</code></pre>\n<p>Note: I am giving this information for future reference. <a href=\"https://stackoverflow.com/questions/4678862/joining-results-from-two-separate-databases\">Reference</a></p>\n"
},
{
"answer_id": 55653353,
"author": "Haroldo_OK",
"author_id": 679240,
"author_profile": "https://Stackoverflow.com/users/679240",
"pm_score": 1,
"selected": false,
"text": "<p>In case someone needs a more involved example on how to do cross-database queries, here's an example that cleans up the <code>databasechangeloglock</code> table on every database that has it:</p>\n\n<pre><code>CREATE EXTENSION IF NOT EXISTS dblink;\n\nDO \n$$\nDECLARE database_name TEXT;\nDECLARE conn_template TEXT;\nDECLARE conn_string TEXT;\nDECLARE table_exists Boolean;\nBEGIN\n conn_template = 'user=myuser password=mypass dbname=';\n\n FOR database_name IN\n SELECT datname FROM pg_database\n WHERE datistemplate = false\n LOOP\n conn_string = conn_template || database_name;\n\n table_exists = (select table_exists_ from dblink(conn_string, '(select Count(*) > 0 from information_schema.tables where table_name = ''databasechangeloglock'')') as (table_exists_ Boolean));\n IF table_exists THEN\n perform dblink_exec(conn_string, 'delete from databasechangeloglock');\n END IF; \n END LOOP;\n\nEND\n$$\n</code></pre>\n"
},
{
"answer_id": 57008050,
"author": "Rocckk",
"author_id": 11248397,
"author_profile": "https://Stackoverflow.com/users/11248397",
"pm_score": 2,
"selected": false,
"text": "<p>I have checked and tried to create a foreign key relationships between 2 tables in 2 different databases using both <em>dblink</em> and <em>postgres_fdw</em> but with no result.</p>\n\n<p>Having read the other peoples feedback on this, for example <a href=\"https://www.postgresql.org/message-id/flat/CADVWZZL-yARvY9srTy2HM2n8HxW%3DeYhpEJJjzYor7E_5tUYRqw%40mail.gmail.com\" rel=\"nofollow noreferrer\">here</a> and <a href=\"https://dba.stackexchange.com/questions/212649/create-foreign-key-on-foreign-table-in-postgresql\">here</a> and in some other sources it looks like there is no way to do that currently:</p>\n\n<p>The <em>dblink</em> and <em>postgres_fdw</em> indeed enable one to connect to and query tables in other databases, which is not possible with the standard Postgres, but they do not allow to establish foreign key relationships between tables in different databases.</p>\n"
},
{
"answer_id": 66078827,
"author": "Kind Contributor",
"author_id": 887092,
"author_profile": "https://Stackoverflow.com/users/887092",
"pm_score": 2,
"selected": false,
"text": "<p>see <a href=\"https://www.cybertec-postgresql.com/en/joining-data-from-multiple-postgres-databases/\" rel=\"nofollow noreferrer\">https://www.cybertec-postgresql.com/en/joining-data-from-multiple-postgres-databases/</a> [published 2017]</p>\n<p>These days you also have the option to use <a href=\"https://prestodb.io/\" rel=\"nofollow noreferrer\">https://prestodb.io/</a></p>\n<p>You can run SQL on that PrestoDB node and it will distribute the SQL query as required. It can connect to the same node twice for different databases, or it might be connecting to different nodes on different hosts.</p>\n<p>It does not support:</p>\n<pre><code>DELETE\nALTER TABLE\nCREATE TABLE (CREATE TABLE AS is supported)\nGRANT\nREVOKE\nSHOW GRANTS\nSHOW ROLES\nSHOW ROLE GRANTS\n</code></pre>\n<p>So you should only use it for SELECT and JOIN needs. Connect directly to each database for the above needs. (It looks like you can also INSERT or UPDATE which is nice)</p>\n<p>Client applications connect to PrestoDB primarily using <a href=\"https://prestodb.io/docs/current/installation/jdbc.html\" rel=\"nofollow noreferrer\">JDBC</a>, but other types of connection are possible including a <a href=\"https://prestodb.io/docs/current/installation/tableau.html\" rel=\"nofollow noreferrer\">Tableu compatible web API</a></p>\n<p>This is an open source tool governed by the Linux Foundation and Presto Foundation.</p>\n<blockquote>\n<p>The founding members of the Presto Foundation are: Facebook, Uber,\nTwitter, and Alibaba.</p>\n<p>The current members are: Facebook, Uber, Twitter, Alibaba, Alluxio,\nAhana, Upsolver, and Intel.</p>\n</blockquote>\n"
}
] | 2008/09/05 | [
"https://Stackoverflow.com/questions/46324",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4249/"
] | I'm going to guess that the answer is "no" based on the below error message (and [this Google result](http://archives.postgresql.org/pgsql-sql/2004-08/msg00076.php)), but is there anyway to perform a cross-database query using PostgreSQL?
```
databaseA=# select * from databaseB.public.someTableName;
ERROR: cross-database references are not implemented:
"databaseB.public.someTableName"
```
I'm working with some data that is partitioned across two databases although data is really shared between the two (userid columns in one database come from the `users` table in the other database). I have no idea why these are two separate databases instead of schema, but c'est la vie... | *Note: As the original asker implied, if you are setting up two databases on the same machine you probably want to make two [schemas](https://www.postgresql.org/docs/current/static/ddl-schemas.html) instead - in that case you don't need anything special to query across them.*
`postgres_fdw`
--------------
Use [`postgres_fdw`](https://www.postgresql.org/docs/current/postgres-fdw.html) (foreign data wrapper) to connect to tables in any Postgres database - local or remote.
Note that there are [foreign data wrappers for other popular data sources](http://wiki.postgresql.org/wiki/Foreign_data_wrappers). At this time, only `postgres_fdw` and `file_fdw` are part of the official Postgres distribution.
### For Postgres versions before 9.3
Versions this old are no longer supported, but if you need to do this in a pre-2013 Postgres installation, there is a function called [`dblink`](https://www.postgresql.org/docs/current/dblink.html).
I've never used it, but it is maintained and distributed with the rest of PostgreSQL. If you're using the version of PostgreSQL that came with your Linux distro, you might need to install a package called postgresql-contrib. |
46,338 | <p>I am writing a webapp using CodeIgniter that requires authentication. I created a model which handles all my authentication. However, I can't find a way to access this authentication model from inside another model. Is there a way to access a model from inside another mode, or a better way to handle authentication inside CodeIgniter?</p>
| [
{
"answer_id": 46356,
"author": "Till",
"author_id": 2859,
"author_profile": "https://Stackoverflow.com/users/2859",
"pm_score": 5,
"selected": true,
"text": "<p>In general, you don't want to create objects inside an object. That's a bad habit, instead, write a clear API and inject a model into your model.</p>\n\n<pre><code><?php\n// in your controller\n$model1 = new Model1();\n$model2 = new Model2();\n$model2->setWhatever($model1);\n?>\n</code></pre>\n"
},
{
"answer_id": 74972,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 1,
"selected": false,
"text": "<p>Don't handle authentication in your model. Only use models to interface with your database, or ldap or whatever.</p>\n\n<p>I created an Auth library that I use to manage authentication and authorization. You can access a library like this from your controllers.</p>\n"
},
{
"answer_id": 75087,
"author": "Christian Davén",
"author_id": 12534,
"author_profile": "https://Stackoverflow.com/users/12534",
"pm_score": 4,
"selected": false,
"text": "<p>It seems you can load models inside models, although you probably should solve this another way. See <a href=\"http://codeigniter.com/forums/viewthread/49625\" rel=\"noreferrer\">CodeIgniter forums</a> for a discussion.</p>\n\n<pre><code>class SomeModel extends Model\n{\n function doSomething($foo)\n {\n $CI =& get_instance();\n $CI->load->model('SomeOtherModel','NiceName',true);\n\n // use $CI instead of $this to query the other models\n $CI->NiceName->doSomethingElse();\n }\n}\n</code></pre>\n\n<p>Also, I don't understand what Till is saying about that you shouldn't create objects inside objects. Of course you should! Sending objects as arguments looks much less clear to me.</p>\n"
},
{
"answer_id": 17734189,
"author": "saada",
"author_id": 1204900,
"author_profile": "https://Stackoverflow.com/users/1204900",
"pm_score": 1,
"selected": false,
"text": "<p>Loading a model within a model is now possible with the new CodeIgniter.</p>\n"
}
] | 2008/09/05 | [
"https://Stackoverflow.com/questions/46338",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/889/"
] | I am writing a webapp using CodeIgniter that requires authentication. I created a model which handles all my authentication. However, I can't find a way to access this authentication model from inside another model. Is there a way to access a model from inside another mode, or a better way to handle authentication inside CodeIgniter? | In general, you don't want to create objects inside an object. That's a bad habit, instead, write a clear API and inject a model into your model.
```
<?php
// in your controller
$model1 = new Model1();
$model2 = new Model2();
$model2->setWhatever($model1);
?>
``` |
46,346 | <p>Any ideas on how to implement tab completion for a .NET (C#) Console Application?
And I mean within an application that is run and then loops for user input (like if you run ftp.exe without any arguments), like this: </p>
<pre><code> string line = string.Empty;
while (line != "exit")
{
//do something here
Console.ReadLine();
}
</code></pre>
<p>I know I probably couldn't actually use readline, but I would like to be able to do tab completion at that same point where you retrieve input from the user.</p>
| [
{
"answer_id": 46352,
"author": "Andrew Burns",
"author_id": 3683,
"author_profile": "https://Stackoverflow.com/users/3683",
"pm_score": 2,
"selected": false,
"text": "<p><a href=\"http://msdn.microsoft.com/en-us/library/system.console.readkey.aspx\" rel=\"nofollow noreferrer\">Console.ReadKey</a></p>\n"
},
{
"answer_id": 46396,
"author": "kenny",
"author_id": 3225,
"author_profile": "https://Stackoverflow.com/users/3225",
"pm_score": 4,
"selected": true,
"text": "<p>Take a look at this code from the Mono project\n<a href=\"http://tirania.org/blog/archive/2008/Aug-26.html\" rel=\"noreferrer\">http://tirania.org/blog/archive/2008/Aug-26.html</a>\nI played with it some the other day.\nIt does a lot of command line editingy, but I don't think it does line completion.</p>\n"
},
{
"answer_id": 47594,
"author": "Lars Mæhlum",
"author_id": 960,
"author_profile": "https://Stackoverflow.com/users/960",
"pm_score": 3,
"selected": false,
"text": "<p>Do a Console.ReadKey(). </p>\n\n<p>If you get a Tab, look at what you have in the command buffer, and loop through your available commands. If <code>someCommand.Name.BeginsWith(currentinput)</code>, you have a winner, and you can write to screen a list of possible commands. </p>\n\n<p>If <em>there is only one(TM)</em> you can substitute it with what the user had typed :)</p>\n"
},
{
"answer_id": 38383928,
"author": "Fábio Junqueira",
"author_id": 2716578,
"author_profile": "https://Stackoverflow.com/users/2716578",
"pm_score": 3,
"selected": false,
"text": "<p>I created a small lib to add this functionality to an app i made:</p>\n\n<p><a href=\"https://github.com/fjunqueira/hinter\" rel=\"noreferrer\">https://github.com/fjunqueira/hinter</a></p>\n\n<p>It might not suit your needs, but you can feel free to edit it.</p>\n"
},
{
"answer_id": 57116500,
"author": "Olivier Duhart",
"author_id": 5006676,
"author_profile": "https://Stackoverflow.com/users/5006676",
"pm_score": 1,
"selected": false,
"text": "<p><a href=\"https://github.com/tonerdo/readline\" rel=\"nofollow noreferrer\">https://github.com/tonerdo/readline</a> is what you need.\ngreat lib available as a nuget from the talented dev tonerdo.</p>\n<p><em>pasted from the site:</em></p>\n<blockquote>\n<p>...<br/>\n<strong>ReadLine</strong> is a GNU Readline like library built in pure C#\nIt can serve as a drop in replacement for the inbuilt <code>Console.ReadLine()</code> and brings along with it some of the terminal goodness you get from unix shells, like command history navigation and tab auto completion.<br/>\n...</p>\n</blockquote>\n"
}
] | 2008/09/05 | [
"https://Stackoverflow.com/questions/46346",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/194/"
] | Any ideas on how to implement tab completion for a .NET (C#) Console Application?
And I mean within an application that is run and then loops for user input (like if you run ftp.exe without any arguments), like this:
```
string line = string.Empty;
while (line != "exit")
{
//do something here
Console.ReadLine();
}
```
I know I probably couldn't actually use readline, but I would like to be able to do tab completion at that same point where you retrieve input from the user. | Take a look at this code from the Mono project
<http://tirania.org/blog/archive/2008/Aug-26.html>
I played with it some the other day.
It does a lot of command line editingy, but I don't think it does line completion. |
46,347 | <p>Is there a clean way to redirect all attempts to going to an HTTP:// version of a site to its HTTPS:// equivalent?</p>
| [
{
"answer_id": 46418,
"author": "slipsec",
"author_id": 1635,
"author_profile": "https://Stackoverflow.com/users/1635",
"pm_score": -1,
"selected": false,
"text": "<p>I think by 'cleanly' you mean like with a 300 redirect. Config for a lot of servers & languages <a href=\"http://www.somacon.com/p145.php\" rel=\"nofollow noreferrer\">here</a>.</p>\n"
},
{
"answer_id": 1207097,
"author": "mika",
"author_id": 13460,
"author_profile": "https://Stackoverflow.com/users/13460",
"pm_score": 3,
"selected": false,
"text": "<p>A clean way changes only the URL scheme from http -> https and leaves everything else equivalent. It should be server-side so that there are no browser issues.</p>\n\n<p>JPPinto.com has <a href=\"http://www.jppinto.com/index.php/2009/04/automatically-redirect-http-requests-to-https-iis-7/\" rel=\"nofollow noreferrer\">Step-By-Step instructions</a> on how this is done, except that they use javascript (HttpRedirect.htm) instead of a server-side redirect. For some reason, I couldn't get IE run the javascript if you have ‘Show friendly HTTP error messages’ enabled, which is on by default. Another thing with the script is that redirection to path didn't work even in FF or Chrome. The script always redirects to root. (Maybe I have missed something, because it should redirect to path.)</p>\n\n<p>For these reasons I have used an ASP page for the redirect. The downside is of course that this requires classic ASP to be enabled on the server.</p>\n\n<p>OpsanBlog has an <a href=\"http://blog.opsan.com/archive/2005/04/17/395.aspx\" rel=\"nofollow noreferrer\">ASP script and instructions</a> that work well with IIS6. </p>\n\n<p>I've had a few issues using this method with IIS7. User interface issues mostly, since IIS7 makes it really easy to miss something.</p>\n\n<ul>\n<li>First, you need to install ASP as a\nweb server role feature. </li>\n<li>Second, using a virtual directory didn't not\nwork as expected in IIS7 and I didn't\ntry to debug this. Instead, I put the file in the root folder of the site and used\nthe url '/SSLRedirect.asp' in the\n403.4 error page to reference it.</li>\n<li>Last, the most tricky part, you <strong>must NOT enforce SSL for SSLRedirect.asp</strong>. Otherwise you'll get an 403.4 error. To do this you pick the file in IIS7 'Content View', and switch to 'Features View' so that you can edit the SSL settings for the single file and disable 'Require SSL' checkbox. </li>\n</ul>\n\n<p>IIS manager should show the file name in the header. </p>\n"
},
{
"answer_id": 7605311,
"author": "toxaq",
"author_id": 97429,
"author_profile": "https://Stackoverflow.com/users/97429",
"pm_score": 8,
"selected": true,
"text": "<p>I think the cleanest way is as described <a href=\"http://www.iis-aid.com/articles/how_to_guides/redirect_http_to_https_iis_7\" rel=\"nofollow noreferrer\">here on IIS-aid.com</a>. It's web.config only and so if you change server you don't have to remember all the steps you went through with the 403.4 custom error page or other special permissions, it just works.</p>\n\n<pre><code><configuration>\n <system.webServer>\n <rewrite>\n <rules>\n <rule name=\"HTTP to HTTPS redirect\" stopProcessing=\"true\">\n <match url=\"(.*)\" />\n <conditions>\n <add input=\"{HTTPS}\" pattern=\"off\" ignoreCase=\"true\" />\n </conditions>\n <action type=\"Redirect\" redirectType=\"Permanent\" url=\"https://{HTTP_HOST}/{R:1}\" />\n </rule>\n </rules>\n </rewrite>\n </system.webServer>\n</configuration>\n</code></pre>\n"
},
{
"answer_id": 38369227,
"author": "ColacX",
"author_id": 700735,
"author_profile": "https://Stackoverflow.com/users/700735",
"pm_score": 4,
"selected": false,
"text": "<p>The most easy and clean solution I found was to</p>\n\n<ol>\n<li><p>In SSL Settings -> require SSL</p></li>\n<li><p>In Error Pages -> On 403.4 error -> Redirect to the HTTPS site</p></li>\n<li><p>In Error Pages -> Edit Features Settings... -> Set Detailed errors for local requests and custom error pages for remote request</p></li>\n</ol>\n\n<p>The benefit is that it requires no extra lines of code.\nDownside is that it redirects you to an absolute url.</p>\n"
},
{
"answer_id": 44283235,
"author": "Toolkit",
"author_id": 631527,
"author_profile": "https://Stackoverflow.com/users/631527",
"pm_score": 0,
"selected": false,
"text": "<p>Global.asax</p>\n\n<pre><code>protected void Application_BeginRequest()\n{\nif (!Context.Request.Url.AbsoluteUri.Contains(\"localhost\") && !Context.Request.IsSecureConnection)\nResponse.Redirect(Context.Request.Url.ToString().Replace(\"http:\", \"https:\"));\n}\n</code></pre>\n"
},
{
"answer_id": 53725455,
"author": "Jean-Marc",
"author_id": 2729328,
"author_profile": "https://Stackoverflow.com/users/2729328",
"pm_score": 0,
"selected": false,
"text": "<p>I use classic asp (intranet) and on pages that requires login the logon include file does the redirect: </p>\n\n<pre><code>if Request.ServerVariables(\"SERVER_PORT_SECURE\") <> \"1\" or Request.ServerVariables(\"HTTPS\") <> \"on\" then \n Response.Redirect \"https://\" & Request.ServerVariables(\"SERVER_NAME\") & Request.ServerVariables(\"URL\")\nend if\n</code></pre>\n\n<p>This of course does not include GET or POST data. So in effect it's a clean redirect to your secured page. </p>\n"
}
] | 2008/09/05 | [
"https://Stackoverflow.com/questions/46347",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2312/"
] | Is there a clean way to redirect all attempts to going to an HTTP:// version of a site to its HTTPS:// equivalent? | I think the cleanest way is as described [here on IIS-aid.com](http://www.iis-aid.com/articles/how_to_guides/redirect_http_to_https_iis_7). It's web.config only and so if you change server you don't have to remember all the steps you went through with the 403.4 custom error page or other special permissions, it just works.
```
<configuration>
<system.webServer>
<rewrite>
<rules>
<rule name="HTTP to HTTPS redirect" stopProcessing="true">
<match url="(.*)" />
<conditions>
<add input="{HTTPS}" pattern="off" ignoreCase="true" />
</conditions>
<action type="Redirect" redirectType="Permanent" url="https://{HTTP_HOST}/{R:1}" />
</rule>
</rules>
</rewrite>
</system.webServer>
</configuration>
``` |
46,350 | <p>After lots of attempts and search I have never found a satisfactory way to do it with CSS2.</p>
<p>A simple way to accomplish it is to wrap it into a handy <code><table></code> as shown in the sample below. Do you know how to do it avoiding table layouts and also avoiding quirky tricks?</p>
<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-css lang-css prettyprint-override"><code>table {
margin: 0 auto;
}</code></pre>
<pre class="snippet-code-html lang-html prettyprint-override"><code><table>
<tr>
<td>test<br/>test</td>
</tr>
</table></code></pre>
</div>
</div>
</p>
<hr />
<p>What I want to know is how to do it without a fixed width and also being a block.</p>
| [
{
"answer_id": 46364,
"author": "Jason Bunting",
"author_id": 1790,
"author_profile": "https://Stackoverflow.com/users/1790",
"pm_score": 2,
"selected": false,
"text": "<p>This is going to be the lamest answer, but it works:</p>\n\n<p><a href=\"http://www.w3schools.com/TAGS/tag_center.asp\" rel=\"nofollow noreferrer\"><strong>Use the deprecated <center> tag</strong></a>.</p>\n\n<p>:P</p>\n\n<p>I told you it would be lame. But, like I said, it works!</p>\n\n<p>*shudder*</p>\n"
},
{
"answer_id": 46391,
"author": "Joe Liversedge",
"author_id": 4552,
"author_profile": "https://Stackoverflow.com/users/4552",
"pm_score": 4,
"selected": true,
"text": "<p>@Jason, yep, <code><center></code> works. Good times. I'll propose the following, though:</p>\n\n<p><div class=\"snippet\" data-lang=\"js\" data-hide=\"false\" data-console=\"true\" data-babel=\"false\">\r\n<div class=\"snippet-code\">\r\n<pre class=\"snippet-code-css lang-css prettyprint-override\"><code>body {\r\n text-align: center;\r\n}\r\n\r\n.my-centered-content {\r\n margin: 0 auto; /* Centering */\r\n display: inline;\r\n}</code></pre>\r\n<pre class=\"snippet-code-html lang-html prettyprint-override\"><code><div class=\"my-centered-content\">\r\n <p>test</p>\r\n <p>test</p>\r\n</div></code></pre>\r\n</div>\r\n</div>\r\n</p>\n\n<p><strong>EDIT</strong> @Santi, a block-level element will fill the width of the parent container, so it will effectively be <code>width:100%</code> and the text will flow on the left, leaving you with useless markup and an uncentered element. You might want to try <code>display: inline-block;</code>. Firefox might complain, but <a href=\"http://www.w3.org/TR/CSS21/visuren.html#display-prop\" rel=\"nofollow noreferrer\">it's right</a>. Also, try adding a <code>border: solid red 1px;</code> to the CSS of the <code>.my-centered-content</code> DIV to see what's happening as you try these things out.</p>\n"
},
{
"answer_id": 46392,
"author": "Neall",
"author_id": 619,
"author_profile": "https://Stackoverflow.com/users/619",
"pm_score": 1,
"selected": false,
"text": "<p>I think that your example would work just as well if you used a <div> instead of a <table>. The only difference is that the text in the <table> is also centered. If you want that too, just add the text-align: center; rule.</p>\n\n<p>Another thing to keep in mind is that the <div> will by default fill up all the available horizontal space. Put a border on it if you aren't sure where it starts and ends.</p>\n"
},
{
"answer_id": 46420,
"author": "codeLes",
"author_id": 3030,
"author_profile": "https://Stackoverflow.com/users/3030",
"pm_score": 0,
"selected": false,
"text": "<p>The following works well enough. note the <em>position</em>, and the use of <em>auto</em></p>\n\n<pre><code><div style=\"border: 1px solid black; \n width: 300px; \n height: 300px;\">\n <div style=\"width: 150px; \n height: 150px; \n background-color: blue;\n position: relative;\n left: auto;\n right: auto;\n margin-right: auto;\n margin-left: auto;\">\n </div>\n</div>\n</code></pre>\n\n\n \n \n\n\n<p>NOTE: not sure if it works in IE.</p>\n"
},
{
"answer_id": 46652,
"author": "ironkeith",
"author_id": 4106,
"author_profile": "https://Stackoverflow.com/users/4106",
"pm_score": 0,
"selected": false,
"text": "<p><div class=\"snippet\" data-lang=\"js\" data-hide=\"false\" data-console=\"true\" data-babel=\"false\">\r\n<div class=\"snippet-code\">\r\n<pre class=\"snippet-code-css lang-css prettyprint-override\"><code>#wrapper {\r\n width: 100%;\r\n border: 1px solid #333;\r\n}\r\n#content {\r\n width: 200px;\r\n background: #0f0;\r\n}</code></pre>\r\n<pre class=\"snippet-code-html lang-html prettyprint-override\"><code><div id=\"wrapper\" align=\"center\">\r\n <div id=\"content\" align=\"left\"> Content Here </div>\r\n</div></code></pre>\r\n</div>\r\n</div>\r\n</p>\n"
},
{
"answer_id": 50393,
"author": "Bobby Jack",
"author_id": 5058,
"author_profile": "https://Stackoverflow.com/users/5058",
"pm_score": 0,
"selected": false,
"text": "<p>In FF3, you can:</p>\n\n<pre><code><div style=\"display: table; margin: 0px auto 0 auto;\">test<br>test</div>\n</code></pre>\n\n<p>This has the advantage of using whatever element makes most semantic sense (replace the div with something better, if appropriate), but the disadvantage that it fails in IE (grr...)</p>\n\n<p>Other than that, without setting the width, your best bet is to use javascript to precisely position the left-hand edge. I'm not sure if you'd class that as a 'quirky trick', though.</p>\n\n<p>It really depends on what you want to do, of course. Given your simple test case, a div with text-align: center would have exactly the same effect.</p>\n"
}
] | 2008/09/05 | [
"https://Stackoverflow.com/questions/46350",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4264/"
] | After lots of attempts and search I have never found a satisfactory way to do it with CSS2.
A simple way to accomplish it is to wrap it into a handy `<table>` as shown in the sample below. Do you know how to do it avoiding table layouts and also avoiding quirky tricks?
```css
table {
margin: 0 auto;
}
```
```html
<table>
<tr>
<td>test<br/>test</td>
</tr>
</table>
```
---
What I want to know is how to do it without a fixed width and also being a block. | @Jason, yep, `<center>` works. Good times. I'll propose the following, though:
```css
body {
text-align: center;
}
.my-centered-content {
margin: 0 auto; /* Centering */
display: inline;
}
```
```html
<div class="my-centered-content">
<p>test</p>
<p>test</p>
</div>
```
**EDIT** @Santi, a block-level element will fill the width of the parent container, so it will effectively be `width:100%` and the text will flow on the left, leaving you with useless markup and an uncentered element. You might want to try `display: inline-block;`. Firefox might complain, but [it's right](http://www.w3.org/TR/CSS21/visuren.html#display-prop). Also, try adding a `border: solid red 1px;` to the CSS of the `.my-centered-content` DIV to see what's happening as you try these things out. |
46,354 | <p>I'm trying to perform a SQL query through a linked SSAS server. The initial query works fine:</p>
<pre><code>SELECT "Ugly OLAP name" as "Value"
FROM OpenQuery( OLAP, 'OLAP Query')
</code></pre>
<p>But if I try to add:</p>
<pre><code>WHERE "Value" > 0
</code></pre>
<p>I get an error</p>
<blockquote>
<p>Invalid column name 'Value'</p>
</blockquote>
<p>Any ideas what I might be doing wrong?</p>
<hr>
<p>So the problem was that the order in which elements of the query are processed are different that the order they are written. According to this source:</p>
<p><a href="http://blogs.x2line.com/al/archive/2007/06/30/3187.aspx" rel="noreferrer">http://blogs.x2line.com/al/archive/2007/06/30/3187.aspx</a></p>
<p>The order of evaluation in MSSQL is:</p>
<ol>
<li>FROM</li>
<li>ON</li>
<li>JOIN</li>
<li>WHERE</li>
<li>GROUP BY</li>
<li>HAVING</li>
<li>SELECT</li>
<li>ORDER BY</li>
</ol>
<p>So the alias wasn't processed until after the WHERE and HAVING clauses.</p>
| [
{
"answer_id": 46375,
"author": "Till",
"author_id": 2859,
"author_profile": "https://Stackoverflow.com/users/2859",
"pm_score": 0,
"selected": false,
"text": "<p>Oh, bummer. I just saw, you select AS FOO. Don't you need a HAVING claus in this case?</p>\n\n<pre><code>SELECT whatever AS value FROM table HAVING value > 1;\n</code></pre>\n\n<p>I still would not use \"value\". But to be sure, look it up in your docs!</p>\n"
},
{
"answer_id": 46382,
"author": "Chris Miller",
"author_id": 206,
"author_profile": "https://Stackoverflow.com/users/206",
"pm_score": 5,
"selected": true,
"text": "<p>This should work:</p>\n\n<pre><code>SELECT A.Value\nFROM (\nSELECT \"Ugly OLAP name\" as \"Value\" \nFROM OpenQuery( OLAP, 'OLAP Query')\n) AS a\nWHERE a.Value > 0\n</code></pre>\n\n<p>It's not that Value is a reserved word, the problem is that it's a column alias, not the column name. By making it an inline view, \"Value\" becomes the column name and can then be used in a where clause.</p>\n"
},
{
"answer_id": 46552,
"author": "Andrew",
"author_id": 826,
"author_profile": "https://Stackoverflow.com/users/826",
"pm_score": 3,
"selected": false,
"text": "<p>You're using \"Value\" as a column alias, and I don't think the alias can appear in the where clause. It's simply used to name the returned column value. Your where clause should refer to the original column name:</p>\n\n<pre><code>SELECT \"Ugly OLAP name\" as \"Value\" \nFROM OpenQuery( OLAP, 'OLAP Query')\nWHERE \"Ugly OLAP name\" > 0\n</code></pre>\n"
},
{
"answer_id": 10235088,
"author": "John Dunagan",
"author_id": 28939,
"author_profile": "https://Stackoverflow.com/users/28939",
"pm_score": 0,
"selected": false,
"text": "<p>I can vouch for leaving it out of GROUP BY. Good news is, it works just fine being a plain old selected alias.</p>\n"
}
] | 2008/09/05 | [
"https://Stackoverflow.com/questions/46354",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1807/"
] | I'm trying to perform a SQL query through a linked SSAS server. The initial query works fine:
```
SELECT "Ugly OLAP name" as "Value"
FROM OpenQuery( OLAP, 'OLAP Query')
```
But if I try to add:
```
WHERE "Value" > 0
```
I get an error
>
> Invalid column name 'Value'
>
>
>
Any ideas what I might be doing wrong?
---
So the problem was that the order in which elements of the query are processed are different that the order they are written. According to this source:
<http://blogs.x2line.com/al/archive/2007/06/30/3187.aspx>
The order of evaluation in MSSQL is:
1. FROM
2. ON
3. JOIN
4. WHERE
5. GROUP BY
6. HAVING
7. SELECT
8. ORDER BY
So the alias wasn't processed until after the WHERE and HAVING clauses. | This should work:
```
SELECT A.Value
FROM (
SELECT "Ugly OLAP name" as "Value"
FROM OpenQuery( OLAP, 'OLAP Query')
) AS a
WHERE a.Value > 0
```
It's not that Value is a reserved word, the problem is that it's a column alias, not the column name. By making it an inline view, "Value" becomes the column name and can then be used in a where clause. |
46,365 | <p>We have a SQL Server 2005 SP2 machine running a large number of databases, all of which contain full-text catalogs. Whenever we try to drop one of these databases or rebuild a full-text index, the drop or rebuild process hangs indefinitely with a MSSEARCH wait type. The process can’t be killed, and a server reboot is required to get things running again. Based on a Microsoft forums post<a href="http://forums.microsoft.com/MSDN/ShowPost.aspx?PostID=2681739&SiteID=1" rel="noreferrer">1</a>, it appears that the problem might be an improperly removed full-text catalog. Can anyone recommend a way to determine which catalog is causing the problem, without having to remove all of them?</p>
<p><a href="http://forums.microsoft.com/MSDN/ShowPost.aspx?PostID=2681739&SiteID=1" rel="noreferrer">1</a> [<a href="http://forums.microsoft.com/MSDN/ShowPost.aspx?PostID=2681739&SiteID=1]" rel="noreferrer">http://forums.microsoft.com/MSDN/ShowPost.aspx?PostID=2681739&SiteID=1]</a>
“Yes we did have full text catalogues in the database, but since I had disabled full text search for the database, and disabled msftesql, I didn't suspect them. I got however an article from Microsoft support, showing me how I could test for catalogues not properly removed. So I discovered that there still existed an old catalogue, which I ,after and only after re-enabling full text search, were able to delete, since then my backup has worked”</p>
| [
{
"answer_id": 49073,
"author": "Booji Boy",
"author_id": 1433,
"author_profile": "https://Stackoverflow.com/users/1433",
"pm_score": 1,
"selected": false,
"text": "<p>Have you tried running process monitor and when it hangs and see what the underlying error is? Using process moniter you should be able to tell whick file/resource it waiting for/erroring on. </p>\n"
},
{
"answer_id": 168518,
"author": "Josef",
"author_id": 5581,
"author_profile": "https://Stackoverflow.com/users/5581",
"pm_score": 2,
"selected": false,
"text": "<p>Here's a suggestion. I don't have any corrupted databases but you can try this:</p>\n\n<pre><code>declare @t table (name nvarchar(128))\ninsert into @t select name from sys.databases --where is_fulltext_enabled \n\nwhile exists(SELECT * FROM @t)\nbegin\n declare @name nvarchar(128)\n select @name = name from @t\n declare @SQL nvarchar(4000)\n set @SQL = 'IF EXISTS(SELECT * FROM '+@name+'.sys.fulltext_catalogs) AND NOT EXISTS(SELECT * FROM sys.databases where is_fulltext_enabled=1 AND name='''+@name+''') PRINT ''' +@Name + ' Could be the culprit'''\n print @sql\n exec sp_sqlexec @SQL\n delete from @t where name = @name\nend\n</code></pre>\n\n<p>If it doesn't work, remove the filter checking <code>sys.databases</code>.</p>\n"
},
{
"answer_id": 2496808,
"author": "user146109",
"author_id": 146109,
"author_profile": "https://Stackoverflow.com/users/146109",
"pm_score": 1,
"selected": false,
"text": "<p>I had a similar problem with invalid full text catalog locations. \nThe server wouldn't bring all databases online at start-up. It would process databases in dbid order and get half way through and stop. Only the older DBs were brought online and the remainder were inaccessible. \nLooking at sysprocesses revealed a dozen or more processes with a waittype = 0x00CC , lastwaittype = MSSEARCH. MSSEARCH could not be stopped.\nThe problem was caused when we relocated the full text catalogs but entered the wrong path for one of them when running the alter database ... modifyfile command.\nThe solution was to disable MSSEARCH, reboot the server allowing all DBs to come online, find the offending database, take it offline, correct the file path using the alter database command, and bring the DB online. Then start MSSEARCH and set to automatic start-up.</p>\n"
}
] | 2008/09/05 | [
"https://Stackoverflow.com/questions/46365",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4803/"
] | We have a SQL Server 2005 SP2 machine running a large number of databases, all of which contain full-text catalogs. Whenever we try to drop one of these databases or rebuild a full-text index, the drop or rebuild process hangs indefinitely with a MSSEARCH wait type. The process can’t be killed, and a server reboot is required to get things running again. Based on a Microsoft forums post[1](http://forums.microsoft.com/MSDN/ShowPost.aspx?PostID=2681739&SiteID=1), it appears that the problem might be an improperly removed full-text catalog. Can anyone recommend a way to determine which catalog is causing the problem, without having to remove all of them?
[1](http://forums.microsoft.com/MSDN/ShowPost.aspx?PostID=2681739&SiteID=1) [<http://forums.microsoft.com/MSDN/ShowPost.aspx?PostID=2681739&SiteID=1]>
“Yes we did have full text catalogues in the database, but since I had disabled full text search for the database, and disabled msftesql, I didn't suspect them. I got however an article from Microsoft support, showing me how I could test for catalogues not properly removed. So I discovered that there still existed an old catalogue, which I ,after and only after re-enabling full text search, were able to delete, since then my backup has worked” | Here's a suggestion. I don't have any corrupted databases but you can try this:
```
declare @t table (name nvarchar(128))
insert into @t select name from sys.databases --where is_fulltext_enabled
while exists(SELECT * FROM @t)
begin
declare @name nvarchar(128)
select @name = name from @t
declare @SQL nvarchar(4000)
set @SQL = 'IF EXISTS(SELECT * FROM '+@name+'.sys.fulltext_catalogs) AND NOT EXISTS(SELECT * FROM sys.databases where is_fulltext_enabled=1 AND name='''+@name+''') PRINT ''' +@Name + ' Could be the culprit'''
print @sql
exec sp_sqlexec @SQL
delete from @t where name = @name
end
```
If it doesn't work, remove the filter checking `sys.databases`. |
46,377 | <p>What is the syntax for placing constraints on multiple types? The basic example:</p>
<pre><code>class Animal<SpeciesType> where SpeciesType : Species
</code></pre>
<p>I would like to place constraints on both types in the following definition such that <code>SpeciesType</code> must inherit from <code>Species</code> and <code>OrderType</code> must inherit from <code>Order</code>:</p>
<pre><code>class Animal<SpeciesType, OrderType>
</code></pre>
| [
{
"answer_id": 46384,
"author": "Darren Kopp",
"author_id": 77,
"author_profile": "https://Stackoverflow.com/users/77",
"pm_score": 7,
"selected": true,
"text": "<pre><code>public class Animal<SpeciesType,OrderType>\n where SpeciesType : Species\n where OrderType : Order\n{\n}\n</code></pre>\n"
},
{
"answer_id": 46390,
"author": "Ryan Lanciaux",
"author_id": 1385358,
"author_profile": "https://Stackoverflow.com/users/1385358",
"pm_score": 4,
"selected": false,
"text": "<p>You should be able to go :</p>\n\n<pre><code>class Animal<SpeciesType, OrderType>\n where SpeciesType : Species\n where OrderType : Order {\n}\n</code></pre>\n"
}
] | 2008/09/05 | [
"https://Stackoverflow.com/questions/46377",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/327/"
] | What is the syntax for placing constraints on multiple types? The basic example:
```
class Animal<SpeciesType> where SpeciesType : Species
```
I would like to place constraints on both types in the following definition such that `SpeciesType` must inherit from `Species` and `OrderType` must inherit from `Order`:
```
class Animal<SpeciesType, OrderType>
``` | ```
public class Animal<SpeciesType,OrderType>
where SpeciesType : Species
where OrderType : Order
{
}
``` |
46,385 | <p>What's the best way to delete all rows from a table in sql but to keep n number of rows on the top? </p>
| [
{
"answer_id": 46386,
"author": "Cory Foy",
"author_id": 4083,
"author_profile": "https://Stackoverflow.com/users/4083",
"pm_score": 7,
"selected": true,
"text": "<pre><code>DELETE FROM Table WHERE ID NOT IN (SELECT TOP 10 ID FROM Table)\n</code></pre>\n\n<p><strong>Edit:</strong> </p>\n\n<p>Chris brings up a good performance hit since the TOP 10 query would be run for each row. If this is a one time thing, then it may not be as big of a deal, but if it is a common thing, then I did look closer at it.</p>\n"
},
{
"answer_id": 46388,
"author": "Mark Biek",
"author_id": 305,
"author_profile": "https://Stackoverflow.com/users/305",
"pm_score": 2,
"selected": false,
"text": "<p>I don't know about other flavors but MySQL <a href=\"http://dev.mysql.com/doc/refman/5.0/en/delete.html\" rel=\"nofollow noreferrer\">DELETE</a> allows LIMIT.</p>\n\n<p>If you could order things so that the n rows you want to keep are at the bottom, then you could do a DELETE FROM table LIMIT tablecount-n.</p>\n\n<p><strong>Edit</strong></p>\n\n<p>Oooo. I think I like <a href=\"https://stackoverflow.com/questions/46385/delete-all-but-top-n-from-database-table-in-sql#46386\">Cory Foy's</a> answer better, assuming it works in your case. My way feels a little clunky by comparison.</p>\n"
},
{
"answer_id": 46393,
"author": "Riri",
"author_id": 298,
"author_profile": "https://Stackoverflow.com/users/298",
"pm_score": 0,
"selected": false,
"text": "<p>I would solve it using the technique below. The example expect an <em>article</em> table with an <em>id</em> on each row.</p>\n\n<pre><code>Delete article where id not in (select top 1000 id from article)\n</code></pre>\n\n<p>Edit: Too slow to answer my own question ...</p>\n"
},
{
"answer_id": 46404,
"author": "Chris Miller",
"author_id": 206,
"author_profile": "https://Stackoverflow.com/users/206",
"pm_score": 5,
"selected": false,
"text": "<p>I would select ID column(s) the set of rows that you want to keep into a temp table or table variable. Then delete all the rows that do not exist in the temp table. The syntax mentioned by another user:</p>\n\n<pre><code>DELETE FROM Table WHERE ID NOT IN (SELECT TOP 10 ID FROM Table)\n</code></pre>\n\n<p>Has a potential problem. The \"SELECT TOP 10\" query will be executed for each row in the table, which could be a huge performance hit. You want to avoid making the same query over and over again.</p>\n\n<p>This syntax should work, based what you listed as your original SQL statement:</p>\n\n<pre><code>create table #nuke(NukeID int)\n\ninsert into #nuke(Nuke) select top 1000 id from article\n\ndelete article where not exists (select 1 from nuke where Nukeid = id)\n\ndrop table #nuke\n</code></pre>\n"
},
{
"answer_id": 46505,
"author": "Shawn",
"author_id": 26,
"author_profile": "https://Stackoverflow.com/users/26",
"pm_score": 0,
"selected": false,
"text": "<p>Refactored?</p>\n\n<pre><code>Delete a From Table a Inner Join (\n Select Top (Select Count(tableID) From Table) - 10) \n From Table Order By tableID Desc\n) b On b.tableID = A.tableID\n</code></pre>\n\n<p><em>edit: tried them both in the query analyzer, current answer is fasted (damn order by...)</em></p>\n"
},
{
"answer_id": 46514,
"author": "SQLMenace",
"author_id": 740,
"author_profile": "https://Stackoverflow.com/users/740",
"pm_score": 0,
"selected": false,
"text": "<p>Better way would be to insert the rows you DO want into another table, drop the original table and then rename the new table so it has the same name as the old table</p>\n"
},
{
"answer_id": 46520,
"author": "Simurr",
"author_id": 3478,
"author_profile": "https://Stackoverflow.com/users/3478",
"pm_score": 4,
"selected": false,
"text": "<p>Future reference for those of use who don't use MS SQL.</p>\n\n<p>In PostgreSQL use <code>ORDER BY</code> and <code>LIMIT</code> instead of <code>TOP</code>.</p>\n\n<pre><code>DELETE FROM table\nWHERE id NOT IN (SELECT id FROM table ORDER BY id LIMIT n);\n</code></pre>\n\n<p>MySQL -- well...</p>\n\n<blockquote>\n <p><strong>Error</strong> -- This version of MySQL does not yet support 'LIMIT &\n IN/ALL/ANY/SOME subquery'</p>\n</blockquote>\n\n<p>Not yet I guess.</p>\n"
},
{
"answer_id": 509158,
"author": "Noah",
"author_id": 12113,
"author_profile": "https://Stackoverflow.com/users/12113",
"pm_score": 2,
"selected": false,
"text": "<p>This really is going to be language specific, but I would likely use something like the following for SQL server.</p>\n\n<pre><code>declare @n int\nSET @n = SELECT Count(*) FROM dTABLE;\nDELETE TOP (@n - 10 ) FROM dTable\n</code></pre>\n\n<p>if you don't care about the exact number of rows, there is always</p>\n\n<pre><code>DELETE TOP 90 PERCENT FROM dTABLE;\n</code></pre>\n"
},
{
"answer_id": 13226312,
"author": "Tim Wilson",
"author_id": 1734757,
"author_profile": "https://Stackoverflow.com/users/1734757",
"pm_score": 3,
"selected": false,
"text": "<p>I think using a virtual table would be much better than an IN-clause or temp table.</p>\n\n<pre><code>DELETE \n Product\nFROM\n Product\n LEFT OUTER JOIN\n (\n SELECT TOP 10\n Product.id\n FROM\n Product\n ) TopProducts ON Product.id = TopProducts.id\nWHERE\n TopProducts.id IS NULL\n</code></pre>\n"
},
{
"answer_id": 55834751,
"author": "Hrvoje",
"author_id": 2119941,
"author_profile": "https://Stackoverflow.com/users/2119941",
"pm_score": 3,
"selected": false,
"text": "<p>Here is how I did it. This method is faster and simpler:</p>\n<p><strong>Delete all but top n from database table in MS SQL using OFFSET command</strong></p>\n<pre><code>WITH CTE AS\n (\n SELECT ID\n FROM dbo.TableName\n ORDER BY ID DESC\n OFFSET 11 ROWS\n )\nDELETE CTE;\n</code></pre>\n<p>Replace <code>ID</code> with column by which you want to sort.\nReplace number after <code>OFFSET</code> with number of rows which you want to keep.\nChoose <code>DESC</code> or <code>ASC</code> - whatever suits your case.</p>\n"
},
{
"answer_id": 63455642,
"author": "clamchoda",
"author_id": 591285,
"author_profile": "https://Stackoverflow.com/users/591285",
"pm_score": 0,
"selected": false,
"text": "<p>I've got a trick to avoid executing the <code>TOP</code> expression for every row. We can combine <code>TOP</code> with <code>MAX</code> to get the <code>MaxId</code> we want to keep. Then we just delete everything greater than <code>MaxId</code>.</p>\n<pre><code>-- Declare Variable to hold the highest id we want to keep. \nDECLARE @MaxId as int = (\nSELECT MAX(temp.ID)\nFROM (SELECT TOP 10 ID FROM table ORDER BY ID ASC) temp\n)\n\n-- Delete anything greater than MaxId. If MaxId is null, there is nothing to delete.\nIF @MaxId IS NOT NULL\n DELETE FROM table WHERE ID > @MaxId\n</code></pre>\n<p>Note: It is important to use <code>ORDER BY</code> when declaring <code>MaxId</code> to ensure proper results are queried.</p>\n"
}
] | 2008/09/05 | [
"https://Stackoverflow.com/questions/46385",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/298/"
] | What's the best way to delete all rows from a table in sql but to keep n number of rows on the top? | ```
DELETE FROM Table WHERE ID NOT IN (SELECT TOP 10 ID FROM Table)
```
**Edit:**
Chris brings up a good performance hit since the TOP 10 query would be run for each row. If this is a one time thing, then it may not be as big of a deal, but if it is a common thing, then I did look closer at it. |
46,387 | <p>I am using a perl script to POST to Google Appengine application. I post a text file containing some XML using the -F option.</p>
<p><a href="http://www.cpan.org/authors/id/E/EL/ELIJAH/bget-1.1" rel="nofollow noreferrer">http://www.cpan.org/authors/id/E/EL/ELIJAH/bget-1.1</a></p>
<p>There is a version 1.2, already tested and get the same issue. The post looks something like this.</p>
<pre><code>Host: foo.appspot.com
User-Agent: lwp-request/1.38
Content-Type: text/plain
Content-Length: 202
<XML>
<BLAH>Hello World</BLAH>
</XML>
</code></pre>
<p>I have modified the example so the 202 isn't right, don't worry about that. On to the problem. The Content-Length matches the number of bytes on the file, however unless I manually increase the Content-Length it does not send all of the file, a few bytes get truncated. The number of bytes truncated is not the same for files of different sizes. I used the -r option on the script and I can see what it is sending and it is sending all of the file, but Google Appengine self.request.body shows that not everything is received. I think the solution is to get the right number for Content-Length and apparently it isn't as simple as number of bytes on the file or the perl script is mangling it somehow.</p>
<p>Update:
Thanks to Erickson for the right answer. I used printf to append characters to the end of the file and it always truncated exactly the number of lines in the file. I suppose I could figure out what is being added by iterating through every character on the server side but not worth it. This wasn't even answered over on the google groups set up for app engine!</p>
| [
{
"answer_id": 46405,
"author": "erickson",
"author_id": 3474,
"author_profile": "https://Stackoverflow.com/users/3474",
"pm_score": 3,
"selected": true,
"text": "<p>Is the number of extra bytes you need equal to the number of lines in the file? I ask because perhaps its possible that somehow carriage-returns are being introduced but not counted.</p>\n"
},
{
"answer_id": 46417,
"author": "Jagmal",
"author_id": 4406,
"author_profile": "https://Stackoverflow.com/users/4406",
"pm_score": 0,
"selected": false,
"text": "<p>How are you getting the number of bytes? .. By looking at the size of the file on the filesystem?</p>\n\n<p>You can use \"-s\" to get the size of the file.</p>\n\n<p>Or, if you want to do more, you may use <a href=\"http://search.cpan.org/~rgarcia/perl-5.10.0/lib/File/stat.pm\" rel=\"nofollow noreferrer\">File::Stat</a></p>\n"
},
{
"answer_id": 46551,
"author": "shelfoo",
"author_id": 3444,
"author_profile": "https://Stackoverflow.com/users/3444",
"pm_score": 1,
"selected": false,
"text": "<p>I've run into similar problems before.</p>\n\n<p>I assume you're using the length() function to determine the size of the file? If so, it;s likely the data that you're posting is UTF-8 encoded, instead of ASCII.</p>\n\n<p>To get the correct count you may need to add a \"use bytes;\" pragma to the top of your script, or wrap the length call in a block:</p>\n\n<pre><code>my $size;\ndo {use bytes; $size = length($file_data)}\n</code></pre>\n\n<p>From the perlfunc man page:</p>\n\n<p>\"Note the characters: if the EXPR is in Unicode, you will get the number of characters, not the number of bytes.\"</p>\n"
}
] | 2008/09/05 | [
"https://Stackoverflow.com/questions/46387",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4527/"
] | I am using a perl script to POST to Google Appengine application. I post a text file containing some XML using the -F option.
<http://www.cpan.org/authors/id/E/EL/ELIJAH/bget-1.1>
There is a version 1.2, already tested and get the same issue. The post looks something like this.
```
Host: foo.appspot.com
User-Agent: lwp-request/1.38
Content-Type: text/plain
Content-Length: 202
<XML>
<BLAH>Hello World</BLAH>
</XML>
```
I have modified the example so the 202 isn't right, don't worry about that. On to the problem. The Content-Length matches the number of bytes on the file, however unless I manually increase the Content-Length it does not send all of the file, a few bytes get truncated. The number of bytes truncated is not the same for files of different sizes. I used the -r option on the script and I can see what it is sending and it is sending all of the file, but Google Appengine self.request.body shows that not everything is received. I think the solution is to get the right number for Content-Length and apparently it isn't as simple as number of bytes on the file or the perl script is mangling it somehow.
Update:
Thanks to Erickson for the right answer. I used printf to append characters to the end of the file and it always truncated exactly the number of lines in the file. I suppose I could figure out what is being added by iterating through every character on the server side but not worth it. This wasn't even answered over on the google groups set up for app engine! | Is the number of extra bytes you need equal to the number of lines in the file? I ask because perhaps its possible that somehow carriage-returns are being introduced but not counted. |
46,425 | <p>I have a function that gets x(a value) and xs(a list) and removes all values that are bigger than x from the list. Well it doesn't work, can you tell me why?</p>
<pre><code>(defun biggerElems(x xs)
(let ((xst))
(dolist (elem xs)
(if (> x elem)
(setf xst (remove elem xs))))
xst))
</code></pre>
| [
{
"answer_id": 46437,
"author": "Ben Collins",
"author_id": 3279,
"author_profile": "https://Stackoverflow.com/users/3279",
"pm_score": 4,
"selected": true,
"text": "<p>I think it's this line that's not right:</p>\n\n<pre><code>(setf xst (remove elem xs))))\n</code></pre>\n\n<p>The first argument to <code>setf</code> is the place, followed by the value. It looks like you have it backwards (and <code>xst</code> is either <code>nil</code> or uninitialized).</p>\n\n<p>You might find it easier to do this:</p>\n\n<pre><code>(defun biggerElems (x xs)\n (remove-if (lambda (item) (> item x)) xs))\n</code></pre>\n"
},
{
"answer_id": 46474,
"author": "Alexander Stolz",
"author_id": 2450,
"author_profile": "https://Stackoverflow.com/users/2450",
"pm_score": 1,
"selected": false,
"text": "<p>It worked like that:</p>\n\n<pre><code>(defun filterBig (x xs)\n (remove-if (lambda (item) (> item x)) xs))\n</code></pre>\n\n<p>What was the '#' for? It didn't compile with it.</p>\n"
},
{
"answer_id": 46494,
"author": "Ben Collins",
"author_id": 3279,
"author_profile": "https://Stackoverflow.com/users/3279",
"pm_score": 0,
"selected": false,
"text": "<blockquote>\n <p>What was the '#' for? It didn't\n compile with it.</p>\n</blockquote>\n\n<p>Typo. Normally you refer to functions with <code>#'</code> (like <code>(remove-if #'oddp list)</code>), but when I was editing, I forgot to remove the '#'.</p>\n"
},
{
"answer_id": 46500,
"author": "Kyle Cronin",
"author_id": 658,
"author_profile": "https://Stackoverflow.com/users/658",
"pm_score": 1,
"selected": false,
"text": "<p>If you want to do this the Lisp Way, you could use recursion to return the new list:</p>\n\n<pre><code>(defun biggerElems (x xs)\n (cond ((null xs) NIL)\n ((< x (car xs))\n (biggerElems x (cdr xs)))\n (t\n (cons (car xs) (biggerElems x (cdr xs))))))\n</code></pre>\n\n<p>@Luís Oliveira</p>\n\n<p>This solution is to contrast with the one posted in the question. Had we needed to do something slightly more complicated it's important to be grounded in the recursive approach to manipulating lists. </p>\n"
},
{
"answer_id": 72912,
"author": "Bart",
"author_id": 9792,
"author_profile": "https://Stackoverflow.com/users/9792",
"pm_score": 2,
"selected": false,
"text": "<p>Most concise AFAIK:</p>\n\n<pre><code>(defun bigger-elements (x xs) (remove x xs :test #'<))\n</code></pre>\n\n<p>returning a fresh list, it removes all elements y from xs for which </p>\n\n<pre><code>(< y x)\n</code></pre>\n\n<p>or using the famous LOOP:</p>\n\n<pre><code>(defun bigger-elements-2 (x xs) \n (loop for e in xs\n unless (< e x)\n collect e))\n</code></pre>\n"
},
{
"answer_id": 118049,
"author": "Morikal",
"author_id": 18272,
"author_profile": "https://Stackoverflow.com/users/18272",
"pm_score": 1,
"selected": false,
"text": "<p>@Ben: It isn't the setf call that is wrong--the problem is that he is not updating xs.</p>\n\n<p>ie: xst is being set to xs with the element removed, but xs is not being updated. If a second element is to be removed, xst will have the first back in it.</p>\n\n<p>you would need to bind xst to xs, and replace the xs in the remove call with xst. This would then remove all elements x is bigger than. ie:</p>\n\n<pre><code>(defun biggerElems(x xs)\n (let ((xst xs))\n (dolist (elem xs)\n (when (> x elem)\n (setf xst (remove elem xst))))\n xst))\n</code></pre>\n\n<p>It might be slightly faster to set xst to (copy-list xs) and then use delete instead of remove (delete is destructive... depending on your implementation, it may be faster than remove. Since you are calling this multiple times, you may get better performance copying the list once and destructively deleting from it).</p>\n\n<p>Alternatively:</p>\n\n<pre><code>(defun bigger-elems (x xs) ; I prefer hyphen separated to camelCase... to each his own\n (loop for elem in xs when (<= x elem) collect elem))\n</code></pre>\n\n<p>Looking back over your original post, it is a little confusing... you say you remove all elements bigger than x, but your code looks like it is attempting to remove all elements x is bigger than. The solutions I wrote return all elements bigger than x (ie: remove all elements x is bigger than).</p>\n"
}
] | 2008/09/05 | [
"https://Stackoverflow.com/questions/46425",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2450/"
] | I have a function that gets x(a value) and xs(a list) and removes all values that are bigger than x from the list. Well it doesn't work, can you tell me why?
```
(defun biggerElems(x xs)
(let ((xst))
(dolist (elem xs)
(if (> x elem)
(setf xst (remove elem xs))))
xst))
``` | I think it's this line that's not right:
```
(setf xst (remove elem xs))))
```
The first argument to `setf` is the place, followed by the value. It looks like you have it backwards (and `xst` is either `nil` or uninitialized).
You might find it easier to do this:
```
(defun biggerElems (x xs)
(remove-if (lambda (item) (> item x)) xs))
``` |
46,454 | <p>I am working on a simple chat application using a System.Windows.Forms.WebBrowser Control to display the messages between the user and the recipient. How do I get the control to automatically scroll to the bottom every time I update the DocumentText of the control?</p>
| [
{
"answer_id": 46463,
"author": "Oded",
"author_id": 1583,
"author_profile": "https://Stackoverflow.com/users/1583",
"pm_score": 2,
"selected": false,
"text": "<p>I would use the AutoScrollOffset property and set it the the bottom left of the WebBrowser control, so something like:</p>\n\n<pre><code>webCtrl.AutoScrollOffset = new Point(0, webCtrl.Height);\n</code></pre>\n"
},
{
"answer_id": 46903,
"author": "David Mohundro",
"author_id": 4570,
"author_profile": "https://Stackoverflow.com/users/4570",
"pm_score": 2,
"selected": false,
"text": "<p>This is probably overkill, but you could also invoke script on the WebBrowser control and then use the scroll properties of the body tag. Or the scrollTo method of the window.</p>\n\n<p>To invoke script, the WebBrowser control has a Document property that represents the document object from the DOM. It has a method called InvokeScript that you can pass a string of JavaScript to be executed.</p>\n\n<p>But... if the AutoScrollOffset property works... yeah, I'd just use that instead of getting into JavaScript :)</p>\n"
},
{
"answer_id": 50264,
"author": "Ryan Lanciaux",
"author_id": 1385358,
"author_profile": "https://Stackoverflow.com/users/1385358",
"pm_score": 4,
"selected": true,
"text": "<p>Thanks guys -- I voted you both up but neither would work out for my situation. What I ended up doing was </p>\n\n<pre><code>webCtrl.Document.Window.ScrollTo(0, int.MaxValue);\n</code></pre>\n"
},
{
"answer_id": 22340865,
"author": "IlPADlI",
"author_id": 2430943,
"author_profile": "https://Stackoverflow.com/users/2430943",
"pm_score": 0,
"selected": false,
"text": "<p>You can keep scroll position on top, and insert new message on top.</p>\n\n<p>that don't need scroll to bottom, its look like twitter :)</p>\n\n<pre><code>user2:\n new message ← a new message is insert on top\n\nuser1:\n old message\n</code></pre>\n"
},
{
"answer_id": 40783280,
"author": "Chathuranga Abeyrathne",
"author_id": 7204504,
"author_profile": "https://Stackoverflow.com/users/7204504",
"pm_score": 0,
"selected": false,
"text": "<pre><code> public virtual void ScrollMessageIntoView()\n {\n\n System.Windows.Forms.Application.DoEvents();\n if (browser == null || browser.IsDisposed)\n return;\n\n if (browser.Document == null)\n {\n browser.Document.Window.ScrollTo(0,\n browser.Document.Body.ScrollRectangle.Height);\n }\n }\n</code></pre>\n"
}
] | 2008/09/05 | [
"https://Stackoverflow.com/questions/46454",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1385358/"
] | I am working on a simple chat application using a System.Windows.Forms.WebBrowser Control to display the messages between the user and the recipient. How do I get the control to automatically scroll to the bottom every time I update the DocumentText of the control? | Thanks guys -- I voted you both up but neither would work out for my situation. What I ended up doing was
```
webCtrl.Document.Window.ScrollTo(0, int.MaxValue);
``` |
46,482 | <p>Is there an easy way to read an entire Access file (.mdb) into a DataSet in .NET (specifically C# or VB)?</p>
<p>Or at least to get a list of tables from an access file so that I can loop through it and add them one at a time into a DataSet?</p>
| [
{
"answer_id": 46490,
"author": "Rob Cooper",
"author_id": 832,
"author_profile": "https://Stackoverflow.com/users/832",
"pm_score": 2,
"selected": false,
"text": "<p>You should be able to access it using an <a href=\"http://msdn.microsoft.com/en-us/library/system.data.oledb.oledbconnection.aspx\" rel=\"nofollow noreferrer\">OleDbConnection</a>.</p>\n<p><a href=\"http://www.csharphelp.com/archives/archive70.html\" rel=\"nofollow noreferrer\">Heres</a> a tut on DB access using it for MS Access files.</p>\n<p>In terms of getting the table names, back in my VB6 days I always used ADOX, not sure how they do this in .NET now.. Although I know there is a system table in the access file - wanna say "mso...". I google!</p>\n<h3>EDIT</h3>\n<p>Ah ha! <em>msysobjects</em> !! xD</p>\n"
},
{
"answer_id": 46492,
"author": "Dillie-O",
"author_id": 71,
"author_profile": "https://Stackoverflow.com/users/71",
"pm_score": 2,
"selected": false,
"text": "<p><a href=\"http://msdn.microsoft.com/en-us/library/ms971485.aspx\" rel=\"nofollow noreferrer\">MSDN</a> has an article on how to use ADO.NET to connect and edit records in an Access database. Once your OleDB connection is made, you can easily create your DataReader/DataAdapter and process as needed.</p>\n\n<p>EDIT: Gah! Curse you Rob and your god-like typing abilities!!! 8^D</p>\n"
},
{
"answer_id": 46526,
"author": "jerhinesmith",
"author_id": 1108,
"author_profile": "https://Stackoverflow.com/users/1108",
"pm_score": 4,
"selected": true,
"text": "<p>Thanks for the suggestions. I was able to use those samples to put together this code, which seems to achieve what I'm looking for.</p>\n\n<pre><code>Using cn = New OleDbConnection(connectionstring)\n cn.Open()\n Dim ds As DataSet = new DataSet()\n\n Dim Schema As DataTable = cn.GetOleDbSchemaTable(OleDbSchemaGuid.Tables, New Object() {Nothing, Nothing, Nothing, \"TABLE\"})\n For i As Integer = 0 To Schema.Rows.Count - 1\n Dim dt As DataTable = New DataTable(Schema.Rows(i)!TABLE_NAME.ToString())\n\n Using adapter = New OleDbDataAdapter(\"SELECT * FROM \" + Schema.Rows(i)!TABLE_NAME.ToString(), cn)\n adapter.Fill(dt)\n End Using\n\n ds.Tables.Add(dt)\n Next i\nEnd Using\n</code></pre>\n"
},
{
"answer_id": 46531,
"author": "Fionnuala",
"author_id": 2548,
"author_profile": "https://Stackoverflow.com/users/2548",
"pm_score": 0,
"selected": false,
"text": "<p>There is a discussion on this point in <a href=\"http://forum.lessthandot.com/viewtopic.php?f=95&t=1262\" rel=\"nofollow noreferrer\">Less Than Dot</a>. Here is one example of code from the discussion.</p>\n\n<pre><code> public DataTable GetColumns(string tableName)\n {\n string[] restrictions = new string[4];\n restrictions[2] = tableName;\n\n _connDb.Open();\n\n DataTable mDT = _connDb.GetSchema(\"Columns\", restrictions);\n\n _connDb.Close();\n\n return mDT;\n }\n</code></pre>\n"
},
{
"answer_id": 67510,
"author": "David-W-Fenton",
"author_id": 9787,
"author_profile": "https://Stackoverflow.com/users/9787",
"pm_score": 0,
"selected": false,
"text": "<p>Your original question as worded is nonsense:</p>\n\n<blockquote>\n <p>Is there an easy way to read an entire Access file (.mdb) into...</p>\n</blockquote>\n\n<p>You certainly <em>don't</em> want the entire contents of the MDB file. What you want is the contents of your data tables that are stored in the MDB. Keep in mind that you don't want the contents of the system tables, either.</p>\n\n<p>The key point:</p>\n\n<p>You're asking about JET, not about ACCESS.</p>\n\n<p>Jet is the database engine that ships as the default data store of Access (and in which Access's own objects are stored). But \"Access\" means something much more than just the data tables.</p>\n\n<p>Whenever you ask a question and confuse Access and Jet, you will likely get at least some unuseful answers.</p>\n\n<p>And you'll get scolded by the likes of me, because developers really should know better than to obfuscate crucial distinctions.</p>\n"
}
] | 2008/09/05 | [
"https://Stackoverflow.com/questions/46482",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1108/"
] | Is there an easy way to read an entire Access file (.mdb) into a DataSet in .NET (specifically C# or VB)?
Or at least to get a list of tables from an access file so that I can loop through it and add them one at a time into a DataSet? | Thanks for the suggestions. I was able to use those samples to put together this code, which seems to achieve what I'm looking for.
```
Using cn = New OleDbConnection(connectionstring)
cn.Open()
Dim ds As DataSet = new DataSet()
Dim Schema As DataTable = cn.GetOleDbSchemaTable(OleDbSchemaGuid.Tables, New Object() {Nothing, Nothing, Nothing, "TABLE"})
For i As Integer = 0 To Schema.Rows.Count - 1
Dim dt As DataTable = New DataTable(Schema.Rows(i)!TABLE_NAME.ToString())
Using adapter = New OleDbDataAdapter("SELECT * FROM " + Schema.Rows(i)!TABLE_NAME.ToString(), cn)
adapter.Fill(dt)
End Using
ds.Tables.Add(dt)
Next i
End Using
``` |
46,483 | <p>What are the differences between <code>htmlspecialchars()</code> and <code>htmlentities()</code>. When should I use one or the other?</p>
| [
{
"answer_id": 46491,
"author": "Thomas Owens",
"author_id": 572,
"author_profile": "https://Stackoverflow.com/users/572",
"pm_score": 10,
"selected": true,
"text": "<p>From the PHP documentation for <a href=\"http://us2.php.net/htmlentities\" rel=\"noreferrer\">htmlentities</a>:</p>\n\n<blockquote>\n <p>This function is identical to <code>htmlspecialchars()</code> in all ways, except with <code>htmlentities()</code>, all characters which have HTML character entity equivalents are translated into these entities. </p>\n</blockquote>\n\n<p>From the PHP documentation for <a href=\"http://us.php.net/htmlspecialchars\" rel=\"noreferrer\">htmlspecialchars</a>:</p>\n\n<blockquote>\n <p>Certain characters have special significance in HTML, and should be represented by HTML entities if they are to preserve their meanings. This function returns a string with some of these conversions made; the translations made are those most useful for everyday web programming. If you require all HTML character entities to be translated, use <code>htmlentities()</code> instead.</p>\n</blockquote>\n\n<p>The difference is what gets encoded. The choices are everything (entities) or \"special\" characters, like ampersand, double and single quotes, less than, and greater than (specialchars).</p>\n\n<p>I prefer to use <code>htmlspecialchars</code> whenever possible.</p>\n\n<p>For example:</p>\n\n <pre class=\"lang-php prettyprint-override\"><code> echo htmlentities('<Il était une fois un être>.');\n // Output: &lt;Il &eacute;tait une fois un &ecirc;tre&gt;.\n // ^^^^^^^^ ^^^^^^^\n\n echo htmlspecialchars('<Il était une fois un être>.');\n // Output: &lt;Il était une fois un être&gt;.\n // ^ ^\n</code></pre>\n"
},
{
"answer_id": 46523,
"author": "cic",
"author_id": 4771,
"author_profile": "https://Stackoverflow.com/users/4771",
"pm_score": 3,
"selected": false,
"text": "<p>You probably want to use some Unicode character encoding, for example <a href=\"http://en.wikipedia.org/wiki/UTF-8\" rel=\"noreferrer\">UTF-8</a>, and htmlspecialchars. Because there isn't <em>any</em> need to generate \"HTML entities\" for \"all [the] applicable characters\" (that is what htmlentities does according to the documentation) if it's already in your character set.</p>\n"
},
{
"answer_id": 3614330,
"author": "Artefacto",
"author_id": 127724,
"author_profile": "https://Stackoverflow.com/users/127724",
"pm_score": 7,
"selected": false,
"text": "<p>Because:</p>\n\n<ul>\n<li>Sometimes you're writing XML data, and you can't use HTML entities in a XML file.</li>\n<li>Because <code>htmlentities</code> substitutes more characters than <code>htmlspecialchars</code>. This is unnecessary, makes the PHP script less efficient and the resulting HTML code less readable.</li>\n</ul>\n\n<p><code>htmlentities</code> is only necessary if your pages use encodings such as ASCII or LATIN-1 instead of UTF-8 and you're handling data with an encoding different from the page's.</p>\n"
},
{
"answer_id": 3614333,
"author": "grossvogel",
"author_id": 14957,
"author_profile": "https://Stackoverflow.com/users/14957",
"pm_score": 4,
"selected": false,
"text": "<p><code>htmlspecialchars ()</code> does the minimum amount of encoding to ensure that your string is not parsed as HTML. This leaves your string more human-readable than it would be if you used <code>htmlentities ()</code> to encode absolutely everything that has an encoding.</p>\n"
},
{
"answer_id": 3614344,
"author": "Arseni Mourzenko",
"author_id": 240613,
"author_profile": "https://Stackoverflow.com/users/240613",
"pm_score": 9,
"selected": false,
"text": "<p><code>htmlspecialchars</code> may be used:</p>\n\n<ol>\n<li><p>When there is no need to encode all characters which have their HTML equivalents.</p>\n\n<p>If you know that the page encoding match the text special symbols, why would you use <code>htmlentities</code>? <code>htmlspecialchars</code> is much straightforward, and produce less code to send to the client.</p>\n\n<p>For example:</p>\n\n<pre class=\"lang-php prettyprint-override\"><code>echo htmlentities('<Il était une fois un être>.');\n// Output: &lt;Il &eacute;tait une fois un &ecirc;tre&gt;.\n// ^^^^^^^^ ^^^^^^^\n\necho htmlspecialchars('<Il était une fois un être>.');\n// Output: &lt;Il était une fois un être&gt;.\n// ^ ^\n</code></pre>\n\n<p>The second one is shorter, and does not cause any problems if ISO-8859-1 charset is set.</p></li>\n<li><p>When the data will be processed not only through a browser (to avoid decoding HTML entities),</p></li>\n<li><p>If the output is XML (see <a href=\"https://stackoverflow.com/a/3614330/240613\">the answer by Artefacto</a>).</p></li>\n</ol>\n"
},
{
"answer_id": 5570629,
"author": "Eric Hogue",
"author_id": 4137,
"author_profile": "https://Stackoverflow.com/users/4137",
"pm_score": 4,
"selected": false,
"text": "<p>I just found out about the <a href=\"http://www.php.net/manual/en/function.get-html-translation-table.php\" rel=\"noreferrer\"><code>get_html_translation_table</code></a> function. You pass it <code>HTML_ENTITIES</code> or <code>HTML_SPECIALCHARS</code> and it returns an array with the characters that will be encoded and how they will be encoded. </p>\n"
},
{
"answer_id": 12079371,
"author": "Kmeixner",
"author_id": 1598979,
"author_profile": "https://Stackoverflow.com/users/1598979",
"pm_score": 4,
"selected": false,
"text": "<p>You should use <code>htmlspecialchars($strText, ENT_QUOTES)</code> when you just want your string to be XML and HTML safe:</p>\n\n<p>For example, encode </p>\n\n<ul>\n<li>& to &amp;</li>\n<li>" to &quot;</li>\n<li>< to &lt;</li>\n<li>> to &gt;</li>\n<li>' to &#039;</li>\n</ul>\n\n<p>However, if you also have additional characters that are <a href=\"http://en.wikipedia.org/wiki/Unicode\" rel=\"noreferrer\">Unicode</a> or uncommon symbols in your text then you should use htmlentities() to ensure they show up properly in your HTML page.</p>\n\n<p>Notes: </p>\n\n<ul>\n<li>' will only be encoded by htmlspecialchars() to &#039; if the ENT_QUOTES option is passed in. &#039; is safer to use then &apos; since older versions of Internet Explorer do not support the &apos; entity.</li>\n<li>Technically, > does not need to be encoded as per the XML specification, but it is usually encoded too for consistency with the requirement of < being encoded.</li>\n</ul>\n"
},
{
"answer_id": 24351380,
"author": "Berky",
"author_id": 3500977,
"author_profile": "https://Stackoverflow.com/users/3500977",
"pm_score": 7,
"selected": false,
"text": "<p>This is being encoded with <code>htmlentities</code>. </p>\n\n<p><code>implode( \"\\t\", array_values( get_html_translation_table( HTML_ENTITIES ) ) )</code>:</p>\n\n<blockquote>\n <p>\" & < ><br>\n ¡ ¢ £ ¤ ¥ ¦ § ¨ © ª « ¬ ® ¯ ° ± ² ³ ´ µ ¶ · ¸ ¹ º » ¼ ½ ¾ ¿ À Á Â Ã Ä Å Æ Ç È É Ê Ë\n Ì Í Î Ï Ð Ñ Ò Ó Ô Õ Ö × Ø Ù Ú Û Ü Ý Þ ß à á â ã ä å æ ç è é ê ë ì í î ï ð ñ ò ó ô õ ö ÷ ø ù ú û ü ý þ ÿ Œ\n œ Š š Ÿ ƒ ˆ ˜ Α Β Γ Δ Ε Ζ Η Θ Ι Κ Λ Μ Ν Ξ Ο Π Ρ Σ Τ Υ Φ Χ Ψ Ω α β γ δ ε ζ η θ ι κ λ μ ν ξ ο π ρ ς σ τ\n υ φ χ ψ ω ϑ ϒ ϖ – — ‘ ’ ‚ “ ” „ † ‡ • … ‰ ′ ″ ‹ › ‾ ⁄ € ℑ ℘ ℜ ™ ℵ ← ↑ → ↓ ↔ ↵ ⇐ ⇑ ⇒ ⇓ ⇔\n ∀ ∂ ∃ ∅ ∇ ∈ ∉ ∋ ∏ ∑ − ∗ √ ∝ ∞ ∠ ∧ ∨ ∩ ∪ ∫ ∴ ∼ ≅ ≈ ≠ ≡ ≤ ≥ ⊂ ⊃ ⊄ ⊆ ⊇ ⊕ ⊗ ⊥ ⋅ ⌈ ⌉ ⌊ ⌋ ⟨\n ⟩ ◊ ♠ ♣ ♥ ♦</p>\n</blockquote>\n\n<p>This is being encoded with <code>htmlspecialchars</code>.</p>\n\n<p><code>implode( \"\\t\", array_values( get_html_translation_table( HTML_SPECIALCHARS ) ) )</code>:</p>\n\n<blockquote>\n <p>\" & < ></p>\n</blockquote>\n"
},
{
"answer_id": 30159066,
"author": "Joko Wandiro",
"author_id": 515536,
"author_profile": "https://Stackoverflow.com/users/515536",
"pm_score": 3,
"selected": false,
"text": "<p>htmlentities — Convert all applicable characters to HTML entities.</p>\n\n<p>htmlspecialchars — Convert special characters to HTML entities.</p>\n\n<p>The translations performed translation characters on the below: </p>\n\n<ul>\n<li>'&' (ampersand) becomes '&amp;' </li>\n<li>'\"' (double quote) becomes '&quot;' when ENT_NOQUOTES is not set. </li>\n<li>\"'\" (single quote) becomes '&#039;' (or ') only when ENT_QUOTES is set. </li>\n<li>'<' (less than) becomes '&lt;' </li>\n<li>'>' (greater than) becomes '&gt;'</li>\n</ul>\n\n<p>You can check the following code for more information about what's htmlentities and htmlspecialchars:</p>\n\n<p><a href=\"https://gist.github.com/joko-wandiro/f5c935708d9c37d8940b\" rel=\"noreferrer\">https://gist.github.com/joko-wandiro/f5c935708d9c37d8940b</a></p>\n"
},
{
"answer_id": 35146143,
"author": "learn2reid",
"author_id": 2141301,
"author_profile": "https://Stackoverflow.com/users/2141301",
"pm_score": 2,
"selected": false,
"text": "<p>One small example, I needed to have 2 client names indexed in a function:</p>\n\n<pre><code>[1] => Altisoxxce Soluxxons S.à r.l.\n[5] => Joxxson & Joxxson\n</code></pre>\n\n<p>I originally <code>$term = get_term_by('name', htmlentities($name), 'client');</code> which resulted in term names that only included the ampersand array item (&) but not the accented item. But when I changed the variable setting to <code>htmlspecialchars</code> both were able to run through the function. Hope this helps!</p>\n"
},
{
"answer_id": 41745526,
"author": "Anson Hwang",
"author_id": 7033914,
"author_profile": "https://Stackoverflow.com/users/7033914",
"pm_score": 1,
"selected": false,
"text": "<pre><code>**HTML Character Entity Reference Chart at W3.org**\n</code></pre>\n\n<p><a href=\"https://dev.w3.org/html5/html-author/charref\" rel=\"nofollow noreferrer\">https://dev.w3.org/html5/html-author/charref</a></p>\n\n<pre><code>&Tab;\n&NewLine;\n!\n&excl;\n\"\n&quot; &QUOT;\n#\n&num;\n$\n&dollar;\n%\n&percnt;\n&\n&amp; &AMP;\n'\n&apos;\n(\n&lpar;\n)\n&rpar;\n*\n&ast; &midast;\n+\n&plus;\n,\n&comma;\n.\n&period;\n/\n&sol;\n:\n&colon;\n;\n&semi;\n<\n&lt; &LT;\n=\n&equals;\n>\n&gt; &GT;\n?\n&quest;\n@\n&commat;\n[\n&lsqb; &lbrack;\n\\\n&bsol;\n]\n&rsqb; &rbrack;\n^\n&Hat;\n_\n&lowbar;\n`\n&grave; &DiacriticalGrave;\n{\n&lcub; &lbrace;\n|\n&verbar; &vert; &VerticalLine;\n}\n&rcub; &rbrace;\n\n&nbsp; &NonBreakingSpace;\n¡\n&iexcl;\n¢\n&cent;\n£\n&pound;\n¤\n&curren;\n¥\n&yen;\n¦\n&brvbar;\n§\n&sect;\n¨\n&Dot; &die; &DoubleDot; &uml;\n©\n&copy; &COPY;\nª\n&ordf;\n«\n&laquo;\n¬\n&not;\n&shy;\n®\n&reg; &circledR; &REG;\n¯\n&macr; &OverBar; &strns;\n°\n&deg;\n±\n&plusmn; &pm; &PlusMinus;\n²\n&sup2;\n³\n&sup3;\n´\n&acute; &DiacriticalAcute;\nµ\n&micro;\n¶\n&para;\n·\n&middot; &centerdot; &CenterDot;\n¸\n&cedil; &Cedilla;\n¹\n&sup1;\nº\n&ordm;\n»\n&raquo;\n¼\n&frac14;\n½\n&frac12; &half;\n¾\n&frac34;\n¿\n&iquest;\nÀ\n&Agrave;\nÁ\n&Aacute;\nÂ\n&Acirc;\nÃ\n&Atilde;\nÄ\n&Auml;\nÅ\n&Aring;\nÆ\n&AElig;\nÇ\n&Ccedil;\nÈ\n&Egrave;\nÉ\n&Eacute;\nÊ\n&Ecirc;\nË\n&Euml;\nÌ\n&Igrave;\nÍ\n&Iacute;\nÎ\n&Icirc;\nÏ\n&Iuml;\nÐ\n&ETH;\nÑ\n&Ntilde;\nÒ\n&Ograve;\nÓ\n&Oacute;\nÔ\n&Ocirc;\nÕ\n&Otilde;\nÖ\n&Ouml;\n×\n&times;\nØ\n&Oslash;\nÙ\n&Ugrave;\nÚ\n&Uacute;\nÛ\n&Ucirc;\nÜ\n&Uuml;\nÝ\n&Yacute;\nÞ\n&THORN;\nß\n&szlig;\nà\n&agrave;\ná\n&aacute;\nâ\n&acirc;\nã\n&atilde;\nä\n&auml;\nå\n&aring;\næ\n&aelig;\nç\n&ccedil;\nè\n&egrave;\né\n&eacute;\nê\n&ecirc;\në\n&euml;\nì\n&igrave;\ní\n&iacute;\nî\n&icirc;\nï\n&iuml;\nð\n&eth;\nñ\n&ntilde;\nò\n&ograve;\nó\n&oacute;\nô\n&ocirc;\nõ\n&otilde;\nö\n&ouml;\n÷\n&divide; &div;\nø\n&oslash;\nù\n&ugrave;\nú\n&uacute;\nû\n&ucirc;\nü\n&uuml;\ný\n&yacute;\nþ\n&thorn;\nÿ\n&yuml;\nĀ\n&Amacr;\nā\n&amacr;\nĂ\n&Abreve;\nă\n&abreve;\nĄ\n&Aogon;\ną\n&aogon;\nĆ\n&Cacute;\nć\n&cacute;\nĈ\n&Ccirc;\nĉ\n&ccirc;\nĊ\n&Cdot;\nċ\n&cdot;\nČ\n&Ccaron;\nč\n&ccaron;\nĎ\n&Dcaron;\nď\n&dcaron;\nĐ\n&Dstrok;\nđ\n&dstrok;\nĒ\n&Emacr;\nē\n&emacr;\nĖ\n&Edot;\nė\n&edot;\nĘ\n&Eogon;\nę\n&eogon;\nĚ\n&Ecaron;\ně\n&ecaron;\nĜ\n&Gcirc;\nĝ\n&gcirc;\nĞ\n&Gbreve;\nğ\n&gbreve;\nĠ\n&Gdot;\nġ\n&gdot;\nĢ\n&Gcedil;\nĤ\n&Hcirc;\nĥ\n&hcirc;\nĦ\n&Hstrok;\nħ\n&hstrok;\nĨ\n&Itilde;\nĩ\n&itilde;\nĪ\n&Imacr;\nī\n&imacr;\nĮ\n&Iogon;\nį\n&iogon;\nİ\n&Idot;\nı\n&imath; &inodot;\nIJ\n&IJlig;\nij\n&ijlig;\nĴ\n&Jcirc;\nĵ\n&jcirc;\nĶ\n&Kcedil;\nķ\n&kcedil;\nĸ\n&kgreen;\nĹ\n&Lacute;\nĺ\n&lacute;\nĻ\n&Lcedil;\nļ\n&lcedil;\nĽ\n&Lcaron;\nľ\n&lcaron;\nĿ\n&Lmidot;\nŀ\n&lmidot;\nŁ\n&Lstrok;\nł\n&lstrok;\nŃ\n&Nacute;\nń\n&nacute;\nŅ\n&Ncedil;\nņ\n&ncedil;\nŇ\n&Ncaron;\nň\n&ncaron;\nʼn\n&napos;\nŊ\n&ENG;\nŋ\n&eng;\nŌ\n&Omacr;\nō\n&omacr;\nŐ\n&Odblac;\nő\n&odblac;\nŒ\n&OElig;\nœ\n&oelig;\nŔ\n&Racute;\nŕ\n&racute;\nŖ\n&Rcedil;\nŗ\n&rcedil;\nŘ\n&Rcaron;\nř\n&rcaron;\nŚ\n&Sacute;\nś\n&sacute;\nŜ\n&Scirc;\nŝ\n&scirc;\nŞ\n&Scedil;\nş\n&scedil;\nŠ\n&Scaron;\nš\n&scaron;\nŢ\n&Tcedil;\nţ\n&tcedil;\nŤ\n&Tcaron;\nť\n&tcaron;\nŦ\n&Tstrok;\nŧ\n&tstrok;\nŨ\n&Utilde;\nũ\n&utilde;\nŪ\n&Umacr;\nū\n&umacr;\nŬ\n&Ubreve;\nŭ\n&ubreve;\nŮ\n&Uring;\nů\n&uring;\nŰ\n&Udblac;\nű\n&udblac;\nŲ\n&Uogon;\nų\n&uogon;\nŴ\n&Wcirc;\nŵ\n&wcirc;\nŶ\n&Ycirc;\nŷ\n&ycirc;\nŸ\n&Yuml;\nŹ\n&Zacute;\nź\n&zacute;\nŻ\n&Zdot;\nż\n&zdot;\nŽ\n&Zcaron;\nž\n&zcaron;\nƒ\n&fnof;\nƵ\n&imped;\nǵ\n&gacute;\nȷ\n&jmath;\nˆ\n&circ;\nˇ\n&caron; &Hacek;\n˘\n&breve; &Breve;\n˙\n&dot; &DiacriticalDot;\n˚\n&ring;\n˛\n&ogon;\n˜\n&tilde; &DiacriticalTilde;\n˝\n&dblac; &DiacriticalDoubleAcute;\n̑\n&DownBreve;\n̲\n&UnderBar;\nΑ\n&Alpha;\nΒ\n&Beta;\nΓ\n&Gamma;\nΔ\n&Delta;\nΕ\n&Epsilon;\nΖ\n&Zeta;\nΗ\n&Eta;\nΘ\n&Theta;\nΙ\n&Iota;\nΚ\n&Kappa;\nΛ\n&Lambda;\nΜ\n&Mu;\nΝ\n&Nu;\nΞ\n&Xi;\nΟ\n&Omicron;\nΠ\n&Pi;\nΡ\n&Rho;\nΣ\n&Sigma;\nΤ\n&Tau;\nΥ\n&Upsilon;\nΦ\n&Phi;\nΧ\n&Chi;\nΨ\n&Psi;\nΩ\n&Omega;\nα\n&alpha;\nβ\n&beta;\nγ\n&gamma;\nδ\n&delta;\nε\n&epsiv; &varepsilon; &epsilon;\nζ\n&zeta;\nη\n&eta;\nθ\n&theta;\nι\n&iota;\nκ\n&kappa;\nλ\n&lambda;\nμ\n&mu;\nν\n&nu;\nξ\n&xi;\nο\n&omicron;\nπ\n&pi;\nρ\n&rho;\nς\n&sigmav; &varsigma; &sigmaf;\nσ\n&sigma;\nτ\n&tau;\nυ\n&upsi; &upsilon;\nφ\n&phi; &phiv; &varphi;\nχ\n&chi;\nψ\n&psi;\nω\n&omega;\nϑ\n&thetav; &vartheta; &thetasym;\nϒ\n&Upsi; &upsih;\nϕ\n&straightphi;\nϖ\n&piv; &varpi;\nϜ\n&Gammad;\nϝ\n&gammad; &digamma;\nϰ\n&kappav; &varkappa;\nϱ\n&rhov; &varrho;\nϵ\n&epsi; &straightepsilon;\n϶\n&bepsi; &backepsilon;\nЁ\n&IOcy;\nЂ\n&DJcy;\nЃ\n&GJcy;\nЄ\n&Jukcy;\nЅ\n&DScy;\nІ\n&Iukcy;\nЇ\n&YIcy;\nЈ\n&Jsercy;\nЉ\n&LJcy;\nЊ\n&NJcy;\nЋ\n&TSHcy;\nЌ\n&KJcy;\nЎ\n&Ubrcy;\nЏ\n&DZcy;\nА\n&Acy;\nБ\n&Bcy;\nВ\n&Vcy;\nГ\n&Gcy;\nД\n&Dcy;\nЕ\n&IEcy;\nЖ\n&ZHcy;\nЗ\n&Zcy;\nИ\n&Icy;\nЙ\n&Jcy;\nК\n&Kcy;\nЛ\n&Lcy;\nМ\n&Mcy;\nН\n&Ncy;\nО\n&Ocy;\nП\n&Pcy;\nР\n&Rcy;\nС\n&Scy;\nТ\n&Tcy;\nУ\n&Ucy;\nФ\n&Fcy;\nХ\n&KHcy;\nЦ\n&TScy;\nЧ\n&CHcy;\nШ\n&SHcy;\nЩ\n&SHCHcy;\nЪ\n&HARDcy;\nЫ\n&Ycy;\nЬ\n&SOFTcy;\nЭ\n&Ecy;\nЮ\n&YUcy;\nЯ\n&YAcy;\nа\n&acy;\nб\n&bcy;\nв\n&vcy;\nг\n&gcy;\nд\n&dcy;\nе\n&iecy;\nж\n&zhcy;\nз\n&zcy;\nи\n&icy;\nй\n&jcy;\nк\n&kcy;\nл\n&lcy;\nм\n&mcy;\nн\n&ncy;\nо\n&ocy;\nп\n&pcy;\nр\n&rcy;\nс\n&scy;\nт\n&tcy;\nу\n&ucy;\nф\n&fcy;\nх\n&khcy;\nц\n&tscy;\nч\n&chcy;\nш\n&shcy;\nщ\n&shchcy;\nъ\n&hardcy;\nы\n&ycy;\nь\n&softcy;\nэ\n&ecy;\nю\n&yucy;\nя\n&yacy;\nё\n&iocy;\nђ\n&djcy;\nѓ\n&gjcy;\nє\n&jukcy;\nѕ\n&dscy;\nі\n&iukcy;\nї\n&yicy;\nј\n&jsercy;\nљ\n&ljcy;\nњ\n&njcy;\nћ\n&tshcy;\nќ\n&kjcy;\nў\n&ubrcy;\nџ\n&dzcy;\n \n&ensp;\n \n&emsp;\n \n&emsp13;\n \n&emsp14;\n \n&numsp;\n \n&puncsp;\n \n&thinsp; &ThinSpace;\n \n&hairsp; &VeryThinSpace;\n\n&ZeroWidthSpace; &NegativeVeryThinSpace; &NegativeThinSpace; &NegativeMediumSpace; &NegativeThickSpace;\n\n&zwnj;\n\n&zwj;\n\n&lrm;\n\n&rlm;\n‐\n&hyphen; &dash;\n–\n&ndash;\n—\n&mdash;\n―\n&horbar;\n‖\n&Verbar; &Vert;\n‘\n&lsquo; &OpenCurlyQuote;\n’\n&rsquo; &rsquor; &CloseCurlyQuote;\n‚\n&lsquor; &sbquo;\n“\n&ldquo; &OpenCurlyDoubleQuote;\n”\n&rdquo; &rdquor; &CloseCurlyDoubleQuote;\n„\n&ldquor; &bdquo;\n†\n&dagger;\n‡\n&Dagger; &ddagger;\n•\n&bull; &bullet;\n‥\n&nldr;\n…\n&hellip; &mldr;\n‰\n&permil;\n‱\n&pertenk;\n′\n&prime;\n″\n&Prime;\n‴\n&tprime;\n‵\n&bprime; &backprime;\n‹\n&lsaquo;\n›\n&rsaquo;\n‾\n&oline;\n⁁\n&caret;\n⁃\n&hybull;\n⁄\n&frasl;\n⁏\n&bsemi;\n⁗\n&qprime;\n \n&MediumSpace;\n\n&NoBreak;\n\n&ApplyFunction; &af;\n\n&InvisibleTimes; &it;\n\n&InvisibleComma; &ic;\n€\n&euro;\n⃛\n&tdot; &TripleDot;\n⃜\n&DotDot;\nℂ\n&Copf; &complexes;\n℅\n&incare;\nℊ\n&gscr;\nℋ\n&hamilt; &HilbertSpace; &Hscr;\nℌ\n&Hfr; &Poincareplane;\nℍ\n&quaternions; &Hopf;\nℎ\n&planckh;\nℏ\n&planck; &hbar; &plankv; &hslash;\nℐ\n&Iscr; &imagline;\nℑ\n&image; &Im; &imagpart; &Ifr;\nℒ\n&Lscr; &lagran; &Laplacetrf;\nℓ\n&ell;\nℕ\n&Nopf; &naturals;\n№\n&numero;\n℗\n&copysr;\n℘\n&weierp; &wp;\nℙ\n&Popf; &primes;\nℚ\n&rationals; &Qopf;\nℛ\n&Rscr; &realine;\nℜ\n&real; &Re; &realpart; &Rfr;\nℝ\n&reals; &Ropf;\n℞\n&rx;\n™\n&trade; &TRADE;\nℤ\n&integers; &Zopf;\nΩ\n&ohm;\n℧\n&mho;\nℨ\n&Zfr; &zeetrf;\n℩\n&iiota;\nÅ\n&angst;\nℬ\n&bernou; &Bernoullis; &Bscr;\nℭ\n&Cfr; &Cayleys;\nℯ\n&escr;\nℰ\n&Escr; &expectation;\nℱ\n&Fscr; &Fouriertrf;\nℳ\n&phmmat; &Mellintrf; &Mscr;\nℴ\n&order; &orderof; &oscr;\nℵ\n&alefsym; &aleph;\nℶ\n&beth;\nℷ\n&gimel;\nℸ\n&daleth;\nⅅ\n&CapitalDifferentialD; &DD;\nⅆ\n&DifferentialD; &dd;\nⅇ\n&ExponentialE; &exponentiale; &ee;\nⅈ\n&ImaginaryI; &ii;\n⅓\n&frac13;\n⅔\n&frac23;\n⅕\n&frac15;\n⅖\n&frac25;\n⅗\n&frac35;\n⅘\n&frac45;\n⅙\n&frac16;\n⅚\n&frac56;\n⅛\n&frac18;\n⅜\n&frac38;\n⅝\n&frac58;\n⅞\n&frac78;\n←\n&larr; &leftarrow; &LeftArrow; &slarr; &ShortLeftArrow;\n↑\n&uarr; &uparrow; &UpArrow; &ShortUpArrow;\n→\n&rarr; &rightarrow; &RightArrow; &srarr; &ShortRightArrow;\n↓\n&darr; &downarrow; &DownArrow; &ShortDownArrow;\n↔\n&harr; &leftrightarrow; &LeftRightArrow;\n↕\n&varr; &updownarrow; &UpDownArrow;\n↖\n&nwarr; &UpperLeftArrow; &nwarrow;\n↗\n&nearr; &UpperRightArrow; &nearrow;\n↘\n&searr; &searrow; &LowerRightArrow;\n↙\n&swarr; &swarrow; &LowerLeftArrow;\n↚\n&nlarr; &nleftarrow;\n↛\n&nrarr; &nrightarrow;\n↝\n&rarrw; &rightsquigarrow;\n↞\n&Larr; &twoheadleftarrow;\n↟\n&Uarr;\n↠\n&Rarr; &twoheadrightarrow;\n↡\n&Darr;\n↢\n&larrtl; &leftarrowtail;\n↣\n&rarrtl; &rightarrowtail;\n↤\n&LeftTeeArrow; &mapstoleft;\n↥\n&UpTeeArrow; &mapstoup;\n↦\n&map; &RightTeeArrow; &mapsto;\n↧\n&DownTeeArrow; &mapstodown;\n↩\n&larrhk; &hookleftarrow;\n↪\n&rarrhk; &hookrightarrow;\n↫\n&larrlp; &looparrowleft;\n↬\n&rarrlp; &looparrowright;\n↭\n&harrw; &leftrightsquigarrow;\n↮\n&nharr; &nleftrightarrow;\n↰\n&lsh; &Lsh;\n↱\n&rsh; &Rsh;\n↲\n&ldsh;\n↳\n&rdsh;\n↵\n&crarr;\n↶\n&cularr; &curvearrowleft;\n↷\n&curarr; &curvearrowright;\n↺\n&olarr; &circlearrowleft;\n↻\n&orarr; &circlearrowright;\n↼\n&lharu; &LeftVector; &leftharpoonup;\n↽\n&lhard; &leftharpoondown; &DownLeftVector;\n↾\n&uharr; &upharpoonright; &RightUpVector;\n↿\n&uharl; &upharpoonleft; &LeftUpVector;\n⇀\n&rharu; &RightVector; &rightharpoonup;\n⇁\n&rhard; &rightharpoondown; &DownRightVector;\n⇂\n&dharr; &RightDownVector; &downharpoonright;\n⇃\n&dharl; &LeftDownVector; &downharpoonleft;\n⇄\n&rlarr; &rightleftarrows; &RightArrowLeftArrow;\n⇅\n&udarr; &UpArrowDownArrow;\n⇆\n&lrarr; &leftrightarrows; &LeftArrowRightArrow;\n⇇\n&llarr; &leftleftarrows;\n⇈\n&uuarr; &upuparrows;\n⇉\n&rrarr; &rightrightarrows;\n⇊\n&ddarr; &downdownarrows;\n⇋\n&lrhar; &ReverseEquilibrium; &leftrightharpoons;\n⇌\n&rlhar; &rightleftharpoons; &Equilibrium;\n⇍\n&nlArr; &nLeftarrow;\n⇎\n&nhArr; &nLeftrightarrow;\n⇏\n&nrArr; &nRightarrow;\n⇐\n&lArr; &Leftarrow; &DoubleLeftArrow;\n⇑\n&uArr; &Uparrow; &DoubleUpArrow;\n⇒\n&rArr; &Rightarrow; &Implies; &DoubleRightArrow;\n⇓\n&dArr; &Downarrow; &DoubleDownArrow;\n⇔\n&hArr; &Leftrightarrow; &DoubleLeftRightArrow; &iff;\n⇕\n&vArr; &Updownarrow; &DoubleUpDownArrow;\n⇖\n&nwArr;\n⇗\n&neArr;\n⇘\n&seArr;\n⇙\n&swArr;\n⇚\n&lAarr; &Lleftarrow;\n⇛\n&rAarr; &Rrightarrow;\n⇝\n&zigrarr;\n⇤\n&larrb; &LeftArrowBar;\n⇥\n&rarrb; &RightArrowBar;\n⇵\n&duarr; &DownArrowUpArrow;\n⇽\n&loarr;\n⇾\n&roarr;\n⇿\n&hoarr;\n∀\n&forall; &ForAll;\n∁\n&comp; &complement;\n∂\n&part; &PartialD;\n∃\n&exist; &Exists;\n∄\n&nexist; &NotExists; &nexists;\n∅\n&empty; &emptyset; &emptyv; &varnothing;\n∇\n&nabla; &Del;\n∈\n&isin; &isinv; &Element; &in;\n∉\n&notin; &NotElement; &notinva;\n∋\n&niv; &ReverseElement; &ni; &SuchThat;\n∌\n&notni; &notniva; &NotReverseElement;\n∏\n&prod; &Product;\n∐\n&coprod; &Coproduct;\n∑\n&sum; &Sum;\n−\n&minus;\n∓\n&mnplus; &mp; &MinusPlus;\n∔\n&plusdo; &dotplus;\n∖\n&setmn; &setminus; &Backslash; &ssetmn; &smallsetminus;\n∗\n&lowast;\n∘\n&compfn; &SmallCircle;\n√\n&radic; &Sqrt;\n∝\n&prop; &propto; &Proportional; &vprop; &varpropto;\n∞\n&infin;\n∟\n&angrt;\n∠\n&ang; &angle;\n∡\n&angmsd; &measuredangle;\n∢\n&angsph;\n∣\n&mid; &VerticalBar; &smid; &shortmid;\n∤\n&nmid; &NotVerticalBar; &nsmid; &nshortmid;\n∥\n&par; &parallel; &DoubleVerticalBar; &spar; &shortparallel;\n∦\n&npar; &nparallel; &NotDoubleVerticalBar; &nspar; &nshortparallel;\n∧\n&and; &wedge;\n∨\n&or; &vee;\n∩\n&cap;\n∪\n&cup;\n∫\n&int; &Integral;\n∬\n&Int;\n∭\n&tint; &iiint;\n∮\n&conint; &oint; &ContourIntegral;\n∯\n&Conint; &DoubleContourIntegral;\n∰\n&Cconint;\n∱\n&cwint;\n∲\n&cwconint; &ClockwiseContourIntegral;\n∳\n&awconint; &CounterClockwiseContourIntegral;\n∴\n&there4; &therefore; &Therefore;\n∵\n&becaus; &because; &Because;\n∶\n&ratio;\n∷\n&Colon; &Proportion;\n∸\n&minusd; &dotminus;\n∺\n&mDDot;\n∻\n&homtht;\n∼\n&sim; &Tilde; &thksim; &thicksim;\n∽\n&bsim; &backsim;\n∾\n&ac; &mstpos;\n∿\n&acd;\n≀\n&wreath; &VerticalTilde; &wr;\n≁\n&nsim; &NotTilde;\n≂\n&esim; &EqualTilde; &eqsim;\n≃\n&sime; &TildeEqual; &simeq;\n≄\n&nsime; &nsimeq; &NotTildeEqual;\n≅\n&cong; &TildeFullEqual;\n≆\n&simne;\n≇\n&ncong; &NotTildeFullEqual;\n≈\n&asymp; &ap; &TildeTilde; &approx; &thkap; &thickapprox;\n≉\n&nap; &NotTildeTilde; &napprox;\n≊\n&ape; &approxeq;\n≋\n&apid;\n≌\n&bcong; &backcong;\n≍\n&asympeq; &CupCap;\n≎\n&bump; &HumpDownHump; &Bumpeq;\n≏\n&bumpe; &HumpEqual; &bumpeq;\n≐\n&esdot; &DotEqual; &doteq;\n≑\n&eDot; &doteqdot;\n≒\n&efDot; &fallingdotseq;\n≓\n&erDot; &risingdotseq;\n≔\n&colone; &coloneq; &Assign;\n≕\n&ecolon; &eqcolon;\n≖\n&ecir; &eqcirc;\n≗\n&cire; &circeq;\n≙\n&wedgeq;\n≚\n&veeeq;\n≜\n&trie; &triangleq;\n≟\n&equest; &questeq;\n≠\n&ne; &NotEqual;\n≡\n&equiv; &Congruent;\n≢\n&nequiv; &NotCongruent;\n≤\n&le; &leq;\n≥\n&ge; &GreaterEqual; &geq;\n≦\n&lE; &LessFullEqual; &leqq;\n≧\n&gE; &GreaterFullEqual; &geqq;\n≨\n&lnE; &lneqq;\n≩\n&gnE; &gneqq;\n≪\n&Lt; &NestedLessLess; &ll;\n≫\n&Gt; &NestedGreaterGreater; &gg;\n≬\n&twixt; &between;\n≭\n&NotCupCap;\n≮\n&nlt; &NotLess; &nless;\n≯\n&ngt; &NotGreater; &ngtr;\n≰\n&nle; &NotLessEqual; &nleq;\n≱\n&nge; &NotGreaterEqual; &ngeq;\n≲\n&lsim; &LessTilde; &lesssim;\n≳\n&gsim; &gtrsim; &GreaterTilde;\n≴\n&nlsim; &NotLessTilde;\n≵\n&ngsim; &NotGreaterTilde;\n≶\n&lg; &lessgtr; &LessGreater;\n≷\n&gl; &gtrless; &GreaterLess;\n≸\n&ntlg; &NotLessGreater;\n≹\n&ntgl; &NotGreaterLess;\n≺\n&pr; &Precedes; &prec;\n≻\n&sc; &Succeeds; &succ;\n≼\n&prcue; &PrecedesSlantEqual; &preccurlyeq;\n≽\n&sccue; &SucceedsSlantEqual; &succcurlyeq;\n≾\n&prsim; &precsim; &PrecedesTilde;\n≿\n&scsim; &succsim; &SucceedsTilde;\n⊀\n&npr; &nprec; &NotPrecedes;\n⊁\n&nsc; &nsucc; &NotSucceeds;\n⊂\n&sub; &subset;\n⊃\n&sup; &supset; &Superset;\n⊄\n&nsub;\n⊅\n&nsup;\n⊆\n&sube; &SubsetEqual; &subseteq;\n⊇\n&supe; &supseteq; &SupersetEqual;\n⊈\n&nsube; &nsubseteq; &NotSubsetEqual;\n⊉\n&nsupe; &nsupseteq; &NotSupersetEqual;\n⊊\n&subne; &subsetneq;\n⊋\n&supne; &supsetneq;\n⊍\n&cupdot;\n⊎\n&uplus; &UnionPlus;\n⊏\n&sqsub; &SquareSubset; &sqsubset;\n⊐\n&sqsup; &SquareSuperset; &sqsupset;\n⊑\n&sqsube; &SquareSubsetEqual; &sqsubseteq;\n⊒\n&sqsupe; &SquareSupersetEqual; &sqsupseteq;\n⊓\n&sqcap; &SquareIntersection;\n⊔\n&sqcup; &SquareUnion;\n⊕\n&oplus; &CirclePlus;\n⊖\n&ominus; &CircleMinus;\n⊗\n&otimes; &CircleTimes;\n⊘\n&osol;\n⊙\n&odot; &CircleDot;\n⊚\n&ocir; &circledcirc;\n⊛\n&oast; &circledast;\n⊝\n&odash; &circleddash;\n⊞\n&plusb; &boxplus;\n⊟\n&minusb; &boxminus;\n⊠\n&timesb; &boxtimes;\n⊡\n&sdotb; &dotsquare;\n⊢\n&vdash; &RightTee;\n⊣\n&dashv; &LeftTee;\n⊤\n&top; &DownTee;\n⊥\n&bottom; &bot; &perp; &UpTee;\n⊧\n&models;\n⊨\n&vDash; &DoubleRightTee;\n⊩\n&Vdash;\n⊪\n&Vvdash;\n⊫\n&VDash;\n⊬\n&nvdash;\n⊭\n&nvDash;\n⊮\n&nVdash;\n⊯\n&nVDash;\n⊰\n&prurel;\n⊲\n&vltri; &vartriangleleft; &LeftTriangle;\n⊳\n&vrtri; &vartriangleright; &RightTriangle;\n⊴\n&ltrie; &trianglelefteq; &LeftTriangleEqual;\n⊵\n&rtrie; &trianglerighteq; &RightTriangleEqual;\n⊶\n&origof;\n⊷\n&imof;\n⊸\n&mumap; &multimap;\n⊹\n&hercon;\n⊺\n&intcal; &intercal;\n⊻\n&veebar;\n⊽\n&barvee;\n⊾\n&angrtvb;\n⊿\n&lrtri;\n⋀\n&xwedge; &Wedge; &bigwedge;\n⋁\n&xvee; &Vee; &bigvee;\n⋂\n&xcap; &Intersection; &bigcap;\n⋃\n&xcup; &Union; &bigcup;\n⋄\n&diam; &diamond; &Diamond;\n⋅\n&sdot;\n⋆\n&sstarf; &Star;\n⋇\n&divonx; &divideontimes;\n⋈\n&bowtie;\n⋉\n&ltimes;\n⋊\n&rtimes;\n⋋\n&lthree; &leftthreetimes;\n⋌\n&rthree; &rightthreetimes;\n⋍\n&bsime; &backsimeq;\n⋎\n&cuvee; &curlyvee;\n⋏\n&cuwed; &curlywedge;\n⋐\n&Sub; &Subset;\n⋑\n&Sup; &Supset;\n⋒\n&Cap;\n⋓\n&Cup;\n⋔\n&fork; &pitchfork;\n⋕\n&epar;\n⋖\n&ltdot; &lessdot;\n⋗\n&gtdot; &gtrdot;\n⋘\n&Ll;\n⋙\n&Gg; &ggg;\n⋚\n&leg; &LessEqualGreater; &lesseqgtr;\n⋛\n&gel; &gtreqless; &GreaterEqualLess;\n⋞\n&cuepr; &curlyeqprec;\n⋟\n&cuesc; &curlyeqsucc;\n⋠\n&nprcue; &NotPrecedesSlantEqual;\n⋡\n&nsccue; &NotSucceedsSlantEqual;\n⋢\n&nsqsube; &NotSquareSubsetEqual;\n⋣\n&nsqsupe; &NotSquareSupersetEqual;\n⋦\n&lnsim;\n⋧\n&gnsim;\n⋨\n&prnsim; &precnsim;\n⋩\n&scnsim; &succnsim;\n⋪\n&nltri; &ntriangleleft; &NotLeftTriangle;\n⋫\n&nrtri; &ntriangleright; &NotRightTriangle;\n⋬\n&nltrie; &ntrianglelefteq; &NotLeftTriangleEqual;\n⋭\n&nrtrie; &ntrianglerighteq; &NotRightTriangleEqual;\n⋮\n&vellip;\n⋯\n&ctdot;\n⋰\n&utdot;\n⋱\n&dtdot;\n⋲\n&disin;\n⋳\n&isinsv;\n⋴\n&isins;\n⋵\n&isindot;\n⋶\n&notinvc;\n⋷\n&notinvb;\n⋹\n&isinE;\n⋺\n&nisd;\n⋻\n&xnis;\n⋼\n&nis;\n⋽\n&notnivc;\n⋾\n&notnivb;\n⌅\n&barwed; &barwedge;\n⌆\n&Barwed; &doublebarwedge;\n⌈\n&lceil; &LeftCeiling;\n⌉\n&rceil; &RightCeiling;\n⌊\n&lfloor; &LeftFloor;\n⌋\n&rfloor; &RightFloor;\n⌌\n&drcrop;\n⌍\n&dlcrop;\n⌎\n&urcrop;\n⌏\n&ulcrop;\n⌐\n&bnot;\n⌒\n&profline;\n⌓\n&profsurf;\n⌕\n&telrec;\n⌖\n&target;\n⌜\n&ulcorn; &ulcorner;\n⌝\n&urcorn; &urcorner;\n⌞\n&dlcorn; &llcorner;\n⌟\n&drcorn; &lrcorner;\n⌢\n&frown; &sfrown;\n⌣\n&smile; &ssmile;\n⌭\n&cylcty;\n⌮\n&profalar;\n⌶\n&topbot;\n⌽\n&ovbar;\n⌿\n&solbar;\n⍼\n&angzarr;\n⎰\n&lmoust; &lmoustache;\n⎱\n&rmoust; &rmoustache;\n⎴\n&tbrk; &OverBracket;\n⎵\n&bbrk; &UnderBracket;\n⎶\n&bbrktbrk;\n⏜\n&OverParenthesis;\n⏝\n&UnderParenthesis;\n⏞\n&OverBrace;\n⏟\n&UnderBrace;\n⏢\n&trpezium;\n⏧\n&elinters;\n␣\n&blank;\nⓈ\n&oS; &circledS;\n─\n&boxh; &HorizontalLine;\n│\n&boxv;\n┌\n&boxdr;\n┐\n&boxdl;\n└\n&boxur;\n┘\n&boxul;\n├\n&boxvr;\n┤\n&boxvl;\n┬\n&boxhd;\n┴\n&boxhu;\n┼\n&boxvh;\n═\n&boxH;\n║\n&boxV;\n╒\n&boxdR;\n╓\n&boxDr;\n╔\n&boxDR;\n╕\n&boxdL;\n╖\n&boxDl;\n╗\n&boxDL;\n╘\n&boxuR;\n╙\n&boxUr;\n╚\n&boxUR;\n╛\n&boxuL;\n╜\n&boxUl;\n╝\n&boxUL;\n╞\n&boxvR;\n╟\n&boxVr;\n╠\n&boxVR;\n╡\n&boxvL;\n╢\n&boxVl;\n╣\n&boxVL;\n╤\n&boxHd;\n╥\n&boxhD;\n╦\n&boxHD;\n╧\n&boxHu;\n╨\n&boxhU;\n╩\n&boxHU;\n╪\n&boxvH;\n╫\n&boxVh;\n╬\n&boxVH;\n▀\n&uhblk;\n▄\n&lhblk;\n█\n&block;\n░\n&blk14;\n▒\n&blk12;\n▓\n&blk34;\n□\n&squ; &square; &Square;\n▪\n&squf; &squarf; &blacksquare; &FilledVerySmallSquare;\n▫\n&EmptyVerySmallSquare;\n▭\n&rect;\n▮\n&marker;\n▱\n&fltns;\n△\n&xutri; &bigtriangleup;\n▴\n&utrif; &blacktriangle;\n▵\n&utri; &triangle;\n▸\n&rtrif; &blacktriangleright;\n▹\n&rtri; &triangleright;\n▽\n&xdtri; &bigtriangledown;\n▾\n&dtrif; &blacktriangledown;\n▿\n&dtri; &triangledown;\n◂\n&ltrif; &blacktriangleleft;\n◃\n&ltri; &triangleleft;\n◊\n&loz; &lozenge;\n○\n&cir;\n◬\n&tridot;\n◯\n&xcirc; &bigcirc;\n◸\n&ultri;\n◹\n&urtri;\n◺\n&lltri;\n◻\n&EmptySmallSquare;\n◼\n&FilledSmallSquare;\n★\n&starf; &bigstar;\n☆\n&star;\n☎\n&phone;\n♀\n&female;\n♂\n&male;\n♠\n&spades; &spadesuit;\n♣\n&clubs; &clubsuit;\n♥\n&hearts; &heartsuit;\n♦\n&diams; &diamondsuit;\n♪\n&sung;\n♭\n&flat;\n♮\n&natur; &natural;\n♯\n&sharp;\n✓\n&check; &checkmark;\n✗\n&cross;\n✠\n&malt; &maltese;\n✶\n&sext;\n❘\n&VerticalSeparator;\n❲\n&lbbrk;\n❳\n&rbbrk;\n⟦\n&lobrk; &LeftDoubleBracket;\n⟧\n&robrk; &RightDoubleBracket;\n⟨\n&lang; &LeftAngleBracket; &langle;\n⟩\n&rang; &RightAngleBracket; &rangle;\n⟪\n&Lang;\n⟫\n&Rang;\n⟬\n&loang;\n⟭\n&roang;\n⟵\n&xlarr; &longleftarrow; &LongLeftArrow;\n⟶\n&xrarr; &longrightarrow; &LongRightArrow;\n⟷\n&xharr; &longleftrightarrow; &LongLeftRightArrow;\n⟸\n&xlArr; &Longleftarrow; &DoubleLongLeftArrow;\n⟹\n&xrArr; &Longrightarrow; &DoubleLongRightArrow;\n⟺\n&xhArr; &Longleftrightarrow; &DoubleLongLeftRightArrow;\n⟼\n&xmap; &longmapsto;\n⟿\n&dzigrarr;\n⤂\n&nvlArr;\n⤃\n&nvrArr;\n⤄\n&nvHarr;\n⤅\n&Map;\n⤌\n&lbarr;\n⤍\n&rbarr; &bkarow;\n⤎\n&lBarr;\n⤏\n&rBarr; &dbkarow;\n⤐\n&RBarr; &drbkarow;\n⤑\n&DDotrahd;\n⤒\n&UpArrowBar;\n⤓\n&DownArrowBar;\n⤖\n&Rarrtl;\n⤙\n&latail;\n⤚\n&ratail;\n⤛\n&lAtail;\n⤜\n&rAtail;\n⤝\n&larrfs;\n⤞\n&rarrfs;\n⤟\n&larrbfs;\n⤠\n&rarrbfs;\n⤣\n&nwarhk;\n⤤\n&nearhk;\n⤥\n&searhk; &hksearow;\n⤦\n&swarhk; &hkswarow;\n⤧\n&nwnear;\n⤨\n&nesear; &toea;\n⤩\n&seswar; &tosa;\n⤪\n&swnwar;\n⤳\n&rarrc;\n⤵\n&cudarrr;\n⤶\n&ldca;\n⤷\n&rdca;\n⤸\n&cudarrl;\n⤹\n&larrpl;\n⤼\n&curarrm;\n⤽\n&cularrp;\n⥅\n&rarrpl;\n⥈\n&harrcir;\n⥉\n&Uarrocir;\n⥊\n&lurdshar;\n⥋\n&ldrushar;\n⥎\n&LeftRightVector;\n⥏\n&RightUpDownVector;\n⥐\n&DownLeftRightVector;\n⥑\n&LeftUpDownVector;\n⥒\n&LeftVectorBar;\n⥓\n&RightVectorBar;\n⥔\n&RightUpVectorBar;\n⥕\n&RightDownVectorBar;\n⥖\n&DownLeftVectorBar;\n⥗\n&DownRightVectorBar;\n⥘\n&LeftUpVectorBar;\n⥙\n&LeftDownVectorBar;\n⥚\n&LeftTeeVector;\n⥛\n&RightTeeVector;\n⥜\n&RightUpTeeVector;\n⥝\n&RightDownTeeVector;\n⥞\n&DownLeftTeeVector;\n⥟\n&DownRightTeeVector;\n⥠\n&LeftUpTeeVector;\n⥡\n&LeftDownTeeVector;\n⥢\n&lHar;\n⥣\n&uHar;\n⥤\n&rHar;\n⥥\n&dHar;\n⥦\n&luruhar;\n⥧\n&ldrdhar;\n⥨\n&ruluhar;\n⥩\n&rdldhar;\n⥪\n&lharul;\n⥫\n&llhard;\n⥬\n&rharul;\n⥭\n&lrhard;\n⥮\n&udhar; &UpEquilibrium;\n⥯\n&duhar; &ReverseUpEquilibrium;\n⥰\n&RoundImplies;\n⥱\n&erarr;\n⥲\n&simrarr;\n⥳\n&larrsim;\n⥴\n&rarrsim;\n⥵\n&rarrap;\n⥶\n&ltlarr;\n⥸\n&gtrarr;\n⥹\n&subrarr;\n⥻\n&suplarr;\n⥼\n&lfisht;\n⥽\n&rfisht;\n⥾\n&ufisht;\n⥿\n&dfisht;\n⦅\n&lopar;\n⦆\n&ropar;\n⦋\n&lbrke;\n⦌\n&rbrke;\n⦍\n&lbrkslu;\n⦎\n&rbrksld;\n⦏\n&lbrksld;\n⦐\n&rbrkslu;\n⦑\n&langd;\n⦒\n</code></pre>\n\n<p>Not fully, pls track the link for fully document.</p>\n"
},
{
"answer_id": 52678432,
"author": "N Randhawa",
"author_id": 4854721,
"author_profile": "https://Stackoverflow.com/users/4854721",
"pm_score": 3,
"selected": false,
"text": "<p>The differences between htmlspecialchars() and htmlentities() is very small. Lets see some examples:</p>\n\n<blockquote>\n <p>htmlspecialchars</p>\n</blockquote>\n\n<p><strong>htmlspecialchars(string $string)</strong> takes multiple arguments where as the first argument is a string and all other arguments (certain flags, certain encodings etc. ) are optional. <strong>htmlspecialchars</strong> converts special characters in the string to HTML entities. For example if you have <strong>< br ></strong> in your string, <strong>htmlspecialchars</strong> will convert it into <strong>&lt; b &gt;</strong>. Whereas characters like µ † etc. have no special significance in HTML. So they will be not converted to HTML entities by <strong>htmlspecialchars</strong> function as shown in the below example. </p>\n\n<pre><code>echo htmlspecialchars('An example <br>'); // This will print - An example &lt; br &gt;\necho htmlspecialchars('µ †'); // This will print - µ †\n</code></pre>\n\n<blockquote>\n <p>htmlentities </p>\n</blockquote>\n\n<p><strong>htmlentities ( string $string)</strong> is very similar to <strong>htmlspecialchars</strong> and takes multiple arguments where as the first argument is a string and all other arguments are optional (certain flags, certain encodings etc.). Unlike <strong>htmlspecialchars</strong>, <strong>htmlentities</strong> converts not only special characters in the string to HTML entities but all applicable characters to HTML entities.</p>\n\n<pre><code>echo htmlentities('An example <br>'); // This will print - An example &lt; br &gt;\necho htmlentities('µ †'); // This will print - &micro; &dagger; \n</code></pre>\n"
}
] | 2008/09/05 | [
"https://Stackoverflow.com/questions/46483",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4137/"
] | What are the differences between `htmlspecialchars()` and `htmlentities()`. When should I use one or the other? | From the PHP documentation for [htmlentities](http://us2.php.net/htmlentities):
>
> This function is identical to `htmlspecialchars()` in all ways, except with `htmlentities()`, all characters which have HTML character entity equivalents are translated into these entities.
>
>
>
From the PHP documentation for [htmlspecialchars](http://us.php.net/htmlspecialchars):
>
> Certain characters have special significance in HTML, and should be represented by HTML entities if they are to preserve their meanings. This function returns a string with some of these conversions made; the translations made are those most useful for everyday web programming. If you require all HTML character entities to be translated, use `htmlentities()` instead.
>
>
>
The difference is what gets encoded. The choices are everything (entities) or "special" characters, like ampersand, double and single quotes, less than, and greater than (specialchars).
I prefer to use `htmlspecialchars` whenever possible.
For example:
```php
echo htmlentities('<Il était une fois un être>.');
// Output: <Il était une fois un être>.
// ^^^^^^^^ ^^^^^^^
echo htmlspecialchars('<Il était une fois un être>.');
// Output: <Il était une fois un être>.
// ^ ^
``` |
46,489 | <p>In my web application I include all of my JavaScripts as js files that are embedded resources in the assembly, and add them to the page using <code>ClientScriptManager.GetWebResourceUrl()</code>. However, in some of my js files, I have references to other static assets like image urls. I would like to make those assembly resources as well. Is there a way to tokenize the reference to the resource? e.g.</p>
<pre><code>this.drophint = document.createElement('img');
this.drophint.src = '/_layouts/images/dragdrophint.gif';
</code></pre>
<p>Could become something like:</p>
<pre><code>this.drophint = document.createElement('img');
this.drophint.src = '{resource:assembly.location.dragdrophint.gif}';
</code></pre>
| [
{
"answer_id": 47242,
"author": "Jon",
"author_id": 4764,
"author_profile": "https://Stackoverflow.com/users/4764",
"pm_score": 3,
"selected": true,
"text": "<p>I'd suggest that you emit the web resources as a dynamic javascript associative array.</p>\n\n<p>Server side code:</p>\n\n<pre><code>StringBuilder script = new StringBuilder();\nscript.Append(\"var imgResources = {};\");\nscript.AppendFormat(\"imgResources['{0}'] = '{1}';\", \n \"drophint\", \n Page.ClientScript.GetWebResourceUrl(Page.GetType(), \"assembly.location.dragdrophint.gif\"));\nscript.AppendFormat(\"imgResources['{0}'] = '{1}';\", \n \"anotherimg\", \n Page.ClientScript.GetWebResourceUrl(Page.GetType(), \"assembly.location.anotherimg.gif\"));\n\nPage.ClientScript.RegisterClientScriptBlock(\n Page.GetType(),\n \"imgResources\",\n script.ToString(), \n true);\n</code></pre>\n\n<p>Then your client side code looks like this:</p>\n\n<pre><code>this.drophint = document.createElement('img');\nthis.drophint.src = imgResources['drophint'];\nthis.anotherimg = document.createElement('img');\nthis.anotherimg.src = imgResources['anotherimg'];\n</code></pre>\n\n<p>Hope this helps.</p>\n"
},
{
"answer_id": 47681,
"author": "Jason Bunting",
"author_id": 1790,
"author_profile": "https://Stackoverflow.com/users/1790",
"pm_score": 2,
"selected": false,
"text": "<p>I don't particularly care for the exact implementation <a href=\"https://stackoverflow.com/questions/46489/referencing-embedded-resources-from-other-resources-in-c#47242\"><strong>@Jon</strong></a> suggests, but the idea behind it is sound and I would concur that emitting these would be a good thing to do. </p>\n\n<p>A slightly better implementation, though this is all subjective to some degree, would be to create a server-side model (read: C# class(es)) that represents this dictionary (or simply use an instance of Dictionary<string, string>) and serialize that to JavaScript literal object notation. That way you are not dealing with the string hacking you see in Jon's example (if that bothers you).</p>\n"
},
{
"answer_id": 47750,
"author": "Jon",
"author_id": 4764,
"author_profile": "https://Stackoverflow.com/users/4764",
"pm_score": 2,
"selected": false,
"text": "<p>I concur with Jason's assessment of the initial solution I proposed, it can definitely be improved. My solution represents an older school javascript mentality (read, pre the emergence of ajax and JSON). There are always better ways to solve a problem, which one of the reasons why StackOverflow is so cool. Collectively we are better at the craft of programming than anyone of us on our own.</p>\n<p>Based on Jason's ideas I'd revise my initial code, and revise some of what Jason suggested. Implement a <code>C#</code> class with two properties, the <code>img</code> resource <code>id</code> and a property that contains the <code>WebResourceUrl</code>. Then, where I differ some from Jason is that rather than using a <code>Dictionary<string, string></code> I'd propose using a <code>List<MyImageResourceClass></code>, which you can then in turn serialize to JSON (using <a href=\"http://msdn.microsoft.com/en-us/library/bb412170.aspx\" rel=\"nofollow noreferrer\">DataContractJsonSerializer</a>), and emit the JSON as the dynamic script, rather than manually generating the javascript using a string builder.</p>\n<p>Why a List? I think you may find that dictionaries when serialized to JSON, at least using the <code>DataContractJsonSerializer</code> (fyi available with the 3.5 framework only, with the 2.0 or 3.0 framework you'd need to bolt on aspnet ajax and use is JSON serializer), are a little more cumbersome to work with than how a list would serialize. Although that is subjective.</p>\n<p>There are implications too with your client side code. Now on the client side you'll have an array of the JSON serialized MyImageResourceClass instances. You'd need to iterate through this array creating your <code>img</code> tags as you go.</p>\n<p>Hopefully, these ideas and suggestions can help get you going! And no doubt there are other solutions. I'm interested to see what comes of this.</p>\n"
}
] | 2008/09/05 | [
"https://Stackoverflow.com/questions/46489",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/67/"
] | In my web application I include all of my JavaScripts as js files that are embedded resources in the assembly, and add them to the page using `ClientScriptManager.GetWebResourceUrl()`. However, in some of my js files, I have references to other static assets like image urls. I would like to make those assembly resources as well. Is there a way to tokenize the reference to the resource? e.g.
```
this.drophint = document.createElement('img');
this.drophint.src = '/_layouts/images/dragdrophint.gif';
```
Could become something like:
```
this.drophint = document.createElement('img');
this.drophint.src = '{resource:assembly.location.dragdrophint.gif}';
``` | I'd suggest that you emit the web resources as a dynamic javascript associative array.
Server side code:
```
StringBuilder script = new StringBuilder();
script.Append("var imgResources = {};");
script.AppendFormat("imgResources['{0}'] = '{1}';",
"drophint",
Page.ClientScript.GetWebResourceUrl(Page.GetType(), "assembly.location.dragdrophint.gif"));
script.AppendFormat("imgResources['{0}'] = '{1}';",
"anotherimg",
Page.ClientScript.GetWebResourceUrl(Page.GetType(), "assembly.location.anotherimg.gif"));
Page.ClientScript.RegisterClientScriptBlock(
Page.GetType(),
"imgResources",
script.ToString(),
true);
```
Then your client side code looks like this:
```
this.drophint = document.createElement('img');
this.drophint.src = imgResources['drophint'];
this.anotherimg = document.createElement('img');
this.anotherimg.src = imgResources['anotherimg'];
```
Hope this helps. |
46,495 | <p>Why can't you do this and is there are work around?</p>
<p>You get this error.</p>
<p>Msg 2714, Level 16, State 1, Line 13
There is already an object named '#temptable' in the database.</p>
<pre><code>declare @x int
set @x = 1
if (@x = 0)
begin
select 1 as Value into #temptable
end
else
begin
select 2 as Value into #temptable
end
select * from #temptable
drop table #temptable
</code></pre>
| [
{
"answer_id": 46527,
"author": "Craig",
"author_id": 2894,
"author_profile": "https://Stackoverflow.com/users/2894",
"pm_score": 0,
"selected": false,
"text": "<p>I am going to guess that the issue is that you haven't created the #temptable.</p>\n\n<p>Sorry I can't be more detailed but since you haven't even tried to explain what you are seeing you get a less than stellar answer.</p>\n"
},
{
"answer_id": 46530,
"author": "SQLMenace",
"author_id": 740,
"author_profile": "https://Stackoverflow.com/users/740",
"pm_score": 1,
"selected": false,
"text": "<p>You can't do that because of deferred name resolution, you can do it with a real table, just take out the pound signs</p>\n\n<p>You could also create the temp table first on top and then do a regular insert into table</p>\n"
},
{
"answer_id": 46539,
"author": "Andrew",
"author_id": 826,
"author_profile": "https://Stackoverflow.com/users/826",
"pm_score": 0,
"selected": false,
"text": "<p>From the look of the code is seems like you might have been prototyping this in SQL Studio or similiar, right? Can I guess that you've run this a few times and had it get to the point where it's created #temptable but then failed before it got to the end and dropped the table again? Restart the SQL editing tool you're using and try again.</p>\n"
},
{
"answer_id": 46565,
"author": "Kevin Fairchild",
"author_id": 3743,
"author_profile": "https://Stackoverflow.com/users/3743",
"pm_score": 1,
"selected": false,
"text": "<p>First step... check if the table already exists... if it does, delete it. Next, explicitly create the table rather than using SELECT INTO...</p>\n\n<p>You'll find it much more reliable that way.</p>\n\n<pre><code>IF OBJECT_ID('tempdb..#temptable', 'U') IS NOT NULL \nBEGIN\nDROP TABLE #temptable\nEND\n\nCREATE TABLE #temptable (Value INT)\n\ndeclare @x int\n\nset @x = 1\n\nif (@x = 0)\nbegin\n INSERT INTO #temptable (Value) select 1\nend\nelse\nbegin\n INSERT INTO #temptable (Value) select 2\nend\n\nselect * from #temptable\n\ndrop table #temptable\n</code></pre>\n\n<p>Also, hopefully the table and field names are simplified for your example and aren't what you <em>really</em> call them ;)</p>\n\n<p>-- Kevin Fairchild</p>\n"
},
{
"answer_id": 46575,
"author": "SQLMenace",
"author_id": 740,
"author_profile": "https://Stackoverflow.com/users/740",
"pm_score": 1,
"selected": false,
"text": "<p>Deferred name resolution is also the reason you cannot be sure that sp_depends gives back correct results, check out this post I wrote a while back <a href=\"http://sqlblog.com/blogs/denis_gobo/archive/2008/05/06/6653.aspx\" rel=\"nofollow noreferrer\">Do you depend on sp_depends (no pun intended)</a></p>\n"
},
{
"answer_id": 147571,
"author": "Peter Wone",
"author_id": 1715673,
"author_profile": "https://Stackoverflow.com/users/1715673",
"pm_score": 2,
"selected": true,
"text": "<p>This is a two-part question and while Kev Fairchild provides a good answer to the second question he totally ignores the first - <em>why is the error produced?</em></p>\n\n<p>The answer lies in the way the preprocessor works. This</p>\n\n<pre><code>SELECT field-list INTO #symbol ...\n</code></pre>\n\n<p>is resolved into a parse-tree that is directly equivalent to </p>\n\n<pre><code>DECLARE #symbol_sessionid TABLE(field-list)\nINSERT INTO #symbol_sessionid SELECT field-list ...\n</code></pre>\n\n<p>and this puts #symbol into the local scope's name table. The business with _sessionid is to provide each user session with a private namespace; if you specify two hashes (##symbol) this behaviour is suppressed. Munging and unmunging of the sessionid extension is (ovbiously) transparent.</p>\n\n<p>The upshot of all this is that multiple INTO #symbol clauses produce multiple declarations in the same scope, leading to Msg 2714.</p>\n"
}
] | 2008/09/05 | [
"https://Stackoverflow.com/questions/46495",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2184/"
] | Why can't you do this and is there are work around?
You get this error.
Msg 2714, Level 16, State 1, Line 13
There is already an object named '#temptable' in the database.
```
declare @x int
set @x = 1
if (@x = 0)
begin
select 1 as Value into #temptable
end
else
begin
select 2 as Value into #temptable
end
select * from #temptable
drop table #temptable
``` | This is a two-part question and while Kev Fairchild provides a good answer to the second question he totally ignores the first - *why is the error produced?*
The answer lies in the way the preprocessor works. This
```
SELECT field-list INTO #symbol ...
```
is resolved into a parse-tree that is directly equivalent to
```
DECLARE #symbol_sessionid TABLE(field-list)
INSERT INTO #symbol_sessionid SELECT field-list ...
```
and this puts #symbol into the local scope's name table. The business with \_sessionid is to provide each user session with a private namespace; if you specify two hashes (##symbol) this behaviour is suppressed. Munging and unmunging of the sessionid extension is (ovbiously) transparent.
The upshot of all this is that multiple INTO #symbol clauses produce multiple declarations in the same scope, leading to Msg 2714. |
46,532 | <p>If I have an XElement that has child elements, and if I remove a child element from the parent, removing all references between the two, will the child XElement have the same namespaces as the parent?</p>
<p>In other words, if I have the following XML:</p>
<pre><code><parent xmlns:foo="abc">
<foo:child />
</parent>
</code></pre>
<p>and I remove the child element, will the child element's xml look like</p>
<pre><code><child xmlns="abc" />
</code></pre>
<p>or like </p>
<pre><code><child />
</code></pre>
| [
{
"answer_id": 46637,
"author": "xanadont",
"author_id": 1886,
"author_profile": "https://Stackoverflow.com/users/1886",
"pm_score": 1,
"selected": false,
"text": "<p>Sure. Ultimately the image comes from a URL of some sort. Do a view-source on the web page and see what that URL looks like. With a certain amount of reverse-engineering, usage of System.Web.UI.HtmlTextWriter, perhaps an HttpHandler, etc. you should be able to get what you want.</p>\n"
},
{
"answer_id": 283130,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 0,
"selected": false,
"text": "<p>Use the ExportToImage method of the ChartControl object .. This is WinForm code, but the same concept should hold true for WebChartControl:</p>\n\n<pre><code> Dim chart As ChartControl = ChartControl1.Clone()\n chart.Size = New Size(800, 600)\n chart.ExportToImage(\"file.png\", System.Drawing.Imaging.ImageFormat.Png)\n</code></pre>\n"
},
{
"answer_id": 1809828,
"author": "Martin Bell",
"author_id": 220160,
"author_profile": "https://Stackoverflow.com/users/220160",
"pm_score": 1,
"selected": false,
"text": "<p>The best solution for exporting an image from a Developer Express chart control (web) is:</p>\n\n<pre><code>((IChartContainer)[Your web chart control]).Chart.ExportToImage([Your file name], ImageFormat.Png);\n</code></pre>\n"
}
] | 2008/09/05 | [
"https://Stackoverflow.com/questions/46532",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] | If I have an XElement that has child elements, and if I remove a child element from the parent, removing all references between the two, will the child XElement have the same namespaces as the parent?
In other words, if I have the following XML:
```
<parent xmlns:foo="abc">
<foo:child />
</parent>
```
and I remove the child element, will the child element's xml look like
```
<child xmlns="abc" />
```
or like
```
<child />
``` | Sure. Ultimately the image comes from a URL of some sort. Do a view-source on the web page and see what that URL looks like. With a certain amount of reverse-engineering, usage of System.Web.UI.HtmlTextWriter, perhaps an HttpHandler, etc. you should be able to get what you want. |
46,571 | <p>I have been tasked with going through a number of ColdFusion sites that have recently been the subject of a rather nasty SQL Injection attack. Basically my work involves adding <code><cfqueryparam</code>> tags to all of the inline sql. For the most part I've got it down, but can anybody tell me how to use cfqueryparam with the LIKE operator?</p>
<p>If my query looks like this:</p>
<pre><code>select * from Foo where name like '%Bob%'
</code></pre>
<p>what should my <code><cfqueryparam</code>> tag look like?</p>
| [
{
"answer_id": 47197,
"author": "Adam Tuttle",
"author_id": 751,
"author_profile": "https://Stackoverflow.com/users/751",
"pm_score": 7,
"selected": true,
"text": "<p>@Joel, I have to disagree.</p>\n\n<pre><code>select a,b,c\nfrom Foo\nwhere name like <cfqueryparam cfsqltype=\"columnType\" value=\"%#variables.someName#%\" />\n</code></pre>\n\n<ol>\n<li><p>Never suggest to someone that they should \"select star.\" Bad form! Even for an example! (Even copied from the question!)</p></li>\n<li><p>The query is pre-compiled and you should include the wild card character(s) as part of the parameter being passed to the query. This format is more readable and will run more efficiently.</p></li>\n<li><p>When doing string concatenation, use the ampersand operator (&), not the plus sign. Technically, in most cases, plus will work just fine... until you throw a NumberFormat() in the middle of the string and start wondering why you're being told that you're not passing a valid number when you've checked and you are.</p></li>\n</ol>\n"
},
{
"answer_id": 16583567,
"author": "Ramalinga Raju",
"author_id": 2358182,
"author_profile": "https://Stackoverflow.com/users/2358182",
"pm_score": 0,
"selected": false,
"text": "<pre><code>select a,b,c\nfrom Foo\nwhere name like <cfqueryparam cfsqltype=\"cf_sql_varchar\" value=\"%Bob%\" />;\n</code></pre>\n"
}
] | 2008/09/05 | [
"https://Stackoverflow.com/questions/46571",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3271/"
] | I have been tasked with going through a number of ColdFusion sites that have recently been the subject of a rather nasty SQL Injection attack. Basically my work involves adding `<cfqueryparam`> tags to all of the inline sql. For the most part I've got it down, but can anybody tell me how to use cfqueryparam with the LIKE operator?
If my query looks like this:
```
select * from Foo where name like '%Bob%'
```
what should my `<cfqueryparam`> tag look like? | @Joel, I have to disagree.
```
select a,b,c
from Foo
where name like <cfqueryparam cfsqltype="columnType" value="%#variables.someName#%" />
```
1. Never suggest to someone that they should "select star." Bad form! Even for an example! (Even copied from the question!)
2. The query is pre-compiled and you should include the wild card character(s) as part of the parameter being passed to the query. This format is more readable and will run more efficiently.
3. When doing string concatenation, use the ampersand operator (&), not the plus sign. Technically, in most cases, plus will work just fine... until you throw a NumberFormat() in the middle of the string and start wondering why you're being told that you're not passing a valid number when you've checked and you are. |
46,582 | <p>We have the requirement to take a form submission and save some data, then redirect the user to a page offsite, but in redirecting, we need to "submit" a form with POST, not GET.</p>
<p>I was hoping there was an easy way to accomplish this, but I'm starting to think there isn't. I think I must now create a simple other page, with just the form that I want, redirect to it, populate the form variables, then do a body.onload call to a script that merely calls document.forms[0].submit();</p>
<p>Can anyone tell me if there is an alternative? We might need to tweak this later in the project, and it might get sort of complicated, so if there was an easy we could do this all non-other page dependent that would be fantastic.</p>
<p>Anyway, thanks for any and all responses.</p>
| [
{
"answer_id": 46611,
"author": "Jimmy",
"author_id": 4435,
"author_profile": "https://Stackoverflow.com/users/4435",
"pm_score": 2,
"selected": false,
"text": "<p>PostbackUrl can be set on your asp button to post to a different page.</p>\n\n<p>if you need to do it in codebehind, try Server.Transfer. </p>\n"
},
{
"answer_id": 46657,
"author": "Ben Griswold",
"author_id": 4115,
"author_profile": "https://Stackoverflow.com/users/4115",
"pm_score": 2,
"selected": false,
"text": "<p>I suggest building an HttpWebRequest to programmatically execute your POST and then redirect after reading the Response if applicable.</p>\n"
},
{
"answer_id": 46700,
"author": "FlySwat",
"author_id": 1965,
"author_profile": "https://Stackoverflow.com/users/1965",
"pm_score": 5,
"selected": false,
"text": "<p>HttpWebRequest is used for this.</p>\n\n<p>On postback, create a HttpWebRequest to your third party and post the form data, then once that is done, you can Response.Redirect wherever you want.</p>\n\n<p>You get the added advantage that you don't have to name all of your server controls to make the 3rd parties form, you can do this translation when building the POST string.</p>\n\n<pre><code>string url = \"3rd Party Url\";\n\nStringBuilder postData = new StringBuilder();\n\npostData.Append(\"first_name=\" + HttpUtility.UrlEncode(txtFirstName.Text) + \"&\");\npostData.Append(\"last_name=\" + HttpUtility.UrlEncode(txtLastName.Text));\n\n//ETC for all Form Elements\n\n// Now to Send Data.\nStreamWriter writer = null;\n\nHttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);\nrequest.Method = \"POST\";\nrequest.ContentType = \"application/x-www-form-urlencoded\"; \nrequest.ContentLength = postData.ToString().Length;\ntry\n{\n writer = new StreamWriter(request.GetRequestStream());\n writer.Write(postData.ToString());\n}\nfinally\n{\n if (writer != null)\n writer.Close();\n}\n\nResponse.Redirect(\"NewPage\");\n</code></pre>\n\n<p>However, if you need the user to see the response page from this form, your only option is to utilize Server.Transfer, and that may or may not work.</p>\n"
},
{
"answer_id": 46906,
"author": "FlySwat",
"author_id": 1965,
"author_profile": "https://Stackoverflow.com/users/1965",
"pm_score": 2,
"selected": false,
"text": "<p>@Matt,</p>\n\n<p>You can still use the HttpWebRequest, then direct the response you receive to the actual outputstream response, this would serve the response back to the user. The only issue is that any relative urls would be broken.</p>\n\n<p>Still, that may work.</p>\n"
},
{
"answer_id": 47670,
"author": "Andrei Rînea",
"author_id": 1796,
"author_profile": "https://Stackoverflow.com/users/1796",
"pm_score": 2,
"selected": false,
"text": "<p>Here's what I'd do :</p>\n\n<p>Put the data in a standard form (with no runat=\"server\" attribute) and set the action of the form to post to the target off-site page.\nBefore submitting I would submit the data to my server <strong>using an XmlHttpRequest</strong> and analyze the response. If the response means you should go ahead with the offsite POSTing then I (the JavaScript) would proceed with the post otherwise I would redirect to a page on my site</p>\n"
},
{
"answer_id": 47735,
"author": "tghw",
"author_id": 2363,
"author_profile": "https://Stackoverflow.com/users/2363",
"pm_score": 9,
"selected": true,
"text": "<p>Doing this requires understanding how HTTP redirects work. When you use <code>Response.Redirect()</code>, you send a response (to the browser that made the request) with <a href=\"http://en.wikipedia.org/wiki/HTTP_302\" rel=\"noreferrer\">HTTP Status Code 302</a>, which tells the browser where to go next. By definition, the browser will make that via a <code>GET</code> request, even if the original request was a <code>POST</code>.</p>\n\n<p>Another option is to use <a href=\"http://en.wikipedia.org/wiki/List_of_HTTP_status_codes#3xx_Redirection\" rel=\"noreferrer\">HTTP Status Code 307</a>, which specifies that the browser should make the redirect request in the same way as the original request, but to prompt the user with a security warning. To do that, you would write something like this:</p>\n\n<pre><code>public void PageLoad(object sender, EventArgs e)\n{\n // Process the post on your side \n\n Response.Status = \"307 Temporary Redirect\";\n Response.AddHeader(\"Location\", \"http://example.com/page/to/post.to\");\n}\n</code></pre>\n\n<p>Unfortunately, this won't always work. <a href=\"http://ilia.ws/archives/152-Cross-Domain-POST-Redirection.html\" rel=\"noreferrer\">Different browsers implement this differently</a>, since it is not a common status code.</p>\n\n<blockquote>\n <p>Alas, unlike the Opera and FireFox developers, the IE developers have never read the spec, and even the latest, most secure IE7 will redirect the POST request from domain A to domain B without any warnings or confirmation dialogs! Safari also acts in an interesting manner, while it does not raise a confirmation dialog and performs the redirect, it throws away the POST data, <strong>effectively changing 307 redirect into the more common 302.</strong></p>\n</blockquote>\n\n<p>So, as far as I know, the only way to implement something like this would be to use Javascript. There are two options I can think of off the top of my head:</p>\n\n<ol>\n<li>Create the form and have its <code>action</code> attribute point to the third-party server. Then, add a click event to the submit button that first executes an AJAX request to your server with the data, and then allows the form to be submitted to the third-party server.</li>\n<li>Create the form to post to your server. When the form is submitted, show the user a page that has a form in it with all of the data you want to pass on, all in hidden inputs. Just show a message like \"Redirecting...\". Then, add a javascript event to the page that submits the form to the third-party server.</li>\n</ol>\n\n<p>Of the two, I would choose the second, for two reasons. First, it is more reliable than the first because Javascript is not required for it to work; for those who don't have it enabled, you can always make the submit button for the hidden form visible, and instruct them to press it if it takes more than 5 seconds. Second, you can decide what data gets transmitted to the third-party server; if you use just process the form as it goes by, you will be passing along all of the post data, which is not always what you want. Same for the 307 solution, assuming it worked for all of your users.</p>\n\n<p>Hope this helps!</p>\n"
},
{
"answer_id": 47832,
"author": "FlySwat",
"author_id": 1965,
"author_profile": "https://Stackoverflow.com/users/1965",
"pm_score": 2,
"selected": false,
"text": "<blockquote>\n <p>In PHP, you can send POST data with cURL. Is there something comparable for .NET?</p>\n</blockquote>\n\n<p>Yes, HttpWebRequest, see my post below.</p>\n"
},
{
"answer_id": 50809,
"author": "erickson",
"author_id": 3474,
"author_profile": "https://Stackoverflow.com/users/3474",
"pm_score": 2,
"selected": false,
"text": "<p>The GET (and HEAD) method should never be used to do anything that has side-effects. A side-effect might be updating the state of a web application, or it might be charging your credit card. If an action has side-effects another method (POST) should be used instead.</p>\n\n<p>So, a user (or their browser) shouldn't be held accountable for something done by a GET. If some harmful or expensive side-effect occurred as the result of a GET, that would be the fault of the web application, not the user. According to the spec, a user agent <strong>must not</strong> automatically follow a redirect unless it is a response to a GET or HEAD request.</p>\n\n<p>Of course, a lot of GET requests do have some side-effects, even if it's just appending to a log file. The important thing is that the application, not the user, should be held responsible for those effects.</p>\n\n<p>The relevant sections of the HTTP spec are <a href=\"http://www.w3.org/Protocols/rfc2616/rfc2616-sec9.html\" rel=\"nofollow noreferrer\">9.1.1 and 9.1.2</a>, and <a href=\"http://www.w3.org/Protocols/rfc2616/rfc2616-sec10.html#sec10.3\" rel=\"nofollow noreferrer\">10.3</a>.</p>\n"
},
{
"answer_id": 1353717,
"author": "John Leidegren",
"author_id": 58961,
"author_profile": "https://Stackoverflow.com/users/58961",
"pm_score": 1,
"selected": false,
"text": "<p>Typically, all you'll ever need is to carry some state between these two requests. There's actually a really funky way to do this which doesn't rely on JavaScript (think <noscript/>).</p>\n\n<pre><code>Set-Cookie: name=value; Max-Age=120; Path=/redirect.html\n</code></pre>\n\n<p>With that cookie there, you can in the following request to /redirect.html retrieve the name=value info, you can store any kind of information in this name/value pair string, up to say 4K of data (typical cookie limit). Of course you should avoid this and store status codes and flag bits instead.</p>\n\n<p>Upon receiving this request you in return respond with a delete request for that status code.</p>\n\n<pre><code>Set-Cookie: name=value; Max-Age=0; Path=/redirect.html\n</code></pre>\n\n<p>My HTTP is a bit rusty I've been going trough RFC2109 and RFC2965 to figure how reliable this really is, preferably I would want the cookie to round trip exactly once but that doesn't seem to be possible, also, <em>third-party cookies might be a problem for you if you are relocating to another domain. This is still possible but not as painless as when you're doing stuff within your own domain.</em></p>\n\n<p>The problem here is concurrency, if a power user is using multiple tabs and manages to interleave a couple of requests belonging to the same session (this is very unlikely, but not impossible) this may lead to inconsistencies in your application.</p>\n\n<p>It's the <noscript/> way of doing HTTP round trips without meaningless URLs and JavaScript</p>\n\n<p>I provide this code as a prof of concept: If this code is run in a context that you are not familiar with I think you can work out what part is what.</p>\n\n<p>The idea is that you call Relocate with some state when you redirect, and the URL which you relocated calls GetState to get the data (if any).</p>\n\n<pre><code>const string StateCookieName = \"state\";\n\nstatic int StateCookieID;\n\nprotected void Relocate(string url, object state)\n{\n var key = \"__\" + StateCookieName + Interlocked\n .Add(ref StateCookieID, 1).ToInvariantString();\n\n var absoluteExpiration = DateTime.Now\n .Add(new TimeSpan(120 * TimeSpan.TicksPerSecond));\n\n Context.Cache.Insert(key, state, null, absoluteExpiration,\n Cache.NoSlidingExpiration);\n\n var path = Context.Response.ApplyAppPathModifier(url);\n\n Context.Response.Cookies\n .Add(new HttpCookie(StateCookieName, key)\n {\n Path = path,\n Expires = absoluteExpiration\n });\n\n Context.Response.Redirect(path, false);\n}\n\nprotected TData GetState<TData>()\n where TData : class\n{\n var cookie = Context.Request.Cookies[StateCookieName];\n if (cookie != null)\n {\n var key = cookie.Value;\n if (key.IsNonEmpty())\n {\n var obj = Context.Cache.Remove(key);\n\n Context.Response.Cookies\n .Add(new HttpCookie(StateCookieName)\n { \n Path = cookie.Path, \n Expires = new DateTime(1970, 1, 1) \n });\n\n return obj as TData;\n }\n }\n return null;\n}\n</code></pre>\n"
},
{
"answer_id": 2802848,
"author": "Pavlo Neiman",
"author_id": 164001,
"author_profile": "https://Stackoverflow.com/users/164001",
"pm_score": 7,
"selected": false,
"text": "<p>You can use this aproach:</p>\n\n<pre><code>Response.Clear();\n\nStringBuilder sb = new StringBuilder();\nsb.Append(\"<html>\");\nsb.AppendFormat(@\"<body onload='document.forms[\"\"form\"\"].submit()'>\");\nsb.AppendFormat(\"<form name='form' action='{0}' method='post'>\",postbackUrl);\nsb.AppendFormat(\"<input type='hidden' name='id' value='{0}'>\", id);\n// Other params go here\nsb.Append(\"</form>\");\nsb.Append(\"</body>\");\nsb.Append(\"</html>\");\n\nResponse.Write(sb.ToString());\n\nResponse.End();\n</code></pre>\n\n<p>As result right after client will get all html from server the event <strong>onload</strong> take place that triggers form submit and post all data to defined postbackUrl.</p>\n"
},
{
"answer_id": 2825011,
"author": "Mike K",
"author_id": 45606,
"author_profile": "https://Stackoverflow.com/users/45606",
"pm_score": 3,
"selected": false,
"text": "<p>Something new in ASP.Net 3.5 is this \"PostBackUrl\" property of ASP buttons. You can set it to the address of the page you want to post directly to, and when that button is clicked, instead of posting back to the same page like normal, it instead posts to the page you've indicated. Handy. Be sure UseSubmitBehavior is also set to TRUE.</p>\n"
},
{
"answer_id": 12175053,
"author": "ZooZ",
"author_id": 772930,
"author_profile": "https://Stackoverflow.com/users/772930",
"pm_score": 3,
"selected": false,
"text": "<p>This should make life much easier.\nYou can simply use Response.RedirectWithData(...) method in your web application easily.</p>\n\n<pre><code>Imports System.Web\nImports System.Runtime.CompilerServices\n\nModule WebExtensions\n\n <Extension()> _\n Public Sub RedirectWithData(ByRef aThis As HttpResponse, ByVal aDestination As String, _\n ByVal aData As NameValueCollection)\n aThis.Clear()\n Dim sb As StringBuilder = New StringBuilder()\n\n sb.Append(\"<html>\")\n sb.AppendFormat(\"<body onload='document.forms[\"\"form\"\"].submit()'>\")\n sb.AppendFormat(\"<form name='form' action='{0}' method='post'>\", aDestination)\n\n For Each key As String In aData\n sb.AppendFormat(\"<input type='hidden' name='{0}' value='{1}' />\", key, aData(key))\n Next\n\n sb.Append(\"</form>\")\n sb.Append(\"</body>\")\n sb.Append(\"</html>\")\n\n aThis.Write(sb.ToString())\n\n aThis.End()\n End Sub\n\nEnd Module\n</code></pre>\n"
},
{
"answer_id": 19598053,
"author": "jacob",
"author_id": 1784298,
"author_profile": "https://Stackoverflow.com/users/1784298",
"pm_score": 3,
"selected": false,
"text": "<p>Thought it might interesting to share that heroku does this with it's SSO to Add-on providers</p>\n\n<p>An example of how it works can be seen in the source to the \"kensa\" tool:</p>\n\n<p><a href=\"https://github.com/heroku/kensa/blob/d4a56d50dcbebc2d26a4950081acda988937ee10/lib/heroku/kensa/post_proxy.rb\" rel=\"noreferrer\">https://github.com/heroku/kensa/blob/d4a56d50dcbebc2d26a4950081acda988937ee10/lib/heroku/kensa/post_proxy.rb</a></p>\n\n<p>And can be seen in practice if you turn of javascript. Example page source:</p>\n\n<pre><code><!DOCTYPE HTML>\n<html>\n <head>\n <meta http-equiv=\"Content-Type\" content=\"text/html; charset=utf-8\" />\n <title>Heroku Add-ons SSO</title>\n </head>\n\n <body>\n <form method=\"POST\" action=\"https://XXXXXXXX/sso/login\">\n\n <input type=\"hidden\" name=\"email\" value=\"XXXXXXXX\" />\n\n <input type=\"hidden\" name=\"app\" value=\"XXXXXXXXXX\" />\n\n <input type=\"hidden\" name=\"id\" value=\"XXXXXXXX\" />\n\n <input type=\"hidden\" name=\"timestamp\" value=\"1382728968\" />\n\n <input type=\"hidden\" name=\"token\" value=\"XXXXXXX\" />\n\n <input type=\"hidden\" name=\"nav-data\" value=\"XXXXXXXXX\" />\n\n </form>\n\n <script type=\"text/javascript\">\n document.forms[0].submit();\n </script>\n </body>\n</html>\n</code></pre>\n"
},
{
"answer_id": 54929640,
"author": "Zar Shardan",
"author_id": 913845,
"author_profile": "https://Stackoverflow.com/users/913845",
"pm_score": 1,
"selected": false,
"text": "<p>Copy-pasteable code based on <a href=\"https://stackoverflow.com/a/2802848/913845\">Pavlo Neyman's method</a></p>\n\n<p>RedirectPost(string url, T bodyPayload) and GetPostData() are for those who just want to dump some strongly typed data in the source page and fetch it back in the target one.\nThe data must be serializeable by NewtonSoft Json.NET and you need to reference the library of course.</p>\n\n<p>Just copy-paste into your page(s) or better yet base class for your pages and use it anywhere in you application. </p>\n\n<p>My heart goes out to all of you who still have to use Web Forms in 2019 for whatever reason.</p>\n\n<pre><code> protected void RedirectPost(string url, IEnumerable<KeyValuePair<string,string>> fields)\n {\n Response.Clear();\n\n const string template =\n@\"<html>\n<body onload='document.forms[\"\"form\"\"].submit()'>\n<form name='form' action='{0}' method='post'>\n{1}\n</form>\n</body>\n</html>\";\n\n var fieldsSection = string.Join(\n Environment.NewLine,\n fields.Select(x => $\"<input type='hidden' name='{HttpUtility.UrlEncode(x.Key)}' value='{HttpUtility.UrlEncode(x.Value)}'>\")\n );\n\n var html = string.Format(template, HttpUtility.UrlEncode(url), fieldsSection);\n\n Response.Write(html);\n\n Response.End();\n }\n\n private const string JsonDataFieldName = \"_jsonData\";\n\n protected void RedirectPost<T>(string url, T bodyPayload)\n {\n var json = JsonConvert.SerializeObject(bodyPayload, Formatting.Indented);\n //explicit type declaration to prevent recursion\n IEnumerable<KeyValuePair<string, string>> postFields = new List<KeyValuePair<string, string>>()\n {new KeyValuePair<string, string>(JsonDataFieldName, json)};\n\n RedirectPost(url, postFields);\n\n }\n\n protected T GetPostData<T>() where T: class \n {\n var urlEncodedFieldData = Request.Params[JsonDataFieldName];\n if (string.IsNullOrEmpty(urlEncodedFieldData))\n {\n return null;// default(T);\n }\n\n var fieldData = HttpUtility.UrlDecode(urlEncodedFieldData);\n\n var result = JsonConvert.DeserializeObject<T>(fieldData);\n return result;\n }\n</code></pre>\n"
}
] | 2008/09/05 | [
"https://Stackoverflow.com/questions/46582",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/232/"
] | We have the requirement to take a form submission and save some data, then redirect the user to a page offsite, but in redirecting, we need to "submit" a form with POST, not GET.
I was hoping there was an easy way to accomplish this, but I'm starting to think there isn't. I think I must now create a simple other page, with just the form that I want, redirect to it, populate the form variables, then do a body.onload call to a script that merely calls document.forms[0].submit();
Can anyone tell me if there is an alternative? We might need to tweak this later in the project, and it might get sort of complicated, so if there was an easy we could do this all non-other page dependent that would be fantastic.
Anyway, thanks for any and all responses. | Doing this requires understanding how HTTP redirects work. When you use `Response.Redirect()`, you send a response (to the browser that made the request) with [HTTP Status Code 302](http://en.wikipedia.org/wiki/HTTP_302), which tells the browser where to go next. By definition, the browser will make that via a `GET` request, even if the original request was a `POST`.
Another option is to use [HTTP Status Code 307](http://en.wikipedia.org/wiki/List_of_HTTP_status_codes#3xx_Redirection), which specifies that the browser should make the redirect request in the same way as the original request, but to prompt the user with a security warning. To do that, you would write something like this:
```
public void PageLoad(object sender, EventArgs e)
{
// Process the post on your side
Response.Status = "307 Temporary Redirect";
Response.AddHeader("Location", "http://example.com/page/to/post.to");
}
```
Unfortunately, this won't always work. [Different browsers implement this differently](http://ilia.ws/archives/152-Cross-Domain-POST-Redirection.html), since it is not a common status code.
>
> Alas, unlike the Opera and FireFox developers, the IE developers have never read the spec, and even the latest, most secure IE7 will redirect the POST request from domain A to domain B without any warnings or confirmation dialogs! Safari also acts in an interesting manner, while it does not raise a confirmation dialog and performs the redirect, it throws away the POST data, **effectively changing 307 redirect into the more common 302.**
>
>
>
So, as far as I know, the only way to implement something like this would be to use Javascript. There are two options I can think of off the top of my head:
1. Create the form and have its `action` attribute point to the third-party server. Then, add a click event to the submit button that first executes an AJAX request to your server with the data, and then allows the form to be submitted to the third-party server.
2. Create the form to post to your server. When the form is submitted, show the user a page that has a form in it with all of the data you want to pass on, all in hidden inputs. Just show a message like "Redirecting...". Then, add a javascript event to the page that submits the form to the third-party server.
Of the two, I would choose the second, for two reasons. First, it is more reliable than the first because Javascript is not required for it to work; for those who don't have it enabled, you can always make the submit button for the hidden form visible, and instruct them to press it if it takes more than 5 seconds. Second, you can decide what data gets transmitted to the third-party server; if you use just process the form as it goes by, you will be passing along all of the post data, which is not always what you want. Same for the 307 solution, assuming it worked for all of your users.
Hope this helps! |
46,585 | <p>From what I can gather, there are three categories:</p>
<ol>
<li>Never use <code>GET</code> and use <code>POST</code></li>
<li>Never use <code>POST</code> and use <code>GET</code></li>
<li>It doesn't matter which one you use.</li>
</ol>
<p>Am I correct in assuming those three cases? If so, what are some examples from each case?</p>
| [
{
"answer_id": 46591,
"author": "Kyle Cronin",
"author_id": 658,
"author_profile": "https://Stackoverflow.com/users/658",
"pm_score": 3,
"selected": false,
"text": "<p>Use GET when you want the URL to reflect the state of the page. This is useful for viewing dynamically generated pages, such as those seen here. A POST should be used in a form to submit data, like when I click the \"Post Your Answer\" button. It also produces a cleaner URL since it doesn't generate a parameter string after the path.</p>\n"
},
{
"answer_id": 46594,
"author": "Douglas Leeder",
"author_id": 3978,
"author_profile": "https://Stackoverflow.com/users/3978",
"pm_score": 6,
"selected": false,
"text": "<p>Use GET if you don't mind the request being repeated (That is it doesn't change state).</p>\n\n<p>Use POST if the operation does change the system's state.</p>\n"
},
{
"answer_id": 46595,
"author": "Chris Miller",
"author_id": 206,
"author_profile": "https://Stackoverflow.com/users/206",
"pm_score": 1,
"selected": false,
"text": "<p>The original intent was that GET was used for getting data back and POST was to be anything. The rule of thumb that I use is that if I'm sending anything back to the server, I use POST. If I'm just calling an URL to get back data, I use GET.</p>\n"
},
{
"answer_id": 46598,
"author": "TonyLa",
"author_id": 1295,
"author_profile": "https://Stackoverflow.com/users/1295",
"pm_score": 3,
"selected": false,
"text": "<p>My general rule of thumb is to use Get when you are making requests to the server that aren't going to alter state. Posts are reserved for requests to the server that alter state. </p>\n"
},
{
"answer_id": 46602,
"author": "John Boker",
"author_id": 2847,
"author_profile": "https://Stackoverflow.com/users/2847",
"pm_score": 2,
"selected": false,
"text": "<p>I use POST when I don't want people to see the QueryString or when the QueryString gets large. Also, POST is needed for file uploads.</p>\n\n<p>I don't see a problem using GET though, I use it for simple things where it makes sense to keep things on the QueryString.</p>\n\n<p>Using GET will allow linking to a particular page possible too where POST would not work.</p>\n"
},
{
"answer_id": 46614,
"author": "Brian Warshaw",
"author_id": 1344,
"author_profile": "https://Stackoverflow.com/users/1344",
"pm_score": 10,
"selected": true,
"text": "<p>Use <code>POST</code> for destructive actions such as creation (I'm aware of the irony), editing, and deletion, because you can't hit a <code>POST</code> action in the address bar of your browser. Use <code>GET</code> when it's safe to allow a person to call an action. So a URL like:</p>\n\n<pre><code>http://myblog.org/admin/posts/delete/357\n</code></pre>\n\n<p>Should bring you to a confirmation page, rather than simply deleting the item. It's far easier to avoid accidents this way.</p>\n\n<p><code>POST</code> is also more secure than <code>GET</code>, because you aren't sticking information into a URL. And so using <code>GET</code> as the <code>method</code> for an HTML form that collects a password or other sensitive information is not the best idea.</p>\n\n<p>One final note: <code>POST</code> can transmit a larger amount of information than <code>GET</code>. 'POST' has no size restrictions for transmitted data, whilst 'GET' is limited to 2048 characters.</p>\n"
},
{
"answer_id": 46617,
"author": "ceejayoz",
"author_id": 1902010,
"author_profile": "https://Stackoverflow.com/users/1902010",
"pm_score": 2,
"selected": false,
"text": "<blockquote>\n <p>i dont see a problem using get though, i use it for simple things where it makes sense to keep things on the query string.</p>\n</blockquote>\n\n<p>Using it to update state - like a GET of <code>delete.php?id=5</code> to delete a page - is very risky. People found that out when Google's web accelerator started prefetching URLs on pages - it hit all the 'delete' links and wiped out peoples' data. Same thing can happen with search engine spiders.</p>\n"
},
{
"answer_id": 46639,
"author": "reefnet_alex",
"author_id": 2745,
"author_profile": "https://Stackoverflow.com/users/2745",
"pm_score": 8,
"selected": false,
"text": "<p><strong>In brief</strong></p>\n\n<ul>\n<li>Use <code>GET</code> for <code>safe and</code><a href=\"https://stackoverflow.com/questions/1077412/what-is-an-idempotent-operation\"><code>idempotent</code></a> requests</li>\n<li>Use <code>POST</code> for <code>neither safe nor idempotent</code> requests</li>\n</ul>\n\n<hr>\n\n<p><strong>In details</strong>\nThere is a proper place for each. Even if you don't follow <a href=\"http://en.wikipedia.org/wiki/REST\" rel=\"noreferrer\">RESTful</a> principles, a lot can be gained from learning about REST and how a resource oriented approach works. </p>\n\n<blockquote>\n <p>A RESTful application will <code>use GETs</code> for operations which are both <code>safe and idempotent</code>. </p>\n</blockquote>\n\n<p>A <code>safe</code> operation is an operation which does <code>not change the data</code> requested. </p>\n\n<p>An <code>idempotent</code> operation is one in which the result will <code>be the same</code> no matter how many times you request it. </p>\n\n<p>It stands to reason that, as GETs are used for <em>safe</em> operations they are automatically also <em>idempotent</em>. Typically a GET is used for retrieving a resource (a question and its associated answers on stack overflow for example) or collection of resources. </p>\n\n<blockquote>\n <p>A RESTful app will use <code>PUTs</code> for operations which are <code>not safe but idempotent</code>. </p>\n</blockquote>\n\n<p>I know the question was about GET and POST, but I'll return to POST in a second.</p>\n\n<p>Typically a PUT is used for editing a resource (editing a question or an answer on stack overflow for example). </p>\n\n<blockquote>\n <p>A <code>POST</code> would be used for any operation which is <code>neither safe or idempotent</code>. </p>\n</blockquote>\n\n<p>Typically a POST would be used to create a new resource for example creating a NEW SO question (though in some designs a PUT would be used for this also). </p>\n\n<p>If you run the POST twice you would end up creating TWO new questions.</p>\n\n<blockquote>\n <p>There's also a DELETE operation, but I'm guessing I can leave that there :)</p>\n</blockquote>\n\n<p><strong>Discussion</strong></p>\n\n<p>In practical terms modern web browsers typically only support GET and POST reliably (you can perform all of these operations via javascript calls, but in terms of entering data in forms and pressing submit you've generally got the two options). In a RESTful application the POST will often be overriden to provide the PUT and DELETE calls also. </p>\n\n<p>But, even if you are not following RESTful principles, it can be useful to think in terms of using GET for retrieving / viewing information and POST for creating / editing information.</p>\n\n<p>You should never use GET for an operation which alters data. If a search engine crawls a link to your evil op, or the client bookmarks it could spell big trouble. </p>\n"
},
{
"answer_id": 46666,
"author": "kemiller2002",
"author_id": 1942,
"author_profile": "https://Stackoverflow.com/users/1942",
"pm_score": 2,
"selected": false,
"text": "<p>This traverses into the concept of REST and how the web was kinda intended on being used. There is an excellent <a href=\"http://www.se-radio.net/2008/05/episode-98-stefan-tilkov-on-rest/\" rel=\"nofollow noreferrer\">podcast</a> on Software Engineering radio that gives an in depth talk about the use of Get and Post.</p>\n\n<p>Get is used to pull data from the server, where an update action shouldn't be needed. The idea being is that you should be able to use the same GET request over and over and have the same information returned. The URL has the get information in the query string, because it was meant to be able to be easily sent to other systems and people like a address on where to find something. </p>\n\n<p>Post is supposed to be used (at least by the REST architecture which the web is kinda based on) for pushing information to the server/telling the server to perform an action. Examples like: Update this data, Create this record. </p>\n"
},
{
"answer_id": 46737,
"author": "Brian Warshaw",
"author_id": 1344,
"author_profile": "https://Stackoverflow.com/users/1344",
"pm_score": -1,
"selected": false,
"text": "<p>Gorgapor, <code>mod_rewrite</code> still often utilizes <code>GET</code>. It just allows to translate a friendlier URL into a URL with a <code>GET</code> query string.</p>\n"
},
{
"answer_id": 47335,
"author": "davenpcj",
"author_id": 4777,
"author_profile": "https://Stackoverflow.com/users/4777",
"pm_score": 3,
"selected": false,
"text": "<p>Because GETs are purely URLs, they can be cached by the web browser and may be better used for things like consistently generated images. (Set an Expiry time)</p>\n\n<p>One example from the gravatar page: <a href=\"http://www.gravatar.com/avatar/4c3be63a4c2f539b013787725dfce802?d=monsterid\" rel=\"noreferrer\">http://www.gravatar.com/avatar/4c3be63a4c2f539b013787725dfce802?d=monsterid</a></p>\n\n<p>GET may yeild marginally better performance, some webservers write POST contents to a temporary file before invoking the handler.</p>\n\n<p>Another thing to consider is the size limit. GETs are capped by the size of the URL, 1024 bytes by the standard, though browsers may support more.</p>\n\n<p>Transferring more data than that should use a POST to get better browser compatibility. </p>\n\n<p>Even less than that limit is a problem, as another poster wrote, anything in the URL could end up in other parts of the brower's UI, like history.</p>\n"
},
{
"answer_id": 943861,
"author": "Cimplicity",
"author_id": 110161,
"author_profile": "https://Stackoverflow.com/users/110161",
"pm_score": 6,
"selected": false,
"text": "<h2>Short Version</h2>\n\n<p>GET: Usually used for submitted search requests, or any request where you want the user to be able to pull up the exact page again.</p>\n\n<p>Advantages of GET:</p>\n\n<ul>\n<li>URLs can be bookmarked safely.</li>\n<li>Pages can be reloaded safely.</li>\n</ul>\n\n<p>Disadvantages of GET:</p>\n\n<ul>\n<li>Variables are passed through url as name-value pairs. (Security risk)</li>\n<li>Limited number of variables that can be passed. (Based upon browser. For example, <a href=\"http://support.microsoft.com/kb/208427\" rel=\"noreferrer\">Internet Explorer is limited to 2,048 characters.</a>)</li>\n</ul>\n\n<p>POST: Used for higher security requests where data may be used to alter a database, or a page that you don't want someone to bookmark. </p>\n\n<p>Advantages of POST:</p>\n\n<ul>\n<li>Name-value pairs are not displayed in url. (Security += 1)</li>\n<li>Unlimited number of name-value pairs can be passed via POST. <a href=\"http://support.microsoft.com/kb/208427\" rel=\"noreferrer\">Reference.</a></li>\n</ul>\n\n<p>Disadvantages of POST:</p>\n\n<ul>\n<li>Page that used POST data cannot be bookmark. (If you so desired.) </li>\n</ul>\n\n<h2>Longer Version</h2>\n\n<p>Directly from the <a href=\"http://www.w3.org/Protocols/rfc2616/rfc2616.html\" rel=\"noreferrer\">Hypertext Transfer Protocol -- HTTP/1.1</a>:</p>\n\n<blockquote>\n <h3>9.3 GET</h3>\n \n <p>The GET method means retrieve whatever information (in the form of an entity) is identified by the Request-URI. If the Request-URI refers to a data-producing process, it is the produced data which shall be returned as the entity in the response and not the source text of the process, unless that text happens to be the output of the process. </p>\n \n <p>The semantics of the GET method change to a \"conditional GET\" if the request message includes an If-Modified-Since, If-Unmodified-Since, If-Match, If-None-Match, or If-Range header field. A conditional GET method requests that the entity be transferred only under the circumstances described by the conditional header field(s). The conditional GET method is intended to reduce unnecessary network usage by allowing cached entities to be refreshed without requiring multiple requests or transferring data already held by the client. </p>\n \n <p>The semantics of the GET method change to a \"partial GET\" if the request message includes a Range header field. A partial GET requests that only part of the entity be transferred, as described in section 14.35. The partial GET method is intended to reduce unnecessary network usage by allowing partially-retrieved entities to be completed without transferring data already held by the client. </p>\n \n <p>The response to a GET request is cacheable if and only if it meets the requirements for HTTP caching described in section 13. </p>\n \n <p>See section 15.1.3 for security considerations when used for forms. </p>\n \n <h3>9.5 POST</h3>\n \n <p>The POST method is used to request that the origin server accept the\n entity enclosed in the request as a new subordinate of the resource\n identified by the Request-URI in the Request-Line. POST is designed\n to allow a uniform method to cover the following functions:</p>\n \n <ul>\n <li><p>Annotation of existing resources;</p></li>\n <li><p>Posting a message to a bulletin board, newsgroup, mailing list,\n or similar group of articles;</p></li>\n <li><p>Providing a block of data, such as the result of submitting a\n form, to a data-handling process;</p></li>\n <li><p>Extending a database through an append operation.</p></li>\n </ul>\n \n <p>The actual function performed by the POST method is determined by the\n server and is usually dependent on the Request-URI. The posted entity\n is subordinate to that URI in the same way that a file is subordinate\n to a directory containing it, a news article is subordinate to a\n newsgroup to which it is posted, or a record is subordinate to a\n database.</p>\n \n <p>The action performed by the POST method might not result in a\n resource that can be identified by a URI. In this case, either 200\n (OK) or 204 (No Content) is the appropriate response status,\n depending on whether or not the response includes an entity that\n describes the result.</p>\n</blockquote>\n"
},
{
"answer_id": 2267837,
"author": "ceejayoz",
"author_id": 1902010,
"author_profile": "https://Stackoverflow.com/users/1902010",
"pm_score": 3,
"selected": false,
"text": "<p>One practical difference is that browsers and webservers have a limit on the number of characters that can exist in a URL. It's different from application to application, but it's certainly possible to hit it if you've got <code>textarea</code>s in your forms.</p>\n\n<p>Another gotcha with GETs - they get indexed by search engines and other automatic systems. Google once had a product that would pre-fetch links on the page you were viewing, so they'd be faster to load if you clicked those links. It caused <strong>major</strong> havoc on sites that had links like <code>delete.php?id=1</code> - people lost their entire sites.</p>\n"
},
{
"answer_id": 2267841,
"author": "Pascal MARTIN",
"author_id": 138475,
"author_profile": "https://Stackoverflow.com/users/138475",
"pm_score": 5,
"selected": false,
"text": "<p>The first important thing is the <em>meaning</em> of GET versus POST :</p>\n\n<ul>\n<li>GET should be used to... get... some information <strong>from</strong> the server,</li>\n<li>while POST should be used to send some information <strong>to</strong> the server.</li>\n</ul>\n\n<p><br>\nAfter that, a couple of things that can be noted :</p>\n\n<ul>\n<li>Using GET, your users can use the \"back\" button in their browser, and they can bookmark pages</li>\n<li>There is a limit in the size of the parameters you can pass as GET <em>(2KB for some versions of Internet Explorer, if I'm not mistaken)</em> ; the limit is much more for POST, and generally depends on the server's configuration.</li>\n</ul>\n\n<p><br>\nAnyway, I don't think we could \"live\" without GET : think of how many URLs you are using with parameters in the query string, every day -- without GET, all those wouldn't work ;-)</p>\n"
},
{
"answer_id": 2267843,
"author": "Plynx",
"author_id": 254441,
"author_profile": "https://Stackoverflow.com/users/254441",
"pm_score": 0,
"selected": false,
"text": "<p>Another difference is that POST generally requires two HTTP operations, whereas GET only requires one.</p>\n\n<p>Edit: I should clarify--for common programming patterns. Generally responding to a POST with a straight up HTML web page is a questionable design for a variety of reasons, one of which is the annoying \"you must resubmit this form, do you wish to do so?\" on pressing the back button.</p>\n"
},
{
"answer_id": 2267844,
"author": "cherouvim",
"author_id": 72478,
"author_profile": "https://Stackoverflow.com/users/72478",
"pm_score": 2,
"selected": false,
"text": "<p>POST can move large data while GET cannot.</p>\n\n<p>But generally it's not about a shortcomming of GET, rather a convention if you want your website/webapp to be behaving nicely.</p>\n\n<p>Have a look at <a href=\"http://www.w3.org/2001/tag/doc/whenToUseGet.html\" rel=\"nofollow noreferrer\">http://www.w3.org/2001/tag/doc/whenToUseGet.html</a></p>\n"
},
{
"answer_id": 2267847,
"author": "Mark Byers",
"author_id": 61974,
"author_profile": "https://Stackoverflow.com/users/61974",
"pm_score": 4,
"selected": false,
"text": "<p>Apart from the length constraints difference in many web browsers, there is also a semantic difference. GETs are supposed to be \"safe\" in that they are read-only operations that don't change the server state. POSTs will typically change state and will give warnings on resubmission. Search engines' web crawlers may make GETs but should never make POSTs.</p>\n\n<p>Use GET if you want to read data without changing state, and use POST if you want to update state on the server.</p>\n"
},
{
"answer_id": 2267848,
"author": "prodigitalson",
"author_id": 215966,
"author_profile": "https://Stackoverflow.com/users/215966",
"pm_score": 0,
"selected": false,
"text": "<p>Well one major thing is anything you submit over <code>GET</code> is going to be exposed via the URL. Secondly as Ceejayoz says, there is a limit on characters for a URL. </p>\n"
},
{
"answer_id": 2267861,
"author": "mythz",
"author_id": 85785,
"author_profile": "https://Stackoverflow.com/users/85785",
"pm_score": -1,
"selected": false,
"text": "<p>HTTP Post data doesn't have a specified limit on the amount of data, where as different browsers have different limits for GET's. The RFC 2068 states:</p>\n\n<blockquote>\n <p>Servers should be cautious about\n depending on URI lengths above 255\n bytes, because some older client or\n proxy implementations may not properly\n support these lengths</p>\n</blockquote>\n\n<p>Specifically you should the right HTTP constructs for what they're used for. HTTP GET's shouldn't have side-effects and can be safely refreshed and stored by HTTP Proxies, etc.</p>\n\n<p>HTTP POST's are used when you want to submit data against a url resource.</p>\n\n<p>A typical example for using HTTP GET is on a Search, i.e. Search?Query=my+query\nA typical example for using a HTTP POST is submitting feedback to an online form.</p>\n"
},
{
"answer_id": 2267868,
"author": "Gili",
"author_id": 14731,
"author_profile": "https://Stackoverflow.com/users/14731",
"pm_score": 2,
"selected": false,
"text": "<p>There is nothing you can't do per-se. The point is that you're not <em>supposed</em> to modify the server state on an HTTP GET. HTTP proxies assume that since HTTP GET does not modify the state then whether a user invokes HTTP GET one time or 1000 times makes no difference. Using this information they assume it is safe to return a cached version of the first HTTP GET. If you break the HTTP specification you risk breaking HTTP client and proxies in the wild. Don't do it :)</p>\n"
},
{
"answer_id": 2267871,
"author": "Dmytro",
"author_id": 263321,
"author_profile": "https://Stackoverflow.com/users/263321",
"pm_score": 2,
"selected": false,
"text": "<p>From <a href=\"http://www.w3.org/Protocols/rfc2616/rfc2616-sec9.html\" rel=\"nofollow noreferrer\">RFC 2616</a>:</p>\n\n<blockquote>\n <p>9.3 <strong>GET</strong> <br/>\n The GET method means retrieve whatever information (in the form of\n an entity) is identified by the\n Request-URI. If the Request-URI refers\n to a data-producing process, it is the\n produced data which shall be returned\n as the entity in the response and not\n the source text of the process, unless\n that text happens to be the output of\n the process.</p>\n</blockquote>\n\n<p><br/></p>\n\n<blockquote>\n <p>9.5 <strong>POST</strong><br/> The POST method is used to request that the origin server\n accept the entity enclosed in the\n request as a new subordinate of the\n resource identified by the Request-URI\n in the Request-Line. POST is designed\n to allow a uniform method to cover the\n following functions: </p>\n \n <ul>\n <li>Annotation of existing resources;</li>\n <li>Posting a message to a bulletin board, newsgroup, mailing list, or\n similar group of articles;</li>\n <li>Providing a block of data, such as the result of submitting a form, to a\n data-handling process;</li>\n <li>Extending a database through an append operation.</li>\n </ul>\n \n <p>The actual function performed by the\n POST method is determined by the\n server and is usually dependent on the\n Request-URI. The posted entity is\n subordinate to that URI in the same\n way that a file is subordinate to a\n directory containing it, a news\n article is subordinate to a newsgroup\n to which it is posted, or a record is\n subordinate to a database. </p>\n \n <p>The action performed by the POST\n method might not result in a resource\n that can be identified by a URI. In\n this case, either 200 (OK) or 204 (No\n Content) is the appropriate response\n status, depending on whether or not\n the response includes an entity that\n describes the result.</p>\n</blockquote>\n"
},
{
"answer_id": 2267879,
"author": "Gordon",
"author_id": 208809,
"author_profile": "https://Stackoverflow.com/users/208809",
"pm_score": 1,
"selected": false,
"text": "<p>Read the <a href=\"http://en.wikipedia.org/wiki/Hypertext_Transfer_Protocol\" rel=\"nofollow noreferrer\">article about HTTP in the Wikipedia</a>. It will explain what the protocol is and what it does:</p>\n\n<blockquote>\n <p><strong>GET</strong> </p>\n \n <p>Requests a representation of the specified resource. Note that GET should not be used for operations that cause side-effects, such as using it for taking actions in web applications. One reason for this is that GET may be used arbitrarily by robots or crawlers, which should not need to consider the side effects that a request should cause. </p>\n</blockquote>\n\n<p>and </p>\n\n<blockquote>\n <p><strong>POST</strong>\n Submits data to be processed (e.g., from an HTML form) to the identified resource. The data is included in the body of the request. This may result in the creation of a new resource or the updates of existing resources or both.</p>\n</blockquote>\n\n<p>The W3C has a document named <a href=\"http://www.w3.org/2001/tag/doc/whenToUseGet.html\" rel=\"nofollow noreferrer\">URIs, Addressability, and the use of HTTP GET and POST</a> that explains when to use what. Citing </p>\n\n<blockquote>\n <p>1.3 Quick Checklist for Choosing HTTP GET or POST</p>\n \n <ul>\n <li>Use GET if:\n \n <ul>\n <li>The interaction is more like a question (i.e., it is a \n safe operation such as a query, read operation, or lookup).</li>\n </ul></li>\n </ul>\n</blockquote>\n\n<p>and</p>\n\n<blockquote>\n <ul>\n <li>Use POST if:\n \n <ul>\n <li>The interaction is more like an order, or</li>\n <li>The interaction changes the state of the resource in a way that the user would perceive (e.g., a subscription to a service), or\n o The user be held accountable for the results of the interaction.</li>\n </ul></li>\n </ul>\n \n <p>However, before the final decision to use HTTP GET or POST, please also consider considerations for sensitive data and practical considerations.</p>\n</blockquote>\n\n<p>A practial example would be whenever you submit an HTML form. You specify either <em>post</em> or <em>get</em> for the form action. PHP will populate $_GET and $_POST accordingly.</p>\n"
},
{
"answer_id": 2268041,
"author": "Elizabeth Buckwalter",
"author_id": 167034,
"author_profile": "https://Stackoverflow.com/users/167034",
"pm_score": 0,
"selected": false,
"text": "<p>As answered by others, there's a limit on url size with get, and files can be submitted with post only.</p>\n\n<p>I'd like to add that one <b>can</b> add things to a database with a get and perform actions with a post. When a script receives a post or a get, it can do whatever the author wants it to do. I believe the lack of understanding comes from the wording the book chose or how you read it.</p>\n\n<p>A script author <b>should</b> use posts to change the database and use get only for retrieval of information. </p>\n\n<p>Scripting languages provided many means with which to access the request. For example, PHP allows the use of <code>$_REQUEST</code> to retrieve either a post or a get. One should avoid this in favor of the more specific <code>$_GET</code> or <code>$_POST</code>.</p>\n\n<p>In web programming, there's a lot more room for interpretation. There's what one <b>should</b> and what one <b>can</b> do, but which one is better is often up for debate. Luckily, in this case, there is no ambiguity. You <b>should</b> use posts to change data, and you <b>should</b> use get to retrieve information.</p>\n"
},
{
"answer_id": 2268326,
"author": "jellyfishtree",
"author_id": 273632,
"author_profile": "https://Stackoverflow.com/users/273632",
"pm_score": 1,
"selected": false,
"text": "<p>In PHP, <code>POST</code> data limit is usually set by your <code>php.ini</code>. <code>GET</code> is limited by server/browser settings I believe - usually around <code>255</code> bytes.</p>\n"
},
{
"answer_id": 18511298,
"author": "Anagha",
"author_id": 2063953,
"author_profile": "https://Stackoverflow.com/users/2063953",
"pm_score": 3,
"selected": false,
"text": "<p>1.3 Quick Checklist for Choosing HTTP <code>GET</code> or <code>POST</code></p>\n<h1>Use GET if:</h1>\n<pre><code> The interaction is more like a question (i.e., it is a safe operation such as a query, read operation, or lookup).\n</code></pre>\n<h1>Use POST if:</h1>\n<pre><code> The interaction is more like an order, or\n The interaction changes the state of the resource in a way that the user would perceive (e.g., a subscription to a service), or\n The user be held accountable for the results of the interaction.\n</code></pre>\n<p><a href=\"http://www.w3.org/2001/tag/doc/whenToUseGet.html#checklist\" rel=\"nofollow noreferrer\">Source</a>.</p>\n"
},
{
"answer_id": 33962313,
"author": "Rajesh",
"author_id": 2632634,
"author_profile": "https://Stackoverflow.com/users/2632634",
"pm_score": -1,
"selected": false,
"text": "<p>Simple version of POST GET PUT DELETE</p>\n\n<ul>\n<li>use GET - when you want to get any resource like List of data based on any Id or Name</li>\n<li>use POST - when you want to send any data to server. keep in mind POST is heavy weight operation because for updation we should use PUT instead of POST\ninternally POST will create new resource</li>\n<li>use PUT - when you</li>\n</ul>\n"
},
{
"answer_id": 35970239,
"author": "Madhusudhan Reddy",
"author_id": 5110404,
"author_profile": "https://Stackoverflow.com/users/5110404",
"pm_score": 1,
"selected": false,
"text": "<p>From <a href=\"http://www.w3schools.com/tags/ref_httpmethods.asp\" rel=\"nofollow noreferrer\">w3schools.com</a>:</p>\n\n<blockquote>\n <p>What is HTTP?</p>\n \n <p>The Hypertext Transfer Protocol (HTTP) is designed to enable\n communications between clients and servers.</p>\n \n <p>HTTP works as a request-response protocol between a client and server.</p>\n \n <p>A web browser may be the client, and an application on a computer that\n hosts a web site may be the server.</p>\n \n <p>Example: A client (browser) submits an HTTP request to the server;\n then the server returns a response to the client. The response\n contains status information about the request and may also contain the\n requested content.</p>\n \n <p>Two HTTP Request Methods: GET and POST</p>\n \n <p>Two commonly used methods for a request-response between a client and\n server are: GET and POST.</p>\n \n <p>GET – Requests data from a specified resource POST – Submits data to\n be processed to a specified resource</p>\n</blockquote>\n\n<p>Here we distinguish the major differences:</p>\n\n<p><img src=\"https://i.stack.imgur.com/2ELRX.jpg\" alt=\"enter image description here\"></p>\n"
}
] | 2008/09/05 | [
"https://Stackoverflow.com/questions/46585",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/572/"
] | From what I can gather, there are three categories:
1. Never use `GET` and use `POST`
2. Never use `POST` and use `GET`
3. It doesn't matter which one you use.
Am I correct in assuming those three cases? If so, what are some examples from each case? | Use `POST` for destructive actions such as creation (I'm aware of the irony), editing, and deletion, because you can't hit a `POST` action in the address bar of your browser. Use `GET` when it's safe to allow a person to call an action. So a URL like:
```
http://myblog.org/admin/posts/delete/357
```
Should bring you to a confirmation page, rather than simply deleting the item. It's far easier to avoid accidents this way.
`POST` is also more secure than `GET`, because you aren't sticking information into a URL. And so using `GET` as the `method` for an HTML form that collects a password or other sensitive information is not the best idea.
One final note: `POST` can transmit a larger amount of information than `GET`. 'POST' has no size restrictions for transmitted data, whilst 'GET' is limited to 2048 characters. |
46,586 | <p>Everyone is aware of Dijkstra's <a href="http://portal.acm.org/citation.cfm?doid=362947" rel="noreferrer">Letters to the editor: go to statement considered harmful</a> (also <a href="http://www.cs.utexas.edu/%7EEWD/transcriptions/EWD02xx/EWD215.html" rel="noreferrer">here</a> .html transcript and <a href="http://www.cs.utexas.edu/users/EWD/ewd02xx/EWD215.PDF" rel="noreferrer">here</a> .pdf) and there has been a formidable push since that time to eschew the goto statement whenever possible. While it's possible to use goto to produce unmaintainable, sprawling code, it nevertheless remains in <a href="http://msdn.microsoft.com/en-us/library/13940fs2(VS.71).aspx" rel="noreferrer">modern programming languages</a>. Even the advanced <a href="http://en.wikipedia.org/wiki/Goto#Continuations" rel="noreferrer">continuation</a> control structure in Scheme can be described as a sophisticated goto.</p>
<p>What circumstances warrant the use of goto? When is it best to avoid?</p>
<p>As a follow-up question: C provides a pair of functions, setjmp() and longjmp(), that provide the ability to goto not just within the current stack frame but within any of the calling frames. Should these be considered as dangerous as goto? More dangerous?</p>
<hr />
<p>Dijkstra himself regretted that title, for which he was not responsible. At the end of <a href="http://www.cs.utexas.edu/%7EEWD/transcriptions/EWD13xx/EWD1308.html" rel="noreferrer">EWD1308</a> (also <a href="http://www.cs.utexas.edu/%7EEWD/ewd13xx/EWD1308.PDF" rel="noreferrer">here</a> .pdf) he wrote:</p>
<blockquote>
<p>Finally a short story for the record.
In 1968, the Communications of the ACM
published a text of mine under the
title "<em>The goto statement considered
harmful</em>", which in later years would
be most frequently referenced,
regrettably, however, often by authors
who had seen no more of it than its
title, which became a cornerstone of
my fame by becoming a template: we
would see all sorts of articles under
the title "X considered harmful" for
almost any X, including one titled
"Dijkstra considered harmful". But
what had happened? I had submitted a
paper under the title "<em><strong>A case against
the goto statement</strong></em>", which, in order
to speed up its publication, the
editor had changed into a "letter to
the Editor", and in the process he had
given it a new title of his own
invention! The editor was Niklaus
Wirth.</p>
</blockquote>
<p>A well thought out classic paper about this topic, to be matched to that of Dijkstra, is <a href="http://www.clifford.at/cfun/cliffdev/p261-knuth.pdf" rel="noreferrer">Structured Programming with go to Statements</a>, by Donald E. Knuth. Reading both helps to reestablish context and a non-dogmatic understanding of the subject. In this paper, Dijkstra's opinion on this case is reported and is even more strong:</p>
<blockquote>
<p><em>Donald E. Knuth:</em> I believe that by presenting such a
view I am not in fact disagreeing
sharply with Dijkstra's ideas, since
he recently wrote the following:
"Please don't fall into the trap of
believing that I am terribly
dogmatical about [the go to
statement]. <strong>I have the uncomfortable
feeling that others are making a
religion out of it, as if the
conceptual problems of programming
could be solved by a single trick, by
a simple form of coding discipline!</strong>"</p>
</blockquote>
| [
{
"answer_id": 46597,
"author": "John Millikin",
"author_id": 3560,
"author_profile": "https://Stackoverflow.com/users/3560",
"pm_score": 3,
"selected": false,
"text": "<p>The original paper should be thought of as \"Unconditional GOTO Considered Harmful\". It was in particular advocating a form of programming based on conditional (<code>if</code>) and iterative (<code>while</code>) constructs, rather than the test-and-jump common to early code. <code>goto</code> is still useful in some languages or circumstances, where no appropriate control structure exists.</p>\n"
},
{
"answer_id": 46599,
"author": "Brian R. Bondy",
"author_id": 3153,
"author_profile": "https://Stackoverflow.com/users/3153",
"pm_score": 2,
"selected": false,
"text": "<p>You can use it for breaking from a deeply nested loop, but most of the time your code can be refactored to be cleaner without deeply nested loops. </p>\n"
},
{
"answer_id": 46635,
"author": "Lasse V. Karlsen",
"author_id": 267,
"author_profile": "https://Stackoverflow.com/users/267",
"pm_score": 4,
"selected": false,
"text": "<p>There is no such things as <em>GOTO considered harmful</em>.</p>\n\n<p>GOTO is a tool, and as all tools, it can be used and <em>abused</em>.</p>\n\n<p>There are, however, many tools in the programming world that have a tendency to be <em>abused</em> more than being <em>used</em>, and GOTO is one of them. the <em>WITH</em> statement of Delphi is another.</p>\n\n<p>Personally I don't use either <em>in typical code</em>, but I've had the odd usage of both <em>GOTO</em> and <em>WITH</em> that were warranted, and an alternative solution would've contained more code.</p>\n\n<p>The best solution would be for the compiler to just warn you that the keyword was <em>tainted</em>, and you'd have to stuff a couple of pragma directives around the statement to get rid of the warnings.</p>\n\n<p>It's like telling your kids to <em>not run with scissors</em>. Scissors are not bad, but some usage of them are perhaps not the best way to keep your health.</p>\n"
},
{
"answer_id": 46638,
"author": "Rob Walker",
"author_id": 3631,
"author_profile": "https://Stackoverflow.com/users/3631",
"pm_score": 7,
"selected": false,
"text": "<p>Sometimes it is valid to use GOTO as an alternative to exception handling within a single function:</p>\n<pre class=\"lang-c prettyprint-override\"><code> if (f() == false) goto err_cleanup;\n if (g() == false) goto err_cleanup;\n if (h() == false) goto err_cleanup;\n \n return;\n \n err_cleanup:\n ...\n</code></pre>\n<p>COM code seems to fall into this pattern fairly often.</p>\n"
},
{
"answer_id": 46658,
"author": "Brian Leahy",
"author_id": 580,
"author_profile": "https://Stackoverflow.com/users/580",
"pm_score": 3,
"selected": false,
"text": "<p>One modern GOTO usage is by the C# compiler to create state machines for enumerators defined by yield return.</p>\n\n<p>GOTO is something that should be used by compilers and not programmers.</p>\n"
},
{
"answer_id": 46661,
"author": "DevelopingChris",
"author_id": 1220,
"author_profile": "https://Stackoverflow.com/users/1220",
"pm_score": 2,
"selected": false,
"text": "<p>GOTO is like a table saw, extremely useful when appropriate safety measures are taken.</p>\n\n<p>I consider it harmful, because most beginners lose fingers with both table saws, and GOTOs.</p>\n\n<p>There are some situations where its the only way to control flow, but those situations can be avoided.</p>\n"
},
{
"answer_id": 46665,
"author": "Christian Oudard",
"author_id": 3757,
"author_profile": "https://Stackoverflow.com/users/3757",
"pm_score": 0,
"selected": false,
"text": "<p>The basic idea is that goto gives you too much freedom to do something you didn't intend to. It can cause errors in places that don't appear to be related to the goto statement, so it makes code maintenance more difficult. If you think you need a goto statement, you're wrong :) and you should instead rethink your code construction. This is why modern programming languages have put alot of effort into giving you readable, maintainable flow control constructs, and exception handling mechanisms.</p>\n\n<p>I'm also going to disagree with lassevk. Since goto is abused more than correctly used, I believe it has no place in a well designed language. Even for goto's \"ideal\" uses, the other ways of doing it which require more code should be preferred.</p>\n\n<p>So in summary, yes it is still considered harmful.</p>\n"
},
{
"answer_id": 46732,
"author": "Adam Davis",
"author_id": 2915,
"author_profile": "https://Stackoverflow.com/users/2915",
"pm_score": 3,
"selected": false,
"text": "<p>About the only place I agree Goto <em>could</em> be used is when you need to deal with errors, and each particular point an error occurs requires special handling.</p>\n\n<p>For instance, if you're grabbing resources and using semaphores or mutexes, you have to grab them in order and you should always release them in the opposite manner.</p>\n\n<p>Some code requires a very odd pattern of grabbing these resources, and you can't just write an easily maintained and understood control structure to correctly handle both the grabbing and releasing of these resources to avoid deadlock.</p>\n\n<p>It's always possible to do it right without goto, but in this case and a few others Goto is actually the better solution primarily for readability and maintainability.</p>\n\n<p>-Adam</p>\n"
},
{
"answer_id": 46789,
"author": "Jim McKeeth",
"author_id": 255,
"author_profile": "https://Stackoverflow.com/users/255",
"pm_score": 8,
"selected": false,
"text": "<p><a href=\"http://xkcd.com/292/\" rel=\"noreferrer\"><img src=\"https://i.stack.imgur.com/6C1F5.png\" alt=\"XKCD's GOTO Comic\" title=\"Neal Stephenson thinks it's cute to name his labels 'dengo'\"></a></p>\n\n<p>A coworker of mine said the only reason to use a GOTO is if you programmed yourself so far into a corner that it is the only way out. In other words, proper design ahead of time and you won't need to use a GOTO later. </p>\n\n<p>I thought this comic illustrates that beautifully \"I could restructure the program's flow, or use one little 'GOTO' instead.\" A GOTO is a weak way out when you have weak design. <em>Velociraptors prey on the weak</em>. </p>\n"
},
{
"answer_id": 46809,
"author": "Aardvark",
"author_id": 3655,
"author_profile": "https://Stackoverflow.com/users/3655",
"pm_score": 2,
"selected": false,
"text": "<p>I avoid it since a coworker/manager will undoubtedly question its use either in a code review or when they stumble across it. While I think it has uses (the error handling case for example) - you'll run afoul of some other developer who will have some type of problem with it. </p>\n\n<p>It’s not worth it.</p>\n"
},
{
"answer_id": 46852,
"author": "bruceatk",
"author_id": 791,
"author_profile": "https://Stackoverflow.com/users/791",
"pm_score": 1,
"selected": false,
"text": "<p>I only have the need for it in Basic (ie. VB, VBScript, etc.) and batch files. I then only use it for error handling. In Basic I tend only use the \"on error goto\". In batch files I have to use it because there isn't an else command. I then only use them as forward jumps to meaningful labels.</p>\n"
},
{
"answer_id": 47461,
"author": "Marcio Aguiar",
"author_id": 4213,
"author_profile": "https://Stackoverflow.com/users/4213",
"pm_score": 6,
"selected": false,
"text": "<p>In <a href=\"http://web.archive.org/web/20130521051957/http://kerneltrap.org/node/553/2131\" rel=\"noreferrer\">Linux: Using goto In Kernel Code</a> on Kernel Trap, there's a discussion with Linus Torvalds and a \"new guy\" about the use of GOTOs in Linux code. There are some very good points there and Linus dressed in that usual arrogance :)</p>\n\n<p>Some passages:</p>\n\n<blockquote>\n <p>Linus: \"No, you've been brainwashed by\n CS people who thought that Niklaus\n Wirth actually knew what he was\n talking about. He didn't. He doesn't\n have a frigging clue.\"</p>\n</blockquote>\n\n<p>-</p>\n\n<blockquote>\n <p>Linus: \"I think goto's are fine, and\n they are often more readable than\n large amounts of indentation.\"</p>\n</blockquote>\n\n<p>-</p>\n\n<blockquote>\n <p>Linus: \"Of course, in stupid languages\n like Pascal, where labels cannot be \n descriptive, goto's can be bad.\"</p>\n</blockquote>\n"
},
{
"answer_id": 47467,
"author": "Bruno Ranschaert",
"author_id": 4900,
"author_profile": "https://Stackoverflow.com/users/4900",
"pm_score": 5,
"selected": false,
"text": "<p>Donald E. Knuth answered this question in the book \"Literate Programming\", 1992 CSLI. On p. 17 there is an essay \"<a href=\"http://pplab.snu.ac.kr/courses/adv_pl05/papers/p261-knuth.pdf\" rel=\"noreferrer\">Structured Programming with goto Statements</a>\" (PDF). I think the article might have been published in other books as well.</p>\n\n<p>The article describes Dijkstra's suggestion and describes the circumstances where this is valid. But he also gives a number of counter examples (problems and algorithms) which cannot be easily reproduced using structured loops only.</p>\n\n<p>The article contains a complete description of the problem, the history, examples and counter examples.</p>\n"
},
{
"answer_id": 47472,
"author": "shsteimer",
"author_id": 292,
"author_profile": "https://Stackoverflow.com/users/292",
"pm_score": 7,
"selected": false,
"text": "<p>I can only recall using a goto once. I had a series of five nested counted loops and I needed to be able to break out of the entire structure from the inside early based on certain conditions:</p>\n<pre class=\"lang-c prettyprint-override\"><code> for{\n for{\n for{\n for{\n for{\n if(stuff){\n GOTO ENDOFLOOPS;\n }\n }\n }\n }\n }\n }\n \n ENDOFLOOPS:\n</code></pre>\n<p>I could just have easily declared a boolean break variable and used it as part of the conditional for each loop, but in this instance I decided a GOTO was just as practical and just as readable.</p>\n<p><strong>No velociraptors attacked me.</strong></p>\n"
},
{
"answer_id": 47476,
"author": "Konrad Rudolph",
"author_id": 1968,
"author_profile": "https://Stackoverflow.com/users/1968",
"pm_score": 7,
"selected": false,
"text": "<p>We already had this <a href=\"https://stackoverflow.com/questions/24451/goto-usage\">discussion</a> and I stand by <a href=\"https://stackoverflow.com/questions/24451/goto-usage#24475\">my point</a>.</p>\n\n<p>Furthermore, I'm fed up with people describing higher-level language structures as “<code>goto</code> in disguise” because they clearly haven't got the point <em>at all</em>. For example:</p>\n\n<blockquote>\n <p>Even the advanced continuation control structure in Scheme can be described as a sophisticated goto.</p>\n</blockquote>\n\n<p>That is complete nonsense. <em>Every</em> control structure can be implemented in terms of <code>goto</code> but this observation is utterly trivial and useless. <code>goto</code> isn't considered harmful because of its positive effects but because of its negative consequences and these have been eliminated by structured programming.</p>\n\n<p>Similarly, saying “GOTO is a tool, and as all tools, it can be used and abused” is completely off the mark. No modern construction worker would use a rock and claim it “is a tool.” Rocks have been replaced by hammers. <code>goto</code> has been replaced by control structures. If the construction worker were stranded in the wild without a hammer, of course he would use a rock instead. If a programmer has to use an inferior programming language that doesn't have feature X, well, of course she may have to use <code>goto</code> instead. But if she uses it anywhere else instead of the appropriate language feature she clearly hasn't understood the language properly and uses it wrongly. It's really as simple as that.</p>\n"
},
{
"answer_id": 47512,
"author": "DrPizza",
"author_id": 2131,
"author_profile": "https://Stackoverflow.com/users/2131",
"pm_score": 3,
"selected": false,
"text": "<p>Until C and C++ (amongst other culprits) have labelled breaks and continues, goto will continue to have a role.</p>\n"
},
{
"answer_id": 47517,
"author": "smh",
"author_id": 1077,
"author_profile": "https://Stackoverflow.com/users/1077",
"pm_score": 6,
"selected": false,
"text": "<p>In C, <code>goto</code> only works within the scope of the current function, which tends to localise any potential bugs. <code>setjmp</code> and <code>longjmp</code> are far more dangerous, being non-local, complicated and implementation-dependent. In practice however, they're too obscure and uncommon to cause many problems.</p>\n\n<p>I believe that the danger of <code>goto</code> in C is greatly exaggerated. Remember that the original <code>goto</code> arguments took place back in the days of languages like old-fashioned BASIC, where beginners would write spaghetti code like this:</p>\n\n<pre><code>3420 IF A > 2 THEN GOTO 1430\n</code></pre>\n\n<p>Here Linus describes an appropriate use of <code>goto</code>: <a href=\"http://www.kernel.org/doc/Documentation/CodingStyle\" rel=\"noreferrer\">http://www.kernel.org/doc/Documentation/CodingStyle</a> (chapter 7).</p>\n"
},
{
"answer_id": 47590,
"author": "vt.",
"author_id": 3905,
"author_profile": "https://Stackoverflow.com/users/3905",
"pm_score": 4,
"selected": false,
"text": "<p>If you're writing a VM in C, it turns out that using (gcc's) computed gotos like this:</p>\n\n<pre><code>char run(char *pc) {\n void *opcodes[3] = {&&op_inc, &&op_lda_direct, &&op_hlt};\n #define NEXT_INSTR(stride) goto *(opcodes[*(pc += stride)])\n NEXT_INSTR(0);\n op_inc:\n ++acc;\n NEXT_INSTR(1);\n op_lda_direct:\n acc = ram[++pc];\n NEXT_INSTR(1);\n op_hlt:\n return acc;\n}</code></pre>\n\n<p>works much faster than the conventional switch inside a loop.</p>\n"
},
{
"answer_id": 52307,
"author": "joel.neely",
"author_id": 3525,
"author_profile": "https://Stackoverflow.com/users/3525",
"pm_score": 9,
"selected": true,
"text": "<p>The following statements are generalizations; while it is always possible to plead exception, it usually (in my experience and humble opinion) isn't worth the risks.</p>\n<ol>\n<li>Unconstrained use of memory addresses (either GOTO or raw pointers) provides too many opportunities to make easily avoidable mistakes.</li>\n<li>The more ways there are to arrive at a particular "location" in the code, the less confident one can be about what the state of the system is at that point. (See below.)</li>\n<li>Structured programming IMHO is less about "avoiding GOTOs" and more about making the structure of the code match the structure of the data. For example, a repeating data structure (e.g. array, sequential file, etc.) is naturally processed by a repeated unit of code. Having built-in structures (e.g. while, for, until, for-each, etc.) allows the programmer to avoid the tedium of repeating the same cliched code patterns.</li>\n<li>Even if GOTO is low-level implementation detail (not always the case!) it's below the level that the programmer should be thinking. How many programmers balance their personal checkbooks in raw binary? How many programmers worry about which sector on the disk contains a particular record, instead of just providing a key to a database engine (and how many ways could things go wrong if we really wrote all of our programs in terms of physical disk sectors)?</li>\n</ol>\n<p>Footnotes to the above:</p>\n<p>Regarding point 2, consider the following code:</p>\n<pre class=\"lang-c prettyprint-override\"><code> a = b + 1\n /* do something with a */\n</code></pre>\n<p>At the "do something" point in the code, we can state with high confidence that <code>a</code> is greater than <code>b</code>. (Yes, I'm ignoring the possibility of untrapped integer overflow. Let's not bog down a simple example.)</p>\n<p>On the other hand, if the code had read this way:</p>\n<pre class=\"lang-c prettyprint-override\"><code> ...\n goto 10\n ...\n a = b + 1\n 10: /* do something with a */\n ...\n goto 10\n ...\n</code></pre>\n<p>The multiplicity of ways to get to label 10 means that we have to work much harder to be confident about the relationships between <code>a</code> and <code>b</code> at that point. (In fact, in the general case it's undecideable!)</p>\n<p>Regarding point 4, the whole notion of "going someplace" in the code is just a metaphor. Nothing is really "going" anywhere inside the CPU except electrons and photons (for the waste heat). Sometimes we give up a metaphor for another, more useful, one. I recall encountering (a few decades ago!) a language where</p>\n<pre class=\"lang-c prettyprint-override\"><code> if (some condition) {\n action-1\n } else {\n action-2\n }\n</code></pre>\n<p>was implemented on a virtual machine by compiling action-1 and action-2 as out-of-line parameterless routines, then using a single two-argument VM opcode which used the boolean value of the condition to invoke one or the other. The concept was simply "choose what to invoke now" rather than "go here or go there". Again, just a change of metaphor.</p>\n"
},
{
"answer_id": 52345,
"author": "srclontz",
"author_id": 4606,
"author_profile": "https://Stackoverflow.com/users/4606",
"pm_score": 1,
"selected": false,
"text": "<p>Using a goto makes it far too easy to write \"spaghetti code\" which is not particularly maintainable. The most important rule to follow is to write readable code, but of course it depends on what the goals of the project are. As a \"best practice\" avoiding a goto is a good idea. It's something extreme programming types would refer to as \"code smell\" because it indicates that you may be doing something wrong. Using a break while looping is remarkably similar to a goto, except it isn't a goto, but again is an indication that the code may not be optimal. This is why, I believe, it is also important to not find more modern programming loopholes which are essentially a goto by a different name. </p>\n"
},
{
"answer_id": 119103,
"author": "Steve Jessop",
"author_id": 13005,
"author_profile": "https://Stackoverflow.com/users/13005",
"pm_score": 7,
"selected": false,
"text": "<p>Goto is extremely low on my list of things to include in a program just for the sake of it. That doesn't mean it's unacceptable.</p>\n\n<p>Goto can be nice for state machines. A switch statement in a loop is (in order of typical importance): (a) not actually representative of the control flow, (b) ugly, (c) potentially inefficient depending on language and compiler. So you end up writing one function per state, and doing things like \"return NEXT_STATE;\" which even look like goto.</p>\n\n<p>Granted, it is difficult to code state machines in a way which make them easy to understand. However, none of that difficulty is to do with using goto, and none of it can be reduced by using alternative control structures. Unless your language has a 'state machine' construct. Mine doesn't.</p>\n\n<p>On those rare occasions when your algorithm really is most comprehensible in terms of a path through a sequence of nodes (states) connected by a limited set of permissible transitions (gotos), rather than by any more specific control flow (loops, conditionals, whatnot), then that should be explicit in the code. And you ought to draw a pretty diagram.</p>\n\n<p>setjmp/longjmp can be nice for implementing exceptions or exception-like behaviour. While not universally praised, exceptions are generally considered a \"valid\" control structure.</p>\n\n<p>setjmp/longjmp are 'more dangerous' than goto in the sense that they're harder to use correctly, never mind comprehensibly.</p>\n\n<blockquote>\n <p>There never has been, nor will there\n ever be, any language in which it is\n the least bit difficult to write bad\n code. -- Donald Knuth.</p>\n</blockquote>\n\n<p>Taking goto out of C would not make it any easier to write good code in C. In fact, it would rather miss the point that C is <em>supposed</em> to be capable of acting as a glorified assembler language.</p>\n\n<p>Next it'll be \"pointers considered harmful\", then \"duck typing considered harmful\". Then who will be left to defend you when they come to take away your unsafe programming construct? Eh?</p>\n"
},
{
"answer_id": 122836,
"author": "eet_1024",
"author_id": 21302,
"author_profile": "https://Stackoverflow.com/users/21302",
"pm_score": 2,
"selected": false,
"text": "<p>On every platform I have seen, high level control structures are implemented as low level gotos (jumps). For example, the Java Virtual Machine has a Jump byte code, but nothing for if, else, while, for, etc.</p>\n\n<p>And some of these compilers create spaghetti code for a simple conditional block.</p>\n\n<p>To answer your question, goto is still considered harmful by people who believe it to be harmful. Goto makes it easy to lose the advantages of structured programming.</p>\n\n<p>In the end, it's your program; and therefore your decision. I suggest not using goto until you are able to answer your question yourself, but in the context of a specific problem.</p>\n"
},
{
"answer_id": 323815,
"author": "Mike Dunlavey",
"author_id": 23771,
"author_profile": "https://Stackoverflow.com/users/23771",
"pm_score": 3,
"selected": false,
"text": "<p>If GOTO itself were evil, compilers would be evil, because they generate JMPs. If jumping into a block of code, especially following a pointer, were inherently evil, the RETurn instruction would be evil. Rather, the evil is in the potential for abuse.</p>\n\n<p>At times I have had to write apps that had to keep track of a number of objects where each object had to follow an intricate sequence of states in response to events, but the whole thing was definitely single-thread. A typical sequence of states, if represented in pseudo-code would be:</p>\n\n<pre><code>request something\nwait for it to be done\nwhile some condition\n request something\n wait for it\n if one response\n while another condition\n request something\n wait for it\n do something\n endwhile\n request one more thing\n wait for it\n else if some other response\n ... some other similar sequence ...\n ... etc, etc.\nendwhile\n</code></pre>\n\n<p>I'm sure this is not new, but the way I handled it in C(++) was to define some macros:</p>\n\n<pre><code>#define WAIT(n) do{state=(n); enque(this); return; L##n:;}while(0)\n#define DONE state = -1\n\n#define DISPATCH0 if state < 0) return;\n#define DISPATCH1 if(state==1) goto L1; DISPATCH0\n#define DISPATCH2 if(state==2) goto L2; DISPATCH1\n#define DISPATCH3 if(state==3) goto L3; DISPATCH2\n#define DISPATCH4 if(state==4) goto L4; DISPATCH3\n... as needed ...\n</code></pre>\n\n<p>Then (assuming state is initially 0) the structured state machine above turns into the structured code:</p>\n\n<pre><code>{\n DISPATCH4; // or as high a number as needed\n request something;\n WAIT(1); // each WAIT has a different number\n while (some condition){\n request something;\n WAIT(2);\n if (one response){\n while (another condition){\n request something;\n WAIT(3);\n do something;\n }\n request one more thing;\n WAIT(4);\n }\n else if (some other response){\n ... some other similar sequence ...\n }\n ... etc, etc.\n }\n DONE;\n}\n</code></pre>\n\n<p>With a variation on this, there can be CALL and RETURN, so some state machines can act like subroutines of other state machines.</p>\n\n<p>Is it unusual? Yes. Does it take some learning on the part of the maintainer? Yes. Does that learning pay off? I think so. Could it be done without GOTOs that jump into blocks? Nope.</p>\n"
},
{
"answer_id": 325005,
"author": "J.T. Hurley",
"author_id": 39851,
"author_profile": "https://Stackoverflow.com/users/39851",
"pm_score": 1,
"selected": false,
"text": "<p>Once, early in my programming life, I produced a program that consisted of a series of functions in a chain, where each function called its successor given successful conditions and completions.</p>\n\n<p>It was a hideous cludge that had multiple serious problems, the most serious being that no function could terminate until all the functions under it had terminated.</p>\n\n<p>But it was quickly developed, worked well for the limited set of problems it was designed to solve, and was showed the logic and flow of the program explicitly, which worked well when I refactored and extended it for inclusion in another project.</p>\n\n<p>My vote's on use it when it makes sense, and refactor it out as soon as its convenient.</p>\n"
},
{
"answer_id": 357028,
"author": "CurtTampa",
"author_id": 18225,
"author_profile": "https://Stackoverflow.com/users/18225",
"pm_score": 4,
"selected": false,
"text": "<p>Denying the use of the GOTO statement to programmers is like telling a carpenter not to use a hammer as it Might damage the wall while he is hammering in a nail. A real programmer Knows How and When to use a GOTO. I’ve followed behind some of these so-called ‘Structured Programs’ I’ve see such Horrid code just to avoid using a GOTO, that I could shoot the programmer. Ok, In defense of the other side, I’ve seen some real spaghetti code too and again, those programmers should be shot too.</p>\n\n<p>Here is just one small example of code I’ve found.</p>\n\n<pre><code> YORN = ''\n LOOP\n UNTIL YORN = 'Y' OR YORN = 'N' DO\n CRT 'Is this correct? (Y/N) : ':\n INPUT YORN\n REPEAT\n IF YORN = 'N' THEN\n CRT 'Aborted!'\n STOP\n END\n</code></pre>\n\n<p>-----------------------OR----------------------</p>\n\n<pre><code>10: CRT 'Is this Correct (Y)es/(N)o ':\n\n INPUT YORN\n\n IF YORN='N' THEN\n CRT 'Aborted!'\n STOP\n ENDIF\n IF YORN<>'Y' THEN GOTO 10\n</code></pre>\n"
},
{
"answer_id": 453816,
"author": "Rocketmagnet",
"author_id": 55934,
"author_profile": "https://Stackoverflow.com/users/55934",
"pm_score": 3,
"selected": false,
"text": "<p>I actually found myself forced to use a goto, because I literally couldn't think of a better (faster) way to write this code:</p>\n\n<p>I had a complex object, and I needed to do some operation on it. If the object was in one state, then I could do a quick version of the operation, otherwise I had to do a slow version of the operation. The thing was that in some cases, in the middle of the slow operation, it was possible to realise that this could have been done with the fast operation.</p>\n\n<pre><code>SomeObject someObject; \n\nif (someObject.IsComplex()) // this test is trivial\n{\n // begin slow calculations here\n if (result of calculations)\n {\n // just discovered that I could use the fast calculation !\n goto Fast_Calculations;\n }\n // do the rest of the slow calculations here\n return;\n}\n\nif (someObject.IsmediumComplex()) // this test is slightly less trivial\n{\n Fast_Calculations:\n // Do fast calculations\n return;\n}\n\n// object is simple, no calculations needed.\n</code></pre>\n\n<p>This was in a speed critical piece of realtime UI code, so I honestly think that a GOTO was justified here.</p>\n\n<p>Hugo</p>\n"
},
{
"answer_id": 548701,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 3,
"selected": false,
"text": "<p>\"In this link <a href=\"http://kerneltrap.org/node/553/2131\" rel=\"noreferrer\">http://kerneltrap.org/node/553/2131</a>\"</p>\n\n<p>Ironically, eliminating the goto introduced a bug: the spinlock call was omitted.</p>\n"
},
{
"answer_id": 548769,
"author": "Jonathan Leffler",
"author_id": 15168,
"author_profile": "https://Stackoverflow.com/users/15168",
"pm_score": 5,
"selected": false,
"text": "<p>Attracted by Jay Ballou adding an answer, I'll add my £0.02. If Bruno Ranschaert had not already done so, I'd have mentioned Knuth's "Structured Programming with GOTO Statements" article.</p>\n<p>One thing that I've not seen discussed is the sort of code that, while not exactly common, was taught in Fortran text books. Things like the extended range of a DO loop and open-coded subroutines (remember, this would be Fortran II, or Fortran IV, or Fortran 66 - not Fortran 77 or 90). There's at least a chance that the syntactic details are inexact, but the concepts should be accurate enough. The snippets in each case are inside a single function.</p>\n<p>Note that the excellent but dated (and out of print) book '<a href=\"https://rads.stackoverflow.com/amzn/click/com/0070342075\" rel=\"noreferrer\" rel=\"nofollow noreferrer\">The Elements of Programming Style, 2nd Edn</a>' by Kernighan & Plauger includes some real-life examples of abuse of GOTO from programming text books of its era (late-70s). The material below is not from that book, however.</p>\n<h3>Extended range for a DO loop</h3>\n<pre><code> do 10 i = 1,30\n ...blah...\n ...blah...\n if (k.gt.4) goto 37\n91 ...blah...\n ...blah...\n10 continue\n ...blah...\n return\n37 ...some computation...\n goto 91\n</code></pre>\n<p>One reason for such nonsense was the good old-fashioned punch-card. You might notice that the labels (nicely out of sequence because that was canonical style!) are in column 1 (actually, they had to be in columns 1-5) and the code is in columns 7-72 (column 6 was the continuation marker column). Columns 73-80 would be given a sequence number, and there were machines that would sort punch card decks into sequence number order. If you had your program on sequenced cards and needed to add a few cards (lines) into the middle of a loop, you'd have to repunch everything after those extra lines. However, if you replaced one card with the GOTO stuff, you could avoid resequencing all the cards - you just tucked the new cards at the end of the routine with new sequence numbers. Consider it to be the first attempt at 'green computing' - a saving of punch cards (or, more specifically, a saving of retyping labour - and a saving of consequential rekeying errors).</p>\n<p>Oh, you might also note that I'm cheating and not shouting - Fortran IV was written in all upper-case normally.</p>\n<h3>Open-coded subroutine</h3>\n<pre><code> ...blah...\n i = 1\n goto 76\n123 ...blah...\n ...blah...\n i = 2\n goto 76\n79 ...blah...\n ...blah...\n goto 54\n ...blah...\n12 continue\n return\n76 ...calculate something...\n ...blah...\n goto (123, 79) i\n54 ...more calculation...\n goto 12\n</code></pre>\n<p>The GOTO between labels 76 and 54 is a version of computed goto. If the variable i has the value 1, goto the first label in the list (123); if it has the value 2, goto the second, and so on. The fragment from 76 to the computed goto is the open-coded subroutine. It was a piece of code executed rather like a subroutine, but written out in the body of a function. (Fortran also had statement functions - which were embedded functions that fitted on a single line.)</p>\n<p>There were worse constructs than the computed goto - you could assign labels to variables and then use an assigned goto. Googling <a href=\"http://publib.boulder.ibm.com/infocenter/comphelp/v8v101/index.jsp?topic=/com.ibm.xlf101a.doc/xlflr/gotoass.htm\" rel=\"noreferrer\">assigned goto</a> tells me it was deleted from Fortran 95. Chalk one up for the structured programming revolution which could fairly be said to have started in public with Dijkstra's "GOTO Considered Harmful" letter or article.</p>\n<p>Without some knowledge of the sorts of things that were done in Fortran (and in other languages, most of which have rightly fallen by the wayside), it is hard for us newcomers to understand the scope of the problem which Dijkstra was dealing with. Heck, I didn't start programming until ten years after that letter was published (but I did have the misfortune to program in Fortran IV for a while).</p>\n"
},
{
"answer_id": 549764,
"author": "mweiss",
"author_id": 33254,
"author_profile": "https://Stackoverflow.com/users/33254",
"pm_score": 2,
"selected": false,
"text": "<p>While I think it's best to avoid goto on almost any situation, there are exceptions.\nFor example, one place I've seen where goto statements are the elegant solution compared to others much more convoluted ways is implementing tail call elimintation for an interpreter. </p>\n"
},
{
"answer_id": 741446,
"author": "Nicolas Dorier",
"author_id": 19803,
"author_profile": "https://Stackoverflow.com/users/19803",
"pm_score": 0,
"selected": false,
"text": "<p>Look <a href=\"https://www.securecoding.cert.org/confluence/display/seccode/MEM12-C.+Use+a+Goto-Chain+when+leaving+a+function+on+error+when+using+and+releasing+resources\" rel=\"nofollow noreferrer\">this</a>, it's a good usse of GoTo, but in a language with garbage collector I think the only reason to use GoTo is to obfuscate your code (obfuscators tools use GoTo to hide their code)</p>\n"
},
{
"answer_id": 741455,
"author": "stesch",
"author_id": 41860,
"author_profile": "https://Stackoverflow.com/users/41860",
"pm_score": 4,
"selected": false,
"text": "<p>It never was, as long as you were able to think for yourself.</p>\n"
},
{
"answer_id": 741517,
"author": "tylerl",
"author_id": 86060,
"author_profile": "https://Stackoverflow.com/users/86060",
"pm_score": 5,
"selected": false,
"text": "<p>Go To can provide a sort of stand-in for \"real\" exception handling in certain cases. Consider:</p>\n\n<pre><code>ptr = malloc(size);\nif (!ptr) goto label_fail;\nbytes_in = read(f_in,ptr,size);\nif (bytes_in=<0) goto label_fail;\nbytes_out = write(f_out,ptr,bytes_in);\nif (bytes_out != bytes_in) goto label_fail;\n</code></pre>\n\n<p>Obviously this code was simplified to take up less space, so don't get too hung up on the details. But consider an alternative I've seen all too many times in <strong>production</strong> code by coders going to absurd lengths to avoid using goto:</p>\n\n<pre><code>success=false;\ndo {\n ptr = malloc(size);\n if (!ptr) break;\n bytes_in = read(f_in,ptr,size);\n if (count=<0) break;\n bytes_out = write(f_out,ptr,bytes_in);\n if (bytes_out != bytes_in) break;\n success = true;\n} while (false);\n</code></pre>\n\n<p>Now functionally this code does the exact same thing. In fact, the code generated by the compiler is nearly identical. However, in the programmer's zeal to appease <em>Nogoto</em> (the dreaded god of academic rebuke), this programmer has completely broken the underlying idiom that the <code>while</code> loop represents, and did a real number on the readability of the code. <strong>This is not better.</strong></p>\n\n<p>So, the moral of the story is, if you find yourself resorting to something really stupid in order to avoid using goto, then don't.</p>\n"
},
{
"answer_id": 780172,
"author": "nelix",
"author_id": 93863,
"author_profile": "https://Stackoverflow.com/users/93863",
"pm_score": 0,
"selected": false,
"text": "<p>Computed gotos for dispatch, often is easyer to understand than a very large switch statement.</p>\n\n<p>For errors and co-threads I think setcontex or setjmp (where available) are 'better'.</p>\n"
},
{
"answer_id": 780212,
"author": "las3rjock",
"author_id": 94732,
"author_profile": "https://Stackoverflow.com/users/94732",
"pm_score": 2,
"selected": false,
"text": "<p>Yes, GOTO is still considered harmful. By the time you find yourself in the rare situation where the use of a GOTO might be valid, you should be confident enough in your own programming skill not to need the validation of others. Any GOTO-like functions that allow you to jump even farther away in scope than allowed by GOTO should be considered more dangerous than GOTO.</p>\n"
},
{
"answer_id": 780245,
"author": "smcameron",
"author_id": 77514,
"author_profile": "https://Stackoverflow.com/users/77514",
"pm_score": 4,
"selected": false,
"text": "<p>Since I began doing a few things in the linux kernel, gotos don't bother me so much as they once did. At first I was sort of horrified to see they (kernel guys) added gotos into my code. I've since become accustomed to the use of gotos, in some limited contexts, and will now occasionally use them myself. Typically, it's a goto that jumps to the end of a function to do some kind of cleanup and bail out, rather than duplicating that same cleanup and bailout in several places in the function. And typically, it's not something large enough to hand off to another function -- e.g. freeing some locally (k)malloc'ed variables is a typical case.</p>\n\n<p>I've written code that used setjmp/longjmp only once. It was in a MIDI drum sequencer program. Playback happened in a separate process from all user interaction, and the playback process used shared memory with the UI process to get the limited info it needed to do the playback. When the user wanted to stop playback, the playback process just did a longjmp \"back to the beginning\" to start over, rather than some complicated unwinding of wherever it happened to be executing when the user wanted it to stop. It worked great, was simple, and I never had any problems or bugs related to it in that instance.</p>\n\n<p>setjmp/longjmp have their place -- but that place is one you'll not likely visit but once in a very long while.</p>\n\n<p>Edit: I just looked at the code. It was actually siglongjmp() that I used, not longjmp (not that it's a big deal, but I had forgotten that siglongjmp even existed.)</p>\n"
},
{
"answer_id": 880151,
"author": "mfx",
"author_id": 8015,
"author_profile": "https://Stackoverflow.com/users/8015",
"pm_score": 0,
"selected": false,
"text": "<p>Using a GOTO can be nice when you are generating C state machines. I would never use a GOTO in hand-written code - \"modern\" language constructs make it utterly unnecessary.</p>\n\n<p>The setjmp/longjmp construct can be useful in certain circumstances (when \"true\" exceptions are missing, or when you are implementing something like Chicken scheme), but it has no place in \"ordinary\" programming. </p>\n"
},
{
"answer_id": 1616884,
"author": "Loren Pechtel",
"author_id": 10659,
"author_profile": "https://Stackoverflow.com/users/10659",
"pm_score": 0,
"selected": false,
"text": "<p>In a perfect world we would never need a GOTO. However, we live in an imperfect world. We don't have compilers with every control structure we can dream of. On occasion I feel it's better to use a GOTO than kludge a control structure that doesn't really exist.</p>\n\n<p>The most common (not that it's common) is the loop and a half construct. You always execute the first part, maybe you execute the rest of it and then go back and do the first part again. Sure, you can implement it with a boolean flag inside a while loop but I don't like this answer because it's less clear in my opinion. When you see something like:</p>\n\n<pre><code>loop:\n GetSomeData;\n if GotData then\n Begin\n ProcessTheData;\n StoreTheResult;\n Goto Loop;\n End;\n</code></pre>\n\n<p>to me it's clearer than</p>\n\n<pre><code>Repeat\n GetSomeData;\n Flag := GotData;\n if Flag then\n Begin\n ProcessTheData;\n StoreTheResult;\n End;\nUntil Not Flag;\n</code></pre>\n\n<p>and there are times where</p>\n\n<pre><code>Function GotTheData;\n\nBegin\n GetSomeData;\n Result := GotData;\nEnd;\n\nWhile GotTheData do\n Begin\n ProcessTheData;\n StoreTheResult;\n End;\n</code></pre>\n\n<p>isn't a workable answer, and I'm a firm believer that code should be clear. If I have to make a comment explaining what the code is doing I consider whether I could make the code clearer and get rid of the comment.</p>\n"
},
{
"answer_id": 1616905,
"author": "John K",
"author_id": 179972,
"author_profile": "https://Stackoverflow.com/users/179972",
"pm_score": 1,
"selected": false,
"text": "<p>Many modern programming languages use their compiler to enforce restrictions on the usage of GOTO - this cuts down on the potential risks. For example, C# will not allow you to use GOTO to jump into the body of a loop from outside of it. <a href=\"http://msdn.microsoft.com/en-us/library/aa664758(VS.71).aspx\" rel=\"nofollow noreferrer\">Restrictions are mentioned in the documentation</a>.</p>\n\n<p>This is one example of how GOTO is sometimes safer than it used to be.</p>\n\n<p>In some cases the use of GOTO is the same as returning early from a function (i.e. to break out of a loop early). However good form can be argued.</p>\n"
},
{
"answer_id": 1857927,
"author": "DigitalRoss",
"author_id": 140740,
"author_profile": "https://Stackoverflow.com/users/140740",
"pm_score": 4,
"selected": false,
"text": "<h2>Because <code>goto</code> can be used for confusing metaprogramming</h2>\n\n<p><code>Goto</code> is both a <em>high-level</em> and a <em>low-level</em> control expression, and as a result it just doesn't have a appropriate design pattern suitable for most problems.</p>\n\n<p>It's <em>low-level</em> in the sense that a goto is a primitive operation that implements something higher like <code>while</code> or <code>foreach</code> or something.</p>\n\n<p>It's <em>high-level</em> in the sense that when used in certain ways it takes code that executes in a clear sequence, in an uninterrupted fashion, except for structured loops, and it changes it into pieces of logic that are, with enough <code>goto</code>s, a grab-bag of logic being dynamically reassembled.</p>\n\n<p>So, there is a <em>prosaic</em> and an <em>evil</em> side to <code>goto</code>.</p>\n\n<p>The <em>prosaic side</em> is that an upward pointing goto can implement a perfectly reasonable loop and a downward-pointing goto can do a perfectly reasonable <code>break</code> or <code>return</code>. Of course, an actual <code>while</code>, <code>break</code>, or <code>return</code> would be a lot more readable, as the poor human wouldn't have to simulate the effect of the <code>goto</code> in order to get the big picture. So, a bad idea in general.</p>\n\n<p>The <em>evil side</em> involves a routine not using goto for while, break, or return, but using it for what's called <em>spaghetti logic</em>. In this case the goto-happy developer is constructing pieces of code out of a maze of goto's, and the only way to understand it is to simulate it mentally as a whole, a terribly tiring task when there are many goto's. I mean, imagine the trouble of evaluating code where the <code>else</code> is not precisely an inverse of the <code>if</code>, where nested <code>if</code>s might allow in some things that were rejected by the outer <code>if</code>, etc, etc.</p>\n\n<p>Finally, to really cover the subject, we should note that essentially all early languages except Algol initially made only single statements subject to their versions of <code>if-then-else</code>. So, the only way to do a conditional block was to <code>goto</code> around it using an inverse conditional. Insane, I know, but I've read some old specs. Remember that the first computers were programmed in binary machine code so I suppose any kind of an HLL was a lifesaver; I guess they weren't too picky about exactly what HLL features they got.</p>\n\n<p>Having said all that I used to stick one <code>goto</code> into every program I wrote <em>\"just to annoy the purists\"</em>.</p>\n"
},
{
"answer_id": 2394549,
"author": "dan04",
"author_id": 287586,
"author_profile": "https://Stackoverflow.com/users/287586",
"pm_score": 6,
"selected": false,
"text": "<p>Today, it's hard to see the big deal about the <code>GOTO</code> statement because the \"structured programming\" people mostly won the debate and today's languages have sufficient control flow structures to avoid <code>GOTO</code>.</p>\n\n<p>Count the number of <code>goto</code>s in a modern C program. Now add the number of <code>break</code>, <code>continue</code>, and <code>return</code> statements. Furthermore, add the number of times you use <code>if</code>, <code>else</code>, <code>while</code>, <code>switch</code> or <code>case</code>. That's about how many <code>GOTO</code>s your program would have had if you were writing in FORTRAN or BASIC in 1968 when Dijkstra wrote his letter.</p>\n\n<p>Programming languages at the time were lacking in control flow. For example, in the original Dartmouth BASIC:</p>\n\n<ul>\n<li><p><code>IF</code> statements had no <code>ELSE</code>. If you wanted one, you had to write:</p>\n\n<pre><code>100 IF NOT condition THEN GOTO 200\n...stuff to do if condition is true...\n190 GOTO 300\n200 REM else\n...stuff to do if condition is false...\n300 REM end if\n</code></pre></li>\n<li><p>Even if your <code>IF</code> statement didn't need an <code>ELSE</code>, it was still limited to a single line, which usually consisted of a <code>GOTO</code>.</p></li>\n<li><p>There was no <code>DO...LOOP</code> statement. For non-<code>FOR</code> loops, you had to end the loop with an explicit <code>GOTO</code> or <code>IF...GOTO</code> back to the beginning.</p></li>\n<li><p>There was no <code>SELECT CASE</code>. You had to use <code>ON...GOTO</code>.</p></li>\n</ul>\n\n<p>So, you ended up with a <em>lot</em> of <code>GOTO</code>s in your program. And you couldn't depend on the restriction of <code>GOTO</code>s to within a single subroutine (because <code>GOSUB...RETURN</code> was such a weak concept of subroutines), so these <code>GOTO</code>s could go <em>anywhere</em>. Obviously, this made control flow hard to follow.</p>\n\n<p>This is where the anti-<code>GOTO</code> movement came from.</p>\n"
},
{
"answer_id": 2394566,
"author": "kyoryu",
"author_id": 129175,
"author_profile": "https://Stackoverflow.com/users/129175",
"pm_score": 1,
"selected": false,
"text": "<p>In my opinion, 'goto being harmful' is more about encapsulation and consistency of state than anything else.</p>\n\n<p>Much code, even 'oo' code, has as bad messy state encapsultation as any spaghetti code ever did.</p>\n\n<p>The problem with 'goto considered harmful' is that it leaves the programmer who only looks at the mechanistic rule without the understanding the impression that the only flow control that should be available is the return method, and that very easily leads to passing much state around by reference - and <em>that</em> leads right back to a lack of state encapsulation, the very thing that 'goto considered harmful' was trying to get rid of.</p>\n\n<p>Follow the flow of control in a typical 'OO' codebase, and tell me that we don't still have spaghetti code.... (btw, I don't mean the 'ravioli' code that usuall gets so much hate - the path of execution of ravioli code is usually pretty straightforward, even if the object relationships aren't immediately obvious).</p>\n\n<p>Or, to put it a different way, avoiding gotos in favor of everything being a subroutine is only useful if each subroutine only modifies local state, that cannot be modified except via that subroutine (or at least that object).</p>\n"
},
{
"answer_id": 3059735,
"author": "Adam Houldsworth",
"author_id": 358221,
"author_profile": "https://Stackoverflow.com/users/358221",
"pm_score": 2,
"selected": false,
"text": "<p>Almost all situations where a goto can be used, you can do the same using other constructs. Goto is used by the compiler anyway.</p>\n\n<p>I personally never use it explicitly, don't ever need to.</p>\n"
},
{
"answer_id": 3444091,
"author": "Sled",
"author_id": 254477,
"author_profile": "https://Stackoverflow.com/users/254477",
"pm_score": 1,
"selected": false,
"text": "<p>There are a few issues with goto. One is that it is difficult to see how the code flows. It is easier to see an if-block because of the curly braces, but a goto hides that from you. Also, while and if are also essentially gotos, but they help explain why you are jumping back and forth in your code. With a regular goto that you have to piece together yourself. </p>\n\n<p>As an excercise try writing some code for calculating the fibonacci sequence and see how hard it is to read when you are done.</p>\n\n<p>If you are going to be working on that code then I would recommend writing some unittests and rewriting it. Otherwise, just let it be.</p>\n\n<p>All that said, sometimes, for performance reasons, it 'may' be appropriate to use a goto.</p>\n"
},
{
"answer_id": 3444224,
"author": "David Given",
"author_id": 404568,
"author_profile": "https://Stackoverflow.com/users/404568",
"pm_score": 1,
"selected": false,
"text": "<p>It's not that goto in of itself is bad; it's that using goto when the same logic can be more clearly expressed in another way is bad. It can make the code very hard to follow and makes maintenance hard. Just go and look at some programs in Basic from the Bad Old Days as an example.</p>\n\n<p>In my opinion, in a modern language like C# we should never have a need for goto in normal circumstances. If I find myself using it, it's usually a sign that I need to rethink my logic --- there's almost certainly a clearer way of expressing the same code using normal code flow statements.</p>\n\n<p>That said, there <em>are</em> special purposes for which goto can be extremely useful (and I find myself getting annoyed at languages that don't have it). I mostly use it in C for breaking out of multiple levels of loops, or for error handling; I believe that C# has language features that mean you don't have to do this. (It's also really useful when producing autogenerated code, but that's not something most people encounter in real life.)</p>\n\n<p>There's also another problem with goto, which is purely political: a lot of people hate it, and using it in code, <em>even if justified</em>, may cause issues. If this is assignment code, then yes, rewrite it, or you're likely to get marked down. Otherwise I'd be inclined to leave it in until the next time you need to do maintenance on that section.</p>\n"
},
{
"answer_id": 10859707,
"author": "Tim",
"author_id": 1110442,
"author_profile": "https://Stackoverflow.com/users/1110442",
"pm_score": 2,
"selected": false,
"text": "<p>C++ contains constructors and destructors. This allows for a pattern know as RAII (resource allocation is initialization). Basically, you create a local stack variable, and the act of creating the stack variable opens a file, allocates memory, locks a mutex, or otherwise acquires a resource that must later be released.</p>\n\n<p>When the variable goes out of scope, the destructor runs and frees the resource.</p>\n\n<p>C doesn't have this feature. But you still often need to acquire resources at the beginning of a function, and release them at the end.</p>\n\n<p>Your function probably has one or more error conditions that cause it to return early. You don't want to duplicate the resource release code. The solution is to use goto.</p>\n\n<p>Example:</p>\n\n<pre><code>int\nfoo(const char *arg)\n{\n char *argcopy = strdup(arg);\n\n if (!isvalid(argcopy))\n goto out1;\n\n FILE *myfile = fopen(argcopy, \"r\");\n if (myfile == NULL)\n goto out1;\n\n char bytes[10];\n if (fread(bytes, sizeof(bytes), 1, myfile) != sizeof(mybytes))\n goto out2;\n\n /* do some actual work */\n /* .... */\n /* end of actual work */\n\n out2:\n fclose(myfile);\n\n out1:\n free(argcopy);\n\n return 0;\n }\n</code></pre>\n"
},
{
"answer_id": 10921640,
"author": "gkimsey",
"author_id": 1224427,
"author_profile": "https://Stackoverflow.com/users/1224427",
"pm_score": 3,
"selected": false,
"text": "<p>One thing I've not seen from <em>any</em> of the answers here is that a 'goto' solution is often <strong>more efficient</strong> than one of the structured programming solutions often mentioned.</p>\n\n<p>Consider the many-nested-loops case, where using 'goto' instead of a bunch of <code>if(breakVariable)</code> sections is obviously more efficient. The solution \"Put your loops in a function and use return\" is often totally unreasonable. In the likely case that the loops are using local variables, you now have to pass them all through function parameters, potentially handling loads of extra headaches that arise from that.</p>\n\n<p>Now consider the cleanup case, which I've used myself quite often, and is so common as to have presumably been responsible for the try{} catch {} structure not available in many languages. The number of checks and extra variables that are required to accomplish the same thing are far worse than the one or two instructions to make the jump, and again, the additional function solution is not a solution at all. You can't tell me that's more manageable or more readable.</p>\n\n<p>Now code space, stack usage, and execution time may not matter enough in many situations to many programmers, but when you're in an embedded environment with only 2KB of code space to work with, 50 bytes of extra instructions to avoid one clearly defined 'goto' is just laughable, and this is not as rare a situation as many high-level programmers believe.</p>\n\n<p>The statement that 'goto is harmful' was very helpful in moving towards structured programming, even if it was always an over-generalization. At this point, we've all heard it enough to be wary of using it (as we should). When it's obviously the right tool for the job, we don't need to be scared of it.</p>\n"
},
{
"answer_id": 14960832,
"author": "guido",
"author_id": 389099,
"author_profile": "https://Stackoverflow.com/users/389099",
"pm_score": 0,
"selected": false,
"text": "<p>Example of jump in Java <a href=\"http://www.docjar.com/html/api/java/lang/String.java.html\" rel=\"nofollow\">String class</a> source code:</p>\n\n<pre><code>int firstUpper;\n\n/* Now check if there are any characters that need to be changed. */\nscan: {\n for (firstUpper = 0 ; firstUpper < count; ) {\n char c = value[offset+firstUpper];\n if ((c >= Character.MIN_HIGH_SURROGATE) &&\n (c <= Character.MAX_HIGH_SURROGATE)) {\n int supplChar = codePointAt(firstUpper);\n if (supplChar != Character.toLowerCase(supplChar)) {\n break scan;\n }\n firstUpper += Character.charCount(supplChar);\n } else {\n if (c != Character.toLowerCase(c)) {\n break scan;\n }\n firstUpper++;\n }\n }\n return this;\n}\n[... subsequent use of firstUpper ...]\n</code></pre>\n\n<p>this could be rewritten with very little overhead for instance as:</p>\n\n<pre><code> int firstUpper = indexOfFirstUpper();\n if (firstUpper < 0) return this; \n</code></pre>\n\n<p>Even in modern languages, and even if I don't actually like the use of gotos but I consider those acceptable in many cases, in a low-level case like this one looks better to me (and it does a little more than just exiting the loop).</p>\n\n<p>No intention to reanimate a religion war.</p>\n"
},
{
"answer_id": 24473250,
"author": "Akavall",
"author_id": 1078084,
"author_profile": "https://Stackoverflow.com/users/1078084",
"pm_score": 1,
"selected": false,
"text": "<p><code>goto</code> can be useful, here is an <a href=\"https://github.com/mcostalba/Stockfish/blob/master/src/search.cpp\" rel=\"nofollow\">example</a> of very strong open-source chess engine stockfish written in <code>c++</code>. The <code>goto</code> just skips some conditions checking (efficiency gain) that the program would have to do if not for the <code>goto</code> statement. If the <code>goto</code> statement label is after the <code>goto</code> declaration, then they are pretty harmless and readable. </p>\n"
},
{
"answer_id": 25773503,
"author": "thb",
"author_id": 1275653,
"author_profile": "https://Stackoverflow.com/users/1275653",
"pm_score": 5,
"selected": false,
"text": "<p>Goto considered helpful.</p>\n\n<p>I started programming in 1975. To 1970s-era programmers, the words \"goto considered harmful\" said more or less that new programming languages with modern control structures were worth trying. We did try the new languages. We quickly converted. We never went back.</p>\n\n<p>We never went back, but, if you are younger, then you have never been there in the first place.</p>\n\n<p>Now, a background in ancient programming languages may not be very useful except as an indicator of the programmer's age. Notwithstanding, younger programmers lack this background, so they no longer understand the message the slogan \"goto considered harmful\" conveyed <em>to its intended audience at the time it was introduced.</em></p>\n\n<p>Slogans one does not understand are not very illuminating. It is probably best to forget such slogans. Such slogans do not help.</p>\n\n<p>This particular slogan however, \"Goto considered harmful,\" has taken on an undead life of its own.</p>\n\n<p>Can goto not be abused? Answer: sure, but so what? Practically every programming element <em>can</em> be abused. The humble <code>bool</code> for example is abused more often than some of us would like to believe.</p>\n\n<p>By contrast, I cannot remember meeting a single, actual instance of goto abuse since 1990.</p>\n\n<p>The biggest problem with goto is probably not technical but social. Programmers who do not know very much sometimes seem to feel that deprecating goto makes them sound smart. You might have to satisfy such programmers from time to time. Such is life.</p>\n\n<p>The worst thing about goto today is that it is not used enough.</p>\n"
}
] | 2008/09/05 | [
"https://Stackoverflow.com/questions/46586",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/658/"
] | Everyone is aware of Dijkstra's [Letters to the editor: go to statement considered harmful](http://portal.acm.org/citation.cfm?doid=362947) (also [here](http://www.cs.utexas.edu/%7EEWD/transcriptions/EWD02xx/EWD215.html) .html transcript and [here](http://www.cs.utexas.edu/users/EWD/ewd02xx/EWD215.PDF) .pdf) and there has been a formidable push since that time to eschew the goto statement whenever possible. While it's possible to use goto to produce unmaintainable, sprawling code, it nevertheless remains in [modern programming languages](http://msdn.microsoft.com/en-us/library/13940fs2(VS.71).aspx). Even the advanced [continuation](http://en.wikipedia.org/wiki/Goto#Continuations) control structure in Scheme can be described as a sophisticated goto.
What circumstances warrant the use of goto? When is it best to avoid?
As a follow-up question: C provides a pair of functions, setjmp() and longjmp(), that provide the ability to goto not just within the current stack frame but within any of the calling frames. Should these be considered as dangerous as goto? More dangerous?
---
Dijkstra himself regretted that title, for which he was not responsible. At the end of [EWD1308](http://www.cs.utexas.edu/%7EEWD/transcriptions/EWD13xx/EWD1308.html) (also [here](http://www.cs.utexas.edu/%7EEWD/ewd13xx/EWD1308.PDF) .pdf) he wrote:
>
> Finally a short story for the record.
> In 1968, the Communications of the ACM
> published a text of mine under the
> title "*The goto statement considered
> harmful*", which in later years would
> be most frequently referenced,
> regrettably, however, often by authors
> who had seen no more of it than its
> title, which became a cornerstone of
> my fame by becoming a template: we
> would see all sorts of articles under
> the title "X considered harmful" for
> almost any X, including one titled
> "Dijkstra considered harmful". But
> what had happened? I had submitted a
> paper under the title "***A case against
> the goto statement***", which, in order
> to speed up its publication, the
> editor had changed into a "letter to
> the Editor", and in the process he had
> given it a new title of his own
> invention! The editor was Niklaus
> Wirth.
>
>
>
A well thought out classic paper about this topic, to be matched to that of Dijkstra, is [Structured Programming with go to Statements](http://www.clifford.at/cfun/cliffdev/p261-knuth.pdf), by Donald E. Knuth. Reading both helps to reestablish context and a non-dogmatic understanding of the subject. In this paper, Dijkstra's opinion on this case is reported and is even more strong:
>
> *Donald E. Knuth:* I believe that by presenting such a
> view I am not in fact disagreeing
> sharply with Dijkstra's ideas, since
> he recently wrote the following:
> "Please don't fall into the trap of
> believing that I am terribly
> dogmatical about [the go to
> statement]. **I have the uncomfortable
> feeling that others are making a
> religion out of it, as if the
> conceptual problems of programming
> could be solved by a single trick, by
> a simple form of coding discipline!**"
>
>
> | The following statements are generalizations; while it is always possible to plead exception, it usually (in my experience and humble opinion) isn't worth the risks.
1. Unconstrained use of memory addresses (either GOTO or raw pointers) provides too many opportunities to make easily avoidable mistakes.
2. The more ways there are to arrive at a particular "location" in the code, the less confident one can be about what the state of the system is at that point. (See below.)
3. Structured programming IMHO is less about "avoiding GOTOs" and more about making the structure of the code match the structure of the data. For example, a repeating data structure (e.g. array, sequential file, etc.) is naturally processed by a repeated unit of code. Having built-in structures (e.g. while, for, until, for-each, etc.) allows the programmer to avoid the tedium of repeating the same cliched code patterns.
4. Even if GOTO is low-level implementation detail (not always the case!) it's below the level that the programmer should be thinking. How many programmers balance their personal checkbooks in raw binary? How many programmers worry about which sector on the disk contains a particular record, instead of just providing a key to a database engine (and how many ways could things go wrong if we really wrote all of our programs in terms of physical disk sectors)?
Footnotes to the above:
Regarding point 2, consider the following code:
```c
a = b + 1
/* do something with a */
```
At the "do something" point in the code, we can state with high confidence that `a` is greater than `b`. (Yes, I'm ignoring the possibility of untrapped integer overflow. Let's not bog down a simple example.)
On the other hand, if the code had read this way:
```c
...
goto 10
...
a = b + 1
10: /* do something with a */
...
goto 10
...
```
The multiplicity of ways to get to label 10 means that we have to work much harder to be confident about the relationships between `a` and `b` at that point. (In fact, in the general case it's undecideable!)
Regarding point 4, the whole notion of "going someplace" in the code is just a metaphor. Nothing is really "going" anywhere inside the CPU except electrons and photons (for the waste heat). Sometimes we give up a metaphor for another, more useful, one. I recall encountering (a few decades ago!) a language where
```c
if (some condition) {
action-1
} else {
action-2
}
```
was implemented on a virtual machine by compiling action-1 and action-2 as out-of-line parameterless routines, then using a single two-argument VM opcode which used the boolean value of the condition to invoke one or the other. The concept was simply "choose what to invoke now" rather than "go here or go there". Again, just a change of metaphor. |
46,636 | <p>What's the best way to copy a file from a network share to the local file system using a Windows batch file? Normally, I would use "net use *" but using this approach how can I get the drive letter?</p>
| [
{
"answer_id": 46640,
"author": "Mark Biek",
"author_id": 305,
"author_profile": "https://Stackoverflow.com/users/305",
"pm_score": 5,
"selected": true,
"text": "<p>Can you just use the full UNC path to the file?</p>\n\n<pre><code>copy \\\\myserver\\myshare\\myfolder\\myfile.txt c:\\myfiles\n</code></pre>\n"
},
{
"answer_id": 46646,
"author": "Joel Coehoorn",
"author_id": 3043,
"author_profile": "https://Stackoverflow.com/users/3043",
"pm_score": 1,
"selected": false,
"text": "<p>You can specify the drive letter for <code>net use</code>. Put this in the command prompt for more info: </p>\n\n<pre><code>net use /?\n</code></pre>\n"
},
{
"answer_id": 59326025,
"author": "Wasif",
"author_id": 12269857,
"author_profile": "https://Stackoverflow.com/users/12269857",
"pm_score": 0,
"selected": false,
"text": "<p>You can also use <code>xcopy</code> and <code>robocopy</code>:</p>\n\n<pre><code>xcopy \"\\\\server\\share\\path\" \"destination\"\n</code></pre>\n\n<pre><code>robocopy \"\\\\server\\share\\path\" \"destination\"\n</code></pre>\n"
}
] | 2008/09/05 | [
"https://Stackoverflow.com/questions/46636",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4778/"
] | What's the best way to copy a file from a network share to the local file system using a Windows batch file? Normally, I would use "net use \*" but using this approach how can I get the drive letter? | Can you just use the full UNC path to the file?
```
copy \\myserver\myshare\myfolder\myfile.txt c:\myfiles
``` |
46,663 | <p>Is it possible to send an email from my Java application using a GMail account? I have configured my company mail server with Java app to send email, but that's not going to cut it when I distribute the application. Answers with any of using Hotmail, Yahoo or GMail are acceptable.</p>
| [
{
"answer_id": 46676,
"author": "Ryan Farley",
"author_id": 1627,
"author_profile": "https://Stackoverflow.com/users/1627",
"pm_score": 0,
"selected": false,
"text": "<p>An easy route would be to have the gmail account configured/enabled for POP3 access. This would allow you to send out via normal SMTP through the gmail servers. </p>\n\n<p>Then you'd just send through smtp.gmail.com (on port 587)</p>\n"
},
{
"answer_id": 46681,
"author": "jodonnell",
"author_id": 4223,
"author_profile": "https://Stackoverflow.com/users/4223",
"pm_score": 7,
"selected": false,
"text": "<p>Something like this (sounds like you just need to change your SMTP server):</p>\n\n<pre><code>String host = \"smtp.gmail.com\";\nString from = \"user name\";\nProperties props = System.getProperties();\nprops.put(\"mail.smtp.host\", host);\nprops.put(\"mail.smtp.user\", from);\nprops.put(\"mail.smtp.password\", \"asdfgh\");\nprops.put(\"mail.smtp.port\", \"587\"); // 587 is the port number of yahoo mail\nprops.put(\"mail.smtp.auth\", \"true\");\n\nSession session = Session.getDefaultInstance(props, null);\nMimeMessage message = new MimeMessage(session);\nmessage.setFrom(new InternetAddress(from));\n\nInternetAddress[] to_address = new InternetAddress[to.length];\nint i = 0;\n// To get the array of addresses\nwhile (to[i] != null) {\n to_address[i] = new InternetAddress(to[i]);\n i++;\n}\nSystem.out.println(Message.RecipientType.TO);\ni = 0;\nwhile (to_address[i] != null) {\n\n message.addRecipient(Message.RecipientType.TO, to_address[i]);\n i++;\n}\nmessage.setSubject(\"sending in a group\");\nmessage.setText(\"Welcome to JavaMail\");\n// alternately, to send HTML mail:\n// message.setContent(\"<p>Welcome to JavaMail</p>\", \"text/html\");\nTransport transport = session.getTransport(\"smtp\");\ntransport.connect(\"smtp.mail.yahoo.co.in\", \"user name\", \"asdfgh\");\ntransport.sendMessage(message, message.getAllRecipients());\ntransport.close();\n</code></pre>\n"
},
{
"answer_id": 47452,
"author": "Bill the Lizard",
"author_id": 1288,
"author_profile": "https://Stackoverflow.com/users/1288",
"pm_score": 9,
"selected": true,
"text": "<p>First download the <a href=\"https://java.net/projects/javamail/pages/Home\" rel=\"noreferrer\">JavaMail API</a> and make sure the relevant jar files are in your classpath.</p>\n\n<p>Here's a full working example using GMail.</p>\n\n<pre><code>import java.util.*;\nimport javax.mail.*;\nimport javax.mail.internet.*;\n\npublic class Main {\n\n private static String USER_NAME = \"*****\"; // GMail user name (just the part before \"@gmail.com\")\n private static String PASSWORD = \"********\"; // GMail password\n private static String RECIPIENT = \"[email protected]\";\n\n public static void main(String[] args) {\n String from = USER_NAME;\n String pass = PASSWORD;\n String[] to = { RECIPIENT }; // list of recipient email addresses\n String subject = \"Java send mail example\";\n String body = \"Welcome to JavaMail!\";\n\n sendFromGMail(from, pass, to, subject, body);\n }\n\n private static void sendFromGMail(String from, String pass, String[] to, String subject, String body) {\n Properties props = System.getProperties();\n String host = \"smtp.gmail.com\";\n props.put(\"mail.smtp.starttls.enable\", \"true\");\n props.put(\"mail.smtp.host\", host);\n props.put(\"mail.smtp.user\", from);\n props.put(\"mail.smtp.password\", pass);\n props.put(\"mail.smtp.port\", \"587\");\n props.put(\"mail.smtp.auth\", \"true\");\n\n Session session = Session.getDefaultInstance(props);\n MimeMessage message = new MimeMessage(session);\n\n try {\n message.setFrom(new InternetAddress(from));\n InternetAddress[] toAddress = new InternetAddress[to.length];\n\n // To get the array of addresses\n for( int i = 0; i < to.length; i++ ) {\n toAddress[i] = new InternetAddress(to[i]);\n }\n\n for( int i = 0; i < toAddress.length; i++) {\n message.addRecipient(Message.RecipientType.TO, toAddress[i]);\n }\n\n message.setSubject(subject);\n message.setText(body);\n Transport transport = session.getTransport(\"smtp\");\n transport.connect(host, from, pass);\n transport.sendMessage(message, message.getAllRecipients());\n transport.close();\n }\n catch (AddressException ae) {\n ae.printStackTrace();\n }\n catch (MessagingException me) {\n me.printStackTrace();\n }\n }\n}\n</code></pre>\n\n<p>Naturally, you'll want to do more in the <code>catch</code> blocks than print the stack trace as I did in the example code above. (Remove the <code>catch</code> blocks to see which method calls from the JavaMail API throw exceptions so you can better see how to properly handle them.)</p>\n\n<hr>\n\n<p>Thanks to <a href=\"https://stackoverflow.com/users/4223/jodonnell\">@jodonnel</a> and everyone else who answered. I'm giving him a bounty because his answer led me about 95% of the way to a complete answer.</p>\n"
},
{
"answer_id": 886689,
"author": "user109771",
"author_id": 109771,
"author_profile": "https://Stackoverflow.com/users/109771",
"pm_score": 4,
"selected": false,
"text": "<p>Even though this question is closed, I'd like to post a counter solution, but now using <a href=\"http://www.simplejavamail.org\" rel=\"nofollow noreferrer\">Simple Java Mail</a> (Open Source JavaMail smtp wrapper):</p>\n\n<pre><code>final Email email = new Email();\n\nString host = \"smtp.gmail.com\";\nInteger port = 587;\nString from = \"username\";\nString pass = \"password\";\nString[] to = {\"[email protected]\"};\n\nemail.setFromAddress(\"\", from);\nemail.setSubject(\"sending in a group\");\nfor( int i=0; i < to.length; i++ ) {\n email.addRecipient(\"\", to[i], RecipientType.TO);\n}\nemail.setText(\"Welcome to JavaMail\");\n\nnew Mailer(host, port, from, pass).sendMail(email);\n// you could also still use your mail session instead\nnew Mailer(session).sendMail(email);\n</code></pre>\n"
},
{
"answer_id": 935714,
"author": "Ifnu",
"author_id": 115520,
"author_profile": "https://Stackoverflow.com/users/115520",
"pm_score": 1,
"selected": false,
"text": "<p>This is what I do when i want to send email with attachment, work fine. :)</p>\n\n<pre><code> public class NewClass {\n\n public static void main(String[] args) {\n try {\n Properties props = System.getProperties();\n props.put(\"mail.smtp.starttls.enable\", \"true\");\n props.put(\"mail.smtp.host\", \"smtp.gmail.com\");\n props.put(\"mail.smtp.auth\", \"true\");\n props.put(\"mail.smtp.port\", \"465\"); // smtp port\n Authenticator auth = new Authenticator() {\n\n @Override\n protected PasswordAuthentication getPasswordAuthentication() {\n return new PasswordAuthentication(\"username-gmail\", \"password-gmail\");\n }\n };\n Session session = Session.getDefaultInstance(props, auth);\n MimeMessage msg = new MimeMessage(session);\n msg.setFrom(new InternetAddress(\"[email protected]\"));\n msg.setSubject(\"Try attachment gmail\");\n msg.setRecipient(RecipientType.TO, new InternetAddress(\"[email protected]\"));\n //add atleast simple body\n MimeBodyPart body = new MimeBodyPart();\n body.setText(\"Try attachment\");\n //do attachment\n MimeBodyPart attachMent = new MimeBodyPart();\n FileDataSource dataSource = new FileDataSource(new File(\"file-sent.txt\"));\n attachMent.setDataHandler(new DataHandler(dataSource));\n attachMent.setFileName(\"file-sent.txt\");\n attachMent.setDisposition(MimeBodyPart.ATTACHMENT);\n Multipart multipart = new MimeMultipart();\n multipart.addBodyPart(body);\n multipart.addBodyPart(attachMent);\n msg.setContent(multipart);\n Transport.send(msg);\n } catch (AddressException ex) {\n Logger.getLogger(NewClass.class.getName()).log(Level.SEVERE, null, ex);\n } catch (MessagingException ex) {\n Logger.getLogger(NewClass.class.getName()).log(Level.SEVERE, null, ex);\n }\n }\n\n}\n</code></pre>\n"
},
{
"answer_id": 1013676,
"author": "Jason Thrasher",
"author_id": 124754,
"author_profile": "https://Stackoverflow.com/users/124754",
"pm_score": 5,
"selected": false,
"text": "<p>Other people have good answers above, but I wanted to add a note on my experience here. I've found that when using Gmail as an outbound SMTP server for my webapp, Gmail only lets me send ~10 or so messages before responding with an anti-spam response that I have to manually step through to re-enable SMTP access. The emails I was sending were not spam, but were website \"welcome\" emails when users registered with my system. So, YMMV, and I wouldn't rely on Gmail for a production webapp. If you're sending email on a user's behalf, like an installed desktop app (where the user enters their own Gmail credentials), you may be okay.</p>\n\n<p>Also, if you're using Spring, here's a working config to use Gmail for outbound SMTP:</p>\n\n<pre><code><bean id=\"mailSender\" class=\"org.springframework.mail.javamail.JavaMailSenderImpl\">\n <property name=\"defaultEncoding\" value=\"UTF-8\"/>\n <property name=\"host\" value=\"smtp.gmail.com\"/>\n <property name=\"port\" value=\"465\"/>\n <property name=\"username\" value=\"${mail.username}\"/>\n <property name=\"password\" value=\"${mail.password}\"/>\n <property name=\"javaMailProperties\">\n <value>\n mail.debug=true\n mail.smtp.auth=true\n mail.smtp.socketFactory.class=java.net.SocketFactory\n mail.smtp.socketFactory.fallback=false\n </value>\n </property>\n</bean>\n</code></pre>\n"
},
{
"answer_id": 3970608,
"author": "vishnu",
"author_id": 480749,
"author_profile": "https://Stackoverflow.com/users/480749",
"pm_score": 2,
"selected": false,
"text": "<pre><code>//set CLASSPATH=%CLASSPATH%;activation.jar;mail.jar\nimport javax.mail.*;\nimport javax.mail.internet.*;\nimport java.util.*;\n\npublic class Mail\n{\n String d_email = \"[email protected]\",\n d_password = \"****\",\n d_host = \"smtp.gmail.com\",\n d_port = \"465\",\n m_to = \"[email protected]\",\n m_subject = \"Testing\",\n m_text = \"Hey, this is the testing email using smtp.gmail.com.\";\n public static void main(String[] args)\n {\n String[] to={\"[email protected]\"};\n String[] cc={\"[email protected]\"};\n String[] bcc={\"[email protected]\"};\n //This is for google\n Mail.sendMail(\"[email protected]\", \"password\", \"smtp.gmail.com\", \n \"465\", \"true\", \"true\", \n true, \"javax.net.ssl.SSLSocketFactory\", \"false\", \n to, cc, bcc, \n \"hi baba don't send virus mails..\", \n \"This is my style...of reply..If u send virus mails..\");\n }\n\n public synchronized static boolean sendMail(\n String userName, String passWord, String host, \n String port, String starttls, String auth, \n boolean debug, String socketFactoryClass, String fallback, \n String[] to, String[] cc, String[] bcc, \n String subject, String text) \n {\n Properties props = new Properties();\n //Properties props=System.getProperties();\n props.put(\"mail.smtp.user\", userName);\n props.put(\"mail.smtp.host\", host);\n if(!\"\".equals(port))\n props.put(\"mail.smtp.port\", port);\n if(!\"\".equals(starttls))\n props.put(\"mail.smtp.starttls.enable\",starttls);\n props.put(\"mail.smtp.auth\", auth);\n if(debug) {\n props.put(\"mail.smtp.debug\", \"true\");\n } else {\n props.put(\"mail.smtp.debug\", \"false\"); \n }\n if(!\"\".equals(port))\n props.put(\"mail.smtp.socketFactory.port\", port);\n if(!\"\".equals(socketFactoryClass))\n props.put(\"mail.smtp.socketFactory.class\",socketFactoryClass);\n if(!\"\".equals(fallback))\n props.put(\"mail.smtp.socketFactory.fallback\", fallback);\n\n try\n {\n Session session = Session.getDefaultInstance(props, null);\n session.setDebug(debug);\n MimeMessage msg = new MimeMessage(session);\n msg.setText(text);\n msg.setSubject(subject);\n msg.setFrom(new InternetAddress(\"[email protected]\"));\n for(int i=0;i<to.length;i++) {\n msg.addRecipient(Message.RecipientType.TO, \n new InternetAddress(to[i]));\n }\n for(int i=0;i<cc.length;i++) {\n msg.addRecipient(Message.RecipientType.CC, \n new InternetAddress(cc[i]));\n }\n for(int i=0;i<bcc.length;i++) {\n msg.addRecipient(Message.RecipientType.BCC, \n new InternetAddress(bcc[i]));\n }\n msg.saveChanges();\n Transport transport = session.getTransport(\"smtp\");\n transport.connect(host, userName, passWord);\n transport.sendMessage(msg, msg.getAllRecipients());\n transport.close();\n return true;\n }\n catch (Exception mex)\n {\n mex.printStackTrace();\n return false;\n }\n }\n\n}\n</code></pre>\n"
},
{
"answer_id": 14191227,
"author": "Ripon Al Wasim",
"author_id": 617450,
"author_profile": "https://Stackoverflow.com/users/617450",
"pm_score": 3,
"selected": false,
"text": "<p>My complete code as below is working well:</p>\n\n<pre><code>package ripon.java.mail;\nimport java.util.*;\nimport javax.mail.*;\nimport javax.mail.internet.*;\n\npublic class SendEmail\n{\npublic static void main(String [] args)\n{ \n // Sender's email ID needs to be mentioned\n String from = \"[email protected]\";\n String pass =\"test123\";\n // Recipient's email ID needs to be mentioned.\n String to = \"[email protected]\";\n\n String host = \"smtp.gmail.com\";\n\n // Get system properties\n Properties properties = System.getProperties();\n // Setup mail server\n properties.put(\"mail.smtp.starttls.enable\", \"true\");\n properties.put(\"mail.smtp.host\", host);\n properties.put(\"mail.smtp.user\", from);\n properties.put(\"mail.smtp.password\", pass);\n properties.put(\"mail.smtp.port\", \"587\");\n properties.put(\"mail.smtp.auth\", \"true\");\n\n // Get the default Session object.\n Session session = Session.getDefaultInstance(properties);\n\n try{\n // Create a default MimeMessage object.\n MimeMessage message = new MimeMessage(session);\n\n // Set From: header field of the header.\n message.setFrom(new InternetAddress(from));\n\n // Set To: header field of the header.\n message.addRecipient(Message.RecipientType.TO,\n new InternetAddress(to));\n\n // Set Subject: header field\n message.setSubject(\"This is the Subject Line!\");\n\n // Now set the actual message\n message.setText(\"This is actual message\");\n\n // Send message\n Transport transport = session.getTransport(\"smtp\");\n transport.connect(host, from, pass);\n transport.sendMessage(message, message.getAllRecipients());\n transport.close();\n System.out.println(\"Sent message successfully....\");\n }catch (MessagingException mex) {\n mex.printStackTrace();\n }\n}\n}\n</code></pre>\n"
},
{
"answer_id": 20550855,
"author": "Bryan",
"author_id": 908570,
"author_profile": "https://Stackoverflow.com/users/908570",
"pm_score": 2,
"selected": false,
"text": "<p>The posted code solutions may cause problems when you need to set up multiple SMTP sessions anywhere within the same JVM.</p>\n\n<p>The JavaMail FAQ recommends using</p>\n\n<pre><code>Session.getInstance(properties);\n</code></pre>\n\n<p>instead of</p>\n\n<pre><code>Session.getDefaultInstance(properties);\n</code></pre>\n\n<p>because the getDefault will only use the properties given the first time it is invoked. All later uses of the default instance will ignore property changes.</p>\n\n<p>See <a href=\"http://www.oracle.com/technetwork/java/faq-135477.html#getdefaultinstance\" rel=\"nofollow\">http://www.oracle.com/technetwork/java/faq-135477.html#getdefaultinstance</a></p>\n"
},
{
"answer_id": 21800051,
"author": "Pyare",
"author_id": 1911977,
"author_profile": "https://Stackoverflow.com/users/1911977",
"pm_score": 0,
"selected": false,
"text": "<p>Hi try this code....</p>\n\n<pre><code>package my.test.service;\n\nimport java.util.Properties;\n\nimport javax.mail.Authenticator;\nimport javax.mail.MessagingException;\nimport javax.mail.PasswordAuthentication;\nimport javax.mail.Session;\nimport javax.mail.Message;\nimport javax.mail.Transport;\nimport javax.mail.internet.AddressException;\nimport javax.mail.internet.InternetAddress;\nimport javax.mail.internet.MimeMessage;\n\npublic class Sample {\n public static void main(String args[]) {\n final String SMTP_HOST = \"smtp.gmail.com\";\n final String SMTP_PORT = \"587\";\n final String GMAIL_USERNAME = \"[email protected]\";\n final String GMAIL_PASSWORD = \"xxxxxxxxxx\";\n\n System.out.println(\"Process Started\");\n\n Properties prop = System.getProperties();\n prop.setProperty(\"mail.smtp.starttls.enable\", \"true\");\n prop.setProperty(\"mail.smtp.host\", SMTP_HOST);\n prop.setProperty(\"mail.smtp.user\", GMAIL_USERNAME);\n prop.setProperty(\"mail.smtp.password\", GMAIL_PASSWORD);\n prop.setProperty(\"mail.smtp.port\", SMTP_PORT);\n prop.setProperty(\"mail.smtp.auth\", \"true\");\n System.out.println(\"Props : \" + prop);\n\n Session session = Session.getInstance(prop, new Authenticator() {\n protected PasswordAuthentication getPasswordAuthentication() {\n return new PasswordAuthentication(GMAIL_USERNAME,\n GMAIL_PASSWORD);\n }\n });\n\n System.out.println(\"Got Session : \" + session);\n\n MimeMessage message = new MimeMessage(session);\n try {\n System.out.println(\"before sending\");\n message.setFrom(new InternetAddress(GMAIL_USERNAME));\n message.addRecipients(Message.RecipientType.TO,\n InternetAddress.parse(GMAIL_USERNAME));\n message.setSubject(\"My First Email Attempt from Java\");\n message.setText(\"Hi, This mail came from Java Application.\");\n message.setRecipients(Message.RecipientType.TO,\n InternetAddress.parse(GMAIL_USERNAME));\n Transport transport = session.getTransport(\"smtp\");\n System.out.println(\"Got Transport\" + transport);\n transport.connect(SMTP_HOST, GMAIL_USERNAME, GMAIL_PASSWORD);\n transport.sendMessage(message, message.getAllRecipients());\n System.out.println(\"message Object : \" + message);\n System.out.println(\"Email Sent Successfully\");\n } catch (AddressException e) {\n // TODO Auto-generated catch block\n e.printStackTrace();\n } catch (MessagingException e) {\n // TODO Auto-generated catch block\n e.printStackTrace();\n }\n }\n}\n</code></pre>\n"
},
{
"answer_id": 27402060,
"author": "AlikElzin-kilaka",
"author_id": 435605,
"author_profile": "https://Stackoverflow.com/users/435605",
"pm_score": 2,
"selected": false,
"text": "<p>The minimum required:</p>\n\n<pre><code>import java.util.Properties;\n\nimport javax.mail.Message;\nimport javax.mail.MessagingException;\nimport javax.mail.PasswordAuthentication;\nimport javax.mail.Session;\nimport javax.mail.Transport;\nimport javax.mail.internet.AddressException;\nimport javax.mail.internet.InternetAddress;\nimport javax.mail.internet.MimeMessage;\n\npublic class MessageSender {\n\n public static void sendHardCoded() throws AddressException, MessagingException {\n String to = \"[email protected]\";\n final String from = \"[email protected]\";\n\n Properties properties = new Properties();\n properties.put(\"mail.smtp.starttls.enable\", \"true\");\n properties.put(\"mail.smtp.auth\", \"true\");\n properties.put(\"mail.smtp.host\", \"smtp.gmail.com\");\n properties.put(\"mail.smtp.port\", \"587\");\n\n Session session = Session.getInstance(properties,\n new javax.mail.Authenticator() {\n protected PasswordAuthentication getPasswordAuthentication() {\n return new PasswordAuthentication(from, \"BeNice\");\n }\n });\n\n MimeMessage message = new MimeMessage(session);\n message.setFrom(new InternetAddress(from));\n message.addRecipient(Message.RecipientType.TO, new InternetAddress(to));\n message.setSubject(\"Hello\");\n message.setText(\"What's up?\");\n\n Transport.send(message);\n }\n\n}\n</code></pre>\n"
},
{
"answer_id": 31224370,
"author": "BullyWiiPlaza",
"author_id": 3764804,
"author_profile": "https://Stackoverflow.com/users/3764804",
"pm_score": 0,
"selected": false,
"text": "<p>Here's an easy-to-use class for sending emails with <a href=\"https://mail.google.com/\" rel=\"nofollow\"><code>Gmail</code></a>. You need to have the <a href=\"https://java.net/projects/javamail/pages/Home\" rel=\"nofollow\"><code>JavaMail</code></a> library <a href=\"http://www.wikihow.com/Add-JARs-to-Project-Build-Paths-in-Eclipse-(Java)\" rel=\"nofollow\">added to your build path</a> or just use <a href=\"http://mvnrepository.com/artifact/javax.mail\" rel=\"nofollow\"><code>Maven</code></a>.</p>\n\n<pre><code>import java.util.Properties;\n\nimport javax.activation.DataHandler;\nimport javax.activation.DataSource;\nimport javax.activation.FileDataSource;\nimport javax.mail.BodyPart;\nimport javax.mail.Message;\nimport javax.mail.MessagingException;\nimport javax.mail.Multipart;\nimport javax.mail.Session;\nimport javax.mail.Transport;\nimport javax.mail.internet.AddressException;\nimport javax.mail.internet.InternetAddress;\nimport javax.mail.internet.MimeBodyPart;\nimport javax.mail.internet.MimeMessage;\nimport javax.mail.internet.MimeMultipart;\n\npublic class GmailSender\n{\n private static String protocol = \"smtp\";\n\n private String username;\n private String password;\n\n private Session session;\n private Message message;\n private Multipart multipart;\n\n public GmailSender()\n {\n this.multipart = new MimeMultipart();\n }\n\n public void setSender(String username, String password)\n {\n this.username = username;\n this.password = password;\n\n this.session = getSession();\n this.message = new MimeMessage(session);\n }\n\n public void addRecipient(String recipient) throws AddressException, MessagingException\n {\n message.addRecipient(Message.RecipientType.TO, new InternetAddress(recipient));\n }\n\n public void setSubject(String subject) throws MessagingException\n {\n message.setSubject(subject);\n }\n\n public void setBody(String body) throws MessagingException\n {\n BodyPart messageBodyPart = new MimeBodyPart();\n messageBodyPart.setText(body);\n multipart.addBodyPart(messageBodyPart);\n\n message.setContent(multipart);\n }\n\n public void send() throws MessagingException\n {\n Transport transport = session.getTransport(protocol);\n transport.connect(username, password);\n transport.sendMessage(message, message.getAllRecipients());\n\n transport.close();\n }\n\n public void addAttachment(String filePath) throws MessagingException\n {\n BodyPart messageBodyPart = getFileBodyPart(filePath);\n multipart.addBodyPart(messageBodyPart);\n\n message.setContent(multipart);\n }\n\n private BodyPart getFileBodyPart(String filePath) throws MessagingException\n {\n BodyPart messageBodyPart = new MimeBodyPart();\n DataSource dataSource = new FileDataSource(filePath);\n messageBodyPart.setDataHandler(new DataHandler(dataSource));\n messageBodyPart.setFileName(filePath);\n\n return messageBodyPart;\n }\n\n private Session getSession()\n {\n Properties properties = getMailServerProperties();\n Session session = Session.getDefaultInstance(properties);\n\n return session;\n }\n\n private Properties getMailServerProperties()\n {\n Properties properties = System.getProperties();\n properties.put(\"mail.smtp.starttls.enable\", \"true\");\n properties.put(\"mail.smtp.host\", protocol + \".gmail.com\");\n properties.put(\"mail.smtp.user\", username);\n properties.put(\"mail.smtp.password\", password);\n properties.put(\"mail.smtp.port\", \"587\");\n properties.put(\"mail.smtp.auth\", \"true\");\n\n return properties;\n }\n}\n</code></pre>\n\n<p>Example usage:</p>\n\n<pre><code>GmailSender sender = new GmailSender();\nsender.setSender(\"[email protected]\", \"mypassword\");\nsender.addRecipient(\"[email protected]\");\nsender.setSubject(\"The subject\");\nsender.setBody(\"The body\");\nsender.addAttachment(\"TestFile.txt\");\nsender.send();\n</code></pre>\n"
},
{
"answer_id": 41347492,
"author": "Inzimam Tariq IT",
"author_id": 5055401,
"author_profile": "https://Stackoverflow.com/users/5055401",
"pm_score": 0,
"selected": false,
"text": "<p>If you want to use outlook with <code>Javamail API</code> then use </p>\n\n<pre><code>smtp-mail.outlook.com\n</code></pre>\n\n<p>as a <strong>host</strong> for more and complete working code <a href=\"https://stackoverflow.com/questions/39218352/how-to-send-an-email-from-outlook-via-java/41347253#41347253\">Check out this answer</a>.</p>\n"
},
{
"answer_id": 62555019,
"author": "Reto Höhener",
"author_id": 1124509,
"author_profile": "https://Stackoverflow.com/users/1124509",
"pm_score": 2,
"selected": false,
"text": "<p>Value added:</p>\n<ul>\n<li><strong>encoding pitfalls</strong> in subject, message and display name</li>\n<li><strong>only one magic property</strong> is needed for modern java mail library versions</li>\n<li><code>Session.getInstance()</code> recommended over <code>Session.getDefaultInstance()</code></li>\n<li><strong>attachment</strong> in the same example</li>\n<li><strong>still works</strong> after <a href=\"https://gsuiteupdates.googleblog.com/2019/12/less-secure-apps-oauth-google-username-password-incorrect.html\" rel=\"nofollow noreferrer\">Google turns off less secure apps</a>: Enable 2-factor authentication in your organization -> turn on 2FA -> generate app password.</li>\n</ul>\n<pre><code> import java.io.File;\n import java.nio.charset.StandardCharsets;\n import java.util.Properties;\n import java.util.logging.Level;\n import java.util.logging.Logger;\n import javax.activation.DataHandler;\n import javax.mail.Message;\n import javax.mail.Session;\n import javax.mail.Transport;\n import javax.mail.internet.InternetAddress;\n import javax.mail.internet.MimeBodyPart;\n import javax.mail.internet.MimeMessage;\n import javax.mail.internet.MimeMultipart;\n import javax.mail.util.ByteArrayDataSource;\n \n public class Gmailer {\n private static final Logger LOGGER = Logger.getLogger(Gmailer.class.getName());\n \n public static void main(String[] args) {\n send();\n }\n \n public static void send() {\n Transport transport = null;\n try {\n String accountEmail = "[email protected]";\n String accountAppPassword = "";\n String displayName = "Display-Name 東";\n String replyTo = "[email protected]";\n \n String to = "[email protected]";\n String cc = "[email protected]";\n String bcc = "[email protected]";\n \n String subject = "Subject 東";\n String message = "<span style='color: red;'>東</span>";\n String type = "html"; // or "plain"\n String mimeTypeWithEncoding = "text/" + type + "; charset=" + StandardCharsets.UTF_8.name();\n \n File attachmentFile = new File("Attachment.pdf");\n // https://developer.mozilla.org/en-US/docs/Web/HTTP/Basics_of_HTTP/MIME_types/Common_types\n String attachmentMimeType = "application/pdf";\n byte[] bytes = ...; // read file to byte array\n \n Properties properties = System.getProperties();\n properties.put("mail.debug", "true");\n // i found that this is the only property necessary for a modern java mail version\n properties.put("mail.smtp.starttls.enable", "true");\n // https://javaee.github.io/javamail/FAQ#getdefaultinstance\n Session session = Session.getInstance(properties);\n \n MimeMessage mimeMessage = new MimeMessage(session);\n \n // probably best to use the account email address, to avoid landing in spam or blacklists\n // not even sure if the server would accept a differing from address\n InternetAddress from = new InternetAddress(accountEmail);\n from.setPersonal(displayName, StandardCharsets.UTF_8.name());\n mimeMessage.setFrom(from);\n \n mimeMessage.setReplyTo(InternetAddress.parse(replyTo));\n \n mimeMessage.setRecipients(Message.RecipientType.TO, InternetAddress.parse(to));\n mimeMessage.setRecipients(Message.RecipientType.CC, InternetAddress.parse(cc));\n mimeMessage.setRecipients(Message.RecipientType.BCC, InternetAddress.parse(bcc));\n \n mimeMessage.setSubject(subject, StandardCharsets.UTF_8.name());\n \n MimeMultipart multipart = new MimeMultipart();\n \n MimeBodyPart messagePart = new MimeBodyPart();\n messagePart.setContent(mimeMessage, mimeTypeWithEncoding);\n multipart.addBodyPart(messagePart);\n \n MimeBodyPart attachmentPart = new MimeBodyPart();\n attachmentPart.setDataHandler(new DataHandler(new ByteArrayDataSource(bytes, attachmentMimeType)));\n attachmentPart.setFileName(attachmentFile.getName());\n multipart.addBodyPart(attachmentPart);\n \n mimeMessage.setContent(multipart);\n \n transport = session.getTransport();\n transport.connect("smtp.gmail.com", 587, accountEmail, accountAppPassword);\n transport.sendMessage(mimeMessage, mimeMessage.getAllRecipients());\n }\n catch(Exception e) {\n // I prefer to bubble up exceptions, so the caller has the info that someting went wrong, and gets a chance to handle it.\n // I also prefer not to force the exception in the signature.\n throw e instanceof RuntimeException ? (RuntimeException) e : new RuntimeException(e);\n }\n finally {\n if(transport != null) {\n try {\n transport.close();\n }\n catch(Exception e) {\n LOGGER.log(Level.WARNING, "failed to close java mail transport: " + e);\n }\n }\n }\n }\n }\n</code></pre>\n"
}
] | 2008/09/05 | [
"https://Stackoverflow.com/questions/46663",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1288/"
] | Is it possible to send an email from my Java application using a GMail account? I have configured my company mail server with Java app to send email, but that's not going to cut it when I distribute the application. Answers with any of using Hotmail, Yahoo or GMail are acceptable. | First download the [JavaMail API](https://java.net/projects/javamail/pages/Home) and make sure the relevant jar files are in your classpath.
Here's a full working example using GMail.
```
import java.util.*;
import javax.mail.*;
import javax.mail.internet.*;
public class Main {
private static String USER_NAME = "*****"; // GMail user name (just the part before "@gmail.com")
private static String PASSWORD = "********"; // GMail password
private static String RECIPIENT = "[email protected]";
public static void main(String[] args) {
String from = USER_NAME;
String pass = PASSWORD;
String[] to = { RECIPIENT }; // list of recipient email addresses
String subject = "Java send mail example";
String body = "Welcome to JavaMail!";
sendFromGMail(from, pass, to, subject, body);
}
private static void sendFromGMail(String from, String pass, String[] to, String subject, String body) {
Properties props = System.getProperties();
String host = "smtp.gmail.com";
props.put("mail.smtp.starttls.enable", "true");
props.put("mail.smtp.host", host);
props.put("mail.smtp.user", from);
props.put("mail.smtp.password", pass);
props.put("mail.smtp.port", "587");
props.put("mail.smtp.auth", "true");
Session session = Session.getDefaultInstance(props);
MimeMessage message = new MimeMessage(session);
try {
message.setFrom(new InternetAddress(from));
InternetAddress[] toAddress = new InternetAddress[to.length];
// To get the array of addresses
for( int i = 0; i < to.length; i++ ) {
toAddress[i] = new InternetAddress(to[i]);
}
for( int i = 0; i < toAddress.length; i++) {
message.addRecipient(Message.RecipientType.TO, toAddress[i]);
}
message.setSubject(subject);
message.setText(body);
Transport transport = session.getTransport("smtp");
transport.connect(host, from, pass);
transport.sendMessage(message, message.getAllRecipients());
transport.close();
}
catch (AddressException ae) {
ae.printStackTrace();
}
catch (MessagingException me) {
me.printStackTrace();
}
}
}
```
Naturally, you'll want to do more in the `catch` blocks than print the stack trace as I did in the example code above. (Remove the `catch` blocks to see which method calls from the JavaMail API throw exceptions so you can better see how to properly handle them.)
---
Thanks to [@jodonnel](https://stackoverflow.com/users/4223/jodonnell) and everyone else who answered. I'm giving him a bounty because his answer led me about 95% of the way to a complete answer. |
46,704 | <p>For the following HTML:</p>
<pre><code><form name="myForm">
<label>One<input name="area" type="radio" value="S" /></label>
<label>Two<input name="area" type="radio" value="R" /></label>
<label>Three<input name="area" type="radio" value="O" /></label>
<label>Four<input name="area" type="radio" value="U" /></label>
</form>
</code></pre>
<p>Changing from the following JavaScript code:</p>
<pre><code>$(function() {
var myForm = document.myForm;
var radios = myForm.area;
// Loop through radio buttons
for (var i=0; i<radios.length; i++) {
if (radios[i].value == "S") {
radios[i].checked = true; // Selected when form displays
radioClicks(); // Execute the function, initial setup
}
radios[i].onclick = radioClicks; // Assign to run when clicked
}
});
</code></pre>
<p>Thanks</p>
<p>EDIT: The response I selected answers the question I asked, however I like the answer that uses <code>bind()</code> because it also shows how to distinguish the group of radio buttons</p>
| [
{
"answer_id": 46715,
"author": "Adam Cuzzort",
"author_id": 4760,
"author_profile": "https://Stackoverflow.com/users/4760",
"pm_score": 1,
"selected": false,
"text": "<pre><code>$(function() {\n $('input[@type=\"radio\"]').click(radioClicks);\n});\n</code></pre>\n"
},
{
"answer_id": 46717,
"author": "Ben Scheirman",
"author_id": 3381,
"author_profile": "https://Stackoverflow.com/users/3381",
"pm_score": 2,
"selected": false,
"text": "<pre><code>$(function() {\n\n $(\"form#myForm input[type='radio']\").click( fn );\n\n});\n\nfunction fn()\n{\n //do stuff here\n}\n</code></pre>\n"
},
{
"answer_id": 46733,
"author": "pix0r",
"author_id": 72,
"author_profile": "https://Stackoverflow.com/users/72",
"pm_score": 0,
"selected": false,
"text": "<p>I think something like this should work (but it's untested):</p>\n\n<pre><code>$(\"input[@type='radio']\").each(function(i) {\n if (this.val() == 'E') {\n radioClicks();\n this.get().checked = true;\n }\n}\n$(\"input[@type='radio']\").click(radioClicks);\n</code></pre>\n"
},
{
"answer_id": 46735,
"author": "Chris Zwiryk",
"author_id": 734,
"author_profile": "https://Stackoverflow.com/users/734",
"pm_score": 0,
"selected": false,
"text": "<pre><code>$(function() {\n $('#myForm :radio').each(function() {\n if ($(this).value == 'S') {\n $(this).attr(\"checked\", true);\n radioClicks();\n }\n\n $(this).click(radioClicks);\n });\n});\n</code></pre>\n"
},
{
"answer_id": 46800,
"author": "Juan",
"author_id": 550,
"author_profile": "https://Stackoverflow.com/users/550",
"pm_score": 5,
"selected": true,
"text": "<pre><code>$( function() {\n $(\"input:radio\")\n .click(radioClicks)\n .filter(\"[value='S']\")\n .attr(\"checked\", \"checked\");\n});\n</code></pre>\n"
},
{
"answer_id": 46824,
"author": "rp.",
"author_id": 2536,
"author_profile": "https://Stackoverflow.com/users/2536",
"pm_score": 4,
"selected": false,
"text": "<pre><code>$(document).ready(function(){\n $(\"input[name='area']\").bind(\"click\", radioClicks);\n});\n\nfunctionradioClicks() {\n alert($(this).val());\n}\n</code></pre>\n\n<p>I like to use <code>bind()</code> instead of directly wiring the event handler because you can pass additional data to the event hander (not shown here but the data is a third bind() argument) and because you can easily unbind it (and you can bind and unbind by group--see the jQuery docs).</p>\n\n<p><a href=\"http://docs.jquery.com/Events/bind#typedatafn\" rel=\"nofollow noreferrer\">http://docs.jquery.com/Events/bind#typedatafn</a></p>\n"
}
] | 2008/09/05 | [
"https://Stackoverflow.com/questions/46704",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2755/"
] | For the following HTML:
```
<form name="myForm">
<label>One<input name="area" type="radio" value="S" /></label>
<label>Two<input name="area" type="radio" value="R" /></label>
<label>Three<input name="area" type="radio" value="O" /></label>
<label>Four<input name="area" type="radio" value="U" /></label>
</form>
```
Changing from the following JavaScript code:
```
$(function() {
var myForm = document.myForm;
var radios = myForm.area;
// Loop through radio buttons
for (var i=0; i<radios.length; i++) {
if (radios[i].value == "S") {
radios[i].checked = true; // Selected when form displays
radioClicks(); // Execute the function, initial setup
}
radios[i].onclick = radioClicks; // Assign to run when clicked
}
});
```
Thanks
EDIT: The response I selected answers the question I asked, however I like the answer that uses `bind()` because it also shows how to distinguish the group of radio buttons | ```
$( function() {
$("input:radio")
.click(radioClicks)
.filter("[value='S']")
.attr("checked", "checked");
});
``` |
46,718 | <p>I'm just curious how most people make their ASP.NET pages printer-friendly? Do you create a separate printer-friendly version of the ASPX page, use CSS or something else? How do you handle situations like page breaks and wide tables?</p>
<p>Is there one elegant solution that works for the majority of the cases? </p>
| [
{
"answer_id": 46724,
"author": "Ryan Farley",
"author_id": 1627,
"author_profile": "https://Stackoverflow.com/users/1627",
"pm_score": 5,
"selected": true,
"text": "<p>You basically make another CSS file that hide things or gives simpler \"printer-friendly\" style to things then add that with a <code>media=\"print\"</code> so that it only applies to print media (when it is printed)</p>\n\n<pre><code><link rel=\"stylesheet\" type=\"text/css\" media=\"print\" href=\"print.css\" />\n</code></pre>\n"
},
{
"answer_id": 46728,
"author": "Alexander Morland",
"author_id": 4013,
"author_profile": "https://Stackoverflow.com/users/4013",
"pm_score": 0,
"selected": false,
"text": "<p>I am a php user, but the point must be that the result no matter what is HTML and HTML is styled with CSS and there is an option for your style sheets for just using the style for printing. This should be the way to do it, imho. About big tables, there isnt really a magic \"fix\" for that. Page will break where it breaks, dont really understand the problem here either. </p>\n\n<pre><code><link rel=\"stylesheet\" type=\"text/css\" media=\"print\" href=\"print.css\" /> \n<link rel=\"stylesheet\" type=\"text/css\" media=\"screen\" href=\"screen.css\" />\n</code></pre>\n"
},
{
"answer_id": 46742,
"author": "Ian Nelson",
"author_id": 2084,
"author_profile": "https://Stackoverflow.com/users/2084",
"pm_score": 3,
"selected": false,
"text": "<p>Our gracious host wrote a good blog post on this topic:</p>\n\n<p><a href=\"http://blog.codinghorror.com/stylesheets-for-print-and-handheld/\" rel=\"nofollow noreferrer\">Coding Horror: Stylesheets for Print and Handheld</a></p>\n"
}
] | 2008/09/05 | [
"https://Stackoverflow.com/questions/46718",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3329/"
] | I'm just curious how most people make their ASP.NET pages printer-friendly? Do you create a separate printer-friendly version of the ASPX page, use CSS or something else? How do you handle situations like page breaks and wide tables?
Is there one elegant solution that works for the majority of the cases? | You basically make another CSS file that hide things or gives simpler "printer-friendly" style to things then add that with a `media="print"` so that it only applies to print media (when it is printed)
```
<link rel="stylesheet" type="text/css" media="print" href="print.css" />
``` |
46,719 | <p>I have a regex call that I need help with.</p>
<p>I haven't posted my regex, because it is not relevant here.
What I want to be able to do is, during the Replace, I also want to modify the ${test} portion by doing a Html.Encode on the entire text that is effecting the regex.</p>
<p>Basically, wrap the entire text that is within the range of the regex with the bold tag, but also Html.Encode the text inbetween the bold tag.</p>
<pre><code>RegexOptions regexOptions = RegexOptions.Compiled | RegexOptions.IgnoreCase;
text = Regex.Replace(text, regexBold, @"<b>${text}</b>", regexOptions);
</code></pre>
| [
{
"answer_id": 46722,
"author": "Ben Scheirman",
"author_id": 3381,
"author_profile": "https://Stackoverflow.com/users/3381",
"pm_score": 2,
"selected": false,
"text": "<p>Don't use Regex.Replace in this case... use..</p>\n\n<pre><code>foreach(Match in Regex.Matches(...))\n{\n //do your stuff here\n}\n</code></pre>\n"
},
{
"answer_id": 46725,
"author": "DevelopingChris",
"author_id": 1220,
"author_profile": "https://Stackoverflow.com/users/1220",
"pm_score": 0,
"selected": false,
"text": "<p>If you do a Regex.Match, the resulting match objects group at the 0th index, is the subset of the intput that matched the regex.</p>\n\n<p>you can use this to stitch in the bold tags and encode it there.</p>\n"
},
{
"answer_id": 46761,
"author": "public static",
"author_id": 1368,
"author_profile": "https://Stackoverflow.com/users/1368",
"pm_score": 0,
"selected": false,
"text": "<p>Can you fill in the code inside {} to add the bold tag, and encode the text?\nI'm confused as to how to apply the changes to the entire text block AND replace the section in the text variable at the end.</p>\n"
},
{
"answer_id": 46785,
"author": "DevelopingChris",
"author_id": 1220,
"author_profile": "https://Stackoverflow.com/users/1220",
"pm_score": 3,
"selected": true,
"text": "<p>Heres an implementation of this I've used to pick out special replace strings from content and localize them.</p>\n\n<pre><code> protected string FindAndTranslateIn(string content)\n {\n return Regex.Replace(content, @\"\\{\\^(.+?);(.+?)?}\", new MatchEvaluator(TranslateHandler), RegexOptions.IgnoreCase);\n }\n\npublic string TranslateHandler(Match m)\n{\n if (m.Success)\n {\n string key = m.Groups[1].Value;\n key = FindAndTranslateIn(key);\n string def = string.Empty;\n if (m.Groups.Count > 2)\n {\n def = m.Groups[2].Value;\n if(def.Length > 1)\n {\n def = FindAndTranslateIn(def);\n }\n }\n\n if (group == null)\n {\n return Translate(key, def);\n }\n else\n {\n return Translate(key, group, def);\n }\n }\n return string.Empty;\n}\n</code></pre>\n\n<p>From the match evaluator delegate you return everything you want replaced, so where I have returns you would have bold tags and an encode call, mine also supports recursion, so a little over complicated for your needs, but you can just pare down the example for your needs.</p>\n\n<p>This is equivalent to doing an iteration over the collection of matches and doing parts of the replace methods job. It just saves you some code, and you get to use a fancy shmancy delegate.</p>\n"
},
{
"answer_id": 46810,
"author": "viggity",
"author_id": 4572,
"author_profile": "https://Stackoverflow.com/users/4572",
"pm_score": 2,
"selected": false,
"text": "<p>There is an incredibly easy way of doing this (in .net). Its called a MatchEvaluator and it lets you do all sorts of cool find and replace. Essentially you just feed the Regex.Replace method the method name of a method that returns a string and takes in a Match object as its only parameter. Do whatever makes sense for your particular match (html encode) and the string you return will replace the entire text of the match in the input string. </p>\n\n<p>Example: Lets say you wanted to find all the places where there are two numbers being added (in text) and you want to replace the expression with the actual number. You can't do that with a strict regex approach, but you can when you throw in a MatchEvaluator it becomes easy.</p>\n\n<pre><code>public void Stuff()\n{\n string pattern = @\"(?<firstNumber>\\d+)\\s*(?<operator>[*+-/])\\s*(?<secondNumber>\\d+)\";\n string input = \"something something 123 + 456 blah blah 100 - 55\";\n string output = Regex.Replace(input, pattern, MatchMath);\n //output will be \"something something 579 blah blah 45\"\n}\n\nprivate static string MatchMath(Match match)\n{\n try\n {\n double first = double.Parse(match.Groups[\"firstNumber\"].Value);\n double second = double.Parse(match.Groups[\"secondNumber\"].Value);\n switch (match.Groups[\"operator\"].Value)\n {\n case \"*\":\n return (first * second).ToString();\n case \"+\":\n return (first + second).ToString();\n case \"-\":\n return (first - second).ToString();\n case \"/\":\n return (first / second).ToString();\n }\n }\n catch { }\n return \"NaN\"; \n}\n</code></pre>\n\n<p>Find out more at <a href=\"http://msdn.microsoft.com/en-us/library/system.text.regularexpressions.matchevaluator.aspx\" rel=\"nofollow noreferrer\">http://msdn.microsoft.com/en-us/library/system.text.regularexpressions.matchevaluator.aspx</a></p>\n"
}
] | 2008/09/05 | [
"https://Stackoverflow.com/questions/46719",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1368/"
] | I have a regex call that I need help with.
I haven't posted my regex, because it is not relevant here.
What I want to be able to do is, during the Replace, I also want to modify the ${test} portion by doing a Html.Encode on the entire text that is effecting the regex.
Basically, wrap the entire text that is within the range of the regex with the bold tag, but also Html.Encode the text inbetween the bold tag.
```
RegexOptions regexOptions = RegexOptions.Compiled | RegexOptions.IgnoreCase;
text = Regex.Replace(text, regexBold, @"<b>${text}</b>", regexOptions);
``` | Heres an implementation of this I've used to pick out special replace strings from content and localize them.
```
protected string FindAndTranslateIn(string content)
{
return Regex.Replace(content, @"\{\^(.+?);(.+?)?}", new MatchEvaluator(TranslateHandler), RegexOptions.IgnoreCase);
}
public string TranslateHandler(Match m)
{
if (m.Success)
{
string key = m.Groups[1].Value;
key = FindAndTranslateIn(key);
string def = string.Empty;
if (m.Groups.Count > 2)
{
def = m.Groups[2].Value;
if(def.Length > 1)
{
def = FindAndTranslateIn(def);
}
}
if (group == null)
{
return Translate(key, def);
}
else
{
return Translate(key, group, def);
}
}
return string.Empty;
}
```
From the match evaluator delegate you return everything you want replaced, so where I have returns you would have bold tags and an encode call, mine also supports recursion, so a little over complicated for your needs, but you can just pare down the example for your needs.
This is equivalent to doing an iteration over the collection of matches and doing parts of the replace methods job. It just saves you some code, and you get to use a fancy shmancy delegate. |
46,777 | <p>I want to run a web application on php and mysql, using the CakePHP framework. And to keep the threshold of using the site at a very low place, I want to not use the standard login with username/password. (And I don't want to hassle my users with something like OpenID either. Goes to user type.)</p>
<p>So I'm thinking that the users shall be able to log in by sending an email to [email protected] with no subject or content required. And they will get, in reply, an email with a link that will log them in (it will contain a hash). Also I will let the users do some actions without even visiting the site at all, just send an email with [email protected] and the command will be carried out. I will assume that the users and their email providers takes care of their email account security and as such there is no need for it on my site.</p>
<p>Now, how do I go from an email is sent to an account that is not read by humans to there being fired off some script (basically a "dummy browser client" calls an url( and the cakephp will take care of the rest)?</p>
<hr>
<p>I have never used a cron job before, but I do think I understand their purpose or how they generally work. I can not have the script be called by random people visiting the site, as that solution won't work for several reasons. I think I would like to hear more about the possibility of having the script be run as response to an email coming in, if anyone has any input at all on that. If it's run as a cron job it would only check every X minutes and users would get a lag in their response (if i understand it correctly). </p>
<p>Since there will be different email addresses for different commands, like <strong>login</strong>@domain.com and I know what to do and how to do it to based on the sender email, i dont even need the content, subject or any other headers from the email.</p>
<hr>
<p>There is a lot of worry about security of this application, I understand the issues, but without giving away my concept, I dont think it is a big issue for what I am doing. Also about the usability issue, there really isnt any. It's just gonna be login to provide changes on a users profile if/when they need that and one other command. And this is the main email and is very easy to remember and the outset of this whole concept.</p>
| [
{
"answer_id": 46792,
"author": "Michael Stum",
"author_id": 91,
"author_profile": "https://Stackoverflow.com/users/91",
"pm_score": 2,
"selected": false,
"text": "<p>You'll need some sort of CronJob/Timer Service that checks the Mailbox regularly and then acts on it. Alternatively, you should check the mailserver if it can run a script when a mail arrives (i.e. see if it's possible to put a spamfilter-script in and \"abuse\" that functionality to call your script instead).</p>\n\n<p>With pure PHP, you're mostly out of luck as something needs to trigger the script. On a Pagewith a LOT of traffic, you could have your index.php or whatever do the check, but when no one visits your site for quite some time, then the mail will not be sent, and you have to be careful of \"race conditions\" when multiple people are accessing the script at the same time.</p>\n\n<p><strong>Edit:</strong> Just keep one usability flaw in mind: People with Multiple PCs and without an e-Mail Client on every one. For example, I use 4 PCs, but only 1 (my main one) has a Mail Client installed, and I use Webmail to check the other ones. Now, logging in and sending a mail through Webmail is not the greatest usability - in order to use YOUR site, I first have to log in to ANOTHER site, compose a mail through the crappy interface most Webmail tools have and wait for answer. Could as well use OpenID there :-)</p>\n"
},
{
"answer_id": 46794,
"author": "Mark Biek",
"author_id": 305,
"author_profile": "https://Stackoverflow.com/users/305",
"pm_score": 4,
"selected": true,
"text": "<p>I have used the <a href=\"http://www.phpclasses.org/browse/file/3.html\" rel=\"nofollow noreferrer\">pop3 php class</a> with great success (there is also a <a href=\"http://pear.php.net/package/Net_POP3\" rel=\"nofollow noreferrer\">Pear POP3 module</a>).</p>\n\n<p>Using the pop3 class looks something like this:</p>\n\n<pre><code>require ('pop3.php');\n\n$pop3 = new pop3_class();\n$pop3->hostname = MAILHOST;\n$pop3->Open();\n$pop3->Login('[email protected]', 'mypassword');\n\nforeach($pop3->ListMessages(\"\",\"\") as $msgidx => $msgsize)\n{\n $headers = \"\";\n $body = \"\";\n\n $pop3->RetrieveMessage($msgidx, $headers, $body, -1);\n}\n</code></pre>\n\n<p>I use it to monitor a POP3 mailbox which feeds into a database. </p>\n\n<p>It gets called by a cronjob which uses wget to call the url to my php script.</p>\n\n<pre><code>*/5 * * * * \"wget -q --http-user=me --http-passwd=pass 'http://mydomain.com/mail.php'\" >> /dev/null 2>&1\n</code></pre>\n\n<p><strong>Edit</strong></p>\n\n<p>I've been thinking about your need to have users send certain site commands by email.</p>\n\n<p>Wouldn't it be easier to have a single address that multiple commands can be sent to rather than having multiple addresses?</p>\n\n<p>I think the security concerns are pretty valid too. Unless the commands are non-destructive or aren't doing anything user-specific, the system will be wide open to anyone who knows how to spoof an email address (which would be everyone :) ).</p>\n"
},
{
"answer_id": 49556,
"author": "Pat",
"author_id": 238,
"author_profile": "https://Stackoverflow.com/users/238",
"pm_score": 2,
"selected": false,
"text": "<p>If your server allows it you can use a <a href=\"http://activecampaign.com/support/tt/index.php?action=kb&article=145\" rel=\"nofollow noreferrer\">.forward</a> file or <a href=\"http://en.wikipedia.org/wiki/Procmail\" rel=\"nofollow noreferrer\">Procmail</a> to start a process (php or anything) when a mail arrives to a certain address.</p>\n"
},
{
"answer_id": 49584,
"author": "Kibbee",
"author_id": 1862,
"author_profile": "https://Stackoverflow.com/users/1862",
"pm_score": 1,
"selected": false,
"text": "<p>You don't want to hassle users with OpenID, but you want them to deal with this email scheme. Firstly, email can take a long time to go through. There isn't any guaranteed time that an email will be delivered in. It's not even guaranteed that the email will get there at all. I know things usually are quick, but it's not uncommon to take up to 10 minutes for a round trip to be completed. Also, unless you're encrypting the email, the link you are sending back is sent in the open. That means anybody can use that link to log in. Depending one how secure you want to be, this may or may not be an issue, but it's definitely something to think about. Using a non-standard login method like this is going to be a lot more work than it is probably worth, and I can't really see any advantages to the whole process.</p>\n"
},
{
"answer_id": 49600,
"author": "Marie Fischer",
"author_id": 719,
"author_profile": "https://Stackoverflow.com/users/719",
"pm_score": 1,
"selected": false,
"text": "<p>I was also thinking using procmail to start some script. There is also formail, which might come in handy to change or extract headers. If you have admin access to the mail server, you could also use /etc/aliases and just pipe to your script.</p>\n\n<p>Besides usability issues, you should really think about security - it's actually quite simple to send email with a fake sender address, so I would not rely on it for anything critical.</p>\n"
},
{
"answer_id": 49617,
"author": "erlando",
"author_id": 4192,
"author_profile": "https://Stackoverflow.com/users/4192",
"pm_score": 0,
"selected": false,
"text": "<p>I would seriously reconsider this approach. E-mail hasn't got very high reliability. There's all kinds of spamfilters that might intercept e-mails with links thereby rendering the \"command\" half-finished, not to mention the security risks.</p>\n\n<p>It's very easy to spoof the sender-address on an e-mail. You are basically opening up your system to anyone.</p>\n\n<p>Also instead of a username/password combination you're suddenly requiring the users to remember a list of commands to put in front of an email-address. It would be better to provide them with a username/password and then giving access to a help page.</p>\n\n<p>In other words the usability and security of this scheme scores very low.</p>\n\n<p>I can't really find any advantages to this approach that even comes close to outweighing the massive disadvantages.</p>\n"
},
{
"answer_id": 55290,
"author": "bmb",
"author_id": 5298,
"author_profile": "https://Stackoverflow.com/users/5298",
"pm_score": 1,
"selected": false,
"text": "<p>I agree with all the security concerns. Your assumption that \"the users and their email providers takes care of their email account security\" is not correct when it comes to the sender's e-mail address.</p>\n\n<p>But since you specifically asked \"how do I go from an email is sent to an account that is not read by humans to there being fired off some script\", I recommend using procmail to deliver the incoming e-mail to a script you write. </p>\n\n<p>I would not call a URL. I would have the script perform the work by reading the message sent in on stdin. That way, the script is not acessible to anyone on the web site.</p>\n\n<p>To set this up, the e-mail address you provide to your users will have to be associated with a real user\non the system. In that user's home directory, create a file called \".procmailrc\"</p>\n\n<p>In that file, add these two lines:</p>\n\n<pre><code>:0 hb:\n| /path/to/program\n</code></pre>\n\n<p>Where /path/to/program is the full path to the script or program for handling\nthe incoming message. Then create the script with code something like this:</p>\n\n<pre><code>#!/usr/bin/php\n<?php\n\n$fp=fopen('php://stdin','r');\nwhile($line = fgets($fp)) {\n [do something with each $line of input here]\n}\n\n?>\n</code></pre>\n\n<p>The e-mail message will not remain in the mailbox, so if you want to save or log it, have the script do it.</p>\n\n<p>--<br>\nBruce</p>\n"
},
{
"answer_id": 76272,
"author": "Trausti Thor",
"author_id": 6801,
"author_profile": "https://Stackoverflow.com/users/6801",
"pm_score": 0,
"selected": false,
"text": "<p>One solution to prevent spam, make sure the first line, last line or a specific line contains a certain string, almost like a password, but a full sentence is better.</p>\n\n<p>Only you have the word or words, pretty secure, just remember to delete the mails after use and those that do not have the secret line.</p>\n"
},
{
"answer_id": 85628,
"author": "Gaurav",
"author_id": 13492,
"author_profile": "https://Stackoverflow.com/users/13492",
"pm_score": 0,
"selected": false,
"text": "<p>Apart from the security and usability email delivery can be another problem. Depending on the user's email provider, email delivery can be delayed from a few minutes to few hours.</p>\n"
},
{
"answer_id": 86272,
"author": "Rene",
"author_id": 16352,
"author_profile": "https://Stackoverflow.com/users/16352",
"pm_score": 0,
"selected": false,
"text": "<p>There is a realy nice educational story on <a href=\"http://thedailywtf.com/Comments/Classic-WTF-The-Complicators-Gloves.aspx\" rel=\"nofollow noreferrer\">thedailywtf.com</a> on designing software. The posed question should be solved by a proper design, not by techo-woopla.</p>\n\n<p>Alexander, please read the linked story and think gloves, not email-driven webpage browsing.</p>\n\n<p>PHP is not a <a href=\"http://www.answers.com/topic/when-all-you-have-is-a-hammer-everything-looks-like-a-nail\" rel=\"nofollow noreferrer\">hammer</a>.</p>\n"
}
] | 2008/09/05 | [
"https://Stackoverflow.com/questions/46777",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4013/"
] | I want to run a web application on php and mysql, using the CakePHP framework. And to keep the threshold of using the site at a very low place, I want to not use the standard login with username/password. (And I don't want to hassle my users with something like OpenID either. Goes to user type.)
So I'm thinking that the users shall be able to log in by sending an email to [email protected] with no subject or content required. And they will get, in reply, an email with a link that will log them in (it will contain a hash). Also I will let the users do some actions without even visiting the site at all, just send an email with [email protected] and the command will be carried out. I will assume that the users and their email providers takes care of their email account security and as such there is no need for it on my site.
Now, how do I go from an email is sent to an account that is not read by humans to there being fired off some script (basically a "dummy browser client" calls an url( and the cakephp will take care of the rest)?
---
I have never used a cron job before, but I do think I understand their purpose or how they generally work. I can not have the script be called by random people visiting the site, as that solution won't work for several reasons. I think I would like to hear more about the possibility of having the script be run as response to an email coming in, if anyone has any input at all on that. If it's run as a cron job it would only check every X minutes and users would get a lag in their response (if i understand it correctly).
Since there will be different email addresses for different commands, like **login**@domain.com and I know what to do and how to do it to based on the sender email, i dont even need the content, subject or any other headers from the email.
---
There is a lot of worry about security of this application, I understand the issues, but without giving away my concept, I dont think it is a big issue for what I am doing. Also about the usability issue, there really isnt any. It's just gonna be login to provide changes on a users profile if/when they need that and one other command. And this is the main email and is very easy to remember and the outset of this whole concept. | I have used the [pop3 php class](http://www.phpclasses.org/browse/file/3.html) with great success (there is also a [Pear POP3 module](http://pear.php.net/package/Net_POP3)).
Using the pop3 class looks something like this:
```
require ('pop3.php');
$pop3 = new pop3_class();
$pop3->hostname = MAILHOST;
$pop3->Open();
$pop3->Login('[email protected]', 'mypassword');
foreach($pop3->ListMessages("","") as $msgidx => $msgsize)
{
$headers = "";
$body = "";
$pop3->RetrieveMessage($msgidx, $headers, $body, -1);
}
```
I use it to monitor a POP3 mailbox which feeds into a database.
It gets called by a cronjob which uses wget to call the url to my php script.
```
*/5 * * * * "wget -q --http-user=me --http-passwd=pass 'http://mydomain.com/mail.php'" >> /dev/null 2>&1
```
**Edit**
I've been thinking about your need to have users send certain site commands by email.
Wouldn't it be easier to have a single address that multiple commands can be sent to rather than having multiple addresses?
I think the security concerns are pretty valid too. Unless the commands are non-destructive or aren't doing anything user-specific, the system will be wide open to anyone who knows how to spoof an email address (which would be everyone :) ). |
46,827 | <p>Visual Studio 2005 doesn't provide an interface for creating relationships between tables in a SQL Server CE database (I'm using version 3.0) and you can't open a Compact Edition DB using Management Studio as far as I know. Any ideas?</p>
| [
{
"answer_id": 46832,
"author": "Espo",
"author_id": 2257,
"author_profile": "https://Stackoverflow.com/users/2257",
"pm_score": 7,
"selected": true,
"text": "<p>Unfortunately there is currently no designer support (unlike for SQL Server 2005) for building relationships between tables in SQL Server CE. To build relationships you need to use SQL commands such as:</p>\n\n<pre><code>ALTER TABLE Orders\nADD CONSTRAINT FK_Customer_Order\nFOREIGN KEY (CustomerId) REFERENCES Customers(CustomerId)\n</code></pre>\n\n<p>If you are doing CE development, i would recomend this FAQ:</p>\n\n<p><strong>EDIT</strong>: In Visual Studio 2008 this is now possible to do in the GUI by right-clicking on your table.</p>\n"
},
{
"answer_id": 46834,
"author": "Ryan Shripat",
"author_id": 1943,
"author_profile": "https://Stackoverflow.com/users/1943",
"pm_score": 3,
"selected": false,
"text": "<p>You need to create a query (in Visual Studio, right-click on the DB connection -> New Query) and execute the following SQL:</p>\n\n<pre><code>ALTER TABLE tblAlpha\nADD CONSTRAINT MyConstraint FOREIGN KEY (FK_id) REFERENCES\ntblGamma(GammaID)\nON UPDATE CASCADE\n</code></pre>\n\n<p>To verify that your foreign key was created, execute the following SQL:</p>\n\n<pre><code>SELECT * FROM INFORMATION_SCHEMA.REFERENTIAL_CONSTRAINTS\n</code></pre>\n\n<p>Credit to E Jensen (<a href=\"http://forums.microsoft.com/MSDN/ShowPost.aspx?PostID=532377&SiteID=1\" rel=\"noreferrer\">http://forums.microsoft.com/MSDN/ShowPost.aspx?PostID=532377&SiteID=1</a>)</p>\n"
},
{
"answer_id": 650900,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 5,
"selected": false,
"text": "<p>Visual Studio 2008 <em>does</em> have a designer that allows you to add FK's. Just right-click the table... Table Properties, then go to the \"Add Relations\" section.</p>\n"
},
{
"answer_id": 1258873,
"author": "Rob",
"author_id": 108141,
"author_profile": "https://Stackoverflow.com/users/108141",
"pm_score": 2,
"selected": false,
"text": "<p>Alan is correct when he says there's designer support. Rhywun is incorrect when he implies you cannot choose the foreign key table. What he means is that in the UI the foreign key table drop down is greyed out - all that means is he has not right clicked on the correct table to add the foreign key to.</p>\n\n<p>In summary, right click on the foriegn key table and then via the 'Table Properties' > 'Add Relations' option you select the related primary key table.</p>\n\n<p>I've done it numerous times and it works.</p>\n"
},
{
"answer_id": 16894739,
"author": "shahwazir haqmall",
"author_id": 2447464,
"author_profile": "https://Stackoverflow.com/users/2447464",
"pm_score": 1,
"selected": false,
"text": "<pre><code>create table employee\n(\n empid int,\n empname varchar(40),\n designation varchar(30),\n hiredate datetime, \n Bsalary int,\n depno constraint emp_m foreign key references department(depno)\n)\n</code></pre>\n\n<p>We should have an primary key to create foreign key or relationship between two or more table . </p>\n"
},
{
"answer_id": 20942153,
"author": "Tharaka",
"author_id": 2390020,
"author_profile": "https://Stackoverflow.com/users/2390020",
"pm_score": 1,
"selected": false,
"text": "<p>I know it's a \"very long time\" since this question was first asked. Just in case, if it helps someone,</p>\n\n<p>Adding relationships is well supported by MS via SQL Server Compact Tool Box (<a href=\"https://sqlcetoolbox.codeplex.com/\" rel=\"nofollow noreferrer\">https://sqlcetoolbox.codeplex.com/</a>). Just install it, then you would get the option to connect to the Compact Database using the Server Explorer Window. Right click on the primary table , select \"Table Properties\". You should have the following window, which contains \"Add Relations\" tab allowing you to add relations.</p>\n\n<p><img src=\"https://i.stack.imgur.com/nzptp.png\" alt=\"Add Relations Tab - SQL Server Compact Tool Box\"></p>\n"
},
{
"answer_id": 26601080,
"author": "Alex Jolig",
"author_id": 2263683,
"author_profile": "https://Stackoverflow.com/users/2263683",
"pm_score": 1,
"selected": false,
"text": "<p><a href=\"http://msdn.microsoft.com/en-us/library/vstudio/bb546200%28v=vs.100%29.aspx\" rel=\"nofollow\">Walkthrough: Creating a SQL Server Compact 3.5 Database</a></p>\n\n<p>To create a relationship between the tables created in the previous procedure</p>\n\n<ol>\n<li>In Server Explorer/Database Explorer, expand Tables.</li>\n<li>Right-click the Orders table and then click Table Properties.</li>\n<li>Click Add Relations.</li>\n<li>Type FK_Orders_Customers in the Relation Name box.</li>\n<li>Select CustomerID in the Foreign Key Table Column list.</li>\n<li>Click Add Columns.</li>\n<li>Click Add Relation.</li>\n<li>Click OK to complete the process and create the relationship in the\ndatabase.</li>\n<li>Click OK again to close the Table Properties dialog box.</li>\n</ol>\n"
}
] | 2008/09/05 | [
"https://Stackoverflow.com/questions/46827",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1943/"
] | Visual Studio 2005 doesn't provide an interface for creating relationships between tables in a SQL Server CE database (I'm using version 3.0) and you can't open a Compact Edition DB using Management Studio as far as I know. Any ideas? | Unfortunately there is currently no designer support (unlike for SQL Server 2005) for building relationships between tables in SQL Server CE. To build relationships you need to use SQL commands such as:
```
ALTER TABLE Orders
ADD CONSTRAINT FK_Customer_Order
FOREIGN KEY (CustomerId) REFERENCES Customers(CustomerId)
```
If you are doing CE development, i would recomend this FAQ:
**EDIT**: In Visual Studio 2008 this is now possible to do in the GUI by right-clicking on your table. |
46,841 | <p>Occasionally, on a ASP (classic) site users will get this error:</p>
<pre><code>[DBNETLIB][ConnectionRead (recv()).]General network error.
</code></pre>
<p>Seems to be random and not connected to any particular page. The SQL server is separated from the web server and my guess is that every once and a while the "link" goes down between the two. Router/switch issue... or has someone else ran into this problem before?</p>
| [
{
"answer_id": 47080,
"author": "Grzegorz Gierlik",
"author_id": 1483,
"author_profile": "https://Stackoverflow.com/users/1483",
"pm_score": 0,
"selected": false,
"text": "<p>I'd seen this error many times. It could be caused by many things including network errors too :).</p>\n\n<p>But one of the reason could be built-in feature of MS-SQL. </p>\n\n<p>The feature detects DoS attacks -- in this case too many request from web server :).</p>\n\n<p>But I have no idea how we fixed it :(.</p>\n"
},
{
"answer_id": 47237,
"author": "Simon Forrest",
"author_id": 4733,
"author_profile": "https://Stackoverflow.com/users/4733",
"pm_score": 2,
"selected": true,
"text": "<p>Using the same setup as yours (ie separate web and database server), I've seen it from time to time and it has always been a connection problem between the servers - typically when the database server is being rebooted but sometimes when there's a comms problem somewhere in the system. I've not seen it triggered by any problems with the ASP code itself, which is why you're seeing it apparently at random and not connected to a particular page.</p>\n"
},
{
"answer_id": 7594164,
"author": "Lahiru Jayalath",
"author_id": 970642,
"author_profile": "https://Stackoverflow.com/users/970642",
"pm_score": 0,
"selected": false,
"text": "<p>SQL server configuration Manager</p>\n\n<p>Disable TCP/IP , Enable Shared Memory & Named Pipes</p>\n\n<p>Good Luck !</p>\n"
},
{
"answer_id": 17943191,
"author": "yangli.liy",
"author_id": 1719474,
"author_profile": "https://Stackoverflow.com/users/1719474",
"pm_score": 0,
"selected": false,
"text": "<p>Not a solution exactly and not the same environment. However I get this error in a VBA/Excel program, and the problem is I have a hanging transaction which has not been submitted in SQL Server Management Studio (SSMS). After closing SSMS, everything works. So the lesson is a hanging transaction can block sprocs from proceeding (obvious fact, I know!). Hope this help someone here.</p>\n"
},
{
"answer_id": 39923881,
"author": "Shrikrishna Vhale",
"author_id": 6938776,
"author_profile": "https://Stackoverflow.com/users/6938776",
"pm_score": 0,
"selected": false,
"text": "<p>open command prompt - Run as administrator and type following command on the client side</p>\n\n<pre><code>netsh advfirewall set allprofiles state off\n</code></pre>\n"
},
{
"answer_id": 49283898,
"author": "AjV Jsy",
"author_id": 2078245,
"author_profile": "https://Stackoverflow.com/users/2078245",
"pm_score": 0,
"selected": false,
"text": "<p>FWIW, I had this error from Excel, which would hang on an EXEC which worked fine within SSMS. I've seen queries with problems before, which were also OK within SSMS, due to 'parameter sniffing' and unsuitable cached query plans. Making a minor edit to the SP cured the problem, and it worked OK afterwards in its orginal form. I'd be interested to hear if anyone has encountered this scenario too. Try the good old <code>OPTION (OPTIMIZE FOR UNKNOWN)</code> :)</p>\n"
}
] | 2008/09/05 | [
"https://Stackoverflow.com/questions/46841",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4835/"
] | Occasionally, on a ASP (classic) site users will get this error:
```
[DBNETLIB][ConnectionRead (recv()).]General network error.
```
Seems to be random and not connected to any particular page. The SQL server is separated from the web server and my guess is that every once and a while the "link" goes down between the two. Router/switch issue... or has someone else ran into this problem before? | Using the same setup as yours (ie separate web and database server), I've seen it from time to time and it has always been a connection problem between the servers - typically when the database server is being rebooted but sometimes when there's a comms problem somewhere in the system. I've not seen it triggered by any problems with the ASP code itself, which is why you're seeing it apparently at random and not connected to a particular page. |
46,842 | <p>What is the best way to determine duplicate records in a SQL Server table?</p>
<p>For instance, I want to find the last duplicate email received in a table (table has primary key, receiveddate and email fields).</p>
<p>Sample data:</p>
<pre><code>1 01/01/2008 [email protected]
2 02/01/2008 [email protected]
3 01/12/2008 [email protected]
</code></pre>
| [
{
"answer_id": 46843,
"author": "Rob Rolnick",
"author_id": 4798,
"author_profile": "https://Stackoverflow.com/users/4798",
"pm_score": 0,
"selected": false,
"text": "<p>Couldn't you join the list on the e-mail field and then see what nulls you get in your result?</p>\n\n<p>Or better yet, count the instances of each e-mail address? And only return the ones with count > 1</p>\n\n<p>Or even take the email and id fields. And return the entries where the e-mail is the same, and the IDs are different. (To avoid duplicates don't use != but rather either < or >.)</p>\n"
},
{
"answer_id": 46845,
"author": "SQLMenace",
"author_id": 740,
"author_profile": "https://Stackoverflow.com/users/740",
"pm_score": 3,
"selected": false,
"text": "<p>something like this</p>\n\n<pre><code>select email ,max(receiveddate) as MaxDate\nfrom YourTable\ngroup by email \nhaving count(email) > 1\n</code></pre>\n"
},
{
"answer_id": 46846,
"author": "Michael Sharek",
"author_id": 1958,
"author_profile": "https://Stackoverflow.com/users/1958",
"pm_score": 0,
"selected": false,
"text": "<p>Try this</p>\n\n<pre><code>select * from table a, table b\nwhere a.email = b.email\n</code></pre>\n"
},
{
"answer_id": 46849,
"author": "palehorse",
"author_id": 312,
"author_profile": "https://Stackoverflow.com/users/312",
"pm_score": 0,
"selected": false,
"text": "<pre><code>SELECT [id], [receivedate], [email]\nFROM [mytable]\nWHERE [email] IN ( SELECT [email]\n FROM [myTable]\n GROUP BY [email]\n HAVING COUNT([email]) > 1 )\n</code></pre>\n"
},
{
"answer_id": 46853,
"author": "enigmatic",
"author_id": 443575,
"author_profile": "https://Stackoverflow.com/users/443575",
"pm_score": 0,
"selected": false,
"text": "<p>Do you want a list of the last items? If so you could use:</p>\n\n<pre><code>SELECT [info] FROM [table] t WHERE NOT EXISTS (SELECT * FROM [table] tCheck WHERE t.date > tCheck.date)\n</code></pre>\n\n<p>If you want a list of all duplicate email address use GROUP BY to collect similar data, then a HAVING clause to make sure the quantity is more than 1:</p>\n\n<pre><code>SELECT [info] FROM [table] GROUP BY [email] HAVING Count(*) > 1 DESC\n</code></pre>\n\n<p>If you want the last duplicate e-mail (a single result) you simply add a \"TOP 1\" and \"ORDER BY\":</p>\n\n<pre><code>SELECT TOP 1 [info] FROM [table] GROUP BY [email] HAVING Count(*) > 1 ORDER BY Date DESC\n</code></pre>\n"
},
{
"answer_id": 46861,
"author": "Brian",
"author_id": 700,
"author_profile": "https://Stackoverflow.com/users/700",
"pm_score": 0,
"selected": false,
"text": "<p>If you have surrogate key, it is relatively easy to use the group by syntax mentioned in SQLMenance's post. Essentially, group by all the fields that make two or more rows 'the same'. </p>\n\n<p>Example pseudo-code to delete duplicate records.</p>\n\n<pre><code>Create table people (ID(PK), Name, Address, DOB)\n\nDelete from people where id not in (\nSelect min(ID) from people group by name, address, dob\n)\n</code></pre>\n"
},
{
"answer_id": 14757344,
"author": "user2051770",
"author_id": 2051770,
"author_profile": "https://Stackoverflow.com/users/2051770",
"pm_score": 1,
"selected": false,
"text": "<p>Try something like:</p>\n\n<pre><code>SELECT * FROM (\n SELECT *, \n ROW_NUMBER() OVER (PARTITION BY ReceivedDate, Email ORDER BY ReceivedDate, Email DESC) AS RowNumber \n FROM EmailTable\n) a\nWHERE RowNumber = 1\n</code></pre>\n\n<p>See <a href=\"http://www.technicaloverload.com/working-with-duplicates-in-sql-server/\" rel=\"nofollow\">http://www.technicaloverload.com/working-with-duplicates-in-sql-server/</a></p>\n"
}
] | 2008/09/05 | [
"https://Stackoverflow.com/questions/46842",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] | What is the best way to determine duplicate records in a SQL Server table?
For instance, I want to find the last duplicate email received in a table (table has primary key, receiveddate and email fields).
Sample data:
```
1 01/01/2008 [email protected]
2 02/01/2008 [email protected]
3 01/12/2008 [email protected]
``` | something like this
```
select email ,max(receiveddate) as MaxDate
from YourTable
group by email
having count(email) > 1
``` |
46,863 | <p>How do I concatenate together two strings, of unknown length, in COBOL? So for example:</p>
<pre><code>WORKING-STORAGE.
FIRST-NAME PIC X(15) VALUE SPACES.
LAST-NAME PIC X(15) VALUE SPACES.
FULL-NAME PIC X(31) VALUE SPACES.
</code></pre>
<p>If <code>FIRST-NAME = 'JOHN '</code> and <code>LAST-NAME = 'DOE '</code>, how can I get:</p>
<pre><code>FULL-NAME = 'JOHN DOE '
</code></pre>
<p>as opposed to:</p>
<pre><code>FULL-NAME = 'JOHN DOE '
</code></pre>
| [
{
"answer_id": 46899,
"author": "Eric H",
"author_id": 4650,
"author_profile": "https://Stackoverflow.com/users/4650",
"pm_score": 2,
"selected": false,
"text": "<p>At first glance, the solution is to use reference modification to STRING together the two strings, including the space. The problem is that you must know how many trailing spaces are present in FIRST-NAME, otherwise you'll produce something like 'JOHNbbbbbbbbbbbbDOE', where b is a space.</p>\n\n<p>There's no intrinsic COBOL function to determine the number of trailing spaces in a string, but there is one to determine the number of leading spaces in a string. Therefore, the fastest way, as far as I can tell, is to reverse the first name, find the number of leading spaces, and use reference modification to string together the first and last names.</p>\n\n<p>You'll have to add these fields to working storage:</p>\n\n<pre><code>WORK-FIELD PIC X(15) VALUE SPACES.\nTRAILING-SPACES PIC 9(3) VALUE ZERO.\nFIELD-LENGTH PIC 9(3) VALUE ZERO.\n</code></pre>\n\n<ol>\n<li>Reverse the FIRST-NAME\n\n<ul>\n<li>MOVE FUNCTION REVERSE (FIRST-NAME) TO WORK-FIELD.</li>\n<li>WORK-FIELD now contains leading spaces, instead of trailing spaces.</li>\n</ul></li>\n<li>Find the number of trailing spaces in FIRST-NAME\n\n<ul>\n<li>INSPECT WORK-FIELD TALLYING TRAILING-SPACES FOR LEADING SPACES.</li>\n<li>TRAILING-SPACE now contains the number of trailing spaces in FIRST-NAME.</li>\n</ul></li>\n<li>Find the length of the FIRST-NAME field\n\n<ul>\n<li>COMPUTE FIELD-LENGTH = FUNCTION LENGTH (FIRST-NAME).</li>\n</ul></li>\n<li>Concatenate the two strings together.\n\n<ul>\n<li>STRING FIRST-NAME (1:FIELD-LENGTH – TRAILING-SPACES) “ “ LAST-NAME DELIMITED BY SIZE, INTO FULL-NAME.</li>\n</ul></li>\n</ol>\n"
},
{
"answer_id": 47119,
"author": "Thayne",
"author_id": 3749,
"author_profile": "https://Stackoverflow.com/users/3749",
"pm_score": 4,
"selected": true,
"text": "<p>I believe the following will give you what you desire.</p>\n\n<pre><code>STRING\nFIRST-NAME DELIMITED BY \" \",\n\" \",\nLAST-NAME DELIMITED BY SIZE\nINTO FULL-NAME.\n</code></pre>\n"
},
{
"answer_id": 55763849,
"author": "Rubén Navarro Davó",
"author_id": 5181067,
"author_profile": "https://Stackoverflow.com/users/5181067",
"pm_score": 0,
"selected": false,
"text": "<p>You could try making a loop for to get the real length.</p>\n"
}
] | 2008/09/05 | [
"https://Stackoverflow.com/questions/46863",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4650/"
] | How do I concatenate together two strings, of unknown length, in COBOL? So for example:
```
WORKING-STORAGE.
FIRST-NAME PIC X(15) VALUE SPACES.
LAST-NAME PIC X(15) VALUE SPACES.
FULL-NAME PIC X(31) VALUE SPACES.
```
If `FIRST-NAME = 'JOHN '` and `LAST-NAME = 'DOE '`, how can I get:
```
FULL-NAME = 'JOHN DOE '
```
as opposed to:
```
FULL-NAME = 'JOHN DOE '
``` | I believe the following will give you what you desire.
```
STRING
FIRST-NAME DELIMITED BY " ",
" ",
LAST-NAME DELIMITED BY SIZE
INTO FULL-NAME.
``` |
46,898 | <p>If I have an object implementing the <code>Map</code> interface in Java and I wish to iterate over every pair contained within it, what is the most efficient way of going through the map?</p>
<p>Will the ordering of elements depend on the specific map implementation that I have for the interface?</p>
| [
{
"answer_id": 46905,
"author": "pkaeding",
"author_id": 4257,
"author_profile": "https://Stackoverflow.com/users/4257",
"pm_score": 8,
"selected": false,
"text": "<p>Yes, the order depends on the specific Map implementation.</p>\n\n<p><a href=\"https://stackoverflow.com/questions/46898/how-to-efficiently-iterate-over-each-entry-in-a-map/46908#46908\">@ScArcher2 has the more elegant Java 1.5 syntax</a>. In 1.4, I would do something like this:</p>\n\n<pre><code>Iterator entries = myMap.entrySet().iterator();\nwhile (entries.hasNext()) {\n Entry thisEntry = (Entry) entries.next();\n Object key = thisEntry.getKey();\n Object value = thisEntry.getValue();\n // ...\n}\n</code></pre>\n"
},
{
"answer_id": 46908,
"author": "ScArcher2",
"author_id": 1310,
"author_profile": "https://Stackoverflow.com/users/1310",
"pm_score": 13,
"selected": true,
"text": "<pre class=\"lang-java prettyprint-override\"><code>Map<String, String> map = ...\nfor (Map.Entry<String, String> entry : map.entrySet()) {\n System.out.println(entry.getKey() + "/" + entry.getValue());\n}\n</code></pre>\n<p>On Java 10+:</p>\n<pre class=\"lang-java prettyprint-override\"><code>for (var entry : map.entrySet()) {\n System.out.println(entry.getKey() + "/" + entry.getValue());\n}\n</code></pre>\n"
},
{
"answer_id": 46912,
"author": "Leigh Caldwell",
"author_id": 3267,
"author_profile": "https://Stackoverflow.com/users/3267",
"pm_score": 5,
"selected": false,
"text": "<p>In theory, the most efficient way will depend on which implementation of Map. The official way to do this is to call <code>map.entrySet()</code>, which returns a set of <code>Map.Entry</code>, each of which contains a key and a value (<code>entry.getKey()</code> and <code>entry.getValue()</code>).</p>\n\n<p>In an idiosyncratic implementation, it might make some difference whether you use <code>map.keySet()</code>, <code>map.entrySet()</code> or something else. But I can't think of a reason why anyone would write it like that. Most likely it makes no difference to performance what you do.</p>\n\n<p>And yes, the order will depend on the implementation - as well as (possibly) the order of insertion and other hard-to-control factors.</p>\n\n<p>[edit] I wrote <code>valueSet()</code> originally but of course <code>entrySet()</code> is actually the answer.</p>\n"
},
{
"answer_id": 46926,
"author": "Tom Hawtin - tackline",
"author_id": 4725,
"author_profile": "https://Stackoverflow.com/users/4725",
"pm_score": 7,
"selected": false,
"text": "<p>Typical code for iterating over a map is:</p>\n<pre><code>Map<String,Thing> map = ...;\nfor (Map.Entry<String,Thing> entry : map.entrySet()) {\n String key = entry.getKey();\n Thing thing = entry.getValue();\n ...\n}\n</code></pre>\n<p><code>HashMap</code> is the canonical map implementation and doesn't make guarantees (or though it should not change the order if no mutating operations are performed on it). <code>SortedMap</code> will return entries based on the natural ordering of the keys, or a <code>Comparator</code>, if provided. <code>LinkedHashMap</code> will either return entries in insertion-order or access-order depending upon how it has been constructed. <code>EnumMap</code> returns entries in the natural order of keys.</p>\n<p><strong>(Update: I think this is no longer true.</strong>) Note, <code>IdentityHashMap</code> <code>entrySet</code> iterator currently has a peculiar implementation which returns the same <code>Map.Entry</code> instance for every item in the <code>entrySet</code>! However, every time a new iterator advances the <code>Map.Entry</code> is updated.</p>\n"
},
{
"answer_id": 46989,
"author": "serg10",
"author_id": 1853,
"author_profile": "https://Stackoverflow.com/users/1853",
"pm_score": 7,
"selected": false,
"text": "<p>This is a two part question:</p>\n\n<p><em>How to iterate over the entries of a Map</em> - @ScArcher2 has <a href=\"https://stackoverflow.com/a/46908/1851302\">answered</a> that perfectly.</p>\n\n<p><em>What is the order of iteration</em> - if you are just using <code>Map</code>, then strictly speaking, there are <strong>no ordering guarantees</strong>. So you shouldn't really rely on the ordering given by any implementation. However, the <a href=\"http://docs.oracle.com/javase/8/docs/api/java/util/SortedMap.html\" rel=\"noreferrer\"><code>SortedMap</code></a> interface extends <code>Map</code> and provides exactly what you are looking for - implementations will aways give a consistent sort order.</p>\n\n<p><strong><a href=\"http://docs.oracle.com/javase/8/docs/api/java/util/NavigableMap.html\" rel=\"noreferrer\"><code>NavigableMap</code></a> is another useful extension</strong> - this is a <code>SortedMap</code> with additional methods for finding entries by their ordered position in the key set. So potentially this can remove the need for iterating in the first place - you might be able to find the specific <code>entry</code> you are after using the <code>higherEntry</code>, <code>lowerEntry</code>, <code>ceilingEntry</code>, or <code>floorEntry</code> methods. The <code>descendingMap</code> method even gives you an explicit method of <strong>reversing the traversal order</strong>.</p>\n"
},
{
"answer_id": 47004,
"author": "ckpwong",
"author_id": 2551,
"author_profile": "https://Stackoverflow.com/users/2551",
"pm_score": 6,
"selected": false,
"text": "<p>FYI, you can also use <code>map.keySet()</code> and <code>map.values()</code> if you're only interested in keys/values of the map and not the other.</p>\n"
},
{
"answer_id": 48720,
"author": "Chris Dail",
"author_id": 5077,
"author_profile": "https://Stackoverflow.com/users/5077",
"pm_score": 6,
"selected": false,
"text": "<p>The correct way to do this is to use the accepted answer as it is the most efficient. I find the following code looks a bit cleaner.</p>\n\n<pre><code>for (String key: map.keySet()) {\n System.out.println(key + \"/\" + map.get(key));\n}\n</code></pre>\n"
},
{
"answer_id": 1295383,
"author": "serg",
"author_id": 20128,
"author_profile": "https://Stackoverflow.com/users/20128",
"pm_score": 7,
"selected": false,
"text": "<p>Example of using iterator and generics:</p>\n\n<pre><code>Iterator<Map.Entry<String, String>> entries = myMap.entrySet().iterator();\nwhile (entries.hasNext()) {\n Map.Entry<String, String> entry = entries.next();\n String key = entry.getKey();\n String value = entry.getValue();\n // ...\n}\n</code></pre>\n"
},
{
"answer_id": 2190043,
"author": "abods",
"author_id": 265011,
"author_profile": "https://Stackoverflow.com/users/265011",
"pm_score": 5,
"selected": false,
"text": "<p>Try this with Java 1.4:</p>\n\n<pre><code>for( Iterator entries = myMap.entrySet().iterator(); entries.hasNext();){\n\n Entry entry = (Entry) entries.next();\n\n System.out.println(entry.getKey() + \"/\" + entry.getValue());\n\n //...\n}\n</code></pre>\n"
},
{
"answer_id": 10632923,
"author": "Fathah Rehman P",
"author_id": 991065,
"author_profile": "https://Stackoverflow.com/users/991065",
"pm_score": 4,
"selected": false,
"text": "<pre><code>public class abcd{\n public static void main(String[] args)\n {\n Map<Integer, String> testMap = new HashMap<Integer, String>();\n testMap.put(10, \"a\");\n testMap.put(20, \"b\");\n testMap.put(30, \"c\");\n testMap.put(40, \"d\");\n for (Integer key:testMap.keySet()) {\n String value=testMap.get(key);\n System.out.println(value);\n }\n }\n}\n</code></pre>\n\n<p>OR</p>\n\n<pre><code>public class abcd {\n public static void main(String[] args)\n {\n Map<Integer, String> testMap = new HashMap<Integer, String>();\n testMap.put(10, \"a\");\n testMap.put(20, \"b\");\n testMap.put(30, \"c\");\n testMap.put(40, \"d\");\n for (Entry<Integer, String> entry : testMap.entrySet()) {\n Integer key=entry.getKey();\n String value=entry.getValue();\n }\n }\n}\n</code></pre>\n"
},
{
"answer_id": 13943066,
"author": "Donald Raab",
"author_id": 1570415,
"author_profile": "https://Stackoverflow.com/users/1570415",
"pm_score": 5,
"selected": false,
"text": "<p>With <a href=\"https://github.com/eclipse/eclipse-collections\" rel=\"noreferrer\">Eclipse Collections</a>, you would use the <code>forEachKeyValue</code> method on the <a href=\"https://github.com/eclipse/eclipse-collections/blob/master/eclipse-collections-api/src/main/java/org/eclipse/collections/api/map/MapIterable.java\" rel=\"noreferrer\"><code>MapIterable</code></a> interface, which is inherited by the <code>MutableMap</code> and <code>ImmutableMap</code> interfaces and their implementations.</p>\n\n<pre><code>MutableBag<String> result = Bags.mutable.empty();\nMutableMap<Integer, String> map = Maps.mutable.of(1, \"One\", 2, \"Two\", 3, \"Three\");\nmap.forEachKeyValue((key, value) -> result.add(key + value));\nAssert.assertEquals(Bags.mutable.of(\"1One\", \"2Two\", \"3Three\"), result);\n</code></pre>\n\n<p>Using an anonymous inner class, you can write the code as follows:</p>\n\n<pre><code>final MutableBag<String> result = Bags.mutable.empty();\nMutableMap<Integer, String> map = Maps.mutable.of(1, \"One\", 2, \"Two\", 3, \"Three\");\nmap.forEachKeyValue(new Procedure2<Integer, String>()\n{\n public void value(Integer key, String value)\n {\n result.add(key + value);\n }\n});\nAssert.assertEquals(Bags.mutable.of(\"1One\", \"2Two\", \"3Three\"), result);\n</code></pre>\n\n<p><strong>Note:</strong> I am a committer for Eclipse Collections.</p>\n"
},
{
"answer_id": 15556457,
"author": "Suresh Atta",
"author_id": 1927832,
"author_profile": "https://Stackoverflow.com/users/1927832",
"pm_score": 3,
"selected": false,
"text": "<p>Yes, as many people agreed this is the best way to iterate over a <code>Map</code>.</p>\n\n<p>But there are chances to throw <code>nullpointerexception</code> if the map is <code>null</code>. Don't forget to put <code>null</code> .check in.</p>\n\n<pre><code> |\n |\n - - - -\n |\n |\nfor (Map.Entry<String, Object> entry : map.entrySet()) {\n String key = entry.getKey();\n Object value = entry.getValue();\n}\n</code></pre>\n"
},
{
"answer_id": 17404976,
"author": "Learner",
"author_id": 1918772,
"author_profile": "https://Stackoverflow.com/users/1918772",
"pm_score": 4,
"selected": false,
"text": "<p>You can do it using generics:</p>\n\n<pre><code>Map<Integer, Integer> map = new HashMap<Integer, Integer>();\nIterator<Map.Entry<Integer, Integer>> entries = map.entrySet().iterator();\nwhile (entries.hasNext()) {\n Map.Entry<Integer, Integer> entry = entries.next();\n System.out.println(\"Key = \" + entry.getKey() + \", Value = \" + entry.getValue());\n}\n</code></pre>\n"
},
{
"answer_id": 19491759,
"author": "The Coordinator",
"author_id": 1584255,
"author_profile": "https://Stackoverflow.com/users/1584255",
"pm_score": 8,
"selected": false,
"text": "<p>In Java 8 you can do it clean and fast using the new lambdas features:</p>\n\n<pre><code> Map<String,String> map = new HashMap<>();\n map.put(\"SomeKey\", \"SomeValue\");\n map.forEach( (k,v) -> [do something with key and value] );\n\n // such as\n map.forEach( (k,v) -> System.out.println(\"Key: \" + k + \": Value: \" + v));\n</code></pre>\n\n<p>The type of <code>k</code> and <code>v</code> will be inferred by the compiler and there is no need to use <code>Map.Entry</code> anymore.</p>\n\n<p>Easy-peasy!</p>\n"
},
{
"answer_id": 20286334,
"author": "dmunozfer",
"author_id": 1276364,
"author_profile": "https://Stackoverflow.com/users/1276364",
"pm_score": 5,
"selected": false,
"text": "<p>If you have a generic untyped Map you can use:</p>\n\n<pre><code>Map map = new HashMap();\nfor (Map.Entry entry : ((Set<Map.Entry>) map.entrySet())) {\n System.out.println(entry.getKey() + \"/\" + entry.getValue());\n}\n</code></pre>\n"
},
{
"answer_id": 20903678,
"author": "J.B.Vala",
"author_id": 3141443,
"author_profile": "https://Stackoverflow.com/users/3141443",
"pm_score": 3,
"selected": false,
"text": "<p>There are several ways to iterate a map. Please refer to the following code.</p>\n<p>When you iterate a map using iterator Interface you must go with <code>Entry<K,V></code> or <code>entrySet()</code>.</p>\n<p>It looks like this:</p>\n<pre class=\"lang-java prettyprint-override\"><code> import java.util.*;\n import java.util.HashMap;\n import java.util.Iterator;\n import java.util.Map;\n\n public class IteratMapDemo{\n\n public static void main(String arg[]){\n Map<String, String> mapOne = new HashMap<String, String>();\n mapOne.put("1", "January");\n mapOne.put("2", "February");\n mapOne.put("3", "March");\n mapOne.put("4", "April");\n mapOne.put("5", "May");\n mapOne.put("6", "June");\n mapOne.put("7", "July");\n mapOne.put("8", "August");\n mapOne.put("9", "September");\n mapOne.put("10", "Octomber");\n mapOne.put("11", "November");\n mapOne.put("12", "December");\n\n Iterator it = mapOne.entrySet().iterator();\n while(it.hasNext())\n {\n Map.Entry me = (Map.Entry) it.next();\n //System.out.println("Get Key through While loop = " + me.getKey());\n }\n for(Map.Entry<String, String> entry:mapOne.entrySet()){\n //System.out.println(entry.getKey() + "=" + entry.getValue());\n }\n\n for (Object key : mapOne.keySet()) {\n System.out.println("Key: " + key.toString() + " Value: " +\n mapOne.get(key));\n }\n }\n }\n</code></pre>\n"
},
{
"answer_id": 21431305,
"author": "Rupesh Yadav",
"author_id": 918472,
"author_profile": "https://Stackoverflow.com/users/918472",
"pm_score": 5,
"selected": false,
"text": "<p>In Map one can Iteration over <code>keys</code> and/or <code>values</code> and/or <code>both (e.g., entrySet)</code> depends on one's interested in_ Like:</p>\n<ol>\n<li><p>Iterate through the <a href=\"http://java.sun.com/j2se/1.5.0/docs/api/java/util/Map.html#keySet%28%29\" rel=\"nofollow noreferrer\"><code>keys -> keySet()</code></a> of the map:</p>\n<pre><code> Map<String, Object> map = ...;\n\n for (String key : map.keySet()) {\n //your Business logic...\n }\n</code></pre>\n</li>\n<li><p>Iterate through the <a href=\"http://java.sun.com/j2se/1.5.0/docs/api/java/util/Map.html#values%28%29\" rel=\"nofollow noreferrer\"><code>values -> values()</code></a> of the map:</p>\n<pre><code> for (Object value : map.values()) {\n //your Business logic...\n }\n</code></pre>\n</li>\n<li><p>Iterate through the <a href=\"http://java.sun.com/j2se/1.5.0/docs/api/java/util/Map.html#entrySet%28%29\" rel=\"nofollow noreferrer\"><code>both -> entrySet()</code></a> of the map:</p>\n<pre><code> for (Map.Entry<String, Object> entry : map.entrySet()) {\n String key = entry.getKey();\n Object value = entry.getValue();\n //your Business logic...\n }\n</code></pre>\n</li>\n</ol>\n<p>Moreover, there are 3 different ways to iterate through a HashMap. They are as below:</p>\n<pre><code>//1.\nfor (Map.Entry entry : hm.entrySet()) {\n System.out.print("key,val: ");\n System.out.println(entry.getKey() + "," + entry.getValue());\n}\n\n//2.\nIterator iter = hm.keySet().iterator();\nwhile(iter.hasNext()) {\n Integer key = (Integer)iter.next();\n String val = (String)hm.get(key);\n System.out.println("key,val: " + key + "," + val);\n}\n\n//3.\nIterator it = hm.entrySet().iterator();\nwhile (it.hasNext()) {\n Map.Entry entry = (Map.Entry) it.next();\n Integer key = (Integer)entry.getKey();\n String val = (String)entry.getValue();\n System.out.println("key,val: " + key + "," + val);\n}\n</code></pre>\n"
},
{
"answer_id": 21570332,
"author": "Darshan Patel",
"author_id": 3131537,
"author_profile": "https://Stackoverflow.com/users/3131537",
"pm_score": 6,
"selected": false,
"text": "<p>There are several ways to iterate over map.</p>\n\n<p>Here is comparison of their performances for a common data set stored in map by storing a million key value pairs in map and will iterate over map.</p>\n\n<p><strong>1) Using <code>entrySet()</code> in for each loop</strong></p>\n\n<pre><code>for (Map.Entry<String,Integer> entry : testMap.entrySet()) {\n entry.getKey();\n entry.getValue();\n}\n</code></pre>\n\n<p><em>50 milliseconds</em></p>\n\n<p><strong>2) Using <code>keySet()</code> in for each loop</strong></p>\n\n<pre><code>for (String key : testMap.keySet()) {\n testMap.get(key);\n}\n</code></pre>\n\n<p><em>76 milliseconds</em></p>\n\n<p><strong>3) Using <code>entrySet()</code> and iterator</strong></p>\n\n<pre><code>Iterator<Map.Entry<String,Integer>> itr1 = testMap.entrySet().iterator();\nwhile(itr1.hasNext()) {\n Map.Entry<String,Integer> entry = itr1.next();\n entry.getKey();\n entry.getValue();\n}\n</code></pre>\n\n<p><em>50 milliseconds</em></p>\n\n<p><strong>4) Using <code>keySet()</code> and iterator</strong></p>\n\n<pre><code>Iterator itr2 = testMap.keySet().iterator();\nwhile(itr2.hasNext()) {\n String key = itr2.next();\n testMap.get(key);\n}\n</code></pre>\n\n<p><em>75 milliseconds</em></p>\n\n<p>I have referred <a href=\"http://howtodoinjava.com/2013/04/01/performance-comparison-of-different-ways-to-iterate-over-hashmap/\" rel=\"noreferrer\"><code>this link</code></a>.</p>\n"
},
{
"answer_id": 22513787,
"author": "Fadid",
"author_id": 3254469,
"author_profile": "https://Stackoverflow.com/users/3254469",
"pm_score": 4,
"selected": false,
"text": "<pre><code> Iterator iterator = map.entrySet().iterator();\n while (iterator.hasNext()) {\n Map.Entry element = (Map.Entry)it.next();\n LOGGER.debug(\"Key: \" + element.getKey());\n LOGGER.debug(\"value: \" + element.getValue()); \n }\n</code></pre>\n"
},
{
"answer_id": 25116661,
"author": "Georgios Syngouroglou",
"author_id": 1123501,
"author_profile": "https://Stackoverflow.com/users/1123501",
"pm_score": 5,
"selected": false,
"text": "<p><strong>Java 8:</strong></p>\n\n<p>You can use lambda expressions:</p>\n\n<pre><code>myMap.entrySet().stream().forEach((entry) -> {\n Object currentKey = entry.getKey();\n Object currentValue = entry.getValue();\n});\n</code></pre>\n\n<p>For more information, follow <a href=\"http://docs.oracle.com/javase/tutorial/java/javaOO/lambdaexpressions.html\" rel=\"noreferrer\">this</a>.</p>\n"
},
{
"answer_id": 25436802,
"author": "fechidal89",
"author_id": 1941878,
"author_profile": "https://Stackoverflow.com/users/1941878",
"pm_score": 2,
"selected": false,
"text": "<p>I copied the data of a map to another with this code:</p>\n\n<pre><code>HashMap product =(HashMap)shopping_truck.get(i);\nHashMap tmp = new HashMap();\nfor (Iterator it = product.entrySet().iterator(); it.hasNext();) {\n Map.Entry thisEntry = (Map.Entry) it.next();\n tmp.put(thisEntry.getKey(), thisEntry.getValue());\n}\n</code></pre>\n"
},
{
"answer_id": 27871427,
"author": "JohnK",
"author_id": 1431728,
"author_profile": "https://Stackoverflow.com/users/1431728",
"pm_score": 2,
"selected": false,
"text": "<p>It doesn't quite answer the OP's question, but might be useful to others who find this page:</p>\n\n<p>If you only need the values and not the keys, you can do this:</p>\n\n<pre><code>Map<Ktype, Vtype> myMap = [...];\nfor (Vtype v: myMap.values()) {\n System.out.println(\"value: \" + v);\n}\n</code></pre>\n\n<p><code>Ktype</code>, <code>Vtype</code> are pseudocode.</p>\n"
},
{
"answer_id": 30215019,
"author": "Mr. Polywhirl",
"author_id": 1762224,
"author_profile": "https://Stackoverflow.com/users/1762224",
"pm_score": 3,
"selected": false,
"text": "<p>Here is a generic type-safe method which can be called to dump any given <code>Map</code>.</p>\n\n<pre><code>import java.util.Iterator;\nimport java.util.Map;\n\npublic class MapUtils {\n static interface ItemCallback<K, V> {\n void handler(K key, V value, Map<K, V> map);\n }\n\n public static <K, V> void forEach(Map<K, V> map, ItemCallback<K, V> callback) {\n Iterator<Map.Entry<K, V>> it = map.entrySet().iterator();\n\n while (it.hasNext()) {\n Map.Entry<K, V> entry = it.next();\n\n callback.handler(entry.getKey(), entry.getValue(), map);\n }\n }\n\n public static <K, V> void printMap(Map<K, V> map) {\n forEach(map, new ItemCallback<K, V>() {\n @Override\n public void handler(K key, V value, Map<K, V> map) {\n System.out.println(key + \" = \" + value);\n }\n });\n }\n}\n</code></pre>\n\n<h2>Example</h2>\n\n<p>Here is an example of its use. Notice that the type of the <code>Map</code> is inferred by the method.</p>\n\n<pre><code>import java.util.*;\n\npublic class MapPrinter {\n public static void main(String[] args) {\n List<Map<?, ?>> maps = new ArrayList<Map<?, ?>>() {\n private static final long serialVersionUID = 1L;\n {\n add(new LinkedHashMap<String, Integer>() {\n private static final long serialVersionUID = 1L;\n {\n put(\"One\", 0);\n put(\"Two\", 1);\n put(\"Three\", 3);\n }\n });\n\n add(new LinkedHashMap<String, Object>() {\n private static final long serialVersionUID = 1L;\n {\n put(\"Object\", new Object());\n put(\"Integer\", new Integer(0));\n put(\"Double\", new Double(0.0));\n }\n });\n }\n };\n\n for (Map<?, ?> map : maps) {\n MapUtils.printMap(map);\n System.out.println();\n }\n }\n}\n</code></pre>\n\n<h2>Output</h2>\n\n<pre><code>One = 0\nTwo = 1\nThree = 3\n\nObject = java.lang.Object@15db9742\nInteger = 0\nDouble = 0.0\n</code></pre>\n"
},
{
"answer_id": 30550239,
"author": "Joshua Michael Calafell",
"author_id": 2197975,
"author_profile": "https://Stackoverflow.com/users/2197975",
"pm_score": 2,
"selected": false,
"text": "<p>This is the easiest way of doing it I believe...</p>\n\n<pre><code>/* For example, this could be a map object */\nMap<String, Integer> MAP = new Map<>();\n\n// Do something like put keys/value pairs into the map, etc...\nMAP.put(\"Denver\", 35);\nMAP.put(\"Patriots\", 14);\n\n/* Then, simply use a for each loop like this to iterate */\nfor (Object o : MAP.entrySet()) {\n Map.Entry pair = (Map.Entry) o;\n // Do whatever with the pair here (i.e. pair.getKey(), or pair.getValue();\n}\n</code></pre>\n"
},
{
"answer_id": 32288690,
"author": "tomaj",
"author_id": 1758634,
"author_profile": "https://Stackoverflow.com/users/1758634",
"pm_score": 3,
"selected": false,
"text": "<p>If your reason for iterating trough the <code>Map</code>, is to do an operation on the value and write to a resulting <code>Map</code>. I recommend using the <code>transform</code>-methods in the <a href=\"https://github.com/google/guava\" rel=\"noreferrer\">Google Guava</a> <code>Maps</code> class.</p>\n\n<pre><code>import com.google.common.collect.Maps;\n</code></pre>\n\n<p>After you have added the <code>Maps</code> to your imports, you can use <code>Maps.transformValues</code> and <code>Maps.transformEntries</code> on your maps, like this:</p>\n\n<pre><code>public void transformMap(){\n Map<String, Integer> map = new HashMap<>();\n map.put(\"a\", 2);\n map.put(\"b\", 4);\n\n Map<String, Integer> result = Maps.transformValues(map, num -> num * 2);\n result.forEach((key, val) -> print(key, Integer.toString(val)));\n // key=a,value=4\n // key=b,value=8\n\n Map<String, String> result2 = Maps.transformEntries(map, (key, value) -> value + \"[\" + key + \"]\");\n result2.forEach(this::print);\n // key=a,value=2[a]\n // key=b,value=4[b]\n}\n\nprivate void print(String key, String val){\n System.out.println(\"key=\" + key + \",value=\" + val);\n}\n</code></pre>\n"
},
{
"answer_id": 32343110,
"author": "akhil_mittal",
"author_id": 1216775,
"author_profile": "https://Stackoverflow.com/users/1216775",
"pm_score": 5,
"selected": false,
"text": "<h2>Java 8</h2>\n\n<p>We have got <code>forEach</code> method that accepts a <a href=\"https://docs.oracle.com/javase/tutorial/java/javaOO/lambdaexpressions.html\" rel=\"noreferrer\">lambda expression</a>. We have also got <a href=\"https://docs.oracle.com/javase/8/docs/api/java/util/stream/package-summary.html\" rel=\"noreferrer\">stream</a> APIs. Consider a map:</p>\n\n<pre><code>Map<String,String> sample = new HashMap<>();\nsample.put(\"A\",\"Apple\");\nsample.put(\"B\", \"Ball\");\n</code></pre>\n\n<p><strong>Iterate over keys:</strong></p>\n\n<pre><code>sample.keySet().forEach((k) -> System.out.println(k));\n</code></pre>\n\n<p><strong>Iterate over values:</strong></p>\n\n<pre><code>sample.values().forEach((v) -> System.out.println(v));\n</code></pre>\n\n<p><strong>Iterate over entries (Using forEach and Streams):</strong></p>\n\n<pre><code>sample.forEach((k,v) -> System.out.println(k + \":\" + v)); \nsample.entrySet().stream().forEach((entry) -> {\n Object currentKey = entry.getKey();\n Object currentValue = entry.getValue();\n System.out.println(currentKey + \":\" + currentValue);\n });\n</code></pre>\n\n<p>The advantage with streams is they can be parallelized easily in case we want to. We simply need to use <code>parallelStream()</code> in place of <code>stream()</code> above.</p>\n\n<p><strong><code>forEachOrdered</code> vs <code>forEach</code> with streams ?</strong>\nThe <code>forEach</code> does not follow encounter order (if defined) and is inherently non-deterministic in nature where as the <code>forEachOrdered</code> does. So <code>forEach</code> does not guarantee that the order would be kept. Also check <a href=\"https://stackoverflow.com/questions/32797579/foreach-vs-foreachordered-in-java-8-stream\">this</a> for more.</p>\n"
},
{
"answer_id": 32973406,
"author": "Nitin Mahesh",
"author_id": 1503859,
"author_profile": "https://Stackoverflow.com/users/1503859",
"pm_score": 5,
"selected": false,
"text": "<blockquote>\n <p><strong>Lambda</strong> Expression Java 8</p>\n</blockquote>\n\n<p>In Java 1.8 (Java 8) this has become lot easier by using <strong>forEach</strong> method from Aggregate operations(<strong>Stream operations</strong>) that looks similar to iterators from <strong>Iterable</strong> Interface. </p>\n\n<p>Just copy paste below statement to your code and rename the <strong>HashMap</strong> variable from <strong>hm</strong> to your HashMap variable to print out key-value pair.</p>\n\n<pre><code>HashMap<Integer,Integer> hm = new HashMap<Integer, Integer>();\n/*\n * Logic to put the Key,Value pair in your HashMap hm\n */\n\n// Print the key value pair in one line.\n\nhm.forEach((k, v) -> System.out.println(\"key: \" + k + \" value:\" + v));\n\n// Just copy and paste above line to your code.\n</code></pre>\n\n<p>Below is the sample code that I tried using <strong>Lambda Expression</strong>. This stuff is so cool. Must try.</p>\n\n<pre><code>HashMap<Integer, Integer> hm = new HashMap<Integer, Integer>();\n Random rand = new Random(47);\n int i = 0;\n while(i < 5) {\n i++;\n int key = rand.nextInt(20);\n int value = rand.nextInt(50);\n System.out.println(\"Inserting key: \" + key + \" Value: \" + value);\n Integer imap = hm.put(key, value);\n if( imap == null) {\n System.out.println(\"Inserted\");\n } else {\n System.out.println(\"Replaced with \" + imap);\n } \n }\n\n hm.forEach((k, v) -> System.out.println(\"key: \" + k + \" value:\" + v));\n\nOutput:\n\nInserting key: 18 Value: 5\nInserted\nInserting key: 13 Value: 11\nInserted\nInserting key: 1 Value: 29\nInserted\nInserting key: 8 Value: 0\nInserted\nInserting key: 2 Value: 7\nInserted\nkey: 1 value:29\nkey: 18 value:5\nkey: 2 value:7\nkey: 8 value:0\nkey: 13 value:11\n</code></pre>\n\n<p>Also one can use <strong>Spliterator</strong> for the same.</p>\n\n<pre><code>Spliterator sit = hm.entrySet().spliterator();\n</code></pre>\n\n<p><strong>UPDATE</strong></p>\n\n<hr>\n\n<p>Including documentation links to Oracle Docs.\nFor more on <strong>Lambda</strong> go to this <a href=\"https://docs.oracle.com/javase/tutorial/java/javaOO/lambdaexpressions.html\" rel=\"noreferrer\">link</a> and must read <a href=\"https://docs.oracle.com/javase/tutorial/collections/streams/\" rel=\"noreferrer\">Aggregate Operations</a> and for Spliterator go to this <a href=\"https://docs.oracle.com/javase/8/docs/api/java/util/Spliterator.html\" rel=\"noreferrer\">link</a>.</p>\n"
},
{
"answer_id": 33375492,
"author": "Syd Lambert",
"author_id": 5135746,
"author_profile": "https://Stackoverflow.com/users/5135746",
"pm_score": 2,
"selected": false,
"text": "<p>If you want to iterate through the map in the order that the elements were added, use <code>LinkedHashMap</code> as opposed to just <code>Map</code>.</p>\n\n<p>This approach has worked for me in the past:</p>\n\n<pre><code>LinkedHashMap<String,Integer> test=new LinkedHashMap();\n\ntest.put(\"foo\",69);\ntest.put(\"bar\",1337);\n\nfor(int i=0;i<test.size();i++){\n System.out.println(test.get(test.keySet().toArray()[i]));\n}\n</code></pre>\n\n<p>Output:</p>\n\n<pre><code>69\n1337\n</code></pre>\n"
},
{
"answer_id": 35558955,
"author": "Slava Vedenin",
"author_id": 4318868,
"author_profile": "https://Stackoverflow.com/users/4318868",
"pm_score": 11,
"selected": false,
"text": "<p>To summarize the other answers and combine them with what I know, I found 10 main ways to do this (see below). Also, I wrote some performance tests (see results below). For example, if we want to find the sum of all of the keys and values of a map, we can write:</p>\n\n<ol>\n<li><p>Using <strong>iterator</strong> and <strong>Map.Entry</strong></p>\n\n<pre><code>long i = 0;\nIterator<Map.Entry<Integer, Integer>> it = map.entrySet().iterator();\nwhile (it.hasNext()) {\n Map.Entry<Integer, Integer> pair = it.next();\n i += pair.getKey() + pair.getValue();\n}\n</code></pre></li>\n<li><p>Using <strong>foreach</strong> and <strong>Map.Entry</strong></p>\n\n<pre><code>long i = 0;\nfor (Map.Entry<Integer, Integer> pair : map.entrySet()) {\n i += pair.getKey() + pair.getValue();\n}\n</code></pre></li>\n<li><p>Using <strong>forEach</strong> from Java 8</p>\n\n<pre><code>final long[] i = {0};\nmap.forEach((k, v) -> i[0] += k + v);\n</code></pre></li>\n<li><p>Using <strong>keySet</strong> and <strong>foreach</strong></p>\n\n<pre><code>long i = 0;\nfor (Integer key : map.keySet()) {\n i += key + map.get(key);\n}\n</code></pre></li>\n<li><p>Using <strong>keySet</strong> and <strong>iterator</strong></p>\n\n<pre><code>long i = 0;\nIterator<Integer> itr2 = map.keySet().iterator();\nwhile (itr2.hasNext()) {\n Integer key = itr2.next();\n i += key + map.get(key);\n}\n</code></pre></li>\n<li><p>Using <strong>for</strong> and <strong>Map.Entry</strong></p>\n\n<pre><code>long i = 0;\nfor (Iterator<Map.Entry<Integer, Integer>> entries = map.entrySet().iterator(); entries.hasNext(); ) {\n Map.Entry<Integer, Integer> entry = entries.next();\n i += entry.getKey() + entry.getValue();\n}\n</code></pre></li>\n<li><p>Using the Java 8 <strong>Stream API</strong></p>\n\n<pre><code>final long[] i = {0};\nmap.entrySet().stream().forEach(e -> i[0] += e.getKey() + e.getValue());\n</code></pre></li>\n<li><p>Using the Java 8 <strong>Stream API parallel</strong></p>\n\n<pre><code>final long[] i = {0};\nmap.entrySet().stream().parallel().forEach(e -> i[0] += e.getKey() + e.getValue());\n</code></pre></li>\n<li><p>Using <strong>IterableMap</strong> of <code>Apache Collections</code></p>\n\n<pre><code>long i = 0;\nMapIterator<Integer, Integer> it = iterableMap.mapIterator();\nwhile (it.hasNext()) {\n i += it.next() + it.getValue();\n}\n</code></pre></li>\n<li><p>Using <strong>MutableMap</strong> of Eclipse (CS) collections</p>\n\n<pre><code>final long[] i = {0};\nmutableMap.forEachKeyValue((key, value) -> {\n i[0] += key + value;\n});\n</code></pre></li>\n</ol>\n\n<p><strong>Perfomance tests</strong> (mode = AverageTime, system = Windows 8.1 64-bit, Intel i7-4790 3.60 GHz, 16 GB)</p>\n\n<ol>\n<li><p>For a small map (100 elements), score 0.308 is the best</p>\n\n<pre><code>Benchmark Mode Cnt Score Error Units\ntest3_UsingForEachAndJava8 avgt 10 0.308 ± 0.021 µs/op\ntest10_UsingEclipseMap avgt 10 0.309 ± 0.009 µs/op\ntest1_UsingWhileAndMapEntry avgt 10 0.380 ± 0.014 µs/op\ntest6_UsingForAndIterator avgt 10 0.387 ± 0.016 µs/op\ntest2_UsingForEachAndMapEntry avgt 10 0.391 ± 0.023 µs/op\ntest7_UsingJava8StreamApi avgt 10 0.510 ± 0.014 µs/op\ntest9_UsingApacheIterableMap avgt 10 0.524 ± 0.008 µs/op\ntest4_UsingKeySetAndForEach avgt 10 0.816 ± 0.026 µs/op\ntest5_UsingKeySetAndIterator avgt 10 0.863 ± 0.025 µs/op\ntest8_UsingJava8StreamApiParallel avgt 10 5.552 ± 0.185 µs/op\n</code></pre></li>\n<li><p>For a map with 10000 elements, score 37.606 is the best</p>\n\n<pre><code>Benchmark Mode Cnt Score Error Units\ntest10_UsingEclipseMap avgt 10 37.606 ± 0.790 µs/op\ntest3_UsingForEachAndJava8 avgt 10 50.368 ± 0.887 µs/op\ntest6_UsingForAndIterator avgt 10 50.332 ± 0.507 µs/op\ntest2_UsingForEachAndMapEntry avgt 10 51.406 ± 1.032 µs/op\ntest1_UsingWhileAndMapEntry avgt 10 52.538 ± 2.431 µs/op\ntest7_UsingJava8StreamApi avgt 10 54.464 ± 0.712 µs/op\ntest4_UsingKeySetAndForEach avgt 10 79.016 ± 25.345 µs/op\ntest5_UsingKeySetAndIterator avgt 10 91.105 ± 10.220 µs/op\ntest8_UsingJava8StreamApiParallel avgt 10 112.511 ± 0.365 µs/op\ntest9_UsingApacheIterableMap avgt 10 125.714 ± 1.935 µs/op\n</code></pre></li>\n<li><p>For a map with 100000 elements, score 1184.767 is the best</p>\n\n<pre><code>Benchmark Mode Cnt Score Error Units\ntest1_UsingWhileAndMapEntry avgt 10 1184.767 ± 332.968 µs/op\ntest10_UsingEclipseMap avgt 10 1191.735 ± 304.273 µs/op\ntest2_UsingForEachAndMapEntry avgt 10 1205.815 ± 366.043 µs/op\ntest6_UsingForAndIterator avgt 10 1206.873 ± 367.272 µs/op\ntest8_UsingJava8StreamApiParallel avgt 10 1485.895 ± 233.143 µs/op\ntest5_UsingKeySetAndIterator avgt 10 1540.281 ± 357.497 µs/op\ntest4_UsingKeySetAndForEach avgt 10 1593.342 ± 294.417 µs/op\ntest3_UsingForEachAndJava8 avgt 10 1666.296 ± 126.443 µs/op\ntest7_UsingJava8StreamApi avgt 10 1706.676 ± 436.867 µs/op\ntest9_UsingApacheIterableMap avgt 10 3289.866 ± 1445.564 µs/op\n</code></pre></li>\n</ol>\n\n<p>Graphs (performance tests depending on map size)</p>\n\n<p><a href=\"https://i.stack.imgur.com/17VGh.png\" rel=\"noreferrer\"><img src=\"https://i.stack.imgur.com/17VGh.png\" alt=\"Enter image description here\"></a></p>\n\n<p>Table (perfomance tests depending on map size)</p>\n\n<pre><code> 100 600 1100 1600 2100\ntest10 0.333 1.631 2.752 5.937 8.024\ntest3 0.309 1.971 4.147 8.147 10.473\ntest6 0.372 2.190 4.470 8.322 10.531\ntest1 0.405 2.237 4.616 8.645 10.707\ntest2 0.376 2.267 4.809 8.403 10.910\ntest7 0.473 2.448 5.668 9.790 12.125\ntest9 0.565 2.830 5.952 13.220 16.965\ntest4 0.808 5.012 8.813 13.939 17.407\ntest5 0.810 5.104 8.533 14.064 17.422\ntest8 5.173 12.499 17.351 24.671 30.403\n</code></pre>\n\n<p>All tests are on <a href=\"https://github.com/Vedenin/useful-java-links/blob/master/helloworlds/5.0-other-examples/src/main/java/other_examples/IterateThroughHashMapTest.java\" rel=\"noreferrer\">GitHub</a>.</p>\n"
},
{
"answer_id": 36591840,
"author": "Sajad NasiriNezhad",
"author_id": 4533984,
"author_profile": "https://Stackoverflow.com/users/4533984",
"pm_score": 4,
"selected": false,
"text": "<pre><code> //Functional Oprations\n Map<String, String> mapString = new HashMap<>();\n mapString.entrySet().stream().map((entry) -> {\n String mapKey = entry.getKey();\n return entry;\n }).forEach((entry) -> {\n String mapValue = entry.getValue();\n });\n\n //Intrator\n Map<String, String> mapString = new HashMap<>();\n for (Iterator<Map.Entry<String, String>> it = mapString.entrySet().iterator(); it.hasNext();) {\n Map.Entry<String, String> entry = it.next();\n String mapKey = entry.getKey();\n String mapValue = entry.getValue();\n }\n\n //Simple for loop\n Map<String, String> mapString = new HashMap<>();\n for (Map.Entry<String, String> entry : mapString.entrySet()) {\n String mapKey = entry.getKey();\n String mapValue = entry.getValue();\n\n }\n</code></pre>\n"
},
{
"answer_id": 40260450,
"author": "Witold Kaczurba",
"author_id": 6931119,
"author_profile": "https://Stackoverflow.com/users/6931119",
"pm_score": 5,
"selected": false,
"text": "<p>The ordering will always depend on the specific map implementation.\nUsing Java 8 you can use either of these:</p>\n<pre><code>map.forEach((k,v) -> { System.out.println(k + ":" + v); });\n</code></pre>\n<p>Or:</p>\n<pre><code>map.entrySet().forEach((e) -> {\n System.out.println(e.getKey() + " : " + e.getValue());\n });\n</code></pre>\n<p>The result will be the same (same order). The entrySet backed by the map so you are getting the same order. The second one is handy as it allows you to use lambdas, e.g. if you want only to print only Integer objects that are greater than 5:</p>\n<pre><code>map.entrySet()\n .stream()\n .filter(e-> e.getValue() > 5)\n .forEach(System.out::println);\n</code></pre>\n<p>The code below shows iteration through LinkedHashMap and normal HashMap (example). You will see difference in the order:</p>\n<pre><code>public class HMIteration {\n\n\n public static void main(String[] args) {\n Map<Object, Object> linkedHashMap = new LinkedHashMap<>();\n Map<Object, Object> hashMap = new HashMap<>();\n\n for (int i=10; i>=0; i--) {\n linkedHashMap.put(i, i);\n hashMap.put(i, i);\n }\n\n System.out.println("LinkedHashMap (1): ");\n linkedHashMap.forEach((k,v) -> { System.out.print(k + " (#="+k.hashCode() + "):" + v + ", "); });\n\n System.out.println("\\nLinkedHashMap (2): ");\n\n linkedHashMap.entrySet().forEach((e) -> {\n System.out.print(e.getKey() + " : " + e.getValue() + ", ");\n });\n\n\n System.out.println("\\n\\nHashMap (1): ");\n hashMap.forEach((k,v) -> { System.out.print(k + " (#:"+k.hashCode() + "):" + v + ", "); });\n\n System.out.println("\\nHashMap (2): ");\n\n hashMap.entrySet().forEach((e) -> {\n System.out.print(e.getKey() + " : " + e.getValue() + ", ");\n });\n }\n}\n</code></pre>\n<p>Output:</p>\n<pre><code>LinkedHashMap (1):\n10 (#=10):10, 9 (#=9):9, 8 (#=8):8, 7 (#=7):7, 6 (#=6):6, 5 (#=5):5, 4 (#=4):4, 3 (#=3):3, 2 (#=2):2, 1 (#=1):1, 0 (#=0):0,\nLinkedHashMap (2):\n10 : 10, 9 : 9, 8 : 8, 7 : 7, 6 : 6, 5 : 5, 4 : 4, 3 : 3, 2 : 2, 1 : 1, 0 : 0,\nHashMap (1):\n0 (#:0):0, 1 (#:1):1, 2 (#:2):2, 3 (#:3):3, 4 (#:4):4, 5 (#:5):5, 6 (#:6):6, 7 (#:7):7, 8 (#:8):8, 9 (#:9):9, 10 (#:10):10,\nHashMap (2):\n0 : 0, 1 : 1, 2 : 2, 3 : 3, 4 : 4, 5 : 5, 6 : 6, 7 : 7, 8 : 8, 9 : 9, 10 : 10,\n</code></pre>\n"
},
{
"answer_id": 43247492,
"author": "Rupendra Sharma",
"author_id": 1706743,
"author_profile": "https://Stackoverflow.com/users/1706743",
"pm_score": 3,
"selected": false,
"text": "<pre><code>package com.test;\n\nimport java.util.Collection;\nimport java.util.HashMap;\nimport java.util.Iterator;\nimport java.util.Map;\nimport java.util.Map.Entry;\nimport java.util.Set;\n\npublic class Test {\n\n public static void main(String[] args) {\n Map<String, String> map = new HashMap<String, String>();\n map.put(\"ram\", \"ayodhya\");\n map.put(\"krishan\", \"mathura\");\n map.put(\"shiv\", \"kailash\");\n\n System.out.println(\"********* Keys *********\");\n Set<String> keys = map.keySet();\n for (String key : keys) {\n System.out.println(key);\n }\n\n System.out.println(\"********* Values *********\");\n Collection<String> values = map.values();\n for (String value : values) {\n System.out.println(value);\n }\n\n System.out.println(\"***** Keys and Values (Using for each loop) *****\");\n for (Map.Entry<String, String> entry : map.entrySet()) {\n System.out.println(\"Key: \" + entry.getKey() + \"\\t Value: \"\n + entry.getValue());\n }\n\n System.out.println(\"***** Keys and Values (Using while loop) *****\");\n Iterator<Entry<String, String>> entries = map.entrySet().iterator();\n while (entries.hasNext()) {\n Map.Entry<String, String> entry = (Map.Entry<String, String>) entries\n .next();\n System.out.println(\"Key: \" + entry.getKey() + \"\\t Value: \"\n + entry.getValue());\n }\n\n System.out\n .println(\"** Keys and Values (Using java 8 using lambdas )***\");\n map.forEach((k, v) -> System.out\n .println(\"Key: \" + k + \"\\t value: \" + v));\n }\n}\n</code></pre>\n"
},
{
"answer_id": 47122590,
"author": "shivampip",
"author_id": 6759926,
"author_profile": "https://Stackoverflow.com/users/6759926",
"pm_score": 4,
"selected": false,
"text": "<p>Iterating a <a href=\"https://docs.oracle.com/javase/10/docs/api/java/util/Map.html\" rel=\"noreferrer\">Map</a> is very easy. </p>\n\n<pre><code>for(Object key: map.keySet()){\n Object value= map.get(key);\n //Do your stuff\n}\n</code></pre>\n\n<p>For instance, you have a <code>Map<String, int> data;</code></p>\n\n<pre><code>for(Object key: data.keySet()){\n int value= data.get(key);\n}\n</code></pre>\n"
},
{
"answer_id": 47256829,
"author": "Utpal Kumar",
"author_id": 4745890,
"author_profile": "https://Stackoverflow.com/users/4745890",
"pm_score": 4,
"selected": false,
"text": "<p>There are a lot of ways to do this. Below is a few simple steps:</p>\n\n<p>Suppose you have one Map like:</p>\n\n<pre><code>Map<String, Integer> m = new HashMap<String, Integer>();\n</code></pre>\n\n<p>Then you can do something like the below to iterate over map elements.</p>\n\n<pre><code>// ********** Using an iterator ****************\nIterator<Entry<String, Integer>> me = m.entrySet().iterator();\nwhile(me.hasNext()){\n Entry<String, Integer> pair = me.next();\n System.out.println(pair.getKey() + \":\" + pair.getValue());\n}\n\n// *********** Using foreach ************************\nfor(Entry<String, Integer> me : m.entrySet()){\n System.out.println(me.getKey() + \" : \" + me.getValue());\n}\n\n// *********** Using keySet *****************************\nfor(String s : m.keySet()){\n System.out.println(s + \" : \" + m.get(s));\n}\n\n// *********** Using keySet and iterator *****************\nIterator<String> me = m.keySet().iterator();\nwhile(me.hasNext()){\n String key = me.next();\n System.out.println(key + \" : \" + m.get(key));\n}\n</code></pre>\n"
},
{
"answer_id": 49885402,
"author": "ABHAY JOHRI",
"author_id": 7369238,
"author_profile": "https://Stackoverflow.com/users/7369238",
"pm_score": 4,
"selected": false,
"text": "<p>Use Java 8:</p>\n\n<pre><code>map.entrySet().forEach(entry -> System.out.println(entry.getValue()));\n</code></pre>\n"
},
{
"answer_id": 49921231,
"author": "bluehallu",
"author_id": 512907,
"author_profile": "https://Stackoverflow.com/users/512907",
"pm_score": 5,
"selected": false,
"text": "<p>Most compact with Java 8:</p>\n\n<pre><code>map.entrySet().forEach(System.out::println);\n</code></pre>\n"
},
{
"answer_id": 50153908,
"author": "Taras Melnyk",
"author_id": 4813777,
"author_profile": "https://Stackoverflow.com/users/4813777",
"pm_score": 6,
"selected": false,
"text": "<p>With <strong>Java 8</strong>, you can iterate Map using forEach and lambda expression,</p>\n\n<pre><code>map.forEach((k, v) -> System.out.println((k + \":\" + v)));\n</code></pre>\n"
},
{
"answer_id": 53497541,
"author": "anandchaugule",
"author_id": 5756557,
"author_profile": "https://Stackoverflow.com/users/5756557",
"pm_score": 4,
"selected": false,
"text": "<p>An effective iterative solution over a Map is a <code>for</code> loop from Java 5 through Java 7. Here it is:</p>\n<pre><code>for (String key : phnMap.keySet()) {\n System.out.println("Key: " + key + " Value: " + phnMap.get(key));\n}\n</code></pre>\n<p>From Java 8 you can use a lambda expression to iterate over a Map. It is an enhanced <code>forEach</code></p>\n<pre><code>phnMap.forEach((k,v) -> System.out.println("Key: " + k + " Value: " + v));\n</code></pre>\n<p>If you want to write a conditional for lambda you can write it like this:</p>\n<pre><code>phnMap.forEach((k,v)->{\n System.out.println("Key: " + k + " Value: " + v);\n if("abc".equals(k)){\n System.out.println("Hello abc");\n }\n});\n</code></pre>\n"
},
{
"answer_id": 56467159,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 3,
"selected": false,
"text": "<p>I like to concat a counter, then save the final value of the counter;</p>\n\n<pre><code>int counter = 0;\nHashMap<String, String> m = new HashMap<String, String>();\nfor(int i = 0;i<items.length;i++)\n{\nm.put(\"firstname\"+i, items.get(i).getFirstName());\ncounter = i;\n}\n\nm.put(\"recordCount\",String.valueOf(counter));\n</code></pre>\n\n<p>Then when you want to retrieve:</p>\n\n<pre><code>int recordCount = Integer.parseInf(m.get(\"recordCount\"));\nfor(int i =0 ;i<recordCount;i++)\n{\nSystem.out.println(\"First Name :\" + m.get(\"firstname\"+i));\n}\n</code></pre>\n"
},
{
"answer_id": 57321787,
"author": "Lova Chittumuri",
"author_id": 5256337,
"author_profile": "https://Stackoverflow.com/users/5256337",
"pm_score": 3,
"selected": false,
"text": "<blockquote>\n <p>Using Java 7</p>\n</blockquote>\n\n<pre><code>Map<String,String> sampleMap = new HashMap<>();\nfor (sampleMap.Entry<String,String> entry : sampleMap.entrySet()) {\n String key = entry.getKey();\n String value = entry.getValue();\n\n /* your Code as per the Business Justification */\n\n}\n</code></pre>\n\n<blockquote>\n <p>Using Java 8</p>\n</blockquote>\n\n<pre><code>Map<String,String> sampleMap = new HashMap<>();\n\nsampleMap.forEach((k, v) -> System.out.println(\"Key is : \" + k + \" Value is : \" + v));\n</code></pre>\n"
},
{
"answer_id": 58574145,
"author": "Basil Bourque",
"author_id": 642706,
"author_profile": "https://Stackoverflow.com/users/642706",
"pm_score": 5,
"selected": false,
"text": "<blockquote>\n <p>If I have an object implementing the Map interface in Java and I wish to iterate over every pair contained within it, what is the most efficient way of going through the map?</p>\n</blockquote>\n\n<p>If efficiency of looping the keys is a priority for your app, then choose a <code>Map</code> implementation that maintains the keys in your desired order.</p>\n\n<blockquote>\n <p>Will the ordering of elements depend on the specific map implementation that I have for the interface?</p>\n</blockquote>\n\n<p>Yes, absolutely. </p>\n\n<ul>\n<li>Some <code>Map</code> implementations promise a certain iteration order, others do not.</li>\n<li>Different implementations of <code>Map</code> maintain different ordering of the key-value pairs. </li>\n</ul>\n\n<p>See this table I created summarizing the various <code>Map</code> implementations bundled with Java 11. Specifically, notice the <em>iteration order</em> column. Click/tap to zoom.</p>\n\n<p><a href=\"https://i.stack.imgur.com/4z5Fb.png\" rel=\"noreferrer\"><img src=\"https://i.stack.imgur.com/4z5Fb.png\" alt=\"Table of map implementations in Java 11, comparing their features\"></a></p>\n\n<p>You can see there are <strong>four <code>Map</code> implementations maintaining an order</strong>:</p>\n\n<ul>\n<li><code>TreeMap</code></li>\n<li><code>ConcurrentSkipListMap</code> </li>\n<li><code>LinkedHashMap</code></li>\n<li><code>EnumMap</code></li>\n</ul>\n\n<h2><code>NavigableMap</code> interface</h2>\n\n<p>Two of those implement the <a href=\"https://docs.oracle.com/en/java/javase/11/docs/api/java.base/java/util/NavigableMap.html\" rel=\"noreferrer\"><code>NavigableMap</code></a> interface: <code>TreeMap</code> & <code>ConcurrentSkipListMap</code>. </p>\n\n<p>The older <a href=\"https://docs.oracle.com/en/java/javase/11/docs/api/java.base/java/util/SortedMap.html\" rel=\"noreferrer\"><code>SortedMap</code></a> interface is effectively supplanted by the newer <a href=\"https://docs.oracle.com/en/java/javase/11/docs/api/java.base/java/util/NavigableMap.html\" rel=\"noreferrer\"><code>NavigableMap</code></a> interface. But you may find 3rd-party implementations implementing the older interface only.</p>\n\n<h2>Natural order</h2>\n\n<p>If you want a <a href=\"https://docs.oracle.com/en/java/javase/11/docs/api/java.base/java/util/Map.html\" rel=\"noreferrer\"><code>Map</code></a> that keeps its pairs arranged by the “natural order” of the key, use <a href=\"https://docs.oracle.com/en/java/javase/11/docs/api/java.base/java/util/TreeMap.html\" rel=\"noreferrer\"><code>TreeMap</code></a> or <a href=\"https://docs.oracle.com/en/java/javase/11/docs/api/java.base/java/util/concurrent/ConcurrentSkipListMap.html\" rel=\"noreferrer\"><code>ConcurrentSkipListMap</code></a>. The term “natural order” means the class of the keys implements <a href=\"https://docs.oracle.com/en/java/javase/11/docs/api/java.base/java/lang/Comparable.html\" rel=\"noreferrer\"><code>Comparable</code></a>. The value returned by the <a href=\"https://docs.oracle.com/en/java/javase/11/docs/api/java.base/java/lang/Comparable.html#compareTo(T)\" rel=\"noreferrer\"><code>compareTo</code></a> method is used for comparison in sorting.</p>\n\n<h2>Custom order</h2>\n\n<p>If you want to specify a custom sorting routine for your keys to be used in maintaining a sorted order, pass a <a href=\"https://docs.oracle.com/en/java/javase/11/docs/api/java.base/java/util/Comparator.html\" rel=\"noreferrer\"><code>Comparator</code></a> implementation appropriate to the class of your keys. Use either <a href=\"https://docs.oracle.com/en/java/javase/11/docs/api/java.base/java/util/TreeMap.html\" rel=\"noreferrer\"><code>TreeMap</code></a> or <a href=\"https://docs.oracle.com/en/java/javase/11/docs/api/java.base/java/util/concurrent/ConcurrentSkipListMap.html\" rel=\"noreferrer\"><code>ConcurrentSkipListMap</code></a>, passing your <code>Comparator</code>. </p>\n\n<h2>Original insertion order</h2>\n\n<p>If you want the pairs of your map to be kept in their original order in which you inserted them into the map, use <a href=\"https://docs.oracle.com/en/java/javase/11/docs/api/java.base/java/util/LinkedHashMap.html\" rel=\"noreferrer\"><code>LinkedHashMap</code></a>. </p>\n\n<h2>Enum-definition order</h2>\n\n<p>If you are using an enum such as <a href=\"https://docs.oracle.com/en/java/javase/11/docs/api/java.base/java/time/DayOfWeek.html\" rel=\"noreferrer\"><code>DayOfWeek</code></a> or <a href=\"https://docs.oracle.com/en/java/javase/11/docs/api/java.base/java/time/Month.html\" rel=\"noreferrer\"><code>Month</code></a> as your keys, use the <a href=\"https://docs.oracle.com/en/java/javase/11/docs/api/java.base/java/util/EnumMap.html\" rel=\"noreferrer\"><code>EnumMap</code></a> class. Not only is this class <em>highly</em> optimized to use very little memory and run very fast, it maintains your pairs in the order defined by the enum. For <code>DayOfWeek</code>, for example, the key of <code>DayOfWeek.MONDAY</code> will be first found when iterated, and the key of <code>DayOfWeek.SUNDAY</code> will be last.</p>\n\n<h2>Other considerations</h2>\n\n<p>In choosing a <code>Map</code> implementation, also consider:</p>\n\n<ul>\n<li>NULLs. Some implementations forbid/accept a NULL as key and/or value. </li>\n<li>Concurrency. If you are manipulating the map across threads, you must use an implementation that supports concurrency. Or wrap the map with <a href=\"https://docs.oracle.com/en/java/javase/11/docs/api/java.base/java/util/Collections.html#synchronizedMap(java.util.Map)\" rel=\"noreferrer\"><code>Collections::synchronizedMap</code></a> (less preferable). </li>\n</ul>\n\n<p>Both of these considerations are covered in the graphic table above.</p>\n"
},
{
"answer_id": 59608364,
"author": "Ali Akram",
"author_id": 4332316,
"author_profile": "https://Stackoverflow.com/users/4332316",
"pm_score": 3,
"selected": false,
"text": "<h1><code>Map.forEach</code></h1>\n\n<p>What about simply using <a href=\"https://docs.oracle.com/en/java/javase/11/docs/api/java.base/java/util/Map.html#forEach(java.util.function.BiConsumer)\" rel=\"noreferrer\"><code>Map::forEach</code></a> where both the key and the value are passed to your <a href=\"https://docs.oracle.com/en/java/javase/11/docs/api/java.base/java/util/function/BiConsumer.html\" rel=\"noreferrer\"><code>BiConsumer</code></a>?</p>\n\n<pre><code>map.forEach((k,v)->{\n System.out.println(k+\"->\"+v);\n});\n</code></pre>\n"
},
{
"answer_id": 62378360,
"author": "Younes El Ouarti",
"author_id": 3705861,
"author_profile": "https://Stackoverflow.com/users/3705861",
"pm_score": 3,
"selected": false,
"text": "<p>Since Java 10, you can use local variable inference (a.k.a. \"var\") to make a lot of the already available answers less bloated. For example:</p>\n\n<pre class=\"lang-java prettyprint-override\"><code>for (var entry : map.entrySet()) {\n System.out.println(entry.getKey() + \" : \" + entry.getValue());\n}\n</code></pre>\n"
},
{
"answer_id": 63910874,
"author": "Dubstep",
"author_id": 9363081,
"author_profile": "https://Stackoverflow.com/users/9363081",
"pm_score": 2,
"selected": false,
"text": "<pre><code>Map<String, String> map = \nfor (Map.Entry<String, String> entry : map.entrySet()) {\n MapKey = entry.getKey() \n MapValue = entry.getValue();\n}\n</code></pre>\n"
},
{
"answer_id": 65670377,
"author": "Badri Paudel",
"author_id": 9898251,
"author_profile": "https://Stackoverflow.com/users/9898251",
"pm_score": 2,
"selected": false,
"text": "<p>You can search for the key and with the help of the key you can find the associated value of the map as map has <strong>unique key</strong>, see what happens when key is duplicate <a href=\"https://stackoverflow.com/a/20537942/9898251\">here</a> or <a href=\"https://docs.oracle.com/javase/7/docs/api/java/util/HashMap.html#put%28K,%20V%29\" rel=\"nofollow noreferrer\">here</a>.</p>\n<p>Demo map :</p>\n<pre><code> Map<String, String> map = new HashMap();\n map.put("name", "Name");\n map.put("age", "23");\n map.put("address", "NP");\n map.put("faculty", "BE");\n map.put("major", "CS");\n map.put("head", "MDK");\n \n</code></pre>\n<p>To get key only, you can use <code>map.keySet();</code> like this :</p>\n<pre><code>for(String key : map.keySet()) {\n System.out.println(key);\n }\n</code></pre>\n<p>To get value only , you can use <code>map.values();</code> like this:</p>\n<pre><code> for(String value : map.values()) {\n System.out.println(value);\n }\n</code></pre>\n<p>To get both key and its value you still can use <code>map.keySet();</code> and get its corresponding value, like this :</p>\n<pre><code> //this prints the key value pair\n for (String k : map.keySet()) {\n System.out.println(k + " " + map.get(k) + " ");\n }\n</code></pre>\n<p><code>map.get(key)</code> gives the value pointed by that key.</p>\n"
},
{
"answer_id": 69379440,
"author": "anand krish",
"author_id": 2147814,
"author_profile": "https://Stackoverflow.com/users/2147814",
"pm_score": 4,
"selected": false,
"text": "<p>These are all the possible ways of iterating HashMap.</p>\n<pre><code>HashMap<Integer,String> map=new HashMap<Integer,String>();\n map.put(1,"David"); //Adding elements in Map\n map.put(2,"John");\n map.put(4,"Samyuktha");\n map.put(3,"jasmin");\n System.out.println("Iterating Hashmap...");\n\n //way 1 (java 8 Method)\n map.forEach((key, value) -> {\n System.out.println(key+" : "+ value);\n });\n\n //way 2 (java 7 Method)\n for(Map.Entry me : map.entrySet()){\n System.out.println(me.getKey()+" "+me.getValue());\n }\n\n //way 3 (Legacy way to iterate HashMap)\n Iterator iterator = map.entrySet().iterator();//map.keySet().iterator()\n while (iterator.hasNext())\n {\n Map.Entry me =(Map.Entry)iterator.next();\n System.out.println(me.getKey()+" : "+ me.getValue());\n }\n \n}\n</code></pre>\n"
}
] | 2008/09/05 | [
"https://Stackoverflow.com/questions/46898",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4807/"
] | If I have an object implementing the `Map` interface in Java and I wish to iterate over every pair contained within it, what is the most efficient way of going through the map?
Will the ordering of elements depend on the specific map implementation that I have for the interface? | ```java
Map<String, String> map = ...
for (Map.Entry<String, String> entry : map.entrySet()) {
System.out.println(entry.getKey() + "/" + entry.getValue());
}
```
On Java 10+:
```java
for (var entry : map.entrySet()) {
System.out.println(entry.getKey() + "/" + entry.getValue());
}
``` |
46,907 | <pre><code>INSERT INTO tblExcel (ename, position, phone, email) VALUES ('Burton, Andrew', 'Web Developer / Network Assistant', '876-9259', '[email protected]')
</code></pre>
<p>I've got an Access table that has five fields: id, ename, position, phone, and email...each one is plain text field with 50 characters, save for position which is 255 and id which is an autoincrement field. I'm using a VB.NET to read data from an Excel table, which gets pushed into a simple class that's used to fill out that query. I do the same thing with two other tables, whose data are pulled from a DB2 table and a MySQL table through. The other two work, but this simple INSERT loop keeps failing, so I don't think it's my "InsertNoExe" function that handles all the OleDb stuff.</p>
<p>So, um, does that query, any of the field titles, etc. look bogus? I can post other bits of code if anyone wants to see it.</p>
<p><strong>EDIT:</strong> Fixed. I wasn't sure if the wide image counted as a Stack Overflow bug or not, which is why I left it.</p>
<p><strong>EDIT 2:</strong> I'm dense. I use a try...catch to see the bogus query, and don't even check the ex.messsage. Gah.</p>
<pre><code>INSERT INTO tblExcel (ename, position, phone, email) VALUES ('Burton, Andrew', 'Web Developer / Network Assistant', '876-9259', '[email protected]')
at System.Data.OleDb.OleDbCommand.ExecuteCommandTextErrorHandling(Int32 hr)
at System.Data.OleDb.OleDbCommand.ExecuteCommandTextForSingleResult(tagDBPARAMS dbParams, Object& executeResult)
at System.Data.OleDb.OleDbCommand.ExecuteCommandText(Object& executeResult)
at System.Data.OleDb.OleDbCommand.ExecuteCommand(CommandBehavior behavior, Object& executeResult)
at System.Data.OleDb.OleDbCommand.ExecuteReaderInternal(CommandBehavior behavior, String method)
at System.Data.OleDb.OleDbCommand.ExecuteNonQuery()
at EmployeeList.EmployeeDatabase.ExeNonQuery(String sql) in C:\andy\html\code\vb\EmployeeList\EmployeeDatabase.vb:line 263
Syntax error in INSERT INTO statement.
</code></pre>
<p><strong>EDIT 3:</strong> Thank you, Chris.</p>
| [
{
"answer_id": 46916,
"author": "Guy Starbuck",
"author_id": 2194,
"author_profile": "https://Stackoverflow.com/users/2194",
"pm_score": 0,
"selected": false,
"text": "<p>The spacing of \"Web Developer / Network Assistant\" looks a little wonky, maybe there is a hidden character in there (carriage return?)</p>\n\n<p>I'd try taking the slash out, and see if the insert works, if not try taking all punctuation out. Then add it back and maybe you will be able to identify the bug.</p>\n"
},
{
"answer_id": 46931,
"author": "Chris",
"author_id": 4624,
"author_profile": "https://Stackoverflow.com/users/4624",
"pm_score": 4,
"selected": true,
"text": "<p>I beleive \"position\" is a reserved word.</p>\n\n<p>Try...</p>\n\n<p>INSERT into tblExcel (ename, [position], phone, email) VALUES (...</p>\n\n<p><a href=\"http://office.microsoft.com/en-us/access/HP010322491033.aspx\" rel=\"nofollow noreferrer\">Reserved Words</a></p>\n"
}
] | 2008/09/05 | [
"https://Stackoverflow.com/questions/46907",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4252/"
] | ```
INSERT INTO tblExcel (ename, position, phone, email) VALUES ('Burton, Andrew', 'Web Developer / Network Assistant', '876-9259', '[email protected]')
```
I've got an Access table that has five fields: id, ename, position, phone, and email...each one is plain text field with 50 characters, save for position which is 255 and id which is an autoincrement field. I'm using a VB.NET to read data from an Excel table, which gets pushed into a simple class that's used to fill out that query. I do the same thing with two other tables, whose data are pulled from a DB2 table and a MySQL table through. The other two work, but this simple INSERT loop keeps failing, so I don't think it's my "InsertNoExe" function that handles all the OleDb stuff.
So, um, does that query, any of the field titles, etc. look bogus? I can post other bits of code if anyone wants to see it.
**EDIT:** Fixed. I wasn't sure if the wide image counted as a Stack Overflow bug or not, which is why I left it.
**EDIT 2:** I'm dense. I use a try...catch to see the bogus query, and don't even check the ex.messsage. Gah.
```
INSERT INTO tblExcel (ename, position, phone, email) VALUES ('Burton, Andrew', 'Web Developer / Network Assistant', '876-9259', '[email protected]')
at System.Data.OleDb.OleDbCommand.ExecuteCommandTextErrorHandling(Int32 hr)
at System.Data.OleDb.OleDbCommand.ExecuteCommandTextForSingleResult(tagDBPARAMS dbParams, Object& executeResult)
at System.Data.OleDb.OleDbCommand.ExecuteCommandText(Object& executeResult)
at System.Data.OleDb.OleDbCommand.ExecuteCommand(CommandBehavior behavior, Object& executeResult)
at System.Data.OleDb.OleDbCommand.ExecuteReaderInternal(CommandBehavior behavior, String method)
at System.Data.OleDb.OleDbCommand.ExecuteNonQuery()
at EmployeeList.EmployeeDatabase.ExeNonQuery(String sql) in C:\andy\html\code\vb\EmployeeList\EmployeeDatabase.vb:line 263
Syntax error in INSERT INTO statement.
```
**EDIT 3:** Thank you, Chris. | I beleive "position" is a reserved word.
Try...
INSERT into tblExcel (ename, [position], phone, email) VALUES (...
[Reserved Words](http://office.microsoft.com/en-us/access/HP010322491033.aspx) |
46,909 | <p>I have a situation where I might have multiple instances of a program running at once, and it's important that just one specific function not be executing in more than one of these instances at once.</p>
<p>Is this the proper way to use a mutex to prevent this from happening?</p>
<pre><code>lock (this.GetType()) {
_log.Info("Doing Sync");
DoSync();
_log.Info("Sync Completed");
}
</code></pre>
| [
{
"answer_id": 46928,
"author": "Jonathan Webb",
"author_id": 1518,
"author_profile": "https://Stackoverflow.com/users/1518",
"pm_score": 3,
"selected": false,
"text": "<p>TheSeeker is correct.</p>\n\n<p>Jeff Richter's advice in <a href=\"http://books.google.com/books?id=C-V_AAAACAAJ&dq=clr+via+c%23&ei=k6TBSPjYOomUzATIs8WIDg\" rel=\"nofollow noreferrer\">Clr Via C#</a> (p638-9) on locking is to create a private object specifically for the purpose of being locked.</p>\n\n<pre><code>private Object _lock = new Object();\n\n// usage\nlock( _lock )\n{\n // thread-safe code here..\n}\n</code></pre>\n\n<p>This works because _lock cannot be locked by anything outside the current class.</p>\n\n<p>EDIT: this is applicable to threads executing within a single process. @David Mohundro's answer is correct for inter-process locking.</p>\n"
},
{
"answer_id": 46952,
"author": "David Mohundro",
"author_id": 4570,
"author_profile": "https://Stackoverflow.com/users/4570",
"pm_score": 5,
"selected": true,
"text": "<p>You said multiple instances of one application, so we're talking about two program.exe's running, right? The lock statement won't lock across multiple programs, just within the program. If you want a true Mutex, look at the <a href=\"https://learn.microsoft.com/en-us/dotnet/api/system.threading.mutex\" rel=\"nofollow noreferrer\">System.Threading.Mutex</a> object.</p>\n\n<p>Here is a usage example:</p>\n\n<pre><code>bool createdNew;\nusing (Mutex mtx = new Mutex(false, \"MyAwesomeMutex\", out createdNew))\n{\n try\n {\n mtx.WaitOne();\n\n MessageBox.Show(\"Click OK to release the mutex.\");\n }\n finally\n {\n mtx.ReleaseMutex();\n }\n}\n</code></pre>\n\n<p>The createdNew variable will let you know whether or not it was created the first time. It only tells you if it has been created, though. If you want to acquire the lock, you need to call WaitOne and then call ReleaseMutex to release it. If you just want to see if you created a Mutex, just constructing it is fine.</p>\n"
}
] | 2008/09/05 | [
"https://Stackoverflow.com/questions/46909",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1512/"
] | I have a situation where I might have multiple instances of a program running at once, and it's important that just one specific function not be executing in more than one of these instances at once.
Is this the proper way to use a mutex to prevent this from happening?
```
lock (this.GetType()) {
_log.Info("Doing Sync");
DoSync();
_log.Info("Sync Completed");
}
``` | You said multiple instances of one application, so we're talking about two program.exe's running, right? The lock statement won't lock across multiple programs, just within the program. If you want a true Mutex, look at the [System.Threading.Mutex](https://learn.microsoft.com/en-us/dotnet/api/system.threading.mutex) object.
Here is a usage example:
```
bool createdNew;
using (Mutex mtx = new Mutex(false, "MyAwesomeMutex", out createdNew))
{
try
{
mtx.WaitOne();
MessageBox.Show("Click OK to release the mutex.");
}
finally
{
mtx.ReleaseMutex();
}
}
```
The createdNew variable will let you know whether or not it was created the first time. It only tells you if it has been created, though. If you want to acquire the lock, you need to call WaitOne and then call ReleaseMutex to release it. If you just want to see if you created a Mutex, just constructing it is fine. |
46,915 | <p>As a follow up to this question: <a href="https://stackoverflow.com/questions/46873/developing-a-online-exam-application-how-do-i-prevent-cheaters">Developing a online exam application, how do I prevent cheaters?</a></p>
<p>Can I detect when Flex application looses its focus? that is if a user has clicked onto another application or opened a browser tab?</p>
<p>I read this: <a href="http://blog.flexmonkeypatches.com/2007/12/07/detecting-when-a-flex-application-loses-focus/" rel="nofollow noreferrer">Detecting when a Flex application loses focus</a> but was not very clear...</p>
| [
{
"answer_id": 47161,
"author": "Raleigh Buckner",
"author_id": 1153,
"author_profile": "https://Stackoverflow.com/users/1153",
"pm_score": 4,
"selected": true,
"text": "<p>The key part of the code at that link is the </p>\n\n<pre><code>systemManager.stage.addEventListener(Event.DEACTIVATE,deactivate);\n</code></pre>\n\n<p>The Flash player send outs activate and deactivate events when the focus enters and leaves the player. All you need to do is create a listenr for them and react appropriately.</p>\n\n<p>A more clear example of how to use to the activate and deactivate events can be seen at <a href=\"http://blog.flexexamples.com/2008/02/29/determining-if-a-flex-application-has-focus-using-the-activate-and-deactivate-events/\" rel=\"noreferrer\">blog.flexaxamples.com</a>. </p>\n\n<p>Also, it looks like the activate and deactivate events have trouble in some browsers. <a href=\"http://www.moock.org/blog/archives/000252.html\" rel=\"noreferrer\">Colin Moock has more info on that here.</a></p>\n"
},
{
"answer_id": 158463,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 0,
"selected": false,
"text": "<p>This will work to detect when the Flex windows loses focus, but to detect when the window regains focus without having to actually click on the flex app requires an update in the HTML wrapper, correct? Something like:</p>\n\n<pre><code><script language=\"JavaScript\" type=\"text/javascript\">\n<!--\n// -----------------------------------------------------------------------------\n// Globals\n// Major version of Flash required\nvar requiredMajorVersion = ${version_major};\n// Minor version of Flash required\nvar requiredMinorVersion = ${version_minor};\n// Minor version of Flash required\nvar requiredRevision = ${version_revision};\n// -----------------------------------------------------------------------------\n// -->\n\n\n function onAppFocusIn()\n {\n ${application}.onAppFocusIn();\n alert(\"onAppFocusIn\");\n }\n\n</script>\n<body scroll=\"no\" onFocus=\"onAppFocusIn()\">\n</code></pre>\n\n<p>I am trying to implement this but the onAppFocusIn() function is not executing once I move back to the flex app window. When I view the source, the code is there. Does anyone know why??</p>\n\n<p>Thanks,\nAnnie</p>\n"
},
{
"answer_id": 6071245,
"author": "Preeyanka",
"author_id": 762650,
"author_profile": "https://Stackoverflow.com/users/762650",
"pm_score": 1,
"selected": false,
"text": "<p>You can add a handler for activate in the main application tag. This detects whenever the flex application comes to focus. \nEg: </p>\n\n<p><code><mx:Application xmlns:mx=\"http://www.adobe.com/2006/mxml\"\n layout=\"vertical\"\n verticalAlign=\"middle\"\n backgroundColor=\"white\"\n activate=\"activateHandler(event);\"\n deactivate=\"deactivateHandler(event);\"></code></p>\n"
},
{
"answer_id": 20466605,
"author": "Patrick",
"author_id": 2495697,
"author_profile": "https://Stackoverflow.com/users/2495697",
"pm_score": 0,
"selected": false,
"text": "<p>In Flex 4.6, this command works systemManager.stage.addEventListener(Event.DEACTIVATE, deactivate)\nbut make sure the flash app wmode is set to window (default). When the wmode was transparent, the event didn't get caught. You set the wmode in the embedded html where you put your flash app. example:</p>\n\n<pre><code><object classid=\"clsid:D27WEE-A16D-21cf-90F2-422253540410\" width=\"100%\" height=\"100%\"\nid=\"MyApp\" name=\"MyApp\" align=\"middle\">\n<param name=\"movie\" value=\"MyApp.swf?v=1.00.008\" />\n<param name=\"wmode\" value=\"transparent\"> <----- take out this\n</code></pre>\n\n<p>...</p>\n"
}
] | 2008/09/05 | [
"https://Stackoverflow.com/questions/46915",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1638/"
] | As a follow up to this question: [Developing a online exam application, how do I prevent cheaters?](https://stackoverflow.com/questions/46873/developing-a-online-exam-application-how-do-i-prevent-cheaters)
Can I detect when Flex application looses its focus? that is if a user has clicked onto another application or opened a browser tab?
I read this: [Detecting when a Flex application loses focus](http://blog.flexmonkeypatches.com/2007/12/07/detecting-when-a-flex-application-loses-focus/) but was not very clear... | The key part of the code at that link is the
```
systemManager.stage.addEventListener(Event.DEACTIVATE,deactivate);
```
The Flash player send outs activate and deactivate events when the focus enters and leaves the player. All you need to do is create a listenr for them and react appropriately.
A more clear example of how to use to the activate and deactivate events can be seen at [blog.flexaxamples.com](http://blog.flexexamples.com/2008/02/29/determining-if-a-flex-application-has-focus-using-the-activate-and-deactivate-events/).
Also, it looks like the activate and deactivate events have trouble in some browsers. [Colin Moock has more info on that here.](http://www.moock.org/blog/archives/000252.html) |
46,924 | <p>Suppose I want to implement a reasonably efficient 'keyword recognition algorithm', that is first given a list of keyword, and must then answer if another given word was in the list. </p>
<p>In an imperative language, I would store the keywords in a tree (one node per character). Then, when receiving a word to test, I would scan my tree to test if the word is a keyword.</p>
<p>I'd like to understand how such an algorithm would be coded in a functional language. How does one get the benefits of 'stateless' programming while keeping the efficiency of 'imperative' algorithms. Isn't it necessary to store the tree somewhere between the lookups if you don't want to rebuild it each time? </p>
| [
{
"answer_id": 46948,
"author": "Rob Rolnick",
"author_id": 4798,
"author_profile": "https://Stackoverflow.com/users/4798",
"pm_score": 0,
"selected": false,
"text": "<p>I imagine you'd want something like a tree with a list of children, as described <a href=\"http://csus.cs.mcgill.ca/wiki/COMP-302_(Panangaden%2C_Pientka%2C_Winter_06)_Lectures#Trees_with_a_list_of_children\" rel=\"nofollow noreferrer\">here</a>.</p>\n"
},
{
"answer_id": 47002,
"author": "Thomas Kammeyer",
"author_id": 4410,
"author_profile": "https://Stackoverflow.com/users/4410",
"pm_score": 3,
"selected": true,
"text": "<p>I think what you mean is a character per node... sort of like a simple hash tree scheme for keyword lookup. Assuming this or even another kind of tree... imagine doing something like this (in pseudo-LISP):</p>\n\n<pre><code>(defun buildtree (wordlist) ...code to build tree recursively returns the tree...)\n(define lookup (tree word) ...code to look up word using tree, returns t or nil...)\n\n(defun lookupmany (tree querylist)\n (if (eq querylist nil)\n nil\n (cons (lookup tree (car querylist)) (lookupmany tree (cdr querylist))\n )\n)\n\n(defun main (wordlist querylist) ; the main entry point\n (lookupmany (buildtree wordlist) querylist)\n)\n</code></pre>\n\n<p>if this is what you mean, this is fairly straight-forward functional programming.\nIs it really stateless? That's a matter of debate. Some people would say some\nforms of functional programming store what we normally call \"state\" on the stack.\nMoreover, Common LISP even since the first edition of the Steele book has had iterative\nconstructs, and LISP has had setq for a long, long time.</p>\n\n<p>But in the theory of programming languages, what we mean by \"stateless\" is pretty much satisfied by the idea shown here.</p>\n\n<p>I think the above is something like the arrangement you mean.</p>\n"
}
] | 2008/09/05 | [
"https://Stackoverflow.com/questions/46924",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4177/"
] | Suppose I want to implement a reasonably efficient 'keyword recognition algorithm', that is first given a list of keyword, and must then answer if another given word was in the list.
In an imperative language, I would store the keywords in a tree (one node per character). Then, when receiving a word to test, I would scan my tree to test if the word is a keyword.
I'd like to understand how such an algorithm would be coded in a functional language. How does one get the benefits of 'stateless' programming while keeping the efficiency of 'imperative' algorithms. Isn't it necessary to store the tree somewhere between the lookups if you don't want to rebuild it each time? | I think what you mean is a character per node... sort of like a simple hash tree scheme for keyword lookup. Assuming this or even another kind of tree... imagine doing something like this (in pseudo-LISP):
```
(defun buildtree (wordlist) ...code to build tree recursively returns the tree...)
(define lookup (tree word) ...code to look up word using tree, returns t or nil...)
(defun lookupmany (tree querylist)
(if (eq querylist nil)
nil
(cons (lookup tree (car querylist)) (lookupmany tree (cdr querylist))
)
)
(defun main (wordlist querylist) ; the main entry point
(lookupmany (buildtree wordlist) querylist)
)
```
if this is what you mean, this is fairly straight-forward functional programming.
Is it really stateless? That's a matter of debate. Some people would say some
forms of functional programming store what we normally call "state" on the stack.
Moreover, Common LISP even since the first edition of the Steele book has had iterative
constructs, and LISP has had setq for a long, long time.
But in the theory of programming languages, what we mean by "stateless" is pretty much satisfied by the idea shown here.
I think the above is something like the arrangement you mean. |
46,933 | <p>I'm having some inheritance issues as I've got a group of inter-related abstract classes that need to all be overridden together to create a client implementation. Ideally I would like to do something like the following:</p>
<pre><code>abstract class Animal
{
public Leg GetLeg() {...}
}
abstract class Leg { }
class Dog : Animal
{
public override DogLeg Leg() {...}
}
class DogLeg : Leg { }
</code></pre>
<p>This would allow anyone using the Dog class to automatically get DogLegs and anyone using the Animal class to get Legs. The problem is that the overridden function has to have the same type as the base class so this will not compile. I don't see why it shouldn't though, since DogLeg is implicitly castable to Leg. I know there are plenty of ways around this, but I'm more curious why this isn't possible/implemented in C#.</p>
<p><strong>EDIT</strong>: I modified this somewhat, since I'm actually using properties instead of functions in my code. </p>
<p><strong>EDIT</strong>: I changed it back to functions, because the answer only applies to that situation (covariance on the value parameter of a property's set function <strong>shouldn't</strong> work). Sorry for the fluctuations! I realize it makes a lot of the answers seem irrelevant.</p>
| [
{
"answer_id": 46935,
"author": "shsteimer",
"author_id": 292,
"author_profile": "https://Stackoverflow.com/users/292",
"pm_score": 2,
"selected": false,
"text": "<p>GetLeg() must return Leg to be an override. Your Dog class however, can still return DogLeg objects since they are a child class of Leg. clients can then cast and operate on them as doglegs.</p>\n\n<pre><code>public class ClientObj{\n public void doStuff(){\n Animal a=getAnimal();\n if(a is Dog){\n DogLeg dl = (DogLeg)a.GetLeg();\n }\n }\n}\n</code></pre>\n"
},
{
"answer_id": 46940,
"author": "Brian Leahy",
"author_id": 580,
"author_profile": "https://Stackoverflow.com/users/580",
"pm_score": 3,
"selected": false,
"text": "<p>Dog should return a Leg not a DogLeg as the return type. The actual class may be a DogLeg, but the point is to decouple so the user of Dog doesn't have to know about DogLegs, they only need to know about Legs.</p>\n\n<p>Change:</p>\n\n<pre><code>class Dog : Animal\n{\n public override DogLeg GetLeg() {...}\n}\n</code></pre>\n\n<p>to:</p>\n\n<pre><code>class Dog : Animal\n{\n public override Leg GetLeg() {...}\n}\n</code></pre>\n\n<p>Don't Do this:</p>\n\n<pre><code> if(a instanceof Dog){\n DogLeg dl = (DogLeg)a.GetLeg();\n</code></pre>\n\n<p>it defeats the purpose of programing to the abstract type.</p>\n\n<p>The reason to hide DogLeg is because the GetLeg function in the abstract class returns an Abstract Leg. If you are overriding the GetLeg you must return a Leg. Thats the point of having a method in an abstract class. To propagate that method to it's childern. If you want the users of the Dog to know about DogLegs make a method called GetDogLeg and return a DogLeg.</p>\n\n<p>If you COULD do as the question asker wants to, then every user of Animal would need to know about ALL animals.</p>\n"
},
{
"answer_id": 46942,
"author": "Luke",
"author_id": 327,
"author_profile": "https://Stackoverflow.com/users/327",
"pm_score": 0,
"selected": false,
"text": "<p>Right, I understand that I can just cast, but that means the client has to know that Dogs have DogLegs. What I'm wondering is if there are technical reasons why this isn't possible, given that an implicit conversion exists.</p>\n"
},
{
"answer_id": 46946,
"author": "Apocalisp",
"author_id": 3434,
"author_profile": "https://Stackoverflow.com/users/3434",
"pm_score": 5,
"selected": true,
"text": "<p>The short answer is that GetLeg is invariant in its return type. The long answer can be found here: <a href=\"http://blogs.msdn.com/ericlippert/archive/2007/10/16/covariance-and-contravariance-in-c-part-one.aspx\" rel=\"noreferrer\">Covariance and contravariance</a></p>\n\n<p>I'd like to add that while inheritance is usually the first abstraction tool that most developers pull out of their toolbox, it is almost always possible to use composition instead. Composition is slightly more work for the API developer, but makes the API more useful for its consumers.</p>\n"
},
{
"answer_id": 46950,
"author": "shsteimer",
"author_id": 292,
"author_profile": "https://Stackoverflow.com/users/292",
"pm_score": 0,
"selected": false,
"text": "<p>@Brian Leahy\nObviously if you are only operating on it as a Leg there is no need or reason to cast. But if there is some DogLeg or Dog specific behavior, there are sometimes reasons that the cast is neccessary.</p>\n"
},
{
"answer_id": 46951,
"author": "ben",
"author_id": 4607,
"author_profile": "https://Stackoverflow.com/users/4607",
"pm_score": 2,
"selected": false,
"text": "<p>The concept that is causing you problems is described at <a href=\"http://en.wikipedia.org/wiki/Covariance_and_contravariance_(computer_science)\" rel=\"nofollow noreferrer\">http://en.wikipedia.org/wiki/Covariance_and_contravariance_(computer_science)</a></p>\n"
},
{
"answer_id": 46959,
"author": "shsteimer",
"author_id": 292,
"author_profile": "https://Stackoverflow.com/users/292",
"pm_score": 0,
"selected": false,
"text": "<p>@Luke</p>\n\n<p>I think your perhaps misunderstanding inheritance. Dog.GetLeg() will return a DogLeg object. </p>\n\n<pre><code>public class Dog{\n public Leg GetLeg(){\n DogLeg dl = new DogLeg(super.GetLeg());\n //set dogleg specific properties\n }\n}\n\n\n Animal a = getDog();\n Leg l = a.GetLeg();\n l.kick();\n</code></pre>\n\n<p>the actual method called will be Dog.GetLeg(); and DogLeg.Kick() (I'm assuming a method Leg.kick() exists) there for, the declared return type being DogLeg is unneccessary, because that is what returned, even if the return type for Dog.GetLeg() is Leg.</p>\n"
},
{
"answer_id": 46962,
"author": "Keith Sirmons",
"author_id": 1048,
"author_profile": "https://Stackoverflow.com/users/1048",
"pm_score": 0,
"selected": false,
"text": "<p>You could also return the interface ILeg that both Leg and/or DogLeg implement.</p>\n"
},
{
"answer_id": 46964,
"author": "FlySwat",
"author_id": 1965,
"author_profile": "https://Stackoverflow.com/users/1965",
"pm_score": 2,
"selected": false,
"text": "<pre><code>abstract class Animal\n{\n public virtual Leg GetLeg ()\n}\n\nabstract class Leg { }\n\nclass Dog : Animal\n{\n public override Leg GetLeg () { return new DogLeg(); }\n}\n\nclass DogLeg : Leg { void Hump(); }\n</code></pre>\n\n<p>Do it like this, then you can leverage the abstraction in your client:</p>\n\n<pre><code>Leg myleg = myDog.GetLeg();\n</code></pre>\n\n<p>Then if you need to, you can cast it:</p>\n\n<pre><code>if (myleg is DogLeg) { ((DogLeg)myLeg).Hump()); }\n</code></pre>\n\n<p>Totally contrived, but the point is so you can do this:</p>\n\n<pre><code>foreach (Animal a in animals)\n{\n a.GetLeg().SomeMethodThatIsOnAllLegs();\n}\n</code></pre>\n\n<p>While still retaining the ability to have a special Hump method on Doglegs.</p>\n"
},
{
"answer_id": 46967,
"author": "Tom Hawtin - tackline",
"author_id": 4725,
"author_profile": "https://Stackoverflow.com/users/4725",
"pm_score": 1,
"selected": false,
"text": "<p>Perhaps it's easier to see the problem with an example:</p>\n\n<pre><code>Animal dog = new Dog();\ndog.SetLeg(new CatLeg());\n</code></pre>\n\n<p>Now that should compile if you're Dog compiled, but we probably don't want such a mutant.</p>\n\n<p>A related issue is should Dog[] be an Animal[], or IList<Dog> an IList<Animal>?</p>\n"
},
{
"answer_id": 46968,
"author": "Nir",
"author_id": 3509,
"author_profile": "https://Stackoverflow.com/users/3509",
"pm_score": 0,
"selected": false,
"text": "<p>The important thing to remember is that you can use a derived type every place you use the base type (you can pass Dog to any method/property/field/variable that expects Animal)</p>\n\n<p>Let's take this function:</p>\n\n<pre><code>public void AddLeg(Animal a)\n{\n a.Leg = new Leg();\n}\n</code></pre>\n\n<p>A perfectly valid function, now let's call the function like that:</p>\n\n<pre><code>AddLeg(new Dog());\n</code></pre>\n\n<p>If the property Dog.Leg isn't of type Leg the AddLeg function suddenly contains an error and cannot be compiled.</p>\n"
},
{
"answer_id": 46980,
"author": "serg10",
"author_id": 1853,
"author_profile": "https://Stackoverflow.com/users/1853",
"pm_score": 2,
"selected": false,
"text": "<p>Not that it is much use, but it is maybe interesting to note the Java does support covariant returns, and so this would work exactly how you hoped. Except obviously that Java doesn't have properties ;)</p>\n"
},
{
"answer_id": 47010,
"author": "vextasy",
"author_id": 3010,
"author_profile": "https://Stackoverflow.com/users/3010",
"pm_score": 4,
"selected": false,
"text": "<p>Clearly, you'll need a cast if you're \noperating on a broken DogLeg. </p>\n"
},
{
"answer_id": 47256,
"author": "Mark Cidade",
"author_id": 1659,
"author_profile": "https://Stackoverflow.com/users/1659",
"pm_score": 2,
"selected": false,
"text": "<p>You can use generics and interfaces to implement that in C#:</p>\n\n<pre><code>abstract class Leg { }\n\ninterface IAnimal { Leg GetLeg(); }\n\nabstract class Animal<TLeg> : IAnimal where TLeg : Leg\n { public abstract TLeg GetLeg();\n Leg IAnimal.GetLeg() { return this.GetLeg(); }\n }\n\nclass Dog : Animal<Dog.DogLeg>\n { public class DogLeg : Leg { }\n public override DogLeg GetLeg() { return new DogLeg();}\n } \n</code></pre>\n"
},
{
"answer_id": 47300,
"author": "Ivan Hamilton",
"author_id": 4729,
"author_profile": "https://Stackoverflow.com/users/4729",
"pm_score": 2,
"selected": false,
"text": "<p>It is a perfectly valid desire to have the signature an overriding method have a return type that is a subtype of the return type in the overridden method (<em>phew</em>). After all, they are run-time type compatible.</p>\n<p>But C# does not yet support "covariant return types" in overridden methods (unlike C++ [1998] & Java [2004]).</p>\n<p>You'll need to work around and make do for the foreseeable future, as Eric Lippert stated in <a href=\"http://blogs.msdn.com/ericlippert/archive/2008/05/07/covariance-and-contravariance-part-twelve-to-infinity-but-not-beyond.aspx\" rel=\"nofollow noreferrer\">his blog</a>\n[June 19, 2008]:</p>\n<blockquote>\n<p>That kind of variance is called "return type covariance".</p>\n<p>we have no plans to implement that kind of variance in C#.</p>\n</blockquote>\n"
},
{
"answer_id": 68313,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 0,
"selected": false,
"text": "<p>You can achieve what you want by using a generic with an appropriate constraint, like the following:</p>\n\n<pre><code>abstract class Animal<LegType> where LegType : Leg\n{\n public abstract LegType GetLeg();\n}\n\nabstract class Leg { }\n\nclass Dog : Animal<DogLeg>\n{\n public override DogLeg GetLeg()\n {\n return new DogLeg();\n }\n}\n\nclass DogLeg : Leg { }\n</code></pre>\n"
},
{
"answer_id": 73720,
"author": "munificent",
"author_id": 9457,
"author_profile": "https://Stackoverflow.com/users/9457",
"pm_score": 1,
"selected": false,
"text": "<p>C# has explicit interface implementations to address just this issue:</p>\n\n<pre><code>abstract class Leg { }\nclass DogLeg : Leg { }\n\ninterface IAnimal\n{\n Leg GetLeg();\n}\n\nclass Dog : IAnimal\n{\n public override DogLeg GetLeg() { /* */ }\n\n Leg IAnimal.GetLeg() { return GetLeg(); }\n}\n</code></pre>\n\n<p>If you have a Dog through a reference of type Dog, then calling GetLeg() will return a DogLeg. If you have the same object, but the reference is of type IAnimal, then it will return a Leg.</p>\n"
}
] | 2008/09/05 | [
"https://Stackoverflow.com/questions/46933",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/327/"
] | I'm having some inheritance issues as I've got a group of inter-related abstract classes that need to all be overridden together to create a client implementation. Ideally I would like to do something like the following:
```
abstract class Animal
{
public Leg GetLeg() {...}
}
abstract class Leg { }
class Dog : Animal
{
public override DogLeg Leg() {...}
}
class DogLeg : Leg { }
```
This would allow anyone using the Dog class to automatically get DogLegs and anyone using the Animal class to get Legs. The problem is that the overridden function has to have the same type as the base class so this will not compile. I don't see why it shouldn't though, since DogLeg is implicitly castable to Leg. I know there are plenty of ways around this, but I'm more curious why this isn't possible/implemented in C#.
**EDIT**: I modified this somewhat, since I'm actually using properties instead of functions in my code.
**EDIT**: I changed it back to functions, because the answer only applies to that situation (covariance on the value parameter of a property's set function **shouldn't** work). Sorry for the fluctuations! I realize it makes a lot of the answers seem irrelevant. | The short answer is that GetLeg is invariant in its return type. The long answer can be found here: [Covariance and contravariance](http://blogs.msdn.com/ericlippert/archive/2007/10/16/covariance-and-contravariance-in-c-part-one.aspx)
I'd like to add that while inheritance is usually the first abstraction tool that most developers pull out of their toolbox, it is almost always possible to use composition instead. Composition is slightly more work for the API developer, but makes the API more useful for its consumers. |
46,981 | <p>I have an Image control with it's source bound to a property on an object(string url to an image). After making a service call, i update the data object with a new URL. The exception is thrown after it leaves my code, after invoking the PropertyChanged event.</p>
<p>The data structure and the service logic are all done in a core dll that has no knowledge of the UI. How do I sync up with the UI thread when i cant access a Dispatcher? </p>
<p>PS: Accessing Application.Current.RootVisual in order to get at a Dispatcher is not a solution because the root visual is on a different thread(causing the exact exception i need to prevent). </p>
<p>PPS: This only is a problem with the image control, binding to any other ui element, the cross thread issue is handled for you.</p>
| [
{
"answer_id": 47294,
"author": "Jonathan Parker",
"author_id": 4504,
"author_profile": "https://Stackoverflow.com/users/4504",
"pm_score": 1,
"selected": false,
"text": "<p>Have you tried implementing <a href=\"http://msdn.microsoft.com/en-us/library/system.componentmodel.inotifypropertychanged.aspx\" rel=\"nofollow noreferrer\">INotifyPropertyChanged</a>?</p>\n"
},
{
"answer_id": 404706,
"author": "Rob Fonseca-Ensor",
"author_id": 21433,
"author_profile": "https://Stackoverflow.com/users/21433",
"pm_score": 0,
"selected": false,
"text": "<p>The property getter for RootVisual on the Application class has a thread check which causes that exception. I got around this by storing the root visual's dispatcher in my own property in my App.xaml.cs:</p>\n\n<pre><code>public static Dispatcher RootVisualDispatcher { get; set; }\n\nprivate void Application_Startup(object sender, StartupEventArgs e)\n{\n this.RootVisual = new Page();\n RootVisualDispatcher = RootVisual.Dispatcher;\n}\n</code></pre>\n\n<p>If you then call BeginInvoke on App.RootVisualDispatcher rather than Application.Current.RootVisual.Dispatcher you shouldn't get this exception.</p>\n"
},
{
"answer_id": 1261531,
"author": "Brandon ",
"author_id": 151840,
"author_profile": "https://Stackoverflow.com/users/151840",
"pm_score": 0,
"selected": false,
"text": "<p>I ran into a similar issue to this, but this was in windows forms:</p>\n\n<p>I have a class that has it's own thread, updating statistics about another process, there is a control in my UI that is databound to this object. I was running into cross-thread call issues, here is how I resolved it:</p>\n\n<pre><code>Form m_MainWindow; //Reference to the main window of my application\nprotected virtual void OnPropertyChanged(string propertyName)\n{\n if(PropertyChanged != null)\n if(m_MainWindow.InvokeRequired)\n m_MainWindow.Invoke(\n PropertyChanged, this, new PropertyChangedEventArgs(propertyName);\n else\n PropertyChanged(this, new PropertyChangedEventArgs(propertyName);\n}\n</code></pre>\n\n<p>This seems to work great, if anyone has suggestions, please let me know.</p>\n"
},
{
"answer_id": 1929825,
"author": "Phil",
"author_id": 138757,
"author_profile": "https://Stackoverflow.com/users/138757",
"pm_score": 3,
"selected": false,
"text": "<pre><code>System.Windows.Deployment.Current.Dispatcher.BeginInvoke(() => {...});\n</code></pre>\n\n<p>Also look <a href=\"https://stackoverflow.com/questions/1924408/invalid-cross-thread-access-issue/1925827#1925827\">here.</a></p>\n"
},
{
"answer_id": 16381177,
"author": "Doitdotnet",
"author_id": 2348909,
"author_profile": "https://Stackoverflow.com/users/2348909",
"pm_score": 0,
"selected": false,
"text": "<p>When ever we want to update UI related items that action should happen in the UI thread else you will get an invalid cross thread access exception</p>\n\n<pre><code>Deployment.Current.Dispatcher.BeginInvoke( () =>\n\n{\n\nUpdateUI(); // DO the actions in the function Update UI\n\n});\n\npublic void UpdateUI()\n\n{\n\n//to do :Update UI elements here\n\n}\n</code></pre>\n"
},
{
"answer_id": 18246948,
"author": "Jignesh.Raj",
"author_id": 1928157,
"author_profile": "https://Stackoverflow.com/users/1928157",
"pm_score": 0,
"selected": false,
"text": "<p>The <code>INotifyPropertyChanged</code> interface is used to notify clients, typically binding clients, that a property value has changed.</p>\n\n<p>For example, consider a Person object with a property called FirstName. To provide generic property-change notification, the Person type implements the INotifyPropertyChanged interface and raises a PropertyChanged event when FirstName is changed.</p>\n\n<p>For change notification to occur in a binding between a bound client and a data source, your bound type should either:</p>\n\n<p>Implement the <code>INotifyPropertyChanged</code> interface (preferred).</p>\n\n<p>Provide a change event for each property of the bound type.</p>\n\n<p>Do not do both.</p>\n\n<p><strong>Example:</strong></p>\n\n<pre><code>using System;\nusing System.Collections.Generic;\nusing System.ComponentModel;\nusing System.Drawing;\nusing System.Runtime.CompilerServices;\nusing System.Windows.Forms;\n\n// Change the namespace to the project name. \nnamespace TestNotifyPropertyChangedCS\n{\n // This form demonstrates using a BindingSource to bind \n // a list to a DataGridView control. The list does not \n // raise change notifications. However the DemoCustomer type \n // in the list does. \n public partial class Form1 : Form\n {\n // This button causes the value of a list element to be changed. \n private Button changeItemBtn = new Button();\n\n // This DataGridView control displays the contents of the list. \n private DataGridView customersDataGridView = new DataGridView();\n\n // This BindingSource binds the list to the DataGridView control. \n private BindingSource customersBindingSource = new BindingSource();\n\n public Form1()\n {\n InitializeComponent();\n\n // Set up the \"Change Item\" button.\n this.changeItemBtn.Text = \"Change Item\";\n this.changeItemBtn.Dock = DockStyle.Bottom;\n this.changeItemBtn.Click +=\n new EventHandler(changeItemBtn_Click);\n this.Controls.Add(this.changeItemBtn);\n\n // Set up the DataGridView.\n customersDataGridView.Dock = DockStyle.Top;\n this.Controls.Add(customersDataGridView);\n\n this.Size = new Size(400, 200);\n }\n\n private void Form1_Load(object sender, EventArgs e)\n {\n // Create and populate the list of DemoCustomer objects \n // which will supply data to the DataGridView.\n BindingList<DemoCustomer> customerList = new BindingList<DemoCustomer>();\n customerList.Add(DemoCustomer.CreateNewCustomer());\n customerList.Add(DemoCustomer.CreateNewCustomer());\n customerList.Add(DemoCustomer.CreateNewCustomer());\n\n // Bind the list to the BindingSource. \n this.customersBindingSource.DataSource = customerList;\n\n // Attach the BindingSource to the DataGridView. \n this.customersDataGridView.DataSource =\n this.customersBindingSource;\n\n }\n\n // Change the value of the CompanyName property for the first \n // item in the list when the \"Change Item\" button is clicked.\n void changeItemBtn_Click(object sender, EventArgs e)\n {\n // Get a reference to the list from the BindingSource.\n BindingList<DemoCustomer> customerList =\n this.customersBindingSource.DataSource as BindingList<DemoCustomer>;\n\n // Change the value of the CompanyName property for the \n // first item in the list.\n customerList[0].CustomerName = \"Tailspin Toys\";\n customerList[0].PhoneNumber = \"(708)555-0150\";\n }\n\n }\n\n // This is a simple customer class that \n // implements the IPropertyChange interface. \n public class DemoCustomer : INotifyPropertyChanged\n {\n // These fields hold the values for the public properties. \n private Guid idValue = Guid.NewGuid();\n private string customerNameValue = String.Empty;\n private string phoneNumberValue = String.Empty;\n\n public event PropertyChangedEventHandler PropertyChanged;\n\n // This method is called by the Set accessor of each property. \n // The CallerMemberName attribute that is applied to the optional propertyName \n // parameter causes the property name of the caller to be substituted as an argument. \n private void NotifyPropertyChanged([CallerMemberName] String propertyName = \"\")\n {\n if (PropertyChanged != null)\n {\n PropertyChanged(this, new PropertyChangedEventArgs(propertyName));\n }\n }\n\n // The constructor is private to enforce the factory pattern. \n private DemoCustomer()\n {\n customerNameValue = \"Customer\";\n phoneNumberValue = \"(312)555-0100\";\n }\n\n // This is the public factory method. \n public static DemoCustomer CreateNewCustomer()\n {\n return new DemoCustomer();\n }\n\n // This property represents an ID, suitable \n // for use as a primary key in a database. \n public Guid ID\n {\n get\n {\n return this.idValue;\n }\n }\n\n public string CustomerName\n {\n get\n {\n return this.customerNameValue;\n }\n\n set\n {\n if (value != this.customerNameValue)\n {\n this.customerNameValue = value;\n NotifyPropertyChanged();\n }\n }\n }\n\n public string PhoneNumber\n {\n get\n {\n return this.phoneNumberValue;\n }\n\n set\n {\n if (value != this.phoneNumberValue)\n {\n this.phoneNumberValue = value;\n NotifyPropertyChanged();\n }\n }\n }\n }\n}\n</code></pre>\n"
}
] | 2008/09/05 | [
"https://Stackoverflow.com/questions/46981",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/580/"
] | I have an Image control with it's source bound to a property on an object(string url to an image). After making a service call, i update the data object with a new URL. The exception is thrown after it leaves my code, after invoking the PropertyChanged event.
The data structure and the service logic are all done in a core dll that has no knowledge of the UI. How do I sync up with the UI thread when i cant access a Dispatcher?
PS: Accessing Application.Current.RootVisual in order to get at a Dispatcher is not a solution because the root visual is on a different thread(causing the exact exception i need to prevent).
PPS: This only is a problem with the image control, binding to any other ui element, the cross thread issue is handled for you. | ```
System.Windows.Deployment.Current.Dispatcher.BeginInvoke(() => {...});
```
Also look [here.](https://stackoverflow.com/questions/1924408/invalid-cross-thread-access-issue/1925827#1925827) |
47,007 | <p>A question that occasionally arises is what is the best way to determine the changelist that you last synced to in Perforce. This is often needed for things like injecting the changelist number into the revision info by the automatic build system.</p>
| [
{
"answer_id": 47012,
"author": "Greg Whitfield",
"author_id": 2102,
"author_profile": "https://Stackoverflow.com/users/2102",
"pm_score": 5,
"selected": false,
"text": "<p>Just to answer this myself in keeping with Jeff's suggestion of using Stackoverflow as a place to keep technical snippets....</p>\n\n<p>From the command line use:</p>\n\n<pre><code>p4 changes -m1 @<clientname>\n</code></pre>\n\n<p>And just replace with the name of your client spec. This will produce output of the form:</p>\n\n<pre><code>Change 12345 on 2008/08/21 by joebloggs@mainline-client '....top line of description...'\n</code></pre>\n\n<p>Which is easily parsed to extract the changelist number.</p>\n"
},
{
"answer_id": 47019,
"author": "erickson",
"author_id": 3474,
"author_profile": "https://Stackoverflow.com/users/3474",
"pm_score": 3,
"selected": false,
"text": "<p>For a serious build (one that is being prepared for testing), explicitly specify the desired label or changelist number, <em>sync to label,</em> and imbed it in build artifacts. </p>\n\n<p>If a changelist (or label) is not given, use <code>p4 counter change</code> to get the current change number, and record it. But you still need to <em>sync everything using that change number.</em></p>\n\n<p>I don't think you can achieve exactly what you want, because in general, an entire workspace isn't synced to a particular changelist number. One can explicitly sync some files to older revisions, and then a single changelist number is meaningless. That's why a fresh <code>sync</code> is required to ensure that a single changelist number accurately represents the code version.</p>\n\n<hr>\n\n<p>Regarding the comments: Yes, my answer is intended for use by configuration managers preparing a build to give to QA. Our developers don't normally sync as part of a build; they do a build prior to submitting—so that they can make sure their changes don't break the build or tests. In that context, we don't bother to embed a repository label.</p>\n\n<p>With your approach, you are making the assumption that your whole workspace was synced to head at the time of your last changelist submission, and that changelist included all of your open files. It's too easy to be mistaken in those assumptions, hard to detect, and horribly expensive in terms of lost time. On the other hand, solving the problem is easy, with no drawbacks. And because a changelist number can be explicitly specified, it doesn't matter what revision you need or how quickly the codebase is changing.</p>\n"
},
{
"answer_id": 256455,
"author": "Syeberman",
"author_id": 14576,
"author_profile": "https://Stackoverflow.com/users/14576",
"pm_score": 8,
"selected": true,
"text": "<p>I recommend the opposite for automatic build systems: you should first get the latest changelist from the server using:</p>\n<pre><code>p4 changes -s submitted -m1\n</code></pre>\n<p>then sync to that change and record it in the revision info. The reason is as follows. Although <a href=\"https://portal.perforce.com/s/article/3458\" rel=\"nofollow noreferrer\">Perforce recommends the following</a> to determine the changelist to which the workspace is synced:</p>\n<pre><code>p4 changes -m1 @clientname\n</code></pre>\n<p>they note a few gotchas:</p>\n<ul>\n<li>This only works if you have not submitted anything from the workspace in question.</li>\n<li>It is also possible that a client workspace is not synced to any specific changelist.</li>\n</ul>\n<p>and there's an additional gotcha they don't mention:</p>\n<ul>\n<li>If the highest changelist to which the sync occured strictly deleted files from the workspace, the next-highest changelist will be reported (unless it, too, strictly deleted files).</li>\n</ul>\n<p>If you must sync first and record later, Perforce recommends running the following command to determine if you've been bit by the above gotchas; it should indicate nothing was synced or removed:</p>\n<pre><code>p4 sync -n @changelist_number\n</code></pre>\n"
},
{
"answer_id": 668631,
"author": "eel ghEEz",
"author_id": 80772,
"author_profile": "https://Stackoverflow.com/users/80772",
"pm_score": 4,
"selected": false,
"text": "<p>You may try finding the maximum change number in the output of the \"p4 files\" command. The working directory should not contain post-sync commits, though. This is just a tad better than </p>\n\n<pre><code>p4 changes -m1 \"./...#have\"\n</code></pre>\n\n<p>as the latter seems to run on the server and may fail on big source trees due to \"MaxResults\" limits.</p>\n\n<pre><code>$ p4 changes -m1 \"./...#have\"\nRequest too large (over 850000); see 'p4 help maxresults'.\n\n$ p4 -G files \"./...#have\" | python c:/cygwin/usr/local/bin/p4lastchange.py\nFiles: 266948\n2427657\n</code></pre>\n\n<p>where p4lastchange.py is based on the code from the <a href=\"http://www.perforce.com/perforce/conferences/us/2005/presentations/GoldstonePresentation.pdf\" rel=\"noreferrer\">Using P4G.py From the Command Line</a> presentation by J.T.Goldstone, Kodak Information Network/Ofoto, April 15, 2005.</p>\n\n<pre><code>#! /usr/bin/env python\nimport sys, os, marshal\n\nif os.name == \"nt\":\n # Disable newline translation in Windows. Other operating systems do not\n # translate file contents.\n import msvcrt\n msvcrt.setmode( sys.stdin.fileno(), os.O_BINARY )\n\nlastcl = 0\nnum = 0\ntry:\n while 1:\n dict = marshal.load(sys.stdin)\n num = num + 1\n for key in dict.keys():\n # print \"%s: %s\" % (key,dict[key])\n if key == \"change\":\n cl = int(dict[key])\n if cl > lastcl:\n lastcl = cl\nexcept EOFError:\n pass\nprint \"Files: %s\" % num\nprint lastcl\n</code></pre>\n"
},
{
"answer_id": 687228,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 2,
"selected": false,
"text": "<p>The best I've found so far is to do your sync to whatever changelist you want to build and then use changes -m1 //...#have to get the current local changelist (revision).</p>\n\n<p>p4 sync @CHANGELIST_NUM\np4 changes -m1 //...#have | awk '{print $2}'</p>\n\n<p>Gives you the changelist number that you can the use wherever you want. I am currently looking for a simpler way than p4 changes -m1 //...#have.</p>\n"
},
{
"answer_id": 10182886,
"author": "gmaghera",
"author_id": 209849,
"author_profile": "https://Stackoverflow.com/users/209849",
"pm_score": 3,
"selected": false,
"text": "<p>You could also use the cstat command:</p>\n\n<p>p4 help cstat</p>\n\n<pre><code>cstat -- Dump change/sync status for current client\n\np4 cstat [files...]\n\nLists changes that are needed, had or partially synced in the current\nclient. The output is returned in tagged format, similar to the fstat\ncommand.\n\nThe fields that cstat displays are:\n\n change changelist number\n status 'have', 'need' or 'partial'\n</code></pre>\n"
},
{
"answer_id": 10937773,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 2,
"selected": false,
"text": "<p>For the whole depot (not just your workspace/client)</p>\n\n<pre><code>p4 counter change\n</code></pre>\n\n<p>does the job, just telling the last changelist.</p>\n"
},
{
"answer_id": 14938631,
"author": "Assaf Mendelson",
"author_id": 1547734,
"author_profile": "https://Stackoverflow.com/users/1547734",
"pm_score": 0,
"selected": false,
"text": "<p>I am not sure if you got the answer you needed but I had a similar problem. The goal was to write in our logger the specific version of the project. The problem was that while we are making our own makefile, the overall build system is controlled by our configuration management. This means that all the solutions which say \"sync to something then do something\" don't really work and I didn't want to manually change the version whenever we commit (a sure source for errors). \nThe solution (which is actually hinted in some of the answers above) is this:\nin our makefile, I do p4 changes -m1 \"./...#have\"\nThe result for this is Change change_number on date by user@client 'msg'\nI simply create the message into a string which is printed by the logger (the change number is the important element but the other is also useful to quickly decide if a certain version contains changes you know you made yourself without going to perforce to check).\nHope this helps.</p>\n"
},
{
"answer_id": 33069657,
"author": "gsf",
"author_id": 1870790,
"author_profile": "https://Stackoverflow.com/users/1870790",
"pm_score": 4,
"selected": false,
"text": "<p><code>p4 changes -m1 @clientname</code> which is the \"recommended\" way to do it for my client takes about 10 minutes</p>\n\n<p>this is what I use:</p>\n\n<pre><code>p4 cstat ...#have | grep change | awk '$3 > x { x = $3 };END { print x }'\n</code></pre>\n\n<p>for the same client takes 2.1 seconds </p>\n"
},
{
"answer_id": 36795719,
"author": "user31389",
"author_id": 2436687,
"author_profile": "https://Stackoverflow.com/users/2436687",
"pm_score": 4,
"selected": false,
"text": "<p>If you are using P4V you can do this graphically:</p>\n\n<ul>\n<li>In the Dashboard tab (View->Dashboard) choose a folder and you will see a list of changelists that the folder isn't yet updated with. Note the lowest number (in the highest row).</li>\n<li>Make sure that in the Workspace Tree you have selected the same folder as previously in the Dashboard. Then go to the History tab (View->History) and scroll down to the number noted previously. The number just below that number is the number of your current changelist.</li>\n</ul>\n"
}
] | 2008/09/05 | [
"https://Stackoverflow.com/questions/47007",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2102/"
] | A question that occasionally arises is what is the best way to determine the changelist that you last synced to in Perforce. This is often needed for things like injecting the changelist number into the revision info by the automatic build system. | I recommend the opposite for automatic build systems: you should first get the latest changelist from the server using:
```
p4 changes -s submitted -m1
```
then sync to that change and record it in the revision info. The reason is as follows. Although [Perforce recommends the following](https://portal.perforce.com/s/article/3458) to determine the changelist to which the workspace is synced:
```
p4 changes -m1 @clientname
```
they note a few gotchas:
* This only works if you have not submitted anything from the workspace in question.
* It is also possible that a client workspace is not synced to any specific changelist.
and there's an additional gotcha they don't mention:
* If the highest changelist to which the sync occured strictly deleted files from the workspace, the next-highest changelist will be reported (unless it, too, strictly deleted files).
If you must sync first and record later, Perforce recommends running the following command to determine if you've been bit by the above gotchas; it should indicate nothing was synced or removed:
```
p4 sync -n @changelist_number
``` |
47,022 | <p>I've somehow managed to get an SVN repository into a bad state. I've moved a directory and now I can't commit it in its new location.</p>
<p>As far as <code>svn status</code> is concerned, the directory is unknown (the name of the directory is <code>type</code>).</p>
<pre>
$ svn status
? type
</pre>
<p>When I try to add the directory, the server says it already exists.</p>
<pre>
$ svn add type
svn: warning: 'type' is already under version control
</pre>
<p>If I try to update the directory, it's gone again.</p>
<pre>
$ svn update type
svn: '.' is not under version control
</pre>
<p>If I try to commit it, the server complains that it's old parent directory no longer exists.</p>
<pre>
$ svn commit type -m "Moving type"
svn: Commit failed (details follow):
svn: '/prior/trunk/src/nyu/prior/cvc3/theorem_prover/expression' path not found
</pre>
<p>To add to the mystery, the contents of the directory are marked as modified.</p>
<pre>
$ svn status type
A + type
M + type/IntegerType.java
M + type/BooleanType.java
M + type/Type.java
M + type/RationalRangeType.java
M + type/RationalType.java
M + type/IntegerRangeType.java
</pre>
<p>If I try to update from within the directory, I get this.</p>
<pre>
$ cd type
$ svn update
svn: Two top-level reports with no target
</pre>
<p>Committing from within the directory gives the same <code>path not found</code> error as above.</p>
<p>What's going on and how do I fix it?</p>
<p>EDIT: @Rob Oxspring caught me out: I got too aggressive moving things around in Eclipse.</p>
<p>UPDATE: I'm accepting @Rob Oxspring's answer of "don't do that/just start over" and taking his advice. I'd still be interested if anybody could tell me: (a) what the above error messages <em>mean</em> precisely and (b) how to actually <em>fix</em> the problem.</p>
| [
{
"answer_id": 47030,
"author": "crashmstr",
"author_id": 1441,
"author_profile": "https://Stackoverflow.com/users/1441",
"pm_score": 2,
"selected": false,
"text": "<p>Did you start by just copying/moving the directory with OS commands, or did you start with SVN stuff? If you just copied the files via the OS, you would still have hidden folders containing SVN information pointing to the old location.</p>\n"
},
{
"answer_id": 47042,
"author": "BCS",
"author_id": 1343,
"author_profile": "https://Stackoverflow.com/users/1343",
"pm_score": 3,
"selected": false,
"text": "<p>The easy way to fix many SVN errors is to move the whole directory away via the OS, update to get another clean copy of it and then merge in anything you changed with some other tool, WinMerge or the like.</p>\n\n<p>After that, you can do whatever you were trying to do, but do it correctly :).</p>\n"
},
{
"answer_id": 47051,
"author": "Andreas Kraft",
"author_id": 4799,
"author_profile": "https://Stackoverflow.com/users/4799",
"pm_score": 0,
"selected": false,
"text": "<p>My experience is that sometimes the local copy gets out of sync with the repository. I usually solve this by going up the local directory tree, starting from the directory with the problem and try to do do cleanup and update with each step.</p>\n"
},
{
"answer_id": 47098,
"author": "Rob Oxspring",
"author_id": 1867,
"author_profile": "https://Stackoverflow.com/users/1867",
"pm_score": 5,
"selected": true,
"text": "<p>It looks to me like <code>type</code> was created by some Subversion-aware copy command, then moved into the current directory using a Subversion-unaware copy. In my experience, this sort of thing typically occurs when package refactoring operations have been chained together in Eclipse without commits in between. Typically, Subversion doesn't handle it well when you copy/move a locally copied/moved file or folder, although I think version 1.5 may handle it better.</p>\n\n<p>To avoid this in the future, commit between such steps. If you'd like to hide the intervening commits then I'd recommend doing the multi-step refactoring on a branch and then merging the changes back into the mainline in that single commit you were after.</p>\n\n<p>If it's not too much work, then I'd recommend getting back to a clean working copy and redoing your changes, committing after each step. If you're happy to lose the history, i.e. allowing the new <code>IntegerType.java</code> to not be linked at all to the old <code>IntegerType.java</code>, then you could take the approach suggested by BCS:</p>\n\n<ul>\n<li>Move your changed files into some temporary location, stripping out any <code>.svn</code> directories</li>\n<li>Update your working copy into a clean working state</li>\n<li>Copy your changes back to where you want them to be</li>\n<li>Commit the resulting working copy</li>\n</ul>\n"
},
{
"answer_id": 47185,
"author": "Matt Sheppard",
"author_id": 797,
"author_profile": "https://Stackoverflow.com/users/797",
"pm_score": 1,
"selected": false,
"text": "<p>I'd suggest, to delete (outside subversionso with rm or similar), the directory above test, and then running svn update there.</p>\n\n<p>That is, if you don't want to get a whole new working copy as others have suggested, which might be the safest approach.</p>\n"
},
{
"answer_id": 1891622,
"author": "déo",
"author_id": 102550,
"author_profile": "https://Stackoverflow.com/users/102550",
"pm_score": 0,
"selected": false,
"text": "<p>What happened is that you made a checkout of a folder, then locally 'svn add'ed and/or modified something to/in this folder, but before you have committed your changes, the original folder was moved (or deleted) from the SVN repository.</p>\n\n<p>All you need to do is to switch your current checkout to the new location in the SVN repository. So, supposing you have a checkout of the foo folder from path/to/folder1/foo, and that foo was moved to path/to/foo, you just need to run:</p>\n\n<pre><code>$ svn switch path/to/foo\n</code></pre>\n\n<p>That's it... ;-)</p>\n"
},
{
"answer_id": 6645011,
"author": "BlueRaja - Danny Pflughoeft",
"author_id": 238419,
"author_profile": "https://Stackoverflow.com/users/238419",
"pm_score": 1,
"selected": false,
"text": "<p>I just had this same problem. I fixed it by deleting the <code>.svn</code> folder from the affected folder.</p>\n"
}
] | 2008/09/05 | [
"https://Stackoverflow.com/questions/47022",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1412/"
] | I've somehow managed to get an SVN repository into a bad state. I've moved a directory and now I can't commit it in its new location.
As far as `svn status` is concerned, the directory is unknown (the name of the directory is `type`).
```
$ svn status
? type
```
When I try to add the directory, the server says it already exists.
```
$ svn add type
svn: warning: 'type' is already under version control
```
If I try to update the directory, it's gone again.
```
$ svn update type
svn: '.' is not under version control
```
If I try to commit it, the server complains that it's old parent directory no longer exists.
```
$ svn commit type -m "Moving type"
svn: Commit failed (details follow):
svn: '/prior/trunk/src/nyu/prior/cvc3/theorem_prover/expression' path not found
```
To add to the mystery, the contents of the directory are marked as modified.
```
$ svn status type
A + type
M + type/IntegerType.java
M + type/BooleanType.java
M + type/Type.java
M + type/RationalRangeType.java
M + type/RationalType.java
M + type/IntegerRangeType.java
```
If I try to update from within the directory, I get this.
```
$ cd type
$ svn update
svn: Two top-level reports with no target
```
Committing from within the directory gives the same `path not found` error as above.
What's going on and how do I fix it?
EDIT: @Rob Oxspring caught me out: I got too aggressive moving things around in Eclipse.
UPDATE: I'm accepting @Rob Oxspring's answer of "don't do that/just start over" and taking his advice. I'd still be interested if anybody could tell me: (a) what the above error messages *mean* precisely and (b) how to actually *fix* the problem. | It looks to me like `type` was created by some Subversion-aware copy command, then moved into the current directory using a Subversion-unaware copy. In my experience, this sort of thing typically occurs when package refactoring operations have been chained together in Eclipse without commits in between. Typically, Subversion doesn't handle it well when you copy/move a locally copied/moved file or folder, although I think version 1.5 may handle it better.
To avoid this in the future, commit between such steps. If you'd like to hide the intervening commits then I'd recommend doing the multi-step refactoring on a branch and then merging the changes back into the mainline in that single commit you were after.
If it's not too much work, then I'd recommend getting back to a clean working copy and redoing your changes, committing after each step. If you're happy to lose the history, i.e. allowing the new `IntegerType.java` to not be linked at all to the old `IntegerType.java`, then you could take the approach suggested by BCS:
* Move your changed files into some temporary location, stripping out any `.svn` directories
* Update your working copy into a clean working state
* Copy your changes back to where you want them to be
* Commit the resulting working copy |
47,045 | <p>Printf got added to Java with the 1.5 release but I can't seem to find how to send the output to a string rather than a file (which is what sprintf does in C). Does anyone know how to do this? </p>
| [
{
"answer_id": 47049,
"author": "Eugene Yokota",
"author_id": 3827,
"author_profile": "https://Stackoverflow.com/users/3827",
"pm_score": 10,
"selected": true,
"text": "<pre><code>// Store the formatted string in 'result'\nString result = String.format(\"%4d\", i * j);\n\n// Write the result to standard output\nSystem.out.println( result );\n</code></pre>\n\n<p>See <a href=\"http://docs.oracle.com/javase/7/docs/api/java/lang/String.html#format(java.lang.String,%20java.lang.Object...)\" rel=\"noreferrer\">format</a> and its <a href=\"http://docs.oracle.com/javase/7/docs/api/java/util/Formatter.html#syntax\" rel=\"noreferrer\">syntax</a></p>\n"
},
{
"answer_id": 198356,
"author": "FlySwat",
"author_id": 1965,
"author_profile": "https://Stackoverflow.com/users/1965",
"pm_score": 5,
"selected": false,
"text": "<p>Strings are immutable types. You cannot modify them, only return new string instances.</p>\n\n<p>Because of that, formatting with an instance method makes little sense, as it would have to be called like:</p>\n\n<pre><code>String formatted = \"%s: %s\".format(key, value);\n</code></pre>\n\n<p>The original Java authors (and .NET authors) decided that a static method made more sense in this situation, as you are not modifying the target, but instead calling a format method and passing in an input string.</p>\n\n<p>Here is an example of why <code>format()</code> would be dumb as an instance method. In .NET (and probably in Java), <code>Replace()</code> is an instance method.</p>\n\n<p>You can do this:</p>\n\n<pre><code> \"I Like Wine\".Replace(\"Wine\",\"Beer\");\n</code></pre>\n\n<p>However, nothing happens, because strings are immutable. <code>Replace()</code> tries to return a new string, but it is assigned to nothing.</p>\n\n<p>This causes lots of common rookie mistakes like:</p>\n\n<pre><code>inputText.Replace(\" \", \"%20\");\n</code></pre>\n\n<p>Again, nothing happens, instead you have to do:</p>\n\n<pre><code>inputText = inputText.Replace(\" \",\"%20\");\n</code></pre>\n\n<p>Now, if you understand that strings are immutable, that makes perfect sense. If you don't, then you are just confused. The proper place for <code>Replace()</code> would be where <code>format()</code> is, as a static method of <code>String</code>:</p>\n\n<pre><code> inputText = String.Replace(inputText, \" \", \"%20\");\n</code></pre>\n\n<p>Now there is no question as to what's going on.</p>\n\n<p>The real question is, why did the authors of these frameworks decide that one should be an instance method, and the other static? In my opinion, both are more elegantly expressed as static methods.</p>\n\n<p>Regardless of your opinion, the truth is that you are less prone to make a mistake using the static version, and the code is easier to understand (No Hidden Gotchas).</p>\n\n<p>Of course there are some methods that are perfect as instance methods, take String.Length()</p>\n\n<pre><code>int length = \"123\".Length();\n</code></pre>\n\n<p>In this situation, it's obvious we are not trying to modify \"123\", we are just inspecting it, and returning its length. This is a perfect candidate for an instance method.</p>\n\n<p>My simple rules for Instance Methods on Immutable Objects:</p>\n\n<ul>\n<li>If you need to return a new instance of the same type, use a static method.</li>\n<li>Otherwise, use an instance method.</li>\n</ul>\n"
},
{
"answer_id": 31405706,
"author": "догонят",
"author_id": 3199507,
"author_profile": "https://Stackoverflow.com/users/3199507",
"pm_score": 2,
"selected": false,
"text": "<p>Both solutions workto simulate printf, but in a different way.\nFor instance, to convert a value to a hex string, you have the 2 following solutions:</p>\n\n<ul>\n<li><p>with <code>format()</code>, closest to <code>sprintf()</code>:</p>\n\n<pre><code>final static String HexChars = \"0123456789abcdef\";\n\npublic static String getHexQuad(long v) {\n String ret;\n if(v > 0xffff) ret = getHexQuad(v >> 16); else ret = \"\";\n ret += String.format(\"%c%c%c%c\",\n HexChars.charAt((int) ((v >> 12) & 0x0f)),\n HexChars.charAt((int) ((v >> 8) & 0x0f)),\n HexChars.charAt((int) ((v >> 4) & 0x0f)),\n HexChars.charAt((int) ( v & 0x0f)));\n return ret;\n}\n</code></pre></li>\n<li><p>with <code>replace(char oldchar , char newchar)</code>, somewhat faster but pretty limited:</p>\n\n<pre><code> ...\n ret += \"ABCD\".\n replace('A', HexChars.charAt((int) ((v >> 12) & 0x0f))).\n replace('B', HexChars.charAt((int) ((v >> 8) & 0x0f))).\n replace('C', HexChars.charAt((int) ((v >> 4) & 0x0f))).\n replace('D', HexChars.charAt((int) ( v & 0x0f)));\n ...\n</code></pre></li>\n<li><p>There is a third solution consisting of just adding the char to <code>ret</code> one by one (char are numbers that <i>add to each other</i>!) such as in:</p>\n\n<pre><code>...\nret += HexChars.charAt((int) ((v >> 12) & 0x0f)));\nret += HexChars.charAt((int) ((v >> 8) & 0x0f)));\n...\n</code></pre></li>\n</ul>\n\n<p>...but that'd be <strong>really</strong> ugly.</p>\n"
},
{
"answer_id": 57359951,
"author": "armagedescu",
"author_id": 4582948,
"author_profile": "https://Stackoverflow.com/users/4582948",
"pm_score": 1,
"selected": false,
"text": "<p>You can do a printf with a PrintStream to anything that is an OutputStream.\nSomehow like this, printing into a string stream:</p>\n<pre><code>PrintStream ps = new PrintStream(baos);\nps.printf("there is a %s from %d %s", "hello", 3, "friends");\nSystem.out.println(baos.toString());\n</code></pre>\n<p>This outputs following text <strong>there is a hello from 3 friends</strong>\nThe string stream can be created like this ByteArrayOutputStream:</p>\n<pre><code>ByteArrayOutputStream baos = new ByteArrayOutputStream();\n</code></pre>\n<p>You can accumulate many formats:</p>\n<pre><code>PrintStream ps = new PrintStream(baos);\nps.printf("there is a %s from %d %s ", "hello", 3, "friends");\nps.printf("there are %d % from a %", 2, "kisses", "girl");\nSystem.out.println(baos.toString());\n</code></pre>\n<p>This outputs <strong>there is a hello from 3 friends there are 2 kisses from a girl</strong><br />\nCall reset on ByteArrayOutputStream to generate a clean new string</p>\n<pre><code>ps.printf("there is a %s from %d %s", "flip", 5, "haters");\nbaos.reset(); //need reset to write new string\nps.printf("there are %d % from a %", 2, "kisses", "girl");\nSystem.out.println(baos.toString());\n</code></pre>\n<p>The output will be <strong>there are 2 kisses from a girl</strong></p>\n"
},
{
"answer_id": 62706682,
"author": "andreoss",
"author_id": 12462444,
"author_profile": "https://Stackoverflow.com/users/12462444",
"pm_score": 3,
"selected": false,
"text": "<p>Since Java 13 you have <code>formatted</code> <a href=\"https://docs.oracle.com/en/java/javase/14/docs/api/java.base/java/lang/String.html#formatted(java.lang.Object...)\" rel=\"noreferrer\">1</a> method on String, which was added along with text blocks as a preview feature <a href=\"https://docs.oracle.com/en/java/javase/13/text_blocks/index.html#string-formattedobject...-args\" rel=\"noreferrer\">2</a>.\nYou can use it instead of <code>String.format()</code></p>\n<pre class=\"lang-java prettyprint-override\"><code>Assertions.assertEquals(\n "%s %d %.3f".formatted("foo", 123, 7.89),\n "foo 123 7.890"\n);\n</code></pre>\n"
}
] | 2008/09/05 | [
"https://Stackoverflow.com/questions/47045",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4498/"
] | Printf got added to Java with the 1.5 release but I can't seem to find how to send the output to a string rather than a file (which is what sprintf does in C). Does anyone know how to do this? | ```
// Store the formatted string in 'result'
String result = String.format("%4d", i * j);
// Write the result to standard output
System.out.println( result );
```
See [format](http://docs.oracle.com/javase/7/docs/api/java/lang/String.html#format(java.lang.String,%20java.lang.Object...)) and its [syntax](http://docs.oracle.com/javase/7/docs/api/java/util/Formatter.html#syntax) |
47,052 | <p>I'm looking to convert a SQL like statement on the fly to the equivalent regex i.e. </p>
<pre><code>LIKE '%this%'
LIKE 'Sm_th'
LIKE '[C-P]arsen'
</code></pre>
<p>What's the best approach to doing this?</p>
<p>P.S. I'm looking to do this on the .Net Framework (C#).</p>
| [
{
"answer_id": 47075,
"author": "Eugene Yokota",
"author_id": 3827,
"author_profile": "https://Stackoverflow.com/users/3827",
"pm_score": -1,
"selected": false,
"text": "<p>I found a Perl module called <a href=\"http://search.cpan.org/dist/Regexp-Wildcards/lib/Regexp/Wildcards.pm\" rel=\"nofollow noreferrer\">Regexp::Wildcards</a>. You can try to port it or try Perl.NET. I have a feeling you can write something up yourself too.</p>\n"
},
{
"answer_id": 47088,
"author": "Martin",
"author_id": 2581,
"author_profile": "https://Stackoverflow.com/users/2581",
"pm_score": 2,
"selected": false,
"text": "<p>From your example above, I would attack it like this (I speak in general terms because I do not know C#):</p>\n\n<p>Break it apart by <strong>LIKE '...'</strong>, put the <strong>...</strong> pieces into an array.\nReplace unescaped <strong>%</strong> signs by <strong>.*</strong>, underscores by ., and in this case the <strong>[C-P]arsen</strong> translates directly into regex.</p>\n\n<p>Join the array pieces back together with a pipe, and wrap the result in parentheses, and standard regex bits.</p>\n\n<p>The result would be:</p>\n\n<pre><code>/^(.*this.*|Sm.th|[C-P]arsen)$/\n</code></pre>\n\n<p>The most important thing here is to be wary of all the ways you can escape data, and which wildcards translate to which regular expressions.</p>\n\n<pre><code>% becomes .*\n_ becomes .\n</code></pre>\n"
},
{
"answer_id": 13180223,
"author": "Nathan Baulch",
"author_id": 8799,
"author_profile": "https://Stackoverflow.com/users/8799",
"pm_score": 4,
"selected": true,
"text": "<p>The following Regex converts an SQL like pattern into a Regex pattern with the help of a <a href=\"http://msdn.microsoft.com/en-us/library/system.text.regularexpressions.matchevaluator.aspx\" rel=\"nofollow noreferrer\"><code>MatchEvaluator</code></a> delegate. It correctly handles square bracket blocks and escapes special Regex characters.</p>\n<pre><code>string regexPattern = "^" + Regex.Replace(\n likePattern,\n @"[%_]|\\[[^]]*\\]|[^%_[]+",\n match =>\n {\n if (match.Value == "%")\n {\n return ".*";\n }\n if (match.Value == "_")\n {\n return ".";\n }\n if (match.Value.StartsWith("[") && match.Value.EndsWith("]"))\n {\n return match.Value;\n }\n return Regex.Escape(match.Value);\n }) + "$";\n</code></pre>\n"
},
{
"answer_id": 29847510,
"author": "TheEadie",
"author_id": 1930030,
"author_profile": "https://Stackoverflow.com/users/1930030",
"pm_score": 2,
"selected": false,
"text": "<p>In addition to @Nathan-Baulch's solution you can use the code below to also handle the case where a custom escape character has been defined using the <code>LIKE '!%' ESCAPE '!'</code> syntax.</p>\n\n<pre><code> public Regex ConvertSqlLikeToDotNetRegex(string regex, char? likeEscape = null)\n {\n var pattern = string.Format(@\"\n {0}[%_]|\n [%_]|\n \\[[^]]*\\]|\n [^%_[{0}]+\n \", likeEscape);\n\n var regexPattern = Regex.Replace(\n regex,\n pattern,\n ConvertWildcardsAndEscapedCharacters,\n RegexOptions.IgnorePatternWhitespace);\n\n regexPattern = \"^\" + regexPattern + \"$\";\n\n return new Regex(regexPattern,\n !m_CaseSensitive ? RegexOptions.IgnoreCase : RegexOptions.None);\n }\n\n private string ConvertWildcardsAndEscapedCharacters(Match match)\n {\n // Wildcards\n switch (match.Value)\n {\n case \"%\":\n return \".*\";\n case \"_\":\n return \".\";\n }\n\n // Remove SQL defined escape characters from C# regex\n if (StartsWithEscapeCharacter(match.Value, likeEscape))\n {\n return match.Value.Remove(0, 1);\n }\n\n // Pass anything contained in []s straight through \n // (These have the same behaviour in SQL LIKE Regex and C# Regex)\n if (StartsAndEndsWithSquareBrackets(match.Value))\n {\n return match.Value;\n }\n\n return Regex.Escape(match.Value);\n }\n\n private static bool StartsAndEndsWithSquareBrackets(string text)\n {\n return text.StartsWith(\"[\", StringComparison.Ordinal) &&\n text.EndsWith(\"]\", StringComparison.Ordinal);\n }\n\n private bool StartsWithEscapeCharacter(string text, char? likeEscape)\n {\n return (likeEscape != null) &&\n text.StartsWith(likeEscape.ToString(), StringComparison.Ordinal);\n }\n</code></pre>\n"
}
] | 2008/09/05 | [
"https://Stackoverflow.com/questions/47052",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4843/"
] | I'm looking to convert a SQL like statement on the fly to the equivalent regex i.e.
```
LIKE '%this%'
LIKE 'Sm_th'
LIKE '[C-P]arsen'
```
What's the best approach to doing this?
P.S. I'm looking to do this on the .Net Framework (C#). | The following Regex converts an SQL like pattern into a Regex pattern with the help of a [`MatchEvaluator`](http://msdn.microsoft.com/en-us/library/system.text.regularexpressions.matchevaluator.aspx) delegate. It correctly handles square bracket blocks and escapes special Regex characters.
```
string regexPattern = "^" + Regex.Replace(
likePattern,
@"[%_]|\[[^]]*\]|[^%_[]+",
match =>
{
if (match.Value == "%")
{
return ".*";
}
if (match.Value == "_")
{
return ".";
}
if (match.Value.StartsWith("[") && match.Value.EndsWith("]"))
{
return match.Value;
}
return Regex.Escape(match.Value);
}) + "$";
``` |
47,066 | <p>I am writing a C program in Linux. Commands like execv() require a path in the form of a C string. Is there a command that will return the current path in the form of a C-style string?</p>
| [
{
"answer_id": 47071,
"author": "John Millikin",
"author_id": 3560,
"author_profile": "https://Stackoverflow.com/users/3560",
"pm_score": 5,
"selected": true,
"text": "<p><a href=\"http://www.opengroup.org/onlinepubs/009695399/functions/getcwd.html\" rel=\"nofollow noreferrer\">getcwd()</a>:</p>\n\n<blockquote>\n <h3><em>SYNOPSIS</em></h3>\n\n<pre><code>#include <unistd.h>\n\nchar *getcwd(char *buf, size_t size);\n</code></pre>\n \n <h3><em>DESCRIPTION</em></h3>\n \n <p>The <em>getcwd()</em> function shall place an absolute pathname of the current working directory in the array pointed to by <em>buf, and return buf</em>. The pathname copied to the array shall contain no components that are symbolic links. The <em>size</em> argument is the size in bytes of the character array pointed to by the <em>buf</em> argument. If <em>buf</em> is a null pointer, the behavior of getcwd() is unspecified.</p>\n \n <h3><em>RETURN VALUE</em></h3>\n \n <p>Upon successful completion, <em>getcwd()</em> shall return the <em>buf</em> argument. Otherwise, <em>getcwd()</em> shall return a null pointer and set <em>errno</em> to indicate the error. The contents of the array pointed to by <em>buf</em> are then undefined....</p>\n</blockquote>\n"
},
{
"answer_id": 47073,
"author": "Tanj",
"author_id": 4275,
"author_profile": "https://Stackoverflow.com/users/4275",
"pm_score": -1,
"selected": false,
"text": "<p>You need to grab the environment variable PWD (present working directory).</p>\n<p>I'm not sure what the library it is in, but it is a standard Linux header.</p>\n<p>I was thinking of <a href=\"http://www.opengroup.org/onlinepubs/000095399/functions/getenv.html\" rel=\"nofollow noreferrer\">getenv()</a> which would help if you also need to run system commands and need the various bin paths located in PATH.</p>\n"
},
{
"answer_id": 47074,
"author": "Andreas Kraft",
"author_id": 4799,
"author_profile": "https://Stackoverflow.com/users/4799",
"pm_score": 2,
"selected": false,
"text": "<p>This is <em>not</em> ANSI C:</p>\n\n<pre><code>#include <unistd.h>\n\nchar path[MAXPATHLEN];\ngetcwd(path, MAXPATHLEN);\nprintf(\"pwd -> %s\\n\", path);\n</code></pre>\n"
},
{
"answer_id": 47081,
"author": "Commodore Jaeger",
"author_id": 4659,
"author_profile": "https://Stackoverflow.com/users/4659",
"pm_score": 3,
"selected": false,
"text": "<p>The <strong>path</strong> argument to execv() is the path to the application you wish to execute, not the current working directory (which will be returned by getcwd()) or the shell search path (which will be returned by getenv(\"PATH\")).</p>\n\n<p>Depending on what you're doing, you may get more mileage out of the system() function in the C library rather than the lower-level exec() family.</p>\n"
},
{
"answer_id": 47090,
"author": "Paige Ruten",
"author_id": 813,
"author_profile": "https://Stackoverflow.com/users/813",
"pm_score": 0,
"selected": false,
"text": "<p>If the path can be a relative path, you should be able to use '.' or './' as the path. I'm not sure if it will work, but you could try it.</p>\n"
}
] | 2008/09/05 | [
"https://Stackoverflow.com/questions/47066",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/159/"
] | I am writing a C program in Linux. Commands like execv() require a path in the form of a C string. Is there a command that will return the current path in the form of a C-style string? | [getcwd()](http://www.opengroup.org/onlinepubs/009695399/functions/getcwd.html):
>
> ### *SYNOPSIS*
>
>
>
> ```
> #include <unistd.h>
>
> char *getcwd(char *buf, size_t size);
>
> ```
>
> ### *DESCRIPTION*
>
>
> The *getcwd()* function shall place an absolute pathname of the current working directory in the array pointed to by *buf, and return buf*. The pathname copied to the array shall contain no components that are symbolic links. The *size* argument is the size in bytes of the character array pointed to by the *buf* argument. If *buf* is a null pointer, the behavior of getcwd() is unspecified.
>
>
> ### *RETURN VALUE*
>
>
> Upon successful completion, *getcwd()* shall return the *buf* argument. Otherwise, *getcwd()* shall return a null pointer and set *errno* to indicate the error. The contents of the array pointed to by *buf* are then undefined....
>
>
> |
47,078 | <p>We are currently using the ExtJS tree view in an application - a requirement has arisen requiring a user to select multiple nodes (which the tree view supports currently through a pluggable selection model) - but you can not then drag the multiple selections to another part of the tree.</p>
<p>Does anyone know of an ajax control (commercial or non-commercial) that supports multiple-selection drag / drop - or a example of enabling this functionality in ExtJS?</p>
| [
{
"answer_id": 48901,
"author": "Candidasa",
"author_id": 5010,
"author_profile": "https://Stackoverflow.com/users/5010",
"pm_score": 2,
"selected": false,
"text": "<p>Check out this post in the ExtJS forum that details how you can enable multi-select in a Javascript tree.</p>\n\n<p><a href=\"http://extjs.com/forum/showthread.php?t=28115\" rel=\"nofollow noreferrer\">http://extjs.com/forum/showthread.php?t=28115</a></p>\n"
},
{
"answer_id": 2681839,
"author": "Fabian Loibl",
"author_id": 322145,
"author_profile": "https://Stackoverflow.com/users/322145",
"pm_score": 0,
"selected": false,
"text": "<p>Ha i just asked the exact same question in their forum... want to acheive the goal without using the Custom User-Extension tough.</p>\n\n<p><a href=\"http://www.extjs.com/forum/showthread.php?97463-3.2.0-Treepanel-MultiSelectionModel-and-Dragdrop&p=459962\" rel=\"nofollow noreferrer\">http://www.extjs.com/forum/showthread.php?97463-3.2.0-Treepanel-MultiSelectionModel-and-Dragdrop&p=459962</a></p>\n\n<p>Just for reference.</p>\n\n<p>Regards,\nFabian Loibl</p>\n"
},
{
"answer_id": 3988952,
"author": "Benoit",
"author_id": 483194,
"author_profile": "https://Stackoverflow.com/users/483194",
"pm_score": 2,
"selected": true,
"text": "<p>Got the same issue. I just found the solution : </p>\n\n<pre><code>..new Ext.tree.TreePanel({\n ...\n selModel : new Ext.tree.MultiSelectionModel()\n ...\n})\n</code></pre>\n"
}
] | 2008/09/05 | [
"https://Stackoverflow.com/questions/47078",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4843/"
] | We are currently using the ExtJS tree view in an application - a requirement has arisen requiring a user to select multiple nodes (which the tree view supports currently through a pluggable selection model) - but you can not then drag the multiple selections to another part of the tree.
Does anyone know of an ajax control (commercial or non-commercial) that supports multiple-selection drag / drop - or a example of enabling this functionality in ExtJS? | Got the same issue. I just found the solution :
```
..new Ext.tree.TreePanel({
...
selModel : new Ext.tree.MultiSelectionModel()
...
})
``` |
47,089 | <p>About 6 months ago I rolled out a site where every request needed to be over https. The only way at the time I could find to ensure that every request to a page was over https was to check it in the page load event. If the request was not over http I would response.redirect("<a href="https://example.com" rel="noreferrer">https://example.com</a>")</p>
<p>Is there a better way -- ideally some setting in the web.config?</p>
| [
{
"answer_id": 47095,
"author": "John Boker",
"author_id": 2847,
"author_profile": "https://Stackoverflow.com/users/2847",
"pm_score": 9,
"selected": true,
"text": "<p>Please use <a href=\"https://en.wikipedia.org/wiki/HTTP_Strict_Transport_Security\" rel=\"noreferrer\">HSTS</a> (HTTP Strict Transport Security)</p>\n\n<p>from <a href=\"http://www.hanselman.com/blog/HowToEnableHTTPStrictTransportSecurityHSTSInIIS7.aspx\" rel=\"noreferrer\">http://www.hanselman.com/blog/HowToEnableHTTPStrictTransportSecurityHSTSInIIS7.aspx</a></p>\n\n<pre><code><?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<configuration>\n <system.webServer>\n <rewrite>\n <rules>\n <rule name=\"HTTP to HTTPS redirect\" stopProcessing=\"true\">\n <match url=\"(.*)\" />\n <conditions>\n <add input=\"{HTTPS}\" pattern=\"off\" ignoreCase=\"true\" />\n </conditions>\n <action type=\"Redirect\" url=\"https://{HTTP_HOST}/{R:1}\"\n redirectType=\"Permanent\" />\n </rule>\n </rules>\n <outboundRules>\n <rule name=\"Add Strict-Transport-Security when HTTPS\" enabled=\"true\">\n <match serverVariable=\"RESPONSE_Strict_Transport_Security\"\n pattern=\".*\" />\n <conditions>\n <add input=\"{HTTPS}\" pattern=\"on\" ignoreCase=\"true\" />\n </conditions>\n <action type=\"Rewrite\" value=\"max-age=31536000\" />\n </rule>\n </outboundRules>\n </rewrite>\n </system.webServer>\n</configuration>\n</code></pre>\n\n<p><strong>Original Answer</strong> (replaced with the above on 4 December 2015)</p>\n\n<p>basically</p>\n\n<pre><code>protected void Application_BeginRequest(Object sender, EventArgs e)\n{\n if (HttpContext.Current.Request.IsSecureConnection.Equals(false) && HttpContext.Current.Request.IsLocal.Equals(false))\n {\n Response.Redirect(\"https://\" + Request.ServerVariables[\"HTTP_HOST\"]\n+ HttpContext.Current.Request.RawUrl);\n }\n}\n</code></pre>\n\n<p>that would go in the global.asax.cs (or global.asax.vb)</p>\n\n<p>i dont know of a way to specify it in the web.config</p>\n"
},
{
"answer_id": 47110,
"author": "FlySwat",
"author_id": 1965,
"author_profile": "https://Stackoverflow.com/users/1965",
"pm_score": 4,
"selected": false,
"text": "<p>If you are unable to set this up in IIS for whatever reason, I'd make an HTTP module that does the redirect for you:</p>\n\n<pre><code>using System;\nusing System.Web;\n\nnamespace HttpsOnly\n{\n /// <summary>\n /// Redirects the Request to HTTPS if it comes in on an insecure channel.\n /// </summary>\n public class HttpsOnlyModule : IHttpModule\n {\n public void Init(HttpApplication app)\n {\n // Note we cannot trust IsSecureConnection when \n // in a webfarm, because usually only the load balancer \n // will come in on a secure port the request will be then \n // internally redirected to local machine on a specified port.\n\n // Move this to a config file, if your behind a farm, \n // set this to the local port used internally.\n int specialPort = 443;\n\n if (!app.Context.Request.IsSecureConnection \n || app.Context.Request.Url.Port != specialPort)\n {\n app.Context.Response.Redirect(\"https://\" \n + app.Context.Request.ServerVariables[\"HTTP_HOST\"] \n + app.Context.Request.RawUrl); \n }\n }\n\n public void Dispose()\n {\n // Needed for IHttpModule\n }\n }\n}\n</code></pre>\n\n<p>Then just compile it to a DLL, add it as a reference to your project and place this in web.config:</p>\n\n<pre><code> <httpModules>\n <add name=\"HttpsOnlyModule\" type=\"HttpsOnly.HttpsOnlyModule, HttpsOnly\" />\n </httpModules>\n</code></pre>\n"
},
{
"answer_id": 2269476,
"author": "Mark",
"author_id": 18264,
"author_profile": "https://Stackoverflow.com/users/18264",
"pm_score": 7,
"selected": false,
"text": "<p>The IIS7 module will let you redirect.</p>\n\n<pre><code> <rewrite>\n <rules>\n <rule name=\"Redirect HTTP to HTTPS\" stopProcessing=\"true\">\n <match url=\"(.*)\"/>\n <conditions>\n <add input=\"{HTTPS}\" pattern=\"^OFF$\"/>\n </conditions>\n <action type=\"Redirect\" url=\"https://{HTTP_HOST}/{R:1}\" redirectType=\"SeeOther\"/>\n </rule>\n </rules>\n </rewrite>\n</code></pre>\n"
},
{
"answer_id": 4190691,
"author": "Alexander",
"author_id": 509015,
"author_profile": "https://Stackoverflow.com/users/509015",
"pm_score": 2,
"selected": false,
"text": "<p>It also depends on the brand of your balancer, for the web mux, you would need to look for http header <code>X-WebMux-SSL-termination: true</code> to figure that incoming traffic was ssl. details here: <a href=\"http://www.cainetworks.com/support/redirect2ssl.html\" rel=\"nofollow\">http://www.cainetworks.com/support/redirect2ssl.html</a></p>\n"
},
{
"answer_id": 8234498,
"author": "Troy Hunt",
"author_id": 73948,
"author_profile": "https://Stackoverflow.com/users/73948",
"pm_score": 7,
"selected": false,
"text": "<p>The other thing you can do is use <a href=\"http://en.wikipedia.org/wiki/HTTP_Strict_Transport_Security\" rel=\"noreferrer\">HSTS</a> by returning the \"Strict-Transport-Security\" header to the browser. The browser has to support this (and at present, it's primarily Chrome and Firefox that do), but it means that once set, the browser won't make requests to the site over HTTP and will instead translate them to HTTPS requests before issuing them. Try this in combination with a redirect from HTTP:</p>\n\n<pre><code>protected void Application_BeginRequest(Object sender, EventArgs e)\n{\n switch (Request.Url.Scheme)\n {\n case \"https\":\n Response.AddHeader(\"Strict-Transport-Security\", \"max-age=300\");\n break;\n case \"http\":\n var path = \"https://\" + Request.Url.Host + Request.Url.PathAndQuery;\n Response.Status = \"301 Moved Permanently\";\n Response.AddHeader(\"Location\", path);\n break;\n }\n}\n</code></pre>\n\n<p>Browsers that aren't HSTS aware will just ignore the header but will still get caught by the switch statement and sent over to HTTPS.</p>\n"
},
{
"answer_id": 13847410,
"author": "Paul Schroeder",
"author_id": 1392711,
"author_profile": "https://Stackoverflow.com/users/1392711",
"pm_score": 2,
"selected": false,
"text": "<p>For @Joe above, \"This is giving me a redirect loop. Before I added the code it worked fine. Any suggestions? – Joe Nov 8 '11 at 4:13\"</p>\n\n<p>This was happening to me as well and what I believe was happening is that there was a load balancer terminating the SSL request in front of the Web server. So, my Web site was always thinking the request was \"http\", even if the original browser requested it to be \"https\".</p>\n\n<p>I admit this is a bit hacky, but what worked for me was to implement a \"JustRedirected\" property that I could leverage to figure out the person was already redirected once. So, I test for specific conditions that warrant the redirect and, if they are met, I set this property (value stored in session) prior to the redirection. Even if the http/https conditions for redirection are met the second time, I bypass the redirection logic and reset the \"JustRedirected\" session value to false. You'll need your own conditional test logic, but here's a simple implementation of the property:</p>\n\n<pre><code> public bool JustRedirected\n {\n get\n {\n if (Session[RosadaConst.JUSTREDIRECTED] == null)\n return false;\n\n return (bool)Session[RosadaConst.JUSTREDIRECTED];\n }\n set\n {\n Session[RosadaConst.JUSTREDIRECTED] = value;\n }\n }\n</code></pre>\n"
},
{
"answer_id": 23977980,
"author": "yarg",
"author_id": 2418212,
"author_profile": "https://Stackoverflow.com/users/2418212",
"pm_score": 2,
"selected": false,
"text": "<p>If SSL support is not configurable in your site (ie. should be able to turn https on/off) - you can use the [RequireHttps] attribute on any controller / controller action you wish to secure.</p>\n"
},
{
"answer_id": 26232427,
"author": "Chandan Kumar",
"author_id": 707137,
"author_profile": "https://Stackoverflow.com/users/707137",
"pm_score": 3,
"selected": false,
"text": "<p>What you need to do is :</p>\n\n<p>1) Add a key inside of web.config, depending upon the production or stage server like below</p>\n\n<pre><code><add key=\"HttpsServer\" value=\"stage\"/>\n or\n<add key=\"HttpsServer\" value=\"prod\"/>\n</code></pre>\n\n<p>2) Inside your Global.asax file add below method.</p>\n\n<pre><code>void Application_BeginRequest(Object sender, EventArgs e)\n{\n //if (ConfigurationManager.AppSettings[\"HttpsServer\"].ToString() == \"prod\")\n if (ConfigurationManager.AppSettings[\"HttpsServer\"].ToString() == \"stage\")\n {\n if (!HttpContext.Current.Request.IsSecureConnection)\n {\n if (!Request.Url.GetLeftPart(UriPartial.Authority).Contains(\"www\"))\n {\n HttpContext.Current.Response.Redirect(\n Request.Url.GetLeftPart(UriPartial.Authority).Replace(\"http://\", \"https://www.\"), true);\n }\n else\n {\n HttpContext.Current.Response.Redirect(\n Request.Url.GetLeftPart(UriPartial.Authority).Replace(\"http://\", \"https://\"), true);\n }\n }\n }\n}\n</code></pre>\n"
},
{
"answer_id": 29126120,
"author": "Muhammad Rehan Saeed",
"author_id": 1212017,
"author_profile": "https://Stackoverflow.com/users/1212017",
"pm_score": 5,
"selected": false,
"text": "<p>For those using ASP.NET MVC. You can use the following to force SSL/TLS over HTTPS over the whole site in two ways:</p>\n\n<p><strong>The Hard Way</strong></p>\n\n<p>1 - Add the RequireHttpsAttribute to the global filters:</p>\n\n<pre><code>GlobalFilters.Filters.Add(new RequireHttpsAttribute());\n</code></pre>\n\n<p>2 - Force Anti-Forgery tokens to use SSL/TLS:</p>\n\n<pre><code>AntiForgeryConfig.RequireSsl = true;\n</code></pre>\n\n<p>3 - Require Cookies to require HTTPS by default by changing the Web.config file:</p>\n\n<pre><code><system.web>\n <httpCookies httpOnlyCookies=\"true\" requireSSL=\"true\" />\n</system.web>\n</code></pre>\n\n<p>4 - Use the NWebSec.Owin NuGet package and add the following line of code to enable Strict Transport Security accross the site. Don't forget to add the Preload directive below and submit your site to the <a href=\"https://hstspreload.appspot.com\" rel=\"noreferrer\">HSTS Preload site</a>. More information <a href=\"http://rehansaeed.com/nwebsec-asp-net-mvc-security-through-http-headers/\" rel=\"noreferrer\">here</a> and <a href=\"https://developer.mozilla.org/en-US/docs/Web/Security/HTTP_strict_transport_security\" rel=\"noreferrer\">here</a>. Note that if you are not using OWIN, there is a Web.config method you can read up on on the <a href=\"https://github.com/NWebsec\" rel=\"noreferrer\">NWebSec</a> site.</p>\n\n<pre><code>// app is your OWIN IAppBuilder app in Startup.cs\napp.UseHsts(options => options.MaxAge(days: 30).Preload());\n</code></pre>\n\n<p>5 - Use the NWebSec.Owin NuGet package and add the following line of code to enable Public Key Pinning (HPKP) across the site. More information <a href=\"http://rehansaeed.com/nwebsec-asp-net-mvc-security-through-http-headers/\" rel=\"noreferrer\">here</a> and <a href=\"https://visualstudiogallery.msdn.microsoft.com/6cf50a48-fc1e-4eaf-9e82-0b2a6705ca7d\" rel=\"noreferrer\">here</a>.</p>\n\n<pre><code>// app is your OWIN IAppBuilder app in Startup.cs\napp.UseHpkp(options => options\n .Sha256Pins(\n \"Base64 encoded SHA-256 hash of your first certificate e.g. cUPcTAZWKaASuYWhhneDttWpY3oBAkE3h2+soZS7sWs=\",\n \"Base64 encoded SHA-256 hash of your second backup certificate e.g. M8HztCzM3elUxkcjR2S5P4hhyBNf6lHkmjAHKhpGPWE=\")\n .MaxAge(days: 30));\n</code></pre>\n\n<p>6 - Include the https scheme in any URL's used. <a href=\"http://rehansaeed.com/content-security-policy-for-asp-net-mvc/\" rel=\"noreferrer\">Content Security Policy (CSP)</a> HTTP header and <a href=\"http://rehansaeed.com/subresource-integrity-taghelper-using-asp-net-core/\" rel=\"noreferrer\">Subresource Integrity (SRI)</a> do not play nice when you imit the scheme in some browsers. It is better to be explicit about HTTPS. e.g.</p>\n\n<pre><code><script src=\"https://ajax.aspnetcdn.com/ajax/bootstrap/3.3.4/bootstrap.min.js\"></script>\n</code></pre>\n\n<p><strong>The Easy Way</strong></p>\n\n<p>Use the <a href=\"https://visualstudiogallery.msdn.microsoft.com/6cf50a48-fc1e-4eaf-9e82-0b2a6705ca7d\" rel=\"noreferrer\">ASP.NET MVC Boilerplate</a> Visual Studio project template to generate a project with all of this and much more built in. You can also view the code on <a href=\"https://github.com/RehanSaeed/ASP.NET-MVC-Boilerplate\" rel=\"noreferrer\">GitHub</a>.</p>\n"
},
{
"answer_id": 33682196,
"author": "Gup3rSuR4c",
"author_id": 188081,
"author_profile": "https://Stackoverflow.com/users/188081",
"pm_score": 2,
"selected": false,
"text": "<p>I'm going to throw my two cents in. <strong>IF</strong> you have access to IIS server side, then you can force HTTPS by use of the protocol bindings. For example, you have a website called <em>Blah</em>. In IIS you'd setup two sites: <em>Blah</em>, and <em>Blah (Redirect)</em>. For <em>Blah</em> only configure the <code>HTTPS</code> binding (and <code>FTP</code> if you need to, make sure to force it over a secure connection as well). For <em>Blah (Redirect)</em> only configure the <code>HTTP</code> binding. Lastly, in the <em>HTTP Redirect</em> section for <em>Blah (Redirect)</em> make sure to set a 301 redirect to <code>https://blah.com</code>, with exact destination enabled. Make sure that each site in IIS is pointing to it's <strong>own</strong> root folder otherwise the <em>Web.config</em> will get all screwed up. Also make sure to have <code>HSTS</code> configured on your HTTPSed site so that subsequent requests by the browser are always forced to HTTPS and no redirects occur.</p>\n"
},
{
"answer_id": 35973181,
"author": "Santosh K",
"author_id": 5595669,
"author_profile": "https://Stackoverflow.com/users/5595669",
"pm_score": 1,
"selected": false,
"text": "<p>-> Simply ADD [RequireHttps] on top of the public class HomeController : Controller.</p>\n\n<p>-> And add GlobalFilters.Filters.Add(new RequireHttpsAttribute()); in 'protected void Application_Start()' method in Global.asax.cs file.</p>\n\n<p>Which forces your entire application to HTTPS.</p>\n"
},
{
"answer_id": 39425833,
"author": "noelicus",
"author_id": 865643,
"author_profile": "https://Stackoverflow.com/users/865643",
"pm_score": 2,
"selected": false,
"text": "<p>This is a fuller answer based on @Troy Hunt's. Add this function to your <code>WebApplication</code> class in <code>Global.asax.cs</code>:</p>\n\n<pre><code> protected void Application_BeginRequest(Object sender, EventArgs e)\n {\n // Allow https pages in debugging\n if (Request.IsLocal)\n {\n if (Request.Url.Scheme == \"http\")\n {\n int localSslPort = 44362; // Your local IIS port for HTTPS\n\n var path = \"https://\" + Request.Url.Host + \":\" + localSslPort + Request.Url.PathAndQuery;\n\n Response.Status = \"301 Moved Permanently\";\n Response.AddHeader(\"Location\", path);\n }\n }\n else\n {\n switch (Request.Url.Scheme)\n {\n case \"https\":\n Response.AddHeader(\"Strict-Transport-Security\", \"max-age=31536000\");\n break;\n case \"http\":\n var path = \"https://\" + Request.Url.Host + Request.Url.PathAndQuery;\n Response.Status = \"301 Moved Permanently\";\n Response.AddHeader(\"Location\", path);\n break;\n }\n }\n }\n</code></pre>\n\n<p>(To enable SSL on your local build enable it in the Properties dock for the project)</p>\n"
},
{
"answer_id": 42969197,
"author": "user7755300",
"author_id": 7755300,
"author_profile": "https://Stackoverflow.com/users/7755300",
"pm_score": 1,
"selected": false,
"text": "<p>If you are using ASP.NET Core you could try out the nuget package SaidOut.AspNetCore.HttpsWithStrictTransportSecurity.</p>\n\n<p>Then you only need to add </p>\n\n<pre><code>app.UseHttpsWithHsts(HttpsMode.AllowedRedirectForGet, configureRoutes: routeAction);\n</code></pre>\n\n<p>This will also add HTTP StrictTransportSecurity header to all request made using https scheme.</p>\n\n<p>Example code and documentation <a href=\"https://github.com/saidout/saidout-aspnetcore-httpswithstricttransportsecurity#example-code\" rel=\"nofollow noreferrer\">https://github.com/saidout/saidout-aspnetcore-httpswithstricttransportsecurity#example-code</a></p>\n"
},
{
"answer_id": 52229827,
"author": "Nour Lababidi",
"author_id": 1461144,
"author_profile": "https://Stackoverflow.com/users/1461144",
"pm_score": 2,
"selected": false,
"text": "<p>I spent sometime looking for best practice that make sense and found the following which worked perfected for me. I hope this will save you sometime. </p>\n\n<p>Using <strong>Config file</strong> (for example an asp.net website)\n<a href=\"https://blogs.msdn.microsoft.com/kaushal/2013/05/22/http-to-https-redirects-on-iis-7-x-and-higher/\" rel=\"nofollow noreferrer\">https://blogs.msdn.microsoft.com/kaushal/2013/05/22/http-to-https-redirects-on-iis-7-x-and-higher/</a></p>\n\n<p>or on your own server\n<a href=\"https://www.sslshopper.com/iis7-redirect-http-to-https.html\" rel=\"nofollow noreferrer\">https://www.sslshopper.com/iis7-redirect-http-to-https.html</a></p>\n\n<p>[SHORT ANSWER]\nSimply The code below goes inside </p>\n\n<pre><code><system.webServer> \n <rewrite>\n <rules>\n <rule name=\"HTTP/S to HTTPS Redirect\" enabled=\"true\" \n stopProcessing=\"true\">\n <match url=\"(.*)\" />\n <conditions logicalGrouping=\"MatchAny\">\n <add input=\"{SERVER_PORT_SECURE}\" pattern=\"^0$\" />\n </conditions>\n <action type=\"Redirect\" url=\"https://{HTTP_HOST}{REQUEST_URI}\" \n redirectType=\"Permanent\" />\n </rule>\n </rules>\n </rewrite>\n</code></pre>\n"
},
{
"answer_id": 53457767,
"author": "Mike",
"author_id": 914490,
"author_profile": "https://Stackoverflow.com/users/914490",
"pm_score": 3,
"selected": false,
"text": "<p>In IIS10 (Windows 10 and Server 2016), from version 1709 onwards, there is a new, simpler option for enabling HSTS for a website. </p>\n\n<p>Microsoft describe the advantages of the new approach <a href=\"https://learn.microsoft.com/en-us/iis/configuration/system.applicationhost/sites/site/hsts\" rel=\"noreferrer\">here</a>, and provide many different examples of how to implement the change programmatically or by directly editing the ApplicationHost.config file (which is like web.config but operates at the IIS level, rather than individual site level). ApplicationHost.config can be found in C:\\Windows\\System32\\inetsrv\\config.</p>\n\n<p>I've outlined two of the example methods here to avoid link rot.</p>\n\n<p><strong>Method 1</strong> - Edit the ApplicationHost.config file directly\nBetween the <code><site></code> tags, add this line:</p>\n\n<pre><code><hsts enabled=\"true\" max-age=\"31536000\" includeSubDomains=\"true\" redirectHttpToHttps=\"true\" />\n</code></pre>\n\n<p><strong>Method 2</strong> - Command Line:\nExecute the following from an elevated command prompt (i.e. right mouse on CMD and run as administrator). Remember to swap Contoso with the name of your site as it appears in IIS Manager.</p>\n\n<pre><code>c:\ncd C:\\WINDOWS\\system32\\inetsrv\\\nappcmd.exe set config -section:system.applicationHost/sites \"/[name='Contoso'].hsts.enabled:True\" /commit:apphost\nappcmd.exe set config -section:system.applicationHost/sites \"/[name='Contoso'].hsts.max-age:31536000\" /commit:apphost\nappcmd.exe set config -section:system.applicationHost/sites \"/[name='Contoso'].hsts.includeSubDomains:True\" /commit:apphost\nappcmd.exe set config -section:system.applicationHost/sites \"/[name='Contoso'].hsts.redirectHttpToHttps:True\" /commit:apphost\n</code></pre>\n\n<p>The other methods Microsoft offer in that articles might be better options if you are on a hosted environment where you have limited access.</p>\n\n<p>Keep in mind that IIS10 version 1709 is available on Windows 10 now, but for Windows Server 2016 it is on a different release track, and won't be released as a patch or service pack. See <a href=\"https://learn.microsoft.com/en-us/windows-server/get-started/get-started-with-1709\" rel=\"noreferrer\">here</a> for details about 1709.</p>\n"
}
] | 2008/09/05 | [
"https://Stackoverflow.com/questions/47089",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4846/"
] | About 6 months ago I rolled out a site where every request needed to be over https. The only way at the time I could find to ensure that every request to a page was over https was to check it in the page load event. If the request was not over http I would response.redirect("<https://example.com>")
Is there a better way -- ideally some setting in the web.config? | Please use [HSTS](https://en.wikipedia.org/wiki/HTTP_Strict_Transport_Security) (HTTP Strict Transport Security)
from <http://www.hanselman.com/blog/HowToEnableHTTPStrictTransportSecurityHSTSInIIS7.aspx>
```
<?xml version="1.0" encoding="UTF-8"?>
<configuration>
<system.webServer>
<rewrite>
<rules>
<rule name="HTTP to HTTPS redirect" stopProcessing="true">
<match url="(.*)" />
<conditions>
<add input="{HTTPS}" pattern="off" ignoreCase="true" />
</conditions>
<action type="Redirect" url="https://{HTTP_HOST}/{R:1}"
redirectType="Permanent" />
</rule>
</rules>
<outboundRules>
<rule name="Add Strict-Transport-Security when HTTPS" enabled="true">
<match serverVariable="RESPONSE_Strict_Transport_Security"
pattern=".*" />
<conditions>
<add input="{HTTPS}" pattern="on" ignoreCase="true" />
</conditions>
<action type="Rewrite" value="max-age=31536000" />
</rule>
</outboundRules>
</rewrite>
</system.webServer>
</configuration>
```
**Original Answer** (replaced with the above on 4 December 2015)
basically
```
protected void Application_BeginRequest(Object sender, EventArgs e)
{
if (HttpContext.Current.Request.IsSecureConnection.Equals(false) && HttpContext.Current.Request.IsLocal.Equals(false))
{
Response.Redirect("https://" + Request.ServerVariables["HTTP_HOST"]
+ HttpContext.Current.Request.RawUrl);
}
}
```
that would go in the global.asax.cs (or global.asax.vb)
i dont know of a way to specify it in the web.config |
47,104 | <p>Can anyone explain this behavior or how to get around it?</p>
<p>If you execute this query:</p>
<pre><code>select *
from TblA
left join freetexttable ( TblB, *, 'query' ) on TblA.ID = [Key]
inner join DifferentDbCatalog.dbo.TblC on TblA.ID = TblC.TblAID
</code></pre>
<p>It will be very very very slow.</p>
<p>If you change that query to use two inner joins instead of a left join, it will be very fast. If you change it to use two left joins instead of an inner join, it will be very fast.</p>
<p>You can observe this same behavior if you use a sql table variable instead of the freetexttable as well. </p>
<p>The performance problem arises any time you have a table variable (or freetexttable) and a table in a different database catalog where one is in an inner join and the other is in a left join.</p>
<p>Does anyone know why this is slow, or how to speed it up?</p>
| [
{
"answer_id": 47109,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 0,
"selected": false,
"text": "<p>Index the field you use to perform the join.</p>\n\n<p>A good rule of thumb is to assign an index to any commonly referenced <a href=\"http://en.wikipedia.org/wiki/Foreign_key\" rel=\"nofollow noreferrer\">foreign</a> or <a href=\"http://en.wikipedia.org/wiki/Candidate_key\" rel=\"nofollow noreferrer\">candidate keys</a>.</p>\n"
},
{
"answer_id": 47120,
"author": "The How-To Geek",
"author_id": 291,
"author_profile": "https://Stackoverflow.com/users/291",
"pm_score": 2,
"selected": false,
"text": "<p>What you should usually do is turn on the \"Show Actual Execution Plan\" option and then take a close look at what is causing the slowdown. (hover your mouse over each join to see the details) You'll want to make sure that you are getting an index seek and not a table scan.</p>\n\n<p>I would assume what is happening is that SQL is being forced to pull everything from one table into memory in order to do one of the joins. Sometimes reversing the order that you join the tables will also help things.</p>\n"
},
{
"answer_id": 47128,
"author": "Joel Coehoorn",
"author_id": 3043,
"author_profile": "https://Stackoverflow.com/users/3043",
"pm_score": 3,
"selected": false,
"text": "<p>A general rule of thumb is that OUTER JOINs cause the number of rows in a result set to <em>increase,</em> while INNER JOINs cause the number of rows in a result set to <em>decrease.</em> Of course, there are plenty of scenarios where the opposite is true as well, but it's more likely to work this way than not. What you want to do for performance is keep the size of the result set (working set) as small as possible for as long as possible. </p>\n\n<p>Since both joins match on the first table, changing up the order won't effect the accuracy of the results. Therefore, you probably want to do the INNER JOIN before the LEFT JOIN:</p>\n\n<pre><code>SELECT * \nFROM TblA\nINNER JOIN DifferentDbCatalog.dbo.TblC on TblA.ID = TblC.TblAID\nLEFT JOIN freetexttable ( TblB, *, 'query' ) on TblA.ID = [Key]\n</code></pre>\n\n<p>As a practical matter, the query optimizer <em>should</em> be smart enough to compile to use the faster option, regardless of which order you specified for the joins. However, it's good practice to pretend that you have a dumb query optimizer, and that query operations happen in order. This helps future maintainers spot potential errors or assumptions about the nature of the tables.</p>\n\n<p>Because the optimizer should re-write things, this probably isn't good enough to fully explain the behavior you're seeing, so you'll still want to <em>examine the execution plan</em> used for each query, and probably add an index as suggested earlier. This is still a good principle to learn, though.</p>\n"
},
{
"answer_id": 47131,
"author": "Eugene Yokota",
"author_id": 3827,
"author_profile": "https://Stackoverflow.com/users/3827",
"pm_score": 1,
"selected": false,
"text": "<p>Putting <code>freetexttable(TblB, *, 'query')</code> into a temp table may help if it's getting called repeatedly in the execution plan.</p>\n"
}
] | 2008/09/05 | [
"https://Stackoverflow.com/questions/47104",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4407/"
] | Can anyone explain this behavior or how to get around it?
If you execute this query:
```
select *
from TblA
left join freetexttable ( TblB, *, 'query' ) on TblA.ID = [Key]
inner join DifferentDbCatalog.dbo.TblC on TblA.ID = TblC.TblAID
```
It will be very very very slow.
If you change that query to use two inner joins instead of a left join, it will be very fast. If you change it to use two left joins instead of an inner join, it will be very fast.
You can observe this same behavior if you use a sql table variable instead of the freetexttable as well.
The performance problem arises any time you have a table variable (or freetexttable) and a table in a different database catalog where one is in an inner join and the other is in a left join.
Does anyone know why this is slow, or how to speed it up? | A general rule of thumb is that OUTER JOINs cause the number of rows in a result set to *increase,* while INNER JOINs cause the number of rows in a result set to *decrease.* Of course, there are plenty of scenarios where the opposite is true as well, but it's more likely to work this way than not. What you want to do for performance is keep the size of the result set (working set) as small as possible for as long as possible.
Since both joins match on the first table, changing up the order won't effect the accuracy of the results. Therefore, you probably want to do the INNER JOIN before the LEFT JOIN:
```
SELECT *
FROM TblA
INNER JOIN DifferentDbCatalog.dbo.TblC on TblA.ID = TblC.TblAID
LEFT JOIN freetexttable ( TblB, *, 'query' ) on TblA.ID = [Key]
```
As a practical matter, the query optimizer *should* be smart enough to compile to use the faster option, regardless of which order you specified for the joins. However, it's good practice to pretend that you have a dumb query optimizer, and that query operations happen in order. This helps future maintainers spot potential errors or assumptions about the nature of the tables.
Because the optimizer should re-write things, this probably isn't good enough to fully explain the behavior you're seeing, so you'll still want to *examine the execution plan* used for each query, and probably add an index as suggested earlier. This is still a good principle to learn, though. |
47,107 | <p>Is there a way to disallow publishing of debug builds with ClickOnce?</p>
<p>I only want to allow release builds through, but right now human error causes a debug build to slip through once in a while. </p>
<p>We're publishing the build from within Visual Studio.</p>
| [
{
"answer_id": 865822,
"author": "Judah Gabriel Himango",
"author_id": 536,
"author_profile": "https://Stackoverflow.com/users/536",
"pm_score": 3,
"selected": false,
"text": "<p>One thing you can do is add a condition to the .csproj or .vbproj file that MSBuild will check when doing a build. </p>\n\n<p>The condition would check if a publish is occurring and check if the build is a debug build, then do something like run an external tool or otherwise interrupt the build process or cause it to fail.</p>\n\n<p>An example might be something like this:</p>\n\n<pre><code><Choose>\n <When Condition=\" '$(Configuration)'=='Debug' \">\n <Exec Command=\"C:\\foo.bat\" ContinueOnError=\"false\" />\n </When>\n </Choose>\n</code></pre>\n\n<p>Where foo.bat is a batch file that return non-zero, thus stopping the publish from occurring.</p>\n"
},
{
"answer_id": 6738914,
"author": "Rodrigo Britto",
"author_id": 850784,
"author_profile": "https://Stackoverflow.com/users/850784",
"pm_score": 2,
"selected": false,
"text": "<p>I have chosen another solution that worked for me:</p>\n\n<p>I couldn't change my build process. So I did <em>Tools</em> → <em>Customize...</em> and change the text of the action, adding an alert like \"Publish [CONFIGURE TO RELEASE!]\", and placing the Publish button next to the Debug/Release configuration option. It's easy!</p>\n\n<p>With this I considerably reduced the risk of human error. Those buttons should always be together.</p>\n"
},
{
"answer_id": 15080048,
"author": "Sam Storie",
"author_id": 571237,
"author_profile": "https://Stackoverflow.com/users/571237",
"pm_score": 7,
"selected": true,
"text": "<p>I have started to modify the .csproj files to include the following code to throw an error for debug deploys, effectively preventing the deploy from happening:</p>\n\n<pre><code><!-- The following makes sure we don’t try to publish a configuration that defines the DEBUG constant -->\n<Target Name=\"BeforePublish\">\n <Error Condition=\"'$(DebugSymbols)' == 'true'\" Text=\"You attempted to publish a configuration that defines the DEBUG constant!\" />\n</Target>\n</code></pre>\n\n<p>Just place it at the end of the file, right before the <code></Project></code> tag.</p>\n\n<p>(original source: <a href=\"http://www.nathanpjones.com/wp/2010/05/preventing-clickonce-publishing-a-debug-configuration/comment-page-1/#comment-625\">http://www.nathanpjones.com/wp/2010/05/preventing-clickonce-publishing-a-debug-configuration/comment-page-1/#comment-625</a>)</p>\n"
}
] | 2008/09/05 | [
"https://Stackoverflow.com/questions/47107",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3641/"
] | Is there a way to disallow publishing of debug builds with ClickOnce?
I only want to allow release builds through, but right now human error causes a debug build to slip through once in a while.
We're publishing the build from within Visual Studio. | I have started to modify the .csproj files to include the following code to throw an error for debug deploys, effectively preventing the deploy from happening:
```
<!-- The following makes sure we don’t try to publish a configuration that defines the DEBUG constant -->
<Target Name="BeforePublish">
<Error Condition="'$(DebugSymbols)' == 'true'" Text="You attempted to publish a configuration that defines the DEBUG constant!" />
</Target>
```
Just place it at the end of the file, right before the `</Project>` tag.
(original source: <http://www.nathanpjones.com/wp/2010/05/preventing-clickonce-publishing-a-debug-configuration/comment-page-1/#comment-625>) |
47,144 | <p>In my C# program, I have a thread that represents a running test, which can be aborted by a click on a button labeled "Interrupt execution". In order for the thread (and therefore the test) to terminate in an elegant manner (and do some vital work beforehand), this button is enabled only in some well-defined moments, in which I catch <code>ThreadAbortedException</code>, do <code>Thread.ResetAbort()</code> and die beautifully (that is, the thread).</p>
<p>The problem is that, in the time window in which aborting is possible, there are some tasks that need to be done from start to finish once initiated, and, so, I fear TAE. Locks don't provide a solution for this, and, although finally blocks do, I don't find it elegant to wrap important code in the following manner:</p>
<pre><code>try {
} finally {
// vital code
}
</code></pre>
<p>However, I didn't find any other solution.</p>
<p>Is this another way to delay the interference of <code>ThreadAbortException</code> until the end of the block?</p>
| [
{
"answer_id": 47147,
"author": "Rob Walker",
"author_id": 3631,
"author_profile": "https://Stackoverflow.com/users/3631",
"pm_score": 3,
"selected": true,
"text": "<p>The situations under which a ThreadAbortException will be generated can be complex. A better option might be to ask why you are using ThreadAbortExceptions at all.</p>\n\n<p>A better pattern would be to simply use a flag to indicate to the running thread that it should abort, and then test the flag regularly while it is working. If it is set you can throw an exception at that point if you want.</p>\n\n<p>With this pattern you are totally in control of when the thread will act on the abort, and don't have to worry about the critical operations being interrupted.</p>\n"
},
{
"answer_id": 47150,
"author": "Corey",
"author_id": 1595,
"author_profile": "https://Stackoverflow.com/users/1595",
"pm_score": 2,
"selected": false,
"text": "<p>Use <a href=\"http://msdn.microsoft.com/en-us/library/system.threading.thread.begincriticalregion.aspx\" rel=\"nofollow noreferrer\">Thread.BeginCriticalRegion()</a> </p>\n\n<blockquote>\n <p>Notifies a host that execution is about to enter a region of code in which the effects of a thread abort or unhandled exception might jeopardize other tasks in the application domain. </p>\n</blockquote>\n\n<pre><code>Thread.BeginCriticalRegion()\n\n//do important stuff here\n\nThread.EndCriticalRegion()\n</code></pre>\n"
}
] | 2008/09/06 | [
"https://Stackoverflow.com/questions/47144",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4850/"
] | In my C# program, I have a thread that represents a running test, which can be aborted by a click on a button labeled "Interrupt execution". In order for the thread (and therefore the test) to terminate in an elegant manner (and do some vital work beforehand), this button is enabled only in some well-defined moments, in which I catch `ThreadAbortedException`, do `Thread.ResetAbort()` and die beautifully (that is, the thread).
The problem is that, in the time window in which aborting is possible, there are some tasks that need to be done from start to finish once initiated, and, so, I fear TAE. Locks don't provide a solution for this, and, although finally blocks do, I don't find it elegant to wrap important code in the following manner:
```
try {
} finally {
// vital code
}
```
However, I didn't find any other solution.
Is this another way to delay the interference of `ThreadAbortException` until the end of the block? | The situations under which a ThreadAbortException will be generated can be complex. A better option might be to ask why you are using ThreadAbortExceptions at all.
A better pattern would be to simply use a flag to indicate to the running thread that it should abort, and then test the flag regularly while it is working. If it is set you can throw an exception at that point if you want.
With this pattern you are totally in control of when the thread will act on the abort, and don't have to worry about the critical operations being interrupted. |
47,169 | <p>I'd like to enable/disable some other controls based on how many items are in my <code>ListView</code> control. I can't find any event that would do this, either on the <code>ListView</code> itself or on the <code>ListViewItemCollection</code>. Maybe there's a way to generically watch any collection in C# for changes?</p>
<p>I'd be happy with other events too, even ones that sometimes fire when the items don't change, but for example the <code>ControlAdded</code> and <code>Layout</code> events didn't work :(.</p>
| [
{
"answer_id": 47178,
"author": "Kibbee",
"author_id": 1862,
"author_profile": "https://Stackoverflow.com/users/1862",
"pm_score": 0,
"selected": false,
"text": "<p>I can't find any events that you could use. Perhaps you could subclass ListViewItemCollection, and raise your own event when something is added, with code similar to this.</p>\n\n<pre><code>Public Class MyListViewItemCollection\n Inherits ListView.ListViewItemCollection\n\n Public Event ItemAdded(ByVal Item As ListViewItem)\n\n Sub New(ByVal owner As ListView)\n MyBase.New(owner)\n End Sub\n\n Public Overrides Function Add(ByVal value As System.Windows.Forms.ListViewItem) As System.Windows.Forms.ListViewItem\n Dim Item As ListViewItem\n\n Item = MyBase.Add(value)\n\n RaiseEvent ItemAdded(Item)\n\n Return Item\n End Function\nEnd Class\n</code></pre>\n"
},
{
"answer_id": 47196,
"author": "jfs",
"author_id": 718,
"author_profile": "https://Stackoverflow.com/users/718",
"pm_score": 0,
"selected": false,
"text": "<p>I think the best thing that you can do here is to subclass ListView and provide the events that you want.</p>\n"
},
{
"answer_id": 47200,
"author": "Kibbee",
"author_id": 1862,
"author_profile": "https://Stackoverflow.com/users/1862",
"pm_score": 3,
"selected": true,
"text": "<p>@Domenic</p>\n\n<p>Not too sure, Never quite got that far in the thought process. </p>\n\n<p>Another solution might be to extend ListView, and when adding and removing stuff, instead of calling .items.add, and items.remove, you call your other functions. It would still be possible to add and remove without events being raised, but with a little code review to make sure .items.add and .items.remove weren't called directly, it could work out quite well. Here's a little example. I only showed 1 Add function, but there are 6 you would have to implement, if you wanted to have use of all the available add functions. There's also .AddRange, and .Clear that you might want to take a look at.</p>\n\n<pre><code>Public Class MonitoredListView\n Inherits ListView\n\n Public Event ItemAdded()\n Public Event ItemRemoved()\n\n Public Sub New()\n MyBase.New()\n End Sub\n\n Public Function AddItem(ByVal Text As String) As ListViewItem\n RaiseEvent ItemAdded()\n\n MyBase.Items.Add(Text)\n End Function\n\n Public Sub RemoveItem(ByVal Item As ListViewItem)\n RaiseEvent ItemRemoved()\n\n MyBase.Items.Remove(Item)\n End Sub\n\nEnd Class\n</code></pre>\n"
}
] | 2008/09/06 | [
"https://Stackoverflow.com/questions/47169",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3191/"
] | I'd like to enable/disable some other controls based on how many items are in my `ListView` control. I can't find any event that would do this, either on the `ListView` itself or on the `ListViewItemCollection`. Maybe there's a way to generically watch any collection in C# for changes?
I'd be happy with other events too, even ones that sometimes fire when the items don't change, but for example the `ControlAdded` and `Layout` events didn't work :(. | @Domenic
Not too sure, Never quite got that far in the thought process.
Another solution might be to extend ListView, and when adding and removing stuff, instead of calling .items.add, and items.remove, you call your other functions. It would still be possible to add and remove without events being raised, but with a little code review to make sure .items.add and .items.remove weren't called directly, it could work out quite well. Here's a little example. I only showed 1 Add function, but there are 6 you would have to implement, if you wanted to have use of all the available add functions. There's also .AddRange, and .Clear that you might want to take a look at.
```
Public Class MonitoredListView
Inherits ListView
Public Event ItemAdded()
Public Event ItemRemoved()
Public Sub New()
MyBase.New()
End Sub
Public Function AddItem(ByVal Text As String) As ListViewItem
RaiseEvent ItemAdded()
MyBase.Items.Add(Text)
End Function
Public Sub RemoveItem(ByVal Item As ListViewItem)
RaiseEvent ItemRemoved()
MyBase.Items.Remove(Item)
End Sub
End Class
``` |
47,207 | <p>Can i print out a url <code>/admin/manage/products/add</code> of a certain view in a template?</p>
<p>Here is the rule i want to create a link for</p>
<pre><code>(r'^manage/products/add/$', create_object, {'model': Product, 'post_save_redirect': ''}),
</code></pre>
<p>I would like to have /manage/products/add in a template without hardcoding it. How can i do this?</p>
<p><strong>Edit:</strong> I am not using the default admin (well, i am but it is at another url), this is my own</p>
| [
{
"answer_id": 47212,
"author": "Peter Hoffmann",
"author_id": 720,
"author_profile": "https://Stackoverflow.com/users/720",
"pm_score": 2,
"selected": false,
"text": "<p>If you use <a href=\"https://docs.djangoproject.com/en/1.2/topics/http/urls/#naming-url-patterns\" rel=\"nofollow noreferrer\">named url patterns</a> you can do the follwing in your template</p>\n\n<pre><code>{% url create_object %}\n</code></pre>\n"
},
{
"answer_id": 47213,
"author": "Cristian",
"author_id": 680,
"author_profile": "https://Stackoverflow.com/users/680",
"pm_score": 0,
"selected": false,
"text": "<p>The preferred way of creating the URL is by adding a <code>get_absolute_url</code> method to your model classes. You can hardcode the path there so you at least get closer to following the KISS philosophy.</p>\n\n<p>You can go further by utilizing the <code>permalink</code> decorator that figures the path based on the urls configuration.</p>\n\n<p>You can read more in the django documentation <a href=\"https://docs.djangoproject.com/en/dev/ref/models/instances/#get-absolute-url\" rel=\"nofollow noreferrer\">here</a>.</p>\n"
},
{
"answer_id": 47304,
"author": "Harley Holcombe",
"author_id": 1057,
"author_profile": "https://Stackoverflow.com/users/1057",
"pm_score": 5,
"selected": true,
"text": "<p>You can use <code>get_absolute_url</code>, but that will only work for a particular object. Since your object hasn't been created yet, it won't work in this case.</p>\n\n<p>You want to use <a href=\"https://docs.djangoproject.com/en/1.2/topics/http/urls/#naming-url-patterns\" rel=\"nofollow noreferrer\">named URL patterns</a>. Here's a quick intro:</p>\n\n<p>Change the line in your urls.py to:</p>\n\n<pre><code>(r'^manage/products/add/$', create_object, {'model': Product, 'post_save_redirect': ''}, \"create-product\"),\n</code></pre>\n\n<p>Then, in your template you use this to display the URL:</p>\n\n<pre><code>{% url create-product %}\n</code></pre>\n\n<p>If you're using Django 1.5 or higher you need this:</p>\n\n<pre><code>{% url 'create-product' %}\n</code></pre>\n\n<p>You can do some more powerful things with named URL patterns, they're very handy. Note that they are only in the development version (and also 1.0).</p>\n"
}
] | 2008/09/06 | [
"https://Stackoverflow.com/questions/47207",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2592/"
] | Can i print out a url `/admin/manage/products/add` of a certain view in a template?
Here is the rule i want to create a link for
```
(r'^manage/products/add/$', create_object, {'model': Product, 'post_save_redirect': ''}),
```
I would like to have /manage/products/add in a template without hardcoding it. How can i do this?
**Edit:** I am not using the default admin (well, i am but it is at another url), this is my own | You can use `get_absolute_url`, but that will only work for a particular object. Since your object hasn't been created yet, it won't work in this case.
You want to use [named URL patterns](https://docs.djangoproject.com/en/1.2/topics/http/urls/#naming-url-patterns). Here's a quick intro:
Change the line in your urls.py to:
```
(r'^manage/products/add/$', create_object, {'model': Product, 'post_save_redirect': ''}, "create-product"),
```
Then, in your template you use this to display the URL:
```
{% url create-product %}
```
If you're using Django 1.5 or higher you need this:
```
{% url 'create-product' %}
```
You can do some more powerful things with named URL patterns, they're very handy. Note that they are only in the development version (and also 1.0). |
47,239 | <p>Does anyone know a way to auto-generate database tables for a given class? I'm not looking for an entire persistence layer - I already have a data access solution I'm using, but I suddenly have to store a lot of information from a large number of classes and I really don't want to have to create all these tables by hand. For example, given the following class:</p>
<pre><code>class Foo
{
private string property1;
public string Property1
{
get { return property1; }
set { property1 = value; }
}
private int property2;
public int Property2
{
get { return property2; }
set { property2 = value; }
}
}
</code></pre>
<p>I'd expect the following SQL:</p>
<pre><code>CREATE TABLE Foo
(
Property1 VARCHAR(500),
Property2 INT
)
</code></pre>
<p>I'm also wondering how you could handle complex types. For example, in the previously cited class, if we changed that to be :</p>
<pre><code>class Foo
{
private string property1;
public string Property1
{
get { return property1; }
set { property1 = value; }
}
private System.Management.ManagementObject property2;
public System.Management.ManagementObject Property2
{
get { return property2; }
set { property2 = value; }
}
}
</code></pre>
<p></p>
<p>How could I handle this?</p>
<p>I've looked at trying to auto-generate the database scripts by myself using reflection to enumerate through each class' properties, but it's clunky and the complex data types have me stumped.</p>
| [
{
"answer_id": 47251,
"author": "Mark Cidade",
"author_id": 1659,
"author_profile": "https://Stackoverflow.com/users/1659",
"pm_score": 1,
"selected": false,
"text": "<p>For complex types, you can recursively convert each one that you come across into a table of its own and then attempt to manage foreign key relationships. </p>\n\n<p>You may also want to pre-specify <em>which</em> classes will or won't be converted to tables. As for complex data that you want reflected in the database without bloating the schema, you can have one or more tables for miscellaneous types. This example uses as many as 4:</p>\n\n<pre><code>CREATE TABLE MiscTypes /* may have to include standard types as well */\n ( TypeID INT,\n TypeName VARCHAR(...)\n )\n\nCREATE TABLE MiscProperties\n ( PropertyID INT,\n DeclaringTypeID INT, /* FK to MiscTypes */\n PropertyName VARCHAR(...),\n ValueTypeID INT /* FK to MiscTypes */\n )\n\nCREATE TABLE MiscData\n ( ObjectID INT,\n TypeID INT\n )\n\nCREATE TABLE MiscValues\n ( ObjectID INT, /* FK to MiscData*/\n PropertyID INT,\n Value VARCHAR(...)\n )\n</code></pre>\n"
},
{
"answer_id": 47273,
"author": "FlySwat",
"author_id": 1965,
"author_profile": "https://Stackoverflow.com/users/1965",
"pm_score": 8,
"selected": true,
"text": "<p>It's really late, and I only spent about 10 minutes on this, so its extremely sloppy, however it does work and will give you a good jumping off point:</p>\n\n<pre><code>using System;\nusing System.Collections.Generic;\nusing System.Text;\nusing System.Reflection;\n\nnamespace TableGenerator\n{\n class Program\n {\n static void Main(string[] args)\n {\n List<TableClass> tables = new List<TableClass>();\n\n // Pass assembly name via argument\n Assembly a = Assembly.LoadFile(args[0]);\n\n Type[] types = a.GetTypes();\n\n // Get Types in the assembly.\n foreach (Type t in types)\n {\n TableClass tc = new TableClass(t); \n tables.Add(tc);\n }\n\n // Create SQL for each table\n foreach (TableClass table in tables)\n {\n Console.WriteLine(table.CreateTableScript());\n Console.WriteLine();\n }\n\n // Total Hacked way to find FK relationships! Too lazy to fix right now\n foreach (TableClass table in tables)\n {\n foreach (KeyValuePair<String, Type> field in table.Fields)\n {\n foreach (TableClass t2 in tables)\n {\n if (field.Value.Name == t2.ClassName)\n {\n // We have a FK Relationship!\n Console.WriteLine(\"GO\");\n Console.WriteLine(\"ALTER TABLE \" + table.ClassName + \" WITH NOCHECK\");\n Console.WriteLine(\"ADD CONSTRAINT FK_\" + field.Key + \" FOREIGN KEY (\" + field.Key + \") REFERENCES \" + t2.ClassName + \"(ID)\");\n Console.WriteLine(\"GO\");\n\n }\n }\n }\n }\n }\n }\n\n public class TableClass\n {\n private List<KeyValuePair<String, Type>> _fieldInfo = new List<KeyValuePair<String, Type>>();\n private string _className = String.Empty;\n\n private Dictionary<Type, String> dataMapper\n {\n get\n {\n // Add the rest of your CLR Types to SQL Types mapping here\n Dictionary<Type, String> dataMapper = new Dictionary<Type, string>();\n dataMapper.Add(typeof(int), \"BIGINT\");\n dataMapper.Add(typeof(string), \"NVARCHAR(500)\");\n dataMapper.Add(typeof(bool), \"BIT\");\n dataMapper.Add(typeof(DateTime), \"DATETIME\");\n dataMapper.Add(typeof(float), \"FLOAT\");\n dataMapper.Add(typeof(decimal), \"DECIMAL(18,0)\");\n dataMapper.Add(typeof(Guid), \"UNIQUEIDENTIFIER\");\n\n return dataMapper;\n }\n }\n\n public List<KeyValuePair<String, Type>> Fields\n {\n get { return this._fieldInfo; }\n set { this._fieldInfo = value; }\n }\n\n public string ClassName\n {\n get { return this._className; }\n set { this._className = value; }\n }\n\n public TableClass(Type t)\n {\n this._className = t.Name;\n\n foreach (PropertyInfo p in t.GetProperties())\n {\n KeyValuePair<String, Type> field = new KeyValuePair<String, Type>(p.Name, p.PropertyType);\n\n this.Fields.Add(field);\n }\n }\n\n public string CreateTableScript()\n {\n System.Text.StringBuilder script = new StringBuilder();\n\n script.AppendLine(\"CREATE TABLE \" + this.ClassName);\n script.AppendLine(\"(\");\n script.AppendLine(\"\\t ID BIGINT,\");\n for (int i = 0; i < this.Fields.Count; i++)\n {\n KeyValuePair<String, Type> field = this.Fields[i];\n\n if (dataMapper.ContainsKey(field.Value))\n {\n script.Append(\"\\t \" + field.Key + \" \" + dataMapper[field.Value]);\n }\n else\n {\n // Complex Type? \n script.Append(\"\\t \" + field.Key + \" BIGINT\");\n }\n\n if (i != this.Fields.Count - 1)\n {\n script.Append(\",\");\n }\n\n script.Append(Environment.NewLine);\n }\n\n script.AppendLine(\")\");\n\n return script.ToString();\n }\n }\n}\n</code></pre>\n\n<p>I put these classes in an assembly to test it:</p>\n\n<pre><code>public class FakeDataClass\n{\n public int AnInt\n {\n get;\n set;\n }\n\n public string AString\n {\n get;\n set;\n }\n\n public float AFloat\n {\n get;\n set;\n }\n\n public FKClass AFKReference\n {\n get;\n set;\n }\n}\n\npublic class FKClass\n {\n public int AFKInt\n {\n get;\n set;\n }\n }\n</code></pre>\n\n<p>And it generated the following SQL:</p>\n\n<pre><code>CREATE TABLE FakeDataClass\n(\n ID BIGINT,\n AnInt BIGINT,\n AString NVARCHAR(255),\n AFloat FLOAT,\n AFKReference BIGINT\n)\n\n\nCREATE TABLE FKClass\n(\n ID BIGINT,\n AFKInt BIGINT\n)\n\n\nGO\nALTER TABLE FakeDataClass WITH NOCHECK\nADD CONSTRAINT FK_AFKReference FOREIGN KEY (AFKReference) REFERENCES FKClass(ID)\nGO\n</code></pre>\n\n<p>Some further thoughts...I'd consider adding an attribute such as [SqlTable] to your classes, that way it only generates tables for the classes you want. Also, this can be cleaned up a ton, bugs fixed, optimized (the FK Checker is a joke) etc etc...Just to get you started.</p>\n"
},
{
"answer_id": 47274,
"author": "Vaibhav",
"author_id": 380,
"author_profile": "https://Stackoverflow.com/users/380",
"pm_score": 2,
"selected": false,
"text": "<p>I think for complex data types, you should extend them by specifying a ToDB() method which holds their own implementation for creating tables in the DB, and this way it becomes auto-recursive.</p>\n"
},
{
"answer_id": 47275,
"author": "Vaibhav",
"author_id": 380,
"author_profile": "https://Stackoverflow.com/users/380",
"pm_score": 0,
"selected": false,
"text": "<p>Also... maybe you can use some tool such as Visio (not sure if Visio does this, but I think it does) to reverse engineer your classes into UML and then use the UML to generate the DB Schema... or maybe use a tool such as this <a href=\"http://www.tangiblearchitect.net/visual-studio/\" rel=\"nofollow noreferrer\">http://www.tangiblearchitect.net/visual-studio/</a></p>\n"
},
{
"answer_id": 47350,
"author": "Cheekysoft",
"author_id": 1820,
"author_profile": "https://Stackoverflow.com/users/1820",
"pm_score": 0,
"selected": false,
"text": "<p>I know you're looking for an entire persistence layer, but NHibernate's hbm2ddl task can do this almost as a one-liner.</p>\n\n<p>There is a <a href=\"http://biasecurities.com/blog/2005/nhibernate-hbm2ddl-nant-task/\" rel=\"nofollow noreferrer\">NAnt task</a> available to call it which may well be of interest.</p>\n"
},
{
"answer_id": 47389,
"author": "Portman",
"author_id": 1690,
"author_profile": "https://Stackoverflow.com/users/1690",
"pm_score": 4,
"selected": false,
"text": "<p>@Jonathan Holland</p>\n\n<p>Wow, I think that's the most raw work I've ever seen put into a StackOverflow post. Well done. <strong>However</strong>, instead of constructing DDL statements as strings, you should definitely use the <a href=\"http://msdn.microsoft.com/en-us/library/ms162169.aspx\" rel=\"noreferrer\">SQL Server Management Objects</a> classes introduced with SQL 2005.</p>\n\n<p>David Hayden has a post entitled <a href=\"http://www.davidhayden.com/blog/dave/archive/2006/01/27/2775.aspx\" rel=\"noreferrer\">Create Table in SQL Server 2005 Using C# and SQL Server Management Objects (SMO) - Code Generation</a> that walks through how to create a table using SMO. The strongly-typed objects make it a breeze with methods like:</p>\n\n<pre><code>// Create new table, called TestTable\nTable newTable = new Table(db, \"TestTable\");\n</code></pre>\n\n<p>and</p>\n\n<pre><code>// Create a PK Index for the table\nIndex index = new Index(newTable, \"PK_TestTable\");\nindex.IndexKeyType = IndexKeyType.DriPrimaryKey;\n</code></pre>\n\n<p>VanOrman, if you're using SQL 2005, definitely make SMO part of your solution.</p>\n"
},
{
"answer_id": 48152,
"author": "IanStallings",
"author_id": 4933,
"author_profile": "https://Stackoverflow.com/users/4933",
"pm_score": 0,
"selected": false,
"text": "<p><a href=\"http://subsonicproject.com/\" rel=\"nofollow noreferrer\">Subsonic</a> is also another option. I often use it to generate entity classes that map to a database. It has a command line utility that lets you specify tables, types, and a host of other useful things</p>\n"
},
{
"answer_id": 415162,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": -1,
"selected": false,
"text": "<p>Try DaoliteMappingTool for .net. It can help you generate the classes.\nDownload form <a href=\"http://www.idevlite.com/download/daolitemappingtool(net).zip\" rel=\"nofollow noreferrer\">Here</a></p>\n"
},
{
"answer_id": 750311,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": -1,
"selected": false,
"text": "<p>You can do the opposite, database table to C# classes here:\n<a href=\"http://pureobjects.com/dbCode.aspx\" rel=\"nofollow noreferrer\">http://pureobjects.com/dbCode.aspx</a></p>\n"
},
{
"answer_id": 10033792,
"author": "Kai Sevelin",
"author_id": 1315993,
"author_profile": "https://Stackoverflow.com/users/1315993",
"pm_score": 2,
"selected": false,
"text": "<p>Try out my CreateSchema extension method for objects at <a href=\"http://createschema.codeplex.com/\" rel=\"nofollow\">http://createschema.codeplex.com/</a></p>\n\n<p>It returns a string for any object containing CREATE TABLE scripts. </p>\n"
},
{
"answer_id": 30419749,
"author": "Nitin",
"author_id": 290174,
"author_profile": "https://Stackoverflow.com/users/290174",
"pm_score": 0,
"selected": false,
"text": "<p>There is a free app, Schematrix which generates classes from DB, check out if does the reverse too :) <a href=\"http://www.schematrix.com/products/schemacoder/download.aspx\" rel=\"nofollow\">http://www.schematrix.com/products/schemacoder/download.aspx</a></p>\n"
},
{
"answer_id": 39836180,
"author": "tatigo",
"author_id": 906258,
"author_profile": "https://Stackoverflow.com/users/906258",
"pm_score": 2,
"selected": false,
"text": "<p>As of 2016 (I think), you can use Entity Framework 6 Code First to generate SQL schema from poco c# classes or to use Database First to generate c# code from sql.\n<a href=\"https://msdn.microsoft.com/en-ca/data/jj193542.aspx\" rel=\"nofollow noreferrer\">Code First to DB walkthrough </a></p>\n"
}
] | 2008/09/06 | [
"https://Stackoverflow.com/questions/47239",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4550/"
] | Does anyone know a way to auto-generate database tables for a given class? I'm not looking for an entire persistence layer - I already have a data access solution I'm using, but I suddenly have to store a lot of information from a large number of classes and I really don't want to have to create all these tables by hand. For example, given the following class:
```
class Foo
{
private string property1;
public string Property1
{
get { return property1; }
set { property1 = value; }
}
private int property2;
public int Property2
{
get { return property2; }
set { property2 = value; }
}
}
```
I'd expect the following SQL:
```
CREATE TABLE Foo
(
Property1 VARCHAR(500),
Property2 INT
)
```
I'm also wondering how you could handle complex types. For example, in the previously cited class, if we changed that to be :
```
class Foo
{
private string property1;
public string Property1
{
get { return property1; }
set { property1 = value; }
}
private System.Management.ManagementObject property2;
public System.Management.ManagementObject Property2
{
get { return property2; }
set { property2 = value; }
}
}
```
How could I handle this?
I've looked at trying to auto-generate the database scripts by myself using reflection to enumerate through each class' properties, but it's clunky and the complex data types have me stumped. | It's really late, and I only spent about 10 minutes on this, so its extremely sloppy, however it does work and will give you a good jumping off point:
```
using System;
using System.Collections.Generic;
using System.Text;
using System.Reflection;
namespace TableGenerator
{
class Program
{
static void Main(string[] args)
{
List<TableClass> tables = new List<TableClass>();
// Pass assembly name via argument
Assembly a = Assembly.LoadFile(args[0]);
Type[] types = a.GetTypes();
// Get Types in the assembly.
foreach (Type t in types)
{
TableClass tc = new TableClass(t);
tables.Add(tc);
}
// Create SQL for each table
foreach (TableClass table in tables)
{
Console.WriteLine(table.CreateTableScript());
Console.WriteLine();
}
// Total Hacked way to find FK relationships! Too lazy to fix right now
foreach (TableClass table in tables)
{
foreach (KeyValuePair<String, Type> field in table.Fields)
{
foreach (TableClass t2 in tables)
{
if (field.Value.Name == t2.ClassName)
{
// We have a FK Relationship!
Console.WriteLine("GO");
Console.WriteLine("ALTER TABLE " + table.ClassName + " WITH NOCHECK");
Console.WriteLine("ADD CONSTRAINT FK_" + field.Key + " FOREIGN KEY (" + field.Key + ") REFERENCES " + t2.ClassName + "(ID)");
Console.WriteLine("GO");
}
}
}
}
}
}
public class TableClass
{
private List<KeyValuePair<String, Type>> _fieldInfo = new List<KeyValuePair<String, Type>>();
private string _className = String.Empty;
private Dictionary<Type, String> dataMapper
{
get
{
// Add the rest of your CLR Types to SQL Types mapping here
Dictionary<Type, String> dataMapper = new Dictionary<Type, string>();
dataMapper.Add(typeof(int), "BIGINT");
dataMapper.Add(typeof(string), "NVARCHAR(500)");
dataMapper.Add(typeof(bool), "BIT");
dataMapper.Add(typeof(DateTime), "DATETIME");
dataMapper.Add(typeof(float), "FLOAT");
dataMapper.Add(typeof(decimal), "DECIMAL(18,0)");
dataMapper.Add(typeof(Guid), "UNIQUEIDENTIFIER");
return dataMapper;
}
}
public List<KeyValuePair<String, Type>> Fields
{
get { return this._fieldInfo; }
set { this._fieldInfo = value; }
}
public string ClassName
{
get { return this._className; }
set { this._className = value; }
}
public TableClass(Type t)
{
this._className = t.Name;
foreach (PropertyInfo p in t.GetProperties())
{
KeyValuePair<String, Type> field = new KeyValuePair<String, Type>(p.Name, p.PropertyType);
this.Fields.Add(field);
}
}
public string CreateTableScript()
{
System.Text.StringBuilder script = new StringBuilder();
script.AppendLine("CREATE TABLE " + this.ClassName);
script.AppendLine("(");
script.AppendLine("\t ID BIGINT,");
for (int i = 0; i < this.Fields.Count; i++)
{
KeyValuePair<String, Type> field = this.Fields[i];
if (dataMapper.ContainsKey(field.Value))
{
script.Append("\t " + field.Key + " " + dataMapper[field.Value]);
}
else
{
// Complex Type?
script.Append("\t " + field.Key + " BIGINT");
}
if (i != this.Fields.Count - 1)
{
script.Append(",");
}
script.Append(Environment.NewLine);
}
script.AppendLine(")");
return script.ToString();
}
}
}
```
I put these classes in an assembly to test it:
```
public class FakeDataClass
{
public int AnInt
{
get;
set;
}
public string AString
{
get;
set;
}
public float AFloat
{
get;
set;
}
public FKClass AFKReference
{
get;
set;
}
}
public class FKClass
{
public int AFKInt
{
get;
set;
}
}
```
And it generated the following SQL:
```
CREATE TABLE FakeDataClass
(
ID BIGINT,
AnInt BIGINT,
AString NVARCHAR(255),
AFloat FLOAT,
AFKReference BIGINT
)
CREATE TABLE FKClass
(
ID BIGINT,
AFKInt BIGINT
)
GO
ALTER TABLE FakeDataClass WITH NOCHECK
ADD CONSTRAINT FK_AFKReference FOREIGN KEY (AFKReference) REFERENCES FKClass(ID)
GO
```
Some further thoughts...I'd consider adding an attribute such as [SqlTable] to your classes, that way it only generates tables for the classes you want. Also, this can be cleaned up a ton, bugs fixed, optimized (the FK Checker is a joke) etc etc...Just to get you started. |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.