qid
int64 4
8.14M
| question
stringlengths 20
48.3k
| answers
list | date
stringlengths 10
10
| metadata
list | input
stringlengths 12
45k
| output
stringlengths 2
31.8k
|
---|---|---|---|---|---|---|
201,233 |
<p>I have a "settings file" in my Winforms application called Settings.settings with a partial class for custom methods, etc. Is there a way to load / save dynamic settings based on arbitrary keys?</p>
<p>For example, I have some ListViews in my application in which I want to save / load the column widths; Instead of creating a width setting for each column for each list view I would like a simple method to load / save the widths automatically.</p>
<p>Below is an example of the <strong>save</strong> method I have tried:</p>
<pre><code>internal sealed partial class Settings
{
public void SetListViewColumnWidths(ListView listView)
{
String baseKey = listView.Name;
foreach (ColumnHeader h in listView.Columns)
{
String key = String.Format("{0}-{1}", baseKey, h.Index);
this[key] = h.Width;
}
}
}
</code></pre>
<p>When running that code I get the error <strong>"The settings property 'TestsListView-0' was not found."</strong> Is there something I am missing?</p>
|
[
{
"answer_id": 201500,
"author": "James Osborn",
"author_id": 6686,
"author_profile": "https://Stackoverflow.com/users/6686",
"pm_score": 0,
"selected": false,
"text": "<p>I think the error</p>\n\n<blockquote>\n <p>The settings property\n 'key' was not found.</p>\n</blockquote>\n\n<p>occurs because the 'key' value does not exist in your settings file (fairly self-explanatory).</p>\n\n<p>As far as I am aware, you can't add settings values programmatically, you might need to investigate adding all of the settings you need to the file after all, although once they are there, I think you'll be able to use the sort of code you've given to save changes.</p>\n\n<p>To Save changes, you'll need to make sure they are 'User' settings, not 'Application'.</p>\n\n<p>The Settings file is quite simple XML, so you might be able to attack the problem by writing the XML directly to the file, but I've never done it, so can't be sure it would work, or necessarily recommend that approach.</p>\n\n<p><a href=\"http://msdn.microsoft.com/en-us/library/cftf714c.aspx\" rel=\"nofollow noreferrer\">http://msdn.microsoft.com/en-us/library/cftf714c.aspx</a> is the MSDN link to start with.</p>\n"
},
{
"answer_id": 201935,
"author": "dbkk",
"author_id": 838,
"author_profile": "https://Stackoverflow.com/users/838",
"pm_score": 0,
"selected": false,
"text": "<p>You can do Settings.Save() or similar on user settings, but note that such settings would NOT get persisted to the xxx.exe.config file in your app directory as you'd expect. They actually go somewhere deep inside the user folder (search your drive for xxx.exe.config to find it). Next time that you manually change xxx.exe.config in your app directory, the change will mysteriously not apply (the system is still using the saved one from the user directory).</p>\n"
},
{
"answer_id": 211722,
"author": "orj",
"author_id": 20480,
"author_profile": "https://Stackoverflow.com/users/20480",
"pm_score": 2,
"selected": true,
"text": "<p>Store your column width settings in an Xml Serializable object. Ie, something that implements <a href=\"http://msdn.microsoft.com/en-us/library/system.xml.serialization.ixmlserializable.aspx\" rel=\"nofollow noreferrer\">IXmlSerializable</a> then create a single setting entry of that type in Settings.settings.</p>\n\n<p>A good option would probably be an Xml Serializable Dictionary. A quick <a href=\"http://www.google.com.au/search?&q=xml+serializable+dictionary\" rel=\"nofollow noreferrer\">google search</a> found quite a few different blog posts that describe how to implement that.</p>\n\n<p>As mentioned in other answers you'll need to ensure that this object is a User setting. You may also need to initialize the setting instance. Ie, create a XmlSerializableDictionary() instance and assign it to the setting if the setting is null. The settings subsystem doesn't create default instances of complex setting objects.</p>\n\n<p>Also, if you want these settings to persist between assembly versions (ie, be upgradable) you will need to upgrade the settings on application startup. This is described in detail on <a href=\"http://cs.rthand.com/blogs/blog_with_righthand/archive/2005/12/09/246.aspx\" rel=\"nofollow noreferrer\">Miha Markič's</a> blog and <a href=\"http://blogs.msdn.com/rprabhu/articles/433979.aspx\" rel=\"nofollow noreferrer\">Raghavendra Prabhu's</a> blog.</p>\n"
}
] |
2008/10/14
|
[
"https://Stackoverflow.com/questions/201233",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/27847/"
] |
I have a "settings file" in my Winforms application called Settings.settings with a partial class for custom methods, etc. Is there a way to load / save dynamic settings based on arbitrary keys?
For example, I have some ListViews in my application in which I want to save / load the column widths; Instead of creating a width setting for each column for each list view I would like a simple method to load / save the widths automatically.
Below is an example of the **save** method I have tried:
```
internal sealed partial class Settings
{
public void SetListViewColumnWidths(ListView listView)
{
String baseKey = listView.Name;
foreach (ColumnHeader h in listView.Columns)
{
String key = String.Format("{0}-{1}", baseKey, h.Index);
this[key] = h.Width;
}
}
}
```
When running that code I get the error **"The settings property 'TestsListView-0' was not found."** Is there something I am missing?
|
Store your column width settings in an Xml Serializable object. Ie, something that implements [IXmlSerializable](http://msdn.microsoft.com/en-us/library/system.xml.serialization.ixmlserializable.aspx) then create a single setting entry of that type in Settings.settings.
A good option would probably be an Xml Serializable Dictionary. A quick [google search](http://www.google.com.au/search?&q=xml+serializable+dictionary) found quite a few different blog posts that describe how to implement that.
As mentioned in other answers you'll need to ensure that this object is a User setting. You may also need to initialize the setting instance. Ie, create a XmlSerializableDictionary() instance and assign it to the setting if the setting is null. The settings subsystem doesn't create default instances of complex setting objects.
Also, if you want these settings to persist between assembly versions (ie, be upgradable) you will need to upgrade the settings on application startup. This is described in detail on [Miha Markič's](http://cs.rthand.com/blogs/blog_with_righthand/archive/2005/12/09/246.aspx) blog and [Raghavendra Prabhu's](http://blogs.msdn.com/rprabhu/articles/433979.aspx) blog.
|
201,235 |
<p>I need to import all ad groups in a few OUs into a table in SQL Server 2008. Once I have those I need to import all the members of those groups to a different table. I can use c# to do the work and pass the data to SQL server or do it directly in SQL server.</p>
<p>Suggestions on the best way to approach this?</p>
|
[
{
"answer_id": 201253,
"author": "Matthias Meid",
"author_id": 17713,
"author_profile": "https://Stackoverflow.com/users/17713",
"pm_score": 3,
"selected": false,
"text": "<p>Add a Linked Server to your SQL Server and query the Active Directory via LDAP queries. This here described this quite well:</p>\n\n<p><a href=\"http://codebetter.com/blogs/brendan.tompkins/archive/2003/12/19/4746.aspx\" rel=\"noreferrer\">Create a SQL Server View of your AD Users, Brendan Tompkins (MVP)</a> </p>\n"
},
{
"answer_id": 207923,
"author": "Matthias Meid",
"author_id": 17713,
"author_profile": "https://Stackoverflow.com/users/17713",
"pm_score": 3,
"selected": true,
"text": "<p>Arry,</p>\n\n<p>I don't know exactly, but found some links that may help you. I think the hottest track is this expression:</p>\n\n<pre><code>\"(&(objectCategory=Person)(memberOf=DN=GroupName, OU=Org, DC=domain,\nDC=com))\"\n</code></pre>\n\n<p>I found it in <a href=\"http://www.houseoffusion.com/groups/cf-talk/thread.cfm/threadid:55298\" rel=\"nofollow noreferrer\">LDAP Query for group members</a> on a ColdFusion community's site. I'm more or less sure the filter can easily be applied to your query. I'm sorry, but I cannot test it, because I have no AD around here.</p>\n\n<p>This one could also be a bit (but less) interesting:</p>\n\n<p><a href=\"http://forge.novell.com/pipermail/cldap-dev/2004-April/000042.html\" rel=\"nofollow noreferrer\">http://forge.novell.com/pipermail/cldap-dev/2004-April/000042.html</a></p>\n\n<p>Hope this helps, cheers,</p>\n\n<p>Matthias</p>\n"
},
{
"answer_id": 7073026,
"author": "billinkc",
"author_id": 181965,
"author_profile": "https://Stackoverflow.com/users/181965",
"pm_score": 2,
"selected": false,
"text": "<p>As the OP of this question seemed open to other technologies (3 years ago), I posted a walk through that uses SSIS as the technology for querying AD for users, writing those users to a table and doing group lookups on those users. <a href=\"http://billfellows.blogspot.com/2011/04/active-directory-ssis-data-source.html\" rel=\"nofollow\">Active Directory SSIS Data Source</a> Even if you aren't interested in SSIS, the LDAP query for source objects and the C# for group membership might be handy for anyone reviewing this question.</p>\n"
}
] |
2008/10/14
|
[
"https://Stackoverflow.com/questions/201235",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/26792/"
] |
I need to import all ad groups in a few OUs into a table in SQL Server 2008. Once I have those I need to import all the members of those groups to a different table. I can use c# to do the work and pass the data to SQL server or do it directly in SQL server.
Suggestions on the best way to approach this?
|
Arry,
I don't know exactly, but found some links that may help you. I think the hottest track is this expression:
```
"(&(objectCategory=Person)(memberOf=DN=GroupName, OU=Org, DC=domain,
DC=com))"
```
I found it in [LDAP Query for group members](http://www.houseoffusion.com/groups/cf-talk/thread.cfm/threadid:55298) on a ColdFusion community's site. I'm more or less sure the filter can easily be applied to your query. I'm sorry, but I cannot test it, because I have no AD around here.
This one could also be a bit (but less) interesting:
<http://forge.novell.com/pipermail/cldap-dev/2004-April/000042.html>
Hope this helps, cheers,
Matthias
|
201,255 |
<p>Using C#, does anyone know how to get the MarshalAsAttribute's Sizeconst value in runtime ?</p>
<p>Eg. I would like to retrieve the value of 10.</p>
<pre><code>[StructLayout[LayoutKind.Sequential, Pack=1]
Class StructureToMarshalFrom
{
[MarshalAs(UnmanagedType.ByValArray, SizeConst = 10)]
public byte[] _value1;
}
</code></pre>
|
[
{
"answer_id": 201266,
"author": "Jon Skeet",
"author_id": 22656,
"author_profile": "https://Stackoverflow.com/users/22656",
"pm_score": 3,
"selected": true,
"text": "<p>Yup, with reflection:</p>\n\n<pre><code>FieldInfo field = typeof(StructureToMarshalFrom).GetField(\"_value1\");\nobject[] attributes = field.GetCustomAttributes(typeof(MarshalAsAttribute), false);\nMarshalAsAttribute marshal = (MarshalAsAttribute) attributes[0];\nint sizeConst = marshal.SizeConst;\n</code></pre>\n\n<p>(Untested, and obviously lacking rather a lot of error checking, but should work.)</p>\n"
},
{
"answer_id": 201291,
"author": "Dave Markle",
"author_id": 24995,
"author_profile": "https://Stackoverflow.com/users/24995",
"pm_score": 1,
"selected": false,
"text": "<pre><code>var x = new StructureToMarshalFrom();\nvar fields = x.GetType().GetFields();\n\nvar att = (MarshalAsAttribute[])fields[0].GetCustomAttributes(typeof(MarshalAsAttribute), false);\nif (att.Length > 0) {\n Console.WriteLine(att[0].SizeConst);\n}\n</code></pre>\n"
}
] |
2008/10/14
|
[
"https://Stackoverflow.com/questions/201255",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/279238/"
] |
Using C#, does anyone know how to get the MarshalAsAttribute's Sizeconst value in runtime ?
Eg. I would like to retrieve the value of 10.
```
[StructLayout[LayoutKind.Sequential, Pack=1]
Class StructureToMarshalFrom
{
[MarshalAs(UnmanagedType.ByValArray, SizeConst = 10)]
public byte[] _value1;
}
```
|
Yup, with reflection:
```
FieldInfo field = typeof(StructureToMarshalFrom).GetField("_value1");
object[] attributes = field.GetCustomAttributes(typeof(MarshalAsAttribute), false);
MarshalAsAttribute marshal = (MarshalAsAttribute) attributes[0];
int sizeConst = marshal.SizeConst;
```
(Untested, and obviously lacking rather a lot of error checking, but should work.)
|
201,282 |
<p>Microsoft SQL Server and MySQL have an INFORMATION_SCHEMA table that I can query. However it does not exist in an MS Access database.</p>
<p>Is there an equivalent I can use?</p>
|
[
{
"answer_id": 201297,
"author": "Ilya Kochetov",
"author_id": 15329,
"author_profile": "https://Stackoverflow.com/users/15329",
"pm_score": 1,
"selected": false,
"text": "<p>Getting a list of tables:</p>\n\n<pre><code>SELECT \n Table_Name = Name, \nFROM \n MSysObjects \nWHERE \n (Left([Name],1)<>\"~\") \n AND (Left([Name],4) <> \"MSys\") \n AND ([Type] In (1, 4, 6)) \nORDER BY \n Name\n</code></pre>\n"
},
{
"answer_id": 201455,
"author": "onedaywhen",
"author_id": 15354,
"author_profile": "https://Stackoverflow.com/users/15354",
"pm_score": 2,
"selected": false,
"text": "<p>Schema information which is designed to be very close to that of the SQL-92 INFORMATION_SCHEMA may be obtained for the Jet/ACE engine (which is what I assume you mean by 'access') via the OLE DB providers. </p>\n\n<p>See:</p>\n\n<p><a href=\"http://msdn.microsoft.com/en-us/library/aa704826.aspx\" rel=\"nofollow noreferrer\">OpenSchema Method (ADO) </a></p>\n\n<p><a href=\"http://msdn.microsoft.com/en-us/library/ms723054(VS.85).aspx\" rel=\"nofollow noreferrer\">Supported Schema Rowsets</a></p>\n"
},
{
"answer_id": 202307,
"author": "Fionnuala",
"author_id": 2548,
"author_profile": "https://Stackoverflow.com/users/2548",
"pm_score": 4,
"selected": false,
"text": "<p>You can use schemas in Access.</p>\n\n<pre><code>Sub ListAccessTables2(strDBPath)\n Dim cnnDB As ADODB.Connection\n Dim rstList As ADODB.Recordset\n\n Set cnnDB = New ADODB.Connection\n\n ' Open the connection.\n With cnnDB\n .Provider = \"Microsoft.Jet.OLEDB.4.0\"\n .Open strDBPath\n End With\n\n ' Open the tables schema rowset.\n Set rstList = cnnDB.OpenSchema(adSchemaTables)\n\n ' Loop through the results and print the\n ' names and types in the Immediate pane.\n With rstList\n Do While Not .EOF\n If .Fields(\"TABLE_TYPE\") <> \"VIEW\" Then\n Debug.Print .Fields(\"TABLE_NAME\") & vbTab & _\n .Fields(\"TABLE_TYPE\")\n End If\n .MoveNext\n Loop\n End With\n cnnDB.Close\n Set cnnDB = Nothing\nEnd Sub\n</code></pre>\n\n<p>From: <a href=\"http://msdn.microsoft.com/en-us/library/aa165325(office.10).aspx\" rel=\"noreferrer\">http://msdn.microsoft.com/en-us/library/aa165325(office.10).aspx</a></p>\n"
},
{
"answer_id": 202534,
"author": "BIBD",
"author_id": 685,
"author_profile": "https://Stackoverflow.com/users/685",
"pm_score": 7,
"selected": true,
"text": "<p>To build on Ilya's answer try the following query:</p>\n\n<pre><code>SELECT MSysObjects.Name AS table_name\nFROM MSysObjects\nWHERE (((Left([Name],1))<>\"~\") \n AND ((Left([Name],4))<>\"MSys\") \n AND ((MSysObjects.Type) In (1,4,6)))\norder by MSysObjects.Name \n</code></pre>\n\n<p>(this one works without modification with an MDB)</p>\n\n<p>ACCDB users may need to do something like this</p>\n\n<pre><code>SELECT MSysObjects.Name AS table_name\nFROM MSysObjects\nWHERE (((Left([Name],1))<>\"~\") \n AND ((Left([Name],4))<>\"MSys\") \n AND ((MSysObjects.Type) In (1,4,6))\n AND ((MSysObjects.Flags)=0))\norder by MSysObjects.Name \n</code></pre>\n\n<p>As there is an extra table is included that appears to be a system table of some sort.</p>\n"
},
{
"answer_id": 7725797,
"author": "Syed Daud",
"author_id": 989456,
"author_profile": "https://Stackoverflow.com/users/989456",
"pm_score": 0,
"selected": false,
"text": "<pre><code>SELECT \nName \nFROM \nMSysObjects \nWHERE \n(Left([Name],1)<>\"~\") \nAND (Left([Name],4) <> \"MSys\") \nAND ([Type] In (1, 4, 6)) \nORDER BY \nName\n</code></pre>\n"
},
{
"answer_id": 10132295,
"author": "Pete",
"author_id": 349043,
"author_profile": "https://Stackoverflow.com/users/349043",
"pm_score": 3,
"selected": false,
"text": "<p>Here is an updated answer which works in Access 2010 VBA using Data Access Objects (DAO). The table's name is held in TableDef.Name. The collection of all table definitions is held in TableDefs. Here is a quick example of looping through the table names:</p>\n\n<pre><code>Dim db as Database\nDim td as TableDef\nSet db = CurrentDb()\nFor Each td In db.TableDefs\n YourSubTakingTableName(td.Name)\nNext td\n</code></pre>\n"
},
{
"answer_id": 43460090,
"author": "Jim",
"author_id": 7868125,
"author_profile": "https://Stackoverflow.com/users/7868125",
"pm_score": 0,
"selected": false,
"text": "<p>Best not to mess with msysObjects (IMHO).</p>\n\n<pre><code>CurrentDB.TableDefs\nCurrentDB.QueryDefs\nCurrentProject.AllForms\nCurrentProject.AllReports\nCurrentProject.AllMacros\n</code></pre>\n"
},
{
"answer_id": 68581054,
"author": "John",
"author_id": 2670571,
"author_profile": "https://Stackoverflow.com/users/2670571",
"pm_score": 0,
"selected": false,
"text": "<p>I needed to slightly modify the SQL posted by BIBD (needed to fully quality the table name by adding sys. to MSysObjects in the from clause.</p>\n<pre><code> String sqlString = "";\n sqlString += "SELECT MSysObjects.Name AS table_name \\n";\n sqlString += "FROM sys.MSysObjects \\n";\n sqlString += "WHERE (((Left([Name],1))<>\\"~\\") \\n";\n sqlString += " AND ((Left([Name],4))<>\\"MSys\\") \\n";\n sqlString += " AND ((MSysObjects.Type) In (1,4,6)) \\n";\n sqlString += " AND ((MSysObjects.Flags)=0)) \\n";\n sqlString += "order by MSysObjects.Name \\n";\n</code></pre>\n<p>A full working example is available at <a href=\"https://github.com/NACHC-CAD/access-to-csv-tool\" rel=\"nofollow noreferrer\">https://github.com/NACHC-CAD/access-to-csv-tool</a>. This example also shows connecting to an MS Access database using jdbc and exporting all tables as csv using Apache Commons CSV.</p>\n"
}
] |
2008/10/14
|
[
"https://Stackoverflow.com/questions/201282",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5978/"
] |
Microsoft SQL Server and MySQL have an INFORMATION\_SCHEMA table that I can query. However it does not exist in an MS Access database.
Is there an equivalent I can use?
|
To build on Ilya's answer try the following query:
```
SELECT MSysObjects.Name AS table_name
FROM MSysObjects
WHERE (((Left([Name],1))<>"~")
AND ((Left([Name],4))<>"MSys")
AND ((MSysObjects.Type) In (1,4,6)))
order by MSysObjects.Name
```
(this one works without modification with an MDB)
ACCDB users may need to do something like this
```
SELECT MSysObjects.Name AS table_name
FROM MSysObjects
WHERE (((Left([Name],1))<>"~")
AND ((Left([Name],4))<>"MSys")
AND ((MSysObjects.Type) In (1,4,6))
AND ((MSysObjects.Flags)=0))
order by MSysObjects.Name
```
As there is an extra table is included that appears to be a system table of some sort.
|
201,314 |
<p>In my javascript experience, I found that is a very common task "searching the nearest ancestor of an element with some condition (tag name, class,...)".
Can the parents() method of jquery do the job? The order of returned elements of parents() is predictable? Is top-to-bottom or bottom-to-top?
For the moment I use this utility function:</p>
<pre><code>function ancestor(elem, selector) {
var $elem = $( elem ).parent();
while( $elem.size() > 0 ) {
if( $elem.is( selector ) )
return $elem;
else
$elem = $elem.parent();
}
return null;
}
</code></pre>
<p>Can someone tell me if there is a clever way to do the job?</p>
|
[
{
"answer_id": 201330,
"author": "nickf",
"author_id": 9021,
"author_profile": "https://Stackoverflow.com/users/9021",
"pm_score": 5,
"selected": true,
"text": "<p><strong>Edit</strong>: Since jQuery 1.3, this has been built in as the <a href=\"http://api.jquery.com/closest\" rel=\"noreferrer\"><code>closest()</code></a> function. eg: <code>$('#foo').closest('.bar');</code></p>\n\n<hr>\n\n<p>yep - parents() traverses up the tree.</p>\n\n<pre><code><div id=\"a\">\n <div id=\"b\">\n <p id=\"c\">\n <a id=\"d\"></a>\n </p>\n </div>\n</div>\n</code></pre>\n\n<p><code>$('#d').parents(\"div:first\");</code> will select div b.</p>\n"
},
{
"answer_id": 944765,
"author": "Borgar",
"author_id": 27388,
"author_profile": "https://Stackoverflow.com/users/27388",
"pm_score": 4,
"selected": false,
"text": "<p><em>Adding to @<a href=\"https://stackoverflow.com/users/9021/nickf\">nickf</a>'s answer:</em></p>\n\n<p>jQuery 1.3 simplifyed this task with <code>closest</code>.</p>\n\n<p>Given a DOM:</p>\n\n<pre><code><div id=\"a\">\n <div id=\"b\">\n <p id=\"c\">\n <a id=\"d\"></a>\n </p>\n </div>\n</div>\n</code></pre>\n\n<p>You can do:</p>\n\n<pre><code>$('#d').closest(\"div\"); // returns [ div#b ]\n</code></pre>\n\n<blockquote>\n <p>[<a href=\"http://docs.jquery.com/Traversing/closest\" rel=\"nofollow noreferrer\">Closest</a> returns a] set of\n elements containing the closest parent\n element that matches the specified\n selector, the starting element\n included.</p>\n</blockquote>\n"
},
{
"answer_id": 1235262,
"author": "LaC",
"author_id": 151238,
"author_profile": "https://Stackoverflow.com/users/151238",
"pm_score": 2,
"selected": false,
"text": "<p>You should use <code>closest</code>, because <code>parents</code> won't give you the result you expect if you're working with multiple elements. For instance, let's say you have this:</p>\n\n<pre><code> <div id=\"0\">\n <div id=\"1\">test with <b>nested</b> divs.</div>\n <div id=\"2\">another div.</div>\n <div id=\"3\">yet <b>another</b> div.</div>\n </div>\n</code></pre>\n\n<p>and you want to add a class to the divs that have a <code><b></code> element as their immediate child (ie, 1 and 3). If you use <code>$('b').parents('div')</code>, you get divs 0, 1 and 3. If you use <code>$('b').parents('div:first')</code>, you only get div 1. To get 1 and 3, but not 0, you have to use <code>$('b').closest(elem)</code>.</p>\n"
},
{
"answer_id": 3310223,
"author": "Ron",
"author_id": 342293,
"author_profile": "https://Stackoverflow.com/users/342293",
"pm_score": 2,
"selected": false,
"text": "<p>closest() starts at current element, if the parent you are looking for has the same tag as current (eg. both are divs), use parent().closest()</p>\n"
}
] |
2008/10/14
|
[
"https://Stackoverflow.com/questions/201314",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/27789/"
] |
In my javascript experience, I found that is a very common task "searching the nearest ancestor of an element with some condition (tag name, class,...)".
Can the parents() method of jquery do the job? The order of returned elements of parents() is predictable? Is top-to-bottom or bottom-to-top?
For the moment I use this utility function:
```
function ancestor(elem, selector) {
var $elem = $( elem ).parent();
while( $elem.size() > 0 ) {
if( $elem.is( selector ) )
return $elem;
else
$elem = $elem.parent();
}
return null;
}
```
Can someone tell me if there is a clever way to do the job?
|
**Edit**: Since jQuery 1.3, this has been built in as the [`closest()`](http://api.jquery.com/closest) function. eg: `$('#foo').closest('.bar');`
---
yep - parents() traverses up the tree.
```
<div id="a">
<div id="b">
<p id="c">
<a id="d"></a>
</p>
</div>
</div>
```
`$('#d').parents("div:first");` will select div b.
|
201,323 |
<p>Over the years I have slowly developed a <a href="http://en.wikipedia.org/wiki/Regular_expression" rel="noreferrer">regular expression</a> that validates <em>most</em> email addresses correctly, assuming they don't use an IP address as the server part.</p>
<p>I use it in several PHP programs, and it works most of the time. However, from time to time I get contacted by someone that is having trouble with a site that uses it, and I end up having to make some adjustment (most recently I realized that I wasn't allowing four-character <a href="https://en.wikipedia.org/wiki/Top-level_domain" rel="noreferrer">TLDs</a>).</p>
<p><em>What is the best regular expression you have or have seen for validating emails?</em></p>
<p>I've seen several solutions that use functions that use several shorter expressions, but I'd rather have one long complex expression in a simple function instead of several short expression in a more complex function.</p>
|
[
{
"answer_id": 201336,
"author": "Per Hornshøj-Schierbeck",
"author_id": 11619,
"author_profile": "https://Stackoverflow.com/users/11619",
"pm_score": 8,
"selected": false,
"text": "<p>I use</p>\n\n<pre class=\"lang-none prettyprint-override\"><code>^\\w+([-+.']\\w+)*@\\w+([-.]\\w+)*\\.\\w+([-.]\\w+)*$\n</code></pre>\n\n<p>Which is the one used in ASP.NET by the RegularExpressionValidator.</p>\n"
},
{
"answer_id": 201337,
"author": "Chris Vest",
"author_id": 13251,
"author_profile": "https://Stackoverflow.com/users/13251",
"pm_score": 7,
"selected": false,
"text": "<p>I don't know about best, but <a href=\"http://ex-parrot.com/%7Epdw/Mail-RFC822-Address.html\" rel=\"nofollow noreferrer\">this one</a> is at least correct, as long as the addresses have their comments stripped and replaced with white space.</p>\n<p>Seriously. You should use an already-written library for validating emails. The best way is probably to just send a verification e-mail to that address.</p>\n"
},
{
"answer_id": 201340,
"author": "Draemon",
"author_id": 26334,
"author_profile": "https://Stackoverflow.com/users/26334",
"pm_score": 6,
"selected": false,
"text": "<p>There are plenty examples of this out on the Internet (and I think even one that fully validates the RFC - but it's tens/hundreds of lines long if memory serves).</p>\n<p>People tend to get carried away validating this sort of thing. Why not just check it has an @ and at least one <code>.</code> and meets some simple minimum length? It's trivial to enter a fake email and still match any valid regex anyway. I would guess that false positives are better than false negatives.</p>\n"
},
{
"answer_id": 201358,
"author": "Kon",
"author_id": 22303,
"author_profile": "https://Stackoverflow.com/users/22303",
"pm_score": 5,
"selected": false,
"text": "<p>I never bother creating with my own regular expression, because chances are that someone else has already come up with a better version. I always use <a href=\"http://regexlib.com/Search.aspx\" rel=\"noreferrer\">regexlib</a> to find one to my liking.</p>\n"
},
{
"answer_id": 201378,
"author": "bortzmeyer",
"author_id": 15625,
"author_profile": "https://Stackoverflow.com/users/15625",
"pm_score": 13,
"selected": true,
"text": "<p>The <a href=\"http://ex-parrot.com/%7Epdw/Mail-RFC822-Address.html\" rel=\"noreferrer\">fully RFC 822 compliant regex</a> is inefficient and obscure because of its length. Fortunately, RFC 822 was superseded twice and the current specification for email addresses is <a href=\"https://datatracker.ietf.org/doc/html/rfc5322\" rel=\"noreferrer\">RFC 5322</a>. RFC 5322 leads to a regex that can be understood if studied for a few minutes and is efficient enough for actual use.</p>\n<p>One RFC 5322 compliant regex can be found at the top of the page at <a href=\"http://emailregex.com/\" rel=\"noreferrer\">http://emailregex.com/</a> but uses the IP address pattern that is floating around the internet with a bug that allows <code>00</code> for any of the unsigned byte decimal values in a dot-delimited address, which is illegal. The rest of it appears to be consistent with the RFC 5322 grammar and passes several tests using <code>grep -Po</code>, including cases domain names, IP addresses, bad ones, and account names with and without quotes.</p>\n<p>Correcting the <code>00</code> bug in the IP pattern, we obtain a working and fairly fast regex. (Scrape the rendered version, not the markdown, for actual code.)</p>\n<blockquote>\n<p>(?:[a-z0-9!#$%&'*+/=?^_`{|}~-]+(?:\\.[a-z0-9!#$%&'*+/=?^_`{|}~-]+)*|"(?:[\\x01-\\x08\\x0b\\x0c\\x0e-\\x1f\\x21\\x23-\\x5b\\x5d-\\x7f]|\\\\[\\x01-\\x09\\x0b\\x0c\\x0e-\\x7f])*")@(?:(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\\.)+[a-z0-9](?:[a-z0-9-]*[a-z0-9])?|\\[(?:(?:(2(5[0-5]|[0-4][0-9])|1[0-9][0-9]|[1-9]?[0-9]))\\.){3}(?:(2(5[0-5]|[0-4][0-9])|1[0-9][0-9]|[1-9]?[0-9])|[a-z0-9-]*[a-z0-9]:(?:[\\x01-\\x08\\x0b\\x0c\\x0e-\\x1f\\x21-\\x5a\\x53-\\x7f]|\\\\[\\x01-\\x09\\x0b\\x0c\\x0e-\\x7f])+)\\])</p>\n</blockquote>\n<p>or:</p>\n<pre><code>(?:[a-z0-9!#$%&'*+/=?^_`{|}~-]+(?:\\.[a-z0-9!#$%&'*+/=?^_`{|}~-]+)*|"(?:[\\x01-\\x08\\x0b\\x0c\\x0e-\\x1f\\x21\\x23-\\x5b\\x5d-\\x7f]|\\\\[\\x01-\\x09\\x0b\\x0c\\x0e-\\x7f])*")@(?:(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\\.)+[a-z0-9](?:[a-z0-9-]*[a-z0-9])?|\\[(?:(?:(2(5[0-5]|[0-4][0-9])|1[0-9][0-9]|[1-9]?[0-9]))\\.){3}(?:(2(5[0-5]|[0-4][0-9])|1[0-9][0-9]|[1-9]?[0-9])|[a-z0-9-]*[a-z0-9]:(?:[\\x01-\\x08\\x0b\\x0c\\x0e-\\x1f\\x21-\\x5a\\x53-\\x7f]|\\\\[\\x01-\\x09\\x0b\\x0c\\x0e-\\x7f])+)\\])\n</code></pre>\n<p>Here is <a href=\"https://regexper.com/#(%3F%3A%5Ba-z0-9!%23%24%25%26%27*%2B%2F%3D%3F%5E_%60%7B%7C%7D%7E-%5D%2B(%3F%3A%5C.%5Ba-z0-9!%23%24%25%26%27*%2B%2F%3D%3F%5E_%60%7B%7C%7D%7E-%5D%2B)*%7C%22(%3F%3A%5B%5Cx01-%5Cx08%5Cx0b%5Cx0c%5Cx0e-%5Cx1f%5Cx21%5Cx23-%5Cx5b%5Cx5d-%5Cx7f%5D%7C%5C%5C%5B%5Cx01-%5Cx09%5Cx0b%5Cx0c%5Cx0e-%5Cx7f%5D)*%22)%40(%3F%3A(%3F%3A%5Ba-z0-9%5D(%3F%3A%5Ba-z0-9-%5D*%5Ba-z0-9%5D)%3F%5C.)%2B%5Ba-z0-9%5D(%3F%3A%5Ba-z0-9-%5D*%5Ba-z0-9%5D)%3F%7C%5C%5B(%3F%3A(%3F%3A(2(5%5B0-5%5D%7C%5B0-4%5D%5B0-9%5D)%7C1%5B0-9%5D%5B0-9%5D%7C%5B1-9%5D%3F%5B0-9%5D))%5C.)%7B3%7D(%3F%3A(2(5%5B0-5%5D%7C%5B0-4%5D%5B0-9%5D)%7C1%5B0-9%5D%5B0-9%5D%7C%5B1-9%5D%3F%5B0-9%5D)%7C%5Ba-z0-9-%5D*%5Ba-z0-9%5D%3A(%3F%3A%5B%5Cx01-%5Cx08%5Cx0b%5Cx0c%5Cx0e-%5Cx1f%5Cx21-%5Cx5a%5Cx53-%5Cx7f%5D%7C%5C%5C%5B%5Cx01-%5Cx09%5Cx0b%5Cx0c%5Cx0e-%5Cx7f%5D)%2B)%5C%5D)\" rel=\"noreferrer\">diagram</a> of <a href=\"https://en.wikipedia.org/wiki/Finite-state_machine\" rel=\"noreferrer\">finite state machine</a> for above regexp which is more clear than regexp itself\n<a href=\"https://i.stack.imgur.com/YI6KR.png\" rel=\"noreferrer\"><img src=\"https://i.stack.imgur.com/YI6KR.png\" alt=\"enter image description here\" /></a></p>\n<p>The more sophisticated patterns in Perl and PCRE (regex library used e.g. in PHP) can <a href=\"https://stackoverflow.com/questions/201323/what-is-the-best-regular-expression-for-validating-email-addresses/1917982#1917982\">correctly parse RFC 5322 without a hitch</a>. Python and C# can do that too, but they use a different syntax from those first two. However, if you are forced to use one of the many less powerful pattern-matching languages, then it’s best to use a real parser.</p>\n<p>It's also important to understand that validating it per the RFC tells you absolutely nothing about whether that address actually exists at the supplied domain, or whether the person entering the address is its true owner. People sign others up to mailing lists this way all the time. Fixing that requires a fancier kind of validation that involves sending that address a message that includes a confirmation token meant to be entered on the same web page as was the address.</p>\n<p>Confirmation tokens are the only way to know you got the address of the person entering it. This is why most mailing lists now use that mechanism to confirm sign-ups. After all, anybody can put down <code>[email protected]</code>, and that will even parse as legal, but it isn't likely to be the person at the other end.</p>\n<p>For PHP, you should <em>not</em> use the pattern given in <a href=\"http://www.linuxjournal.com/article/9585\" rel=\"noreferrer\">Validate an E-Mail Address with PHP, the Right Way</a> from which I quote:</p>\n<blockquote>\n<p>There is some danger that common usage and widespread sloppy coding will establish a de facto standard for e-mail addresses that is more restrictive than the recorded formal standard.</p>\n</blockquote>\n<p>That is no better than all the other non-RFC patterns. It isn’t even smart enough to handle even <a href=\"https://datatracker.ietf.org/doc/html/rfc822\" rel=\"noreferrer\">RFC 822</a>, let alone RFC 5322. <a href=\"https://stackoverflow.com/questions/201323/what-is-the-best-regular-expression-for-validating-email-addresses/1917982#1917982\">This one</a>, however, is.</p>\n<p>If you want to get fancy and pedantic, <a href=\"http://cubicspot.blogspot.com/2012/06/correct-way-to-validate-e-mail-address.html\" rel=\"noreferrer\">implement a complete state engine</a>. A regular expression can only act as a rudimentary filter. The problem with regular expressions is that telling someone that their perfectly valid e-mail address is invalid (a false positive) because your regular expression can't handle it is just rude and impolite from the user's perspective. A state engine for the purpose can both validate and even correct e-mail addresses that would otherwise be considered invalid as it disassembles the e-mail address according to each RFC. This allows for a potentially more pleasing experience, like</p>\n<blockquote>\n<p>The specified e-mail address 'myemail@address,com' is invalid. Did you mean '[email protected]'?</p>\n</blockquote>\n<p>See also <a href=\"http://worsethanfailure.com/Articles/Validating_Email_Addresses.aspx\" rel=\"noreferrer\">Validating Email Addresses</a>, including the comments. Or <a href=\"http://fightingforalostcause.net/misc/2006/compare-email-regex.php\" rel=\"noreferrer\">Comparing E-mail Address Validating Regular Expressions</a>.</p>\n<p><a href=\"https://i.stack.imgur.com/SrUwP.png\" rel=\"noreferrer\"><img src=\"https://i.stack.imgur.com/SrUwP.png\" alt=\"Regular expression visualization\" /></a></p>\n<p><a href=\"https://www.debuggex.com/r/aH_x42NflV8G-GS7\" rel=\"noreferrer\">Debuggex Demo</a></p>\n"
},
{
"answer_id": 201447,
"author": "Andy Lester",
"author_id": 8454,
"author_profile": "https://Stackoverflow.com/users/8454",
"pm_score": 9,
"selected": false,
"text": "<p>It all depends on how accurate you want to be. For my purposes, where I'm just trying to keep out things like <code>bob @ aol.com</code> (spaces in emails) or <code>steve</code> (no domain at all) or <code>mary@aolcom</code> (no period before .com), I use</p>\n\n<pre><code>/^\\S+@\\S+\\.\\S+$/\n</code></pre>\n\n<p>Sure, it will match things that aren't valid email addresses, but it's a matter of getting common simple errors.</p>\n\n<p>There are any number of changes that can be made to that regex (and some are in the comments for this answer), but it's simple, and easy to understand, and is a fine first attempt.</p>\n"
},
{
"answer_id": 201688,
"author": "PhiLho",
"author_id": 15459,
"author_profile": "https://Stackoverflow.com/users/15459",
"pm_score": 5,
"selected": false,
"text": "<p>There is not one which is really usable. I discuss some issues in my <a href=\"https://stackoverflow.com/questions/161342/is-there-a-php-library-for-email-address-validation#161582\" title=\"Is there a PHP library for email address validation?\">answer to <em>Is there a PHP library for email address validation?</em></a>, it is discussed also in <em><a href=\"https://stackoverflow.com/questions/156430/regexp-recognition-of-email-address-hard\" title=\"Is regular expression recognition of an email address hard?\">Is regular expression recognition of an email address hard?</a></em>.</p>\n<p>In short, don't expect a single, usable regex to do a proper job. And the best regex will validate the syntax, not the validity of an e-mail (<em>[email protected]</em> is correct, but it will probably bounce...).</p>\n"
},
{
"answer_id": 201905,
"author": "adnam",
"author_id": 27886,
"author_profile": "https://Stackoverflow.com/users/27886",
"pm_score": 5,
"selected": false,
"text": "<p><a href=\"http://www.iamcal.com/\" rel=\"nofollow noreferrer\">Cal Henderson</a> (Flickr) wrote an article called <em><a href=\"http://www.iamcal.com/publish/articles/php/parsing_email/\" rel=\"nofollow noreferrer\">Parsing Email Addresses in PHP</a></em> and shows how to do proper RFC (2)822-compliant email address parsing.</p>\n<p>You can also get the source code in <a href=\"http://code.iamcal.com/php/rfc822/\" rel=\"nofollow noreferrer\">PHP</a>, Python, and Ruby which is <a href=\"http://creativecommons.org/licenses/by-sa/2.5/\" rel=\"nofollow noreferrer\">Creative Commons licensed</a>.</p>\n"
},
{
"answer_id": 202528,
"author": "JacquesB",
"author_id": 7488,
"author_profile": "https://Stackoverflow.com/users/7488",
"pm_score": 9,
"selected": false,
"text": "<p>This question is asked a lot, but I think you should step back and ask yourself <em>why</em> you want to validate email adresses syntactically? What is the benefit really?</p>\n<ul>\n<li>It will not catch common typos.</li>\n<li>It does not prevent people from entering invalid or made-up email addresses, or entering someone else's address for that matter.</li>\n</ul>\n<p>If you want to validate that an email is correct, you have no choice than to send a confirmation email and have the user reply to that. In many cases you will <em>have</em> to send a confirmation mail anyway for security reasons or for ethical reasons (so you cannot e.g. sign someone up to a service against their will).</p>\n"
},
{
"answer_id": 267670,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 3,
"selected": false,
"text": "<p>Strange that you "cannot" allow 4 characters TLDs. You are banning people from <em>.info</em> and <em>.name</em>, and the length limitation stop <em>.travel</em> and <em>.museum</em>, but yes, they are less common than 2 characters TLDs and 3 characters TLDs.</p>\n<p>You should allow uppercase alphabets too. Email systems will normalize the local part and domain part.</p>\n<p>For your regex of domain part, domain name cannot starts with '-' and cannot ends with '-'. Dash can only stays in between.</p>\n<p>If you used the <a href=\"https://en.wikipedia.org/wiki/PEAR\" rel=\"nofollow noreferrer\">PEAR</a> library, check out their mail function (I forgot the exact name/library). You can validate email address by calling one function, and it validates the email address according to definition in <a href=\"https://en.wikipedia.org/wiki/Email\" rel=\"nofollow noreferrer\">RFC 822</a>.</p>\n"
},
{
"answer_id": 267679,
"author": "cbp",
"author_id": 21966,
"author_profile": "https://Stackoverflow.com/users/21966",
"pm_score": 2,
"selected": false,
"text": "<p>We have used <a href=\"http://www.aspnetmx.com/\" rel=\"nofollow noreferrer\">http://www.aspnetmx.com/</a> with a degree of success for a few years now. You can choose the level you want to validate at (e.g. syntax check, check for the domain, <a href=\"https://en.wikipedia.org/wiki/MX_record\" rel=\"nofollow noreferrer\">MX records</a> or the actual email).</p>\n<p>For front-end forms we generally verify that the domain exists and the syntax is correct, and then we do stricter verification to clean out our database before doing bulk mail-outs.</p>\n"
},
{
"answer_id": 407102,
"author": "davcar",
"author_id": 5033,
"author_profile": "https://Stackoverflow.com/users/5033",
"pm_score": 7,
"selected": false,
"text": "<p>The email addresses I want to validate are going to be used by an ASP.NET web application using the <code>System.Net.Mail</code> namespace to send emails to a list of people.</p>\n\n<p>So, rather than using some very complex regular expression, I just try to create a <code>MailAddress</code> instance from the address. The <code>MailAddress</code> constructor will throw an exception if the address is not formed properly. This way, I know I can at least get the email out of the door. Of course this is server-side validation, but at a minimum you need that anyway.</p>\n\n<pre class=\"lang-cs prettyprint-override\"><code>protected void emailValidator_ServerValidate(object source, ServerValidateEventArgs args)\n{\n try\n {\n var a = new MailAddress(txtEmail.Text);\n }\n catch (Exception ex)\n {\n args.IsValid = false;\n emailValidator.ErrorMessage = \"email: \" + ex.Message;\n }\n}\n</code></pre>\n"
},
{
"answer_id": 532972,
"author": "Dominic Sayers",
"author_id": 63349,
"author_profile": "https://Stackoverflow.com/users/63349",
"pm_score": 8,
"selected": false,
"text": "<p>[UPDATED] I've collated everything I know about email address validation at <a href=\"http://isemail.info\" rel=\"nofollow noreferrer\">http://isemail.info</a>, which now not only validates, but it also diagnoses problems with email addresses. I agree with many of the comments here that validation is only part of the answer; see my essay <em><a href=\"http://isemail.info/about\" rel=\"nofollow noreferrer\">What is a valid email address?</a></em>.</p>\n<p>is_email() remains, as far as I know, the only validator that will tell you definitively whether a given string is a valid email address or not. I've uploaded a new version at <a href=\"http://isemail.info/\" rel=\"nofollow noreferrer\">http://isemail.info/</a></p>\n<p>I collated test cases from Cal Henderson, Dave Child, Phil Haack, Doug Lovell, <a href=\"https://en.wikipedia.org/wiki/Email#Message_format\" rel=\"nofollow noreferrer\">RFC 5322</a> and <a href=\"https://en.wikipedia.org/wiki/Email_address#Syntax\" rel=\"nofollow noreferrer\">RFC 3696</a>. 275 test addresses in all. I ran all these tests against all the free validators I could find.</p>\n<p>I'll try to keep this page up-to-date as people enhance their validators. Thanks to Cal, Michael, Dave, Paul and Phil for their help and cooperation in compiling these tests and constructive criticism of <a href=\"http://code.google.com/p/isemail\" rel=\"nofollow noreferrer\">my own validator</a>.</p>\n<p>People should be aware of the <a href=\"http://www.rfc-editor.org/errata_search.php?rfc=3696\" rel=\"nofollow noreferrer\">errata against RFC 3696</a> in particular. Three of the canonical examples are in fact invalid addresses. And the maximum length of an address is 254 or 256 characters, <strong>not</strong> 320.</p>\n"
},
{
"answer_id": 719543,
"author": "Good Person",
"author_id": 87280,
"author_profile": "https://Stackoverflow.com/users/87280",
"pm_score": 9,
"selected": false,
"text": "<p>It depends on what you mean by best:\nIf you're talking about catching every valid email address use the following:</p>\n\n<pre class=\"lang-none prettyprint-override\"><code>(?:(?:\\r\\n)?[ \\t])*(?:(?:(?:[^()<>@,;:\\\\\".\\[\\] \\000-\\031]+(?:(?:(?:\\r\\n)?[ \\t]\n)+|\\Z|(?=[\\[\"()<>@,;:\\\\\".\\[\\]]))|\"(?:[^\\\"\\r\\\\]|\\\\.|(?:(?:\\r\\n)?[ \\t]))*\"(?:(?:\n\\r\\n)?[ \\t])*)(?:\\.(?:(?:\\r\\n)?[ \\t])*(?:[^()<>@,;:\\\\\".\\[\\] \\000-\\031]+(?:(?:(\n?:\\r\\n)?[ \\t])+|\\Z|(?=[\\[\"()<>@,;:\\\\\".\\[\\]]))|\"(?:[^\\\"\\r\\\\]|\\\\.|(?:(?:\\r\\n)?[ \n\\t]))*\"(?:(?:\\r\\n)?[ \\t])*))*@(?:(?:\\r\\n)?[ \\t])*(?:[^()<>@,;:\\\\\".\\[\\] \\000-\\0\n31]+(?:(?:(?:\\r\\n)?[ \\t])+|\\Z|(?=[\\[\"()<>@,;:\\\\\".\\[\\]]))|\\[([^\\[\\]\\r\\\\]|\\\\.)*\\\n](?:(?:\\r\\n)?[ \\t])*)(?:\\.(?:(?:\\r\\n)?[ \\t])*(?:[^()<>@,;:\\\\\".\\[\\] \\000-\\031]+\n(?:(?:(?:\\r\\n)?[ \\t])+|\\Z|(?=[\\[\"()<>@,;:\\\\\".\\[\\]]))|\\[([^\\[\\]\\r\\\\]|\\\\.)*\\](?:\n(?:\\r\\n)?[ \\t])*))*|(?:[^()<>@,;:\\\\\".\\[\\] \\000-\\031]+(?:(?:(?:\\r\\n)?[ \\t])+|\\Z\n|(?=[\\[\"()<>@,;:\\\\\".\\[\\]]))|\"(?:[^\\\"\\r\\\\]|\\\\.|(?:(?:\\r\\n)?[ \\t]))*\"(?:(?:\\r\\n)\n?[ \\t])*)*\\<(?:(?:\\r\\n)?[ \\t])*(?:@(?:[^()<>@,;:\\\\\".\\[\\] \\000-\\031]+(?:(?:(?:\\\nr\\n)?[ \\t])+|\\Z|(?=[\\[\"()<>@,;:\\\\\".\\[\\]]))|\\[([^\\[\\]\\r\\\\]|\\\\.)*\\](?:(?:\\r\\n)?[\n \\t])*)(?:\\.(?:(?:\\r\\n)?[ \\t])*(?:[^()<>@,;:\\\\\".\\[\\] \\000-\\031]+(?:(?:(?:\\r\\n)\n?[ \\t])+|\\Z|(?=[\\[\"()<>@,;:\\\\\".\\[\\]]))|\\[([^\\[\\]\\r\\\\]|\\\\.)*\\](?:(?:\\r\\n)?[ \\t]\n)*))*(?:,@(?:(?:\\r\\n)?[ \\t])*(?:[^()<>@,;:\\\\\".\\[\\] \\000-\\031]+(?:(?:(?:\\r\\n)?[\n \\t])+|\\Z|(?=[\\[\"()<>@,;:\\\\\".\\[\\]]))|\\[([^\\[\\]\\r\\\\]|\\\\.)*\\](?:(?:\\r\\n)?[ \\t])*\n)(?:\\.(?:(?:\\r\\n)?[ \\t])*(?:[^()<>@,;:\\\\\".\\[\\] \\000-\\031]+(?:(?:(?:\\r\\n)?[ \\t]\n)+|\\Z|(?=[\\[\"()<>@,;:\\\\\".\\[\\]]))|\\[([^\\[\\]\\r\\\\]|\\\\.)*\\](?:(?:\\r\\n)?[ \\t])*))*)\n*:(?:(?:\\r\\n)?[ \\t])*)?(?:[^()<>@,;:\\\\\".\\[\\] \\000-\\031]+(?:(?:(?:\\r\\n)?[ \\t])+\n|\\Z|(?=[\\[\"()<>@,;:\\\\\".\\[\\]]))|\"(?:[^\\\"\\r\\\\]|\\\\.|(?:(?:\\r\\n)?[ \\t]))*\"(?:(?:\\r\n\\n)?[ \\t])*)(?:\\.(?:(?:\\r\\n)?[ \\t])*(?:[^()<>@,;:\\\\\".\\[\\] \\000-\\031]+(?:(?:(?:\n\\r\\n)?[ \\t])+|\\Z|(?=[\\[\"()<>@,;:\\\\\".\\[\\]]))|\"(?:[^\\\"\\r\\\\]|\\\\.|(?:(?:\\r\\n)?[ \\t\n]))*\"(?:(?:\\r\\n)?[ \\t])*))*@(?:(?:\\r\\n)?[ \\t])*(?:[^()<>@,;:\\\\\".\\[\\] \\000-\\031\n]+(?:(?:(?:\\r\\n)?[ \\t])+|\\Z|(?=[\\[\"()<>@,;:\\\\\".\\[\\]]))|\\[([^\\[\\]\\r\\\\]|\\\\.)*\\](\n?:(?:\\r\\n)?[ \\t])*)(?:\\.(?:(?:\\r\\n)?[ \\t])*(?:[^()<>@,;:\\\\\".\\[\\] \\000-\\031]+(?\n:(?:(?:\\r\\n)?[ \\t])+|\\Z|(?=[\\[\"()<>@,;:\\\\\".\\[\\]]))|\\[([^\\[\\]\\r\\\\]|\\\\.)*\\](?:(?\n:\\r\\n)?[ \\t])*))*\\>(?:(?:\\r\\n)?[ \\t])*)|(?:[^()<>@,;:\\\\\".\\[\\] \\000-\\031]+(?:(?\n:(?:\\r\\n)?[ \\t])+|\\Z|(?=[\\[\"()<>@,;:\\\\\".\\[\\]]))|\"(?:[^\\\"\\r\\\\]|\\\\.|(?:(?:\\r\\n)?\n[ \\t]))*\"(?:(?:\\r\\n)?[ \\t])*)*:(?:(?:\\r\\n)?[ \\t])*(?:(?:(?:[^()<>@,;:\\\\\".\\[\\] \n\\000-\\031]+(?:(?:(?:\\r\\n)?[ \\t])+|\\Z|(?=[\\[\"()<>@,;:\\\\\".\\[\\]]))|\"(?:[^\\\"\\r\\\\]|\n\\\\.|(?:(?:\\r\\n)?[ \\t]))*\"(?:(?:\\r\\n)?[ \\t])*)(?:\\.(?:(?:\\r\\n)?[ \\t])*(?:[^()<>\n@,;:\\\\\".\\[\\] \\000-\\031]+(?:(?:(?:\\r\\n)?[ \\t])+|\\Z|(?=[\\[\"()<>@,;:\\\\\".\\[\\]]))|\"\n(?:[^\\\"\\r\\\\]|\\\\.|(?:(?:\\r\\n)?[ \\t]))*\"(?:(?:\\r\\n)?[ \\t])*))*@(?:(?:\\r\\n)?[ \\t]\n)*(?:[^()<>@,;:\\\\\".\\[\\] \\000-\\031]+(?:(?:(?:\\r\\n)?[ \\t])+|\\Z|(?=[\\[\"()<>@,;:\\\\\n\".\\[\\]]))|\\[([^\\[\\]\\r\\\\]|\\\\.)*\\](?:(?:\\r\\n)?[ \\t])*)(?:\\.(?:(?:\\r\\n)?[ \\t])*(?\n:[^()<>@,;:\\\\\".\\[\\] \\000-\\031]+(?:(?:(?:\\r\\n)?[ \\t])+|\\Z|(?=[\\[\"()<>@,;:\\\\\".\\[\n\\]]))|\\[([^\\[\\]\\r\\\\]|\\\\.)*\\](?:(?:\\r\\n)?[ \\t])*))*|(?:[^()<>@,;:\\\\\".\\[\\] \\000-\n\\031]+(?:(?:(?:\\r\\n)?[ \\t])+|\\Z|(?=[\\[\"()<>@,;:\\\\\".\\[\\]]))|\"(?:[^\\\"\\r\\\\]|\\\\.|(\n?:(?:\\r\\n)?[ \\t]))*\"(?:(?:\\r\\n)?[ \\t])*)*\\<(?:(?:\\r\\n)?[ \\t])*(?:@(?:[^()<>@,;\n:\\\\\".\\[\\] \\000-\\031]+(?:(?:(?:\\r\\n)?[ \\t])+|\\Z|(?=[\\[\"()<>@,;:\\\\\".\\[\\]]))|\\[([\n^\\[\\]\\r\\\\]|\\\\.)*\\](?:(?:\\r\\n)?[ \\t])*)(?:\\.(?:(?:\\r\\n)?[ \\t])*(?:[^()<>@,;:\\\\\"\n.\\[\\] \\000-\\031]+(?:(?:(?:\\r\\n)?[ \\t])+|\\Z|(?=[\\[\"()<>@,;:\\\\\".\\[\\]]))|\\[([^\\[\\\n]\\r\\\\]|\\\\.)*\\](?:(?:\\r\\n)?[ \\t])*))*(?:,@(?:(?:\\r\\n)?[ \\t])*(?:[^()<>@,;:\\\\\".\\\n[\\] \\000-\\031]+(?:(?:(?:\\r\\n)?[ \\t])+|\\Z|(?=[\\[\"()<>@,;:\\\\\".\\[\\]]))|\\[([^\\[\\]\\\nr\\\\]|\\\\.)*\\](?:(?:\\r\\n)?[ \\t])*)(?:\\.(?:(?:\\r\\n)?[ \\t])*(?:[^()<>@,;:\\\\\".\\[\\] \n\\000-\\031]+(?:(?:(?:\\r\\n)?[ \\t])+|\\Z|(?=[\\[\"()<>@,;:\\\\\".\\[\\]]))|\\[([^\\[\\]\\r\\\\]\n|\\\\.)*\\](?:(?:\\r\\n)?[ \\t])*))*)*:(?:(?:\\r\\n)?[ \\t])*)?(?:[^()<>@,;:\\\\\".\\[\\] \\0\n00-\\031]+(?:(?:(?:\\r\\n)?[ \\t])+|\\Z|(?=[\\[\"()<>@,;:\\\\\".\\[\\]]))|\"(?:[^\\\"\\r\\\\]|\\\\\n.|(?:(?:\\r\\n)?[ \\t]))*\"(?:(?:\\r\\n)?[ \\t])*)(?:\\.(?:(?:\\r\\n)?[ \\t])*(?:[^()<>@,\n;:\\\\\".\\[\\] \\000-\\031]+(?:(?:(?:\\r\\n)?[ \\t])+|\\Z|(?=[\\[\"()<>@,;:\\\\\".\\[\\]]))|\"(?\n:[^\\\"\\r\\\\]|\\\\.|(?:(?:\\r\\n)?[ \\t]))*\"(?:(?:\\r\\n)?[ \\t])*))*@(?:(?:\\r\\n)?[ \\t])*\n(?:[^()<>@,;:\\\\\".\\[\\] \\000-\\031]+(?:(?:(?:\\r\\n)?[ \\t])+|\\Z|(?=[\\[\"()<>@,;:\\\\\".\n\\[\\]]))|\\[([^\\[\\]\\r\\\\]|\\\\.)*\\](?:(?:\\r\\n)?[ \\t])*)(?:\\.(?:(?:\\r\\n)?[ \\t])*(?:[\n^()<>@,;:\\\\\".\\[\\] \\000-\\031]+(?:(?:(?:\\r\\n)?[ \\t])+|\\Z|(?=[\\[\"()<>@,;:\\\\\".\\[\\]\n]))|\\[([^\\[\\]\\r\\\\]|\\\\.)*\\](?:(?:\\r\\n)?[ \\t])*))*\\>(?:(?:\\r\\n)?[ \\t])*)(?:,\\s*(\n?:(?:[^()<>@,;:\\\\\".\\[\\] \\000-\\031]+(?:(?:(?:\\r\\n)?[ \\t])+|\\Z|(?=[\\[\"()<>@,;:\\\\\n\".\\[\\]]))|\"(?:[^\\\"\\r\\\\]|\\\\.|(?:(?:\\r\\n)?[ \\t]))*\"(?:(?:\\r\\n)?[ \\t])*)(?:\\.(?:(\n?:\\r\\n)?[ \\t])*(?:[^()<>@,;:\\\\\".\\[\\] \\000-\\031]+(?:(?:(?:\\r\\n)?[ \\t])+|\\Z|(?=[\n\\[\"()<>@,;:\\\\\".\\[\\]]))|\"(?:[^\\\"\\r\\\\]|\\\\.|(?:(?:\\r\\n)?[ \\t]))*\"(?:(?:\\r\\n)?[ \\t\n])*))*@(?:(?:\\r\\n)?[ \\t])*(?:[^()<>@,;:\\\\\".\\[\\] \\000-\\031]+(?:(?:(?:\\r\\n)?[ \\t\n])+|\\Z|(?=[\\[\"()<>@,;:\\\\\".\\[\\]]))|\\[([^\\[\\]\\r\\\\]|\\\\.)*\\](?:(?:\\r\\n)?[ \\t])*)(?\n:\\.(?:(?:\\r\\n)?[ \\t])*(?:[^()<>@,;:\\\\\".\\[\\] \\000-\\031]+(?:(?:(?:\\r\\n)?[ \\t])+|\n\\Z|(?=[\\[\"()<>@,;:\\\\\".\\[\\]]))|\\[([^\\[\\]\\r\\\\]|\\\\.)*\\](?:(?:\\r\\n)?[ \\t])*))*|(?:\n[^()<>@,;:\\\\\".\\[\\] \\000-\\031]+(?:(?:(?:\\r\\n)?[ \\t])+|\\Z|(?=[\\[\"()<>@,;:\\\\\".\\[\\\n]]))|\"(?:[^\\\"\\r\\\\]|\\\\.|(?:(?:\\r\\n)?[ \\t]))*\"(?:(?:\\r\\n)?[ \\t])*)*\\<(?:(?:\\r\\n)\n?[ \\t])*(?:@(?:[^()<>@,;:\\\\\".\\[\\] \\000-\\031]+(?:(?:(?:\\r\\n)?[ \\t])+|\\Z|(?=[\\[\"\n()<>@,;:\\\\\".\\[\\]]))|\\[([^\\[\\]\\r\\\\]|\\\\.)*\\](?:(?:\\r\\n)?[ \\t])*)(?:\\.(?:(?:\\r\\n)\n?[ \\t])*(?:[^()<>@,;:\\\\\".\\[\\] \\000-\\031]+(?:(?:(?:\\r\\n)?[ \\t])+|\\Z|(?=[\\[\"()<>\n@,;:\\\\\".\\[\\]]))|\\[([^\\[\\]\\r\\\\]|\\\\.)*\\](?:(?:\\r\\n)?[ \\t])*))*(?:,@(?:(?:\\r\\n)?[\n \\t])*(?:[^()<>@,;:\\\\\".\\[\\] \\000-\\031]+(?:(?:(?:\\r\\n)?[ \\t])+|\\Z|(?=[\\[\"()<>@,\n;:\\\\\".\\[\\]]))|\\[([^\\[\\]\\r\\\\]|\\\\.)*\\](?:(?:\\r\\n)?[ \\t])*)(?:\\.(?:(?:\\r\\n)?[ \\t]\n)*(?:[^()<>@,;:\\\\\".\\[\\] \\000-\\031]+(?:(?:(?:\\r\\n)?[ \\t])+|\\Z|(?=[\\[\"()<>@,;:\\\\\n\".\\[\\]]))|\\[([^\\[\\]\\r\\\\]|\\\\.)*\\](?:(?:\\r\\n)?[ \\t])*))*)*:(?:(?:\\r\\n)?[ \\t])*)?\n(?:[^()<>@,;:\\\\\".\\[\\] \\000-\\031]+(?:(?:(?:\\r\\n)?[ \\t])+|\\Z|(?=[\\[\"()<>@,;:\\\\\".\n\\[\\]]))|\"(?:[^\\\"\\r\\\\]|\\\\.|(?:(?:\\r\\n)?[ \\t]))*\"(?:(?:\\r\\n)?[ \\t])*)(?:\\.(?:(?:\n\\r\\n)?[ \\t])*(?:[^()<>@,;:\\\\\".\\[\\] \\000-\\031]+(?:(?:(?:\\r\\n)?[ \\t])+|\\Z|(?=[\\[\n\"()<>@,;:\\\\\".\\[\\]]))|\"(?:[^\\\"\\r\\\\]|\\\\.|(?:(?:\\r\\n)?[ \\t]))*\"(?:(?:\\r\\n)?[ \\t])\n*))*@(?:(?:\\r\\n)?[ \\t])*(?:[^()<>@,;:\\\\\".\\[\\] \\000-\\031]+(?:(?:(?:\\r\\n)?[ \\t])\n+|\\Z|(?=[\\[\"()<>@,;:\\\\\".\\[\\]]))|\\[([^\\[\\]\\r\\\\]|\\\\.)*\\](?:(?:\\r\\n)?[ \\t])*)(?:\\\n.(?:(?:\\r\\n)?[ \\t])*(?:[^()<>@,;:\\\\\".\\[\\] \\000-\\031]+(?:(?:(?:\\r\\n)?[ \\t])+|\\Z\n|(?=[\\[\"()<>@,;:\\\\\".\\[\\]]))|\\[([^\\[\\]\\r\\\\]|\\\\.)*\\](?:(?:\\r\\n)?[ \\t])*))*\\>(?:(\n?:\\r\\n)?[ \\t])*))*)?;\\s*)\n</code></pre>\n\n<p>(<a href=\"http://www.ex-parrot.com/~pdw/Mail-RFC822-Address.html\" rel=\"noreferrer\">http://www.ex-parrot.com/~pdw/Mail-RFC822-Address.html</a>)\nIf you're looking for something simpler but that will catch most valid email addresses try something like: </p>\n\n<pre class=\"lang-php prettyprint-override\"><code>\"^[a-zA-Z0-9_.+-]+@[a-zA-Z0-9-]+\\.[a-zA-Z0-9-.]+$\"\n</code></pre>\n\n<p>EDIT:\nFrom the link:</p>\n\n<blockquote>\n <p>This regular expression will only validate addresses that have had any comments stripped and replaced with whitespace (this is done by the module).</p>\n</blockquote>\n"
},
{
"answer_id": 902121,
"author": "chaos",
"author_id": 47529,
"author_profile": "https://Stackoverflow.com/users/47529",
"pm_score": 5,
"selected": false,
"text": "<p>You could use the one employed by the jQuery Validation plugin:</p>\n\n<pre><code>/^((([a-z]|\\d|[!#\\$%&'\\*\\+\\-\\/=\\?\\^_`{\\|}~]|[\\u00A0-\\uD7FF\\uF900-\\uFDCF\\uFDF0-\\uFFEF])+(\\.([a-z]|\\d|[!#\\$%&'\\*\\+\\-\\/=\\?\\^_`{\\|}~]|[\\u00A0-\\uD7FF\\uF900-\\uFDCF\\uFDF0-\\uFFEF])+)*)|((\\x22)((((\\x20|\\x09)*(\\x0d\\x0a))?(\\x20|\\x09)+)?(([\\x01-\\x08\\x0b\\x0c\\x0e-\\x1f\\x7f]|\\x21|[\\x23-\\x5b]|[\\x5d-\\x7e]|[\\u00A0-\\uD7FF\\uF900-\\uFDCF\\uFDF0-\\uFFEF])|(\\\\([\\x01-\\x09\\x0b\\x0c\\x0d-\\x7f]|[\\u00A0-\\uD7FF\\uF900-\\uFDCF\\uFDF0-\\uFFEF]))))*(((\\x20|\\x09)*(\\x0d\\x0a))?(\\x20|\\x09)+)?(\\x22)))@((([a-z]|\\d|[\\u00A0-\\uD7FF\\uF900-\\uFDCF\\uFDF0-\\uFFEF])|(([a-z]|\\d|[\\u00A0-\\uD7FF\\uF900-\\uFDCF\\uFDF0-\\uFFEF])([a-z]|\\d|-|\\.|_|~|[\\u00A0-\\uD7FF\\uF900-\\uFDCF\\uFDF0-\\uFFEF])*([a-z]|\\d|[\\u00A0-\\uD7FF\\uF900-\\uFDCF\\uFDF0-\\uFFEF])))\\.)+(([a-z]|[\\u00A0-\\uD7FF\\uF900-\\uFDCF\\uFDF0-\\uFFEF])|(([a-z]|[\\u00A0-\\uD7FF\\uF900-\\uFDCF\\uFDF0-\\uFFEF])([a-z]|\\d|-|\\.|_|~|[\\u00A0-\\uD7FF\\uF900-\\uFDCF\\uFDF0-\\uFFEF])*([a-z]|[\\u00A0-\\uD7FF\\uF900-\\uFDCF\\uFDF0-\\uFFEF])))\\.?$/i\n</code></pre>\n"
},
{
"answer_id": 1044515,
"author": "Greg Bacon",
"author_id": 123109,
"author_profile": "https://Stackoverflow.com/users/123109",
"pm_score": 4,
"selected": false,
"text": "<p>For a vivid demonstration, the following monster is pretty good, but it still does not correctly recognize all syntactically valid email addresses: it recognizes nested comments up to four levels deep.</p>\n<p>This is a job for a parser, but even if an address is syntactically valid, it still may not be deliverable. Sometimes you have to resort to the hillbilly method of "Hey, y'all, watch ee-us!"</p>\n<pre class=\"lang-none prettyprint-override\"><code>// derivative of work with the following copyright and license:\n// Copyright (c) 2004 Casey West. All rights reserved.\n// This module is free software; you can redistribute it and/or\n// modify it under the same terms as Perl itself.\n\n// see http://search.cpan.org/~cwest/Email-Address-1.80/\n\nprivate static string gibberish = @"\n(?-xism:(?:(?-xism:(?-xism:(?-xism:(?-xism:(?-xism:(?-xism:\\\ns*\\((?:\\s*(?-xism:(?-xism:(?>[^()\\\\]+))|(?-xism:\\\\(?-xism:[^\n\\x0A\\x0D]))|(?-xism:\\s*\\((?:\\s*(?-xism:(?-xism:(?>[^()\\\\]+))\n|(?-xism:\\\\(?-xism:[^\\x0A\\x0D]))|)+)*\\s*\\)\\s*))+)*\\s*\\)\\s*)+\n|\\s+)*[^\\x00-\\x1F\\x7F()<>\\[\\]:;@\\,.<DQ>\\s]+(?-xism:(?-xism:\\\ns*\\((?:\\s*(?-xism:(?-xism:(?>[^()\\\\]+))|(?-xism:\\\\(?-xism:[^\n\\x0A\\x0D]))|(?-xism:\\s*\\((?:\\s*(?-xism:(?-xism:(?>[^()\\\\]+))\n|(?-xism:\\\\(?-xism:[^\\x0A\\x0D]))|)+)*\\s*\\)\\s*))+)*\\s*\\)\\s*)+\n|\\s+)*)|(?-xism:(?-xism:(?-xism:\\s*\\((?:\\s*(?-xism:(?-xism:(\n?>[^()\\\\]+))|(?-xism:\\\\(?-xism:[^\\x0A\\x0D]))|(?-xism:\\s*\\((?\n:\\s*(?-xism:(?-xism:(?>[^()\\\\]+))|(?-xism:\\\\(?-xism:[^\\x0A\\x\n0D]))|)+)*\\s*\\)\\s*))+)*\\s*\\)\\s*)+|\\s+)*<DQ>(?-xism:(?-xism:[\n^\\\\<DQ>])|(?-xism:\\\\(?-xism:[^\\x0A\\x0D])))+<DQ>(?-xism:(?-xi\nsm:\\s*\\((?:\\s*(?-xism:(?-xism:(?>[^()\\\\]+))|(?-xism:\\\\(?-xis\nm:[^\\x0A\\x0D]))|(?-xism:\\s*\\((?:\\s*(?-xism:(?-xism:(?>[^()\\\\\n]+))|(?-xism:\\\\(?-xism:[^\\x0A\\x0D]))|)+)*\\s*\\)\\s*))+)*\\s*\\)\\\ns*)+|\\s+)*))+)?(?-xism:(?-xism:(?-xism:\\s*\\((?:\\s*(?-xism:(?\n-xism:(?>[^()\\\\]+))|(?-xism:\\\\(?-xism:[^\\x0A\\x0D]))|(?-xism:\n\\s*\\((?:\\s*(?-xism:(?-xism:(?>[^()\\\\]+))|(?-xism:\\\\(?-xism:[\n^\\x0A\\x0D]))|)+)*\\s*\\)\\s*))+)*\\s*\\)\\s*)+|\\s+)*<(?-xism:(?-xi\nsm:(?-xism:(?-xism:(?-xism:\\s*\\((?:\\s*(?-xism:(?-xism:(?>[^(\n)\\\\]+))|(?-xism:\\\\(?-xism:[^\\x0A\\x0D]))|(?-xism:\\s*\\((?:\\s*(\n?-xism:(?-xism:(?>[^()\\\\]+))|(?-xism:\\\\(?-xism:[^\\x0A\\x0D]))\n|)+)*\\s*\\)\\s*))+)*\\s*\\)\\s*)+|\\s+)*(?-xism:[^\\x00-\\x1F\\x7F()<\n>\\[\\]:;@\\,.<DQ>\\s]+(?:\\.[^\\x00-\\x1F\\x7F()<>\\[\\]:;@\\,.<DQ>\\s]\n+)*)(?-xism:(?-xism:\\s*\\((?:\\s*(?-xism:(?-xism:(?>[^()\\\\]+))\n|(?-xism:\\\\(?-xism:[^\\x0A\\x0D]))|(?-xism:\\s*\\((?:\\s*(?-xism:\n(?-xism:(?>[^()\\\\]+))|(?-xism:\\\\(?-xism:[^\\x0A\\x0D]))|)+)*\\s\n*\\)\\s*))+)*\\s*\\)\\s*)+|\\s+)*)|(?-xism:(?-xism:(?-xism:\\s*\\((?\n:\\s*(?-xism:(?-xism:(?>[^()\\\\]+))|(?-xism:\\\\(?-xism:[^\\x0A\\x\n0D]))|(?-xism:\\s*\\((?:\\s*(?-xism:(?-xism:(?>[^()\\\\]+))|(?-xi\nsm:\\\\(?-xism:[^\\x0A\\x0D]))|)+)*\\s*\\)\\s*))+)*\\s*\\)\\s*)+|\\s+)*\n<DQ>(?-xism:(?-xism:[^\\\\<DQ>])|(?-xism:\\\\(?-xism:[^\\x0A\\x0D]\n)))+<DQ>(?-xism:(?-xism:\\s*\\((?:\\s*(?-xism:(?-xism:(?>[^()\\\\\n]+))|(?-xism:\\\\(?-xism:[^\\x0A\\x0D]))|(?-xism:\\s*\\((?:\\s*(?-x\nism:(?-xism:(?>[^()\\\\]+))|(?-xism:\\\\(?-xism:[^\\x0A\\x0D]))|)+\n)*\\s*\\)\\s*))+)*\\s*\\)\\s*)+|\\s+)*))\\@(?-xism:(?-xism:(?-xism:(\n?-xism:\\s*\\((?:\\s*(?-xism:(?-xism:(?>[^()\\\\]+))|(?-xism:\\\\(?\n-xism:[^\\x0A\\x0D]))|(?-xism:\\s*\\((?:\\s*(?-xism:(?-xism:(?>[^\n()\\\\]+))|(?-xism:\\\\(?-xism:[^\\x0A\\x0D]))|)+)*\\s*\\)\\s*))+)*\\s\n*\\)\\s*)+|\\s+)*(?-xism:[^\\x00-\\x1F\\x7F()<>\\[\\]:;@\\,.<DQ>\\s]+(\n?:\\.[^\\x00-\\x1F\\x7F()<>\\[\\]:;@\\,.<DQ>\\s]+)*)(?-xism:(?-xism:\n\\s*\\((?:\\s*(?-xism:(?-xism:(?>[^()\\\\]+))|(?-xism:\\\\(?-xism:[\n^\\x0A\\x0D]))|(?-xism:\\s*\\((?:\\s*(?-xism:(?-xism:(?>[^()\\\\]+)\n)|(?-xism:\\\\(?-xism:[^\\x0A\\x0D]))|)+)*\\s*\\)\\s*))+)*\\s*\\)\\s*)\n+|\\s+)*)|(?-xism:(?-xism:(?-xism:\\s*\\((?:\\s*(?-xism:(?-xism:\n(?>[^()\\\\]+))|(?-xism:\\\\(?-xism:[^\\x0A\\x0D]))|(?-xism:\\s*\\((\n?:\\s*(?-xism:(?-xism:(?>[^()\\\\]+))|(?-xism:\\\\(?-xism:[^\\x0A\\\nx0D]))|)+)*\\s*\\)\\s*))+)*\\s*\\)\\s*)+|\\s+)*\\[(?:\\s*(?-xism:(?-x\nism:[^\\[\\]\\\\])|(?-xism:\\\\(?-xism:[^\\x0A\\x0D])))+)*\\s*\\](?-xi\nsm:(?-xism:\\s*\\((?:\\s*(?-xism:(?-xism:(?>[^()\\\\]+))|(?-xism:\n\\\\(?-xism:[^\\x0A\\x0D]))|(?-xism:\\s*\\((?:\\s*(?-xism:(?-xism:(\n?>[^()\\\\]+))|(?-xism:\\\\(?-xism:[^\\x0A\\x0D]))|)+)*\\s*\\)\\s*))+\n)*\\s*\\)\\s*)+|\\s+)*)))>(?-xism:(?-xism:\\s*\\((?:\\s*(?-xism:(?-\nxism:(?>[^()\\\\]+))|(?-xism:\\\\(?-xism:[^\\x0A\\x0D]))|(?-xism:\\\ns*\\((?:\\s*(?-xism:(?-xism:(?>[^()\\\\]+))|(?-xism:\\\\(?-xism:[^\n\\x0A\\x0D]))|)+)*\\s*\\)\\s*))+)*\\s*\\)\\s*)+|\\s+)*))|(?-xism:(?-x\nism:(?-xism:(?-xism:(?-xism:\\s*\\((?:\\s*(?-xism:(?-xism:(?>[^\n()\\\\]+))|(?-xism:\\\\(?-xism:[^\\x0A\\x0D]))|(?-xism:\\s*\\((?:\\s*\n(?-xism:(?-xism:(?>[^()\\\\]+))|(?-xism:\\\\(?-xism:[^\\x0A\\x0D])\n)|)+)*\\s*\\)\\s*))+)*\\s*\\)\\s*)+|\\s+)*(?-xism:[^\\x00-\\x1F\\x7F()\n<>\\[\\]:;@\\,.<DQ>\\s]+(?:\\.[^\\x00-\\x1F\\x7F()<>\\[\\]:;@\\,.<DQ>\\s\n]+)*)(?-xism:(?-xism:\\s*\\((?:\\s*(?-xism:(?-xism:(?>[^()\\\\]+)\n)|(?-xism:\\\\(?-xism:[^\\x0A\\x0D]))|(?-xism:\\s*\\((?:\\s*(?-xism\n:(?-xism:(?>[^()\\\\]+))|(?-xism:\\\\(?-xism:[^\\x0A\\x0D]))|)+)*\\\ns*\\)\\s*))+)*\\s*\\)\\s*)+|\\s+)*)|(?-xism:(?-xism:(?-xism:\\s*\\((\n?:\\s*(?-xism:(?-xism:(?>[^()\\\\]+))|(?-xism:\\\\(?-xism:[^\\x0A\\\nx0D]))|(?-xism:\\s*\\((?:\\s*(?-xism:(?-xism:(?>[^()\\\\]+))|(?-x\nism:\\\\(?-xism:[^\\x0A\\x0D]))|)+)*\\s*\\)\\s*))+)*\\s*\\)\\s*)+|\\s+)\n*<DQ>(?-xism:(?-xism:[^\\\\<DQ>])|(?-xism:\\\\(?-xism:[^\\x0A\\x0D\n])))+<DQ>(?-xism:(?-xism:\\s*\\((?:\\s*(?-xism:(?-xism:(?>[^()\\\n\\]+))|(?-xism:\\\\(?-xism:[^\\x0A\\x0D]))|(?-xism:\\s*\\((?:\\s*(?-\nxism:(?-xism:(?>[^()\\\\]+))|(?-xism:\\\\(?-xism:[^\\x0A\\x0D]))|)\n+)*\\s*\\)\\s*))+)*\\s*\\)\\s*)+|\\s+)*))\\@(?-xism:(?-xism:(?-xism:\n(?-xism:\\s*\\((?:\\s*(?-xism:(?-xism:(?>[^()\\\\]+))|(?-xism:\\\\(\n?-xism:[^\\x0A\\x0D]))|(?-xism:\\s*\\((?:\\s*(?-xism:(?-xism:(?>[\n^()\\\\]+))|(?-xism:\\\\(?-xism:[^\\x0A\\x0D]))|)+)*\\s*\\)\\s*))+)*\\\ns*\\)\\s*)+|\\s+)*(?-xism:[^\\x00-\\x1F\\x7F()<>\\[\\]:;@\\,.<DQ>\\s]+\n(?:\\.[^\\x00-\\x1F\\x7F()<>\\[\\]:;@\\,.<DQ>\\s]+)*)(?-xism:(?-xism\n:\\s*\\((?:\\s*(?-xism:(?-xism:(?>[^()\\\\]+))|(?-xism:\\\\(?-xism:\n[^\\x0A\\x0D]))|(?-xism:\\s*\\((?:\\s*(?-xism:(?-xism:(?>[^()\\\\]+\n))|(?-xism:\\\\(?-xism:[^\\x0A\\x0D]))|)+)*\\s*\\)\\s*))+)*\\s*\\)\\s*\n)+|\\s+)*)|(?-xism:(?-xism:(?-xism:\\s*\\((?:\\s*(?-xism:(?-xism\n:(?>[^()\\\\]+))|(?-xism:\\\\(?-xism:[^\\x0A\\x0D]))|(?-xism:\\s*\\(\n(?:\\s*(?-xism:(?-xism:(?>[^()\\\\]+))|(?-xism:\\\\(?-xism:[^\\x0A\n\\x0D]))|)+)*\\s*\\)\\s*))+)*\\s*\\)\\s*)+|\\s+)*\\[(?:\\s*(?-xism:(?-\nxism:[^\\[\\]\\\\])|(?-xism:\\\\(?-xism:[^\\x0A\\x0D])))+)*\\s*\\](?-x\nism:(?-xism:\\s*\\((?:\\s*(?-xism:(?-xism:(?>[^()\\\\]+))|(?-xism\n:\\\\(?-xism:[^\\x0A\\x0D]))|(?-xism:\\s*\\((?:\\s*(?-xism:(?-xism:\n(?>[^()\\\\]+))|(?-xism:\\\\(?-xism:[^\\x0A\\x0D]))|)+)*\\s*\\)\\s*))\n+)*\\s*\\)\\s*)+|\\s+)*))))(?-xism:\\s*\\((?:\\s*(?-xism:(?-xism:(?\n>[^()\\\\]+))|(?-xism:\\\\(?-xism:[^\\x0A\\x0D]))|(?-xism:\\s*\\((?:\n\\s*(?-xism:(?-xism:(?>[^()\\\\]+))|(?-xism:\\\\(?-xism:[^\\x0A\\x0\nD]))|)+)*\\s*\\)\\s*))+)*\\s*\\)\\s*)*)"\n .Replace("<DQ>", "\\"")\n .Replace("\\t", "")\n .Replace(" ", "")\n .Replace("\\r", "")\n .Replace("\\n", "");\n\nprivate static Regex mailbox =\n new Regex(gibberish, RegexOptions.ExplicitCapture);\n</code></pre>\n"
},
{
"answer_id": 1086376,
"author": "Nazmul Hasan",
"author_id": 309111,
"author_profile": "https://Stackoverflow.com/users/309111",
"pm_score": 2,
"selected": false,
"text": "<p>This is one of the regexes for email:</p>\n<pre><code>^((([a-z]|\\d|[!#\\$%&'\\*\\+\\-\\/=\\?\\^_`{\\|}~]|[\\u00A0-\\uD7FF\\uF900-\\uFDCF\\uFDF0-\\uFFEF])+(\\.([a-z]|\\d|[!#\\$%&'\\*\\+\\-\\/=\\?\\^_`{\\|}~]|[\\u00A0-\\uD7FF\\uF900-\\uFDCF\\uFDF0-\\uFFEF])+)*)|((\\x22)((((\\x20|\\x09)*(\\x0d\\x0a))?(\\x20|\\x09)+)?(([\\x01-\\x08\\x0b\\x0c\\x0e-\\x1f\\x7f]|\\x21|[\\x23-\\x5b]|[\\x5d-\\x7e]|[\\u00A0-\\uD7FF\\uF900-\\uFDCF\\uFDF0-\\uFFEF])|(\\\\([\\x01-\\x09\\x0b\\x0c\\x0d-\\x7f]|[\\u00A0-\\uD7FF\\uF900-\\uFDCF\\uFDF0-\\uFFEF]))))*(((\\x20|\\x09)*(\\x0d\\x0a))?(\\x20|\\x09)+)?(\\x22)))@((([a-z]|\\d|[\\u00A0-\\uD7FF\\uF900-\\uFDCF\\uFDF0-\\uFFEF])|(([a-z]|\\d|[\\u00A0-\\uD7FF\\uF900-\\uFDCF\\uFDF0-\\uFFEF])([a-z]|\\d|-|\\.|_|~|[\\u00A0-\\uD7FF\\uF900-\\uFDCF\\uFDF0-\\uFFEF])*([a-z]|\\d|[\\u00A0-\\uD7FF\\uF900-\\uFDCF\\uFDF0-\\uFFEF])))\\.)+(([a-z]|[\\u00A0-\\uD7FF\\uF900-\\uFDCF\\uFDF0-\\uFFEF])|(([a-z]|[\\u00A0-\\uD7FF\\uF900-\\uFDCF\\uFDF0-\\uFFEF])([a-z]|\\d|-|\\.|_|~|[\\u00A0-\\uD7FF\\uF900-\\uFDCF\\uFDF0-\\uFFEF])*([a-z]|[\\u00A0-\\uD7FF\\uF900-\\uFDCF\\uFDF0-\\uFFEF])))\\.?$\n</code></pre>\n"
},
{
"answer_id": 1329339,
"author": "Dimitris Andreou",
"author_id": 162895,
"author_profile": "https://Stackoverflow.com/users/162895",
"pm_score": 3,
"selected": false,
"text": "<p>I don't believe <a href=\"https://stackoverflow.com/questions/201323/how-can-i-validate-an-email-address-using-a-regular-expression/201378#201378\">the claim made by bortzmeyer</a> that "The grammar (specified in <a href=\"https://en.wikipedia.org/wiki/Email#Message_format\" rel=\"nofollow noreferrer\">RFC 5322</a>) is too complicated for that" (to be handled by a regular expression).</p>\n<p>Here is the grammar (from <em><a href=\"https://www.rfc-editor.org/rfc/rfc5322#section-3.4.1\" rel=\"nofollow noreferrer\">3.4.1. Addr-Spec Specification</a></em>):</p>\n<pre><code>addr-spec = local-part "@" domain\nlocal-part = dot-atom / quoted-string / obs-local-part\ndomain = dot-atom / domain-literal / obs-domain\ndomain-literal = [CFWS] "[" *([FWS] dtext) [FWS] "]" [CFWS]\ndtext = %d33-90 / ; Printable US-ASCII\n %d94-126 / ; characters not including\n obs-dtext ; "[", "]", or "\\"\n</code></pre>\n<p>Assuming that dot-atom, quoted-string, obs-local-part, obs-domain are themselves regular languages, this is a very simple grammar. Just replace the local-part and domain in the addr-spec production with their respective productions, and you have a regular language, directly translatable to a regular expression.</p>\n"
},
{
"answer_id": 1610200,
"author": "spig",
"author_id": 17891,
"author_profile": "https://Stackoverflow.com/users/17891",
"pm_score": 5,
"selected": false,
"text": "<p>One simple regular expression which would at least not reject any valid email address would be checking for something, followed by an @ sign and then something followed by a period and at least 2 somethings. It won't reject anything, but after reviewing the spec I can't find any email that would be valid and rejected.</p>\n\n<p>email =~ <code>/.+@[^@]+\\.[^@]{2,}$/</code></p>\n"
},
{
"answer_id": 1771483,
"author": "Michael",
"author_id": 215384,
"author_profile": "https://Stackoverflow.com/users/215384",
"pm_score": 4,
"selected": false,
"text": "<p>RFC 5322 standard:</p>\n\n<p>Allows dot-atom local-part, quoted-string local-part, obsolete (mixed dot-atom and quoted-string) local-part, domain name domain, (IPv4, IPv6, and IPv4-mapped IPv6 address) domain literal domain, and (nested) CFWS.</p>\n\n<pre><code>'/^(?!(?>(?1)\"?(?>\\\\\\[ -~]|[^\"])\"?(?1)){255,})(?!(?>(?1)\"?(?>\\\\\\[ -~]|[^\"])\"?(?1)){65,}@)((?>(?>(?>((?>(?>(?>\\x0D\\x0A)?[\\t ])+|(?>[\\t ]*\\x0D\\x0A)?[\\t ]+)?)(\\((?>(?2)(?>[\\x01-\\x08\\x0B\\x0C\\x0E-\\'*-\\[\\]-\\x7F]|\\\\\\[\\x00-\\x7F]|(?3)))*(?2)\\)))+(?2))|(?2))?)([!#-\\'*+\\/-9=?^-~-]+|\"(?>(?2)(?>[\\x01-\\x08\\x0B\\x0C\\x0E-!#-\\[\\]-\\x7F]|\\\\\\[\\x00-\\x7F]))*(?2)\")(?>(?1)\\.(?1)(?4))*(?1)@(?!(?1)[a-z0-9-]{64,})(?1)(?>([a-z0-9](?>[a-z0-9-]*[a-z0-9])?)(?>(?1)\\.(?!(?1)[a-z0-9-]{64,})(?1)(?5)){0,126}|\\[(?:(?>IPv6:(?>([a-f0-9]{1,4})(?>:(?6)){7}|(?!(?:.*[a-f0-9][:\\]]){8,})((?6)(?>:(?6)){0,6})?::(?7)?))|(?>(?>IPv6:(?>(?6)(?>:(?6)){5}:|(?!(?:.*[a-f0-9]:){6,})(?8)?::(?>((?6)(?>:(?6)){0,4}):)?))?(25[0-5]|2[0-4][0-9]|1[0-9]{2}|[1-9]?[0-9])(?>\\.(?9)){3}))\\])(?1)$/isD'\n</code></pre>\n\n<p>RFC 5321 standard:</p>\n\n<p>Allows dot-atom local-part, quoted-string local-part, domain name domain, and (IPv4, IPv6, and IPv4-mapped IPv6 address) domain literal domain.</p>\n\n<pre><code>'/^(?!(?>\"?(?>\\\\\\[ -~]|[^\"])\"?){255,})(?!\"?(?>\\\\\\[ -~]|[^\"]){65,}\"?@)(?>([!#-\\'*+\\/-9=?^-~-]+)(?>\\.(?1))*|\"(?>[ !#-\\[\\]-~]|\\\\\\[ -~])*\")@(?!.*[^.]{64,})(?>([a-z0-9](?>[a-z0-9-]*[a-z0-9])?)(?>\\.(?2)){0,126}|\\[(?:(?>IPv6:(?>([a-f0-9]{1,4})(?>:(?3)){7}|(?!(?:.*[a-f0-9][:\\]]){8,})((?3)(?>:(?3)){0,6})?::(?4)?))|(?>(?>IPv6:(?>(?3)(?>:(?3)){5}:|(?!(?:.*[a-f0-9]:){6,})(?5)?::(?>((?3)(?>:(?3)){0,4}):)?))?(25[0-5]|2[0-4][0-9]|1[0-9]{2}|[1-9]?[0-9])(?>\\.(?6)){3}))\\])$/iD'\n</code></pre>\n\n<p>Basic:</p>\n\n<p>Allows dot-atom local-part and domain name domain (requiring at least two domain name labels with the TLD limited to 2-6 alphabetic characters).</p>\n\n<pre><code>\"/^(?!.{255,})(?!.{65,}@)([!#-'*+\\/-9=?^-~-]+)(?>\\.(?1))*@(?!.*[^.]{64,})(?>[a-z0-9](?>[a-z0-9-]*[a-z0-9])?\\.){1,126}[a-z]{2,6}$/iD\"\n</code></pre>\n"
},
{
"answer_id": 1903368,
"author": "SLaks",
"author_id": 34397,
"author_profile": "https://Stackoverflow.com/users/34397",
"pm_score": 10,
"selected": false,
"text": "<p>You should not use regular expressions to validate email addresses.</p>\n<p>Instead, in C# use the <a href=\"http://msdn.microsoft.com/en-us/library/system.net.mail.mailaddress.aspx\" rel=\"noreferrer\">MailAddress</a> class, like this:</p>\n<pre class=\"lang-csharp prettyprint-override\"><code>try {\n address = new MailAddress(address).Address;\n} catch(FormatException) {\n // address is invalid\n}\n</code></pre>\n<p>The <code>MailAddress</code> class uses a <a href=\"https://en.wikipedia.org/wiki/Backus%E2%80%93Naur_form\" rel=\"noreferrer\">BNF</a> parser to validate the address in full accordance with RFC822.</p>\n<p>If you plan to use the <code>MailAddress</code> to validate the e-mail address, be aware that this approach accepts the display name part of the e-mail address as well, and that may not be exactly what you want to achieve. For example, it accepts these strings as valid e-mail addresses:</p>\n<ul>\n<li>"[email protected]; [email protected]"</li>\n<li>"[email protected]; [email protected]; [email protected]"</li>\n<li>"User Display Name [email protected]"</li>\n<li>"user4 @company.com"</li>\n</ul>\n<p>In some of these cases, only the last part of the strings is parsed as the address; the rest before that is the display name. To get a plain e-mail address without any display name, you can check the normalized address against your original string.</p>\n<pre class=\"lang-csharp prettyprint-override\"><code>bool isValid = false;\n\ntry\n{\n MailAddress address = new MailAddress(emailAddress);\n isValid = (address.Address == emailAddress);\n // or\n // isValid = string.IsNullOrEmpty(address.DisplayName);\n}\ncatch (FormatException)\n{\n // address is invalid\n}\n</code></pre>\n<p>Furthermore, an address having a dot at the end, like <code>user@company.</code> is accepted by MailAddress as well.</p>\n<p>If you really want to use a regex, <a href=\"http://www.ex-parrot.com/%7Epdw/Mail-RFC822-Address.html\" rel=\"noreferrer\">here it is</a>:</p>\n<pre>(?:(?:\\r\\n)?[ \\t])*(?:(?:(?:[^()<>@,;:\\\\\".\\[\\] \\000-\\031]+(?:(?:(?:\\r\\n)?[ \\t]\n)+|\\Z|(?=[\\[\"()<>@,;:\\\\\".\\[\\]]))|\"(?:[^\\\"\\r\\\\]|\\\\.|(?:(?:\\r\\n)?[ \\t]))*\"(?:(?:\n\\r\\n)?[ \\t])*)(?:\\.(?:(?:\\r\\n)?[ \\t])*(?:[^()<>@,;:\\\\\".\\[\\] \\000-\\031]+(?:(?:(\n?:\\r\\n)?[ \\t])+|\\Z|(?=[\\[\"()<>@,;:\\\\\".\\[\\]]))|\"(?:[^\\\"\\r\\\\]|\\\\.|(?:(?:\\r\\n)?[ \n\\t]))*\"(?:(?:\\r\\n)?[ \\t])*))*@(?:(?:\\r\\n)?[ \\t])*(?:[^()<>@,;:\\\\\".\\[\\] \\000-\\0\n31]+(?:(?:(?:\\r\\n)?[ \\t])+|\\Z|(?=[\\[\"()<>@,;:\\\\\".\\[\\]]))|\\[([^\\[\\]\\r\\\\]|\\\\.)*\\\n](?:(?:\\r\\n)?[ \\t])*)(?:\\.(?:(?:\\r\\n)?[ \\t])*(?:[^()<>@,;:\\\\\".\\[\\] \\000-\\031]+\n(?:(?:(?:\\r\\n)?[ \\t])+|\\Z|(?=[\\[\"()<>@,;:\\\\\".\\[\\]]))|\\[([^\\[\\]\\r\\\\]|\\\\.)*\\](?:\n(?:\\r\\n)?[ \\t])*))*|(?:[^()<>@,;:\\\\\".\\[\\] \\000-\\031]+(?:(?:(?:\\r\\n)?[ \\t])+|\\Z\n|(?=[\\[\"()<>@,;:\\\\\".\\[\\]]))|\"(?:[^\\\"\\r\\\\]|\\\\.|(?:(?:\\r\\n)?[ \\t]))*\"(?:(?:\\r\\n)\n?[ \\t])*)*\\<(?:(?:\\r\\n)?[ \\t])*(?:@(?:[^()<>@,;:\\\\\".\\[\\] \\000-\\031]+(?:(?:(?:\\\nr\\n)?[ \\t])+|\\Z|(?=[\\[\"()<>@,;:\\\\\".\\[\\]]))|\\[([^\\[\\]\\r\\\\]|\\\\.)*\\](?:(?:\\r\\n)?[\n \\t])*)(?:\\.(?:(?:\\r\\n)?[ \\t])*(?:[^()<>@,;:\\\\\".\\[\\] \\000-\\031]+(?:(?:(?:\\r\\n)\n?[ \\t])+|\\Z|(?=[\\[\"()<>@,;:\\\\\".\\[\\]]))|\\[([^\\[\\]\\r\\\\]|\\\\.)*\\](?:(?:\\r\\n)?[ \\t]\n)*))*(?:,@(?:(?:\\r\\n)?[ \\t])*(?:[^()<>@,;:\\\\\".\\[\\] \\000-\\031]+(?:(?:(?:\\r\\n)?[\n \\t])+|\\Z|(?=[\\[\"()<>@,;:\\\\\".\\[\\]]))|\\[([^\\[\\]\\r\\\\]|\\\\.)*\\](?:(?:\\r\\n)?[ \\t])*\n)(?:\\.(?:(?:\\r\\n)?[ \\t])*(?:[^()<>@,;:\\\\\".\\[\\] \\000-\\031]+(?:(?:(?:\\r\\n)?[ \\t]\n)+|\\Z|(?=[\\[\"()<>@,;:\\\\\".\\[\\]]))|\\[([^\\[\\]\\r\\\\]|\\\\.)*\\](?:(?:\\r\\n)?[ \\t])*))*)\n*:(?:(?:\\r\\n)?[ \\t])*)?(?:[^()<>@,;:\\\\\".\\[\\] \\000-\\031]+(?:(?:(?:\\r\\n)?[ \\t])+\n|\\Z|(?=[\\[\"()<>@,;:\\\\\".\\[\\]]))|\"(?:[^\\\"\\r\\\\]|\\\\.|(?:(?:\\r\\n)?[ \\t]))*\"(?:(?:\\r\n\\n)?[ \\t])*)(?:\\.(?:(?:\\r\\n)?[ \\t])*(?:[^()<>@,;:\\\\\".\\[\\] \\000-\\031]+(?:(?:(?:\n\\r\\n)?[ \\t])+|\\Z|(?=[\\[\"()<>@,;:\\\\\".\\[\\]]))|\"(?:[^\\\"\\r\\\\]|\\\\.|(?:(?:\\r\\n)?[ \\t\n]))*\"(?:(?:\\r\\n)?[ \\t])*))*@(?:(?:\\r\\n)?[ \\t])*(?:[^()<>@,;:\\\\\".\\[\\] \\000-\\031\n]+(?:(?:(?:\\r\\n)?[ \\t])+|\\Z|(?=[\\[\"()<>@,;:\\\\\".\\[\\]]))|\\[([^\\[\\]\\r\\\\]|\\\\.)*\\](\n?:(?:\\r\\n)?[ \\t])*)(?:\\.(?:(?:\\r\\n)?[ \\t])*(?:[^()<>@,;:\\\\\".\\[\\] \\000-\\031]+(?\n:(?:(?:\\r\\n)?[ \\t])+|\\Z|(?=[\\[\"()<>@,;:\\\\\".\\[\\]]))|\\[([^\\[\\]\\r\\\\]|\\\\.)*\\](?:(?\n:\\r\\n)?[ \\t])*))*\\>(?:(?:\\r\\n)?[ \\t])*)|(?:[^()<>@,;:\\\\\".\\[\\] \\000-\\031]+(?:(?\n:(?:\\r\\n)?[ \\t])+|\\Z|(?=[\\[\"()<>@,;:\\\\\".\\[\\]]))|\"(?:[^\\\"\\r\\\\]|\\\\.|(?:(?:\\r\\n)?\n[ \\t]))*\"(?:(?:\\r\\n)?[ \\t])*)*:(?:(?:\\r\\n)?[ \\t])*(?:(?:(?:[^()<>@,;:\\\\\".\\[\\] \n\\000-\\031]+(?:(?:(?:\\r\\n)?[ \\t])+|\\Z|(?=[\\[\"()<>@,;:\\\\\".\\[\\]]))|\"(?:[^\\\"\\r\\\\]|\n\\\\.|(?:(?:\\r\\n)?[ \\t]))*\"(?:(?:\\r\\n)?[ \\t])*)(?:\\.(?:(?:\\r\\n)?[ \\t])*(?:[^()<>\n\n@,;:\\\\\".\\[\\] \\000-\\031]+(?:(?:(?:\\r\\n)?[ \\t])+|\\Z|(?=[\\[\"()<>@,;:\\\\\".\\[\\]]))|\"\n(?:[^\\\"\\r\\\\]|\\\\.|(?:(?:\\r\\n)?[ \\t]))*\"(?:(?:\\r\\n)?[ \\t])*))*@(?:(?:\\r\\n)?[ \\t]\n)*(?:[^()<>@,;:\\\\\".\\[\\] \\000-\\031]+(?:(?:(?:\\r\\n)?[ \\t])+|\\Z|(?=[\\[\"()<>@,;:\\\\\n\".\\[\\]]))|\\[([^\\[\\]\\r\\\\]|\\\\.)*\\](?:(?:\\r\\n)?[ \\t])*)(?:\\.(?:(?:\\r\\n)?[ \\t])*(?\n:[^()<>@,;:\\\\\".\\[\\] \\000-\\031]+(?:(?:(?:\\r\\n)?[ \\t])+|\\Z|(?=[\\[\"()<>@,;:\\\\\".\\[\n\\]]))|\\[([^\\[\\]\\r\\\\]|\\\\.)*\\](?:(?:\\r\\n)?[ \\t])*))*|(?:[^()<>@,;:\\\\\".\\[\\] \\000-\n\\031]+(?:(?:(?:\\r\\n)?[ \\t])+|\\Z|(?=[\\[\"()<>@,;:\\\\\".\\[\\]]))|\"(?:[^\\\"\\r\\\\]|\\\\.|(\n?:(?:\\r\\n)?[ \\t]))*\"(?:(?:\\r\\n)?[ \\t])*)*\\<(?:(?:\\r\\n)?[ \\t])*(?:@(?:[^()<>@,;\n:\\\\\".\\[\\] \\000-\\031]+(?:(?:(?:\\r\\n)?[ \\t])+|\\Z|(?=[\\[\"()<>@,;:\\\\\".\\[\\]]))|\\[([\n^\\[\\]\\r\\\\]|\\\\.)*\\](?:(?:\\r\\n)?[ \\t])*)(?:\\.(?:(?:\\r\\n)?[ \\t])*(?:[^()<>@,;:\\\\\"\n.\\[\\] \\000-\\031]+(?:(?:(?:\\r\\n)?[ \\t])+|\\Z|(?=[\\[\"()<>@,;:\\\\\".\\[\\]]))|\\[([^\\[\\\n]\\r\\\\]|\\\\.)*\\](?:(?:\\r\\n)?[ \\t])*))*(?:,@(?:(?:\\r\\n)?[ \\t])*(?:[^()<>@,;:\\\\\".\\\n[\\] \\000-\\031]+(?:(?:(?:\\r\\n)?[ \\t])+|\\Z|(?=[\\[\"()<>@,;:\\\\\".\\[\\]]))|\\[([^\\[\\]\\\nr\\\\]|\\\\.)*\\](?:(?:\\r\\n)?[ \\t])*)(?:\\.(?:(?:\\r\\n)?[ \\t])*(?:[^()<>@,;:\\\\\".\\[\\] \n\\000-\\031]+(?:(?:(?:\\r\\n)?[ \\t])+|\\Z|(?=[\\[\"()<>@,;:\\\\\".\\[\\]]))|\\[([^\\[\\]\\r\\\\]\n|\\\\.)*\\](?:(?:\\r\\n)?[ \\t])*))*)*:(?:(?:\\r\\n)?[ \\t])*)?(?:[^()<>@,;:\\\\\".\\[\\] \\0\n00-\\031]+(?:(?:(?:\\r\\n)?[ \\t])+|\\Z|(?=[\\[\"()<>@,;:\\\\\".\\[\\]]))|\"(?:[^\\\"\\r\\\\]|\\\\\n.|(?:(?:\\r\\n)?[ \\t]))*\"(?:(?:\\r\\n)?[ \\t])*)(?:\\.(?:(?:\\r\\n)?[ \\t])*(?:[^()<>@,\n;:\\\\\".\\[\\] \\000-\\031]+(?:(?:(?:\\r\\n)?[ \\t])+|\\Z|(?=[\\[\"()<>@,;:\\\\\".\\[\\]]))|\"(?\n:[^\\\"\\r\\\\]|\\\\.|(?:(?:\\r\\n)?[ \\t]))*\"(?:(?:\\r\\n)?[ \\t])*))*@(?:(?:\\r\\n)?[ \\t])*\n(?:[^()<>@,;:\\\\\".\\[\\] \\000-\\031]+(?:(?:(?:\\r\\n)?[ \\t])+|\\Z|(?=[\\[\"()<>@,;:\\\\\".\n\\[\\]]))|\\[([^\\[\\]\\r\\\\]|\\\\.)*\\](?:(?:\\r\\n)?[ \\t])*)(?:\\.(?:(?:\\r\\n)?[ \\t])*(?:[\n^()<>@,;:\\\\\".\\[\\] \\000-\\031]+(?:(?:(?:\\r\\n)?[ \\t])+|\\Z|(?=[\\[\"()<>@,;:\\\\\".\\[\\]\n]))|\\[([^\\[\\]\\r\\\\]|\\\\.)*\\](?:(?:\\r\\n)?[ \\t])*))*\\>(?:(?:\\r\\n)?[ \\t])*)(?:,\\s*(\n?:(?:[^()<>@,;:\\\\\".\\[\\] \\000-\\031]+(?:(?:(?:\\r\\n)?[ \\t])+|\\Z|(?=[\\[\"()<>@,;:\\\\\n\".\\[\\]]))|\"(?:[^\\\"\\r\\\\]|\\\\.|(?:(?:\\r\\n)?[ \\t]))*\"(?:(?:\\r\\n)?[ \\t])*)(?:\\.(?:(\n?:\\r\\n)?[ \\t])*(?:[^()<>@,;:\\\\\".\\[\\] \\000-\\031]+(?:(?:(?:\\r\\n)?[ \\t])+|\\Z|(?=[\n\\[\"()<>@,;:\\\\\".\\[\\]]))|\"(?:[^\\\"\\r\\\\]|\\\\.|(?:(?:\\r\\n)?[ \\t]))*\"(?:(?:\\r\\n)?[ \\t\n])*))*@(?:(?:\\r\\n)?[ \\t])*(?:[^()<>@,;:\\\\\".\\[\\] \\000-\\031]+(?:(?:(?:\\r\\n)?[ \\t\n])+|\\Z|(?=[\\[\"()<>@,;:\\\\\".\\[\\]]))|\\[([^\\[\\]\\r\\\\]|\\\\.)*\\](?:(?:\\r\\n)?[ \\t])*)(?\n:\\.(?:(?:\\r\\n)?[ \\t])*(?:[^()<>@,;:\\\\\".\\[\\] \\000-\\031]+(?:(?:(?:\\r\\n)?[ \\t])+|\n\\Z|(?=[\\[\"()<>@,;:\\\\\".\\[\\]]))|\\[([^\\[\\]\\r\\\\]|\\\\.)*\\](?:(?:\\r\\n)?[ \\t])*))*|(?:\n[^()<>@,;:\\\\\".\\[\\] \\000-\\031]+(?:(?:(?:\\r\\n)?[ \\t])+|\\Z|(?=[\\[\"()<>@,;:\\\\\".\\[\\\n]]))|\"(?:[^\\\"\\r\\\\]|\\\\.|(?:(?:\\r\\n)?[ \\t]))*\"(?:(?:\\r\\n)?[ \\t])*)*\\<(?:(?:\\r\\n)\n?[ \\t])*(?:@(?:[^()<>@,;:\\\\\".\\[\\] \\000-\\031]+(?:(?:(?:\\r\\n)?[ \\t])+|\\Z|(?=[\\[\"\n()<>@,;:\\\\\".\\[\\]]))|\\[([^\\[\\]\\r\\\\]|\\\\.)*\\](?:(?:\\r\\n)?[ \\t])*)(?:\\.(?:(?:\\r\\n)\n?[ \\t])*(?:[^()<>@,;:\\\\\".\\[\\] \\000-\\031]+(?:(?:(?:\\r\\n)?[ \\t])+|\\Z|(?=[\\[\"()<>\n\n@,;:\\\\\".\\[\\]]))|\\[([^\\[\\]\\r\\\\]|\\\\.)*\\](?:(?:\\r\\n)?[ \\t])*))*(?:,@(?:(?:\\r\\n)?[\n \\t])*(?:[^()<>@,;:\\\\\".\\[\\] \\000-\\031]+(?:(?:(?:\\r\\n)?[ \\t])+|\\Z|(?=[\\[\"()<>@,\n;:\\\\\".\\[\\]]))|\\[([^\\[\\]\\r\\\\]|\\\\.)*\\](?:(?:\\r\\n)?[ \\t])*)(?:\\.(?:(?:\\r\\n)?[ \\t]\n)*(?:[^()<>@,;:\\\\\".\\[\\] \\000-\\031]+(?:(?:(?:\\r\\n)?[ \\t])+|\\Z|(?=[\\[\"()<>@,;:\\\\\n\".\\[\\]]))|\\[([^\\[\\]\\r\\\\]|\\\\.)*\\](?:(?:\\r\\n)?[ \\t])*))*)*:(?:(?:\\r\\n)?[ \\t])*)?\n(?:[^()<>@,;:\\\\\".\\[\\] \\000-\\031]+(?:(?:(?:\\r\\n)?[ \\t])+|\\Z|(?=[\\[\"()<>@,;:\\\\\".\n\\[\\]]))|\"(?:[^\\\"\\r\\\\]|\\\\.|(?:(?:\\r\\n)?[ \\t]))*\"(?:(?:\\r\\n)?[ \\t])*)(?:\\.(?:(?:\n\\r\\n)?[ \\t])*(?:[^()<>@,;:\\\\\".\\[\\] \\000-\\031]+(?:(?:(?:\\r\\n)?[ \\t])+|\\Z|(?=[\\[\n\"()<>@,;:\\\\\".\\[\\]]))|\"(?:[^\\\"\\r\\\\]|\\\\.|(?:(?:\\r\\n)?[ \\t]))*\"(?:(?:\\r\\n)?[ \\t])\n*))*@(?:(?:\\r\\n)?[ \\t])*(?:[^()<>@,;:\\\\\".\\[\\] \\000-\\031]+(?:(?:(?:\\r\\n)?[ \\t])\n+|\\Z|(?=[\\[\"()<>@,;:\\\\\".\\[\\]]))|\\[([^\\[\\]\\r\\\\]|\\\\.)*\\](?:(?:\\r\\n)?[ \\t])*)(?:\\\n.(?:(?:\\r\\n)?[ \\t])*(?:[^()<>@,;:\\\\\".\\[\\] \\000-\\031]+(?:(?:(?:\\r\\n)?[ \\t])+|\\Z\n|(?=[\\[\"()<>@,;:\\\\\".\\[\\]]))|\\[([^\\[\\]\\r\\\\]|\\\\.)*\\](?:(?:\\r\\n)?[ \\t])*))*\\>(?:(\n?:\\r\\n)?[ \\t])*))*)?;\\s*)</pre>\n"
},
{
"answer_id": 1911522,
"author": "Jay Zeng",
"author_id": 201438,
"author_profile": "https://Stackoverflow.com/users/201438",
"pm_score": 2,
"selected": false,
"text": "<p>No one mentioned the issue of localization (<a href=\"https://en.wikipedia.org/wiki/Internationalization_and_localization\" rel=\"nofollow noreferrer\">i18n</a>). What if you have clients coming from all over the world?</p>\n<p>You will need to then need to sub-categorize your regex per country/area, which I have seen developers ending up building a large dictionary or configuration. Detecting the users' browser language setting may be a good starting point.</p>\n"
},
{
"answer_id": 1917982,
"author": "Abigail",
"author_id": 233315,
"author_profile": "https://Stackoverflow.com/users/233315",
"pm_score": 8,
"selected": false,
"text": "<p>It’s easy in Perl 5.10 or newer:</p>\n<pre class=\"lang-none prettyprint-override\"><code>/(?(DEFINE)\n (?<address> (?&mailbox) | (?&group))\n (?<mailbox> (?&name_addr) | (?&addr_spec))\n (?<name_addr> (?&display_name)? (?&angle_addr))\n (?<angle_addr> (?&CFWS)? < (?&addr_spec) > (?&CFWS)?)\n (?<group> (?&display_name) : (?:(?&mailbox_list) | (?&CFWS))? ;\n (?&CFWS)?)\n (?<display_name> (?&phrase))\n (?<mailbox_list> (?&mailbox) (?: , (?&mailbox))*)\n\n (?<addr_spec> (?&local_part) \\@ (?&domain))\n (?<local_part> (?&dot_atom) | (?&quoted_string))\n (?<domain> (?&dot_atom) | (?&domain_literal))\n (?<domain_literal> (?&CFWS)? \\[ (?: (?&FWS)? (?&dcontent))* (?&FWS)?\n \\] (?&CFWS)?)\n (?<dcontent> (?&dtext) | (?&quoted_pair))\n (?<dtext> (?&NO_WS_CTL) | [\\x21-\\x5a\\x5e-\\x7e])\n\n (?<atext> (?&ALPHA) | (?&DIGIT) | [!#\\$%&'*+-/=?^_`{|}~])\n (?<atom> (?&CFWS)? (?&atext)+ (?&CFWS)?)\n (?<dot_atom> (?&CFWS)? (?&dot_atom_text) (?&CFWS)?)\n (?<dot_atom_text> (?&atext)+ (?: \\. (?&atext)+)*)\n\n (?<text> [\\x01-\\x09\\x0b\\x0c\\x0e-\\x7f])\n (?<quoted_pair> \\\\ (?&text))\n\n (?<qtext> (?&NO_WS_CTL) | [\\x21\\x23-\\x5b\\x5d-\\x7e])\n (?<qcontent> (?&qtext) | (?&quoted_pair))\n (?<quoted_string> (?&CFWS)? (?&DQUOTE) (?:(?&FWS)? (?&qcontent))*\n (?&FWS)? (?&DQUOTE) (?&CFWS)?)\n\n (?<word> (?&atom) | (?&quoted_string))\n (?<phrase> (?&word)+)\n\n # Folding white space\n (?<FWS> (?: (?&WSP)* (?&CRLF))? (?&WSP)+)\n (?<ctext> (?&NO_WS_CTL) | [\\x21-\\x27\\x2a-\\x5b\\x5d-\\x7e])\n (?<ccontent> (?&ctext) | (?&quoted_pair) | (?&comment))\n (?<comment> \\( (?: (?&FWS)? (?&ccontent))* (?&FWS)? \\) )\n (?<CFWS> (?: (?&FWS)? (?&comment))*\n (?: (?:(?&FWS)? (?&comment)) | (?&FWS)))\n\n # No whitespace control\n (?<NO_WS_CTL> [\\x01-\\x08\\x0b\\x0c\\x0e-\\x1f\\x7f])\n\n (?<ALPHA> [A-Za-z])\n (?<DIGIT> [0-9])\n (?<CRLF> \\x0d \\x0a)\n (?<DQUOTE> ")\n (?<WSP> [\\x20\\x09])\n )\n\n (?&address)/x\n</code></pre>\n"
},
{
"answer_id": 1931322,
"author": "BalusC",
"author_id": 157882,
"author_profile": "https://Stackoverflow.com/users/157882",
"pm_score": 5,
"selected": false,
"text": "<p><a href=\"http://en.wikipedia.org/wiki/Internationalized_domain_name\" rel=\"nofollow noreferrer\">Since May 2010</a>, non-Latin (Chinese, Arabic, Greek, Hebrew, Cyrillic and so on) domain names exist on the Internet. Everyone has to change the email regex used, because those characters are surely not to be covered by <code>[a-z]/i</code> nor <code>\\w</code>. They will all fail.</p>\n<p>After all, the <strong>best</strong> way to validate the email address is still to actually <em>send</em> an email to the address in question to validate the address. If the email address is part of user authentication (register/login/etc), then you can perfectly combine it with the user activation system. I.e. send an email with a link with an unique activation key to the specified email address and only allow login when the user has activated the newly created account using the link in the email.</p>\n<p>If the purpose of the regex is just to quickly inform the user in the UI that the specified email address doesn't look like in the right format, best is still to check if it matches basically the following regex:</p>\n<pre><code>^([^.@]+)(\\.[^.@]+)*@([^.@]+\\.)+([^.@]+)$\n</code></pre>\n<p>Simple as that. Why on earth would you care about the characters used in the name and domain? It's the client's responsibility to enter a valid email address, not the server's. Even when the client enters a <em>syntactically</em> valid email address like <code>[email protected]</code>, this does not guarantee that it's a legit email address. No one regex can cover that.</p>\n"
},
{
"answer_id": 2148664,
"author": "Evan Carroll",
"author_id": 124486,
"author_profile": "https://Stackoverflow.com/users/124486",
"pm_score": 6,
"selected": false,
"text": "<p>This regex is from Perl's <a href=\"https://metacpan.org/source/RJBS/Email-Valid-1.198/lib/Email/Valid.pm\" rel=\"nofollow noreferrer\">Email::Valid</a> library. I believe it to be the most accurate, and it matches all of <a href=\"https://en.wikipedia.org/wiki/Email\" rel=\"nofollow noreferrer\">RFC 822</a>. And, it is based on the regular expression in the O'Reilly book:</p>\n<blockquote>\n<p>Regular expression built using Jeffrey Friedl's example in\n<em>Mastering Regular Expressions</em> (<a href=\"http://www.ora.com/catalog/regexp/\" rel=\"nofollow noreferrer\">http://www.ora.com/catalog/regexp/</a>).</p>\n</blockquote>\n<pre class=\"lang-none prettyprint-override\"><code>$RFC822PAT = <<'EOF';\n[\\040\\t]*(?:\\([^\\\\\\x80-\\xff\\n\\015()]*(?:(?:\\\\[^\\x80-\\xff]|\\([^\\\\\\x80-\\\nxff\\n\\015()]*(?:\\\\[^\\x80-\\xff][^\\\\\\x80-\\xff\\n\\015()]*)*\\))[^\\\\\\x80-\\xf\nf\\n\\015()]*)*\\)[\\040\\t]*)*(?:(?:[^(\\040)<>@,;:".\\\\\\[\\]\\000-\\037\\x80-\\x\nff]+(?![^(\\040)<>@,;:".\\\\\\[\\]\\000-\\037\\x80-\\xff])|"[^\\\\\\x80-\\xff\\n\\015\n"]*(?:\\\\[^\\x80-\\xff][^\\\\\\x80-\\xff\\n\\015"]*)*")[\\040\\t]*(?:\\([^\\\\\\x80-\\\nxff\\n\\015()]*(?:(?:\\\\[^\\x80-\\xff]|\\([^\\\\\\x80-\\xff\\n\\015()]*(?:\\\\[^\\x80\n-\\xff][^\\\\\\x80-\\xff\\n\\015()]*)*\\))[^\\\\\\x80-\\xff\\n\\015()]*)*\\)[\\040\\t]*\n)*(?:\\.[\\040\\t]*(?:\\([^\\\\\\x80-\\xff\\n\\015()]*(?:(?:\\\\[^\\x80-\\xff]|\\([^\\\n\\\\x80-\\xff\\n\\015()]*(?:\\\\[^\\x80-\\xff][^\\\\\\x80-\\xff\\n\\015()]*)*\\))[^\\\\\\\nx80-\\xff\\n\\015()]*)*\\)[\\040\\t]*)*(?:[^(\\040)<>@,;:".\\\\\\[\\]\\000-\\037\\x8\n0-\\xff]+(?![^(\\040)<>@,;:".\\\\\\[\\]\\000-\\037\\x80-\\xff])|"[^\\\\\\x80-\\xff\\n\n\\015"]*(?:\\\\[^\\x80-\\xff][^\\\\\\x80-\\xff\\n\\015"]*)*")[\\040\\t]*(?:\\([^\\\\\\x\n80-\\xff\\n\\015()]*(?:(?:\\\\[^\\x80-\\xff]|\\([^\\\\\\x80-\\xff\\n\\015()]*(?:\\\\[^\n\\x80-\\xff][^\\\\\\x80-\\xff\\n\\015()]*)*\\))[^\\\\\\x80-\\xff\\n\\015()]*)*\\)[\\040\n\\t]*)*)*@[\\040\\t]*(?:\\([^\\\\\\x80-\\xff\\n\\015()]*(?:(?:\\\\[^\\x80-\\xff]|\\([\n^\\\\\\x80-\\xff\\n\\015()]*(?:\\\\[^\\x80-\\xff][^\\\\\\x80-\\xff\\n\\015()]*)*\\))[^\\\n\\\\x80-\\xff\\n\\015()]*)*\\)[\\040\\t]*)*(?:[^(\\040)<>@,;:".\\\\\\[\\]\\000-\\037\\\nx80-\\xff]+(?![^(\\040)<>@,;:".\\\\\\[\\]\\000-\\037\\x80-\\xff])|\\[(?:[^\\\\\\x80-\n\\xff\\n\\015\\[\\]]|\\\\[^\\x80-\\xff])*\\])[\\040\\t]*(?:\\([^\\\\\\x80-\\xff\\n\\015()\n]*(?:(?:\\\\[^\\x80-\\xff]|\\([^\\\\\\x80-\\xff\\n\\015()]*(?:\\\\[^\\x80-\\xff][^\\\\\\\nx80-\\xff\\n\\015()]*)*\\))[^\\\\\\x80-\\xff\\n\\015()]*)*\\)[\\040\\t]*)*(?:\\.[\\04\n0\\t]*(?:\\([^\\\\\\x80-\\xff\\n\\015()]*(?:(?:\\\\[^\\x80-\\xff]|\\([^\\\\\\x80-\\xff\\\nn\\015()]*(?:\\\\[^\\x80-\\xff][^\\\\\\x80-\\xff\\n\\015()]*)*\\))[^\\\\\\x80-\\xff\\n\\\n015()]*)*\\)[\\040\\t]*)*(?:[^(\\040)<>@,;:".\\\\\\[\\]\\000-\\037\\x80-\\xff]+(?!\n[^(\\040)<>@,;:".\\\\\\[\\]\\000-\\037\\x80-\\xff])|\\[(?:[^\\\\\\x80-\\xff\\n\\015\\[\\\n]]|\\\\[^\\x80-\\xff])*\\])[\\040\\t]*(?:\\([^\\\\\\x80-\\xff\\n\\015()]*(?:(?:\\\\[^\\\nx80-\\xff]|\\([^\\\\\\x80-\\xff\\n\\015()]*(?:\\\\[^\\x80-\\xff][^\\\\\\x80-\\xff\\n\\01\n5()]*)*\\))[^\\\\\\x80-\\xff\\n\\015()]*)*\\)[\\040\\t]*)*)*|(?:[^(\\040)<>@,;:".\n\\\\\\[\\]\\000-\\037\\x80-\\xff]+(?![^(\\040)<>@,;:".\\\\\\[\\]\\000-\\037\\x80-\\xff]\n)|"[^\\\\\\x80-\\xff\\n\\015"]*(?:\\\\[^\\x80-\\xff][^\\\\\\x80-\\xff\\n\\015"]*)*")[^\n()<>@,;:".\\\\\\[\\]\\x80-\\xff\\000-\\010\\012-\\037]*(?:(?:\\([^\\\\\\x80-\\xff\\n\\0\n15()]*(?:(?:\\\\[^\\x80-\\xff]|\\([^\\\\\\x80-\\xff\\n\\015()]*(?:\\\\[^\\x80-\\xff][\n^\\\\\\x80-\\xff\\n\\015()]*)*\\))[^\\\\\\x80-\\xff\\n\\015()]*)*\\)|"[^\\\\\\x80-\\xff\\\nn\\015"]*(?:\\\\[^\\x80-\\xff][^\\\\\\x80-\\xff\\n\\015"]*)*")[^()<>@,;:".\\\\\\[\\]\\\nx80-\\xff\\000-\\010\\012-\\037]*)*<[\\040\\t]*(?:\\([^\\\\\\x80-\\xff\\n\\015()]*(?\n:(?:\\\\[^\\x80-\\xff]|\\([^\\\\\\x80-\\xff\\n\\015()]*(?:\\\\[^\\x80-\\xff][^\\\\\\x80-\n\\xff\\n\\015()]*)*\\))[^\\\\\\x80-\\xff\\n\\015()]*)*\\)[\\040\\t]*)*(?:@[\\040\\t]*\n(?:\\([^\\\\\\x80-\\xff\\n\\015()]*(?:(?:\\\\[^\\x80-\\xff]|\\([^\\\\\\x80-\\xff\\n\\015\n()]*(?:\\\\[^\\x80-\\xff][^\\\\\\x80-\\xff\\n\\015()]*)*\\))[^\\\\\\x80-\\xff\\n\\015()\n]*)*\\)[\\040\\t]*)*(?:[^(\\040)<>@,;:".\\\\\\[\\]\\000-\\037\\x80-\\xff]+(?![^(\\0\n40)<>@,;:".\\\\\\[\\]\\000-\\037\\x80-\\xff])|\\[(?:[^\\\\\\x80-\\xff\\n\\015\\[\\]]|\\\\\n[^\\x80-\\xff])*\\])[\\040\\t]*(?:\\([^\\\\\\x80-\\xff\\n\\015()]*(?:(?:\\\\[^\\x80-\\\nxff]|\\([^\\\\\\x80-\\xff\\n\\015()]*(?:\\\\[^\\x80-\\xff][^\\\\\\x80-\\xff\\n\\015()]*\n)*\\))[^\\\\\\x80-\\xff\\n\\015()]*)*\\)[\\040\\t]*)*(?:\\.[\\040\\t]*(?:\\([^\\\\\\x80\n-\\xff\\n\\015()]*(?:(?:\\\\[^\\x80-\\xff]|\\([^\\\\\\x80-\\xff\\n\\015()]*(?:\\\\[^\\x\n80-\\xff][^\\\\\\x80-\\xff\\n\\015()]*)*\\))[^\\\\\\x80-\\xff\\n\\015()]*)*\\)[\\040\\t\n]*)*(?:[^(\\040)<>@,;:".\\\\\\[\\]\\000-\\037\\x80-\\xff]+(?![^(\\040)<>@,;:".\\\\\n\\[\\]\\000-\\037\\x80-\\xff])|\\[(?:[^\\\\\\x80-\\xff\\n\\015\\[\\]]|\\\\[^\\x80-\\xff])\n*\\])[\\040\\t]*(?:\\([^\\\\\\x80-\\xff\\n\\015()]*(?:(?:\\\\[^\\x80-\\xff]|\\([^\\\\\\x\n80-\\xff\\n\\015()]*(?:\\\\[^\\x80-\\xff][^\\\\\\x80-\\xff\\n\\015()]*)*\\))[^\\\\\\x80\n-\\xff\\n\\015()]*)*\\)[\\040\\t]*)*)*(?:,[\\040\\t]*(?:\\([^\\\\\\x80-\\xff\\n\\015(\n)]*(?:(?:\\\\[^\\x80-\\xff]|\\([^\\\\\\x80-\\xff\\n\\015()]*(?:\\\\[^\\x80-\\xff][^\\\\\n\\x80-\\xff\\n\\015()]*)*\\))[^\\\\\\x80-\\xff\\n\\015()]*)*\\)[\\040\\t]*)*@[\\040\\t\n]*(?:\\([^\\\\\\x80-\\xff\\n\\015()]*(?:(?:\\\\[^\\x80-\\xff]|\\([^\\\\\\x80-\\xff\\n\\0\n15()]*(?:\\\\[^\\x80-\\xff][^\\\\\\x80-\\xff\\n\\015()]*)*\\))[^\\\\\\x80-\\xff\\n\\015\n()]*)*\\)[\\040\\t]*)*(?:[^(\\040)<>@,;:".\\\\\\[\\]\\000-\\037\\x80-\\xff]+(?![^(\n\\040)<>@,;:".\\\\\\[\\]\\000-\\037\\x80-\\xff])|\\[(?:[^\\\\\\x80-\\xff\\n\\015\\[\\]]|\n\\\\[^\\x80-\\xff])*\\])[\\040\\t]*(?:\\([^\\\\\\x80-\\xff\\n\\015()]*(?:(?:\\\\[^\\x80\n-\\xff]|\\([^\\\\\\x80-\\xff\\n\\015()]*(?:\\\\[^\\x80-\\xff][^\\\\\\x80-\\xff\\n\\015()\n]*)*\\))[^\\\\\\x80-\\xff\\n\\015()]*)*\\)[\\040\\t]*)*(?:\\.[\\040\\t]*(?:\\([^\\\\\\x\n80-\\xff\\n\\015()]*(?:(?:\\\\[^\\x80-\\xff]|\\([^\\\\\\x80-\\xff\\n\\015()]*(?:\\\\[^\n\\x80-\\xff][^\\\\\\x80-\\xff\\n\\015()]*)*\\))[^\\\\\\x80-\\xff\\n\\015()]*)*\\)[\\040\n\\t]*)*(?:[^(\\040)<>@,;:".\\\\\\[\\]\\000-\\037\\x80-\\xff]+(?![^(\\040)<>@,;:".\n\\\\\\[\\]\\000-\\037\\x80-\\xff])|\\[(?:[^\\\\\\x80-\\xff\\n\\015\\[\\]]|\\\\[^\\x80-\\xff\n])*\\])[\\040\\t]*(?:\\([^\\\\\\x80-\\xff\\n\\015()]*(?:(?:\\\\[^\\x80-\\xff]|\\([^\\\\\n\\x80-\\xff\\n\\015()]*(?:\\\\[^\\x80-\\xff][^\\\\\\x80-\\xff\\n\\015()]*)*\\))[^\\\\\\x\n80-\\xff\\n\\015()]*)*\\)[\\040\\t]*)*)*)*:[\\040\\t]*(?:\\([^\\\\\\x80-\\xff\\n\\015\n()]*(?:(?:\\\\[^\\x80-\\xff]|\\([^\\\\\\x80-\\xff\\n\\015()]*(?:\\\\[^\\x80-\\xff][^\\\n\\\\x80-\\xff\\n\\015()]*)*\\))[^\\\\\\x80-\\xff\\n\\015()]*)*\\)[\\040\\t]*)*)?(?:[^\n(\\040)<>@,;:".\\\\\\[\\]\\000-\\037\\x80-\\xff]+(?![^(\\040)<>@,;:".\\\\\\[\\]\\000-\n\\037\\x80-\\xff])|"[^\\\\\\x80-\\xff\\n\\015"]*(?:\\\\[^\\x80-\\xff][^\\\\\\x80-\\xff\\\nn\\015"]*)*")[\\040\\t]*(?:\\([^\\\\\\x80-\\xff\\n\\015()]*(?:(?:\\\\[^\\x80-\\xff]|\n\\([^\\\\\\x80-\\xff\\n\\015()]*(?:\\\\[^\\x80-\\xff][^\\\\\\x80-\\xff\\n\\015()]*)*\\))\n[^\\\\\\x80-\\xff\\n\\015()]*)*\\)[\\040\\t]*)*(?:\\.[\\040\\t]*(?:\\([^\\\\\\x80-\\xff\n\\n\\015()]*(?:(?:\\\\[^\\x80-\\xff]|\\([^\\\\\\x80-\\xff\\n\\015()]*(?:\\\\[^\\x80-\\x\nff][^\\\\\\x80-\\xff\\n\\015()]*)*\\))[^\\\\\\x80-\\xff\\n\\015()]*)*\\)[\\040\\t]*)*(\n?:[^(\\040)<>@,;:".\\\\\\[\\]\\000-\\037\\x80-\\xff]+(?![^(\\040)<>@,;:".\\\\\\[\\]\\\n000-\\037\\x80-\\xff])|"[^\\\\\\x80-\\xff\\n\\015"]*(?:\\\\[^\\x80-\\xff][^\\\\\\x80-\\\nxff\\n\\015"]*)*")[\\040\\t]*(?:\\([^\\\\\\x80-\\xff\\n\\015()]*(?:(?:\\\\[^\\x80-\\x\nff]|\\([^\\\\\\x80-\\xff\\n\\015()]*(?:\\\\[^\\x80-\\xff][^\\\\\\x80-\\xff\\n\\015()]*)\n*\\))[^\\\\\\x80-\\xff\\n\\015()]*)*\\)[\\040\\t]*)*)*@[\\040\\t]*(?:\\([^\\\\\\x80-\\x\nff\\n\\015()]*(?:(?:\\\\[^\\x80-\\xff]|\\([^\\\\\\x80-\\xff\\n\\015()]*(?:\\\\[^\\x80-\n\\xff][^\\\\\\x80-\\xff\\n\\015()]*)*\\))[^\\\\\\x80-\\xff\\n\\015()]*)*\\)[\\040\\t]*)\n*(?:[^(\\040)<>@,;:".\\\\\\[\\]\\000-\\037\\x80-\\xff]+(?![^(\\040)<>@,;:".\\\\\\[\\\n]\\000-\\037\\x80-\\xff])|\\[(?:[^\\\\\\x80-\\xff\\n\\015\\[\\]]|\\\\[^\\x80-\\xff])*\\]\n)[\\040\\t]*(?:\\([^\\\\\\x80-\\xff\\n\\015()]*(?:(?:\\\\[^\\x80-\\xff]|\\([^\\\\\\x80-\n\\xff\\n\\015()]*(?:\\\\[^\\x80-\\xff][^\\\\\\x80-\\xff\\n\\015()]*)*\\))[^\\\\\\x80-\\x\nff\\n\\015()]*)*\\)[\\040\\t]*)*(?:\\.[\\040\\t]*(?:\\([^\\\\\\x80-\\xff\\n\\015()]*(\n?:(?:\\\\[^\\x80-\\xff]|\\([^\\\\\\x80-\\xff\\n\\015()]*(?:\\\\[^\\x80-\\xff][^\\\\\\x80\n-\\xff\\n\\015()]*)*\\))[^\\\\\\x80-\\xff\\n\\015()]*)*\\)[\\040\\t]*)*(?:[^(\\040)<\n>@,;:".\\\\\\[\\]\\000-\\037\\x80-\\xff]+(?![^(\\040)<>@,;:".\\\\\\[\\]\\000-\\037\\x8\n0-\\xff])|\\[(?:[^\\\\\\x80-\\xff\\n\\015\\[\\]]|\\\\[^\\x80-\\xff])*\\])[\\040\\t]*(?:\n\\([^\\\\\\x80-\\xff\\n\\015()]*(?:(?:\\\\[^\\x80-\\xff]|\\([^\\\\\\x80-\\xff\\n\\015()]\n*(?:\\\\[^\\x80-\\xff][^\\\\\\x80-\\xff\\n\\015()]*)*\\))[^\\\\\\x80-\\xff\\n\\015()]*)\n*\\)[\\040\\t]*)*)*>)\nEOF\n</code></pre>\n"
},
{
"answer_id": 2932811,
"author": "Eric Schoonover",
"author_id": 3957,
"author_profile": "https://Stackoverflow.com/users/3957",
"pm_score": 5,
"selected": false,
"text": "<p>For the most comprehensive evaluation of the best regular expression for validating an email address please see this link; \"<a href=\"http://fightingforalostcause.net/misc/2006/compare-email-regex.php\" rel=\"noreferrer\">Comparing E-mail Address Validating Regular Expressions</a>\"</p>\n\n<p>Here is the current top expression for reference purposes:</p>\n\n<pre><code>/^([\\w\\!\\#$\\%\\&\\'\\*\\+\\-\\/\\=\\?\\^\\`{\\|\\}\\~]+\\.)*[\\w\\!\\#$\\%\\&\\'\\*\\+\\-\\/\\=\\?\\^\\`{\\|\\}\\~]+@((((([a-z0-9]{1}[a-z0-9\\-]{0,62}[a-z0-9]{1})|[a-z])\\.)+[a-z]{2,6})|(\\d{1,3}\\.){3}\\d{1,3}(\\:\\d{1,5})?)$/i\n</code></pre>\n"
},
{
"answer_id": 4554294,
"author": "AZ_",
"author_id": 185022,
"author_profile": "https://Stackoverflow.com/users/185022",
"pm_score": 4,
"selected": false,
"text": "<p>According to the official standard, <a href=\"https://www.rfc-editor.org/rfc/rfc2822#section-3.4.1\" rel=\"nofollow noreferrer\">RFC 2822</a>, a valid email regex is:</p>\n<pre class=\"lang-none prettyprint-override\"><code>(?:[a-z0-9!#$%&'*+/=?^_`{|}~-]+(?:\\.[a-z0-9!#$%&'*+/=?^_`{|}~-]+)*|"(?:[\\x01-\\x08\\x0b\\x0c\\x0e-\\x1f\\x21\\x23-\\x5b\\x5d-\\x7f]|\\\\[\\x01-\\x09\\x0b\\x0c\\x0e-\\x7f])*")@(?:(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\\.)+[a-z0-9](?:[a-z0-9-]*[a-z0-9])?|\\[(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\\.){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?|[a-z0-9-]*[a-z0-9]:(?:[\\x01-\\x08\\x0b\\x0c\\x0e-\\x1f\\x21-\\x5a\\x53-\\x7f]|\\\\[\\x01-\\x09\\x0b\\x0c\\x0e-\\x7f])+)\\])\n</code></pre>\n<p>If you want to use it in Java, it's really very easy:</p>\n<pre><code>import java.util.regex.*;\n\nclass regexSample \n{\n public static void main(String args[]) \n {\n //Input the string for validation\n String email = "[email protected]";\n\n //Set the email pattern string\n Pattern p = Pattern.compile(" (?:[a-z0-9!#$%&'*+/=?^_`{|}~-]+(?:\\\\.[a-z0-9!#$%&'*+/=?^_`{|}~-]+)*|"\n +"(?:[\\\\x01-\\\\x08\\\\x0b\\\\x0c\\\\x0e-\\\\x1f\\\\x21\\\\x23-\\\\x5b\\\\x5d-\\\\x7f]|\\\\[\\\\x01-\\\\x09\\\\x0b\\\\x0c\\\\x0e-\\\\x7f])*\\")"\n + "@(?:(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\\\\.)+[a-z0-9](?:[a-z0-9-]*[a-z0-9])?|\\\\[(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\\\\.){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?|[a-z0-9-]*[a-z0-9]:(?:[\\\\x01-\\\\x08\\\\x0b\\\\x0c\\\\x0e-\\\\x1f\\\\x21-\\\\x5a\\\\x53-\\\\x7f]|\\\\[\\\\x01-\\\\x09\\\\x0b\\\\x0c\\\\x0e-\\\\x7f])+)\\\\]");\n\n //Match the given string with the pattern\n Matcher m = p.matcher(email);\n\n //Check whether match is found \n boolean matchFound = m.matches();\n\n if (matchFound)\n System.out.println("Valid Email Id.");\n else\n System.out.println("Invalid Email Id.");\n }\n}\n</code></pre>\n"
},
{
"answer_id": 6756736,
"author": "Mac",
"author_id": 406196,
"author_profile": "https://Stackoverflow.com/users/406196",
"pm_score": 4,
"selected": false,
"text": "<p>Here's the PHP code I use. I've chosen this solution in the spirit of "false positives are better than false negatives" as declared by another commenter here <em>and</em> with regards to keeping your response time up and server load down ... there's really no need to waste server resources with a regular expression when this will weed out most simple user errors. You can always follow this up by sending a test email if you want.</p>\n<pre><code>function validateEmail($email) {\n return (bool) stripos($email,'@');\n}\n</code></pre>\n"
},
{
"answer_id": 6908269,
"author": "Murthy Jeedigunta",
"author_id": 874032,
"author_profile": "https://Stackoverflow.com/users/874032",
"pm_score": 3,
"selected": false,
"text": "<pre><code>public bool ValidateEmail(string sEmail)\n{\n if (sEmail == null)\n {\n return false;\n }\n\n int nFirstAT = sEmail.IndexOf('@');\n int nLastAT = sEmail.LastIndexOf('@');\n\n if ((nFirstAT > 0) && (nLastAT == nFirstAT) && (nFirstAT < (sEmail.Length - 1)))\n {\n return (Regex.IsMatch(sEmail, @\"^[a-z|0-9|A-Z]*([_][a-z|0-9|A-Z]+)*([.][a-z|0-9|A-Z]+)*([.][a-z|0-9|A-Z]+)*(([_][a-z|0-9|A-Z]+)*)?@[a-z][a-z|0-9|A-Z]*\\.([a-z][a-z|0-9|A-Z]*(\\.[a-z][a-z|0-9|A-Z]*)?)$\"));\n }\n else\n {\n return false;\n }\n}\n</code></pre>\n"
},
{
"answer_id": 6954888,
"author": "grosser",
"author_id": 110333,
"author_profile": "https://Stackoverflow.com/users/110333",
"pm_score": 2,
"selected": false,
"text": "<p>This rule matches what our <a href=\"https://en.wikipedia.org/wiki/Postfix_(software)\" rel=\"nofollow noreferrer\">Postfix</a> server could not send to.</p>\n<p>Allow letters, numbers, -, _, +, ., &, /, and !</p>\n<p>No [email protected]</p>\n<p>No [email protected]</p>\n<pre><code>/^([a-z0-9\\+\\._\\/&!][-a-z0-9\\+\\._\\/&!]*)@(([a-z0-9][-a-z0-9]*\\.)([-a-z0-9]+\\.)*[a-z]{2,})$/i\n</code></pre>\n"
},
{
"answer_id": 8014127,
"author": "Hans-Peter Störr",
"author_id": 21499,
"author_profile": "https://Stackoverflow.com/users/21499",
"pm_score": 2,
"selected": false,
"text": "<p>I would not suggest to use an regex at all - email addresses are way too complicated for that. This is a common problem so I would guess there are many libraries that contain a validator - if you use Java the <a href=\"http://commons.apache.org/validator/apidocs/org/apache/commons/validator/EmailValidator.html\" rel=\"nofollow\">EmailValidator</a> of <a href=\"http://commons.apache.org/validator/\" rel=\"nofollow\">apache commons validator</a> is a good one.</p>\n"
},
{
"answer_id": 8587017,
"author": "SimonSimCity",
"author_id": 517914,
"author_profile": "https://Stackoverflow.com/users/517914",
"pm_score": 6,
"selected": false,
"text": "<p>As you're writing in PHP I'd advice you to use the PHP built-in validation for emails.</p>\n<pre><code>filter_var($value, FILTER_VALIDATE_EMAIL)\n</code></pre>\n<p>If you're running a PHP version lower than 5.3.6, please be aware of this issue: <em><a href=\"https://bugs.php.net/bug.php?id=53091\" rel=\"nofollow noreferrer\">Bug #53091: Crashes when I try to filter a text of > 2264 characters</a></em></p>\n<p>If you want more information how this built-in validation works, see here: <em><a href=\"https://stackoverflow.com/questions/3722831/does-phps-filter-var-filter-validate-email-actually-work\">Does PHP's filter_var FILTER_VALIDATE_EMAIL actually work?</a></em></p>\n"
},
{
"answer_id": 8829363,
"author": "Josh Stodola",
"author_id": 54420,
"author_profile": "https://Stackoverflow.com/users/54420",
"pm_score": 8,
"selected": false,
"text": "<p>Per <a href=\"http://www.w3.org/TR/html5/forms.html#valid-e-mail-address\" rel=\"noreferrer\">the W3C HTML5 specification</a>:</p>\n<pre class=\"lang-none prettyprint-override\"><code>^[a-zA-Z0-9.!#$%&'*+/=?^_`{|}~-]+@[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\\.[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)*$\n</code></pre>\n<p>Context:</p>\n<blockquote>\n<p>A <strong>valid e-mail address</strong> is a string that matches the ABNF production […].</p>\n<p><i>Note: This requirement is a <a href=\"http://www.w3.org/TR/html5/introduction.html#willful-violation\" rel=\"noreferrer\">willful violation</a> of <a href=\"https://www.rfc-editor.org/rfc/rfc5322\" rel=\"noreferrer\">RFC 5322</a>, which defines a syntax for e-mail addresses that is simultaneously too strict (before the “@” character), too vague (after the “@” character), and too lax (allowing comments, whitespace characters, and quoted strings in manners unfamiliar to most users) to be of practical use here.</i></p>\n<p><i>The following JavaScript- and Perl-compatible regular expression is an implementation of the above definition.</p>\n<pre class=\"lang-none prettyprint-override\"><code>/^[a-zA-Z0-9.!#$%&'*+\\/=?^_`{|}~-]+@[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\\.[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)*$/\n</code></pre>\n</i>\n</blockquote>\n"
},
{
"answer_id": 10362389,
"author": "Prasad",
"author_id": 318244,
"author_profile": "https://Stackoverflow.com/users/318244",
"pm_score": 3,
"selected": false,
"text": "<p>If you are fine with accepting empty values (which is not an invalid email) and are running PHP 5.2+, I would suggest:</p>\n<pre><code>static public function checkEmail($email, $ignore_empty = false) {\n if($ignore_empty && (is_null($email) || $email == ''))\n return true;\n return filter_var($email, FILTER_VALIDATE_EMAIL);\n}\n</code></pre>\n"
},
{
"answer_id": 13666913,
"author": "TombMedia",
"author_id": 112397,
"author_profile": "https://Stackoverflow.com/users/112397",
"pm_score": 3,
"selected": false,
"text": "<p>I've been using this touched up version of the OP's regex for a while and it hasn't left me with too many surprises. <strike>I've never encountered an apostrophe in an email yet so it doesn't validate that</strike>. It does validate <code>Jean+Franç[email protected]</code> and <code>试@例子.测试.مثال.آزمایشی</code>, but not weird abuse of those non alphanumeric characters <code>[email protected]</code>.</p>\n<pre class=\"lang-none prettyprint-override\"><code>(?!^[.+&'_-]*@.*$)(^[_\\w\\d+&'-]+(\\.[_\\w\\d+&'-]*)*@[\\w\\d-]+(\\.[\\w\\d-]+)*\\.(([\\d]{1,3})|([\\w]{2,}))$)\n</code></pre>\n<p>It does support IP addresses <code>[email protected]</code>, but I haven't refined it enough to deal with bogus IP address ranges such as <code>999.999.999.1</code>.</p>\n<p><strike>It also supports all the TLDs over three characters which stops <code>[email protected]</code> which I think the original let through.</strike> <a href=\"http://data.iana.org/TLD/tlds-alpha-by-domain.txt\" rel=\"nofollow noreferrer\">I've been beat, there are too many TLDs now over 3 characters</a>.</p>\n<p>I know the OP has abandoned his regex, but this flavour lives on.</p>\n"
},
{
"answer_id": 14075810,
"author": "Rinke",
"author_id": 942671,
"author_profile": "https://Stackoverflow.com/users/942671",
"pm_score": 7,
"selected": false,
"text": "<h1>Quick answer</h1>\n<p>Use the following regex for input validation:</p>\n<p><code>([-!#-'*+/-9=?A-Z^-~]+(\\.[-!#-'*+/-9=?A-Z^-~]+)*|"([]!#-[^-~ \\t]|(\\\\[\\t -~]))+")@[0-9A-Za-z]([0-9A-Za-z-]{0,61}[0-9A-Za-z])?(\\.[0-9A-Za-z]([0-9A-Za-z-]{0,61}[0-9A-Za-z])?)+</code></p>\n<p>Addresses matched by this regex:</p>\n<ul>\n<li>have a local part (i.e. the part before the @-sign) that is strictly compliant with RFC 5321/5322,</li>\n<li>have a domain part (i.e. the part after the @-sign) that is a host name with at least two labels, each of which is at most 63 characters long.</li>\n</ul>\n<p>The second constraint is a restriction on RFC 5321/5322.</p>\n<h1>Elaborate answer</h1>\n<p>Using a regular expression that recognizes email addresses could be useful in various situations: for example to scan for email addresses in a document, to validate user input, or as an integrity constraint on a data repository.</p>\n<p>It should however be noted that if you want to find out if the address actually refers to an existing mailbox, there's no substitute for sending a message to the address. If you only want to check if an address is grammatically correct then you could use a regular expression, but note that <code>""@[]</code> is a grammatically correct email address that certainly doesn't refer to an existing mailbox.</p>\n<p>The syntax of email addresses has been defined in various <a href=\"http://en.wikipedia.org/wiki/Request_for_Comments\" rel=\"nofollow noreferrer\">RFCs</a>, most notably <a href=\"https://www.rfc-editor.org/rfc/rfc822\" rel=\"nofollow noreferrer\">RFC 822</a> and <a href=\"https://www.rfc-editor.org/rfc/rfc5322\" rel=\"nofollow noreferrer\">RFC 5322</a>. RFC 822 should be seen as the "original" standard and RFC 5322 as the latest standard. The syntax defined in RFC 822 is the most lenient and subsequent standards have restricted the syntax further and further, where newer systems or services should recognize obsolete syntax, but never produce it.</p>\n<p>In this answer I’ll take “email address” to mean <code>addr-spec</code> as defined in the RFCs (i.e. <code>[email protected]</code>, but not <code>"John Doe"<[email protected]></code>, nor <code>some-group:[email protected],[email protected];</code>).</p>\n<p>There's one problem with translating the RFC syntaxes into regexes: the syntaxes are not regular! This is because they allow for optional comments in email addresses that can be infinitely nested, while infinite nesting can't be described by a regular expression. To scan for or validate addresses containing comments you need a parser or more powerful expressions. (Note that languages like Perl have constructs to describe context free grammars in a regex-like way.) In this answer I'll disregard comments and only consider proper regular expressions.</p>\n<p>The RFCs define syntaxes for email messages, not for email addresses as such. Addresses may appear in various header fields and this is where they are primarily defined. When they appear in header fields addresses may contain (between lexical tokens) whitespace, comments and even linebreaks. Semantically this has no significance however. By removing this whitespace, etc. from an address you get a semantically equivalent <em>canonical representation</em>. Thus, the canonical representation of <code>first. last (comment) @ [3.5.7.9]</code> is <code>first.last@[3.5.7.9]</code>.</p>\n<p>Different syntaxes should be used for different purposes. If you want to scan for email addresses in a (possibly very old) document it may be a good idea to use the syntax as defined in RFC 822. On the other hand, if you want to validate user input you may want to use the syntax as defined in RFC 5322, probably only accepting canonical representations. You should decide which syntax applies to your specific case.</p>\n<p>I use POSIX "extended" regular expressions in this answer, assuming an ASCII compatible character set.</p>\n<h2>RFC 822</h2>\n<p>I arrived at the following regular expression. I invite everyone to try and break it. If you find any false positives or false negatives, please post them in a comment and I'll try to fix the expression as soon as possible.</p>\n<p><code>([^][()<>@,;:\\\\". \\x00-\\x1F\\x7F]+|"(\\n|(\\\\\\r)*([^"\\\\\\r\\n]|\\\\[^\\r]))*(\\\\\\r)*")(\\.([^][()<>@,;:\\\\". \\x00-\\x1F\\x7F]+|"(\\n|(\\\\\\r)*([^"\\\\\\r\\n]|\\\\[^\\r]))*(\\\\\\r)*"))*@([^][()<>@,;:\\\\". \\x00-\\x1F\\x7F]+|\\[(\\n|(\\\\\\r)*([^][\\\\\\r\\n]|\\\\[^\\r]))*(\\\\\\r)*])(\\.([^][()<>@,;:\\\\". \\x00-\\x1F\\x7F]+|\\[(\\n|(\\\\\\r)*([^][\\\\\\r\\n]|\\\\[^\\r]))*(\\\\\\r)*]))*</code></p>\n<p>I believe it's fully compliant with RFC 822 including the <a href=\"http://www.rfc-editor.org/errata_search.php?rfc=822\" rel=\"nofollow noreferrer\">errata</a>. It only recognizes email addresses in their canonical form. For a regex that recognizes (folding) whitespace see the derivation below.</p>\n<p>The derivation shows how I arrived at the expression. I list all the relevant grammar rules from the RFC exactly as they appear, followed by the corresponding regex. Where an erratum has been published I give a separate expression for the corrected grammar rule (marked "erratum") and use the updated version as a subexpression in subsequent regular expressions.</p>\n<p>As stated in paragraph 3.1.4. of RFC 822 optional linear white space may be inserted between lexical tokens. Where applicable I've expanded the expressions to accommodate this rule and marked the result with "opt-lwsp".</p>\n<pre class=\"lang-none prettyprint-override\"><code>CHAR = <any ASCII character>\n =~ .\n\nCTL = <any ASCII control character and DEL>\n =~ [\\x00-\\x1F\\x7F]\n\nCR = <ASCII CR, carriage return>\n =~ \\r\n\nLF = <ASCII LF, linefeed>\n =~ \\n\n\nSPACE = <ASCII SP, space>\n =~ \n\nHTAB = <ASCII HT, horizontal-tab>\n =~ \\t\n\n<"> = <ASCII quote mark>\n =~ "\n\nCRLF = CR LF\n =~ \\r\\n\n\nLWSP-char = SPACE / HTAB\n =~ [ \\t]\n\nlinear-white-space = 1*([CRLF] LWSP-char)\n =~ ((\\r\\n)?[ \\t])+\n\nspecials = "(" / ")" / "<" / ">" / "@" / "," / ";" / ":" / "\\" / <"> / "." / "[" / "]"\n =~ [][()<>@,;:\\\\".]\n\nquoted-pair = "\\" CHAR\n =~ \\\\.\n\nqtext = <any CHAR excepting <">, "\\" & CR, and including linear-white-space>\n =~ [^"\\\\\\r]|((\\r\\n)?[ \\t])+\n\ndtext = <any CHAR excluding "[", "]", "\\" & CR, & including linear-white-space>\n =~ [^][\\\\\\r]|((\\r\\n)?[ \\t])+\n\nquoted-string = <"> *(qtext|quoted-pair) <">\n =~ "([^"\\\\\\r]|((\\r\\n)?[ \\t])|\\\\.)*"\n(erratum) =~ "(\\n|(\\\\\\r)*([^"\\\\\\r\\n]|\\\\[^\\r]|(\\r\\n)?[ \\t]))*(\\\\\\r)*"\n\ndomain-literal = "[" *(dtext|quoted-pair) "]"\n =~ \\[([^][\\\\\\r]|((\\r\\n)?[ \\t])|\\\\.)*]\n(erratum) =~ \\[(\\n|(\\\\\\r)*([^][\\\\\\r\\n]|\\\\[^\\r]|(\\r\\n)?[ \\t]))*(\\\\\\r)*]\n\natom = 1*<any CHAR except specials, SPACE and CTLs>\n =~ [^][()<>@,;:\\\\". \\x00-\\x1F\\x7F]+\n\nword = atom / quoted-string\n =~ [^][()<>@,;:\\\\". \\x00-\\x1F\\x7F]+|"(\\n|(\\\\\\r)*([^"\\\\\\r\\n]|\\\\[^\\r]|(\\r\\n)?[ \\t]))*(\\\\\\r)*"\n\ndomain-ref = atom\n\nsub-domain = domain-ref / domain-literal\n =~ [^][()<>@,;:\\\\". \\x00-\\x1F\\x7F]+|\\[(\\n|(\\\\\\r)*([^][\\\\\\r\\n]|\\\\[^\\r]|(\\r\\n)?[ \\t]))*(\\\\\\r)*]\n\nlocal-part = word *("." word)\n =~ ([^][()<>@,;:\\\\". \\x00-\\x1F\\x7F]+|"(\\n|(\\\\\\r)*([^"\\\\\\r\\n]|\\\\[^\\r]|(\\r\\n)?[ \\t]))*(\\\\\\r)*")(\\.([^][()<>@,;:\\\\". \\x00-\\x1F\\x7F]+|"(\\n|(\\\\\\r)*([^"\\\\\\r\\n]|\\\\[^\\r]|(\\r\\n)?[ \\t]))*(\\\\\\r)*"))*\n(opt-lwsp) =~ ([^][()<>@,;:\\\\". \\x00-\\x1F\\x7F]+|"(\\n|(\\\\\\r)*([^"\\\\\\r\\n]|\\\\[^\\r]|(\\r\\n)?[ \\t]))*(\\\\\\r)*")(((\\r\\n)?[ \\t])*\\.((\\r\\n)?[ \\t])*([^][()<>@,;:\\\\". \\x00-\\x1F\\x7F]+|"(\\n|(\\\\\\r)*([^"\\\\\\r\\n]|\\\\[^\\r]|(\\r\\n)?[ \\t]))*(\\\\\\r)*"))*\n\ndomain = sub-domain *("." sub-domain)\n =~ ([^][()<>@,;:\\\\". \\x00-\\x1F\\x7F]+|\\[(\\n|(\\\\\\r)*([^][\\\\\\r\\n]|\\\\[^\\r]|(\\r\\n)?[ \\t]))*(\\\\\\r)*])(\\.([^][()<>@,;:\\\\". \\x00-\\x1F\\x7F]+|\\[(\\n|(\\\\\\r)*([^][\\\\\\r\\n]|\\\\[^\\r]|(\\r\\n)?[ \\t]))*(\\\\\\r)*]))*\n(opt-lwsp) =~ ([^][()<>@,;:\\\\". \\x00-\\x1F\\x7F]+|\\[(\\n|(\\\\\\r)*([^][\\\\\\r\\n]|\\\\[^\\r]|(\\r\\n)?[ \\t]))*(\\\\\\r)*])(((\\r\\n)?[ \\t])*\\.((\\r\\n)?[ \\t])*([^][()<>@,;:\\\\". \\x00-\\x1F\\x7F]+|\\[(\\n|(\\\\\\r)*([^][\\\\\\r\\n]|\\\\[^\\r]|(\\r\\n)?[ \\t]))*(\\\\\\r)*]))*\n\naddr-spec = local-part "@" domain\n =~ ([^][()<>@,;:\\\\". \\x00-\\x1F\\x7F]+|"(\\n|(\\\\\\r)*([^"\\\\\\r\\n]|\\\\[^\\r]|(\\r\\n)?[ \\t]))*(\\\\\\r)*")(\\.([^][()<>@,;:\\\\". \\x00-\\x1F\\x7F]+|"(\\n|(\\\\\\r)*([^"\\\\\\r\\n]|\\\\[^\\r]|(\\r\\n)?[ \\t]))*(\\\\\\r)*"))*@([^][()<>@,;:\\\\". \\x00-\\x1F\\x7F]+|\\[(\\n|(\\\\\\r)*([^][\\\\\\r\\n]|\\\\[^\\r]|(\\r\\n)?[ \\t]))*(\\\\\\r)*])(\\.([^][()<>@,;:\\\\". \\x00-\\x1F\\x7F]+|\\[(\\n|(\\\\\\r)*([^][\\\\\\r\\n]|\\\\[^\\r]|(\\r\\n)?[ \\t]))*(\\\\\\r)*]))*\n(opt-lwsp) =~ ([^][()<>@,;:\\\\". \\x00-\\x1F\\x7F]+|"(\\n|(\\\\\\r)*([^"\\\\\\r\\n]|\\\\[^\\r]|(\\r\\n)?[ \\t]))*(\\\\\\r)*")((\\r\\n)?[ \\t])*(\\.((\\r\\n)?[ \\t])*([^][()<>@,;:\\\\". \\x00-\\x1F\\x7F]+|"(\\n|(\\\\\\r)*([^"\\\\\\r\\n]|\\\\[^\\r]|(\\r\\n)?[ \\t]))*(\\\\\\r)*")((\\r\\n)?[ \\t])*)*@((\\r\\n)?[ \\t])*([^][()<>@,;:\\\\". \\x00-\\x1F\\x7F]+|\\[(\\n|(\\\\\\r)*([^][\\\\\\r\\n]|\\\\[^\\r]|(\\r\\n)?[ \\t]))*(\\\\\\r)*])(((\\r\\n)?[ \\t])*\\.((\\r\\n)?[ \\t])*([^][()<>@,;:\\\\". \\x00-\\x1F\\x7F]+|\\[(\\n|(\\\\\\r)*([^][\\\\\\r\\n]|\\\\[^\\r]|(\\r\\n)?[ \\t]))*(\\\\\\r)*]))*\n(canonical) =~ ([^][()<>@,;:\\\\". \\x00-\\x1F\\x7F]+|"(\\n|(\\\\\\r)*([^"\\\\\\r\\n]|\\\\[^\\r]))*(\\\\\\r)*")(\\.([^][()<>@,;:\\\\". \\x00-\\x1F\\x7F]+|"(\\n|(\\\\\\r)*([^"\\\\\\r\\n]|\\\\[^\\r]))*(\\\\\\r)*"))*@([^][()<>@,;:\\\\". \\x00-\\x1F\\x7F]+|\\[(\\n|(\\\\\\r)*([^][\\\\\\r\\n]|\\\\[^\\r]))*(\\\\\\r)*])(\\.([^][()<>@,;:\\\\". \\x00-\\x1F\\x7F]+|\\[(\\n|(\\\\\\r)*([^][\\\\\\r\\n]|\\\\[^\\r]))*(\\\\\\r)*]))*\n</code></pre>\n<h2>RFC 5322</h2>\n<p>I arrived at the following regular expression. I invite everyone to try and break it. If you find any false positives or false negatives, please post them in a comment and I'll try to fix the expression as soon as possible.</p>\n<p><code>([-!#-'*+/-9=?A-Z^-~]+(\\.[-!#-'*+/-9=?A-Z^-~]+)*|"([]!#-[^-~ \\t]|(\\\\[\\t -~]))+")@([-!#-'*+/-9=?A-Z^-~]+(\\.[-!#-'*+/-9=?A-Z^-~]+)*|\\[[\\t -Z^-~]*])</code></p>\n<p>I believe it's fully compliant with RFC 5322 including the <a href=\"http://www.rfc-editor.org/errata_search.php?rfc=5322\" rel=\"nofollow noreferrer\">errata</a>. It only recognizes email addresses in their canonical form. For a regex that recognizes (folding) whitespace see the derivation below.</p>\n<p>The derivation shows how I arrived at the expression. I list all the relevant grammar rules from the RFC exactly as they appear, followed by the corresponding regex. For rules that include semantically irrelevant (folding) whitespace, I give a separate regex marked "(normalized)" that doesn't accept this whitespace.</p>\n<p>I ignored all the "obs-" rules from the RFC. This means that the regexes only match email addresses that are strictly RFC 5322 compliant. If you have to match "old" addresses (as the looser grammar including the "obs-" rules does), you can use one of the RFC 822 regexes from the previous paragraph.</p>\n<pre class=\"lang-none prettyprint-override\"><code>VCHAR = %x21-7E\n =~ [!-~]\n\nALPHA = %x41-5A / %x61-7A\n =~ [A-Za-z]\n\nDIGIT = %x30-39\n =~ [0-9]\n\nHTAB = %x09\n =~ \\t\n\nCR = %x0D\n =~ \\r\n\nLF = %x0A\n =~ \\n\n\nSP = %x20\n =~ \n\nDQUOTE = %x22\n =~ "\n\nCRLF = CR LF\n =~ \\r\\n\n\nWSP = SP / HTAB\n =~ [\\t ]\n\nquoted-pair = "\\" (VCHAR / WSP)\n =~ \\\\[\\t -~]\n\nFWS = ([*WSP CRLF] 1*WSP)\n =~ ([\\t ]*\\r\\n)?[\\t ]+\n\nctext = %d33-39 / %d42-91 / %d93-126\n =~ []!-'*-[^-~]\n\n("comment" is left out in the regex)\nccontent = ctext / quoted-pair / comment\n =~ []!-'*-[^-~]|(\\\\[\\t -~])\n\n(not regular)\ncomment = "(" *([FWS] ccontent) [FWS] ")"\n\n(is equivalent to FWS when leaving out comments)\nCFWS = (1*([FWS] comment) [FWS]) / FWS\n =~ ([\\t ]*\\r\\n)?[\\t ]+\n\natext = ALPHA / DIGIT / "!" / "#" / "$" / "%" / "&" / "'" / "*" / "+" / "-" / "/" / "=" / "?" / "^" / "_" / "`" / "{" / "|" / "}" / "~"\n =~ [-!#-'*+/-9=?A-Z^-~]\n\ndot-atom-text = 1*atext *("." 1*atext)\n =~ [-!#-'*+/-9=?A-Z^-~]+(\\.[-!#-'*+/-9=?A-Z^-~]+)*\n\ndot-atom = [CFWS] dot-atom-text [CFWS]\n =~ (([\\t ]*\\r\\n)?[\\t ]+)?[-!#-'*+/-9=?A-Z^-~]+(\\.[-!#-'*+/-9=?A-Z^-~]+)*(([\\t ]*\\r\\n)?[\\t ]+)?\n(normalized) =~ [-!#-'*+/-9=?A-Z^-~]+(\\.[-!#-'*+/-9=?A-Z^-~]+)*\n\nqtext = %d33 / %d35-91 / %d93-126\n =~ []!#-[^-~]\n\nqcontent = qtext / quoted-pair\n =~ []!#-[^-~]|(\\\\[\\t -~])\n\n(erratum)\nquoted-string = [CFWS] DQUOTE ((1*([FWS] qcontent) [FWS]) / FWS) DQUOTE [CFWS]\n =~ (([\\t ]*\\r\\n)?[\\t ]+)?"(((([\\t ]*\\r\\n)?[\\t ]+)?([]!#-[^-~]|(\\\\[\\t -~])))+(([\\t ]*\\r\\n)?[\\t ]+)?|(([\\t ]*\\r\\n)?[\\t ]+)?)"(([\\t ]*\\r\\n)?[\\t ]+)?\n(normalized) =~ "([]!#-[^-~ \\t]|(\\\\[\\t -~]))+"\n\ndtext = %d33-90 / %d94-126\n =~ [!-Z^-~]\n\ndomain-literal = [CFWS] "[" *([FWS] dtext) [FWS] "]" [CFWS]\n =~ (([\\t ]*\\r\\n)?[\\t ]+)?\\[((([\\t ]*\\r\\n)?[\\t ]+)?[!-Z^-~])*(([\\t ]*\\r\\n)?[\\t ]+)?](([\\t ]*\\r\\n)?[\\t ]+)?\n(normalized) =~ \\[[\\t -Z^-~]*]\n\nlocal-part = dot-atom / quoted-string\n =~ (([\\t ]*\\r\\n)?[\\t ]+)?[-!#-'*+/-9=?A-Z^-~]+(\\.[-!#-'*+/-9=?A-Z^-~]+)*(([\\t ]*\\r\\n)?[\\t ]+)?|(([\\t ]*\\r\\n)?[\\t ]+)?"(((([\\t ]*\\r\\n)?[\\t ]+)?([]!#-[^-~]|(\\\\[\\t -~])))+(([\\t ]*\\r\\n)?[\\t ]+)?|(([\\t ]*\\r\\n)?[\\t ]+)?)"(([\\t ]*\\r\\n)?[\\t ]+)?\n(normalized) =~ [-!#-'*+/-9=?A-Z^-~]+(\\.[-!#-'*+/-9=?A-Z^-~]+)*|"([]!#-[^-~ \\t]|(\\\\[\\t -~]))+"\n\ndomain = dot-atom / domain-literal\n =~ (([\\t ]*\\r\\n)?[\\t ]+)?[-!#-'*+/-9=?A-Z^-~]+(\\.[-!#-'*+/-9=?A-Z^-~]+)*(([\\t ]*\\r\\n)?[\\t ]+)?|(([\\t ]*\\r\\n)?[\\t ]+)?\\[((([\\t ]*\\r\\n)?[\\t ]+)?[!-Z^-~])*(([\\t ]*\\r\\n)?[\\t ]+)?](([\\t ]*\\r\\n)?[\\t ]+)?\n(normalized) =~ [-!#-'*+/-9=?A-Z^-~]+(\\.[-!#-'*+/-9=?A-Z^-~]+)*|\\[[\\t -Z^-~]*]\n\naddr-spec = local-part "@" domain\n =~ ((([\\t ]*\\r\\n)?[\\t ]+)?[-!#-'*+/-9=?A-Z^-~]+(\\.[-!#-'*+/-9=?A-Z^-~]+)*(([\\t ]*\\r\\n)?[\\t ]+)?|(([\\t ]*\\r\\n)?[\\t ]+)?"(((([\\t ]*\\r\\n)?[\\t ]+)?([]!#-[^-~]|(\\\\[\\t -~])))+(([\\t ]*\\r\\n)?[\\t ]+)?|(([\\t ]*\\r\\n)?[\\t ]+)?)"(([\\t ]*\\r\\n)?[\\t ]+)?)@((([\\t ]*\\r\\n)?[\\t ]+)?[-!#-'*+/-9=?A-Z^-~]+(\\.[-!#-'*+/-9=?A-Z^-~]+)*(([\\t ]*\\r\\n)?[\\t ]+)?|(([\\t ]*\\r\\n)?[\\t ]+)?\\[((([\\t ]*\\r\\n)?[\\t ]+)?[!-Z^-~])*(([\\t ]*\\r\\n)?[\\t ]+)?](([\\t ]*\\r\\n)?[\\t ]+)?)\n(normalized) =~ ([-!#-'*+/-9=?A-Z^-~]+(\\.[-!#-'*+/-9=?A-Z^-~]+)*|"([]!#-[^-~ \\t]|(\\\\[\\t -~]))+")@([-!#-'*+/-9=?A-Z^-~]+(\\.[-!#-'*+/-9=?A-Z^-~]+)*|\\[[\\t -Z^-~]*])\n</code></pre>\n<p>Note that some sources (notably <a href=\"http://www.w3.org/TR/html5/forms.html#valid-e-mail-address\" rel=\"nofollow noreferrer\">W3C</a>) claim that RFC 5322 is too strict on the local part (i.e. the part before the @-sign). This is because "..", "a..b" and "a." are <em>not</em> valid dot-atoms, while they may be used as mailbox names. The RFC, however, <em>does</em> allow for local parts like these, except that they have to be quoted. So instead of <code>[email protected]</code> you should write <code>"a..b"@example.net</code>, which is semantically equivalent.</p>\n<h2>Further restrictions</h2>\n<p>SMTP (as defined in <a href=\"https://www.rfc-editor.org/rfc/rfc5321\" rel=\"nofollow noreferrer\">RFC 5321</a>) further restricts the set of valid email addresses (or actually: mailbox names). It seems reasonable to impose this stricter grammar, so that the matched email address can actually be used to send an email.</p>\n<p>RFC 5321 basically leaves alone the "local" part (i.e. the part before the @-sign), but is stricter on the domain part (i.e. the part after the @-sign). It allows only host names in place of dot-atoms and address literals in place of domain literals.</p>\n<p>The grammar presented in RFC 5321 is too lenient when it comes to both host names and IP addresses. I took the liberty of "correcting" the rules in question, using <a href=\"https://tools.ietf.org/id/draft-main-ipaddr-text-rep-01.txt\" rel=\"nofollow noreferrer\">this draft</a> and <a href=\"https://www.rfc-editor.org/rfc/rfc1034\" rel=\"nofollow noreferrer\">RFC 1034</a> as guidelines. Here's the resulting regex.</p>\n<p><code>([-!#-'*+/-9=?A-Z^-~]+(\\.[-!#-'*+/-9=?A-Z^-~]+)*|"([]!#-[^-~ \\t]|(\\\\[\\t -~]))+")@([0-9A-Za-z]([0-9A-Za-z-]{0,61}[0-9A-Za-z])?(\\.[0-9A-Za-z]([0-9A-Za-z-]{0,61}[0-9A-Za-z])?)*|\\[((25[0-5]|2[0-4][0-9]|1[0-9]{2}|[1-9]?[0-9])(\\.(25[0-5]|2[0-4][0-9]|1[0-9]{2}|[1-9]?[0-9])){3}|IPv6:((((0|[1-9A-Fa-f][0-9A-Fa-f]{0,3}):){6}|::((0|[1-9A-Fa-f][0-9A-Fa-f]{0,3}):){5}|[0-9A-Fa-f]{0,4}::((0|[1-9A-Fa-f][0-9A-Fa-f]{0,3}):){4}|(((0|[1-9A-Fa-f][0-9A-Fa-f]{0,3}):)?(0|[1-9A-Fa-f][0-9A-Fa-f]{0,3}))?::((0|[1-9A-Fa-f][0-9A-Fa-f]{0,3}):){3}|(((0|[1-9A-Fa-f][0-9A-Fa-f]{0,3}):){0,2}(0|[1-9A-Fa-f][0-9A-Fa-f]{0,3}))?::((0|[1-9A-Fa-f][0-9A-Fa-f]{0,3}):){2}|(((0|[1-9A-Fa-f][0-9A-Fa-f]{0,3}):){0,3}(0|[1-9A-Fa-f][0-9A-Fa-f]{0,3}))?::(0|[1-9A-Fa-f][0-9A-Fa-f]{0,3}):|(((0|[1-9A-Fa-f][0-9A-Fa-f]{0,3}):){0,4}(0|[1-9A-Fa-f][0-9A-Fa-f]{0,3}))?::)((0|[1-9A-Fa-f][0-9A-Fa-f]{0,3}):(0|[1-9A-Fa-f][0-9A-Fa-f]{0,3})|(25[0-5]|2[0-4][0-9]|1[0-9]{2}|[1-9]?[0-9])(\\.(25[0-5]|2[0-4][0-9]|1[0-9]{2}|[1-9]?[0-9])){3})|(((0|[1-9A-Fa-f][0-9A-Fa-f]{0,3}):){0,5}(0|[1-9A-Fa-f][0-9A-Fa-f]{0,3}))?::(0|[1-9A-Fa-f][0-9A-Fa-f]{0,3})|(((0|[1-9A-Fa-f][0-9A-Fa-f]{0,3}):){0,6}(0|[1-9A-Fa-f][0-9A-Fa-f]{0,3}))?::)|(?!IPv6:)[0-9A-Za-z-]*[0-9A-Za-z]:[!-Z^-~]+)])</code></p>\n<p>Note that depending on the use case you may not want to allow for a "General-address-literal" in your regex. Also note that I used a negative lookahead <code>(?!IPv6:)</code> in the final regex to prevent the "General-address-literal" part to match malformed IPv6 addresses. Some regex processors don't support negative lookahead. Remove the substring <code>|(?!IPv6:)[0-9A-Za-z-]*[0-9A-Za-z]:[!-Z^-~]+</code> from the regex if you want to take the whole "General-address-literal" part out.</p>\n<p>Here's the derivation:</p>\n<pre class=\"lang-none prettyprint-override\"><code>Let-dig = ALPHA / DIGIT\n =~ [0-9A-Za-z]\n\nLdh-str = *( ALPHA / DIGIT / "-" ) Let-dig\n =~ [0-9A-Za-z-]*[0-9A-Za-z]\n\n(regex is updated to make sure sub-domains are max. 63 characters long - RFC 1034 section 3.5)\nsub-domain = Let-dig [Ldh-str]\n =~ [0-9A-Za-z]([0-9A-Za-z-]{0,61}[0-9A-Za-z])?\n\nDomain = sub-domain *("." sub-domain)\n =~ [0-9A-Za-z]([0-9A-Za-z-]{0,61}[0-9A-Za-z])?(\\.[0-9A-Za-z]([0-9A-Za-z-]{0,61}[0-9A-Za-z])?)*\n\nSnum = 1*3DIGIT\n =~ [0-9]{1,3}\n\n(suggested replacement for "Snum")\nip4-octet = DIGIT / %x31-39 DIGIT / "1" 2DIGIT / "2" %x30-34 DIGIT / "25" %x30-35\n =~ 25[0-5]|2[0-4][0-9]|1[0-9]{2}|[1-9]?[0-9]\n\nIPv4-address-literal = Snum 3("." Snum)\n =~ [0-9]{1,3}(\\.[0-9]{1,3}){3}\n\n(suggested replacement for "IPv4-address-literal")\nip4-address = ip4-octet 3("." ip4-octet)\n =~ (25[0-5]|2[0-4][0-9]|1[0-9]{2}|[1-9]?[0-9])(\\.(25[0-5]|2[0-4][0-9]|1[0-9]{2}|[1-9]?[0-9])){3}\n\n(suggested replacement for "IPv6-hex")\nip6-h16 = "0" / ( (%x49-57 / %x65-70 /%x97-102) 0*3(%x48-57 / %x65-70 /%x97-102) )\n =~ 0|[1-9A-Fa-f][0-9A-Fa-f]{0,3}\n\n(not from RFC)\nls32 = ip6-h16 ":" ip6-h16 / ip4-address\n =~ (0|[1-9A-Fa-f][0-9A-Fa-f]{0,3}):(0|[1-9A-Fa-f][0-9A-Fa-f]{0,3})|(25[0-5]|2[0-4][0-9]|1[0-9]{2}|[1-9]?[0-9])(\\.(25[0-5]|2[0-4][0-9]|1[0-9]{2}|[1-9]?[0-9])){3}\n\n(suggested replacement of "IPv6-addr")\nip6-address = 6(ip6-h16 ":") ls32\n / "::" 5(ip6-h16 ":") ls32\n / [ ip6-h16 ] "::" 4(ip6-h16 ":") ls32\n / [ *1(ip6-h16 ":") ip6-h16 ] "::" 3(ip6-h16 ":") ls32\n / [ *2(ip6-h16 ":") ip6-h16 ] "::" 2(ip6-h16 ":") ls32\n / [ *3(ip6-h16 ":") ip6-h16 ] "::" ip6-h16 ":" ls32\n / [ *4(ip6-h16 ":") ip6-h16 ] "::" ls32\n / [ *5(ip6-h16 ":") ip6-h16 ] "::" ip6-h16\n / [ *6(ip6-h16 ":") ip6-h16 ] "::"\n =~ (((0|[1-9A-Fa-f][0-9A-Fa-f]{0,3}):){6}|::((0|[1-9A-Fa-f][0-9A-Fa-f]{0,3}):){5}|[0-9A-Fa-f]{0,4}::((0|[1-9A-Fa-f][0-9A-Fa-f]{0,3}):){4}|(((0|[1-9A-Fa-f][0-9A-Fa-f]{0,3}):)?(0|[1-9A-Fa-f][0-9A-Fa-f]{0,3}))?::((0|[1-9A-Fa-f][0-9A-Fa-f]{0,3}):){3}|(((0|[1-9A-Fa-f][0-9A-Fa-f]{0,3}):){0,2}(0|[1-9A-Fa-f][0-9A-Fa-f]{0,3}))?::((0|[1-9A-Fa-f][0-9A-Fa-f]{0,3}):){2}|(((0|[1-9A-Fa-f][0-9A-Fa-f]{0,3}):){0,3}(0|[1-9A-Fa-f][0-9A-Fa-f]{0,3}))?::(0|[1-9A-Fa-f][0-9A-Fa-f]{0,3}):|(((0|[1-9A-Fa-f][0-9A-Fa-f]{0,3}):){0,4}(0|[1-9A-Fa-f][0-9A-Fa-f]{0,3}))?::)((0|[1-9A-Fa-f][0-9A-Fa-f]{0,3}):(0|[1-9A-Fa-f][0-9A-Fa-f]{0,3})|(25[0-5]|2[0-4][0-9]|1[0-9]{2}|[1-9]?[0-9])(\\.(25[0-5]|2[0-4][0-9]|1[0-9]{2}|[1-9]?[0-9])){3})|(((0|[1-9A-Fa-f][0-9A-Fa-f]{0,3}):){0,5}(0|[1-9A-Fa-f][0-9A-Fa-f]{0,3}))?::(0|[1-9A-Fa-f][0-9A-Fa-f]{0,3})|(((0|[1-9A-Fa-f][0-9A-Fa-f]{0,3}):){0,6}(0|[1-9A-Fa-f][0-9A-Fa-f]{0,3}))?::\n\nIPv6-address-literal = "IPv6:" ip6-address\n =~ IPv6:((((0|[1-9A-Fa-f][0-9A-Fa-f]{0,3}):){6}|::((0|[1-9A-Fa-f][0-9A-Fa-f]{0,3}):){5}|[0-9A-Fa-f]{0,4}::((0|[1-9A-Fa-f][0-9A-Fa-f]{0,3}):){4}|(((0|[1-9A-Fa-f][0-9A-Fa-f]{0,3}):)?(0|[1-9A-Fa-f][0-9A-Fa-f]{0,3}))?::((0|[1-9A-Fa-f][0-9A-Fa-f]{0,3}):){3}|(((0|[1-9A-Fa-f][0-9A-Fa-f]{0,3}):){0,2}(0|[1-9A-Fa-f][0-9A-Fa-f]{0,3}))?::((0|[1-9A-Fa-f][0-9A-Fa-f]{0,3}):){2}|(((0|[1-9A-Fa-f][0-9A-Fa-f]{0,3}):){0,3}(0|[1-9A-Fa-f][0-9A-Fa-f]{0,3}))?::(0|[1-9A-Fa-f][0-9A-Fa-f]{0,3}):|(((0|[1-9A-Fa-f][0-9A-Fa-f]{0,3}):){0,4}(0|[1-9A-Fa-f][0-9A-Fa-f]{0,3}))?::)((0|[1-9A-Fa-f][0-9A-Fa-f]{0,3}):(0|[1-9A-Fa-f][0-9A-Fa-f]{0,3})|(25[0-5]|2[0-4][0-9]|1[0-9]{2}|[1-9]?[0-9])(\\.(25[0-5]|2[0-4][0-9]|1[0-9]{2}|[1-9]?[0-9])){3})|(((0|[1-9A-Fa-f][0-9A-Fa-f]{0,3}):){0,5}(0|[1-9A-Fa-f][0-9A-Fa-f]{0,3}))?::(0|[1-9A-Fa-f][0-9A-Fa-f]{0,3})|(((0|[1-9A-Fa-f][0-9A-Fa-f]{0,3}):){0,6}(0|[1-9A-Fa-f][0-9A-Fa-f]{0,3}))?::)\n\nStandardized-tag = Ldh-str\n =~ [0-9A-Za-z-]*[0-9A-Za-z]\n\ndcontent = %d33-90 / %d94-126\n =~ [!-Z^-~]\n\nGeneral-address-literal = Standardized-tag ":" 1*dcontent\n =~ [0-9A-Za-z-]*[0-9A-Za-z]:[!-Z^-~]+\n\naddress-literal = "[" ( IPv4-address-literal / IPv6-address-literal / General-address-literal ) "]"\n =~ \\[((25[0-5]|2[0-4][0-9]|1[0-9]{2}|[1-9]?[0-9])(\\.(25[0-5]|2[0-4][0-9]|1[0-9]{2}|[1-9]?[0-9])){3}|IPv6:((((0|[1-9A-Fa-f][0-9A-Fa-f]{0,3}):){6}|::((0|[1-9A-Fa-f][0-9A-Fa-f]{0,3}):){5}|[0-9A-Fa-f]{0,4}::((0|[1-9A-Fa-f][0-9A-Fa-f]{0,3}):){4}|(((0|[1-9A-Fa-f][0-9A-Fa-f]{0,3}):)?(0|[1-9A-Fa-f][0-9A-Fa-f]{0,3}))?::((0|[1-9A-Fa-f][0-9A-Fa-f]{0,3}):){3}|(((0|[1-9A-Fa-f][0-9A-Fa-f]{0,3}):){0,2}(0|[1-9A-Fa-f][0-9A-Fa-f]{0,3}))?::((0|[1-9A-Fa-f][0-9A-Fa-f]{0,3}):){2}|(((0|[1-9A-Fa-f][0-9A-Fa-f]{0,3}):){0,3}(0|[1-9A-Fa-f][0-9A-Fa-f]{0,3}))?::(0|[1-9A-Fa-f][0-9A-Fa-f]{0,3}):|(((0|[1-9A-Fa-f][0-9A-Fa-f]{0,3}):){0,4}(0|[1-9A-Fa-f][0-9A-Fa-f]{0,3}))?::)((0|[1-9A-Fa-f][0-9A-Fa-f]{0,3}):(0|[1-9A-Fa-f][0-9A-Fa-f]{0,3})|(25[0-5]|2[0-4][0-9]|1[0-9]{2}|[1-9]?[0-9])(\\.(25[0-5]|2[0-4][0-9]|1[0-9]{2}|[1-9]?[0-9])){3})|(((0|[1-9A-Fa-f][0-9A-Fa-f]{0,3}):){0,5}(0|[1-9A-Fa-f][0-9A-Fa-f]{0,3}))?::(0|[1-9A-Fa-f][0-9A-Fa-f]{0,3})|(((0|[1-9A-Fa-f][0-9A-Fa-f]{0,3}):){0,6}(0|[1-9A-Fa-f][0-9A-Fa-f]{0,3}))?::)|(?!IPv6:)[0-9A-Za-z-]*[0-9A-Za-z]:[!-Z^-~]+)]\n\nMailbox = Local-part "@" ( Domain / address-literal )\n =~ ([-!#-'*+/-9=?A-Z^-~]+(\\.[-!#-'*+/-9=?A-Z^-~]+)*|"([]!#-[^-~ \\t]|(\\\\[\\t -~]))+")@([0-9A-Za-z]([0-9A-Za-z-]{0,61}[0-9A-Za-z])?(\\.[0-9A-Za-z]([0-9A-Za-z-]{0,61}[0-9A-Za-z])?)*|\\[((25[0-5]|2[0-4][0-9]|1[0-9]{2}|[1-9]?[0-9])(\\.(25[0-5]|2[0-4][0-9]|1[0-9]{2}|[1-9]?[0-9])){3}|IPv6:((((0|[1-9A-Fa-f][0-9A-Fa-f]{0,3}):){6}|::((0|[1-9A-Fa-f][0-9A-Fa-f]{0,3}):){5}|[0-9A-Fa-f]{0,4}::((0|[1-9A-Fa-f][0-9A-Fa-f]{0,3}):){4}|(((0|[1-9A-Fa-f][0-9A-Fa-f]{0,3}):)?(0|[1-9A-Fa-f][0-9A-Fa-f]{0,3}))?::((0|[1-9A-Fa-f][0-9A-Fa-f]{0,3}):){3}|(((0|[1-9A-Fa-f][0-9A-Fa-f]{0,3}):){0,2}(0|[1-9A-Fa-f][0-9A-Fa-f]{0,3}))?::((0|[1-9A-Fa-f][0-9A-Fa-f]{0,3}):){2}|(((0|[1-9A-Fa-f][0-9A-Fa-f]{0,3}):){0,3}(0|[1-9A-Fa-f][0-9A-Fa-f]{0,3}))?::(0|[1-9A-Fa-f][0-9A-Fa-f]{0,3}):|(((0|[1-9A-Fa-f][0-9A-Fa-f]{0,3}):){0,4}(0|[1-9A-Fa-f][0-9A-Fa-f]{0,3}))?::)((0|[1-9A-Fa-f][0-9A-Fa-f]{0,3}):(0|[1-9A-Fa-f][0-9A-Fa-f]{0,3})|(25[0-5]|2[0-4][0-9]|1[0-9]{2}|[1-9]?[0-9])(\\.(25[0-5]|2[0-4][0-9]|1[0-9]{2}|[1-9]?[0-9])){3})|(((0|[1-9A-Fa-f][0-9A-Fa-f]{0,3}):){0,5}(0|[1-9A-Fa-f][0-9A-Fa-f]{0,3}))?::(0|[1-9A-Fa-f][0-9A-Fa-f]{0,3})|(((0|[1-9A-Fa-f][0-9A-Fa-f]{0,3}):){0,6}(0|[1-9A-Fa-f][0-9A-Fa-f]{0,3}))?::)|(?!IPv6:)[0-9A-Za-z-]*[0-9A-Za-z]:[!-Z^-~]+)])\n</code></pre>\n<h2>User input validation</h2>\n<p>A common use case is user input validation, for example on an html form. In that case it's usually reasonable to preclude address-literals and to require at least two labels in the hostname. Taking the improved RFC 5321 regex from the previous section as a basis, the resulting expression would be:</p>\n<p><code>([-!#-'*+/-9=?A-Z^-~]+(\\.[-!#-'*+/-9=?A-Z^-~]+)*|"([]!#-[^-~ \\t]|(\\\\[\\t -~]))+")@[0-9A-Za-z]([0-9A-Za-z-]{0,61}[0-9A-Za-z])?(\\.[0-9A-Za-z]([0-9A-Za-z-]{0,61}[0-9A-Za-z])?)+</code></p>\n<p>I do not recommend restricting the local part further, e.g. by precluding quoted strings, since we don't know what kind of mailbox names some hosts allow (like <code>"a..b"@example.net</code> or even <code>"a b"@example.net</code>).</p>\n<p>I also do not recommend explicitly validating against a list of literal top-level domains or even imposing length-constraints (remember how ".museum" invalidated <code>[a-z]{2,4}</code>), but if you must:</p>\n<p><code>([-!#-'*+/-9=?A-Z^-~]+(\\.[-!#-'*+/-9=?A-Z^-~]+)*|"([]!#-[^-~ \\t]|(\\\\[\\t -~]))+")@([0-9A-Za-z]([0-9A-Za-z-]{0,61}[0-9A-Za-z])?\\.)*(net|org|com|info|</code><em>etc...</em><code>)</code></p>\n<p>Make sure to keep your regex up-to-date if you decide to go down the path of explicit top-level domain validation.</p>\n<h2>Further considerations</h2>\n<p>When only accepting host names in the domain part (after the @-sign), the regexes above accept only labels with at most 63 characters, as they should. However, they don't enforce the fact that the entire host name must be at most 253 characters long (including the dots). Although this constraint is strictly speaking still regular, it's not feasible to make a regex that incorporates this rule.</p>\n<p>Another consideration, especially when using the regexes for input validation, is feedback to the user. If a user enters an incorrect address, it would be nice to give a little more feedback than a simple "syntactically incorrect address". With "vanilla" regexes this is not possible.</p>\n<p>These two considerations could be addressed by parsing the address. The extra length constraint on host names could in some cases also be addressed by using an extra regex that checks it, and matching the address against both expressions.</p>\n<p>None of the regexes in this answer are optimized for performance. If performance is an issue, you should see if (and how) the regex of your choice can be optimized.</p>\n"
},
{
"answer_id": 14102027,
"author": "Mohit Gupta",
"author_id": 1264203,
"author_profile": "https://Stackoverflow.com/users/1264203",
"pm_score": 2,
"selected": false,
"text": "<p>As per my understanding, it will most probably be covered by...</p>\n<pre><code>/^([a-z0-9_-]+)(@[a-z0-9-]+)(\\.[a-z]+|\\.[a-z]+\\.[a-z]+)?$/is\n</code></pre>\n"
},
{
"answer_id": 14321045,
"author": "FLY",
"author_id": 286143,
"author_profile": "https://Stackoverflow.com/users/286143",
"pm_score": 2,
"selected": false,
"text": "<p>Here is the one I've build. It is not a bulletproof version, but it is 'simple' and checks almost everything.</p>\n<pre class=\"lang-none prettyprint-override\"><code>[\\w+-]+(?:\\.[\\w+-]+)*@[\\w+-]+(?:\\.[\\w+-]+)*(?:\\.[a-zA-Z]{2,4})\n</code></pre>\n<p>I think an explanation is in place so you can modify it if you want:</p>\n<p>(<strong>e</strong>) <code>[\\w+-]+</code> matches a-z, A-Z, _, +, - at least one time</p>\n<p>(<strong>m</strong>) <code>(?:\\.[\\w+-]+)*</code> matches a-z, A-Z, _, +, - zero or more times but need to start with a . (dot)</p>\n<p><code>@</code> = <code>@</code></p>\n<p>(<strong>i</strong>) <code>[\\w+-]+</code> matches a-z, A-Z, _, +, - at least one time</p>\n<p>(<strong>l</strong>) <code>(?:\\.[\\w+-]+)*</code> matches a-z, A-Z, _, +, - zero or more times but need to start with a . (dot)</p>\n<p>(<strong>com</strong>) <code>(?:\\.[a-zA-Z]{2,4})</code> matches a-z, A-Z for 2 to 4 times starting with a . (dot)</p>\n<p>giving <code>e(.m)@i(.l).com</code> where <code>(.m)</code> and <code>(.l)</code> are optional but also can be repeated multiple times.</p>\n<p>I think this validates all valid email addresses, but blocks potential invalid without using an overcomplex regular expression which won't be necessary in most cases.</p>\n<p>Notice this will allow <code>[email protected]</code>, but that is the compromise for keeping it simple.</p>\n"
},
{
"answer_id": 14401049,
"author": "Cees Timmerman",
"author_id": 819417,
"author_profile": "https://Stackoverflow.com/users/819417",
"pm_score": 3,
"selected": false,
"text": "<p>I'm still using:</p>\n<pre class=\"lang-none prettyprint-override\"><code>^[A-Za-z0-9._+\\-\\']+@[A-Za-z0-9.\\-]+\\.[A-Za-z]{2,}$\n</code></pre>\n<p>But with IPv6 and Unicode coming up, perhaps this is best:</p>\n<p><div class=\"snippet\" data-lang=\"js\" data-hide=\"false\" data-console=\"true\" data-babel=\"false\">\r\n<div class=\"snippet-code\">\r\n<pre class=\"snippet-code-js lang-js prettyprint-override\"><code>console.log(/^[\\p{L}!#-'*+\\-/\\d=?^-~]+(.[\\p{L}!#-'*+\\-/\\d=?^-~])*@[^@\\s]{2,}$/u.test(\"תה.בועות@.fm\"))</code></pre>\r\n</div>\r\n</div>\r\n</p>\n<p>Gmail allows sequential dots, but Microsoft Exchange Server 2007 refuses them, which follows <a href=\"https://www.rfc-editor.org/rfc/rfc5322\" rel=\"nofollow noreferrer\">the most recent standard</a> afaik.</p>\n"
},
{
"answer_id": 16497018,
"author": "PrivateUser",
"author_id": 736037,
"author_profile": "https://Stackoverflow.com/users/736037",
"pm_score": 1,
"selected": false,
"text": "<p>The world's most popular blogging platform <a href=\"https://en.wikipedia.org/wiki/WordPress\" rel=\"nofollow noreferrer\">WordPress</a> uses this function to validate email address...</p>\n<p>But they are doing it with multiple steps.</p>\n<p>You don't have to worry anymore when using the regex mentioned in this function...</p>\n<p>Here is the function...</p>\n<pre><code>/**\n * Verifies that an email is valid.\n *\n * Does not grok i18n domains. Not RFC compliant.\n *\n * @since 0.71\n *\n * @param string $email Email address to verify.\n * @param boolean $deprecated Deprecated.\n * @return string|bool Either false or the valid email address.\n */\nfunction is_email( $email, $deprecated = false ) {\n if ( ! empty( $deprecated ) )\n _deprecated_argument( __FUNCTION__, '3.0' );\n\n // Test for the minimum length the email can be\n if ( strlen( $email ) < 3 ) {\n return apply_filters( 'is_email', false, $email, 'email_too_short' );\n }\n\n // Test for an @ character after the first position\n if ( strpos( $email, '@', 1 ) === false ) {\n return apply_filters( 'is_email', false, $email, 'email_no_at' );\n }\n\n // Split out the local and domain parts\n list( $local, $domain ) = explode( '@', $email, 2 );\n\n // LOCAL PART\n // Test for invalid characters\n if ( !preg_match( '/^[a-zA-Z0-9!#$%&\\'*+\\/=?^_`{|}~\\.-]+$/', $local ) ) {\n return apply_filters( 'is_email', false, $email, 'local_invalid_chars' );\n }\n\n // DOMAIN PART\n // Test for sequences of periods\n if ( preg_match( '/\\.{2,}/', $domain ) ) {\n return apply_filters( 'is_email', false, $email, 'domain_period_sequence' );\n }\n\n // Test for leading and trailing periods and whitespace\n if ( trim( $domain, " \\t\\n\\r\\0\\x0B." ) !== $domain ) {\n return apply_filters( 'is_email', false, $email, 'domain_period_limits' );\n }\n\n // Split the domain into subs\n $subs = explode( '.', $domain );\n\n // Assume the domain will have at least two subs\n if ( 2 > count( $subs ) ) {\n return apply_filters( 'is_email', false, $email, 'domain_no_periods' );\n }\n\n // Loop through each sub\n foreach ( $subs as $sub ) {\n // Test for leading and trailing hyphens and whitespace\n if ( trim( $sub, " \\t\\n\\r\\0\\x0B-" ) !== $sub ) {\n return apply_filters( 'is_email', false, $email, 'sub_hyphen_limits' );\n }\n\n // Test for invalid characters\n if ( !preg_match('/^[a-z0-9-]+$/i', $sub ) ) {\n return apply_filters( 'is_email', false, $email, 'sub_invalid_chars' );\n }\n }\n\n // Congratulations your email made it!\n return apply_filters( 'is_email', $email, $email, null );\n}\n</code></pre>\n"
},
{
"answer_id": 17244210,
"author": "user2467899",
"author_id": 2467899,
"author_profile": "https://Stackoverflow.com/users/2467899",
"pm_score": -1,
"selected": false,
"text": "<p>In order to validate an email address with JavaScript it is more convenient and efficient use this function (according with <a href=\"https://en.wikipedia.org/wiki/W3Schools\" rel=\"nofollow noreferrer\">W3Schools</a>):</p>\n<pre><code>function validateEmail()\n{\n var x = document.f.email.value;\n var atpos = x.indexOf("@");\n var dotpos = x.lastIndexOf(".");\n if (atpos < 1 || dotpos < atpos+2 || dotpos+2 >= x.length)\n {\n alert("Not a valid e-mail address");\n return false;\n }\n}\n</code></pre>\n<p>I use it and it's perfect.</p>\n"
},
{
"answer_id": 17742589,
"author": "mrswadge",
"author_id": 1247302,
"author_profile": "https://Stackoverflow.com/users/1247302",
"pm_score": 2,
"selected": false,
"text": "<p>I <a href=\"http://www.regular-expressions.info/email.html\" rel=\"nofollow noreferrer\">found a regular expression</a> that is compliant with <a href=\"https://en.wikipedia.org/wiki/Email#Message_format\" rel=\"nofollow noreferrer\">RFC 2822</a>. The preceding standard to <a href=\"https://en.wikipedia.org/wiki/Email#Message_format\" rel=\"nofollow noreferrer\">RFC 5322</a>. This regular expression appears to perform fairly well and will cover most cases, however with RFC 5322 becoming the standard there may be some holes that ought to be plugged.</p>\n<pre class=\"lang-none prettyprint-override\"><code>^(?:[a-z0-9!#$%&'*+/=?^_`{|}~-]+(?:\\.[a-z0-9!#$%&'*+/=?^_`{|}~-]+)*|"(?:[\\x01-\\x08\\x0b\\x0c\\x0e-\\x1f\\x21\\x23-\\x5b\\x5d-\\x7f]|\\\\[\\x01-\\x09\\x0b\\x0c\\x0e-\\x7f])*")@(?:(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\\.)+[a-z0-9](?:[a-z0-9-]*[a-z0-9])?|\\[(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\\.){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?|[a-z0-9-]*[a-z0-9]:(?:[\\x01-\\x08\\x0b\\x0c\\x0e-\\x1f\\x21-\\x5a\\x53-\\x7f]|\\\\[\\x01-\\x09\\x0b\\x0c\\x0e-\\x7f])+)\\])$\n</code></pre>\n<p>The documentation says you shouldn't use the above regular expression, but instead favour this flavour, which is a bit more manageable.</p>\n<pre class=\"lang-none prettyprint-override\"><code>[a-z0-9!#$%&'*+/=?^_`{|}~-]+(?:\\.[a-z0-9!#$%&'*+/=?^_`{|}~-]+)*@(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\\.)+[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\n</code></pre>\n<p>I noticed this is case-sensitive, so I actually made an alteration to this landing.</p>\n<pre class=\"lang-none prettyprint-override\"><code>^[a-zA-Z0-9!#$%&'*+/=?^_`{|}~-]+(?:\\.[a-zA-Z0-9!#$%&'*+/=?^_`{|}~-]+)*@(?:[a-zA-Z0-9](?:[a-zA-Z0-9-]*[a-zA-Z0-9])?\\.)+[a-zA-Z0-9](?:[a-zA-Z0-9-]*[a-zA-Z0-9])?$\n</code></pre>\n"
},
{
"answer_id": 19592376,
"author": "Francisco Costa",
"author_id": 621727,
"author_profile": "https://Stackoverflow.com/users/621727",
"pm_score": 0,
"selected": false,
"text": "<pre><code>^[_a-zA-Z0-9-]+(\\.[_a-zA-Z0-9-]+)*@[a-zA-Z0-9-]+(\\.[a-zA-Z0-9-]+)*\\.(([0-9]{1,3})|([a-zA-Z]{2,3})|(aero|coop|info|museum|name))$\n</code></pre>\n\n<p>This matches 99.99% of email addresses, including some of the newer top-level-domain extensions, such as info, museum, name, etc. It also allows for emails tied directly to IP addresses.</p>\n"
},
{
"answer_id": 20413337,
"author": "mirabilos",
"author_id": 2171120,
"author_profile": "https://Stackoverflow.com/users/2171120",
"pm_score": 2,
"selected": false,
"text": "<p>I’ve had a similar desire: wanting a quick check for syntax in email addresses without going overboard (the <code>Mail::RFC822::Address</code> answer which is the obviously correct one) for <a href=\"https://www.mirbsd.org/cvs.cgi/contrib/hosted/tg/mailfrom.php?rev=HEAD\" rel=\"nofollow noreferrer\">an email send utility</a>. I went with this (I’m a <a href=\"https://en.wikipedia.org/wiki/POSIX\" rel=\"nofollow noreferrer\">POSIX</a> regular expression person, so I don’t normally use <code>\\d</code> and such from <a href=\"https://en.wikipedia.org/wiki/Perl_Compatible_Regular_Expressions\" rel=\"nofollow noreferrer\">PCRE</a>, as they make things less legible to me):</p>\n<pre class=\"lang-php prettyprint-override\"><code>preg_match("_^[-!#-'*+/-9=?A-Z^-~]+(\\.[-!#-'*+/-9=?A-Z^-~]+)*@[0-9A-Za-z]([-0-9A-Za-z]{0,61}[0-9A-Za-z])?(\\.[0-9A-Za-z]([-0-9A-Za-z]{0,61}[0-9A-Za-z])?)*\\$_", $adr)\n</code></pre>\n<p>This is RFC-correct, but it explicitly excludes the obsolete forms as well as direct IP addresses (IP addresses and legacy IP addresses both), which someone in the target group of that utility (mostly: people who bother us in #sendmail on <a href=\"https://en.wikipedia.org/wiki/Internet_Relay_Chat\" rel=\"nofollow noreferrer\">IRC</a>) would not normally want or need anyway.</p>\n<p><a href=\"https://en.wikipedia.org/wiki/Internationalized_domain_name\" rel=\"nofollow noreferrer\">IDNs</a> (internationalised domain names) are explicitly <em>not</em> in the scope of email: addresses like “foo@cäcilienchor-bonn.de” <em>must</em> be written “[email protected]” on the wire instead (this includes <em>mailto:</em> links in HTML and such fun), only the GUI is allowed to display (and accept then convert) such names to (and from) the user.</p>\n"
},
{
"answer_id": 20428348,
"author": "auco",
"author_id": 388412,
"author_profile": "https://Stackoverflow.com/users/388412",
"pm_score": 3,
"selected": false,
"text": "<p>I know this question is about regular expressions, but I am guessing that 90% of all developers reading these solutions are trying to validate an email address in an HTML form displayed in a browser.</p>\n<p>If this is the case, I'd suggest checking out the new HTML5 <code><input type="email"></code> form element:</p>\n<p>HTML5:</p>\n<pre><code> <input type="email" required />\n</code></pre>\n<p>CSS 3:</p>\n<pre><code> input:required {\n background-color: rgba(255, 0, 0, 0.2);\n }\n\n input:focus:invalid {\n box-shadow: 0 0 1em red;\n border-color: red;\n }\n\n input:focus:valid {\n box-shadow: 0 0 1em green;\n border-color: green;\n }\n</code></pre>\n<p>It is at <em><a href=\"http://jsfiddle.net/mYRe7/1/\" rel=\"nofollow noreferrer\">HTML5 Form Validation Without JS - JSFiddle - Code Playground</a></em>.</p>\n<p>This has a couple of advantages:</p>\n<ol>\n<li>Automatic validation and no custom solution needed: simple and easy to implement</li>\n<li>No JavaScript, and no problems if JavaScript has been disabled</li>\n<li>No server has to calculate anything for that</li>\n<li>The user has immediate feedback</li>\n<li>Old browsers should automatically fallback to input type "text"</li>\n<li>Mobile browsers can display a specialized keyboard (@-Keyboard)</li>\n<li>Form validation feedback is very easy with CSS 3</li>\n</ol>\n<p>The apparent downside might be missing validation for old browsers, but that'll change over time. I'd prefer this over any of these insane regular expression masterpieces.</p>\n<p>Also see:</p>\n<ul>\n<li><em><a href=\"http://jsfiddle.net/mYRe7/1/\" rel=\"nofollow noreferrer\">HTML5 Form Validation Without JS - JSFiddle - Code Playground</a></em></li>\n<li><em><a href=\"http://diveintohtml5.info/forms.html\" rel=\"nofollow noreferrer\">Web Forms - Dive Into HTML5. A Form of Madness</a></em></li>\n<li><em><a href=\"http://blog.mozilla.org/webdev/2011/03/14/html5-form-validation-on-sumo/\" rel=\"nofollow noreferrer\">HTML5 Form Validation on SUMO</a></em></li>\n</ul>\n"
},
{
"answer_id": 21595782,
"author": "Suhaib Janjua",
"author_id": 3240038,
"author_profile": "https://Stackoverflow.com/users/3240038",
"pm_score": 2,
"selected": false,
"text": "<p>I always use the below regular expression to validate the email address. It covers all formats of email addresses based on English language characters.</p>\n<pre><code>"\\A(?:[a-z0-9!#$%&'*+/=?^_`{|}~-]+(?:\\.[a-z0-9!#$%&'*+/=?^_`{|}~-]+)*@(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\\.)+[a-z0-9](?:[a-z0-9-]*[a-z0-9])?)\\Z";\n</code></pre>\n<p><strong>Given below is a C# example:</strong></p>\n<p>Add the assembly reference:</p>\n<pre><code>using System.Text.RegularExpressions;\n</code></pre>\n<p>and use the below method to pass the email address and get a boolean in return</p>\n<pre><code>private bool IsValidEmail(string email) {\n bool isValid = false;\n const string pattern = @"\\A(?:[a-z0-9!#$%&'*+/=?^_`{|}~-]+(?:\\.[a-z0-9!#$%&'*+/=?^_`{|}~-]+)*@(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\\.)+[a-z0-9](?:[a-z0-9-]*[a-z0-9])?)\\Z";\n\n isValid = email != "" && Regex.IsMatch(email, pattern);\n\n // Same above approach in multiple lines\n //\n //if (!email) {\n // isValid = false;\n //} else {\n // // email param contains a value; Pass it to the isMatch method\n // isValid = Regex.IsMatch(email, pattern);\n //}\n return isValid;\n}\n</code></pre>\n<p>This method validates the email string passed in the parameter.\nIt will return false for all cases where param is null, empty string, undefined or the param value is not a valid email address.\nIt will only return true when the param contains a valid email address string.</p>\n"
},
{
"answer_id": 22078163,
"author": "Coder12345",
"author_id": 974700,
"author_profile": "https://Stackoverflow.com/users/974700",
"pm_score": 3,
"selected": false,
"text": "<p>I use multi-step validation. As there isn't any perfect way to validate an email address, a perfect one can't be made, but at least you can notify the user he/she is doing something wrong - here is my approach:</p>\n<ol>\n<li><p>I first validate with the very basic regex which just checks if the email contains exactly one @ sign and it is not blank before or after that sign. e.g. <code>/^[^@\\s]+@[^@\\s]+$/</code></p>\n</li>\n<li><p>if the first validator does not pass (and for most addresses it should although it is not perfect), then warn the user the email is invalid and do not allow him/her to continue with the input</p>\n</li>\n<li><p>if it passes, then validate against a more strict regex - something which might disallow valid emails. If it does not pass, the user is warned about a possible error, but the user is allowed to continue. Unlike step (1) where the user is not allowed to continue because it is an obvious error.</p>\n</li>\n</ol>\n<p>So in other words, the first liberal validation is just to strip obvious errors and it is treated as "error". People type a blank address, address without @ sign and so on. This should be treated as an error. The second one is more strict, but it is treated as a "warning" and the user is allowed to continue with the input, but warned to at least examine if he/she entered a valid entry. The key here is in the error/warning approach - the error being something that can't under 99.99% circumstances be a valid email.</p>\n<p>Of course, you can adjust what makes the first regex more liberal and the second one more strict.</p>\n<p>Depending on what you need, the above approach might work for you.</p>\n"
},
{
"answer_id": 24092435,
"author": "Joeytje50",
"author_id": 1256925,
"author_profile": "https://Stackoverflow.com/users/1256925",
"pm_score": 2,
"selected": false,
"text": "<p>A regex that does exactly what the standards say is allowed, according to what I've seen about them, is this:</p>\n\n<pre><code>/^(?!(^[.-].*|.*[.-]@|.*\\.{2,}.*)|^.{254}.+@)([a-z\\xC0-\\xFF0-9!#$%&'*+\\/=?^_`{|}~.-]+@)(?!.{253}.+$)((?!-.*|.*-\\.)([a-z0-9-]{1,63}\\.)+[a-z]{2,63}|(([01]?[0-9]{2}|2([0-4][0-9]|5[0-5])|[0-9])\\.){3}([01]?[0-9]{2}|2([0-4][0-9]|5[0-5])|[0-9]))$/gim\n</code></pre>\n\n<p><a href=\"http://regex101.com/r/nO4jB0\" rel=\"nofollow noreferrer\"><strong>Demo</strong></a> / <a href=\"https://www.debuggex.com/i/JN4oFLSjtB5QMK4j.png\" rel=\"nofollow noreferrer\"><strong>Debuggex analysis</strong></a> (<a href=\"https://www.debuggex.com/r/JN4oFLSjtB5QMK4j\" rel=\"nofollow noreferrer\">interactive</a>)</p>\n\n<p>Split up:</p>\n\n<pre><code>^(?!(^[.-].*|.*[.-]@|.*\\.{2,}.*)|^.{254}.+@)\n([a-z\\xC0-\\xFF0-9!#$%&'*+\\/=?^_`{|}~.-]+@)\n(?!.{253}.+$)\n(\n (?!-.*|.*-\\.)\n ([a-z0-9-]{1,63}\\.)+\n [a-z]{2,63}\n |\n (([01]?[0-9]{2}|2([0-4][0-9]|5[0-5])|[0-9])\\.){3}\n ([01]?[0-9]{2}|2([0-4][0-9]|5[0-5])|[0-9])\n)$\n</code></pre>\n\n<p>Analysis:</p>\n\n<pre><code>(?!(^[.-].*|.*[.-]@|.*\\.{2,}.*)|^.{254}.+@)\n</code></pre>\n\n<p>Negative lookahead for either <a href=\"https://stackoverflow.com/a/2049510/1256925\">an address starting with a <code>.</code>, ending with one, having <code>..</code> in it</a>, or exceeding <a href=\"https://stackoverflow.com/a/574698/1256925\">the 254 character max length</a></p>\n\n<hr>\n\n<pre><code>([a-z\\xC0-\\xFF0-9!#$%&'*+\\/=?^_`{|}~.-]+@)\n</code></pre>\n\n<p>matching 1 or more of the <a href=\"https://stackoverflow.com/a/2049510/1256925\">permitted characters</a>, with the negative look applying to it</p>\n\n<hr>\n\n<pre><code>(?!.{253}.+$)\n</code></pre>\n\n<p>Negative lookahead for the domain name part, restricting it to <a href=\"https://webmasters.stackexchange.com/a/16997\">253 characters in total</a></p>\n\n<hr>\n\n<pre><code>(?!-.*|.*-\\.)\n</code></pre>\n\n<p>Negative lookahead for each of the domain names, which are don't allow <a href=\"https://stackoverflow.com/a/7111947/1256925\">starting or ending with <code>.</code></a></p>\n\n<hr>\n\n<pre><code>([a-z0-9-]{1,63}\\.)+\n</code></pre>\n\n<p>simple group match for the allowed characters in a domain name, which are limited to <a href=\"https://webmasters.stackexchange.com/a/16997\">63 characters each</a></p>\n\n<hr>\n\n<pre><code>[a-zA-Z]{2,63}\n</code></pre>\n\n<p>simple group match for the allowed top-level domain, which currently <a href=\"https://en.wikipedia.org/wiki/TLD#IDN_test_domains\" rel=\"nofollow noreferrer\">still</a> is restricted to letters only, but <a href=\"https://en.wikipedia.org/wiki/List_of_Internet_top-level_domains#ICANN-era_generic_top-level_domains\" rel=\"nofollow noreferrer\">does include >4 letter TLDs</a>.</p>\n\n<hr>\n\n<pre><code>(([01]?[0-9]{2}|2([0-4][0-9]|5[0-5])|[0-9])\\.){3}\n([01]?[0-9]{2}|2([0-4][0-9]|5[0-5])|[0-9])\n</code></pre>\n\n<p>the alternative for domain names: this matches the first 3 numbers in an IP address <em>with</em> a <code>.</code> behind it, and then the fourth number in the IP address without <code>.</code> behind it.</p>\n"
},
{
"answer_id": 24836448,
"author": "Alexey Ossikine",
"author_id": 3850045,
"author_profile": "https://Stackoverflow.com/users/3850045",
"pm_score": 2,
"selected": false,
"text": "<p>If you want to improve on a regex that has been working reasonably well over several years, then the answer depends on what exactly you want to achieve - what kinds of email addresses have been failing. Fine-tuning email regexes is very difficult, and I have yet to see a perfect solution.</p>\n<ul>\n<li>If your application involves something very technical in nature (or something internal to organizations), then maybe you need to support IP addresses instead of domain names, or comments in the "local" part of the email address.</li>\n<li>If your application is multinational, I would consider focusing on <a href=\"https://en.wikipedia.org/wiki/Unicode\" rel=\"nofollow noreferrer\">Unicode</a> and <a href=\"https://en.wikipedia.org/wiki/UTF-8\" rel=\"nofollow noreferrer\">UTF-8</a> support.</li>\n</ul>\n<p>The leading answer to your question currently links to a "fully RFC‑822–compliant regex". However, in spite of the complexity of that regex and its presumed attention to detail in RFC rules, it completely fails when it comes to Unicode support.</p>\n<p>The regex that I've written for most of my applications focuses on Unicode support, as well as <em>reasonably</em> good overall adherence to RFC standards:</p>\n<pre><code>/^(?!\\.)((?!.*\\.{2})[a-zA-Z0-9\\u0080-\\u00FF\\u0100-\\u017F\\u0180-\\u024F\\u0250-\\u02AF\\u0300-\\u036F\\u0370-\\u03FF\\u0400-\\u04FF\\u0500-\\u052F\\u0530-\\u058F\\u0590-\\u05FF\\u0600-\\u06FF\\u0700-\\u074F\\u0750-\\u077F\\u0780-\\u07BF\\u07C0-\\u07FF\\u0900-\\u097F\\u0980-\\u09FF\\u0A00-\\u0A7F\\u0A80-\\u0AFF\\u0B00-\\u0B7F\\u0B80-\\u0BFF\\u0C00-\\u0C7F\\u0C80-\\u0CFF\\u0D00-\\u0D7F\\u0D80-\\u0DFF\\u0E00-\\u0E7F\\u0E80-\\u0EFF\\u0F00-\\u0FFF\\u1000-\\u109F\\u10A0-\\u10FF\\u1100-\\u11FF\\u1200-\\u137F\\u1380-\\u139F\\u13A0-\\u13FF\\u1400-\\u167F\\u1680-\\u169F\\u16A0-\\u16FF\\u1700-\\u171F\\u1720-\\u173F\\u1740-\\u175F\\u1760-\\u177F\\u1780-\\u17FF\\u1800-\\u18AF\\u1900-\\u194F\\u1950-\\u197F\\u1980-\\u19DF\\u19E0-\\u19FF\\u1A00-\\u1A1F\\u1B00-\\u1B7F\\u1D00-\\u1D7F\\u1D80-\\u1DBF\\u1DC0-\\u1DFF\\u1E00-\\u1EFF\\u1F00-\\u1FFFu20D0-\\u20FF\\u2100-\\u214F\\u2C00-\\u2C5F\\u2C60-\\u2C7F\\u2C80-\\u2CFF\\u2D00-\\u2D2F\\u2D30-\\u2D7F\\u2D80-\\u2DDF\\u2F00-\\u2FDF\\u2FF0-\\u2FFF\\u3040-\\u309F\\u30A0-\\u30FF\\u3100-\\u312F\\u3130-\\u318F\\u3190-\\u319F\\u31C0-\\u31EF\\u31F0-\\u31FF\\u3200-\\u32FF\\u3300-\\u33FF\\u3400-\\u4DBF\\u4DC0-\\u4DFF\\u4E00-\\u9FFF\\uA000-\\uA48F\\uA490-\\uA4CF\\uA700-\\uA71F\\uA800-\\uA82F\\uA840-\\uA87F\\uAC00-\\uD7AF\\uF900-\\uFAFF\\.!#$%&'*+-/=?^_`{|}~\\-\\d]+)@(?!\\.)([a-zA-Z0-9\\u0080-\\u00FF\\u0100-\\u017F\\u0180-\\u024F\\u0250-\\u02AF\\u0300-\\u036F\\u0370-\\u03FF\\u0400-\\u04FF\\u0500-\\u052F\\u0530-\\u058F\\u0590-\\u05FF\\u0600-\\u06FF\\u0700-\\u074F\\u0750-\\u077F\\u0780-\\u07BF\\u07C0-\\u07FF\\u0900-\\u097F\\u0980-\\u09FF\\u0A00-\\u0A7F\\u0A80-\\u0AFF\\u0B00-\\u0B7F\\u0B80-\\u0BFF\\u0C00-\\u0C7F\\u0C80-\\u0CFF\\u0D00-\\u0D7F\\u0D80-\\u0DFF\\u0E00-\\u0E7F\\u0E80-\\u0EFF\\u0F00-\\u0FFF\\u1000-\\u109F\\u10A0-\\u10FF\\u1100-\\u11FF\\u1200-\\u137F\\u1380-\\u139F\\u13A0-\\u13FF\\u1400-\\u167F\\u1680-\\u169F\\u16A0-\\u16FF\\u1700-\\u171F\\u1720-\\u173F\\u1740-\\u175F\\u1760-\\u177F\\u1780-\\u17FF\\u1800-\\u18AF\\u1900-\\u194F\\u1950-\\u197F\\u1980-\\u19DF\\u19E0-\\u19FF\\u1A00-\\u1A1F\\u1B00-\\u1B7F\\u1D00-\\u1D7F\\u1D80-\\u1DBF\\u1DC0-\\u1DFF\\u1E00-\\u1EFF\\u1F00-\\u1FFF\\u20D0-\\u20FF\\u2100-\\u214F\\u2C00-\\u2C5F\\u2C60-\\u2C7F\\u2C80-\\u2CFF\\u2D00-\\u2D2F\\u2D30-\\u2D7F\\u2D80-\\u2DDF\\u2F00-\\u2FDF\\u2FF0-\\u2FFF\\u3040-\\u309F\\u30A0-\\u30FF\\u3100-\\u312F\\u3130-\\u318F\\u3190-\\u319F\\u31C0-\\u31EF\\u31F0-\\u31FF\\u3200-\\u32FF\\u3300-\\u33FF\\u3400-\\u4DBF\\u4DC0-\\u4DFF\\u4E00-\\u9FFF\\uA000-\\uA48F\\uA490-\\uA4CF\\uA700-\\uA71F\\uA800-\\uA82F\\uA840-\\uA87F\\uAC00-\\uD7AF\\uF900-\\uFAFF\\-\\.\\d]+)((\\.([a-zA-Z\\u0080-\\u00FF\\u0100-\\u017F\\u0180-\\u024F\\u0250-\\u02AF\\u0300-\\u036F\\u0370-\\u03FF\\u0400-\\u04FF\\u0500-\\u052F\\u0530-\\u058F\\u0590-\\u05FF\\u0600-\\u06FF\\u0700-\\u074F\\u0750-\\u077F\\u0780-\\u07BF\\u07C0-\\u07FF\\u0900-\\u097F\\u0980-\\u09FF\\u0A00-\\u0A7F\\u0A80-\\u0AFF\\u0B00-\\u0B7F\\u0B80-\\u0BFF\\u0C00-\\u0C7F\\u0C80-\\u0CFF\\u0D00-\\u0D7F\\u0D80-\\u0DFF\\u0E00-\\u0E7F\\u0E80-\\u0EFF\\u0F00-\\u0FFF\\u1000-\\u109F\\u10A0-\\u10FF\\u1100-\\u11FF\\u1200-\\u137F\\u1380-\\u139F\\u13A0-\\u13FF\\u1400-\\u167F\\u1680-\\u169F\\u16A0-\\u16FF\\u1700-\\u171F\\u1720-\\u173F\\u1740-\\u175F\\u1760-\\u177F\\u1780-\\u17FF\\u1800-\\u18AF\\u1900-\\u194F\\u1950-\\u197F\\u1980-\\u19DF\\u19E0-\\u19FF\\u1A00-\\u1A1F\\u1B00-\\u1B7F\\u1D00-\\u1D7F\\u1D80-\\u1DBF\\u1DC0-\\u1DFF\\u1E00-\\u1EFF\\u1F00-\\u1FFF\\u20D0-\\u20FF\\u2100-\\u214F\\u2C00-\\u2C5F\\u2C60-\\u2C7F\\u2C80-\\u2CFF\\u2D00-\\u2D2F\\u2D30-\\u2D7F\\u2D80-\\u2DDF\\u2F00-\\u2FDF\\u2FF0-\\u2FFF\\u3040-\\u309F\\u30A0-\\u30FF\\u3100-\\u312F\\u3130-\\u318F\\u3190-\\u319F\\u31C0-\\u31EF\\u31F0-\\u31FF\\u3200-\\u32FF\\u3300-\\u33FF\\u3400-\\u4DBF\\u4DC0-\\u4DFF\\u4E00-\\u9FFF\\uA000-\\uA48F\\uA490-\\uA4CF\\uA700-\\uA71F\\uA800-\\uA82F\\uA840-\\uA87F\\uAC00-\\uD7AF\\uF900-\\uFAFF]){2,63})+)$/i\n</code></pre>\n<p>I'll avoid copy-pasting complete answers, so I'll just link this to a similar answer I provided here: <em><a href=\"https://stackoverflow.com/questions/19461943/how-to-validate-a-unicode-email/24817336#24817336\">How to validate a unicode email?</a></em></p>\n<p>There is also a live demo available for the regex above at: <a href=\"http://jsfiddle.net/aossikine/qCLVH/3/\" rel=\"nofollow noreferrer\">http://jsfiddle.net/aossikine/qCLVH/3/</a></p>\n"
},
{
"answer_id": 25055145,
"author": "Fragment",
"author_id": 2157164,
"author_profile": "https://Stackoverflow.com/users/2157164",
"pm_score": 2,
"selected": false,
"text": "<p>There has nearly been added a new domain, "yandex". Possible emails: [email protected]. And also uppercase letters are supported, so a bit modified version of acrosman's solution is:</p>\n<pre class=\"lang-none prettyprint-override\"><code>^[_a-zA-Z0-9-]+(\\.[_a-zA-Z0-9-]+)*@[a-zA-Z0-9-]+(\\.[a-zA-Z0-9-]+)*(\\.[a-zA-Z]{2,6})$\n</code></pre>\n"
},
{
"answer_id": 25158388,
"author": "McGaz",
"author_id": 2116417,
"author_profile": "https://Stackoverflow.com/users/2116417",
"pm_score": 2,
"selected": false,
"text": "<p>The regular expressions posted for this question are out of date now, because of the new generic <a href=\"https://en.wikipedia.org/wiki/Top-level_domain\" rel=\"nofollow noreferrer\">top-level domains</a> (gTLDs) coming in (e.g. .london, .basketball, .通販). To validate an email address there are two answers (that would be relevant to the vast majority).</p>\n<ol>\n<li>As the main answer says - don't use a regular expression. Just validate it by sending an email to the address (catch exceptions for invalid addresses)</li>\n<li>Use a very generic regex to at least make sure that they are using an email structure like <code>{something}@{something}.{something}</code>. There's no point in going for a detailed regex, because you won't catch them all and there'll be a new batch in a few years and you'll have to update your regular expression again.</li>\n</ol>\n<p>I have decided to use the regular expression because, unfortunately, some users don't read forms and put the wrong data in the wrong fields. This will at least alert them when they try to put something which isn't an email into the email input field and should save you some time supporting users on email issues.</p>\n<pre><code>(.+)@(.+){2,}\\.(.+){2,}\n</code></pre>\n"
},
{
"answer_id": 25484628,
"author": "sunleo",
"author_id": 1755242,
"author_profile": "https://Stackoverflow.com/users/1755242",
"pm_score": 2,
"selected": false,
"text": "<p><strong>Java Mail API does magic for us.</strong></p>\n<pre><code>try\n{\n InternetAddress internetAddress = new InternetAddress(email);\n internetAddress.validate();\n return true;\n}\ncatch(Exception ex)\n{\n return false;\n}\n</code></pre>\n<p>I got this from <a href=\"http://crunchify.com/how-to-validate-email-address-using-java-mail-api/\" rel=\"nofollow noreferrer\">here</a>.</p>\n"
},
{
"answer_id": 25789972,
"author": "zıəs uɐɟəʇs",
"author_id": 2115830,
"author_profile": "https://Stackoverflow.com/users/2115830",
"pm_score": 1,
"selected": false,
"text": "<p>As mentioned already, you can't validate an email with a regex. However, here's what we currently use to make sure user-input isn't totally bogus (forgetting the <a href=\"https://en.wikipedia.org/wiki/Top-level_domain\" rel=\"nofollow noreferrer\">TLD</a>, etc.).</p>\n<p>This regex will allow <a href=\"https://en.wikipedia.org/wiki/Internationalized_domain_name\" rel=\"nofollow noreferrer\">IDN</a> domains and special characters (like Umlauts) before and after the @ sign.</p>\n<pre class=\"lang-none prettyprint-override\"><code>/^[\\w.+-_]+@[^.][\\w.-]*\\.[\\w-]{2,63}$/iu\n</code></pre>\n"
},
{
"answer_id": 26800017,
"author": "Prasad Bhosale",
"author_id": 3698756,
"author_profile": "https://Stackoverflow.com/users/3698756",
"pm_score": 2,
"selected": false,
"text": "<p>Following is the regular expression for validating an email address:</p>\n<pre class=\"lang-none prettyprint-override\"><code>^.+@\\w+(\\.\\w+)+$\n</code></pre>\n"
},
{
"answer_id": 26861346,
"author": "Rajneesh071",
"author_id": 1369972,
"author_profile": "https://Stackoverflow.com/users/1369972",
"pm_score": -1,
"selected": false,
"text": "<p>A valid regular expression according to <a href=\"http://www.w3.org/TR/html-markup/datatypes.html#form.data.emailaddress\" rel=\"nofollow noreferrer\">W3C</a> and <a href=\"http://fr.wikipedia.org/wiki/Adresse_%C3%A9lectronique\" rel=\"nofollow noreferrer\">Wikipedia</a></p>\n<pre class=\"lang-none prettyprint-override\"><code>\n[A-Z0-9a-z.!#$%&'*+-/=?^_`{|}~]+@[A-Za-z0-9.-]+\\\\.[A-Za-z]{2,4}\n</code></pre>\n<p>E.g., !#$%&'*+-/=?^_`.{|}[email protected]</p>\n"
},
{
"answer_id": 27394451,
"author": "Ramesh Kotkar",
"author_id": 3090422,
"author_profile": "https://Stackoverflow.com/users/3090422",
"pm_score": 0,
"selected": false,
"text": "<p>You can use following regular expression for any email address:</p>\n<pre><code>^(([^<>()[\\]\\\\.,;:\\s@\\"]+(\\.[^<>()[\\]\\\\.,;:\\s@\\"]+)*)|(\\".+\\"))@((\\[[0-9]{1,3}\\.[0-9]{1,3}\\.[0-9]{1,3}\\.[0-9]{1,3}\\])|(([a-zA-Z\\-0-9]+\\.)+[a-zA-Z]{2,}))$\n</code></pre>\n<h3>For PHP</h3>\n<pre><code>function checkEmailValidation($email)\n{\n $expression = '/^(([^<>()[\\]\\\\.,;:\\s@\\"]+(\\.[^<>()[\\]\\\\.,;:\\s@\\"]+)*)|(\\".+\\"))@((\\[[0-9]{1,3}\\.[0-9]{1,3}\\.[0-9]{1,3}\\.[0-9]{1,3}\\])|(([a-zA-Z\\-0-9]+\\.)+[a-zA-Z]{2,}))$/';\n if(preg_match($expression, $email))\n {\n return true;\n }\n else\n {\n return false;\n }\n}\n</code></pre>\n<h3>For JavaScript</h3>\n<pre><code>function checkEmailValidation(email)\n{\n var pattern = '/^(([^<>()[\\]\\\\.,;:\\s@\\"]+(\\.[^<>()[\\]\\\\.,;:\\s@\\"]+)*)|(\\".+\\"))@((\\[[0-9]{1,3}\\.[0-9]{1,3}\\.[0-9]{1,3}\\.[0-9]{1,3}\\])|(([a-zA-Z\\-0-9]+\\.)+[a-zA-Z]{2,}))$/';\n if(pattern.test(email))\n {\n return true;\n }\n else\n {\n return false;\n }\n}\n</code></pre>\n"
},
{
"answer_id": 31442287,
"author": "Ondřej Šotek",
"author_id": 5112619,
"author_profile": "https://Stackoverflow.com/users/5112619",
"pm_score": 2,
"selected": false,
"text": "<p>For PHP I'm using <a href=\"http://api.nette.org/2.3.3/source-Utils.Validators.php.html#234-247\" rel=\"nofollow noreferrer\">the email address validator from the Nette Framework</a>:</p>\n<pre class=\"lang-php prettyprint-override\"><code>/* public static */ function isEmail($value)\n{\n $atom = "[-a-z0-9!#$%&'*+/=?^_`{|}~]"; // RFC 5322 unquoted characters in local-part\n $localPart = "(?:\\"(?:[ !\\\\x23-\\\\x5B\\\\x5D-\\\\x7E]*|\\\\\\\\[ -~])+\\"|$atom+(?:\\\\.$atom+)*)"; // Quoted or unquoted\n $alpha = "a-z\\x80-\\xFF"; // Superset of IDN\n $domain = "[0-9$alpha](?:[-0-9$alpha]{0,61}[0-9$alpha])?"; // RFC 1034 one domain component\n $topDomain = "[$alpha](?:[-0-9$alpha]{0,17}[$alpha])?";\n return (bool) preg_match("(^$localPart@(?:$domain\\\\.)+$topDomain\\\\z)i", $value);\n}\n</code></pre>\n"
},
{
"answer_id": 32010185,
"author": "Luna",
"author_id": 250076,
"author_profile": "https://Stackoverflow.com/users/250076",
"pm_score": 5,
"selected": false,
"text": "<p>The <a href=\"http://www.w3.org/TR/html5/forms.html#valid-e-mail-address\" rel=\"nofollow noreferrer\">HTML5 specification suggests</a> a simple regex for validating email addresses:</p>\n<pre class=\"lang-none prettyprint-override\"><code>/^[a-zA-Z0-9.!#$%&'*+\\/=?^_`{|}~-]+@[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\\.[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)*$/\n</code></pre>\n<p>This intentionally doesn't comply with <a href=\"https://www.rfc-editor.org/rfc/rfc5322\" rel=\"nofollow noreferrer\">RFC 5322</a>.</p>\n<blockquote>\n<p><strong>Note:</strong> This requirement is a <a href=\"http://www.w3.org/TR/html5/introduction.html#willful-violation\" rel=\"nofollow noreferrer\">wilful violation</a> of <a href=\"https://www.rfc-editor.org/rfc/rfc5322\" rel=\"nofollow noreferrer\">RFC 5322</a>, which defines a syntax for e-mail addresses that is simultaneously too strict (before the <code>@</code> character), too vague (after the <code>@</code> character), and too lax (allowing comments, whitespace characters, and quoted strings in manners unfamiliar to most users) to be of practical use here.</p>\n</blockquote>\n<p>The total length could also be limited to 254 characters, per <a href=\"https://www.rfc-editor.org/errata_search.php?rfc=3696&eid=1690\" rel=\"nofollow noreferrer\">RFC 3696 errata 1690</a>.</p>\n"
},
{
"answer_id": 32541986,
"author": "SIslam",
"author_id": 1045364,
"author_profile": "https://Stackoverflow.com/users/1045364",
"pm_score": 2,
"selected": false,
"text": "<p>I did not find any that deals with a <a href=\"https://en.wikipedia.org/wiki/Top-level_domain\" rel=\"nofollow noreferrer\">top-level domain</a> name, but it should be considered.</p>\n<p>So for me the following worked:</p>\n<pre class=\"lang-none prettyprint-override\"><code>[a-z0-9!#$%&'*+/=?^_`{|}~-]+(?:\\.[a-z0-9!#$%&'*+/=?^_`{|}~-]+)*@(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\\.)+(?:[A-Z]{2}AAA|AARP|ABB|ABBOTT|ABOGADO|AC|ACADEMY|ACCENTURE|ACCOUNTANT|ACCOUNTANTS|ACO|ACTIVE|ACTOR|AD|ADAC|ADS|ADULT|AE|AEG|AERO|AF|AFL|AG|AGENCY|AI|AIG|AIRFORCE|AIRTEL|AL|ALIBABA|ALIPAY|ALLFINANZ|ALSACE|AM|AMICA|AMSTERDAM|ANALYTICS|ANDROID|AO|APARTMENTS|APP|APPLE|AQ|AQUARELLE|AR|ARAMCO|ARCHI|ARMY|ARPA|ARTE|AS|ASIA|ASSOCIATES|AT|ATTORNEY|AU|AUCTION|AUDI|AUDIO|AUTHOR|AUTO|AUTOS|AW|AX|AXA|AZ|AZURE|BA|BAIDU|BAND|BANK|BAR|BARCELONA|BARCLAYCARD|BARCLAYS|BARGAINS|BAUHAUS|BAYERN|BB|BBC|BBVA|BCN|BD|BE|BEATS|BEER|BENTLEY|BERLIN|BEST|BET|BF|BG|BH|BHARTI|BI|BIBLE|BID|BIKE|BING|BINGO|BIO|BIZ|BJ|BLACK|BLACKFRIDAY|BLOOMBERG|BLUE|BM|BMS|BMW|BN|BNL|BNPPARIBAS|BO|BOATS|BOEHRINGER|BOM|BOND|BOO|BOOK|BOOTS|BOSCH|BOSTIK|BOT|BOUTIQUE|BR|BRADESCO|BRIDGESTONE|BROADWAY|BROKER|BROTHER|BRUSSELS|BS|BT|BUDAPEST|BUGATTI|BUILD|BUILDERS|BUSINESS|BUY|BUZZ|BV|BW|BY|BZ|BZH|CA|CAB|CAFE|CAL|CALL|CAMERA|CAMP|CANCERRESEARCH|CANON|CAPETOWN|CAPITAL|CAR|CARAVAN|CARDS|CARE|CAREER|CAREERS|CARS|CARTIER|CASA|CASH|CASINO|CAT|CATERING|CBA|CBN|CC|CD|CEB|CENTER|CEO|CERN|CF|CFA|CFD|CG|CH|CHANEL|CHANNEL|CHAT|CHEAP|CHLOE|CHRISTMAS|CHROME|CHURCH|CI|CIPRIANI|CIRCLE|CISCO|CITIC|CITY|CITYEATS|CK|CL|CLAIMS|CLEANING|CLICK|CLINIC|CLINIQUE|CLOTHING|CLOUD|CLUB|CLUBMED|CM|CN|CO|COACH|CODES|COFFEE|COLLEGE|COLOGNE|COM|COMMBANK|COMMUNITY|COMPANY|COMPARE|COMPUTER|COMSEC|CONDOS|CONSTRUCTION|CONSULTING|CONTACT|CONTRACTORS|COOKING|COOL|COOP|CORSICA|COUNTRY|COUPONS|COURSES|CR|CREDIT|CREDITCARD|CREDITUNION|CRICKET|CROWN|CRS|CRUISES|CSC|CU|CUISINELLA|CV|CW|CX|CY|CYMRU|CYOU|CZ|DABUR|DAD|DANCE|DATE|DATING|DATSUN|DAY|DCLK|DE|DEALER|DEALS|DEGREE|DELIVERY|DELL|DELTA|DEMOCRAT|DENTAL|DENTIST|DESI|DESIGN|DEV|DIAMONDS|DIET|DIGITAL|DIRECT|DIRECTORY|DISCOUNT|DJ|DK|DM|DNP|DO|DOCS|DOG|DOHA|DOMAINS|DOOSAN|DOWNLOAD|DRIVE|DUBAI|DURBAN|DVAG|DZ|EARTH|EAT|EC|EDEKA|EDU|EDUCATION|EE|EG|EMAIL|EMERCK|ENERGY|ENGINEER|ENGINEERING|ENTERPRISES|EPSON|EQUIPMENT|ER|ERNI|ES|ESQ|ESTATE|ET|EU|EUROVISION|EUS|EVENTS|EVERBANK|EXCHANGE|EXPERT|EXPOSED|EXPRESS|FAGE|FAIL|FAIRWINDS|FAITH|FAMILY|FAN|FANS|FARM|FASHION|FAST|FEEDBACK|FERRERO|FI|FILM|FINAL|FINANCE|FINANCIAL|FIRESTONE|FIRMDALE|FISH|FISHING|FIT|FITNESS|FJ|FK|FLIGHTS|FLORIST|FLOWERS|FLSMIDTH|FLY|FM|FO|FOO|FOOTBALL|FORD|FOREX|FORSALE|FORUM|FOUNDATION|FOX|FR|FRESENIUS|FRL|FROGANS|FUND|FURNITURE|FUTBOL|FYI|GA|GAL|GALLERY|GAME|GARDEN|GB|GBIZ|GD|GDN|GE|GEA|GENT|GENTING|GF|GG|GGEE|GH|GI|GIFT|GIFTS|GIVES|GIVING|GL|GLASS|GLE|GLOBAL|GLOBO|GM|GMAIL|GMO|GMX|GN|GOLD|GOLDPOINT|GOLF|GOO|GOOG|GOOGLE|GOP|GOT|GOV|GP|GQ|GR|GRAINGER|GRAPHICS|GRATIS|GREEN|GRIPE|GROUP|GS|GT|GU|GUCCI|GUGE|GUIDE|GUITARS|GURU|GW|GY|HAMBURG|HANGOUT|HAUS|HEALTH|HEALTHCARE|HELP|HELSINKI|HERE|HERMES|HIPHOP|HITACHI|HIV|HK|HM|HN|HOCKEY|HOLDINGS|HOLIDAY|HOMEDEPOT|HOMES|HONDA|HORSE|HOST|HOSTING|HOTELES|HOTMAIL|HOUSE|HOW|HR|HSBC|HT|HU|HYUNDAI|IBM|ICBC|ICE|ICU|ID|IE|IFM|IINET|IL|IM|IMMO|IMMOBILIEN|IN|INDUSTRIES|INFINITI|INFO|ING|INK|INSTITUTE|INSURANCE|INSURE|INT|INTERNATIONAL|INVESTMENTS|IO|IPIRANGA|IQ|IR|IRISH|IS|ISELECT|IST|ISTANBUL|IT|ITAU|IWC|JAGUAR|JAVA|JCB|JE|JETZT|JEWELRY|JLC|JLL|JM|JMP|JO|JOBS|JOBURG|JOT|JOY|JP|JPRS|JUEGOS|KAUFEN|KDDI|KE|KFH|KG|KH|KI|KIA|KIM|KINDER|KITCHEN|KIWI|KM|KN|KOELN|KOMATSU|KP|KPN|KR|KRD|KRED|KW|KY|KYOTO|KZ|LA|LACAIXA|LAMBORGHINI|LAMER|LANCASTER|LAND|LANDROVER|LANXESS|LASALLE|LAT|LATROBE|LAW|LAWYER|LB|LC|LDS|LEASE|LECLERC|LEGAL|LEXUS|LGBT|LI|LIAISON|LIDL|LIFE|LIFEINSURANCE|LIFESTYLE|LIGHTING|LIKE|LIMITED|LIMO|LINCOLN|LINDE|LINK|LIVE|LIVING|LIXIL|LK|LOAN|LOANS|LOL|LONDON|LOTTE|LOTTO|LOVE|LR|LS|LT|LTD|LTDA|LU|LUPIN|LUXE|LUXURY|LV|LY|MA|MADRID|MAIF|MAISON|MAKEUP|MAN|MANAGEMENT|MANGO|MARKET|MARKETING|MARKETS|MARRIOTT|MBA|MC|MD|ME|MED|MEDIA|MEET|MELBOURNE|MEME|MEMORIAL|MEN|MENU|MEO|MG|MH|MIAMI|MICROSOFT|MIL|MINI|MK|ML|MM|MMA|MN|MO|MOBI|MOBILY|MODA|MOE|MOI|MOM|MONASH|MONEY|MONTBLANC|MORMON|MORTGAGE|MOSCOW|MOTORCYCLES|MOV|MOVIE|MOVISTAR|MP|MQ|MR|MS|MT|MTN|MTPC|MTR|MU|MUSEUM|MUTUELLE|MV|MW|MX|MY|MZ|NA|NADEX|NAGOYA|NAME|NAVY|NC|NE|NEC|NET|NETBANK|NETWORK|NEUSTAR|NEW|NEWS|NEXUS|NF|NG|NGO|NHK|NI|NICO|NINJA|NISSAN|NL|NO|NOKIA|NORTON|NOWRUZ|NP|NR|NRA|NRW|NTT|NU|NYC|NZ|OBI|OFFICE|OKINAWA|OM|OMEGA|ONE|ONG|ONL|ONLINE|OOO|ORACLE|ORANGE|ORG|ORGANIC|ORIGINS|OSAKA|OTSUKA|OVH|PA|PAGE|PAMPEREDCHEF|PANERAI|PARIS|PARS|PARTNERS|PARTS|PARTY|PE|PET|PF|PG|PH|PHARMACY|PHILIPS|PHOTO|PHOTOGRAPHY|PHOTOS|PHYSIO|PIAGET|PICS|PICTET|PICTURES|PID|PIN|PING|PINK|PIZZA|PK|PL|PLACE|PLAY|PLAYSTATION|PLUMBING|PLUS|PM|PN|POHL|POKER|PORN|POST|PR|PRAXI|PRESS|PRO|PROD|PRODUCTIONS|PROF|PROMO|PROPERTIES|PROPERTY|PROTECTION|PS|PT|PUB|PW|PY|QA|QPON|QUEBEC|RACING|RE|READ|REALTOR|REALTY|RECIPES|RED|REDSTONE|REDUMBRELLA|REHAB|REISE|REISEN|REIT|REN|RENT|RENTALS|REPAIR|REPORT|REPUBLICAN|REST|RESTAURANT|REVIEW|REVIEWS|REXROTH|RICH|RICOH|RIO|RIP|RO|ROCHER|ROCKS|RODEO|ROOM|RS|RSVP|RU|RUHR|RUN|RW|RWE|RYUKYU|SA|SAARLAND|SAFE|SAFETY|SAKURA|SALE|SALON|SAMSUNG|SANDVIK|SANDVIKCOROMANT|SANOFI|SAP|SAPO|SARL|SAS|SAXO|SB|SBS|SC|SCA|SCB|SCHAEFFLER|SCHMIDT|SCHOLARSHIPS|SCHOOL|SCHULE|SCHWARZ|SCIENCE|SCOR|SCOT|SD|SE|SEAT|SECURITY|SEEK|SELECT|SENER|SERVICES|SEVEN|SEW|SEX|SEXY|SFR|SG|SH|SHARP|SHELL|SHIA|SHIKSHA|SHOES|SHOW|SHRIRAM|SI|SINGLES|SITE|SJ|SK|SKI|SKIN|SKY|SKYPE|SL|SM|SMILE|SN|SNCF|SO|SOCCER|SOCIAL|SOFTBANK|SOFTWARE|SOHU|SOLAR|SOLUTIONS|SONY|SOY|SPACE|SPIEGEL|SPREADBETTING|SR|SRL|ST|STADA|STAR|STARHUB|STATEFARM|STATOIL|STC|STCGROUP|STOCKHOLM|STORAGE|STUDIO|STUDY|STYLE|SU|SUCKS|SUPPLIES|SUPPLY|SUPPORT|SURF|SURGERY|SUZUKI|SV|SWATCH|SWISS|SX|SY|SYDNEY|SYMANTEC|SYSTEMS|SZ|TAB|TAIPEI|TAOBAO|TATAMOTORS|TATAR|TATTOO|TAX|TAXI|TC|TCI|TD|TEAM|TECH|TECHNOLOGY|TEL|TELEFONICA|TEMASEK|TENNIS|TF|TG|TH|THD|THEATER|THEATRE|TICKETS|TIENDA|TIFFANY|TIPS|TIRES|TIROL|TJ|TK|TL|TM|TMALL|TN|TO|TODAY|TOKYO|TOOLS|TOP|TORAY|TOSHIBA|TOURS|TOWN|TOYOTA|TOYS|TR|TRADE|TRADING|TRAINING|TRAVEL|TRAVELERS|TRAVELERSINSURANCE|TRUST|TRV|TT|TUBE|TUI|TUSHU|TV|TW|TZ|UA|UBS|UG|UK|UNIVERSITY|UNO|UOL|US|UY|UZ|VA|VACATIONS|VANA|VC|VE|VEGAS|VENTURES|VERISIGN|VERSICHERUNG|VET|VG|VI|VIAJES|VIDEO|VILLAS|VIN|VIP|VIRGIN|VISION|VISTA|VISTAPRINT|VIVA|VLAANDEREN|VN|VODKA|VOLKSWAGEN|VOTE|VOTING|VOTO|VOYAGE|VU|WALES|WALTER|WANG|WANGGOU|WATCH|WATCHES|WEATHER|WEBCAM|WEBER|WEBSITE|WED|WEDDING|WEIR|WF|WHOSWHO|WIEN|WIKI|WILLIAMHILL|WIN|WINDOWS|WINE|WME|WORK|WORKS|WORLD|WS|WTC|WTF|XBOX|XEROX|XIN|XN--11B4C3D|XN--1QQW23A|XN--30RR7Y|XN--3BST00M|XN--3DS443G|XN--3E0B707E|XN--3PXU8K|XN--42C2D9A|XN--45BRJ9C|XN--45Q11C|XN--4GBRIM|XN--55QW42G|XN--55QX5D|XN--6FRZ82G|XN--6QQ986B3XL|XN--80ADXHKS|XN--80AO21A|XN--80ASEHDB|XN--80ASWG|XN--90A3AC|XN--90AIS|XN--9DBQ2A|XN--9ET52U|XN--B4W605FERD|XN--C1AVG|XN--C2BR7G|XN--CG4BKI|XN--CLCHC0EA0B2G2A9GCD|XN--CZR694B|XN--CZRS0T|XN--CZRU2D|XN--D1ACJ3B|XN--D1ALF|XN--ECKVDTC9D|XN--EFVY88H|XN--ESTV75G|XN--FHBEI|XN--FIQ228C5HS|XN--FIQ64B|XN--FIQS8S|XN--FIQZ9S|XN--FJQ720A|XN--FLW351E|XN--FPCRJ9C3D|XN--FZC2C9E2C|XN--G2XX48C|XN--GECRJ9C|XN--H2BRJ9C|XN--HXT814E|XN--I1B6B1A6A2E|XN--IMR513N|XN--IO0A7I|XN--J1AEF|XN--J1AMH|XN--J6W193G|XN--JLQ61U9W7B|XN--KCRX77D1X4A|XN--KPRW13D|XN--KPRY57D|XN--KPU716F|XN--KPUT3I|XN--L1ACC|XN--LGBBAT1AD8J|XN--MGB9AWBF|XN--MGBA3A3EJT|XN--MGBA3A4F16A|XN--MGBAAM7A8H|XN--MGBAB2BD|XN--MGBAYH7GPA|XN--MGBB9FBPOB|XN--MGBBH1A71E|XN--MGBC0A9AZCG|XN--MGBERP4A5D4AR|XN--MGBPL2FH|XN--MGBT3DHD|XN--MGBTX2B|XN--MGBX4CD0AB|XN--MK1BU44C|XN--MXTQ1M|XN--NGBC5AZD|XN--NGBE9E0A|XN--NODE|XN--NQV7F|XN--NQV7FS00EMA|XN--NYQY26A|XN--O3CW4H|XN--OGBPF8FL|XN--P1ACF|XN--P1AI|XN--PBT977C|XN--PGBS0DH|XN--PSSY2U|XN--Q9JYB4C|XN--QCKA1PMC|XN--QXAM|XN--RHQV96G|XN--S9BRJ9C|XN--SES554G|XN--T60B56A|XN--TCKWE|XN--UNUP4Y|XN--VERMGENSBERATER-CTB|XN--VERMGENSBERATUNG-PWB|XN--VHQUV|XN--VUQ861B|XN--WGBH1C|XN--WGBL6A|XN--XHQ521B|XN--XKC2AL3HYE2A|XN--XKC2DL3A5EE0H|XN--Y9A3AQ|XN--YFRO4I67O|XN--YGBI2AMMX|XN--ZFR164B|XPERIA|XXX|XYZ|YACHTS|YAMAXUN|YANDEX|YE|YODOBASHI|YOGA|YOKOHAMA|YOUTUBE|YT|ZA|ZARA|ZERO|ZIP|ZM|ZONE|ZUERICH|ZW)\\b\n</code></pre>\n<p>That easily discarded emails like <code>[email protected], [email protected]</code>, etc.</p>\n<p>The domain name can be further edited if needed, e.g., specific country domain, etc.</p>\n<p>Another <a href=\"https://data.iana.org/TLD/tlds-alpha-by-domain.txt\" rel=\"nofollow noreferrer\">list</a> of top level domains that updates frequently.</p>\n"
},
{
"answer_id": 32669200,
"author": "syp_dino",
"author_id": 2165131,
"author_profile": "https://Stackoverflow.com/users/2165131",
"pm_score": 1,
"selected": false,
"text": "<p>I found a <a href=\"http://davidcel.is/posts/stop-validating-email-addresses-with-regex/\" rel=\"nofollow noreferrer\">nice article</a>, which says that the best way to validate e-mail address is the regular expression <code>/.+@.+\\..+/i</code>.</p>\n"
},
{
"answer_id": 41129750,
"author": "FlameStorm",
"author_id": 1848217,
"author_profile": "https://Stackoverflow.com/users/1848217",
"pm_score": 2,
"selected": false,
"text": "<p>For me the right way for checking email addresses is:</p>\n<ol>\n<li>Check that symbol @ exists, and before and after it there are some non-@ symbols: <code> /^[^@]+@[^@]+$/</code></li>\n<li>Try to send an email to this address with some "activation code".</li>\n<li>When the user "activated" his/her email address, we will see that all is right.</li>\n</ol>\n<p>Of course, you can show some warning or tooltip in front-end when the user typed a "strange" email to help him/her to avoid common mistakes, like no dot in the domain part or spaces in name without quoting and so on. But you must accept the address "hello@world" if user really want it.</p>\n<p>Also, you must remember that the email address standard was and can evolve, so you can't just type some "standard-valid" regexp once and for all times. And you must remember that some concrete internet servers can fail some details of common standard and in fact work with own "modified standard".</p>\n<p>So, just check @, hint user on frontend and send verification emails on the given address.</p>\n"
},
{
"answer_id": 41359876,
"author": "Prassd Nidode",
"author_id": 5815954,
"author_profile": "https://Stackoverflow.com/users/5815954",
"pm_score": 2,
"selected": false,
"text": "<p>List item</p>\n<p>I use this function</p>\n<pre class=\"lang-php prettyprint-override\"><code>function checkmail($value) {\n $value = trim($value);\n if (stristr($value,"@") &&\n stristr($value,".") &&\n (strrpos($value, ".") - stripos($value, "@") > 2) &&\n (stripos($value, "@") > 1) &&\n (strlen($value) - strrpos($value, ".") < 6) &&\n (strlen($value) - strrpos($value, ".") > 2) &&\n ($value == preg_replace('/[ ]/', '', $value)) &&\n ($value == preg_replace('/[^A-Za-z0-9\\-_.@!*]/', '', $value))\n )\n {\n\n }\n else {\n return "Invalid Mail-Id";\n }\n}\n</code></pre>\n"
},
{
"answer_id": 42149701,
"author": "Simon_Weaver",
"author_id": 16940,
"author_profile": "https://Stackoverflow.com/users/16940",
"pm_score": 2,
"selected": false,
"text": "<p>Just about every regular expression I've seen - including some used by Microsoft will not allow the following <em>valid</em> email to get through: <code>[email protected]</code></p>\n<p>I just had a real customer with an email address in this format who couldn't place an order.</p>\n<p>Here's what I settled on:</p>\n<ul>\n<li>A minimal regular expression that won't have false negatives. Alternatively use the <code>MailAddress</code> constructor with some additional checks (see below):</li>\n<li>Checking for common typos <code>.cmo</code> or <code>.gmial.com</code> and asking for confirmation <em>"Are you sure this is your correct email address. It looks like there may be a mistake."</em> Allow the user to accept what they typed if they are sure.</li>\n<li>Handling bounces when the email is actually sent and manually verifying them to check for obvious mistakes.</li>\n</ul>\n<hr />\n<pre><code>try\n{\n var email = new MailAddress(str);\n\n if (email.Host.EndsWith(".cmo"))\n {\n return EmailValidation.PossibleTypo;\n }\n\n if (!email.Host.EndsWith(".") && email.Host.Contains("."))\n {\n return EmailValidation.OK;\n }\n}\ncatch\n{\n return EmailValidation.Invalid;\n}\n</code></pre>\n"
},
{
"answer_id": 46445787,
"author": "Hany Sakr",
"author_id": 4619784,
"author_profile": "https://Stackoverflow.com/users/4619784",
"pm_score": 1,
"selected": false,
"text": "<p>I converted the code into Java to match the compiler:</p>\n<pre class=\"lang-java prettyprint-override\"><code>String pattern = "(?:[a-zA-Z0-9!#$%&'*+/=?^_`{|}~-]+(?:\\\\.[a-zA-Z0-9!#$%&'*+/=?^_`{|}~-]+)*|\\"(?:[\\\\x01-\\\\x08\\\\x0b\\\\x0c\\\\x0e-\\\\x1f\\\\x21\\\\x23-\\\\x5b\\\\x5d-\\\\x7f]|\\\\\\\\[\\\\x01-\\\\x09\\\\x0b\\\\x0c\\\\x0e-\\\\x7f])*\\")@(?:(?:[a-zA-Z0-9](?:[a-zA-Z0-9-]*[a-zA-Z0-9])?\\\\.)+[a-zA-Z0-9](?:[a-zA-Z0-9-]*[a-zA-Z0-9])?|\\\\[(?:(?:(2(5[0-5]|[0-4][0-9])|1[0-9][0-9]|[1-9]?[0-9]))\\\\.){3}(?:(2(5[0-5]|[0-4][0-9])|1[0-9][0-9]|[1-9]?[0-9])|[a-zA-Z0-9-]*[a-zA-Z0-9]:(?:[\\\\x01-\\\\x08\\\\x0b\\\\x0c\\\\x0e-\\\\x1f\\\\x21-\\\\x5a\\\\x53-\\\\x7f]|\\\\\\\\[\\\\x01-\\\\x09\\\\x0b\\\\x0c\\\\x0e-\\\\x7f])+)\\\\])";\n</code></pre>\n"
},
{
"answer_id": 51332395,
"author": "Dave Black",
"author_id": 251267,
"author_profile": "https://Stackoverflow.com/users/251267",
"pm_score": 2,
"selected": false,
"text": "<p>According to <a href=\"http://tools.ietf.org/html/2821\" rel=\"nofollow noreferrer\">RFC 2821</a> and <a href=\"http://tools.ietf.org/html/2822\" rel=\"nofollow noreferrer\">RFC 2822</a>, the local-part of an email addresses may use any of these ASCII characters:</p>\n<ol>\n<li>Uppercase and lowercase letters</li>\n<li>The digits 0 through 9</li>\n<li>The characters, !#$%&'*+-/=?^_`{|}~</li>\n<li>The character "." provided that it is not the first or last character in the local-part.</li>\n</ol>\n<p>Matches:</p>\n<ul>\n<li>a&[email protected]</li>\n<li>a*[email protected]</li>\n<li>a/[email protected]</li>\n</ul>\n<p>Non-Matches:</p>\n<ul>\n<li>[email protected]</li>\n<li>[email protected]</li>\n<li>a>[email protected]</li>\n</ul>\n<p>For one that is RFC 2821 and 2822 compliant, you can use:</p>\n<pre class=\"lang-none prettyprint-override\"><code>^((([!#$%&'*+\\-/=?^_`{|}~\\w])|([!#$%&'*+\\-/=?^_`{|}~\\w][!#$%&'*+\\-/=?^_`{|}~\\.\\w]{0,}[!#$%&'*+\\-/=?^_`{|}~\\w]))[@]\\w+([-.]\\w+)*\\.\\w+([-.]\\w+)*)$\n</code></pre>\n<p><a href=\"http://regexlib.com/REDetails.aspx?regexp_id=2558\" rel=\"nofollow noreferrer\">Email - RFC 2821, 2822 Compliant</a></p>\n"
},
{
"answer_id": 53151299,
"author": "Savas Adar",
"author_id": 793880,
"author_profile": "https://Stackoverflow.com/users/793880",
"pm_score": -1,
"selected": false,
"text": "<p>I use this;</p>\n<pre class=\"lang-none prettyprint-override\"><code>^(([^<>()\\[\\]\\\\.,;:\\s@"]+(\\.[^<>()\\[\\]\\\\.,;:\\s@"]+)*)|(".+"))@((\\[[0-9]{1,3}\\.[0-9]{1,3}\\.[0-9]{1,3}\\.[0-9]{1,3}])|(([a-zA-Z\\-0-9]+\\.)+[a-zA-Z]{2,}))$\n</code></pre>\n"
},
{
"answer_id": 55109472,
"author": "Carli B",
"author_id": 6698988,
"author_profile": "https://Stackoverflow.com/users/6698988",
"pm_score": -1,
"selected": false,
"text": "<p>For Angular2 / Angular7 I use this pattern:</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>emailPattern = '^[a-zA-Z0-9_.+-]+@[a-zA-Z0-9-]+[.]+[a-zA-Z0-9-.]+(\\\\s)*';\r\n\r\nprivate createForm() {\r\n this.form = this.formBuilder.group({\r\n email: ['', [Validators.required, Validators.pattern(this.emailPattern)]]\r\n });\r\n}</code></pre>\r\n</div>\r\n</div>\r\n</p>\n\n<p>It also allows for extra spaces at the end, which you should truncate before sending it to the backend, but some users, especially on mobile are easy to mistakenly add a space at the end.</p>\n"
},
{
"answer_id": 55885412,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": -1,
"selected": false,
"text": "<p>Email regex (RFC 5322)</p>\n<pre class=\"lang-none prettyprint-override\"><code>(?im)^(?=.{1,64}@)(?:("[^"\\\\]*(?:\\\\.[^"\\\\]*)*"@)|((?:[0-9a-z](?:\\.(?!\\.)|[-!#\\$%&'\\*\\+/=\\?\\^`\\{\\}\\|~\\w])*)?[0-9a-z]@))(?=.{1,255}$)(?:(\\[(?:\\d{1,3}\\.){3}\\d{1,3}\\])|((?:(?=.{1,63}\\.)[0-9a-z][-\\w]*[0-9a-z]*\\.)+[a-z0-9][\\-a-z0-9]{0,22}[a-z0-9])|((?=.{1,63}$)[0-9a-z][-\\w]*))$\n</code></pre>\n<p>Demo <a href=\"https://regex101.com/r/ObS3QZ/1\" rel=\"nofollow noreferrer\">https://regex101.com/r/ObS3QZ/1</a></p>\n<pre class=\"lang-none prettyprint-override\"><code># (?im)^(?=.{1,64}@)(?:("[^"\\\\]*(?:\\\\.[^"\\\\]*)*"@)|((?:[0-9a-z](?:\\.(?!\\.)|[-!#\\$%&'\\*\\+/=\\?\\^`\\{\\}\\|~\\w])*)?[0-9a-z]@))(?=.{1,255}$)(?:(\\[(?:\\d{1,3}\\.){3}\\d{1,3}\\])|((?:(?=.{1,63}\\.)[0-9a-z][-\\w]*[0-9a-z]*\\.)+[a-z0-9][\\-a-z0-9]{0,22}[a-z0-9])|((?=.{1,63}$)[0-9a-z][-\\w]*))$\n\n# Note - remove all comments '(comments)' before running this regex\n# Find \\([^)]*\\) replace with nothing\n\n(?im) # Case insensitive\n^ # BOS\n\n # Local part\n(?= .{1,64} @ ) # 64 max chars\n(?:\n ( # (1 start), Quoted\n " [^"\\\\]*\n (?: \\\\ . [^"\\\\]* )*\n "\n @\n ) # (1 end)\n | # or,\n ( # (2 start), Non-quoted\n (?:\n [0-9a-z]\n (?:\n \\.\n (?! \\. )\n | # or,\n [-!#\\$%&'\\*\\+/=\\?\\^`\\{\\}\\|~\\w]\n )*\n )?\n [0-9a-z]\n @\n ) # (2 end)\n)\n # Domain part\n(?= .{1,255} $ ) # 255 max chars\n(?:\n ( # (3 start), IP\n \\[\n (?: \\d{1,3} \\. ){3}\n \\d{1,3} \\]\n ) # (3 end)\n | # or,\n ( # (4 start), Others\n (?: # Labels (63 max chars each)\n (?= .{1,63} \\. )\n [0-9a-z] [-\\w]* [0-9a-z]*\n \\.\n )+\n [a-z0-9] [\\-a-z0-9]{0,22} [a-z0-9]\n ) # (4 end)\n | # or,\n ( # (5 start), Localdomain\n (?= .{1,63} $ )\n [0-9a-z] [-\\w]*\n ) # (5 end)\n)\n$ # EOS\n</code></pre>\n"
},
{
"answer_id": 56562639,
"author": "partoftheorigin",
"author_id": 6017440,
"author_profile": "https://Stackoverflow.com/users/6017440",
"pm_score": 2,
"selected": false,
"text": "<p>Writing a regular expression for all the things will take a lot of effort. Instead, you can use <a href=\"https://pypi.org/project/pyIsEmail/\" rel=\"nofollow noreferrer\">pyIsEmail</a> package.</p>\n<p>Below text is taken from <a href=\"https://pypi.org/project/pyIsEmail/\" rel=\"nofollow noreferrer\">pyIsEmail</a> website.</p>\n<p>pyIsEmail is a no-nonsense approach for checking whether that user-supplied email address could be real.</p>\n<p>Regular expressions are cheap to write, but often require maintenance when new top-level domains come out or don’t conform to email addressing features that come back into vogue. pyIsEmail allows you to validate an email address – and even check the domain, if you wish – with one simple call, making your code more readable and faster to write. When you want to know why an email address doesn’t validate, they even provide you with a diagnosis.</p>\n<h2>Usage</h2>\n<p>For the simplest usage, import and use the is_email function:</p>\n<pre><code>from pyisemail import is_email\n\naddress = "[email protected]"\nbool_result = is_email(address)\ndetailed_result = is_email(address, diagnose=True)\n</code></pre>\n<p>You can also check whether the domain used in the email is a valid domain and whether or not it has a valid <a href=\"https://en.wikipedia.org/wiki/MX_record\" rel=\"nofollow noreferrer\">MX record</a>:</p>\n<pre><code>from pyisemail import is_email\n\naddress = "[email protected]"\nbool_result_with_dns = is_email(address, check_dns=True)\ndetailed_result_with_dns = is_email(address, check_dns=True, diagnose=True)\n</code></pre>\n<p>These are primary indicators of whether an email address can even be issued at that domain. However, a valid response here is not a guarantee that the email exists, merely that is can exist.</p>\n<p>In addition to the base <em>is_email</em> functionality, you can also use the validators by themselves. Check the validator source doc to see how this works.</p>\n"
},
{
"answer_id": 58786483,
"author": "Asad Ali Choudhry",
"author_id": 5701085,
"author_profile": "https://Stackoverflow.com/users/5701085",
"pm_score": 2,
"selected": false,
"text": "<p>Although very detailed answers are already added, I think those are complex enough for a developer who is just looking for a simple method to validate an email address or to get all email addresses from a string in Java.</p>\n<pre><code>public static boolean isEmailValid(@NonNull String email) {\n return android.util.Patterns.EMAIL_ADDRESS.matcher(email).matches();\n}\n</code></pre>\n<p>As per the regular expression is concerned, I always use this regular expression, which works for my problems.</p>\n<pre class=\"lang-none prettyprint-override\"><code>"[A-Z0-9a-z._%+-]+@[A-Za-z0-9.-]+\\.[A-Za-z]{2,6}"\n</code></pre>\n<p>If you are looking to find all email addresses from a string by matching the email regular expression. You can find a method at <a href=\"https://handyopinion.com/utility-method-to-get-all-email-addresses-from-a-string-in-java/\" rel=\"nofollow noreferrer\">this link</a>.</p>\n"
},
{
"answer_id": 63295767,
"author": "Dreamray",
"author_id": 11421834,
"author_profile": "https://Stackoverflow.com/users/11421834",
"pm_score": -1,
"selected": false,
"text": "<p>Maybe the best:</p>\n<pre><code>/^[a-zA-Z0-9]+([-._][a-zA-Z0-9]+)*@[a-zA-Z0-9]+([-.][a-zA-Z0-9]+)*\\.[a-zA-Z]{2,7}$/\n</code></pre>\n<p>Start with a letter or number. It may include "-_ .", end with "." and less than seven characters (such as <em>.company</em>).</p>\n"
},
{
"answer_id": 63841473,
"author": "awwright",
"author_id": 7117939,
"author_profile": "https://Stackoverflow.com/users/7117939",
"pm_score": 3,
"selected": false,
"text": "<p>The regular expression for an email address is:</p>\n<pre class=\"lang-none prettyprint-override\"><code>/^("(?:[!#-\\[\\]-\\u{10FFFF}]|\\\\[\\t -\\u{10FFFF}])*"|[!#-'*+\\-/-9=?A-Z\\^-\\u{10FFFF}](?:\\.?[!#-'*+\\-/-9=?A-Z\\^-\\u{10FFFF}])*)@([!#-'*+\\-/-9=?A-Z\\^-\\u{10FFFF}](?:\\.?[!#-'*+\\-/-9=?A-Z\\^-\\u{10FFFF}])*|\\[[!-Z\\^-\\u{10FFFF}]*\\])$/u\n</code></pre>\n<p>This regular expression is 100% identical to the <code>addr-spec</code> <a href=\"https://en.wikipedia.org/wiki/Augmented_Backus%E2%80%93Naur_form\" rel=\"nofollow noreferrer\">ABNF</a> for non-obsolete email addresses, as specified across <a href=\"https://www.rfc-editor.org/rfc/rfc5321#section-4.5.3.1\" rel=\"nofollow noreferrer\">RFC 5321</a>, <a href=\"https://www.rfc-editor.org/rfc/rfc5322#section-3.4.1\" rel=\"nofollow noreferrer\">RFC 5322</a>, and <a href=\"https://www.rfc-editor.org/rfc/rfc6532#section-3.2\" rel=\"nofollow noreferrer\">RFC 6532</a>.</p>\n<p>Additionally, you must verify:</p>\n<ul>\n<li>The email address is well-formed UTF-8 (or ASCII, if you cannot send to internationalized email addresses)</li>\n<li>The address is not more than 320 UTF-8 bytes</li>\n<li>The user part (the first match group) is not more than 64 UTF-8 bytes</li>\n<li>The domain part (the second match group) is not more than 255 UTF-8 bytes</li>\n</ul>\n<p>The easiest way to do all of this is to use an existing function. In PHP, see the <a href=\"https://www.php.net/manual/en/function.filter-var\" rel=\"nofollow noreferrer\">filter_var</a> function using <code>FILTER_VALIDATE_EMAIL</code> and <code>FILTER_FLAG_EMAIL_UNICODE</code> (if you can send to internationalized email addresses):</p>\n<pre><code>$email_valid = filter_var($email_input, FILTER_VALIDATE_EMAIL, FILTER_FLAG_EMAIL_UNICODE);\n</code></pre>\n<p>However, maybe you're building such a function—indeed the easiest way to implement this is to use a regular expression.</p>\n<p>Remember, this only verifies that the email address will not cause a syntax error. The only way to verify that the address can receive email is to <em>actually</em> send an email.</p>\n<p>Next, I will treat how you generate this regular expression.</p>\n<hr />\n<p>I write a new answer, because most of the answers here make the mistake of either specifying a pattern that is too restrictive (and so have not aged well); or they present a regular expression that's actually matching a header for a <a href=\"https://en.wikipedia.org/wiki/MIME\" rel=\"nofollow noreferrer\">MIME</a> message, and not the email address itself.</p>\n<p>It is entirely possible to make a regular expression from an ABNF, so long as there are no recursive parts.</p>\n<p>RFC 5322 specifies what is legal to send in a MIME message; consider this the upper bound on what is a legal email address.</p>\n<p>However, to follow this ABNF exactly would be a mistake: this pattern technically represents how you encode an email address <em>in a MIME message</em>, and allows strings not part of the email address, like folding whitespace and comments; and it includes support for obsolete forms that are not legal to generate (but that servers read for historical reasons). An email address does not include these.</p>\n<p>RFC 5322 explains:</p>\n<blockquote>\n<p>Both atom and dot-atom are interpreted as a single unit, comprising\nthe string of characters that make it up. Semantically, the optional\ncomments and FWS surrounding the rest of the characters are not part\nof the atom; the atom is only the run of atext characters in an atom,\nor the atext and "." characters in a dot-atom.</p>\n</blockquote>\n<blockquote>\n<p>In some of the definitions, there will be non-terminals whose names\nstart with "obs-". These "obs-" elements refer to tokens defined in\nthe obsolete syntax in section 4. In all cases, these productions\nare to be ignored for the purposes of generating legal Internet\nmessages and MUST NOT be used as part of such a message.</p>\n</blockquote>\n<p>If you remove <code>CFWS</code>, <code>BWS</code>, and <code>obs-*</code> rules from the <code>addr-spec</code> in RFC 5322, and perform some optimization on the result (I used <a href=\"https://github.com/qntm/greenery\" rel=\"nofollow noreferrer\">"greenery"</a>), you can produce this regular expression, quoted with slashes and anchored (suitable for use in ECMAScript and compatible dialects, with added newline for clarity):</p>\n<pre class=\"lang-none prettyprint-override\"><code>/^("(?:[!#-\\[\\]-~]|\\\\[\\t -~])*"|[!#-'*+\\-/-9=?A-Z\\^-~](?:\\.?[!#-'*+\\-/-9=?A-Z\\^-~])*)\n@([!#-'*+\\-/-9=?A-Z\\^-~](?:\\.?[!#-'*+\\-/-9=?A-Z\\^-~])*|\\[[!-Z\\^-~]*\\])$/\n</code></pre>\n<p>This only supports ASCII email addresses. To support <a href=\"https://www.rfc-editor.org/rfc/rfc6532#section-3.2\" rel=\"nofollow noreferrer\">RFC 6532 Internationalized Email Addresses</a>, replace the <code>~</code> character with <code>\\u{10FFFF}</code> (PHP, ECMAScript with the <code>u</code> flag), or <code>\\uFFFF</code> (for UTF-16 implementations, like <a href=\"https://en.wikipedia.org/wiki/.NET_Framework\" rel=\"nofollow noreferrer\">.NET</a> and older ECMAScript/JavaScript):</p>\n<pre class=\"lang-none prettyprint-override\"><code>/^("(?:[!#-\\[\\]-\\u{10FFFF}]|\\\\[\\t -\\u{10FFFF}])*"|[!#-'*+\\-/-9=?A-Z\\^-\\u{10FFFF}](?:\\.?[!#-'*+\\-/-9=?A-Z\\^-\\u{10FFFF}])*)@([!#-'*+\\-/-9=?A-Z\\^-\\u{10FFFF}](?:\\.?[!#-'*+\\-/-9=?A-Z\\^-\\u{10FFFF}])*|\\[[!-Z\\^-\\u{10FFFF}]*\\])$/u\n</code></pre>\n<p>This works, because the ABNF we are using is not recursive, and so forms a non-recursive, regular grammar that can be converted into a regular expression.</p>\n<p>It breaks down like so:</p>\n<ul>\n<li>The user part (before the <code>@</code>) may be a dot-atom or a quoted-string</li>\n<li><code>"([!#-\\[\\]-~]|\\\\[\\t -~])*"</code> specifies the quoted-string form of the user, e.g. <code>"root@home"@example.com</code>. It permits any non-control character inside double quotes; except that spaces, tabs, double quotes, and backslashes must be backslash-escaped.</li>\n<li><code>[!#-'*+\\-/-9=?A-Z\\^-~]</code> is the first character of the dot-atom of the user.</li>\n<li><code>(\\.?[!#-'*+\\-/-9=?A-Z\\^-~])*</code> matches the rest of the dot-atom, allowing dots (except after another dot, or as the final character).</li>\n<li><code>@</code> denotes the domain.</li>\n<li>The domain part may be a dot-atom or a domain-literal.</li>\n<li><code>[!#-'*+\\-/-9=?A-Z\\^-~](\\.?[!#-'*+\\-/-9=?A-Z\\^-~])*</code> is the same dot-atom form as above, but here it represents domain names and IPv4 addresses.</li>\n<li><code>\\[[!-Z\\^-~]*\\]</code> will match IPv6 addresses and future definitions of host names.</li>\n</ul>\n<p>This regular expression allows all specification-compliant email addresses, and can be used verbatim in a MIME message (except for line length limits, in which case folding whitespace must be added).</p>\n<p>This also sets non-capturing groups such that <code>match[1]</code> will be the user, <code>match[2]</code> will be the host. (However if <code>match[1]</code> starts with a double quote, then filter out backslash escapes, and the start and end double quotes: <code>"root"@example.com</code> and <code>[email protected]</code> identify the same inbox.)</p>\n<p>Finally, note that <a href=\"https://www.rfc-editor.org/rfc/rfc5321#section-4.5.3.1\" rel=\"nofollow noreferrer\">RFC 5321</a> sets limits on how long an email address may be. The user part may be up to 64 bytes, and the domain part may be up to 255 bytes. Including the <code>@</code> character, the limit for the entire address is 320 bytes. This is measured in bytes after the address is UTF-8 encoded; not characters.</p>\n<p>Note that RFC 5322 ABNF defines a permissive syntax for domain names, allowing names currently known to be invalid. This also allows for domain names that could become legal in the future. This should not be a problem, as this should be handled the same way a non-existent domain name is.</p>\n<p>Always consider the possibility that a user typed in an email address that works, but that they do not have access to. <em>The only foolproof way to verify an email address is to send an email.</em></p>\n<p><sub>This is adapted from my article <em><a href=\"https://fullstack.wiki/mail/address\" rel=\"nofollow noreferrer\">E-Mail Addresses & Syntax</a></em>.</sub></p>\n"
},
{
"answer_id": 64162842,
"author": "Andriy B.",
"author_id": 4564046,
"author_profile": "https://Stackoverflow.com/users/4564046",
"pm_score": -1,
"selected": false,
"text": "<p>This simple pattern works for me:</p>\n<pre class=\"lang-none prettyprint-override\"><code>^(?<name>[^<>#()\\.,;\\s@\\"]{1,})@(?<domain>[^<>#()\\.,;\\s@\\"]{2,}\\.(?<top>[^<>#()\\.,;:\\s@\\"]{2,}))$\n</code></pre>\n"
},
{
"answer_id": 66244914,
"author": "alejandro juarez",
"author_id": 10582300,
"author_profile": "https://Stackoverflow.com/users/10582300",
"pm_score": 2,
"selected": false,
"text": "<p>If you need a simple form to validate, you can use the answer of <a href=\"https://regexr.com/3e48o\" rel=\"nofollow noreferrer\">https://regexr.com/3e48o</a></p>\n<pre class=\"lang-none prettyprint-override\"><code>^[\\w-\\.]+@([\\w-]+\\.)+[\\w-]{2,4}$\n</code></pre>\n<p><div class=\"snippet\" data-lang=\"js\" data-hide=\"true\" data-console=\"true\" data-babel=\"false\">\r\n<div class=\"snippet-code snippet-currently-hidden\">\r\n<pre class=\"snippet-code-js lang-js prettyprint-override\"><code>let r = new RegExp(String.raw `^[\\w-\\.]+@([\\w-]+\\.)+[\\w-]{2,4}$`);\n\n//should be true\nconsole.log(r.test('[email protected]'));\nconsole.log(r.test('[email protected]'));\nconsole.log(r.test('[email protected]'));\n\n//should be false\nconsole.log(r.test('@domain.tld'));\nconsole.log(r.test('[email protected]'));\nconsole.log(r.test('name@domain.'));\nconsole.log(r.test('namedomain.tld'));\nconsole.log(r.test(''));\n\n//now that basic client-side validation is done, send a token from the server side to validate the user actually has access to the email</code></pre>\r\n</div>\r\n</div>\r\n</p>\n"
},
{
"answer_id": 66854124,
"author": "GooDeeJAY",
"author_id": 8323650,
"author_profile": "https://Stackoverflow.com/users/8323650",
"pm_score": -1,
"selected": false,
"text": "<p>The regular expression that I use:</p>\n<pre class=\"lang-none prettyprint-override\"><code>[\\w-+]+([.][\\w]+)?@[\\w-+]+([.][a-z]{2,})+\n</code></pre>\n"
},
{
"answer_id": 67439425,
"author": "Craig",
"author_id": 525558,
"author_profile": "https://Stackoverflow.com/users/525558",
"pm_score": 0,
"selected": false,
"text": "<p>Yet another option we have is to use <code>DataAnnotations</code> which has an <code>EmailAddressAttribute</code>. This can not only be applied to the property of a class but can also leveraged at runtime.</p>\n<p><code>using System.ComponentModel.DataAnnotations;</code></p>\n<p><strong>Typical Usage</strong></p>\n<pre><code>public class Person\n{\n public int Id { get; set; }\n\n [EmailAddress]\n public string Email { get; set; }\n}\n</code></pre>\n<p><strong>At Runtime</strong></p>\n<pre><code>var emailAddressAttribute = new EmailAddressAttribute();\n\nif (emailAddressAttribute.IsValid("[email protected]"))\n{\n //email is valid\n}\nelse\n{\n //email is invalid\n}\n</code></pre>\n"
},
{
"answer_id": 68309817,
"author": "Tim Wißmann",
"author_id": 2707575,
"author_profile": "https://Stackoverflow.com/users/2707575",
"pm_score": 0,
"selected": false,
"text": "<p>For my purpose, I needed a way to also extract a display name if provided.<br />\nThanks to the other answers and the regex provided on <a href=\"https://emailregex.com/\" rel=\"nofollow noreferrer\">https://emailregex.com/</a> I came up with the following solution:</p>\n<pre class=\"lang-none prettyprint-override\"><code>/^(?:([^<]*?)\\s*<)?((?:[a-z0-9!#$%&'*+\\/=?^_`{|}~-]+(?:\\.[a-z0-9!#$%&'*+\\/=?^_`{|}~-]+)*|"(?:[\\x01-\\x08\\x0b\\x0c\\x0e-\\x1f\\x21\\x23-\\x5b\\x5d-\\x7f]|\\\\[\\x01-\\x09\\x0b\\x0c\\x0e-\\x7f])*")@(?:(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\\.)+[a-z0-9](?:[a-z0-9-]*[a-z0-9])?|\\[(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\\.){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?|[a-z0-9-]*[a-z0-9]:(?:[\\x01-\\x08\\x0b\\x0c\\x0e-\\x1f\\x21-\\x5a\\x53-\\x7f]|\\\\[\\x01-\\x09\\x0b\\x0c\\x0e-\\x7f])+)\\]))>?$/gi\n</code></pre>\n<p>This matches <strong>Display name (=group 1)</strong> + <strong>email address (=group 2)</strong>.</p>\n<p>Examples of matches:</p>\n<pre class=\"lang-none prettyprint-override\"><code>[email protected]\njohn.o'[email protected]\nJohn <[email protected]>\n<[email protected]>\nThis is <[email protected]>\n</code></pre>\n<p><em>Tested with <a href=\"https://regex101.com/\" rel=\"nofollow noreferrer\">https://regex101.com/</a></em></p>\n<p>Of course, as also mentioned in other answers, additional validation of the length of display name and email address is required (shouldn't exceed 320 UTF-8 bytes).</p>\n"
},
{
"answer_id": 72008375,
"author": "ThinkTrans",
"author_id": 15234493,
"author_profile": "https://Stackoverflow.com/users/15234493",
"pm_score": 0,
"selected": false,
"text": "<p>The question title is fairly generic, however the body of the question indicates that it is about the PHP based solution. Will try to address both.</p>\n<p><strong>Generically speaking, for all programming languages:</strong>\nTypically, validating" an e-mail address with a reg-ex is something that any internet based service provider should desist from. The possibilities of kinds of domain names and e-mail addresses have increased so much in terms of variety, any attempt at validation, which is not well thought may end up denying some valid users into your system. To avoid this, one of the best ways is to send an email to the user and verify it being received. The good folks at "<a href=\"https://uasg.tech/\" rel=\"nofollow noreferrer\">Universal Acceptance Steering Group</a>" have compiled a languagewise list of libraries which are found to be compliant/non-compliant with various parameters involving validations vis-a-vis Internationalized Domain Names and Internationalized Email addresses. Please find the links to those documents over <a href=\"https://uasg.tech/download/uasg-018a-ua-compliance-of-some-programming-language-libraries-and-frameworks-en/\" rel=\"nofollow noreferrer\">here</a> and <a href=\"https://uasg.tech/download/uasg-037-ua-readiness-of-some-programming-language-libraries-and-frameworks-en/\" rel=\"nofollow noreferrer\">here</a>.</p>\n<p><strong>Speaking specifically of PHP:</strong></p>\n<p>There is one good library available in PHP i.e. EmailValidator. It is an email address validator that includes many validation methods such as DNS validation. The validator specifically recommended is called RFCValidator and validates email addresses against several RFCs. It has good compliance when it comes to being inclusive towards IDNs and Internationalized Email addresses.</p>\n"
},
{
"answer_id": 72060047,
"author": "Eggon",
"author_id": 11244772,
"author_profile": "https://Stackoverflow.com/users/11244772",
"pm_score": 1,
"selected": false,
"text": "<p>I'd like to propose my approach which is relatively simple while ensuring proper email structure and restricting forbidden characters. Valid for latin characters.</p>\n<pre><code>/^(?![\\w\\.@]*\\.\\.)(?![\\w\\.@]*\\.@)(?![\\w\\.]*@\\.)\\w+[\\w\\.]*@[\\w\\.]+\\.\\w{2,}$/\n</code></pre>\n"
},
{
"answer_id": 73311375,
"author": "amatinya",
"author_id": 18078396,
"author_profile": "https://Stackoverflow.com/users/18078396",
"pm_score": -1,
"selected": false,
"text": "<p>This is the best regular expression I've ever found!</p>\n<pre><code>/^((([a-z]|\\d|[!#\\$%&'\\*\\+\\-\\/=\\?\\^_`{\\|}~]|[\\u00A0-\\uD7FF\\uF900-\\uFDCF\\uFDF0-\\uFFEF])+(\\.([a-z]|\\d|[!#\\$%&'\\*\\+\\-\\/=\\?\\^_`{\\|}~]|[\\u00A0-\\uD7FF\\uF900-\\uFDCF\\uFDF0-\\uFFEF])+)*)|((\\x22)((((\\x20|\\x09)*(\\x0d\\x0a))?(\\x20|\\x09)+)?(([\\x01-\\x08\\x0b\\x0c\\x0e-\\x1f\\x7f]|\\x21|[\\x23-\\x5b]|[\\x5d-\\x7e]|[\\u00A0-\\uD7FF\\uF900-\\uFDCF\\uFDF0-\\uFFEF])|(\\\\([\\x01-\\x09\\x0b\\x0c\\x0d-\\x7f]|[\\u00A0-\\uD7FF\\uF900-\\uFDCF\\uFDF0-\\uFFEF]))))*(((\\x20|\\x09)*(\\x0d\\x0a))?(\\x20|\\x09)+)?(\\x22)))@((([a-z]|\\d|[\\u00A0-\\uD7FF\\uF900-\\uFDCF\\uFDF0-\\uFFEF])|(([a-z]|\\d|[\\u00A0-\\uD7FF\\uF900-\\uFDCF\\uFDF0-\\uFFEF])([a-z]|\\d|-|\\.|_|~|[\\u00A0-\\uD7FF\\uF900-\\uFDCF\\uFDF0-\\uFFEF])*([a-z]|\\d|[\\u00A0-\\uD7FF\\uF900-\\uFDCF\\uFDF0-\\uFFEF])))\\.)+(([a-z]|[\\u00A0-\\uD7FF\\uF900-\\uFDCF\\uFDF0-\\uFFEF])|(([a-z]|[\\u00A0-\\uD7FF\\uF900-\\uFDCF\\uFDF0-\\uFFEF])([a-z]|\\d|-|\\.|_|~|[\\u00A0-\\uD7FF\\uF900-\\uFDCF\\uFDF0-\\uFFEF])*([a-z]|[\\u00A0-\\uD7FF\\uF900-\\uFDCF\\uFDF0-\\uFFEF])))$/i\n</code></pre>\n"
}
] |
2008/10/14
|
[
"https://Stackoverflow.com/questions/201323",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/24215/"
] |
Over the years I have slowly developed a [regular expression](http://en.wikipedia.org/wiki/Regular_expression) that validates *most* email addresses correctly, assuming they don't use an IP address as the server part.
I use it in several PHP programs, and it works most of the time. However, from time to time I get contacted by someone that is having trouble with a site that uses it, and I end up having to make some adjustment (most recently I realized that I wasn't allowing four-character [TLDs](https://en.wikipedia.org/wiki/Top-level_domain)).
*What is the best regular expression you have or have seen for validating emails?*
I've seen several solutions that use functions that use several shorter expressions, but I'd rather have one long complex expression in a simple function instead of several short expression in a more complex function.
|
The [fully RFC 822 compliant regex](http://ex-parrot.com/%7Epdw/Mail-RFC822-Address.html) is inefficient and obscure because of its length. Fortunately, RFC 822 was superseded twice and the current specification for email addresses is [RFC 5322](https://datatracker.ietf.org/doc/html/rfc5322). RFC 5322 leads to a regex that can be understood if studied for a few minutes and is efficient enough for actual use.
One RFC 5322 compliant regex can be found at the top of the page at <http://emailregex.com/> but uses the IP address pattern that is floating around the internet with a bug that allows `00` for any of the unsigned byte decimal values in a dot-delimited address, which is illegal. The rest of it appears to be consistent with the RFC 5322 grammar and passes several tests using `grep -Po`, including cases domain names, IP addresses, bad ones, and account names with and without quotes.
Correcting the `00` bug in the IP pattern, we obtain a working and fairly fast regex. (Scrape the rendered version, not the markdown, for actual code.)
>
> (?:[a-z0-9!#$%&'\*+/=?^\_`{|}~-]+(?:\.[a-z0-9!#$%&'\*+/=?^\_`{|}~-]+)\*|"(?:[\x01-\x08\x0b\x0c\x0e-\x1f\x21\x23-\x5b\x5d-\x7f]|\\[\x01-\x09\x0b\x0c\x0e-\x7f])\*")@(?:(?:[a-z0-9](?:[a-z0-9-]\*[a-z0-9])?\.)+[a-z0-9](?:[a-z0-9-]\*[a-z0-9])?|\[(?:(?:(2(5[0-5]|[0-4][0-9])|1[0-9][0-9]|[1-9]?[0-9]))\.){3}(?:(2(5[0-5]|[0-4][0-9])|1[0-9][0-9]|[1-9]?[0-9])|[a-z0-9-]\*[a-z0-9]:(?:[\x01-\x08\x0b\x0c\x0e-\x1f\x21-\x5a\x53-\x7f]|\\[\x01-\x09\x0b\x0c\x0e-\x7f])+)\])
>
>
>
or:
```
(?:[a-z0-9!#$%&'*+/=?^_`{|}~-]+(?:\.[a-z0-9!#$%&'*+/=?^_`{|}~-]+)*|"(?:[\x01-\x08\x0b\x0c\x0e-\x1f\x21\x23-\x5b\x5d-\x7f]|\\[\x01-\x09\x0b\x0c\x0e-\x7f])*")@(?:(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\.)+[a-z0-9](?:[a-z0-9-]*[a-z0-9])?|\[(?:(?:(2(5[0-5]|[0-4][0-9])|1[0-9][0-9]|[1-9]?[0-9]))\.){3}(?:(2(5[0-5]|[0-4][0-9])|1[0-9][0-9]|[1-9]?[0-9])|[a-z0-9-]*[a-z0-9]:(?:[\x01-\x08\x0b\x0c\x0e-\x1f\x21-\x5a\x53-\x7f]|\\[\x01-\x09\x0b\x0c\x0e-\x7f])+)\])
```
Here is [diagram](https://regexper.com/#(%3F%3A%5Ba-z0-9!%23%24%25%26%27*%2B%2F%3D%3F%5E_%60%7B%7C%7D%7E-%5D%2B(%3F%3A%5C.%5Ba-z0-9!%23%24%25%26%27*%2B%2F%3D%3F%5E_%60%7B%7C%7D%7E-%5D%2B)*%7C%22(%3F%3A%5B%5Cx01-%5Cx08%5Cx0b%5Cx0c%5Cx0e-%5Cx1f%5Cx21%5Cx23-%5Cx5b%5Cx5d-%5Cx7f%5D%7C%5C%5C%5B%5Cx01-%5Cx09%5Cx0b%5Cx0c%5Cx0e-%5Cx7f%5D)*%22)%40(%3F%3A(%3F%3A%5Ba-z0-9%5D(%3F%3A%5Ba-z0-9-%5D*%5Ba-z0-9%5D)%3F%5C.)%2B%5Ba-z0-9%5D(%3F%3A%5Ba-z0-9-%5D*%5Ba-z0-9%5D)%3F%7C%5C%5B(%3F%3A(%3F%3A(2(5%5B0-5%5D%7C%5B0-4%5D%5B0-9%5D)%7C1%5B0-9%5D%5B0-9%5D%7C%5B1-9%5D%3F%5B0-9%5D))%5C.)%7B3%7D(%3F%3A(2(5%5B0-5%5D%7C%5B0-4%5D%5B0-9%5D)%7C1%5B0-9%5D%5B0-9%5D%7C%5B1-9%5D%3F%5B0-9%5D)%7C%5Ba-z0-9-%5D*%5Ba-z0-9%5D%3A(%3F%3A%5B%5Cx01-%5Cx08%5Cx0b%5Cx0c%5Cx0e-%5Cx1f%5Cx21-%5Cx5a%5Cx53-%5Cx7f%5D%7C%5C%5C%5B%5Cx01-%5Cx09%5Cx0b%5Cx0c%5Cx0e-%5Cx7f%5D)%2B)%5C%5D)) of [finite state machine](https://en.wikipedia.org/wiki/Finite-state_machine) for above regexp which is more clear than regexp itself
[](https://i.stack.imgur.com/YI6KR.png)
The more sophisticated patterns in Perl and PCRE (regex library used e.g. in PHP) can [correctly parse RFC 5322 without a hitch](https://stackoverflow.com/questions/201323/what-is-the-best-regular-expression-for-validating-email-addresses/1917982#1917982). Python and C# can do that too, but they use a different syntax from those first two. However, if you are forced to use one of the many less powerful pattern-matching languages, then it’s best to use a real parser.
It's also important to understand that validating it per the RFC tells you absolutely nothing about whether that address actually exists at the supplied domain, or whether the person entering the address is its true owner. People sign others up to mailing lists this way all the time. Fixing that requires a fancier kind of validation that involves sending that address a message that includes a confirmation token meant to be entered on the same web page as was the address.
Confirmation tokens are the only way to know you got the address of the person entering it. This is why most mailing lists now use that mechanism to confirm sign-ups. After all, anybody can put down `[email protected]`, and that will even parse as legal, but it isn't likely to be the person at the other end.
For PHP, you should *not* use the pattern given in [Validate an E-Mail Address with PHP, the Right Way](http://www.linuxjournal.com/article/9585) from which I quote:
>
> There is some danger that common usage and widespread sloppy coding will establish a de facto standard for e-mail addresses that is more restrictive than the recorded formal standard.
>
>
>
That is no better than all the other non-RFC patterns. It isn’t even smart enough to handle even [RFC 822](https://datatracker.ietf.org/doc/html/rfc822), let alone RFC 5322. [This one](https://stackoverflow.com/questions/201323/what-is-the-best-regular-expression-for-validating-email-addresses/1917982#1917982), however, is.
If you want to get fancy and pedantic, [implement a complete state engine](http://cubicspot.blogspot.com/2012/06/correct-way-to-validate-e-mail-address.html). A regular expression can only act as a rudimentary filter. The problem with regular expressions is that telling someone that their perfectly valid e-mail address is invalid (a false positive) because your regular expression can't handle it is just rude and impolite from the user's perspective. A state engine for the purpose can both validate and even correct e-mail addresses that would otherwise be considered invalid as it disassembles the e-mail address according to each RFC. This allows for a potentially more pleasing experience, like
>
> The specified e-mail address 'myemail@address,com' is invalid. Did you mean '[email protected]'?
>
>
>
See also [Validating Email Addresses](http://worsethanfailure.com/Articles/Validating_Email_Addresses.aspx), including the comments. Or [Comparing E-mail Address Validating Regular Expressions](http://fightingforalostcause.net/misc/2006/compare-email-regex.php).
[](https://i.stack.imgur.com/SrUwP.png)
[Debuggex Demo](https://www.debuggex.com/r/aH_x42NflV8G-GS7)
|
201,355 |
<p>I have a web application which provides Excel files via IE 7. It requests the files with an HTTP GET from a URL which returns the data with a content type of 'application/vnd.ms-excel'. It then opens the spreadsheets in an IFrame.</p>
<p>This all works fine unless Excel is already open when a spreadsheet is downloaded. In this case it is still displayed correctly but reuses the instance of Excel which is open. When the IFrame is closed, Excel hangs. Excel only becomes unlocked if the user logs out of the web application or if they download a file of a different type.</p>
<p>I've tried turning on the 'Ignore other applications' setting under Tools | Options | General but it didn't solve the problem.</p>
<p>I've also tried following the steps in <a href="https://stackoverflow.com/questions/213110/make-excel-2003-open-spreadsheets-in-new-instances/213187#213187">this answer</a> (as the <a href="http://www.drewery.net/blog/2006/08/29/utilising-dual-monitors-with-microsoft-excel-2003/" rel="nofollow noreferrer">linked reference</a> says 'This issue has been addressed in Excel 2007 beta 2.') with no luck.</p>
<p>Is there some kind of 'disposal' step which I'm not currently doing which would prevent Excel from hanging?</p>
<p>Versions:</p>
<p>Excel 2003 (11.8220.8221) SP3</p>
<p>IE 7.0.5730.11 (Update Versions: 0)</p>
|
[
{
"answer_id": 201372,
"author": "NotMe",
"author_id": 2424,
"author_profile": "https://Stackoverflow.com/users/2424",
"pm_score": 0,
"selected": false,
"text": "<p>Unfortunately, this is completely out of your hands. It really depends on what version of excel they have and what updates have been applied.</p>\n"
},
{
"answer_id": 484476,
"author": "Jas Panesar",
"author_id": 35886,
"author_profile": "https://Stackoverflow.com/users/35886",
"pm_score": 0,
"selected": false,
"text": "<p>Have you been able to reproduce this issue in your own environment? If not, it may be an issue on the client's computer. Is there any way you can find out what options were or werent installed, or if Excel has been maintained with it's patches?</p>\n\n<p>It seems to me that office itself needs to be re-installed, if not IE 7 after that. </p>\n\n<p>I would also look into any iFrame closing issues. To test this theory out, you could post the iframe to a new page (without iframes) and then link back to a page with iframes and the excel file? I realize that probably wont' be a working solution for you, but it should help you eliminate whether it's excel, IE7 or the iframe code having a bug.</p>\n"
},
{
"answer_id": 495387,
"author": "Matthew Murdoch",
"author_id": 4023,
"author_profile": "https://Stackoverflow.com/users/4023",
"pm_score": 2,
"selected": true,
"text": "<p>Further to <a href=\"https://stackoverflow.com/questions/201355/how-can-i-stop-excel-2003-from-hanging-after-opening-a-spreadsheet-in-ie/497100#497100\">Robert's answer</a>, the following line of (Java) code fixes this problem, in that it prevents Excel from hanging:</p>\n\n<pre><code>response.setHeader(\"Content-Disposition\", \n \"attachment; filename=\\\"\" + filename + \"\\\"\");\n</code></pre>\n\n<p>[NB 'response' is an HttpServletResponse]</p>\n\n<p>However, it forces the spreadsheet to be loaded into an Excel window rather than being displayed in the IFrame...</p>\n\n<p><strong>Update:</strong> Resetting the URL of the IFrame to blank forces the Excel instance to be disposed and fixes this problem (without requiring the <code>Content-Disposition</code> change).</p>\n"
},
{
"answer_id": 496313,
"author": "SqlRyan",
"author_id": 8114,
"author_profile": "https://Stackoverflow.com/users/8114",
"pm_score": 0,
"selected": false,
"text": "<p>Is this something you're able to reproduce, or is it something being reported to you by a customer, and you're trying to hunt it down?</p>\n\n<p>The link you've provided deals with multiple monitors - I have multiple monitors as well when I dock my laptop, and I've found a number of applications don't respond well. For example, if an application attempts to open a modal dialog box in a desktop space that doesn't exist anymore (for example, on my \"second monitor\" after I'veundocked my laptop), it will lock up the application since I can't get to the box. Could that be what's happening here?</p>\n\n<p>Another potential problem happens if you're asking the user for some kind of authentication when they get the Excel file. On our sharepoint site, Excel wants the user to authenticate, and if that modal authentication dialog somehow gets pushed into the background, it can be impossible to get to the front again. The only way is if you kill the process or if you close the sharepoint browser, since that terminates the request for the file in the first place.</p>\n\n<p>Hope this helps, and if either of these give you some more clues, post them here and we'll get this solved.</p>\n"
},
{
"answer_id": 497100,
"author": "Robert Vuković",
"author_id": 438025,
"author_profile": "https://Stackoverflow.com/users/438025",
"pm_score": 1,
"selected": false,
"text": "<p>Not sure if this helps but ...</p>\n\n<p>I had some similar problem (generating CSV content on the fly) long time ago and all I can remember is that it had to do something with right Response methods being called. The code was something like this</p>\n\n<pre><code>\nResponse.Clear();\nResponse.Buffer = true;\n\nResponse.AppendHeader(\"Content-Disposition\", \"attachment; filename=export.csv\");\nResponse.Cache.SetCacheability(HttpCacheability.Private);\nResponse.Cache.SetExpires(DateTime.MinValue);\nResponse.Cache.SetLastModified(DateTime.Now);\nResponse.Cache.SetMaxAge(new TimeSpan(1));\nResponse.ContentType = \"text/csv\";\n\nResponse.ContentEncoding = System.Text.Encoding.Unicode;\n\n...\n//Some writing to the Response.OutputStream\n...\n\nResponse.Flush();\n\n//I am not sure about the following line:\nResponse.End(); \n\n</code></pre>\n"
}
] |
2008/10/14
|
[
"https://Stackoverflow.com/questions/201355",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4023/"
] |
I have a web application which provides Excel files via IE 7. It requests the files with an HTTP GET from a URL which returns the data with a content type of 'application/vnd.ms-excel'. It then opens the spreadsheets in an IFrame.
This all works fine unless Excel is already open when a spreadsheet is downloaded. In this case it is still displayed correctly but reuses the instance of Excel which is open. When the IFrame is closed, Excel hangs. Excel only becomes unlocked if the user logs out of the web application or if they download a file of a different type.
I've tried turning on the 'Ignore other applications' setting under Tools | Options | General but it didn't solve the problem.
I've also tried following the steps in [this answer](https://stackoverflow.com/questions/213110/make-excel-2003-open-spreadsheets-in-new-instances/213187#213187) (as the [linked reference](http://www.drewery.net/blog/2006/08/29/utilising-dual-monitors-with-microsoft-excel-2003/) says 'This issue has been addressed in Excel 2007 beta 2.') with no luck.
Is there some kind of 'disposal' step which I'm not currently doing which would prevent Excel from hanging?
Versions:
Excel 2003 (11.8220.8221) SP3
IE 7.0.5730.11 (Update Versions: 0)
|
Further to [Robert's answer](https://stackoverflow.com/questions/201355/how-can-i-stop-excel-2003-from-hanging-after-opening-a-spreadsheet-in-ie/497100#497100), the following line of (Java) code fixes this problem, in that it prevents Excel from hanging:
```
response.setHeader("Content-Disposition",
"attachment; filename=\"" + filename + "\"");
```
[NB 'response' is an HttpServletResponse]
However, it forces the spreadsheet to be loaded into an Excel window rather than being displayed in the IFrame...
**Update:** Resetting the URL of the IFrame to blank forces the Excel instance to be disposed and fixes this problem (without requiring the `Content-Disposition` change).
|
201,359 |
<p>int l = strlen(s);</p>
<p>warning C4244: '=' : conversion from '__w64 int' to 'int', possible loss of data</p>
<p>I need to replace strlen with an inline function
int l = new_strlen(s);</p>
<p>But how do I portably get the result of the strlen into the int without a warning, and without using pragmas? I can guarantee there aren't more than 2 billion characters in my string!</p>
<p>All the obvious things like reinterpret_cast, static_cast also produce errors or warnings.</p>
<p>EDIT: Argh. a c-style cast: (int) does work. I had been convinced that it did not.</p>
|
[
{
"answer_id": 201373,
"author": "John Dibling",
"author_id": 241536,
"author_profile": "https://Stackoverflow.com/users/241536",
"pm_score": 1,
"selected": false,
"text": "<p>Cast it:</p>\n\n<pre><code>int i = (int) strlen(s);\n</code></pre>\n"
},
{
"answer_id": 201383,
"author": "Andy Lester",
"author_id": 8454,
"author_profile": "https://Stackoverflow.com/users/8454",
"pm_score": 1,
"selected": false,
"text": "<p>Or don't use a signed int. The return value of strlen() is unsigned.</p>\n"
},
{
"answer_id": 201394,
"author": "Igor Semenov",
"author_id": 11401,
"author_profile": "https://Stackoverflow.com/users/11401",
"pm_score": 3,
"selected": false,
"text": "<pre><code>const char * str = \"Hello\";\nint len = static_cast< int >( strlen( str ) );\nreturn len;\n</code></pre>\n\n<p>This code doesn't produce any error or warning even on Warning Level 4 (VS2005).\nWhat compiler do you use?</p>\n"
},
{
"answer_id": 201415,
"author": "James Curran",
"author_id": 12725,
"author_profile": "https://Stackoverflow.com/users/12725",
"pm_score": 0,
"selected": false,
"text": "<blockquote>\n <p>I need to replace strlen with an\n inline function int l = new_strlen(s);</p>\n</blockquote>\n\n<p>Note that in VC++, strlen is automatically replaced by a inline version when you build an optimized version.</p>\n"
},
{
"answer_id": 201439,
"author": "Roger Lipscombe",
"author_id": 8446,
"author_profile": "https://Stackoverflow.com/users/8446",
"pm_score": 2,
"selected": false,
"text": "<p>Also note that /Wp64 is deprecated in VS2008; apparently it's <a href=\"http://blogs.msdn.com/vcblog/archive/2007/08/10/the-future-of-the-c-language.aspx#4421146\" rel=\"nofollow noreferrer\">not reliable</a>.</p>\n"
},
{
"answer_id": 201560,
"author": "bk1e",
"author_id": 8090,
"author_profile": "https://Stackoverflow.com/users/8090",
"pm_score": 1,
"selected": false,
"text": "<p>In cases where you really have a good reason to truncate pointers, you can make <code>/Wp64</code> accept your code by stacking multiple casts. These cases are rare. One example: device drivers for legacy PCI devices, doing DMA, with memory allocated below the 4GB limit. (Note: there is also the <code>PtrToUlong()</code> macro, which will make your intentions clearer.)</p>\n\n<p>This single cast will produce a warning:</p>\n\n<pre><code>const char* p = \"abc\";\nunsigned int u = reinterpret_cast<unsigned int>(p);\n</code></pre>\n\n<p>wp64.cpp(10) : warning C4311: 'reinterpret_cast' : pointer truncation from 'const char *' to 'unsigned int'</p>\n\n<p>But these stacked casts will not:</p>\n\n<pre><code>const char* p = \"abc\";\nunsigned int u = static_cast<unsigned int>(reinterpret_cast<uintptr_t>(p));\n</code></pre>\n\n<p>I'm not able to reproduce your warning with the version of the compiler that I have installed, but I suspect that your problem is related to the fact that you're casting a 64-bit unsigned <code>size_t</code> into a 32-bit signed <code>int</code>.</p>\n\n<p>You might have better luck if you stack multiple casts to do the 64-bit to 32-bit conversion and the unsigned-to-signed conversion:</p>\n\n<pre><code>const char* s = \"abcdef\";\nint l = static_cast<int>(static_cast<intptr_t>(strlen(s)));\n</code></pre>\n\n<p>Also, if you build both x86 and x64 binaries, you can disable <code>/Wp64</code> for your 32-bit builds so that you don't have to annotate any types with <code>__w64</code>. Using <code>/Wp64</code> for your 64-bit builds will catch a lot of bugs.</p>\n"
},
{
"answer_id": 201692,
"author": "Dustin Getz",
"author_id": 20003,
"author_profile": "https://Stackoverflow.com/users/20003",
"pm_score": 1,
"selected": false,
"text": "<p>if you understand a warning, its perfectly acceptable to disable the warning instead of stacking casts or whatever other confusing mess as a workaround.</p>\n\n<blockquote>\n <p>A pragma warning directive with the\n suppress specifier suppresses the\n warning only for the line of code that\n immediately follows the #pragma\n warning statement. </p>\n\n<pre><code>#pragma warning( suppress : 6001 ) \narr[i+1] = 0; // Warning 6001 is suppressed\nj++; // Warning 6001 is reported\n</code></pre>\n \n <p><a href=\"http://msdn.microsoft.com/en-us/library/aa468780.aspx\" rel=\"nofollow noreferrer\">(msvc specific)</a></p>\n</blockquote>\n"
}
] |
2008/10/14
|
[
"https://Stackoverflow.com/questions/201359",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] |
int l = strlen(s);
warning C4244: '=' : conversion from '\_\_w64 int' to 'int', possible loss of data
I need to replace strlen with an inline function
int l = new\_strlen(s);
But how do I portably get the result of the strlen into the int without a warning, and without using pragmas? I can guarantee there aren't more than 2 billion characters in my string!
All the obvious things like reinterpret\_cast, static\_cast also produce errors or warnings.
EDIT: Argh. a c-style cast: (int) does work. I had been convinced that it did not.
|
```
const char * str = "Hello";
int len = static_cast< int >( strlen( str ) );
return len;
```
This code doesn't produce any error or warning even on Warning Level 4 (VS2005).
What compiler do you use?
|
201,368 |
<p>Not of the site collection itself, but the individual SPWeb's.</p>
|
[
{
"answer_id": 201393,
"author": "Pascal Paradis",
"author_id": 1291,
"author_profile": "https://Stackoverflow.com/users/1291",
"pm_score": 3,
"selected": false,
"text": "<p>You should take a look at this blog entry by Alexander Meijers : <a href=\"http://www.bloggix.com/blogs/microsoft/archive/2008/04/03/size-of-spweb-based-on-its-folders-and-files.aspx\" rel=\"noreferrer\">Size of SPWeb based on its Folders and Files</a></p>\n\n<p>It provides a clever way of finding the size of an SPWeb or SPFolder by iterating through his content.</p>\n\n<pre><code>private long GetWebSize(SPWeb web)\n{\n long total = 0;\n\n foreach (SPFolder folder in web.Folders)\n {\n total += GetFolderSize(folder);\n }\n\n foreach (SPWeb subweb in web.Webs)\n {\n total += GetWebSize(subweb);\n subweb.Dispose();\n }\n\n return total;\n}\n</code></pre>\n"
},
{
"answer_id": 24517075,
"author": "JasonV",
"author_id": 658944,
"author_profile": "https://Stackoverflow.com/users/658944",
"pm_score": 0,
"selected": false,
"text": "<p>For anyone who comes back to this question, here is the missing method:</p>\n\n<pre><code>private long GetFolderSize(SPFolder folder)\n{\n long folderSize = 0;\n\n foreach (SPFile file in folder.Files)\n {\n folderSize += file.Length;\n }\n\n foreach (SPFolder subfolder in folder.SubFolders)\n {\n folderSize += GetFolderSize(subfolder);\n }\n\n return folderSize;\n}\n</code></pre>\n"
}
] |
2008/10/14
|
[
"https://Stackoverflow.com/questions/201368",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] |
Not of the site collection itself, but the individual SPWeb's.
|
You should take a look at this blog entry by Alexander Meijers : [Size of SPWeb based on its Folders and Files](http://www.bloggix.com/blogs/microsoft/archive/2008/04/03/size-of-spweb-based-on-its-folders-and-files.aspx)
It provides a clever way of finding the size of an SPWeb or SPFolder by iterating through his content.
```
private long GetWebSize(SPWeb web)
{
long total = 0;
foreach (SPFolder folder in web.Folders)
{
total += GetFolderSize(folder);
}
foreach (SPWeb subweb in web.Webs)
{
total += GetWebSize(subweb);
subweb.Dispose();
}
return total;
}
```
|
201,370 |
<p>On the site we are building. We need to be able to redirect the user to a default page when his session has ended.</p>
<p>At first sight we used the Session_End with a Response.Redirect to do this job.</p>
<pre><code>Sub Session_End(ByVal sender As Object, ByVal e As EventArgs)
Response.Redirect("~/global/exit.aspx")
End Sub
</code></pre>
<p>But it generates a crapload of <em>Response is not available in this context</em> errors. Naturally we don't want to spam our servers error logs.</p>
<p>What is the most efficient way to handle session ending with ASP.NET 2.0?</p>
|
[
{
"answer_id": 201402,
"author": "Sijin",
"author_id": 8884,
"author_profile": "https://Stackoverflow.com/users/8884",
"pm_score": 2,
"selected": false,
"text": "<p>We handled it by checking if the session data existed in Application.Begin_Request for the pages that were user specific and if it didn't then redirecting the user to login or homepage.</p>\n"
},
{
"answer_id": 201690,
"author": "Mitchel Sellers",
"author_id": 13279,
"author_profile": "https://Stackoverflow.com/users/13279",
"pm_score": 2,
"selected": false,
"text": "<p>You can use the session_end method, as it is not a user callable method, it is triggered by ASP.NET and response isn't available, as it is not part of the request.</p>\n\n<p>The biggest way is to check and see if session is missing, somewhere in the load of your pages and redirect back to the main.</p>\n\n<p>What I have done before is to put this checking logic inside a \"RestrictedPage.master\" master page that was used for all session specific pages, if session is lost, it redirects.</p>\n"
},
{
"answer_id": 203951,
"author": "Schalk Versteeg",
"author_id": 15724,
"author_profile": "https://Stackoverflow.com/users/15724",
"pm_score": 2,
"selected": false,
"text": "<p>We added the following code to the global.asax.cs file: </p>\n\n<pre><code> private void IsAuthenticated()\n {\n string vFileName = Path.GetFileName(HttpContext.Current.Request.Path);\n string vExt = Path.GetExtension(vFileName).ToLower();\n if ((vFileName != \"Login.aspx\") && (vExt == \".aspx\"))\n {\n if (HttpContext.Current.Session[\"LoggedIn\"] == null)\n {\n HttpContext.Current.Response.Redirect(\"~/Login.aspx\");\n }\n }\n }\n void Application_PostAcquireRequestState(object sender, EventArgs e)\n {\n IsAuthenticated();\n } \n</code></pre>\n\n<p>NS: The first line in our Global .asax file is : </p>\n\n<pre><code><%@ Application Inherits=\"???.Global\" Language=\"C#\" %>\n</code></pre>\n"
}
] |
2008/10/14
|
[
"https://Stackoverflow.com/questions/201370",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1291/"
] |
On the site we are building. We need to be able to redirect the user to a default page when his session has ended.
At first sight we used the Session\_End with a Response.Redirect to do this job.
```
Sub Session_End(ByVal sender As Object, ByVal e As EventArgs)
Response.Redirect("~/global/exit.aspx")
End Sub
```
But it generates a crapload of *Response is not available in this context* errors. Naturally we don't want to spam our servers error logs.
What is the most efficient way to handle session ending with ASP.NET 2.0?
|
We handled it by checking if the session data existed in Application.Begin\_Request for the pages that were user specific and if it didn't then redirecting the user to login or homepage.
|
201,374 |
<p>I'm trying to work through Project Euler and I'm hitting a barrier on problem 03. I have an algorithm that works for smaller numbers, but problem 3 uses a very, very large number.</p>
<p><strong>Problem 03:</strong>
The prime factors of 13195 are 5, 7, 13 and 29.
What is the largest prime factor of the number 600851475143?</p>
<p>Here is my solution in C# and it's been running for I think close to an hour. I'm not looking for an answer because I do actually want to solve this myself. Mainly just looking for some help.</p>
<pre><code> static void Main(string[] args) {
const long n = 600851475143;
//const long n = 13195;
long count, half, largestPrime = 0;
bool IsAPrime;
half = n / 2;
for (long i = half; i > 1 && largestPrime == 0; i--) {
if (n % i == 0) { // these are factors of n
count = 1;
IsAPrime = true;
while (++count < i && IsAPrime) {
if (i % count == 0) { // does a factor of n have a factor? (not prime)
IsAPrime = false;
}
}
if (IsAPrime) {
largestPrime = i;
}
}
}
Console.WriteLine("The largest prime factor is " + largestPrime.ToString() + ".");
Console.ReadLine();
}
</code></pre>
|
[
{
"answer_id": 201387,
"author": "nickf",
"author_id": 9021,
"author_profile": "https://Stackoverflow.com/users/9021",
"pm_score": 5,
"selected": true,
"text": "<p>For starters, instead of beginning your search at n / 2, start it at the square root of n. You'll get half of the factors, the other half being their complement.</p>\n\n<p>eg:</p>\n\n<pre><code>n = 27\nstart at floor(sqrt(27)) = 5\nis 5 a factor? no\nis 4 a factor? no\nis 3 a factor? yes. 27 / 3 = 9. 9 is also a factor.\nis 2 a factor? no.\nfactors are 3 and 9.\n</code></pre>\n"
},
{
"answer_id": 201388,
"author": "Rob Walker",
"author_id": 3631,
"author_profile": "https://Stackoverflow.com/users/3631",
"pm_score": 3,
"selected": false,
"text": "<p>You need to reduce the amount of checking you are doing ... think about what numbers you need to test.</p>\n\n<p>For a better approach read up on the <a href=\"http://en.wikipedia.org/wiki/Sieve_of_Eratosthenes\" rel=\"nofollow noreferrer\">Sieve of Erathosthenes</a> ... it should get you pointed in the right direction.</p>\n"
},
{
"answer_id": 201410,
"author": "Nicholas Mancuso",
"author_id": 8945,
"author_profile": "https://Stackoverflow.com/users/8945",
"pm_score": -1,
"selected": false,
"text": "<p>Try using the <a href=\"http://en.wikipedia.org/wiki/Miller-Rabin_primality_test\" rel=\"nofollow noreferrer\">Miller-Rabin Primality Test</a> to test for a number being prime. That should speed things up considerably.</p>\n"
},
{
"answer_id": 201435,
"author": "Bill Barksdale",
"author_id": 16113,
"author_profile": "https://Stackoverflow.com/users/16113",
"pm_score": 3,
"selected": false,
"text": "<p>Although the question asks for the <em>largest</em> prime factor, it doesn't necessarily mean you have to find that one first...</p>\n"
},
{
"answer_id": 201462,
"author": "JesperE",
"author_id": 13051,
"author_profile": "https://Stackoverflow.com/users/13051",
"pm_score": 3,
"selected": false,
"text": "<p>Actually, for this case you don't need to check for primality, just remove the factors you find. Start with n == 2 and scan upwards. When evil-big-number % n == 0, divide evil-big-number by n and continue with smaller-evil-number. Stop when n >= sqrt(big-evil-number).</p>\n\n<p>Should not take more than a few seconds on any modern machine.</p>\n"
},
{
"answer_id": 201480,
"author": "Ralph M. Rickenbach",
"author_id": 4549416,
"author_profile": "https://Stackoverflow.com/users/4549416",
"pm_score": 2,
"selected": false,
"text": "<p>As for the reason to accepted nicf's answer:</p>\n\n<p>It is OK for the problem at Euler, but does not make this an efficient solution in the general case. Why would you try even numbers for factors? </p>\n\n<ul>\n<li>If n is even, shift left (divide by\n2) until it is not anymore. If it is\none then, 2 is the largest prime\nfactor.</li>\n<li>If n is not even, you do not have to\ntest even numbers.</li>\n<li>It is true that you can stop at\nsqrt(n).</li>\n<li>You only have to test primes for\nfactors. It might be faster to test\nwhether k divides n and then test it\nfor primality though.</li>\n<li>You can optimize the upper limit on\nthe fly when you find a factor.</li>\n</ul>\n\n<p>This would lead to some code like this:</p>\n\n<pre><code>n = abs(number);\nresult = 1;\nif (n mod 2 = 0) {\n result = 2;\n while (n mod 2 = 0) n /= 2;\n}\nfor(i=3; i<sqrt(n); i+=2) {\n if (n mod i = 0) {\n result = i;\n while (n mod i = 0) n /= i;\n }\n}\nreturn max(n,result)\n</code></pre>\n\n<p>There are some modulo tests that are superflous, as n can never be divided by 6 if all factors 2 and 3 have been removed. You could only allow primes for i.</p>\n\n<p>Just as an example lets look at the result for 21:</p>\n\n<p>21 is not even, so we go into the for loop with upper limit sqrt(21) (~4.6).\nWe can then divide 21 by 3, therefore result = 3 and n = 21/3 = 7. We now only have to test up to sqrt(7). which is smaller then 3, so we are done with the for loop. We return the max of n and result, which is n = 7.</p>\n"
},
{
"answer_id": 201485,
"author": "AquilaX",
"author_id": 17734,
"author_profile": "https://Stackoverflow.com/users/17734",
"pm_score": -1,
"selected": false,
"text": "<p>Another approach is to get all primes up to n/2 first and then to check if the modulus is 0.\nAn algorithm I use to get all the primes up to <strong>n</strong> can be found <a href=\"http://dev.horemag.net/2007/11/04/prime-numbers-in-php/\" rel=\"nofollow noreferrer\">here</a>.</p>\n"
},
{
"answer_id": 201707,
"author": "Steve Moyer",
"author_id": 17008,
"author_profile": "https://Stackoverflow.com/users/17008",
"pm_score": 1,
"selected": false,
"text": "<p>Using a recursive algorithm in Java runs less than a second ... think your algorithm through a bit as it includes some \"brute-forcing\" that can be eliminated. Also look at how your solution space can be reduced by intermediate calculations.</p>\n"
},
{
"answer_id": 210103,
"author": "Matthew Scharley",
"author_id": 15537,
"author_profile": "https://Stackoverflow.com/users/15537",
"pm_score": 2,
"selected": false,
"text": "<p>The way I did it was to search for primes (<code>p</code>), starting at 2 using the Sieve of Eratosthenes. This algorithm can find all the primes under 10 million in <2s on a decently fast machine.</p>\n\n<p>For every prime you find, test divide it into the number you are testing against untill you can't do integer division anymore. (ie. check <code>n % p == 0</code> and if true, then divide.)</p>\n\n<p>Once <code>n = 1</code>, you're done. The last value of <code>n</code> that successfully divided is your answer. On a sidenote, you've also found all the prime factors of <code>n</code> on the way.</p>\n\n<p>PS: As been noted before, you only need to search for primes between <code>2 <= n <= sqrt(p)</code>. This makes the Sieve of Eratosthenes a very fast and easy to implement algorithm for our purposes.</p>\n"
},
{
"answer_id": 211229,
"author": "jfs",
"author_id": 4279,
"author_profile": "https://Stackoverflow.com/users/4279",
"pm_score": 0,
"selected": false,
"text": "<p>All Project Euler's problems should take less then a minute; even an unoptimized recursive implementation in Python takes less then a second [0.09 secs (cpu 4.3GHz)].</p>\n\n<pre><code>from math import sqrt\n\ndef largest_primefactor(number):\n for divisor in range(2, int(sqrt(number) + 1.5)): # divisor <= sqrt(n)\n q, r = divmod(number, divisor)\n if r == 0:\n #assert(isprime(divisor))\n # recursion depth == number of prime factors,\n # e.g. 4 has two prime factors: {2,2}\n return largest_primefactor(q) \n\n return number # number is a prime itself\n</code></pre>\n"
},
{
"answer_id": 1185740,
"author": "pageman",
"author_id": 64253,
"author_profile": "https://Stackoverflow.com/users/64253",
"pm_score": 0,
"selected": false,
"text": "<p>you might want to see this:\n<a href=\"https://stackoverflow.com/questions/188425/project-euler-problem\">Is there a simple algorithm that can determine if X is prime, and not confuse a mere mortal programmer?</a></p>\n\n<p>and I like lill mud's solution:</p>\n\n<blockquote>\n <p>require \"mathn.rb\"<br/>\n puts 600851475143.prime_division.last.first</p>\n</blockquote>\n\n<p>I checked it <a href=\"http://codepad.org/NgBPxoSK\" rel=\"nofollow noreferrer\">here</a></p>\n"
},
{
"answer_id": 3004386,
"author": "st0le",
"author_id": 216517,
"author_profile": "https://Stackoverflow.com/users/216517",
"pm_score": 3,
"selected": false,
"text": "<pre><code>long n = 600851475143L; //not even, so 2 wont be a factor\nint factor = 3; \nwhile( n > 1)\n{\n if(n % factor == 0)\n {\n n/=factor;\n }else\n factor += 2; //skip even numbrs\n}\n print factor;\n</code></pre>\n\n<p>This should be quick enough...Notice, there's no need to check for prime...</p>\n"
},
{
"answer_id": 3095865,
"author": "Dr. belisarius",
"author_id": 353410,
"author_profile": "https://Stackoverflow.com/users/353410",
"pm_score": 2,
"selected": false,
"text": "<p>Once you find the answer, enter the following in your browser ;)</p>\n\n<p><a href=\"http://www.wolframalpha.com/input/?i=FactorInteger(600851475143)\" rel=\"nofollow noreferrer\">http://www.wolframalpha.com/input/?i=FactorInteger(600851475143)</a></p>\n\n<p>Wofram Alpha is your friend</p>\n"
},
{
"answer_id": 3376319,
"author": "Deepak",
"author_id": 407233,
"author_profile": "https://Stackoverflow.com/users/407233",
"pm_score": 1,
"selected": false,
"text": "<p>Easy peasy in C++:</p>\n\n<pre><code>#include <iostream>\n\nusing namespace std;\n\n\nint main()\n{\n unsigned long long int largefactor = 600851475143;\n for(int i = 2;;)\n {\n if (largefactor <= i)\n break;\n if (largefactor % i == 0)\n {\n largefactor = largefactor / i;\n }\n else\n i++;\n }\n\n cout << largefactor << endl;\n\n cin.get();\n return 0;\n}\n</code></pre>\n"
},
{
"answer_id": 7017924,
"author": "Dangrr888",
"author_id": 888774,
"author_profile": "https://Stackoverflow.com/users/888774",
"pm_score": 1,
"selected": false,
"text": "<p>This solution on C++ took 3.7 ms on my Intel Quad Core i5 iMac (3.1 GHz)</p>\n\n<pre><code>#include <iostream>\n#include <cmath>\n#include <ctime>\n\nusing std::sqrt; using std::cin;\nusing std::cout; using std::endl;\n\nlong lpf(long n)\n{\n long start = (sqrt(n) + 2 % 2);\n if(start % 2 == 0) start++;\n\n for(long i = start; i != 2; i -= 2)\n {\n if(n % i == 0) //then i is a factor of n \n {\n long j = 2L;\n do {\n ++j;\n }\n while(i % j != 0 && j <= i);\n\n if(j == i) //then i is a prime number \n return i;\n }\n }\n}\n\nint main()\n{\n long n, ans;\n cout << \"Please enter your number: \";\n cin >> n; //600851475143L \n\n time_t start, end;\n time(&start);\n int i;\n for(i = 0; i != 3000; ++i)\n ans = lpf(n);\n time(&end);\n\n cout << \"The largest prime factor of your number is: \" << ans << endl;\n cout << \"Running time: \" << 1000*difftime(end, start)/i << \" ms.\" << endl;\n\n return 0;\n}\n</code></pre>\n"
},
{
"answer_id": 32215017,
"author": "stian",
"author_id": 1546268,
"author_profile": "https://Stackoverflow.com/users/1546268",
"pm_score": -1,
"selected": false,
"text": "<p>Maybe it is considered cheating, but one possibility in haskell is to write (for the record I wrote the lines myself and haven't checked eulerproject threads); </p>\n\n<pre><code>import Data.Numbers.Primes\nlast (primeFactors 600851475143)\n</code></pre>\n"
}
] |
2008/10/14
|
[
"https://Stackoverflow.com/questions/201374",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1444511/"
] |
I'm trying to work through Project Euler and I'm hitting a barrier on problem 03. I have an algorithm that works for smaller numbers, but problem 3 uses a very, very large number.
**Problem 03:**
The prime factors of 13195 are 5, 7, 13 and 29.
What is the largest prime factor of the number 600851475143?
Here is my solution in C# and it's been running for I think close to an hour. I'm not looking for an answer because I do actually want to solve this myself. Mainly just looking for some help.
```
static void Main(string[] args) {
const long n = 600851475143;
//const long n = 13195;
long count, half, largestPrime = 0;
bool IsAPrime;
half = n / 2;
for (long i = half; i > 1 && largestPrime == 0; i--) {
if (n % i == 0) { // these are factors of n
count = 1;
IsAPrime = true;
while (++count < i && IsAPrime) {
if (i % count == 0) { // does a factor of n have a factor? (not prime)
IsAPrime = false;
}
}
if (IsAPrime) {
largestPrime = i;
}
}
}
Console.WriteLine("The largest prime factor is " + largestPrime.ToString() + ".");
Console.ReadLine();
}
```
|
For starters, instead of beginning your search at n / 2, start it at the square root of n. You'll get half of the factors, the other half being their complement.
eg:
```
n = 27
start at floor(sqrt(27)) = 5
is 5 a factor? no
is 4 a factor? no
is 3 a factor? yes. 27 / 3 = 9. 9 is also a factor.
is 2 a factor? no.
factors are 3 and 9.
```
|
201,377 |
<p>For example, I am trying to get a min date, a max date, and a sum in different instances. I am trying to avoid hard coding a SQL string or looping through an IList to get these values.</p>
|
[
{
"answer_id": 201387,
"author": "nickf",
"author_id": 9021,
"author_profile": "https://Stackoverflow.com/users/9021",
"pm_score": 5,
"selected": true,
"text": "<p>For starters, instead of beginning your search at n / 2, start it at the square root of n. You'll get half of the factors, the other half being their complement.</p>\n\n<p>eg:</p>\n\n<pre><code>n = 27\nstart at floor(sqrt(27)) = 5\nis 5 a factor? no\nis 4 a factor? no\nis 3 a factor? yes. 27 / 3 = 9. 9 is also a factor.\nis 2 a factor? no.\nfactors are 3 and 9.\n</code></pre>\n"
},
{
"answer_id": 201388,
"author": "Rob Walker",
"author_id": 3631,
"author_profile": "https://Stackoverflow.com/users/3631",
"pm_score": 3,
"selected": false,
"text": "<p>You need to reduce the amount of checking you are doing ... think about what numbers you need to test.</p>\n\n<p>For a better approach read up on the <a href=\"http://en.wikipedia.org/wiki/Sieve_of_Eratosthenes\" rel=\"nofollow noreferrer\">Sieve of Erathosthenes</a> ... it should get you pointed in the right direction.</p>\n"
},
{
"answer_id": 201410,
"author": "Nicholas Mancuso",
"author_id": 8945,
"author_profile": "https://Stackoverflow.com/users/8945",
"pm_score": -1,
"selected": false,
"text": "<p>Try using the <a href=\"http://en.wikipedia.org/wiki/Miller-Rabin_primality_test\" rel=\"nofollow noreferrer\">Miller-Rabin Primality Test</a> to test for a number being prime. That should speed things up considerably.</p>\n"
},
{
"answer_id": 201435,
"author": "Bill Barksdale",
"author_id": 16113,
"author_profile": "https://Stackoverflow.com/users/16113",
"pm_score": 3,
"selected": false,
"text": "<p>Although the question asks for the <em>largest</em> prime factor, it doesn't necessarily mean you have to find that one first...</p>\n"
},
{
"answer_id": 201462,
"author": "JesperE",
"author_id": 13051,
"author_profile": "https://Stackoverflow.com/users/13051",
"pm_score": 3,
"selected": false,
"text": "<p>Actually, for this case you don't need to check for primality, just remove the factors you find. Start with n == 2 and scan upwards. When evil-big-number % n == 0, divide evil-big-number by n and continue with smaller-evil-number. Stop when n >= sqrt(big-evil-number).</p>\n\n<p>Should not take more than a few seconds on any modern machine.</p>\n"
},
{
"answer_id": 201480,
"author": "Ralph M. Rickenbach",
"author_id": 4549416,
"author_profile": "https://Stackoverflow.com/users/4549416",
"pm_score": 2,
"selected": false,
"text": "<p>As for the reason to accepted nicf's answer:</p>\n\n<p>It is OK for the problem at Euler, but does not make this an efficient solution in the general case. Why would you try even numbers for factors? </p>\n\n<ul>\n<li>If n is even, shift left (divide by\n2) until it is not anymore. If it is\none then, 2 is the largest prime\nfactor.</li>\n<li>If n is not even, you do not have to\ntest even numbers.</li>\n<li>It is true that you can stop at\nsqrt(n).</li>\n<li>You only have to test primes for\nfactors. It might be faster to test\nwhether k divides n and then test it\nfor primality though.</li>\n<li>You can optimize the upper limit on\nthe fly when you find a factor.</li>\n</ul>\n\n<p>This would lead to some code like this:</p>\n\n<pre><code>n = abs(number);\nresult = 1;\nif (n mod 2 = 0) {\n result = 2;\n while (n mod 2 = 0) n /= 2;\n}\nfor(i=3; i<sqrt(n); i+=2) {\n if (n mod i = 0) {\n result = i;\n while (n mod i = 0) n /= i;\n }\n}\nreturn max(n,result)\n</code></pre>\n\n<p>There are some modulo tests that are superflous, as n can never be divided by 6 if all factors 2 and 3 have been removed. You could only allow primes for i.</p>\n\n<p>Just as an example lets look at the result for 21:</p>\n\n<p>21 is not even, so we go into the for loop with upper limit sqrt(21) (~4.6).\nWe can then divide 21 by 3, therefore result = 3 and n = 21/3 = 7. We now only have to test up to sqrt(7). which is smaller then 3, so we are done with the for loop. We return the max of n and result, which is n = 7.</p>\n"
},
{
"answer_id": 201485,
"author": "AquilaX",
"author_id": 17734,
"author_profile": "https://Stackoverflow.com/users/17734",
"pm_score": -1,
"selected": false,
"text": "<p>Another approach is to get all primes up to n/2 first and then to check if the modulus is 0.\nAn algorithm I use to get all the primes up to <strong>n</strong> can be found <a href=\"http://dev.horemag.net/2007/11/04/prime-numbers-in-php/\" rel=\"nofollow noreferrer\">here</a>.</p>\n"
},
{
"answer_id": 201707,
"author": "Steve Moyer",
"author_id": 17008,
"author_profile": "https://Stackoverflow.com/users/17008",
"pm_score": 1,
"selected": false,
"text": "<p>Using a recursive algorithm in Java runs less than a second ... think your algorithm through a bit as it includes some \"brute-forcing\" that can be eliminated. Also look at how your solution space can be reduced by intermediate calculations.</p>\n"
},
{
"answer_id": 210103,
"author": "Matthew Scharley",
"author_id": 15537,
"author_profile": "https://Stackoverflow.com/users/15537",
"pm_score": 2,
"selected": false,
"text": "<p>The way I did it was to search for primes (<code>p</code>), starting at 2 using the Sieve of Eratosthenes. This algorithm can find all the primes under 10 million in <2s on a decently fast machine.</p>\n\n<p>For every prime you find, test divide it into the number you are testing against untill you can't do integer division anymore. (ie. check <code>n % p == 0</code> and if true, then divide.)</p>\n\n<p>Once <code>n = 1</code>, you're done. The last value of <code>n</code> that successfully divided is your answer. On a sidenote, you've also found all the prime factors of <code>n</code> on the way.</p>\n\n<p>PS: As been noted before, you only need to search for primes between <code>2 <= n <= sqrt(p)</code>. This makes the Sieve of Eratosthenes a very fast and easy to implement algorithm for our purposes.</p>\n"
},
{
"answer_id": 211229,
"author": "jfs",
"author_id": 4279,
"author_profile": "https://Stackoverflow.com/users/4279",
"pm_score": 0,
"selected": false,
"text": "<p>All Project Euler's problems should take less then a minute; even an unoptimized recursive implementation in Python takes less then a second [0.09 secs (cpu 4.3GHz)].</p>\n\n<pre><code>from math import sqrt\n\ndef largest_primefactor(number):\n for divisor in range(2, int(sqrt(number) + 1.5)): # divisor <= sqrt(n)\n q, r = divmod(number, divisor)\n if r == 0:\n #assert(isprime(divisor))\n # recursion depth == number of prime factors,\n # e.g. 4 has two prime factors: {2,2}\n return largest_primefactor(q) \n\n return number # number is a prime itself\n</code></pre>\n"
},
{
"answer_id": 1185740,
"author": "pageman",
"author_id": 64253,
"author_profile": "https://Stackoverflow.com/users/64253",
"pm_score": 0,
"selected": false,
"text": "<p>you might want to see this:\n<a href=\"https://stackoverflow.com/questions/188425/project-euler-problem\">Is there a simple algorithm that can determine if X is prime, and not confuse a mere mortal programmer?</a></p>\n\n<p>and I like lill mud's solution:</p>\n\n<blockquote>\n <p>require \"mathn.rb\"<br/>\n puts 600851475143.prime_division.last.first</p>\n</blockquote>\n\n<p>I checked it <a href=\"http://codepad.org/NgBPxoSK\" rel=\"nofollow noreferrer\">here</a></p>\n"
},
{
"answer_id": 3004386,
"author": "st0le",
"author_id": 216517,
"author_profile": "https://Stackoverflow.com/users/216517",
"pm_score": 3,
"selected": false,
"text": "<pre><code>long n = 600851475143L; //not even, so 2 wont be a factor\nint factor = 3; \nwhile( n > 1)\n{\n if(n % factor == 0)\n {\n n/=factor;\n }else\n factor += 2; //skip even numbrs\n}\n print factor;\n</code></pre>\n\n<p>This should be quick enough...Notice, there's no need to check for prime...</p>\n"
},
{
"answer_id": 3095865,
"author": "Dr. belisarius",
"author_id": 353410,
"author_profile": "https://Stackoverflow.com/users/353410",
"pm_score": 2,
"selected": false,
"text": "<p>Once you find the answer, enter the following in your browser ;)</p>\n\n<p><a href=\"http://www.wolframalpha.com/input/?i=FactorInteger(600851475143)\" rel=\"nofollow noreferrer\">http://www.wolframalpha.com/input/?i=FactorInteger(600851475143)</a></p>\n\n<p>Wofram Alpha is your friend</p>\n"
},
{
"answer_id": 3376319,
"author": "Deepak",
"author_id": 407233,
"author_profile": "https://Stackoverflow.com/users/407233",
"pm_score": 1,
"selected": false,
"text": "<p>Easy peasy in C++:</p>\n\n<pre><code>#include <iostream>\n\nusing namespace std;\n\n\nint main()\n{\n unsigned long long int largefactor = 600851475143;\n for(int i = 2;;)\n {\n if (largefactor <= i)\n break;\n if (largefactor % i == 0)\n {\n largefactor = largefactor / i;\n }\n else\n i++;\n }\n\n cout << largefactor << endl;\n\n cin.get();\n return 0;\n}\n</code></pre>\n"
},
{
"answer_id": 7017924,
"author": "Dangrr888",
"author_id": 888774,
"author_profile": "https://Stackoverflow.com/users/888774",
"pm_score": 1,
"selected": false,
"text": "<p>This solution on C++ took 3.7 ms on my Intel Quad Core i5 iMac (3.1 GHz)</p>\n\n<pre><code>#include <iostream>\n#include <cmath>\n#include <ctime>\n\nusing std::sqrt; using std::cin;\nusing std::cout; using std::endl;\n\nlong lpf(long n)\n{\n long start = (sqrt(n) + 2 % 2);\n if(start % 2 == 0) start++;\n\n for(long i = start; i != 2; i -= 2)\n {\n if(n % i == 0) //then i is a factor of n \n {\n long j = 2L;\n do {\n ++j;\n }\n while(i % j != 0 && j <= i);\n\n if(j == i) //then i is a prime number \n return i;\n }\n }\n}\n\nint main()\n{\n long n, ans;\n cout << \"Please enter your number: \";\n cin >> n; //600851475143L \n\n time_t start, end;\n time(&start);\n int i;\n for(i = 0; i != 3000; ++i)\n ans = lpf(n);\n time(&end);\n\n cout << \"The largest prime factor of your number is: \" << ans << endl;\n cout << \"Running time: \" << 1000*difftime(end, start)/i << \" ms.\" << endl;\n\n return 0;\n}\n</code></pre>\n"
},
{
"answer_id": 32215017,
"author": "stian",
"author_id": 1546268,
"author_profile": "https://Stackoverflow.com/users/1546268",
"pm_score": -1,
"selected": false,
"text": "<p>Maybe it is considered cheating, but one possibility in haskell is to write (for the record I wrote the lines myself and haven't checked eulerproject threads); </p>\n\n<pre><code>import Data.Numbers.Primes\nlast (primeFactors 600851475143)\n</code></pre>\n"
}
] |
2008/10/14
|
[
"https://Stackoverflow.com/questions/201377",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1284/"
] |
For example, I am trying to get a min date, a max date, and a sum in different instances. I am trying to avoid hard coding a SQL string or looping through an IList to get these values.
|
For starters, instead of beginning your search at n / 2, start it at the square root of n. You'll get half of the factors, the other half being their complement.
eg:
```
n = 27
start at floor(sqrt(27)) = 5
is 5 a factor? no
is 4 a factor? no
is 3 a factor? yes. 27 / 3 = 9. 9 is also a factor.
is 2 a factor? no.
factors are 3 and 9.
```
|
201,391 |
<p>Why is the <em>CheckBoxList</em> removed from ASP.NET MVC preview release 5? </p>
<p>Currently I don't see any way in which I can create a list of checkboxes (with similar names but different id's) so people can select 0-1-more options from the list.</p>
<p>There is an <code>CheckBoxList</code> list present in the MVCContrib library, but it is deprecated. I can understand this for the other HtmlHelpers, but there does not seem to be a replacement for the <code>CheckBoxList</code> in preview 5.</p>
<p>I would like to create a very simple list like you see below, but what is the best way to do this using ASP.NET MVC preview release 5?</p>
<pre><code><INPUT TYPE="checkbox" NAME="Inhoud" VALUE="goed"> goed
<INPUT TYPE="checkbox" NAME="Inhoud" VALUE="redelijk"> redelijk
<INPUT TYPE="checkbox" NAME="Inhoud" VALUE="matig"> matig
<INPUT TYPE="checkbox" NAME="Inhoud" VALUE="slecht"> slecht
</code></pre>
|
[
{
"answer_id": 201423,
"author": "Corin Blaikie",
"author_id": 1736,
"author_profile": "https://Stackoverflow.com/users/1736",
"pm_score": 4,
"selected": false,
"text": "<p>A for loop in the view to generate the checkboxes</p>\n\n<pre><code><% foreach(Inhoud i in ViewData[\"InhoudList\"] as List<Inhoud>) { %>\n <input type=\"checkbox\" name=\"Inhoud\" value=\"<%= i.name %>\" checked=\"checked\" /> <%= i.name %>\n<% } %> \n</code></pre>\n\n<p>Don't use <code>Html.Checkbox</code>, as that will generate two values for each item in the list (as it uses a hidden input for false values)</p>\n"
},
{
"answer_id": 279849,
"author": "JeremiahClark",
"author_id": 581,
"author_profile": "https://Stackoverflow.com/users/581",
"pm_score": 3,
"selected": false,
"text": "<p>I recently blogged about implementing the CheckBoxList helper in the MVC Beta. <a href=\"http://blogs.msdn.com/miah/archive/2008/11/10/checkboxlist-helper-for-mvc.aspx\" rel=\"nofollow noreferrer\">Here is the link.</a></p>\n"
},
{
"answer_id": 706208,
"author": "javierlinked",
"author_id": 65629,
"author_profile": "https://Stackoverflow.com/users/65629",
"pm_score": 0,
"selected": false,
"text": "<p>I recommend using <strong>JeremiahClark</strong> extension posted above. (<a href=\"http://blogs.msdn.com/miah/archive/2008/11/10/checkboxlist-helper-for-mvc.aspx\" rel=\"nofollow noreferrer\">CheckBoxList</a>)</p>\n\n<p>My controller resulted into very simple instructions. For clarify I add a fragment of my code that's absent in the sample.</p>\n\n<pre><code> var rolesList = new List<CheckBoxListInfo>();\n foreach (var role in Roles.GetAllRoles())\n {\n rolesList.Add(new CheckBoxListInfo(role, role, Roles.IsUserInRole(user.UserName, role)));\n }\n ViewData[\"roles\"] = listaRoles;\n</code></pre>\n\n<p>And in the view:</p>\n\n<pre><code><div><%= Html.CheckBoxList(\"roles\", ViewData[\"roles\"]) %></div>\n</code></pre>\n\n<p>That's all.</p>\n"
},
{
"answer_id": 1083450,
"author": "Gerardo Contijoch",
"author_id": 48468,
"author_profile": "https://Stackoverflow.com/users/48468",
"pm_score": 1,
"selected": false,
"text": "<p>I have my own implementation of CheckListBox which has support for ModelState.\nIf you are interested it's in <em><a href=\"http://gerardocontijoch.wordpress.com/2009/07/04/un-checkboxlist-que-funciona-en-asp-net-mvc/\" rel=\"nofollow noreferrer\">Un CheckBoxList que funciona en ASP.NET MVC</a></em>. The post is in Spanish, but you shouldn't have any problems reading the code.</p>\n\n<p>What is interesting in Jeremiah solution is the fact that you can set the initial state of the checkboxes, something you can't do with my CheckListBox.</p>\n"
}
] |
2008/10/14
|
[
"https://Stackoverflow.com/questions/201391",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/27857/"
] |
Why is the *CheckBoxList* removed from ASP.NET MVC preview release 5?
Currently I don't see any way in which I can create a list of checkboxes (with similar names but different id's) so people can select 0-1-more options from the list.
There is an `CheckBoxList` list present in the MVCContrib library, but it is deprecated. I can understand this for the other HtmlHelpers, but there does not seem to be a replacement for the `CheckBoxList` in preview 5.
I would like to create a very simple list like you see below, but what is the best way to do this using ASP.NET MVC preview release 5?
```
<INPUT TYPE="checkbox" NAME="Inhoud" VALUE="goed"> goed
<INPUT TYPE="checkbox" NAME="Inhoud" VALUE="redelijk"> redelijk
<INPUT TYPE="checkbox" NAME="Inhoud" VALUE="matig"> matig
<INPUT TYPE="checkbox" NAME="Inhoud" VALUE="slecht"> slecht
```
|
A for loop in the view to generate the checkboxes
```
<% foreach(Inhoud i in ViewData["InhoudList"] as List<Inhoud>) { %>
<input type="checkbox" name="Inhoud" value="<%= i.name %>" checked="checked" /> <%= i.name %>
<% } %>
```
Don't use `Html.Checkbox`, as that will generate two values for each item in the list (as it uses a hidden input for false values)
|
201,392 |
<p>I have a large number of files in a .tar.gz archive. Checking the file type with the command</p>
<pre><code>file SMS.tar.gz
</code></pre>
<p>gives the response</p>
<pre><code>gzip compressed data - deflate method , max compression
</code></pre>
<p>When I try to extract the archive with gunzip, after a delay I receive the message</p>
<pre><code>gunzip: SMS.tar.gz: unexpected end of file
</code></pre>
<p>Is there any way to recover even part of the archive?</p>
|
[
{
"answer_id": 201409,
"author": "David Segonds",
"author_id": 13673,
"author_profile": "https://Stackoverflow.com/users/13673",
"pm_score": 5,
"selected": true,
"text": "<p>Are you sure that it is a gzip file? I would first run 'file SMS.tar.gz' to validate that.</p>\n\n<p>Then I would read the <a href=\"http://www.urbanophile.com/arenn/coding/gzrt/gzrt.html\" rel=\"nofollow noreferrer\">The gzip Recovery Toolkit</a> page.</p>\n"
},
{
"answer_id": 222943,
"author": "Liudvikas Bukys",
"author_id": 5845,
"author_profile": "https://Stackoverflow.com/users/5845",
"pm_score": 5,
"selected": false,
"text": "<p>Recovery is possible but it depends on what caused the corruption.</p>\n\n<p>If the file is just truncated, getting some partial result out is not too hard; just run</p>\n\n<pre><code>gunzip < SMS.tar.gz > SMS.tar.partial\n</code></pre>\n\n<p>which will give some output despite the error at the end.</p>\n\n<p>If the compressed file has large missing blocks, it's basically hopeless after the bad block.</p>\n\n<p>If the compressed file is systematically corrupted in small ways (e.g. transferring the binary file in ASCII mode, which smashes carriage returns and newlines throughout the file), it is possible to recover but requires quite a bit of custom programming, it's really only worth it if you have absolutely no other recourse (no backups) and the data is worth a lot of effort. (I have done it successfully.) I mentioned this scenario in a <a href=\"https://stackoverflow.com/questions/59735/recover-corrupt-zip-or-gzip-files\">previous question</a>.</p>\n\n<p>The answers for .zip files differ somewhat, since zip archives have multiple separately-compressed members, so there's more hope (though most commercial tools are rather bogus, they eliminate warnings by patching CRCs, not by recovering good data). But your question was about a .tar.gz file, which is an archive with one big member.</p>\n"
},
{
"answer_id": 18915270,
"author": "Anthony Palmer",
"author_id": 572860,
"author_profile": "https://Stackoverflow.com/users/572860",
"pm_score": 2,
"selected": false,
"text": "<p>Here is one possible scenario that we encountered. We had a tar.gz file that would not decompress, trying to unzip gave the error:</p>\n\n<pre><code>gzip -d A.tar.gz\ngzip: A.tar.gz: invalid compressed data--format violated\n</code></pre>\n\n<p>I figured out that the file <em>may</em> been originally uploaded over a non binary ftp connection (we don't know for sure).</p>\n\n<p>The solution was relatively simple using the unix <code>dos2unix</code> utility</p>\n\n<pre><code>dos2unix A.tar.gz\ndos2unix: converting file A.tar.gz to UNIX format ...\ntar -xvf A.tar\nfile1.txt\nfile2.txt \n....etc.\n</code></pre>\n\n<p>It worked!\nThis is one slim possibility, and maybe worth a try - it may help somebody out there.</p>\n"
}
] |
2008/10/14
|
[
"https://Stackoverflow.com/questions/201392",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11787/"
] |
I have a large number of files in a .tar.gz archive. Checking the file type with the command
```
file SMS.tar.gz
```
gives the response
```
gzip compressed data - deflate method , max compression
```
When I try to extract the archive with gunzip, after a delay I receive the message
```
gunzip: SMS.tar.gz: unexpected end of file
```
Is there any way to recover even part of the archive?
|
Are you sure that it is a gzip file? I would first run 'file SMS.tar.gz' to validate that.
Then I would read the [The gzip Recovery Toolkit](http://www.urbanophile.com/arenn/coding/gzrt/gzrt.html) page.
|
201,436 |
<p>I'm trying to get the following code working: </p>
<pre><code> string url = String.Format(@"SOMEURL");
string user = "SOMEUSER";
string password = "SOMEPASSWORD";
FtpWebRequest ftpclientRequest = (FtpWebRequest)WebRequest.Create(new Uri(url));
ftpclientRequest.Method = WebRequestMethods.Ftp.ListDirectory;
ftpclientRequest.UsePassive = true;
ftpclientRequest.Proxy = null;
ftpclientRequest.Credentials = new NetworkCredential(user, password);
FtpWebResponse response = ftpclientRequest.GetResponse() as FtpWebResponse;
</code></pre>
<p>This normally works, but for 1 particular server this gives an Error 500: Syntax not recognized. The Change Directory command is disabled on the problem server, and the site administrator told me that .NET issues a Change Directory command by default with all FTP connections. Is that true? Is there a way to disable that?
<BR>EDIT: When I login from a command line I am in the correct directory:<BR>
ftp> pwd<BR>
257 "/" is current directory</p>
|
[
{
"answer_id": 201493,
"author": "Sijin",
"author_id": 8884,
"author_profile": "https://Stackoverflow.com/users/8884",
"pm_score": 0,
"selected": false,
"text": "<p>I think we had a similar issue a while back, I don't remember the exact details though.</p>\n\n<p>To prevent .net from issuing the cd command, see if setting the default directory for the user you're login in as is set to the directory you want to work in. You can just use a command line ftp client to check this out.</p>\n"
},
{
"answer_id": 201847,
"author": "Kev",
"author_id": 419,
"author_profile": "https://Stackoverflow.com/users/419",
"pm_score": 5,
"selected": true,
"text": "<p>I just tested this on one of our dev servers and indeed there is a CWD issued by the .NET FtpWebRequest:</p>\n\n<pre>\nnew connection from 172.16.3.210 on 172.16.3.210:21 (Explicit SSL)\nhostname resolved : devpc\nsending welcome message.\n220 Gene6 FTP Server v3.10.0 (Build 2) ready...\nUSER testuser\ntestuser, 331 Password required for testuser.\ntestuser, PASS ****\ntestuser, logged in as \"testuser\".\ntestuser, 230 User testuser logged in.\ntestuser, OPTS utf8 on\ntestuser, 501 Please CLNT first.\ntestuser, PWD\n<strong>testuser, 257 \"/\" is current directory.\ntestuser, CWD /\ntestuser, change directory '/' -> 'D:\\testfolder' --> Access allowed.\ntestuser, 250 CWD command successful. \"/\" is current directory.</strong>\ntestuser, TYPE I\ntestuser, 200 Type set to I.\ntestuser, PORT 172,16,3,210,4,127\ntestuser, 200 Port command successful.\ntestuser, NLST\ntestuser, 150 Opening data connection for directory list.\ntestuser, 226 Transfer ok.\ntestuser, 421 Connection closed, timed out.\ntestuser, disconnected. (00d00:05:01)\n</pre>\n\n<p>This was without even specifying '/' in the uri when creating the FtpWebRequest object.</p>\n\n<p>If you debug or browse the source code, a class called 'FtpControlStream' comes into play. See call stack:</p>\n\n<pre>\nSystem.dll!System.Net.FtpControlStream.BuildCommandsList(System.Net.WebRequest req) Line 555 C#\nSystem.dll!System.Net.CommandStream.SubmitRequest(System.Net.WebRequest request = \n {System.Net.FtpWebRequest}, bool async = false, bool readInitalResponseOnConnect = true) Line 143 C#\nSystem.dll!System.Net.FtpWebRequest.TimedSubmitRequestHelper(bool async) Line 1122 + 0x13 bytes C#\nSystem.dll!System.Net.FtpWebRequest.SubmitRequest(bool async = false) Line 1042 + 0xc bytes C#\nSystem.dll!System.Net.FtpWebRequest.GetResponse() Line 649 C#\n</pre>\n\n<p>There's a method named BuildCommandsList() which is invoked. BuildCommandsList() builds a list of commands to send to the FTP server. This method has the following snippet of code:</p>\n\n<pre><code>if (m_PreviousServerPath != newServerPath) { \n if (!m_IsRootPath\n && m_LoginState == FtpLoginState.LoggedIn\n && m_LoginDirectory != null)\n { \n newServerPath = m_LoginDirectory+newServerPath;\n } \n m_NewServerPath = newServerPath; \n\n commandList.Add(new PipelineEntry(FormatFtpCommand(\"CWD\", newServerPath), PipelineEntryFlags.UserCommand)); \n}\n</code></pre>\n\n<p>Upon the first connection to the server m_PreviousServerPath is always null, the value of newServerPath is \"/\" and is computed by a function named GetPathAndFileName() (invoked a few lines prior to this block of code). GetPathAndFileName() computes newServerPath as \"/\" if no path is supplied or if \"/\" is explicitly tacked on the end of the 'ftp://....' uri.</p>\n\n<p>So this of course ultimately causes the CWD command to be added to the command pipeline because null != \"/\".</p>\n\n<p>In a nutshell unfortunately you can't override this behaviour because it's burned in the source.</p>\n"
},
{
"answer_id": 205615,
"author": "David Grayson",
"author_id": 28128,
"author_profile": "https://Stackoverflow.com/users/28128",
"pm_score": 0,
"selected": false,
"text": "<p>Here is a solution: use this free, open source, FTP Client Library for C# made by Dan at C-SharpCorner.com:\n<a href=\"http://www.c-sharpcorner.com/uploadfile/danglass/ftpclient12062005053849am/ftpclient.aspx\" rel=\"nofollow noreferrer\">http://www.c-sharpcorner.com/uploadfile/danglass/ftpclient12062005053849am/ftpclient.aspx</a></p>\n\n<p>Here is some example code for uploading a file:</p>\n\n<pre><code>FtpClient ftp = new FtpClient(FtpServer,FtpUserName,FtpPassword);\nftp.Login();\nftp.Upload(@\"C:\\image.jpg\");\nftp.Close(); \n</code></pre>\n\n<p>This library works fine out of the box, but can also easily be extended and modified.</p>\n"
},
{
"answer_id": 8165539,
"author": "Riddle",
"author_id": 1051534,
"author_profile": "https://Stackoverflow.com/users/1051534",
"pm_score": 1,
"selected": false,
"text": "<p>Though the post is like long time ago... never mind, I'll provide the answer here.</p>\n\n<p>Instead of using <code>ftp://server/path</code> as the uri, try <code>ftp://server/%2fpath/</code>.</p>\n\n<p>The added <code>%2f</code>\" is just an escaped <code>/</code>, adding this will make C# treat the whole path as absolute. \nOr else C# will login to <code>ftp://server/</code> with the username, go to the user's home folder, then cd to your specified path, so your path become <code>user_home_path/path</code>, which may not be desirable.</p>\n\n<p>More info could be found at msdn\n<a href=\"http://msdn.microsoft.com/en-us/library/system.net.ftpwebrequest.aspx\" rel=\"nofollow\">http://msdn.microsoft.com/en-us/library/system.net.ftpwebrequest.aspx</a></p>\n\n<p>Hope this helps.</p>\n"
},
{
"answer_id": 46574248,
"author": "Jim Software",
"author_id": 6827636,
"author_profile": "https://Stackoverflow.com/users/6827636",
"pm_score": 0,
"selected": false,
"text": "<p>Using the info above, this worked for me.</p>\n\n<p>Sends CWD -\nftpState.ftpRequest = GetRequest(\"<a href=\"ftp://192.168.0.2/tmp/file2download\" rel=\"nofollow noreferrer\">ftp://192.168.0.2/tmp/file2download</a>\")</p>\n\n<p>Does not send CWD -\nftpState.ftpRequest = GetRequest(\"<a href=\"ftp://192.168.0.2//tmp/file2download\" rel=\"nofollow noreferrer\">ftp://192.168.0.2//tmp/file2download</a>\")\n notice the // after the server IP (or name)</p>\n\n<p>DotNET version 2.0</p>\n\n<pre><code>Private Function GetRequest(ByVal URI As String) As FtpWebRequest\n 'create request\n Dim result As FtpWebRequest = CType(FtpWebRequest.Create(URI), FtpWebRequest)\n Return result\nEnd Function\n</code></pre>\n"
}
] |
2008/10/14
|
[
"https://Stackoverflow.com/questions/201436",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20754/"
] |
I'm trying to get the following code working:
```
string url = String.Format(@"SOMEURL");
string user = "SOMEUSER";
string password = "SOMEPASSWORD";
FtpWebRequest ftpclientRequest = (FtpWebRequest)WebRequest.Create(new Uri(url));
ftpclientRequest.Method = WebRequestMethods.Ftp.ListDirectory;
ftpclientRequest.UsePassive = true;
ftpclientRequest.Proxy = null;
ftpclientRequest.Credentials = new NetworkCredential(user, password);
FtpWebResponse response = ftpclientRequest.GetResponse() as FtpWebResponse;
```
This normally works, but for 1 particular server this gives an Error 500: Syntax not recognized. The Change Directory command is disabled on the problem server, and the site administrator told me that .NET issues a Change Directory command by default with all FTP connections. Is that true? Is there a way to disable that?
EDIT: When I login from a command line I am in the correct directory:
ftp> pwd
257 "/" is current directory
|
I just tested this on one of our dev servers and indeed there is a CWD issued by the .NET FtpWebRequest:
```
new connection from 172.16.3.210 on 172.16.3.210:21 (Explicit SSL)
hostname resolved : devpc
sending welcome message.
220 Gene6 FTP Server v3.10.0 (Build 2) ready...
USER testuser
testuser, 331 Password required for testuser.
testuser, PASS ****
testuser, logged in as "testuser".
testuser, 230 User testuser logged in.
testuser, OPTS utf8 on
testuser, 501 Please CLNT first.
testuser, PWD
**testuser, 257 "/" is current directory.
testuser, CWD /
testuser, change directory '/' -> 'D:\testfolder' --> Access allowed.
testuser, 250 CWD command successful. "/" is current directory.**
testuser, TYPE I
testuser, 200 Type set to I.
testuser, PORT 172,16,3,210,4,127
testuser, 200 Port command successful.
testuser, NLST
testuser, 150 Opening data connection for directory list.
testuser, 226 Transfer ok.
testuser, 421 Connection closed, timed out.
testuser, disconnected. (00d00:05:01)
```
This was without even specifying '/' in the uri when creating the FtpWebRequest object.
If you debug or browse the source code, a class called 'FtpControlStream' comes into play. See call stack:
```
System.dll!System.Net.FtpControlStream.BuildCommandsList(System.Net.WebRequest req) Line 555 C#
System.dll!System.Net.CommandStream.SubmitRequest(System.Net.WebRequest request =
{System.Net.FtpWebRequest}, bool async = false, bool readInitalResponseOnConnect = true) Line 143 C#
System.dll!System.Net.FtpWebRequest.TimedSubmitRequestHelper(bool async) Line 1122 + 0x13 bytes C#
System.dll!System.Net.FtpWebRequest.SubmitRequest(bool async = false) Line 1042 + 0xc bytes C#
System.dll!System.Net.FtpWebRequest.GetResponse() Line 649 C#
```
There's a method named BuildCommandsList() which is invoked. BuildCommandsList() builds a list of commands to send to the FTP server. This method has the following snippet of code:
```
if (m_PreviousServerPath != newServerPath) {
if (!m_IsRootPath
&& m_LoginState == FtpLoginState.LoggedIn
&& m_LoginDirectory != null)
{
newServerPath = m_LoginDirectory+newServerPath;
}
m_NewServerPath = newServerPath;
commandList.Add(new PipelineEntry(FormatFtpCommand("CWD", newServerPath), PipelineEntryFlags.UserCommand));
}
```
Upon the first connection to the server m\_PreviousServerPath is always null, the value of newServerPath is "/" and is computed by a function named GetPathAndFileName() (invoked a few lines prior to this block of code). GetPathAndFileName() computes newServerPath as "/" if no path is supplied or if "/" is explicitly tacked on the end of the 'ftp://....' uri.
So this of course ultimately causes the CWD command to be added to the command pipeline because null != "/".
In a nutshell unfortunately you can't override this behaviour because it's burned in the source.
|
201,450 |
<p>I've been working for years with VS's debugger, but every now and then I come across a feature I have never noticed before, and think "Damn! How could I have missed that? It's <strong>so</strong> useful!"</p>
<p>[Disclaimer: These tips work in VS 2005 on a C# project, no guarantees for older incarnations of VS or other languages]</p>
<h3>Keep track of object instances</h3>
<p>Working with multiple instances of a given class? How can you tell them apart?
In pre-garbage collection programming days, it was easy to keep track of references - just look at the memory address. With .NET, you can't do that - objects can get moved around.
Fortunately, the watches view lets you right-click on a watch and select 'Make Object ID'.</p>
<p>This appends a {1#}, {2#} etc. after the instance's value, effectively giving the instance a unique label.</p>
<p>The label is persisted for the lifetime of that object.</p>
<h3>Meaningful values for watched variables</h3>
<p>By default, a watched variable's value is it's type. If you want to see its fields, you have to expand it, and this could take a long time (or even timeout!) if there are many fields or they do something complicated.</p>
<p>However, some predefined types show more meaningful information :</p>
<ul>
<li>strings show their actual contents</li>
<li>lists and dictionaries show their elements count etc.</li>
</ul>
<p>Wouldn't it be nice to have that for my own types?</p>
<p>Hmm...</p>
<p>...some quality time with .NET Reflector shows how easily this can be accomplished with the <code>DebuggerDisplay</code> attribute on my custom type:</p>
<pre><code>[System.Diagnostics.DebuggerDisplay("Employee: '{Name}'")]
public class Employee {
public string Name { get { ... } }
...
}
</code></pre>
<p>... re-run, and it works.</p>
<p>There's a lot more info on the subject here: <a href="http://msdn.microsoft.com/en-us/magazine/cc163974.aspx" rel="nofollow noreferrer">MSDN</a></p>
<h3>Break on all exceptions</h3>
<p>... even the ones that are handled in code!
I know, I'm such a n00b for not knowing about this ever since I was born, but here it goes anyway - maybe this will help someone someday:</p>
<p>You can force a debugged process to break into debug mode each time an exception is thrown. Ever went on a bug hunt for hours only to come across a piece of code like this?</p>
<pre><code>try {
runStrangeContraption();
} catch(Exception ex) {
/* TODO: Will handle this error later */
}
</code></pre>
<p>Catching all exceptions is really handy in these cases.
This can be enabled from <em>Debug > Exceptions... (Ctrl-Alt-E)</em>. Tick the boxes in the 'Thrown' column for each type of exception you need.</p>
<hr />
<p>Those were a few forehead-slapping moments for me.
Would you care to share yours?</p>
|
[
{
"answer_id": 201570,
"author": "Brian",
"author_id": 19299,
"author_profile": "https://Stackoverflow.com/users/19299",
"pm_score": 3,
"selected": false,
"text": "<p>Of course, check out the VS tip of the day:</p>\n\n<p><a href=\"http://blogs.msdn.com/SaraFord/\" rel=\"nofollow noreferrer\">http://blogs.msdn.com/SaraFord/</a></p>\n"
},
{
"answer_id": 201613,
"author": "Jon Tackabury",
"author_id": 343,
"author_profile": "https://Stackoverflow.com/users/343",
"pm_score": 4,
"selected": false,
"text": "<p>I always make sure to set the \"Name\" property on new threads that I create. That way, when I'm debugging I can more easily identify different threads.</p>\n"
},
{
"answer_id": 204458,
"author": "Cristian Diaconescu",
"author_id": 11545,
"author_profile": "https://Stackoverflow.com/users/11545",
"pm_score": 4,
"selected": false,
"text": "<p>Here's another neat trick I learned:</p>\n\n<pre><code>System.Diagnostics.Debugger.Break()\n</code></pre>\n\n<p>programatically causes the debugger to break on the next instruction. The <em>really</em> nice part is, this also works for a program compiled in <strong>Release</strong> mode, without debugging information.</p>\n"
},
{
"answer_id": 204493,
"author": "ARKBAN",
"author_id": 11889,
"author_profile": "https://Stackoverflow.com/users/11889",
"pm_score": 2,
"selected": false,
"text": "<p>Conditional breaks are very useful if you have code that is repeated a lot but only fails under a specific set of conditions, such as code in a loop, methods called from a loop, or methods called from multiple threads. Put the break statement at the line of interest and set its conditions to match the error case. (There is a quick example <a href=\"http://www.odetocode.com/Articles/425.aspx\" rel=\"nofollow noreferrer\">here</a>.)</p>\n"
},
{
"answer_id": 204496,
"author": "Atanas Korchev",
"author_id": 10141,
"author_profile": "https://Stackoverflow.com/users/10141",
"pm_score": 3,
"selected": false,
"text": "<p>A few from me</p>\n\n<ul>\n<li>Uncheck the \"Enable Just My Code\" option in Tools->Options->Debugging.</li>\n<li>Conditional breakpoints - they save my life almost every day</li>\n<li><a href=\"http://blogs.msdn.com/sburke/archive/2008/01/16/configuring-visual-studio-to-debug-net-framework-source-code.aspx\" rel=\"nofollow noreferrer\">Use the .NET framework source</a> if things get ugly</li>\n</ul>\n"
},
{
"answer_id": 204499,
"author": "David Mohundro",
"author_id": 4570,
"author_profile": "https://Stackoverflow.com/users/4570",
"pm_score": 2,
"selected": false,
"text": "<p>Tools -> Attach To Process - easy to forget, but with it I can debug script in web pages, managed code loaded up in another process (think an add-in model), or even unmanaged code. Be careful with letting it automatically pick the type of debugging you're interested in.</p>\n\n<p>Tracepoints (and other breakpoint features... right click on the breakpoint and have fun)! - <a href=\"http://blogs.msdn.com/saraford/archive/2008/06/13/did-you-know-you-can-use-tracepoints-to-log-printf-or-console-writeline-info-without-editing-your-code-237.aspx\" rel=\"nofollow noreferrer\">http://blogs.msdn.com/saraford/archive/2008/06/13/did-you-know-you-can-use-tracepoints-to-log-printf-or-console-writeline-info-without-editing-your-code-237.aspx</a></p>\n\n<p>The immediate window is awesome.</p>\n\n<p><a href=\"http://msdn.microsoft.com/en-us/library/bt727f1t.aspx\" rel=\"nofollow noreferrer\">Remote Debugging</a> is very useful if you deploy apps (and can get to the machine where the problem can be reproduced).</p>\n\n<p>There are tons more. Try getting into WinDbg and SoS!</p>\n"
},
{
"answer_id": 204591,
"author": "leppie",
"author_id": 15541,
"author_profile": "https://Stackoverflow.com/users/15541",
"pm_score": 3,
"selected": false,
"text": "<p><code>.load sos</code> in the Immediate window :)</p>\n"
},
{
"answer_id": 204609,
"author": "plinth",
"author_id": 20481,
"author_profile": "https://Stackoverflow.com/users/20481",
"pm_score": 4,
"selected": false,
"text": "<pre><code>try {\n // do something big\n}\ncatch {\n // breakpoint set here:\n throw CantHappenException(\"something horrible happened that should never happen.\");\n}\n</code></pre>\n\n<p>How do you see the exception that was originally thrown? In a watch window, enter $exception</p>\n"
},
{
"answer_id": 400874,
"author": "CestLaGalere",
"author_id": 6684,
"author_profile": "https://Stackoverflow.com/users/6684",
"pm_score": 2,
"selected": false,
"text": "<p>Two from me:\none that I hope everyone uses all over the place:</p>\n\n<pre><code>Debug.Assert(<condition>, <message>)\n</code></pre>\n\n<p>the second DebuggerHidden:</p>\n\n<pre><code><DebuggerHidden()> _\nPublic Sub ReadDocumentProperty(ByVal propertyName As String, ByRef PropVal As Integer, ByVal DefaultVal As Integer)\n Try\n Dim prop As Office.DocumentProperty\n prop = CustomProps.Item(propertyName)\n PropVal = CType(prop.Value, Integer)\n Catch\n PropVal = DefaultVal\n End Try\nEnd Sub\n</code></pre>\n\n<p>Even if you have Debug, Exceptions, Break on thrown exceptions set, exceptions in here will not be caught.</p>\n"
},
{
"answer_id": 401149,
"author": "etsuba",
"author_id": 46483,
"author_profile": "https://Stackoverflow.com/users/46483",
"pm_score": 2,
"selected": false,
"text": "<p>I found the Modules window useful a lot of times. It tells whether the debugger has loaded a required dll and which version of the dll is loaded. It also lets you manually load or unload a dll.</p>\n"
},
{
"answer_id": 1367758,
"author": "Paolo Tedesco",
"author_id": 15622,
"author_profile": "https://Stackoverflow.com/users/15622",
"pm_score": 4,
"selected": true,
"text": "<p>Two in-code tricks:</p>\n\n<p>I really like the <a href=\"http://msdn.microsoft.com/en-us/library/system.diagnostics.debuggerstepthroughattribute.aspx\" rel=\"nofollow noreferrer\">System.Diagnostics.DebuggerStepThrough</a> attribute; you can attach it to a class, method or property to make VS not enter the code by default when debugging. I prefer it over the <a href=\"http://msdn.microsoft.com/en-us/library/system.diagnostics.debuggerhiddenattribute.aspx\" rel=\"nofollow noreferrer\">DebuggerHidden</a> attribute as it will still allow you to put breakpoints in the ignored code if you really need to debug it.</p>\n\n<p>Another (sometimes) useful call is <a href=\"http://msdn.microsoft.com/en-us/library/system.diagnostics.debugger.launch.aspx\" rel=\"nofollow noreferrer\">System.Diagnostics.Debugger.Launch()</a>; when the execution hits it, you will be presented with the \"select a debugger\" dialog, and a debugger will start. A bit rude, but useful with particularly nasty to attach to processes, like a process that gets spawned by another and immediately executes your code.</p>\n"
},
{
"answer_id": 3558770,
"author": "Dominik Weber",
"author_id": 428708,
"author_profile": "https://Stackoverflow.com/users/428708",
"pm_score": 0,
"selected": false,
"text": "<p>In unmanaged code you can set \"data breakpoints\". They user the debug registers of the CPU to issue an INT3 and the debugger stops on that instruction with no overhead during run time (in older version the debugger stepped through the program checking the memory..... slow!)</p>\n\n<p>This is useful if you have some corruption at a knwon address (stack / heap vaiable getting clobbered). </p>\n\n<p>Also AutoExp.dat in ide\\packages\\debugger can be customized to show your data structures.</p>\n\n<p>pointer, mb shows a hex dump in the watch window\n<a href=\"http://msdn.microsoft.com/en-us/magazine/dd252945.aspx\" rel=\"nofollow noreferrer\">http://msdn.microsoft.com/en-us/magazine/dd252945.aspx</a></p>\n\n<p>Yum!</p>\n"
},
{
"answer_id": 4351298,
"author": "Tony_Henrich",
"author_id": 129001,
"author_profile": "https://Stackoverflow.com/users/129001",
"pm_score": 1,
"selected": false,
"text": "<p>Create a Macro for attaching to a process and assign to an unused keyboard shortcut. Much faster than going: debug -> attach to process -> search for the process in the processes list ->...</p>\n"
},
{
"answer_id": 5328667,
"author": "Chathuranga Wijeratna",
"author_id": 144452,
"author_profile": "https://Stackoverflow.com/users/144452",
"pm_score": 1,
"selected": false,
"text": "<p>How about setting the IDE to break into exceptions when they occur, even when we don't have any debug point set.</p>\n\n<p>Debug--> Exceptions-->Commmon Language Runtime Exceptions-->Thrown</p>\n\n<p>This makes finding hidden exception handling problems a breeze. Actually this is kind of a setting every developer should have set through out the development, to avoid any unhanded or even handled exceptions that are going underneath.</p>\n"
}
] |
2008/10/14
|
[
"https://Stackoverflow.com/questions/201450",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11545/"
] |
I've been working for years with VS's debugger, but every now and then I come across a feature I have never noticed before, and think "Damn! How could I have missed that? It's **so** useful!"
[Disclaimer: These tips work in VS 2005 on a C# project, no guarantees for older incarnations of VS or other languages]
### Keep track of object instances
Working with multiple instances of a given class? How can you tell them apart?
In pre-garbage collection programming days, it was easy to keep track of references - just look at the memory address. With .NET, you can't do that - objects can get moved around.
Fortunately, the watches view lets you right-click on a watch and select 'Make Object ID'.
This appends a {1#}, {2#} etc. after the instance's value, effectively giving the instance a unique label.
The label is persisted for the lifetime of that object.
### Meaningful values for watched variables
By default, a watched variable's value is it's type. If you want to see its fields, you have to expand it, and this could take a long time (or even timeout!) if there are many fields or they do something complicated.
However, some predefined types show more meaningful information :
* strings show their actual contents
* lists and dictionaries show their elements count etc.
Wouldn't it be nice to have that for my own types?
Hmm...
...some quality time with .NET Reflector shows how easily this can be accomplished with the `DebuggerDisplay` attribute on my custom type:
```
[System.Diagnostics.DebuggerDisplay("Employee: '{Name}'")]
public class Employee {
public string Name { get { ... } }
...
}
```
... re-run, and it works.
There's a lot more info on the subject here: [MSDN](http://msdn.microsoft.com/en-us/magazine/cc163974.aspx)
### Break on all exceptions
... even the ones that are handled in code!
I know, I'm such a n00b for not knowing about this ever since I was born, but here it goes anyway - maybe this will help someone someday:
You can force a debugged process to break into debug mode each time an exception is thrown. Ever went on a bug hunt for hours only to come across a piece of code like this?
```
try {
runStrangeContraption();
} catch(Exception ex) {
/* TODO: Will handle this error later */
}
```
Catching all exceptions is really handy in these cases.
This can be enabled from *Debug > Exceptions... (Ctrl-Alt-E)*. Tick the boxes in the 'Thrown' column for each type of exception you need.
---
Those were a few forehead-slapping moments for me.
Would you care to share yours?
|
Two in-code tricks:
I really like the [System.Diagnostics.DebuggerStepThrough](http://msdn.microsoft.com/en-us/library/system.diagnostics.debuggerstepthroughattribute.aspx) attribute; you can attach it to a class, method or property to make VS not enter the code by default when debugging. I prefer it over the [DebuggerHidden](http://msdn.microsoft.com/en-us/library/system.diagnostics.debuggerhiddenattribute.aspx) attribute as it will still allow you to put breakpoints in the ignored code if you really need to debug it.
Another (sometimes) useful call is [System.Diagnostics.Debugger.Launch()](http://msdn.microsoft.com/en-us/library/system.diagnostics.debugger.launch.aspx); when the execution hits it, you will be presented with the "select a debugger" dialog, and a debugger will start. A bit rude, but useful with particularly nasty to attach to processes, like a process that gets spawned by another and immediately executes your code.
|
201,461 |
<p>I was playing around with my own Sudoku solver and was looking for some pointers to good and fast design when I came across this:</p>
<pre><code>def r(a):i=a.find('0');~i or exit(a);[m
in[(i-j)%9*(i/9^j/9)*(i/27^j/27|i%9/3^j%9/3)or a[j]for
j in range(81)]or r(a[:i]+m+a[i+1:])for m in'%d'%5**18]
from sys import*;r(argv[1])
</code></pre>
<p>My own implementation solves Sudokus the same way I solve them in my head but how does this cryptic algorithm work?</p>
<p><a href="http://scottkirkwood.blogspot.com/2006/07/shortest-sudoku-solver-in-python.html" rel="noreferrer">http://scottkirkwood.blogspot.com/2006/07/shortest-sudoku-solver-in-python.html</a></p>
|
[
{
"answer_id": 201496,
"author": "Lou Franco",
"author_id": 3937,
"author_profile": "https://Stackoverflow.com/users/3937",
"pm_score": 3,
"selected": false,
"text": "<p>A lot of the short sudoku solvers just recursively try every possible legal number left until they have successfully filled the cells. I haven't taken this apart, but just skimming it, it looks like that's what it does.</p>\n"
},
{
"answer_id": 201550,
"author": "Tetha",
"author_id": 17663,
"author_profile": "https://Stackoverflow.com/users/17663",
"pm_score": 3,
"selected": false,
"text": "<p>unobfuscating it:</p>\n\n<pre><code>def r(a):\n i = a.find('0') # returns -1 on fail, index otherwise\n ~i or exit(a) # ~(-1) == 0, anthing else is not 0\n # thus: if i == -1: exit(a)\n inner_lexp = [ (i-j)%9*(i/9 ^ j/9)*(i/27 ^ j/27 | i%9/3 ^ j%9/3) or a[j] \n for j in range(81)] # r appears to be a string of 81 \n # characters with 0 for empty and 1-9 \n # otherwise\n [m in inner_lexp or r(a[:i]+m+a[i+1:]) for m in'%d'%5**18] # recurse\n # trying all possible digits for that empty field\n # if m is not in the inner lexp\n\nfrom sys import *\nr(argv[1]) # thus, a is some string\n</code></pre>\n\n<p>So, we just need to work out the inner list expression. I know it collects the digits set in the line -- otherwise, the code around it makes no sense. However, I have no real clue how it does that (and Im too tired to work out that binary fancyness right now, sorry)</p>\n"
},
{
"answer_id": 201566,
"author": "Deestan",
"author_id": 6848,
"author_profile": "https://Stackoverflow.com/users/6848",
"pm_score": 3,
"selected": false,
"text": "<p><code>r(a)</code> is a recursive function which attempts to fill in a <code>0</code> in the board in each step.</p>\n\n<p><code>i=a.find('0');~i or exit(a)</code> is the on-success termination. If no more <code>0</code> values exist in the board, we're done.</p>\n\n<p><code>m</code> is the current value we will try to fill the <code>0</code> with.</p>\n\n<p><code>m\nin[(i-j)%9*(i/9^j/9)*(i/27^j/27|i%9/3^j%9/3)or a[j]for\nj in range(81)]</code> evaluates to truthy if it is obivously incorrect to put <code>m</code> in the current <code>0</code>. Let's nickname it \"is_bad\". This is the most tricky bit. :)</p>\n\n<p><code>is_bad or r(a[:i]+m+a[i+1:]</code> is a conditional recursive step. It will recursively try to evaluate the next <code>0</code> in the board iff the current solution candidate appears to be sane.</p>\n\n<p><code>for m in '%d'%5**18</code> enumerates all the numbers from 1 to 9 (inefficiently).</p>\n"
},
{
"answer_id": 201771,
"author": "Bill Barksdale",
"author_id": 16113,
"author_profile": "https://Stackoverflow.com/users/16113",
"pm_score": 9,
"selected": true,
"text": "<p>Well, you can make things a little easier by fixing up the syntax:</p>\n\n<pre><code>def r(a):\n i = a.find('0')\n ~i or exit(a)\n [m in[(i-j)%9*(i/9^j/9)*(i/27^j/27|i%9/3^j%9/3)or a[j]for j in range(81)] or r(a[:i]+m+a[i+1:])for m in'%d'%5**18]\nfrom sys import *\nr(argv[1])\n</code></pre>\n\n<p>Cleaning up a little:</p>\n\n<pre><code>from sys import exit, argv\ndef r(a):\n i = a.find('0')\n if i == -1:\n exit(a)\n for m in '%d' % 5**18:\n m in[(i-j)%9*(i/9^j/9)*(i/27^j/27|i%9/3^j%9/3) or a[j] for j in range(81)] or r(a[:i]+m+a[i+1:])\n\nr(argv[1])\n</code></pre>\n\n<p>Okay, so this script expects a command-line argument, and calls the function r on it. If there are no zeros in that string, r exits and prints out its argument. </p>\n\n<blockquote>\n <p>(If another type of object is passed,\n None is equivalent to passing zero,\n and any other object is printed to\n sys.stderr and results in an exit\n code of 1. In particular,\n sys.exit(\"some error message\") is a\n quick way to exit a program when an\n error occurs. See\n <a href=\"http://www.python.org/doc/2.5.2/lib/module-sys.html\" rel=\"noreferrer\">http://www.python.org/doc/2.5.2/lib/module-sys.html</a>)</p>\n</blockquote>\n\n<p>I guess this means that zeros correspond to open spaces, and a puzzle with no zeros is solved. Then there's that nasty recursive expression.</p>\n\n<p>The loop is interesting: <code>for m in'%d'%5**18</code></p>\n\n<p>Why 5**18? It turns out that <code>'%d'%5**18</code> evaluates to <code>'3814697265625'</code>. This is a string that has each digit 1-9 at least once, so maybe it's trying to place each of them. In fact, it looks like this is what <code>r(a[:i]+m+a[i+1:])</code> is doing: recursively calling r, with the first blank filled in by a digit from that string. But this only happens if the earlier expression is false. Let's look at that:</p>\n\n<p><code>m in [(i-j)%9*(i/9^j/9)*(i/27^j/27|i%9/3^j%9/3) or a[j] for j in range(81)]</code></p>\n\n<p>So the placement is done only if m is not in that monster list. Each element is either a number (if the first expression is nonzero) or a character (if the first expression is zero). m is ruled out as a possible substitution if it appears as a character, which can only happen if the first expression is zero. When is the expression zero?</p>\n\n<p>It has three parts that are multiplied:</p>\n\n<ul>\n<li><code>(i-j)%9</code> which is zero if i and j are a multiple of 9 apart, i.e. the same column.</li>\n<li><code>(i/9^j/9)</code> which is zero if i/9 == j/9, i.e. the same row.</li>\n<li><code>(i/27^j/27|i%9/3^j%9/3)</code> which is zero if both of these are zero:</li>\n<li><ul>\n<li><code>i/27^j^27</code> which is zero if i/27 == j/27, i.e. the same block of three rows</li>\n</ul></li>\n<li><ul>\n<li><code>i%9/3^j%9/3</code> which is zero if i%9/3 == j%9/3, i.e. the same block of three columns</li>\n</ul></li>\n</ul>\n\n<p>If any of these three parts is zero, the entire expression is zero. In other words, if i and j share a row, column, or 3x3 block, then the value of j can't be used as a candidate for the blank at i. Aha!</p>\n\n<pre><code>from sys import exit, argv\ndef r(a):\n i = a.find('0')\n if i == -1:\n exit(a)\n for m in '3814697265625':\n okay = True\n for j in range(81):\n if (i-j)%9 == 0 or (i/9 == j/9) or (i/27 == j/27 and i%9/3 == j%9/3):\n if a[j] == m:\n okay = False\n break\n if okay:\n # At this point, m is not excluded by any row, column, or block, so let's place it and recurse\n r(a[:i]+m+a[i+1:])\n\nr(argv[1])\n</code></pre>\n\n<p>Note that if none of the placements work out, r will return and back up to the point where something else can be chosen, so it's a basic depth first algorithm.</p>\n\n<p>Not using any heuristics, it's not particularly efficient. I took this puzzle from Wikipedia (<a href=\"http://en.wikipedia.org/wiki/Sudoku\" rel=\"noreferrer\">http://en.wikipedia.org/wiki/Sudoku</a>):</p>\n\n<pre><code>$ time python sudoku.py 530070000600195000098000060800060003400803001700020006060000280000419005000080079\n534678912672195348198342567859761423426853791713924856961537284287419635345286179\n\nreal 0m47.881s\nuser 0m47.223s\nsys 0m0.137s\n</code></pre>\n\n<p>Addendum: How I would rewrite it as a maintenance programmer (this version has about a 93x speedup :)</p>\n\n<pre><code>import sys\n\ndef same_row(i,j): return (i/9 == j/9)\ndef same_col(i,j): return (i-j) % 9 == 0\ndef same_block(i,j): return (i/27 == j/27 and i%9/3 == j%9/3)\n\ndef r(a):\n i = a.find('0')\n if i == -1:\n sys.exit(a)\n\n excluded_numbers = set()\n for j in range(81):\n if same_row(i,j) or same_col(i,j) or same_block(i,j):\n excluded_numbers.add(a[j])\n\n for m in '123456789':\n if m not in excluded_numbers:\n # At this point, m is not excluded by any row, column, or block, so let's place it and recurse\n r(a[:i]+m+a[i+1:])\n\nif __name__ == '__main__':\n if len(sys.argv) == 2 and len(sys.argv[1]) == 81:\n r(sys.argv[1])\n else:\n print 'Usage: python sudoku.py puzzle'\n print ' where puzzle is an 81 character string representing the puzzle read left-to-right, top-to-bottom, and 0 is a blank'\n</code></pre>\n"
},
{
"answer_id": 21995076,
"author": "Basil",
"author_id": 3347848,
"author_profile": "https://Stackoverflow.com/users/3347848",
"pm_score": 2,
"selected": false,
"text": "<p>The code doesn't actually work. You can test it yourself. Here is a sample unsolved sudoku puzzle:</p>\n\n<p>807000003602080000000200900040005001000798000200100070004003000000040108300000506</p>\n\n<p>You can use this website (<a href=\"http://www.sudokuwiki.org/sudoku.htm\" rel=\"nofollow\">http://www.sudokuwiki.org/sudoku.htm</a>), click on import puzzle and simply copy the above string. The output of the python program is:\n817311213622482322131224934443535441555798655266156777774663869988847188399979596</p>\n\n<p>which does not correspond to the solution. In fact you can already see a contradiction, two 1s in the first row. </p>\n"
}
] |
2008/10/14
|
[
"https://Stackoverflow.com/questions/201461",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/27736/"
] |
I was playing around with my own Sudoku solver and was looking for some pointers to good and fast design when I came across this:
```
def r(a):i=a.find('0');~i or exit(a);[m
in[(i-j)%9*(i/9^j/9)*(i/27^j/27|i%9/3^j%9/3)or a[j]for
j in range(81)]or r(a[:i]+m+a[i+1:])for m in'%d'%5**18]
from sys import*;r(argv[1])
```
My own implementation solves Sudokus the same way I solve them in my head but how does this cryptic algorithm work?
<http://scottkirkwood.blogspot.com/2006/07/shortest-sudoku-solver-in-python.html>
|
Well, you can make things a little easier by fixing up the syntax:
```
def r(a):
i = a.find('0')
~i or exit(a)
[m in[(i-j)%9*(i/9^j/9)*(i/27^j/27|i%9/3^j%9/3)or a[j]for j in range(81)] or r(a[:i]+m+a[i+1:])for m in'%d'%5**18]
from sys import *
r(argv[1])
```
Cleaning up a little:
```
from sys import exit, argv
def r(a):
i = a.find('0')
if i == -1:
exit(a)
for m in '%d' % 5**18:
m in[(i-j)%9*(i/9^j/9)*(i/27^j/27|i%9/3^j%9/3) or a[j] for j in range(81)] or r(a[:i]+m+a[i+1:])
r(argv[1])
```
Okay, so this script expects a command-line argument, and calls the function r on it. If there are no zeros in that string, r exits and prints out its argument.
>
> (If another type of object is passed,
> None is equivalent to passing zero,
> and any other object is printed to
> sys.stderr and results in an exit
> code of 1. In particular,
> sys.exit("some error message") is a
> quick way to exit a program when an
> error occurs. See
> <http://www.python.org/doc/2.5.2/lib/module-sys.html>)
>
>
>
I guess this means that zeros correspond to open spaces, and a puzzle with no zeros is solved. Then there's that nasty recursive expression.
The loop is interesting: `for m in'%d'%5**18`
Why 5\*\*18? It turns out that `'%d'%5**18` evaluates to `'3814697265625'`. This is a string that has each digit 1-9 at least once, so maybe it's trying to place each of them. In fact, it looks like this is what `r(a[:i]+m+a[i+1:])` is doing: recursively calling r, with the first blank filled in by a digit from that string. But this only happens if the earlier expression is false. Let's look at that:
`m in [(i-j)%9*(i/9^j/9)*(i/27^j/27|i%9/3^j%9/3) or a[j] for j in range(81)]`
So the placement is done only if m is not in that monster list. Each element is either a number (if the first expression is nonzero) or a character (if the first expression is zero). m is ruled out as a possible substitution if it appears as a character, which can only happen if the first expression is zero. When is the expression zero?
It has three parts that are multiplied:
* `(i-j)%9` which is zero if i and j are a multiple of 9 apart, i.e. the same column.
* `(i/9^j/9)` which is zero if i/9 == j/9, i.e. the same row.
* `(i/27^j/27|i%9/3^j%9/3)` which is zero if both of these are zero:
* + `i/27^j^27` which is zero if i/27 == j/27, i.e. the same block of three rows
* + `i%9/3^j%9/3` which is zero if i%9/3 == j%9/3, i.e. the same block of three columns
If any of these three parts is zero, the entire expression is zero. In other words, if i and j share a row, column, or 3x3 block, then the value of j can't be used as a candidate for the blank at i. Aha!
```
from sys import exit, argv
def r(a):
i = a.find('0')
if i == -1:
exit(a)
for m in '3814697265625':
okay = True
for j in range(81):
if (i-j)%9 == 0 or (i/9 == j/9) or (i/27 == j/27 and i%9/3 == j%9/3):
if a[j] == m:
okay = False
break
if okay:
# At this point, m is not excluded by any row, column, or block, so let's place it and recurse
r(a[:i]+m+a[i+1:])
r(argv[1])
```
Note that if none of the placements work out, r will return and back up to the point where something else can be chosen, so it's a basic depth first algorithm.
Not using any heuristics, it's not particularly efficient. I took this puzzle from Wikipedia (<http://en.wikipedia.org/wiki/Sudoku>):
```
$ time python sudoku.py 530070000600195000098000060800060003400803001700020006060000280000419005000080079
534678912672195348198342567859761423426853791713924856961537284287419635345286179
real 0m47.881s
user 0m47.223s
sys 0m0.137s
```
Addendum: How I would rewrite it as a maintenance programmer (this version has about a 93x speedup :)
```
import sys
def same_row(i,j): return (i/9 == j/9)
def same_col(i,j): return (i-j) % 9 == 0
def same_block(i,j): return (i/27 == j/27 and i%9/3 == j%9/3)
def r(a):
i = a.find('0')
if i == -1:
sys.exit(a)
excluded_numbers = set()
for j in range(81):
if same_row(i,j) or same_col(i,j) or same_block(i,j):
excluded_numbers.add(a[j])
for m in '123456789':
if m not in excluded_numbers:
# At this point, m is not excluded by any row, column, or block, so let's place it and recurse
r(a[:i]+m+a[i+1:])
if __name__ == '__main__':
if len(sys.argv) == 2 and len(sys.argv[1]) == 81:
r(sys.argv[1])
else:
print 'Usage: python sudoku.py puzzle'
print ' where puzzle is an 81 character string representing the puzzle read left-to-right, top-to-bottom, and 0 is a blank'
```
|
201,468 |
<p>I like the flexibility of Dynamic SQL and I like the security + improved performance of Prepared Statements. So what I really want is Dynamic Prepared Statements, which is troublesome to make because bind_param and bind_result accept "fixed" number of arguments. So I made use of an eval() statement to get around this problem. But I get the feeling this is a bad idea. Here's example code of what I mean</p>
<pre><code>// array of WHERE conditions
$param = array('customer_id'=>1, 'qty'=>'2');
$stmt = $mysqli->stmt_init();
$types = ''; $bindParam = array(); $where = ''; $count = 0;
// build the dynamic sql and param bind conditions
foreach($param as $key=>$val)
{
$types .= 'i';
$bindParam[] = '$p'.$count.'=$param["'.$key.'"]';
$where .= "$key = ? AND ";
$count++;
}
// prepare the query -- SELECT * FROM t1 WHERE customer_id = ? AND qty = ?
$sql = "SELECT * FROM t1 WHERE ".substr($where, 0, strlen($where)-4);
$stmt->prepare($sql);
// assemble the bind_param command
$command = '$stmt->bind_param($types, '.implode(', ', $bindParam).');';
// evaluate the command -- $stmt->bind_param($types,$p0=$param["customer_id"],$p1=$param["qty"]);
eval($command);
</code></pre>
<p>Is that last eval() statement a bad idea? I tried to avoid code injection by encapsulating values behind the variable name $param.</p>
<p>Does anyone have an opinion or other suggestions? Are there issues I need to be aware of?</p>
|
[
{
"answer_id": 201639,
"author": "Tomalak",
"author_id": 18771,
"author_profile": "https://Stackoverflow.com/users/18771",
"pm_score": 5,
"selected": true,
"text": "<p>I think it is dangerous to use <code>eval()</code> here.</p>\n\n<p>Try this:</p>\n\n<ul>\n<li>iterate the params array to build the SQL string with question marks <code>\"SELECT * FROM t1 WHERE p1 = ? AND p2 = ?\"</code></li>\n<li>call <code>prepare()</code> on that </li>\n<li>use <code>call_user_func_array()</code> to make the call to <code>bind_param()</code>, passing in the dynamic params array.</li>\n</ul>\n\n<p>The code:</p>\n\n<pre><code>call_user_func_array(array($stmt, 'bind_param'), array($types)+$param);\n</code></pre>\n"
},
{
"answer_id": 205145,
"author": "rix0rrr",
"author_id": 2474,
"author_profile": "https://Stackoverflow.com/users/2474",
"pm_score": -1,
"selected": false,
"text": "<p>You don't really need prepared statements and bound arguments, because you can always use mysql_real_escape_string(). And you're right; dynamically generated SQL is far more flexible and valuable. </p>\n\n<p>Here's a simple example using the regular mysql_* interface:</p>\n\n<pre><code>// Array of WHERE conditions\n$conds = array(\"customer_id\" => 1, \"qty\" => 2);\n\n$wherec = array(\"1\");\nforeach ($conds as $col=>$val) $wherec[] = sprintf(\"`%s` = '%s'\", $col, mysql_real_escape_string($val));\n\n$result_set = mysql_query(\"SELECT * FROM t1 WHERE \" . implode(\" AND \", $wherec);\n</code></pre>\n\n<p>Of course, this is a simplistic example, and to make it useful you have to build and refine it a lot, but it shows the ideas and it's really very very useful. For example, here is a completely generic function to insert a new row into an arbitrary table, with the columns filled with the values from an associative array and completely SQL-injection safe:</p>\n\n<pre><code>function insert($table, $record) {\n $cols = array();\n $vals = array();\n foreach (array_keys($record) as $col) $cols[] = sprintf(\"`%s`\", $col);\n foreach (array_values($record) as $val) $vals[] = sprintf(\"'%s'\", mysql_real_escape_string($val));\n\n mysql_query(sprintf(\"INSERT INTO `%s`(%s) VALUES(%s)\", $table, implode(\", \", $cols), implode(\", \", $vals)));\n}\n\n// Use as follows:\ninsert(\"customer\", array(\"customer_id\" => 15, \"qty\" => 86));\n</code></pre>\n"
},
{
"answer_id": 54048416,
"author": "boctulus",
"author_id": 980631,
"author_profile": "https://Stackoverflow.com/users/980631",
"pm_score": 0,
"selected": false,
"text": "<p>I made a filter function which recives an array an asociative array like $_GET:</p>\n\n<p>In model class I've defined a couple of properties including the schema:</p>\n\n<pre><code>private $table_name = \"products\";\n\nprotected $schema = [\n 'id' => 'INT',\n 'name' => 'STR',\n 'description' => 'STR',\n 'size' => 'STR',\n 'cost' => 'INT',\n 'active' => 'BOOL'\n];\n</code></pre>\n\n<p>Then a filter method which recive an asociative arrays of conditions:</p>\n\n<pre><code>function filter($conditions)\n{\n $vars = array_keys($conditions);\n $values = array_values($conditions);\n\n $where = '';\n foreach($vars as $ix => $var){\n $where .= \"$var = :$var AND \";\n }\n $where =trim(substr($where, 0, strrpos( $where, 'AND ')));\n\n $q = \"SELECT * FROM {$this->table_name} WHERE $where\";\n $st = $this->conn->prepare($q);\n\n foreach($values as $ix => $val){\n $st->bindValue(\":{$vars[$ix]}\", $val, constant(\"PDO::PARAM_{$this->schema[$vars[$ix]]}\"));\n }\n\n $st->execute();\n return $st->fetchAll(PDO::FETCH_ASSOC);\n}\n</code></pre>\n\n<p>And works great to filter results</p>\n"
}
] |
2008/10/14
|
[
"https://Stackoverflow.com/questions/201468",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/27305/"
] |
I like the flexibility of Dynamic SQL and I like the security + improved performance of Prepared Statements. So what I really want is Dynamic Prepared Statements, which is troublesome to make because bind\_param and bind\_result accept "fixed" number of arguments. So I made use of an eval() statement to get around this problem. But I get the feeling this is a bad idea. Here's example code of what I mean
```
// array of WHERE conditions
$param = array('customer_id'=>1, 'qty'=>'2');
$stmt = $mysqli->stmt_init();
$types = ''; $bindParam = array(); $where = ''; $count = 0;
// build the dynamic sql and param bind conditions
foreach($param as $key=>$val)
{
$types .= 'i';
$bindParam[] = '$p'.$count.'=$param["'.$key.'"]';
$where .= "$key = ? AND ";
$count++;
}
// prepare the query -- SELECT * FROM t1 WHERE customer_id = ? AND qty = ?
$sql = "SELECT * FROM t1 WHERE ".substr($where, 0, strlen($where)-4);
$stmt->prepare($sql);
// assemble the bind_param command
$command = '$stmt->bind_param($types, '.implode(', ', $bindParam).');';
// evaluate the command -- $stmt->bind_param($types,$p0=$param["customer_id"],$p1=$param["qty"]);
eval($command);
```
Is that last eval() statement a bad idea? I tried to avoid code injection by encapsulating values behind the variable name $param.
Does anyone have an opinion or other suggestions? Are there issues I need to be aware of?
|
I think it is dangerous to use `eval()` here.
Try this:
* iterate the params array to build the SQL string with question marks `"SELECT * FROM t1 WHERE p1 = ? AND p2 = ?"`
* call `prepare()` on that
* use `call_user_func_array()` to make the call to `bind_param()`, passing in the dynamic params array.
The code:
```
call_user_func_array(array($stmt, 'bind_param'), array($types)+$param);
```
|
201,476 |
<p>I am getting the following error when I get to the line that invokes a REALLY BASIC web service I have running on Tomcat/Axis.</p>
<pre><code>Element or attribute do not match QName production: QName::=(NCName':')?NCName
</code></pre>
<p>Have I got something wrong with QName?- I can't even find any useful information about it.</p>
<p>My client code is below:</p>
<pre><code>import javax.xml.namespace.QName;
import org.apache.axis.client.Call;
import org.apache.axis.client.Service;
public class TestClient {
public static void main(String [] args)
{
try{
String endpoint = "http://localhost:8080/TestWebService/services/DoesMagic";
Service service = new Service();
Call call = (Call) service.createCall();
call.setTargetEndpointAddress( new java.net.URL(endpoint) );
call.setOperationName( new QName("http://testPackage.fc.com/, doBasicStuff") );
String ret = (String) call.invoke( new Object[] {"some kind of message"} );
System.out.println(ret);
}catch(Exception e){
System.err.println(e.toString());
}
}
}
</code></pre>
<p>My web serivce code is really basic - just a simple class that returns your input string with a bit of concat text:</p>
<pre><code>public String doBasicStuff(String message)
{
return "This is your message: " + message;
}
</code></pre>
|
[
{
"answer_id": 201497,
"author": "Rich Kroll",
"author_id": 58733,
"author_profile": "https://Stackoverflow.com/users/58733",
"pm_score": 3,
"selected": false,
"text": "<p>Could it be a typo in your QName?:</p>\n\n<pre><code>new QName(\"http://testPackage.fc.com/\", \"doBasicStuff\")\n</code></pre>\n\n<p>instead of:</p>\n\n<pre><code>new QName(\"http://testPackage.fc.com/, doBasicStuff\")\n</code></pre>\n"
},
{
"answer_id": 201508,
"author": "Martin Probst",
"author_id": 22227,
"author_profile": "https://Stackoverflow.com/users/22227",
"pm_score": 4,
"selected": true,
"text": "<p>As the exception says, you call the QName constructor incorrectly:</p>\n\n<pre><code>new QName(\"http://testPackage.fc.com/, doBasicStuff\")\n</code></pre>\n\n<p>is incorrect. I think you have to pass two strings, one containing the namespace, one the localname. The documentation will typically contain a description on how to use that class.</p>\n"
},
{
"answer_id": 2632101,
"author": "Don G.",
"author_id": 315793,
"author_profile": "https://Stackoverflow.com/users/315793",
"pm_score": 0,
"selected": false,
"text": "<p>You should use one of these:</p>\n\n<pre><code>public QName(String localPart) or\npublic QName(final String namespaceURI, final String localPart)\n</code></pre>\n\n<p>but\n new QName(\"<a href=\"http://testPackage.fc.com/\" rel=\"nofollow noreferrer\">http://testPackage.fc.com/</a>, doBasicStuff\")\nis wrong, since both values are in the same string \".., ..\"</p>\n\n<p>Regards</p>\n"
},
{
"answer_id": 8368592,
"author": "Ali Hashemi",
"author_id": 1079103,
"author_profile": "https://Stackoverflow.com/users/1079103",
"pm_score": 0,
"selected": false,
"text": "<p>new QName(\"soapenc:string\", \"doBasicStuff\")</p>\n"
},
{
"answer_id": 13887993,
"author": "mohamed",
"author_id": 1905444,
"author_profile": "https://Stackoverflow.com/users/1905444",
"pm_score": 0,
"selected": false,
"text": "<p>Just type the name of metod that have to on your case it would be \n<code>call.setOperationName(\"doBasicStuff\");</code></p>\n"
}
] |
2008/10/14
|
[
"https://Stackoverflow.com/questions/201476",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5175/"
] |
I am getting the following error when I get to the line that invokes a REALLY BASIC web service I have running on Tomcat/Axis.
```
Element or attribute do not match QName production: QName::=(NCName':')?NCName
```
Have I got something wrong with QName?- I can't even find any useful information about it.
My client code is below:
```
import javax.xml.namespace.QName;
import org.apache.axis.client.Call;
import org.apache.axis.client.Service;
public class TestClient {
public static void main(String [] args)
{
try{
String endpoint = "http://localhost:8080/TestWebService/services/DoesMagic";
Service service = new Service();
Call call = (Call) service.createCall();
call.setTargetEndpointAddress( new java.net.URL(endpoint) );
call.setOperationName( new QName("http://testPackage.fc.com/, doBasicStuff") );
String ret = (String) call.invoke( new Object[] {"some kind of message"} );
System.out.println(ret);
}catch(Exception e){
System.err.println(e.toString());
}
}
}
```
My web serivce code is really basic - just a simple class that returns your input string with a bit of concat text:
```
public String doBasicStuff(String message)
{
return "This is your message: " + message;
}
```
|
As the exception says, you call the QName constructor incorrectly:
```
new QName("http://testPackage.fc.com/, doBasicStuff")
```
is incorrect. I think you have to pass two strings, one containing the namespace, one the localname. The documentation will typically contain a description on how to use that class.
|
201,515 |
<p>I have a simple website I'm testing. It's running on localhost and I can access it in my web browser. The index page is simply the word "running". <code>urllib.urlopen</code> will successfully read the page but <code>urllib2.urlopen</code> will not. Here's a script which demonstrates the problem (this is the actual script and not a simplification of a different test script):</p>
<pre><code>import urllib, urllib2
print urllib.urlopen("http://127.0.0.1").read() # prints "running"
print urllib2.urlopen("http://127.0.0.1").read() # throws an exception
</code></pre>
<p>Here's the stack trace:</p>
<pre><code>Traceback (most recent call last):
File "urltest.py", line 5, in <module>
print urllib2.urlopen("http://127.0.0.1").read()
File "C:\Python25\lib\urllib2.py", line 121, in urlopen
return _opener.open(url, data)
File "C:\Python25\lib\urllib2.py", line 380, in open
response = meth(req, response)
File "C:\Python25\lib\urllib2.py", line 491, in http_response
'http', request, response, code, msg, hdrs)
File "C:\Python25\lib\urllib2.py", line 412, in error
result = self._call_chain(*args)
File "C:\Python25\lib\urllib2.py", line 353, in _call_chain
result = func(*args)
File "C:\Python25\lib\urllib2.py", line 575, in http_error_302
return self.parent.open(new)
File "C:\Python25\lib\urllib2.py", line 380, in open
response = meth(req, response)
File "C:\Python25\lib\urllib2.py", line 491, in http_response
'http', request, response, code, msg, hdrs)
File "C:\Python25\lib\urllib2.py", line 418, in error
return self._call_chain(*args)
File "C:\Python25\lib\urllib2.py", line 353, in _call_chain
result = func(*args)
File "C:\Python25\lib\urllib2.py", line 499, in http_error_default
raise HTTPError(req.get_full_url(), code, msg, hdrs, fp)
urllib2.HTTPError: HTTP Error 504: Gateway Timeout
</code></pre>
<p>Any ideas? I might end up needing some of the more advanced features of <code>urllib2</code>, so I don't want to just resort to using <code>urllib</code>, plus I want to understand this problem.</p>
|
[
{
"answer_id": 201556,
"author": "Sijin",
"author_id": 8884,
"author_profile": "https://Stackoverflow.com/users/8884",
"pm_score": 1,
"selected": false,
"text": "<p>Does calling urlib2.open first followed by urllib.open have the same results? Just wondering if the first call to open is causing the http server to get busy causing the timeout?</p>\n"
},
{
"answer_id": 201737,
"author": "John Millikin",
"author_id": 3560,
"author_profile": "https://Stackoverflow.com/users/3560",
"pm_score": 5,
"selected": true,
"text": "<p>Sounds like you have proxy settings defined that urllib2 is picking up on. When it tries to proxy \"127.0.0.01/\", the proxy gives up and returns a 504 error.</p>\n\n<p>From <a href=\"http://kember.net/articles/obscure-python-urllib2-proxy-gotcha\" rel=\"nofollow noreferrer\">Obscure python urllib2 proxy gotcha</a>:</p>\n\n<pre><code>proxy_support = urllib2.ProxyHandler({})\nopener = urllib2.build_opener(proxy_support)\nprint opener.open(\"http://127.0.0.1\").read()\n\n# Optional - makes this opener default for urlopen etc.\nurllib2.install_opener(opener)\nprint urllib2.urlopen(\"http://127.0.0.1\").read()\n</code></pre>\n"
},
{
"answer_id": 201754,
"author": "Alex Coventry",
"author_id": 1941213,
"author_profile": "https://Stackoverflow.com/users/1941213",
"pm_score": 1,
"selected": false,
"text": "<p>I don't know what's going on, but you may find this helpful in figuring it out:</p>\n\n<pre><code>>>> import urllib2\n>>> urllib2.urlopen('http://mit.edu').read()[:10]\n'<!DOCTYPE '\n>>> urllib2._opener.handlers[1].set_http_debuglevel(100)\n>>> urllib2.urlopen('http://mit.edu').read()[:10]\nconnect: (mit.edu, 80)\nsend: 'GET / HTTP/1.1\\r\\nAccept-Encoding: identity\\r\\nHost: mit.edu\\r\\nConnection: close\\r\\nUser-Agent: Python-urllib/2.5\\r\\n\\r\\n'\nreply: 'HTTP/1.1 200 OK\\r\\n'\nheader: Date: Tue, 14 Oct 2008 15:52:03 GMT\nheader: Server: MIT Web Server Apache/1.3.26 Mark/1.5 (Unix) mod_ssl/2.8.9 OpenSSL/0.9.7c\nheader: Last-Modified: Tue, 14 Oct 2008 04:02:15 GMT\nheader: ETag: \"71d3f96-2895-48f419c7\"\nheader: Accept-Ranges: bytes\nheader: Content-Length: 10389\nheader: Connection: close\nheader: Content-Type: text/html\n'<!DOCTYPE '\n</code></pre>\n"
},
{
"answer_id": 201756,
"author": "Deestan",
"author_id": 6848,
"author_profile": "https://Stackoverflow.com/users/6848",
"pm_score": 1,
"selected": false,
"text": "<p>urllib.urlopen() throws the following request at the server:</p>\n\n<pre><code>GET / HTTP/1.0\nHost: 127.0.0.1\nUser-Agent: Python-urllib/1.17\n</code></pre>\n\n<p>while urllib2.urlopen() throws this:</p>\n\n<pre><code>GET / HTTP/1.1\nAccept-Encoding: identity\nHost: 127.0.0.1\nConnection: close\nUser-Agent: Python-urllib/2.5\n</code></pre>\n\n<p>So, your server either doesn't understand HTTP/1.1 or the extra header fields.</p>\n"
}
] |
2008/10/14
|
[
"https://Stackoverflow.com/questions/201515",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1694/"
] |
I have a simple website I'm testing. It's running on localhost and I can access it in my web browser. The index page is simply the word "running". `urllib.urlopen` will successfully read the page but `urllib2.urlopen` will not. Here's a script which demonstrates the problem (this is the actual script and not a simplification of a different test script):
```
import urllib, urllib2
print urllib.urlopen("http://127.0.0.1").read() # prints "running"
print urllib2.urlopen("http://127.0.0.1").read() # throws an exception
```
Here's the stack trace:
```
Traceback (most recent call last):
File "urltest.py", line 5, in <module>
print urllib2.urlopen("http://127.0.0.1").read()
File "C:\Python25\lib\urllib2.py", line 121, in urlopen
return _opener.open(url, data)
File "C:\Python25\lib\urllib2.py", line 380, in open
response = meth(req, response)
File "C:\Python25\lib\urllib2.py", line 491, in http_response
'http', request, response, code, msg, hdrs)
File "C:\Python25\lib\urllib2.py", line 412, in error
result = self._call_chain(*args)
File "C:\Python25\lib\urllib2.py", line 353, in _call_chain
result = func(*args)
File "C:\Python25\lib\urllib2.py", line 575, in http_error_302
return self.parent.open(new)
File "C:\Python25\lib\urllib2.py", line 380, in open
response = meth(req, response)
File "C:\Python25\lib\urllib2.py", line 491, in http_response
'http', request, response, code, msg, hdrs)
File "C:\Python25\lib\urllib2.py", line 418, in error
return self._call_chain(*args)
File "C:\Python25\lib\urllib2.py", line 353, in _call_chain
result = func(*args)
File "C:\Python25\lib\urllib2.py", line 499, in http_error_default
raise HTTPError(req.get_full_url(), code, msg, hdrs, fp)
urllib2.HTTPError: HTTP Error 504: Gateway Timeout
```
Any ideas? I might end up needing some of the more advanced features of `urllib2`, so I don't want to just resort to using `urllib`, plus I want to understand this problem.
|
Sounds like you have proxy settings defined that urllib2 is picking up on. When it tries to proxy "127.0.0.01/", the proxy gives up and returns a 504 error.
From [Obscure python urllib2 proxy gotcha](http://kember.net/articles/obscure-python-urllib2-proxy-gotcha):
```
proxy_support = urllib2.ProxyHandler({})
opener = urllib2.build_opener(proxy_support)
print opener.open("http://127.0.0.1").read()
# Optional - makes this opener default for urlopen etc.
urllib2.install_opener(opener)
print urllib2.urlopen("http://127.0.0.1").read()
```
|
201,518 |
<p>Greetings!</p>
<p>I've created a custom button class to render the following:</p>
<pre><code><span class="btnOrange">
<input type="submit" id="ctl00_MainContent_m_GoBack" value="Back" name="ctl00$MainContent$m_GoBack"/>
</span>
</code></pre>
<p>However, it renders like this instead (note the extraneous "class" attribute in the INPUT tag):</p>
<pre><code><span class="btnOrange">
<input type="submit" class="btnOrange" id="ctl00_MainContent_m_GoBack" value="Back" name="ctl00$MainContent$m_GoBack"/>
</span>
</code></pre>
<p>My custom button class looks like this:</p>
<pre><code>[ToolboxData(@"<{0}:MyButton runat=server></{0}:MyButton>")]
public class MyButton : Button
{
public override void RenderBeginTag(HtmlTextWriter writer)
{
writer.AddAttribute(HtmlTextWriterAttribute.Class, this.CssClass);
writer.RenderBeginTag("span");
base.RenderBeginTag(writer);
}
public override void RenderEndTag(HtmlTextWriter writer)
{
writer.RenderEndTag();
base.RenderEndTag(writer);
}
}
</code></pre>
<p>Since I only need to set the class attribute for the SPAN tag, is it possible to not include or "blank out" the class attribute for the INPUT tag?</p>
|
[
{
"answer_id": 201526,
"author": "Konrad Rudolph",
"author_id": 1968,
"author_profile": "https://Stackoverflow.com/users/1968",
"pm_score": 0,
"selected": false,
"text": "<p>How about removing the <code>class</code> attribute from the <code>writer</code> object after rendering the <code>span</code> begin tag? I don't know ASP though so I could be wrong.</p>\n"
},
{
"answer_id": 203613,
"author": "cfeduke",
"author_id": 5645,
"author_profile": "https://Stackoverflow.com/users/5645",
"pm_score": 2,
"selected": true,
"text": "<p>You can do this:</p>\n\n<pre><code>private string _heldCssClass = null;\npublic override void RenderBeginTag(HtmlTextWriter writer)\n{\n writer.AddAttribute(HtmlTextWriterAttribute.Class, this.CssClass); \n writer.RenderBeginTag(\"span\");\n _heldCssClass = this.CssClass;\n this.CssClass = String.Empty;\n base.RenderBeginTag(writer);\n}\n\npublic override void RenderEndTag(HtmlTextWriter writer)\n{\n writer.RenderEndTag();\n base.RenderEndTag(writer);\n this.CssClass = _heldCssClass;\n}\n</code></pre>\n\n<p>The reason why I retain the CssClass property in a private variable between the method invocations is so prevent side effects from occurring during rendering. This may be unimportant in your particular code (\"is the CssClass property really that important -after- rendering?\") but it is always a good idea to prevent or reduce the impact of side effects such as what the code above exhibits by blanking out the property.</p>\n"
},
{
"answer_id": 206831,
"author": "deepcode.co.uk",
"author_id": 20524,
"author_profile": "https://Stackoverflow.com/users/20524",
"pm_score": 0,
"selected": false,
"text": "<p>Instead of invoking the base RenderBegin/RenderEnd methods, which themselves will invoke AddAttributesToRender (thereby adding the class attribute), just render the input tag yourself like you are doing with the span....</p>\n"
}
] |
2008/10/14
|
[
"https://Stackoverflow.com/questions/201518",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/27870/"
] |
Greetings!
I've created a custom button class to render the following:
```
<span class="btnOrange">
<input type="submit" id="ctl00_MainContent_m_GoBack" value="Back" name="ctl00$MainContent$m_GoBack"/>
</span>
```
However, it renders like this instead (note the extraneous "class" attribute in the INPUT tag):
```
<span class="btnOrange">
<input type="submit" class="btnOrange" id="ctl00_MainContent_m_GoBack" value="Back" name="ctl00$MainContent$m_GoBack"/>
</span>
```
My custom button class looks like this:
```
[ToolboxData(@"<{0}:MyButton runat=server></{0}:MyButton>")]
public class MyButton : Button
{
public override void RenderBeginTag(HtmlTextWriter writer)
{
writer.AddAttribute(HtmlTextWriterAttribute.Class, this.CssClass);
writer.RenderBeginTag("span");
base.RenderBeginTag(writer);
}
public override void RenderEndTag(HtmlTextWriter writer)
{
writer.RenderEndTag();
base.RenderEndTag(writer);
}
}
```
Since I only need to set the class attribute for the SPAN tag, is it possible to not include or "blank out" the class attribute for the INPUT tag?
|
You can do this:
```
private string _heldCssClass = null;
public override void RenderBeginTag(HtmlTextWriter writer)
{
writer.AddAttribute(HtmlTextWriterAttribute.Class, this.CssClass);
writer.RenderBeginTag("span");
_heldCssClass = this.CssClass;
this.CssClass = String.Empty;
base.RenderBeginTag(writer);
}
public override void RenderEndTag(HtmlTextWriter writer)
{
writer.RenderEndTag();
base.RenderEndTag(writer);
this.CssClass = _heldCssClass;
}
```
The reason why I retain the CssClass property in a private variable between the method invocations is so prevent side effects from occurring during rendering. This may be unimportant in your particular code ("is the CssClass property really that important -after- rendering?") but it is always a good idea to prevent or reduce the impact of side effects such as what the code above exhibits by blanking out the property.
|
201,527 |
<p>I need to create a database table to store different changelog/auditing
(when something was added, deleted, modified, etc). I don't need to store particularly detailed info, so I was thinking something along the lines of:</p>
<ul>
<li>id (for the event)</li>
<li>user that triggered it</li>
<li>event name</li>
<li>event description</li>
<li>timestamp of the event</li>
</ul>
<p>Am I missing something here? Obviously, I can keep improving the design, although I don't plan on making it complicated (creating other tables for event types or stuff like that is out of the question since it's a complication for my need).</p>
|
[
{
"answer_id": 201561,
"author": "JosephStyons",
"author_id": 672,
"author_profile": "https://Stackoverflow.com/users/672",
"pm_score": 2,
"selected": false,
"text": "<p>There are many ways to do this. My favorite way is:</p>\n\n<ol>\n<li><p>Add a <code>mod_user</code> field to your source table (the one you want to log).</p></li>\n<li><p>Create a log table that contains the fields you want to log, plus a <code>log_datetime</code> and <code>seq_num</code> field. <code>seq_num</code> is the primary key.</p></li>\n<li><p>Build a trigger on the source table that inserts the current record into the log table whenever any monitored field is changed.</p></li>\n</ol>\n\n<p>Now you've got a record of every change and who made it.</p>\n"
},
{
"answer_id": 202643,
"author": "HLGEM",
"author_id": 9034,
"author_profile": "https://Stackoverflow.com/users/9034",
"pm_score": 5,
"selected": false,
"text": "<p>We also log old and new values and the column they are from as well as the primary key of the table being audited in an audit detail table. Think what you need the audit table for? Not only do you want to know who made a change and when, but when a bad change happens, you want a fast way to put the data back.</p>\n\n<p>While you are designing, you should write the code to recover data. When you need to recover, it is usually in a hurry, best to already be prepared.</p>\n"
},
{
"answer_id": 211540,
"author": "WW.",
"author_id": 14663,
"author_profile": "https://Stackoverflow.com/users/14663",
"pm_score": 2,
"selected": false,
"text": "<p>What we have in our table:-</p>\n\n<pre><code>Primary Key\nEvent type (e.g. \"UPDATED\", \"APPROVED\")\nDescription (\"Frisbar was added to blong\")\nUser Id\nUser Id of second authoriser\nAmount\nDate/time\nGeneric Id\nTable Name\n</code></pre>\n\n<p>The generic id points at a row in the table that was updated and the table name is the name of that table as a string. Not a good DB design, but very usable. All our tables have a single surrogate key column so this works well.</p>\n"
},
{
"answer_id": 302311,
"author": "Yarik",
"author_id": 31415,
"author_profile": "https://Stackoverflow.com/users/31415",
"pm_score": 7,
"selected": true,
"text": "<p>In the project I'm working on, audit log also started from the very minimalistic design, like the one you described:</p>\n\n<pre><code>event ID\nevent date/time\nevent type\nuser ID\ndescription\n</code></pre>\n\n<p>The idea was the same: to keep things simple. </p>\n\n<p>However, it quickly became obvious that this minimalistic design was not sufficient. The typical audit was boiling down to questions like this: </p>\n\n<pre><code>Who the heck created/updated/deleted a record \nwith ID=X in the table Foo and when?\n</code></pre>\n\n<p>So, in order to be able to answer such questions quickly (using SQL), we ended up having two additional columns in the audit table</p>\n\n<pre><code>object type (or table name)\nobject ID\n</code></pre>\n\n<p>That's when design of our audit log really stabilized (for a few years now).</p>\n\n<p>Of course, the last \"improvement\" would work only for tables that had surrogate keys. But guess what? All our tables that are worth auditing do have such a key! </p>\n"
},
{
"answer_id": 14288969,
"author": "Robert4Real",
"author_id": 68532,
"author_profile": "https://Stackoverflow.com/users/68532",
"pm_score": 4,
"selected": false,
"text": "<p>There are a lot of interesting answers here and in similar questions. The only things that I can add from personal experience are:</p>\n\n<ol>\n<li><p>Put your audit table in another database. Ideally, you want separation from the original data. If you need to restore your database, you don't really want to restore the audit trail.</p></li>\n<li><p>Denormalize as much as reasonably possible. You want the table to have as few dependencies as possible to the original data. The audit table should be simple and lightning fast to retrieve data from. No fancy joins or lookups across other tables to get to the data.</p></li>\n</ol>\n"
},
{
"answer_id": 15944955,
"author": "Kenneth Hampton",
"author_id": 2054061,
"author_profile": "https://Stackoverflow.com/users/2054061",
"pm_score": 5,
"selected": false,
"text": "<p>There are several more things you might want to audit, such as table/column names, computer/application from which an update was made, and more.</p>\n\n<p>Now, this depends on how detailed auditing you really need and at what level. </p>\n\n<p>We started building our own trigger-based auditing solution, and we wanted to audit everything and also have a recovery option at hand. This turned out to be too complex, so we ended up reverse engineering the trigger-based, third-party tool <a href=\"http://www.apexsql.com/sql_tools_audit.aspx\" rel=\"noreferrer\">ApexSQL Audit</a> to create our own custom solution.</p>\n\n<p>Tips:</p>\n\n<ul>\n<li><p>Include before/after values</p></li>\n<li><p>Include 3-4 columns for storing the primary key (in case it’s a composite key)</p></li>\n<li><p>Store data outside the main database as already suggested by Robert</p></li>\n<li><p>Spend a decent amount of time on preparing reports – especially those you might need for recovery </p></li>\n<li><p>Plan for storing host/application name – this might come very useful for tracking suspicious activities </p></li>\n</ul>\n"
},
{
"answer_id": 37855620,
"author": "Bhagat007",
"author_id": 3378349,
"author_profile": "https://Stackoverflow.com/users/3378349",
"pm_score": 2,
"selected": false,
"text": "<p>According to the principle of separation:</p>\n\n<ol>\n<li><p>Auditing data tables need to be separate from the main database. Because audit databases can have a lot of historical data, it makes sense from a memory utilization standpoint to keep them separate.</p></li>\n<li><p>Do not use triggers to audit the whole database, because you will end up with a mess of different databases to support. You will have to write one for DB2, SQLServer, Mysql, etc.</p></li>\n</ol>\n"
},
{
"answer_id": 42332475,
"author": "Joel Mamedov",
"author_id": 7589828,
"author_profile": "https://Stackoverflow.com/users/7589828",
"pm_score": 3,
"selected": false,
"text": "<p>In general custom audit (creating various tables) is a bad option. Database/table triggers can be disabled to skip some log activities. Custom audit tables can be tampered. Exceptions can take place that will bring down application. Not to mentions difficulties designing a robust solution. So far I see a very simple cases in this discussion. You need a complete separation from current database and from any privileged users(DBA, Developers).\nEvery mainstream RDBMSs provide audit facilities that even DBA not able to disable, tamper in secrecy. Therefore, provided audit capability by RDBMS vendor must be the first option. Other option would be 3rd party transaction log reader or custom log reader that pushes decomposed information into messaging system that ends up in some forms of Audit Data Warehouse or real time event handler.\nIn summary: Solution Architect/\"Hands on Data Architect\" needs to involve in destining such a system based on requirements. It is usually too serious stuff just to hand over to a developers for solution.</p>\n"
}
] |
2008/10/14
|
[
"https://Stackoverflow.com/questions/201527",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9114/"
] |
I need to create a database table to store different changelog/auditing
(when something was added, deleted, modified, etc). I don't need to store particularly detailed info, so I was thinking something along the lines of:
* id (for the event)
* user that triggered it
* event name
* event description
* timestamp of the event
Am I missing something here? Obviously, I can keep improving the design, although I don't plan on making it complicated (creating other tables for event types or stuff like that is out of the question since it's a complication for my need).
|
In the project I'm working on, audit log also started from the very minimalistic design, like the one you described:
```
event ID
event date/time
event type
user ID
description
```
The idea was the same: to keep things simple.
However, it quickly became obvious that this minimalistic design was not sufficient. The typical audit was boiling down to questions like this:
```
Who the heck created/updated/deleted a record
with ID=X in the table Foo and when?
```
So, in order to be able to answer such questions quickly (using SQL), we ended up having two additional columns in the audit table
```
object type (or table name)
object ID
```
That's when design of our audit log really stabilized (for a few years now).
Of course, the last "improvement" would work only for tables that had surrogate keys. But guess what? All our tables that are worth auditing do have such a key!
|
201,530 |
<p>I need to add multiple empty divs to a container element using jQuery.</p>
<p>At the moment I am generating a string containing the empty html using a loop</p>
<pre><code>divstr = '<div></div><div></div>...<div></div>';
</code></pre>
<p>and then injecting that into my container:</p>
<pre><code>$('#container').html(divstr);
</code></pre>
<p>Is there a more elegant way to insert multiple, identical elements?</p>
<p>I'm hoping to find something that wouldn't break chaining but wouldn't bring the browser to its knees. A chainable <code>.repeat()</code> plugin?</p>
|
[
{
"answer_id": 201564,
"author": "Wayne",
"author_id": 8236,
"author_profile": "https://Stackoverflow.com/users/8236",
"pm_score": 1,
"selected": false,
"text": "<p>You can use a regular loop with the Jquery <a href=\"http://docs.jquery.com/Manipulation/append#content\" rel=\"nofollow noreferrer\">append</a> function.</p>\n\n<pre><code>for(i=0;i<10; i++){\n $('#container').append(\"<div></div>\");\n}\n</code></pre>\n"
},
{
"answer_id": 201661,
"author": "Remy Sharp",
"author_id": 22617,
"author_profile": "https://Stackoverflow.com/users/22617",
"pm_score": 5,
"selected": true,
"text": "<p>If you want IE to be fast - or generally consider speed, then you'll want to build up a DOM fragment first before inserting it.</p>\n\n<p>John Resig explains the technique and includes a performance benchmark:</p>\n\n<p><a href=\"http://ejohn.org/blog/dom-documentfragments/\" rel=\"noreferrer\">http://ejohn.org/blog/dom-documentfragments/</a></p>\n\n<pre><code>var i = 10, \n fragment = document.createDocumentFragment(), \n div = document.createElement('div');\n\nwhile (i--) {\n fragment.appendChild(div.cloneNode(true));\n}\n\n$('#container').append(fragment);\n</code></pre>\n\n<p>I realise it's not making a lot of use of jQuery in building up the fragment, but I've run a few tests and I can't seem to do $(fragment).append() - but I've read John's jQuery 1.3 release is supposed to include changes based on the research linked above.</p>\n"
},
{
"answer_id": 201991,
"author": "MonkeyBrother",
"author_id": 16296,
"author_profile": "https://Stackoverflow.com/users/16296",
"pm_score": 3,
"selected": false,
"text": "<p>The fastest way to do this is to build the content first with strings. It is MUCH faster to work with strings to build your document fragment before working with the DOM or jquery at all. Unfortunately, IE does a really poor job of concatenating strings, so the best way to do it is to use an array.</p>\n\n<pre><code>var cont = []; //Initialize an array to build the content\nfor (var i = 0;i<10;i++) cont.push('<div>bunch of text</div>');\n$('#container').html(cont.join(''));\n</code></pre>\n\n<p>I use this technique a ton in my code. You can build very large html fragments using this method and it is very efficient in all browsers.</p>\n"
},
{
"answer_id": 361563,
"author": "Vincent Robert",
"author_id": 268,
"author_profile": "https://Stackoverflow.com/users/268",
"pm_score": 3,
"selected": false,
"text": "<p>You can wrap a native JavaScript array in a jQuery and use map() to transform it into a jQuery (list of DOM nodes). This is officially supported.</p>\n\n<pre><code>$(['plop', 'onk', 'gloubi'])\n.map(function(i, text)\n{\n return $('<div/>').text(text).get(0);\n})\n.appendTo('#container');\n</code></pre>\n\n<p>This will create</p>\n\n<pre><code><div id=\"container\">\n<div>plop</div>\n<div>onk</div>\n<div>gloubi</div>\n</div>\n</code></pre>\n\n<p>I often use this technique in order to avoid repeating myself (DRY).</p>\n"
}
] |
2008/10/14
|
[
"https://Stackoverflow.com/questions/201530",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20074/"
] |
I need to add multiple empty divs to a container element using jQuery.
At the moment I am generating a string containing the empty html using a loop
```
divstr = '<div></div><div></div>...<div></div>';
```
and then injecting that into my container:
```
$('#container').html(divstr);
```
Is there a more elegant way to insert multiple, identical elements?
I'm hoping to find something that wouldn't break chaining but wouldn't bring the browser to its knees. A chainable `.repeat()` plugin?
|
If you want IE to be fast - or generally consider speed, then you'll want to build up a DOM fragment first before inserting it.
John Resig explains the technique and includes a performance benchmark:
<http://ejohn.org/blog/dom-documentfragments/>
```
var i = 10,
fragment = document.createDocumentFragment(),
div = document.createElement('div');
while (i--) {
fragment.appendChild(div.cloneNode(true));
}
$('#container').append(fragment);
```
I realise it's not making a lot of use of jQuery in building up the fragment, but I've run a few tests and I can't seem to do $(fragment).append() - but I've read John's jQuery 1.3 release is supposed to include changes based on the research linked above.
|
201,590 |
<p>I've inherited a .NET application that pulls together about 100 dlls built by two teams or purchased from vendors. I would like to quickly identify whether a given dll is a .NET assembly or a COM component. I realize that I could just invoke ildasm on each dll individually and make a note if the dll does not have a valid CLR header, but this approach seems clumsy and difficult to automate.</p>
|
[
{
"answer_id": 201603,
"author": "Bob King",
"author_id": 6897,
"author_profile": "https://Stackoverflow.com/users/6897",
"pm_score": 2,
"selected": false,
"text": "<p>You can always try to add the \"Assembly Version\" column to the Explorer Window, and note which ones are blank to find the non-.NET assemblies.</p>\n"
},
{
"answer_id": 201781,
"author": "Jimmy",
"author_id": 4435,
"author_profile": "https://Stackoverflow.com/users/4435",
"pm_score": 0,
"selected": false,
"text": "<pre><code>System.Reflection.Assembly.ReflectionOnlyLoadFrom(\"mydll.dll\")\n</code></pre>\n\n<p>will return a valid assembly reference to a .NET dll but will throw an error for a COM dll. </p>\n"
},
{
"answer_id": 202633,
"author": "Tim Farley",
"author_id": 4425,
"author_profile": "https://Stackoverflow.com/users/4425",
"pm_score": 3,
"selected": true,
"text": "<p>If you want to approach from the COM side, testing for COM objects in a DLL boils down to looking for an export named \"DllGetClassObject\". This is because an in-proc COM object is accessed by the COM runtime by calling <a href=\"http://msdn.microsoft.com/en-us/library/ms680760(VS.85).aspx\" rel=\"nofollow noreferrer\">DllGetClassObject()</a> on that DLL.</p>\n\n<p>You could do this from a batch file using <a href=\"http://msdn.microsoft.com/en-us/library/c1h23y6c(VS.71).aspx\" rel=\"nofollow noreferrer\">DUMPBIN.EXE</a> which comes with Visual Studio as follows:</p>\n\n<pre><code>dumpbin unknown.dll /exports | find \"DllGetClassObject\"\n</code></pre>\n\n<p>The above command line will produce one line of text if it is an unmanaged DLL that contains COM objects, or zero bytes of output otherwise. </p>\n\n<p>You could do this programmatically by loading each DLL and try to do a GetProcAddress() on that entry point. Here is a tested and working C# command line program that uses this technique:</p>\n\n<pre><code>using System;\nusing System.Collections.Generic;\nusing System.Linq;\nusing System.Text;\nusing System.Runtime.InteropServices;\n\nstatic class NativeStuff\n{\n [DllImport(\"kernel32.dll\")]\n public static extern IntPtr LoadLibrary(string dllToLoad);\n\n [DllImport(\"kernel32.dll\")]\n public static extern IntPtr GetProcAddress(IntPtr hModule, string procedureName);\n\n [DllImport(\"kernel32.dll\")]\n public static extern bool FreeLibrary(IntPtr hModule);\n}\n\nnamespace IsComDLL\n{\n class Program\n {\n static void Main(string[] args)\n {\n if ( (args.Length == 0 ) || String.IsNullOrEmpty( args[0] ) )\n {\n Console.WriteLine( \"Give DLL name on command line\" );\n Environment.Exit(255);\n }\n\n IntPtr pDll = NativeStuff.LoadLibrary(args[0]);\n if ( pDll == IntPtr.Zero )\n {\n Console.WriteLine( \"DLL file {0} not found\", args[0] );\n Environment.Exit(256);\n }\n\n IntPtr pFunction = NativeStuff.GetProcAddress(pDll, \"DllGetClassObject\");\n int exitValue = 0;\n if (pFunction == IntPtr.Zero)\n {\n Console.WriteLine(\"DLL file {0} does NOT contain COM objects\", args[0]);\n }\n else\n {\n Console.WriteLine(\"DLL file {0} does contain COM objects\", args[0]);\n exitValue = 1;\n }\n\n NativeStuff.FreeLibrary(pDll);\n\n Environment.Exit(exitValue);\n }\n }\n}\n</code></pre>\n"
}
] |
2008/10/14
|
[
"https://Stackoverflow.com/questions/201590",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5985/"
] |
I've inherited a .NET application that pulls together about 100 dlls built by two teams or purchased from vendors. I would like to quickly identify whether a given dll is a .NET assembly or a COM component. I realize that I could just invoke ildasm on each dll individually and make a note if the dll does not have a valid CLR header, but this approach seems clumsy and difficult to automate.
|
If you want to approach from the COM side, testing for COM objects in a DLL boils down to looking for an export named "DllGetClassObject". This is because an in-proc COM object is accessed by the COM runtime by calling [DllGetClassObject()](http://msdn.microsoft.com/en-us/library/ms680760(VS.85).aspx) on that DLL.
You could do this from a batch file using [DUMPBIN.EXE](http://msdn.microsoft.com/en-us/library/c1h23y6c(VS.71).aspx) which comes with Visual Studio as follows:
```
dumpbin unknown.dll /exports | find "DllGetClassObject"
```
The above command line will produce one line of text if it is an unmanaged DLL that contains COM objects, or zero bytes of output otherwise.
You could do this programmatically by loading each DLL and try to do a GetProcAddress() on that entry point. Here is a tested and working C# command line program that uses this technique:
```
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Runtime.InteropServices;
static class NativeStuff
{
[DllImport("kernel32.dll")]
public static extern IntPtr LoadLibrary(string dllToLoad);
[DllImport("kernel32.dll")]
public static extern IntPtr GetProcAddress(IntPtr hModule, string procedureName);
[DllImport("kernel32.dll")]
public static extern bool FreeLibrary(IntPtr hModule);
}
namespace IsComDLL
{
class Program
{
static void Main(string[] args)
{
if ( (args.Length == 0 ) || String.IsNullOrEmpty( args[0] ) )
{
Console.WriteLine( "Give DLL name on command line" );
Environment.Exit(255);
}
IntPtr pDll = NativeStuff.LoadLibrary(args[0]);
if ( pDll == IntPtr.Zero )
{
Console.WriteLine( "DLL file {0} not found", args[0] );
Environment.Exit(256);
}
IntPtr pFunction = NativeStuff.GetProcAddress(pDll, "DllGetClassObject");
int exitValue = 0;
if (pFunction == IntPtr.Zero)
{
Console.WriteLine("DLL file {0} does NOT contain COM objects", args[0]);
}
else
{
Console.WriteLine("DLL file {0} does contain COM objects", args[0]);
exitValue = 1;
}
NativeStuff.FreeLibrary(pDll);
Environment.Exit(exitValue);
}
}
}
```
|
201,593 |
<p>Suppose we have some named enums:</p>
<pre><code>enum MyEnum {
FOO,
BAR = 0x50
};
</code></pre>
<p>What I googled for is a script (any language) that scans all the headers in my project and generates a header with one function per enum.</p>
<pre><code>char* enum_to_string(MyEnum t);
</code></pre>
<p>And a implementation with something like this:</p>
<pre><code>char* enum_to_string(MyEnum t){
switch(t){
case FOO:
return "FOO";
case BAR:
return "BAR";
default:
return "INVALID ENUM";
}
}
</code></pre>
<p>The gotcha is really with typedefed enums, and unnamed C style enums. Does anybody know something for this?</p>
<p>EDIT: The solution should not modify my source, except for the generated functions. The enums are in an API, so using the solutions proposed until now is just not an option.</p>
|
[
{
"answer_id": 201610,
"author": "James Curran",
"author_id": 12725,
"author_profile": "https://Stackoverflow.com/users/12725",
"pm_score": 0,
"selected": false,
"text": "<p>That's pretty much the only way it can be done (an array of string could work also).</p>\n\n<p>The problem is, once a C program is compiled, the binary value of the enum is all that is used, and the name is gone.</p>\n"
},
{
"answer_id": 201665,
"author": "gbjbaanb",
"author_id": 13744,
"author_profile": "https://Stackoverflow.com/users/13744",
"pm_score": 5,
"selected": false,
"text": "<p>What I tend to do is create a C array with the names in the same order and position as the enum values.</p>\n\n<p>eg.</p>\n\n<pre><code>enum colours { red, green, blue };\nconst char *colour_names[] = { \"red\", \"green\", \"blue\" };\n</code></pre>\n\n<p>then you can use the array in places where you want a human-readable value, eg</p>\n\n<pre><code>colours mycolour = red;\ncout << \"the colour is\" << colour_names[mycolour];\n</code></pre>\n\n<p>You could experiment a little with the stringizing operator (see # in your preprocessor reference) that will do what you want, in some circumstances- eg:</p>\n\n<pre><code>#define printword(XX) cout << #XX;\nprintword(red);\n</code></pre>\n\n<p>will print \"red\" to stdout. Unfortunately it won't work for a variable (as you'll get the variable name printed out)</p>\n"
},
{
"answer_id": 201742,
"author": "mpez0",
"author_id": 27898,
"author_profile": "https://Stackoverflow.com/users/27898",
"pm_score": 1,
"selected": false,
"text": "<p>A problem with answer 0 is that the enum binary values do not necessarily start at 0 and are not necessarily contiguous.</p>\n\n<p>When I need this, I usually:</p>\n\n<ul>\n<li>pull the enum definition into my source</li>\n<li>edit it to get just the names</li>\n<li>do a macro to change the name to the case clause in the question, though typically on one line: case foo: return \"foo\";</li>\n<li>add the switch, default and other syntax to make it legal</li>\n</ul>\n"
},
{
"answer_id": 201770,
"author": "Marcin Koziuk",
"author_id": 27909,
"author_profile": "https://Stackoverflow.com/users/27909",
"pm_score": 6,
"selected": false,
"text": "<p>X-macros are the best solution. Example:</p>\n\n<pre><code>#include <iostream>\n\nenum Colours {\n# define X(a) a,\n# include \"colours.def\"\n# undef X\n ColoursCount\n};\n\nchar const* const colours_str[] = {\n# define X(a) #a,\n# include \"colours.def\"\n# undef X\n 0\n};\n\nstd::ostream& operator<<(std::ostream& os, enum Colours c)\n{\n if (c >= ColoursCount || c < 0) return os << \"???\";\n return os << colours_str[c];\n}\n\nint main()\n{\n std::cout << Red << Blue << Green << Cyan << Yellow << Magenta << std::endl;\n}\n</code></pre>\n\n<p>colours.def:</p>\n\n<pre><code>X(Red)\nX(Green)\nX(Blue)\nX(Cyan)\nX(Yellow)\nX(Magenta)\n</code></pre>\n\n<p>However, I usually prefer the following method, so that it's possible to tweak the string a bit.</p>\n\n<pre><code>#define X(a, b) a,\n#define X(a, b) b,\n\nX(Red, \"red\")\nX(Green, \"green\")\n// etc.\n</code></pre>\n"
},
{
"answer_id": 201792,
"author": "MSalters",
"author_id": 15416,
"author_profile": "https://Stackoverflow.com/users/15416",
"pm_score": 2,
"selected": false,
"text": "<p><a href=\"https://stackoverflow.com/questions/147267/easy-way-to-use-variables-of-enum-types-as-string-in-c#202511\">Suma's macro solution</a> is nice. You don't need to have two different macro's, though. C++ wil happily include a header twice. Just leave out the include guard.</p>\n\n<p>So you'd have an foobar.h defining just</p>\n\n<pre><code>ENUM(Foo, 1)\nENUM(Bar, 2)\n</code></pre>\n\n<p>and you would include it like this:</p>\n\n<pre><code>#define ENUMFACTORY_ARGUMENT \"foobar.h\"\n#include \"enumfactory.h\"\n</code></pre>\n\n<p>enumfactory.h will do 2 <code>#include ENUMFACTORY_ARGUMENT</code>s. In the first round, it expands ENUM like Suma's <code>DECLARE_ENUM</code>; in the second round ENUM works like <code>DEFINE_ENUM</code>.</p>\n\n<p>You can include enumfactory.h multiple times, too, as long as you pass in different #define's for ENUMFACTORY_ARGUMENT</p>\n"
},
{
"answer_id": 201795,
"author": "Avdi",
"author_id": 20487,
"author_profile": "https://Stackoverflow.com/users/20487",
"pm_score": 7,
"selected": true,
"text": "<p>You may want to check out <a href=\"http://www.gccxml.org/HTML/Index.html\" rel=\"noreferrer\">GCCXML</a>.</p>\n\n<p>Running GCCXML on your sample code produces:</p>\n\n<pre><code><GCC_XML>\n <Namespace id=\"_1\" name=\"::\" members=\"_3 \" mangled=\"_Z2::\"/>\n <Namespace id=\"_2\" name=\"std\" context=\"_1\" members=\"\" mangled=\"_Z3std\"/>\n <Enumeration id=\"_3\" name=\"MyEnum\" context=\"_1\" location=\"f0:1\" file=\"f0\" line=\"1\">\n <EnumValue name=\"FOO\" init=\"0\"/>\n <EnumValue name=\"BAR\" init=\"80\"/>\n </Enumeration>\n <File id=\"f0\" name=\"my_enum.h\"/>\n</GCC_XML>\n</code></pre>\n\n<p>You could use any language you prefer to pull out the Enumeration and EnumValue tags and generate your desired code.</p>\n"
},
{
"answer_id": 201806,
"author": "Ates Goral",
"author_id": 23501,
"author_profile": "https://Stackoverflow.com/users/23501",
"pm_score": 2,
"selected": false,
"text": "<p>Note that your conversion function should ideally be returning a <strong>const</strong> char *.</p>\n\n<p>If you can afford to put your enums in their separate header files, you could perhaps do something like this with macros (oh, this will be ugly):</p>\n\n<pre><code>#include \"enum_def.h\"\n#include \"colour.h\"\n#include \"enum_conv.h\"\n#include \"colour.h\"\n</code></pre>\n\n<p>Where enum_def.h has:</p>\n\n<pre><code>#undef ENUM_START\n#undef ENUM_ADD\n#undef ENUM_END\n#define ENUM_START(NAME) enum NAME {\n#define ENUM_ADD(NAME, VALUE) NAME = VALUE,\n#define ENUM_END };\n</code></pre>\n\n<p>And enum_conv.h has:</p>\n\n<pre><code>#undef ENUM_START\n#undef ENUM_ADD\n#undef ENUM_END\n#define ENUM_START(NAME) const char *##NAME##_to_string(NAME val) { switch (val) {\n#define ENUM_ADD(NAME, VALUE) case NAME: return #NAME;\n#define ENUM_END default: return \"Invalid value\"; } }\n</code></pre>\n\n<p>And finally, colour.h has:</p>\n\n<pre><code>ENUM_START(colour)\nENUM_ADD(red, 0xff0000)\nENUM_ADD(green, 0x00ff00)\nENUM_ADD(blue, 0x0000ff)\nENUM_END\n</code></pre>\n\n<p>And you can use the conversion function as:</p>\n\n<pre><code>printf(\"%s\", colour_to_string(colour::red));\n</code></pre>\n\n<p>This is ugly, but it's the only way (at the preprocessor level) that lets you define your enum just in a single place in your code. Your code is therefore not prone to errors due to modifications to the enum. Your enum definition and the conversion function will always be in sync. However, I repeat, this is ugly :)</p>\n"
},
{
"answer_id": 202024,
"author": "bltxd",
"author_id": 11892,
"author_profile": "https://Stackoverflow.com/users/11892",
"pm_score": 1,
"selected": false,
"text": "<p>The following ruby script attempts to parse the headers and builts the required sources alongside the original headers.</p>\n\n<pre><code>#! /usr/bin/env ruby\n\n# Let's \"parse\" the headers\n# Note that using a regular expression is rather fragile\n# and may break on some inputs\n\nGLOBS = [\n \"toto/*.h\",\n \"tutu/*.h\",\n \"tutu/*.hxx\"\n]\n\nenums = {}\nGLOBS.each { |glob|\n Dir[glob].each { |header|\n enums[header] = File.open(header, 'rb') { |f|\n f.read\n }.scan(/enum\\s+(\\w+)\\s+\\{\\s*([^}]+?)\\s*\\}/m).collect { |enum_name, enum_key_and_values|\n [\n enum_name, enum_key_and_values.split(/\\s*,\\s*/).collect { |enum_key_and_value|\n enum_key_and_value.split(/\\s*=\\s*/).first\n }\n ]\n }\n }\n}\n\n\n# Now we build a .h and .cpp alongside the parsed headers\n# using the template engine provided with ruby\nrequire 'erb'\n\ntemplate_h = ERB.new <<-EOS\n#ifndef <%= enum_name %>_to_string_h_\n#define <%= enum_name %>_to_string_h_ 1\n\n#include \"<%= header %>\"\nchar* enum_to_string(<%= enum_name %> e);\n\n#endif\nEOS\n\ntemplate_cpp = ERB.new <<-EOS\n#include \"<%= enum_name %>_to_string.h\"\n\nchar* enum_to_string(<%= enum_name %> e)\n{\n switch (e)\n {<% enum_keys.each do |enum_key| %>\n case <%= enum_key %>: return \"<%= enum_key %>\";<% end %>\n default: return \"INVALID <%= enum_name %> VALUE\";\n }\n}\nEOS\n\nenums.each { |header, enum_name_and_keys|\n enum_name_and_keys.each { |enum_name, enum_keys|\n File.open(\"#{File.dirname(header)}/#{enum_name}_to_string.h\", 'wb') { |built_h|\n built_h.write(template_h.result(binding))\n }\n\n File.open(\"#{File.dirname(header)}/#{enum_name}_to_string.cpp\", 'wb') { |built_cpp|\n built_cpp.write(template_cpp.result(binding))\n }\n }\n}\n</code></pre>\n\n<p>Using regular expressions makes this \"parser\" quite fragile, it may not be able to handle your specific headers gracefully.</p>\n\n<p>Let's say you have a header toto/a.h, containing definitions for enums MyEnum and MyEnum2. The script will build:</p>\n\n<pre><code>toto/MyEnum_to_string.h\ntoto/MyEnum_to_string.cpp\ntoto/MyEnum2_to_string.h\ntoto/MyEnum2_to_string.cpp\n</code></pre>\n\n<p>More robust solutions would be:</p>\n\n<ul>\n<li>Build all sources defining enums and their operations from another source. This means you'll define your enums in a XML/YML/whatever file which is much easier to parse than C/C++.</li>\n<li>Use a real compiler such as suggested by Avdi.</li>\n<li>Use preprocessor macros with or without templates.</li>\n</ul>\n"
},
{
"answer_id": 202126,
"author": "Avdi",
"author_id": 20487,
"author_profile": "https://Stackoverflow.com/users/20487",
"pm_score": 2,
"selected": false,
"text": "<p>Another answer: in some contexts, it makes sense to define your enumeration in a non-code format, like a CSV, YAML, or XML file, and then generate both the C++ enumeration code and the to-string code from the definition. This approach may or may not be practical in your application, but it's something to keep in mind.</p>\n"
},
{
"answer_id": 202175,
"author": "Ronny Brendel",
"author_id": 14114,
"author_profile": "https://Stackoverflow.com/users/14114",
"pm_score": 3,
"selected": false,
"text": "<p>QT is able to pull that of (thanks to the meta object compiler):</p>\n<pre><code>QNetworkReply::NetworkError error;\n\nerror = fetchStuff();\n\nif (error != QNetworkReply::NoError) {\n\n QString errorValue;\n\n QMetaObject meta = QNetworkReply::staticMetaObject;\n\n for (int i=0; i < meta.enumeratorCount(); ++i) {\n\n QMetaEnum m = meta.enumerator(i);\n\n if (m.name() == QLatin1String("NetworkError")) {\n\n errorValue = QLatin1String(m.valueToKey(error));\n\n break;\n\n }\n\n }\n\n QMessageBox box(QMessageBox::Information, "Failed to fetch",\n\n "Fetching stuff failed with error '%1`").arg(errorValue),\n\n QMessageBox::Ok);\n\n box.exec();\n\n return 1;\n\n}\n</code></pre>\n<blockquote>\n<p>In Qt every class that has the Q_OBJECT macro will automatically have a static member "staticMetaObject" of the type QMetaObject. You can then find all sorts of cool things like the properties, signals, slots and indeed enums.</p>\n</blockquote>\n<p><a href=\"https://www.qt.io/blog/2008/10/09/coding-tip-pretty-printing-enum-values\" rel=\"nofollow noreferrer\">Source</a></p>\n"
},
{
"answer_id": 202529,
"author": "Nick",
"author_id": 26240,
"author_profile": "https://Stackoverflow.com/users/26240",
"pm_score": 2,
"selected": false,
"text": "<p>I do this with separate side-by-side enum wrapper classes which are generated with macros. There are several advantages:</p>\n\n<ul>\n<li>Can generate them for enums I don't define (eg: OS platform header enums)</li>\n<li>Can incorporate range checking into the wrapper class</li>\n<li>Can do \"smarter\" formatting with bit field enums</li>\n</ul>\n\n<p>The downside, of course, is that I need to duplicate the enum values in the formatter classes, and I don't have any script to generate them. Other than that, though, it seems to work pretty well.</p>\n\n<p>Here's an example of an enum from my codebase, sans all the framework code which implements the macros and templates, but you can get the idea:</p>\n\n<pre><code>enum EHelpLocation\n{\n HELP_LOCATION_UNKNOWN = 0, \n HELP_LOCAL_FILE = 1, \n HELP_HTML_ONLINE = 2, \n};\nclass CEnumFormatter_EHelpLocation : public CEnumDefaultFormatter< EHelpLocation >\n{\npublic:\n static inline CString FormatEnum( EHelpLocation eValue )\n {\n switch ( eValue )\n {\n ON_CASE_VALUE_RETURN_STRING_OF_VALUE( HELP_LOCATION_UNKNOWN );\n ON_CASE_VALUE_RETURN_STRING_OF_VALUE( HELP_LOCAL_FILE );\n ON_CASE_VALUE_RETURN_STRING_OF_VALUE( HELP_HTML_ONLINE );\n default:\n return FormatAsNumber( eValue );\n }\n }\n};\nDECLARE_RANGE_CHECK_CLASS( EHelpLocation, CRangeInfoSequential< HELP_HTML_ONLINE > );\ntypedef ESmartEnum< EHelpLocation, HELP_LOCATION_UNKNOWN, CEnumFormatter_EHelpLocation, CRangeInfo_EHelpLocation > SEHelpLocation;\n</code></pre>\n\n<p>The idea then is instead of using EHelpLocation, you use SEHelpLocation; everything works the same, but you get range checking and a 'Format()' method on the enum variable itself. If you need to format a stand-alone value, you can use CEnumFormatter_EHelpLocation::FormatEnum(...).</p>\n\n<p>Hope this is helpful. I realize this also doesn't address the original question about a script to actually generate the other class, but I hope the structure helps someone trying to solve the same problem, or write such a script.</p>\n"
},
{
"answer_id": 238157,
"author": "Jasper Bekkers",
"author_id": 31486,
"author_profile": "https://Stackoverflow.com/users/31486",
"pm_score": 6,
"selected": false,
"text": "<p>@hydroo: Without the extra file:</p>\n\n<pre><code>#define SOME_ENUM(DO) \\\n DO(Foo) \\\n DO(Bar) \\\n DO(Baz)\n\n#define MAKE_ENUM(VAR) VAR,\nenum MetaSyntacticVariable{\n SOME_ENUM(MAKE_ENUM)\n};\n\n#define MAKE_STRINGS(VAR) #VAR,\nconst char* const MetaSyntacticVariableNames[] = {\n SOME_ENUM(MAKE_STRINGS)\n};\n</code></pre>\n"
},
{
"answer_id": 1030248,
"author": "Carl",
"author_id": 13760,
"author_profile": "https://Stackoverflow.com/users/13760",
"pm_score": 3,
"selected": false,
"text": "<p>Interesting to see the number of ways. here's one i used a long time ago: </p>\n\n<p>in file myenummap.h:</p>\n\n<pre><code>#include <map>\n#include <string>\nenum test{ one, two, three, five=5, six, seven };\nstruct mymap : std::map<unsigned int, std::string>\n{\n mymap()\n {\n this->operator[]( one ) = \"ONE\";\n this->operator[]( two ) = \"TWO\";\n this->operator[]( three ) = \"THREE\";\n this->operator[]( five ) = \"FIVE\";\n this->operator[]( six ) = \"SIX\";\n this->operator[]( seven ) = \"SEVEN\";\n };\n ~mymap(){};\n};\n</code></pre>\n\n<p>in main.cpp</p>\n\n<pre><code>#include \"myenummap.h\"\n\n...\nmymap nummap;\nstd::cout<< nummap[ one ] << std::endl;\n</code></pre>\n\n<p>Its not const, but its convenient.</p>\n\n<p>Here's another way that uses C++11 features. This is const, doesn't inherit an STL container and is a little tidier:</p>\n\n<pre><code>#include <vector>\n#include <string>\n#include <algorithm>\n#include <iostream>\n\n//These stay together and must be modified together\nenum test{ one, two, three, five=5, six, seven };\nstd::string enum_to_str(test const& e)\n{\n typedef std::pair<int,std::string> mapping;\n auto m = [](test const& e,std::string const& s){return mapping(static_cast<int>(e),s);}; \n std::vector<mapping> const nummap = \n { \n m(one,\"one\"), \n m(two,\"two\"), \n m(three,\"three\"),\n m(five,\"five\"),\n m(six,\"six\"),\n m(seven,\"seven\"),\n };\n for(auto i : nummap)\n {\n if(i.first==static_cast<int>(e))\n {\n return i.second;\n }\n }\n return \"\";\n}\n\nint main()\n{\n// std::cout<< enum_to_str( 46 ) << std::endl; //compilation will fail\n std::cout<< \"Invalid enum to string : [\" << enum_to_str( test(46) ) << \"]\"<<std::endl; //returns an empty string\n std::cout<< \"Enumval five to string : [\"<< enum_to_str( five ) << \"] \"<< std::endl; //works\n return 0;\n}\n</code></pre>\n"
},
{
"answer_id": 1674938,
"author": "Alexis",
"author_id": 173987,
"author_profile": "https://Stackoverflow.com/users/173987",
"pm_score": 2,
"selected": false,
"text": "<p>It's unreleased software but it seems BOOST_ENUM from Frank Laub could fit the bill. The part I like about it is that you can define an enum within the scope of a class which most of the Macro based enums usually don't let you do. It is located in the Boost Vault at: <a href=\"http://www.boostpro.com/vault/index.php?action=downloadfile&filename=enum_rev4.6.zip&directory=&\" rel=\"nofollow noreferrer\">http://www.boostpro.com/vault/index.php?action=downloadfile&filename=enum_rev4.6.zip&directory=&</a>\nIt hasn't seen any development since 2006 so I don't know how well it compiles with the new Boost releases.\nLook under libs/test for an example of usage.</p>\n"
},
{
"answer_id": 2993686,
"author": "Programmer_P",
"author_id": 360877,
"author_profile": "https://Stackoverflow.com/users/360877",
"pm_score": 0,
"selected": false,
"text": "<p>Here is a CLI program I wrote to easily convert enums to strings.\nIts easy to use, and takes about 5 seconds to get it done (including the time to cd to the directory containing the program, then run it, passing to it the file containing the enum).</p>\n\n<p>Download here:\n<a href=\"http://www.mediafire.com/?nttignoozzz\" rel=\"nofollow noreferrer\">http://www.mediafire.com/?nttignoozzz</a></p>\n\n<p>Discussion topic on it here:\n<a href=\"http://cboard.cprogramming.com/projects-job-recruitment/127488-free-program-im-sharing-convertenumtostrings.html\" rel=\"nofollow noreferrer\">http://cboard.cprogramming.com/projects-job-recruitment/127488-free-program-im-sharing-convertenumtostrings.html</a></p>\n\n<p>Run the program with the \"--help\" argument to get a description how to use it.</p>\n"
},
{
"answer_id": 11586083,
"author": "Mark Ransom",
"author_id": 5987,
"author_profile": "https://Stackoverflow.com/users/5987",
"pm_score": 3,
"selected": false,
"text": "<p>I just re-invented this wheel today, and thought I'd share it.</p>\n\n<p>This implementation does <em>not</em> require any changes to the code that defines the constants, which can be enumerations or <code>#define</code>s or anything else that devolves to an integer - in my case I had symbols defined in terms of other symbols. It also works well with sparse values. It even allows multiple names for the same value, returning the first one always. The only downside is that it requires you to make a table of the constants, which might become out-of-date as new ones are added for example.</p>\n\n<pre><code>struct IdAndName\n{\n int id;\n const char * name;\n bool operator<(const IdAndName &rhs) const { return id < rhs.id; }\n};\n#define ID_AND_NAME(x) { x, #x }\n\nconst char * IdToName(int id, IdAndName *table_begin, IdAndName *table_end)\n{\n if ((table_end - table_begin) > 1 && table_begin[0].id > table_begin[1].id)\n std::stable_sort(table_begin, table_end);\n\n IdAndName searchee = { id, NULL };\n IdAndName *p = std::lower_bound(table_begin, table_end, searchee);\n return (p == table_end || p->id != id) ? NULL : p->name;\n}\n\ntemplate<int N>\nconst char * IdToName(int id, IdAndName (&table)[N])\n{\n return IdToName(id, &table[0], &table[N]);\n}\n</code></pre>\n\n<p>An example of how you'd use it:</p>\n\n<pre><code>static IdAndName WindowsErrorTable[] =\n{\n ID_AND_NAME(INT_MAX), // flag value to indicate unsorted table\n ID_AND_NAME(NO_ERROR),\n ID_AND_NAME(ERROR_INVALID_FUNCTION),\n ID_AND_NAME(ERROR_FILE_NOT_FOUND),\n ID_AND_NAME(ERROR_PATH_NOT_FOUND),\n ID_AND_NAME(ERROR_TOO_MANY_OPEN_FILES),\n ID_AND_NAME(ERROR_ACCESS_DENIED),\n ID_AND_NAME(ERROR_INVALID_HANDLE),\n ID_AND_NAME(ERROR_ARENA_TRASHED),\n ID_AND_NAME(ERROR_NOT_ENOUGH_MEMORY),\n ID_AND_NAME(ERROR_INVALID_BLOCK),\n ID_AND_NAME(ERROR_BAD_ENVIRONMENT),\n ID_AND_NAME(ERROR_BAD_FORMAT),\n ID_AND_NAME(ERROR_INVALID_ACCESS),\n ID_AND_NAME(ERROR_INVALID_DATA),\n ID_AND_NAME(ERROR_INVALID_DRIVE),\n ID_AND_NAME(ERROR_CURRENT_DIRECTORY),\n ID_AND_NAME(ERROR_NOT_SAME_DEVICE),\n ID_AND_NAME(ERROR_NO_MORE_FILES)\n};\n\nconst char * error_name = IdToName(GetLastError(), WindowsErrorTable);\n</code></pre>\n\n<p>The <code>IdToName</code> function relies on <code>std::lower_bound</code> to do quick lookups, which requires the table to be sorted. If the first two entries in the table are out of order, the function will sort it automatically.</p>\n\n<p>Edit: A comment made me think of another way of using the same principle. A macro simplifies the generation of a big <code>switch</code> statement.</p>\n\n<pre><code>#define ID_AND_NAME(x) case x: return #x\n\nconst char * WindowsErrorToName(int id)\n{\n switch(id)\n {\n ID_AND_NAME(ERROR_INVALID_FUNCTION);\n ID_AND_NAME(ERROR_FILE_NOT_FOUND);\n ID_AND_NAME(ERROR_PATH_NOT_FOUND);\n ID_AND_NAME(ERROR_TOO_MANY_OPEN_FILES);\n ID_AND_NAME(ERROR_ACCESS_DENIED);\n ID_AND_NAME(ERROR_INVALID_HANDLE);\n ID_AND_NAME(ERROR_ARENA_TRASHED);\n ID_AND_NAME(ERROR_NOT_ENOUGH_MEMORY);\n ID_AND_NAME(ERROR_INVALID_BLOCK);\n ID_AND_NAME(ERROR_BAD_ENVIRONMENT);\n ID_AND_NAME(ERROR_BAD_FORMAT);\n ID_AND_NAME(ERROR_INVALID_ACCESS);\n ID_AND_NAME(ERROR_INVALID_DATA);\n ID_AND_NAME(ERROR_INVALID_DRIVE);\n ID_AND_NAME(ERROR_CURRENT_DIRECTORY);\n ID_AND_NAME(ERROR_NOT_SAME_DEVICE);\n ID_AND_NAME(ERROR_NO_MORE_FILES);\n default: return NULL;\n }\n}\n</code></pre>\n"
},
{
"answer_id": 13188585,
"author": "Ben",
"author_id": 385273,
"author_profile": "https://Stackoverflow.com/users/385273",
"pm_score": 3,
"selected": false,
"text": "<pre><code>#define stringify( name ) # name\n\nenum MyEnum {\n ENUMVAL1\n};\n...stuff...\n\nstringify(EnumName::ENUMVAL1); // Returns MyEnum::ENUMVAL1\n</code></pre>\n\n<p><a href=\"http://www.cplusplus.com/forum/general/2949/\" rel=\"noreferrer\">Further discussion on this method</a> </p>\n\n<p><a href=\"http://www.cprogramming.com/tutorial/cpreprocessor.html\" rel=\"noreferrer\">Preprocessor directive tricks for newcomers</a></p>\n"
},
{
"answer_id": 15270402,
"author": "kassak",
"author_id": 1904007,
"author_profile": "https://Stackoverflow.com/users/1904007",
"pm_score": 0,
"selected": false,
"text": "<p>Not so long ago I made some trick to have enums properly displayed in QComboBox and to have definition of enum and string representations as one statement</p>\n\n<pre><code>#pragma once\n#include <boost/unordered_map.hpp>\n\nnamespace enumeration\n{\n\n struct enumerator_base : boost::noncopyable\n {\n typedef\n boost::unordered_map<int, std::wstring>\n kv_storage_t;\n typedef\n kv_storage_t::value_type\n kv_type;\n kv_storage_t const & kv() const\n {\n return storage_;\n }\n\n LPCWSTR name(int i) const\n {\n kv_storage_t::const_iterator it = storage_.find(i);\n if(it != storage_.end())\n return it->second.c_str();\n return L\"empty\";\n }\n\n protected:\n kv_storage_t storage_;\n };\n\n template<class T>\n struct enumerator;\n\n template<class D>\n struct enum_singleton : enumerator_base\n {\n static enumerator_base const & instance()\n {\n static D inst;\n return inst;\n }\n };\n}\n\n#define QENUM_ENTRY(K, V, N) K, N storage_.insert(std::make_pair((int)K, V));\n\n#define QBEGIN_ENUM(NAME, C) \\\nenum NAME \\\n{ \\\n C \\\n} \\\n}; \\\n} \\\n\n#define QEND_ENUM(NAME) \\\n}; \\\nnamespace enumeration \\\n{ \\\ntemplate<> \\\nstruct enumerator<NAME>\\\n : enum_singleton< enumerator<NAME> >\\\n{ \\\n enumerator() \\\n {\n\n//usage\n/*\nQBEGIN_ENUM(test_t,\n QENUM_ENTRY(test_entry_1, L\"number uno\",\n QENUM_ENTRY(test_entry_2, L\"number dos\",\n QENUM_ENTRY(test_entry_3, L\"number tres\",\nQEND_ENUM(test_t)))))\n*/\n</code></pre>\n\n<p>Now you've got <code>enumeration::enum_singleton<your_enum>::instance()</code> able to convert enums to strings. If you replace <code>kv_storage_t</code> with <code>boost::bimap</code>, you will also be able to do backward conversion.\nCommon base class for converter was introduced to store it in Qt object, because Qt objects couldn't be templates</p>\n\n<p><a href=\"https://stackoverflow.com/a/15266261/1904007\">Previous appearance</a></p>\n"
},
{
"answer_id": 16013017,
"author": "Andrii Syrokomskyi",
"author_id": 963948,
"author_profile": "https://Stackoverflow.com/users/963948",
"pm_score": 0,
"selected": false,
"text": "<p>As variant, use simple lib > <a href=\"http://codeproject.com/Articles/42035/Enum-to-String-and-Vice-Versa-in-C\" rel=\"nofollow\">http://codeproject.com/Articles/42035/Enum-to-String-and-Vice-Versa-in-C</a></p>\n\n<p>In the code</p>\n\n<pre><code>#include <EnumString.h>\n\nenum FORM {\n F_NONE = 0,\n F_BOX,\n F_CUBE,\n F_SPHERE,\n};\n</code></pre>\n\n<p>add lines</p>\n\n<pre><code>Begin_Enum_String( FORM )\n{\n Enum_String( F_NONE );\n Enum_String( F_BOX );\n Enum_String( F_CUBE );\n Enum_String( F_SPHERE );\n}\nEnd_Enum_String;\n</code></pre>\n\n<p>Work fine, <strong>if values in enum are not dublicate</strong>.</p>\n\n<p>Example usage</p>\n\n<pre><code>enum FORM f = ...\nconst std::string& str = EnumString< FORM >::From( f );\n</code></pre>\n\n<p>and vice versa</p>\n\n<pre><code>assert( EnumString< FORM >::To( f, str ) );\n</code></pre>\n"
},
{
"answer_id": 22067277,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 2,
"selected": false,
"text": "<pre><code>#include <stdarg.h>\n#include <algorithm>\n#include <string> \n#include <vector>\n#include <sstream>\n#include <map>\n\n#define SMART_ENUM(EnumName, ...) \\\nclass EnumName \\\n{ \\\nprivate: \\\n static std::map<int, std::string> nameMap; \\\npublic: \\\n enum {__VA_ARGS__}; \\\nprivate: \\\n static std::map<int, std::string> initMap() \\\n { \\\n using namespace std; \\\n \\\n int val = 0; \\\n string buf_1, buf_2, str = #__VA_ARGS__; \\\n replace(str.begin(), str.end(), '=', ' '); \\\n stringstream stream(str); \\\n vector<string> strings; \\\n while (getline(stream, buf_1, ',')) \\\n strings.push_back(buf_1); \\\n map<int, string> tmp; \\\n for(vector<string>::iterator it = strings.begin(); \\\n it != strings.end(); \\\n ++it) \\\n { \\\n buf_1.clear(); buf_2.clear(); \\\n stringstream localStream(*it); \\\n localStream>> buf_1 >> buf_2; \\\n if(buf_2.size() > 0) \\\n val = atoi(buf_2.c_str()); \\\n tmp[val++] = buf_1; \\\n } \\\n return tmp; \\\n } \\\npublic: \\\n static std::string toString(int aInt) \\\n { \\\n return nameMap[aInt]; \\\n } \\\n}; \\\nstd::map<int, std::string> \\\nEnumName::nameMap = EnumName::initMap();\n</code></pre>\n\n<p>Usage:</p>\n\n<pre><code>SMART_ENUM(MyEnum, ONE=1, TWO, THREE, TEN=10, ELEVEN)\ncout<<MyEnum::toString(MyEnum::TWO);\ncout<<MyEnum::toString(10);\n</code></pre>\n"
},
{
"answer_id": 22255215,
"author": "OlivierB",
"author_id": 586277,
"author_profile": "https://Stackoverflow.com/users/586277",
"pm_score": 0,
"selected": false,
"text": "<p>Here is an attempt to get << and >> stream operators on enum automatically with an one line macro command only...</p>\n\n<p>Definitions:</p>\n\n<pre><code>#include <string>\n#include <iostream>\n#include <stdexcept>\n#include <algorithm>\n#include <iterator>\n#include <sstream>\n#include <vector>\n\n#define MAKE_STRING(str, ...) #str, MAKE_STRING1_(__VA_ARGS__)\n#define MAKE_STRING1_(str, ...) #str, MAKE_STRING2_(__VA_ARGS__)\n#define MAKE_STRING2_(str, ...) #str, MAKE_STRING3_(__VA_ARGS__)\n#define MAKE_STRING3_(str, ...) #str, MAKE_STRING4_(__VA_ARGS__)\n#define MAKE_STRING4_(str, ...) #str, MAKE_STRING5_(__VA_ARGS__)\n#define MAKE_STRING5_(str, ...) #str, MAKE_STRING6_(__VA_ARGS__)\n#define MAKE_STRING6_(str, ...) #str, MAKE_STRING7_(__VA_ARGS__)\n#define MAKE_STRING7_(str, ...) #str, MAKE_STRING8_(__VA_ARGS__)\n#define MAKE_STRING8_(str, ...) #str, MAKE_STRING9_(__VA_ARGS__)\n#define MAKE_STRING9_(str, ...) #str, MAKE_STRING10_(__VA_ARGS__)\n#define MAKE_STRING10_(str) #str\n\n#define MAKE_ENUM(name, ...) MAKE_ENUM_(, name, __VA_ARGS__)\n#define MAKE_CLASS_ENUM(name, ...) MAKE_ENUM_(friend, name, __VA_ARGS__)\n\n#define MAKE_ENUM_(attribute, name, ...) name { __VA_ARGS__ }; \\\n attribute std::istream& operator>>(std::istream& is, name& e) { \\\n const char* name##Str[] = { MAKE_STRING(__VA_ARGS__) }; \\\n std::string str; \\\n std::istream& r = is >> str; \\\n const size_t len = sizeof(name##Str)/sizeof(name##Str[0]); \\\n const std::vector<std::string> enumStr(name##Str, name##Str + len); \\\n const std::vector<std::string>::const_iterator it = std::find(enumStr.begin(), enumStr.end(), str); \\\n if (it != enumStr.end())\\\n e = name(it - enumStr.begin()); \\\n else \\\n throw std::runtime_error(\"Value \\\"\" + str + \"\\\" is not part of enum \"#name); \\\n return r; \\\n }; \\\n attribute std::ostream& operator<<(std::ostream& os, const name& e) { \\\n const char* name##Str[] = { MAKE_STRING(__VA_ARGS__) }; \\\n return (os << name##Str[e]); \\\n }\n</code></pre>\n\n<p>Usage:</p>\n\n<pre><code>// Declare global enum\nenum MAKE_ENUM(Test3, Item13, Item23, Item33, Itdsdgem43);\n\nclass Essai {\npublic:\n // Declare enum inside class\n enum MAKE_CLASS_ENUM(Test, Item1, Item2, Item3, Itdsdgem4);\n\n};\n\nint main() {\n std::cout << Essai::Item1 << std::endl;\n\n Essai::Test ddd = Essai::Item1;\n std::cout << ddd << std::endl;\n\n std::istringstream strm(\"Item2\");\n strm >> ddd;\n\n std::cout << (int) ddd << std::endl;\n std::cout << ddd << std::endl;\n}\n</code></pre>\n\n<p>Not sure about the limitations of this scheme though... comments are welcome!</p>\n"
},
{
"answer_id": 23290572,
"author": "user3510054",
"author_id": 3510054,
"author_profile": "https://Stackoverflow.com/users/3510054",
"pm_score": 0,
"selected": false,
"text": "<pre><code>#include <iostream>\n#include <map>\n#define IDMAP(x) (x,#x)\n\nstd::map<int , std::string> enToStr;\nclass mapEnumtoString\n{\npublic:\n mapEnumtoString(){ }\n mapEnumtoString& operator()(int i,std::string str)\n {\n enToStr[i] = str;\n return *this;\n }\npublic:\n std::string operator [] (int i)\n {\n return enToStr[i];\n }\n\n};\nmapEnumtoString k;\nmapEnumtoString& init()\n{\n return k;\n}\n\nint main()\n{\n\ninit()\n IDMAP(1)\n IDMAP(2)\n IDMAP(3)\n IDMAP(4)\n IDMAP(5);\nstd::cout<<enToStr[1];\nstd::cout<<enToStr[2];\nstd::cout<<enToStr[3];\nstd::cout<<enToStr[4];\nstd::cout<<enToStr[5];\n}\n</code></pre>\n"
},
{
"answer_id": 23402871,
"author": "Debdatta Basu",
"author_id": 1078703,
"author_profile": "https://Stackoverflow.com/users/1078703",
"pm_score": 4,
"selected": false,
"text": "<p>I have an incredibly simple to use macro that does this in a completely DRY fashion. It involves variadic macros and some simple parsing magic. Here goes:</p>\n\n<pre><code>#define AWESOME_MAKE_ENUM(name, ...) enum class name { __VA_ARGS__, __COUNT}; \\\ninline std::ostream& operator<<(std::ostream& os, name value) { \\\nstd::string enumName = #name; \\\nstd::string str = #__VA_ARGS__; \\\nint len = str.length(); \\\nstd::vector<std::string> strings; \\\nstd::ostringstream temp; \\\nfor(int i = 0; i < len; i ++) { \\\nif(isspace(str[i])) continue; \\\n else if(str[i] == ',') { \\\n strings.push_back(temp.str()); \\\n temp.str(std::string());\\\n } \\\n else temp<< str[i]; \\\n} \\\nstrings.push_back(temp.str()); \\\nos << enumName << \"::\" << strings[static_cast<int>(value)]; \\\nreturn os;} \n</code></pre>\n\n<p>To use this in your code, simply do:</p>\n\n<pre><code>AWESOME_MAKE_ENUM(Animal,\n DOG,\n CAT,\n HORSE\n);\n</code></pre>\n"
},
{
"answer_id": 23415866,
"author": "Mark Lakata",
"author_id": 364818,
"author_profile": "https://Stackoverflow.com/users/364818",
"pm_score": 2,
"selected": false,
"text": "<p>This is a modification to @user3360260 answer. It has the following new features</p>\n\n<ul>\n<li><code>MyEnum fromString(const string&)</code> support</li>\n<li>compiles with VisualStudio 2012</li>\n<li>the enum is an actual POD type (not just const declarations), so you can assign it to a variable.</li>\n<li>added C++ \"range\" feature (in form of vector) to allow \"foreach\" iteration over enum</li>\n</ul>\n\n<p>Usage:</p>\n\n<pre><code>SMART_ENUM(MyEnum, ONE=1, TWO, THREE, TEN=10, ELEVEN)\nMyEnum foo = MyEnum::TWO;\ncout << MyEnum::toString(foo); // static method\ncout << foo.toString(); // member method\ncout << MyEnum::toString(MyEnum::TWO);\ncout << MyEnum::toString(10);\nMyEnum foo = myEnum::fromString(\"TWO\");\n\n// C++11 iteration over all values\nfor( auto x : MyEnum::allValues() )\n{\n cout << x.toString() << endl;\n}\n</code></pre>\n\n<p>Here's the code</p>\n\n<pre><code>#define SMART_ENUM(EnumName, ...) \\\nclass EnumName \\\n{ \\\npublic: \\\n EnumName() : value(0) {} \\\n EnumName(int x) : value(x) {} \\\npublic: \\\n enum {__VA_ARGS__}; \\\nprivate: \\\n static void initMap(std::map<int, std::string>& tmp) \\\n { \\\n using namespace std; \\\n \\\n int val = 0; \\\n string buf_1, buf_2, str = #__VA_ARGS__; \\\n replace(str.begin(), str.end(), '=', ' '); \\\n stringstream stream(str); \\\n vector<string> strings; \\\n while (getline(stream, buf_1, ',')) \\\n strings.push_back(buf_1); \\\n for(vector<string>::iterator it = strings.begin(); \\\n it != strings.end(); \\\n ++it) \\\n { \\\n buf_1.clear(); buf_2.clear(); \\\n stringstream localStream(*it); \\\n localStream>> buf_1 >> buf_2; \\\n if(buf_2.size() > 0) \\\n val = atoi(buf_2.c_str()); \\\n tmp[val++] = buf_1; \\\n } \\\n } \\\n int value; \\\npublic: \\\n operator int () const { return value; } \\\n std::string toString(void) const { \\\n return toString(value); \\\n } \\\n static std::string toString(int aInt) \\\n { \\\n return nameMap()[aInt]; \\\n } \\\n static EnumName fromString(const std::string& s) \\\n { \\\n auto it = find_if(nameMap().begin(), nameMap().end(), [s](const std::pair<int,std::string>& p) { \\\n return p.second == s; \\\n }); \\\n if (it == nameMap().end()) { \\\n /*value not found*/ \\\n throw EnumName::Exception(); \\\n } else { \\\n return EnumName(it->first); \\\n } \\\n } \\\n class Exception : public std::exception {}; \\\n static std::map<int,std::string>& nameMap() { \\\n static std::map<int,std::string> nameMap0; \\\n if (nameMap0.size() ==0) initMap(nameMap0); \\\n return nameMap0; \\\n } \\\n static std::vector<EnumName> allValues() { \\\n std::vector<EnumName> x{ __VA_ARGS__ }; \\\n return x; \\\n } \\\n bool operator<(const EnumName a) const { return (int)*this < (int)a; } \\\n}; \n</code></pre>\n\n<p>Note that the conversion toString is a fast has lookup, while the conversion fromString is a slow linear search. But strings are so expensive anyways(and the associated file IO), I didn't feel the need to optimize or use a bimap.</p>\n"
},
{
"answer_id": 24296298,
"author": "serge",
"author_id": 3754427,
"author_profile": "https://Stackoverflow.com/users/3754427",
"pm_score": 3,
"selected": false,
"text": "<p>This can be done in C++11</p>\n\n<pre><code>#include <map>\nenum MyEnum { AA, BB, CC, DD };\n\nstatic std::map< MyEnum, const char * > info = {\n {AA, \"This is an apple\"},\n {BB, \"This is a book\"},\n {CC, \"This is a coffee\"},\n {DD, \"This is a door\"}\n};\n\nvoid main()\n{\n std::cout << info[AA] << endl\n << info[BB] << endl\n << info[CC] << endl\n << info[DD] << endl;\n}\n</code></pre>\n"
},
{
"answer_id": 25415021,
"author": "FractalSpace",
"author_id": 175169,
"author_profile": "https://Stackoverflow.com/users/175169",
"pm_score": 2,
"selected": false,
"text": "<p>Here a one-file solution (based on elegant answer by @Marcin:</p>\n\n<pre><code>#include <iostream>\n\n#define ENUM_TXT \\\nX(Red) \\\nX(Green) \\\nX(Blue) \\\nX(Cyan) \\\nX(Yellow) \\\nX(Magenta) \\\n\nenum Colours {\n# define X(a) a,\nENUM_TXT\n# undef X\n ColoursCount\n};\n\nchar const* const colours_str[] = {\n# define X(a) #a,\nENUM_TXT\n# undef X\n 0\n};\n\nstd::ostream& operator<<(std::ostream& os, enum Colours c)\n{\n if (c >= ColoursCount || c < 0) return os << \"???\";\n return os << colours_str[c] << std::endl;\n}\n\nint main()\n{\n std::cout << Red << Blue << Green << Cyan << Yellow << Magenta << std::endl;\n}\n</code></pre>\n"
},
{
"answer_id": 25554855,
"author": "lopes",
"author_id": 2777927,
"author_profile": "https://Stackoverflow.com/users/2777927",
"pm_score": 2,
"selected": false,
"text": "<p>This was my solution with BOOST:</p>\n\n<pre><code>#include <boost/preprocessor.hpp>\n\n#define X_STR_ENUM_TOSTRING_CASE(r, data, elem) \\\n case elem : return BOOST_PP_STRINGIZE(elem);\n\n#define X_ENUM_STR_TOENUM_IF(r, data, elem) \\\n else if(data == BOOST_PP_STRINGIZE(elem)) return elem;\n\n#define STR_ENUM(name, enumerators) \\\n enum name { \\\n BOOST_PP_SEQ_ENUM(enumerators) \\\n }; \\\n \\\n inline const QString enumToStr(name v) \\\n { \\\n switch (v) \\\n { \\\n BOOST_PP_SEQ_FOR_EACH( \\\n X_STR_ENUM_TOSTRING_CASE, \\\n name, \\\n enumerators \\\n ) \\\n \\\n default: \\\n return \"[Unknown \" BOOST_PP_STRINGIZE(name) \"]\"; \\\n } \\\n } \\\n \\\n template <typename T> \\\n inline const T strToEnum(QString v); \\\n \\\n template <> \\\n inline const name strToEnum(QString v) \\\n { \\\n if(v==\"\") \\\n throw std::runtime_error(\"Empty enum value\"); \\\n \\\n BOOST_PP_SEQ_FOR_EACH( \\\n X_ENUM_STR_TOENUM_IF, \\\n v, \\\n enumerators \\\n ) \\\n \\\n else \\\n throw std::runtime_error( \\\n QString(\"[Unknown value %1 for enum %2]\") \\\n .arg(v) \\\n .arg(BOOST_PP_STRINGIZE(name)) \\\n .toStdString().c_str()); \\\n }\n</code></pre>\n\n<p>To create enum, declare:</p>\n\n<pre><code>STR_ENUM\n(\n SERVICE_RELOAD,\n (reload_log)\n (reload_settings)\n (reload_qxml_server)\n)\n</code></pre>\n\n<p>For conversions:</p>\n\n<pre><code>SERVICE_RELOAD serviceReloadEnum = strToEnum<SERVICE_RELOAD>(\"reload_log\");\nQString serviceReloadStr = enumToStr(reload_log);\n</code></pre>\n"
},
{
"answer_id": 40370302,
"author": "Alexandru Irimiea",
"author_id": 4806882,
"author_profile": "https://Stackoverflow.com/users/4806882",
"pm_score": 2,
"selected": false,
"text": "<p>I want to post this in case someone finds it useful. </p>\n\n<p>In my case, I simply need to generate <code>ToString()</code> and <code>FromString()</code> functions for a single C++11 enum from a single <code>.hpp</code> file.</p>\n\n<p>I wrote a python script that parses the header file containing the enum items and generates the functions in a new <code>.cpp</code> file. </p>\n\n<p>You can add this script in CMakeLists.txt with <a href=\"https://cmake.org/cmake/help/v3.0/command/execute_process.html\" rel=\"nofollow noreferrer\">execute_process</a>, or as a pre-build event in Visual Studio. The <code>.cpp</code> file will be automatically generated, without the need to manually update it each time a new enum item is added.</p>\n\n<p><strong>generate_enum_strings.py</strong></p>\n\n<pre><code># This script is used to generate strings from C++ enums\n\nimport re\nimport sys\nimport os\n\nfileName = sys.argv[1]\nenumName = os.path.basename(os.path.splitext(fileName)[0])\n\nwith open(fileName, 'r') as f:\n content = f.read().replace('\\n', '')\n\nsearchResult = re.search('enum(.*)\\{(.*?)\\};', content)\ntokens = searchResult.group(2)\ntokens = tokens.split(',')\ntokens = map(str.strip, tokens)\ntokens = map(lambda token: re.search('([a-zA-Z0-9_]*)', token).group(1), tokens)\n\ntextOut = ''\ntextOut += '\\n#include \"' + enumName + '.hpp\"\\n\\n'\ntextOut += 'namespace myns\\n'\ntextOut += '{\\n'\ntextOut += ' std::string ToString(ErrorCode errorCode)\\n'\ntextOut += ' {\\n'\ntextOut += ' switch (errorCode)\\n'\ntextOut += ' {\\n'\n\nfor token in tokens:\n textOut += ' case ' + enumName + '::' + token + ':\\n'\n textOut += ' return \"' + token + '\";\\n'\n\ntextOut += ' default:\\n'\ntextOut += ' return \"Last\";\\n'\ntextOut += ' }\\n'\ntextOut += ' }\\n'\ntextOut += '\\n'\ntextOut += ' ' + enumName + ' FromString(const std::string &errorCode)\\n'\ntextOut += ' {\\n'\ntextOut += ' if (\"' + tokens[0] + '\" == errorCode)\\n'\ntextOut += ' {\\n'\ntextOut += ' return ' + enumName + '::' + tokens[0] + ';\\n'\ntextOut += ' }\\n'\n\nfor token in tokens[1:]:\n textOut += ' else if(\"' + token + '\" == errorCode)\\n'\n textOut += ' {\\n'\n textOut += ' return ' + enumName + '::' + token + ';\\n'\n textOut += ' }\\n'\n\ntextOut += '\\n'\ntextOut += ' return ' + enumName + '::Last;\\n'\ntextOut += ' }\\n'\ntextOut += '}\\n'\n\nfileOut = open(enumName + '.cpp', 'w')\nfileOut.write(textOut)\n</code></pre>\n\n<p>Example:</p>\n\n<p><strong>ErrorCode.hpp</strong></p>\n\n<pre><code>#pragma once\n\n#include <string>\n#include <cstdint>\n\nnamespace myns\n{\n enum class ErrorCode : uint32_t\n {\n OK = 0,\n OutOfSpace,\n ConnectionFailure,\n InvalidJson,\n DatabaseFailure,\n HttpError,\n FileSystemError,\n FailedToEncrypt,\n FailedToDecrypt,\n EndOfFile,\n FailedToOpenFileForRead,\n FailedToOpenFileForWrite,\n FailedToLaunchProcess,\n\n Last\n };\n\n std::string ToString(ErrorCode errorCode);\n ErrorCode FromString(const std::string &errorCode);\n}\n</code></pre>\n\n<p>Run <code>python generate_enum_strings.py ErrorCode.hpp</code></p>\n\n<p>Result:</p>\n\n<p><strong>ErrorCode.cpp</strong></p>\n\n<pre><code>#include \"ErrorCode.hpp\"\n\nnamespace myns\n{\n std::string ToString(ErrorCode errorCode)\n {\n switch (errorCode)\n {\n case ErrorCode::OK:\n return \"OK\";\n case ErrorCode::OutOfSpace:\n return \"OutOfSpace\";\n case ErrorCode::ConnectionFailure:\n return \"ConnectionFailure\";\n case ErrorCode::InvalidJson:\n return \"InvalidJson\";\n case ErrorCode::DatabaseFailure:\n return \"DatabaseFailure\";\n case ErrorCode::HttpError:\n return \"HttpError\";\n case ErrorCode::FileSystemError:\n return \"FileSystemError\";\n case ErrorCode::FailedToEncrypt:\n return \"FailedToEncrypt\";\n case ErrorCode::FailedToDecrypt:\n return \"FailedToDecrypt\";\n case ErrorCode::EndOfFile:\n return \"EndOfFile\";\n case ErrorCode::FailedToOpenFileForRead:\n return \"FailedToOpenFileForRead\";\n case ErrorCode::FailedToOpenFileForWrite:\n return \"FailedToOpenFileForWrite\";\n case ErrorCode::FailedToLaunchProcess:\n return \"FailedToLaunchProcess\";\n case ErrorCode::Last:\n return \"Last\";\n default:\n return \"Last\";\n }\n }\n\n ErrorCode FromString(const std::string &errorCode)\n {\n if (\"OK\" == errorCode)\n {\n return ErrorCode::OK;\n }\n else if(\"OutOfSpace\" == errorCode)\n {\n return ErrorCode::OutOfSpace;\n }\n else if(\"ConnectionFailure\" == errorCode)\n {\n return ErrorCode::ConnectionFailure;\n }\n else if(\"InvalidJson\" == errorCode)\n {\n return ErrorCode::InvalidJson;\n }\n else if(\"DatabaseFailure\" == errorCode)\n {\n return ErrorCode::DatabaseFailure;\n }\n else if(\"HttpError\" == errorCode)\n {\n return ErrorCode::HttpError;\n }\n else if(\"FileSystemError\" == errorCode)\n {\n return ErrorCode::FileSystemError;\n }\n else if(\"FailedToEncrypt\" == errorCode)\n {\n return ErrorCode::FailedToEncrypt;\n }\n else if(\"FailedToDecrypt\" == errorCode)\n {\n return ErrorCode::FailedToDecrypt;\n }\n else if(\"EndOfFile\" == errorCode)\n {\n return ErrorCode::EndOfFile;\n }\n else if(\"FailedToOpenFileForRead\" == errorCode)\n {\n return ErrorCode::FailedToOpenFileForRead;\n }\n else if(\"FailedToOpenFileForWrite\" == errorCode)\n {\n return ErrorCode::FailedToOpenFileForWrite;\n }\n else if(\"FailedToLaunchProcess\" == errorCode)\n {\n return ErrorCode::FailedToLaunchProcess;\n }\n else if(\"Last\" == errorCode)\n {\n return ErrorCode::Last;\n }\n\n return ErrorCode::Last;\n }\n}\n</code></pre>\n"
},
{
"answer_id": 43415137,
"author": "cibercitizen1",
"author_id": 286335,
"author_profile": "https://Stackoverflow.com/users/286335",
"pm_score": 0,
"selected": false,
"text": "<p>Well, yet another option. A typical use case is where you need constant for the HTTP verbs as well as using is string version values.</p>\n\n<p>The example:</p>\n\n<pre><code>int main () {\n\n VERB a = VERB::GET;\n VERB b = VERB::GET;\n VERB c = VERB::POST;\n VERB d = VERB::PUT;\n VERB e = VERB::DELETE;\n\n\n std::cout << a.toString() << std::endl;\n\n std::cout << a << std::endl;\n\n if ( a == VERB::GET ) {\n std::cout << \"yes\" << std::endl;\n }\n\n if ( a == b ) {\n std::cout << \"yes\" << std::endl;\n }\n\n if ( a != c ) {\n std::cout << \"no\" << std::endl;\n }\n\n}\n</code></pre>\n\n<p>The VERB class:</p>\n\n<pre><code>// -----------------------------------------------------------\n// -----------------------------------------------------------\nclass VERB {\n\nprivate:\n\n // private constants\n enum Verb {GET_=0, POST_, PUT_, DELETE_};\n\n // private string values\n static const std::string theStrings[];\n\n // private value\n const Verb value;\n const std::string text;\n\n // private constructor\n VERB (Verb v) :\n value(v), text (theStrings[v])\n {\n // std::cout << \" constructor \\n\";\n }\n\npublic:\n\n operator const char * () const { return text.c_str(); }\n\n operator const std::string () const { return text; }\n\n const std::string toString () const { return text; }\n\n bool operator == (const VERB & other) const { return (*this).value == other.value; }\n\n bool operator != (const VERB & other) const { return ! ( (*this) == other); }\n\n // ---\n\n static const VERB GET;\n static const VERB POST;\n static const VERB PUT;\n static const VERB DELETE;\n\n};\n\nconst std::string VERB::theStrings[] = {\"GET\", \"POST\", \"PUT\", \"DELETE\"};\n\nconst VERB VERB::GET = VERB ( VERB::Verb::GET_ );\nconst VERB VERB::POST = VERB ( VERB::Verb::POST_ );\nconst VERB VERB::PUT = VERB ( VERB::Verb::PUT_ );\nconst VERB VERB::DELETE = VERB ( VERB::Verb::DELETE_ );\n// end of file\n</code></pre>\n"
},
{
"answer_id": 45175792,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 0,
"selected": false,
"text": "<p>Using compound ternary statements can be somewhat elegant for enums with few elements (one-liner). The expression only grows approximately linearly in length with the number of elements too.</p>\n\n<p>Here's a good use case:</p>\n\n<pre><code>enum log_level {INFO, WARNING, ERROR};\n...\nvoid logger::write(const std::string log, const log_level l) {\n ...\n std::string s = (l == INFO) ? \"INFO\" : \n (l == WARNING) ? \"WARNING\" : \n (l == ERROR) ? \"ERROR\" : \"UNKNOWN\";\n ...\n}\n...\n</code></pre>\n\n<p>Of course, it's just another switch/if statement block, but it's a single line statement. And as a matter of terseness vs. simplicity, it meets somewhere in the middle. As a constant expression, it can be easily made into an inline function as well.</p>\n"
},
{
"answer_id": 51255099,
"author": "Joe C",
"author_id": 9344166,
"author_profile": "https://Stackoverflow.com/users/9344166",
"pm_score": 0,
"selected": false,
"text": "<p>I came across this question when I was looking for a solution to my own problem for printing the \"words\" of the enumeration in C++. I came back to provide a simple solution which answers the presented question as worded. All that's required is to 'mirror' the enum list with a vector.</p>\n\n<pre><code>enum class genre { Fiction, NonFiction, Periodical, Biography, Children };\n\nvector<string>genre_tbl { \"Fiction\", \"NonFiction\", \"Periodical\", \"Biography\", \"Children\" };\n</code></pre>\n\n<p>Because the enum as typed above will do the following by default;</p>\n\n<pre><code>Fiction = 0\nNonFiction = 1\nPeriodical = 2\nBiography = 3\nChildren = 4\n</code></pre>\n\n<p>This matches the vector positions which makes enum to string conversion pretty straight forward.</p>\n\n<pre><code>string s1 = genre_tbl[int(genre::fiction)];\n</code></pre>\n\n<p>For my problem I created a user defined class called Book with a member called Gen of type genre. The program needed to be able to print the genre as the word.</p>\n\n<pre><code>class book {...};\nostream& operator<<(ostream& os, genre g) { return os << genre_tbl[int(g)]; }\n\nbook b1;\nb1.Gen = genre(0)\ncout << b1.Gen;\n</code></pre>\n\n<p>For which \"Fiction\" will print to screen in this case.</p>\n"
},
{
"answer_id": 52264973,
"author": "Francois Bertrand",
"author_id": 5669529,
"author_profile": "https://Stackoverflow.com/users/5669529",
"pm_score": 2,
"selected": false,
"text": "<p>Adding even more simplicity of use to <a href=\"https://stackoverflow.com/a/238157/2124447\">Jasper Bekkers' fantastic answer</a>:</p>\n\n<p>Set up once:</p>\n\n<pre><code>#define MAKE_ENUM(VAR) VAR,\n#define MAKE_STRINGS(VAR) #VAR,\n#define MAKE_ENUM_AND_STRINGS(source, enumName, enumStringName) \\\n enum enumName { \\\n source(MAKE_ENUM) \\\n };\\\nconst char* const enumStringName[] = { \\\n source(MAKE_STRINGS) \\\n };\n</code></pre>\n\n<p>Then, for usage:</p>\n\n<pre><code>#define SOME_ENUM(DO) \\\n DO(Foo) \\\n DO(Bar) \\\n DO(Baz)\n...\nMAKE_ENUM_AND_STRINGS(SOME_ENUM, someEnum, someEnumNames)\n</code></pre>\n"
},
{
"answer_id": 52669478,
"author": "Nick",
"author_id": 3233,
"author_profile": "https://Stackoverflow.com/users/3233",
"pm_score": 2,
"selected": false,
"text": "<p>You could use a reflection library, like <a href=\"https://billyquith.github.io/ponder/\" rel=\"nofollow noreferrer\">Ponder</a>. You register the enums and then you can convert them back and forth with the API.</p>\n\n<pre><code>enum class MyEnum\n{\n Zero = 0,\n One = 1,\n Two = 2\n};\n\nponder::Enum::declare<MyEnum>()\n .value(\"Zero\", MyEnum::Zero)\n .value(\"One\", MyEnum::One)\n .value(\"Two\", MyEnum::Two);\n\nponder::EnumObject zero(MyEnum::Zero);\n\nzero.name(); // -> \"Zero\"\n</code></pre>\n"
},
{
"answer_id": 54507451,
"author": "jose.angel.jimenez",
"author_id": 634355,
"author_profile": "https://Stackoverflow.com/users/634355",
"pm_score": 0,
"selected": false,
"text": "<p>This question is a duplicate of,</p>\n\n<ul>\n<li><a href=\"https://stackoverflow.com/questions/207976/how-to-easily-map-c-enums-to-strings/54504663#54504663\">How to easily map c++ enums to strings</a></li>\n</ul>\n\n<p>However, in none of the questions, I could find good answers.</p>\n\n<p>After delving into the topic, I found two great open source solutions:</p>\n\n<p><a href=\"https://github.com/quicknir/wise_enum\" rel=\"nofollow noreferrer\"><strong>wise_enum</strong></a></p>\n\n<ul>\n<li><strong>Standalone smart enum library for C++11/14/17</strong>. It supports all of the standard functionality that you would expect from a smart enum class in C++.</li>\n<li>Limitations: requires at least C++11.</li>\n</ul>\n\n<p><a href=\"https://github.com/aantron/better-enums\" rel=\"nofollow noreferrer\"><strong>Better Enums</strong></a></p>\n\n<ul>\n<li><strong>Reflective compile-time enum library with clean syntax</strong>, in a single header file, and without dependencies.</li>\n<li>Limitations: based on macros, can't be used inside a class.</li>\n</ul>\n\n<p>Note: I am repeating the recommendation here. This question has a lot of traffic/views and really requires listing the solutions above.</p>\n"
},
{
"answer_id": 72580429,
"author": "cppguy",
"author_id": 1325084,
"author_profile": "https://Stackoverflow.com/users/1325084",
"pm_score": 2,
"selected": false,
"text": "<p>A little late to the party here but I really like this pattern because it saves you from copy-pasta errors and will flat out not compile if the enum doesn't get mapped to a string. It also has the advantage of being very <code>constexpr</code> friendly so it inlines extremely well. It also requires no intermediate classes, switch statements, or runtime values.</p>\n<pre><code>// Create a mapping between the enum value and the string\n#define MY_ENUM_LIST(DECLARE) \\\nDECLARE(foo, "This is a foo!") \\\nDECLARE(bar, "This is a bar!") \\\nDECLARE(bam, "This is a bam!")\n\n// Define the enum officially\nenum class MyEnum {\n#define ENUM_ENTRY(NAME, TEXT) NAME, // TEXT expressly not used here\n MY_ENUM_LIST(ENUM_ENTRY)\n#undef ENUM_ENTRY // Always undef as a good citizen ;)\n};\n\n// Create a template function that would fail to compile if called\ntemplate <MyEnum KEY> constexpr const char* MyEnumText() {}\n\n// Specialize that bad function with versions that map the enum value to the string declared above\n#define ENUM_FUNC(NAME, TEXT) template <> constexpr const char* MyEnumText<MyEnum::NAME>() { return TEXT; }\nMY_ENUM_LIST(ENUM_FUNC)\n#undef ENUM_FUNC\n</code></pre>\n<p>The way you use it is pretty straight forward. If you're always hardcoding the enum value at the site that you need the string, you simply call the specialized version of <code>MyEnumText</code>:</p>\n<pre><code>const auto text{::MyEnumText<MyEnum::foo>()}; // inlines beautifully\n</code></pre>\n<p>If you need to handle dynamic enum values, you can add this additional helper:</p>\n<pre><code>constexpr const char* MyEnumText(MyEnum key) {\n switch (key) {\n#define ENUM_CASE(NAME, TEXT) case MyEnum::NAME: return MyEnumText<MyEnum::NAME>();\n MY_ENUM_LIST(ENUM_CASE)\n#undef ENUM_CASE\n }\n return nullptr;\n}\n</code></pre>\n<p>Which is invoked similarly to the template specialization:</p>\n<pre><code>const auto text{::MyEnumText(MyEnum::foo)}; // inlines beautifully\n</code></pre>\n<p>or</p>\n<pre><code>const MyEnum e{GetTheEnumValue()};\nconst auto text{::MyEnumText(e)};\n</code></pre>\n"
}
] |
2008/10/14
|
[
"https://Stackoverflow.com/questions/201593",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/21648/"
] |
Suppose we have some named enums:
```
enum MyEnum {
FOO,
BAR = 0x50
};
```
What I googled for is a script (any language) that scans all the headers in my project and generates a header with one function per enum.
```
char* enum_to_string(MyEnum t);
```
And a implementation with something like this:
```
char* enum_to_string(MyEnum t){
switch(t){
case FOO:
return "FOO";
case BAR:
return "BAR";
default:
return "INVALID ENUM";
}
}
```
The gotcha is really with typedefed enums, and unnamed C style enums. Does anybody know something for this?
EDIT: The solution should not modify my source, except for the generated functions. The enums are in an API, so using the solutions proposed until now is just not an option.
|
You may want to check out [GCCXML](http://www.gccxml.org/HTML/Index.html).
Running GCCXML on your sample code produces:
```
<GCC_XML>
<Namespace id="_1" name="::" members="_3 " mangled="_Z2::"/>
<Namespace id="_2" name="std" context="_1" members="" mangled="_Z3std"/>
<Enumeration id="_3" name="MyEnum" context="_1" location="f0:1" file="f0" line="1">
<EnumValue name="FOO" init="0"/>
<EnumValue name="BAR" init="80"/>
</Enumeration>
<File id="f0" name="my_enum.h"/>
</GCC_XML>
```
You could use any language you prefer to pull out the Enumeration and EnumValue tags and generate your desired code.
|
201,606 |
<p>For the past 2 years-(ish) I've been using <a href="http://maven.apache.org" rel="nofollow noreferrer">Maven2</a> for my build/continuous integration solution. I used <a href="http://ant.apache.org" rel="nofollow noreferrer">Ant</a> a bit before that but really didn't get a lot of experience with it. Now I've taken a new job and the team I'm on now uses Ant. </p>
<p>What I'm wondering about is this:</p>
<p>In Maven we had directory conventions for seperating our java source and files and java test files (<a href="http://junit.org" rel="nofollow noreferrer">JUnit</a> tests). It looked like this:</p>
<pre><code>Project-
-src/main/java
-src/test/java
</code></pre>
<p>This way your tests are separate from your source/production code and won't be built/deployed as such.</p>
<p>Going over the Ant documentation I don't really see any convention for this. Am I missing something? Is there a similar convention in Ant?</p>
|
[
{
"answer_id": 201623,
"author": "Chris R",
"author_id": 23309,
"author_profile": "https://Stackoverflow.com/users/23309",
"pm_score": 4,
"selected": true,
"text": "<p>My experience with ant -- which is our primary build tool for Java source, so make of this what you will -- is that there are no such <em>formal</em> conventions. Many source projects I've seen organize things in a similar manner; JBoss uses <module>/src/main for sources, etc... Ant just uses whatever conventions you want, which makes it an ideal tool to integrate into a larger project building framework.</p>\n\n<p>At any rate, the Maven conventions work just fine for Ant, so if you've already got them in place, just re-use the same structures. Not only is it easier for you to keep track of where things are, when you use a familiar structure, but if you ever decide to mavenize the project, you'll already be set.</p>\n"
},
{
"answer_id": 203454,
"author": "Mads Hansen",
"author_id": 14419,
"author_profile": "https://Stackoverflow.com/users/14419",
"pm_score": 2,
"selected": false,
"text": "<p>A lot of ANT conventions/best practices are explained in <a href=\"http://ant.apache.org/ant_in_anger.html\" rel=\"nofollow noreferrer\">ANT in Anger</a></p>\n"
},
{
"answer_id": 247994,
"author": "Mnementh",
"author_id": 21005,
"author_profile": "https://Stackoverflow.com/users/21005",
"pm_score": 0,
"selected": false,
"text": "<p>An older resource but fine in my opinion are <a href=\"http://www.onjava.com/pub/a/onjava/2003/12/17/ant_bestpractices.html\" rel=\"nofollow noreferrer\">ant-best-practices</a>.</p>\n"
}
] |
2008/10/14
|
[
"https://Stackoverflow.com/questions/201606",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3030/"
] |
For the past 2 years-(ish) I've been using [Maven2](http://maven.apache.org) for my build/continuous integration solution. I used [Ant](http://ant.apache.org) a bit before that but really didn't get a lot of experience with it. Now I've taken a new job and the team I'm on now uses Ant.
What I'm wondering about is this:
In Maven we had directory conventions for seperating our java source and files and java test files ([JUnit](http://junit.org) tests). It looked like this:
```
Project-
-src/main/java
-src/test/java
```
This way your tests are separate from your source/production code and won't be built/deployed as such.
Going over the Ant documentation I don't really see any convention for this. Am I missing something? Is there a similar convention in Ant?
|
My experience with ant -- which is our primary build tool for Java source, so make of this what you will -- is that there are no such *formal* conventions. Many source projects I've seen organize things in a similar manner; JBoss uses <module>/src/main for sources, etc... Ant just uses whatever conventions you want, which makes it an ideal tool to integrate into a larger project building framework.
At any rate, the Maven conventions work just fine for Ant, so if you've already got them in place, just re-use the same structures. Not only is it easier for you to keep track of where things are, when you use a familiar structure, but if you ever decide to mavenize the project, you'll already be set.
|
201,607 |
<p>I'd like to do something like this:</p>
<pre><code>Dim Foo as String = "a,b,c,d,e"
Dim Boo as List(of String) = Foo.Split(","c)
</code></pre>
<p>Of course <code>Foo.Split</code> returns a one-dimensional array of <code>String</code>, not a generic <code>List</code>. Is there a way to do this without iterating through the array to turn it into a generic <code>List</code>?</p>
|
[
{
"answer_id": 201622,
"author": "IAmCodeMonkey",
"author_id": 27613,
"author_profile": "https://Stackoverflow.com/users/27613",
"pm_score": 0,
"selected": false,
"text": "<p>If you use Linq, you can use the ToList() extension method</p>\n\n<pre><code>Dim strings As List<string> = string_variable.Split().ToList<string>();\n</code></pre>\n"
},
{
"answer_id": 201627,
"author": "Mats Fredriksson",
"author_id": 2973,
"author_profile": "https://Stackoverflow.com/users/2973",
"pm_score": 3,
"selected": false,
"text": "<p>You can use the List's constructor.</p>\n\n<pre><code>String foo = \"a,b,c,d,e\";\nList<String> boo = new List<String>(foo.Split(\",\"));\n</code></pre>\n"
},
{
"answer_id": 201633,
"author": "Bob King",
"author_id": 6897,
"author_profile": "https://Stackoverflow.com/users/6897",
"pm_score": 6,
"selected": true,
"text": "<p>If you don't want to use LINQ, you can do:</p>\n\n<pre><code>Dim foo As String = \"a,b,c,d,e\"\nDim boo As New List(Of String)(foo.Split(\",\"c))\n</code></pre>\n"
},
{
"answer_id": 201635,
"author": "Jon Skeet",
"author_id": 22656,
"author_profile": "https://Stackoverflow.com/users/22656",
"pm_score": 3,
"selected": false,
"text": "<p>Do you really need a List<T> or will IList<T> do? Because string[] already implements the latter... just another reason why it's worth programming to the interfaces where you can. (It could be that in this case you really can't, admittedly.)</p>\n"
},
{
"answer_id": 201642,
"author": "amcoder",
"author_id": 26898,
"author_profile": "https://Stackoverflow.com/users/26898",
"pm_score": 2,
"selected": false,
"text": "<p>The easiest method would probably be the AddRange method.</p>\n\n<pre><code>Dim Foo as String = \"a,b,c,d,e\"\nDim Boo as List(of String)\n\nBoo.AddRange(Foo.Split(\",\"c))\n</code></pre>\n"
},
{
"answer_id": 320699,
"author": "mattruma",
"author_id": 1768,
"author_profile": "https://Stackoverflow.com/users/1768",
"pm_score": 0,
"selected": false,
"text": "<p>Here is how I am doing it ... since the split is looking for an array of char I clip off the first value in my string.</p>\n\n<pre><code>var values = labels.Split(\" \"[0]).ToList<string>();\n</code></pre>\n"
},
{
"answer_id": 33397537,
"author": "Gopher",
"author_id": 2317134,
"author_profile": "https://Stackoverflow.com/users/2317134",
"pm_score": 0,
"selected": false,
"text": "<p>To build on the answer, Ive found the following very helpful:</p>\n\n<pre><code>Return New List(Of String)(IO.File.ReadAllLines(sFileName))\n</code></pre>\n"
},
{
"answer_id": 52590547,
"author": "Tim Makins",
"author_id": 3750058,
"author_profile": "https://Stackoverflow.com/users/3750058",
"pm_score": 0,
"selected": false,
"text": "<pre><code>Dim Foo as String = \"a,b,c,d,e\"\nDim Boo as List(of String)\nBoo = Split(Foo, \",\").ToList\n</code></pre>\n\n<p>The advantage of doing it this way is that the split-string will accept multiple characters:</p>\n\n<pre><code>Dim Foo as String = \"a<blah>b<blah>c<blah>d<blah>e\"\nDim Boo as List(of String)\nBoo = Split(Foo, \"<blah>\").ToList\n</code></pre>\n"
}
] |
2008/10/14
|
[
"https://Stackoverflow.com/questions/201607",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/239663/"
] |
I'd like to do something like this:
```
Dim Foo as String = "a,b,c,d,e"
Dim Boo as List(of String) = Foo.Split(","c)
```
Of course `Foo.Split` returns a one-dimensional array of `String`, not a generic `List`. Is there a way to do this without iterating through the array to turn it into a generic `List`?
|
If you don't want to use LINQ, you can do:
```
Dim foo As String = "a,b,c,d,e"
Dim boo As New List(Of String)(foo.Split(","c))
```
|
201,615 |
<p>Can some one post an example of using syslog outputter for log4r, I am currently using stdout but want to log to syslog.</p>
<pre><code>mylog = Logger.new 'mylog'
mylog.outputters = Outputter.stdout
mylog.info "Starting up."
</code></pre>
<p>raj</p>
<hr>
<p>Thanks also to the following blog posts.<br> </p>
<p><a href="http://angrez.blogspot.com/2006/12/log4r-usage-and-examples.html" rel="nofollow noreferrer">Angrez's blog: Log4r - Usage and Examples</a></p>
<p><a href="http://programmingstuff.wikidot.com/log4r" rel="nofollow noreferrer">ProgrammingStuff: Log4r</a></p>
|
[
{
"answer_id": 203848,
"author": "Rajkumar S",
"author_id": 25453,
"author_profile": "https://Stackoverflow.com/users/25453",
"pm_score": 4,
"selected": true,
"text": "<p>Kind of lame answering my own question, but I found answer to this and adding it for later searches.</p>\n\n<p>For some reason I need to require log4r/outputter/syslogoutputter explicitly other wise SyslogOutputter would cause \"uninitialized constant SyslogOutputter (NameError)\" error. Other outputters do not seem to have this problem. </p>\n\n<pre><code>require 'rubygems'\nrequire 'log4r'\nrequire 'log4r/outputter/syslogoutputter'\nmylog = Logger.new 'mylog'\nmylog.outputters = SyslogOutputter.new(\"f1\", :ident => \"myscript\")\nmylog.info \"Starting up.\"\n</code></pre>\n\n<p>raj</p>\n"
},
{
"answer_id": 887063,
"author": "Anders Eurenius",
"author_id": 1421,
"author_profile": "https://Stackoverflow.com/users/1421",
"pm_score": 1,
"selected": false,
"text": "<p>I found this very helpful, but I had to make further edits. Something tried to re-open the syslog, causing an unhandled RuntimeError. I fixed it with this axe-crazy override in environments/production.rb:</p>\n\n<pre><code>require 'rubygems'\nrequire 'log4r'\nrequire 'log4r/outputter/syslogoutputter'\n\n# The outputter needs some love to avoid attempts to reopen syslog. Most of this is cargo-culted from source.\nclass Log4r::SyslogOutputter\n def initialize(_name, hash={})\n super(_name, hash)\n ident = (hash[:ident] or hash['ident'] or _name)\n logopt = (hash[:logopt] or hash['logopt'] or LOG_PID | LOG_CONS).to_i\n facility = (hash[:facility] or hash['facility'] or LOG_USER).to_i\n if Syslog.opened? then\n @syslog = Syslog\n else\n @syslog = Syslog.open(ident, logopt, facility)\n end\n end\nend\n\nRAILS_DEFAULT_LOGGER = Log4r::Logger.new 'mylog'\nconfig.logger = RAILS_DEFAULT_LOGGER\nconfig.logger.outputters = Log4r::SyslogOutputter.new(\"f1\", :ident=>\"RoR\")\nconfig.logger.info \"Starting up.\"\n</code></pre>\n\n<p>There's probably a much prettier way of doing it, but this would seem to do it for me.</p>\n"
}
] |
2008/10/14
|
[
"https://Stackoverflow.com/questions/201615",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/25453/"
] |
Can some one post an example of using syslog outputter for log4r, I am currently using stdout but want to log to syslog.
```
mylog = Logger.new 'mylog'
mylog.outputters = Outputter.stdout
mylog.info "Starting up."
```
raj
---
Thanks also to the following blog posts.
[Angrez's blog: Log4r - Usage and Examples](http://angrez.blogspot.com/2006/12/log4r-usage-and-examples.html)
[ProgrammingStuff: Log4r](http://programmingstuff.wikidot.com/log4r)
|
Kind of lame answering my own question, but I found answer to this and adding it for later searches.
For some reason I need to require log4r/outputter/syslogoutputter explicitly other wise SyslogOutputter would cause "uninitialized constant SyslogOutputter (NameError)" error. Other outputters do not seem to have this problem.
```
require 'rubygems'
require 'log4r'
require 'log4r/outputter/syslogoutputter'
mylog = Logger.new 'mylog'
mylog.outputters = SyslogOutputter.new("f1", :ident => "myscript")
mylog.info "Starting up."
```
raj
|
201,621 |
<p>In MySQL, how do I get a list of all foreign key constraints pointing to a particular table? a particular column? This is the same thing as <a href="https://stackoverflow.com/questions/85978/query-a-tables-foreign-key-relationships">this Oracle question</a>, but for MySQL.</p>
|
[
{
"answer_id": 201647,
"author": "Node",
"author_id": 7190,
"author_profile": "https://Stackoverflow.com/users/7190",
"pm_score": 7,
"selected": false,
"text": "<p>If you use InnoDB and defined FK's you could query the information_schema database e.g.:</p>\n\n<pre><code>SELECT * FROM information_schema.TABLE_CONSTRAINTS \nWHERE information_schema.TABLE_CONSTRAINTS.CONSTRAINT_TYPE = 'FOREIGN KEY' \nAND information_schema.TABLE_CONSTRAINTS.TABLE_SCHEMA = 'myschema'\nAND information_schema.TABLE_CONSTRAINTS.TABLE_NAME = 'mytable';\n</code></pre>\n"
},
{
"answer_id": 201676,
"author": "Christian Oudard",
"author_id": 3757,
"author_profile": "https://Stackoverflow.com/users/3757",
"pm_score": 2,
"selected": false,
"text": "<p>The solution I came up with is fragile; it relies on django's naming convention for foreign keys.</p>\n\n<pre><code>USE information_schema;\ntee mysql_output\nSELECT * FROM TABLE_CONSTRAINTS WHERE CONSTRAINT_TYPE = 'FOREIGN KEY' AND TABLE_SCHEMA = 'database_name';\nnotee\n</code></pre>\n\n<p>Then, in the shell,</p>\n\n<pre><code>grep 'refs_tablename_id' mysql_output\n</code></pre>\n"
},
{
"answer_id": 201678,
"author": "Vinko Vrsalovic",
"author_id": 5190,
"author_profile": "https://Stackoverflow.com/users/5190",
"pm_score": 11,
"selected": true,
"text": "<p><strong>For a Table:</strong></p>\n\n<pre><code>SELECT \n TABLE_NAME,COLUMN_NAME,CONSTRAINT_NAME, REFERENCED_TABLE_NAME,REFERENCED_COLUMN_NAME\nFROM\n INFORMATION_SCHEMA.KEY_COLUMN_USAGE\nWHERE\n REFERENCED_TABLE_SCHEMA = '<database>' AND\n REFERENCED_TABLE_NAME = '<table>';\n</code></pre>\n\n<p><strong>For a Column:</strong></p>\n\n<pre><code>SELECT \n TABLE_NAME,COLUMN_NAME,CONSTRAINT_NAME, REFERENCED_TABLE_NAME,REFERENCED_COLUMN_NAME\nFROM\n INFORMATION_SCHEMA.KEY_COLUMN_USAGE\nWHERE\n REFERENCED_TABLE_SCHEMA = '<database>' AND\n REFERENCED_TABLE_NAME = '<table>' AND\n REFERENCED_COLUMN_NAME = '<column>';\n</code></pre>\n\n<p>Basically, we changed REFERENCED_TABLE_NAME with REFERENCED_COLUMN_NAME in the where clause.</p>\n"
},
{
"answer_id": 11302791,
"author": "Andy",
"author_id": 850977,
"author_profile": "https://Stackoverflow.com/users/850977",
"pm_score": 6,
"selected": false,
"text": "<p>Posting on an old answer to add some useful information.</p>\n\n<p>I had a similar problem, but I also wanted to see the CONSTRAINT_TYPE along with the REFERENCED table and column names. So,</p>\n\n<ol>\n<li><p>To see all FKs in your table:</p>\n\n<pre><code>USE '<yourschema>';\n\nSELECT i.TABLE_NAME, i.CONSTRAINT_TYPE, i.CONSTRAINT_NAME, k.REFERENCED_TABLE_NAME, k.REFERENCED_COLUMN_NAME \nFROM information_schema.TABLE_CONSTRAINTS i \nLEFT JOIN information_schema.KEY_COLUMN_USAGE k ON i.CONSTRAINT_NAME = k.CONSTRAINT_NAME \nWHERE i.CONSTRAINT_TYPE = 'FOREIGN KEY' \nAND i.TABLE_SCHEMA = DATABASE()\nAND i.TABLE_NAME = '<yourtable>';\n</code></pre></li>\n<li><p>To see all the tables and FKs in your schema:</p>\n\n<pre><code>USE '<yourschema>';\n\nSELECT i.TABLE_NAME, i.CONSTRAINT_TYPE, i.CONSTRAINT_NAME, k.REFERENCED_TABLE_NAME, k.REFERENCED_COLUMN_NAME \nFROM information_schema.TABLE_CONSTRAINTS i \nLEFT JOIN information_schema.KEY_COLUMN_USAGE k ON i.CONSTRAINT_NAME = k.CONSTRAINT_NAME \nWHERE i.CONSTRAINT_TYPE = 'FOREIGN KEY' \nAND i.TABLE_SCHEMA = DATABASE();\n</code></pre></li>\n<li><p>To see all the FKs in your database:</p>\n\n<pre><code>SELECT i.TABLE_SCHEMA, i.TABLE_NAME, i.CONSTRAINT_TYPE, i.CONSTRAINT_NAME, k.REFERENCED_TABLE_NAME, k.REFERENCED_COLUMN_NAME \nFROM information_schema.TABLE_CONSTRAINTS i \nLEFT JOIN information_schema.KEY_COLUMN_USAGE k ON i.CONSTRAINT_NAME = k.CONSTRAINT_NAME \nWHERE i.CONSTRAINT_TYPE = 'FOREIGN KEY';\n</code></pre></li>\n</ol>\n\n<p><strong>Remember!</strong></p>\n\n<p>This is using the InnoDB storage engine. If you can't seem to get any foreign keys to show up after adding them it's probably because your tables are using MyISAM. </p>\n\n<p>To check:</p>\n\n<pre><code>SELECT * TABLE_NAME, ENGINE FROM information_schema.TABLES WHERE TABLE_SCHEMA = '<yourschema>';\n</code></pre>\n\n<p>To fix, use this:</p>\n\n<pre><code>ALTER TABLE `<yourtable>` ENGINE=InnoDB;\n</code></pre>\n"
},
{
"answer_id": 17049173,
"author": "CenterOrbit",
"author_id": 663058,
"author_profile": "https://Stackoverflow.com/users/663058",
"pm_score": 8,
"selected": false,
"text": "<p>EDIT: As pointed out in the comments, this is not the correct answer to the OPs question, but it is useful to know this command. This question showed up in Google for what I was looking for, and figured I'd leave this answer for the others to find.</p>\n\n<pre><code>SHOW CREATE TABLE `<yourtable>`;\n</code></pre>\n\n<p>I found this answer here:\n<a href=\"https://stackoverflow.com/questions/4004205/mysql-show-constraints-on-tables-command\">MySQL : show constraints on tables command</a></p>\n\n<p>I needed this way because I wanted to see how the FK functioned, rather than just see if it existed or not.</p>\n"
},
{
"answer_id": 17078317,
"author": "Daniel Rodas",
"author_id": 1609645,
"author_profile": "https://Stackoverflow.com/users/1609645",
"pm_score": 3,
"selected": false,
"text": "<p>A quick way to list your FKs (Foreign Key references) using the </p>\n\n<pre><code>KEY_COLUMN_USAGE view:\n\nSELECT CONCAT( table_name, '.',\ncolumn_name, ' -> ',\nreferenced_table_name, '.',\nreferenced_column_name ) AS list_of_fks\nFROM information_schema.KEY_COLUMN_USAGE\nWHERE REFERENCED_TABLE_SCHEMA = (your schema name here)\nAND REFERENCED_TABLE_NAME is not null\nORDER BY TABLE_NAME, COLUMN_NAME;\n</code></pre>\n\n<p>This query does assume that the constraints and all referenced and referencing tables are in the same schema.</p>\n\n<p>Add your own comment.</p>\n\n<p>Source: the official mysql manual.</p>\n"
},
{
"answer_id": 18825955,
"author": "Panayotis",
"author_id": 339146,
"author_profile": "https://Stackoverflow.com/users/339146",
"pm_score": 4,
"selected": false,
"text": "<p>This solution will not only display all relations but also the constraint name, which is required in some cases (e.g. drop contraint):</p>\n\n<pre><code>select\n concat(table_name, '.', column_name) as 'foreign key',\n concat(referenced_table_name, '.', referenced_column_name) as 'references',\n constraint_name as 'constraint name'\nfrom\n information_schema.key_column_usage\nwhere\n referenced_table_name is not null;\n</code></pre>\n\n<p>If you want to check tables in a specific database, at the end of the query add the schema name:</p>\n\n<pre><code>select\n concat(table_name, '.', column_name) as 'foreign key',\n concat(referenced_table_name, '.', referenced_column_name) as 'references',\n constraint_name as 'constraint name'\nfrom\n information_schema.key_column_usage\nwhere\n referenced_table_name is not null\n and table_schema = 'database_name';\n</code></pre>\n\n<p>Likewise, for a specific column name, add</p>\n\n<blockquote>\n <p>and table_name = 'table_name</p>\n</blockquote>\n\n<p>at the end of the query.</p>\n\n<p>Inspired by this post <a href=\"http://www.binarytides.com/list-foreign-keys-in-mysql/\" rel=\"noreferrer\">here</a></p>\n"
},
{
"answer_id": 20543002,
"author": "ChrisV",
"author_id": 342943,
"author_profile": "https://Stackoverflow.com/users/342943",
"pm_score": 5,
"selected": false,
"text": "<p>As an alternative to Node’s answer, if you use InnoDB and defined FK’s you could query the information_schema database e.g.:</p>\n\n<pre><code>SELECT CONSTRAINT_NAME, TABLE_NAME, REFERENCED_TABLE_NAME\nFROM information_schema.REFERENTIAL_CONSTRAINTS\nWHERE CONSTRAINT_SCHEMA = '<schema>'\nAND TABLE_NAME = '<table>'\n</code></pre>\n\n<p>for foreign keys from <table>, or</p>\n\n<pre><code>SELECT CONSTRAINT_NAME, TABLE_NAME, REFERENCED_TABLE_NAME\nFROM information_schema.REFERENTIAL_CONSTRAINTS\nWHERE CONSTRAINT_SCHEMA = '<schema>'\nAND REFERENCED_TABLE_NAME = '<table>'\n</code></pre>\n\n<p>for foreign keys to <table></p>\n\n<p>You can also get the UPDATE_RULE and DELETE_RULE if you want them.</p>\n"
},
{
"answer_id": 27476989,
"author": "Anthony Vipond",
"author_id": 1002324,
"author_profile": "https://Stackoverflow.com/users/1002324",
"pm_score": 1,
"selected": false,
"text": "<p>To find all tables <strong>containing a particular foreign key</strong> such as <code>employee_id</code></p>\n\n<pre><code>SELECT DISTINCT TABLE_NAME \nFROM INFORMATION_SCHEMA.COLUMNS\nWHERE COLUMN_NAME IN ('employee_id')\nAND TABLE_SCHEMA='table_name';\n</code></pre>\n"
},
{
"answer_id": 28356242,
"author": "Hazok",
"author_id": 644035,
"author_profile": "https://Stackoverflow.com/users/644035",
"pm_score": 3,
"selected": false,
"text": "<p>Using REFERENCED_TABLE_NAME does not always work and can be a NULL value. The following query can work instead:</p>\n\n<pre><code>select * from INFORMATION_SCHEMA.KEY_COLUMN_USAGE where TABLE_NAME = '<table>';\n</code></pre>\n"
},
{
"answer_id": 45598345,
"author": "omarjebari",
"author_id": 2867894,
"author_profile": "https://Stackoverflow.com/users/2867894",
"pm_score": 2,
"selected": false,
"text": "<p>If you also want to get the name of the foreign key column:</p>\n\n<pre><code>SELECT i.TABLE_SCHEMA, i.TABLE_NAME, \n i.CONSTRAINT_TYPE, i.CONSTRAINT_NAME, \n k.COLUMN_NAME, k.REFERENCED_TABLE_NAME, k.REFERENCED_COLUMN_NAME \n FROM information_schema.TABLE_CONSTRAINTS i \n LEFT JOIN information_schema.KEY_COLUMN_USAGE k \n ON i.CONSTRAINT_NAME = k.CONSTRAINT_NAME \n WHERE i.TABLE_SCHEMA = '<TABLE_NAME>' AND i.CONSTRAINT_TYPE = 'FOREIGN KEY' \n ORDER BY i.TABLE_NAME;\n</code></pre>\n"
},
{
"answer_id": 63050074,
"author": "DJDave",
"author_id": 1280840,
"author_profile": "https://Stackoverflow.com/users/1280840",
"pm_score": 3,
"selected": false,
"text": "<p>I'm reluctant to add yet another answer, but I've had to beg, borrow and steal from the others to get what I want, which is a complete list of all the FK relationships on tables in a given schema, INCLUDING FKs to tables in other schemas. The two crucial recordsets are information_schema.KEY_COLUMN_USAGE and information_schema.referential_constraints. If an attribute you want is missing, just uncomment the KCU.<em>, RC.</em> to see what's available</p>\n<pre><code>SELECT DISTINCT KCU.TABLE_NAME, KCU.COLUMN_NAME, REFERENCED_TABLE_SCHEMA, KCU.REFERENCED_TABLE_NAME, KCU.REFERENCED_COLUMN_NAME, UPDATE_RULE, DELETE_RULE #, KCU.*, RC.*\nFROM information_schema.KEY_COLUMN_USAGE KCU\nINNER JOIN information_schema.referential_constraints RC ON KCU.CONSTRAINT_NAME = RC.CONSTRAINT_NAME\nWHERE TABLE_SCHEMA = (your schema name)\nAND KCU.REFERENCED_TABLE_NAME IS NOT NULL\nORDER BY KCU.TABLE_NAME, KCU.COLUMN_NAME;\n</code></pre>\n"
},
{
"answer_id": 63376922,
"author": "imatwork",
"author_id": 13013884,
"author_profile": "https://Stackoverflow.com/users/13013884",
"pm_score": 4,
"selected": false,
"text": "<p>Constraints in SQL are the rules defined for the data in a table. Constraints also limit the types of data that go into the table. If new data does not abide by these rules the action is aborted.</p>\n<pre><code>select * from INFORMATION_SCHEMA.TABLE_CONSTRAINTS where CONSTRAINT_TYPE = 'FOREIGN KEY';\n</code></pre>\n<p>You can view all constraints by using <code>select * from information_schema.table_constraints;</code></p>\n<p>(This will produce a lot of table data).</p>\n<p>You can also use this for MySQL:</p>\n<pre><code>show create table tableName;\n</code></pre>\n"
},
{
"answer_id": 67779853,
"author": "akinuri",
"author_id": 2202732,
"author_profile": "https://Stackoverflow.com/users/2202732",
"pm_score": 1,
"selected": false,
"text": "<p>I needed a bird's-eye-view on the relationships among the tables (to use in an ORM). Using the suggestions from this page, and after experimenting, I've put together the following query:</p>\n<pre class=\"lang-sql prettyprint-override\"><code>SELECT\n KCU.CONSTRAINT_NAME,\n KCU.TABLE_NAME,\n KCU.COLUMN_NAME,\n KCU.REFERENCED_TABLE_NAME,\n KCU.REFERENCED_COLUMN_NAME\nFROM\n INFORMATION_SCHEMA.KEY_COLUMN_USAGE AS KCU\n JOIN INFORMATION_SCHEMA.COLUMNS AS COLS\n ON\n COLS.TABLE_SCHEMA = KCU.TABLE_SCHEMA\n AND COLS.TABLE_NAME = KCU.TABLE_NAME\n AND COLS.COLUMN_NAME = KCU.COLUMN_NAME\nWHERE\n KCU.CONSTRAINT_SCHEMA = {YOUR_SCHEMA_NAME}\n AND KCU.REFERENCED_TABLE_NAME IS NOT NULL\nORDER BY\n KCU.TABLE_NAME,\n COLS.ORDINAL_POSITION\n</code></pre>\n<p>It returns just what I need, and in the order that I want.</p>\n<p>I also do little processing on the result (turn it into a some kind of dictionary), so that it's ready to be used for creating an aggregate.</p>\n"
},
{
"answer_id": 71882817,
"author": "John Muraguri",
"author_id": 2742117,
"author_profile": "https://Stackoverflow.com/users/2742117",
"pm_score": 2,
"selected": false,
"text": "<p>It's often helpful to know the update and delete behaviour, which the other answers don't provide. So here goes.</p>\n<pre class=\"lang-sql prettyprint-override\"><code>SELECT cu.table_name,\n cu.column_name,\n cu.constraint_name,\n cu.referenced_table_name,\n cu.referenced_column_name,\n IF(rc.update_rule = 'NO ACTION', 'RESTRICT', rc.update_rule) AS update_rule,-- See: https://stackoverflow.com/a/1498015/2742117\n IF(rc.delete_rule = 'NO ACTION', 'RESTRICT', rc.delete_rule) AS delete_rule -- See: https://stackoverflow.com/a/1498015/2742117\nFROM information_schema.key_column_usage cu\nINNER JOIN information_schema.referential_constraints rc ON rc.constraint_schema = cu.table_schema\nAND rc.table_name = cu.table_name\nAND rc.constraint_name = cu.constraint_name\nWHERE cu.referenced_table_schema = '<your schema>'\n AND cu.referenced_table_name = '<your table>';\n</code></pre>\n"
},
{
"answer_id": 72682357,
"author": "M Shafaei N",
"author_id": 11583351,
"author_profile": "https://Stackoverflow.com/users/11583351",
"pm_score": 1,
"selected": false,
"text": "<p>I had a "myprodb" MySql database and for checking all foreign keys in this data base I used the following simple command.</p>\n<pre><code>select * from INFORMATION_SCHEMA.TABLE_CONSTRAINTS where CONSTRAINT_SCHEMA = 'myprodb' AND CONSTRAINT_TYPE = 'FOREIGN KEY';\n</code></pre>\n<p>I hope it help.</p>\n"
}
] |
2008/10/14
|
[
"https://Stackoverflow.com/questions/201621",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3757/"
] |
In MySQL, how do I get a list of all foreign key constraints pointing to a particular table? a particular column? This is the same thing as [this Oracle question](https://stackoverflow.com/questions/85978/query-a-tables-foreign-key-relationships), but for MySQL.
|
**For a Table:**
```
SELECT
TABLE_NAME,COLUMN_NAME,CONSTRAINT_NAME, REFERENCED_TABLE_NAME,REFERENCED_COLUMN_NAME
FROM
INFORMATION_SCHEMA.KEY_COLUMN_USAGE
WHERE
REFERENCED_TABLE_SCHEMA = '<database>' AND
REFERENCED_TABLE_NAME = '<table>';
```
**For a Column:**
```
SELECT
TABLE_NAME,COLUMN_NAME,CONSTRAINT_NAME, REFERENCED_TABLE_NAME,REFERENCED_COLUMN_NAME
FROM
INFORMATION_SCHEMA.KEY_COLUMN_USAGE
WHERE
REFERENCED_TABLE_SCHEMA = '<database>' AND
REFERENCED_TABLE_NAME = '<table>' AND
REFERENCED_COLUMN_NAME = '<column>';
```
Basically, we changed REFERENCED\_TABLE\_NAME with REFERENCED\_COLUMN\_NAME in the where clause.
|
201,636 |
<p>We are using Linq To SQL with our own data context logic that executes the one linq query across multiple databases. When we get the results back, we need the database for each of the rows. So...</p>
<p>I want to have a property on my class that will return the database name (SQL Server, so DB_NAME()). How can I do this in Linq To Sql?</p>
<p><strong>NOTE: We have hundreds of databases and do not want to put views in each db. The return should come back as just another property on each row of the return result set.</strong></p>
|
[
{
"answer_id": 231477,
"author": "gfrizzle",
"author_id": 23935,
"author_profile": "https://Stackoverflow.com/users/23935",
"pm_score": 0,
"selected": false,
"text": "<p>How are you iterating through the different databases? Could you just include information from the context in the query? For example:</p>\n\n<pre><code>Dim results = _\n From x In myContext.MyTables _\n Select x, info = myContext.Connection.ConnectionString\n</code></pre>\n"
},
{
"answer_id": 231817,
"author": "Mark Cidade",
"author_id": 1659,
"author_profile": "https://Stackoverflow.com/users/1659",
"pm_score": 3,
"selected": true,
"text": "<p>In the DBML XML file, you can set the Expression attribute of a Column element to this:</p>\n\n<pre><code> <Column Name=\"Table1.DBName\" \n DbType=\"nvarahcar(128)\" \n Type=\"System.String\" \n Expression=\"DB_NAME()\" />\n</code></pre>\n"
}
] |
2008/10/14
|
[
"https://Stackoverflow.com/questions/201636",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5189/"
] |
We are using Linq To SQL with our own data context logic that executes the one linq query across multiple databases. When we get the results back, we need the database for each of the rows. So...
I want to have a property on my class that will return the database name (SQL Server, so DB\_NAME()). How can I do this in Linq To Sql?
**NOTE: We have hundreds of databases and do not want to put views in each db. The return should come back as just another property on each row of the return result set.**
|
In the DBML XML file, you can set the Expression attribute of a Column element to this:
```
<Column Name="Table1.DBName"
DbType="nvarahcar(128)"
Type="System.String"
Expression="DB_NAME()" />
```
|
201,660 |
<p>I have some code which returns InnerXML for a XMLNode.</p>
<p>The node can contain just some text (with HTML) or XML.</p>
<p>For example:</p>
<pre><code><XMLNode>
Here is some &lt;strong&gt;HTML&lt;/strong&gt;
<XMLNode>
</code></pre>
<p>or</p>
<pre><code><XMLNode>
<XMLContent>Here is some content</XMLContnet>
</XMLNode>
</code></pre>
<p>if I get the InnerXML for <code><XmlNode></code> the HTML tags are returned as XML entities.</p>
<p>I cannot use InnerText because I need to be able to get the XML contents. So all I really need is a way to un-escape the HTML tags, because I can detect if it's XML or not and act accordingly.</p>
<p>I guess I could use HTMLDecode, but will this decode all the XML encoded entities?</p>
<p><strong>Update:</strong> I guess I'm rambling a bit above so here is a clarified scenario:</p>
<p>I have a XML document that looks like this:</p>
<pre><code><content id="1">
<data>&lt;p&gt;A Test&lt;/p&gt;</data>
</content id="2">
<content>
<data>
<dataitem>A test</dataitem>
</data>
</content>
</code></pre>
<p>If I do:</p>
<pre><code>XmlNode xn1 = document.SelectSingleNode("/content[@id=1]/data");
XmlNode xn2 = document.SelectSingleNode("/content[@id=2]/data");
Console.WriteLine(xn1.InnerXml);
Console.WriteLine(xn2.InnerXml);
</code></pre>
<p>xn1 will return </p>
<pre><code> &lt;p&gt;A Test&lt;/p&gt;
</code></pre>
<p>xn2 will return <code><dataitem>A test</dataitem></code></p>
<p>I am already checking to see if what is returned is XML (in the case of xn2) so all I need to do is un-escape the <code>&lt;</code> etc in xn1.</p>
<p>HTMLDecode does this, but I'm not sure it would work for everything. So the question remains would HTMLDecode handle all the possible entities or is there a class somewhere that will do it for me.</p>
|
[
{
"answer_id": 201672,
"author": "Joachim Kerschbaumer",
"author_id": 20227,
"author_profile": "https://Stackoverflow.com/users/20227",
"pm_score": 2,
"selected": false,
"text": "<p>why not inserting them as &lt; and &gt; ? you avoid mixing xml and custom markup stuff with this...</p>\n"
},
{
"answer_id": 201790,
"author": "Tomalak",
"author_id": 18771,
"author_profile": "https://Stackoverflow.com/users/18771",
"pm_score": 2,
"selected": false,
"text": "<p>Your question is a bit hard to follow. Here are the things that I did not fully understand:</p>\n\n<ol>\n<li>If you are using XmlNode/XmlElement objects, you are working with XML, not HTML. So all you can have are XML elements. These may have HTML element names, but they <em>are</em> XML.</li>\n<li>InnerXml returns a string, at least for the XmlElement object. What are you working with?</li>\n<li>What data are you expecting to get out of the operation? Can you give an example on what you need?</li>\n<li>What exactly are you intending to do with the data when you have it? Maybe there is a better way to your goal than what have in mind?</li>\n</ol>\n\n<hr>\n\n<p><strong>EDIT</strong></p>\n\n<p>I think I get the picture, but correct me if I'm still wrong. You want to pluck <code>\"<p>A Test</p>\"</code> out of <code>xn1</code>, but <code>\"A test\"</code> out of <code>xn2</code>. </p>\n\n<p>So <code>InnerXml</code> is the way to go for <code>xn1</code>, and <code>InnerText</code> would be right for <code>xn2</code>.</p>\n\n<p>Well do it that way then - test for the existence of <code>dataitem</code> and decide what to do when you know.</p>\n\n<pre><code>XmlNode xn = document.SelectSingleNode(\"/content[@id=1]/data\");\n\nif (xn.SelectSingleNode(\"dataitem\") == null)\n Console.WriteLine(xn.InnerXml);\nelse\n Console.WriteLine(xn.InnerText);\n</code></pre>\n\n<p>To answer your question regarding <code>HttpUtility.HtmlDecode</code>, I just looked at the implementation and it looks like it would \"work for everything\", but it seems superfluous to me if the string you are looking for is coming out of <code>InnerXml</code>.</p>\n"
},
{
"answer_id": 205962,
"author": "Robert Rossney",
"author_id": 19403,
"author_profile": "https://Stackoverflow.com/users/19403",
"pm_score": 2,
"selected": true,
"text": "<p>I think Tomalak is on the right track, but I'd write the code a little differently:</p>\n\n<pre><code> XmlNode xn = document.SelectSingleNode(\"/content[@id=1]/data\");\n if (xn.ChildNodes.Count != 1)\n {\n throw new InvalidOperationException(\"I don't know what to do if there's not exactly one child node.\");\n }\n XmlNode child = xn.ChildNodes[0];\n switch (child.NodeType)\n {\n case XmlNodeType.Element:\n Console.WriteLine(xn.InnerXml);\n break;\n case XmlNodeType.Text:\n Console.WriteLine(xn.Value);\n break;\n default:\n throw new InvalidOperationException(\"I can only handle elements and text nodes.\");\n }\n</code></pre>\n\n<p>This code makes a lot of your implicit assumptions explicit, and when you encounter data that's not in the form you expect, it will tell you why it failed.</p>\n"
}
] |
2008/10/14
|
[
"https://Stackoverflow.com/questions/201660",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1970/"
] |
I have some code which returns InnerXML for a XMLNode.
The node can contain just some text (with HTML) or XML.
For example:
```
<XMLNode>
Here is some <strong>HTML</strong>
<XMLNode>
```
or
```
<XMLNode>
<XMLContent>Here is some content</XMLContnet>
</XMLNode>
```
if I get the InnerXML for `<XmlNode>` the HTML tags are returned as XML entities.
I cannot use InnerText because I need to be able to get the XML contents. So all I really need is a way to un-escape the HTML tags, because I can detect if it's XML or not and act accordingly.
I guess I could use HTMLDecode, but will this decode all the XML encoded entities?
**Update:** I guess I'm rambling a bit above so here is a clarified scenario:
I have a XML document that looks like this:
```
<content id="1">
<data><p>A Test</p></data>
</content id="2">
<content>
<data>
<dataitem>A test</dataitem>
</data>
</content>
```
If I do:
```
XmlNode xn1 = document.SelectSingleNode("/content[@id=1]/data");
XmlNode xn2 = document.SelectSingleNode("/content[@id=2]/data");
Console.WriteLine(xn1.InnerXml);
Console.WriteLine(xn2.InnerXml);
```
xn1 will return
```
<p>A Test</p>
```
xn2 will return `<dataitem>A test</dataitem>`
I am already checking to see if what is returned is XML (in the case of xn2) so all I need to do is un-escape the `<` etc in xn1.
HTMLDecode does this, but I'm not sure it would work for everything. So the question remains would HTMLDecode handle all the possible entities or is there a class somewhere that will do it for me.
|
I think Tomalak is on the right track, but I'd write the code a little differently:
```
XmlNode xn = document.SelectSingleNode("/content[@id=1]/data");
if (xn.ChildNodes.Count != 1)
{
throw new InvalidOperationException("I don't know what to do if there's not exactly one child node.");
}
XmlNode child = xn.ChildNodes[0];
switch (child.NodeType)
{
case XmlNodeType.Element:
Console.WriteLine(xn.InnerXml);
break;
case XmlNodeType.Text:
Console.WriteLine(xn.Value);
break;
default:
throw new InvalidOperationException("I can only handle elements and text nodes.");
}
```
This code makes a lot of your implicit assumptions explicit, and when you encounter data that's not in the form you expect, it will tell you why it failed.
|
201,671 |
<p>When I refer to nested set model I mean what is described <a href="http://mikehillyer.com/articles/managing-hierarchical-data-in-mysql/" rel="nofollow noreferrer">here.</a></p>
<p>I need to build a new system for storing "categories" (I can't think of better word for it) in a user defined hierarchy. Since the nested set model is optimized for reads instead of writes, I decided to use that. Unfortunately during my research and testing of nested sets, I ran into the problem of how do I display the hierarchical tree with sorted nodes. For example if I have the hierarchy:</p>
<pre><code>root
finances
budgeting
fy08
projects
research
fabrication
release
trash
</code></pre>
<p>I want that to be sorted so that it displays as:</p>
<pre><code>root
finances
budgeting
fy08
projects
fabrication
release
research
trash
</code></pre>
<p>Notice that the fabrication appears before research.</p>
<p>Anyway, after a long search I saw answer such as "store the tree in a multi-dimensional array and sort it" and "resort the tree and serialized back into your nested set model" (I'm paraphrazing...). Either way, the first solution is a horrible waste of RAM and CPU, which are both very finite resources... The second solution just looks like a lot of painful code.</p>
<p>Regardless, I was able to figure out how to (using the nested set model):</p>
<ol>
<li>Start a new tree in SQL</li>
<li>Insert a node as a child of another node in tree</li>
<li>Insert a node after a sibling node in the tree</li>
<li>Pull the entire tree with the hierarchy structure from SQL</li>
<li>Pull a subtree from a specific node (including root) in the hierarchy with or without a depth limit</li>
<li>Find the parent of any node in the tree</li>
</ol>
<p>So I figured #5 and #6 could be used to do the sorting I wanted, and it could also be used to rebuild the tree in sorted order as well.</p>
<p>However, now that I've looked at all of these things I've learned to do I see that #3, #5, and #6 could be used together to perform sorted inserts. If I did sorted inserts it always be sorted. However, if I ever change the sort criteria or I want a different sort order I'm back to square one.</p>
<p>Could this just be the limitation of the nested set model? Does its use inhibit in query sorting of the output?</p>
|
[
{
"answer_id": 202735,
"author": "Simon Lehmann",
"author_id": 27011,
"author_profile": "https://Stackoverflow.com/users/27011",
"pm_score": 3,
"selected": false,
"text": "<p>I think this is indeed a limitation of the nested set model. You can not easily sort the child nodes within their respective parent node, because the ordering of the result set is essential to reconstruct the tree structure.</p>\n\n<p>I think it is probably the best approach to keep the tree sorted when inserting, updating or deleting nodes. This even makes queries very fast, which is one of the main goals of this data structure. If you implement stored procedures for all operations, it is very easy to use.</p>\n\n<p>You can also reverse the sort order of a presorted tree. You just have to use <code>ORDER BY node.rgt DESC</code> instead of <code>ORDER BY node.lft ASC</code>.</p>\n\n<p>If you really need to support another sort criteria, you could possible implement it by adding a second <code>lft</code> and <code>rgt</code> index to each node and keep this sorted by the other criteria on every insert/update/delete.</p>\n"
},
{
"answer_id": 204442,
"author": "Bell",
"author_id": 28158,
"author_profile": "https://Stackoverflow.com/users/28158",
"pm_score": 1,
"selected": false,
"text": "<p>Yes it is a limitation of the nested set model, since nested sets are a pre-ordered representation of a hierarchy. This pre-ordering is the reason that it's so quick for reads.\nThe adjacency model, also described on the page you link to, provides for the most flexible sorting and filtering but with a significant performance impact.</p>\n\n<p>My preferred approach for inserts and moves in a nested set is to handle the affected branch as in the adjacency model: Get a list of the new siblings; find the right place in the list for the new node; and construct the required update statements (that being the bit where you really have to be careful). As for changing your ordering criteria: It's a one off batch job, so you can afford to blow some RAM and CPU on it, the most flexible answer would be to break the nested set representation down into an adjacency representation and rebuild the nested set from the adjacency based on new criteria.</p>\n"
},
{
"answer_id": 457424,
"author": "Justin Wignall",
"author_id": 42774,
"author_profile": "https://Stackoverflow.com/users/42774",
"pm_score": 2,
"selected": false,
"text": "<p>I have just finished writing the following which works for me in sorting an entire nested set tree. </p>\n\n<p>The sort (ideally) requires a view that lists the current level of each node in the tree and a procedure for swapping two nodes - both are included below, the sibling swap code comes from Joe Celkos ' Tree & Hierarchies' book which I strongly recommend to anyone using nested sets.</p>\n\n<p>The sort can be altered in the 'INSERT INTO @t' statement, here it is a simple alphanumeric sort on 'Name'</p>\n\n<p>This may be a poor way of doing it especially using the cursor for set based code but as I say it works for me, hope it helps.</p>\n\n<p><strong>UPDATE:</strong></p>\n\n<p>Code below now shows version without using cusor. I see about 10x speed improvements</p>\n\n<pre><code>CREATE VIEW dbo.tree_view\n\nAS\n\nSELECT t2.NodeID,t2.lft,t2.rgt ,t2.Name, COUNT(t1.NodeID) AS level \nFROM dbo.tree t1,dbo.tree t2\nWHERE t2.lft BETWEEN t1.lft AND t1.rgt\nGROUP BY t2.NodeID,t2.lft,t2.rgt,t2.Name\n\nGO\n\n----------------------------------------------\n\n DECLARE @CurrentNodeID int\nDECLARE @CurrentActualOrder int\nDECLARE @CurrentRequiredOrder int\nDECLARE @DestinationNodeID int\nDECLARE @i0 int\nDECLARE @i1 int\nDECLARE @i2 int\nDECLARE @i3 int\n\nDECLARE @t TABLE (TopLft int,NodeID int NOT NULL,lft int NOT NULL,rgt int NOT NULL,Name varchar(50),RequiredOrder int NOT NULL,ActualOrder int NOT NULL)\n\n\nINSERT INTO @t (toplft,NodeID,lft,rgt,Name,RequiredOrder,ActualOrder)\n SELECT tv2.lft,tv1.NodeID,tv1.lft,tv1.rgt,tv1.Name,ROW_NUMBER() OVER(PARTITION BY tv2.lft ORDER BY tv1.ColumnToSort),ROW_NUMBER() OVER(PARTITION BY tv2.lft ORDER BY tv1.lft ASC)\n FROM dbo.tree_view tv1 \n LEFT OUTER JOIN dbo.tree_view tv2 ON tv1.lft > tv2.lft and tv1.lft < tv2.rgt and tv1.level = tv2.level+1\n WHERE tv2.rgt > tv2.lft+1\n\n DELETE FROM @t where ActualOrder = RequiredOrder\n\n\nWHILE EXISTS(SELECT * FROM @t WHERE ActualOrder <> RequiredOrder)\nBEGIN\n\n\n SELECT Top 1 @CurrentNodeID = NodeID,@CurrentActualOrder = ActualOrder,@CurrentRequiredOrder = RequiredOrder\n FROM @t \n WHERE ActualOrder <> RequiredOrder\n ORDER BY toplft,requiredorder\n\n SELECT @DestinationNodeID = NodeID\n FROM @t WHERE ActualOrder = @CurrentRequiredOrder AND TopLft = (SELECT TopLft FROM @t WHERE NodeID = @CurrentNodeID) \n\n SELECT @i0 = CASE WHEN c.lft < d.lft THEN c.lft ELSE d.lft END,\n @i1 = CASE WHEN c.lft < d.lft THEN c.rgt ELSE d.rgt END,\n @i2 = CASE WHEN c.lft < d.lft THEN d.lft ELSE c.lft END,\n @i3 = CASE WHEN c.lft < d.lft THEN d.rgt ELSE c.rgt END\n FROM dbo.tree c\n CROSS JOIN dbo.tree d\n WHERE c.NodeID = @CurrentNodeID AND d.NodeID = @DestinationNodeID\n\n UPDATE dbo.tree\n SET lft = CASE WHEN lft BETWEEN @i0 AND @i1 THEN @i3 + lft - @i1\n WHEN lft BETWEEN @i2 AND @i3 THEN @i0 + lft - @i2\n ELSE @i0 + @i3 + lft - @i1 - @i2\n END,\n rgt = CASE WHEN rgt BETWEEN @i0 AND @i1 THEN @i3 + rgt - @i1\n WHEN rgt BETWEEN @i2 AND @i3 THEN @i0 + rgt - @i2\n ELSE @i0 + @i3 + rgt - @i1 - @i2\n END\n WHERE lft BETWEEN @i0 AND @i3 \n AND @i0 < @i1\n AND @i1 < @i2\n AND @i2 < @i3\n\n UPDATE @t SET actualorder = @CurrentRequiredOrder where NodeID = @CurrentNodeID\n UPDATE @t SET actualorder = @CurrentActualOrder where NodeID = @DestinationNodeID\n\n DELETE FROM @t where ActualOrder = RequiredOrder\n\nEND\n</code></pre>\n"
},
{
"answer_id": 462019,
"author": "Hanno Fietz",
"author_id": 2077,
"author_profile": "https://Stackoverflow.com/users/2077",
"pm_score": 2,
"selected": false,
"text": "<p>I have used Nested Sets a lot and I have faced the same problem often. What I do, and what I would recommend, is to just not sort the items in the database. Instead, sort them in the user interface. After you pulled all the nodes from the DB, you likely have to convert them into some hierarchical data structure, anyway. In that structure, sort all the arrays containing the node's children.</p>\n\n<p>For example, if your frontend is a Flex app, and the children of a node are stored in an ICollectionView, you can use the sort property to have them display the way you want.</p>\n\n<p>Another example, if your frontend is some output from a PHP script, you could have the children of each node in an array and use PHP's array sorting functions to perform your sorting.</p>\n\n<p>Of course, this only works if you don't need the actual db entries to be sorted, but do you?</p>\n"
},
{
"answer_id": 2199228,
"author": "FrontierPsycho",
"author_id": 190833,
"author_profile": "https://Stackoverflow.com/users/190833",
"pm_score": 0,
"selected": false,
"text": "<p>I believe that, in your case, where the nodes you want to swap don't have any descendants, you can simply swap the lft and rgt values around. Consider this tree:</p>\n\n<pre><code> A\n / \\\nB C\n / \\\n D E\n</code></pre>\n\n<p>This could turn into this group of nested sets:</p>\n\n<pre><code>1 A 10 \n2 B 3 \n4 C 9\n5 D 6\n7 E 8\n</code></pre>\n\n<p>Now consider you want to swap D and E. The following nested sets are valid and D and E are swapped:</p>\n\n<pre><code>1 A 10\n2 B 3 \n4 C 9 \n7 D 8\n5 E 6 \n</code></pre>\n\n<p>Swapping nodes that have subtrees cannot be done this way, of course, because you would need to update the childrens' lft and rgt values as well. </p>\n"
},
{
"answer_id": 4143361,
"author": "Anton Orel",
"author_id": 368144,
"author_profile": "https://Stackoverflow.com/users/368144",
"pm_score": 0,
"selected": false,
"text": "<p>You can sort thier when you render. I explained rendering here <a href=\"https://stackoverflow.com/questions/1372366/how-to-render-all-records-from-a-nested-set-into-a-real-html-tree/3052506#3052506\">How to render all records from a nested set into a real html tree</a></p>\n"
},
{
"answer_id": 4751769,
"author": "Jeff Moden",
"author_id": 313265,
"author_profile": "https://Stackoverflow.com/users/313265",
"pm_score": -1,
"selected": false,
"text": "<p>Sorting Nested Sets has no limits and it's not difficult. Just sort by the LEFT bower (anchor, whatever) and it's done. If you have a LEVEL for each node, you can also pull-off correct indentation based on the Level.</p>\n"
},
{
"answer_id": 20448404,
"author": "pj.cz",
"author_id": 3078846,
"author_profile": "https://Stackoverflow.com/users/3078846",
"pm_score": 0,
"selected": false,
"text": "<p>See my simple solution from method of my class. $this->table->order is Nette framework code to get data from DB.</p>\n\n<pre><code>$tree = Array();\n$parents = Array();\n$nodes = $this->table->order('depth ASC, parent_id ASC, name ASC');\n$i = 0;\n$depth = 0;\n$parent_id = 0;\n\nforeach($nodes as $node) {\n if($depth < $node->depth || $parent_id < $node->parent_id) {\n $i = $parents[\"{$node->parent_id}\"] + 1;\n }\n $tree[$i] = $node;\n $parents[\"{$node->id}\"] = $i;\n $depth = $node->depth;\n $parent_id = $node->parent_id;\n $i += (($node->rgt - $node->lft - 1) / 2) + 1;\n}\nksort($tree);\n</code></pre>\n"
}
] |
2008/10/14
|
[
"https://Stackoverflow.com/questions/201671",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] |
When I refer to nested set model I mean what is described [here.](http://mikehillyer.com/articles/managing-hierarchical-data-in-mysql/)
I need to build a new system for storing "categories" (I can't think of better word for it) in a user defined hierarchy. Since the nested set model is optimized for reads instead of writes, I decided to use that. Unfortunately during my research and testing of nested sets, I ran into the problem of how do I display the hierarchical tree with sorted nodes. For example if I have the hierarchy:
```
root
finances
budgeting
fy08
projects
research
fabrication
release
trash
```
I want that to be sorted so that it displays as:
```
root
finances
budgeting
fy08
projects
fabrication
release
research
trash
```
Notice that the fabrication appears before research.
Anyway, after a long search I saw answer such as "store the tree in a multi-dimensional array and sort it" and "resort the tree and serialized back into your nested set model" (I'm paraphrazing...). Either way, the first solution is a horrible waste of RAM and CPU, which are both very finite resources... The second solution just looks like a lot of painful code.
Regardless, I was able to figure out how to (using the nested set model):
1. Start a new tree in SQL
2. Insert a node as a child of another node in tree
3. Insert a node after a sibling node in the tree
4. Pull the entire tree with the hierarchy structure from SQL
5. Pull a subtree from a specific node (including root) in the hierarchy with or without a depth limit
6. Find the parent of any node in the tree
So I figured #5 and #6 could be used to do the sorting I wanted, and it could also be used to rebuild the tree in sorted order as well.
However, now that I've looked at all of these things I've learned to do I see that #3, #5, and #6 could be used together to perform sorted inserts. If I did sorted inserts it always be sorted. However, if I ever change the sort criteria or I want a different sort order I'm back to square one.
Could this just be the limitation of the nested set model? Does its use inhibit in query sorting of the output?
|
I think this is indeed a limitation of the nested set model. You can not easily sort the child nodes within their respective parent node, because the ordering of the result set is essential to reconstruct the tree structure.
I think it is probably the best approach to keep the tree sorted when inserting, updating or deleting nodes. This even makes queries very fast, which is one of the main goals of this data structure. If you implement stored procedures for all operations, it is very easy to use.
You can also reverse the sort order of a presorted tree. You just have to use `ORDER BY node.rgt DESC` instead of `ORDER BY node.lft ASC`.
If you really need to support another sort criteria, you could possible implement it by adding a second `lft` and `rgt` index to each node and keep this sorted by the other criteria on every insert/update/delete.
|
201,686 |
<p>On large tables in MSSQL; selecting specific columns results in greater speed of the query. Does the same apply to Linq to SQL?</p>
<p>Would this:</p>
<pre><code>var person = from p in [DataContextObject].Persons
where p.PersonsID == 1
select new { p.PersonsID, p.PersonsAdress, p.PersonsZipcode };
</code></pre>
<p>be faster than this:</p>
<pre><code>var person = from p in [DataContextObject].Persons
where p.PersonsID == 1
select p;
</code></pre>
<p>... ?</p>
|
[
{
"answer_id": 201691,
"author": "Mitchel Sellers",
"author_id": 13279,
"author_profile": "https://Stackoverflow.com/users/13279",
"pm_score": 2,
"selected": false,
"text": "<p>If you are limiting the size of the result set by only selecting a few specific columns, then YES it will have an affect.</p>\n\n<p><strong>EDIT</strong> ading clarification from comment</p>\n\n<p>How is this better, it will reduce the size of the resultant data returned from SQL AND it will reduce the size of the objects used to store the results in memory.</p>\n\n<p>This is due to the fact that in the end LINQ to SQL generates SQL, so the same performance benefits exist.</p>\n"
},
{
"answer_id": 201695,
"author": "Christian C. Salvadó",
"author_id": 5445,
"author_profile": "https://Stackoverflow.com/users/5445",
"pm_score": 1,
"selected": false,
"text": "<p>I think the same applies, because LINQ to SQL translates the Linq query operations to SQL commands.</p>\n"
},
{
"answer_id": 201702,
"author": "Peter",
"author_id": 5189,
"author_profile": "https://Stackoverflow.com/users/5189",
"pm_score": 4,
"selected": true,
"text": "<p>I highly recommend <a href=\"http://linqpad.net/\" rel=\"nofollow noreferrer\">LinqPad</a>. It is free and lets you run LINQ queries dynamically. When you can also look at the SQL that is generated.</p>\n\n<p>What you will see is that the LINQ query will translate the first query into selecting only those columns. So it is faster.</p>\n"
},
{
"answer_id": 201708,
"author": "James Curran",
"author_id": 12725,
"author_profile": "https://Stackoverflow.com/users/12725",
"pm_score": 1,
"selected": false,
"text": "<p>Additionally to what the others have said, the new unnamed structure will be a much lighter-weight object than the Person object -- it would be much faster, even if you selected all the columns. (Person has method/fields etc to support writing the object back to the database. The unnamed type does not.)</p>\n"
},
{
"answer_id": 201797,
"author": "liggett78",
"author_id": 19762,
"author_profile": "https://Stackoverflow.com/users/19762",
"pm_score": 2,
"selected": false,
"text": "<p>There are 3 aspects with \"faster\" here.</p>\n\n<ol>\n<li>less data transmitted means\nfaster. On the other hand it will\nnot get that <em>significantly</em> faster,\nunless you select more than one row\nor if your Person contains some\nother \"heavy\" columns - long\nvarchars, image etc.</li>\n<li><p>as J. Curran pointed out, less\nmemory allocated means faster. Same remark as in 1. applies here.</p></li>\n<li><p>Your query executes faster if you\nhave an index containing all\nselected columns (or attached to it starting from SQL Server 2005). In this case the SQL Server engine does not need to load the page with the row in memory - if it's not there yet.</p></li>\n</ol>\n\n<p>Personally I wouldn't bother trying to optimize my queries this way (unless, as I said your rows contain binary data or very long strings that you don't need), partially because if you decide later that you'd like to have more information about this selected Person, you would need to change your DB access code vs. just accessing a property in your POCO/anonymous class.</p>\n"
},
{
"answer_id": 206377,
"author": "DamienG",
"author_id": 5720,
"author_profile": "https://Stackoverflow.com/users/5720",
"pm_score": 1,
"selected": false,
"text": "<p>If you have columns that are very large such as binaries and images then it can make a significant difference which is why LINQ to SQL allows you to specify delay loading for certain columns so that you can still select entire objects without performing 'select new' projections.</p>\n"
}
] |
2008/10/14
|
[
"https://Stackoverflow.com/questions/201686",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20946/"
] |
On large tables in MSSQL; selecting specific columns results in greater speed of the query. Does the same apply to Linq to SQL?
Would this:
```
var person = from p in [DataContextObject].Persons
where p.PersonsID == 1
select new { p.PersonsID, p.PersonsAdress, p.PersonsZipcode };
```
be faster than this:
```
var person = from p in [DataContextObject].Persons
where p.PersonsID == 1
select p;
```
... ?
|
I highly recommend [LinqPad](http://linqpad.net/). It is free and lets you run LINQ queries dynamically. When you can also look at the SQL that is generated.
What you will see is that the LINQ query will translate the first query into selecting only those columns. So it is faster.
|
201,699 |
<p>I have a Java applet that runs inside a forms-authenticated aspx page. In the .NET 1.1 version of my site, the applet has access to the session cookie and is able to retrieve a file from the server, but in the .NET 2.0 version it fails to authenticate.</p>
<p>I have seen a couple of forum posts elsewhere that state that 2.0 sets cookies to HttpOnly by default, but the solutions given haven't worked for me so far. I also read somewhere that 2.0 may be discriminating based on user-agent.</p>
<p>Does anyone have any experience or insight into this?</p>
|
[
{
"answer_id": 656465,
"author": "Aidan Black",
"author_id": 8211,
"author_profile": "https://Stackoverflow.com/users/8211",
"pm_score": 0,
"selected": false,
"text": "<p>Filip's answer isn't entirely correct. I ran a program to sniff the HTTP headers on my workstation, and the Java applet does in fact present the ASP.NET authentication ticket in some circumstances - just not reliably enough for my needs.</p>\n\n<p>Eventually I did find a solution to this, but it didn't entirely solve my problem. You can add an entry to the web.config in .NET 2.0: <code><httpCookies httpOnlyCookies=\"false\" /></code>; but this didn't work for all my users.</p>\n\n<p>The long term solution turned out to be modifying the Java applet so that it doesn't need to retrieve anything from the web server.</p>\n"
},
{
"answer_id": 4318115,
"author": "Dr. Dad",
"author_id": 525631,
"author_profile": "https://Stackoverflow.com/users/525631",
"pm_score": 1,
"selected": false,
"text": "<p>Filip is both correct and incorrect, at least wrt to Java and ASP.NET. An applet can get access to the ASP.NET session by cheating. In my case, we added the session id as a parameter to the applet, which the applet then adds as a cookie in it's requests. Seems to work ok. (We encrypted the session id to foil those nasty hacker folk!)</p>\n"
},
{
"answer_id": 7314616,
"author": "Trevor Lohrbeer",
"author_id": 929862,
"author_profile": "https://Stackoverflow.com/users/929862",
"pm_score": 4,
"selected": true,
"text": "<p>This question is old, but I figured it was valuable to have the correct answer here.</p>\n\n<p>Filip is confusing server-side Java with client-side Java. He is correct that you cannot share sessions between two server-side platforms, such as Java (J2EE) and ASP.Net without using a custom approach.</p>\n\n<p>However, applets are client-side and therefore should be able to access the session information of the host page. The issue is that ASP.Net 2.0 added the HttpOnly flag on session cookies. This flag prevents JavaScript and Java applets from accessing these cookies.</p>\n\n<p>The workaround is to turn off the HttpOnly flag on session cookies. While you may be able to do it in the configuration in newer versions of ASP.Net, in previous versions the solution was to add the following code to your Global.asax file:</p>\n\n<pre><code>protected void Application_EndRequest(object sender, EventArgs e)\n{\n /**\n * @note Remove the HttpOnly attribute from session cookies, otherwise the \n * Java applet won't have access to the session. This solution taken\n * from\n * http://blogs.msdn.com/jorman/archive/2006/03/05/session-loss-after-migrating-to-asp-net-2-0.aspx\n *\n * For more information on the HttpOnly attribute see:\n *\n * http://msdn.microsoft.com/netframework/programming/breakingchanges/runtime/aspnet.aspx\n * http://msdn2.microsoft.com/en-us/library/system.web.httpcookie.httponly.aspx\n */\n if (Response.Cookies.Count > 0)\n {\n foreach (string lName in Response.Cookies.AllKeys)\n {\n if (lName == FormsAuthentication.FormsCookieName || \n lName.ToLower() == \"asp.net_sessionid\")\n {\n Response.Cookies[lName].HttpOnly = false;\n }\n }\n }\n}\n</code></pre>\n\n<p>Note that even with this fix, not all browser/OS/Java combinations can access cookies. I'm currently researching an issue with session cookies not being accessible on Firefox 4.0.1 with Java 1.6.0_13 on Windows XP. </p>\n\n<p>The workaround is to use the approach Dr. Dad suggested, where the session ID gets passed to the applet as a parameter, and then either gets embedded into the request URL (requires URL sessions to be turned on in the server-side configuration) or sent as a manually-set cookie.</p>\n"
},
{
"answer_id": 10089532,
"author": "marcelo-ferraz",
"author_id": 141345,
"author_profile": "https://Stackoverflow.com/users/141345",
"pm_score": 0,
"selected": false,
"text": "<p>I am aware that it may be a very late answer, but I can give you a simpler solution:\n- usually, not always, applets make heavy use of html and javascript for their interfaces and interaction.\n- Javascript is run in the browser.\n- Ajax calls are made by the browser.\n- Ajax calls are asynchronous and can be integrated easily to an applets logic.</p>\n\n<p>One can find an elegant solution integrating Ajax calls to an applet's logic, delegating to the browser the security. </p>\n"
}
] |
2008/10/14
|
[
"https://Stackoverflow.com/questions/201699",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/8211/"
] |
I have a Java applet that runs inside a forms-authenticated aspx page. In the .NET 1.1 version of my site, the applet has access to the session cookie and is able to retrieve a file from the server, but in the .NET 2.0 version it fails to authenticate.
I have seen a couple of forum posts elsewhere that state that 2.0 sets cookies to HttpOnly by default, but the solutions given haven't worked for me so far. I also read somewhere that 2.0 may be discriminating based on user-agent.
Does anyone have any experience or insight into this?
|
This question is old, but I figured it was valuable to have the correct answer here.
Filip is confusing server-side Java with client-side Java. He is correct that you cannot share sessions between two server-side platforms, such as Java (J2EE) and ASP.Net without using a custom approach.
However, applets are client-side and therefore should be able to access the session information of the host page. The issue is that ASP.Net 2.0 added the HttpOnly flag on session cookies. This flag prevents JavaScript and Java applets from accessing these cookies.
The workaround is to turn off the HttpOnly flag on session cookies. While you may be able to do it in the configuration in newer versions of ASP.Net, in previous versions the solution was to add the following code to your Global.asax file:
```
protected void Application_EndRequest(object sender, EventArgs e)
{
/**
* @note Remove the HttpOnly attribute from session cookies, otherwise the
* Java applet won't have access to the session. This solution taken
* from
* http://blogs.msdn.com/jorman/archive/2006/03/05/session-loss-after-migrating-to-asp-net-2-0.aspx
*
* For more information on the HttpOnly attribute see:
*
* http://msdn.microsoft.com/netframework/programming/breakingchanges/runtime/aspnet.aspx
* http://msdn2.microsoft.com/en-us/library/system.web.httpcookie.httponly.aspx
*/
if (Response.Cookies.Count > 0)
{
foreach (string lName in Response.Cookies.AllKeys)
{
if (lName == FormsAuthentication.FormsCookieName ||
lName.ToLower() == "asp.net_sessionid")
{
Response.Cookies[lName].HttpOnly = false;
}
}
}
}
```
Note that even with this fix, not all browser/OS/Java combinations can access cookies. I'm currently researching an issue with session cookies not being accessible on Firefox 4.0.1 with Java 1.6.0\_13 on Windows XP.
The workaround is to use the approach Dr. Dad suggested, where the session ID gets passed to the applet as a parameter, and then either gets embedded into the request URL (requires URL sessions to be turned on in the server-side configuration) or sent as a manually-set cookie.
|
201,700 |
<p>I'm currently logging via the simplest of methods within my servlet using Tomcat. I use the ServletConfig.getServletContext().log to record activity. This writes to the localhost.YYYY-MM-DD.log in $TOMCAT_HOME/logs.</p>
<p>I don't want to get away from the simplicity of this logging mechanism unless absolutely necessary. But I would like to name my log file. Rather than "localhost".YYYY-MM-DD.log, is there a way to have it write to "myAppName".YYYY-MM-DD.log. I know I could create my own mechanism, but again, I looking for simplicity here.</p>
<p>I'm hoping to stay away from a complete framework like Log4j.</p>
|
[
{
"answer_id": 656465,
"author": "Aidan Black",
"author_id": 8211,
"author_profile": "https://Stackoverflow.com/users/8211",
"pm_score": 0,
"selected": false,
"text": "<p>Filip's answer isn't entirely correct. I ran a program to sniff the HTTP headers on my workstation, and the Java applet does in fact present the ASP.NET authentication ticket in some circumstances - just not reliably enough for my needs.</p>\n\n<p>Eventually I did find a solution to this, but it didn't entirely solve my problem. You can add an entry to the web.config in .NET 2.0: <code><httpCookies httpOnlyCookies=\"false\" /></code>; but this didn't work for all my users.</p>\n\n<p>The long term solution turned out to be modifying the Java applet so that it doesn't need to retrieve anything from the web server.</p>\n"
},
{
"answer_id": 4318115,
"author": "Dr. Dad",
"author_id": 525631,
"author_profile": "https://Stackoverflow.com/users/525631",
"pm_score": 1,
"selected": false,
"text": "<p>Filip is both correct and incorrect, at least wrt to Java and ASP.NET. An applet can get access to the ASP.NET session by cheating. In my case, we added the session id as a parameter to the applet, which the applet then adds as a cookie in it's requests. Seems to work ok. (We encrypted the session id to foil those nasty hacker folk!)</p>\n"
},
{
"answer_id": 7314616,
"author": "Trevor Lohrbeer",
"author_id": 929862,
"author_profile": "https://Stackoverflow.com/users/929862",
"pm_score": 4,
"selected": true,
"text": "<p>This question is old, but I figured it was valuable to have the correct answer here.</p>\n\n<p>Filip is confusing server-side Java with client-side Java. He is correct that you cannot share sessions between two server-side platforms, such as Java (J2EE) and ASP.Net without using a custom approach.</p>\n\n<p>However, applets are client-side and therefore should be able to access the session information of the host page. The issue is that ASP.Net 2.0 added the HttpOnly flag on session cookies. This flag prevents JavaScript and Java applets from accessing these cookies.</p>\n\n<p>The workaround is to turn off the HttpOnly flag on session cookies. While you may be able to do it in the configuration in newer versions of ASP.Net, in previous versions the solution was to add the following code to your Global.asax file:</p>\n\n<pre><code>protected void Application_EndRequest(object sender, EventArgs e)\n{\n /**\n * @note Remove the HttpOnly attribute from session cookies, otherwise the \n * Java applet won't have access to the session. This solution taken\n * from\n * http://blogs.msdn.com/jorman/archive/2006/03/05/session-loss-after-migrating-to-asp-net-2-0.aspx\n *\n * For more information on the HttpOnly attribute see:\n *\n * http://msdn.microsoft.com/netframework/programming/breakingchanges/runtime/aspnet.aspx\n * http://msdn2.microsoft.com/en-us/library/system.web.httpcookie.httponly.aspx\n */\n if (Response.Cookies.Count > 0)\n {\n foreach (string lName in Response.Cookies.AllKeys)\n {\n if (lName == FormsAuthentication.FormsCookieName || \n lName.ToLower() == \"asp.net_sessionid\")\n {\n Response.Cookies[lName].HttpOnly = false;\n }\n }\n }\n}\n</code></pre>\n\n<p>Note that even with this fix, not all browser/OS/Java combinations can access cookies. I'm currently researching an issue with session cookies not being accessible on Firefox 4.0.1 with Java 1.6.0_13 on Windows XP. </p>\n\n<p>The workaround is to use the approach Dr. Dad suggested, where the session ID gets passed to the applet as a parameter, and then either gets embedded into the request URL (requires URL sessions to be turned on in the server-side configuration) or sent as a manually-set cookie.</p>\n"
},
{
"answer_id": 10089532,
"author": "marcelo-ferraz",
"author_id": 141345,
"author_profile": "https://Stackoverflow.com/users/141345",
"pm_score": 0,
"selected": false,
"text": "<p>I am aware that it may be a very late answer, but I can give you a simpler solution:\n- usually, not always, applets make heavy use of html and javascript for their interfaces and interaction.\n- Javascript is run in the browser.\n- Ajax calls are made by the browser.\n- Ajax calls are asynchronous and can be integrated easily to an applets logic.</p>\n\n<p>One can find an elegant solution integrating Ajax calls to an applet's logic, delegating to the browser the security. </p>\n"
}
] |
2008/10/14
|
[
"https://Stackoverflow.com/questions/201700",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/13930/"
] |
I'm currently logging via the simplest of methods within my servlet using Tomcat. I use the ServletConfig.getServletContext().log to record activity. This writes to the localhost.YYYY-MM-DD.log in $TOMCAT\_HOME/logs.
I don't want to get away from the simplicity of this logging mechanism unless absolutely necessary. But I would like to name my log file. Rather than "localhost".YYYY-MM-DD.log, is there a way to have it write to "myAppName".YYYY-MM-DD.log. I know I could create my own mechanism, but again, I looking for simplicity here.
I'm hoping to stay away from a complete framework like Log4j.
|
This question is old, but I figured it was valuable to have the correct answer here.
Filip is confusing server-side Java with client-side Java. He is correct that you cannot share sessions between two server-side platforms, such as Java (J2EE) and ASP.Net without using a custom approach.
However, applets are client-side and therefore should be able to access the session information of the host page. The issue is that ASP.Net 2.0 added the HttpOnly flag on session cookies. This flag prevents JavaScript and Java applets from accessing these cookies.
The workaround is to turn off the HttpOnly flag on session cookies. While you may be able to do it in the configuration in newer versions of ASP.Net, in previous versions the solution was to add the following code to your Global.asax file:
```
protected void Application_EndRequest(object sender, EventArgs e)
{
/**
* @note Remove the HttpOnly attribute from session cookies, otherwise the
* Java applet won't have access to the session. This solution taken
* from
* http://blogs.msdn.com/jorman/archive/2006/03/05/session-loss-after-migrating-to-asp-net-2-0.aspx
*
* For more information on the HttpOnly attribute see:
*
* http://msdn.microsoft.com/netframework/programming/breakingchanges/runtime/aspnet.aspx
* http://msdn2.microsoft.com/en-us/library/system.web.httpcookie.httponly.aspx
*/
if (Response.Cookies.Count > 0)
{
foreach (string lName in Response.Cookies.AllKeys)
{
if (lName == FormsAuthentication.FormsCookieName ||
lName.ToLower() == "asp.net_sessionid")
{
Response.Cookies[lName].HttpOnly = false;
}
}
}
}
```
Note that even with this fix, not all browser/OS/Java combinations can access cookies. I'm currently researching an issue with session cookies not being accessible on Firefox 4.0.1 with Java 1.6.0\_13 on Windows XP.
The workaround is to use the approach Dr. Dad suggested, where the session ID gets passed to the applet as a parameter, and then either gets embedded into the request URL (requires URL sessions to be turned on in the server-side configuration) or sent as a manually-set cookie.
|
201,718 |
<p>How do I concatenate two <code>std::vector</code>s?</p>
|
[
{
"answer_id": 201727,
"author": "Tom Ritter",
"author_id": 8435,
"author_profile": "https://Stackoverflow.com/users/8435",
"pm_score": 8,
"selected": false,
"text": "<p>I would use the <a href=\"http://cppreference.com/wiki/stl/vector/insert\" rel=\"noreferrer\">insert function</a>, something like:</p>\n\n<pre><code>vector<int> a, b;\n//fill with data\nb.insert(b.end(), a.begin(), a.end());\n</code></pre>\n"
},
{
"answer_id": 201729,
"author": "Robert Gamble",
"author_id": 25222,
"author_profile": "https://Stackoverflow.com/users/25222",
"pm_score": 10,
"selected": false,
"text": "<pre><code>vector1.insert( vector1.end(), vector2.begin(), vector2.end() );\n</code></pre>\n"
},
{
"answer_id": 201731,
"author": "James Curran",
"author_id": 12725,
"author_profile": "https://Stackoverflow.com/users/12725",
"pm_score": 5,
"selected": false,
"text": "<pre><code>std::vector<int> first;\nstd::vector<int> second;\n\nfirst.insert(first.end(), second.begin(), second.end());\n</code></pre>\n"
},
{
"answer_id": 201859,
"author": "Roger Lipscombe",
"author_id": 8446,
"author_profile": "https://Stackoverflow.com/users/8446",
"pm_score": 7,
"selected": false,
"text": "<p>Or you could use:</p>\n<pre><code>std::copy(source.begin(), source.end(), std::back_inserter(destination));\n</code></pre>\n<p>This pattern is useful if the two vectors don't contain exactly the same type of thing, because you can use something instead of <code>std::back_inserter</code> to convert from one type to the other.</p>\n"
},
{
"answer_id": 21972296,
"author": "Alex",
"author_id": 2918069,
"author_profile": "https://Stackoverflow.com/users/2918069",
"pm_score": 8,
"selected": false,
"text": "<p>If you are using C++11, and wish to move the elements rather than merely copying them, you can use <a href=\"http://en.cppreference.com/w/cpp/iterator/move_iterator\" rel=\"noreferrer\"><code>std::move_iterator</code></a> along with insert (or copy):</p>\n\n<pre><code>#include <vector>\n#include <iostream>\n#include <iterator>\n\nint main(int argc, char** argv) {\n std::vector<int> dest{1,2,3,4,5};\n std::vector<int> src{6,7,8,9,10};\n\n // Move elements from src to dest.\n // src is left in undefined but safe-to-destruct state.\n dest.insert(\n dest.end(),\n std::make_move_iterator(src.begin()),\n std::make_move_iterator(src.end())\n );\n\n // Print out concatenated vector.\n std::copy(\n dest.begin(),\n dest.end(),\n std::ostream_iterator<int>(std::cout, \"\\n\")\n );\n\n return 0;\n}\n</code></pre>\n\n<p>This will not be more efficient for the example with ints, since moving them is no more efficient than copying them, but for a data structure with optimized moves, it can avoid copying unnecessary state:</p>\n\n<pre><code>#include <vector>\n#include <iostream>\n#include <iterator>\n\nint main(int argc, char** argv) {\n std::vector<std::vector<int>> dest{{1,2,3,4,5}, {3,4}};\n std::vector<std::vector<int>> src{{6,7,8,9,10}};\n\n // Move elements from src to dest.\n // src is left in undefined but safe-to-destruct state.\n dest.insert(\n dest.end(),\n std::make_move_iterator(src.begin()),\n std::make_move_iterator(src.end())\n );\n\n return 0;\n}\n</code></pre>\n\n<p>After the move, src's element is left in an undefined but safe-to-destruct state, and its former elements were transfered directly to dest's new element at the end.</p>\n"
},
{
"answer_id": 23489497,
"author": "AlexT",
"author_id": 834552,
"author_profile": "https://Stackoverflow.com/users/834552",
"pm_score": 3,
"selected": false,
"text": "<p>If you are interested in strong exception guarantee (when copy constructor can throw an exception):</p>\n\n<pre><code>template<typename T>\ninline void append_copy(std::vector<T>& v1, const std::vector<T>& v2)\n{\n const auto orig_v1_size = v1.size();\n v1.reserve(orig_v1_size + v2.size());\n try\n {\n v1.insert(v1.end(), v2.begin(), v2.end());\n }\n catch(...)\n {\n v1.erase(v1.begin() + orig_v1_size, v1.end());\n throw;\n }\n}\n</code></pre>\n\n<p>Similar <code>append_move</code> with strong guarantee can't be implemented in general if vector element's move constructor can throw (which is unlikely but still).</p>\n"
},
{
"answer_id": 30798014,
"author": "Deqing",
"author_id": 558892,
"author_profile": "https://Stackoverflow.com/users/558892",
"pm_score": 6,
"selected": false,
"text": "<p>With C++11, I'd prefer following to append vector b to a:</p>\n\n<pre><code>std::move(b.begin(), b.end(), std::back_inserter(a));\n</code></pre>\n\n<p>when <code>a</code> and <code>b</code> are not overlapped, and <code>b</code> is not going to be used anymore.</p>\n\n<hr>\n\n<p>This is <a href=\"https://en.cppreference.com/w/cpp/algorithm/move\" rel=\"noreferrer\"><code>std::move</code></a> from <code><algorithm></code>, not the <em>usual</em> <a href=\"https://en.cppreference.com/w/cpp/utility/move\" rel=\"noreferrer\"><code>std::move</code></a> from <code><utility></code>.</p>\n"
},
{
"answer_id": 33649647,
"author": "Stepan Yakovenko",
"author_id": 517073,
"author_profile": "https://Stackoverflow.com/users/517073",
"pm_score": 3,
"selected": false,
"text": "<p>Add this one to your header file:</p>\n\n<pre><code>template <typename T> vector<T> concat(vector<T> &a, vector<T> &b) {\n vector<T> ret = vector<T>();\n copy(a.begin(), a.end(), back_inserter(ret));\n copy(b.begin(), b.end(), back_inserter(ret));\n return ret;\n}\n</code></pre>\n\n<p>and use it this way:</p>\n\n<pre><code>vector<int> a = vector<int>();\nvector<int> b = vector<int>();\n\na.push_back(1);\na.push_back(2);\nb.push_back(62);\n\nvector<int> r = concat(a, b);\n</code></pre>\n\n<p>r will contain [1,2,62]</p>\n"
},
{
"answer_id": 35561577,
"author": "Jonathan Mee",
"author_id": 2642059,
"author_profile": "https://Stackoverflow.com/users/2642059",
"pm_score": 0,
"selected": false,
"text": "<p>If what you're looking for is a way to append a vector to another after creation, <a href=\"http://en.cppreference.com/w/cpp/container/vector/insert\" rel=\"nofollow noreferrer\"><code>vector::insert</code></a> is your best bet, as has been answered several times, for example:</p>\n\n<pre><code>vector<int> first = {13};\nconst vector<int> second = {42};\n\nfirst.insert(first.end(), second.cbegin(), second.cend());\n</code></pre>\n\n<p>Sadly there's no way to construct a <code>const vector<int></code>, as above you must construct and then <code>insert</code>.</p>\n\n<hr>\n\n<p>If what you're actually looking for is a container to hold the concatenation of these two <code>vector<int></code>s, there may be something better available to you, if:</p>\n\n<ol>\n<li>Your <code>vector</code> contains primitives</li>\n<li>Your contained primitives are of size 32-bit or smaller</li>\n<li>You want a <code>const</code> container</li>\n</ol>\n\n<p>If the above are all true, I'd suggest using the <a href=\"http://en.cppreference.com/w/cpp/string/basic_string\" rel=\"nofollow noreferrer\"><code>basic_string</code></a> who's <code>char_type</code> matches the size of the primitive contained in your <code>vector</code>. You should include a <a href=\"http://en.cppreference.com/w/cpp/language/static_assert\" rel=\"nofollow noreferrer\"><code>static_assert</code></a> in your code to validate these sizes stay consistent:</p>\n\n<pre><code>static_assert(sizeof(char32_t) == sizeof(int));\n</code></pre>\n\n<p>With this holding true you can just do:</p>\n\n<pre><code>const u32string concatenation = u32string(first.cbegin(), first.cend()) + u32string(second.cbegin(), second.cend());\n</code></pre>\n\n<p>For more information on the differences between <code>string</code> and <code>vector</code> you can look here: <a href=\"https://stackoverflow.com/a/35558008/2642059\">https://stackoverflow.com/a/35558008/2642059</a></p>\n\n<p>For a live example of this code you can look here: <a href=\"http://ideone.com/7Iww3I\" rel=\"nofollow noreferrer\">http://ideone.com/7Iww3I</a></p>\n"
},
{
"answer_id": 37744652,
"author": "ST3",
"author_id": 1237747,
"author_profile": "https://Stackoverflow.com/users/1237747",
"pm_score": 5,
"selected": false,
"text": "<p>I prefer one that is already mentioned: </p>\n\n<pre><code>a.insert(a.end(), b.begin(), b.end());\n</code></pre>\n\n<p>But if you use C++11, there is one more generic way:</p>\n\n<pre><code>a.insert(std::end(a), std::begin(b), std::end(b));\n</code></pre>\n\n<hr>\n\n<p>Also, not part of a question, but it is advisable to use <a href=\"http://www.cplusplus.com/reference/vector/vector/reserve/\" rel=\"noreferrer\"><code>reserve</code></a> before appending for better performance. And if you are concatenating vector with itself, without reserving it fails, so you always should <code>reserve</code>.</p>\n\n<hr>\n\n<p>So basically what you need:</p>\n\n<pre><code>template <typename T>\nvoid Append(std::vector<T>& a, const std::vector<T>& b)\n{\n a.reserve(a.size() + b.size());\n a.insert(a.end(), b.begin(), b.end());\n}\n</code></pre>\n"
},
{
"answer_id": 41183892,
"author": "instance",
"author_id": 3312772,
"author_profile": "https://Stackoverflow.com/users/3312772",
"pm_score": 2,
"selected": false,
"text": "<pre><code>vector<int> v1 = {1, 2, 3, 4, 5};\nvector<int> v2 = {11, 12, 13, 14, 15};\ncopy(v2.begin(), v2.end(), back_inserter(v1));\n</code></pre>\n"
},
{
"answer_id": 41340227,
"author": "nvnhcmus",
"author_id": 5697579,
"author_profile": "https://Stackoverflow.com/users/5697579",
"pm_score": -1,
"selected": false,
"text": "<p>To be honest, you could fast concatenate two vectors by copy elements from two vectors into the other one or just only append one of two vectors!. It depends on your aim.</p>\n\n<p><strong>Method 1:</strong> Assign new vector with its size is the sum of two original vectors' size.</p>\n\n<pre><code>vector<int> concat_vector = vector<int>();\nconcat_vector.setcapacity(vector_A.size() + vector_B.size());\n// Loop for copy elements in two vectors into concat_vector\n</code></pre>\n\n<p><strong>Method 2:</strong> Append vector A by adding/inserting elements of vector B. </p>\n\n<pre><code>// Loop for insert elements of vector_B into vector_A with insert() \nfunction: vector_A.insert(vector_A .end(), vector_B.cbegin(), vector_B.cend());\n</code></pre>\n"
},
{
"answer_id": 45563644,
"author": "Jarod42",
"author_id": 2684539,
"author_profile": "https://Stackoverflow.com/users/2684539",
"pm_score": 5,
"selected": false,
"text": "<p>With <a href=\"https://ericniebler.github.io/range-v3/\" rel=\"noreferrer\">range v3</a>, you may have a <strong>lazy</strong> concatenation:</p>\n\n<pre><code>ranges::view::concat(v1, v2)\n</code></pre>\n\n<p><a href=\"http://coliru.stacked-crooked.com/a/a323e3792a869244\" rel=\"noreferrer\">Demo</a>.</p>\n"
},
{
"answer_id": 45564780,
"author": "Boris",
"author_id": 7739417,
"author_profile": "https://Stackoverflow.com/users/7739417",
"pm_score": 3,
"selected": false,
"text": "<p>You should use <a href=\"http://www.cplusplus.com/reference/vector/vector/insert/\" rel=\"noreferrer\">vector::insert</a> </p>\n\n<pre><code>v1.insert(v1.end(), v2.begin(), v2.end());\n</code></pre>\n"
},
{
"answer_id": 49174699,
"author": "Daniel",
"author_id": 2970186,
"author_profile": "https://Stackoverflow.com/users/2970186",
"pm_score": 2,
"selected": false,
"text": "<p>Here's a general purpose solution using C++11 move semantics:</p>\n\n<pre><code>template <typename T>\nstd::vector<T> concat(const std::vector<T>& lhs, const std::vector<T>& rhs)\n{\n if (lhs.empty()) return rhs;\n if (rhs.empty()) return lhs;\n std::vector<T> result {};\n result.reserve(lhs.size() + rhs.size());\n result.insert(result.cend(), lhs.cbegin(), lhs.cend());\n result.insert(result.cend(), rhs.cbegin(), rhs.cend());\n return result;\n}\n\ntemplate <typename T>\nstd::vector<T> concat(std::vector<T>&& lhs, const std::vector<T>& rhs)\n{\n lhs.insert(lhs.cend(), rhs.cbegin(), rhs.cend());\n return std::move(lhs);\n}\n\ntemplate <typename T>\nstd::vector<T> concat(const std::vector<T>& lhs, std::vector<T>&& rhs)\n{\n rhs.insert(rhs.cbegin(), lhs.cbegin(), lhs.cend());\n return std::move(rhs);\n}\n\ntemplate <typename T>\nstd::vector<T> concat(std::vector<T>&& lhs, std::vector<T>&& rhs)\n{\n if (lhs.empty()) return std::move(rhs);\n lhs.insert(lhs.cend(), std::make_move_iterator(rhs.begin()), std::make_move_iterator(rhs.end()));\n return std::move(lhs);\n}\n</code></pre>\n\n<p>Note how this differs from <a href=\"https://stackoverflow.com/a/37210097/2970186\"><code>append</code></a>ing to a <code>vector</code>.</p>\n"
},
{
"answer_id": 50231136,
"author": "Vikramjit Roy",
"author_id": 5402524,
"author_profile": "https://Stackoverflow.com/users/5402524",
"pm_score": 4,
"selected": false,
"text": "<p>A <strong>general performance boost</strong> for concatenate is to check the size of the vectors. And merge/insert the smaller one with the larger one. </p>\n\n<pre><code>//vector<int> v1,v2;\nif(v1.size()>v2.size()) {\n v1.insert(v1.end(),v2.begin(),v2.end());\n} else {\n v2.insert(v2.end(),v1.begin(),v1.end());\n}\n</code></pre>\n"
},
{
"answer_id": 51613711,
"author": "Vladimir U.",
"author_id": 7759292,
"author_profile": "https://Stackoverflow.com/users/7759292",
"pm_score": 2,
"selected": false,
"text": "<p>You can prepare your own template for + operator:</p>\n\n<pre><code>template <typename T> \ninline T operator+(const T & a, const T & b)\n{\n T res = a;\n res.insert(res.end(), b.begin(), b.end());\n return res;\n}\n</code></pre>\n\n<p>Next thing - just use +:</p>\n\n<pre><code>vector<int> a{1, 2, 3, 4};\nvector<int> b{5, 6, 7, 8};\nfor (auto x: a + b)\n cout << x << \" \";\ncout << endl;\n</code></pre>\n\n<p>This example gives output:</p>\n\n<pre><blockquote>1 2 3 4 5 6 7 8</blockquote></pre>\n"
},
{
"answer_id": 53652797,
"author": "Aleph0",
"author_id": 5762796,
"author_profile": "https://Stackoverflow.com/users/5762796",
"pm_score": 1,
"selected": false,
"text": "<p>This solution might be a bit complicated, but <code>boost-range</code> has also some other nice things to offer.</p>\n\n<pre><code>#include <iostream>\n#include <vector>\n#include <boost/range/algorithm/copy.hpp>\n\nint main(int, char**) {\n std::vector<int> a = { 1,2,3 };\n std::vector<int> b = { 4,5,6 };\n boost::copy(b, std::back_inserter(a));\n for (auto& iter : a) {\n std::cout << iter << \" \";\n }\n return EXIT_SUCCESS;\n}\n</code></pre>\n\n<p>Often ones intention is to combine vector <code>a</code> and <code>b</code> just iterate over it doing some operation. In this case, there is the ridiculous simple <code>join</code> function. </p>\n\n<pre><code>#include <iostream>\n#include <vector>\n#include <boost/range/join.hpp>\n#include <boost/range/algorithm/copy.hpp>\n\nint main(int, char**) {\n std::vector<int> a = { 1,2,3 };\n std::vector<int> b = { 4,5,6 };\n std::vector<int> c = { 7,8,9 };\n // Just creates an iterator\n for (auto& iter : boost::join(a, boost::join(b, c))) {\n std::cout << iter << \" \";\n }\n std::cout << \"\\n\";\n // Can also be used to create a copy\n std::vector<int> d;\n boost::copy(boost::join(a, boost::join(b, c)), std::back_inserter(d));\n for (auto& iter : d) {\n std::cout << iter << \" \";\n }\n return EXIT_SUCCESS;\n}\n</code></pre>\n\n<p>For large vectors this might be an advantage, as there is no copying. It can be also used for copying an generalizes easily to more than one container. </p>\n\n<p>For some reason there is nothing like <code>boost::join(a,b,c)</code>, which could be reasonable.</p>\n"
},
{
"answer_id": 56781594,
"author": "Daniel Giger",
"author_id": 6338179,
"author_profile": "https://Stackoverflow.com/users/6338179",
"pm_score": 4,
"selected": false,
"text": "<p>If you want to be able to concatenate vectors concisely, you could overload the <code>+=</code> operator.</p>\n\n<pre><code>template <typename T>\nstd::vector<T>& operator +=(std::vector<T>& vector1, const std::vector<T>& vector2) {\n vector1.insert(vector1.end(), vector2.begin(), vector2.end());\n return vector1;\n}\n</code></pre>\n\n<p>Then you can call it like this:</p>\n\n<pre><code>vector1 += vector2;\n</code></pre>\n"
},
{
"answer_id": 56997340,
"author": "Drew",
"author_id": 595605,
"author_profile": "https://Stackoverflow.com/users/595605",
"pm_score": 2,
"selected": false,
"text": "<p>I've implemented this function which concatenates any number of containers, moving from rvalue-references and copying otherwise</p>\n\n<pre><code>namespace internal {\n\n// Implementation detail of Concatenate, appends to a pre-reserved vector, copying or moving if\n// appropriate\ntemplate<typename Target, typename Head, typename... Tail>\nvoid AppendNoReserve(Target* target, Head&& head, Tail&&... tail) {\n // Currently, require each homogenous inputs. If there is demand, we could probably implement a\n // version that outputs a vector whose value_type is the common_type of all the containers\n // passed to it, and call it ConvertingConcatenate.\n static_assert(\n std::is_same_v<\n typename std::decay_t<Target>::value_type,\n typename std::decay_t<Head>::value_type>,\n \"Concatenate requires each container passed to it to have the same value_type\");\n if constexpr (std::is_lvalue_reference_v<Head>) {\n std::copy(head.begin(), head.end(), std::back_inserter(*target));\n } else {\n std::move(head.begin(), head.end(), std::back_inserter(*target));\n }\n if constexpr (sizeof...(Tail) > 0) {\n AppendNoReserve(target, std::forward<Tail>(tail)...);\n }\n}\n\ntemplate<typename Head, typename... Tail>\nsize_t TotalSize(const Head& head, const Tail&... tail) {\n if constexpr (sizeof...(Tail) > 0) {\n return head.size() + TotalSize(tail...);\n } else {\n return head.size();\n }\n}\n\n} // namespace internal\n\n/// Concatenate the provided containers into a single vector. Moves from rvalue references, copies\n/// otherwise.\ntemplate<typename Head, typename... Tail>\nauto Concatenate(Head&& head, Tail&&... tail) {\n size_t totalSize = internal::TotalSize(head, tail...);\n std::vector<typename std::decay_t<Head>::value_type> result;\n result.reserve(totalSize);\n internal::AppendNoReserve(&result, std::forward<Head>(head), std::forward<Tail>(tail)...);\n return result;\n}\n</code></pre>\n"
},
{
"answer_id": 57533671,
"author": "Pavan Chandaka",
"author_id": 6866309,
"author_profile": "https://Stackoverflow.com/users/6866309",
"pm_score": 4,
"selected": false,
"text": "<p>There is an algorithm <a href=\"https://en.cppreference.com/w/cpp/algorithm/merge\" rel=\"noreferrer\"><code>std::merge</code></a> from <strong>C++17</strong>, which is very easy to use when the input vectors are sorted,</p>\n<p>Below is the example:</p>\n<pre><code>#include <iostream>\n#include <vector>\n#include <algorithm>\n\nint main()\n{\n //DATA\n std::vector<int> v1{2,4,6,8};\n std::vector<int> v2{12,14,16,18};\n\n //MERGE\n std::vector<int> dst;\n std::merge(v1.begin(), v1.end(), v2.begin(), v2.end(), std::back_inserter(dst));\n\n //PRINT\n for(auto item:dst)\n std::cout<<item<<" ";\n\n return 0;\n}\n</code></pre>\n"
},
{
"answer_id": 58492880,
"author": "Ronald Souza",
"author_id": 2379625,
"author_profile": "https://Stackoverflow.com/users/2379625",
"pm_score": 3,
"selected": false,
"text": "<p>If your goal is simply to iterate over the range of values for read-only purposes, an alternative is to wrap both vectors around a proxy (O(1)) instead of copying them (O(n)), so they are promptly seen as a single, contiguous one. </p>\n\n<pre><code>std::vector<int> A{ 1, 2, 3, 4, 5};\nstd::vector<int> B{ 10, 20, 30 };\n\nVecProxy<int> AB(A, B); // ----> O(1)!\n\nfor (size_t i = 0; i < AB.size(); i++)\n std::cout << AB[i] << \" \"; // ----> 1 2 3 4 5 10 20 30\n</code></pre>\n\n<p>Refer to <a href=\"https://stackoverflow.com/a/55838758/2379625\">https://stackoverflow.com/a/55838758/2379625</a> for more details, including the 'VecProxy' implementation as well as pros & cons.</p>\n"
},
{
"answer_id": 61988198,
"author": "rekkalmd",
"author_id": 9694134,
"author_profile": "https://Stackoverflow.com/users/9694134",
"pm_score": 0,
"selected": false,
"text": "<p>You can do it with pre-implemented STL algorithms using a template for a polymorphic type use.</p>\n\n<pre><code>#include <iostream>\n#include <vector>\n#include <algorithm>\n\ntemplate<typename T>\n\nvoid concat(std::vector<T>& valuesa, std::vector<T>& valuesb){\n\n for_each(valuesb.begin(), valuesb.end(), [&](int value){ valuesa.push_back(value);});\n}\n\nint main()\n{\n std::vector<int> values_p={1,2,3,4,5};\n std::vector<int> values_s={6,7};\n\n concat(values_p, values_s);\n\n for(auto& it : values_p){\n\n std::cout<<it<<std::endl;\n }\n\n return 0;\n}\n</code></pre>\n\n<p>You can clear the second vector if you don't want to use it further (<code>clear()</code> method).</p>\n"
},
{
"answer_id": 62255226,
"author": "GobeRadJem32",
"author_id": 10903517,
"author_profile": "https://Stackoverflow.com/users/10903517",
"pm_score": -1,
"selected": false,
"text": "<p>Concatenate two <code>std::vector-s</code> with <code>for</code> loop in one <code>std::vector</code>.</p>\n<pre class=\"lang-cpp prettyprint-override\"><code> std::vector <int> v1 {1, 2, 3}; //declare vector1\n std::vector <int> v2 {4, 5}; //declare vector2\n std::vector <int> suma; //declare vector suma\n\n for(int i = 0; i < v1.size(); i++) //for loop 1\n {\n suma.push_back(v1[i]);\n }\n\n for(int i = 0; i< v2.size(); i++) //for loop 2\n {\n suma.push_back(v2[i]);\n }\n\n for(int i = 0; i < suma.size(); i++) //for loop 3-output\n {\n std::cout << suma[i];\n }\n</code></pre>\n"
},
{
"answer_id": 62582258,
"author": "GobeRadJem32",
"author_id": 10903517,
"author_profile": "https://Stackoverflow.com/users/10903517",
"pm_score": -1,
"selected": false,
"text": "<p>Try, create two vectors and add second vector to first vector,\ncode:</p>\n<pre><code>std::vector<int> v1{1,2,3};\nstd::vector<int> v2{4,5};\n\nfor(int i = 0; i<v2.size();i++)\n{\n v1.push_back(v2[i]);\n}\n</code></pre>\n<p>v1:1,2,3.</p>\n<p>Description:</p>\n<p>While i int not v2 size, push back element , index i in v1 vector.</p>\n"
},
{
"answer_id": 68109876,
"author": "Aroonalok",
"author_id": 3258380,
"author_profile": "https://Stackoverflow.com/users/3258380",
"pm_score": 1,
"selected": false,
"text": "<p>For containers which offer <code>push_back</code> (string, vector, deque, ...):</p>\n<p><code>std::copy(std::begin(input), std::end(input), std::back_inserter(output))</code></p>\n<p>and</p>\n<p>for containers which offer <code>insert</code> (maps, sets):</p>\n<p><code>std::copy(std::begin(input), std::end(input), std::inserter(output, output.end()))</code></p>\n"
},
{
"answer_id": 72288186,
"author": "Olppah",
"author_id": 2021579,
"author_profile": "https://Stackoverflow.com/users/2021579",
"pm_score": 2,
"selected": false,
"text": "<p>Using C++20 you can get rid of begin() and end() with ranges.</p>\n<pre><code>#include <ranges>\n\nstd::ranges::copy(vec2, std::back_inserter(vec1));\n</code></pre>\n<p>or if you want to move elements:</p>\n<pre><code>std::ranges::move(vec2, std::back_inserter(vec1));\n</code></pre>\n"
}
] |
2008/10/14
|
[
"https://Stackoverflow.com/questions/201718",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] |
How do I concatenate two `std::vector`s?
|
```
vector1.insert( vector1.end(), vector2.begin(), vector2.end() );
```
|
201,724 |
<p>I have a one-dimensional array of strings in JavaScript that I'd like to turn into a comma-separated list. Is there a simple way in garden-variety JavaScript (or jQuery) to turn that into a comma-separated list? (I know how to iterate through the array and build the string myself by concatenation if that's the only way.)</p>
|
[
{
"answer_id": 201733,
"author": "Wayne",
"author_id": 8236,
"author_profile": "https://Stackoverflow.com/users/8236",
"pm_score": 11,
"selected": true,
"text": "<p>The <a href=\"https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/Array/join\" rel=\"noreferrer\">Array.prototype.join()</a> method:</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-js lang-js prettyprint-override\"><code>var arr = [\"Zero\", \"One\", \"Two\"];\r\n\r\ndocument.write(arr.join(\", \"));</code></pre>\r\n</div>\r\n</div>\r\n</p>\n"
},
{
"answer_id": 202127,
"author": "Sergey Ilinsky",
"author_id": 23815,
"author_profile": "https://Stackoverflow.com/users/23815",
"pm_score": 5,
"selected": false,
"text": "<p>Or (more efficiently):</p>\n\n<pre>\nvar arr = new Array(3);\narr[0] = \"Zero\";\narr[1] = \"One\";\narr[2] = \"Two\";\n\ndocument.write(arr); // same as document.write(arr.toString()) in this context\n</pre>\n\n<p>The toString method of an array when called returns exactly what you need - comma-separated list.</p>\n"
},
{
"answer_id": 202247,
"author": "Ates Goral",
"author_id": 23501,
"author_profile": "https://Stackoverflow.com/users/23501",
"pm_score": 7,
"selected": false,
"text": "<p>Actually, the <code>toString()</code> implementation does a join with commas by default:</p>\n\n<pre><code>var arr = [ 42, 55 ];\nvar str1 = arr.toString(); // Gives you \"42,55\"\nvar str2 = String(arr); // Ditto\n</code></pre>\n\n<p>I don't know if this is mandated by the JS spec but this is what <del>most</del> pretty much all browsers seem to be doing.</p>\n"
},
{
"answer_id": 22184713,
"author": "skibulk",
"author_id": 1017480,
"author_profile": "https://Stackoverflow.com/users/1017480",
"pm_score": 4,
"selected": false,
"text": "<p>Here's an implementation that converts a two-dimensional array or an array of columns into a properly escaped CSV string. The functions do not check for valid string/number input or column counts (ensure your array is valid to begin with). The cells can contain commas and quotes! </p>\n\n<p>Here's a <a href=\"https://github.com/thetalecrafter/excel.js/blob/master/src/csv.js\" rel=\"nofollow noreferrer\">script for decoding CSV strings</a>.</p>\n\n<p>Here's my <a href=\"http://jsfiddle.net/skibulk/F5hGx/19/\" rel=\"nofollow noreferrer\">script for encoding CSV strings</a>:</p>\n\n<pre><code>// Example\nvar csv = new csvWriter();\ncsv.del = '\\t';\ncsv.enc = \"'\";\n\nvar nullVar;\nvar testStr = \"The comma (,) pipe (|) single quote (') double quote (\\\") and tab (\\t) are commonly used to tabulate data in plain-text formats.\";\nvar testArr = [\n false,\n 0,\n nullVar,\n // undefinedVar,\n '',\n {key:'value'},\n];\n\nconsole.log(csv.escapeCol(testStr));\nconsole.log(csv.arrayToRow(testArr));\nconsole.log(csv.arrayToCSV([testArr, testArr, testArr]));\n\n/**\n * Class for creating csv strings\n * Handles multiple data types\n * Objects are cast to Strings\n **/\n\nfunction csvWriter(del, enc) {\n this.del = del || ','; // CSV Delimiter\n this.enc = enc || '\"'; // CSV Enclosure\n\n // Convert Object to CSV column\n this.escapeCol = function (col) {\n if(isNaN(col)) {\n // is not boolean or numeric\n if (!col) {\n // is null or undefined\n col = '';\n } else {\n // is string or object\n col = String(col);\n if (col.length > 0) {\n // use regex to test for del, enc, \\r or \\n\n // if(new RegExp( '[' + this.del + this.enc + '\\r\\n]' ).test(col)) {\n\n // escape inline enclosure\n col = col.split( this.enc ).join( this.enc + this.enc );\n\n // wrap with enclosure\n col = this.enc + col + this.enc;\n }\n }\n }\n return col;\n };\n\n // Convert an Array of columns into an escaped CSV row\n this.arrayToRow = function (arr) {\n var arr2 = arr.slice(0);\n\n var i, ii = arr2.length;\n for(i = 0; i < ii; i++) {\n arr2[i] = this.escapeCol(arr2[i]);\n }\n return arr2.join(this.del);\n };\n\n // Convert a two-dimensional Array into an escaped multi-row CSV \n this.arrayToCSV = function (arr) {\n var arr2 = arr.slice(0);\n\n var i, ii = arr2.length;\n for(i = 0; i < ii; i++) {\n arr2[i] = this.arrayToRow(arr2[i]);\n }\n return arr2.join(\"\\r\\n\");\n };\n}\n</code></pre>\n"
},
{
"answer_id": 22313674,
"author": "mpen",
"author_id": 65387,
"author_profile": "https://Stackoverflow.com/users/65387",
"pm_score": 4,
"selected": false,
"text": "<p>I think this should do it:</p>\n\n<pre><code>var arr = ['contains,comma', 3.14, 'contains\"quote', \"more'quotes\"]\nvar item, i;\nvar line = [];\n\nfor (i = 0; i < arr.length; ++i) {\n item = arr[i];\n if (item.indexOf && (item.indexOf(',') !== -1 || item.indexOf('\"') !== -1)) {\n item = '\"' + item.replace(/\"/g, '\"\"') + '\"';\n }\n line.push(item);\n}\n\ndocument.getElementById('out').innerHTML = line.join(',');\n</code></pre>\n\n<p><a href=\"http://jsfiddle.net/mnbayazit/G9mYj/4/\">fiddle</a></p>\n\n<p>Basically all it does is check if the string contains a comma or quote. If it does, then it doubles all the quotes, and puts quotes on the ends. Then it joins each of the parts with a comma.</p>\n"
},
{
"answer_id": 31013271,
"author": "E Roberts",
"author_id": 4945400,
"author_profile": "https://Stackoverflow.com/users/4945400",
"pm_score": 1,
"selected": false,
"text": "<p>Taking the initial code:</p>\n\n<pre><code>var arr = new Array(3);\narr[0] = \"Zero\";\narr[1] = \"One\";\narr[2] = \"Two\";\n</code></pre>\n\n<p>The initial answer of using the join function is ideal. One thing to consider would be the ultimate use of the string. </p>\n\n<p>For using in some end textual display:</p>\n\n<pre><code>arr.join(\",\")\n=> \"Zero,One,Two\"\n</code></pre>\n\n<p>For using in a URL for passing multiple values through in a (somewhat) RESTful manner:</p>\n\n<pre><code>arr.join(\"|\")\n=> \"Zero|One|Two\"\n\nvar url = 'http://www.yoursitehere.com/do/something/to/' + arr.join(\"|\");\n=> \"http://www.yoursitehere.com/do/something/to/Zero|One|Two\"\n</code></pre>\n\n<p>Of course, it all depends on the final use. Just keep the data source and use in mind and all will be right with the world.</p>\n"
},
{
"answer_id": 34250056,
"author": "Avijit Gupta",
"author_id": 4135178,
"author_profile": "https://Stackoverflow.com/users/4135178",
"pm_score": 3,
"selected": false,
"text": "<p>Use the built-in <code>Array.toString</code> method </p>\n\n<pre><code>var arr = ['one', 'two', 'three'];\narr.toString(); // 'one,two,three'\n</code></pre>\n\n<p><a href=\"https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/Array/toString\" rel=\"noreferrer\">MDN on Array.toString()</a></p>\n"
},
{
"answer_id": 35597142,
"author": "Dawson B",
"author_id": 3855197,
"author_profile": "https://Stackoverflow.com/users/3855197",
"pm_score": 1,
"selected": false,
"text": "<p>Do you want to end it with an \"and\"?</p>\n\n<p>For this situation, I created an npm module.</p>\n\n<p>Try <a href=\"https://github.com/dawsonbotsford/arrford\" rel=\"nofollow\">arrford</a>:</p>\n\n<p><br></p>\n\n<h2>Usage</h2>\n\n<pre><code>const arrford = require('arrford');\n\narrford(['run', 'climb', 'jump!']);\n//=> 'run, climb, and jump!'\n\narrford(['run', 'climb', 'jump!'], false);\n//=> 'run, climb and jump!'\n\narrford(['run', 'climb!']);\n//=> 'run and climb!'\n\narrford(['run!']);\n//=> 'run!'\n</code></pre>\n\n<p><br></p>\n\n<h2>Install</h2>\n\n<pre><code>npm install --save arrford\n</code></pre>\n\n<p><br></p>\n\n<h2>Read More</h2>\n\n<p><a href=\"https://github.com/dawsonbotsford/arrford\" rel=\"nofollow\">https://github.com/dawsonbotsford/arrford</a></p>\n\n<p><br></p>\n\n<h2>Try it yourself</h2>\n\n<p><a href=\"https://tonicdev.com/dawsonbotsford/56f46dd154d4e814002e34b9\" rel=\"nofollow\">Tonic link</a></p>\n"
},
{
"answer_id": 40460413,
"author": "Akash",
"author_id": 4218672,
"author_profile": "https://Stackoverflow.com/users/4218672",
"pm_score": -1,
"selected": false,
"text": "<pre><code>var arr = [\"Pro1\", \"Pro2\", \"Pro3\"];\nconsole.log(arr.join());// Pro1,Pro2,Pro3\nconsole.log(arr.join(', '));// Pro1, Pro2, Pro3\n</code></pre>\n"
},
{
"answer_id": 43015176,
"author": "Andrew Downes",
"author_id": 1409410,
"author_profile": "https://Stackoverflow.com/users/1409410",
"pm_score": 4,
"selected": false,
"text": "<p>If you need to use \" and \" instead of \", \" between the last two items you can do this:</p>\n\n<pre><code>function arrayToList(array){\n return array\n .join(\", \")\n .replace(/, ((?:.(?!, ))+)$/, ' and $1');\n}\n</code></pre>\n"
},
{
"answer_id": 44299490,
"author": "alejandro",
"author_id": 505002,
"author_profile": "https://Stackoverflow.com/users/505002",
"pm_score": -1,
"selected": false,
"text": "<pre><code>var array = [\"Zero\", \"One\", \"Two\"];\nvar s = array + [];\nconsole.log(s); // => Zero,One,Two\n</code></pre>\n"
},
{
"answer_id": 44844082,
"author": "knowbody",
"author_id": 1957849,
"author_profile": "https://Stackoverflow.com/users/1957849",
"pm_score": 2,
"selected": false,
"text": "<p>I usually find myself needing something that also skips the value if that value is <code>null</code> or <code>undefined</code>, etc.</p>\n\n<p>So here is the solution that works for me:</p>\n\n<pre><code>// Example 1\nconst arr1 = ['apple', null, 'banana', '', undefined, 'pear'];\nconst commaSeparated1 = arr1.filter(item => item).join(', ');\nconsole.log(commaSeparated1); // 'apple, banana, pear'\n\n// Example 2\nconst arr2 = [null, 'apple'];\nconst commaSeparated2 = arr2.filter(item => item).join(', ');\nconsole.log(commaSeparated2); // 'apple'\n</code></pre>\n\n<p>Most of the solutions here would return <code>', apple'</code> if my array would look like the one in my second example. That's why I prefer this solution.</p>\n"
},
{
"answer_id": 44988398,
"author": "Bob",
"author_id": 4779501,
"author_profile": "https://Stackoverflow.com/users/4779501",
"pm_score": 2,
"selected": false,
"text": "<p><a href=\"http://papaparse.com/\" rel=\"nofollow noreferrer\">Papa Parse</a> handles commas in values and other edge cases.</p>\n\n<p>(<a href=\"https://www.npmjs.com/package/babyparse\" rel=\"nofollow noreferrer\">Baby Parse</a> for Node has been deprecated - you can now use Papa Parse in the Browser and in Node.)</p>\n\n<p>Eg. (node)</p>\n\n<pre><code>const csvParser = require('papaparse'); // previously you might have used babyparse\nvar arr = [1,null,\"a,b\"] ;\nvar csv = csvParser.unparse([arr]) ;\nconsole.log(csv) ;\n</code></pre>\n\n<p>1,,\"a,b\"</p>\n"
},
{
"answer_id": 45161169,
"author": "Sagar V",
"author_id": 2427065,
"author_profile": "https://Stackoverflow.com/users/2427065",
"pm_score": 3,
"selected": false,
"text": "<p>There are many methods to convert an array to comma separated list</p>\n\n<h1>1. Using array#join</h1>\n\n<p>From <a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/join\" rel=\"noreferrer\">MDN</a></p>\n\n<blockquote>\n <p>The join() method joins all elements of an array (or an array-like object) into a string.</p>\n</blockquote>\n\n<p>The code</p>\n\n<pre><code>var arr = [\"this\",\"is\",\"a\",\"comma\",\"separated\",\"list\"];\narr = arr.join(\",\");\n</code></pre>\n\n<h3>Snippet</h3>\n\n<p><div class=\"snippet\" data-lang=\"js\" data-hide=\"true\" data-console=\"true\" data-babel=\"false\">\r\n<div class=\"snippet-code snippet-currently-hidden\">\r\n<pre class=\"snippet-code-js lang-js prettyprint-override\"><code>var arr = [\"this\", \"is\", \"a\", \"comma\", \"separated\", \"list\"];\r\narr = arr.join(\",\");\r\nconsole.log(arr);</code></pre>\r\n</div>\r\n</div>\r\n</p>\n\n<h1>2. Using array#toString</h1>\n\n<p>From <a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/toString\" rel=\"noreferrer\">MDN</a></p>\n\n<blockquote>\n <p>The toString() method returns a string representing the specified array and its elements.</p>\n</blockquote>\n\n<p>The code</p>\n\n<pre><code>var arr = [\"this\",\"is\",\"a\",\"comma\",\"separated\",\"list\"];\narr = arr.toString();\n</code></pre>\n\n<h3>Snippet</h3>\n\n<p><div class=\"snippet\" data-lang=\"js\" data-hide=\"true\" data-console=\"true\" data-babel=\"false\">\r\n<div class=\"snippet-code snippet-currently-hidden\">\r\n<pre class=\"snippet-code-js lang-js prettyprint-override\"><code>var arr = [\"this\", \"is\", \"a\", \"comma\", \"separated\", \"list\"];\r\narr = arr.toString();\r\nconsole.log(arr);</code></pre>\r\n</div>\r\n</div>\r\n</p>\n\n<h1>3. Add []+ before array or +[] after an array</h1>\n\n<p>The <em>[]+</em> or <em>+[]</em> will convert it into a string</p>\n\n<h2>Proof</h2>\n\n<pre><code>([]+[] === [].toString())\n</code></pre>\n\n<p>will output <em>true</em></p>\n\n<p><div class=\"snippet\" data-lang=\"js\" data-hide=\"true\" data-console=\"true\" data-babel=\"false\">\r\n<div class=\"snippet-code snippet-currently-hidden\">\r\n<pre class=\"snippet-code-js lang-js prettyprint-override\"><code>console.log([]+[] === [].toString());</code></pre>\r\n</div>\r\n</div>\r\n</p>\n\n<pre><code>var arr = [\"this\",\"is\",\"a\",\"comma\",\"separated\",\"list\"];\narr = []+arr;\n</code></pre>\n\n<h3>Snippet</h3>\n\n<p><div class=\"snippet\" data-lang=\"js\" data-hide=\"true\" data-console=\"true\" data-babel=\"false\">\r\n<div class=\"snippet-code snippet-currently-hidden\">\r\n<pre class=\"snippet-code-js lang-js prettyprint-override\"><code>var arr = [\"this\", \"is\", \"a\", \"comma\", \"separated\", \"list\"];\r\narr = []+arr;\r\nconsole.log(arr);</code></pre>\r\n</div>\r\n</div>\r\n</p>\n\n<h3>Also</h3>\n\n<pre><code>var arr = [\"this\",\"is\",\"a\",\"comma\",\"separated\",\"list\"];\narr = arr+[];\n</code></pre>\n\n<p><div class=\"snippet\" data-lang=\"js\" data-hide=\"true\" data-console=\"true\" data-babel=\"false\">\r\n<div class=\"snippet-code snippet-currently-hidden\">\r\n<pre class=\"snippet-code-js lang-js prettyprint-override\"><code>var arr = [\"this\", \"is\", \"a\", \"comma\", \"separated\", \"list\"];\r\narr = arr + [];\r\nconsole.log(arr);</code></pre>\r\n</div>\r\n</div>\r\n</p>\n"
},
{
"answer_id": 52081537,
"author": "Jaime Montoya",
"author_id": 4242086,
"author_profile": "https://Stackoverflow.com/users/4242086",
"pm_score": 1,
"selected": false,
"text": "<p>I liked the solution at <a href=\"https://jsfiddle.net/rwone/qJUh2/\" rel=\"nofollow noreferrer\">https://jsfiddle.net/rwone/qJUh2/</a> because it adds spaces after commas:</p>\n\n<pre><code>array = [\"test\",\"test2\",\"test3\"]\narray = array.toString();\narray = array.replace(/,/g, \", \");\nalert(array);\n</code></pre>\n\n<p>Or, as suggested by @StackOverflaw in the comments:</p>\n\n<pre><code>array.join(', ');\n</code></pre>\n"
},
{
"answer_id": 54442843,
"author": "Eliya Cohen",
"author_id": 1860540,
"author_profile": "https://Stackoverflow.com/users/1860540",
"pm_score": 2,
"selected": false,
"text": "<p>As of <a href=\"https://developers.google.com/web/updates/2019/01/nic72#intl-format\" rel=\"nofollow noreferrer\">Chrome 72</a>, it's possible to use <a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/ListFormat\" rel=\"nofollow noreferrer\">Intl.ListFormat</a>:</p>\n\n<p><div class=\"snippet\" data-lang=\"js\" data-hide=\"false\" data-console=\"true\" data-babel=\"false\">\r\n<div class=\"snippet-code\">\r\n<pre class=\"snippet-code-js lang-js prettyprint-override\"><code>const vehicles = ['Motorcycle', 'Bus', 'Car'];\r\n\r\nconst formatter = new Intl.ListFormat('en', { style: 'long', type: 'conjunction' });\r\nconsole.log(formatter.format(vehicles));\r\n// expected output: \"Motorcycle, Bus, and Car\"\r\n\r\nconst formatter2 = new Intl.ListFormat('de', { style: 'short', type: 'disjunction' });\r\nconsole.log(formatter2.format(vehicles));\r\n// expected output: \"Motorcycle, Bus oder Car\"\r\n\r\nconst formatter3 = new Intl.ListFormat('en', { style: 'narrow', type: 'unit' });\r\nconsole.log(formatter3.format(vehicles));\r\n// expected output: \"Motorcycle Bus Car\"</code></pre>\r\n</div>\r\n</div>\r\n</p>\n\n<p>Please note that this way is in its very earlier stage, so as of the date of posting this answer, expect incompatibility with older versions of Chrome and other browsers.</p>\n"
},
{
"answer_id": 57397123,
"author": "Yorkshireman",
"author_id": 4111480,
"author_profile": "https://Stackoverflow.com/users/4111480",
"pm_score": -1,
"selected": false,
"text": "<p>This solution also removes values such as <code>\" \"</code>:</p>\n\n<pre><code>const result = ['', null, 'foo', ' ', undefined, 'bar'].filter(el => {\n return Boolean(el) && el.trim() !== '';\n}).join(', ');\n\nconsole.log(result); // => foo, bar\n</code></pre>\n"
},
{
"answer_id": 64129307,
"author": "gildniy",
"author_id": 1992866,
"author_profile": "https://Stackoverflow.com/users/1992866",
"pm_score": 2,
"selected": false,
"text": "<pre><code>const arr = [1, 2, 3];\nconsole.log(`${arr}`)\n</code></pre>\n"
},
{
"answer_id": 65460835,
"author": "Jafar Karuthedath",
"author_id": 2668564,
"author_profile": "https://Stackoverflow.com/users/2668564",
"pm_score": 5,
"selected": false,
"text": "<p>Simple Array</p>\n<p><div class=\"snippet\" data-lang=\"js\" data-hide=\"false\" data-console=\"true\" data-babel=\"false\">\r\n<div class=\"snippet-code\">\r\n<pre class=\"snippet-code-js lang-js prettyprint-override\"><code>let simpleArray = [1,2,3,4]\nlet commaSeperated = simpleArray.join(\",\");\nconsole.log(commaSeperated);</code></pre>\r\n</div>\r\n</div>\r\n</p>\n<p>Array of Objects with a particular attributes as comma separated.</p>\n<p><div class=\"snippet\" data-lang=\"js\" data-hide=\"false\" data-console=\"true\" data-babel=\"false\">\r\n<div class=\"snippet-code\">\r\n<pre class=\"snippet-code-js lang-js prettyprint-override\"><code>let arrayOfObjects = [\n{\nid : 1,\nname : \"Name 1\",\naddress : \"Address 1\"\n},\n{\nid : 2,\nname : \"Name 2\",\naddress : \"Address 2\"\n},\n{\nid : 3,\nname : \"Name 3\",\naddress : \"Address 3\"\n}]\nlet names = arrayOfObjects.map(x => x.name).join(\", \");\nconsole.log(names);</code></pre>\r\n</div>\r\n</div>\r\n</p>\n<p>Result</p>\n<pre><code>Name 1, Name 2, Name 3\n</code></pre>\n"
},
{
"answer_id": 69657454,
"author": "Ali Akram",
"author_id": 8652059,
"author_profile": "https://Stackoverflow.com/users/8652059",
"pm_score": 1,
"selected": false,
"text": "<blockquote>\n<p>here you can separate with any char and can take any property list with just foreach</p>\n</blockquote>\n<pre><code>let taskIds: string = ''; \nthis.checkedTaskList.forEach(res => {\n taskIds = taskIds + res.taskId.toString() + ','\n});\nif (taskIds) {\n taskIds.substring(0, taskIds.length - 1),**\n}\n</code></pre>\n"
},
{
"answer_id": 72925744,
"author": "roel",
"author_id": 627794,
"author_profile": "https://Stackoverflow.com/users/627794",
"pm_score": 2,
"selected": false,
"text": "<p>Safe way for string that contains separator (comma)</p>\n<pre><code>let arr = ["Hello, there", "How's there", 'the "best"']\nlet csv = arr.map(e => JSON.stringify(e)).join(",")\nconsole.log(csv)\n</code></pre>\n<p>result</p>\n<pre><code>"Hello, there","How's there","the \\\\"best\\\\""\n</code></pre>\n"
}
] |
2008/10/14
|
[
"https://Stackoverflow.com/questions/201724",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/239663/"
] |
I have a one-dimensional array of strings in JavaScript that I'd like to turn into a comma-separated list. Is there a simple way in garden-variety JavaScript (or jQuery) to turn that into a comma-separated list? (I know how to iterate through the array and build the string myself by concatenation if that's the only way.)
|
The [Array.prototype.join()](https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/Array/join) method:
```js
var arr = ["Zero", "One", "Two"];
document.write(arr.join(", "));
```
|
201,734 |
<p>I have an HttpHandler on my webserver that takes a URL in the form of "<a href="https://servername/myhandler?op=get&k=Internal&m=jdahug1" rel="nofollow noreferrer">https://servername/myhandler?op=get&k=Internal&m=jdahug1</a>". I need to call this URL from my .NET app and capture whatever the output is. Does anyone know how I can do that? I want it to be simple so that I just get back a string with the output, and that I can specify my own timeout.</p>
<ul>
<li>Thanks!</li>
</ul>
|
[
{
"answer_id": 201740,
"author": "Joel Coehoorn",
"author_id": 3043,
"author_profile": "https://Stackoverflow.com/users/3043",
"pm_score": 3,
"selected": false,
"text": "<p>Try the System.Net.WebClient class.</p>\n\n<p>You can use the .DownloadStringAsync() method to enforce a timeout.</p>\n"
},
{
"answer_id": 201759,
"author": "Andrew Cox",
"author_id": 27907,
"author_profile": "https://Stackoverflow.com/users/27907",
"pm_score": 2,
"selected": true,
"text": "<p>we have used the following in the backend of our product (this is just the core code, not with timeout errorhandling etc.)</p>\n\n<pre><code>using System.Net;\n\nusing System.IO;\n\nHttpWebRequest req = (HttpWebRequest) WebRequest.Create(WebPageUrl);\n\nWebResponse resp = req.GetResponse();\n\nStream stream = resp.GetResponseStream();\n\nStreamReader reader = new StreamReader(stream);\n\noutput.Write(reader.ReadToEnd());\n</code></pre>\n"
},
{
"answer_id": 201769,
"author": "Quintin Robinson",
"author_id": 12707,
"author_profile": "https://Stackoverflow.com/users/12707",
"pm_score": 2,
"selected": false,
"text": "<p>As Joel had said WebClient would do the trick..</p>\n\n<pre><code>string handlerResponse = new System.Net.WebClient().DownloadString(\"https://servername/myhandler?op=get&k=Internal&m=jdahug1\");\n</code></pre>\n\n<p>of course given your own timeout and good practices you probably don't want to inline the call, but you get the idea.</p>\n"
},
{
"answer_id": 201774,
"author": "William Rohrbach",
"author_id": 27910,
"author_profile": "https://Stackoverflow.com/users/27910",
"pm_score": 2,
"selected": false,
"text": "<p>Shawn Wildermuth gives a great overview of the two options you have: WebClient and WebRequest (<a href=\"http://wildermuth.com/2008/09/27/WebClient_vs_WebRequest_in_Silverlight_2\" rel=\"nofollow noreferrer\">http://wildermuth.com/2008/09/27/WebClient_vs_WebRequest_in_Silverlight_2</a>). WebClient is just a higher level abstraction that handles more of the details for you. Since you are just looking to get a string back I would look to use the WebClient, which as Shawn describes, has a DownloadString method just waiting for you to use.</p>\n"
}
] |
2008/10/14
|
[
"https://Stackoverflow.com/questions/201734",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/14101/"
] |
I have an HttpHandler on my webserver that takes a URL in the form of "<https://servername/myhandler?op=get&k=Internal&m=jdahug1>". I need to call this URL from my .NET app and capture whatever the output is. Does anyone know how I can do that? I want it to be simple so that I just get back a string with the output, and that I can specify my own timeout.
* Thanks!
|
we have used the following in the backend of our product (this is just the core code, not with timeout errorhandling etc.)
```
using System.Net;
using System.IO;
HttpWebRequest req = (HttpWebRequest) WebRequest.Create(WebPageUrl);
WebResponse resp = req.GetResponse();
Stream stream = resp.GetResponseStream();
StreamReader reader = new StreamReader(stream);
output.Write(reader.ReadToEnd());
```
|
201,776 |
<p>I have an ASP.NET web page with a Login control on it. When I hit Enter, the Login button doesn't fire; instead the page submits, doing nothing.</p>
<p>The standard solution to this that I've found online is to enclose the Login control in a Panel, then set the Panel default button. But apparently that doesn't work so well if the page has a master page. I've tried setting the default button in code with <em>control</em>.ID, <em>control</em>.ClientID, and <em>control</em>.UniqueID, and in each case I get:</p>
<blockquote>
<p>The DefaultButton of panelName must be the ID of a control of type IButtonControl.</p>
</blockquote>
<p>I'm sure there's a way to do this with JavaScript, but I'd really like to do it with plain old C# code if possible. Is it possible?</p>
|
[
{
"answer_id": 201822,
"author": "StingyJack",
"author_id": 16391,
"author_profile": "https://Stackoverflow.com/users/16391",
"pm_score": 2,
"selected": false,
"text": "<p>you have to add something like this in page load...</p>\n\n<pre><code>txtPassword.Attributes.Add(\"onKeyPress\", \"javascript:if (event.keyCode == 13) __doPostBack('\" + lnkSubmit.UniqueID + \"','')\")\n</code></pre>\n\n<p>the password textbox has an onKeyPress attribute added that will force a doPostBack on the submit button if the \"Enter\" key is pressed. This simulates clicking the submit button.</p>\n"
},
{
"answer_id": 201879,
"author": "roryf",
"author_id": 270,
"author_profile": "https://Stackoverflow.com/users/270",
"pm_score": 2,
"selected": false,
"text": "<p>Sounds like the login button is being spat out as <code><input type=\"button\"></code> rather than <code><input type=\"submit\"></code>. You could always template the LoginControl and add the submit button, getting rid of the hideous default markup at the same time!</p>\n\n<p>If you have to use Javascript to fix this something is seriously wrong! (but then it sounds like you know this)</p>\n"
},
{
"answer_id": 201889,
"author": "Vassili Altynikov",
"author_id": 22205,
"author_profile": "https://Stackoverflow.com/users/22205",
"pm_score": 6,
"selected": true,
"text": "<p>This should be helpful: <a href=\"http://weblogs.asp.net/jgalloway/archive/2007/10/03/asp-net-setting-the-defaultbutton-for-a-login-control.aspx\" rel=\"noreferrer\">http://weblogs.asp.net/jgalloway/archive/2007/10/03/asp-net-setting-the-defaultbutton-for-a-login-control.aspx</a></p>\n\n<p>You can use the following to reference the button within the Login control template:</p>\n\n<pre><code>DefaultButton=\"Login$LoginButton\"\n</code></pre>\n\n<p>Basically, you can define a DefaultButton not just on the Form level, but also on individual Panel level, as long as the focus is within the panel, the default button for the panel will be used if you hit \"Enter\"</p>\n"
},
{
"answer_id": 434218,
"author": "EMP",
"author_id": 20336,
"author_profile": "https://Stackoverflow.com/users/20336",
"pm_score": 3,
"selected": false,
"text": "<p>Great answer by <strong>Blend Master</strong>! Essentially just use Panel.DefaultButton, but I want to clear up the confusion about what exactly you need to set it to. It's not just \".ID\" or \".UniqueID\" - the documentation is a bit lacking on this.</p>\n\n<p>You must set it to the UniqueID of the button, <em>relative to</em> the Panel's naming container UniqueID. For example, if your panel UniqueID is\"Body$Content$pnlLogin\" and your login button's UniqueID is \"Body$Content$ucLogin$btnLogin\" (because it's inside a control called \"ucLogin\") then you need to set Panel.DefaultButton to \"ucLogin$btnLogin\".</p>\n\n<p>You can work this out in code as follows. (I couldn't find any class library method for this, but let me know if you find one.)</p>\n\n<pre><code>void SetDefaultButton(Panel panel, IButtonControl button)\n{\n string uniqueId = ((Control)button).UniqueID;\n string panelIdPrefix = panel.NamingContainer.UniqueID + Page.IdSeparator;\n\n if (uniqueId.StartsWith(panelIdPrefix))\n {\n uniqueId = uniqueId.Substring(panelIdPrefix.Length);\n }\n\n panel.DefaultButton = uniqueId;\n}\n</code></pre>\n"
},
{
"answer_id": 893478,
"author": "Kb.",
"author_id": 49544,
"author_profile": "https://Stackoverflow.com/users/49544",
"pm_score": 1,
"selected": false,
"text": "<p>Based on your good answers, made a custom control that<br/>\nenables a Page to have several default buttons based on which panel which is in focus.<br/>\nIt overrides Panel's OnLoad method and DefaultButton property.</p>\n\n<pre><code>public class DefaultButtonPanel:Panel\n{\n protected override void OnLoad(EventArgs e)\n {\n if(!string.IsNullOrEmpty(DefaultButton))\n {\n LinkButton btn = FindControl(DefaultButton) as LinkButton;\n if(btn != null)\n {\n Button defaultButton = new Button {ID = DefaultButton.Replace(Page.IdSeparator.ToString(), \"_\") + \"_Default\", Text = \" \"};\n defaultButton.Style.Add(\"display\", \"none\");\n PostBackOptions p = new PostBackOptions(btn, \"\", null, false, true, true, true, true, btn.ValidationGroup);\n defaultButton.OnClientClick = Page.ClientScript.GetPostBackEventReference(p) + \"; return false;\";\n Controls.Add(defaultButton);\n DefaultButton = defaultButton.ID;\n }\n }\n base.OnLoad(e);\n }\n\n /// <summary>\n /// Set the default button in a Panel.\n /// The UniqueID of the button, must be relative to the Panel's naming container UniqueID. \n /// \n /// For example:\n /// Panel UniqueID is \"Body$Content$pnlLogin\" \n /// Button's UniqueID is \"Body$Content$ucLogin$btnLogin\" \n /// (because it's inside a control called \"ucLogin\") \n /// Set Panel.DefaultButton to \"ucLogin$btnLogin\".\n /// </summary>\n /// <param name=\"panel\"></param>\n /// <param name=\"button\"></param>\n public override string DefaultButton\n {\n get\n {\n return base.DefaultButton;\n }\n\n set\n {\n string uniqueId = value;\n string panelIdPrefix = this.NamingContainer.UniqueID + Page.IdSeparator;\n if (uniqueId.StartsWith(panelIdPrefix))\n {\n uniqueId = uniqueId.Substring(panelIdPrefix.Length);\n }\n base.DefaultButton = uniqueId;\n }\n } \n}\n</code></pre>\n"
},
{
"answer_id": 3014829,
"author": "qwebek",
"author_id": 345052,
"author_profile": "https://Stackoverflow.com/users/345052",
"pm_score": 2,
"selected": false,
"text": "<p>Yo, i found this solution on the net, it worked for me.</p>\n\n<pre><code> <asp:Panel ID=\"panelLogin\" runat=\"server\" DefaultButton=\"Login1$LoginButton\">\n <asp:Login ID=\"Login1\" runat=\"server\" >\n <LayoutTemplate>\n ...\n <asp:Button ID=\"LoginButton\" .../>\n </LayoutTemplate>\n </asp:Login>\n </asp:Panel>\n</code></pre>\n"
},
{
"answer_id": 3419311,
"author": "David Eison",
"author_id": 72670,
"author_profile": "https://Stackoverflow.com/users/72670",
"pm_score": 2,
"selected": false,
"text": "<p>Assuming Login1 is the ID of your login control.</p>\n\n<p>For 'enter' anywhere on the page to submit, add to init in your codebehind:</p>\n\n<pre><code>protected void Page_Init(object sender, EventArgs e)\n{\n this.Form.DefaultButton = Login1.FindControl(\"LoginButton\").UniqueID;\n}\n</code></pre>\n\n<p>For 'enter' to only submit when inside the login control, wrap the login control in an asp:Panel and set \n<code>DefaultButton=\"Login1$LoginButton\"</code> on the panel</p>\n\n<p>Both approaches work fine with master pages.</p>\n"
},
{
"answer_id": 4524232,
"author": "samuel",
"author_id": 510340,
"author_profile": "https://Stackoverflow.com/users/510340",
"pm_score": 1,
"selected": false,
"text": "<p>A solution is provided by embedding the login control inside the panel control and setting the <code>defaultbutton</code> of the panel to the <code>Parent$ID</code> of the button inside Login control works. There's the code:</p>\n\n<pre><code><asp:Panel id=\"panel1\" runat=\"server\" DefaultButton=\"Login1$LoginButton\">\n<asp:Login ID=\"Login1\" runat=\"server\" BackColor=\"#F7F6F3\">\n<LayoutTemplate>\n<table>\n...\n<tr>\n<td><asp:Button ID=\"LoginButton\" runat=\"server\" /></td>\n</tr>\n</table>\n</LayoutTemplate>\n</asp:Login>\n</asp:Panel>\n</code></pre>\n"
},
{
"answer_id": 6833891,
"author": "Jason Marsell",
"author_id": 429825,
"author_profile": "https://Stackoverflow.com/users/429825",
"pm_score": 1,
"selected": false,
"text": "<p><strong>To add a bit more detail and instructions to the posts above, here's a walkthrough:</strong></p>\n\n<p>In the markup of any pages that load your login control, you need to update the html in two places. </p>\n\n<p>First, in the page's form tag, you need to set the default button. See below for how I came up with the name.</p>\n\n<pre><code><form id=\"form1\" runat=\"server\" defaultbutton=\"ucLogin$btnSubmit\">\n</code></pre>\n\n<p>(Naming: The ucLogin part before the dollar sign needs to be the ID of your login control, as declared further down in your page. The btnSubmit part needs to be the ID of the button as it’s named in the login control’s html)</p>\n\n<p>Next, you need to wrap the declaration of your login control in a panel, and set it’s DefaultButton property, as well:</p>\n\n<pre><code><!-- Login Control - use a panel so we can set the default button -->\n<asp:Panel runat=\"server\" ID=\"loginControlPanel\" DefaultButton=\"ucLogin$btnSubmit\"> \n <uc:Login runat=\"server\" ID=\"ucLogin\"/> \n</asp:Panel>\n</code></pre>\n\n<p>That should do it for you.</p>\n"
}
] |
2008/10/14
|
[
"https://Stackoverflow.com/questions/201776",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5486/"
] |
I have an ASP.NET web page with a Login control on it. When I hit Enter, the Login button doesn't fire; instead the page submits, doing nothing.
The standard solution to this that I've found online is to enclose the Login control in a Panel, then set the Panel default button. But apparently that doesn't work so well if the page has a master page. I've tried setting the default button in code with *control*.ID, *control*.ClientID, and *control*.UniqueID, and in each case I get:
>
> The DefaultButton of panelName must be the ID of a control of type IButtonControl.
>
>
>
I'm sure there's a way to do this with JavaScript, but I'd really like to do it with plain old C# code if possible. Is it possible?
|
This should be helpful: <http://weblogs.asp.net/jgalloway/archive/2007/10/03/asp-net-setting-the-defaultbutton-for-a-login-control.aspx>
You can use the following to reference the button within the Login control template:
```
DefaultButton="Login$LoginButton"
```
Basically, you can define a DefaultButton not just on the Form level, but also on individual Panel level, as long as the focus is within the panel, the default button for the panel will be used if you hit "Enter"
|
201,782 |
<p>When manually generating a JSON object or array, it's often easier to leave a trailing comma on the last item in the object or array. For example, code to output from an array of strings might look like (in a C++ like pseudocode):</p>
<pre><code>s.append("[");
for (i = 0; i < 5; ++i) {
s.appendF("\"%d\",", i);
}
s.append("]");
</code></pre>
<p>giving you a string like</p>
<pre><code>[0,1,2,3,4,5,]
</code></pre>
<p>Is this allowed?</p>
|
[
{
"answer_id": 201784,
"author": "Ben Combee",
"author_id": 1323,
"author_profile": "https://Stackoverflow.com/users/1323",
"pm_score": 7,
"selected": false,
"text": "<p>No. The JSON spec, as maintained at <a href=\"http://json.org\" rel=\"noreferrer\">http://json.org</a>, does not allow trailing commas. From what I've seen, some parsers may silently allow them when reading a JSON string, while others will throw errors. For interoperability, you shouldn't include it.</p>\n\n<p>The code above could be restructured, either to remove the trailing comma when adding the array terminator or to add the comma before items, skipping that for the first one.</p>\n"
},
{
"answer_id": 201856,
"author": "brianb",
"author_id": 27892,
"author_profile": "https://Stackoverflow.com/users/27892",
"pm_score": 9,
"selected": true,
"text": "<p>Unfortunately <a href=\"http://www.json.org/\" rel=\"noreferrer\">the JSON specification</a> does not allow a trailing comma. There are a few browsers that will allow it, but generally you need to worry about all browsers.</p>\n\n<p>In general I try turn the problem around, and add the comma before the actual value, so you end up with code that looks like this:</p>\n\n<pre><code>s.append(\"[\");\nfor (i = 0; i < 5; ++i) {\n if (i) s.append(\",\"); // add the comma only if this isn't the first entry\n s.appendF(\"\\\"%d\\\"\", i);\n}\ns.append(\"]\");\n</code></pre>\n\n<p>That extra one line of code in your for loop is hardly expensive...</p>\n\n<p>Another alternative I've used when output a structure to JSON from a dictionary of some form is to always append a comma after each entry (as you are doing above) and then add a dummy entry at the end that has not trailing comma (but that is just lazy ;->).</p>\n\n<p>Doesn't work well with an array unfortunately.</p>\n"
},
{
"answer_id": 202081,
"author": "James Curran",
"author_id": 12725,
"author_profile": "https://Stackoverflow.com/users/12725",
"pm_score": 3,
"selected": false,
"text": "<p>Interestingly, both C & C++ (and I think C#, but I'm not sure) specifically allow the trailing comma -- for exactly the reason given: It make programmaticly generating lists much easier. Not sure why JavaScript didn't follow their lead. </p>\n"
},
{
"answer_id": 207681,
"author": "Rik Heywood",
"author_id": 4012,
"author_profile": "https://Stackoverflow.com/users/4012",
"pm_score": 4,
"selected": false,
"text": "<p>PHP coders may want to check out <strong>implode()</strong>. This takes an array joins it up using a string.</p>\n\n<p>From the <a href=\"http://www.php.net/implode\" rel=\"noreferrer\">docs</a>...</p>\n\n<pre><code>$array = array('lastname', 'email', 'phone');\necho implode(\",\", $array); // lastname,email,phone\n</code></pre>\n"
},
{
"answer_id": 358867,
"author": "Nils",
"author_id": 44232,
"author_profile": "https://Stackoverflow.com/users/44232",
"pm_score": -1,
"selected": false,
"text": "<p>I usually loop over the array and attach a comma after every entry in the string. After the loop I delete the last comma again.</p>\n\n<p>Maybe not the best way, but less expensive than checking every time if it's the last object in the loop I guess.</p>\n"
},
{
"answer_id": 4159435,
"author": "eddie",
"author_id": 505074,
"author_profile": "https://Stackoverflow.com/users/505074",
"pm_score": 0,
"selected": false,
"text": "<p>I keep a current count and compare it to a total count. If the current count is less than the total count, I display the comma.</p>\n\n<p>May not work if you don't have a total count prior to executing the JSON generation.</p>\n\n<p>Then again, if your using PHP 5.2.0 or better, you can just format your response using the JSON API built in.</p>\n"
},
{
"answer_id": 7770323,
"author": "dnshio",
"author_id": 969501,
"author_profile": "https://Stackoverflow.com/users/969501",
"pm_score": 0,
"selected": false,
"text": "<p>From my past experience, I found that different browsers deal with trailing commas in JSON differently. </p>\n\n<p>Both Firefox and Chrome handles it just fine. But IE (All versions) seems to break. I mean really break and stop reading the rest of the script. </p>\n\n<p>Keeping that in mind, and also the fact that it's always nice to write compliant code, I suggest spending the extra effort of making sure that there's no trailing comma. </p>\n\n<p>:) </p>\n"
},
{
"answer_id": 8531175,
"author": "Overflowee",
"author_id": 1101474,
"author_profile": "https://Stackoverflow.com/users/1101474",
"pm_score": 7,
"selected": false,
"text": "<p>Simple, cheap, easy to read, and always works regardless of the specs.</p>\n\n<pre><code>$delimiter = '';\nfor .... {\n print $delimiter.$whatever\n $delimiter = ',';\n}\n</code></pre>\n\n<p>The redundant assignment to $delim is a very small price to pay.\nAlso works just as well if there is no explicit loop but separate code fragments.</p>\n"
},
{
"answer_id": 11495287,
"author": "Tobu",
"author_id": 229753,
"author_profile": "https://Stackoverflow.com/users/229753",
"pm_score": 5,
"selected": false,
"text": "<p>Trailing commas are allowed in JavaScript, but don't work in IE. Douglas Crockford's versionless JSON spec didn't allow them, and because it was versionless this wasn't supposed to change. The ES5 JSON spec allowed them as an extension, but Crockford's <a href=\"https://www.rfc-editor.org/rfc/rfc4627\" rel=\"nofollow noreferrer\">RFC 4627</a> didn't, and ES5 reverted to disallowing them. <a href=\"http://whereswalden.com/2010/09/08/spidermonkey-json-change-trailing-commas-no-longer-accepted/\" rel=\"nofollow noreferrer\">Firefox</a> followed suit. Internet Explorer is why we can't have nice things.</p>\n"
},
{
"answer_id": 23033546,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 4,
"selected": false,
"text": "<p>As it's been already said, JSON spec (based on ECMAScript 3) doesn't allow trailing comma. ES >= 5 allows it, so you can actually use that notation in pure JS. It's been argued about, and some parsers <em>did</em> support it (<a href=\"http://bolinfest.com/essays/json.html\" rel=\"noreferrer\">http://bolinfest.com/essays/json.html</a>, <a href=\"http://whereswalden.com/2010/09/08/spidermonkey-json-change-trailing-commas-no-longer-accepted/\" rel=\"noreferrer\">http://whereswalden.com/2010/09/08/spidermonkey-json-change-trailing-commas-no-longer-accepted/</a>), but it's the spec fact (as shown on <a href=\"http://json.org/\" rel=\"noreferrer\">http://json.org/</a>) that it <em>shouldn't</em> work in JSON. That thing said...</p>\n\n<p>... I'm wondering why no-one pointed out that you can actually split the loop at 0th iteration and use <em>leading</em> comma instead of trailing one to get rid of the comparison code smell and any actual performance overhead in the loop, resulting in a code that's actually shorter, simpler and faster (due to no branching/conditionals in the loop) than other solutions proposed.</p>\n\n<p>E.g. (in a C-style pseudocode similar to OP's proposed code):</p>\n\n<pre><code>s.append(\"[\");\n// MAX == 5 here. if it's constant, you can inline it below and get rid of the comparison\nif ( MAX > 0 ) {\n s.appendF(\"\\\"%d\\\"\", 0); // 0-th iteration\n for( int i = 1; i < MAX; ++i ) {\n s.appendF(\",\\\"%d\\\"\", i); // i-th iteration\n }\n}\ns.append(\"]\");\n</code></pre>\n"
},
{
"answer_id": 25469529,
"author": "user619271",
"author_id": 619271,
"author_profile": "https://Stackoverflow.com/users/619271",
"pm_score": 3,
"selected": false,
"text": "<p>Use JSON5. Don't use JSON. </p>\n\n<ul>\n<li>Objects and arrays can have trailing commas</li>\n<li>Object keys can be unquoted if they're valid identifiers</li>\n<li>Strings can be single-quoted</li>\n<li>Strings can be split across multiple lines</li>\n<li>Numbers can be hexadecimal (base 16)</li>\n<li>Numbers can begin or end with a (leading or trailing) decimal point.</li>\n<li>Numbers can include Infinity and -Infinity.</li>\n<li>Numbers can begin with an explicit plus (+) sign.</li>\n<li>Both inline (single-line) and block (multi-line) comments are allowed.</li>\n</ul>\n\n<p><a href=\"http://json5.org/\" rel=\"noreferrer\">http://json5.org/</a></p>\n\n<p><a href=\"https://github.com/aseemk/json5\" rel=\"noreferrer\">https://github.com/aseemk/json5</a></p>\n"
},
{
"answer_id": 29792864,
"author": "Timoty Weis",
"author_id": 2416998,
"author_profile": "https://Stackoverflow.com/users/2416998",
"pm_score": 2,
"selected": false,
"text": "<p>According to the <a href=\"http://www.json.org/javadoc/org/json/JSONArray.html\" rel=\"nofollow noreferrer\">Class JSONArray specification</a>:</p>\n<ul>\n<li>An extra , (comma) may appear just before the closing bracket.</li>\n<li>The null value will be inserted when there is , (comma) elision.</li>\n</ul>\n<p>So, as I understand it, it should be allowed to write:</p>\n<pre><code>[0,1,2,3,4,5,]\n</code></pre>\n<p>But it could happen that some parsers will return the 7 as item count (like IE8 as Daniel Earwicker pointed out) instead of the expected 6.</p>\n<hr />\n<p>Edited:</p>\n<p>I found this <a href=\"http://www.freeformatter.com/json-validator.html\" rel=\"nofollow noreferrer\">JSON Validator</a> that validates a JSON string against <a href=\"https://www.rfc-editor.org/rfc/rfc4627\" rel=\"nofollow noreferrer\">RFC 4627</a> (The application/json media type for JavaScript Object Notation) and against the JavaScript language specification. Actually here an array with a trailing comma is considered valid just for JavaScript and not for the RFC 4627 specification.</p>\n<p>However, in the RFC 4627 specification is stated that:</p>\n<blockquote>\n<p>2.3. Arrays</p>\n<p>An array structure is represented as square brackets surrounding zero\nor more values (or elements). Elements are separated by commas.</p>\n<pre><code>array = begin-array [ value *( value-separator value ) ] end-array\n</code></pre>\n</blockquote>\n<p>To me this is again an interpretation problem. If you write that <em>Elements are separated by commas</em> (without stating something about special cases, like the last element), it could be understood in both ways.</p>\n<p>P.S. RFC 4627 isn't a standard (as explicitly stated), and is already obsolited by RFC 7159 (which is a proposed standard) <a href=\"https://www.rfc-editor.org/rfc/rfc7159\" rel=\"nofollow noreferrer\">RFC 7159</a></p>\n"
},
{
"answer_id": 47064069,
"author": "feibing",
"author_id": 2529677,
"author_profile": "https://Stackoverflow.com/users/2529677",
"pm_score": 1,
"selected": false,
"text": "<p>It is not recommended, but you can still do something like this to parse it.</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>jsonStr = '[0,1,2,3,4,5,]';\r\nlet data;\r\neval('data = ' + jsonStr);\r\nconsole.log(data)</code></pre>\r\n</div>\r\n</div>\r\n</p>\n"
},
{
"answer_id": 48676317,
"author": "Steven Spungin",
"author_id": 5093961,
"author_profile": "https://Stackoverflow.com/users/5093961",
"pm_score": 1,
"selected": false,
"text": "<p>With Relaxed JSON, you can have trailing commas, <strong>or just leave the commas out</strong>. They are optional.</p>\n\n<p>There is no reason at all commas need to be present to parse a JSON-like document.</p>\n\n<p>Take a look at the Relaxed JSON spec and you will see how 'noisy' the original JSON spec is. Way too many commas and quotes...</p>\n\n<p><a href=\"http://www.relaxedjson.org\" rel=\"nofollow noreferrer\">http://www.relaxedjson.org</a></p>\n\n<p>You can also try out your example using this online RJSON parser and see it get parsed correctly.</p>\n\n<p><a href=\"http://www.relaxedjson.org/docs/converter.html?source=%5B0%2C1%2C2%2C3%2C4%2C5%2C%5D\" rel=\"nofollow noreferrer\">http://www.relaxedjson.org/docs/converter.html?source=%5B0%2C1%2C2%2C3%2C4%2C5%2C%5D</a></p>\n"
},
{
"answer_id": 53362255,
"author": "Zhang Boyang",
"author_id": 1953809,
"author_profile": "https://Stackoverflow.com/users/1953809",
"pm_score": 2,
"selected": false,
"text": "<p>There is a possible way to avoid a if-branch in the loop. </p>\n\n<pre><code>s.append(\"[ \"); // there is a space after the left bracket\nfor (i = 0; i < 5; ++i) {\n s.appendF(\"\\\"%d\\\",\", i); // always add comma\n}\ns.back() = ']'; // modify last comma (or the space) to right bracket\n</code></pre>\n"
},
{
"answer_id": 54937553,
"author": "Gregory Horne 07AD",
"author_id": 11039908,
"author_profile": "https://Stackoverflow.com/users/11039908",
"pm_score": 0,
"selected": false,
"text": "<p>Since a for-loop is used to iterate over an array, or similar iterable data structure, we can use the length of the array as shown,</p>\n\n<pre><code>awk -v header=\"FirstName,LastName,DOB\" '\n BEGIN {\n FS = \",\";\n print(\"[\");\n columns = split(header, column_names, \",\");\n }\n { print(\" {\");\n for (i = 1; i < columns; i++) {\n printf(\" \\\"%s\\\":\\\"%s\\\",\\n\", column_names[i], $(i));\n }\n printf(\" \\\"%s\\\":\\\"%s\\\"\\n\", column_names[i], $(i));\n print(\" }\");\n }\n END { print(\"]\"); } ' datafile.txt\n</code></pre>\n\n<p>With datafile.txt containing,</p>\n\n<pre><code> Angela,Baker,2010-05-23\n Betty,Crockett,1990-12-07\n David,Done,2003-10-31\n</code></pre>\n"
},
{
"answer_id": 58878371,
"author": "theking2",
"author_id": 718960,
"author_profile": "https://Stackoverflow.com/users/718960",
"pm_score": 1,
"selected": false,
"text": "<p>As stated it is not allowed. But in JavaScript this is:</p>\n\n<pre><code>var a = Array()\nfor(let i=1; i<=5; i++) {\n a.push(i)\n}\nvar s = \"[\" + a.join(\",\") + \"]\"\n</code></pre>\n\n<p>(works fine in Firefox, Chrome, Edge, IE11, and without the let in IE9, 8, 7, 5)</p>\n"
},
{
"answer_id": 62909779,
"author": "Beni Cherniavsky-Paskin",
"author_id": 239657,
"author_profile": "https://Stackoverflow.com/users/239657",
"pm_score": 2,
"selected": false,
"text": "<p>No. The "railroad diagrams" in <a href=\"https://json.org\" rel=\"nofollow noreferrer\">https://json.org</a> are an exact translation of the spec and make it clear a <code>,</code> always comes before a <code>value</code>, never directly before <code>]</code>:</p>\n<p><a href=\"https://i.stack.imgur.com/1CcmB.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/1CcmB.png\" alt=\"railroad diagram for array\" /></a></p>\n<p>or <code>}</code>:</p>\n<p><a href=\"https://i.stack.imgur.com/DQhz5.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/DQhz5.png\" alt=\"railroad diagram for object\" /></a></p>\n"
},
{
"answer_id": 64065832,
"author": "Roland",
"author_id": 1845672,
"author_profile": "https://Stackoverflow.com/users/1845672",
"pm_score": 3,
"selected": false,
"text": "<p>Rather than engage in a debating club, I would adhere to the principle of <code>Defensive Programming</code> by combining both simple techniques in order to simplify interfacing with others:</p>\n<ul>\n<li><p>As a developer of an app that <strong>receives</strong> json data, I'd be <strong>relaxed</strong> and <strong>allow</strong> the trailing comma.</p>\n</li>\n<li><p>When developing an app that <strong>writes</strong> json, I'd be <strong>strict</strong> and use one of the clever techniques of the other answers to only add commas between items and <strong>avoid</strong> the trailing comma.</p>\n</li>\n</ul>\n<p>There are bigger problems to be solved...</p>\n"
},
{
"answer_id": 72644879,
"author": "Prudhvik Chirunomula",
"author_id": 9733388,
"author_profile": "https://Stackoverflow.com/users/9733388",
"pm_score": 0,
"selected": false,
"text": "<pre><code>String l = "[" + List<int>.generate(5, (i) => i + 1).join(",") + "]";\n</code></pre>\n"
},
{
"answer_id": 74167082,
"author": "Qwert Yuiop",
"author_id": 10135157,
"author_profile": "https://Stackoverflow.com/users/10135157",
"pm_score": 0,
"selected": false,
"text": "<p>Using a trailing comma is not allowed for json. A solution I like, which you could do if you're not writing for an external recipient but for your own project, is to just strip (or replace by whitespace) the trailing comma on the receiving end before feeding it to the json parser. I do this for the trailing comma in the outermost json object. The convenient thing is then if you add an object at the end, you don't have to add a comma to the now second last object. This also makes for cleaner diffs if your config file is in a version control system, since it will only show the lines of the stuff you actually added.</p>\n<pre><code> char* str = readFile("myConfig.json");\n char* chr = strrchr(str, '}') - 1;\n int i = 0;\n while( chr[i] == ' ' || chr[i] == '\\n' ){\n i--;\n }\n if( chr[i] == ',' ) chr[i] = ' ';\n JsonParser parser;\n parser.parse(str);\n\n</code></pre>\n"
}
] |
2008/10/14
|
[
"https://Stackoverflow.com/questions/201782",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1323/"
] |
When manually generating a JSON object or array, it's often easier to leave a trailing comma on the last item in the object or array. For example, code to output from an array of strings might look like (in a C++ like pseudocode):
```
s.append("[");
for (i = 0; i < 5; ++i) {
s.appendF("\"%d\",", i);
}
s.append("]");
```
giving you a string like
```
[0,1,2,3,4,5,]
```
Is this allowed?
|
Unfortunately [the JSON specification](http://www.json.org/) does not allow a trailing comma. There are a few browsers that will allow it, but generally you need to worry about all browsers.
In general I try turn the problem around, and add the comma before the actual value, so you end up with code that looks like this:
```
s.append("[");
for (i = 0; i < 5; ++i) {
if (i) s.append(","); // add the comma only if this isn't the first entry
s.appendF("\"%d\"", i);
}
s.append("]");
```
That extra one line of code in your for loop is hardly expensive...
Another alternative I've used when output a structure to JSON from a dictionary of some form is to always append a comma after each entry (as you are doing above) and then add a dummy entry at the end that has not trailing comma (but that is just lazy ;->).
Doesn't work well with an array unfortunately.
|
201,791 |
<p>I am currently coding a simple Data Access Layer, and I was wondering which type I should expose to the other layers.</p>
<p>I am going to internally implement the Data as a List<>, but I remember reading something about not exposing the List type to the consumers if not needed.</p>
<pre><code>public List<User> GetAllUsers() // non C# users: that means List of User :)
</code></pre>
<p>Do you know why (google didn't help)? What do you usually expose for that kind of stuff? IList? IEnumerable?</p>
|
[
{
"answer_id": 201803,
"author": "Joel Coehoorn",
"author_id": 3043,
"author_profile": "https://Stackoverflow.com/users/3043",
"pm_score": 2,
"selected": false,
"text": "<p>Definitely an ISomething. Using an interface will reduce coupling and make it easier to change details of your data layer's implementation down the road. Which interface depends on the circumstances. IList is good, but sometimes you may need ICollection functionality or want to specify values that are ReadOnly.</p>\n"
},
{
"answer_id": 201805,
"author": "Konrad Rudolph",
"author_id": 1968,
"author_profile": "https://Stackoverflow.com/users/1968",
"pm_score": 4,
"selected": true,
"text": "<p>Usually it's best to expose the least powerful interface that the user can still meaningfully work with. If the user just needs some enumerable data, return <code>IEnumerable<User></code>. If that's not enough because the user needs to be able to modify the list (attention! shouldn't often be the case), return an <code>IList<User></code>.</p>\n\n<h2>/EDIT:</h2>\n\n<p>Joel asks a valid question in his comment: Why indeed expose the least powerful interface instead of granting the user maximum power? (paraphrased)</p>\n\n<p>The idea behind this is that the method returning the data might not expect the user to modify its content: Another method of the class might still expect the list to be non-empty after a reference to it was returned. Imagine the user removes all data from the list. The other method now has to make an additional check that ele might have been unnecessary.</p>\n\n<p>More importantly, this exposes parts of the internal implementation through the return type. If I need to change the implementation in the future so that it no longer uses an <code>IList</code> container, I have a problem: I either need to change the method contract, introducing a build-breaking change. Or I need to copy the data into a list container.</p>\n\n<p>As an example, imagine that an efficient implementation uses a Dictionary and just returns the <code>Values</code> collection which doesn't implement <code>IList</code>.</p>\n"
},
{
"answer_id": 201835,
"author": "Roger Lipscombe",
"author_id": 8446,
"author_profile": "https://Stackoverflow.com/users/8446",
"pm_score": 2,
"selected": false,
"text": "<p>You should think carefully before returning IEnumerable. If the underlying code is using \"yield\" to generate the IEnumerable, or is using LINQ, then you'll end up holding open any resources used.</p>\n\n<p>You should copy the IEnumerable into another IEnumerable before returning it. By using IList, you make this a requirement, so that nobody can inadvertently return an IEnumerable.</p>\n\n<p>On the other hand, returning an IList implies to the caller that they can change the returned list.</p>\n"
}
] |
2008/10/14
|
[
"https://Stackoverflow.com/questions/201791",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5789/"
] |
I am currently coding a simple Data Access Layer, and I was wondering which type I should expose to the other layers.
I am going to internally implement the Data as a List<>, but I remember reading something about not exposing the List type to the consumers if not needed.
```
public List<User> GetAllUsers() // non C# users: that means List of User :)
```
Do you know why (google didn't help)? What do you usually expose for that kind of stuff? IList? IEnumerable?
|
Usually it's best to expose the least powerful interface that the user can still meaningfully work with. If the user just needs some enumerable data, return `IEnumerable<User>`. If that's not enough because the user needs to be able to modify the list (attention! shouldn't often be the case), return an `IList<User>`.
/EDIT:
------
Joel asks a valid question in his comment: Why indeed expose the least powerful interface instead of granting the user maximum power? (paraphrased)
The idea behind this is that the method returning the data might not expect the user to modify its content: Another method of the class might still expect the list to be non-empty after a reference to it was returned. Imagine the user removes all data from the list. The other method now has to make an additional check that ele might have been unnecessary.
More importantly, this exposes parts of the internal implementation through the return type. If I need to change the implementation in the future so that it no longer uses an `IList` container, I have a problem: I either need to change the method contract, introducing a build-breaking change. Or I need to copy the data into a list container.
As an example, imagine that an efficient implementation uses a Dictionary and just returns the `Values` collection which doesn't implement `IList`.
|
201,816 |
<p>I'm trying to run a particular JUnit test by hand on a Windows XP command line, which has an unusually high number of elements in the class path. I've tried several variations, such as:</p>
<pre><code>set CLASS_PATH=C:\path\a\b\c;C:\path\e\f\g;....
set CLASS_PATH=%CLASS_PATH%;C:\path2\a\b\c;C:\path2\e\f\g;....
...
C:\apps\jdk1.6.0_07\bin\java.exe -client oracle.jdevimpl.junit.runner.TestRunner com.myco.myClass.MyTest testMethod
</code></pre>
<p>(Other variations are setting the classpath all on one line, setting the classpath via -classpath as an argument to java"). It always comes down to the console throwing up it's hands with this error:</p>
<pre><code>The input line is too long.
The syntax of the command is incorrect.
</code></pre>
<p>This is a JUnit test testing a rather large existing legacy project, so no suggestions about rearranging my directory structure to something more reasonable, those types of solutions are out for now. I was just trying to gen up a quick test against this project and run it on the command line, and the console is stonewalling me. Help!</p>
|
[
{
"answer_id": 201857,
"author": "Nick Berardi",
"author_id": 17,
"author_profile": "https://Stackoverflow.com/users/17",
"pm_score": -1,
"selected": false,
"text": "<p>Have you tried stacking them?</p>\n\n<pre><code>set CLASS_PATH = c:\\path\nset ALT_A = %CLASS_PATH%\\a\\b\\c;\nset ALT_B = %CLASS_PATH%\\e\\f\\g;\n...\n\nset ALL_PATHS = %CLASS_PATH%;%ALT_A%;%ALT_B%\n</code></pre>\n"
},
{
"answer_id": 201858,
"author": "Huibert Gill",
"author_id": 1254442,
"author_profile": "https://Stackoverflow.com/users/1254442",
"pm_score": 0,
"selected": false,
"text": "<p>I think you are up the creek without a paddle here.\nThe commandline has a limit for arguments to call a programm.</p>\n\n<p>I have 2 sugestion you could try.\nFirst, prior to running the junit tests, you can let a script/ant_task create JARs of the various classes on the classpath.\nThen you can put the JARs on the classpath, which should be shorter.</p>\n\n<p>Another way you could try is to create an antscript to run JUNIT,\nin ANT there should not be such a limit for classpath entries.</p>\n"
},
{
"answer_id": 201876,
"author": "Tomalak",
"author_id": 18771,
"author_profile": "https://Stackoverflow.com/users/18771",
"pm_score": 2,
"selected": false,
"text": "<p><em>(I suppose you do not really mean DOS, but refer to cmd.exe.)</em></p>\n\n<p>I think it is less a CLASSPATH limitation than an environment size/environment variable size limit. On XP, individual environment variables can be 8k in size, the entire environment is limited to 64k. I can't see you would hit that limit.</p>\n\n<p>There is a limit on windows that restricts the length of a command line, on WindowsNT+ it is 8k for cmd.exe. A set command is subject to that restriction. Can it be you have more than 8k worth of directories in your set command? You may be out of luck, then - even if you split them up like <a href=\"https://stackoverflow.com/questions/201816/how-to-set-a-long-java-classpath-in-msdoswindows#201857\">Nick Berardi</a> suggested.</p>\n"
},
{
"answer_id": 201969,
"author": "Chris Noe",
"author_id": 14749,
"author_profile": "https://Stackoverflow.com/users/14749",
"pm_score": 7,
"selected": true,
"text": "<p>The Windows command line is very limiting in this regard. A workaround is to create a \"pathing jar\". This is a jar containing only a <code>Manifest.mf</code> file, whose <code>Class-Path</code> specifies the disk paths of your long list of jars, etc. Now just add this <em>pathing jar</em> to your command line classpath. This is usually more convenient than packaging the actual resources together.</p>\n\n<p>As I recall, the disk paths can be relative to the <em>pathing jar</em> itself. So the <code>Manifest.mf</code> might look something like this:</p>\n\n<pre><code>Class-Path: this.jar that.jar ../lib/other.jar\n</code></pre>\n\n<p>If your <em>pathing jar</em> contains mainly foundational resources, then it won't change too frequently, but you will probably still want to generate it somewhere in your build. For example:</p>\n\n<pre><code><jar destfile=\"pathing.jar\">\n <manifest>\n <attribute name=\"Class-Path\" value=\"this.jar that.jar ../lib/other.jar\"/>\n </manifest>\n</jar>\n</code></pre>\n"
},
{
"answer_id": 202034,
"author": "johnstok",
"author_id": 27929,
"author_profile": "https://Stackoverflow.com/users/27929",
"pm_score": 4,
"selected": false,
"text": "<p>Since Java 6 you can use <a href=\"https://docs.oracle.com/javase/6/docs/technotes/tools/windows/classpath.html#Understanding\" rel=\"nofollow noreferrer\">classpath wildcards</a>.</p>\n\n<p>Example: <code>foo/*</code>, refers to all .jar files in the directory <code>foo</code></p>\n\n<ul>\n<li>this will not match class files (only jar files). To match both use: <code>foo;foo/*</code> or <code>foo/*;foo</code>. The order determines what is loaded first.</li>\n<li>The search is NOT recursive</li>\n</ul>\n"
},
{
"answer_id": 202056,
"author": "matt b",
"author_id": 4249,
"author_profile": "https://Stackoverflow.com/users/4249",
"pm_score": 0,
"selected": false,
"text": "<p>As HuibertGill mentions, I would wrap this in an Ant build script just so that you don't have to manage all of this yourself.</p>\n"
},
{
"answer_id": 202199,
"author": "anjanb",
"author_id": 11142,
"author_profile": "https://Stackoverflow.com/users/11142",
"pm_score": 1,
"selected": false,
"text": "<p>If I were in your shoes, I would download the junction utility from MS : <a href=\"http://technet.microsoft.com/en-us/sysinternals/bb896768.aspx\" rel=\"nofollow noreferrer\">http://technet.microsoft.com/en-us/sysinternals/bb896768.aspx</a> and then map your \n\"C:\\path\" to say, \"z:\\\" and \"c:\\path2\" to say, \"y:\\\". This way, you will be reducing 4 characters per item in your <code>classpath</code>. <br></p>\n\n<pre><code>set CLASS_PATH=C:\\path\\a\\b\\c;C:\\path\\e\\f\\g;\nset CLASS_PATH=%CLASS_PATH%;C:\\path2\\a\\b\\c;C:\\path2\\e\\f\\g;\n</code></pre>\n\n<p>Now, your classpath will be : <br></p>\n\n<pre><code>set CLASS_PATH=z\\a\\b\\c;z\\e\\f\\g;\nset CLASS_PATH=%CLASS_PATH%;y:\\a\\b\\c;y:\\e\\f\\g;\n</code></pre>\n\n<p>It might do more depending on your actual <code>classpath</code>.</p>\n"
},
{
"answer_id": 11416271,
"author": "Shivananda Sahu",
"author_id": 1515205,
"author_profile": "https://Stackoverflow.com/users/1515205",
"pm_score": 0,
"selected": false,
"text": "<p>You could try this</p>\n\n<hr>\n\n<pre><code>@echo off\nset A=D:\\jdk1.6.0_23\\bin\nset B=C:\\Documents and Settings\\674205\\Desktop\\JavaProj\nset PATH=\"%PATH%;%A%;\"\nset CLASSPATH=\"%CLASSPATH%;%B%;\"\n</code></pre>\n\n<p>go to a command prompt and run it twice(no idea why....i have to do so on a windows XP machine)\nalso the paths r set only for the current command prompt session</p>\n"
},
{
"answer_id": 40128455,
"author": "Snehal Masne",
"author_id": 1792003,
"author_profile": "https://Stackoverflow.com/users/1792003",
"pm_score": 0,
"selected": false,
"text": "<p>There was no solution to the issue other than somehow making the classpath shorter by moving the jar files into a folder like \"C:\\jars\".</p>\n"
},
{
"answer_id": 54270831,
"author": "Raman",
"author_id": 430128,
"author_profile": "https://Stackoverflow.com/users/430128",
"pm_score": 4,
"selected": false,
"text": "<h1>Use An \"Argument File\" on Java 9+</h1>\n\n<p>In Java 9+, the java executable supports providing arguments via a file. See \n<a href=\"https://docs.oracle.com/javase/9/tools/java.htm#JSWOR-GUID-4856361B-8BFD-4964-AE84-121F5F6CF111\" rel=\"noreferrer\">https://docs.oracle.com/javase/9/tools/java.htm#JSWOR-GUID-4856361B-8BFD-4964-AE84-121F5F6CF111</a>.</p>\n\n<p>This mechanism is explicitly intended to solve the problem of OS limitations on command lengths:</p>\n\n<blockquote>\n <p>You can shorten or simplify the java command by using @argument files\n to specify a text file that contains arguments, such as options and\n class names, passed to the java command. <strong>This let’s you to create java\n commands of any length on any operating system.</strong></p>\n \n <p>In the command line, use the at sign (@) prefix to identify an\n argument file that contains java options and class names. When the\n java command encounters a file beginning with the at sign (@) , it\n expands the contents of that file into an argument list just as they\n would be specified on the command line.</p>\n</blockquote>\n\n<p>This is the \"right\" solution, if you are running version 9 or above. This mechanism simply modifies how the argument is provided to the JVM, and <em>is therefore 100% compatible with any framework or application</em>, regardless of how they do classloading i.e. it is completely equivalent to simply providing the argument on the command line as usual. This is not true for manifest-based workarounds to this OS limitation.</p>\n\n<p>An example of this is:</p>\n\n<p>Original command:</p>\n\n<p><code>java -cp c:\\foo\\bar.jar;c:\\foo\\baz.jar</code></p>\n\n<p>can be rewritten as:</p>\n\n<p><code>java @c:\\path\\to\\cparg</code></p>\n\n<p>where <code>c:\\path\\to\\cparg</code> is a file which contains:</p>\n\n<pre><code>-cp c:\\foo\\bar.jar;c:\\foo\\baz.jar\n</code></pre>\n\n<p>This \"argument file\" also supports line continuation characters and quoting for properly handling spaces in paths e.g.</p>\n\n<pre><code>-cp \"\\\nc:\\foo\\bar.jar;\\\nc:\\foo\\baz.jar\"\n</code></pre>\n\n<h2>Gradle</h2>\n\n<p>If you are encountering this issue in Gradle, see this plugin, which converts your classpath automatically into an \"argument file\" and provides that to the JVM when doing exec or test tasks on Windows. On Linux or other operating systems it does nothing by default, though an optional configuration value can be used to apply the transformation regardless of OS.</p>\n\n<p><a href=\"https://github.com/redocksoft/classpath-to-file-gradle-plugin\" rel=\"noreferrer\">https://github.com/redocksoft/classpath-to-file-gradle-plugin</a></p>\n\n<p>(disclaimer: I am the author)</p>\n\n<p>See also this related Gradle issue -- hopefully this capability will eventually be integrated into Gradle core: <a href=\"https://github.com/gradle/gradle/issues/1989\" rel=\"noreferrer\">https://github.com/gradle/gradle/issues/1989</a>.</p>\n"
},
{
"answer_id": 55300229,
"author": "user1921819",
"author_id": 1921819,
"author_profile": "https://Stackoverflow.com/users/1921819",
"pm_score": 2,
"selected": false,
"text": "<p>Thanks to <strong>Raman</strong> for introducing a new solution to a pathing problem for Java 9+. I made a hack to <code>bootRun</code> task that allows using everything already evaluated by gradle to run java with argument files. Not very elegant but working.</p>\n\n<pre><code>// Fix long path problem on Windows by utilizing java Command-Line Argument Files \n// https://docs.oracle.com/javase/9/tools/java.htm#JSWOR-GUID-4856361B-8BFD-4964-AE84-121F5F6CF111 \n// The task creates the command-line argument file with classpath\n// Then we specify the args parameter with path to command-line argument file and main class\n// Then we clear classpath and main parameters\n// As arguments are applied after applying classpath and main class last step \n// is done to cheat gradle plugin: we will skip classpath and main and manually\n// apply them through args\n// Hopefully at some point gradle will do this automatically \n// https://github.com/gradle/gradle/issues/1989 \n\nif (Os.isFamily(Os.FAMILY_WINDOWS)) {\n bootRun {\n doFirst {\n def argumentFilePath = \"build/javaArguments.txt\"\n def argumentFile = project.file(argumentFilePath)\n def writer = argumentFile.newPrintWriter()\n writer.print('-cp ')\n writer.println(classpath.join(';'))\n writer.close()\n\n args = [\"@${argumentFile.absolutePath}\", main]\n classpath = project.files()\n main = ''\n }\n }\n}\n\n</code></pre>\n"
},
{
"answer_id": 59370815,
"author": "Trushit Shekhda",
"author_id": 12444527,
"author_profile": "https://Stackoverflow.com/users/12444527",
"pm_score": 0,
"selected": false,
"text": "<p>Fix for windows gradle long classpath issue. Fixes JavaExec tasks that error out with message \"CreateProcess error=206, The filename or extension is too long\"</p>\n\n<p>Using the plugins DSL:</p>\n\n<pre><code>plugins {\n id \"com.github.ManifestClasspath\" version \"0.1.0-RELEASE\"\n}\n</code></pre>\n\n<p>Using legacy plugin application:</p>\n\n<pre><code>buildscript {\n repositories {\n maven {\n url \"https://plugins.gradle.org/m2/\"\n }\n }\n dependencies {\n classpath \"gradle.plugin.com.github.viswaramamoorthy:gradle-util-plugins:0.1.0-RELEASE\"\n }\n}\n\napply plugin: \"com.github.ManifestClasspath\"\n</code></pre>\n"
},
{
"answer_id": 67805810,
"author": "user16106533",
"author_id": 16106533,
"author_profile": "https://Stackoverflow.com/users/16106533",
"pm_score": 0,
"selected": false,
"text": "<p>I had a similar issue here with a giant classpath definition inside a .bat file.\nThe problem was that this class path was also including the execution path into the giant path, its ok, its make sense.\nIn this context, the software was not able to run and the message "The input line is too long" appeared everytime.</p>\n<p>Solution:\nI just moved the all files to a shorter position.\nFor instance, I was trying to execute the software in a directory tree like:\nc:\\softwares\\testing\\testing_solution\\one</p>\n<p>and I moved the whole structure to a point like this</p>\n<p>c:\\test</p>\n<p>The software worked very well.\nIt is not the best option, I know, but might help some one who is looking to a fast solution.</p>\n<p>Tks</p>\n"
}
] |
2008/10/14
|
[
"https://Stackoverflow.com/questions/201816",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/13140/"
] |
I'm trying to run a particular JUnit test by hand on a Windows XP command line, which has an unusually high number of elements in the class path. I've tried several variations, such as:
```
set CLASS_PATH=C:\path\a\b\c;C:\path\e\f\g;....
set CLASS_PATH=%CLASS_PATH%;C:\path2\a\b\c;C:\path2\e\f\g;....
...
C:\apps\jdk1.6.0_07\bin\java.exe -client oracle.jdevimpl.junit.runner.TestRunner com.myco.myClass.MyTest testMethod
```
(Other variations are setting the classpath all on one line, setting the classpath via -classpath as an argument to java"). It always comes down to the console throwing up it's hands with this error:
```
The input line is too long.
The syntax of the command is incorrect.
```
This is a JUnit test testing a rather large existing legacy project, so no suggestions about rearranging my directory structure to something more reasonable, those types of solutions are out for now. I was just trying to gen up a quick test against this project and run it on the command line, and the console is stonewalling me. Help!
|
The Windows command line is very limiting in this regard. A workaround is to create a "pathing jar". This is a jar containing only a `Manifest.mf` file, whose `Class-Path` specifies the disk paths of your long list of jars, etc. Now just add this *pathing jar* to your command line classpath. This is usually more convenient than packaging the actual resources together.
As I recall, the disk paths can be relative to the *pathing jar* itself. So the `Manifest.mf` might look something like this:
```
Class-Path: this.jar that.jar ../lib/other.jar
```
If your *pathing jar* contains mainly foundational resources, then it won't change too frequently, but you will probably still want to generate it somewhere in your build. For example:
```
<jar destfile="pathing.jar">
<manifest>
<attribute name="Class-Path" value="this.jar that.jar ../lib/other.jar"/>
</manifest>
</jar>
```
|
201,826 |
<p><strong>ASPX Code</strong></p>
<pre>
<asp:RadioButtonList ID="rbServer" runat="server" >
<asp:ListItem Value=<%=ServerDeveloper%>> Developer </asp:ListItemv
<asp:ListItem Value="dev.ahsvendor.com"> dev.test.com</asp:ListItem>
<asp:ListItem Value="staging.ahsvendor.com"> staging.test.com</asp:ListItem>
</asp:RadioButtonList>
</pre>
<p><strong>ASPX.CS - Codebehind</strong></p>
<pre>
const string ServerDeveloper = "developer";
</pre>
<p><strong>ASPX Error</strong>: Code blocks are not supported in this context.</p>
<p><strong>Question:</strong> So what is the correct way to tie an dropdown/radio buttion/... ASPX value to a constant that is shared with the CodeBehind code?</p>
<p>I know that I could do rbServer.Add.Item("developer") [from the CodeBehind], but is there a way to achieve it from the Presentation side of things?</p>
|
[
{
"answer_id": 201842,
"author": "Cory Foy",
"author_id": 4083,
"author_profile": "https://Stackoverflow.com/users/4083",
"pm_score": 3,
"selected": true,
"text": "<p>Would it be:</p>\n\n<pre>rbServer.Items.Add(ServerDeveloper)</pre>\n\n<p>Ok, so since you want to do it from presentation...It is possible, but horribly ugly:</p>\n\n<pre>\n<div>\n<% rbServer.Items.Add(new ListItem(\"Dev\", ServerDeveloper)); %>\n<asp:RadioButtonList ID=\"rbServer\" runat=\"server\">\n <asp:ListItem Value=\"Blah\">Blah</asp:ListItem>\n</asp:RadioButtonList>\n</div>\n</pre>\n\n<p>Note that the code block has to be <em>above</em> the markup - if you put it below, it doesn't seem to work. Note also that the const will have to be protected in order for the page to access it. This feels terribly like a hack to me, but there it is.</p>\n"
},
{
"answer_id": 201845,
"author": "Mitchel Sellers",
"author_id": 13279,
"author_profile": "https://Stackoverflow.com/users/13279",
"pm_score": 0,
"selected": false,
"text": "<p>In retrospect, the better solution would be to add it from the codebehind using rbServer.Items.Add()</p>\n"
},
{
"answer_id": 201852,
"author": "Torbjørn",
"author_id": 22621,
"author_profile": "https://Stackoverflow.com/users/22621",
"pm_score": 0,
"selected": false,
"text": "<p>In most cases I add the ListItems to the List in the codebehind, not in the markup. I'm guessing that will solve your problem (even though I think we are missing some information here). Create new ListItems and add them to rbServer's Items collection.</p>\n"
},
{
"answer_id": 3010487,
"author": "Josh",
"author_id": 175121,
"author_profile": "https://Stackoverflow.com/users/175121",
"pm_score": 0,
"selected": false,
"text": "<p>I generally try to avoid the RadioButtonList control for the very reason that you have posted. Although I haven't come up with an easy to use alternative :(</p>\n"
}
] |
2008/10/14
|
[
"https://Stackoverflow.com/questions/201826",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/27912/"
] |
**ASPX Code**
```
<asp:RadioButtonList ID="rbServer" runat="server" >
<asp:ListItem Value=<%=ServerDeveloper%>> Developer </asp:ListItemv
<asp:ListItem Value="dev.ahsvendor.com"> dev.test.com</asp:ListItem>
<asp:ListItem Value="staging.ahsvendor.com"> staging.test.com</asp:ListItem>
</asp:RadioButtonList>
```
**ASPX.CS - Codebehind**
```
const string ServerDeveloper = "developer";
```
**ASPX Error**: Code blocks are not supported in this context.
**Question:** So what is the correct way to tie an dropdown/radio buttion/... ASPX value to a constant that is shared with the CodeBehind code?
I know that I could do rbServer.Add.Item("developer") [from the CodeBehind], but is there a way to achieve it from the Presentation side of things?
|
Would it be:
```
rbServer.Items.Add(ServerDeveloper)
```
Ok, so since you want to do it from presentation...It is possible, but horribly ugly:
```
<div>
<% rbServer.Items.Add(new ListItem("Dev", ServerDeveloper)); %>
<asp:RadioButtonList ID="rbServer" runat="server">
<asp:ListItem Value="Blah">Blah</asp:ListItem>
</asp:RadioButtonList>
</div>
```
Note that the code block has to be *above* the markup - if you put it below, it doesn't seem to work. Note also that the const will have to be protected in order for the page to access it. This feels terribly like a hack to me, but there it is.
|
201,827 |
<p>Ok, strange setup, strange question. We've got a Client and an Admin web application for our SaaS app, running on asp.net-2.0/iis-6. The Admin application can change options displayed on the Client application. When those options are saved in the Admin we call a Webservice on the Client, from the Admin, to flush our cache of the options for that specific account. </p>
<p>Recently we started giving our Client application >1 Worker Processes, thus causing the cache of options to only be cleared on 1 of the currently running Worker Processes.</p>
<p>So, I obviously have other avenues of fixing this problem (however input is appreciated), but <strong>my question is:</strong> is there any way to target/iterate through each Worker Processes via a web request?</p>
|
[
{
"answer_id": 201842,
"author": "Cory Foy",
"author_id": 4083,
"author_profile": "https://Stackoverflow.com/users/4083",
"pm_score": 3,
"selected": true,
"text": "<p>Would it be:</p>\n\n<pre>rbServer.Items.Add(ServerDeveloper)</pre>\n\n<p>Ok, so since you want to do it from presentation...It is possible, but horribly ugly:</p>\n\n<pre>\n<div>\n<% rbServer.Items.Add(new ListItem(\"Dev\", ServerDeveloper)); %>\n<asp:RadioButtonList ID=\"rbServer\" runat=\"server\">\n <asp:ListItem Value=\"Blah\">Blah</asp:ListItem>\n</asp:RadioButtonList>\n</div>\n</pre>\n\n<p>Note that the code block has to be <em>above</em> the markup - if you put it below, it doesn't seem to work. Note also that the const will have to be protected in order for the page to access it. This feels terribly like a hack to me, but there it is.</p>\n"
},
{
"answer_id": 201845,
"author": "Mitchel Sellers",
"author_id": 13279,
"author_profile": "https://Stackoverflow.com/users/13279",
"pm_score": 0,
"selected": false,
"text": "<p>In retrospect, the better solution would be to add it from the codebehind using rbServer.Items.Add()</p>\n"
},
{
"answer_id": 201852,
"author": "Torbjørn",
"author_id": 22621,
"author_profile": "https://Stackoverflow.com/users/22621",
"pm_score": 0,
"selected": false,
"text": "<p>In most cases I add the ListItems to the List in the codebehind, not in the markup. I'm guessing that will solve your problem (even though I think we are missing some information here). Create new ListItems and add them to rbServer's Items collection.</p>\n"
},
{
"answer_id": 3010487,
"author": "Josh",
"author_id": 175121,
"author_profile": "https://Stackoverflow.com/users/175121",
"pm_score": 0,
"selected": false,
"text": "<p>I generally try to avoid the RadioButtonList control for the very reason that you have posted. Although I haven't come up with an easy to use alternative :(</p>\n"
}
] |
2008/10/14
|
[
"https://Stackoverflow.com/questions/201827",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/27915/"
] |
Ok, strange setup, strange question. We've got a Client and an Admin web application for our SaaS app, running on asp.net-2.0/iis-6. The Admin application can change options displayed on the Client application. When those options are saved in the Admin we call a Webservice on the Client, from the Admin, to flush our cache of the options for that specific account.
Recently we started giving our Client application >1 Worker Processes, thus causing the cache of options to only be cleared on 1 of the currently running Worker Processes.
So, I obviously have other avenues of fixing this problem (however input is appreciated), but **my question is:** is there any way to target/iterate through each Worker Processes via a web request?
|
Would it be:
```
rbServer.Items.Add(ServerDeveloper)
```
Ok, so since you want to do it from presentation...It is possible, but horribly ugly:
```
<div>
<% rbServer.Items.Add(new ListItem("Dev", ServerDeveloper)); %>
<asp:RadioButtonList ID="rbServer" runat="server">
<asp:ListItem Value="Blah">Blah</asp:ListItem>
</asp:RadioButtonList>
</div>
```
Note that the code block has to be *above* the markup - if you put it below, it doesn't seem to work. Note also that the const will have to be protected in order for the page to access it. This feels terribly like a hack to me, but there it is.
|
201,829 |
<p>I have a format file where I want one of the columns to be "group". I'm auto-generating the format file and a client wants to upload a file with "group" as one of the columns. I could restrict it so they can't use SQL keywords, but then I need a function to determine if a column name is a SQL keyword, so I'd like to support the user being able to name their clients however they want. I'm wondering if this is possible. I tried using brackets, but that didn't appear to work. My file looks like:</p>
<pre>
8.0
1
1 SQLCHAR 0 0 "\r\n" 1 [group] SQL_Latin1_General_CP1_CI_AS
</pre>
|
[
{
"answer_id": 203931,
"author": "Ed Harper",
"author_id": 27825,
"author_profile": "https://Stackoverflow.com/users/27825",
"pm_score": 1,
"selected": false,
"text": "<p>I tested this out several different ways on SQL 2005 SP2 (target databases in both compatibility modes 80 and 90) and it works OK for me using the SQL 2005 version of bcp.</p>\n\n<p>However, I also tested it with the SQL 2000 version of bcp, and that failed with </p>\n\n<pre><code>Error = [Microsoft][ODBC SQL Server Driver][SQL Server]Incorrect syntax near the keyword 'group'.\n</code></pre>\n\n<p>which I guess is what you're getting.</p>\n\n<p>Are you able to upgrade the system where you're running bcp to use the SQL 2005 client tools?</p>\n\n<p>If you believe that you have already upgraded, check your PATH environment variable to confirm that </p>\n\n<pre><code>C:\\Program Files\\Microsoft SQL Server\\90\\Tools\\binn\\\n</code></pre>\n\n<p>(adjusted for your installation) appears before</p>\n\n<pre><code>C:\\Program Files\\Microsoft SQL Server\\80\\Tools\\BINN\n</code></pre>\n\n<p>otherwise the SQL 2000 command line tools will be used in preference to the SQL 2005</p>\n"
},
{
"answer_id": 210720,
"author": "Hapkido",
"author_id": 27646,
"author_profile": "https://Stackoverflow.com/users/27646",
"pm_score": 0,
"selected": false,
"text": "<p>On MS SQL, you can use a SQL Keywork as a column name if you put it in quotation.</p>\n\n<p>Example: <code>SELECT id, \"group\" FROM myTable</code></p>\n"
}
] |
2008/10/14
|
[
"https://Stackoverflow.com/questions/201829",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2484/"
] |
I have a format file where I want one of the columns to be "group". I'm auto-generating the format file and a client wants to upload a file with "group" as one of the columns. I could restrict it so they can't use SQL keywords, but then I need a function to determine if a column name is a SQL keyword, so I'd like to support the user being able to name their clients however they want. I'm wondering if this is possible. I tried using brackets, but that didn't appear to work. My file looks like:
```
8.0
1
1 SQLCHAR 0 0 "\r\n" 1 [group] SQL_Latin1_General_CP1_CI_AS
```
|
I tested this out several different ways on SQL 2005 SP2 (target databases in both compatibility modes 80 and 90) and it works OK for me using the SQL 2005 version of bcp.
However, I also tested it with the SQL 2000 version of bcp, and that failed with
```
Error = [Microsoft][ODBC SQL Server Driver][SQL Server]Incorrect syntax near the keyword 'group'.
```
which I guess is what you're getting.
Are you able to upgrade the system where you're running bcp to use the SQL 2005 client tools?
If you believe that you have already upgraded, check your PATH environment variable to confirm that
```
C:\Program Files\Microsoft SQL Server\90\Tools\binn\
```
(adjusted for your installation) appears before
```
C:\Program Files\Microsoft SQL Server\80\Tools\BINN
```
otherwise the SQL 2000 command line tools will be used in preference to the SQL 2005
|
201,830 |
<p>I just asked <a href="https://stackoverflow.com/questions/201686/linq-to-sql-select-optimization">this question</a>. Which lead me to a new question :)</p>
<p>Up until this point, I have used the following pattern of selecting stuff with Linq to SQL, with the purpose of being able to handle 0 "rows" returned by the query:</p>
<pre><code>var person = (from p in [DataContextObject].Persons
where p.PersonsID == 1
select new p).FirstOrDefault();
if (person == null)
{
// handle 0 "rows" returned.
}
</code></pre>
<p>But I can't use <code>FirstOrDefault()</code> when I do:</p>
<pre><code>var person = from p in [DataContextObject].Persons
where p.PersonsID == 1
select new { p.PersonsID, p.PersonsAdress, p.PersonsZipcode };
// Under the hood, this pattern generates a query which selects specific
// columns which will be faster than selecting all columns as the above
// snippet of code does. This results in a performance-boost on large tables.
</code></pre>
<p>How do I check for 0 "rows" returned by the query, using the second pattern?
<br />
<br />
<br />
<br />
<strong>UPDATE:</strong></p>
<p>I think my build fails because I am trying to assign the result of the query to a variable (<code>this._user</code>) declared with the type of <code>[DataContext].User</code>.</p>
<pre><code>this._user = (from u in [DataContextObject].Users
where u.UsersID == [Int32]
select new { u.UsersID }).FirstOrDefault();
</code></pre>
<p><em>Compilation error: Cannot implicitly convert type "AnonymousType#1" to "[DataContext].User".</em></p>
<p>Any thoughts on how I can get around this? Would I have to make my own object?</p>
|
[
{
"answer_id": 201853,
"author": "Mark Cidade",
"author_id": 1659,
"author_profile": "https://Stackoverflow.com/users/1659",
"pm_score": 1,
"selected": false,
"text": "<pre><code>if (person.Any()) /* ... */;\n</code></pre>\n\n<p>OR</p>\n\n<pre><code>if (person.Count() == 0) /* ... */;\n</code></pre>\n"
},
{
"answer_id": 201871,
"author": "Peter",
"author_id": 5189,
"author_profile": "https://Stackoverflow.com/users/5189",
"pm_score": 0,
"selected": false,
"text": "<p>You can still use <code>FirstOrDefault</code>. Just have </p>\n\n<pre><code>var PersonFields = (...).FirstOrDefault() \n</code></pre>\n\n<p>PersonFields will be be null or an object with those properties you created.</p>\n"
},
{
"answer_id": 201874,
"author": "Nick Berardi",
"author_id": 17,
"author_profile": "https://Stackoverflow.com/users/17",
"pm_score": 4,
"selected": false,
"text": "<p>Why can you keep doing the samething? Is it giving you an error?</p>\n\n<pre><code>var person = (from p in [DataContextObject].Persons\n where p.PersonsID == 1\n select new { p.PersonsID, p.PersonsAdress, p.PersonsZipcode }).FirstOrDefault();\n\nif (person == null) { \n // handle 0 \"rows\" returned.\n}\n</code></pre>\n\n<p>It is still a reference object just like you actual object, it is just anonymous so you don't know the actual type before the code is compiled.</p>\n"
},
{
"answer_id": 202026,
"author": "liggett78",
"author_id": 19762,
"author_profile": "https://Stackoverflow.com/users/19762",
"pm_score": 2,
"selected": true,
"text": "<p>Regarding your UPDATE: you have to either create your own type, change this._user to be <em>int</em>, or select the whole object, not only specific columns.</p>\n"
},
{
"answer_id": 449107,
"author": "Andrew",
"author_id": 15127,
"author_profile": "https://Stackoverflow.com/users/15127",
"pm_score": 2,
"selected": false,
"text": "<p><strong>Update:</strong></p>\n\n<blockquote>\n <p>I see now what you were <em>actually</em> asking! Sorry, my answer no longer applies. I thought you were not getting a null value when it was empty. The accepted response is correct, if you want to use the object out of scope, you need to create a new type and just use New MyType(...). I know DevEx's RefactorPro has a refactoring for this, and I think resharper does as well.</p>\n</blockquote>\n\n<p>Call .FirstOrDefault(null) like this:</p>\n\n<pre><code>string[] names = { \"jim\", \"jane\", \"joe\", \"john\", \"jeremy\", \"jebus\" };\nvar person = (\n from p in names where p.StartsWith(\"notpresent\") select \n new { Name=p, FirstLetter=p.Substring(0,1) } \n )\n .DefaultIfEmpty(null)\n .FirstOrDefault();\n\nMessageBox.Show(person==null?\"person was null\":person.Name + \"/\" + person.FirstLetter);\n</code></pre>\n\n<p>That does the trick for me.</p>\n"
}
] |
2008/10/14
|
[
"https://Stackoverflow.com/questions/201830",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20946/"
] |
I just asked [this question](https://stackoverflow.com/questions/201686/linq-to-sql-select-optimization). Which lead me to a new question :)
Up until this point, I have used the following pattern of selecting stuff with Linq to SQL, with the purpose of being able to handle 0 "rows" returned by the query:
```
var person = (from p in [DataContextObject].Persons
where p.PersonsID == 1
select new p).FirstOrDefault();
if (person == null)
{
// handle 0 "rows" returned.
}
```
But I can't use `FirstOrDefault()` when I do:
```
var person = from p in [DataContextObject].Persons
where p.PersonsID == 1
select new { p.PersonsID, p.PersonsAdress, p.PersonsZipcode };
// Under the hood, this pattern generates a query which selects specific
// columns which will be faster than selecting all columns as the above
// snippet of code does. This results in a performance-boost on large tables.
```
How do I check for 0 "rows" returned by the query, using the second pattern?
**UPDATE:**
I think my build fails because I am trying to assign the result of the query to a variable (`this._user`) declared with the type of `[DataContext].User`.
```
this._user = (from u in [DataContextObject].Users
where u.UsersID == [Int32]
select new { u.UsersID }).FirstOrDefault();
```
*Compilation error: Cannot implicitly convert type "AnonymousType#1" to "[DataContext].User".*
Any thoughts on how I can get around this? Would I have to make my own object?
|
Regarding your UPDATE: you have to either create your own type, change this.\_user to be *int*, or select the whole object, not only specific columns.
|
201,832 |
<p>Hey right now I'm using jQuery and I have some global variables to hold a bit of preloaded ajax stuff (preloaded to make pages come up nice and fast):</p>
<pre><code>
$.get("content.py?pageName=viewer", function(data)
{viewer = data;});
$.get("content.py?pageName=artists", function(data)
{artists = data;});
$.get("content.py?pageName=instores", function(data)
{instores = data;});
$.get("content.py?pageName=specs", function(data)
{specs = data;});
$.get("content.py?pageName=about", function(data)
{about = data;});
</code></pre>
<p>As you can see, we have a huge violation of the DRY principle, but... I don't really see a way to fix it... any ideas?</p>
<p>maybe an array?</p>
|
[
{
"answer_id": 201855,
"author": "Greg",
"author_id": 24181,
"author_profile": "https://Stackoverflow.com/users/24181",
"pm_score": 2,
"selected": false,
"text": "<p>You can avoid eval using new Function:</p>\n\n<pre><code>var names = ['viewer', 'artists', 'instores', 'specs', 'about'];\nfor (var i = 0; i < names.length; i++)\n $.get(\"content.py?pageName=\" + names[i], new Function('data', names[i] + ' = data;'));\n</code></pre>\n\n<p>It's not a lot better though tbh</p>\n"
},
{
"answer_id": 201903,
"author": "kentaromiura",
"author_id": 27340,
"author_profile": "https://Stackoverflow.com/users/27340",
"pm_score": 0,
"selected": false,
"text": "<p>You can call only one time that page, and returning a json object instead of text</p>\n\n<pre><code>{\nviewer:'me',\nartists:'you',\ninstores:'instores',\nspecs:'specs',\nabout:'about'\n}\n</code></pre>\n\n<p>and eval that\nSince now you're calling N times your server, this slow down all, you should reconsider your logic!</p>\n\n<p>PS. as I write i saw the RoBorg answer, you see, when using new Function you are using eval under the hood, so if you want to use it go for it (in some browser is faster too)</p>\n"
},
{
"answer_id": 201941,
"author": "Ates Goral",
"author_id": 23501,
"author_profile": "https://Stackoverflow.com/users/23501",
"pm_score": 3,
"selected": false,
"text": "<p>Using the jQuery each method to iterate through an array of page names and then setting a global (in window scope) variable:</p>\n\n<pre><code>jQuery.each(\n [\"viewer\", \"artists\", \"instores\", \"specs\", \"about\"],\n function (page) {\n $.get(\"content.py?pageName=\" + page,\n new Function(\"window[\" + page + \"] = arguments[0]\"));\n }\n);\n</code></pre>\n\n<p><strong>Update:</strong> Actually, you don't even need the \"new Function\":</p>\n\n<pre><code>jQuery.each(\n [\"viewer\", \"artists\", \"instores\", \"specs\", \"about\"],\n function (page) {\n $.get(\"content.py?pageName=\" + page, function () { window[page] = arguments[0]; });\n }\n);\n</code></pre>\n"
},
{
"answer_id": 202004,
"author": "Shog9",
"author_id": 811,
"author_profile": "https://Stackoverflow.com/users/811",
"pm_score": 4,
"selected": true,
"text": "<p>You don't need <code>eval()</code> or <code>Function()</code> for this. An array, as you suspected, will do the job nicely:</p>\n\n<pre><code>(function() // keep outer scope clean\n{\n // pages to load. Each name is used both for the request and the name\n // of the property to store the result in (so keep them valid identifiers\n // unless you want to use window['my funky page'] to retrieve them)\n var pages = ['viewer', 'artists', 'instores', 'specs', 'about'];\n\n for (var i=0; i<pages.length; ++i)\n {\n // \"this\" refers to the outer scope; likely the window object. \n // And will result in page contents being stored in global variables \n // with the same names as the pages being loaded. We use the with({})\n // construct to create a local scope for each callback with the\n // appropriate context and page name.\n with ({context: this, pageName: pages[i]})\n $.get(\"content.py?pageName=\" + pageName, function(data)\n {context[pageName] = data;});\n }\n\n})(); // close scope, execute anonymous function\n\n// at this point, viewer, artists, etc. are populated with page contents \n// (assuming all requests completed successfully)\n</code></pre>\n"
},
{
"answer_id": 202048,
"author": "Daniel Beardsley",
"author_id": 13216,
"author_profile": "https://Stackoverflow.com/users/13216",
"pm_score": 0,
"selected": false,
"text": "<p>This doesn't use eval, though it's a little more wordy.</p>\n\n<pre><code>function get_content(name){\n $.get(\"content.py?pageName=\" + name, function(data){ window[name] = data;});\n}\n\nvar names = ['viewer', 'artists', 'instores', 'specs', 'about'];\nfor (var i = 0; i < names.length; i++)\n get_content(names[i]);\n</code></pre>\n\n<p>But one of the of answerers made a good point, you should probably try and combine all these requests into one otherwise your server will be hit 6 times for dynamic content on each request of the page. </p>\n"
},
{
"answer_id": 212159,
"author": "DOK",
"author_id": 27637,
"author_profile": "https://Stackoverflow.com/users/27637",
"pm_score": 0,
"selected": false,
"text": "<p>Most of these proposed solutions avoid the use of <strong>eval</strong>. That practice is further reinforced in Doduglas Crockford's \" <a href=\"http://javascript.crockford.com/code.html\" rel=\"nofollow noreferrer\">Code Conventions for the JavaScript Programming Language</a>\" which says in part </p>\n\n<blockquote>\n <p>\"eval is Evil</p>\n \n <p>The eval function is the most misused\n feature of JavaScript. Avoid it.</p>\n \n <p>eval has aliases. Do not use the\n Function constructor.\"</p>\n</blockquote>\n"
}
] |
2008/10/14
|
[
"https://Stackoverflow.com/questions/201832",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2908/"
] |
Hey right now I'm using jQuery and I have some global variables to hold a bit of preloaded ajax stuff (preloaded to make pages come up nice and fast):
```
$.get("content.py?pageName=viewer", function(data)
{viewer = data;});
$.get("content.py?pageName=artists", function(data)
{artists = data;});
$.get("content.py?pageName=instores", function(data)
{instores = data;});
$.get("content.py?pageName=specs", function(data)
{specs = data;});
$.get("content.py?pageName=about", function(data)
{about = data;});
```
As you can see, we have a huge violation of the DRY principle, but... I don't really see a way to fix it... any ideas?
maybe an array?
|
You don't need `eval()` or `Function()` for this. An array, as you suspected, will do the job nicely:
```
(function() // keep outer scope clean
{
// pages to load. Each name is used both for the request and the name
// of the property to store the result in (so keep them valid identifiers
// unless you want to use window['my funky page'] to retrieve them)
var pages = ['viewer', 'artists', 'instores', 'specs', 'about'];
for (var i=0; i<pages.length; ++i)
{
// "this" refers to the outer scope; likely the window object.
// And will result in page contents being stored in global variables
// with the same names as the pages being loaded. We use the with({})
// construct to create a local scope for each callback with the
// appropriate context and page name.
with ({context: this, pageName: pages[i]})
$.get("content.py?pageName=" + pageName, function(data)
{context[pageName] = data;});
}
})(); // close scope, execute anonymous function
// at this point, viewer, artists, etc. are populated with page contents
// (assuming all requests completed successfully)
```
|
201,840 |
<p>Running <code>rake db:migrate</code> followed by <code>rake test:units</code> yields the following:</p>
<pre><code>rake test:functionals
(in /projects/my_project)
rake aborted!
SQLite3::SQLException: index unique_schema_migrations already exists: CREATE UNIQUE INDEX "unique_schema_migrations" ON "ts_schema_migrations" ("version")
</code></pre>
<p>The relevant part of <code>db/schema.rb</code> is as follows:</p>
<pre><code>create_table "ts_schema_migrations", :id => false, :force => true do |t|
t.string "version", :null => false
end
add_index "ts_schema_migrations", ["version"], :name => "unique_schema_migrations", :unique => true
</code></pre>
<p>I'm not manually changing this index anywhere, and I'm using Rails' default SQLite3 adapter with a brand new database. (That is, running <code>rm db/*sqlite3</code> before <code>rake db:migrate</code> doesn't help.)</p>
<p>Is the <code>test:units</code> task perhaps trying to re-load the schema? If so, why? Shouldn't it recognize the schema is already up to date?</p>
|
[
{
"answer_id": 201900,
"author": "Vitalie",
"author_id": 27913,
"author_profile": "https://Stackoverflow.com/users/27913",
"pm_score": 0,
"selected": false,
"text": "<p>Try to search if your schema.rb file does not contain other declarations that create an index with the same name: <code>unique_schema_migrations</code></p>\n"
},
{
"answer_id": 206848,
"author": "Tilendor",
"author_id": 1470,
"author_profile": "https://Stackoverflow.com/users/1470",
"pm_score": 2,
"selected": false,
"text": "<p>In your database.yml file are your environments setup up to connect to different databases for Development and Test?</p>\n\n<p>IE:</p>\n\n<pre><code>development:\n adapter: sqlite3\n database: db/dev.sqlite3\n timeout: 5000\n\ntest:\n adapter: sqlite3\n database: db/test.sqlite3\n timeout: 5000\n</code></pre>\n"
},
{
"answer_id": 1982880,
"author": "Ian Lesperance",
"author_id": 199806,
"author_profile": "https://Stackoverflow.com/users/199806",
"pm_score": 4,
"selected": false,
"text": "<p>In SQLite, index name uniqueness is enforced at the database level. In MySQL, uniqueness is enforced only at the table level. That's why your migrations work in the latter and not the former: you have two indexes with the same name on different tables.</p>\n\n<p>Rename the index, or find and rename the other <code>unique_schema_migrations</code> index, and your migrations should work.</p>\n"
}
] |
2008/10/14
|
[
"https://Stackoverflow.com/questions/201840",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1190/"
] |
Running `rake db:migrate` followed by `rake test:units` yields the following:
```
rake test:functionals
(in /projects/my_project)
rake aborted!
SQLite3::SQLException: index unique_schema_migrations already exists: CREATE UNIQUE INDEX "unique_schema_migrations" ON "ts_schema_migrations" ("version")
```
The relevant part of `db/schema.rb` is as follows:
```
create_table "ts_schema_migrations", :id => false, :force => true do |t|
t.string "version", :null => false
end
add_index "ts_schema_migrations", ["version"], :name => "unique_schema_migrations", :unique => true
```
I'm not manually changing this index anywhere, and I'm using Rails' default SQLite3 adapter with a brand new database. (That is, running `rm db/*sqlite3` before `rake db:migrate` doesn't help.)
Is the `test:units` task perhaps trying to re-load the schema? If so, why? Shouldn't it recognize the schema is already up to date?
|
In SQLite, index name uniqueness is enforced at the database level. In MySQL, uniqueness is enforced only at the table level. That's why your migrations work in the latter and not the former: you have two indexes with the same name on different tables.
Rename the index, or find and rename the other `unique_schema_migrations` index, and your migrations should work.
|
201,846 |
<p>i have the following script</p>
<pre><code>import getopt, sys
opts, args = getopt.getopt(sys.argv[1:], "h:s")
for key,value in opts:
print key, "=>", value
</code></pre>
<p>if i name this getopt.py and run it doesn't work as it tries to import itself</p>
<p>is there a way around this, so i can keep this filename but specify on import that i want the standard python lib and not this file? </p>
<p>Solution based on Vinko's answer:</p>
<pre><code>import sys
sys.path.reverse()
from getopt import getopt
opts, args = getopt(sys.argv[1:], "h:s")
for key,value in opts:
print key, "=>", value
</code></pre>
|
[
{
"answer_id": 201862,
"author": "axblount",
"author_id": 1729005,
"author_profile": "https://Stackoverflow.com/users/1729005",
"pm_score": -1,
"selected": false,
"text": "<pre><code>import getopt as bettername\n</code></pre>\n\n<p>This should allow you to call getopt as bettername.</p>\n"
},
{
"answer_id": 201881,
"author": "gimel",
"author_id": 6491,
"author_profile": "https://Stackoverflow.com/users/6491",
"pm_score": 2,
"selected": false,
"text": "<p>You should avoid naming your python files with standard library module names.</p>\n"
},
{
"answer_id": 201891,
"author": "Vinko Vrsalovic",
"author_id": 5190,
"author_profile": "https://Stackoverflow.com/users/5190",
"pm_score": 4,
"selected": true,
"text": "<p>You shouldn't name your scripts like existing modules. Especially if standard. </p>\n\n<p>That said, you can touch sys.path to modify the library loading order</p>\n\n<pre><code>~# cat getopt.py\nprint \"HI\"\n~# python\nPython 2.5.2 (r252:60911, Jul 31 2008, 17:28:52)\n[GCC 4.2.3 (Ubuntu 4.2.3-2ubuntu7)] on linux2\nType \"help\", \"copyright\", \"credits\" or \"license\" for more information.\n>>> import sys\n>>> import getopt\nHI\n\n~# python\nPython 2.5.2 (r252:60911, Jul 31 2008, 17:28:52)\n[GCC 4.2.3 (Ubuntu 4.2.3-2ubuntu7)] on linux2\nType \"help\", \"copyright\", \"credits\" or \"license\" for more information.\n>>> import sys\n>>> sys.path.remove('')\n>>> import getopt\n>>> dir(getopt)\n['GetoptError', '__all__', '__builtins__', '__doc__', '__file__', '__name__', 'do_longs', 'do_shorts', 'error', 'getopt', 'gnu_getopt', 'long_has_args', 'os', 'short_has_arg']\n</code></pre>\n\n<p>In addition, you may wish to avoid the full import and do it differently, like this:</p>\n\n<pre><code>import sys\nsys.path.remove('')\nfrom getopt import getopt\nsys.path.insert(0,'')\nopts, args = getopt(sys.argv[1:], \"h:s\")\nfor key,value in opts:\n print key, \"=>\", value\n</code></pre>\n"
},
{
"answer_id": 201907,
"author": "Fred Larson",
"author_id": 10077,
"author_profile": "https://Stackoverflow.com/users/10077",
"pm_score": 0,
"selected": false,
"text": "<p>Python doesn't give you a way to qualify modules. You might be able to accomplish this by removing the '' entry from sys.path or by moving it to the end. I wouldn't recommend it.</p>\n"
},
{
"answer_id": 201916,
"author": "André",
"author_id": 9683,
"author_profile": "https://Stackoverflow.com/users/9683",
"pm_score": 0,
"selected": false,
"text": "<p>Well, you could (re)move the current diretory from sys.path, which contains the modifiable search path for libraries to make it work, if you really need that.</p>\n"
}
] |
2008/10/14
|
[
"https://Stackoverflow.com/questions/201846",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9789/"
] |
i have the following script
```
import getopt, sys
opts, args = getopt.getopt(sys.argv[1:], "h:s")
for key,value in opts:
print key, "=>", value
```
if i name this getopt.py and run it doesn't work as it tries to import itself
is there a way around this, so i can keep this filename but specify on import that i want the standard python lib and not this file?
Solution based on Vinko's answer:
```
import sys
sys.path.reverse()
from getopt import getopt
opts, args = getopt(sys.argv[1:], "h:s")
for key,value in opts:
print key, "=>", value
```
|
You shouldn't name your scripts like existing modules. Especially if standard.
That said, you can touch sys.path to modify the library loading order
```
~# cat getopt.py
print "HI"
~# python
Python 2.5.2 (r252:60911, Jul 31 2008, 17:28:52)
[GCC 4.2.3 (Ubuntu 4.2.3-2ubuntu7)] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> import sys
>>> import getopt
HI
~# python
Python 2.5.2 (r252:60911, Jul 31 2008, 17:28:52)
[GCC 4.2.3 (Ubuntu 4.2.3-2ubuntu7)] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> import sys
>>> sys.path.remove('')
>>> import getopt
>>> dir(getopt)
['GetoptError', '__all__', '__builtins__', '__doc__', '__file__', '__name__', 'do_longs', 'do_shorts', 'error', 'getopt', 'gnu_getopt', 'long_has_args', 'os', 'short_has_arg']
```
In addition, you may wish to avoid the full import and do it differently, like this:
```
import sys
sys.path.remove('')
from getopt import getopt
sys.path.insert(0,'')
opts, args = getopt(sys.argv[1:], "h:s")
for key,value in opts:
print key, "=>", value
```
|
201,848 |
<p>I'm automating Outlook and I need to control who the email appears to be from. The users will have two or more Accounts set up in Outlook and I need to be able to select which account to send the email from. Any ideas?</p>
<p>Needs to be supported on Outlook 2003 and above. I'm using Delphi 2006 to code this, but that doesn't really matter.</p>
|
[
{
"answer_id": 201862,
"author": "axblount",
"author_id": 1729005,
"author_profile": "https://Stackoverflow.com/users/1729005",
"pm_score": -1,
"selected": false,
"text": "<pre><code>import getopt as bettername\n</code></pre>\n\n<p>This should allow you to call getopt as bettername.</p>\n"
},
{
"answer_id": 201881,
"author": "gimel",
"author_id": 6491,
"author_profile": "https://Stackoverflow.com/users/6491",
"pm_score": 2,
"selected": false,
"text": "<p>You should avoid naming your python files with standard library module names.</p>\n"
},
{
"answer_id": 201891,
"author": "Vinko Vrsalovic",
"author_id": 5190,
"author_profile": "https://Stackoverflow.com/users/5190",
"pm_score": 4,
"selected": true,
"text": "<p>You shouldn't name your scripts like existing modules. Especially if standard. </p>\n\n<p>That said, you can touch sys.path to modify the library loading order</p>\n\n<pre><code>~# cat getopt.py\nprint \"HI\"\n~# python\nPython 2.5.2 (r252:60911, Jul 31 2008, 17:28:52)\n[GCC 4.2.3 (Ubuntu 4.2.3-2ubuntu7)] on linux2\nType \"help\", \"copyright\", \"credits\" or \"license\" for more information.\n>>> import sys\n>>> import getopt\nHI\n\n~# python\nPython 2.5.2 (r252:60911, Jul 31 2008, 17:28:52)\n[GCC 4.2.3 (Ubuntu 4.2.3-2ubuntu7)] on linux2\nType \"help\", \"copyright\", \"credits\" or \"license\" for more information.\n>>> import sys\n>>> sys.path.remove('')\n>>> import getopt\n>>> dir(getopt)\n['GetoptError', '__all__', '__builtins__', '__doc__', '__file__', '__name__', 'do_longs', 'do_shorts', 'error', 'getopt', 'gnu_getopt', 'long_has_args', 'os', 'short_has_arg']\n</code></pre>\n\n<p>In addition, you may wish to avoid the full import and do it differently, like this:</p>\n\n<pre><code>import sys\nsys.path.remove('')\nfrom getopt import getopt\nsys.path.insert(0,'')\nopts, args = getopt(sys.argv[1:], \"h:s\")\nfor key,value in opts:\n print key, \"=>\", value\n</code></pre>\n"
},
{
"answer_id": 201907,
"author": "Fred Larson",
"author_id": 10077,
"author_profile": "https://Stackoverflow.com/users/10077",
"pm_score": 0,
"selected": false,
"text": "<p>Python doesn't give you a way to qualify modules. You might be able to accomplish this by removing the '' entry from sys.path or by moving it to the end. I wouldn't recommend it.</p>\n"
},
{
"answer_id": 201916,
"author": "André",
"author_id": 9683,
"author_profile": "https://Stackoverflow.com/users/9683",
"pm_score": 0,
"selected": false,
"text": "<p>Well, you could (re)move the current diretory from sys.path, which contains the modifiable search path for libraries to make it work, if you really need that.</p>\n"
}
] |
2008/10/14
|
[
"https://Stackoverflow.com/questions/201848",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1008/"
] |
I'm automating Outlook and I need to control who the email appears to be from. The users will have two or more Accounts set up in Outlook and I need to be able to select which account to send the email from. Any ideas?
Needs to be supported on Outlook 2003 and above. I'm using Delphi 2006 to code this, but that doesn't really matter.
|
You shouldn't name your scripts like existing modules. Especially if standard.
That said, you can touch sys.path to modify the library loading order
```
~# cat getopt.py
print "HI"
~# python
Python 2.5.2 (r252:60911, Jul 31 2008, 17:28:52)
[GCC 4.2.3 (Ubuntu 4.2.3-2ubuntu7)] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> import sys
>>> import getopt
HI
~# python
Python 2.5.2 (r252:60911, Jul 31 2008, 17:28:52)
[GCC 4.2.3 (Ubuntu 4.2.3-2ubuntu7)] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> import sys
>>> sys.path.remove('')
>>> import getopt
>>> dir(getopt)
['GetoptError', '__all__', '__builtins__', '__doc__', '__file__', '__name__', 'do_longs', 'do_shorts', 'error', 'getopt', 'gnu_getopt', 'long_has_args', 'os', 'short_has_arg']
```
In addition, you may wish to avoid the full import and do it differently, like this:
```
import sys
sys.path.remove('')
from getopt import getopt
sys.path.insert(0,'')
opts, args = getopt(sys.argv[1:], "h:s")
for key,value in opts:
print key, "=>", value
```
|
201,883 |
<p>I have the same problem as described in the posts listed below. That is, certain keys don't work at all when I type them into my combobox until I first hit the spacebar. One of the keys is ".", but another is the letter "Q", and there are others: "$", "%". </p>
<p><a href="http://forums.microsoft.com/msdn/ShowPost.aspx?PostID=659716&SiteID=1" rel="nofollow noreferrer">http://forums.microsoft.com/msdn/ShowPost.aspx?PostID=659716&SiteID=1</a><br>
<a href="http://forums.microsoft.com/MSDN/ShowPost.aspx?PostID=2909173&SiteID=1&pageid=0" rel="nofollow noreferrer">http://forums.microsoft.com/MSDN/ShowPost.aspx?PostID=2909173&SiteID=1&pageid=0</a><br>
<a href="http://bytes.com/forum/thread548399.html" rel="nofollow noreferrer">http://bytes.com/forum/thread548399.html</a></p>
<p>I've tried a lot of things so far. My latest failure was based on the theory that maybe the DataGridView was using WIN32 API wndproc subclassing to intercept messages, so I wrote logic to save the old wndproc and restore it after adding it to the DataGridView's control collection. That didn't work.</p>
<p>Messina - thanks for reminding me about Spy++. For the letter "A", the edit window sends an EN_UPDATE to its combobox parent. But, not for the "Q". That's so strange.</p>
<p>I have convinced myself that the DataGridView is not subclassing the combo and the edit, because I check the address of the wndprocs just after creation and before adding them to the grid's collection, and then later when I paint. Unless the grid installs some sort of global hooks..</p>
<p>I'm thinkin, maybe I can subclass the edit control, and then send the notification to the combobox the way I see the edit control doing here?</p>
<p>EDIT: More info here. Windows messages from grid, combobox, and edit control, from Spy++:</p>
<p>HWNDs:
122064e < grid
010d0674 < combobox
01360696 < combox's edit control</p>
<pre><code><01402> 01360696 P WM_KEYDOWN nVirtKey:'A' cRepeat:1 ScanCode:1E fExtended:0 fAltDown:0 fRepeat:0 fUp:0
<01403> 010D0674 S WM_GETDLGCODE
<01404> 010D0674 R WM_GETDLGCODE fuDlgCode:DLGC_WANTARROWS | DLGC_WANTCHARS
<01405> 010D0674 S WM_GETDLGCODE
<01406> 010D0674 R WM_GETDLGCODE fuDlgCode:DLGC_WANTARROWS | DLGC_WANTCHARS
<01407> 010D0674 S WM_GETDLGCODE
<01408> 010D0674 R WM_GETDLGCODE fuDlgCode:DLGC_WANTARROWS | DLGC_WANTCHARS
<01409> 010D0674 S WM_GETDLGCODE
<01410> 010D0674 R WM_GETDLGCODE fuDlgCode:DLGC_WANTARROWS | DLGC_WANTCHARS
<01411> 01360696 P WM_CHAR chCharCode:'0061' (97) cRepeat:1 ScanCode:1E fExtended:0 fAltDown:0 fRepeat:0 fUp:0
<01412> 010D0674 S WM_GETDLGCODE
<01413> 010D0674 R WM_GETDLGCODE fuDlgCode:DLGC_WANTARROWS | DLGC_WANTCHARS
<01414> 010D0674 S WM_GETDLGCODE
<01415> 010D0674 R WM_GETDLGCODE fuDlgCode:DLGC_WANTARROWS | DLGC_WANTCHARS
<01416> 010D0674 S WM_COMMAND wNotifyCode:EN_UPDATE wID:1001 hwndCtl:01360696 <<< edit control sends to combobox
<01417> 010D0674 S message:0x2111 [User-defined:WM_USER+7441] wParam:00060674 lParam:010D0674 What do these do?
<01418> 010D0674 R message:0x2111 [User-defined:WM_USER+7441] lResult:00000000
<01419> 010D0674 R WM_COMMAND
<01420> 010D0674 S WM_CTLCOLOREDIT hdcEdit:C7011AA6 hwndEdit:01360696
<01421> 010D0674 R WM_CTLCOLOREDIT hBrush:F0103EB0
<01422> 010D0674 S WM_COMMAND wNotifyCode:EN_CHANGE wID:1001 hwndCtl:01360696 << edit control sends to combobox
<01423> 010D0674 S message:0x2111 [User-defined:WM_USER+7441] wParam:00050674 lParam:010D0674
<01424> 0122064E S WM_PAINT hdc:00000000 <<< grid is told to paint
<01425> 0122064E S WM_ERASEBKGND hdc:94011D4E
<01426> 0122064E R WM_ERASEBKGND fErased:True
<01427> 0122064E S WM_GETTEXTLENGTH
<01428> 0122064E R WM_GETTEXTLENGTH cch:0
<01429> 0122064E S WM_GETTEXT cchTextMax:2 lpszText:0012D0C0
<01430> 0122064E R WM_GETTEXT cchCopied:0 lpszText:0012D0C0 ("")
<01431> 0122064E S WM_GETTEXTLENGTH
<01432> 0122064E R WM_GETTEXTLENGTH cch:0
<01433> 0122064E S WM_GETTEXT cchTextMax:2 lpszText:0012D0C0
<01434> 0122064E R WM_GETTEXT cchCopied:0 lpszText:0012D0C0 ("")
<01435> 010D0674 S WM_WINDOWPOSCHANGING lpwp:0012D4B0
<01436> 010D0674 R WM_WINDOWPOSCHANGING
<01437> 010D0674 S CB_GETCURSEL
<01438> 010D0674 R CB_GETCURSEL index:CB_ERR
<01439> 010D0674 S WM_GETTEXTLENGTH
<01440> 01360696 S WM_GETTEXTLENGTH
<01441> 01360696 R WM_GETTEXTLENGTH cch:2
<01442> 010D0674 R WM_GETTEXTLENGTH cch:2
<01443> 010D0674 S WM_GETTEXT cchTextMax:6 lpszText:0012CC44
<01444> 01360696 S WM_GETTEXT cchTextMax:6 lpszText:0012BE64
<01445> 01360696 R WM_GETTEXT cchCopied:2 lpszText:0012BE64 ("a")
<01446> 010D0674 R WM_GETTEXT cchCopied:2 lpszText:0012CC44 ("a")
<01447> 010D0674 S CB_GETCURSEL
<01448> 010D0674 R CB_GETCURSEL index:CB_ERR
<01449> 010D0674 S WM_GETTEXTLENGTH
<01450> 01360696 S WM_GETTEXTLENGTH
<01451> 01360696 R WM_GETTEXTLENGTH cch:2
<01452> 010D0674 R WM_GETTEXTLENGTH cch:2
<01453> 010D0674 S WM_GETTEXT cchTextMax:6 lpszText:0012CC44
<01454> 01360696 S WM_GETTEXT cchTextMax:6 lpszText:0012BE64
<01455> 01360696 R WM_GETTEXT cchCopied:2 lpszText:0012BE64 ("a")
<01456> 010D0674 R WM_GETTEXT cchCopied:2 lpszText:0012CC44 ("a")
<01457> 010D0674 S CB_GETCURSEL
<01458> 010D0674 R CB_GETCURSEL index:CB_ERR
<01531> 0122064E R WM_PAINT
<01532> 010D0674 S WM_PAINT hdc:00000000
<01533> 010D0674 S WM_NCPAINT hrgn:00000001
<01534> 010D0674 R WM_NCPAINT
<01535> 010D0674 S WM_ERASEBKGND hdc:0F0141ED
<01536> 010D0674 R WM_ERASEBKGND fErased:True
<01537> 0122064E S WM_CTLCOLOREDIT hdcEdit:840137F1 hwndEdit:010D0674
<01538> 0122064E R WM_CTLCOLOREDIT hBrush:F0103EB0
<01539> 010D0674 R WM_PAINT
<01540> 01360696 S WM_PAINT hdc:00000000
<01541> 01360696 S WM_NCPAINT hrgn:00000001
<01542> 01360696 R WM_NCPAINT
<01543> 01360696 S WM_ERASEBKGND hdc:C7011AA6
<01544> 01360696 R WM_ERASEBKGND fErased:True
<01545> 010D0674 S WM_CTLCOLOREDIT hdcEdit:870137F1 hwndEdit:01360696
<01546> 010D0674 R WM_CTLCOLOREDIT hBrush:F0103EB0
<01547> 010D0674 S WM_CTLCOLOREDIT hdcEdit:870137F1 hwndEdit:01360696
<01548> 010D0674 R WM_CTLCOLOREDIT hBrush:F0103EB0
<01549> 01360696 R WM_PAINT
<01555> 0122064E S WM_CTLCOLOREDIT hdcEdit:8A0137F1 hwndEdit:010306AC
<01556> 0122064E R WM_CTLCOLOREDIT hBrush:78103C5B
<01568> 010D0674 S CB_GETCURSEL
<01569> 010D0674 R CB_GETCURSEL index:CB_ERR
<01570> 010D0674 S WM_GETTEXTLENGTH
<01571> 01360696 S WM_GETTEXTLENGTH
<01572> 01360696 R WM_GETTEXTLENGTH cch:2
<01573> 010D0674 R WM_GETTEXTLENGTH cch:2
<01574> 010D0674 S WM_GETTEXT cchTextMax:6 lpszText:0012D7A4
<01575> 01360696 S WM_GETTEXT cchTextMax:6 lpszText:0012C9C4
<01576> 01360696 R WM_GETTEXT cchCopied:2 lpszText:0012C9C4 ("a")
<01577> 010D0674 R WM_GETTEXT cchCopied:2 lpszText:0012D7A4 ("a")
<01578> 010D0674 S CB_GETCURSEL
<01579> 010D0674 R CB_GETCURSEL index:CB_ERR
<01580> 010D0674 S WM_GETTEXTLENGTH
<01581> 01360696 S WM_GETTEXTLENGTH
<01582> 01360696 R WM_GETTEXTLENGTH cch:2
<01583> 010D0674 R WM_GETTEXTLENGTH cch:2
<01584> 010D0674 S WM_GETTEXT cchTextMax:6 lpszText:0012D6E0
<01585> 01360696 S WM_GETTEXT cchTextMax:6 lpszText:0012C900
<01586> 01360696 R WM_GETTEXT cchCopied:2 lpszText:0012C900 ("a")
<01587> 010D0674 R WM_GETTEXT cchCopied:2 lpszText:0012D6E0 ("a")
<01588> 010D0674 S CB_GETCURSEL
<01589> 010D0674 R CB_GETCURSEL index:CB_ERR
<01590> 010D0674 S WM_GETTEXTLENGTH
<01591> 01360696 S WM_GETTEXTLENGTH
<01592> 01360696 R WM_GETTEXTLENGTH cch:2
<01593> 010D0674 R WM_GETTEXTLENGTH cch:2
<01594> 010D0674 S WM_GETTEXT cchTextMax:6 lpszText:0012D6E0
<01595> 01360696 S WM_GETTEXT cchTextMax:6 lpszText:0012C900
<01596> 01360696 R WM_GETTEXT cchCopied:2 lpszText:0012C900 ("a")
<01597> 010D0674 R WM_GETTEXT cchCopied:2 lpszText:0012D6E0 ("a")
<01598> 010D0674 R message:0x2111 [User-defined:WM_USER+7441] lResult:00000000
<01599> 01360696 S WM_GETTEXTLENGTH
<01600> 01360696 R WM_GETTEXTLENGTH cch:2
<01601> 01360696 S WM_GETTEXT cchTextMax:6 lpszText:0012DF8C
<01602> 01360696 R WM_GETTEXT cchCopied:2 lpszText:0012DF8C ("a")
<01603> 010D0674 R WM_COMMAND
<01604> 01360696 P WM_KEYUP nVirtKey:'A' cRepeat:1 ScanCode:1E fExtended:0 fAltDown:0 fRepeat:1 fUp:1
</code></pre>
<p>Letter q</p>
<pre><code><01625> 01360696 P WM_KEYDOWN nVirtKey:'Q' cRepeat:1 ScanCode:10 fExtended:0 fAltDown:0 fRepeat:0 fUp:0
<01626> 010D0674 S WM_GETDLGCODE
<01627> 010D0674 R WM_GETDLGCODE fuDlgCode:DLGC_WANTARROWS | DLGC_WANTCHARS
<01628> 010D0674 S WM_GETDLGCODE
<01629> 010D0674 R WM_GETDLGCODE fuDlgCode:DLGC_WANTARROWS | DLGC_WANTCHARS
<01630> 010D0674 S WM_GETDLGCODE
<01631> 010D0674 R WM_GETDLGCODE fuDlgCode:DLGC_WANTARROWS | DLGC_WANTCHARS
<01632> 010D0674 S WM_GETDLGCODE
<01633> 010D0674 R WM_GETDLGCODE fuDlgCode:DLGC_WANTARROWS | DLGC_WANTCHARS
<01634> 01360696 P WM_CHAR chCharCode:'0071' (113) cRepeat:1 ScanCode:10 fExtended:0 fAltDown:0 fRepeat:0 fUp:0
<01635> 010D0674 S WM_GETDLGCODE
<01636> 010D0674 R WM_GETDLGCODE fuDlgCode:DLGC_WANTARROWS | DLGC_WANTCHARS
<01637> 010D0674 S WM_GETDLGCODE
<01638> 010D0674 R WM_GETDLGCODE fuDlgCode:DLGC_WANTARROWS | DLGC_WANTCHARS
<01640> 01360696 P WM_KEYUP nVirtKey:'Q' cRepeat:1 ScanCode:10 fExtended:0 fAltDown:0 fRepeat:1 fUp:1
</code></pre>
|
[
{
"answer_id": 203033,
"author": "Corey Trager",
"author_id": 9328,
"author_profile": "https://Stackoverflow.com/users/9328",
"pm_score": 0,
"selected": false,
"text": "<p>Partial answer to my question. In the Combobox I handle the KeyDown, TextChanged, and KeyUp events, which fire in that order. If I go from KeyDown to KeyUp with TextChanged skipped, I check whether the character was a Keys.Q or Keys.OemPeriod. (I'm not sure it's safe to others, like shift/D1, shift/D2, etc...). If it's one of those keys, I change the combobox text myself.</p>\n\n<p>But that's not enough, because merely changing the text sets the cursor in the edit control (that belongs to the combobox) to the start of the text. So, to fix that, I use FindWindowEx to get the handle of the edit control, then send it a EM_SETSEL to reset the cursor to the end of the word.</p>\n"
},
{
"answer_id": 454773,
"author": "Michael Buen",
"author_id": 11432,
"author_profile": "https://Stackoverflow.com/users/11432",
"pm_score": 2,
"selected": true,
"text": "<p>By any chance, have you already solved your problem?</p>\n\n<p>I have the same problem as yours, my custom control for DataGridView cannot receive letter Q, period, dollar, single quote, percent, etc.</p>\n\n<p>I was able to solve the problem by changing the \"switch .. default: return false\" to \"switch .. default: return !dataGridViewWantsInputKey\"</p>\n\n<p>I guess the pattern code from Microsoft for making your own usercontrol for datagridview is not optimal. This is the pattern code from Microsoft:</p>\n\n<p><a href=\"http://msdn.microsoft.com/en-au/library/7tas5c80(vs.80).aspx\" rel=\"nofollow noreferrer\">http://msdn.microsoft.com/en-au/library/7tas5c80(vs.80).aspx</a></p>\n\n<pre><code>public bool EditingControlWantsInputKey(\n Keys key, bool dataGridViewWantsInputKey)\n{\n // Let the DateTimePicker handle the keys listed.\n switch (key & Keys.KeyCode)\n {\n case Keys.Left:\n case Keys.Up:\n case Keys.Down:\n case Keys.Right:\n case Keys.Home:\n case Keys.End:\n case Keys.PageDown:\n case Keys.PageUp:\n return true;\n default:\n return false; // I changed this to: return !dataGridViewWantsInputKey. My usercontrol can now receive Q, period, dollar, etc.\n }\n}\n</code></pre>\n"
}
] |
2008/10/14
|
[
"https://Stackoverflow.com/questions/201883",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9328/"
] |
I have the same problem as described in the posts listed below. That is, certain keys don't work at all when I type them into my combobox until I first hit the spacebar. One of the keys is ".", but another is the letter "Q", and there are others: "$", "%".
<http://forums.microsoft.com/msdn/ShowPost.aspx?PostID=659716&SiteID=1>
<http://forums.microsoft.com/MSDN/ShowPost.aspx?PostID=2909173&SiteID=1&pageid=0>
<http://bytes.com/forum/thread548399.html>
I've tried a lot of things so far. My latest failure was based on the theory that maybe the DataGridView was using WIN32 API wndproc subclassing to intercept messages, so I wrote logic to save the old wndproc and restore it after adding it to the DataGridView's control collection. That didn't work.
Messina - thanks for reminding me about Spy++. For the letter "A", the edit window sends an EN\_UPDATE to its combobox parent. But, not for the "Q". That's so strange.
I have convinced myself that the DataGridView is not subclassing the combo and the edit, because I check the address of the wndprocs just after creation and before adding them to the grid's collection, and then later when I paint. Unless the grid installs some sort of global hooks..
I'm thinkin, maybe I can subclass the edit control, and then send the notification to the combobox the way I see the edit control doing here?
EDIT: More info here. Windows messages from grid, combobox, and edit control, from Spy++:
HWNDs:
122064e < grid
010d0674 < combobox
01360696 < combox's edit control
```
<01402> 01360696 P WM_KEYDOWN nVirtKey:'A' cRepeat:1 ScanCode:1E fExtended:0 fAltDown:0 fRepeat:0 fUp:0
<01403> 010D0674 S WM_GETDLGCODE
<01404> 010D0674 R WM_GETDLGCODE fuDlgCode:DLGC_WANTARROWS | DLGC_WANTCHARS
<01405> 010D0674 S WM_GETDLGCODE
<01406> 010D0674 R WM_GETDLGCODE fuDlgCode:DLGC_WANTARROWS | DLGC_WANTCHARS
<01407> 010D0674 S WM_GETDLGCODE
<01408> 010D0674 R WM_GETDLGCODE fuDlgCode:DLGC_WANTARROWS | DLGC_WANTCHARS
<01409> 010D0674 S WM_GETDLGCODE
<01410> 010D0674 R WM_GETDLGCODE fuDlgCode:DLGC_WANTARROWS | DLGC_WANTCHARS
<01411> 01360696 P WM_CHAR chCharCode:'0061' (97) cRepeat:1 ScanCode:1E fExtended:0 fAltDown:0 fRepeat:0 fUp:0
<01412> 010D0674 S WM_GETDLGCODE
<01413> 010D0674 R WM_GETDLGCODE fuDlgCode:DLGC_WANTARROWS | DLGC_WANTCHARS
<01414> 010D0674 S WM_GETDLGCODE
<01415> 010D0674 R WM_GETDLGCODE fuDlgCode:DLGC_WANTARROWS | DLGC_WANTCHARS
<01416> 010D0674 S WM_COMMAND wNotifyCode:EN_UPDATE wID:1001 hwndCtl:01360696 <<< edit control sends to combobox
<01417> 010D0674 S message:0x2111 [User-defined:WM_USER+7441] wParam:00060674 lParam:010D0674 What do these do?
<01418> 010D0674 R message:0x2111 [User-defined:WM_USER+7441] lResult:00000000
<01419> 010D0674 R WM_COMMAND
<01420> 010D0674 S WM_CTLCOLOREDIT hdcEdit:C7011AA6 hwndEdit:01360696
<01421> 010D0674 R WM_CTLCOLOREDIT hBrush:F0103EB0
<01422> 010D0674 S WM_COMMAND wNotifyCode:EN_CHANGE wID:1001 hwndCtl:01360696 << edit control sends to combobox
<01423> 010D0674 S message:0x2111 [User-defined:WM_USER+7441] wParam:00050674 lParam:010D0674
<01424> 0122064E S WM_PAINT hdc:00000000 <<< grid is told to paint
<01425> 0122064E S WM_ERASEBKGND hdc:94011D4E
<01426> 0122064E R WM_ERASEBKGND fErased:True
<01427> 0122064E S WM_GETTEXTLENGTH
<01428> 0122064E R WM_GETTEXTLENGTH cch:0
<01429> 0122064E S WM_GETTEXT cchTextMax:2 lpszText:0012D0C0
<01430> 0122064E R WM_GETTEXT cchCopied:0 lpszText:0012D0C0 ("")
<01431> 0122064E S WM_GETTEXTLENGTH
<01432> 0122064E R WM_GETTEXTLENGTH cch:0
<01433> 0122064E S WM_GETTEXT cchTextMax:2 lpszText:0012D0C0
<01434> 0122064E R WM_GETTEXT cchCopied:0 lpszText:0012D0C0 ("")
<01435> 010D0674 S WM_WINDOWPOSCHANGING lpwp:0012D4B0
<01436> 010D0674 R WM_WINDOWPOSCHANGING
<01437> 010D0674 S CB_GETCURSEL
<01438> 010D0674 R CB_GETCURSEL index:CB_ERR
<01439> 010D0674 S WM_GETTEXTLENGTH
<01440> 01360696 S WM_GETTEXTLENGTH
<01441> 01360696 R WM_GETTEXTLENGTH cch:2
<01442> 010D0674 R WM_GETTEXTLENGTH cch:2
<01443> 010D0674 S WM_GETTEXT cchTextMax:6 lpszText:0012CC44
<01444> 01360696 S WM_GETTEXT cchTextMax:6 lpszText:0012BE64
<01445> 01360696 R WM_GETTEXT cchCopied:2 lpszText:0012BE64 ("a")
<01446> 010D0674 R WM_GETTEXT cchCopied:2 lpszText:0012CC44 ("a")
<01447> 010D0674 S CB_GETCURSEL
<01448> 010D0674 R CB_GETCURSEL index:CB_ERR
<01449> 010D0674 S WM_GETTEXTLENGTH
<01450> 01360696 S WM_GETTEXTLENGTH
<01451> 01360696 R WM_GETTEXTLENGTH cch:2
<01452> 010D0674 R WM_GETTEXTLENGTH cch:2
<01453> 010D0674 S WM_GETTEXT cchTextMax:6 lpszText:0012CC44
<01454> 01360696 S WM_GETTEXT cchTextMax:6 lpszText:0012BE64
<01455> 01360696 R WM_GETTEXT cchCopied:2 lpszText:0012BE64 ("a")
<01456> 010D0674 R WM_GETTEXT cchCopied:2 lpszText:0012CC44 ("a")
<01457> 010D0674 S CB_GETCURSEL
<01458> 010D0674 R CB_GETCURSEL index:CB_ERR
<01531> 0122064E R WM_PAINT
<01532> 010D0674 S WM_PAINT hdc:00000000
<01533> 010D0674 S WM_NCPAINT hrgn:00000001
<01534> 010D0674 R WM_NCPAINT
<01535> 010D0674 S WM_ERASEBKGND hdc:0F0141ED
<01536> 010D0674 R WM_ERASEBKGND fErased:True
<01537> 0122064E S WM_CTLCOLOREDIT hdcEdit:840137F1 hwndEdit:010D0674
<01538> 0122064E R WM_CTLCOLOREDIT hBrush:F0103EB0
<01539> 010D0674 R WM_PAINT
<01540> 01360696 S WM_PAINT hdc:00000000
<01541> 01360696 S WM_NCPAINT hrgn:00000001
<01542> 01360696 R WM_NCPAINT
<01543> 01360696 S WM_ERASEBKGND hdc:C7011AA6
<01544> 01360696 R WM_ERASEBKGND fErased:True
<01545> 010D0674 S WM_CTLCOLOREDIT hdcEdit:870137F1 hwndEdit:01360696
<01546> 010D0674 R WM_CTLCOLOREDIT hBrush:F0103EB0
<01547> 010D0674 S WM_CTLCOLOREDIT hdcEdit:870137F1 hwndEdit:01360696
<01548> 010D0674 R WM_CTLCOLOREDIT hBrush:F0103EB0
<01549> 01360696 R WM_PAINT
<01555> 0122064E S WM_CTLCOLOREDIT hdcEdit:8A0137F1 hwndEdit:010306AC
<01556> 0122064E R WM_CTLCOLOREDIT hBrush:78103C5B
<01568> 010D0674 S CB_GETCURSEL
<01569> 010D0674 R CB_GETCURSEL index:CB_ERR
<01570> 010D0674 S WM_GETTEXTLENGTH
<01571> 01360696 S WM_GETTEXTLENGTH
<01572> 01360696 R WM_GETTEXTLENGTH cch:2
<01573> 010D0674 R WM_GETTEXTLENGTH cch:2
<01574> 010D0674 S WM_GETTEXT cchTextMax:6 lpszText:0012D7A4
<01575> 01360696 S WM_GETTEXT cchTextMax:6 lpszText:0012C9C4
<01576> 01360696 R WM_GETTEXT cchCopied:2 lpszText:0012C9C4 ("a")
<01577> 010D0674 R WM_GETTEXT cchCopied:2 lpszText:0012D7A4 ("a")
<01578> 010D0674 S CB_GETCURSEL
<01579> 010D0674 R CB_GETCURSEL index:CB_ERR
<01580> 010D0674 S WM_GETTEXTLENGTH
<01581> 01360696 S WM_GETTEXTLENGTH
<01582> 01360696 R WM_GETTEXTLENGTH cch:2
<01583> 010D0674 R WM_GETTEXTLENGTH cch:2
<01584> 010D0674 S WM_GETTEXT cchTextMax:6 lpszText:0012D6E0
<01585> 01360696 S WM_GETTEXT cchTextMax:6 lpszText:0012C900
<01586> 01360696 R WM_GETTEXT cchCopied:2 lpszText:0012C900 ("a")
<01587> 010D0674 R WM_GETTEXT cchCopied:2 lpszText:0012D6E0 ("a")
<01588> 010D0674 S CB_GETCURSEL
<01589> 010D0674 R CB_GETCURSEL index:CB_ERR
<01590> 010D0674 S WM_GETTEXTLENGTH
<01591> 01360696 S WM_GETTEXTLENGTH
<01592> 01360696 R WM_GETTEXTLENGTH cch:2
<01593> 010D0674 R WM_GETTEXTLENGTH cch:2
<01594> 010D0674 S WM_GETTEXT cchTextMax:6 lpszText:0012D6E0
<01595> 01360696 S WM_GETTEXT cchTextMax:6 lpszText:0012C900
<01596> 01360696 R WM_GETTEXT cchCopied:2 lpszText:0012C900 ("a")
<01597> 010D0674 R WM_GETTEXT cchCopied:2 lpszText:0012D6E0 ("a")
<01598> 010D0674 R message:0x2111 [User-defined:WM_USER+7441] lResult:00000000
<01599> 01360696 S WM_GETTEXTLENGTH
<01600> 01360696 R WM_GETTEXTLENGTH cch:2
<01601> 01360696 S WM_GETTEXT cchTextMax:6 lpszText:0012DF8C
<01602> 01360696 R WM_GETTEXT cchCopied:2 lpszText:0012DF8C ("a")
<01603> 010D0674 R WM_COMMAND
<01604> 01360696 P WM_KEYUP nVirtKey:'A' cRepeat:1 ScanCode:1E fExtended:0 fAltDown:0 fRepeat:1 fUp:1
```
Letter q
```
<01625> 01360696 P WM_KEYDOWN nVirtKey:'Q' cRepeat:1 ScanCode:10 fExtended:0 fAltDown:0 fRepeat:0 fUp:0
<01626> 010D0674 S WM_GETDLGCODE
<01627> 010D0674 R WM_GETDLGCODE fuDlgCode:DLGC_WANTARROWS | DLGC_WANTCHARS
<01628> 010D0674 S WM_GETDLGCODE
<01629> 010D0674 R WM_GETDLGCODE fuDlgCode:DLGC_WANTARROWS | DLGC_WANTCHARS
<01630> 010D0674 S WM_GETDLGCODE
<01631> 010D0674 R WM_GETDLGCODE fuDlgCode:DLGC_WANTARROWS | DLGC_WANTCHARS
<01632> 010D0674 S WM_GETDLGCODE
<01633> 010D0674 R WM_GETDLGCODE fuDlgCode:DLGC_WANTARROWS | DLGC_WANTCHARS
<01634> 01360696 P WM_CHAR chCharCode:'0071' (113) cRepeat:1 ScanCode:10 fExtended:0 fAltDown:0 fRepeat:0 fUp:0
<01635> 010D0674 S WM_GETDLGCODE
<01636> 010D0674 R WM_GETDLGCODE fuDlgCode:DLGC_WANTARROWS | DLGC_WANTCHARS
<01637> 010D0674 S WM_GETDLGCODE
<01638> 010D0674 R WM_GETDLGCODE fuDlgCode:DLGC_WANTARROWS | DLGC_WANTCHARS
<01640> 01360696 P WM_KEYUP nVirtKey:'Q' cRepeat:1 ScanCode:10 fExtended:0 fAltDown:0 fRepeat:1 fUp:1
```
|
By any chance, have you already solved your problem?
I have the same problem as yours, my custom control for DataGridView cannot receive letter Q, period, dollar, single quote, percent, etc.
I was able to solve the problem by changing the "switch .. default: return false" to "switch .. default: return !dataGridViewWantsInputKey"
I guess the pattern code from Microsoft for making your own usercontrol for datagridview is not optimal. This is the pattern code from Microsoft:
<http://msdn.microsoft.com/en-au/library/7tas5c80(vs.80).aspx>
```
public bool EditingControlWantsInputKey(
Keys key, bool dataGridViewWantsInputKey)
{
// Let the DateTimePicker handle the keys listed.
switch (key & Keys.KeyCode)
{
case Keys.Left:
case Keys.Up:
case Keys.Down:
case Keys.Right:
case Keys.Home:
case Keys.End:
case Keys.PageDown:
case Keys.PageUp:
return true;
default:
return false; // I changed this to: return !dataGridViewWantsInputKey. My usercontrol can now receive Q, period, dollar, etc.
}
}
```
|
201,887 |
<p>Is there a cross database platform way to get the primary key of the record you have just inserted?</p>
<p>I noted that <a href="https://stackoverflow.com/questions/165156/easy-mysql-question-regarding-primary-keys-and-an-insert">this answer</a> says that you can get it by Calling <code>SELECT LAST_INSERT_ID()</code> and I think that you can call <code>SELECT @@IDENTITY AS 'Identity';</code> is there a common way to do this accross databases in jdbc?</p>
<p>If not how would you suggest I implement this for a piece of code that could access any of SQL Server, MySQL and Oracle?</p>
|
[
{
"answer_id": 202533,
"author": "extraneon",
"author_id": 24582,
"author_profile": "https://Stackoverflow.com/users/24582",
"pm_score": 7,
"selected": true,
"text": "<p>Copied from my code:</p>\n\n<pre><code>pInsertOid = connection.prepareStatement(INSERT_OID_SQL, Statement.RETURN_GENERATED_KEYS);\n</code></pre>\n\n<p>where pInsertOid is a prepared statement.</p>\n\n<p>you can then obtain the key:</p>\n\n<pre><code>// fill in the prepared statement and\npInsertOid.executeUpdate();\nResultSet rs = pInsertOid.getGeneratedKeys();\nif (rs.next()) {\n int newId = rs.getInt(1);\n oid.setId(newId);\n}\n</code></pre>\n\n<p>Hope this gives you a good starting point.</p>\n"
},
{
"answer_id": 202808,
"author": "anjanb",
"author_id": 11142,
"author_profile": "https://Stackoverflow.com/users/11142",
"pm_score": 1,
"selected": false,
"text": "<p>for oracle, Hibernate uses NEXT_VALUE from a sequence if you have mapped a sequence for PKEY value generation.</p>\n\n<p>Not sure what it does for MySQL or MS SQL server</p>\n"
},
{
"answer_id": 202920,
"author": "johnstok",
"author_id": 27929,
"author_profile": "https://Stackoverflow.com/users/27929",
"pm_score": 2,
"selected": false,
"text": "<p>Have you tried the <a href=\"http://java.sun.com/j2se/1.4.2/docs/api/java/sql/Statement.html\" rel=\"nofollow noreferrer\">Statement.executeUpdate()</a> and <a href=\"http://java.sun.com/j2se/1.4.2/docs/api/java/sql/Statement.html#getGeneratedKeys()\" rel=\"nofollow noreferrer\">Statement.getGeneratedKeys()</a> methods? There is a <a href=\"http://www.ibm.com/developerworks/java/library/j-jdbcnew/\" rel=\"nofollow noreferrer\">developerWorks article</a> that mentions the approach.</p>\n\n<p>Also, in JDBC 4.0 Sun added the <a href=\"http://www.onjava.com/pub/a/onjava/2006/08/02/jjdbc-4-enhancements-in-java-se-6.html\" rel=\"nofollow noreferrer\">row_id feature</a> that allows you to get a unique handle on a row. The feature is supported by Oracle and DB2. For sql server you will probably need a third party driver such as <a href=\"http://www.inetsoftware.de/products/jdbc/mssql/merlia/\" rel=\"nofollow noreferrer\">this one</a>.</p>\n\n<p>Good luck!</p>\n"
},
{
"answer_id": 212823,
"author": "Dónal",
"author_id": 2648,
"author_profile": "https://Stackoverflow.com/users/2648",
"pm_score": 1,
"selected": false,
"text": "<p>Spring provides some useful support for <a href=\"http://static.springframework.org/spring/docs/2.5.x/reference/jdbc.html#jdbc-auto-genereted-keys\" rel=\"nofollow noreferrer\">this operation</a> and the reference guide seems to answer your question:</p>\n\n<blockquote>\n <p>There is not a standard single way to\n create an appropriate\n PreparedStatement (which explains why\n the method signature is the way it\n is). An example that works on Oracle\n and may not work on other platforms\n is...</p>\n</blockquote>\n\n<p>I've tested this example on MySQL and it works there too, but I can't speak for other platforms.</p>\n"
},
{
"answer_id": 7570347,
"author": "Jeff Miller",
"author_id": 912813,
"author_profile": "https://Stackoverflow.com/users/912813",
"pm_score": 1,
"selected": false,
"text": "<p>For databases that conform to SQL-99, you can use identity columns:\nCREATE TABLE sometable (id INTEGER GENERATED ALWAYS AS IDENTITY(START WITH 101) PRIMARY KEY, ...</p>\n\n<p>Use <a href=\"http://download.oracle.com/javase/6/docs/api/java/sql/Statement.html#getGeneratedKeys%28%29\" rel=\"nofollow\">getGeneratedKeys()</a> to retrieve the key that was just inserted with <a href=\"http://download.oracle.com/javase/6/docs/api/java/sql/Statement.html#executeUpdate%28java.lang.String,%20int%29\" rel=\"nofollow\">executeUpdate(String sql, int autoGeneratedKeys)</a>. Use Statement.RETURN_GENERATED_KEYS for 2nd parameter to executeUpdate()</p>\n"
},
{
"answer_id": 13873673,
"author": "atripathi",
"author_id": 1862828,
"author_profile": "https://Stackoverflow.com/users/1862828",
"pm_score": 5,
"selected": false,
"text": "<p>extraneon's answer, although correct, <strong>doesn't work for Oracle</strong>.</p>\n\n<p>The way you do this for Oracle is:</p>\n\n<pre><code>String key[] = {\"ID\"}; //put the name of the primary key column\n\nps = con.prepareStatement(insertQuery, key);\nps.executeUpdate();\n\nrs = ps.getGeneratedKeys();\nif (rs.next()) {\n generatedKey = rs.getLong(1);\n}\n</code></pre>\n"
},
{
"answer_id": 31740789,
"author": "ANURAG SHARMA",
"author_id": 5176873,
"author_profile": "https://Stackoverflow.com/users/5176873",
"pm_score": -1,
"selected": false,
"text": "<p>Just declare id column as id integer not NULL primary key <code>auto_increment</code></p>\n\n<p>after this execute this code</p>\n\n<pre><code>ResultSet ds=st.executeQuery(\"select * from user\");\n while(ds.next())\n {\n\n ds.last();\n System.out.println(\"please note down your registration id which is \"+ds.getInt(\"id\"));\n }\n ds.close();\n</code></pre>\n\n<p>the above code will show you the current row's id</p>\n\n<p>if you remove <code>ds.last()</code> than it will show all values of id column</p>\n"
}
] |
2008/10/14
|
[
"https://Stackoverflow.com/questions/201887",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20400/"
] |
Is there a cross database platform way to get the primary key of the record you have just inserted?
I noted that [this answer](https://stackoverflow.com/questions/165156/easy-mysql-question-regarding-primary-keys-and-an-insert) says that you can get it by Calling `SELECT LAST_INSERT_ID()` and I think that you can call `SELECT @@IDENTITY AS 'Identity';` is there a common way to do this accross databases in jdbc?
If not how would you suggest I implement this for a piece of code that could access any of SQL Server, MySQL and Oracle?
|
Copied from my code:
```
pInsertOid = connection.prepareStatement(INSERT_OID_SQL, Statement.RETURN_GENERATED_KEYS);
```
where pInsertOid is a prepared statement.
you can then obtain the key:
```
// fill in the prepared statement and
pInsertOid.executeUpdate();
ResultSet rs = pInsertOid.getGeneratedKeys();
if (rs.next()) {
int newId = rs.getInt(1);
oid.setId(newId);
}
```
Hope this gives you a good starting point.
|
201,888 |
<p>Suppose I have a couple of spring beans: </p>
<pre><code><beans>
<bean name="A" ... />
<bean name="B" ... />
</beans>
</code></pre>
<p>"B" exposes a remote service that doesn't need "A". Assume that "A" takes a non-negligble time to load. What this means is that during a restart cycle, the application hangs the remote client, which can actually connect to the server but waits for a response until the spring container fully initializes. </p>
<p>What I'd like to be able to do is have the "B" remote service respond immediately, even if (based on the application state) it can only return NOT_READY or some such. The container, however, forces a wait until all of it's beans are initialized, even if you specify the beans as lazy-init and irrespective of load order. </p>
<p>I suspect that having "B" available immediately would mean that spring would have to make available a partially initialized container, which sounds bad. However, I'd appreciate any information anyone's got on the initialization order and whether you've found any reasonable workarounds. </p>
|
[
{
"answer_id": 202565,
"author": "Arne Burmeister",
"author_id": 12890,
"author_profile": "https://Stackoverflow.com/users/12890",
"pm_score": 0,
"selected": false,
"text": "<p>I do not understand, why \"A takes a non-negligble time to load\", but maybe you could to a lazy initialize yourself by refactoring A. Do not use InitializingBean or handle an ApplicationEvent. Just initialize on the first Request to be handled. This will slow down the first request!</p>\n\n<p>The other possibility is to move the initialization to a separated thread created by the bean handling an ApplicationEvent. The thread calls the initialization method of the bean an async way. Be carefull to handle Requests to the uninitialized bean!</p>\n"
},
{
"answer_id": 210142,
"author": "Paul Sonier",
"author_id": 28053,
"author_profile": "https://Stackoverflow.com/users/28053",
"pm_score": 3,
"selected": true,
"text": "<p>Don't refer to bean \"A\" directly. Instead, refer to a bean which is a FACTORY for bean \"A\"; in this way, the Factory bean can be created without taking the initialization hit for instantiating \"A\". You'll need to refactor your classes which refer to an \"A\" to retrieve an \"A\" first, of course.</p>\n\n<p>Or, you could create a bean \"AA\", which is a container for bean \"A\", which has an initialization state, and which exposes the interface of bean \"A\"; upon invocation, it sets its initialization state to not initialized, and begins initialization of bean \"A\" in some thread; calls to any interface methods of \"A\" on \"AA\" can then either block or return a not ready response, until the initialization of \"A\" within \"AA\" has completed.</p>\n\n<p>This all kinda hinges on what your definition of \"takes a non-negligible time to load\" is. Why does it take a non-negligible amount of time to load? Is there some particularly tricky initialization that's going on within A? Or is A just so monstrously huge that it chokes the JVM?</p>\n"
}
] |
2008/10/14
|
[
"https://Stackoverflow.com/questions/201888",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/19479/"
] |
Suppose I have a couple of spring beans:
```
<beans>
<bean name="A" ... />
<bean name="B" ... />
</beans>
```
"B" exposes a remote service that doesn't need "A". Assume that "A" takes a non-negligble time to load. What this means is that during a restart cycle, the application hangs the remote client, which can actually connect to the server but waits for a response until the spring container fully initializes.
What I'd like to be able to do is have the "B" remote service respond immediately, even if (based on the application state) it can only return NOT\_READY or some such. The container, however, forces a wait until all of it's beans are initialized, even if you specify the beans as lazy-init and irrespective of load order.
I suspect that having "B" available immediately would mean that spring would have to make available a partially initialized container, which sounds bad. However, I'd appreciate any information anyone's got on the initialization order and whether you've found any reasonable workarounds.
|
Don't refer to bean "A" directly. Instead, refer to a bean which is a FACTORY for bean "A"; in this way, the Factory bean can be created without taking the initialization hit for instantiating "A". You'll need to refactor your classes which refer to an "A" to retrieve an "A" first, of course.
Or, you could create a bean "AA", which is a container for bean "A", which has an initialization state, and which exposes the interface of bean "A"; upon invocation, it sets its initialization state to not initialized, and begins initialization of bean "A" in some thread; calls to any interface methods of "A" on "AA" can then either block or return a not ready response, until the initialization of "A" within "AA" has completed.
This all kinda hinges on what your definition of "takes a non-negligible time to load" is. Why does it take a non-negligible amount of time to load? Is there some particularly tricky initialization that's going on within A? Or is A just so monstrously huge that it chokes the JVM?
|
201,893 |
<p>I'm working to set up Panda on an Amazon EC2 instance.
I set up my account and tools last night and had no problem using SSH to interact with my own personal instance, but right now I'm not being allowed permission into Panda's EC2 instance.
<a href="http://pandastream.com/docs/getting_started" rel="noreferrer">Getting Started with Panda</a></p>
<p>I'm getting the following error:</p>
<pre><code>@ WARNING: UNPROTECTED PRIVATE KEY FILE! @
Permissions 0644 for '~/.ec2/id_rsa-gsg-keypair' are too open.
It is recommended that your private key files are NOT accessible by others.
This private key will be ignored.
</code></pre>
<p>I've chmoded my keypair to 600 in order to get into my personal instance last night, and experimented at length setting the permissions to 0 and even generating new key strings, but nothing seems to be working.</p>
<p>Any help at all would be a great help!</p>
<hr>
<p>Hm, it seems as though unless permissions are set to 777 on the directory, the ec2-run-instances script is unable to find my keyfiles.
I'm new to SSH so I might be overlooking something.</p>
|
[
{
"answer_id": 201898,
"author": "Mark Biek",
"author_id": 305,
"author_profile": "https://Stackoverflow.com/users/305",
"pm_score": 6,
"selected": false,
"text": "<p>Make sure that the directory containing the private key files is set to <strong>700</strong></p>\n\n<pre><code>chmod 700 ~/.ec2\n</code></pre>\n"
},
{
"answer_id": 217729,
"author": "Stu Thompson",
"author_id": 2961,
"author_profile": "https://Stackoverflow.com/users/2961",
"pm_score": 9,
"selected": true,
"text": "<blockquote>\n <p>I've chmoded my keypair to 600 in order to get into my personal instance last night,</p>\n</blockquote>\n\n<p>And this is the way it is supposed to be. </p>\n\n<p>From the <a href=\"http://docs.aws.amazon.com/AWSEC2/latest/UserGuide/AccessingInstancesLinux.html\" rel=\"noreferrer\">EC2 documentation</a> we have <em>\"If you're using OpenSSH (or any reasonably paranoid SSH client) then you'll probably need to set the permissions of this file so that it's only readable by you.\"</em> The Panda documentation you link to links to Amazon's documentation but really doesn't convey how important it all is.</p>\n\n<p>The idea is that the key pair files are like passwords and need to be protected. So, the ssh client you are using requires that those files be secured and that only your account can read them.</p>\n\n<p>Setting the directory to 700 really should be enough, but 777 is not going to hurt as long as the files are 600.</p>\n\n<p>Any problems you are having are client side, so be sure to include local OS information with any follow up questions! </p>\n"
},
{
"answer_id": 25681412,
"author": "Alena",
"author_id": 989896,
"author_profile": "https://Stackoverflow.com/users/989896",
"pm_score": 6,
"selected": false,
"text": "<p>To fix this,</p>\n<ol>\n<li><p>you’ll need to reset the permissions back to default:</p>\n<pre><code>sudo chmod 600 ~/.ssh/id_rsa\nsudo chmod 600 ~/.ssh/id_rsa.pub\n</code></pre>\n<p>If you are getting another error:</p>\n<ul>\n<li>Are you sure you want to continue connecting (yes/no)? yes</li>\n<li>Failed to add the host to the list of known hosts (/home/geek/.ssh/known_hosts).</li>\n</ul>\n</li>\n<li><p>This means that the permissions on that file are also set incorrectly, and can be adjusted with this:</p>\n<pre><code>sudo chmod 644 ~/.ssh/known_hosts\n</code></pre>\n</li>\n</ol>\n<ol start=\"3\">\n<li><p>Finally, you may need to adjust the directory permissions as well:</p>\n<pre><code>sudo chmod 755 ~/.ssh\n</code></pre>\n</li>\n</ol>\n<p>This should get you back up and running.</p>\n"
},
{
"answer_id": 29692711,
"author": "Sandeep Sasikumar",
"author_id": 4341230,
"author_profile": "https://Stackoverflow.com/users/4341230",
"pm_score": 5,
"selected": false,
"text": "<p>The private key file should be protected. In my case i have been using the public_key authentication for a long time and i used to set the permission as 600 (rw- --- ---) for private key and 644 (rw- r-- r--) and for the .ssh folder in the home folder you will have 700 permission (rwx --- ---). For setting this go to the user's home folder and run the following command</p>\n\n<p><br>Set the <strong>700</strong> permission for .ssh folder</p>\n\n<pre><code>chmod 700 .ssh\n</code></pre>\n\n<p><br>Set the <strong>600</strong> permission for private key file</p>\n\n<pre><code>chmod 600 .ssh/id_rsa\n</code></pre>\n\n<p><br>Set <strong>644</strong> permission for public key file</p>\n\n<pre><code>chmod 644 .ssh/id_rsa.pub\n</code></pre>\n"
},
{
"answer_id": 44410255,
"author": "Prince Charu",
"author_id": 8124996,
"author_profile": "https://Stackoverflow.com/users/8124996",
"pm_score": 2,
"selected": false,
"text": "<p>Keep your private key, public key, known_hosts in same directory and try login as below:</p>\n\n<pre><code>ssh -I(small i) \"hi.pem\" ec2-user@ec2-**-***-**-***.us-west-2.compute.amazonaws.com\n</code></pre>\n\n<ul>\n<li>Same directory in the sense, \n<code>cd /Users/prince/Desktop</code>. \nNow type <code>ls</code> command \nand you should see \n<code>**.pem **.ppk known_hosts</code></li>\n</ul>\n\n<p><strong>Note:</strong> You have to try to login from the same directory or you'll get a permission denied error as it can't find the .pem file from your present directory.</p>\n\n<hr>\n\n<p>If you want to be able to SSH from any directory, you can add the following to you <code>~/.ssh/config</code> file...</p>\n\n<pre><code>Host your.server\nHostName ec2-user@ec2-**-***-**-***.us-west-2.compute.amazonaws.com\nUser ec2-user\nIdentityFile ~/.ec2/id_rsa-gsg-keypair\nIdentitiesOnly yes\n</code></pre>\n\n<p>Now you can SSH to your server regardless of where the directory is by simply typing <code>ssh your.server</code> (or whatever name you place after \"Host\").</p>\n"
},
{
"answer_id": 44533445,
"author": "Abdel Hegazi",
"author_id": 2080766,
"author_profile": "https://Stackoverflow.com/users/2080766",
"pm_score": 0,
"selected": false,
"text": "<p>I am thinking about something else, if you are trying to login with a different username that doesn't exist this is the message you will get.</p>\n\n<p>So I assume you may be trying to ssh with ec2-user but I recall recently most of centos AMIs for example are using centos user instead of ec2-user</p>\n\n<p>so if you are \n<code>ssh -i file.pem centos@public_IP</code> please tell me you aretrying to ssh with the right user name otherwise this may be a strong reason of you see such error message even with the right permissions on your ~/.ssh/id_rsa or file.pem</p>\n"
},
{
"answer_id": 51299474,
"author": "ANAND SONI",
"author_id": 4907956,
"author_profile": "https://Stackoverflow.com/users/4907956",
"pm_score": 5,
"selected": false,
"text": "<p>I also got the same issue, but I fix it by changing my key file permission to 600.</p>\n<p><code>sudo chmod 600 /path/to/my/key.pem</code></p>\n"
},
{
"answer_id": 53799161,
"author": "Dheeraj",
"author_id": 5985586,
"author_profile": "https://Stackoverflow.com/users/5985586",
"pm_score": 3,
"selected": false,
"text": "<p>On windows, Try using git bash and use your Linux commands there. Easy approach</p>\n\n<pre><code>chmod 400 *****.pem\n\nssh -i \"******.pem\" [email protected]\n</code></pre>\n"
},
{
"answer_id": 56860192,
"author": "Kubie",
"author_id": 8422565,
"author_profile": "https://Stackoverflow.com/users/8422565",
"pm_score": -1,
"selected": false,
"text": "<p>Just a note for anyone who stumbles upon this:</p>\n\n<p>If you are trying to SSH with a key that has been shared with you, for example:</p>\n\n<p><code>ssh -i /path/to/keyfile.pem user@some-host</code></p>\n\n<p>Where <code>keyfile.pem</code> is the private/public key shared with you and you're using it to connect, <strong>make sure you save it into <code>~/.ssh/</code> and <code>chmod 777</code>.</strong></p>\n\n<p>Trying to use the file when it was saved elsewhere on my machine was giving the OP's error. Not sure if it is directly related.</p>\n"
},
{
"answer_id": 57288745,
"author": "Greenkraftz",
"author_id": 9794314,
"author_profile": "https://Stackoverflow.com/users/9794314",
"pm_score": 3,
"selected": false,
"text": "<p>Change the File Permission using chmod command </p>\n\n<pre><code>sudo chmod 700 keyfile.pem\n</code></pre>\n"
},
{
"answer_id": 58452178,
"author": "Luc",
"author_id": 1201863,
"author_profile": "https://Stackoverflow.com/users/1201863",
"pm_score": 0,
"selected": false,
"text": "<p>The solution is to make it readable only by the owner of the file, i.e. the last two digits of the octal mode representation should be zero (e.g. mode <code>0400</code>).</p>\n\n<p>OpenSSH checks this in <code>authfile.c</code>, in a function named <code>sshkey_perm_ok</code>:</p>\n\n<pre><code>/*\n * if a key owned by the user is accessed, then we check the\n * permissions of the file. if the key owned by a different user,\n * then we don't care.\n */\nif ((st.st_uid == getuid()) && (st.st_mode & 077) != 0) {\n error(\"@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@\");\n error(\"@ WARNING: UNPROTECTED PRIVATE KEY FILE! @\");\n error(\"@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@\");\n error(\"Permissions 0%3.3o for '%s' are too open.\",\n (u_int)st.st_mode & 0777, filename);\n error(\"It is required that your private key files are NOT accessible by others.\");\n error(\"This private key will be ignored.\");\n return SSH_ERR_KEY_BAD_PERMISSIONS;\n}\n</code></pre>\n\n<p>See the first line after the comment: it does a \"bitwise and\" against the mode of the file, selecting all bits in the last two octal digits (since <code>07</code> is octal for <code>0b111</code>, where each bit stands for r/w/x, respectively).</p>\n"
},
{
"answer_id": 70146311,
"author": "Shri_Automation",
"author_id": 6188559,
"author_profile": "https://Stackoverflow.com/users/6188559",
"pm_score": 1,
"selected": false,
"text": "<p>Just to brief the issue, that pem files permissions are open for every user on machine i.e any one can read and write on that file\nOn windows it difficult to do chmod the way I found was using a git bash.\nI have followed below steps</p>\n<ol>\n<li><p>Remove user permissions</p>\n<p>chmod ugo-rwx abc.pem</p>\n</li>\n<li><p>Add permission only for that user</p>\n<p>chmod u+rw</p>\n</li>\n<li><p>run chmod 400</p>\n<p>chmod 400 abc.pem</p>\n</li>\n</ol>\n<p>4.Now try ssh -i for your instance</p>\n"
},
{
"answer_id": 74109836,
"author": "Sandip Mahato",
"author_id": 13913019,
"author_profile": "https://Stackoverflow.com/users/13913019",
"pm_score": 0,
"selected": false,
"text": "<p>If you are on a windows machine just copy the .pem file into C drive any folder and\nre-run the command.</p>\n<pre><code>ssh -i /path/to/keyfile.pem user@some-host\n</code></pre>\n<p>In my case, I put that file in downloads and this actually works.</p>\n<p>Or follow this <a href=\"https://99robots.com/how-to-fix-permission-error-ssh-amazon-ec2-instance/\" rel=\"nofollow noreferrer\">https://99robots.com/how-to-fix-permission-error-ssh-amazon-ec2-instance/</a></p>\n"
}
] |
2008/10/14
|
[
"https://Stackoverflow.com/questions/201893",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2293/"
] |
I'm working to set up Panda on an Amazon EC2 instance.
I set up my account and tools last night and had no problem using SSH to interact with my own personal instance, but right now I'm not being allowed permission into Panda's EC2 instance.
[Getting Started with Panda](http://pandastream.com/docs/getting_started)
I'm getting the following error:
```
@ WARNING: UNPROTECTED PRIVATE KEY FILE! @
Permissions 0644 for '~/.ec2/id_rsa-gsg-keypair' are too open.
It is recommended that your private key files are NOT accessible by others.
This private key will be ignored.
```
I've chmoded my keypair to 600 in order to get into my personal instance last night, and experimented at length setting the permissions to 0 and even generating new key strings, but nothing seems to be working.
Any help at all would be a great help!
---
Hm, it seems as though unless permissions are set to 777 on the directory, the ec2-run-instances script is unable to find my keyfiles.
I'm new to SSH so I might be overlooking something.
|
>
> I've chmoded my keypair to 600 in order to get into my personal instance last night,
>
>
>
And this is the way it is supposed to be.
From the [EC2 documentation](http://docs.aws.amazon.com/AWSEC2/latest/UserGuide/AccessingInstancesLinux.html) we have *"If you're using OpenSSH (or any reasonably paranoid SSH client) then you'll probably need to set the permissions of this file so that it's only readable by you."* The Panda documentation you link to links to Amazon's documentation but really doesn't convey how important it all is.
The idea is that the key pair files are like passwords and need to be protected. So, the ssh client you are using requires that those files be secured and that only your account can read them.
Setting the directory to 700 really should be enough, but 777 is not going to hurt as long as the files are 600.
Any problems you are having are client side, so be sure to include local OS information with any follow up questions!
|
201,896 |
<p>I want something that can check if a string is <code>"SELECT"</code>, <code>"INSERT"</code>, etc. I'm just curious if this exists.</p>
|
[
{
"answer_id": 201901,
"author": "Richard Harrison",
"author_id": 19624,
"author_profile": "https://Stackoverflow.com/users/19624",
"pm_score": 1,
"selected": false,
"text": "<p>why not start with <a href=\"http://www.novicksoftware.com/UDFofWeek/Vol2/T-SQL-UDF-Vol-2-Num-29-udf_SQL2K_IsKeywordBIT.htm\" rel=\"nofollow noreferrer\">this stored procedure</a> and modify it to suit your needs, possibly even convert it to Java using the hashmap as Steve suggested.</p>\n\n<p>Personally I like the idea of a stored procedure because different databases may have different keywords so it seems elegant to have the database pass judgement</p>\n"
},
{
"answer_id": 201902,
"author": "Steve B.",
"author_id": 19479,
"author_profile": "https://Stackoverflow.com/users/19479",
"pm_score": 3,
"selected": true,
"text": "<p>Easy enough to add : </p>\n\n<pre><code> HashSet<String> sqlKeywords =\n new HashSet<String>(Arrays.asList(\n new String[] { ... cut and paste a list of sql keywords here .. }));\n</code></pre>\n"
},
{
"answer_id": 202596,
"author": "Chase Seibert",
"author_id": 7679,
"author_profile": "https://Stackoverflow.com/users/7679",
"pm_score": 2,
"selected": false,
"text": "<p>If you're trying to prevent SQL injection, it would be better to leverage the built in features of JDBC, such as prepared statements. In general, using string concatenation to form the SQL statement is dangerous. From <a href=\"http://www.owasp.org/index.php/Preventing_SQL_Injection_in_Java\" rel=\"nofollow noreferrer\">Preventing SQL Injection in Java</a>:</p>\n\n<p><strong>Prepared Statements</strong>:</p>\n\n<pre><code>String selectStatement = \"SELECT * FROM User WHERE userId = ? \";\nPreparedStatement prepStmt = con.prepareStatement(selectStatement);\nprepStmt.setString(1, userId);\nResultSet rs = prepStmt.executeQuery();\n</code></pre>\n"
},
{
"answer_id": 202619,
"author": "Tom Hawtin - tackline",
"author_id": 4725,
"author_profile": "https://Stackoverflow.com/users/4725",
"pm_score": 1,
"selected": false,
"text": "<p>DatabaseMetaData.getSQLKeywords will return the databases keywords that are not in SQL-2003 (SQL-2003 keyword can be found in the standard). There are other methods within that interface for getting various types of function names and similar.</p>\n\n<p>As Chase Seibert mentions, don't think this is an effective way to block SQL injection attacks.</p>\n"
}
] |
2008/10/14
|
[
"https://Stackoverflow.com/questions/201896",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2484/"
] |
I want something that can check if a string is `"SELECT"`, `"INSERT"`, etc. I'm just curious if this exists.
|
Easy enough to add :
```
HashSet<String> sqlKeywords =
new HashSet<String>(Arrays.asList(
new String[] { ... cut and paste a list of sql keywords here .. }));
```
|
201,919 |
<p>I'm living in nightmares because of this situation, I have a HttpWebRequest.GetResponse that keeps on giving me a ThreadAbortException, that causes the whole app to go down.</p>
<p>How can I avoid that, or at least handle it, would using Thread.ResetAbort() be useful in such a case?</p>
<p>To explain more here is a rough code sample:</p>
<pre><code>HttpWebRequest req = (HttpWebRequest)WebRequest.Create("http://someurl.com/");
HttpWebResponse resp = req.GetResponse();
</code></pre>
<p>now the last line above throws the ThreadAbortException, it might be because the request timed out which is fine, but I don't want to get a ThreadAbortException inside my ASP.NET 2.0 app because it kills it. The ThreadAborException can't be caught with try/catch, the only way to handle it is using Thread.ResetAbort() which has its own bad effects too, it will keep the thread alive and god only knows for how long.</p>
|
[
{
"answer_id": 201945,
"author": "StingyJack",
"author_id": 16391,
"author_profile": "https://Stackoverflow.com/users/16391",
"pm_score": 2,
"selected": false,
"text": "<p>I had this problem with using Response. Check out this article for some workarounds. <a href=\"http://support.microsoft.com/kb/312629\" rel=\"nofollow noreferrer\">http://support.microsoft.com/kb/312629</a></p>\n\n<p>Also take a look at this MSDN documentation in the section for WebException and Remarks. <a href=\"http://msdn.microsoft.com/en-us/library/system.net.httpwebrequest.getresponse.aspx\" rel=\"nofollow noreferrer\">http://msdn.microsoft.com/en-us/library/system.net.httpwebrequest.getresponse.aspx</a> </p>\n\n<p>This exception can be caught... If you are having trouble detecting the right one, you should try catching a general exception (system.Exception) and from there the stack trace should tell you the specific type (HttpException, WebException, etc) to actually catch. </p>\n"
},
{
"answer_id": 202025,
"author": "ForCripeSake",
"author_id": 14833,
"author_profile": "https://Stackoverflow.com/users/14833",
"pm_score": 0,
"selected": false,
"text": "<p>Our application threw ThreadAbortException's all the time b/c of\nResponse.Redirect(\"url\") calls. The app never closed, most likely b/c the exception was being caught at some point and remained active.</p>\n\n<p>Incidentally, Response.Redirect(\"url\",false) will prevent the Response from terminating with the exception. Andrew's post links to similar workarounds for different uses of the Response class.</p>\n"
},
{
"answer_id": 202224,
"author": "Zachary Yates",
"author_id": 8360,
"author_profile": "https://Stackoverflow.com/users/8360",
"pm_score": 0,
"selected": false,
"text": "<p>I've seen both of the problems listed by Andrew and \"ForCripesSake\".</p>\n\n<p>Another possibility for your ThreadAbortException is any code that runs outside the page request lifecycle on the server side, such as HttpModules and HttpHandlers. Any exceptions thrown within a module or handler don't go to the default unhandled exception mechanism in ASP.Net, and can cause the thread to die.</p>\n\n<p>There are a couple of exceptions that can't be handled easily in ASP.net or the CLR in general, according to this article:</p>\n\n<p><a href=\"http://msdn.microsoft.com/en-us/library/ms228970(VS.80).aspx\" rel=\"nofollow noreferrer\">Reliability Best Practices</a></p>\n\n<p>Not sure if it applies to the client code you've listed in your question, but it might be related.</p>\n\n<p>Hope that helps!</p>\n"
},
{
"answer_id": 202667,
"author": "Joe",
"author_id": 13087,
"author_profile": "https://Stackoverflow.com/users/13087",
"pm_score": 5,
"selected": true,
"text": "<p>From what you say it seems you are making an outgoing WebRequest to an external resource from within the processing of an incoming request to an ASP.NET application. There are (at least) two timeouts that are relevant here:</p>\n\n<ul>\n<li><p>WebRequest.Timeout (default 100000ms = 100s) specifies the timeout for execution of the outgoing WebRequest. If this timeout expires, you should get a WebException - so this isn't your problem.</p></li>\n<li><p>The HttpRuntime that is processing your incoming request has an execution timeout: the default value according to <a href=\"http://msdn.microsoft.com/en-us/library/e1f13641.aspx\" rel=\"noreferrer\">MSDN</a> is 110s for .NET 2.0 or later, 90s for .NET 1.x. When this timeout expires, you'll get a ThreadAbortException. It looks like this is what is happening.</p></li>\n</ul>\n\n<p>In .NET 1.x, you'd expect this, because the default HttpRuntime executionTimeout is less than WebRequest.Timeout. In .NET 2.0, you'd expect this with the default timeouts if you have already spent >10s before making the outgoing WebRequest (e.g. if you have more than one outgoing WebRequest from within the same incoming request).</p>\n\n<p>I would suggest you either:</p>\n\n<ul>\n<li><p>Reduce the WebRequest.Timeout for outgoing requests, and handle WebException, or</p></li>\n<li><p>If the outgoing requests can really take that long, then increase the httpRuntime execution timeout as described in <a href=\"http://msdn.microsoft.com/en-us/library/e1f13641.aspx\" rel=\"noreferrer\">MSDN</a>.</p></li>\n</ul>\n"
}
] |
2008/10/14
|
[
"https://Stackoverflow.com/questions/201919",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20006/"
] |
I'm living in nightmares because of this situation, I have a HttpWebRequest.GetResponse that keeps on giving me a ThreadAbortException, that causes the whole app to go down.
How can I avoid that, or at least handle it, would using Thread.ResetAbort() be useful in such a case?
To explain more here is a rough code sample:
```
HttpWebRequest req = (HttpWebRequest)WebRequest.Create("http://someurl.com/");
HttpWebResponse resp = req.GetResponse();
```
now the last line above throws the ThreadAbortException, it might be because the request timed out which is fine, but I don't want to get a ThreadAbortException inside my ASP.NET 2.0 app because it kills it. The ThreadAborException can't be caught with try/catch, the only way to handle it is using Thread.ResetAbort() which has its own bad effects too, it will keep the thread alive and god only knows for how long.
|
From what you say it seems you are making an outgoing WebRequest to an external resource from within the processing of an incoming request to an ASP.NET application. There are (at least) two timeouts that are relevant here:
* WebRequest.Timeout (default 100000ms = 100s) specifies the timeout for execution of the outgoing WebRequest. If this timeout expires, you should get a WebException - so this isn't your problem.
* The HttpRuntime that is processing your incoming request has an execution timeout: the default value according to [MSDN](http://msdn.microsoft.com/en-us/library/e1f13641.aspx) is 110s for .NET 2.0 or later, 90s for .NET 1.x. When this timeout expires, you'll get a ThreadAbortException. It looks like this is what is happening.
In .NET 1.x, you'd expect this, because the default HttpRuntime executionTimeout is less than WebRequest.Timeout. In .NET 2.0, you'd expect this with the default timeouts if you have already spent >10s before making the outgoing WebRequest (e.g. if you have more than one outgoing WebRequest from within the same incoming request).
I would suggest you either:
* Reduce the WebRequest.Timeout for outgoing requests, and handle WebException, or
* If the outgoing requests can really take that long, then increase the httpRuntime execution timeout as described in [MSDN](http://msdn.microsoft.com/en-us/library/e1f13641.aspx).
|
201,933 |
<p>We have a DLL used as the middle layer between our website front end and our back end ticketing system. The method of insertion into the ticketing system is a bit complicated to explain, but the short version is that it's slow. The best case scenario I've gotten is a 9 second submission time.</p>
<p>The real problem though, is that I can only get that time through a Windows app, not through an ASP.NET web site. I've set up both a Windows test application and a web page for testing, and even though the code is copied between them the web page is consistently submitting in 17-20 seconds, while the windows app is getting 8-11 seconds.</p>
<p>What could be causing that?</p>
<p>EDIT: In response to a couple of the answers...</p>
<p>The call to the web service is taking the bulk of the time, but I have no control over this web service as it's provided by the ticketing system vendor. I need to find out why the web service is taking different amounts of time when it's being called form a different kind of application. The code is exactly the same in both cases, and it's running a loop then reporting the times recorded.</p>
<p>The code is:</p>
<pre><code>for (int i = 0; i < numIterations; i++)
{
startTimes[i] = DateTime.Now;
try
{
cvNum = Clearview.Submit(req, DateTime.Now, DateTime.Now, false);
}
catch (Exception ex)
{
exceptionCount++;
lblResult.Text += @"<br />Exception Caught: " + ex.Message + @"<br />";
}
endTimes[i] = DateTime.Now;
}
</code></pre>
<p>It's the same loop in both cases, and I'm marking the time right before and after the call to the library, which does further processing and then calls the web service. But that processing should be consistent shouldn't it? I have traced during debugging and not seen any delay getting to the actual web service call...</p>
<p>EDIT Again: Working with Ants, in both cases 99.4% of the time is being sent just on the web service call. There appears to be no difference there... except that when timed out the web page is taking longer than the windows app.</p>
|
[
{
"answer_id": 201987,
"author": "Jon Skeet",
"author_id": 22656,
"author_profile": "https://Stackoverflow.com/users/22656",
"pm_score": 1,
"selected": false,
"text": "<p>Pepper your application on both sides with logs - that will show you where the time is going. If that doesn't help, use <a href=\"http://www.wireshark.org/\" rel=\"nofollow noreferrer\">Wireshark</a> to trace the network activity.</p>\n"
},
{
"answer_id": 202085,
"author": "Mitchel Sellers",
"author_id": 13279,
"author_profile": "https://Stackoverflow.com/users/13279",
"pm_score": 2,
"selected": false,
"text": "<p>Potentially the location of the web service in relation to the web server could be having an issue. Also, the page structure and other processing inside your web UI could be having an impact on how long it takes the application to process.</p>\n\n<p>As mentioned logging items on both sides is a great idea, if that doesn't get you what you need, you might try a performance profiler such as Ants Profiler by Red Gate that can help identify the line, method, or class that is using the bulk of the time.</p>\n"
},
{
"answer_id": 202150,
"author": "Toybuilder",
"author_id": 22329,
"author_profile": "https://Stackoverflow.com/users/22329",
"pm_score": 2,
"selected": true,
"text": "<p>Are you running both on the same machine? Is the middle-layer that you are calling located on a remote machine? The time durations you mentioned vaguely feels like a DNS timeout issue, when opening a connection incurs the penalty for the first (down/misaddressed) DNS response to timeout. Are you sure that whatever config file/var pointing the DLL to the middle-layer are the same in both invocations?</p>\n\n<p>I second the suggestion to use Wireshark to see what is going on. You can at least satisfy yourself that the backend processing time is (should be, anyways) the same...</p>\n"
}
] |
2008/10/14
|
[
"https://Stackoverflow.com/questions/201933",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/17145/"
] |
We have a DLL used as the middle layer between our website front end and our back end ticketing system. The method of insertion into the ticketing system is a bit complicated to explain, but the short version is that it's slow. The best case scenario I've gotten is a 9 second submission time.
The real problem though, is that I can only get that time through a Windows app, not through an ASP.NET web site. I've set up both a Windows test application and a web page for testing, and even though the code is copied between them the web page is consistently submitting in 17-20 seconds, while the windows app is getting 8-11 seconds.
What could be causing that?
EDIT: In response to a couple of the answers...
The call to the web service is taking the bulk of the time, but I have no control over this web service as it's provided by the ticketing system vendor. I need to find out why the web service is taking different amounts of time when it's being called form a different kind of application. The code is exactly the same in both cases, and it's running a loop then reporting the times recorded.
The code is:
```
for (int i = 0; i < numIterations; i++)
{
startTimes[i] = DateTime.Now;
try
{
cvNum = Clearview.Submit(req, DateTime.Now, DateTime.Now, false);
}
catch (Exception ex)
{
exceptionCount++;
lblResult.Text += @"<br />Exception Caught: " + ex.Message + @"<br />";
}
endTimes[i] = DateTime.Now;
}
```
It's the same loop in both cases, and I'm marking the time right before and after the call to the library, which does further processing and then calls the web service. But that processing should be consistent shouldn't it? I have traced during debugging and not seen any delay getting to the actual web service call...
EDIT Again: Working with Ants, in both cases 99.4% of the time is being sent just on the web service call. There appears to be no difference there... except that when timed out the web page is taking longer than the windows app.
|
Are you running both on the same machine? Is the middle-layer that you are calling located on a remote machine? The time durations you mentioned vaguely feels like a DNS timeout issue, when opening a connection incurs the penalty for the first (down/misaddressed) DNS response to timeout. Are you sure that whatever config file/var pointing the DLL to the middle-layer are the same in both invocations?
I second the suggestion to use Wireshark to see what is going on. You can at least satisfy yourself that the backend processing time is (should be, anyways) the same...
|
201,956 |
<p>Often times I need a collection of non-sequential objects with numeric identifiers. I like using the KeyedCollection for this, but I think there's a serious drawback. If you use an int for the key, you can no longer access members of the collection by their index (collection[index] is now really collection[key]). Is this a serious enough problem to avoid using the int as the key? What would a preferable alternative be? (maybe int.ToString()?)</p>
<p>I've done this before without any major problems, but recently I hit a nasty snag where XML serialization against a KeyedCollection does <em>not</em> work if the key is an int, due to <a href="http://connect.microsoft.com/VisualStudio/feedback/ViewFeedback.aspx?FeedbackID=120461" rel="noreferrer">a bug in .NET</a>.</p>
|
[
{
"answer_id": 201968,
"author": "Mark Cidade",
"author_id": 1659,
"author_profile": "https://Stackoverflow.com/users/1659",
"pm_score": 2,
"selected": false,
"text": "<p>It might be best to add a <strong><code>GetById(int)</code></strong> method to a collection type. <code>Collection<T></code> can be used instead if you don't need any other key for accessing the contained objects:</p>\n\n<pre><code>public class FooCollection : Collection<Foo>\n { Dictionary<int,Foo> dict = new Dictionary<int,Foo>();\n\n public Foo GetById(int id) { return dict[id]; }\n\n public bool Contains(int id) { return dict.Containskey(id);}\n\n protected override void InsertItem(Foo f)\n { dict[f.Id] = f;\n base.InsertItem(f);\n }\n\n protected override void ClearItems()\n { dict.Clear();\n base.ClearItems();\n }\n\n protected override void RemoveItem(int index)\n { dict.Remove(base.Items[index].Id);\n base.RemoveItem(index);\n }\n\n protected override void SetItem(int index, Foo item)\n { dict.Remove(base.Items[index].Id);\n dict[item.Id] = item;\n base.SetItem(index, item);\n }\n }\n\n\n\n\n\n\n\n\n\n }\n</code></pre>\n"
},
{
"answer_id": 201976,
"author": "Joel Coehoorn",
"author_id": 3043,
"author_profile": "https://Stackoverflow.com/users/3043",
"pm_score": 1,
"selected": false,
"text": "<p>The key in a KeyedCollection should be unique and quickly derivable from the object being collected. Given a person class, for example, it could be the SSN property or perhaps even concatenating FirstName and LastName properties (if the result is known to be unique). If an ID is legitimately a field of the object being collected than it is a valid candidate for the key. But perhaps try casting it as a string instead to avoid the collision.</p>\n"
},
{
"answer_id": 201983,
"author": "Konrad Rudolph",
"author_id": 1968,
"author_profile": "https://Stackoverflow.com/users/1968",
"pm_score": 2,
"selected": false,
"text": "<p>An easy solution might be to wrap the <code>int</code> into another type to create a distinct type for overload resolution. If you use a <code>struct</code>, this wrapper doesn't have any additional overhead:</p>\n\n<pre><code>struct Id {\n public int Value;\n\n public Id(int value) { Value = value; }\n\n override int GetHashCode() { return Value.GetHashCode(); }\n\n // … Equals method.\n}\n</code></pre>\n"
},
{
"answer_id": 202050,
"author": "Joe",
"author_id": 13087,
"author_profile": "https://Stackoverflow.com/users/13087",
"pm_score": 4,
"selected": true,
"text": "<p>Basically you need to decide if users of the class are likely to be confused by the fact that they can't, for example, do:</p>\n\n<pre><code>for(int i=0; i=< myCollection.Count; i++)\n{\n ... myCollection[i] ...\n}\n</code></pre>\n\n<p>though they can of course use foreach, or use a cast:</p>\n\n<pre><code>for(int i=0; i=< myCollection.Count; i++)\n{\n ... ((Collection<MyType>)myCollection)[i] ...\n}\n</code></pre>\n\n<p>It's not an easy decision, as it can easily lead to heisenbugs. I decided to allow it in one of my apps, where access from users of the class was almost exclusively by key. </p>\n\n<p>I'm not sure I'd do so for a shared class library though: in general I'd avoid exposing a KeyedCollection in a public API: instead I would expose IList<T> in a public API, and consumers of the API who need keyed access can define their own internal KeyedCollection with a constructor that takes an IEnumerable<TItem> and populates the collection with it. This means you can easily build a new KeyedCollection from a list retrieved from an API.</p>\n\n<p>Regarding serialization, there is also a performance problem <a href=\"http://connect.microsoft.com/VisualStudio/feedback/ViewFeedback.aspx?FeedbackID=302290\" rel=\"nofollow noreferrer\">that I reported to Microsoft Connect</a>: the KeyedCollection maintains an internal dictionary as well as a list, and serializes both - it is sufficient to serialize the list as the dictionary can easily be recreated on deserialization.</p>\n\n<p>For this reason as well as the XmlSerialization bug, I'd recommend you avoid serializing a KeyedCollection - instead only serialize the KeyedCollection.Items list.</p>\n\n<p>I don't like <a href=\"https://stackoverflow.com/questions/201956/is-it-ok-to-use-an-int-for-the-key-in-a-keyedcollection#201983\">the suggestion of wrapping your int key in another type</a>. It seems to me wrong to add complexity simply so that a type can be used as an item in a KeyedCollection. I'd use a string key (ToString) rather than doing this - this is rather like the VB6 Collection class.</p>\n\n<p>FWIW, I asked <a href=\"http://social.msdn.microsoft.com/Forums/en-US/vstscode/thread/d2163d71-636e-4521-926a-a7cce260143c/\" rel=\"nofollow noreferrer\">the same question</a> some time ago on the MSDN forums. There is a response from a member of the FxCop team, but no conclusive guidelines.</p>\n"
}
] |
2008/10/14
|
[
"https://Stackoverflow.com/questions/201956",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/27414/"
] |
Often times I need a collection of non-sequential objects with numeric identifiers. I like using the KeyedCollection for this, but I think there's a serious drawback. If you use an int for the key, you can no longer access members of the collection by their index (collection[index] is now really collection[key]). Is this a serious enough problem to avoid using the int as the key? What would a preferable alternative be? (maybe int.ToString()?)
I've done this before without any major problems, but recently I hit a nasty snag where XML serialization against a KeyedCollection does *not* work if the key is an int, due to [a bug in .NET](http://connect.microsoft.com/VisualStudio/feedback/ViewFeedback.aspx?FeedbackID=120461).
|
Basically you need to decide if users of the class are likely to be confused by the fact that they can't, for example, do:
```
for(int i=0; i=< myCollection.Count; i++)
{
... myCollection[i] ...
}
```
though they can of course use foreach, or use a cast:
```
for(int i=0; i=< myCollection.Count; i++)
{
... ((Collection<MyType>)myCollection)[i] ...
}
```
It's not an easy decision, as it can easily lead to heisenbugs. I decided to allow it in one of my apps, where access from users of the class was almost exclusively by key.
I'm not sure I'd do so for a shared class library though: in general I'd avoid exposing a KeyedCollection in a public API: instead I would expose IList<T> in a public API, and consumers of the API who need keyed access can define their own internal KeyedCollection with a constructor that takes an IEnumerable<TItem> and populates the collection with it. This means you can easily build a new KeyedCollection from a list retrieved from an API.
Regarding serialization, there is also a performance problem [that I reported to Microsoft Connect](http://connect.microsoft.com/VisualStudio/feedback/ViewFeedback.aspx?FeedbackID=302290): the KeyedCollection maintains an internal dictionary as well as a list, and serializes both - it is sufficient to serialize the list as the dictionary can easily be recreated on deserialization.
For this reason as well as the XmlSerialization bug, I'd recommend you avoid serializing a KeyedCollection - instead only serialize the KeyedCollection.Items list.
I don't like [the suggestion of wrapping your int key in another type](https://stackoverflow.com/questions/201956/is-it-ok-to-use-an-int-for-the-key-in-a-keyedcollection#201983). It seems to me wrong to add complexity simply so that a type can be used as an item in a KeyedCollection. I'd use a string key (ToString) rather than doing this - this is rather like the VB6 Collection class.
FWIW, I asked [the same question](http://social.msdn.microsoft.com/Forums/en-US/vstscode/thread/d2163d71-636e-4521-926a-a7cce260143c/) some time ago on the MSDN forums. There is a response from a member of the FxCop team, but no conclusive guidelines.
|
201,957 |
<p>I am attempting to create a Clipboard stack in C#. Clipboard data is stored in <code>System.Windows.Forms.DataObject</code> objects. I wanted to store each clipboard entry (<code>IDataObject</code>) directly in a Generic list. Due to the way Bitmaps (seem to be) stored I am thinking I need to perform a deep copy first before I add it to the list.</p>
<p>I attempted to use Binary serialization (see below) to create a deep copy but since <code>System.Windows.Forms.DataObject</code> is not marked as serializable the serialization step fails. Any ideas?</p>
<pre><code>public IDataObject GetClipboardData()
{
MemoryStream memoryStream = new MemoryStream();
BinaryFormatter binaryFormatter = new BinaryFormatter();
binaryFormatter.Serialize(memoryStream, Clipboard.GetDataObject());
memoryStream.Position = 0;
return (IDataObject) binaryFormatter.Deserialize(memoryStream);
}
</code></pre>
|
[
{
"answer_id": 202020,
"author": "cfeduke",
"author_id": 5645,
"author_profile": "https://Stackoverflow.com/users/5645",
"pm_score": 2,
"selected": false,
"text": "<p>I wrote the code below for another question and maybe it could come in useful for you in this scenario:</p>\n\n<pre><code> public static class GhettoSerializer\n {\n // you could make this a factory method if your type\n // has a constructor that appeals to you (i.e. default \n // parameterless constructor)\n public static void Initialize<T>(T instance, IDictionary<string, object> values)\n {\n var props = typeof(T).GetProperties();\n\n // my approach does nothing to handle rare properties with array indexers\n var matches = props.Join(\n values,\n pi => pi.Name,\n kvp => kvp.Key,\n (property, kvp) =>\n new {\n Set = new Action<object,object,object[]>(property.SetValue), \n kvp.Value\n }\n );\n\n foreach (var match in matches)\n match.Set(instance, match.Value, null);\n }\n public static IDictionary<string, object> Serialize<T>(T instance)\n {\n var props = typeof(T).GetProperties();\n\n var ret = new Dictionary<string, object>();\n\n foreach (var property in props)\n {\n if (!property.CanWrite || !property.CanRead)\n continue;\n ret.Add(property.Name, property.GetValue(instance, null));\n }\n\n return ret;\n }\n }\n</code></pre>\n\n<p>However I don't think this will be the final solution to your problem though it may give you a place to start.</p>\n"
},
{
"answer_id": 412308,
"author": "DrFloyd5",
"author_id": 1736623,
"author_profile": "https://Stackoverflow.com/users/1736623",
"pm_score": 0,
"selected": false,
"text": "<p>Look up the docks for Serializable and find the stuff about serialization helpers. You can wrap the bitmap in your own serialization code the integrates with the .net framework. </p>\n"
},
{
"answer_id": 19837014,
"author": "No answer",
"author_id": 2696426,
"author_profile": "https://Stackoverflow.com/users/2696426",
"pm_score": 0,
"selected": false,
"text": "<p>Copy of my answer to: <a href=\"https://stackoverflow.com/questions/4545439/difference-between-datacontract-attribute-and-serializable-attribute-in-net/19836842#19836842\">difference between DataContract attribute and Serializable attribute in .net</a></p>\n\n<p>My answer fits much better here than there, although above question ends with:</p>\n\n<blockquote>\n <p>\"... or maybe a different way of creating a deepclone?\"</p>\n</blockquote>\n\n<p>I once did some inspection to an object structure via Reflection to find all assemblies required for deserialization and serialize them alongside for bootstrapping.</p>\n\n<p>With a bit of work one could build a similar method for deep copying. Basically you need a recursive method that carrys along a Dictionary to detect circular references. Inside the method you inspect all fields about like this:</p>\n\n<pre><code>private void InspectRecursively(object input,\n Dictionary<object, bool> processedObjects)\n{\n if ((input != null) && !processedObjects.ContainsKey(input))\n {\n processedObjects.Add(input, true);\n\n List<FieldInfo> fields = type.GetFields(BindingFlags.Instance |\n BindingFlags.Public | BindingFlags.NonPublic );\n foreach (FieldInfo field in fields)\n {\n object nextInput = field.GetValue(input);\n\n if (nextInput is System.Collections.IEnumerable)\n {\n System.Collections.IEnumerator enumerator = (nextInput as\n System.Collections.IEnumerable).GetEnumerator();\n\n while (enumerator.MoveNext())\n {\n InspectRecursively(enumerator.Current, processedObjects);\n }\n }\n else\n {\n InspectRecursively(nextInput, processedObjects);\n }\n }\n }\n}\n</code></pre>\n\n<p>To get it working you need to add an output object and something like <code>System.Runtime.Serialization.FormatterServices.GetUninitializedObject(Type type)</code> to create the most shallowest copy (even without copying references) of each field's value. Finally you can set each field with something like <code>field.SetValue(input, output)</code></p>\n\n<p>However this implementation does not support registered event handlers, which is _<strong>un</strong>_supported by deserializing, too. Additionally each object in the hierarchy will be broken, if its class' constructor needs to initialize anything but setting all fields. The last point only work with serialization, if the class has a respective implementation, e.g. method marked <code>[OnDeserialized]</code>, implements <code>ISerializable</code>,... .</p>\n"
}
] |
2008/10/14
|
[
"https://Stackoverflow.com/questions/201957",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2690646/"
] |
I am attempting to create a Clipboard stack in C#. Clipboard data is stored in `System.Windows.Forms.DataObject` objects. I wanted to store each clipboard entry (`IDataObject`) directly in a Generic list. Due to the way Bitmaps (seem to be) stored I am thinking I need to perform a deep copy first before I add it to the list.
I attempted to use Binary serialization (see below) to create a deep copy but since `System.Windows.Forms.DataObject` is not marked as serializable the serialization step fails. Any ideas?
```
public IDataObject GetClipboardData()
{
MemoryStream memoryStream = new MemoryStream();
BinaryFormatter binaryFormatter = new BinaryFormatter();
binaryFormatter.Serialize(memoryStream, Clipboard.GetDataObject());
memoryStream.Position = 0;
return (IDataObject) binaryFormatter.Deserialize(memoryStream);
}
```
|
I wrote the code below for another question and maybe it could come in useful for you in this scenario:
```
public static class GhettoSerializer
{
// you could make this a factory method if your type
// has a constructor that appeals to you (i.e. default
// parameterless constructor)
public static void Initialize<T>(T instance, IDictionary<string, object> values)
{
var props = typeof(T).GetProperties();
// my approach does nothing to handle rare properties with array indexers
var matches = props.Join(
values,
pi => pi.Name,
kvp => kvp.Key,
(property, kvp) =>
new {
Set = new Action<object,object,object[]>(property.SetValue),
kvp.Value
}
);
foreach (var match in matches)
match.Set(instance, match.Value, null);
}
public static IDictionary<string, object> Serialize<T>(T instance)
{
var props = typeof(T).GetProperties();
var ret = new Dictionary<string, object>();
foreach (var property in props)
{
if (!property.CanWrite || !property.CanRead)
continue;
ret.Add(property.Name, property.GetValue(instance, null));
}
return ret;
}
}
```
However I don't think this will be the final solution to your problem though it may give you a place to start.
|
201,966 |
<p>I'm trying to create a QTVR movie via QTKit, and I've got all the frames in the movie. However, setting the attributes necessary doesn't seem to be having any effect. For example:</p>
<pre><code>NSNumber *val = [NSNumber numberWithBool:YES];
[fMovie setAttribute:val forKey:QTMovieIsInteractiveAttribute];
val = [NSNumber numberWithBool:NO];
[fMovie setAttribute:val forKey:QTMovieIsLinearAttribute];
</code></pre>
<p>If I then get the value of these attributes, they come up as NO and YES, respectively. The movie is editable, so I can't understand what I'm doing wrong here. How can I ensure that the attributes will actually change?</p>
|
[
{
"answer_id": 513584,
"author": "Daniel",
"author_id": 6852,
"author_profile": "https://Stackoverflow.com/users/6852",
"pm_score": 1,
"selected": false,
"text": "<p>What I do when I want to export a Quicktime movie is something like the following:</p>\n\n<pre><code>NSMutableDictionary *dictionary = [NSMutableDictionary dictionaryWithObjectsAndKeys:\n [NSNumber numberWithBool:YES], QTMovieExport,\n [exportSettings objectForKey: @\"subtype\"], QTMovieExportType,\n [exportSettings objectForKey: @\"manufacturer\"], QTMovieExportManufacturer,\n [exportSettings objectForKey: @\"settings\"], QTMovieExportSettings, \n nil];\n\nBOOL didSucceed = [movie writeToFile: tmpFileName withAttributes:dictionary error: &error];\n</code></pre>\n"
},
{
"answer_id": 2982426,
"author": "JWWalker",
"author_id": 309425,
"author_profile": "https://Stackoverflow.com/users/309425",
"pm_score": 0,
"selected": false,
"text": "<p>Those attributes are documented as things you can read but not write. However, you might be able to set them when you create the movie, with initWithAttributes:error:.</p>\n"
}
] |
2008/10/14
|
[
"https://Stackoverflow.com/questions/201966",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3830/"
] |
I'm trying to create a QTVR movie via QTKit, and I've got all the frames in the movie. However, setting the attributes necessary doesn't seem to be having any effect. For example:
```
NSNumber *val = [NSNumber numberWithBool:YES];
[fMovie setAttribute:val forKey:QTMovieIsInteractiveAttribute];
val = [NSNumber numberWithBool:NO];
[fMovie setAttribute:val forKey:QTMovieIsLinearAttribute];
```
If I then get the value of these attributes, they come up as NO and YES, respectively. The movie is editable, so I can't understand what I'm doing wrong here. How can I ensure that the attributes will actually change?
|
What I do when I want to export a Quicktime movie is something like the following:
```
NSMutableDictionary *dictionary = [NSMutableDictionary dictionaryWithObjectsAndKeys:
[NSNumber numberWithBool:YES], QTMovieExport,
[exportSettings objectForKey: @"subtype"], QTMovieExportType,
[exportSettings objectForKey: @"manufacturer"], QTMovieExportManufacturer,
[exportSettings objectForKey: @"settings"], QTMovieExportSettings,
nil];
BOOL didSucceed = [movie writeToFile: tmpFileName withAttributes:dictionary error: &error];
```
|
201,978 |
<p>I use Visual Studio to do a lot of my coding. I find the open containing folder feature quite helpful. But I don't want the folder to be "opened" by the windows explorer, instead I want to "explore" the folder -- you know, get the nice little frame showing me all the other folders on the left hand side. Does anyone know how to do this?</p>
<p>Thank you,
Rohit</p>
|
[
{
"answer_id": 513584,
"author": "Daniel",
"author_id": 6852,
"author_profile": "https://Stackoverflow.com/users/6852",
"pm_score": 1,
"selected": false,
"text": "<p>What I do when I want to export a Quicktime movie is something like the following:</p>\n\n<pre><code>NSMutableDictionary *dictionary = [NSMutableDictionary dictionaryWithObjectsAndKeys:\n [NSNumber numberWithBool:YES], QTMovieExport,\n [exportSettings objectForKey: @\"subtype\"], QTMovieExportType,\n [exportSettings objectForKey: @\"manufacturer\"], QTMovieExportManufacturer,\n [exportSettings objectForKey: @\"settings\"], QTMovieExportSettings, \n nil];\n\nBOOL didSucceed = [movie writeToFile: tmpFileName withAttributes:dictionary error: &error];\n</code></pre>\n"
},
{
"answer_id": 2982426,
"author": "JWWalker",
"author_id": 309425,
"author_profile": "https://Stackoverflow.com/users/309425",
"pm_score": 0,
"selected": false,
"text": "<p>Those attributes are documented as things you can read but not write. However, you might be able to set them when you create the movie, with initWithAttributes:error:.</p>\n"
}
] |
2008/10/14
|
[
"https://Stackoverflow.com/questions/201978",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/27928/"
] |
I use Visual Studio to do a lot of my coding. I find the open containing folder feature quite helpful. But I don't want the folder to be "opened" by the windows explorer, instead I want to "explore" the folder -- you know, get the nice little frame showing me all the other folders on the left hand side. Does anyone know how to do this?
Thank you,
Rohit
|
What I do when I want to export a Quicktime movie is something like the following:
```
NSMutableDictionary *dictionary = [NSMutableDictionary dictionaryWithObjectsAndKeys:
[NSNumber numberWithBool:YES], QTMovieExport,
[exportSettings objectForKey: @"subtype"], QTMovieExportType,
[exportSettings objectForKey: @"manufacturer"], QTMovieExportManufacturer,
[exportSettings objectForKey: @"settings"], QTMovieExportSettings,
nil];
BOOL didSucceed = [movie writeToFile: tmpFileName withAttributes:dictionary error: &error];
```
|
201,992 |
<p>I am coding a program that reads data directly from user input and was wondering how could I (without loops) read all data until EOF from standard input. I was considering using <code>cin.get( input, '\0' )</code> but <code>'\0'</code> is not really the EOF character, that just reads until EOF or <code>'\0'</code>, whichever comes first.</p>
<p>Or is using loops the only way to do it? If so, what is the best way?</p>
|
[
{
"answer_id": 202033,
"author": "luke",
"author_id": 16434,
"author_profile": "https://Stackoverflow.com/users/16434",
"pm_score": 2,
"selected": false,
"text": "<p>You can use the <a href=\"http://www.cplusplus.com/reference/iostream/istream/getline.html\" rel=\"nofollow noreferrer\">std::istream::getline()</a> (or preferably the <a href=\"http://www.cppreference.com/wiki/string/getline\" rel=\"nofollow noreferrer\">version that works on std::string</a>) function to get an entire line. Both have versions that allow you to specify the delimiter (end of line character). The default for the string version is '\\n'.</p>\n"
},
{
"answer_id": 202043,
"author": "trotterdylan",
"author_id": 17695,
"author_profile": "https://Stackoverflow.com/users/17695",
"pm_score": 7,
"selected": false,
"text": "<p>The only way you can read a variable amount of data from <code>stdin</code> is using loops. I've always found that the <a href=\"http://en.cppreference.com/w/cpp/string/basic_string/getline\" rel=\"noreferrer\"><code>std::getline()</code></a> function works very well:</p>\n\n<pre><code>std::string line;\nwhile (std::getline(std::cin, line))\n{\n std::cout << line << std::endl;\n}\n</code></pre>\n\n<p>By default <code>getline()</code> reads until a newline. You can specify an alternative termination character, but EOF is not itself a character so you cannot simply make one call to <code>getline()</code>.</p>\n"
},
{
"answer_id": 202097,
"author": "KeithB",
"author_id": 2298,
"author_profile": "https://Stackoverflow.com/users/2298",
"pm_score": 6,
"selected": false,
"text": "<p>You can do it without explicit loops by using stream iterators. I'm sure that it uses some kind of loop internally.</p>\n\n<pre><code>#include <string>\n#include <iostream>\n#include <istream>\n#include <ostream>\n#include <iterator>\n\nint main()\n{\n// don't skip the whitespace while reading\n std::cin >> std::noskipws;\n\n// use stream iterators to copy the stream to a string\n std::istream_iterator<char> it(std::cin);\n std::istream_iterator<char> end;\n std::string results(it, end);\n\n std::cout << results;\n}\n</code></pre>\n"
},
{
"answer_id": 202120,
"author": "Degvik",
"author_id": 26276,
"author_profile": "https://Stackoverflow.com/users/26276",
"pm_score": 6,
"selected": false,
"text": "<p>Using loops:</p>\n\n<pre><code>#include <iostream>\nusing namespace std;\n...\n// numbers\nint n;\nwhile (cin >> n)\n{\n ...\n}\n// lines\nstring line;\nwhile (getline(cin, line))\n{\n ...\n}\n// characters\nchar c;\nwhile (cin.get(c))\n{\n ...\n}\n</code></pre>\n\n<p><a href=\"http://acm.timus.ru/help.aspx?topic=cpp\" rel=\"noreferrer\">resource</a></p>\n"
},
{
"answer_id": 6132182,
"author": "Bryan",
"author_id": 770491,
"author_profile": "https://Stackoverflow.com/users/770491",
"pm_score": 0,
"selected": false,
"text": "<pre><code>while(std::cin) {\n // do something\n}\n</code></pre>\n"
},
{
"answer_id": 11793641,
"author": "liborm",
"author_id": 1496234,
"author_profile": "https://Stackoverflow.com/users/1496234",
"pm_score": 2,
"selected": false,
"text": "<p>Sad side note: I decided to use C++ IO to be consistent with boost based code. From answers to this question I chose <code>while (std::getline(std::cin, line))</code>. Using g++ version 4.5.3 (-O3) in cygwin (mintty) i got 2 MB/s throughput. Microsoft Visual C++ 2010 (/O2) made it 40 MB/s for the same code.</p>\n\n<p>After rewriting the IO to pure C <code>while (fgets(buf, 100, stdin))</code> the throughput jumped to 90 MB/s in both tested compilers. That makes a difference for any input bigger than 10 MB...</p>\n"
},
{
"answer_id": 11906161,
"author": "derpface",
"author_id": 1578197,
"author_profile": "https://Stackoverflow.com/users/1578197",
"pm_score": 0,
"selected": false,
"text": "<p>Wait, am I understanding you correctly? You're using cin for keyboard input, and you want to stop reading input when the user enters the EOF character? Why would the user ever type in the EOF character? Or did you mean you want to stop reading from a file at the EOF?</p>\n\n<p>If you're actually trying to use cin to read an EOF character, then why not just specify the EOF as the delimiter?</p>\n\n<pre><code>// Needed headers: iostream\n\nchar buffer[256];\ncin.get( buffer, '\\x1A' );\n</code></pre>\n\n<p>If you mean to stop reading from a file at the EOF, then just use getline and once again specify the EOF as the delimiter.</p>\n\n<pre><code>// Needed headers: iostream, string, and fstream\n\nstring buffer;\n\n ifstream fin;\n fin.open(\"test.txt\");\n if(fin.is_open()) {\n getline(fin,buffer,'\\x1A');\n\n fin.close();\n }\n</code></pre>\n"
},
{
"answer_id": 27557352,
"author": "0xbadf00d",
"author_id": 547231,
"author_profile": "https://Stackoverflow.com/users/547231",
"pm_score": 0,
"selected": false,
"text": "<p>One option is to a use a container, e.g.</p>\n\n<pre><code>std::vector<char> data;\n</code></pre>\n\n<p>and <em>redirect</em> all input into this collection until <code>EOF</code> is received, i.e.</p>\n\n<pre><code>std::copy(std::istream_iterator<char>(std::cin),\n std::istream_iterator<char>(),\n std::back_inserter(data));\n</code></pre>\n\n<p>However, the used container might need to reallocate memory too often, or you will end with a <code>std::bad_alloc</code> exception when your system gets out of memory. In order to solve these problems, you could <em>reserve</em> a fixed amount <code>N</code> of elements and process these amount of elements in isolation, i.e.</p>\n\n<pre><code>data.reserve(N); \nwhile (/*some condition is met*/)\n{\n std::copy_n(std::istream_iterator<char>(std::cin),\n N,\n std::back_inserter(data));\n\n /* process data */\n\n data.clear();\n}\n</code></pre>\n"
},
{
"answer_id": 30306694,
"author": "FrankHB",
"author_id": 2307646,
"author_profile": "https://Stackoverflow.com/users/2307646",
"pm_score": 3,
"selected": false,
"text": "<p>Probable simplest and generally efficient:</p>\n\n<pre><code>#include <iostream>\nint main()\n{\n std::cout << std::cin.rdbuf();\n}\n</code></pre>\n\n<p>If needed, use stream of other types like <code>std::ostringstream</code> as buffer instead of standard output stream here.</p>\n"
},
{
"answer_id": 36978839,
"author": "Richard Smith",
"author_id": 4862445,
"author_profile": "https://Stackoverflow.com/users/4862445",
"pm_score": 5,
"selected": false,
"text": "<p>After researching KeithB's solution using <code>std::istream_iterator</code>, I discovered the <a href=\"http://en.cppreference.com/w/cpp/iterator/istreambuf_iterator\" rel=\"noreferrer\"><code>std:istreambuf_iterator</code></a>.</p>\n\n<p>Test program to read all piped input into a string, then write it out again:</p>\n\n<pre><code>#include <iostream>\n#include <iterator>\n#include <string>\n\nint main()\n{\n std::istreambuf_iterator<char> begin(std::cin), end;\n std::string s(begin, end);\n std::cout << s;\n}\n</code></pre>\n"
}
] |
2008/10/14
|
[
"https://Stackoverflow.com/questions/201992",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/14759/"
] |
I am coding a program that reads data directly from user input and was wondering how could I (without loops) read all data until EOF from standard input. I was considering using `cin.get( input, '\0' )` but `'\0'` is not really the EOF character, that just reads until EOF or `'\0'`, whichever comes first.
Or is using loops the only way to do it? If so, what is the best way?
|
The only way you can read a variable amount of data from `stdin` is using loops. I've always found that the [`std::getline()`](http://en.cppreference.com/w/cpp/string/basic_string/getline) function works very well:
```
std::string line;
while (std::getline(std::cin, line))
{
std::cout << line << std::endl;
}
```
By default `getline()` reads until a newline. You can specify an alternative termination character, but EOF is not itself a character so you cannot simply make one call to `getline()`.
|
202,002 |
<p>I need to open a Microsoft Word 2003 file and change its file properties. Such as changing the Subject in the Summary Tab. <br/>
<img src="https://i.stack.imgur.com/FEpJY.gif" alt="alt text"></p>
|
[
{
"answer_id": 202010,
"author": "ine",
"author_id": 4965,
"author_profile": "https://Stackoverflow.com/users/4965",
"pm_score": 3,
"selected": false,
"text": "<p>I can think of 2 ways to do this:</p>\n\n<ul>\n<li>Use the Microsoft Office APIs. You\nwill have to reference them in your\nproject, and you will need the\n<a href=\"http://msdn.microsoft.com/en-us/library/aa163987.aspx\" rel=\"nofollow noreferrer\">Primary Interop Assemblies</a>.</li>\n<li>Convert the file to the Word 2003\nXML format and change that value in\nthe XML document. Here is the MSDN\ndocumentation on the document\nproperties:\n<a href=\"http://msdn.microsoft.com/en-us/library/aa223625(office.11).aspx\" rel=\"nofollow noreferrer\">http://msdn.microsoft.com/en-us/library/aa223625(office.11).aspx</a></li>\n</ul>\n\n<p>I would go with the second option if you can, because that way you don't have to depend on Word being installed on the system.</p>\n"
},
{
"answer_id": 202880,
"author": "AR.",
"author_id": 1354,
"author_profile": "https://Stackoverflow.com/users/1354",
"pm_score": 4,
"selected": true,
"text": "<p>Microsoft provides a very useful little assembly called DSOFile. With a reference to it in your project, you can modify Office document properties. It won't necessarily let you open the actual Office file's properties dialog, but you could certainly simulate it.</p>\n\n<p>According to Microsoft:</p>\n\n<blockquote>\n <p>The Dsofile.dll files lets you edit\n Office document properties when you do\n not have Office installed</p>\n</blockquote>\n\n<p>More details and a download link can be found at <a href=\"http://support.microsoft.com/kb/224351\" rel=\"noreferrer\">http://support.microsoft.com/kb/224351</a></p>\n\n<p>Here's a snippet some (very old) VB code I used ages ago. Sorry I haven't converted to C# and be aware that it's part of a class so there are references to instance variables. Still, it should be pretty easy to understand and covert to your own needs:</p>\n\n<pre><code>Private Sub ProcessOfficeDocument(ByVal fileName As String)\n Dim docDSO As New DSOFile.OleDocumentPropertiesClass\n Dim docTitle, docModified, docAuthor, docKeywords As String\n Try\n docDSO.Open(fileName, True)\n Dim docSummary As DSOFile.SummaryProperties = docDSO.SummaryProperties\n docTitle = docSummary.Title\n docAuthor = docSummary.Author\n docKeywords = docSummary.Keywords\n docModified = CStr(docSummary.DateLastSaved)\n\n If (Not String.IsNullOrEmpty(docTitle)) Then\n _Title = docTitle\n End If\n\n If (Not String.IsNullOrEmpty(docAuthor)) Then\n _Author = docAuthor\n End If\n\n If (Not String.IsNullOrEmpty(docModified)) Then\n _DateModified = DateTime.Parse(docModified)\n End If\n\n Catch ex As Exception\n 'Do whatever you need to do here...'\n Finally\n If (Not docDSO Is Nothing) Then\n docDSO.Close()\n End If\n End Try\nEnd Sub\n</code></pre>\n"
}
] |
2008/10/14
|
[
"https://Stackoverflow.com/questions/202002",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5653/"
] |
I need to open a Microsoft Word 2003 file and change its file properties. Such as changing the Subject in the Summary Tab.

|
Microsoft provides a very useful little assembly called DSOFile. With a reference to it in your project, you can modify Office document properties. It won't necessarily let you open the actual Office file's properties dialog, but you could certainly simulate it.
According to Microsoft:
>
> The Dsofile.dll files lets you edit
> Office document properties when you do
> not have Office installed
>
>
>
More details and a download link can be found at <http://support.microsoft.com/kb/224351>
Here's a snippet some (very old) VB code I used ages ago. Sorry I haven't converted to C# and be aware that it's part of a class so there are references to instance variables. Still, it should be pretty easy to understand and covert to your own needs:
```
Private Sub ProcessOfficeDocument(ByVal fileName As String)
Dim docDSO As New DSOFile.OleDocumentPropertiesClass
Dim docTitle, docModified, docAuthor, docKeywords As String
Try
docDSO.Open(fileName, True)
Dim docSummary As DSOFile.SummaryProperties = docDSO.SummaryProperties
docTitle = docSummary.Title
docAuthor = docSummary.Author
docKeywords = docSummary.Keywords
docModified = CStr(docSummary.DateLastSaved)
If (Not String.IsNullOrEmpty(docTitle)) Then
_Title = docTitle
End If
If (Not String.IsNullOrEmpty(docAuthor)) Then
_Author = docAuthor
End If
If (Not String.IsNullOrEmpty(docModified)) Then
_DateModified = DateTime.Parse(docModified)
End If
Catch ex As Exception
'Do whatever you need to do here...'
Finally
If (Not docDSO Is Nothing) Then
docDSO.Close()
End If
End Try
End Sub
```
|
202,011 |
<p>How can I encrypt and decrypt a string in C#?</p>
|
[
{
"answer_id": 202075,
"author": "Tamas Czinege",
"author_id": 8954,
"author_profile": "https://Stackoverflow.com/users/8954",
"pm_score": 7,
"selected": false,
"text": "<p>Here is an example using RSA. </p>\n\n<p><strong>Important:</strong> There is a limit to the size of data you can encrypt with the RSA encryption, <code>KeySize - MinimumPadding</code>. <em>e.g. 256 bytes (assuming 2048 bit key) - 42 bytes (min OEAP padding) = 214 bytes (max plaintext size)</em></p>\n\n<p>Replace your_rsa_key with your RSA key.</p>\n\n<pre><code>var provider = new System.Security.Cryptography.RSACryptoServiceProvider();\nprovider.ImportParameters(your_rsa_key);\n\nvar encryptedBytes = provider.Encrypt(\n System.Text.Encoding.UTF8.GetBytes(\"Hello World!\"), true);\n\nstring decryptedTest = System.Text.Encoding.UTF8.GetString(\n provider.Decrypt(encryptedBytes, true));\n</code></pre>\n\n<p>For more info, visit <a href=\"http://msdn.microsoft.com/en-us/library/system.security.cryptography.rsacryptoserviceprovider.aspx\" rel=\"noreferrer\">MSDN - RSACryptoServiceProvider </a></p>\n"
},
{
"answer_id": 2791259,
"author": "Brett",
"author_id": 188474,
"author_profile": "https://Stackoverflow.com/users/188474",
"pm_score": 9,
"selected": false,
"text": "<p><strong>EDIT 2013-Oct</strong>: Although I've edited this answer over time to address shortcomings, please see <a href=\"https://stackoverflow.com/a/10366194/157247\">jbtule's answer</a> for a more robust, informed solution.</p>\n\n<p><a href=\"https://stackoverflow.com/a/10366194/188474\">https://stackoverflow.com/a/10366194/188474</a></p>\n\n<p><strong>Original Answer:</strong></p>\n\n<p>Here's a working example derived from the <a href=\"http://msdn.microsoft.com/en-us/library/system.security.cryptography.rijndaelmanaged%28v=VS.90%29.aspx\" rel=\"noreferrer\">\"RijndaelManaged Class\" documentation</a> and the <a href=\"https://rads.stackoverflow.com/amzn/click/com/0735626197\" rel=\"noreferrer\" rel=\"nofollow noreferrer\">MCTS Training Kit</a>. </p>\n\n<p><strong>EDIT 2012-April</strong>: This answer was edited to pre-pend the IV per jbtule's suggestion and as illustrated here:</p>\n\n<p><a href=\"http://msdn.microsoft.com/en-us/library/system.security.cryptography.aesmanaged%28v=vs.95%29.aspx\" rel=\"noreferrer\">http://msdn.microsoft.com/en-us/library/system.security.cryptography.aesmanaged%28v=vs.95%29.aspx</a></p>\n\n<p>Good luck!</p>\n\n<pre><code>public class Crypto\n{\n\n //While an app specific salt is not the best practice for\n //password based encryption, it's probably safe enough as long as\n //it is truly uncommon. Also too much work to alter this answer otherwise.\n private static byte[] _salt = __To_Do__(\"Add a app specific salt here\");\n\n /// <summary>\n /// Encrypt the given string using AES. The string can be decrypted using \n /// DecryptStringAES(). The sharedSecret parameters must match.\n /// </summary>\n /// <param name=\"plainText\">The text to encrypt.</param>\n /// <param name=\"sharedSecret\">A password used to generate a key for encryption.</param>\n public static string EncryptStringAES(string plainText, string sharedSecret)\n {\n if (string.IsNullOrEmpty(plainText))\n throw new ArgumentNullException(\"plainText\");\n if (string.IsNullOrEmpty(sharedSecret))\n throw new ArgumentNullException(\"sharedSecret\");\n\n string outStr = null; // Encrypted string to return\n RijndaelManaged aesAlg = null; // RijndaelManaged object used to encrypt the data.\n\n try\n {\n // generate the key from the shared secret and the salt\n Rfc2898DeriveBytes key = new Rfc2898DeriveBytes(sharedSecret, _salt);\n\n // Create a RijndaelManaged object\n aesAlg = new RijndaelManaged();\n aesAlg.Key = key.GetBytes(aesAlg.KeySize / 8);\n\n // Create a decryptor to perform the stream transform.\n ICryptoTransform encryptor = aesAlg.CreateEncryptor(aesAlg.Key, aesAlg.IV);\n\n // Create the streams used for encryption.\n using (MemoryStream msEncrypt = new MemoryStream())\n {\n // prepend the IV\n msEncrypt.Write(BitConverter.GetBytes(aesAlg.IV.Length), 0, sizeof(int));\n msEncrypt.Write(aesAlg.IV, 0, aesAlg.IV.Length);\n using (CryptoStream csEncrypt = new CryptoStream(msEncrypt, encryptor, CryptoStreamMode.Write))\n {\n using (StreamWriter swEncrypt = new StreamWriter(csEncrypt))\n {\n //Write all data to the stream.\n swEncrypt.Write(plainText);\n }\n }\n outStr = Convert.ToBase64String(msEncrypt.ToArray());\n }\n }\n finally\n {\n // Clear the RijndaelManaged object.\n if (aesAlg != null)\n aesAlg.Clear();\n }\n\n // Return the encrypted bytes from the memory stream.\n return outStr;\n }\n\n /// <summary>\n /// Decrypt the given string. Assumes the string was encrypted using \n /// EncryptStringAES(), using an identical sharedSecret.\n /// </summary>\n /// <param name=\"cipherText\">The text to decrypt.</param>\n /// <param name=\"sharedSecret\">A password used to generate a key for decryption.</param>\n public static string DecryptStringAES(string cipherText, string sharedSecret)\n {\n if (string.IsNullOrEmpty(cipherText))\n throw new ArgumentNullException(\"cipherText\");\n if (string.IsNullOrEmpty(sharedSecret))\n throw new ArgumentNullException(\"sharedSecret\");\n\n // Declare the RijndaelManaged object\n // used to decrypt the data.\n RijndaelManaged aesAlg = null;\n\n // Declare the string used to hold\n // the decrypted text.\n string plaintext = null;\n\n try\n {\n // generate the key from the shared secret and the salt\n Rfc2898DeriveBytes key = new Rfc2898DeriveBytes(sharedSecret, _salt);\n\n // Create the streams used for decryption. \n byte[] bytes = Convert.FromBase64String(cipherText);\n using (MemoryStream msDecrypt = new MemoryStream(bytes))\n {\n // Create a RijndaelManaged object\n // with the specified key and IV.\n aesAlg = new RijndaelManaged();\n aesAlg.Key = key.GetBytes(aesAlg.KeySize / 8);\n // Get the initialization vector from the encrypted stream\n aesAlg.IV = ReadByteArray(msDecrypt);\n // Create a decrytor to perform the stream transform.\n ICryptoTransform decryptor = aesAlg.CreateDecryptor(aesAlg.Key, aesAlg.IV);\n using (CryptoStream csDecrypt = new CryptoStream(msDecrypt, decryptor, CryptoStreamMode.Read))\n {\n using (StreamReader srDecrypt = new StreamReader(csDecrypt))\n\n // Read the decrypted bytes from the decrypting stream\n // and place them in a string.\n plaintext = srDecrypt.ReadToEnd();\n }\n }\n }\n finally\n {\n // Clear the RijndaelManaged object.\n if (aesAlg != null)\n aesAlg.Clear();\n }\n\n return plaintext;\n }\n\n private static byte[] ReadByteArray(Stream s)\n {\n byte[] rawLength = new byte[sizeof(int)];\n if (s.Read(rawLength, 0, rawLength.Length) != rawLength.Length)\n {\n throw new SystemException(\"Stream did not contain properly formatted byte array\");\n }\n\n byte[] buffer = new byte[BitConverter.ToInt32(rawLength, 0)];\n if (s.Read(buffer, 0, buffer.Length) != buffer.Length)\n {\n throw new SystemException(\"Did not read byte array properly\");\n }\n\n return buffer;\n }\n}\n</code></pre>\n"
},
{
"answer_id": 5509947,
"author": "BPL",
"author_id": 666157,
"author_profile": "https://Stackoverflow.com/users/666157",
"pm_score": -1,
"selected": false,
"text": "<pre><code>using System;\nusing System.Data;\nusing System.Configuration;\nusing System.Text;\nusing System.Security.Cryptography;\n\nnamespace Encription\n{\n class CryptorEngine\n {\n public static string Encrypt(string ToEncrypt, bool useHasing)\n {\n byte[] keyArray;\n byte[] toEncryptArray = UTF8Encoding.UTF8.GetBytes(ToEncrypt);\n //System.Configuration.AppSettingsReader settingsReader = new AppSettingsReader();\n string Key = \"Bhagwati\";\n if (useHasing)\n {\n MD5CryptoServiceProvider hashmd5 = new MD5CryptoServiceProvider();\n keyArray = hashmd5.ComputeHash(UTF8Encoding.UTF8.GetBytes(Key));\n hashmd5.Clear(); \n }\n else\n {\n keyArray = UTF8Encoding.UTF8.GetBytes(Key);\n }\n TripleDESCryptoServiceProvider tDes = new TripleDESCryptoServiceProvider();\n tDes.Key = keyArray;\n tDes.Mode = CipherMode.ECB;\n tDes.Padding = PaddingMode.PKCS7;\n ICryptoTransform cTransform = tDes.CreateEncryptor();\n byte[] resultArray = cTransform.TransformFinalBlock(toEncryptArray, 0, toEncryptArray.Length);\n tDes.Clear();\n return Convert.ToBase64String(resultArray, 0, resultArray.Length);\n }\n public static string Decrypt(string cypherString, bool useHasing)\n {\n byte[] keyArray;\n byte[] toDecryptArray = Convert.FromBase64String(cypherString);\n //byte[] toEncryptArray = Convert.FromBase64String(cypherString);\n //System.Configuration.AppSettingsReader settingReader = new AppSettingsReader();\n string key = \"Bhagwati\";\n if (useHasing)\n {\n MD5CryptoServiceProvider hashmd = new MD5CryptoServiceProvider();\n keyArray = hashmd.ComputeHash(UTF8Encoding.UTF8.GetBytes(key));\n hashmd.Clear();\n }\n else\n {\n keyArray = UTF8Encoding.UTF8.GetBytes(key);\n }\n TripleDESCryptoServiceProvider tDes = new TripleDESCryptoServiceProvider();\n tDes.Key = keyArray;\n tDes.Mode = CipherMode.ECB;\n tDes.Padding = PaddingMode.PKCS7;\n ICryptoTransform cTransform = tDes.CreateDecryptor();\n try\n {\n byte[] resultArray = cTransform.TransformFinalBlock(toDecryptArray, 0, toDecryptArray.Length);\n\n tDes.Clear();\n return UTF8Encoding.UTF8.GetString(resultArray,0,resultArray.Length);\n }\n catch (Exception ex)\n {\n throw ex;\n }\n }\n }\n}\n</code></pre>\n"
},
{
"answer_id": 10366194,
"author": "jbtule",
"author_id": 637783,
"author_profile": "https://Stackoverflow.com/users/637783",
"pm_score": 9,
"selected": false,
"text": "<p><strong>Modern Examples of Symmetric Authenticated Encryption of a string.</strong> </p>\n\n<p>The general best practice for symmetric encryption is to use Authenticated Encryption with Associated Data (AEAD), however this isn't a part of the standard .net crypto libraries. So the first example uses <a href=\"http://en.wikipedia.org/wiki/Advanced_Encryption_Standard\" rel=\"noreferrer\">AES256</a> and then <a href=\"http://en.wikipedia.org/wiki/HMAC\" rel=\"noreferrer\">HMAC256</a>, a two step <a href=\"https://crypto.stackexchange.com/a/205/1934\">Encrypt then MAC</a>, which requires more overhead and more keys.</p>\n\n<p>The second example uses the simpler practice of AES256-<a href=\"http://en.wikipedia.org/wiki/Galois/Counter_Mode\" rel=\"noreferrer\">GCM</a> using the open source Bouncy Castle (via nuget).</p>\n\n<p>Both examples have a main function that takes secret message string, key(s) and an optional non-secret payload and return and authenticated encrypted string optionally prepended with the non-secret data. Ideally you would use these with 256bit key(s) randomly generated see <code>NewKey()</code>.</p>\n\n<p>Both examples also have a helper methods that use a string password to generate the keys. These helper methods are provided as a convenience to match up with other examples, however they are <em>far less secure</em> because the strength of the password is going to be <em>far weaker than a 256 bit key</em>.</p>\n\n<p><strong>Update:</strong>\nAdded <code>byte[]</code> overloads, and only the <a href=\"https://gist.github.com/4336842\" rel=\"noreferrer\">Gist</a> has the full formatting with 4 spaces indent and api docs due to StackOverflow answer limits.</p>\n\n<hr>\n\n<p><strong>.NET Built-in Encrypt(AES)-Then-MAC(HMAC) <a href=\"https://gist.github.com/jbtule/4336842#file-aesthenhmac-cs\" rel=\"noreferrer\">[Gist]</a></strong></p>\n\n<pre><code>/*\n * This work (Modern Encryption of a String C#, by James Tuley), \n * identified by James Tuley, is free of known copyright restrictions.\n * https://gist.github.com/4336842\n * http://creativecommons.org/publicdomain/mark/1.0/ \n */\n\nusing System;\nusing System.IO;\nusing System.Security.Cryptography;\nusing System.Text;\n\nnamespace Encryption\n{\n public static class AESThenHMAC\n {\n private static readonly RandomNumberGenerator Random = RandomNumberGenerator.Create();\n\n //Preconfigured Encryption Parameters\n public static readonly int BlockBitSize = 128;\n public static readonly int KeyBitSize = 256;\n\n //Preconfigured Password Key Derivation Parameters\n public static readonly int SaltBitSize = 64;\n public static readonly int Iterations = 10000;\n public static readonly int MinPasswordLength = 12;\n\n /// <summary>\n /// Helper that generates a random key on each call.\n /// </summary>\n /// <returns></returns>\n public static byte[] NewKey()\n {\n var key = new byte[KeyBitSize / 8];\n Random.GetBytes(key);\n return key;\n }\n\n /// <summary>\n /// Simple Encryption (AES) then Authentication (HMAC) for a UTF8 Message.\n /// </summary>\n /// <param name=\"secretMessage\">The secret message.</param>\n /// <param name=\"cryptKey\">The crypt key.</param>\n /// <param name=\"authKey\">The auth key.</param>\n /// <param name=\"nonSecretPayload\">(Optional) Non-Secret Payload.</param>\n /// <returns>\n /// Encrypted Message\n /// </returns>\n /// <exception cref=\"System.ArgumentException\">Secret Message Required!;secretMessage</exception>\n /// <remarks>\n /// Adds overhead of (Optional-Payload + BlockSize(16) + Message-Padded-To-Blocksize + HMac-Tag(32)) * 1.33 Base64\n /// </remarks>\n public static string SimpleEncrypt(string secretMessage, byte[] cryptKey, byte[] authKey,\n byte[] nonSecretPayload = null)\n {\n if (string.IsNullOrEmpty(secretMessage))\n throw new ArgumentException(\"Secret Message Required!\", \"secretMessage\");\n\n var plainText = Encoding.UTF8.GetBytes(secretMessage);\n var cipherText = SimpleEncrypt(plainText, cryptKey, authKey, nonSecretPayload);\n return Convert.ToBase64String(cipherText);\n }\n\n /// <summary>\n /// Simple Authentication (HMAC) then Decryption (AES) for a secrets UTF8 Message.\n /// </summary>\n /// <param name=\"encryptedMessage\">The encrypted message.</param>\n /// <param name=\"cryptKey\">The crypt key.</param>\n /// <param name=\"authKey\">The auth key.</param>\n /// <param name=\"nonSecretPayloadLength\">Length of the non secret payload.</param>\n /// <returns>\n /// Decrypted Message\n /// </returns>\n /// <exception cref=\"System.ArgumentException\">Encrypted Message Required!;encryptedMessage</exception>\n public static string SimpleDecrypt(string encryptedMessage, byte[] cryptKey, byte[] authKey,\n int nonSecretPayloadLength = 0)\n {\n if (string.IsNullOrWhiteSpace(encryptedMessage))\n throw new ArgumentException(\"Encrypted Message Required!\", \"encryptedMessage\");\n\n var cipherText = Convert.FromBase64String(encryptedMessage);\n var plainText = SimpleDecrypt(cipherText, cryptKey, authKey, nonSecretPayloadLength);\n return plainText == null ? null : Encoding.UTF8.GetString(plainText);\n }\n\n /// <summary>\n /// Simple Encryption (AES) then Authentication (HMAC) of a UTF8 message\n /// using Keys derived from a Password (PBKDF2).\n /// </summary>\n /// <param name=\"secretMessage\">The secret message.</param>\n /// <param name=\"password\">The password.</param>\n /// <param name=\"nonSecretPayload\">The non secret payload.</param>\n /// <returns>\n /// Encrypted Message\n /// </returns>\n /// <exception cref=\"System.ArgumentException\">password</exception>\n /// <remarks>\n /// Significantly less secure than using random binary keys.\n /// Adds additional non secret payload for key generation parameters.\n /// </remarks>\n public static string SimpleEncryptWithPassword(string secretMessage, string password,\n byte[] nonSecretPayload = null)\n {\n if (string.IsNullOrEmpty(secretMessage))\n throw new ArgumentException(\"Secret Message Required!\", \"secretMessage\");\n\n var plainText = Encoding.UTF8.GetBytes(secretMessage);\n var cipherText = SimpleEncryptWithPassword(plainText, password, nonSecretPayload);\n return Convert.ToBase64String(cipherText);\n }\n\n /// <summary>\n /// Simple Authentication (HMAC) and then Descryption (AES) of a UTF8 Message\n /// using keys derived from a password (PBKDF2). \n /// </summary>\n /// <param name=\"encryptedMessage\">The encrypted message.</param>\n /// <param name=\"password\">The password.</param>\n /// <param name=\"nonSecretPayloadLength\">Length of the non secret payload.</param>\n /// <returns>\n /// Decrypted Message\n /// </returns>\n /// <exception cref=\"System.ArgumentException\">Encrypted Message Required!;encryptedMessage</exception>\n /// <remarks>\n /// Significantly less secure than using random binary keys.\n /// </remarks>\n public static string SimpleDecryptWithPassword(string encryptedMessage, string password,\n int nonSecretPayloadLength = 0)\n {\n if (string.IsNullOrWhiteSpace(encryptedMessage))\n throw new ArgumentException(\"Encrypted Message Required!\", \"encryptedMessage\");\n\n var cipherText = Convert.FromBase64String(encryptedMessage);\n var plainText = SimpleDecryptWithPassword(cipherText, password, nonSecretPayloadLength);\n return plainText == null ? null : Encoding.UTF8.GetString(plainText);\n }\n\n public static byte[] SimpleEncrypt(byte[] secretMessage, byte[] cryptKey, byte[] authKey, byte[] nonSecretPayload = null)\n {\n //User Error Checks\n if (cryptKey == null || cryptKey.Length != KeyBitSize / 8)\n throw new ArgumentException(String.Format(\"Key needs to be {0} bit!\", KeyBitSize), \"cryptKey\");\n\n if (authKey == null || authKey.Length != KeyBitSize / 8)\n throw new ArgumentException(String.Format(\"Key needs to be {0} bit!\", KeyBitSize), \"authKey\");\n\n if (secretMessage == null || secretMessage.Length < 1)\n throw new ArgumentException(\"Secret Message Required!\", \"secretMessage\");\n\n //non-secret payload optional\n nonSecretPayload = nonSecretPayload ?? new byte[] { };\n\n byte[] cipherText;\n byte[] iv;\n\n using (var aes = new AesManaged\n {\n KeySize = KeyBitSize,\n BlockSize = BlockBitSize,\n Mode = CipherMode.CBC,\n Padding = PaddingMode.PKCS7\n })\n {\n\n //Use random IV\n aes.GenerateIV();\n iv = aes.IV;\n\n using (var encrypter = aes.CreateEncryptor(cryptKey, iv))\n using (var cipherStream = new MemoryStream())\n {\n using (var cryptoStream = new CryptoStream(cipherStream, encrypter, CryptoStreamMode.Write))\n using (var binaryWriter = new BinaryWriter(cryptoStream))\n {\n //Encrypt Data\n binaryWriter.Write(secretMessage);\n }\n\n cipherText = cipherStream.ToArray();\n }\n\n }\n\n //Assemble encrypted message and add authentication\n using (var hmac = new HMACSHA256(authKey))\n using (var encryptedStream = new MemoryStream())\n {\n using (var binaryWriter = new BinaryWriter(encryptedStream))\n {\n //Prepend non-secret payload if any\n binaryWriter.Write(nonSecretPayload);\n //Prepend IV\n binaryWriter.Write(iv);\n //Write Ciphertext\n binaryWriter.Write(cipherText);\n binaryWriter.Flush();\n\n //Authenticate all data\n var tag = hmac.ComputeHash(encryptedStream.ToArray());\n //Postpend tag\n binaryWriter.Write(tag);\n }\n return encryptedStream.ToArray();\n }\n\n }\n\n public static byte[] SimpleDecrypt(byte[] encryptedMessage, byte[] cryptKey, byte[] authKey, int nonSecretPayloadLength = 0)\n {\n\n //Basic Usage Error Checks\n if (cryptKey == null || cryptKey.Length != KeyBitSize / 8)\n throw new ArgumentException(String.Format(\"CryptKey needs to be {0} bit!\", KeyBitSize), \"cryptKey\");\n\n if (authKey == null || authKey.Length != KeyBitSize / 8)\n throw new ArgumentException(String.Format(\"AuthKey needs to be {0} bit!\", KeyBitSize), \"authKey\");\n\n if (encryptedMessage == null || encryptedMessage.Length == 0)\n throw new ArgumentException(\"Encrypted Message Required!\", \"encryptedMessage\");\n\n using (var hmac = new HMACSHA256(authKey))\n {\n var sentTag = new byte[hmac.HashSize / 8];\n //Calculate Tag\n var calcTag = hmac.ComputeHash(encryptedMessage, 0, encryptedMessage.Length - sentTag.Length);\n var ivLength = (BlockBitSize / 8);\n\n //if message length is to small just return null\n if (encryptedMessage.Length < sentTag.Length + nonSecretPayloadLength + ivLength)\n return null;\n\n //Grab Sent Tag\n Array.Copy(encryptedMessage, encryptedMessage.Length - sentTag.Length, sentTag, 0, sentTag.Length);\n\n //Compare Tag with constant time comparison\n var compare = 0;\n for (var i = 0; i < sentTag.Length; i++)\n compare |= sentTag[i] ^ calcTag[i]; \n\n //if message doesn't authenticate return null\n if (compare != 0)\n return null;\n\n using (var aes = new AesManaged\n {\n KeySize = KeyBitSize,\n BlockSize = BlockBitSize,\n Mode = CipherMode.CBC,\n Padding = PaddingMode.PKCS7\n })\n {\n\n //Grab IV from message\n var iv = new byte[ivLength];\n Array.Copy(encryptedMessage, nonSecretPayloadLength, iv, 0, iv.Length);\n\n using (var decrypter = aes.CreateDecryptor(cryptKey, iv))\n using (var plainTextStream = new MemoryStream())\n {\n using (var decrypterStream = new CryptoStream(plainTextStream, decrypter, CryptoStreamMode.Write))\n using (var binaryWriter = new BinaryWriter(decrypterStream))\n {\n //Decrypt Cipher Text from Message\n binaryWriter.Write(\n encryptedMessage,\n nonSecretPayloadLength + iv.Length,\n encryptedMessage.Length - nonSecretPayloadLength - iv.Length - sentTag.Length\n );\n }\n //Return Plain Text\n return plainTextStream.ToArray();\n }\n }\n }\n }\n\n public static byte[] SimpleEncryptWithPassword(byte[] secretMessage, string password, byte[] nonSecretPayload = null)\n {\n nonSecretPayload = nonSecretPayload ?? new byte[] {};\n\n //User Error Checks\n if (string.IsNullOrWhiteSpace(password) || password.Length < MinPasswordLength)\n throw new ArgumentException(String.Format(\"Must have a password of at least {0} characters!\", MinPasswordLength), \"password\");\n\n if (secretMessage == null || secretMessage.Length ==0)\n throw new ArgumentException(\"Secret Message Required!\", \"secretMessage\");\n\n var payload = new byte[((SaltBitSize / 8) * 2) + nonSecretPayload.Length];\n\n Array.Copy(nonSecretPayload, payload, nonSecretPayload.Length);\n int payloadIndex = nonSecretPayload.Length;\n\n byte[] cryptKey;\n byte[] authKey;\n //Use Random Salt to prevent pre-generated weak password attacks.\n using (var generator = new Rfc2898DeriveBytes(password, SaltBitSize / 8, Iterations))\n {\n var salt = generator.Salt;\n\n //Generate Keys\n cryptKey = generator.GetBytes(KeyBitSize / 8);\n\n //Create Non Secret Payload\n Array.Copy(salt, 0, payload, payloadIndex, salt.Length);\n payloadIndex += salt.Length;\n }\n\n //Deriving separate key, might be less efficient than using HKDF, \n //but now compatible with RNEncryptor which had a very similar wireformat and requires less code than HKDF.\n using (var generator = new Rfc2898DeriveBytes(password, SaltBitSize / 8, Iterations))\n {\n var salt = generator.Salt;\n\n //Generate Keys\n authKey = generator.GetBytes(KeyBitSize / 8);\n\n //Create Rest of Non Secret Payload\n Array.Copy(salt, 0, payload, payloadIndex, salt.Length);\n }\n\n return SimpleEncrypt(secretMessage, cryptKey, authKey, payload);\n }\n\n public static byte[] SimpleDecryptWithPassword(byte[] encryptedMessage, string password, int nonSecretPayloadLength = 0)\n {\n //User Error Checks\n if (string.IsNullOrWhiteSpace(password) || password.Length < MinPasswordLength)\n throw new ArgumentException(String.Format(\"Must have a password of at least {0} characters!\", MinPasswordLength), \"password\");\n\n if (encryptedMessage == null || encryptedMessage.Length == 0)\n throw new ArgumentException(\"Encrypted Message Required!\", \"encryptedMessage\");\n\n var cryptSalt = new byte[SaltBitSize / 8];\n var authSalt = new byte[SaltBitSize / 8];\n\n //Grab Salt from Non-Secret Payload\n Array.Copy(encryptedMessage, nonSecretPayloadLength, cryptSalt, 0, cryptSalt.Length);\n Array.Copy(encryptedMessage, nonSecretPayloadLength + cryptSalt.Length, authSalt, 0, authSalt.Length);\n\n byte[] cryptKey;\n byte[] authKey;\n\n //Generate crypt key\n using (var generator = new Rfc2898DeriveBytes(password, cryptSalt, Iterations))\n {\n cryptKey = generator.GetBytes(KeyBitSize / 8);\n }\n //Generate auth key\n using (var generator = new Rfc2898DeriveBytes(password, authSalt, Iterations))\n {\n authKey = generator.GetBytes(KeyBitSize / 8);\n }\n\n return SimpleDecrypt(encryptedMessage, cryptKey, authKey, cryptSalt.Length + authSalt.Length + nonSecretPayloadLength);\n }\n }\n}\n</code></pre>\n\n<hr>\n\n<p><strong>Bouncy Castle AES-GCM <a href=\"https://gist.github.com/jbtule/4336842#file-aesgcm-cs\" rel=\"noreferrer\">[Gist]</a></strong></p>\n\n<pre><code>/*\n * This work (Modern Encryption of a String C#, by James Tuley), \n * identified by James Tuley, is free of known copyright restrictions.\n * https://gist.github.com/4336842\n * http://creativecommons.org/publicdomain/mark/1.0/ \n */\n\nusing System;\nusing System.IO;\nusing System.Text;\nusing Org.BouncyCastle.Crypto;\nusing Org.BouncyCastle.Crypto.Engines;\nusing Org.BouncyCastle.Crypto.Generators;\nusing Org.BouncyCastle.Crypto.Modes;\nusing Org.BouncyCastle.Crypto.Parameters;\nusing Org.BouncyCastle.Security;\nnamespace Encryption\n{\n\n public static class AESGCM\n {\n private static readonly SecureRandom Random = new SecureRandom();\n\n //Preconfigured Encryption Parameters\n public static readonly int NonceBitSize = 128;\n public static readonly int MacBitSize = 128;\n public static readonly int KeyBitSize = 256;\n\n //Preconfigured Password Key Derivation Parameters\n public static readonly int SaltBitSize = 128;\n public static readonly int Iterations = 10000;\n public static readonly int MinPasswordLength = 12;\n\n\n /// <summary>\n /// Helper that generates a random new key on each call.\n /// </summary>\n /// <returns></returns>\n public static byte[] NewKey()\n {\n var key = new byte[KeyBitSize / 8];\n Random.NextBytes(key);\n return key;\n }\n\n /// <summary>\n /// Simple Encryption And Authentication (AES-GCM) of a UTF8 string.\n /// </summary>\n /// <param name=\"secretMessage\">The secret message.</param>\n /// <param name=\"key\">The key.</param>\n /// <param name=\"nonSecretPayload\">Optional non-secret payload.</param>\n /// <returns>\n /// Encrypted Message\n /// </returns>\n /// <exception cref=\"System.ArgumentException\">Secret Message Required!;secretMessage</exception>\n /// <remarks>\n /// Adds overhead of (Optional-Payload + BlockSize(16) + Message + HMac-Tag(16)) * 1.33 Base64\n /// </remarks>\n public static string SimpleEncrypt(string secretMessage, byte[] key, byte[] nonSecretPayload = null)\n {\n if (string.IsNullOrEmpty(secretMessage))\n throw new ArgumentException(\"Secret Message Required!\", \"secretMessage\");\n\n var plainText = Encoding.UTF8.GetBytes(secretMessage);\n var cipherText = SimpleEncrypt(plainText, key, nonSecretPayload);\n return Convert.ToBase64String(cipherText);\n }\n\n\n /// <summary>\n /// Simple Decryption & Authentication (AES-GCM) of a UTF8 Message\n /// </summary>\n /// <param name=\"encryptedMessage\">The encrypted message.</param>\n /// <param name=\"key\">The key.</param>\n /// <param name=\"nonSecretPayloadLength\">Length of the optional non-secret payload.</param>\n /// <returns>Decrypted Message</returns>\n public static string SimpleDecrypt(string encryptedMessage, byte[] key, int nonSecretPayloadLength = 0)\n {\n if (string.IsNullOrEmpty(encryptedMessage))\n throw new ArgumentException(\"Encrypted Message Required!\", \"encryptedMessage\");\n\n var cipherText = Convert.FromBase64String(encryptedMessage);\n var plainText = SimpleDecrypt(cipherText, key, nonSecretPayloadLength);\n return plainText == null ? null : Encoding.UTF8.GetString(plainText);\n }\n\n /// <summary>\n /// Simple Encryption And Authentication (AES-GCM) of a UTF8 String\n /// using key derived from a password (PBKDF2).\n /// </summary>\n /// <param name=\"secretMessage\">The secret message.</param>\n /// <param name=\"password\">The password.</param>\n /// <param name=\"nonSecretPayload\">The non secret payload.</param>\n /// <returns>\n /// Encrypted Message\n /// </returns>\n /// <remarks>\n /// Significantly less secure than using random binary keys.\n /// Adds additional non secret payload for key generation parameters.\n /// </remarks>\n public static string SimpleEncryptWithPassword(string secretMessage, string password,\n byte[] nonSecretPayload = null)\n {\n if (string.IsNullOrEmpty(secretMessage))\n throw new ArgumentException(\"Secret Message Required!\", \"secretMessage\");\n\n var plainText = Encoding.UTF8.GetBytes(secretMessage);\n var cipherText = SimpleEncryptWithPassword(plainText, password, nonSecretPayload);\n return Convert.ToBase64String(cipherText);\n }\n\n\n /// <summary>\n /// Simple Decryption and Authentication (AES-GCM) of a UTF8 message\n /// using a key derived from a password (PBKDF2)\n /// </summary>\n /// <param name=\"encryptedMessage\">The encrypted message.</param>\n /// <param name=\"password\">The password.</param>\n /// <param name=\"nonSecretPayloadLength\">Length of the non secret payload.</param>\n /// <returns>\n /// Decrypted Message\n /// </returns>\n /// <exception cref=\"System.ArgumentException\">Encrypted Message Required!;encryptedMessage</exception>\n /// <remarks>\n /// Significantly less secure than using random binary keys.\n /// </remarks>\n public static string SimpleDecryptWithPassword(string encryptedMessage, string password,\n int nonSecretPayloadLength = 0)\n {\n if (string.IsNullOrWhiteSpace(encryptedMessage))\n throw new ArgumentException(\"Encrypted Message Required!\", \"encryptedMessage\");\n\n var cipherText = Convert.FromBase64String(encryptedMessage);\n var plainText = SimpleDecryptWithPassword(cipherText, password, nonSecretPayloadLength);\n return plainText == null ? null : Encoding.UTF8.GetString(plainText);\n }\n\n public static byte[] SimpleEncrypt(byte[] secretMessage, byte[] key, byte[] nonSecretPayload = null)\n {\n //User Error Checks\n if (key == null || key.Length != KeyBitSize / 8)\n throw new ArgumentException(String.Format(\"Key needs to be {0} bit!\", KeyBitSize), \"key\");\n\n if (secretMessage == null || secretMessage.Length == 0)\n throw new ArgumentException(\"Secret Message Required!\", \"secretMessage\");\n\n //Non-secret Payload Optional\n nonSecretPayload = nonSecretPayload ?? new byte[] { };\n\n //Using random nonce large enough not to repeat\n var nonce = new byte[NonceBitSize / 8];\n Random.NextBytes(nonce, 0, nonce.Length);\n\n var cipher = new GcmBlockCipher(new AesFastEngine());\n var parameters = new AeadParameters(new KeyParameter(key), MacBitSize, nonce, nonSecretPayload);\n cipher.Init(true, parameters);\n\n //Generate Cipher Text With Auth Tag\n var cipherText = new byte[cipher.GetOutputSize(secretMessage.Length)];\n var len = cipher.ProcessBytes(secretMessage, 0, secretMessage.Length, cipherText, 0);\n cipher.DoFinal(cipherText, len);\n\n //Assemble Message\n using (var combinedStream = new MemoryStream())\n {\n using (var binaryWriter = new BinaryWriter(combinedStream))\n {\n //Prepend Authenticated Payload\n binaryWriter.Write(nonSecretPayload);\n //Prepend Nonce\n binaryWriter.Write(nonce);\n //Write Cipher Text\n binaryWriter.Write(cipherText);\n }\n return combinedStream.ToArray();\n }\n }\n\n public static byte[] SimpleDecrypt(byte[] encryptedMessage, byte[] key, int nonSecretPayloadLength = 0)\n {\n //User Error Checks\n if (key == null || key.Length != KeyBitSize / 8)\n throw new ArgumentException(String.Format(\"Key needs to be {0} bit!\", KeyBitSize), \"key\");\n\n if (encryptedMessage == null || encryptedMessage.Length == 0)\n throw new ArgumentException(\"Encrypted Message Required!\", \"encryptedMessage\");\n\n using (var cipherStream = new MemoryStream(encryptedMessage))\n using (var cipherReader = new BinaryReader(cipherStream))\n {\n //Grab Payload\n var nonSecretPayload = cipherReader.ReadBytes(nonSecretPayloadLength);\n\n //Grab Nonce\n var nonce = cipherReader.ReadBytes(NonceBitSize / 8);\n\n var cipher = new GcmBlockCipher(new AesFastEngine());\n var parameters = new AeadParameters(new KeyParameter(key), MacBitSize, nonce, nonSecretPayload);\n cipher.Init(false, parameters);\n\n //Decrypt Cipher Text\n var cipherText = cipherReader.ReadBytes(encryptedMessage.Length - nonSecretPayloadLength - nonce.Length);\n var plainText = new byte[cipher.GetOutputSize(cipherText.Length)]; \n\n try\n {\n var len = cipher.ProcessBytes(cipherText, 0, cipherText.Length, plainText, 0);\n cipher.DoFinal(plainText, len);\n\n }\n catch (InvalidCipherTextException)\n {\n //Return null if it doesn't authenticate\n return null;\n }\n\n return plainText;\n }\n\n }\n\n public static byte[] SimpleEncryptWithPassword(byte[] secretMessage, string password, byte[] nonSecretPayload = null)\n {\n nonSecretPayload = nonSecretPayload ?? new byte[] {};\n\n //User Error Checks\n if (string.IsNullOrWhiteSpace(password) || password.Length < MinPasswordLength)\n throw new ArgumentException(String.Format(\"Must have a password of at least {0} characters!\", MinPasswordLength), \"password\");\n\n if (secretMessage == null || secretMessage.Length == 0)\n throw new ArgumentException(\"Secret Message Required!\", \"secretMessage\");\n\n var generator = new Pkcs5S2ParametersGenerator();\n\n //Use Random Salt to minimize pre-generated weak password attacks.\n var salt = new byte[SaltBitSize / 8];\n Random.NextBytes(salt);\n\n generator.Init(\n PbeParametersGenerator.Pkcs5PasswordToBytes(password.ToCharArray()),\n salt,\n Iterations);\n\n //Generate Key\n var key = (KeyParameter)generator.GenerateDerivedMacParameters(KeyBitSize);\n\n //Create Full Non Secret Payload\n var payload = new byte[salt.Length + nonSecretPayload.Length];\n Array.Copy(nonSecretPayload, payload, nonSecretPayload.Length);\n Array.Copy(salt,0, payload,nonSecretPayload.Length, salt.Length);\n\n return SimpleEncrypt(secretMessage, key.GetKey(), payload);\n }\n\n public static byte[] SimpleDecryptWithPassword(byte[] encryptedMessage, string password, int nonSecretPayloadLength = 0)\n {\n //User Error Checks\n if (string.IsNullOrWhiteSpace(password) || password.Length < MinPasswordLength)\n throw new ArgumentException(String.Format(\"Must have a password of at least {0} characters!\", MinPasswordLength), \"password\");\n\n if (encryptedMessage == null || encryptedMessage.Length == 0)\n throw new ArgumentException(\"Encrypted Message Required!\", \"encryptedMessage\");\n\n var generator = new Pkcs5S2ParametersGenerator();\n\n //Grab Salt from Payload\n var salt = new byte[SaltBitSize / 8];\n Array.Copy(encryptedMessage, nonSecretPayloadLength, salt, 0, salt.Length);\n\n generator.Init(\n PbeParametersGenerator.Pkcs5PasswordToBytes(password.ToCharArray()),\n salt,\n Iterations);\n\n //Generate Key\n var key = (KeyParameter)generator.GenerateDerivedMacParameters(KeyBitSize);\n\n return SimpleDecrypt(encryptedMessage, key.GetKey(), salt.Length + nonSecretPayloadLength);\n }\n }\n}\n</code></pre>\n"
},
{
"answer_id": 12122345,
"author": "MAXE",
"author_id": 833644,
"author_profile": "https://Stackoverflow.com/users/833644",
"pm_score": -1,
"selected": false,
"text": "<p>I want to give you my contribute, with my code for AES <code>Rfc2898DeriveBytes</code> (<a href=\"http://msdn.microsoft.com/en-us/library/system.security.cryptography.rfc2898derivebytes.aspx\" rel=\"nofollow\">here</a> the documentation) algorhytm, written in C# (.NET framework 4) and fully working also for limited platforms, as .NET Compact Framework for Windows Phone 7.0+ (not all platforms support every criptographic method of the .NET framework!).</p>\n\n<p>I hope this can help anyone!</p>\n\n<pre><code>using System;\nusing System.IO;\nusing System.Security.Cryptography;\nusing System.Text;\n\npublic static class Crypto\n{\n private static readonly byte[] IVa = new byte[] { 0x0b, 0x0c, 0x0d, 0x0e, 0x0f, 0x11, 0x11, 0x12, 0x13, 0x14, 0x0e, 0x16, 0x17 };\n\n\n public static string Encrypt(this string text, string salt)\n {\n try\n {\n using (Aes aes = new AesManaged())\n {\n Rfc2898DeriveBytes deriveBytes = new Rfc2898DeriveBytes(Encoding.UTF8.GetString(IVa, 0, IVa.Length), Encoding.UTF8.GetBytes(salt));\n aes.Key = deriveBytes.GetBytes(128 / 8);\n aes.IV = aes.Key;\n using (MemoryStream encryptionStream = new MemoryStream())\n {\n using (CryptoStream encrypt = new CryptoStream(encryptionStream, aes.CreateEncryptor(), CryptoStreamMode.Write))\n {\n byte[] cleanText = Encoding.UTF8.GetBytes(text);\n encrypt.Write(cleanText, 0, cleanText.Length);\n encrypt.FlushFinalBlock();\n }\n\n byte[] encryptedData = encryptionStream.ToArray();\n string encryptedText = Convert.ToBase64String(encryptedData);\n\n\n return encryptedText;\n }\n }\n }\n catch\n {\n return String.Empty;\n }\n }\n\n public static string Decrypt(this string text, string salt)\n {\n try\n {\n using (Aes aes = new AesManaged())\n {\n Rfc2898DeriveBytes deriveBytes = new Rfc2898DeriveBytes(Encoding.UTF8.GetString(IVa, 0, IVa.Length), Encoding.UTF8.GetBytes(salt));\n aes.Key = deriveBytes.GetBytes(128 / 8);\n aes.IV = aes.Key;\n\n using (MemoryStream decryptionStream = new MemoryStream())\n {\n using (CryptoStream decrypt = new CryptoStream(decryptionStream, aes.CreateDecryptor(), CryptoStreamMode.Write))\n {\n byte[] encryptedData = Convert.FromBase64String(text);\n\n\n decrypt.Write(encryptedData, 0, encryptedData.Length);\n decrypt.Flush();\n }\n\n byte[] decryptedData = decryptionStream.ToArray();\n string decryptedText = Encoding.UTF8.GetString(decryptedData, 0, decryptedData.Length);\n\n\n return decryptedText;\n }\n }\n }\n catch\n {\n return String.Empty;\n }\n }\n }\n}\n</code></pre>\n"
},
{
"answer_id": 13511671,
"author": "nerdybeardo",
"author_id": 1572267,
"author_profile": "https://Stackoverflow.com/users/1572267",
"pm_score": 6,
"selected": false,
"text": "<p><a href=\"http://www.bouncycastle.org/\" rel=\"noreferrer\">BouncyCastle</a> is a great Crypto library for .NET, it's available as a <a href=\"http://nuget.org/packages/BouncyCastle\" rel=\"noreferrer\">Nuget</a> package for install into your projects. I like it a lot more than what's currently available in the System.Security.Cryptography library. It gives you a lot more options in terms of available algorithms, and provides more modes for those algorithms.</p>\n\n<p>This is an example of an implementation of <a href=\"http://en.wikipedia.org/wiki/Twofish\" rel=\"noreferrer\">TwoFish</a>, which was written by <a href=\"http://en.wikipedia.org/wiki/Bruce_Schneier\" rel=\"noreferrer\">Bruce Schneier</a> (hero to all us paranoid people out there). It's a symmetric algorithm like the Rijndael\n(aka AES). It was one of the three finalists for the AES standard and sibling to another famous algorithm written by Bruce Schneier called BlowFish.</p>\n\n<p>First thing with bouncycastle is to create an encryptor class, this will make it easier to implement other block ciphers within the library. The following encryptor class takes in a generic argument T where T implements IBlockCipher and has a default constructor.</p>\n\n<p><strong>UPDATE:</strong> Due to popular demand I have decided to implement generating a random IV as well as include an HMAC into this class. Although from a style perspective this goes against the SOLID principle of single responsibility, because of the nature of what this class does I reniged. This class will now take two generic parameters, one for the cipher and one for the digest. It automatically generates the IV using RNGCryptoServiceProvider to provide good RNG entropy, and allows you to use whatever digest algorithm you want from BouncyCastle to generate the MAC.</p>\n\n<pre><code>using System;\nusing System.Security.Cryptography;\nusing System.Text;\nusing Org.BouncyCastle.Crypto;\nusing Org.BouncyCastle.Crypto.Macs;\nusing Org.BouncyCastle.Crypto.Modes;\nusing Org.BouncyCastle.Crypto.Paddings;\nusing Org.BouncyCastle.Crypto.Parameters;\n\npublic sealed class Encryptor<TBlockCipher, TDigest>\n where TBlockCipher : IBlockCipher, new()\n where TDigest : IDigest, new()\n{\n private Encoding encoding;\n\n private IBlockCipher blockCipher;\n\n private BufferedBlockCipher cipher;\n\n private HMac mac;\n\n private byte[] key;\n\n public Encryptor(Encoding encoding, byte[] key, byte[] macKey)\n {\n this.encoding = encoding;\n this.key = key;\n this.Init(key, macKey, new Pkcs7Padding());\n }\n\n public Encryptor(Encoding encoding, byte[] key, byte[] macKey, IBlockCipherPadding padding)\n {\n this.encoding = encoding;\n this.key = key;\n this.Init(key, macKey, padding);\n }\n\n private void Init(byte[] key, byte[] macKey, IBlockCipherPadding padding)\n {\n this.blockCipher = new CbcBlockCipher(new TBlockCipher());\n this.cipher = new PaddedBufferedBlockCipher(this.blockCipher, padding);\n this.mac = new HMac(new TDigest());\n this.mac.Init(new KeyParameter(macKey));\n }\n\n public string Encrypt(string plain)\n {\n return Convert.ToBase64String(EncryptBytes(plain));\n }\n\n public byte[] EncryptBytes(string plain)\n {\n byte[] input = this.encoding.GetBytes(plain);\n\n var iv = this.GenerateIV();\n\n var cipher = this.BouncyCastleCrypto(true, input, new ParametersWithIV(new KeyParameter(key), iv));\n byte[] message = CombineArrays(iv, cipher);\n\n this.mac.Reset();\n this.mac.BlockUpdate(message, 0, message.Length);\n byte[] digest = new byte[this.mac.GetUnderlyingDigest().GetDigestSize()];\n this.mac.DoFinal(digest, 0);\n\n var result = CombineArrays(digest, message);\n return result;\n }\n\n public byte[] DecryptBytes(byte[] bytes)\n {\n // split the digest into component parts\n var digest = new byte[this.mac.GetUnderlyingDigest().GetDigestSize()];\n var message = new byte[bytes.Length - digest.Length];\n var iv = new byte[this.blockCipher.GetBlockSize()];\n var cipher = new byte[message.Length - iv.Length];\n\n Buffer.BlockCopy(bytes, 0, digest, 0, digest.Length);\n Buffer.BlockCopy(bytes, digest.Length, message, 0, message.Length);\n if (!IsValidHMac(digest, message))\n {\n throw new CryptoException();\n }\n\n Buffer.BlockCopy(message, 0, iv, 0, iv.Length);\n Buffer.BlockCopy(message, iv.Length, cipher, 0, cipher.Length);\n\n byte[] result = this.BouncyCastleCrypto(false, cipher, new ParametersWithIV(new KeyParameter(key), iv));\n return result;\n }\n\n public string Decrypt(byte[] bytes)\n {\n return this.encoding.GetString(DecryptBytes(bytes));\n }\n\n public string Decrypt(string cipher)\n {\n return this.Decrypt(Convert.FromBase64String(cipher));\n }\n\n private bool IsValidHMac(byte[] digest, byte[] message)\n {\n this.mac.Reset();\n this.mac.BlockUpdate(message, 0, message.Length);\n byte[] computed = new byte[this.mac.GetUnderlyingDigest().GetDigestSize()];\n this.mac.DoFinal(computed, 0);\n\n return AreEqual(digest,computed);\n }\n\n private static bool AreEqual(byte [] digest, byte[] computed)\n {\n if(digest.Length != computed.Length)\n {\n return false;\n }\n\n int result = 0;\n for (int i = 0; i < digest.Length; i++)\n {\n // compute equality of all bytes before returning.\n // helps prevent timing attacks: \n // https://codahale.com/a-lesson-in-timing-attacks/\n result |= digest[i] ^ computed[i];\n }\n\n return result == 0;\n }\n\n private byte[] BouncyCastleCrypto(bool forEncrypt, byte[] input, ICipherParameters parameters)\n {\n try\n {\n cipher.Init(forEncrypt, parameters);\n\n return this.cipher.DoFinal(input);\n }\n catch (CryptoException)\n {\n throw;\n }\n }\n\n private byte[] GenerateIV()\n {\n using (var provider = new RNGCryptoServiceProvider())\n {\n // 1st block\n byte[] result = new byte[this.blockCipher.GetBlockSize()];\n provider.GetBytes(result);\n\n return result;\n }\n }\n\n private static byte[] CombineArrays(byte[] source1, byte[] source2)\n {\n byte[] result = new byte[source1.Length + source2.Length];\n Buffer.BlockCopy(source1, 0, result, 0, source1.Length);\n Buffer.BlockCopy(source2, 0, result, source1.Length, source2.Length);\n\n return result;\n }\n}\n</code></pre>\n\n<p>Next just call the encrypt and decrypt methods on the new class, here's the example using twofish:</p>\n\n<pre><code>var encrypt = new Encryptor<TwofishEngine, Sha1Digest>(Encoding.UTF8, key, hmacKey);\n\nstring cipher = encrypt.Encrypt(\"TEST\"); \nstring plainText = encrypt.Decrypt(cipher);\n</code></pre>\n\n<p>It's just as easy to substitute another block cipher like TripleDES:</p>\n\n<pre><code>var des = new Encryptor<DesEdeEngine, Sha1Digest>(Encoding.UTF8, key, hmacKey);\n\nstring cipher = des.Encrypt(\"TEST\");\nstring plainText = des.Decrypt(cipher);\n</code></pre>\n\n<p>Finally if you want to use AES with SHA256 HMAC you can do the following:</p>\n\n<pre><code>var aes = new Encryptor<AesEngine, Sha256Digest>(Encoding.UTF8, key, hmacKey);\n\ncipher = aes.Encrypt(\"TEST\");\nplainText = aes.Decrypt(cipher);\n</code></pre>\n\n<p>The hardest part about encryption actually deals with the keys and not the algorithms. You'll have to think about where you store your keys, and if you have to, how you exchange them. These algorithms have all withstood the test of time, and are extremely hard to break. Someone who wants to steal information from you isn't going to spend eternity doing cryptanalysis on your messages, they're going to try to figure out what or where your key is. So #1 choose your keys wisely, #2 store them in a safe place, if you use a web.config and IIS then you can <a href=\"http://msdn.microsoft.com/en-us/library/dtkwfdky%28v=vs.100%29.aspx\" rel=\"noreferrer\">encrypt parts of the the web.config</a>, and finally if you have to exchange keys make sure that your protocol for exchanging the key is secure.</p>\n\n<p><strong>Update 2</strong>\nChanged compare method to mitigate against timing attacks. See more info here <a href=\"http://codahale.com/a-lesson-in-timing-attacks/\" rel=\"noreferrer\">http://codahale.com/a-lesson-in-timing-attacks/</a> . Also updated to default to PKCS7 padding and added new constructor to allow end user the ability to choose which padding they would like to use. Thanks @CodesInChaos for the suggestions.</p>\n"
},
{
"answer_id": 15407665,
"author": "mattmanser",
"author_id": 62829,
"author_profile": "https://Stackoverflow.com/users/62829",
"pm_score": 6,
"selected": false,
"text": "<p>If you are using ASP.Net you can now use built in functionality in .Net 4.0 onwards.</p>\n\n<p><a href=\"http://msdn.microsoft.com/en-us/library/system.web.security.machinekey.aspx\" rel=\"noreferrer\">System.Web.Security.MachineKey</a></p>\n\n<p>.Net 4.5 has <code>MachineKey.Protect()</code> and <code>MachineKey.Unprotect()</code>.</p>\n\n<p>.Net 4.0 has <code>MachineKey.Encode()</code> and <code>MachineKey.Decode()</code>. You should just set the MachineKeyProtection to 'All'.</p>\n\n<p>Outside of ASP.Net this class seems to generate a new key with every app restart so doesn't work. With a quick peek in ILSpy it looks to me like it generates its own defaults if the appropriate app.settings are missing. So you may actually be able to set it up outside ASP.Net.</p>\n\n<p>I haven't been able to find a non-ASP.Net equivalent outside the System.Web namespace.</p>\n"
},
{
"answer_id": 19125021,
"author": "Catto",
"author_id": 17877,
"author_profile": "https://Stackoverflow.com/users/17877",
"pm_score": 2,
"selected": false,
"text": "<p>This is the class that was placed here by Brett. However I made a slight edit since I was receiving the error 'Invalid length for a Base-64 char array' when using it for URL strings to encrypt and decrypt.</p>\n\n<pre><code>public class CryptoURL\n{\n private static byte[] _salt = Encoding.ASCII.GetBytes(\"Catto_Salt_Enter_Any_Value99\");\n\n /// <summary>\n /// Encrypt the given string using AES. The string can be decrypted using \n /// DecryptStringAES(). The sharedSecret parameters must match. \n /// The SharedSecret for the Password Reset that is used is in the next line\n /// string sharedSecret = \"OneUpSharedSecret9\";\n /// </summary>\n /// <param name=\"plainText\">The text to encrypt.</param>\n /// <param name=\"sharedSecret\">A password used to generate a key for encryption.</param>\n public static string EncryptString(string plainText, string sharedSecret)\n {\n if (string.IsNullOrEmpty(plainText))\n throw new ArgumentNullException(\"plainText\");\n if (string.IsNullOrEmpty(sharedSecret))\n throw new ArgumentNullException(\"sharedSecret\");\n\n string outStr = null; // Encrypted string to return\n RijndaelManaged aesAlg = null; // RijndaelManaged object used to encrypt the data.\n\n try\n {\n // generate the key from the shared secret and the salt\n Rfc2898DeriveBytes key = new Rfc2898DeriveBytes(sharedSecret, _salt);\n\n // Create a RijndaelManaged object\n aesAlg = new RijndaelManaged();\n aesAlg.Key = key.GetBytes(aesAlg.KeySize / 8);\n\n // Create a decryptor to perform the stream transform.\n ICryptoTransform encryptor = aesAlg.CreateEncryptor(aesAlg.Key, aesAlg.IV);\n\n // Create the streams used for encryption.\n using (MemoryStream msEncrypt = new MemoryStream())\n {\n // prepend the IV\n msEncrypt.Write(BitConverter.GetBytes(aesAlg.IV.Length), 0, sizeof(int));\n msEncrypt.Write(aesAlg.IV, 0, aesAlg.IV.Length);\n using (CryptoStream csEncrypt = new CryptoStream(msEncrypt, encryptor, CryptoStreamMode.Write))\n {\n using (StreamWriter swEncrypt = new StreamWriter(csEncrypt))\n {\n //Write all data to the stream.\n swEncrypt.Write(plainText);\n }\n }\n\n outStr = HttpServerUtility.UrlTokenEncode(msEncrypt.ToArray());\n //outStr = Convert.ToBase64String(msEncrypt.ToArray());\n // you may need to add a reference. right click reference in solution explorer => \"add Reference\" => .NET tab => select \"System.Web\"\n }\n }\n finally\n {\n // Clear the RijndaelManaged object.\n if (aesAlg != null)\n aesAlg.Clear();\n }\n\n // Return the encrypted bytes from the memory stream.\n return outStr;\n }\n\n /// <summary>\n /// Decrypt the given string. Assumes the string was encrypted using \n /// EncryptStringAES(), using an identical sharedSecret.\n /// </summary>\n /// <param name=\"cipherText\">The text to decrypt.</param>\n /// <param name=\"sharedSecret\">A password used to generate a key for decryption.</param>\n public static string DecryptString(string cipherText, string sharedSecret)\n {\n if (string.IsNullOrEmpty(cipherText))\n throw new ArgumentNullException(\"cipherText\");\n if (string.IsNullOrEmpty(sharedSecret))\n throw new ArgumentNullException(\"sharedSecret\");\n\n // Declare the RijndaelManaged object\n // used to decrypt the data.\n RijndaelManaged aesAlg = null;\n\n // Declare the string used to hold\n // the decrypted text.\n string plaintext = null;\n\n byte[] inputByteArray;\n\n try\n {\n // generate the key from the shared secret and the salt\n Rfc2898DeriveBytes key = new Rfc2898DeriveBytes(sharedSecret, _salt);\n\n // Create the streams used for decryption. \n //byte[] bytes = Convert.FromBase64String(cipherText);\n inputByteArray = HttpServerUtility.UrlTokenDecode(cipherText);\n\n using (MemoryStream msDecrypt = new MemoryStream(inputByteArray))\n {\n // Create a RijndaelManaged object\n // with the specified key and IV.\n aesAlg = new RijndaelManaged();\n aesAlg.Key = key.GetBytes(aesAlg.KeySize / 8);\n // Get the initialization vector from the encrypted stream\n aesAlg.IV = ReadByteArray(msDecrypt);\n // Create a decrytor to perform the stream transform.\n ICryptoTransform decryptor = aesAlg.CreateDecryptor(aesAlg.Key, aesAlg.IV);\n using (CryptoStream csDecrypt = new CryptoStream(msDecrypt, decryptor, CryptoStreamMode.Read))\n {\n using (StreamReader srDecrypt = new StreamReader(csDecrypt))\n\n // Read the decrypted bytes from the decrypting stream\n // and place them in a string.\n plaintext = srDecrypt.ReadToEnd();\n }\n }\n }\n catch (System.Exception ex)\n {\n return \"ERROR\";\n //throw ex;\n\n }\n finally\n {\n // Clear the RijndaelManaged object.\n if (aesAlg != null)\n aesAlg.Clear();\n }\n\n return plaintext;\n }\n\n static string ConvertStringArrayToString(string[] array)\n {\n //\n // Concatenate all the elements into a StringBuilder.\n //\n StringBuilder builder = new StringBuilder();\n foreach (string value in array)\n {\n builder.Append(value);\n builder.Append('.');\n }\n return builder.ToString();\n }\n\n private static byte[] ReadByteArray(Stream s)\n {\n byte[] rawLength = new byte[sizeof(int)];\n if (s.Read(rawLength, 0, rawLength.Length) != rawLength.Length)\n {\n throw new SystemException(\"Stream did not contain properly formatted byte array\");\n }\n\n byte[] buffer = new byte[BitConverter.ToInt32(rawLength, 0)];\n if (s.Read(buffer, 0, buffer.Length) != buffer.Length)\n {\n throw new SystemException(\"Did not read byte array properly\");\n }\n\n return buffer;\n }\n\n}\n</code></pre>\n"
},
{
"answer_id": 22934397,
"author": "KarthikManoharan",
"author_id": 1463105,
"author_profile": "https://Stackoverflow.com/users/1463105",
"pm_score": -1,
"selected": false,
"text": "<pre><code> using System;\n using System.Collections.Generic;\n using System.Text;\n using System.Text.RegularExpressions; // This is for password validation\n using System.Security.Cryptography;\n using System.Configuration; // This is where the hash functions reside\n\n namespace BullyTracker.Common\n {\n public class HashEncryption\n {\n //public string GenerateHashvalue(string thisPassword)\n //{\n // MD5CryptoServiceProvider md5 = new MD5CryptoServiceProvider();\n // byte[] tmpSource;\n // byte[] tmpHash;\n\n // tmpSource = ASCIIEncoding.ASCII.GetBytes(thisPassword); // Turn password into byte array\n // tmpHash = md5.ComputeHash(tmpSource);\n\n // StringBuilder sOutput = new StringBuilder(tmpHash.Length);\n // for (int i = 0; i < tmpHash.Length; i++)\n // {\n // sOutput.Append(tmpHash[i].ToString(\"X2\")); // X2 formats to hexadecimal\n // }\n // return sOutput.ToString();\n //}\n //public Boolean VerifyHashPassword(string thisPassword, string thisHash)\n //{\n // Boolean IsValid = false;\n // string tmpHash = GenerateHashvalue(thisPassword); // Call the routine on user input\n // if (tmpHash == thisHash) IsValid = true; // Compare to previously generated hash\n // return IsValid;\n //}\n public string GenerateHashvalue(string toEncrypt, bool useHashing)\n {\n byte[] keyArray;\n byte[] toEncryptArray = UTF8Encoding.UTF8.GetBytes(toEncrypt);\n\n System.Configuration.AppSettingsReader settingsReader = new AppSettingsReader();\n // Get the key from config file\n string key = (string)settingsReader.GetValue(\"SecurityKey\", typeof(String));\n //System.Windows.Forms.MessageBox.Show(key);\n if (useHashing)\n {\n MD5CryptoServiceProvider hashmd5 = new MD5CryptoServiceProvider();\n keyArray = hashmd5.ComputeHash(UTF8Encoding.UTF8.GetBytes(key));\n hashmd5.Clear();\n }\n else\n keyArray = UTF8Encoding.UTF8.GetBytes(key);\n\n TripleDESCryptoServiceProvider tdes = new TripleDESCryptoServiceProvider();\n tdes.Key = keyArray;\n tdes.Mode = CipherMode.ECB;\n tdes.Padding = PaddingMode.PKCS7;\n\n ICryptoTransform cTransform = tdes.CreateEncryptor();\n byte[] resultArray = cTransform.TransformFinalBlock(toEncryptArray, 0, toEncryptArray.Length);\n tdes.Clear();\n return Convert.ToBase64String(resultArray, 0, resultArray.Length);\n }\n /// <summary>\n /// DeCrypt a string using dual encryption method. Return a DeCrypted clear string\n /// </summary>\n /// <param name=\"cipherString\">encrypted string</param>\n /// <param name=\"useHashing\">Did you use hashing to encrypt this data? pass true is yes</param>\n /// <returns></returns>\n public string Decrypt(string cipherString, bool useHashing)\n {\n byte[] keyArray;\n byte[] toEncryptArray = Convert.FromBase64String(cipherString);\n\n System.Configuration.AppSettingsReader settingsReader = new AppSettingsReader();\n //Get your key from config file to open the lock!\n string key = (string)settingsReader.GetValue(\"SecurityKey\", typeof(String));\n\n if (useHashing)\n {\n MD5CryptoServiceProvider hashmd5 = new MD5CryptoServiceProvider();\n keyArray = hashmd5.ComputeHash(UTF8Encoding.UTF8.GetBytes(key));\n hashmd5.Clear();\n }\n else\n keyArray = UTF8Encoding.UTF8.GetBytes(key);\n\n TripleDESCryptoServiceProvider tdes = new TripleDESCryptoServiceProvider();\n tdes.Key = keyArray;\n tdes.Mode = CipherMode.ECB;\n tdes.Padding = PaddingMode.PKCS7;\n\n ICryptoTransform cTransform = tdes.CreateDecryptor();\n byte[] resultArray = cTransform.TransformFinalBlock(toEncryptArray, 0, toEncryptArray.Length);\n\n tdes.Clear();\n return UTF8Encoding.UTF8.GetString(resultArray);\n }\n\n\n }\n\n }\n</code></pre>\n"
},
{
"answer_id": 23245293,
"author": "user3556387",
"author_id": 3556387,
"author_profile": "https://Stackoverflow.com/users/3556387",
"pm_score": -1,
"selected": false,
"text": "<p>for simplicity i made for myself this function that i use for non crypto purposes : replace \"yourpassphrase\" with your password ...</p>\n\n<pre><code>using System;\nusing System.Collections.Generic;\nusing System.Linq;\nusing System.Text;\nusing System.Security.Cryptography;\nusing System.IO;\n\n namespace My\n{\n public class strCrypto\n {\n // This constant string is used as a \"salt\" value for the PasswordDeriveBytes function calls.\n // This size of the IV (in bytes) must = (keysize / 8). Default keysize is 256, so the IV must be\n // 32 bytes long. Using a 16 character string here gives us 32 bytes when converted to a byte array.\n private const string initVector = \"r5dm5fgm24mfhfku\";\n private const string passPhrase = \"yourpassphrase\"; // email password encryption password\n\n // This constant is used to determine the keysize of the encryption algorithm.\n private const int keysize = 256;\n\n public static string encryptString(string plainText)\n {\n //if the plaintext is empty or null string just return an empty string\n if (plainText == \"\" || plainText == null )\n {\n return \"\";\n }\n\n byte[] initVectorBytes = Encoding.UTF8.GetBytes(initVector);\n byte[] plainTextBytes = Encoding.UTF8.GetBytes(plainText);\n PasswordDeriveBytes password = new PasswordDeriveBytes(passPhrase, null);\n byte[] keyBytes = password.GetBytes(keysize / 8);\n RijndaelManaged symmetricKey = new RijndaelManaged();\n symmetricKey.Mode = CipherMode.CBC;\n ICryptoTransform encryptor = symmetricKey.CreateEncryptor(keyBytes, initVectorBytes);\n MemoryStream memoryStream = new MemoryStream();\n CryptoStream cryptoStream = new CryptoStream(memoryStream, encryptor, CryptoStreamMode.Write);\n cryptoStream.Write(plainTextBytes, 0, plainTextBytes.Length);\n cryptoStream.FlushFinalBlock();\n byte[] cipherTextBytes = memoryStream.ToArray();\n memoryStream.Close();\n cryptoStream.Close();\n return Convert.ToBase64String(cipherTextBytes);\n }\n\n public static string decryptString(string cipherText)\n {\n //if the ciphertext is empty or null string just return an empty string\n if (cipherText == \"\" || cipherText == null )\n {\n return \"\";\n }\n\n byte[] initVectorBytes = Encoding.ASCII.GetBytes(initVector);\n byte[] cipherTextBytes = Convert.FromBase64String(cipherText);\n PasswordDeriveBytes password = new PasswordDeriveBytes(passPhrase, null);\n byte[] keyBytes = password.GetBytes(keysize / 8);\n RijndaelManaged symmetricKey = new RijndaelManaged();\n symmetricKey.Mode = CipherMode.CBC;\n ICryptoTransform decryptor = symmetricKey.CreateDecryptor(keyBytes, initVectorBytes);\n MemoryStream memoryStream = new MemoryStream(cipherTextBytes);\n CryptoStream cryptoStream = new CryptoStream(memoryStream, decryptor, CryptoStreamMode.Read);\n byte[] plainTextBytes = new byte[cipherTextBytes.Length];\n int decryptedByteCount = cryptoStream.Read(plainTextBytes, 0, plainTextBytes.Length);\n memoryStream.Close();\n cryptoStream.Close();\n return Encoding.UTF8.GetString(plainTextBytes, 0, decryptedByteCount);\n }\n\n\n}\n</code></pre>\n\n<p>}</p>\n"
},
{
"answer_id": 24401587,
"author": "Jim Flood",
"author_id": 233596,
"author_profile": "https://Stackoverflow.com/users/233596",
"pm_score": 2,
"selected": false,
"text": "<p>Here is a simple example of encrypting strings in C# using AES CBC mode with random IV and HMAC and password-derived keys, to show the basic moving parts:</p>\n\n<pre><code>private byte[] EncryptBytes(byte[] key, byte[] plaintext)\n{\n using (var cipher = new RijndaelManaged { Key = key })\n {\n using (var encryptor = cipher.CreateEncryptor())\n {\n var ciphertext = encryptor.TransformFinalBlock(plaintext, 0, plaintext.Length);\n\n // IV is prepended to ciphertext\n return cipher.IV.Concat(ciphertext).ToArray();\n }\n }\n}\n\nprivate byte[] DecryptBytes(byte[] key, byte[] packed)\n{\n using (var cipher = new RijndaelManaged { Key = key })\n {\n int ivSize = cipher.BlockSize / 8;\n\n cipher.IV = packed.Take(ivSize).ToArray();\n\n using (var encryptor = cipher.CreateDecryptor())\n {\n return encryptor.TransformFinalBlock(packed, ivSize, packed.Length - ivSize);\n }\n }\n}\n\nprivate byte[] AddMac(byte[] key, byte[] data)\n{\n using (var hmac = new HMACSHA256(key))\n {\n var macBytes = hmac.ComputeHash(data);\n\n // HMAC is appended to data\n return data.Concat(macBytes).ToArray();\n }\n}\n\nprivate bool BadMac(byte[] found, byte[] computed)\n{\n int mismatch = 0;\n\n // Aim for consistent timing regardless of inputs\n for (int i = 0; i < found.Length; i++)\n {\n mismatch += found[i] == computed[i] ? 0 : 1;\n }\n\n return mismatch != 0;\n}\n\nprivate byte[] RemoveMac(byte[] key, byte[] data)\n{\n using (var hmac = new HMACSHA256(key))\n {\n int macSize = hmac.HashSize / 8;\n\n var packed = data.Take(data.Length - macSize).ToArray();\n\n var foundMac = data.Skip(packed.Length).ToArray();\n\n var computedMac = hmac.ComputeHash(packed);\n\n if (this.BadMac(foundMac, computedMac))\n {\n throw new Exception(\"Bad MAC\");\n }\n\n return packed;\n } \n}\n\nprivate List<byte[]> DeriveTwoKeys(string password)\n{\n var salt = new byte[] { 1, 2, 3, 4, 5, 6, 7, 8 };\n\n var kdf = new Rfc2898DeriveBytes(password, salt, 10000);\n\n var bytes = kdf.GetBytes(32); // Two keys 128 bits each\n\n return new List<byte[]> { bytes.Take(16).ToArray(), bytes.Skip(16).ToArray() };\n}\n\npublic byte[] EncryptString(string password, String message)\n{\n var keys = this.DeriveTwoKeys(password);\n\n var plaintext = Encoding.UTF8.GetBytes(message);\n\n var packed = this.EncryptBytes(keys[0], plaintext);\n\n return this.AddMac(keys[1], packed);\n}\n\npublic String DecryptString(string password, byte[] secret)\n{\n var keys = this.DeriveTwoKeys(password);\n\n var packed = this.RemoveMac(keys[1], secret);\n\n var plaintext = this.DecryptBytes(keys[0], packed);\n\n return Encoding.UTF8.GetString(plaintext);\n}\n\npublic void Example()\n{\n var password = \"correcthorsebatterystaple\";\n\n var secret = this.EncryptString(password, \"Hello World\");\n\n Console.WriteLine(\"secret: \" + BitConverter.ToString(secret));\n\n var recovered = this.DecryptString(password, secret);\n\n Console.WriteLine(recovered);\n}\n</code></pre>\n"
},
{
"answer_id": 26518619,
"author": "angularsen",
"author_id": 134761,
"author_profile": "https://Stackoverflow.com/users/134761",
"pm_score": 0,
"selected": false,
"text": "<p>Copied in my <a href=\"https://stackoverflow.com/a/26518496/134761\">answer</a> here from a similar question: <a href=\"https://stackoverflow.com/q/165808/134761\">Simple two-way encryption for C#</a>.</p>\n\n<p>Based on multiple answers and comments.</p>\n\n<ul>\n<li>Random initialization vector prepended to crypto text (@jbtule)</li>\n<li>Use TransformFinalBlock() instead of MemoryStream (@RenniePet)</li>\n<li>No pre-filled keys to avoid anyone copy & pasting a disaster</li>\n<li>Proper dispose and using patterns</li>\n</ul>\n\n<p>Code:</p>\n\n<pre><code>/// <summary>\n/// Simple encryption/decryption using a random initialization vector\n/// and prepending it to the crypto text.\n/// </summary>\n/// <remarks>Based on multiple answers in https://stackoverflow.com/questions/165808/simple-two-way-encryption-for-c-sharp </remarks>\npublic class SimpleAes : IDisposable\n{\n /// <summary>\n /// Initialization vector length in bytes.\n /// </summary>\n private const int IvBytes = 16;\n\n /// <summary>\n /// Must be exactly 16, 24 or 32 characters long.\n /// </summary>\n private static readonly byte[] Key = Convert.FromBase64String(\"FILL ME WITH 16, 24 OR 32 CHARS\");\n\n private readonly UTF8Encoding _encoder;\n private readonly ICryptoTransform _encryptor;\n private readonly RijndaelManaged _rijndael;\n\n public SimpleAes()\n {\n _rijndael = new RijndaelManaged {Key = Key};\n _rijndael.GenerateIV();\n _encryptor = _rijndael.CreateEncryptor();\n _encoder = new UTF8Encoding();\n }\n\n public string Decrypt(string encrypted)\n {\n return _encoder.GetString(Decrypt(Convert.FromBase64String(encrypted)));\n }\n\n public void Dispose()\n {\n _rijndael.Dispose();\n _encryptor.Dispose();\n }\n\n public string Encrypt(string unencrypted)\n {\n return Convert.ToBase64String(Encrypt(_encoder.GetBytes(unencrypted)));\n }\n\n private byte[] Decrypt(byte[] buffer)\n {\n // IV is prepended to cryptotext\n byte[] iv = buffer.Take(IvBytes).ToArray();\n using (ICryptoTransform decryptor = _rijndael.CreateDecryptor(_rijndael.Key, iv))\n {\n return decryptor.TransformFinalBlock(buffer, IvBytes, buffer.Length - IvBytes);\n }\n }\n\n private byte[] Encrypt(byte[] buffer)\n {\n // Prepend cryptotext with IV\n byte[] inputBuffer = _rijndael.IV.Concat(buffer).ToArray();\n return _encryptor.TransformFinalBlock(inputBuffer, IvBytes, buffer.Length);\n }\n}\n</code></pre>\n"
},
{
"answer_id": 27223411,
"author": "Manu Nair",
"author_id": 4310461,
"author_profile": "https://Stackoverflow.com/users/4310461",
"pm_score": -1,
"selected": false,
"text": "<p>You have to use the namespace using System.Security.Cryptography; and useHashing is a bool type either true or false. String variable \"key\" should be same for Encryption and for Decryption</p>\n\n<pre><code>//Encryption\npublic string EncryptText(string toEncrypt, bool useHashing)\n {\n try\n {\n byte[] keyArray;\n byte[] toEncryptArray = UTF8Encoding.UTF8.GetBytes(toEncrypt);\n\n string key = \"String Key Value\"; //Based on this key stirng is encrypting\n //System.Windows.Forms.MessageBox.Show(key);\n //If hashing use get hashcode regards to your key\n if (useHashing)\n {\n MD5CryptoServiceProvider hashmd5 = new MD5CryptoServiceProvider();\n keyArray = hashmd5.ComputeHash(UTF8Encoding.UTF8.GetBytes(key));\n //Always release the resources and flush data\n //of the Cryptographic service provide. Best Practice\n\n hashmd5.Clear();\n }\n else\n keyArray = UTF8Encoding.UTF8.GetBytes(key);\n\n TripleDESCryptoServiceProvider tdes = new TripleDESCryptoServiceProvider();\n //set the secret key for the tripleDES algorithm\n tdes.Key = keyArray;\n //mode of operation. there are other 4 modes. We choose ECB(Electronic code Book)\n tdes.Mode = CipherMode.ECB;\n //padding mode(if any extra byte added)\n tdes.Padding = PaddingMode.PKCS7;\n\n ICryptoTransform cTransform = tdes.CreateEncryptor();\n //transform the specified region of bytes array to resultArray\n byte[] resultArray = cTransform.TransformFinalBlock(toEncryptArray, 0, toEncryptArray.Length);\n //Release resources held by TripleDes Encryptor\n tdes.Clear();\n //Return the encrypted data into unreadable string format\n return Convert.ToBase64String(resultArray, 0, resultArray.Length);\n }\n catch (Exception e)\n {\n throw e;\n }\n }\n\n //Decryption\n public string DecryptText(string cipherString, bool useHashing)\n {\n\n try\n {\n byte[] keyArray;\n //get the byte code of the string\n\n byte[] toEncryptArray = Convert.FromBase64String(cipherString);\n\n string key = \"String Key Value\"; //Based on this key string is decrypted\n\n if (useHashing)\n {\n //if hashing was used get the hash code with regards to your key\n MD5CryptoServiceProvider hashmd5 = new MD5CryptoServiceProvider();\n keyArray = hashmd5.ComputeHash(UTF8Encoding.UTF8.GetBytes(key));\n //release any resource held by the MD5CryptoServiceProvider\n\n hashmd5.Clear();\n }\n else\n {\n //if hashing was not implemented get the byte code of the key\n keyArray = UTF8Encoding.UTF8.GetBytes(key);\n }\n\n TripleDESCryptoServiceProvider tdes = new TripleDESCryptoServiceProvider();\n //set the secret key for the tripleDES algorithm\n tdes.Key = keyArray;\n //mode of operation. there are other 4 modes.\n //We choose ECB(Electronic code Book)\n\n tdes.Mode = CipherMode.ECB;\n //padding mode(if any extra byte added)\n tdes.Padding = PaddingMode.PKCS7;\n\n ICryptoTransform cTransform = tdes.CreateDecryptor();\n byte[] resultArray = cTransform.TransformFinalBlock\n (toEncryptArray, 0, toEncryptArray.Length);\n //Release resources held by TripleDes Encryptor\n tdes.Clear();\n //return the Clear decrypted TEXT\n return UTF8Encoding.UTF8.GetString(resultArray);\n }\n catch (Exception ex)\n {\n throw ex;\n }\n }\n</code></pre>\n"
},
{
"answer_id": 27519762,
"author": "Vijay Kumbhoje",
"author_id": 3583859,
"author_profile": "https://Stackoverflow.com/users/3583859",
"pm_score": 0,
"selected": false,
"text": "<p>Here is simple Snippet originally by ASP Snippets </p>\n\n<pre><code>using System.Text;\nusing System.Security.Cryptography;\nusing System.IO;\n\n\n private string Encrypt(string clearText)\n {\n string EncryptionKey = \"yourkey\";\n byte[] clearBytes = Encoding.Unicode.GetBytes(clearText);\n using (Aes encryptor = Aes.Create())\n {\n Rfc2898DeriveBytes pdb = new Rfc2898DeriveBytes(EncryptionKey, new byte[] { 0x49, 0x76, 0x61, 0x6e, 0x20, 0x4d, 0x65, 0x64, 0x76, 0x65, 0x64, 0x65, 0x76 });\n encryptor.Key = pdb.GetBytes(32);\n encryptor.IV = pdb.GetBytes(16);\n using (MemoryStream ms = new MemoryStream())\n {\n using (CryptoStream cs = new CryptoStream(ms, encryptor.CreateEncryptor(), CryptoStreamMode.Write))\n {\n cs.Write(clearBytes, 0, clearBytes.Length);\n cs.Close();\n }\n clearText = Convert.ToBase64String(ms.ToArray());\n }\n }\n return clearText;\n }\n\n private string Decrypt(string cipherText)\n {\n string EncryptionKey = \"yourkey\";\n cipherText = cipherText.Replace(\" \", \"+\");\n byte[] cipherBytes = Convert.FromBase64String(cipherText);\n using (Aes encryptor = Aes.Create())\n {\n Rfc2898DeriveBytes pdb = new Rfc2898DeriveBytes(EncryptionKey, new byte[] { 0x49, 0x76, 0x61, 0x6e, 0x20, 0x4d, 0x65, 0x64, 0x76, 0x65, 0x64, 0x65, 0x76 });\n encryptor.Key = pdb.GetBytes(32);\n encryptor.IV = pdb.GetBytes(16);\n using (MemoryStream ms = new MemoryStream())\n {\n using (CryptoStream cs = new CryptoStream(ms, encryptor.CreateDecryptor(), CryptoStreamMode.Write))\n {\n cs.Write(cipherBytes, 0, cipherBytes.Length);\n cs.Close();\n }\n cipherText = Encoding.Unicode.GetString(ms.ToArray());\n }\n }\n return cipherText;\n }\n</code></pre>\n"
},
{
"answer_id": 28605068,
"author": "Gopal Reddy V",
"author_id": 4540291,
"author_profile": "https://Stackoverflow.com/users/4540291",
"pm_score": 4,
"selected": false,
"text": "<p>Encryption</p>\n\n<pre class=\"lang-cs prettyprint-override\"><code>public string EncryptString(string inputString)\n{\n MemoryStream memStream = null;\n try\n {\n byte[] key = { };\n byte[] IV = { 12, 21, 43, 17, 57, 35, 67, 27 };\n string encryptKey = \"aXb2uy4z\"; // MUST be 8 characters\n key = Encoding.UTF8.GetBytes(encryptKey);\n byte[] byteInput = Encoding.UTF8.GetBytes(inputString);\n DESCryptoServiceProvider provider = new DESCryptoServiceProvider();\n memStream = new MemoryStream();\n ICryptoTransform transform = provider.CreateEncryptor(key, IV);\n CryptoStream cryptoStream = new CryptoStream(memStream, transform, CryptoStreamMode.Write);\n cryptoStream.Write(byteInput, 0, byteInput.Length);\n cryptoStream.FlushFinalBlock();\n }\n catch (Exception ex)\n {\n Response.Write(ex.Message);\n }\n return Convert.ToBase64String(memStream.ToArray());\n}\n</code></pre>\n\n<p>Decryption: </p>\n\n<pre class=\"lang-cs prettyprint-override\"><code>public string DecryptString(string inputString)\n{\n MemoryStream memStream = null;\n try\n {\n byte[] key = { };\n byte[] IV = { 12, 21, 43, 17, 57, 35, 67, 27 };\n string encryptKey = \"aXb2uy4z\"; // MUST be 8 characters\n key = Encoding.UTF8.GetBytes(encryptKey);\n byte[] byteInput = new byte[inputString.Length];\n byteInput = Convert.FromBase64String(inputString);\n DESCryptoServiceProvider provider = new DESCryptoServiceProvider();\n memStream = new MemoryStream();\n ICryptoTransform transform = provider.CreateDecryptor(key, IV);\n CryptoStream cryptoStream = new CryptoStream(memStream, transform, CryptoStreamMode.Write);\n cryptoStream.Write(byteInput, 0, byteInput.Length);\n cryptoStream.FlushFinalBlock();\n }\n catch (Exception ex)\n {\n Response.Write(ex.Message);\n }\n\n Encoding encoding1 = Encoding.UTF8;\n return encoding1.GetString(memStream.ToArray());\n}\n</code></pre>\n"
},
{
"answer_id": 30094557,
"author": "Konamiman",
"author_id": 4574,
"author_profile": "https://Stackoverflow.com/users/4574",
"pm_score": -1,
"selected": false,
"text": "<p>A good algorithm to securely hash data is <a href=\"http://en.wikipedia.org/wiki/Bcrypt\" rel=\"nofollow noreferrer\">BCrypt</a>:</p>\n\n<blockquote>\n <p>Besides incorporating a salt to protect against rainbow table attacks,\n bcrypt is an adaptive function: over time, the iteration count can be\n increased to make it slower, so it remains resistant to brute-force\n search attacks even with increasing computation power.</p>\n</blockquote>\n\n<p>There's a nice <a href=\"https://github.com/BcryptNet/bcrypt.net\" rel=\"nofollow noreferrer\">.NET implementation of BCrypt</a> that is available also <a href=\"https://www.nuget.org/packages/BCrypt.Net-Next/\" rel=\"nofollow noreferrer\">as a NuGet package</a>.</p>\n"
},
{
"answer_id": 30438370,
"author": "Gil Cohen",
"author_id": 2464918,
"author_profile": "https://Stackoverflow.com/users/2464918",
"pm_score": 5,
"selected": false,
"text": "<p>Disclaimer: This solution should only be used for data at rest that is not exposed to the public (for example - a configuration file or DB). Only in this scenario, the quick-and-dirty solution can be considered better than @jbtule's solution, due to lower maintanance.</p>\n\n<p>Original post:\nI found <a href=\"https://stackoverflow.com/a/10366194/188474\">jbtule</a>'s answer a bit complicated for a quick and dirty secured AES string encryption and <a href=\"https://stackoverflow.com/a/2791259\">Brett</a>'s answer had a bug with the Initialization Vector being a fixed value making it vulnerable to padding attacks, so I fixed Brett's code and added a random IV that is added to the chipered string, creating a different encrypted value each and every encryption of the same value:</p>\n\n<p>Encryption:</p>\n\n<pre><code>public static string Encrypt(string clearText)\n{ \n byte[] clearBytes = Encoding.Unicode.GetBytes(clearText);\n using (Aes encryptor = Aes.Create())\n {\n byte[] IV = new byte[15];\n rand.NextBytes(IV);\n Rfc2898DeriveBytes pdb = new Rfc2898DeriveBytes(EncryptionKey, IV);\n encryptor.Key = pdb.GetBytes(32);\n encryptor.IV = pdb.GetBytes(16);\n using (MemoryStream ms = new MemoryStream())\n {\n using (CryptoStream cs = new CryptoStream(ms, encryptor.CreateEncryptor(), CryptoStreamMode.Write))\n {\n cs.Write(clearBytes, 0, clearBytes.Length);\n cs.Close();\n }\n clearText = Convert.ToBase64String(IV) + Convert.ToBase64String(ms.ToArray());\n }\n }\n return clearText;\n}\n</code></pre>\n\n<p>Decryption:</p>\n\n<pre><code>public static string Decrypt(string cipherText)\n{\n byte[] IV = Convert.FromBase64String(cipherText.Substring(0, 20));\n cipherText = cipherText.Substring(20).Replace(\" \", \"+\");\n byte[] cipherBytes = Convert.FromBase64String(cipherText);\n using (Aes encryptor = Aes.Create())\n {\n Rfc2898DeriveBytes pdb = new Rfc2898DeriveBytes(EncryptionKey, IV);\n encryptor.Key = pdb.GetBytes(32);\n encryptor.IV = pdb.GetBytes(16);\n using (MemoryStream ms = new MemoryStream())\n {\n using (CryptoStream cs = new CryptoStream(ms, encryptor.CreateDecryptor(), CryptoStreamMode.Write))\n {\n cs.Write(cipherBytes, 0, cipherBytes.Length);\n cs.Close();\n }\n cipherText = Encoding.Unicode.GetString(ms.ToArray());\n }\n }\n return cipherText;\n}\n</code></pre>\n\n<p>Replace EncryptionKey with your key.\nIn my implementation, the key is being saved in the configuration file (web.config\\app.config) as you shouldn't save it hard coded. The configuration file should be <a href=\"https://msdn.microsoft.com/en-us/library/zhhddkxy.aspx\" rel=\"noreferrer\">also encrypted</a> so the key won't be saved as clear text in it.</p>\n\n<pre><code>protected static string _Key = \"\";\nprotected static string EncryptionKey\n{\n get\n {\n if (String.IsNullOrEmpty(_Key))\n {\n _Key = ConfigurationManager.AppSettings[\"AESKey\"].ToString();\n }\n\n return _Key;\n }\n}\n</code></pre>\n"
},
{
"answer_id": 37429667,
"author": "Skull",
"author_id": 5244641,
"author_profile": "https://Stackoverflow.com/users/5244641",
"pm_score": 0,
"selected": false,
"text": "<p>AES Algorithm:</p>\n\n<pre><code>public static class CryptographyProvider\n {\n public static string EncryptString(string plainText, out string Key)\n {\n if (plainText == null || plainText.Length <= 0)\n throw new ArgumentNullException(\"plainText\");\n\n using (Aes _aesAlg = Aes.Create())\n {\n Key = Convert.ToBase64String(_aesAlg.Key);\n ICryptoTransform _encryptor = _aesAlg.CreateEncryptor(_aesAlg.Key, _aesAlg.IV);\n\n using (MemoryStream _memoryStream = new MemoryStream())\n {\n _memoryStream.Write(_aesAlg.IV, 0, 16);\n using (CryptoStream _cryptoStream = new CryptoStream(_memoryStream, _encryptor, CryptoStreamMode.Write))\n {\n using (StreamWriter _streamWriter = new StreamWriter(_cryptoStream))\n {\n _streamWriter.Write(plainText);\n }\n return Convert.ToBase64String(_memoryStream.ToArray());\n }\n }\n }\n }\n public static string DecryptString(string cipherText, string Key)\n {\n\n if (string.IsNullOrEmpty(cipherText))\n throw new ArgumentNullException(\"cipherText\");\n if (string.IsNullOrEmpty(Key))\n throw new ArgumentNullException(\"Key\");\n\n string plaintext = null;\n\n byte[] _initialVector = new byte[16];\n byte[] _Key = Convert.FromBase64String(Key);\n byte[] _cipherTextBytesArray = Convert.FromBase64String(cipherText);\n byte[] _originalString = new byte[_cipherTextBytesArray.Length - 16];\n\n Array.Copy(_cipherTextBytesArray, 0, _initialVector, 0, _initialVector.Length);\n Array.Copy(_cipherTextBytesArray, 16, _originalString, 0, _cipherTextBytesArray.Length - 16);\n\n using (Aes _aesAlg = Aes.Create())\n {\n _aesAlg.Key = _Key;\n _aesAlg.IV = _initialVector;\n ICryptoTransform decryptor = _aesAlg.CreateDecryptor(_aesAlg.Key, _aesAlg.IV);\n\n using (MemoryStream _memoryStream = new MemoryStream(_originalString))\n {\n using (CryptoStream _cryptoStream = new CryptoStream(_memoryStream, decryptor, CryptoStreamMode.Read))\n {\n using (StreamReader _streamReader = new StreamReader(_cryptoStream))\n {\n plaintext = _streamReader.ReadToEnd();\n }\n }\n }\n }\n return plaintext;\n }\n }\n</code></pre>\n"
},
{
"answer_id": 39034489,
"author": "josedbaez",
"author_id": 991459,
"author_profile": "https://Stackoverflow.com/users/991459",
"pm_score": 2,
"selected": false,
"text": "<p>To support <a href=\"https://stackoverflow.com/a/15407665/991459\">mattmanser answer</a>. Here's an example using MachineKey class to encrypt/decrypt URL safe values. </p>\n\n<p>Something to bear in mind, as mentioned before, this will use Machine config settings (<a href=\"https://msdn.microsoft.com/en-us/library/ff649308.aspx\" rel=\"nofollow noreferrer\">https://msdn.microsoft.com/en-us/library/ff649308.aspx</a>). You can set encryption and decryption key/algorithm manually (you might need this specially if your site is running on multiple servers) in web.config file. You can generate keys from IIS (see here: <a href=\"https://blogs.msdn.microsoft.com/vijaysk/2009/05/13/iis-7-tip-10-you-can-generate-machine-keys-from-the-iis-manager/\" rel=\"nofollow noreferrer\">https://blogs.msdn.microsoft.com/vijaysk/2009/05/13/iis-7-tip-10-you-can-generate-machine-keys-from-the-iis-manager/</a>) or can use an online machine key generator like: <a href=\"http://www.developerfusion.com/tools/generatemachinekey/\" rel=\"nofollow noreferrer\">http://www.developerfusion.com/tools/generatemachinekey/</a></p>\n\n<pre><code> private static readonly UTF8Encoding Encoder = new UTF8Encoding();\n\n public static string Encrypt(string unencrypted)\n {\n if (string.IsNullOrEmpty(unencrypted)) \n return string.Empty;\n\n try\n {\n var encryptedBytes = MachineKey.Protect(Encoder.GetBytes(unencrypted));\n\n if (encryptedBytes != null && encryptedBytes.Length > 0)\n return HttpServerUtility.UrlTokenEncode(encryptedBytes); \n }\n catch (Exception)\n {\n return string.Empty;\n }\n\n return string.Empty;\n }\n\n public static string Decrypt(string encrypted)\n {\n if (string.IsNullOrEmpty(encrypted)) \n return string.Empty;\n\n try\n {\n var bytes = HttpServerUtility.UrlTokenDecode(encrypted);\n if (bytes != null && bytes.Length > 0)\n {\n var decryptedBytes = MachineKey.Unprotect(bytes);\n if(decryptedBytes != null && decryptedBytes.Length > 0)\n return Encoder.GetString(decryptedBytes);\n }\n\n }\n catch (Exception)\n {\n return string.Empty;\n }\n\n return string.Empty;\n }\n</code></pre>\n"
},
{
"answer_id": 40258330,
"author": "Ashkan S",
"author_id": 6519111,
"author_profile": "https://Stackoverflow.com/users/6519111",
"pm_score": 2,
"selected": false,
"text": "<p>Encryption is a very common matter in programming. I think it is better to install a package to do the task for you. Maybe a simple open source NuGet project like\n<a href=\"https://github.com/ArtisanCode/SimpleAesEncryption\" rel=\"nofollow noreferrer\">Simple Aes Encryption</a></p>\n<p>The key is in the config file and therefore it is easy to change in the production environment, and I don't see any drawbacks.</p>\n<pre class=\"lang-xml prettyprint-override\"><code><MessageEncryption>\n <EncryptionKey KeySize="256" Key="3q2+796tvu/erb7v3q2+796tvu/erb7v3q2+796tvu8="/>\n</MessageEncryption>\n</code></pre>\n"
},
{
"answer_id": 41474826,
"author": "James McLachlan",
"author_id": 217499,
"author_profile": "https://Stackoverflow.com/users/217499",
"pm_score": 2,
"selected": false,
"text": "<p>An alternative to BouncyCastle for <a href=\"https://bitbeans.gitbooks.io/libsodium-net/content/advanced/aes256_gcm.html\" rel=\"nofollow noreferrer\">AES-GCM</a> encryption is <a href=\"https://github.com/adamcaudill/libsodium-net\" rel=\"nofollow noreferrer\">libsodium-net</a>. It wraps the libsodium C library. One nice advantage is that it uses the AES-NI extension in CPUs for very fast encryption. The down side is that it won't work at all if the CPU doesn't have the extension. There's no software fall back.</p>\n"
},
{
"answer_id": 42043869,
"author": "Rahul Modi",
"author_id": 5669379,
"author_profile": "https://Stackoverflow.com/users/5669379",
"pm_score": 3,
"selected": false,
"text": "<p>With the reference of <a href=\"https://social.msdn.microsoft.com/Forums/vstudio/en-US/d6a2836a-d587-4068-8630-94f4fb2a2aeb/encrypt-and-decrypt-a-string-in-c?forum=csharpgeneral\" rel=\"noreferrer\">Encrypt and Decrypt a String in c#</a>, I found one of good solution :</p>\n\n<pre><code>static readonly string PasswordHash = \"P@@Sw0rd\";\nstatic readonly string SaltKey = \"S@LT&KEY\";\nstatic readonly string VIKey = \"@1B2c3D4e5F6g7H8\";\n</code></pre>\n\n<p>For Encrypt</p>\n\n<pre><code>public static string Encrypt(string plainText)\n{\n byte[] plainTextBytes = Encoding.UTF8.GetBytes(plainText);\n\n byte[] keyBytes = new Rfc2898DeriveBytes(PasswordHash, Encoding.ASCII.GetBytes(SaltKey)).GetBytes(256 / 8);\n var symmetricKey = new RijndaelManaged() { Mode = CipherMode.CBC, Padding = PaddingMode.Zeros };\n var encryptor = symmetricKey.CreateEncryptor(keyBytes, Encoding.ASCII.GetBytes(VIKey));\n\n byte[] cipherTextBytes;\n\n using (var memoryStream = new MemoryStream())\n {\n using (var cryptoStream = new CryptoStream(memoryStream, encryptor, CryptoStreamMode.Write))\n {\n cryptoStream.Write(plainTextBytes, 0, plainTextBytes.Length);\n cryptoStream.FlushFinalBlock();\n cipherTextBytes = memoryStream.ToArray();\n cryptoStream.Close();\n }\n memoryStream.Close();\n }\n return Convert.ToBase64String(cipherTextBytes);\n}\n</code></pre>\n\n<p>For Decrypt</p>\n\n<pre><code>public static string Decrypt(string encryptedText)\n{\n byte[] cipherTextBytes = Convert.FromBase64String(encryptedText);\n byte[] keyBytes = new Rfc2898DeriveBytes(PasswordHash, Encoding.ASCII.GetBytes(SaltKey)).GetBytes(256 / 8);\n var symmetricKey = new RijndaelManaged() { Mode = CipherMode.CBC, Padding = PaddingMode.None };\n\n var decryptor = symmetricKey.CreateDecryptor(keyBytes, Encoding.ASCII.GetBytes(VIKey));\n var memoryStream = new MemoryStream(cipherTextBytes);\n var cryptoStream = new CryptoStream(memoryStream, decryptor, CryptoStreamMode.Read);\n byte[] plainTextBytes = new byte[cipherTextBytes.Length];\n\n int decryptedByteCount = cryptoStream.Read(plainTextBytes, 0, plainTextBytes.Length);\n memoryStream.Close();\n cryptoStream.Close();\n return Encoding.UTF8.GetString(plainTextBytes, 0, decryptedByteCount).TrimEnd(\"\\0\".ToCharArray());\n}\n</code></pre>\n"
},
{
"answer_id": 52748781,
"author": "Davit Tvildiani",
"author_id": 715224,
"author_profile": "https://Stackoverflow.com/users/715224",
"pm_score": 2,
"selected": false,
"text": "<pre><code>using System;\nusing System.IO;\nusing System.Security.Cryptography;\nusing System.Text;\n\npublic class Program\n{\n public static void Main()\n {\n var key = Encoding.UTF8.GetBytes(\"SUkbqO2ycDo7QwpR25kfgmC7f8CoyrZy\");\n var data = Encoding.UTF8.GetBytes(\"testData\");\n\n //Encrypt data\n var encrypted = CryptoHelper.EncryptData(data,key);\n\n //Decrypt data\n var decrypted = CryptoHelper.DecryptData(encrypted,key);\n\n //Display result\n Console.WriteLine(Encoding.UTF8.GetString(decrypted));\n }\n}\n\npublic static class CryptoHelper\n{\n public static byte[] EncryptData(byte[] data, byte[] key)\n {\n using (var aesAlg = Aes.Create())\n {\n aesAlg.Mode = CipherMode.CBC;\n using (var encryptor = aesAlg.CreateEncryptor(key, aesAlg.IV))\n {\n using (var msEncrypt = new MemoryStream())\n {\n msEncrypt.Write(aesAlg.IV, 0, aesAlg.IV.Length);\n\n using (var csEncrypt = new CryptoStream(msEncrypt, encryptor, CryptoStreamMode.Write))\n csEncrypt.Write(data, 0, data.Length);\n\n return msEncrypt.ToArray();\n }\n }\n }\n\n }\n\n public static byte[] DecryptData(byte[] encrypted, byte[] key)\n {\n var iv = new byte[16];\n Buffer.BlockCopy(encrypted, 0, iv, 0, iv.Length);\n using (var aesAlg = Aes.Create())\n {\n aesAlg.Mode = CipherMode.CBC;\n using (var decryptor = aesAlg.CreateDecryptor(key, iv))\n {\n using (var msDecrypt = new MemoryStream(encrypted, iv.Length, encrypted.Length - iv.Length))\n {\n using (var csDecrypt = new CryptoStream(msDecrypt, decryptor, CryptoStreamMode.Read))\n {\n using (var resultStream = new MemoryStream())\n {\n csDecrypt.CopyTo(resultStream);\n return resultStream.ToArray();\n }\n }\n }\n }\n }\n }\n}\n</code></pre>\n"
},
{
"answer_id": 52754623,
"author": "oleksa",
"author_id": 940182,
"author_profile": "https://Stackoverflow.com/users/940182",
"pm_score": 0,
"selected": false,
"text": "<p><a href=\"https://github.com/lukemerrett/Bouncy-Castle-AES-GCM-Encryption/blob/master/Cryptography/EncryptionService.cs\" rel=\"nofollow noreferrer\">Here is the sample</a> how AES-GCM encryption/decryption can be done using Bouncy castle package.</p>\n\n<p>I've found that sample when googled for possibility to decrypt data from GOlang <code>crypto/aes</code> api:</p>\n\n<pre><code>const (\n gcmBlockSize = 16 // this is key size\n gcmTagSize = 16 // this is mac\n gcmStandardNonceSize = 12 // this is nonce\n)\n\nfunc encrypt(data []byte, passphrase string) []byte {\n block, _ := aes.NewCipher([]byte(createHash(passphrase)))\n gcm, err := cipher.NewGCM(block)\n if err != nil {\n panic(err.Error())\n }\n nonce := make([]byte, gcm.NonceSize())\n if _, err = io.ReadFull(rand.Reader, nonce); err != nil {\n panic(err.Error())\n }\n ciphertext := gcm.Seal(nonce, nonce, data, nil)\n return ciphertext\n}\n</code></pre>\n\n<p>.Net sample works like a charm with key (256 bit), mac (128bit) and nonce (96 bit). </p>\n"
},
{
"answer_id": 56023792,
"author": "Kolappan N",
"author_id": 5407188,
"author_profile": "https://Stackoverflow.com/users/5407188",
"pm_score": 2,
"selected": false,
"text": "<p>The following code is an improved version of Ghazal's <a href=\"https://stackoverflow.com/a/27484425/5407188\">answer</a> to a similar <a href=\"https://stackoverflow.com/q/10168240/5407188\">question</a>.</p>\n\n<pre class=\"lang-csharp prettyprint-override\"><code>public class EncryptionHelper\n{\n private Aes aesEncryptor;\n\n public EncryptionHelper()\n {\n }\n\n private void BuildAesEncryptor(string key)\n {\n aesEncryptor = Aes.Create();\n var pdb = new Rfc2898DeriveBytes(key, new byte[] { 0x49, 0x76, 0x61, 0x6e, 0x20, 0x4d, 0x65, 0x64, 0x76, 0x65, 0x64, 0x65, 0x76 });\n aesEncryptor.Key = pdb.GetBytes(32);\n aesEncryptor.IV = pdb.GetBytes(16);\n }\n\n public string EncryptString(string clearText, string key)\n {\n BuildAesEncryptor(key);\n var clearBytes = Encoding.Unicode.GetBytes(clearText);\n using (var ms = new MemoryStream())\n {\n using (var cs = new CryptoStream(ms, aesEncryptor.CreateEncryptor(), CryptoStreamMode.Write))\n {\n cs.Write(clearBytes, 0, clearBytes.Length);\n }\n var encryptedText = Convert.ToBase64String(ms.ToArray());\n return encryptedText;\n }\n }\n\n public string DecryptString(string cipherText, string key)\n {\n BuildAesEncryptor(key);\n cipherText = cipherText.Replace(\" \", \"+\");\n var cipherBytes = Convert.FromBase64String(cipherText);\n using (var ms = new MemoryStream())\n {\n using (var cs = new CryptoStream(ms, aesEncryptor.CreateDecryptor(), CryptoStreamMode.Write))\n {\n cs.Write(cipherBytes, 0, cipherBytes.Length);\n }\n var clearText = Encoding.Unicode.GetString(ms.ToArray());\n return clearText;\n }\n }\n}\n</code></pre>\n"
},
{
"answer_id": 56185068,
"author": "reza.Nikmaram",
"author_id": 1369854,
"author_profile": "https://Stackoverflow.com/users/1369854",
"pm_score": 3,
"selected": false,
"text": "<p>The following example demonstrates how to encrypt and decrypt sample data:</p>\n\n<pre><code> // This constant is used to determine the keysize of the encryption algorithm in bits.\n // We divide this by 8 within the code below to get the equivalent number of bytes.\n private const int Keysize = 128;\n\n // This constant determines the number of iterations for the password bytes generation function.\n private const int DerivationIterations = 1000;\n\n public static string Encrypt(string plainText, string passPhrase)\n {\n // Salt and IV is randomly generated each time, but is preprended to encrypted cipher text\n // so that the same Salt and IV values can be used when decrypting. \n var saltStringBytes = GenerateBitsOfRandomEntropy(16);\n var ivStringBytes = GenerateBitsOfRandomEntropy(16);\n var plainTextBytes = Encoding.UTF8.GetBytes(plainText);\n using (var password = new Rfc2898DeriveBytes(passPhrase, saltStringBytes, DerivationIterations))\n {\n var keyBytes = password.GetBytes(Keysize / 8);\n using (var symmetricKey = new RijndaelManaged())\n {\n symmetricKey.BlockSize = 128;\n symmetricKey.Mode = CipherMode.CBC;\n symmetricKey.Padding = PaddingMode.PKCS7;\n using (var encryptor = symmetricKey.CreateEncryptor(keyBytes, ivStringBytes))\n {\n using (var memoryStream = new MemoryStream())\n {\n using (var cryptoStream = new CryptoStream(memoryStream, encryptor, CryptoStreamMode.Write))\n {\n cryptoStream.Write(plainTextBytes, 0, plainTextBytes.Length);\n cryptoStream.FlushFinalBlock();\n // Create the final bytes as a concatenation of the random salt bytes, the random iv bytes and the cipher bytes.\n var cipherTextBytes = saltStringBytes;\n cipherTextBytes = cipherTextBytes.Concat(ivStringBytes).ToArray();\n cipherTextBytes = cipherTextBytes.Concat(memoryStream.ToArray()).ToArray();\n memoryStream.Close();\n cryptoStream.Close();\n return Convert.ToBase64String(cipherTextBytes);\n }\n }\n }\n }\n }\n }\n\n public static string Decrypt(string cipherText, string passPhrase)\n {\n // Get the complete stream of bytes that represent:\n // [32 bytes of Salt] + [32 bytes of IV] + [n bytes of CipherText]\n var cipherTextBytesWithSaltAndIv = Convert.FromBase64String(cipherText);\n // Get the saltbytes by extracting the first 32 bytes from the supplied cipherText bytes.\n var saltStringBytes = cipherTextBytesWithSaltAndIv.Take(Keysize / 8).ToArray();\n // Get the IV bytes by extracting the next 32 bytes from the supplied cipherText bytes.\n var ivStringBytes = cipherTextBytesWithSaltAndIv.Skip(Keysize / 8).Take(Keysize / 8).ToArray();\n // Get the actual cipher text bytes by removing the first 64 bytes from the cipherText string.\n var cipherTextBytes = cipherTextBytesWithSaltAndIv.Skip((Keysize / 8) * 2).Take(cipherTextBytesWithSaltAndIv.Length - ((Keysize / 8) * 2)).ToArray();\n\n using (var password = new Rfc2898DeriveBytes(passPhrase, saltStringBytes, DerivationIterations))\n {\n var keyBytes = password.GetBytes(Keysize / 8);\n using (var symmetricKey = new RijndaelManaged())\n {\n symmetricKey.BlockSize = 128;\n symmetricKey.Mode = CipherMode.CBC;\n symmetricKey.Padding = PaddingMode.PKCS7;\n using (var decryptor = symmetricKey.CreateDecryptor(keyBytes, ivStringBytes))\n {\n using (var memoryStream = new MemoryStream(cipherTextBytes))\n {\n using (var cryptoStream = new CryptoStream(memoryStream, decryptor, CryptoStreamMode.Read))\n {\n var plainTextBytes = new byte[cipherTextBytes.Length];\n var decryptedByteCount = cryptoStream.Read(plainTextBytes, 0, plainTextBytes.Length);\n memoryStream.Close();\n cryptoStream.Close();\n return Encoding.UTF8.GetString(plainTextBytes, 0, decryptedByteCount);\n }\n }\n }\n }\n }\n }\n\n private static byte[] GenerateBitsOfRandomEntropy(int size)\n {\n // 32 Bytes will give us 256 bits.\n // 16 Bytes will give us 128 bits.\n var randomBytes = new byte[size]; \n using (var rngCsp = new RNGCryptoServiceProvider())\n {\n // Fill the array with cryptographically secure random bytes.\n rngCsp.GetBytes(randomBytes);\n }\n return randomBytes;\n }\n</code></pre>\n"
},
{
"answer_id": 56424902,
"author": "Code",
"author_id": 9787173,
"author_profile": "https://Stackoverflow.com/users/9787173",
"pm_score": 1,
"selected": false,
"text": "<pre><code>using System;\nusing System.Collections.Generic;\nusing System.Linq;\nusing System.Web;\nusing System.Security.Cryptography;\nusing System.IO;\nusing System.Text; \n\n/// <summary>\n/// Summary description for Encryption\n/// </summary>\npublic class Encryption\n{\n public TripleDES CreateDES(string key)\n {\n MD5 md5 = new MD5CryptoServiceProvider();\n TripleDES des = new TripleDESCryptoServiceProvider();\n des.Key = md5.ComputeHash(Encoding.Unicode.GetBytes(key));\n des.IV = new byte[des.BlockSize / 8];\n return des;\n }\n public byte[] Encryptiondata(string PlainText)\n {\n TripleDES des = CreateDES(\"DreamMLMKey\");\n ICryptoTransform ct = des.CreateEncryptor();\n byte[] input = Encoding.Unicode.GetBytes(PlainText);\n return ct.TransformFinalBlock(input, 0, input.Length);\n }\n\n public string Decryptiondata(string CypherText)\n {\n string stringToDecrypt = CypherText.Replace(\" \", \"+\");\n int len = stringToDecrypt.Length;\n byte[] inputByteArray = Convert.FromBase64String(stringToDecrypt); \n\n byte[] b = Convert.FromBase64String(CypherText);\n TripleDES des = CreateDES(\"DreamMLMKey\");\n ICryptoTransform ct = des.CreateDecryptor();\n byte[] output = ct.TransformFinalBlock(b, 0, b.Length);\n return Encoding.Unicode.GetString(output);\n }\n public string Decryptiondataurl(string CypherText)\n {\n string newcyperttext=CypherText.Replace(' ', '+');\n byte[] b = Convert.FromBase64String(newcyperttext);\n TripleDES des = CreateDES(\"DreamMLMKey\");\n ICryptoTransform ct = des.CreateDecryptor();\n byte[] output = ct.TransformFinalBlock(b, 0, b.Length);\n return Encoding.Unicode.GetString(output);\n }\n\n\n #region encryption & Decription\n public string Encrypt(string input, string key)\n {\n byte[] inputArray = UTF8Encoding.UTF8.GetBytes(input);\n TripleDESCryptoServiceProvider tripleDES = new TripleDESCryptoServiceProvider();\n tripleDES.Key = UTF8Encoding.UTF8.GetBytes(key);\n tripleDES.Mode = CipherMode.ECB;\n tripleDES.Padding = PaddingMode.PKCS7;\n ICryptoTransform cTransform = tripleDES.CreateEncryptor();\n byte[] resultArray = cTransform.TransformFinalBlock(inputArray, 0, inputArray.Length);\n tripleDES.Clear();\n return Convert.ToBase64String(resultArray, 0, resultArray.Length);\n }\n public string Decrypt(string input, string key)\n {\n byte[] inputArray = Convert.FromBase64String(input);\n TripleDESCryptoServiceProvider tripleDES = new TripleDESCryptoServiceProvider();\n tripleDES.Key = UTF8Encoding.UTF8.GetBytes(key);\n tripleDES.Mode = CipherMode.ECB;\n tripleDES.Padding = PaddingMode.PKCS7;\n ICryptoTransform cTransform = tripleDES.CreateDecryptor();\n byte[] resultArray = cTransform.TransformFinalBlock(inputArray, 0, inputArray.Length);\n tripleDES.Clear();\n return UTF8Encoding.UTF8.GetString(resultArray);\n }\n\n public string encrypt(string encryptString)\n {\n string EncryptionKey = \"0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ\";\n byte[] clearBytes = Encoding.Unicode.GetBytes(encryptString);\n using (Aes encryptor = Aes.Create())\n {\n Rfc2898DeriveBytes pdb = new Rfc2898DeriveBytes(EncryptionKey, new byte[] {\n 0x49, 0x76, 0x61, 0x6e, 0x20, 0x4d, 0x65, 0x64, 0x76, 0x65, 0x64, 0x65, 0x76\n });\n encryptor.Key = pdb.GetBytes(32);\n encryptor.IV = pdb.GetBytes(16);\n using (MemoryStream ms = new MemoryStream())\n {\n using (CryptoStream cs = new CryptoStream(ms, encryptor.CreateEncryptor(), CryptoStreamMode.Write))\n {\n cs.Write(clearBytes, 0, clearBytes.Length);\n cs.Close();\n }\n encryptString = Convert.ToBase64String(ms.ToArray());\n }\n }\n return encryptString;\n }\n\n public string Decrypt(string cipherText)\n {\n string EncryptionKey = \"0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ\";\n cipherText = cipherText.Replace(\" \", \"+\");\n byte[] cipherBytes = Convert.FromBase64String(cipherText);\n using (Aes encryptor = Aes.Create())\n {\n Rfc2898DeriveBytes pdb = new Rfc2898DeriveBytes(EncryptionKey, new byte[] {\n 0x49, 0x76, 0x61, 0x6e, 0x20, 0x4d, 0x65, 0x64, 0x76, 0x65, 0x64, 0x65, 0x76\n });\n encryptor.Key = pdb.GetBytes(32);\n encryptor.IV = pdb.GetBytes(16);\n using (MemoryStream ms = new MemoryStream())\n {\n using (CryptoStream cs = new CryptoStream(ms, encryptor.CreateDecryptor(), CryptoStreamMode.Write))\n {\n cs.Write(cipherBytes, 0, cipherBytes.Length);\n cs.Close();\n }\n cipherText = Encoding.Unicode.GetString(ms.ToArray());\n }\n }\n return cipherText;\n }\n\n #endregion\n}\n</code></pre>\n"
},
{
"answer_id": 58418522,
"author": "Wieslaw Olborski",
"author_id": 3098913,
"author_profile": "https://Stackoverflow.com/users/3098913",
"pm_score": 2,
"selected": false,
"text": "<p>Good example how to do this using <a href=\"https://www.nuget.org/packages/PgpCore/1.2.0\" rel=\"nofollow noreferrer\">PGPCore</a> with BouncyCastle, very simple solution: <a href=\"https://blog.bitscry.com/2018/07/05/pgp-encryption-and-decryption-in-c/\" rel=\"nofollow noreferrer\">https://blog.bitscry.com/2018/07/05/pgp-encryption-and-decryption-in-c/</a></p>\n\n<p>I tried different solutions but this works best for me, some have bugs but this is perfect for me.</p>\n\n<pre><code>using (PGP pgp = new PGP())\n{\n// Generate keys\npgp.GenerateKey(@\"C:\\TEMP\\keys\\public.asc\", @\"C:\\TEMP\\keys\\private.asc\", \"[email protected]\", \"password\");\n// Encrypt file\npgp.EncryptFile(@\"C:\\TEMP\\keys\\content.txt\", @\"C:\\TEMP\\keys\\content__encrypted.pgp\", @\"C:\\TEMP\\keys\\public.asc\", true, true);\n// Encrypt and sign file\npgp.EncryptFileAndSign(@\"C:\\TEMP\\keys\\content.txt\", @\"C:\\TEMP\\keys\\content__encrypted_signed.pgp\", @\"C:\\TEMP\\keys\\public.asc\", @\"C:\\TEMP\\keys\\private.asc\", \"password\", true, true);\n// Decrypt file\npgp.DecryptFile(@\"C:\\TEMP\\keys\\content__encrypted.pgp\", @\"C:\\TEMP\\keys\\content__decrypted.txt\", @\"C:\\TEMP\\keys\\private.asc\", \"password\");\n// Decrypt signed file\npgp.DecryptFile(@\"C:\\TEMP\\keys\\content__encrypted_signed.pgp\", @\"C:\\TEMP\\keys\\content__decrypted_signed.txt\", @\"C:\\TEMP\\keys\\private.asc\", \"password\");\n\n// Encrypt stream\nusing (FileStream inputFileStream = new FileStream(@\"C:\\TEMP\\keys\\content.txt\", FileMode.Open))\nusing (Stream outputFileStream = File.Create(@\"C:\\TEMP\\keys\\content__encrypted2.pgp\"))\nusing (Stream publicKeyStream = new FileStream(@\"C:\\TEMP\\keys\\public.asc\", FileMode.Open))\n pgp.EncryptStream(inputFileStream, outputFileStream, publicKeyStream, true, true);\n\n// Decrypt stream\nusing (FileStream inputFileStream = new FileStream(@\"C:\\TEMP\\keys\\content__encrypted2.pgp\", FileMode.Open))\nusing (Stream outputFileStream = File.Create(@\"C:\\TEMP\\keys\\content__decrypted2.txt\"))\nusing (Stream privateKeyStream = new FileStream(@\"C:\\TEMP\\keys\\private.asc\", FileMode.Open))\n pgp.DecryptStream(inputFileStream, outputFileStream, privateKeyStream, \"password\");\n}\n</code></pre>\n"
},
{
"answer_id": 62546530,
"author": "Mike Bruno",
"author_id": 4664256,
"author_profile": "https://Stackoverflow.com/users/4664256",
"pm_score": 0,
"selected": false,
"text": "<p>I have an open source project called <a href=\"http://www.x509crypto.org\" rel=\"nofollow noreferrer\">X509Crypto</a> that leverages certificates to encrypt and decrypt strings. It's very easy to use. Here is an example for how to use it:</p>\n<p><strong>1. Use the <a href=\"https://github.com/MikeBrunoCISSP/x509Crypto/tree/master/zip\" rel=\"nofollow noreferrer\">X509Crypto Commandline Interface</a> (CLI) to generate a new encryption certificate and key pair</strong></p>\n<pre><code>>x509crypto.exe\nX509Crypto> makecert -context user -keysize medium -alias myvault\n\nCertificate with thumbprint B31FE7E7AE5229F8186782742CF579197FA859FD was added to X509Alias "myvault" in the user X509Context\n\nX509Crypto>\n</code></pre>\n<p><strong>2. Use the <strong>Encrypt</strong> CLI command to add a secret to your new X509Alias</strong></p>\n<pre><code>X509Crypto> encrypt -text -alias myvault -context user -secret apikey -in "80EAF03248965AC2B78090"\n\nSecret apikey has been added to X509Alias myvault in the user X509Context\n\nX509Crypto>\n</code></pre>\n<p><strong>3. Reference the secret in your program</strong></p>\n<p>Once you have an <em>X509Alias</em> established with your secret(s) added, it is trivial to retreive them in your program with the Org.X509Crypto nuget package installed:</p>\n<pre><code>using Org.X509Crypto;\n\nnamespace SampleApp\n{\n class Program\n {\n static void Main(string[] args)\n {\n var Alias = new X509Alias(@"myvault", X509Context.UserReadOnly);\n var apiKey = Alias.RecoverSecret(@"apikey");\n }\n }\n}\n</code></pre>\n"
}
] |
2008/10/14
|
[
"https://Stackoverflow.com/questions/202011",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3291/"
] |
How can I encrypt and decrypt a string in C#?
|
**EDIT 2013-Oct**: Although I've edited this answer over time to address shortcomings, please see [jbtule's answer](https://stackoverflow.com/a/10366194/157247) for a more robust, informed solution.
<https://stackoverflow.com/a/10366194/188474>
**Original Answer:**
Here's a working example derived from the ["RijndaelManaged Class" documentation](http://msdn.microsoft.com/en-us/library/system.security.cryptography.rijndaelmanaged%28v=VS.90%29.aspx) and the [MCTS Training Kit](https://rads.stackoverflow.com/amzn/click/com/0735626197).
**EDIT 2012-April**: This answer was edited to pre-pend the IV per jbtule's suggestion and as illustrated here:
<http://msdn.microsoft.com/en-us/library/system.security.cryptography.aesmanaged%28v=vs.95%29.aspx>
Good luck!
```
public class Crypto
{
//While an app specific salt is not the best practice for
//password based encryption, it's probably safe enough as long as
//it is truly uncommon. Also too much work to alter this answer otherwise.
private static byte[] _salt = __To_Do__("Add a app specific salt here");
/// <summary>
/// Encrypt the given string using AES. The string can be decrypted using
/// DecryptStringAES(). The sharedSecret parameters must match.
/// </summary>
/// <param name="plainText">The text to encrypt.</param>
/// <param name="sharedSecret">A password used to generate a key for encryption.</param>
public static string EncryptStringAES(string plainText, string sharedSecret)
{
if (string.IsNullOrEmpty(plainText))
throw new ArgumentNullException("plainText");
if (string.IsNullOrEmpty(sharedSecret))
throw new ArgumentNullException("sharedSecret");
string outStr = null; // Encrypted string to return
RijndaelManaged aesAlg = null; // RijndaelManaged object used to encrypt the data.
try
{
// generate the key from the shared secret and the salt
Rfc2898DeriveBytes key = new Rfc2898DeriveBytes(sharedSecret, _salt);
// Create a RijndaelManaged object
aesAlg = new RijndaelManaged();
aesAlg.Key = key.GetBytes(aesAlg.KeySize / 8);
// Create a decryptor to perform the stream transform.
ICryptoTransform encryptor = aesAlg.CreateEncryptor(aesAlg.Key, aesAlg.IV);
// Create the streams used for encryption.
using (MemoryStream msEncrypt = new MemoryStream())
{
// prepend the IV
msEncrypt.Write(BitConverter.GetBytes(aesAlg.IV.Length), 0, sizeof(int));
msEncrypt.Write(aesAlg.IV, 0, aesAlg.IV.Length);
using (CryptoStream csEncrypt = new CryptoStream(msEncrypt, encryptor, CryptoStreamMode.Write))
{
using (StreamWriter swEncrypt = new StreamWriter(csEncrypt))
{
//Write all data to the stream.
swEncrypt.Write(plainText);
}
}
outStr = Convert.ToBase64String(msEncrypt.ToArray());
}
}
finally
{
// Clear the RijndaelManaged object.
if (aesAlg != null)
aesAlg.Clear();
}
// Return the encrypted bytes from the memory stream.
return outStr;
}
/// <summary>
/// Decrypt the given string. Assumes the string was encrypted using
/// EncryptStringAES(), using an identical sharedSecret.
/// </summary>
/// <param name="cipherText">The text to decrypt.</param>
/// <param name="sharedSecret">A password used to generate a key for decryption.</param>
public static string DecryptStringAES(string cipherText, string sharedSecret)
{
if (string.IsNullOrEmpty(cipherText))
throw new ArgumentNullException("cipherText");
if (string.IsNullOrEmpty(sharedSecret))
throw new ArgumentNullException("sharedSecret");
// Declare the RijndaelManaged object
// used to decrypt the data.
RijndaelManaged aesAlg = null;
// Declare the string used to hold
// the decrypted text.
string plaintext = null;
try
{
// generate the key from the shared secret and the salt
Rfc2898DeriveBytes key = new Rfc2898DeriveBytes(sharedSecret, _salt);
// Create the streams used for decryption.
byte[] bytes = Convert.FromBase64String(cipherText);
using (MemoryStream msDecrypt = new MemoryStream(bytes))
{
// Create a RijndaelManaged object
// with the specified key and IV.
aesAlg = new RijndaelManaged();
aesAlg.Key = key.GetBytes(aesAlg.KeySize / 8);
// Get the initialization vector from the encrypted stream
aesAlg.IV = ReadByteArray(msDecrypt);
// Create a decrytor to perform the stream transform.
ICryptoTransform decryptor = aesAlg.CreateDecryptor(aesAlg.Key, aesAlg.IV);
using (CryptoStream csDecrypt = new CryptoStream(msDecrypt, decryptor, CryptoStreamMode.Read))
{
using (StreamReader srDecrypt = new StreamReader(csDecrypt))
// Read the decrypted bytes from the decrypting stream
// and place them in a string.
plaintext = srDecrypt.ReadToEnd();
}
}
}
finally
{
// Clear the RijndaelManaged object.
if (aesAlg != null)
aesAlg.Clear();
}
return plaintext;
}
private static byte[] ReadByteArray(Stream s)
{
byte[] rawLength = new byte[sizeof(int)];
if (s.Read(rawLength, 0, rawLength.Length) != rawLength.Length)
{
throw new SystemException("Stream did not contain properly formatted byte array");
}
byte[] buffer = new byte[BitConverter.ToInt32(rawLength, 0)];
if (s.Read(buffer, 0, buffer.Length) != buffer.Length)
{
throw new SystemException("Did not read byte array properly");
}
return buffer;
}
}
```
|
202,013 |
<p>The Winform application is release with ClickOnce in our Intranet. We store personal preference for the GUI in the Isolated Storage. All works pretty fine :)</p>
<p>The problem is when we have a new version of the application, we publish... all preferences are lost! User need to setup their preference over and over each version.</p>
<p>Is there a way to freeze the isolation for the whole application instead of the version?</p>
|
[
{
"answer_id": 202028,
"author": "Gulzar Nazim",
"author_id": 4337,
"author_profile": "https://Stackoverflow.com/users/4337",
"pm_score": 1,
"selected": false,
"text": "<p>You have to store a permanent version of user settings in a more durable store like database. Your application can decide to use the isolated storage if it is available. If it is not available (because of a newer version), the app should get the settings from database and use it to re-initialize the settings in isolated storage. If settings are changed, you should update both places. Unless there is a newer version of the app, your app should not have to get the settings from DB.</p>\n"
},
{
"answer_id": 202071,
"author": "liggett78",
"author_id": 19762,
"author_profile": "https://Stackoverflow.com/users/19762",
"pm_score": 2,
"selected": false,
"text": "<p>I was working on a ClickOnce app a while ago and used Environment.GetFolderPath(ApplicationData) - e.g. roaming app data folder, to store all settings. Worked fine and survived numerous updates. Just create a subdireectory with the name of your app or CompanyName/AppName or whatever and store everything in there.</p>\n"
},
{
"answer_id": 227218,
"author": "codeConcussion",
"author_id": 1321,
"author_profile": "https://Stackoverflow.com/users/1321",
"pm_score": 5,
"selected": true,
"text": "<p>You need to use <em>application</em> scoped, rather than <em>domain</em> scoped, isolated storage. This can be done by using one of <strong>IsolatedStorageFileStream's</strong> overloaded constructors.</p>\n\n<p>Example:</p>\n\n<pre><code>using System.IO;\nusing System.IO.IsolatedStorage;\n...\n\nIsolatedStorageFile appScope = IsolatedStorageFile.GetUserStoreForApplication(); \nusing(IsolatedStorageFileStream fs = new IsolatedStorageFileStream(\"data.dat\", FileMode.OpenOrCreate, appScope))\n{\n...\n</code></pre>\n\n<p>However, now you will run into the issue of this code only working when the application has been launched via ClickOnce because that's the only time application scoped isolated storage is available. If you don't launch via ClickOnce (such as through Visual Studio), <strong>GetUserStoreForApplication()</strong> will throw an exception.</p>\n\n<p>The way around <em>this</em> problem is to make sure <strong>AppDomain.CurrentDomain.ActivationContext</strong> is not null before trying to use application scoped isolated storage.</p>\n"
},
{
"answer_id": 47694201,
"author": "Florjon",
"author_id": 86653,
"author_profile": "https://Stackoverflow.com/users/86653",
"pm_score": 2,
"selected": false,
"text": "<p>a summary from the other answers:</p>\n\n<pre><code>IsolatedStorageFile isolatedStorage = IsolatedStorageFile.GetUserStoreForAssembly();//for visual studio\nif (System.Deployment.Application.ApplicationDeployment.IsNetworkDeployed)\n{\n isolatedStorage = IsolatedStorageFile.GetUserStoreForApplication();//for click once applications\n}\n</code></pre>\n"
}
] |
2008/10/14
|
[
"https://Stackoverflow.com/questions/202013",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/13913/"
] |
The Winform application is release with ClickOnce in our Intranet. We store personal preference for the GUI in the Isolated Storage. All works pretty fine :)
The problem is when we have a new version of the application, we publish... all preferences are lost! User need to setup their preference over and over each version.
Is there a way to freeze the isolation for the whole application instead of the version?
|
You need to use *application* scoped, rather than *domain* scoped, isolated storage. This can be done by using one of **IsolatedStorageFileStream's** overloaded constructors.
Example:
```
using System.IO;
using System.IO.IsolatedStorage;
...
IsolatedStorageFile appScope = IsolatedStorageFile.GetUserStoreForApplication();
using(IsolatedStorageFileStream fs = new IsolatedStorageFileStream("data.dat", FileMode.OpenOrCreate, appScope))
{
...
```
However, now you will run into the issue of this code only working when the application has been launched via ClickOnce because that's the only time application scoped isolated storage is available. If you don't launch via ClickOnce (such as through Visual Studio), **GetUserStoreForApplication()** will throw an exception.
The way around *this* problem is to make sure **AppDomain.CurrentDomain.ActivationContext** is not null before trying to use application scoped isolated storage.
|
202,060 |
<p>I have a page where search resuts are shown both in a grid and on a map (using KML generated on the fly, overlaid on an embedded Google map). I've wired this up to work as the user types; here's the skeleton of my code, which works:</p>
<pre><code>$(function() {
// Wire up search textbox
$('input.Search').bind("keyup", update);
});
update = function(e) {
// Get text from search box
// Pass to web method and bind to concessions grid
$.ajax({
...
success: function(msg) {
displayResults(msg, filterParams);
},
});
}
displayResults = function(msg, filterParams) {
// Databind results grid using jTemplates
// Show results on map: Pass parameters to KML generator and overlay on map
}
</code></pre>
<p>Depending on the search, there may be hundreds of results; and so the work that happens in <code>displayResults</code> is processor-intensive both on the server (querying the database, building and simplifying the KML on the fly) and on the client (databinding the results grid, overlaying big KML files on the map). </p>
<p>I like the immediacy of getting progressively narrower results as I type, but I'd like to minimize the number of times this refreshes. What's the simplest way to introduce an N-second delay after the user stops typing, before running the <code>update</code> function?</p>
|
[
{
"answer_id": 202077,
"author": "Guido",
"author_id": 12388,
"author_profile": "https://Stackoverflow.com/users/12388",
"pm_score": 0,
"selected": false,
"text": "<p>As a first approach, what about something like :</p>\n\n<pre><code>$('input.Search').bind(\"keyup\", function() { setTimeout(update, 5) } );\n</code></pre>\n\n<p>(not sure about the exact setTimeout syntax).</p>\n\n<p>You can also keep a variable to track whether the timeout has already been scheduled or not.</p>\n"
},
{
"answer_id": 202088,
"author": "Mohamed Faramawi",
"author_id": 20006,
"author_profile": "https://Stackoverflow.com/users/20006",
"pm_score": 0,
"selected": false,
"text": "<p>You can use Window.SetTimeOut(YourRefreshMethod) , when the YourRefereshMethod gets called, it will check number of characters being typed so far , and compare it to the some counter, the counter will starts with 0 value, so the initial call will do nothing other than updating the counter with the current characters typed count, the second time your method get called , it will check the number of characters typed, if it matches the previous number recorded by the counter , then it means the user didn't type anything new and you can fire your Refresh method, otherwise you will update the counter value</p>\n"
},
{
"answer_id": 202093,
"author": "Ates Goral",
"author_id": 23501,
"author_profile": "https://Stackoverflow.com/users/23501",
"pm_score": 3,
"selected": true,
"text": "<p>Instead of calling <code>update()</code> directly, call a wrapper that checks to see if there are any pending delayed updates:</p>\n\n<pre><code>$('input.Search').bind(\"keyup\", delayedUpdate);\n\nfunction delayedUpdate() {\n if (updatePending) {\n clearTimeout(updatePending);\n }\n\n updatePending = setTimeout(update, 250);\n}\n\nfunction update() {\n updatePending = false;\n\n //$.ajax(...\n}\n</code></pre>\n\n<p>You should also probably add:</p>\n\n<pre><code>$('input.Search').bind(\"blur\", update);\n</code></pre>\n\n<p>This will do an immediate update when the user leaves the field. But make sure you also add handling for the case where the user leaves the field while there's a pending delayed update (cancel the delayed update first).</p>\n"
}
] |
2008/10/14
|
[
"https://Stackoverflow.com/questions/202060",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/239663/"
] |
I have a page where search resuts are shown both in a grid and on a map (using KML generated on the fly, overlaid on an embedded Google map). I've wired this up to work as the user types; here's the skeleton of my code, which works:
```
$(function() {
// Wire up search textbox
$('input.Search').bind("keyup", update);
});
update = function(e) {
// Get text from search box
// Pass to web method and bind to concessions grid
$.ajax({
...
success: function(msg) {
displayResults(msg, filterParams);
},
});
}
displayResults = function(msg, filterParams) {
// Databind results grid using jTemplates
// Show results on map: Pass parameters to KML generator and overlay on map
}
```
Depending on the search, there may be hundreds of results; and so the work that happens in `displayResults` is processor-intensive both on the server (querying the database, building and simplifying the KML on the fly) and on the client (databinding the results grid, overlaying big KML files on the map).
I like the immediacy of getting progressively narrower results as I type, but I'd like to minimize the number of times this refreshes. What's the simplest way to introduce an N-second delay after the user stops typing, before running the `update` function?
|
Instead of calling `update()` directly, call a wrapper that checks to see if there are any pending delayed updates:
```
$('input.Search').bind("keyup", delayedUpdate);
function delayedUpdate() {
if (updatePending) {
clearTimeout(updatePending);
}
updatePending = setTimeout(update, 250);
}
function update() {
updatePending = false;
//$.ajax(...
}
```
You should also probably add:
```
$('input.Search').bind("blur", update);
```
This will do an immediate update when the user leaves the field. But make sure you also add handling for the case where the user leaves the field while there's a pending delayed update (cancel the delayed update first).
|
202,073 |
<p>I want to get a type of a "BasePage" object that I am creating. Every Page object is based off BasePage. For instance, I have a Login.aspx and in my code-behind and a class that has a method Display:</p>
<pre><code>Display(BasePage page) {
ResourceManager manager = new ResourceManager(page.GetType());
}
</code></pre>
<p>In my project structure I have a default resource file and a psuedo-translation resource file. If I set try something like this:</p>
<pre><code>Display(BasePage page) {
ResourceManager manager = new ResourceManager(typeof(Login));
}
</code></pre>
<p>it returns the translated page. After some research I found that page.GetType().ToString() returned something to the effect of "ASP_login.aspx" How can I get the actual code behind class type, such that I get an object of type "Login" that is derived from "BasePage"? </p>
<p>Thanks in advance!</p>
|
[
{
"answer_id": 202095,
"author": "chadmyers",
"author_id": 10862,
"author_profile": "https://Stackoverflow.com/users/10862",
"pm_score": 0,
"selected": false,
"text": "<p>It depends where you're calling Display() from. If you're calling it from the ASPX, then you'llse \"ASP_login.aspx\". If you're calling it from the code-behind (i.e. the Page_Load() method) you should get the Login page type.</p>\n\n<p>Instead of passing the Page in, you might consider just using the Page property (i.e. this.Page.GetType()) which should always be the current page/codebehind type, if I recall correctly.</p>\n\n<p>I should also make the point that you might consider moving this sort of stuff out of the ASPX/codebehind and into some sort of service. It's generally a good idea to minimize the amount of things you do in a code behind and, instead, push logic into a presenter class and follow the MVP pattern for ASP.NET Web Forms development.</p>\n"
},
{
"answer_id": 202099,
"author": "Mark Cidade",
"author_id": 1659,
"author_profile": "https://Stackoverflow.com/users/1659",
"pm_score": 4,
"selected": true,
"text": "<p>If your code-beside looks like this:</p>\n\n<pre><code>public partial class _Login : BasePage \n { /* ... */ \n }\n</code></pre>\n\n<p>Then you would get the <code>Type</code> object for it with <em><code>typeof(_Login)</code></em>. To get the type dynamically, you can find it recursively:</p>\n\n<pre><code>Type GetCodeBehindType()\n { return getCodeBehindTypeRecursive(this.GetType());\n }\n\nType getCodeBehindTypeRecursive(Type t)\n { var baseType = t.BaseType;\n if (baseType == typeof(BasePage)) return t;\n else return getCodeBehindTypeRecursive(baseType);\n }\n</code></pre>\n"
},
{
"answer_id": 202155,
"author": "Adam Driscoll",
"author_id": 13688,
"author_profile": "https://Stackoverflow.com/users/13688",
"pm_score": 2,
"selected": false,
"text": "<p>After some additional research I found that if I call Page.GetType().BaseType it returns the code-behind type of the Aspx page. </p>\n"
},
{
"answer_id": 202228,
"author": "Guvante",
"author_id": 16800,
"author_profile": "https://Stackoverflow.com/users/16800",
"pm_score": 1,
"selected": false,
"text": "<p>page.GetType().BaseType, it has been said before, but let me elaborate as to why.</p>\n\n<p>Aspx pages inherit from their code-behind pages, meaning that the inheritance hierarchy looks like this:</p>\n\n<pre><code>...\nPage\nBasePage\nLogin\nASP_Login\n</code></pre>\n\n<p>Where the top is the parent and the bottom is the child.</p>\n\n<p>This allows your code behind to be accessible from the aspx page, without requiring all of the generated code related to your actual aspx page to be copied into the base class page.</p>\n"
}
] |
2008/10/14
|
[
"https://Stackoverflow.com/questions/202073",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/13688/"
] |
I want to get a type of a "BasePage" object that I am creating. Every Page object is based off BasePage. For instance, I have a Login.aspx and in my code-behind and a class that has a method Display:
```
Display(BasePage page) {
ResourceManager manager = new ResourceManager(page.GetType());
}
```
In my project structure I have a default resource file and a psuedo-translation resource file. If I set try something like this:
```
Display(BasePage page) {
ResourceManager manager = new ResourceManager(typeof(Login));
}
```
it returns the translated page. After some research I found that page.GetType().ToString() returned something to the effect of "ASP\_login.aspx" How can I get the actual code behind class type, such that I get an object of type "Login" that is derived from "BasePage"?
Thanks in advance!
|
If your code-beside looks like this:
```
public partial class _Login : BasePage
{ /* ... */
}
```
Then you would get the `Type` object for it with *`typeof(_Login)`*. To get the type dynamically, you can find it recursively:
```
Type GetCodeBehindType()
{ return getCodeBehindTypeRecursive(this.GetType());
}
Type getCodeBehindTypeRecursive(Type t)
{ var baseType = t.BaseType;
if (baseType == typeof(BasePage)) return t;
else return getCodeBehindTypeRecursive(baseType);
}
```
|
202,084 |
<p>Cells in DataGridViewComboBoxColumn have ComboBoxStyle DropDownList. It means the user can only select values from the dropdown. The underlying control is ComboBox, so it can have style DropDown. How do I change the style of the underlying combo box in DataGridViewComboBoxColumn. Or, more general, can I have a column in DataGridView with dropdown where user can type?</p>
|
[
{
"answer_id": 202478,
"author": "Aleris",
"author_id": 20417,
"author_profile": "https://Stackoverflow.com/users/20417",
"pm_score": 3,
"selected": false,
"text": "<pre><code>void dataGridView1_EditingControlShowing(object sender, \n DataGridViewEditingControlShowingEventArgs e)\n{\n if (e.Control.GetType() == typeof(DataGridViewComboBoxEditingControl))\n {\n DataGridViewComboBoxEditingControl cbo = \n e.Control as DataGridViewComboBoxEditingControl;\n cbo.DropDownStyle = ComboBoxStyle.DropDown;\n }\n}\n</code></pre>\n\n<p><a href=\"http://forums.microsoft.com/MSDN/ShowPost.aspx?PostID=13855&SiteID=1\" rel=\"nofollow noreferrer\">Problem with combobox and databound datagridview</a></p>\n"
},
{
"answer_id": 203491,
"author": "chgman",
"author_id": 14727,
"author_profile": "https://Stackoverflow.com/users/14727",
"pm_score": 2,
"selected": false,
"text": "<p>Following solution works for me</p>\n\n<pre><code>private void dataGridView1_CellValidating(object sender, \n DataGridViewCellValidatingEventArgs e) \n{\n if (e.ColumnIndex == Column1.Index) \n {\n // Add the value to column's Items to pass validation\n if (!Column1.Items.Contains(e.FormattedValue.ToString())) \n {\n Column1.Items.Add(e.FormattedValue);\n dataGridView1.Rows[e.RowIndex].Cells[e.ColumnIndex].Value = \n e.FormattedValue;\n }\n }\n}\n\nprivate void dataGridView1_EditingControlShowing(object sender, \n DataGridViewEditingControlShowingEventArgs e) \n{\n if (dataGridView1.CurrentCell.ColumnIndex == Column1.Index) \n {\n ComboBox cb = (ComboBox)e.Control;\n if (cb != null) \n {\n cb.Items.Clear();\n // Customize content of the dropdown list\n cb.Items.AddRange(appropriateCollectionOfStrings);\n cb.DropDownStyle = ComboBoxStyle.DropDown;\n }\n }\n}\n</code></pre>\n"
},
{
"answer_id": 6867121,
"author": "Jamie Pate",
"author_id": 193232,
"author_profile": "https://Stackoverflow.com/users/193232",
"pm_score": 1,
"selected": false,
"text": "<pre><code>if (!Column1.Items.Contains(e.FormattedValue.ToString())) { \n Column1.Items.Add(e.FormattedValue); \n dataGridView1.Rows[e.RowIndex].Cells[e.ColumnIndex].Value = e.FormattedValue; \n} \n</code></pre>\n\n<p>may always return true because \n<code>Column1.Items.Contains()</code>\nis searching for <code>String</code> values. \nif <code>e.FormattedValue</code> is not a <code>String</code> then the comparison will fail.</p>\n\n<p>try</p>\n\n<pre><code>if (!Column1.Items.Contains(e.FormattedValue.ToString())) { \n Column1.Items.Add(e.FormattedValue.ToString()); \n dataGridView1.Rows[e.RowIndex].Cells[e.ColumnIndex].Value = e.FormattedValue.ToString(); \n}\n</code></pre>\n\n<p>or </p>\n\n<pre><code>if (!Column1.Items.Contains(e.FormattedValue)) { \n Column1.Items.Add(e.FormattedValue); \n dataGridView1.Rows[e.RowIndex].Cells[e.ColumnIndex].Value = e.FormattedValue; \n}\n</code></pre>\n"
}
] |
2008/10/14
|
[
"https://Stackoverflow.com/questions/202084",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/14727/"
] |
Cells in DataGridViewComboBoxColumn have ComboBoxStyle DropDownList. It means the user can only select values from the dropdown. The underlying control is ComboBox, so it can have style DropDown. How do I change the style of the underlying combo box in DataGridViewComboBoxColumn. Or, more general, can I have a column in DataGridView with dropdown where user can type?
|
```
void dataGridView1_EditingControlShowing(object sender,
DataGridViewEditingControlShowingEventArgs e)
{
if (e.Control.GetType() == typeof(DataGridViewComboBoxEditingControl))
{
DataGridViewComboBoxEditingControl cbo =
e.Control as DataGridViewComboBoxEditingControl;
cbo.DropDownStyle = ComboBoxStyle.DropDown;
}
}
```
[Problem with combobox and databound datagridview](http://forums.microsoft.com/MSDN/ShowPost.aspx?PostID=13855&SiteID=1)
|
202,116 |
<p>Linux provides the stime(2) call to set the system time. However, while this will update the system's time, it does not set the BIOS hardware clock to match the new system time.</p>
<p>Linux systems typically sync the hardware clock with the system time at shutdown and at periodic intervals. However, if the machine gets power-cycled before one of these automatic syncs, the time will be incorrect when the machine restarts.</p>
<p>How do you ensure that the hardware clock gets updated when you set the system time?</p>
|
[
{
"answer_id": 202118,
"author": "Kristopher Johnson",
"author_id": 1175,
"author_profile": "https://Stackoverflow.com/users/1175",
"pm_score": 3,
"selected": false,
"text": "<p>After calling stime(), do this:</p>\n\n<pre><code>system(\"/sbin/hwclock --systohc\");\n</code></pre>\n\n<p>See the hwclock(8) man page for more information.</p>\n"
},
{
"answer_id": 202137,
"author": "Martin York",
"author_id": 14065,
"author_profile": "https://Stackoverflow.com/users/14065",
"pm_score": 2,
"selected": false,
"text": "<p>I would also like to point out the hardware clock is only accurate to a point (I have seen systems that will loose/gain a couple of seconds a day).</p>\n\n<p>Have you considered setting up the network time daemon to sync your clock against a time server?</p>\n\n<p>Admittedly this syncing does not happen until after the daemon starts so keeping your hardware clock in sync also helps between the power up and the point the time daemon syncs against the time server.</p>\n"
},
{
"answer_id": 202149,
"author": "iny",
"author_id": 27067,
"author_profile": "https://Stackoverflow.com/users/27067",
"pm_score": 2,
"selected": false,
"text": "<p>I would start by reading the source code of hwclock.</p>\n"
},
{
"answer_id": 202170,
"author": "Zan Lynx",
"author_id": 13422,
"author_profile": "https://Stackoverflow.com/users/13422",
"pm_score": 5,
"selected": true,
"text": "<p>Check out the rtc man-page for details, but if you are logged in as root, something like this: </p>\n\n<pre><code>#include <linux/rtc.h>\n#include <sys/ioctl.h>\n\n\n struct rtc_time {\n int tm_sec; \n int tm_min; \n int tm_hour; \n int tm_mday; \n int tm_mon; \n int tm_year; \n int tm_wday; /* unused */\n int tm_yday; /* unused */\n int tm_isdst;/* unused */\n };\n\nint fd;\nstruct rtc_time rt;\n/* set your values here */\nfd = open(\"/dev/rtc\", O_RDONLY);\nioctl(fd, RTC_SET_TIME, &rt);\nclose(fd);\n</code></pre>\n"
},
{
"answer_id": 4057822,
"author": "brian carr",
"author_id": 492022,
"author_profile": "https://Stackoverflow.com/users/492022",
"pm_score": -1,
"selected": false,
"text": "<p>If the text editor is different than kubuntu (kate is the default in editor), use your own with the <code>sudo</code> command in terminal.</p>\n\n<ol>\n<li>run terminal</li>\n<li>copy and paste this command\n<code>sudo kate /etc/default/rcS</code> press <kbd>Enter</kbd></li>\n<li>enter user password (your login password) press <kbd>Enter</kbd></li>\n<li>text editor will open on the desktop</li>\n<li>change the line <code>UTC=yes</code> to <code>UTC=no</code></li>\n<li>and click save (at top of text editor tab bar)</li>\n<li>reboot</li>\n</ol>\n"
}
] |
2008/10/14
|
[
"https://Stackoverflow.com/questions/202116",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1175/"
] |
Linux provides the stime(2) call to set the system time. However, while this will update the system's time, it does not set the BIOS hardware clock to match the new system time.
Linux systems typically sync the hardware clock with the system time at shutdown and at periodic intervals. However, if the machine gets power-cycled before one of these automatic syncs, the time will be incorrect when the machine restarts.
How do you ensure that the hardware clock gets updated when you set the system time?
|
Check out the rtc man-page for details, but if you are logged in as root, something like this:
```
#include <linux/rtc.h>
#include <sys/ioctl.h>
struct rtc_time {
int tm_sec;
int tm_min;
int tm_hour;
int tm_mday;
int tm_mon;
int tm_year;
int tm_wday; /* unused */
int tm_yday; /* unused */
int tm_isdst;/* unused */
};
int fd;
struct rtc_time rt;
/* set your values here */
fd = open("/dev/rtc", O_RDONLY);
ioctl(fd, RTC_SET_TIME, &rt);
close(fd);
```
|
202,124 |
<p>I´m trying to expose services using jax-ws but the first surprise i got was that Weblogic does not support inner classes for request/response objects. After get over this situation <a href="https://stackoverflow.com/questions/144118/jaxb-binding-customization">here</a>, i´m facing another challenge:</p>
<p>Generate <code>getXXX()</code> rather than/additionally to the <code>isXXX()</code> Method.</p>
<p>I need to generate this methods cause when i start the service i get the message:</p>
<pre><code><WS data binding error>could not find getter for property 'IsXXX' on com.foo.MyClass
</code></pre>
<p>Tried a customization:</p>
<pre><code><jaxb:globalBindings generateIsSetMethod="false" enableJavaNamingConventions="false">
</code></pre>
<p>without effect. :(</p>
<p>Any help?</p>
|
[
{
"answer_id": 1009590,
"author": "AlanG",
"author_id": 11645,
"author_profile": "https://Stackoverflow.com/users/11645",
"pm_score": 2,
"selected": true,
"text": "<p>BooleanGetter XJC plugin for JAXB is available at <a href=\"http://fisheye5.cenqua.com/browse/~raw,r=1.1/jaxb2-commons/www/boolean-getter/index.html\" rel=\"nofollow noreferrer\">http://fisheye5.cenqua.com/browse/~raw,r=1.1/jaxb2-commons/www/boolean-getter/index.html</a></p>\n\n<p>If you are working with JavaSE 6 then it needs to be re-packaged - see <a href=\"http://forums.java.net/jive/message.jspa?messageID=319434\" rel=\"nofollow noreferrer\">http://forums.java.net/jive/message.jspa?messageID=319434</a></p>\n\n<p>Use in ant build like below:</p>\n\n<pre><code> <taskdef name=\"xjc\" classname=\"com.sun.tools.xjc.XJCTask\" classpathref=\"development.classpath\"/>\n\n <xjc schema=\"some.xsd\" package=\"com.acme.jaxb\" destdir=\"gen-src\">\n <arg value=\"-Xcollection-setter-injector\"/> \n <arg value=\"-Xboolean-getter\"/>\n </xjc> \n</code></pre>\n\n<p>HTH</p>\n"
},
{
"answer_id": 9275553,
"author": "Stevo Slavić",
"author_id": 381140,
"author_profile": "https://Stackoverflow.com/users/381140",
"pm_score": 3,
"selected": false,
"text": "<p>This has been fixed or better to say supported in jaxb 2.1.13 ( see <a href=\"http://java.net/jira/browse/JAXB-131\" rel=\"noreferrer\">JAXB-131</a> for more details). Upgrade your dependencies and configure enableIntrospection xjc option. More details on xjc options can be found on <a href=\"http://jaxb.java.net/nonav/2.1.13/docs/xjc.html\" rel=\"noreferrer\">this link</a>. If you're using org.codehause.mojo:jaxb2-maven-plugin:1.3.1 plugin see <a href=\"http://jira.codehaus.org/browse/MJAXB-37?focusedCommentId=291602&page=com.atlassian.jira.plugin.system.issuetabpanels%3acomment-tabpanel#comment-291602\" rel=\"noreferrer\">this issue comment</a> for a workaround.</p>\n\n<p>Option: -enableIntrospection</p>\n"
},
{
"answer_id": 11139042,
"author": "rainer198",
"author_id": 602856,
"author_profile": "https://Stackoverflow.com/users/602856",
"pm_score": 2,
"selected": false,
"text": "<p>Here is another plugin which resolves the issue:</p>\n\n<p><a href=\"http://code.google.com/p/nebulent-xjc-booleangetter/wiki/AboutThisProject\" rel=\"nofollow\">http://code.google.com/p/nebulent-xjc-booleangetter/wiki/AboutThisProject</a></p>\n\n<p>It geneates the <code>getXXX()</code> addiotionally to the default <code>isXXX()</code> , hence, code already using these classes do not break after applying the plugin.</p>\n"
}
] |
2008/10/14
|
[
"https://Stackoverflow.com/questions/202124",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/21370/"
] |
I´m trying to expose services using jax-ws but the first surprise i got was that Weblogic does not support inner classes for request/response objects. After get over this situation [here](https://stackoverflow.com/questions/144118/jaxb-binding-customization), i´m facing another challenge:
Generate `getXXX()` rather than/additionally to the `isXXX()` Method.
I need to generate this methods cause when i start the service i get the message:
```
<WS data binding error>could not find getter for property 'IsXXX' on com.foo.MyClass
```
Tried a customization:
```
<jaxb:globalBindings generateIsSetMethod="false" enableJavaNamingConventions="false">
```
without effect. :(
Any help?
|
BooleanGetter XJC plugin for JAXB is available at <http://fisheye5.cenqua.com/browse/~raw,r=1.1/jaxb2-commons/www/boolean-getter/index.html>
If you are working with JavaSE 6 then it needs to be re-packaged - see <http://forums.java.net/jive/message.jspa?messageID=319434>
Use in ant build like below:
```
<taskdef name="xjc" classname="com.sun.tools.xjc.XJCTask" classpathref="development.classpath"/>
<xjc schema="some.xsd" package="com.acme.jaxb" destdir="gen-src">
<arg value="-Xcollection-setter-injector"/>
<arg value="-Xboolean-getter"/>
</xjc>
```
HTH
|
202,136 |
<p>Hello fellow stackoverflowers!</p>
<p>I have a word list of 200.000 string entries, average string length is around 30 characters. This list of words are the key and to each key i have a domain object. I would like to find the domain objects in this collection by only knowing a part of the key. I.E. the search string "kov" would for example match the key "stackoverflow". </p>
<p>Currently I am using a Ternary Search Tree (TST), which usually will find the items within 100 milliseconds. This is however too slow for my requirements. The TST implementation could be improved with some minor optimizations and I could try to balance the tree. But i figured that these things would not give me the 5x - 10x speed improvement I am aiming at. I am assuming that the reason for being so slow is that i basically have to visit most nodes in the tree.</p>
<p>Any ideas on how to improve the speed of the algorithm? Are there any other algorithms that I should be looking at?</p>
<p>Thanks in advance,
Oskar</p>
|
[
{
"answer_id": 202164,
"author": "Superpolock",
"author_id": 16496,
"author_profile": "https://Stackoverflow.com/users/16496",
"pm_score": 0,
"selected": false,
"text": "<p>Would you get any advantage having your trie keys comparable to the size of the machine register? So if you are on a 32bit box you can compare 4 characters at once instead of each character individually? I don't know how bad that would increase the size of your app.</p>\n"
},
{
"answer_id": 202195,
"author": "Konrad Rudolph",
"author_id": 1968,
"author_profile": "https://Stackoverflow.com/users/1968",
"pm_score": 4,
"selected": false,
"text": "<h2>Suffix Array and <em>q</em>-gram index</h2>\n\n<p>If your strings have a strict upper bound on the size you might consider the use of a <a href=\"http://en.wikipedia.org/wiki/Suffix_array\" rel=\"noreferrer\"><strong>suffix array</strong></a>: Simply pad all your strings to the same maximum length using a special character (e.g. the null char). Then concatenate all strings and build a suffix array index over them.</p>\n\n<p>This gives you a lookup runtime of <em>m</em> * log <em>n</em> where <em>m</em> is the length of your query string and <em>n</em> is the overall length of your combined strings. If this still isn't good enough and your <em>m</em> has a fixed, small length, and your alphabet Σ is restricted in size (say, Σ < 128 different characters) you can additionally build a <strong><em>q</em>-gram index</strong>. This will allow retrieval in <strong>constant time</strong>. However, the <em>q</em>-gram table requires Σ<sup><em>m</em></sup> entries (= 8 MiB in the case of just 3 characters, and 1 GiB for 4 characters!).</p>\n\n<h2>Making the index smaller</h2>\n\n<p>It might be possible to <strong>reduce the size of the <em>q</em>-gram table</strong> (exponentially, in the best case) by adjusting the hash function. Instead of assigning a unique number to every possible <em>q</em>-gram you might employ a lossy hash function. The table then would have to store lists of possible suffix array indices instead of just one suffix array entry corresponding to an exact match. This would entail that lookup is no longer constant, though, because all entries in the list would have to be considered.</p>\n\n<p>By the way, I'm not sure if you're familiar with <strong>how a <em>q</em>-gram index works</strong> since the Internet isn't helpful on this topic. I've mentioned this before in another topic. I've therefore included a description and an algorithm for the construction in my <a href=\"http://madrat.net/my/bachelor/thesis.pdf\" rel=\"noreferrer\">bachelor thesis</a>.</p>\n\n<h2>Proof of concept</h2>\n\n<p>I've written a very small C# proof of concept (since you stated otherwise that you worked with C#). It works, however it is <em>very</em> slow for two reasons. First, the suffix array creation simply sorts the suffixes. This alone has runtime <em>n</em><sup>2</sup> log <em>n</em>. There are far superior methods. Worse, however, is the fact that I use <code>SubString</code> to obtain the suffixes. Unfortunately, .NET creates copies of the whole suffix for this. To use this code in practice, make sure that you use in-place methods which do not copy any data around unnecessarily. The same is true for retrieving the <em>q</em>-grams from the string.</p>\n\n<p>It would possibly even better to not construct the <code>m_Data</code> string used in my example. Instead, you could save a reference to the original array and simulate all my <code>SubString</code> accesses by working on this array.</p>\n\n<p>Still, it's easy to see that this implementation has essentially expected constant time retrieval (if the dictionary is well-behaved)! This is quite an achievement that can't possibly be beaten by a search tree/trie!</p>\n\n<pre><code>class QGramIndex {\n private readonly int m_Maxlen;\n private readonly string m_Data;\n private readonly int m_Q;\n private int[] m_SA;\n private Dictionary<string, int> m_Dir = new Dictionary<string, int>();\n\n private struct StrCmp : IComparer<int> {\n public readonly String Data;\n public StrCmp(string data) { Data = data; }\n public int Compare(int x, int y) {\n return string.CompareOrdinal(Data.Substring(x), Data.Substring(y));\n }\n }\n\n private readonly StrCmp cmp;\n\n public QGramIndex(IList<string> strings, int maxlen, int q) {\n m_Maxlen = maxlen;\n m_Q = q;\n\n var sb = new StringBuilder(strings.Count * maxlen);\n foreach (string str in strings)\n sb.AppendFormat(str.PadRight(maxlen, '\\u0000'));\n m_Data = sb.ToString();\n cmp = new StrCmp(m_Data);\n MakeSuffixArray();\n MakeIndex();\n }\n\n public int this[string s] { get { return FindInIndex(s); } }\n\n private void MakeSuffixArray() {\n // Approx. runtime: n^3 * log n!!!\n // But I claim the shortest ever implementation of a suffix array!\n m_SA = Enumerable.Range(0, m_Data.Length).ToArray();\n Array.Sort(m_SA, cmp);\n }\n\n private int FindInArray(int ith) {\n return Array.BinarySearch(m_SA, ith, cmp);\n }\n\n private int FindInIndex(string s) {\n int idx;\n if (!m_Dir.TryGetValue(s, out idx))\n return -1;\n return m_SA[idx] / m_Maxlen;\n }\n\n private string QGram(int i) {\n return i > m_Data.Length - m_Q ?\n m_Data.Substring(i) :\n m_Data.Substring(i, m_Q);\n }\n\n private void MakeIndex() {\n for (int i = 0; i < m_Data.Length; ++i) {\n int pos = FindInArray(i);\n if (pos < 0) continue;\n m_Dir[QGram(i)] = pos;\n }\n }\n}\n</code></pre>\n\n<h2>Example of usage:</h2>\n\n<pre><code>static void Main(string[] args) {\n var strings = new [] { \"hello\", \"world\", \"this\", \"is\", \"a\",\n \"funny\", \"test\", \"which\", \"i\", \"have\",\n \"taken\", \"much\", \"too\", \"far\", \"already\" };\n\n var index = new QGramIndex(strings, 10, 3);\n\n var tests = new [] { \"xyz\", \"aki\", \"ake\", \"muc\", \"uch\", \"too\", \"fun\", \"est\",\n \"hic\", \"ell\", \"llo\", \"his\" };\n\n foreach (var str in tests) {\n int pos = index[str];\n if (pos > -1)\n Console.WriteLine(\"\\\"{0}\\\" found in \\\"{1}\\\".\", str, strings[pos]);\n else\n Console.WriteLine(\"\\\"{0}\\\" not found.\", str);\n }\n}\n</code></pre>\n"
},
{
"answer_id": 202230,
"author": "jim",
"author_id": 27628,
"author_profile": "https://Stackoverflow.com/users/27628",
"pm_score": 0,
"selected": false,
"text": "<p>would it be possible to \"hash\" the key value ? basically have a 2nd tree will all the possible values to search for pointing to a list of keys into the 1st tree.</p>\n\n<p>You're going to need 2 trees; 1st one is a hash value to the domain object. the 2nd tree is the search strings to the hash value. the 2nd tree has multiple keys to the same hash value.</p>\n\n<p>Example\ntree 1:\nSTCKVRFLW -> domain object</p>\n\n<p>tree 2:\nstack -> STCKVRFLW,STCK\nover -> STCKVRFLW, VRBRD, VR</p>\n\n<p>So using the search for on the 2nd tree gives you a list of keys to search on the 1st tree.</p>\n"
},
{
"answer_id": 202250,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 2,
"selected": false,
"text": "<p>Here's a WAG for you. <em>I am in NO WAY Knuthian in my algorithm savvy</em></p>\n\n<p>Okay, so the naiive Trie encodes string keys by starting at the root of the tree and moving down branches that match each letter in the key, starting at the first letter of the key. So the key \"foo\" would be mapped to <code>(root)->f->fo->foo</code> and the value would be stored in the location pointed to by the 'foo' node.</p>\n\n<p>You are searching for ANY substring within the key, not just substrings that start at the beginning of the key.</p>\n\n<p>So, what you need to do, is associate a node with ANY key that contains that particular substring. In the foo example I gave before, you would NOT have found a reference to foo's value under the nodes 'f' and 'fo'. In a TST that supports the type of searches you're looking to do, you'd not only find the foo object under all three nodes ('f', 'fo', and 'foo'), you'd also find it under 'o' and 'oo' as well.</p>\n\n<p>There are a couple obvious consequences to expanding the search tree to support this type of indexing. First, you've just exploded the size of the tree. Staggeringly. If you can store it and use it in an efficient manner, your searches will take O(1) time. If your keys remain static, and you can find a way to partition the index so you don't take a huge IO penalty in using it, this might amortize to be worth while. </p>\n\n<p>Second, you are going to find that searches for small strings will result in massive numbers of hits, which may make your search useless unless you, say, put a minimum length on search terms.</p>\n\n<p>On the bright side, you might also find that you can compress the tree via tokenization (like zip compression does) or by compressing nodes that don't branch down (i.e., if you have 'w'->'o'->'o'-> and the first 'o' doesn't branch, you can safely collapse it to 'w'->'oo'). Maybe even a wicked-ass hash could make things easier...</p>\n\n<p>Anyhow, WAG as I said. </p>\n"
},
{
"answer_id": 202352,
"author": "Simon Howard",
"author_id": 24806,
"author_profile": "https://Stackoverflow.com/users/24806",
"pm_score": 0,
"selected": false,
"text": "<p>Choose a minimum search string size (eg. four characters). Go through your list of string entries and build up a dictionary of every four character substring, mapping to a list of entries that the substring appears in. When you do a search, look up based on the first four characters of the search string to get an initial set, then narrow down that initial set to only those that match the full search string.</p>\n\n<p>The worst case of this is O(n), but you'll only get that if your string entries are almost all identical. The lookup dictionary is likely to be quite large, so it's probably a good idea to store it on disk or use a relational database :-)</p>\n"
},
{
"answer_id": 204977,
"author": "Konrad Rudolph",
"author_id": 1968,
"author_profile": "https://Stackoverflow.com/users/1968",
"pm_score": 0,
"selected": false,
"text": "<p><em>/EDIT: A friend of mine just pointed out a stupid assumption in my construction of the q-gram table. The construction can be made much simpler – and consequently, much faster. I've edited the source code and explanation to reflect this. I think it might be the <strong>final solution</strong>.</em></p>\n\n<p>Inspired by Rafał Dowgird's comment to my previous answer, I've updated my code. I think this merits an own answer however, since it's also quite long. Instead of padding the existing strings, this code builds the index over the original array of strings. Instead of storing a single position, the suffix array stores a pair: the index of the target string and the position of the suffix in that string. In the result, only the first number is needed. However, the second number is necessary for the construction of the <em>q</em>-gram table.</p>\n\n<p>The new version of the algorithm builds the <em>q</em>-gram table by walking over the suffix array instead of the original strings. This saves the binary search of the suffix array. Consequently, the runtime of the construction drops from <em>O</em>(<em>n</em> * log <em>n</em>) down to <em>O</em>(<em>n</em>) (where <em>n</em> is the size of the suffix array).</p>\n\n<p>Notice that, like my first solution, use of <code>SubString</code> results in a lot of unnecessary copies. The obvious solution is to write an extension method that creates a lightweight wrapper instead of copying the string. The comparison then has to be slightly adapted. This is left as an exercise for the reader. ;-)</p>\n\n<pre><code>using Position = System.Collections.Generic.KeyValuePair<int, int>;\n\nclass QGramIndex {\n private readonly int m_Q;\n private readonly IList<string> m_Data;\n private Position[] m_SA;\n private Dictionary<string, int> m_Dir;\n\n public QGramIndex(IList<string> strings, int q) {\n m_Q = q;\n m_Data = strings;\n MakeSuffixArray();\n MakeIndex();\n }\n\n public int this[string s] { get { return FindInIndex(s); } }\n\n private int FindInIndex(string s) {\n int idx;\n if (!m_Dir.TryGetValue(s, out idx))\n return -1;\n return m_SA[idx].Key;\n }\n\n private void MakeSuffixArray() {\n int size = m_Data.Sum(str => str.Length < m_Q ? 0 : str.Length - m_Q + 1);\n m_SA = new Position[size];\n int pos = 0;\n for (int i = 0; i < m_Data.Count; ++i)\n for (int j = 0; j <= m_Data[i].Length - m_Q; ++j)\n m_SA[pos++] = new Position(i, j);\n\n Array.Sort(\n m_SA,\n (x, y) => string.CompareOrdinal(\n m_Data[x.Key].Substring(x.Value),\n m_Data[y.Key].Substring(y.Value)\n )\n );\n }\n\n private void MakeIndex() {\n m_Dir = new Dictionary<string, int>(m_SA.Length);\n\n // Every q-gram is a prefix in the suffix table.\n for (int i = 0; i < m_SA.Length; ++i) {\n var pos = m_SA[i];\n m_Dir[m_Data[pos.Key].Substring(pos.Value, 5)] = i;\n }\n }\n}\n</code></pre>\n\n<p>Usage is the same as in the other example, minus the required <code>maxlen</code> argument for the constructor.</p>\n"
},
{
"answer_id": 43089193,
"author": "Baxter",
"author_id": 2254421,
"author_profile": "https://Stackoverflow.com/users/2254421",
"pm_score": 0,
"selected": false,
"text": "<p>To query a large set of text in efficient manner you can use the concept of Edit Distance/ Prefix Edit Distance. </p>\n\n<blockquote>\n <p>Edit Distance ED(x,y): minimal number of transfroms to get from x to y</p>\n</blockquote>\n\n<p>But computing ED between each term and query text is resource and time consuming. Therefore instead of calculating ED for each term first we can extract possible matching terms using a technique called <strong>Qgram Index</strong>. and then apply ED calculation on those selected terms.</p>\n\n<p>An advantage of Qgram index technique is it supports for <strong>Fuzzy Search</strong>. </p>\n\n<p>One possible approach to adapt QGram index is build an Inverted Index using Qgrams. In there we store all the words which consists with particular Qgram(Instead of storing full string you can use unique ID for each string).</p>\n\n<blockquote>\n <p>col : <strong>col</strong>mbia, <strong>col</strong>ombo, gan<strong>col</strong>a, ta<strong>col</strong>ama</p>\n</blockquote>\n\n<p>Then when querying, we calculate the number of common Qgrams between query text and available terms.</p>\n\n<pre><code>Example: x = HILLARY, y = HILARI(query term)\nQgrams\n$$HILLARY$$ -> $$H, $HI, HIL, ILL, LLA, LAR, ARY, RY$, Y$$\n$$HILARI$$ -> $$H, $HI, HIL, ILA, LAR, ARI, RI$, I$$\nnumber of q-grams in common = 4\n</code></pre>\n\n<p>For the terms with high number of common Qgrams, we calculate the ED/PED against the query term and then suggest the term to the end user.</p>\n\n<p>you can find an implementation of this theory in following project. Feel free to ask any questions.\n<a href=\"https://github.com/Bhashitha-Gamage/City_Search\" rel=\"nofollow noreferrer\">https://github.com/Bhashitha-Gamage/City_Search</a></p>\n\n<p>To study more about Edit Distance, Prefix Edit Distance Qgram index please watch the following video of Prof. Dr Hannah Bast\n<a href=\"https://www.youtube.com/embed/6pUg2wmGJRo\" rel=\"nofollow noreferrer\">https://www.youtube.com/embed/6pUg2wmGJRo</a> (Lesson starts from 20:06)</p>\n"
}
] |
2008/10/14
|
[
"https://Stackoverflow.com/questions/202136",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] |
Hello fellow stackoverflowers!
I have a word list of 200.000 string entries, average string length is around 30 characters. This list of words are the key and to each key i have a domain object. I would like to find the domain objects in this collection by only knowing a part of the key. I.E. the search string "kov" would for example match the key "stackoverflow".
Currently I am using a Ternary Search Tree (TST), which usually will find the items within 100 milliseconds. This is however too slow for my requirements. The TST implementation could be improved with some minor optimizations and I could try to balance the tree. But i figured that these things would not give me the 5x - 10x speed improvement I am aiming at. I am assuming that the reason for being so slow is that i basically have to visit most nodes in the tree.
Any ideas on how to improve the speed of the algorithm? Are there any other algorithms that I should be looking at?
Thanks in advance,
Oskar
|
Suffix Array and *q*-gram index
-------------------------------
If your strings have a strict upper bound on the size you might consider the use of a [**suffix array**](http://en.wikipedia.org/wiki/Suffix_array): Simply pad all your strings to the same maximum length using a special character (e.g. the null char). Then concatenate all strings and build a suffix array index over them.
This gives you a lookup runtime of *m* \* log *n* where *m* is the length of your query string and *n* is the overall length of your combined strings. If this still isn't good enough and your *m* has a fixed, small length, and your alphabet Σ is restricted in size (say, Σ < 128 different characters) you can additionally build a ***q*-gram index**. This will allow retrieval in **constant time**. However, the *q*-gram table requires Σ*m* entries (= 8 MiB in the case of just 3 characters, and 1 GiB for 4 characters!).
Making the index smaller
------------------------
It might be possible to **reduce the size of the *q*-gram table** (exponentially, in the best case) by adjusting the hash function. Instead of assigning a unique number to every possible *q*-gram you might employ a lossy hash function. The table then would have to store lists of possible suffix array indices instead of just one suffix array entry corresponding to an exact match. This would entail that lookup is no longer constant, though, because all entries in the list would have to be considered.
By the way, I'm not sure if you're familiar with **how a *q*-gram index works** since the Internet isn't helpful on this topic. I've mentioned this before in another topic. I've therefore included a description and an algorithm for the construction in my [bachelor thesis](http://madrat.net/my/bachelor/thesis.pdf).
Proof of concept
----------------
I've written a very small C# proof of concept (since you stated otherwise that you worked with C#). It works, however it is *very* slow for two reasons. First, the suffix array creation simply sorts the suffixes. This alone has runtime *n*2 log *n*. There are far superior methods. Worse, however, is the fact that I use `SubString` to obtain the suffixes. Unfortunately, .NET creates copies of the whole suffix for this. To use this code in practice, make sure that you use in-place methods which do not copy any data around unnecessarily. The same is true for retrieving the *q*-grams from the string.
It would possibly even better to not construct the `m_Data` string used in my example. Instead, you could save a reference to the original array and simulate all my `SubString` accesses by working on this array.
Still, it's easy to see that this implementation has essentially expected constant time retrieval (if the dictionary is well-behaved)! This is quite an achievement that can't possibly be beaten by a search tree/trie!
```
class QGramIndex {
private readonly int m_Maxlen;
private readonly string m_Data;
private readonly int m_Q;
private int[] m_SA;
private Dictionary<string, int> m_Dir = new Dictionary<string, int>();
private struct StrCmp : IComparer<int> {
public readonly String Data;
public StrCmp(string data) { Data = data; }
public int Compare(int x, int y) {
return string.CompareOrdinal(Data.Substring(x), Data.Substring(y));
}
}
private readonly StrCmp cmp;
public QGramIndex(IList<string> strings, int maxlen, int q) {
m_Maxlen = maxlen;
m_Q = q;
var sb = new StringBuilder(strings.Count * maxlen);
foreach (string str in strings)
sb.AppendFormat(str.PadRight(maxlen, '\u0000'));
m_Data = sb.ToString();
cmp = new StrCmp(m_Data);
MakeSuffixArray();
MakeIndex();
}
public int this[string s] { get { return FindInIndex(s); } }
private void MakeSuffixArray() {
// Approx. runtime: n^3 * log n!!!
// But I claim the shortest ever implementation of a suffix array!
m_SA = Enumerable.Range(0, m_Data.Length).ToArray();
Array.Sort(m_SA, cmp);
}
private int FindInArray(int ith) {
return Array.BinarySearch(m_SA, ith, cmp);
}
private int FindInIndex(string s) {
int idx;
if (!m_Dir.TryGetValue(s, out idx))
return -1;
return m_SA[idx] / m_Maxlen;
}
private string QGram(int i) {
return i > m_Data.Length - m_Q ?
m_Data.Substring(i) :
m_Data.Substring(i, m_Q);
}
private void MakeIndex() {
for (int i = 0; i < m_Data.Length; ++i) {
int pos = FindInArray(i);
if (pos < 0) continue;
m_Dir[QGram(i)] = pos;
}
}
}
```
Example of usage:
-----------------
```
static void Main(string[] args) {
var strings = new [] { "hello", "world", "this", "is", "a",
"funny", "test", "which", "i", "have",
"taken", "much", "too", "far", "already" };
var index = new QGramIndex(strings, 10, 3);
var tests = new [] { "xyz", "aki", "ake", "muc", "uch", "too", "fun", "est",
"hic", "ell", "llo", "his" };
foreach (var str in tests) {
int pos = index[str];
if (pos > -1)
Console.WriteLine("\"{0}\" found in \"{1}\".", str, strings[pos]);
else
Console.WriteLine("\"{0}\" not found.", str);
}
}
```
|
202,142 |
<p>I can connect with a user who has permissions to set passwords. I'm able to change attributes, but I can't set the password.</p>
<p>Found some instructions to set the attribute <code>unicodePwd</code> to <code>\UNC:"*password*"</code>, but it says:</p>
<blockquote>
<p>Error: Modify: Unwilling To Perform. <53></p>
</blockquote>
<p>Setting LDAP_OPT_ENCRYPT to 1 didn't work either. The port I'm using is 389.</p>
|
[
{
"answer_id": 202164,
"author": "Superpolock",
"author_id": 16496,
"author_profile": "https://Stackoverflow.com/users/16496",
"pm_score": 0,
"selected": false,
"text": "<p>Would you get any advantage having your trie keys comparable to the size of the machine register? So if you are on a 32bit box you can compare 4 characters at once instead of each character individually? I don't know how bad that would increase the size of your app.</p>\n"
},
{
"answer_id": 202195,
"author": "Konrad Rudolph",
"author_id": 1968,
"author_profile": "https://Stackoverflow.com/users/1968",
"pm_score": 4,
"selected": false,
"text": "<h2>Suffix Array and <em>q</em>-gram index</h2>\n\n<p>If your strings have a strict upper bound on the size you might consider the use of a <a href=\"http://en.wikipedia.org/wiki/Suffix_array\" rel=\"noreferrer\"><strong>suffix array</strong></a>: Simply pad all your strings to the same maximum length using a special character (e.g. the null char). Then concatenate all strings and build a suffix array index over them.</p>\n\n<p>This gives you a lookup runtime of <em>m</em> * log <em>n</em> where <em>m</em> is the length of your query string and <em>n</em> is the overall length of your combined strings. If this still isn't good enough and your <em>m</em> has a fixed, small length, and your alphabet Σ is restricted in size (say, Σ < 128 different characters) you can additionally build a <strong><em>q</em>-gram index</strong>. This will allow retrieval in <strong>constant time</strong>. However, the <em>q</em>-gram table requires Σ<sup><em>m</em></sup> entries (= 8 MiB in the case of just 3 characters, and 1 GiB for 4 characters!).</p>\n\n<h2>Making the index smaller</h2>\n\n<p>It might be possible to <strong>reduce the size of the <em>q</em>-gram table</strong> (exponentially, in the best case) by adjusting the hash function. Instead of assigning a unique number to every possible <em>q</em>-gram you might employ a lossy hash function. The table then would have to store lists of possible suffix array indices instead of just one suffix array entry corresponding to an exact match. This would entail that lookup is no longer constant, though, because all entries in the list would have to be considered.</p>\n\n<p>By the way, I'm not sure if you're familiar with <strong>how a <em>q</em>-gram index works</strong> since the Internet isn't helpful on this topic. I've mentioned this before in another topic. I've therefore included a description and an algorithm for the construction in my <a href=\"http://madrat.net/my/bachelor/thesis.pdf\" rel=\"noreferrer\">bachelor thesis</a>.</p>\n\n<h2>Proof of concept</h2>\n\n<p>I've written a very small C# proof of concept (since you stated otherwise that you worked with C#). It works, however it is <em>very</em> slow for two reasons. First, the suffix array creation simply sorts the suffixes. This alone has runtime <em>n</em><sup>2</sup> log <em>n</em>. There are far superior methods. Worse, however, is the fact that I use <code>SubString</code> to obtain the suffixes. Unfortunately, .NET creates copies of the whole suffix for this. To use this code in practice, make sure that you use in-place methods which do not copy any data around unnecessarily. The same is true for retrieving the <em>q</em>-grams from the string.</p>\n\n<p>It would possibly even better to not construct the <code>m_Data</code> string used in my example. Instead, you could save a reference to the original array and simulate all my <code>SubString</code> accesses by working on this array.</p>\n\n<p>Still, it's easy to see that this implementation has essentially expected constant time retrieval (if the dictionary is well-behaved)! This is quite an achievement that can't possibly be beaten by a search tree/trie!</p>\n\n<pre><code>class QGramIndex {\n private readonly int m_Maxlen;\n private readonly string m_Data;\n private readonly int m_Q;\n private int[] m_SA;\n private Dictionary<string, int> m_Dir = new Dictionary<string, int>();\n\n private struct StrCmp : IComparer<int> {\n public readonly String Data;\n public StrCmp(string data) { Data = data; }\n public int Compare(int x, int y) {\n return string.CompareOrdinal(Data.Substring(x), Data.Substring(y));\n }\n }\n\n private readonly StrCmp cmp;\n\n public QGramIndex(IList<string> strings, int maxlen, int q) {\n m_Maxlen = maxlen;\n m_Q = q;\n\n var sb = new StringBuilder(strings.Count * maxlen);\n foreach (string str in strings)\n sb.AppendFormat(str.PadRight(maxlen, '\\u0000'));\n m_Data = sb.ToString();\n cmp = new StrCmp(m_Data);\n MakeSuffixArray();\n MakeIndex();\n }\n\n public int this[string s] { get { return FindInIndex(s); } }\n\n private void MakeSuffixArray() {\n // Approx. runtime: n^3 * log n!!!\n // But I claim the shortest ever implementation of a suffix array!\n m_SA = Enumerable.Range(0, m_Data.Length).ToArray();\n Array.Sort(m_SA, cmp);\n }\n\n private int FindInArray(int ith) {\n return Array.BinarySearch(m_SA, ith, cmp);\n }\n\n private int FindInIndex(string s) {\n int idx;\n if (!m_Dir.TryGetValue(s, out idx))\n return -1;\n return m_SA[idx] / m_Maxlen;\n }\n\n private string QGram(int i) {\n return i > m_Data.Length - m_Q ?\n m_Data.Substring(i) :\n m_Data.Substring(i, m_Q);\n }\n\n private void MakeIndex() {\n for (int i = 0; i < m_Data.Length; ++i) {\n int pos = FindInArray(i);\n if (pos < 0) continue;\n m_Dir[QGram(i)] = pos;\n }\n }\n}\n</code></pre>\n\n<h2>Example of usage:</h2>\n\n<pre><code>static void Main(string[] args) {\n var strings = new [] { \"hello\", \"world\", \"this\", \"is\", \"a\",\n \"funny\", \"test\", \"which\", \"i\", \"have\",\n \"taken\", \"much\", \"too\", \"far\", \"already\" };\n\n var index = new QGramIndex(strings, 10, 3);\n\n var tests = new [] { \"xyz\", \"aki\", \"ake\", \"muc\", \"uch\", \"too\", \"fun\", \"est\",\n \"hic\", \"ell\", \"llo\", \"his\" };\n\n foreach (var str in tests) {\n int pos = index[str];\n if (pos > -1)\n Console.WriteLine(\"\\\"{0}\\\" found in \\\"{1}\\\".\", str, strings[pos]);\n else\n Console.WriteLine(\"\\\"{0}\\\" not found.\", str);\n }\n}\n</code></pre>\n"
},
{
"answer_id": 202230,
"author": "jim",
"author_id": 27628,
"author_profile": "https://Stackoverflow.com/users/27628",
"pm_score": 0,
"selected": false,
"text": "<p>would it be possible to \"hash\" the key value ? basically have a 2nd tree will all the possible values to search for pointing to a list of keys into the 1st tree.</p>\n\n<p>You're going to need 2 trees; 1st one is a hash value to the domain object. the 2nd tree is the search strings to the hash value. the 2nd tree has multiple keys to the same hash value.</p>\n\n<p>Example\ntree 1:\nSTCKVRFLW -> domain object</p>\n\n<p>tree 2:\nstack -> STCKVRFLW,STCK\nover -> STCKVRFLW, VRBRD, VR</p>\n\n<p>So using the search for on the 2nd tree gives you a list of keys to search on the 1st tree.</p>\n"
},
{
"answer_id": 202250,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 2,
"selected": false,
"text": "<p>Here's a WAG for you. <em>I am in NO WAY Knuthian in my algorithm savvy</em></p>\n\n<p>Okay, so the naiive Trie encodes string keys by starting at the root of the tree and moving down branches that match each letter in the key, starting at the first letter of the key. So the key \"foo\" would be mapped to <code>(root)->f->fo->foo</code> and the value would be stored in the location pointed to by the 'foo' node.</p>\n\n<p>You are searching for ANY substring within the key, not just substrings that start at the beginning of the key.</p>\n\n<p>So, what you need to do, is associate a node with ANY key that contains that particular substring. In the foo example I gave before, you would NOT have found a reference to foo's value under the nodes 'f' and 'fo'. In a TST that supports the type of searches you're looking to do, you'd not only find the foo object under all three nodes ('f', 'fo', and 'foo'), you'd also find it under 'o' and 'oo' as well.</p>\n\n<p>There are a couple obvious consequences to expanding the search tree to support this type of indexing. First, you've just exploded the size of the tree. Staggeringly. If you can store it and use it in an efficient manner, your searches will take O(1) time. If your keys remain static, and you can find a way to partition the index so you don't take a huge IO penalty in using it, this might amortize to be worth while. </p>\n\n<p>Second, you are going to find that searches for small strings will result in massive numbers of hits, which may make your search useless unless you, say, put a minimum length on search terms.</p>\n\n<p>On the bright side, you might also find that you can compress the tree via tokenization (like zip compression does) or by compressing nodes that don't branch down (i.e., if you have 'w'->'o'->'o'-> and the first 'o' doesn't branch, you can safely collapse it to 'w'->'oo'). Maybe even a wicked-ass hash could make things easier...</p>\n\n<p>Anyhow, WAG as I said. </p>\n"
},
{
"answer_id": 202352,
"author": "Simon Howard",
"author_id": 24806,
"author_profile": "https://Stackoverflow.com/users/24806",
"pm_score": 0,
"selected": false,
"text": "<p>Choose a minimum search string size (eg. four characters). Go through your list of string entries and build up a dictionary of every four character substring, mapping to a list of entries that the substring appears in. When you do a search, look up based on the first four characters of the search string to get an initial set, then narrow down that initial set to only those that match the full search string.</p>\n\n<p>The worst case of this is O(n), but you'll only get that if your string entries are almost all identical. The lookup dictionary is likely to be quite large, so it's probably a good idea to store it on disk or use a relational database :-)</p>\n"
},
{
"answer_id": 204977,
"author": "Konrad Rudolph",
"author_id": 1968,
"author_profile": "https://Stackoverflow.com/users/1968",
"pm_score": 0,
"selected": false,
"text": "<p><em>/EDIT: A friend of mine just pointed out a stupid assumption in my construction of the q-gram table. The construction can be made much simpler – and consequently, much faster. I've edited the source code and explanation to reflect this. I think it might be the <strong>final solution</strong>.</em></p>\n\n<p>Inspired by Rafał Dowgird's comment to my previous answer, I've updated my code. I think this merits an own answer however, since it's also quite long. Instead of padding the existing strings, this code builds the index over the original array of strings. Instead of storing a single position, the suffix array stores a pair: the index of the target string and the position of the suffix in that string. In the result, only the first number is needed. However, the second number is necessary for the construction of the <em>q</em>-gram table.</p>\n\n<p>The new version of the algorithm builds the <em>q</em>-gram table by walking over the suffix array instead of the original strings. This saves the binary search of the suffix array. Consequently, the runtime of the construction drops from <em>O</em>(<em>n</em> * log <em>n</em>) down to <em>O</em>(<em>n</em>) (where <em>n</em> is the size of the suffix array).</p>\n\n<p>Notice that, like my first solution, use of <code>SubString</code> results in a lot of unnecessary copies. The obvious solution is to write an extension method that creates a lightweight wrapper instead of copying the string. The comparison then has to be slightly adapted. This is left as an exercise for the reader. ;-)</p>\n\n<pre><code>using Position = System.Collections.Generic.KeyValuePair<int, int>;\n\nclass QGramIndex {\n private readonly int m_Q;\n private readonly IList<string> m_Data;\n private Position[] m_SA;\n private Dictionary<string, int> m_Dir;\n\n public QGramIndex(IList<string> strings, int q) {\n m_Q = q;\n m_Data = strings;\n MakeSuffixArray();\n MakeIndex();\n }\n\n public int this[string s] { get { return FindInIndex(s); } }\n\n private int FindInIndex(string s) {\n int idx;\n if (!m_Dir.TryGetValue(s, out idx))\n return -1;\n return m_SA[idx].Key;\n }\n\n private void MakeSuffixArray() {\n int size = m_Data.Sum(str => str.Length < m_Q ? 0 : str.Length - m_Q + 1);\n m_SA = new Position[size];\n int pos = 0;\n for (int i = 0; i < m_Data.Count; ++i)\n for (int j = 0; j <= m_Data[i].Length - m_Q; ++j)\n m_SA[pos++] = new Position(i, j);\n\n Array.Sort(\n m_SA,\n (x, y) => string.CompareOrdinal(\n m_Data[x.Key].Substring(x.Value),\n m_Data[y.Key].Substring(y.Value)\n )\n );\n }\n\n private void MakeIndex() {\n m_Dir = new Dictionary<string, int>(m_SA.Length);\n\n // Every q-gram is a prefix in the suffix table.\n for (int i = 0; i < m_SA.Length; ++i) {\n var pos = m_SA[i];\n m_Dir[m_Data[pos.Key].Substring(pos.Value, 5)] = i;\n }\n }\n}\n</code></pre>\n\n<p>Usage is the same as in the other example, minus the required <code>maxlen</code> argument for the constructor.</p>\n"
},
{
"answer_id": 43089193,
"author": "Baxter",
"author_id": 2254421,
"author_profile": "https://Stackoverflow.com/users/2254421",
"pm_score": 0,
"selected": false,
"text": "<p>To query a large set of text in efficient manner you can use the concept of Edit Distance/ Prefix Edit Distance. </p>\n\n<blockquote>\n <p>Edit Distance ED(x,y): minimal number of transfroms to get from x to y</p>\n</blockquote>\n\n<p>But computing ED between each term and query text is resource and time consuming. Therefore instead of calculating ED for each term first we can extract possible matching terms using a technique called <strong>Qgram Index</strong>. and then apply ED calculation on those selected terms.</p>\n\n<p>An advantage of Qgram index technique is it supports for <strong>Fuzzy Search</strong>. </p>\n\n<p>One possible approach to adapt QGram index is build an Inverted Index using Qgrams. In there we store all the words which consists with particular Qgram(Instead of storing full string you can use unique ID for each string).</p>\n\n<blockquote>\n <p>col : <strong>col</strong>mbia, <strong>col</strong>ombo, gan<strong>col</strong>a, ta<strong>col</strong>ama</p>\n</blockquote>\n\n<p>Then when querying, we calculate the number of common Qgrams between query text and available terms.</p>\n\n<pre><code>Example: x = HILLARY, y = HILARI(query term)\nQgrams\n$$HILLARY$$ -> $$H, $HI, HIL, ILL, LLA, LAR, ARY, RY$, Y$$\n$$HILARI$$ -> $$H, $HI, HIL, ILA, LAR, ARI, RI$, I$$\nnumber of q-grams in common = 4\n</code></pre>\n\n<p>For the terms with high number of common Qgrams, we calculate the ED/PED against the query term and then suggest the term to the end user.</p>\n\n<p>you can find an implementation of this theory in following project. Feel free to ask any questions.\n<a href=\"https://github.com/Bhashitha-Gamage/City_Search\" rel=\"nofollow noreferrer\">https://github.com/Bhashitha-Gamage/City_Search</a></p>\n\n<p>To study more about Edit Distance, Prefix Edit Distance Qgram index please watch the following video of Prof. Dr Hannah Bast\n<a href=\"https://www.youtube.com/embed/6pUg2wmGJRo\" rel=\"nofollow noreferrer\">https://www.youtube.com/embed/6pUg2wmGJRo</a> (Lesson starts from 20:06)</p>\n"
}
] |
2008/10/14
|
[
"https://Stackoverflow.com/questions/202142",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1533/"
] |
I can connect with a user who has permissions to set passwords. I'm able to change attributes, but I can't set the password.
Found some instructions to set the attribute `unicodePwd` to `\UNC:"*password*"`, but it says:
>
> Error: Modify: Unwilling To Perform. <53>
>
>
>
Setting LDAP\_OPT\_ENCRYPT to 1 didn't work either. The port I'm using is 389.
|
Suffix Array and *q*-gram index
-------------------------------
If your strings have a strict upper bound on the size you might consider the use of a [**suffix array**](http://en.wikipedia.org/wiki/Suffix_array): Simply pad all your strings to the same maximum length using a special character (e.g. the null char). Then concatenate all strings and build a suffix array index over them.
This gives you a lookup runtime of *m* \* log *n* where *m* is the length of your query string and *n* is the overall length of your combined strings. If this still isn't good enough and your *m* has a fixed, small length, and your alphabet Σ is restricted in size (say, Σ < 128 different characters) you can additionally build a ***q*-gram index**. This will allow retrieval in **constant time**. However, the *q*-gram table requires Σ*m* entries (= 8 MiB in the case of just 3 characters, and 1 GiB for 4 characters!).
Making the index smaller
------------------------
It might be possible to **reduce the size of the *q*-gram table** (exponentially, in the best case) by adjusting the hash function. Instead of assigning a unique number to every possible *q*-gram you might employ a lossy hash function. The table then would have to store lists of possible suffix array indices instead of just one suffix array entry corresponding to an exact match. This would entail that lookup is no longer constant, though, because all entries in the list would have to be considered.
By the way, I'm not sure if you're familiar with **how a *q*-gram index works** since the Internet isn't helpful on this topic. I've mentioned this before in another topic. I've therefore included a description and an algorithm for the construction in my [bachelor thesis](http://madrat.net/my/bachelor/thesis.pdf).
Proof of concept
----------------
I've written a very small C# proof of concept (since you stated otherwise that you worked with C#). It works, however it is *very* slow for two reasons. First, the suffix array creation simply sorts the suffixes. This alone has runtime *n*2 log *n*. There are far superior methods. Worse, however, is the fact that I use `SubString` to obtain the suffixes. Unfortunately, .NET creates copies of the whole suffix for this. To use this code in practice, make sure that you use in-place methods which do not copy any data around unnecessarily. The same is true for retrieving the *q*-grams from the string.
It would possibly even better to not construct the `m_Data` string used in my example. Instead, you could save a reference to the original array and simulate all my `SubString` accesses by working on this array.
Still, it's easy to see that this implementation has essentially expected constant time retrieval (if the dictionary is well-behaved)! This is quite an achievement that can't possibly be beaten by a search tree/trie!
```
class QGramIndex {
private readonly int m_Maxlen;
private readonly string m_Data;
private readonly int m_Q;
private int[] m_SA;
private Dictionary<string, int> m_Dir = new Dictionary<string, int>();
private struct StrCmp : IComparer<int> {
public readonly String Data;
public StrCmp(string data) { Data = data; }
public int Compare(int x, int y) {
return string.CompareOrdinal(Data.Substring(x), Data.Substring(y));
}
}
private readonly StrCmp cmp;
public QGramIndex(IList<string> strings, int maxlen, int q) {
m_Maxlen = maxlen;
m_Q = q;
var sb = new StringBuilder(strings.Count * maxlen);
foreach (string str in strings)
sb.AppendFormat(str.PadRight(maxlen, '\u0000'));
m_Data = sb.ToString();
cmp = new StrCmp(m_Data);
MakeSuffixArray();
MakeIndex();
}
public int this[string s] { get { return FindInIndex(s); } }
private void MakeSuffixArray() {
// Approx. runtime: n^3 * log n!!!
// But I claim the shortest ever implementation of a suffix array!
m_SA = Enumerable.Range(0, m_Data.Length).ToArray();
Array.Sort(m_SA, cmp);
}
private int FindInArray(int ith) {
return Array.BinarySearch(m_SA, ith, cmp);
}
private int FindInIndex(string s) {
int idx;
if (!m_Dir.TryGetValue(s, out idx))
return -1;
return m_SA[idx] / m_Maxlen;
}
private string QGram(int i) {
return i > m_Data.Length - m_Q ?
m_Data.Substring(i) :
m_Data.Substring(i, m_Q);
}
private void MakeIndex() {
for (int i = 0; i < m_Data.Length; ++i) {
int pos = FindInArray(i);
if (pos < 0) continue;
m_Dir[QGram(i)] = pos;
}
}
}
```
Example of usage:
-----------------
```
static void Main(string[] args) {
var strings = new [] { "hello", "world", "this", "is", "a",
"funny", "test", "which", "i", "have",
"taken", "much", "too", "far", "already" };
var index = new QGramIndex(strings, 10, 3);
var tests = new [] { "xyz", "aki", "ake", "muc", "uch", "too", "fun", "est",
"hic", "ell", "llo", "his" };
foreach (var str in tests) {
int pos = index[str];
if (pos > -1)
Console.WriteLine("\"{0}\" found in \"{1}\".", str, strings[pos]);
else
Console.WriteLine("\"{0}\" not found.", str);
}
}
```
|
202,147 |
<p>Is there a way to start another application from within Compact .Net framework 1.0 similar to </p>
<pre><code>System.Diagnostics.Process.Start
</code></pre>
<p>on the Windows side?</p>
<p>I need to start a CAB file for installation.</p>
|
[
{
"answer_id": 202160,
"author": "Scott Dorman",
"author_id": 1559,
"author_profile": "https://Stackoverflow.com/users/1559",
"pm_score": 4,
"selected": true,
"text": "<p>Treat the share as if it were your source control system. Make the share read-only, which will force developers to get local copies in order to make changes. You then have a somewhat stable version to compare against. This would help facilitate being able to do \"merges\". \"Checking\" code in would have to consist of some sort of backup strategy for the file (possibly making a copy of the file with a timestamp and username as part of the new file name) and replacing the original with the new version.</p>\n\n<p>That being said, doing this type of activity without a real source control system that is reliable is going to be difficult and error-prone.</p>\n"
},
{
"answer_id": 202169,
"author": "Bryan Anderson",
"author_id": 21186,
"author_profile": "https://Stackoverflow.com/users/21186",
"pm_score": 2,
"selected": false,
"text": "<p>You're probably going to have to download something unless you want to do it by hand. I highly recommend <a href=\"http://www.winmerge.org/\" rel=\"nofollow noreferrer\">Winmerge</a>. It's free, open source, and probably better for you a small download that doesn't mess things up.</p>\n"
},
{
"answer_id": 202173,
"author": "Franci Penov",
"author_id": 17028,
"author_profile": "https://Stackoverflow.com/users/17028",
"pm_score": 2,
"selected": false,
"text": "<p>Get git and install it locally on every dev's machine. Then set the repositories to replicate.</p>\n"
},
{
"answer_id": 202182,
"author": "Frank Schmitt",
"author_id": 27951,
"author_profile": "https://Stackoverflow.com/users/27951",
"pm_score": 2,
"selected": false,
"text": "<p>There is a standard unix command-line tool called merge that will fairly intelligently merge two sets of changes to a file. The syntax is:</p>\n\n<pre><code>merge mine older yours\n</code></pre>\n\n<p>Where \"mine\" is the file with your changes, \"older\" is the original file, and \"yours\" contains someone else's changes. </p>\n\n<p>Not sure if you have a UNIX (or Mac OS X) box lying around to do this on though. </p>\n"
},
{
"answer_id": 202183,
"author": "crashmstr",
"author_id": 1441,
"author_profile": "https://Stackoverflow.com/users/1441",
"pm_score": 1,
"selected": false,
"text": "<p>Working off of a shared drive is not a good idea, and gets my vote of \"no confidence\".</p>\n\n<p>It would be too easy to overwrite other's changes, you have no change tracking, no way to branch or tag/label, etc.</p>\n"
},
{
"answer_id": 202187,
"author": "chills42",
"author_id": 23855,
"author_profile": "https://Stackoverflow.com/users/23855",
"pm_score": 2,
"selected": false,
"text": "<p>This might not be a viable option, but perhaps you could use a distributed system like <a href=\"http://bazaar-vcs.org/\" rel=\"nofollow noreferrer\">bazaar</a>, <a href=\"http://git.or.cz/\" rel=\"nofollow noreferrer\">git</a>, or <a href=\"http://www.selenic.com/mercurial/wiki/\" rel=\"nofollow noreferrer\">Mercurial</a>.</p>\n\n<p>The reason I suggest these is that they are very low overhead and can be used with other systems. I know with bazaar the repository is simply a hidden folder added to the directory.</p>\n"
},
{
"answer_id": 202193,
"author": "user8035",
"author_id": 8035,
"author_profile": "https://Stackoverflow.com/users/8035",
"pm_score": 3,
"selected": false,
"text": "<p>Learn to use Harvest. It takes a little effort to get things going smoothly but overall it is an excellent source control system.</p>\n"
},
{
"answer_id": 202211,
"author": "Ralph M. Rickenbach",
"author_id": 4549416,
"author_profile": "https://Stackoverflow.com/users/4549416",
"pm_score": 3,
"selected": false,
"text": "<p>Another possibility would be <a href=\"http://www.scootersoftware.com/\" rel=\"nofollow noreferrer\">Beyond Compare from Scooter</a>. It has two and three way merge and great diff functionality on files and directories. If you want to know a little more about it, listen to <a href=\"http://www.delphi.org/2008/09/episode-7-beyond-compare/\" rel=\"nofollow noreferrer\">the delphi podcast</a> by <a href=\"https://stackoverflow.com/users/255/jim-mckeeth\">Jim McKeith</a>.</p>\n\n<p>But like most others I would recommend to either use Git or learn Harvest.If the source control system allows to change its diff application, Beyond Compare would be an excellent replacement.</p>\n"
},
{
"answer_id": 202581,
"author": "Ed Lucas",
"author_id": 12551,
"author_profile": "https://Stackoverflow.com/users/12551",
"pm_score": 2,
"selected": false,
"text": "<p>There are two distinct issues: version control and merging. There's absolutely no excuse to NOT use a version control system. If the company has decided on a solution (for whatever reason), then use it. Not liking it or not \"having confidence\" in it is not a valid reason for not using it. And using a shared drive to mimic a source code control system is beyond crazy.</p>\n\n<p>Merging is a second issue. You simply need a diff/merge tool. Pick one. How have you gone this long without one?! </p>\n\n<p>Araxis is a great one. Costs a few bucks. The SourceGear folks have been freely distributing their diff/merge tool for some time (the one that comes with Vault). It's also a solid contender. Those are two that I've used that I know are still on the market now. There are others some already have mentioned. </p>\n\n<p>Merging everything by hand is not a tenable solution. Combining that with <em>not</em> using a VCS is a recipe for disaster.</p>\n"
}
] |
2008/10/14
|
[
"https://Stackoverflow.com/questions/202147",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/18169/"
] |
Is there a way to start another application from within Compact .Net framework 1.0 similar to
```
System.Diagnostics.Process.Start
```
on the Windows side?
I need to start a CAB file for installation.
|
Treat the share as if it were your source control system. Make the share read-only, which will force developers to get local copies in order to make changes. You then have a somewhat stable version to compare against. This would help facilitate being able to do "merges". "Checking" code in would have to consist of some sort of backup strategy for the file (possibly making a copy of the file with a timestamp and username as part of the new file name) and replacing the original with the new version.
That being said, doing this type of activity without a real source control system that is reliable is going to be difficult and error-prone.
|
202,197 |
<p>I have a requirement to create a simple database in Access to collect some user data that will be loaded into another database for further reporting. There will be a module in the Access db that when invoked by the user (probably by clicking a button) will output a query to a delimited file. The user also needs a mechanism (for example a form with a button) to easily transfer the file to a remote server, using sftp. Does anyone have an idea of how to accomplish this?</p>
|
[
{
"answer_id": 202269,
"author": "jmatthias",
"author_id": 2768,
"author_profile": "https://Stackoverflow.com/users/2768",
"pm_score": 0,
"selected": false,
"text": "<p>I would imagine you just need to find an FTP COM object. You should then be able to instantiate this in the Access module code. dart.com has one and I'm sure there are many more (just Google FTP COM).</p>\n"
},
{
"answer_id": 202316,
"author": "Mat Nadrofsky",
"author_id": 26853,
"author_profile": "https://Stackoverflow.com/users/26853",
"pm_score": 4,
"selected": true,
"text": "<p>You can simply write a call to the sftp command line client via a batch file if you want to accomplish that.</p>\n\n<p>Check out the Shell() function in VBA.</p>\n\n<p>Under the click event of the button on your form add in the code:</p>\n\n<pre><code>mySFTPCall = \"sftp <insert your options here!>\"\nCall Shell(mySFTPCall, 1)\n</code></pre>\n\n<p>I've used this before to just copy files straight across network shares etc. to share data from an in-house Access DB. Of course you could get more fancy if necessary.</p>\n"
},
{
"answer_id": 202349,
"author": "micahwittman",
"author_id": 11181,
"author_profile": "https://Stackoverflow.com/users/11181",
"pm_score": 0,
"selected": false,
"text": "<p>You could make a shell call to a command line app such as <a href=\"http://www.ipswitchft.com/products/moveit/client/freely/index.asp\" rel=\"nofollow noreferrer\">MOVEit Freely</a>, which is freeware, to script secure ftp transfers. I've used it in the past and it has some nice features and worked quite well.</p>\n\n<blockquote>\n <p><em>MOVEit Freely is a free command line FTP/secure FTP SSL (FTPS) client for Windows Vista Business Edition, 2003, XP, 2000, ME and NT 4.0 systems.</em></p>\n</blockquote>\n"
},
{
"answer_id": 202369,
"author": "Kibbee",
"author_id": 1862,
"author_profile": "https://Stackoverflow.com/users/1862",
"pm_score": 0,
"selected": false,
"text": "<p><a href=\"http://www.chilkatsoft.com/ftp-features.asp\" rel=\"nofollow noreferrer\">Chilkat</a> has an FTP component that works with COM/ActiveX. It says that it supports FTP over SSL (FTPS), which I think is the same as SFTP. I've used some of their other products before for .Net and they have worked very well. They have a free trial, so you having nothing to lose by downloading and checking if they work for you.</p>\n"
},
{
"answer_id": 383118,
"author": "Eugene Mayevski 'Callback",
"author_id": 47961,
"author_profile": "https://Stackoverflow.com/users/47961",
"pm_score": 2,
"selected": false,
"text": "<p>You can use our <a href=\"http://www.eldos.com/sbbdev/activex-sftp.php\" rel=\"nofollow noreferrer\">SFTPBlackbox (ActiveX Edition)</a>. </p>\n"
}
] |
2008/10/14
|
[
"https://Stackoverflow.com/questions/202197",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3734/"
] |
I have a requirement to create a simple database in Access to collect some user data that will be loaded into another database for further reporting. There will be a module in the Access db that when invoked by the user (probably by clicking a button) will output a query to a delimited file. The user also needs a mechanism (for example a form with a button) to easily transfer the file to a remote server, using sftp. Does anyone have an idea of how to accomplish this?
|
You can simply write a call to the sftp command line client via a batch file if you want to accomplish that.
Check out the Shell() function in VBA.
Under the click event of the button on your form add in the code:
```
mySFTPCall = "sftp <insert your options here!>"
Call Shell(mySFTPCall, 1)
```
I've used this before to just copy files straight across network shares etc. to share data from an in-house Access DB. Of course you could get more fancy if necessary.
|
202,198 |
<p>I'm interested in hearing your opinions in which is the best way of implementing a social activity stream (Facebook is the most famous example). Problems/challenges involved are:</p>
<ul>
<li>Different types of activities (posting, commenting ..)</li>
<li>Different types of objects (post, comment, photo ..)</li>
<li>1-n users involved in different roles ("User x replied to User y's comment on User's Z post")</li>
<li>Different views of the same activity item ("you commented .." vs. "your friend x commented" vs. "user x commented .." => 3 representations of a "comment" activity)</li>
</ul>
<p>.. and some more, especially if you take it to a high level of sophistication, as Facebook does, for example, combining several activity items into one ("users x, y and z commented on that photo"</p>
<p>Any thoughts or pointers on patterns, papers, etc on the most flexible, efficient and powerful approaches to implementing such a system, data model, etc. would be appreciated.</p>
<p>Although most of the issues are platform-agnostic, chances are I end up implementing such a system on Ruby on Rails</p>
|
[
{
"answer_id": 202227,
"author": "warren",
"author_id": 4418,
"author_profile": "https://Stackoverflow.com/users/4418",
"pm_score": 2,
"selected": false,
"text": "<p>I think <a href=\"http://plurk.com\" rel=\"nofollow noreferrer\">Plurk's</a> approach is interesting: they supply your entire timeline in a format that looks a lot like Google Finance's stock charts.</p>\n\n<p>It may be worth looking at <a href=\"http://ning.com\" rel=\"nofollow noreferrer\">Ning</a> to see how a social networking network works. The <a href=\"http://developer.ning.com\" rel=\"nofollow noreferrer\">developer</a> pages look especially helpful.</p>\n"
},
{
"answer_id": 204819,
"author": "Tim Howland",
"author_id": 4276,
"author_profile": "https://Stackoverflow.com/users/4276",
"pm_score": 4,
"selected": false,
"text": "<p>The biggest issues with event streams are visibility and performance; you need to restrict the events displayed to be only the interesting ones for that particular user, and you need to keep the amount of time it takes to sort through and identify those events manageable. I've built a smallish social network; I found that at small scales, keeping an \"events\" table in a database works, but that it gets to be a performance problem under moderate load.</p>\n\n<p>With a larger stream of messages and users, it's probably best to go with a messaging system, where events are sent as messages to individual profiles. This means that you can't easily subscribe to people's event streams and see previous events very easily, but you are simply rendering a small group of messages when you need to render the stream for a particular user.</p>\n\n<p>I believe this was Twitter's original design flaw- I remember reading that they were hitting the database to pull in and filter their events. This had everything to do with architecture and nothing to do with Rails, which (unfortunately) gave birth to the \"ruby doesn't scale\" meme. I recently saw a presentation where the developer used Amazon's <a href=\"http://aws.amazon.com/sqs/\" rel=\"noreferrer\">Simple Queue Service</a> as their messaging backend for a twitter-like application that would have far higher scaling capabilities- it may be worth looking into SQS as part of your system, if your loads are high enough.</p>\n"
},
{
"answer_id": 205477,
"author": "heyman",
"author_id": 27406,
"author_profile": "https://Stackoverflow.com/users/27406",
"pm_score": 7,
"selected": false,
"text": "<p>I have created such system and I took this approach:</p>\n\n<p>Database table with the following columns: id, userId, type, data, time.</p>\n\n<ul>\n<li><strong>userId</strong> is the user who generated the activity</li>\n<li><strong>type</strong> is the type of the activity (i.e. Wrote blog post, added photo, commented on user's photo)</li>\n<li><strong>data</strong> is a serialized object with meta-data for the activity where you can put in whatever you want</li>\n</ul>\n\n<p>This limits the searches/lookups, you can do in the feeds, to users, time and activity types, but in a facebook-type activity feed, this isn't really limiting. And with correct indices on the table the lookups are <em>fast</em>.</p>\n\n<p>With this design you would have to decide what metadata each type of event should require. For example a feed activity for a new photo could look something like this:</p>\n\n<pre><code>{id:1, userId:1, type:PHOTO, time:2008-10-15 12:00:00, data:{photoId:2089, photoName:A trip to the beach}}\n</code></pre>\n\n<p>You can see that, although the name of the photo most certainly is stored in some other table containing the photos, and I could retrieve the name from there, I will duplicate the name in the metadata field, because you don't want to do any joins on other database tables if you want speed. And in order to display, say 200, different events from 50 different users, you need speed.</p>\n\n<p>Then I have classes that extends a basic FeedActivity class for rendering the different types of activity entries. Grouping of events would be built in the rendering code as well, to keep away complexity from the database.</p>\n"
},
{
"answer_id": 206386,
"author": "jedediah",
"author_id": 6342,
"author_profile": "https://Stackoverflow.com/users/6342",
"pm_score": 3,
"selected": false,
"text": "<pre>\n// one entry per actual event\nevents {\n id, timestamp, type, data\n}\n\n// one entry per event, per feed containing that event\nevents_feeds {\n event_id, feed_id\n}\n</pre>\n\n<p>When the event is created, decide which feeds it appears in and add those to events_feeds. \nTo get a feed, select from events_feeds, join in events, order by timestamp.\nFiltering and aggregation can then be done on the results of that query.\nWith this model, you can change the event properties after creation with no extra work.</p>\n"
},
{
"answer_id": 302753,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 3,
"selected": false,
"text": "<p>I had a similar approach to that of heyman - a denormalized table containing all of the data that would be displayed in a given activity stream. It works fine for a small site with limited activity.</p>\n\n<p>As mentioned above, it is likely to face scalability issues as the site grows. Personally, I am not worried about the scaling issues right now. I'll worry about that at a later time.</p>\n\n<p>Facebook has obviously done a great job of scaling so I would recommend that you read their engineering blog, as it has a ton of great content -> <a href=\"http://www.facebook.com/notes.php?id=9445547199\" rel=\"noreferrer\">http://www.facebook.com/notes.php?id=9445547199</a></p>\n\n<p>I have been looking into better solutions than the denormalized table I mentioned above. Another way I have found of accomplishing this is to condense all the content that would be in a given activity stream into a single row. It could be stored in XML, JSON, or some serialized format that could be read by your application. The update process would be simple too. Upon activity, place the new activity into a queue (perhaps using Amazon SQS or something else) and then continually poll the queue for the next item. Grab that item, parse it, and place its contents in the appropriate feed object stored in the database.</p>\n\n<p>The good thing about this method is that you only need to read a single database table whenever that particular feed is requested, rather than grabbing a series of tables. Also, it allows you to maintain a finite list of activities as you may pop off the oldest activity item whenever you update the list.</p>\n\n<p>Hope this helps! :)</p>\n"
},
{
"answer_id": 336816,
"author": "Alderete",
"author_id": 11062,
"author_profile": "https://Stackoverflow.com/users/11062",
"pm_score": 3,
"selected": false,
"text": "<p>If you do decide that you're going to implement in Rails, perhaps you will find the following plugin useful:</p>\n\n<p>ActivityStreams: <a href=\"http://github.com/face/activity_streams/tree/master\" rel=\"noreferrer\">http://github.com/face/activity_streams/tree/master</a></p>\n\n<p>If nothing else, you'll get to look at an implementation, both in terms of the data model, as well as the API provided for pushing and pulling activities.</p>\n"
},
{
"answer_id": 352404,
"author": "jammus",
"author_id": 984,
"author_profile": "https://Stackoverflow.com/users/984",
"pm_score": 4,
"selected": false,
"text": "<p>I started to implement a system like this yesterday, here's where I've got to...</p>\n\n<p>I created a <strong>StreamEvent</strong> class with the properties <em>Id</em>, <em>ActorId</em>, <em>TypeId</em>, <em>Date</em>, <em>ObjectId</em> and a hashtable of additional <em>Details</em> key/value pairs. This is represented in the database by a <strong>StreamEvent</strong> table (<em>Id</em>, <em>ActorId</em>, <em>TypeId</em>, <em>Date</em>, <em>ObjectId</em>) and a <strong>StreamEventDetails</strong> table (<em>StreamEventId</em>, <em>DetailKey</em>, <em>DetailValue</em>).</p>\n\n<p>The <em>ActorId</em>, <em>TypeId</em> and <em>ObjectId</em> allow for a Subject-Verb-Object event to be captured (and later queried). Each action may result in several StreamEvent instances being created.</p>\n\n<p>I've then created a sub-class for of StreamEvent each type of event, e.g. <strong>LoginEvent</strong>, <strong>PictureCommentEvent</strong>. Each of these subclasses has more context specific properties such as <em>PictureId</em>, <em>ThumbNail</em>, <em>CommenText</em>, etc (whatever is required for the event) which are actually stored as key/value pairs in the hashtable/StreamEventDetail table.</p>\n\n<p>When pulling these events back from the database I use a factory method (based on the <em>TypeId</em>) to create the correct StreamEvent class.</p>\n\n<p>Each subclass of StreamEvent has a Render(<em>context</em> As <strong>StreamContext</strong>) method which outputs the event to screen based on the passed <strong>StreamContext</strong> class. The StreamContext class allows options to be set based on the context of the view. If you look at Facebook for example your news feed on the homepage lists the fullnames (and links to their profile) of everyone involved in each action, whereas looking a friend's feed you only see their first name (but the full names of other actors).</p>\n\n<p>I haven't implemented a aggregate feed (Facebook home) yet but I imagine I'll create a <strong>AggregateFeed</strong> table which has the fields <em>UserId</em>, <em>StreamEventId</em> which is populated based on some kind of 'Hmmm, you might find this interesting' algorithm.</p>\n\n<p>Any comments would be massively appreciated.</p>\n"
},
{
"answer_id": 1753335,
"author": "Rodrigo",
"author_id": 213432,
"author_profile": "https://Stackoverflow.com/users/213432",
"pm_score": 2,
"selected": false,
"text": "<p>I solved this a few months ago, but I think my implementation is too basic.<br>\nI created the following models:</p>\n\n<pre><code>HISTORY_TYPE\n\nID - The id of the history type\nNAME - The name (type of the history)\nDESCRIPTION - A description\n\nHISTORY_MESSAGES\n\nID\nHISTORY_TYPE - A message of history belongs to a history type\nMESSAGE - The message to print, I put variables to be replaced by the actual values\n\nHISTORY_ACTIVITY\n\nID\nMESSAGE_ID - The message ID to use\nVALUES - The data to use\n</code></pre>\n\n<p>Example</p>\n\n<pre><code>MESSAGE_ID_1 => \"User %{user} created a new entry\"\nACTIVITY_ID_1 => MESSAGE_ID = 1, VALUES = {user: \"Rodrigo\"}\n</code></pre>\n"
},
{
"answer_id": 5022398,
"author": "Mark Kennedy",
"author_id": 286541,
"author_profile": "https://Stackoverflow.com/users/286541",
"pm_score": 7,
"selected": false,
"text": "<p>This is a very good presentation outlining how Etsy.com architected their activity streams. It's the best example I've found on the topic, though it's not rails specific.</p>\n\n<p><a href=\"http://www.slideshare.net/danmckinley/etsy-activity-feeds-architecture\" rel=\"noreferrer\">http://www.slideshare.net/danmckinley/etsy-activity-feeds-architecture</a></p>\n"
},
{
"answer_id": 13171306,
"author": "Rene Pickhardt",
"author_id": 1512538,
"author_profile": "https://Stackoverflow.com/users/1512538",
"pm_score": 4,
"selected": false,
"text": "<p>If you are willing to use a separate software I suggest the Graphity server which exactly solves the problem for activity streams (building on top of neo4j graph data base).</p>\n\n<p>The algorithms have been implemented as a standalone REST server so that you can host your own server to deliver activity streams: <a href=\"http://www.rene-pickhardt.de/graphity-server-for-social-activity-streams-released-gplv3/\">http://www.rene-pickhardt.de/graphity-server-for-social-activity-streams-released-gplv3/</a></p>\n\n<p>In the paper and benchmark I showed that retrieving news streams depends only linear on the amount of items you want to retrieve without any redundancy you would get from denormalizing the data:</p>\n\n<p><a href=\"http://www.rene-pickhardt.de/graphity-an-efficient-graph-model-for-retrieving-the-top-k-news-feeds-for-users-in-social-networks/\">http://www.rene-pickhardt.de/graphity-an-efficient-graph-model-for-retrieving-the-top-k-news-feeds-for-users-in-social-networks/</a></p>\n\n<p>On the above link you find screencasts and a benchmark of this approach (showing that graphity is able to retrieve more than 10k streams per second). </p>\n"
},
{
"answer_id": 16087652,
"author": "Benjamin Crouzier",
"author_id": 311744,
"author_profile": "https://Stackoverflow.com/users/311744",
"pm_score": 3,
"selected": false,
"text": "<p>There are two railscasts about such an activity stream:</p>\n\n<ul>\n<li><a href=\"http://railscasts.com/episodes/406-public-activity\" rel=\"nofollow\">http://railscasts.com/episodes/406-public-activity</a> (An activity feed with the gem <a href=\"https://github.com/pokonski/public_activity\" rel=\"nofollow\">public_activity</a>)</li>\n<li><a href=\"http://railscasts.com/episodes/407-activity-feed-from-scratch\" rel=\"nofollow\">http://railscasts.com/episodes/407-activity-feed-from-scratch</a> (Same thing from scratch)</li>\n</ul>\n\n<p>Those solutions dont include all your requirements, but it should give you some ideas.</p>\n"
},
{
"answer_id": 17182358,
"author": "Mafuba",
"author_id": 256401,
"author_profile": "https://Stackoverflow.com/users/256401",
"pm_score": 2,
"selected": false,
"text": "<p>After implementing activity streams to enable social feeds, microblogging, and collaboration features in several applications, I realized that the base functionality is quite common and could be turned into an external service that you utilize via an API. If you are building the stream into a production application and do not have unique or deeply complex needs, utilizing a proven service may be the best way to go. I would definitely recommend this for production applications over rolling your own simple solution on top of a relational database.</p>\n\n<p>My company Collabinate (<a href=\"http://www.collabinate.com\" rel=\"nofollow\">http://www.collabinate.com</a>) grew out of this realization, and we have implemented a scalable, high performance activity stream engine on top of a graph database to achieve it. We actually utilized a variant of the Graphity algorithm (adapted from the early work of @RenePickhardt who also provided an answer here) to build the engine.</p>\n\n<p>If you want to host the engine yourself or require specialized functionality, the core code is actually open source for non-commercial purposes, so you're welcome to take a look.</p>\n"
},
{
"answer_id": 19683260,
"author": "Thierry",
"author_id": 178343,
"author_profile": "https://Stackoverflow.com/users/178343",
"pm_score": 6,
"selected": false,
"text": "<p>We've open sourced our approach:\n<a href=\"https://github.com/tschellenbach/Stream-Framework\" rel=\"noreferrer\">https://github.com/tschellenbach/Stream-Framework</a>\nIt's currently the largest open source library aimed at solving this problem.</p>\n\n<p>The same team which built Stream Framework also offers a hosted API, which handles the complexity for you. Have a look at <a href=\"https://getstream.io\" rel=\"noreferrer\">getstream.io</a> There are clients available for Node, Python, Rails and PHP.</p>\n\n<p>In addition have a look at this high scalability post were we explain some of the design decisions involved:\n<a href=\"http://highscalability.com/blog/2013/10/28/design-decisions-for-scaling-your-high-traffic-feeds.html\" rel=\"noreferrer\">http://highscalability.com/blog/2013/10/28/design-decisions-for-scaling-your-high-traffic-feeds.html</a></p>\n\n<p><a href=\"http://www.mellowmorning.com/2013/10/18/scalable-pinterest-tutorial-feedly-redis/\" rel=\"noreferrer\">This tutorial</a> will help you setup a system like Pinterest's feed using Redis. It's quite easy to get started with.</p>\n\n<p>To learn more about feed design I highly recommend reading some of the articles which we based Feedly on:</p>\n\n<ul>\n<li><a href=\"http://research.yahoo.com/files/sigmod278-silberstein.pdf\" rel=\"noreferrer\">Yahoo Research Paper</a></li>\n<li><a href=\"http://highscalability.com/blog/2013/7/8/the-architecture-twitter-uses-to-deal-with-150m-active-users.html\" rel=\"noreferrer\">Twitter 2013 Redis based</a>, with fallback</li>\n<li><a href=\"http://planetcassandra.org/blog/post/instagram-making-the-switch-to-cassandra-from-redis-75-instasavings\" rel=\"noreferrer\">Cassandra at Instagram</a></li>\n<li><a href=\"http://www.slideshare.net/danmckinley/etsy-activity-feeds-architecture/\" rel=\"noreferrer\">Etsy feed scaling</a></li>\n<li><a href=\"http://www.infoq.com/presentations/Facebook-Software-Stack\" rel=\"noreferrer\">Facebook history</a></li>\n<li><a href=\"http://django-activity-stream.readthedocs.io/en/latest/\" rel=\"noreferrer\">Django project</a>, with good naming conventions. (But database only)</li>\n<li><a href=\"http://activitystrea.ms/specs/atom/1.0/\" rel=\"noreferrer\">http://activitystrea.ms/specs/atom/1.0/</a> (actor, verb, object, target)</li>\n<li><a href=\"http://www.quora.com/What-are-best-practices-for-building-something-like-a-News-Feed?q=news%20feeds\" rel=\"noreferrer\">Quora post on best practises</a></li>\n<li><a href=\"http://www.quora.com/What-are-the-scaling-issues-to-keep-in-mind-while-developing-a-social-network-feed\" rel=\"noreferrer\">Quora scaling a social network feed</a></li>\n<li><a href=\"http://web.archive.org/web/20130525202810/http://blog.waxman.me/how-to-build-a-fast-news-feed-in-redis\" rel=\"noreferrer\">Redis ruby example</a></li>\n<li><a href=\"http://backchannel.org/blog/friendfeed-schemaless-mysql\" rel=\"noreferrer\">FriendFeed approach</a></li>\n<li><a href=\"http://blog.thoonk.com/\" rel=\"noreferrer\">Thoonk setup</a></li>\n<li><a href=\"http://www.slideshare.net/nkallen/q-con-3770885\" rel=\"noreferrer\">Twitter's Approach</a></li>\n</ul>\n\n<p>Though Stream Framework is Python based it wouldn't be too hard to use from a Ruby app. You could simply run it as a service and stick a small http API in front of it. We are considering adding an API to access Feedly from other languages. At the moment you'll have to role your own though.</p>\n"
}
] |
2008/10/14
|
[
"https://Stackoverflow.com/questions/202198",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] |
I'm interested in hearing your opinions in which is the best way of implementing a social activity stream (Facebook is the most famous example). Problems/challenges involved are:
* Different types of activities (posting, commenting ..)
* Different types of objects (post, comment, photo ..)
* 1-n users involved in different roles ("User x replied to User y's comment on User's Z post")
* Different views of the same activity item ("you commented .." vs. "your friend x commented" vs. "user x commented .." => 3 representations of a "comment" activity)
.. and some more, especially if you take it to a high level of sophistication, as Facebook does, for example, combining several activity items into one ("users x, y and z commented on that photo"
Any thoughts or pointers on patterns, papers, etc on the most flexible, efficient and powerful approaches to implementing such a system, data model, etc. would be appreciated.
Although most of the issues are platform-agnostic, chances are I end up implementing such a system on Ruby on Rails
|
I have created such system and I took this approach:
Database table with the following columns: id, userId, type, data, time.
* **userId** is the user who generated the activity
* **type** is the type of the activity (i.e. Wrote blog post, added photo, commented on user's photo)
* **data** is a serialized object with meta-data for the activity where you can put in whatever you want
This limits the searches/lookups, you can do in the feeds, to users, time and activity types, but in a facebook-type activity feed, this isn't really limiting. And with correct indices on the table the lookups are *fast*.
With this design you would have to decide what metadata each type of event should require. For example a feed activity for a new photo could look something like this:
```
{id:1, userId:1, type:PHOTO, time:2008-10-15 12:00:00, data:{photoId:2089, photoName:A trip to the beach}}
```
You can see that, although the name of the photo most certainly is stored in some other table containing the photos, and I could retrieve the name from there, I will duplicate the name in the metadata field, because you don't want to do any joins on other database tables if you want speed. And in order to display, say 200, different events from 50 different users, you need speed.
Then I have classes that extends a basic FeedActivity class for rendering the different types of activity entries. Grouping of events would be built in the rendering code as well, to keep away complexity from the database.
|
202,205 |
<p>One of the responses to <a href="https://stackoverflow.com/questions/198721/converting-a-word-document-into-usable-html-in-php">a question I asked yesterday</a> suggested that I should make sure my database can handle UTF-8 characters correctly. How I can do this with MySQL?</p>
|
[
{
"answer_id": 202246,
"author": "Owen",
"author_id": 4853,
"author_profile": "https://Stackoverflow.com/users/4853",
"pm_score": 8,
"selected": true,
"text": "<p><strong>Update:</strong> </p>\n\n<p>Short answer - You should almost always be using the <code>utf8mb4</code> charset and <code>utf8mb4_unicode_ci</code> collation.</p>\n\n<p>To alter database:</p>\n\n<pre><code>ALTER DATABASE dbname CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci;\n</code></pre>\n\n<p>See: </p>\n\n<ul>\n<li><p>Aaron's comment on this answer <a href=\"https://stackoverflow.com/questions/202205/how-to-make-mysql-handle-utf-8-properly#comment28222734_202246\">How to make MySQL handle UTF-8 properly</a></p></li>\n<li><p><a href=\"https://stackoverflow.com/questions/766809/whats-the-difference-between-utf8-general-ci-and-utf8-unicode-ci\">What's the difference between utf8_general_ci and utf8_unicode_ci</a></p></li>\n<li><p>Conversion guide: <a href=\"https://dev.mysql.com/doc/refman/5.5/en/charset-unicode-conversion.html\" rel=\"noreferrer\">https://dev.mysql.com/doc/refman/5.5/en/charset-unicode-conversion.html</a></p></li>\n</ul>\n\n<p><strong>Original Answer:</strong></p>\n\n<p>MySQL 4.1 and above has a default character set of UTF-8. You can verify this in your <code>my.cnf</code> file, remember to set <strong>both</strong> client and server (<code>default-character-set</code> and <code>character-set-server</code>).</p>\n\n<p>If you have existing data that you wish to convert to UTF-8, dump your database, and import it back as UTF-8 making sure:</p>\n\n<ul>\n<li>use <code>SET NAMES utf8</code> before you query/insert into the database</li>\n<li>use <code>DEFAULT CHARSET=utf8</code> when creating new tables</li>\n<li>at this point your MySQL client and server should be in UTF-8 (see <code>my.cnf</code>). remember any languages you use (such as PHP) must be UTF-8 as well. Some versions of PHP will use their own MySQL client library, which may not be UTF-8 aware.</li>\n</ul>\n\n<p>If you do want to migrate existing data remember to backup first! Lots of weird choping of data can happen when things don't go as planned!</p>\n\n<p>Some resources:</p>\n\n<ul>\n<li><a href=\"http://www.oreillynet.com/onlamp/blog/2006/01/turning_mysql_data_in_latin1_t.html\" rel=\"noreferrer\">complete UTF-8 migration</a> (cdbaby.com)</li>\n<li>article on <a href=\"http://www.phpwact.org/php/i18n/utf-8\" rel=\"noreferrer\">UTF-8 readiness of php functions</a> (note some of this information is outdated)</li>\n</ul>\n"
},
{
"answer_id": 202248,
"author": "Claudio",
"author_id": 27958,
"author_profile": "https://Stackoverflow.com/users/27958",
"pm_score": -1,
"selected": false,
"text": "<p><code>SET NAMES UTF8</code></p>\n\n<p>This is does the trick</p>\n"
},
{
"answer_id": 202276,
"author": "Javier",
"author_id": 11649,
"author_profile": "https://Stackoverflow.com/users/11649",
"pm_score": 6,
"selected": false,
"text": "<p>To make this 'permanent', in <code>my.cnf</code>:</p>\n\n<pre><code>[client]\ndefault-character-set=utf8\n[mysqld]\ncharacter-set-server = utf8\n</code></pre>\n\n<p>To check, go to the client and show some variables:</p>\n\n<pre><code>SHOW VARIABLES LIKE 'character_set%';\n</code></pre>\n\n<p>Verify that they're all <code>utf8</code>, except <code>..._filesystem</code>, which should be <code>binary</code> and <code>..._dir</code>, that points somewhere in the MySQL installation.</p>\n"
},
{
"answer_id": 202287,
"author": "extraneon",
"author_id": 24582,
"author_profile": "https://Stackoverflow.com/users/24582",
"pm_score": 3,
"selected": false,
"text": "<p>The charset is a property of the database (default) and the table.\nYou can have a look (MySQL commands):</p>\n\n<pre><code>show create database foo; \n> CREATE DATABASE `foo`.`foo` /*!40100 DEFAULT CHARACTER SET latin1 */\n\nshow create table foo.bar;\n> lots of stuff ending with\n> ) ENGINE=InnoDB AUTO_INCREMENT=252 DEFAULT CHARSET=latin1\n</code></pre>\n\n<p>In other words; it's quite easy to check your database charset or change it:</p>\n\n<pre><code>ALTER TABLE `foo`.`bar` CHARACTER SET utf8;\n</code></pre>\n"
},
{
"answer_id": 10673309,
"author": "Vlad Balan",
"author_id": 791250,
"author_profile": "https://Stackoverflow.com/users/791250",
"pm_score": 2,
"selected": false,
"text": "<p>I followed Javier's solution, but I added some different lines in my.cnf:</p>\n\n<pre><code>[myslqd]\nskip-character-set-client-handshake\ncollation_server=utf8_unicode_ci\ncharacter_set_server=utf8 \n</code></pre>\n\n<p>I found this idea here: <a href=\"http://dev.mysql.com/doc/refman/5.0/en/charset-server.html\" rel=\"nofollow\">http://dev.mysql.com/doc/refman/5.0/en/charset-server.html</a> in the first/only user comment on the bottom of the page. He mentions that <em>skip-character-set-client-handshake</em> has some importance.</p>\n"
},
{
"answer_id": 18197185,
"author": "fin",
"author_id": 2676561,
"author_profile": "https://Stackoverflow.com/users/2676561",
"pm_score": -1,
"selected": false,
"text": "<p>Set your database connection to UTF8:</p>\n\n<pre><code> if($handle = @mysql_connect(DB_HOST, DB_USER, DB_PASS)){ \n //set to utf8 encoding\n mysql_set_charset('utf8',$handle);\n }\n</code></pre>\n"
},
{
"answer_id": 29929677,
"author": "T.W.R. Cole",
"author_id": 1536280,
"author_profile": "https://Stackoverflow.com/users/1536280",
"pm_score": 5,
"selected": false,
"text": "<p>MySQL 4.1 and above has a default character set that it calls <code>utf8</code> but which is actually only a subset of UTF-8 (allows only three-byte characters and smaller).</p>\n\n<p>Use <code>utf8mb4</code> as your charset if you want \"full\" UTF-8.</p>\n"
},
{
"answer_id": 30725859,
"author": "Nishant",
"author_id": 4960611,
"author_profile": "https://Stackoverflow.com/users/4960611",
"pm_score": -1,
"selected": false,
"text": "<p>Was able to find a solution. Ran the following as specified at <a href=\"http://technoguider.com/2015/05/utf8-set-up-in-mysql/\" rel=\"nofollow\">http://technoguider.com/2015/05/utf8-set-up-in-mysql/</a></p>\n\n<pre><code>SET NAMES UTF8;\nset collation_server = utf8_general_ci;\nset default-character-set = utf8;\nset init_connect = ’SET NAMES utf8′;\nset character_set_server = utf8;\nset character_set_client = utf8;\n</code></pre>\n"
},
{
"answer_id": 34889966,
"author": "Rick James",
"author_id": 1766831,
"author_profile": "https://Stackoverflow.com/users/1766831",
"pm_score": 4,
"selected": false,
"text": "<p>The short answer: Use <code>utf8mb4</code> in 4 places:</p>\n\n<ul>\n<li>The bytes in your client are utf8, not latin1/cp1251/etc.</li>\n<li><code>SET NAMES utf8mb4</code> or something equivalent when establishing the client's connection to MySQL</li>\n<li><code>CHARACTER SET utf8mb4</code> on all tables/columns -- except columns that are strictly ascii/hex/country_code/zip_code/etc.</li>\n<li><code><meta charset charset=UTF-8></code> if you are outputting to HTML. (Yes the spelling is different here.)</li>\n</ul>\n\n<p><a href=\"http://mysql.rjweb.org/doc.php/charcoll#best_practice\" rel=\"noreferrer\"><em>More info</em></a> ;<br>\n<a href=\"https://stackoverflow.com/questions/279170/utf-8-all-the-way-through\"><em>UTF8 all the way</em></a></p>\n\n<p>The above links provide the \"detailed canonical answer is required to address all the concerns\". -- There is a space limit on this forum.</p>\n\n<p><strong>Edit</strong></p>\n\n<p>In addition to <code>CHARACTER SET utf8mb4</code> containing \"all\" the world's characters, <code>COLLATION utf8mb4_unicode_520_ci</code> is arguable the 'best all-around' collation to use. (There are also Turkish, Spanish, etc, collations for those who want the nuances in those languages.)</p>\n"
},
{
"answer_id": 34892639,
"author": "Vipin Jain",
"author_id": 2153834,
"author_profile": "https://Stackoverflow.com/users/2153834",
"pm_score": -1,
"selected": false,
"text": "<p>Your answer is you can configure by MySql Settings. In My Answer may be something gone out of context but this is also know is help for you.<br>\n <em>how to configure <code>Character Set</code> and <code>Collation</code></em>. </p>\n\n<blockquote>\n <p>For applications that store data using the default MySQL character set\n and collation (<code>latin1, latin1_swedish_ci</code>), no special configuration\n should be needed. If applications require data storage using a\n different character set or collation, you can configure character set\n information several ways:</p>\n</blockquote>\n\n<ul>\n<li><em>Specify character settings per database.</em> For example, applications\nthat use one database might require <code>utf8</code>, whereas applications that\nuse another database might require sjis.</li>\n<li><em>Specify character settings at server startup.</em> This causes the server\nto use the given settings for all applications that do not make other\narrangements.</li>\n<li><em>Specify character settings at configuration time</em>, if you build MySQL\nfrom source. This causes the server to use the given settings for all\napplications, without having to specify them at server startup.</li>\n</ul>\n\n<p>The examples shown here for your question to set utf8 character set , here also set collation for more helpful(<code>utf8_general_ci</code> collation`). </p>\n\n<p><strong>Specify character settings per database</strong> </p>\n\n<pre><code> CREATE DATABASE new_db\n DEFAULT CHARACTER SET utf8\n DEFAULT COLLATE utf8_general_ci;\n</code></pre>\n\n<p><strong>Specify character settings at server startup</strong></p>\n\n<pre><code>[mysqld]\ncharacter-set-server=utf8\ncollation-server=utf8_general_ci\n</code></pre>\n\n<p><strong>Specify character settings at MySQL configuration time</strong></p>\n\n<pre><code>shell> cmake . -DDEFAULT_CHARSET=utf8 \\\n -DDEFAULT_COLLATION=utf8_general_ci\n</code></pre>\n\n<p><em>To see the values of the character set and collation system variables that apply to your connection, use these statements:</em></p>\n\n<pre><code>SHOW VARIABLES LIKE 'character_set%';\nSHOW VARIABLES LIKE 'collation%';\n</code></pre>\n\n<p>This May be lengthy answer but there is all way, you can use. Hopeful my answer is helpful for you. for more information <a href=\"http://dev.mysql.com/doc/refman/5.7/en/charset-applications.html\" rel=\"nofollow\">http://dev.mysql.com/doc/refman/5.7/en/charset-applications.html</a></p>\n"
},
{
"answer_id": 34986985,
"author": "Nyein Aung",
"author_id": 5789774,
"author_profile": "https://Stackoverflow.com/users/5789774",
"pm_score": 2,
"selected": false,
"text": "<p>To change the character set encoding to UTF-8 for the database itself, type the following command at the mysql> prompt. USE <code>ALTER DATABASE</code>.. Replace DBNAME with the database name:</p>\n\n<pre><code>ALTER DATABASE DBNAME CHARACTER SET utf8 COLLATE utf8_general_ci;\n</code></pre>\n\n<p>This is a duplicate of this question <a href=\"https://stackoverflow.com/questions/6115612/how-to-convert-an-entire-mysql-database-characterset-and-collation-to-utf-8/34986915#34986915\">How to convert an entire MySQL database characterset and collation to UTF-8?</a></p>\n"
},
{
"answer_id": 34987675,
"author": "Gaurav Lad",
"author_id": 4587277,
"author_profile": "https://Stackoverflow.com/users/4587277",
"pm_score": 0,
"selected": false,
"text": "<p>Set your <code>database collation</code> to <code>UTF-8</code>\nthen apply <code>table collation</code> to database default.</p>\n"
},
{
"answer_id": 36616316,
"author": "sunil subramanya",
"author_id": 3494644,
"author_profile": "https://Stackoverflow.com/users/3494644",
"pm_score": -1,
"selected": false,
"text": "<p>DATABASE CONNECTION TO UTF-8</p>\n\n<pre><code>$connect = mysql_connect('$localhost','$username','$password') or die(mysql_error());\nmysql_set_charset('utf8',$connect);\nmysql_select_db('$database_name','$connect') or die(mysql_error());\n</code></pre>\n"
},
{
"answer_id": 68782518,
"author": "Øystein Buvik",
"author_id": 5235327,
"author_profile": "https://Stackoverflow.com/users/5235327",
"pm_score": -1,
"selected": false,
"text": "<p>This worked for me:</p>\n<p>mysqli_query($connection, "SET NAMES 'utf8'");</p>\n"
}
] |
2008/10/14
|
[
"https://Stackoverflow.com/questions/202205",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11522/"
] |
One of the responses to [a question I asked yesterday](https://stackoverflow.com/questions/198721/converting-a-word-document-into-usable-html-in-php) suggested that I should make sure my database can handle UTF-8 characters correctly. How I can do this with MySQL?
|
**Update:**
Short answer - You should almost always be using the `utf8mb4` charset and `utf8mb4_unicode_ci` collation.
To alter database:
```
ALTER DATABASE dbname CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci;
```
See:
* Aaron's comment on this answer [How to make MySQL handle UTF-8 properly](https://stackoverflow.com/questions/202205/how-to-make-mysql-handle-utf-8-properly#comment28222734_202246)
* [What's the difference between utf8\_general\_ci and utf8\_unicode\_ci](https://stackoverflow.com/questions/766809/whats-the-difference-between-utf8-general-ci-and-utf8-unicode-ci)
* Conversion guide: <https://dev.mysql.com/doc/refman/5.5/en/charset-unicode-conversion.html>
**Original Answer:**
MySQL 4.1 and above has a default character set of UTF-8. You can verify this in your `my.cnf` file, remember to set **both** client and server (`default-character-set` and `character-set-server`).
If you have existing data that you wish to convert to UTF-8, dump your database, and import it back as UTF-8 making sure:
* use `SET NAMES utf8` before you query/insert into the database
* use `DEFAULT CHARSET=utf8` when creating new tables
* at this point your MySQL client and server should be in UTF-8 (see `my.cnf`). remember any languages you use (such as PHP) must be UTF-8 as well. Some versions of PHP will use their own MySQL client library, which may not be UTF-8 aware.
If you do want to migrate existing data remember to backup first! Lots of weird choping of data can happen when things don't go as planned!
Some resources:
* [complete UTF-8 migration](http://www.oreillynet.com/onlamp/blog/2006/01/turning_mysql_data_in_latin1_t.html) (cdbaby.com)
* article on [UTF-8 readiness of php functions](http://www.phpwact.org/php/i18n/utf-8) (note some of this information is outdated)
|
202,231 |
<p>I need to detect the device resolution automatically, right now I have a global var & hardwire the resolution:</p>
<pre><code>Public gDeviceRes As String = "640"
'Public gDeviceRes As String = "320"
</code></pre>
<p>then recompile for each device, does anyone have a quick snippit of code for this??</p>
|
[
{
"answer_id": 202512,
"author": "ctacke",
"author_id": 13154,
"author_profile": "https://Stackoverflow.com/users/13154",
"pm_score": 4,
"selected": true,
"text": "<p>Depending on your exact needs, you can check the current screen dimensions with <a href=\"http://msdn.microsoft.com/en-us/library/system.windows.forms.screen.primaryscreen.aspx\" rel=\"noreferrer\">Screen.PrimaryScreen</a> or you can P/Invoke <a href=\"http://msdn.microsoft.com/en-us/library/ms929469.aspx\" rel=\"noreferrer\">GetSystemMetrics</a> with SM_CXSCREEN or <a href=\"http://msdn.microsoft.com/en-us/library/ms929295.aspx\" rel=\"noreferrer\">GetDeviceCaps</a> with HORZRES. Vertical dimesions are similarly available.</p>\n"
},
{
"answer_id": 202582,
"author": "Scott Kramer",
"author_id": 3522,
"author_profile": "https://Stackoverflow.com/users/3522",
"pm_score": 2,
"selected": false,
"text": "<p>This did exactly what i needed: </p>\n\n<pre><code> Dim screensize As System.Drawing.Rectangle = Screen.PrimaryScreen.Bounds\n Public gDeviceRes As String = screensize.Height\n</code></pre>\n"
}
] |
2008/10/14
|
[
"https://Stackoverflow.com/questions/202231",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3522/"
] |
I need to detect the device resolution automatically, right now I have a global var & hardwire the resolution:
```
Public gDeviceRes As String = "640"
'Public gDeviceRes As String = "320"
```
then recompile for each device, does anyone have a quick snippit of code for this??
|
Depending on your exact needs, you can check the current screen dimensions with [Screen.PrimaryScreen](http://msdn.microsoft.com/en-us/library/system.windows.forms.screen.primaryscreen.aspx) or you can P/Invoke [GetSystemMetrics](http://msdn.microsoft.com/en-us/library/ms929469.aspx) with SM\_CXSCREEN or [GetDeviceCaps](http://msdn.microsoft.com/en-us/library/ms929295.aspx) with HORZRES. Vertical dimesions are similarly available.
|
202,243 |
<p>I am trying to write a stored procedure which selects columns from a table and adds 2 extra columns to the ResultSet. These 2 extra columns are the result of conversions on a field in the table which is a Datetime field.</p>
<p>The Datetime format field has the following format 'YYYY-MM-DD HH:MM:SS.S'</p>
<p>The 2 additional fields which should be in the following format:</p>
<ol>
<li>DDMMM</li>
<li>HHMMT, where T is 'A' for a.m. and 'P' for p.m.</li>
</ol>
<p>Example: If the data in the field was '2008-10-12 13:19:12.0' then the extracted fields should contain:</p>
<ol>
<li>12OCT</li>
<li>0119P</li>
</ol>
<p>I have tried using CONVERT string formats, but none of the formats match the output I want to get. I am thinking along the lines of extracting the field data via CONVERT and then using REPLACE, but I surely need some help here, as I am no sure.</p>
<p>Could anyone well versed in stored procedures help me out here?
Thanks!</p>
|
[
{
"answer_id": 202284,
"author": "Cade Roux",
"author_id": 18255,
"author_profile": "https://Stackoverflow.com/users/18255",
"pm_score": 4,
"selected": true,
"text": "<p>If dt is your datetime column, then </p>\n\n<p>For 1:</p>\n\n<pre><code>SUBSTRING(CONVERT(varchar, dt, 13), 1, 2)\n + UPPER(SUBSTRING(CONVERT(varchar, dt, 13), 4, 3))\n</code></pre>\n\n<p>For 2:</p>\n\n<pre><code>SUBSTRING(CONVERT(varchar, dt, 100), 13, 2)\n + SUBSTRING(CONVERT(varchar, dt, 100), 16, 3)\n</code></pre>\n"
},
{
"answer_id": 202288,
"author": "StingyJack",
"author_id": 16391,
"author_profile": "https://Stackoverflow.com/users/16391",
"pm_score": 5,
"selected": false,
"text": "<p>Use DATENAME and wrap the logic in a Function, not a Stored Proc</p>\n\n<pre><code>declare @myTime as DateTime\n\nset @myTime = GETDATE()\n\nselect @myTime\n\nselect DATENAME(day, @myTime) + SUBSTRING(UPPER(DATENAME(month, @myTime)), 0,4)\n</code></pre>\n\n<p>Returns \"14OCT\"</p>\n\n<p>Try not to use any Character / String based operations if possible when working with dates. They are numerical (a float) and performance will suffer from those data type conversions. </p>\n\n<p>Dig these handy conversions I have compiled over the years...</p>\n\n<pre><code>/* Common date functions */\n--//This contains common date functions for MSSQL server\n\n/*Getting Parts of a DateTime*/\n --//gets the date only, 20x faster than using Convert/Cast to varchar\n --//this has been especially useful for JOINS\n SELECT (CAST(FLOOR(CAST(GETDATE() as FLOAT)) AS DateTime))\n\n --//gets the time only (date portion is '1900-01-01' and is considered the \"0 time\" of dates in MSSQL, even with the datatype min value of 01/01/1753. \n SELECT (GETDATE() - (CAST(FLOOR(CAST(GETDATE() as FLOAT)) AS DateTime)))\n\n\n/*Relative Dates*/\n--//These are all functions that will calculate a date relative to the current date and time\n /*Current Day*/\n --//now\n SELECT (GETDATE())\n\n --//midnight of today\n SELECT (DATEADD(ms,-4,(DATEADD(dd,DATEDIFF(dd,0,GETDATE()) + 1,0))))\n\n --//Current Hour\n SELECT DATEADD(hh,DATEPART(hh,GETDATE()),CAST(FLOOR(CAST(GETDATE() AS FLOAT)) as DateTime))\n\n --//Current Half-Hour - if its 9:36, this will show 9:30\n SELECT DATEADD(mi,((DATEDIFF(mi,(CAST(FLOOR(CAST(GETDATE() as FLOAT)) as DateTime)), GETDATE())) / 30) * 30,(CAST(FLOOR(CAST(GETDATE() as FLOAT)) as DateTime)))\n\n /*Yearly*/\n --//first datetime of the current year\n SELECT (DATEADD(yy,DATEDIFF(yy,0,GETDATE()),0))\n\n --//last datetime of the current year\n SELECT (DATEADD(ms,-4,(DATEADD(yy,DATEDIFF(yy,0,GETDATE()) + 1,0))))\n\n /*Monthly*/\n --//first datetime of current month\n SELECT (DATEADD(mm,DATEDIFF(mm,0,GETDATE()),0))\n\n --//last datetime of the current month\n SELECT (DATEADD(ms,-4,DATEADD(mm,1,DATEADD(mm,DATEDIFF(mm,0,GETDATE()),0))))\n\n --//first datetime of the previous month\n SELECT (DATEADD(mm,DATEDIFF(mm,0,GETDATE()) -1,0))\n\n --//last datetime of the previous month\n SELECT (DATEADD(ms, -4,DATEADD(mm,DATEDIFF(mm,0,GETDATE()),0)))\n\n /*Weekly*/\n --//previous monday at 12AM\n SELECT (DATEADD(wk,DATEDIFF(wk,0,GETDATE()) -1 ,0))\n\n --//previous friday at 11:59:59 PM\n SELECT (DATEADD(ms,-4,DATEADD(dd,5,DATEADD(wk,DATEDIFF(wk,0,GETDATE()) -1 ,0))))\n\n /*Quarterly*/\n --//first datetime of current quarter\n SELECT (DATEADD(qq,DATEDIFF(qq,0,GETDATE()),0))\n\n --//last datetime of current quarter\n SELECT (DATEADD(ms,-4,DATEADD(qq,DATEDIFF(qq,0,GETDATE()) + 1,0)))\n</code></pre>\n"
},
{
"answer_id": 202314,
"author": "Paul Williams",
"author_id": 27968,
"author_profile": "https://Stackoverflow.com/users/27968",
"pm_score": 0,
"selected": false,
"text": "<p>You're going to need DATEPART here. You can concatenate the results of the DATEPART calls together.</p>\n\n<p>To get the month abbreviations, you might be able to use DATENAME; if that doesn't work for you, you can use a CASE statement on the DATEPART.</p>\n\n<p>DATEPART also works for the time field.</p>\n\n<p>I can think of a couple of ways of getting the AM/PM indicator, including comparing new dates built via DATEPART or calculating the total seconds elapsed in the day and comparing that to known AM/PM thresholds.</p>\n"
},
{
"answer_id": 202343,
"author": "Kibbee",
"author_id": 1862,
"author_profile": "https://Stackoverflow.com/users/1862",
"pm_score": 3,
"selected": false,
"text": "<p>Not answering your question specifically, but isn't that something that should be handled by the presentation layer of your application. Doing it the way you describe creates extra processing on the database end as well as adding extra network traffic (assuming the database exists on a different machine than the application), for something that could be easily computed on the application side, with more rich date processing libraries, as well as being more language agnostic, especially in the case of your first example which contains the abbreviated month name. Anyway the answers others give you should point you in the right direction if you still decide to go this route.</p>\n"
},
{
"answer_id": 202377,
"author": "Joel Coehoorn",
"author_id": 3043,
"author_profile": "https://Stackoverflow.com/users/3043",
"pm_score": 2,
"selected": false,
"text": "<blockquote>\n <p>The Datetime format field has the following format 'YYYY-MM-DD HH:MM:SS.S'</p>\n</blockquote>\n\n<p>That statement is false. That's just how Enterprise Manager or SQL Server chooses to <em>show</em> the date. Internally it's a 8-byte binary value, which is why some of the functions posted by Andrew will work so well.</p>\n\n<p>Kibbee makes a valid point as well, and in a perfect world I would agree with him. However, sometimes you want to bind query results directly to display control or widgets and there's really not a chance to do any formatting. And sometimes the presentation layer lives on a web server that's even busier than the database. With those in mind, it's not necessarily a bad thing to know how to do this in SQL.</p>\n"
},
{
"answer_id": 6368613,
"author": "Davut Gürbüz",
"author_id": 413032,
"author_profile": "https://Stackoverflow.com/users/413032",
"pm_score": 1,
"selected": false,
"text": "<p>Yes Depart is a solution for that but I think this kind of methods are long trips!</p>\n\n<p>SQL SERVER:</p>\n\n<pre><code>SELECT CAST(DATEPART(DD,GETDATE()) AS VARCHAR)+'/'\n+CAST(DATEPART(MM,GETDATE()) AS VARCHAR)\n+'/'+CAST(DATEPART(YYYY,GETDATE()) AS VARCHAR)\n+' '+CAST(DATEPART(HH,GETDATE()) AS VARCHAR)\n+':'+CAST(DATEPART(MI,GETDATE()) AS VARCHAR)\n</code></pre>\n\n<p>Oracle:</p>\n\n<pre><code>Select to_char(sysdate,'DD/MM/YYYY HH24:MI') from dual\n</code></pre>\n\n<p>You may write your own function by this way you can get rid of this mess;</p>\n\n<p><a href=\"http://sql.dzone.com/news/custom-date-formatting-sql-ser\" rel=\"nofollow\">http://sql.dzone.com/news/custom-date-formatting-sql-ser</a></p>\n\n<pre><code>select myshortfun(getdate(),myformat)\nGO\n</code></pre>\n"
},
{
"answer_id": 18985572,
"author": "ch2o",
"author_id": 982488,
"author_profile": "https://Stackoverflow.com/users/982488",
"pm_score": 0,
"selected": false,
"text": "<p>in MS SQL Server you can do:</p>\n\n<p>SET DATEFORMAT ymd</p>\n\n<p>year,\nmonth,\nday,</p>\n"
},
{
"answer_id": 21631065,
"author": "Mark",
"author_id": 3250242,
"author_profile": "https://Stackoverflow.com/users/3250242",
"pm_score": 0,
"selected": false,
"text": "<p>If it's something more specific like <code>DateKey</code> (<code>yyyymmdd</code>) that you need for dimensional models, I suggest something without any casts/converts:</p>\n\n<pre><code>DECLARE @DateKeyToday int = (SELECT 10000 * DATEPART(yy,GETDATE()) + 100 * DATEPART(mm,GETDATE()) + DATEPART(dd,GETDATE()));\nPRINT @DateKeyToday\n</code></pre>\n"
},
{
"answer_id": 28683330,
"author": "Pawel Cioch",
"author_id": 1818723,
"author_profile": "https://Stackoverflow.com/users/1818723",
"pm_score": 0,
"selected": false,
"text": "<p>I'm adding this answer (for myself) as relevant to custom formatting. </p>\n\n<p>For underscore yyyy_MM_dd </p>\n\n<pre><code>REPLACE(SUBSTRING(CONVERT(VARCHAR, @dt, 120), 1, 10),'-','_')\n</code></pre>\n"
},
{
"answer_id": 38428513,
"author": "Mehdi",
"author_id": 1010619,
"author_profile": "https://Stackoverflow.com/users/1010619",
"pm_score": 4,
"selected": false,
"text": "<p>You can use the following command in SQL server to make it:</p>\n\n<pre><code>select FORMAT(getdate(), N'yyyy-MM-ddThh:mm:ss')\n</code></pre>\n"
}
] |
2008/10/14
|
[
"https://Stackoverflow.com/questions/202243",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1311/"
] |
I am trying to write a stored procedure which selects columns from a table and adds 2 extra columns to the ResultSet. These 2 extra columns are the result of conversions on a field in the table which is a Datetime field.
The Datetime format field has the following format 'YYYY-MM-DD HH:MM:SS.S'
The 2 additional fields which should be in the following format:
1. DDMMM
2. HHMMT, where T is 'A' for a.m. and 'P' for p.m.
Example: If the data in the field was '2008-10-12 13:19:12.0' then the extracted fields should contain:
1. 12OCT
2. 0119P
I have tried using CONVERT string formats, but none of the formats match the output I want to get. I am thinking along the lines of extracting the field data via CONVERT and then using REPLACE, but I surely need some help here, as I am no sure.
Could anyone well versed in stored procedures help me out here?
Thanks!
|
If dt is your datetime column, then
For 1:
```
SUBSTRING(CONVERT(varchar, dt, 13), 1, 2)
+ UPPER(SUBSTRING(CONVERT(varchar, dt, 13), 4, 3))
```
For 2:
```
SUBSTRING(CONVERT(varchar, dt, 100), 13, 2)
+ SUBSTRING(CONVERT(varchar, dt, 100), 16, 3)
```
|
202,245 |
<p>I'm looking for a way to sequentially number rows in a <em>result set</em> (not a table). In essence, I'm starting with a query like the following:</p>
<pre><code>SELECT id, name FROM people WHERE name = 'Spiewak'
</code></pre>
<p>The <code>id</code>s are obviously not a true sequence (e.g. <code>1, 2, 3, 4</code>). What I need is another column in the result set which contains these auto-numberings. I'm willing to use a SQL function if I have to, but I would rather do it without using extensions on the ANSI spec.</p>
<p>Platform is MySQL, but the technique should be cross-platform if at all possible (hence the desire to avoid non-standard extensions).</p>
|
[
{
"answer_id": 202261,
"author": "Cade Roux",
"author_id": 18255,
"author_profile": "https://Stackoverflow.com/users/18255",
"pm_score": 2,
"selected": false,
"text": "<p>There is no ANSI-standard way to do this of which I am aware.</p>\n\n<p>In SQL Server you have a ROW_NUMBER() function which can be used and in Oracle, there is a ROWNUM pseudo column.</p>\n\n<p>In MySQL, there is <a href=\"http://squeejee.com/articles/9-mysql-oracle-rownum\" rel=\"nofollow noreferrer\">this technique</a></p>\n"
},
{
"answer_id": 202265,
"author": "Joel Coehoorn",
"author_id": 3043,
"author_profile": "https://Stackoverflow.com/users/3043",
"pm_score": 4,
"selected": true,
"text": "<p>To have a meaningful row number you need to order your results. Then you can do something like this:</p>\n\n<pre><code>SELECT id, name\n , (SELECT COUNT(*) FROM people p2 WHERE name='Spiewak' AND p2.id <= p1.id) AS RowNumber\nFROM people p1\nWHERE name = 'Spiewak'\nORDER BY id\n</code></pre>\n\n<p>Note that the WHERE clause of the sub query needs to match the WHERE clause or the primary key from the main query <em>and</em> the ORDER BY of the main query.</p>\n\n<p>SQL Server has the ROW_NUMBER() OVER construct to simplify this, but I don't know if MySQL has anything special to address it.</p>\n\n<hr>\n\n<p>Since my post here was accepted as the answer, I want to also call out Dan Goldstein's response, which is very similar in approach but uses a JOIN instead of a sub query and will often perform better </p>\n"
},
{
"answer_id": 202270,
"author": "BoltBait",
"author_id": 20848,
"author_profile": "https://Stackoverflow.com/users/20848",
"pm_score": 2,
"selected": false,
"text": "<p>This page should give you a standard SQL way of doing it:</p>\n<p><a href=\"https://www.sqlteam.com/articles/returning-a-row-number-in-a-query\" rel=\"nofollow noreferrer\">https://www.sqlteam.com/articles/returning-a-row-number-in-a-query</a></p>\n<p>Hope this helps.</p>\n"
},
{
"answer_id": 202275,
"author": "Claudio",
"author_id": 27958,
"author_profile": "https://Stackoverflow.com/users/27958",
"pm_score": 3,
"selected": false,
"text": "<p>AFAIK, there's no \"standard\" way.</p>\n\n<p>MS SQL Server has row_number(), which MySQL has not.</p>\n\n<p>The simplest way to do this in MySQL is </p>\n\n<p><code>SELECT a.*, @num := @num + 1 b from test a, (SELECT @num := 0) d;</code></p>\n\n<p>Source: comments in <a href=\"http://www.xaprb.com/blog/2006/12/02/how-to-number-rows-in-mysql/\" rel=\"noreferrer\">http://www.xaprb.com/blog/2006/12/02/how-to-number-rows-in-mysql/</a></p>\n"
},
{
"answer_id": 202278,
"author": "Dan Goldstein",
"author_id": 23427,
"author_profile": "https://Stackoverflow.com/users/23427",
"pm_score": 3,
"selected": false,
"text": "<p>One idea that is pretty inefficient but is ANSI SQL would be to count the number of rows with a lesser id matching the same criteria. I haven't tested this SQL and it probably won't work, but something like: </p>\n\n<pre><code>SELECT id, name, sub.lcount\nFROM people outer\nJOIN (SELECT id, COUNT(id) lcount FROM people WHERE name = 'Spiewak' AND id < outer.id GROUP BY id) sub on outer.id = sub.id\nWHERE name = 'Spiewak'\n</code></pre>\n"
},
{
"answer_id": 3470394,
"author": "Peter Johnson",
"author_id": 339280,
"author_profile": "https://Stackoverflow.com/users/339280",
"pm_score": 2,
"selected": false,
"text": "<pre><code>SELECT @i:=@i+1 AS iterator, t.*\nFROM tablename t,(SELECT @i:=0) foo\n</code></pre>\n"
},
{
"answer_id": 8056028,
"author": "jsutSomeRandonAnswer",
"author_id": 1036325,
"author_profile": "https://Stackoverflow.com/users/1036325",
"pm_score": 2,
"selected": false,
"text": "<p>In oracle the only database I know what you would want to do is do a sub select on the data</p>\n\n<p>i.e.</p>\n\n<pre><code>select rownum, id , blah, blah\nfrom (\nselect id, name FROM people WHERE name = 'Spiewak'\n)\n</code></pre>\n\n<p>the basic concept is that the rownum will be evaluated on the result set returned from the inner select.</p>\n\n<p>I hope this might point you to a solution that you can use.</p>\n"
},
{
"answer_id": 16679882,
"author": "Code Cavalier",
"author_id": 2125476,
"author_profile": "https://Stackoverflow.com/users/2125476",
"pm_score": 1,
"selected": false,
"text": "<p>I know this is an old thread, but I was just now looking for this answer. I tried Dan Goldstein's query in MySQL, but it didn't work as written because 'outer' is a reserved word. Then, I noticed that it is still using a sub-query, anyways.</p>\n\n<p>So, I figured out a version using JOIN, but NO sub-query:</p>\n\n<pre><code> SELECT SUM(IF(p1.id > p2.id, 0, 1)) AS `row`, p2.id, p2.name\n FROM people p1 JOIN people p2 ON p1.name = p2.name\n WHERE p1.name = 'Spiewak'\n GROUP BY p2.id\n</code></pre>\n\n<p>This worked for me in MySQL 5.1. For MySQL, it seems to be enough to GROUP BY p2.id. An explicit ORDER BY p2.id can be added to the end of the query, but I got the same results, either way.</p>\n"
},
{
"answer_id": 67137995,
"author": "k0L1081",
"author_id": 8875079,
"author_profile": "https://Stackoverflow.com/users/8875079",
"pm_score": 1,
"selected": false,
"text": "<p>Recent answer to question but I believe window functions are now standard for ANSI SQL or, at least, most current SQL flavors. Therefore, use the ROW_NUMBER() function.</p>\n<pre><code>SELECT\n p.ROW_NUMBER() over (order by id) as 'row_id',\n p.id as 'id',\n p.name as 'name'\nFROM\n people p\nWHERE\n p.name = 'Spiewak'\n</code></pre>\n"
}
] |
2008/10/14
|
[
"https://Stackoverflow.com/questions/202245",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9815/"
] |
I'm looking for a way to sequentially number rows in a *result set* (not a table). In essence, I'm starting with a query like the following:
```
SELECT id, name FROM people WHERE name = 'Spiewak'
```
The `id`s are obviously not a true sequence (e.g. `1, 2, 3, 4`). What I need is another column in the result set which contains these auto-numberings. I'm willing to use a SQL function if I have to, but I would rather do it without using extensions on the ANSI spec.
Platform is MySQL, but the technique should be cross-platform if at all possible (hence the desire to avoid non-standard extensions).
|
To have a meaningful row number you need to order your results. Then you can do something like this:
```
SELECT id, name
, (SELECT COUNT(*) FROM people p2 WHERE name='Spiewak' AND p2.id <= p1.id) AS RowNumber
FROM people p1
WHERE name = 'Spiewak'
ORDER BY id
```
Note that the WHERE clause of the sub query needs to match the WHERE clause or the primary key from the main query *and* the ORDER BY of the main query.
SQL Server has the ROW\_NUMBER() OVER construct to simplify this, but I don't know if MySQL has anything special to address it.
---
Since my post here was accepted as the answer, I want to also call out Dan Goldstein's response, which is very similar in approach but uses a JOIN instead of a sub query and will often perform better
|
202,253 |
<p>I'm using Eclipse 3.4 and Tomcat 5.5 and I have a Dynamic Web Project set up. I can access it from <a href="http://127.0.0.1:8080/project/" rel="noreferrer">http://127.0.0.1:8080/project/</a> but by default it serves files from WebContent folder. The real files, that I want to serve, can be found under folder named "share". This folder comes from CVS so I'd like to use it with its given name instead of renaming it. How can this be done?</p>
|
[
{
"answer_id": 202303,
"author": "anjanb",
"author_id": 11142,
"author_profile": "https://Stackoverflow.com/users/11142",
"pm_score": 2,
"selected": false,
"text": "<p>if you're running windows, use the junction utility from MS : <a href=\"http://technet.microsoft.com/en-us/sysinternals/bb896768.aspx\" rel=\"nofollow noreferrer\">http://technet.microsoft.com/en-us/sysinternals/bb896768.aspx</a> and map your share directory to the Webcontent folder. I've regularly done several of these mappings quite regularly.</p>\n"
},
{
"answer_id": 202391,
"author": "matt b",
"author_id": 4249,
"author_profile": "https://Stackoverflow.com/users/4249",
"pm_score": 4,
"selected": true,
"text": "<p>In the project folder, there should be a file under the <code>.settings</code> folder named <code>org.eclipse.wst.common.component</code> that contains an XML fragment like this:</p>\n\n<pre><code><wb-module deploy-name=\"WebProjectName\">\n <wb-resource deploy-path=\"/\" source-path=\"/WebContent\"/>\n <wb-resource deploy-path=\"/WEB-INF/classes\" source-path=\"/src\"/>\n</code></pre>\n\n<p>You should be able to change the source-path under <code>wb-resource</code> to your share folder. I'd make these changes with the Eclipse project closed to be safe.</p>\n\n<p>This is a setting that you pick when you first create the Dynamic Web Project in Eclipse - I can't find how to change the value in an existing project thru Eclipse itself.</p>\n\n<p>If you want the share folder to be mapped to a different path when deployed, such as <code>/share/</code> in your webapp, you can probably just add another wb-resource element.</p>\n"
},
{
"answer_id": 5646861,
"author": "user705663",
"author_id": 705663,
"author_profile": "https://Stackoverflow.com/users/705663",
"pm_score": 2,
"selected": false,
"text": "<p>Can be done through Eclipse, no need to manually edit .settings files.</p>\n\n<p>In Eclipse 3.6 (and possibly earlier releases), </p>\n\n<ol>\n<li>right click on your project</li>\n<li>click on properties</li>\n<li>Click on 'Deployment Assembly'</li>\n<li>Add... Folder -> Next</li>\n<li>Navigate to source folder</li>\n<li>Finish</li>\n</ol>\n"
},
{
"answer_id": 11969842,
"author": "Adugna",
"author_id": 936387,
"author_profile": "https://Stackoverflow.com/users/936387",
"pm_score": 0,
"selected": false,
"text": "<p>On STS 2.5.1 </p>\n\n<ol>\n<li>right click on your project</li>\n<li>click on properties</li>\n<li>Click on 'Java Build path'</li>\n<li>Click \"Source\" tab</li>\n<li>Navigate to default out put folder</li>\n<li>Browse and add your path</li>\n<li>Finish</li>\n</ol>\n"
},
{
"answer_id": 29397568,
"author": "Vinay Taneja",
"author_id": 3699577,
"author_profile": "https://Stackoverflow.com/users/3699577",
"pm_score": 0,
"selected": false,
"text": "<p>you can specify location of webcontent in R-click on project > Properties > Deployment Assembly</p>\n\n<p>This is what I did in mys STS, you can add or remove a location.</p>\n"
}
] |
2008/10/14
|
[
"https://Stackoverflow.com/questions/202253",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/27736/"
] |
I'm using Eclipse 3.4 and Tomcat 5.5 and I have a Dynamic Web Project set up. I can access it from <http://127.0.0.1:8080/project/> but by default it serves files from WebContent folder. The real files, that I want to serve, can be found under folder named "share". This folder comes from CVS so I'd like to use it with its given name instead of renaming it. How can this be done?
|
In the project folder, there should be a file under the `.settings` folder named `org.eclipse.wst.common.component` that contains an XML fragment like this:
```
<wb-module deploy-name="WebProjectName">
<wb-resource deploy-path="/" source-path="/WebContent"/>
<wb-resource deploy-path="/WEB-INF/classes" source-path="/src"/>
```
You should be able to change the source-path under `wb-resource` to your share folder. I'd make these changes with the Eclipse project closed to be safe.
This is a setting that you pick when you first create the Dynamic Web Project in Eclipse - I can't find how to change the value in an existing project thru Eclipse itself.
If you want the share folder to be mapped to a different path when deployed, such as `/share/` in your webapp, you can probably just add another wb-resource element.
|
202,271 |
<p>The following code will not compile:</p>
<pre><code>string foo = "bar";
Object o = foo == null ? DBNull.Value : foo;
</code></pre>
<p>I get: <em>Error 1 Type of conditional expression cannot be determined because there is no implicit conversion between 'System.DBNull' and 'string'</em></p>
<p>To fix this, I must do something like this:</p>
<pre><code>string foo = "bar";
Object o = foo == null ? DBNull.Value : (Object)foo;
</code></pre>
<p>This cast seems pointless as this is certainly legal:</p>
<pre><code>string foo = "bar";
Object o = foo == null ? "gork" : foo;
</code></pre>
<p>It seems to me that when the ternary branches are of different types, the compiler will not autobox the values to the type object...but when they are of the same type then the autoboxing is automatic.</p>
<p>In my mind the first statement should be legal...</p>
<p>Can anyone describe why the compiler does not allow this and why the designers of C# chose to do this? I believe this is legal in Java...Though I have not verified this.</p>
<p>Thanks.</p>
<p><strong>EDIT:</strong> I am asking for an understanding of why Java and C# handle this differently, what is going on underneath the scenes in C# that make this invalid. I know how to use ternary, and am not looking for a "better way" to code the examples. I understand the rules of ternary in C#, but I want to know WHY...</p>
<p><strong>EDIT</strong> (Jon Skeet): Removed "autoboxing" tag as no boxing is involved in this question.</p>
|
[
{
"answer_id": 202281,
"author": "Keith",
"author_id": 905,
"author_profile": "https://Stackoverflow.com/users/905",
"pm_score": 4,
"selected": false,
"text": "<p><code>DBNull.Value</code> returns type <code>DBNull</code>.</p>\n\n<p>You want the type to be <code>string</code>.</p>\n\n<p>While <code>string</code> can be <code>null</code> it cannot be a <code>DBNull</code>.</p>\n\n<p>In your code the statement on the right of the equals executes before assignment to the object.</p>\n\n<p>Basically if you use:</p>\n\n<pre><code>[condition] ? true value : false value;\n</code></pre>\n\n<p>In .Net both the true and false options need to be implicitly convertible to the same type, before whatever you assign them to.</p>\n\n<p>This is a result of how C# deals with type-safety. For instance the following is valid:</p>\n\n<pre><code>string item = \"item\";\n\nvar test = item != null ? item : \"BLANK\";\n</code></pre>\n\n<p>C#3 doesn't support dynamic types, so what is test? In C# every assignment is also a statement with a return value, so although the <code>var</code> construct is new in C#3 the statement on the right of the equals always has to resolve to a single type.</p>\n\n<p>In C#4 and above you can explicitly support dynamic types, but I don't think that helps here.</p>\n"
},
{
"answer_id": 202296,
"author": "Jon Skeet",
"author_id": 22656,
"author_profile": "https://Stackoverflow.com/users/22656",
"pm_score": 6,
"selected": false,
"text": "<p>The compiler requires that either the types of second and third operands are the same, or that one is implicitly convertible to the other. In your case, the types are DBNull and string, neither of which is implicitly convertible to the other. Casting either of them to object solves that.</p>\n\n<p>EDIT: Looks like it is indeed legal in Java. Quite how it works out what to do when it comes to method overloading, I'm not sure... I've just looked at the JLS, and it's extremely unclear about what the type of the conditional is when there are two incompatible reference types involved. The C# way of working may be more irritating occasionally, but it's clearer IMO.</p>\n\n<p>The relevant section of the C# 3.0 spec is 7.13, the conditional operator:</p>\n\n<blockquote>\n <p>The second and third operands of the\n ?: operator control the type of the\n conditional expression. Let X and Y be\n the types of the second and third\n operands. Then,</p>\n \n <ul>\n <li>If X and Y are the same type, then this is the type of the conditional</li>\n <li>Otherwise, if an implicit conversion (§6.1) exists from X to Y,\n but not from Y to X, then Y is the\n type of the conditional expression.</li>\n <li>Otherwise, if an implicit conversion (§6.1) exists from Y to X,\n but not from X to Y, then X is the\n type of the conditional expression.</li>\n <li>Otherwise, no expression type can be determined, and a compile-time\n error occurs.</li>\n </ul>\n</blockquote>\n"
},
{
"answer_id": 202382,
"author": "Konrad Rudolph",
"author_id": 1968,
"author_profile": "https://Stackoverflow.com/users/1968",
"pm_score": 3,
"selected": false,
"text": "<p>By the way, your code is a special case that doesn't have to use the conditional operator at all. Instead, the null coalesce operator is more appropriate (but still requires casting):</p>\n\n<pre><code>object result = (object)foo ?? DBNull.Value;\n</code></pre>\n"
}
] |
2008/10/14
|
[
"https://Stackoverflow.com/questions/202271",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1638/"
] |
The following code will not compile:
```
string foo = "bar";
Object o = foo == null ? DBNull.Value : foo;
```
I get: *Error 1 Type of conditional expression cannot be determined because there is no implicit conversion between 'System.DBNull' and 'string'*
To fix this, I must do something like this:
```
string foo = "bar";
Object o = foo == null ? DBNull.Value : (Object)foo;
```
This cast seems pointless as this is certainly legal:
```
string foo = "bar";
Object o = foo == null ? "gork" : foo;
```
It seems to me that when the ternary branches are of different types, the compiler will not autobox the values to the type object...but when they are of the same type then the autoboxing is automatic.
In my mind the first statement should be legal...
Can anyone describe why the compiler does not allow this and why the designers of C# chose to do this? I believe this is legal in Java...Though I have not verified this.
Thanks.
**EDIT:** I am asking for an understanding of why Java and C# handle this differently, what is going on underneath the scenes in C# that make this invalid. I know how to use ternary, and am not looking for a "better way" to code the examples. I understand the rules of ternary in C#, but I want to know WHY...
**EDIT** (Jon Skeet): Removed "autoboxing" tag as no boxing is involved in this question.
|
The compiler requires that either the types of second and third operands are the same, or that one is implicitly convertible to the other. In your case, the types are DBNull and string, neither of which is implicitly convertible to the other. Casting either of them to object solves that.
EDIT: Looks like it is indeed legal in Java. Quite how it works out what to do when it comes to method overloading, I'm not sure... I've just looked at the JLS, and it's extremely unclear about what the type of the conditional is when there are two incompatible reference types involved. The C# way of working may be more irritating occasionally, but it's clearer IMO.
The relevant section of the C# 3.0 spec is 7.13, the conditional operator:
>
> The second and third operands of the
> ?: operator control the type of the
> conditional expression. Let X and Y be
> the types of the second and third
> operands. Then,
>
>
> * If X and Y are the same type, then this is the type of the conditional
> * Otherwise, if an implicit conversion (§6.1) exists from X to Y,
> but not from Y to X, then Y is the
> type of the conditional expression.
> * Otherwise, if an implicit conversion (§6.1) exists from Y to X,
> but not from X to Y, then X is the
> type of the conditional expression.
> * Otherwise, no expression type can be determined, and a compile-time
> error occurs.
>
>
>
|
202,273 |
<p>I can currently to the following:</p>
<pre><code>class SubClass extends SuperClass {
function __construct() {
parent::__construct();
}
}
class SuperClass {
function __construct() {
// this echoes "I'm SubClass and I'm extending SuperClass"
echo 'I\'m '.get_class($this).' and I\'m extending '.__CLASS__;
}
}
</code></pre>
<p>I would like to do something similar with the filenames (<code>__FILE__</code>, but dynamically evaluated); I would like to know what file the subclass resides in, from the superclass. Is it possible in any elegant way?</p>
<p>I know you could do something with <a href="http://fi.php.net/get_included_files" rel="nofollow noreferrer"><code>get_included_files()</code></a>, but that's not very efficient, especially if I have numerous instances.</p>
|
[
{
"answer_id": 202308,
"author": "Peter Bailey",
"author_id": 8815,
"author_profile": "https://Stackoverflow.com/users/8815",
"pm_score": 0,
"selected": false,
"text": "<p>Uh, not really, that I can think of. Each subclass would need to have an explicitly implemented method that returned <code>__FILE__</code>, which completely defeats the point of inheritance in the first place.</p>\n\n<p>I'm also really curious as to why something like this would be useful. </p>\n"
},
{
"answer_id": 202687,
"author": "user27987",
"author_id": 27987,
"author_profile": "https://Stackoverflow.com/users/27987",
"pm_score": 3,
"selected": true,
"text": "<p>You can use Reflection.</p>\n\n<pre><code>$ref = new ReflectionObject($this);\n$ref->getFileName(); // return the file where the object's class was declared\n</code></pre>\n"
}
] |
2008/10/14
|
[
"https://Stackoverflow.com/questions/202273",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2238/"
] |
I can currently to the following:
```
class SubClass extends SuperClass {
function __construct() {
parent::__construct();
}
}
class SuperClass {
function __construct() {
// this echoes "I'm SubClass and I'm extending SuperClass"
echo 'I\'m '.get_class($this).' and I\'m extending '.__CLASS__;
}
}
```
I would like to do something similar with the filenames (`__FILE__`, but dynamically evaluated); I would like to know what file the subclass resides in, from the superclass. Is it possible in any elegant way?
I know you could do something with [`get_included_files()`](http://fi.php.net/get_included_files), but that's not very efficient, especially if I have numerous instances.
|
You can use Reflection.
```
$ref = new ReflectionObject($this);
$ref->getFileName(); // return the file where the object's class was declared
```
|
202,302 |
<p>How can you round <em>any</em> number (not just integers > 0) to N significant digits?</p>
<p>For example, if I want to round to three significant digits, I'm looking for a formula that could take:</p>
<p>1,239,451 and return 1,240,000</p>
<p>12.1257 and return 12.1</p>
<p>.0681 and return .0681</p>
<p>5 and return 5</p>
<p>Naturally the algorithm should not be hard-coded to only handle N of 3, although that would be a start.</p>
|
[
{
"answer_id": 202336,
"author": "Claudiu",
"author_id": 15055,
"author_profile": "https://Stackoverflow.com/users/15055",
"pm_score": 4,
"selected": false,
"text": "<p>SUMMARY:</p>\n\n<pre><code>double roundit(double num, double N)\n{\n double d = log10(num);\n double power;\n if (num > 0)\n {\n d = ceil(d);\n power = -(d-N);\n }\n else\n {\n d = floor(d); \n power = -(d-N);\n }\n\n return (int)(num * pow(10.0, power) + 0.5) * pow(10.0, -power);\n}\n</code></pre>\n\n<hr>\n\n<p>So you need to find the decimal place of the first non-zero digit, then save the next N-1 digits, then round the Nth digit based on the rest.</p>\n\n<p>We can use log to do the first.</p>\n\n<pre><code>log 1239451 = 6.09\nlog 12.1257 = 1.08\nlog 0.0681 = -1.16\n</code></pre>\n\n<p>So for numbers > 0, take the ceil of the log. For numbers < 0, take the floor of the log.</p>\n\n<p>Now we have the digit <code>d</code>: 7 in the first case, 2 in the 2nd, -2 in the 3rd.</p>\n\n<p>We have to round the <code>(d-N)</code>th digit. Something like:</p>\n\n<pre><code>double roundedrest = num * pow(10, -(d-N));\n\npow(1239451, -4) = 123.9451\npow(12.1257, 1) = 121.257\npow(0.0681, 4) = 681\n</code></pre>\n\n<p>Then do the standard rounding thing:</p>\n\n<pre><code>roundedrest = (int)(roundedrest + 0.5);\n</code></pre>\n\n<p>And undo the pow.</p>\n\n<pre><code>roundednum = pow(roundedrest, -(power))\n</code></pre>\n\n<p>Where power is the power calculated above.</p>\n\n<hr>\n\n<p>About accuracy: Pyrolistical's answer is indeed closer to the real result. But note that you can't represent 12.1 exactly in any case. If you print the answers as follows:</p>\n\n<pre><code>System.out.println(new BigDecimal(n));\n</code></pre>\n\n<p>The answers are:</p>\n\n<pre><code>Pyro's: 12.0999999999999996447286321199499070644378662109375\nMine: 12.10000000000000142108547152020037174224853515625\nPrinting 12.1 directly: 12.0999999999999996447286321199499070644378662109375\n</code></pre>\n\n<p>So, use Pyro's answer!</p>\n"
},
{
"answer_id": 202360,
"author": "Mark Bessey",
"author_id": 17826,
"author_profile": "https://Stackoverflow.com/users/17826",
"pm_score": 1,
"selected": false,
"text": "<p>Have you tried just coding it up the way you'd do it by hand?</p>\n\n<ol>\n<li>Convert the number to a string</li>\n<li>Starting at the beginning of the\nstring, count digits - leading zeroes aren't\nsignificant, everything else is.</li>\n<li>When you get to the \"nth\" digit,\npeek ahead at the next digit and if\nit's 5 or higher, round up.</li>\n<li>Replace all of the trailing digits with zeroes.</li>\n</ol>\n"
},
{
"answer_id": 202476,
"author": "Ates Goral",
"author_id": 23501,
"author_profile": "https://Stackoverflow.com/users/23501",
"pm_score": 4,
"selected": false,
"text": "<p>Here's a short and sweet JavaScript implementation:</p>\n\n<pre><code>function sigFigs(n, sig) {\n var mult = Math.pow(10, sig - Math.floor(Math.log(n) / Math.LN10) - 1);\n return Math.round(n * mult) / mult;\n}\n\nalert(sigFigs(1234567, 3)); // Gives 1230000\nalert(sigFigs(0.06805, 3)); // Gives 0.0681\nalert(sigFigs(5, 3)); // Gives 5\n</code></pre>\n"
},
{
"answer_id": 730518,
"author": "Justin Wignall",
"author_id": 42774,
"author_profile": "https://Stackoverflow.com/users/42774",
"pm_score": 4,
"selected": false,
"text": "<p>Isn't the \"short and sweet\" JavaScript implementation</p>\n\n<pre><code>Number(n).toPrecision(sig)\n</code></pre>\n\n<p>e.g.</p>\n\n<pre><code>alert(Number(12345).toPrecision(3)\n</code></pre>\n\n<p>?</p>\n\n<p>Sorry, I'm not being facetious here, it's just that using the \"roundit\" function from Claudiu and the .toPrecision in JavaScript gives me different results but only in the rounding of the last digit.</p>\n\n<p>JavaScript:</p>\n\n<pre><code>Number(8.14301).toPrecision(4) == 8.143\n</code></pre>\n\n<p>.NET</p>\n\n<pre><code>roundit(8.14301,4) == 8.144\n</code></pre>\n"
},
{
"answer_id": 1581007,
"author": "Pyrolistical",
"author_id": 21838,
"author_profile": "https://Stackoverflow.com/users/21838",
"pm_score": 8,
"selected": true,
"text": "<p>Here's the same code in Java without the 12.100000000000001 bug other answers have</p>\n\n<p>I also removed repeated code, changed <code>power</code> to a type integer to prevent floating issues when <code>n - d</code> is done, and made the long intermediate more clear</p>\n\n<p>The bug was caused by multiplying a large number with a small number. Instead I divide two numbers of similar size.</p>\n\n<p><strong>EDIT</strong><br>\nFixed more bugs. Added check for 0 as it would result in NaN. Made the function actually work with negative numbers (The original code doesn't handle negative numbers because a log of a negative number is a complex number)</p>\n\n<pre><code>public static double roundToSignificantFigures(double num, int n) {\n if(num == 0) {\n return 0;\n }\n\n final double d = Math.ceil(Math.log10(num < 0 ? -num: num));\n final int power = n - (int) d;\n\n final double magnitude = Math.pow(10, power);\n final long shifted = Math.round(num*magnitude);\n return shifted/magnitude;\n}\n</code></pre>\n"
},
{
"answer_id": 1581060,
"author": "David R Tribble",
"author_id": 170383,
"author_profile": "https://Stackoverflow.com/users/170383",
"pm_score": 1,
"selected": false,
"text": "<p><em>[Corrected, 2009-10-26]</em><br/></p>\n\n<p>Essentially, for N significant <em>fractional</em> digits:</p>\n\n<p>• Multiply the number by 10<sup>N</sup><br/>\n• Add 0.5<br/>\n• Truncate the fraction digits (i.e., truncate the result into an integer)<br/>\n• Divide by 10<sup>N</sup></p>\n\n<p>For N significant <em>integral</em> (non-fractional) digits:</p>\n\n<p>• Divide the number by 10<sup>N</sup><br/>\n• Add 0.5<br/>\n• Truncate the fraction digits (i.e., truncate the result into an integer)<br/>\n• Multiply by 10<sup>N</sup></p>\n\n<p>You can do this on any calculator, for example, that has an \"INT\" (integer truncation) operator.</p>\n"
},
{
"answer_id": 2975934,
"author": "Jason Swank",
"author_id": 358645,
"author_profile": "https://Stackoverflow.com/users/358645",
"pm_score": 2,
"selected": false,
"text": "<p>Here is a modified version of Ates' JavaScript that handles negative numbers.</p>\n\n<pre><code>function sigFigs(n, sig) {\n if ( n === 0 )\n return 0\n var mult = Math.pow(10,\n sig - Math.floor(Math.log(n < 0 ? -n: n) / Math.LN10) - 1);\n return Math.round(n * mult) / mult;\n }\n</code></pre>\n"
},
{
"answer_id": 3089387,
"author": "Valeri Shibaev",
"author_id": 372677,
"author_profile": "https://Stackoverflow.com/users/372677",
"pm_score": 1,
"selected": false,
"text": "<pre><code>/**\n * Set Significant Digits.\n * @param value value\n * @param digits digits\n * @return\n */\npublic static BigDecimal setSignificantDigits(BigDecimal value, int digits) {\n //# Start with the leftmost non-zero digit (e.g. the \"1\" in 1200, or the \"2\" in 0.0256).\n //# Keep n digits. Replace the rest with zeros.\n //# Round up by one if appropriate.\n int p = value.precision();\n int s = value.scale();\n if (p < digits) {\n value = value.setScale(s + digits - p); //, RoundingMode.HALF_UP\n }\n value = value.movePointRight(s).movePointLeft(p - digits).setScale(0, RoundingMode.HALF_UP)\n .movePointRight(p - digits).movePointLeft(s);\n s = (s > (p - digits)) ? (s - (p - digits)) : 0;\n return value.setScale(s);\n}\n</code></pre>\n"
},
{
"answer_id": 3447049,
"author": "wolfgang grinfeld",
"author_id": 415911,
"author_profile": "https://Stackoverflow.com/users/415911",
"pm_score": 3,
"selected": false,
"text": "<p>How about this java solution :</p>\n\n<pre>\ndouble roundToSignificantFigure(double num, int precision){\n return new BigDecimal(num)\n .round(new MathContext(precision, RoundingMode.HALF_EVEN))\n .doubleValue(); \n}\n</pre>\n"
},
{
"answer_id": 4221300,
"author": "Thomas Becker",
"author_id": 512951,
"author_profile": "https://Stackoverflow.com/users/512951",
"pm_score": 3,
"selected": false,
"text": "<p>Pyrolistical's (very nice!) solution still has an issue. The maximum double value in Java is on the order of 10^308, while the minimum value is on the order of 10^-324. Therefore, you can run into trouble when applying the function <code>roundToSignificantFigures</code> to something that's within a few powers of ten of <code>Double.MIN_VALUE</code>. For example, when you call</p>\n\n<pre><code>roundToSignificantFigures(1.234E-310, 3);\n</code></pre>\n\n<p>then the variable <code>power</code> will have the value 3 - (-309) = 312. Consequently, the variable <code>magnitude</code> will become <code>Infinity</code>, and it's all garbage from then on out. Fortunately, this is not an insurmountable problem: it is only the <em>factor</em> <code>magnitude</code> that's overflowing. What really matters is the <em>product</em> <code>num * magnitude</code>, and that does not overflow. One way of resolving this is by breaking up the multiplication by the factor <code>magintude</code> into two steps:</p>\n\n<pre>\n<code>\n public static double roundToNumberOfSignificantDigits(double num, int n) {\n\n final double maxPowerOfTen = Math.floor(Math.log10(Double.MAX_VALUE));\n\n if(num == 0) {\n return 0;\n }\n\n final double d = Math.ceil(Math.log10(num < 0 ? -num: num));\n final int power = n - (int) d;\n\n double firstMagnitudeFactor = 1.0;\n double secondMagnitudeFactor = 1.0;\n if (power > maxPowerOfTen) {\n firstMagnitudeFactor = Math.pow(10.0, maxPowerOfTen);\n secondMagnitudeFactor = Math.pow(10.0, (double) power - maxPowerOfTen);\n } else {\n firstMagnitudeFactor = Math.pow(10.0, (double) power);\n }\n\n double toBeRounded = num * firstMagnitudeFactor;\n toBeRounded *= secondMagnitudeFactor;\n\n final long shifted = Math.round(toBeRounded);\n double rounded = ((double) shifted) / firstMagnitudeFactor;\n rounded /= secondMagnitudeFactor;\n return rounded;\n}\n</code>\n</pre>\n"
},
{
"answer_id": 6428541,
"author": "Michael Zlatkovsky - Microsoft",
"author_id": 678505,
"author_profile": "https://Stackoverflow.com/users/678505",
"pm_score": 1,
"selected": false,
"text": "<p>Here is Pyrolistical's (currently top answer) code in Visual Basic.NET, should anyone need it:</p>\n\n<pre><code>Public Shared Function roundToSignificantDigits(ByVal num As Double, ByVal n As Integer) As Double\n If (num = 0) Then\n Return 0\n End If\n\n Dim d As Double = Math.Ceiling(Math.Log10(If(num < 0, -num, num)))\n Dim power As Integer = n - CInt(d)\n Dim magnitude As Double = Math.Pow(10, power)\n Dim shifted As Double = Math.Round(num * magnitude)\n Return shifted / magnitude\nEnd Function\n</code></pre>\n"
},
{
"answer_id": 16631847,
"author": "Harikrishnan",
"author_id": 2279606,
"author_profile": "https://Stackoverflow.com/users/2279606",
"pm_score": -1,
"selected": false,
"text": "<pre><code>public static double roundToSignificantDigits(double num, int n) {\n return Double.parseDouble(new java.util.Formatter().format(\"%.\" + (n - 1) + \"e\", num).toString());\n}\n</code></pre>\n\n<p>This code uses the inbuilt formatting function which is turned to a rounding function</p>\n"
},
{
"answer_id": 16874602,
"author": "SomeGuy",
"author_id": 2443570,
"author_profile": "https://Stackoverflow.com/users/2443570",
"pm_score": 0,
"selected": false,
"text": "<p>This is one that I came up with in VB:</p>\n\n<pre><code>Function SF(n As Double, SigFigs As Integer)\n Dim l As Integer = n.ToString.Length\n n = n / 10 ^ (l - SigFigs)\n n = Math.Round(n)\n n = n * 10 ^ (l - SigFigs)\n Return n\nEnd Function\n</code></pre>\n"
},
{
"answer_id": 19506883,
"author": "JackDev",
"author_id": 1381093,
"author_profile": "https://Stackoverflow.com/users/1381093",
"pm_score": 2,
"selected": false,
"text": "<p>This came 5 years late, but though I'll share for others still having the same issue. I like it because it's simple and no calculations on the code side. \nSee <a href=\"https://stackoverflow.com/questions/19487506/built-in-methods-for-displaying-significant-figures/19506712#19506712\">Built in methods for displaying Significant figures</a> for more info.</p>\n\n<p>This is if you just want to print it out.</p>\n\n<pre><code>public String toSignificantFiguresString(BigDecimal bd, int significantFigures){\n return String.format(\"%.\"+significantFigures+\"G\", bd);\n}\n</code></pre>\n\n<p>This is if you want to convert it:</p>\n\n<pre><code>public BigDecimal toSignificantFigures(BigDecimal bd, int significantFigures){\n String s = String.format(\"%.\"+significantFigures+\"G\", bd);\n BigDecimal result = new BigDecimal(s);\n return result;\n}\n</code></pre>\n\n<p>Here's an example of it in action:</p>\n\n<pre><code>BigDecimal bd = toSignificantFigures(BigDecimal.valueOf(0.0681), 2);\n</code></pre>\n"
},
{
"answer_id": 30041389,
"author": "Zaz",
"author_id": 405550,
"author_profile": "https://Stackoverflow.com/users/405550",
"pm_score": 2,
"selected": false,
"text": "<h2>JavaScript:</h2>\n\n<pre><code>Number( my_number.toPrecision(3) );\n</code></pre>\n\n<p>The <code>Number</code> function will change output of the form <code>\"8.143e+5\"</code> to <code>\"814300\"</code>.</p>\n"
},
{
"answer_id": 43051623,
"author": "Duncan Calvert",
"author_id": 1070333,
"author_profile": "https://Stackoverflow.com/users/1070333",
"pm_score": 0,
"selected": false,
"text": "<p><code>return new BigDecimal(value, new MathContext(significantFigures, RoundingMode.HALF_UP)).doubleValue();</code></p>\n"
},
{
"answer_id": 48482674,
"author": "Michael Hampton",
"author_id": 1068283,
"author_profile": "https://Stackoverflow.com/users/1068283",
"pm_score": 0,
"selected": false,
"text": "<p>I needed this in Go, which was a bit complicated by the Go standard library's lack of <code>math.Round()</code> (before go1.10). So I had to whip that up too. Here is my translation of <a href=\"https://stackoverflow.com/a/1581007/1068283\">Pyrolistical's excellent answer</a>:</p>\n\n<pre><code>// TODO: replace in go1.10 with math.Round()\nfunc round(x float64) float64 {\n return float64(int64(x + 0.5))\n}\n\n// SignificantDigits rounds a float64 to digits significant digits.\n// Translated from Java at https://stackoverflow.com/a/1581007/1068283\nfunc SignificantDigits(x float64, digits int) float64 {\n if x == 0 {\n return 0\n }\n\n power := digits - int(math.Ceil(math.Log10(math.Abs(x))))\n magnitude := math.Pow(10, float64(power))\n shifted := round(x * magnitude)\n return shifted / magnitude\n}\n</code></pre>\n\n"
}
] |
2008/10/14
|
[
"https://Stackoverflow.com/questions/202302",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7442/"
] |
How can you round *any* number (not just integers > 0) to N significant digits?
For example, if I want to round to three significant digits, I'm looking for a formula that could take:
1,239,451 and return 1,240,000
12.1257 and return 12.1
.0681 and return .0681
5 and return 5
Naturally the algorithm should not be hard-coded to only handle N of 3, although that would be a start.
|
Here's the same code in Java without the 12.100000000000001 bug other answers have
I also removed repeated code, changed `power` to a type integer to prevent floating issues when `n - d` is done, and made the long intermediate more clear
The bug was caused by multiplying a large number with a small number. Instead I divide two numbers of similar size.
**EDIT**
Fixed more bugs. Added check for 0 as it would result in NaN. Made the function actually work with negative numbers (The original code doesn't handle negative numbers because a log of a negative number is a complex number)
```
public static double roundToSignificantFigures(double num, int n) {
if(num == 0) {
return 0;
}
final double d = Math.ceil(Math.log10(num < 0 ? -num: num));
final int power = n - (int) d;
final double magnitude = Math.pow(10, power);
final long shifted = Math.round(num*magnitude);
return shifted/magnitude;
}
```
|
202,305 |
<p>I've created a PHP DOM xml piece and saved it to a string like this:</p>
<pre><code><?php
// create a new XML document
$doc = new DomDocument('1.0');
...
...
...
$xmldata = $doc->saveXML();
?>
</code></pre>
<p>Now I can't use the headers to send a file download prompt and I can't write the file to the server, or rather I don't want the file laying around on it.</p>
<p>Something like a save this file link or a download prompt would be good. How do I do it?</p>
|
[
{
"answer_id": 202866,
"author": "Daniel Rucci",
"author_id": 27604,
"author_profile": "https://Stackoverflow.com/users/27604",
"pm_score": 1,
"selected": false,
"text": "<p>You could enable output_buffering in your php.ini, then you might have some options with sending headers.</p>\n\n<p><a href=\"http://us.php.net/manual/en/function.headers-sent.php\" rel=\"nofollow noreferrer\">http://us.php.net/manual/en/function.headers-sent.php</a></p>\n"
},
{
"answer_id": 204074,
"author": "Jon Cram",
"author_id": 5343,
"author_profile": "https://Stackoverflow.com/users/5343",
"pm_score": 4,
"selected": true,
"text": "<p>I see from the comments that you're working from within a CMS framework and are unable to stop content from being output prior to where your code will be.</p>\n\n<p>If the script in which you're working has already output content (beyond your control), then you can't do what you're trying to achieve in just one script.</p>\n\n<p>Your script can either send headers saying \"the following content is HTML\" then output the HTML or send headers saying \"the following content is XML, is an attachment and has a certain filename\". You can't do both.</p>\n\n<p>You can either output HTML containing a link to a separate script for downloading an XML file or you can issue a file download and output no HTML.</p>\n\n<p>Therefore, you'll have to add a download link in the output of the CMS script you're modifying and then handle the download in a separate script.</p>\n\n<p>I have made a working example that should help. The example includes a simple HTML document containing a download link, and a PHP script that then handles the download.</p>\n\n<p>View the code below or take a look at the <a href=\"http://webignition.net/examples/xmldownload/\" rel=\"nofollow noreferrer\">live example</a>.</p>\n\n<p><strong>HTML (extraneous fluff removed, not necessarily valid)</strong></p>\n\n<pre><code><html>\n<head>\n<title>XML Download Example</title>\n</head>\n\n<body>\n\n<a href=\"download.php\">Download XML example</a>\n\n</body>\n</html>\n</code></pre>\n\n<p><strong>PHP</strong></p>\n\n<pre><code><?php\n// Populate XML document\n $doc = new DomDocument();\n // ... various modifications to the document are made\n\n// Output headers\n header('Content-type: \"text/xml\"; charset=\"utf8\"');\n header('Content-disposition: attachment; filename=\"example.xml\"');\n\n// Output content\n echo $doc->saveXML();\n?>\n</code></pre>\n\n<p>If you are fully unable to handle the download via a second script (perhaps you can't get access to the relevant data), you'll have to re-think the problem.</p>\n"
},
{
"answer_id": 2947481,
"author": "Goysar",
"author_id": 205504,
"author_profile": "https://Stackoverflow.com/users/205504",
"pm_score": 1,
"selected": false,
"text": "<p>The same thing worked for me. But i am not using XML DOM. i use SimpleXML to parse my xml.</p>\n\n<blockquote>\n <p>$xml = new\n SimpleXMLElement(\"<root></root>\");</p>\n</blockquote>\n\n<p>I want to give my view a custom xml which will be generated depending upon the data they give through the form. On submiting the form they get the xml as download with thier own desired name.</p>\n\n<blockquote>\n <p>header('Content-type: \"text/xml\";\n charset=\"utf8\"');</p>\n \n <p>header('Content-disposition:\n attachment;\n filename=\"'.$_POST['filename'].'.xml\"');</p>\n \n <p>echo $xml->asXML();</p>\n</blockquote>\n"
}
] |
2008/10/14
|
[
"https://Stackoverflow.com/questions/202305",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/27943/"
] |
I've created a PHP DOM xml piece and saved it to a string like this:
```
<?php
// create a new XML document
$doc = new DomDocument('1.0');
...
...
...
$xmldata = $doc->saveXML();
?>
```
Now I can't use the headers to send a file download prompt and I can't write the file to the server, or rather I don't want the file laying around on it.
Something like a save this file link or a download prompt would be good. How do I do it?
|
I see from the comments that you're working from within a CMS framework and are unable to stop content from being output prior to where your code will be.
If the script in which you're working has already output content (beyond your control), then you can't do what you're trying to achieve in just one script.
Your script can either send headers saying "the following content is HTML" then output the HTML or send headers saying "the following content is XML, is an attachment and has a certain filename". You can't do both.
You can either output HTML containing a link to a separate script for downloading an XML file or you can issue a file download and output no HTML.
Therefore, you'll have to add a download link in the output of the CMS script you're modifying and then handle the download in a separate script.
I have made a working example that should help. The example includes a simple HTML document containing a download link, and a PHP script that then handles the download.
View the code below or take a look at the [live example](http://webignition.net/examples/xmldownload/).
**HTML (extraneous fluff removed, not necessarily valid)**
```
<html>
<head>
<title>XML Download Example</title>
</head>
<body>
<a href="download.php">Download XML example</a>
</body>
</html>
```
**PHP**
```
<?php
// Populate XML document
$doc = new DomDocument();
// ... various modifications to the document are made
// Output headers
header('Content-type: "text/xml"; charset="utf8"');
header('Content-disposition: attachment; filename="example.xml"');
// Output content
echo $doc->saveXML();
?>
```
If you are fully unable to handle the download via a second script (perhaps you can't get access to the relevant data), you'll have to re-think the problem.
|
202,306 |
<p>How can I AutoIncrement the assembly (build) number in Visual Studio?</p>
<h3>Duplicate:</h3>
<p><a href="https://stackoverflow.com/questions/650/">/questions/650/automatically-update-version-number</a></p>
|
[
{
"answer_id": 202315,
"author": "Mark Cidade",
"author_id": 1659,
"author_profile": "https://Stackoverflow.com/users/1659",
"pm_score": 3,
"selected": false,
"text": "<p>You can just use a wildcard in the <a href=\"http://msdn.microsoft.com/en-us/library/system.reflection.assemblyversionattribute.assemblyversionattribute.aspx\" rel=\"noreferrer\">AssemblyVersionAttribute</a>:</p>\n\n<pre><code>[assembly: AssemblyVersion(\"1.0.*\")]\n</code></pre>\n\n<p>This will cause build to be equal to the number of days since January 1, 2000 local time.</p>\n"
},
{
"answer_id": 202318,
"author": "Patrick Desjardins",
"author_id": 13913,
"author_profile": "https://Stackoverflow.com/users/13913",
"pm_score": 1,
"selected": false,
"text": "<p>Maybe this is what you want from <a href=\"http://www.codeproject.com/Articles/11160/Increment-Build-Number-in-VS-NET\" rel=\"nofollow noreferrer\">Code Project</a>. Otherwise, you can do it from the property of the project by using the *.</p>\n"
},
{
"answer_id": 202324,
"author": "kenny",
"author_id": 3225,
"author_profile": "https://Stackoverflow.com/users/3225",
"pm_score": 1,
"selected": false,
"text": "<p>I use <a href=\"http://code.mattgriffith.net/UpdateVersion/\" rel=\"nofollow noreferrer\">http://code.mattgriffith.net/UpdateVersion/</a> in a batch file as a pre-build step with calls to interact with our revision control system.</p>\n"
},
{
"answer_id": 202327,
"author": "hangy",
"author_id": 11963,
"author_profile": "https://Stackoverflow.com/users/11963",
"pm_score": 0,
"selected": false,
"text": "<p>Setting it as such should do so:</p>\n\n<pre><code>[assembly: AssemblyVersion(\"1.0.*.*\")]\n</code></pre>\n"
}
] |
2008/10/14
|
[
"https://Stackoverflow.com/questions/202306",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] |
How can I AutoIncrement the assembly (build) number in Visual Studio?
### Duplicate:
[/questions/650/automatically-update-version-number](https://stackoverflow.com/questions/650/)
|
You can just use a wildcard in the [AssemblyVersionAttribute](http://msdn.microsoft.com/en-us/library/system.reflection.assemblyversionattribute.assemblyversionattribute.aspx):
```
[assembly: AssemblyVersion("1.0.*")]
```
This will cause build to be equal to the number of days since January 1, 2000 local time.
|
202,340 |
<p>Often times I find myself using std::pair to define logical groupings of two related quantities as function arguments/return values. Some examples: row/col, tag/value, etc.</p>
<p>Often times I should really be rolling my own class instead of just using std::pair. It's pretty easy to see when things start breaking down - when the code becomes littered with make_pair, first, and second, its very hard to remember what is what - an <code>std::pair<int, int></code> conveys less meaning than a type <code>Position</code>.</p>
<p>What have you found are the best ways to wrap the functionality of std::pair in a type that conveys real meaning?</p>
<p>Here are some things I have considered:</p>
<pre><code>typedef std::pair<int, int> Position;
</code></pre>
<p>This at least gives the type a meaningful name when passing it around, but the type isn't enforced, its still really just a pair, and most of the same problems still exist. This is however very simple to write.</p>
<pre><code>struct Position : public std::pair<int, int>
{
typedef std::pair<int, int> Base;
Position() : Base() {}
Position(const Position &x) : Base(x) {}
Position(int a, int b) : Base(a, b) {}
int &row() { return first; }
const int &row() const { return first; }
int &col() { return second; }
const int &col() const { return second; }
};
</code></pre>
<p>This is better, since we can access the variables via a reasonably descriptive name. The problem here is that you can still access first and second, so its easy for the abstraction to leak. Also, accessing simple variables via functions makes the syntax annoying.</p>
<p>The obvious next step is to make the inheritance private:</p>
<pre><code>struct Position : private std::pair<int, int>
{
typedef std::pair<int, int> Base;
Position() {}
Position(const Position &x) : Base(x) {}
Position(int a, int b) : Base(a, b) {}
int &row() { return first; }
const int &row() const { return first; }
int &col() { return second; }
const int &col() const { return second; }
bool operator<(const Position &x) const { return Base(*this) < Base(x); }
// other forwarding operators as needed...
};
</code></pre>
<p>So now at least we have gotten rid of the access to first and second, but now a new problem pops up. When we want to store the type in an std::set, we now don't have access to the operator< overload since we don't have access to first and second. This means we have to define a forwarding function for each operator overload we want. For me this is usually ==, !=, and <, but there could be others that I'd want. Yes I know I probably shouldn't overload operator< just to stick it in an associative container, but it makes everything so darn simple... And defining these operators for each new type is a pain, and we STILL have to access via functions. We can fix that:</p>
<pre><code>struct Position
{
Position() {}
Position(const Position &x) : row(x.row), col(x.col) {}
Position(int row, int col) : row(row), col(col) {}
int row, col;
};
bool operator<(const Position &a, const Position &b)
{
return a.row < b.row || (!(b.row < a.row) && a.col < b.col);
}
// more overloads as needed
</code></pre>
<p>So now we have simple variable access, but now defining overloaded operators is even more of a pain, because instead of just forwarding them to the pair's implementation, we actually have to re-implement them each time...</p>
<p>Are there any solutions I have overlooked that make this easy without the drawbacks? If there aren't which would you tend to prefer?</p>
|
[
{
"answer_id": 202350,
"author": "Ferruccio",
"author_id": 4086,
"author_profile": "https://Stackoverflow.com/users/4086",
"pm_score": 3,
"selected": false,
"text": "<p>This is what <a href=\"http://www.boost.org/doc/libs/1_36_0/libs/tuple/doc/tuple_users_guide.html\" rel=\"nofollow noreferrer\">Boost.Tuple</a> was made for.</p>\n\n<p>But you should probably be using <a href=\"http://en.cppreference.com/w/cpp/utility/tuple\" rel=\"nofollow noreferrer\">std::tuple</a> now...</p>\n"
},
{
"answer_id": 202363,
"author": "xtofl",
"author_id": 6610,
"author_profile": "https://Stackoverflow.com/users/6610",
"pm_score": 2,
"selected": false,
"text": "<p>You can still reuse the <code>pair</code> functionality by forwarding to it:</p>\n\n<pre><code>bool operator< ( const Position &a, const Position &b ) \n{\n return\n std::make_pair( a.row, a.col ) < std::make_pair( b.row, b.col );\n}\n</code></pre>\n\n<p>Although you still end up with doing this for every operatory you need...</p>\n"
},
{
"answer_id": 202425,
"author": "Martin York",
"author_id": 14065,
"author_profile": "https://Stackoverflow.com/users/14065",
"pm_score": 2,
"selected": false,
"text": "<p>You can use some standard utility templates that help define the relation operators.</p>\n\n<p>#include <utility></p>\n\n<p><a href=\"http://www.sgi.com/tech/stl/operators.html\" rel=\"nofollow noreferrer\">http://www.sgi.com/tech/stl/operators.html</a></p>\n\n<h3>Requirements on types</h3>\n\n<p>The requirement for operator!= is that x == y is a valid expression<br>\nThe requirement for operator> is that y < x is a valid expression<br>\nThe requirement for operator<= is that y < x is a valid expression<br>\nThe requirement for operator>= is that x < y is a valid expression<br></p>\n\n<p>So basically it will automatically generate the other operators give < and == all you have to do is include <utility></p>\n"
},
{
"answer_id": 202483,
"author": "Greg Rogers",
"author_id": 5963,
"author_profile": "https://Stackoverflow.com/users/5963",
"pm_score": 2,
"selected": false,
"text": "<p>A coworker pointed me to two possible solutions:</p>\n\n<p>Using <a href=\"http://www.boost.org/doc/libs/1_36_0/boost/strong_typedef.hpp\" rel=\"nofollow noreferrer\">boost strong typedef</a> as an improved version of the typedef. I'd never heard of this before, and it doesn't seem to really be part of any sub-library, just kind of floating.</p>\n\n<p>Using a macro to generate the code needed for the different operators. This way I wouldn't have to explicitly write anything on a per definition level, just do something like <code>DEFINE_PAIR_TYPE(Position, int, int, row, col);</code>. This is probably closest to what I'm looking for, but it still feels kind of evil compared to some of the solutions presented by others.</p>\n"
},
{
"answer_id": 203573,
"author": "Head Geek",
"author_id": 12193,
"author_profile": "https://Stackoverflow.com/users/12193",
"pm_score": 2,
"selected": false,
"text": "<p>There's also the <a href=\"http://www.boost.org/doc/libs/1_36_0/libs/utility/operators.htm#arithmetic\" rel=\"nofollow noreferrer\">Boost::Operators</a> library to automatically generate operator code. It's similar to the SGI library that <a href=\"https://stackoverflow.com/questions/202340/is-there-a-convenient-way-to-wrap-stdpair-as-a-new-type#202425\">Martin York suggested</a>, but might be more portable.</p>\n"
},
{
"answer_id": 206762,
"author": "gbjbaanb",
"author_id": 13744,
"author_profile": "https://Stackoverflow.com/users/13744",
"pm_score": 1,
"selected": false,
"text": "<p>I must say that's a lot of thought just to make a simple struct.</p>\n\n<p>Overload operator< and operator== and you're done. I use that for a lot of code I write, mainly because I usually have more member variables to store than 2.</p>\n\n<pre><code>struct MyStruct\n{\n std::string var1;\n std::string var2;\n bool var3;\n\n struct less : std::binary_function<struct MyStruct, struct MyStruct, bool>\n {\n bool operator() (const struct MyStruct& s1, const struct MyStruct& s2) const\n { if (var1== a2.var1) return var2 < a2.var2; else return var3 < a2.var3; }\n };\n};\ntypedef std::set<struct MyStruct, MyStruct::less> MySet;\n</code></pre>\n\n<p>or put these inside the class definition</p>\n\n<pre><code>bool operator==(const MyStruct& rhs) const \n { return var1 == rhs.var1 && var2 == rhs.var2 && var3 == rhs.var3; };\nbool operator<(const MyStruct& a2) const \n { if (var1== a2.var1) return var2 < a2.var2; else return var3 < a2.var3; };\n</code></pre>\n\n<p>The best reasons are that its easy to understand the above, they can be slipped into the class definition easily, and they are easy to expand if you find you need more variables later on. I would never try to overload std::pair when there's a much simpler solution.</p>\n"
},
{
"answer_id": 242742,
"author": "Motti",
"author_id": 3848,
"author_profile": "https://Stackoverflow.com/users/3848",
"pm_score": 0,
"selected": false,
"text": "<p>Unfortunately <a href=\"http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2006/n2141.html\" rel=\"nofollow noreferrer\">strong <code>typedef</code>s</a> will not make it into <a href=\"http://www.open-std.org/JTC1/SC22/WG21/docs/papers/2008/n2565.html\" rel=\"nofollow noreferrer\">C++0x</a>, it has been given the classification of <em>Not ready for C++0x, but open to resubmit in future</em>.</p>\n"
},
{
"answer_id": 972888,
"author": "Tobias",
"author_id": 118854,
"author_profile": "https://Stackoverflow.com/users/118854",
"pm_score": 1,
"selected": false,
"text": "<p>Don't use it.</p>\n\n<p>I hate std::pair exactly for this reason. You never know which is which, and since access to first and second are public you can't enforce contracts either.</p>\n\n<p>But after all, it's a matter of taste.</p>\n"
}
] |
2008/10/14
|
[
"https://Stackoverflow.com/questions/202340",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5963/"
] |
Often times I find myself using std::pair to define logical groupings of two related quantities as function arguments/return values. Some examples: row/col, tag/value, etc.
Often times I should really be rolling my own class instead of just using std::pair. It's pretty easy to see when things start breaking down - when the code becomes littered with make\_pair, first, and second, its very hard to remember what is what - an `std::pair<int, int>` conveys less meaning than a type `Position`.
What have you found are the best ways to wrap the functionality of std::pair in a type that conveys real meaning?
Here are some things I have considered:
```
typedef std::pair<int, int> Position;
```
This at least gives the type a meaningful name when passing it around, but the type isn't enforced, its still really just a pair, and most of the same problems still exist. This is however very simple to write.
```
struct Position : public std::pair<int, int>
{
typedef std::pair<int, int> Base;
Position() : Base() {}
Position(const Position &x) : Base(x) {}
Position(int a, int b) : Base(a, b) {}
int &row() { return first; }
const int &row() const { return first; }
int &col() { return second; }
const int &col() const { return second; }
};
```
This is better, since we can access the variables via a reasonably descriptive name. The problem here is that you can still access first and second, so its easy for the abstraction to leak. Also, accessing simple variables via functions makes the syntax annoying.
The obvious next step is to make the inheritance private:
```
struct Position : private std::pair<int, int>
{
typedef std::pair<int, int> Base;
Position() {}
Position(const Position &x) : Base(x) {}
Position(int a, int b) : Base(a, b) {}
int &row() { return first; }
const int &row() const { return first; }
int &col() { return second; }
const int &col() const { return second; }
bool operator<(const Position &x) const { return Base(*this) < Base(x); }
// other forwarding operators as needed...
};
```
So now at least we have gotten rid of the access to first and second, but now a new problem pops up. When we want to store the type in an std::set, we now don't have access to the operator< overload since we don't have access to first and second. This means we have to define a forwarding function for each operator overload we want. For me this is usually ==, !=, and <, but there could be others that I'd want. Yes I know I probably shouldn't overload operator< just to stick it in an associative container, but it makes everything so darn simple... And defining these operators for each new type is a pain, and we STILL have to access via functions. We can fix that:
```
struct Position
{
Position() {}
Position(const Position &x) : row(x.row), col(x.col) {}
Position(int row, int col) : row(row), col(col) {}
int row, col;
};
bool operator<(const Position &a, const Position &b)
{
return a.row < b.row || (!(b.row < a.row) && a.col < b.col);
}
// more overloads as needed
```
So now we have simple variable access, but now defining overloaded operators is even more of a pain, because instead of just forwarding them to the pair's implementation, we actually have to re-implement them each time...
Are there any solutions I have overlooked that make this easy without the drawbacks? If there aren't which would you tend to prefer?
|
This is what [Boost.Tuple](http://www.boost.org/doc/libs/1_36_0/libs/tuple/doc/tuple_users_guide.html) was made for.
But you should probably be using [std::tuple](http://en.cppreference.com/w/cpp/utility/tuple) now...
|
202,368 |
<p>I'm writing an ASP.NET application. I have a textbox on a webform, and I want to force whatever the user types to upper case. I'd like to do this on the front end. You should also note that there is a validation control on this textbox, so I want to make sure the solution doesn't interfere with the ASP.NET validation.</p>
<p><strong>Clarification:</strong>
It appears that the CSS text transform makes the user input appear in uppercase. However, under the hood, it's still lower case as the validation control fails. You see, my validation control checks to see if a valid state code is entered, however the regular expression I'm using only works with uppercase characters.</p>
|
[
{
"answer_id": 202386,
"author": "billb",
"author_id": 26805,
"author_profile": "https://Stackoverflow.com/users/26805",
"pm_score": 5,
"selected": false,
"text": "<p>Use a CSS style on the text box. Your CSS should be something like this:</p>\n\n<pre><code>.uppercase\n{\n text-transform: uppercase;\n}\n\n<asp:TextBox ID=\"TextBox1\" runat=\"server\" Text=\"\" CssClass=\"uppercase\"></asp:TextBox>;\n</code></pre>\n"
},
{
"answer_id": 202387,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 1,
"selected": false,
"text": "<p>Set the style on the textbox as <a href=\"http://devhints.wordpress.com/2006/11/01/css-make-it-all-uppercaselowercase/\" rel=\"nofollow noreferrer\">text-transform: uppercase</a>?</p>\n"
},
{
"answer_id": 202389,
"author": "Stephen Wrighton",
"author_id": 7516,
"author_profile": "https://Stackoverflow.com/users/7516",
"pm_score": 0,
"selected": false,
"text": "<p>JavaScript has the \"toUpperCase()\" function of a string.</p>\n\n<p>So, something along these lines:</p>\n\n<pre><code>function makeUpperCase(this)\n{\n this.value = this.value.toUpperCase();\n}\n</code></pre>\n"
},
{
"answer_id": 202398,
"author": "Diodeus - James MacFarlane",
"author_id": 12579,
"author_profile": "https://Stackoverflow.com/users/12579",
"pm_score": 2,
"selected": false,
"text": "<pre><code> style='text-transform:uppercase'\n</code></pre>\n"
},
{
"answer_id": 202410,
"author": "shahkalpesh",
"author_id": 23574,
"author_profile": "https://Stackoverflow.com/users/23574",
"pm_score": 1,
"selected": false,
"text": "<p>CSS could be of help here.</p>\n\n<pre><code>style=\"text-transform: uppercase\";\"\n</code></pre>\n\n<p>does this help?</p>\n"
},
{
"answer_id": 202496,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 1,
"selected": false,
"text": "<p>Use the text-transform CSS for the front-end and then use the toUpper method on your string server-side before you validate.</p>\n"
},
{
"answer_id": 202537,
"author": "Jason Z",
"author_id": 2470,
"author_profile": "https://Stackoverflow.com/users/2470",
"pm_score": 2,
"selected": false,
"text": "<p>I just did something similar today. Here is the modified version:</p>\n\n<pre><code><asp:TextBox ID=\"txtInput\" runat=\"server\"></asp:TextBox>\n<script type=\"text/javascript\">\n function setFormat() {\n var inp = document.getElementById('ctl00_MainContent_txtInput');\n var x = inp.value;\n inp.value = x.toUpperCase();\n }\n\n var inp = document.getElementById('ctl00_MainContent_txtInput');\n inp.onblur = function(evt) {\n setFormat();\n };\n</script>\n</code></pre>\n\n<p>Basically, the script attaches an event that fires when the text box loses focus.</p>\n"
},
{
"answer_id": 202545,
"author": "Ryan Abbott",
"author_id": 27908,
"author_profile": "https://Stackoverflow.com/users/27908",
"pm_score": 6,
"selected": false,
"text": "<p>Why not use a combination of the CSS and backend? Use:</p>\n\n<pre><code>style='text-transform:uppercase' \n</code></pre>\n\n<p>on the TextBox, and in your codebehind use:</p>\n\n<pre><code>Textbox.Value.ToUpper();\n</code></pre>\n\n<p>You can also easily change your regex on the validator to use lowercase and uppercase letters. That's probably the easier solution than forcing uppercase on them.</p>\n"
},
{
"answer_id": 203659,
"author": "Ates Goral",
"author_id": 23501,
"author_profile": "https://Stackoverflow.com/users/23501",
"pm_score": 3,
"selected": false,
"text": "<p>You can intercept the key press events, cancel the lowercase ones, and append their uppercase versions to the input:</p>\n\n<pre><code>window.onload = function () {\n var input = document.getElementById(\"test\");\n\n input.onkeypress = function () {\n // So that things work both on Firefox and Internet Explorer.\n var evt = arguments[0] || event;\n var char = String.fromCharCode(evt.which || evt.keyCode);\n\n // Is it a lowercase character?\n if (/[a-z]/.test(char)) {\n // Append its uppercase version\n input.value += char.toUpperCase();\n\n // Cancel the original event\n evt.cancelBubble = true;\n return false;\n }\n }\n};\n</code></pre>\n\n<p>This works in both Firefox and Internet Explorer. You can see it in action <a href=\"http://jsbin.com/avulo/edit\" rel=\"nofollow noreferrer\">here</a>.</p>\n"
},
{
"answer_id": 1339834,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 2,
"selected": false,
"text": "<pre><code><!-- Script by hscripts.com -->\n<script language=javascript>\n function upper(ustr)\n {\n var str=ustr.value;\n ustr.value=str.toUpperCase();\n }\n\n function lower(ustr)\n {\n var str=ustr.value;\n ustr.value=str.toLowerCase();\n }\n</script>\n\n<form>\n Type Lower-case Letters<textarea name=\"address\" onkeyup=\"upper(this)\"></textarea>\n</form>\n\n<form>\n Type Upper-case Letters<textarea name=\"address\" onkeyup=\"lower(this)\"></textarea>\n</form>\n</code></pre>\n"
},
{
"answer_id": 1345185,
"author": "Cyril Gupta",
"author_id": 33052,
"author_profile": "https://Stackoverflow.com/users/33052",
"pm_score": 2,
"selected": false,
"text": "<p>I would do this using jQuery.</p>\n\n<pre><code><script src=\"Scripts/jquery-1.3.2.js\" type=\"text/javascript\"></script>\n<script type=\"text/javascript\">\n $(document).ready(function() {\n $(\"#txt\").keydown(function(e) {\n if (e.keyCode >= 65 & e.keyCode <= 90) {\n val1 = $(\"#txt\").val();\n $(\"#txt\").val(val1 + String.fromCharCode(e.keyCode));\n return false;\n }\n });\n });\n</script>\n</code></pre>\n\n<p>You must have the jQuery library in the <code>/script</code> folder.</p>\n"
},
{
"answer_id": 2042635,
"author": "Vinay Yadav",
"author_id": 248138,
"author_profile": "https://Stackoverflow.com/users/248138",
"pm_score": 3,
"selected": false,
"text": "<pre><code>**I would do like:\n<asp:TextBox ID=\"txtName\" onkeyup=\"this.value=this.value.toUpperCase()\" runat=\"server\"></asp:TextBox>**\n</code></pre>\n"
},
{
"answer_id": 2815198,
"author": "NetMage",
"author_id": 2557128,
"author_profile": "https://Stackoverflow.com/users/2557128",
"pm_score": 0,
"selected": false,
"text": "<p>I realize it is a bit late, but I couldn't find a good answer that worked with ASP.NET AJAX, so I fixed the code above:</p>\n\n<pre><code>function ToUpper() {\n // So that things work both on FF and IE\n var evt = arguments[0] || event;\n var char = String.fromCharCode(evt.which || evt.keyCode);\n\n // Is it a lowercase character?\n if (/[a-z]/.test(char)) {\n // convert to uppercase version\n if (evt.which) {\n evt.which = char.toUpperCase().charCodeAt(0);\n }\n else {\n evt.keyCode = char.toUpperCase().charCodeAt(0);\n }\n }\n\n return true;\n }\n</code></pre>\n\n<p>Used like so:</p>\n\n<pre><code> <asp:TextBox ID=\"txtAddManager\" onKeyPress=\"ToUpper()\" runat=\"server\" \n Width=\"84px\" Font-Names=\"Courier New\"></asp:TextBox>\n</code></pre>\n"
},
{
"answer_id": 4474650,
"author": "Vasan Ramani",
"author_id": 546518,
"author_profile": "https://Stackoverflow.com/users/546518",
"pm_score": 2,
"selected": false,
"text": "<p>I have done some analysis about this issue on four popular browser versions.</p>\n\n<ol>\n<li>the style tag simple displays the characters in uppercase but, the control value still remains as lowercase</li>\n<li>the keypress functionality using the char code displayed above is a bit worry some as in firefox chrome and safari it disables the feature to <kbd>Ctrl</kbd> + <kbd>V</kbd> into the control.</li>\n<li>the other issue with using character level to upper case is also not translating the whole string to upper case.</li>\n<li><p>the answer I found is to implement this on keyup in conjunction with the style tag.</p>\n\n<pre><code><-- form name=\"frmTest\" -->\n<-- input type=\"text\" size=100 class=\"ucasetext\" name=\"textBoxUCase\" id=\"textBoxUCase\" -->\n<-- /form -->\n\nwindow.onload = function() {\n var input = document.frmTest.textBoxUCase;\n input.onkeyup = function() {\n input.value = input.value.toUpperCase();\n }\n};\n</code></pre></li>\n</ol>\n"
},
{
"answer_id": 7249968,
"author": "Robert Green MBA",
"author_id": 663853,
"author_profile": "https://Stackoverflow.com/users/663853",
"pm_score": 1,
"selected": false,
"text": "<p>here is a solution that worked for me.</p>\n\n<p><a href=\"http://plugins.jquery.com/project/bestupper\" rel=\"nofollow\">http://plugins.jquery.com/project/bestupper</a></p>\n\n<p>You have to get the JavaScript from <a href=\"http://plugins.jquery.com/files/jquery.bestupper.min.js.txt\" rel=\"nofollow\">http://plugins.jquery.com/files/jquery.bestupper.min.js.txt</a> and there you go. </p>\n\n<p>Works like a charm!</p>\n"
},
{
"answer_id": 7250093,
"author": "Robert Green MBA",
"author_id": 663853,
"author_profile": "https://Stackoverflow.com/users/663853",
"pm_score": 3,
"selected": false,
"text": "<p>Okay, after testing, here is a better, cleaner solution.</p>\n\n<p></p>\n\n<pre><code>$('#FirstName').bind('keyup', function () {\n\n // Get the current value of the contents within the text box\n var val = $('#FirstName').val().toUpperCase();\n\n // Reset the current value to the Upper Case Value\n $('#FirstName').val(val);\n\n});\n</code></pre>\n"
},
{
"answer_id": 15717742,
"author": "Chetan Sanghani",
"author_id": 1936231,
"author_profile": "https://Stackoverflow.com/users/1936231",
"pm_score": 0,
"selected": false,
"text": "<pre><code> <telerik:RadTextBox ID=\"txtCityName\" runat=\"server\" MaxLength=\"50\" Width=\"200px\"\n Style=\"text-transform: uppercase;\">\n</code></pre>\n"
},
{
"answer_id": 24300082,
"author": "Vijay Kumbhoje",
"author_id": 3583859,
"author_profile": "https://Stackoverflow.com/users/3583859",
"pm_score": 2,
"selected": false,
"text": "<p>I use a simple one inline statement</p>\n\n<pre><code><asp:TextBox ID=\"txtLocatorName\" runat=\"server\"\n style=\"text-transform:uppercase\" CssClass=\"textbox\" \n TabIndex=\"1\">\n</asp:TextBox>\n</code></pre>\n\n<p>If you don't want to use css classes you can just use inline style statement.(This one just visibly make uppercase) :)</p>\n\n<p>On Server side use</p>\n\n<pre><code>string UCstring = txtName.Text.ToUpper();\n</code></pre>\n"
},
{
"answer_id": 25896426,
"author": "greg",
"author_id": 1829881,
"author_profile": "https://Stackoverflow.com/users/1829881",
"pm_score": 0,
"selected": false,
"text": "<pre><code> $().ready(docReady);\n\n function docReady() {\n\n $(\"#myTextbox\").focusout(uCaseMe);\n }\n\n function uCaseMe() {\n\n var val = $(this).val().toUpperCase();\n\n // Reset the current value to the Upper Case Value\n $(this).val(val);\n }\n</code></pre>\n\n<p>This is a reusable approach. Any number of textboxes can be done this way w/o naming them. \nA page wide solution could be achieved by changing the selector in docReady.</p>\n\n<p>My example uses lost focus, the question did not specify as they type. You could trigger on change if thats important in your scenario. </p>\n"
},
{
"answer_id": 37958370,
"author": "Codeone",
"author_id": 5519409,
"author_profile": "https://Stackoverflow.com/users/5519409",
"pm_score": 2,
"selected": false,
"text": "<p><strong>text-transform</strong> <code>\nCSS property specifies how to capitalize an element's text. It can be used to make text appear in all-uppercase or all-lowercase</code></p>\n\n<p><strong>CssClass</strong></p>\n\n<p>WebControl.CssClass Property</p>\n\n<p>you can learn more about it - <a href=\"https://developer.mozilla.org/en/docs/Web/CSS/text-transform\" rel=\"nofollow\">https://developer.mozilla.org/en/docs/Web/CSS/text-transform</a></p>\n\n<p><a href=\"https://msdn.microsoft.com/en-us/library/system.web.ui.webcontrols.webcontrol.cssclass(v=vs.110).aspx\" rel=\"nofollow\">https://msdn.microsoft.com/en-us/library/system.web.ui.webcontrols.webcontrol.cssclass(v=vs.110).aspx</a></p>\n\n<hr>\n\n<p><strong>use</strong> <code>Style=\"text-transform: uppercase;\"</code> or <code>CssClass=\"upper\"</code></p>\n"
},
{
"answer_id": 70932970,
"author": "Sarbajyoti Mallik",
"author_id": 10332706,
"author_profile": "https://Stackoverflow.com/users/10332706",
"pm_score": -1,
"selected": false,
"text": "<p>Minimum 8 characters at least 1 Alphabet and 1 Number\n<asp:TextBox ID="txtPolicy1" runat="server"></asp:TextBox><br />\n<asp:RegularExpressionValidator ID="Regex1" runat="server" ControlToValidate="txtPolicy1"\nValidationExpression="^(?=.<em>[A-Za-z])(?=.</em>\\d)[A-Za-z\\d]{8,}$" ErrorMessage="Password must contain: Minimum 8 characters atleast 1 Alphabet and 1 Number" ForeColor="Red" /></p>\n<p>Valid Password Examples: pass1234 OR PaSs1234 OR PASS1234</p>\n<p>Minimum 8 characters at least 1 Alphabet, 1 Number and 1 Special Character\n<asp:TextBox ID="txtPolicy2" runat="server"></asp:TextBox><br />\n<asp:RegularExpressionValidator ID="Regex2" runat="server" ControlToValidate="txtPolicy2"\nValidationExpression="^(?=.<em>[A-Za-z])(?=.</em>\\d)(?=.<em>[$@$!%</em>#?&])[A-Za-z\\d$@$!%*#?&]{8,}$"\nErrorMessage="Minimum 8 characters atleast 1 Alphabet, 1 Number and 1 Special Character" ForeColor="Red" /></p>\n<p>Valid Password Examples: pass@123 OR PaSS#123 OR PASS@123</p>\n<p>Minimum 8 characters at least 1 Uppercase Alphabet, 1 Lowercase Alphabet and 1 Number\n<asp:TextBox ID="txtPolicy3" runat="server"></asp:TextBox><br />\n<asp:RegularExpressionValidator ID="Regex3" runat="server" ControlToValidate="txtPolicy3"\nValidationExpression="^(?=.<em>[a-z])(?=.</em>[A-Z])(?=.*\\d)[a-zA-Z\\d]{8,}$"\nErrorMessage="Password must contain: Minimum 8 characters atleast 1 UpperCase Alphabet, 1 LowerCase Alphabet and 1 Number" ForeColor="Red" /></p>\n<p>Valid Password Examples: PaSs1234 OR pASS1234</p>\n<p>Minimum 8 characters at least 1 Uppercase Alphabet, 1 Lowercase Alphabet, 1 Number and 1 Special Character</p>\n<p><asp:TextBox ID="txtPolicy4" runat="server"></asp:TextBox><br />\n<asp:RegularExpressionValidator ID="Regex4" runat="server" ControlToValidate="txtPolicy4"\nValidationExpression="^(?=.<em>[a-z])(?=.</em>[A-Z])(?=.<em>\\d)(?=.</em>[$@$!%<em>?&])[A-Za-z\\d$@$!%</em>?&]{8,}"\nErrorMessage="Password must contain: Minimum 8 characters atleast 1 UpperCase Alphabet, 1 LowerCase Alphabet, 1 Number and 1 Special Character" ForeColor="Red" /></p>\n<p>Valid Password Examples: PaSs@123 OR pAss@123</p>\n<p>Minimum 8 and Maximum 10 characters at least 1 Uppercase Alphabet, 1 Lowercase Alphabet, 1 Number and 1 Special Character</p>\n<p><asp:TextBox ID="txtPolicy5" runat="server"></asp:TextBox><br />\n<asp:RegularExpressionValidator ID="Regex5" runat="server" ControlToValidate="txtPolicy5"\nValidationExpression="^(?=.<em>[a-z])(?=.</em>[A-Z])(?=.<em>\\d)(?=.</em>[$@$!%<em>?&])[A-Za-z\\d$@$!%</em>?&]{8,10}"\nErrorMessage="Password must contain: Minimum 8 and Maximum 10 characters atleast 1 UpperCase Alphabet, 1 LowerCase Alphabet, 1 Number and 1 Special Character"\nForeColor="Red" /></p>\n<p>Valid Password Examples: PaSs@123</p>\n"
}
] |
2008/10/14
|
[
"https://Stackoverflow.com/questions/202368",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/21155/"
] |
I'm writing an ASP.NET application. I have a textbox on a webform, and I want to force whatever the user types to upper case. I'd like to do this on the front end. You should also note that there is a validation control on this textbox, so I want to make sure the solution doesn't interfere with the ASP.NET validation.
**Clarification:**
It appears that the CSS text transform makes the user input appear in uppercase. However, under the hood, it's still lower case as the validation control fails. You see, my validation control checks to see if a valid state code is entered, however the regular expression I'm using only works with uppercase characters.
|
Why not use a combination of the CSS and backend? Use:
```
style='text-transform:uppercase'
```
on the TextBox, and in your codebehind use:
```
Textbox.Value.ToUpper();
```
You can also easily change your regex on the validator to use lowercase and uppercase letters. That's probably the easier solution than forcing uppercase on them.
|
202,378 |
<p>I am trying to make this feature available, maybe in an apache .htaccess file.</p>
|
[
{
"answer_id": 202385,
"author": "Thomas Owens",
"author_id": 572,
"author_profile": "https://Stackoverflow.com/users/572",
"pm_score": 0,
"selected": false,
"text": "<p>My understanding is that everything in PHP 4 is in PHP 5, so if you install PHP 5 and configure it, you will be able to use all features in both 4 and 5.</p>\n"
},
{
"answer_id": 202393,
"author": "DylanJ",
"author_id": 87,
"author_profile": "https://Stackoverflow.com/users/87",
"pm_score": 0,
"selected": false,
"text": "<p>Just use the CGI binarys. Or recompile PHP5 with X feature.</p>\n"
},
{
"answer_id": 202925,
"author": "Heron",
"author_id": 9837,
"author_profile": "https://Stackoverflow.com/users/9837",
"pm_score": 0,
"selected": false,
"text": "<p>My web host (1&1) does this; to use php5 I have to use .php5 extensions or add an .htaccess command to use php5 for my .php files.</p>\n\n<p>I would think it's simply a matter of installing php4 and php5 to separate directories and telling apache to interpret .php files with php4 and .php5 files with php5.</p>\n"
},
{
"answer_id": 207094,
"author": "coderGeek",
"author_id": 28426,
"author_profile": "https://Stackoverflow.com/users/28426",
"pm_score": 0,
"selected": false,
"text": "<p>If you are using a control panel application on your server such as cPanel, this can probably already handle this for you.</p>\n\n<p>If you are on a bare server, simply have PHP 5 run using one method (e.g. DSO) and have PHP 4 run using a different method (e.g. SuPHP). You can then use a .htaccess file to determine which version of PHP to use or just have .php for PHP 5 and .php4 for PHP 4 files.</p>\n\n<p>However, there is a huge overlap between PHP 4 and PHP 5. The only major difference I can think of offhand that one would likely encounter is XML processing.</p>\n"
},
{
"answer_id": 448435,
"author": "OIS",
"author_id": 36175,
"author_profile": "https://Stackoverflow.com/users/36175",
"pm_score": 1,
"selected": false,
"text": "<p>I used the virtual server config to setup several folders with PHP5 and some with PHP4 on my PC to test code. I also set them up with different hostnames (also in the windows host file). (I dont have access to that machine anymore, but here is what I remember.)</p>\n\n<p>Just include one of the following (for linux)</p>\n\n<pre><code>AddHandler php4 .php\nAction php4 /cgi-bin/php4\n</code></pre>\n\n<p>or</p>\n\n<pre><code>AddHandler php5 .php\nAction php5 /cgi-bin/php5\n</code></pre>\n\n<p>in the virtual server config.</p>\n\n<p>If you want to use them for the same (virtual) server, one of the file extensions would have to be renamed to .php5, .php4 or similar.</p>\n"
}
] |
2008/10/14
|
[
"https://Stackoverflow.com/questions/202378",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] |
I am trying to make this feature available, maybe in an apache .htaccess file.
|
I used the virtual server config to setup several folders with PHP5 and some with PHP4 on my PC to test code. I also set them up with different hostnames (also in the windows host file). (I dont have access to that machine anymore, but here is what I remember.)
Just include one of the following (for linux)
```
AddHandler php4 .php
Action php4 /cgi-bin/php4
```
or
```
AddHandler php5 .php
Action php5 /cgi-bin/php5
```
in the virtual server config.
If you want to use them for the same (virtual) server, one of the file extensions would have to be renamed to .php5, .php4 or similar.
|
202,406 |
<p>In my user model, I have an attribute called "nickname" and validates as such:</p>
<blockquote>
<p>validates_format_of :nickname, :with => /[a-zA-Z0-9]$/, :allow_nil => true</p>
</blockquote>
<p>However, it is currently letting this string pass as valid:</p>
<p>a?c</p>
<p>I only want to accept alphanumeric strings - does anyone know why my regular expression is failing? If anybody could suggest a better regular expression, I'm all ears.</p>
|
[
{
"answer_id": 202411,
"author": "Robert Gamble",
"author_id": 25222,
"author_profile": "https://Stackoverflow.com/users/25222",
"pm_score": 4,
"selected": true,
"text": "<p>You need to anchor the pattern on both sides:</p>\n\n<pre><code>/^[a-zA-Z0-9]+$/\n</code></pre>\n"
},
{
"answer_id": 202412,
"author": "Joel Coehoorn",
"author_id": 3043,
"author_profile": "https://Stackoverflow.com/users/3043",
"pm_score": 4,
"selected": false,
"text": "<p>That will match true if the string ends with a valid character. No validation on anything in the middle. Try this:</p>\n\n<pre><code>^[a-zA-Z0-9]*$\n</code></pre>\n"
}
] |
2008/10/14
|
[
"https://Stackoverflow.com/questions/202406",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/19527/"
] |
In my user model, I have an attribute called "nickname" and validates as such:
>
> validates\_format\_of :nickname, :with => /[a-zA-Z0-9]$/, :allow\_nil => true
>
>
>
However, it is currently letting this string pass as valid:
a?c
I only want to accept alphanumeric strings - does anyone know why my regular expression is failing? If anybody could suggest a better regular expression, I'm all ears.
|
You need to anchor the pattern on both sides:
```
/^[a-zA-Z0-9]+$/
```
|
202,417 |
<p>When I shrink a sql server database using the GUI (All Tasks->Shrink Database->Accept all defaults, click OK), it finishes quickly.</p>
<p>But if I run this command, it takes a very very long time.</p>
<pre><code>DBCC SHRINKDATABASE('my_database')
</code></pre>
<p>What am I missing?</p>
<p>This is in SQL Server 2000.</p>
|
[
{
"answer_id": 202427,
"author": "Mitchel Sellers",
"author_id": 13279,
"author_profile": "https://Stackoverflow.com/users/13279",
"pm_score": 1,
"selected": false,
"text": "<p>If I recall correctly the interface will leave about 20% grown space, running DBCC SHRINKDATABASE without any parameters shrinks it to as small as possible.</p>\n\n<p>I don't have Enterprise Manager handy to check the defaults. But you should notice a smaller database file with the manual run than the GUI run, thus the time difference</p>\n"
},
{
"answer_id": 12951449,
"author": "Hallgeir Engen",
"author_id": 813606,
"author_profile": "https://Stackoverflow.com/users/813606",
"pm_score": -1,
"selected": false,
"text": "<p>Details about the DBCC SHRINKDATABASE can be found here: <a href=\"http://msdn.microsoft.com/en-us/library/ms190488.aspx\" rel=\"nofollow\">http://msdn.microsoft.com/en-us/library/ms190488.aspx</a>. Notice this is for SQL Server 2005 -> </p>\n"
}
] |
2008/10/14
|
[
"https://Stackoverflow.com/questions/202417",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/672/"
] |
When I shrink a sql server database using the GUI (All Tasks->Shrink Database->Accept all defaults, click OK), it finishes quickly.
But if I run this command, it takes a very very long time.
```
DBCC SHRINKDATABASE('my_database')
```
What am I missing?
This is in SQL Server 2000.
|
If I recall correctly the interface will leave about 20% grown space, running DBCC SHRINKDATABASE without any parameters shrinks it to as small as possible.
I don't have Enterprise Manager handy to check the defaults. But you should notice a smaller database file with the manual run than the GUI run, thus the time difference
|
202,430 |
<p>Does anyone have any information about getting the current versions of ASP.NET MVC (Preview 5) working on Mono 2.0? There was info on the old versions (Preview 2, maybe Preview 3), but I've seen no details about making Preview 5 actually work.</p>
<p>The <a href="http://www.mono-project.com/Roadmap" rel="nofollow noreferrer">Mono Project Roadmap</a> indicates ASP.NET 3.5 for Mono 2.4 (next year). Any ideas on how to get this useful before then?</p>
<p>More details: The basic MVC Preview 5 template seems to work, so long as I avoid the root directory. If I request the root, I get:</p>
<pre><code>Server Error in '/' Application
The virtual path '' maps to another application.
Description: HTTP 500. Error processing request.
Stack Trace:
System.Web.HttpException: The virtual path '' maps to another application.
at System.Web.HttpContext.RewritePath (System.String filePath, System.String pathInfo, System.String queryString, Boolean setClientFilePath) [0x00000]
at System.Web.HttpContext.RewritePath (System.String path, Boolean rebaseClientPath) [0x00000]
at System.Web.HttpContext.RewritePath (System.String path) [0x00000]
at MvcApplication1._Default.Page_Load (System.Object sender, System.EventArgs e) [0x00000]
at System.Web.UI.Control.OnLoad (System.EventArgs e) [0x00000]
at System.Web.UI.Control.LoadRecursive () [0x00000]
at System.Web.UI.Page.ProcessLoad () [0x00000]
at System.Web.UI.Page.ProcessPostData () [0x00000]
at System.Web.UI.Page.InternalProcessRequest () [0x00000]
at System.Web.UI.Page.ProcessRequest (System.Web.HttpContext context) [0x00000]
Version information: Mono Version: 2.0.50727.42; ASP.NET Version: 2.0.50727.42
</code></pre>
|
[
{
"answer_id": 202568,
"author": "MichaelGG",
"author_id": 27012,
"author_profile": "https://Stackoverflow.com/users/27012",
"pm_score": 5,
"selected": true,
"text": "<p>Well a potential is that RewritePath to / has some sort of bug, so just avoid that. Changing the RewritePath(Request.ApplicationPath) to:</p>\n\n<pre><code>HttpContext.Current.RewritePath(\"/Home/Index\");\n</code></pre>\n\n<p>Seems to fix the problem, and at least the demo works so far. </p>\n"
},
{
"answer_id": 202570,
"author": "Paco",
"author_id": 13376,
"author_profile": "https://Stackoverflow.com/users/13376",
"pm_score": 1,
"selected": false,
"text": "<p>Are you using Mono from svn or stable?\nWhat kind of webserver are you using?\nWhat kind of Operating system?\nDo you have rewrite rules in your web server?</p>\n\n<p>I can run preview 4 in Linux with this in the page_load method in default.aspx.cs</p>\n\n<pre><code>HttpContext.Current.RewritePath(Request.ApplicationPath);\n ((IHttpHandler)new MvcHttpHandler()).ProcessRequest(HttpContext.Current);\n</code></pre>\n\n<p>I need that in windows sometimes too.\nI didn't test version 5 in Linux yet, so it might not work.</p>\n"
},
{
"answer_id": 673244,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 2,
"selected": false,
"text": "<p>Asp.Net MVC 1.0 will work with the 2.4 branch of mono but you will still need to fix the RewritePath in page load of default.aspx.cs</p>\n"
}
] |
2008/10/14
|
[
"https://Stackoverflow.com/questions/202430",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/27012/"
] |
Does anyone have any information about getting the current versions of ASP.NET MVC (Preview 5) working on Mono 2.0? There was info on the old versions (Preview 2, maybe Preview 3), but I've seen no details about making Preview 5 actually work.
The [Mono Project Roadmap](http://www.mono-project.com/Roadmap) indicates ASP.NET 3.5 for Mono 2.4 (next year). Any ideas on how to get this useful before then?
More details: The basic MVC Preview 5 template seems to work, so long as I avoid the root directory. If I request the root, I get:
```
Server Error in '/' Application
The virtual path '' maps to another application.
Description: HTTP 500. Error processing request.
Stack Trace:
System.Web.HttpException: The virtual path '' maps to another application.
at System.Web.HttpContext.RewritePath (System.String filePath, System.String pathInfo, System.String queryString, Boolean setClientFilePath) [0x00000]
at System.Web.HttpContext.RewritePath (System.String path, Boolean rebaseClientPath) [0x00000]
at System.Web.HttpContext.RewritePath (System.String path) [0x00000]
at MvcApplication1._Default.Page_Load (System.Object sender, System.EventArgs e) [0x00000]
at System.Web.UI.Control.OnLoad (System.EventArgs e) [0x00000]
at System.Web.UI.Control.LoadRecursive () [0x00000]
at System.Web.UI.Page.ProcessLoad () [0x00000]
at System.Web.UI.Page.ProcessPostData () [0x00000]
at System.Web.UI.Page.InternalProcessRequest () [0x00000]
at System.Web.UI.Page.ProcessRequest (System.Web.HttpContext context) [0x00000]
Version information: Mono Version: 2.0.50727.42; ASP.NET Version: 2.0.50727.42
```
|
Well a potential is that RewritePath to / has some sort of bug, so just avoid that. Changing the RewritePath(Request.ApplicationPath) to:
```
HttpContext.Current.RewritePath("/Home/Index");
```
Seems to fix the problem, and at least the demo works so far.
|
202,432 |
<p>I am trying to capture output from an install script (that uses scp) and log it. However, I am not getting everything that scp is printing out, namely, the progress bar. </p>
<p>screen output:</p>
<blockquote>
<p>Copying
/user2/cdb/builds/tmp/uat/myfiles/* to
server /users/myfiles as cdb</p>
<p>cdb@server's password:
myfile 100% |*****************************| 2503 00:00</p>
</blockquote>
<p>log output:</p>
<blockquote>
<p>Copying
/user2/cdb/builds/tmp/uat/myfiles/* to
server /users/myfiles as cdb</p>
</blockquote>
<p>I'd really like to know that my file got there. Here's what I am trying now to no avail:</p>
<blockquote>
<p>myscript.sh 2>&1 | tee mylogfile.log</p>
</blockquote>
<p>Does anyone have a good way to capture scp output and log it? </p>
<p>Thanks.</p>
|
[
{
"answer_id": 202477,
"author": "ayaz",
"author_id": 23191,
"author_profile": "https://Stackoverflow.com/users/23191",
"pm_score": 1,
"selected": false,
"text": "<p>Maybe you can use '<a href=\"http://ayaz.wordpress.com/2006/11/19/script1-logging-terminal-sessions-to-files/\" rel=\"nofollow noreferrer\">script</a>' to log the terminal session.</p>\n"
},
{
"answer_id": 202479,
"author": "Tarski",
"author_id": 27653,
"author_profile": "https://Stackoverflow.com/users/27653",
"pm_score": 4,
"selected": true,
"text": "<p>It looks like your just missing whether the scp was succesful or not from the log. </p>\n\n<p>I'm guessing the scroll bar doesn't print to stdout and uses ncurses or some other kind of TUI?</p>\n\n<p>You could just look at the return value of scp to see whether it was successful. Like </p>\n\n<pre><code>scp myfile [email protected]:. && echo success!\n</code></pre>\n\n<p><code>man scp</code> says</p>\n\n<pre><code>scp exits with 0 on success or >0 if an error occurred.\n</code></pre>\n"
},
{
"answer_id": 1264017,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 0,
"selected": false,
"text": "<p>yes i recently was trying to get output within a php script from proc_open()\ni lost a quiet a time trying to get output :-)\nbut its a bit late here and i then reading this post here made me realize that i dont really need this junky output to my script</p>\n\n<p>just the exit code will do the job :-)</p>\n\n<p>$exit_code = proc_close($process);</p>\n"
},
{
"answer_id": 12925408,
"author": "Martin",
"author_id": 1751663,
"author_profile": "https://Stackoverflow.com/users/1751663",
"pm_score": 5,
"selected": false,
"text": "<p>scp prints its progress bar to the terminal using control codes. It will detect if you redirect output and thus omit the progress bar.</p>\n\n<p>You can get around that by tricking scp into thinking it runs in a terminal using the \"script\" command which is installed on most distros by default:</p>\n\n<pre><code>script -q -c \"scp server:/file /tmp/\" > /tmp/test.txt\n</code></pre>\n\n<p>The content of test.txt will be:</p>\n\n<pre><code>file 0% 0 0.0KB/s --:-- ETA\nfile 18% 11MB 11.2MB/s 00:04 ETA\nfile 36% 22MB 11.2MB/s 00:03 ETA\nfile 54% 34MB 11.2MB/s 00:02 ETA\nfile 73% 45MB 11.2MB/s 00:01 ETA\nfile 91% 56MB 11.2MB/s 00:00 ETA\nfile 100% 61MB 10.2MB/s 00:06\n</code></pre>\n\n<p>...which is probably what you want.</p>\n\n<p>I stumbled over this problem while redirecting the output of an interactive script into a log file. Not having the results in the log wasn't a problem as you can always evaluate exit codes. But I really wanted the interactive user to see the progress bar. This answer solves both problems.</p>\n"
},
{
"answer_id": 24546732,
"author": "Fekensa D.",
"author_id": 2412924,
"author_profile": "https://Stackoverflow.com/users/2412924",
"pm_score": 1,
"selected": false,
"text": "<pre><code>scp myfile [email protected]:. && echo success! \n</code></pre>\n\n<p>is very helpful but to write the message to a log file I changed it like this</p>\n\n<pre><code>scp myfile [email protected]:. && echo myfile successfully copied! >> logfile 2>&1\n</code></pre>\n\n<p>and this will write \"myfile successfully copied!\" message to the log file.</p>\n"
},
{
"answer_id": 26613793,
"author": "Benjamin Crouzier",
"author_id": 311744,
"author_profile": "https://Stackoverflow.com/users/311744",
"pm_score": -1,
"selected": false,
"text": "<p>Try: </p>\n\n<pre><code>scp server:/file /tmp/ > /dev/tty\n</code></pre>\n"
},
{
"answer_id": 28356510,
"author": "sysadmiral",
"author_id": 3411119,
"author_profile": "https://Stackoverflow.com/users/3411119",
"pm_score": 1,
"selected": false,
"text": "<p>I can't comment yet :( so I'll add an update here...</p>\n\n<p>@Martin had the best solution for me although if your scp command is midway through your script then it's output <em>may</em> appear after commands that actually ran afterwards.</p>\n\n<p>I think that is because script must run the command in a subshell but I am yet to test.</p>\n\n<p>EDIT: it does indeed spawn a shell so if you need things to run (and indeed fail) in a sequential manner (like in a build script) then you would have to add some logic around the use of the script command.</p>\n\n<p>i.e.</p>\n\n<p>script -q -c \"your command\" && sleep 1</p>\n\n<p>or something similar so that your parent shell waits for the child shell to finish before moving on.</p>\n"
},
{
"answer_id": 37545874,
"author": "ravi teja Kadem",
"author_id": 6404619,
"author_profile": "https://Stackoverflow.com/users/6404619",
"pm_score": 0,
"selected": false,
"text": "<pre><code>$ grep -r \"Error\" xyz.out > abc.txt\n</code></pre>\n\n<p>Here in the above command I am storing output into file abc.txt.</p>\n\n<p>This <code>grep</code> command is for searching text containg <em>Error</em> in file <em>xyz.out</em> and storing the output in <em>abc.txt</em> without displaying on console.</p>\n"
},
{
"answer_id": 59227260,
"author": "Tregoreg",
"author_id": 1137187,
"author_profile": "https://Stackoverflow.com/users/1137187",
"pm_score": 2,
"selected": false,
"text": "<p>None of the answers here worked for me, I needed to recursively copy large directory with lot of files over long geo distance, so I wanted to log the <strong>progress</strong> (<code>&& echo success!</code> was by far not enough).</p>\n\n<p>What I finally engineered and somehow worked was:</p>\n\n<pre><code>scp -vrC root@host:/path/to/directory . 2> copy.log &\n</code></pre>\n\n<p>With <code>-v</code> doing the trick of verbose logging (<code>-C</code> allows compression and <code>-r</code> recursion).</p>\n\n<p>Grepping the logfile</p>\n\n<pre><code>grep file copy.log | wc -l\n</code></pre>\n\n<p>allowed me to see the number of files copied so far.</p>\n"
},
{
"answer_id": 72377986,
"author": "Naresh B",
"author_id": 6933608,
"author_profile": "https://Stackoverflow.com/users/6933608",
"pm_score": 0,
"selected": false,
"text": "<p>SCP on my server did not have <code>-c</code> option (well <code>-c</code> was to specify a cihper) - I needed the rate, so I used below:</p>\n<pre><code>$ scp -q -v nb3510@servername:sftp.dummy . 2>&1 | grep 'Bytes per second'\nBytes per second: sent 52945.7, received 188047087.0\n</code></pre>\n<p><code>-v</code> is for verbose on my server.</p>\n"
}
] |
2008/10/14
|
[
"https://Stackoverflow.com/questions/202432",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/807/"
] |
I am trying to capture output from an install script (that uses scp) and log it. However, I am not getting everything that scp is printing out, namely, the progress bar.
screen output:
>
> Copying
> /user2/cdb/builds/tmp/uat/myfiles/\* to
> server /users/myfiles as cdb
>
>
> cdb@server's password:
> myfile 100% |\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*| 2503 00:00
>
>
>
log output:
>
> Copying
> /user2/cdb/builds/tmp/uat/myfiles/\* to
> server /users/myfiles as cdb
>
>
>
I'd really like to know that my file got there. Here's what I am trying now to no avail:
>
> myscript.sh 2>&1 | tee mylogfile.log
>
>
>
Does anyone have a good way to capture scp output and log it?
Thanks.
|
It looks like your just missing whether the scp was succesful or not from the log.
I'm guessing the scroll bar doesn't print to stdout and uses ncurses or some other kind of TUI?
You could just look at the return value of scp to see whether it was successful. Like
```
scp myfile [email protected]:. && echo success!
```
`man scp` says
```
scp exits with 0 on success or >0 if an error occurred.
```
|
202,434 |
<p>How can I detect the current text formatting at the cursor position in a WPF RichTextBox?</p>
|
[
{
"answer_id": 202737,
"author": "Artur Carvalho",
"author_id": 1013,
"author_profile": "https://Stackoverflow.com/users/1013",
"pm_score": 2,
"selected": true,
"text": "<p>Try the code below where rtb is the RichTextBox:</p>\n\n<pre><code>TextRange tr = new TextRange(rtb.Selection.Start, rtb.Selection.End);\nobject oFont = tr.GetPropertyValue(Run.FontFamilyProperty);\n</code></pre>\n"
},
{
"answer_id": 203465,
"author": "Donnelle",
"author_id": 28074,
"author_profile": "https://Stackoverflow.com/users/28074",
"pm_score": 2,
"selected": false,
"text": "<p>I'd use the CaretPosition instead of the selection start and end, as if the RichTextBox actually has a selection that spans multiple areas of formatting you would get DependencyProperty.UnsetValue.</p>\n\n<pre>\nTextRange tr = new TextRange(rtb.CaretPosition, rtb.CaretPosition);\nobject oFont = tr.GetPropertyValue(Run.FontFamilyProperty);\n</pre>\n"
},
{
"answer_id": 3453568,
"author": "msfanboy",
"author_id": 252289,
"author_profile": "https://Stackoverflow.com/users/252289",
"pm_score": 3,
"selected": false,
"text": "<p>The author of this thread also asked about TextDecorations where you did not provide sample code and its different to use. I post this as a <strong>further solution</strong>:</p>\n\n<pre><code>var obj = _myText.GetPropertyValue(Inline.TextDecorationsProperty);\n\n if (obj == DependencyProperty.UnsetValue) \n IsTextUnderline = false;// mixed formatting \n\n if (obj is TextDecorationCollection)\n {\n var objProper = obj as TextDecorationCollection;\n\n if (objProper.Count > 0) \n IsTextUnderline = true; // all underlined \n else \n IsTextUnderline = false; // nothing underlined \n } \n</code></pre>\n"
},
{
"answer_id": 25736503,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 2,
"selected": false,
"text": "<p>Here is a solution that determines FontWeight, FontStyle, TextDecorations (strikethrough, underline) and Super- and Subscripts.</p>\n\n<pre><code> TextRange textRange = new TextRange(rtb.Selection.Start, rtb.Selection.End);\n\n bool IsTextUnderline = false;\n bool IsTextStrikethrough = false;\n bool IsTextBold = false;\n bool IsTextItalic = false;\n bool IsSuperscript = false;\n bool IsSubscript = false;\n\n // determine underline property\n if (textRange.GetPropertyValue(Inline.TextDecorationsProperty).Equals(TextDecorations.Strikethrough))\n IsTextStrikethrough = true; // all underlined \n else if (textRange.GetPropertyValue(Inline.TextDecorationsProperty).Equals(TextDecorations.Underline))\n IsTextUnderline = true; // all strikethrough\n\n // determine bold property\n if (textRange.GetPropertyValue(Inline.FontWeightProperty).Equals(FontWeights.Bold))\n IsTextBold = true; // all bold\n\n // determine if superscript or subscript\n if (textRange.GetPropertyValue(Inline.BaselineAlignmentProperty).Equals(BaselineAlignment.Subscript))\n IsSubscript = true; // all subscript\n else if (textRange.GetPropertyValue(Inline.BaselineAlignmentProperty).Equals(BaselineAlignment.Superscript))\n IsSuperscript = true; // all superscript\n</code></pre>\n"
}
] |
2008/10/14
|
[
"https://Stackoverflow.com/questions/202434",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1807/"
] |
How can I detect the current text formatting at the cursor position in a WPF RichTextBox?
|
Try the code below where rtb is the RichTextBox:
```
TextRange tr = new TextRange(rtb.Selection.Start, rtb.Selection.End);
object oFont = tr.GetPropertyValue(Run.FontFamilyProperty);
```
|
202,440 |
<p>I am building a C#/ASP.NET app with an SQL backend. I am on deadline and finishing up my pages, out of left field one of my designers incorporated a full text search on one of my pages. My "searches" up until this point have been filters, being able to narrow a result set by certain factors and column values. </p>
<p>Being that I'm on deadline (you know 3 hours sleep a night, at the point where I am looking like something the cat ate and threw up), I was expecting this page to be very similar to be others and I'm trying to decide whether or not to make a stink. I have never done a full text search on a page before.... is this a mountain to climb or is there a simple solution?</p>
<p>thank you. </p>
|
[
{
"answer_id": 202457,
"author": "Dónal",
"author_id": 2648,
"author_profile": "https://Stackoverflow.com/users/2648",
"pm_score": 0,
"selected": false,
"text": "<p>\"How hard is it\" is a tough question to answer. For example, someone who's already done it 10 times will probably reckon it's a snap. All I can really say is that you're likely to find it a lot easier if you use something like <a href=\"http://sourceforge.net/projects/nlucene\" rel=\"nofollow noreferrer\">NLucene</a> rather than rolling your own.</p>\n"
},
{
"answer_id": 202460,
"author": "Mitchel Sellers",
"author_id": 13279,
"author_profile": "https://Stackoverflow.com/users/13279",
"pm_score": 2,
"selected": false,
"text": "<p>Full text search in SQL Server is really easy, a bit of configuration and a slight tweak on the queryside and you are good to go! I have done it for clients in under 20 minutes before, being familiar with the process</p>\n\n<p>Here is the <a href=\"http://msdn.microsoft.com/en-us/library/ms142571.aspx\" rel=\"nofollow noreferrer\">2008 MSDN article</a>, links go out to the 2005 versions from there</p>\n"
},
{
"answer_id": 202474,
"author": "FlySwat",
"author_id": 1965,
"author_profile": "https://Stackoverflow.com/users/1965",
"pm_score": 6,
"selected": true,
"text": "<p>First off, you need to enabled Full text Searching indexing on the production servers, so if thats not in scope, your not going to want to go with this.</p>\n\n<p>However, if that's already ready to go, full text searching is relatively simple.</p>\n\n<p>T-SQL has 4 predicates used for full text search:</p>\n\n<ul>\n<li>FREETEXT</li>\n<li>FREETEXTTABLE</li>\n<li>CONTAINS</li>\n<li>CONTAINSTABLE</li>\n</ul>\n\n<p>FREETEXT is the simplest, and can be done like this:</p>\n\n<pre><code>SELECT UserName\nFROM Tbl_Users\nWHERE FREETEXT (UserName, 'bob' )\n\nResults:\n\nJimBob\nLittle Bobby Tables\n</code></pre>\n\n<p>FREETEXTTABLE works the same as FreeTEXT, except it returns the results as a table.</p>\n\n<p>The real power of T-SQL's full text search comes from the CONTAINS (and CONTAINSTABLE) predicate...This one is huge, so I'll just paste its usage in:</p>\n\n<pre><code>CONTAINS\n ( { column | * } , '< contains_search_condition >' \n ) \n\n< contains_search_condition > ::= \n { < simple_term > \n | < prefix_term > \n | < generation_term > \n | < proximity_term > \n | < weighted_term > \n } \n | { ( < contains_search_condition > ) \n { AND | AND NOT | OR } < contains_search_condition > [ ...n ] \n } \n\n< simple_term > ::= \n word | \" phrase \"\n\n< prefix term > ::= \n { \"word * \" | \"phrase * \" }\n\n< generation_term > ::= \n FORMSOF ( INFLECTIONAL , < simple_term > [ ,...n ] ) \n\n< proximity_term > ::= \n { < simple_term > | < prefix_term > } \n { { NEAR | ~ } { < simple_term > | < prefix_term > } } [ ...n ] \n\n< weighted_term > ::= \n ISABOUT \n ( { { \n < simple_term > \n | < prefix_term > \n | < generation_term > \n | < proximity_term > \n } \n [ WEIGHT ( weight_value ) ] \n } [ ,...n ] \n ) \n</code></pre>\n\n<p>This means you can write queries such as:</p>\n\n<pre><code>SELECT UserName\nFROM Tbl_Users\nWHERE CONTAINS(UserName, '\"little*\" NEAR tables')\n\nResults:\n\nLittle Bobby Tables\n</code></pre>\n\n<p>Good luck :)</p>\n"
},
{
"answer_id": 202494,
"author": "StingyJack",
"author_id": 16391,
"author_profile": "https://Stackoverflow.com/users/16391",
"pm_score": 2,
"selected": false,
"text": "<p>I have used dtSearch before for adding full text searching to files and databases, and their stuff is pretty cheap and easy to use. </p>\n\n<p>Short of adding all that and configuring SQL, This script will search through all columns in a database and tell you what columns contain the values you are looking for. I know its not the \"proper\" solution, but may buy you some time. </p>\n\n<pre><code>/*This script will find any text value in the database*/\n/*Output will be directed to the Messages window. Don't forget to look there!!!*/\n\nSET NOCOUNT ON\nDECLARE @valuetosearchfor varchar(128), @objectOwner varchar(64)\nSET @valuetosearchfor = '%staff%' --should be formatted as a like search \nSET @objectOwner = 'dbo'\n\nDECLARE @potentialcolumns TABLE (id int IDENTITY, sql varchar(4000))\n\nINSERT INTO @potentialcolumns (sql)\nSELECT \n ('if exists (select 1 from [' +\n [tabs].[table_schema] + '].[' +\n [tabs].[table_name] + \n '] (NOLOCK) where [' + \n [cols].[column_name] + \n '] like ''' + @valuetosearchfor + ''' ) print ''SELECT * FROM [' +\n [tabs].[table_schema] + '].[' +\n [tabs].[table_name] + \n '] (NOLOCK) WHERE [' + \n [cols].[column_name] + \n '] LIKE ''''' + @valuetosearchfor + '''''' +\n '''') as 'sql'\nFROM information_schema.columns cols\n INNER JOIN information_schema.tables tabs\n ON cols.TABLE_CATALOG = tabs.TABLE_CATALOG\n AND cols.TABLE_SCHEMA = tabs.TABLE_SCHEMA\n AND cols.TABLE_NAME = tabs.TABLE_NAME\nWHERE cols.data_type IN ('char', 'varchar', 'nvchar', 'nvarchar','text','ntext')\n AND tabs.table_schema = @objectOwner\n AND tabs.TABLE_TYPE = 'BASE TABLE'\nORDER BY tabs.table_catalog, tabs.table_name, cols.ordinal_position\n\nDECLARE @count int\nSET @count = (SELECT MAX(id) FROM @potentialcolumns)\nPRINT 'Found ' + CAST(@count as varchar) + ' potential columns.'\nPRINT 'Beginning scan...'\nPRINT ''\nPRINT 'These columns contain the values being searched for...'\nPRINT ''\nDECLARE @iterator int, @sql varchar(4000)\nSET @iterator = 1\nWHILE @iterator <= (SELECT Max(id) FROM @potentialcolumns)\nBEGIN\n SET @sql = (SELECT [sql] FROM @potentialcolumns where [id] = @iterator)\n IF (@sql IS NOT NULL) and (RTRIM(LTRIM(@sql)) <> '')\n BEGIN\n --SELECT @sql --use when checking sql output\n EXEC (@sql)\n END\n SET @iterator = @iterator + 1\nEND\n\nPRINT ''\nPRINT 'Scan completed'\n</code></pre>\n"
},
{
"answer_id": 202614,
"author": "yogman",
"author_id": 24349,
"author_profile": "https://Stackoverflow.com/users/24349",
"pm_score": 1,
"selected": false,
"text": "<p>I've been there. It works like a charm until you start to consider scalability and advanced search functionalities like search over multiple columns with giving each one different weight values.</p>\n\n<p>For example, the only way to search over <strong>Title</strong> and <strong>Summary</strong> columns is to have a computed column with <code>SearchColumn = CONCAT(Title, Summary)</code> and index over <code>SearchColumn</code>. Weighting? <code>SearchColumn = CONCAT(CONCAT(Title,Title), Summary)</code> something like that. ;) Filtering? Forget about it.</p>\n"
}
] |
2008/10/14
|
[
"https://Stackoverflow.com/questions/202440",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4140/"
] |
I am building a C#/ASP.NET app with an SQL backend. I am on deadline and finishing up my pages, out of left field one of my designers incorporated a full text search on one of my pages. My "searches" up until this point have been filters, being able to narrow a result set by certain factors and column values.
Being that I'm on deadline (you know 3 hours sleep a night, at the point where I am looking like something the cat ate and threw up), I was expecting this page to be very similar to be others and I'm trying to decide whether or not to make a stink. I have never done a full text search on a page before.... is this a mountain to climb or is there a simple solution?
thank you.
|
First off, you need to enabled Full text Searching indexing on the production servers, so if thats not in scope, your not going to want to go with this.
However, if that's already ready to go, full text searching is relatively simple.
T-SQL has 4 predicates used for full text search:
* FREETEXT
* FREETEXTTABLE
* CONTAINS
* CONTAINSTABLE
FREETEXT is the simplest, and can be done like this:
```
SELECT UserName
FROM Tbl_Users
WHERE FREETEXT (UserName, 'bob' )
Results:
JimBob
Little Bobby Tables
```
FREETEXTTABLE works the same as FreeTEXT, except it returns the results as a table.
The real power of T-SQL's full text search comes from the CONTAINS (and CONTAINSTABLE) predicate...This one is huge, so I'll just paste its usage in:
```
CONTAINS
( { column | * } , '< contains_search_condition >'
)
< contains_search_condition > ::=
{ < simple_term >
| < prefix_term >
| < generation_term >
| < proximity_term >
| < weighted_term >
}
| { ( < contains_search_condition > )
{ AND | AND NOT | OR } < contains_search_condition > [ ...n ]
}
< simple_term > ::=
word | " phrase "
< prefix term > ::=
{ "word * " | "phrase * " }
< generation_term > ::=
FORMSOF ( INFLECTIONAL , < simple_term > [ ,...n ] )
< proximity_term > ::=
{ < simple_term > | < prefix_term > }
{ { NEAR | ~ } { < simple_term > | < prefix_term > } } [ ...n ]
< weighted_term > ::=
ISABOUT
( { {
< simple_term >
| < prefix_term >
| < generation_term >
| < proximity_term >
}
[ WEIGHT ( weight_value ) ]
} [ ,...n ]
)
```
This means you can write queries such as:
```
SELECT UserName
FROM Tbl_Users
WHERE CONTAINS(UserName, '"little*" NEAR tables')
Results:
Little Bobby Tables
```
Good luck :)
|
202,442 |
<p>What tricks can be used to stop javascript callouts to various online services from slowing down page loading?</p>
<p>The obvious solution is to do all the javascript calls at the bottom of the page, but some calls need to happen at the top and in the middle. Another idea that comes to mind is using iframes. </p>
<p>Have you ever had to untangle a site full of externally loading javascript that is so slow that it does not release apache and causes outages on high load? Any tips and tricks?</p>
|
[
{
"answer_id": 202482,
"author": "Guido",
"author_id": 12388,
"author_profile": "https://Stackoverflow.com/users/12388",
"pm_score": 1,
"selected": false,
"text": "<p>Not easy solution. In some cases it is possible to merge the external files into a single unit and compress it in order to minimize HTTP requests and data transfer. But with this approach you need to serve the new javascript file from your host, and that's not always possible.</p>\n\n<p>I can't see iframes solving the problem... Could you please elaborate ?</p>\n"
},
{
"answer_id": 202536,
"author": "Christopher Parker",
"author_id": 27583,
"author_profile": "https://Stackoverflow.com/users/27583",
"pm_score": 1,
"selected": false,
"text": "<p>If you're using a third-party JavaScript framework/toolkit/library, it probably provides a function/method that allows you to execute code once the DOM has fully loaded. <a href=\"http://dojotoolkit.org/\" rel=\"nofollow noreferrer\">The Dojo Toolkit</a>, for example, provides <a href=\"http://api.dojotoolkit.org/jsdoc/dojo/1.2/dojo.addOnLoad\" rel=\"nofollow noreferrer\">dojo.addOnLoad</a>. Similarly, <a href=\"http://jquery.com/\" rel=\"nofollow noreferrer\">jQuery</a> provides <a href=\"http://docs.jquery.com/Events/ready\" rel=\"nofollow noreferrer\">Events/ready</a> (or its <a href=\"http://docs.jquery.com/Core/jQuery#jQuery.28.C2.A0callback_.29\" rel=\"nofollow noreferrer\">shorthand form</a>, accessible by passing a function directly to the jQuery object).</p>\n\n<p>If you're sticking with plain JavaScript, then the trick is to use the window.onload event handler. While this will ultimately accomplish the same thing, window.onload executes after the page--and everything on it, including images--is completely loaded, whereas the aforementioned libraries detect the first moment the DOM is ready, before images are loaded.</p>\n\n<p>If you need access to the DOM from a script in the head, this would be the preferred alternative to adding scripts to the end of the document, as well.</p>\n\n<p>For example (using window.onload):</p>\n\n<pre><code><html>\n <head>\n <title>Test Page</title>\n <script type=\"text/javascript\">\n window.onload = function () {\n alert(document.getElementsByTagName(\"body\")[0].className);\n };\n </script>\n <style type=\"text/css\">\n .testClass { color: green; background-color: red; }\n </style>\n </head>\n <body class=\"testClass\">\n <p>Test Content</p>\n </body>\n</html>\n</code></pre>\n\n<p>This would enable you to schedule a certain action to take place once the page has finished loading. To see this effect in action, compare the above script with the following, which blocks the page from loading until you dismiss the modal alert box:</p>\n\n<pre><code><html>\n <head>\n <title>Test Page</title>\n <script type=\"text/javascript\">\n alert(\"Are you seeing a blank page underneath this alert?\");\n </script>\n <style type=\"text/css\">\n .testClass { color: green; background-color: red; }\n </style>\n </head>\n <body class=\"testClass\">\n <p>Test Content</p>\n </body>\n</html>\n</code></pre>\n\n<p>If you've already defined window.onload, or if you're worried you might redefine it and break third party scripts, use this method to append to--rather than redefine--window.onload. (This is a slightly modified version of <a href=\"http://simonwillison.net/2004/May/26/addLoadEvent/\" rel=\"nofollow noreferrer\">Simon Willison's addLoadEvent function</a>.)</p>\n\n<pre><code>if (!window.addOnLoad)\n{\n window.addOnLoad = function (f) {\n var o = window.onload;\n\n window.onload = function () {\n if (typeof o == \"function\") o();\n f();\n }\n };\n}\n</code></pre>\n\n<p>The script from the first example, modified to make use of this method:</p>\n\n<pre><code>window.addOnLoad(function () {\n alert(document.getElementsByTagName(\"body\")[0].className);\n});\n</code></pre>\n\n<p>Modified to make use of Dojo:</p>\n\n<pre><code>dojo.addOnLoad(function () {\n alert(document.getElementsByTagName(\"body\")[0].className);\n});\n</code></pre>\n\n<p>Modified to make use of jQuery:</p>\n\n<pre><code>$(function () {\n alert(document.getElementsByTagName(\"body\")[0].className);\n});\n</code></pre>\n\n<p>So, now that you can execute code on page load, you're probably going to want to dynamically load external scripts. Just like the above section, most major frameworks/toolkits/libraries provide a method of doing this.</p>\n\n<p>Or, you can roll your own:</p>\n\n<pre><code>if (!window.addScript)\n{\n window.addScript = function (src, callback) {\n var head = document.getElementsByTagName(\"head\")[0];\n var script = document.createElement(\"script\");\n script.src = src;\n script.type = \"text/javascript\";\n head.appendChild(script);\n if (typeof callback == \"function\") callback();\n };\n}\n\nwindow.addOnLoad(function () {\n window.addScript(\"example.js\");\n});\n</code></pre>\n\n<p>With Dojo (<a href=\"http://api.dojotoolkit.org/jsdoc/dojo/1.2/dojo.io.script.attach\" rel=\"nofollow noreferrer\">dojo.io.script.attach</a>):</p>\n\n<pre><code>dojo.addOnLoad(function () {\n dojo.require(\"dojo.io.script\");\n dojo.io.script.attach(\"exampleJsId\", \"example.js\");\n});\n</code></pre>\n\n<p>With jQuery (<a href=\"http://docs.jquery.com/Ajax/jQuery.getScript\" rel=\"nofollow noreferrer\">jQuery.getScript</a>):</p>\n\n<pre><code>$(function () {\n $.getScript(\"example.js\");\n});\n</code></pre>\n"
},
{
"answer_id": 202542,
"author": "Jay",
"author_id": 20840,
"author_profile": "https://Stackoverflow.com/users/20840",
"pm_score": 1,
"selected": false,
"text": "<p>See articles <a href=\"http://www.thinkvitamin.com/features/webapps/serving-javascript-fast\" rel=\"nofollow noreferrer\">Serving JavaScript Fast</a> and <a href=\"http://www.codeproject.com/KB/ajax/FasterAjaxWebsevices.aspx\" rel=\"nofollow noreferrer\">Faster AJAX Web Services through multiple subdomain calls</a> for a few suggestions.</p>\n"
},
{
"answer_id": 202548,
"author": "Michael",
"author_id": 27966,
"author_profile": "https://Stackoverflow.com/users/27966",
"pm_score": 2,
"selected": false,
"text": "<p>window onload is a good concept, but the better option is to use jQuery and put your code in a 'document ready' block. This has the same effect, but you don't have to worry about the onload function already having a subscriber.</p>\n\n<p><a href=\"http://docs.jquery.com/Core/jQuery#callback\" rel=\"nofollow noreferrer\">http://docs.jquery.com/Core/jQuery#callback</a></p>\n\n<pre><code>$(function(){\n // Document is ready\n});\n</code></pre>\n\n<p>OR:</p>\n\n<pre><code>jQuery(function($) {\n // Your code using failsafe $ alias here...\n});\n</code></pre>\n\n<p>edit: \nUse this pattern to call all your external services. Refactor your external script files to put their ajax calls to external services inside one of these document ready blocks instead of executing inline. Then the only load time will be the time it takes to actually download the script files.</p>\n\n<p>edit2:\nYou can load scripts after the page has loaded or at any other dom event on the page using built in capability for jQuery.</p>\n\n<p><a href=\"http://docs.jquery.com/Ajax/jQuery.getScript\" rel=\"nofollow noreferrer\">http://docs.jquery.com/Ajax/jQuery.getScript</a></p>\n\n<pre><code>jQuery(function($) {\n $.getScript(\"http://www.yourdomain.com/scripts/somescript1.js\"); \n $.getScript(\"http://www.yourdomain.com/scripts/somescript2.js\"); \n});\n</code></pre>\n"
},
{
"answer_id": 202589,
"author": "Diodeus - James MacFarlane",
"author_id": 12579,
"author_profile": "https://Stackoverflow.com/users/12579",
"pm_score": 0,
"selected": false,
"text": "<p>If you don't need a particular script ad load time, you can load it later by adding another script element to your page at run time.</p>\n"
}
] |
2008/10/14
|
[
"https://Stackoverflow.com/questions/202442",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/556/"
] |
What tricks can be used to stop javascript callouts to various online services from slowing down page loading?
The obvious solution is to do all the javascript calls at the bottom of the page, but some calls need to happen at the top and in the middle. Another idea that comes to mind is using iframes.
Have you ever had to untangle a site full of externally loading javascript that is so slow that it does not release apache and causes outages on high load? Any tips and tricks?
|
window onload is a good concept, but the better option is to use jQuery and put your code in a 'document ready' block. This has the same effect, but you don't have to worry about the onload function already having a subscriber.
<http://docs.jquery.com/Core/jQuery#callback>
```
$(function(){
// Document is ready
});
```
OR:
```
jQuery(function($) {
// Your code using failsafe $ alias here...
});
```
edit:
Use this pattern to call all your external services. Refactor your external script files to put their ajax calls to external services inside one of these document ready blocks instead of executing inline. Then the only load time will be the time it takes to actually download the script files.
edit2:
You can load scripts after the page has loaded or at any other dom event on the page using built in capability for jQuery.
<http://docs.jquery.com/Ajax/jQuery.getScript>
```
jQuery(function($) {
$.getScript("http://www.yourdomain.com/scripts/somescript1.js");
$.getScript("http://www.yourdomain.com/scripts/somescript2.js");
});
```
|
202,459 |
<p>I stumbled across this code and am too proud to go and ask the author what it means.</p>
<pre><code>Hashtable^ tempHash = gcnew Hashtable(iterators_);
IDictionaryEnumerator^ enumerator = tempHash->GetEnumerator();
</code></pre>
<p>What is <code>gcnew</code> and how important is it to use that instead of simply <code>new</code>? (I'm also stumped by the caret; I asked about that <a href="https://stackoverflow.com/questions/202463/what-does-the-caret-mean-in-cnet">over here</a>.)</p>
|
[
{
"answer_id": 202464,
"author": "Steven A. Lowe",
"author_id": 9345,
"author_profile": "https://Stackoverflow.com/users/9345",
"pm_score": 7,
"selected": true,
"text": "<p><a href=\"http://msdn.microsoft.com/en-us/library/te3ecsc8.aspx\" rel=\"noreferrer\">gcnew</a> is for .NET reference objects; objects created with gcnew are automatically garbage-collected; it is important to use gcnew with CLR types</p>\n"
},
{
"answer_id": 202469,
"author": "Joel Coehoorn",
"author_id": 3043,
"author_profile": "https://Stackoverflow.com/users/3043",
"pm_score": 6,
"selected": false,
"text": "<p><code>gcnew</code> is an operator, just like the <code>new</code> operator, except you don't need to <code>delete</code> anything created with it; it's <em><strong>g</strong></em>arbage <em><strong>c</strong></em>ollected. You use <code>gcnew</code> for creating .Net managed types, and <code>new</code> for creating unmanaged types.</p>\n"
},
{
"answer_id": 36863084,
"author": "user2796283",
"author_id": 2796283,
"author_profile": "https://Stackoverflow.com/users/2796283",
"pm_score": 3,
"selected": false,
"text": "<p>The caret '^' acts simarly to the '*' in C/C++ when declaring a type;</p>\n\n<pre><code>// pointer to new std::string object -> memory is not garbage-collected\nstd::string* strPtr = new std::string;\n\n// pointer to System::String object -> memory is garbage-collected\nSystem::String^ manStr = gcnew System::String;\n</code></pre>\n\n<p>I use the term 'pointer' when describing the managed object as a managed object can be compared to 'nullptr' just like a pointer in C/C++. A reference in C/C++ can not be compared to 'nullptr' as it is the address of an existing object.</p>\n\n<p>Managed objects use automatic-reference-counting meaning that they are destroyed automatically when they have a reference count of zero although if two or more unreachable objects refer to eachother, you will still have a memory leak. Be warned that automatic reference counting is not free performance wise so use it wisely.</p>\n"
}
] |
2008/10/14
|
[
"https://Stackoverflow.com/questions/202459",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4790/"
] |
I stumbled across this code and am too proud to go and ask the author what it means.
```
Hashtable^ tempHash = gcnew Hashtable(iterators_);
IDictionaryEnumerator^ enumerator = tempHash->GetEnumerator();
```
What is `gcnew` and how important is it to use that instead of simply `new`? (I'm also stumped by the caret; I asked about that [over here](https://stackoverflow.com/questions/202463/what-does-the-caret-mean-in-cnet).)
|
[gcnew](http://msdn.microsoft.com/en-us/library/te3ecsc8.aspx) is for .NET reference objects; objects created with gcnew are automatically garbage-collected; it is important to use gcnew with CLR types
|
202,463 |
<p>I just came across this code and a few Google searches turn up no explanation of this mysterious (to me) syntax.</p>
<pre><code>Hashtable^ tempHash = gcnew Hashtable(iterators_);
IDictionaryEnumerator^ enumerator = tempHash->GetEnumerator();
</code></pre>
<p>What the heck does the caret mean? (The <code>gcnew</code> is also new to me, and I asked about that <a href="https://stackoverflow.com/questions/202459/what-is-gcnew">here</a>.)</p>
|
[
{
"answer_id": 202472,
"author": "1800 INFORMATION",
"author_id": 3146,
"author_profile": "https://Stackoverflow.com/users/3146",
"pm_score": 2,
"selected": false,
"text": "<p>It means that it is a reference to a managed object.</p>\n"
},
{
"answer_id": 202473,
"author": "Rob Walker",
"author_id": 3631,
"author_profile": "https://Stackoverflow.com/users/3631",
"pm_score": 9,
"selected": true,
"text": "<p>This is <a href=\"http://en.wikipedia.org/wiki/C%2B%2B/CLI\" rel=\"noreferrer\">C++/CLI</a> and the caret is the managed equivalent of a * (pointer) which in C++/CLI terminology is called a <a href=\"https://learn.microsoft.com/en-us/cpp/extensions/handle-to-object-operator-hat-cpp-component-extensions\" rel=\"noreferrer\">'handle'</a> to a 'reference type' (since you can still have unmanaged pointers).</p>\n\n<p>(Thanks to Aardvark for pointing out the better terminology.)</p>\n"
},
{
"answer_id": 202480,
"author": "Franci Penov",
"author_id": 17028,
"author_profile": "https://Stackoverflow.com/users/17028",
"pm_score": 5,
"selected": false,
"text": "<p>It means that this is a reference to a managed object vs. a regular C++ pointer. Objects behind such references are managed by the runtime and can be relocated in the memory. They are also garbage-collected automatically.</p>\n"
},
{
"answer_id": 202484,
"author": "Mark Ingram",
"author_id": 986,
"author_profile": "https://Stackoverflow.com/users/986",
"pm_score": 3,
"selected": false,
"text": "<p>In C++/CLI it means a managed pointer. You can read more about it (and other C++/CLI features) here:</p>\n\n<p><a href=\"http://en.wikipedia.org/wiki/C%2B%2B/CLI\" rel=\"noreferrer\">http://en.wikipedia.org/wiki/C%2B%2B/CLI</a></p>\n"
},
{
"answer_id": 202485,
"author": "Jon Tackabury",
"author_id": 343,
"author_profile": "https://Stackoverflow.com/users/343",
"pm_score": 3,
"selected": false,
"text": "<p>From MSDN, it looks like the caret means you are getting a handle to the type being created.</p>\n<p><a href=\"https://web.archive.org/web/20150117095313/http://msdn.microsoft.com/en-us/library/te3ecsc8%28VS.80%29.aspx\" rel=\"nofollow noreferrer\">https://web.archive.org/web/20150117095313/http://msdn.microsoft.com/en-us/library/te3ecsc8%28VS.80%29.aspx</a></p>\n"
},
{
"answer_id": 202487,
"author": "Joel Coehoorn",
"author_id": 3043,
"author_profile": "https://Stackoverflow.com/users/3043",
"pm_score": 5,
"selected": false,
"text": "<p>When you allocated managed memory, that memory can be moved around by the garbage collector. The <code>^</code> operator is a pointer for managed memory which continues to point to the <em>correct</em> place even if the garbage collector moves the object it points to.</p>\n"
},
{
"answer_id": 14378351,
"author": "salomon",
"author_id": 958953,
"author_profile": "https://Stackoverflow.com/users/958953",
"pm_score": 7,
"selected": false,
"text": "<pre><code>// here normal pointer\nP* ptr = new P; // usual pointer allocated on heap\nP& nat = *ptr; // object on heap bind to native object\n\n//.. here CLI managed \nMO^ mngd = gcnew MO; // allocate on CLI heap\nMO% rr = *mngd; // object on CLI heap reference to gc-lvalue\n</code></pre>\n\n<p>In general, the punctuator <code>%</code> is to <code>^</code> as the punctuator <code>&</code> is to <code>*</code>. In C++ the unary <code>&</code> operator is in C++/CLI the unary <code>%</code> operator.</p>\n\n<p>While <code>&ptr</code> yields a <code>P*</code>, <code>%mngd</code> yields at <code>MO^</code>.</p>\n"
},
{
"answer_id": 67858146,
"author": "DennisVM-D2i",
"author_id": 9407289,
"author_profile": "https://Stackoverflow.com/users/9407289",
"pm_score": 0,
"selected": false,
"text": "<p>It's also worth considering the following couple of sentences, that put the answer in a slightly different way:</p>\n<p>"The handle declarator (^, pronounced "hat"), modifies the type specifier to mean that the declared object should be automatically deleted when the system determines that the object is no longer accessible."</p>\n<p>"Because native C++ pointers (*) and references (&) are not managed references, the garbage collector cannot automatically update the addresses they point to. To solve this problem, use the handle declarator to specify a variable that the garbage collector is aware of and can update automatically."</p>\n<p>(And "native" is I.M.H.O. a better word than 'handle', as handle is possibly a word that was brought more so in by the use of the 'Windows SDK')</p>\n"
}
] |
2008/10/14
|
[
"https://Stackoverflow.com/questions/202463",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4790/"
] |
I just came across this code and a few Google searches turn up no explanation of this mysterious (to me) syntax.
```
Hashtable^ tempHash = gcnew Hashtable(iterators_);
IDictionaryEnumerator^ enumerator = tempHash->GetEnumerator();
```
What the heck does the caret mean? (The `gcnew` is also new to me, and I asked about that [here](https://stackoverflow.com/questions/202459/what-is-gcnew).)
|
This is [C++/CLI](http://en.wikipedia.org/wiki/C%2B%2B/CLI) and the caret is the managed equivalent of a \* (pointer) which in C++/CLI terminology is called a ['handle'](https://learn.microsoft.com/en-us/cpp/extensions/handle-to-object-operator-hat-cpp-component-extensions) to a 'reference type' (since you can still have unmanaged pointers).
(Thanks to Aardvark for pointing out the better terminology.)
|
202,481 |
<p>How can I use HttpWebRequest (.NET, C#) asynchronously?</p>
|
[
{
"answer_id": 202896,
"author": "Jon B",
"author_id": 27414,
"author_profile": "https://Stackoverflow.com/users/27414",
"pm_score": 8,
"selected": true,
"text": "<p>Use <a href=\"http://msdn.microsoft.com/en-us/library/system.net.httpwebrequest.begingetresponse.aspx\" rel=\"noreferrer\"><code>HttpWebRequest.BeginGetResponse()</code></a></p>\n\n<pre><code>HttpWebRequest webRequest;\n\nvoid StartWebRequest()\n{\n webRequest.BeginGetResponse(new AsyncCallback(FinishWebRequest), null);\n}\n\nvoid FinishWebRequest(IAsyncResult result)\n{\n webRequest.EndGetResponse(result);\n}\n</code></pre>\n\n<p>The callback function is called when the asynchronous operation is complete. You need to at least call <a href=\"http://msdn.microsoft.com/en-us/library/system.net.httpwebrequest.endgetresponse.aspx\" rel=\"noreferrer\"><code>EndGetResponse()</code></a> from this function.</p>\n"
},
{
"answer_id": 4434127,
"author": "xlarsx",
"author_id": 541167,
"author_profile": "https://Stackoverflow.com/users/541167",
"pm_score": 6,
"selected": false,
"text": "<p>Considering the answer:</p>\n\n<pre><code>HttpWebRequest webRequest;\n\nvoid StartWebRequest()\n{\n webRequest.BeginGetResponse(new AsyncCallback(FinishWebRequest), null);\n}\n\nvoid FinishWebRequest(IAsyncResult result)\n{\n webRequest.EndGetResponse(result);\n}\n</code></pre>\n\n<p>You could send the request pointer or any other object like this:</p>\n\n<pre><code>void StartWebRequest()\n{\n HttpWebRequest webRequest = ...;\n webRequest.BeginGetResponse(new AsyncCallback(FinishWebRequest), webRequest);\n}\n\nvoid FinishWebRequest(IAsyncResult result)\n{\n HttpWebResponse response = (result.AsyncState as HttpWebRequest).EndGetResponse(result) as HttpWebResponse;\n}\n</code></pre>\n\n<p>Greetings</p>\n"
},
{
"answer_id": 12776096,
"author": "Sten Petrov",
"author_id": 1416035,
"author_profile": "https://Stackoverflow.com/users/1416035",
"pm_score": 2,
"selected": false,
"text": "<pre><code>public void GetResponseAsync (HttpWebRequest request, Action<HttpWebResponse> gotResponse)\n {\n if (request != null) { \n request.BeginGetRequestStream ((r) => {\n try { // there's a try/catch here because execution path is different from invokation one, exception here may cause a crash\n HttpWebResponse response = request.EndGetResponse (r);\n if (gotResponse != null) \n gotResponse (response);\n } catch (Exception x) {\n Console.WriteLine (\"Unable to get response for '\" + request.RequestUri + \"' Err: \" + x);\n }\n }, null);\n } \n }\n</code></pre>\n"
},
{
"answer_id": 13963255,
"author": "Isak",
"author_id": 371698,
"author_profile": "https://Stackoverflow.com/users/371698",
"pm_score": 6,
"selected": false,
"text": "<p>Everyone so far has been wrong, because <code>BeginGetResponse()</code> does some work on the current thread. From the <a href=\"http://msdn.microsoft.com/en-us/library/system.net.httpwebrequest.begingetresponse.aspx\">documentation</a>:</p>\n\n<blockquote>\n <p>The BeginGetResponse method requires some synchronous setup tasks to\n complete (DNS resolution, proxy detection, and TCP socket connection,\n for example) before this method becomes asynchronous. As a result,\n this method should never be called on a user interface (UI) thread\n because it might take considerable time (up to several minutes\n depending on network settings) to complete the initial synchronous\n setup tasks before an exception for an error is thrown or the method\n succeeds.</p>\n</blockquote>\n\n<p>So to do this right:</p>\n\n<pre><code>void DoWithResponse(HttpWebRequest request, Action<HttpWebResponse> responseAction)\n{\n Action wrapperAction = () =>\n {\n request.BeginGetResponse(new AsyncCallback((iar) =>\n {\n var response = (HttpWebResponse)((HttpWebRequest)iar.AsyncState).EndGetResponse(iar);\n responseAction(response);\n }), request);\n };\n wrapperAction.BeginInvoke(new AsyncCallback((iar) =>\n {\n var action = (Action)iar.AsyncState;\n action.EndInvoke(iar);\n }), wrapperAction);\n}\n</code></pre>\n\n<p>You can then do what you need to with the response. For example:</p>\n\n<pre><code>HttpWebRequest request;\n// init your request...then:\nDoWithResponse(request, (response) => {\n var body = new StreamReader(response.GetResponseStream()).ReadToEnd();\n Console.Write(body);\n});\n</code></pre>\n"
},
{
"answer_id": 15254807,
"author": "eggbert",
"author_id": 519074,
"author_profile": "https://Stackoverflow.com/users/519074",
"pm_score": 3,
"selected": false,
"text": "<p>I ended up using BackgroundWorker, it is definitely asynchronous unlike some of the above solutions, it handles returning to the GUI thread for you, and it is very easy to understand. </p>\n\n<p>It is also very easy to handle exceptions, as they end up in the RunWorkerCompleted method, but make sure you read this: <a href=\"https://stackoverflow.com/questions/1044460/unhandled-exceptions-in-backgroundworker\">Unhandled exceptions in BackgroundWorker</a></p>\n\n<p>I used WebClient but obviously you could use HttpWebRequest.GetResponse if you wanted.</p>\n\n<pre><code>var worker = new BackgroundWorker();\n\nworker.DoWork += (sender, args) => {\n args.Result = new WebClient().DownloadString(settings.test_url);\n};\n\nworker.RunWorkerCompleted += (sender, e) => {\n if (e.Error != null) {\n connectivityLabel.Text = \"Error: \" + e.Error.Message;\n } else {\n connectivityLabel.Text = \"Connectivity OK\";\n Log.d(\"result:\" + e.Result);\n }\n};\n\nconnectivityLabel.Text = \"Testing Connectivity\";\nworker.RunWorkerAsync();\n</code></pre>\n"
},
{
"answer_id": 23004036,
"author": "Nathan Baulch",
"author_id": 8799,
"author_profile": "https://Stackoverflow.com/users/8799",
"pm_score": 6,
"selected": false,
"text": "<p>By far the easiest way is by using <a href=\"http://msdn.microsoft.com/en-us/library/system.threading.tasks.taskfactory.fromasync.aspx\" rel=\"noreferrer\">TaskFactory.FromAsync</a> from the <a href=\"http://msdn.microsoft.com/en-us/library/dd460717.aspx\" rel=\"noreferrer\">TPL</a>. It's literally a couple of lines of code when used in conjunction with the new <a href=\"http://msdn.microsoft.com/en-us/library/hh191443.aspx\" rel=\"noreferrer\">async/await</a> keywords:</p>\n\n<pre><code>var request = WebRequest.Create(\"http://www.stackoverflow.com\");\nvar response = (HttpWebResponse) await Task.Factory\n .FromAsync<WebResponse>(request.BeginGetResponse,\n request.EndGetResponse,\n null);\nDebug.Assert(response.StatusCode == HttpStatusCode.OK);\n</code></pre>\n\n<p>If you can't use the C#5 compiler then the above can be accomplished using the <a href=\"http://msdn.microsoft.com/en-us/library/system.threading.tasks.task.continuewith.aspx\" rel=\"noreferrer\">Task.ContinueWith</a> method:</p>\n\n<pre><code>Task.Factory.FromAsync<WebResponse>(request.BeginGetResponse,\n request.EndGetResponse,\n null)\n .ContinueWith(task =>\n {\n var response = (HttpWebResponse) task.Result;\n Debug.Assert(response.StatusCode == HttpStatusCode.OK);\n });\n</code></pre>\n"
},
{
"answer_id": 46833750,
"author": "tronman",
"author_id": 244104,
"author_profile": "https://Stackoverflow.com/users/244104",
"pm_score": 3,
"selected": false,
"text": "<p>.NET has changed since many of these answers were posted, and I'd like to provide a more up-to-date answer. Use an async method to start a <code>Task</code> that will run on a background thread:</p>\n\n<pre><code>private async Task<String> MakeRequestAsync(String url)\n{ \n String responseText = await Task.Run(() =>\n {\n try\n {\n HttpWebRequest request = WebRequest.Create(url) as HttpWebRequest;\n WebResponse response = request.GetResponse(); \n Stream responseStream = response.GetResponseStream();\n return new StreamReader(responseStream).ReadToEnd(); \n }\n catch (Exception e)\n {\n Console.WriteLine(\"Error: \" + e.Message);\n }\n return null;\n });\n\n return responseText;\n}\n</code></pre>\n\n<p>To use the async method:</p>\n\n<pre><code>String response = await MakeRequestAsync(\"http://example.com/\");\n</code></pre>\n\n<p><strong>Update:</strong></p>\n\n<p>This solution does not work for UWP apps which use <code>WebRequest.GetResponseAsync()</code> instead of <code>WebRequest.GetResponse()</code>, and it does not call the <code>Dispose()</code> methods where appropriate. @dragansr has a good alternative solution that addresses these issues.</p>\n"
},
{
"answer_id": 49225438,
"author": "dragansr",
"author_id": 1924224,
"author_profile": "https://Stackoverflow.com/users/1924224",
"pm_score": 3,
"selected": false,
"text": "<pre><code>public static async Task<byte[]> GetBytesAsync(string url) {\n var request = (HttpWebRequest)WebRequest.Create(url);\n using (var response = await request.GetResponseAsync())\n using (var content = new MemoryStream())\n using (var responseStream = response.GetResponseStream()) {\n await responseStream.CopyToAsync(content);\n return content.ToArray();\n }\n}\n\npublic static async Task<string> GetStringAsync(string url) {\n var bytes = await GetBytesAsync(url);\n return Encoding.UTF8.GetString(bytes, 0, bytes.Length);\n}\n</code></pre>\n"
},
{
"answer_id": 70461277,
"author": "Raiio",
"author_id": 17747759,
"author_profile": "https://Stackoverflow.com/users/17747759",
"pm_score": 0,
"selected": false,
"text": "<p>Follow up to the @Isak 's answer, which is very good. Nonetheless it's biggest flaw is that it will only call the responseAction if the response has status 200-299. The best way to fix this is:</p>\n<pre><code>private void DoWithResponseAsync(HttpWebRequest request, Action<HttpWebResponse> responseAction)\n{\n Action wrapperAction = () =>\n {\n request.BeginGetResponse(new AsyncCallback((iar) =>\n {\n HttpWebResponse response;\n try\n {\n response = (HttpWebResponse)((HttpWebRequest)iar.AsyncState).EndGetResponse(iar);\n }\n catch (WebException ex)\n {\n // It needs to be done like this in order to read responses with error status:\n response = ex.Response as HttpWebResponse;\n }\n responseAction(response);\n }), request);\n };\n wrapperAction.BeginInvoke(new AsyncCallback((iar) =>\n {\n var action = (Action)iar.AsyncState;\n action.EndInvoke(iar);\n }), wrapperAction);\n}\n</code></pre>\n<p>And then as @Isak follows:</p>\n<pre><code>HttpWebRequest request;\n// init your request...then:\nDoWithResponse(request, (response) => {\n var body = new StreamReader(response.GetResponseStream()).ReadToEnd();\n Console.Write(body);\n});\n</code></pre>\n"
},
{
"answer_id": 70746121,
"author": "Jacksonkr",
"author_id": 332578,
"author_profile": "https://Stackoverflow.com/users/332578",
"pm_score": -1,
"selected": false,
"text": "<p>I've been using this for async UWR, hopefully it helps someone</p>\n<pre><code> string uri = "http://some.place.online";\n\n using (UnityWebRequest uwr = UnityWebRequest.Get(uri))\n {\n var asyncOp = uwr.SendWebRequest();\n while (asyncOp.isDone == false) await Task.Delay(1000 / 30); // 30 hertz\n\n if(uwr.result == UnityWebRequest.Result.Success) return uwr.downloadHandler.text;\n Debug.LogError(uwr.error);\n }\n</code></pre>\n"
}
] |
2008/10/14
|
[
"https://Stackoverflow.com/questions/202481",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/16794/"
] |
How can I use HttpWebRequest (.NET, C#) asynchronously?
|
Use [`HttpWebRequest.BeginGetResponse()`](http://msdn.microsoft.com/en-us/library/system.net.httpwebrequest.begingetresponse.aspx)
```
HttpWebRequest webRequest;
void StartWebRequest()
{
webRequest.BeginGetResponse(new AsyncCallback(FinishWebRequest), null);
}
void FinishWebRequest(IAsyncResult result)
{
webRequest.EndGetResponse(result);
}
```
The callback function is called when the asynchronous operation is complete. You need to at least call [`EndGetResponse()`](http://msdn.microsoft.com/en-us/library/system.net.httpwebrequest.endgetresponse.aspx) from this function.
|
202,491 |
<p>Is there a way to automatically increment the "minimum required version" fields in a ClickOnce deployment to always equal the current build number? Basically, I always want my deployment to be automatically updated at launch.</p>
<p>I suspect I'm going to need a some pre-/post-build events, but I hope there's an easier way.</p>
|
[
{
"answer_id": 213920,
"author": "Jared Updike",
"author_id": 2543,
"author_profile": "https://Stackoverflow.com/users/2543",
"pm_score": -1,
"selected": false,
"text": "<p>Are you looking for Application Updates?</p>\n\n<p>Right clicking on the project in the Solution Explorer and then clicking Publish... is the wrong way to get Application Updates. You have to right-click your project and the click Properties, then click the Publish tab. Click the Updates... button and then check the \"The application should check for updates\" check box. There you can also specify a <b>minimum required version for the application.</b> (I haven't used that functionality but the Updates functionality is the core reason I use ClickOnce and it works great.)</p>\n"
},
{
"answer_id": 224522,
"author": "Scott Weinstein",
"author_id": 25201,
"author_profile": "https://Stackoverflow.com/users/25201",
"pm_score": 3,
"selected": false,
"text": "<p>Out of the box, I don't belive there is a way. It's not too much effort to spin your own however.</p>\n\n<p>The approach I use is as follows:</p>\n\n<p>1) create a Version.Properties file</p>\n\n<pre><code><Project xmlns=\"http://schemas.microsoft.com/developer/msbuild/2003\">\n <PropertyGroup>\n <Util-VersionMajor>1</Util-VersionMajor>\n <Util-VersionMinor>11</Util-VersionMinor>\n <Util-VersionBuild>25</Util-VersionBuild>\n <Util-VersionRevision>0</Util-VersionRevision>\n <Util-VersionDots>$(Util-VersionMajor).$(Util-VersionMinor).$(Util-VersionBuild).$(Util-VersionRevision)</Util-VersionDots>\n <Util-VersionUnders>$(Util-VersionMajor)_$(Util-VersionMinor)_$(Util-VersionBuild)_$(Util-VersionRevision)</Util-VersionUnders>\n <MinimumRequiredVersion>$(Util-VersionDots)</MinimumRequiredVersion>\n <ApplicationVersion>$(Util-VersionDots)</ApplicationVersion>\n <ApplicationRevision>$(Util-VersionRevision)</ApplicationRevision>\n </PropertyGroup>\n</Project>\n</code></pre>\n\n<p>2) Import the Version.Properties file into your project files</p>\n\n<p>3) Create a task to increment the version on Build. Here's mine</p>\n\n<pre><code><Target Name=\"IncrementVersion\" DependsOnTargets=\"Build\" Condition=\"'$(BuildingInsideVisualStudio)'==''\">\n <ItemGroup>\n <Util-VersionProjectFileItem Include=\"$(Util-VersionProjectFile)\" />\n </ItemGroup>\n <PropertyGroup>\n <Util-VersionProjectFileFullPath>@(Util-VersionProjectFileItem->'%(FullPath)')</Util-VersionProjectFileFullPath>\n </PropertyGroup>\n <Exec Command=\"&quot;$(TfCommand)&quot; get /overwrite /force /noprompt &quot;$(Util-VersionProjectFileFullPath)&quot;\" Outputs=\"\" />\n <Exec Command=\"&quot;$(TfCommand)&quot; checkout /lock:checkout &quot;$(Util-VersionProjectFileFullPath)&quot;\" Outputs=\"\" />\n <Version Major=\"$(Util-VersionMajor)\" Minor=\"$(Util-VersionMinor)\" Build=\"$(Util-VersionBuild)\" Revision=\"$(Util-VersionRevision)\" RevisionType=\"None\" BuildType=\"Increment\">\n <Output TaskParameter=\"Major\" PropertyName=\"Util-VersionMajor\" />\n <Output TaskParameter=\"Minor\" PropertyName=\"Util-VersionMinor\" />\n <Output TaskParameter=\"Build\" PropertyName=\"Util-VersionBuild\" />\n <Output TaskParameter=\"Revision\" PropertyName=\"Util-VersionRevision\" />\n </Version>\n <XmlUpdate Prefix=\"msb\" Namespace=\"http://schemas.microsoft.com/developer/msbuild/2003\" XPath=\"/msb:Project/msb:PropertyGroup/msb:Util-VersionMajor\" XmlFileName=\"$(Util-VersionProjectFile)\" Value=\"$(Util-VersionMajor)\" />\n <XmlUpdate Prefix=\"msb\" Namespace=\"http://schemas.microsoft.com/developer/msbuild/2003\" XPath=\"/msb:Project/msb:PropertyGroup/msb:Util-VersionMinor\" XmlFileName=\"$(Util-VersionProjectFile)\" Value=\"$(Util-VersionMinor)\" />\n <XmlUpdate Prefix=\"msb\" Namespace=\"http://schemas.microsoft.com/developer/msbuild/2003\" XPath=\"/msb:Project/msb:PropertyGroup/msb:Util-VersionBuild\" XmlFileName=\"$(Util-VersionProjectFile)\" Value=\"$(Util-VersionBuild)\" />\n <XmlUpdate Prefix=\"msb\" Namespace=\"http://schemas.microsoft.com/developer/msbuild/2003\" XPath=\"/msb:Project/msb:PropertyGroup/msb:Util-VersionRevision\" XmlFileName=\"$(Util-VersionProjectFile)\" Value=\"$(Util-VersionRevision)\" />\n <Exec Command=\"&quot;$(TfCommand)&quot; checkin /override:AutoBuildIncrement /comment:***NO_CI*** &quot;$(Util-VersionProjectFileFullPath)&quot;\" />\n <Exec Command=\"&quot;$(TfCommand)&quot; get /overwrite /force /noprompt &quot;$(Util-AssemblyInfoFile)&quot;\" Outputs=\"\" />\n <Exec Command=\"&quot;$(TfCommand)&quot; checkout /lock:checkout &quot;$(Util-AssemblyInfoFile)&quot;\" Outputs=\"\" />\n <AssemblyInfo CodeLanguage=\"CS\" OutputFile=\"$(Util-AssemblyInfoFile)\" AssemblyConfiguration=\"$(Configuration)\" AssemblyVersion=\"$(Util-VersionMajor).$(Util-VersionMinor).$(Util-VersionBuild).$(Util-VersionRevision)\" AssemblyFileVersion=\"$(Util-VersionMajor).$(Util-VersionMinor).$(Util-VersionBuild).$(Util-VersionRevision)\" />\n <Exec Command=\"&quot;$(TfCommand)&quot; checkin /override:AutoBuildIncrement /comment:***NO_CI*** &quot;$(Util-AssemblyInfoFile)&quot;\" />\n </Target>\n</code></pre>\n\n<p>Some additional clickonce tricks here <a href=\"http://weblogs.asp.net/sweinstein/archive/2008/08/24/top-5-secrets-of-net-desktop-deployment-wizards.aspx\" rel=\"noreferrer\">http://weblogs.asp.net/sweinstein/archive/2008/08/24/top-5-secrets-of-net-desktop-deployment-wizards.aspx</a></p>\n"
},
{
"answer_id": 231129,
"author": "Bob King",
"author_id": 6897,
"author_profile": "https://Stackoverflow.com/users/6897",
"pm_score": 3,
"selected": false,
"text": "<p>I ended up actually rolling an AddIn to VS that synchronizes all the version numbers, and then builds and publishes with a single click. It was pretty easy.</p>\n\n<pre><code> Public Sub Publish()\n Try\n Dim startProjName As String = Nothing\n Dim targetProj As Project = Nothing\n Dim soln As Solution2 = TryCast(Me._applicationObject.DTE.Solution, Solution2)\n If soln IsNot Nothing Then\n For Each prop As [Property] In soln.Properties\n If prop.Name = \"StartupProject\" Then\n startProjName = prop.Value.ToString()\n Exit For\n End If\n Next\n If startProjName IsNot Nothing Then\n For Each proj As Project In soln.Projects\n If proj.Name = startProjName Then\n targetProj = proj\n Exit For\n End If\n Next\n If targetProj IsNot Nothing Then\n Dim currAssemVersionString As String = targetProj.Properties.Item(\"AssemblyVersion\").Value.ToString\n Dim currAssemVer As New Version(currAssemVersionString)\n Dim newAssemVer As New Version(currAssemVer.Major, currAssemVer.Minor, currAssemVer.Build, currAssemVer.Revision + 1)\n targetProj.Properties.Item(\"AssemblyVersion\").Value = newAssemVer.ToString()\n targetProj.Properties.Item(\"AssemblyFileVersion\").Value = newAssemVer.ToString()\n Dim publishProps As Properties = TryCast(targetProj.Properties.Item(\"Publish\").Value, Properties)\n Dim shouldPublish As Boolean = False\n If publishProps IsNot Nothing Then\n shouldPublish = CBool(publishProps.Item(\"Install\").Value)\n If shouldPublish Then\n targetProj.Properties.Item(\"GenerateManifests\").Value = \"true\"\n publishProps.Item(\"ApplicationVersion\").Value = newAssemVer.ToString()\n publishProps.Item(\"MinimumRequiredVersion\").Value = newAssemVer.ToString()\n publishProps.Item(\"ApplicationRevision\").Value = newAssemVer.Revision.ToString()\n End If\n End If\n targetProj.Save()\n Dim build As SolutionBuild2 = TryCast(soln.SolutionBuild, SolutionBuild2)\n If build IsNot Nothing Then\n build.Clean(True)\n build.Build(True)\n If shouldPublish Then\n If build.LastBuildInfo = 0 Then\n\n build.Publish(True)\n End If\n End If\n End If\n End If\n End If\n End If\n Catch ex As Exception\n MsgBox(ex.ToString)\n End Try\n End Sub\n</code></pre>\n"
},
{
"answer_id": 495458,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 0,
"selected": false,
"text": "<p>Here's how I handled this one. First I created a custom task that wraps string replacement:</p>\n\n<pre><code>using System;\nusing System.Collections.Generic;\nusing System.Linq;\nusing System.Text;\nusing Microsoft.Build.Utilities;\nusing Microsoft.Build.Framework;\n\nnamespace SynchBuild\n{\n public class RemoveAsterisk : Task\n {\n private string myVersion;\n\n [Required]\n public string Version\n {\n set{myVersion = value;}\n }\n\n\n [Output]\n public string ReturnValue\n {\n get { return myVersion.Replace(\"*\", \"\"); }\n }\n\n\n public override bool Execute()\n {\n return true;\n }\n }\n}\n</code></pre>\n\n<p>So that gets built into SynchBuild.dll which you see referenced in the UsingTask below. Now I tried just overwritting the MinimumRequiredVersion property, but it didn't seem to get picked up, so I just overwrote the GenerateApplicationManifest target by adding the following lines to the end of my csproj file:</p>\n\n<pre><code><UsingTask AssemblyFile=\"$(MSBuildExtensionsPath)\\WegmansBuildTasks\\SynchBuild.dll\" TaskName=\"SynchBuild.RemoveAsterisk\" />\n <Target Name=\"GenerateDeploymentManifest\" DependsOnTargets=\"GenerateApplicationManifest\" Inputs=\"&#xD;&#xA; $(MSBuildAllProjects);&#xD;&#xA; @(ApplicationManifest)&#xD;&#xA; \" Outputs=\"@(DeployManifest)\">\n <RemoveAsterisk Version=\"$(ApplicationVersion)$(ApplicationRevision)\">\n <Output TaskParameter=\"ReturnValue\" PropertyName=\"MinimumRequiredVersion\" />\n </RemoveAsterisk>\n <GenerateDeploymentManifest MinimumRequiredVersion=\"$(MinimumRequiredVersion)\" AssemblyName=\"$(_DeploymentDeployManifestIdentity)\" AssemblyVersion=\"$(_DeploymentManifestVersion)\" CreateDesktopShortcut=\"$(CreateDesktopShortcut)\" DeploymentUrl=\"$(_DeploymentFormattedDeploymentUrl)\" Description=\"$(Description)\" DisallowUrlActivation=\"$(DisallowUrlActivation)\" EntryPoint=\"@(_DeploymentResolvedDeploymentManifestEntryPoint)\" ErrorReportUrl=\"$(_DeploymentFormattedErrorReportUrl)\" Install=\"$(Install)\" MapFileExtensions=\"$(MapFileExtensions)\" MaxTargetPath=\"$(MaxTargetPath)\" OutputManifest=\"@(DeployManifest)\" Platform=\"$(PlatformTarget)\" Product=\"$(ProductName)\" Publisher=\"$(PublisherName)\" SuiteName=\"$(SuiteName)\" SupportUrl=\"$(_DeploymentFormattedSupportUrl)\" TargetCulture=\"$(TargetCulture)\" TargetFrameworkVersion=\"$(TargetFrameworkVersion)\" TrustUrlParameters=\"$(TrustUrlParameters)\" UpdateEnabled=\"$(UpdateEnabled)\" UpdateInterval=\"$(_DeploymentBuiltUpdateInterval)\" UpdateMode=\"$(UpdateMode)\" UpdateUnit=\"$(_DeploymentBuiltUpdateIntervalUnits)\" Condition=\"'$(GenerateClickOnceManifests)'=='true'\">\n <Output TaskParameter=\"OutputManifest\" ItemName=\"FileWrites\" />\n</GenerateDeploymentManifest>\n </Target>\n</code></pre>\n\n<p>The end result is we take the app version and revision, combine them, remove the asterisk, then set the minimum required version. I have the auto increment app version in my publish properties set so that's how incrementing takes place, then I'm just setting the minimumrequiredversion to always match.I don't use team build, this is just designed so that a developer using visual studio can make all clickonce deployments required. Hope this helps.</p>\n"
},
{
"answer_id": 13483142,
"author": "Kev",
"author_id": 745813,
"author_profile": "https://Stackoverflow.com/users/745813",
"pm_score": 6,
"selected": true,
"text": "<p>I may be a little late with answering this one but I found it difficult to find the solution on google but eventually figured it out so thought I would share.</p>\n\n<p>With MSBuild version 4 (VS2010 and VS2012) this can be achieved by inserting the following target:</p>\n\n<pre><code> <Target Name=\"AutoSetMinimumRequiredVersion\" BeforeTargets=\"GenerateDeploymentManifest\">\n <FormatVersion Version=\"$(ApplicationVersion)\" Revision=\"$(ApplicationRevision)\">\n <Output PropertyName=\"MinimumRequiredVersion\" TaskParameter=\"OutputVersion\" />\n </FormatVersion>\n <FormatVersion Version=\"$(ApplicationVersion)\" Revision=\"$(ApplicationRevision)\">\n <Output PropertyName=\"_DeploymentBuiltMinimumRequiredVersion\" TaskParameter=\"OutputVersion\" />\n </FormatVersion>\n </Target>\n</code></pre>\n\n<p>The $(ApplicationVersion) is the same setting that you can set manually in the project's Publish window in the VS IDE, with the revision part set to an asterisk. The $(ApplicationRevision) is the actual revision being used for the published version. The FormatVersion task is a built-in MSBuild task that formats the two into a single full version number.</p>\n\n<p>This will set the 'Minimum Required Version' to be the same as the 'Publish Version' therefore ensuring that the new deployment will always be installed by users, ie no option to Skip the update.</p>\n\n<p>Of course, if you don't want to set the minimum required version to the publish version and want to use a different source property then it is straight-forward to amend the target, but the principle is the same.</p>\n"
},
{
"answer_id": 41564221,
"author": "deadlydog",
"author_id": 602585,
"author_profile": "https://Stackoverflow.com/users/602585",
"pm_score": 0,
"selected": false,
"text": "<p>If you are publishing your ClickOnce application from Visual Studio then just install the <a href=\"https://www.nuget.org/packages/AutoUpdateProjectsMinimumRequiredClickOnceVersion\" rel=\"nofollow noreferrer\">AutoUpdateProjectsMinimumRequiredClickOnceVersion NuGet Package</a> in your project and you're good to go.</p>\n\n<p>If you are publishing from a build server or other script, then you can use the <a href=\"https://github.com/deadlydog/Set-ProjectFilesClickOnceVersion\" rel=\"nofollow noreferrer\">Set-ProjectFilesClickOnceVersion PowerShell script</a>. My blog describes in more detail <a href=\"http://blog.danskingdom.com/continuously-deploy-your-clickonce-application-from-your-build-server/\" rel=\"nofollow noreferrer\">how to setup your build server to accommodate publishing ClickOnce applications</a>.</p>\n"
}
] |
2008/10/14
|
[
"https://Stackoverflow.com/questions/202491",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6897/"
] |
Is there a way to automatically increment the "minimum required version" fields in a ClickOnce deployment to always equal the current build number? Basically, I always want my deployment to be automatically updated at launch.
I suspect I'm going to need a some pre-/post-build events, but I hope there's an easier way.
|
I may be a little late with answering this one but I found it difficult to find the solution on google but eventually figured it out so thought I would share.
With MSBuild version 4 (VS2010 and VS2012) this can be achieved by inserting the following target:
```
<Target Name="AutoSetMinimumRequiredVersion" BeforeTargets="GenerateDeploymentManifest">
<FormatVersion Version="$(ApplicationVersion)" Revision="$(ApplicationRevision)">
<Output PropertyName="MinimumRequiredVersion" TaskParameter="OutputVersion" />
</FormatVersion>
<FormatVersion Version="$(ApplicationVersion)" Revision="$(ApplicationRevision)">
<Output PropertyName="_DeploymentBuiltMinimumRequiredVersion" TaskParameter="OutputVersion" />
</FormatVersion>
</Target>
```
The $(ApplicationVersion) is the same setting that you can set manually in the project's Publish window in the VS IDE, with the revision part set to an asterisk. The $(ApplicationRevision) is the actual revision being used for the published version. The FormatVersion task is a built-in MSBuild task that formats the two into a single full version number.
This will set the 'Minimum Required Version' to be the same as the 'Publish Version' therefore ensuring that the new deployment will always be installed by users, ie no option to Skip the update.
Of course, if you don't want to set the minimum required version to the publish version and want to use a different source property then it is straight-forward to amend the target, but the principle is the same.
|
202,540 |
<p>We have a customer that is trying to call our web service written in C# from PHP code. The web service call takes a long as parameter.</p>
<p>This call works fine for other customers calling from C# or Java but this customer is getting an error back from the call. I haven't debugged their specific call but I am guessing that the 64bit integer is getting truncated somehow from PHP. The customer says they are just making the web service call with a string but is there a wrapper in PHP that does type conversion. Could this be losing the number information?</p>
<p>Thanks for any info.</p>
|
[
{
"answer_id": 202601,
"author": "Peter Bailey",
"author_id": 8815,
"author_profile": "https://Stackoverflow.com/users/8815",
"pm_score": 2,
"selected": true,
"text": "<p>Most PHP installations won't support 64 bit integers - 32 is the max. You can check this by reading the PHP_INT_SIZE constant (4 = 32bit, 8 = 64bit) or read the PHP_INT_MAX value.</p>\n\n<pre><code><?php\n\necho PHP_INT_SIZE, \"\\n\", PHP_INT_MAX;\n\n?>\n</code></pre>\n\n<p>If the web service class he is using is trying to type-convert a string representation of a 64 bit integer, then yes, it's mostly likely being truncated or converted into a float. You can sort of see this behavior with this simple test</p>\n\n<pre><code><?php\n\necho intval( \"12345678901234567890\" );\n// prints 2147483647, the max value for a 32 bit signed int.\n</code></pre>\n\n<p>Without knowing the details of his implementation, it's difficult to postulate on what a good solution/workaround might be.</p>\n"
},
{
"answer_id": 203168,
"author": "Francisco Soto",
"author_id": 3695,
"author_profile": "https://Stackoverflow.com/users/3695",
"pm_score": 0,
"selected": false,
"text": "<p>If you absolutely must take a big number like that, make it a string, and convert it to long in your web service. </p>\n\n<p>This will bother your other users a little bit, but would make it more friendly to your PHP-using costumers.</p>\n"
},
{
"answer_id": 203196,
"author": "FlySwat",
"author_id": 1965,
"author_profile": "https://Stackoverflow.com/users/1965",
"pm_score": 0,
"selected": false,
"text": "<p>PHP brutally murdered its integer support, to the point where you have no predictable way of knowing it a specific install will handle 32-bit or 64-bit integers.</p>\n\n<p>The easiest way to handle this would be to expose a new endpoint that takes a string, and just cast it on your end.</p>\n\n<p>For reference on PHP's epic fail:</p>\n\n<p><a href=\"http://www.mysqlperformanceblog.com/2007/03/27/integers-in-php-running-with-scissors-and-portability/\" rel=\"nofollow noreferrer\">http://www.mysqlperformanceblog.com/2007/03/27/integers-in-php-running-with-scissors-and-portability/</a></p>\n"
},
{
"answer_id": 1501512,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 0,
"selected": false,
"text": "<p>I wrote an article regarding PHP using nuSoap to call a C# web service... Haven't yet encountered the issue with long int conversions, but I will definately be running some tests to see if I should add it into my article. Thanks, Sean\n<a href=\"http://seanmcilvenna.com/blog/7-general/24-windows-php-development\" rel=\"nofollow noreferrer\">http://seanmcilvenna.com/blog/7-general/24-windows-php-development</a></p>\n"
}
] |
2008/10/14
|
[
"https://Stackoverflow.com/questions/202540",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/27989/"
] |
We have a customer that is trying to call our web service written in C# from PHP code. The web service call takes a long as parameter.
This call works fine for other customers calling from C# or Java but this customer is getting an error back from the call. I haven't debugged their specific call but I am guessing that the 64bit integer is getting truncated somehow from PHP. The customer says they are just making the web service call with a string but is there a wrapper in PHP that does type conversion. Could this be losing the number information?
Thanks for any info.
|
Most PHP installations won't support 64 bit integers - 32 is the max. You can check this by reading the PHP\_INT\_SIZE constant (4 = 32bit, 8 = 64bit) or read the PHP\_INT\_MAX value.
```
<?php
echo PHP_INT_SIZE, "\n", PHP_INT_MAX;
?>
```
If the web service class he is using is trying to type-convert a string representation of a 64 bit integer, then yes, it's mostly likely being truncated or converted into a float. You can sort of see this behavior with this simple test
```
<?php
echo intval( "12345678901234567890" );
// prints 2147483647, the max value for a 32 bit signed int.
```
Without knowing the details of his implementation, it's difficult to postulate on what a good solution/workaround might be.
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.