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
|
---|---|---|---|---|---|---|
18,685 | <p>Can anyone tell me how I can display a status message like "12 seconds ago" or "5 minutes ago" etc in a web page?</p>
| [
{
"answer_id": 18693,
"author": "Niyaz",
"author_id": 184,
"author_profile": "https://Stackoverflow.com/users/184",
"pm_score": 7,
"selected": true,
"text": "<p>Here is the php code for the same:</p>\n\n<pre><code>function time_since($since) {\n $chunks = array(\n array(60 * 60 * 24 * 365 , 'year'),\n array(60 * 60 * 24 * 30 , 'month'),\n array(60 * 60 * 24 * 7, 'week'),\n array(60 * 60 * 24 , 'day'),\n array(60 * 60 , 'hour'),\n array(60 , 'minute'),\n array(1 , 'second')\n );\n\n for ($i = 0, $j = count($chunks); $i < $j; $i++) {\n $seconds = $chunks[$i][0];\n $name = $chunks[$i][1];\n if (($count = floor($since / $seconds)) != 0) {\n break;\n }\n }\n\n $print = ($count == 1) ? '1 '.$name : \"$count {$name}s\";\n return $print;\n}\n</code></pre>\n\n<p>The function takes the number of seconds as input and outputs text such as:</p>\n\n<ul>\n<li>10 seconds</li>\n<li>1 minute</li>\n</ul>\n\n<p>etc</p>\n"
},
{
"answer_id": 16248251,
"author": "Dipesh",
"author_id": 1689396,
"author_profile": "https://Stackoverflow.com/users/1689396",
"pm_score": 4,
"selected": false,
"text": "<pre><code>function timeAgo($timestamp){\n $datetime1=new DateTime(\"now\");\n $datetime2=date_create($timestamp);\n $diff=date_diff($datetime1, $datetime2);\n $timemsg='';\n if($diff->y > 0){\n $timemsg = $diff->y .' year'. ($diff->y > 1?\"'s\":'');\n\n }\n else if($diff->m > 0){\n $timemsg = $diff->m . ' month'. ($diff->m > 1?\"'s\":'');\n }\n else if($diff->d > 0){\n $timemsg = $diff->d .' day'. ($diff->d > 1?\"'s\":'');\n }\n else if($diff->h > 0){\n $timemsg = $diff->h .' hour'.($diff->h > 1 ? \"'s\":'');\n }\n else if($diff->i > 0){\n $timemsg = $diff->i .' minute'. ($diff->i > 1?\"'s\":'');\n }\n else if($diff->s > 0){\n $timemsg = $diff->s .' second'. ($diff->s > 1?\"'s\":'');\n }\n\n$timemsg = $timemsg.' ago';\nreturn $timemsg;\n}\n</code></pre>\n"
},
{
"answer_id": 23475770,
"author": "Sebastiaan Hilbers",
"author_id": 2450545,
"author_profile": "https://Stackoverflow.com/users/2450545",
"pm_score": 3,
"selected": false,
"text": "<p>PHP's <code>\\DateTime::diff</code> returns a <a href=\"http://nl3.php.net/dateInterval\" rel=\"noreferrer\"><code>\\DateInterval</code></a> object on which you can get the minutes by the public <code>i</code> property.</p>\n"
}
] | 2008/08/20 | [
"https://Stackoverflow.com/questions/18685",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/184/"
] | Can anyone tell me how I can display a status message like "12 seconds ago" or "5 minutes ago" etc in a web page? | Here is the php code for the same:
```
function time_since($since) {
$chunks = array(
array(60 * 60 * 24 * 365 , 'year'),
array(60 * 60 * 24 * 30 , 'month'),
array(60 * 60 * 24 * 7, 'week'),
array(60 * 60 * 24 , 'day'),
array(60 * 60 , 'hour'),
array(60 , 'minute'),
array(1 , 'second')
);
for ($i = 0, $j = count($chunks); $i < $j; $i++) {
$seconds = $chunks[$i][0];
$name = $chunks[$i][1];
if (($count = floor($since / $seconds)) != 0) {
break;
}
}
$print = ($count == 1) ? '1 '.$name : "$count {$name}s";
return $print;
}
```
The function takes the number of seconds as input and outputs text such as:
* 10 seconds
* 1 minute
etc |
18,754 | <p>I'm writing some documentation in Markdown, and creating a separate file for each section of the doc. I would like to be able to convert all the files to HTML in one go, but I can't find anyone else who has tried the same thing. I'm on a Mac, so I would think a simple bash script should be able to handle it, but I've never done anything in bash and haven't had any luck. It seems like it should be simple to write something so I could just run:</p>
<pre><code>markdown-batch ./*.markdown
</code></pre>
<p>Any ideas?</p>
| [
{
"answer_id": 18775,
"author": "Julio César",
"author_id": 2148,
"author_profile": "https://Stackoverflow.com/users/2148",
"pm_score": -1,
"selected": false,
"text": "<p>I use this in a .bat file:</p>\n\n<pre><code>@echo off\nfor %i in (*.txt) python markdown.py \"%i\"\n</code></pre>\n"
},
{
"answer_id": 18831,
"author": "Patrick McElhaney",
"author_id": 437,
"author_profile": "https://Stackoverflow.com/users/437",
"pm_score": 6,
"selected": true,
"text": "<p>This is how you would do it in Bash. </p>\n\n<pre><code>for i in ./*.markdown; do perl markdown.pl --html4tags $i > $i.html; done;\n</code></pre>\n\n<p>Of course, you need the <a href=\"http://daringfireball.net/projects/markdown/\" rel=\"noreferrer\">Markdown script</a>.</p>\n"
},
{
"answer_id": 18841,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 6,
"selected": false,
"text": "<p>Use <a href=\"https://github.com/jgm/pandoc\" rel=\"noreferrer\">pandoc</a> — it's a commandline tool that lets you convert from one format to another. This tool supports Markdown to HTML and back.</p>\n\n<p>E.g. to generate HTML from Markdown, run:</p>\n\n<pre><code>pandoc -f markdown index.md > index.html\n</code></pre>\n"
},
{
"answer_id": 40245401,
"author": "Bruce Zu",
"author_id": 913717,
"author_profile": "https://Stackoverflow.com/users/913717",
"pm_score": -1,
"selected": false,
"text": "<p>// using Bash in mac</p>\n\n<pre><code>for i in *.md; do asciidoc $i; done; \n</code></pre>\n"
},
{
"answer_id": 70998307,
"author": "np8",
"author_id": 3015186,
"author_profile": "https://Stackoverflow.com/users/3015186",
"pm_score": 0,
"selected": false,
"text": "<p>You can do this really easily with <strong><a href=\"https://code.visualstudio.com/\" rel=\"nofollow noreferrer\">VS Code</a></strong>. <em>(Well, this is not a command line tool, but proved itself to be super helpful.)</em></p>\n<ul>\n<li>Install the <a href=\"https://marketplace.visualstudio.com/items?itemName=yzhang.markdown-all-in-one\" rel=\"nofollow noreferrer\">Markdown All In One</a> extension by Yu Zhang</li>\n<li>Open the VS Code Command Palette (<code>Ctrl-Shift-P</code>), and select <code>Markdown All In One: Print documents to HTML (select a source folder)</code></li>\n<li><strong>Tip</strong>: If you want to make your export portable, you want to change absolute image paths to relative paths by using the following setting in your <code>settings.json</code> (<code>Ctrl-Shift-P</code> -> <code>Preferences: Open Settings (JSON)</code>)</li>\n</ul>\n<pre><code> "markdown.extension.print.absoluteImgPath": false\n</code></pre>\n<p>In this way, after conversion, just copy all non-markdown files (images) to the destination folder and the HTML pages are portable.</p>\n"
},
{
"answer_id": 73435178,
"author": "injashkin",
"author_id": 19661777,
"author_profile": "https://Stackoverflow.com/users/19661777",
"pm_score": 1,
"selected": false,
"text": "<p>If you have Node.js installed, then you can use the [MdPugToHtml] converter (<a href=\"https://www.npmjs.com/package/md-pug-to-html\" rel=\"nofollow noreferrer\">https://www.npmjs.com/package/md-pug-to-html</a>). It massively converts Markdown to Html. Moreover, it is possible to use Pug templates, but you can use them without templates.</p>\n<p>The conversion is performed in the terminal with just one command:</p>\n<pre><code>npx md-pug-to-html /home/content\n</code></pre>\n<p>where:</p>\n<ul>\n<li><code>npx</code> is an npm command that installs md-pug-to-html at the first launch, and then launches the md-pug-to-html converter.</li>\n<li><code>/home/content</code> is a directory with your Markdown files. You may have another one.</li>\n</ul>\n<p>The converter has various settings and can be used both in the CLI command line and has an API for use in applications.</p>\n<p>There is detailed documentation on the MdPugToHtml converter in <a href=\"https://github.com/injashkin/md-pug-to-html/blob/main/README.md\" rel=\"nofollow noreferrer\">English</a> and <a href=\"https://github.com/injashkin/md-pug-to-html/blob/main/README.ru.md\" rel=\"nofollow noreferrer\">Russian</a>.</p>\n"
}
] | 2008/08/20 | [
"https://Stackoverflow.com/questions/18754",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2185/"
] | I'm writing some documentation in Markdown, and creating a separate file for each section of the doc. I would like to be able to convert all the files to HTML in one go, but I can't find anyone else who has tried the same thing. I'm on a Mac, so I would think a simple bash script should be able to handle it, but I've never done anything in bash and haven't had any luck. It seems like it should be simple to write something so I could just run:
```
markdown-batch ./*.markdown
```
Any ideas? | This is how you would do it in Bash.
```
for i in ./*.markdown; do perl markdown.pl --html4tags $i > $i.html; done;
```
Of course, you need the [Markdown script](http://daringfireball.net/projects/markdown/). |
18,757 | <p>The Add view and the Edit view are often incredibly similar that it is unwarranted to write 2 views. As the app evolves you would be making the same changes to both.</p>
<p>However, there are usually subtle differences. For instance, a field might be read-only once it's been added, and if that field is a DropDownList you no longer need that List in the ViewData.</p>
<p>So, should I create a view data class which contains all the information for both views, where, depending on the operation you're performing, certain properties will be null?<br>
Should I include the operation in the view data as an enum?<br>
Should I surround all the subtle differences with <em><% if( ViewData.Model.Op == Ops.Editing ) { %></em> ?</p>
<p>Or is there a better way?</p>
| [
{
"answer_id": 18876,
"author": "Andrew Rimmer",
"author_id": 1982,
"author_profile": "https://Stackoverflow.com/users/1982",
"pm_score": 2,
"selected": false,
"text": "<p>I don't like the Views to become too complex, and so far I have tended to have separate views for Edit and Add. I use a user control to store the common elements to avoid repetition. Both of the views will be centered around the same ViewData, and I have a marker on my data to say whether the object is new or an existing object. </p>\n\n<p>This isn't any more elegant than what you have stipulated, so I wonder if any of the Django or Rails guys can provide any input. </p>\n\n<p>I love asp.net mvc but it is still maturing, and still needs more sugar adding to take away some of the friction of creating websites.</p>\n"
},
{
"answer_id": 18956,
"author": "Jim",
"author_id": 1208,
"author_profile": "https://Stackoverflow.com/users/1208",
"pm_score": 2,
"selected": false,
"text": "<p>I personally just prefer to use the if/else right there in the view. It helps me see everything going on in view at once. </p>\n\n<p>If you want to avoid the tag soup though, I would suggest creating a helper method. </p>\n\n<pre><code><%= Helper.ProfessionField() %>\n\nstring ProfessionField()\n{\n if(IsNewItem) { return /* some drop down code */ }\n else { return \"<p>\" + _profession+ \"</p>\"; } \n}\n</code></pre>\n"
},
{
"answer_id": 41866,
"author": "Ben Scheirman",
"author_id": 3381,
"author_profile": "https://Stackoverflow.com/users/3381",
"pm_score": 3,
"selected": false,
"text": "<p>It's pretty easy really. Let's assume you're editing a blog post.</p>\n\n<p>Here's your 2 actions for new/edit:</p>\n\n<pre><code>public class BlogController : Controller\n{\n public ActionResult New()\n {\n var post = new Post();\n return View(\"Edit\", post);\n }\n\n public ActionResult Edit(int id)\n {\n var post = _repository.Get(id);\n return View(post);\n }\n\n ....\n\n}\n</code></pre>\n\n<p>And here's the view:</p>\n\n<pre><code><% using(Html.Form(\"save\")) { %>\n<%= Html.Hidden(\"Id\") %>\n\n<label for=\"Title\">Title</label>\n<%= Html.TextBox(\"Title\") %>\n\n<label for=\"Body\">Body</label>\n<%= Html.TextArea(\"Body\") %>\n\n<%= Html.Submit(\"Submit\") %>\n<% } %>\n</code></pre>\n\n<p>And here's the Save action that the view submits to:</p>\n\n<pre><code>public ActionResult Save(int id, string title, string body)\n{\n var post = id == 0 ? new Post() : _repository.Get(id);\n post.Title = title;\n post.Body = body;\n\n _repository.Save(post);\n\n return RedirectToAction(\"list\");\n}\n</code></pre>\n"
},
{
"answer_id": 290841,
"author": "labilbe",
"author_id": 1195872,
"author_profile": "https://Stackoverflow.com/users/1195872",
"pm_score": 1,
"selected": false,
"text": "<p>You can specify a CustomViewData class and pass the parameters here.</p>\n\n<pre><code>\npublic class MyViewData {\n public bool IsReadOnly { get; set; }\n public ModelObject MyObject { get; set; }\n}\n</code></pre>\n\n<p>And both views should implement this ViewData.\nAs a result you can use provided IsReadOnly property to manage the UserControl result.</p>\n\n<p>As the controller uses this, you can unit test it and your views doesn't have implementation, so you can respect the MVC principles.</p>\n"
}
] | 2008/08/20 | [
"https://Stackoverflow.com/questions/18757",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1851/"
] | The Add view and the Edit view are often incredibly similar that it is unwarranted to write 2 views. As the app evolves you would be making the same changes to both.
However, there are usually subtle differences. For instance, a field might be read-only once it's been added, and if that field is a DropDownList you no longer need that List in the ViewData.
So, should I create a view data class which contains all the information for both views, where, depending on the operation you're performing, certain properties will be null?
Should I include the operation in the view data as an enum?
Should I surround all the subtle differences with *<% if( ViewData.Model.Op == Ops.Editing ) { %>* ?
Or is there a better way? | It's pretty easy really. Let's assume you're editing a blog post.
Here's your 2 actions for new/edit:
```
public class BlogController : Controller
{
public ActionResult New()
{
var post = new Post();
return View("Edit", post);
}
public ActionResult Edit(int id)
{
var post = _repository.Get(id);
return View(post);
}
....
}
```
And here's the view:
```
<% using(Html.Form("save")) { %>
<%= Html.Hidden("Id") %>
<label for="Title">Title</label>
<%= Html.TextBox("Title") %>
<label for="Body">Body</label>
<%= Html.TextArea("Body") %>
<%= Html.Submit("Submit") %>
<% } %>
```
And here's the Save action that the view submits to:
```
public ActionResult Save(int id, string title, string body)
{
var post = id == 0 ? new Post() : _repository.Get(id);
post.Title = title;
post.Body = body;
_repository.Save(post);
return RedirectToAction("list");
}
``` |
18,764 | <p>Since both a <code>Table Scan</code> and a <code>Clustered Index Scan</code> essentially scan all records in the table, why is a Clustered Index Scan supposedly better?</p>
<p>As an example - what's the performance difference between the following when there are many records?:</p>
<pre><code>declare @temp table(
SomeColumn varchar(50)
)
insert into @temp
select 'SomeVal'
select * from @temp
-----------------------------
declare @temp table(
RowID int not null identity(1,1) primary key,
SomeColumn varchar(50)
)
insert into @temp
select 'SomeVal'
select * from @temp
</code></pre>
| [
{
"answer_id": 18782,
"author": "DrPizza",
"author_id": 2131,
"author_profile": "https://Stackoverflow.com/users/2131",
"pm_score": -1,
"selected": false,
"text": "<p>A table scan has to examine every single row of the table. The clustered index scan only needs to scan the index. It doesn't scan every record in the table. That's the point, really, of indices.</p>\n"
},
{
"answer_id": 18807,
"author": "Stu",
"author_id": 414,
"author_profile": "https://Stackoverflow.com/users/414",
"pm_score": 3,
"selected": false,
"text": "<p><a href=\"http://msdn.microsoft.com/en-us/library/aa216840(SQL.80).aspx\" rel=\"noreferrer\">http://msdn.microsoft.com/en-us/library/aa216840(SQL.80).aspx</a></p>\n\n<p>The Clustered Index Scan logical and physical operator scans the clustered index specified in the Argument column. When an optional WHERE:() predicate is present, only those rows that satisfy the predicate are returned. If the Argument column contains the ORDERED clause, the query processor has requested that the rows' output be returned in the order in which the clustered index has sorted them. If the ORDERED clause is not present, the storage engine will scan the index in the optimal way (not guaranteeing the output to be sorted).</p>\n\n<p><a href=\"http://msdn.microsoft.com/en-us/library/aa178416(SQL.80).aspx\" rel=\"noreferrer\">http://msdn.microsoft.com/en-us/library/aa178416(SQL.80).aspx</a></p>\n\n<p>The Table Scan logical and physical operator retrieves all rows from the table specified in the Argument column. If a WHERE:() predicate appears in the Argument column, only those rows that satisfy the predicate are returned.</p>\n"
},
{
"answer_id": 18906,
"author": "Mark Brackett",
"author_id": 2199,
"author_profile": "https://Stackoverflow.com/users/2199",
"pm_score": 7,
"selected": true,
"text": "<p>In a table without a clustered index (a heap table), data pages are not linked together - so traversing pages requires a <a href=\"http://msdn.microsoft.com/en-us/library/ms188270.aspx\" rel=\"noreferrer\">lookup into the Index Allocation Map</a>.</p>\n\n<p>A clustered table, however, has it's <a href=\"http://msdn.microsoft.com/en-us/library/ms177443.aspx\" rel=\"noreferrer\">data pages linked in a doubly linked list</a> - making sequential scans a bit faster. Of course, in exchange, you have the overhead of dealing with keeping the data pages in order on <code>INSERT</code>, <code>UPDATE</code>, and <code>DELETE</code>. A heap table, however, requires a second write to the IAM.</p>\n\n<p>If your query has a <code>RANGE</code> operator (e.g.: <code>SELECT * FROM TABLE WHERE Id BETWEEN 1 AND 100</code>), then a clustered table (being in a guaranteed order) would be more efficient - as it could use the index pages to find the relevant data page(s). A heap would have to scan all rows, since it cannot rely on ordering.</p>\n\n<p>And, of course, a clustered index lets you do a CLUSTERED INDEX SEEK, which is pretty much optimal for performance...a heap with no indexes would always result in a table scan.</p>\n\n<p>So:</p>\n\n<ul>\n<li><p>For your example query where you select all rows, the only difference is the doubly linked list a clustered index maintains. This should make your clustered table just a tiny bit faster than a heap with a large number of rows.</p></li>\n<li><p>For a query with a <code>WHERE</code> clause that can be (at least partially) satisfied by the clustered index, you'll come out ahead because of the ordering - so you won't have to scan the entire table.</p></li>\n<li><p>For a query that is not satisified by the clustered index, you're pretty much even...again, the only difference being that doubly linked list for sequential scanning. In either case, you're suboptimal.</p></li>\n<li><p>For <code>INSERT</code>, <code>UPDATE</code>, and <code>DELETE</code> a heap may or may not win. The heap doesn't have to maintain order, but does require a second write to the IAM. I think the relative performance difference would be negligible, but also pretty data dependent.</p></li>\n</ul>\n\n<p>Microsoft has a <a href=\"http://www.microsoft.com/technet/prodtechnol/sql/bestpractice/clusivsh.mspx\" rel=\"noreferrer\">whitepaper</a> which compares a clustered index to an equivalent non-clustered index on a heap (not exactly the same as I discussed above, but close). Their conclusion is basically to put a clustered index on all tables. I'll do my best to summarize their results (again, note that they're really comparing a non-clustered index to a clustered index here - but I think it's relatively comparable):</p>\n\n<ul>\n<li><code>INSERT</code> performance: clustered index wins by about 3% due to the second write needed for a heap.</li>\n<li><code>UPDATE</code> performance: clustered index wins by about 8% due to the second lookup needed for a heap.</li>\n<li><code>DELETE</code> performance: clustered index wins by about 18% due to the second lookup needed and the second delete needed from the IAM for a heap.</li>\n<li>single <code>SELECT</code> performance: clustered index wins by about 16% due to the second lookup needed for a heap.</li>\n<li>range <code>SELECT</code> performance: clustered index wins by about 29% due to the random ordering for a heap.</li>\n<li>concurrent <code>INSERT</code>: heap table wins by 30% under load due to page splits for the clustered index.</li>\n</ul>\n"
}
] | 2008/08/20 | [
"https://Stackoverflow.com/questions/18764",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/357/"
] | Since both a `Table Scan` and a `Clustered Index Scan` essentially scan all records in the table, why is a Clustered Index Scan supposedly better?
As an example - what's the performance difference between the following when there are many records?:
```
declare @temp table(
SomeColumn varchar(50)
)
insert into @temp
select 'SomeVal'
select * from @temp
-----------------------------
declare @temp table(
RowID int not null identity(1,1) primary key,
SomeColumn varchar(50)
)
insert into @temp
select 'SomeVal'
select * from @temp
``` | In a table without a clustered index (a heap table), data pages are not linked together - so traversing pages requires a [lookup into the Index Allocation Map](http://msdn.microsoft.com/en-us/library/ms188270.aspx).
A clustered table, however, has it's [data pages linked in a doubly linked list](http://msdn.microsoft.com/en-us/library/ms177443.aspx) - making sequential scans a bit faster. Of course, in exchange, you have the overhead of dealing with keeping the data pages in order on `INSERT`, `UPDATE`, and `DELETE`. A heap table, however, requires a second write to the IAM.
If your query has a `RANGE` operator (e.g.: `SELECT * FROM TABLE WHERE Id BETWEEN 1 AND 100`), then a clustered table (being in a guaranteed order) would be more efficient - as it could use the index pages to find the relevant data page(s). A heap would have to scan all rows, since it cannot rely on ordering.
And, of course, a clustered index lets you do a CLUSTERED INDEX SEEK, which is pretty much optimal for performance...a heap with no indexes would always result in a table scan.
So:
* For your example query where you select all rows, the only difference is the doubly linked list a clustered index maintains. This should make your clustered table just a tiny bit faster than a heap with a large number of rows.
* For a query with a `WHERE` clause that can be (at least partially) satisfied by the clustered index, you'll come out ahead because of the ordering - so you won't have to scan the entire table.
* For a query that is not satisified by the clustered index, you're pretty much even...again, the only difference being that doubly linked list for sequential scanning. In either case, you're suboptimal.
* For `INSERT`, `UPDATE`, and `DELETE` a heap may or may not win. The heap doesn't have to maintain order, but does require a second write to the IAM. I think the relative performance difference would be negligible, but also pretty data dependent.
Microsoft has a [whitepaper](http://www.microsoft.com/technet/prodtechnol/sql/bestpractice/clusivsh.mspx) which compares a clustered index to an equivalent non-clustered index on a heap (not exactly the same as I discussed above, but close). Their conclusion is basically to put a clustered index on all tables. I'll do my best to summarize their results (again, note that they're really comparing a non-clustered index to a clustered index here - but I think it's relatively comparable):
* `INSERT` performance: clustered index wins by about 3% due to the second write needed for a heap.
* `UPDATE` performance: clustered index wins by about 8% due to the second lookup needed for a heap.
* `DELETE` performance: clustered index wins by about 18% due to the second lookup needed and the second delete needed from the IAM for a heap.
* single `SELECT` performance: clustered index wins by about 16% due to the second lookup needed for a heap.
* range `SELECT` performance: clustered index wins by about 29% due to the random ordering for a heap.
* concurrent `INSERT`: heap table wins by 30% under load due to page splits for the clustered index. |
18,765 | <p>I'm currently working on creating a new C# project that needs to interact with an older C++ application. There is an error enumeration that already exists in the C++ app that I need to use in the C# app.</p>
<p><em>I don't want to just re declare the enumeration in C# because that could cause sync issues down the line if the files aren't updated together</em>. </p>
<p>All that being said my question is this:
Is there a way for me to taken an enumeration declared like so:</p>
<pre><code>typedef enum
{
eDEVICEINT_ERR_FATAL = 0x10001
...
} eDeviceIntErrCodes;
</code></pre>
<p>and use it in a C# program like so:</p>
<pre><code>eDeviceIntErrCodes.eDEVICEINT_ERR_FATAL
</code></pre>
| [
{
"answer_id": 18774,
"author": "Adam Haile",
"author_id": 194,
"author_profile": "https://Stackoverflow.com/users/194",
"pm_score": 2,
"selected": false,
"text": "<p>Simple answer is going to be no. Sorry, you are going to have to re-declare.</p>\n\n<p>I have, in the past however, written scripts to import my C++ enums to a C# format in a enums.cs file and run it as part of the build, that way everything syncs.</p>\n"
},
{
"answer_id": 18786,
"author": "Brian Ensink",
"author_id": 1254,
"author_profile": "https://Stackoverflow.com/users/1254",
"pm_score": 5,
"selected": true,
"text": "<p>Check out the PInvoke Interop Assistant tool <a href=\"http://www.codeplex.com/clrinterop/Release/ProjectReleases.aspx?ReleaseId=14120\" rel=\"noreferrer\">http://www.codeplex.com/clrinterop/Release/ProjectReleases.aspx?ReleaseId=14120</a>. Its a useful tool for generating PInvoke signatures for native methods. </p>\n\n<p>If I feed it your enum it generates this code. There is a command line version of the tool included so you could potentially build an automated process to keep the C# definition of the enum up to date whenever the C++ version changes.</p>\n\n<pre><code>\n public enum eDeviceIntErrCodes \n {\n /// eDEVICEINT_ERR_FATAL -> 0x10001\n eDEVICEINT_ERR_FATAL = 65537,\n }\n</code></pre>\n"
},
{
"answer_id": 18798,
"author": "Joel Lucsy",
"author_id": 645,
"author_profile": "https://Stackoverflow.com/users/645",
"pm_score": 0,
"selected": false,
"text": "<p>If you had declared the enum like:</p>\n\n<pre><code>namespace blah\n{\n enum DEVICE_ERR_CODES\n {\n eDEVICEINT_ERR_FATAL = 0x10001,\n eDEVICEINT_ERR_OTHER = 0x10002,\n };\n}</code></pre>\n\n<p>and in another file:</p>\n\n<pre><code>DEVICE_ERR_CODES eDeviceIntErrCodes;</code></pre>\n\n<p>and named the enum file with a .cs extension, you might be able to get it to work.\nYou'd reference it like:</p>\n\n<pre><code>DEVICE_ERR_CODES err = DEVICE_ERR_CODES.eDEVICEINT_ERR_FATAL;</code></pre>\n"
},
{
"answer_id": 18870,
"author": "Rob",
"author_id": 1006,
"author_profile": "https://Stackoverflow.com/users/1006",
"pm_score": 4,
"selected": false,
"text": "<p>In C/C++ you can #include a .cs file which contains the enumeration definition. Careful use of preprocessor directives takes care of the syntax differences between C# and C.</p>\n\n<p>Example:</p>\n\n<pre><code>#if CSharp\nnamespace MyNamespace.SharedEnumerations\n{\npublic\n#endif\n\n\nenum MyFirstEnumeration\n{\n Autodetect = -1,\n Windows2000,\n WindowsXP,\n WindowsVista,\n OSX,\n Linux,\n\n // Count must be last entry - is used to determine number of items in the enum\n Count\n};\n#if CSharp\npublic \n#endif\n\nenum MessageLevel\n{\n None, // Message is ignored\n InfoMessage, // Message is written to info port.\n InfoWarning, // Message is written to info port and warning is issued\n Popup // User is alerted to the message\n};\n\n#if CSharp\n public delegate void MessageEventHandler(MessageLevel level, string message);\n}\n#endif\n</code></pre>\n\n<p>In your C# project, set a conditional compilation symbol \"CSharp\", make sure no such preprocessor definition exists in the C/C++ build environment.</p>\n\n<p>Note that this will only ensure both parts are syncronised at build time. If you mix-and-match binaries from different builds, the guarantee fails.</p>\n"
},
{
"answer_id": 51630980,
"author": "doosik71",
"author_id": 3763893,
"author_profile": "https://Stackoverflow.com/users/3763893",
"pm_score": 0,
"selected": false,
"text": "<p>If you define strong enum in C++/CLI, enum codes will be included in the dll meta data. So, you can use enum codes in C#.</p>\n\n<pre><code>public enum class eDeviceIntErrCodes: int\n{\n eDEVICEINT_ERR_FATAL = 0x10001\n ...\n};\n</code></pre>\n"
}
] | 2008/08/20 | [
"https://Stackoverflow.com/questions/18765",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2191/"
] | I'm currently working on creating a new C# project that needs to interact with an older C++ application. There is an error enumeration that already exists in the C++ app that I need to use in the C# app.
*I don't want to just re declare the enumeration in C# because that could cause sync issues down the line if the files aren't updated together*.
All that being said my question is this:
Is there a way for me to taken an enumeration declared like so:
```
typedef enum
{
eDEVICEINT_ERR_FATAL = 0x10001
...
} eDeviceIntErrCodes;
```
and use it in a C# program like so:
```
eDeviceIntErrCodes.eDEVICEINT_ERR_FATAL
``` | Check out the PInvoke Interop Assistant tool <http://www.codeplex.com/clrinterop/Release/ProjectReleases.aspx?ReleaseId=14120>. Its a useful tool for generating PInvoke signatures for native methods.
If I feed it your enum it generates this code. There is a command line version of the tool included so you could potentially build an automated process to keep the C# definition of the enum up to date whenever the C++ version changes.
```
public enum eDeviceIntErrCodes
{
/// eDEVICEINT_ERR_FATAL -> 0x10001
eDEVICEINT_ERR_FATAL = 65537,
}
``` |
18,787 | <p>When a controller renders a view based on a model you can get the properties from the ViewData collection using the indexer (ie. ViewData["Property"]). However, I have a shared user control that I tried to call using the following:</p>
<pre><code>return View("Message", new { DisplayMessage = "This is a test" });
</code></pre>
<p>and on my Message control I had this:</p>
<pre><code><%= ViewData["DisplayMessage"] %>
</code></pre>
<p>I would think this would render the DisplayMessage correctly, however, null is being returned. After a heavy dose of tinkering around, I finally created a "MessageData" class in order to strongly type my user control:</p>
<pre><code>public class MessageControl : ViewUserControl<MessageData>
</code></pre>
<p>and now this call works:</p>
<pre><code>return View("Message", new MessageData() { DisplayMessage = "This is a test" });
</code></pre>
<p>and can be displayed like this:</p>
<pre><code><%= ViewData.Model.DisplayMessage %>
</code></pre>
<p>Why wouldn't the DisplayMessage property be added to the ViewData (ie. ViewData["DisplayMessage"]) collection without strong typing the user control? Is this by design? Wouldn't it make sense that ViewData would contain a key for "DisplayMessage"?</p>
| [
{
"answer_id": 18830,
"author": "Ryan Eastabrook",
"author_id": 105,
"author_profile": "https://Stackoverflow.com/users/105",
"pm_score": 2,
"selected": false,
"text": "<p>Of course after I create this question I immediately find the answer after a few more searches on Google</p>\n\n<p><a href=\"http://forums.asp.net/t/1197059.aspx\" rel=\"nofollow noreferrer\">http://forums.asp.net/t/1197059.aspx</a></p>\n\n<p>Apparently this happens because of the wrapper class. Even so, it seems like any property passed should get added to the ViewData collection by default.</p>\n\n<p>I really need to stop answering my own questions :(</p>\n"
},
{
"answer_id": 31726,
"author": "Haacked",
"author_id": 598,
"author_profile": "https://Stackoverflow.com/users/598",
"pm_score": 4,
"selected": true,
"text": "<p>The method </p>\n\n<pre><code>ViewData.Eval(\"DisplayMessage\") \n</code></pre>\n\n<p>should work for you.</p>\n"
}
] | 2008/08/20 | [
"https://Stackoverflow.com/questions/18787",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/105/"
] | When a controller renders a view based on a model you can get the properties from the ViewData collection using the indexer (ie. ViewData["Property"]). However, I have a shared user control that I tried to call using the following:
```
return View("Message", new { DisplayMessage = "This is a test" });
```
and on my Message control I had this:
```
<%= ViewData["DisplayMessage"] %>
```
I would think this would render the DisplayMessage correctly, however, null is being returned. After a heavy dose of tinkering around, I finally created a "MessageData" class in order to strongly type my user control:
```
public class MessageControl : ViewUserControl<MessageData>
```
and now this call works:
```
return View("Message", new MessageData() { DisplayMessage = "This is a test" });
```
and can be displayed like this:
```
<%= ViewData.Model.DisplayMessage %>
```
Why wouldn't the DisplayMessage property be added to the ViewData (ie. ViewData["DisplayMessage"]) collection without strong typing the user control? Is this by design? Wouldn't it make sense that ViewData would contain a key for "DisplayMessage"? | The method
```
ViewData.Eval("DisplayMessage")
```
should work for you. |
18,836 | <p>I'm looking for shell scripts files installed on my system, but <strong>find</strong> doesn't work:</p>
<pre><code>$ find /usr -name *.sh
</code></pre>
<p>But I know there are a ton of scripts out there. For instance:</p>
<pre><code>$ ls /usr/local/lib/*.sh
/usr/local/lib/tclConfig.sh
/usr/local/lib/tkConfig.sh
</code></pre>
<p>Why doesn't <strong>find</strong> work?</p>
| [
{
"answer_id": 18837,
"author": "Jon Ericson",
"author_id": 1438,
"author_profile": "https://Stackoverflow.com/users/1438",
"pm_score": 7,
"selected": true,
"text": "<p>Try quoting the wildcard:</p>\n\n<pre><code>$ find /usr -name \\*.sh\n</code></pre>\n\n<p>or:</p>\n\n<pre><code>$ find /usr -name '*.sh'\n</code></pre>\n\n<p>If you happen to have a file that matches <strong>*.sh</strong> in the current working directory, the wildcard will be expanded before find sees it. If you happen to have a file named tkConfig.sh in your working directory, the <strong>find</strong> command would expand to:</p>\n\n<pre><code>$ find /usr -name tkConfig.sh\n</code></pre>\n\n<p>which would only find files named tkConfig.sh. If you had more than one file that matches <strong>*.sh</strong>, you'd get a syntax error from <strong>find</strong>:</p>\n\n<pre><code>$ cd /usr/local/lib\n$ find /usr -name *.sh\nfind: bad option tkConfig.sh\nfind: path-list predicate-list\n</code></pre>\n\n<p>Again, the reason is that the wildcard expands to both files:</p>\n\n<pre><code>$ find /usr -name tclConfig.sh tkConfig.sh\n</code></pre>\n\n<p>Quoting the wildcard prevents it from being prematurely expanded.</p>\n\n<p>Another possibility is that /usr or one of its subdirectories is a symlink. <strong>find</strong> doesn't normally follow links, so you might need the <strong>-follow</strong> option:</p>\n\n<pre><code>$ find /usr -follow -name '*.sh'\n</code></pre>\n"
},
{
"answer_id": 18843,
"author": "Mark Harrison",
"author_id": 116,
"author_profile": "https://Stackoverflow.com/users/116",
"pm_score": 4,
"selected": false,
"text": "<p>On some systems (Solaris, for example), there's no default action, so you need to add the -print command. </p>\n\n<pre><code>find /usr -name '*.foo' -print\n</code></pre>\n"
},
{
"answer_id": 476874,
"author": "Colas Nahaboo",
"author_id": 58468,
"author_profile": "https://Stackoverflow.com/users/58468",
"pm_score": 3,
"selected": false,
"text": "<p>For finding files on your disks, lean to use \"locate\" instead that is instantaneous\n(looks into a daily built index)\nyou example would be:</p>\n\n<pre><code>locate '/usr*.sh'\n</code></pre>\n"
}
] | 2008/08/20 | [
"https://Stackoverflow.com/questions/18836",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1438/"
] | I'm looking for shell scripts files installed on my system, but **find** doesn't work:
```
$ find /usr -name *.sh
```
But I know there are a ton of scripts out there. For instance:
```
$ ls /usr/local/lib/*.sh
/usr/local/lib/tclConfig.sh
/usr/local/lib/tkConfig.sh
```
Why doesn't **find** work? | Try quoting the wildcard:
```
$ find /usr -name \*.sh
```
or:
```
$ find /usr -name '*.sh'
```
If you happen to have a file that matches **\*.sh** in the current working directory, the wildcard will be expanded before find sees it. If you happen to have a file named tkConfig.sh in your working directory, the **find** command would expand to:
```
$ find /usr -name tkConfig.sh
```
which would only find files named tkConfig.sh. If you had more than one file that matches **\*.sh**, you'd get a syntax error from **find**:
```
$ cd /usr/local/lib
$ find /usr -name *.sh
find: bad option tkConfig.sh
find: path-list predicate-list
```
Again, the reason is that the wildcard expands to both files:
```
$ find /usr -name tclConfig.sh tkConfig.sh
```
Quoting the wildcard prevents it from being prematurely expanded.
Another possibility is that /usr or one of its subdirectories is a symlink. **find** doesn't normally follow links, so you might need the **-follow** option:
```
$ find /usr -follow -name '*.sh'
``` |
18,858 | <p>Does anyone here know of good batch file code indenters or beautifiers?</p>
<p>Specifically for PHP, JS and SGML-languages.</p>
<p>Preferably with options as to style.</p>
| [
{
"answer_id": 18837,
"author": "Jon Ericson",
"author_id": 1438,
"author_profile": "https://Stackoverflow.com/users/1438",
"pm_score": 7,
"selected": true,
"text": "<p>Try quoting the wildcard:</p>\n\n<pre><code>$ find /usr -name \\*.sh\n</code></pre>\n\n<p>or:</p>\n\n<pre><code>$ find /usr -name '*.sh'\n</code></pre>\n\n<p>If you happen to have a file that matches <strong>*.sh</strong> in the current working directory, the wildcard will be expanded before find sees it. If you happen to have a file named tkConfig.sh in your working directory, the <strong>find</strong> command would expand to:</p>\n\n<pre><code>$ find /usr -name tkConfig.sh\n</code></pre>\n\n<p>which would only find files named tkConfig.sh. If you had more than one file that matches <strong>*.sh</strong>, you'd get a syntax error from <strong>find</strong>:</p>\n\n<pre><code>$ cd /usr/local/lib\n$ find /usr -name *.sh\nfind: bad option tkConfig.sh\nfind: path-list predicate-list\n</code></pre>\n\n<p>Again, the reason is that the wildcard expands to both files:</p>\n\n<pre><code>$ find /usr -name tclConfig.sh tkConfig.sh\n</code></pre>\n\n<p>Quoting the wildcard prevents it from being prematurely expanded.</p>\n\n<p>Another possibility is that /usr or one of its subdirectories is a symlink. <strong>find</strong> doesn't normally follow links, so you might need the <strong>-follow</strong> option:</p>\n\n<pre><code>$ find /usr -follow -name '*.sh'\n</code></pre>\n"
},
{
"answer_id": 18843,
"author": "Mark Harrison",
"author_id": 116,
"author_profile": "https://Stackoverflow.com/users/116",
"pm_score": 4,
"selected": false,
"text": "<p>On some systems (Solaris, for example), there's no default action, so you need to add the -print command. </p>\n\n<pre><code>find /usr -name '*.foo' -print\n</code></pre>\n"
},
{
"answer_id": 476874,
"author": "Colas Nahaboo",
"author_id": 58468,
"author_profile": "https://Stackoverflow.com/users/58468",
"pm_score": 3,
"selected": false,
"text": "<p>For finding files on your disks, lean to use \"locate\" instead that is instantaneous\n(looks into a daily built index)\nyou example would be:</p>\n\n<pre><code>locate '/usr*.sh'\n</code></pre>\n"
}
] | 2008/08/20 | [
"https://Stackoverflow.com/questions/18858",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2118/"
] | Does anyone here know of good batch file code indenters or beautifiers?
Specifically for PHP, JS and SGML-languages.
Preferably with options as to style. | Try quoting the wildcard:
```
$ find /usr -name \*.sh
```
or:
```
$ find /usr -name '*.sh'
```
If you happen to have a file that matches **\*.sh** in the current working directory, the wildcard will be expanded before find sees it. If you happen to have a file named tkConfig.sh in your working directory, the **find** command would expand to:
```
$ find /usr -name tkConfig.sh
```
which would only find files named tkConfig.sh. If you had more than one file that matches **\*.sh**, you'd get a syntax error from **find**:
```
$ cd /usr/local/lib
$ find /usr -name *.sh
find: bad option tkConfig.sh
find: path-list predicate-list
```
Again, the reason is that the wildcard expands to both files:
```
$ find /usr -name tclConfig.sh tkConfig.sh
```
Quoting the wildcard prevents it from being prematurely expanded.
Another possibility is that /usr or one of its subdirectories is a symlink. **find** doesn't normally follow links, so you might need the **-follow** option:
```
$ find /usr -follow -name '*.sh'
``` |
18,861 | <p>So I am writing a registration form and I need the display name to be only numbers, letters and underscores. </p>
<p>Have a look at my code and tell me what I'm doing wrong.</p>
<pre><code><form method="post" action="/" onsubmit="return check_form()">
<input type="text" id="display-name" name="display-name" maxlength="255" />
<input type="submit" />
</form>
<script type="text/javascript">
<!--
var name_regex = /^([a-zA-Z0-9_])+/
function check_form()
{
if (!name_regex.test(document.forms[0].elements[0].value))
{
document.forms[0].elements[0].focus()
alert("Your display name may only contain letters, numbers and underscores")
return false
}
}
-->
</script>
</code></pre>
<p>It's obviously been trimmed down to not include anything not related to the problem but even this snippet doesn't work.</p>
| [
{
"answer_id": 18874,
"author": "AnnanFay",
"author_id": 2118,
"author_profile": "https://Stackoverflow.com/users/2118",
"pm_score": 3,
"selected": false,
"text": "<p>My regexp would go along the lines of: <code>/^[a-zA-Z0-9_]+$/</code></p>\n\n<p>edit: I think it's the lack of a line end <code>$</code> that makes it fail.</p>\n"
},
{
"answer_id": 18881,
"author": "samjudson",
"author_id": 1908,
"author_profile": "https://Stackoverflow.com/users/1908",
"pm_score": 0,
"selected": false,
"text": "<p>By 'not working' I take it you mean it is letting invalid entries through (rather than not letting valid entries through).</p>\n\n<p>As @Annan has said, this would probably be due to the lack of the <code>$</code> character at the end of the expression, as currently it only requires a single valid character at the start of the value, and the rest can be anything.</p>\n"
},
{
"answer_id": 18884,
"author": "Orion Edwards",
"author_id": 234,
"author_profile": "https://Stackoverflow.com/users/234",
"pm_score": 5,
"selected": true,
"text": "<p>Your regex</p>\n\n<pre><code>/^([a-zA-Z0-9_])+/\n</code></pre>\n\n<p>Looks for </p>\n\n<ol>\n<li>Start of string(check), followed by</li>\n<li>1 or more letters, numbers, or underscore (check)</li>\n</ol>\n\n<p>And then whatever comes after it doesn't matter. This regex will match anything at all so long as it begins with a letter, number, or underscore</p>\n\n<p>If you put a <code>$</code> at the end, then it will work - <code>$</code> matches 'end of string', so the only way it can match is if there are <em>only</em> numbers, letters, and underscores between the start and end of the string.</p>\n\n<pre><code>/^([a-zA-Z0-9_])+$/\n</code></pre>\n\n<p>Secondly, I'd suggest using <code>document.getElementById('display-name').value</code> instead of <code>document.forms</code> as it won't break if you rearrange the HTML, and is more 'the commonly accepted standard of what to do'</p>\n"
},
{
"answer_id": 18892,
"author": "Chris Conway",
"author_id": 1412,
"author_profile": "https://Stackoverflow.com/users/1412",
"pm_score": 0,
"selected": false,
"text": "<p>What does \"doesn't work\" mean? Does it reject valid display names? Does it accept invalid display names? Which ones?</p>\n\n<p>Per @Annan, leaving off the <code>$</code> would make the regexp accept invalid display names like <code>abc123!@#</code>.</p>\n\n<p>If the code is rejecting valid display names, it may be because the parentheses are being matched literally instead of denoting a group (I'm not sure of the quoting convention in JS).</p>\n"
},
{
"answer_id": 18903,
"author": "Andy",
"author_id": 1993,
"author_profile": "https://Stackoverflow.com/users/1993",
"pm_score": 0,
"selected": false,
"text": "<p>I tested your script and meddled with the javascript. This seem to work: </p>\n\n<pre><code><form method=\"post\" action=\"/\" onsubmit=\"return check_form()\">\n <input type=\"text\" id=\"display-name\" name=\"display-name\" maxlength=\"255\" />\n <input type=\"submit\" />\n</form>\n<script type=\"text/javascript\">\n <!--\n var name_regex = /^([a-zA-Z0-9_])+$/;\n\n function check_form()\n {\n if (!name_regex.test(document.forms[0].elements[0].value))\n {\n document.forms[0].elements[0].focus();\n alert(\"Your display name may only contain letters, numbers and underscores\");\n return false;\n }\n }\n -->\n</script>\n</code></pre>\n"
},
{
"answer_id": 18997,
"author": "Andrew G. Johnson",
"author_id": 428190,
"author_profile": "https://Stackoverflow.com/users/428190",
"pm_score": 0,
"selected": false,
"text": "<p>Sorry guys I should have been more specific. Whenever I added spaces the values were still being accepted. The dollar sign <code>$</code> did the trick!</p>\n"
},
{
"answer_id": 19026,
"author": "Robert Swisher",
"author_id": 1852,
"author_profile": "https://Stackoverflow.com/users/1852",
"pm_score": 0,
"selected": false,
"text": "<p>A simpler way to write it still would be</p>\n\n<pre><code>var name_regex = /^([a-z0-9_])+$/i;\n</code></pre>\n"
},
{
"answer_id": 19341,
"author": "travis",
"author_id": 1414,
"author_profile": "https://Stackoverflow.com/users/1414",
"pm_score": 0,
"selected": false,
"text": "<p>Even simpler:</p>\n\n<pre><code>var name_regex = /^\\w+$/;\n</code></pre>\n"
}
] | 2008/08/20 | [
"https://Stackoverflow.com/questions/18861",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/428190/"
] | So I am writing a registration form and I need the display name to be only numbers, letters and underscores.
Have a look at my code and tell me what I'm doing wrong.
```
<form method="post" action="/" onsubmit="return check_form()">
<input type="text" id="display-name" name="display-name" maxlength="255" />
<input type="submit" />
</form>
<script type="text/javascript">
<!--
var name_regex = /^([a-zA-Z0-9_])+/
function check_form()
{
if (!name_regex.test(document.forms[0].elements[0].value))
{
document.forms[0].elements[0].focus()
alert("Your display name may only contain letters, numbers and underscores")
return false
}
}
-->
</script>
```
It's obviously been trimmed down to not include anything not related to the problem but even this snippet doesn't work. | Your regex
```
/^([a-zA-Z0-9_])+/
```
Looks for
1. Start of string(check), followed by
2. 1 or more letters, numbers, or underscore (check)
And then whatever comes after it doesn't matter. This regex will match anything at all so long as it begins with a letter, number, or underscore
If you put a `$` at the end, then it will work - `$` matches 'end of string', so the only way it can match is if there are *only* numbers, letters, and underscores between the start and end of the string.
```
/^([a-zA-Z0-9_])+$/
```
Secondly, I'd suggest using `document.getElementById('display-name').value` instead of `document.forms` as it won't break if you rearrange the HTML, and is more 'the commonly accepted standard of what to do' |
18,912 | <p>I know in JavaScript, <em>objects</em> double as hashes, but I have been unable to find a built-in function to get the keys:</p>
<pre><code>var h = {a:'b', c:'d'};
</code></pre>
<p>I want something like</p>
<pre><code>var k = h.keys() ; // k = ['a', 'c'];
</code></pre>
<p>It is simple to write a function myself to iterate over the items and add the keys to an array that I return, but is there a standard cleaner way to do that?</p>
<p>I keep feeling it must be a simple built in function that I missed but I can't find it!</p>
| [
{
"answer_id": 18929,
"author": "danb",
"author_id": 2031,
"author_profile": "https://Stackoverflow.com/users/2031",
"pm_score": 4,
"selected": false,
"text": "<p>This is the best you can do, as far as I know...</p>\n\n<pre><code>var keys = [];\nfor (var k in h)keys.push(k);\n</code></pre>\n"
},
{
"answer_id": 18930,
"author": "palmsey",
"author_id": 521,
"author_profile": "https://Stackoverflow.com/users/521",
"pm_score": 3,
"selected": false,
"text": "<p>I believe you can loop through the properties of the object using for/in, so you could do something like this:</p>\n\n<pre><code>function getKeys(h) {\n Array keys = new Array();\n for (var key in h)\n keys.push(key);\n return keys;\n}\n</code></pre>\n"
},
{
"answer_id": 18941,
"author": "AnnanFay",
"author_id": 2118,
"author_profile": "https://Stackoverflow.com/users/2118",
"pm_score": 6,
"selected": false,
"text": "<p>For production code requiring a large compatibility with client browsers I still suggest <a href=\"https://stackoverflow.com/questions/18912/how-can-i-find-the-keys-of-a-hash/6921193#6921193\">Ivan Nevostruev's answer</a> with shim to ensure <code>Object.keys</code> in older browsers. However, it's possible to get the exact functionality requested using ECMA's new <code>defineProperty</code> feature.</p>\n<p><strong>As of ECMAScript 5 - Object.defineProperty</strong></p>\n<p>As of ECMA5 you can use <a href=\"https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/Object/defineProperty\" rel=\"nofollow noreferrer\"><code>Object.defineProperty()</code></a> to define non-enumerable properties. The <a href=\"http://kangax.github.io/compat-table/es5/#test-Object.defineProperty\" rel=\"nofollow noreferrer\"><strong>current compatibility</strong></a> still has much to be desired, but this should eventually become usable in all browsers. (Specifically note the current incompatibility with IE8!)</p>\n<pre><code>Object.defineProperty(Object.prototype, 'keys', {\n value: function keys() {\n var keys = [];\n for(var i in this) if (this.hasOwnProperty(i)) {\n keys.push(i);\n }\n return keys;\n },\n enumerable: false\n});\n\nvar o = {\n 'a': 1,\n 'b': 2\n}\n\nfor (var k in o) {\n console.log(k, o[k])\n}\n\nconsole.log(o.keys())\n\n# OUTPUT\n# > a 1\n# > b 2\n# > ["a", "b"]\n</code></pre>\n<p>However, since ECMA5 already added <code>Object.keys</code> you might as well use:</p>\n<pre><code>Object.defineProperty(Object.prototype, 'keys', {\n value: function keys() {\n return Object.keys(this);\n },\n enumerable: false\n});\n</code></pre>\n<p><strong>Original answer</strong></p>\n<pre><code>Object.prototype.keys = function ()\n{\n var keys = [];\n for(var i in this) if (this.hasOwnProperty(i))\n {\n keys.push(i);\n }\n return keys;\n}\n</code></pre>\n<hr />\n<p><strong>Edit:</strong> Since this answer has been around for a while I'll leave the above untouched. Anyone reading this should also read Ivan Nevostruev's answer below.</p>\n<p>There's no way of making prototype functions non-enumerable which leads to them always turning up in for-in loops that don't use <code>hasOwnProperty</code>. I still think this answer would be ideal if extending the prototype of Object wasn't so messy.</p>\n"
},
{
"answer_id": 3325571,
"author": "Matthew Darwin",
"author_id": 218940,
"author_profile": "https://Stackoverflow.com/users/218940",
"pm_score": 2,
"selected": false,
"text": "<p>I wanted to use <a href=\"https://stackoverflow.com/questions/18912/how-can-i-find-the-keys-of-a-hash/18941#18941\">AnnanFay's answer</a>:</p>\n<pre><code>Object.prototype.keys = function () ...\n</code></pre>\n<p>However, when using it in conjunction with the <a href=\"https://en.wikipedia.org/wiki/Google_Maps\" rel=\"nofollow noreferrer\">Google Maps</a> API v3, Google Maps is non-functional.</p>\n<p>However,</p>\n<pre><code>for (var key in h) ...\n</code></pre>\n<p>works well.</p>\n"
},
{
"answer_id": 6921193,
"author": "Ivan Nevostruev",
"author_id": 93988,
"author_profile": "https://Stackoverflow.com/users/93988",
"pm_score": 9,
"selected": true,
"text": "<p>There is function in modern JavaScript (ECMAScript 5) called <a href=\"https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Object/keys\" rel=\"noreferrer\"><code>Object.keys</code></a> performing this operation:</p>\n\n<pre><code>var obj = { \"a\" : 1, \"b\" : 2, \"c\" : 3};\nalert(Object.keys(obj)); // will output [\"a\", \"b\", \"c\"]\n</code></pre>\n\n<p>Compatibility details can be found <a href=\"http://kangax.github.com/es5-compat-table/\" rel=\"noreferrer\">here</a>. </p>\n\n<p>On the <a href=\"https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Object/keys\" rel=\"noreferrer\">Mozilla site</a> there is also a snippet for backward compatibility:</p>\n\n<pre><code>if(!Object.keys) Object.keys = function(o){\n if (o !== Object(o))\n throw new TypeError('Object.keys called on non-object');\n var ret=[],p;\n for(p in o) if(Object.prototype.hasOwnProperty.call(o,p)) ret.push(p);\n return ret;\n}\n</code></pre>\n"
},
{
"answer_id": 7027468,
"author": "timotti",
"author_id": 751340,
"author_profile": "https://Stackoverflow.com/users/751340",
"pm_score": 5,
"selected": false,
"text": "<p>You could use <a href=\"http://documentcloud.github.com/underscore/#keys\" rel=\"nofollow noreferrer\">Underscore.js</a>, which is a JavaScript utility library.</p>\n<pre><code>_.keys({one : 1, two : 2, three : 3});\n// => ["one", "two", "three"]\n</code></pre>\n"
},
{
"answer_id": 9293357,
"author": "chim",
"author_id": 673282,
"author_profile": "https://Stackoverflow.com/users/673282",
"pm_score": 3,
"selected": false,
"text": "<p>Using <a href=\"https://jquery.com/\" rel=\"nofollow noreferrer\">jQuery</a>, you can get the keys like this:</p>\n<pre><code>var bobject = {primary:"red", bg:"maroon", hilite:"green"};\nvar keys = [];\n$.each(bobject, function(key, val){ keys.push(key); });\nconsole.log(keys); // ["primary", "bg", "hilite"]\n</code></pre>\n<p>Or:</p>\n<pre><code>var bobject = {primary:"red", bg:"maroon", hilite:"green"};\n$.map(bobject, function(v, k){return k;});\n</code></pre>\n<p>Thanks to @pimlottc.</p>\n"
},
{
"answer_id": 9513780,
"author": "zeacuss",
"author_id": 312329,
"author_profile": "https://Stackoverflow.com/users/312329",
"pm_score": 1,
"selected": false,
"text": "<p>If you are trying to get the elements only, but not the functions then this code can help you:</p>\n<pre><code>this.getKeys = function() {\n\n var keys = new Array();\n for (var key in this) {\n\n if (typeof this[key] !== 'function') {\n\n keys.push(key);\n }\n }\n return keys;\n}\n</code></pre>\n<p>This is part of my implementation of the HashMap and I only want the keys. <code>this</code> is the hashmap object that contains the keys.</p>\n"
},
{
"answer_id": 18153555,
"author": "Leticia Santos",
"author_id": 2655009,
"author_profile": "https://Stackoverflow.com/users/2655009",
"pm_score": 5,
"selected": false,
"text": "<p>You can use <code>Object.keys</code>:</p>\n<pre><code>Object.keys(h)\n</code></pre>\n"
},
{
"answer_id": 72699782,
"author": "Mouzam Ali",
"author_id": 7188711,
"author_profile": "https://Stackoverflow.com/users/7188711",
"pm_score": 1,
"selected": false,
"text": "<p>In Javascript we can use</p>\n<pre><code>Object.keys(h)\n</code></pre>\n"
}
] | 2008/08/20 | [
"https://Stackoverflow.com/questions/18912",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/238/"
] | I know in JavaScript, *objects* double as hashes, but I have been unable to find a built-in function to get the keys:
```
var h = {a:'b', c:'d'};
```
I want something like
```
var k = h.keys() ; // k = ['a', 'c'];
```
It is simple to write a function myself to iterate over the items and add the keys to an array that I return, but is there a standard cleaner way to do that?
I keep feeling it must be a simple built in function that I missed but I can't find it! | There is function in modern JavaScript (ECMAScript 5) called [`Object.keys`](https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Object/keys) performing this operation:
```
var obj = { "a" : 1, "b" : 2, "c" : 3};
alert(Object.keys(obj)); // will output ["a", "b", "c"]
```
Compatibility details can be found [here](http://kangax.github.com/es5-compat-table/).
On the [Mozilla site](https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Object/keys) there is also a snippet for backward compatibility:
```
if(!Object.keys) Object.keys = function(o){
if (o !== Object(o))
throw new TypeError('Object.keys called on non-object');
var ret=[],p;
for(p in o) if(Object.prototype.hasOwnProperty.call(o,p)) ret.push(p);
return ret;
}
``` |
18,918 | <p>Im testing an ASP.NEt site. When I execute it, it starts the ASP.NET Development Server and opens up a page.</p>
<p>Now I want to test it in the intranet I have. </p>
<ol>
<li><p>Can I use this server or I need to configure IIS in this machine? </p></li>
<li><p>Do I need to configure something for it to work?</p></li>
</ol>
<p>I've changed the localhost to the correct IP and I opened up the firewall.</p>
<p>Thanks</p>
| [
{
"answer_id": 18919,
"author": "Jason",
"author_id": 1338,
"author_profile": "https://Stackoverflow.com/users/1338",
"pm_score": 1,
"selected": false,
"text": "<p>I believe the built in ASP.NET server only works on localhost. You'll have to use IIS.</p>\n"
},
{
"answer_id": 18925,
"author": "Jon Galloway",
"author_id": 5,
"author_profile": "https://Stackoverflow.com/users/5",
"pm_score": 4,
"selected": false,
"text": "<p>No, you can't. It's set up so it only works on localhost, and I couldn't find any workarounds to make it work.</p>\n\n<p>But, here's what I've been doing - I created the website on a specific port in IIS and opened that port up so it's visible on the network. I pointed that IIS website to my website's root folder (the one with web.config in it). Then I continued to use the ASP.NET Development server on that local machine while developing - both IIS and the ASP.NET Development Server can access the files at the same time (unless you're doing something wacky).</p>\n\n<p>Let me know if there's a challenge with running IIS on your machine and I'll update my answer.</p>\n"
},
{
"answer_id": 18939,
"author": "Mark Brackett",
"author_id": 2199,
"author_profile": "https://Stackoverflow.com/users/2199",
"pm_score": 2,
"selected": false,
"text": "<p>You can recompile Cassini to get it to work - there's a fairly easy to remove check for localhost in there. Or, I'm pretty sure <a href=\"http://www.ultidev.com/products/Cassini/\" rel=\"nofollow noreferrer\">Ultidev's Cassini</a> doesn't have this restriction. Both of these are easier to setup than IIS.</p>\n\n<p>But, yeah, the builtin WebDev.WebServer doesn't work....Hmm, unless you run something like <a href=\"http://www.analogx.com/contents/download/network/proxy.htm\" rel=\"nofollow noreferrer\">AnalogX's Proxy</a> on your dev box and point it to the WebDev port. That should work (though I haven't tried it, it should take < 2 mins to setup).</p>\n"
},
{
"answer_id": 3283913,
"author": "Pete Hodgson",
"author_id": 53529,
"author_profile": "https://Stackoverflow.com/users/53529",
"pm_score": 3,
"selected": false,
"text": "<p>I realize this isn't a direct answer to your question, but an alternative to debugging using the ASP development server is to attach to the IIS process: <a href=\"https://stackoverflow.com/questions/210250/how-do-i-attach-the-debugger-to-iis-instead-of-asp-net-development-server\">How do I attach the debugger to IIS instead of ASP.NET Development Server?</a></p>\n"
},
{
"answer_id": 3404898,
"author": "Jez",
"author_id": 178757,
"author_profile": "https://Stackoverflow.com/users/178757",
"pm_score": 3,
"selected": false,
"text": "<p>Nope, stupidly (IMHO) there's no way to get the default ASP.net development server to serve pages to IPs other than localhost. What I did was to use <a href=\"http://www.ultidev.com/products/Cassini/\" rel=\"noreferrer\">UltiDev Cassini</a> which is very quick to set up and is basically a version of the ASP.net development server compiled by UltiDev, and it will serve pages to any IP address.</p>\n"
},
{
"answer_id": 5812758,
"author": "koush",
"author_id": 704837,
"author_profile": "https://Stackoverflow.com/users/704837",
"pm_score": 2,
"selected": false,
"text": "<p>You can use Cassini to expose your web apps externally. You just need to proxy the connection. I wrote a simple program to do this that you can run in another VS instance. Just change the port to match the port Cassini is using.</p>\n\n<p><a href=\"https://gist.github.com/945649\" rel=\"nofollow\">https://gist.github.com/945649</a></p>\n"
},
{
"answer_id": 6152011,
"author": "Sebastien GISSINGER",
"author_id": 606648,
"author_profile": "https://Stackoverflow.com/users/606648",
"pm_score": 2,
"selected": false,
"text": "<p>You can do port redirection using <a href=\"http://www.microsoft.com/downloads/en/details.aspx?FamilyID=c943c0dd-ceec-4088-9753-86f052ec8450\" rel=\"nofollow\">SOAP Toolkit 3.0</a></p>\n\n<p>Once installed, go to My Programs > Microsoft Soap Toolkit 3 > Trace Utility</p>\n\n<p>Once Trace Utility opened, go to File > New > Formatted Trace</p>\n\n<p>In the dialog insert your ASP .NET Development Server port in Forward To Destination Port field.</p>\n\n<p>It's only a workaround for testing purposes</p>\n"
},
{
"answer_id": 7394935,
"author": "strongriley",
"author_id": 561956,
"author_profile": "https://Stackoverflow.com/users/561956",
"pm_score": 7,
"selected": true,
"text": "<p><strong>Yes you can! And you don't need IIS</strong></p>\n\n<p>Just use a simple Java TCP tunnel. Download this Java app & just tunnel the traffic back.\n<a href=\"http://jcbserver.uwaterloo.ca/cs436/software/tgui/tcpTunnelGUI.shtml\" rel=\"nofollow noreferrer\">http://jcbserver.uwaterloo.ca/cs436/software/tgui/tcpTunnelGUI.shtml</a></p>\n\n<p>In command prompt, you'd then run the java app like this... Let's assume you want external access on port 80 and your standard debug environment runs on port 1088...</p>\n\n<pre><code>java -jar tunnel.jar 80 localhost 1088\n</code></pre>\n\n<p>(Also answered here: <a href=\"https://stackoverflow.com/questions/1555058/accessing-asp-net-development-server-external-to-vm/7394823#7394823\">Accessing asp. net development server external to VM</a>)</p>\n"
},
{
"answer_id": 10656521,
"author": "gvelasquez85",
"author_id": 1403861,
"author_profile": "https://Stackoverflow.com/users/1403861",
"pm_score": 1,
"selected": false,
"text": "<p>Compile all you website in Debug mode, then create the website and publish it in IIS (make sure you can view it from other machine). Then attach the VS2010 Debugger to the process with the AppPool of your website (the process is called w3wp.exe when IIS>v5 and aspnet_wp.exe when IIS<5).</p>\n\n<p>If you make some changes, just replace the package contents on the physical path of the website, and there you go again.</p>\n"
},
{
"answer_id": 12008223,
"author": "deive",
"author_id": 1552178,
"author_profile": "https://Stackoverflow.com/users/1552178",
"pm_score": 2,
"selected": false,
"text": "<p>Just for those who don't want/cant set up IIS for whatever reason...</p>\n\n<p>Use fiddler or similar on your host - set your browser on the client VM to use the proxy then just use localhost:dev_port as usual on the client.</p>\n\n<p>All requests from the client goto the proxy on your dev machine which routes to localhost on the dev machine and the ASP.net dev server thinks the request is from your dev machine!</p>\n"
}
] | 2008/08/20 | [
"https://Stackoverflow.com/questions/18918",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1013/"
] | Im testing an ASP.NEt site. When I execute it, it starts the ASP.NET Development Server and opens up a page.
Now I want to test it in the intranet I have.
1. Can I use this server or I need to configure IIS in this machine?
2. Do I need to configure something for it to work?
I've changed the localhost to the correct IP and I opened up the firewall.
Thanks | **Yes you can! And you don't need IIS**
Just use a simple Java TCP tunnel. Download this Java app & just tunnel the traffic back.
<http://jcbserver.uwaterloo.ca/cs436/software/tgui/tcpTunnelGUI.shtml>
In command prompt, you'd then run the java app like this... Let's assume you want external access on port 80 and your standard debug environment runs on port 1088...
```
java -jar tunnel.jar 80 localhost 1088
```
(Also answered here: [Accessing asp. net development server external to VM](https://stackoverflow.com/questions/1555058/accessing-asp-net-development-server-external-to-vm/7394823#7394823)) |
18,920 | <p>When opening a file from your hard drive into your browser, where is the document root? To illustrate, given the following HTML code, if the page is opened from the local machine <code>(file:///)</code> then where should the <code>css</code> file be for the browser to find it?</p>
<pre><code><link href="/temp/test.css" rel="stylesheet" type="text/css" />
</code></pre>
| [
{
"answer_id": 18924,
"author": "Andy",
"author_id": 1993,
"author_profile": "https://Stackoverflow.com/users/1993",
"pm_score": 3,
"selected": true,
"text": "<p>It depends on what browser you use, but Internet Explorer, for example, would take you to the root directory of your harddrive (eg. <code>C:/</code>), while browsers such as Firefox does nothing. </p>\n"
},
{
"answer_id": 19301,
"author": "Mario Marinato",
"author_id": 431,
"author_profile": "https://Stackoverflow.com/users/431",
"pm_score": 0,
"selected": false,
"text": "<p>Eric, the document root is the folder in which your file is, wherever it may be.</p>\n"
},
{
"answer_id": 19338,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 1,
"selected": false,
"text": "<p>On a Mac, the document root is what you see in the window that appears after you double click on the main hard drive icon on your desktop. The temp folder needs to be in there for a browser to find the CSS file as you have it written in your code. </p>\n\n<p>Actually, you could also write the code like this:</p>\n\n<pre><code><link href=\"file:///temp/test.css\" rel=\"stylesheet\" type=\"text/css\" />\n</code></pre>\n"
},
{
"answer_id": 27725,
"author": "Sam Murray-Sutton",
"author_id": 2977,
"author_profile": "https://Stackoverflow.com/users/2977",
"pm_score": 0,
"selected": false,
"text": "<p>As far as local, static html goes, unless you specify it, most browsers will take the location of the html file you are viewing as the root. So any css put in there can just be referenced by it's name only. </p>\n\n<p>The lazy way to get the correct reference for your css file is to open it in your browser. Then just grab the url that you see there - something like: <pre>file:///blah/test.css</pre> and copy that into your stylesheet link on your html: <pre><code><link href=\"file:///blah/test.css\" rel=\"stylesheet\" type=\"text/css\"></code></pre></p>\n\n<p>Either that or you can just take the url for the html file and amend it to refer to the stylesheet.</p>\n\n<p>Then your local page should load fine with the local stylesheet.</p>\n"
},
{
"answer_id": 27728,
"author": "Brian Warshaw",
"author_id": 1344,
"author_profile": "https://Stackoverflow.com/users/1344",
"pm_score": 0,
"selected": false,
"text": "<p>If you're interested in setting the document root, you might look at getting a web server installed on your machine, or, if you already have one (like Apache or IIS), storing your project-in-development in the web root of that server (htdocs in Apache, not entirely sure in IIS). If you'd rather leave your files where they are, you can set up virtual hosts and even map them to addresses that you can type into your browser (for example, I have a local.mrwarshaw.com address that resolves to the web root of my personal site's development folder).</p>\n\n<p>If you're on Windows and don't want to mess around with setting up a server on your own, you could get a package like XAMPP or WAMPP, though bear in mind that those carry the extra weight of PHP and MySQL with them. Still, if you've got the space, they're a pretty easy drop-in development environment for your machine.</p>\n"
},
{
"answer_id": 38377,
"author": "bstark",
"author_id": 4056,
"author_profile": "https://Stackoverflow.com/users/4056",
"pm_score": 4,
"selected": false,
"text": "<p>You <i>can</i>, but probably don't want to, set the document root on a per-file basis in the head of your file:</p>\n\n<pre>\n<base href=\"my-root\">\n</pre>\n"
}
] | 2008/08/20 | [
"https://Stackoverflow.com/questions/18920",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1858/"
] | When opening a file from your hard drive into your browser, where is the document root? To illustrate, given the following HTML code, if the page is opened from the local machine `(file:///)` then where should the `css` file be for the browser to find it?
```
<link href="/temp/test.css" rel="stylesheet" type="text/css" />
``` | It depends on what browser you use, but Internet Explorer, for example, would take you to the root directory of your harddrive (eg. `C:/`), while browsers such as Firefox does nothing. |
18,932 | <p>I need to remove duplicate rows from a fairly large SQL Server table (i.e. 300,000+ rows).</p>
<p>The rows, of course, will not be perfect duplicates because of the existence of the <code>RowID</code> identity field.</p>
<p><strong>MyTable</strong></p>
<pre><code>RowID int not null identity(1,1) primary key,
Col1 varchar(20) not null,
Col2 varchar(2048) not null,
Col3 tinyint not null
</code></pre>
<p>How can I do this?</p>
| [
{
"answer_id": 18934,
"author": "Jon Galloway",
"author_id": 5,
"author_profile": "https://Stackoverflow.com/users/5",
"pm_score": 7,
"selected": false,
"text": "<p>There's a good article on <a href=\"http://support.microsoft.com/kb/139444\" rel=\"noreferrer\">removing duplicates</a> on the Microsoft Support site. It's pretty conservative - they have you do everything in separate steps - but it should work well against large tables.</p>\n\n<p>I've used self-joins to do this in the past, although it could probably be prettied up with a HAVING clause:</p>\n\n<pre><code>DELETE dupes\nFROM MyTable dupes, MyTable fullTable\nWHERE dupes.dupField = fullTable.dupField \nAND dupes.secondDupField = fullTable.secondDupField \nAND dupes.uniqueField > fullTable.uniqueField\n</code></pre>\n"
},
{
"answer_id": 18947,
"author": "Craig",
"author_id": 1611,
"author_profile": "https://Stackoverflow.com/users/1611",
"pm_score": 4,
"selected": false,
"text": "<p>Here is another good article on <a href=\"http://www.xaprb.com/blog/2007/02/06/how-to-delete-duplicate-rows-with-sql-part-2/\" rel=\"noreferrer\">removing duplicates</a>.</p>\n\n<p>It discusses why its hard: \"<em>SQL is based on relational algebra, and duplicates cannot occur in relational algebra, because duplicates are not allowed in a set.</em>\"</p>\n\n<p>The temp table solution, and two mysql examples.</p>\n\n<p>In the future are you going to prevent it at a database level, or from an application perspective. I would suggest the database level because your database should be responsible for maintaining referential integrity, developers just will cause problems ;)</p>\n"
},
{
"answer_id": 18949,
"author": "Mark Brackett",
"author_id": 2199,
"author_profile": "https://Stackoverflow.com/users/2199",
"pm_score": 11,
"selected": true,
"text": "<p>Assuming no nulls, you <code>GROUP BY</code> the unique columns, and <code>SELECT</code> the <code>MIN (or MAX)</code> RowId as the row to keep. Then, just delete everything that didn't have a row id:</p>\n\n<pre><code>DELETE FROM MyTable\nLEFT OUTER JOIN (\n SELECT MIN(RowId) as RowId, Col1, Col2, Col3 \n FROM MyTable \n GROUP BY Col1, Col2, Col3\n) as KeepRows ON\n MyTable.RowId = KeepRows.RowId\nWHERE\n KeepRows.RowId IS NULL\n</code></pre>\n\n<p>In case you have a GUID instead of an integer, you can replace</p>\n\n<pre><code>MIN(RowId)\n</code></pre>\n\n<p>with</p>\n\n<pre><code>CONVERT(uniqueidentifier, MIN(CONVERT(char(36), MyGuidColumn)))\n</code></pre>\n"
},
{
"answer_id": 18983,
"author": "Jacob Proffitt",
"author_id": 1336,
"author_profile": "https://Stackoverflow.com/users/1336",
"pm_score": 4,
"selected": false,
"text": "<p>Oh sure. Use a temp table. If you want a single, not-very-performant statement that \"works\" you can go with:</p>\n\n<pre><code>DELETE FROM MyTable WHERE NOT RowID IN\n (SELECT \n (SELECT TOP 1 RowID FROM MyTable mt2 \n WHERE mt2.Col1 = mt.Col1 \n AND mt2.Col2 = mt.Col2 \n AND mt2.Col3 = mt.Col3) \n FROM MyTable mt)\n</code></pre>\n\n<p>Basically, for each row in the table, the sub-select finds the top RowID of all rows that are exactly like the row under consideration. So you end up with a list of RowIDs that represent the \"original\" non-duplicated rows.</p>\n"
},
{
"answer_id": 19034,
"author": "DrPizza",
"author_id": 2131,
"author_profile": "https://Stackoverflow.com/users/2131",
"pm_score": 3,
"selected": false,
"text": "<blockquote>\n <p>From the application level (unfortunately). I agree that the proper way to prevent duplication is at the database level through the use of a unique index, but in SQL Server 2005, an index is allowed to be only 900 bytes, and my varchar(2048) field blows that away.</p>\n</blockquote>\n\n<p>I dunno how well it would perform, but I think you could write a trigger to enforce this, even if you couldn't do it directly with an index. Something like:</p>\n\n<pre><code>-- given a table stories(story_id int not null primary key, story varchar(max) not null)\nCREATE TRIGGER prevent_plagiarism \nON stories \nafter INSERT, UPDATE \nAS \n DECLARE @cnt AS INT \n\n SELECT @cnt = Count(*) \n FROM stories \n INNER JOIN inserted \n ON ( stories.story = inserted.story \n AND stories.story_id != inserted.story_id ) \n\n IF @cnt > 0 \n BEGIN \n RAISERROR('plagiarism detected',16,1) \n\n ROLLBACK TRANSACTION \n END \n</code></pre>\n\n<p>Also, varchar(2048) sounds fishy to me (some things in life are 2048 bytes, but it's pretty uncommon); should it really not be varchar(max)?</p>\n"
},
{
"answer_id": 839710,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 3,
"selected": false,
"text": "<ol>\n<li><p>Create new blank table with the same structure</p></li>\n<li><p>Execute query like this</p>\n\n<pre><code>INSERT INTO tc_category1\nSELECT *\nFROM tc_category\nGROUP BY category_id, application_id\nHAVING count(*) > 1\n</code></pre></li>\n<li><p>Then execute this query</p>\n\n<pre><code>INSERT INTO tc_category1\nSELECT *\nFROM tc_category\nGROUP BY category_id, application_id\nHAVING count(*) = 1\n</code></pre></li>\n</ol>\n"
},
{
"answer_id": 1888176,
"author": "codegoalie",
"author_id": 12852,
"author_profile": "https://Stackoverflow.com/users/12852",
"pm_score": 4,
"selected": false,
"text": "<p>I had a table where I needed to preserve non-duplicate rows.\nI'm not sure on the speed or efficiency.</p>\n\n<pre><code>DELETE FROM myTable WHERE RowID IN (\n SELECT MIN(RowID) AS IDNo FROM myTable\n GROUP BY Col1, Col2, Col3\n HAVING COUNT(*) = 2 )\n</code></pre>\n"
},
{
"answer_id": 3822833,
"author": "Martin Smith",
"author_id": 73226,
"author_profile": "https://Stackoverflow.com/users/73226",
"pm_score": 10,
"selected": false,
"text": "<p>Another possible way of doing this is</p>\n\n<pre><code>; \n\n--Ensure that any immediately preceding statement is terminated with a semicolon above\nWITH cte\n AS (SELECT ROW_NUMBER() OVER (PARTITION BY Col1, Col2, Col3 \n ORDER BY ( SELECT 0)) RN\n FROM #MyTable)\nDELETE FROM cte\nWHERE RN > 1;\n</code></pre>\n\n<p>I am using <code>ORDER BY (SELECT 0)</code> above as it is arbitrary which row to preserve in the event of a tie. </p>\n\n<p>To preserve the latest one in <code>RowID</code> order for example you could use <code>ORDER BY RowID DESC</code> </p>\n\n<p><strong>Execution Plans</strong></p>\n\n<p>The execution plan for this is often simpler and more efficient than that in the accepted answer as it does not require the self join.</p>\n\n<p><a href=\"https://i.stack.imgur.com/ZJiWF.jpg\" rel=\"noreferrer\"><img src=\"https://i.stack.imgur.com/ZJiWF.jpg\" alt=\"Execution Plans\"></a></p>\n\n<p>This is not always the case however. One place where the <code>GROUP BY</code> solution might be preferred is situations where a <a href=\"https://learn.microsoft.com/en-gb/archive/blogs/craigfr/hash-aggregate\" rel=\"noreferrer\">hash aggregate</a> would be chosen in preference to a stream aggregate. </p>\n\n<p>The <code>ROW_NUMBER</code> solution will always give pretty much the same plan whereas the <code>GROUP BY</code> strategy is more flexible.</p>\n\n<p><a href=\"https://i.stack.imgur.com/iUlWm.jpg\" rel=\"noreferrer\"><img src=\"https://i.stack.imgur.com/iUlWm.jpg\" alt=\"Execution Plans\"></a></p>\n\n<p>Factors which might favour the hash aggregate approach would be </p>\n\n<ul>\n<li>No useful index on the partitioning columns</li>\n<li>relatively fewer groups with relatively more duplicates in each group </li>\n</ul>\n\n<p>In extreme versions of this second case (if there are very few groups with many duplicates in each) one could also consider simply inserting the rows to keep into a new table then <code>TRUNCATE</code>-ing the original and copying them back to minimise logging compared to deleting a very high proportion of the rows.</p>\n"
},
{
"answer_id": 3827302,
"author": "SoftwareGeek",
"author_id": 168882,
"author_profile": "https://Stackoverflow.com/users/168882",
"pm_score": 6,
"selected": false,
"text": "<pre><code>delete t1\nfrom table t1, table t2\nwhere t1.columnA = t2.columnA\nand t1.rowid>t2.rowid\n</code></pre>\n\n<p>Postgres: </p>\n\n<pre><code>delete\nfrom table t1\nusing table t2\nwhere t1.columnA = t2.columnA\nand t1.rowid > t2.rowid\n</code></pre>\n"
},
{
"answer_id": 8244823,
"author": "gngolakia",
"author_id": 1050111,
"author_profile": "https://Stackoverflow.com/users/1050111",
"pm_score": 7,
"selected": false,
"text": "<p>The following query is useful to delete duplicate rows. The table in this example has <code>ID</code> as an identity column and the columns which have duplicate data are <code>Column1</code>, <code>Column2</code> and <code>Column3</code>.</p>\n\n<pre><code>DELETE FROM TableName\nWHERE ID NOT IN (SELECT MAX(ID)\n FROM TableName\n GROUP BY Column1,\n Column2,\n Column3\n /*Even if ID is not null-able SQL Server treats MAX(ID) as potentially\n nullable. Because of semantics of NOT IN (NULL) including the clause\n below can simplify the plan*/\n HAVING MAX(ID) IS NOT NULL) \n</code></pre>\n\n<p>The following script shows usage of <code>GROUP BY</code>, <code>HAVING</code>, <code>ORDER BY</code> in one query, and returns the results with duplicate column and its count.</p>\n\n<pre><code>SELECT YourColumnName,\n COUNT(*) TotalCount\nFROM YourTableName\nGROUP BY YourColumnName\nHAVING COUNT(*) > 1\nORDER BY COUNT(*) DESC \n</code></pre>\n"
},
{
"answer_id": 9193001,
"author": "Sudhakar NV",
"author_id": 1197119,
"author_profile": "https://Stackoverflow.com/users/1197119",
"pm_score": 3,
"selected": false,
"text": "<p>By useing below query we can able to delete duplicate records based on the single column or multiple column. below query is deleting based on two columns. table name is: <code>testing</code> and column names <code>empno,empname</code></p>\n\n<pre><code>DELETE FROM testing WHERE empno not IN (SELECT empno FROM (SELECT empno, ROW_NUMBER() OVER (PARTITION BY empno ORDER BY empno) \nAS [ItemNumber] FROM testing) a WHERE ItemNumber > 1)\nor empname not in\n(select empname from (select empname,row_number() over(PARTITION BY empno ORDER BY empno) \nAS [ItemNumber] FROM testing) a WHERE ItemNumber > 1)\n</code></pre>\n"
},
{
"answer_id": 11431968,
"author": "AnandPhadke",
"author_id": 1495994,
"author_profile": "https://Stackoverflow.com/users/1495994",
"pm_score": 3,
"selected": false,
"text": "<pre><code>CREATE TABLE car(Id int identity(1,1), PersonId int, CarId int)\n\nINSERT INTO car(PersonId,CarId)\nVALUES(1,2),(1,3),(1,2),(2,4)\n\n--SELECT * FROM car\n\n;WITH CTE as(\nSELECT ROW_NUMBER() over (PARTITION BY personid,carid order by personid,carid) as rn,Id,PersonID,CarId from car)\n\nDELETE FROM car where Id in(SELECT Id FROM CTE WHERE rn>1)\n</code></pre>\n"
},
{
"answer_id": 12818055,
"author": "heta77",
"author_id": 1734652,
"author_profile": "https://Stackoverflow.com/users/1734652",
"pm_score": 4,
"selected": false,
"text": "<pre><code>SELECT DISTINCT *\n INTO tempdb.dbo.tmpTable\nFROM myTable\n\nTRUNCATE TABLE myTable\nINSERT INTO myTable SELECT * FROM tempdb.dbo.tmpTable\nDROP TABLE tempdb.dbo.tmpTable\n</code></pre>\n"
},
{
"answer_id": 14612370,
"author": "Evgueny Sedov",
"author_id": 1193024,
"author_profile": "https://Stackoverflow.com/users/1193024",
"pm_score": 3,
"selected": false,
"text": "<p>I would mention this approach as well as it can be helpful, and works in all SQL servers:\nPretty often there is only one - two duplicates, and Ids and count of duplicates are known. In this case:</p>\n\n<pre><code>SET ROWCOUNT 1 -- or set to number of rows to be deleted\ndelete from myTable where RowId = DuplicatedID\nSET ROWCOUNT 0\n</code></pre>\n"
},
{
"answer_id": 14717523,
"author": "JuanJo",
"author_id": 2044799,
"author_profile": "https://Stackoverflow.com/users/2044799",
"pm_score": 5,
"selected": false,
"text": "<p>Quick and Dirty to delete exact duplicated rows (for small tables):</p>\n\n<pre><code>select distinct * into t2 from t1;\ndelete from t1;\ninsert into t1 select * from t2;\ndrop table t2;\n</code></pre>\n"
},
{
"answer_id": 18086447,
"author": "Nitish Pareek",
"author_id": 918385,
"author_profile": "https://Stackoverflow.com/users/918385",
"pm_score": 4,
"selected": false,
"text": "<p>Yet another easy solution can be found at the link pasted <a href=\"http://www.codeproject.com/Articles/157977/Remove-Duplicate-Rows-from-a-Table-in-SQL-Server\" rel=\"noreferrer\">here</a>. This one easy to grasp and seems to be effective for most of the similar problems. It is for SQL Server though but the concept used is more than acceptable.</p>\n\n<p>Here are the relevant portions from the linked page:</p>\n\n<p>Consider this data:</p>\n\n<pre><code>EMPLOYEE_ID ATTENDANCE_DATE\nA001 2011-01-01\nA001 2011-01-01\nA002 2011-01-01\nA002 2011-01-01\nA002 2011-01-01\nA003 2011-01-01\n</code></pre>\n\n<p>So how can we delete those duplicate data?</p>\n\n<p>First, insert an identity column in that table by using the following code:</p>\n\n<pre><code>ALTER TABLE dbo.ATTENDANCE ADD AUTOID INT IDENTITY(1,1) \n</code></pre>\n\n<p>Use the following code to resolve it:</p>\n\n<pre><code>DELETE FROM dbo.ATTENDANCE WHERE AUTOID NOT IN (SELECT MIN(AUTOID) _\n FROM dbo.ATTENDANCE GROUP BY EMPLOYEE_ID,ATTENDANCE_DATE) \n</code></pre>\n"
},
{
"answer_id": 18719814,
"author": "Syed Mohamed",
"author_id": 2089963,
"author_profile": "https://Stackoverflow.com/users/2089963",
"pm_score": 5,
"selected": false,
"text": "<p>This will delete duplicate rows, except the first row</p>\n\n<pre><code>DELETE\nFROM\n Mytable\nWHERE\n RowID NOT IN (\n SELECT\n MIN(RowID)\n FROM\n Mytable\n GROUP BY\n Col1,\n Col2,\n Col3\n )\n</code></pre>\n\n<p>Refer (<a href=\"http://www.codeproject.com/Articles/157977/Remove-Duplicate-Rows-from-a-Table-in-SQL-Server\" rel=\"noreferrer\">http://www.codeproject.com/Articles/157977/Remove-Duplicate-Rows-from-a-Table-in-SQL-Server</a>)</p>\n"
},
{
"answer_id": 18865386,
"author": "Ismail Yavuz",
"author_id": 2290369,
"author_profile": "https://Stackoverflow.com/users/2290369",
"pm_score": 3,
"selected": false,
"text": "<p>The other way is <strong>Create a new</strong> table with same fields and <strong>with Unique Index</strong>. Then <strong>move all data from old table to new table</strong>. Automatically SQL SERVER ignore (there is also an option about what to do if there will be a duplicate value: ignore, interrupt or sth) duplicate values. So we have the same table without duplicate rows. <strong>If you don't want Unique Index, after the transfer data you can drop it</strong>.</p>\n\n<p>Especially <strong>for larger tables</strong> you may use DTS (SSIS package to import/export data) in order to transfer all data rapidly to your new uniquely indexed table. For 7 million row it takes just a few minute.</p>\n"
},
{
"answer_id": 19152091,
"author": "Teena",
"author_id": 2841400,
"author_profile": "https://Stackoverflow.com/users/2841400",
"pm_score": 3,
"selected": false,
"text": "<pre><code>DELETE\nFROM\n table_name T1\nWHERE\n rowid > (\n SELECT\n min(rowid)\n FROM\n table_name T2\n WHERE\n T1.column_name = T2.column_name\n );\n</code></pre>\n"
},
{
"answer_id": 20886125,
"author": "Jayron Soares",
"author_id": 2665070,
"author_profile": "https://Stackoverflow.com/users/2665070",
"pm_score": 3,
"selected": false,
"text": "<pre><code>DELETE \nFROM MyTable\nWHERE NOT EXISTS (\n SELECT min(RowID)\n FROM Mytable\n WHERE (SELECT RowID \n FROM Mytable\n GROUP BY Col1, Col2, Col3\n ))\n );\n</code></pre>\n"
},
{
"answer_id": 21380738,
"author": "Ruben Verschueren",
"author_id": 1396478,
"author_profile": "https://Stackoverflow.com/users/1396478",
"pm_score": 4,
"selected": false,
"text": "<p>I thought I'd share my solution since it works under special circumstances.\nI my case the table with duplicate values did not have a foreign key (because the values were duplicated from another db).</p>\n\n<pre><code>begin transaction\n-- create temp table with identical structure as source table\nSelect * Into #temp From tableName Where 1 = 2\n\n-- insert distinct values into temp\ninsert into #temp \nselect distinct * \nfrom tableName\n\n-- delete from source\ndelete from tableName \n\n-- insert into source from temp\ninsert into tableName \nselect * \nfrom #temp\n\nrollback transaction\n-- if this works, change rollback to commit and execute again to keep you changes!!\n</code></pre>\n\n<p>PS: when working on things like this I always use a transaction, this not only ensures everything is executed as a whole, but also allows me to test without risking anything. But off course you should take a backup anyway just to be sure...</p>\n"
},
{
"answer_id": 22111625,
"author": "James Errico",
"author_id": 832005,
"author_profile": "https://Stackoverflow.com/users/832005",
"pm_score": 4,
"selected": false,
"text": "<p>I prefer the subquery\\having count(*) > 1 solution to the inner join because I found it easier to read and it was very easy to turn into a SELECT statement to verify what would be deleted before you run it. </p>\n\n<pre><code>--DELETE FROM table1 \n--WHERE id IN ( \n SELECT MIN(id) FROM table1 \n GROUP BY col1, col2, col3 \n -- could add a WHERE clause here to further filter\n HAVING count(*) > 1\n--)\n</code></pre>\n"
},
{
"answer_id": 23777260,
"author": "Jithin Shaji",
"author_id": 3265371,
"author_profile": "https://Stackoverflow.com/users/3265371",
"pm_score": 6,
"selected": false,
"text": "<pre><code>DELETE LU \nFROM (SELECT *, \n Row_number() \n OVER ( \n partition BY col1, col1, col3 \n ORDER BY rowid DESC) [Row] \n FROM mytable) LU \nWHERE [row] > 1 \n</code></pre>\n"
},
{
"answer_id": 26913528,
"author": "Ostati",
"author_id": 2654100,
"author_profile": "https://Stackoverflow.com/users/2654100",
"pm_score": 4,
"selected": false,
"text": "<p>Using CTE. The idea is to join on one or more columns that form a duplicate record and then remove whichever you like:</p>\n\n<pre><code>;with cte as (\n select \n min(PrimaryKey) as PrimaryKey\n UniqueColumn1,\n UniqueColumn2\n from dbo.DuplicatesTable \n group by\n UniqueColumn1, UniqueColumn1\n having count(*) > 1\n)\ndelete d\nfrom dbo.DuplicatesTable d \ninner join cte on \n d.PrimaryKey > cte.PrimaryKey and\n d.UniqueColumn1 = cte.UniqueColumn1 and \n d.UniqueColumn2 = cte.UniqueColumn2;\n</code></pre>\n"
},
{
"answer_id": 27409405,
"author": "Draško",
"author_id": 1176497,
"author_profile": "https://Stackoverflow.com/users/1176497",
"pm_score": 4,
"selected": false,
"text": "<p>This query showed very good performance for me:</p>\n\n<pre><code>DELETE tbl\nFROM\n MyTable tbl\nWHERE\n EXISTS (\n SELECT\n *\n FROM\n MyTable tbl2\n WHERE\n tbl2.SameValue = tbl.SameValue\n AND tbl.IdUniqueValue < tbl2.IdUniqueValue\n )\n</code></pre>\n\n<p>it deleted 1M rows in little more than 30sec from a table of 2M (50% duplicates)</p>\n"
},
{
"answer_id": 27732094,
"author": "Lauri Lubi",
"author_id": 412368,
"author_profile": "https://Stackoverflow.com/users/412368",
"pm_score": 3,
"selected": false,
"text": "<p>I you want to preview the rows you are about to remove and keep control over which of the duplicate rows to keep. See <a href=\"http://developer.azurewebsites.net/2014/09/better-sql-group-by-find-duplicate-data/\">http://developer.azurewebsites.net/2014/09/better-sql-group-by-find-duplicate-data/</a></p>\n\n<pre><code>with MYCTE as (\n SELECT ROW_NUMBER() OVER (\n PARTITION BY DuplicateKey1\n ,DuplicateKey2 -- optional\n ORDER BY CreatedAt -- the first row among duplicates will be kept, other rows will be removed\n ) RN\n FROM MyTable\n)\nDELETE FROM MYCTE\nWHERE RN > 1\n</code></pre>\n"
},
{
"answer_id": 30328691,
"author": "Shamseer K",
"author_id": 4133590,
"author_profile": "https://Stackoverflow.com/users/4133590",
"pm_score": 5,
"selected": false,
"text": "<p>I would prefer CTE for deleting duplicate rows from sql server table</p>\n\n<p>strongly recommend to follow this article ::<a href=\"http://codaffection.com/sql-server-article/delete-duplicate-rows-in-sql-server/\" rel=\"noreferrer\">http://codaffection.com/sql-server-article/delete-duplicate-rows-in-sql-server/</a></p>\n\n<blockquote>\n <p>by keeping original</p>\n</blockquote>\n\n<pre><code>WITH CTE AS\n(\nSELECT *,ROW_NUMBER() OVER (PARTITION BY col1,col2,col3 ORDER BY col1,col2,col3) AS RN\nFROM MyTable\n)\n\nDELETE FROM CTE WHERE RN<>1\n</code></pre>\n\n<blockquote>\n <p>without keeping original</p>\n</blockquote>\n\n<pre><code>WITH CTE AS\n(SELECT *,R=RANK() OVER (ORDER BY col1,col2,col3)\nFROM MyTable)\n \nDELETE CTE\nWHERE R IN (SELECT R FROM CTE GROUP BY R HAVING COUNT(*)>1)\n</code></pre>\n"
},
{
"answer_id": 31586339,
"author": "Haris N I",
"author_id": 5073609,
"author_profile": "https://Stackoverflow.com/users/5073609",
"pm_score": 4,
"selected": false,
"text": "<p>Use this</p>\n\n<pre><code>WITH tblTemp as\n(\nSELECT ROW_NUMBER() Over(PARTITION BY Name,Department ORDER BY Name)\n As RowNumber,* FROM <table_name>\n)\nDELETE FROM tblTemp where RowNumber >1\n</code></pre>\n"
},
{
"answer_id": 34305065,
"author": "Chanukya",
"author_id": 5093602,
"author_profile": "https://Stackoverflow.com/users/5093602",
"pm_score": 1,
"selected": false,
"text": "<pre><code>alter table MyTable add sno int identity(1,1)\n delete from MyTable where sno in\n (\n select sno from (\n select *,\n RANK() OVER ( PARTITION BY RowID,Col3 ORDER BY sno DESC )rank\n From MyTable\n )T\n where rank>1\n )\n\n alter table MyTable \n drop column sno\n</code></pre>\n"
},
{
"answer_id": 34730529,
"author": "Hamit YILDIRIM",
"author_id": 914284,
"author_profile": "https://Stackoverflow.com/users/914284",
"pm_score": 0,
"selected": false,
"text": "<p>Now lets look elasticalsearch table which this tables has duplicated rows and Id is identical uniq field. We know if some id exist by a group criteria then we can delete other rows outscope of this group. My manner shows this criteria.</p>\n\n<p>So many case of this thread are in the like state of mine. Just change your target group criteria according your case for deleting repeated (duplicated) rows.</p>\n\n<pre><code>DELETE \nFROM elasticalsearch\nWHERE Id NOT IN \n (SELECT min(Id)\n FROM elasticalsearch\n GROUP BY FirmId,FilterSearchString\n ) \n</code></pre>\n\n<p>cheers</p>\n"
},
{
"answer_id": 35147002,
"author": "yuvi",
"author_id": 4919084,
"author_profile": "https://Stackoverflow.com/users/4919084",
"pm_score": 3,
"selected": false,
"text": "<p>Another way of doing this :--</p>\n\n<pre><code>DELETE A\nFROM TABLE A,\n TABLE B\nWHERE A.COL1 = B.COL1\n AND A.COL2 = B.COL2\n AND A.UNIQUEFIELD > B.UNIQUEFIELD \n</code></pre>\n"
},
{
"answer_id": 37669155,
"author": "Brett Ryan",
"author_id": 140037,
"author_profile": "https://Stackoverflow.com/users/140037",
"pm_score": 1,
"selected": false,
"text": "<p>Sometimes a soft delete mechanism is used where a date is recorded to indicate the deleted date. In this case an <code>UPDATE</code> statement may be used to update this field based on duplicate entries.</p>\n\n<pre><code>UPDATE MY_TABLE\n SET DELETED = getDate()\n WHERE TABLE_ID IN (\n SELECT x.TABLE_ID\n FROM MY_TABLE x\n JOIN (SELECT min(TABLE_ID) id, COL_1, COL_2, COL_3\n FROM MY_TABLE d\n GROUP BY d.COL_1, d.COL_2, d.COL_3\n HAVING count(*) > 1) AS d ON d.COL_1 = x.COL_1\n AND d.COL_2 = x.COL_2\n AND d.COL_3 = x.COL_3\n AND d.TABLE_ID <> x.TABLE_ID\n /*WHERE x.COL_4 <> 'D' -- Additional filter*/)\n</code></pre>\n\n<p>This method has served me well for fairly moderate tables containing ~30 million rows with high and low amounts of duplications.</p>\n"
},
{
"answer_id": 39738697,
"author": "Harikesh Yadav",
"author_id": 6546950,
"author_profile": "https://Stackoverflow.com/users/6546950",
"pm_score": 4,
"selected": false,
"text": "<p>This is the easiest way to delete duplicate record</p>\n<pre><code> DELETE FROM tblemp WHERE id IN \n (\n SELECT MIN(id) FROM tblemp\n GROUP BY title HAVING COUNT(id)>1\n )\n</code></pre>\n"
},
{
"answer_id": 41377822,
"author": "Shaini Sinha",
"author_id": 5887766,
"author_profile": "https://Stackoverflow.com/users/5887766",
"pm_score": 5,
"selected": false,
"text": "<p><strong>To Fetch Duplicate Rows:</strong><br></p>\n\n<pre><code>SELECT\nname, email, COUNT(*)\nFROM \nusers\nGROUP BY\nname, email\nHAVING COUNT(*) > 1\n</code></pre>\n\n<p><strong>To Delete the Duplicate Rows:</strong></p>\n\n<pre><code>DELETE users \nWHERE rowid NOT IN \n(SELECT MIN(rowid)\nFROM users\nGROUP BY name, email); \n</code></pre>\n"
},
{
"answer_id": 43387570,
"author": "Jakub Ojmucianski",
"author_id": 6696265,
"author_profile": "https://Stackoverflow.com/users/6696265",
"pm_score": 1,
"selected": false,
"text": "<p>I know that this question has been already answered, but I've created pretty useful sp which will create a dynamic delete statement for a table duplicates:</p>\n\n<pre><code> CREATE PROCEDURE sp_DeleteDuplicate @tableName varchar(100), @DebugMode int =1\nAS \nBEGIN\nSET NOCOUNT ON;\n\nIF(OBJECT_ID('tempdb..#tableMatrix') is not null) DROP TABLE #tableMatrix;\n\nSELECT ROW_NUMBER() OVER(ORDER BY name) as rn,name into #tableMatrix FROM sys.columns where [object_id] = object_id(@tableName) ORDER BY name\n\nDECLARE @MaxRow int = (SELECT MAX(rn) from #tableMatrix)\nIF(@MaxRow is null)\n RAISERROR ('I wasn''t able to find any columns for this table!',16,1)\nELSE \n BEGIN\nDECLARE @i int =1 \nDECLARE @Columns Varchar(max) ='';\n\nWHILE (@i <= @MaxRow)\nBEGIN \n SET @Columns=@Columns+(SELECT '['+name+'],' from #tableMatrix where rn = @i)\n\n SET @i = @i+1;\nEND\n\n---DELETE LAST comma\nSET @Columns = LEFT(@Columns,LEN(@Columns)-1)\n\nDECLARE @Sql nvarchar(max) = '\nWITH cteRowsToDelte\n AS (\nSELECT ROW_NUMBER() OVER (PARTITION BY '+@Columns+' ORDER BY ( SELECT 0)) as rowNumber,* FROM '+@tableName\n+')\n\nDELETE FROM cteRowsToDelte\nWHERE rowNumber > 1;\n'\nSET NOCOUNT OFF;\n IF(@DebugMode = 1)\n SELECT @Sql\n ELSE\n EXEC sp_executesql @Sql\n END\nEND\n</code></pre>\n\n<p>So if you create table like that:</p>\n\n<pre><code>IF(OBJECT_ID('MyLitleTable') is not null)\n DROP TABLE MyLitleTable \n\n\nCREATE TABLE MyLitleTable\n(\n A Varchar(10),\n B money,\n C int\n)\n---------------------------------------------------------\n\n INSERT INTO MyLitleTable VALUES\n ('ABC',100,1),\n ('ABC',100,1), -- only this row should be deleted\n ('ABC',101,1),\n ('ABC',100,2),\n ('ABCD',100,1)\n\n -----------------------------------------------------------\n\n exec sp_DeleteDuplicate 'MyLitleTable',0\n</code></pre>\n\n<p>It will delete all duplicates from your table. If you run it without the second parameter it will return a SQL statement to run.</p>\n\n<p>If you need to exclude any of the column just run it in the debug mode get the code and modify it whatever you like.</p>\n"
},
{
"answer_id": 50782285,
"author": "Selim Reza",
"author_id": 4079929,
"author_profile": "https://Stackoverflow.com/users/4079929",
"pm_score": 0,
"selected": false,
"text": "<p>I think this would be helpfull. Here, <strong>ROW_NUMBER() OVER(PARTITION BY res1.Title ORDER BY res1.Id)as num</strong> has been used to differentiate the duplicate rows.</p>\n\n<pre><code>delete FROM\n(SELECT res1.*,ROW_NUMBER() OVER(PARTITION BY res1.Title ORDER BY res1.Id)as num\n FROM \n(select * from [dbo].[tbl_countries])as res1\n)as res2\nWHERE res2.num > 1\n</code></pre>\n"
},
{
"answer_id": 53047498,
"author": "Suraj Kumar",
"author_id": 10532500,
"author_profile": "https://Stackoverflow.com/users/10532500",
"pm_score": 1,
"selected": false,
"text": "<p>If all the columns in duplicate rows are same then below query can be used to delete the duplicate records.</p>\n\n<pre><code>SELECT DISTINCT * INTO #TemNewTable FROM #OriginalTable\nTRUNCATE TABLE #OriginalTable\nINSERT INTO #OriginalTable SELECT * FROM #TemNewTable\nDROP TABLE #TemNewTable\n</code></pre>\n"
},
{
"answer_id": 63276678,
"author": "Ankit Jindal",
"author_id": 4198180,
"author_profile": "https://Stackoverflow.com/users/4198180",
"pm_score": 1,
"selected": false,
"text": "<p>For the table structure</p>\n<p><strong>MyTable</strong></p>\n<pre><code>RowID int not null identity(1,1) primary key,\nCol1 varchar(20) not null,\nCol2 varchar(2048) not null,\nCol3 tinyint not null\n</code></pre>\n<p>The query for removing duplicates:</p>\n<pre><code>DELETE t1\nFROM MyTable t1\nINNER JOIN MyTable t2\nWHERE t1.RowID > t2.RowID\n AND t1.Col1 = t2.Col1\n AND t1.Col2=t2.Col2\n AND t1.Col3=t2.Col3;\n</code></pre>\n<blockquote>\n<p>I am assuming that <code>RowID</code> is kind of auto-increment and rest of the columns have duplicate values.</p>\n</blockquote>\n"
},
{
"answer_id": 66499181,
"author": "Mansour Alnasser",
"author_id": 1448379,
"author_profile": "https://Stackoverflow.com/users/1448379",
"pm_score": 0,
"selected": false,
"text": "<h2>Other way to remove duplicates based on two columns</h2>\n<p>I found this query easier to read and replace.</p>\n<pre class=\"lang-sql prettyprint-override\"><code>DELETE \nFROM \n TABLE_NAME \n WHERE FIRST_COLUMNS \n IN( \n SELECT * FROM \n ( SELECT MIN(FIRST_COLUMNS) \n FROM TABLE_NAME \n GROUP BY \n FIRST_COLUMNS,\n SECOND_COLUMNS \n HAVING COUNT(FIRST_COLUMNS) > 1 \n ) temp \n )\n</code></pre>\n<p>note: It's good to <code>simulate query</code> before you run it.</p>\n<p><a href=\"https://i.stack.imgur.com/dwLM3.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/dwLM3.png\" alt=\"enter image description here\" /></a></p>\n"
},
{
"answer_id": 67339432,
"author": "Chandan Kumar Singh",
"author_id": 8124278,
"author_profile": "https://Stackoverflow.com/users/8124278",
"pm_score": -1,
"selected": false,
"text": "<p><strong>A very simple way to delete duplicate rows of table in postgresql.</strong></p>\n<pre><code>DELETE FROM table1 a\nUSING table1 b\nWHERE a.id < b.id\nAND a.column1 = b.column1\nAND a.column2 = b.column2;\n</code></pre>\n"
},
{
"answer_id": 69237652,
"author": "Md. Tarikul Islam Soikot",
"author_id": 15078671,
"author_profile": "https://Stackoverflow.com/users/15078671",
"pm_score": 0,
"selected": false,
"text": "<p>First you can select minimum RowId's using MIN() and Group By. We will keep these Rows.</p>\n<pre><code> SELECT MIN(RowId) as RowId\n FROM MyTable \n GROUP BY Col1, Col2, Col3\n</code></pre>\n<p>And Delete RowId's those are not in selected minimum RowId's using</p>\n<pre><code>DELETE FROM MyTable WHERE RowId Not IN()\n</code></pre>\n<p>Final query:</p>\n<pre><code>DELETE FROM MyTable WHERE RowId Not IN(\n\n SELECT MIN(RowId) as RowId\n FROM MyTable \n GROUP BY Col1, Col2, Col3\n)\n</code></pre>\n<p>You can also check my answer in <a href=\"http://sqlfiddle.com/#!18/6a5dc/5\" rel=\"nofollow noreferrer\">SQL Fiddle</a></p>\n"
},
{
"answer_id": 72659315,
"author": "Vikas kumar",
"author_id": 5826097,
"author_profile": "https://Stackoverflow.com/users/5826097",
"pm_score": -1,
"selected": false,
"text": "<p>Delete Duplicate record</p>\n<blockquote>\n<p>Greater Than operator in this case delete all record except first record</p>\n</blockquote>\n<p>DELETE u1 FROM users u1 JOIN users u2\nWHERE u1.id > u2.id\nAND u1.email=u2.email</p>\n<p>< Less than operator in this case delete all record except last record</p>\n<p>DELETE u1 FROM users u1 JOIN users u2\nWHERE u1.id < u2.id\nAND u1.email=u2.email</p>\n"
},
{
"answer_id": 73993006,
"author": "michael satumba",
"author_id": 16040742,
"author_profile": "https://Stackoverflow.com/users/16040742",
"pm_score": -1,
"selected": false,
"text": "<p>Create another table that will consist of original values:</p>\n<pre><code>CREATE TABLE table2 AS SELECT *, COUNT(*) FROM table1 GROUP BY name HAVING COUNT (*) > 0\n</code></pre>\n"
}
] | 2008/08/20 | [
"https://Stackoverflow.com/questions/18932",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/357/"
] | I need to remove duplicate rows from a fairly large SQL Server table (i.e. 300,000+ rows).
The rows, of course, will not be perfect duplicates because of the existence of the `RowID` identity field.
**MyTable**
```
RowID int not null identity(1,1) primary key,
Col1 varchar(20) not null,
Col2 varchar(2048) not null,
Col3 tinyint not null
```
How can I do this? | Assuming no nulls, you `GROUP BY` the unique columns, and `SELECT` the `MIN (or MAX)` RowId as the row to keep. Then, just delete everything that didn't have a row id:
```
DELETE FROM MyTable
LEFT OUTER JOIN (
SELECT MIN(RowId) as RowId, Col1, Col2, Col3
FROM MyTable
GROUP BY Col1, Col2, Col3
) as KeepRows ON
MyTable.RowId = KeepRows.RowId
WHERE
KeepRows.RowId IS NULL
```
In case you have a GUID instead of an integer, you can replace
```
MIN(RowId)
```
with
```
CONVERT(uniqueidentifier, MIN(CONVERT(char(36), MyGuidColumn)))
``` |
18,955 | <p>Is there a way to disable entering multi-line entries in a Text Box (i.e., I'd like to stop my users from doing ctrl-enter to get a newline)?</p>
| [
{
"answer_id": 18972,
"author": "Mauro",
"author_id": 2208,
"author_profile": "https://Stackoverflow.com/users/2208",
"pm_score": 0,
"selected": false,
"text": "<p>not entirely sure about that one, you should be able to remove the line breaks when you render the content though, or even run a vbscript to clear it out, you just need to check for chr(13) or vbCrLf.</p>\n"
},
{
"answer_id": 19063,
"author": "Ian Patrick Hughes",
"author_id": 2213,
"author_profile": "https://Stackoverflow.com/users/2213",
"pm_score": 2,
"selected": false,
"text": "<p>The way I did it before (and the last time I worked in Access was around '97 so my memory is not so hot) was raising a key-up event and executing a VBA function. It's a similar method to what you do with an AJAX suggest text box in a modern webform application, but as I recall it could get tripped up if your Access form has other events which tend to occur frequently such a onMouseMove over the entire form object.</p>\n"
},
{
"answer_id": 20255,
"author": "BIBD",
"author_id": 685,
"author_profile": "https://Stackoverflow.com/users/685",
"pm_score": 4,
"selected": true,
"text": "<p>I was able to do it on using KeyPress event.\nHere's the code example:</p>\n\n<pre><code>Private Sub SingleLineTextBox_ KeyPress(ByRef KeyAscii As Integer)\n If KeyAscii = 10 _\n or KeyAscii = 13 Then\n '10 -> Ctrl-Enter. AKA ^J or ctrl-j\n '13 -> Enter. AKA ^M or ctrl-m\n KeyAscii = 0 'clear the the KeyPress\n End If\nEnd Sub\n</code></pre>\n"
},
{
"answer_id": 22711,
"author": "Jason Z",
"author_id": 2470,
"author_profile": "https://Stackoverflow.com/users/2470",
"pm_score": 0,
"selected": false,
"text": "<p>If you don't want an event interfering, you can set up the Validation Rule property for the textbox to be</p>\n\n<pre><code>NOT LIKE \"*\"+Chr(10)+\"*\" OR \"*\"+Chr(13)+\"*\"\n</code></pre>\n\n<p>You will probably also want to set the Validation Text to explain specifically why Access is throwing up an error box.</p>\n"
},
{
"answer_id": 67730,
"author": "David-W-Fenton",
"author_id": 9787,
"author_profile": "https://Stackoverflow.com/users/9787",
"pm_score": 2,
"selected": false,
"text": "<p>Using the KeyPress event means that your code will fire every time the user types. This can lead to screen flickering and other problems (the OnChange event would be the same).</p>\n\n<p>It seems to me that you should use a single event to strip out the CrLf's, and the correct event would be AfterUpdate. You'd simply do this:</p>\n\n<pre><code> If InStr(Me!MyMemoControl, vbCrLf) Then\n Me!MyMemoControl = Replace(Me!MyMemoControl, vbCrLf, vbNullString)\n End If\n</code></pre>\n\n<p>Note the use of the Access global constants, vbCrLf (for Chr(10) & Chr(13)) and vbNullString (for zero-length string).</p>\n\n<p>Using a validation rule means that you're going to pop up an ugly error message to your user, but provide them with little in the way of tools to correct the problem. The AfterUpdate approach is much cleaner and easier for the users, seems to me.</p>\n"
},
{
"answer_id": 29218275,
"author": "kernelk",
"author_id": 1305420,
"author_profile": "https://Stackoverflow.com/users/1305420",
"pm_score": 1,
"selected": false,
"text": "<p>Thanks Ian and BIBD. I created a public sub based on your answer that is reusable.</p>\n\n<pre><code>Public Sub PreventNewlines(ByRef KeyAscii As Integer)\n If KeyAscii = 10 Or KeyAscii = 13 Then KeyAscii = 0\nEnd Sub\n\nPrivate Sub textbox_KeyPress(KeyAscii As Integer)\n Call PreventNewlines(KeyAscii)\nEnd Sub\n</code></pre>\n\n<p>Screen flicker should never be an issue, as these are handled events, not constant polling (and it's per control further limiting the scope). Seems to me like an invalid argument, as every text editor is executing some code per keystroke.</p>\n\n<p>Thanks</p>\n"
},
{
"answer_id": 60349089,
"author": "John Litchfield",
"author_id": 12942182,
"author_profile": "https://Stackoverflow.com/users/12942182",
"pm_score": 0,
"selected": false,
"text": "<p>Jason's response works well. Just to add to it..</p>\n\n<p>If you want to allow the user to leave the text box blank, you could use this:</p>\n\n<p>Not Like \"<em>\"+Chr(10)+\"</em>\" Or \"<em>\"+Chr(13)+\"</em>\" Or Is Null</p>\n"
}
] | 2008/08/20 | [
"https://Stackoverflow.com/questions/18955",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/685/"
] | Is there a way to disable entering multi-line entries in a Text Box (i.e., I'd like to stop my users from doing ctrl-enter to get a newline)? | I was able to do it on using KeyPress event.
Here's the code example:
```
Private Sub SingleLineTextBox_ KeyPress(ByRef KeyAscii As Integer)
If KeyAscii = 10 _
or KeyAscii = 13 Then
'10 -> Ctrl-Enter. AKA ^J or ctrl-j
'13 -> Enter. AKA ^M or ctrl-m
KeyAscii = 0 'clear the the KeyPress
End If
End Sub
``` |
18,984 | <p>What are your opinions on developing for the command line first, then adding a GUI on after the fact by simply calling the command line methods?</p>
<p>eg.</p>
<blockquote>
<p>W:\ todo AddTask "meeting with John, re: login peer review" "John's office" "2008-08-22" "14:00" </p>
</blockquote>
<p>loads <code>todo.exe</code> and calls a function called <code>AddTask</code> that does some validation and throws the meeting in a database. </p>
<p>Eventually you add in a screen for this: </p>
<pre>
============================================================
Event: [meeting with John, re: login peer review]
Location: [John's office]
Date: [Fri. Aug. 22, 2008]
Time: [ 2:00 PM]
[Clear] [Submit]
============================================================
</pre>
<p>When you click submit, it calls the same AddTask function.</p>
<p>Is this considered: </p>
<ul>
<li>a good way to code</li>
<li>just for the newbies</li>
<li>horrendous!.</li>
</ul>
<p><strong>Addendum:</strong> </p>
<p>I'm noticing a trend here for "shared library called by both the GUI and CLI executables." Is there some compelling reason why they would have to be separated, other than maybe the size of the binaries themselves? </p>
<p>Why not just call the same executable in different ways:</p>
<ul>
<li><code>"todo /G"</code> when you want the full-on graphical interface</li>
<li><code>"todo /I"</code> for an interactive prompt <em>within</em> <code>todo.exe</code> (scripting, etc)</li>
<li>plain old <code>"todo <function>"</code> when you just want to do one thing and be done with it.</li>
</ul>
<p><strong>Addendum 2:</strong> </p>
<p>It was mentioned that "the way [I've] described things, you [would] need to spawn an executable every time the GUI needs to do something." </p>
<p>Again, this wasn't my intent. When I mentioned that the example GUI called "the same <code>AddTask</code> function," I didn't mean the GUI called the command line program each time. I agree that would be totally nasty. I had intended (see first addendum) that this all be held in a single executable, since it was a tiny example, but I don't think my phrasing necessarily precluded a shared library.</p>
<p>Also, I'd like to thank all of you for your input. This is something that keeps popping back in my mind and I appreciate the wisdom of your experience.</p>
| [
{
"answer_id": 18990,
"author": "Stu",
"author_id": 414,
"author_profile": "https://Stackoverflow.com/users/414",
"pm_score": 3,
"selected": false,
"text": "<p>Put the shared functionality in a library, then write a command-line and a GUI front-end for it. That way your layer transition isn't tied to the command-line.</p>\n\n<p>(Also, this way adds another security concern: shouldn't the GUI first have to make sure it's the RIGHT todo.exe that is being called?)</p>\n"
},
{
"answer_id": 18994,
"author": "Shog9",
"author_id": 811,
"author_profile": "https://Stackoverflow.com/users/811",
"pm_score": 1,
"selected": false,
"text": "<p>Kinda depends on your goal for the program, but yeah i do this from time to time - it's quicker to code, easier to debug, and easier to write quick and dirty test cases for. And so long as i structure my code properly, i can go back and tack on a GUI later without too much work.</p>\n\n<p>To those suggesting that this technique will result in horrible, unusable UIs: You're right. Writing a command-line utility is a terrible way to design a GUI. Take note, everyone out there thinking of writing a UI that <em>isn't</em> a CLUI - don't prototype it as a CLUI.</p>\n\n<p>But, <em>if you're writing new code that does not itself depend on a UI</em>, then go for it.</p>\n"
},
{
"answer_id": 18995,
"author": "Matt Hamilton",
"author_id": 615,
"author_profile": "https://Stackoverflow.com/users/615",
"pm_score": 3,
"selected": false,
"text": "<p>Joel wrote an article contrasting this (\"unix-style\") development to the GUI first (\"Windows-style\") method a few years back. He called it <a href=\"http://www.joelonsoftware.com/articles/Biculturalism.html\" rel=\"nofollow noreferrer\">Biculturalism</a>.</p>\n\n<p>I think on Windows it will become normal (if it hasn't already) to wrap your logic into .NET assemblies, which you can then access from both a GUI and a PowerShell provider. That way you get the best of both worlds.</p>\n"
},
{
"answer_id": 18998,
"author": "Cristian",
"author_id": 680,
"author_profile": "https://Stackoverflow.com/users/680",
"pm_score": 2,
"selected": false,
"text": "<p>It's probably better to start with a command line first to make sure you have the functionality correct. If your main users can't (or won't) use the command line then you can add a GUI on top of your work.</p>\n\n<p>This will make your app better suited for scripting as well as limiting the amount of upfront <a href=\"http://en.wikipedia.org/wiki/Bikeshedding\" rel=\"nofollow noreferrer\">Bikeshedding</a> so you can get to the actual solution faster.</p>\n"
},
{
"answer_id": 18999,
"author": "Steve",
"author_id": 2019,
"author_profile": "https://Stackoverflow.com/users/2019",
"pm_score": 2,
"selected": false,
"text": "<p>If you plan to keep your command-line version of your app then I don't see a problem with doing it this way - it's not time wasted. You'll still end up coding the main functionality of your app for the command-line and so you'll have a large chunk of the work done.</p>\n\n<p>I don't see working this way as being a barrier to a nice UI - you've still got the time to add one and make is usable etc.</p>\n\n<p>I guess this way of working would only really work if you intend for your finished app to have both command-line and GUI variants. It's easy enough to mock a UI and build your functionality into that and then beautify the UI later.</p>\n\n<p>Agree with Stu: your base functionality should be in a library that is called from the command-line and GUI code. Calling the executable from the UI is unnecessary overhead at runtime.</p>\n"
},
{
"answer_id": 19001,
"author": "AgentConundrum",
"author_id": 1588,
"author_profile": "https://Stackoverflow.com/users/1588",
"pm_score": 2,
"selected": false,
"text": "<p>@jcarrascal </p>\n\n<p>I don't see why this has to make the GUI \"bad?\"<br>\nMy thought would be that it would force you to think about what the \"business\" logic actually needs to accomplish, without worrying too much about things being pretty. Once you know what it should/can do, you can build your interface around that in whatever way makes the most sense. </p>\n\n<p>Side note: Not to start a separate topic, but what is the preferred way to address answers to/comments on your questions? I considered both this, and editing the question itself. </p>\n"
},
{
"answer_id": 19002,
"author": "bmavity",
"author_id": 2001,
"author_profile": "https://Stackoverflow.com/users/2001",
"pm_score": 2,
"selected": false,
"text": "<p>I think it depends on what type of application you are developing. Designing for the command line puts you on the fast track to what Alan Cooper refers to as \"Implementation Model\" in <a href=\"http://books.google.com/books?id=04cFCVXC_AUC&dq=alan+cooper+implementation+model&pg=PP1&ots=jfukV6o2oL&source=citation&sig=_T9wipBcKuO-eobfI3cjvzzsOak&hl=en&sa=X&oi=book_result&resnum=11&ct=result\" rel=\"nofollow noreferrer\">The Inmates are Running the Asylum</a>. The result is a user interface that is unintuitive and difficult to use.</p>\n\n<p>37signals also advocates designing your user interface first in <a href=\"http://gettingreal.37signals.com/ch09_Interface_First.php\" rel=\"nofollow noreferrer\">Getting Real</a>. Remember, for all intents and purposes, in the majority of applications, the user interface <em>is</em> the program. The back end code is just there to support it.</p>\n"
},
{
"answer_id": 19027,
"author": "Mike Stone",
"author_id": 122,
"author_profile": "https://Stackoverflow.com/users/122",
"pm_score": 2,
"selected": false,
"text": "<p>I did exactly this on one tool I wrote, and it worked great. The end result is a scriptable tool that can also be used via a GUI.</p>\n\n<p>I do agree with the sentiment that you should ensure the GUI is easy and intuitive to use, so it might be wise to even develop both at the same time... a little command line feature followed by a GUI wrapper to ensure you are doing things intuitively.</p>\n\n<p>If you are true to implementing both equally, the result is an app that can be used in an automated manner, which I think is very powerful for power users.</p>\n"
},
{
"answer_id": 19031,
"author": "wusher",
"author_id": 1632,
"author_profile": "https://Stackoverflow.com/users/1632",
"pm_score": 0,
"selected": false,
"text": "<p><strike>Command line tools generate less events then GUI apps and usually check all the params before starting. This will limit your gui because for a gui, it could make more sense to ask for the params as your program works or afterwards. </p>\n\n<p>If you don't care about the GUI then don't worry about it. If the end result will be a gui, make the gui first, then do the command line version. Or you could work on both at the same time.</strike></p>\n\n<p>--Massive edit--</p>\n\n<p>After spending some time on my current project, I feel as though I have come full circle from my previous answer. I think it is better to do the command line first and then wrap a gui on it. If you need to, I think you can make a great gui afterwards. By doing the command line first, you get all of the arguments down first so there is no surprises (until the requirements change) when you are doing the UI/UX. </p>\n"
},
{
"answer_id": 19046,
"author": "Steve",
"author_id": 2019,
"author_profile": "https://Stackoverflow.com/users/2019",
"pm_score": 0,
"selected": false,
"text": "<p>@Maudite</p>\n\n<p>The command-line app will check params up front and the GUI won't - but they'll still be checking the <em>same</em> params and inputting them into some generic worker functions.</p>\n\n<p>Still the same goal. I don't see the command-line version affecting the quality of the GUI one.</p>\n"
},
{
"answer_id": 19048,
"author": "Jon Limjap",
"author_id": 372,
"author_profile": "https://Stackoverflow.com/users/372",
"pm_score": 3,
"selected": false,
"text": "<p>My technique for programming backend functionality first without having the need for an explicit UI (especially when the UI isn't my job yet, e.g., I'm desigining a web application that is still in the design phase) is to write unit tests. </p>\n\n<p>That way I don't even need to write a console application to mock the output of my backend code -- it's all in the tests, and unlike your console app I don't have to throw the code for the tests away because they still are useful later.</p>\n"
},
{
"answer_id": 19059,
"author": "Michael Stum",
"author_id": 91,
"author_profile": "https://Stackoverflow.com/users/91",
"pm_score": 1,
"selected": false,
"text": "<p>I usually start with a class library and a separate, really crappy and basic GUI. As the Command Line involves parsing the Command Line, I feel like i'm adding a lot of unneccessary overhead.</p>\n\n<p>As a Bonus, this gives an MVC-like approach, as all the \"real\" code is in a Class Library. Of course, at a later stage, Refactoring the library together with a real GUI into one EXE is also an option.</p>\n"
},
{
"answer_id": 19090,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 1,
"selected": false,
"text": "<p>If you do your development right, then it should be relatively easy to switch to a GUI later on in the project. The problem is that it's kinda difficult to get it right.</p>\n"
},
{
"answer_id": 19094,
"author": "Kristopher Johnson",
"author_id": 1175,
"author_profile": "https://Stackoverflow.com/users/1175",
"pm_score": 1,
"selected": false,
"text": "<p>John Gruber had a good post about the concept of adding a GUI to a program not designed for one: <a href=\"http://daringfireball.net/2004/04/spray_on_usability\" rel=\"nofollow noreferrer\">Ronco Spray-On Usability</a></p>\n\n<p>Summary: It doesn't work. If usability isn't designed into an application from the beginning, adding it later is more work than anyone is willing to do.</p>\n"
},
{
"answer_id": 19101,
"author": "Christopher Mahan",
"author_id": 479,
"author_profile": "https://Stackoverflow.com/users/479",
"pm_score": 0,
"selected": false,
"text": "<p>Do a program that you expose as a web-service. then do the gui and command line to call the same web service. This approach also allows you to make a web-gui, and also to provide the functionality as SaaS to extranet partners, and/or to better secure the business logic.</p>\n\n<p>This also allows your program to more easily participate in a SOA environement. </p>\n\n<p>For the web-service, don't go overboard. do yaml or xml-rpc. Keep it simple.</p>\n"
},
{
"answer_id": 19136,
"author": "BCS",
"author_id": 1343,
"author_profile": "https://Stackoverflow.com/users/1343",
"pm_score": 1,
"selected": false,
"text": "<p>A better approach might be to develop the logic as a lib with a well defined API and, at the dev stage, no interface (or a hard coded interface) then you can wright the CLI or GUI later</p>\n"
},
{
"answer_id": 19179,
"author": "Mark Cidade",
"author_id": 1659,
"author_profile": "https://Stackoverflow.com/users/1659",
"pm_score": 5,
"selected": true,
"text": "<p>I would go with building a library with a command line application that links to it. Afterwards, you can create a GUI that links to the same library. Calling a command line from a GUI spawns external processes for each command and is more disruptive to the OS.</p>\n\n<p>Also, with a library you can easily do unit tests for the functionality.</p>\n\n<p>But even as long as your functional code is separate from your command line interpreter, then you can just re-use the source for a GUI without having the two kinds at once to perform an operation.</p>\n"
},
{
"answer_id": 19244,
"author": "grom",
"author_id": 486,
"author_profile": "https://Stackoverflow.com/users/486",
"pm_score": 0,
"selected": false,
"text": "<p>In addition to what <a href=\"https://stackoverflow.com/questions/18984/what-do-you-think-of-developing-for-the-command-line-first#18990\">Stu</a> said, having a shared library will allow you to use it from web applications as well. Or even from an IDE plugin.</p>\n"
},
{
"answer_id": 19841,
"author": "17 of 26",
"author_id": 2284,
"author_profile": "https://Stackoverflow.com/users/2284",
"pm_score": 1,
"selected": false,
"text": "<p>I would not do this for a couple of reasons.</p>\n\n<p>Design:</p>\n\n<p>A GUI and a CLI are two different interfaces used to access an underlying implementation. They are generally used for different purposes (GUI is for a live user, CLI is usually accessed by scripting) and can often have different requirements. Coupling the two together is not a wise choice and is bound to cause you trouble down the road.</p>\n\n<p>Performance:</p>\n\n<p>The way you've described things, you need to spawn an executable every time the GUI needs to d o something. This is just plain ugly.</p>\n\n<p>The right way to do this is to put the implementation in a library that's called by both the CLI and the GUI.</p>\n"
},
{
"answer_id": 27017,
"author": "Thomas Vander Stichele",
"author_id": 2900,
"author_profile": "https://Stackoverflow.com/users/2900",
"pm_score": 0,
"selected": false,
"text": "<p>There are several reasons why doing it this way is not a good idea. A lot of them have been mentioned, so I'll just stick with one specific point.</p>\n\n<p>Command-line tools are usually not interactive at all, while GUI's are. This is a fundamental difference. This is for example painful for long-running tasks.</p>\n\n<p>Your command-line tool will at best print out some kind of progress information - newlines, a textual progress bar, a bunch of output, ... Any kind of error it can only output to the console.</p>\n\n<p>Now you want to slap a GUI on top of that, what do you do ? Parse the output of your long-running command line tool ? Scan for WARNING and ERROR in that output to throw up a dialog box ?</p>\n\n<p>At best, most UI's built this way throw up a pulsating busy bar for as long as the command runs, then show you a success or failure dialog when the command exits. Sadly, this is how a lot of UNIX GUI programs are thrown together, making it a terrible user experience.</p>\n\n<p>Most repliers here are correct in saying that you should probably abstract the actual functionality of your program into a library, then write a command-line interface and the GUI at the same time for it. All your business logic should be in your library, and either UI (yes, a command line is a UI) should only do whatever is necessary to interface between your business logic and your UI.</p>\n\n<p>A command line is too poor a UI to make sure you develop your library good enough for GUI use later. You should start with both from the get-go, or start with the GUI programming. It's easy to add a command line interface to a library developed for a GUI, but it's a lot harder the other way around, precisely because of all the interactive features the GUI will need (reporting, progress, error dialogs, i18n, ...)</p>\n"
},
{
"answer_id": 41648027,
"author": "SystematicFrank",
"author_id": 253098,
"author_profile": "https://Stackoverflow.com/users/253098",
"pm_score": 0,
"selected": false,
"text": "<p>That is exactly one of my most important realizations about coding and I wish more people would take such approach.</p>\n\n<p>Just one minor clarification: The GUI should not be a wrapper around the command line. Instead one should be able to drive the core of the program from either a GUI or a command line. At least at the beginning and just basic operations.</p>\n\n<p><strong>When is this a great idea?</strong></p>\n\n<p>When you want to make sure that your domain implementation is independent of the GUI framework. You want to code <em>around</em> the framework not <em>into</em> the framework</p>\n\n<p><strong>When is this a bad idea?</strong></p>\n\n<p>When you are sure your framework will never die</p>\n"
}
] | 2008/08/20 | [
"https://Stackoverflow.com/questions/18984",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1588/"
] | What are your opinions on developing for the command line first, then adding a GUI on after the fact by simply calling the command line methods?
eg.
>
> W:\ todo AddTask "meeting with John, re: login peer review" "John's office" "2008-08-22" "14:00"
>
>
>
loads `todo.exe` and calls a function called `AddTask` that does some validation and throws the meeting in a database.
Eventually you add in a screen for this:
```
============================================================
Event: [meeting with John, re: login peer review]
Location: [John's office]
Date: [Fri. Aug. 22, 2008]
Time: [ 2:00 PM]
[Clear] [Submit]
============================================================
```
When you click submit, it calls the same AddTask function.
Is this considered:
* a good way to code
* just for the newbies
* horrendous!.
**Addendum:**
I'm noticing a trend here for "shared library called by both the GUI and CLI executables." Is there some compelling reason why they would have to be separated, other than maybe the size of the binaries themselves?
Why not just call the same executable in different ways:
* `"todo /G"` when you want the full-on graphical interface
* `"todo /I"` for an interactive prompt *within* `todo.exe` (scripting, etc)
* plain old `"todo <function>"` when you just want to do one thing and be done with it.
**Addendum 2:**
It was mentioned that "the way [I've] described things, you [would] need to spawn an executable every time the GUI needs to do something."
Again, this wasn't my intent. When I mentioned that the example GUI called "the same `AddTask` function," I didn't mean the GUI called the command line program each time. I agree that would be totally nasty. I had intended (see first addendum) that this all be held in a single executable, since it was a tiny example, but I don't think my phrasing necessarily precluded a shared library.
Also, I'd like to thank all of you for your input. This is something that keeps popping back in my mind and I appreciate the wisdom of your experience. | I would go with building a library with a command line application that links to it. Afterwards, you can create a GUI that links to the same library. Calling a command line from a GUI spawns external processes for each command and is more disruptive to the OS.
Also, with a library you can easily do unit tests for the functionality.
But even as long as your functional code is separate from your command line interpreter, then you can just re-use the source for a GUI without having the two kinds at once to perform an operation. |
18,985 | <p>I am writing a batch script in order to beautify JavaScript code. It needs to work on both <strong>Windows</strong> and <strong>Linux</strong>. </p>
<p>How can I beautify JavaScript code using the command line tools? </p>
| [
{
"answer_id": 27343,
"author": "Alan Storm",
"author_id": 2838,
"author_profile": "https://Stackoverflow.com/users/2838",
"pm_score": 7,
"selected": true,
"text": "<p>First, pick your favorite Javascript based Pretty Print/Beautifier. I prefer the one at <a href=\"http://jsbeautifier.org/\" rel=\"noreferrer\"><a href=\"http://jsbeautifier.org/\" rel=\"noreferrer\">http://jsbeautifier.org/</a></a>, because it's what I found first. Downloads its file <a href=\"https://github.com/beautify-web/js-beautify/blob/master/js/lib/beautify.js\" rel=\"noreferrer\">https://github.com/beautify-web/js-beautify/blob/master/js/lib/beautify.js</a></p>\n\n<p>Second, download and install The Mozilla group's Java based Javascript engine, <a href=\"https://www.mozilla.org/rhino/\" rel=\"noreferrer\">Rhino</a>. \"Install\" is a little bit misleading; Download the zip file, extract everything, place js.jar in your Java classpath (or Library/Java/Extensions on OS X). You can then run scripts with an invocation similar to this </p>\n\n<pre><code>java -cp js.jar org.mozilla.javascript.tools.shell.Main name-of-script.js\n</code></pre>\n\n<p>Use the Pretty Print/Beautifier from step 1 to write a small shell script that will read in your javascript file and run it through the Pretty Print/Beautifier from step one. For example</p>\n\n<pre><code>//original code \n(function() { ... js_beautify code ... }());\n\n//new code\nprint(global.js_beautify(readFile(arguments[0])));\n</code></pre>\n\n<p>Rhino gives javascript a few extra useful functions that don't necessarily make sense in a browser context, but do in a console context. The function print does what you'd expect, and prints out a string. The function readFile accepts a file path string as an argument and returns the contents of that file. </p>\n\n<p>You'd invoke the above something like </p>\n\n<pre><code>java -cp js.jar org.mozilla.javascript.tools.shell.Main beautify.js file-to-pp.js\n</code></pre>\n\n<p>You can mix and match Java and Javascript in your Rhino run scripts, so if you know a little Java it shouldn't be too hard to get this running with text-streams as well.</p>\n"
},
{
"answer_id": 4041563,
"author": "knb",
"author_id": 202553,
"author_profile": "https://Stackoverflow.com/users/202553",
"pm_score": 6,
"selected": false,
"text": "<p><strong>UPDATE April 2014</strong>:</p>\n<p>The beautifier has been rewritten since I answered this in 2010. There is now a python module in there, an npm Package for nodejs, and the jar file is gone. Please read the <a href=\"https://github.com/einars/js-beautify/\" rel=\"noreferrer\">project page on github.com</a>.</p>\n<p>Python style:</p>\n<pre><code> $ pip install jsbeautifier\n</code></pre>\n<p>NPM style:</p>\n<pre><code> $ npm -g install js-beautify\n</code></pre>\n<p>to use it (this will return the beatified js file on the terminal, the main file remains unchanged):</p>\n<pre><code> $ js-beautify file.js\n</code></pre>\n<p>To <strong>make the changes take effect on the file</strong>, you should use this command:</p>\n<pre class=\"lang-sh prettyprint-override\"><code>$ js-beautify -r file.js\n</code></pre>\n<p><strong>Original answer</strong></p>\n<p>Adding to Answer of @Alan Storm</p>\n<p>the command line beautifier based on <a href=\"http://jsbeautifier.org/\" rel=\"noreferrer\">http://jsbeautifier.org/</a> has gotten a bit easier to use, because it is now (alternatively) based on the V8 javascript engine (c++ code) instead of rhino (java-based JS engine, packaged as "js.jar"). So you can use V8 instead of rhino.</p>\n<p>How to use:</p>\n<p>download jsbeautifier.org zip file from\n<a href=\"http://github.com/einars/js-beautify/zipball/master\" rel=\"noreferrer\">http://github.com/einars/js-beautify/zipball/master</a></p>\n<p>(this is a download URL linked to a zip file such as <a href=\"http://download.github.com/einars-js-beautify-10384df.zip\" rel=\"noreferrer\">http://download.github.com/einars-js-beautify-10384df.zip</a>)</p>\n<p>old (no longer works, jar file is gone)</p>\n<pre><code> java -jar js.jar name-of-script.js\n</code></pre>\n<p>new (alternative)</p>\n<p>install/compile v8 lib FROM svn, see v8/README.txt in above-mentioned zip file</p>\n<pre><code> ./jsbeautify somefile.js\n</code></pre>\n<p>-has slightly different command line options than the rhino version,</p>\n<p>-and works great in Eclipse when configured as an "External Tool"</p>\n"
},
{
"answer_id": 4065400,
"author": "Shonzilla",
"author_id": 31625,
"author_profile": "https://Stackoverflow.com/users/31625",
"pm_score": 1,
"selected": false,
"text": "<p>I've written an article explaining how to build a <a href=\"http://blog.shonzilla.com/post/1448821411/command-line-javascript-beautifier\" rel=\"nofollow\">command-line JavaScript beautifier implemented in JavaScript</a> in under 5 minutes. YMMV.</p>\n\n<blockquote>\n <ol>\n <li>Download the latest stable Rhino and unpack it somewhere, e.g. ~/dev/javascript/rhino</li>\n <li>Download beautify.js which is referenced from aforementioned jsbeautifier.org then copy it somewhere, e.g. ~/dev/javascript/bin/cli-beautifier.js</li>\n <li><p>Add this at the end of beautify.js (using some additional top-level properties to JavaScript):</p>\n\n<pre><code>// Run the beautifier on the file passed as the first argument.\nprint( j23s_beautify( readFile( arguments[0] )));\n</code></pre></li>\n <li><p>Copy-paste the following code in an executable file, e.g. ~/dev/javascript/bin/jsbeautifier.sh:</p>\n\n<pre><code>#!/bin/sh\njava -cp ~/dev/javascript/rhino/js.jar org.mozilla.javascript.tools.shell.Main ~/dev/web/javascript/bin/cli-beautifier.js $*\n</code></pre></li>\n <li><p>(optional) Add the folder with jsbeautifier.js to PATH or moving to some folder already there.</p></li>\n </ol>\n</blockquote>\n"
},
{
"answer_id": 14545400,
"author": "ioikka",
"author_id": 1662291,
"author_profile": "https://Stackoverflow.com/users/1662291",
"pm_score": 2,
"selected": false,
"text": "<p>I'm not able to add a comment to the accepted answer so that's why you see a post that should have not existed in the first place. </p>\n\n<p>Basically I also needed a javascript beautifier in a java code and to my surprise none is available as far as I could find. So I coded one myself entirely based on the accepted answer (it wraps the jsbeautifier.org beautifier .js script but is callable from java or the command line).</p>\n\n<p>The code is located at <a href=\"https://github.com/belgampaul/JsBeautifier\" rel=\"nofollow\">https://github.com/belgampaul/JsBeautifier</a></p>\n\n<p>I used rhino and beautifier.js</p>\n\n<p>USAGE from console: java -jar jsbeautifier.jar script indentation</p>\n\n<p>example: java -jar jsbeautifier.jar \"function ff() {return;}\" 2</p>\n\n<p>USAGE from java code:\npublic static String jsBeautify(String jsCode, int indentSize)</p>\n\n<p>You are welcome to extend the code. In my case I only needed the indentation so I could check the generated javascript while developing.</p>\n\n<p>In the hope it'll save you some time in your project.</p>\n"
},
{
"answer_id": 16513195,
"author": "erapert",
"author_id": 1411115,
"author_profile": "https://Stackoverflow.com/users/1411115",
"pm_score": 5,
"selected": false,
"text": "<p>If you're using nodejs then try <a href=\"https://github.com/mishoo/UglifyJS/\" rel=\"noreferrer\">uglify-js</a></p>\n\n<p>On Linux or Mac, assuming you already have nodejs installed, you can install uglify with:</p>\n\n<blockquote>\n <p><code>sudo npm install -g uglify-js</code></p>\n</blockquote>\n\n<p>And then get the options:</p>\n\n<blockquote>\n <p><code>uglifyjs -h</code></p>\n</blockquote>\n\n<p>So if I have a source file <code>foo.js</code> which looks like this:</p>\n\n<pre><code>// foo.js -- minified\nfunction foo(bar,baz){console.log(\"something something\");return true;}\n</code></pre>\n\n<p>I can beautify it like so:</p>\n\n<blockquote>\n <p><code>uglifyjs foo.js --beautify --output cutefoo.js</code></p>\n</blockquote>\n\n<p><code>uglify</code> uses spaces for indentation by default so if I want to convert the 4-space-indentation to tabs I can run it through <code>unexpand</code> which Ubuntu 12.04 comes with:</p>\n\n<blockquote>\n <p><code>unexpand --tabs=4 cutefoo.js > cuterfoo.js</code></p>\n</blockquote>\n\n<p>Or you can do it all in one go:</p>\n\n<blockquote>\n <p><code>uglifyjs foo.js --beautify | unexpand --tabs=4 > cutestfoo.js</code></p>\n</blockquote>\n\n<p>You can find out more about unexpand <a href=\"https://stackoverflow.com/questions/1424126/replace-whitespaces-with-tabs-in-linux\">here</a></p>\n\n<p>so after all this I wind up with a file that looks like so:</p>\n\n<pre><code>function foo(bar, baz) {\n console.log(\"something something\");\n return true;\n}\n</code></pre>\n\n<p><strong>update 2016-06-07</strong></p>\n\n<p>It appears that the maintainer of uglify-js is now working on <a href=\"https://github.com/mishoo/UglifyJS2\" rel=\"noreferrer\">version 2</a> though installation is the same.</p>\n"
},
{
"answer_id": 18343340,
"author": "humkins",
"author_id": 1902296,
"author_profile": "https://Stackoverflow.com/users/1902296",
"pm_score": 1,
"selected": false,
"text": "<p>I believe when you asked about command line tool you just wanted to beautify all your js files in batch. </p>\n\n<p>In this case Intellij IDEA (tested with 11.5) can do this.</p>\n\n<p>You just need to select any of your project files and select \"Code\"->\"Reformat code..\" in main IDE menu. Then in the dialog select \"all files in directory ...\" and press \"enter\".\nJust make sure you dedicated enough memory for the JVM.</p>\n"
},
{
"answer_id": 21812204,
"author": "tmaric",
"author_id": 704028,
"author_profile": "https://Stackoverflow.com/users/704028",
"pm_score": 2,
"selected": false,
"text": "<p>In the console, you can use <a href=\"http://astyle.sourceforge.net/\" rel=\"nofollow\">Artistic Style</a> (a.k.a. AStyle) with <code>--mode=java</code>.<br>\nIt works great and it's free, open-source and cross-platform (Linux, Mac OS X, Windows).</p>\n"
},
{
"answer_id": 25855828,
"author": "Tchakabam",
"author_id": 589493,
"author_profile": "https://Stackoverflow.com/users/589493",
"pm_score": 2,
"selected": false,
"text": "<p>Use the modern JavaScript way:</p>\n\n<p>Use <a href=\"http://gruntjs.com/\" rel=\"nofollow\">Grunt</a> in combination with the <a href=\"https://www.npmjs.org/package/grunt-jsbeautifier\" rel=\"nofollow\">jsbeautifier plugin for Grunt</a> </p>\n\n<p>You can install everything easily into your dev environment using <a href=\"https://www.npmjs.org/\" rel=\"nofollow\">npm</a>.</p>\n\n<p>All you will need is set up a Gruntfile.js with the appropriate tasks, which can also involve file concatenation, lint, uglify, minify etc, and run the grunt command.</p>\n"
},
{
"answer_id": 55358995,
"author": "Serge Stroobandt",
"author_id": 2192488,
"author_profile": "https://Stackoverflow.com/users/2192488",
"pm_score": 4,
"selected": false,
"text": "<h1>On Ubuntu LTS</h1>\n<pre><code>$ sudo apt install jsbeautifier\n$ js-beautify ugly.js > beautiful.js\n</code></pre>\n<p>For in place beautifying, any of the follwing commands:</p>\n<pre><code>$ js-beautify -r file.js\n$ js-beautify --replace file.js\n</code></pre>\n"
},
{
"answer_id": 63420552,
"author": "Alex Nolasco",
"author_id": 65694,
"author_profile": "https://Stackoverflow.com/users/65694",
"pm_score": 3,
"selected": false,
"text": "<p>You have a few one liner choices. Use with npm or standalone with <a href=\"https://stackoverflow.com/questions/50605219/difference-between-npx-and-npm\">npx</a>.</p>\n<p><a href=\"https://github.com/standard/semistandard\" rel=\"noreferrer\">Semistandar</a></p>\n<pre><code>npx semistandard "js/**/*.js" --fix\n</code></pre>\n<p><a href=\"https://standardjs.com/\" rel=\"noreferrer\">Standard</a></p>\n<pre><code>npx standard "js/**/*.js" --fix\n</code></pre>\n<p><a href=\"https://prettier.io/\" rel=\"noreferrer\">Prettier</a></p>\n<pre><code>npx prettier --single-quote --write --trailing-comma all "js/**/*.js"\n</code></pre>\n"
}
] | 2008/08/20 | [
"https://Stackoverflow.com/questions/18985",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/486/"
] | I am writing a batch script in order to beautify JavaScript code. It needs to work on both **Windows** and **Linux**.
How can I beautify JavaScript code using the command line tools? | First, pick your favorite Javascript based Pretty Print/Beautifier. I prefer the one at [<http://jsbeautifier.org/>](http://jsbeautifier.org/), because it's what I found first. Downloads its file <https://github.com/beautify-web/js-beautify/blob/master/js/lib/beautify.js>
Second, download and install The Mozilla group's Java based Javascript engine, [Rhino](https://www.mozilla.org/rhino/). "Install" is a little bit misleading; Download the zip file, extract everything, place js.jar in your Java classpath (or Library/Java/Extensions on OS X). You can then run scripts with an invocation similar to this
```
java -cp js.jar org.mozilla.javascript.tools.shell.Main name-of-script.js
```
Use the Pretty Print/Beautifier from step 1 to write a small shell script that will read in your javascript file and run it through the Pretty Print/Beautifier from step one. For example
```
//original code
(function() { ... js_beautify code ... }());
//new code
print(global.js_beautify(readFile(arguments[0])));
```
Rhino gives javascript a few extra useful functions that don't necessarily make sense in a browser context, but do in a console context. The function print does what you'd expect, and prints out a string. The function readFile accepts a file path string as an argument and returns the contents of that file.
You'd invoke the above something like
```
java -cp js.jar org.mozilla.javascript.tools.shell.Main beautify.js file-to-pp.js
```
You can mix and match Java and Javascript in your Rhino run scripts, so if you know a little Java it shouldn't be too hard to get this running with text-streams as well. |
19,014 | <p>I want to use Lucene (in particular, Lucene.NET) to search for email address domains.</p>
<p>E.g. I want to search for "@gmail.com" to find all emails sent to a gmail address.</p>
<p>Running a Lucene query for "*@gmail.com" results in an error, asterisks cannot be at the start of queries. Running a query for "@gmail.com" doesn't return any matches, because "[email protected]" is seen as a whole word, and you cannot search for just parts of a word.</p>
<p>How can I do this?</p>
| [
{
"answer_id": 20468,
"author": "Judah Gabriel Himango",
"author_id": 536,
"author_profile": "https://Stackoverflow.com/users/536",
"pm_score": 5,
"selected": true,
"text": "<p>No one gave a satisfactory answer, so we started poking around Lucene documentation and discovered we can accomplish this using custom Analyzers and Tokenizers.</p>\n\n<p>The answer is this: create a WhitespaceAndAtSymbolTokenizer and a WhitespaceAndAtSymbolAnalyzer, then recreate your index using this analyzer. Once you do this, a search for \"@gmail.com\" will return all gmail addresses, because it's seen as a separate word thanks to the Tokenizer we just created.</p>\n\n<p>Here's the source code, it's actually very simple:</p>\n\n<pre><code>class WhitespaceAndAtSymbolTokenizer : CharTokenizer\n{\n public WhitespaceAndAtSymbolTokenizer(TextReader input)\n : base(input)\n {\n }\n\n protected override bool IsTokenChar(char c)\n {\n // Make whitespace characters and the @ symbol be indicators of new words.\n return !(char.IsWhiteSpace(c) || c == '@');\n }\n}\n\n\ninternal class WhitespaceAndAtSymbolAnalyzer : Analyzer\n{\n public override TokenStream TokenStream(string fieldName, TextReader reader)\n {\n return new WhitespaceAndAtSymbolTokenizer(reader);\n }\n}\n</code></pre>\n\n<p>That's it! Now you just need to rebuild your index and do all searches using this new Analyzer. For example, to write documents to your index:</p>\n\n<pre><code>IndexWriter index = new IndexWriter(indexDirectory, new WhitespaceAndAtSymbolAnalyzer());\nindex.AddDocument(myDocument);\n</code></pre>\n\n<p>Performing searches should use the analyzer as well:</p>\n\n<pre><code>IndexSearcher searcher = new IndexSearcher(indexDirectory);\nQuery query = new QueryParser(\"TheFieldNameToSearch\", new WhitespaceAndAtSymbolAnalyzer()).Parse(\"@gmail.com\");\nHits hits = query.Search(query);\n</code></pre>\n"
},
{
"answer_id": 23488,
"author": "dlamblin",
"author_id": 459,
"author_profile": "https://Stackoverflow.com/users/459",
"pm_score": 3,
"selected": false,
"text": "<p>I see you have your solution, but mine would have avoided this and added a field to the documents you're indexing called email_domain, into which I would have added the parsed out domain of the email address. It might sound silly, but the amount of storage associated with this is pretty minimal. If you feel like getting fancier, say some domain had many subdomains, you could instead make a field into which the reversed domain went, so you'd store com.gmail, com.company.department, or ae.eim so you could find all the United Arab Emirates related addresses with a prefix query of 'ae.'</p>\n"
},
{
"answer_id": 83669,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 0,
"selected": false,
"text": "<p>You could a separate field that indexes the email address reversed:\nIndex '[email protected]' as 'moc.liamg@oof'\nWhich enables you to do a query for \"moc.liamg@*\" </p>\n"
},
{
"answer_id": 100285,
"author": "Markus",
"author_id": 18597,
"author_profile": "https://Stackoverflow.com/users/18597",
"pm_score": 2,
"selected": false,
"text": "<p>There also is <a href=\"http://lucene.apache.org/java/2_3_2/api/org/apache/lucene/queryParser/QueryParser.html#setAllowLeadingWildcard(boolean)\" rel=\"nofollow noreferrer\"><strong>setAllowLeadingWildcard</strong></a></p>\n\n<p>But be <strong>careful</strong>. This could get very performance expensive (thats why it is disabled by default). Maybe in some cases this would be an easy solution, but I would prefer a custom Tokenizer as stated by <a href=\"https://stackoverflow.com/questions/19014/using-lucene-to-search-for-email-addresses#20468\">Judah Himango</a>, too.</p>\n"
}
] | 2008/08/20 | [
"https://Stackoverflow.com/questions/19014",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/536/"
] | I want to use Lucene (in particular, Lucene.NET) to search for email address domains.
E.g. I want to search for "@gmail.com" to find all emails sent to a gmail address.
Running a Lucene query for "\*@gmail.com" results in an error, asterisks cannot be at the start of queries. Running a query for "@gmail.com" doesn't return any matches, because "[email protected]" is seen as a whole word, and you cannot search for just parts of a word.
How can I do this? | No one gave a satisfactory answer, so we started poking around Lucene documentation and discovered we can accomplish this using custom Analyzers and Tokenizers.
The answer is this: create a WhitespaceAndAtSymbolTokenizer and a WhitespaceAndAtSymbolAnalyzer, then recreate your index using this analyzer. Once you do this, a search for "@gmail.com" will return all gmail addresses, because it's seen as a separate word thanks to the Tokenizer we just created.
Here's the source code, it's actually very simple:
```
class WhitespaceAndAtSymbolTokenizer : CharTokenizer
{
public WhitespaceAndAtSymbolTokenizer(TextReader input)
: base(input)
{
}
protected override bool IsTokenChar(char c)
{
// Make whitespace characters and the @ symbol be indicators of new words.
return !(char.IsWhiteSpace(c) || c == '@');
}
}
internal class WhitespaceAndAtSymbolAnalyzer : Analyzer
{
public override TokenStream TokenStream(string fieldName, TextReader reader)
{
return new WhitespaceAndAtSymbolTokenizer(reader);
}
}
```
That's it! Now you just need to rebuild your index and do all searches using this new Analyzer. For example, to write documents to your index:
```
IndexWriter index = new IndexWriter(indexDirectory, new WhitespaceAndAtSymbolAnalyzer());
index.AddDocument(myDocument);
```
Performing searches should use the analyzer as well:
```
IndexSearcher searcher = new IndexSearcher(indexDirectory);
Query query = new QueryParser("TheFieldNameToSearch", new WhitespaceAndAtSymbolAnalyzer()).Parse("@gmail.com");
Hits hits = query.Search(query);
``` |
19,030 | <p>I have a bunch of files (TV episodes, although that is fairly arbitrary) that I want to check match a specific naming/organisation scheme..</p>
<p>Currently: I have three arrays of regex, one for valid filenames, one for files missing an episode name, and one for valid paths.</p>
<p>Then, I loop though each valid-filename regex, if it matches, append it to a "valid" dict, if not, do the same with the missing-ep-name regexs, if it matches this I append it to an "invalid" dict with an error code (2:'missing epsiode name'), if it matches neither, it gets added to invalid with the 'malformed name' error code.</p>
<p>The current code can be found <a href="http://github.com/dbr/checktveps/tree/8a6dc68ad61e684c8d8f0ca1dc37a22d1c51aa82/2checkTvEps.py" rel="nofollow noreferrer">here</a></p>
<p>I want to add a rule that checks for the presence of a folder.jpg file in each directory, but to add this would make the code substantially more messy in it's current state.. </p>
<p>How could I write this system in a more expandable way?</p>
<p>The rules it needs to check would be..</p>
<ul>
<li>File is in the format <code>Show Name - [01x23] - Episode Name.avi</code> or <code>Show Name - [01xSpecial02] - Special Name.avi</code> or <code>Show Name - [01xExtra01] - Extra Name.avi</code></li>
<li>If filename is in the format <code>Show Name - [01x23].avi</code> display it a 'missing episode name' section of the output</li>
<li>The path should be in the format <code>Show Name/season 2/the_file.avi</code> (where season 2 should be the correct season number in the filename)</li>
<li>each <code>Show Name/season 1/</code> folder should contain "folder.jpg"</li>
</ul>
<p>.any ideas? While I'm trying to check TV episodes, this concept/code should be able to apply to many things..</p>
<p>The only thought I had was a list of dicts in the format:</p>
<pre><code>checker = [
{
'name':'valid files',
'type':'file',
'function':check_valid(), # runs check_valid() on all files
'status':0 # if it returns True, this is the status the file gets
}
</code></pre>
| [
{
"answer_id": 19389,
"author": "sven",
"author_id": 46,
"author_profile": "https://Stackoverflow.com/users/46",
"pm_score": 0,
"selected": false,
"text": "<p>maybe you should take the approach of defaulting to: \"the filename is correct\" and work from there to disprove that statement:</p>\n\n<p>with the fact that you only allow filenames with: 'show name', 'season number x episode number' and 'episode name', you know for certain that these items should be separated by a \"-\" (dash) so you have to have 2 of those for a filename to be correct.<br>\nif that checks out, you can use your code to check that the show name matches the show name as seen in the parent's parent folder (case insensitive i assume), the season number matches the parents folder numeric value (with or without an extra 0 prepended).</p>\n\n<p>if however you don't see the correct amount of dashes you instantly know that there is something wrong and stop before the rest of the tests etc.</p>\n\n<p>and separately you can check if the file <code>folder.jpg</code> exists and take the necessary actions. <strong>or</strong> do that first and filter that file from the rest of the files in that folder.</p>\n"
},
{
"answer_id": 21302,
"author": "Joseph Pecoraro",
"author_id": 792,
"author_profile": "https://Stackoverflow.com/users/792",
"pm_score": 3,
"selected": true,
"text": "<blockquote>\n <p>I want to add a rule that checks for\n the presence of a folder.jpg file in\n each directory, but to add this would\n make the code substantially more messy\n in it's current state..</p>\n</blockquote>\n\n<p>This doesn't look bad. In fact your current code does it very nicely, and Sven mentioned a good way to do it as well:</p>\n\n<ol>\n<li>Get a list of all the files</li>\n<li>Check for \"required\" files</li>\n</ol>\n\n<p>You would just have have add to your dictionary a list of required files:</p>\n\n<pre><code>checker = {\n ...\n 'required': ['file', 'list', 'for_required']\n}\n</code></pre>\n\n<p>As far as there being a better/extensible way to do this? I am not exactly sure. I could only really think of a way to possibly drop the \"multiple\" regular expressions and build off of Sven's idea for using a delimiter. So my strategy would be defining a dictionary as follows (and I'm sorry I don't know Python syntax and I'm a tad to lazy to look it up but it should make sense. The /regex/ is shorthand for a regex):</p>\n\n<pre><code>check_dict = {\n 'delim' : /\\-/,\n 'parts' : [ 'Show Name', 'Episode Name', 'Episode Number' ],\n 'patterns' : [/valid name/, /valid episode name/, /valid number/ ],\n 'required' : ['list', 'of', 'files'],\n 'ignored' : ['.*', 'hidden.txt'],\n 'start_dir': '/path/to/dir/to/test/'\n}\n</code></pre>\n\n<ol>\n<li>Split the filename based on the delimiter.</li>\n<li>Check each of the parts.</li>\n</ol>\n\n<p>Because its an ordered list you can determine what parts are missing and if a section doesn't match any pattern it is malformed. Here the <code>parts</code> and <code>patterns</code> have a 1 to 1 ratio. Two arrays instead of a dictionary enforces the order.</p>\n\n<p>Ignored and required files can be listed. The <code>.</code> and <code>..</code> files should probably be ignored automatically. The user should be allowed to input \"globs\" which can be shell expanded. I'm thinking here of <code>svn:ignore</code> properties, but globbing is natural for listing files.</p>\n\n<p>Here <code>start_dir</code> would be default to the current directory but if you wanted a single file to run automated testing of a bunch of directories this would be useful.</p>\n\n<p>The real loose end here is the path template and along the same lines what path is required for \"valid files\". I really couldn't come up with a solid idea without writing one large regular expression and taking groups from it... to build a template. It felt a lot like writing a TextMate language grammar. But that starts to stray on the ease of use. The real problem was that the path template was not composed of <code>parts</code>, which makes sense but adds complexity.</p>\n\n<p>Is this strategy in tune with what you were thinking of?</p>\n"
}
] | 2008/08/20 | [
"https://Stackoverflow.com/questions/19030",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/745/"
] | I have a bunch of files (TV episodes, although that is fairly arbitrary) that I want to check match a specific naming/organisation scheme..
Currently: I have three arrays of regex, one for valid filenames, one for files missing an episode name, and one for valid paths.
Then, I loop though each valid-filename regex, if it matches, append it to a "valid" dict, if not, do the same with the missing-ep-name regexs, if it matches this I append it to an "invalid" dict with an error code (2:'missing epsiode name'), if it matches neither, it gets added to invalid with the 'malformed name' error code.
The current code can be found [here](http://github.com/dbr/checktveps/tree/8a6dc68ad61e684c8d8f0ca1dc37a22d1c51aa82/2checkTvEps.py)
I want to add a rule that checks for the presence of a folder.jpg file in each directory, but to add this would make the code substantially more messy in it's current state..
How could I write this system in a more expandable way?
The rules it needs to check would be..
* File is in the format `Show Name - [01x23] - Episode Name.avi` or `Show Name - [01xSpecial02] - Special Name.avi` or `Show Name - [01xExtra01] - Extra Name.avi`
* If filename is in the format `Show Name - [01x23].avi` display it a 'missing episode name' section of the output
* The path should be in the format `Show Name/season 2/the_file.avi` (where season 2 should be the correct season number in the filename)
* each `Show Name/season 1/` folder should contain "folder.jpg"
.any ideas? While I'm trying to check TV episodes, this concept/code should be able to apply to many things..
The only thought I had was a list of dicts in the format:
```
checker = [
{
'name':'valid files',
'type':'file',
'function':check_valid(), # runs check_valid() on all files
'status':0 # if it returns True, this is the status the file gets
}
``` | >
> I want to add a rule that checks for
> the presence of a folder.jpg file in
> each directory, but to add this would
> make the code substantially more messy
> in it's current state..
>
>
>
This doesn't look bad. In fact your current code does it very nicely, and Sven mentioned a good way to do it as well:
1. Get a list of all the files
2. Check for "required" files
You would just have have add to your dictionary a list of required files:
```
checker = {
...
'required': ['file', 'list', 'for_required']
}
```
As far as there being a better/extensible way to do this? I am not exactly sure. I could only really think of a way to possibly drop the "multiple" regular expressions and build off of Sven's idea for using a delimiter. So my strategy would be defining a dictionary as follows (and I'm sorry I don't know Python syntax and I'm a tad to lazy to look it up but it should make sense. The /regex/ is shorthand for a regex):
```
check_dict = {
'delim' : /\-/,
'parts' : [ 'Show Name', 'Episode Name', 'Episode Number' ],
'patterns' : [/valid name/, /valid episode name/, /valid number/ ],
'required' : ['list', 'of', 'files'],
'ignored' : ['.*', 'hidden.txt'],
'start_dir': '/path/to/dir/to/test/'
}
```
1. Split the filename based on the delimiter.
2. Check each of the parts.
Because its an ordered list you can determine what parts are missing and if a section doesn't match any pattern it is malformed. Here the `parts` and `patterns` have a 1 to 1 ratio. Two arrays instead of a dictionary enforces the order.
Ignored and required files can be listed. The `.` and `..` files should probably be ignored automatically. The user should be allowed to input "globs" which can be shell expanded. I'm thinking here of `svn:ignore` properties, but globbing is natural for listing files.
Here `start_dir` would be default to the current directory but if you wanted a single file to run automated testing of a bunch of directories this would be useful.
The real loose end here is the path template and along the same lines what path is required for "valid files". I really couldn't come up with a solid idea without writing one large regular expression and taking groups from it... to build a template. It felt a lot like writing a TextMate language grammar. But that starts to stray on the ease of use. The real problem was that the path template was not composed of `parts`, which makes sense but adds complexity.
Is this strategy in tune with what you were thinking of? |
19,035 | <p>I am working with both <a href="http://activemq.apache.org/ajax.html" rel="nofollow noreferrer">amq.js</a> (ActiveMQ) and <a href="http://code.google.com/apis/maps/documentation/reference.html" rel="nofollow noreferrer">Google Maps</a>. I load my scripts in this order</p>
<pre><code><head>
<meta http-equiv="content-type" content="text/html;charset=UTF-8" />
<title>AMQ & Maps Demo</title>
<!-- Stylesheet -->
<link rel="stylesheet" type="text/css" href="style.css"></link>
<!-- Google APIs -->
<script type="text/javascript" src="http://www.google.com/jsapi?key=abcdefg"></script>
<!-- Active MQ -->
<script type="text/javascript" src="amq/amq.js"></script>
<script type="text/javascript">amq.uri='amq';</script>
<!-- Application -->
<script type="text/javascript" src="application.js"></script>
</head>
</code></pre>
<p>However in my application.js it loads Maps fine but I get an error when trying to subscribe to a Topic with AMQ. AMQ depends on prototype which the error console in Firefox says object is not defined. I think I have a problem with using the amq object before the script is finished loading. <strong>Is there a way to make sure both scripts load before I use them in my application.js?</strong> </p>
<p>Google has this nice function call <code>google.setOnLoadCallback(initialize);</code> which works great. I'm not sure amq.js has something like this.</p>
| [
{
"answer_id": 19067,
"author": "maxsilver",
"author_id": 1477,
"author_profile": "https://Stackoverflow.com/users/1477",
"pm_score": 2,
"selected": false,
"text": "<blockquote>\n <p><strong>Is there a way to make sure both scripts load before I use them?</strong></p>\n</blockquote>\n\n<p>Yes.</p>\n\n<p>Put the code you want loaded last (your <code>application.js</code> stuff) into prototype's <a href=\"http://www.prototypejs.org/api/document/observe\" rel=\"nofollow noreferrer\">document.observe</a>. This should ensure that the code will load only after prototype + other stuff is finished and ready. (If you are familiar with jQuery, this function is similar to jQuery's <code>$(document).ready</code> )</p>\n"
},
{
"answer_id": 19069,
"author": "danb",
"author_id": 2031,
"author_profile": "https://Stackoverflow.com/users/2031",
"pm_score": 3,
"selected": false,
"text": "<p>in jquery you can use: </p>\n\n<pre><code>$(document).ready(function(){/*do stuff here*/});\n</code></pre>\n\n<p>which makes sure the javascript is loaded and the dom is ready before doing your stuff.</p>\n\n<p>in prototype it looks like this might work</p>\n\n<pre><code>document.observe(\"dom:loaded\", function() {/*do stuff here*/});\n</code></pre>\n\n<p>If I understand your problem correctly.. I think that may help..</p>\n\n<p>If you don't want to rely on a lib to do this... I think this might work:</p>\n\n<pre><code><script>\n function doIt() {/*do stuff here*/}\n</script>\n<body onLoad=\"doIt();\"></body>\n</code></pre>\n"
},
{
"answer_id": 19276,
"author": "Walter Rumsby",
"author_id": 1654,
"author_profile": "https://Stackoverflow.com/users/1654",
"pm_score": 2,
"selected": false,
"text": "<blockquote>\n <p>AMQ depends on prototype which the error console in FireFox says object is not defined.</p>\n</blockquote>\n\n<p>Do you mean that AMQ depends on the <a href=\"http://www.prototypejs.org/\" rel=\"nofollow noreferrer\">Prototype library</a>? I can't see an import for that library in the code you've provided.</p>\n"
},
{
"answer_id": 19348,
"author": "Walter Rumsby",
"author_id": 1654,
"author_profile": "https://Stackoverflow.com/users/1654",
"pm_score": 6,
"selected": true,
"text": "<blockquote>\n <p><strong>Is there a way to make sure both scripts load before I use them in my application.js?</strong></p>\n</blockquote>\n\n<p>JavaScript files should load sequentially <em>and block</em> so unless the scripts you are depending on are doing something unusual all you should need to do is load application.js after the other files.</p>\n\n<p><a href=\"http://yuiblog.com/blog/2008/07/22/non-blocking-scripts/\" rel=\"noreferrer\">Non-blocking JavaScript Downloads</a> has some information about how scripts load (and discusses some techniques to subvert the blocking).</p>\n"
},
{
"answer_id": 20504,
"author": "Bernie Perez",
"author_id": 1992,
"author_profile": "https://Stackoverflow.com/users/1992",
"pm_score": 2,
"selected": false,
"text": "<blockquote>\n <p>Do you mean that AMQ depends on the\n Prototype library? I can't see an\n import for that library in the code\n you've provided.</p>\n</blockquote>\n\n<p>Yes for ActiveMQ's javascript (amq.js) does depend on Prototype. In the amq.js it loads 3 scripts, _amq.js, behaviour.js and prototype.js.</p>\n\n<p>Thanks you for your help on the JavaScript load order wrumsby. This tells me that my bug is in another castle :(</p>\n\n<p>I guess I have a different problem. I also checked the js files from ActiveMQ 5.0 to 5.1 and noticed they were the same as well. Something has changed in 5.0 to 5.1 that requires a refresh for the topics to subscribe. I'll keep looking, but thanks for eliminating this possible cause.</p>\n"
},
{
"answer_id": 601866,
"author": "cmcginty",
"author_id": 64313,
"author_profile": "https://Stackoverflow.com/users/64313",
"pm_score": 3,
"selected": false,
"text": "<p>I had a similar problem to this, only with a single script. The solution I came up with was to use <code>addEventListener(\"load\",fn,false)</code> to a <code>script</code> object created using <code>document.createElement('script')</code> Here is the final function which loads any standard JS file and lets you add a \"post load\" script.</p>\n\n<pre><code>function addJavaScript( js, onload ) {\n var head, ref;\n head = document.getElementsByTagName('head')[0];\n if (!head) { return; }\n script = document.createElement('script');\n script.type = 'text/javascript';\n script.src = js;\n script.addEventListener( \"load\", onload, false );\n head.appendChild(script);\n}\n</code></pre>\n\n<p>I hope this may help someone in the future.</p>\n"
},
{
"answer_id": 5147936,
"author": "John Doe",
"author_id": 638415,
"author_profile": "https://Stackoverflow.com/users/638415",
"pm_score": 5,
"selected": false,
"text": "<p>cross-domain scripts are loaded after scripts of site itself, this is why you get errors. interestingly, nobody knows this here.</p>\n"
},
{
"answer_id": 11761498,
"author": "Brian Scott",
"author_id": 135731,
"author_profile": "https://Stackoverflow.com/users/135731",
"pm_score": 0,
"selected": false,
"text": "<p>You can also use the built in SharePoint javascript method to control the execution of your scripts;</p>\n\n<pre><code>_spBodyOnLoadFunctionNames.push(\"yourFunction\");\n</code></pre>\n"
}
] | 2008/08/20 | [
"https://Stackoverflow.com/questions/19035",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1992/"
] | I am working with both [amq.js](http://activemq.apache.org/ajax.html) (ActiveMQ) and [Google Maps](http://code.google.com/apis/maps/documentation/reference.html). I load my scripts in this order
```
<head>
<meta http-equiv="content-type" content="text/html;charset=UTF-8" />
<title>AMQ & Maps Demo</title>
<!-- Stylesheet -->
<link rel="stylesheet" type="text/css" href="style.css"></link>
<!-- Google APIs -->
<script type="text/javascript" src="http://www.google.com/jsapi?key=abcdefg"></script>
<!-- Active MQ -->
<script type="text/javascript" src="amq/amq.js"></script>
<script type="text/javascript">amq.uri='amq';</script>
<!-- Application -->
<script type="text/javascript" src="application.js"></script>
</head>
```
However in my application.js it loads Maps fine but I get an error when trying to subscribe to a Topic with AMQ. AMQ depends on prototype which the error console in Firefox says object is not defined. I think I have a problem with using the amq object before the script is finished loading. **Is there a way to make sure both scripts load before I use them in my application.js?**
Google has this nice function call `google.setOnLoadCallback(initialize);` which works great. I'm not sure amq.js has something like this. | >
> **Is there a way to make sure both scripts load before I use them in my application.js?**
>
>
>
JavaScript files should load sequentially *and block* so unless the scripts you are depending on are doing something unusual all you should need to do is load application.js after the other files.
[Non-blocking JavaScript Downloads](http://yuiblog.com/blog/2008/07/22/non-blocking-scripts/) has some information about how scripts load (and discusses some techniques to subvert the blocking). |
19,047 | <p>After upgrading to the latest version of TortoiseSVN (1.5.2.13595), it's context menu is no longer available.</p>
<p>When attempting to run it manually, I get this error:</p>
<pre><code>The application has failed to start because its side-by-side configuration is incorrect.
Please see the application event log for more detail
</code></pre>
<p>The application log shows this</p>
<pre><code>Activation context generation failed for "C:\Program Files\TortoiseSVN\bin\TortoiseSVN.dll".
Dependent Assembly Microsoft.VC90.CRT,processorArchitecture="x86",publicKeyToken="1fc8b3b9a1e18e3b",type="win32",version="9.0.30411.0" could not be found.
Please use sxstrace.exe for detailed diagnosis.
</code></pre>
| [
{
"answer_id": 19053,
"author": "Orion Edwards",
"author_id": 234,
"author_profile": "https://Stackoverflow.com/users/234",
"pm_score": 4,
"selected": true,
"text": "<p>I remembered I'd seen this thing before just after posting to SO</p>\n\n<p>It seems that later versions of TortoiseSVN are built with Visual Studio 2008 SP1 (hence the 9.0.30411.0 build number)</p>\n\n<p>Installing the <a href=\"http://www.microsoft.com/downloads/details.aspx?familyid=A5C84275-3B97-4AB7-A40D-3802B2AF5FC2&displaylang=en\" rel=\"noreferrer\">VC2008 SP1 Redistributable</a> fixes it</p>\n"
},
{
"answer_id": 1664190,
"author": "thejspr",
"author_id": 321060,
"author_profile": "https://Stackoverflow.com/users/321060",
"pm_score": 0,
"selected": false,
"text": "<p>Confirmed working on windows 7 x64.</p>\n"
}
] | 2008/08/20 | [
"https://Stackoverflow.com/questions/19047",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/234/"
] | After upgrading to the latest version of TortoiseSVN (1.5.2.13595), it's context menu is no longer available.
When attempting to run it manually, I get this error:
```
The application has failed to start because its side-by-side configuration is incorrect.
Please see the application event log for more detail
```
The application log shows this
```
Activation context generation failed for "C:\Program Files\TortoiseSVN\bin\TortoiseSVN.dll".
Dependent Assembly Microsoft.VC90.CRT,processorArchitecture="x86",publicKeyToken="1fc8b3b9a1e18e3b",type="win32",version="9.0.30411.0" could not be found.
Please use sxstrace.exe for detailed diagnosis.
``` | I remembered I'd seen this thing before just after posting to SO
It seems that later versions of TortoiseSVN are built with Visual Studio 2008 SP1 (hence the 9.0.30411.0 build number)
Installing the [VC2008 SP1 Redistributable](http://www.microsoft.com/downloads/details.aspx?familyid=A5C84275-3B97-4AB7-A40D-3802B2AF5FC2&displaylang=en) fixes it |
19,058 | <p>Example:</p>
<pre><code>select ename from emp where hiredate = todate('01/05/81','dd/mm/yy')
</code></pre>
<p>and </p>
<pre><code>select ename from emp where hiredate = todate('01/05/81','dd/mm/rr')
</code></pre>
<p>return different results</p>
| [
{
"answer_id": 19061,
"author": "Michael Stum",
"author_id": 91,
"author_profile": "https://Stackoverflow.com/users/91",
"pm_score": 7,
"selected": true,
"text": "<p><a href=\"http://oracle.ittoolbox.com/groups/technical-functional/oracle-dev-l/difference-between-yyyy-and-rrrr-format-519525\" rel=\"noreferrer\">http://oracle.ittoolbox.com/groups/technical-functional/oracle-dev-l/difference-between-yyyy-and-rrrr-format-519525</a></p>\n\n<blockquote>\n <p>YY allows you to retrieve just two digits of a year, for example, the 99 in\n 1999. The other digits (19) are automatically assigned to the current\n century. RR converts two-digit years into four-digit years by rounding.</p>\n \n <p>50-99 are stored as 1950-1999, and dates ending in 00-49 are stored as\n 2000-2049. RRRR accepts a four-digit input (although not required), and\n converts two-digit dates as RR does. YYYY accepts 4-digit inputs butdoesn't\n do any date converting</p>\n</blockquote>\n\n<p>Essentially, your first example will assume that 81 is 2081 whereas the RR one assumes 1981. So the first example should not return any rows as you most likely did not hire any guys after May 1 2081 yet :-)</p>\n"
},
{
"answer_id": 19062,
"author": "mauriciopastrana",
"author_id": 547,
"author_profile": "https://Stackoverflow.com/users/547",
"pm_score": 3,
"selected": false,
"text": "<p>y2k compatibility. rr assumes 01 to be 2001, yy assumes 01 to be 1901</p>\n\n<p>see: <a href=\"http://www.oradev.com/oracle_date_format.jsp\" rel=\"nofollow noreferrer\">http://www.oradev.com/oracle_date_format.jsp</a></p>\n\n<p>edit: damn! <a href=\"https://stackoverflow.com/users/91/michael-stum\">michael \"quickfingers\" stum</a> <a href=\"https://stackoverflow.com/questions/19058/what-is-the-difference-between-oracles-yy-and-rr-date-mask#19061\">beat me to it</a>!</p>\n\n<p>/mp</p>\n"
},
{
"answer_id": 19202,
"author": "mauriciopastrana",
"author_id": 547,
"author_profile": "https://Stackoverflow.com/users/547",
"pm_score": 3,
"selected": false,
"text": "<p>@<a href=\"https://stackoverflow.com/questions/19058/what-is-the-difference-between-oracles-yy-and-rr-date-mask#19066\">Michael Stum</a></p>\n\n<blockquote>\n <p>My last Oracle experience is a bit long ago</p>\n</blockquote>\n\n<p>uhm, was it, before 2000? :p</p>\n\n<p>...</p>\n\n<blockquote>\n <p>Will yy always assume 19xx? </p>\n</blockquote>\n\n<p><a href=\"http://oracle.ittoolbox.com/groups/technical-functional/oracle-dev-l/difference-between-yyyy-and-rrrr-format-519525#\" rel=\"nofollow noreferrer\">according to your source</a>, we get the following scenarios:</p>\n\n<pre><code>USING\nENTERED\nSTORED\nSELECT of date column\n\n\nYY\n22-FEB-01\n22-FEB-1901\n22-FEB-01\n\n\nYYYY\n22-FEB-01\n22-FEB-0001\n22-FEB-0001\n\n\nRR\n22-FEB-01\n22-FEB-2001\n22-FEB-01\n\n\nRRRR\n22-FEB-01\n22-FEB-2001\n22-FEB-2001 \n</code></pre>\n\n<p>/mp</p>\n"
},
{
"answer_id": 1042506,
"author": "vivek",
"author_id": 100823,
"author_profile": "https://Stackoverflow.com/users/100823",
"pm_score": -1,
"selected": false,
"text": "<p>RR stands for after 1990 and yy assumes 90 as 2090....as we are in the current yr,...</p>\n"
},
{
"answer_id": 5740115,
"author": "hariharan",
"author_id": 718361,
"author_profile": "https://Stackoverflow.com/users/718361",
"pm_score": 1,
"selected": false,
"text": "<p>RR displays four digits as 1999 or 2015(if it is <49 then it will consider 20th century)</p>\n"
},
{
"answer_id": 34434455,
"author": "Pritam Bhansali",
"author_id": 4585034,
"author_profile": "https://Stackoverflow.com/users/4585034",
"pm_score": 0,
"selected": false,
"text": "<h1>About RR or RRRR</h1>\n\n<p>When we are inserting the dates with 2 digits years (i.e. 09/oct/15)\nthen Oracle may changes the centuries automatically hence the \nsolution is 4 digit dates. But 4 digit version is introduced in \nsome recent versions, therefore the solutions for this problem \nin earlier versions was <code>RR</code> or <code>RRRR</code>. But note that it only works \nwith the <code>TO_DATE()</code> function but not with the <code>TO_CHAR()</code> function.</p>\n\n<p>Whenever inserts/updates are conducted upon dates we should always clarify current date running in the clock in association with the date translation since Oracle conducts every date translation by contacting the server.</p>\n\n<p>In order to keep the consistencies among the centuries, it is always better to execute the date translation with 4 digit years.</p>\n\n<h1>About YY or YYYY</h1>\n\n<p>It accepts the dates but doesn't has functionality to automatically change it.</p>\n\n<p><a href=\"https://i.stack.imgur.com/zVJ8D.png\" rel=\"nofollow noreferrer\">This Image shows behaviour when inserting date with two digit (i.e. \n09/oct/15)</a></p>\n"
}
] | 2008/08/20 | [
"https://Stackoverflow.com/questions/19058",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1782/"
] | Example:
```
select ename from emp where hiredate = todate('01/05/81','dd/mm/yy')
```
and
```
select ename from emp where hiredate = todate('01/05/81','dd/mm/rr')
```
return different results | <http://oracle.ittoolbox.com/groups/technical-functional/oracle-dev-l/difference-between-yyyy-and-rrrr-format-519525>
>
> YY allows you to retrieve just two digits of a year, for example, the 99 in
> 1999. The other digits (19) are automatically assigned to the current
> century. RR converts two-digit years into four-digit years by rounding.
>
>
> 50-99 are stored as 1950-1999, and dates ending in 00-49 are stored as
> 2000-2049. RRRR accepts a four-digit input (although not required), and
> converts two-digit dates as RR does. YYYY accepts 4-digit inputs butdoesn't
> do any date converting
>
>
>
Essentially, your first example will assume that 81 is 2081 whereas the RR one assumes 1981. So the first example should not return any rows as you most likely did not hire any guys after May 1 2081 yet :-) |
19,089 | <p>I have a view that has a list of jobs in it, with data like who they're assigned to and the stage they are in. I need to write a stored procedure that returns how many jobs each person has at each stage.</p>
<p>So far I have this (simplified):</p>
<pre><code>DECLARE @ResultTable table
(
StaffName nvarchar(100),
Stage1Count int,
Stage2Count int
)
INSERT INTO @ResultTable (StaffName, Stage1Count)
SELECT StaffName, COUNT(*) FROM ViewJob
WHERE InStage1 = 1
GROUP BY StaffName
INSERT INTO @ResultTable (StaffName, Stage2Count)
SELECT StaffName, COUNT(*) FROM ViewJob
WHERE InStage2 = 1
GROUP BY StaffName
</code></pre>
<p>The problem with that is that the rows don't combine. So if a staff member has jobs in stage1 and stage2 there's two rows in @ResultTable. What I would really like to do is to update the row if one exists for the staff member and insert a new row if one doesn't exist.</p>
<p>Does anyone know how to do this, or can suggest a different approach?
I would really like to avoid using cursors to iterate on the list of users (but that's my fall back option).</p>
<p>I'm using SQL Server 2005.</p>
<p><strong>Edit: @Lee:</strong> Unfortunately the InStage1 = 1 was a simplification. It's really more like WHERE DateStarted IS NOT NULL and DateFinished IS NULL.</p>
<p><strong>Edit: @BCS:</strong> I like the idea of doing an insert of all the staff first so I just have to do an update every time. But I'm struggling to get those UPDATE statements correct.</p>
| [
{
"answer_id": 19097,
"author": "AlexCuse",
"author_id": 794,
"author_profile": "https://Stackoverflow.com/users/794",
"pm_score": 1,
"selected": false,
"text": "<p>To get a real \"upsert\" type of query you need to use an if exists... type of thing, and this unfortunately means using a cursor.</p>\n\n<p>However, you could run two queries, one to do your updates where there is an existing row, then afterwards insert the new one. I'd think this set-based approach would be preferable unless you're dealing exclusively with small numbers of rows.</p>\n"
},
{
"answer_id": 19098,
"author": "Ryan Farley",
"author_id": 1627,
"author_profile": "https://Stackoverflow.com/users/1627",
"pm_score": 2,
"selected": false,
"text": "<p>You could just check for existence and use the appropriate command. I believe this really does use a cursor behind the scenes, but it's the best you'll likely get: </p>\n\n<pre><code>IF (EXISTS (SELECT * FROM MyTable WHERE StaffName = @StaffName))\nbegin\n UPDATE MyTable SET ... WHERE StaffName = @StaffName\nend\nelse\nbegin\n INSERT MyTable ...\nend \n</code></pre>\n\n<p>SQL2008 has a new MERGE capability which is cool, but it's not in 2005.</p>\n"
},
{
"answer_id": 19099,
"author": "Lee",
"author_id": 1954,
"author_profile": "https://Stackoverflow.com/users/1954",
"pm_score": 2,
"selected": false,
"text": "<p>Actually, I think you're making it much harder than it is. Won't this code work for what you're trying to do?</p>\n\n<pre><code>SELECT StaffName, SUM(InStage1) AS 'JobsAtStage1', SUM(InStage2) AS 'JobsAtStage2'\n FROM ViewJob\nGROUP BY StaffName\n</code></pre>\n"
},
{
"answer_id": 19105,
"author": "Blorgbeard",
"author_id": 369,
"author_profile": "https://Stackoverflow.com/users/369",
"pm_score": 0,
"selected": false,
"text": "<p>The following query on your result table should combine the rows again. This is assuming that InStage1 and InStage2 are never both '1'.</p>\n\n<pre><code>select distinct(rt1.StaffName), rt2.Stage1Count, rt3.Stage2Count\nfrom @ResultTable rt1\nleft join @ResultTable rt2 on rt1.StaffName=rt2.StaffName and rt2.Stage1Count is not null\nleft join @ResultTable rt3 on rt1.StaffName=rt2.StaffName and rt3.Stage2Count is not null\n</code></pre>\n"
},
{
"answer_id": 19109,
"author": "BCS",
"author_id": 1343,
"author_profile": "https://Stackoverflow.com/users/1343",
"pm_score": 2,
"selected": true,
"text": "<p>IIRC there is some sort of \"On Duplicate\" (name might be wrong) syntax that lets you update if a row exists (MySQL)</p>\n\n<p>Alternately some form of:</p>\n\n<pre><code>INSERT INTO @ResultTable (StaffName, Stage1Count, Stage2Count)\n SELECT StaffName,0,0 FROM ViewJob\n GROUP BY StaffName\n\nUPDATE @ResultTable Stage1Count= (\n SELECT COUNT(*) AS count FROM ViewJob\n WHERE InStage1 = 1\n @ResultTable.StaffName = StaffName)\n\nUPDATE @ResultTable Stage2Count= (\n SELECT COUNT(*) AS count FROM ViewJob\n WHERE InStage2 = 1\n @ResultTable.StaffName = StaffName)\n</code></pre>\n"
},
{
"answer_id": 19198,
"author": "Ray",
"author_id": 233,
"author_profile": "https://Stackoverflow.com/users/233",
"pm_score": 0,
"selected": false,
"text": "<p>I managed to get it working with a variation of BCS's answer. It wouldn't let me use a table variable though, so I had to make a temp table.</p>\n\n<pre><code>CREATE TABLE #ResultTable\n(\n StaffName nvarchar(100),\n Stage1Count int,\n Stage2Count int\n)\n\nINSERT INTO #ResultTable (StaffName)\n SELECT StaffName FROM ViewJob\n GROUP BY StaffName\n\nUPDATE #ResultTable SET \n Stage1Count= (\n SELECT COUNT(*) FROM ViewJob V\n WHERE InStage1 = 1 AND \n V.StaffName = @ResultTable.StaffName COLLATE Latin1_General_CI_AS\n GROUP BY V.StaffName),\n Stage2Count= (\n SELECT COUNT(*) FROM ViewJob V\n WHERE InStage2 = 1 AND \n V.StaffName = @ResultTable.StaffName COLLATE Latin1_General_CI_AS\n GROUP BY V.StaffName)\n\nSELECT StaffName, Stage1Count, Stage2Count FROM #ResultTable\n\nDROP TABLE #ResultTable\n</code></pre>\n"
}
] | 2008/08/20 | [
"https://Stackoverflow.com/questions/19089",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/233/"
] | I have a view that has a list of jobs in it, with data like who they're assigned to and the stage they are in. I need to write a stored procedure that returns how many jobs each person has at each stage.
So far I have this (simplified):
```
DECLARE @ResultTable table
(
StaffName nvarchar(100),
Stage1Count int,
Stage2Count int
)
INSERT INTO @ResultTable (StaffName, Stage1Count)
SELECT StaffName, COUNT(*) FROM ViewJob
WHERE InStage1 = 1
GROUP BY StaffName
INSERT INTO @ResultTable (StaffName, Stage2Count)
SELECT StaffName, COUNT(*) FROM ViewJob
WHERE InStage2 = 1
GROUP BY StaffName
```
The problem with that is that the rows don't combine. So if a staff member has jobs in stage1 and stage2 there's two rows in @ResultTable. What I would really like to do is to update the row if one exists for the staff member and insert a new row if one doesn't exist.
Does anyone know how to do this, or can suggest a different approach?
I would really like to avoid using cursors to iterate on the list of users (but that's my fall back option).
I'm using SQL Server 2005.
**Edit: @Lee:** Unfortunately the InStage1 = 1 was a simplification. It's really more like WHERE DateStarted IS NOT NULL and DateFinished IS NULL.
**Edit: @BCS:** I like the idea of doing an insert of all the staff first so I just have to do an update every time. But I'm struggling to get those UPDATE statements correct. | IIRC there is some sort of "On Duplicate" (name might be wrong) syntax that lets you update if a row exists (MySQL)
Alternately some form of:
```
INSERT INTO @ResultTable (StaffName, Stage1Count, Stage2Count)
SELECT StaffName,0,0 FROM ViewJob
GROUP BY StaffName
UPDATE @ResultTable Stage1Count= (
SELECT COUNT(*) AS count FROM ViewJob
WHERE InStage1 = 1
@ResultTable.StaffName = StaffName)
UPDATE @ResultTable Stage2Count= (
SELECT COUNT(*) AS count FROM ViewJob
WHERE InStage2 = 1
@ResultTable.StaffName = StaffName)
``` |
19,122 | <p>Does anyone know how bash handles sending data through pipes?</p>
<pre><code>cat file.txt | tail -20
</code></pre>
<p>Does this command print all the contents of file.txt into a buffer, which is then read by tail? Or does this command, say, print the contents of file.txt line by line, and then pause at each line for tail to process, and then ask for more data? </p>
<p>The reason I ask is that I'm writing a program on an embedded device that basically performs a sequence of operations on some chunk of data, where the output of one operation is send off as the input of the next operation. I would like to know how linux (bash) handles this so please give me a general answer, not specifically what happens when I run "cat file.txt | tail -20".</p>
<p>EDIT: Shog9 pointed out a relevant Wikipedia Article, this didn't lead me directly to the article but it helped me find this: <a href="http://en.wikipedia.org/wiki/Pipeline_%28Unix%29#Implementation" rel="nofollow noreferrer">http://en.wikipedia.org/wiki/Pipeline_%28Unix%29#Implementation</a> which did have the information I was looking for.</p>
<hr>
<p>I'm sorry for not making myself clear. Of course you're using a pipe and of course you're using stdin and stdout of the respective parts of the command. I had assumed that was too obvious to state.</p>
<p>What I'm asking is how this is handled/implemented. Since both programs cannot run at once, how is data sent from stdin to stdout? What happens if the first program generates data significantly faster than the second program? Does the system just run the first command until either it's terminated or it's stdout buffer is full, and then move on to the next program, and so on in a loop until no more data is left to be processed or is there a more complicated mechanism?</p>
| [
{
"answer_id": 19134,
"author": "Mike Stone",
"author_id": 122,
"author_profile": "https://Stackoverflow.com/users/122",
"pm_score": 0,
"selected": false,
"text": "<p>cat will just print the data to standard out, which happens to be redirected to the standard in of tail. This can be seen in the man page of bash.</p>\n\n<p>In other words, there is no pausing going on, tail is just reading from standard in and cat is just writing to standard out.</p>\n"
},
{
"answer_id": 19200,
"author": "David Schlosnagle",
"author_id": 1750,
"author_profile": "https://Stackoverflow.com/users/1750",
"pm_score": 1,
"selected": false,
"text": "<p>Shog9 already referenced the Wikipedia article, but the <a href=\"http://en.wikipedia.org/wiki/Pipeline_(Unix)#Implementation\" rel=\"nofollow noreferrer\">implementation section</a> has the details you want. The basic implementation is a bounded buffer.</p>\n"
},
{
"answer_id": 19383,
"author": "postfuturist",
"author_id": 1892,
"author_profile": "https://Stackoverflow.com/users/1892",
"pm_score": 7,
"selected": true,
"text": "<p>I decided to write a slightly more detailed explanation.</p>\n\n<p>The \"magic\" here lies in the operating system. Both programs do start up at roughly the same time, and run at the same time (the operating system assigns them slices of time on the processor to run) as every other simultaneously running process on your computer (including the terminal application and the kernel). So, before any data gets passed, the processes are doing whatever initialization necessary. In your example, tail is parsing the '-20' argument and cat is parsing the 'file.txt' argument and opening the file. At some point tail will get to the point where it needs input and it will tell the operating system that it is waiting for input. At some other point (either before or after, it doesn't matter) cat will start passing data to the operating system using stdout. This goes into a buffer in the operating system. The next time tail gets a time slice on the processor after some data has been put into the buffer by cat, it will retrieve some amount of that data (or all of it) which leaves the buffer on the operating system. When the buffer is empty, at some point tail will have to wait for cat to output more data. If cat is outputting data much faster than tail is handling it, the buffer will expand. cat will eventually be done outputting data, but tail will still be processing, so cat will close and tail will process all remaining data in the buffer. The operating system will signal tail when their is no more incoming data with an EOF. Tail will process the remaining data. In this case, tail is probably just receiving all the data into a circular buffer of 20 lines, and when it is signalled by the operating system that there is no more incoming data, it then dumps the last twenty lines to its own stdout, which just gets displayed in the terminal. Since tail is a much simpler program than cat, it will likely spend most of the time waiting for cat to put data into the buffer.</p>\n\n<p>On a system with multiple processors, the two programs will not just be sharing alternating time slices on the same processor core, but likely running at the same time on separate cores.</p>\n\n<p>To get into a little more detail, if you open some kind of process monitor (operating system specific) like 'top' in Linux you will see a whole list of running processes, most of which are effectively using 0% of the processor. Most applications, unless they are crunching data, spend most of their time doing nothing. This is good, because it allows other processes to have unfettered access to the processor according to their needs. This is accomplished in basically three ways. A process could get to a sleep(n) style instruction where it basically tells the kernel to wait n milliseconds before giving it another time slice to work with. Most commonly a program needs to wait for something from another program, like 'tail' waiting for more data to enter the buffer. In this case the operating system will wake up the process when more data is available. Lastly, the kernel can preempt a process in the middle of execution, giving some processor time slices to other processes. 'cat' and 'tail' are simple programs. In this example, tail spends most of it's time waiting for more data on the buffer, and cat spends most of it's time waiting for the operating system to retrieve data from the harddrive. The bottleneck is the speed (or slowness) of the physical medium that the file is stored on. That perceptible delay you might detect when you run this command for the first time is the time it takes for the read heads on the disk drive to seek to the position on the harddrive where 'file.txt' is. If you run the command a second time, the operating system will likely have the contents of file.txt cached in memory, and you will not likely see any perceptible delay (unless file.txt is very large, or the file is no longer cached.)</p>\n\n<p>Most operations you do on your computer are IO bound, which is to say that you are usually waiting for data to come from your harddrive, or from a network device, etc.</p>\n"
}
] | 2008/08/21 | [
"https://Stackoverflow.com/questions/19122",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/306/"
] | Does anyone know how bash handles sending data through pipes?
```
cat file.txt | tail -20
```
Does this command print all the contents of file.txt into a buffer, which is then read by tail? Or does this command, say, print the contents of file.txt line by line, and then pause at each line for tail to process, and then ask for more data?
The reason I ask is that I'm writing a program on an embedded device that basically performs a sequence of operations on some chunk of data, where the output of one operation is send off as the input of the next operation. I would like to know how linux (bash) handles this so please give me a general answer, not specifically what happens when I run "cat file.txt | tail -20".
EDIT: Shog9 pointed out a relevant Wikipedia Article, this didn't lead me directly to the article but it helped me find this: <http://en.wikipedia.org/wiki/Pipeline_%28Unix%29#Implementation> which did have the information I was looking for.
---
I'm sorry for not making myself clear. Of course you're using a pipe and of course you're using stdin and stdout of the respective parts of the command. I had assumed that was too obvious to state.
What I'm asking is how this is handled/implemented. Since both programs cannot run at once, how is data sent from stdin to stdout? What happens if the first program generates data significantly faster than the second program? Does the system just run the first command until either it's terminated or it's stdout buffer is full, and then move on to the next program, and so on in a loop until no more data is left to be processed or is there a more complicated mechanism? | I decided to write a slightly more detailed explanation.
The "magic" here lies in the operating system. Both programs do start up at roughly the same time, and run at the same time (the operating system assigns them slices of time on the processor to run) as every other simultaneously running process on your computer (including the terminal application and the kernel). So, before any data gets passed, the processes are doing whatever initialization necessary. In your example, tail is parsing the '-20' argument and cat is parsing the 'file.txt' argument and opening the file. At some point tail will get to the point where it needs input and it will tell the operating system that it is waiting for input. At some other point (either before or after, it doesn't matter) cat will start passing data to the operating system using stdout. This goes into a buffer in the operating system. The next time tail gets a time slice on the processor after some data has been put into the buffer by cat, it will retrieve some amount of that data (or all of it) which leaves the buffer on the operating system. When the buffer is empty, at some point tail will have to wait for cat to output more data. If cat is outputting data much faster than tail is handling it, the buffer will expand. cat will eventually be done outputting data, but tail will still be processing, so cat will close and tail will process all remaining data in the buffer. The operating system will signal tail when their is no more incoming data with an EOF. Tail will process the remaining data. In this case, tail is probably just receiving all the data into a circular buffer of 20 lines, and when it is signalled by the operating system that there is no more incoming data, it then dumps the last twenty lines to its own stdout, which just gets displayed in the terminal. Since tail is a much simpler program than cat, it will likely spend most of the time waiting for cat to put data into the buffer.
On a system with multiple processors, the two programs will not just be sharing alternating time slices on the same processor core, but likely running at the same time on separate cores.
To get into a little more detail, if you open some kind of process monitor (operating system specific) like 'top' in Linux you will see a whole list of running processes, most of which are effectively using 0% of the processor. Most applications, unless they are crunching data, spend most of their time doing nothing. This is good, because it allows other processes to have unfettered access to the processor according to their needs. This is accomplished in basically three ways. A process could get to a sleep(n) style instruction where it basically tells the kernel to wait n milliseconds before giving it another time slice to work with. Most commonly a program needs to wait for something from another program, like 'tail' waiting for more data to enter the buffer. In this case the operating system will wake up the process when more data is available. Lastly, the kernel can preempt a process in the middle of execution, giving some processor time slices to other processes. 'cat' and 'tail' are simple programs. In this example, tail spends most of it's time waiting for more data on the buffer, and cat spends most of it's time waiting for the operating system to retrieve data from the harddrive. The bottleneck is the speed (or slowness) of the physical medium that the file is stored on. That perceptible delay you might detect when you run this command for the first time is the time it takes for the read heads on the disk drive to seek to the position on the harddrive where 'file.txt' is. If you run the command a second time, the operating system will likely have the contents of file.txt cached in memory, and you will not likely see any perceptible delay (unless file.txt is very large, or the file is no longer cached.)
Most operations you do on your computer are IO bound, which is to say that you are usually waiting for data to come from your harddrive, or from a network device, etc. |
19,132 | <p>I'm asking with regards to c#, but I assume its the same in most other languages.</p>
<p>Does anyone have a good definition of <em>expressions</em> and <em>statements</em> and what the differences are?</p>
| [
{
"answer_id": 19138,
"author": "Mark Cidade",
"author_id": 1659,
"author_profile": "https://Stackoverflow.com/users/1659",
"pm_score": 3,
"selected": false,
"text": "<p>Expressions can be evaluated to get a value, whereas statements don't return a value (they're of type <em>void</em>).</p>\n\n<p>Function call expressions can also be considered statements of course, but unless the execution environment has a special built-in variable to hold the returned value, there is no way to retrieve it.</p>\n\n<p>Statement-oriented languages require all procedures to be a list of statements. Expression-oriented languages, which is probably all functional languages, are lists of expressions, or in tha case of LISP, one long S-expression that represents a list of expressions.</p>\n\n<p>Although both types can be composed, most expressions can be composed arbitrarily as long as the types match up. Each type of statement has its own way of composing other statements, if they can do that all. Foreach and if statements require either a single statment or that all subordinate statements go in a statement block, one after another, unless the substatements allow for thier own substatements. </p>\n\n<p>Statements can also include expressions, where an expression doesn't really include any statements. One exception, though, would be a lambda expression, which represents a function, and so can include anything a function can iclude unless the language only allows for limited lambdas, like Python's single-expression lambdas. </p>\n\n<p>In an expression-based language, all you need is a single expression for a function since all control structures return a value (a lot of them return NIL). There's no need for a return statement since the last-evaluated expression in the function is the return value.</p>\n"
},
{
"answer_id": 19139,
"author": "Patrick",
"author_id": 429,
"author_profile": "https://Stackoverflow.com/users/429",
"pm_score": 4,
"selected": false,
"text": "<p>An expression is something that returns a value, whereas a statement does not.</p>\n\n<p>For examples:</p>\n\n<pre><code>1 + 2 * 4 * foo.bar() //Expression\nfoo.voidFunc(1); //Statement\n</code></pre>\n\n<p>The Big Deal between the two is that you can chain expressions together, whereas statements cannot be chained.</p>\n"
},
{
"answer_id": 19144,
"author": "Matthew Schinckel",
"author_id": 188,
"author_profile": "https://Stackoverflow.com/users/188",
"pm_score": 3,
"selected": false,
"text": "<p>Simply: an expression evaluates to a value, a statement doesn't.</p>\n"
},
{
"answer_id": 19150,
"author": "Mike Stone",
"author_id": 122,
"author_profile": "https://Stackoverflow.com/users/122",
"pm_score": 4,
"selected": false,
"text": "<p>You can find this on <a href=\"http://en.wikipedia.org/wiki/Statement_%28programming%29\" rel=\"noreferrer\">wikipedia</a>, but expressions are evaluated to some value, while statements have no evaluated value.</p>\n\n<p>Thus, expressions can be used in statements, but not the other way around.</p>\n\n<p>Note that some languages (such as Lisp, and I believe Ruby, and many others) do not differentiate statement vs expression... in such languages, everything is an expression and can be chained with other expressions.</p>\n"
},
{
"answer_id": 19224,
"author": "Joel Spolsky",
"author_id": 4,
"author_profile": "https://Stackoverflow.com/users/4",
"pm_score": 10,
"selected": true,
"text": "<p><strong>Expression:</strong> Something which evaluates to a value. Example: <em>1+2/x</em><br>\n<strong>Statement:</strong> A line of code which does something. Example: <em>GOTO 100</em></p>\n\n<p>In the earliest general-purpose programming languages, like FORTRAN, the distinction was crystal-clear. In FORTRAN, a statement was one unit of execution, a thing that you did. The only reason it wasn't called a \"line\" was because sometimes it spanned multiple lines. An expression on its own couldn't do anything... you had to assign it to a variable.</p>\n\n<pre><code>1 + 2 / X\n</code></pre>\n\n<p>is an error in FORTRAN, because it doesn't do anything. You had to do something with that expression:</p>\n\n<pre><code>X = 1 + 2 / X\n</code></pre>\n\n<p>FORTRAN didn't have a grammar as we know it today—that idea was invented, along with Backus-Naur Form (BNF), as part of the definition of Algol-60. At that point the <em>semantic</em> distinction (\"have a value\" versus \"do something\") was enshrined in <em>syntax</em>: one kind of phrase was an expression, and another was a statement, and the parser could tell them apart.</p>\n\n<p>Designers of later languages blurred the distinction: they allowed syntactic expressions to do things, and they allowed syntactic statements that had values.\nThe earliest popular language example that still survives is C. The designers of C realized that no harm was done if you were allowed to evaluate an expression and throw away the result. In C, every syntactic expression can be a made into a statement just by tacking a semicolon along the end:</p>\n\n<pre><code>1 + 2 / x;\n</code></pre>\n\n<p>is a totally legit statement even though absolutely nothing will happen. Similarly, in C, an expression can have <em>side-effects</em>—it can change something.</p>\n\n<pre><code>1 + 2 / callfunc(12);\n</code></pre>\n\n<p>because <code>callfunc</code> might just do something useful.</p>\n\n<p>Once you allow any expression to be a statement, you might as well allow the assignment operator (=) inside expressions. That's why C lets you do things like</p>\n\n<pre><code>callfunc(x = 2);\n</code></pre>\n\n<p>This evaluates the expression x = 2 (assigning the value of 2 to x) and then passes that (the 2) to the function <code>callfunc</code>.</p>\n\n<p>This blurring of expressions and statements occurs in all the C-derivatives (C, C++, C#, and Java), which still have some statements (like <code>while</code>) but which allow almost any expression to be used as a statement (in C# only assignment, call, increment, and decrement expressions may be used as statements; see <a href=\"https://stackoverflow.com/a/20771/8554766\">Scott Wisniewski's answer</a>).</p>\n\n<p>Having two \"syntactic categories\" (which is the technical name for the sort of thing statements and expressions are) can lead to duplication of effort. For example, C has two forms of conditional, the statement form</p>\n\n<pre><code>if (E) S1; else S2;\n</code></pre>\n\n<p>and the expression form</p>\n\n<pre><code>E ? E1 : E2\n</code></pre>\n\n<p>And sometimes people <em>want</em> duplication that isn't there: in standard C, for example, only a statement can declare a new local variable—but this ability is useful enough that the \nGNU C compiler provides a GNU extension that enables an expression to declare a local variable as well.</p>\n\n<p>Designers of other languages didn't like this kind of duplication, and they saw early on that if expressions can have side effects as well as values, then the <em>syntactic</em> distinction between statements and expressions is not all that useful—so they got rid of it. Haskell, Icon, Lisp, and ML are all languages that don't have syntactic statements—they only have expressions. Even the class structured looping and conditional forms are considered expressions, and they have values—but not very interesting ones.</p>\n"
},
{
"answer_id": 19362,
"author": "Mark Harrison",
"author_id": 116,
"author_profile": "https://Stackoverflow.com/users/116",
"pm_score": 5,
"selected": false,
"text": "<ul>\n<li>an expression is anything that yields a value: 2 + 2</li>\n<li>a statement is one of the basic \"blocks\" of program execution.</li>\n</ul>\n\n<p>Note that in C, \"=\" is actually an operator, which does two things:</p>\n\n<ul>\n<li>returns the value of the right hand subexpression.</li>\n<li>copies the value of the right hand subexpression into the variable on the left hand side.</li>\n</ul>\n\n<p>Here's an extract from the ANSI C grammar. You can see that C doesn't have many different kinds of statements... the majority of statements in a program are expression statements, i.e. an expression with a semicolon at the end.</p>\n\n<pre><code>statement\n : labeled_statement\n | compound_statement\n | expression_statement\n | selection_statement\n | iteration_statement\n | jump_statement\n ;\n\nexpression_statement\n : ';'\n | expression ';'\n ;\n</code></pre>\n\n<p><a href=\"http://www.lysator.liu.se/c/ANSI-C-grammar-y.html\" rel=\"noreferrer\">http://www.lysator.liu.se/c/ANSI-C-grammar-y.html</a></p>\n"
},
{
"answer_id": 379882,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 2,
"selected": false,
"text": "<p>Some things about expression based languages:</p>\n\n<hr>\n\n<p>Most important: Everything returns an value</p>\n\n<hr>\n\n<p>There is no difference between curly brackets and braces for delimiting code blocks and expressions, since everything is an expression. This doesn't prevent lexical scoping though: A local variable could be defined for the expression in which its definition is contained and all statements contained within that, for example.</p>\n\n<hr>\n\n<p>In an expression based language, everything returns a value. This can be a bit strange at first -- What does <code>(FOR i = 1 TO 10 DO (print i))</code> return? </p>\n\n<p>Some simple examples:</p>\n\n<ul>\n<li><code>(1)</code> returns <code>1</code></li>\n<li><code>(1 + 1)</code> returns <code>2</code></li>\n<li><code>(1 == 1)</code> returns <code>TRUE</code></li>\n<li><code>(1 == 2)</code> returns <code>FALSE</code></li>\n<li><code>(IF 1 == 1 THEN 10 ELSE 5)</code> returns <code>10</code></li>\n<li><code>(IF 1 == 2 THEN 10 ELSE 5)</code> returns <code>5</code></li>\n</ul>\n\n<p>A couple more complex examples:</p>\n\n<ul>\n<li>Some things, such as some function calls, don't really have a meaningful value to return (Things that only produce side effects?). Calling <code>OpenADoor(), FlushTheToilet()</code> or <code>TwiddleYourThumbs()</code> will return some sort of mundane value, such as OK, Done, or Success.</li>\n<li>When multiple unlinked expressions are evaluated within one larger expression, the value of the last thing evaluated in the large expression becomes the value of the large expression. To take the example of <code>(FOR i = 1 TO 10 DO (print i))</code>, the value of the for loop is \"10\", it causes the <code>(print i)</code> expression to be evaluated 10 times, each time returning i as a string. The final time through returns <code>10</code>, our final answer</li>\n</ul>\n\n<hr>\n\n<p>It often requires a slight change of mindset to get the most out of an expression based language, since the fact that everything is an expression makes it possible to 'inline' a lot of things</p>\n\n<p>As a quick example:</p>\n\n<blockquote>\n<pre><code> FOR i = 1 to (IF MyString == \"Hello, World!\" THEN 10 ELSE 5) DO\n (\n LotsOfCode\n )\n</code></pre>\n</blockquote>\n\n<p>is a perfectly valid replacement for the non expression-based</p>\n\n<blockquote>\n<pre><code>IF MyString == \"Hello, World!\" THEN TempVar = 10 ELSE TempVar = 5 \nFOR i = 1 TO TempVar DO\n( \n LotsOfCode \n)\n</code></pre>\n</blockquote>\n\n<p>In some cases, the layout that expression-based code permits feels much more natural to me</p>\n\n<p>Of course, this can lead to madness. As part of a hobby project in an expression-based scripting language called MaxScript, I managed to come up with this monster line</p>\n\n<pre><code>IF FindSectionStart \"rigidifiers\" != 0 THEN FOR i = 1 TO (local rigidifier_array = (FOR i = (local NodeStart = FindsectionStart \"rigidifiers\" + 1) TO (FindSectionEnd(NodeStart) - 1) collect full_array[i])).count DO\n(\n LotsOfCode\n)\n</code></pre>\n"
},
{
"answer_id": 646331,
"author": "Daniel Earwicker",
"author_id": 27423,
"author_profile": "https://Stackoverflow.com/users/27423",
"pm_score": 2,
"selected": false,
"text": "<p>A statement is a special case of an expression, one with <code>void</code> type. The tendency of languages to treat statements differently often causes problems, and it would be better if they were properly generalized.</p>\n\n<p>For example, in C# we have the very useful <code>Func<T1, T2, T3, TResult></code> overloaded set of generic delegates. But we also have to have a corresponding <code>Action<T1, T2, T3></code> set as well, and general purpose higher-order programming constantly has to be duplicated to deal with this unfortunate bifurcation.</p>\n\n<p>Trivial example - a function that checks whether a reference is null before calling onto another function:</p>\n\n<pre><code>TResult IfNotNull<TValue, TResult>(TValue value, Func<TValue, TResult> func)\n where TValue : class\n{\n return (value == null) ? default(TValue) : func(value);\n}\n</code></pre>\n\n<p>Could the compiler deal with the possibility of <code>TResult</code> being <code>void</code>? Yes. All it has to do is require that return is followed by an expression that is of type <code>void</code>. The result of <code>default(void)</code> would be of type <code>void</code>, and the func being passed in would need to be of the form <code>Func<TValue, void></code> (which would be equivalent to <code>Action<TValue></code>).</p>\n\n<p>A number of other answers imply that you can't chain statements like you can with expressions, but I'm not sure where this idea comes from. We can think of the <code>;</code> that appears after statements as a binary infix operator, taking two expressions of type <code>void</code> and combining them into a single expression of type <code>void</code>.</p>\n"
},
{
"answer_id": 1035106,
"author": "Conal",
"author_id": 127335,
"author_profile": "https://Stackoverflow.com/users/127335",
"pm_score": 3,
"selected": false,
"text": "<p>For an explanation of important differences in composability (chainability) of expressions vs statements, my favorite reference is John Backus's Turing award paper, <em><a href=\"http://citeseerx.ist.psu.edu/viewdoc/download?doi=10.1.1.130.4539&rep=rep1&type=pdf\" rel=\"noreferrer\">Can programming be liberated from the von Neumann style?</a></em>.</p>\n\n<p>Imperative languages (Fortran, C, Java, ...) emphasize statements for structuring programs, and have expressions as a sort of after-thought. Functional languages emphasize expressions. <em>Purely</em> functional languages have such powerful expressions than statements can be eliminated altogether.</p>\n"
},
{
"answer_id": 5439795,
"author": "ncmathsadist",
"author_id": 467379,
"author_profile": "https://Stackoverflow.com/users/467379",
"pm_score": 0,
"selected": false,
"text": "<p>Statements are grammatically complete sentences. Expressions are not. For example</p>\n\n<pre><code>x = 5\n</code></pre>\n\n<p>reads as \"x gets 5.\" This is a complete sentence. The code</p>\n\n<pre><code>(x + 5)/9.0\n</code></pre>\n\n<p>reads, \"x plus 5 all divided by 9.0.\" This is not a complete sentence. The statement</p>\n\n<pre><code>while k < 10: \n print k\n k += 1\n</code></pre>\n\n<p>is a complete sentence. Notice that the loop header is not; \"while k < 10,\" is a subordinating clause.</p>\n"
},
{
"answer_id": 8450398,
"author": "Shelby Moore III",
"author_id": 615784,
"author_profile": "https://Stackoverflow.com/users/615784",
"pm_score": -1,
"selected": false,
"text": "<p>Most precisely, a statement must have a <strong>"side-effect"</strong> (i.e. <a href=\"https://stackoverflow.com/questions/602444/what-is-functional-declarative-and-imperative-programming/8357604#8357604\">be imperative</a>) and an expression must <em>have</em> a <strong>value</strong> type (i.e. not the bottom type).</p>\n<p>The <a href=\"http://james-iry.blogspot.com/2009/08/getting-to-bottom-of-nothing-at-all.html\" rel=\"nofollow noreferrer\">type of a statement</a> is the unit type, but due to Halting theorem unit is fiction so lets say the <a href=\"https://stackoverflow.com/a/8450076/615784\">bottom type</a>.</p>\n<hr />\n<p><code>Void</code> is not precisely the bottom type (it isn't the subtype of all possible types). It exists in languages that <a href=\"http://james-iry.blogspot.com/2009/08/getting-to-bottom-of-nothing-at-all.html\" rel=\"nofollow noreferrer\">don't have a completely sound type system</a>. That may sound like a snobbish statement, but completeness <a href=\"https://stackoverflow.com/a/8438947/615784\">such as variance annotations</a> are critical to writing extensible software.</p>\n<p>Let's see what Wikipedia has to say on this matter.</p>\n<p><a href=\"https://en.wikipedia.org/wiki/Statement_(computer_science)\" rel=\"nofollow noreferrer\">https://en.wikipedia.org/wiki/Statement_(computer_science)</a></p>\n<blockquote>\n<p>In computer programming a statement is the smallest standalone element of an <strong>imperative</strong> programming language that expresses <strong>some action</strong> to be carried out.</p>\n<p>Many languages (e.g. C) make a distinction between statements and definitions, with a statement only containing executable code and a definition declaring an identifier, while an expression evaluates to a value only.</p>\n</blockquote>\n"
},
{
"answer_id": 12285190,
"author": "Andaquin",
"author_id": 1038008,
"author_profile": "https://Stackoverflow.com/users/1038008",
"pm_score": 2,
"selected": false,
"text": "<p>Statements -> Instructions to follow sequentially<br/>\nExpressions -> Evaluation that returns a value</p>\n\n<p>Statements are basically like steps, or instructions in an algorithm, the result of the execution of a statement is the actualization of the instruction pointer (so-called in assembler)</p>\n\n<p>Expressions do not imply and execution order at first sight, their purpose is to evaluate and return a value. In the imperative programming languages the evaluation of an expression has an order, but it is just because of the imperative model, but it is not their essence.</p>\n\n<p>Examples of Statements:</p>\n\n<pre><code>for\ngoto\nreturn\nif\n</code></pre>\n\n<p>(all of them imply the advance of the line (statement) of execution to another line)</p>\n\n<p>Example of expressions:</p>\n\n<pre><code>2+2\n</code></pre>\n\n<p>(it doesn't imply the idea of execution, but of the evaluation)</p>\n"
},
{
"answer_id": 12458901,
"author": "Sujit",
"author_id": 792713,
"author_profile": "https://Stackoverflow.com/users/792713",
"pm_score": 1,
"selected": false,
"text": "<p><strong><a href=\"http://msdn.microsoft.com/en-us/library/ms173143%28v=vs.80%29.aspx\" rel=\"nofollow\">Statement</a>,</strong></p>\n\n<p>A statement is a procedural building-block from which all C# programs are constructed. A statement can declare a local variable or constant, call a method, create an object, or assign a value to a variable, property, or field.</p>\n\n<p>A series of statements surrounded by curly braces form a block of code. A method body is one example of a code block.</p>\n\n<pre><code>bool IsPositive(int number)\n{\n if (number > 0)\n {\n return true;\n }\n else\n {\n return false;\n }\n}\n</code></pre>\n\n<p>Statements in C# often contain expressions. An expression in C# is a fragment of code containing a literal value, a simple name, or an operator and its operands.</p>\n\n<p><strong><a href=\"http://msdn.microsoft.com/en-us/library/ms173144%28v=vs.80%29.aspx\" rel=\"nofollow\">Expression</a>,</strong></p>\n\n<p>An expression is a fragment of code that can be evaluated to a single value, object, method, or namespace. The two simplest types of expressions are literals and simple names. A literal is a constant value that has no name.</p>\n\n<pre><code>int i = 5;\nstring s = \"Hello World\";\n</code></pre>\n\n<p>Both i and s are simple names identifying local variables. When those variables are used in an expression, the value of the variable is retrieved and used for the expression.</p>\n"
},
{
"answer_id": 16422689,
"author": "vfclists",
"author_id": 172406,
"author_profile": "https://Stackoverflow.com/users/172406",
"pm_score": 1,
"selected": false,
"text": "<p>I prefer the meaning of <code>statement</code> in the formal logic sense of the word. It is one that changes the state of one or more of the variables in the computation, enabling a true or false statement to be made about their value(s).</p>\n\n<p>I guess there will always be confusion in the computing world and science in general when new terminology or words are introduced, existing words are 'repurposed' or users are ignorant of the existing, established or 'proper' terminology for what they are describing</p>\n"
},
{
"answer_id": 25722497,
"author": "MadNik",
"author_id": 1239426,
"author_profile": "https://Stackoverflow.com/users/1239426",
"pm_score": 1,
"selected": false,
"text": "<p>Here is the summery of one of the simplest answer I found.</p>\n\n<p>originally Answered by Anders Kaseorg</p>\n\n<p>A statement is a complete line of code that performs some action, while an expression is any section of the code that evaluates to a value. </p>\n\n<p><strong>Expressions can be combined “horizontally” into larger expressions using operators, while statements can only be combined “vertically” by writing one after another, or with block constructs.</strong> </p>\n\n<p>Every expression can be used as a statement (whose effect is to evaluate the expression and ignore the resulting value), but most statements cannot be used as expressions.</p>\n\n<p><a href=\"http://www.quora.com/Python-programming-language-1/Whats-the-difference-between-a-statement-and-an-expression-in-Python\" rel=\"nofollow\">http://www.quora.com/Python-programming-language-1/Whats-the-difference-between-a-statement-and-an-expression-in-Python</a></p>\n"
},
{
"answer_id": 30960293,
"author": "Ely",
"author_id": 1566187,
"author_profile": "https://Stackoverflow.com/users/1566187",
"pm_score": 2,
"selected": false,
"text": "<p>I am not really satisfied with any of the answers here. I looked at the grammar for <a href=\"http://slps.github.io/zoo/cpp/iso-n2723.html\" rel=\"nofollow\">C++ (ISO 2008)</a>. However maybe for the sake of didactics and programming the answers might suffice to distinguish the two elements (reality looks more complicated though).</p>\n\n<p>A statement consists of zero or more expressions, but can also be other language concepts. This is the Extended Backus Naur form for the grammar (excerpt for statement):</p>\n\n<pre><code>statement:\n labeled-statement\n expression-statement <-- can be zero or more expressions\n compound-statement\n selection-statement\n iteration-statement\n jump-statement\n declaration-statement\n try-block\n</code></pre>\n\n<p>We can see the other concepts that are considered statements in C++.</p>\n\n<ul>\n<li><em>expression-statement</em>s is self-explaining (a statement can consist of zero or <em>more</em> expressions, read the grammar carefully, it's tricky) </li>\n<li><code>case</code> for example is a <em>labeled-statement</em></li>\n<li><em>selection-statement</em>s are <code>if</code> <code>if/else</code>, <code>case</code></li>\n<li><em>iteration-statement</em>s are <code>while</code>, <code>do...while</code>, <code>for (...)</code></li>\n<li><em>jump-statement</em>s are <code>break</code>, <code>continue</code>, <code>return</code> (can return expression), <code>goto</code></li>\n<li><em>declaration-statement</em> is the set of declarations</li>\n<li><em>try-block</em> is statement representing <code>try/catch</code> blocks</li>\n<li><em>and there might be some more down the grammar</em></li>\n</ul>\n\n<p>This is an excerpt showing the expressions part:</p>\n\n<pre><code>expression:\n assignment-expression\n expression \",\" assignment-expression\nassignment-expression:\n conditional-expression\n logical-or-expression assignment-operator initializer-clause\n throw-expression\n</code></pre>\n\n<ul>\n<li>expressions are or contain often assignments</li>\n<li><em>conditional-expression</em> (sounds misleading) refers to usage of the operators (<code>+</code>, <code>-</code>, <code>*</code>, <code>/</code>, <code>&</code>, <code>|</code>, <code>&&</code>, <code>||</code>, ...)</li>\n<li><em>throw-expression</em> - uh? the <code>throw</code> clause is an expression too</li>\n</ul>\n"
},
{
"answer_id": 32057203,
"author": "Shelby Moore III",
"author_id": 615784,
"author_profile": "https://Stackoverflow.com/users/615784",
"pm_score": -1,
"selected": false,
"text": "<p>To improve on and validate my prior answer, definitions of programming language terms should be explained from computer science type theory when applicable.</p>\n\n<p>An expression has a type other than the Bottom type, i.e. it has a value. A statement has the Unit or Bottom type.</p>\n\n<p>From this it follows that a statement can only have any effect in a program when it creates a side-effect, because it either can not return a value or it only returns the value of the Unit type which is either nonassignable (in some languages such a C's <code>void</code>) or (such as in Scala) can be stored for a delayed evaluation of the statement.</p>\n\n<p>Obviously a <code>@pragma</code> or a <code>/*comment*/</code> have no type and thus are differentiated from statements. Thus the only type of statement that would have no side-effects would be a non-operation. Non-operation is only useful as a placeholder for future side-effects. Any other action due to a statement would be a side-effect. Again a compiler hint, e.g. <code>@pragma</code>, is not a statement because it has no type.</p>\n"
},
{
"answer_id": 57619680,
"author": "FrankHB",
"author_id": 2307646,
"author_profile": "https://Stackoverflow.com/users/2307646",
"pm_score": 2,
"selected": false,
"text": "<p>The de-facto basis of these concepts is:</p>\n\n<p><strong>Expressions</strong>: A syntactic category whose instance can be evaluated to a value.</p>\n\n<p><strong>Statement</strong>: A syntactic category whose instance may be involved with evaluations of an expression and the resulted value of the evaluation (if any) is not guaranteed available.</p>\n\n<p>Besides to the very initial context for FORTRAN in the early decades, both definitions of expressions and statements in the accepted answer are obviously wrong:</p>\n\n<ul>\n<li>Expressions can be unvaluated operands. Values are never produced from them.\n\n<ul>\n<li>Subexpressions in non-strict evaluations can be definitely unevaluated.\n\n<ul>\n<li>Most C-like languages have the so-called <a href=\"https://en.wikipedia.org/wiki/Short-circuit_evaluation\" rel=\"nofollow noreferrer\">short-circuit evaluation</a> rules to conditionally skip some subexpression evaluations not change the final result in spite of the side effects.</li>\n</ul></li>\n<li>C and some C-like languages have the notion of unevaluated operand which may be even normatively defined in the language specification. Such constructs are used to avoid the evaluations definitely, so the remained context information (e.g. types or alignment requirements) can be statically distinguished without changing the behavior after the program translation.\n\n<ul>\n<li>For example, an expression used as the operand of the <code>sizeof</code> operator is never evaluated.</li>\n</ul></li>\n</ul></li>\n<li>Statements have nothing to do with line constructs. They can do something more than expressions, depending on the language specifications.\n\n<ul>\n<li>Modern Fortran, as the direct descendant of the old FORTRAN, has concepts of <em>executable statement</em>s and <em>nonexecutable statement</em>s.</li>\n<li>Similarly, C++ defines declarations as the top-level subcategory of a translation unit. A declaration in C++ is a statement. <sub>(This is not true in C.)</sub> There are also <em>expression-statement</em>s like Fortran's executable statements.</li>\n<li>To the interest of the comparison with expressions, only the \"executable\" statements matter. But you can't ignore the fact that statements are already generalized to be constructs forming the translation units in such imperative languages. So, as you can see, the definitions of the category vary a lot. The (probably) only remained common property preserved among these languages is that <strong>statements are expected to be interpreted in the lexical order</strong> (for most users, left-to-right and top-to-bottom).</li>\n</ul></li>\n</ul>\n\n<p><sub>(BTW, I want to add [citation needed] to that answer concerning materials about C because I can't recall whether DMR has such opinions. It seems not, otherwise there should be no reasons to preserve the functionality duplication in the design of C: notably, the comma operator vs. the statements.)</sub></p>\n\n<p>(The following rationale is not the direct response to the original question, but I feel it necessary to clarify something already answered here.)</p>\n\n<p>Nevertheless, it is doubtful that we need a specific category of \"statements\" in general-purpose programming languages:</p>\n\n<ul>\n<li>Statements are not guaranteed to have more semantic capabilities over expressions in usual designs.\n\n<ul>\n<li>Many languages have already successfully abandon the notion of statements to get clean, neat and consistent overall designs.\n\n<ul>\n<li>In such languages, expressions can do everything old-style statements can do: just drop the unused results when the expressions are evaluated, either by leaving the results explicitly unspecified (e.g. in R<sup>n</sup>RS Scheme), or having a special value (as a value of a unit type) not producible from normal expression evaluations.</li>\n<li>The lexical order rules of evaluation of expressions can be replaced by explicit sequence control operator (e.g. <code>begin</code> in Scheme) or syntactic sugar of monadic structures.</li>\n<li>The lexical order rules of other kinds of \"statements\" can be derived as syntactic extensions (using hygienic macros, for example) to get the similar syntactic functionality. (And it can actually <a href=\"https://en.wikipedia.org/wiki/Fexpr\" rel=\"nofollow noreferrer\">do more</a>.)</li>\n</ul></li>\n<li>On the contrary, statements cannot have such conventional rules, because they don't compose on evaluation: there is just no such common notion of \"substatement evaluation\". <sub>(Even if any, I doubt there can be something much more than copy and paste from existed rules of evaluation of expressions.)</sub> \n\n<ul>\n<li>Typically, languages preserving statements will also have expressions to express computations, and there is a top-level subcategory of the statements preserved to expression evaluations for that subcategory. For example, C++ has the so-called <em>expression-statement</em> as the subcategory, and uses the <em>discarded-value expression</em> evaluation rules to specify the general cases of full-expression evaluations in such context. Some languages like C# chooses to refine the contexts to simplify the use cases, but it bloats the specification more.</li>\n</ul></li>\n</ul></li>\n<li>For users of programming languages, the significance of statements may confuse them further.\n\n<ul>\n<li>The separation of rules of expressions and statements in the languages requires more effort to learn a language.</li>\n<li>The naive lexical order interpretation hides the more important notion: expression evaluation. (This is probably most problematic over all.)\n\n<ul>\n<li>Even the evaluations of full expressions in statements are constraint with the lexical order, subexpressions are not (necessarily). Users should ultimately learn this besides any rules coupled to the statements. (Consider how to make a newbie get the point that <code>++i + ++i</code> is meaningless in C.)</li>\n<li>Some languages like Java and C# further constraints the order of evaluations of subexpressions to be permissive of ignorance of evaluation rules. It can be even more problematic.\n\n<ul>\n<li>This seems overspecified to users who have already learned the idea of expression evaluation. It also encourages the user community to follow the blurred mental model of the language design.</li>\n<li>It bloats the language specification even more.</li>\n<li>It is harmful to optimization by missing the expressiveness of nondeterminism on evaluations, before more complicated primitives are introduced.</li>\n</ul></li>\n<li>A few languages like C++ (particularly, C++17) specify more subtle contexts of evaluation rules, as a compromise of the problems above.\n\n<ul>\n<li>It bloats the language specification a lot.</li>\n<li>This goes totally against to simplicity to average users...</li>\n</ul></li>\n</ul></li>\n</ul></li>\n</ul>\n\n<p>So why statements? Anyway, the history is already a mess. It seems most language designers do not take their choice carefully.</p>\n\n<p>Worse, it even gives some type system enthusiasts (who are not familiar enough with the PL history) some misconceptions that type systems must have important things to do with the more essential designs of rules on the operational semantics.</p>\n\n<p>Seriously, reasoning depending on types are not that bad in many cases, but particularly not constructive in this special one. Even experts can screw things up.</p>\n\n<p>For example, someone emphasizes the well-typing nature <a href=\"http://okmij.org/ftp/continuations/undelimited.html#introduction\" rel=\"nofollow noreferrer\">as the central argument against the traditional treatment of undelimited continuations</a>. Although the conclusion is somewhat reasonable and the insights about composed functions are OK (<a href=\"http://fexpr.blogspot.com/2014/03/continuations-and-term-rewriting-calculi.html\" rel=\"nofollow noreferrer\">but still far too naive to the essense</a>), this argument is not sound because it totally ignores the \"side channel\" approach in practice like <code>_Noreturn any_of_returnable_types</code> (in C11) to encode <code>Falsum</code>. <sub>And strictly speaking, an abstract machine with unpredictable state is not identical to \"a crashed computer\".</sub></p>\n"
},
{
"answer_id": 62324086,
"author": "Xwtek",
"author_id": 5784051,
"author_profile": "https://Stackoverflow.com/users/5784051",
"pm_score": 0,
"selected": false,
"text": "<p>In a statement-oriented programming language, a code block is defined as a list of statements. In other words, a statement is a piece of syntax that you can put inside a code block without causing a syntax error.</p>\n\n<p>Wikipedia defines the word statement similarly</p>\n\n<blockquote>\n <p>In computer programming, a statement is a syntactic unit of an imperative programming language that expresses some action to be carried out. A program written in such a language is formed by a sequence of one or more statements</p>\n</blockquote>\n\n<p>Notice the latter statement. (although \"a program\" in this case is technically wrong because both C and Java reject a program that consists of nothing of statements.)</p>\n\n<p>Wikipedia defines the word expression as </p>\n\n<blockquote>\n <p>An expression in a programming language is a syntactic entity that may be evaluated to determine its value</p>\n</blockquote>\n\n<p>This is, however, false, because in Kotlin, <code>throw new Exception(\"\")</code> is an expression but when evaluated, it simply throws an exception, never returning any value.</p>\n\n<p>In a statically typed programming language, every expression has a type. This definition, however, doesn't work in a dynamically typed programming language.</p>\n\n<p>Personally, I define an expression as a piece of syntax that can be composed with an operator or function calls to yield a bigger expression. This is actually similar to the explanation of expression by Wikipedia:</p>\n\n<blockquote>\n <p>It is a combination of one or more constants, variables, functions, and operators that the programming language interprets (according to its particular rules of precedence and of association) and computes to produce (\"to return\", in a stateful environment) another value</p>\n</blockquote>\n\n<p>But, the problem is in C programming language, given a function executeSomething like this:</p>\n\n<pre><code>void executeSomething(void){\n return;\n}\n</code></pre>\n\n<p>Is <code>executeSomething()</code> an expression or is it a statement? According to my definition, it is a statement because as defined in Microsoft's C reference grammar, </p>\n\n<blockquote>\n <p>You cannot use the (nonexistent) value of an expression that has type void in any way, nor can you convert a void expression (by implicit or explicit conversion) to any type except void</p>\n</blockquote>\n\n<p>But the same page clearly indicates that such syntax is an expression.</p>\n"
},
{
"answer_id": 63378331,
"author": "Gk Mohammad Emon",
"author_id": 7200133,
"author_profile": "https://Stackoverflow.com/users/7200133",
"pm_score": 0,
"selected": false,
"text": "<p>A <strong>statement</strong> is a block of code that doesn't return anything and which is just a standalone unit of execution. For example-</p>\n<pre><code>if(a>=0)\nprintf("Hello Humen,I'm a statement");\n</code></pre>\n<p>An <strong>expression</strong>, on the other hand, returns or evaluates a new value. For example -</p>\n<pre><code> if(a>=0)\n return a+10;//This is an expression because it evalutes an new value;\n</code></pre>\n<p>or</p>\n<pre><code> a=10+y;//This is also an expression because it returns a new value. \n</code></pre>\n"
},
{
"answer_id": 63503616,
"author": "Vlad Bezden",
"author_id": 30038,
"author_profile": "https://Stackoverflow.com/users/30038",
"pm_score": 0,
"selected": false,
"text": "<p><a href=\"https://docs.python.org/3/glossary.html#term-expression\" rel=\"nofollow noreferrer\">Expression</a></p>\n<blockquote>\n<p>A piece of syntax which can be evaluated to some value. In other words, an expression is an accumulation of expression elements like literals, names, attribute access, operators or function calls which all return a value. In contrast to many other languages, not all language constructs are expressions. There are also statements which cannot be used as expressions, such as while. Assignments are also statements, not expressions.</p>\n</blockquote>\n<p><a href=\"https://docs.python.org/3/glossary.html#term-statement\" rel=\"nofollow noreferrer\">Statement</a></p>\n<blockquote>\n<p>A statement is part of a suite (a “block” of code). A statement is either an expression or one of several constructs with a keyword, such as if, while or for.</p>\n</blockquote>\n"
}
] | 2008/08/21 | [
"https://Stackoverflow.com/questions/19132",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] | I'm asking with regards to c#, but I assume its the same in most other languages.
Does anyone have a good definition of *expressions* and *statements* and what the differences are? | **Expression:** Something which evaluates to a value. Example: *1+2/x*
**Statement:** A line of code which does something. Example: *GOTO 100*
In the earliest general-purpose programming languages, like FORTRAN, the distinction was crystal-clear. In FORTRAN, a statement was one unit of execution, a thing that you did. The only reason it wasn't called a "line" was because sometimes it spanned multiple lines. An expression on its own couldn't do anything... you had to assign it to a variable.
```
1 + 2 / X
```
is an error in FORTRAN, because it doesn't do anything. You had to do something with that expression:
```
X = 1 + 2 / X
```
FORTRAN didn't have a grammar as we know it today—that idea was invented, along with Backus-Naur Form (BNF), as part of the definition of Algol-60. At that point the *semantic* distinction ("have a value" versus "do something") was enshrined in *syntax*: one kind of phrase was an expression, and another was a statement, and the parser could tell them apart.
Designers of later languages blurred the distinction: they allowed syntactic expressions to do things, and they allowed syntactic statements that had values.
The earliest popular language example that still survives is C. The designers of C realized that no harm was done if you were allowed to evaluate an expression and throw away the result. In C, every syntactic expression can be a made into a statement just by tacking a semicolon along the end:
```
1 + 2 / x;
```
is a totally legit statement even though absolutely nothing will happen. Similarly, in C, an expression can have *side-effects*—it can change something.
```
1 + 2 / callfunc(12);
```
because `callfunc` might just do something useful.
Once you allow any expression to be a statement, you might as well allow the assignment operator (=) inside expressions. That's why C lets you do things like
```
callfunc(x = 2);
```
This evaluates the expression x = 2 (assigning the value of 2 to x) and then passes that (the 2) to the function `callfunc`.
This blurring of expressions and statements occurs in all the C-derivatives (C, C++, C#, and Java), which still have some statements (like `while`) but which allow almost any expression to be used as a statement (in C# only assignment, call, increment, and decrement expressions may be used as statements; see [Scott Wisniewski's answer](https://stackoverflow.com/a/20771/8554766)).
Having two "syntactic categories" (which is the technical name for the sort of thing statements and expressions are) can lead to duplication of effort. For example, C has two forms of conditional, the statement form
```
if (E) S1; else S2;
```
and the expression form
```
E ? E1 : E2
```
And sometimes people *want* duplication that isn't there: in standard C, for example, only a statement can declare a new local variable—but this ability is useful enough that the
GNU C compiler provides a GNU extension that enables an expression to declare a local variable as well.
Designers of other languages didn't like this kind of duplication, and they saw early on that if expressions can have side effects as well as values, then the *syntactic* distinction between statements and expressions is not all that useful—so they got rid of it. Haskell, Icon, Lisp, and ML are all languages that don't have syntactic statements—they only have expressions. Even the class structured looping and conditional forms are considered expressions, and they have values—but not very interesting ones. |
19,147 | <p>Using C# and WPF under .NET (rather than <a href="http://en.wikipedia.org/wiki/Windows_Forms" rel="noreferrer">Windows Forms</a> or console), what is the correct way to create an application that can only be run as a single instance?</p>
<p>I know it has something to do with some mythical thing called a mutex, rarely can I find someone that bothers to stop and explain what one of these are.</p>
<p>The code needs to also inform the already-running instance that the user tried to start a second one, and maybe also pass any command-line arguments if any existed.</p>
| [
{
"answer_id": 19165,
"author": "jason saldo",
"author_id": 1293,
"author_profile": "https://Stackoverflow.com/users/1293",
"pm_score": 7,
"selected": false,
"text": "<p>From <a href=\"http://www.albahari.com/threading/part2.html#_MutexSingleAppInstance\" rel=\"noreferrer\">here</a>.</p>\n\n<p>A common use for a cross-process Mutex is to ensure that only instance of a program can run at a time. Here's how it's done:</p>\n\n<pre><code>class OneAtATimePlease {\n\n // Use a name unique to the application (eg include your company URL)\n static Mutex mutex = new Mutex (false, \"oreilly.com OneAtATimeDemo\");\n\n static void Main()\n {\n // Wait 5 seconds if contended – in case another instance\n // of the program is in the process of shutting down.\n if (!mutex.WaitOne(TimeSpan.FromSeconds (5), false))\n {\n Console.WriteLine(\"Another instance of the app is running. Bye!\");\n return;\n }\n\n try\n { \n Console.WriteLine(\"Running - press Enter to exit\");\n Console.ReadLine();\n }\n finally\n {\n mutex.ReleaseMutex();\n } \n } \n}\n</code></pre>\n\n<p>A good feature of Mutex is that if the application terminates without ReleaseMutex first being called, the CLR will release the Mutex automatically.</p>\n"
},
{
"answer_id": 19326,
"author": "Dale Ragan",
"author_id": 1117,
"author_profile": "https://Stackoverflow.com/users/1117",
"pm_score": 7,
"selected": false,
"text": "<p>You could use the Mutex class, but you will soon find out that you will need to implement the code to pass the arguments and such yourself. Well, I learned a trick when programming in WinForms when I read <a href=\"http://sellsbrothers.com/wfbook/\" rel=\"noreferrer\">Chris Sell's book</a>. This trick uses logic that is already available to us in the framework. I don't know about you, but when I learn about stuff I can reuse in the framework, that is usually the route I take instead of reinventing the wheel. Unless of course it doesn't do everything I want.</p>\n\n<p>When I got into WPF, I came up with a way to use that same code, but in a WPF application. This solution should meet your needs based off your question.</p>\n\n<p>First, we need to create our application class. In this class we are going override the OnStartup event and create a method called Activate, which will be used later.</p>\n\n<pre><code>public class SingleInstanceApplication : System.Windows.Application\n{\n protected override void OnStartup(System.Windows.StartupEventArgs e)\n {\n // Call the OnStartup event on our base class\n base.OnStartup(e);\n\n // Create our MainWindow and show it\n MainWindow window = new MainWindow();\n window.Show();\n }\n\n public void Activate()\n {\n // Reactivate the main window\n MainWindow.Activate();\n }\n}\n</code></pre>\n\n<p>Second, we will need to create a class that can manage our instances. Before we go through that, we are actually going to reuse some code that is in the Microsoft.VisualBasic assembly. Since, I am using C# in this example, I had to make a reference to the assembly. If you are using VB.NET, you don't have to do anything. The class we are going to use is WindowsFormsApplicationBase and inherit our instance manager off of it and then leverage properties and events to handle the single instancing.</p>\n\n<pre><code>public class SingleInstanceManager : Microsoft.VisualBasic.ApplicationServices.WindowsFormsApplicationBase\n{\n private SingleInstanceApplication _application;\n private System.Collections.ObjectModel.ReadOnlyCollection<string> _commandLine;\n\n public SingleInstanceManager()\n {\n IsSingleInstance = true;\n }\n\n protected override bool OnStartup(Microsoft.VisualBasic.ApplicationServices.StartupEventArgs eventArgs)\n {\n // First time _application is launched\n _commandLine = eventArgs.CommandLine;\n _application = new SingleInstanceApplication();\n _application.Run();\n return false;\n }\n\n protected override void OnStartupNextInstance(StartupNextInstanceEventArgs eventArgs)\n {\n // Subsequent launches\n base.OnStartupNextInstance(eventArgs);\n _commandLine = eventArgs.CommandLine;\n _application.Activate();\n }\n}\n</code></pre>\n\n<p>Basically, we are using the VB bits to detect single instance's and process accordingly. OnStartup will be fired when the first instance loads. OnStartupNextInstance is fired when the application is re-run again. As you can see, I can get to what was passed on the command line through the event arguments. I set the value to an instance field. You could parse the command line here, or you could pass it to your application through the constructor and the call to the Activate method.</p>\n\n<p>Third, it's time to create our EntryPoint. Instead of newing up the application like you would normally do, we are going to take advantage of our SingleInstanceManager.</p>\n\n<pre><code>public class EntryPoint\n{\n [STAThread]\n public static void Main(string[] args)\n {\n SingleInstanceManager manager = new SingleInstanceManager();\n manager.Run(args);\n }\n}\n</code></pre>\n\n<p>Well, I hope you are able to follow everything and be able use this implementation and make it your own.</p>\n"
},
{
"answer_id": 481203,
"author": "Matt Davison",
"author_id": 1995476,
"author_profile": "https://Stackoverflow.com/users/1995476",
"pm_score": 2,
"selected": false,
"text": "<p>You should never use a named mutex to implement a single-instance application (or at least not for production code). Malicious code can easily DoS (<a href=\"https://en.wikipedia.org/wiki/Denial-of-service_attack\" rel=\"nofollow noreferrer\">Denial of Service</a>) your ass...</p>\n"
},
{
"answer_id": 522874,
"author": "Matt Davis",
"author_id": 51170,
"author_profile": "https://Stackoverflow.com/users/51170",
"pm_score": 10,
"selected": true,
"text": "<p>Here is a very good <a href=\"http://sanity-free.org/143/csharp_dotnet_single_instance_application.html\" rel=\"noreferrer\">article</a> regarding the Mutex solution. The approach described by the article is advantageous for two reasons.</p>\n\n<p>First, it does not require a dependency on the Microsoft.VisualBasic assembly. If my project already had a dependency on that assembly, I would probably advocate using the approach <a href=\"https://stackoverflow.com/a/19326/3195477\">shown in another answer</a>. But as it is, I do not use the Microsoft.VisualBasic assembly, and I'd rather not add an unnecessary dependency to my project.</p>\n\n<p>Second, the article shows how to bring the existing instance of the application to the foreground when the user tries to start another instance. That's a very nice touch that the other Mutex solutions described here do not address.</p>\n\n<hr>\n\n<h3>UPDATE</h3>\n\n<p>As of 8/1/2014, the article I linked to above is still active, but the blog hasn't been updated in a while. That makes me worry that eventually it might disappear, and with it, the advocated solution. I'm reproducing the content of the article here for posterity. The words belong solely to the blog owner at <a href=\"http://sanity-free.org/\" rel=\"noreferrer\">Sanity Free Coding</a>.</p>\n\n<blockquote>\n <p>Today I wanted to refactor some code that prohibited my application\n from running multiple instances of itself.</p>\n \n <p>Previously I had use <a href=\"http://msdn.microsoft.com/en-us/library/system.diagnostics.process(v=vs.110).aspx\" rel=\"noreferrer\">System.Diagnostics.Process</a> to search for an\n instance of my myapp.exe in the process list. While this works, it\n brings on a lot of overhead, and I wanted something cleaner.</p>\n \n <p>Knowing that I could use a mutex for this (but never having done it\n before) I set out to cut down my code and simplify my life.</p>\n \n <p>In the class of my application main I created a static named <a href=\"http://msdn.microsoft.com/en-us/library/system.threading.mutex(v=vs.110).aspx\" rel=\"noreferrer\">Mutex</a>:</p>\n</blockquote>\n\n<pre><code>static class Program\n{\n static Mutex mutex = new Mutex(true, \"{8F6F0AC4-B9A1-45fd-A8CF-72F04E6BDE8F}\");\n [STAThread]\n ...\n}\n</code></pre>\n\n<blockquote>\n <p>Having a named mutex allows us to stack synchronization across\n multiple threads and processes which is just the magic I'm looking\n for.</p>\n \n <p><a href=\"http://msdn.microsoft.com/en-us/library/58195swd(v=vs.110).aspx\" rel=\"noreferrer\">Mutex.WaitOne</a> has an overload that specifies an amount of time for us\n to wait. Since we're not actually wanting to synchronizing our code\n (more just check if it is currently in use) we use the overload with\n two parameters: <a href=\"http://msdn.microsoft.com/en-us/library/85bbbxt9(v=vs.110).aspx\" rel=\"noreferrer\">Mutex.WaitOne(Timespan timeout, bool exitContext)</a>.\n Wait one returns true if it is able to enter, and false if it wasn't.\n In this case, we don't want to wait at all; If our mutex is being\n used, skip it, and move on, so we pass in TimeSpan.Zero (wait 0\n milliseconds), and set the exitContext to true so we can exit the\n synchronization context before we try to aquire a lock on it. Using\n this, we wrap our Application.Run code inside something like this:</p>\n</blockquote>\n\n<pre><code>static class Program\n{\n static Mutex mutex = new Mutex(true, \"{8F6F0AC4-B9A1-45fd-A8CF-72F04E6BDE8F}\");\n [STAThread]\n static void Main() {\n if(mutex.WaitOne(TimeSpan.Zero, true)) {\n Application.EnableVisualStyles();\n Application.SetCompatibleTextRenderingDefault(false);\n Application.Run(new Form1());\n mutex.ReleaseMutex();\n } else {\n MessageBox.Show(\"only one instance at a time\");\n }\n }\n}\n</code></pre>\n\n<blockquote>\n <p>So, if our app is running, WaitOne will return false, and we'll get a\n message box.</p>\n \n <p>Instead of showing a message box, I opted to utilize a little Win32 to\n notify my running instance that someone forgot that it was already\n running (by bringing itself to the top of all the other windows). To\n achieve this I used <a href=\"http://msdn.microsoft.com/en-us/library/windows/desktop/ms644944(v=vs.85).aspx\" rel=\"noreferrer\">PostMessage</a> to broadcast a custom message to every\n window (the custom message was registered with <a href=\"http://msdn.microsoft.com/en-us/library/windows/desktop/ms644947(v=vs.85).aspx\" rel=\"noreferrer\">RegisterWindowMessage</a>\n by my running application, which means only my application knows what\n it is) then my second instance exits. The running application instance\n would receive that notification and process it. In order to do that, I\n overrode <a href=\"http://msdn.microsoft.com/en-us/library/system.windows.forms.form.wndproc(v=vs.110).aspx\" rel=\"noreferrer\">WndProc</a> in my main form and listened for my custom\n notification. When I received that notification I set the form's\n TopMost property to true to bring it up on top.</p>\n \n <p>Here is what I ended up with:</p>\n \n <ul>\n <li>Program.cs</li>\n </ul>\n</blockquote>\n\n<pre><code>static class Program\n{\n static Mutex mutex = new Mutex(true, \"{8F6F0AC4-B9A1-45fd-A8CF-72F04E6BDE8F}\");\n [STAThread]\n static void Main() {\n if(mutex.WaitOne(TimeSpan.Zero, true)) {\n Application.EnableVisualStyles();\n Application.SetCompatibleTextRenderingDefault(false);\n Application.Run(new Form1());\n mutex.ReleaseMutex();\n } else {\n // send our Win32 message to make the currently running instance\n // jump on top of all the other windows\n NativeMethods.PostMessage(\n (IntPtr)NativeMethods.HWND_BROADCAST,\n NativeMethods.WM_SHOWME,\n IntPtr.Zero,\n IntPtr.Zero);\n }\n }\n}\n</code></pre>\n\n<blockquote>\n <ul>\n <li>NativeMethods.cs</li>\n </ul>\n</blockquote>\n\n<pre><code>// this class just wraps some Win32 stuff that we're going to use\ninternal class NativeMethods\n{\n public const int HWND_BROADCAST = 0xffff;\n public static readonly int WM_SHOWME = RegisterWindowMessage(\"WM_SHOWME\");\n [DllImport(\"user32\")]\n public static extern bool PostMessage(IntPtr hwnd, int msg, IntPtr wparam, IntPtr lparam);\n [DllImport(\"user32\")]\n public static extern int RegisterWindowMessage(string message);\n}\n</code></pre>\n\n<blockquote>\n <ul>\n <li>Form1.cs (front side partial)</li>\n </ul>\n</blockquote>\n\n<pre><code>public partial class Form1 : Form\n{\n public Form1()\n {\n InitializeComponent();\n }\n protected override void WndProc(ref Message m)\n {\n if(m.Msg == NativeMethods.WM_SHOWME) {\n ShowMe();\n }\n base.WndProc(ref m);\n }\n private void ShowMe()\n {\n if(WindowState == FormWindowState.Minimized) {\n WindowState = FormWindowState.Normal;\n }\n // get our current \"TopMost\" value (ours will always be false though)\n bool top = TopMost;\n // make our form jump to the top of everything\n TopMost = true;\n // set it back to whatever it was\n TopMost = top;\n }\n}\n</code></pre>\n"
},
{
"answer_id": 1924705,
"author": "Bruce",
"author_id": 133297,
"author_profile": "https://Stackoverflow.com/users/133297",
"pm_score": 4,
"selected": false,
"text": "<p>Just some thoughts:\nThere are cases when requiring that only one instance of an application is not \"lame\" as some would have you believe. Database apps, etc. are an order of magnitude more difficult if one allows multiple instances of the app for a single user to access a database (you know, all that updating all the records that are open in multiple instances of the app on the users machine, etc.). \nFirst, for the \"name collision thing, don't use a human readable name - use a GUID instead or, even better a GUID + the human readable name. Chances of name collision just dropped off the radar and the Mutex doesn't care. As someone pointed out, a DOS attack would suck, but if the malicious person has gone to the trouble of getting the mutex name and incorporating it into their app, you are pretty much a target anyway and will have to do MUCH more to protect yourself than just fiddle a mutex name.\nAlso, if one uses the variant of:\nnew Mutex(true, \"some GUID plus Name\", out AIsFirstInstance), you already have your indicator as to whether or not the Mutex is the first instance.</p>\n"
},
{
"answer_id": 2295625,
"author": "Oliver Friedrich",
"author_id": 44532,
"author_profile": "https://Stackoverflow.com/users/44532",
"pm_score": 4,
"selected": false,
"text": "<p>Well, I have a disposable Class for this that works easily for most use cases:</p>\n\n<p>Use it like this:</p>\n\n<pre><code>static void Main()\n{\n using (SingleInstanceMutex sim = new SingleInstanceMutex())\n {\n if (sim.IsOtherInstanceRunning)\n {\n Application.Exit();\n }\n\n // Initialize program here.\n }\n}\n</code></pre>\n\n<p>Here it is:</p>\n\n<pre><code>/// <summary>\n/// Represents a <see cref=\"SingleInstanceMutex\"/> class.\n/// </summary>\npublic partial class SingleInstanceMutex : IDisposable\n{\n #region Fields\n\n /// <summary>\n /// Indicator whether another instance of this application is running or not.\n /// </summary>\n private bool isNoOtherInstanceRunning;\n\n /// <summary>\n /// The <see cref=\"Mutex\"/> used to ask for other instances of this application.\n /// </summary>\n private Mutex singleInstanceMutex = null;\n\n /// <summary>\n /// An indicator whether this object is beeing actively disposed or not.\n /// </summary>\n private bool disposed;\n\n #endregion\n\n #region Constructor\n\n /// <summary>\n /// Initializes a new instance of the <see cref=\"SingleInstanceMutex\"/> class.\n /// </summary>\n public SingleInstanceMutex()\n {\n this.singleInstanceMutex = new Mutex(true, Assembly.GetCallingAssembly().FullName, out this.isNoOtherInstanceRunning);\n }\n\n #endregion\n\n #region Properties\n\n /// <summary>\n /// Gets an indicator whether another instance of the application is running or not.\n /// </summary>\n public bool IsOtherInstanceRunning\n {\n get\n {\n return !this.isNoOtherInstanceRunning;\n }\n }\n\n #endregion\n\n #region Methods\n\n /// <summary>\n /// Closes the <see cref=\"SingleInstanceMutex\"/>.\n /// </summary>\n public void Close()\n {\n this.ThrowIfDisposed();\n this.singleInstanceMutex.Close();\n }\n\n public void Dispose()\n {\n this.Dispose(true);\n GC.SuppressFinalize(this);\n }\n\n private void Dispose(bool disposing)\n {\n if (!this.disposed)\n {\n /* Release unmanaged ressources */\n\n if (disposing)\n {\n /* Release managed ressources */\n this.Close();\n }\n\n this.disposed = true;\n }\n }\n\n /// <summary>\n /// Throws an exception if something is tried to be done with an already disposed object.\n /// </summary>\n /// <remarks>\n /// All public methods of the class must first call this.\n /// </remarks>\n public void ThrowIfDisposed()\n {\n if (this.disposed)\n {\n throw new ObjectDisposedException(this.GetType().Name);\n }\n }\n\n #endregion\n}\n</code></pre>\n"
},
{
"answer_id": 2769924,
"author": "Peter",
"author_id": 331895,
"author_profile": "https://Stackoverflow.com/users/331895",
"pm_score": 3,
"selected": false,
"text": "<p>So many answers to such a seemingly simple question. Just to shake things up a little bit here is my solution to this problem.</p>\n\n<p>Creating a Mutex can be troublesome because the JIT-er only sees you using it for a small portion of your code and wants to mark it as ready for garbage collection. It pretty much wants to out-smart you thinking you are not going to be using that Mutex for that long. In reality you want to hang onto this Mutex for as long as your application is running. The best way to tell the garbage collector to leave you Mutex alone is to tell it to keep it alive though out the different generations of garage collection. Example:</p>\n\n<pre><code>var m = new Mutex(...);\n...\nGC.KeepAlive(m);\n</code></pre>\n\n<p>I lifted the idea from this page: <a href=\"http://www.ai.uga.edu/~mc/SingleInstance.html\" rel=\"noreferrer\">http://www.ai.uga.edu/~mc/SingleInstance.html</a></p>\n"
},
{
"answer_id": 2932076,
"author": "huseyint",
"author_id": 39,
"author_profile": "https://Stackoverflow.com/users/39",
"pm_score": 4,
"selected": false,
"text": "<p>A new one that uses Mutex and IPC stuff, and also passes any command line arguments to the running instance, is <em><a href=\"http://blogs.microsoft.co.il/blogs/arik/archive/2010/05/28/wpf-single-instance-application.aspx\" rel=\"noreferrer\">WPF Single Instance Application</a></em>.</p>\n"
},
{
"answer_id": 3089321,
"author": "Sergey Aldoukhov",
"author_id": 58463,
"author_profile": "https://Stackoverflow.com/users/58463",
"pm_score": 2,
"selected": false,
"text": "<p>Here is what I use. It combined process enumeration to perform switching and mutex to safeguard from \"active clickers\":</p>\n\n<pre><code>public partial class App\n{\n [DllImport(\"user32\")]\n private static extern int OpenIcon(IntPtr hWnd);\n\n [DllImport(\"user32.dll\")]\n private static extern bool SetForegroundWindow(IntPtr hWnd);\n\n protected override void OnStartup(StartupEventArgs e)\n {\n base.OnStartup(e);\n var p = Process\n .GetProcessesByName(Process.GetCurrentProcess().ProcessName);\n foreach (var t in p.Where(t => t.MainWindowHandle != IntPtr.Zero))\n {\n OpenIcon(t.MainWindowHandle);\n SetForegroundWindow(t.MainWindowHandle);\n Current.Shutdown();\n return;\n }\n\n // there is a chance the user tries to click on the icon repeatedly\n // and the process cannot be discovered yet\n bool createdNew;\n var mutex = new Mutex(true, \"MyAwesomeApp\", \n out createdNew); // must be a variable, though it is unused - \n // we just need a bit of time until the process shows up\n if (!createdNew)\n {\n Current.Shutdown();\n return;\n }\n\n new Bootstrapper().Run();\n }\n }\n</code></pre>\n"
},
{
"answer_id": 3808173,
"author": "Simon_Weaver",
"author_id": 16940,
"author_profile": "https://Stackoverflow.com/users/16940",
"pm_score": 6,
"selected": false,
"text": "<p>MSDN actually has a sample application for both C# and VB to do exactly this: <a href=\"http://msdn.microsoft.com/en-us/library/ms771662(v=VS.90).aspx\" rel=\"noreferrer\">http://msdn.microsoft.com/en-us/library/ms771662(v=VS.90).aspx</a></p>\n\n<blockquote>\n <p>The most common and reliable technique\n for developing single-instance\n detection is to use the Microsoft .NET\n Framework remoting infrastructure\n (System.Remoting). The Microsoft .NET\n Framework (version 2.0) includes a\n type, WindowsFormsApplicationBase,\n which encapsulates the required\n remoting functionality. To incorporate\n this type into a WPF application, a\n type needs to derive from it, and be\n used as a shim between the application\n static entry point method, Main, and\n the WPF application's Application\n type. The shim detects when an\n application is first launched, and\n when subsequent launches are\n attempted, and yields control the WPF\n Application type to determine how to\n process the launches.</p>\n</blockquote>\n\n<ul>\n<li>For C# people just take a deep breath and forget about the whole 'I don't wanna include VisualBasic DLL'. Because of <a href=\"https://stackoverflow.com/questions/226517/is-the-microsoft-visualbasic-namespace-true-net-code\">this</a> and what <a href=\"http://www.hanselman.com/blog/TheWeeklySourceCode31SingleInstanceWinFormsAndMicrosoftVisualBasicdll.aspx\" rel=\"noreferrer\">Scott Hanselman says</a> and the fact that this pretty much is the cleanest solution to the problem and is designed by people who know a lot more about the framework than you do.</li>\n<li>From a usability standpoint the fact is if your user is loading an application and it is already open and you're giving them an error message like <code>'Another instance of the app is running. Bye'</code> then they're not gonna be a very happy user. You simply MUST (in a GUI application) switch to that application and pass in the arguments provided - or if command line parameters have no meaning then you must pop up the application which may have been minimized.</li>\n</ul>\n\n<p>The framework already has support for this - its just that some idiot named the DLL <code>Microsoft.VisualBasic</code> and it didn't get put into <code>Microsoft.ApplicationUtils</code> or something like that. Get over it - or open up Reflector.</p>\n\n<p>Tip: If you use this approach exactly as is, and you already have an App.xaml with resources etc. you'll want to <a href=\"http://www.infosysblogs.com/microsoft/2008/09/how_to_write_custom_main_metho.html\" rel=\"noreferrer\">take a look at this too</a>.</p>\n"
},
{
"answer_id": 5536495,
"author": "Mikhail Semenov",
"author_id": 653772,
"author_profile": "https://Stackoverflow.com/users/653772",
"pm_score": 2,
"selected": false,
"text": "<p>I found the simpler solution, similar to Dale Ragan's, but slightly modified. It does practically everything you need and based on the standard Microsoft WindowsFormsApplicationBase class.</p>\n\n<p>Firstly, you create SingleInstanceController class, which you can use in all other single-instance applications, which use Windows Forms:</p>\n\n<pre><code>using System;\nusing System.Collections.Generic;\nusing System.Linq;\nusing System.Text;\nusing System.Windows.Forms;\nusing Microsoft.VisualBasic.ApplicationServices;\n\n\nnamespace SingleInstanceController_NET\n{\n public class SingleInstanceController\n : WindowsFormsApplicationBase\n {\n public delegate Form CreateMainForm();\n public delegate void StartNextInstanceDelegate(Form mainWindow);\n CreateMainForm formCreation;\n StartNextInstanceDelegate onStartNextInstance;\n public SingleInstanceController(CreateMainForm formCreation, StartNextInstanceDelegate onStartNextInstance)\n {\n // Set whether the application is single instance\n this.formCreation = formCreation;\n this.onStartNextInstance = onStartNextInstance;\n this.IsSingleInstance = true;\n\n this.StartupNextInstance += new StartupNextInstanceEventHandler(this_StartupNextInstance); \n }\n\n void this_StartupNextInstance(object sender, StartupNextInstanceEventArgs e)\n {\n if (onStartNextInstance != null)\n {\n onStartNextInstance(this.MainForm); // This code will be executed when the user tries to start the running program again,\n // for example, by clicking on the exe file.\n } // This code can determine how to re-activate the existing main window of the running application.\n }\n\n protected override void OnCreateMainForm()\n {\n // Instantiate your main application form\n this.MainForm = formCreation();\n }\n\n public void Run()\n {\n string[] commandLine = new string[0];\n base.Run(commandLine);\n }\n }\n}\n</code></pre>\n\n<p>Then you can use it in your program as follows:</p>\n\n<pre><code>using System;\nusing System.Collections.Generic;\nusing System.Linq;\nusing System.Windows.Forms;\nusing SingleInstanceController_NET;\n\nnamespace SingleInstance\n{\n static class Program\n {\n /// <summary>\n /// The main entry point for the application.\n /// </summary>\n static Form CreateForm()\n {\n return new Form1(); // Form1 is used for the main window.\n }\n\n static void OnStartNextInstance(Form mainWindow) // When the user tries to restart the application again,\n // the main window is activated again.\n {\n mainWindow.WindowState = FormWindowState.Maximized;\n }\n [STAThread]\n static void Main()\n {\n Application.EnableVisualStyles();\n Application.SetCompatibleTextRenderingDefault(false); \n SingleInstanceController controller = new SingleInstanceController(CreateForm, OnStartNextInstance);\n controller.Run(); \n }\n }\n}\n</code></pre>\n\n<p>Both the program and the SingleInstanceController_NET solution should reference Microsoft.VisualBasic . If you just want to reactivate the running application as a normal window when the user tries to restart the running program, the second parameter in the SingleInstanceController can be null. In the given example, the window is maximized.</p>\n"
},
{
"answer_id": 5919904,
"author": "Nathan Moinvaziri",
"author_id": 610692,
"author_profile": "https://Stackoverflow.com/users/610692",
"pm_score": 4,
"selected": false,
"text": "<p>Here is an example that allows you to have a single instance of an application. When any new instances load, they pass their arguments to the main instance that is running.</p>\n\n<pre><code>public partial class App : Application\n{\n private static Mutex SingleMutex;\n public static uint MessageId;\n\n private void Application_Startup(object sender, StartupEventArgs e)\n {\n IntPtr Result;\n IntPtr SendOk;\n Win32.COPYDATASTRUCT CopyData;\n string[] Args;\n IntPtr CopyDataMem;\n bool AllowMultipleInstances = false;\n\n Args = Environment.GetCommandLineArgs();\n\n // TODO: Replace {00000000-0000-0000-0000-000000000000} with your application's GUID\n MessageId = Win32.RegisterWindowMessage(\"{00000000-0000-0000-0000-000000000000}\");\n SingleMutex = new Mutex(false, \"AppName\");\n\n if ((AllowMultipleInstances) || (!AllowMultipleInstances && SingleMutex.WaitOne(1, true)))\n {\n new Main();\n }\n else if (Args.Length > 1)\n {\n foreach (Process Proc in Process.GetProcesses())\n {\n SendOk = Win32.SendMessageTimeout(Proc.MainWindowHandle, MessageId, IntPtr.Zero, IntPtr.Zero,\n Win32.SendMessageTimeoutFlags.SMTO_BLOCK | Win32.SendMessageTimeoutFlags.SMTO_ABORTIFHUNG,\n 2000, out Result);\n\n if (SendOk == IntPtr.Zero)\n continue;\n if ((uint)Result != MessageId)\n continue;\n\n CopyDataMem = Marshal.AllocHGlobal(Marshal.SizeOf(typeof(Win32.COPYDATASTRUCT)));\n\n CopyData.dwData = IntPtr.Zero;\n CopyData.cbData = Args[1].Length*2;\n CopyData.lpData = Marshal.StringToHGlobalUni(Args[1]);\n\n Marshal.StructureToPtr(CopyData, CopyDataMem, false);\n\n Win32.SendMessageTimeout(Proc.MainWindowHandle, Win32.WM_COPYDATA, IntPtr.Zero, CopyDataMem,\n Win32.SendMessageTimeoutFlags.SMTO_BLOCK | Win32.SendMessageTimeoutFlags.SMTO_ABORTIFHUNG,\n 5000, out Result);\n\n Marshal.FreeHGlobal(CopyData.lpData);\n Marshal.FreeHGlobal(CopyDataMem);\n }\n\n Shutdown(0);\n }\n }\n}\n\npublic partial class Main : Window\n{\n private void Window_Loaded(object sender, RoutedEventArgs e)\n {\n HwndSource Source;\n\n Source = HwndSource.FromHwnd(new WindowInteropHelper(this).Handle);\n Source.AddHook(new HwndSourceHook(Window_Proc));\n }\n\n private IntPtr Window_Proc(IntPtr hWnd, int Msg, IntPtr wParam, IntPtr lParam, ref bool Handled)\n {\n Win32.COPYDATASTRUCT CopyData;\n string Path;\n\n if (Msg == Win32.WM_COPYDATA)\n {\n CopyData = (Win32.COPYDATASTRUCT)Marshal.PtrToStructure(lParam, typeof(Win32.COPYDATASTRUCT));\n Path = Marshal.PtrToStringUni(CopyData.lpData, CopyData.cbData / 2);\n\n if (WindowState == WindowState.Minimized)\n {\n // Restore window from tray\n }\n\n // Do whatever we want with information\n\n Activate();\n Focus();\n }\n\n if (Msg == App.MessageId)\n {\n Handled = true;\n return new IntPtr(App.MessageId);\n }\n\n return IntPtr.Zero;\n }\n}\n\npublic class Win32\n{\n public const uint WM_COPYDATA = 0x004A;\n\n public struct COPYDATASTRUCT\n {\n public IntPtr dwData;\n public int cbData;\n public IntPtr lpData;\n }\n\n [Flags]\n public enum SendMessageTimeoutFlags : uint\n {\n SMTO_NORMAL = 0x0000,\n SMTO_BLOCK = 0x0001,\n SMTO_ABORTIFHUNG = 0x0002,\n SMTO_NOTIMEOUTIFNOTHUNG = 0x0008\n }\n\n [DllImport(\"user32.dll\", SetLastError=true, CharSet=CharSet.Auto)]\n public static extern uint RegisterWindowMessage(string lpString);\n [DllImport(\"user32.dll\")]\n public static extern IntPtr SendMessageTimeout(\n IntPtr hWnd, uint Msg, IntPtr wParam, IntPtr lParam,\n SendMessageTimeoutFlags fuFlags, uint uTimeout, out IntPtr lpdwResult);\n}\n</code></pre>\n"
},
{
"answer_id": 7030059,
"author": "Joel Barsotti",
"author_id": 37154,
"author_profile": "https://Stackoverflow.com/users/37154",
"pm_score": 3,
"selected": false,
"text": "<p>It looks like there is a really good way to handle this:</p>\n\n<p><em><a href=\"http://blogs.microsoft.co.il/blogs/arik/archive/2010/05/28/wpf-single-instance-application.aspx\" rel=\"nofollow\">WPF Single Instance Application</a></em></p>\n\n<p>This provides a class you can add that manages all the mutex and messaging cruff to simplify the your implementation to the point where it's simply trivial.</p>\n"
},
{
"answer_id": 7183246,
"author": "CharithJ",
"author_id": 591656,
"author_profile": "https://Stackoverflow.com/users/591656",
"pm_score": 5,
"selected": false,
"text": "<p>This code should go to the main method. Look at <a href=\"http://joyfulwpf.blogspot.com/2009/05/where-is-main-method-in-my-wpf.html\" rel=\"noreferrer\">here</a> for more information about the main method in WPF.</p>\n\n<pre><code>[DllImport(\"user32.dll\")]\nprivate static extern Boolean ShowWindow(IntPtr hWnd, Int32 nCmdShow);\n\nprivate const int SW_SHOWMAXIMIZED = 3;\n\nstatic void Main() \n{\n Process currentProcess = Process.GetCurrentProcess();\n var runningProcess = (from process in Process.GetProcesses()\n where\n process.Id != currentProcess.Id &&\n process.ProcessName.Equals(\n currentProcess.ProcessName,\n StringComparison.Ordinal)\n select process).FirstOrDefault();\n if (runningProcess != null)\n {\n ShowWindow(runningProcess.MainWindowHandle, SW_SHOWMAXIMIZED);\n return; \n }\n}\n</code></pre>\n\n<p><strong>Method 2</strong></p>\n\n<pre><code>static void Main()\n{\n string procName = Process.GetCurrentProcess().ProcessName;\n // get the list of all processes by that name\n\n Process[] processes=Process.GetProcessesByName(procName);\n\n if (processes.Length > 1)\n {\n MessageBox.Show(procName + \" already running\"); \n return;\n } \n else\n {\n // Application.Run(...);\n }\n}\n</code></pre>\n\n<p><strong>Note :</strong> Above methods assumes your process/application has a unique name. Because it uses process name to find if any existing processors. So, if your application has a very common name (ie: Notepad), above approach won't work. </p>\n"
},
{
"answer_id": 13646352,
"author": "carlito",
"author_id": 1865565,
"author_profile": "https://Stackoverflow.com/users/1865565",
"pm_score": 3,
"selected": false,
"text": "<p>Look at the folllowing code. It is a great and simple solution to prevent multiple instances of a WPF application.</p>\n\n<pre><code>private void Application_Startup(object sender, StartupEventArgs e)\n{\n Process thisProc = Process.GetCurrentProcess();\n if (Process.GetProcessesByName(thisProc.ProcessName).Length > 1)\n {\n MessageBox.Show(\"Application running\");\n Application.Current.Shutdown();\n return;\n }\n\n var wLogin = new LoginWindow();\n\n if (wLogin.ShowDialog() == true)\n {\n var wMain = new Main();\n wMain.WindowState = WindowState.Maximized;\n wMain.Show();\n }\n else\n {\n Application.Current.Shutdown();\n }\n}\n</code></pre>\n"
},
{
"answer_id": 14337614,
"author": "Tommaso Belluzzo",
"author_id": 796085,
"author_profile": "https://Stackoverflow.com/users/796085",
"pm_score": 0,
"selected": false,
"text": "<p>Normally, this is the code I use for single-instance <a href=\"http://en.wikipedia.org/wiki/Windows_Forms\" rel=\"nofollow\">Windows Forms</a> applications:</p>\n\n<pre><code>[STAThread]\npublic static void Main()\n{\n String assemblyName = Assembly.GetExecutingAssembly().GetName().Name;\n\n using (Mutex mutex = new Mutex(false, assemblyName))\n {\n if (!mutex.WaitOne(0, false))\n {\n Boolean shownProcess = false;\n Process currentProcess = Process.GetCurrentProcess();\n\n foreach (Process process in Process.GetProcessesByName(currentProcess.ProcessName))\n {\n if (!process.Id.Equals(currentProcess.Id) && process.MainModule.FileName.Equals(currentProcess.MainModule.FileName) && !process.MainWindowHandle.Equals(IntPtr.Zero))\n {\n IntPtr windowHandle = process.MainWindowHandle;\n\n if (NativeMethods.IsIconic(windowHandle))\n NativeMethods.ShowWindow(windowHandle, ShowWindowCommand.Restore);\n\n NativeMethods.SetForegroundWindow(windowHandle);\n\n shownProcess = true;\n }\n }\n\n if (!shownProcess)\n MessageBox.Show(String.Format(CultureInfo.CurrentCulture, \"An instance of {0} is already running!\", assemblyName), assemblyName, MessageBoxButtons.OK, MessageBoxIcon.Asterisk, MessageBoxDefaultButton.Button1, (MessageBoxOptions)0);\n }\n else\n {\n Application.EnableVisualStyles();\n Application.SetCompatibleTextRenderingDefault(false);\n Application.Run(new Form());\n }\n }\n}\n</code></pre>\n\n<p>Where native components are:</p>\n\n<pre><code>[DllImport(\"User32.dll\", CharSet = CharSet.Unicode, ExactSpelling = true, SetLastError = true)]\n[return: MarshalAs(UnmanagedType.Bool)]\ninternal static extern Boolean IsIconic([In] IntPtr windowHandle);\n\n[DllImport(\"User32.dll\", CharSet = CharSet.Unicode, ExactSpelling = true, SetLastError = true)]\n[return: MarshalAs(UnmanagedType.Bool)]\ninternal static extern Boolean SetForegroundWindow([In] IntPtr windowHandle);\n\n[DllImport(\"User32.dll\", CharSet = CharSet.Unicode, ExactSpelling = true, SetLastError = true)]\n[return: MarshalAs(UnmanagedType.Bool)]\ninternal static extern Boolean ShowWindow([In] IntPtr windowHandle, [In] ShowWindowCommand command);\n\npublic enum ShowWindowCommand : int\n{\n Hide = 0x0,\n ShowNormal = 0x1,\n ShowMinimized = 0x2,\n ShowMaximized = 0x3,\n ShowNormalNotActive = 0x4,\n Minimize = 0x6,\n ShowMinimizedNotActive = 0x7,\n ShowCurrentNotActive = 0x8,\n Restore = 0x9,\n ShowDefault = 0xA,\n ForceMinimize = 0xB\n}\n</code></pre>\n"
},
{
"answer_id": 16097909,
"author": "Dan",
"author_id": 1507012,
"author_profile": "https://Stackoverflow.com/users/1507012",
"pm_score": 3,
"selected": false,
"text": "<p>The following code is my WCF named pipes solution to register a single-instance application. It's nice because it also raises an event when another instance attempts to start, and receives the command line of the other instance.</p>\n\n<p>It's geared toward WPF because it uses the <code>System.Windows.StartupEventHandler</code> class, but this could be easily modified.</p>\n\n<p>This code requires a reference to <code>PresentationFramework</code>, and <code>System.ServiceModel</code>.</p>\n\n<p><strong>Usage:</strong></p>\n\n<pre><code>class Program\n{\n static void Main()\n {\n var applicationId = new Guid(\"b54f7b0d-87f9-4df9-9686-4d8fd76066dc\");\n\n if (SingleInstanceManager.VerifySingleInstance(applicationId))\n {\n SingleInstanceManager.OtherInstanceStarted += OnOtherInstanceStarted;\n\n // Start the application\n }\n }\n\n static void OnOtherInstanceStarted(object sender, StartupEventArgs e)\n {\n // Do something in response to another instance starting up.\n }\n}\n</code></pre>\n\n<h3>Source Code:</h3>\n\n<pre><code>/// <summary>\n/// A class to use for single-instance applications.\n/// </summary>\npublic static class SingleInstanceManager\n{\n /// <summary>\n /// Raised when another instance attempts to start up.\n /// </summary>\n public static event StartupEventHandler OtherInstanceStarted;\n\n /// <summary>\n /// Checks to see if this instance is the first instance running on this machine. If it is not, this method will\n /// send the main instance this instance's startup information.\n /// </summary>\n /// <param name=\"guid\">The application's unique identifier.</param>\n /// <returns>True if this instance is the main instance.</returns>\n public static bool VerifySingleInstace(Guid guid)\n {\n if (!AttemptPublishService(guid))\n {\n NotifyMainInstance(guid);\n\n return false;\n }\n\n return true;\n }\n\n /// <summary>\n /// Attempts to publish the service.\n /// </summary>\n /// <param name=\"guid\">The application's unique identifier.</param>\n /// <returns>True if the service was published successfully.</returns>\n private static bool AttemptPublishService(Guid guid)\n {\n try\n {\n ServiceHost serviceHost = new ServiceHost(typeof(SingleInstance));\n NetNamedPipeBinding binding = new NetNamedPipeBinding(NetNamedPipeSecurityMode.None);\n serviceHost.AddServiceEndpoint(typeof(ISingleInstance), binding, CreateAddress(guid));\n serviceHost.Open();\n\n return true;\n }\n catch\n {\n return false;\n }\n }\n\n /// <summary>\n /// Notifies the main instance that this instance is attempting to start up.\n /// </summary>\n /// <param name=\"guid\">The application's unique identifier.</param>\n private static void NotifyMainInstance(Guid guid)\n {\n NetNamedPipeBinding binding = new NetNamedPipeBinding(NetNamedPipeSecurityMode.None);\n EndpointAddress remoteAddress = new EndpointAddress(CreateAddress(guid));\n using (ChannelFactory<ISingleInstance> factory = new ChannelFactory<ISingleInstance>(binding, remoteAddress))\n {\n ISingleInstance singleInstance = factory.CreateChannel();\n singleInstance.NotifyMainInstance(Environment.GetCommandLineArgs());\n }\n }\n\n /// <summary>\n /// Creates an address to publish/contact the service at based on a globally unique identifier.\n /// </summary>\n /// <param name=\"guid\">The identifier for the application.</param>\n /// <returns>The address to publish/contact the service.</returns>\n private static string CreateAddress(Guid guid)\n {\n return string.Format(CultureInfo.CurrentCulture, \"net.pipe://localhost/{0}\", guid);\n }\n\n /// <summary>\n /// The interface that describes the single instance service.\n /// </summary>\n [ServiceContract]\n private interface ISingleInstance\n {\n /// <summary>\n /// Notifies the main instance that another instance of the application attempted to start.\n /// </summary>\n /// <param name=\"args\">The other instance's command-line arguments.</param>\n [OperationContract]\n void NotifyMainInstance(string[] args);\n }\n\n /// <summary>\n /// The implementation of the single instance service interface.\n /// </summary>\n private class SingleInstance : ISingleInstance\n {\n /// <summary>\n /// Notifies the main instance that another instance of the application attempted to start.\n /// </summary>\n /// <param name=\"args\">The other instance's command-line arguments.</param>\n public void NotifyMainInstance(string[] args)\n {\n if (OtherInstanceStarted != null)\n {\n Type type = typeof(StartupEventArgs);\n ConstructorInfo constructor = type.GetConstructor(BindingFlags.Instance | BindingFlags.NonPublic, null, Type.EmptyTypes, null);\n StartupEventArgs e = (StartupEventArgs)constructor.Invoke(null);\n FieldInfo argsField = type.GetField(\"_args\", BindingFlags.Instance | BindingFlags.NonPublic);\n Debug.Assert(argsField != null);\n argsField.SetValue(e, args);\n\n OtherInstanceStarted(null, e);\n }\n }\n }\n}\n</code></pre>\n"
},
{
"answer_id": 16522305,
"author": "Simon Mourier",
"author_id": 403671,
"author_profile": "https://Stackoverflow.com/users/403671",
"pm_score": 4,
"selected": false,
"text": "<p>The code <a href=\"http://sanity-free.org/143/csharp_dotnet_single_instance_application.html\" rel=\"noreferrer\">C# .NET Single Instance Application</a> that is the reference for the marked answer is a great start.</p>\n\n<p>However, I found it doesn't handle very well the cases when the instance that already exist has a modal dialog open, whether that dialog is a managed one (like another Form such as an about box), or an unmanaged one (like the OpenFileDialog even when using the standard .NET class). With the original code, the main form is activated, but the modal one stays unactive, which looks strange, plus the user must click on it to keep using the app.</p>\n\n<p>So, I have create a SingleInstance utility class to handle all this quite automatically for Winforms and WPF applications.</p>\n\n<p><strong>Winforms</strong>:</p>\n\n<p>1) modify the Program class like this:</p>\n\n<pre><code>static class Program\n{\n public static readonly SingleInstance Singleton = new SingleInstance(typeof(Program).FullName);\n\n [STAThread]\n static void Main(string[] args)\n {\n // NOTE: if this always return false, close & restart Visual Studio\n // this is probably due to the vshost.exe thing\n Singleton.RunFirstInstance(() =>\n {\n SingleInstanceMain(args);\n });\n }\n\n public static void SingleInstanceMain(string[] args)\n {\n // standard code that was in Main now goes here\n Application.EnableVisualStyles();\n Application.SetCompatibleTextRenderingDefault(false);\n Application.Run(new Form1());\n }\n}\n</code></pre>\n\n<p>2) modify the main window class like this:</p>\n\n<pre><code>public partial class Form1 : Form\n{\n public Form1()\n {\n InitializeComponent();\n }\n\n protected override void WndProc(ref Message m)\n {\n // if needed, the singleton will restore this window\n Program.Singleton.OnWndProc(this, m, true);\n\n // TODO: handle specific messages here if needed\n base.WndProc(ref m);\n }\n}\n</code></pre>\n\n<p><strong>WPF:</strong></p>\n\n<p>1) modify the App page like this (and make sure you set its build action to page to be able to redefine the Main method):</p>\n\n<pre><code>public partial class App : Application\n{\n public static readonly SingleInstance Singleton = new SingleInstance(typeof(App).FullName);\n\n [STAThread]\n public static void Main(string[] args)\n {\n // NOTE: if this always return false, close & restart Visual Studio\n // this is probably due to the vshost.exe thing\n Singleton.RunFirstInstance(() =>\n {\n SingleInstanceMain(args);\n });\n }\n\n public static void SingleInstanceMain(string[] args)\n {\n // standard code that was in Main now goes here\n App app = new App();\n app.InitializeComponent();\n app.Run();\n }\n}\n</code></pre>\n\n<p>2) modify the main window class like this:</p>\n\n<pre><code>public partial class MainWindow : Window\n{\n private HwndSource _source;\n\n public MainWindow()\n {\n InitializeComponent();\n }\n\n protected override void OnSourceInitialized(EventArgs e)\n {\n base.OnSourceInitialized(e);\n _source = (HwndSource)PresentationSource.FromVisual(this);\n _source.AddHook(HwndSourceHook);\n }\n\n protected virtual IntPtr HwndSourceHook(IntPtr hwnd, int msg, IntPtr wParam, IntPtr lParam, ref bool handled)\n {\n // if needed, the singleton will restore this window\n App.Singleton.OnWndProc(hwnd, msg, wParam, lParam, true, true);\n\n // TODO: handle other specific message\n return IntPtr.Zero;\n }\n</code></pre>\n\n<p>And here is the utility class:</p>\n\n<pre><code>using System;\nusing System.ComponentModel;\nusing System.Runtime.InteropServices;\nusing System.Threading;\n\nnamespace SingleInstanceUtilities\n{\n public sealed class SingleInstance\n {\n private const int HWND_BROADCAST = 0xFFFF;\n\n [DllImport(\"user32.dll\")]\n private static extern bool PostMessage(IntPtr hwnd, int msg, IntPtr wparam, IntPtr lparam);\n\n [DllImport(\"user32.dll\", CharSet = CharSet.Unicode)]\n private static extern int RegisterWindowMessage(string message);\n\n [DllImport(\"user32.dll\")]\n private static extern bool SetForegroundWindow(IntPtr hWnd);\n\n public SingleInstance(string uniqueName)\n {\n if (uniqueName == null)\n throw new ArgumentNullException(\"uniqueName\");\n\n Mutex = new Mutex(true, uniqueName);\n Message = RegisterWindowMessage(\"WM_\" + uniqueName);\n }\n\n public Mutex Mutex { get; private set; }\n public int Message { get; private set; }\n\n public void RunFirstInstance(Action action)\n {\n RunFirstInstance(action, IntPtr.Zero, IntPtr.Zero);\n }\n\n // NOTE: if this always return false, close & restart Visual Studio\n // this is probably due to the vshost.exe thing\n public void RunFirstInstance(Action action, IntPtr wParam, IntPtr lParam)\n {\n if (action == null)\n throw new ArgumentNullException(\"action\");\n\n if (WaitForMutext(wParam, lParam))\n {\n try\n {\n action();\n }\n finally\n {\n ReleaseMutex();\n }\n }\n }\n\n public static void ActivateWindow(IntPtr hwnd)\n {\n if (hwnd == IntPtr.Zero)\n return;\n\n FormUtilities.ActivateWindow(FormUtilities.GetModalWindow(hwnd));\n }\n\n public void OnWndProc(IntPtr hwnd, int m, IntPtr wParam, IntPtr lParam, bool restorePlacement, bool activate)\n {\n if (m == Message)\n {\n if (restorePlacement)\n {\n WindowPlacement placement = WindowPlacement.GetPlacement(hwnd, false);\n if (placement.IsValid && placement.IsMinimized)\n {\n const int SW_SHOWNORMAL = 1;\n placement.ShowCmd = SW_SHOWNORMAL;\n placement.SetPlacement(hwnd);\n }\n }\n\n if (activate)\n {\n SetForegroundWindow(hwnd);\n FormUtilities.ActivateWindow(FormUtilities.GetModalWindow(hwnd));\n }\n }\n }\n\n#if WINFORMS // define this for Winforms apps\n public void OnWndProc(System.Windows.Forms.Form form, int m, IntPtr wParam, IntPtr lParam, bool activate)\n {\n if (form == null)\n throw new ArgumentNullException(\"form\");\n\n if (m == Message)\n {\n if (activate)\n {\n if (form.WindowState == System.Windows.Forms.FormWindowState.Minimized)\n {\n form.WindowState = System.Windows.Forms.FormWindowState.Normal;\n }\n\n form.Activate();\n FormUtilities.ActivateWindow(FormUtilities.GetModalWindow(form.Handle));\n }\n }\n }\n\n public void OnWndProc(System.Windows.Forms.Form form, System.Windows.Forms.Message m, bool activate)\n {\n if (form == null)\n throw new ArgumentNullException(\"form\");\n\n OnWndProc(form, m.Msg, m.WParam, m.LParam, activate);\n }\n#endif\n\n public void ReleaseMutex()\n {\n Mutex.ReleaseMutex();\n }\n\n public bool WaitForMutext(bool force, IntPtr wParam, IntPtr lParam)\n {\n bool b = PrivateWaitForMutext(force);\n if (!b)\n {\n PostMessage((IntPtr)HWND_BROADCAST, Message, wParam, lParam);\n }\n return b;\n }\n\n public bool WaitForMutext(IntPtr wParam, IntPtr lParam)\n {\n return WaitForMutext(false, wParam, lParam);\n }\n\n private bool PrivateWaitForMutext(bool force)\n {\n if (force)\n return true;\n\n try\n {\n return Mutex.WaitOne(TimeSpan.Zero, true);\n }\n catch (AbandonedMutexException)\n {\n return true;\n }\n }\n }\n\n // NOTE: don't add any field or public get/set property, as this must exactly map to Windows' WINDOWPLACEMENT structure\n [StructLayout(LayoutKind.Sequential)]\n public struct WindowPlacement\n {\n public int Length { get; set; }\n public int Flags { get; set; }\n public int ShowCmd { get; set; }\n public int MinPositionX { get; set; }\n public int MinPositionY { get; set; }\n public int MaxPositionX { get; set; }\n public int MaxPositionY { get; set; }\n public int NormalPositionLeft { get; set; }\n public int NormalPositionTop { get; set; }\n public int NormalPositionRight { get; set; }\n public int NormalPositionBottom { get; set; }\n\n [DllImport(\"user32.dll\", SetLastError = true)]\n private static extern bool SetWindowPlacement(IntPtr hWnd, ref WindowPlacement lpwndpl);\n\n [DllImport(\"user32.dll\", SetLastError = true)]\n private static extern bool GetWindowPlacement(IntPtr hWnd, ref WindowPlacement lpwndpl);\n\n private const int SW_SHOWMINIMIZED = 2;\n\n public bool IsMinimized\n {\n get\n {\n return ShowCmd == SW_SHOWMINIMIZED;\n }\n }\n\n public bool IsValid\n {\n get\n {\n return Length == Marshal.SizeOf(typeof(WindowPlacement));\n }\n }\n\n public void SetPlacement(IntPtr windowHandle)\n {\n SetWindowPlacement(windowHandle, ref this);\n }\n\n public static WindowPlacement GetPlacement(IntPtr windowHandle, bool throwOnError)\n {\n WindowPlacement placement = new WindowPlacement();\n if (windowHandle == IntPtr.Zero)\n return placement;\n\n placement.Length = Marshal.SizeOf(typeof(WindowPlacement));\n if (!GetWindowPlacement(windowHandle, ref placement))\n {\n if (throwOnError)\n throw new Win32Exception(Marshal.GetLastWin32Error());\n\n return new WindowPlacement();\n }\n return placement;\n }\n }\n\n public static class FormUtilities\n {\n [DllImport(\"user32.dll\")]\n private static extern IntPtr GetWindow(IntPtr hWnd, int uCmd);\n\n [DllImport(\"user32.dll\", SetLastError = true)]\n private static extern IntPtr SetActiveWindow(IntPtr hWnd);\n\n [DllImport(\"user32.dll\")]\n private static extern bool IsWindowVisible(IntPtr hWnd);\n\n [DllImport(\"kernel32.dll\")]\n public static extern int GetCurrentThreadId();\n\n private delegate bool EnumChildrenCallback(IntPtr hwnd, IntPtr lParam);\n\n [DllImport(\"user32.dll\")]\n private static extern bool EnumThreadWindows(int dwThreadId, EnumChildrenCallback lpEnumFunc, IntPtr lParam);\n\n private class ModalWindowUtil\n {\n private const int GW_OWNER = 4;\n private int _maxOwnershipLevel;\n private IntPtr _maxOwnershipHandle;\n\n private bool EnumChildren(IntPtr hwnd, IntPtr lParam)\n {\n int level = 1;\n if (IsWindowVisible(hwnd) && IsOwned(lParam, hwnd, ref level))\n {\n if (level > _maxOwnershipLevel)\n {\n _maxOwnershipHandle = hwnd;\n _maxOwnershipLevel = level;\n }\n }\n return true;\n }\n\n private static bool IsOwned(IntPtr owner, IntPtr hwnd, ref int level)\n {\n IntPtr o = GetWindow(hwnd, GW_OWNER);\n if (o == IntPtr.Zero)\n return false;\n\n if (o == owner)\n return true;\n\n level++;\n return IsOwned(owner, o, ref level);\n }\n\n public static void ActivateWindow(IntPtr hwnd)\n {\n if (hwnd != IntPtr.Zero)\n {\n SetActiveWindow(hwnd);\n }\n }\n\n public static IntPtr GetModalWindow(IntPtr owner)\n {\n ModalWindowUtil util = new ModalWindowUtil();\n EnumThreadWindows(GetCurrentThreadId(), util.EnumChildren, owner);\n return util._maxOwnershipHandle; // may be IntPtr.Zero\n }\n }\n\n public static void ActivateWindow(IntPtr hwnd)\n {\n ModalWindowUtil.ActivateWindow(hwnd);\n }\n\n public static IntPtr GetModalWindow(IntPtr owner)\n {\n return ModalWindowUtil.GetModalWindow(owner);\n }\n }\n}\n</code></pre>\n"
},
{
"answer_id": 19470753,
"author": "Cornel Marian",
"author_id": 736113,
"author_profile": "https://Stackoverflow.com/users/736113",
"pm_score": 1,
"selected": false,
"text": "<p>Use mutex solution:</p>\n\n<pre><code>using System;\nusing System.Windows.Forms;\nusing System.Threading;\n\nnamespace OneAndOnlyOne\n{\nstatic class Program\n{\n static String _mutexID = \" // generate guid\"\n /// <summary>\n /// The main entry point for the application.\n /// </summary>\n [STAThread]\n static void Main()\n {\n Application.EnableVisualStyles();\n Application.SetCompatibleTextRenderingDefault(false);\n\n Boolean _isNotRunning;\n using (Mutex _mutex = new Mutex(true, _mutexID, out _isNotRunning))\n {\n if (_isNotRunning)\n {\n Application.Run(new Form1());\n }\n else\n {\n MessageBox.Show(\"An instance is already running.\");\n return;\n }\n }\n }\n}\n}\n</code></pre>\n"
},
{
"answer_id": 20278491,
"author": "Jason Lim",
"author_id": 1973634,
"author_profile": "https://Stackoverflow.com/users/1973634",
"pm_score": 1,
"selected": false,
"text": "<p>Here's a lightweight solution I use which allows the application to bring an already existing window to the foreground without resorting to custom windows messages or blindly searching process names.</p>\n\n<pre><code>[DllImport(\"user32.dll\")]\nstatic extern bool SetForegroundWindow(IntPtr hWnd);\n\nstatic readonly string guid = \"<Application Guid>\";\n\nstatic void Main()\n{\n Mutex mutex = null;\n if (!CreateMutex(out mutex))\n return;\n\n // Application startup code.\n\n Environment.SetEnvironmentVariable(guid, null, EnvironmentVariableTarget.User);\n}\n\nstatic bool CreateMutex(out Mutex mutex)\n{\n bool createdNew = false;\n mutex = new Mutex(false, guid, out createdNew);\n\n if (createdNew)\n {\n Process process = Process.GetCurrentProcess();\n string value = process.Id.ToString();\n\n Environment.SetEnvironmentVariable(guid, value, EnvironmentVariableTarget.User);\n }\n else\n {\n string value = Environment.GetEnvironmentVariable(guid, EnvironmentVariableTarget.User);\n Process process = null;\n int processId = -1;\n\n if (int.TryParse(value, out processId))\n process = Process.GetProcessById(processId);\n\n if (process == null || !SetForegroundWindow(process.MainWindowHandle))\n MessageBox.Show(\"Unable to start application. An instance of this application is already running.\");\n }\n\n return createdNew;\n}\n</code></pre>\n\n<p>Edit: You can also store and initialize mutex and createdNew statically, but you'll need to explicitly dispose/release the mutex once you're done with it. Personally, I prefer keeping the mutex local as it will be automatically disposed of even if the application closes without ever reaching the end of Main.</p>\n"
},
{
"answer_id": 20412588,
"author": "Eric Ouellet",
"author_id": 452845,
"author_profile": "https://Stackoverflow.com/users/452845",
"pm_score": 2,
"selected": false,
"text": "<p><strong>Update 2017-01-25.</strong> After trying few things, I decided to go with VisualBasic.dll it is easier and works better (at least for me). I let my previous answer just as reference...</p>\n\n<p>Just as reference, this is how I did without passing arguments (which I can't find any reason to do so... I mean a single app with arguments that as to be passed out from one instance to another one).\nIf file association is required, then an app should (per users standard expectation) be instanciated for each doc. If you have to pass args to existing app, I think I would used vb dll.</p>\n\n<p>Not passing args (just single instance app), I prefer not registering a new Window message and not override the message loop as defined in Matt Davis Solution. Although it's not a big deal to add a VisualBasic dll, but I prefer not add a new reference just to do single instance app. Also, I do prefer instanciate a new class with Main instead of calling Shutdown from App.Startup override to ensure to exit as soon as possible.</p>\n\n<p>In hope that anybody will like it... or will inspire a little bit :-) </p>\n\n<p>Project startup class should be set as 'SingleInstanceApp'.</p>\n\n<pre><code>public class SingleInstanceApp\n{\n [STAThread]\n public static void Main(string[] args)\n {\n Mutex _mutexSingleInstance = new Mutex(true, \"MonitorMeSingleInstance\");\n\n if (_mutexSingleInstance.WaitOne(TimeSpan.Zero, true))\n {\n try\n {\n var app = new App();\n app.InitializeComponent();\n app.Run();\n\n }\n finally\n {\n _mutexSingleInstance.ReleaseMutex();\n _mutexSingleInstance.Close();\n }\n }\n else\n {\n MessageBox.Show(\"One instance is already running.\");\n\n var processes = Process.GetProcessesByName(Assembly.GetEntryAssembly().GetName().Name);\n {\n if (processes.Length > 1)\n {\n foreach (var process in processes)\n {\n if (process.Id != Process.GetCurrentProcess().Id)\n {\n WindowHelper.SetForegroundWindow(process.MainWindowHandle);\n }\n }\n }\n }\n }\n }\n}\n</code></pre>\n\n<p>WindowHelper:</p>\n\n<pre><code>using System;\nusing System.Runtime.InteropServices;\nusing System.Windows;\nusing System.Windows.Interop;\nusing System.Windows.Threading;\n\nnamespace HQ.Util.Unmanaged\n{\n public class WindowHelper\n {\n [DllImport(\"user32.dll\")]\n [return: MarshalAs(UnmanagedType.Bool)]\n public static extern bool SetForegroundWindow(IntPtr hWnd);\n</code></pre>\n"
},
{
"answer_id": 25844191,
"author": "Antoine Diekmann",
"author_id": 1955485,
"author_profile": "https://Stackoverflow.com/users/1955485",
"pm_score": 0,
"selected": false,
"text": "<p>You can also use the <a href=\"http://www.softfluent.com/products/codefluent-runtime-client\" rel=\"nofollow\">CodeFluent Runtime</a> which is free set of tools. It provides a <a href=\"http://blog.codefluententities.com/2014/09/10/single-instance-application-in-net/\" rel=\"nofollow\">SingleInstance</a> class to implement a single instance application.</p>\n"
},
{
"answer_id": 28146800,
"author": "Martin Bech",
"author_id": 1677634,
"author_profile": "https://Stackoverflow.com/users/1677634",
"pm_score": 2,
"selected": false,
"text": "<p>I added a sendMessage Method to the NativeMethods Class.</p>\n\n<p>Apparently the postmessage method dosent work, if the application is not show in the taskbar, however using the sendmessage method solves this.</p>\n\n<pre><code>class NativeMethods\n{\n public const int HWND_BROADCAST = 0xffff;\n public static readonly int WM_SHOWME = RegisterWindowMessage(\"WM_SHOWME\");\n [DllImport(\"user32\")]\n public static extern bool PostMessage(IntPtr hwnd, int msg, IntPtr wparam, IntPtr lparam);\n [DllImport(\"user32.dll\", CharSet = CharSet.Auto)]\n public static extern IntPtr SendMessage(IntPtr hWnd, int Msg, IntPtr wParam, IntPtr lParam);\n [DllImport(\"user32\")]\n public static extern int RegisterWindowMessage(string message);\n}\n</code></pre>\n"
},
{
"answer_id": 38212569,
"author": "Code Scratcher",
"author_id": 4342676,
"author_profile": "https://Stackoverflow.com/users/4342676",
"pm_score": 0,
"selected": false,
"text": "<p>Here is a solution:</p>\n\n<pre><code>Protected Overrides Sub OnStartup(e As StartupEventArgs)\n Const appName As String = \"TestApp\"\n Dim createdNew As Boolean\n _mutex = New Mutex(True, appName, createdNew)\n If Not createdNew Then\n 'app is already running! Exiting the application\n MessageBox.Show(\"Application is already running.\")\n Application.Current.Shutdown()\n End If\n MyBase.OnStartup(e)\nEnd Sub\n</code></pre>\n"
},
{
"answer_id": 38306338,
"author": "Siarhei Kuchuk",
"author_id": 212746,
"author_profile": "https://Stackoverflow.com/users/212746",
"pm_score": 1,
"selected": false,
"text": "<p>Here's the same thing implemented via Event.</p>\n\n<pre><code>public enum ApplicationSingleInstanceMode\n{\n CurrentUserSession,\n AllSessionsOfCurrentUser,\n Pc\n}\n\npublic class ApplicationSingleInstancePerUser: IDisposable\n{\n private readonly EventWaitHandle _event;\n\n /// <summary>\n /// Shows if the current instance of ghost is the first\n /// </summary>\n public bool FirstInstance { get; private set; }\n\n /// <summary>\n /// Initializes \n /// </summary>\n /// <param name=\"applicationName\">The application name</param>\n /// <param name=\"mode\">The single mode</param>\n public ApplicationSingleInstancePerUser(string applicationName, ApplicationSingleInstanceMode mode = ApplicationSingleInstanceMode.CurrentUserSession)\n {\n string name;\n if (mode == ApplicationSingleInstanceMode.CurrentUserSession)\n name = $\"Local\\\\{applicationName}\";\n else if (mode == ApplicationSingleInstanceMode.AllSessionsOfCurrentUser)\n name = $\"Global\\\\{applicationName}{Environment.UserDomainName}\";\n else\n name = $\"Global\\\\{applicationName}\";\n\n try\n {\n bool created;\n _event = new EventWaitHandle(false, EventResetMode.ManualReset, name, out created);\n FirstInstance = created;\n }\n catch\n {\n }\n }\n\n public void Dispose()\n {\n _event.Dispose();\n }\n}\n</code></pre>\n"
},
{
"answer_id": 38853721,
"author": "pStan",
"author_id": 1221380,
"author_profile": "https://Stackoverflow.com/users/1221380",
"pm_score": 1,
"selected": false,
"text": "<p>This is how I ended up taking care of this issue. Note that debug code is still in there for testing. This code is within the OnStartup in the App.xaml.cs file. (WPF) </p>\n\n<pre><code> // Process already running ? \n if (Process.GetProcessesByName(Process.GetCurrentProcess().ProcessName).Length > 1)\n {\n\n // Show your error message\n MessageBox.Show(\"xxx is already running. \\r\\n\\r\\nIf the original process is hung up you may need to restart your computer, or kill the current xxx process using the task manager.\", \"xxx is already running!\", MessageBoxButton.OK, MessageBoxImage.Exclamation);\n\n // This process \n Process currentProcess = Process.GetCurrentProcess();\n\n // Get all processes running on the local computer.\n Process[] localAll = Process.GetProcessesByName(Process.GetCurrentProcess().ProcessName);\n\n // ID of this process... \n int temp = currentProcess.Id;\n MessageBox.Show(\"This Process ID: \" + temp.ToString());\n\n for (int i = 0; i < localAll.Length; i++)\n {\n // Find the other process \n if (localAll[i].Id != currentProcess.Id)\n {\n MessageBox.Show(\"Original Process ID (Switching to): \" + localAll[i].Id.ToString());\n\n // Switch to it... \n SetForegroundWindow(localAll[i].MainWindowHandle);\n\n }\n }\n\n Application.Current.Shutdown();\n\n }\n</code></pre>\n\n<p>This may have issues that I have not caught yet. If I run into any I'll update my answer. </p>\n"
},
{
"answer_id": 39160390,
"author": "kakopappa",
"author_id": 192901,
"author_profile": "https://Stackoverflow.com/users/192901",
"pm_score": 0,
"selected": false,
"text": "<p>Here is my 2 cents</p>\n\n<pre><code> static class Program\n {\n [STAThread]\n static void Main()\n {\n bool createdNew;\n using (new Mutex(true, \"MyApp\", out createdNew))\n {\n if (createdNew) {\n Application.EnableVisualStyles();\n Application.SetCompatibleTextRenderingDefault(false);\n var mainClass = new SynGesturesLogic();\n Application.ApplicationExit += mainClass.tray_exit;\n Application.Run();\n }\n else\n {\n var current = Process.GetCurrentProcess();\n foreach (var process in Process.GetProcessesByName(current.ProcessName).Where(process => process.Id != current.Id))\n {\n NativeMethods.SetForegroundWindow(process.MainWindowHandle);\n break;\n }\n }\n }\n }\n }\n</code></pre>\n"
},
{
"answer_id": 39775932,
"author": "Pete",
"author_id": 2833784,
"author_profile": "https://Stackoverflow.com/users/2833784",
"pm_score": 0,
"selected": false,
"text": "<p>I like a solution to allow multiple Instances, if the exe is called from an other path. I modified CharithJ solution Method 1:</p>\n\n<pre><code> static class Program {\n [DllImport(\"user32.dll\")]\n private static extern bool ShowWindow(IntPtr hWnd, Int32 nCmdShow);\n [DllImport(\"User32.dll\")]\n public static extern Int32 SetForegroundWindow(IntPtr hWnd);\n [STAThread]\n static void Main() {\n Process currentProcess = Process.GetCurrentProcess();\n foreach (var process in Process.GetProcesses()) {\n try {\n if ((process.Id != currentProcess.Id) && \n (process.ProcessName == currentProcess.ProcessName) &&\n (process.MainModule.FileName == currentProcess.MainModule.FileName)) {\n ShowWindow(process.MainWindowHandle, 5); // const int SW_SHOW = 5; //Activates the window and displays it in its current size and position. \n SetForegroundWindow(process.MainWindowHandle);\n return;\n }\n } catch (Exception ex) {\n //ignore Exception \"Access denied \"\n }\n }\n\n Application.EnableVisualStyles();\n Application.SetCompatibleTextRenderingDefault(false);\n Application.Run(new Form1());\n }\n}\n</code></pre>\n"
},
{
"answer_id": 41390636,
"author": "newbieguy",
"author_id": 4477797,
"author_profile": "https://Stackoverflow.com/users/4477797",
"pm_score": 2,
"selected": false,
"text": "<p>Not using Mutex though, simple answer:</p>\n\n<pre><code>System.Diagnostics; \n...\nstring thisprocessname = Process.GetCurrentProcess().ProcessName;\n\nif (Process.GetProcesses().Count(p => p.ProcessName == thisprocessname) > 1)\n return;\n</code></pre>\n\n<p>Put it inside the <code>Program.Main()</code>.<br>\n<strong>Example</strong>:</p>\n\n<pre><code>using System;\nusing System.Collections.Generic;\nusing System.Linq;\nusing System.Threading.Tasks;\nusing System.Windows.Forms;\nusing System.Diagnostics;\n\nnamespace Sample\n{\n static class Program\n {\n /// <summary>\n /// The main entry point for the application.\n /// </summary>\n [STAThread]\n static void Main()\n {\n //simple add Diagnostics namespace, and these 3 lines below \n string thisprocessname = Process.GetCurrentProcess().ProcessName;\n if (Process.GetProcesses().Count(p => p.ProcessName == thisprocessname) > 1)\n return;\n\n Application.EnableVisualStyles();\n Application.SetCompatibleTextRenderingDefault(false);\n Application.Run(new Sample());\n }\n }\n}\n</code></pre>\n\n<p>You can add <code>MessageBox.Show</code> to the <code>if</code>-statement and put \"Application already running\".<br>\nThis might be helpful to someone.</p>\n"
},
{
"answer_id": 41599502,
"author": "Divins Mathew",
"author_id": 3201403,
"author_profile": "https://Stackoverflow.com/users/3201403",
"pm_score": 0,
"selected": false,
"text": "<p>Simply using a <code>StreamWriter</code>, how about this?</p>\n\n<pre><code>System.IO.File.StreamWriter OpenFlag = null; //globally\n</code></pre>\n\n<p>and</p>\n\n<pre><code>try\n{\n OpenFlag = new StreamWriter(Path.GetTempPath() + \"OpenedIfRunning\");\n}\ncatch (System.IO.IOException) //file in use\n{\n Environment.Exit(0);\n}\n</code></pre>\n"
},
{
"answer_id": 45778772,
"author": "A.T.",
"author_id": 2734629,
"author_profile": "https://Stackoverflow.com/users/2734629",
"pm_score": 2,
"selected": false,
"text": "<p>Named-mutex-based approaches are not cross-platform because named mutexes are not global in Mono. Process-enumeration-based approaches don't have any synchronization and may result in incorrect behavior (e.g. multiple processes started at the same time may all self-terminate depending on timing). Windowing-system-based approaches are not desirable in a console application. This solution, built on top of Divin's answer, addresses all these issues:</p>\n\n<pre><code>using System;\nusing System.IO;\n\nnamespace TestCs\n{\n public class Program\n {\n // The app id must be unique. Generate a new guid for your application. \n public static string AppId = \"01234567-89ab-cdef-0123-456789abcdef\";\n\n // The stream is stored globally to ensure that it won't be disposed before the application terminates.\n public static FileStream UniqueInstanceStream;\n\n public static int Main(string[] args)\n {\n EnsureUniqueInstance();\n\n // Your code here.\n\n return 0;\n }\n\n private static void EnsureUniqueInstance()\n {\n // Note: If you want the check to be per-user, use Environment.SpecialFolder.ApplicationData instead.\n string lockDir = Path.Combine(\n Environment.GetFolderPath(Environment.SpecialFolder.CommonApplicationData),\n \"UniqueInstanceApps\");\n string lockPath = Path.Combine(lockDir, $\"{AppId}.unique\");\n\n Directory.CreateDirectory(lockDir);\n\n try\n {\n // Create the file with exclusive write access. If this fails, then another process is executing.\n UniqueInstanceStream = File.Open(lockPath, FileMode.Create, FileAccess.Write, FileShare.None);\n\n // Although only the line above should be sufficient, when debugging with a vshost on Visual Studio\n // (that acts as a proxy), the IO exception isn't passed to the application before a Write is executed.\n UniqueInstanceStream.Write(new byte[] { 0 }, 0, 1);\n UniqueInstanceStream.Flush();\n }\n catch\n {\n throw new Exception(\"Another instance of the application is already running.\");\n }\n }\n }\n}\n</code></pre>\n"
},
{
"answer_id": 47849014,
"author": "Legends",
"author_id": 2581562,
"author_profile": "https://Stackoverflow.com/users/2581562",
"pm_score": 2,
"selected": false,
"text": "<p><strong>[I have provided sample code for console and wpf applications below.]</strong></p>\n\n<p>You only have to check the value of the <code>createdNew</code> variable (example below!), after you create the named Mutex instance.</p>\n\n<p>The boolean <code>createdNew</code> will return <strong>false:</strong></p>\n\n<blockquote>\n <p>if the Mutex instance named \"YourApplicationNameHere\" was already\n created on the system somewhere </p>\n</blockquote>\n\n<p>The boolean <code>createdNew</code> will return <strong>true:</strong></p>\n\n<blockquote>\n <p>if this is the first Mutex named \"YourApplicationNameHere\" on the\n system.</p>\n</blockquote>\n\n<p><hr>\n<strong>Console application - Example:</strong></p>\n\n<pre><code>static Mutex m = null;\n\nstatic void Main(string[] args)\n{\n const string mutexName = \"YourApplicationNameHere\";\n bool createdNew = false;\n\n try\n {\n // Initializes a new instance of the Mutex class with a Boolean value that indicates \n // whether the calling thread should have initial ownership of the mutex, a string that is the name of the mutex, \n // and a Boolean value that, when the method returns, indicates whether the calling thread was granted initial ownership of the mutex.\n\n using (m = new Mutex(true, mutexName, out createdNew))\n {\n if (!createdNew)\n {\n Console.WriteLine(\"instance is alreday running... shutting down !!!\");\n Console.Read();\n return; // Exit the application\n }\n\n // Run your windows forms app here\n Console.WriteLine(\"Single instance app is running!\");\n Console.ReadLine();\n }\n\n\n }\n catch (Exception ex)\n {\n\n Console.WriteLine(ex.Message);\n Console.ReadLine();\n }\n}\n</code></pre>\n\n<p><strong>WPF-Example:</strong></p>\n\n<pre><code>public partial class App : Application\n{\nstatic Mutex m = null;\n\nprotected override void OnStartup(StartupEventArgs e)\n{\n\n const string mutexName = \"YourApplicationNameHere\";\n bool createdNew = false;\n\n try\n {\n // Initializes a new instance of the Mutex class with a Boolean value that indicates \n // whether the calling thread should have initial ownership of the mutex, a string that is the name of the mutex, \n // and a Boolean value that, when the method returns, indicates whether the calling thread was granted initial ownership of the mutex.\n\n m = new Mutex(true, mutexName, out createdNew);\n\n if (!createdNew)\n {\n Current.Shutdown(); // Exit the application\n }\n\n }\n catch (Exception)\n {\n throw;\n }\n\n base.OnStartup(e);\n}\n\n\nprotected override void OnExit(ExitEventArgs e)\n{\n if (m != null)\n {\n m.Dispose();\n }\n base.OnExit(e);\n}\n}\n</code></pre>\n"
},
{
"answer_id": 48657296,
"author": "A.J.Bauer",
"author_id": 1278334,
"author_profile": "https://Stackoverflow.com/users/1278334",
"pm_score": 1,
"selected": false,
"text": "<p>A time saving solution for C# Winforms...</p>\n\n<p>Program.cs:</p>\n\n<pre><code>using System;\nusing System.Windows.Forms;\n// needs reference to Microsoft.VisualBasic\nusing Microsoft.VisualBasic.ApplicationServices; \n\nnamespace YourNamespace\n{\n public class SingleInstanceController : WindowsFormsApplicationBase\n {\n public SingleInstanceController()\n {\n this.IsSingleInstance = true;\n }\n\n protected override void OnStartupNextInstance(StartupNextInstanceEventArgs e)\n {\n e.BringToForeground = true;\n base.OnStartupNextInstance(e);\n }\n\n protected override void OnCreateMainForm()\n {\n this.MainForm = new Form1();\n }\n }\n\n static class Program\n {\n [STAThread]\n static void Main()\n {\n Application.EnableVisualStyles();\n Application.SetCompatibleTextRenderingDefault(false);\n string[] args = Environment.GetCommandLineArgs();\n SingleInstanceController controller = new SingleInstanceController();\n controller.Run(args);\n }\n }\n}\n</code></pre>\n"
},
{
"answer_id": 49796895,
"author": "Deniz",
"author_id": 9569602,
"author_profile": "https://Stackoverflow.com/users/9569602",
"pm_score": 2,
"selected": false,
"text": "<p>I can't find a <strong>short solution</strong> here so I hope someone will like this:</p>\n\n<p><strong>UPDATED 2018-09-20</strong></p>\n\n<p>Put this code in your <code>Program.cs</code>:</p>\n\n<pre><code>using System.Diagnostics;\n\nstatic void Main()\n{\n Process thisProcess = Process.GetCurrentProcess();\n Process[] allProcesses = Process.GetProcessesByName(thisProcess.ProcessName);\n if (allProcesses.Length > 1)\n {\n // Don't put a MessageBox in here because the user could spam this MessageBox.\n return;\n }\n\n // Optional code. If you don't want that someone runs your \".exe\" with a different name:\n\n string exeName = AppDomain.CurrentDomain.FriendlyName;\n // in debug mode, don't forget that you don't use your normal .exe name.\n // Debug uses the .vshost.exe.\n if (exeName != \"the name of your executable.exe\") \n {\n // You can add a MessageBox here if you want.\n // To point out to users that the name got changed and maybe what the name should be or something like that^^ \n MessageBox.Show(\"The executable name should be \\\"the name of your executable.exe\\\"\", \n \"Wrong executable name\", MessageBoxButtons.OK, MessageBoxIcon.Error);\n return;\n }\n\n // Following code is default code:\n Application.EnableVisualStyles();\n Application.SetCompatibleTextRenderingDefault(false);\n Application.Run(new MainForm());\n}\n</code></pre>\n"
},
{
"answer_id": 57140889,
"author": "Vishnu Babu",
"author_id": 5342284,
"author_profile": "https://Stackoverflow.com/users/5342284",
"pm_score": 2,
"selected": false,
"text": "<p>I use <a href=\"https://learn.microsoft.com/en-us/dotnet/api/system.threading.mutex?view=netframework-4.8\" rel=\"nofollow noreferrer\">Mutex</a> in my solution for preventing multiple instances.</p>\n\n<pre><code>static Mutex mutex = null;\n//A string that is the name of the mutex\nstring mutexName = @\"Global\\test\";\n//Prevent Multiple Instances of Application\nbool onlyInstance = false;\nmutex = new Mutex(true, mutexName, out onlyInstance);\n\nif (!onlyInstance)\n{\n MessageBox.Show(\"You are already running this application in your system.\", \"Already Running..\", MessageBoxButton.OK);\n Application.Current.Shutdown();\n}\n</code></pre>\n"
},
{
"answer_id": 59851185,
"author": "Alexandru Dicu",
"author_id": 1140388,
"author_profile": "https://Stackoverflow.com/users/1140388",
"pm_score": 1,
"selected": false,
"text": "<p>Please check the proposed solution from <a href=\"https://stackoverflow.com/questions/59706160/c-sharp-dot-net-core-single-instance-app-passing-parameters-to-first-instance\">here</a> that uses a semaphore to determine if an existing instance is already running, works for a WPF application and can pass arguments from second instance to the first already running instance by using a TcpListener and a TcpClient:</p>\n\n<p>It works also for .NET Core, not only for .NET Framework.</p>\n"
},
{
"answer_id": 62712773,
"author": "std8590",
"author_id": 13319821,
"author_profile": "https://Stackoverflow.com/users/13319821",
"pm_score": 0,
"selected": false,
"text": "<p>My favourite solution is from MVP Daniel Vaughan:\n<a href=\"http://danielvaughan.org/posts/.net/wpf/2010/08/01/Enforcing-Single-Instance-WPF-Applications/\" rel=\"nofollow noreferrer\">Enforcing Single Instance Wpf Applications</a></p>\n<p>It use MemoryMappedFile to send command line arguments to the first instance:</p>\n<pre><code>/// <summary>\n/// This class allows restricting the number of executables in execution, to one.\n/// </summary>\npublic sealed class SingletonApplicationEnforcer\n{\n readonly Action<IEnumerable<string>> processArgsFunc;\n readonly string applicationId;\n Thread thread;\n string argDelimiter = "_;;_";\n\n /// <summary>\n /// Gets or sets the string that is used to join \n /// the string array of arguments in memory.\n /// </summary>\n /// <value>The arg delimeter.</value>\n public string ArgDelimeter\n {\n get\n {\n return argDelimiter;\n }\n set\n {\n argDelimiter = value;\n }\n }\n\n /// <summary>\n /// Initializes a new instance of the <see cref="SingletonApplicationEnforcer"/> class.\n /// </summary>\n /// <param name="processArgsFunc">A handler for processing command line args \n /// when they are received from another application instance.</param>\n /// <param name="applicationId">The application id used \n /// for naming the <seealso cref="EventWaitHandle"/>.</param>\n public SingletonApplicationEnforcer(Action<IEnumerable<string>> processArgsFunc, \n string applicationId = "DisciplesRock")\n {\n if (processArgsFunc == null)\n {\n throw new ArgumentNullException("processArgsFunc");\n }\n this.processArgsFunc = processArgsFunc;\n this.applicationId = applicationId;\n }\n\n /// <summary>\n /// Determines if this application instance is not the singleton instance.\n /// If this application is not the singleton, then it should exit.\n /// </summary>\n /// <returns><c>true</c> if the application should shutdown, \n /// otherwise <c>false</c>.</returns>\n public bool ShouldApplicationExit()\n {\n bool createdNew;\n string argsWaitHandleName = "ArgsWaitHandle_" + applicationId;\n string memoryFileName = "ArgFile_" + applicationId;\n\n EventWaitHandle argsWaitHandle = new EventWaitHandle(\n false, EventResetMode.AutoReset, argsWaitHandleName, out createdNew);\n\n GC.KeepAlive(argsWaitHandle);\n\n if (createdNew)\n {\n /* This is the main, or singleton application. \n * A thread is created to service the MemoryMappedFile. \n * We repeatedly examine this file each time the argsWaitHandle \n * is Set by a non-singleton application instance. */\n thread = new Thread(() =>\n {\n try\n {\n using (MemoryMappedFile file = MemoryMappedFile.CreateOrOpen(memoryFileName, 10000))\n {\n while (true)\n {\n argsWaitHandle.WaitOne();\n using (MemoryMappedViewStream stream = file.CreateViewStream())\n {\n var reader = new BinaryReader(stream);\n string args;\n try\n {\n args = reader.ReadString();\n }\n catch (Exception ex)\n {\n Debug.WriteLine("Unable to retrieve string. " + ex);\n continue;\n }\n string[] argsSplit = args.Split(new string[] { argDelimiter }, \n StringSplitOptions.RemoveEmptyEntries);\n processArgsFunc(argsSplit);\n }\n\n }\n }\n }\n catch (Exception ex)\n {\n Debug.WriteLine("Unable to monitor memory file. " + ex);\n }\n });\n\n thread.IsBackground = true;\n thread.Start();\n }\n else\n {\n /* Non singleton application instance. \n * Should exit, after passing command line args to singleton process, \n * via the MemoryMappedFile. */\n using (MemoryMappedFile mmf = MemoryMappedFile.OpenExisting(memoryFileName))\n {\n using (MemoryMappedViewStream stream = mmf.CreateViewStream())\n {\n var writer = new BinaryWriter(stream);\n string[] args = Environment.GetCommandLineArgs();\n string joined = string.Join(argDelimiter, args);\n writer.Write(joined);\n }\n }\n argsWaitHandle.Set();\n }\n\n return !createdNew;\n }\n}\n</code></pre>\n"
},
{
"answer_id": 68214933,
"author": "datchung",
"author_id": 4856020,
"author_profile": "https://Stackoverflow.com/users/4856020",
"pm_score": -1,
"selected": false,
"text": "<p>Based Matt Davis' answer, wrapped into a class for convenience.</p>\n<pre><code>public static class SingleAppInstanceChecker\n{\n /// <summary>\n /// Arbitrary unique string\n /// </summary>\n private static Mutex _mutex = new Mutex(true, "0d12ad74-026f-40c3-bdae-e178ddee8602");\n\n public static bool IsNotRunning()\n {\n return _mutex.WaitOne(TimeSpan.Zero, true);\n }\n}\n</code></pre>\n<p>Example usage:</p>\n<pre><code>private void Application_Startup(object sender, StartupEventArgs e)\n{\n if (!SingleAppInstanceChecker.IsNotRunning())\n {\n MessageBox.Show("Application is already running.");\n\n // Exit application using:\n // Environment.Exit(1);\n // Application.Current.Shutdown();\n // Etc...\n\n return;\n }\n \n // Allow startup and continue with normal processing\n // ...\n}\n</code></pre>\n"
},
{
"answer_id": 72174023,
"author": "Hanabi",
"author_id": 14700529,
"author_profile": "https://Stackoverflow.com/users/14700529",
"pm_score": 0,
"selected": false,
"text": "<p>Here is my entire <code>App.xaml.cs</code>, this code also brings the launched program instance to the foreground:</p>\n<pre class=\"lang-cs prettyprint-override\"><code>public partial class App : Application\n{\n private static Mutex _mutex = null;\n\n [DllImport("user32.dll")]\n static extern bool SetForegroundWindow(IntPtr hWnd);\n\n [DllImport("user32.dll")]\n static extern bool ShowWindow(IntPtr hWnd, int nCmdShow);\n\n protected override void OnStartup(StartupEventArgs e)\n {\n _mutex = new Mutex(true, "YourMutexName", out var createdNew);\n\n if (!createdNew)\n {\n using (var currentProcess = Process.GetCurrentProcess())\n {\n foreach (var process in Process.GetProcessesByName(currentProcess.ProcessName))\n {\n if (process.Id != currentProcess.Id)\n {\n ShowWindow(process.MainWindowHandle, 9);\n SetForegroundWindow(process.MainWindowHandle);\n }\n process.Dispose();\n }\n }\n // app is already running! Exiting the application \n Shutdown();\n }\n\n base.OnStartup(e);\n }\n\n protected override void OnExit(ExitEventArgs e)\n {\n _mutex.Dispose();\n base.OnExit(e);\n }\n}\n</code></pre>\n"
}
] | 2008/08/21 | [
"https://Stackoverflow.com/questions/19147",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/483/"
] | Using C# and WPF under .NET (rather than [Windows Forms](http://en.wikipedia.org/wiki/Windows_Forms) or console), what is the correct way to create an application that can only be run as a single instance?
I know it has something to do with some mythical thing called a mutex, rarely can I find someone that bothers to stop and explain what one of these are.
The code needs to also inform the already-running instance that the user tried to start a second one, and maybe also pass any command-line arguments if any existed. | Here is a very good [article](http://sanity-free.org/143/csharp_dotnet_single_instance_application.html) regarding the Mutex solution. The approach described by the article is advantageous for two reasons.
First, it does not require a dependency on the Microsoft.VisualBasic assembly. If my project already had a dependency on that assembly, I would probably advocate using the approach [shown in another answer](https://stackoverflow.com/a/19326/3195477). But as it is, I do not use the Microsoft.VisualBasic assembly, and I'd rather not add an unnecessary dependency to my project.
Second, the article shows how to bring the existing instance of the application to the foreground when the user tries to start another instance. That's a very nice touch that the other Mutex solutions described here do not address.
---
### UPDATE
As of 8/1/2014, the article I linked to above is still active, but the blog hasn't been updated in a while. That makes me worry that eventually it might disappear, and with it, the advocated solution. I'm reproducing the content of the article here for posterity. The words belong solely to the blog owner at [Sanity Free Coding](http://sanity-free.org/).
>
> Today I wanted to refactor some code that prohibited my application
> from running multiple instances of itself.
>
>
> Previously I had use [System.Diagnostics.Process](http://msdn.microsoft.com/en-us/library/system.diagnostics.process(v=vs.110).aspx) to search for an
> instance of my myapp.exe in the process list. While this works, it
> brings on a lot of overhead, and I wanted something cleaner.
>
>
> Knowing that I could use a mutex for this (but never having done it
> before) I set out to cut down my code and simplify my life.
>
>
> In the class of my application main I created a static named [Mutex](http://msdn.microsoft.com/en-us/library/system.threading.mutex(v=vs.110).aspx):
>
>
>
```
static class Program
{
static Mutex mutex = new Mutex(true, "{8F6F0AC4-B9A1-45fd-A8CF-72F04E6BDE8F}");
[STAThread]
...
}
```
>
> Having a named mutex allows us to stack synchronization across
> multiple threads and processes which is just the magic I'm looking
> for.
>
>
> [Mutex.WaitOne](http://msdn.microsoft.com/en-us/library/58195swd(v=vs.110).aspx) has an overload that specifies an amount of time for us
> to wait. Since we're not actually wanting to synchronizing our code
> (more just check if it is currently in use) we use the overload with
> two parameters: [Mutex.WaitOne(Timespan timeout, bool exitContext)](http://msdn.microsoft.com/en-us/library/85bbbxt9(v=vs.110).aspx).
> Wait one returns true if it is able to enter, and false if it wasn't.
> In this case, we don't want to wait at all; If our mutex is being
> used, skip it, and move on, so we pass in TimeSpan.Zero (wait 0
> milliseconds), and set the exitContext to true so we can exit the
> synchronization context before we try to aquire a lock on it. Using
> this, we wrap our Application.Run code inside something like this:
>
>
>
```
static class Program
{
static Mutex mutex = new Mutex(true, "{8F6F0AC4-B9A1-45fd-A8CF-72F04E6BDE8F}");
[STAThread]
static void Main() {
if(mutex.WaitOne(TimeSpan.Zero, true)) {
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
Application.Run(new Form1());
mutex.ReleaseMutex();
} else {
MessageBox.Show("only one instance at a time");
}
}
}
```
>
> So, if our app is running, WaitOne will return false, and we'll get a
> message box.
>
>
> Instead of showing a message box, I opted to utilize a little Win32 to
> notify my running instance that someone forgot that it was already
> running (by bringing itself to the top of all the other windows). To
> achieve this I used [PostMessage](http://msdn.microsoft.com/en-us/library/windows/desktop/ms644944(v=vs.85).aspx) to broadcast a custom message to every
> window (the custom message was registered with [RegisterWindowMessage](http://msdn.microsoft.com/en-us/library/windows/desktop/ms644947(v=vs.85).aspx)
> by my running application, which means only my application knows what
> it is) then my second instance exits. The running application instance
> would receive that notification and process it. In order to do that, I
> overrode [WndProc](http://msdn.microsoft.com/en-us/library/system.windows.forms.form.wndproc(v=vs.110).aspx) in my main form and listened for my custom
> notification. When I received that notification I set the form's
> TopMost property to true to bring it up on top.
>
>
> Here is what I ended up with:
>
>
> * Program.cs
>
>
>
```
static class Program
{
static Mutex mutex = new Mutex(true, "{8F6F0AC4-B9A1-45fd-A8CF-72F04E6BDE8F}");
[STAThread]
static void Main() {
if(mutex.WaitOne(TimeSpan.Zero, true)) {
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
Application.Run(new Form1());
mutex.ReleaseMutex();
} else {
// send our Win32 message to make the currently running instance
// jump on top of all the other windows
NativeMethods.PostMessage(
(IntPtr)NativeMethods.HWND_BROADCAST,
NativeMethods.WM_SHOWME,
IntPtr.Zero,
IntPtr.Zero);
}
}
}
```
>
> * NativeMethods.cs
>
>
>
```
// this class just wraps some Win32 stuff that we're going to use
internal class NativeMethods
{
public const int HWND_BROADCAST = 0xffff;
public static readonly int WM_SHOWME = RegisterWindowMessage("WM_SHOWME");
[DllImport("user32")]
public static extern bool PostMessage(IntPtr hwnd, int msg, IntPtr wparam, IntPtr lparam);
[DllImport("user32")]
public static extern int RegisterWindowMessage(string message);
}
```
>
> * Form1.cs (front side partial)
>
>
>
```
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
protected override void WndProc(ref Message m)
{
if(m.Msg == NativeMethods.WM_SHOWME) {
ShowMe();
}
base.WndProc(ref m);
}
private void ShowMe()
{
if(WindowState == FormWindowState.Minimized) {
WindowState = FormWindowState.Normal;
}
// get our current "TopMost" value (ours will always be false though)
bool top = TopMost;
// make our form jump to the top of everything
TopMost = true;
// set it back to whatever it was
TopMost = top;
}
}
``` |
19,151 | <p>How would one create an iterative function (or iterator object) in python?</p>
| [
{
"answer_id": 19152,
"author": "akdom",
"author_id": 145,
"author_profile": "https://Stackoverflow.com/users/145",
"pm_score": 7,
"selected": false,
"text": "<p>First of all the <a href=\"https://docs.python.org/3/library/itertools.html\" rel=\"noreferrer\">itertools module</a> is incredibly useful for all sorts of cases in which an iterator would be useful, but here is all you need to create an iterator in python:</p>\n\n<blockquote>\n <p>yield</p>\n</blockquote>\n\n<p>Isn't that cool? Yield can be used to replace a normal <strong>return</strong> in a function. It returns the object just the same, but instead of destroying state and exiting, it saves state for when you want to execute the next iteration. Here is an example of it in action pulled directly from the <a href=\"http://docs.python.org/lib/itertools-functions.html\" rel=\"noreferrer\">itertools function list</a>:</p>\n\n<pre><code>def count(n=0):\n while True:\n yield n\n n += 1\n</code></pre>\n\n<p>As stated in the functions description (it's the <strong>count()</strong> function from the itertools module...) , it produces an iterator that returns consecutive integers starting with n.</p>\n\n<p><a href=\"https://docs.python.org/2/reference/expressions.html#generator-expressions\" rel=\"noreferrer\">Generator expressions</a> are a whole other can of worms (awesome worms!). They may be used in place of a <a href=\"http://www.secnetix.de/olli/Python/list_comprehensions.hawk\" rel=\"noreferrer\">List Comprehension</a> to save memory (list comprehensions create a list in memory that is destroyed after use if not assigned to a variable, but generator expressions can create a Generator Object... which is a fancy way of saying Iterator). Here is an example of a generator expression definition:</p>\n\n<pre><code>gen = (n for n in xrange(0,11))\n</code></pre>\n\n<p>This is very similar to our iterator definition above except the full range is predetermined to be between 0 and 10.</p>\n\n<p>I just found <strong>xrange()</strong> (suprised I hadn't seen it before...) and added it to the above example. <strong>xrange()</strong> is an iterable version of <strong>range()</strong> which has the advantage of not prebuilding the list. It would be very useful if you had a giant corpus of data to iterate over and only had so much memory to do it in.</p>\n"
},
{
"answer_id": 24377,
"author": "ars",
"author_id": 2611,
"author_profile": "https://Stackoverflow.com/users/2611",
"pm_score": 11,
"selected": true,
"text": "<p>Iterator objects in python conform to the iterator protocol, which basically means they provide two methods: <code>__iter__()</code> and <code>__next__()</code>. </p>\n\n<ul>\n<li><p>The <code>__iter__</code> returns the iterator object and is implicitly called\nat the start of loops.</p></li>\n<li><p>The <code>__next__()</code> method returns the next value and is implicitly called at each loop increment. This method raises a StopIteration exception when there are no more value to return, which is implicitly captured by looping constructs to stop iterating.</p></li>\n</ul>\n\n<p>Here's a simple example of a counter:</p>\n\n<pre><code>class Counter:\n def __init__(self, low, high):\n self.current = low - 1\n self.high = high\n\n def __iter__(self):\n return self\n\n def __next__(self): # Python 2: def next(self)\n self.current += 1\n if self.current < self.high:\n return self.current\n raise StopIteration\n\n\nfor c in Counter(3, 9):\n print(c)\n</code></pre>\n\n<p>This will print:</p>\n\n<pre><code>3\n4\n5\n6\n7\n8\n</code></pre>\n\n<p>This is easier to write using a generator, as covered in a previous answer:</p>\n\n<pre><code>def counter(low, high):\n current = low\n while current < high:\n yield current\n current += 1\n\nfor c in counter(3, 9):\n print(c)\n</code></pre>\n\n<p>The printed output will be the same. Under the hood, the generator object supports the iterator protocol and does something roughly similar to the class Counter.</p>\n\n<p>David Mertz's article, <a href=\"https://www.ibm.com/developerworks/library/l-pycon/\" rel=\"noreferrer\">Iterators and Simple Generators</a>, is a pretty good introduction. </p>\n"
},
{
"answer_id": 7542261,
"author": "Ethan Furman",
"author_id": 208880,
"author_profile": "https://Stackoverflow.com/users/208880",
"pm_score": 9,
"selected": false,
"text": "<p>There are four ways to build an iterative function:</p>\n\n<ul>\n<li>create a generator (uses the <a href=\"http://docs.python.org/py3k/reference/expressions.html#yield-expressions\" rel=\"noreferrer\">yield keyword</a>)</li>\n<li>use a generator expression (<a href=\"http://docs.python.org/py3k/reference/expressions.html#generator-expressions\" rel=\"noreferrer\">genexp</a>)</li>\n<li>create an iterator (defines <a href=\"http://docs.python.org/py3k/library/stdtypes.html?highlight=__iter__#iterator-types\" rel=\"noreferrer\"><code>__iter__</code> and <code>__next__</code></a> (or <code>next</code> in Python 2.x))</li>\n<li>create a class that Python can iterate over on its own (<a href=\"http://docs.python.org/py3k/reference/datamodel.html?highlight=__getitem__#object.__getitem__\" rel=\"noreferrer\">defines <code>__getitem__</code></a>)</li>\n</ul>\n\n<p>Examples:</p>\n\n<pre><code># generator\ndef uc_gen(text):\n for char in text.upper():\n yield char\n\n# generator expression\ndef uc_genexp(text):\n return (char for char in text.upper())\n\n# iterator protocol\nclass uc_iter():\n def __init__(self, text):\n self.text = text.upper()\n self.index = 0\n def __iter__(self):\n return self\n def __next__(self):\n try:\n result = self.text[self.index]\n except IndexError:\n raise StopIteration\n self.index += 1\n return result\n\n# getitem method\nclass uc_getitem():\n def __init__(self, text):\n self.text = text.upper()\n def __getitem__(self, index):\n return self.text[index]\n</code></pre>\n\n<p>To see all four methods in action:</p>\n\n<pre><code>for iterator in uc_gen, uc_genexp, uc_iter, uc_getitem:\n for ch in iterator('abcde'):\n print(ch, end=' ')\n print()\n</code></pre>\n\n<p>Which results in:</p>\n\n<pre><code>A B C D E\nA B C D E\nA B C D E\nA B C D E\n</code></pre>\n\n<p><strong>Note</strong>:</p>\n\n<p>The two generator types (<code>uc_gen</code> and <code>uc_genexp</code>) cannot be <code>reversed()</code>; the plain iterator (<code>uc_iter</code>) would need the <code>__reversed__</code> magic method (which, <a href=\"https://docs.python.org/3/reference/datamodel.html#object.__reversed__\" rel=\"noreferrer\">according to the docs</a>, must return a new iterator, but returning <code>self</code> works (at least in CPython)); and the getitem iteratable (<code>uc_getitem</code>) must have the <code>__len__</code> magic method:</p>\n\n<pre><code> # for uc_iter we add __reversed__ and update __next__\n def __reversed__(self):\n self.index = -1\n return self\n def __next__(self):\n try:\n result = self.text[self.index]\n except IndexError:\n raise StopIteration\n self.index += -1 if self.index < 0 else +1\n return result\n\n # for uc_getitem\n def __len__(self)\n return len(self.text)\n</code></pre>\n\n<hr>\n\n<p>To answer Colonel Panic's secondary question about an infinite lazily evaluated iterator, here are those examples, using each of the four methods above:</p>\n\n<pre><code># generator\ndef even_gen():\n result = 0\n while True:\n yield result\n result += 2\n\n\n# generator expression\ndef even_genexp():\n return (num for num in even_gen()) # or even_iter or even_getitem\n # not much value under these circumstances\n\n# iterator protocol\nclass even_iter():\n def __init__(self):\n self.value = 0\n def __iter__(self):\n return self\n def __next__(self):\n next_value = self.value\n self.value += 2\n return next_value\n\n# getitem method\nclass even_getitem():\n def __getitem__(self, index):\n return index * 2\n\nimport random\nfor iterator in even_gen, even_genexp, even_iter, even_getitem:\n limit = random.randint(15, 30)\n count = 0\n for even in iterator():\n print even,\n count += 1\n if count >= limit:\n break\n print\n</code></pre>\n\n<p>Which results in (at least for my sample run):</p>\n\n<pre><code>0 2 4 6 8 10 12 14 16 18 20 22 24 26 28 30 32 34 36 38 40 42 44 46 48 50 52 54\n0 2 4 6 8 10 12 14 16 18 20 22 24 26 28 30 32 34 36 38\n0 2 4 6 8 10 12 14 16 18 20 22 24 26 28 30\n0 2 4 6 8 10 12 14 16 18 20 22 24 26 28 30 32\n</code></pre>\n\n<hr>\n\n<p>How to choose which one to use? This is mostly a matter of taste. The two methods I see most often are generators and the iterator protocol, as well as a hybrid (<code>__iter__</code> returning a generator).</p>\n\n<p>Generator expressions are useful for replacing list comprehensions (they are lazy and so can save on resources).</p>\n\n<p>If one needs compatibility with earlier Python 2.x versions use <code>__getitem__</code>.</p>\n"
},
{
"answer_id": 11690539,
"author": "Manux",
"author_id": 319926,
"author_profile": "https://Stackoverflow.com/users/319926",
"pm_score": 7,
"selected": false,
"text": "<p>I see some of you doing <code>return self</code> in <code>__iter__</code>. I just wanted to note that <code>__iter__</code> itself can be a generator (thus removing the need for <code>__next__</code> and raising <code>StopIteration</code> exceptions)</p>\n\n<pre><code>class range:\n def __init__(self,a,b):\n self.a = a\n self.b = b\n def __iter__(self):\n i = self.a\n while i < self.b:\n yield i\n i+=1\n</code></pre>\n\n<p>Of course here one might as well directly make a generator, but for more complex classes it can be useful.</p>\n"
},
{
"answer_id": 35779493,
"author": "Nizam Mohamed",
"author_id": 4522780,
"author_profile": "https://Stackoverflow.com/users/4522780",
"pm_score": 2,
"selected": false,
"text": "<p>This is an iterable function without <code>yield</code>. It make use of the <code>iter</code> function and a closure which keeps it's state in a mutable (<code>list</code>) in the enclosing scope for python 2. </p>\n\n<pre><code>def count(low, high):\n counter = [0]\n def tmp():\n val = low + counter[0]\n if val < high:\n counter[0] += 1\n return val\n return None\n return iter(tmp, None)\n</code></pre>\n\n<p>For Python 3, closure state is kept in an immutable in the enclosing scope and <code>nonlocal</code> is used in local scope to update the state variable. </p>\n\n<pre><code>def count(low, high):\n counter = 0\n def tmp():\n nonlocal counter\n val = low + counter\n if val < high:\n counter += 1\n return val\n return None\n return iter(tmp, None) \n</code></pre>\n\n<p>Test;</p>\n\n<pre><code>for i in count(1,10):\n print(i)\n1\n2\n3\n4\n5\n6\n7\n8\n9\n</code></pre>\n"
},
{
"answer_id": 36138037,
"author": "aq2",
"author_id": 5806943,
"author_profile": "https://Stackoverflow.com/users/5806943",
"pm_score": 4,
"selected": false,
"text": "<p>This question is about iterable objects, not about iterators. In Python, sequences are iterable too so one way to make an iterable class is to make it behave like a sequence, i.e. give it <code>__getitem__</code> and <code>__len__</code> methods. I have tested this on Python 2 and 3.</p>\n\n<pre><code>class CustomRange:\n\n def __init__(self, low, high):\n self.low = low\n self.high = high\n\n def __getitem__(self, item):\n if item >= len(self):\n raise IndexError(\"CustomRange index out of range\")\n return self.low + item\n\n def __len__(self):\n return self.high - self.low\n\n\ncr = CustomRange(0, 10)\nfor i in cr:\n print(i)\n</code></pre>\n"
},
{
"answer_id": 50038486,
"author": "Daniil Mashkin",
"author_id": 2207154,
"author_profile": "https://Stackoverflow.com/users/2207154",
"pm_score": 3,
"selected": false,
"text": "<p>If you looking for something short and simple, maybe it will be enough for you:</p>\n\n<pre><code>class A(object):\n def __init__(self, l):\n self.data = l\n\n def __iter__(self):\n return iter(self.data)\n</code></pre>\n\n<p>example of usage:</p>\n\n<pre><code>In [3]: a = A([2,3,4])\n\nIn [4]: [i for i in a]\nOut[4]: [2, 3, 4]\n</code></pre>\n"
},
{
"answer_id": 51836944,
"author": "John Strood",
"author_id": 5337834,
"author_profile": "https://Stackoverflow.com/users/5337834",
"pm_score": 3,
"selected": false,
"text": "<p>All answers on this page are really great for a complex object. But for those containing builtin iterable types as attributes, like <code>str</code>, <code>list</code>, <code>set</code> or <code>dict</code>, or any implementation of <code>collections.Iterable</code>, you can omit certain things in your class.</p>\n\n<pre><code>class Test(object):\n def __init__(self, string):\n self.string = string\n\n def __iter__(self):\n # since your string is already iterable\n return (ch for ch in self.string)\n # or simply\n return self.string.__iter__()\n # also\n return iter(self.string)\n</code></pre>\n\n<p>It can be used like:</p>\n\n<pre><code>for x in Test(\"abcde\"):\n print(x)\n\n# prints\n# a\n# b\n# c\n# d\n# e\n</code></pre>\n"
},
{
"answer_id": 63337271,
"author": "Sreevatsan",
"author_id": 13093094,
"author_profile": "https://Stackoverflow.com/users/13093094",
"pm_score": 2,
"selected": false,
"text": "<p>Include the following code in your class code.</p>\n<pre><code> def __iter__(self):\n for x in self.iterable:\n yield x\n</code></pre>\n<p><strong>Make sure that you replace <code>self.iterable</code>with the iterable which you iterate through.</strong></p>\n<p><em>Here's an example code</em></p>\n<pre><code>class someClass:\n def __init__(self,list):\n self.list = list\n def __iter__(self):\n for x in self.list:\n yield x\n\n\nvar = someClass([1,2,3,4,5])\nfor num in var: \n print(num) \n</code></pre>\n<p>Output</p>\n<pre><code>1\n2\n3\n4\n5\n</code></pre>\n<p><strong>Note: Since strings are also iterable, they can also be used as an argument for the class</strong></p>\n<pre><code>foo = someClass("Python")\nfor x in foo:\n print(x)\n</code></pre>\n<p>Output</p>\n<pre><code>P\ny\nt\nh\no\nn\n</code></pre>\n"
},
{
"answer_id": 71498451,
"author": "Muhammad Yasirroni",
"author_id": 11671779,
"author_profile": "https://Stackoverflow.com/users/11671779",
"pm_score": 1,
"selected": false,
"text": "<blockquote>\n<pre class=\"lang-py prettyprint-override\"><code>class uc_iter():\n def __init__(self):\n self.value = 0\n def __iter__(self):\n return self\n def __next__(self):\n next_value = self.value\n self.value += 2\n return next_value\n</code></pre>\n</blockquote>\n<p>Improving previous <a href=\"https://stackoverflow.com/a/7542261/11671779\">answer</a>, one of the advantage of using <code>class</code> is that you can add <code>__call__</code> to return <code>self.value</code> or even <code>next_value</code>.</p>\n<pre class=\"lang-py prettyprint-override\"><code>class uc_iter():\n def __init__(self):\n self.value = 0\n def __iter__(self):\n return self\n def __next__(self):\n next_value = self.value\n self.value += 2\n return next_value\n def __call__(self):\n next_value = self.value\n self.value += 2\n return next_value\n</code></pre>\n<pre class=\"lang-py prettyprint-override\"><code>c = uc_iter()\nprint([c() for _ in range(10)])\nprint([next(c) for _ in range(5)])\n# [0, 2, 4, 6, 8, 10, 12, 14, 16, 18]\n# [20, 22, 24, 26, 28]\n</code></pre>\n<hr />\n<p>Other example of a class based on Python Random that can be both called and iterated could be seen on my implementation <a href=\"https://github.com/yasirroni/fakertype/blob/main/fakertype/generator.py\" rel=\"nofollow noreferrer\">here</a></p>\n"
}
] | 2008/08/21 | [
"https://Stackoverflow.com/questions/19151",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/145/"
] | How would one create an iterative function (or iterator object) in python? | Iterator objects in python conform to the iterator protocol, which basically means they provide two methods: `__iter__()` and `__next__()`.
* The `__iter__` returns the iterator object and is implicitly called
at the start of loops.
* The `__next__()` method returns the next value and is implicitly called at each loop increment. This method raises a StopIteration exception when there are no more value to return, which is implicitly captured by looping constructs to stop iterating.
Here's a simple example of a counter:
```
class Counter:
def __init__(self, low, high):
self.current = low - 1
self.high = high
def __iter__(self):
return self
def __next__(self): # Python 2: def next(self)
self.current += 1
if self.current < self.high:
return self.current
raise StopIteration
for c in Counter(3, 9):
print(c)
```
This will print:
```
3
4
5
6
7
8
```
This is easier to write using a generator, as covered in a previous answer:
```
def counter(low, high):
current = low
while current < high:
yield current
current += 1
for c in counter(3, 9):
print(c)
```
The printed output will be the same. Under the hood, the generator object supports the iterator protocol and does something roughly similar to the class Counter.
David Mertz's article, [Iterators and Simple Generators](https://www.ibm.com/developerworks/library/l-pycon/), is a pretty good introduction. |
19,185 | <p>There is some documentation on the internet that shows that Windows changes the behavior of the NotifyIcon.BalloonTipShown command if the user is currently idle and this is <a href="http://forums.microsoft.com/MSDN/ShowPost.aspx?PostID=343411&SiteID=1" rel="nofollow noreferrer">detected by checking for keyboard and mouse events</a>. I am currently working on an application that spends most of its time in the system tray, but pop-ups up multiple balloon tips from time to time and I would like to prevent the user from missing any of them if they are currently away from the system. Since any currently displayed balloon tips are destroyed if a new one is displayed, I want to hold off on displaying them if the user is away.</p>
<p>As such, is there any way to check to see if the user is currently idle if the application is minimized to the system tray?</p>
| [
{
"answer_id": 19187,
"author": "lubos hasko",
"author_id": 275,
"author_profile": "https://Stackoverflow.com/users/275",
"pm_score": 1,
"selected": false,
"text": "<p><strong>Managed code</strong></p>\n\n<p>Check position of the mouse every second. If there are new messages for user, hold on to them until you detect any move with the mouse.</p>\n\n<p><strong>Unmanaged code</strong></p>\n\n<p>See <a href=\"http://weblogs.asp.net/jdanforth/archive/2006/06/21/454219.aspx\" rel=\"nofollow noreferrer\">Detecting Idle Time with Mouse and Keyboard Hooks</a></p>\n"
},
{
"answer_id": 19188,
"author": "Mark Cidade",
"author_id": 1659,
"author_profile": "https://Stackoverflow.com/users/1659",
"pm_score": 3,
"selected": true,
"text": "<p>How about the Win32 <a href=\"http://www.codeproject.com/KB/cs/GetIdleTimeWithCS.aspx\" rel=\"nofollow noreferrer\">LASTINPUTINFO</a> function?</p>\n\n<pre><code>using System.Runtime.InteropServices;\n\n[DllImport(\"User32.dll\")] \nstatic extern bool GetLastInputInfo(ref LASTINPUTINFO plii);\n\nstruct LASTINPUTINFO \n{\n public uint cbSize;\n public uint dwTime;\n}\n</code></pre>\n"
},
{
"answer_id": 20002,
"author": "rjzii",
"author_id": 1185,
"author_profile": "https://Stackoverflow.com/users/1185",
"pm_score": 0,
"selected": false,
"text": "<p>Thanks for the responses, I ended up going with the GetLastInputInfo function as it is pretty straight forward to implement in the application I'm working on.</p>\n"
}
] | 2008/08/21 | [
"https://Stackoverflow.com/questions/19185",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1185/"
] | There is some documentation on the internet that shows that Windows changes the behavior of the NotifyIcon.BalloonTipShown command if the user is currently idle and this is [detected by checking for keyboard and mouse events](http://forums.microsoft.com/MSDN/ShowPost.aspx?PostID=343411&SiteID=1). I am currently working on an application that spends most of its time in the system tray, but pop-ups up multiple balloon tips from time to time and I would like to prevent the user from missing any of them if they are currently away from the system. Since any currently displayed balloon tips are destroyed if a new one is displayed, I want to hold off on displaying them if the user is away.
As such, is there any way to check to see if the user is currently idle if the application is minimized to the system tray? | How about the Win32 [LASTINPUTINFO](http://www.codeproject.com/KB/cs/GetIdleTimeWithCS.aspx) function?
```
using System.Runtime.InteropServices;
[DllImport("User32.dll")]
static extern bool GetLastInputInfo(ref LASTINPUTINFO plii);
struct LASTINPUTINFO
{
public uint cbSize;
public uint dwTime;
}
``` |
19,193 | <p>How do I make a tree data structure in C++ that uses iterators instead of pointers? I couldn't find anything in the STL that can do this. What I would like to do is to be able to create and manipulate trees like this:</p>
<pre><code>#include <iostream>
#include <tree>
using namespace std;
int main()
{
tree<int> myTree;
tree<int>::iterator i = myTree.root();
*i = 42;
tree<int>::iterator j = i.add_child();
*j = 777;
j = j.parent();
if (i == myTree.root() && i == j) cout << "i and j are both pointing to the root\n";
return 0;
}
</code></pre>
<hr>
<p>Thank you, tree.hh seems to be just what I was looking for.</p>
<blockquote>
<p>If this is for gaining the benefit of
a data-structure holding arbitrary
index types, optimized for searching
and good at insertion then consider
using a map.</p>
<p>A map is an associative container that
has performance guarantees identical
to those of a tree: logarithmic
searching, logarithmic insertion,
logarithmic deletion, linear space.
Internally they are often implemented
as red-black trees, although that is
not a guarantee. Still, as an STL user
all you should care about is the
performance guarantees of the STL
algorithms and data-structures.
Whether they're implemented as trees
or little green men shouldn't matter
to you.</p>
</blockquote>
<p>I'm not sure if a map is what I need, but thanks for the info. I will remember to use maps whenever possible instead of implementing trees.</p>
| [
{
"answer_id": 19204,
"author": "wilhelmtell",
"author_id": 456,
"author_profile": "https://Stackoverflow.com/users/456",
"pm_score": 2,
"selected": false,
"text": "<p>Why would you want to do that? If this is for learning purposes then you can write your own tree data structure. If this is for gaining the benefit of a data-structure holding arbitrary index types, optimized for searching and good at insertion then consider using a map.</p>\n\n<p>A map is an associative container that has performance guarantees identical to those of a tree: logarithmic searching, logarithmic insertion, logarithmic deletion, linear space. Internally they are often implemented as red-black trees, although that is not a guarantee. Still, as an STL user all you should care about is the performance guarantees of the STL algorithms and data-structures. Whether they're implemented as trees or little green men shouldn't matter to you.</p>\n\n<p>As a side note, there's no such thing as a root() function. All STL containers have the begin() function implementing the conceptual beginning of a container. The kind of iterator returned by that function depends on the characteristics of the container.</p>\n"
},
{
"answer_id": 19255,
"author": "fulmicoton",
"author_id": 446497,
"author_profile": "https://Stackoverflow.com/users/446497",
"pm_score": 4,
"selected": true,
"text": "<p>Here is <a href=\"http://www.aei.mpg.de/~peekas/tree/\" rel=\"noreferrer\">tree.hh</a> which is a bit close to what you want to do, though a bit\ndifferent.</p>\n\n<p>Here is a piece of code extracted from its website.</p>\n\n<pre><code>int main(int, char **)\n {\n tree<string> tr;\n tree<string>::iterator top, one, two, loc, banana;\n\n top=tr.begin();\n one=tr.insert(top, \"one\");\n two=tr.append_child(one, \"two\");\n tr.append_child(two, \"apple\");\n banana=tr.append_child(two, \"banana\");\n tr.append_child(banana,\"cherry\");\n tr.append_child(two, \"peach\");\n tr.append_child(one,\"three\");\n\n loc=find(tr.begin(), tr.end(), \"two\");\n if(loc!=tr.end()) {\n tree<string>::sibling_iterator sib=tr.begin(loc);\n while(sib!=tr.end(loc)) {\n cout << (*sib) << endl;\n ++sib;\n }\n cout << endl;\n tree<string>::iterator sib2=tr.begin(loc);\n tree<string>::iterator end2=tr.end(loc);\n while(sib2!=end2) {\n for(int i=0; i<tr.depth(sib2)-2; ++i) \n cout << \" \";\n cout << (*sib2) << endl;\n ++sib2;\n }\n }\n }\n</code></pre>\n\n<p>Now what's different? Your implementation is simpler when it comes to \nappend a node to the tree. \nThough your version is indiscutably simpler, the dev of this lib probably wanted to have some info accessible without browsing the tree, such as the size of the tree for instance.</p>\n\n<p>I also assume he didn't want to store the root on all nodes for performance reason.\nSo if you want to implement it your way, I suggest you keep most of the logic and add the link to the parent tree in the iterator and rewrite append a bit.</p>\n"
}
] | 2008/08/21 | [
"https://Stackoverflow.com/questions/19193",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2222/"
] | How do I make a tree data structure in C++ that uses iterators instead of pointers? I couldn't find anything in the STL that can do this. What I would like to do is to be able to create and manipulate trees like this:
```
#include <iostream>
#include <tree>
using namespace std;
int main()
{
tree<int> myTree;
tree<int>::iterator i = myTree.root();
*i = 42;
tree<int>::iterator j = i.add_child();
*j = 777;
j = j.parent();
if (i == myTree.root() && i == j) cout << "i and j are both pointing to the root\n";
return 0;
}
```
---
Thank you, tree.hh seems to be just what I was looking for.
>
> If this is for gaining the benefit of
> a data-structure holding arbitrary
> index types, optimized for searching
> and good at insertion then consider
> using a map.
>
>
> A map is an associative container that
> has performance guarantees identical
> to those of a tree: logarithmic
> searching, logarithmic insertion,
> logarithmic deletion, linear space.
> Internally they are often implemented
> as red-black trees, although that is
> not a guarantee. Still, as an STL user
> all you should care about is the
> performance guarantees of the STL
> algorithms and data-structures.
> Whether they're implemented as trees
> or little green men shouldn't matter
> to you.
>
>
>
I'm not sure if a map is what I need, but thanks for the info. I will remember to use maps whenever possible instead of implementing trees. | Here is [tree.hh](http://www.aei.mpg.de/~peekas/tree/) which is a bit close to what you want to do, though a bit
different.
Here is a piece of code extracted from its website.
```
int main(int, char **)
{
tree<string> tr;
tree<string>::iterator top, one, two, loc, banana;
top=tr.begin();
one=tr.insert(top, "one");
two=tr.append_child(one, "two");
tr.append_child(two, "apple");
banana=tr.append_child(two, "banana");
tr.append_child(banana,"cherry");
tr.append_child(two, "peach");
tr.append_child(one,"three");
loc=find(tr.begin(), tr.end(), "two");
if(loc!=tr.end()) {
tree<string>::sibling_iterator sib=tr.begin(loc);
while(sib!=tr.end(loc)) {
cout << (*sib) << endl;
++sib;
}
cout << endl;
tree<string>::iterator sib2=tr.begin(loc);
tree<string>::iterator end2=tr.end(loc);
while(sib2!=end2) {
for(int i=0; i<tr.depth(sib2)-2; ++i)
cout << " ";
cout << (*sib2) << endl;
++sib2;
}
}
}
```
Now what's different? Your implementation is simpler when it comes to
append a node to the tree.
Though your version is indiscutably simpler, the dev of this lib probably wanted to have some info accessible without browsing the tree, such as the size of the tree for instance.
I also assume he didn't want to store the root on all nodes for performance reason.
So if you want to implement it your way, I suggest you keep most of the logic and add the link to the parent tree in the iterator and rewrite append a bit. |
19,236 | <p>I'm working on a internal web based tool for my company. Part of this tool is another application (The Cruise Control Dashboard) that runs in its own Virtual Directory under my root application.</p>
<p>I wanted to limit access to this internal application by setting up Forms Authentication on it, and having a login form in the root application.</p>
<p>I put the following into the root applications web.config:</p>
<pre><code><location path="ccnet">
<system.web>
<authentication mode="Forms">
<forms loginUrl="/default.aspx" timeout="5000"/>
</authentication>
<authorization>
<allow users="?"/>
<deny users="?"/>
</authorization>
</system.web>
</location>
</code></pre>
<p>However, the Forms Authentication does not appear to be working, it does not redirect back to the login page when I access that application directly.</p>
<p>I have a feeling I have the <allow> and <deny> tags set wrong. Can someone clarify?</p>
| [
{
"answer_id": 19239,
"author": "Darren Kopp",
"author_id": 77,
"author_profile": "https://Stackoverflow.com/users/77",
"pm_score": 0,
"selected": false,
"text": "<p>you are allowing all unauthenticated. You might be looking for something like this</p>\n\n<pre><code><deny users=\"?\"/>\n</code></pre>\n"
},
{
"answer_id": 19253,
"author": "Mark Glorie",
"author_id": 952,
"author_profile": "https://Stackoverflow.com/users/952",
"pm_score": 0,
"selected": false,
"text": "<blockquote>\n <p>That does not work, it still allows all users, (Authenticated or not) to access. </p>\n</blockquote>\n\n<p>I would think you could even omit the allow tag, as it's redundant. Just:</p>\n\n<pre><code><deny users=\"?\"/>\n</code></pre>\n"
},
{
"answer_id": 19287,
"author": "David Wengier",
"author_id": 489,
"author_profile": "https://Stackoverflow.com/users/489",
"pm_score": 2,
"selected": false,
"text": "<p>FormsAuthentication encrypts the tokens that it gives to the user, and by default it encrypts keys different for each application. To get Forms Auth to work across applications, there are a couple of things you need to do:</p>\n\n<p>Firstly, set the Forms Auth \"name\" the same on all Applications. This is done with:</p>\n\n<pre><code><authentication mode=\"Forms\"> \n <forms name=\"{name}\" path=\"/\" ...>\n</authentication>\n</code></pre>\n\n<p>Set the \"name\" to be the same in both applications web.configs.</p>\n\n<p>Secondly, you need to tell both applications to use the same key when encrypting. This is a bit confusing. When I was setting this up, all I had to do was add the following to both web.configs:</p>\n\n<pre><code><machineKey validationKey=\"AutoGenerate\" decryptionKey=\"AutoGenerate\" validation=\"SHA1\" />\n</code></pre>\n\n<p>According to the docs, thats the default value, but it didnt work for me unless I specified it.</p>\n"
},
{
"answer_id": 19291,
"author": "Mark Glorie",
"author_id": 952,
"author_profile": "https://Stackoverflow.com/users/952",
"pm_score": 0,
"selected": false,
"text": "<p>Where does that code sit Jonathan? In my experience I have a login control and in the OnAuthenticate event I would set Authenticated to false... </p>\n\n<pre><code>If CustomAuthenticate(Login1.UserName, Login1.Password) Then\n FormsAuthentication.RedirectFromLoginPage(Login1.UserName, False)\nElse\n e.Authenticated = False\nEnd If\n</code></pre>\n\n<p>But that's using the <em>Microsoft Way</em> </p>\n"
},
{
"answer_id": 19309,
"author": "David Wengier",
"author_id": 489,
"author_profile": "https://Stackoverflow.com/users/489",
"pm_score": 2,
"selected": true,
"text": "<p>You might also need to put path=\"/\" in the <forms tag(s) I think. Sorry, its been a while since i've done this</p>\n"
},
{
"answer_id": 19316,
"author": "FlySwat",
"author_id": 1965,
"author_profile": "https://Stackoverflow.com/users/1965",
"pm_score": 3,
"selected": false,
"text": "<blockquote>\n <p>You might also need to put path=\"/\" in the \n</blockquote>\n\n<p>That was it!</p>\n\n<p>So, Summary, inorder todo this;</p>\n\n<p>In root web.config add:</p>\n\n<pre><code><machineKey validationKey=\"AutoGenerate\" decryptionKey=\"AutoGenerate\" validation=\"SHA1\" />\n</code></pre>\n\n<p>This must be done because by default it is \"AutoGenerate,IsolateApps\".</p>\n\n<p>Second, you must name the form Auth cookie the same in both, I did this all in my root, using the location tag:</p>\n\n<pre><code><authentication mode=\"Forms\">\n <forms name=\"ccAuth\" loginUrl=\"/default.aspx\" path=\"/\" timeout=\"5000\"/>\n</authentication>\n<authorization>\n <deny users=\"?\"/>\n</authorization>\n</code></pre>\n\n<p>Finally:</p>\n\n<pre><code><location path=\"ccnet\">\n <system.web>\n <authentication mode=\"Forms\">\n <forms name=\"ccAuth\" loginUrl=\"/default.aspx\" path=\"/\" timeout=\"5000\"/>\n </authentication>\n <authorization>\n <deny users=\"?\"/>\n </authorization> \n </system.web> \n</location>\n</code></pre>\n\n<p>Thanks everyone for your help. This was a stumper.</p>\n"
},
{
"answer_id": 326127,
"author": "MatthewMartin",
"author_id": 33264,
"author_profile": "https://Stackoverflow.com/users/33264",
"pm_score": 0,
"selected": false,
"text": "<p>What is the file extension for this cruise control application? If it is not a file type that ASP.NET is registered to handle (e.g. jsp, java, etc), then ASP.NET will not act as an authentication mechanism (on IIS 5 and 6). For example, for static html files, unless you have wildcard mapping implemented, IIS does all the authentication and authorization and serves up the file without involving the ASP.NET isapi extension. IIS7 can use the new integrated pipeline mode to intercept all requests. For IIS6, you'll want to look at <a href=\"http://weblogs.asp.net/scottgu/archive/2007/03/04/tip-trick-integrating-asp-net-security-with-classic-asp-and-non-asp-net-urls.aspx\" rel=\"nofollow noreferrer\">Scott Gu's article on the matter</a>.</p>\n"
},
{
"answer_id": 41677870,
"author": "Kevin Pluck",
"author_id": 1507920,
"author_profile": "https://Stackoverflow.com/users/1507920",
"pm_score": 0,
"selected": false,
"text": "<p>None of the above suggestions worked for me. Turns out in the root web.config set:</p>\n\n<pre><code><forms loginUrl=\"/pages/login.aspx\" enableCrossAppRedirects=\"true\"...\n</code></pre>\n\n<p>and make sure that both the root and child app have in system.web</p>\n\n<pre><code><machineKey validationKey=\"AutoGenerate\" decryptionKey=\"AutoGenerate\" validation=\"SHA1\"/>\n</code></pre>\n\n<p>which turns off the IsolateApps default.</p>\n\n<p>Then everything just worked!</p>\n"
}
] | 2008/08/21 | [
"https://Stackoverflow.com/questions/19236",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1965/"
] | I'm working on a internal web based tool for my company. Part of this tool is another application (The Cruise Control Dashboard) that runs in its own Virtual Directory under my root application.
I wanted to limit access to this internal application by setting up Forms Authentication on it, and having a login form in the root application.
I put the following into the root applications web.config:
```
<location path="ccnet">
<system.web>
<authentication mode="Forms">
<forms loginUrl="/default.aspx" timeout="5000"/>
</authentication>
<authorization>
<allow users="?"/>
<deny users="?"/>
</authorization>
</system.web>
</location>
```
However, the Forms Authentication does not appear to be working, it does not redirect back to the login page when I access that application directly.
I have a feeling I have the <allow> and <deny> tags set wrong. Can someone clarify? | You might also need to put path="/" in the <forms tag(s) I think. Sorry, its been a while since i've done this |
19,294 | <p>In my code behind I wire up my events like so:</p>
<pre><code>protected override void OnInit(EventArgs e)
{
base.OnInit(e);
btnUpdateUser.Click += btnUpateUserClick;
}
</code></pre>
<p>I've done it this way because that's what I've seen in examples. </p>
<ul>
<li>Does the base.OnInit() method need to be called? </li>
<li>Will it be implicitly be called? </li>
<li>Is it better to call it at the beginning of the method or at the end? </li>
<li>What would be an example where confusion over the base method can get you in trouble? </li>
</ul>
| [
{
"answer_id": 19296,
"author": "David Wengier",
"author_id": 489,
"author_profile": "https://Stackoverflow.com/users/489",
"pm_score": 0,
"selected": false,
"text": "<p>In this case, if you don't call the base OnInit, then the Init even will not fire.</p>\n\n<p>In general, it is best practice to ALWAYS call the base method, unless you specifically know that you do not want the base behaviour to occur.</p>\n\n<p>Whether its called at the start or the end depends on how you want things to work. In a case like this, where you are using an override instead of hooking up an event handler, calling it at the start of the method makes more sense. That way, your code will run after any handlers, which makes it more emulate a \"normal\" event handler.</p>\n"
},
{
"answer_id": 19299,
"author": "Matt Hamilton",
"author_id": 615,
"author_profile": "https://Stackoverflow.com/users/615",
"pm_score": 0,
"selected": false,
"text": "<p>Although the official framework design guidelines recommend otherwise, most class designers will actually make the OnXxx() method responsible for firing the actual event, like this:</p>\n\n<pre><code>protected virtual void OnClick(EventArgs e)\n{\n if (Click != null) Click(this, e);\n}\n</code></pre>\n\n<p>... so if you inherit from the class and don't call base.OnClick(e), the Click event will never fire.</p>\n\n<p>So yes, even though this <em>shouldn't</em> be the case according to the official design guidelines, I think it's worth calling base.OnInit(e) just to be sure.</p>\n"
},
{
"answer_id": 19302,
"author": "David Wengier",
"author_id": 489,
"author_profile": "https://Stackoverflow.com/users/489",
"pm_score": 0,
"selected": false,
"text": "<blockquote>\n <p>official framework design guidelines recommend otherwise</p>\n</blockquote>\n\n<p>They do? I'm curious, i've always thought the opposite, and reading Framework Design Guidelines and running FxCop has only cemented my view. I was under the impression that events should always be fired from virtual OnXxx() methods, that take an EventArgs parameter</p>\n"
},
{
"answer_id": 19306,
"author": "Matt Hamilton",
"author_id": 615,
"author_profile": "https://Stackoverflow.com/users/615",
"pm_score": 3,
"selected": true,
"text": "<p>I should clarify:</p>\n\n<p>The guidelines recommend that firing an event should involve calling a virtual \"On<em>EventName</em>\" method, but they also say that if a derived class overrides that method and forgets to call the base method, the event should still fire.</p>\n\n<p>See the \"Important Note\" about halfway down <a href=\"http://msdn.microsoft.com/en-us/library/ms229011.aspx\" rel=\"nofollow noreferrer\">this page</a>:</p>\n\n<blockquote>\n <p>Derived classes that override the protected virtual method are not required to call the base class implementation. The base class must continue to work correctly even if its implementation is not called.</p>\n</blockquote>\n"
},
{
"answer_id": 19313,
"author": "David Wengier",
"author_id": 489,
"author_profile": "https://Stackoverflow.com/users/489",
"pm_score": 0,
"selected": false,
"text": "<p>You probably are better off doing it that way, then this debate goes away. The article is interesting though, especially considering that the .NET Framework doesn't honour this guideline.</p>\n"
},
{
"answer_id": 19320,
"author": "Matt Hamilton",
"author_id": 615,
"author_profile": "https://Stackoverflow.com/users/615",
"pm_score": 0,
"selected": false,
"text": "<p>@Ch00k and @Scott I dunno - I like the On<em>EventName</em> pattern myself. And yeah, I'm one of the people who are guilty of firing the event from that method.</p>\n\n<p>I think overriding the On* method and calling the base one is the way to go. Handling your own events seems wrong somehow.</p>\n"
}
] | 2008/08/21 | [
"https://Stackoverflow.com/questions/19294",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1894/"
] | In my code behind I wire up my events like so:
```
protected override void OnInit(EventArgs e)
{
base.OnInit(e);
btnUpdateUser.Click += btnUpateUserClick;
}
```
I've done it this way because that's what I've seen in examples.
* Does the base.OnInit() method need to be called?
* Will it be implicitly be called?
* Is it better to call it at the beginning of the method or at the end?
* What would be an example where confusion over the base method can get you in trouble? | I should clarify:
The guidelines recommend that firing an event should involve calling a virtual "On*EventName*" method, but they also say that if a derived class overrides that method and forgets to call the base method, the event should still fire.
See the "Important Note" about halfway down [this page](http://msdn.microsoft.com/en-us/library/ms229011.aspx):
>
> Derived classes that override the protected virtual method are not required to call the base class implementation. The base class must continue to work correctly even if its implementation is not called.
>
>
> |
19,295 | <p>I'd like to use a database to store i18n key/value pairs so we can modify / reload the i18n data at runtime. Has anyone done this? Or does anyone have an idea of how to implement this? I've read several threads on this, but I haven't seen a workable solution.</p>
<p>I'm specifically refering to something that would work with the jstl tags such as</p>
<pre><code><fmt:setlocale>
<fmt:bundle>
<fmt:setBundle>
<fmt:message>
</code></pre>
<p>I think this will involve extending ResourceBundle, but when I tried this I ran into problems that had to do with the way the jstl tags get the resource bundle.</p>
| [
{
"answer_id": 19308,
"author": "danb",
"author_id": 2031,
"author_profile": "https://Stackoverflow.com/users/2031",
"pm_score": 3,
"selected": true,
"text": "<p>Are you just asking how to store UTF-8/16 characters in a DB? in mysql it's just a matter of making sure you build with UTF8 support and setting that as the default, or specifying it at the column or table level. I've done this in oracle and mysql before. Create a table and cut and paste some i18n data into it and see what happens... you might be set already..</p>\n\n<p>or am I completely missing your point? </p>\n\n<p>edit: </p>\n\n<p>to be more explicit... I usually implement a three column table... language, key, value... where \"value\" contains potentially foreign language words or phrases... \"language\" contains some language key and \"key\" is an english key (i.e. login.error.password.dup)... language and key are indexed... </p>\n\n<p>I've then built interfaces on a structure like this that shows each key with all its translations (values)... it can get fancy and include audit trails and \"dirty\" markers and all the other stuff you need to enable translators and data entry folk to make use of it..</p>\n\n<p>Edit 2:</p>\n\n<p>Now that you added the info about the JSTL tags, I understand a bit more... I've never done that myself.. but I found this old info on <a href=\"http://www.theserverside.com/discussions/thread.tss?thread_id=27390\" rel=\"nofollow noreferrer\">theserverside</a>...</p>\n\n<pre><code>HttpSession session = .. [get hold of the session] \nResourceBundle bundle = new PropertyResourceBundle(toInputStream(myOwnProperties)) [toInputStream just stores the properties into an inputstream] \nLocale locale = .. [get hold of the locale]\njavax.servlet.jsp.jstl.core.Config.set(session, Config.FMT_LOCALIZATION_CONTEXT, new LocalizationContext(bundle ,locale));\n</code></pre>\n"
},
{
"answer_id": 19377,
"author": "dlinsin",
"author_id": 198,
"author_profile": "https://Stackoverflow.com/users/198",
"pm_score": 1,
"selected": false,
"text": "<p>We have a database table with key/language/term where key is a n integer and is a combined primary key together with language.</p>\n\n<p>We are using Struts, so we ended up writing our own <em>PropertyMessageResources</em> implementation which allows us to do something like <code><bean:message key=\"impressum.text\" /></code>.</p>\n\n<p>It works very well and gives us the flexibility to do dynamically switch languages in the front-end as well as updating the translations on the fly.</p>\n"
},
{
"answer_id": 32325,
"author": "ScArcher2",
"author_id": 1310,
"author_profile": "https://Stackoverflow.com/users/1310",
"pm_score": 4,
"selected": false,
"text": "<p>I finally got this working with danb's help above.</p>\n\n<p>This is my resource bundle class and resource bundle control class.</p>\n\n<p>I used this code from @[danb]'s.</p>\n\n<pre><code>ResourceBundle bundle = ResourceBundle.getBundle(\"AwesomeBundle\", locale, DbResourceBundle.getMyControl());\njavax.servlet.jsp.jstl.core.Config.set(actionBeanContext.getRequest(), Config.FMT_LOCALIZATION_CONTEXT, new LocalizationContext(bundle, locale));\n</code></pre>\n\n<p>and wrote this class.</p>\n\n<pre><code>public class DbResourceBundle extends ResourceBundle\n{\n private Properties properties;\n\n public DbResourceBundle(Properties inProperties)\n {\n properties = inProperties;\n }\n\n @Override\n @SuppressWarnings(value = { \"unchecked\" })\n public Enumeration<String> getKeys()\n {\n return properties != null ? ((Enumeration<String>) properties.propertyNames()) : null;\n }\n\n @Override\n protected Object handleGetObject(String key)\n {\n return properties.getProperty(key);\n }\n\n public static ResourceBundle.Control getMyControl()\n {\n return new ResourceBundle.Control()\n {\n\n @Override\n public List<String> getFormats(String baseName)\n {\n if (baseName == null)\n {\n throw new NullPointerException();\n }\n return Arrays.asList(\"db\");\n }\n\n @Override\n public ResourceBundle newBundle(String baseName, Locale locale, String format, ClassLoader loader, boolean reload) throws IllegalAccessException,\n InstantiationException, IOException\n {\n if ((baseName == null) || (locale == null) || (format == null) || (loader == null))\n throw new NullPointerException();\n ResourceBundle bundle = null;\n if (format.equals(\"db\"))\n {\n Properties p = new Properties();\n DataSource ds = (DataSource) ContextFactory.getApplicationContext().getBean(\"clinicalDataSource\");\n Connection con = null;\n Statement s = null;\n ResultSet rs = null;\n try\n {\n con = ds.getConnection();\n StringBuilder query = new StringBuilder();\n query.append(\"select label, value from i18n where bundle='\" + StringEscapeUtils.escapeSql(baseName) + \"' \");\n\n if (locale != null)\n {\n if (StringUtils.isNotBlank(locale.getCountry()))\n {\n query.append(\"and country='\" + escapeSql(locale.getCountry()) + \"' \");\n\n }\n if (StringUtils.isNotBlank(locale.getLanguage()))\n {\n query.append(\"and language='\" + escapeSql(locale.getLanguage()) + \"' \");\n\n }\n if (StringUtils.isNotBlank(locale.getVariant()))\n {\n query.append(\"and variant='\" + escapeSql(locale.getVariant()) + \"' \");\n\n }\n }\n s = con.createStatement();\n rs = s.executeQuery(query.toString());\n while (rs.next())\n {\n p.setProperty(rs.getString(1), rs.getString(2));\n }\n }\n catch (Exception e)\n {\n e.printStackTrace();\n throw new RuntimeException(\"Can not build properties: \" + e);\n }\n finally\n {\n DbUtils.closeQuietly(con, s, rs);\n }\n bundle = new DbResourceBundle(p);\n }\n return bundle;\n }\n\n @Override\n public long getTimeToLive(String baseName, Locale locale)\n {\n return 1000 * 60 * 30;\n }\n\n @Override\n public boolean needsReload(String baseName, Locale locale, String format, ClassLoader loader, ResourceBundle bundle, long loadTime)\n {\n return true;\n }\n\n };\n }\n</code></pre>\n"
},
{
"answer_id": 12210837,
"author": "krsnik",
"author_id": 776464,
"author_profile": "https://Stackoverflow.com/users/776464",
"pm_score": 0,
"selected": false,
"text": "<p>Actuly what ScArcher2 needed is davids response which is not marked a correct or helpfull.</p>\n\n<p>The solution ScArcher2 chose to use is imo terrible mestake:) Loading ALL the translations at one time... in any bigger application its gonna kill it. Loading thousends of translations each request...</p>\n\n<p>david's method is more commonly used in real production environments. \nSometimes to limit db calls, which is with every message translated, you can create groups of translations by topic, functionality etc. to preload them. But this is little bit more complex and can be substituted with good cache system.</p>\n"
}
] | 2008/08/21 | [
"https://Stackoverflow.com/questions/19295",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1310/"
] | I'd like to use a database to store i18n key/value pairs so we can modify / reload the i18n data at runtime. Has anyone done this? Or does anyone have an idea of how to implement this? I've read several threads on this, but I haven't seen a workable solution.
I'm specifically refering to something that would work with the jstl tags such as
```
<fmt:setlocale>
<fmt:bundle>
<fmt:setBundle>
<fmt:message>
```
I think this will involve extending ResourceBundle, but when I tried this I ran into problems that had to do with the way the jstl tags get the resource bundle. | Are you just asking how to store UTF-8/16 characters in a DB? in mysql it's just a matter of making sure you build with UTF8 support and setting that as the default, or specifying it at the column or table level. I've done this in oracle and mysql before. Create a table and cut and paste some i18n data into it and see what happens... you might be set already..
or am I completely missing your point?
edit:
to be more explicit... I usually implement a three column table... language, key, value... where "value" contains potentially foreign language words or phrases... "language" contains some language key and "key" is an english key (i.e. login.error.password.dup)... language and key are indexed...
I've then built interfaces on a structure like this that shows each key with all its translations (values)... it can get fancy and include audit trails and "dirty" markers and all the other stuff you need to enable translators and data entry folk to make use of it..
Edit 2:
Now that you added the info about the JSTL tags, I understand a bit more... I've never done that myself.. but I found this old info on [theserverside](http://www.theserverside.com/discussions/thread.tss?thread_id=27390)...
```
HttpSession session = .. [get hold of the session]
ResourceBundle bundle = new PropertyResourceBundle(toInputStream(myOwnProperties)) [toInputStream just stores the properties into an inputstream]
Locale locale = .. [get hold of the locale]
javax.servlet.jsp.jstl.core.Config.set(session, Config.FMT_LOCALIZATION_CONTEXT, new LocalizationContext(bundle ,locale));
``` |
19,318 | <p>I have an ASP.NET webservice with along the lines of:</p>
<pre><code>[WebService(Namespace = "http://internalservice.net/messageprocessing")]
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
[ToolboxItem(false)]
public class ProvisioningService : WebService
{
[WebMethod]
public XmlDocument ProcessMessage(XmlDocument message)
{
// ... do stuff
}
}
</code></pre>
<p>I am calling the web service from ASP using something like:</p>
<pre><code>provWSDL = "http://servername:12011/MessageProcessor.asmx?wsdl"
Set service = CreateObject("MSSOAP.SoapClient30")
service.ClientProperty("ServerHTTPRequest") = True
Call service.MSSoapInit(provWSDL)
xmlMessage = "<request><task>....various xml</task></request>"
result = service.ProcessMessage(xmlMessage)
</code></pre>
<p>The problem I am encountering is that when the XML reaches the ProcessMessage method, the web service plumbing has added a default namespace along the way. i.e. if I set a breakpoint inside ProcessMessage(XmlDocument message) I see:</p>
<pre><code><request xmlns="http://internalservice.net/messageprocessing">
<task>....various xml</task>
</request>
</code></pre>
<p>When I capture packets on the wire I can see that the XML sent by the SOAP toolkit is slightly different from that sent by the .NET WS client. The SOAP toolkit sends:</p>
<pre><code><SOAP-ENV:Envelope
xmlns:SOAPSDK1="http://www.w3.org/2001/XMLSchema"
xmlns:SOAPSDK2="http://www.w3.org/2001/XMLSchema-instance"
xmlns:SOAPSDK3="http://schemas.xmlsoap.org/soap/encoding/"
xmlns:SOAP-ENV="http://schemas.xmlsoap.org/soap/envelope/">
<SOAP-ENV:Body>
<ProcessMessage xmlns="http://internalservice.net/messageprocessing">
<message xmlns:SOAPSDK4="http://internalservice.net/messageprocessing">
<request>
<task>...stuff to do</task>
</request>
</message>
</ProcessMessage>
</SOAP-ENV:Body>
</SOAP-ENV:Envelope>
</code></pre>
<p>Whilst the .NET client sends:</p>
<pre><code><soap:Envelope
xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:xsd="http://www.w3.org/2001/XMLSchema">
<soap:Body>
<ProcessMessage xmlns="http://internalservice.net/messageprocessing">
<message>
<request xmlns="">
<task>...stuff to do</task>
</request>
</message>
</ProcessMessage>
</soap:Body>
</soap:Envelope>
</code></pre>
<p>It's been so long since I used the ASP/SOAP toolkit to call into .NET webservices, I can't remember all the clever tricks/SOAP-fu I used to pull to get around stuff like this.</p>
<p>Any ideas? One solution is to knock up a COM callable .NET proxy that takes the XML as a string param and calls the WS on my behalf, but it's an extra layer of complexity/work I hoped not to do.</p>
| [
{
"answer_id": 19324,
"author": "FlySwat",
"author_id": 1965,
"author_profile": "https://Stackoverflow.com/users/1965",
"pm_score": 0,
"selected": false,
"text": "<p>I take it you have access to the Services code, not just the consuming client right?</p>\n\n<p>Just pull the namespace out of the XmlDocument as the first part of the method.</p>\n\n<p>Something like:</p>\n\n<pre><code>XmlDocument changeDocumentNamespace(XmlDocument doc, string newNamespace) \n{ \n if (doc.DocumentElement.NamespaceURI.Length > 0) \n {\n doc.DocumentElement.SetAttribute(\"xmlns\", newNameSpace);\n XmlDocument newDoc = new XmlDocument();\n newDoc.LoadXml(doc.OuterXml);\n return newDoc;\n }\n else \n {\n return doc;\n }\n}\n</code></pre>\n\n<p>Then:</p>\n\n<pre><code>[WebService(Namespace = \"http://internalservice.net/messageprocessing\")]\n[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]\n[ToolboxItem(false)]\npublic class ProvisioningService : WebService\n{\n [WebMethod]\n public XmlDocument ProcessMessage(XmlDocument message)\n {\n message = changeDocumentNamespace(message,String.Empty);\n // Do Stuff...\n }\n}\n</code></pre>\n"
},
{
"answer_id": 19328,
"author": "Kev",
"author_id": 419,
"author_profile": "https://Stackoverflow.com/users/419",
"pm_score": 1,
"selected": true,
"text": "<p>I solved this:</p>\n\n<p>The SOAP client <em>request</em> node was picking up the default namespace from:</p>\n\n<pre><code><ProcessMessage xmlns=\"http://internalservice.net/messageprocessing\">\n</code></pre>\n\n<p>Adding an empty default namespace to the XML sent by the ASP client overrides this behaviour:</p>\n\n<pre><code>xmlMessage = \"<request xmlns=''><task>....various xml</task></request>\"\n</code></pre>\n"
},
{
"answer_id": 19352,
"author": "FlySwat",
"author_id": 1965,
"author_profile": "https://Stackoverflow.com/users/1965",
"pm_score": 1,
"selected": false,
"text": "<p>Kev,</p>\n\n<p>I found the solution, but its not trivial.</p>\n\n<p>You need to create a custom implementation of IHeaderHandler that creates the proper headers.</p>\n\n<p>There is a good step by step here:</p>\n\n<p><a href=\"http://msdn.microsoft.com/en-us/library/ms980699.aspx\" rel=\"nofollow noreferrer\">http://msdn.microsoft.com/en-us/library/ms980699.aspx</a></p>\n\n<p>EDIT: I saw your update. Nice workaround, you might want to bookmark this link regardless :D</p>\n"
}
] | 2008/08/21 | [
"https://Stackoverflow.com/questions/19318",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/419/"
] | I have an ASP.NET webservice with along the lines of:
```
[WebService(Namespace = "http://internalservice.net/messageprocessing")]
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
[ToolboxItem(false)]
public class ProvisioningService : WebService
{
[WebMethod]
public XmlDocument ProcessMessage(XmlDocument message)
{
// ... do stuff
}
}
```
I am calling the web service from ASP using something like:
```
provWSDL = "http://servername:12011/MessageProcessor.asmx?wsdl"
Set service = CreateObject("MSSOAP.SoapClient30")
service.ClientProperty("ServerHTTPRequest") = True
Call service.MSSoapInit(provWSDL)
xmlMessage = "<request><task>....various xml</task></request>"
result = service.ProcessMessage(xmlMessage)
```
The problem I am encountering is that when the XML reaches the ProcessMessage method, the web service plumbing has added a default namespace along the way. i.e. if I set a breakpoint inside ProcessMessage(XmlDocument message) I see:
```
<request xmlns="http://internalservice.net/messageprocessing">
<task>....various xml</task>
</request>
```
When I capture packets on the wire I can see that the XML sent by the SOAP toolkit is slightly different from that sent by the .NET WS client. The SOAP toolkit sends:
```
<SOAP-ENV:Envelope
xmlns:SOAPSDK1="http://www.w3.org/2001/XMLSchema"
xmlns:SOAPSDK2="http://www.w3.org/2001/XMLSchema-instance"
xmlns:SOAPSDK3="http://schemas.xmlsoap.org/soap/encoding/"
xmlns:SOAP-ENV="http://schemas.xmlsoap.org/soap/envelope/">
<SOAP-ENV:Body>
<ProcessMessage xmlns="http://internalservice.net/messageprocessing">
<message xmlns:SOAPSDK4="http://internalservice.net/messageprocessing">
<request>
<task>...stuff to do</task>
</request>
</message>
</ProcessMessage>
</SOAP-ENV:Body>
</SOAP-ENV:Envelope>
```
Whilst the .NET client sends:
```
<soap:Envelope
xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:xsd="http://www.w3.org/2001/XMLSchema">
<soap:Body>
<ProcessMessage xmlns="http://internalservice.net/messageprocessing">
<message>
<request xmlns="">
<task>...stuff to do</task>
</request>
</message>
</ProcessMessage>
</soap:Body>
</soap:Envelope>
```
It's been so long since I used the ASP/SOAP toolkit to call into .NET webservices, I can't remember all the clever tricks/SOAP-fu I used to pull to get around stuff like this.
Any ideas? One solution is to knock up a COM callable .NET proxy that takes the XML as a string param and calls the WS on my behalf, but it's an extra layer of complexity/work I hoped not to do. | I solved this:
The SOAP client *request* node was picking up the default namespace from:
```
<ProcessMessage xmlns="http://internalservice.net/messageprocessing">
```
Adding an empty default namespace to the XML sent by the ASP client overrides this behaviour:
```
xmlMessage = "<request xmlns=''><task>....various xml</task></request>"
``` |
19,339 | <p>I have a list of 2-item tuples and I'd like to convert them to 2 lists where the first contains the first item in each tuple and the second list holds the second item.</p>
<p><strong>For example:</strong></p>
<pre><code>original = [('a', 1), ('b', 2), ('c', 3), ('d', 4)]
# and I want to become...
result = (['a', 'b', 'c', 'd'], [1, 2, 3, 4])
</code></pre>
<p>Is there a builtin function that does that?</p>
| [
{
"answer_id": 19343,
"author": "Patrick",
"author_id": 429,
"author_profile": "https://Stackoverflow.com/users/429",
"pm_score": 11,
"selected": true,
"text": "<p><a href=\"http://docs.python.org/library/functions.html#zip\" rel=\"noreferrer\"><code>zip</code></a> is its own inverse! Provided you use the special * operator.</p>\n\n<pre><code>>>> zip(*[('a', 1), ('b', 2), ('c', 3), ('d', 4)])\n[('a', 'b', 'c', 'd'), (1, 2, 3, 4)]\n</code></pre>\n\n<p>The way this works is by calling <code>zip</code> with the arguments:</p>\n\n<pre><code>zip(('a', 1), ('b', 2), ('c', 3), ('d', 4))\n</code></pre>\n\n<p>… except the arguments are passed to <code>zip</code> directly (after being converted to a tuple), so there's no need to worry about the number of arguments getting too big.</p>\n"
},
{
"answer_id": 25193,
"author": "Anders Eurenius",
"author_id": 1421,
"author_profile": "https://Stackoverflow.com/users/1421",
"pm_score": 5,
"selected": false,
"text": "<p>You could also do</p>\n\n<pre><code>result = ([ a for a,b in original ], [ b for a,b in original ])\n</code></pre>\n\n<p>It <em>should</em> scale better. Especially if Python makes good on not expanding the list comprehensions unless needed.</p>\n\n<p>(Incidentally, it makes a 2-tuple (pair) of lists, rather than a list of tuples, like <code>zip</code> does.)</p>\n\n<p>If generators instead of actual lists are ok, this would do that:</p>\n\n<pre><code>result = (( a for a,b in original ), ( b for a,b in original ))\n</code></pre>\n\n<p>The generators don't munch through the list until you ask for each element, but on the other hand, they do keep references to the original list.</p>\n"
},
{
"answer_id": 4578299,
"author": "Chris",
"author_id": 307678,
"author_profile": "https://Stackoverflow.com/users/307678",
"pm_score": 4,
"selected": false,
"text": "<p>If you have lists that are not the same length, you may not want to use zip as per Patricks answer. This works:</p>\n\n<pre><code>>>> zip(*[('a', 1), ('b', 2), ('c', 3), ('d', 4)])\n[('a', 'b', 'c', 'd'), (1, 2, 3, 4)]\n</code></pre>\n\n<p>But with different length lists, zip truncates each item to the length of the shortest list:</p>\n\n<pre><code>>>> zip(*[('a', 1), ('b', 2), ('c', 3), ('d', 4), ('e', )])\n[('a', 'b', 'c', 'd', 'e')]\n</code></pre>\n\n<p>You can use map with no function to fill empty results with None:</p>\n\n<pre><code>>>> map(None, *[('a', 1), ('b', 2), ('c', 3), ('d', 4), ('e', )])\n[('a', 'b', 'c', 'd', 'e'), (1, 2, 3, 4, None)]\n</code></pre>\n\n<p>zip() is marginally faster though.</p>\n"
},
{
"answer_id": 22115957,
"author": "wassimans",
"author_id": 313127,
"author_profile": "https://Stackoverflow.com/users/313127",
"pm_score": 5,
"selected": false,
"text": "<p>I like to use <code>zip(*iterable)</code> (which is the piece of code you're looking for) in my programs as so:</p>\n\n<pre><code>def unzip(iterable):\n return zip(*iterable)\n</code></pre>\n\n<p>I find <code>unzip</code> more readable.</p>\n"
},
{
"answer_id": 35012020,
"author": "G M",
"author_id": 2132157,
"author_profile": "https://Stackoverflow.com/users/2132157",
"pm_score": 2,
"selected": false,
"text": "<p>It's only another way to do it but it helped me a lot so I write it here:</p>\n\n<p>Having this data structure:</p>\n\n<pre><code>X=[1,2,3,4]\nY=['a','b','c','d']\nXY=zip(X,Y)\n</code></pre>\n\n<p>Resulting in:</p>\n\n<pre><code>In: XY\nOut: [(1, 'a'), (2, 'b'), (3, 'c'), (4, 'd')]\n</code></pre>\n\n<p>The more pythonic way to unzip it and go back to the original is this one in my opinion:</p>\n\n<pre><code>x,y=zip(*XY)\n</code></pre>\n\n<p>But this return a tuple so if you need a list you can use:</p>\n\n<pre><code>x,y=(list(x),list(y))\n</code></pre>\n"
},
{
"answer_id": 35813331,
"author": "Noyer282",
"author_id": 5918464,
"author_profile": "https://Stackoverflow.com/users/5918464",
"pm_score": 4,
"selected": false,
"text": "<pre><code>>>> original = [('a', 1), ('b', 2), ('c', 3), ('d', 4)]\n>>> tuple([list(tup) for tup in zip(*original)])\n(['a', 'b', 'c', 'd'], [1, 2, 3, 4])\n</code></pre>\n\n<p>Gives a tuple of lists as in the question.</p>\n\n<pre><code>list1, list2 = [list(tup) for tup in zip(*original)]\n</code></pre>\n\n<p>Unpacks the two lists.</p>\n"
},
{
"answer_id": 50799018,
"author": "Waylon Flinn",
"author_id": 74291,
"author_profile": "https://Stackoverflow.com/users/74291",
"pm_score": 1,
"selected": false,
"text": "<p>Since it returns tuples (and can use tons of memory), the <code>zip(*zipped)</code> trick seems more clever than useful, to me.</p>\n\n<p>Here's a function that will actually give you the inverse of zip.</p>\n\n<pre><code>def unzip(zipped):\n \"\"\"Inverse of built-in zip function.\n Args:\n zipped: a list of tuples\n\n Returns:\n a tuple of lists\n\n Example:\n a = [1, 2, 3]\n b = [4, 5, 6]\n zipped = list(zip(a, b))\n\n assert zipped == [(1, 4), (2, 5), (3, 6)]\n\n unzipped = unzip(zipped)\n\n assert unzipped == ([1, 2, 3], [4, 5, 6])\n\n \"\"\"\n\n unzipped = ()\n if len(zipped) == 0:\n return unzipped\n\n dim = len(zipped[0])\n\n for i in range(dim):\n unzipped = unzipped + ([tup[i] for tup in zipped], )\n\n return unzipped\n</code></pre>\n"
},
{
"answer_id": 51991395,
"author": "jpp",
"author_id": 9209546,
"author_profile": "https://Stackoverflow.com/users/9209546",
"pm_score": 2,
"selected": false,
"text": "<p>None of the previous answers <em>efficiently</em> provide the required output, which is a <strong>tuple of lists</strong>, rather than a <em>list of tuples</em>. For the former, you can use <code>tuple</code> with <code>map</code>. Here's the difference:</p>\n\n<pre><code>res1 = list(zip(*original)) # [('a', 'b', 'c', 'd'), (1, 2, 3, 4)]\nres2 = tuple(map(list, zip(*original))) # (['a', 'b', 'c', 'd'], [1, 2, 3, 4])\n</code></pre>\n\n<p>In addition, most of the previous solutions assume Python 2.7, where <code>zip</code> returns a list rather than an iterator.</p>\n\n<p>For Python 3.x, you will need to pass the result to a function such as <code>list</code> or <code>tuple</code> to exhaust the iterator. For memory-efficient iterators, you can omit the outer <code>list</code> and <code>tuple</code> calls for the respective solutions.</p>\n"
},
{
"answer_id": 52519708,
"author": "Charlie Clark",
"author_id": 2385133,
"author_profile": "https://Stackoverflow.com/users/2385133",
"pm_score": 1,
"selected": false,
"text": "<p>While <code>zip(*seq)</code> is very useful, it may be unsuitable for very long sequences as it will create a tuple of values to be passed in. For example, I've been working with a coordinate system with over a million entries and find it signifcantly faster to create the sequences directly. </p>\n\n<p>A generic approach would be something like this:</p>\n\n<pre><code>from collections import deque\nseq = ((a1, b1, …), (a2, b2, …), …)\nwidth = len(seq[0])\noutput = [deque(len(seq))] * width # preallocate memory\nfor element in seq:\n for s, item in zip(output, element):\n s.append(item)\n</code></pre>\n\n<p>But, depending on what you want to do with the result, the choice of collection can make a big difference. In my actual use case, using sets and no internal loop, is noticeably faster than all other approaches.</p>\n\n<p>And, as others have noted, if you are doing this with datasets, it might make sense to use Numpy or Pandas collections instead.</p>\n"
},
{
"answer_id": 53885047,
"author": "Azat Ibrakov",
"author_id": 5997596,
"author_profile": "https://Stackoverflow.com/users/5997596",
"pm_score": 3,
"selected": false,
"text": "<h1>Naive approach</h1>\n\n<pre><code>def transpose_finite_iterable(iterable):\n return zip(*iterable) # `itertools.izip` for Python 2 users\n</code></pre>\n\n<p>works fine for finite iterable (e.g. sequences like <code>list</code>/<code>tuple</code>/<code>str</code>) of (potentially infinite) iterables which can be illustrated like</p>\n\n<pre><code>| |a_00| |a_10| ... |a_n0| |\n| |a_01| |a_11| ... |a_n1| |\n| |... | |... | ... |... | |\n| |a_0i| |a_1i| ... |a_ni| |\n| |... | |... | ... |... | |\n</code></pre>\n\n<p>where</p>\n\n<ul>\n<li><code>n in ℕ</code>,</li>\n<li><code>a_ij</code> corresponds to <code>j</code>-th element of <code>i</code>-th iterable,</li>\n</ul>\n\n<p>and after applying <code>transpose_finite_iterable</code> we get</p>\n\n<pre><code>| |a_00| |a_01| ... |a_0i| ... |\n| |a_10| |a_11| ... |a_1i| ... |\n| |... | |... | ... |... | ... |\n| |a_n0| |a_n1| ... |a_ni| ... |\n</code></pre>\n\n<p>Python example of such case where <code>a_ij == j</code>, <code>n == 2</code></p>\n\n<pre><code>>>> from itertools import count\n>>> iterable = [count(), count()]\n>>> result = transpose_finite_iterable(iterable)\n>>> next(result)\n(0, 0)\n>>> next(result)\n(1, 1)\n</code></pre>\n\n<p>But we can't use <code>transpose_finite_iterable</code> again to return to structure of original <code>iterable</code> because <code>result</code> is an infinite iterable of finite iterables (<code>tuple</code>s in our case):</p>\n\n<pre><code>>>> transpose_finite_iterable(result)\n... hangs ...\nTraceback (most recent call last):\n File \"...\", line 1, in ...\n File \"...\", line 2, in transpose_finite_iterable\nMemoryError\n</code></pre>\n\n<p>So how can we deal with this case?</p>\n\n<h1>... and here comes the <code>deque</code></h1>\n\n<p>After we take a look at docs of <a href=\"https://docs.python.org/library/itertools.html#itertools.tee\" rel=\"noreferrer\"><code>itertools.tee</code> function</a>, there is Python recipe that with some modification can help in our case</p>\n\n<pre><code>def transpose_finite_iterables(iterable):\n iterator = iter(iterable)\n try:\n first_elements = next(iterator)\n except StopIteration:\n return ()\n queues = [deque([element])\n for element in first_elements]\n\n def coordinate(queue):\n while True:\n if not queue:\n try:\n elements = next(iterator)\n except StopIteration:\n return\n for sub_queue, element in zip(queues, elements):\n sub_queue.append(element)\n yield queue.popleft()\n\n return tuple(map(coordinate, queues))\n</code></pre>\n\n<p>let's check</p>\n\n<pre><code>>>> from itertools import count\n>>> iterable = [count(), count()]\n>>> result = transpose_finite_iterables(transpose_finite_iterable(iterable))\n>>> result\n(<generator object transpose_finite_iterables.<locals>.coordinate at ...>, <generator object transpose_finite_iterables.<locals>.coordinate at ...>)\n>>> next(result[0])\n0\n>>> next(result[0])\n1\n</code></pre>\n\n<h1>Synthesis</h1>\n\n<p>Now we can define general function for working with iterables of iterables ones of which are finite and another ones are potentially infinite using <a href=\"https://docs.python.org/library/functools.html#functools.singledispatch\" rel=\"noreferrer\"><code>functools.singledispatch</code> decorator</a> like</p>\n\n<pre><code>from collections import (abc,\n deque)\nfrom functools import singledispatch\n\n\n@singledispatch\ndef transpose(object_):\n \"\"\"\n Transposes given object.\n \"\"\"\n raise TypeError('Unsupported object type: {type}.'\n .format(type=type))\n\n\[email protected](abc.Iterable)\ndef transpose_finite_iterables(object_):\n \"\"\"\n Transposes given iterable of finite iterables.\n \"\"\"\n iterator = iter(object_)\n try:\n first_elements = next(iterator)\n except StopIteration:\n return ()\n queues = [deque([element])\n for element in first_elements]\n\n def coordinate(queue):\n while True:\n if not queue:\n try:\n elements = next(iterator)\n except StopIteration:\n return\n for sub_queue, element in zip(queues, elements):\n sub_queue.append(element)\n yield queue.popleft()\n\n return tuple(map(coordinate, queues))\n\n\ndef transpose_finite_iterable(object_):\n \"\"\"\n Transposes given finite iterable of iterables.\n \"\"\"\n yield from zip(*object_)\n\ntry:\n transpose.register(abc.Collection, transpose_finite_iterable)\nexcept AttributeError:\n # Python3.5-\n transpose.register(abc.Mapping, transpose_finite_iterable)\n transpose.register(abc.Sequence, transpose_finite_iterable)\n transpose.register(abc.Set, transpose_finite_iterable)\n</code></pre>\n\n<p>which can be considered as its own inverse (mathematicians call this kind of functions <a href=\"https://en.wikipedia.org/wiki/Involution_(mathematics)\" rel=\"noreferrer\">\"involutions\"</a>) in class of binary operators over finite non-empty iterables.</p>\n\n<hr>\n\n<p>As a bonus of <code>singledispatch</code>ing we can handle <code>numpy</code> arrays like</p>\n\n<pre><code>import numpy as np\n...\ntranspose.register(np.ndarray, np.transpose)\n</code></pre>\n\n<p>and then use it like</p>\n\n<pre><code>>>> array = np.arange(4).reshape((2,2))\n>>> array\narray([[0, 1],\n [2, 3]])\n>>> transpose(array)\narray([[0, 2],\n [1, 3]])\n</code></pre>\n\n<h1>Note</h1>\n\n<p>Since <code>transpose</code> returns iterators and if someone wants to have a <code>tuple</code> of <code>list</code>s like in OP -- this can be made additionally with <a href=\"https://docs.python.org/library/functions.html#map\" rel=\"noreferrer\"><code>map</code> built-in function</a> like</p>\n\n<pre><code>>>> original = [('a', 1), ('b', 2), ('c', 3), ('d', 4)]\n>>> tuple(map(list, transpose(original)))\n(['a', 'b', 'c', 'd'], [1, 2, 3, 4])\n</code></pre>\n\n<hr>\n\n<h1>Advertisement</h1>\n\n<p>I've added generalized solution to <a href=\"https://pypi.org/project/lz/\" rel=\"noreferrer\"><code>lz</code> package</a> from <code>0.5.0</code> version which can be used like</p>\n\n<pre><code>>>> from lz.transposition import transpose\n>>> list(map(tuple, transpose(zip(range(10), range(10, 20)))))\n[(0, 1, 2, 3, 4, 5, 6, 7, 8, 9), (10, 11, 12, 13, 14, 15, 16, 17, 18, 19)]\n</code></pre>\n\n<hr>\n\n<h1>P.S.</h1>\n\n<p>There is no solution (at least obvious) for handling potentially infinite iterable of potentially infinite iterables, but this case is less common though.</p>\n"
},
{
"answer_id": 54013413,
"author": "Neil G",
"author_id": 99989,
"author_profile": "https://Stackoverflow.com/users/99989",
"pm_score": 2,
"selected": false,
"text": "<p>Consider using <a href=\"https://more-itertools.readthedocs.io/en/latest/api.html#more_itertools.unzip\" rel=\"nofollow noreferrer\">more_itertools.unzip</a>:</p>\n\n<pre><code>>>> from more_itertools import unzip\n>>> original = [('a', 1), ('b', 2), ('c', 3), ('d', 4)]\n>>> [list(x) for x in unzip(original)]\n[['a', 'b', 'c', 'd'], [1, 2, 3, 4]] \n</code></pre>\n"
},
{
"answer_id": 61685860,
"author": "Trasp",
"author_id": 1388027,
"author_profile": "https://Stackoverflow.com/users/1388027",
"pm_score": 2,
"selected": false,
"text": "<p>While numpy arrays and pandas may be preferrable, this function imitates the behavior of <code>zip(*args)</code> when called as <code>unzip(args)</code>.</p>\n\n<p>Allows for generators, like the result from <code>zip</code> in Python 3, to be passed as <code>args</code> as it iterates through values.</p>\n\n<pre class=\"lang-py prettyprint-override\"><code>def unzip(items, cls=list, ocls=tuple):\n \"\"\"Zip function in reverse.\n\n :param items: Zipped-like iterable.\n :type items: iterable\n\n :param cls: Container factory. Callable that returns iterable containers,\n with a callable append attribute, to store the unzipped items. Defaults\n to ``list``.\n :type cls: callable, optional\n\n :param ocls: Outer container factory. Callable that returns iterable\n containers. with a callable append attribute, to store the inner\n containers (see ``cls``). Defaults to ``tuple``.\n :type ocls: callable, optional\n\n :returns: Unzipped items in instances returned from ``cls``, in an instance\n returned from ``ocls``.\n \"\"\"\n # iter() will return the same iterator passed to it whenever possible.\n items = iter(items)\n\n try:\n i = next(items)\n except StopIteration:\n return ocls()\n\n unzipped = ocls(cls([v]) for v in i)\n\n for i in items:\n for c, v in zip(unzipped, i):\n c.append(v)\n\n return unzipped\n</code></pre>\n\n<p>To use list cointainers, simply run <code>unzip(zipped)</code>, as</p>\n\n<pre class=\"lang-py prettyprint-override\"><code>unzip(zip([\"a\",\"b\",\"c\"],[1,2,3])) == ([\"a\",\"b\",\"c\"],[1,2,3])\n</code></pre>\n\n<p>To use deques, or other any container sporting <code>append</code>, pass a factory function.</p>\n\n<pre class=\"lang-py prettyprint-override\"><code>from collections import deque\n\nunzip([(\"a\",1),(\"b\",2)], deque, list) == [deque([\"a\",\"b\"]),deque([1,2])]\n</code></pre>\n\n<p>(Decorate <code>cls</code> and/or <code>main_cls</code> to micro manage container initialization, as briefly shown in the final assert statement above.)</p>\n"
},
{
"answer_id": 71385682,
"author": "mkearney",
"author_id": 5435428,
"author_profile": "https://Stackoverflow.com/users/5435428",
"pm_score": 0,
"selected": false,
"text": "<p>Here's a simple one-line answer that produces the desired output:</p>\n<pre class=\"lang-py prettyprint-override\"><code>original = [('a', 1), ('b', 2), ('c', 3), ('d', 4)]\nlist(zip(*original))\n# [('a', 'b', 'c', 'd'), (1, 2, 3, 4)]\n</code></pre>\n"
}
] | 2008/08/21 | [
"https://Stackoverflow.com/questions/19339",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/680/"
] | I have a list of 2-item tuples and I'd like to convert them to 2 lists where the first contains the first item in each tuple and the second list holds the second item.
**For example:**
```
original = [('a', 1), ('b', 2), ('c', 3), ('d', 4)]
# and I want to become...
result = (['a', 'b', 'c', 'd'], [1, 2, 3, 4])
```
Is there a builtin function that does that? | [`zip`](http://docs.python.org/library/functions.html#zip) is its own inverse! Provided you use the special \* operator.
```
>>> zip(*[('a', 1), ('b', 2), ('c', 3), ('d', 4)])
[('a', 'b', 'c', 'd'), (1, 2, 3, 4)]
```
The way this works is by calling `zip` with the arguments:
```
zip(('a', 1), ('b', 2), ('c', 3), ('d', 4))
```
… except the arguments are passed to `zip` directly (after being converted to a tuple), so there's no need to worry about the number of arguments getting too big. |
19,355 | <p>In a .NET project, say you have a configuration setting - like a connection string - stored in a app.config file, which is different for each developer on your team (they may be using a local SQL Server, or a specific server instance, or using a remote server, etc). </p>
<p>How can you structure your solution so that each developer can have their own development "preferences" (i.e. not checked into source control), but provide a default connection string that is checked into source control (thereby supplying the correct defaults for a build process or new developers).</p>
<p><hr />
Edit: Can the "<code>file</code>" method suggested by @Jonathon be somehow used with the <code>connectionStrings</code> section?</p>
| [
{
"answer_id": 19359,
"author": "Scott Muc",
"author_id": 1894,
"author_profile": "https://Stackoverflow.com/users/1894",
"pm_score": 0,
"selected": false,
"text": "<p>I always make templates for my config files. </p>\n\n<p>As an example I use NAnt for the building of my projects. I have a file checked in called local.properties.xml.template. My NAnt build will warn the developer if local.properties.xml does not exist. Inside that file will be workstation specific settings. The template will be checked into source control, but the actual config won't be.</p>\n"
},
{
"answer_id": 19360,
"author": "DevelopingChris",
"author_id": 1220,
"author_profile": "https://Stackoverflow.com/users/1220",
"pm_score": 0,
"selected": false,
"text": "<p>I use quite archaic design that just works.</p>\n\n<ul>\n<li>/_Test__app.config</li>\n<li>/_Prod__app.config</li>\n<li>/app.config</li>\n</ul>\n\n<p>Then in my nant script, I have a task that copies, the current build environment plus _ app.config and copy it to app.config.</p>\n\n<p>Its nasty, but you can't get in between providers and ConfigurationManager to spoof it, by saying providers look at \"dev\" or \"prod\" connection string and just have 3 named connection strings.</p>\n\n<p>nant task:</p>\n\n<pre><code><target name=\"copyconfigs\" depends=\"clean\">\n <foreach item=\"File\" property=\"filename\" unless=\"${string::get-length(ConfigPrefix) == 0}\">\n <in>\n <items>\n <include name=\"**/${ConfigPrefix}App.config\" />\n <include name=\"**/${ConfigPrefix}connectionstrings.config\" />\n <include name=\"**/${ConfigPrefix}web.config\" />\n </items>\n </in>\n <do>\n <copy overwrite=\"true\" file=\"${filename}\" tofile=\"${string::replace(filename, ConfigPrefix,'')}\" />\n </do>\n </foreach></target>\n</code></pre>\n"
},
{
"answer_id": 19361,
"author": "FlySwat",
"author_id": 1965,
"author_profile": "https://Stackoverflow.com/users/1965",
"pm_score": 3,
"selected": true,
"text": "<p>AppSettings can be overridden with a local file:</p>\n\n<pre><code><appSettings file=\"localoveride.config\"/>\n</code></pre>\n\n<p>This allows for each developer to keep their own local settings.</p>\n\n<p>As far as the connection string, in a perfect world all developers should connect to a test DB, not run SQL Server each.</p>\n\n<p>However, I've found it best to keep a file named Web.Config.Prd in source control, and use that for build deployments. If someone modifies web.config, they must also add the change to the .PRD file...There is no good automation there :(</p>\n"
},
{
"answer_id": 19375,
"author": "FlySwat",
"author_id": 1965,
"author_profile": "https://Stackoverflow.com/users/1965",
"pm_score": 0,
"selected": false,
"text": "<blockquote>\n <p>Can the \"file\" method suggested by @Jonathon be somehow used with the connectionStrings section?</p>\n</blockquote>\n\n<p>No, but there is nothing stopping you from storing the ConnectionString as an AppSettings key.</p>\n"
},
{
"answer_id": 19380,
"author": "Scott Muc",
"author_id": 1894,
"author_profile": "https://Stackoverflow.com/users/1894",
"pm_score": 2,
"selected": false,
"text": "<blockquote>\n <p>Edit: Can the \"file\" method suggested\n by @Jonathon be somehow used with the\n connectionStrings section?</p>\n</blockquote>\n\n<p>Or you can have multiple connection strings in the checked in config file, and use an AppSettings key to determine which ConnectionString is to be used. I have the following in my codebase for this purpose:</p>\n\n<pre><code>public class ConnectionString\n{\n public static string Default\n {\n get \n { \n if (string.IsNullOrEmpty(ConfigurationManager.AppSettings[\"DefaultConnectionStringName\"]))\n throw new ApplicationException(\"DefaultConnectionStringName must be set in the appSettings\");\n\n return GetByName(ConfigurationManager.AppSettings[\"DefaultConnectionStringName\"]);\n }\n }\n\n public static string GetByName(string dsn)\n {\n return ConfigurationManager.ConnectionStrings[dsn].ConnectionString;\n }\n}\n</code></pre>\n"
}
] | 2008/08/21 | [
"https://Stackoverflow.com/questions/19355",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/708/"
] | In a .NET project, say you have a configuration setting - like a connection string - stored in a app.config file, which is different for each developer on your team (they may be using a local SQL Server, or a specific server instance, or using a remote server, etc).
How can you structure your solution so that each developer can have their own development "preferences" (i.e. not checked into source control), but provide a default connection string that is checked into source control (thereby supplying the correct defaults for a build process or new developers).
---
Edit: Can the "`file`" method suggested by @Jonathon be somehow used with the `connectionStrings` section? | AppSettings can be overridden with a local file:
```
<appSettings file="localoveride.config"/>
```
This allows for each developer to keep their own local settings.
As far as the connection string, in a perfect world all developers should connect to a test DB, not run SQL Server each.
However, I've found it best to keep a file named Web.Config.Prd in source control, and use that for build deployments. If someone modifies web.config, they must also add the change to the .PRD file...There is no good automation there :( |
19,388 | <p>I've heard rumors that PHP is planning on introducing a "goto" command. What is it supposed to be doing?</p>
<p>I've tried searching a bit, but haven't found anything awfully descriptive. I understand that it won't be a "<code>GOTO 10</code>"-like command...</p>
| [
{
"answer_id": 19398,
"author": "postfuturist",
"author_id": 1892,
"author_profile": "https://Stackoverflow.com/users/1892",
"pm_score": 2,
"selected": false,
"text": "<p>Granted, I am not a PHP programmer, and I don't know what PHP's exact implementation of GOTO will look like, but here is my understanding of GOTO:</p>\n\n<p>GOTO is just a more explicit flow control statement like any other. Let's say you have some nested loops and you only need to find one thing. You can put in a conditional statement (or several) and when conditions are met properly, you can use a GOTO statement to get out of all the loops, (instead of having a 'break' statement at each level of nesting with a conditional statement for each. And yes, I believe the traditional implementation is to have named labels that the GOTO statement can jump to by name. You can do something like this:</p>\n\n<pre><code>for(...) {\n for (...) {\n for (...) {\n // some code\n if (x) GOTO outside;\n }\n }\n} \n:outside\n</code></pre>\n\n<p>This is a simpler (and more efficient) implementation than without GOTO statements. The equivalent would be:</p>\n\n<pre><code>for(...) {\n for (...) {\n for (...) {\n // some code\n if (x) break;\n }\n if(x) break;\n }\n if(x) break;\n} \n</code></pre>\n\n<p>In the second case (which is common practice) there are three conditional statements, which is obviously slower than just having one. So, for optimization/simplification reasons, you might want to use GOTO statements in tightly nested loops.</p>\n"
},
{
"answer_id": 19402,
"author": "Kyle Cronin",
"author_id": 658,
"author_profile": "https://Stackoverflow.com/users/658",
"pm_score": 0,
"selected": false,
"text": "<p>It <a href=\"http://wiki.php.net/doc/todo/undocumented#php_5.3\" rel=\"nofollow noreferrer\">looks</a> like it's currently in PHP 5.3, but is not fully documented yet. From what I can tell it shares its goto syntax with C, so it should be easy to pick up and use. Just remember Dijkstra's <a href=\"http://www.cs.utexas.edu/users/EWD/ewd02xx/EWD215.PDF\" rel=\"nofollow noreferrer\">warning</a> and use it only when necessary.</p>\n"
},
{
"answer_id": 19403,
"author": "Ishmaeel",
"author_id": 227,
"author_profile": "https://Stackoverflow.com/users/227",
"pm_score": 4,
"selected": true,
"text": "<p>They are not adding a real GOTO, but extending the BREAK keyword to use static labels. Basically, it will be enhancing the ability to break out of <s>switch</s> nested if statements. Here's the concept example I found:</p>\n\n<pre><code><?php\nfor ($i = 0; $i < 9; $i++) {\n if (true) {\n break blah;\n }\n echo \"not shown\";\n blah:\n echo \"iteration $i\\n\";\n}\n?>\n</code></pre>\n\n<p>Of course, once the GOTO \"rumor\" was out, there was nothing to stop some evil guys to propagate an additional <strong>COMEFROM</strong> joke. Be on your toes.</p>\n\n<p>See also:</p>\n\n<p><a href=\"http://www.php.net/~derick/meeting-notes.html#adding-goto\" rel=\"nofollow noreferrer\">http://www.php.net/~derick/meeting-notes.html#adding-goto</a></p>\n"
},
{
"answer_id": 19404,
"author": "FlySwat",
"author_id": 1965,
"author_profile": "https://Stackoverflow.com/users/1965",
"pm_score": 0,
"selected": false,
"text": "<p>@steveth45</p>\n\n<p>My rule of thumb is that if you have nested code more than 3 levels deep, you are doing \nsomething wrong.</p>\n\n<p>Then you don't have to worry about using multiple break statements or goto :D</p>\n"
},
{
"answer_id": 19452,
"author": "grom",
"author_id": 486,
"author_profile": "https://Stackoverflow.com/users/486",
"pm_score": 1,
"selected": false,
"text": "<p>In the example given by <a href=\"https://stackoverflow.com/questions/19388/goto-command-in-php6#19398\">steveth45</a> you can use a function instead:</p>\n\n<pre><code>function findItem(...) {\n for (...) {\n for (...) {\n for (...) {\n if (x) {\n return theItem;\n }\n }\n }\n }\n}\n\n// no need for label now\ntheItem = findItem(a, b, c);\n</code></pre>\n"
},
{
"answer_id": 1078480,
"author": "Ira Baxter",
"author_id": 120163,
"author_profile": "https://Stackoverflow.com/users/120163",
"pm_score": 3,
"selected": false,
"text": "<p>I'm always astonished at how incredibly dumb the PHP designers are.\nIf the purpose of using GOTOs is to make breaking out of multiply nested\nloops more efficient there's a better way: labelled code blocks\nand break statements that can reference labels:</p>\n\n<pre><code>a: for (...) {\n b: for (...) {\n c: for (...) {\n ...\n break a;\n }\n }\n }\n</code></pre>\n\n<p>Now is is clear which loop/block to exit, and the exit is structured;\nyou can't get spaghetti code with this like you can with real gotos.</p>\n\n<p>This is an old, old, old idea. Designing good control flow management\nstructures has been solved since the 70s, and the literature on all this\nis long since written up. The Bohm-Jacopini theorem showed that\nyou could code anything with function call, if-then-else, and while loops.\nIn practice, to break out of deeply nested blocks, Bohm-Jacopini style\ncoding required extra boolean flags (\"set this flag to get out of the loop\")\nwhich was clumsy coding wise and inefficient (you don't want such flags\nin your inner loop). With if-then-else, various loops (while,for)\nand break-to-labelled block, you can code any algorithm without no\nloss in efficiency. Why don't people read the literature, instead\nof copying what C did? Grrr.</p>\n"
},
{
"answer_id": 16190143,
"author": "Jurijs Nesterovs",
"author_id": 2181738,
"author_profile": "https://Stackoverflow.com/users/2181738",
"pm_score": 0,
"selected": false,
"text": "<p>there is a <code>goto</code> in php -> <a href=\"http://php.net/manual/en/control-structures.goto.php\" rel=\"nofollow\">http://php.net/manual/en/control-structures.goto.php</a>, but i wouldn't use it, just write normal code...</p>\n"
}
] | 2008/08/21 | [
"https://Stackoverflow.com/questions/19388",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2238/"
] | I've heard rumors that PHP is planning on introducing a "goto" command. What is it supposed to be doing?
I've tried searching a bit, but haven't found anything awfully descriptive. I understand that it won't be a "`GOTO 10`"-like command... | They are not adding a real GOTO, but extending the BREAK keyword to use static labels. Basically, it will be enhancing the ability to break out of ~~switch~~ nested if statements. Here's the concept example I found:
```
<?php
for ($i = 0; $i < 9; $i++) {
if (true) {
break blah;
}
echo "not shown";
blah:
echo "iteration $i\n";
}
?>
```
Of course, once the GOTO "rumor" was out, there was nothing to stop some evil guys to propagate an additional **COMEFROM** joke. Be on your toes.
See also:
<http://www.php.net/~derick/meeting-notes.html#adding-goto> |
19,409 | <p>This is kinda oddball, but I was poking around with the GNU assembler today (I want to be able to at least read the syntax), and was trying to get this little contrived example of mine to work. Namely I just want to go from 0 to 100, printing out numbers all the while. So a few minutes later I come up with this:</p>
<pre><code># count.s: print the numbers from 0 to 100.
.text
string: .asciz "%d\n"
.globl _main
_main:
movl $0, %eax # The starting point/current value.
movl $100, %ebx # The ending point.
_loop:
# Display the current value.
pushl %eax
pushl $string
call _printf
addl $8, %esp
# Check against the ending value.
cmpl %eax, %ebx
je _end
# Increment the current value.
incl %eax
jmp _loop
_end:
</code></pre>
<p>All I get from this is 3 printed over and over again. Like I said, just a little contrived example, so don't worry too much about it, it's not a life or death problem.</p>
<p>(The formatting's a little messed up, but nothing major).</p>
| [
{
"answer_id": 19411,
"author": "Nathan Fellman",
"author_id": 1084,
"author_profile": "https://Stackoverflow.com/users/1084",
"pm_score": 3,
"selected": false,
"text": "<p>I'm not too familiar with _printf, but could it be that it modifies eax? Printf should return the number of chars printed, which in this case is two: '0' and '\\n'. I think it returns this in eax, and when you increment it, you get 3, which is what you proceed to print.\nYou might be better off using a different register for the counter.</p>\n"
},
{
"answer_id": 19453,
"author": "seanyboy",
"author_id": 1726,
"author_profile": "https://Stackoverflow.com/users/1726",
"pm_score": 5,
"selected": true,
"text": "<p>You can't trust what any called procedure does to any of the registers. \nEither push the registers onto the stack and pop them back off after calling printf or have the increment and end point values held in memory and read/written into registers as you need them. </p>\n\n<p>I hope the following works. I'm assuming that pushl has an equivalant popl and you can push an extra couple of numbers onto the stack. </p>\n\n<pre><code># count.s: print the numbers from 0 to 100. \n .text\nstring: .asciz \"%d\\n\"\n .globl _main\n\n_main:\n movl $0, %eax # The starting point/current value.\n movl $100, %ebx # The ending point.\n\n_loop:\n # Remember your registers.\n pushl %eax\n pushl %ebx\n\n # Display the current value.\n pushl %eax\n pushl $string\n call _printf\n addl $8, %esp\n\n # reinstate registers.\n popl %ebx\n popl %eax\n\n # Check against the ending value.\n cmpl %eax, %ebx\n je _end\n\n # Increment the current value.\n incl %eax\n jmp _loop \n\n_end:\n</code></pre>\n"
},
{
"answer_id": 19459,
"author": "Wedge",
"author_id": 332,
"author_profile": "https://Stackoverflow.com/users/332",
"pm_score": 1,
"selected": false,
"text": "<p>Nathan is on the right track. You can't assume that register values will be unmodified after calling a subroutine. In fact, it's best to assume they will be modified, else the subroutine wouldn't be able to do it's work (at least for low register count architectures like x86). If you want to preserve a value you should store it in memory (e.g. push it onto the stack and keep track of it's location).</p>\n\n<p>You'll need to do the same for any other variable you have. Using registers to store local variables is pretty much reserved to architectures with enough registers to support it (e.g. EPIC, amd64, etc.)</p>\n"
},
{
"answer_id": 19542,
"author": "Nathan Fellman",
"author_id": 1084,
"author_profile": "https://Stackoverflow.com/users/1084",
"pm_score": 2,
"selected": false,
"text": "<p>Well written functions will usually push all the registers onto the stack and then pop them when they're done so that they remain unchanged during the function. The exception would be eax that contains the return value. Library functions like printf are most likely written this way, so I wouldn't do as Wedge suggests:</p>\n\n<blockquote>\n <p>You'll need to do the same for any other variable you have. Using registers to store local variables is pretty much reserved to architectures with enough registers to support it (e.g. EPIC, amd64, etc.)</p>\n</blockquote>\n\n<p>In fact, from what I know, compilers usually compile functions that way to deal exactly with this issue.</p>\n\n<p>@seanyboy, your solution is overkill. All that's needed is to replace eax with some other register like ecx.</p>\n"
},
{
"answer_id": 21148,
"author": "Brad Gilbert",
"author_id": 1337,
"author_profile": "https://Stackoverflow.com/users/1337",
"pm_score": -1,
"selected": false,
"text": "<p>You could rewrite it so that you use registers that aren't suppose to change, for example <code>%ebp</code>. Just make sure you push them onto the stack at the beginning, and pop them off at the end of your routine.</p>\n\n<pre><code># count.s: print the numbers from 0 to 100. \n .text\nstring: .asciz \"%d\\n\"\n .globl _main\n\n_main:\n push %ecx\n push %ebp\n movl $0, %ecx # The starting point/current value.\n movl $100, %ebp # The ending point.\n\n_loop:\n # Display the current value.\n pushl %ecx\n pushl $string\n call _printf\n addl $8, %esp\n\n # Check against the ending value.\n cmpl %ecx, %ebp\n je _end\n\n # Increment the current value.\n incl %ecx\n jmp _loop \n\n_end:\n pop %ebp\n pop %ecx\n</code></pre>\n"
},
{
"answer_id": 43095,
"author": "alex strange",
"author_id": 4478,
"author_profile": "https://Stackoverflow.com/users/4478",
"pm_score": 3,
"selected": false,
"text": "<p>You can safely use registers that are \"callee-saved\" without having to save them yourself. On x86 these are edi, esi, and ebx; other architectures have more.</p>\n\n<p>These are documented in the ABI references: <a href=\"http://math-atlas.sourceforge.net/devel/assembly/\" rel=\"noreferrer\">http://math-atlas.sourceforge.net/devel/assembly/</a></p>\n"
}
] | 2008/08/21 | [
"https://Stackoverflow.com/questions/19409",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/61/"
] | This is kinda oddball, but I was poking around with the GNU assembler today (I want to be able to at least read the syntax), and was trying to get this little contrived example of mine to work. Namely I just want to go from 0 to 100, printing out numbers all the while. So a few minutes later I come up with this:
```
# count.s: print the numbers from 0 to 100.
.text
string: .asciz "%d\n"
.globl _main
_main:
movl $0, %eax # The starting point/current value.
movl $100, %ebx # The ending point.
_loop:
# Display the current value.
pushl %eax
pushl $string
call _printf
addl $8, %esp
# Check against the ending value.
cmpl %eax, %ebx
je _end
# Increment the current value.
incl %eax
jmp _loop
_end:
```
All I get from this is 3 printed over and over again. Like I said, just a little contrived example, so don't worry too much about it, it's not a life or death problem.
(The formatting's a little messed up, but nothing major). | You can't trust what any called procedure does to any of the registers.
Either push the registers onto the stack and pop them back off after calling printf or have the increment and end point values held in memory and read/written into registers as you need them.
I hope the following works. I'm assuming that pushl has an equivalant popl and you can push an extra couple of numbers onto the stack.
```
# count.s: print the numbers from 0 to 100.
.text
string: .asciz "%d\n"
.globl _main
_main:
movl $0, %eax # The starting point/current value.
movl $100, %ebx # The ending point.
_loop:
# Remember your registers.
pushl %eax
pushl %ebx
# Display the current value.
pushl %eax
pushl $string
call _printf
addl $8, %esp
# reinstate registers.
popl %ebx
popl %eax
# Check against the ending value.
cmpl %eax, %ebx
je _end
# Increment the current value.
incl %eax
jmp _loop
_end:
``` |
19,412 | <p>How can I request a random row (or as close to truly random as is possible) in pure SQL?</p>
| [
{
"answer_id": 19414,
"author": "Matt Hamilton",
"author_id": 615,
"author_profile": "https://Stackoverflow.com/users/615",
"pm_score": 6,
"selected": false,
"text": "<p>I don't know how efficient this is, but I've used it before:</p>\n\n<pre><code>SELECT TOP 1 * FROM MyTable ORDER BY newid()\n</code></pre>\n\n<p>Because GUIDs are pretty random, the ordering means you get a random row.</p>\n"
},
{
"answer_id": 19415,
"author": "Paige Ruten",
"author_id": 813,
"author_profile": "https://Stackoverflow.com/users/813",
"pm_score": 1,
"selected": false,
"text": "<pre><code> SELECT * FROM table ORDER BY RAND() LIMIT 1\n</code></pre>\n"
},
{
"answer_id": 19416,
"author": "Jon Galloway",
"author_id": 5,
"author_profile": "https://Stackoverflow.com/users/5",
"pm_score": 4,
"selected": false,
"text": "<p>You didn't say which server you're using. In older versions of SQL Server, you can use this:</p>\n\n<pre><code>select top 1 * from mytable order by newid()\n</code></pre>\n\n<p>In SQL Server 2005 and up, you can use <code>TABLESAMPLE</code> to get a random sample that's repeatable:</p>\n\n<pre><code>SELECT FirstName, LastName\nFROM Contact \nTABLESAMPLE (1 ROWS) ;\n</code></pre>\n"
},
{
"answer_id": 19419,
"author": "Yaakov Ellis",
"author_id": 51,
"author_profile": "https://Stackoverflow.com/users/51",
"pm_score": 11,
"selected": true,
"text": "<p>See this post: <a href=\"http://www.petefreitag.com/item/466.cfm\" rel=\"noreferrer\">SQL to Select a random row from a database table</a>. It goes through methods for doing this in MySQL, PostgreSQL, Microsoft SQL Server, IBM DB2 and Oracle (the following is copied from that link):</p>\n\n<p>Select a random row with MySQL:</p>\n\n<pre><code>SELECT column FROM table\nORDER BY RAND()\nLIMIT 1\n</code></pre>\n\n<p>Select a random row with PostgreSQL:</p>\n\n<pre><code>SELECT column FROM table\nORDER BY RANDOM()\nLIMIT 1\n</code></pre>\n\n<p>Select a random row with Microsoft SQL Server:</p>\n\n<pre><code>SELECT TOP 1 column FROM table\nORDER BY NEWID()\n</code></pre>\n\n<p>Select a random row with IBM DB2</p>\n\n<pre><code>SELECT column, RAND() as IDX \nFROM table \nORDER BY IDX FETCH FIRST 1 ROWS ONLY\n</code></pre>\n\n<p>Select a random record with Oracle:</p>\n\n<pre><code>SELECT column FROM\n( SELECT column FROM table\nORDER BY dbms_random.value )\nWHERE rownum = 1\n</code></pre>\n"
},
{
"answer_id": 19421,
"author": "Ishmaeel",
"author_id": 227,
"author_profile": "https://Stackoverflow.com/users/227",
"pm_score": 2,
"selected": false,
"text": "<p>Best way is putting a random value in a new column just for that purpose, and using something like this (pseude code + SQL):</p>\n\n<pre><code>randomNo = random()\nexecSql(\"SELECT TOP 1 * FROM MyTable WHERE MyTable.Randomness > $randomNo\")\n</code></pre>\n\n<p>This is the solution employed by the MediaWiki code. Of course, there is some bias against smaller values, but they found that it was sufficient to wrap the random value around to zero when no rows are fetched.</p>\n\n<p>newid() solution may require a full table scan so that each row can be assigned a new guid, which will be much less performant.</p>\n\n<p>rand() solution may not work at all (i.e. with MSSQL) because the function will be evaluated just once, and <em>every</em> row will be assigned the same \"random\" number.</p>\n"
},
{
"answer_id": 19422,
"author": "Grey Panther",
"author_id": 1265,
"author_profile": "https://Stackoverflow.com/users/1265",
"pm_score": 8,
"selected": false,
"text": "<p>Solutions like Jeremies:</p>\n\n<pre><code>SELECT * FROM table ORDER BY RAND() LIMIT 1\n</code></pre>\n\n<p>work, but they need a sequential scan of all the table (because the random value associated with each row needs to be calculated - so that the smallest one can be determined), which can be quite slow for even medium sized tables. My recommendation would be to use some kind of indexed numeric column (many tables have these as their primary keys), and then write something like:</p>\n\n<pre><code>SELECT * FROM table WHERE num_value >= RAND() * \n ( SELECT MAX (num_value ) FROM table ) \nORDER BY num_value LIMIT 1\n</code></pre>\n\n<p>This works in logarithmic time, regardless of the table size, if <code>num_value</code> is indexed. One caveat: this assumes that <code>num_value</code> is equally distributed in the range <code>0..MAX(num_value)</code>. If your dataset strongly deviates from this assumption, you will get skewed results (some rows will appear more often than others).</p>\n"
},
{
"answer_id": 19440,
"author": "BlaM",
"author_id": 999,
"author_profile": "https://Stackoverflow.com/users/999",
"pm_score": 0,
"selected": false,
"text": "<p>I have to agree with CD-MaN: Using \"ORDER BY RAND()\" will work nicely for small tables or when you do your SELECT only a few times.</p>\n\n<p>I also use the \"num_value >= RAND() * ...\" technique, and if I really want to have random results I have a special \"random\" column in the table that I update once a day or so. That single UPDATE run will take some time (especially because you'll have to have an index on that column), but it's much faster than creating random numbers for every row each time the select is run.</p>\n"
},
{
"answer_id": 182584,
"author": "Santiago Cepas",
"author_id": 6547,
"author_profile": "https://Stackoverflow.com/users/6547",
"pm_score": 2,
"selected": false,
"text": "<p>For SQL Server 2005 and 2008, if we want a random sample of individual rows (from <a href=\"http://msdn.microsoft.com/en-us/library/ms189108.aspx\" rel=\"nofollow noreferrer\">Books Online</a>):</p>\n\n<pre><code>SELECT * FROM Sales.SalesOrderDetail\nWHERE 0.01 >= CAST(CHECKSUM(NEWID(), SalesOrderID) & 0x7fffffff AS float)\n/ CAST (0x7fffffff AS int)\n</code></pre>\n"
},
{
"answer_id": 855844,
"author": "Sean Turner",
"author_id": 96894,
"author_profile": "https://Stackoverflow.com/users/96894",
"pm_score": 0,
"selected": false,
"text": "<p>Be careful because TableSample doesn't actually return a random sample of rows. It directs your query to look at a random sample of the 8KB pages that make up your row. Then, your query is executed against the data contained in these pages. Because of how data may be grouped on these pages (insertion order, etc), this could lead to data that isn't actually a random sample. </p>\n\n<p>See: <a href=\"http://www.mssqltips.com/tip.asp?tip=1308\" rel=\"nofollow noreferrer\">http://www.mssqltips.com/tip.asp?tip=1308</a></p>\n\n<p>This MSDN page for TableSample includes an example of how to generate an actualy random sample of data.</p>\n\n<p><a href=\"http://msdn.microsoft.com/en-us/library/ms189108.aspx\" rel=\"nofollow noreferrer\">http://msdn.microsoft.com/en-us/library/ms189108.aspx</a> </p>\n"
},
{
"answer_id": 922443,
"author": "Rob Boek",
"author_id": 27179,
"author_profile": "https://Stackoverflow.com/users/27179",
"pm_score": 4,
"selected": false,
"text": "<p>For SQL Server</p>\n\n<p>newid()/order by will work, but will be very expensive for large result sets because it has to generate an id for every row, and then sort them.</p>\n\n<p>TABLESAMPLE() is good from a performance standpoint, but you will get clumping of results (all rows on a page will be returned).</p>\n\n<p>For a better performing true random sample, the best way is to filter out rows randomly. I found the following code sample in the SQL Server Books Online article <em><a href=\"http://msdn.microsoft.com/en-us/library/ms189108.aspx\" rel=\"noreferrer\">Limiting Results Sets by Using TABLESAMPLE</a></em>:</p>\n\n<blockquote>\n <p>If you really want a random sample of\n individual rows, modify your query to\n filter out rows randomly, instead of\n using TABLESAMPLE. For example, the\n following query uses the NEWID\n function to return approximately one\n percent of the rows of the\n Sales.SalesOrderDetail table:</p>\n\n<pre><code>SELECT * FROM Sales.SalesOrderDetail\nWHERE 0.01 >= CAST(CHECKSUM(NEWID(),SalesOrderID) & 0x7fffffff AS float)\n / CAST (0x7fffffff AS int)\n</code></pre>\n \n <p>The SalesOrderID column is included in\n the CHECKSUM expression so that\n NEWID() evaluates once per row to\n achieve sampling on a per-row basis.\n The expression CAST(CHECKSUM(NEWID(),\n SalesOrderID) & 0x7fffffff AS float /\n CAST (0x7fffffff AS int) evaluates to\n a random float value between 0 and 1.</p>\n</blockquote>\n\n<p>When run against a table with 1,000,000 rows, here are my results:</p>\n\n<pre><code>SET STATISTICS TIME ON\nSET STATISTICS IO ON\n\n/* newid()\n rows returned: 10000\n logical reads: 3359\n CPU time: 3312 ms\n elapsed time = 3359 ms\n*/\nSELECT TOP 1 PERCENT Number\nFROM Numbers\nORDER BY newid()\n\n/* TABLESAMPLE\n rows returned: 9269 (varies)\n logical reads: 32\n CPU time: 0 ms\n elapsed time: 5 ms\n*/\nSELECT Number\nFROM Numbers\nTABLESAMPLE (1 PERCENT)\n\n/* Filter\n rows returned: 9994 (varies)\n logical reads: 3359\n CPU time: 641 ms\n elapsed time: 627 ms\n*/ \nSELECT Number\nFROM Numbers\nWHERE 0.01 >= CAST(CHECKSUM(NEWID(), Number) & 0x7fffffff AS float) \n / CAST (0x7fffffff AS int)\n\nSET STATISTICS IO OFF\nSET STATISTICS TIME OFF\n</code></pre>\n\n<p>If you can get away with using TABLESAMPLE, it will give you the best performance. Otherwise use the newid()/filter method. newid()/order by should be last resort if you have a large result set.</p>\n"
},
{
"answer_id": 1074261,
"author": "hegemon",
"author_id": 113083,
"author_profile": "https://Stackoverflow.com/users/113083",
"pm_score": 1,
"selected": false,
"text": "<p>Most of the solutions here aim to avoid sorting, but they still need to make a sequential scan over a table.</p>\n\n<p>There is also a way to avoid the sequential scan by switching to index scan. If you know the index value of your random row you can get the result almost instantially. The problem is - how to guess an index value.</p>\n\n<p>The following solution works on PostgreSQL 8.4:</p>\n\n<pre><code>explain analyze select * from cms_refs where rec_id in \n (select (random()*(select last_value from cms_refs_rec_id_seq))::bigint \n from generate_series(1,10))\n limit 1;\n</code></pre>\n\n<p>I above solution you guess 10 various random index values from range 0 .. [last value of id]. </p>\n\n<p>The number 10 is arbitrary - you may use 100 or 1000 as it (amazingly) doesn't have a big impact on the response time. </p>\n\n<p>There is also one problem - if you have sparse ids <strong>you might miss</strong>. The solution is to <strong>have a backup plan</strong> :) In this case an pure old order by random() query. When combined id looks like this:</p>\n\n<pre><code>explain analyze select * from cms_refs where rec_id in \n (select (random()*(select last_value from cms_refs_rec_id_seq))::bigint \n from generate_series(1,10))\n union all (select * from cms_refs order by random() limit 1)\n limit 1;\n</code></pre>\n\n<p>Not the <strong>union</strong> <strong>ALL</strong> clause. In this case if the first part returns any data the second one is NEVER executed!</p>\n"
},
{
"answer_id": 3286484,
"author": "alphadogg",
"author_id": 59494,
"author_profile": "https://Stackoverflow.com/users/59494",
"pm_score": 2,
"selected": false,
"text": "<p>In late, but got here via Google, so for the sake of posterity, I'll add an alternative solution. </p>\n\n<p>Another approach is to use TOP twice, with alternating orders. I don't know if it is \"pure SQL\", because it uses a variable in the TOP, but it works in SQL Server 2008. Here's an example I use against a table of dictionary words, if I want a random word.</p>\n\n<pre><code>SELECT TOP 1\n word\nFROM (\n SELECT TOP(@idx)\n word \n FROM\n dbo.DictionaryAbridged WITH(NOLOCK)\n ORDER BY\n word DESC\n) AS D\nORDER BY\n word ASC\n</code></pre>\n\n<p>Of course, @idx is some randomly-generated integer that ranges from 1 to COUNT(*) on the target table, inclusively. If your column is indexed, you'll benefit from it too. Another advantage is that you can use it in a function, since NEWID() is disallowed.</p>\n\n<p>Lastly, the above query runs in about 1/10 of the exec time of a NEWID()-type of query on the same table. YYMV.</p>\n"
},
{
"answer_id": 4497240,
"author": "Neel",
"author_id": 549625,
"author_profile": "https://Stackoverflow.com/users/549625",
"pm_score": 5,
"selected": false,
"text": "<pre><code>ORDER BY NEWID()\n</code></pre>\n\n<p>takes <code>7.4 milliseconds</code></p>\n\n<pre><code>WHERE num_value >= RAND() * (SELECT MAX(num_value) FROM table)\n</code></pre>\n\n<p>takes <code>0.0065 milliseconds</code>!</p>\n\n<p>I will definitely go with latter method.</p>\n"
},
{
"answer_id": 4638036,
"author": "ldrut",
"author_id": 568604,
"author_profile": "https://Stackoverflow.com/users/568604",
"pm_score": 2,
"selected": false,
"text": "<p>If possible, use stored statements to avoid the inefficiency of both indexes on RND() and creating a record number field.</p>\n\n<pre>\nPREPARE RandomRecord FROM \"SELECT * FROM table LIMIT ?,1\";\nSET @n=FLOOR(RAND()*(SELECT COUNT(*) FROM table));\nEXECUTE RandomRecord USING @n;\n</pre>\n"
},
{
"answer_id": 4856912,
"author": "DAVID ",
"author_id": 597598,
"author_profile": "https://Stackoverflow.com/users/597598",
"pm_score": 0,
"selected": false,
"text": "<p>It seems that many of the ideas listed still use ordering</p>\n\n<p>However, if you use a temporary table, you are able to assign a random index (like many of the solutions have suggested), and then grab the first one that is greater than an arbitrary number between 0 and 1.</p>\n\n<p>For example (for DB2):</p>\n\n<pre><code>WITH TEMP AS (\nSELECT COMLUMN, RAND() AS IDX FROM TABLE)\nSELECT COLUMN FROM TABLE WHERE IDX > .5\nFETCH FIRST 1 ROW ONLY\n</code></pre>\n"
},
{
"answer_id": 6729183,
"author": "Jai - gotaninterviewcall",
"author_id": 849458,
"author_profile": "https://Stackoverflow.com/users/849458",
"pm_score": 1,
"selected": false,
"text": "<p>You may also try using <code>new id()</code> function.</p>\n\n<p>Just write a your query and use order by <code>new id()</code> function. It quite random.</p>\n"
},
{
"answer_id": 12852040,
"author": "karmakaze",
"author_id": 720030,
"author_profile": "https://Stackoverflow.com/users/720030",
"pm_score": 2,
"selected": false,
"text": "<p>As pointed out in @BillKarwin's comment on @cnu's answer...</p>\n\n<p>When combining with a LIMIT, I've found that it performs much better (at least with PostgreSQL 9.1) to JOIN with a random ordering rather than to directly order the actual rows: e.g.\n<code><pre>\nSELECT * FROM tbl_post AS t\nJOIN ...\nJOIN ( SELECT id, CAST(-2147483648 * RANDOM() AS integer) AS rand\n FROM tbl_post\n WHERE create_time >= 1349928000\n ) r ON r.id = t.id\nWHERE create_time >= 1349928000 AND ...\nORDER BY r.rand\nLIMIT 100\n</pre></code></p>\n\n<p>Just make sure that the 'r' generates a 'rand' value for every possible key value in the complex query which is joined with it but still limit the number of rows of 'r' where possible.</p>\n\n<p>The CAST as Integer is especially helpful for PostgreSQL 9.2 which has specific sort optimisation for integer and single precision floating types.</p>\n"
},
{
"answer_id": 17768021,
"author": "Sophy",
"author_id": 833394,
"author_profile": "https://Stackoverflow.com/users/833394",
"pm_score": 2,
"selected": false,
"text": "<p>For MySQL to get random record</p>\n\n<pre><code> SELECT name\n FROM random AS r1 JOIN\n (SELECT (RAND() *\n (SELECT MAX(id)\n FROM random)) AS id)\n AS r2\n WHERE r1.id >= r2.id\n ORDER BY r1.id ASC\n LIMIT 1\n</code></pre>\n\n<p>More detail <a href=\"http://jan.kneschke.de/projects/mysql/order-by-rand/\" rel=\"nofollow\">http://jan.kneschke.de/projects/mysql/order-by-rand/</a></p>\n"
},
{
"answer_id": 20661166,
"author": "Mmmh mmh",
"author_id": 1582182,
"author_profile": "https://Stackoverflow.com/users/1582182",
"pm_score": 0,
"selected": false,
"text": "<p>A simple and efficient way from <a href=\"http://akinas.com/pages/en/blog/mysql_random_row/\" rel=\"nofollow\">http://akinas.com/pages/en/blog/mysql_random_row/</a></p>\n\n<pre><code>SET @i = (SELECT FLOOR(RAND() * COUNT(*)) FROM table); PREPARE get_stmt FROM 'SELECT * FROM table LIMIT ?, 1'; EXECUTE get_stmt USING @i;\n</code></pre>\n"
},
{
"answer_id": 25021581,
"author": "klyd",
"author_id": 471810,
"author_profile": "https://Stackoverflow.com/users/471810",
"pm_score": 1,
"selected": false,
"text": "<p>Didn't quite see this variation in the answers yet. I had an additional constraint where I needed, given an initial seed, to select the same set of rows each time.</p>\n\n<p>For MS SQL:</p>\n\n<p>Minimum example:</p>\n\n<pre><code>select top 10 percent *\nfrom table_name\norder by rand(checksum(*))\n</code></pre>\n\n<p>Normalized execution time: 1.00</p>\n\n<p>NewId() example:</p>\n\n<pre><code>select top 10 percent *\nfrom table_name\norder by newid()\n</code></pre>\n\n<p>Normalized execution time: 1.02</p>\n\n<p><code>NewId()</code> is insignificantly slower than <code>rand(checksum(*))</code>, so you may not want to use it against large record sets.</p>\n\n<p>Selection with Initial Seed:</p>\n\n<pre><code>declare @seed int\nset @seed = Year(getdate()) * month(getdate()) /* any other initial seed here */\n\nselect top 10 percent *\nfrom table_name\norder by rand(checksum(*) % seed) /* any other math function here */\n</code></pre>\n\n<p>If you need to select the same set given a seed, this seems to work.</p>\n"
},
{
"answer_id": 25642622,
"author": "sev3ryn",
"author_id": 1167502,
"author_profile": "https://Stackoverflow.com/users/1167502",
"pm_score": 0,
"selected": false,
"text": "<p>There is better solution for Oracle instead of using dbms_random.value, while it requires full scan to order rows by dbms_random.value and it is quite slow for large tables.</p>\n\n<p>Use this instead:</p>\n\n<pre><code>SELECT *\nFROM employee sample(1)\nWHERE rownum=1\n</code></pre>\n"
},
{
"answer_id": 29676451,
"author": "David Knight",
"author_id": 161332,
"author_profile": "https://Stackoverflow.com/users/161332",
"pm_score": 1,
"selected": false,
"text": "<p>In MSSQL (tested on 11.0.5569) using </p>\n\n<pre><code>SELECT TOP 100 * FROM employee ORDER BY CRYPT_GEN_RANDOM(10)\n</code></pre>\n\n<p>is significantly faster than</p>\n\n<pre><code>SELECT TOP 100 * FROM employee ORDER BY NEWID()\n</code></pre>\n"
},
{
"answer_id": 40839843,
"author": "Luigi04",
"author_id": 1964666,
"author_profile": "https://Stackoverflow.com/users/1964666",
"pm_score": 1,
"selected": false,
"text": "<p>For Firebird:</p>\n\n<pre><code>Select FIRST 1 column from table ORDER BY RAND()\n</code></pre>\n"
},
{
"answer_id": 42723045,
"author": "forsberg",
"author_id": 1624397,
"author_profile": "https://Stackoverflow.com/users/1624397",
"pm_score": 2,
"selected": false,
"text": "<p>Insted of <a href=\"http://www.titov.net/2005/09/21/do-not-use-order-by-rand-or-how-to-get-random-rows-from-table/\" rel=\"nofollow noreferrer\">using RAND(), as it is not encouraged</a>, you may simply get max ID (=Max):</p>\n\n<pre><code>SELECT MAX(ID) FROM TABLE;\n</code></pre>\n\n<p>get a random between 1..Max (=My_Generated_Random)</p>\n\n<pre><code>My_Generated_Random = rand_in_your_programming_lang_function(1..Max);\n</code></pre>\n\n<p>and then run this SQL:</p>\n\n<pre><code>SELECT ID FROM TABLE WHERE ID >= My_Generated_Random ORDER BY ID LIMIT 1\n</code></pre>\n\n<p>Note that it will check for any rows which Ids are EQUAL or HIGHER than chosen value.\nIt's also possible to hunt for the row down in the table, and get an equal or lower ID than the My_Generated_Random, then modify the query like this:</p>\n\n<pre><code>SELECT ID FROM TABLE WHERE ID <= My_Generated_Random ORDER BY ID DESC LIMIT 1\n</code></pre>\n"
},
{
"answer_id": 43461850,
"author": "Chris Arbogast",
"author_id": 5361251,
"author_profile": "https://Stackoverflow.com/users/5361251",
"pm_score": 1,
"selected": false,
"text": "<p>In SQL Server you can combine TABLESAMPLE with NEWID() to get pretty good randomness and still have speed. This is especially useful if you really only want 1, or a small number, of rows.</p>\n\n<pre><code>SELECT TOP 1 * FROM [table] \nTABLESAMPLE (500 ROWS) \nORDER BY NEWID()\n</code></pre>\n"
},
{
"answer_id": 49542866,
"author": "gbjbaanb",
"author_id": 13744,
"author_profile": "https://Stackoverflow.com/users/13744",
"pm_score": 2,
"selected": false,
"text": "<p>With SQL Server 2012+ you can use the <a href=\"https://technet.microsoft.com/en-us/library/gg699618(v=sql.110).aspx\" rel=\"nofollow noreferrer\">OFFSET FETCH query</a> to do this for a single random row</p>\n\n<pre><code>select * from MyTable ORDER BY id OFFSET n ROW FETCH NEXT 1 ROWS ONLY\n</code></pre>\n\n<p>where id is an identity column, and n is the row you want - calculated as a random number between 0 and count()-1 of the table (offset 0 is the first row after all)</p>\n\n<p>This works with holes in the table data, as long as you have an index to work with for the ORDER BY clause. Its also very good for the randomness - as you work that out yourself to pass in but the niggles in other methods are not present. In addition the performance is pretty good, on a smaller dataset it holds up well, though I've not tried serious performance tests against several million rows.</p>\n"
},
{
"answer_id": 50562274,
"author": "Endri",
"author_id": 4699575,
"author_profile": "https://Stackoverflow.com/users/4699575",
"pm_score": 0,
"selected": false,
"text": "<p>For SQL Server 2005 and above, extending @GreyPanther's answer for the cases when <code>num_value</code> has not continuous values. This works too for cases when we have not evenly distributed datasets and when <code>num_value</code> is not a number but a unique identifier.</p>\n\n<pre><code>WITH CTE_Table (SelRow, num_value) \nAS \n(\n SELECT ROW_NUMBER() OVER(ORDER BY ID) AS SelRow, num_value FROM table\n) \n\nSELECT * FROM table Where num_value = ( \n SELECT TOP 1 num_value FROM CTE_Table WHERE SelRow >= RAND() * (SELECT MAX(SelRow) FROM CTE_Table)\n)\n</code></pre>\n"
},
{
"answer_id": 51205622,
"author": "Nitin",
"author_id": 2669383,
"author_profile": "https://Stackoverflow.com/users/2669383",
"pm_score": 1,
"selected": false,
"text": "<p>Random function from the sql could help. Also if you would like to limit to just one row, just add that in the end.</p>\n\n<pre><code>SELECT column FROM table\nORDER BY RAND()\nLIMIT 1\n</code></pre>\n"
},
{
"answer_id": 64543769,
"author": "Kuks",
"author_id": 14219455,
"author_profile": "https://Stackoverflow.com/users/14219455",
"pm_score": 0,
"selected": false,
"text": "<pre><code>select r.id, r.name from table AS r\nINNER JOIN(select CEIL(RAND() * (select MAX(id) from table)) as id) as r1\nON r.id >= r1.id ORDER BY r.id ASC LIMIT 1\n</code></pre>\n<p>This will require a lesser computation time</p>\n"
},
{
"answer_id": 66179699,
"author": "user2864740",
"author_id": 2864740,
"author_profile": "https://Stackoverflow.com/users/2864740",
"pm_score": 2,
"selected": false,
"text": "<p><em><strong>For SQL Server and needing "a single random row"..</strong></em></p>\n<p>If not needing a true sampling, generate a random value <code>[0, max_rows)</code> and use the <a href=\"https://learn.microsoft.com/en-us/sql/t-sql/queries/select-order-by-clause-transact-sql\" rel=\"nofollow noreferrer\">ORDER BY..OFFSET..FETCH from SQL Server 2012+</a>.</p>\n<p>This is <em>very fast</em> if the <code>COUNT</code> and <code>ORDER BY</code> are over appropriate indexes - such that the data is 'already sorted' along the query lines. If these operations are covered it's a quick request and does not suffer from the <em>horrid scalability</em> of using <code>ORDER BY NEWID()</code> or similar. Obviously, this approach won't scale well on a non-indexed HEAP table.</p>\n<pre><code>declare @rows int\nselect @rows = count(1) from t\n\n-- Other issues if row counts in the bigint range..\n-- This is also not 'true random', although such is likely not required.\ndeclare @skip int = convert(int, @rows * rand())\n\nselect t.*\nfrom t\norder by t.id -- Make sure this is clustered PK or IX/UCL axis!\noffset (@skip) rows\nfetch first 1 row only\n</code></pre>\n<p>Make sure that the appropriate transaction isolation levels are used and/or account for 0 results.</p>\n<hr />\n<p><em><strong>For SQL Server and needing a "general row sample" approach..</strong></em></p>\n<p>Note: This is an adaptation of the answer as found <a href=\"https://stackoverflow.com/a/66179188/2864740\">on a SQL Server specific question about fetching a sample of rows</a>. <em>It has been tailored for context.</em></p>\n<p>While a general sampling approach should be used with caution here, it's still potentially useful information in context of other answers (and the repetitious suggestions of non-scaling and/or questionable implementations). Such a sampling approach is less efficient than the first code shown and is error-prone if the goal is to find a "single random row".</p>\n<hr />\n<p>Here is <em>an updated and improved form of <strong>sampling a percentage of rows</strong></em>. It is based on the same concept of some other answers that use CHECKSUM / BINARY_CHECKSUM and modulus.</p>\n<ul>\n<li><p><strong>It is <em>relatively fast over huge data sets</em></strong> and <strong>can be efficiently used in/with derived queries</strong>. Millions of pre-filtered rows can be sampled in seconds <em>with no tempdb usage</em> and, if aligned with the rest of the query, the overhead is often minimal.</p>\n</li>\n<li><p><strong><em>Does not suffer from <code>CHECKSUM(*)</code> / <code>BINARY_CHECKSUM(*)</code> issues with runs of data.</em> When using the <code>CHECKSUM(*)</code> approach, the rows can be selected in "chunks" and not "random" at all! This is because <em>CHECKSUM prefers speed over distribution</em>.</strong></p>\n</li>\n<li><p><strong>Results in a <em>stable/repeatable</em> row selection</strong> and can be trivially changed to produce different rows on subsequent query executions. Approaches that use <code>NEWID()</code> can never be stable/repeatable.</p>\n</li>\n<li><p><strong>Does not use <code>ORDER BY NEWID()</code> <em>of the entire input set</em>, as <em>ordering can become a significant bottleneck</em> with large input sets.</strong> Avoiding <em>unnecessary</em> sorting also <em>reduces memory and tempdb usage</em>.</p>\n</li>\n<li><p><strong>Does not use <code>TABLESAMPLE</code> and thus works with a <code>WHERE</code> pre-filter.</strong></p>\n</li>\n</ul>\n<p>Here is the gist. <a href=\"https://stackoverflow.com/a/66179188/2864740\">See this answer for additional details and notes</a>.</p>\n<p>Naïve try:</p>\n<pre><code>declare @sample_percent decimal(7, 4)\n-- Looking at this value should be an indicator of why a\n-- general sampling approach can be error-prone to select 1 row.\nselect @sample_percent = 100.0 / count(1) from t\n\n-- BAD!\n-- When choosing appropriate sample percent of "approximately 1 row"\n-- it is very reasonable to expect 0 rows, which definitely fails the ask!\n-- If choosing a larger sample size the distribution is heavily skewed forward,\n-- and is very much NOT 'true random'.\nselect top 1\n t.*\nfrom t\nwhere 1=1\n and ( -- sample\n @sample_percent = 100\n or abs(\n convert(bigint, hashbytes('SHA1', convert(varbinary(32), t.rowguid)))\n ) % (1000 * 100) < (1000 * @sample_percent)\n )\n</code></pre>\n<p>This can be largely remedied by a hybrid query, by mixing sampling and <code>ORDER BY</code> selection from the <em>much smaller sample set</em>. This limits the sorting operation to the sample size, not the size of the original table.</p>\n<pre><code>-- Sample "approximately 1000 rows" from the table,\n-- dealing with some edge-cases.\ndeclare @rows int\nselect @rows = count(1) from t\n\ndeclare @sample_size int = 1000\ndeclare @sample_percent decimal(7, 4) = case\n when @rows <= 1000 then 100 -- not enough rows\n when (100.0 * @sample_size / @rows) < 0.0001 then 0.0001 -- min sample percent\n else 100.0 * @sample_size / @rows -- everything else\n end\n\n-- There is a statistical "guarantee" of having sampled a limited-yet-non-zero number of rows.\n-- The limited rows are then sorted randomly before the first is selected.\nselect top 1\n t.*\nfrom t\nwhere 1=1\n and ( -- sample\n @sample_percent = 100\n or abs(\n convert(bigint, hashbytes('SHA1', convert(varbinary(32), t.rowguid)))\n ) % (1000 * 100) < (1000 * @sample_percent)\n )\n-- ONLY the sampled rows are ordered, which improves scalability.\norder by newid()\n</code></pre>\n"
}
] | 2008/08/21 | [
"https://Stackoverflow.com/questions/19412",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/473/"
] | How can I request a random row (or as close to truly random as is possible) in pure SQL? | See this post: [SQL to Select a random row from a database table](http://www.petefreitag.com/item/466.cfm). It goes through methods for doing this in MySQL, PostgreSQL, Microsoft SQL Server, IBM DB2 and Oracle (the following is copied from that link):
Select a random row with MySQL:
```
SELECT column FROM table
ORDER BY RAND()
LIMIT 1
```
Select a random row with PostgreSQL:
```
SELECT column FROM table
ORDER BY RANDOM()
LIMIT 1
```
Select a random row with Microsoft SQL Server:
```
SELECT TOP 1 column FROM table
ORDER BY NEWID()
```
Select a random row with IBM DB2
```
SELECT column, RAND() as IDX
FROM table
ORDER BY IDX FETCH FIRST 1 ROWS ONLY
```
Select a random record with Oracle:
```
SELECT column FROM
( SELECT column FROM table
ORDER BY dbms_random.value )
WHERE rownum = 1
``` |
19,436 | <p>I have a datalist with a OnDeleteCommand="Delete_Command".</p>
<p>I want the delete a record with multiple primary Keys but I do not know how to access it from the Delete_Command event.</p>
<p>If I use DataKeyField I'm limited to only one key.
Any workarounds for this?</p>
| [
{
"answer_id": 19447,
"author": "Biri",
"author_id": 968,
"author_profile": "https://Stackoverflow.com/users/968",
"pm_score": 2,
"selected": true,
"text": "<p>You can access all of the keys:</p>\n\n<pre><code>gridView.DataKeys[rowNum][dataKeyName]\n</code></pre>\n\n<p>where rowNum is e.RowIndex from the gridView_RowDeleting event handler, and dataKeyName is the key you want to get:</p>\n\n<pre><code><asp:GridView ID=\"gridView\" runat=\"server\" DataKeyNames=\"userid, id1, id2, id3\" OnRowDeleting=\"gridView_RowDeleting\">\n\nprotected void gridView_RowDeleting(object sender, GridViewDeleteEventArgs e)\n{\n gridView.DataKeys[e.RowIndex][\"userid\"]...\n gridView.DataKeys[e.RowIndex][\"id1\"]...\n gridView.DataKeys[e.RowIndex][\"id2\"]...\n gridView.DataKeys[e.RowIndex][\"id3\"]...\n}\n</code></pre>\n"
},
{
"answer_id": 19513,
"author": "Biri",
"author_id": 968,
"author_profile": "https://Stackoverflow.com/users/968",
"pm_score": 0,
"selected": false,
"text": "<p>Oh, sorry, I missed it.</p>\n\n<p>AFAIK there is no such a possibility by default. Maybe you can create a composite key from your primary keys, like </p>\n\n<blockquote>\n <p>Key1UnderscoreKey2UnderscoreKey3</p>\n</blockquote>\n\n<p>and split it in the event handler. So this is a DIY multi-key handler for DataList :-)</p>\n\n<p>Edit: The underscore got lost during format, it replaces with italic text. So instead of \"underscore\" word use real underscores</p>\n"
}
] | 2008/08/21 | [
"https://Stackoverflow.com/questions/19436",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1013/"
] | I have a datalist with a OnDeleteCommand="Delete\_Command".
I want the delete a record with multiple primary Keys but I do not know how to access it from the Delete\_Command event.
If I use DataKeyField I'm limited to only one key.
Any workarounds for this? | You can access all of the keys:
```
gridView.DataKeys[rowNum][dataKeyName]
```
where rowNum is e.RowIndex from the gridView\_RowDeleting event handler, and dataKeyName is the key you want to get:
```
<asp:GridView ID="gridView" runat="server" DataKeyNames="userid, id1, id2, id3" OnRowDeleting="gridView_RowDeleting">
protected void gridView_RowDeleting(object sender, GridViewDeleteEventArgs e)
{
gridView.DataKeys[e.RowIndex]["userid"]...
gridView.DataKeys[e.RowIndex]["id1"]...
gridView.DataKeys[e.RowIndex]["id2"]...
gridView.DataKeys[e.RowIndex]["id3"]...
}
``` |
19,442 | <p>How can I create this file in a directory in windows 2003 SP2:</p>
<pre><code>.hgignore
</code></pre>
<p>I get error: You must type a file name.</p>
| [
{
"answer_id": 19443,
"author": "Ishmaeel",
"author_id": 227,
"author_profile": "https://Stackoverflow.com/users/227",
"pm_score": 6,
"selected": true,
"text": "<p>That's a \"feature\" of Windows Explorer. Try to create your files from a command line (or from a batch/program you wrote) and it should work fine. Try this from a dos prompt:</p>\n\n<pre><code>echo Hello there! > .hgignore\n</code></pre>\n"
},
{
"answer_id": 19476,
"author": "Pat",
"author_id": 238,
"author_profile": "https://Stackoverflow.com/users/238",
"pm_score": 3,
"selected": false,
"text": "<p>By the way Raymond Chen had a blog post about this topic a while back:</p>\n<p><a href=\"https://devblogs.microsoft.com/oldnewthing/20080414-00/?p=22763\" rel=\"nofollow noreferrer\">Why doesn't Explorer let you create a file whose name begins with a dot?</a> (archive.org link with comments: <a href=\"https://web.archive.org/web/20100305064616/http://blogs.msdn.com/oldnewthing/archive/2008/04/14/8389268.aspx\" rel=\"nofollow noreferrer\">https://web.archive.org/web/20100305064616/http://blogs.msdn.com/oldnewthing/archive/2008/04/14/8389268.aspx</a>)</p>\n<p>In which he mentions</p>\n<blockquote>\n<p>You can do it from the command line or\nuse your favorite file management\ntool.</p>\n</blockquote>\n"
}
] | 2008/08/21 | [
"https://Stackoverflow.com/questions/19442",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/479/"
] | How can I create this file in a directory in windows 2003 SP2:
```
.hgignore
```
I get error: You must type a file name. | That's a "feature" of Windows Explorer. Try to create your files from a command line (or from a batch/program you wrote) and it should work fine. Try this from a dos prompt:
```
echo Hello there! > .hgignore
``` |
19,454 | <p>Following on from my recent question on <a href="https://stackoverflow.com/questions/17725/large-complex-objects-as-a-web-service-result">Large, Complex Objects as a Web Service Result</a>. I have been thinking about how I can ensure all future child classes are serializable to XML.</p>
<p>Now, obviously I could implement the <a href="http://msdn.microsoft.com/en-us/library/system.xml.serialization.ixmlserializable.aspx" rel="noreferrer">IXmlSerializable</a> interface and then chuck a reader/writer to it but I would like to avoid that since it then means I need to instantiate a reader/writer whenever I want to do it, and 99.99% of the time I am going to be working with a <em>string</em> so I may just write my own.</p>
<p>However, to serialize to XML, I am simply decorating the class and its members with the <em>Xml???</em> attributes ( <em>XmlRoot</em> , <em>XmlElement</em> etc.) and then passing it to the <em>XmlSerializer</em> and a <em>StringWriter</em> to get the string. Which is all good. I intend to put the method to return the string into a generic utility method so I don't need to worry about type etc.</p>
<p>The this that concerns me is this: If I do not decorate the class(es) with the required attributes an error is not thrown until run time.</p>
<p><strong>Is there any way to enforce attribute decoration? Can this be done with FxCop?</strong> (I have not used FxCop yet)</p>
<h3>UPDATE:</h3>
<p>Sorry for the delay in getting this close off guys, lots to do!</p>
<p>Definitely like the idea of using reflection to do it in a test case rather than resorting to FxCop (like to keep everything together).. <a href="https://stackoverflow.com/questions/19454/enforce-attribute-decoration-of-classesmethods#19455">Fredrik Kalseth's answer</a> was fantastic, thanks for including the code as it probably would have taken me a bit of digging to figure out how to do it myself!</p>
<p>+1 to the other guys for similar suggestions :)</p>
| [
{
"answer_id": 19455,
"author": "Fredrik Kalseth",
"author_id": 1710,
"author_profile": "https://Stackoverflow.com/users/1710",
"pm_score": 5,
"selected": true,
"text": "<p>I'd write a unit/integration test that verifies that any class matching some given criteria (ie subclassing X) is decorated appropriately. If you set up your build to run with tests, you can have the build fail when this test fails.</p>\n\n<p>UPDATE: You said, \"Looks like I will just have to roll my sleeves up and make sure that the unit tests are collectively maintained\" - you don't have to. Just write a general test class that uses reflection to find all classes that needs to be asserted. Something like this:</p>\n\n<pre><code>[TestClass]\npublic class When_type_inherits_MyObject\n{\n private readonly List<Type> _types = new List<Type>();\n\n public When_type_inherits_MyObject()\n {\n // lets find all types that inherit from MyObject, directly or indirectly\n foreach(Type type in typeof(MyObject).Assembly.GetTypes())\n {\n if(type.IsClass && typeof(MyObject).IsAssignableFrom(type))\n {\n _types.Add(type);\n }\n }\n }\n\n [TestMethod]\n public void Properties_have_XmlElement_attribute\n {\n foreach(Type type in _types)\n {\n foreach(PropertyInfo property in type.GetProperties())\n {\n object[] attribs = property.GetCustomAttributes(typeof(XmlElementAttribute), false);\n Assert.IsTrue(attribs.Count > 0, \"Missing XmlElementAttribute on property \" + property.Name + \" in type \" + type.FullName);\n }\n }\n }\n}\n</code></pre>\n"
},
{
"answer_id": 19473,
"author": "samjudson",
"author_id": 1908,
"author_profile": "https://Stackoverflow.com/users/1908",
"pm_score": 1,
"selected": false,
"text": "<p>You can write unit tests to check for this kind of thing - it basically uses reflection.</p>\n\n<p>Given the fact this is possible I guess it would also be possible to write a FxCop rule, but I've never done such a thing.</p>\n"
},
{
"answer_id": 19570,
"author": "Mark Cidade",
"author_id": 1659,
"author_profile": "https://Stackoverflow.com/users/1659",
"pm_score": 1,
"selected": false,
"text": "<p>You can write an FxCop rule or even check for the attributes by calling GetType() in the base class's constructor and reflecting over the returned type.</p>\n"
},
{
"answer_id": 169087,
"author": "Larry Silverman",
"author_id": 7752,
"author_profile": "https://Stackoverflow.com/users/7752",
"pm_score": 0,
"selected": false,
"text": "<p>A good FXCop rule (and one which I am finding I need right now) would be to check that all objects that are being added to the ASP.NET Session have the Serializable attribute. I'm trying to move from InProc session state to SQL Server. First time I requested a page, my site blew up on me because non-serializable objects were being stored in Session. Then came the task of hunting through all the source code looking for every instance where an object is set in the Session... FXCop would be a nice solution. Something to work on...</p>\n"
},
{
"answer_id": 617732,
"author": "Professional Sounding Name",
"author_id": 70160,
"author_profile": "https://Stackoverflow.com/users/70160",
"pm_score": 0,
"selected": false,
"text": "<p>You can also use this concept/post-processor to enforce relationships between attributes and use similar login to enforce relationships between classes and attributes at compile time:</p>\n\n<p><a href=\"http://www.st.informatik.tu-darmstadt.de/database/publications/data/cepa-mezini-gpce04.pdf?id=92\" rel=\"nofollow noreferrer\">http://www.st.informatik.tu-darmstadt.de/database/publications/data/cepa-mezini-gpce04.pdf?id=92</a></p>\n"
}
] | 2008/08/21 | [
"https://Stackoverflow.com/questions/19454",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/832/"
] | Following on from my recent question on [Large, Complex Objects as a Web Service Result](https://stackoverflow.com/questions/17725/large-complex-objects-as-a-web-service-result). I have been thinking about how I can ensure all future child classes are serializable to XML.
Now, obviously I could implement the [IXmlSerializable](http://msdn.microsoft.com/en-us/library/system.xml.serialization.ixmlserializable.aspx) interface and then chuck a reader/writer to it but I would like to avoid that since it then means I need to instantiate a reader/writer whenever I want to do it, and 99.99% of the time I am going to be working with a *string* so I may just write my own.
However, to serialize to XML, I am simply decorating the class and its members with the *Xml???* attributes ( *XmlRoot* , *XmlElement* etc.) and then passing it to the *XmlSerializer* and a *StringWriter* to get the string. Which is all good. I intend to put the method to return the string into a generic utility method so I don't need to worry about type etc.
The this that concerns me is this: If I do not decorate the class(es) with the required attributes an error is not thrown until run time.
**Is there any way to enforce attribute decoration? Can this be done with FxCop?** (I have not used FxCop yet)
### UPDATE:
Sorry for the delay in getting this close off guys, lots to do!
Definitely like the idea of using reflection to do it in a test case rather than resorting to FxCop (like to keep everything together).. [Fredrik Kalseth's answer](https://stackoverflow.com/questions/19454/enforce-attribute-decoration-of-classesmethods#19455) was fantastic, thanks for including the code as it probably would have taken me a bit of digging to figure out how to do it myself!
+1 to the other guys for similar suggestions :) | I'd write a unit/integration test that verifies that any class matching some given criteria (ie subclassing X) is decorated appropriately. If you set up your build to run with tests, you can have the build fail when this test fails.
UPDATE: You said, "Looks like I will just have to roll my sleeves up and make sure that the unit tests are collectively maintained" - you don't have to. Just write a general test class that uses reflection to find all classes that needs to be asserted. Something like this:
```
[TestClass]
public class When_type_inherits_MyObject
{
private readonly List<Type> _types = new List<Type>();
public When_type_inherits_MyObject()
{
// lets find all types that inherit from MyObject, directly or indirectly
foreach(Type type in typeof(MyObject).Assembly.GetTypes())
{
if(type.IsClass && typeof(MyObject).IsAssignableFrom(type))
{
_types.Add(type);
}
}
}
[TestMethod]
public void Properties_have_XmlElement_attribute
{
foreach(Type type in _types)
{
foreach(PropertyInfo property in type.GetProperties())
{
object[] attribs = property.GetCustomAttributes(typeof(XmlElementAttribute), false);
Assert.IsTrue(attribs.Count > 0, "Missing XmlElementAttribute on property " + property.Name + " in type " + type.FullName);
}
}
}
}
``` |
19,461 | <p>I have a standard HTML image tag with an image in it, 100 by 100 pixels in size. I want people to be able to click the image and for that to pass the X and Y that they click into a function.</p>
<p>The coordinates need to be relative to the image top and left.</p>
| [
{
"answer_id": 19464,
"author": "Jon Galloway",
"author_id": 5,
"author_profile": "https://Stackoverflow.com/users/5",
"pm_score": 3,
"selected": false,
"text": "<p>I think you're talking about:</p>\n\n<pre><code><input id=\"info\" type=\"image\">\n</code></pre>\n\n<p>When submitted, there are form values for the x and y coordinate based on the input element id (<code>info.x</code> and <code>info.y</code> in this case).</p>\n\n<p><a href=\"http://www.w3.org/TR/REC-html40/interact/forms.html#h-17.4.1\" rel=\"nofollow noreferrer\">http://www.w3.org/TR/REC-html40/interact/forms.html#h-17.4.1</a></p>\n"
},
{
"answer_id": 1222641,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 1,
"selected": false,
"text": "<p>from what you describe you should register to the image mouse event, for this case you should have the image mouse button event.</p>\n\n<p>at the function you should use </p>\n\n<pre><code>Point mousePoint = e.GetPosition( this );\n</code></pre>\n\n<p>that will give you the mouse position according to the top left point int pixels.</p>\n\n<p>than at the <code>mousePoint</code> you can print the X and Y information. </p>\n"
},
{
"answer_id": 46995289,
"author": "TessavWalstijn",
"author_id": 7185314,
"author_profile": "https://Stackoverflow.com/users/7185314",
"pm_score": 1,
"selected": false,
"text": "<p>Replace the canvas with your image and it will work the same</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>let img = document.getElementById(\"canvas\");\r\n\r\nimg.x = img.getBoundingClientRect().left;\r\nimg.y = img.getBoundingClientRect().top;\r\n\r\nfunction click(e) {\r\n document.getElementById(\"output\").innerHTML = \"X coords: \" + (e.clientX - img.x) + \"<br> Y coords: \" + (e.clientY - img.y);\r\n}\r\n\r\nimg.addEventListener(\"click\", click);</code></pre>\r\n<pre class=\"snippet-code-html lang-html prettyprint-override\"><code><!--- Like a image --->\r\n<canvas id=\"canvas\" width=\"100\" height=\"100\"></canvas>\r\n<p id=\"output\"></p></code></pre>\r\n</div>\r\n</div>\r\n</p>\n"
}
] | 2008/08/21 | [
"https://Stackoverflow.com/questions/19461",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1384652/"
] | I have a standard HTML image tag with an image in it, 100 by 100 pixels in size. I want people to be able to click the image and for that to pass the X and Y that they click into a function.
The coordinates need to be relative to the image top and left. | I think you're talking about:
```
<input id="info" type="image">
```
When submitted, there are form values for the x and y coordinate based on the input element id (`info.x` and `info.y` in this case).
<http://www.w3.org/TR/REC-html40/interact/forms.html#h-17.4.1> |
19,466 | <p>How can I check <code>file permissions</code>, without having to run operating system specific command via <code>passthru()</code> or <code>exec()</code>?</p>
| [
{
"answer_id": 19469,
"author": "Chris Hanson",
"author_id": 714,
"author_profile": "https://Stackoverflow.com/users/714",
"pm_score": 0,
"selected": false,
"text": "<p>What do you want to do by checking file permissions?</p>\n\n<p>When writing secure code, it's almost always incorrect to \"check, then do\" anything. The reason is that between the checking whether you can do something and actually doing it, the state of the system could change such that doing it would have a different result.</p>\n\n<p>For example, if you check whether a file exists before writing one, don't check whether you wrote the file successfully (or don't check in a detailed-enough fashion), and then later depend on the contents of the file you wrote, you could actually be reading a file written by an attacker.</p>\n\n<p>So instead of checking file permissions, just do whatever it was you were going to do if the permissions check succeeded, and handle errors gracefully.</p>\n"
},
{
"answer_id": 19470,
"author": "Huppie",
"author_id": 1830,
"author_profile": "https://Stackoverflow.com/users/1830",
"pm_score": 4,
"selected": false,
"text": "<p>You can use the <a href=\"http://www.php.net/manual/en/function.is-readable.php\" rel=\"noreferrer\">is_readable()</a>, <a href=\"http://www.php.net/manual/en/function.is-executable.php\" rel=\"noreferrer\">is_executable()</a> etc.. commands.</p>\n"
},
{
"answer_id": 19472,
"author": "Željko Živković",
"author_id": 1926,
"author_profile": "https://Stackoverflow.com/users/1926",
"pm_score": 6,
"selected": true,
"text": "<p>Use <a href=\"http://php.net/fileperms\" rel=\"noreferrer\">fileperms()</a> function</p>\n\n<pre><code>clearstatcache();\necho substr(sprintf('%o', fileperms('/etc/passwd')), -4);\n</code></pre>\n"
},
{
"answer_id": 11434314,
"author": "OzzyCzech",
"author_id": 355316,
"author_profile": "https://Stackoverflow.com/users/355316",
"pm_score": 1,
"selected": false,
"text": "<p>Use <a href=\"http://php.net/manual/en/function.fileperms.php\" rel=\"nofollow\">fileperms()</a> function and substring:</p>\n\n<pre><code>substr(decoct(fileperms(__DIR__)), -4); // 0777\nsubstr(decoct(fileperms(__DIR__)), -3); // 777\n</code></pre>\n\n<p>For file:</p>\n\n<pre><code>substr(decoct(fileperms(__FILE__)), -4); // 0644\nsubstr(decoct(fileperms(__FILE__)), -3); // 644\n</code></pre>\n\n<p>Replace <code>__FILE__</code> and <code>__DIR__</code> with your path or variable</p>\n"
},
{
"answer_id": 16083949,
"author": "Maciej Sz",
"author_id": 1697320,
"author_profile": "https://Stackoverflow.com/users/1697320",
"pm_score": 3,
"selected": false,
"text": "<p>Real coders use bitwise operations, not strings ;) This is much more elegant way of handling permissions:</p>\n\n<pre><code>function checkPerms($path)\n{\n clearstatcache(null, $path);\n return decoct( fileperms($path) & 0777 );\n}\n</code></pre>\n"
}
] | 2008/08/21 | [
"https://Stackoverflow.com/questions/19466",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/115/"
] | How can I check `file permissions`, without having to run operating system specific command via `passthru()` or `exec()`? | Use [fileperms()](http://php.net/fileperms) function
```
clearstatcache();
echo substr(sprintf('%o', fileperms('/etc/passwd')), -4);
``` |
19,516 | <p>Here is a simplification of my database:</p>
<pre>Table: Property
Fields: ID, Address
Table: Quote
Fields: ID, PropertyID, BespokeQuoteFields...
Table: Job
Fields: ID, PropertyID, BespokeJobFields...</pre>
<p>Then we have other tables that relate to the <strong>Quote</strong> and <strong>Job</strong> tables individually.</p>
<p>I now need to add a <strong>Message</strong> table where users can record telephone messages left by customers regarding Jobs and Quotes.</p>
<p>I could create two identical tables (<strong>QuoteMessage</strong> and <strong>JobMessage</strong>), but this violates the DRY principal and seems messy.</p>
<p>I could create one <strong>Message</strong> table:</p>
<pre>Table: Message
Fields: ID, RelationID, RelationType, OtherFields...</pre>
<p>But this stops me from using constraints to enforce my referential integrity. I can also forsee it creating problems with the devlopment side using Linq to SQL later on.</p>
<p>Is there an elegant solution to this problem, or am I ultimately going to have to hack something together?</p>
<p>Burns</p>
| [
{
"answer_id": 19521,
"author": "Ian Nelson",
"author_id": 2084,
"author_profile": "https://Stackoverflow.com/users/2084",
"pm_score": 3,
"selected": true,
"text": "<p>Create one Message table, containing a unique MessageId and the various properties you need to store for a message.</p>\n\n<pre><code>Table: Message\nFields: Id, TimeReceived, MessageDetails, WhateverElse...\n</code></pre>\n\n<p>Create two link tables - QuoteMessage and JobMessage. These will just contain two fields each, foreign keys to the Quote/Job and the Message.</p>\n\n<pre><code>Table: QuoteMessage\nFields: QuoteId, MessageId\n\nTable: JobMessage\nFields: JobId, MessageId\n</code></pre>\n\n<p>In this way you have defined the data properties of a Message in one place only (making it easy to extend, and to query across all messages), but you also have the referential integrity linking Quotes and Jobs to any number of messages. Indeed, both a Quote and Job could be linked to the <em>same</em> message (I'm not sure if that is appropriate to your business model, but at least the data model gives you the option).</p>\n"
},
{
"answer_id": 19545,
"author": "Mark Brackett",
"author_id": 2199,
"author_profile": "https://Stackoverflow.com/users/2199",
"pm_score": 1,
"selected": false,
"text": "<p>About the only other way I can think of is to have a base Message table, with both an Id and a TypeId. Your subtables (QuoteMessage and JobMessage) then reference the base table on both MessageId and TypeId - but also have CHECK CONSTRAINTS on them to enforce only the appropiate MessageTypeId.</p>\n\n<pre><code>Table: Message\nFields: Id, MessageTypeId, Text, ...\nPrimary Key: Id, MessageTypeId\nUnique: Id\n\nTable: MessageType\nFields: Id, Name\nValues: 1, \"Quote\" : 2, \"Job\"\n\nTable: QuoteMessage\nFields: Id, MessageId, MessageTypeId, QuoteId\nConstraints: MessageTypeId = 1\nReferences: (MessageId, MessageTypeId) = (Message.Id, Message.MessageTypeId)\n QuoteId = Quote.QuoteId\n\nTable: JobMessage\nFields: Id, MessageId, MessageTypeId, JobId\nConstraints: MessageTypeId = 2\nReferences: (MessageId, MessageTypeId) = (Message.Id, Message.MessageTypeId)\n JobId = Job.QuoteId\n</code></pre>\n\n<p>What does this buy you, as compared to just a JobMesssage and QuoteMessage table? It elevates a Message to a first class citizen, so that you can read all Messages from a single table. In exchange, your query path from a Message to it's relevant Quote or Job is 1 more join away. It kind of depends on your app flow whether that's a good tradeoff or not.</p>\n\n<p>As for 2 identical tables violating DRY - I wouldn't get hung up on that. In DB design, it's less about DRY, and more about normalization. If the 2 things you're modeling have the same attributes (columns), but are actually different things (tables) - then it's reasonable to have multiple tables with similar schemas. Much better than the reverse of munging different things together.</p>\n"
},
{
"answer_id": 19670,
"author": "Guy",
"author_id": 993,
"author_profile": "https://Stackoverflow.com/users/993",
"pm_score": 1,
"selected": false,
"text": "<p>@burns</p>\n\n<p>Ian's answer (+1) is correct <em>[see note]</em>. Using a many to many table <code>QUOTEMESSAGE</code> to join <code>QUOTE</code> to <code>MESSAGE</code> is the most correct model, but will leave orphaned <code>MESSAGE</code> records.</p>\n\n<p>This is one of those <em>rare</em> cases where a trigger can be used. However, caution needs to be applied to ensure that the a single <code>MESSAGE</code> record cannot be associated with both a <code>QUOTE</code> and a <code>JOB</code>.</p>\n\n<pre><code>create trigger quotemessage_trg\non quotemessage\nfor delete\nas\nbegin\n\ndelete \nfrom [message] \nwhere [message].[msg_id] in \n (select [msg_id] from Deleted);\n\nend\n</code></pre>\n\n<p><em>Note to Ian, I think there is a typo in the table definition for <code>JobMessage</code>, where the columns should be <code>JobId, MessageId</code> (?). I would edit your quote but it might take me a few years to gain that level of reputation!</em></p>\n"
},
{
"answer_id": 20935,
"author": "Blorgbeard",
"author_id": 369,
"author_profile": "https://Stackoverflow.com/users/369",
"pm_score": 0,
"selected": false,
"text": "<p>Why not just have both QuoteId and JobId fields in the message table? Or does a message have to be regarding either a quote or a job and not both?</p>\n"
}
] | 2008/08/21 | [
"https://Stackoverflow.com/questions/19516",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/366/"
] | Here is a simplification of my database:
```
Table: Property
Fields: ID, Address
Table: Quote
Fields: ID, PropertyID, BespokeQuoteFields...
Table: Job
Fields: ID, PropertyID, BespokeJobFields...
```
Then we have other tables that relate to the **Quote** and **Job** tables individually.
I now need to add a **Message** table where users can record telephone messages left by customers regarding Jobs and Quotes.
I could create two identical tables (**QuoteMessage** and **JobMessage**), but this violates the DRY principal and seems messy.
I could create one **Message** table:
```
Table: Message
Fields: ID, RelationID, RelationType, OtherFields...
```
But this stops me from using constraints to enforce my referential integrity. I can also forsee it creating problems with the devlopment side using Linq to SQL later on.
Is there an elegant solution to this problem, or am I ultimately going to have to hack something together?
Burns | Create one Message table, containing a unique MessageId and the various properties you need to store for a message.
```
Table: Message
Fields: Id, TimeReceived, MessageDetails, WhateverElse...
```
Create two link tables - QuoteMessage and JobMessage. These will just contain two fields each, foreign keys to the Quote/Job and the Message.
```
Table: QuoteMessage
Fields: QuoteId, MessageId
Table: JobMessage
Fields: JobId, MessageId
```
In this way you have defined the data properties of a Message in one place only (making it easy to extend, and to query across all messages), but you also have the referential integrity linking Quotes and Jobs to any number of messages. Indeed, both a Quote and Job could be linked to the *same* message (I'm not sure if that is appropriate to your business model, but at least the data model gives you the option). |
19,517 | <p>I was reading the example chapter from <a href="http://www.manning.com/rahien/" rel="nofollow noreferrer">the book by Ayende</a> and on the website of <a href="http://boo.codehaus.org/" rel="nofollow noreferrer">the Boo language</a> I saw a reference to the <a href="http://specter.sourceforge.net/" rel="nofollow noreferrer">Specter BDD Framework</a>.</p>
<p>I am wondering if anybody is using it in their project, how that works out and if there are more examples and/or suggested readings.</p>
<p>Just in case you are wondering, I'm a C# developer and so I plan to use it in a C#/.NET environment.</p>
<hr>
<p>A few year later visiting this question. I think we can safely assume <a href="http://www.specflow.org/" rel="nofollow noreferrer">Specflow</a> and some others like <a href="http://nspec.org/" rel="nofollow noreferrer">NSpec</a> became the tools we are using.</p>
| [
{
"answer_id": 19521,
"author": "Ian Nelson",
"author_id": 2084,
"author_profile": "https://Stackoverflow.com/users/2084",
"pm_score": 3,
"selected": true,
"text": "<p>Create one Message table, containing a unique MessageId and the various properties you need to store for a message.</p>\n\n<pre><code>Table: Message\nFields: Id, TimeReceived, MessageDetails, WhateverElse...\n</code></pre>\n\n<p>Create two link tables - QuoteMessage and JobMessage. These will just contain two fields each, foreign keys to the Quote/Job and the Message.</p>\n\n<pre><code>Table: QuoteMessage\nFields: QuoteId, MessageId\n\nTable: JobMessage\nFields: JobId, MessageId\n</code></pre>\n\n<p>In this way you have defined the data properties of a Message in one place only (making it easy to extend, and to query across all messages), but you also have the referential integrity linking Quotes and Jobs to any number of messages. Indeed, both a Quote and Job could be linked to the <em>same</em> message (I'm not sure if that is appropriate to your business model, but at least the data model gives you the option).</p>\n"
},
{
"answer_id": 19545,
"author": "Mark Brackett",
"author_id": 2199,
"author_profile": "https://Stackoverflow.com/users/2199",
"pm_score": 1,
"selected": false,
"text": "<p>About the only other way I can think of is to have a base Message table, with both an Id and a TypeId. Your subtables (QuoteMessage and JobMessage) then reference the base table on both MessageId and TypeId - but also have CHECK CONSTRAINTS on them to enforce only the appropiate MessageTypeId.</p>\n\n<pre><code>Table: Message\nFields: Id, MessageTypeId, Text, ...\nPrimary Key: Id, MessageTypeId\nUnique: Id\n\nTable: MessageType\nFields: Id, Name\nValues: 1, \"Quote\" : 2, \"Job\"\n\nTable: QuoteMessage\nFields: Id, MessageId, MessageTypeId, QuoteId\nConstraints: MessageTypeId = 1\nReferences: (MessageId, MessageTypeId) = (Message.Id, Message.MessageTypeId)\n QuoteId = Quote.QuoteId\n\nTable: JobMessage\nFields: Id, MessageId, MessageTypeId, JobId\nConstraints: MessageTypeId = 2\nReferences: (MessageId, MessageTypeId) = (Message.Id, Message.MessageTypeId)\n JobId = Job.QuoteId\n</code></pre>\n\n<p>What does this buy you, as compared to just a JobMesssage and QuoteMessage table? It elevates a Message to a first class citizen, so that you can read all Messages from a single table. In exchange, your query path from a Message to it's relevant Quote or Job is 1 more join away. It kind of depends on your app flow whether that's a good tradeoff or not.</p>\n\n<p>As for 2 identical tables violating DRY - I wouldn't get hung up on that. In DB design, it's less about DRY, and more about normalization. If the 2 things you're modeling have the same attributes (columns), but are actually different things (tables) - then it's reasonable to have multiple tables with similar schemas. Much better than the reverse of munging different things together.</p>\n"
},
{
"answer_id": 19670,
"author": "Guy",
"author_id": 993,
"author_profile": "https://Stackoverflow.com/users/993",
"pm_score": 1,
"selected": false,
"text": "<p>@burns</p>\n\n<p>Ian's answer (+1) is correct <em>[see note]</em>. Using a many to many table <code>QUOTEMESSAGE</code> to join <code>QUOTE</code> to <code>MESSAGE</code> is the most correct model, but will leave orphaned <code>MESSAGE</code> records.</p>\n\n<p>This is one of those <em>rare</em> cases where a trigger can be used. However, caution needs to be applied to ensure that the a single <code>MESSAGE</code> record cannot be associated with both a <code>QUOTE</code> and a <code>JOB</code>.</p>\n\n<pre><code>create trigger quotemessage_trg\non quotemessage\nfor delete\nas\nbegin\n\ndelete \nfrom [message] \nwhere [message].[msg_id] in \n (select [msg_id] from Deleted);\n\nend\n</code></pre>\n\n<p><em>Note to Ian, I think there is a typo in the table definition for <code>JobMessage</code>, where the columns should be <code>JobId, MessageId</code> (?). I would edit your quote but it might take me a few years to gain that level of reputation!</em></p>\n"
},
{
"answer_id": 20935,
"author": "Blorgbeard",
"author_id": 369,
"author_profile": "https://Stackoverflow.com/users/369",
"pm_score": 0,
"selected": false,
"text": "<p>Why not just have both QuoteId and JobId fields in the message table? Or does a message have to be regarding either a quote or a job and not both?</p>\n"
}
] | 2008/08/21 | [
"https://Stackoverflow.com/questions/19517",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4367/"
] | I was reading the example chapter from [the book by Ayende](http://www.manning.com/rahien/) and on the website of [the Boo language](http://boo.codehaus.org/) I saw a reference to the [Specter BDD Framework](http://specter.sourceforge.net/).
I am wondering if anybody is using it in their project, how that works out and if there are more examples and/or suggested readings.
Just in case you are wondering, I'm a C# developer and so I plan to use it in a C#/.NET environment.
---
A few year later visiting this question. I think we can safely assume [Specflow](http://www.specflow.org/) and some others like [NSpec](http://nspec.org/) became the tools we are using. | Create one Message table, containing a unique MessageId and the various properties you need to store for a message.
```
Table: Message
Fields: Id, TimeReceived, MessageDetails, WhateverElse...
```
Create two link tables - QuoteMessage and JobMessage. These will just contain two fields each, foreign keys to the Quote/Job and the Message.
```
Table: QuoteMessage
Fields: QuoteId, MessageId
Table: JobMessage
Fields: JobId, MessageId
```
In this way you have defined the data properties of a Message in one place only (making it easy to extend, and to query across all messages), but you also have the referential integrity linking Quotes and Jobs to any number of messages. Indeed, both a Quote and Job could be linked to the *same* message (I'm not sure if that is appropriate to your business model, but at least the data model gives you the option). |
19,553 | <p>I have a "Status" class in C#, used like this:</p>
<pre><code>Status MyFunction()
{
if(...) // something bad
return new Status(false, "Something went wrong")
else
return new Status(true, "OK");
}
</code></pre>
<p>You get the idea.
All callers of MyFunction <em>should</em> check the returned Status:</p>
<pre><code>Status myStatus = MyFunction();
if ( ! myStatus.IsOK() )
// handle it, show a message,...
</code></pre>
<p>Lazy callers however can ignore the Status.</p>
<pre><code>MyFunction(); // call function and ignore returned Status
</code></pre>
<p>or </p>
<pre><code>{
Status myStatus = MyFunction();
} // lose all references to myStatus, without calling IsOK() on it
</code></pre>
<p>Is it possible to make this impossible? e.g. an throw exception</p>
<p><strong>In general</strong>: is it possible to write a C# class on which you <em>have</em> to call a certain function?</p>
<p>In the C++ version of the Status class, I can write a test on some private bool bIsChecked in the <em>destructor</em> and ring some bells when someone doesn't check this instance.</p>
<p>What is the equivalent option in C#?
I read somewhere that "You don't want a destructor in your C# class"</p>
<p>Is the Dispose method of the IDisposable interface an option?</p>
<p>In this case there are no unmanaged resources to free.
Additionally, it is not determined <em>when</em> the GC will dispose the object.
When it eventually gets disposed, is it still possible to know where and when you ignored that specific Status instance?
The "using" keyword does help, but again, it is not <em>required</em> for lazy callers.</p>
| [
{
"answer_id": 19560,
"author": "Ian Nelson",
"author_id": 2084,
"author_profile": "https://Stackoverflow.com/users/2084",
"pm_score": 3,
"selected": false,
"text": "<p>I know this doesn't answer your question directly, but if \"something went wrong\" within your function (unexpected circumstances) I think you should be throwing an exception rather than using status return codes.</p>\n\n<p>Then leave it up to the caller to catch and handle this exception if it can, or allow it to propogate if the caller is unable to handle the situation.</p>\n\n<p>The exception thrown could be of a custom type if this is appropriate.</p>\n\n<p>For <em>expected</em> alternative results, I agree with @Jon Limjap's suggestion. I'm fond of a bool return type and prefixing the method name with \"Try\", a la:</p>\n\n<pre><code>bool TryMyFunction(out Status status)\n{\n}\n</code></pre>\n"
},
{
"answer_id": 19561,
"author": "TK.",
"author_id": 1816,
"author_profile": "https://Stackoverflow.com/users/1816",
"pm_score": 0,
"selected": false,
"text": "<p>You can throw an exception by:</p>\n\n<pre><code>throw MyException;\n\n\n[global::System.Serializable]\n public class MyException : Exception\n {\n //\n // For guidelines regarding the creation of new exception types, see\n // http://msdn.microsoft.com/library/default.asp?url=/library/en-us/cpgenref/html/cpconerrorraisinghandlingguidelines.asp\n // and\n // http://msdn.microsoft.com/library/default.asp?url=/library/en-us/dncscol/html/csharp07192001.asp\n //\n\n public MyException () { }\n public MyException ( string message ) : base( message ) { }\n public MyException ( string message, Exception inner ) : base( message, inner ) { }\n protected MyException (\n System.Runtime.Serialization.SerializationInfo info,\n System.Runtime.Serialization.StreamingContext context )\n : base( info, context ) { }\n }\n</code></pre>\n\n<p>The above exception is fully customizable to your requirements.</p>\n\n<p>One thing I would say is this, I would leave it to the caller to check the return code, it is their responsability you just provide the means and interface. Also, It is a lot more efficient to use return codes and check the status with an if statement rather than trhowing exceptions. If it really is an <em>Exceptional</em> circumstance, then by all means throw away... but say if you failed to open a device, then it might be more prudent to stick with the return code.</p>\n"
},
{
"answer_id": 19569,
"author": "fulmicoton",
"author_id": 446497,
"author_profile": "https://Stackoverflow.com/users/446497",
"pm_score": 0,
"selected": false,
"text": "<p>That would sure be nice to have the compiler check that rather than through an expression. :/\nDon't see any way to do that though...</p>\n"
},
{
"answer_id": 19572,
"author": "Auron",
"author_id": 1679,
"author_profile": "https://Stackoverflow.com/users/1679",
"pm_score": 1,
"selected": false,
"text": "<p>Using Status as a return value remembers me of the \"old days\" of C programming, when you returned an integer below 0 if something didn't work. </p>\n\n<p>Wouldn't it be better if you throw an exception when (as you put it) <em>something went wrong</em>? If some \"lazy code\" doesn't catch your exception, you'll know for sure.</p>\n"
},
{
"answer_id": 19586,
"author": "Mark Cidade",
"author_id": 1659,
"author_profile": "https://Stackoverflow.com/users/1659",
"pm_score": 2,
"selected": false,
"text": "<p>Even System.Net.WebRequest throws an exception when the returned HTTP status code is an error code. The typical way to handle it is to wrap a try/catch around it. You can still ignore the status code in the catch block.</p>\n\n<p>You could, however, have a parameter of Action< Status> so that the caller is forced to pass a callback function that accepts a status and then checking to see if they called it.</p>\n\n<pre><code>void MyFunction(Action<Status> callback)\n { bool errorHappened = false;\n\n if (somethingBadHappend) errorHappened = true;\n\n Status status = (errorHappend)\n ? new Status(false, \"Something went wrong\")\n : new Status(true, \"OK\");\n callback(status)\n\n if (!status.isOkWasCalled) \n throw new Exception(\"Please call IsOK() on Status\"). \n }\n\nMyFunction(status => if (!status.IsOK()) onerror());\n</code></pre>\n\n<p>If you're worried about them calling IsOK() without doing anything, use Expression< Func< Status,bool>> instead and then you can analyse the lambda to see what they do with the status:</p>\n\n<pre><code>void MyFunction(Expression<Func<Status,bool>> callback)\n { if (!visitCallbackExpressionTreeAndCheckForIsOKHandlingPattern(callback))\n throw new Exception\n (\"Please handle any error statuses in your callback\");\n\n\n bool errorHappened = false;\n\n if (somethingBadHappend) errorHappened = true;\n\n Status status = (errorHappend)\n ? new Status(false, \"Something went wrong\")\n : new Status(true, \"OK\");\n\n callback.Compile()(status);\n }\n\nMyFunction(status => status.IsOK() ? true : onerror());\n</code></pre>\n\n<p>Or forego the status class altogether and make them pass in one delegate for success and another one for an error:</p>\n\n<pre><code>void MyFunction(Action success, Action error)\n { if (somethingBadHappened) error(); else success();\n }\n\nMyFunction(()=>;,()=>handleError()); \n</code></pre>\n"
},
{
"answer_id": 19590,
"author": "Jon Limjap",
"author_id": 372,
"author_profile": "https://Stackoverflow.com/users/372",
"pm_score": 3,
"selected": false,
"text": "<p>If you really want to require the user to retrieve the result of MyFunction, you might want to void it instead and use an out or ref variable, e.g.,</p>\n\n<pre><code>void MyFunction(out Status status)\n{\n}\n</code></pre>\n\n<p>It might look ugly but at least it ensures that a variable is passed into the function that will pick up the result you need it to pick up.</p>\n\n<p>@Ian,</p>\n\n<p>The problem with exceptions is that if it's something that happens a little too often, you might be spending too much system resources for the exception. An exception really should be used for <em>exceptional</em> errors, not totally expected messages.</p>\n"
},
{
"answer_id": 19591,
"author": "pauldoo",
"author_id": 755,
"author_profile": "https://Stackoverflow.com/users/755",
"pm_score": 0,
"selected": false,
"text": "<p>GCC has a <a href=\"http://gcc.gnu.org/onlinedocs/gcc/Function-Attributes.html\" rel=\"nofollow noreferrer\"><code>warn_unused_result</code></a> attribute which is ideal for this sort of thing. Perhaps the Microsoft compilers have something similar.</p>\n"
},
{
"answer_id": 19599,
"author": "Mark Cidade",
"author_id": 1659,
"author_profile": "https://Stackoverflow.com/users/1659",
"pm_score": 0,
"selected": false,
"text": "<p>@Paul you could do it at compile time with <a href=\"http://www.google.com/search?hl=en&rls=com.microsoft%3Aen-us&q=%22extensible+C%23%22\" rel=\"nofollow noreferrer\">Extensible C#</a>.</p>\n"
},
{
"answer_id": 19661,
"author": "kemiller2002",
"author_id": 1942,
"author_profile": "https://Stackoverflow.com/users/1942",
"pm_score": 1,
"selected": false,
"text": "<p>Instead of forcing someone to check the status, I think you should assume the programmer is aware of this risks of not doing so and has a reason for taking that course of action. You don't know how the function is going to be used in the future and placing a limitation like that only restricts the possibilities.</p>\n"
},
{
"answer_id": 19835,
"author": "Weeble",
"author_id": 2283,
"author_profile": "https://Stackoverflow.com/users/2283",
"pm_score": 3,
"selected": true,
"text": "<p>I am fairly certain you can't get the effect you want as a return value from a method. C# just can't do some of the things C++ can. However, a somewhat ugly way to get a similar effect is the following:</p>\n\n<pre><code>using System;\n\npublic class Example\n{\n public class Toy\n {\n private bool inCupboard = false;\n public void Play() { Console.WriteLine(\"Playing.\"); }\n public void PutAway() { inCupboard = true; }\n public bool IsInCupboard { get { return inCupboard; } }\n }\n\n public delegate void ToyUseCallback(Toy toy);\n\n public class Parent\n {\n public static void RequestToy(ToyUseCallback callback)\n {\n Toy toy = new Toy();\n callback(toy);\n if (!toy.IsInCupboard)\n {\n throw new Exception(\"You didn't put your toy in the cupboard!\");\n }\n }\n }\n\n public class Child\n {\n public static void Play()\n {\n Parent.RequestToy(delegate(Toy toy)\n {\n toy.Play();\n // Oops! Forgot to put the toy away!\n });\n }\n }\n\n public static void Main()\n {\n Child.Play();\n Console.ReadLine();\n }\n}\n</code></pre>\n\n<p>In the very simple example, you get an instance of Toy by calling Parent.RequestToy, <em>and passing it a delegate</em>. Instead of returning the toy, the method immediately calls the delegate with the toy, which must call PutAway before it returns, or the RequestToy method will throw an exception. I make no claims as to the wisdom of using this technique -- indeed in all \"something went wrong\" examples an exception is almost certainly a better bet -- but I think it comes about as close as you can get to your original request.</p>\n"
},
{
"answer_id": 26170051,
"author": "supercat",
"author_id": 363751,
"author_profile": "https://Stackoverflow.com/users/363751",
"pm_score": 0,
"selected": false,
"text": "<p>One pattern which may sometimes be helpful if the object to which code issues requests will only be used by a single thread(*) is to have the object keep an error state, and say that if an operation fails the object will be unusable until the error state is reset (future requests should fail immediately, preferably by throwing an immediate exception which includes information about both the previous failure and the new request). In cases where calling code happens to anticipate a problem, this may allow the calling code to handle the problem more cleanly than if an exception were thrown; problems which are not ignored by the calling code will generally end up triggering an exception pretty soon after they occur.</p>\n\n<p>(*) If a resource will be accessed by multiple threads, create a wrapper object for each thread, and have each thread's requests go through its own wrapper.</p>\n\n<p>This pattern is usable even in contexts where exceptions aren't, and may sometimes be very practical in such cases. In general, however, some variation of the try/do pattern is usually better. Have methods throw exception on failure unless the caller explicitly indicates (by using a <code>TryXX</code> method) that failures are expected. If callers say failures are expected but don't handle them, that's their problem. One could combine the try/do with a second layer of protection using the scheme above, but I'm not sure whether it would be worth the cost.</p>\n"
}
] | 2008/08/21 | [
"https://Stackoverflow.com/questions/19553",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1163/"
] | I have a "Status" class in C#, used like this:
```
Status MyFunction()
{
if(...) // something bad
return new Status(false, "Something went wrong")
else
return new Status(true, "OK");
}
```
You get the idea.
All callers of MyFunction *should* check the returned Status:
```
Status myStatus = MyFunction();
if ( ! myStatus.IsOK() )
// handle it, show a message,...
```
Lazy callers however can ignore the Status.
```
MyFunction(); // call function and ignore returned Status
```
or
```
{
Status myStatus = MyFunction();
} // lose all references to myStatus, without calling IsOK() on it
```
Is it possible to make this impossible? e.g. an throw exception
**In general**: is it possible to write a C# class on which you *have* to call a certain function?
In the C++ version of the Status class, I can write a test on some private bool bIsChecked in the *destructor* and ring some bells when someone doesn't check this instance.
What is the equivalent option in C#?
I read somewhere that "You don't want a destructor in your C# class"
Is the Dispose method of the IDisposable interface an option?
In this case there are no unmanaged resources to free.
Additionally, it is not determined *when* the GC will dispose the object.
When it eventually gets disposed, is it still possible to know where and when you ignored that specific Status instance?
The "using" keyword does help, but again, it is not *required* for lazy callers. | I am fairly certain you can't get the effect you want as a return value from a method. C# just can't do some of the things C++ can. However, a somewhat ugly way to get a similar effect is the following:
```
using System;
public class Example
{
public class Toy
{
private bool inCupboard = false;
public void Play() { Console.WriteLine("Playing."); }
public void PutAway() { inCupboard = true; }
public bool IsInCupboard { get { return inCupboard; } }
}
public delegate void ToyUseCallback(Toy toy);
public class Parent
{
public static void RequestToy(ToyUseCallback callback)
{
Toy toy = new Toy();
callback(toy);
if (!toy.IsInCupboard)
{
throw new Exception("You didn't put your toy in the cupboard!");
}
}
}
public class Child
{
public static void Play()
{
Parent.RequestToy(delegate(Toy toy)
{
toy.Play();
// Oops! Forgot to put the toy away!
});
}
}
public static void Main()
{
Child.Play();
Console.ReadLine();
}
}
```
In the very simple example, you get an instance of Toy by calling Parent.RequestToy, *and passing it a delegate*. Instead of returning the toy, the method immediately calls the delegate with the toy, which must call PutAway before it returns, or the RequestToy method will throw an exception. I make no claims as to the wisdom of using this technique -- indeed in all "something went wrong" examples an exception is almost certainly a better bet -- but I think it comes about as close as you can get to your original request. |
19,589 | <p>Using C# .NET 3.5 and WCF, I'm trying to write out some of the WCF configuration in a client application (the name of the server the client is connecting to).</p>
<p>The obvious way is to use <code>ConfigurationManager</code> to load the configuration section and write out the data I need.</p>
<pre><code>var serviceModelSection = ConfigurationManager.GetSection("system.serviceModel");
</code></pre>
<p>Appears to always return null.</p>
<pre><code>var serviceModelSection = ConfigurationManager.GetSection("appSettings");
</code></pre>
<p>Works perfectly.</p>
<p>The configuration section is present in the App.config but for some reason <code>ConfigurationManager</code> refuses to load the <code>system.ServiceModel</code> section.</p>
<p>I want to avoid manually loading the xxx.exe.config file and using XPath but if I have to resort to that I will. Just seems like a bit of a hack.</p>
<p>Any suggestions?</p>
| [
{
"answer_id": 19594,
"author": "DavidWhitney",
"author_id": 1297,
"author_profile": "https://Stackoverflow.com/users/1297",
"pm_score": 6,
"selected": false,
"text": "<p><a href=\"http://mostlytech.blogspot.com/2007/11/programmatically-enumerate-wcf.html\" rel=\"noreferrer\">http://mostlytech.blogspot.com/2007/11/programmatically-enumerate-wcf.html</a></p>\n\n<pre><code>// Automagically find all client endpoints defined in app.config\nClientSection clientSection = \n ConfigurationManager.GetSection(\"system.serviceModel/client\") as ClientSection;\n\nChannelEndpointElementCollection endpointCollection =\n clientSection.ElementInformation.Properties[string.Empty].Value as ChannelEndpointElementCollection;\nList<string> endpointNames = new List<string>();\nforeach (ChannelEndpointElement endpointElement in endpointCollection)\n{\n endpointNames.Add(endpointElement.Name);\n}\n// use endpointNames somehow ...\n</code></pre>\n\n<p>Appears to work well.</p>\n"
},
{
"answer_id": 19596,
"author": "Mark Cidade",
"author_id": 1659,
"author_profile": "https://Stackoverflow.com/users/1659",
"pm_score": 7,
"selected": true,
"text": "<p>The <a href=\"http://msdn.microsoft.com/en-us/library/ms731354%28v=vs.90%29.aspx\" rel=\"noreferrer\"><code><system.serviceModel></code></a> element is for a configuration section <strong>group</strong>, not a section. You'll need to use <a href=\"http://msdn.microsoft.com/en-us/library/system.servicemodel.configuration.servicemodelsectiongroup.getsectiongroup%28v=vs.90%29.aspx\" rel=\"noreferrer\"><code>System.ServiceModel.Configuration.ServiceModelSectionGroup.GetSectionGroup()</code></a> to get the whole group.</p>\n"
},
{
"answer_id": 19602,
"author": "DavidWhitney",
"author_id": 1297,
"author_profile": "https://Stackoverflow.com/users/1297",
"pm_score": 4,
"selected": false,
"text": "<p>This is what I was looking for thanks to @marxidad for the pointer.</p>\n\n<pre><code> public static string GetServerName()\n {\n string serverName = \"Unknown\";\n\n Configuration appConfig = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);\n ServiceModelSectionGroup serviceModel = ServiceModelSectionGroup.GetSectionGroup(appConfig);\n BindingsSection bindings = serviceModel.Bindings;\n\n ChannelEndpointElementCollection endpoints = serviceModel.Client.Endpoints;\n\n for(int i=0; i<endpoints.Count; i++)\n {\n ChannelEndpointElement endpointElement = endpoints[i];\n if (endpointElement.Contract == \"MyContractName\")\n {\n serverName = endpointElement.Address.Host;\n }\n }\n\n return serverName;\n }\n</code></pre>\n"
},
{
"answer_id": 5986619,
"author": "midspace",
"author_id": 294393,
"author_profile": "https://Stackoverflow.com/users/294393",
"pm_score": 3,
"selected": false,
"text": "<p>GetSectionGroup() does not support no parameters (under framework 3.5).</p>\n\n<p>Instead use:</p>\n\n<pre><code>Configuration config = System.Configuration.ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);\nServiceModelSectionGroup group = System.ServiceModel.Configuration.ServiceModelSectionGroup.GetSectionGroup(config);\n</code></pre>\n"
},
{
"answer_id": 18844990,
"author": "Robin G Brown",
"author_id": 2771792,
"author_profile": "https://Stackoverflow.com/users/2771792",
"pm_score": 3,
"selected": false,
"text": "<p>Thanks to the other posters this is the function I developed to get the URI of a named endpoint. It also creates a listing of the endpoints in use and which actual config file was being used when debugging:</p>\n\n<pre><code>Private Function GetEndpointAddress(name As String) As String\n Debug.Print(\"--- GetEndpointAddress ---\")\n Dim address As String = \"Unknown\"\n Dim appConfig As Configuration = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None)\n Debug.Print(\"app.config: \" & appConfig.FilePath)\n Dim serviceModel As ServiceModelSectionGroup = ServiceModelSectionGroup.GetSectionGroup(appConfig)\n Dim bindings As BindingsSection = serviceModel.Bindings\n Dim endpoints As ChannelEndpointElementCollection = serviceModel.Client.Endpoints\n For i As Integer = 0 To endpoints.Count - 1\n Dim endpoint As ChannelEndpointElement = endpoints(i)\n Debug.Print(\"Endpoint: \" & endpoint.Name & \" - \" & endpoint.Address.ToString)\n If endpoint.Name = name Then\n address = endpoint.Address.ToString\n End If\n Next\n Debug.Print(\"--- GetEndpointAddress ---\")\n Return address\nEnd Function\n</code></pre>\n"
}
] | 2008/08/21 | [
"https://Stackoverflow.com/questions/19589",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1297/"
] | Using C# .NET 3.5 and WCF, I'm trying to write out some of the WCF configuration in a client application (the name of the server the client is connecting to).
The obvious way is to use `ConfigurationManager` to load the configuration section and write out the data I need.
```
var serviceModelSection = ConfigurationManager.GetSection("system.serviceModel");
```
Appears to always return null.
```
var serviceModelSection = ConfigurationManager.GetSection("appSettings");
```
Works perfectly.
The configuration section is present in the App.config but for some reason `ConfigurationManager` refuses to load the `system.ServiceModel` section.
I want to avoid manually loading the xxx.exe.config file and using XPath but if I have to resort to that I will. Just seems like a bit of a hack.
Any suggestions? | The [`<system.serviceModel>`](http://msdn.microsoft.com/en-us/library/ms731354%28v=vs.90%29.aspx) element is for a configuration section **group**, not a section. You'll need to use [`System.ServiceModel.Configuration.ServiceModelSectionGroup.GetSectionGroup()`](http://msdn.microsoft.com/en-us/library/system.servicemodel.configuration.servicemodelsectiongroup.getsectiongroup%28v=vs.90%29.aspx) to get the whole group. |
19,656 | <p>I have an Interface called <code>IStep</code> that can do some computation (See "<a href="http://steve-yegge.blogspot.com/2006/03/execution-in-kingdom-of-nouns.html" rel="nofollow noreferrer">Execution in the Kingdom of Nouns</a>"). At runtime, I want to select the appropriate implementation by class name.</p>
<pre>
// use like this:
IStep step = GetStep(sName);
</pre>
| [
{
"answer_id": 19658,
"author": "Ian Nelson",
"author_id": 2084,
"author_profile": "https://Stackoverflow.com/users/2084",
"pm_score": 2,
"selected": false,
"text": "<p>If the implementation has a parameterless constructor, you can do this using the System.Activator class. You will need to specify the assembly name in addition to the class name:</p>\n\n<pre><code>IStep step = System.Activator.CreateInstance(sAssemblyName, sClassName).Unwrap() as IStep;\n</code></pre>\n\n<p><a href=\"http://msdn.microsoft.com/en-us/library/system.activator.createinstance.aspx\" rel=\"nofollow noreferrer\">http://msdn.microsoft.com/en-us/library/system.activator.createinstance.aspx</a></p>\n"
},
{
"answer_id": 19663,
"author": "lubos hasko",
"author_id": 275,
"author_profile": "https://Stackoverflow.com/users/275",
"pm_score": 4,
"selected": true,
"text": "<p>Your question is very confusing...</p>\n\n<p>If you want to find types that implement IStep, then do this:</p>\n\n<pre><code>foreach (Type t in Assembly.GetCallingAssembly().GetTypes())\n{\n if (!typeof(IStep).IsAssignableFrom(t)) continue;\n Console.WriteLine(t.FullName + \" implements \" + typeof(IStep).FullName);\n}\n</code></pre>\n\n<p>If you know already the name of the required type, just do this</p>\n\n<pre><code>IStep step = (IStep)Activator.CreateInstance(Type.GetType(\"MyNamespace.MyType\"));\n</code></pre>\n"
},
{
"answer_id": 19667,
"author": "Daren Thomas",
"author_id": 2260,
"author_profile": "https://Stackoverflow.com/users/2260",
"pm_score": 1,
"selected": false,
"text": "<p>Based on what others have pointed out, this is what I ended up writing:</p>\n\n<pre>\n/// \n/// Some magic happens here: Find the correct action to take, by reflecting on types \n/// subclassed from IStep with that name.\n/// \nprivate IStep GetStep(string sName)\n{\n Assembly assembly = Assembly.GetAssembly(typeof (IStep));\n\n try\n {\n return (IStep) (from t in assembly.GetTypes()\n where t.Name == sName && t.GetInterface(\"IStep\") != null\n select t\n ).First().GetConstructor(new Type[] {}\n ).Invoke(new object[] {});\n }\n catch (InvalidOperationException e)\n {\n throw new ArgumentException(\"Action not supported: \" + sName, e);\n }\n}\n</pre>\n"
},
{
"answer_id": 19669,
"author": "samjudson",
"author_id": 1908,
"author_profile": "https://Stackoverflow.com/users/1908",
"pm_score": 0,
"selected": false,
"text": "<p>Well Assembly.CreateInstance would seem to be the way to go - the only problem with this is that it needs the fully qualified name of the type, i.e. including the namespace.</p>\n"
}
] | 2008/08/21 | [
"https://Stackoverflow.com/questions/19656",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2260/"
] | I have an Interface called `IStep` that can do some computation (See "[Execution in the Kingdom of Nouns](http://steve-yegge.blogspot.com/2006/03/execution-in-kingdom-of-nouns.html)"). At runtime, I want to select the appropriate implementation by class name.
```
// use like this:
IStep step = GetStep(sName);
``` | Your question is very confusing...
If you want to find types that implement IStep, then do this:
```
foreach (Type t in Assembly.GetCallingAssembly().GetTypes())
{
if (!typeof(IStep).IsAssignableFrom(t)) continue;
Console.WriteLine(t.FullName + " implements " + typeof(IStep).FullName);
}
```
If you know already the name of the required type, just do this
```
IStep step = (IStep)Activator.CreateInstance(Type.GetType("MyNamespace.MyType"));
``` |
19,708 | <p>To grab the inode of a file in PHP, you can use this:</p>
<pre><code>$fs = stat($file);
echo $fs['ino'];
</code></pre>
<p>The problem with this is EVERYWHERE says it's slow and you should avoid it. So the question becomes what's the fast(er) way to do it?</p>
| [
{
"answer_id": 19716,
"author": "mercutio",
"author_id": 1951,
"author_profile": "https://Stackoverflow.com/users/1951",
"pm_score": 2,
"selected": true,
"text": "<p>You could use <a href=\"http://php.net/fileinode\" rel=\"nofollow noreferrer\"><code>fileinode()</code></a> but you should run benchmarks if you think it is slow.</p>\n"
},
{
"answer_id": 21644,
"author": "Ryan Doherty",
"author_id": 956,
"author_profile": "https://Stackoverflow.com/users/956",
"pm_score": 0,
"selected": false,
"text": "<p>I think you should benchmark and take a look at what you are doing to determine if stat() is the slowest part of your code. Stating 1 file on each request on a server that gets about 100 hits/day is not a problem. Stating every file could be a problem when you have to eek out a few more requests a second.</p>\n\n<p>You can avoid stating the same file repeatedly by caching the results via memcached, apc or some other in-memory caching system.</p>\n\n<p>Premature optimization is the root of all evil. - Donald Knuth</p>\n"
}
] | 2008/08/21 | [
"https://Stackoverflow.com/questions/19708",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/497/"
] | To grab the inode of a file in PHP, you can use this:
```
$fs = stat($file);
echo $fs['ino'];
```
The problem with this is EVERYWHERE says it's slow and you should avoid it. So the question becomes what's the fast(er) way to do it? | You could use [`fileinode()`](http://php.net/fileinode) but you should run benchmarks if you think it is slow. |
19,725 | <p>Right, initially ran:</p>
<pre><code>c:\regsvr32 Amazing.dll
</code></pre>
<p>then, (accidentally - I might add) I must have run it again, and (indeed) again when new versions of 'Amazing.dll' were released. Yes - I know <em>now</em> I should've run:</p>
<pre><code>c:\regsvr32 /u Amazing.dll
</code></pre>
<p>beforehand - but hey! I forgot.</p>
<p>To cut to the chase, when add the COM reference in VS, I can see 3 instances of 'Amazing' all pointing to the same location (c:\Amazing.dll), running <code>regsvr32 /u</code> removes one of the references, the second time - does nothing...</p>
<p>How do I get rid of these references?
Am I looking at a regedit scenario? - If so - what <em>exactly</em> happens if I delete one of the keys???</p>
<p>Cheers</p>
| [
{
"answer_id": 19730,
"author": "Johnno Nolan",
"author_id": 1116,
"author_profile": "https://Stackoverflow.com/users/1116",
"pm_score": 0,
"selected": false,
"text": "<p>I've got myself into a horrible mess with COM before. I had to pick my way though the registry deleting each reference, unfortunately.</p>\n"
},
{
"answer_id": 19740,
"author": "Scott Marlowe",
"author_id": 1683,
"author_profile": "https://Stackoverflow.com/users/1683",
"pm_score": 5,
"selected": true,
"text": "<p>Your object's GUID's should not be changing. In other words, once you register the COM object, re-registering shouldn't be adding anything additional to the registry.</p>\n\n<p>Unless you added additional COM interfaces or objects to the project.</p>\n\n<p>In any case, if this is a one time deal (and it sounds like it is), open regedit and delete the unneeded keys manually.</p>\n"
},
{
"answer_id": 19770,
"author": "Shaun Austin",
"author_id": 1120,
"author_profile": "https://Stackoverflow.com/users/1120",
"pm_score": 2,
"selected": false,
"text": "<p>There's a tool by MS that is still floating around and has been since Win95 days which scans the registry and does stuff like finds COM keys that aren't pointing at a valid file anymore etc called RegClean (I found it here: <a href=\"http://downloads.zdnet.com/abstract.aspx?assetid=881470&node=2094\" rel=\"nofollow noreferrer\">http://downloads.zdnet.com/abstract.aspx?assetid=881470&node=2094</a>) which I've seen some places still using particularly when messing with legacy COM stuff in VB which are generating new COM GUIDs after every build.</p>\n\n<p>So if you got that, then unreg'd and deleted or moved the file, run the app and it will clean out the \"orphaned\" entries.</p>\n\n<p>If you do decide to remove the keys using RegEdit, you might need to remove the class ids as well as the guid entries. </p>\n"
}
] | 2008/08/21 | [
"https://Stackoverflow.com/questions/19725",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2266/"
] | Right, initially ran:
```
c:\regsvr32 Amazing.dll
```
then, (accidentally - I might add) I must have run it again, and (indeed) again when new versions of 'Amazing.dll' were released. Yes - I know *now* I should've run:
```
c:\regsvr32 /u Amazing.dll
```
beforehand - but hey! I forgot.
To cut to the chase, when add the COM reference in VS, I can see 3 instances of 'Amazing' all pointing to the same location (c:\Amazing.dll), running `regsvr32 /u` removes one of the references, the second time - does nothing...
How do I get rid of these references?
Am I looking at a regedit scenario? - If so - what *exactly* happens if I delete one of the keys???
Cheers | Your object's GUID's should not be changing. In other words, once you register the COM object, re-registering shouldn't be adding anything additional to the registry.
Unless you added additional COM interfaces or objects to the project.
In any case, if this is a one time deal (and it sounds like it is), open regedit and delete the unneeded keys manually. |
19,786 | <p>I am maintaining an app for a client that is used in two locations. One in England and one in Poland.</p>
<p>The database is stored in England and uses the format £1000.00 for currency, but the information is being gathered locally in Poland where 1000,00 is the format.</p>
<p>My question is, in VB6 is there a function that takes a currency string in a local format and converts to another, or will I just have to parse the string and replace , or . ?</p>
<p>BTW I have looked at CCur, but not sure if that will do what I want. </p>
| [
{
"answer_id": 19810,
"author": "Espo",
"author_id": 2257,
"author_profile": "https://Stackoverflow.com/users/2257",
"pm_score": 0,
"selected": false,
"text": "<p>What database are you using? And what data type is the amount stored in?</p>\n\n<p>As long as you are always converting from one format to another, you do not need to do any parsing, just replace \".\" with \",\" or the other way around. You may need to remove the \"£\"-sign as well if that is stored in your string.</p>\n"
},
{
"answer_id": 19854,
"author": "Kibbee",
"author_id": 1862,
"author_profile": "https://Stackoverflow.com/users/1862",
"pm_score": 0,
"selected": false,
"text": "<p>There's probably a correct answer dealing with culture objects and such, but the easiest way would be to taken the input from the polish input, and replace the , with a ., and then store it in your database as type \"money\" or \"decimal\". If you know they (possibly configurable per user) are always entering numbers in either Polish or English, you could have a function that you run all the input numbers through to convert the string to a proper \"decimal\" typed variable. Also, for display purposes you could run it through another similar function to ensure that the user always sees the number format they are comfortable with. The key here is to switch it to a decimal as soon as you get it from the user, and only switch it back to a string at the last step before sending it out to the user.</p>\n"
},
{
"answer_id": 19868,
"author": "Espo",
"author_id": 2257,
"author_profile": "https://Stackoverflow.com/users/2257",
"pm_score": 0,
"selected": false,
"text": "<p>@KiwiBastard yes i would think so. Are you storing your amount in an \"(n)varchar\" field or are you using a currency/decimal type field? If the latter is the case, the currency-symbols and separators are added by your client, and there would be no need to replace anything in the database.</p>\n"
},
{
"answer_id": 19920,
"author": "Joel Spolsky",
"author_id": 4,
"author_profile": "https://Stackoverflow.com/users/4",
"pm_score": 4,
"selected": true,
"text": "<p>The data is not actually stored as the string <code>"£1000.00"</code>; it's stored in some numeric format.</p>\n<blockquote>\n<p><strong>Sidebar:</strong> Usually databases are set up to store money amounts using either the <strong>decimal</strong> data type (also called <strong>money</strong> in some DBs), or as a floating point number (also called <strong>double</strong>).</p>\n<p>The difference is that when it's stored as <strong>decimal</strong> certain numbers like 0.01 are represented exactly whereas in <strong>double</strong> those numbers can only be stored approximately, causing rounding errors.</p>\n</blockquote>\n<p>The database <em>appears</em> to be storing the number as <code>"£1000.00"</code> because something is formatting it for display. In VB6, there's a function <code>FormatCurrency</code> which would take a number like 1000 and return a string like <code>"£1000.00"</code>.</p>\n<p>You'll notice that the <code>FormatCurrency</code> function does not take an argument specifying what type of currency to use. That's because it, along with all the other locale-specific functions in VB, figures out the currency from the current locale of the system (from the Windows Control Panel).</p>\n<p>That means that on my system,</p>\n<pre><code>Debug.Print FormatCurrency(1000)\n</code></pre>\n<p>will print <code>$1,000.00</code>, but if I run that same program on a Windows computer set to the UK locale, it will probably print <code>£1,000.00</code>, which, of course, is something completely different.</p>\n<p>Similarly, you've got some code, somewhere, I can't tell where, in Poland, it seems, that is responsible for parsing the user's string and converting it to a number. And if that code is in Visual Basic, again, it's relying on the control panel to decide whether "." or "," is the thousands separator and whether "," or "." is the decimal point.</p>\n<p>The function <code>CDbl</code> converts its argument to a number. So for example on my system in the US</p>\n<pre><code>Debug.Print CDbl("1.200")\n</code></pre>\n<p>produces the number one point two, on a system with the Control Panel set to European formatting, it would produce the number one thousand, two hundred.</p>\n<p>It's possible that the problem is that you have someone sitting a computer with the regional control panel set to use "." as the decimal separator, but they're typing "," as the decimal separator.</p>\n"
}
] | 2008/08/21 | [
"https://Stackoverflow.com/questions/19786",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1075/"
] | I am maintaining an app for a client that is used in two locations. One in England and one in Poland.
The database is stored in England and uses the format £1000.00 for currency, but the information is being gathered locally in Poland where 1000,00 is the format.
My question is, in VB6 is there a function that takes a currency string in a local format and converts to another, or will I just have to parse the string and replace , or . ?
BTW I have looked at CCur, but not sure if that will do what I want. | The data is not actually stored as the string `"£1000.00"`; it's stored in some numeric format.
>
> **Sidebar:** Usually databases are set up to store money amounts using either the **decimal** data type (also called **money** in some DBs), or as a floating point number (also called **double**).
>
>
> The difference is that when it's stored as **decimal** certain numbers like 0.01 are represented exactly whereas in **double** those numbers can only be stored approximately, causing rounding errors.
>
>
>
The database *appears* to be storing the number as `"£1000.00"` because something is formatting it for display. In VB6, there's a function `FormatCurrency` which would take a number like 1000 and return a string like `"£1000.00"`.
You'll notice that the `FormatCurrency` function does not take an argument specifying what type of currency to use. That's because it, along with all the other locale-specific functions in VB, figures out the currency from the current locale of the system (from the Windows Control Panel).
That means that on my system,
```
Debug.Print FormatCurrency(1000)
```
will print `$1,000.00`, but if I run that same program on a Windows computer set to the UK locale, it will probably print `£1,000.00`, which, of course, is something completely different.
Similarly, you've got some code, somewhere, I can't tell where, in Poland, it seems, that is responsible for parsing the user's string and converting it to a number. And if that code is in Visual Basic, again, it's relying on the control panel to decide whether "." or "," is the thousands separator and whether "," or "." is the decimal point.
The function `CDbl` converts its argument to a number. So for example on my system in the US
```
Debug.Print CDbl("1.200")
```
produces the number one point two, on a system with the Control Panel set to European formatting, it would produce the number one thousand, two hundred.
It's possible that the problem is that you have someone sitting a computer with the regional control panel set to use "." as the decimal separator, but they're typing "," as the decimal separator. |
19,787 | <p>Is it possible to look back through the history of a Subversion repository for files of a certain name (even better would be for them to have a wildcard search)?</p>
<p>I want to see if a <code>.bat</code> file has been committed to the repository at some point in the past but has since been removed in later updates. Even a dump of the file history at each revision would work, as I could just grep the output. I have looked through the manual but could not see a good way to do this.</p>
<p>The logs for each commit are descriptive, so I cannot just look through the log messages to see what modifications were done. I presume Subversion does have a way of retrieving this?</p>
| [
{
"answer_id": 19798,
"author": "Ishmaeel",
"author_id": 227,
"author_profile": "https://Stackoverflow.com/users/227",
"pm_score": 2,
"selected": false,
"text": "<p>I assume you are using the SVN command line client. Give TortoiseSVN a try. Its \"Show Log\" dialog allows searching for comments, filenames and authors.</p>\n\n<p><a href=\"http://tortoisesvn.net/downloads\" rel=\"nofollow noreferrer\">http://tortoisesvn.net/downloads</a></p>\n\n<p>PS: Windows only.</p>\n"
},
{
"answer_id": 19824,
"author": "Philip Reynolds",
"author_id": 1087,
"author_profile": "https://Stackoverflow.com/users/1087",
"pm_score": 0,
"selected": false,
"text": "<p>Personally I'd use</p>\n\n<pre><code>svnadmin dump -r1:HEAD /path/to/repo/\n</code></pre>\n\n<p>Pipe it into less and search or grep with some context.</p>\n"
},
{
"answer_id": 19826,
"author": "crashmstr",
"author_id": 1441,
"author_profile": "https://Stackoverflow.com/users/1441",
"pm_score": 6,
"selected": true,
"text": "<p>TortoiseSVN can search the logs very easily, and on my system I can enter \".plg\" in the search box and find all adds, modifies, and deletes for those files.</p>\n\n<p>Without Tortoise, the only way I can think of doing that would be to grep the full logs or parse the logs and do your own searching for 'A' and 'D' indicators on the file you are looking for (use <code>svn log --verbose</code> to get file paths).</p>\n\n<pre>\nsvn log --verbose | grep .bat\n</pre>\n"
},
{
"answer_id": 19846,
"author": "Owen",
"author_id": 2109,
"author_profile": "https://Stackoverflow.com/users/2109",
"pm_score": 2,
"selected": false,
"text": "<p>TortoiseSVN is completely sweet. I can't imagine dealing with Subversion without it.</p>\n\n<p>Also, as a long shot, if you're using Eclipse I'd recommend the Subclipse plug-in. </p>\n"
},
{
"answer_id": 633470,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 0,
"selected": false,
"text": "<p>svn log -v .bat</p>\n"
}
] | 2008/08/21 | [
"https://Stackoverflow.com/questions/19787",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/277/"
] | Is it possible to look back through the history of a Subversion repository for files of a certain name (even better would be for them to have a wildcard search)?
I want to see if a `.bat` file has been committed to the repository at some point in the past but has since been removed in later updates. Even a dump of the file history at each revision would work, as I could just grep the output. I have looked through the manual but could not see a good way to do this.
The logs for each commit are descriptive, so I cannot just look through the log messages to see what modifications were done. I presume Subversion does have a way of retrieving this? | TortoiseSVN can search the logs very easily, and on my system I can enter ".plg" in the search box and find all adds, modifies, and deletes for those files.
Without Tortoise, the only way I can think of doing that would be to grep the full logs or parse the logs and do your own searching for 'A' and 'D' indicators on the file you are looking for (use `svn log --verbose` to get file paths).
```
svn log --verbose | grep .bat
``` |
19,838 | <p>I've been trying to understand how Ruby blocks work, and to do that I've been trying to implement them in C.</p>
<p>One easy way to implement closures is to pass a <code>void*</code> to the enclosing stack to the closure/function but Ruby blocks also seem to handle returns and break statements from the scope that uses the block.</p>
<pre><code>loop do
break i if (i >= 4000)
i *= 2
end
</code></pre>
<p>I think one of the closures proposals for Java works like this also.</p>
<p>So, how would you implement Ruby-blocks/Java-closures in C?</p>
| [
{
"answer_id": 20154,
"author": "wvdschel",
"author_id": 2018,
"author_profile": "https://Stackoverflow.com/users/2018",
"pm_score": 4,
"selected": true,
"text": "<p>The concept of closures requires the concept of contexts. C's context is based on the stack and the registers of the CPU, so to create a block/closure, you need to be able to manipulate the stack pointer in a correct (and reentrant) way, and store/restore registers as needed.</p>\n\n<p>The way this is done by interpreters or virtual machines is to have a <code>context</code> structure or something similar, and not use the stack and registers directly. This structure keeps track of a stack and optionally some registers, if you're designing a register based VM. At least, that's the simplest way to do it (though slightly less performant than actually mapping things correctly).</p>\n"
},
{
"answer_id": 22164,
"author": "Andrew Harmel-Law",
"author_id": 2455,
"author_profile": "https://Stackoverflow.com/users/2455",
"pm_score": 2,
"selected": false,
"text": "<p>There's a good set of slides on Ruby Blocks as part of the \"Rails with Passion\" course:</p>\n\n<p><a href=\"http://www.javapassion.com/rubyonrails/ruby_blocks.pdf\" rel=\"nofollow noreferrer\">Ruby_Blocks.pdf</a></p>\n\n<p>This covers representing a block, how they get passed arguments and executed, and even further into things like Proc objects. It's very clearly explained.</p>\n\n<p>It might then be of interest to look at how the JRuby guys handled these in their parsing to Java. Take a look at the source at <a href=\"http://svn.codehaus.org/jruby/\" rel=\"nofollow noreferrer\">codehaus</a>.</p>\n"
},
{
"answer_id": 38105,
"author": "Pramod",
"author_id": 1386292,
"author_profile": "https://Stackoverflow.com/users/1386292",
"pm_score": 2,
"selected": false,
"text": "<p>I haven't actually implemented any of this, so take it with a sack of salt.</p>\n\n<p>There are two parts to a closure: the data environment and the code environment. Like you said, you can probably pass a void* to handle references to data. You could probably use setjmp and longjmp to implement the non-linear control flow jumps that the Ruby break requires. </p>\n\n<p>If you want closures you should probably be programming in a language that actually supports them. :-)</p>\n\n<p>UPDATE: Interesting things are happening in Clang. They've prototyped a closure for C. <a href=\"http://lists.cs.uiuc.edu/pipermail/cfe-dev/2008-August/002670.html\" rel=\"nofollow noreferrer\">http://lists.cs.uiuc.edu/pipermail/cfe-dev/2008-August/002670.html</a> might prove to be interesting reading.</p>\n"
}
] | 2008/08/21 | [
"https://Stackoverflow.com/questions/19838",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2148/"
] | I've been trying to understand how Ruby blocks work, and to do that I've been trying to implement them in C.
One easy way to implement closures is to pass a `void*` to the enclosing stack to the closure/function but Ruby blocks also seem to handle returns and break statements from the scope that uses the block.
```
loop do
break i if (i >= 4000)
i *= 2
end
```
I think one of the closures proposals for Java works like this also.
So, how would you implement Ruby-blocks/Java-closures in C? | The concept of closures requires the concept of contexts. C's context is based on the stack and the registers of the CPU, so to create a block/closure, you need to be able to manipulate the stack pointer in a correct (and reentrant) way, and store/restore registers as needed.
The way this is done by interpreters or virtual machines is to have a `context` structure or something similar, and not use the stack and registers directly. This structure keeps track of a stack and optionally some registers, if you're designing a register based VM. At least, that's the simplest way to do it (though slightly less performant than actually mapping things correctly). |
19,843 | <p>My question concerns c# and how to access Static members ... Well I don't really know how to explain it (which kind of is bad for a question isn't it?) I will just give you some sample code:</p>
<pre><code>Class test<T>{
int method1(Obj Parameter1){
//in here I want to do something which I would explain as
T.TryParse(Parameter1);
//my problem is that it does not work ... I get an error.
//just to explain: if I declare test<int> (with type Integer)
//I want my sample code to call int.TryParse(). If it were String
//it should have been String.TryParse()
}
}
</code></pre>
<p>So thank you guys for your answers (By the way the question is: how would I solve this problem without getting an error). This probably quite an easy question for you!</p>
<hr />
<p>Edit: Thank you all for your answers!</p>
<p>Though I think the try - catch phrase is the most elegant, I know from my experience with vb that it can really be a bummer. I used it once and it took about 30 minutes to run a program, which later on only took 2 minutes to compute just because I avoided try - catch.</p>
<p>This is why I chose the switch statement as the best answer. It makes the code more complicated but on the other hand I imagine it to be relatively fast and relatively easy to read. (Though I still think there should be a more elegant way ... maybe in the next language I learn)</p>
<hr />
<p>Though if you have some other suggestion I am still waiting (and willing to participate)</p>
| [
{
"answer_id": 19862,
"author": "Greg Hurlman",
"author_id": 35,
"author_profile": "https://Stackoverflow.com/users/35",
"pm_score": 3,
"selected": false,
"text": "<p>The problem is that TryParse isn't defined on an interface or base class anywhere, so you can't make an assumption that the type passed into your class will have that function. Unless you can contrain T in some way, you'll run into this a lot.</p>\n\n<p><a href=\"http://msdn.microsoft.com/en-us/library/d5x73970.aspx\" rel=\"noreferrer\" title=\"C# Programming Guide (MSDN)\">Constraints on Type Parameters</a></p>\n"
},
{
"answer_id": 19863,
"author": "svrist",
"author_id": 86,
"author_profile": "https://Stackoverflow.com/users/86",
"pm_score": 0,
"selected": false,
"text": "<p>You probably cant do it.</p>\n\n<p>First of all if it should be possible you would need a tighter bound on T so the typechecker could be sure that all possible substitutions for T actually had a static method called TryParse.</p>\n"
},
{
"answer_id": 19867,
"author": "Nick Berardi",
"author_id": 17,
"author_profile": "https://Stackoverflow.com/users/17",
"pm_score": -1,
"selected": false,
"text": "<p>That is not how statics work. You have to think of statics as sort of in a Global class even if they are are spread across a whole bunch of types. My recommendation is to make it a property inside the T instance that can access the necessary static method.</p>\n\n<p>Also T is an actual instance of something, and just like any other instance you are not able to access the statics for that type, through the instantiated value. Here is an example of what to do:</p>\n\n<pre><code>class a {\n static StaticMethod1 ()\n virtual Method1 ()\n}\n\nclass b : a {\n override Method1 () return StaticMethod1()\n}\n\nclass c : a {\n override Method1 () return \"XYZ\"\n}\n\nclass generic<T> \n where T : a {\n void DoSomething () T.Method1()\n}\n</code></pre>\n"
},
{
"answer_id": 19885,
"author": "samjudson",
"author_id": 1908,
"author_profile": "https://Stackoverflow.com/users/1908",
"pm_score": 2,
"selected": false,
"text": "<p>To access a member of a specific class or interface you need to use the Where keyword and specify the interface or base class that has the method.</p>\n\n<p>In the above instance TryParse does not come from an interface or base class, so what you are trying to do above is not possible. Best just use Convert.ChangeType and a try/catch statement.</p>\n\n<pre><code>class test<T>\n{\n T Method(object P)\n {\n try {\n return (T)Convert.ChangeType(P, typeof(T));\n } catch(Exception e) {\n return null;\n }\n }\n}\n</code></pre>\n"
},
{
"answer_id": 19887,
"author": "Rob Cooper",
"author_id": 832,
"author_profile": "https://Stackoverflow.com/users/832",
"pm_score": 0,
"selected": false,
"text": "<p>You may want to read my previous post on <a href=\"https://stackoverflow.com/questions/8941/generic-type-checking\">limiting generic types to primitives</a>. This may give you some pointers in limiting the type that can be passed to the generic (since <em>TypeParse</em> is obviously only available to a set number of primitives ( <em>string.TryParse</em> obviously being the exception, which doesn't make sense).</p>\n\n<p>Once you have more of a handle on the type, you can then work on trying to parse it. You may need a bit of an ugly switch in there (to call the correct <em>TryParse</em> ) but I think you can achieve the desired functionality.</p>\n\n<p>If you need me to explain any of the above further, then please ask :)</p>\n"
},
{
"answer_id": 19911,
"author": "Keith",
"author_id": 905,
"author_profile": "https://Stackoverflow.com/users/905",
"pm_score": 1,
"selected": false,
"text": "<p>Do you mean to do something like this:</p>\n\n<pre><code>Class test<T>\n{\n T method1(object Parameter1){\n\n if( Parameter1 is T ) \n {\n T value = (T) Parameter1;\n //do something with value\n return value;\n }\n else\n {\n //Parameter1 is not a T\n return default(T); //or throw exception\n }\n }\n}\n</code></pre>\n\n<p>Unfortunately you can't check for the TryParse pattern as it is static - which unfortunately means that it isn't particularly well suited to generics.</p>\n"
},
{
"answer_id": 19982,
"author": "Dan Herbert",
"author_id": 392,
"author_profile": "https://Stackoverflow.com/users/392",
"pm_score": 1,
"selected": false,
"text": "<p>The only way to do exactly what you're looking for would be to use reflection to check if the method exists for T.</p>\n\n<p>Another option is to ensure that the object you send in is a convertible object by restraining the type to IConvertible (all primitive types implement IConvertible). This would allow you to convert your parameter to the given type very flexibly.</p>\n\n<pre><code>Class test<T>\n{\n int method1(IConvertible Parameter1){\n\n IFormatProvider provider = System.Globalization.CultureInfo.CurrentCulture.GetFormat(typeof(T));\n\n T temp = Parameter1.ToType(typeof(T), provider);\n }\n}\n</code></pre>\n\n<p>You could also do a variation on this by using an 'object' type instead like you had originally.</p>\n\n<pre><code>Class test<T>\n{\n int method1(object Parameter1){\n\n if(Parameter1 is IConvertible) {\n\n IFormatProvider provider = System.Globalization.CultureInfo.CurrentCulture.GetFormat(typeof(T));\n\n T temp = Parameter1.ToType(typeof(T), provider);\n\n } else {\n // Do something else\n }\n }\n}\n</code></pre>\n"
},
{
"answer_id": 20010,
"author": "Weeble",
"author_id": 2283,
"author_profile": "https://Stackoverflow.com/users/2283",
"pm_score": 2,
"selected": false,
"text": "<p>Short answer, you can't.</p>\n\n<p>Long answer, you can cheat:</p>\n\n<pre><code>public class Example\n{\n internal static class Support\n {\n private delegate bool GenericParser<T>(string s, out T o);\n private static Dictionary<Type, object> parsers =\n MakeStandardParsers();\n private static Dictionary<Type, object> MakeStandardParsers()\n {\n Dictionary<Type, object> d = new Dictionary<Type, object>();\n // You need to add an entry for every type you want to cope with.\n d[typeof(int)] = new GenericParser<int>(int.TryParse);\n d[typeof(long)] = new GenericParser<long>(long.TryParse);\n d[typeof(float)] = new GenericParser<float>(float.TryParse);\n return d;\n }\n public static bool TryParse<T>(string s, out T result)\n {\n return ((GenericParser<T>)parsers[typeof(T)])(s, out result);\n }\n }\n public class Test<T>\n {\n public static T method1(string s)\n {\n T value;\n bool success = Support.TryParse(s, out value);\n return value;\n }\n }\n public static void Main()\n {\n Console.WriteLine(Test<int>.method1(\"23\"));\n Console.WriteLine(Test<float>.method1(\"23.4\"));\n Console.WriteLine(Test<long>.method1(\"99999999999999\"));\n Console.ReadLine();\n }\n}\n</code></pre>\n\n<p>I made a static dictionary holding a delegate for the TryParse method of every type I might want to use. I then wrote a generic method to look up the dictionary and pass on the call to the appropriate delegate. Since every delegate has a different type, I just store them as object references and cast them back to the appropriate generic type when I retrieve them. Note that for the sake of a simple example I have omitted error checking, such as to check whether we have an entry in the dictionary for the given type.</p>\n"
},
{
"answer_id": 20053,
"author": "niklasfi",
"author_id": 2275,
"author_profile": "https://Stackoverflow.com/users/2275",
"pm_score": 1,
"selected": false,
"text": "<p>Ok guys: Thanks for all the fish. Now with your answers and my research (especially the article on <a href=\"https://stackoverflow.com/questions/8941/generic-type-checking\">limiting generic types to primitives</a>) I will present you my solution.</p>\n\n<pre><code>Class a<T>{\n private void checkWetherTypeIsOK()\n {\n if (T is int || T is float //|| ... any other types you want to be allowed){\n return true;\n }\n else {\n throw new exception();\n }\n }\n public static a(){\n ccheckWetherTypeIsOK();\n }\n}\n</code></pre>\n"
},
{
"answer_id": 20139,
"author": "Timbo",
"author_id": 1810,
"author_profile": "https://Stackoverflow.com/users/1810",
"pm_score": 3,
"selected": true,
"text": "<p>One more way to do it, this time some reflection in the mix:</p>\n\n<pre><code>static class Parser\n{\n public static bool TryParse<TType>( string str, out TType x )\n {\n // Get the type on that TryParse shall be called\n Type objType = typeof( TType );\n\n // Enumerate the methods of TType\n foreach( MethodInfo mi in objType.GetMethods() )\n {\n if( mi.Name == \"TryParse\" )\n {\n // We found a TryParse method, check for the 2-parameter-signature\n ParameterInfo[] pi = mi.GetParameters();\n if( pi.Length == 2 ) // Find TryParse( String, TType )\n {\n // Build a parameter list for the call\n object[] paramList = new object[2] { str, default( TType ) };\n\n // Invoke the static method\n object ret = objType.InvokeMember( \"TryParse\", BindingFlags.InvokeMethod, null, null, paramList );\n\n // Get the output value from the parameter list\n x = (TType)paramList[1];\n return (bool)ret;\n }\n }\n }\n\n // Maybe we should throw an exception here, because we were unable to find the TryParse\n // method; this is not just a unable-to-parse error.\n\n x = default( TType );\n return false;\n }\n}\n</code></pre>\n\n<p>The next step would be trying to implement</p>\n\n<pre><code>public static TRet CallStaticMethod<TRet>( object obj, string methodName, params object[] args );\n</code></pre>\n\n<p>With full parameter type matching etc.</p>\n"
},
{
"answer_id": 1138729,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 0,
"selected": false,
"text": "<p>Best code: restrict T to ValueType this way:</p>\n\n<pre><code>class test1<T> where T: struct\n</code></pre>\n\n<p>A \"struct\" here means a value type.\nString is a class, not a value type.\nint, float, Enums are all value types.</p>\n\n<p>btw the compiler does not accept to call static methods or access static members on 'type parameters' like in the following example which will not compile :(</p>\n\n<pre><code>class MyStatic { public static int MyValue=0; }\nclass Test<T> where T: MyStatic\n{\n public void TheTest() { T.MyValue++; }\n}\n</code></pre>\n\n<p>=> Error 1 'T' is a 'type parameter', which is not valid in the given context</p>\n\n<p>SL.</p>\n"
},
{
"answer_id": 10590634,
"author": "Amir Abiri",
"author_id": 800334,
"author_profile": "https://Stackoverflow.com/users/800334",
"pm_score": 2,
"selected": false,
"text": "<p>This isn't really a solution, but in certain scenarios it could be a good alternative: We can pass an additional delegate to the generic method.</p>\n\n<p>To clarify what I mean, let's use an example. Let's say we have some generic factory method, that should create an instance of T, and we want it to then call another method, for notification or additional initialization.</p>\n\n<p>Consider the following simple class:</p>\n\n<pre><code>public class Example\n{\n // ...\n\n public static void PostInitCallback(Example example)\n {\n // Do something with the object...\n }\n}\n</code></pre>\n\n<p>And the following static method:</p>\n\n<pre><code>public static T CreateAndInit<T>() where T : new()\n{\n var t = new T();\n // Some initialization code...\n return t;\n}\n</code></pre>\n\n<p>So right now we would have to do:</p>\n\n<pre><code>var example = CreateAndInit<Example>();\nExample.PostInitCallback(example);\n</code></pre>\n\n<p>However, we could change our method to take an additional delegate:</p>\n\n<pre><code>public delegate void PostInitCallback<T>(T t);\npublic static T CreateAndInit<T>(PostInitCallback<T> callback) where T : new()\n{\n var t = new T();\n // Some initialization code...\n callback(t);\n return t;\n}\n</code></pre>\n\n<p>And now we can change the call to:</p>\n\n<pre><code>var example = CreateAndInit<Example>(Example.PostInitCallback);\n</code></pre>\n\n<p>Obviously this is only useful in very specific scenarios. But this is the cleanest solution in the sense that we get compile time safety, there is no \"hacking\" involved, and the code is dead simple.</p>\n"
}
] | 2008/08/21 | [
"https://Stackoverflow.com/questions/19843",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2275/"
] | My question concerns c# and how to access Static members ... Well I don't really know how to explain it (which kind of is bad for a question isn't it?) I will just give you some sample code:
```
Class test<T>{
int method1(Obj Parameter1){
//in here I want to do something which I would explain as
T.TryParse(Parameter1);
//my problem is that it does not work ... I get an error.
//just to explain: if I declare test<int> (with type Integer)
//I want my sample code to call int.TryParse(). If it were String
//it should have been String.TryParse()
}
}
```
So thank you guys for your answers (By the way the question is: how would I solve this problem without getting an error). This probably quite an easy question for you!
---
Edit: Thank you all for your answers!
Though I think the try - catch phrase is the most elegant, I know from my experience with vb that it can really be a bummer. I used it once and it took about 30 minutes to run a program, which later on only took 2 minutes to compute just because I avoided try - catch.
This is why I chose the switch statement as the best answer. It makes the code more complicated but on the other hand I imagine it to be relatively fast and relatively easy to read. (Though I still think there should be a more elegant way ... maybe in the next language I learn)
---
Though if you have some other suggestion I am still waiting (and willing to participate) | One more way to do it, this time some reflection in the mix:
```
static class Parser
{
public static bool TryParse<TType>( string str, out TType x )
{
// Get the type on that TryParse shall be called
Type objType = typeof( TType );
// Enumerate the methods of TType
foreach( MethodInfo mi in objType.GetMethods() )
{
if( mi.Name == "TryParse" )
{
// We found a TryParse method, check for the 2-parameter-signature
ParameterInfo[] pi = mi.GetParameters();
if( pi.Length == 2 ) // Find TryParse( String, TType )
{
// Build a parameter list for the call
object[] paramList = new object[2] { str, default( TType ) };
// Invoke the static method
object ret = objType.InvokeMember( "TryParse", BindingFlags.InvokeMethod, null, null, paramList );
// Get the output value from the parameter list
x = (TType)paramList[1];
return (bool)ret;
}
}
}
// Maybe we should throw an exception here, because we were unable to find the TryParse
// method; this is not just a unable-to-parse error.
x = default( TType );
return false;
}
}
```
The next step would be trying to implement
```
public static TRet CallStaticMethod<TRet>( object obj, string methodName, params object[] args );
```
With full parameter type matching etc. |
19,852 | <p>I'm just designing the schema for a database table which will hold details of email attachments - their size in bytes, filename and content-type (i.e. "image/jpg", "audio/mp3", etc).</p>
<p>Does anybody know the maximum length that I can expect a content-type to be?</p>
| [
{
"answer_id": 136592,
"author": "Walden Leverich",
"author_id": 2673770,
"author_profile": "https://Stackoverflow.com/users/2673770",
"pm_score": 1,
"selected": false,
"text": "<p>We run an SaaS system that allows users to upload files. We'd originally designed it to store MIME Types up to 50 characters. In the last several days we've seen several attempts to upload 71-bytes types. So, we're changing to 250. 100 seemed \"good\" but it's only a few more than the max we're seeing now. 500 seems silly, so 250 is the selected one.</p>\n"
},
{
"answer_id": 1849792,
"author": "speaker",
"author_id": 215670,
"author_profile": "https://Stackoverflow.com/users/215670",
"pm_score": 7,
"selected": true,
"text": "<p>I hope I havn't misread, but it looks like the length is max 127/127 or <strong>255 total</strong>.</p>\n\n<p><a href=\"http://www.ietf.org/rfc/rfc4288.txt?number=4288\" rel=\"noreferrer\">RFC 4288</a> has a reference in 4.2 (page 6):</p>\n\n<pre><code>Type and subtype names MUST conform to the following ABNF:\n\n type-name = reg-name\n subtype-name = reg-name\n\n reg-name = 1*127reg-name-chars\n reg-name-chars = ALPHA / DIGIT / \"!\" /\n \"#\" / \"$\" / \"&\" / \".\" /\n \"+\" / \"-\" / \"^\" / \"_\"\n</code></pre>\n\n<p>It is not clear to me if the +suffix can add past the 127, but it appears not.</p>\n"
},
{
"answer_id": 23928635,
"author": "appleleaf",
"author_id": 3131821,
"author_profile": "https://Stackoverflow.com/users/3131821",
"pm_score": 3,
"selected": false,
"text": "<p>In RFC 6838 which is latest standard and obsoletes RFC4288, there is a following statement.</p>\n<p>"Also note that while this syntax allows names of up to 127 characters, implementation limits may make such long names problematic. For this reason, <code><type-name></code> and <code><subtype-name></code> SHOULD be limited to 64 characters."</p>\n<p>64+1+64 = 129.</p>\n<p>But I suspect the standard should mean 63+1+63=127.</p>\n<p>link: <a href=\"https://www.rfc-editor.org/rfc/rfc6838#section-4.2\" rel=\"nofollow noreferrer\">https://www.rfc-editor.org/rfc/rfc6838#section-4.2</a></p>\n"
}
] | 2008/08/21 | [
"https://Stackoverflow.com/questions/19852",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2084/"
] | I'm just designing the schema for a database table which will hold details of email attachments - their size in bytes, filename and content-type (i.e. "image/jpg", "audio/mp3", etc).
Does anybody know the maximum length that I can expect a content-type to be? | I hope I havn't misread, but it looks like the length is max 127/127 or **255 total**.
[RFC 4288](http://www.ietf.org/rfc/rfc4288.txt?number=4288) has a reference in 4.2 (page 6):
```
Type and subtype names MUST conform to the following ABNF:
type-name = reg-name
subtype-name = reg-name
reg-name = 1*127reg-name-chars
reg-name-chars = ALPHA / DIGIT / "!" /
"#" / "$" / "&" / "." /
"+" / "-" / "^" / "_"
```
It is not clear to me if the +suffix can add past the 127, but it appears not. |
19,952 | <p>The RFC for a Java class is set of all methods that can be invoked in response to a message to an object of the class or by some method in the class.
RFC = M + R where
M = Number of methods in the class.
R = Total number of other methods directly invoked from the M.</p>
<p>Thinking C is the .class and J is the .java file of which we need to calculate RFC.</p>
<pre>
class J{
a(){}
b(){}
c(){
e1.e();
e1.f();
e1.g();
}
h(){
i.k();
i.j();
}
m(){}
n(){
i.o();
i.p();
i.p();
i.p();
}
}
</pre>
<p>here M=6
and R=9 (Don't worry about call inside a loop. It's considered as a single call)</p>
<p>Calculating M is easy. Load C using classloader and use reflection to get the count of methods.</p>
<p>Calculating R is not direct. We need to count the number of method calls from the class. First level only. </p>
<p>For calculating R I must use regex. Usually format would be (calls without using . are not counted)</p>
<pre>
[variable_name].[method_name]([zero or more parameters]);
</pre>
<p>or</p>
<pre>
[variable_name].[method_name]([zero or more parameters])
</pre>
<p>with out semicolon when call return is directly becomes parameter to another method.
or </p>
<pre>
[variable_name].[method_name]([zero or more parameters]).method2();
</pre>
<p>this becomes two method calls</p>
<p>What other patterns of the method call can you think of? Is there any other way other than using RegEx that can be used to calculate R.</p>
<hr>
<p><strong>UPDATE:</strong><br>
<a href="https://stackoverflow.com/questions/19952/rfc-calculation-in-java-need-help-with-algorithm#19983" title="@McDowell">@McDowell</a>
Looks like using BCEL I can simplify the whole process. Let me try it.</p>
| [
{
"answer_id": 19967,
"author": "Nicolas",
"author_id": 1730,
"author_profile": "https://Stackoverflow.com/users/1730",
"pm_score": 0,
"selected": false,
"text": "<p>You should find your answer in the <a href=\"http://java.sun.com/docs/books/jls/third_edition/html/j3TOC.html\" rel=\"nofollow noreferrer\">Java language specification</a>.</p>\n\n<p>You have forgot static method call, method call inside parameters...</p>\n"
},
{
"answer_id": 19973,
"author": "kokos",
"author_id": 1065,
"author_profile": "https://Stackoverflow.com/users/1065",
"pm_score": 0,
"selected": false,
"text": "<p>Calling a method using reflection (the name of the method is in a string).</p>\n"
},
{
"answer_id": 19983,
"author": "McDowell",
"author_id": 304,
"author_profile": "https://Stackoverflow.com/users/304",
"pm_score": 3,
"selected": true,
"text": "<p>You could use the <a href=\"http://jakarta.apache.org/bcel/index.html\" rel=\"nofollow noreferrer\">Byte Code Engineering Library</a> with binaries. You can use a <a href=\"http://jakarta.apache.org/bcel/apidocs/org/apache/bcel/classfile/DescendingVisitor.html\" rel=\"nofollow noreferrer\">DescendingVisitor</a> to visit a class' members and references. I've used it to <a href=\"http://illegalargumentexception.blogspot.com/2008/04/java-finding-binary-class-dependencies.html\" rel=\"nofollow noreferrer\">find class dependencies</a>.</p>\n\n<p>Alternatively, you could reuse some model of the source files. I'm pretty sure the Java editor in the <a href=\"http://www.eclipse.org/jdt/\" rel=\"nofollow noreferrer\">Eclipse JDT</a> is backed by some form of model.</p>\n"
},
{
"answer_id": 19998,
"author": "Herms",
"author_id": 1409,
"author_profile": "https://Stackoverflow.com/users/1409",
"pm_score": 0,
"selected": false,
"text": "<p>Does M include calls to its own methods? Or calls to inner classes? For instance:</p>\n\n<pre><code>class J {\n a() { }\n b() { this.a(); }\n c() { jj.aa(); }\n d() { i.k(); }\n e() { this.f().a(); }\n f() { return this; }\n g() { i.m().n(); }\n\n class JJ {\n aa() { a(); }\n }\n}\n</code></pre>\n\n<p>What would the M value of this be? There's only three function calls to a method not defined in this class (the calls in the d() and g() functions). Do you want to include calls to inner classes, or calls to the main class made in the inner class? Do you want to include calls to other methods on the same class?</p>\n\n<p>If you're looking at any method calls, regardless of the source, then a regex could probably work, but would be tricky to get right (does your regex properly ignore strings that contain method-call like contents? Does it handle constructor calls properly?). If you care about the source of the method call then regexes probably won't get you what you want. You'd need to use reflection (though unfortunately I don't know enough about reflection to be helpful there).</p>\n"
}
] | 2008/08/21 | [
"https://Stackoverflow.com/questions/19952",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/482/"
] | The RFC for a Java class is set of all methods that can be invoked in response to a message to an object of the class or by some method in the class.
RFC = M + R where
M = Number of methods in the class.
R = Total number of other methods directly invoked from the M.
Thinking C is the .class and J is the .java file of which we need to calculate RFC.
```
class J{
a(){}
b(){}
c(){
e1.e();
e1.f();
e1.g();
}
h(){
i.k();
i.j();
}
m(){}
n(){
i.o();
i.p();
i.p();
i.p();
}
}
```
here M=6
and R=9 (Don't worry about call inside a loop. It's considered as a single call)
Calculating M is easy. Load C using classloader and use reflection to get the count of methods.
Calculating R is not direct. We need to count the number of method calls from the class. First level only.
For calculating R I must use regex. Usually format would be (calls without using . are not counted)
```
[variable_name].[method_name]([zero or more parameters]);
```
or
```
[variable_name].[method_name]([zero or more parameters])
```
with out semicolon when call return is directly becomes parameter to another method.
or
```
[variable_name].[method_name]([zero or more parameters]).method2();
```
this becomes two method calls
What other patterns of the method call can you think of? Is there any other way other than using RegEx that can be used to calculate R.
---
**UPDATE:**
[@McDowell](https://stackoverflow.com/questions/19952/rfc-calculation-in-java-need-help-with-algorithm#19983 "@McDowell")
Looks like using BCEL I can simplify the whole process. Let me try it. | You could use the [Byte Code Engineering Library](http://jakarta.apache.org/bcel/index.html) with binaries. You can use a [DescendingVisitor](http://jakarta.apache.org/bcel/apidocs/org/apache/bcel/classfile/DescendingVisitor.html) to visit a class' members and references. I've used it to [find class dependencies](http://illegalargumentexception.blogspot.com/2008/04/java-finding-binary-class-dependencies.html).
Alternatively, you could reuse some model of the source files. I'm pretty sure the Java editor in the [Eclipse JDT](http://www.eclipse.org/jdt/) is backed by some form of model. |
20,047 | <p>We're seeing some pernicious, but rare, deadlock conditions in the Stack Overflow SQL Server 2005 database.</p>
<p>I attached the profiler, set up a trace profile using <a href="http://www.simple-talk.com/sql/learn-sql-server/how-to-track-down-deadlocks-using-sql-server-2005-profiler/" rel="noreferrer">this excellent article on troubleshooting deadlocks</a>, and captured a bunch of examples. The weird thing is that <strong>the deadlocking write is <em>always</em> the same</strong>:</p>
<pre><code>UPDATE [dbo].[Posts]
SET [AnswerCount] = @p1, [LastActivityDate] = @p2, [LastActivityUserId] = @p3
WHERE [Id] = @p0
</code></pre>
<p>The other deadlocking statement varies, but it's usually some kind of trivial, simple <strong>read</strong> of the posts table. This one always gets killed in the deadlock. Here's an example</p>
<pre><code>SELECT
[t0].[Id], [t0].[PostTypeId], [t0].[Score], [t0].[Views], [t0].[AnswerCount],
[t0].[AcceptedAnswerId], [t0].[IsLocked], [t0].[IsLockedEdit], [t0].[ParentId],
[t0].[CurrentRevisionId], [t0].[FirstRevisionId], [t0].[LockedReason],
[t0].[LastActivityDate], [t0].[LastActivityUserId]
FROM [dbo].[Posts] AS [t0]
WHERE [t0].[ParentId] = @p0
</code></pre>
<p>To be perfectly clear, we are not seeing write / write deadlocks, but read / write.</p>
<p>We have a mixture of LINQ and parameterized SQL queries at the moment. We have added <code>with (nolock)</code> to all the SQL queries. This may have helped some. We also had a single (very) poorly-written badge query that I fixed yesterday, which was taking upwards of 20 seconds to run every time, and was running every minute on top of that. I was hoping this was the source of some of the locking problems!</p>
<p>Unfortunately, I got another deadlock error about 2 hours ago. Same exact symptoms, same exact culprit write.</p>
<p>The truly strange thing is that the locking write SQL statement you see above is part of a very specific code path. It's <em>only</em> executed when a new answer is added to a question -- it updates the parent question with the new answer count and last date/user. This is, obviously, not that common relative to the massive number of reads we are doing! As far as I can tell, we're not doing huge numbers of writes anywhere in the app.</p>
<p>I realize that NOLOCK is sort of a giant hammer, but most of the queries we run here don't need to be that accurate. Will you care if your user profile is a few seconds out of date?</p>
<p>Using NOLOCK with Linq is a bit more difficult as <a href="http://www.hanselman.com/blog/GettingLINQToSQLAndLINQToEntitiesToUseNOLOCK.aspx" rel="noreferrer">Scott Hanselman discusses here</a>.</p>
<p>We are flirting with the idea of using</p>
<pre><code>SET TRANSACTION ISOLATION LEVEL READ UNCOMMITTED
</code></pre>
<p>on the base database context so that all our LINQ queries have this set. Without that, we'd have to wrap every LINQ call we make (well, the simple reading ones, which is the vast majority of them) in a 3-4 line transaction code block, which is ugly.</p>
<p>I guess I'm a little frustrated that trivial reads in SQL 2005 can deadlock on writes. I could see write/write deadlocks being a huge issue, but <em>reads?</em> We're not running a banking site here, we don't need perfect accuracy every time.</p>
<p>Ideas? Thoughts?</p>
<hr>
<blockquote>
<p>Are you instantiating a new LINQ to SQL DataContext object for every operation or are you perhaps sharing the same static context for all your calls?</p>
</blockquote>
<p>Jeremy, we are sharing one static datacontext in the base Controller for the most part:</p>
<pre><code>private DBContext _db;
/// <summary>
/// Gets the DataContext to be used by a Request's controllers.
/// </summary>
public DBContext DB
{
get
{
if (_db == null)
{
_db = new DBContext() { SessionName = GetType().Name };
//_db.ExecuteCommand("SET TRANSACTION ISOLATION LEVEL READ UNCOMMITTED");
}
return _db;
}
}
</code></pre>
<p>Do you recommend we create a new context for every Controller, or per Page, or .. more often?</p>
| [
{
"answer_id": 20056,
"author": "Greg Hurlman",
"author_id": 35,
"author_profile": "https://Stackoverflow.com/users/35",
"pm_score": 3,
"selected": false,
"text": "<blockquote>\n <p>Will you care if your user profile is a few seconds out of date?</p>\n</blockquote>\n\n<p>Nope - that's perfectly acceptable. Setting the base transaction isolation level is probably the best/cleanest way to go.</p>\n"
},
{
"answer_id": 20094,
"author": "GateKiller",
"author_id": 383,
"author_profile": "https://Stackoverflow.com/users/383",
"pm_score": 0,
"selected": false,
"text": "<p>I would have to agree with Greg so long as setting the isolation level to read uncommitted doesn't have any ill effects on other queries.</p>\n\n<p>I'd be interested to know, Jeff, how setting it at the database level would affect a query such as the following:</p>\n\n<pre><code>Begin Tran\nInsert into Table (Columns) Values (Values)\nSelect Max(ID) From Table\nCommit Tran\n</code></pre>\n"
},
{
"answer_id": 20101,
"author": "jeremcc",
"author_id": 1436,
"author_profile": "https://Stackoverflow.com/users/1436",
"pm_score": 4,
"selected": false,
"text": "<p>Are you instantiating a new LINQ to SQL DataContext object for every operation or are you perhaps sharing the same static context for all your calls? I originally tried the latter approach, and from what I remember, it caused unwanted locking in the DB. I now create a new context for every atomic operation.</p>\n"
},
{
"answer_id": 20105,
"author": "a_hardin",
"author_id": 1497,
"author_profile": "https://Stackoverflow.com/users/1497",
"pm_score": 1,
"selected": false,
"text": "<blockquote>\n <p>Will you care if your user profile is a few seconds out of date?</p>\n</blockquote>\n\n<p>A few seconds would definitely be acceptable. It doesn't seem like it would be that long, anyways, unless a huge number of people are submitting answers at the same time.</p>\n"
},
{
"answer_id": 20143,
"author": "bruceatk",
"author_id": 791,
"author_profile": "https://Stackoverflow.com/users/791",
"pm_score": 0,
"selected": false,
"text": "<p>It's fine with me if my profile is even several minutes out of date.</p>\n\n<p>Are you re-trying the read after it fails? It's certainly possible when firing a ton of random reads that a few will hit when they can't read. Most of the applications that I work with are very few writes compared to the number of reads and I'm sure the reads are no where near the number you are getting.</p>\n\n<p>If implementing \"READ UNCOMMITTED\" doesn't solve your problem, then it's tough to help without knowing a lot more about the processing. There may be some other tuning option that would help this behavior. Unless some MSSQL guru comes to the rescue, I recommend submitting the problem to the vendor. </p>\n"
},
{
"answer_id": 20147,
"author": "jeremcc",
"author_id": 1436,
"author_profile": "https://Stackoverflow.com/users/1436",
"pm_score": 2,
"selected": false,
"text": "<p>@Jeff - I am definitely not an expert on this, but I have had good results with instantiating a new context on almost every call. I think it's similar to creating a new Connection object on every call with ADO. The overhead isn't as bad as you would think, since connection pooling will still be used anyway.</p>\n\n<p>I just use a global static helper like this:</p>\n\n<pre><code>public static class AppData\n{\n /// <summary>\n /// Gets a new database context\n /// </summary>\n public static CoreDataContext DB\n {\n get\n {\n var dataContext = new CoreDataContext\n {\n DeferredLoadingEnabled = true\n };\n return dataContext;\n }\n }\n}\n</code></pre>\n\n<p>and then I do something like this:</p>\n\n<pre><code>var db = AppData.DB;\n\nvar results = from p in db.Posts where p.ID = id select p;\n</code></pre>\n\n<p>And I would do the same thing for updates. Anyway, I don't have nearly as much traffic as you, but I was definitely getting some locking when I used a shared DataContext early on with just a handful of users. No guarantees, but it might be worth giving a try.</p>\n\n<p><strong>Update</strong>: Then again, looking at your code, you are only sharing the data context for the lifetime of that particular controller instance, which basically seems fine unless it is somehow getting used concurrently by mutiple calls within the controller. In a thread on the topic, ScottGu said:</p>\n\n<blockquote>\n <p>Controllers only live for a single request - so at the end of processing a request they are garbage collected (which means the DataContext is collected)...</p>\n</blockquote>\n\n<p>So anyway, that might not be it, but again it's probably worth a try, perhaps in conjunction with some load testing.</p>\n"
},
{
"answer_id": 20172,
"author": "RobertTheGrey",
"author_id": 1107,
"author_profile": "https://Stackoverflow.com/users/1107",
"pm_score": 1,
"selected": false,
"text": "<p>I agree with Jeremy on this one. You ask if you should create a new data context for each controller or per page - I tend to create a new one for every independent query.</p>\n\n<p>I'm building a solution at present which used to implement the static context like you do, and when I threw tons of requests at the beast of a server (million+) during stress tests, I was also getting read/write locks randomly.</p>\n\n<p>As soon as I changed my strategy to use a different data context at LINQ level per query, and trusted that SQL server could work its connection pooling magic, the locks seemed to disappear.</p>\n\n<p>Of course I was under some time pressure, so trying a number of things all around the same time, so I can't be 100% sure that is what fixed it, but I have a high level of confidence - let's put it that way.</p>\n"
},
{
"answer_id": 20204,
"author": "Michael Sharek",
"author_id": 1958,
"author_profile": "https://Stackoverflow.com/users/1958",
"pm_score": 2,
"selected": false,
"text": "<p>One thing that has worked for me in the past is making sure all my queries and updates access resources (tables) in the same order.</p>\n\n<p>That is, if one query updates in order Table1, Table2 and a different query updates it in order of Table2, Table1 then you might see deadlocks.</p>\n\n<p>Not sure if it's possible for you to change the order of updates since you're using LINQ. But it's something to look at.</p>\n"
},
{
"answer_id": 20224,
"author": "JEzell",
"author_id": 2308,
"author_profile": "https://Stackoverflow.com/users/2308",
"pm_score": 5,
"selected": false,
"text": "<p><strong>NOLOCK</strong> and <strong>READ UNCOMMITTED</strong> are a slippery slope. You should never use them unless you understand why the deadlock is happening first. It would worry me that you say, \"We have added with (nolock) to all the SQL queries\". Needing to add <strong>WITH NOLOCK</strong> everywhere is a sure sign that you have problems in your data layer. </p>\n\n<p>The update statement itself looks a bit problematic. Do you determine the count earlier in the transaction, or just pull it from an object? <code>AnswerCount = AnswerCount+1</code> when a question is added is probably a better way to handle this. Then you don't need a transaction to get the correct count and you don't have to worry about the concurrency issue that you are potentially exposing yourself to.</p>\n\n<p>One easy way to get around this type of deadlock issue without a lot of work and without enabling dirty reads is to use <code>\"Snapshot Isolation Mode\"</code> (new in SQL 2005) which will always give you a clean read of the last unmodified data. You can also catch and retry deadlocked statements fairly easily if you want to handle them gracefully.</p>\n"
},
{
"answer_id": 20473,
"author": "Jon Galloway",
"author_id": 5,
"author_profile": "https://Stackoverflow.com/users/5",
"pm_score": 1,
"selected": false,
"text": "<p>Now that I see Jeremy's answer, I think I remember hearing that the best practice is to use a new DataContext for each data operation. Rob Conery's written several posts about DataContext, and he always news them up rather than using a singleton.</p>\n\n<ul>\n<li><a href=\"http://blog.wekeroad.com/2007/08/17/linqtosql-ranch-dressing-for-your-database-pizza/\" rel=\"nofollow noreferrer\">http://blog.wekeroad.com/2007/08/17/linqtosql-ranch-dressing-for-your-database-pizza/</a></li>\n<li><a href=\"http://blog.wekeroad.com/mvc-storefront/mvcstore-part-9/\" rel=\"nofollow noreferrer\">http://blog.wekeroad.com/mvc-storefront/mvcstore-part-9/</a> (see comments)</li>\n</ul>\n\n<p>Here's the pattern we used for Video.Show (<a href=\"http://www.codeplex.com/videoshow/SourceControl/FileView.aspx?itemId=25033&changeSetId=10876\" rel=\"nofollow noreferrer\">link to source view in CodePlex</a>):</p>\n\n<pre><code>using System.Configuration;\nnamespace VideoShow.Data\n{\n public class DataContextFactory\n {\n public static VideoShowDataContext DataContext()\n {\n return new VideoShowDataContext(ConfigurationManager.ConnectionStrings[\"VideoShowConnectionString\"].ConnectionString);\n }\n public static VideoShowDataContext DataContext(string connectionString)\n {\n return new VideoShowDataContext(connectionString);\n }\n }\n}\n</code></pre>\n\n<p>Then at the service level (or even more granular, for updates):</p>\n\n<pre><code>private VideoShowDataContext dataContext = DataContextFactory.DataContext();\n\npublic VideoSearchResult GetVideos(int pageSize, int pageNumber, string sortType)\n{\n var videos =\n from video in DataContext.Videos\n where video.StatusId == (int)VideoServices.VideoStatus.Complete\n orderby video.DatePublished descending\n select video;\n return GetSearchResult(videos, pageSize, pageNumber);\n}\n</code></pre>\n"
},
{
"answer_id": 20727,
"author": "Seibar",
"author_id": 357,
"author_profile": "https://Stackoverflow.com/users/357",
"pm_score": 1,
"selected": false,
"text": "<p>You should implement dirty reads.</p>\n\n<pre><code>SET TRANSACTION ISOLATION LEVEL READ UNCOMMITTED\n</code></pre>\n\n<p>If you don't absolutely require perfect transactional integrity with your queries, you should be using dirty reads when accessing tables with high concurrency. I assume your Posts table would be one of those.</p>\n\n<p>This may give you so called \"phantom reads\", which is when your query acts upon data from a transaction that hasn't been committed.</p>\n\n<blockquote>\n <p>We're not running a banking site here, we don't need perfect accuracy every time</p>\n</blockquote>\n\n<p>Use dirty reads. You're right in that they won't give you perfect accuracy, but they should clear up your dead locking issues.</p>\n\n<blockquote>\n <p>Without that, we'd have to wrap every LINQ call we make (well, the simple reading ones, which is the vast majority of them) in a 3-4 line transaction code block, which is ugly</p>\n</blockquote>\n\n<p>If you implement dirty reads on \"the base database context\", you can always wrap your individual calls using a higher isolation level if you need the transactional integrity.</p>\n"
},
{
"answer_id": 21158,
"author": "Geoff Dalgas",
"author_id": 2,
"author_profile": "https://Stackoverflow.com/users/2",
"pm_score": 6,
"selected": true,
"text": "<p>According to MSDN:</p>\n\n<p><a href=\"http://msdn.microsoft.com/en-us/library/ms191242.aspx\" rel=\"noreferrer\">http://msdn.microsoft.com/en-us/library/ms191242.aspx</a></p>\n\n<blockquote>\n <p>When either the\n READ COMMITTED SNAPSHOT or\n ALLOW SNAPSHOT ISOLATION database\n options are ON, logical copies\n (versions) are maintained for all data\n modifications performed in the\n database. Every time a row is modified\n by a specific transaction, the\n instance of the Database Engine stores\n a version of the previously committed\n image of the row in tempdb. Each\n version is marked with the transaction\n sequence number of the transaction\n that made the change. The versions of\n modified rows are chained using a link\n list. The newest row value is always\n stored in the current database and\n chained to the versioned rows stored\n in tempdb.</p>\n \n <p>For short-running transactions, a\n version of a modified row may get\n cached in the buffer pool without\n getting written into the disk files of\n the tempdb database. If the need for\n the versioned row is short-lived, it\n will simply get dropped from the\n buffer pool and may not necessarily\n incur I/O overhead.</p>\n</blockquote>\n\n<p>There appears to be a slight performance penalty for the extra overhead, but it may be negligible. We should test to make sure.</p>\n\n<p>Try setting this option and REMOVE all NOLOCKs from code queries unless it’s really necessary. NOLOCKs or using global methods in the database context handler to combat database transaction isolation levels are Band-Aids to the problem. NOLOCKS will mask fundamental issues with our data layer and possibly lead to selecting unreliable data, where automatic select / update row versioning appears to be the solution.</p>\n\n<pre><code>ALTER Database [StackOverflow.Beta] SET READ_COMMITTED_SNAPSHOT ON\n</code></pre>\n"
},
{
"answer_id": 21438,
"author": "Eric Z Beard",
"author_id": 1219,
"author_profile": "https://Stackoverflow.com/users/1219",
"pm_score": 2,
"selected": false,
"text": "<p>Setting your default to read uncommitted is not a good idea. Your will undoubtedly introduce inconsistencies and end up with a problem that is worse than what you have now. Snapshot isolation might work well, but it is a drastic change to the way Sql Server works and puts a <em>huge</em> load on tempdb.</p>\n\n<p>Here is what you should do: use try-catch (in T-SQL) to detect the deadlock condition. When it happens, just re-run the query. This is standard database programming practice. </p>\n\n<p>There are good examples of this technique in Paul Nielson's <a href=\"https://rads.stackoverflow.com/amzn/click/com/0764542567\" rel=\"nofollow noreferrer\" rel=\"nofollow noreferrer\">Sql Server 2005 Bible</a>.</p>\n\n<p>Here is a quick template that I use:</p>\n\n<pre><code>-- Deadlock retry template\n\ndeclare @lastError int;\ndeclare @numErrors int;\n\nset @numErrors = 0;\n\nLockTimeoutRetry:\n\nbegin try;\n\n-- The query goes here\n\nreturn; -- this is the normal end of the procedure\n\nend try begin catch\n set @lastError=@@error\n if @lastError = 1222 or @lastError = 1205 -- Lock timeout or deadlock\n begin;\n if @numErrors >= 3 -- We hit the retry limit\n begin;\n raiserror('Could not get a lock after 3 attempts', 16, 1);\n return -100;\n end;\n\n -- Wait and then try the transaction again\n waitfor delay '00:00:00.25';\n set @numErrors = @numErrors + 1;\n goto LockTimeoutRetry;\n\n end;\n\n -- Some other error occurred\n declare @errorMessage nvarchar(4000), @errorSeverity int\n select @errorMessage = error_message(),\n @errorSeverity = error_severity()\n\n raiserror(@errorMessage, @errorSeverity, 1)\n\n return -100\nend catch; \n</code></pre>\n"
},
{
"answer_id": 21927,
"author": "Mark Brackett",
"author_id": 2199,
"author_profile": "https://Stackoverflow.com/users/2199",
"pm_score": 3,
"selected": false,
"text": "<p>Before burning the house down to catch a fly with NOLOCK all over, you may want to take a look at that deadlock graph you should've captured with Profiler.</p>\n\n<p>Remember that a deadlock requires (at least) 2 locks. Connection 1 has Lock A, wants Lock B - and vice-versa for Connection 2. This is an unsolvable situation, and someone has to give.</p>\n\n<p>What you've shown so far is solved by simple locking, which Sql Server is happy to do all day long.</p>\n\n<p>I suspect you (or LINQ) are starting a transaction with that UPDATE statement in it, and SELECTing some other piece of info before hand. But, you really need to backtrack through the deadlock graph to find the locks <em>held</em> by each thread, and then backtrack through Profiler to find the statements that caused those locks to be granted. </p>\n\n<p>I expect that there's at least 4 statements to complete this puzzle (or a statement that takes multiple locks - perhaps there's a trigger on the Posts table?).</p>\n"
},
{
"answer_id": 22019,
"author": "Guy",
"author_id": 993,
"author_profile": "https://Stackoverflow.com/users/993",
"pm_score": 2,
"selected": false,
"text": "<p>Q. Why are you storing the <code>AnswerCount</code> in the <code>Posts</code> table in the first place?</p>\n\n<p>An alternative approach is to eliminate the \"write back\" to the <code>Posts</code> table by not storing the <code>AnswerCount</code> in the table but to dynamically calculate the number of answers to the post as required.</p>\n\n<p>Yes, this will mean you're running an additional query:</p>\n\n<pre><code>SELECT COUNT(*) FROM Answers WHERE post_id = @id\n</code></pre>\n\n<p>or more typically (if you're displaying this for the home page):</p>\n\n<pre><code>SELECT p.post_id, \n p.<additional post fields>,\n a.AnswerCount\nFROM Posts p\n INNER JOIN AnswersCount_view a\n ON <join criteria>\nWHERE <home page criteria>\n</code></pre>\n\n<p>but this typically results in an <code>INDEX SCAN</code> and may be more efficient in the use of resources than using <code>READ ISOLATION</code>.</p>\n\n<p><em>There's more than one way to skin a cat. Premature de-normalisation of a database schema can introduce scalability issues.</em></p>\n"
},
{
"answer_id": 26558,
"author": "John Dyer",
"author_id": 2862,
"author_profile": "https://Stackoverflow.com/users/2862",
"pm_score": 1,
"selected": false,
"text": "<p>So what's the problem with implementing a retry mechanism? There will always be the possibility of a deadlock ocurring so why not have some logic to identify it and just try again? </p>\n\n<p>Won't at least some of the other options introduce performance penalties that are taken all the time when a retry system will kick in rarely? </p>\n\n<p>Also, don't forget some sort of logging when a retry happens so that you don't get into that situation of rare becoming often.</p>\n"
},
{
"answer_id": 26621,
"author": "aquinas",
"author_id": 82208,
"author_profile": "https://Stackoverflow.com/users/82208",
"pm_score": 2,
"selected": false,
"text": "<p>You definitely want READ_COMMITTED_SNAPSHOT set to on, which it is not by default. That gives you MVCC semantics. It's the same thing Oracle uses by default. Having an MVCC database is so incredibly useful, NOT using one is insane. This allows you to run the following inside a transaction:</p>\n\n<p>Update USERS Set FirstName = 'foobar';\n//decide to sleep for a year.</p>\n\n<p>meanwhile without committing the above, everyone can continue to select from that table just fine. If you are not familiar with MVCC, you will be shocked that you were ever able to live without it. Seriously. </p>\n"
},
{
"answer_id": 27617,
"author": "Leon Bambrick",
"author_id": 49,
"author_profile": "https://Stackoverflow.com/users/49",
"pm_score": 4,
"selected": false,
"text": "<p>I'm pretty uncomfortable about this question and the attendant answers. There's a lot of \"try this magic dust! No that magic dust!\"</p>\n\n<p>I can't see anywhere that you've anaylzed the locks that are taken, and determined what exact type of locks are deadlocked.</p>\n\n<p>All you've indicated is that some locks occur -- not what is deadlocking.</p>\n\n<p>In SQL 2005 you can get more info about what locks are being taken out by using:</p>\n\n<pre><code>DBCC TRACEON (1222, -1)\n</code></pre>\n\n<p>so that when the deadlock occurs you'll have better diagnostics.</p>\n"
},
{
"answer_id": 75926,
"author": "MrB",
"author_id": 13484,
"author_profile": "https://Stackoverflow.com/users/13484",
"pm_score": 5,
"selected": false,
"text": "<p>The OP question was to ask why this problem occured. This post hopes to answer that while leaving possible solutions to be worked out by others.</p>\n\n<p>This is probably an index related issue. For example, lets say the table Posts has a non-clustered index X which contains the ParentID and one (or more) of the field(s) being updated (AnswerCount, LastActivityDate, LastActivityUserId).</p>\n\n<p>A deadlock would occur if the SELECT cmd does a shared-read lock on index X to search by the ParentId and then needs to do a shared-read lock on the clustered index to get the remaining columns while the UPDATE cmd does a write-exclusive lock on the clustered index and need to get a write-exclusive lock on index X to update it.</p>\n\n<p>You now have a situation where A locked X and is trying to get Y whereas B locked Y and is trying to get X.</p>\n\n<p>Of course, we'll need the OP to update his posting with more information regarding what indexes are in play to confirm if this is actually the cause.</p>\n"
},
{
"answer_id": 192877,
"author": "SqlACID",
"author_id": 19797,
"author_profile": "https://Stackoverflow.com/users/19797",
"pm_score": 0,
"selected": false,
"text": "<p>I would continue to tune everything; how are is the disk subsystem performing? What is the average disk queue length? If I/O's are backing up, the real problem might not be these two queries that are deadlocking, it might be another query that is bottlenecking the system; you mentioned a query taking 20 seconds that has been tuned, are there others? </p>\n\n<p>Focus on shortening the long-running queries, I'll bet the deadlock problems will disappear.</p>\n"
},
{
"answer_id": 243187,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 0,
"selected": false,
"text": "<p>Had the same problem, and cannot use the \"IsolationLevel = IsolationLevel.ReadUncommitted\" on TransactionScope because the server dont have DTS enabled (!).</p>\n\n<p>Thats what i did with an extension method:</p>\n\n<pre><code>public static void SetNoLock(this MyDataContext myDS)\n{\n myDS.ExecuteCommand(\"SET TRANSACTION ISOLATION LEVEL READ UNCOMMITTED\");\n}\n</code></pre>\n\n<p>So, for selects who use critical concurrency tables, we enable the \"nolock\" like this:</p>\n\n<pre><code>using (MyDataContext myDS = new MyDataContext())\n{\n myDS.SetNoLock();\n\n // var query = from ...my dirty querys here...\n}\n</code></pre>\n\n<p>Sugestions are welcome!</p>\n"
},
{
"answer_id": 870449,
"author": "Remus Rusanu",
"author_id": 105929,
"author_profile": "https://Stackoverflow.com/users/105929",
"pm_score": 3,
"selected": false,
"text": "<p>Typical read/write deadlock comes from index order access. Read (T1) locates the row on index A and then looks up projected column on index B (usually clustered). Write (T2) changes index B (the cluster) then has to update the index A. T1 has S-Lck on A, wants S-Lck on B, T2 has X-Lck on B, wants U-Lck on A. Deadlock, puff. T1 is killed.\nThis is prevalent in environments with heavy OLTP traffic and just a tad too many indexes :). Solution is to make either the read not have to jump from A to B (ie. included column in A, or remove column from projected list) or T2 not have to jump from B to A (don't update indexed column). \nUnfortunately, linq is not your friend here...</p>\n"
}
] | 2008/08/21 | [
"https://Stackoverflow.com/questions/20047",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1/"
] | We're seeing some pernicious, but rare, deadlock conditions in the Stack Overflow SQL Server 2005 database.
I attached the profiler, set up a trace profile using [this excellent article on troubleshooting deadlocks](http://www.simple-talk.com/sql/learn-sql-server/how-to-track-down-deadlocks-using-sql-server-2005-profiler/), and captured a bunch of examples. The weird thing is that **the deadlocking write is *always* the same**:
```
UPDATE [dbo].[Posts]
SET [AnswerCount] = @p1, [LastActivityDate] = @p2, [LastActivityUserId] = @p3
WHERE [Id] = @p0
```
The other deadlocking statement varies, but it's usually some kind of trivial, simple **read** of the posts table. This one always gets killed in the deadlock. Here's an example
```
SELECT
[t0].[Id], [t0].[PostTypeId], [t0].[Score], [t0].[Views], [t0].[AnswerCount],
[t0].[AcceptedAnswerId], [t0].[IsLocked], [t0].[IsLockedEdit], [t0].[ParentId],
[t0].[CurrentRevisionId], [t0].[FirstRevisionId], [t0].[LockedReason],
[t0].[LastActivityDate], [t0].[LastActivityUserId]
FROM [dbo].[Posts] AS [t0]
WHERE [t0].[ParentId] = @p0
```
To be perfectly clear, we are not seeing write / write deadlocks, but read / write.
We have a mixture of LINQ and parameterized SQL queries at the moment. We have added `with (nolock)` to all the SQL queries. This may have helped some. We also had a single (very) poorly-written badge query that I fixed yesterday, which was taking upwards of 20 seconds to run every time, and was running every minute on top of that. I was hoping this was the source of some of the locking problems!
Unfortunately, I got another deadlock error about 2 hours ago. Same exact symptoms, same exact culprit write.
The truly strange thing is that the locking write SQL statement you see above is part of a very specific code path. It's *only* executed when a new answer is added to a question -- it updates the parent question with the new answer count and last date/user. This is, obviously, not that common relative to the massive number of reads we are doing! As far as I can tell, we're not doing huge numbers of writes anywhere in the app.
I realize that NOLOCK is sort of a giant hammer, but most of the queries we run here don't need to be that accurate. Will you care if your user profile is a few seconds out of date?
Using NOLOCK with Linq is a bit more difficult as [Scott Hanselman discusses here](http://www.hanselman.com/blog/GettingLINQToSQLAndLINQToEntitiesToUseNOLOCK.aspx).
We are flirting with the idea of using
```
SET TRANSACTION ISOLATION LEVEL READ UNCOMMITTED
```
on the base database context so that all our LINQ queries have this set. Without that, we'd have to wrap every LINQ call we make (well, the simple reading ones, which is the vast majority of them) in a 3-4 line transaction code block, which is ugly.
I guess I'm a little frustrated that trivial reads in SQL 2005 can deadlock on writes. I could see write/write deadlocks being a huge issue, but *reads?* We're not running a banking site here, we don't need perfect accuracy every time.
Ideas? Thoughts?
---
>
> Are you instantiating a new LINQ to SQL DataContext object for every operation or are you perhaps sharing the same static context for all your calls?
>
>
>
Jeremy, we are sharing one static datacontext in the base Controller for the most part:
```
private DBContext _db;
/// <summary>
/// Gets the DataContext to be used by a Request's controllers.
/// </summary>
public DBContext DB
{
get
{
if (_db == null)
{
_db = new DBContext() { SessionName = GetType().Name };
//_db.ExecuteCommand("SET TRANSACTION ISOLATION LEVEL READ UNCOMMITTED");
}
return _db;
}
}
```
Do you recommend we create a new context for every Controller, or per Page, or .. more often? | According to MSDN:
<http://msdn.microsoft.com/en-us/library/ms191242.aspx>
>
> When either the
> READ COMMITTED SNAPSHOT or
> ALLOW SNAPSHOT ISOLATION database
> options are ON, logical copies
> (versions) are maintained for all data
> modifications performed in the
> database. Every time a row is modified
> by a specific transaction, the
> instance of the Database Engine stores
> a version of the previously committed
> image of the row in tempdb. Each
> version is marked with the transaction
> sequence number of the transaction
> that made the change. The versions of
> modified rows are chained using a link
> list. The newest row value is always
> stored in the current database and
> chained to the versioned rows stored
> in tempdb.
>
>
> For short-running transactions, a
> version of a modified row may get
> cached in the buffer pool without
> getting written into the disk files of
> the tempdb database. If the need for
> the versioned row is short-lived, it
> will simply get dropped from the
> buffer pool and may not necessarily
> incur I/O overhead.
>
>
>
There appears to be a slight performance penalty for the extra overhead, but it may be negligible. We should test to make sure.
Try setting this option and REMOVE all NOLOCKs from code queries unless it’s really necessary. NOLOCKs or using global methods in the database context handler to combat database transaction isolation levels are Band-Aids to the problem. NOLOCKS will mask fundamental issues with our data layer and possibly lead to selecting unreliable data, where automatic select / update row versioning appears to be the solution.
```
ALTER Database [StackOverflow.Beta] SET READ_COMMITTED_SNAPSHOT ON
``` |
20,061 | <p>I've recently taken up learning some C# and wrote a Yahtzee clone. My next step (now that the game logic is in place and functioning correctly) is to integrate some method of keeping stats across all the games played.</p>
<p>My question is this, how should I go about storing this information? My first thought would be to use a database and I have a feeling that's the answer I'll get... if that's the case, can you point me to a good resource for creating and accessing a database from a C# application?</p>
<hr>
<p>Storing in an XML file actually makes more sense to me, but I thought if I suggested that I'd get torn apart ;). I'm used to building web applications and for those, text files are generally frowned upon.</p>
<p>So, going with an XML file, what classes should I be looking at that would allow for easy manipulation?</p>
| [
{
"answer_id": 20086,
"author": "palmsey",
"author_id": 521,
"author_profile": "https://Stackoverflow.com/users/521",
"pm_score": 3,
"selected": false,
"text": "<p>A database may be overkill - have you thought about just storing the scores in a file?</p>\n\n<p>If you decide to go with a database, you might consider <a href=\"http://sqlite.org/\" rel=\"nofollow noreferrer\">SQLite</a>, which you can distribute just like a file. There's an open source .NET provider - <a href=\"http://sqlite.phxsoftware.com/\" rel=\"nofollow noreferrer\">System.Data.SQLite</a> - that includes everything you need to get started.</p>\n\n<p>Accessing and reading from a database in .NET is quite easy - take a look at <a href=\"https://stackoverflow.com/questions/930/how-do-i-connect-to-a-database-and-loop-over-a-recordset-in-c\">this question</a> for sample code.</p>\n"
},
{
"answer_id": 20087,
"author": "Greg Hurlman",
"author_id": 35,
"author_profile": "https://Stackoverflow.com/users/35",
"pm_score": 4,
"selected": false,
"text": "<p>A database would probably be overkill for something like this - start with storing your information in an XML doc (or series of XML docs, if there's a lot of data). You get all that nifty XCopy deployment stuff, you can still use LINQ, and it would be a smooth transition to a database if you decided later you really needed performant relational query logic.</p>\n"
},
{
"answer_id": 20089,
"author": "TheSmurf",
"author_id": 1975282,
"author_profile": "https://Stackoverflow.com/users/1975282",
"pm_score": 2,
"selected": false,
"text": "<p>I don't know if a database is necessarily what you want. That may be overkill for storing stats for a simple game like that. Databases are good; but you should not automatically use one in every situation (I'm assuming that this is a client application, not an online game).</p>\n\n<p>Personally, for a game that exists only on the user's computer, I would just store the stats in a file (XML or binary - choice depends on whether you want it to be human-readable or not).</p>\n"
},
{
"answer_id": 20095,
"author": "Jon Dewees",
"author_id": 1365,
"author_profile": "https://Stackoverflow.com/users/1365",
"pm_score": 2,
"selected": false,
"text": "<p><a href=\"http://www.microsoft.com/sql/editions/express/default.mspx\" rel=\"nofollow noreferrer\">SQL Express</a> from MS is a great free, lightweight version of their SQL Server database. You could try that if you go the DB route.</p>\n\n<p>Alternatively, you could simply create datasets within the application and serialize them to xml, or you could use something like the newly minted <a href=\"http://en.wikipedia.org/wiki/ADO.NET_Entity_Framework\" rel=\"nofollow noreferrer\">Entity Framework</a> that shipped with .NET 3.5 SP1</p>\n"
},
{
"answer_id": 20117,
"author": "Skizz",
"author_id": 1898,
"author_profile": "https://Stackoverflow.com/users/1898",
"pm_score": 1,
"selected": false,
"text": "<p>You can either use the <code>System::Xml</code> namespace or the <code>System::Data</code> namespace. The first gives you raw XML, the latter gives you a handy wrapper to the XML.</p>\n"
},
{
"answer_id": 20130,
"author": "Brian Ensink",
"author_id": 1254,
"author_profile": "https://Stackoverflow.com/users/1254",
"pm_score": 5,
"selected": true,
"text": "<p>Here is one idea: use Xml Serialization. Design your GameStats data structure and optionally use Xml attributes to influence the schema as you like. I like to use this method for small data sets because its quick and easy and all I need to do is design and manipulate the data structure.</p>\n\n<pre><code>\nusing (FileStream fs = new FileStream(....))\n{\n // Read in stats\n XmlSerializer xs = new XmlSerializer(typeof(GameStats));\n GameStats stats = (GameStats)xs.Deserialize(fs);\n\n // Manipulate stats here ...\n\n // Write out game stats\n XmlSerializer xs = new XmlSerializer(typeof(GameStats));\n xs.Serialize(fs, stats);\n\n fs.Close();\n}\n</code></pre>\n"
},
{
"answer_id": 20140,
"author": "Dale Ragan",
"author_id": 1117,
"author_profile": "https://Stackoverflow.com/users/1117",
"pm_score": 1,
"selected": false,
"text": "<p>I would recommend just using a database. I would recommend using LINQ or an ORM tool to interact with the database. For learning LINQ, I would take a look at Scott Guthrie's posts. I think there are 9 of them all together. I linked part 1 below. If you want to go with an ORM tool, say nhibernate, then I would recommend checking out the Summer of nHibernate screencasts. They are a really good learning resource for nhibernate.</p>\n\n<p>I disagree with using XML. With reporting stats on a lot of data, you can't beat using a relational database. Yeah, XML is lightweight, but there are a lot of choices for light weight relational databases also, besides going with a full blown service based implementation. (i.e. <a href=\"http://www.microsoft.com/sql/editions/compact/default.mspx\" rel=\"nofollow noreferrer\">SQL Server Compact</a>, <a href=\"http://www.sqlite.org/\" rel=\"nofollow noreferrer\">SQLite</a>, etc...)</p>\n\n<ul>\n<li><a href=\"http://weblogs.asp.net/scottgu/archive/2007/05/19/using-linq-to-sql-part-1.aspx\" rel=\"nofollow noreferrer\">Scott Guthrie on LINQ</a></li>\n<li><a href=\"http://www.summerofnhibernate.com/\" rel=\"nofollow noreferrer\">Summer of nHibernate</a></li>\n</ul>\n"
},
{
"answer_id": 20144,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 2,
"selected": false,
"text": "<p>I'd recommend saving your data in simple POCOs and either serializing them to xml or a binary file, like Brian did above.</p>\n\n<p>If you're hot for a database, I'd suggest <a href=\"http://www.microsoft.com/sql/editions/compact/default.mspx\" rel=\"nofollow noreferrer\">Sql Server Compact Edition</a>, or <a href=\"http://www.vistadb.net/\" rel=\"nofollow noreferrer\">VistaDB</a>. Both are hosted inproc within your application.</p>\n"
},
{
"answer_id": 20209,
"author": "Chris Marasti-Georg",
"author_id": 96,
"author_profile": "https://Stackoverflow.com/users/96",
"pm_score": 1,
"selected": false,
"text": "<p>For this situation, the <code>[Serializable]</code> attribute on a nicely modelled <code>Stats</code> class and <code>XmlSerializer</code> are the way to go, IMO.</p>\n"
}
] | 2008/08/21 | [
"https://Stackoverflow.com/questions/20061",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/271/"
] | I've recently taken up learning some C# and wrote a Yahtzee clone. My next step (now that the game logic is in place and functioning correctly) is to integrate some method of keeping stats across all the games played.
My question is this, how should I go about storing this information? My first thought would be to use a database and I have a feeling that's the answer I'll get... if that's the case, can you point me to a good resource for creating and accessing a database from a C# application?
---
Storing in an XML file actually makes more sense to me, but I thought if I suggested that I'd get torn apart ;). I'm used to building web applications and for those, text files are generally frowned upon.
So, going with an XML file, what classes should I be looking at that would allow for easy manipulation? | Here is one idea: use Xml Serialization. Design your GameStats data structure and optionally use Xml attributes to influence the schema as you like. I like to use this method for small data sets because its quick and easy and all I need to do is design and manipulate the data structure.
```
using (FileStream fs = new FileStream(....))
{
// Read in stats
XmlSerializer xs = new XmlSerializer(typeof(GameStats));
GameStats stats = (GameStats)xs.Deserialize(fs);
// Manipulate stats here ...
// Write out game stats
XmlSerializer xs = new XmlSerializer(typeof(GameStats));
xs.Serialize(fs, stats);
fs.Close();
}
``` |
20,063 | <p>What's the <strong>easiest</strong>, <strong>tersest</strong>, and most <strong>flexible</strong> method or library for parsing Python command line arguments?</p>
| [
{
"answer_id": 20065,
"author": "Corey",
"author_id": 1595,
"author_profile": "https://Stackoverflow.com/users/1595",
"pm_score": 4,
"selected": false,
"text": "<p>Use <code>optparse</code> which comes with the standard library. For example:</p>\n\n<pre><code>#!/usr/bin/env python\nimport optparse\n\ndef main():\n p = optparse.OptionParser()\n p.add_option('--person', '-p', default=\"world\")\n options, arguments = p.parse_args()\n print 'Hello %s' % options.person\n\nif __name__ == '__main__':\n main()\n</code></pre>\n\n<p>Source: <a href=\"http://www.ibm.com/developerworks/aix/library/au-pythocli/\" rel=\"nofollow noreferrer\">Using Python to create UNIX command line tools</a></p>\n\n<p>However as of Python 2.7 optparse is deprecated, see: <a href=\"https://stackoverflow.com/q/3217673/55075\">Why use argparse rather than optparse?</a></p>\n"
},
{
"answer_id": 20069,
"author": "fulmicoton",
"author_id": 446497,
"author_profile": "https://Stackoverflow.com/users/446497",
"pm_score": 4,
"selected": false,
"text": "<p>Pretty much everybody is using <a href=\"http://python.active-venture.com/lib/module-getopt.html\" rel=\"nofollow noreferrer\">getopt</a></p>\n\n<p>Here is the example code for the doc :</p>\n\n<pre><code>import getopt, sys\n\ndef main():\n try:\n opts, args = getopt.getopt(sys.argv[1:], \"ho:v\", [\"help\", \"output=\"])\n except getopt.GetoptError:\n # print help information and exit:\n usage()\n sys.exit(2)\n output = None\n verbose = False\n for o, a in opts:\n if o == \"-v\":\n verbose = True\n if o in (\"-h\", \"--help\"):\n usage()\n sys.exit()\n if o in (\"-o\", \"--output\"):\n output = a\n</code></pre>\n\n<p>So in a word, here is how it works.</p>\n\n<p>You've got two types of options. Those who are receiving arguments, and those who are\njust like switches.</p>\n\n<p><code>sys.argv</code> is pretty much your <code>char** argv</code> in C. Like in C you skip the first element which is the name of your program and parse only the arguments : <code>sys.argv[1:]</code></p>\n\n<p><code>Getopt.getopt</code> will parse it according to the rule you give in argument.</p>\n\n<p><code>\"ho:v\"</code> here describes the short arguments : <code>-ONELETTER</code>. The <code>:</code> means that <code>-o</code> accepts one argument.</p>\n\n<p>Finally <code>[\"help\", \"output=\"]</code> describes long arguments ( <code>--MORETHANONELETTER</code> ).\nThe <code>=</code> after output once again means that output accepts one arguments.</p>\n\n<p>The result is a list of couple (option,argument)</p>\n\n<p>If an option doesn't accept any argument (like <code>--help</code> here) the <code>arg</code> part is an empty string.\nYou then usually want to loop on this list and test the option name as in the example.</p>\n\n<p>I hope this helped you.</p>\n"
},
{
"answer_id": 20169,
"author": "Shadow2531",
"author_id": 1697,
"author_profile": "https://Stackoverflow.com/users/1697",
"pm_score": 3,
"selected": false,
"text": "<p>Just in case you might need to, this may help if you need to <strong>grab</strong> unicode arguments on Win32 (2K, XP etc):</p>\n\n<pre><code>\nfrom ctypes import *\n\ndef wmain(argc, argv):\n print argc\n for i in argv:\n print i\n return 0\n\ndef startup():\n size = c_int()\n ptr = windll.shell32.CommandLineToArgvW(windll.kernel32.GetCommandLineW(), byref(size))\n ref = c_wchar_p * size.value\n raw = ref.from_address(ptr)\n args = [arg for arg in raw]\n windll.kernel32.LocalFree(ptr)\n exit(wmain(len(args), args))\nstartup()\n</code></pre>\n"
},
{
"answer_id": 20222,
"author": "Chris Conway",
"author_id": 1412,
"author_profile": "https://Stackoverflow.com/users/1412",
"pm_score": 2,
"selected": false,
"text": "<p>I prefer optparse to getopt. It's very declarative: you tell it the names of the options and the effects they should have (e.g., setting a boolean field), and it hands you back a dictionary populated according to your specifications.</p>\n\n<p><a href=\"http://docs.python.org/lib/module-optparse.html\" rel=\"nofollow noreferrer\">http://docs.python.org/lib/module-optparse.html</a></p>\n"
},
{
"answer_id": 26910,
"author": "Thomas Vander Stichele",
"author_id": 2900,
"author_profile": "https://Stackoverflow.com/users/2900",
"pm_score": 9,
"selected": true,
"text": "<p><strong>This answer suggests <code>optparse</code> which is appropriate for older Python versions. For Python 2.7 and above, <code>argparse</code> replaces <code>optparse</code>. See <a href=\"https://stackoverflow.com/questions/3217673/why-use-argparse-rather-than-optparse\">this answer</a> for more information.</strong></p>\n\n<p>As other people pointed out, you are better off going with optparse over getopt. getopt is pretty much a one-to-one mapping of the standard getopt(3) C library functions, and not very easy to use.</p>\n\n<p>optparse, while being a bit more verbose, is much better structured and simpler to extend later on.</p>\n\n<p>Here's a typical line to add an option to your parser:</p>\n\n<pre><code>parser.add_option('-q', '--query',\n action=\"store\", dest=\"query\",\n help=\"query string\", default=\"spam\")\n</code></pre>\n\n<p>It pretty much speaks for itself; at processing time, it will accept -q or --query as options, store the argument in an attribute called query and has a default value if you don't specify it. It is also self-documenting in that you declare the help argument (which will be used when run with -h/--help) right there with the option.</p>\n\n<p>Usually you parse your arguments with:</p>\n\n<pre><code>options, args = parser.parse_args()\n</code></pre>\n\n<p>This will, by default, parse the standard arguments passed to the script (sys.argv[1:])</p>\n\n<p>options.query will then be set to the value you passed to the script.</p>\n\n<p>You create a parser simply by doing</p>\n\n<pre><code>parser = optparse.OptionParser()\n</code></pre>\n\n<p>These are all the basics you need. Here's a complete Python script that shows this:</p>\n\n<pre><code>import optparse\n\nparser = optparse.OptionParser()\n\nparser.add_option('-q', '--query',\n action=\"store\", dest=\"query\",\n help=\"query string\", default=\"spam\")\n\noptions, args = parser.parse_args()\n\nprint 'Query string:', options.query\n</code></pre>\n\n<p>5 lines of python that show you the basics.</p>\n\n<p>Save it in sample.py, and run it once with</p>\n\n<pre><code>python sample.py\n</code></pre>\n\n<p>and once with</p>\n\n<pre><code>python sample.py --query myquery\n</code></pre>\n\n<p>Beyond that, you will find that optparse is very easy to extend.\nIn one of my projects, I created a Command class which allows you to nest subcommands in a command tree easily. It uses optparse heavily to chain commands together. It's not something I can easily explain in a few lines, but feel free to <a href=\"https://thomas.apestaart.org/moap/trac/browser/trunk/moap/extern/command/command.py\" rel=\"noreferrer\">browse around in my repository</a> for the main class, as well as <a href=\"https://thomas.apestaart.org/moap/trac/browser/trunk/moap/command/doap.py\" rel=\"noreferrer\">a class that uses it and the option parser</a></p>\n"
},
{
"answer_id": 30973,
"author": "Peter Hoffmann",
"author_id": 720,
"author_profile": "https://Stackoverflow.com/users/720",
"pm_score": 2,
"selected": false,
"text": "<p>I think the best way for larger projects is optparse, but if you are looking for an easy way, maybe <a href=\"http://werkzeug.pocoo.org/documentation/script\" rel=\"nofollow noreferrer\">http://werkzeug.pocoo.org/documentation/script</a> is something for you.</p>\n\n<pre><code>from werkzeug import script\n\n# actions go here\ndef action_foo(name=\"\"):\n \"\"\"action foo does foo\"\"\"\n pass\n\ndef action_bar(id=0, title=\"default title\"):\n \"\"\"action bar does bar\"\"\"\n pass\n\nif __name__ == '__main__':\n script.run()\n</code></pre>\n\n<p>So basically every function action_* is exposed to the command line and a nice\nhelp message is generated for free. </p>\n\n<pre><code>python foo.py \nusage: foo.py <action> [<options>]\n foo.py --help\n\nactions:\n bar:\n action bar does bar\n\n --id integer 0\n --title string default title\n\n foo:\n action foo does foo\n\n --name string\n</code></pre>\n"
},
{
"answer_id": 979871,
"author": "Silfheed",
"author_id": 28421,
"author_profile": "https://Stackoverflow.com/users/28421",
"pm_score": 5,
"selected": false,
"text": "<p>The new hip way is <code>argparse</code> for <a href=\"https://stackoverflow.com/questions/1009860/how-to-read-process-command-line-arguments/1050472#1050472\">these</a> reasons. argparse > optparse > getopt</p>\n\n<p><strong>update:</strong> As of py2.7 <a href=\"http://docs.python.org/library/argparse.html\" rel=\"nofollow noreferrer\">argparse</a> is part of the standard library and <a href=\"http://docs.python.org/library/optparse.html\" rel=\"nofollow noreferrer\">optparse</a> is deprecated.</p>\n"
},
{
"answer_id": 11271779,
"author": "stalk",
"author_id": 821594,
"author_profile": "https://Stackoverflow.com/users/821594",
"pm_score": 1,
"selected": false,
"text": "<p><a href=\"https://github.com/muromec/consoleargs\" rel=\"nofollow\">consoleargs</a> deserves to be mentioned here. It is very easy to use. Check it out:</p>\n\n<pre><code>from consoleargs import command\n\n@command\ndef main(url, name=None):\n \"\"\"\n :param url: Remote URL \n :param name: File name\n \"\"\"\n print \"\"\"Downloading url '%r' into file '%r'\"\"\" % (url, name)\n\nif __name__ == '__main__':\n main()\n</code></pre>\n\n<p>Now in console:</p>\n\n<pre><code>% python demo.py --help\nUsage: demo.py URL [OPTIONS]\n\nURL: Remote URL \n\nOptions:\n --name -n File name\n\n% python demo.py http://www.google.com/\nDownloading url ''http://www.google.com/'' into file 'None'\n\n% python demo.py http://www.google.com/ --name=index.html\nDownloading url ''http://www.google.com/'' into file ''index.html''\n</code></pre>\n"
},
{
"answer_id": 16377263,
"author": "ndemou",
"author_id": 1011025,
"author_profile": "https://Stackoverflow.com/users/1011025",
"pm_score": 6,
"selected": false,
"text": "<h2>Using docopt</h2>\n\n<p>Since 2012 there is a very easy, powerful and really <em>cool</em> module for argument parsing called <a href=\"https://github.com/docopt/docopt\" rel=\"noreferrer\">docopt</a>. Here is an example taken from its documentation: </p>\n\n<pre><code>\"\"\"Naval Fate.\n\nUsage:\n naval_fate.py ship new <name>...\n naval_fate.py ship <name> move <x> <y> [--speed=<kn>]\n naval_fate.py ship shoot <x> <y>\n naval_fate.py mine (set|remove) <x> <y> [--moored | --drifting]\n naval_fate.py (-h | --help)\n naval_fate.py --version\n\nOptions:\n -h --help Show this screen.\n --version Show version.\n --speed=<kn> Speed in knots [default: 10].\n --moored Moored (anchored) mine.\n --drifting Drifting mine.\n\n\"\"\"\nfrom docopt import docopt\n\n\nif __name__ == '__main__':\n arguments = docopt(__doc__, version='Naval Fate 2.0')\n print(arguments)\n</code></pre>\n\n<p>So this is it: 2 lines of code plus your doc string which <em>is</em> essential and you get your arguments parsed and available in your arguments object.</p>\n\n<h2>Using python-fire</h2>\n\n<p>Since 2017 there's another cool module called <a href=\"https://github.com/google/python-fire\" rel=\"noreferrer\">python-fire</a>. It can generate a CLI interface for your code with you doing <em>zero</em> argument parsing. Here's a simple example from the documentation (this small program exposes the function <code>double</code> to the command line):</p>\n\n<pre><code>import fire\n\nclass Calculator(object):\n\n def double(self, number):\n return 2 * number\n\nif __name__ == '__main__':\n fire.Fire(Calculator)\n</code></pre>\n\n<p>From the command line, you can run:</p>\n\n<pre><code>> calculator.py double 10\n20\n> calculator.py double --number=15\n30\n</code></pre>\n"
},
{
"answer_id": 27069329,
"author": "suda",
"author_id": 83055,
"author_profile": "https://Stackoverflow.com/users/83055",
"pm_score": 5,
"selected": false,
"text": "<p>I prefer <a href=\"http://click.pocoo.org/\" rel=\"noreferrer\">Click</a>. It abstracts managing options and allows \"(...) creating beautiful command line interfaces in a composable way with as little code as necessary\".</p>\n\n<p>Here's example usage:</p>\n\n<pre><code>import click\n\[email protected]()\[email protected]('--count', default=1, help='Number of greetings.')\[email protected]('--name', prompt='Your name',\n help='The person to greet.')\ndef hello(count, name):\n \"\"\"Simple program that greets NAME for a total of COUNT times.\"\"\"\n for x in range(count):\n click.echo('Hello %s!' % name)\n\nif __name__ == '__main__':\n hello()\n</code></pre>\n\n<p>It also automatically generates nicely formatted help pages:</p>\n\n<pre><code>$ python hello.py --help\nUsage: hello.py [OPTIONS]\n\n Simple program that greets NAME for a total of COUNT times.\n\nOptions:\n --count INTEGER Number of greetings.\n --name TEXT The person to greet.\n --help Show this message and exit.\n</code></pre>\n"
},
{
"answer_id": 30493366,
"author": "Andrzej Pronobis",
"author_id": 1576602,
"author_profile": "https://Stackoverflow.com/users/1576602",
"pm_score": 9,
"selected": false,
"text": "<p><a href=\"https://docs.python.org/library/argparse.html\" rel=\"noreferrer\"><code>argparse</code></a> is the way to go. Here is a short summary of how to use it:</p>\n\n<p><strong>1) Initialize</strong></p>\n\n<pre><code>import argparse\n\n# Instantiate the parser\nparser = argparse.ArgumentParser(description='Optional app description')\n</code></pre>\n\n<p><strong>2) Add Arguments</strong></p>\n\n<pre><code># Required positional argument\nparser.add_argument('pos_arg', type=int,\n help='A required integer positional argument')\n\n# Optional positional argument\nparser.add_argument('opt_pos_arg', type=int, nargs='?',\n help='An optional integer positional argument')\n\n# Optional argument\nparser.add_argument('--opt_arg', type=int,\n help='An optional integer argument')\n\n# Switch\nparser.add_argument('--switch', action='store_true',\n help='A boolean switch')\n</code></pre>\n\n<p><strong>3) Parse</strong></p>\n\n<pre><code>args = parser.parse_args()\n</code></pre>\n\n<p><strong>4) Access</strong></p>\n\n<pre><code>print(\"Argument values:\")\nprint(args.pos_arg)\nprint(args.opt_pos_arg)\nprint(args.opt_arg)\nprint(args.switch)\n</code></pre>\n\n<p><strong>5) Check Values</strong></p>\n\n<pre><code>if args.pos_arg > 10:\n parser.error(\"pos_arg cannot be larger than 10\")\n</code></pre>\n\n<h2>Usage</h2>\n\n<p><strong>Correct use:</strong></p>\n\n<pre><code>$ ./app 1 2 --opt_arg 3 --switch\n\nArgument values:\n1\n2\n3\nTrue\n</code></pre>\n\n<p><strong>Incorrect arguments:</strong></p>\n\n<pre><code>$ ./app foo 2 --opt_arg 3 --switch\nusage: convert [-h] [--opt_arg OPT_ARG] [--switch] pos_arg [opt_pos_arg]\napp: error: argument pos_arg: invalid int value: 'foo'\n\n$ ./app 11 2 --opt_arg 3\nArgument values:\n11\n2\n3\nFalse\nusage: app [-h] [--opt_arg OPT_ARG] [--switch] pos_arg [opt_pos_arg]\nconvert: error: pos_arg cannot be larger than 10\n</code></pre>\n\n<p><strong>Full help:</strong></p>\n\n<pre><code>$ ./app -h\n\nusage: app [-h] [--opt_arg OPT_ARG] [--switch] pos_arg [opt_pos_arg]\n\nOptional app description\n\npositional arguments:\n pos_arg A required integer positional argument\n opt_pos_arg An optional integer positional argument\n\noptional arguments:\n -h, --help show this help message and exit\n --opt_arg OPT_ARG An optional integer argument\n --switch A boolean switch\n</code></pre>\n"
},
{
"answer_id": 36516929,
"author": "erco",
"author_id": 836131,
"author_profile": "https://Stackoverflow.com/users/836131",
"pm_score": 1,
"selected": false,
"text": "<p>Here's a method, not a library, which seems to work for me.</p>\n\n<p>The goals here are to be terse, each argument parsed by a single line, the args line up for readability, the code is simple and doesn't depend on any special modules (only os + sys), warns about missing or unknown arguments gracefully, use a simple for/range() loop, and works across python 2.x and 3.x</p>\n\n<p>Shown are two toggle flags (-d, -v), and two values controlled by arguments (-i xxx and -o xxx).</p>\n\n<pre><code>import os,sys\n\ndef HelpAndExit():\n print(\"<<your help output goes here>>\")\n sys.exit(1)\n\ndef Fatal(msg):\n sys.stderr.write(\"%s: %s\\n\" % (os.path.basename(sys.argv[0]), msg))\n sys.exit(1)\n\ndef NextArg(i):\n '''Return the next command line argument (if there is one)'''\n if ((i+1) >= len(sys.argv)):\n Fatal(\"'%s' expected an argument\" % sys.argv[i])\n return(1, sys.argv[i+1])\n\n### MAIN\nif __name__=='__main__':\n\n verbose = 0\n debug = 0\n infile = \"infile\"\n outfile = \"outfile\"\n\n # Parse command line\n skip = 0\n for i in range(1, len(sys.argv)):\n if not skip:\n if sys.argv[i][:2] == \"-d\": debug ^= 1\n elif sys.argv[i][:2] == \"-v\": verbose ^= 1\n elif sys.argv[i][:2] == \"-i\": (skip,infile) = NextArg(i)\n elif sys.argv[i][:2] == \"-o\": (skip,outfile) = NextArg(i)\n elif sys.argv[i][:2] == \"-h\": HelpAndExit()\n elif sys.argv[i][:1] == \"-\": Fatal(\"'%s' unknown argument\" % sys.argv[i])\n else: Fatal(\"'%s' unexpected\" % sys.argv[i])\n else: skip = 0\n\n print(\"%d,%d,%s,%s\" % (debug,verbose,infile,outfile))\n</code></pre>\n\n<p>The goal of NextArg() is to return the next argument while checking for missing data, and 'skip' skips the loop when NextArg() is used, keeping the flag parsing down to one liners.</p>\n"
},
{
"answer_id": 43234054,
"author": "Simon Hibbs",
"author_id": 318488,
"author_profile": "https://Stackoverflow.com/users/318488",
"pm_score": 4,
"selected": false,
"text": "<p><strong>Lightweight command line argument defaults</strong></p>\n\n<p>Although <code>argparse</code> is great and is the right answer for fully documented command line switches and advanced features, you can use function argument defaults to handles straightforward positional arguments very simply.</p>\n\n<pre><code>import sys\n\ndef get_args(name='default', first='a', second=2):\n return first, int(second)\n\nfirst, second = get_args(*sys.argv)\nprint first, second\n</code></pre>\n\n<p>The 'name' argument captures the script name and is not used. Test output looks like this:</p>\n\n<pre><code>> ./test.py\na 2\n> ./test.py A\nA 2\n> ./test.py A 20\nA 20\n</code></pre>\n\n<p>For simple scripts where I just want some default values, I find this quite sufficient. You might also want to include some type coercion in the return values or command line values will all be strings.</p>\n"
},
{
"answer_id": 51185393,
"author": "QA Collective",
"author_id": 5196274,
"author_profile": "https://Stackoverflow.com/users/5196274",
"pm_score": 3,
"selected": false,
"text": "<p>Argparse code can be longer than actual implementation code!</p>\n\n<p>That's a problem I find with most popular argument parsing options is that if your parameters are only modest, the code to document them becomes disproportionately large to the benefit they provide. </p>\n\n<p>A relative new-comer to the argument parsing scene (I think) is <a href=\"https://micheles.github.io/plac/\" rel=\"noreferrer\">plac</a>.</p>\n\n<p>It makes some acknowledged trade-offs with argparse, but uses inline documentation and wraps simply around <code>main()</code> type function function:</p>\n\n<pre><code>def main(excel_file_path: \"Path to input training file.\",\n excel_sheet_name:\"Name of the excel sheet containing training data including columns 'Label' and 'Description'.\",\n existing_model_path: \"Path to an existing model to refine.\"=None,\n batch_size_start: \"The smallest size of any minibatch.\"=10.,\n batch_size_stop: \"The largest size of any minibatch.\"=250.,\n batch_size_step: \"The step for increase in minibatch size.\"=1.002,\n batch_test_steps: \"Flag. If True, show minibatch steps.\"=False):\n\"Train a Spacy (http://spacy.io/) text classification model with gold document and label data until the model nears convergence (LOSS < 0.5).\"\n\n pass # Implementation code goes here!\n\nif __name__ == '__main__':\n import plac; plac.call(main)\n</code></pre>\n"
},
{
"answer_id": 51498731,
"author": "Erik",
"author_id": 7384642,
"author_profile": "https://Stackoverflow.com/users/7384642",
"pm_score": 0,
"selected": false,
"text": "<p>I extended Erco's approach to allow for required positional arguments and for optional arguments. These should precede the -d, -v etc. arguments.</p>\n\n<p>Positional and optional arguments can be retrieved with PosArg(i) and OptArg(i, default) respectively.\nWhen an optional argument is found the start position of searching for options (e.g. -i) is moved 1 ahead to avoid causing an 'unexpected' fatal.</p>\n\n<pre><code>import os,sys\n\n\ndef HelpAndExit():\n print(\"<<your help output goes here>>\")\n sys.exit(1)\n\ndef Fatal(msg):\n sys.stderr.write(\"%s: %s\\n\" % (os.path.basename(sys.argv[0]), msg))\n sys.exit(1)\n\ndef NextArg(i):\n '''Return the next command line argument (if there is one)'''\n if ((i+1) >= len(sys.argv)):\n Fatal(\"'%s' expected an argument\" % sys.argv[i])\n return(1, sys.argv[i+1])\n\ndef PosArg(i):\n '''Return positional argument'''\n if i >= len(sys.argv):\n Fatal(\"'%s' expected an argument\" % sys.argv[i])\n return sys.argv[i]\n\ndef OptArg(i, default):\n '''Return optional argument (if there is one)'''\n if i >= len(sys.argv):\n Fatal(\"'%s' expected an argument\" % sys.argv[i])\n if sys.argv[i][:1] != '-':\n return True, sys.argv[i]\n else:\n return False, default\n\n\n### MAIN\nif __name__=='__main__':\n\n verbose = 0\n debug = 0\n infile = \"infile\"\n outfile = \"outfile\"\n options_start = 3\n\n # --- Parse two positional parameters ---\n n1 = int(PosArg(1))\n n2 = int(PosArg(2))\n\n # --- Parse an optional parameters ---\n present, a3 = OptArg(3,50)\n n3 = int(a3)\n options_start += int(present)\n\n # --- Parse rest of command line ---\n skip = 0\n for i in range(options_start, len(sys.argv)):\n if not skip:\n if sys.argv[i][:2] == \"-d\": debug ^= 1\n elif sys.argv[i][:2] == \"-v\": verbose ^= 1\n elif sys.argv[i][:2] == \"-i\": (skip,infile) = NextArg(i)\n elif sys.argv[i][:2] == \"-o\": (skip,outfile) = NextArg(i)\n elif sys.argv[i][:2] == \"-h\": HelpAndExit()\n elif sys.argv[i][:1] == \"-\": Fatal(\"'%s' unknown argument\" % sys.argv[i])\n else: Fatal(\"'%s' unexpected\" % sys.argv[i])\n else: skip = 0\n\n print(\"Number 1 = %d\" % n1)\n print(\"Number 2 = %d\" % n2)\n print(\"Number 3 = %d\" % n3)\n print(\"Debug = %d\" % debug)\n print(\"verbose = %d\" % verbose)\n print(\"infile = %s\" % infile)\n print(\"outfile = %s\" % outfile) \n</code></pre>\n"
}
] | 2008/08/21 | [
"https://Stackoverflow.com/questions/20063",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1335/"
] | What's the **easiest**, **tersest**, and most **flexible** method or library for parsing Python command line arguments? | **This answer suggests `optparse` which is appropriate for older Python versions. For Python 2.7 and above, `argparse` replaces `optparse`. See [this answer](https://stackoverflow.com/questions/3217673/why-use-argparse-rather-than-optparse) for more information.**
As other people pointed out, you are better off going with optparse over getopt. getopt is pretty much a one-to-one mapping of the standard getopt(3) C library functions, and not very easy to use.
optparse, while being a bit more verbose, is much better structured and simpler to extend later on.
Here's a typical line to add an option to your parser:
```
parser.add_option('-q', '--query',
action="store", dest="query",
help="query string", default="spam")
```
It pretty much speaks for itself; at processing time, it will accept -q or --query as options, store the argument in an attribute called query and has a default value if you don't specify it. It is also self-documenting in that you declare the help argument (which will be used when run with -h/--help) right there with the option.
Usually you parse your arguments with:
```
options, args = parser.parse_args()
```
This will, by default, parse the standard arguments passed to the script (sys.argv[1:])
options.query will then be set to the value you passed to the script.
You create a parser simply by doing
```
parser = optparse.OptionParser()
```
These are all the basics you need. Here's a complete Python script that shows this:
```
import optparse
parser = optparse.OptionParser()
parser.add_option('-q', '--query',
action="store", dest="query",
help="query string", default="spam")
options, args = parser.parse_args()
print 'Query string:', options.query
```
5 lines of python that show you the basics.
Save it in sample.py, and run it once with
```
python sample.py
```
and once with
```
python sample.py --query myquery
```
Beyond that, you will find that optparse is very easy to extend.
In one of my projects, I created a Command class which allows you to nest subcommands in a command tree easily. It uses optparse heavily to chain commands together. It's not something I can easily explain in a few lines, but feel free to [browse around in my repository](https://thomas.apestaart.org/moap/trac/browser/trunk/moap/extern/command/command.py) for the main class, as well as [a class that uses it and the option parser](https://thomas.apestaart.org/moap/trac/browser/trunk/moap/command/doap.py) |
20,081 | <p>I've written PL/SQL code to denormalize a table into a much-easer-to-query form. The code uses a temporary table to do some of its work, merging some rows from the original table together.</p>
<p>The logic is written as a <a href="http://www.oreillynet.com/lpt/a/3136" rel="nofollow noreferrer">pipelined table function</a>, following the pattern from the linked article. The table function uses a <code>PRAGMA AUTONOMOUS_TRANSACTION</code> declaration to permit the temporary table manipulation, and also accepts a cursor input parameter to restrict the denormalization to certain ID values.</p>
<p>I then created a view to query the table function, passing in all possible ID values as a cursor (other uses of the function will be more restrictive).</p>
<p>My question: is this all really necessary? Have I completely missed a much more simple way of accomplishing the same thing?</p>
<p>Every time I touch PL/SQL I get the impression that I'm typing way too much.</p>
<p><strong>Update:</strong> I'll add a sketch of the table I'm dealing with to give everyone an idea of the denormalization that I'm talking about. The table stores a history of employee jobs, each with an activation row, and (possibly) a termination row. It's possible for an employee to have multiple simultaneous jobs, as well as the same job over and over again in non-contiguous date ranges. For example:</p>
<pre><code>| EMP_ID | JOB_ID | STATUS | EFF_DATE | other columns...
| 1 | 10 | A | 10-JAN-2008 |
| 2 | 11 | A | 13-JAN-2008 |
| 1 | 12 | A | 20-JAN-2008 |
| 2 | 11 | T | 01-FEB-2008 |
| 1 | 10 | T | 02-FEB-2008 |
| 2 | 11 | A | 20-FEB-2008 |
</code></pre>
<p>Querying that to figure out who is working when in what job is non-trivial. So, my denormalization function populates the temporary table with just the date ranges for each job, for any <code>EMP_ID</code>s passed in though the cursor. Passing in <code>EMP_ID</code>s 1 and 2 would produce the following:</p>
<pre><code>| EMP_ID | JOB_ID | START_DATE | END_DATE |
| 1 | 10 | 10-JAN-2008 | 02-FEB-2008 |
| 2 | 11 | 13-JAN-2008 | 01-FEB-2008 |
| 1 | 12 | 20-JAN-2008 | |
| 2 | 11 | 20-FEB-2008 | |
</code></pre>
<p>(<code>END_DATE</code> allows <code>NULL</code>s for jobs that don't have a predetermined termination date.)</p>
<p>As you can imagine, this denormalized form is much, much easier to query, but creating it--so far as I can tell--requires a temporary table to store the intermediate results (e.g., job records for which the activation row has been found, but not the termination...yet). Using the pipelined table function to populate the temporary table and then return its rows is the only way I've figured out how to do it.</p>
| [
{
"answer_id": 22033,
"author": "hollystyles",
"author_id": 2083160,
"author_profile": "https://Stackoverflow.com/users/2083160",
"pm_score": 1,
"selected": false,
"text": "<p>Rather than having the input parameter as a cursor, I would have a table variable (don't know if Oracle has such a thing I'm a TSQL guy) or populate another temp table with the ID values and join on it in the view/function or wherever you need to.</p>\n\n<p>The only time for cursors in my honest opinion is when you <em>have</em> to loop. And when you have to loop I always recommend to do that outside of the database in the application logic.</p>\n"
},
{
"answer_id": 22680,
"author": "yukondude",
"author_id": 726,
"author_profile": "https://Stackoverflow.com/users/726",
"pm_score": 0,
"selected": false,
"text": "<p>I couldn't agree with you more, HollyStyles. I also used to be a TSQL guy, and find some of Oracle's idiosyncrasies more than a little perplexing. Unfortunately, temp tables aren't as convenient in Oracle, and in this case, other existing SQL logic is expecting to directly query a table, so I give it this view instead. There's really no application logic that exists outside of the database in this system.</p>\n\n<p>Oracle developers do seem to use cursors much more eagerly than I would have thought. Given the bondage & discipline nature of PL/SQL, that's all the more surprising.</p>\n"
},
{
"answer_id": 89084,
"author": "Sergey Stadnik",
"author_id": 10557,
"author_profile": "https://Stackoverflow.com/users/10557",
"pm_score": 0,
"selected": false,
"text": "<p>The simplest solution is:</p>\n\n<ol>\n<li><p>Create a <a href=\"http://www.oracle-base.com/articles/8i/TemporaryTables.php\" rel=\"nofollow noreferrer\">global temporary table</a> containing just IDs you need:</p>\n\n<pre><code>CREATE GLOBAL TEMPORARY TABLE tab_ids (id INTEGER) \nON COMMIT DELETE ROWS;\n</code></pre></li>\n<li><p>Populate the temporary table with the IDs you need.</p></li>\n<li><p>Use EXISTS operation in your procedure to select the rows that are only in the IDs table:</p>\n\n<pre><code> SELECT yt.col1, yt.col2 FROM your\\_table yt \n WHERE EXISTS ( \n SELECT 'X' FROM tab_ids ti \n WHERE ti.id = yt.id \n )\n</code></pre></li>\n</ol>\n\n<p>You can also pass a comma-separated string of IDs as a function parameter and parse it into a table. This is performed by a single SELECT. Want to know more - ask me how :-) But it's got to be a separate question.</p>\n"
},
{
"answer_id": 92283,
"author": "mathewbutler",
"author_id": 2288,
"author_profile": "https://Stackoverflow.com/users/2288",
"pm_score": 1,
"selected": false,
"text": "<p>It sounds like you are giving away some read consistency here ie: it will be possible for the contents of your temporary table to be out of sync with the source data, if you have concurrent modification data modification.</p>\n\n<p>Without knowing the requirements, nor complexity of what you want to achieve. I would attempt</p>\n\n<ol>\n<li>to define a view, containing (possibly complex) logic in SQL, else I'd add some PL/SQL to the mix with;</li>\n<li>A pipelined table function, but using an SQL collection type (instead of the temporary table ). A simple example is here: <a href=\"http://asktom.oracle.com/pls/asktom/f?p=100:11:0::::P11_QUESTION_ID:4447489221109\" rel=\"nofollow noreferrer\">http://asktom.oracle.com/pls/asktom/f?p=100:11:0::::P11_QUESTION_ID:4447489221109</a></li>\n</ol>\n\n<p>Number 2 would give you less moving parts and solve your consistency issue.</p>\n\n<p>Mathew Butler</p>\n"
},
{
"answer_id": 97091,
"author": "Nick Pierpoint",
"author_id": 4003,
"author_profile": "https://Stackoverflow.com/users/4003",
"pm_score": 3,
"selected": true,
"text": "<p>I think a way to approach this is to use analytic functions...</p>\n\n<p>I set up your test case using:</p>\n\n<pre><code>create table employee_job (\n emp_id integer,\n job_id integer,\n status varchar2(1 char),\n eff_date date\n ); \n\ninsert into employee_job values (1,10,'A',to_date('10-JAN-2008','DD-MON-YYYY'));\ninsert into employee_job values (2,11,'A',to_date('13-JAN-2008','DD-MON-YYYY'));\ninsert into employee_job values (1,12,'A',to_date('20-JAN-2008','DD-MON-YYYY'));\ninsert into employee_job values (2,11,'T',to_date('01-FEB-2008','DD-MON-YYYY'));\ninsert into employee_job values (1,10,'T',to_date('02-FEB-2008','DD-MON-YYYY'));\ninsert into employee_job values (2,11,'A',to_date('20-FEB-2008','DD-MON-YYYY'));\n\ncommit;\n</code></pre>\n\n<p>I've used the <strong>lead</strong> function to get the next date and then wrapped it all as a sub-query just to get the \"A\" records and add the end date if there is one.</p>\n\n<pre><code>select\n emp_id,\n job_id,\n eff_date start_date,\n decode(next_status,'T',next_eff_date,null) end_date\nfrom\n (\n select\n emp_id,\n job_id,\n eff_date,\n status,\n lead(eff_date,1,null) over (partition by emp_id, job_id order by eff_date, status) next_eff_date,\n lead(status,1,null) over (partition by emp_id, job_id order by eff_date, status) next_status\n from\n employee_job\n )\nwhere\n status = 'A'\norder by\n start_date,\n emp_id,\n job_id\n</code></pre>\n\n<p>I'm sure there's some use cases I've missed but you get the idea. Analytic functions are your friend :)</p>\n\n<pre><code>EMP_ID JOB_ID START_DATE END_DATE \n 1 10 10-JAN-2008 02-FEB-2008 \n 2 11 13-JAN-2008 01-FEB-2008 \n 2 11 20-FEB-2008 \n 1 12 20-JAN-2008 \n</code></pre>\n"
},
{
"answer_id": 102942,
"author": "Tony Andrews",
"author_id": 18747,
"author_profile": "https://Stackoverflow.com/users/18747",
"pm_score": 1,
"selected": false,
"text": "<p>The real problem here is the \"write-only\" table design - by which I mean, it's easy to insert data into it, but tricky and inefficient to get useful information out of it! Your \"temporary\" table has the structure the \"permanent\" table should have had in the first place.</p>\n\n<p>Could you perhaps do this:</p>\n\n<ul>\n<li>Create a permanent table with the better structure</li>\n<li>Populate it to match the data in the first table</li>\n<li>Define a database trigger on the original table to keep the new table in sync from now on</li>\n</ul>\n\n<p>Then you can just select from the new table to perform your reporting.</p>\n"
}
] | 2008/08/21 | [
"https://Stackoverflow.com/questions/20081",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/726/"
] | I've written PL/SQL code to denormalize a table into a much-easer-to-query form. The code uses a temporary table to do some of its work, merging some rows from the original table together.
The logic is written as a [pipelined table function](http://www.oreillynet.com/lpt/a/3136), following the pattern from the linked article. The table function uses a `PRAGMA AUTONOMOUS_TRANSACTION` declaration to permit the temporary table manipulation, and also accepts a cursor input parameter to restrict the denormalization to certain ID values.
I then created a view to query the table function, passing in all possible ID values as a cursor (other uses of the function will be more restrictive).
My question: is this all really necessary? Have I completely missed a much more simple way of accomplishing the same thing?
Every time I touch PL/SQL I get the impression that I'm typing way too much.
**Update:** I'll add a sketch of the table I'm dealing with to give everyone an idea of the denormalization that I'm talking about. The table stores a history of employee jobs, each with an activation row, and (possibly) a termination row. It's possible for an employee to have multiple simultaneous jobs, as well as the same job over and over again in non-contiguous date ranges. For example:
```
| EMP_ID | JOB_ID | STATUS | EFF_DATE | other columns...
| 1 | 10 | A | 10-JAN-2008 |
| 2 | 11 | A | 13-JAN-2008 |
| 1 | 12 | A | 20-JAN-2008 |
| 2 | 11 | T | 01-FEB-2008 |
| 1 | 10 | T | 02-FEB-2008 |
| 2 | 11 | A | 20-FEB-2008 |
```
Querying that to figure out who is working when in what job is non-trivial. So, my denormalization function populates the temporary table with just the date ranges for each job, for any `EMP_ID`s passed in though the cursor. Passing in `EMP_ID`s 1 and 2 would produce the following:
```
| EMP_ID | JOB_ID | START_DATE | END_DATE |
| 1 | 10 | 10-JAN-2008 | 02-FEB-2008 |
| 2 | 11 | 13-JAN-2008 | 01-FEB-2008 |
| 1 | 12 | 20-JAN-2008 | |
| 2 | 11 | 20-FEB-2008 | |
```
(`END_DATE` allows `NULL`s for jobs that don't have a predetermined termination date.)
As you can imagine, this denormalized form is much, much easier to query, but creating it--so far as I can tell--requires a temporary table to store the intermediate results (e.g., job records for which the activation row has been found, but not the termination...yet). Using the pipelined table function to populate the temporary table and then return its rows is the only way I've figured out how to do it. | I think a way to approach this is to use analytic functions...
I set up your test case using:
```
create table employee_job (
emp_id integer,
job_id integer,
status varchar2(1 char),
eff_date date
);
insert into employee_job values (1,10,'A',to_date('10-JAN-2008','DD-MON-YYYY'));
insert into employee_job values (2,11,'A',to_date('13-JAN-2008','DD-MON-YYYY'));
insert into employee_job values (1,12,'A',to_date('20-JAN-2008','DD-MON-YYYY'));
insert into employee_job values (2,11,'T',to_date('01-FEB-2008','DD-MON-YYYY'));
insert into employee_job values (1,10,'T',to_date('02-FEB-2008','DD-MON-YYYY'));
insert into employee_job values (2,11,'A',to_date('20-FEB-2008','DD-MON-YYYY'));
commit;
```
I've used the **lead** function to get the next date and then wrapped it all as a sub-query just to get the "A" records and add the end date if there is one.
```
select
emp_id,
job_id,
eff_date start_date,
decode(next_status,'T',next_eff_date,null) end_date
from
(
select
emp_id,
job_id,
eff_date,
status,
lead(eff_date,1,null) over (partition by emp_id, job_id order by eff_date, status) next_eff_date,
lead(status,1,null) over (partition by emp_id, job_id order by eff_date, status) next_status
from
employee_job
)
where
status = 'A'
order by
start_date,
emp_id,
job_id
```
I'm sure there's some use cases I've missed but you get the idea. Analytic functions are your friend :)
```
EMP_ID JOB_ID START_DATE END_DATE
1 10 10-JAN-2008 02-FEB-2008
2 11 13-JAN-2008 01-FEB-2008
2 11 20-FEB-2008
1 12 20-JAN-2008
``` |
20,084 | <p>Following on from my <a href="https://stackoverflow.com/questions/19454/enforce-attribute-decoration-of-classesmethods">previous question</a> I have been working on getting my object model to serialize to XML. But I have now run into a problem (quelle surprise!).</p>
<p>The problem I have is that I have a collection, which is of a abstract base class type, which is populated by the concrete derived types.</p>
<p>I thought it would be fine to just add the XML attributes to all of the classes involved and everything would be peachy. Sadly, thats not the case!</p>
<p>So I have done some digging on Google and I now understand <em>why</em> it's not working. In that <strong>the <code>XmlSerializer</code> is in fact doing some clever reflection in order to serialize objects to/from XML, and since its based on the abstract type, it cannot figure out what the hell it's talking to</strong>. Fine.</p>
<p>I did come across <a href="http://www.codeproject.com/KB/XML/xmlserializerforunknown.aspx" rel="noreferrer">this page</a> on CodeProject, which looks like it may well help a lot (yet to read/consume fully), but I thought I would like to bring this problem to the StackOverflow table too, to see if you have any neat hacks/tricks in order to get this up and running in the quickest/lightest way possible.</p>
<p>One thing I should also add is that I <strong>DO NOT</strong> want to go down the <code>XmlInclude</code> route. There is simply too much coupling with it, and this area of the system is under heavy development, so the it would be a real maintenance headache!</p>
| [
{
"answer_id": 20097,
"author": "TheSmurf",
"author_id": 1975282,
"author_profile": "https://Stackoverflow.com/users/1975282",
"pm_score": 1,
"selected": false,
"text": "<p>I've done things similar to this. What I normally do is make sure all the XML serialization attributes are on the concrete class, and just have the properties on that class call through to the base classes (where required) to retrieve information that will be de/serialized when the serializer calls on those properties. It's a bit more coding work, but it does work much better than attempting to force the serializer to just do the right thing.</p>\n"
},
{
"answer_id": 20098,
"author": "Shaun Austin",
"author_id": 1120,
"author_profile": "https://Stackoverflow.com/users/1120",
"pm_score": 3,
"selected": false,
"text": "<p>One thing to look at is the fact that in the XmlSerialiser constructor you can pass an array of types that the serialiser might be having difficulty resolving. I've had to use that quite a few times where a collection or complex set of datastructures needed to be serialised and those types lived in different assemblies etc.</p>\n\n<p><a href=\"http://msdn.microsoft.com/en-us/library/e5aakyae.aspx\" rel=\"nofollow noreferrer\">XmlSerialiser Constructor with extraTypes param</a></p>\n\n<p>EDIT: I would add that this approach has the benefit over XmlInclude attributes etc that you can work out a way of discovering and compiling a list of your possible concrete types at runtime and stuff them in.</p>\n"
},
{
"answer_id": 20126,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 2,
"selected": false,
"text": "<p>Seriously, an extensible framework of POCOs will never serialize to XML reliably. I say this because I can guarantee someone will come along, extend your class, and botch it up.</p>\n\n<p>You should look into using XAML for serializing your object graphs. It is designed to do this, whereas XML serialization isn't. </p>\n\n<p>The Xaml serializer and deserializer handles generics without a problem, collections of base classes and interfaces as well (as long as the collections themselves implement <code>IList</code> or <code>IDictionary</code>). There are some caveats, such as marking your read only collection properties with the <code>DesignerSerializationAttribute</code>, but reworking your code to handle these corner cases isn't that hard.</p>\n"
},
{
"answer_id": 21958,
"author": "Rob Cooper",
"author_id": 832,
"author_profile": "https://Stackoverflow.com/users/832",
"pm_score": 2,
"selected": false,
"text": "<p>Just a quick update on this, I have not forgotten!</p>\n\n<p>Just doing some more research, looks like I am on to a winner, just need to get the code sorted.</p>\n\n<p>So far, I have the following:</p>\n\n<ul>\n<li>The <em>XmlSeralizer</em> is basically a class that does some nifty reflection on the classes it is serializing. It determines the properties that are serialized based on the <strong>Type</strong>.</li>\n<li>The reason the problem occurs is because a type mismatch is occurring, it is expecting the <em>BaseType</em> but in fact receives the <em>DerivedType</em> .. While you may think that it would treat it polymorphically, it doesn't since it would involve a whole extra load of reflection and type-checking, which it is not designed to do.</li>\n</ul>\n\n<p>This behaviour appears to be able to be overridden (code pending) by creating a proxy class to act as the go-between for the serializer. This will basically determine the type of the derived class and then serialize that as normal. This proxy class then will feed that XML back up the line to the main serializer..</p>\n\n<p>Watch this space! ^_^</p>\n"
},
{
"answer_id": 392690,
"author": "Max Galkin",
"author_id": 2351099,
"author_profile": "https://Stackoverflow.com/users/2351099",
"pm_score": 2,
"selected": false,
"text": "<p>It's certainly a solution to your problem, but there is another problem, which somewhat undermines your intention to use \"portable\" XML format. Bad thing happens when you decide to change classes in the next version of your program and you need to support both formats of serialization -- the new one and the old one (because your clients still use thier old files/databases, or they connect to your server using old version of your product). But you can't use this serializator anymore, because you used </p>\n\n<pre><code>type.AssemblyQualifiedName\n</code></pre>\n\n<p>which looks like</p>\n\n<pre><code>TopNamespace.SubNameSpace.ContainingClass+NestedClass, MyAssembly, Version=1.3.0.0, Culture=neutral, PublicKeyToken=b17a5c561934e089\n</code></pre>\n\n<p>that is contains your assembly attributes and version...</p>\n\n<p>Now if you try to change your assembly version, or you decide to sign it, this deserialization is not going to work...</p>\n"
},
{
"answer_id": 985495,
"author": "Rob Cooper",
"author_id": 832,
"author_profile": "https://Stackoverflow.com/users/832",
"pm_score": 7,
"selected": true,
"text": "<h2>Problem Solved!</h2>\n<p>OK, so I finally got there (admittedly with a <strong>lot</strong> of help from <a href=\"http://www.codeproject.com/KB/XML/xmlserializerforunknown.aspx\" rel=\"noreferrer\">here</a>!).</p>\n<p>So summarise:</p>\n<h3>Goals:</h3>\n<ul>\n<li>I didn't want to go down the <em>XmlInclude</em> route due to the maintenence headache.</li>\n<li>Once a solution was found, I wanted it to be quick to implement in other applications.</li>\n<li>Collections of Abstract types may be used, as well as individual abstract properties.</li>\n<li>I didn't really want to bother with having to do "special" things in the concrete classes.</li>\n</ul>\n<h3>Identified Issues/Points to Note:</h3>\n<ul>\n<li><em>XmlSerializer</em> does some pretty cool reflection, but it is <em>very</em> limited when it comes to abstract types (i.e. it will only work with instances of the abstract type itself, not subclasses).</li>\n<li>The Xml attribute decorators define how the XmlSerializer treats the properties its finds. The physical type can also be specified, but this creates a <strong>tight coupling</strong> between the class and the serializer (not good).</li>\n<li>We can implement our own XmlSerializer by creating a class that implements <em>IXmlSerializable</em> .</li>\n</ul>\n<h2>The Solution</h2>\n<p>I created a generic class, in which you specify the generic type as the abstract type you will be working with. This gives the class the ability to "translate" between the abstract type and the concrete type since we can hard-code the casting (i.e. we can get more info than the XmlSerializer can).</p>\n<p>I then implemented the <em>IXmlSerializable</em> interface, this is pretty straight forward, but when serializing we need to ensure we write the type of the concrete class to the XML, so we can cast it back when de-serializing. It is also important to note it must be <strong>fully qualified</strong> as the assemblies that the two classes are in are likely to differ. There is of course a little type checking and stuff that needs to happen here.</p>\n<p>Since the XmlSerializer cannot cast, we need to provide the code to do that, so the implicit operator is then overloaded (I never even knew you could do this!).</p>\n<p>The code for the AbstractXmlSerializer is this:</p>\n<pre><code>using System;\nusing System.Collections.Generic;\nusing System.Text;\nusing System.Xml.Serialization;\n\nnamespace Utility.Xml\n{\n public class AbstractXmlSerializer<AbstractType> : IXmlSerializable\n {\n // Override the Implicit Conversions Since the XmlSerializer\n // Casts to/from the required types implicitly.\n public static implicit operator AbstractType(AbstractXmlSerializer<AbstractType> o)\n {\n return o.Data;\n }\n\n public static implicit operator AbstractXmlSerializer<AbstractType>(AbstractType o)\n {\n return o == null ? null : new AbstractXmlSerializer<AbstractType>(o);\n }\n\n private AbstractType _data;\n /// <summary>\n /// [Concrete] Data to be stored/is stored as XML.\n /// </summary>\n public AbstractType Data\n {\n get { return _data; }\n set { _data = value; }\n }\n\n /// <summary>\n /// **DO NOT USE** This is only added to enable XML Serialization.\n /// </summary>\n /// <remarks>DO NOT USE THIS CONSTRUCTOR</remarks>\n public AbstractXmlSerializer()\n {\n // Default Ctor (Required for Xml Serialization - DO NOT USE)\n }\n\n /// <summary>\n /// Initialises the Serializer to work with the given data.\n /// </summary>\n /// <param name="data">Concrete Object of the AbstractType Specified.</param>\n public AbstractXmlSerializer(AbstractType data)\n {\n _data = data;\n }\n\n #region IXmlSerializable Members\n\n public System.Xml.Schema.XmlSchema GetSchema()\n {\n return null; // this is fine as schema is unknown.\n }\n\n public void ReadXml(System.Xml.XmlReader reader)\n {\n // Cast the Data back from the Abstract Type.\n string typeAttrib = reader.GetAttribute("type");\n\n // Ensure the Type was Specified\n if (typeAttrib == null)\n throw new ArgumentNullException("Unable to Read Xml Data for Abstract Type '" + typeof(AbstractType).Name +\n "' because no 'type' attribute was specified in the XML.");\n\n Type type = Type.GetType(typeAttrib);\n\n // Check the Type is Found.\n if (type == null)\n throw new InvalidCastException("Unable to Read Xml Data for Abstract Type '" + typeof(AbstractType).Name +\n "' because the type specified in the XML was not found.");\n\n // Check the Type is a Subclass of the AbstractType.\n if (!type.IsSubclassOf(typeof(AbstractType)))\n throw new InvalidCastException("Unable to Read Xml Data for Abstract Type '" + typeof(AbstractType).Name +\n "' because the Type specified in the XML differs ('" + type.Name + "').");\n\n // Read the Data, Deserializing based on the (now known) concrete type.\n reader.ReadStartElement();\n this.Data = (AbstractType)new\n XmlSerializer(type).Deserialize(reader);\n reader.ReadEndElement();\n }\n\n public void WriteXml(System.Xml.XmlWriter writer)\n {\n // Write the Type Name to the XML Element as an Attrib and Serialize\n Type type = _data.GetType();\n\n // BugFix: Assembly must be FQN since Types can/are external to current.\n writer.WriteAttributeString("type", type.AssemblyQualifiedName);\n new XmlSerializer(type).Serialize(writer, _data);\n }\n\n #endregion\n }\n}\n</code></pre>\n<p>So, from there, how do we tell the XmlSerializer to work with our serializer rather than the default? We must pass our type within the Xml attributes type property, for example:</p>\n<pre><code>[XmlRoot("ClassWithAbstractCollection")]\npublic class ClassWithAbstractCollection\n{\n private List<AbstractType> _list;\n [XmlArray("ListItems")]\n [XmlArrayItem("ListItem", Type = typeof(AbstractXmlSerializer<AbstractType>))]\n public List<AbstractType> List\n {\n get { return _list; }\n set { _list = value; }\n }\n\n private AbstractType _prop;\n [XmlElement("MyProperty", Type=typeof(AbstractXmlSerializer<AbstractType>))]\n public AbstractType MyProperty\n {\n get { return _prop; }\n set { _prop = value; }\n }\n\n public ClassWithAbstractCollection()\n {\n _list = new List<AbstractType>();\n }\n}\n</code></pre>\n<p>Here you can see, we have a collection and a single property being exposed, and all we need to do is add the <em>type</em> named parameter to the Xml declaration, easy! :D</p>\n<p><strong>NOTE: If you use this code, I would really appreciate a shout-out. It will also help drive more people to the community :)</strong></p>\n<p>Now, but unsure as to what to do with answers here since they all had their pro's and con's. I'll upmod those that I feel were useful (no offence to those that weren't) and close this off once I have the rep :)</p>\n<p>Interesting problem and good fun to solve! :)</p>\n"
},
{
"answer_id": 26373293,
"author": "user2009677",
"author_id": 2009677,
"author_profile": "https://Stackoverflow.com/users/2009677",
"pm_score": 1,
"selected": false,
"text": "<p>Even better, using notation:</p>\n\n<pre><code>[XmlRoot]\npublic class MyClass {\n public abstract class MyAbstract {} \n public class MyInherited : MyAbstract {} \n [XmlArray(), XmlArrayItem(typeof(MyInherited))] \n public MyAbstract[] Items {get; set; } \n}\n</code></pre>\n"
}
] | 2008/08/21 | [
"https://Stackoverflow.com/questions/20084",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/832/"
] | Following on from my [previous question](https://stackoverflow.com/questions/19454/enforce-attribute-decoration-of-classesmethods) I have been working on getting my object model to serialize to XML. But I have now run into a problem (quelle surprise!).
The problem I have is that I have a collection, which is of a abstract base class type, which is populated by the concrete derived types.
I thought it would be fine to just add the XML attributes to all of the classes involved and everything would be peachy. Sadly, thats not the case!
So I have done some digging on Google and I now understand *why* it's not working. In that **the `XmlSerializer` is in fact doing some clever reflection in order to serialize objects to/from XML, and since its based on the abstract type, it cannot figure out what the hell it's talking to**. Fine.
I did come across [this page](http://www.codeproject.com/KB/XML/xmlserializerforunknown.aspx) on CodeProject, which looks like it may well help a lot (yet to read/consume fully), but I thought I would like to bring this problem to the StackOverflow table too, to see if you have any neat hacks/tricks in order to get this up and running in the quickest/lightest way possible.
One thing I should also add is that I **DO NOT** want to go down the `XmlInclude` route. There is simply too much coupling with it, and this area of the system is under heavy development, so the it would be a real maintenance headache! | Problem Solved!
---------------
OK, so I finally got there (admittedly with a **lot** of help from [here](http://www.codeproject.com/KB/XML/xmlserializerforunknown.aspx)!).
So summarise:
### Goals:
* I didn't want to go down the *XmlInclude* route due to the maintenence headache.
* Once a solution was found, I wanted it to be quick to implement in other applications.
* Collections of Abstract types may be used, as well as individual abstract properties.
* I didn't really want to bother with having to do "special" things in the concrete classes.
### Identified Issues/Points to Note:
* *XmlSerializer* does some pretty cool reflection, but it is *very* limited when it comes to abstract types (i.e. it will only work with instances of the abstract type itself, not subclasses).
* The Xml attribute decorators define how the XmlSerializer treats the properties its finds. The physical type can also be specified, but this creates a **tight coupling** between the class and the serializer (not good).
* We can implement our own XmlSerializer by creating a class that implements *IXmlSerializable* .
The Solution
------------
I created a generic class, in which you specify the generic type as the abstract type you will be working with. This gives the class the ability to "translate" between the abstract type and the concrete type since we can hard-code the casting (i.e. we can get more info than the XmlSerializer can).
I then implemented the *IXmlSerializable* interface, this is pretty straight forward, but when serializing we need to ensure we write the type of the concrete class to the XML, so we can cast it back when de-serializing. It is also important to note it must be **fully qualified** as the assemblies that the two classes are in are likely to differ. There is of course a little type checking and stuff that needs to happen here.
Since the XmlSerializer cannot cast, we need to provide the code to do that, so the implicit operator is then overloaded (I never even knew you could do this!).
The code for the AbstractXmlSerializer is this:
```
using System;
using System.Collections.Generic;
using System.Text;
using System.Xml.Serialization;
namespace Utility.Xml
{
public class AbstractXmlSerializer<AbstractType> : IXmlSerializable
{
// Override the Implicit Conversions Since the XmlSerializer
// Casts to/from the required types implicitly.
public static implicit operator AbstractType(AbstractXmlSerializer<AbstractType> o)
{
return o.Data;
}
public static implicit operator AbstractXmlSerializer<AbstractType>(AbstractType o)
{
return o == null ? null : new AbstractXmlSerializer<AbstractType>(o);
}
private AbstractType _data;
/// <summary>
/// [Concrete] Data to be stored/is stored as XML.
/// </summary>
public AbstractType Data
{
get { return _data; }
set { _data = value; }
}
/// <summary>
/// **DO NOT USE** This is only added to enable XML Serialization.
/// </summary>
/// <remarks>DO NOT USE THIS CONSTRUCTOR</remarks>
public AbstractXmlSerializer()
{
// Default Ctor (Required for Xml Serialization - DO NOT USE)
}
/// <summary>
/// Initialises the Serializer to work with the given data.
/// </summary>
/// <param name="data">Concrete Object of the AbstractType Specified.</param>
public AbstractXmlSerializer(AbstractType data)
{
_data = data;
}
#region IXmlSerializable Members
public System.Xml.Schema.XmlSchema GetSchema()
{
return null; // this is fine as schema is unknown.
}
public void ReadXml(System.Xml.XmlReader reader)
{
// Cast the Data back from the Abstract Type.
string typeAttrib = reader.GetAttribute("type");
// Ensure the Type was Specified
if (typeAttrib == null)
throw new ArgumentNullException("Unable to Read Xml Data for Abstract Type '" + typeof(AbstractType).Name +
"' because no 'type' attribute was specified in the XML.");
Type type = Type.GetType(typeAttrib);
// Check the Type is Found.
if (type == null)
throw new InvalidCastException("Unable to Read Xml Data for Abstract Type '" + typeof(AbstractType).Name +
"' because the type specified in the XML was not found.");
// Check the Type is a Subclass of the AbstractType.
if (!type.IsSubclassOf(typeof(AbstractType)))
throw new InvalidCastException("Unable to Read Xml Data for Abstract Type '" + typeof(AbstractType).Name +
"' because the Type specified in the XML differs ('" + type.Name + "').");
// Read the Data, Deserializing based on the (now known) concrete type.
reader.ReadStartElement();
this.Data = (AbstractType)new
XmlSerializer(type).Deserialize(reader);
reader.ReadEndElement();
}
public void WriteXml(System.Xml.XmlWriter writer)
{
// Write the Type Name to the XML Element as an Attrib and Serialize
Type type = _data.GetType();
// BugFix: Assembly must be FQN since Types can/are external to current.
writer.WriteAttributeString("type", type.AssemblyQualifiedName);
new XmlSerializer(type).Serialize(writer, _data);
}
#endregion
}
}
```
So, from there, how do we tell the XmlSerializer to work with our serializer rather than the default? We must pass our type within the Xml attributes type property, for example:
```
[XmlRoot("ClassWithAbstractCollection")]
public class ClassWithAbstractCollection
{
private List<AbstractType> _list;
[XmlArray("ListItems")]
[XmlArrayItem("ListItem", Type = typeof(AbstractXmlSerializer<AbstractType>))]
public List<AbstractType> List
{
get { return _list; }
set { _list = value; }
}
private AbstractType _prop;
[XmlElement("MyProperty", Type=typeof(AbstractXmlSerializer<AbstractType>))]
public AbstractType MyProperty
{
get { return _prop; }
set { _prop = value; }
}
public ClassWithAbstractCollection()
{
_list = new List<AbstractType>();
}
}
```
Here you can see, we have a collection and a single property being exposed, and all we need to do is add the *type* named parameter to the Xml declaration, easy! :D
**NOTE: If you use this code, I would really appreciate a shout-out. It will also help drive more people to the community :)**
Now, but unsure as to what to do with answers here since they all had their pro's and con's. I'll upmod those that I feel were useful (no offence to those that weren't) and close this off once I have the rep :)
Interesting problem and good fun to solve! :) |
20,107 | <p>This line in YUI's <a href="http://developer.yahoo.com/yui/reset/" rel="nofollow noreferrer">Reset CSS</a> is causing trouble for me:</p>
<pre class="lang-css prettyprint-override"><code>address,caption,cite,code,dfn,em,strong,th,var {
font-style: normal;
font-weight: normal;
}
</code></pre>
<p>It makes my <code>em</code> not italic and my <code>strong</code> not bold. Which is okay. I know how to override that in my own stylesheet.</p>
<pre class="lang-css prettyprint-override"><code>strong, b
{
font-weight: bold;
}
em, i
{
font-style: italic;
}
</code></pre>
<p>The problem comes in when I have text that's both <code>em</code> and <code>strong</code>. </p>
<pre><code><strong>This is bold, <em>and this is italic, but not bold</em></strong>
</code></pre>
<p>My rule for <code>strong</code> makes it bold, but YUI's rule for <code>em</code> makes it normal again. How do I fix that? </p>
| [
{
"answer_id": 20118,
"author": "palmsey",
"author_id": 521,
"author_profile": "https://Stackoverflow.com/users/521",
"pm_score": 5,
"selected": true,
"text": "<p>If your strong declaration comes after YUI's yours should override it. You can force it like this:</p>\n\n<pre><code>strong, b, strong *, b * { font-weight: bold; }\nem, i, em *, i * { font-style: italic; }\n</code></pre>\n\n<p>If you still support IE7 you'll need to add <code>!important</code>.</p>\n\n<pre><code>strong, b, strong *, b * { font-weight: bold !important; }\nem, i, em *, i * { font-style: italic !important; }\n</code></pre>\n\n<p>This works - see for yourself:</p>\n\n<p><div class=\"snippet\" data-lang=\"js\" data-hide=\"false\" data-console=\"false\" data-babel=\"false\">\r\n<div class=\"snippet-code\">\r\n<pre class=\"snippet-code-css lang-css prettyprint-override\"><code>/*YUI styles*/\r\naddress,caption,cite,code,dfn,em,strong,th,var {\r\n font-style: normal;\r\n font-weight: normal;\r\n}\r\n/*End YUI styles =*/\r\n\r\nstrong, b, strong *, b * {\r\n font-weight: bold;\r\n}\r\n\r\nem, i, em *, i * {\r\n font-style: italic;\r\n}</code></pre>\r\n<pre class=\"snippet-code-html lang-html prettyprint-override\"><code> <strong>Bold</strong> - <em>Italic</em> - <strong>Bold and <em>Italic</em></strong></code></pre>\r\n</div>\r\n</div>\r\n</p>\n"
},
{
"answer_id": 20120,
"author": "sparkes",
"author_id": 269,
"author_profile": "https://Stackoverflow.com/users/269",
"pm_score": 2,
"selected": false,
"text": "<p>As long as your styles are loaded after the reset ones they should work. What browser is this? because I work in a similar way myself and I've not hit this problem I wonder if it's something in my testing at fault.</p>\n"
},
{
"answer_id": 20138,
"author": "travis",
"author_id": 1414,
"author_profile": "https://Stackoverflow.com/users/1414",
"pm_score": 3,
"selected": false,
"text": "<p>I would use this rule to override the YUI reset:</p>\n\n<pre class=\"lang-css prettyprint-override\"><code>strong, b, strong *, b *\n{\n font-weight: bold;\n}\n\nem, i, em *, i *\n{\n font-style: italic;\n}\n</code></pre>\n"
},
{
"answer_id": 20145,
"author": "Ricky",
"author_id": 653,
"author_profile": "https://Stackoverflow.com/users/653",
"pm_score": 3,
"selected": false,
"text": "<p>If in addition to using YUI reset.css, you also use YUI base.css, then you will be all set with a standard set of cross browser base styles.</p>\n\n<p>LINK: <a href=\"http://developer.yahoo.com/yui/base/\" rel=\"nofollow noreferrer\">http://developer.yahoo.com/yui/base/</a></p>\n"
},
{
"answer_id": 20162,
"author": "alexp206",
"author_id": 666,
"author_profile": "https://Stackoverflow.com/users/666",
"pm_score": 2,
"selected": false,
"text": "<p>I had a similar problem when I added the YUI Reset to the top of my stock CSS file. I found that the best thing for me was to simply remove all of the</p>\n\n<pre><code>font-weight: normal;\n</code></pre>\n\n<p>declarations from the YUI Reset. I haven't noticed that this has affected anything \"cross-browser.\"</p>\n\n<p>All my declarations were after the YUI Reset so I'm not sure why they weren't taking affect.</p>\n"
},
{
"answer_id": 20186,
"author": "Chris Marasti-Georg",
"author_id": 96,
"author_profile": "https://Stackoverflow.com/users/96",
"pm_score": 2,
"selected": false,
"text": "<p>Reset stylesheets are best used as a base. If you don't want to reset em or strong, remove them from the stylesheet.</p>\n"
},
{
"answer_id": 20208,
"author": "Kevin",
"author_id": 40,
"author_profile": "https://Stackoverflow.com/users/40",
"pm_score": 2,
"selected": false,
"text": "<p>As Chris said, you don't have to use the exact CSS they provide religiously. I would just save a copy to your server, and edit to your needs. </p>\n"
},
{
"answer_id": 20265,
"author": "Patrick McElhaney",
"author_id": 437,
"author_profile": "https://Stackoverflow.com/users/437",
"pm_score": 0,
"selected": false,
"text": "<p>I thought I had an ideal solution:</p>\n\n<pre><code>strong, b \n{\n font-weight: bold;\n font-style: inherit;\n}\n\nem, i \n{\n font-style: italic;\n font-weight: inherit;\n}\n</code></pre>\n\n<p>Unfortunately, Internet Explorer doesn't support \"inherit.\" :-(</p>\n"
},
{
"answer_id": 20332,
"author": "Polsonby",
"author_id": 137,
"author_profile": "https://Stackoverflow.com/users/137",
"pm_score": 1,
"selected": false,
"text": "<p>I would suggest avoiding anything which involves hacking the YUI files. You need to be able to update external libraries in the future and if your site relies on edited versions there is a good chance it will get cocked up. I think this is general good practice for any 3rd party library you use.</p>\n\n<p>So I thought <a href=\"https://stackoverflow.com/questions/20107/yui-reset-css-makes-strong-and-em-not-work#20145\">this</a> answer was amongst the better ones</p>\n\n<blockquote>\n <blockquote>\n <p>If in addition to using YUI reset.css, you also use YUI base.css, then you will be all set with a standard set of cross browser base styles.</p>\n </blockquote>\n</blockquote>\n"
},
{
"answer_id": 20723,
"author": "Ricky",
"author_id": 653,
"author_profile": "https://Stackoverflow.com/users/653",
"pm_score": 0,
"selected": false,
"text": "<p>I see what you are saying. I guess you can add a CSS rule like this:</p>\n\n<pre><code>strong em { font-weight: bold; }\n</code></pre>\n\n<p>or:</p>\n\n<pre><code>strong * { font-weight: bold; }\n</code></pre>\n"
}
] | 2008/08/21 | [
"https://Stackoverflow.com/questions/20107",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/437/"
] | This line in YUI's [Reset CSS](http://developer.yahoo.com/yui/reset/) is causing trouble for me:
```css
address,caption,cite,code,dfn,em,strong,th,var {
font-style: normal;
font-weight: normal;
}
```
It makes my `em` not italic and my `strong` not bold. Which is okay. I know how to override that in my own stylesheet.
```css
strong, b
{
font-weight: bold;
}
em, i
{
font-style: italic;
}
```
The problem comes in when I have text that's both `em` and `strong`.
```
<strong>This is bold, <em>and this is italic, but not bold</em></strong>
```
My rule for `strong` makes it bold, but YUI's rule for `em` makes it normal again. How do I fix that? | If your strong declaration comes after YUI's yours should override it. You can force it like this:
```
strong, b, strong *, b * { font-weight: bold; }
em, i, em *, i * { font-style: italic; }
```
If you still support IE7 you'll need to add `!important`.
```
strong, b, strong *, b * { font-weight: bold !important; }
em, i, em *, i * { font-style: italic !important; }
```
This works - see for yourself:
```css
/*YUI styles*/
address,caption,cite,code,dfn,em,strong,th,var {
font-style: normal;
font-weight: normal;
}
/*End YUI styles =*/
strong, b, strong *, b * {
font-weight: bold;
}
em, i, em *, i * {
font-style: italic;
}
```
```html
<strong>Bold</strong> - <em>Italic</em> - <strong>Bold and <em>Italic</em></strong>
``` |
20,146 | <p>I'm looking for something like the <code>tempfile</code> module in Python: A (preferably) secure way to open a file for writing to. This should be easy to delete when I'm done too...</p>
<p>It seems, .NET does not have the "batteries included" features of the <code>tempfile</code> module, which not only creates the file, but returns the file descriptor (old school, I know...) to it along with the path. At the same time, it makes sure only the creating user can access the file and whatnot (<code>mkstemp()</code> I think): <a href="https://docs.python.org/library/tempfile.html" rel="nofollow noreferrer">https://docs.python.org/library/tempfile.html</a></p>
<hr />
<p>Ah, yes, I can see that. But GetTempFileName does have a drawback: There is a race condition between when the file was created (upon call to GetTempFileName a 0-Byte file gets created) and when I get to open it (after return of GetTempFileName). This might be a security issue, although not for my current application...</p>
| [
{
"answer_id": 20150,
"author": "Rob Cooper",
"author_id": 832,
"author_profile": "https://Stackoverflow.com/users/832",
"pm_score": 0,
"selected": false,
"text": "<p>I don't know of any built in (within the framework) classes to do this, but I imagine it wouldn't be too much of an issue to roll your own..</p>\n\n<p>Obviously it depends on the type of data you want to write to it, and the \"security\" required..</p>\n\n<p><a href=\"http://www.developerfusion.co.uk/show/3913/\" rel=\"nofollow noreferrer\">This article</a> on DevFusion may be a good place to start?</p>\n"
},
{
"answer_id": 20153,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 3,
"selected": false,
"text": "<p>Path.GetTempFileName and Path.GetTempPath. Then you can use <a href=\"https://web.archive.org/web/20091108030151/http://www.csharphelp.com/archives2/archive315.html\" rel=\"nofollow noreferrer\">this link</a> to read/write encrypted data to the file.</p>\n\n<p>Note, .NET isn't the best platform for critical security apps. You have to be well versed in how the CLR works in order to avoid some of the pitfalls that might expose your critical data to hackers.</p>\n\n<p>Edit: About the race condition... You could use GetTempPath, then create a temporary filename by using </p>\n\n<pre><code>Path.Combine(Path.GetTempPath(), Path.ChangeExtension(Guid.NewGuid().ToString(), \".TMP\"))\n</code></pre>\n"
},
{
"answer_id": 3378474,
"author": "Jordão",
"author_id": 31158,
"author_profile": "https://Stackoverflow.com/users/31158",
"pm_score": 5,
"selected": false,
"text": "<p>I've also had the same requirement before, and I've created a small class to solve it:</p>\n\n<pre><code>public sealed class TemporaryFile : IDisposable {\n public TemporaryFile() : \n this(Path.GetTempPath()) { }\n\n public TemporaryFile(string directory) {\n Create(Path.Combine(directory, Path.GetRandomFileName()));\n }\n\n ~TemporaryFile() {\n Delete();\n }\n\n public void Dispose() {\n Delete();\n GC.SuppressFinalize(this);\n }\n\n public string FilePath { get; private set; }\n\n private void Create(string path) {\n FilePath = path;\n using (File.Create(FilePath)) { };\n }\n\n private void Delete() {\n if (FilePath == null) return;\n File.Delete(FilePath);\n FilePath = null;\n }\n}\n</code></pre>\n\n<p>It creates a temporary file in a folder you specify or in the system temporary folder. It's a disposable class, so at the end of its life (either <code>Dispose</code> or the destructor), it deletes the file. You get the name of the file created (and path) through the <code>FilePath</code> property. You can certainly extend it to also open the file for writing and return its associated <code>FileStream</code>.</p>\n\n<p>An example usage:</p>\n\n<pre><code>using (var tempFile = new TemporaryFile()) {\n // use the file through tempFile.FilePath...\n}\n</code></pre>\n"
}
] | 2008/08/21 | [
"https://Stackoverflow.com/questions/20146",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2260/"
] | I'm looking for something like the `tempfile` module in Python: A (preferably) secure way to open a file for writing to. This should be easy to delete when I'm done too...
It seems, .NET does not have the "batteries included" features of the `tempfile` module, which not only creates the file, but returns the file descriptor (old school, I know...) to it along with the path. At the same time, it makes sure only the creating user can access the file and whatnot (`mkstemp()` I think): <https://docs.python.org/library/tempfile.html>
---
Ah, yes, I can see that. But GetTempFileName does have a drawback: There is a race condition between when the file was created (upon call to GetTempFileName a 0-Byte file gets created) and when I get to open it (after return of GetTempFileName). This might be a security issue, although not for my current application... | I've also had the same requirement before, and I've created a small class to solve it:
```
public sealed class TemporaryFile : IDisposable {
public TemporaryFile() :
this(Path.GetTempPath()) { }
public TemporaryFile(string directory) {
Create(Path.Combine(directory, Path.GetRandomFileName()));
}
~TemporaryFile() {
Delete();
}
public void Dispose() {
Delete();
GC.SuppressFinalize(this);
}
public string FilePath { get; private set; }
private void Create(string path) {
FilePath = path;
using (File.Create(FilePath)) { };
}
private void Delete() {
if (FilePath == null) return;
File.Delete(FilePath);
FilePath = null;
}
}
```
It creates a temporary file in a folder you specify or in the system temporary folder. It's a disposable class, so at the end of its life (either `Dispose` or the destructor), it deletes the file. You get the name of the file created (and path) through the `FilePath` property. You can certainly extend it to also open the file for writing and return its associated `FileStream`.
An example usage:
```
using (var tempFile = new TemporaryFile()) {
// use the file through tempFile.FilePath...
}
``` |
20,148 | <p>I'm working on a projects which involves a lot of database writes, I'd say (<em>70% inserts and 30% reads</em>). This ratio would also include updates which I consider to be one read and one write. The reads can be dirty (e.g. I don't need 100% accurate information at the time of read).<br>
The task in question will be doing over 1 million database transactions an hour. </p>
<p>I've read a bunch of stuff on the web about the differences between MyISAM and InnoDB, and MyISAM seems like the obvious choice to me for the particular database/tables that I'll be using for this task. From what I seem to be reading, InnoDB is good if transactions are needed since row level locking is supported.</p>
<p>Does anybody have any experience with this type of load (or higher)? Is MyISAM the way to go?</p>
| [
{
"answer_id": 22733,
"author": "rix0rrr",
"author_id": 2474,
"author_profile": "https://Stackoverflow.com/users/2474",
"pm_score": 8,
"selected": false,
"text": "<p>I'm not a database expert, and I do not speak from experience. However:</p>\n\n<p><a href=\"http://dev.mysql.com/doc/refman/5.1/en/internal-locking.html\" rel=\"noreferrer\">MyISAM tables use table-level locking</a>. Based on your traffic estimates, you have close to 200 writes per second. With MyISAM, <em>only one of these could be in progress at any time</em>. You have to make sure that your hardware can keep up with these transaction to avoid being overrun, i.e., a single query can take no more than 5ms.</p>\n\n<p>That suggests to me you would need a storage engine which supports row-level locking, i.e., InnoDB.</p>\n\n<p>On the other hand, it should be fairly trivial to write a few simple scripts to simulate the load with each storage engine, then compare the results.</p>\n"
},
{
"answer_id": 22892,
"author": "Gary Richardson",
"author_id": 2506,
"author_profile": "https://Stackoverflow.com/users/2506",
"pm_score": 2,
"selected": false,
"text": "<p>Every application has it's own performance profile for using a database, and chances are it will change over time.</p>\n\n<p>The best thing you can do is to test your options. Switching between MyISAM and InnoDB is trivial, so load some test data and fire jmeter against your site and see what happens.</p>\n"
},
{
"answer_id": 77374,
"author": "MarkR",
"author_id": 13724,
"author_profile": "https://Stackoverflow.com/users/13724",
"pm_score": 5,
"selected": false,
"text": "<p>If you use MyISAM, you won't be doing <strong>any</strong> transactions per hour, unless you consider each DML statement to be a transaction (which in any case, won't be durable or atomic in the event of a crash).</p>\n\n<p>Therefore I think you have to use InnoDB.</p>\n\n<p>300 transactions per second sounds like quite a lot. If you absolutely need these transactions to be durable across power failure make sure your I/O subsystem can handle this many writes per second easily. You will need at least a RAID controller with battery backed cache.</p>\n\n<p>If you can take a small durability hit, you could use InnoDB with innodb_flush_log_at_trx_commit set to 0 or 2 (see docs for details), you can improve performance.</p>\n\n<p>There are a number of patches which can increase concurrency from Google and others - these may be of interest if you still can't get enough performance without them.</p>\n"
},
{
"answer_id": 77625,
"author": "alanc10n",
"author_id": 14059,
"author_profile": "https://Stackoverflow.com/users/14059",
"pm_score": 7,
"selected": false,
"text": "<p>I've worked on a high-volume system using MySQL and I've tried both MyISAM and InnoDB.</p>\n\n<p>I found that the table-level locking in MyISAM caused serious performance problems for our workload which sounds similar to yours. Unfortunately I also found that performance under InnoDB was also worse than I'd hoped.</p>\n\n<p>In the end I resolved the contention issue by fragmenting the data such that inserts went into a \"hot\" table and selects never queried the hot table.</p>\n\n<p>This also allowed deletes (the data was time-sensitive and we only retained X days worth) to occur on \"stale\" tables that again weren't touched by select queries. InnoDB seems to have poor performance on bulk deletes so if you're planning on purging data you might want to structure it in such a way that the old data is in a stale table which can simply be dropped instead of running deletes on it.</p>\n\n<p>Of course I have no idea what your application is but hopefully this gives you some insight into some of the issues with MyISAM and InnoDB.</p>\n"
},
{
"answer_id": 414934,
"author": "staticsan",
"author_id": 28832,
"author_profile": "https://Stackoverflow.com/users/28832",
"pm_score": 6,
"selected": false,
"text": "<p>For a load with more writes and reads, you will benefit from InnoDB. Because InnoDB provides row-locking rather than table-locking, your <code>SELECT</code>s can be concurrent, not just with each other but also with many <code>INSERT</code>s. However, unless you are intending to use SQL transactions, set the InnoDB commit flush to 2 (<a href=\"http://dev.mysql.com/doc/refman/5.1/en/innodb-parameters.html#sysvar_innodb_flush_log_at_trx_commit\" rel=\"noreferrer\">innodb_flush_log_at_trx_commit</a>). This gives you back a lot of raw performance that you would otherwise lose when moving tables from MyISAM to InnoDB.</p>\n\n<p>Also, consider adding replication. This gives you some read scaling and since you stated your reads don't have to be up-to-date, you can let the replication fall behind a little. Just be sure that it can catch up under anything but the heaviest traffic or it will always be behind and will never catch up. If you go this way, however, I <em>strongly</em> recommend you isolate reading from the slaves and replication lag management to your database handler. It is so much simpler if the application code does not know about this.</p>\n\n<p>Finally, be aware of different table loads. You will not have the same read/write ratio on all tables. Some smaller tables with near 100% reads could afford to stay MyISAM. Likewise, if you have some tables that are near 100% write, you may benefit from <code>INSERT DELAYED</code>, but that is only supported in MyISAM (the <code>DELAYED</code> clause is ignored for an InnoDB table). </p>\n\n<p>But benchmark to be sure.</p>\n"
},
{
"answer_id": 415012,
"author": "yogman",
"author_id": 24349,
"author_profile": "https://Stackoverflow.com/users/24349",
"pm_score": 3,
"selected": false,
"text": "<p>In my experience, MyISAM was a better choice as long as you don't do DELETEs, UPDATEs, a whole lot of single INSERT, transactions, and full-text indexing. BTW, CHECK TABLE is horrible. As the table gets older in terms of the number of rows, you don't know when it will end.</p>\n"
},
{
"answer_id": 1653985,
"author": "pfote",
"author_id": 200096,
"author_profile": "https://Stackoverflow.com/users/200096",
"pm_score": 2,
"selected": false,
"text": "<p>myisam is a NOGO for that type of workload (high concurrency writes), i dont have that much experience with innodb (tested it 3 times and found in each case that the performance sucked, but it's been a while since the last test)\nif you're not forced to run mysql, consider giving postgres a try as it handles concurrent writes MUCH better</p>\n"
},
{
"answer_id": 3180781,
"author": "neal aise",
"author_id": 369798,
"author_profile": "https://Stackoverflow.com/users/369798",
"pm_score": 1,
"selected": false,
"text": "<p>For that ratio of read/writes I would guess InnoDB will perform better. \nSince you are fine with dirty reads, you might (if you afford) replicate to a slave and let all your reads go to the slave. Also, consider inserting in bulk, rather than one record at a time. </p>\n"
},
{
"answer_id": 3535256,
"author": "jsherk",
"author_id": 426804,
"author_profile": "https://Stackoverflow.com/users/426804",
"pm_score": 4,
"selected": false,
"text": "<p>I think this is an excellent article on explaining the differences and when you should use one over the other:\n<a href=\"http://tag1consulting.com/MySQL_Engines_MyISAM_vs_InnoDB\" rel=\"noreferrer\">http://tag1consulting.com/MySQL_Engines_MyISAM_vs_InnoDB</a></p>\n"
},
{
"answer_id": 3707592,
"author": "Ricardo",
"author_id": 288019,
"author_profile": "https://Stackoverflow.com/users/288019",
"pm_score": 3,
"selected": false,
"text": "<p>I've figure out that even though Myisam has locking contention, it's still faster than InnoDb in most scenarios because of the rapid lock acquisition scheme it uses. I've tried several times Innodb and always fall back to MyIsam for one reason or the other. Also InnoDB can be very CPU intensive in huge write loads.</p>\n"
},
{
"answer_id": 6796566,
"author": "developer99",
"author_id": 858727,
"author_profile": "https://Stackoverflow.com/users/858727",
"pm_score": 9,
"selected": false,
"text": "<p>I have briefly <a href=\"http://developer99.blogspot.com/2011/07/mysql-innodb-vs-myisam.html\" rel=\"noreferrer\">discussed</a> this question in a table so you can conclude whether to go with <strong>InnoDB</strong> or <strong>MyISAM</strong>.</p>\n\n<p>Here is a small overview of which db storage engine you should use in which situation:</p>\n\n<pre>\n MyISAM InnoDB\n----------------------------------------------------------------\nRequired full-text search Yes 5.6.4\n----------------------------------------------------------------\nRequire transactions Yes\n----------------------------------------------------------------\nFrequent select queries Yes \n----------------------------------------------------------------\nFrequent insert, update, delete Yes\n----------------------------------------------------------------\nRow locking (multi processing on single table) Yes\n----------------------------------------------------------------\nRelational base design Yes\n</pre>\n\n<p><strong>Summary</strong></p>\n\n<ul>\n<li>In almost all circumstances, <strong>InnoDB</strong> is the best way to go</li>\n<li>But, frequent reading, almost no writing, use <strong>MyISAM</strong></li>\n<li>Full-text search in MySQL <= 5.5, use <strong>MyISAM</strong></li>\n</ul>\n"
},
{
"answer_id": 8250970,
"author": "user965748",
"author_id": 965748,
"author_profile": "https://Stackoverflow.com/users/965748",
"pm_score": 2,
"selected": false,
"text": "<p>I tried to run insertion of random data into MyISAM and InnoDB tables. The result was quite shocking. MyISAM needed a few seconds less for inserting 1 million rows than InnoDB for just 10 thousand!</p>\n"
},
{
"answer_id": 9996879,
"author": "Refiner",
"author_id": 1192825,
"author_profile": "https://Stackoverflow.com/users/1192825",
"pm_score": 4,
"selected": false,
"text": "<p>Also check out some drop-in replacements for MySQL itself:</p>\n\n<p><strong>MariaDB</strong></p>\n\n<p><a href=\"http://mariadb.org/\" rel=\"noreferrer\">http://mariadb.org/</a></p>\n\n<p>MariaDB is a database server that offers drop-in replacement functionality for MySQL. MariaDB is built by some of the original authors of MySQL, with assistance from the broader community of Free and open source software developers. In addition to the core functionality of MySQL, MariaDB offers a rich set of feature enhancements including alternate storage engines, server optimizations, and patches.</p>\n\n<p><strong>Percona Server</strong></p>\n\n<p><a href=\"https://launchpad.net/percona-server\" rel=\"noreferrer\">https://launchpad.net/percona-server</a></p>\n\n<p>An enhanced drop-in replacement for MySQL, with better performance, improved diagnostics, and added features.</p>\n"
},
{
"answer_id": 12130057,
"author": "Patrick Savalle",
"author_id": 1199612,
"author_profile": "https://Stackoverflow.com/users/1199612",
"pm_score": 5,
"selected": false,
"text": "<p>Slightly off-topic, but for documentation purposes and completeness, I would like to add the following.</p>\n\n<p>In general using InnoDB will result in a much LESS complex application, probably also more bug-free. Because you can put all referential integrity (Foreign Key-constraints) into the datamodel, you don't need anywhere near as much application code as you will need with MyISAM.</p>\n\n<p>Every time you insert, delete or replace a record, you will HAVE to check and maintain the relationships. E.g. if you delete a parent, all children should be deleted too. For instance, even in a simple blogging system, if you delete a blogposting record, you will have to delete the comment records, the likes, etc. In InnoDB this is done automatically by the database engine (if you specified the contraints in the model) and requires no application code. In MyISAM this will have to be coded into the application, which is very difficult in web-servers. Web-servers are by nature very concurrent / parallel and because these actions should be atomical and MyISAM supports no real transactions, using MyISAM for web-servers is risky / error-prone.</p>\n\n<p>Also in most general cases, InnoDB will perform much better, for a multiple of reasons, one them being able to use record level locking as opposed to table-level locking. Not only in a situation where writes are more frequent than reads, also in situations with complex joins on large datasets. We noticed a 3 fold performance increase just by using InnoDB tables over MyISAM tables for very large joins (taking several minutes).</p>\n\n<p>I would say that in general InnoDB (using a 3NF datamodel complete with referential integrity) should be the default choice when using MySQL. MyISAM should only be used in very specific cases. It will most likely perform less, result in a bigger and more buggy application.</p>\n\n<p>Having said this. Datamodelling is an art seldom found among webdesigners / -programmers. No offence, but it does explain MyISAM being used so much.</p>\n"
},
{
"answer_id": 16127206,
"author": "Arembjorn",
"author_id": 622675,
"author_profile": "https://Stackoverflow.com/users/622675",
"pm_score": 4,
"selected": false,
"text": "<p><strong>Please note</strong> that my formal education and experience is with Oracle, while my work with MySQL has been entirely personal and on my own time, so if I say things that are true for Oracle but are not true for MySQL, I apologize. While the two systems share a lot, the relational theory/algebra is the same, and relational databases are still relational databases, there are still plenty of differences!!</p>\n\n<p>I particularly like (as well as row-level locking) that InnoDB is transaction-based, meaning that you may be updating/inserting/creating/altering/dropping/etc several times for one \"operation\" of your web application. The problem that arises is that if only <em>some</em> of those changes/operations end up being committed, but others do not, you will most times (depending on the specific design of the database) end up with a database with conflicting data/structure. </p>\n\n<p><strong>Note:</strong> With Oracle, create/alter/drop statements are called \"DDL\" (Data Definition) statements, and implicitly trigger a commit. Insert/update/delete statements, called \"DML\" (Data Manipulation), are <em>not</em> committed automatically, but only when a DDL, commit, or exit/quit is performed (or if you set your session to \"auto-commit\", or if your client auto-commits). It's imperative to be aware of that when working with Oracle, but I am not sure how MySQL handles the two types of statements. Because of this, I want to make it clear that I'm not sure of this when it comes to MySQL; only with Oracle. </p>\n\n<h2>An example of when transaction-based engines excel:</h2>\n\n<p>Let's say that I or you are on a web-page to sign up to attend a free event, and one of the main purposes of the system is to only allow up to 100 people to sign up, since that is the limit of the seating for the event. Once 100 sign-ups are reached, the system would disable further signups, at least until others cancel.</p>\n\n<p>In this case, there may be a table for guests (name, phone, email, etc.), and a second table which tracks the number of guests that have signed up. We thus have two operations for one \"transaction\". Now suppose that after the guest info is added to the GUESTS table, there is a connection loss, or an error with the same impact. The GUESTS table was updated (inserted into), but the connection was lost before the \"available seats\" could be updated.</p>\n\n<p>Now we have a guest added to the guest table, but the number of available seats is now incorrect (for example, value is 85 when it's actually 84).</p>\n\n<p><em>Of course</em> there are many ways to handle this, such as tracking available seats with \"100 minus number of rows in guests table,\" or some code that checks that the info is consistent, etc....\nBut with a transaction-based database engine such as InnoDB, either <em>ALL</em> of the operations are committed, or <em>NONE</em> of them are. This can be helpful in many cases, but like I said, it's not the ONLY way to be safe, no (a nice way, however, handled by the database, not the programmer/script-writer). </p>\n\n<p>That's all \"transaction-based\" essentially means in this context, unless I'm missing something -- that either the whole transaction succeeds as it should, or <em>nothing</em> is changed, since making only partial changes could make a minor to SEVERE mess of the database, perhaps even corrupting it...</p>\n\n<p>But I'll say it one more time, it's not the only way to avoid making a mess. But it is one of the methods that the engine itself handles, leaving you to code/script with only needing to worry about \"was the transaction successful or not, and what do I do if not (such as retry),\" instead of manually writing code to check it \"manually\" from outside of the database, and doing a lot more work for such events.</p>\n\n<h2>Lastly, a note about table-locking vs row-locking:</h2>\n\n<p><strong>DISCLAIMER:</strong> I may be wrong in all that follows in regard to MySQL, and the hypothetical/example situations are things to look into, but I may be wrong in what <em>exactly</em> is possible to cause corruption with MySQL. The examples are however very real in general programming, even if MySQL has more mechanisms to avoid such things...</p>\n\n<p>Anyway, I am fairly confident in agreeing with those who have argued that how many connections are allowed at a time <strong>does <em>not</em></strong> work around a locked table. In fact, multiple connections <strong>are the entire point of locking a table!!</strong> So that other processes/users/apps are not able to corrupt the database by making changes at the same time.</p>\n\n<p>How would two or more connections working on the same row make a REALLY BAD DAY for you??\nSuppose there are two processes both want/need to update the same value in the same row, let's say because the row is a record of a bus tour, and each of the two processes simultaneously want to update the \"riders\" or \"available_seats\" field as \"the current value plus 1.\"</p>\n\n<p>Let's do this hypothetically, step by step:</p>\n\n<ol>\n<li>Process one reads the current value, let's say it's empty, thus '0' so far. </li>\n<li>Process two reads the current value as well, which is still 0.</li>\n<li>Process one writes (current + 1) which is 1.</li>\n<li>Process two <em>should</em> be writing 2, but since it read the current value <em>before</em> process one write the new value, it too writes 1 to the table.</li>\n</ol>\n\n<p>I'm <em>not certain</em> that two connections could intermingle like that, both reading before the first one writes... But if not, then I would still see a problem with:</p>\n\n<ol>\n<li>Process one reads the current value, which is 0.</li>\n<li>Process one writes (current + 1), which is 1.</li>\n<li>Process two reads the current value now. But while process one DID write (update), it has not committed the data, thus only that same process can read the new value that it updated, while all others see the older value, until there is a commit.</li>\n</ol>\n\n<p>Also, at least with Oracle databases, there are isolation levels, which I will not waste our time trying to paraphrase. Here is a good article on that subject, and each isolation level having it's pros and cons, which would go along with how important transaction-based engines may be in a database...</p>\n\n<p>Lastly, there may likely be different safeguards in place within MyISAM, instead of foreign-keys and transaction-based interaction. Well, for one, there is the fact that an entire table is locked, which makes it less likely that transactions/FKs are <em>needed</em>. </p>\n\n<p>And alas, if you are aware of these concurrency issues, yes you can play it less safe and just write your applications, set up your systems so that such errors are not possible (your code is then responsible, rather than the database itself). However, in my opinion, I would say that it is always best to use as many safeguards as possible, programming defensively, and always being aware that human error is impossible to completely avoid. It happens to everyone, and anyone who says they are immune to it must be lying, or hasn't done more than write a \"Hello World\" application/script. ;-)</p>\n\n<p>I hope that SOME of that is helpful to some one, and even more-so, I hope that I have not just now been a culprit of assumptions and being a human in error!! My apologies if so, but the examples are good to think about, research the risk of, and so on, even if they are not potential in this specific context.</p>\n\n<p>Feel free to correct me, edit this \"answer,\" even vote it down. Just please try to improve, rather than correcting a bad assumption of mine with another. ;-)</p>\n\n<p>This is my first response, so please forgive the length due to all the disclaimers, etc... I just don't want to sound arrogant when I am not absolutely certain!</p>\n"
},
{
"answer_id": 16785740,
"author": "Pankaj Khurana",
"author_id": 2413197,
"author_profile": "https://Stackoverflow.com/users/2413197",
"pm_score": 5,
"selected": false,
"text": "<p>InnoDB offers:</p>\n\n<pre><code>ACID transactions\nrow-level locking\nforeign key constraints\nautomatic crash recovery\ntable compression (read/write)\nspatial data types (no spatial indexes)\n</code></pre>\n\n<p>In InnoDB all data in a row except for TEXT and BLOB can occupy 8,000 bytes at most. No full text indexing is available for InnoDB. In InnoDB the COUNT(*)s (when WHERE, GROUP BY, or JOIN is not used) execute slower than in MyISAM because the row count is not stored internally. InnoDB stores both data and indexes in one file. InnoDB uses a buffer pool to cache both data and indexes.</p>\n\n<p>MyISAM offers:</p>\n\n<pre><code>fast COUNT(*)s (when WHERE, GROUP BY, or JOIN is not used)\nfull text indexing\nsmaller disk footprint\nvery high table compression (read only)\nspatial data types and indexes (R-tree)\n</code></pre>\n\n<p>MyISAM has table-level locking, but no row-level locking. No transactions. No automatic crash recovery, but it does offer repair table functionality. No foreign key constraints. MyISAM tables are generally more compact in size on disk when compared to InnoDB tables. MyISAM tables could be further highly reduced in size by compressing with myisampack if needed, but become read-only. MyISAM stores indexes in one file and data in another. MyISAM uses key buffers for caching indexes and leaves the data caching management to the operating system.</p>\n\n<p>Overall I would recommend InnoDB for most purposes and MyISAM for specialized uses only. InnoDB is now the default engine in new MySQL versions.</p>\n"
},
{
"answer_id": 17706717,
"author": "Bill Karwin",
"author_id": 20860,
"author_profile": "https://Stackoverflow.com/users/20860",
"pm_score": 8,
"selected": false,
"text": "<p>People often talk about performance, reads vs. writes, foreign keys, etc. but there's one other must-have feature for a storage engine in my opinion: <strong>atomic updates.</strong></p>\n\n<p>Try this:</p>\n\n<ol>\n<li>Issue an UPDATE against your MyISAM table that takes 5 seconds.</li>\n<li>While the UPDATE is in progress, say 2.5 seconds in, hit Ctrl-C to interrupt it.</li>\n<li>Observe the effects on the table. How many rows were updated? How many were not updated? Is the table even readable, or was it corrupted when you hit Ctrl-C?</li>\n<li>Try the same experiment with UPDATE against an InnoDB table, interrupting the query in progress.</li>\n<li>Observe the InnoDB table. <em>Zero</em> rows were updated. InnoDB has assured you have atomic updates, and if the full update could not be committed, it rolls back the whole change. Also, the table is not corrupt. This works even if you use <code>killall -9 mysqld</code> to simulate a crash.</li>\n</ol>\n\n<p>Performance is desirable of course, but <em>not losing data</em> should trump that.</p>\n"
},
{
"answer_id": 18088402,
"author": "tony gil",
"author_id": 1166727,
"author_profile": "https://Stackoverflow.com/users/1166727",
"pm_score": 0,
"selected": false,
"text": "<p>bottomline: if you are working offline with selects on large chunks of data, MyISAM will probably give you better (much better) speeds.</p>\n\n<p>there are some situations when MyISAM is infinitely more efficient than InnoDB: when manipulating large data dumps offline (because of table lock). </p>\n\n<p>example: I was converting a csv file (15M records) from NOAA which uses VARCHAR fields as keys. InnoDB was taking forever, even with large chunks of memory available.</p>\n\n<p>this an example of the csv (first and third fields are keys).</p>\n\n<pre><code>USC00178998,20130101,TMAX,-22,,,7,0700\nUSC00178998,20130101,TMIN,-117,,,7,0700\nUSC00178998,20130101,TOBS,-28,,,7,0700\nUSC00178998,20130101,PRCP,0,T,,7,0700\nUSC00178998,20130101,SNOW,0,T,,7,\n</code></pre>\n\n<p>since what i need to do is run a batch offline update of observed weather phenomena, i use MyISAM table for receiving data and run JOINS on the keys so that i can clean the incoming file and replace VARCHAR fields with INT keys (which are related to external tables where the original VARCHAR values are stored).</p>\n"
},
{
"answer_id": 18329730,
"author": "Cyberwip",
"author_id": 2671238,
"author_profile": "https://Stackoverflow.com/users/2671238",
"pm_score": 1,
"selected": false,
"text": "<p>Almost every time I start a new project I Google this same question to see if I come up with any new answers.</p>\n\n<p>It eventually boils down to - I take the latest version of MySQL and run tests.</p>\n\n<p>I have tables where I want to do key/value lookups... and that's all. I need to get the value (0-512 bytes) for a hash key. There is not a lot of transactions on this DB. The table gets updates occasionally (in it's entirety), but 0 transactions.</p>\n\n<p>So we're not talking about a complex system here, we are talking about a simple lookup,.. and how (other than making the table RAM resident) we can optimize performance.</p>\n\n<p>I also do tests on other databases (ie NoSQL) to see if there is anywhere I can get an advantage. The biggest advantage I have found is in key mapping but as far as the lookup goes, MyISAM is currently topping them all.</p>\n\n<p>Albeit, I wouldn't perform financial transactions with MyISAM tables but for simple lookups, you should test it out.. typically 2x to 5x the queries/sec.</p>\n\n<p>Test it, I welcome debate.</p>\n"
},
{
"answer_id": 20579257,
"author": "kta",
"author_id": 539023,
"author_profile": "https://Stackoverflow.com/users/539023",
"pm_score": 1,
"selected": false,
"text": "<p>If it is 70% inserts and 30% reads then it is more like on the InnoDB side.</p>\n"
},
{
"answer_id": 28070969,
"author": "d4nyll",
"author_id": 3966682,
"author_profile": "https://Stackoverflow.com/users/3966682",
"pm_score": 6,
"selected": false,
"text": "<p>A bit late to the game...but here's a quite comprehensive <a href=\"http://blog.danyll.com/myisam-vs-innodb/\" rel=\"noreferrer\">post I wrote a few months back</a>, detailing the major differences between MYISAM and InnoDB. Grab a cuppa (and maybe a biscuit), and enjoy.</p>\n\n<hr>\n\n<p>The major difference between MyISAM and InnoDB is in referential integrity and transactions. There are also other difference such as locking, rollbacks, and full-text searches.</p>\n\n<h2>Referential Integrity</h2>\n\n<p>Referential integrity ensures that relationships between tables remains consistent. More specifically, this means when a table (e.g. Listings) has a foreign key (e.g. Product ID) pointing to a different table (e.g. Products), when updates or deletes occur to the pointed-to table, these changes are cascaded to the linking table. In our example, if a product is renamed, the linking table’s foreign keys will also update; if a product is deleted from the ‘Products’ table, any listings which point to the deleted entry will also be deleted. Furthermore, any new listing must have that foreign key pointing to a valid, existing entry.</p>\n\n<p>InnoDB is a relational DBMS (RDBMS) and thus has referential integrity, while MyISAM does not.</p>\n\n<h2>Transactions & Atomicity</h2>\n\n<p>Data in a table is managed using Data Manipulation Language (DML) statements, such as SELECT, INSERT, UPDATE and DELETE. A transaction group two or more DML statements together into a single unit of work, so either the entire unit is applied, or none of it is.</p>\n\n<p>MyISAM do not support transactions whereas InnoDB does.</p>\n\n<p>If an operation is interrupted while using a MyISAM table, the operation is aborted immediately, and the rows (or even data within each row) that are affected remains affected, even if the operation did not go to completion.</p>\n\n<p>If an operation is interrupted while using an InnoDB table, because it using transactions, which has atomicity, any transaction which did not go to completion will not take effect, since no commit is made.</p>\n\n<h2>Table-locking vs Row-locking</h2>\n\n<p>When a query runs against a MyISAM table, the entire table in which it is querying will be locked. This means subsequent queries will only be executed after the current one is finished. If you are reading a large table, and/or there are frequent read and write operations, this can mean a huge backlog of queries.</p>\n\n<p>When a query runs against an InnoDB table, only the row(s) which are involved are locked, the rest of the table remains available for CRUD operations. This means queries can run simultaneously on the same table, provided they do not use the same row.</p>\n\n<p>This feature in InnoDB is known as concurrency. As great as concurrency is, there is a major drawback that applies to a select range of tables, in that there is an overhead in switching between kernel threads, and you should set a limit on the kernel threads to prevent the server coming to a halt.</p>\n\n<h2>Transactions & Rollbacks</h2>\n\n<p>When you run an operation in MyISAM, the changes are set; in InnoDB, those changes can be rolled back. The most common commands used to control transactions are COMMIT, ROLLBACK and SAVEPOINT. 1. COMMIT - you can write multiple DML operations, but the changes will only be saved when a COMMIT is made 2. ROLLBACK - you can discard any operations that have not yet been committed yet 3. SAVEPOINT - sets a point in the list of operations to which a ROLLBACK operation can rollback to</p>\n\n<h2>Reliability</h2>\n\n<p>MyISAM offers no data integrity - Hardware failures, unclean shutdowns and canceled operations can cause the data to become corrupt. This would require full repair or rebuilds of the indexes and tables.</p>\n\n<p>InnoDB, on the other hand, uses a transactional log, a double-write buffer and automatic checksumming and validation to prevent corruption. Before InnoDB makes any changes, it records the data before the transactions into a system tablespace file called ibdata1. If there is a crash, InnoDB would autorecover through the replay of those logs.</p>\n\n<h2>FULLTEXT Indexing</h2>\n\n<p>InnoDB does not support FULLTEXT indexing until MySQL version 5.6.4. As of the writing of this post, many shared hosting providers’ MySQL version is still below 5.6.4, which means FULLTEXT indexing is not supported for InnoDB tables.</p>\n\n<p>However, this is not a valid reason to use MyISAM. It’s best to change to a hosting provider that supports up-to-date versions of MySQL. Not that a MyISAM table that uses FULLTEXT indexing cannot be converted to an InnoDB table.</p>\n\n<h2>Conclusion</h2>\n\n<p>In conclusion, InnoDB should be your default storage engine of choice. Choose MyISAM or other data types when they serve a specific need.</p>\n"
},
{
"answer_id": 28396656,
"author": "Light93",
"author_id": 2049786,
"author_profile": "https://Stackoverflow.com/users/2049786",
"pm_score": 2,
"selected": false,
"text": "<p>In short, InnoDB is good if you are working on something that needs a reliable database that can handles a lot of INSERT and UPDATE instructions.</p>\n\n<p>and, MyISAM is good if you needs a database that will mostly be taking a lot of read (SELECT) instructions rather than write (INSERT and UPDATES), considering its drawback on the table-lock thing.</p>\n\n<p>you may want to check out;<br />\n<a href=\"https://www.sitepoint.com/mysql-innodb-table-pros-cons/\" rel=\"nofollow noreferrer\">Pros and Cons of InnoDB</a><br />\n<a href=\"https://www.sitepoint.com/mysql-myisam-table-pros-con/\" rel=\"nofollow noreferrer\">Pros and Cons of MyISAM</a></p>\n"
},
{
"answer_id": 30776508,
"author": "StackG",
"author_id": 3403718,
"author_profile": "https://Stackoverflow.com/users/3403718",
"pm_score": 6,
"selected": false,
"text": "<p>To add to the wide selection of responses here covering the mechanical differences between the two engines, I present an empirical speed comparison study.</p>\n<p>In terms of pure speed, it is not always the case that MyISAM is faster than InnoDB but in my experience it tends to be faster for PURE READ working environments by a factor of about 2.0-2.5 times. Clearly this isn't appropriate for all environments - as others have written, MyISAM lacks such things as transactions and foreign keys.</p>\n<p>I've done a bit of benchmarking below - I've used python for looping and the timeit library for timing comparisons. For interest I've also included the memory engine, this gives the best performance across the board although it is only suitable for smaller tables (you continually encounter <code>The table 'tbl' is full</code> when you exceed the MySQL memory limit). The four types of select I look at are:</p>\n<ol>\n<li>vanilla SELECTs</li>\n<li>counts</li>\n<li>conditional SELECTs</li>\n<li>indexed and non-indexed sub-selects</li>\n</ol>\n<p>Firstly, I created three tables using the following SQL</p>\n<pre><code>CREATE TABLE\n data_interrogation.test_table_myisam\n (\n index_col BIGINT NOT NULL AUTO_INCREMENT,\n value1 DOUBLE,\n value2 DOUBLE,\n value3 DOUBLE,\n value4 DOUBLE,\n PRIMARY KEY (index_col)\n )\n ENGINE=MyISAM DEFAULT CHARSET=utf8\n</code></pre>\n<p>with 'MyISAM' substituted for 'InnoDB' and 'memory' in the second and third tables.</p>\n<p> </p>\n<h1>1) Vanilla selects</h1>\n<p>Query: <code>SELECT * FROM tbl WHERE index_col = xx</code></p>\n<p>Result: <strong>draw</strong></p>\n<p><img src=\"https://i.stack.imgur.com/zVt8y.png\" alt=\"Comparison of vanilla selects by different database engines\" /></p>\n<p>The speed of these is all broadly the same, and as expected is linear in the number of columns to be selected. InnoDB seems <em>slightly</em> faster than MyISAM but this is really marginal.</p>\n<p>Code:</p>\n<pre><code>import timeit\nimport MySQLdb\nimport MySQLdb.cursors\nimport random\nfrom random import randint\n\ndb = MySQLdb.connect(host="...", user="...", passwd="...", db="...", cursorclass=MySQLdb.cursors.DictCursor)\ncur = db.cursor()\n\nlengthOfTable = 100000\n\n# Fill up the tables with random data\nfor x in xrange(lengthOfTable):\n rand1 = random.random()\n rand2 = random.random()\n rand3 = random.random()\n rand4 = random.random()\n\n insertString = "INSERT INTO test_table_innodb (value1,value2,value3,value4) VALUES (" + str(rand1) + "," + str(rand2) + "," + str(rand3) + "," + str(rand4) + ")"\n insertString2 = "INSERT INTO test_table_myisam (value1,value2,value3,value4) VALUES (" + str(rand1) + "," + str(rand2) + "," + str(rand3) + "," + str(rand4) + ")"\n insertString3 = "INSERT INTO test_table_memory (value1,value2,value3,value4) VALUES (" + str(rand1) + "," + str(rand2) + "," + str(rand3) + "," + str(rand4) + ")"\n\n cur.execute(insertString)\n cur.execute(insertString2)\n cur.execute(insertString3)\n\ndb.commit()\n\n# Define a function to pull a certain number of records from these tables\ndef selectRandomRecords(testTable,numberOfRecords):\n\n for x in xrange(numberOfRecords):\n rand1 = randint(0,lengthOfTable)\n\n selectString = "SELECT * FROM " + testTable + " WHERE index_col = " + str(rand1)\n cur.execute(selectString)\n\nsetupString = "from __main__ import selectRandomRecords"\n\n# Test time taken using timeit\nmyisam_times = []\ninnodb_times = []\nmemory_times = []\n\nfor theLength in [3,10,30,100,300,1000,3000,10000]:\n\n innodb_times.append( timeit.timeit('selectRandomRecords("test_table_innodb",' + str(theLength) + ')', number=100, setup=setupString) )\n myisam_times.append( timeit.timeit('selectRandomRecords("test_table_myisam",' + str(theLength) + ')', number=100, setup=setupString) )\n memory_times.append( timeit.timeit('selectRandomRecords("test_table_memory",' + str(theLength) + ')', number=100, setup=setupString) )\n</code></pre>\n<p> </p>\n<h1>2) Counts</h1>\n<p>Query: <code>SELECT count(*) FROM tbl</code></p>\n<p>Result: <strong>MyISAM wins</strong></p>\n<p><img src=\"https://i.stack.imgur.com/F2sYk.png\" alt=\"Comparison of counts by different database engines\" /></p>\n<p>This one demonstrates a big difference between MyISAM and InnoDB - MyISAM (and memory) keeps track of the number of records in the table, so this transaction is fast and O(1). The amount of time required for InnoDB to count increases super-linearly with table size in the range I investigated. I suspect many of the speed-ups from MyISAM queries that are observed in practice are due to similar effects.</p>\n<p>Code:</p>\n<pre><code>myisam_times = []\ninnodb_times = []\nmemory_times = []\n\n# Define a function to count the records\ndef countRecords(testTable):\n\n selectString = "SELECT count(*) FROM " + testTable\n cur.execute(selectString)\n\nsetupString = "from __main__ import countRecords"\n\n# Truncate the tables and re-fill with a set amount of data\nfor theLength in [3,10,30,100,300,1000,3000,10000,30000,100000]:\n\n truncateString = "TRUNCATE test_table_innodb"\n truncateString2 = "TRUNCATE test_table_myisam"\n truncateString3 = "TRUNCATE test_table_memory"\n\n cur.execute(truncateString)\n cur.execute(truncateString2)\n cur.execute(truncateString3)\n\n for x in xrange(theLength):\n rand1 = random.random()\n rand2 = random.random()\n rand3 = random.random()\n rand4 = random.random()\n\n insertString = "INSERT INTO test_table_innodb (value1,value2,value3,value4) VALUES (" + str(rand1) + "," + str(rand2) + "," + str(rand3) + "," + str(rand4) + ")"\n insertString2 = "INSERT INTO test_table_myisam (value1,value2,value3,value4) VALUES (" + str(rand1) + "," + str(rand2) + "," + str(rand3) + "," + str(rand4) + ")"\n insertString3 = "INSERT INTO test_table_memory (value1,value2,value3,value4) VALUES (" + str(rand1) + "," + str(rand2) + "," + str(rand3) + "," + str(rand4) + ")"\n\n cur.execute(insertString)\n cur.execute(insertString2)\n cur.execute(insertString3)\n\n db.commit()\n\n # Count and time the query\n innodb_times.append( timeit.timeit('countRecords("test_table_innodb")', number=100, setup=setupString) )\n myisam_times.append( timeit.timeit('countRecords("test_table_myisam")', number=100, setup=setupString) )\n memory_times.append( timeit.timeit('countRecords("test_table_memory")', number=100, setup=setupString) )\n</code></pre>\n<p> </p>\n<h1>3) Conditional selects</h1>\n<p>Query: <code>SELECT * FROM tbl WHERE value1<0.5 AND value2<0.5 AND value3<0.5 AND value4<0.5</code></p>\n<p>Result: <strong>MyISAM wins</strong></p>\n<p><img src=\"https://i.stack.imgur.com/2MwCZ.png\" alt=\"Comparison of conditional selects by different database engines\" /></p>\n<p>Here, MyISAM and memory perform approximately the same, and beat InnoDB by about 50% for larger tables. This is the sort of query for which the benefits of MyISAM seem to be maximised.</p>\n<p>Code:</p>\n<pre><code>myisam_times = []\ninnodb_times = []\nmemory_times = []\n\n# Define a function to perform conditional selects\ndef conditionalSelect(testTable):\n selectString = "SELECT * FROM " + testTable + " WHERE value1 < 0.5 AND value2 < 0.5 AND value3 < 0.5 AND value4 < 0.5"\n cur.execute(selectString)\n\nsetupString = "from __main__ import conditionalSelect"\n\n# Truncate the tables and re-fill with a set amount of data\nfor theLength in [3,10,30,100,300,1000,3000,10000,30000,100000]:\n\n truncateString = "TRUNCATE test_table_innodb"\n truncateString2 = "TRUNCATE test_table_myisam"\n truncateString3 = "TRUNCATE test_table_memory"\n\n cur.execute(truncateString)\n cur.execute(truncateString2)\n cur.execute(truncateString3)\n\n for x in xrange(theLength):\n rand1 = random.random()\n rand2 = random.random()\n rand3 = random.random()\n rand4 = random.random()\n\n insertString = "INSERT INTO test_table_innodb (value1,value2,value3,value4) VALUES (" + str(rand1) + "," + str(rand2) + "," + str(rand3) + "," + str(rand4) + ")"\n insertString2 = "INSERT INTO test_table_myisam (value1,value2,value3,value4) VALUES (" + str(rand1) + "," + str(rand2) + "," + str(rand3) + "," + str(rand4) + ")"\n insertString3 = "INSERT INTO test_table_memory (value1,value2,value3,value4) VALUES (" + str(rand1) + "," + str(rand2) + "," + str(rand3) + "," + str(rand4) + ")"\n\n cur.execute(insertString)\n cur.execute(insertString2)\n cur.execute(insertString3)\n\n db.commit()\n\n # Count and time the query\n innodb_times.append( timeit.timeit('conditionalSelect("test_table_innodb")', number=100, setup=setupString) )\n myisam_times.append( timeit.timeit('conditionalSelect("test_table_myisam")', number=100, setup=setupString) )\n memory_times.append( timeit.timeit('conditionalSelect("test_table_memory")', number=100, setup=setupString) )\n</code></pre>\n<p> </p>\n<h1>4) Sub-selects</h1>\n<p>Result: <strong>InnoDB wins</strong></p>\n<p>For this query, I created an additional set of tables for the sub-select. Each is simply two columns of BIGINTs, one with a primary key index and one without any index. Due to the large table size, I didn't test the memory engine. The SQL table creation command was</p>\n<pre><code>CREATE TABLE\n subselect_myisam\n (\n index_col bigint NOT NULL,\n non_index_col bigint,\n PRIMARY KEY (index_col)\n )\n ENGINE=MyISAM DEFAULT CHARSET=utf8;\n</code></pre>\n<p>where once again, 'MyISAM' is substituted for 'InnoDB' in the second table.</p>\n<p>In this query, I leave the size of the selection table at 1000000 and instead vary the size of the sub-selected columns.</p>\n<p><img src=\"https://i.stack.imgur.com/mrhOp.png\" alt=\"Comparison of sub-selects by different database engines\" /></p>\n<p>Here the InnoDB wins easily. After we get to a reasonable size table both engines scale linearly with the size of the sub-select. The index speeds up the MyISAM command but interestingly has little effect on the InnoDB speed.\nsubSelect.png</p>\n<p>Code:</p>\n<pre><code>myisam_times = []\ninnodb_times = []\nmyisam_times_2 = []\ninnodb_times_2 = []\n\ndef subSelectRecordsIndexed(testTable,testSubSelect):\n selectString = "SELECT * FROM " + testTable + " WHERE index_col in ( SELECT index_col FROM " + testSubSelect + " )"\n cur.execute(selectString)\n\nsetupString = "from __main__ import subSelectRecordsIndexed"\n\ndef subSelectRecordsNotIndexed(testTable,testSubSelect):\n selectString = "SELECT * FROM " + testTable + " WHERE index_col in ( SELECT non_index_col FROM " + testSubSelect + " )"\n cur.execute(selectString)\n\nsetupString2 = "from __main__ import subSelectRecordsNotIndexed"\n\n# Truncate the old tables, and re-fill with 1000000 records\ntruncateString = "TRUNCATE test_table_innodb"\ntruncateString2 = "TRUNCATE test_table_myisam"\n\ncur.execute(truncateString)\ncur.execute(truncateString2)\n\nlengthOfTable = 1000000\n\n# Fill up the tables with random data\nfor x in xrange(lengthOfTable):\n rand1 = random.random()\n rand2 = random.random()\n rand3 = random.random()\n rand4 = random.random()\n\n insertString = "INSERT INTO test_table_innodb (value1,value2,value3,value4) VALUES (" + str(rand1) + "," + str(rand2) + "," + str(rand3) + "," + str(rand4) + ")"\n insertString2 = "INSERT INTO test_table_myisam (value1,value2,value3,value4) VALUES (" + str(rand1) + "," + str(rand2) + "," + str(rand3) + "," + str(rand4) + ")"\n\n cur.execute(insertString)\n cur.execute(insertString2)\n\nfor theLength in [3,10,30,100,300,1000,3000,10000,30000,100000]:\n\n truncateString = "TRUNCATE subselect_innodb"\n truncateString2 = "TRUNCATE subselect_myisam"\n\n cur.execute(truncateString)\n cur.execute(truncateString2)\n\n # For each length, empty the table and re-fill it with random data\n rand_sample = sorted(random.sample(xrange(lengthOfTable), theLength))\n rand_sample_2 = random.sample(xrange(lengthOfTable), theLength)\n\n for (the_value_1,the_value_2) in zip(rand_sample,rand_sample_2):\n insertString = "INSERT INTO subselect_innodb (index_col,non_index_col) VALUES (" + str(the_value_1) + "," + str(the_value_2) + ")"\n insertString2 = "INSERT INTO subselect_myisam (index_col,non_index_col) VALUES (" + str(the_value_1) + "," + str(the_value_2) + ")"\n\n cur.execute(insertString)\n cur.execute(insertString2)\n\n db.commit()\n\n # Finally, time the queries\n innodb_times.append( timeit.timeit('subSelectRecordsIndexed("test_table_innodb","subselect_innodb")', number=100, setup=setupString) )\n myisam_times.append( timeit.timeit('subSelectRecordsIndexed("test_table_myisam","subselect_myisam")', number=100, setup=setupString) )\n \n innodb_times_2.append( timeit.timeit('subSelectRecordsNotIndexed("test_table_innodb","subselect_innodb")', number=100, setup=setupString2) )\n myisam_times_2.append( timeit.timeit('subSelectRecordsNotIndexed("test_table_myisam","subselect_myisam")', number=100, setup=setupString2) )\n</code></pre>\n<p>I think the take-home message of all of this is that if you are <em>really</em> concerned about speed, you need to benchmark the queries that you're doing rather than make any assumptions about which engine will be more suitable.</p>\n"
},
{
"answer_id": 36991969,
"author": "pilavdzice",
"author_id": 397048,
"author_profile": "https://Stackoverflow.com/users/397048",
"pm_score": 2,
"selected": false,
"text": "<p>I know this won't be popular but here goes:</p>\n\n<p>myISAM lacks support for database essentials like transactions and referential integrity which often results in glitchy / buggy applications. You cannot not learn proper database design fundamentals if they are not even supported by your db engine. </p>\n\n<p>Not using referential integrity or transactions in the database world is like not using object oriented programming in the software world. </p>\n\n<p>InnoDB exists now, use that instead! Even MySQL developers have finally conceded to change this to the default engine in newer versions, despite myISAM being the original engine that was the default in all legacy systems. </p>\n\n<p>No it does not matter if you are reading or writing or what performance considerations you have, using myISAM can result in a variety of problems, such as this one I just ran into: I was performing a database sync and at the same time someone else accessed an application that accessed a table set to myISAM. Due to the lack of transaction support and the generally poor reliability of this engine, this crashed the entire database and I had to manually restart mysql!</p>\n\n<p>Over the past 15 years of development I have used many databases and engines. myISAM crashed on me about a dozen times during this period, other databases, only once! And that was a microsoft SQL database where some developer wrote faulty CLR code (common language runtime - basically C# code that executes inside the database) by the way, it was not the database engine's fault exactly.</p>\n\n<p>I agree with the other answers here that say that <strong>quality high-availability, high-performance applications should not use myISAM as it will not work, it is not robust or stable enough to result in a frustration-free experience.</strong> See Bill Karwin's answer for more details.</p>\n\n<p>P.S. Gotta love it when myISAM fanboys downvote but can't tell you which part of this answer is incorrect.</p>\n"
},
{
"answer_id": 43767498,
"author": "Rick James",
"author_id": 1766831,
"author_profile": "https://Stackoverflow.com/users/1766831",
"pm_score": 5,
"selected": false,
"text": "<p><em><strong>The Question and most of the Answers are out of date</strong></em>.</p>\n\n<p>Yes, it is an old wives' tale that MyISAM is faster than InnoDB. notice the Question's date: 2008; it is now almost a decade later. InnoDB has made significant performance strides since then.</p>\n\n<p>The dramatic graph was for the one case where MyISAM wins: <code>COUNT(*)</code> <em>without</em> a <code>WHERE</code> clause. But is that really what you spend your time doing?</p>\n\n<p>If you run <em>concurrency</em> test, InnoDB is very likely to win, <em>even against <code>MEMORY</code></em>.</p>\n\n<p>If you do any writes while benchmarking <code>SELECTs</code>, MyISAM and <code>MEMORY</code> are likely to lose because of table-level locking.</p>\n\n<p>In fact, Oracle is so sure that InnoDB is better that they have all but removed MyISAM from 8.0.</p>\n\n<p>The <em>Question</em> was written early in the days of 5.1. Since then, these major versions were marked \"General Availability\":</p>\n\n<ul>\n<li>2010: 5.5 (.8 in Dec.)</li>\n<li>2013: 5.6 (.10 in Feb.)</li>\n<li>2015: 5.7 (.9 in Oct.)</li>\n<li>2018: 8.0 (.11 in Apr.)</li>\n</ul>\n\n<p><em><strong>Bottom line: Don't use MyISAM</strong></em></p>\n"
}
] | 2008/08/21 | [
"https://Stackoverflow.com/questions/20148",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2013/"
] | I'm working on a projects which involves a lot of database writes, I'd say (*70% inserts and 30% reads*). This ratio would also include updates which I consider to be one read and one write. The reads can be dirty (e.g. I don't need 100% accurate information at the time of read).
The task in question will be doing over 1 million database transactions an hour.
I've read a bunch of stuff on the web about the differences between MyISAM and InnoDB, and MyISAM seems like the obvious choice to me for the particular database/tables that I'll be using for this task. From what I seem to be reading, InnoDB is good if transactions are needed since row level locking is supported.
Does anybody have any experience with this type of load (or higher)? Is MyISAM the way to go? | I have briefly [discussed](http://developer99.blogspot.com/2011/07/mysql-innodb-vs-myisam.html) this question in a table so you can conclude whether to go with **InnoDB** or **MyISAM**.
Here is a small overview of which db storage engine you should use in which situation:
```
MyISAM InnoDB
----------------------------------------------------------------
Required full-text search Yes 5.6.4
----------------------------------------------------------------
Require transactions Yes
----------------------------------------------------------------
Frequent select queries Yes
----------------------------------------------------------------
Frequent insert, update, delete Yes
----------------------------------------------------------------
Row locking (multi processing on single table) Yes
----------------------------------------------------------------
Relational base design Yes
```
**Summary**
* In almost all circumstances, **InnoDB** is the best way to go
* But, frequent reading, almost no writing, use **MyISAM**
* Full-text search in MySQL <= 5.5, use **MyISAM** |
20,156 | <p>Is there an easy way in C# to create <a href="http://en.wikipedia.org/wiki/Ordinal_numbers_%28linguistics%29" rel="noreferrer">Ordinals</a> for a number? For example:</p>
<ul>
<li>1 returns 1st</li>
<li>2 returns 2nd</li>
<li>3 returns 3rd</li>
<li>...etc</li>
</ul>
<p>Can this be done through <code>String.Format()</code> or are there any functions available to do this?</p>
| [
{
"answer_id": 20166,
"author": "Stu",
"author_id": 414,
"author_profile": "https://Stackoverflow.com/users/414",
"pm_score": 4,
"selected": false,
"text": "<p>You'll have to roll your own. From the top of my head:</p>\n\n<pre><code>public static string Ordinal(this int number)\n{\n var work = number.ToString();\n if ((number % 100) == 11 || (number % 100) == 12 || (number % 100) == 13)\n return work + \"th\";\n switch (number % 10)\n {\n case 1: work += \"st\"; break;\n case 2: work += \"nd\"; break;\n case 3: work += \"rd\"; break;\n default: work += \"th\"; break;\n }\n return work;\n}\n</code></pre>\n\n<p>You can then do </p>\n\n<pre><code>Console.WriteLine(432.Ordinal());\n</code></pre>\n\n<p>Edited for 11/12/13 exceptions. I DID say from the top of my head :-)</p>\n\n<p>Edited for 1011 -- others have fixed this already, just want to make sure others don't grab this incorrect version.</p>\n"
},
{
"answer_id": 20175,
"author": "samjudson",
"author_id": 1908,
"author_profile": "https://Stackoverflow.com/users/1908",
"pm_score": 9,
"selected": true,
"text": "<p>This page gives you a complete listing of all custom numerical formatting rules:</p>\n<p><a href=\"https://learn.microsoft.com/en-us/dotnet/standard/base-types/custom-numeric-format-strings\" rel=\"noreferrer\">Custom numeric format strings</a></p>\n<p>As you can see, there is nothing in there about ordinals, so it can't be done using <code>String.Format</code>. However its not really that hard to write a function to do it.</p>\n<pre><code>public static string AddOrdinal(int num)\n{\n if( num <= 0 ) return num.ToString();\n\n switch(num % 100)\n {\n case 11:\n case 12:\n case 13:\n return num + "th";\n }\n \n switch(num % 10)\n {\n case 1:\n return num + "st";\n case 2:\n return num + "nd";\n case 3:\n return num + "rd";\n default:\n return num + "th";\n }\n}\n</code></pre>\n<p>Update: Technically Ordinals don't exist for <= 0, so I've updated the code above. Also removed the redundant <code>ToString()</code> methods.</p>\n<p>Also note, this is not internationalized. I've no idea what ordinals look like in other languages.</p>\n"
},
{
"answer_id": 31066,
"author": "Jesse C. Slicer",
"author_id": 3312,
"author_profile": "https://Stackoverflow.com/users/3312",
"pm_score": 4,
"selected": false,
"text": "<p>I rather liked elements from both <a href=\"https://stackoverflow.com/a/20166/3312\">Stu</a>'s and <a href=\"https://stackoverflow.com/a/20175/3312\">samjudson</a>'s solutions and worked them together into what I think is a usable combo:</p>\n<pre><code>public static string Ordinal(this int number)\n{\n const string TH = "th";\n var s = number.ToString();\n \n number %= 100;\n \n if ((number >= 11) && (number <= 13))\n {\n return s + TH;\n }\n \n switch (number % 10)\n {\n case 1:\n return s + "st";\n case 2:\n return s + "nd";\n case 3:\n return s + "rd";\n default:\n return s + TH;\n }\n}\n</code></pre>\n"
},
{
"answer_id": 111542,
"author": "Ryan McGeary",
"author_id": 8985,
"author_profile": "https://Stackoverflow.com/users/8985",
"pm_score": 3,
"selected": false,
"text": "<p>While I haven't benchmarked this yet, you should be able to get better performance by avoiding all the conditional case statements.</p>\n\n<p>This is java, but a port to C# is trivial:</p>\n\n<pre><code>public class NumberUtil {\n final static String[] ORDINAL_SUFFIXES = {\n \"th\", \"st\", \"nd\", \"rd\", \"th\", \"th\", \"th\", \"th\", \"th\", \"th\"\n };\n\n public static String ordinalSuffix(int value) {\n int n = Math.abs(value);\n int lastTwoDigits = n % 100;\n int lastDigit = n % 10;\n int index = (lastTwoDigits >= 11 && lastTwoDigits <= 13) ? 0 : lastDigit;\n return ORDINAL_SUFFIXES[index];\n }\n\n public static String toOrdinal(int n) {\n return new StringBuffer().append(n).append(ordinalSuffix(n)).toString();\n }\n}\n</code></pre>\n\n<p>Note, the reduction of conditionals and the use of the array lookup should speed up performance if generating a lot of ordinals in a tight loop. However, I also concede that this isn't as readable as the case statement solution.</p>\n"
},
{
"answer_id": 115438,
"author": "roomaroo",
"author_id": 3464,
"author_profile": "https://Stackoverflow.com/users/3464",
"pm_score": 6,
"selected": false,
"text": "<p>Remember internationalisation!</p>\n\n<p>The solutions here only work for English. Things get a lot more complex if you need to support other languages. </p>\n\n<p>For example, in Spanish \"1st\" would be written as \"1.o\", \"1.a\", \"1.os\" or \"1.as\" depending on whether the thing you're counting is masculine, feminine or plural!</p>\n\n<p>So if your software needs to support different languages, try to avoid ordinals.</p>\n"
},
{
"answer_id": 620504,
"author": "si618",
"author_id": 44540,
"author_profile": "https://Stackoverflow.com/users/44540",
"pm_score": 5,
"selected": false,
"text": "<p>My version of Jesse's version of Stu's and samjudson's versions :)</p>\n<p>Included unit test to show that the accepted answer is incorrect when number < 1</p>\n<pre><code>/// <summary>\n/// Get the ordinal value of positive integers.\n/// </summary>\n/// <remarks>\n/// Only works for english-based cultures.\n/// Code from: http://stackoverflow.com/questions/20156/is-there-a-quick-way-to-create-ordinals-in-c/31066#31066\n/// With help: http://www.wisegeek.com/what-is-an-ordinal-number.htm\n/// </remarks>\n/// <param name="number">The number.</param>\n/// <returns>Ordinal value of positive integers, or <see cref="int.ToString"/> if less than 1.</returns>\npublic static string Ordinal(this int number)\n{\n const string TH = "th";\n string s = number.ToString();\n\n // Negative and zero have no ordinal representation\n if (number < 1)\n {\n return s;\n }\n\n number %= 100;\n if ((number >= 11) && (number <= 13))\n {\n return s + TH;\n }\n\n switch (number % 10)\n {\n case 1: return s + "st";\n case 2: return s + "nd";\n case 3: return s + "rd";\n default: return s + TH;\n }\n}\n\n[Test]\npublic void Ordinal_ReturnsExpectedResults()\n{\n Assert.AreEqual("-1", (1-2).Ordinal());\n Assert.AreEqual("0", 0.Ordinal());\n Assert.AreEqual("1st", 1.Ordinal());\n Assert.AreEqual("2nd", 2.Ordinal());\n Assert.AreEqual("3rd", 3.Ordinal());\n Assert.AreEqual("4th", 4.Ordinal());\n Assert.AreEqual("5th", 5.Ordinal());\n Assert.AreEqual("6th", 6.Ordinal());\n Assert.AreEqual("7th", 7.Ordinal());\n Assert.AreEqual("8th", 8.Ordinal());\n Assert.AreEqual("9th", 9.Ordinal());\n Assert.AreEqual("10th", 10.Ordinal());\n Assert.AreEqual("11th", 11.Ordinal());\n Assert.AreEqual("12th", 12.Ordinal());\n Assert.AreEqual("13th", 13.Ordinal());\n Assert.AreEqual("14th", 14.Ordinal());\n Assert.AreEqual("20th", 20.Ordinal());\n Assert.AreEqual("21st", 21.Ordinal());\n Assert.AreEqual("22nd", 22.Ordinal());\n Assert.AreEqual("23rd", 23.Ordinal());\n Assert.AreEqual("24th", 24.Ordinal());\n Assert.AreEqual("100th", 100.Ordinal());\n Assert.AreEqual("101st", 101.Ordinal());\n Assert.AreEqual("102nd", 102.Ordinal());\n Assert.AreEqual("103rd", 103.Ordinal());\n Assert.AreEqual("104th", 104.Ordinal());\n Assert.AreEqual("110th", 110.Ordinal());\n Assert.AreEqual("111th", 111.Ordinal());\n Assert.AreEqual("112th", 112.Ordinal());\n Assert.AreEqual("113th", 113.Ordinal());\n Assert.AreEqual("114th", 114.Ordinal());\n Assert.AreEqual("120th", 120.Ordinal());\n Assert.AreEqual("121st", 121.Ordinal());\n Assert.AreEqual("122nd", 122.Ordinal());\n Assert.AreEqual("123rd", 123.Ordinal());\n Assert.AreEqual("124th", 124.Ordinal());\n}\n</code></pre>\n"
},
{
"answer_id": 16339730,
"author": "shawad",
"author_id": 1765067,
"author_profile": "https://Stackoverflow.com/users/1765067",
"pm_score": 2,
"selected": false,
"text": "<p>Similar to Ryan's solution, but even more basic, I just use a plain array and use the day to look up the correct ordinal:</p>\n\n<pre><code>private string[] ordinals = new string[] {\"\",\"st\",\"nd\",\"rd\",\"th\",\"th\",\"th\",\"th\",\"th\",\"th\",\"th\",\"th\",\"th\",\"th\",\"th\",\"th\",\"th\",\"th\",\"th\",\"th\",\"th\",\"st\",\"nd\",\"rd\",\"th\",\"th\",\"th\",\"th\",\"th\",\"th\",\"th\",\"st\" };\nDateTime D = DateTime.Now;\nString date = \"Today's day is: \"+ D.Day.ToString() + ordinals[D.Day];\n</code></pre>\n\n<p>I have not had the need, but I would assume you could use a multidimensional array if you wanted to have multiple language support.</p>\n\n<p>From what I can remember from my Uni days, this method requires minimal effort from the server.</p>\n"
},
{
"answer_id": 20610493,
"author": "Faust",
"author_id": 613004,
"author_profile": "https://Stackoverflow.com/users/613004",
"pm_score": 1,
"selected": false,
"text": "<pre><code>public static string OrdinalSuffix(int ordinal)\n{\n //Because negatives won't work with modular division as expected:\n var abs = Math.Abs(ordinal); \n\n var lastdigit = abs % 10; \n\n return \n //Catch 60% of cases (to infinity) in the first conditional:\n lastdigit > 3 || lastdigit == 0 || (abs % 100) - lastdigit == 10 ? \"th\" \n : lastdigit == 1 ? \"st\" \n : lastdigit == 2 ? \"nd\" \n : \"rd\";\n}\n</code></pre>\n"
},
{
"answer_id": 21968095,
"author": "Rupert",
"author_id": 1904153,
"author_profile": "https://Stackoverflow.com/users/1904153",
"pm_score": -1,
"selected": false,
"text": "<p>Another alternative that I used based on all the other suggestions, but requires no special casing:</p>\n<pre><code>public static string DateSuffix(int day)\n{\n if (day == 11 | day == 12 | day == 13) return "th";\n Math.DivRem(day, 10, out day);\n switch (day)\n {\n case 1:\n return "st";\n case 2:\n return "nd";\n case 3:\n return "rd";\n default:\n return "th";\n }\n}\n</code></pre>\n"
},
{
"answer_id": 25935496,
"author": "AjV Jsy",
"author_id": 2078245,
"author_profile": "https://Stackoverflow.com/users/2078245",
"pm_score": 0,
"selected": false,
"text": "<p>FWIW, for MS-SQL, this expression will do the job. Keep the first WHEN (<code>WHEN num % 100 IN (11, 12, 13) THEN 'th'</code>) as the first one in the list, as this relies upon being tried before the others.</p>\n\n<pre><code>CASE\n WHEN num % 100 IN (11, 12, 13) THEN 'th' -- must be tried first\n WHEN num % 10 = 1 THEN 'st'\n WHEN num % 10 = 2 THEN 'nd'\n WHEN num % 10 = 3 THEN 'rd'\n ELSE 'th'\nEND AS Ordinal\n</code></pre>\n\n<p>For Excel :</p>\n\n<pre><code>=MID(\"thstndrdth\",MIN(9,2*RIGHT(A1)*(MOD(A1-11,100)>2)+1),2)\n</code></pre>\n\n<p>The expression <code>(MOD(A1-11,100)>2)</code> is TRUE (1) for all numbers except any ending in <code>11,12,13</code> (FALSE = 0). So <code>2 * RIGHT(A1) * (MOD(A1-11,100)>2) +1)</code> ends up as 1 for 11/12/13, otherwise :<br>\n1 evaluates to 3<br>\n2 to 5,<br>\n3 to 7<br>\nothers : 9<br>\n - and the required 2 characters are selected from <code>\"thstndrdth\"</code> starting from that position.</p>\n\n<p>If you really want to convert that fairly directly to SQL, this worked for me for a handful of test values :</p>\n\n<pre><code>DECLARE @n as int\nSET @n=13\nSELECT SubString( 'thstndrdth'\n , (SELECT MIN(value) FROM\n (SELECT 9 as value UNION\n SELECT 1+ (2* (ABS(@n) % 10) * CASE WHEN ((ABS(@n)+89) % 100)>2 THEN 1 ELSE 0 END)\n ) AS Mins\n )\n , 2\n )\n</code></pre>\n"
},
{
"answer_id": 26282053,
"author": "Maulik Patel",
"author_id": 4125994,
"author_profile": "https://Stackoverflow.com/users/4125994",
"pm_score": -1,
"selected": false,
"text": "<p>Here is the DateTime Extension class. Copy, Paste & Enjoy</p>\n<pre><code>public static class DateTimeExtensions\n{\n public static string ToStringWithOrdinal(this DateTime d)\n {\n var result = "";\n bool bReturn = false; \n \n switch (d.Day % 100)\n {\n case 11:\n case 12:\n case 13:\n result = d.ToString("dd'th' MMMM yyyy");\n bReturn = true;\n break;\n }\n\n if (!bReturn)\n {\n switch (d.Day % 10)\n {\n case 1:\n result = d.ToString("dd'st' MMMM yyyy");\n break;\n case 2:\n result = d.ToString("dd'nd' MMMM yyyy");\n break;\n case 3:\n result = d.ToString("dd'rd' MMMM yyyy");\n break;\n default:\n result = d.ToString("dd'th' MMMM yyyy");\n break;\n }\n\n }\n\n if (result.StartsWith("0")) result = result.Substring(1);\n return result;\n }\n}\n</code></pre>\n<p>Result :</p>\n<p>9th October 2014</p>\n"
},
{
"answer_id": 26433514,
"author": "Shahzad Qureshi",
"author_id": 2719563,
"author_profile": "https://Stackoverflow.com/users/2719563",
"pm_score": 5,
"selected": false,
"text": "<p>Simple, clean, quick</p>\n<pre><code>private static string GetOrdinalSuffix(int num)\n{\n string number = num.ToString();\n if (number.EndsWith("11")) return "th";\n if (number.EndsWith("12")) return "th";\n if (number.EndsWith("13")) return "th";\n if (number.EndsWith("1")) return "st";\n if (number.EndsWith("2")) return "nd";\n if (number.EndsWith("3")) return "rd";\n return "th";\n}\n</code></pre>\n<p>Or better yet, as an extension method</p>\n<pre><code>public static class IntegerExtensions\n{\n public static string DisplayWithSuffix(this int num)\n {\n string number = num.ToString();\n if (number.EndsWith("11")) return number + "th";\n if (number.EndsWith("12")) return number + "th";\n if (number.EndsWith("13")) return number + "th";\n if (number.EndsWith("1")) return number + "st";\n if (number.EndsWith("2")) return number + "nd";\n if (number.EndsWith("3")) return number + "rd";\n return number + "th";\n }\n}\n</code></pre>\n<p>Now you can just call</p>\n<pre><code>int a = 1;\na.DisplayWithSuffix(); \n</code></pre>\n<p>or even as direct as</p>\n<pre><code>1.DisplayWithSuffix();\n</code></pre>\n"
},
{
"answer_id": 27509908,
"author": "Whelkaholism",
"author_id": 318411,
"author_profile": "https://Stackoverflow.com/users/318411",
"pm_score": 1,
"selected": false,
"text": "<p><strong>EDIT</strong>: As YM_Industries points out in the comment, <a href=\"https://stackoverflow.com/questions/20156/is-there-an-easy-way-to-create-ordinals-in-c/20175#20175\" title=\"accepted answer\">samjudson's answer</a> DOES work for numbers over 1000, nickf's comment seems to have gone, and I can't remember what the problem I saw was. Left this answer here for the comparison timings.</p>\n\n<p>An awful lot of these don't work for numbers > 999, as <a href=\"https://stackoverflow.com/users/9021/nickf\" title=\"nickf\">nickf</a> pointed out in a comment (EDIT: now missing).</p>\n\n<p>Here is a version based off a modified version of <a href=\"https://stackoverflow.com/users/1908/samjudson\" title=\"samjudson\">samjudson</a>'s <a href=\"https://stackoverflow.com/questions/20156/is-there-an-easy-way-to-create-ordinals-in-c/20175#20175\" title=\"accepted answer\">accepted answer</a> that does.</p>\n\n<pre><code>public static String GetOrdinal(int i)\n{\n String res = \"\";\n\n if (i > 0)\n {\n int j = (i - ((i / 100) * 100));\n\n if ((j == 11) || (j == 12) || (j == 13))\n res = \"th\";\n else\n {\n int k = i % 10;\n\n if (k == 1)\n res = \"st\";\n else if (k == 2)\n res = \"nd\";\n else if (k == 3)\n res = \"rd\";\n else\n res = \"th\";\n }\n }\n\n return i.ToString() + res;\n}\n</code></pre>\n\n<p>Also <a href=\"https://stackoverflow.com/users/2719563/shahzad-qureshi\" title=\"Shahzad Qureshi\">Shahzad Qureshi</a>'s <a href=\"https://stackoverflow.com/questions/69262/is-there-an-easy-way-in-net-to-get-st-nd-rd-and-th-endings-for-number/19553611#19553611\">answer</a> using string manipulation works fine, however it does have a performance penalty. For generating a lot of these, a LINQPad example program makes the string version 6-7 times slower than this integer one (although you'd have to be generating a lot to notice).</p>\n\n<p>LINQPad example: </p>\n\n<pre><code>void Main()\n{\n \"Examples:\".Dump();\n\n foreach(int i in new int[] {1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 22, 113, 122, 201, 202, 211, 212, 2013, 1000003, 10000013 })\n Stuff.GetOrdinal(i).Dump();\n\n String s;\n\n System.Diagnostics.Stopwatch sw = System.Diagnostics.Stopwatch.StartNew();\n\n for(int iter = 0; iter < 100000; iter++)\n foreach(int i in new int[] {1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 22, 113, 122, 201, 202, 211, 212, 2013, 1000003, 1000013 })\n s = Stuff.GetOrdinal(i);\n\n \"Integer manipulation\".Dump();\n sw.Elapsed.Dump();\n\n sw.Restart();\n\n for(int iter = 0; iter < 100000; iter++)\n foreach(int i in new int[] {1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 22, 113, 122, 201, 202, 211, 212, 2013, 1000003, 1000013 })\n s = (i.ToString() + Stuff.GetOrdinalSuffix(i));\n\n \"String manipulation\".Dump();\n sw.Elapsed.Dump();\n}\n\npublic class Stuff\n{\n // Use integer manipulation\n public static String GetOrdinal(int i)\n {\n String res = \"\";\n\n if (i > 0)\n {\n int j = (i - ((i / 100) * 100));\n\n if ((j == 11) || (j == 12) || (j == 13))\n res = \"th\";\n else\n {\n int k = i % 10;\n\n if (k == 1)\n res = \"st\";\n else if (k == 2)\n res = \"nd\";\n else if (k == 3)\n res = \"rd\";\n else\n res = \"th\";\n }\n }\n\n return i.ToString() + res;\n }\n\n // Use string manipulation\n public static string GetOrdinalSuffix(int num)\n {\n if (num.ToString().EndsWith(\"11\")) return \"th\";\n if (num.ToString().EndsWith(\"12\")) return \"th\";\n if (num.ToString().EndsWith(\"13\")) return \"th\";\n if (num.ToString().EndsWith(\"1\")) return \"st\";\n if (num.ToString().EndsWith(\"2\")) return \"nd\";\n if (num.ToString().EndsWith(\"3\")) return \"rd\";\n return \"th\";\n }\n}\n</code></pre>\n"
},
{
"answer_id": 36878179,
"author": "Ali Humayun",
"author_id": 1845464,
"author_profile": "https://Stackoverflow.com/users/1845464",
"pm_score": 2,
"selected": false,
"text": "<pre><code>private static string GetOrd(int num) => $"{num}{(!(Range(11, 3).Any(n => n == num % 100) ^ Range(1, 3).All(n => n != num % 10)) ? new[] { "ˢᵗ", "ⁿᵈ", "ʳᵈ" }[num % 10 - 1] : "ᵗʰ")}";\n</code></pre>\n<p>If anyone is looking for one-liner.</p>\n"
},
{
"answer_id": 39665303,
"author": "Perry Tribolet",
"author_id": 5668,
"author_profile": "https://Stackoverflow.com/users/5668",
"pm_score": 2,
"selected": false,
"text": "<p>I use this extension class:</p>\n\n<pre><code>public static class Int32Extensions\n{\n public static string ToOrdinal(this int i)\n {\n return (i + \"th\")\n .Replace(\"1th\", \"1st\")\n .Replace(\"2th\", \"2nd\")\n .Replace(\"3th\", \"3rd\");\n }\n}\n</code></pre>\n"
},
{
"answer_id": 43260913,
"author": "Ian Warburton",
"author_id": 221683,
"author_profile": "https://Stackoverflow.com/users/221683",
"pm_score": 2,
"selected": false,
"text": "<p>Requested \"less redundancy\" version of samjudson's answer...</p>\n\n<pre><code>public static string AddOrdinal(int number)\n{\n if (number <= 0) return number.ToString();\n\n string GetIndicator(int num)\n {\n switch (num % 100)\n {\n case 11:\n case 12:\n case 13:\n return \"th\";\n }\n\n switch (num % 10)\n {\n case 1:\n return \"st\";\n case 2:\n return \"nd\";\n case 3:\n return \"rd\";\n default:\n return \"th\";\n }\n }\n\n return number + GetIndicator(number);\n}\n</code></pre>\n"
},
{
"answer_id": 44010138,
"author": "Dave Sumter",
"author_id": 706866,
"author_profile": "https://Stackoverflow.com/users/706866",
"pm_score": 1,
"selected": false,
"text": "<p>Based off the other answers:</p>\n\n<pre><code>public static string Ordinal(int n)\n{ \n int r = n % 100, m = n % 10;\n\n return (r<4 || r>20) && (m>0 && m<4) ? n+\" stndrd\".Substring(m*2,2) : n+\"th\"; \n}\n</code></pre>\n"
},
{
"answer_id": 56439487,
"author": "Phani Rithvij",
"author_id": 8608146,
"author_profile": "https://Stackoverflow.com/users/8608146",
"pm_score": 0,
"selected": false,
"text": "<p>This is the implementation in <code>dart</code> and can be modified according to the language.</p>\n\n<pre class=\"lang-dart prettyprint-override\"><code>String getOrdinalSuffix(int num){\n if (num.toString().endsWith(\"11\")) return \"th\";\n if (num.toString().endsWith(\"12\")) return \"th\";\n if (num.toString().endsWith(\"13\")) return \"th\";\n if (num.toString().endsWith(\"1\")) return \"st\";\n if (num.toString().endsWith(\"2\")) return \"nd\";\n if (num.toString().endsWith(\"3\")) return \"rd\";\n return \"th\";\n}\n</code></pre>\n"
},
{
"answer_id": 58378465,
"author": "Dan Dohotaru",
"author_id": 2583579,
"author_profile": "https://Stackoverflow.com/users/2583579",
"pm_score": 1,
"selected": false,
"text": "<p>While there are plenty of good answers in here, I guess there is room for another one, this time based on pattern matching, if not for anything else, then at least for debatable readability</p>\n<pre><code>public static string Ordinals1(this int number)\n{\n switch (number)\n {\n case int p when p % 100 == 11:\n case int q when q % 100 == 12:\n case int r when r % 100 == 13:\n return $"{number}th";\n case int p when p % 10 == 1:\n return $"{number}st";\n case int p when p % 10 == 2:\n return $"{number}nd";\n case int p when p % 10 == 3:\n return $"{number}rd";\n default:\n return $"{number}th";\n }\n}\n</code></pre>\n<p>and what makes this solution special? nothing but the fact that I'm adding some performance considerations for various other solutions</p>\n<p>frankly I doubt performance really matters for this particular scenario (who really needs the ordinals of millions of numbers) but at least it surfaces some comparisons to be taken into account...</p>\n<blockquote>\n<p>1 million items for reference (your millage may vary based on machine specs of course)</p>\n<p>with pattern matching and divisions (this answer)</p>\n<p>~622 ms</p>\n<p>with pattern matching and strings (this answer)</p>\n<p>~1967 ms</p>\n<p>with two switches and divisions (accepted answer)</p>\n<p>~637 ms</p>\n<p>with one switch and divisions (another answer)</p>\n<p>~725 ms</p>\n</blockquote>\n<pre><code>void Main()\n{\n var timer = new Stopwatch();\n var numbers = Enumerable.Range(1, 1000000).ToList();\n\n // 1\n timer.Reset();\n timer.Start();\n var results1 = numbers.Select(p => p.Ordinals1()).ToList();\n timer.Stop();\n timer.Elapsed.TotalMilliseconds.Dump("with pattern matching and divisions");\n\n // 2\n timer.Reset();\n timer.Start();\n var results2 = numbers.Select(p => p.Ordinals2()).ToList();\n timer.Stop();\n timer.Elapsed.TotalMilliseconds.Dump("with pattern matching and strings");\n\n // 3\n timer.Reset();\n timer.Start();\n var results3 = numbers.Select(p => p.Ordinals3()).ToList();\n timer.Stop();\n timer.Elapsed.TotalMilliseconds.Dump("with two switches and divisons");\n \n // 4\n timer.Reset();\n timer.Start();\n var results4 = numbers.Select(p => p.Ordinals4()).ToList();\n timer.Stop();\n timer.Elapsed.TotalMilliseconds.Dump("with one switche and divisons");\n}\n\npublic static class Extensions\n{\n public static string Ordinals1(this int number)\n {\n switch (number)\n {\n case int p when p % 100 == 11:\n case int q when q % 100 == 12:\n case int r when r % 100 == 13:\n return $"{number}th";\n case int p when p % 10 == 1:\n return $"{number}st";\n case int p when p % 10 == 2:\n return $"{number}nd";\n case int p when p % 10 == 3:\n return $"{number}rd";\n default:\n return $"{number}th";\n }\n }\n\n public static string Ordinals2(this int number)\n {\n var text = number.ToString();\n switch (text)\n {\n case string p when p.EndsWith("11"):\n return $"{number}th";\n case string p when p.EndsWith("12"):\n return $"{number}th";\n case string p when p.EndsWith("13"):\n return $"{number}th";\n case string p when p.EndsWith("1"):\n return $"{number}st";\n case string p when p.EndsWith("2"):\n return $"{number}nd";\n case string p when p.EndsWith("3"):\n return $"{number}rd";\n default:\n return $"{number}th";\n }\n }\n\n public static string Ordinals3(this int number)\n {\n switch (number % 100)\n {\n case 11:\n case 12:\n case 13:\n return $"{number}th";\n }\n\n switch (number % 10)\n {\n case 1:\n return $"{number}st";\n case 2:\n return $"{number}nd";\n case 3:\n return $"{number}rd";\n default:\n return $"{number}th";\n }\n }\n\n public static string Ordinals4(this int number)\n {\n var ones = number % 10;\n var tens = Math.Floor(number / 10f) % 10;\n if (tens == 1)\n {\n return $"{number}th";\n }\n\n switch (ones)\n {\n case 1:\n return $"{number}th";\n case 2:\n return $"{number}nd";\n case 3:\n return $"{number}rd";\n default:\n return $"{number}th";\n }\n }\n}\n\n</code></pre>\n"
},
{
"answer_id": 58632762,
"author": "Pluto",
"author_id": 1507941,
"author_profile": "https://Stackoverflow.com/users/1507941",
"pm_score": 0,
"selected": false,
"text": "<p>Another one-liner, but without comparisons by only indexing the regex result into an array.</p>\n\n<pre><code>public static string GetOrdinalSuffix(int input)\n{\n return new []{\"th\", \"st\", \"nd\", \"rd\"}[Convert.ToInt32(\"0\" + Regex.Match(input.ToString(), \"(?<!1)[1-3]$\").Value)];\n}\n</code></pre>\n\n<p>The PowerShell version can be shortened further:</p>\n\n<pre><code>function ord($num) { return ('th','st','nd','rd')[[int]($num -match '(?<!1)[1-3]$') * $matches[0]] }\n</code></pre>\n"
},
{
"answer_id": 61644903,
"author": "Echostorm",
"author_id": 12862,
"author_profile": "https://Stackoverflow.com/users/12862",
"pm_score": 0,
"selected": false,
"text": "<p>Another 1 liner.</p>\n\n<pre><code>public static string Ordinal(this int n)\n{ \n return n + (new [] {\"st\",\"nd\",\"rd\" }.ElementAtOrDefault((((n + 90) % 100 - 10) % 10 - 1)) ?? \"th\");\n}\n</code></pre>\n"
},
{
"answer_id": 72025082,
"author": "aloisdg",
"author_id": 1248177,
"author_profile": "https://Stackoverflow.com/users/1248177",
"pm_score": 1,
"selected": false,
"text": "<p>The <a href=\"https://github.com/Humanizr/Humanizer\" rel=\"nofollow noreferrer\">Humanizer</a> nuget package will provide helper methods for you. Disclaimer, I am a contributor to this project.</p>\n<p><code>Ordinalize</code> turns a number into an ordinal string used to denote the position in an ordered sequence such as 1st, 2nd, 3rd, 4th:</p>\n<pre class=\"lang-cs prettyprint-override\"><code>1.Ordinalize() => "1st"\n5.Ordinalize() => "5th"\n</code></pre>\n<p>You can also call <code>Ordinalize</code> on a numeric string and achieve the same result: <code>"21".Ordinalize()</code> => <code>"21st"</code></p>\n<p><code>Ordinalize</code> also supports grammatical gender for both forms.\nYou can pass an argument to <code>Ordinalize</code> to specify which gender the number should be outputted in.\nThe possible values are <code>GrammaticalGender.Masculine</code>, <code>GrammaticalGender.Feminine</code> and <code>GrammaticalGender.Neuter</code>:</p>\n<pre class=\"lang-cs prettyprint-override\"><code>// for Brazilian Portuguese locale\n1.Ordinalize(GrammaticalGender.Masculine) => "1º"\n1.Ordinalize(GrammaticalGender.Feminine) => "1ª"\n1.Ordinalize(GrammaticalGender.Neuter) => "1º"\n"2".Ordinalize(GrammaticalGender.Masculine) => "2º"\n"2".Ordinalize(GrammaticalGender.Feminine) => "2ª"\n"2".Ordinalize(GrammaticalGender.Neuter) => "2º"\n</code></pre>\n<p>Obviously this only applies to some cultures. For others passing gender in or not passing at all doesn't make any difference in the result.</p>\n<p>In addition, <code>Ordinalize</code> supports variations some cultures apply depending on the position of the ordinalized number in a sentence.\nUse the argument <code>wordForm</code> to get one result or another. Possible values are <code>WordForm.Abbreviation</code> and <code>WordForm.Normal</code>.\nYou can combine <code>wordForm</code> argument with gender but passing this argument in when it is not applicable will not make any difference in the result.</p>\n<pre class=\"lang-cs prettyprint-override\"><code>// Spanish locale\n1.Ordinalize(WordForm.Abbreviation) => "1.er" // As in "Vivo en el 1.er piso"\n1.Ordinalize(WordForm.Normal) => "1.º" // As in "He llegado el 1º"\n"3".Ordinalize(GrammaticalGender.Feminine, WordForm.Abbreviation) => "3.ª"\n"3".Ordinalize(GrammaticalGender.Feminine, WordForm.Normal) => "3.ª"\n"3".Ordinalize(GrammaticalGender.Masculine, WordForm.Abbreviation) => "3.er"\n"3".Ordinalize(GrammaticalGender.Masculine, WordForm.Normal) => "3.º"\n</code></pre>\n<p>If you want to go deeper, check those test cases: <a href=\"https://github.com/Humanizr/Humanizer/blob/60822b6ddbfef1097feb873fd0161dc812576fce/src/Humanizer.Tests.Shared/OrdinalizeTests.cs\" rel=\"nofollow noreferrer\">OrdinalizeTests.cs</a></p>\n"
},
{
"answer_id": 72792661,
"author": "Grastveit",
"author_id": 470022,
"author_profile": "https://Stackoverflow.com/users/470022",
"pm_score": 1,
"selected": false,
"text": "<p>The accepted answer with switch-expressions and pattern-matching from c# 8 and 9.</p>\n<p>No unneeded string conversion or allocations.</p>\n<pre class=\"lang-cs prettyprint-override\"><code>string.Concat(number, number < 0 ? "" : (number % 100) switch \n{ \n 11 or 12 or 13 => "th", \n int n => (n % 10) switch \n { \n 1 => "st", \n 2 => "nd", \n 3 => "rd", \n _ => "th", \n }\n})\n</code></pre>\n<p>Or as unfriendly one-liner:</p>\n<pre class=\"lang-cs prettyprint-override\"><code>$"{number}{(number < 0 ? "" : (number % 100) switch { 11 or 12 or 13 => "th", int n => (n % 10) switch { 1 => "st", 2 => "nd", 3 => "rd", _ => "th" }})}"\n</code></pre>\n"
}
] | 2008/08/21 | [
"https://Stackoverflow.com/questions/20156",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/383/"
] | Is there an easy way in C# to create [Ordinals](http://en.wikipedia.org/wiki/Ordinal_numbers_%28linguistics%29) for a number? For example:
* 1 returns 1st
* 2 returns 2nd
* 3 returns 3rd
* ...etc
Can this be done through `String.Format()` or are there any functions available to do this? | This page gives you a complete listing of all custom numerical formatting rules:
[Custom numeric format strings](https://learn.microsoft.com/en-us/dotnet/standard/base-types/custom-numeric-format-strings)
As you can see, there is nothing in there about ordinals, so it can't be done using `String.Format`. However its not really that hard to write a function to do it.
```
public static string AddOrdinal(int num)
{
if( num <= 0 ) return num.ToString();
switch(num % 100)
{
case 11:
case 12:
case 13:
return num + "th";
}
switch(num % 10)
{
case 1:
return num + "st";
case 2:
return num + "nd";
case 3:
return num + "rd";
default:
return num + "th";
}
}
```
Update: Technically Ordinals don't exist for <= 0, so I've updated the code above. Also removed the redundant `ToString()` methods.
Also note, this is not internationalized. I've no idea what ordinals look like in other languages. |
20,185 | <p>I have a collection of classes that inherit from an abstract class I created. I'd like to use the abstract class as a factory for creating instances of concrete implementations of my abstract class. </p>
<p>Is there any way to hide a constructor from all code except a parent class.</p>
<p>I'd like to do this basically</p>
<pre><code>public abstract class AbstractClass
{
public static AbstractClass MakeAbstractClass(string args)
{
if (args == "a")
return new ConcreteClassA();
if (args == "b")
return new ConcreteClassB();
}
}
public class ConcreteClassA : AbstractClass
{
}
public class ConcreteClassB : AbstractClass
{
}
</code></pre>
<p>But I want to prevent anyone from directly instantiating the 2 concrete classes. I want to ensure that only the MakeAbstractClass() method can instantiate the base classes. Is there any way to do this?</p>
<p><strong>UPDATE</strong><br>
I don't need to access any specific methods of ConcreteClassA or B from outside of the Abstract class. I only need the public methods my Abstract class provides. I don't really need to prevent the Concrete classes from being instantiated, I'm just trying to avoid it since they provide no new public interfaces, just different implementations of some very specific things internal to the abstract class.</p>
<p>To me, the simplest solution is to <a href="https://stackoverflow.com/questions/20185/is-there-a-way-to-make-a-constructor-only-visible-to-a-parent-class-in-c#20200">make child classes as samjudson mentioned</a>. I'd like to avoid this however since it would make my abstract class' file a lot bigger than I'd like it to be. I'd rather keep classes split out over a few files for organization.</p>
<p>I guess there's no easy solution to this...</p>
| [
{
"answer_id": 20199,
"author": "Vaibhav",
"author_id": 380,
"author_profile": "https://Stackoverflow.com/users/380",
"pm_score": 1,
"selected": false,
"text": "<p>No, I don't think we can do that.</p>\n"
},
{
"answer_id": 20200,
"author": "samjudson",
"author_id": 1908,
"author_profile": "https://Stackoverflow.com/users/1908",
"pm_score": 3,
"selected": true,
"text": "<p>You can make the sub classes child classes, something like this:</p>\n\n<pre><code>public abstract class AbstractClass\n{\n public static AbstractClass MakeAbstractClass(string args)\n {\n if (args == \"a\")\n return new ConcreteClassA();\n if (args == \"b\")\n return new ConcreteClassB();\n }\n\n private class ConcreteClassA : AbstractClass\n {\n }\n\n private class ConcreteClassB : AbstractClass\n {\n }\n}\n</code></pre>\n\n<p><a href=\"https://stackoverflow.com/questions/20185/is-there-a-way-to-make-a-constructor-only-visible-to-a-parent-class-in-c#20220\">@Vaibhav</a> This does indeed mean that the classes are also hidden. But this is as far as I am aware the only way to completely hide the constructor.</p>\n\n<p>Edit: As others have mentioned the same thing can be accomplished using Reflection, which might actually be closer to what you would like to be the case - for example the above method replies on the concrete classes being inside the same file as the Abstract class, which probably isn't very convenient. Having said that this way is a nice 'Hack', and good if the number and complexity of the concrete classes is low.</p>\n"
},
{
"answer_id": 20221,
"author": "Rob Cooper",
"author_id": 832,
"author_profile": "https://Stackoverflow.com/users/832",
"pm_score": 2,
"selected": false,
"text": "<p>If the classes are in the same assembly, can you not make the constructors internal?</p>\n"
},
{
"answer_id": 20258,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 0,
"selected": false,
"text": "<p>Do you actually <strong>need</strong> to do this? If you're using some kind of pseudo factory pattern without a true design need for it, you're only going to make your code harder to understand, maintain and extend.</p>\n\n<p>If you don't need to do this, just implement a true factory pattern. Or, more ALTy, use a DI/IoC framework.</p>\n"
},
{
"answer_id": 20266,
"author": "lubos hasko",
"author_id": 275,
"author_profile": "https://Stackoverflow.com/users/275",
"pm_score": 3,
"selected": false,
"text": "<blockquote>\n <p>To me, the simplest solution is to\n make child classes as samjudson\n mentioned. I'd like to avoid this\n however since it would make my\n abstract class' file a lot bigger than\n I'd like it to be. I'd rather keep\n classes split out over a few files for\n organization.</p>\n</blockquote>\n\n<p>No problem, just use <strong>partial</strong> keyword and you can split your inner classes into as many files as you wish. You don't have to keep it in the same file.</p>\n\n<p><strong>Previous answer:</strong></p>\n\n<p>It's possible but only with reflection</p>\n\n<pre><code>public abstract class AbstractClass\n{\n public static AbstractClass MakeAbstractClass(string args)\n {\n if (args == \"a\")\n return (AbstractClass)Activator.CreateInstance(typeof(ConcreteClassA), true);\n if (args == \"b\")\n return (AbstractClass)Activator.CreateInstance(typeof(ConcreteClassB), true);\n }\n}\n\npublic class ConcreteClassA : AbstractClass\n{\n private ConcreteClassA()\n {\n }\n}\n\npublic class ConcreteClassB : AbstractClass\n{\n private ConcreteClassB()\n {\n }\n}\n</code></pre>\n\n<p>and here is another pattern, without ugly <strong>MakeAbstractClass(string args)</strong></p>\n\n<pre><code>public abstract class AbstractClass<T> where T : AbstractClass<T>\n{\n public static T MakeAbstractClass()\n {\n T value = (T)Activator.CreateInstance(typeof(T), true);\n // your processing logic\n return value;\n }\n}\n\npublic class ConcreteClassA : AbstractClass<ConcreteClassA>\n{\n private ConcreteClassA()\n {\n }\n}\n\npublic class ConcreteClassB : AbstractClass<ConcreteClassB>\n{\n private ConcreteClassB()\n {\n }\n}\n</code></pre>\n"
},
{
"answer_id": 20279,
"author": "Jedi Master Spooky",
"author_id": 1154,
"author_profile": "https://Stackoverflow.com/users/1154",
"pm_score": -1,
"selected": false,
"text": "<p>What you need to do is this to prevent the default constructor to be create. The internal can be change to public if the classes are not in the same assembly.</p>\n\n<pre><code>public abstract class AbstractClass{\n\n public static AbstractClass MakeAbstractClass(string args)\n {\n if (args == \"a\")\n return ConcreteClassA().GetConcreteClassA();\n if (args == \"b\")\n return ConcreteClassB().GetConcreteClassB();\n }\n}\n\npublic class ConcreteClassA : AbstractClass\n{\n private ConcreteClassA(){}\n\n internal static ConcreteClassA GetConcreteClassA(){\n return ConcreteClassA();\n }\n}\n\npublic class ConcreteClassB : AbstractClass\n{\n private ConcreteClassB(){}\n internal static ConcreteClassB Get ConcreteClassB(){\n return ConcreteClassB();\n }\n\n}\n</code></pre>\n"
},
{
"answer_id": 20325,
"author": "Peteter",
"author_id": 1192,
"author_profile": "https://Stackoverflow.com/users/1192",
"pm_score": 0,
"selected": false,
"text": "<p>Can't you use the keyword <code>partial</code> for splitting the code for a class into many files?</p>\n"
},
{
"answer_id": 24338,
"author": "FlySwat",
"author_id": 1965,
"author_profile": "https://Stackoverflow.com/users/1965",
"pm_score": 0,
"selected": false,
"text": "<p>If you are using this class in a seperate service assembly, you can use the internal keyword.</p>\n\n<pre><code>public class AbstractClass\n{\n public AbstractClass ClassFactory(string args)\n {\n switch (args)\n {\n case \"A\":\n return new ConcreteClassA(); \n case \"B\":\n return new ConcreteClassB(); \n default:\n return null;\n }\n }\n}\n\npublic class ConcreteClassA : AbstractClass\n{\n internal ConcreteClassA(){ }\n}\n\npublic class ConcreteClassB : AbstractClass\n{\n internal ConcreteClassB() {}\n}\n</code></pre>\n"
},
{
"answer_id": 53880,
"author": "Mark Ingram",
"author_id": 986,
"author_profile": "https://Stackoverflow.com/users/986",
"pm_score": 1,
"selected": false,
"text": "<p>Following on from the <a href=\"https://stackoverflow.com/questions/20185/is-there-a-way-to-make-a-constructor-only-visible-to-a-parent-class-in-c#20200\">accepted answer</a>, if you had a public interface and made the private classes implement the interface, you could then return a pointer to the interface and anyone outside of your parent abstract class could then use them (whilst still hiding the child classes).</p>\n"
}
] | 2008/08/21 | [
"https://Stackoverflow.com/questions/20185",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/392/"
] | I have a collection of classes that inherit from an abstract class I created. I'd like to use the abstract class as a factory for creating instances of concrete implementations of my abstract class.
Is there any way to hide a constructor from all code except a parent class.
I'd like to do this basically
```
public abstract class AbstractClass
{
public static AbstractClass MakeAbstractClass(string args)
{
if (args == "a")
return new ConcreteClassA();
if (args == "b")
return new ConcreteClassB();
}
}
public class ConcreteClassA : AbstractClass
{
}
public class ConcreteClassB : AbstractClass
{
}
```
But I want to prevent anyone from directly instantiating the 2 concrete classes. I want to ensure that only the MakeAbstractClass() method can instantiate the base classes. Is there any way to do this?
**UPDATE**
I don't need to access any specific methods of ConcreteClassA or B from outside of the Abstract class. I only need the public methods my Abstract class provides. I don't really need to prevent the Concrete classes from being instantiated, I'm just trying to avoid it since they provide no new public interfaces, just different implementations of some very specific things internal to the abstract class.
To me, the simplest solution is to [make child classes as samjudson mentioned](https://stackoverflow.com/questions/20185/is-there-a-way-to-make-a-constructor-only-visible-to-a-parent-class-in-c#20200). I'd like to avoid this however since it would make my abstract class' file a lot bigger than I'd like it to be. I'd rather keep classes split out over a few files for organization.
I guess there's no easy solution to this... | You can make the sub classes child classes, something like this:
```
public abstract class AbstractClass
{
public static AbstractClass MakeAbstractClass(string args)
{
if (args == "a")
return new ConcreteClassA();
if (args == "b")
return new ConcreteClassB();
}
private class ConcreteClassA : AbstractClass
{
}
private class ConcreteClassB : AbstractClass
{
}
}
```
[@Vaibhav](https://stackoverflow.com/questions/20185/is-there-a-way-to-make-a-constructor-only-visible-to-a-parent-class-in-c#20220) This does indeed mean that the classes are also hidden. But this is as far as I am aware the only way to completely hide the constructor.
Edit: As others have mentioned the same thing can be accomplished using Reflection, which might actually be closer to what you would like to be the case - for example the above method replies on the concrete classes being inside the same file as the Abstract class, which probably isn't very convenient. Having said that this way is a nice 'Hack', and good if the number and complexity of the concrete classes is low. |
20,227 | <p>Every method I write to encode a string in Java using 3DES can't be decrypted back to the original string. Does anyone have a simple code snippet that can just encode and then decode the string back to the original string?</p>
<p>I know I'm making a very silly mistake somewhere in this code. Here's what I've been working with so far:</p>
<p>** note, I am not returning the BASE64 text from the encrypt method, and I am not base64 un-encoding in the decrypt method because I was trying to see if I was making a mistake in the BASE64 part of the puzzle.</p>
<pre><code>public class TripleDESTest {
public static void main(String[] args) {
String text = "kyle boon";
byte[] codedtext = new TripleDESTest().encrypt(text);
String decodedtext = new TripleDESTest().decrypt(codedtext);
System.out.println(codedtext);
System.out.println(decodedtext);
}
public byte[] encrypt(String message) {
try {
final MessageDigest md = MessageDigest.getInstance("md5");
final byte[] digestOfPassword = md.digest("HG58YZ3CR9".getBytes("utf-8"));
final byte[] keyBytes = Arrays.copyOf(digestOfPassword, 24);
for (int j = 0, k = 16; j < 8;)
{
keyBytes[k++] = keyBytes[j++];
}
final SecretKey key = new SecretKeySpec(keyBytes, "DESede");
final IvParameterSpec iv = new IvParameterSpec(new byte[8]);
final Cipher cipher = Cipher.getInstance("DESede/CBC/PKCS5Padding");
cipher.init(Cipher.ENCRYPT_MODE, key, iv);
final byte[] plainTextBytes = message.getBytes("utf-8");
final byte[] cipherText = cipher.doFinal(plainTextBytes);
final String encodedCipherText = new sun.misc.BASE64Encoder().encode(cipherText);
return cipherText;
}
catch (java.security.InvalidAlgorithmParameterException e) { System.out.println("Invalid Algorithm"); }
catch (javax.crypto.NoSuchPaddingException e) { System.out.println("No Such Padding"); }
catch (java.security.NoSuchAlgorithmException e) { System.out.println("No Such Algorithm"); }
catch (java.security.InvalidKeyException e) { System.out.println("Invalid Key"); }
catch (BadPaddingException e) { System.out.println("Invalid Key");}
catch (IllegalBlockSizeException e) { System.out.println("Invalid Key");}
catch (UnsupportedEncodingException e) { System.out.println("Invalid Key");}
return null;
}
public String decrypt(byte[] message) {
try
{
final MessageDigest md = MessageDigest.getInstance("md5");
final byte[] digestOfPassword = md.digest("HG58YZ3CR9".getBytes("utf-8"));
final byte[] keyBytes = Arrays.copyOf(digestOfPassword, 24);
for (int j = 0, k = 16; j < 8;)
{
keyBytes[k++] = keyBytes[j++];
}
final SecretKey key = new SecretKeySpec(keyBytes, "DESede");
final IvParameterSpec iv = new IvParameterSpec(new byte[8]);
final Cipher decipher = Cipher.getInstance("DESede/CBC/PKCS5Padding");
decipher.init(Cipher.DECRYPT_MODE, key, iv);
//final byte[] encData = new sun.misc.BASE64Decoder().decodeBuffer(message);
final byte[] plainText = decipher.doFinal(message);
return plainText.toString();
}
catch (java.security.InvalidAlgorithmParameterException e) { System.out.println("Invalid Algorithm"); }
catch (javax.crypto.NoSuchPaddingException e) { System.out.println("No Such Padding"); }
catch (java.security.NoSuchAlgorithmException e) { System.out.println("No Such Algorithm"); }
catch (java.security.InvalidKeyException e) { System.out.println("Invalid Key"); }
catch (BadPaddingException e) { System.out.println("Invalid Key");}
catch (IllegalBlockSizeException e) { System.out.println("Invalid Key");}
catch (UnsupportedEncodingException e) { System.out.println("Invalid Key");}
catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return null;
}
}
</code></pre>
| [
{
"answer_id": 20670,
"author": "Boris Terzic",
"author_id": 1996,
"author_profile": "https://Stackoverflow.com/users/1996",
"pm_score": 7,
"selected": true,
"text": "<p>Your code was fine except for the Base 64 encoding bit (which you mentioned was a test), the reason the output may not have made sense is that you were displaying a raw byte array (doing toString() on a byte array returns its internal Java reference, not the String representation of the <strong>contents</strong>). Here's a version that's just a teeny bit cleaned up and which prints \"kyle boon\" as the decoded string:</p>\n\n<pre><code>import java.security.MessageDigest;\nimport java.util.Arrays;\n\nimport javax.crypto.Cipher;\nimport javax.crypto.SecretKey;\nimport javax.crypto.spec.IvParameterSpec;\nimport javax.crypto.spec.SecretKeySpec;\n\npublic class TripleDESTest {\n\n public static void main(String[] args) throws Exception {\n\n String text = \"kyle boon\";\n\n byte[] codedtext = new TripleDESTest().encrypt(text);\n String decodedtext = new TripleDESTest().decrypt(codedtext);\n\n System.out.println(codedtext); // this is a byte array, you'll just see a reference to an array\n System.out.println(decodedtext); // This correctly shows \"kyle boon\"\n }\n\n public byte[] encrypt(String message) throws Exception {\n final MessageDigest md = MessageDigest.getInstance(\"md5\");\n final byte[] digestOfPassword = md.digest(\"HG58YZ3CR9\"\n .getBytes(\"utf-8\"));\n final byte[] keyBytes = Arrays.copyOf(digestOfPassword, 24);\n for (int j = 0, k = 16; j < 8;) {\n keyBytes[k++] = keyBytes[j++];\n }\n\n final SecretKey key = new SecretKeySpec(keyBytes, \"DESede\");\n final IvParameterSpec iv = new IvParameterSpec(new byte[8]);\n final Cipher cipher = Cipher.getInstance(\"DESede/CBC/PKCS5Padding\");\n cipher.init(Cipher.ENCRYPT_MODE, key, iv);\n\n final byte[] plainTextBytes = message.getBytes(\"utf-8\");\n final byte[] cipherText = cipher.doFinal(plainTextBytes);\n // final String encodedCipherText = new sun.misc.BASE64Encoder()\n // .encode(cipherText);\n\n return cipherText;\n }\n\n public String decrypt(byte[] message) throws Exception {\n final MessageDigest md = MessageDigest.getInstance(\"md5\");\n final byte[] digestOfPassword = md.digest(\"HG58YZ3CR9\"\n .getBytes(\"utf-8\"));\n final byte[] keyBytes = Arrays.copyOf(digestOfPassword, 24);\n for (int j = 0, k = 16; j < 8;) {\n keyBytes[k++] = keyBytes[j++];\n }\n\n final SecretKey key = new SecretKeySpec(keyBytes, \"DESede\");\n final IvParameterSpec iv = new IvParameterSpec(new byte[8]);\n final Cipher decipher = Cipher.getInstance(\"DESede/CBC/PKCS5Padding\");\n decipher.init(Cipher.DECRYPT_MODE, key, iv);\n\n // final byte[] encData = new\n // sun.misc.BASE64Decoder().decodeBuffer(message);\n final byte[] plainText = decipher.doFinal(message);\n\n return new String(plainText, \"UTF-8\");\n }\n}\n</code></pre>\n"
},
{
"answer_id": 10164989,
"author": "jlmontesdeoca",
"author_id": 1334941,
"author_profile": "https://Stackoverflow.com/users/1334941",
"pm_score": 4,
"selected": false,
"text": "<p>I had hard times figuring it out myself and this post helped me to find the right answer for my case. When working with financial messaging as ISO-8583 the 3DES requirements are quite specific, so for my especial case the \"DESede/CBC/PKCS5Padding\" combinations wasn't solving the problem. After some comparative testing of my results against some 3DES calculators designed for the financial world I found the the value \"DESede/ECB/Nopadding\" is more suited for the the specific task.</p>\n\n<p>Here is a demo implementation of my TripleDes class (using the Bouncy Castle provider)</p>\n\n<pre><code>\n\n import java.security.InvalidKeyException;\n import java.security.NoSuchAlgorithmException;\n import java.security.NoSuchProviderException;\n import java.security.Security;\n import javax.crypto.BadPaddingException;\n import javax.crypto.Cipher;\n import javax.crypto.IllegalBlockSizeException;\n import javax.crypto.NoSuchPaddingException;\n import javax.crypto.SecretKey;\n import javax.crypto.spec.SecretKeySpec;\n import org.bouncycastle.jce.provider.BouncyCastleProvider;\n\n\n /**\n *\n * @author Jose Luis Montes de Oca\n */\n public class TripleDesCipher {\n private static String TRIPLE_DES_TRANSFORMATION = \"DESede/ECB/Nopadding\";\n private static String ALGORITHM = \"DESede\";\n private static String BOUNCY_CASTLE_PROVIDER = \"BC\";\n private Cipher encrypter;\n private Cipher decrypter;\n\n public TripleDesCipher(byte[] key) throws NoSuchAlgorithmException, NoSuchProviderException, NoSuchPaddingException,\n InvalidKeyException {\n Security.addProvider(new BouncyCastleProvider());\n SecretKey keySpec = new SecretKeySpec(key, ALGORITHM);\n encrypter = Cipher.getInstance(TRIPLE_DES_TRANSFORMATION, BOUNCY_CASTLE_PROVIDER);\n encrypter.init(Cipher.ENCRYPT_MODE, keySpec);\n decrypter = Cipher.getInstance(TRIPLE_DES_TRANSFORMATION, BOUNCY_CASTLE_PROVIDER);\n decrypter.init(Cipher.DECRYPT_MODE, keySpec);\n }\n\n public byte[] encode(byte[] input) throws IllegalBlockSizeException, BadPaddingException {\n return encrypter.doFinal(input);\n }\n\n public byte[] decode(byte[] input) throws IllegalBlockSizeException, BadPaddingException {\n return decrypter.doFinal(input);\n }\n }\n\n</code></pre>\n"
},
{
"answer_id": 11367849,
"author": "siliconsmiley",
"author_id": 1024005,
"author_profile": "https://Stackoverflow.com/users/1024005",
"pm_score": 2,
"selected": false,
"text": "<p>Here's a very simply static encrypt/decrypt class biased on the Bouncy Castle no padding example by Jose Luis Montes de Oca. This one is using \"DESede/ECB/PKCS7Padding\" so I don't have to bother manually padding.</p>\n\n<pre><code>\n package com.zenimax.encryption;\n\n import java.security.InvalidKeyException;\n import java.security.NoSuchAlgorithmException;\n import java.security.NoSuchProviderException;\n import java.security.Security;\n import javax.crypto.BadPaddingException;\n import javax.crypto.Cipher;\n import javax.crypto.IllegalBlockSizeException;\n import javax.crypto.NoSuchPaddingException;\n import javax.crypto.SecretKey;\n import javax.crypto.spec.SecretKeySpec;\n import org.bouncycastle.jce.provider.BouncyCastleProvider;\n\n /**\n * \n * @author Matthew H. Wagner\n */\n public class TripleDesBouncyCastle {\n private static String TRIPLE_DES_TRANSFORMATION = \"DESede/ECB/PKCS7Padding\";\n private static String ALGORITHM = \"DESede\";\n private static String BOUNCY_CASTLE_PROVIDER = \"BC\";\n\n private static void init()\n {\n Security.addProvider(new BouncyCastleProvider());\n }\n\n public static byte[] encode(byte[] input, byte[] key)\n throws IllegalBlockSizeException, BadPaddingException,\n NoSuchAlgorithmException, NoSuchProviderException,\n NoSuchPaddingException, InvalidKeyException {\n init();\n SecretKey keySpec = new SecretKeySpec(key, ALGORITHM);\n Cipher encrypter = Cipher.getInstance(TRIPLE_DES_TRANSFORMATION,\n BOUNCY_CASTLE_PROVIDER);\n encrypter.init(Cipher.ENCRYPT_MODE, keySpec);\n return encrypter.doFinal(input);\n }\n\n public static byte[] decode(byte[] input, byte[] key)\n throws IllegalBlockSizeException, BadPaddingException,\n NoSuchAlgorithmException, NoSuchProviderException,\n NoSuchPaddingException, InvalidKeyException {\n init();\n SecretKey keySpec = new SecretKeySpec(key, ALGORITHM);\n Cipher decrypter = Cipher.getInstance(TRIPLE_DES_TRANSFORMATION,\n BOUNCY_CASTLE_PROVIDER);\n decrypter.init(Cipher.DECRYPT_MODE, keySpec);\n return decrypter.doFinal(input);\n }\n }\n</code>\n</pre>\n"
},
{
"answer_id": 13612902,
"author": "oneiros",
"author_id": 861832,
"author_profile": "https://Stackoverflow.com/users/861832",
"pm_score": 4,
"selected": false,
"text": "<p>Here is a solution using the <strong>javax.crypto</strong> library and the apache commons codec library for encoding and decoding in Base64: </p>\n\n<pre><code>import java.security.spec.KeySpec;\nimport javax.crypto.Cipher;\nimport javax.crypto.SecretKey;\nimport javax.crypto.SecretKeyFactory;\nimport javax.crypto.spec.DESedeKeySpec;\nimport org.apache.commons.codec.binary.Base64;\n\npublic class TrippleDes {\n\n private static final String UNICODE_FORMAT = \"UTF8\";\n public static final String DESEDE_ENCRYPTION_SCHEME = \"DESede\";\n private KeySpec ks;\n private SecretKeyFactory skf;\n private Cipher cipher;\n byte[] arrayBytes;\n private String myEncryptionKey;\n private String myEncryptionScheme;\n SecretKey key;\n\n public TrippleDes() throws Exception {\n myEncryptionKey = \"ThisIsSpartaThisIsSparta\";\n myEncryptionScheme = DESEDE_ENCRYPTION_SCHEME;\n arrayBytes = myEncryptionKey.getBytes(UNICODE_FORMAT);\n ks = new DESedeKeySpec(arrayBytes);\n skf = SecretKeyFactory.getInstance(myEncryptionScheme);\n cipher = Cipher.getInstance(myEncryptionScheme);\n key = skf.generateSecret(ks);\n }\n\n\n public String encrypt(String unencryptedString) {\n String encryptedString = null;\n try {\n cipher.init(Cipher.ENCRYPT_MODE, key);\n byte[] plainText = unencryptedString.getBytes(UNICODE_FORMAT);\n byte[] encryptedText = cipher.doFinal(plainText);\n encryptedString = new String(Base64.encodeBase64(encryptedText));\n } catch (Exception e) {\n e.printStackTrace();\n }\n return encryptedString;\n }\n\n\n public String decrypt(String encryptedString) {\n String decryptedText=null;\n try {\n cipher.init(Cipher.DECRYPT_MODE, key);\n byte[] encryptedText = Base64.decodeBase64(encryptedString);\n byte[] plainText = cipher.doFinal(encryptedText);\n decryptedText= new String(plainText);\n } catch (Exception e) {\n e.printStackTrace();\n }\n return decryptedText;\n }\n\n\n public static void main(String args []) throws Exception\n {\n TrippleDes td= new TrippleDes();\n\n String target=\"imparator\";\n String encrypted=td.encrypt(target);\n String decrypted=td.decrypt(encrypted);\n\n System.out.println(\"String To Encrypt: \"+ target);\n System.out.println(\"Encrypted String:\" + encrypted);\n System.out.println(\"Decrypted String:\" + decrypted);\n\n }\n\n}\n</code></pre>\n\n<p>Running the above program results with the following output: </p>\n\n<pre><code>String To Encrypt: imparator\nEncrypted String:FdBNaYWfjpWN9eYghMpbRA==\nDecrypted String:imparator\n</code></pre>\n"
},
{
"answer_id": 25397364,
"author": "shiv",
"author_id": 3728540,
"author_profile": "https://Stackoverflow.com/users/3728540",
"pm_score": -1,
"selected": false,
"text": "<pre><code>import java.io.IOException;\nimport java.io.UnsupportedEncodingException;\nimport java.security.Key;\nimport javax.crypto.Cipher;\nimport javax.crypto.SecretKeyFactory;\nimport javax.crypto.spec.DESedeKeySpec;\nimport javax.crypto.spec.IvParameterSpec;\nimport java.util.Base64;\nimport java.util.Base64.Encoder;\n\n\n/**\n * \n * @author shivshankar pal\n * \n * this code is working properly. doing proper encription and decription\n note:- it will work only with jdk8\n\n * \n\n * \n */\n\npublic class TDes {\n private static byte[] key = { 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,\n 0x00, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x02, 0x02,\n 0x02, 0x02, 0x02, 0x02, 0x02, 0x02 };\n\n private static byte[] keyiv = { 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,\n 0x00 };\n\n\n\n public static String encode(String args) {\n\n\n System.out.println(\"plain data==> \" + args);\n\n byte[] encoding;\n try {\n encoding = Base64.getEncoder().encode(args.getBytes(\"UTF-8\"));\n\n System.out.println(\"Base64.encodeBase64==>\" + new String(encoding));\n byte[] str5 = des3EncodeCBC(key, keyiv, encoding);\n\n System.out.println(\"des3EncodeCBC==> \" + new String(str5));\n\n byte[] encoding1 = Base64.getEncoder().encode(str5);\n System.out.println(\"Base64.encodeBase64==> \" + new String(encoding1));\n return new String(encoding1);\n } catch (UnsupportedEncodingException e) {\n // TODO Auto-generated catch block\n e.printStackTrace();\n }\n return null;\n }\n\n\n public static String decode(String args) {\n try {\n System.out.println(\"encrypted data==>\" + new String(args.getBytes(\"UTF-8\")));\n\n\n byte[] decode = Base64.getDecoder().decode(args.getBytes(\"UTF-8\"));\n System.out.println(\"Base64.decodeBase64(main encription)==>\" + new String(decode));\n\n byte[] str6 = des3DecodeCBC(key, keyiv, decode);\n System.out.println(\"des3DecodeCBC==>\" + new String(str6));\n String data=new String(str6);\n byte[] decode1 = Base64.getDecoder().decode(data.trim().getBytes(\"UTF-8\"));\n System.out.println(\"plaintext==> \" + new String(decode1));\n return new String(decode1);\n } catch (UnsupportedEncodingException e) {\n // TODO Auto-generated catch block\n e.printStackTrace();\n }\n return \"u mistaken in try block\";\n\n }\n\n\n\n private static byte[] des3EncodeCBC(byte[] key, byte[] keyiv, byte[] data) {\n try {\n Key deskey = null;\n DESedeKeySpec spec = new DESedeKeySpec(key);\n SecretKeyFactory keyfactory = SecretKeyFactory.getInstance(\"desede\");\n deskey = keyfactory.generateSecret(spec);\n\n Cipher cipher = Cipher.getInstance(\"desede/ CBC/PKCS5Padding\");\n IvParameterSpec ips = new IvParameterSpec(keyiv);\n cipher.init(Cipher.ENCRYPT_MODE, deskey, ips);\n byte[] bout = cipher.doFinal(data);\n return bout;\n\n } catch (Exception e) {\n System.out.println(\"methods qualified name\" + e);\n }\n return null;\n\n }\n\n private static byte[] des3DecodeCBC(byte[] key, byte[] keyiv, byte[] data) {\n try {\n Key deskey = null;\n DESedeKeySpec spec = new DESedeKeySpec(key);\n SecretKeyFactory keyfactory = SecretKeyFactory.getInstance(\"desede\");\n deskey = keyfactory.generateSecret(spec);\n\n Cipher cipher = Cipher.getInstance(\"desede/ CBC/NoPadding\");//PKCS5Padding NoPadding\n IvParameterSpec ips = new IvParameterSpec(keyiv);\n cipher.init(Cipher.DECRYPT_MODE, deskey, ips);\n\n byte[] bout = cipher.doFinal(data);\n\n\n return bout;\n\n } catch (Exception e) {\n System.out.println(\"methods qualified name\" + e);\n }\n\n return null;\n\n }\n\n}\n</code></pre>\n"
},
{
"answer_id": 70600508,
"author": "Ayomide Joysbright Oyediran",
"author_id": 15661514,
"author_profile": "https://Stackoverflow.com/users/15661514",
"pm_score": 0,
"selected": false,
"text": "<pre><code>private static final String UNICODE_FORMAT = "UTF8";\nprivate static final String DESEDE_ENCRYPTION_SCHEME = "DESede";\nprivate KeySpec ks;\nprivate SecretKeyFactory skf;\nprivate Cipher cipher;\nbyte[] arrayBytes;\nprivate String encryptionSecretKey = "ThisIsSpartaThisIsSparta";\nSecretKey key;\n\npublic TripleDesEncryptDecrypt() throws Exception {\n convertStringToSecretKey(encryptionSecretKey);\n}\n\npublic TripleDesEncryptDecrypt(String encryptionSecretKey) throws Exception {\n convertStringToSecretKey(encryptionSecretKey);\n}\n\npublic SecretKey convertStringToSecretKey (String encryptionSecretKey) throws Exception {\n arrayBytes = encryptionSecretKey.getBytes(UNICODE_FORMAT);\n ks = new DESedeKeySpec(arrayBytes);\n skf = SecretKeyFactory.getInstance(DESEDE_ENCRYPTION_SCHEME);\n cipher = Cipher.getInstance(DESEDE_ENCRYPTION_SCHEME);\n key = skf.generateSecret(ks);\n return key;\n}\n\n/**\n * Encrypt without specifying secret key\n * \n * @param unencryptedString\n * @return String\n */\npublic String encrypt(String unencryptedString) {\n String encryptedString = null;\n try {\n cipher.init(Cipher.ENCRYPT_MODE, key);\n byte[] plainText = unencryptedString.getBytes(UNICODE_FORMAT);\n byte[] encryptedText = cipher.doFinal(plainText);\n encryptedString = new String(Base64.encodeBase64(encryptedText));\n } catch (Exception e) {\n e.printStackTrace();\n }\n return encryptedString;\n}\n\n/**\n * Encrypt with specified secret key\n * \n * @param unencryptedString\n * @return String\n */\npublic String encrypt(String encryptionSecretKey, String unencryptedString) {\n String encryptedString = null;\n try {\n key = convertStringToSecretKey(encryptionSecretKey);\n cipher.init(Cipher.ENCRYPT_MODE, key);\n byte[] plainText = unencryptedString.getBytes(UNICODE_FORMAT);\n byte[] encryptedText = cipher.doFinal(plainText);\n encryptedString = new String(Base64.encodeBase64(encryptedText));\n } catch (Exception e) {\n e.printStackTrace();\n }\n return encryptedString;\n}\n\n\n/**\n * Decrypt without specifying secret key\n * @param encryptedString\n * @return\n */\npublic String decrypt(String encryptedString) {\n String decryptedText=null;\n try {\n cipher.init(Cipher.DECRYPT_MODE, key);\n byte[] encryptedText = Base64.decodeBase64(encryptedString);\n byte[] plainText = cipher.doFinal(encryptedText);\n decryptedText= new String(plainText);\n } catch (Exception e) {\n e.printStackTrace();\n }\n return decryptedText;\n}\n\n/**\n * Decrypt with specified secret key\n * @param encryptedString\n * @return\n */\npublic String decrypt(String encryptionSecretKey, String encryptedString) {\n String decryptedText=null;\n try {\n key = convertStringToSecretKey(encryptionSecretKey);\n cipher.init(Cipher.DECRYPT_MODE, key);\n byte[] encryptedText = Base64.decodeBase64(encryptedString);\n byte[] plainText = cipher.doFinal(encryptedText);\n decryptedText= new String(plainText);\n } catch (Exception e) {\n e.printStackTrace();\n }\n return decryptedText;\n}\n</code></pre>\n"
}
] | 2008/08/21 | [
"https://Stackoverflow.com/questions/20227",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1486/"
] | Every method I write to encode a string in Java using 3DES can't be decrypted back to the original string. Does anyone have a simple code snippet that can just encode and then decode the string back to the original string?
I know I'm making a very silly mistake somewhere in this code. Here's what I've been working with so far:
\*\* note, I am not returning the BASE64 text from the encrypt method, and I am not base64 un-encoding in the decrypt method because I was trying to see if I was making a mistake in the BASE64 part of the puzzle.
```
public class TripleDESTest {
public static void main(String[] args) {
String text = "kyle boon";
byte[] codedtext = new TripleDESTest().encrypt(text);
String decodedtext = new TripleDESTest().decrypt(codedtext);
System.out.println(codedtext);
System.out.println(decodedtext);
}
public byte[] encrypt(String message) {
try {
final MessageDigest md = MessageDigest.getInstance("md5");
final byte[] digestOfPassword = md.digest("HG58YZ3CR9".getBytes("utf-8"));
final byte[] keyBytes = Arrays.copyOf(digestOfPassword, 24);
for (int j = 0, k = 16; j < 8;)
{
keyBytes[k++] = keyBytes[j++];
}
final SecretKey key = new SecretKeySpec(keyBytes, "DESede");
final IvParameterSpec iv = new IvParameterSpec(new byte[8]);
final Cipher cipher = Cipher.getInstance("DESede/CBC/PKCS5Padding");
cipher.init(Cipher.ENCRYPT_MODE, key, iv);
final byte[] plainTextBytes = message.getBytes("utf-8");
final byte[] cipherText = cipher.doFinal(plainTextBytes);
final String encodedCipherText = new sun.misc.BASE64Encoder().encode(cipherText);
return cipherText;
}
catch (java.security.InvalidAlgorithmParameterException e) { System.out.println("Invalid Algorithm"); }
catch (javax.crypto.NoSuchPaddingException e) { System.out.println("No Such Padding"); }
catch (java.security.NoSuchAlgorithmException e) { System.out.println("No Such Algorithm"); }
catch (java.security.InvalidKeyException e) { System.out.println("Invalid Key"); }
catch (BadPaddingException e) { System.out.println("Invalid Key");}
catch (IllegalBlockSizeException e) { System.out.println("Invalid Key");}
catch (UnsupportedEncodingException e) { System.out.println("Invalid Key");}
return null;
}
public String decrypt(byte[] message) {
try
{
final MessageDigest md = MessageDigest.getInstance("md5");
final byte[] digestOfPassword = md.digest("HG58YZ3CR9".getBytes("utf-8"));
final byte[] keyBytes = Arrays.copyOf(digestOfPassword, 24);
for (int j = 0, k = 16; j < 8;)
{
keyBytes[k++] = keyBytes[j++];
}
final SecretKey key = new SecretKeySpec(keyBytes, "DESede");
final IvParameterSpec iv = new IvParameterSpec(new byte[8]);
final Cipher decipher = Cipher.getInstance("DESede/CBC/PKCS5Padding");
decipher.init(Cipher.DECRYPT_MODE, key, iv);
//final byte[] encData = new sun.misc.BASE64Decoder().decodeBuffer(message);
final byte[] plainText = decipher.doFinal(message);
return plainText.toString();
}
catch (java.security.InvalidAlgorithmParameterException e) { System.out.println("Invalid Algorithm"); }
catch (javax.crypto.NoSuchPaddingException e) { System.out.println("No Such Padding"); }
catch (java.security.NoSuchAlgorithmException e) { System.out.println("No Such Algorithm"); }
catch (java.security.InvalidKeyException e) { System.out.println("Invalid Key"); }
catch (BadPaddingException e) { System.out.println("Invalid Key");}
catch (IllegalBlockSizeException e) { System.out.println("Invalid Key");}
catch (UnsupportedEncodingException e) { System.out.println("Invalid Key");}
catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return null;
}
}
``` | Your code was fine except for the Base 64 encoding bit (which you mentioned was a test), the reason the output may not have made sense is that you were displaying a raw byte array (doing toString() on a byte array returns its internal Java reference, not the String representation of the **contents**). Here's a version that's just a teeny bit cleaned up and which prints "kyle boon" as the decoded string:
```
import java.security.MessageDigest;
import java.util.Arrays;
import javax.crypto.Cipher;
import javax.crypto.SecretKey;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;
public class TripleDESTest {
public static void main(String[] args) throws Exception {
String text = "kyle boon";
byte[] codedtext = new TripleDESTest().encrypt(text);
String decodedtext = new TripleDESTest().decrypt(codedtext);
System.out.println(codedtext); // this is a byte array, you'll just see a reference to an array
System.out.println(decodedtext); // This correctly shows "kyle boon"
}
public byte[] encrypt(String message) throws Exception {
final MessageDigest md = MessageDigest.getInstance("md5");
final byte[] digestOfPassword = md.digest("HG58YZ3CR9"
.getBytes("utf-8"));
final byte[] keyBytes = Arrays.copyOf(digestOfPassword, 24);
for (int j = 0, k = 16; j < 8;) {
keyBytes[k++] = keyBytes[j++];
}
final SecretKey key = new SecretKeySpec(keyBytes, "DESede");
final IvParameterSpec iv = new IvParameterSpec(new byte[8]);
final Cipher cipher = Cipher.getInstance("DESede/CBC/PKCS5Padding");
cipher.init(Cipher.ENCRYPT_MODE, key, iv);
final byte[] plainTextBytes = message.getBytes("utf-8");
final byte[] cipherText = cipher.doFinal(plainTextBytes);
// final String encodedCipherText = new sun.misc.BASE64Encoder()
// .encode(cipherText);
return cipherText;
}
public String decrypt(byte[] message) throws Exception {
final MessageDigest md = MessageDigest.getInstance("md5");
final byte[] digestOfPassword = md.digest("HG58YZ3CR9"
.getBytes("utf-8"));
final byte[] keyBytes = Arrays.copyOf(digestOfPassword, 24);
for (int j = 0, k = 16; j < 8;) {
keyBytes[k++] = keyBytes[j++];
}
final SecretKey key = new SecretKeySpec(keyBytes, "DESede");
final IvParameterSpec iv = new IvParameterSpec(new byte[8]);
final Cipher decipher = Cipher.getInstance("DESede/CBC/PKCS5Padding");
decipher.init(Cipher.DECRYPT_MODE, key, iv);
// final byte[] encData = new
// sun.misc.BASE64Decoder().decodeBuffer(message);
final byte[] plainText = decipher.doFinal(message);
return new String(plainText, "UTF-8");
}
}
``` |
20,245 | <p>I am doing an e-commerce solution in ASP.NET which uses <a href="https://www.paypal.com/IntegrationCenter/ic_standard_home.html" rel="noreferrer">PayPal's Website Payments Standard</a> service. Together with that I use a service they offer (<a href="https://www.paypal.com/IntegrationCenter/ic_pdt.html" rel="noreferrer">Payment Data Transfer</a>) that sends you back order information after a user has completed a payment. The final thing I need to do is to parse the POST request from them and persist the info in it. The HTTP request's content is in this form :</p>
<blockquote>
<p>SUCCESS<br>
first_name=Jane+Doe<br>
last_name=Smith<br>
payment_status=Completed<br>
payer_email=janedoesmith%40hotmail.com<br>
payment_gross=3.99<br>
mc_currency=USD<br>
custom=For+the+purchase+of+the+rare+book+Green+Eggs+%26+Ham</p>
</blockquote>
<p>Basically I want to parse this information and do something meaningful, like send it through e-mail or save it in DB. My question is what is the right approach to do parsing raw HTTP data in ASP.NET, not how the parsing itself is done.</p>
| [
{
"answer_id": 20256,
"author": "Greg Hurlman",
"author_id": 35,
"author_profile": "https://Stackoverflow.com/users/35",
"pm_score": 0,
"selected": false,
"text": "<p>If I'm reading your question right, I think you're looking for the <a href=\"http://msdn.microsoft.com/en-us/library/system.web.httprequest.inputstream.aspx\" rel=\"nofollow noreferrer\" title=\"MSDN\">InputStream property</a> on the Request object. Keep in mind that this is a firehose stream, so you can't reset it.</p>\n"
},
{
"answer_id": 20264,
"author": "samjudson",
"author_id": 1908,
"author_profile": "https://Stackoverflow.com/users/1908",
"pm_score": 1,
"selected": false,
"text": "<p>Well if the incoming data is in a standard form encoded POST format, then using the Request.Form array will give you all the data in a nice to handle manner.</p>\n\n<p>If not then I can't see any way other than using Request.InputStream.</p>\n"
},
{
"answer_id": 20274,
"author": "Markus Olsson",
"author_id": 2114,
"author_profile": "https://Stackoverflow.com/users/2114",
"pm_score": 5,
"selected": true,
"text": "<p>Something like this placed in your onload event.</p>\n\n<pre><code>if (Request.RequestType == \"POST\")\n{\n using (StreamReader sr = new StreamReader(Request.InputStream))\n {\n if (sr.ReadLine() == \"SUCCESS\")\n {\n /* Do your parsing here */\n }\n }\n}\n</code></pre>\n\n<p>Mind you that they might want some special sort of response to (ie; not your full webpage), so you might do something like this after you're done parsing.</p>\n\n<pre><code>Response.Clear();\nResponse.ContentType = \"text/plain\";\nResponse.Write(\"Thanks!\");\nResponse.End();\n</code></pre>\n\n<p>Update: this should be done in a Generic Handler (.ashx) file in order to avoid a great deal of overhead from the page model. Check out <a href=\"http://www.aspcode.net/Creating-an-ASHX-handler-in-ASPNET.aspx\" rel=\"noreferrer\">this article</a> for more information about .ashx files</p>\n"
},
{
"answer_id": 20613,
"author": "Mark Brackett",
"author_id": 2199,
"author_profile": "https://Stackoverflow.com/users/2199",
"pm_score": 2,
"selected": false,
"text": "<p>Use an <a href=\"http://msdn.microsoft.com/en-us/library/system.web.ihttphandler.aspx\" rel=\"nofollow noreferrer\">IHttpHandler</a> and avoid the Page model overhead (which you don't need), but use Request.Form to get the values so you don't have to parse name value pairs yourself. Just pretend you're in PHP or Classic ASP (or ASP.NET MVC, for that matter). ;)</p>\n"
},
{
"answer_id": 21968,
"author": "Anders Eurenius",
"author_id": 1421,
"author_profile": "https://Stackoverflow.com/users/1421",
"pm_score": 2,
"selected": false,
"text": "<h2>I'd strongly recommend saving each request to some file.</h2>\n\n<p>This way, you can always go back to the actual contents of it later. You can thank me later, when you find that hostile-endian, koi-8 encoded, [...], whatever it was that stumped your parser...</p>\n"
}
] | 2008/08/21 | [
"https://Stackoverflow.com/questions/20245",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1801/"
] | I am doing an e-commerce solution in ASP.NET which uses [PayPal's Website Payments Standard](https://www.paypal.com/IntegrationCenter/ic_standard_home.html) service. Together with that I use a service they offer ([Payment Data Transfer](https://www.paypal.com/IntegrationCenter/ic_pdt.html)) that sends you back order information after a user has completed a payment. The final thing I need to do is to parse the POST request from them and persist the info in it. The HTTP request's content is in this form :
>
> SUCCESS
>
> first\_name=Jane+Doe
>
> last\_name=Smith
>
> payment\_status=Completed
>
> payer\_email=janedoesmith%40hotmail.com
>
> payment\_gross=3.99
>
> mc\_currency=USD
>
> custom=For+the+purchase+of+the+rare+book+Green+Eggs+%26+Ham
>
>
>
Basically I want to parse this information and do something meaningful, like send it through e-mail or save it in DB. My question is what is the right approach to do parsing raw HTTP data in ASP.NET, not how the parsing itself is done. | Something like this placed in your onload event.
```
if (Request.RequestType == "POST")
{
using (StreamReader sr = new StreamReader(Request.InputStream))
{
if (sr.ReadLine() == "SUCCESS")
{
/* Do your parsing here */
}
}
}
```
Mind you that they might want some special sort of response to (ie; not your full webpage), so you might do something like this after you're done parsing.
```
Response.Clear();
Response.ContentType = "text/plain";
Response.Write("Thanks!");
Response.End();
```
Update: this should be done in a Generic Handler (.ashx) file in order to avoid a great deal of overhead from the page model. Check out [this article](http://www.aspcode.net/Creating-an-ASHX-handler-in-ASPNET.aspx) for more information about .ashx files |
20,249 | <p>We're attemtping to merge our DLL's into one for deployment, thus ILMerge. Almost everything seems to work great. We have a couple web controls that use <code>ClientScript.RegisterClientScriptResource</code> and these are 404-ing after the merge (These worked before the merge).</p>
<p>For example one of our controls would look like</p>
<pre><code>namespace Company.WebControls
{
public class ControlA: CompositeControl, INamingContainer
{
protected override void OnPreRender(EventArgs e)
{
base.OnPreRender(e);
this.Page.ClientScript.RegisterClientScriptResource(typeof(ControlA), "Company.WebControls.ControlA.js");
}
}
}
</code></pre>
<p>It would be located in Project WebControls, assembly Company.WebControls. Underneath would be ControlA.cs and ControlA.js. ControlA.js is marked as an embedded resource. In the AssemblyInfo.cs I include the following:</p>
<pre><code>[assembly: System.Web.UI.WebResource("Company.WebControls.ControlA.js", "application/x-javascript")]
</code></pre>
<p>After this is merged into CompanyA.dll, what is the proper way to reference this web resource? The ILMerge command line is as follows (from the bin directory after the build): <code>"C:\Program Files\Microsoft\ILMerge\ILMerge.exe" /keyfile:../../CompanySK.snk /wildcards:True /copyattrs:True /out:Company.dll Company.*.dll</code></p>
| [
{
"answer_id": 20380,
"author": "John Hoven",
"author_id": 1907,
"author_profile": "https://Stackoverflow.com/users/1907",
"pm_score": 3,
"selected": true,
"text": "<p>OK - I got this working. It looks like the primary assembly was the only one whose assembly attributes were being copied. With copyattrs set, the last one in would win, not a merge (as far as I can tell). I created a dummy project to reference the other DLL's and included all the web resources from those projects in the dummy assembly info - now multiple resources from multiple projects are all loading correctly.</p>\n\n<p>Final post-build command line for dummy project:\n\"C:\\Program Files\\Microsoft\\ILMerge\\ILMerge.exe\" /keyfile:../../Company.snk /wildcards:True /out:Company.dll Company.Merge.dll Company.*.dll</p>\n"
},
{
"answer_id": 15519452,
"author": "Genady Sergeev",
"author_id": 122199,
"author_profile": "https://Stackoverflow.com/users/122199",
"pm_score": 0,
"selected": false,
"text": "<p>You need to set /allowMultiple along with /copyattrs. It is only then that ILMerge will merge the embedded resources from all assemblies.</p>\n"
}
] | 2008/08/21 | [
"https://Stackoverflow.com/questions/20249",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1907/"
] | We're attemtping to merge our DLL's into one for deployment, thus ILMerge. Almost everything seems to work great. We have a couple web controls that use `ClientScript.RegisterClientScriptResource` and these are 404-ing after the merge (These worked before the merge).
For example one of our controls would look like
```
namespace Company.WebControls
{
public class ControlA: CompositeControl, INamingContainer
{
protected override void OnPreRender(EventArgs e)
{
base.OnPreRender(e);
this.Page.ClientScript.RegisterClientScriptResource(typeof(ControlA), "Company.WebControls.ControlA.js");
}
}
}
```
It would be located in Project WebControls, assembly Company.WebControls. Underneath would be ControlA.cs and ControlA.js. ControlA.js is marked as an embedded resource. In the AssemblyInfo.cs I include the following:
```
[assembly: System.Web.UI.WebResource("Company.WebControls.ControlA.js", "application/x-javascript")]
```
After this is merged into CompanyA.dll, what is the proper way to reference this web resource? The ILMerge command line is as follows (from the bin directory after the build): `"C:\Program Files\Microsoft\ILMerge\ILMerge.exe" /keyfile:../../CompanySK.snk /wildcards:True /copyattrs:True /out:Company.dll Company.*.dll` | OK - I got this working. It looks like the primary assembly was the only one whose assembly attributes were being copied. With copyattrs set, the last one in would win, not a merge (as far as I can tell). I created a dummy project to reference the other DLL's and included all the web resources from those projects in the dummy assembly info - now multiple resources from multiple projects are all loading correctly.
Final post-build command line for dummy project:
"C:\Program Files\Microsoft\ILMerge\ILMerge.exe" /keyfile:../../Company.snk /wildcards:True /out:Company.dll Company.Merge.dll Company.\*.dll |
20,272 | <p>In a macro for Visual Studio 6, I wanted to run an external program, so I typed:</p>
<pre><code>shell("p4 open " + ActiveDocument.FullName)
</code></pre>
<p>Which gave me a type mismatch runtime error. What I ended up having to type was this:</p>
<pre><code>Dim wshShell
Set wshShell = CreateObject("WScript.Shell")
strResult = wshShell.Run("p4 open " + ActiveDocument.FullName)
</code></pre>
<p>What is going on here? Is that nonsense really necessary or have I missed something?</p>
| [
{
"answer_id": 20304,
"author": "Lasse V. Karlsen",
"author_id": 267,
"author_profile": "https://Stackoverflow.com/users/267",
"pm_score": 1,
"selected": false,
"text": "<p>VBScript isn't Visual Basic.</p>\n"
},
{
"answer_id": 20353,
"author": "Bryan Roth",
"author_id": 299,
"author_profile": "https://Stackoverflow.com/users/299",
"pm_score": 0,
"selected": false,
"text": "<p>Give this a try:</p>\n\n<pre><code>Shell \"p4 open\" & ActiveDocument.FullName\n</code></pre>\n"
},
{
"answer_id": 29042,
"author": "Michael Pryor",
"author_id": 245,
"author_profile": "https://Stackoverflow.com/users/245",
"pm_score": 2,
"selected": true,
"text": "<p>As <a href=\"https://stackoverflow.com/questions/20272/why-doesnt-shell-work-in-vbscript-in-vs6#20304\">lassevk</a> pointed out, VBScript is not Visual Basic.</p>\n\n<p>I believe the only built in object in VBScript is the WScript object.</p>\n\n<pre><code>WScript.Echo \"Hello, World!\"\n</code></pre>\n\n<p>From the docs</p>\n\n<blockquote>\n <p>The WScript object is the root object of the Windows Script Host\n object model hierarchy. It never needs to be instantiated before invoking its\n properties and methods, and it is always available from any script file.</p>\n</blockquote>\n\n<p>Everything else must be created via the CreateObject call. Some of those objects are <a href=\"http://msdn.microsoft.com/en-us/library/f51wc7hz(VS.85).aspx\" rel=\"nofollow noreferrer\">listed here</a>.</p>\n\n<p>The Shell object is one of the <em>other</em> objects that you need to create if you want to call methods on it.</p>\n\n<p>One caveat, is that RegExp is <em>sort of</em> built in, in that you can instantiate a RegExp object like so in VBScript:</p>\n\n<pre><code>Dim r as New RegExp\n</code></pre>\n"
},
{
"answer_id": 29096,
"author": "Joel Coehoorn",
"author_id": 3043,
"author_profile": "https://Stackoverflow.com/users/3043",
"pm_score": -1,
"selected": false,
"text": "<p>VB6 uses & to concatenate strings rather than +, and you'll want to make sure the file name is encased in quotes in case of spaces. Try it like this: </p>\n\n<pre><code>Shell \"p4 open \"\"\" & ActiveDocument.FullName & \"\"\"\"\n</code></pre>\n"
}
] | 2008/08/21 | [
"https://Stackoverflow.com/questions/20272",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1105/"
] | In a macro for Visual Studio 6, I wanted to run an external program, so I typed:
```
shell("p4 open " + ActiveDocument.FullName)
```
Which gave me a type mismatch runtime error. What I ended up having to type was this:
```
Dim wshShell
Set wshShell = CreateObject("WScript.Shell")
strResult = wshShell.Run("p4 open " + ActiveDocument.FullName)
```
What is going on here? Is that nonsense really necessary or have I missed something? | As [lassevk](https://stackoverflow.com/questions/20272/why-doesnt-shell-work-in-vbscript-in-vs6#20304) pointed out, VBScript is not Visual Basic.
I believe the only built in object in VBScript is the WScript object.
```
WScript.Echo "Hello, World!"
```
From the docs
>
> The WScript object is the root object of the Windows Script Host
> object model hierarchy. It never needs to be instantiated before invoking its
> properties and methods, and it is always available from any script file.
>
>
>
Everything else must be created via the CreateObject call. Some of those objects are [listed here](http://msdn.microsoft.com/en-us/library/f51wc7hz(VS.85).aspx).
The Shell object is one of the *other* objects that you need to create if you want to call methods on it.
One caveat, is that RegExp is *sort of* built in, in that you can instantiate a RegExp object like so in VBScript:
```
Dim r as New RegExp
``` |
20,298 | <p>I have something like this:</p>
<pre>
barProgress.BeginAnimation(RangeBase.ValueProperty, new DoubleAnimation(
barProgress.Value, dNextProgressValue,
new Duration(TimeSpan.FromSeconds(dDuration)));
</pre>
<p>Now, how would you stop that animation (the <code>DoubleAnimation</code>)? The reason I want to do this, is because I would like to start new animations (this seems to work, but it's hard to tell) and eventually stop the last animation...</p>
| [
{
"answer_id": 20306,
"author": "TheSmurf",
"author_id": 1975282,
"author_profile": "https://Stackoverflow.com/users/1975282",
"pm_score": 8,
"selected": true,
"text": "<p>To stop it, call <code>BeginAnimation</code> again with the second argument set to <code>null</code>.</p>\n"
},
{
"answer_id": 20560,
"author": "Brian Leahy",
"author_id": 580,
"author_profile": "https://Stackoverflow.com/users/580",
"pm_score": 2,
"selected": false,
"text": "<p>Place the animation in a StoryBoard. Call Begin() and Stop() on the storyboard to start to stop the animations.</p>\n"
},
{
"answer_id": 36744,
"author": "user3837",
"author_id": 3837,
"author_profile": "https://Stackoverflow.com/users/3837",
"pm_score": 5,
"selected": false,
"text": "<p>When using storyboards to control an animation, make sure you set the second parameter to true in order to set the animation as controllable:</p>\n\n<pre><code>public void Begin(\n FrameworkContentElement containingObject,\n **bool isControllable**\n)\n</code></pre>\n"
},
{
"answer_id": 375105,
"author": "Nick",
"author_id": 44741,
"author_profile": "https://Stackoverflow.com/users/44741",
"pm_score": 3,
"selected": false,
"text": "<blockquote>\n <p>If you want the base value to become\n the effective value again, you must\n stop the animation from influencing\n the property. There are three ways to\n do this with storyboard animations:</p>\n \n <ul>\n <li>Set the animation's FillBehavior\n property to Stop</li>\n <li>Remove the entire Storyboard</li>\n <li>Remove the animation from the\n individual property</li>\n </ul>\n</blockquote>\n\n<p>From MSDN</p>\n\n<p><a href=\"http://msdn.microsoft.com/en-us/library/aa970493.aspx\" rel=\"noreferrer\">How to: Set a Property After Animating It with a Storyboard</a></p>\n"
},
{
"answer_id": 1071741,
"author": "Junior Mayhé",
"author_id": 66708,
"author_profile": "https://Stackoverflow.com/users/66708",
"pm_score": 3,
"selected": false,
"text": "<p>In my case I had to use two commands, my xaml has a button which fires a trigger, and its trigger fires the storyboard animation.</p>\n\n<p>I've put a button to stop animation with this code behind:</p>\n\n<pre><code>MyBeginStoryboard.Storyboard.Begin(this, true);\nMyBeginStoryboard.Storyboard.Stop(this);\n</code></pre>\n\n<p>I don't like it but it really works here. Give it a try!</p>\n"
},
{
"answer_id": 9436145,
"author": "BruceLH",
"author_id": 1231415,
"author_profile": "https://Stackoverflow.com/users/1231415",
"pm_score": 4,
"selected": false,
"text": "<p>There are two ways to stop a BeginAnimation. The first is to call BeginAnimation again with the second parameter set to null. This will remove all animations on the property and <strong>revert</strong> the value back to its base value.</p>\n\n<p>Depending on how you are using that value this may not be the behavior you want. The second way is to set the animations BeginTime to null then call BeginAnimation with it. This will remove that specific animation and leave the value at its current position.</p>\n\n<pre><code>DoubleAnimation myAnimation = new Animation();\n// Initialize animation\n...\n\n// To start\nelement.BeginAnimation(Property, myAnimation);\n\n// To stop and keep the current value of the animated property\nmyAnimation.BeginTime = null;\nelement.BeginAnimation(Property, myAnimation);\n</code></pre>\n"
},
{
"answer_id": 18101726,
"author": "oliver",
"author_id": 1145234,
"author_profile": "https://Stackoverflow.com/users/1145234",
"pm_score": 0,
"selected": false,
"text": "<p>You can use this code:</p>\n\n<pre><code>[StoryBoardName].Remove([StoryBoardOwnerControl]);\n</code></pre>\n"
},
{
"answer_id": 33472902,
"author": "Fawaz",
"author_id": 4998659,
"author_profile": "https://Stackoverflow.com/users/4998659",
"pm_score": 4,
"selected": false,
"text": "<pre><code><Trigger.EnterActions>\n <BeginStoryboard x:Name=\"myStory\">\n .........\n </BeginStoryboard>\n</Trigger.EnterActions>\n<Trigger.ExitActions>\n <StopStoryboard BeginStoryboardName=\"myStory\"/>\n</Trigger.ExitActions>\n</code></pre>\n"
}
] | 2008/08/21 | [
"https://Stackoverflow.com/questions/20298",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2260/"
] | I have something like this:
```
barProgress.BeginAnimation(RangeBase.ValueProperty, new DoubleAnimation(
barProgress.Value, dNextProgressValue,
new Duration(TimeSpan.FromSeconds(dDuration)));
```
Now, how would you stop that animation (the `DoubleAnimation`)? The reason I want to do this, is because I would like to start new animations (this seems to work, but it's hard to tell) and eventually stop the last animation... | To stop it, call `BeginAnimation` again with the second argument set to `null`. |
20,326 | <p>I have a ASP.NET 1.1 application, and I'm trying to find out why when I change a ComboBox which value is used to fill another one (parent-child relation), two postbacks are produced.</p>
<p>I have checked and checked the code, and I can't find the cause.</p>
<p>Here are both call stacks which end in a page_load</p>
<p>First postback (generated by teh ComboBox's autopostback)</p>
<p><a href="http://www.juanformoso.com.ar/images/callstack1.jpg" rel="nofollow noreferrer">Postback call stack</a> (broken)</p>
<p>Second postback (this is what I want to find why it's happening)</p>
<p><a href="http://www.juanformoso.com.ar/images/callstack2.jpg" rel="nofollow noreferrer">alt text</a> (broken)</p>
<p>Any suggestion? What can I check?</p>
| [
{
"answer_id": 20348,
"author": "TheSmurf",
"author_id": 1975282,
"author_profile": "https://Stackoverflow.com/users/1975282",
"pm_score": 0,
"selected": false,
"text": "<p>First thing I would look for is that you don't have the second ComboBox's AutoPostBack property set to true. If you change the value in the second combo with that property set true, I believe it will generate a postback on that control.</p>\n"
},
{
"answer_id": 20479,
"author": "Jason Shoulders",
"author_id": 1953,
"author_profile": "https://Stackoverflow.com/users/1953",
"pm_score": 0,
"selected": false,
"text": "<p>Do you have any code you could share? Double post backs plagued me so much in classic ASP back in the day that it was what finally prompted me to switch to .NET once and for all. Whenever I have problems like these for .NET, I go to every CONTROL and every PAGE element like load, init, prerender, click, SelectedIndexChanged, and the like and put a breakpoint.</p>\n\n<p>Even if I don't have code there, I'll insert something like:</p>\n\n<pre><code>Dim i As Integer\ni = 0\n</code></pre>\n\n<p>I am usually able to pinpoint some action that I wasn't expecting and fix as needed. I would suggest you do that here.</p>\n\n<p>Good luck.</p>\n"
},
{
"answer_id": 20601,
"author": "Mark Brackett",
"author_id": 2199,
"author_profile": "https://Stackoverflow.com/users/2199",
"pm_score": 0,
"selected": false,
"text": "<p>Check Request.Form[\"__EVENTTARGET\"] to find the control initiating the postback - that may help you narrow it down.</p>\n\n<p>Looking at the callstacks, and some Reflectoring (into ASP.NET 2 - I don't have 1.1 handy) - it looks like SessionStateModule.PollLockedSessionCallback is part of the HttpApplication startup routines. It may be possible that your app is being recycled - I'm pretty sure an event gets written into the Event log for that.</p>\n\n<p>My only other suggestion would be Fiddler or something on the client to capture HTTP traffic.</p>\n"
},
{
"answer_id": 20649,
"author": "juan",
"author_id": 1782,
"author_profile": "https://Stackoverflow.com/users/1782",
"pm_score": 4,
"selected": true,
"text": "<p>It's a very specific problem with this code, I doubt it will be useful for someone else, but here it goes:</p>\n\n<p>A check was added to the combo's <code>onchange</code> with an if, if the condition was met, an explicit call to the postback function was made.\nIf the combo was set to <code>AutoPostback</code>, asp.net added the postback call again, producing the two postbacks...</p>\n\n<p>The generated html was like this:</p>\n\n<pre><code>[select onchange=\"javascript: if (CustomFunction()){__doPostBack('name','')}; __doPostBack('name','')\"]\n</code></pre>\n"
},
{
"answer_id": 2801589,
"author": "Ealavan",
"author_id": 337121,
"author_profile": "https://Stackoverflow.com/users/337121",
"pm_score": 0,
"selected": false,
"text": "<p>This is very old post, but people still looking at this for solution exactly same as I did last week.</p>\n\n<p>Like Grengby said Double events are primary reasons - but removing one of them is not allways an option. Atleast on my case and I had to resolve this on 3rd party's application.</p>\n\n<p>I added following script and amended ASP form on masterpage:</p>\n\n<pre><code><script>var Q = 0;</script>\n<form id=\"Form1\" runat=\"server\" onsubmit=\"Q++; if(Q==1){return true;} else { return false;}\">\n</code></pre>\n\n<p>This seems to be working and please forward your comments.</p>\n\n<p>Arun</p>\n\n<p><a href=\"http://www.velocityreviews.com/forums/t117900-asp-net-multiple-postback-issue.html\" rel=\"nofollow noreferrer\">http://www.velocityreviews.com/forums/t117900-asp-net-multiple-postback-issue.html</a></p>\n"
}
] | 2008/08/21 | [
"https://Stackoverflow.com/questions/20326",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1782/"
] | I have a ASP.NET 1.1 application, and I'm trying to find out why when I change a ComboBox which value is used to fill another one (parent-child relation), two postbacks are produced.
I have checked and checked the code, and I can't find the cause.
Here are both call stacks which end in a page\_load
First postback (generated by teh ComboBox's autopostback)
[Postback call stack](http://www.juanformoso.com.ar/images/callstack1.jpg) (broken)
Second postback (this is what I want to find why it's happening)
[alt text](http://www.juanformoso.com.ar/images/callstack2.jpg) (broken)
Any suggestion? What can I check? | It's a very specific problem with this code, I doubt it will be useful for someone else, but here it goes:
A check was added to the combo's `onchange` with an if, if the condition was met, an explicit call to the postback function was made.
If the combo was set to `AutoPostback`, asp.net added the postback call again, producing the two postbacks...
The generated html was like this:
```
[select onchange="javascript: if (CustomFunction()){__doPostBack('name','')}; __doPostBack('name','')"]
``` |
20,346 | <p>What are attributes in .NET, what are they good for, and how do I create my own attributes?</p>
| [
{
"answer_id": 20351,
"author": "TheSmurf",
"author_id": 1975282,
"author_profile": "https://Stackoverflow.com/users/1975282",
"pm_score": 3,
"selected": false,
"text": "<p>An attribute is a class that contains some bit of functionality that you can apply to objects in your code. To create one, create a class that inherits from System.Attribute.</p>\n\n<p>As for what they're good for... there are almost limitless uses for them.</p>\n\n<p><a href=\"http://www.codeproject.com/KB/cs/dotnetattributes.aspx\" rel=\"noreferrer\">http://www.codeproject.com/KB/cs/dotnetattributes.aspx</a></p>\n"
},
{
"answer_id": 20357,
"author": "Stu",
"author_id": 414,
"author_profile": "https://Stackoverflow.com/users/414",
"pm_score": 3,
"selected": false,
"text": "<p>Attributes are like metadata applied to classes, methods or assemblies.</p>\n\n<p>They are good for any number of things (debugger visualization, marking things as obsolete, marking things as serializable, the list is endless).</p>\n\n<p>Creating your own custom ones is easy as pie. Start here:</p>\n\n<p><a href=\"http://msdn.microsoft.com/en-us/library/sw480ze8(VS.71).aspx\" rel=\"noreferrer\">http://msdn.microsoft.com/en-us/library/sw480ze8(VS.71).aspx</a></p>\n"
},
{
"answer_id": 20358,
"author": "Chris Miller",
"author_id": 206,
"author_profile": "https://Stackoverflow.com/users/206",
"pm_score": 2,
"selected": false,
"text": "<p>You can use custom attributes as a simple way to define tag values in sub classes without having to write the same code over and over again for each subclass. I came across a nice <a href=\"http://blog.falafel.com/2008/04/15/CustomAttributesToTheRescue.aspx\" rel=\"nofollow noreferrer\">concise example by John Waters</a> of how to define and use custom attributes in your own code.</p>\n\n<p>There is a tutorial at <a href=\"http://msdn.microsoft.com/en-us/library/aa288454(VS.71).aspx\" rel=\"nofollow noreferrer\">http://msdn.microsoft.com/en-us/library/aa288454(VS.71).aspx</a></p>\n"
},
{
"answer_id": 20418,
"author": "Quibblesome",
"author_id": 1143,
"author_profile": "https://Stackoverflow.com/users/1143",
"pm_score": 8,
"selected": true,
"text": "<p>Metadata. Data about your objects/methods/properties. </p>\n\n<p>For example I might declare an Attribute called: DisplayOrder so I can easily control in what order properties should appear in the UI. I could then append it to a class and write some GUI components that extract the attributes and order the UI elements appropriately.</p>\n\n<pre><code>public class DisplayWrapper\n{\n private UnderlyingClass underlyingObject;\n\n public DisplayWrapper(UnderlyingClass u)\n {\n underlyingObject = u;\n }\n\n [DisplayOrder(1)]\n public int SomeInt\n {\n get\n {\n return underlyingObject .SomeInt;\n }\n }\n\n [DisplayOrder(2)]\n public DateTime SomeDate\n {\n get\n {\n return underlyingObject .SomeDate;\n }\n }\n}\n</code></pre>\n\n<p>Thereby ensuring that SomeInt is always displayed before SomeDate when working with my custom GUI components.</p>\n\n<p>However, you'll see them most commonly used outside of the direct coding environment. For example the Windows Designer uses them extensively so it knows how to deal with custom made objects. Using the BrowsableAttribute like so:</p>\n\n<pre><code>[Browsable(false)]\npublic SomeCustomType DontShowThisInTheDesigner\n{\n get{/*do something*/}\n}\n</code></pre>\n\n<p>Tells the designer not to list this in the available properties in the Properties window at design time for example.</p>\n\n<p>You <em>could</em> also use them for code-generation, pre-compile operations (such as Post-Sharp) or run-time operations such as Reflection.Emit.\nFor example, you could write a bit of code for profiling that transparently wrapped every single call your code makes and times it. You could \"opt-out\" of the timing via an attribute that you place on particular methods.</p>\n\n<pre><code>public void SomeProfilingMethod(MethodInfo targetMethod, object target, params object[] args)\n{\n bool time = true;\n foreach (Attribute a in target.GetCustomAttributes())\n {\n if (a.GetType() is NoTimingAttribute)\n {\n time = false;\n break;\n }\n }\n if (time)\n {\n StopWatch stopWatch = new StopWatch();\n stopWatch.Start();\n targetMethod.Invoke(target, args);\n stopWatch.Stop();\n HandleTimingOutput(targetMethod, stopWatch.Duration);\n }\n else\n {\n targetMethod.Invoke(target, args);\n }\n}\n</code></pre>\n\n<p>Declaring them is easy, just make a class that inherits from Attribute. </p>\n\n<pre><code>public class DisplayOrderAttribute : Attribute\n{\n private int order;\n\n public DisplayOrderAttribute(int order)\n {\n this.order = order;\n }\n\n public int Order\n {\n get { return order; }\n }\n}\n</code></pre>\n\n<p>And remember that when you use the attribute you can omit the suffix \"attribute\" the compiler will add that for you.</p>\n\n<p><strong>NOTE:</strong> Attributes don't do anything by themselves - there needs to be some other code that uses them. Sometimes that code has been written for you but sometimes you have to write it yourself. For example, the C# compiler cares about some and certain frameworks frameworks use some (e.g. NUnit looks for [TestFixture] on a class and [Test] on a test method when loading an assembly).<br>\nSo when creating your own custom attribute be aware that it will not impact the behaviour of your code at all. You'll need to write the other part that checks attributes (via reflection) and act on them. </p>\n"
},
{
"answer_id": 20455,
"author": "Patrik Svensson",
"author_id": 936,
"author_profile": "https://Stackoverflow.com/users/936",
"pm_score": 4,
"selected": false,
"text": "<p>Attributes are a kind of meta data for tagging classes. This is often used in WinForms for example to hide controls from the toolbar, but can be implemented in your own application to enable instances of different classes to behave in specific ways. </p>\n\n<p>Start by creating an attribute:</p>\n\n<pre><code>[AttributeUsage(AttributeTargets.Class, AllowMultiple=false, Inherited=true)]\npublic class SortOrderAttribute : Attribute\n{\n public int SortOrder { get; set; }\n\n public SortOrderAttribute(int sortOrder)\n {\n this.SortOrder = sortOrder;\n }\n}\n</code></pre>\n\n<p>All attribute classes must have the suffix \"Attribute\" to be valid.<br>\nAfter this is done, create a class that uses the attribute.</p>\n\n<pre><code>[SortOrder(23)]\npublic class MyClass\n{\n public MyClass()\n {\n }\n}\n</code></pre>\n\n<p>Now you can check a specific class' <code>SortOrderAttribute</code> (if it has one) by doing the following:</p>\n\n<pre><code>public class MyInvestigatorClass\n{\n public void InvestigateTheAttribute()\n {\n // Get the type object for the class that is using\n // the attribute.\n Type type = typeof(MyClass);\n\n // Get all custom attributes for the type.\n object[] attributes = type.GetCustomAttributes(\n typeof(SortOrderAttribute), true);\n\n // Now let's make sure that we got at least one attribute.\n if (attributes != null && attributes.Length > 0)\n {\n // Get the first attribute in the list of custom attributes\n // that is of the type \"SortOrderAttribute\". This should only\n // be one since we said \"AllowMultiple=false\".\n SortOrderAttribute attribute = \n attributes[0] as SortOrderAttribute;\n\n // Now we can get the sort order for the class \"MyClass\".\n int sortOrder = attribute.SortOrder;\n }\n }\n}\n</code></pre>\n\n<p>If you want to read more about this you can always check out <a href=\"http://msdn.microsoft.com/en-us/library/aa288059.aspx\" rel=\"nofollow noreferrer\">MSDN</a> which has a pretty good description.<br>\nI hope this helped you out!</p>\n"
},
{
"answer_id": 20482,
"author": "denis phillips",
"author_id": 748,
"author_profile": "https://Stackoverflow.com/users/748",
"pm_score": 2,
"selected": false,
"text": "<p>As said, Attributes are relatively easy to create. The other part of the work is creating code that uses it. In most cases you will use reflection at runtime to alter behavior based on the presence of an attribute or its properties. There are also scenarios where you will inspect attributes on compiled code to do some sort of static analysis. For example, parameters might be marked as non-null and the analysis tool can use this as a hint.</p>\n\n<p>Using the attributes and knowing the appropriate scenarios for their use is the bulk of the work.</p>\n"
},
{
"answer_id": 20508,
"author": "Skizz",
"author_id": 1898,
"author_profile": "https://Stackoverflow.com/users/1898",
"pm_score": 3,
"selected": false,
"text": "<p>In the project I'm currently working on, there is a set of UI objects of various flavours and an editor to assembly these objects to create pages for use in the main application, a bit like the form designer in DevStudio. These objects exist in their own assembly and each object is a class derived from <code>UserControl</code> and has a custom attribute. This attribute is defined like this:</p>\n\n<pre><code>[AttributeUsage (AttributeTargets::Class)]\npublic ref class ControlDescriptionAttribute : Attribute\n{\npublic:\n ControlDescriptionAttribute (String ^name, String ^description) :\n _name (name),\n _description (description)\n {\n }\n\n property String ^Name\n {\n String ^get () { return _name; }\n }\n\n property String ^Description\n {\n String ^get () { return _description; }\n }\n\nprivate:\n String\n ^ _name,\n ^ _description;\n};\n</code></pre>\n\n<p>and I apply it to a class like this:</p>\n\n<pre><code>[ControlDescription (\"Pie Chart\", \"Displays a pie chart\")]\npublic ref class PieControl sealed : UserControl\n{\n // stuff\n};\n</code></pre>\n\n<p>which is what the previous posters have said.</p>\n\n<p>To use the attribute, the editor has a <code>Generic::List <Type></code> containing the control types. There is a list box which the user can drag from and drop onto the page to create an instance of the control. To populate the list box, I get the <code>ControlDescriptionAttribute</code> for the control and fill out an entry in the list:</p>\n\n<pre><code>// done for each control type\narray <Object ^>\n // get all the custom attributes\n ^attributes = controltype->GetCustomAttributes (true);\n\nType\n // this is the one we're interested in\n ^attributetype = ECMMainPageDisplay::ControlDescriptionAttribute::typeid;\n\n// iterate over the custom attributes\nfor each (Object ^attribute in attributes)\n{\n if (attributetype->IsInstanceOfType (attribute))\n {\n ECMMainPageDisplay::ControlDescriptionAttribute\n ^description = safe_cast <ECMMainPageDisplay::ControlDescriptionAttribute ^> (attribute);\n\n // get the name and description and create an entry in the list\n ListViewItem\n ^item = gcnew ListViewItem (description->Name);\n\n item->Tag = controltype->Name;\n item->SubItems->Add (description->Description);\n\n mcontrols->Items->Add (item);\n break;\n }\n}\n</code></pre>\n\n<p>Note: the above is C++/CLI but it's not difficult to convert to C#\n(yeah, I know, C++/CLI is an abomination but it's what I have to work with :-( )</p>\n\n<p>You can put attributes on most things and there are whole range of predefined attributes. The editor mentioned above also looks for custom attributes on properties that describe the property and how to edit it.</p>\n\n<p>Once you get the whole idea, you'll wonder how you ever lived without them.</p>\n"
},
{
"answer_id": 20665,
"author": "urini",
"author_id": 373,
"author_profile": "https://Stackoverflow.com/users/373",
"pm_score": 2,
"selected": false,
"text": "<p>Attributes are, essentially, bits of data you want to attach to your <strong>types</strong> (classes, methods, events, enums, etc.)</p>\n\n<p>The idea is that at run time some other type/framework/tool will query <strong>your</strong> type for the information in the attribute and act upon it.</p>\n\n<p>So, for example, Visual Studio can query the attributes on a 3rd party control to figure out which properties of the control should appear in the Properties pane at design time.</p>\n\n<p>Attributes can also be used in Aspect Oriented Programming to inject/manipulate objects at run time based on the attributes that decorate them and add validation, logging, etc. to the objects without affecting the business logic of the object.</p>\n"
},
{
"answer_id": 394559,
"author": "Jay Bazuzi",
"author_id": 5314,
"author_profile": "https://Stackoverflow.com/users/5314",
"pm_score": 2,
"selected": false,
"text": "<p>To get started creating an attribute, open a C# source file, type <code>attribute</code> and hit [TAB]. It will expand to a template for a new attribute.</p>\n"
},
{
"answer_id": 554006,
"author": "Drew Noakes",
"author_id": 24874,
"author_profile": "https://Stackoverflow.com/users/24874",
"pm_score": 5,
"selected": false,
"text": "<p>Many people have answered but no one has mentioned this so far...</p>\n\n<p>Attributes are used heavily with reflection. Reflection is already pretty slow.</p>\n\n<p>It is <em>very worthwhile</em> marking your custom attributes as being <code>sealed</code> classes to improve their runtime performance.</p>\n\n<p>It is also a good idea to consider where it would be appropriate to use place such an attribute, and to attribute your attribute (!) to indicate this via <a href=\"http://msdn.microsoft.com/en-us/library/system.attributeusageattribute.aspx\" rel=\"noreferrer\"><code>AttributeUsage</code></a>. The list of available attribute usages might surprise you:</p>\n\n<ul>\n<li>Assembly</li>\n<li>Module</li>\n<li>Class</li>\n<li>Struct</li>\n<li>Enum</li>\n<li>Constructor</li>\n<li>Method</li>\n<li>Property</li>\n<li>Field</li>\n<li>Event</li>\n<li>Interface</li>\n<li>Parameter</li>\n<li>Delegate </li>\n<li>ReturnValue</li>\n<li>GenericParameter</li>\n<li>All</li>\n</ul>\n\n<p>It's also cool that the AttributeUsage attribute is part of the AttributeUsage attribute's signature. Whoa for circular dependencies!</p>\n\n<pre><code>[AttributeUsageAttribute(AttributeTargets.Class, Inherited = true)]\npublic sealed class AttributeUsageAttribute : Attribute\n</code></pre>\n"
},
{
"answer_id": 1603356,
"author": "Josh G",
"author_id": 64329,
"author_profile": "https://Stackoverflow.com/users/64329",
"pm_score": 1,
"selected": false,
"text": "<p>Attributes are also commonly used for Aspect Oriented Programming. For an example of this check out the <a href=\"http://www.postsharp.org\" rel=\"nofollow noreferrer\">PostSharp</a> project.</p>\n"
}
] | 2008/08/21 | [
"https://Stackoverflow.com/questions/20346",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1595/"
] | What are attributes in .NET, what are they good for, and how do I create my own attributes? | Metadata. Data about your objects/methods/properties.
For example I might declare an Attribute called: DisplayOrder so I can easily control in what order properties should appear in the UI. I could then append it to a class and write some GUI components that extract the attributes and order the UI elements appropriately.
```
public class DisplayWrapper
{
private UnderlyingClass underlyingObject;
public DisplayWrapper(UnderlyingClass u)
{
underlyingObject = u;
}
[DisplayOrder(1)]
public int SomeInt
{
get
{
return underlyingObject .SomeInt;
}
}
[DisplayOrder(2)]
public DateTime SomeDate
{
get
{
return underlyingObject .SomeDate;
}
}
}
```
Thereby ensuring that SomeInt is always displayed before SomeDate when working with my custom GUI components.
However, you'll see them most commonly used outside of the direct coding environment. For example the Windows Designer uses them extensively so it knows how to deal with custom made objects. Using the BrowsableAttribute like so:
```
[Browsable(false)]
public SomeCustomType DontShowThisInTheDesigner
{
get{/*do something*/}
}
```
Tells the designer not to list this in the available properties in the Properties window at design time for example.
You *could* also use them for code-generation, pre-compile operations (such as Post-Sharp) or run-time operations such as Reflection.Emit.
For example, you could write a bit of code for profiling that transparently wrapped every single call your code makes and times it. You could "opt-out" of the timing via an attribute that you place on particular methods.
```
public void SomeProfilingMethod(MethodInfo targetMethod, object target, params object[] args)
{
bool time = true;
foreach (Attribute a in target.GetCustomAttributes())
{
if (a.GetType() is NoTimingAttribute)
{
time = false;
break;
}
}
if (time)
{
StopWatch stopWatch = new StopWatch();
stopWatch.Start();
targetMethod.Invoke(target, args);
stopWatch.Stop();
HandleTimingOutput(targetMethod, stopWatch.Duration);
}
else
{
targetMethod.Invoke(target, args);
}
}
```
Declaring them is easy, just make a class that inherits from Attribute.
```
public class DisplayOrderAttribute : Attribute
{
private int order;
public DisplayOrderAttribute(int order)
{
this.order = order;
}
public int Order
{
get { return order; }
}
}
```
And remember that when you use the attribute you can omit the suffix "attribute" the compiler will add that for you.
**NOTE:** Attributes don't do anything by themselves - there needs to be some other code that uses them. Sometimes that code has been written for you but sometimes you have to write it yourself. For example, the C# compiler cares about some and certain frameworks frameworks use some (e.g. NUnit looks for [TestFixture] on a class and [Test] on a test method when loading an assembly).
So when creating your own custom attribute be aware that it will not impact the behaviour of your code at all. You'll need to write the other part that checks attributes (via reflection) and act on them. |
20,386 | <p>What are all the possible ways in which we can get memory leaks in .NET?</p>
<p>I know of two:</p>
<ol>
<li>Not properly un-registering <a href="http://diditwith.net/PermaLink,guid,fcf59145-3973-468a-ae66-aaa8df9161c7.aspx" rel="nofollow noreferrer">Event Handlers/Delegates</a>.</li>
<li>Not disposing dynamic child controls in Windows Forms:</li>
</ol>
<p>Example:</p>
<pre><code>// Causes Leaks
Label label = new Label();
this.Controls.Add(label);
this.Controls.Remove(label);
// Correct Code
Label label = new Label();
this.Controls.Add(label);
this.Controls.Remove(label);
label.Dispose();
</code></pre>
<p><strong>Update</strong>: The idea is to list common pitfalls which are not too obvious (such as the above). Usually the notion is that memory leaks are not a big problem because of the garbage collector. Not like it used to be in C++.</p>
<hr>
<p>Great discussion guys, but let me clarify... by definition, if there is no reference left to an object in .NET, it will be Garbage Collected at some time. So that is not a way to induce memory leaks.</p>
<p>In the managed environment, I would consider it a memory leak if you had an unintended reference to any object that you aren't aware of (hence the two examples in my question).</p>
<p><strong>So, what are the various possible ways in which such a memory leak can happen?</strong></p>
| [
{
"answer_id": 20393,
"author": "Greg Hurlman",
"author_id": 35,
"author_profile": "https://Stackoverflow.com/users/35",
"pm_score": 4,
"selected": false,
"text": "<p>There's no way to provide a comprehensive list... this is very much like asking \"How can you get wet?\"</p>\n\n<p>That said, make sure you're calling Dispose() on everything that implements IDisposable, and make sure you implement IDisposable on any types that consume unmanaged resources of any kind.</p>\n\n<p>Every now and then, run something like FxCop on your codebase to help you enforce that rule - you'd be surprised how deep some disposable objects get buried within an application framework.</p>\n"
},
{
"answer_id": 20416,
"author": "Mat Noguchi",
"author_id": 1799,
"author_profile": "https://Stackoverflow.com/users/1799",
"pm_score": 2,
"selected": false,
"text": "<p>Are you talking about unexpected memory usage or actual leaks? The two cases you listed aren't exactly leaks; they are cases where objects stick around longer than intended.</p>\n\n<p>In other words, they are references the person who calls them memory leaks didn't know or forgot about.</p>\n\n<p>Edit: Or they are actual bugs in the garbage collector or non-managed code.</p>\n\n<p>Edit 2: Another way to think about this is to always make sure external references to your objects get released appropriately. External means code outside of your control. Any case where that happens is a case where you can \"leak\" memory.</p>\n"
},
{
"answer_id": 20419,
"author": "Derek Park",
"author_id": 872,
"author_profile": "https://Stackoverflow.com/users/872",
"pm_score": 0,
"selected": false,
"text": "<p>A lot of the things that can cause memory leaks in unmanaged languages can still cause memory leaks in managed languages. For example, <a href=\"http://blogs.msdn.com/oldnewthing/archive/2006/05/02/588350.aspx\" rel=\"nofollow noreferrer\">bad caching policies</a> can result in memory leaks.</p>\n\n<p>But as Greg and Danny have said, there is no comprehensive list. Anything that can result in holding memory after its useful lifetime can cause a leak.</p>\n"
},
{
"answer_id": 20423,
"author": "Rex M",
"author_id": 67,
"author_profile": "https://Stackoverflow.com/users/67",
"pm_score": 2,
"selected": false,
"text": "<p>Calling IDisposable every time is the easiest place to start, and definitely an effective way to grab all the low-hanging memory leak fruit in the codebase. However, it is not always enough. For example, it's also important to understand how and when managed code is generated at runtime, and that once assemblies are loaded into the application domain, they are never unloaded, which can increase the application footprint.</p>\n"
},
{
"answer_id": 20431,
"author": "Keith",
"author_id": 905,
"author_profile": "https://Stackoverflow.com/users/905",
"pm_score": 4,
"selected": false,
"text": "<p>That doesn't really cause leaks, it just makes more work for the GC:</p>\n\n<pre><code>// slows GC\nLabel label = new Label(); \nthis.Controls.Add(label); \nthis.Controls.Remove(label); \n\n// better \nLabel label = new Label(); \nthis.Controls.Add(label); \nthis.Controls.Remove(label); \nlabel.Dispose();\n\n// best\nusing( Label label = new Label() )\n{ \n this.Controls.Add(label); \n this.Controls.Remove(label); \n}\n</code></pre>\n\n<p>Leaving disposable components lying around like this is never much of a problem in a managed environment like .Net - that's a big part of what managed means.</p>\n\n<p>You'll slow you app down, certainly. But you won't leave a mess for anything else.</p>\n"
},
{
"answer_id": 20469,
"author": "Quibblesome",
"author_id": 1143,
"author_profile": "https://Stackoverflow.com/users/1143",
"pm_score": 2,
"selected": false,
"text": "<p>Exceptions in Finalise (or Dispose calls from a Finaliser) methods that prevent unmanaged resources from being correctly disposed.\nA common one is due to the programmer <em>assuming</em> what order objects will be disposed and trying to release peer objects that have already been disposed resulting in an exception and the rest of the Finalise/Dispose from Finalise method not being called.</p>\n"
},
{
"answer_id": 24079,
"author": "Leon Bambrick",
"author_id": 49,
"author_profile": "https://Stackoverflow.com/users/49",
"pm_score": 4,
"selected": true,
"text": "<p>Block the finalizer thread. No other objects will be garbage collected until the finalizer thread is unblocked. Thus the amount of memory used will grow and grow.</p>\n\n<p>Further reading: <a href=\"http://dotnetdebug.net/2005/06/22/blocked-finalizer-thread/\" rel=\"nofollow noreferrer\">http://dotnetdebug.net/2005/06/22/blocked-finalizer-thread/</a></p>\n"
},
{
"answer_id": 318679,
"author": "Brian Rasmussen",
"author_id": 38206,
"author_profile": "https://Stackoverflow.com/users/38206",
"pm_score": 0,
"selected": false,
"text": "<p>Deadlocked threads will never release roots. Obviously you could argue that the deadlock presents a bigger problem. </p>\n\n<p>A deadlocked finalizer thread will prevent all remaining finalizers to run and thus prevent all finalizable objects from being reclaimed (as they are still being rooted by the freachable list).</p>\n\n<p>On a multi CPU machine you could create finalizable objects faster than the finalizer thread could run finalizers. As long as that is sustained you will \"leak\" memory. It is probably not very likely that this will happen in the wild, but it is easy to reproduce. </p>\n\n<p>The large object heap is not compacted, so you could leak memory through fragmentation.</p>\n\n<p>There are a number of objects which must be freed manually. E.g. remoting objects with no lease and assemblies (must unload AppDomain).</p>\n"
},
{
"answer_id": 318744,
"author": "Scott Langham",
"author_id": 11898,
"author_profile": "https://Stackoverflow.com/users/11898",
"pm_score": 4,
"selected": false,
"text": "<p>Setting the <strong>GridControl.DataSource</strong> property directly without using an instance of the BindingSource class (<a href=\"http://msdn.microsoft.com/en-us/library/system.windows.forms.bindingsource.aspx\" rel=\"noreferrer\">http://msdn.microsoft.com/en-us/library/system.windows.forms.bindingsource.aspx</a>).</p>\n\n<p>This caused leaks in my application that took me quite a while to track down with a profiler, eventually I found this bug report that Microsoft responded to: <a href=\"http://connect.microsoft.com/VisualStudio/feedback/ViewFeedback.aspx?FeedbackID=92260\" rel=\"noreferrer\">http://connect.microsoft.com/VisualStudio/feedback/ViewFeedback.aspx?FeedbackID=92260</a></p>\n\n<p>It's funny that in the documentation for the BindingSource class Microsoft try to pass it off as a legitmate well thought out class, but I think they just created it to solve a fundamental leak regarding currency managers and binding data to grid controls.</p>\n\n<p>Watch out for this one, I bet there are absolutely loads of leaky applications out there because of this!</p>\n"
},
{
"answer_id": 1726553,
"author": "Steve Townsend",
"author_id": 210102,
"author_profile": "https://Stackoverflow.com/users/210102",
"pm_score": 1,
"selected": false,
"text": "<ol start=\"3\">\n<li>Keeping around references to objects that you no longer need.</li>\n</ol>\n\n<p>Re other comments - one way to ensure Dispose gets called is to use using... when code structure allows it.</p>\n"
},
{
"answer_id": 3121169,
"author": "John Hansen",
"author_id": 368423,
"author_profile": "https://Stackoverflow.com/users/368423",
"pm_score": 2,
"selected": false,
"text": "<p>To prevent .NET memory leaks:</p>\n\n<p>1) Employ the 'using' construct (or 'try-finally construct) whenever an object with 'IDisposable' interface is created.</p>\n\n<p>2) Make classes 'IDisposable' if they create a thread or they add an object to a static or long lived collection. Remember a C# 'event' is a collection.</p>\n\n<p>Here is a short article on <a href=\"http://yourdotnetdesignteam.blogspot.com/2010/06/tips-to-prevent-net-memory-leaks.html\" rel=\"nofollow noreferrer\">Tips to Prevent Memory Leaks</a>.</p>\n"
},
{
"answer_id": 3121231,
"author": "Niki",
"author_id": 70915,
"author_profile": "https://Stackoverflow.com/users/70915",
"pm_score": 1,
"selected": false,
"text": "<p>One thing that was really unexpected for me is this:</p>\n\n<pre><code>Region oldClip = graphics.Clip;\nusing (Region newClip = new Region(...))\n{\n graphics.Clip = newClip;\n // draw something\n graphics.Clip = oldClip;\n}\n</code></pre>\n\n<p>Where's the memory leak? Right, you should have disposed <code>oldClip</code>, too! Because <code>Graphics.Clip</code> is one of the rare properties that returns a new disposable object every time the getter is invoked.</p>\n"
},
{
"answer_id": 3346674,
"author": "user207331",
"author_id": 207331,
"author_profile": "https://Stackoverflow.com/users/207331",
"pm_score": 2,
"selected": false,
"text": "<p>I have 4 additional items to add to this discussion:</p>\n\n<ol>\n<li><p>Terminating threads (Thread.Abort()) that have created UI Controls without properly preparing for such an event may lead to memory being used expectantly. </p></li>\n<li><p>Accessing unmanaged resources through Pinvoke and not cleaning them up may lead to memory leaks.</p></li>\n<li><p>Modifying large string objects. Not necessarily a memory leak, once out of scope, GC will take care of it, however, performance wise, your system may take a hit if large strings are modified often because you can not really depend on GC to ensure your program's foot print is minimal.</p></li>\n<li><p>Creating GDI objects often to perform custom drawing. If performing GDI work often, reuse a single gdi object.</p></li>\n</ol>\n"
},
{
"answer_id": 3353461,
"author": "Valera Kolupaev",
"author_id": 29300,
"author_profile": "https://Stackoverflow.com/users/29300",
"pm_score": 1,
"selected": false,
"text": "<p>Tess Fernandez Has great blog posts about finding and debugging memory leaks.\n<a href=\"http://blogs.msdn.com/b/tess/archive/2008/03/17/net-debugging-demos-lab-6-memory-leak-review.aspx\" rel=\"nofollow noreferrer\">Lab 6</a> <a href=\"http://blogs.msdn.com/b/tess/archive/2008/04/03/net-debugging-demos-lab-7-memory-leak-review.aspx\" rel=\"nofollow noreferrer\">Lab 7</a></p>\n"
}
] | 2008/08/21 | [
"https://Stackoverflow.com/questions/20386",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/380/"
] | What are all the possible ways in which we can get memory leaks in .NET?
I know of two:
1. Not properly un-registering [Event Handlers/Delegates](http://diditwith.net/PermaLink,guid,fcf59145-3973-468a-ae66-aaa8df9161c7.aspx).
2. Not disposing dynamic child controls in Windows Forms:
Example:
```
// Causes Leaks
Label label = new Label();
this.Controls.Add(label);
this.Controls.Remove(label);
// Correct Code
Label label = new Label();
this.Controls.Add(label);
this.Controls.Remove(label);
label.Dispose();
```
**Update**: The idea is to list common pitfalls which are not too obvious (such as the above). Usually the notion is that memory leaks are not a big problem because of the garbage collector. Not like it used to be in C++.
---
Great discussion guys, but let me clarify... by definition, if there is no reference left to an object in .NET, it will be Garbage Collected at some time. So that is not a way to induce memory leaks.
In the managed environment, I would consider it a memory leak if you had an unintended reference to any object that you aren't aware of (hence the two examples in my question).
**So, what are the various possible ways in which such a memory leak can happen?** | Block the finalizer thread. No other objects will be garbage collected until the finalizer thread is unblocked. Thus the amount of memory used will grow and grow.
Further reading: <http://dotnetdebug.net/2005/06/22/blocked-finalizer-thread/> |
20,391 | <p>I have a svn repo on my machine (Windows). Anyone have a script to back it up to a network share?</p>
<p>I'm using the repo locally since I'm disconnected a lot. The network share is on a server with a backup strategy. I'm a perfect candidate for git/hg but I don't want to give up my VS integration just yet.</p>
| [
{
"answer_id": 20408,
"author": "Jedi Master Spooky",
"author_id": 1154,
"author_profile": "https://Stackoverflow.com/users/1154",
"pm_score": 2,
"selected": false,
"text": "<p>svnadmin dump C:\\SVNRepositorio\\Repositorio > \\\\Backups\\BkTmpSubversion\\subversiontemp.dump</p>\n\n<p>Try this.</p>\n"
},
{
"answer_id": 20444,
"author": "BCS",
"author_id": 1343,
"author_profile": "https://Stackoverflow.com/users/1343",
"pm_score": 2,
"selected": false,
"text": "<blockquote>\n <p>svnadmin dump C:\\SVNRepositorio\\Repositorio > \\Backups\\BkTmpSubversion\\subversiontemp.dump</p>\n</blockquote>\n\n<p>ditto Spooky's reply ^^</p>\n\n<p>On linux you might try adding \"| gzip\" in the middle</p>\n\n<p>also take a look at the --incremental & --deltas flags</p>\n\n<hr>\n\n<p>sparkes: For some values of \"My machine\" that won't be local.</p>\n\n<p>Also If you are using SVN for non commercial reasons (I have all my homework from collage checked into a SVN) you might not <em>have</em> a backup system.</p>\n"
},
{
"answer_id": 20453,
"author": "jonezy",
"author_id": 2272,
"author_profile": "https://Stackoverflow.com/users/2272",
"pm_score": 3,
"selected": true,
"text": "<p>I wrote a batch file to do this for a bunch of repos, you could just hook that batch file up to windows scheduler and run it on a schedule.</p>\n\n<pre><code>svnadmin hotcopy m:\\Source\\Q4Press\\Repo m:\\SvnOut\\Q4Press\n</code></pre>\n\n<p>I use the hotcopy but the svn dump would work just as well.</p>\n"
}
] | 2008/08/21 | [
"https://Stackoverflow.com/questions/20391",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1946/"
] | I have a svn repo on my machine (Windows). Anyone have a script to back it up to a network share?
I'm using the repo locally since I'm disconnected a lot. The network share is on a server with a backup strategy. I'm a perfect candidate for git/hg but I don't want to give up my VS integration just yet. | I wrote a batch file to do this for a bunch of repos, you could just hook that batch file up to windows scheduler and run it on a schedule.
```
svnadmin hotcopy m:\Source\Q4Press\Repo m:\SvnOut\Q4Press
```
I use the hotcopy but the svn dump would work just as well. |
20,426 | <p>I have a tree encoded in a MySQL database as edges:</p>
<pre><code>CREATE TABLE items (
num INT,
tot INT,
PRIMARY KEY (num)
);
CREATE TABLE tree (
orig INT,
term INT
FOREIGN KEY (orig,term) REFERENCES items (num,num)
)
</code></pre>
<p>For each leaf in the tree, <code>items.tot</code> is set by someone. For interior nodes, <code>items.tot</code> needs to be the sum of it's children. Running the following query repeatedly would generate the desired result.</p>
<pre><code>UPDATE items SET tot = (
SELECT SUM(b.tot) FROM
tree JOIN items AS b
ON tree.term = b.num
WHERE tree.orig=items.num)
WHERE EXISTS
(SELECT * FROM tree WHERE orig=items.num)
</code></pre>
<p>(note this actually doesn't work but that's beside the point)</p>
<p>Assume that the database exists and the invariant are already satisfied. </p>
<p>The question is:</p>
<blockquote>
<p><strong>What is the most practical way to update the DB while maintaining this requirement? Updates may move nodes around or alter the value of <code>tot</code> on leaf nodes. It can be assumed that leaf nodes will stay as leaf nodes, interior nodes will stay as interior nodes and the whole thing will remain as a proper tree.</strong></p>
</blockquote>
<p>Some thoughts I have had:</p>
<ul>
<li>Full Invalidation, after any update, recompute everything (Um... No)</li>
<li>Set a trigger on the items table to update the parent of any row that is updated
<ul>
<li>This would be recursive (updates trigger updates, trigger updates, ...)</li>
<li>Doesn't work, MySQL can't update the table that kicked off the trigger</li>
</ul></li>
<li>Set a trigger to schedule an update of the parent of any row that is updated
<ul>
<li>This would be iterative (get an item from the schedule, processing it schedules more items)</li>
<li>What kicks this off? Trust client code to get it right?</li>
<li>An advantage is that if the updates are ordered correctly fewer sums need to be computer. But that ordering is a complication in and of it's own.</li>
</ul></li>
</ul>
<p>An ideal solution would generalize to other "aggregating invariants"</p>
<p>FWIW I know this is "a bit overboard", but I'm doing this for fun (Fun: verb, Finding the impossible by doing it. :-)</p>
| [
{
"answer_id": 21019,
"author": "Chris Hanson",
"author_id": 714,
"author_profile": "https://Stackoverflow.com/users/714",
"pm_score": 3,
"selected": false,
"text": "<p>Xcode has refactoring for C and Objective-C built in. Just select what you'd like to refactor, choose \"Refactor...\" from either the menu bar or the contextual menu, and you'll get a window including the available refactorings and a preview area.</p>\n\n<p>Xcode doesn't currently have a public plug-in API; if there are specific types of plug-ins you'd like Apple to enable, file enhancement requests in the <a href=\"http://bugreport.apple.com/\" rel=\"nofollow noreferrer\" title=\"Bug Reporter - it's not just for bugs!\">Bug Reporter</a>. That way Apple can count and track such requests.</p>\n\n<p>However, there are third-party tools like <a href=\"http://www.kevincallahan.org/software/accessorizer.html\" rel=\"nofollow noreferrer\" title=\"Accessorizer\">Accessorizer</a> and <a href=\"http://rentzsch.com/code/mogenerator\" rel=\"nofollow noreferrer\" title=\"mogenerator: Core Data codegen\"><code>mogenerator</code></a> (the latest release is <a href=\"http://rentzsch.com/code/mogenerator_v1.10\" rel=\"nofollow noreferrer\" title=\"mogenerator 1.10\"><code>mogenerator 1.10</code></a>) that you can use to make various development tasks faster. Accessorizer helps you create accessor methods for your classes, while <code>mogenerator</code> does more advanced code generation for Core Data managed object classes that are modeled using Xcode's modeling tools.</p>\n"
},
{
"answer_id": 21106,
"author": "Benjamin Pollack",
"author_id": 2354,
"author_profile": "https://Stackoverflow.com/users/2354",
"pm_score": 6,
"selected": true,
"text": "<p>You sound as if you're looking for three major things: code templates, refactoring tools, and auto-completion.</p>\n\n<p>The good news is that Xcode 3 and later come with superb auto-completion and template support. By default, you have to explicitly request completion by hitting the escape key. (This actually works in all <code>NSTextView</code>s; try it!) If you want to have the completions appear automatically, you can go to <strong>Preferences</strong> -> <strong>Code Sense</strong> and set the pop-up to appear automatically after a few seconds. You should find good completions for C and Objective-C code, and pretty good completions for C++.</p>\n\n<p>Xcode also has a solid template/skeleton system that you can use. You can see what templates are available by default by going to Edit -> Insert Text Macro. Of course, you don't want to insert text macros with the mouse; that defeats the point. Instead, you have two options:</p>\n\n<ol>\n<li>Back in <strong>Preferences</strong>,go to <strong>Key Bindings</strong>, and then, under <strong>Menu Key Bindings</strong>, assign a specific shortcut to macros you use often. I personally don't bother doing this, but I know plenty of great Mac devs who do</li>\n<li><p>Use the <code>CompletionPrefix</code>. By default, nearly all of the templates have a special prefix that, if you type and then hit the escape key, will result in the template being inserted. You can use Control-/ to move between the completion fields.</p>\n\n<p>You can see <a href=\"http://crookedspin.com/2005/06/10/xcode-macros/\" rel=\"noreferrer\">a full list of Xcode's default macros and their associated <code>CompletionPrefix</code>es</a> at <a href=\"http://crookedspin.com\" rel=\"noreferrer\">Crooked Spin</a>.</p>\n\n<p>You can also add your own macros, or modify the defaults. To do so, edit the file <code>/Developer/Library/Xcode/Specifications/{C,HTML}.xctxtmacro</code>. The syntax should be self-explanatory, if not terribly friendly.</p></li>\n</ol>\n\n<p>Unfortunately, if you're addicted to R#, you will be disappointed by your refactoring options. Basic refactoring is provided within Xcode through the context menu or by hitting Shift-Apple-J. From there, you can extract and rename methods, promote and demote them through the class hierarchy, and a few other common operations. Unfortunately, neither Xcode nor any third-party utilities offer anything approaching Resharper, so on that front, you're currently out of luck. Thankfully, Apple has already demonstrated versions of Xcode in the works that have vastly improved refactoring capabilities, so hopefully you won't have to wait too long before the situation starts to improve.</p>\n"
},
{
"answer_id": 562810,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 2,
"selected": false,
"text": "<p>Just so people know, <a href=\"http://www.kevincallahan.org/software/accessorizer.html\" rel=\"nofollow noreferrer\">Accessorizer</a> does more than just generate accessors (both 1.0 and properties for 2.0) it also generates Core Data code for persisting non-standard attributes, your NSSet accessors for custom to-many relationships.</p>\n\n<p>In fact, <a href=\"http://www.kevincallahan.org/software/accessorizer.html\" rel=\"nofollow noreferrer\">Accessorizer</a> will help provide you with the init, keypath, keyed-archiving, indexed accessors, accessors for unordered collections such as NSSet, copyWithZone, KVO, key-validation, singleton overrides, dealloc, setNilForKey, non-standard attribute persistence (Core Data), locking, headerdoc, convert method to selector, NSUndoManager methods and more.</p>\n"
},
{
"answer_id": 4444825,
"author": "Igor Pchelko",
"author_id": 425707,
"author_profile": "https://Stackoverflow.com/users/425707",
"pm_score": 0,
"selected": false,
"text": "<p>I found some xtmacro files in Xcode.app package:\n<strong>/Developer/Applications/Xcode.app/Contents/PlugIns/TextMacros.xctxtmacro/Contents/Resources</strong></p>\n\n<p>Installed Xcode ver. 3.2.5.</p>\n"
},
{
"answer_id": 5624722,
"author": "John Gallagher",
"author_id": 60131,
"author_profile": "https://Stackoverflow.com/users/60131",
"pm_score": 5,
"selected": false,
"text": "<p>I'm excited to say that JetBrains have decided to make a decent IDE for Objective-C coders. </p>\n\n<p>It's called <strong>AppCode</strong> and it's based on their other tools like RubyMine and Resharper. It's not native Cocoa, but has loads of raw refactoring power.</p>\n\n<p><a href=\"http://www.jetbrains.com/objc/index.html\" rel=\"noreferrer\">http://www.jetbrains.com/objc/index.html</a></p>\n\n<p>I've started using it for my main Objective C project and I'm already in love. It's still in it's infancy, but for code editing and refactoring it already blows Xcode away.</p>\n\n<p><strong>Update</strong></p>\n\n<p>It's now at a totally usable speed. I've switched over to it full time and it still blows my mind how amazing refactoring and coding is compared with Xcode. It just handles so much for you - auto importing, almost infinite customisation. It makes Xcode look like a toy.</p>\n"
}
] | 2008/08/21 | [
"https://Stackoverflow.com/questions/20426",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1343/"
] | I have a tree encoded in a MySQL database as edges:
```
CREATE TABLE items (
num INT,
tot INT,
PRIMARY KEY (num)
);
CREATE TABLE tree (
orig INT,
term INT
FOREIGN KEY (orig,term) REFERENCES items (num,num)
)
```
For each leaf in the tree, `items.tot` is set by someone. For interior nodes, `items.tot` needs to be the sum of it's children. Running the following query repeatedly would generate the desired result.
```
UPDATE items SET tot = (
SELECT SUM(b.tot) FROM
tree JOIN items AS b
ON tree.term = b.num
WHERE tree.orig=items.num)
WHERE EXISTS
(SELECT * FROM tree WHERE orig=items.num)
```
(note this actually doesn't work but that's beside the point)
Assume that the database exists and the invariant are already satisfied.
The question is:
>
> **What is the most practical way to update the DB while maintaining this requirement? Updates may move nodes around or alter the value of `tot` on leaf nodes. It can be assumed that leaf nodes will stay as leaf nodes, interior nodes will stay as interior nodes and the whole thing will remain as a proper tree.**
>
>
>
Some thoughts I have had:
* Full Invalidation, after any update, recompute everything (Um... No)
* Set a trigger on the items table to update the parent of any row that is updated
+ This would be recursive (updates trigger updates, trigger updates, ...)
+ Doesn't work, MySQL can't update the table that kicked off the trigger
* Set a trigger to schedule an update of the parent of any row that is updated
+ This would be iterative (get an item from the schedule, processing it schedules more items)
+ What kicks this off? Trust client code to get it right?
+ An advantage is that if the updates are ordered correctly fewer sums need to be computer. But that ordering is a complication in and of it's own.
An ideal solution would generalize to other "aggregating invariants"
FWIW I know this is "a bit overboard", but I'm doing this for fun (Fun: verb, Finding the impossible by doing it. :-) | You sound as if you're looking for three major things: code templates, refactoring tools, and auto-completion.
The good news is that Xcode 3 and later come with superb auto-completion and template support. By default, you have to explicitly request completion by hitting the escape key. (This actually works in all `NSTextView`s; try it!) If you want to have the completions appear automatically, you can go to **Preferences** -> **Code Sense** and set the pop-up to appear automatically after a few seconds. You should find good completions for C and Objective-C code, and pretty good completions for C++.
Xcode also has a solid template/skeleton system that you can use. You can see what templates are available by default by going to Edit -> Insert Text Macro. Of course, you don't want to insert text macros with the mouse; that defeats the point. Instead, you have two options:
1. Back in **Preferences**,go to **Key Bindings**, and then, under **Menu Key Bindings**, assign a specific shortcut to macros you use often. I personally don't bother doing this, but I know plenty of great Mac devs who do
2. Use the `CompletionPrefix`. By default, nearly all of the templates have a special prefix that, if you type and then hit the escape key, will result in the template being inserted. You can use Control-/ to move between the completion fields.
You can see [a full list of Xcode's default macros and their associated `CompletionPrefix`es](http://crookedspin.com/2005/06/10/xcode-macros/) at [Crooked Spin](http://crookedspin.com).
You can also add your own macros, or modify the defaults. To do so, edit the file `/Developer/Library/Xcode/Specifications/{C,HTML}.xctxtmacro`. The syntax should be self-explanatory, if not terribly friendly.
Unfortunately, if you're addicted to R#, you will be disappointed by your refactoring options. Basic refactoring is provided within Xcode through the context menu or by hitting Shift-Apple-J. From there, you can extract and rename methods, promote and demote them through the class hierarchy, and a few other common operations. Unfortunately, neither Xcode nor any third-party utilities offer anything approaching Resharper, so on that front, you're currently out of luck. Thankfully, Apple has already demonstrated versions of Xcode in the works that have vastly improved refactoring capabilities, so hopefully you won't have to wait too long before the situation starts to improve. |
20,450 | <p>I'd like to take some RTF input and clean it to remove all RTF formatting except \ul \b \i to paste it into Word with minor format information.</p>
<p>The command used to paste into Word will be something like:
oWord.ActiveDocument.ActiveWindow.Selection.PasteAndFormat(0) (with some RTF text already in the Clipboard)</p>
<pre><code>{\rtf1\ansi\deff0{\fonttbl{\f0\fnil\fcharset0 Courier New;}}
{\colortbl ;\red255\green255\blue140;}
\viewkind4\uc1\pard\highlight1\lang3084\f0\fs18 The company is a global leader in responsible tourism and was \ul the first major hotel chain in North America\ulnone to embrace environmental stewardship within its daily operations\highlight0\par
</code></pre>
<p>Do you have any idea on how I can clean up the RTF safely with some regular expressions or something? I am using VB.NET to do the processing but any .NET language sample will do.</p>
| [
{
"answer_id": 20498,
"author": "Chris Miller",
"author_id": 206,
"author_profile": "https://Stackoverflow.com/users/206",
"pm_score": 2,
"selected": false,
"text": "<p>You can strip out the tags with regular expressions. Just make sure that your expressions will not filter tags that were actually text. If the text had \"\\b\" in the body of text, it would appear as \\b in the RTF stream. In other words, you would match on \"\\b\" but not \"\\b\".</p>\n\n<p>You could probably take a short cut and filter out the header RTF tags. Look for the first occurrence of \"\\viewkind4\" in the input. Then read ahead to the first space character. You would remove all of the characters from the start of the text up to and including that space character. That would strip out the RTF header information (fonts, colors, etc).</p>\n"
},
{
"answer_id": 20628,
"author": "Nick",
"author_id": 1490,
"author_profile": "https://Stackoverflow.com/users/1490",
"pm_score": 4,
"selected": true,
"text": "<p>I would use a hidden RichTextBox, set the Rtf member, then retrieve the Text member to sanitize the RTF in a well-supported way. Then I would use manually inject the desired formatting afterwards.</p>\n"
},
{
"answer_id": 20708,
"author": "Martin",
"author_id": 770,
"author_profile": "https://Stackoverflow.com/users/770",
"pm_score": 3,
"selected": false,
"text": "<p>I'd do something like the following:</p>\n\n<pre><code>Dim unformatedtext As String\n\nsomeRTFtext = Replace(someRTFtext, \"\\ul\", \"[ul]\")\nsomeRTFtext = Replace(someRTFtext, \"\\b\", \"[b]\")\nsomeRTFtext = Replace(someRTFtext, \"\\i\", \"[i]\")\n\nDim RTFConvert As RichTextBox = New RichTextBox\nRTFConvert.Rtf = someRTFtext\nunformatedtext = RTFConvert.Text\n\nunformatedtext = Replace(unformatedtext, \"[ul]\", \"\\ul\")\nunformatedtext = Replace(unformatedtext, \"[b]\", \"\\b\")\nunformatedtext = Replace(unformatedtext, \"[i]\", \"\\i\")\n\nClipboard.SetText(unformatedtext)\n\noWord.ActiveDocument.ActiveWindow.Selection.PasteAndFormat(0)\n</code></pre>\n"
},
{
"answer_id": 10941969,
"author": "Toby Holland",
"author_id": 1367075,
"author_profile": "https://Stackoverflow.com/users/1367075",
"pm_score": 1,
"selected": false,
"text": "<p>Regex it, it wont parse absolutely everything correctly (tables for example) but does the job in most cases.</p>\n\n<pre><code>string unformatted = Regex.Replace(rtfString, @\"\\{\\*?\\\\[^{}]+}|[{}]|\\\\\\n?[A-Za-z]+\\n?(?:-?\\d+)?[ ]?\", \"\");\n</code></pre>\n\n<p>Magic =)</p>\n"
}
] | 2008/08/21 | [
"https://Stackoverflow.com/questions/20450",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1508/"
] | I'd like to take some RTF input and clean it to remove all RTF formatting except \ul \b \i to paste it into Word with minor format information.
The command used to paste into Word will be something like:
oWord.ActiveDocument.ActiveWindow.Selection.PasteAndFormat(0) (with some RTF text already in the Clipboard)
```
{\rtf1\ansi\deff0{\fonttbl{\f0\fnil\fcharset0 Courier New;}}
{\colortbl ;\red255\green255\blue140;}
\viewkind4\uc1\pard\highlight1\lang3084\f0\fs18 The company is a global leader in responsible tourism and was \ul the first major hotel chain in North America\ulnone to embrace environmental stewardship within its daily operations\highlight0\par
```
Do you have any idea on how I can clean up the RTF safely with some regular expressions or something? I am using VB.NET to do the processing but any .NET language sample will do. | I would use a hidden RichTextBox, set the Rtf member, then retrieve the Text member to sanitize the RTF in a well-supported way. Then I would use manually inject the desired formatting afterwards. |
20,465 | <p>I'm developing an Excel 2007 add-in using Visual Studio Tools for Office (2008). I have one sheet with several ListObjects on it, which are being bound to datatables on startup. When they are bound, they autosize correctly.</p>
<p>The problem comes when they are re-bound. I have a custom button on the ribbon bar which goes back out to the database and retrieves different information based on some criteria that the user inputs. This new data comes back and is re-bound to the ListObjects - however, this time they are not resized and I get an exception:</p>
<blockquote>
<p>ListObject cannot be bound because it
cannot be resized to fit the data. The
ListObject failed to add new rows.
This can be caused because of
inability to move objects below of the
list object.</p>
<blockquote>
<p>Inner exception: "Insert method of Range class failed"<br>
Reason: Microsoft.Office.Tools.Excel.FailureReason.CouldNotResizeListObject</p>
</blockquote>
</blockquote>
<p>I was not able to find anything very meaningful on this error on Google or MSDN. I have been trying to figure this out for a while, but to no avail.</p>
<p>Basic code structure:</p>
<pre><code>//at startup
DataTable tbl = //get from database
listObj1.SetDataBinding(tbl);
DataTable tbl2 = //get from database
listObj2.SetDataBinding(tbl2);
//in buttonClick event handler
DataTable tbl = //get different info from database
//have tried with and without unbinding old source
listObj1.SetDataBinding(tbl); <-- exception here
DataTable tbl2 = //get different info from database
listObj2.SetDataBinding(tbl2);
</code></pre>
<p>Note that this exception occurs even when the ListObject is shrinking, and not only when it grows.</p>
| [
{
"answer_id": 23735,
"author": "Guy",
"author_id": 1463,
"author_profile": "https://Stackoverflow.com/users/1463",
"pm_score": 0,
"selected": false,
"text": "<p>Just an idea of something to try to see if it gives you more info: Try resizes the list object before the exception line and see if that also throws an exception. If not, try and resize the range object to the new size of the DataTable.</p>\n\n<p>You say that this happens when the ListObject shrinks and grows. Does it also happen if the ListObject remains the same size?</p>\n"
},
{
"answer_id": 26691,
"author": "goric",
"author_id": 940,
"author_profile": "https://Stackoverflow.com/users/940",
"pm_score": 4,
"selected": true,
"text": "<p>If anyone else is having this problem, I have found the cause of this exception. ListObjects will automatically re-size on binding, as long as they do not affect any other objects on the sheet. Keep in mind that ListObjects can only affect the Ranges which they wrap around.</p>\n\n<p>In my case, the list object which was above the other one had fewer columns than the one below it. Let's say the top ListObject had 2 columns, and the bottom ListObject had 3 columns. When the top ListObject changed its number of rows, it had no ability to make any changes to the third column since it wasn't in it's underlying Range. This means that it couldn't shift any cells in the third column, and so the second ListObject couldn't be properly moved, resulting in my exception above.</p>\n\n<p>Changing the positions of the ListObjects to place the wider one above the smaller one works fine. Following the logic above, this now means that the wider ListObject can shift all of the columns of the second ListObject, and since there is nothing below the smaller one it can also shift any cells necessary. The reason I wasn't having any trouble on the initial binding is that both ListObjects were a single cell.</p>\n\n<p>Since this is not optimal in my case, I will probably use empty columns or try to play around with invisible columns if that's possible, but at least the cause is now clear.</p>\n"
},
{
"answer_id": 659042,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 1,
"selected": false,
"text": "<p>I've got a similar issue with refreshign multiple listobjects. We are setting each listObject.DataSource = null, then rebinding starting at the bottom listobject and working our way up instead of the top down.</p>\n"
}
] | 2008/08/21 | [
"https://Stackoverflow.com/questions/20465",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/940/"
] | I'm developing an Excel 2007 add-in using Visual Studio Tools for Office (2008). I have one sheet with several ListObjects on it, which are being bound to datatables on startup. When they are bound, they autosize correctly.
The problem comes when they are re-bound. I have a custom button on the ribbon bar which goes back out to the database and retrieves different information based on some criteria that the user inputs. This new data comes back and is re-bound to the ListObjects - however, this time they are not resized and I get an exception:
>
> ListObject cannot be bound because it
> cannot be resized to fit the data. The
> ListObject failed to add new rows.
> This can be caused because of
> inability to move objects below of the
> list object.
>
>
>
> >
> > Inner exception: "Insert method of Range class failed"
> >
> > Reason: Microsoft.Office.Tools.Excel.FailureReason.CouldNotResizeListObject
> >
> >
> >
>
>
>
I was not able to find anything very meaningful on this error on Google or MSDN. I have been trying to figure this out for a while, but to no avail.
Basic code structure:
```
//at startup
DataTable tbl = //get from database
listObj1.SetDataBinding(tbl);
DataTable tbl2 = //get from database
listObj2.SetDataBinding(tbl2);
//in buttonClick event handler
DataTable tbl = //get different info from database
//have tried with and without unbinding old source
listObj1.SetDataBinding(tbl); <-- exception here
DataTable tbl2 = //get different info from database
listObj2.SetDataBinding(tbl2);
```
Note that this exception occurs even when the ListObject is shrinking, and not only when it grows. | If anyone else is having this problem, I have found the cause of this exception. ListObjects will automatically re-size on binding, as long as they do not affect any other objects on the sheet. Keep in mind that ListObjects can only affect the Ranges which they wrap around.
In my case, the list object which was above the other one had fewer columns than the one below it. Let's say the top ListObject had 2 columns, and the bottom ListObject had 3 columns. When the top ListObject changed its number of rows, it had no ability to make any changes to the third column since it wasn't in it's underlying Range. This means that it couldn't shift any cells in the third column, and so the second ListObject couldn't be properly moved, resulting in my exception above.
Changing the positions of the ListObjects to place the wider one above the smaller one works fine. Following the logic above, this now means that the wider ListObject can shift all of the columns of the second ListObject, and since there is nothing below the smaller one it can also shift any cells necessary. The reason I wasn't having any trouble on the initial binding is that both ListObjects were a single cell.
Since this is not optimal in my case, I will probably use empty columns or try to play around with invisible columns if that's possible, but at least the cause is now clear. |
20,467 | <p>Are there any automatic methods for trimming a path string in .NET?</p>
<p>For example:</p>
<pre><code>C:\Documents and Settings\nick\My Documents\Tests\demo data\demo data.emx
</code></pre>
<p>becomes</p>
<pre><code>C:\Documents...\demo data.emx
</code></pre>
<p>It would be particularly cool if this were built into the Label class, and I seem to recall it is--can't find it though!</p>
| [
{
"answer_id": 20492,
"author": "Darren Kopp",
"author_id": 77,
"author_profile": "https://Stackoverflow.com/users/77",
"pm_score": 0,
"selected": false,
"text": "<p>What you are thinking on the label is that it will put ... if it is longer than the width (not set to auto size), but that would be</p>\n\n<pre><code>c:\\Documents and Settings\\nick\\My Doc...\n</code></pre>\n\n<p>If there is support, it would probably be on the Path class in System.IO</p>\n"
},
{
"answer_id": 20493,
"author": "denis phillips",
"author_id": 748,
"author_profile": "https://Stackoverflow.com/users/748",
"pm_score": 0,
"selected": false,
"text": "<p>You could use the System.IO.Path.GetFileName method and append that string to a shortened System.IO.Path.GetDirectoryName string.</p>\n"
},
{
"answer_id": 20494,
"author": "Quibblesome",
"author_id": 1143,
"author_profile": "https://Stackoverflow.com/users/1143",
"pm_score": 2,
"selected": false,
"text": "<p>Not hard to write yourself though:</p>\n\n<pre><code> public static string TrimPath(string path)\n {\n int someArbitaryNumber = 10;\n string directory = Path.GetDirectoryName(path);\n string fileName = Path.GetFileName(path);\n if (directory.Length > someArbitaryNumber)\n {\n return String.Format(@\"{0}...\\{1}\", \n directory.Substring(0, someArbitaryNumber), fileName);\n }\n else\n {\n return path;\n }\n }\n</code></pre>\n\n<p>I guess you could even add it as an extension method.</p>\n"
},
{
"answer_id": 20495,
"author": "lubos hasko",
"author_id": 275,
"author_profile": "https://Stackoverflow.com/users/275",
"pm_score": 4,
"selected": true,
"text": "<p>Use <strong>TextRenderer.DrawText</strong> with <strong>TextFormatFlags.PathEllipsis</strong> flag</p>\n\n<pre><code>void label_Paint(object sender, PaintEventArgs e)\n{\n Label label = (Label)sender;\n TextRenderer.DrawText(e.Graphics, label.Text, label.Font, label.ClientRectangle, label.ForeColor, TextFormatFlags.PathEllipsis);\n}\n</code></pre>\n\n<blockquote>\n <p>Your code is 95% there. The only\n problem is that the trimmed text is\n drawn on top of the text which is\n already on the label.</p>\n</blockquote>\n\n<p>Yes thanks, I was aware of that. My intention was only to demonstrate use of <code>DrawText</code> method. I didn't know whether you want to manually create event for each label or just override <code>OnPaint()</code> method in inherited label. Thanks for sharing your final solution though.</p>\n"
},
{
"answer_id": 20592,
"author": "Nick",
"author_id": 1490,
"author_profile": "https://Stackoverflow.com/users/1490",
"pm_score": 2,
"selected": false,
"text": "<p>@ <a href=\"https://stackoverflow.com/questions/20467?sort=votes#20495\">lubos hasko</a> Your code is 95% there. The only problem is that the trimmed text is drawn on top of the text which is already on the label. This is easily solved:</p>\n\n<pre><code> Label label = (Label)sender;\n using (SolidBrush b = new SolidBrush(label.BackColor))\n e.Graphics.FillRectangle(b, label.ClientRectangle);\n TextRenderer.DrawText(\n e.Graphics, \n label.Text, \n label.Font, \n label.ClientRectangle, \n label.ForeColor, \n TextFormatFlags.PathEllipsis);\n</code></pre>\n"
}
] | 2008/08/21 | [
"https://Stackoverflow.com/questions/20467",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1490/"
] | Are there any automatic methods for trimming a path string in .NET?
For example:
```
C:\Documents and Settings\nick\My Documents\Tests\demo data\demo data.emx
```
becomes
```
C:\Documents...\demo data.emx
```
It would be particularly cool if this were built into the Label class, and I seem to recall it is--can't find it though! | Use **TextRenderer.DrawText** with **TextFormatFlags.PathEllipsis** flag
```
void label_Paint(object sender, PaintEventArgs e)
{
Label label = (Label)sender;
TextRenderer.DrawText(e.Graphics, label.Text, label.Font, label.ClientRectangle, label.ForeColor, TextFormatFlags.PathEllipsis);
}
```
>
> Your code is 95% there. The only
> problem is that the trimmed text is
> drawn on top of the text which is
> already on the label.
>
>
>
Yes thanks, I was aware of that. My intention was only to demonstrate use of `DrawText` method. I didn't know whether you want to manually create event for each label or just override `OnPaint()` method in inherited label. Thanks for sharing your final solution though. |
20,484 | <p>Can/Should I use a LIKE criteria as part of an INNER JOIN when building a stored procedure/query? I'm not sure I'm asking the right thing, so let me explain.</p>
<p>I'm creating a procedure that is going to take a list of keywords to be searched for in a column that contains text. If I was sitting at the console, I'd execute it as such:</p>
<pre><code>SELECT Id, Name, Description
FROM dbo.Card
WHERE Description LIKE '%warrior%'
OR
Description LIKE '%fiend%'
OR
Description LIKE '%damage%'
</code></pre>
<p>But a trick I picked up a little while go to do "strongly typed" list parsing in a stored procedure is to parse the list into a table variable/temporary table, converting it to the proper type and then doing an INNER JOIN against that table in my final result set. This works great when sending say a list of integer IDs to the procedure. I wind up having a final query that looks like this:</p>
<pre><code>SELECT Id, Name, Description
FROM dbo.Card
INNER JOIN @tblExclusiveCard ON dbo.Card.Id = @tblExclusiveCard.CardId
</code></pre>
<p>I want to use this trick with a list of strings. But since I'm looking for a particular keyword, I am going to use the LIKE clause. So ideally I'm thinking I'd have my final query look like this:</p>
<pre><code>SELECT Id, Name, Description
FROM dbo.Card
INNER JOIN @tblKeyword ON dbo.Card.Description LIKE '%' + @tblKeyword.Value + '%'
</code></pre>
<p>Is this possible/recommended?</p>
<p>Is there a better way to do something like this?</p>
<hr>
<p>The reason I'm putting wildcards on both ends of the clause is because there are "archfiend", "beast-warrior", "direct-damage" and "battle-damage" terms that are used in the card texts.</p>
<p>I'm getting the impression that depending on the performance, I can either use the query I specified or use a full-text keyword search to accomplish the same task? </p>
<p>Other than having the server do a text index on the fields I want to text search, is there anything else I need to do?</p>
| [
{
"answer_id": 20513,
"author": "Nick Berardi",
"author_id": 17,
"author_profile": "https://Stackoverflow.com/users/17",
"pm_score": 1,
"selected": false,
"text": "<p>It seems like you are looking for full-text search. Because you want to query a set of keywords against the card description and find any hits? Correct?</p>\n"
},
{
"answer_id": 20515,
"author": "Darren Kopp",
"author_id": 77,
"author_profile": "https://Stackoverflow.com/users/77",
"pm_score": 1,
"selected": false,
"text": "<p>Personally, I have done it before, and it has worked out well for me. The only issues i could see is possibly issues with an unindexed column, but i think you would have the same issue with a where clause.</p>\n\n<p>My advice to you is just look at the execution plans between the two. I'm sure that it will differ which one is better depending on the situation, just like all good programming problems.</p>\n"
},
{
"answer_id": 20531,
"author": "Chris Miller",
"author_id": 206,
"author_profile": "https://Stackoverflow.com/users/206",
"pm_score": 0,
"selected": false,
"text": "<p>Performance will be depend on the actual server than you use, and on the schema of the data, and the amount of data. With current versions of MS SQL Server, that query should run just fine (MS SQL Server 7.0 had issues with that syntax, but <a href=\"http://support.microsoft.com/kb/225093\" rel=\"nofollow noreferrer\">it was addressed in SP2</a>).</p>\n\n<p>Have you run that code through a profiler? If the performance is fast enough and the data has the appropriate indexes in place, you should be all set.</p>\n"
},
{
"answer_id": 20538,
"author": "jason saldo",
"author_id": 1293,
"author_profile": "https://Stackoverflow.com/users/1293",
"pm_score": 4,
"selected": true,
"text": "<p>Your first query will work but will require a full table scan because any index on that column will be ignored. You will also have to do some dynamic SQL to generate all your LIKE clauses.</p>\n\n<p>Try a full text search if your using SQL Server or check out one of the <a href=\"http://lucene.apache.org/java/docs/index.html\" rel=\"noreferrer\">Lucene</a> implementations. Joel talked about his success with it recently.</p>\n"
},
{
"answer_id": 20544,
"author": "SQLMenace",
"author_id": 740,
"author_profile": "https://Stackoverflow.com/users/740",
"pm_score": 0,
"selected": false,
"text": "<p>LIKE '%fiend%' will never use an seek, LIKE 'fiend%' will. Simply a wildcard search is not sargable</p>\n"
},
{
"answer_id": 20599,
"author": "jason saldo",
"author_id": 1293,
"author_profile": "https://Stackoverflow.com/users/1293",
"pm_score": 1,
"selected": false,
"text": "<p>@Dillie-O<br>\nHow big is this table?<br>\nWhat is the data type of Description field? </p>\n\n<p>If either are small a full text search will be overkill.</p>\n\n<p>@Dillie-O<br>\nMaybe not the answer you where looking for but I would advocate a schema change...</p>\n\n<p>proposed schema:</p>\n\n<pre><code>create table name(\n nameID identity / int\n ,name varchar(50))\n\ncreate table description(\n descID identity / int\n ,desc varchar(50)) --something reasonable and to make the most of it alwase lower case your values\n\ncreate table nameDescJunc(\n nameID int\n ,descID int)\n</code></pre>\n\n<p>This will let you use index's without have to implement a bolt on solution, and keeps your data atomic.</p>\n\n<p>related: <a href=\"https://stackoverflow.com/questions/20856\">Recommended SQL database design for tags or tagging</a></p>\n"
},
{
"answer_id": 810683,
"author": "onedaywhen",
"author_id": 15354,
"author_profile": "https://Stackoverflow.com/users/15354",
"pm_score": 1,
"selected": false,
"text": "<blockquote>\n <p>a trick I picked up a little while go\n to do \"strongly typed\" list parsing in\n a stored procedure is to parse the\n list into a table variable/temporary\n table</p>\n</blockquote>\n\n<p>I think what you might be alluding to here is to put the keywords to include into a table then use <a href=\"http://www.dbazine.com/ofinterest/oi-articles/celko1\" rel=\"nofollow noreferrer\">relational division</a> to find matches (could also use another table for words to exclude). For a worked example in SQL see <a href=\"http://www.dbazine.com/ofinterest/oi-articles/celko9\" rel=\"nofollow noreferrer\">Keyword Searches by Joe Celko</a>.</p>\n"
},
{
"answer_id": 891792,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 0,
"selected": false,
"text": "<p>Try this;</p>\n\n<pre><code>SELECT Id, Name, Description\nFROM dbo.Card\nINNER JOIN @tblKeyword ON dbo.Card.Description LIKE '%' + \n CONCAT(CONCAT('%',@tblKeyword.Value),'%') + '%'\n</code></pre>\n"
},
{
"answer_id": 14590796,
"author": "John",
"author_id": 1223661,
"author_profile": "https://Stackoverflow.com/users/1223661",
"pm_score": 3,
"selected": false,
"text": "<p>Try this</p>\n\n<pre><code> select * from Table_1 a\n left join Table_2 b on b.type LIKE '%' + a.type + '%'\n</code></pre>\n\n<p>This practice is not ideal. Use with caution.</p>\n"
},
{
"answer_id": 30483791,
"author": "Manoj",
"author_id": 4944899,
"author_profile": "https://Stackoverflow.com/users/4944899",
"pm_score": 2,
"selected": false,
"text": "<p>try it...</p>\n\n<pre><code>select * from table11 a inner join table2 b on b.id like (select '%'+a.id+'%') where a.city='abc'.\n</code></pre>\n\n<p>Its works for me.:-)</p>\n"
}
] | 2008/08/21 | [
"https://Stackoverflow.com/questions/20484",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/71/"
] | Can/Should I use a LIKE criteria as part of an INNER JOIN when building a stored procedure/query? I'm not sure I'm asking the right thing, so let me explain.
I'm creating a procedure that is going to take a list of keywords to be searched for in a column that contains text. If I was sitting at the console, I'd execute it as such:
```
SELECT Id, Name, Description
FROM dbo.Card
WHERE Description LIKE '%warrior%'
OR
Description LIKE '%fiend%'
OR
Description LIKE '%damage%'
```
But a trick I picked up a little while go to do "strongly typed" list parsing in a stored procedure is to parse the list into a table variable/temporary table, converting it to the proper type and then doing an INNER JOIN against that table in my final result set. This works great when sending say a list of integer IDs to the procedure. I wind up having a final query that looks like this:
```
SELECT Id, Name, Description
FROM dbo.Card
INNER JOIN @tblExclusiveCard ON dbo.Card.Id = @tblExclusiveCard.CardId
```
I want to use this trick with a list of strings. But since I'm looking for a particular keyword, I am going to use the LIKE clause. So ideally I'm thinking I'd have my final query look like this:
```
SELECT Id, Name, Description
FROM dbo.Card
INNER JOIN @tblKeyword ON dbo.Card.Description LIKE '%' + @tblKeyword.Value + '%'
```
Is this possible/recommended?
Is there a better way to do something like this?
---
The reason I'm putting wildcards on both ends of the clause is because there are "archfiend", "beast-warrior", "direct-damage" and "battle-damage" terms that are used in the card texts.
I'm getting the impression that depending on the performance, I can either use the query I specified or use a full-text keyword search to accomplish the same task?
Other than having the server do a text index on the fields I want to text search, is there anything else I need to do? | Your first query will work but will require a full table scan because any index on that column will be ignored. You will also have to do some dynamic SQL to generate all your LIKE clauses.
Try a full text search if your using SQL Server or check out one of the [Lucene](http://lucene.apache.org/java/docs/index.html) implementations. Joel talked about his success with it recently. |
20,510 | <p>I have a flex application that needs the ability to generate and execute JavaScript. When I say this, I mean I need to execute raw JavaScript that I create in my Flex application (not just an existing JavaScript method)</p>
<p>I am currently doing this by exposing the following JavaScript method:</p>
<pre><code>function doScript(js){ eval(js);}
</code></pre>
<p>I can then do something like this in Flex (note: I am doing something more substantial then an alert box in the real Flex app):</p>
<pre><code>ExternalInterface.call("doScript","alert('foo'));
</code></pre>
<p>My question is does this impose any security risk, I am assuming it's not since the Flex and JasvaScript all run client side...</p>
<p>Is there a better way to do this?</p>
| [
{
"answer_id": 20532,
"author": "Darren Kopp",
"author_id": 77,
"author_profile": "https://Stackoverflow.com/users/77",
"pm_score": 0,
"selected": false,
"text": "<p>As far as I know, and I'm definately not a hacker, you are completely fine. Really, if someone wanted to, they could exploit your code anyway clientside, but i don't see how they could exploit your server side code using javascript (unless you use server side javascript)</p>\n"
},
{
"answer_id": 20578,
"author": "jsight",
"author_id": 1432,
"author_profile": "https://Stackoverflow.com/users/1432",
"pm_score": 0,
"selected": false,
"text": "<p>I don't see where this lets them do anything that they couldn't do already by calling eval. If there's a security hole being introduced here, I don't see it.</p>\n"
},
{
"answer_id": 20595,
"author": "Funkatron",
"author_id": 2310,
"author_profile": "https://Stackoverflow.com/users/2310",
"pm_score": 1,
"selected": false,
"text": "<p>This isn't inherently dangerous, but the moment you pass any user-provided data into the function, it's ripe for a code injection exploit. That's worrisome, and something I'd avoid. I think a better approach would be to only expose the functionality you <em>need</em>, and nothing more.</p>\n"
},
{
"answer_id": 20645,
"author": "Theo",
"author_id": 1109,
"author_profile": "https://Stackoverflow.com/users/1109",
"pm_score": 4,
"selected": true,
"text": "<p>There's no need for the JavaScript function, the first argument to <code>ExternalInterface</code> can be any JavaScript code, it doesn't have to be a function name (the documentation says so, but it is wrong).</p>\n\n<p>Try this:</p>\n\n<pre><code>ExternalInterface.call(\"alert('hello')\");\n</code></pre>\n"
},
{
"answer_id": 63603,
"author": "ZebZiggle",
"author_id": 2587612,
"author_profile": "https://Stackoverflow.com/users/2587612",
"pm_score": 0,
"selected": false,
"text": "<p>Remember also that the script actions are controlled by the \"AllowScriptAccess\" tag in the statement. If the web page doesn't want these actions, they should not permit scripts to call out. </p>\n\n<p><a href=\"http://kb.adobe.com/selfservice/viewContent.do?externalId=tn_16494\" rel=\"nofollow noreferrer\">http://kb.adobe.com/selfservice/viewContent.do?externalId=tn_16494</a></p>\n"
},
{
"answer_id": 40553258,
"author": "user2629253",
"author_id": 2629253,
"author_profile": "https://Stackoverflow.com/users/2629253",
"pm_score": -1,
"selected": false,
"text": "<pre><code>ExternalInterface.call(\"eval\", \"alert('hello');\");\n</code></pre>\n"
}
] | 2008/08/21 | [
"https://Stackoverflow.com/questions/20510",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1638/"
] | I have a flex application that needs the ability to generate and execute JavaScript. When I say this, I mean I need to execute raw JavaScript that I create in my Flex application (not just an existing JavaScript method)
I am currently doing this by exposing the following JavaScript method:
```
function doScript(js){ eval(js);}
```
I can then do something like this in Flex (note: I am doing something more substantial then an alert box in the real Flex app):
```
ExternalInterface.call("doScript","alert('foo'));
```
My question is does this impose any security risk, I am assuming it's not since the Flex and JasvaScript all run client side...
Is there a better way to do this? | There's no need for the JavaScript function, the first argument to `ExternalInterface` can be any JavaScript code, it doesn't have to be a function name (the documentation says so, but it is wrong).
Try this:
```
ExternalInterface.call("alert('hello')");
``` |
20,586 | <p>I'm trying to bind a list of custom objects to a WPF Image like this:</p>
<pre><code><Image>
<Image.Source>
<BitmapImage UriSource="{Binding Path=ImagePath}" />
</Image.Source>
</Image>
</code></pre>
<p>But it doesn't work. This is the error I'm getting:</p>
<p><em>"Property 'UriSource' or property 'StreamSource' must be set."</em></p>
<p>What am I missing?</p>
| [
{
"answer_id": 20617,
"author": "Dale Ragan",
"author_id": 1117,
"author_profile": "https://Stackoverflow.com/users/1117",
"pm_score": 3,
"selected": false,
"text": "<p>You need to have an implementation of <a href=\"http://msdn.microsoft.com/en-us/library/system.windows.data.ivalueconverter.aspx\" rel=\"nofollow noreferrer\">IValueConverter</a> interface that converts the uri into an image. Your Convert implementation of IValueConverter will look something like this:</p>\n\n<pre><code>BitmapImage image = new BitmapImage();\nimage.BeginInit();\nimage.UriSource = new Uri(value as string);\nimage.EndInit();\n\nreturn image;\n</code></pre>\n\n<p>Then you will need to use the converter in your binding:</p>\n\n<pre><code><Image>\n <Image.Source>\n <BitmapImage UriSource=\"{Binding Path=ImagePath, Converter=...}\" />\n </Image.Source>\n</Image>\n</code></pre>\n"
},
{
"answer_id": 20648,
"author": "palehorse",
"author_id": 312,
"author_profile": "https://Stackoverflow.com/users/312",
"pm_score": 4,
"selected": false,
"text": "<p>You can also simply set the Source attribute rather than using the child elements. To do this your class needs to return the image as a Bitmap Image. Here is an example of one way I've done it</p>\n\n<pre><code><Image Width=\"90\" Height=\"90\" \n Source=\"{Binding Path=ImageSource}\"\n Margin=\"0,0,0,5\" />\n</code></pre>\n\n<p>And the class property is simply this</p>\n\n<pre><code>public object ImageSource {\n get {\n BitmapImage image = new BitmapImage();\n\n try {\n image.BeginInit();\n image.CacheOption = BitmapCacheOption.OnLoad;\n image.CreateOptions = BitmapCreateOptions.IgnoreImageCache;\n image.UriSource = new Uri( FullPath, UriKind.Absolute );\n image.EndInit();\n }\n catch{\n return DependencyProperty.UnsetValue;\n }\n\n return image;\n }\n}\n</code></pre>\n\n<p>I suppose it may be a little more work than the value converter, but it is another option.</p>\n"
},
{
"answer_id": 20737,
"author": "Brian Leahy",
"author_id": 580,
"author_profile": "https://Stackoverflow.com/users/580",
"pm_score": 7,
"selected": true,
"text": "<p>WPF has built-in converters for certain types. If you bind the Image's <code>Source</code> property to a <code>string</code> or <code>Uri</code> value, under the hood WPF will use an <a href=\"https://msdn.microsoft.com/en-us/library/system.windows.media.imagesourceconverter(v=vs.110).aspx\" rel=\"noreferrer\">ImageSourceConverter</a> to convert the value to an <code>ImageSource</code>.</p>\n\n<p>So</p>\n\n<pre><code><Image Source=\"{Binding ImageSource}\"/>\n</code></pre>\n\n<p>would work if the ImageSource property was a string representation of a valid URI to an image.</p>\n\n<p>You can of course roll your own Binding converter:</p>\n\n<pre class=\"lang-cs prettyprint-override\"><code>public class ImageConverter : IValueConverter\n{\n public object Convert(\n object value, Type targetType, object parameter, CultureInfo culture)\n {\n return new BitmapImage(new Uri(value.ToString()));\n }\n\n public object ConvertBack(\n object value, Type targetType, object parameter, CultureInfo culture)\n {\n throw new NotSupportedException();\n }\n}\n</code></pre>\n\n<p>and use it like this:</p>\n\n<pre><code><Image Source=\"{Binding ImageSource, Converter={StaticResource ImageConverter}}\"/>\n</code></pre>\n"
},
{
"answer_id": 862583,
"author": "Drew Noakes",
"author_id": 24874,
"author_profile": "https://Stackoverflow.com/users/24874",
"pm_score": 4,
"selected": false,
"text": "<p><a href=\"http://www.infosysblogs.com/microsoft/2008/04/wpf_binding_to_image_control.html\" rel=\"noreferrer\">This article</a> by Atul Gupta has sample code that covers several scenarios:</p>\n\n<ol>\n<li>Regular resource image binding to Source property in XAML</li>\n<li>Binding resource image, but from code behind</li>\n<li>Binding resource image in code behind by using Application.GetResourceStream</li>\n<li>Loading image from file path via memory stream (same is applicable when loading blog image data from database)</li>\n<li>Loading image from file path, but by using binding to a file path Property</li>\n<li>Binding image data to a user control which internally has image control via dependency property</li>\n<li>Same as point 5, but also ensuring that the file doesn't get's locked on hard-disk</li>\n</ol>\n"
},
{
"answer_id": 13895496,
"author": "Luis Cantero",
"author_id": 569998,
"author_profile": "https://Stackoverflow.com/users/569998",
"pm_score": 3,
"selected": false,
"text": "<p>The problem with the answer that was chosen here is that when navigating back and forth, the converter will get triggered every time the page is shown.</p>\n\n<p>This causes new file handles to be created continuously and will block any attempt to delete the file because it is still in use. This can be verified by using Process Explorer.</p>\n\n<p>If the image file might be deleted at some point, a converter such as this might be used:\n<a href=\"https://stackoverflow.com/questions/3427034/using-xaml-to-bind-to-a-system-drawing-image-into-a-system-windows-image-control\">using XAML to bind to a System.Drawing.Image into a System.Windows.Image control</a></p>\n\n<p>The disadvantage with this memory stream method is that the image(s) get loaded and decoded every time and no caching can take place:\n\"To prevent images from being decoded more than once, assign the Image.Source property from an Uri rather than using memory streams\"\nSource: \"Performance tips for Windows Store apps using XAML\"</p>\n\n<p>To solve the performance issue, the repository pattern can be used to provide a caching layer. The caching could take place in memory, which may cause memory issues, or as thumbnail files that reside in a temp folder that can be cleared when the app exits.</p>\n"
},
{
"answer_id": 19480862,
"author": "Karthik Krishna Baiju",
"author_id": 2608383,
"author_profile": "https://Stackoverflow.com/users/2608383",
"pm_score": 3,
"selected": false,
"text": "<p>you may use</p>\n\n<blockquote>\n <p>ImageSourceConverter class</p>\n</blockquote>\n\n<p>to get what you want</p>\n\n<pre><code> img1.Source = (ImageSource)new ImageSourceConverter().ConvertFromString(\"/Assets/check.png\");\n</code></pre>\n"
}
] | 2008/08/21 | [
"https://Stackoverflow.com/questions/20586",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/373/"
] | I'm trying to bind a list of custom objects to a WPF Image like this:
```
<Image>
<Image.Source>
<BitmapImage UriSource="{Binding Path=ImagePath}" />
</Image.Source>
</Image>
```
But it doesn't work. This is the error I'm getting:
*"Property 'UriSource' or property 'StreamSource' must be set."*
What am I missing? | WPF has built-in converters for certain types. If you bind the Image's `Source` property to a `string` or `Uri` value, under the hood WPF will use an [ImageSourceConverter](https://msdn.microsoft.com/en-us/library/system.windows.media.imagesourceconverter(v=vs.110).aspx) to convert the value to an `ImageSource`.
So
```
<Image Source="{Binding ImageSource}"/>
```
would work if the ImageSource property was a string representation of a valid URI to an image.
You can of course roll your own Binding converter:
```cs
public class ImageConverter : IValueConverter
{
public object Convert(
object value, Type targetType, object parameter, CultureInfo culture)
{
return new BitmapImage(new Uri(value.ToString()));
}
public object ConvertBack(
object value, Type targetType, object parameter, CultureInfo culture)
{
throw new NotSupportedException();
}
}
```
and use it like this:
```
<Image Source="{Binding ImageSource, Converter={StaticResource ImageConverter}}"/>
``` |
20,587 | <p>I want to get the results of a stored procedure and place them into a CSV file onto an FTP location.</p>
<p>The catch though is that I cannot create a local/temporary file that I can then FTP over.</p>
<p>The approach I was taking was to use an SSIS package to create a temporary file and then have a FTP Task within the pack to FTP the file over, but our DBA's do not allow temporary files to be created on any servers.</p>
<h2><a href="https://stackoverflow.com/questions/20587/execute-stored-procedure-sql-2005-and-place-results-into-a-csv-file-on-a-ftp-lo#20596">in reply to Yaakov Ellis</a></h2>
<p>I think we will need to convince the DBA's to let me use at least a share on a server that they do not operate, or ask them how they would do it.</p>
<h2><a href="https://stackoverflow.com/questions/20587/execute-stored-procedure-sql-2005-and-place-results-into-a-csv-file-on-a-ftp-lo#20689">in reply to Kev</a></h2>
<p>I like the idea of the CLR integration, but I don't think our DBA's even know what that is <em>lol</em> and they would probably not allow it either. But I will probably be able to do this within a Script Task in an SSIS package that can be scheduled.</p>
| [
{
"answer_id": 20593,
"author": "Eric Z Beard",
"author_id": 1219,
"author_profile": "https://Stackoverflow.com/users/1219",
"pm_score": 0,
"selected": false,
"text": "<p>Try using a CLR stored procedure. You might be able to come up with something, but without first creating a temporary file, it might still be difficult. Could you set up a share on another machine and write to that, and then ftp from there?</p>\n"
},
{
"answer_id": 20596,
"author": "Yaakov Ellis",
"author_id": 51,
"author_profile": "https://Stackoverflow.com/users/51",
"pm_score": 1,
"selected": false,
"text": "<p>Is there a server anywhere that you can use where you can create a temporary file? If so, make a web service that returns an array containing the contents of the file. Call the web service from the computer where you can create a temporary file, use the contents of the array to build the temp file and ftp it over.</p>\n\n<p>If there is no where <em>at all</em> where you can create a temporary file, I don't see how you will be able to send anything by FTP.</p>\n"
},
{
"answer_id": 20689,
"author": "Kev",
"author_id": 419,
"author_profile": "https://Stackoverflow.com/users/419",
"pm_score": 3,
"selected": false,
"text": "<p>If you were allowed to implement CLR integration assemblies you could actually use FTP without having to write a temporary file:</p>\n\n<pre><code>public static void DoQueryAndUploadFile(string uri, string username, string password, string filename)\n{\n FtpWebRequest ftp = (FtpWebRequest)FtpWebRequest.Create(uri + \"/\" + filename);\n ftp.Method = WebRequestMethods.Ftp.UploadFile;\n ftp.Credentials = new System.Net.NetworkCredential(username, password);\n\n using(StreamWriter sw = new StreamWriter(ftp.GetRequestStream()))\n {\n // Do the query here then write to the ftp stream by iterating DataReader or other resultset, following code is just to demo concept:\n for (int i = 0; i < 100; i++)\n {\n sw.WriteLine(\"{0},row-{1},data-{2}\", i, i, i);\n }\n sw.Flush();\n }\n}\n</code></pre>\n"
},
{
"answer_id": 37239,
"author": "Mark Brackett",
"author_id": 2199,
"author_profile": "https://Stackoverflow.com/users/2199",
"pm_score": 0,
"selected": false,
"text": "<p>Script from the FTP server, and just call the stored proc.</p>\n"
},
{
"answer_id": 110552,
"author": "Michael Entin",
"author_id": 19880,
"author_profile": "https://Stackoverflow.com/users/19880",
"pm_score": 0,
"selected": false,
"text": "<blockquote>\n <p>The catch though is that I cannot create \n a local/temporary file that I can then FTP over.</p>\n</blockquote>\n\n<p>This restriction does not make any sense, try to talk to DBA nicely and explain it to him/her. It is totally reasonable for any Windows process or job to create temporary file(s) in appropriate location, i.e. %TEMP% folder. Actually, SSIS runtime itself often creates temporary files there - so if DBA allows you to run SSIS, he <strong>is</strong> allowing you to create temporary files :). </p>\n\n<p>As long as DBA understands that these temporary files do not create problem or additional workload for him (explain that he does <strong>not</strong> have to set special permissions, or back them up, etc), he should agree to let you create them.</p>\n\n<p>The only maintenance task for DBA is to periodically clean %TEMP% directory in case your SSIS job fails and leaves the file behind. But he should do this anyway, as many other processes may do the same. A simple SQL Agent job will do this.</p>\n"
},
{
"answer_id": 6800413,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 5,
"selected": true,
"text": "<p>This step-by-step example is for others who might stumble upon this question. This example uses <em>Windows Server 2008 R2 server</em> and <em>SSIS 2008 R2</em>. Even though, the example uses <em>SSIS 2008 R2</em>, the logic used is applicable to <em>SSIS 2005</em> as well. Thanks to <code>@Kev</code> for the <em>FTPWebRequest</em> code.</p>\n\n<p>Create an SSIS package (<a href=\"http://learnbycoding.com/2011/07/creating-a-simple-ssis-package-using-bids/\">Steps to create an SSIS package</a>). I have named the package in the format YYYYMMDD_hhmm in the beginning followed by <em>SO</em> stands for Stack Overflow, followed by the <em>SO question id</em>, and finally a description. I am not saying that you should name your package like this. This is for me to easily refer this back later. Note that I also have two Data Sources namely <em>Adventure Works</em> and <em>Practice DB</em>. I will be using <em>Adventure Works</em> data source, which points to <em>AdventureWorks</em> database downloaded from <a href=\"http://msftdbprodsamples.codeplex.com/\">this link</a>. Refer screenshot <strong>#1</strong> at the bottom of the answer.</p>\n\n<p>In the <em>AdventureWorks</em> database, create a stored procedure named <em>dbo.GetCurrency</em> using the below given script.</p>\n\n<pre><code>CREATE PROCEDURE [dbo].[GetCurrency]\nAS\nBEGIN\n SET NOCOUNT ON;\n SELECT \n TOP 10 CurrencyCode\n , Name\n , ModifiedDate \n FROM Sales.Currency\n ORDER BY CurrencyCode\nEND\nGO\n</code></pre>\n\n<p>On the package’s Connection Manager section, right-click and select <em>New Connection From Data Source</em>. On the <em>Select Data Source</em> dialog, select <em>Adventure Works</em> and click <em>OK</em>. You should now see the Adventure Works data source under the Connection Managers section. Refer screenshot <strong>#2</strong>, <strong>#3</strong> and <strong>#4</strong>.</p>\n\n<p>On the package, create the following variables. Refer screenshot <strong>#5</strong>.</p>\n\n<ul>\n<li><p><em>ColumnDelimiter</em>: This variable is of type String. This will be used to separate the column data when it is written to the file. In this example, we will be using comma (,) and the code is written to handle only displayable characters. For non-displayable characters like tab (\\t), you might need to change the code used in this example accordingly.</p></li>\n<li><p><em>FileName</em>: This variable is of type String. It will contain the name of the file. In this example, I have named the file as Currencies.csv because I am going to export list of currency names.</p></li>\n<li><p><em>FTPPassword</em>: This variable is of type String. This will contain the password to the FTP website. Ideally, the package should be encrypted to hide sensitive information.</p></li>\n<li><p><em>FTPRemotePath</em>: This variable is of type String. This will contain the FTP folder path to which the file should be uploaded to. For example if the complete FTP URI is <a href=\"ftp://myFTPSite.com/ssis/samples/uploads\">ftp://myFTPSite.com/ssis/samples/uploads</a>, then the RemotePath would be /ssis/samples/uploads.</p></li>\n<li><p><em>FTPServerName</em>: This variable is of type String. This will contain the FTP site root URI. For example if the complete FTP URI is <a href=\"ftp://myFTPSite.com/ssis/samples/uploads\">ftp://myFTPSite.com/ssis/samples/uploads</a>, then the FTPServerName would contain <a href=\"ftp://myFTPSite.com\">ftp://myFTPSite.com</a>. You can combine FTPRemotePath with this variable and have a single variable. It is up to your preference.</p></li>\n<li><p><em>FTPUserName</em>:This variable is of type String. This will contain the user name that will be used to connect to the FTP website.</p></li>\n<li><p><em>ListOfCurrencies</em>: This variable is of type Object. This will contain the result set from the stored procedure and it will be looped through in the Script Task.</p></li>\n<li><p><em>ShowHeader</em>: This variable is of type Boolean. This will contain values true/false. True indicates that the first row in the file will contain Column names and False indicates that the first row will not contain Column names.</p></li>\n<li><p><em>SQLGetData</em>: This variable is of type String. This will contain the Stored Procedure execution statement. This example uses the value EXEC dbo.GetCurrency</p></li>\n</ul>\n\n<p>On the package’s <em>Control Flow</em> tab, place an <em>Execute SQL Task</em> and name it as <em>Get Data</em>. Double-click on the Execute SQL Task to bring the <em>Execute SQL Task Editor</em>. On the <em>General</em> section of the <em>Execute SQL Task Editor</em>, set the <em>ResultSet</em> to <code>Full result set</code>, the <em>Connection</em> to <code>Adventure Works</code>, the <em>SQLSourceType</em> to <code>Variable</code> and the <em>SourceVariable</em> to <code>User::SQLGetData</code>. On the Result Set section, click Add button. Set the Result Name to <code>0</code>, this indicates the index and the Variable to <code>User::ListOfCurrencies</code>. The output of the stored procedure will be saved to this object variable. Click <em>OK</em>. Refer screenshot <strong>#6</strong> and <strong>#7</strong>.</p>\n\n<p>On the package’s <em>Control Flow</em> tab, place a Script Task below the Execute SQL Task and name it as <em>Save to FTP</em>. Double-click on the Script Task to bring the <em>Script Task Editor</em>. On the Script section, click the <code>Edit Script…</code> button. Refer screenshot <strong>#8</strong>. This will bring up the Visual Studio Tools for Applications (VSTA) editor. Replace the code within the class <code>ScriptMain</code> in the editor with the code given below. Also, make sure that you add the using statements to the namespaces <code>System.Data.OleDb</code>, <code>System.IO</code>, <code>System.Net</code>, <code>System.Text</code>. Refer screenshot <strong>#9</strong> that highlights the code changes. Close the VSTA editor and click Ok to close the Script Task Editor. Script code takes the object variable ListOfCurrencies and stores it into a DataTable with the help of OleDbDataAdapter because we are using OleDb connection. The code then loops through each row and if the variable ShowHeader is set to true, the code will include the Column names in the first row written to the file. The result is stored in a stringbuilder variable. After the string builder variable is populated with all the data, the code creates an FTPWebRequest object and connects to the FTP Uri by combining the variables FTPServerName, FTPRemotePath and FileName using the credentials provided in the variables FTPUserName and FTPPassword. Then the full string builder variable contents are written to the file. The method WriteRowData is created to loop through columns and provide the column names or data information based on the parameters passed.</p>\n\n<pre><code>using System;\nusing System.Data;\nusing Microsoft.SqlServer.Dts.Runtime;\nusing System.Windows.Forms;\nusing System.Data.OleDb;\nusing System.IO;\nusing System.Net;\nusing System.Text;\n\nnamespace ST_7033c2fc30234dae8086558a88a897dd.csproj\n{\n [System.AddIn.AddIn(\"ScriptMain\", Version = \"1.0\", Publisher = \"\", Description = \"\")]\n public partial class ScriptMain : Microsoft.SqlServer.Dts.Tasks.ScriptTask.VSTARTScriptObjectModelBase\n {\n\n #region VSTA generated code\n enum ScriptResults\n {\n Success = Microsoft.SqlServer.Dts.Runtime.DTSExecResult.Success,\n Failure = Microsoft.SqlServer.Dts.Runtime.DTSExecResult.Failure\n };\n #endregion\n\n public void Main()\n {\n Variables varCollection = null;\n\n Dts.VariableDispenser.LockForRead(\"User::ColumnDelimiter\");\n Dts.VariableDispenser.LockForRead(\"User::FileName\");\n Dts.VariableDispenser.LockForRead(\"User::FTPPassword\");\n Dts.VariableDispenser.LockForRead(\"User::FTPRemotePath\");\n Dts.VariableDispenser.LockForRead(\"User::FTPServerName\");\n Dts.VariableDispenser.LockForRead(\"User::FTPUserName\");\n Dts.VariableDispenser.LockForRead(\"User::ListOfCurrencies\");\n Dts.VariableDispenser.LockForRead(\"User::ShowHeader\");\n Dts.VariableDispenser.GetVariables(ref varCollection);\n\n OleDbDataAdapter dataAdapter = new OleDbDataAdapter();\n DataTable currencies = new DataTable();\n dataAdapter.Fill(currencies, varCollection[\"User::ListOfCurrencies\"].Value);\n\n bool showHeader = Convert.ToBoolean(varCollection[\"User::ShowHeader\"].Value);\n int rowCounter = 0;\n string columnDelimiter = varCollection[\"User::ColumnDelimiter\"].Value.ToString();\n StringBuilder sb = new StringBuilder();\n foreach (DataRow row in currencies.Rows)\n {\n rowCounter++;\n if (rowCounter == 1 && showHeader)\n {\n WriteRowData(currencies, row, columnDelimiter, true, ref sb);\n }\n\n WriteRowData(currencies, row, columnDelimiter, false, ref sb);\n }\n\n string ftpUri = string.Concat(varCollection[\"User::FTPServerName\"].Value,\n varCollection[\"User::FTPRemotePath\"].Value,\n varCollection[\"User::FileName\"].Value);\n\n FtpWebRequest ftp = (FtpWebRequest)FtpWebRequest.Create(ftpUri);\n ftp.Method = WebRequestMethods.Ftp.UploadFile;\n string ftpUserName = varCollection[\"User::FTPUserName\"].Value.ToString();\n string ftpPassword = varCollection[\"User::FTPPassword\"].Value.ToString();\n ftp.Credentials = new System.Net.NetworkCredential(ftpUserName, ftpPassword);\n\n using (StreamWriter sw = new StreamWriter(ftp.GetRequestStream()))\n {\n sw.WriteLine(sb.ToString());\n sw.Flush();\n }\n\n Dts.TaskResult = (int)ScriptResults.Success;\n }\n\n public void WriteRowData(DataTable currencies, DataRow row, string columnDelimiter, bool isHeader, ref StringBuilder sb)\n {\n int counter = 0;\n foreach (DataColumn column in currencies.Columns)\n {\n counter++;\n\n if (isHeader)\n {\n sb.Append(column.ColumnName);\n }\n else\n {\n sb.Append(row[column].ToString());\n }\n\n if (counter != currencies.Columns.Count)\n {\n sb.Append(columnDelimiter);\n }\n }\n sb.Append(System.Environment.NewLine);\n }\n }\n}\n</code></pre>\n\n<p>Once the tasks have been configured, the package’s Control Flow should look like as shown in screenshot <strong>#10</strong>.</p>\n\n<p>Screenshot <strong>#11</strong> shows the output of the stored procedure execution statement EXEC dbo.GetCurrency. </p>\n\n<p>Execute the package. Screenshot <strong>#12</strong> shows successful execution of the package.</p>\n\n<p>Using the <em>FireFTP</em> add-on available in <em>FireFox</em> browser, I logged into the FTP website and verified that the file has been successfully uploaded to the FTP website. Refer screenshot #<strong>13</strong>.</p>\n\n<p>Examining the contents by opening the file in Notepad++ shows that it matches with the stored procedure output. Refer screenshot #<strong>14</strong>.</p>\n\n<p>Thus, the example demonstrated how to write results from database to an FTP website without having to use temporary/local files.</p>\n\n<p>Hope that helps someone.</p>\n\n<p><strong>Screenshots:</strong></p>\n\n<p><strong>#1</strong>: Solution_Explorer</p>\n\n<p><img src=\"https://i.stack.imgur.com/1C8VG.png\" alt=\"Solution_Explorer\"></p>\n\n<p><strong>#2</strong>: New_Connection_From_Data_Source</p>\n\n<p><img src=\"https://i.stack.imgur.com/hYZqX.png\" alt=\"New_Connection_From_Data_Source\"></p>\n\n<p><strong>#3</strong>: Select_Data_Source</p>\n\n<p><img src=\"https://i.stack.imgur.com/ccxdu.png\" alt=\"Select_Data_Source\"></p>\n\n<p><strong>#4</strong>: Connection_Managers</p>\n\n<p><img src=\"https://i.stack.imgur.com/Rw8xv.png\" alt=\"Connection_Managers\"></p>\n\n<p><strong>#5</strong>: Variables</p>\n\n<p><img src=\"https://i.stack.imgur.com/Ov6Ac.png\" alt=\"Variables\"></p>\n\n<p><strong>#6</strong>: Execute_SQL_Task_Editor_General</p>\n\n<p><img src=\"https://i.stack.imgur.com/sMP6f.png\" alt=\"Execute_SQL_Task_Editor_General\"></p>\n\n<p><strong>#7</strong>: Execute_SQL_Task_Editor_Result_Set</p>\n\n<p><img src=\"https://i.stack.imgur.com/D7iKl.png\" alt=\"Execute_SQL_Task_Editor_Result_Set\"></p>\n\n<p><strong>#8</strong>: Script_Task_Editor</p>\n\n<p><img src=\"https://i.stack.imgur.com/Yz20f.png\" alt=\"Script_Task_Editor\"></p>\n\n<p><strong>#9</strong>: Script_Task_VSTA_Code</p>\n\n<p><img src=\"https://i.stack.imgur.com/C39Xc.png\" alt=\"Script_Task_VSTA_Code\"></p>\n\n<p><strong>#10</strong>: Control_Flow_Tab</p>\n\n<p><img src=\"https://i.stack.imgur.com/kFLeF.png\" alt=\"Control_Flow_Tab\"></p>\n\n<p><strong>#11</strong>: Query_Results</p>\n\n<p><img src=\"https://i.stack.imgur.com/t3aGT.png\" alt=\"Query_Results\"></p>\n\n<p><strong>#12</strong>: Package_Execution_Successful</p>\n\n<p><img src=\"https://i.stack.imgur.com/tYKwu.png\" alt=\"Package_Execution_Successful\"></p>\n\n<p><strong>#13</strong>: File_In_FTP</p>\n\n<p><img src=\"https://i.stack.imgur.com/Yt8fD.png\" alt=\"File_In_FTP\"></p>\n\n<p><strong>#14</strong>: File_Contents</p>\n\n<p><img src=\"https://i.stack.imgur.com/nuf2M.png\" alt=\"File_Contents\"></p>\n"
}
] | 2008/08/21 | [
"https://Stackoverflow.com/questions/20587",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1950/"
] | I want to get the results of a stored procedure and place them into a CSV file onto an FTP location.
The catch though is that I cannot create a local/temporary file that I can then FTP over.
The approach I was taking was to use an SSIS package to create a temporary file and then have a FTP Task within the pack to FTP the file over, but our DBA's do not allow temporary files to be created on any servers.
[in reply to Yaakov Ellis](https://stackoverflow.com/questions/20587/execute-stored-procedure-sql-2005-and-place-results-into-a-csv-file-on-a-ftp-lo#20596)
-----------------------------------------------------------------------------------------------------------------------------------------------------------
I think we will need to convince the DBA's to let me use at least a share on a server that they do not operate, or ask them how they would do it.
[in reply to Kev](https://stackoverflow.com/questions/20587/execute-stored-procedure-sql-2005-and-place-results-into-a-csv-file-on-a-ftp-lo#20689)
--------------------------------------------------------------------------------------------------------------------------------------------------
I like the idea of the CLR integration, but I don't think our DBA's even know what that is *lol* and they would probably not allow it either. But I will probably be able to do this within a Script Task in an SSIS package that can be scheduled. | This step-by-step example is for others who might stumble upon this question. This example uses *Windows Server 2008 R2 server* and *SSIS 2008 R2*. Even though, the example uses *SSIS 2008 R2*, the logic used is applicable to *SSIS 2005* as well. Thanks to `@Kev` for the *FTPWebRequest* code.
Create an SSIS package ([Steps to create an SSIS package](http://learnbycoding.com/2011/07/creating-a-simple-ssis-package-using-bids/)). I have named the package in the format YYYYMMDD\_hhmm in the beginning followed by *SO* stands for Stack Overflow, followed by the *SO question id*, and finally a description. I am not saying that you should name your package like this. This is for me to easily refer this back later. Note that I also have two Data Sources namely *Adventure Works* and *Practice DB*. I will be using *Adventure Works* data source, which points to *AdventureWorks* database downloaded from [this link](http://msftdbprodsamples.codeplex.com/). Refer screenshot **#1** at the bottom of the answer.
In the *AdventureWorks* database, create a stored procedure named *dbo.GetCurrency* using the below given script.
```
CREATE PROCEDURE [dbo].[GetCurrency]
AS
BEGIN
SET NOCOUNT ON;
SELECT
TOP 10 CurrencyCode
, Name
, ModifiedDate
FROM Sales.Currency
ORDER BY CurrencyCode
END
GO
```
On the package’s Connection Manager section, right-click and select *New Connection From Data Source*. On the *Select Data Source* dialog, select *Adventure Works* and click *OK*. You should now see the Adventure Works data source under the Connection Managers section. Refer screenshot **#2**, **#3** and **#4**.
On the package, create the following variables. Refer screenshot **#5**.
* *ColumnDelimiter*: This variable is of type String. This will be used to separate the column data when it is written to the file. In this example, we will be using comma (,) and the code is written to handle only displayable characters. For non-displayable characters like tab (\t), you might need to change the code used in this example accordingly.
* *FileName*: This variable is of type String. It will contain the name of the file. In this example, I have named the file as Currencies.csv because I am going to export list of currency names.
* *FTPPassword*: This variable is of type String. This will contain the password to the FTP website. Ideally, the package should be encrypted to hide sensitive information.
* *FTPRemotePath*: This variable is of type String. This will contain the FTP folder path to which the file should be uploaded to. For example if the complete FTP URI is <ftp://myFTPSite.com/ssis/samples/uploads>, then the RemotePath would be /ssis/samples/uploads.
* *FTPServerName*: This variable is of type String. This will contain the FTP site root URI. For example if the complete FTP URI is <ftp://myFTPSite.com/ssis/samples/uploads>, then the FTPServerName would contain <ftp://myFTPSite.com>. You can combine FTPRemotePath with this variable and have a single variable. It is up to your preference.
* *FTPUserName*:This variable is of type String. This will contain the user name that will be used to connect to the FTP website.
* *ListOfCurrencies*: This variable is of type Object. This will contain the result set from the stored procedure and it will be looped through in the Script Task.
* *ShowHeader*: This variable is of type Boolean. This will contain values true/false. True indicates that the first row in the file will contain Column names and False indicates that the first row will not contain Column names.
* *SQLGetData*: This variable is of type String. This will contain the Stored Procedure execution statement. This example uses the value EXEC dbo.GetCurrency
On the package’s *Control Flow* tab, place an *Execute SQL Task* and name it as *Get Data*. Double-click on the Execute SQL Task to bring the *Execute SQL Task Editor*. On the *General* section of the *Execute SQL Task Editor*, set the *ResultSet* to `Full result set`, the *Connection* to `Adventure Works`, the *SQLSourceType* to `Variable` and the *SourceVariable* to `User::SQLGetData`. On the Result Set section, click Add button. Set the Result Name to `0`, this indicates the index and the Variable to `User::ListOfCurrencies`. The output of the stored procedure will be saved to this object variable. Click *OK*. Refer screenshot **#6** and **#7**.
On the package’s *Control Flow* tab, place a Script Task below the Execute SQL Task and name it as *Save to FTP*. Double-click on the Script Task to bring the *Script Task Editor*. On the Script section, click the `Edit Script…` button. Refer screenshot **#8**. This will bring up the Visual Studio Tools for Applications (VSTA) editor. Replace the code within the class `ScriptMain` in the editor with the code given below. Also, make sure that you add the using statements to the namespaces `System.Data.OleDb`, `System.IO`, `System.Net`, `System.Text`. Refer screenshot **#9** that highlights the code changes. Close the VSTA editor and click Ok to close the Script Task Editor. Script code takes the object variable ListOfCurrencies and stores it into a DataTable with the help of OleDbDataAdapter because we are using OleDb connection. The code then loops through each row and if the variable ShowHeader is set to true, the code will include the Column names in the first row written to the file. The result is stored in a stringbuilder variable. After the string builder variable is populated with all the data, the code creates an FTPWebRequest object and connects to the FTP Uri by combining the variables FTPServerName, FTPRemotePath and FileName using the credentials provided in the variables FTPUserName and FTPPassword. Then the full string builder variable contents are written to the file. The method WriteRowData is created to loop through columns and provide the column names or data information based on the parameters passed.
```
using System;
using System.Data;
using Microsoft.SqlServer.Dts.Runtime;
using System.Windows.Forms;
using System.Data.OleDb;
using System.IO;
using System.Net;
using System.Text;
namespace ST_7033c2fc30234dae8086558a88a897dd.csproj
{
[System.AddIn.AddIn("ScriptMain", Version = "1.0", Publisher = "", Description = "")]
public partial class ScriptMain : Microsoft.SqlServer.Dts.Tasks.ScriptTask.VSTARTScriptObjectModelBase
{
#region VSTA generated code
enum ScriptResults
{
Success = Microsoft.SqlServer.Dts.Runtime.DTSExecResult.Success,
Failure = Microsoft.SqlServer.Dts.Runtime.DTSExecResult.Failure
};
#endregion
public void Main()
{
Variables varCollection = null;
Dts.VariableDispenser.LockForRead("User::ColumnDelimiter");
Dts.VariableDispenser.LockForRead("User::FileName");
Dts.VariableDispenser.LockForRead("User::FTPPassword");
Dts.VariableDispenser.LockForRead("User::FTPRemotePath");
Dts.VariableDispenser.LockForRead("User::FTPServerName");
Dts.VariableDispenser.LockForRead("User::FTPUserName");
Dts.VariableDispenser.LockForRead("User::ListOfCurrencies");
Dts.VariableDispenser.LockForRead("User::ShowHeader");
Dts.VariableDispenser.GetVariables(ref varCollection);
OleDbDataAdapter dataAdapter = new OleDbDataAdapter();
DataTable currencies = new DataTable();
dataAdapter.Fill(currencies, varCollection["User::ListOfCurrencies"].Value);
bool showHeader = Convert.ToBoolean(varCollection["User::ShowHeader"].Value);
int rowCounter = 0;
string columnDelimiter = varCollection["User::ColumnDelimiter"].Value.ToString();
StringBuilder sb = new StringBuilder();
foreach (DataRow row in currencies.Rows)
{
rowCounter++;
if (rowCounter == 1 && showHeader)
{
WriteRowData(currencies, row, columnDelimiter, true, ref sb);
}
WriteRowData(currencies, row, columnDelimiter, false, ref sb);
}
string ftpUri = string.Concat(varCollection["User::FTPServerName"].Value,
varCollection["User::FTPRemotePath"].Value,
varCollection["User::FileName"].Value);
FtpWebRequest ftp = (FtpWebRequest)FtpWebRequest.Create(ftpUri);
ftp.Method = WebRequestMethods.Ftp.UploadFile;
string ftpUserName = varCollection["User::FTPUserName"].Value.ToString();
string ftpPassword = varCollection["User::FTPPassword"].Value.ToString();
ftp.Credentials = new System.Net.NetworkCredential(ftpUserName, ftpPassword);
using (StreamWriter sw = new StreamWriter(ftp.GetRequestStream()))
{
sw.WriteLine(sb.ToString());
sw.Flush();
}
Dts.TaskResult = (int)ScriptResults.Success;
}
public void WriteRowData(DataTable currencies, DataRow row, string columnDelimiter, bool isHeader, ref StringBuilder sb)
{
int counter = 0;
foreach (DataColumn column in currencies.Columns)
{
counter++;
if (isHeader)
{
sb.Append(column.ColumnName);
}
else
{
sb.Append(row[column].ToString());
}
if (counter != currencies.Columns.Count)
{
sb.Append(columnDelimiter);
}
}
sb.Append(System.Environment.NewLine);
}
}
}
```
Once the tasks have been configured, the package’s Control Flow should look like as shown in screenshot **#10**.
Screenshot **#11** shows the output of the stored procedure execution statement EXEC dbo.GetCurrency.
Execute the package. Screenshot **#12** shows successful execution of the package.
Using the *FireFTP* add-on available in *FireFox* browser, I logged into the FTP website and verified that the file has been successfully uploaded to the FTP website. Refer screenshot #**13**.
Examining the contents by opening the file in Notepad++ shows that it matches with the stored procedure output. Refer screenshot #**14**.
Thus, the example demonstrated how to write results from database to an FTP website without having to use temporary/local files.
Hope that helps someone.
**Screenshots:**
**#1**: Solution\_Explorer

**#2**: New\_Connection\_From\_Data\_Source

**#3**: Select\_Data\_Source

**#4**: Connection\_Managers

**#5**: Variables

**#6**: Execute\_SQL\_Task\_Editor\_General

**#7**: Execute\_SQL\_Task\_Editor\_Result\_Set

**#8**: Script\_Task\_Editor

**#9**: Script\_Task\_VSTA\_Code

**#10**: Control\_Flow\_Tab

**#11**: Query\_Results

**#12**: Package\_Execution\_Successful

**#13**: File\_In\_FTP

**#14**: File\_Contents
 |
20,598 | <p>I'm interested in doing comparisons between the date string and the MySQL timestamp. However, I'm not seeing an easy conversion. Am I overlooking something obvious?</p>
| [
{
"answer_id": 20605,
"author": "Ross",
"author_id": 2025,
"author_profile": "https://Stackoverflow.com/users/2025",
"pm_score": 5,
"selected": true,
"text": "<p>Converting from timestamp to format:</p>\n\n<pre><code>date('Y-m-d', $timestamp);\n</code></pre>\n\n<p>Converting from formatted to timestamp:</p>\n\n<pre><code>mktime(0, 0, 0, $month, $day, $year, $is_dst);\n</code></pre>\n\n<p>See <a href=\"http://www.php.net/manual/en/function.date.php\" rel=\"noreferrer\">date</a> and <a href=\"http://www.php.net/manual/en/function.mktime.php\" rel=\"noreferrer\">mktime</a> for further documentation.</p>\n\n<p>When it comes to storing it's up to you whether to use the MySQL DATE format for stroing as a formatted date; as an integer for storing as a UNIX timestamp; or you can use MySQL's TIMESTAMP format which converts a numeric timestamp into a readable format. <a href=\"http://dev.mysql.com/doc/refman/5.0/en/datetime.html\" rel=\"noreferrer\">Check the MySQL Doc</a> for TIMESTAMP info.</p>\n"
},
{
"answer_id": 20607,
"author": "Nate Smith",
"author_id": 1238,
"author_profile": "https://Stackoverflow.com/users/1238",
"pm_score": 0,
"selected": false,
"text": "<p><a href=\"http://ca.php.net/manual/en/function.strtotime.php\" rel=\"nofollow noreferrer\">strtotime()</a> and <a href=\"http://ca.php.net/manual/en/function.getdate.php\" rel=\"nofollow noreferrer\">getdate()</a> are two functions that can be used to get dates from strings and timestamps. There isn't a standard library function that converts between MySQL and PHP timestamps though.</p>\n"
},
{
"answer_id": 20608,
"author": "Yaakov Ellis",
"author_id": 51,
"author_profile": "https://Stackoverflow.com/users/51",
"pm_score": 0,
"selected": false,
"text": "<p>Use the PHP <a href=\"http://il2.php.net/date\" rel=\"nofollow noreferrer\">Date</a> function. You may have to convert the mysql timestamp to a Unix timestamp in your query using the <a href=\"http://dev.mysql.com/doc/refman/5.0/en/date-and-time-functions.html\" rel=\"nofollow noreferrer\">UNIX_TIMESTAMP</a> function in mysql.</p>\n"
},
{
"answer_id": 20668,
"author": "Jake McGraw",
"author_id": 302,
"author_profile": "https://Stackoverflow.com/users/302",
"pm_score": 0,
"selected": false,
"text": "<p>A date string of the form:</p>\n\n<pre><code>YYYY-MM-DD\n</code></pre>\n\n<p>has no time associated with it. A MySQL Timestamp is of the form:</p>\n\n<pre><code>YYYY-MM-DD HH:mm:ss\n</code></pre>\n\n<p>to compare the two, you'll either have to add a time to the date string, like midnight for example</p>\n\n<pre><code>$datetime = '2008-08-21'.' 00:00:00';\n</code></pre>\n\n<p>and then use a function to compare the epoc time between them</p>\n\n<pre><code>if (strtotime($datetime) > strtotime($timestamp)) {\n echo 'Datetime later';\n} else {\n echo 'Timestamp equal or greater';\n}\n</code></pre>\n"
},
{
"answer_id": 30471,
"author": "jonthornton",
"author_id": 3250,
"author_profile": "https://Stackoverflow.com/users/3250",
"pm_score": 2,
"selected": false,
"text": "<p>You can avoid having to use <code>strtotime()</code> or <code>getdate()</code> in <strong>PHP</strong> by using MySQL's <code>UNIX_TIMESTAMP()</code> function.</p>\n\n<pre><code>SELECT UNIX_TIMESTAMP(timestamp) FROM sometable\n</code></pre>\n\n<p>The resulting data will be a standard integer Unix timestamp, so you can do a direct comparison to <code>time()</code>.</p>\n"
},
{
"answer_id": 635809,
"author": "St. John Johnson",
"author_id": 76734,
"author_profile": "https://Stackoverflow.com/users/76734",
"pm_score": 2,
"selected": false,
"text": "<p>I wrote this little function to simplify the process: </p>\n\n<pre><code>/**\n * Convert MySQL datetime to PHP time\n */\nfunction convert_datetime($datetime) {\n //example: 2008-02-07 12:19:32\n $values = split(\" \", $datetime);\n\n $dates = split(\"-\", $values[0]);\n $times = split(\":\", $values[1]);\n\n $newdate = mktime($times[0], $times[1], $times[2], $dates[1], $dates[2], $dates[0]);\n\n return $newdate;\n}\n</code></pre>\n\n<p>I hope this helps</p>\n"
}
] | 2008/08/21 | [
"https://Stackoverflow.com/questions/20598",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/572/"
] | I'm interested in doing comparisons between the date string and the MySQL timestamp. However, I'm not seeing an easy conversion. Am I overlooking something obvious? | Converting from timestamp to format:
```
date('Y-m-d', $timestamp);
```
Converting from formatted to timestamp:
```
mktime(0, 0, 0, $month, $day, $year, $is_dst);
```
See [date](http://www.php.net/manual/en/function.date.php) and [mktime](http://www.php.net/manual/en/function.mktime.php) for further documentation.
When it comes to storing it's up to you whether to use the MySQL DATE format for stroing as a formatted date; as an integer for storing as a UNIX timestamp; or you can use MySQL's TIMESTAMP format which converts a numeric timestamp into a readable format. [Check the MySQL Doc](http://dev.mysql.com/doc/refman/5.0/en/datetime.html) for TIMESTAMP info. |
20,611 | <p>The following code should find the appropriate project tag and remove it from the XmlDocument, however when I test it, it says:</p>
<p><strong>The node to be removed is not a child of this node.</strong></p>
<p>Does anyone know the proper way to do this?</p>
<pre><code>public void DeleteProject (string projectName)
{
string ccConfigPath = ConfigurationManager.AppSettings["ConfigPath"];
XmlDocument configDoc = new XmlDocument();
configDoc.Load(ccConfigPath);
XmlNodeList projectNodes = configDoc.GetElementsByTagName("project");
for (int i = 0; i < projectNodes.Count; i++)
{
if (projectNodes[i].Attributes["name"] != null)
{
if (projectName == projectNodes[i].Attributes["name"].InnerText)
{
configDoc.RemoveChild(projectNodes[i]);
configDoc.Save(ccConfigPath);
}
}
}
}
</code></pre>
<p><strong>UPDATE</strong></p>
<p>Fixed. I did two things:</p>
<pre><code>XmlNode project = configDoc.SelectSingleNode("//project[@name='" + projectName + "']");
</code></pre>
<p>Replaced the For loop with an XPath query, which wasn't for fixing it, just because it was a better approach.</p>
<p>The actual fix was:</p>
<pre><code>project.ParentNode.RemoveChild(project);
</code></pre>
<p>Thanks Pat and Chuck for this suggestion.</p>
| [
{
"answer_id": 20614,
"author": "Greg Hurlman",
"author_id": 35,
"author_profile": "https://Stackoverflow.com/users/35",
"pm_score": 1,
"selected": false,
"text": "<p>Is it possible that the project nodes aren't child nodes, but grandchildren or lower? GetElementsByTagName will give you elements from anywhere in the child element tree, IIRC.</p>\n"
},
{
"answer_id": 20624,
"author": "David Hayes",
"author_id": 1769,
"author_profile": "https://Stackoverflow.com/users/1769",
"pm_score": 0,
"selected": false,
"text": "<p>It would be handy to see a sample of the XML file you're processing but my guess would be that you have something like this</p>\n\n<pre><code><Root>\n <Blah>\n <project>...</project>\n </Blah>\n</Root>\n</code></pre>\n\n<p>The error message seems to be because you're trying to remove <code><project></code> from the grandparent rather than the direct parent of the project node</p>\n"
},
{
"answer_id": 20625,
"author": "Pat",
"author_id": 238,
"author_profile": "https://Stackoverflow.com/users/238",
"pm_score": 7,
"selected": true,
"text": "<p>Instead of </p>\n\n<pre><code>configDoc.RemoveChild(projectNodes[i]);\n</code></pre>\n\n<p>try </p>\n\n<pre><code>projectNodes[i].parentNode.RemoveChild(projectNodes[i]);\n</code></pre>\n"
},
{
"answer_id": 20629,
"author": "Jason",
"author_id": 1338,
"author_profile": "https://Stackoverflow.com/users/1338",
"pm_score": 2,
"selected": false,
"text": "<p>try </p>\n\n<pre><code>configDoc.DocumentElement.RemoveChild(projectNodes[i]);\n</code></pre>\n"
},
{
"answer_id": 20636,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 2,
"selected": false,
"text": "<p>Looks like you need to select the parent node of projectNodes[i] before calling RemoveChild.</p>\n"
},
{
"answer_id": 11116820,
"author": "Eugene Ryabtsev",
"author_id": 1353187,
"author_profile": "https://Stackoverflow.com/users/1353187",
"pm_score": 1,
"selected": false,
"text": "<p>When you get sufficiently annoyed by writing it the long way (for me that was fairly soon) you can use a helper extension method provided below. Yay new technology!</p>\n\n<pre><code>public static class Extensions {\n ...\n public static XmlNode RemoveFromParent(this XmlNode node) {\n return (node == null) ? null : node.ParentNode.RemoveChild(node);\n }\n}\n...\n//some_long_node_expression.parentNode.RemoveChild(some_long_node_expression);\nsome_long_node_expression.RemoveFromParent();\n</code></pre>\n"
}
] | 2008/08/21 | [
"https://Stackoverflow.com/questions/20611",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1965/"
] | The following code should find the appropriate project tag and remove it from the XmlDocument, however when I test it, it says:
**The node to be removed is not a child of this node.**
Does anyone know the proper way to do this?
```
public void DeleteProject (string projectName)
{
string ccConfigPath = ConfigurationManager.AppSettings["ConfigPath"];
XmlDocument configDoc = new XmlDocument();
configDoc.Load(ccConfigPath);
XmlNodeList projectNodes = configDoc.GetElementsByTagName("project");
for (int i = 0; i < projectNodes.Count; i++)
{
if (projectNodes[i].Attributes["name"] != null)
{
if (projectName == projectNodes[i].Attributes["name"].InnerText)
{
configDoc.RemoveChild(projectNodes[i]);
configDoc.Save(ccConfigPath);
}
}
}
}
```
**UPDATE**
Fixed. I did two things:
```
XmlNode project = configDoc.SelectSingleNode("//project[@name='" + projectName + "']");
```
Replaced the For loop with an XPath query, which wasn't for fixing it, just because it was a better approach.
The actual fix was:
```
project.ParentNode.RemoveChild(project);
```
Thanks Pat and Chuck for this suggestion. | Instead of
```
configDoc.RemoveChild(projectNodes[i]);
```
try
```
projectNodes[i].parentNode.RemoveChild(projectNodes[i]);
``` |
20,674 | <p>Other than <code>self.class.send :method, args...</code>, of course. I'd like to make a rather complex method available at both the class and instance level without duplicating the code.</p>
<hr>
<p><strong>UPDATE:</strong> </p>
<p>@Jonathan Branam: that was my assumption, but I wanted to make sure nobody else had found a way around. Visibility in Ruby is very different from that in Java. You're also quite right that <code>private</code> doesn't work on class methods, though this will declare a private class method:</p>
<pre><code>class Foo
class <<self
private
def bar
puts 'bar'
end
end
end
Foo.bar
# => NoMethodError: private method 'bar' called for Foo:Class
</code></pre>
| [
{
"answer_id": 20690,
"author": "John",
"author_id": 2168,
"author_profile": "https://Stackoverflow.com/users/2168",
"pm_score": -1,
"selected": false,
"text": "<p>Unless I'm misunderstanding, don't you just need something like this:</p>\n\n<pre><code>class Foo\n private\n def Foo.bar\n # Complex logic goes here\n puts \"hi\"\n end\n\n public\n def bar\n Foo.bar\n end\nend\n</code></pre>\n\n<p>Of course you could change the second definition to use your self.class.send approach if you wanted to avoid hardcoding the class name... </p>\n"
},
{
"answer_id": 20746,
"author": "Jonathan Branam",
"author_id": 2347,
"author_profile": "https://Stackoverflow.com/users/2347",
"pm_score": 5,
"selected": true,
"text": "<p>Here is a code snippet to go along with the question. Using \"private\" in a class definition does not apply to class methods. You need to use \"private_class_method\" as in the following example.</p>\n\n<pre><code>class Foo\n def self.private_bar\n # Complex logic goes here\n puts \"hi\"\n end\n private_class_method :private_bar\n class <<self\n private\n def another_private_bar\n puts \"bar\"\n end\n end\n public\n def instance_bar\n self.class.private_bar\n end\n def instance_bar2\n self.class.another_private_bar\n end\nend\n\nf=Foo.new\nf=instance_bar # NoMethodError: private method `private_bar' called for Foo:Class\nf=instance_bar2 # NoMethodError: private method `another_private_bar' called for Foo:Class\n</code></pre>\n\n<p>I don't see a way to get around this. The documentation says that you cannot specify the receive of a private method. Also you can only access a private method from the same instance. The class Foo is a different object than a given instance of Foo.</p>\n\n<p>Don't take my answer as final. I'm certainly not an expert, but I wanted to provide a code snippet so that others who attempt to answer will have properly private class methods.</p>\n"
},
{
"answer_id": 8543280,
"author": "Andrew Grimm",
"author_id": 38765,
"author_profile": "https://Stackoverflow.com/users/38765",
"pm_score": 0,
"selected": false,
"text": "<p>If your method is merely a <a href=\"https://github.com/kevinrutherford/reek/wiki/utility-function\" rel=\"nofollow\">utility function</a> (that is, it doesn't rely on any instance variables), you could put the method into a module and <code>include</code> and <code>extend</code> the class so that it's available as both a private class method and a private instance method.</p>\n"
},
{
"answer_id": 11322794,
"author": "magicgregz",
"author_id": 1169468,
"author_profile": "https://Stackoverflow.com/users/1169468",
"pm_score": 0,
"selected": false,
"text": "<p>This is the way to play with \"real\" private class methods.</p>\n\n<pre><code>class Foo\n def self.private_bar\n # Complex logic goes here\n puts \"hi\"\n end\n private_class_method :private_bar\n class <<self\n private\n def another_private_bar\n puts \"bar\"\n end\n end\n public\n def instance_bar\n self.class.private_bar\n end\n def instance_bar2\n self.class.another_private_bar\n end\n def calling_private_method\n Foo.send :another_private_bar\n self.class.send :private_bar\n end\nend\nf=Foo.new\nf.send :calling_private_method \n # \"bar\"\n # \"hi\"\nFoo.send :another_private_bar\n# \"bar\"\n</code></pre>\n\n<p>cheers</p>\n"
},
{
"answer_id": 24224054,
"author": "Alexey",
"author_id": 898649,
"author_profile": "https://Stackoverflow.com/users/898649",
"pm_score": 3,
"selected": false,
"text": "<p>Let me contribute to this list of more or less strange solutions and non-solutions:</p>\n\n<pre class=\"lang-rb prettyprint-override\"><code>puts RUBY_VERSION # => 2.1.2\n\nclass C\n class << self\n private def foo\n 'Je suis foo'\n end\n end\n\n private define_method :foo, &method(:foo)\n\n def bar\n foo\n end\nend\n\nputs C.new.bar # => Je suis foo\nputs C.new.foo # => NoMethodError\n</code></pre>\n"
},
{
"answer_id": 35921805,
"author": "Michael Krupp",
"author_id": 1986344,
"author_profile": "https://Stackoverflow.com/users/1986344",
"pm_score": 2,
"selected": false,
"text": "<p>Nowadays you don't need the helper methods anymore. You can simply inline them with your method definition. This should feel very familiar to the Java folks:</p>\n\n<pre><code>class MyClass\n\n private_class_method def self.my_private_method\n puts \"private class method\"\n end\n\n private def my_private_method\n puts \"private instance method\"\n end\n\nend\n</code></pre>\n\n<p>And no, you cannot call a private class method from an instance method. However, you could instead implement the the <strong>private</strong> class method as <strong>public</strong> class method in a <strong>private</strong> nested class instead, using the <code>private_constant</code> helper method. See <a href=\"https://blog.arkency.com/2016/02/private-classes-in-ruby/\" rel=\"nofollow\">this blogpost</a> for more detail.</p>\n"
},
{
"answer_id": 55486235,
"author": "Kache",
"author_id": 234593,
"author_profile": "https://Stackoverflow.com/users/234593",
"pm_score": 0,
"selected": false,
"text": "<p>This is probably the most \"native vanilla Ruby\" way:</p>\n\n<pre><code>class Foo\n module PrivateStatic # like Java\n private def foo\n 'foo'\n end\n end\n extend PrivateStatic\n include PrivateStatic\n\n def self.static_public_call\n \"static public #{foo}\"\n end\n\n def public_call\n \"instance public #{foo}\"\n end\nend\n\nFoo.static_public_call # 'static public foo'\nFoo.new.public_call # 'instance public foo'\nFoo.foo # NoMethodError: private method `foo' called for Foo:Class\nFoo.new.foo # NoMethodError: private method `foo' called for #<Foo:0x00007fa154d13f10>\n</code></pre>\n\n<p>With some Ruby metaprogramming, you could even make it look like:</p>\n\n<pre><code>class Foo\n def self.foo\n 'foo'\n end\n\n extend PrivateStatic\n private_static :foo\nend\n</code></pre>\n\n<p>Ruby's metaprogramming is quite powerful, so you could technically implement any scoping rules you might want. That being said, I'd still prefer the clarity and <a href=\"https://en.wikipedia.org/wiki/Principle_of_least_astonishment\" rel=\"nofollow noreferrer\">minimal surprise</a> of the first variant.</p>\n"
}
] | 2008/08/21 | [
"https://Stackoverflow.com/questions/20674",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1190/"
] | Other than `self.class.send :method, args...`, of course. I'd like to make a rather complex method available at both the class and instance level without duplicating the code.
---
**UPDATE:**
@Jonathan Branam: that was my assumption, but I wanted to make sure nobody else had found a way around. Visibility in Ruby is very different from that in Java. You're also quite right that `private` doesn't work on class methods, though this will declare a private class method:
```
class Foo
class <<self
private
def bar
puts 'bar'
end
end
end
Foo.bar
# => NoMethodError: private method 'bar' called for Foo:Class
``` | Here is a code snippet to go along with the question. Using "private" in a class definition does not apply to class methods. You need to use "private\_class\_method" as in the following example.
```
class Foo
def self.private_bar
# Complex logic goes here
puts "hi"
end
private_class_method :private_bar
class <<self
private
def another_private_bar
puts "bar"
end
end
public
def instance_bar
self.class.private_bar
end
def instance_bar2
self.class.another_private_bar
end
end
f=Foo.new
f=instance_bar # NoMethodError: private method `private_bar' called for Foo:Class
f=instance_bar2 # NoMethodError: private method `another_private_bar' called for Foo:Class
```
I don't see a way to get around this. The documentation says that you cannot specify the receive of a private method. Also you can only access a private method from the same instance. The class Foo is a different object than a given instance of Foo.
Don't take my answer as final. I'm certainly not an expert, but I wanted to provide a code snippet so that others who attempt to answer will have properly private class methods. |
20,696 | <p>In E (specman) I want to declare variables that are lists, and I want to fix their lengths.</p>
<p>It's easy to do for a member of a struct:</p>
<pre><code>thread[2] : list of thread_t;
</code></pre>
<p>while for a "regular" variable in a function the above doesn't work, and I have to do something like:</p>
<pre><code>var warned : list of bool;
gen warned keeping {
it.size() == 5;
};
</code></pre>
<p>Is there a better way to declare a list of fixed size?</p>
| [
{
"answer_id": 28801,
"author": "Joel Coehoorn",
"author_id": 3043,
"author_profile": "https://Stackoverflow.com/users/3043",
"pm_score": -1,
"selected": false,
"text": "<p>I know nothing of specman, but a fixed sized list is an array, so that might point you somewhere.</p>\n"
},
{
"answer_id": 37438,
"author": "JawnV6",
"author_id": 3869,
"author_profile": "https://Stackoverflow.com/users/3869",
"pm_score": 3,
"selected": true,
"text": "<p>A hard keep like you have is only going to fix the size at initialization but elements could still be added or dropped later, are you trying to guard against this condition? The only way I can think of to guarantee that elements aren't added or dropped later is emitting an event synced on the size != the predetermined amount:</p>\n\n<pre><code>event list_size_changed is true (wanted.size() != 5) @clk;\n</code></pre>\n\n<p>The only other thing that I can offer is a bit of syntactic sugar for the hard keep:</p>\n\n<pre><code>var warned : list of bool;\nkeep warned.size() == 5;\n</code></pre>\n"
}
] | 2008/08/21 | [
"https://Stackoverflow.com/questions/20696",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1084/"
] | In E (specman) I want to declare variables that are lists, and I want to fix their lengths.
It's easy to do for a member of a struct:
```
thread[2] : list of thread_t;
```
while for a "regular" variable in a function the above doesn't work, and I have to do something like:
```
var warned : list of bool;
gen warned keeping {
it.size() == 5;
};
```
Is there a better way to declare a list of fixed size? | A hard keep like you have is only going to fix the size at initialization but elements could still be added or dropped later, are you trying to guard against this condition? The only way I can think of to guarantee that elements aren't added or dropped later is emitting an event synced on the size != the predetermined amount:
```
event list_size_changed is true (wanted.size() != 5) @clk;
```
The only other thing that I can offer is a bit of syntactic sugar for the hard keep:
```
var warned : list of bool;
keep warned.size() == 5;
``` |
20,722 | <p>How can I efficiently and effectively detect the version and, for that matter, any available information about the instance of <a href="http://silverlight.net/" rel="nofollow noreferrer">Silverlight</a> currently running on the browser?</p>
| [
{
"answer_id": 20729,
"author": "Stu",
"author_id": 414,
"author_profile": "https://Stackoverflow.com/users/414",
"pm_score": 0,
"selected": false,
"text": "<p>Look in silverlight.js:</p>\n\n<p><a href=\"http://forums.asp.net/p/1135746/1997617.aspx#1997617\" rel=\"nofollow noreferrer\">http://forums.asp.net/p/1135746/1997617.aspx#1997617</a></p>\n"
},
{
"answer_id": 20745,
"author": "Bryan Roth",
"author_id": 299,
"author_profile": "https://Stackoverflow.com/users/299",
"pm_score": 2,
"selected": false,
"text": "<p>I got this from <a href=\"http://forums.asp.net/p/1135746/1997617.aspx#1997617\" rel=\"nofollow noreferrer\">http://forums.asp.net/p/1135746/1997617.aspx#1997617</a> which is the same link <a href=\"https://stackoverflow.com/users/414/stu\">Stu</a> gave you. I just included the code snippet.</p>\n\n<pre><code>Silverlight.isInstalled = function(d)\n{\n var c = false, a = null;\n try\n {\n var b = null;\n if(Silverlight.ua.Browser == \"MSIE\")\n b = new ActiveXObject(\"AgControl.AgControl\");\n else\n if(navigator.plugins[\"Silverlight Plug-In\"])\n {\n a = document.createElement(\"div\");\n document.body.appendChild(a);\n a.innerHTML = '<embed type=\"application/x-silverlight\" />';\n b = a.childNodes[0]\n }\n\n if(b.IsVersionSupported(d))\n c = true;\n b = null;\n Silverlight.available = true\n }\n catch(e)\n {\n c=false\n }\n\n if(a)\n document.body.removeChild(a);\n return c\n};\n</code></pre>\n"
},
{
"answer_id": 26956,
"author": "Jon Galloway",
"author_id": 5,
"author_profile": "https://Stackoverflow.com/users/5",
"pm_score": 4,
"selected": true,
"text": "<p>The Silverlight control only has an <a href=\"http://msdn.microsoft.com/en-us/library/system.windows.interop.silverlighthost.isversionsupported(VS.95).aspx\" rel=\"nofollow noreferrer\">IsVersionSupported function</a>, which returns true / false when you give it a version number, e.g.:</p>\n\n<pre><code>if(slPlugin.isVersionSupported(\"2.0\")) {\n alert(\"I haz some flavour of Silverlight 2\");\n</code></pre>\n\n<p>You can be as specific as you want when checking the build, since the version string can include all of the following:</p>\n\n<ul>\n<li>major - the major number</li>\n<li>minor - the minor number</li>\n<li>build - the build number</li>\n<li>revision - the revision number</li>\n</ul>\n\n<p>So we can check for a specific build number as follows:</p>\n\n<pre><code>if(slPlugin.isVersionSupported(\"2.0.30523\")) {\n alert(\"I haz Silverlight 2.0.30523, but could be any revision.\");\n</code></pre>\n\n<p><a href=\"http://msdn.microsoft.com/en-us/library/bb693297.aspx#replace_version\" rel=\"nofollow noreferrer\">Silverlight 1.0 Beta included a control.settings.version property, which was replaced with the isVersionSupported() method</a>. The idea is that you shouldn't be programming against specific versions of Silverlight. Rather, you should be checking if the client has <em>at least</em> verion 1.0, or 2.0, etc.</p>\n\n<p>That being said, you can get the Silverlight version number in Firefox by checking the Silverlight plugin description:</p>\n\n<pre><code>alert(navigator.plugins[\"Silverlight Plug-In\"].description);\n</code></pre>\n\n<p>Shows '2.0.30523.8' on my computer.</p>\n\n<p>Note that it is possible to brute force it by iterating through all released version numbers. <a href=\"http://pages.citebite.com/w3o7qsydtr\" rel=\"nofollow noreferrer\">Presumably that's what BrowserHawk does</a> - they'll report which version of Silverlight the client has installed.</p>\n"
},
{
"answer_id": 790573,
"author": "APIJunkie",
"author_id": 96169,
"author_profile": "https://Stackoverflow.com/users/96169",
"pm_score": 1,
"selected": false,
"text": "<p>As mentioned in the above comments there is currently no efficient direct way to get the installed Silverlight version number (that works cross browser platform).</p>\n\n<p>I wrote a post on how to workaround this problem and detect the Silverlight major version number (including version 3) programmatically and more efficiently using JavaScript.</p>\n\n<p>You can find the code and the post at:</p>\n\n<p><a href=\"http://www.apijunkie.com/APIJunkie/blog/post/2009/04/How-to-programmatically-detect-Silverlight-version.aspx\" rel=\"nofollow noreferrer\">http://www.apijunkie.com/APIJunkie/blog/post/2009/04/How-to-programmatically-detect-Silverlight-version.aspx</a></p>\n\n<p>Good luck!</p>\n"
},
{
"answer_id": 1460758,
"author": "Brady Moritz",
"author_id": 177242,
"author_profile": "https://Stackoverflow.com/users/177242",
"pm_score": 2,
"selected": false,
"text": "<p>found this site that detects the full version of silverlight- <a href=\"http://www.silverlightversion.com\" rel=\"nofollow noreferrer\">silverlight version</a> (aka silverlightversion.com)</p>\n"
},
{
"answer_id": 11331849,
"author": "eFloh",
"author_id": 543303,
"author_profile": "https://Stackoverflow.com/users/543303",
"pm_score": 1,
"selected": false,
"text": "<p>Environment.Version will do what you want! Supported since Silverlight 2.0</p>\n"
}
] | 2008/08/21 | [
"https://Stackoverflow.com/questions/20722",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/375/"
] | How can I efficiently and effectively detect the version and, for that matter, any available information about the instance of [Silverlight](http://silverlight.net/) currently running on the browser? | The Silverlight control only has an [IsVersionSupported function](http://msdn.microsoft.com/en-us/library/system.windows.interop.silverlighthost.isversionsupported(VS.95).aspx), which returns true / false when you give it a version number, e.g.:
```
if(slPlugin.isVersionSupported("2.0")) {
alert("I haz some flavour of Silverlight 2");
```
You can be as specific as you want when checking the build, since the version string can include all of the following:
* major - the major number
* minor - the minor number
* build - the build number
* revision - the revision number
So we can check for a specific build number as follows:
```
if(slPlugin.isVersionSupported("2.0.30523")) {
alert("I haz Silverlight 2.0.30523, but could be any revision.");
```
[Silverlight 1.0 Beta included a control.settings.version property, which was replaced with the isVersionSupported() method](http://msdn.microsoft.com/en-us/library/bb693297.aspx#replace_version). The idea is that you shouldn't be programming against specific versions of Silverlight. Rather, you should be checking if the client has *at least* verion 1.0, or 2.0, etc.
That being said, you can get the Silverlight version number in Firefox by checking the Silverlight plugin description:
```
alert(navigator.plugins["Silverlight Plug-In"].description);
```
Shows '2.0.30523.8' on my computer.
Note that it is possible to brute force it by iterating through all released version numbers. [Presumably that's what BrowserHawk does](http://pages.citebite.com/w3o7qsydtr) - they'll report which version of Silverlight the client has installed. |
20,731 | <p>I've tried several things already,</p>
<pre><code>std::stringstream m;
m.empty();
m.clear();
</code></pre>
<p>both of which don't work.</p>
| [
{
"answer_id": 20732,
"author": "CodingWithoutComments",
"author_id": 25,
"author_profile": "https://Stackoverflow.com/users/25",
"pm_score": 5,
"selected": false,
"text": "<pre><code>m.str(\"\");\n</code></pre>\n\n<p>seems to work.</p>\n"
},
{
"answer_id": 20792,
"author": "Wilka",
"author_id": 1367,
"author_profile": "https://Stackoverflow.com/users/1367",
"pm_score": 11,
"selected": true,
"text": "<p>For all the standard library types the member function <code>empty()</code> is a query, not a command, i.e. it means \"are you empty?\" not \"please throw away your contents\".</p>\n\n<p>The <code>clear()</code> member function is inherited from <code>ios</code> and is used to clear the error state of the stream, e.g. if a file stream has the error state set to <code>eofbit</code> (end-of-file), then calling <code>clear()</code> will set the error state back to <code>goodbit</code> (no error).</p>\n\n<p>For clearing the contents of a <code>stringstream</code>, using:</p>\n\n<pre><code>m.str(\"\");\n</code></pre>\n\n<p>is correct, although using:</p>\n\n<pre><code>m.str(std::string());\n</code></pre>\n\n<p>is technically more efficient, because you avoid invoking the <code>std::string</code> constructor that takes <code>const char*</code>. But any compiler these days should be able to generate the same code in both cases - so I would just go with whatever is more readable.</p>\n"
},
{
"answer_id": 12309628,
"author": "John",
"author_id": 1653342,
"author_profile": "https://Stackoverflow.com/users/1653342",
"pm_score": -1,
"selected": false,
"text": "<p>These do not discard the data in the stringstream in gnu c++</p>\n\n<pre><code> m.str(\"\");\n m.str() = \"\";\n m.str(std::string());\n</code></pre>\n\n<p>The following does empty the stringstream for me:</p>\n\n<pre><code> m.str().clear();\n</code></pre>\n"
},
{
"answer_id": 12843784,
"author": "jerron",
"author_id": 1738731,
"author_profile": "https://Stackoverflow.com/users/1738731",
"pm_score": 5,
"selected": false,
"text": "<p>This should be the most reliable way regardless of the compiler:</p>\n\n<pre><code>m=std::stringstream();\n</code></pre>\n"
},
{
"answer_id": 19439633,
"author": "Francisco Cortes",
"author_id": 2406499,
"author_profile": "https://Stackoverflow.com/users/2406499",
"pm_score": 4,
"selected": false,
"text": "<p>my 2 cents:</p>\n\n<p>this seemed to work for me in xcode and dev-c++, I had a program in the form of a menu that if executed iteratively as per the request of a user will fill up a stringstream variable which would work ok the first time the code would run but would not clear the stringstream the next time the user will run the same code. but the two lines of code below finally cleared up the stringstream variable everytime before filling up the string variable. (2 hours of trial and error and google searches), btw, using each line on their own would not do the trick.</p>\n\n<pre><code>//clear the stringstream variable\n\nsstm.str(\"\");\nsstm.clear();\n\n//fill up the streamstream variable\nsstm << \"crap\" << \"morecrap\";\n</code></pre>\n"
},
{
"answer_id": 22668889,
"author": "TimoK",
"author_id": 2757147,
"author_profile": "https://Stackoverflow.com/users/2757147",
"pm_score": 4,
"selected": false,
"text": "<p>I am always scoping it:</p>\n\n<pre><code>{\n std::stringstream ss;\n ss << \"what\";\n}\n\n{\n std::stringstream ss;\n ss << \"the\";\n}\n\n{\n std::stringstream ss;\n ss << \"heck\";\n}\n</code></pre>\n"
},
{
"answer_id": 23266418,
"author": "Nikos Athanasiou",
"author_id": 2567683,
"author_profile": "https://Stackoverflow.com/users/2567683",
"pm_score": 6,
"selected": false,
"text": "<p>You can <strong>clear the error state <strong>and</strong> empty the stringstream</strong> all in one line</p>\n<pre><code>std::stringstream().swap(m); // swap m with a default constructed stringstream\n</code></pre>\n<p>This effectively resets m to a default constructed state, meaning that <strong>it actually deletes the buffers allocated by the string stream and resets the error state</strong>. Here's an experimental proof:</p>\n<pre class=\"lang-cpp prettyprint-override\"><code>int main ()\n{\n std::string payload(16, 'x');\n \n std::stringstream *ss = new std::stringstream; // Create a memory leak\n (*ss) << payload; // Leak more memory\n \n // Now choose a way to "clear" a string stream\n //std::stringstream().swap(*ss); // Method 1\n //ss->str(std::string()); // Method 2\n \n std::cout << "end" << std::endl;\n}\n</code></pre>\n<p><a href=\"http://coliru.stacked-crooked.com/a/937f6a279f4cc876\" rel=\"noreferrer\">Demo</a></p>\n<p>When the demo is compiled with address sanitizer, memory usage is revealed:</p>\n<pre><code>=================================================================\n==10415==ERROR: LeakSanitizer: detected memory leaks\n\nDirect leak of 392 byte(s) in 1 object(s) allocated from:\n #0 0x510ae8 in operator new(unsigned long) (/tmp/1637178326.0089633/a.out+0x510ae8)\n #1 0x514e80 in main (/tmp/1637178326.0089633/a.out+0x514e80)\n #2 0x7f3079ffb82f in __libc_start_main /build/glibc-Cl5G7W/glibc-2.23/csu/../csu/libc-start.c:291\n\nIndirect leak of 513 byte(s) in 1 object(s) allocated from:\n #0 0x510ae8 in operator new(unsigned long) (/tmp/1637178326.0089633/a.out+0x510ae8)\n #1 0x7f307b03a25c in std::__cxx11::basic_string<char, std::char_traits<char>, std::allocator<char> >::reserve(unsigned long) (/usr/local/lib64/libstdc++.so.6+0x13725c)\n #2 0x603000000010 (<unknown module>)\n\nSUMMARY: AddressSanitizer: 905 byte(s) leaked in 2 allocation(s).\n</code></pre>\n<p>Pretty steep if you ask me. To hold just 16bytes of payload, we spent 905 bytes ... string streams are no toy. Memory is allocated in two parts:</p>\n<ul>\n<li>The constructed string stream (392 bytes)</li>\n<li>The extra buffer needed for the payload (513 bytes). The extraneous size has to do with the allocation strategy chosen by the stream and for payloads <= 8 bytes, blocks inside the initial object can be used.</li>\n</ul>\n<p>If you <a href=\"http://coliru.stacked-crooked.com/a/a9c231eb2783479b\" rel=\"noreferrer\">enable method 1</a> (the one shown in this answer) the extra 513 (payload) bytes are reclaimed, because the stream is <strong>actually cleared</strong>.</p>\n<p>If you <a href=\"http://coliru.stacked-crooked.com/a/de372b604e5b9b51\" rel=\"noreferrer\">enable method2</a> as suggested in the comments or other answers, you can see that all 905 bytes are in use by the time we exit.</p>\n<p>In terms of program semantics, one may only care that the stream "appears" and "behaves" as empty, similar to how a <code>vector::clear</code> may leave the capacity untouched but render the vector empty to the user (of course vector would spend just 16 bytes here). Given the memory allocation that string stream requires, I can imagine this approach being often faster. <strong>This answer's primary goal is to actually clear the string stream, given that memory consumption that comes with it is no joke</strong>. Depending on your use case (number of streams, data they hold, frequency of clearing) you may choose the best approach.</p>\n<p>Finally note that it's rarely useful to clear the stream without clearing the error state <strong>and all inherited state</strong>. The one liner in this answer does both.</p>\n"
},
{
"answer_id": 26307234,
"author": "Alcino Dall Igna Junior",
"author_id": 4130754,
"author_profile": "https://Stackoverflow.com/users/4130754",
"pm_score": -1,
"selected": false,
"text": "<p>It's a conceptual problem.</p>\n\n<p>Stringstream is a stream, so its iterators are forward, cannot return. In an output stringstream, you need a flush() to reinitialize it, as in any other output stream.</p>\n"
},
{
"answer_id": 69164375,
"author": "Kuba hasn't forgotten Monica",
"author_id": 1329652,
"author_profile": "https://Stackoverflow.com/users/1329652",
"pm_score": 2,
"selected": false,
"text": "<p>There are many other answers that "work", but they often do unnecessary copies or reallocate memory.</p>\n<ol>\n<li><p>Swapping streams means that you need to discard one of them, wasting the memory allocation. Same goes for assigning a default-constructed stream,</p>\n</li>\n<li><p>Assigning to the string in the string buffer (via <code>stringstream::str</code> or <code>stringbuf::str</code>) may lose the buffer already allocated by the string.</p>\n</li>\n</ol>\n<p>The canonical way to clear the string stream would be:</p>\n<pre><code>void clear(std::stringstream &stream)\n{\n if (stream.rdbuf()) stream.rdbuf()->pubseekpos(0);\n}\n</code></pre>\n<p>The canonical way to get the size of the data in the stream's buffer is:</p>\n<pre><code>std::size_t availSize() (const std::stringstream& stream)\n{\n if (stream.rdbuf())\n return std::size_t(\n stream.rdbuf()->pubseekoff(0, std::ios_base::cur, std::ios_base::out));\n else\n return 0;\n}\n</code></pre>\n<p>The canonical way to copy the data from the stream to some other preallocated buffer and then clear it would then be:</p>\n<pre><code>std::size_t readAndClear(std::stringstream &stream, void* outBuf, std::size_t outSize)\n{\n auto const copySize = std::min(availSize(stream), outSize);\n if (!copySize) return 0; // takes care of null stream.rdbuf()\n\n stream.rdbuf()->sgetn(outBuf, copySize);\n stream.rdbuf()->pubseekpos(0); // clear the buffer\n\n return copySize;\n}\n</code></pre>\n<hr />\n<p>I intend this to be a canonical answer. Language lawyers, feel free to pitch in.</p>\n"
}
] | 2008/08/21 | [
"https://Stackoverflow.com/questions/20731",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/25/"
] | I've tried several things already,
```
std::stringstream m;
m.empty();
m.clear();
```
both of which don't work. | For all the standard library types the member function `empty()` is a query, not a command, i.e. it means "are you empty?" not "please throw away your contents".
The `clear()` member function is inherited from `ios` and is used to clear the error state of the stream, e.g. if a file stream has the error state set to `eofbit` (end-of-file), then calling `clear()` will set the error state back to `goodbit` (no error).
For clearing the contents of a `stringstream`, using:
```
m.str("");
```
is correct, although using:
```
m.str(std::string());
```
is technically more efficient, because you avoid invoking the `std::string` constructor that takes `const char*`. But any compiler these days should be able to generate the same code in both cases - so I would just go with whatever is more readable. |
20,744 | <p>Using the viewer control for display of SQL Reporting Services reports on web page (Microsoft.ReportViewer.WebForms), can you move the View Report button? It defaults to the very right side of the report, which means you have to scroll all the way across before the button is visible. Not a problem for reports that fit the window width, but on very wide reports that is quickly an issue.</p>
| [
{
"answer_id": 20781,
"author": "Bryan Roth",
"author_id": 299,
"author_profile": "https://Stackoverflow.com/users/299",
"pm_score": 2,
"selected": false,
"text": "<p>No, you cannot reposition the view report button in the ReportViewer control.</p>\n\n<p>However, you could create your own custom report viewing control. The control would be comprised of fields for report parameters and a button to generate the report. When a user clicks the button you could generate the report in the background. You could display the report as a PDF, HTML, etc.</p>\n"
},
{
"answer_id": 886149,
"author": "Liron Yahdav",
"author_id": 62,
"author_profile": "https://Stackoverflow.com/users/62",
"pm_score": 3,
"selected": true,
"text": "<p>It's kind of a hack, but you can move it in JavaScript. Just see what HTML the ReportViewer generates, and write the appropriate JavaScript code to move the button. I used JavaScript to hide the button (because we wanted our own View Report button). Any JavaScript code that manipulates the generated ReportViewer's HTML must come after the ReportViewer control in the .aspx page. Here's my code for hiding the button, to give you an idea of what you'd do:</p>\n\n<pre><code>function getRepViewBtn() {\n return document.getElementsByName(\"ReportViewer1$ctl00$ctl00\")[0];\n}\n\nfunction hideViewReportButton() { // call this where needed\n var btn = getRepViewBtn();\n btn.style.display = 'none';\n}\n</code></pre>\n"
},
{
"answer_id": 1843548,
"author": "Travis Collins",
"author_id": 30460,
"author_profile": "https://Stackoverflow.com/users/30460",
"pm_score": 2,
"selected": false,
"text": "<p>The reason the button is pushed over to the right is that the td for the parameters has width=\"100%\". I'm solving this problem with the following jquery. It simply changes the width of the parameters td to 1. Browsers will expand the width on their own to the width of the contents of the element. Hope this helps.</p>\n\n<pre><code><script type=\"text/javascript\">\n $(document).ready(function() {\n $(\"#<%= ReportViewer1.ClientID %> td:first\").attr(\"width\", \"1\");\n });\n</script>\n</code></pre>\n"
},
{
"answer_id": 27257819,
"author": "PoppyIndicular",
"author_id": 4317302,
"author_profile": "https://Stackoverflow.com/users/4317302",
"pm_score": 1,
"selected": false,
"text": "<p>Since I was searching for this answer just yesterday, I thought I'd post what I came up with to solve our problem. Our reports were coming back wide, and we wanted the \"view reports\" button to exist on the left side of the control so there was no need to scroll to get to the button. I did need to go into the source of the rendered file to find the ID names of the button and the target table. </p>\n\n<p>I wrote a simple cut and paste javascript function to pull the button from its original position and essentially drop it into the next row in the containing table below the date pickers. </p>\n\n<pre><code>function moveButton() {\n document.getElementById('ParameterTable_ctl00_MainContent_MyReports_ctl04').appendChild(document.getElementById('ctl00_MainContent_MyReports_ctl04_ctl00'));\n }\n</code></pre>\n\n<p>This function gets called on the report viewer load event.</p>\n\n<pre><code>ScriptManager.RegisterStartupScript(Me, Me.GetType(), \"moveButton\", \"moveButton();\", True)\n</code></pre>\n\n<p>To adjust the position, I used the CSS ID. </p>\n\n<pre><code>#ctl00_MainContent_MyReports_ctl04_ctl00 {\n margin: 0px 0px 0px 50px;\n}\n</code></pre>\n"
},
{
"answer_id": 52813948,
"author": "Paul",
"author_id": 894995,
"author_profile": "https://Stackoverflow.com/users/894995",
"pm_score": 0,
"selected": false,
"text": "<p>I had the same problem and ended up using an extension on Travis Collins answer; As well as changing the table column width I also align the \"View Report\" button left so that it appears neearer to rest of the controls.</p>\n\n<pre><code> <script type=\"text/javascript\">\n $(document).ready(function() {\n $(\"#_ctl0_MainContent_reportViewer_fixedTable tr:first td:first-child\").attr(\"width\", \"1\"); \n $(\"#_ctl0_MainContent_reportViewer_fixedTable tr:first td:last-child\").attr(\"align\", \"left\"); \n });\n</script>\n</code></pre>\n\n<p>You may need to tweak the JQuery selector depending on the element naming assigned to your existing control.</p>\n"
}
] | 2008/08/21 | [
"https://Stackoverflow.com/questions/20744",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1215/"
] | Using the viewer control for display of SQL Reporting Services reports on web page (Microsoft.ReportViewer.WebForms), can you move the View Report button? It defaults to the very right side of the report, which means you have to scroll all the way across before the button is visible. Not a problem for reports that fit the window width, but on very wide reports that is quickly an issue. | It's kind of a hack, but you can move it in JavaScript. Just see what HTML the ReportViewer generates, and write the appropriate JavaScript code to move the button. I used JavaScript to hide the button (because we wanted our own View Report button). Any JavaScript code that manipulates the generated ReportViewer's HTML must come after the ReportViewer control in the .aspx page. Here's my code for hiding the button, to give you an idea of what you'd do:
```
function getRepViewBtn() {
return document.getElementsByName("ReportViewer1$ctl00$ctl00")[0];
}
function hideViewReportButton() { // call this where needed
var btn = getRepViewBtn();
btn.style.display = 'none';
}
``` |
20,762 | <p>Is there any easy/general way to clean an XML based data source prior to using it in an XmlReader so that I can gracefully consume XML data that is non-conformant to the hexadecimal character restrictions placed on XML?</p>
<p>Note: </p>
<ul>
<li>The solution needs to handle XML
data sources that use character
encodings other than UTF-8, e.g. by
specifying the character encoding at
the XML document declaration. Not
mangling the character encoding of
the source while stripping invalid
hexadecimal characters has been a
major sticking point.</li>
<li>The removal of invalid hexadecimal characters should only remove hexadecimal encoded values, as you can often find href values in data that happens to contains a string that would be a string match for a hexadecimal character.</li>
</ul>
<p><em>Background:</em></p>
<p>I need to consume an XML-based data source that conforms to a specific format (think Atom or RSS feeds), but want to be able to consume data sources that have been published which contain invalid hexadecimal characters per the XML specification.</p>
<p>In .NET if you have a Stream that represents the XML data source, and then attempt to parse it using an XmlReader and/or XPathDocument, an exception is raised due to the inclusion of invalid hexadecimal characters in the XML data. My current attempt to resolve this issue is to parse the Stream as a string and use a regular expression to remove and/or replace the invalid hexadecimal characters, but I am looking for a more performant solution.</p>
| [
{
"answer_id": 20777,
"author": "Eugene Katz",
"author_id": 1533,
"author_profile": "https://Stackoverflow.com/users/1533",
"pm_score": 7,
"selected": true,
"text": "<p>It <strong>may not be perfect</strong> (emphasis added since people missing this disclaimer), but what I've done in that case is below. You can adjust to use with a stream.</p>\n\n<pre><code>/// <summary>\n/// Removes control characters and other non-UTF-8 characters\n/// </summary>\n/// <param name=\"inString\">The string to process</param>\n/// <returns>A string with no control characters or entities above 0x00FD</returns>\npublic static string RemoveTroublesomeCharacters(string inString)\n{\n if (inString == null) return null;\n\n StringBuilder newString = new StringBuilder();\n char ch;\n\n for (int i = 0; i < inString.Length; i++)\n {\n\n ch = inString[i];\n // remove any characters outside the valid UTF-8 range as well as all control characters\n // except tabs and new lines\n //if ((ch < 0x00FD && ch > 0x001F) || ch == '\\t' || ch == '\\n' || ch == '\\r')\n //if using .NET version prior to 4, use above logic\n if (XmlConvert.IsXmlChar(ch)) //this method is new in .NET 4\n {\n newString.Append(ch);\n }\n }\n return newString.ToString();\n\n}\n</code></pre>\n"
},
{
"answer_id": 641632,
"author": "dnewcome",
"author_id": 35311,
"author_profile": "https://Stackoverflow.com/users/35311",
"pm_score": 6,
"selected": false,
"text": "<p>I like Eugene's whitelist concept. I needed to do a similar thing as the original poster, but I needed to support all Unicode characters, not just up to 0x00FD. The XML spec is:</p>\n\n<p>Char = #x9 | #xA | #xD | [#x20-#xD7FF] | [#xE000-#xFFFD] | [#x10000-#x10FFFF]</p>\n\n<p>In .NET, the internal representation of Unicode characters is only 16 bits, so we can't `allow' 0x10000-0x10FFFF explicitly. The XML spec explicitly <em>disallows</em> the surrogate code points starting at 0xD800 from appearing. However it is possible that if we allowed these surrogate code points in our whitelist, utf-8 encoding our string might produce valid XML in the end as long as proper utf-8 encoding was produced from the surrogate pairs of utf-16 characters in the .NET string. I haven't explored this though, so I went with the safer bet and didn't allow the surrogates in my whitelist.</p>\n\n<p>The comments in Eugene's solution are misleading though, the problem is that the characters we are excluding are not valid in <em>XML</em> ... they are perfectly valid Unicode code points. We are not removing `non-utf-8 characters'. We are removing utf-8 characters that may not appear in well-formed XML documents.</p>\n\n<pre><code>public static string XmlCharacterWhitelist( string in_string ) {\n if( in_string == null ) return null;\n\n StringBuilder sbOutput = new StringBuilder();\n char ch;\n\n for( int i = 0; i < in_string.Length; i++ ) {\n ch = in_string[i];\n if( ( ch >= 0x0020 && ch <= 0xD7FF ) || \n ( ch >= 0xE000 && ch <= 0xFFFD ) ||\n ch == 0x0009 ||\n ch == 0x000A || \n ch == 0x000D ) {\n sbOutput.Append( ch );\n }\n }\n return sbOutput.ToString();\n}\n</code></pre>\n"
},
{
"answer_id": 2293111,
"author": "savio",
"author_id": 276570,
"author_profile": "https://Stackoverflow.com/users/276570",
"pm_score": -1,
"selected": false,
"text": "<pre><code>private static String removeNonUtf8CompliantCharacters( final String inString ) {\n if (null == inString ) return null;\n byte[] byteArr = inString.getBytes();\n for ( int i=0; i < byteArr.length; i++ ) {\n byte ch= byteArr[i]; \n // remove any characters outside the valid UTF-8 range as well as all control characters\n // except tabs and new lines\n if ( !( (ch > 31 && ch < 253 ) || ch == '\\t' || ch == '\\n' || ch == '\\r') ) {\n byteArr[i]=' ';\n }\n }\n return new String( byteArr );\n}\n</code></pre>\n"
},
{
"answer_id": 3503958,
"author": "Kesavan",
"author_id": 422998,
"author_profile": "https://Stackoverflow.com/users/422998",
"pm_score": -1,
"selected": false,
"text": "<p>Try this for PHP!</p>\n\n<pre><code>$goodUTF8 = iconv(\"utf-8\", \"utf-8//IGNORE\", $badUTF8);\n</code></pre>\n"
},
{
"answer_id": 5239529,
"author": "Nathan G",
"author_id": 423508,
"author_profile": "https://Stackoverflow.com/users/423508",
"pm_score": 2,
"selected": false,
"text": "<p>The above solutions seem to be for removing invalid characters prior to converting to XML.</p>\n\n<p>Use this code to remove invalid XML characters from an XML string. eg. &x1A;</p>\n\n<pre><code> public static string CleanInvalidXmlChars( string Xml, string XMLVersion )\n {\n string pattern = String.Empty;\n switch( XMLVersion )\n {\n case \"1.0\":\n pattern = @\"&#x((10?|[2-F])FFF[EF]|FDD[0-9A-F]|7F|8[0-46-9A-F]9[0-9A-F]);\";\n break;\n case \"1.1\":\n pattern = @\"&#x((10?|[2-F])FFF[EF]|FDD[0-9A-F]|[19][0-9A-F]|7F|8[0-46-9A-F]|0?[1-8BCEF]);\";\n break;\n default:\n throw new Exception( \"Error: Invalid XML Version!\" );\n }\n\n Regex regex = new Regex( pattern, RegexOptions.IgnoreCase );\n if( regex.IsMatch( Xml ) )\n Xml = regex.Replace( Xml, String.Empty );\n return Xml;\n }\n</code></pre>\n\n<p><a href=\"http://balajiramesh.wordpress.com/2008/05/30/strip-illegal-xml-characters-based-on-w3c-standard/\" rel=\"nofollow\">http://balajiramesh.wordpress.com/2008/05/30/strip-illegal-xml-characters-based-on-w3c-standard/</a></p>\n"
},
{
"answer_id": 5936162,
"author": "Murari Kumar",
"author_id": 430608,
"author_profile": "https://Stackoverflow.com/users/430608",
"pm_score": -1,
"selected": false,
"text": "<p>You can pass non-UTF characters with the following:</p>\n\n<pre><code>string sFinalString = \"\";\nstring hex = \"\";\nforeach (char ch in UTFCHAR)\n{\n int tmp = ch;\n if ((ch < 0x00FD && ch > 0x001F) || ch == '\\t' || ch == '\\n' || ch == '\\r')\n {\n sFinalString += ch;\n }\n else\n { \n sFinalString += \"&#\" + tmp+\";\";\n }\n}\n</code></pre>\n"
},
{
"answer_id": 10244306,
"author": "Jodrell",
"author_id": 659190,
"author_profile": "https://Stackoverflow.com/users/659190",
"pm_score": 3,
"selected": false,
"text": "<p>Modernising <a href=\"https://stackoverflow.com/a/641632/659190\">dnewcombe's</a> answer, you could take a slightly simpler approach</p>\n\n<pre><code>public static string RemoveInvalidXmlChars(string input)\n{\n var isValid = new Predicate<char>(value =>\n (value >= 0x0020 && value <= 0xD7FF) ||\n (value >= 0xE000 && value <= 0xFFFD) ||\n value == 0x0009 ||\n value == 0x000A ||\n value == 0x000D);\n\n return new string(Array.FindAll(input.ToCharArray(), isValid));\n}\n</code></pre>\n\n<p>or, with Linq</p>\n\n<pre><code>public static string RemoveInvalidXmlChars(string input)\n{\n return new string(input.Where(value =>\n (value >= 0x0020 && value <= 0xD7FF) ||\n (value >= 0xE000 && value <= 0xFFFD) ||\n value == 0x0009 ||\n value == 0x000A ||\n value == 0x000D).ToArray());\n}\n</code></pre>\n\n<p>I'd be interested to know how the performance of these methods compares and how they all compare to a black list approach using <code>Buffer.BlockCopy</code>.</p>\n"
},
{
"answer_id": 14912930,
"author": "Igor Kustov",
"author_id": 1244353,
"author_profile": "https://Stackoverflow.com/users/1244353",
"pm_score": 5,
"selected": false,
"text": "<p>As the way to remove invalid XML characters I suggest you to use <a href=\"http://msdn.microsoft.com/en-us/library/system.xml.xmlconvert.isxmlchar%28v=vs.100%29.aspx\" rel=\"noreferrer\">XmlConvert.IsXmlChar</a> method. It was added since .NET Framework 4 and is presented in Silverlight too. Here is the small sample:</p>\n\n<pre><code>void Main() {\n string content = \"\\v\\f\\0\";\n Console.WriteLine(IsValidXmlString(content)); // False\n\n content = RemoveInvalidXmlChars(content);\n Console.WriteLine(IsValidXmlString(content)); // True\n}\n\nstatic string RemoveInvalidXmlChars(string text) {\n char[] validXmlChars = text.Where(ch => XmlConvert.IsXmlChar(ch)).ToArray();\n return new string(validXmlChars);\n}\n\nstatic bool IsValidXmlString(string text) {\n try {\n XmlConvert.VerifyXmlChars(text);\n return true;\n } catch {\n return false;\n }\n}\n</code></pre>\n"
},
{
"answer_id": 24225671,
"author": "mnaoumov",
"author_id": 1074455,
"author_profile": "https://Stackoverflow.com/users/1074455",
"pm_score": 2,
"selected": false,
"text": "<p>Regex based approach</p>\n\n<pre><code>public static string StripInvalidXmlCharacters(string str)\n{\n var invalidXmlCharactersRegex = new Regex(\"[^\\u0009\\u000a\\u000d\\u0020-\\ud7ff\\ue000-\\ufffd]|([\\ud800-\\udbff](?![\\udc00-\\udfff]))|((?<![\\ud800-\\udbff])[\\udc00-\\udfff])\");\n return invalidXmlCharactersRegex.Replace(str, \"\");\n</code></pre>\n\n<p>}</p>\n\n<p>See my <a href=\"http://mnaoumov.wordpress.com/2014/06/15/escaping-invalid-xml-unicode-characters/\" rel=\"nofollow\">blogpost</a> for more details</p>\n"
},
{
"answer_id": 27239510,
"author": "Ryan Adams",
"author_id": 4313632,
"author_profile": "https://Stackoverflow.com/users/4313632",
"pm_score": 3,
"selected": false,
"text": "<p>Here is <a href=\"https://stackoverflow.com/a/641632/4313632\">dnewcome</a>'s answer in a custom StreamReader. It simply wraps a real stream reader and replaces the characters as they are read. </p>\n\n<p>I only implemented a few methods to save myself time. I used this in conjunction with XDocument.Load and a file stream and only the Read(char[] buffer, int index, int count) method was called, so it worked like this. You may need to implement additional methods to get this to work for your application. I used this approach because it seems more efficient than the other answers. I also only implemented one of the constructors, you could obviously implement any of the StreamReader constructors that you need, since it is just a pass through. </p>\n\n<p>I chose to replace the characters rather than removing them because it greatly simplifies the solution. In this way the length of the text stays the same, so there is no need to keep track of a separate index.</p>\n\n<pre><code>public class InvalidXmlCharacterReplacingStreamReader : TextReader\n{\n private StreamReader implementingStreamReader;\n private char replacementCharacter;\n\n public InvalidXmlCharacterReplacingStreamReader(Stream stream, char replacementCharacter)\n {\n implementingStreamReader = new StreamReader(stream);\n this.replacementCharacter = replacementCharacter;\n }\n\n public override void Close()\n {\n implementingStreamReader.Close();\n }\n\n public override ObjRef CreateObjRef(Type requestedType)\n {\n return implementingStreamReader.CreateObjRef(requestedType);\n }\n\n public void Dispose()\n {\n implementingStreamReader.Dispose();\n }\n\n public override bool Equals(object obj)\n {\n return implementingStreamReader.Equals(obj);\n }\n\n public override int GetHashCode()\n {\n return implementingStreamReader.GetHashCode();\n }\n\n public override object InitializeLifetimeService()\n {\n return implementingStreamReader.InitializeLifetimeService();\n }\n\n public override int Peek()\n {\n int ch = implementingStreamReader.Peek();\n if (ch != -1)\n {\n if (\n (ch < 0x0020 || ch > 0xD7FF) &&\n (ch < 0xE000 || ch > 0xFFFD) &&\n ch != 0x0009 &&\n ch != 0x000A &&\n ch != 0x000D\n )\n {\n return replacementCharacter;\n }\n }\n return ch;\n }\n\n public override int Read()\n {\n int ch = implementingStreamReader.Read();\n if (ch != -1)\n {\n if (\n (ch < 0x0020 || ch > 0xD7FF) &&\n (ch < 0xE000 || ch > 0xFFFD) &&\n ch != 0x0009 &&\n ch != 0x000A &&\n ch != 0x000D\n )\n {\n return replacementCharacter;\n }\n }\n return ch;\n }\n\n public override int Read(char[] buffer, int index, int count)\n {\n int readCount = implementingStreamReader.Read(buffer, index, count);\n for (int i = index; i < readCount+index; i++)\n {\n char ch = buffer[i];\n if (\n (ch < 0x0020 || ch > 0xD7FF) &&\n (ch < 0xE000 || ch > 0xFFFD) &&\n ch != 0x0009 &&\n ch != 0x000A &&\n ch != 0x000D\n )\n {\n buffer[i] = replacementCharacter;\n }\n }\n return readCount;\n }\n\n public override Task<int> ReadAsync(char[] buffer, int index, int count)\n {\n throw new NotImplementedException();\n }\n\n public override int ReadBlock(char[] buffer, int index, int count)\n {\n throw new NotImplementedException();\n }\n\n public override Task<int> ReadBlockAsync(char[] buffer, int index, int count)\n {\n throw new NotImplementedException();\n }\n\n public override string ReadLine()\n {\n throw new NotImplementedException();\n }\n\n public override Task<string> ReadLineAsync()\n {\n throw new NotImplementedException();\n }\n\n public override string ReadToEnd()\n {\n throw new NotImplementedException();\n }\n\n public override Task<string> ReadToEndAsync()\n {\n throw new NotImplementedException();\n }\n\n public override string ToString()\n {\n return implementingStreamReader.ToString();\n }\n}\n</code></pre>\n"
},
{
"answer_id": 30351313,
"author": "Victor Zakharov",
"author_id": 897326,
"author_profile": "https://Stackoverflow.com/users/897326",
"pm_score": 4,
"selected": false,
"text": "<p>DRY implementation of <a href=\"https://stackoverflow.com/a/27239510/897326\">this answer</a>'s solution (using a different constructor - feel free to use the one you need in your application):</p>\n\n<pre><code>public class InvalidXmlCharacterReplacingStreamReader : StreamReader\n{\n private readonly char _replacementCharacter;\n\n public InvalidXmlCharacterReplacingStreamReader(string fileName, char replacementCharacter) : base(fileName)\n {\n this._replacementCharacter = replacementCharacter;\n }\n\n public override int Peek()\n {\n int ch = base.Peek();\n if (ch != -1 && IsInvalidChar(ch))\n {\n return this._replacementCharacter;\n }\n return ch;\n }\n\n public override int Read()\n {\n int ch = base.Read();\n if (ch != -1 && IsInvalidChar(ch))\n {\n return this._replacementCharacter;\n }\n return ch;\n }\n\n public override int Read(char[] buffer, int index, int count)\n {\n int readCount = base.Read(buffer, index, count);\n for (int i = index; i < readCount + index; i++)\n {\n char ch = buffer[i];\n if (IsInvalidChar(ch))\n {\n buffer[i] = this._replacementCharacter;\n }\n }\n return readCount;\n }\n\n private static bool IsInvalidChar(int ch)\n {\n return (ch < 0x0020 || ch > 0xD7FF) &&\n (ch < 0xE000 || ch > 0xFFFD) &&\n ch != 0x0009 &&\n ch != 0x000A &&\n ch != 0x000D;\n }\n}\n</code></pre>\n"
},
{
"answer_id": 40720009,
"author": "Munavvar",
"author_id": 3261852,
"author_profile": "https://Stackoverflow.com/users/3261852",
"pm_score": 0,
"selected": false,
"text": "<p>Use this function to remove invalid xml characters.</p>\n\n<pre><code>public static string CleanInvalidXmlChars(string text) \n{ \n string re = @\"[^\\x09\\x0A\\x0D\\x20-\\xD7FF\\xE000-\\xFFFD\\x10000-x10FFFF]\"; \n return Regex.Replace(text, re, \"\"); \n} \n</code></pre>\n"
},
{
"answer_id": 44189911,
"author": "BogdanRB",
"author_id": 1295946,
"author_profile": "https://Stackoverflow.com/users/1295946",
"pm_score": 1,
"selected": false,
"text": "<p>Modified answer or original answer by <a href=\"https://stackoverflow.com/a/30351313/1295946\">Neolisk above</a>.\n<br/>Changes: of \\0 character is passed, removal is done, rather than a replacement. also, made use of XmlConvert.IsXmlChar(char) method</p>\n\n<pre><code> /// <summary>\n /// Replaces invalid Xml characters from input file, NOTE: if replacement character is \\0, then invalid Xml character is removed, instead of 1-for-1 replacement\n /// </summary>\n public class InvalidXmlCharacterReplacingStreamReader : StreamReader\n {\n private readonly char _replacementCharacter;\n\n public InvalidXmlCharacterReplacingStreamReader(string fileName, char replacementCharacter)\n : base(fileName)\n {\n _replacementCharacter = replacementCharacter;\n }\n\n public override int Peek()\n {\n int ch = base.Peek();\n if (ch != -1 && IsInvalidChar(ch))\n {\n if ('\\0' == _replacementCharacter)\n return Peek(); // peek at the next one\n\n return _replacementCharacter;\n }\n return ch;\n }\n\n public override int Read()\n {\n int ch = base.Read();\n if (ch != -1 && IsInvalidChar(ch))\n {\n if ('\\0' == _replacementCharacter)\n return Read(); // read next one\n\n return _replacementCharacter;\n }\n return ch;\n }\n\n public override int Read(char[] buffer, int index, int count)\n {\n int readCount= 0, ch;\n\n for (int i = 0; i < count && (ch = Read()) != -1; i++)\n {\n readCount++;\n buffer[index + i] = (char)ch;\n }\n\n return readCount;\n }\n\n\n private static bool IsInvalidChar(int ch)\n {\n return !XmlConvert.IsXmlChar((char)ch);\n }\n }\n</code></pre>\n"
},
{
"answer_id": 54390234,
"author": "Georg Jung",
"author_id": 1200847,
"author_profile": "https://Stackoverflow.com/users/1200847",
"pm_score": 2,
"selected": false,
"text": "<p>I created <a href=\"https://gist.github.com/georg-jung/6ab5b05ea0ea362c705362b098bc584b#file-invalidxmlcharacterreplacingstreamreader-cs\" rel=\"nofollow noreferrer\">a slightly updated version</a> of <a href=\"https://stackoverflow.com/a/30351313/1200847\">@Neolisk's answer</a>, which supports the <code>*Async</code> functions and uses the .Net 4.0 <code>XmlConvert.IsXmlChar</code> function.</p>\n\n<pre><code>public class InvalidXmlCharacterReplacingStreamReader : StreamReader\n{\n private readonly char _replacementCharacter;\n\n public InvalidXmlCharacterReplacingStreamReader(string fileName, char replacementCharacter) : base(fileName)\n {\n _replacementCharacter = replacementCharacter;\n }\n\n public InvalidXmlCharacterReplacingStreamReader(Stream stream, char replacementCharacter) : base(stream)\n {\n _replacementCharacter = replacementCharacter;\n }\n\n public override int Peek()\n {\n var ch = base.Peek();\n if (ch != -1 && IsInvalidChar(ch))\n {\n return _replacementCharacter;\n }\n return ch;\n }\n\n public override int Read()\n {\n var ch = base.Read();\n if (ch != -1 && IsInvalidChar(ch))\n {\n return _replacementCharacter;\n }\n return ch;\n }\n\n public override int Read(char[] buffer, int index, int count)\n {\n var readCount = base.Read(buffer, index, count);\n ReplaceInBuffer(buffer, index, readCount);\n return readCount;\n }\n\n public override async Task<int> ReadAsync(char[] buffer, int index, int count)\n {\n var readCount = await base.ReadAsync(buffer, index, count).ConfigureAwait(false);\n ReplaceInBuffer(buffer, index, readCount);\n return readCount;\n }\n\n private void ReplaceInBuffer(char[] buffer, int index, int readCount)\n {\n for (var i = index; i < readCount + index; i++)\n {\n var ch = buffer[i];\n if (IsInvalidChar(ch))\n {\n buffer[i] = _replacementCharacter;\n }\n }\n }\n\n private static bool IsInvalidChar(int ch)\n {\n return IsInvalidChar((char)ch);\n }\n\n private static bool IsInvalidChar(char ch)\n {\n return !XmlConvert.IsXmlChar(ch);\n }\n}\n</code></pre>\n"
}
] | 2008/08/21 | [
"https://Stackoverflow.com/questions/20762",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2029/"
] | Is there any easy/general way to clean an XML based data source prior to using it in an XmlReader so that I can gracefully consume XML data that is non-conformant to the hexadecimal character restrictions placed on XML?
Note:
* The solution needs to handle XML
data sources that use character
encodings other than UTF-8, e.g. by
specifying the character encoding at
the XML document declaration. Not
mangling the character encoding of
the source while stripping invalid
hexadecimal characters has been a
major sticking point.
* The removal of invalid hexadecimal characters should only remove hexadecimal encoded values, as you can often find href values in data that happens to contains a string that would be a string match for a hexadecimal character.
*Background:*
I need to consume an XML-based data source that conforms to a specific format (think Atom or RSS feeds), but want to be able to consume data sources that have been published which contain invalid hexadecimal characters per the XML specification.
In .NET if you have a Stream that represents the XML data source, and then attempt to parse it using an XmlReader and/or XPathDocument, an exception is raised due to the inclusion of invalid hexadecimal characters in the XML data. My current attempt to resolve this issue is to parse the Stream as a string and use a regular expression to remove and/or replace the invalid hexadecimal characters, but I am looking for a more performant solution. | It **may not be perfect** (emphasis added since people missing this disclaimer), but what I've done in that case is below. You can adjust to use with a stream.
```
/// <summary>
/// Removes control characters and other non-UTF-8 characters
/// </summary>
/// <param name="inString">The string to process</param>
/// <returns>A string with no control characters or entities above 0x00FD</returns>
public static string RemoveTroublesomeCharacters(string inString)
{
if (inString == null) return null;
StringBuilder newString = new StringBuilder();
char ch;
for (int i = 0; i < inString.Length; i++)
{
ch = inString[i];
// remove any characters outside the valid UTF-8 range as well as all control characters
// except tabs and new lines
//if ((ch < 0x00FD && ch > 0x001F) || ch == '\t' || ch == '\n' || ch == '\r')
//if using .NET version prior to 4, use above logic
if (XmlConvert.IsXmlChar(ch)) //this method is new in .NET 4
{
newString.Append(ch);
}
}
return newString.ToString();
}
``` |
20,778 | <p>I have binary data in a file that I can read into a byte array and process with no problem. Now I need to send parts of the data over a network connection as elements in an XML document. My problem is that when I convert the data from an array of bytes to a String and back to an array of bytes, the data is getting corrupted. I've tested this on one machine to isolate the problem to the String conversion, so I now know that it isn't getting corrupted by the XML parser or the network transport.</p>
<p>What I've got right now is</p>
<pre><code>byte[] buffer = ...; // read from file
// a few lines that prove I can process the data successfully
String element = new String(buffer);
byte[] newBuffer = element.getBytes();
// a few lines that try to process newBuffer and fail because it is not the same data anymore
</code></pre>
<p>Does anyone know how to convert binary to String and back without data loss?</p>
<p>Answered: Thanks Sam. I feel like an idiot. I had this answered yesterday because my SAX parser was complaining. For some reason when I ran into this seemingly separate issue, it didn't occur to me that it was a new symptom of the same problem.</p>
<p>EDIT: Just for the sake of completeness, I used the <a href="http://commons.apache.org/codec/apidocs/org/apache/commons/codec/binary/Base64.html" rel="noreferrer">Base64</a> class from the <a href="http://commons.apache.org/" rel="noreferrer">Apache Commons</a> <a href="http://commons.apache.org/codec/" rel="noreferrer">Codec</a> package to solve this problem.</p>
| [
{
"answer_id": 20779,
"author": "Sam",
"author_id": 428,
"author_profile": "https://Stackoverflow.com/users/428",
"pm_score": 5,
"selected": true,
"text": "<p>If you encode it in base64, this will turn any data into ascii safe text, but base64 encoded data is larger than the orignal data</p>\n"
},
{
"answer_id": 20831,
"author": "Herms",
"author_id": 1409,
"author_profile": "https://Stackoverflow.com/users/1409",
"pm_score": 0,
"selected": false,
"text": "<p>How are you building your XML document? If you use java's built in XML classes then the string encoding should be handled for you.</p>\n\n<p>Take a look at the javax.xml and org.xml packages. That's what we use for generating XML docs, and it handles all the string encoding and decoding quite nicely.</p>\n\n<p>---EDIT:</p>\n\n<p>Hmm, I think I misunderstood the problem. You're not trying to encode a regular string, but some set of arbitrary binary data? In that case the Base64 encoding suggested in an earlier comment is probably the way to go. I believe that's a fairly standard way of encoding binary data in XML.</p>\n"
},
{
"answer_id": 20844,
"author": "basszero",
"author_id": 287,
"author_profile": "https://Stackoverflow.com/users/287",
"pm_score": 2,
"selected": false,
"text": "<p>See this question, <a href=\"https://stackoverflow.com/questions/19893\">How do you embed binary data in XML?</a>\nInstead of converting the byte[] into String then pushing into XML somewhere, convert the byte[] to a String via BASE64 encoding (some XML libraries have a type to do this for you). The BASE64 decode once you get the String back from XML.</p>\n\n<p>Use <a href=\"http://commons.apache.org/codec/\" rel=\"nofollow noreferrer\">http://commons.apache.org/codec/</a></p>\n\n<p>You data may be getting messed up due to all sorts of weird character set restrictions and the presence of non-priting characters. Stick w/ BASE64.</p>\n"
},
{
"answer_id": 20860,
"author": "McDowell",
"author_id": 304,
"author_profile": "https://Stackoverflow.com/users/304",
"pm_score": 5,
"selected": false,
"text": "<p><a href=\"http://docs.oracle.com/javase/7/docs/api/java/lang/String.html\" rel=\"noreferrer\">String(byte[])</a> treats the data as the default character encoding. So, how bytes get converted from 8-bit values to 16-bit Java Unicode chars will vary not only between operating systems, but can even vary between different users using different codepages on the same machine! This constructor is only good for decoding one of your own text files. Do not try to convert arbitrary bytes to chars in Java!</p>\n\n<p>Encoding as <a href=\"http://en.wikipedia.org/wiki/Base64\" rel=\"noreferrer\">base64</a> is a good solution. This is how files are sent over SMTP (e-mail). The (free) Apache <a href=\"http://commons.apache.org/codec/\" rel=\"noreferrer\">Commons Codec</a> project will do the job.</p>\n\n<pre class=\"lang-java prettyprint-override\"><code>byte[] bytes = loadFile(file); \n//all chars in encoded are guaranteed to be 7-bit ASCII\nbyte[] encoded = Base64.encodeBase64(bytes);\nString printMe = new String(encoded, \"US-ASCII\");\nSystem.out.println(printMe);\nbyte[] decoded = Base64.decodeBase64(encoded);\n</code></pre>\n\n<p>Alternatively, you can use the Java 6 <a href=\"http://download.oracle.com/javase/6/docs/api/javax/xml/bind/DatatypeConverter.html\" rel=\"noreferrer\">DatatypeConverter</a>:</p>\n\n<pre class=\"lang-java prettyprint-override\"><code>import java.io.*;\nimport java.nio.channels.*;\nimport javax.xml.bind.DatatypeConverter;\n\npublic class EncodeDecode { \n public static void main(String[] args) throws Exception {\n File file = new File(\"/bin/ls\");\n byte[] bytes = loadFile(file, new ByteArrayOutputStream()).toByteArray();\n String encoded = DatatypeConverter.printBase64Binary(bytes);\n System.out.println(encoded);\n byte[] decoded = DatatypeConverter.parseBase64Binary(encoded);\n // check\n for (int i = 0; i < bytes.length; i++) {\n assert bytes[i] == decoded[i];\n }\n }\n\n private static <T extends OutputStream> T loadFile(File file, T out)\n throws IOException {\n FileChannel in = new FileInputStream(file).getChannel();\n try {\n assert in.size() == in.transferTo(0, in.size(), Channels.newChannel(out));\n return out;\n } finally {\n in.close();\n }\n }\n}\n</code></pre>\n"
}
] | 2008/08/21 | [
"https://Stackoverflow.com/questions/20778",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1288/"
] | I have binary data in a file that I can read into a byte array and process with no problem. Now I need to send parts of the data over a network connection as elements in an XML document. My problem is that when I convert the data from an array of bytes to a String and back to an array of bytes, the data is getting corrupted. I've tested this on one machine to isolate the problem to the String conversion, so I now know that it isn't getting corrupted by the XML parser or the network transport.
What I've got right now is
```
byte[] buffer = ...; // read from file
// a few lines that prove I can process the data successfully
String element = new String(buffer);
byte[] newBuffer = element.getBytes();
// a few lines that try to process newBuffer and fail because it is not the same data anymore
```
Does anyone know how to convert binary to String and back without data loss?
Answered: Thanks Sam. I feel like an idiot. I had this answered yesterday because my SAX parser was complaining. For some reason when I ran into this seemingly separate issue, it didn't occur to me that it was a new symptom of the same problem.
EDIT: Just for the sake of completeness, I used the [Base64](http://commons.apache.org/codec/apidocs/org/apache/commons/codec/binary/Base64.html) class from the [Apache Commons](http://commons.apache.org/) [Codec](http://commons.apache.org/codec/) package to solve this problem. | If you encode it in base64, this will turn any data into ascii safe text, but base64 encoded data is larger than the orignal data |
20,794 | <p>If I call <code>os.stat()</code> on a broken <code>symlink</code>, python throws an <code>OSError</code> exception. This makes it useful for finding them. However, there are a few other reasons that <code>os.stat()</code> might throw a similar exception. Is there a more precise way of detecting broken <code>symlinks</code> with Python under Linux?</p>
| [
{
"answer_id": 20843,
"author": "dlamblin",
"author_id": 459,
"author_profile": "https://Stackoverflow.com/users/459",
"pm_score": 2,
"selected": false,
"text": "<p>Can I mention testing for hardlinks without python? /bin/test has the FILE1 -ef FILE2 condition that is true when files share an inode.</p>\n\n<p>Therefore, something like <code>find . -type f -exec test \\{} -ef /path/to/file \\; -print</code> works for hard link testing to a specific file.</p>\n\n<p>Which brings me to reading <code>man test</code> and the mentions of <code>-L</code> and <code>-h</code> which both work on one file and return true if that file is a symbolic link, however that doesn't tell you if the target is missing.</p>\n\n<p>I did find that <code>head -0 FILE1</code> would return an exit code of <code>0</code> if the file can be opened and a <code>1</code> if it cannot, which in the case of a symbolic link to a regular file works as a test for whether it's target can be read.</p>\n"
},
{
"answer_id": 20845,
"author": "jj33",
"author_id": 430,
"author_profile": "https://Stackoverflow.com/users/430",
"pm_score": 1,
"selected": false,
"text": "<p>I'm not a python guy but it looks like os.readlink()? The logic I would use in perl is to use readlink() to find the target and the use stat() to test to see if the target exists.</p>\n\n<p>Edit: I banged out some perl that demos readlink. I believe perl's stat and readlink and python's os.stat() and os.readlink()are both wrappers for the system calls, so this should translate reasonable well as proof of concept code:</p>\n\n<pre><code>wembley 0 /home/jj33/swap > cat p\nmy $f = shift;\n\nwhile (my $l = readlink($f)) {\n print \"$f -> $l\\n\";\n $f = $l;\n}\n\nif (!-e $f) {\n print \"$f doesn't exist\\n\";\n}\nwembley 0 /home/jj33/swap > ls -l | grep ^l\nlrwxrwxrwx 1 jj33 users 17 Aug 21 14:30 link -> non-existant-file\nlrwxrwxrwx 1 root users 31 Oct 10 2007 mm -> ../systems/mm/20071009-rewrite//\nlrwxrwxrwx 1 jj33 users 2 Aug 21 14:34 mmm -> mm/\nwembley 0 /home/jj33/swap > perl p mm\nmm -> ../systems/mm/20071009-rewrite/\nwembley 0 /home/jj33/swap > perl p mmm\nmmm -> mm\nmm -> ../systems/mm/20071009-rewrite/\nwembley 0 /home/jj33/swap > perl p link\nlink -> non-existant-file\nnon-existant-file doesn't exist\nwembley 0 /home/jj33/swap >\n</code></pre>\n"
},
{
"answer_id": 20848,
"author": "Greg Hewgill",
"author_id": 893,
"author_profile": "https://Stackoverflow.com/users/893",
"pm_score": 4,
"selected": false,
"text": "<p><a href=\"https://docs.python.org/2/library/os.html#os.lstat\" rel=\"nofollow noreferrer\">os.lstat()</a> may be helpful. If lstat() succeeds and stat() fails, then it's probably a broken link.</p>\n"
},
{
"answer_id": 20859,
"author": "Jason Baker",
"author_id": 2147,
"author_profile": "https://Stackoverflow.com/users/2147",
"pm_score": 2,
"selected": false,
"text": "<p><a href=\"http://docs.python.org/lib/module-os.path.html\" rel=\"nofollow noreferrer\">os.path</a></p>\n\n<p>You may try using realpath() to get what the symlink points to, then trying to determine if it's a valid file using is file.</p>\n\n<p>(I'm not able to try that out at the moment, so you'll have to play around with it and see what you get)</p>\n"
},
{
"answer_id": 26957,
"author": "Thomas Vander Stichele",
"author_id": 2900,
"author_profile": "https://Stackoverflow.com/users/2900",
"pm_score": 6,
"selected": true,
"text": "<p>A common Python saying is that it's easier to ask forgiveness than permission. While I'm not a fan of this statement in real life, it does apply in a lot of cases. Usually you want to avoid code that chains two system calls on the same file, because you never know what will happen to the file in between your two calls in your code.</p>\n\n<p><strong>A typical mistake is to write something like</strong>:</p>\n\n<pre><code>if os.path.exists(path):\n os.unlink(path)\n</code></pre>\n\n<p>The second call (os.unlink) may fail if something else deleted it after your if test, raise an Exception, and stop the rest of your function from executing. (You might think this doesn't happen in real life, but we just fished another bug like that out of our codebase last week - and it was the kind of bug that left a few programmers scratching their head and claiming 'Heisenbug' for the last few months)</p>\n\n<p>So, in your particular case, I would probably do:</p>\n\n<pre><code>try:\n os.stat(path)\nexcept OSError, e:\n if e.errno == errno.ENOENT:\n print 'path %s does not exist or is a broken symlink' % path\n else:\n raise e\n</code></pre>\n\n<p>The annoyance here is that stat returns the same error code for a symlink that just isn't there and a broken symlink.</p>\n\n<p>So, I guess you have no choice than to break the atomicity, and do something like</p>\n\n<pre><code>if not os.path.exists(os.readlink(path)):\n print 'path %s is a broken symlink' % path\n</code></pre>\n"
},
{
"answer_id": 31102280,
"author": "am70",
"author_id": 5058564,
"author_profile": "https://Stackoverflow.com/users/5058564",
"pm_score": 4,
"selected": false,
"text": "<p>This is not atomic but it works.</p>\n<p><code> os.path.islink(filename) and not os.path.exists(filename)</code></p>\n<p>Indeed by <a href=\"https://docs.python.org/2/library/os.path.html\" rel=\"noreferrer\">RTFM</a>\n(reading the fantastic manual) we see</p>\n<blockquote>\n<p>os.path.exists(path)</p>\n<p>Return True if path refers to an existing path. Returns False for broken symbolic links.</p>\n</blockquote>\n<p>It also says:</p>\n<blockquote>\n<p>On some platforms, this function may return False if permission is not granted to execute os.stat() on the requested file, even if the path physically exists.</p>\n</blockquote>\n<p>So if you are worried about permissions, you should add other clauses.</p>\n"
},
{
"answer_id": 40274852,
"author": "Pierre D",
"author_id": 758174,
"author_profile": "https://Stackoverflow.com/users/758174",
"pm_score": 0,
"selected": false,
"text": "<p>I had a similar problem: how to catch broken symlinks, even when they occur in some parent dir? I also wanted to log all of them (in an application dealing with a fairly large number of files), but without too many repeats.</p>\n\n<p>Here is what I came up with, including unit tests.</p>\n\n<p><strong>fileutil.py</strong>:</p>\n\n<pre><code>import os\nfrom functools import lru_cache\nimport logging\n\nlogger = logging.getLogger(__name__)\n\n@lru_cache(maxsize=2000)\ndef check_broken_link(filename):\n \"\"\"\n Check for broken symlinks, either at the file level, or in the\n hierarchy of parent dirs.\n If it finds a broken link, an ERROR message is logged.\n The function is cached, so that the same error messages are not repeated.\n\n Args:\n filename: file to check\n\n Returns:\n True if the file (or one of its parents) is a broken symlink.\n False otherwise (i.e. either it exists or not, but no element\n on its path is a broken link).\n\n \"\"\"\n if os.path.isfile(filename) or os.path.isdir(filename):\n return False\n if os.path.islink(filename):\n # there is a symlink, but it is dead (pointing nowhere)\n link = os.readlink(filename)\n logger.error('broken symlink: {} -> {}'.format(filename, link))\n return True\n # ok, we have either:\n # 1. a filename that simply doesn't exist (but the containing dir\n does exist), or\n # 2. a broken link in some parent dir\n parent = os.path.dirname(filename)\n if parent == filename:\n # reached root\n return False\n return check_broken_link(parent)\n</code></pre>\n\n<p>Unit tests:</p>\n\n<pre><code>import logging\nimport shutil\nimport tempfile\nimport os\n\nimport unittest\nfrom ..util import fileutil\n\n\nclass TestFile(unittest.TestCase):\n\n def _mkdir(self, path, create=True):\n d = os.path.join(self.test_dir, path)\n if create:\n os.makedirs(d, exist_ok=True)\n return d\n\n def _mkfile(self, path, create=True):\n f = os.path.join(self.test_dir, path)\n if create:\n d = os.path.dirname(f)\n os.makedirs(d, exist_ok=True)\n with open(f, mode='w') as fp:\n fp.write('hello')\n return f\n\n def _mklink(self, target, path):\n f = os.path.join(self.test_dir, path)\n d = os.path.dirname(f)\n os.makedirs(d, exist_ok=True)\n os.symlink(target, f)\n return f\n\n def setUp(self):\n # reset the lru_cache of check_broken_link\n fileutil.check_broken_link.cache_clear()\n\n # create a temporary directory for our tests\n self.test_dir = tempfile.mkdtemp()\n\n # create a small tree of dirs, files, and symlinks\n self._mkfile('a/b/c/foo.txt')\n self._mklink('b', 'a/x')\n self._mklink('b/c/foo.txt', 'a/f')\n self._mklink('../..', 'a/b/c/y')\n self._mklink('not_exist.txt', 'a/b/c/bad_link.txt')\n bad_path = self._mkfile('a/XXX/c/foo.txt', create=False)\n self._mklink(bad_path, 'a/b/c/bad_path.txt')\n self._mklink('not_a_dir', 'a/bad_dir')\n\n def tearDown(self):\n # Remove the directory after the test\n shutil.rmtree(self.test_dir)\n\n def catch_check_broken_link(self, expected_errors, expected_result, path):\n filename = self._mkfile(path, create=False)\n with self.assertLogs(level='ERROR') as cm:\n result = fileutil.check_broken_link(filename)\n logging.critical('nothing') # trick: emit one extra message, so the with assertLogs block doesn't fail\n error_logs = [r for r in cm.records if r.levelname is 'ERROR']\n actual_errors = len(error_logs)\n self.assertEqual(expected_result, result, msg=path)\n self.assertEqual(expected_errors, actual_errors, msg=path)\n\n def test_check_broken_link_exists(self):\n self.catch_check_broken_link(0, False, 'a/b/c/foo.txt')\n self.catch_check_broken_link(0, False, 'a/x/c/foo.txt')\n self.catch_check_broken_link(0, False, 'a/f')\n self.catch_check_broken_link(0, False, 'a/b/c/y/b/c/y/b/c/foo.txt')\n\n def test_check_broken_link_notfound(self):\n self.catch_check_broken_link(0, False, 'a/b/c/not_found.txt')\n\n def test_check_broken_link_badlink(self):\n self.catch_check_broken_link(1, True, 'a/b/c/bad_link.txt')\n self.catch_check_broken_link(0, True, 'a/b/c/bad_link.txt')\n\n def test_check_broken_link_badpath(self):\n self.catch_check_broken_link(1, True, 'a/b/c/bad_path.txt')\n self.catch_check_broken_link(0, True, 'a/b/c/bad_path.txt')\n\n def test_check_broken_link_badparent(self):\n self.catch_check_broken_link(1, True, 'a/bad_dir/c/foo.txt')\n self.catch_check_broken_link(0, True, 'a/bad_dir/c/foo.txt')\n # bad link, but shouldn't log a new error:\n self.catch_check_broken_link(0, True, 'a/bad_dir/c')\n # bad link, but shouldn't log a new error:\n self.catch_check_broken_link(0, True, 'a/bad_dir')\n\nif __name__ == '__main__':\n unittest.main()\n</code></pre>\n"
},
{
"answer_id": 64213004,
"author": "Владислав Шибалов",
"author_id": 14395948,
"author_profile": "https://Stackoverflow.com/users/14395948",
"pm_score": 2,
"selected": false,
"text": "<p>I used this variant, When symlink is broken it will return false for the path.exists and true for path.islink, so combining this two facts we may use the following:</p>\n<pre><code>def kek(argum):\n if path.exists("/root/" + argum) == False and path.islink("/root/" + argum) == True:\n print("The path is a broken link, location: " + os.readlink("/root/" + argum))\n else:\n return "No broken links fond"\n</code></pre>\n"
}
] | 2008/08/21 | [
"https://Stackoverflow.com/questions/20794",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1892/"
] | If I call `os.stat()` on a broken `symlink`, python throws an `OSError` exception. This makes it useful for finding them. However, there are a few other reasons that `os.stat()` might throw a similar exception. Is there a more precise way of detecting broken `symlinks` with Python under Linux? | A common Python saying is that it's easier to ask forgiveness than permission. While I'm not a fan of this statement in real life, it does apply in a lot of cases. Usually you want to avoid code that chains two system calls on the same file, because you never know what will happen to the file in between your two calls in your code.
**A typical mistake is to write something like**:
```
if os.path.exists(path):
os.unlink(path)
```
The second call (os.unlink) may fail if something else deleted it after your if test, raise an Exception, and stop the rest of your function from executing. (You might think this doesn't happen in real life, but we just fished another bug like that out of our codebase last week - and it was the kind of bug that left a few programmers scratching their head and claiming 'Heisenbug' for the last few months)
So, in your particular case, I would probably do:
```
try:
os.stat(path)
except OSError, e:
if e.errno == errno.ENOENT:
print 'path %s does not exist or is a broken symlink' % path
else:
raise e
```
The annoyance here is that stat returns the same error code for a symlink that just isn't there and a broken symlink.
So, I guess you have no choice than to break the atomicity, and do something like
```
if not os.path.exists(os.readlink(path)):
print 'path %s is a broken symlink' % path
``` |
20,797 | <p>I have a byte array in memory, read from a file. I would like to split the byte array at a certain point (index) without having to just create a new byte array and copy each byte at a time, increasing the in memory foot print of the operation. What I would like is something like this:</p>
<pre><code>byte[] largeBytes = [1,2,3,4,5,6,7,8,9];
byte[] smallPortion;
smallPortion = split(largeBytes, 3);
</code></pre>
<p><code>smallPortion</code> would equal 1,2,3,4<br>
<code>largeBytes</code> would equal 5,6,7,8,9</p>
| [
{
"answer_id": 20826,
"author": "Stu",
"author_id": 414,
"author_profile": "https://Stackoverflow.com/users/414",
"pm_score": 0,
"selected": false,
"text": "<p>You can't. What you might want is keep a starting point and number of items; in essence, build iterators. If this is C++, you can just use <code>std::vector<int></code> and use the built-in ones.</p>\n\n<p>In C#, I'd build a small iterator class that holds start index, count and implements <code>IEnumerable<></code>.</p>\n"
},
{
"answer_id": 20949,
"author": "Michał Piaskowski",
"author_id": 1534,
"author_profile": "https://Stackoverflow.com/users/1534",
"pm_score": 5,
"selected": true,
"text": "<p>This is how I would do that:</p>\n\n<pre><code>using System;\nusing System.Collections;\nusing System.Collections.Generic;\n\nclass ArrayView<T> : IEnumerable<T>\n{\n private readonly T[] array;\n private readonly int offset, count;\n\n public ArrayView(T[] array, int offset, int count)\n {\n this.array = array;\n this.offset = offset;\n this.count = count;\n }\n\n public int Length\n {\n get { return count; }\n }\n\n public T this[int index]\n {\n get\n {\n if (index < 0 || index >= this.count)\n throw new IndexOutOfRangeException();\n else\n return this.array[offset + index];\n }\n set\n {\n if (index < 0 || index >= this.count)\n throw new IndexOutOfRangeException();\n else\n this.array[offset + index] = value;\n }\n }\n\n public IEnumerator<T> GetEnumerator()\n {\n for (int i = offset; i < offset + count; i++)\n yield return array[i];\n }\n\n IEnumerator IEnumerable.GetEnumerator()\n {\n IEnumerator<T> enumerator = this.GetEnumerator();\n while (enumerator.MoveNext())\n {\n yield return enumerator.Current;\n }\n }\n}\n\nclass Program\n{\n static void Main(string[] args)\n {\n byte[] arr = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 0 };\n ArrayView<byte> p1 = new ArrayView<byte>(arr, 0, 5);\n ArrayView<byte> p2 = new ArrayView<byte>(arr, 5, 5);\n Console.WriteLine(\"First array:\");\n foreach (byte b in p1)\n {\n Console.Write(b);\n }\n Console.Write(\"\\n\");\n Console.WriteLine(\"Second array:\");\n foreach (byte b in p2)\n {\n Console.Write(b);\n }\n Console.ReadKey();\n }\n}\n</code></pre>\n"
},
{
"answer_id": 20990,
"author": "Tim Frey",
"author_id": 1471,
"author_profile": "https://Stackoverflow.com/users/1471",
"pm_score": 1,
"selected": false,
"text": "<p>I'm not sure what you mean by:</p>\n\n<blockquote>\n <p>I would like to split the byte array at a certain point(index) without having to just create a new byte array and copy each byte at a time, increasing the in memory foot print of the operation.</p>\n</blockquote>\n\n<p>In most languages, certainly C#, once an array has been allocated, there is no way to change the size of it. It sounds like you're looking for a way to change the length of an array, which you can't. You also want to somehow recycle the memory for the second part of the array, to create a second array, which you also can't do.</p>\n\n<p>In summary: just create a new array.</p>\n"
},
{
"answer_id": 1662438,
"author": "Eren Ersönmez",
"author_id": 201088,
"author_profile": "https://Stackoverflow.com/users/201088",
"pm_score": 5,
"selected": false,
"text": "<p>FYI. <code>System.ArraySegment<T></code> structure basically is the same thing as <code>ArrayView<T></code> in the code above. You can use this out-of-the-box structure in the same way, if you'd like. </p>\n"
},
{
"answer_id": 5057108,
"author": "Alireza Naghizadeh",
"author_id": 625217,
"author_profile": "https://Stackoverflow.com/users/625217",
"pm_score": 5,
"selected": false,
"text": "<p>In C# with Linq you can do this:</p>\n\n<pre><code>smallPortion = largeBytes.Take(4).ToArray();\nlargeBytes = largeBytes.Skip(4).Take(5).ToArray();\n</code></pre>\n\n<p>;)</p>\n"
},
{
"answer_id": 13176553,
"author": "Robert Wisniewski",
"author_id": 1791254,
"author_profile": "https://Stackoverflow.com/users/1791254",
"pm_score": 2,
"selected": false,
"text": "<p>Try this one: </p>\n\n<pre><code>private IEnumerable<byte[]> ArraySplit(byte[] bArray, int intBufforLengt)\n {\n int bArrayLenght = bArray.Length;\n byte[] bReturn = null;\n\n int i = 0;\n for (; bArrayLenght > (i + 1) * intBufforLengt; i++)\n {\n bReturn = new byte[intBufforLengt];\n Array.Copy(bArray, i * intBufforLengt, bReturn, 0, intBufforLengt);\n yield return bReturn;\n }\n\n int intBufforLeft = bArrayLenght - i * intBufforLengt;\n if (intBufforLeft > 0)\n {\n bReturn = new byte[intBufforLeft];\n Array.Copy(bArray, i * intBufforLengt, bReturn, 0, intBufforLeft);\n yield return bReturn;\n }\n }\n</code></pre>\n"
},
{
"answer_id": 44464131,
"author": "orad",
"author_id": 450913,
"author_profile": "https://Stackoverflow.com/users/450913",
"pm_score": 2,
"selected": false,
"text": "<p>As <a href=\"https://stackoverflow.com/a/1662438/450913\">Eren said</a>, you can use <code>ArraySegment<T></code>. Here's an extension method and usage example:</p>\n\n<pre><code>public static class ArrayExtensionMethods\n{\n public static ArraySegment<T> GetSegment<T>(this T[] arr, int offset, int? count = null)\n {\n if (count == null) { count = arr.Length - offset; }\n return new ArraySegment<T>(arr, offset, count.Value);\n }\n}\n\nvoid Main()\n{\n byte[] arr = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 0 };\n var p1 = arr.GetSegment(0, 5);\n var p2 = arr.GetSegment(5);\n Console.WriteLine(\"First array:\");\n foreach (byte b in p1)\n {\n Console.Write(b);\n }\n Console.Write(\"\\n\");\n Console.WriteLine(\"Second array:\");\n foreach (byte b in p2)\n {\n Console.Write(b);\n }\n}\n</code></pre>\n"
},
{
"answer_id": 66403734,
"author": "Yefka",
"author_id": 1008954,
"author_profile": "https://Stackoverflow.com/users/1008954",
"pm_score": 0,
"selected": false,
"text": "<p>I tried different algorithms :</p>\n<ul>\n<li>Skip().Take() => the worst, by far</li>\n<li>Array.Copy</li>\n<li>ArraySegment</li>\n<li>new Guid(int, int16, int16 ...)</li>\n</ul>\n<p>The latest being the fastest I'm now using this extension method:</p>\n<pre class=\"lang-cs prettyprint-override\"><code> public static Guid ToGuid(this byte[] byteArray, int offset)\n {\n return new Guid(BitConverter.ToInt32(byteArray, offset), BitConverter.ToInt16(byteArray, offset + 4), BitConverter.ToInt16(byteArray, offset + 6), byteArray[offset + 8], byteArray[offset + 9], byteArray[offset + 10], byteArray[offset + 11], byteArray[offset + 12], byteArray[offset + 13], byteArray[offset + 14], byteArray[offset + 15]);\n }\n</code></pre>\n<p>With a byte array with 10000000 guids:</p>\n<pre><code>Done (Skip().Take()) in 1,156ms (for only 100000 guids :))\nDone (Array.Copy) in 1,219ms\nDone (ToGuid extension) in 994ms\nDone (ArraySegment) in 2,411ms\n</code></pre>\n"
}
] | 2008/08/21 | [
"https://Stackoverflow.com/questions/20797",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1048/"
] | I have a byte array in memory, read from a file. I would like to split the byte array at a certain point (index) without having to just create a new byte array and copy each byte at a time, increasing the in memory foot print of the operation. What I would like is something like this:
```
byte[] largeBytes = [1,2,3,4,5,6,7,8,9];
byte[] smallPortion;
smallPortion = split(largeBytes, 3);
```
`smallPortion` would equal 1,2,3,4
`largeBytes` would equal 5,6,7,8,9 | This is how I would do that:
```
using System;
using System.Collections;
using System.Collections.Generic;
class ArrayView<T> : IEnumerable<T>
{
private readonly T[] array;
private readonly int offset, count;
public ArrayView(T[] array, int offset, int count)
{
this.array = array;
this.offset = offset;
this.count = count;
}
public int Length
{
get { return count; }
}
public T this[int index]
{
get
{
if (index < 0 || index >= this.count)
throw new IndexOutOfRangeException();
else
return this.array[offset + index];
}
set
{
if (index < 0 || index >= this.count)
throw new IndexOutOfRangeException();
else
this.array[offset + index] = value;
}
}
public IEnumerator<T> GetEnumerator()
{
for (int i = offset; i < offset + count; i++)
yield return array[i];
}
IEnumerator IEnumerable.GetEnumerator()
{
IEnumerator<T> enumerator = this.GetEnumerator();
while (enumerator.MoveNext())
{
yield return enumerator.Current;
}
}
}
class Program
{
static void Main(string[] args)
{
byte[] arr = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 0 };
ArrayView<byte> p1 = new ArrayView<byte>(arr, 0, 5);
ArrayView<byte> p2 = new ArrayView<byte>(arr, 5, 5);
Console.WriteLine("First array:");
foreach (byte b in p1)
{
Console.Write(b);
}
Console.Write("\n");
Console.WriteLine("Second array:");
foreach (byte b in p2)
{
Console.Write(b);
}
Console.ReadKey();
}
}
``` |
20,840 | <p>Why should I or shouldn't I use dirty reads:</p>
<pre><code>set transaction isolation level read uncommitted
</code></pre>
<p>in SQL Server?</p>
| [
{
"answer_id": 20879,
"author": "Tokabi",
"author_id": 315,
"author_profile": "https://Stackoverflow.com/users/315",
"pm_score": 3,
"selected": false,
"text": "<p>Generally when you need to do a sizeable (or frequent) queries to busy tables, where read committed would possibly be blocked by locks from uncommited transactions, but ONLY when you can live with inaccurate data. </p>\n\n<p>As an example, on a gaming web site I worked on recently there was a summary display of some stats about recent games, this was all based on dirty reads, it was more important for us to include then exclude the transactional data not yet committed (we knew anyway that few, if any, transactions would be backed out), we felt that on average the data would be more accurate that way.</p>\n"
},
{
"answer_id": 20881,
"author": "SQLMenace",
"author_id": 740,
"author_profile": "https://Stackoverflow.com/users/740",
"pm_score": 0,
"selected": false,
"text": "<p>use it if you want the data back right away and it is not that important if it is right<br>\ndo not use if if the data is important to be correct or if you are doing updates with it</p>\n\n<p>Also take a look at snapshot isolation which has been introduced in sql server 2005</p>\n"
},
{
"answer_id": 20890,
"author": "Yaakov Ellis",
"author_id": 51,
"author_profile": "https://Stackoverflow.com/users/51",
"pm_score": 5,
"selected": true,
"text": "<p>From <a href=\"http://msdn.microsoft.com/en-us/library/aa259216(SQL.80).aspx\" rel=\"noreferrer\">MSDN</a>:</p>\n\n<blockquote>\n <p>When this option is set, it is possible to read uncommitted or dirty data; values in the data can be changed and rows can appear or disappear in the data set before the end of the transaction. </p>\n</blockquote>\n\n<p>Simply put, when you are using this isolation level, and you are performing multiple queries on an active table as part of one transaction, there is no guarantee that the information returned to you within different parts of the transaction will remain the same. You could query the same data twice within one transaction and get different results (this might happen in the case where a different user was updating the same data in the midst of your transaction). This can obviously have severe ramifications for parts of your application that rely on data integrity.</p>\n"
},
{
"answer_id": 34477845,
"author": "K ROHAN",
"author_id": 5719882,
"author_profile": "https://Stackoverflow.com/users/5719882",
"pm_score": -1,
"selected": false,
"text": "<p>The Thing is when you want to read the data before committing, we can do with the help of set transaction isolation level read uncommitted, the data may, or may not change.</p>\n\n<p>We can read the data by using the query:</p>\n\n<pre><code>Select * from table_name with(nolock) \n</code></pre>\n\n<p>This is applicable to only read uncommitted isolation level.</p>\n"
}
] | 2008/08/21 | [
"https://Stackoverflow.com/questions/20840",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/357/"
] | Why should I or shouldn't I use dirty reads:
```
set transaction isolation level read uncommitted
```
in SQL Server? | From [MSDN](http://msdn.microsoft.com/en-us/library/aa259216(SQL.80).aspx):
>
> When this option is set, it is possible to read uncommitted or dirty data; values in the data can be changed and rows can appear or disappear in the data set before the end of the transaction.
>
>
>
Simply put, when you are using this isolation level, and you are performing multiple queries on an active table as part of one transaction, there is no guarantee that the information returned to you within different parts of the transaction will remain the same. You could query the same data twice within one transaction and get different results (this might happen in the case where a different user was updating the same data in the midst of your transaction). This can obviously have severe ramifications for parts of your application that rely on data integrity. |
20,850 | <p>I'm a bit newbieish when it comes to the deeper parts of OSX configuration and am having to put up with a fairly irritating niggle which while I can put up with it, I know under Windows I could have sorted in minutes.</p>
<p>Basically, I have an external disk with two volumes: </p>
<p>One is an HFS+ volume which I use for TimeMachine backups.
The other, an NTFS volume that I use for general file copying etc on Mac and Windows boxes.</p>
<p>So what happens is that whenever I plug in the disk into my Mac USB, OSX goes off and mounts both volumes and shows an icon on the desktop for each. The thing is that to remove the disk you have to eject the volume and in this case do it for both volumes, which causes an annoying warning dialog to be shown every time. </p>
<p>What I'd prefer is some way to prevent the NTFS volume from auto-mounting altogether. I've done some hefty googling and here's a list of things I've tried so far:</p>
<ul>
<li>I've tried going through options in Disk Utility</li>
<li>I've tried setting AutoMount to No in /etc/hostconfig but that is a bit too global for my liking.</li>
<li>I've also tried the suggested approach to putting settings in fstab but it appears the OSX (10.5) is ignoring these settings.</li>
</ul>
<p>Any other suggestions would be welcomed. Just a little dissapointed that I can't just tick a box somewhere (or untick).</p>
<p>EDIT: Thanks heaps to hop for the answer it worked a treat. For the record it turns out that it wasn't OSX not picking up the settings I actually had "msdos" instead of "ntfs" in the fs type column.</p>
| [
{
"answer_id": 21101,
"author": "Orion Edwards",
"author_id": 234,
"author_profile": "https://Stackoverflow.com/users/234",
"pm_score": 1,
"selected": false,
"text": "<p>This is not directly an answer, but</p>\n\n<blockquote>\n <p>The thing is that to remove the disk you have to eject the volume and in this case do it for both volumes</p>\n</blockquote>\n\n<p>I have a similar situation.</p>\n\n<p>OSX remembers where you put your icons on the desktop - I've moved the icons for both of my removable drives to <em>just</em> above where the trash can lives.</p>\n\n<p>Eject procedure becomes</p>\n\n<ul>\n<li>Hit top-left of screen with mouse to show desktop</li>\n<li>Drag small box around both removable drives</li>\n<li>Drag 2cm onto trash so they both get ejected</li>\n<li>Remove firewire cable</li>\n</ul>\n"
},
{
"answer_id": 36907,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 3,
"selected": true,
"text": "<p>The following entry in <code>/etc/fstab</code> will do what you want, even on 10.5 (Leopard):</p>\n\n<pre><code>LABEL=VolumeName none ntfs noauto\n</code></pre>\n\n<p>If the file is not already there, just create it. Do not use <code>/etc/fstab.hd</code>! No reloading of <code>diskarbitrationd</code> needed.</p>\n\n<p>If this still doesn't work for you, maybe you can find a hint in the syslog.</p>\n"
}
] | 2008/08/21 | [
"https://Stackoverflow.com/questions/20850",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1120/"
] | I'm a bit newbieish when it comes to the deeper parts of OSX configuration and am having to put up with a fairly irritating niggle which while I can put up with it, I know under Windows I could have sorted in minutes.
Basically, I have an external disk with two volumes:
One is an HFS+ volume which I use for TimeMachine backups.
The other, an NTFS volume that I use for general file copying etc on Mac and Windows boxes.
So what happens is that whenever I plug in the disk into my Mac USB, OSX goes off and mounts both volumes and shows an icon on the desktop for each. The thing is that to remove the disk you have to eject the volume and in this case do it for both volumes, which causes an annoying warning dialog to be shown every time.
What I'd prefer is some way to prevent the NTFS volume from auto-mounting altogether. I've done some hefty googling and here's a list of things I've tried so far:
* I've tried going through options in Disk Utility
* I've tried setting AutoMount to No in /etc/hostconfig but that is a bit too global for my liking.
* I've also tried the suggested approach to putting settings in fstab but it appears the OSX (10.5) is ignoring these settings.
Any other suggestions would be welcomed. Just a little dissapointed that I can't just tick a box somewhere (or untick).
EDIT: Thanks heaps to hop for the answer it worked a treat. For the record it turns out that it wasn't OSX not picking up the settings I actually had "msdos" instead of "ntfs" in the fs type column. | The following entry in `/etc/fstab` will do what you want, even on 10.5 (Leopard):
```
LABEL=VolumeName none ntfs noauto
```
If the file is not already there, just create it. Do not use `/etc/fstab.hd`! No reloading of `diskarbitrationd` needed.
If this still doesn't work for you, maybe you can find a hint in the syslog. |
20,856 | <p>I've heard of a few ways to implement tagging; using a mapping table between TagID and ItemID (makes sense to me, but does it scale?), adding a fixed number of possible TagID columns to ItemID (seems like a bad idea), Keeping tags in a text column that's comma separated (sounds crazy but could work). I've even heard someone recommend a sparse matrix, but then how do the tag names grow gracefully?</p>
<p>Am I missing a best practice for tags?</p>
| [
{
"answer_id": 20871,
"author": "Yaakov Ellis",
"author_id": 51,
"author_profile": "https://Stackoverflow.com/users/51",
"pm_score": 10,
"selected": true,
"text": "<p>Three tables (one for storing all items, one for all tags, and one for the relation between the two), properly indexed, with foreign keys set running on a proper database, should work well and scale properly. </p>\n\n<pre><code>Table: Item\nColumns: ItemID, Title, Content\n\nTable: Tag\nColumns: TagID, Title\n\nTable: ItemTag\nColumns: ItemID, TagID\n</code></pre>\n"
},
{
"answer_id": 20873,
"author": "Mark Biek",
"author_id": 305,
"author_profile": "https://Stackoverflow.com/users/305",
"pm_score": 3,
"selected": false,
"text": "<p>I've always kept the tags in a separate table and then had a mapping table. Of course I've never done anything on a really large scale either.</p>\n\n<p>Having a \"tags\" table and a map table makes it pretty trivial to generate tag clouds & such since you can easily put together SQL to get a list of tags with counts of how often each tag is used.</p>\n"
},
{
"answer_id": 48348,
"author": "David Schmitt",
"author_id": 4918,
"author_profile": "https://Stackoverflow.com/users/4918",
"pm_score": 4,
"selected": false,
"text": "<p>Use a single formatted text column[1] for storing the tags and use a capable full text search engine to index this. Else you will run into scaling problems when trying to implement boolean queries.</p>\n\n<p>If you need details about the tags you have, you can either keep track of it in a incrementally maintained table or run a batch job to extract the information.</p>\n\n<p>[1] Some RDBMS even provide a native array type which might be even better suited for storage by not needing a parsing step, but might cause problems with the full text search.</p>\n"
},
{
"answer_id": 48714,
"author": "Nick Retallack",
"author_id": 2653,
"author_profile": "https://Stackoverflow.com/users/2653",
"pm_score": 5,
"selected": false,
"text": "<p>If you are using a database that supports map-reduce, like couchdb, storing tags in a plain text field or list field is indeed the best way. Example:</p>\n\n<pre><code>tagcloud: {\n map: function(doc){ \n for(tag in doc.tags){ \n emit(doc.tags[tag],1) \n }\n }\n reduce: function(keys,values){\n return values.length\n }\n}\n</code></pre>\n\n<p>Running this with group=true will group the results by tag name, and even return a count of the number of times that tag was encountered. It's very similar to <a href=\"http://web.archive.org/web/20090107022604/http://jchris.mfdz.com/posts/107\" rel=\"noreferrer\">counting the occurrences of a word in text</a>.</p>\n"
},
{
"answer_id": 18923641,
"author": "Scheintod",
"author_id": 1455622,
"author_profile": "https://Stackoverflow.com/users/1455622",
"pm_score": 7,
"selected": false,
"text": "<p>Normally I would agree with Yaakov Ellis but in this special case there is another viable solution:</p>\n\n<p>Use two tables:</p>\n\n<pre><code>Table: Item\nColumns: ItemID, Title, Content\nIndexes: ItemID\n\nTable: Tag\nColumns: ItemID, Title\nIndexes: ItemId, Title\n</code></pre>\n\n<p>This has some major advantages:</p>\n\n<p>First it makes development much simpler: in the three-table solution for insert and update of <code>item</code> you have to lookup the <code>Tag</code> table to see if there are already entries. Then you have to join them with new ones. This is no trivial task.</p>\n\n<p>Then it makes queries simpler (and perhaps faster). There are three major database queries which you will do: Output all <code>Tags</code> for one <code>Item</code>, draw a Tag-Cloud and select all items for one Tag Title.</p>\n\n<p><strong>All Tags for one Item:</strong></p>\n\n<p>3-Table:</p>\n\n<pre><code>SELECT Tag.Title \n FROM Tag \n JOIN ItemTag ON Tag.TagID = ItemTag.TagID\n WHERE ItemTag.ItemID = :id\n</code></pre>\n\n<p>2-Table:</p>\n\n<pre><code>SELECT Tag.Title\nFROM Tag\nWHERE Tag.ItemID = :id\n</code></pre>\n\n<p><strong>Tag-Cloud:</strong></p>\n\n<p>3-Table:</p>\n\n<pre><code>SELECT Tag.Title, count(*)\n FROM Tag\n JOIN ItemTag ON Tag.TagID = ItemTag.TagID\n GROUP BY Tag.Title\n</code></pre>\n\n<p>2-Table:</p>\n\n<pre><code>SELECT Tag.Title, count(*)\n FROM Tag\n GROUP BY Tag.Title\n</code></pre>\n\n<p><strong>Items for one Tag:</strong></p>\n\n<p>3-Table:</p>\n\n<pre><code>SELECT Item.*\n FROM Item\n JOIN ItemTag ON Item.ItemID = ItemTag.ItemID\n JOIN Tag ON ItemTag.TagID = Tag.TagID\n WHERE Tag.Title = :title\n</code></pre>\n\n<p>2-Table:</p>\n\n<pre><code>SELECT Item.*\n FROM Item\n JOIN Tag ON Item.ItemID = Tag.ItemID\n WHERE Tag.Title = :title\n</code></pre>\n\n<p>But there are some drawbacks, too: It could take more space in the database (which could lead to more disk operations which is slower) and it's not normalized which could lead to inconsistencies.</p>\n\n<p>The size argument is not that strong because the very nature of tags is that they are normally pretty small so the size increase is not a large one. One could argue that the query for the tag title is much faster in a small table which contains each tag only once and this certainly is true. But taking in regard the savings for not having to join and the fact that you can build a good index on them could easily compensate for this. This of course depends heavily on the size of the database you are using.</p>\n\n<p>The inconsistency argument is a little moot too. Tags are free text fields and there is no expected operation like 'rename all tags \"foo\" to \"bar\"'.</p>\n\n<p>So tldr: I would go for the two-table solution. (In fact I'm going to. I found this article to see if there are valid arguments against it.)</p>\n"
},
{
"answer_id": 33969961,
"author": "user236575",
"author_id": 3279014,
"author_profile": "https://Stackoverflow.com/users/3279014",
"pm_score": -1,
"selected": false,
"text": "<p>I would suggest following design : \nItem Table: \nItemid, taglist1, taglist2<br>\nthis will be fast and make easy saving and retrieving the data at item level. </p>\n\n<p>In parallel build another table: \nTags \ntag \ndo not make tag unique identifier and if you run out of space in 2nd column which contains lets say 100 items create another row. </p>\n\n<p>Now while searching for items for a tag it will be super fast.</p>\n"
}
] | 2008/08/21 | [
"https://Stackoverflow.com/questions/20856",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/459/"
] | I've heard of a few ways to implement tagging; using a mapping table between TagID and ItemID (makes sense to me, but does it scale?), adding a fixed number of possible TagID columns to ItemID (seems like a bad idea), Keeping tags in a text column that's comma separated (sounds crazy but could work). I've even heard someone recommend a sparse matrix, but then how do the tag names grow gracefully?
Am I missing a best practice for tags? | Three tables (one for storing all items, one for all tags, and one for the relation between the two), properly indexed, with foreign keys set running on a proper database, should work well and scale properly.
```
Table: Item
Columns: ItemID, Title, Content
Table: Tag
Columns: TagID, Title
Table: ItemTag
Columns: ItemID, TagID
``` |
20,876 | <p>I'm new to SQL Server Reporting Services, and was wondering the best way to do the following:</p>
<blockquote>
<ul>
<li>Query to get a list of popular IDs</li>
<li>Subquery on each item to get properties from another table</li>
</ul>
</blockquote>
<p>Ideally, the final report columns would look like this:</p>
<pre><code>[ID] [property1] [property2] [SELECT COUNT(*)
FROM AnotherTable
WHERE ForeignID=ID]
</code></pre>
<p>There may be ways to construct a giant SQL query to do this all in one go, but I'd prefer to compartmentalize it. Is the recommended approach to write a VB function to perform the subquery for each row? Thanks for any help.</p>
| [
{
"answer_id": 20895,
"author": "Bryan Roth",
"author_id": 299,
"author_profile": "https://Stackoverflow.com/users/299",
"pm_score": 3,
"selected": true,
"text": "<p>I would recommend using a <a href=\"http://msdn.microsoft.com/en-us/library/ms160348.aspx\" rel=\"nofollow noreferrer\">SubReport</a>. You would place the SubReport in a table cell.</p>\n"
},
{
"answer_id": 20914,
"author": "Carlton Jenke",
"author_id": 1215,
"author_profile": "https://Stackoverflow.com/users/1215",
"pm_score": 0,
"selected": false,
"text": "<p>Simplest method is this:</p>\n\n<pre><code>select *,\n (select count(*) from tbl2 t2 where t2.tbl1ID = t1.tbl1ID) as cnt\nfrom tbl1 t1\n</code></pre>\n\n<p>here is a workable version (using table variables):</p>\n\n<pre><code>declare @tbl1 table\n(\n tbl1ID int,\n prop1 varchar(1),\n prop2 varchar(2)\n)\n\ndeclare @tbl2 table\n(\n tbl2ID int,\n tbl1ID int\n)\n\nselect *,\n (select count(*) from @tbl2 t2 where t2.tbl1ID = t1.tbl1ID) as cnt\nfrom @tbl1 t1\n</code></pre>\n\n<p>Obviously this is just a raw example - standard rules apply like don't select *, etc ...</p>\n\n<hr>\n\n<p><strong>UPDATE from Aug 21 '08 at 21:27:</strong><br>\n@AlexCuse - Yes, totally agree on the performance.</p>\n\n<p>I started to write it with the outer join, but then saw in his sample output the count and thought that was what he wanted, and the count would not return correctly if the tables are outer joined. Not to mention that joins can cause your records to be multiplied (1 entry from tbl1 that matches 2 entries in tbl2 = 2 returns) which can be unintended.</p>\n\n<p>So I guess it really boils down to the specifics on what your query needs to return.</p>\n\n<hr>\n\n<p><strong>UPDATE from Aug 21 '08 at 22:07:</strong><br>\nTo answer the other parts of your question - is a VB function the way to go? No. Absolutely not. Not for something this simple.</p>\n\n<p>Functions are very bad on performance, each row in the return set executes the function.</p>\n\n<p>If you want to \"compartmentalize\" the different parts of the query you have to approach it more like a stored procedure. Build a temp table, do part of the query and insert the results into the table, then do any further queries you need and update the original temp table (or insert into more temp tables).</p>\n"
},
{
"answer_id": 21037,
"author": "AlexCuse",
"author_id": 794,
"author_profile": "https://Stackoverflow.com/users/794",
"pm_score": 0,
"selected": false,
"text": "<p>Depending on how you want the output to look, a subreport could do, or you could group on ID, property1, property2 and show the items from your other table as detail items (assuming you want to show more than just count).</p>\n\n<p>Something like </p>\n\n<pre><code>select t1.ID, t1.property1, t1.property2, t2.somecol, t2.someothercol\nfrom table t1 left join anothertable t2 on t1.ID = t2.ID\n</code></pre>\n\n<p>@Carlton Jenke I think you will find an outer join a better performer than the correlated subquery in the example you gave. Remember that the subquery needs to be run for each row.</p>\n"
}
] | 2008/08/21 | [
"https://Stackoverflow.com/questions/20876",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/109/"
] | I'm new to SQL Server Reporting Services, and was wondering the best way to do the following:
>
> * Query to get a list of popular IDs
> * Subquery on each item to get properties from another table
>
>
>
Ideally, the final report columns would look like this:
```
[ID] [property1] [property2] [SELECT COUNT(*)
FROM AnotherTable
WHERE ForeignID=ID]
```
There may be ways to construct a giant SQL query to do this all in one go, but I'd prefer to compartmentalize it. Is the recommended approach to write a VB function to perform the subquery for each row? Thanks for any help. | I would recommend using a [SubReport](http://msdn.microsoft.com/en-us/library/ms160348.aspx). You would place the SubReport in a table cell. |
20,923 | <p>I need to script the creation of app pools and websites on IIS 6.0. I have been able to create these using adsutil.vbs and iisweb.vbs, but don't know how to set the version of ASP.NET for the sites I have just created to 2.0.50727.0.</p>
<p>Ideally I would like to adsutil.vbs to update the metabase. How do I do this?</p>
| [
{
"answer_id": 20953,
"author": "Chris Miller",
"author_id": 206,
"author_profile": "https://Stackoverflow.com/users/206",
"pm_score": 2,
"selected": false,
"text": "<p>I found the following script <a href=\"http://www.diablopup.net/post/Set-an-IIS-Object%27s-ASPNET-Version-Using-VBScript.aspx\" rel=\"nofollow noreferrer\">posted</a> on Diablo Pup's blog. It uses ADSI automation.</p>\n\n<pre><code>'******************************************************************************************\n' Name: SetASPDotNetVersion\n' Description: Set the script mappings for the specified ASP.NET version\n' Inputs: objIIS, strNewVersion\n'******************************************************************************************\nSub SetASPDotNetVersion(objIIS, strNewVersion)\n Dim i, ScriptMaps, arrVersions(2), thisVersion, thisScriptMap\n Dim strSearchText, strReplaceText\n\n Select Case Trim(LCase(strNewVersion))\n Case \"1.1\"\n strReplaceText = \"v1.1.4322\"\n Case \"2.0\"\n strReplaceText = \"v2.0.50727\"\n Case Else\n wscript.echo \"WARNING: Non-supported ASP.NET version specified!\"\n Exit Sub\n End Select\n\n ScriptMaps = objIIS.ScriptMaps\n arrVersions(0) = \"v1.1.4322\"\n arrVersions(1) = \"v2.0.50727\"\n 'Loop through all three potential old values\n For Each thisVersion in arrVersions\n 'Loop through all the mappings\n For thisScriptMap = LBound(ScriptMaps) to UBound(ScriptMaps)\n 'Replace the old with the new \n ScriptMaps(thisScriptMap) = Replace(ScriptMaps(thisScriptMap), thisVersion, strReplaceText)\n Next\n Next \n\n objIIS.ScriptMaps = ScriptMaps\n objIIS.SetInfo\n wscript.echo \"<-------Set ASP.NET version to \" & strNewVersion & \" successfully.------->\"\nEnd Sub \n</code></pre>\n"
},
{
"answer_id": 21001,
"author": "Kev",
"author_id": 419,
"author_profile": "https://Stackoverflow.com/users/419",
"pm_score": 4,
"selected": true,
"text": "<p>@<a href=\"https://stackoverflow.com/questions/20923/vbscriptiis-how-do-i-automatically-set-aspnet-version-for-a-particular-website#20953\">Chris</a> beat me to the punch on the ADSI way</p>\n\n<p>You can do this using the aspnet_regiis.exe tool. There is one of these tools per version of ASP.NET installed on the machine. You could shell out to -</p>\n\n<p>This configures ASP.NET 1.1</p>\n\n<pre><code>%windir%\\microsoft.net\\framework\\v1.1.4322\\aspnet_regiis -s W3SVC/[iisnumber]/ROOT\n</code></pre>\n\n<p>This configures ASP.NET 2.0</p>\n\n<pre><code>%windir%\\microsoft.net\\framework\\v2.0.50727\\aspnet_regiis -s W3SVC/[iisnumber]/ROOT\n</code></pre>\n\n<p>You probably already know this, but if you have multiple 1.1 and 2.0 sites on your machine, just remember to switch the website you're changing ASP.NET versions on to compatible app pool. ASP.NET 1.1 and 2.0 sites don't mix in the same app pool.</p>\n"
}
] | 2008/08/21 | [
"https://Stackoverflow.com/questions/20923",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/636/"
] | I need to script the creation of app pools and websites on IIS 6.0. I have been able to create these using adsutil.vbs and iisweb.vbs, but don't know how to set the version of ASP.NET for the sites I have just created to 2.0.50727.0.
Ideally I would like to adsutil.vbs to update the metabase. How do I do this? | @[Chris](https://stackoverflow.com/questions/20923/vbscriptiis-how-do-i-automatically-set-aspnet-version-for-a-particular-website#20953) beat me to the punch on the ADSI way
You can do this using the aspnet\_regiis.exe tool. There is one of these tools per version of ASP.NET installed on the machine. You could shell out to -
This configures ASP.NET 1.1
```
%windir%\microsoft.net\framework\v1.1.4322\aspnet_regiis -s W3SVC/[iisnumber]/ROOT
```
This configures ASP.NET 2.0
```
%windir%\microsoft.net\framework\v2.0.50727\aspnet_regiis -s W3SVC/[iisnumber]/ROOT
```
You probably already know this, but if you have multiple 1.1 and 2.0 sites on your machine, just remember to switch the website you're changing ASP.NET versions on to compatible app pool. ASP.NET 1.1 and 2.0 sites don't mix in the same app pool. |
20,926 | <p>Today I was working on a tab navigation for a webpage. I tried the <a href="http://www.alistapart.com/articles/slidingdoors2/" rel="noreferrer">Sliding Doors</a> approach which worked fine. Then I realized that I must include an option to delete a tab (usually a small X in the right corner of each tab). </p>
<p>I wanted to use a nested anchor, which didn't work because it is <a href="http://www.w3.org/TR/html4/struct/links.html#h-12.2.2" rel="noreferrer">not</a> allowed. Then I saw the tab- navigation at <a href="http://www.pageflakes.com" rel="noreferrer">Pageflakes</a>, which was actually working (including nested hyperlinks). Why?</p>
| [
{
"answer_id": 20944,
"author": "Yaakov Ellis",
"author_id": 51,
"author_profile": "https://Stackoverflow.com/users/51",
"pm_score": 4,
"selected": true,
"text": "<p>They must be doing some really crazy stuff with JavaScript to get it to work (notice how neither the parent nor the nested anchor tags have a name or href attribute - all functionality is done through the class name and JS).</p>\n\n<p>Here is what the html looks like:</p>\n\n<pre><code><a class=\"page_tab page_tab\">\n <div class=\"page_title\" title=\"Click to rename this page.\">Click & Type Page Name</div>\n <a class=\"delete_page\" title=\"Click to delete this page\" style=\"display: block;\">X</a>\n</a>\n</code></pre>\n"
},
{
"answer_id": 20967,
"author": "Chris Marasti-Georg",
"author_id": 96,
"author_profile": "https://Stackoverflow.com/users/96",
"pm_score": 0,
"selected": false,
"text": "<p>Actually, the code I had pasted previously was the generated DOM, after all JS manipulation. If you don't have the <a href=\"https://addons.mozilla.org/en-US/firefox/addon/1843\" rel=\"nofollow noreferrer\">Firebug</a> extension for Firefox, you should get it now.</p>\n\n<p>Edit: Deleted the old post, it was no longer useful. Firebug is, so this one is staying :)</p>\n"
},
{
"answer_id": 366021,
"author": "Jakub Narębski",
"author_id": 46058,
"author_profile": "https://Stackoverflow.com/users/46058",
"pm_score": 0,
"selected": false,
"text": "<p>I suspect that working or not working nested links might depend if your browser renders page in strict mode (e.g. XHTML DTD, application/xml+html MIMEtype), or in \"quirks\" mode.</p>\n"
},
{
"answer_id": 2096795,
"author": "Jarosław Przygódzki",
"author_id": 254352,
"author_profile": "https://Stackoverflow.com/users/254352",
"pm_score": 4,
"selected": false,
"text": "<p><a href=\"http://www.w3.org/TR/html401/struct/links.html#h-12.2.2\" rel=\"noreferrer\">Nested links are illegal</a></p>\n"
},
{
"answer_id": 33499678,
"author": "Anas",
"author_id": 2721727,
"author_profile": "https://Stackoverflow.com/users/2721727",
"pm_score": 0,
"selected": false,
"text": "<p>In spite of nested tags are illegal but writing them using JS will work!, try this:</p>\n\n<pre><code>$('<a>', {\n href: 'http://google.com',\n html: '<a>i am nested anchor </a>I am top Anchor'\n }).appendTo($('body'))\n</code></pre>\n"
}
] | 2008/08/21 | [
"https://Stackoverflow.com/questions/20926",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2078/"
] | Today I was working on a tab navigation for a webpage. I tried the [Sliding Doors](http://www.alistapart.com/articles/slidingdoors2/) approach which worked fine. Then I realized that I must include an option to delete a tab (usually a small X in the right corner of each tab).
I wanted to use a nested anchor, which didn't work because it is [not](http://www.w3.org/TR/html4/struct/links.html#h-12.2.2) allowed. Then I saw the tab- navigation at [Pageflakes](http://www.pageflakes.com), which was actually working (including nested hyperlinks). Why? | They must be doing some really crazy stuff with JavaScript to get it to work (notice how neither the parent nor the nested anchor tags have a name or href attribute - all functionality is done through the class name and JS).
Here is what the html looks like:
```
<a class="page_tab page_tab">
<div class="page_title" title="Click to rename this page.">Click & Type Page Name</div>
<a class="delete_page" title="Click to delete this page" style="display: block;">X</a>
</a>
``` |
20,927 | <p>I've got two models: Message and Attachment. Each attachment is attached to a specific message, using a ForeignKey on the Attachment model. Both models have an auto_now DateTimeField called updated. I'm trying to make it so that when any attachment is saved, it also sets the updated field on the associated message to now. Here's my code:</p>
<pre><code>def save(self):
super(Attachment, self).save()
self.message.updated = self.updated
</code></pre>
<p>Will this work, and if you can explain it to me, why? If not, how would I accomplish this?</p>
| [
{
"answer_id": 20983,
"author": "John",
"author_id": 2168,
"author_profile": "https://Stackoverflow.com/users/2168",
"pm_score": 5,
"selected": true,
"text": "<p>You would also need to then save the message. Then it that should work.</p>\n"
},
{
"answer_id": 72359,
"author": "zgoda",
"author_id": 12138,
"author_profile": "https://Stackoverflow.com/users/12138",
"pm_score": 1,
"selected": false,
"text": "<p>DateTime fields with auto_now are automatically updated upon calling <code>save()</code>, so you do not need to update them manually. Django will do this work for you.</p>\n"
},
{
"answer_id": 33449486,
"author": "Serjik",
"author_id": 546822,
"author_profile": "https://Stackoverflow.com/users/546822",
"pm_score": 3,
"selected": false,
"text": "<p>Proper version to work is: (attention to last line <code>self.message.save()</code>)</p>\n\n<pre><code>class Message(models.Model):\n updated = models.DateTimeField(auto_now = True)\n ...\n\nclass Attachment(models.Model):\n updated = models.DateTimeField(auto_now = True)\n message = models.ForeignKey(Message)\n\n def save(self):\n super(Attachment, self).save()\n self.message.save()\n</code></pre>\n"
}
] | 2008/08/21 | [
"https://Stackoverflow.com/questions/20927",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1914/"
] | I've got two models: Message and Attachment. Each attachment is attached to a specific message, using a ForeignKey on the Attachment model. Both models have an auto\_now DateTimeField called updated. I'm trying to make it so that when any attachment is saved, it also sets the updated field on the associated message to now. Here's my code:
```
def save(self):
super(Attachment, self).save()
self.message.updated = self.updated
```
Will this work, and if you can explain it to me, why? If not, how would I accomplish this? | You would also need to then save the message. Then it that should work. |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.