qid
int64 4
8.14M
| question
stringlengths 20
48.3k
| answers
list | date
stringlengths 10
10
| metadata
sequence | input
stringlengths 12
45k
| output
stringlengths 2
31.8k
|
---|---|---|---|---|---|---|
8,800 | <p>So I've been poking around with C# a bit lately, and all the Generic Collections have me a little confused. Say I wanted to represent a data structure where the head of a tree was a key value pair, and then there is one optional list of key value pairs below that (but no more levels than these). Would this be suitable?</p>
<pre><code>public class TokenTree
{
public TokenTree()
{
/* I must admit to not fully understanding this,
* I got it from msdn. As far as I can tell, IDictionary is an
* interface, and Dictionary is the default implementation of
* that interface, right?
*/
SubPairs = new Dictionary<string, string>();
}
public string Key;
public string Value;
public IDictionary<string, string> SubPairs;
}
</code></pre>
<p>It's only really a simple shunt for passing around data.</p>
| [
{
"answer_id": 8811,
"author": "Adam Haile",
"author_id": 194,
"author_profile": "https://Stackoverflow.com/users/194",
"pm_score": 8,
"selected": true,
"text": "<p>There is an actual Data Type called KeyValuePair, use like this</p>\n\n<pre><code>KeyValuePair<string, string> myKeyValuePair = new KeyValuePair<string,string>(\"defaultkey\", \"defaultvalue\");\n</code></pre>\n"
},
{
"answer_id": 8813,
"author": "Lasse V. Karlsen",
"author_id": 267,
"author_profile": "https://Stackoverflow.com/users/267",
"pm_score": 1,
"selected": false,
"text": "<p><a href=\"http://msdn.microsoft.com/en-us/library/xfhwa508.aspx\" rel=\"nofollow noreferrer\">Dictionary Class</a> is exactly what you want, correct.</p>\n\n<p>You can declare the field directly as Dictionary, instead of IDictionary, but that's up to you.</p>\n"
},
{
"answer_id": 8814,
"author": "Coincoin",
"author_id": 42,
"author_profile": "https://Stackoverflow.com/users/42",
"pm_score": 3,
"selected": false,
"text": "<p>There is a KeyValuePair built-in type. As a matter of fact, this is what the IDictionary is giving you access to when you iterate in it.</p>\n\n<p>Also, this structure is hardly a tree, finding a more representative name might be a good exercise.</p>\n"
},
{
"answer_id": 8816,
"author": "Jon Limjap",
"author_id": 372,
"author_profile": "https://Stackoverflow.com/users/372",
"pm_score": 4,
"selected": false,
"text": "<p>One possible thing you could do is use the Dictionary object straight out of the box and then just extend it with your own modifications:</p>\n\n<pre><code>public class TokenTree : Dictionary<string, string>\n{\n public IDictionary<string, string> SubPairs;\n}\n</code></pre>\n\n<p>This gives you the advantage of not having to enforce the rules of IDictionary for your Key (e.g., key uniqueness, etc).</p>\n\n<p>And yup you got the concept of the constructor right :)</p>\n"
},
{
"answer_id": 8818,
"author": "Lasse V. Karlsen",
"author_id": 267,
"author_profile": "https://Stackoverflow.com/users/267",
"pm_score": 2,
"selected": false,
"text": "<p>@<a href=\"https://stackoverflow.com/users/733/jay-mooney\">Jay Mooney</a>: A generic Dictionary class in .NET is actually a hash table, just with fixed types.</p>\n\n<p>The code you've shown shouldn't convince anyone to use Hashtable instead of Dictionary, since both code pieces can be used for both types.</p>\n\n<p>For hashtable:</p>\n\n<pre><code>foreach(object key in h.keys)\n{\n string keyAsString = key.ToString(); // btw, this is unnecessary\n string valAsString = h[key].ToString();\n\n System.Diagnostics.Debug.WriteLine(keyAsString + \" \" + valAsString);\n}\n</code></pre>\n\n<p>For dictionary:</p>\n\n<pre><code>foreach(string key in d.keys)\n{\n string valAsString = d[key].ToString();\n\n System.Diagnostics.Debug.WriteLine(key + \" \" + valAsString);\n}\n</code></pre>\n\n<p>And just the same for the other one with KeyValuePair, just use the non-generic version for Hashtable, and the generic version for Dictionary.</p>\n\n<p>So it's just as easy both ways, but Hashtable uses Object for both key and value, which means you will box all value types, and you don't have type safety, and Dictionary uses generic types and is thus better.</p>\n"
},
{
"answer_id": 8826,
"author": "kokos",
"author_id": 1065,
"author_profile": "https://Stackoverflow.com/users/1065",
"pm_score": 1,
"selected": false,
"text": "<p>Use something like this: </p>\n\n<pre><code>class Tree < T > : Dictionary < T, IList< Tree < T > > > \n{ \n} \n</code></pre>\n\n<p>It's ugly, but I think it will give you what you want. Too bad KeyValuePair is sealed.</p>\n"
},
{
"answer_id": 8833,
"author": "Rob Cooper",
"author_id": 832,
"author_profile": "https://Stackoverflow.com/users/832",
"pm_score": 2,
"selected": false,
"text": "<p>Just one thing to add to this (although I do think you have already had your question answered by others). In the interests of extensibility (since we all know it will happen at some point) you may want to check out the <a href=\"http://www.dofactory.com/Patterns/PatternComposite.aspx\" rel=\"nofollow noreferrer\">Composite Pattern</a> This is ideal for working with \"Tree-Like Structures\"..</p>\n\n<p>Like I said, I know you are only expecting one sub-level, but this could really be useful for you if you later need to extend ^_^</p>\n"
},
{
"answer_id": 8834,
"author": "Shaun Austin",
"author_id": 1120,
"author_profile": "https://Stackoverflow.com/users/1120",
"pm_score": 3,
"selected": false,
"text": "<p>I think what you might be after (as a literal implementation of your question), is:</p>\n\n<pre><code>public class TokenTree\n{\n public TokenTree()\n {\n tree = new Dictionary<string, IDictionary<string,string>>();\n }\n\n IDictionary<string, IDictionary<string, string>> tree; \n}\n</code></pre>\n\n<p>You did actually say a \"list\" of key-values in your question, so you might want to swap the inner <code>IDictionary</code> with a:</p>\n\n<pre><code>IList<KeyValuePair<string, string>>\n</code></pre>\n"
}
] | 2008/08/12 | [
"https://Stackoverflow.com/questions/8800",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/61/"
] | So I've been poking around with C# a bit lately, and all the Generic Collections have me a little confused. Say I wanted to represent a data structure where the head of a tree was a key value pair, and then there is one optional list of key value pairs below that (but no more levels than these). Would this be suitable?
```
public class TokenTree
{
public TokenTree()
{
/* I must admit to not fully understanding this,
* I got it from msdn. As far as I can tell, IDictionary is an
* interface, and Dictionary is the default implementation of
* that interface, right?
*/
SubPairs = new Dictionary<string, string>();
}
public string Key;
public string Value;
public IDictionary<string, string> SubPairs;
}
```
It's only really a simple shunt for passing around data. | There is an actual Data Type called KeyValuePair, use like this
```
KeyValuePair<string, string> myKeyValuePair = new KeyValuePair<string,string>("defaultkey", "defaultvalue");
``` |
8,832 | <p>I hope I can explain this clearly enough, but if not let me know and I'll try to clarify.</p>
<p>I'm currently developing a site using ColdFusion and have a mod_rewrite rule in place to make it look like the site is using PHP. Any requests for index.php get processed by index.cfm (the rule maps *.php to *.cfm).</p>
<p>This works great - so far, so good. The problem is that I want to return a 404 status code if index.cfm (or any ColdFusion page) is requested directly.</p>
<p>If I try to block access to *.cfm files using mod_rewrite it also returns a 404 for requests to *.php.</p>
<p>I figure I might have to change my Apache config rather than use .htaccess</p>
| [
{
"answer_id": 8861,
"author": "jj33",
"author_id": 430,
"author_profile": "https://Stackoverflow.com/users/430",
"pm_score": 0,
"selected": false,
"text": "<p>Post the rules you already have as a starting point so people don't have to recreate it to help you.</p>\n\n<p>I would suggest testing [L] on the rule that maps .php to .cfm files as the first thing to try.</p>\n"
},
{
"answer_id": 8927,
"author": "PW.",
"author_id": 927,
"author_profile": "https://Stackoverflow.com/users/927",
"pm_score": 0,
"selected": false,
"text": "<p>You have to use two distinct groups of rewrite rules, one for .php, the other for .chm and make them mutually exclusives with RewriteCond %{REQUEST_FILENAME}. And make use of the flag [L] as suggested by jj33.</p>\n\n<p>You can keep your rules in .htaccess.</p>\n"
},
{
"answer_id": 12062,
"author": "T Percival",
"author_id": 954,
"author_profile": "https://Stackoverflow.com/users/954",
"pm_score": 2,
"selected": true,
"text": "<p>You can use the <code>S</code> flag to skip the <code>404</code> rule, like this:</p>\n\n<pre><code>RewriteEngine on\n\n# Do not separate these two rules so long as the first has S=1\nRewriteRule (.*)\\.php$ $1.cfm [S=1]\nRewriteRule \\.cfm$ - [R=404]\n</code></pre>\n\n<p>If you are also using the <code>Alias</code> option then you should also add the <code>PT</code> flag. See the <a href=\"http://httpd.apache.org/docs/2.2/mod/mod_rewrite.html\" rel=\"nofollow noreferrer\">mod_rewrite documentation</a> for details.</p>\n"
}
] | 2008/08/12 | [
"https://Stackoverflow.com/questions/8832",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1025/"
] | I hope I can explain this clearly enough, but if not let me know and I'll try to clarify.
I'm currently developing a site using ColdFusion and have a mod\_rewrite rule in place to make it look like the site is using PHP. Any requests for index.php get processed by index.cfm (the rule maps \*.php to \*.cfm).
This works great - so far, so good. The problem is that I want to return a 404 status code if index.cfm (or any ColdFusion page) is requested directly.
If I try to block access to \*.cfm files using mod\_rewrite it also returns a 404 for requests to \*.php.
I figure I might have to change my Apache config rather than use .htaccess | You can use the `S` flag to skip the `404` rule, like this:
```
RewriteEngine on
# Do not separate these two rules so long as the first has S=1
RewriteRule (.*)\.php$ $1.cfm [S=1]
RewriteRule \.cfm$ - [R=404]
```
If you are also using the `Alias` option then you should also add the `PT` flag. See the [mod\_rewrite documentation](http://httpd.apache.org/docs/2.2/mod/mod_rewrite.html) for details. |
8,880 | <p>Using the Windows API, how can I get a list of domains on my network?</p>
| [
{
"answer_id": 8881,
"author": "JosephStyons",
"author_id": 672,
"author_profile": "https://Stackoverflow.com/users/672",
"pm_score": 2,
"selected": false,
"text": "<p>Answered my own question:</p>\n\n<p>Use the <a href=\"http://msdn.microsoft.com/en-us/library/aa370623(VS.85).aspx\" rel=\"nofollow noreferrer\">NetServerEnum</a> function, passing in the <code>SV_TYPE_DOMAIN_ENUM</code> constant for the \"servertype\" argument.</p>\n\n<p>In Delphi, the code looks like this:</p>\n\n<pre><code><snip>\ntype\n NET_API_STATUS = DWORD;\n PSERVER_INFO_100 = ^SERVER_INFO_100;\n SERVER_INFO_100 = packed record\n sv100_platform_id : DWORD;\n sv100_name : PWideChar;\nend;\n\nfunction NetServerEnum( //get a list of pcs on the network (same as DOS cmd \"net view\")\n const servername : PWideChar;\n const level : DWORD;\n const bufptr : Pointer;\n const prefmaxlen : DWORD;\n const entriesread : PDWORD;\n const totalentries : PDWORD;\n const servertype : DWORD;\n const domain : PWideChar;\n const resume_handle : PDWORD\n) : NET_API_STATUS; stdcall; external 'netapi32.dll';\n\nfunction NetApiBufferFree( //memory mgmt routine\n const Buffer : Pointer\n) : NET_API_STATUS; stdcall; external 'netapi32.dll';\n\nconst\n MAX_PREFERRED_LENGTH = DWORD(-1);\n NERR_Success = 0;\n SV_TYPE_ALL = $FFFFFFFF;\n SV_TYPE_DOMAIN_ENUM = $80000000;\n\n\nfunction TNetwork.ComputersInDomain: TStringList;\nvar\n pBuffer : PSERVER_INFO_100;\n pWork : PSERVER_INFO_100;\n dwEntriesRead : DWORD;\n dwTotalEntries : DWORD;\n i : integer;\n dwResult : NET_API_STATUS;\nbegin\n Result := TStringList.Create;\n Result.Clear;\n\n dwResult := NetServerEnum(nil,100,@pBuffer,MAX_PREFERRED_LENGTH,\n @dwEntriesRead,@dwTotalEntries,SV_TYPE_DOMAIN_ENUM,\n PWideChar(FDomainName),nil);\n\n if dwResult = NERR_SUCCESS then begin\n try\n pWork := pBuffer;\n for i := 1 to dwEntriesRead do begin\n Result.Add(pWork.sv100_name);\n inc(pWork);\n end; //for i\n finally\n NetApiBufferFree(pBuffer);\n end; //try-finally\n end //if no error\n else begin\n raise Exception.Create('Error while retrieving computer list from domain ' +\n FDomainName + #13#10 +\n SysErrorMessage(dwResult));\n end;\nend;\n<snip>\n</code></pre>\n"
},
{
"answer_id": 8888,
"author": "Shane O'Grady",
"author_id": 1115,
"author_profile": "https://Stackoverflow.com/users/1115",
"pm_score": 2,
"selected": true,
"text": "<p>You will need to use some LDAP queries</p>\n\n<h2>Here is some code I have used in a previous script (it was taken off the net somewhere, and I've left in the copyright notices)</h2>\n\n<pre><code>' This VBScript code gets the list of the domains contained in the \n' forest that the user running the script is logged into\n\n' ---------------------------------------------------------------\n' From the book \"Active Directory Cookbook\" by Robbie Allen\n' Publisher: O'Reilly and Associates\n' ISBN: 0-596-00466-4\n' Book web site: http://rallenhome.com/books/adcookbook/code.html\n' ---------------------------------------------------------------\n\nset objRootDSE = GetObject(\"LDAP://RootDSE\")\nstrADsPath = \"<GC://\" & objRootDSE.Get(\"rootDomainNamingContext\") & \">;\"\nstrFilter = \"(objectcategory=domainDNS);\"\nstrAttrs = \"name;\"\nstrScope = \"SubTree\"\n\nset objConn = CreateObject(\"ADODB.Connection\")\nobjConn.Provider = \"ADsDSOObject\"\nobjConn.Open \"Active Directory Provider\"\nset objRS = objConn.Execute(strADsPath & strFilter & strAttrs & strScope)\nobjRS.MoveFirst\nwhile Not objRS.EOF\n Wscript.Echo objRS.Fields(0).Value\n objRS.MoveNext\nwend\n</code></pre>\n\n<hr>\n\n<p><a href=\"http://www.janus-net.de/2005/11/18/getting-list-of-sub-domains-from-active-directory-with-c/\" rel=\"nofollow noreferrer\">Also a C# version</a></p>\n"
}
] | 2008/08/12 | [
"https://Stackoverflow.com/questions/8880",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/672/"
] | Using the Windows API, how can I get a list of domains on my network? | You will need to use some LDAP queries
Here is some code I have used in a previous script (it was taken off the net somewhere, and I've left in the copyright notices)
-------------------------------------------------------------------------------------------------------------------------------
```
' This VBScript code gets the list of the domains contained in the
' forest that the user running the script is logged into
' ---------------------------------------------------------------
' From the book "Active Directory Cookbook" by Robbie Allen
' Publisher: O'Reilly and Associates
' ISBN: 0-596-00466-4
' Book web site: http://rallenhome.com/books/adcookbook/code.html
' ---------------------------------------------------------------
set objRootDSE = GetObject("LDAP://RootDSE")
strADsPath = "<GC://" & objRootDSE.Get("rootDomainNamingContext") & ">;"
strFilter = "(objectcategory=domainDNS);"
strAttrs = "name;"
strScope = "SubTree"
set objConn = CreateObject("ADODB.Connection")
objConn.Provider = "ADsDSOObject"
objConn.Open "Active Directory Provider"
set objRS = objConn.Execute(strADsPath & strFilter & strAttrs & strScope)
objRS.MoveFirst
while Not objRS.EOF
Wscript.Echo objRS.Fields(0).Value
objRS.MoveNext
wend
```
---
[Also a C# version](http://www.janus-net.de/2005/11/18/getting-list-of-sub-domains-from-active-directory-with-c/) |
8,941 | <p><strong>Is there a way to enforce/limit the types that are passed to primitives?</strong> <em>(bool, int, string, etc.)</em></p>
<p>Now, I know you can limit the generic type parameter to a type or interface implementation via the <em>where</em> clause. However, this doesn't fit the bill for primitives (AFAIK) because they do not all have a common ground (apart from <em>object</em> before someone says! :P).</p>
<p>So, my current thoughts are to just grit my teeth and do a big <em>switch</em> statement and throw an <em>ArgumentException</em> on failure.</p>
<hr />
<p><strong>EDIT 1:</strong></p>
<p>Just to clarify:</p>
<p>The code definition should be like this:</p>
<pre><code>public class MyClass<GenericType> ....
</code></pre>
<p>And instantiation:</p>
<pre><code>MyClass<bool> = new MyClass<bool>(); // Legal
MyClass<string> = new MyClass<string>(); // Legal
MyClass<DataSet> = new MyClass<DataSet>(); // Illegal
MyClass<RobsFunkyHat> = new MyClass<RobsFunkyHat>(); // Illegal (but looks awesome!)
</code></pre>
<hr />
<p><strong>EDIT 2</strong></p>
<p>@Jon Limjap - Good point, and something I was already considering. I'm sure there is a generic method that can be used to determine if the type is of a value or reference type.</p>
<p>This could be useful in instantly removing a lot of the objects I don't want to deal with (but then you need to worry about the structs that are used such as <em>Size</em> ). Interesting problem no? :)</p>
<p>Here it is:</p>
<pre><code>where T: struct
</code></pre>
<p>Taken from <a href="http://msdn.microsoft.com/en-us/library/d5x73970.aspx" rel="nofollow noreferrer">MSDN</a>.</p>
<hr />
<p>I'm curious. Could this be done in .NET 3.x using extension methods? Create an interface, and implement the interface in the extension methods (which would probably be cleaner than a bit fat switch). Plus if you then need to later extend to any lightweight custom types, they can also implement the same interface, with no changes required to the base code.</p>
<p>What do you guys think?</p>
<p>The sad news is I am working in Framework 2!! :D</p>
<hr />
<p><strong>EDIT 3</strong></p>
<p>This was so simple following on from <a href="https://stackoverflow.com/questions/8941/generic-type-checking#8956">Jon Limjaps Pointer</a>.. So simple I almost want to cry, but it's great because the code works like a charm!</p>
<p>So here is what I did (you'll laugh!):</p>
<h2>Code added to the generic class</h2>
<pre><code>bool TypeValid()
{
// Get the TypeCode from the Primitive Type
TypeCode code = Type.GetTypeCode(typeof(PrimitiveDataType));
// All of the TypeCode Enumeration refer Primitive Types
// with the exception of Object and Empty (Null).
// Since I am willing to allow Null Types (at this time)
// all we need to check for is Object!
switch (code)
{
case TypeCode.Object:
return false;
default:
return true;
}
}
</code></pre>
<p>Then a little utility method to check the type and throw an exception,</p>
<pre><code>private void EnforcePrimitiveType()
{
if (!TypeValid())
throw new InvalidOperationException(
"Unable to Instantiate SimpleMetadata based on the Generic Type of '" + typeof(PrimitiveDataType).Name +
"' - this Class is Designed to Work with Primitive Data Types Only.");
}
</code></pre>
<p>All that then needs to be done is to call <em>EnforcePrimitiveType()</em> in the classes constructors. Job done! :-)</p>
<p>The only downside, it only throws an exception at runtime (obviously) rather than design time. But that's no big deal and could be picked up with utilities like <a href="http://en.wikipedia.org/wiki/FxCop" rel="nofollow noreferrer">FxCop</a> (which we don't use at work).</p>
<p>Special thanks to Jon Limjap on this one!</p>
| [
{
"answer_id": 8945,
"author": "Lars Mæhlum",
"author_id": 960,
"author_profile": "https://Stackoverflow.com/users/960",
"pm_score": 6,
"selected": false,
"text": "<pre><code>public class Class1<GenericType> where GenericType : struct\n{\n}\n</code></pre>\n\n<p>This one seemed to do the job..</p>\n"
},
{
"answer_id": 8954,
"author": "JoshL",
"author_id": 630,
"author_profile": "https://Stackoverflow.com/users/630",
"pm_score": 2,
"selected": false,
"text": "<p>Use a custom <a href=\"http://en.wikipedia.org/wiki/FxCop\" rel=\"nofollow noreferrer\">FxCop</a> rule that flags undesirable usage of <code>MyClass<></code>.</p>\n"
},
{
"answer_id": 8956,
"author": "Jon Limjap",
"author_id": 372,
"author_profile": "https://Stackoverflow.com/users/372",
"pm_score": 6,
"selected": true,
"text": "<p>Primitives appear to be specified in the <a href=\"http://msdn.microsoft.com/en-us/library/system.typecode.aspx\" rel=\"noreferrer\"><code>TypeCode</code></a> enumeration:</p>\n\n<p>Perhaps there is a way to find out if an object contains the <code>TypeCode enum</code> without having to cast it to an specific object or call <code>GetType()</code> or <code>typeof()</code>?</p>\n\n<p><strong>Update</strong> It was right under my nose. The code sample there shows this:</p>\n\n<pre><code>static void WriteObjectInfo(object testObject)\n{\n TypeCode typeCode = Type.GetTypeCode( testObject.GetType() );\n\n switch( typeCode )\n {\n case TypeCode.Boolean:\n Console.WriteLine(\"Boolean: {0}\", testObject);\n break;\n\n case TypeCode.Double:\n Console.WriteLine(\"Double: {0}\", testObject);\n break;\n\n default:\n Console.WriteLine(\"{0}: {1}\", typeCode.ToString(), testObject);\n break;\n }\n }\n}\n</code></pre>\n\n<p>It's still an ugly switch. But it's a good place to start!</p>\n"
},
{
"answer_id": 8980,
"author": "Keith",
"author_id": 905,
"author_profile": "https://Stackoverflow.com/users/905",
"pm_score": 5,
"selected": false,
"text": "<p>Pretty much what @Lars already said:</p>\n\n<pre><code>//Force T to be a value (primitive) type.\npublic class Class1<T> where T: struct\n\n//Force T to be a reference type.\npublic class Class1<T> where T: class\n\n//Force T to be a parameterless constructor.\npublic class Class1<T> where T: new()\n</code></pre>\n\n<p>All work in .NET 2, 3 and 3.5.</p>\n"
},
{
"answer_id": 69673,
"author": "Doug McClean",
"author_id": 11173,
"author_profile": "https://Stackoverflow.com/users/11173",
"pm_score": 2,
"selected": false,
"text": "<p>If you can tolerate using factory methods (instead of the constructors MyClass you asked for) you could always do something like this:</p>\n\n<pre><code>class MyClass<T>\n{\n private readonly T _value;\n\n private MyClass(T value) { _value = value; }\n\n public static MyClass<int> FromInt32(int value) { return new MyClass<int>(value); }\n public static MyClass<string> FromString(string value) { return new MyClass<string>(value); }\n // etc for all the primitive types, or whatever other fixed set of types you are concerned about\n}\n</code></pre>\n\n<p>A problem here is that you would need to type <code>MyClass<AnyTypeItDoesntMatter>.FromInt32</code>, which is annoying. There isn't a very good way around this if you want to maintain the private-ness of the constructor, but here are a couple of workarounds:</p>\n\n<ul>\n<li>Create an abstract class <code>MyClass</code>. Make <code>MyClass<T></code> inherit from <code>MyClass</code> <strong>and nest it within <code>MyClass</code></strong>. Move the static methods to <code>MyClass</code>. This will all the visibility work out, at the cost of having to access <code>MyClass<T></code> as <code>MyClass.MyClass<T></code>.</li>\n<li>Use <code>MyClass<T></code> as given. Make a static class <code>MyClass</code> which calls the static methods in <code>MyClass<T></code> using <code>MyClass<AnyTypeItDoesntMatter></code> (probably using the appropriate type each time, just for giggles).</li>\n<li>(Easier, but certainly weird) Make an abstract type <code>MyClass</code> <strong>which inherits from <code>MyClass<AnyTypeItDoesntMatter></code></strong>. (For concreteness, let's say <code>MyClass<int></code>.) Because you can call static methods defined in a base class through the name of a derived class, you can now use <code>MyClass.FromString</code>.</li>\n</ul>\n\n<p>This gives you static checking at the expense of more writing.</p>\n\n<p>If you are happy with dynamic checking, I would use some variation on the TypeCode solution above.</p>\n"
},
{
"answer_id": 217079,
"author": "Vivek",
"author_id": 7418,
"author_profile": "https://Stackoverflow.com/users/7418",
"pm_score": 2,
"selected": false,
"text": "<p>You can simplify the <code>EnforcePrimitiveType</code> method by using <a href=\"http://msdn.microsoft.com/en-us/library/system.type.isprimitive.aspx\" rel=\"nofollow noreferrer\"><code>typeof(PrimitiveDataType).IsPrimitive</code></a> property. Am I missing something?</p>\n"
},
{
"answer_id": 686709,
"author": "Matthew Boehlig",
"author_id": 83235,
"author_profile": "https://Stackoverflow.com/users/83235",
"pm_score": 2,
"selected": false,
"text": "<p>@Rob, <code>Enum</code>'s will slip through the <code>TypeValid</code> function as it's <code>TypeCode</code> is <code>Integer</code>. I've updated the function to also check for <code>Enum</code>.</p>\n\n<pre><code>Private Function TypeValid() As Boolean\n Dim g As Type = GetType(T)\n Dim code As TypeCode = Type.GetTypeCode(g)\n\n ' All of the TypeCode Enumeration refer Primitive Types\n ' with the exception of Object and Empty (Nothing).\n ' Note: must also catch Enum as its type is Integer.\n Select Case code\n Case TypeCode.Object\n Return False\n Case Else\n ' Enum's TypeCode is Integer, so check BaseType\n If g.BaseType Is GetType(System.Enum) Then\n Return False\n Else\n Return True\n End If\n End Select\nEnd Function\n</code></pre>\n"
},
{
"answer_id": 11690199,
"author": "gimlichael",
"author_id": 175073,
"author_profile": "https://Stackoverflow.com/users/175073",
"pm_score": 2,
"selected": false,
"text": "<p>Having a similar challenge, I was wondering how you guys felt about the <a href=\"http://msdn.microsoft.com/en-us/library/system.iconvertible.aspx\" rel=\"nofollow\">IConvertible interface</a>. It allows what the requester requires, and you can extend with your own implementations.</p>\n\n<p>Example:</p>\n\n<pre><code> public class MyClass<TKey>\n where TKey : IConvertible\n{\n // class intentionally abbreviated\n}\n</code></pre>\n\n<p>I am thinking about this as a solution, all though many of the suggested was part of my selection also.</p>\n\n<p>My concern is - however - is it misleading for potential developers using your class?</p>\n\n<p>Cheers - and thanks.</p>\n"
},
{
"answer_id": 72332537,
"author": "Chris Kao",
"author_id": 9823251,
"author_profile": "https://Stackoverflow.com/users/9823251",
"pm_score": 0,
"selected": false,
"text": "<p>In dotnet 6, I encountered this error when using <code>struct</code>:</p>\n<blockquote>\n<p>The type 'string' must be a non-nullable value type in order to use it as parameter 'T'</p>\n</blockquote>\n<p>So I use IConvertible instead</p>\n<pre><code>var intClass = new PrimitivesOnly<int>();\nvar doubleClass = new PrimitivesOnly<double>();\nvar boolClass = new PrimitivesOnly<bool>();\nvar stringClass = new PrimitivesOnly<string>();\nvar myAwesomeClass = new PrimitivesOnly<MyAwesomeClass>(); // illegal\n\n// The line below encounter issue when using "string" type\n// class PrimitivesOnly<T> where T : struct\nclass PrimitivesOnly<T> where T : IConvertible\n{\n \n}\n\nclass MyAwesomeClass\n{\n}\n</code></pre>\n"
}
] | 2008/08/12 | [
"https://Stackoverflow.com/questions/8941",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/832/"
] | **Is there a way to enforce/limit the types that are passed to primitives?** *(bool, int, string, etc.)*
Now, I know you can limit the generic type parameter to a type or interface implementation via the *where* clause. However, this doesn't fit the bill for primitives (AFAIK) because they do not all have a common ground (apart from *object* before someone says! :P).
So, my current thoughts are to just grit my teeth and do a big *switch* statement and throw an *ArgumentException* on failure.
---
**EDIT 1:**
Just to clarify:
The code definition should be like this:
```
public class MyClass<GenericType> ....
```
And instantiation:
```
MyClass<bool> = new MyClass<bool>(); // Legal
MyClass<string> = new MyClass<string>(); // Legal
MyClass<DataSet> = new MyClass<DataSet>(); // Illegal
MyClass<RobsFunkyHat> = new MyClass<RobsFunkyHat>(); // Illegal (but looks awesome!)
```
---
**EDIT 2**
@Jon Limjap - Good point, and something I was already considering. I'm sure there is a generic method that can be used to determine if the type is of a value or reference type.
This could be useful in instantly removing a lot of the objects I don't want to deal with (but then you need to worry about the structs that are used such as *Size* ). Interesting problem no? :)
Here it is:
```
where T: struct
```
Taken from [MSDN](http://msdn.microsoft.com/en-us/library/d5x73970.aspx).
---
I'm curious. Could this be done in .NET 3.x using extension methods? Create an interface, and implement the interface in the extension methods (which would probably be cleaner than a bit fat switch). Plus if you then need to later extend to any lightweight custom types, they can also implement the same interface, with no changes required to the base code.
What do you guys think?
The sad news is I am working in Framework 2!! :D
---
**EDIT 3**
This was so simple following on from [Jon Limjaps Pointer](https://stackoverflow.com/questions/8941/generic-type-checking#8956).. So simple I almost want to cry, but it's great because the code works like a charm!
So here is what I did (you'll laugh!):
Code added to the generic class
-------------------------------
```
bool TypeValid()
{
// Get the TypeCode from the Primitive Type
TypeCode code = Type.GetTypeCode(typeof(PrimitiveDataType));
// All of the TypeCode Enumeration refer Primitive Types
// with the exception of Object and Empty (Null).
// Since I am willing to allow Null Types (at this time)
// all we need to check for is Object!
switch (code)
{
case TypeCode.Object:
return false;
default:
return true;
}
}
```
Then a little utility method to check the type and throw an exception,
```
private void EnforcePrimitiveType()
{
if (!TypeValid())
throw new InvalidOperationException(
"Unable to Instantiate SimpleMetadata based on the Generic Type of '" + typeof(PrimitiveDataType).Name +
"' - this Class is Designed to Work with Primitive Data Types Only.");
}
```
All that then needs to be done is to call *EnforcePrimitiveType()* in the classes constructors. Job done! :-)
The only downside, it only throws an exception at runtime (obviously) rather than design time. But that's no big deal and could be picked up with utilities like [FxCop](http://en.wikipedia.org/wiki/FxCop) (which we don't use at work).
Special thanks to Jon Limjap on this one! | Primitives appear to be specified in the [`TypeCode`](http://msdn.microsoft.com/en-us/library/system.typecode.aspx) enumeration:
Perhaps there is a way to find out if an object contains the `TypeCode enum` without having to cast it to an specific object or call `GetType()` or `typeof()`?
**Update** It was right under my nose. The code sample there shows this:
```
static void WriteObjectInfo(object testObject)
{
TypeCode typeCode = Type.GetTypeCode( testObject.GetType() );
switch( typeCode )
{
case TypeCode.Boolean:
Console.WriteLine("Boolean: {0}", testObject);
break;
case TypeCode.Double:
Console.WriteLine("Double: {0}", testObject);
break;
default:
Console.WriteLine("{0}: {1}", typeCode.ToString(), testObject);
break;
}
}
}
```
It's still an ugly switch. But it's a good place to start! |
8,948 | <p>Is there a maintained package I can use to retrieve and set MP3 ID3 metadata using Python?</p>
| [
{
"answer_id": 8974,
"author": "PabloG",
"author_id": 394,
"author_profile": "https://Stackoverflow.com/users/394",
"pm_score": 3,
"selected": false,
"text": "<p>A simple example from the book Dive Into Python works ok for me, <a href=\"http://www.diveintopython.org/download/diveintopython-examples-5.4.zip\" rel=\"nofollow noreferrer\">this</a> is the download link, the example is fileinfo.py. Don't know if it's the best, but it can do the basic job.</p>\n\n<p>The entire book is available online <a href=\"http://www.diveintopython.org/\" rel=\"nofollow noreferrer\">here</a>.</p>\n"
},
{
"answer_id": 8976,
"author": "Philip Reynolds",
"author_id": 1087,
"author_profile": "https://Stackoverflow.com/users/1087",
"pm_score": 1,
"selected": false,
"text": "<p>It can depend on exactly what you want to do in addition to reading the metadata. If it is just simply the bitrate / name etc. that you need, and nothing else, something lightweight is probably best.</p>\n\n<p>If you're manipulating the mp3 past that PyMedia may be suitable.</p>\n\n<p>There are quite a few, whatever you do get, make sure and test it out on plenty of sample media. There are a few different versions of ID3 tags in particular, so make sure it's not too out of date. </p>\n\n<p>Personally I've used this small MP3Info class with luck. It is quite old though.</p>\n\n<p><a href=\"http://www.omniscia.org/~vivake/python/MP3Info.py\" rel=\"nofollow noreferrer\">http://www.omniscia.org/~vivake/python/MP3Info.py</a></p>\n"
},
{
"answer_id": 9358,
"author": "Harley Holcombe",
"author_id": 1057,
"author_profile": "https://Stackoverflow.com/users/1057",
"pm_score": 4,
"selected": false,
"text": "<p>What you're after is the <a href=\"http://id3-py.sourceforge.net/\" rel=\"noreferrer\">ID3</a> module. It's very simple and will give you exactly what you need. Just copy the ID3.py file into your site-packages directory and you'll be able to do something like the following:</p>\n\n<pre><code>from ID3 import *\ntry:\n id3info = ID3('file.mp3')\n print id3info\n # Change the tags\n id3info['TITLE'] = \"Green Eggs and Ham\"\n id3info['ARTIST'] = \"Dr. Seuss\"\n for k, v in id3info.items():\n print k, \":\", v\nexcept InvalidTagError, message:\n print \"Invalid ID3 tag:\", message\n</code></pre>\n"
},
{
"answer_id": 10845,
"author": "jkp",
"author_id": 912,
"author_profile": "https://Stackoverflow.com/users/912",
"pm_score": 5,
"selected": false,
"text": "<p>I've used <a href=\"https://github.com/quodlibet/mutagen\" rel=\"noreferrer\">mutagen</a> to edit tags in media files before. The nice thing about mutagen is that it can handle other formats, such as mp4, FLAC etc. I've written several scripts with a lot of success using this API.</p>\n"
},
{
"answer_id": 102285,
"author": "Owen",
"author_id": 2109,
"author_profile": "https://Stackoverflow.com/users/2109",
"pm_score": 7,
"selected": false,
"text": "<p>I used <a href=\"http://eyed3.nicfit.net/\" rel=\"noreferrer\">eyeD3</a> the other day with a lot of success. I found that it could add artwork to the ID3 tag which the other modules I looked at couldn't. You'll have to install using pip or download the tar and execute <code>python setup.py install</code> from the source folder. </p>\n\n<p>Relevant examples from the website are below.</p>\n\n<p>Reading the contents of an mp3 file containing either v1 or v2 tag info:</p>\n\n<pre><code> import eyeD3\n tag = eyeD3.Tag()\n tag.link(\"/some/file.mp3\")\n print tag.getArtist()\n print tag.getAlbum()\n print tag.getTitle()\n</code></pre>\n\n<p>Read an mp3 file (track length, bitrate, etc.) and access it's tag:</p>\n\n<pre><code>if eyeD3.isMp3File(f):\n audioFile = eyeD3.Mp3AudioFile(f)\n tag = audioFile.getTag()\n</code></pre>\n\n<p>Specific tag versions can be selected:</p>\n\n<pre><code> tag.link(\"/some/file.mp3\", eyeD3.ID3_V2)\n tag.link(\"/some/file.mp3\", eyeD3.ID3_V1)\n tag.link(\"/some/file.mp3\", eyeD3.ID3_ANY_VERSION) # The default.\n</code></pre>\n\n<p>Or you can iterate over the raw frames:</p>\n\n<pre><code> tag = eyeD3.Tag()\n tag.link(\"/some/file.mp3\")\n for frame in tag.frames:\n print frame\n</code></pre>\n\n<p>Once a tag is linked to a file it can be modified and saved:</p>\n\n<pre><code> tag.setArtist(u\"Cro-Mags\")\n tag.setAlbum(u\"Age of Quarrel\")\n tag.update()\n</code></pre>\n\n<p>If the tag linked in was v2 and you'd like to save it as v1:</p>\n\n<pre><code> tag.update(eyeD3.ID3_V1_1)\n</code></pre>\n\n<p>Read in a tag and remove it from the file:</p>\n\n<pre><code> tag.link(\"/some/file.mp3\")\n tag.remove()\n tag.update()\n</code></pre>\n\n<p>Add a new tag:</p>\n\n<pre><code> tag = eyeD3.Tag()\n tag.link('/some/file.mp3') # no tag in this file, link returned False\n tag.header.setVersion(eyeD3.ID3_V2_3)\n tag.setArtist('Fugazi')\n tag.update()\n</code></pre>\n"
},
{
"answer_id": 1936720,
"author": "Ciantic",
"author_id": 183544,
"author_profile": "https://Stackoverflow.com/users/183544",
"pm_score": 3,
"selected": false,
"text": "<p>I looked the above answers and found out that they are not good for my project because of licensing problems with GPL.</p>\n\n<p>And I found out this: <a href=\"http://pyid3lib.sourceforge.net/\" rel=\"noreferrer\">PyID3Lib</a>, while that particular <em>python binding</em> release date is old, it uses the <a href=\"http://id3lib.sourceforge.net/\" rel=\"noreferrer\">ID3Lib</a>, which itself is up to date.</p>\n\n<p>Notable to mention is that both are <strong>LGPL</strong>, and are good to go.</p>\n"
},
{
"answer_id": 4559380,
"author": "Corey Goldberg",
"author_id": 16148,
"author_profile": "https://Stackoverflow.com/users/16148",
"pm_score": 3,
"selected": false,
"text": "<p>check this one out:</p>\n\n<p><a href=\"https://github.com/Ciantic/songdetails\" rel=\"noreferrer\">https://github.com/Ciantic/songdetails</a></p>\n\n<p>Usage example:</p>\n\n<pre><code>>>> import songdetails\n>>> song = songdetails.scan(\"data/song.mp3\")\n>>> print song.duration\n0:03:12\n</code></pre>\n\n<p>Saving changes:</p>\n\n<pre><code>>>> import songdetails\n>>> song = songdetails.scan(\"data/commit.mp3\")\n>>> song.artist = \"Great artist\"\n>>> song.save()\n</code></pre>\n"
},
{
"answer_id": 6621839,
"author": "quabug",
"author_id": 667519,
"author_profile": "https://Stackoverflow.com/users/667519",
"pm_score": 3,
"selected": false,
"text": "<p>Just additional information to you guys:</p>\n\n<p>take a look at the section \"MP3 stuff and Metadata editors\" in the page of <a href=\"http://wiki.python.org/moin/PythonInMusic\" rel=\"noreferrer\">PythonInMusic</a>.</p>\n"
},
{
"answer_id": 31373513,
"author": "larryy",
"author_id": 3307951,
"author_profile": "https://Stackoverflow.com/users/3307951",
"pm_score": 1,
"selected": false,
"text": "<p>After some initial research I thought songdetails might fit my use case, but it doesn't handle .m4b files. Mutagen does. Note that while some have (reasonably) taken issue with Mutagen's surfacing of format-native keys, that vary from format to format (TIT2 for mp3, title for ogg, \\xa9nam for mp4, Title for WMA etc.), mutagen.File() has a (new?) easy=True parameter that provides EasyMP3/EasyID3 tags, which have a consistent, albeit limited, set of keys. I've only done limited testing so far, but the common keys, like album, artist, albumartist, genre, tracknumber, discnumber, etc. are all present and identical for .mb4 and .mp3 files when using easy=True, making it very convenient for my purposes.</p>\n"
},
{
"answer_id": 34970600,
"author": "Chris Redford",
"author_id": 130427,
"author_profile": "https://Stackoverflow.com/users/130427",
"pm_score": 5,
"selected": false,
"text": "<p>A problem with <code>eyed3</code> is that it will throw <code>NotImplementedError(\"Unable to write ID3 v2.2\")</code> for common MP3 files.</p>\n\n<p>In my experience, the <code>mutagen</code> class <code>EasyID3</code> works more reliably. Example:</p>\n\n<pre><code>from mutagen.easyid3 import EasyID3\n\naudio = EasyID3(\"example.mp3\")\naudio['title'] = u\"Example Title\"\naudio['artist'] = u\"Me\"\naudio['album'] = u\"My album\"\naudio['composer'] = u\"\" # clear\naudio.save()\n</code></pre>\n\n<p>All other tags can be accessed this way and saved, which will serve most purposes. More information can be found in the <a href=\"https://mutagen.readthedocs.io/en/latest/user/id3.html?#easy-id3\" rel=\"noreferrer\">Mutagen Tutorial</a>.</p>\n"
},
{
"answer_id": 38891913,
"author": "Abhijeet Deshani",
"author_id": 4972892,
"author_profile": "https://Stackoverflow.com/users/4972892",
"pm_score": 3,
"selected": false,
"text": "<p>easiest method is <a href=\"https://github.com/Ciantic/songdetails\" rel=\"nofollow noreferrer\">songdetails</a>..</p>\n<p>for read data</p>\n<pre><code>import songdetails\nsong = songdetails.scan("blah.mp3")\nif song is not None:\n print song.artist\n</code></pre>\n<p>similarly for edit</p>\n<pre><code>import songdetails\nsong = songdetails.scan("blah.mp3")\nif song is not None:\n song.artist = u"The Great Blah"\n song.save()\n</code></pre>\n<p>Don't forget to add <strong>u</strong> before name until you know chinese language.</p>\n<p>u can read and edit in bulk using python glob module</p>\n<p>ex.</p>\n<pre><code>import glob\nsongs = glob.glob('*') # script should be in directory of songs.\nfor song in songs:\n # do the above work.\n</code></pre>\n"
},
{
"answer_id": 49719777,
"author": "Elijah",
"author_id": 7732434,
"author_profile": "https://Stackoverflow.com/users/7732434",
"pm_score": 2,
"selected": false,
"text": "<p>The first answer that uses <a href=\"http://eyed3.nicfit.net/\" rel=\"nofollow noreferrer\">eyed3</a> is outdated so here is an updated version of it.</p>\n\n<p>Reading tags from an mp3 file:</p>\n\n<pre><code> import eyed3\n\n audiofile = eyed3.load(\"some/file.mp3\")\n print(audiofile.tag.artist)\n print(audiofile.tag.album)\n print(audiofile.tag.album_artist)\n print(audiofile.tag.title)\n print(audiofile.tag.track_num)\n</code></pre>\n\n<p>An example from the website to modify tags:</p>\n\n<pre><code> import eyed3\n\n audiofile = eyed3.load(\"some/file.mp3\")\n audiofile.tag.artist = u\"Integrity\"\n audiofile.tag.album = u\"Humanity Is The Devil\"\n audiofile.tag.album_artist = u\"Integrity\"\n audiofile.tag.title = u\"Hollow\"\n audiofile.tag.track_num = 2\n</code></pre>\n\n<p>An issue I encountered while trying to use eyed3 for the first time had to do with an import error of libmagic even though it was installed. To fix this install the magic-bin whl from <a href=\"https://pypi.python.org/pypi/python-magic-bin\" rel=\"nofollow noreferrer\">here</a></p>\n"
},
{
"answer_id": 49848525,
"author": "Marc Maxmeister",
"author_id": 536538,
"author_profile": "https://Stackoverflow.com/users/536538",
"pm_score": 3,
"selected": false,
"text": "<p>After trying the simple <code>pip install</code> route for eyeD3, pytaglib, and ID3 modules recommended here, I found this fourth option was the only one to work. The rest had import errors with missing dependencies in C++ or something magic or some other library that <code>pip</code> missed. So go with this one for basic reading of ID3 tags (all versions):</p>\n\n<p><a href=\"https://pypi.python.org/pypi/tinytag/0.18.0\" rel=\"noreferrer\">https://pypi.python.org/pypi/tinytag/0.18.0</a></p>\n\n<pre><code>from tinytag import TinyTag\ntag = TinyTag.get('/some/music.mp3')\n</code></pre>\n\n<p>List of possible attributes you can get with TinyTag:</p>\n\n<pre><code>tag.album # album as string\ntag.albumartist # album artist as string\ntag.artist # artist name as string\ntag.audio_offset # number of bytes before audio data begins\ntag.bitrate # bitrate in kBits/s\ntag.disc # disc number\ntag.disc_total # the total number of discs\ntag.duration # duration of the song in seconds\ntag.filesize # file size in bytes\ntag.genre # genre as string\ntag.samplerate # samples per second\ntag.title # title of the song\ntag.track # track number as string\ntag.track_total # total number of tracks as string\ntag.year # year or data as string\n</code></pre>\n\n<p>It was tiny and self-contained, as advertised.</p>\n"
},
{
"answer_id": 51044551,
"author": "Ashish Shirodkar",
"author_id": 8920642,
"author_profile": "https://Stackoverflow.com/users/8920642",
"pm_score": 2,
"selected": false,
"text": "<p>I would suggest <strong><a href=\"https://pypi.org/project/mp3-tagger/\" rel=\"nofollow noreferrer\">mp3-tagger</a></strong>. Best thing about this is it is distributed under <strong>MIT License</strong> and supports all the required attributes.</p>\n\n<pre><code>- artist;\n- album;\n- song;\n- track;\n- comment;\n- year;\n- genre;\n- band;\n- composer;\n- copyright;\n- url;\n- publisher.\n</code></pre>\n\n<p>Example:</p>\n\n<pre><code>from mp3_tagger import MP3File\n\n# Create MP3File instance.\nmp3 = MP3File('File_Name.mp3')\n\n# Get all tags.\ntags = mp3.get_tags()\nprint(tags)\n</code></pre>\n\n<p>It supports set, get, update and delete attributes of mp3 files.</p>\n"
},
{
"answer_id": 60105280,
"author": "apokhi",
"author_id": 12743260,
"author_profile": "https://Stackoverflow.com/users/12743260",
"pm_score": 1,
"selected": false,
"text": "<p>using <a href=\"https://github.com/nicfit/eyeD3\" rel=\"nofollow noreferrer\">https://github.com/nicfit/eyeD3</a></p>\n\n<pre><code>import eyed3\nimport os\n\nfor root, dirs, files in os.walk(folderp):\n for file in files:\n try:\n if file.find(\".mp3\") < 0:\n continue\n path = os.path.abspath(os.path.join(root , file))\n t = eyed3.load(path)\n print(t.tag.title , t.tag.artist)\n #print(t.getArtist())\n except Exception as e:\n print(e)\n continue\n</code></pre>\n"
},
{
"answer_id": 60625881,
"author": "Love and peace - Joe Codeswell",
"author_id": 601770,
"author_profile": "https://Stackoverflow.com/users/601770",
"pm_score": 3,
"selected": false,
"text": "<p>I used <a href=\"https://pypi.org/project/tinytag/\" rel=\"noreferrer\">tinytag 1.3.1</a> because</p>\n\n<ol>\n<li>It is actively supported:</li>\n</ol>\n\n<pre><code>1.3.0 (2020-03-09):\nadded option to ignore encoding errors ignore_errors #73\nImproved text decoding for many malformed files\n</code></pre>\n\n<ol start=\"2\">\n<li>It supports the major formats:</li>\n</ol>\n\n<pre><code>MP3 (ID3 v1, v1.1, v2.2, v2.3+)\nWave/RIFF\nOGG\nOPUS\nFLAC\nWMA\nMP4/M4A/M4B\n</code></pre>\n\n<ol start=\"3\">\n<li>The code WORKED in just a few minutes of development.</li>\n</ol>\n\n<pre class=\"lang-py prettyprint-override\"><code>from tinytag import TinyTag\n\nfileNameL ='''0bd1ab5f-e42c-4e48-a9e6-b485664594c1.mp3\n0ea292c0-2c4b-42d4-a059-98192ac8f55c.mp3\n1c49f6b7-6f94-47e1-a0ea-dd0265eb516c.mp3\n5c706f3c-eea4-4882-887a-4ff71326d284.mp3\n'''.split()\n\nfor fn in fileNameL:\n fpath = './data/'+fn\n tag = TinyTag.get(fpath)\n print()\n print('\"artist\": \"%s\",' % tag.artist)\n print('\"album\": \"%s\",' % tag.album)\n print('\"title\": \"%s\",' % tag.title)\n print('\"duration(secs)\": \"%s\",' % tag.duration)\n\n</code></pre>\n\n<ul>\n<li>RESULT</li>\n</ul>\n\n<pre><code>JoeTagPj>python joeTagTest.py\n\n\"artist\": \"Conan O’Brien Needs A Friend\",\n\"album\": \"Conan O’Brien Needs A Friend\",\n\"title\": \"17. Thomas Middleditch and Ben Schwartz\",\n\"duration(secs)\": \"3565.1829583532785\",\n\n\"artist\": \"Conan O’Brien Needs A Friend\",\n\"album\": \"Conan O’Brien Needs A Friend\",\n\"title\": \"Are you ready to make friends?\",\n\"duration(secs)\": \"417.71840447045264\",\n\n\"artist\": \"Conan O’Brien Needs A Friend\",\n\"album\": \"Conan O’Brien Needs A Friend\",\n\"title\": \"Introducing Conan’s new podcast\",\n\"duration(secs)\": \"327.22187551899646\",\n\n\"artist\": \"Conan O’Brien Needs A Friend\",\n\"album\": \"Conan O’Brien Needs A Friend\",\n\"title\": \"19. Ray Romano\",\n\"duration(secs)\": \"3484.1986772305863\",\n\nC:\\1d\\PodcastPjs\\JoeTagPj>\n</code></pre>\n"
}
] | 2008/08/12 | [
"https://Stackoverflow.com/questions/8948",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/145/"
] | Is there a maintained package I can use to retrieve and set MP3 ID3 metadata using Python? | I used [eyeD3](http://eyed3.nicfit.net/) the other day with a lot of success. I found that it could add artwork to the ID3 tag which the other modules I looked at couldn't. You'll have to install using pip or download the tar and execute `python setup.py install` from the source folder.
Relevant examples from the website are below.
Reading the contents of an mp3 file containing either v1 or v2 tag info:
```
import eyeD3
tag = eyeD3.Tag()
tag.link("/some/file.mp3")
print tag.getArtist()
print tag.getAlbum()
print tag.getTitle()
```
Read an mp3 file (track length, bitrate, etc.) and access it's tag:
```
if eyeD3.isMp3File(f):
audioFile = eyeD3.Mp3AudioFile(f)
tag = audioFile.getTag()
```
Specific tag versions can be selected:
```
tag.link("/some/file.mp3", eyeD3.ID3_V2)
tag.link("/some/file.mp3", eyeD3.ID3_V1)
tag.link("/some/file.mp3", eyeD3.ID3_ANY_VERSION) # The default.
```
Or you can iterate over the raw frames:
```
tag = eyeD3.Tag()
tag.link("/some/file.mp3")
for frame in tag.frames:
print frame
```
Once a tag is linked to a file it can be modified and saved:
```
tag.setArtist(u"Cro-Mags")
tag.setAlbum(u"Age of Quarrel")
tag.update()
```
If the tag linked in was v2 and you'd like to save it as v1:
```
tag.update(eyeD3.ID3_V1_1)
```
Read in a tag and remove it from the file:
```
tag.link("/some/file.mp3")
tag.remove()
tag.update()
```
Add a new tag:
```
tag = eyeD3.Tag()
tag.link('/some/file.mp3') # no tag in this file, link returned False
tag.header.setVersion(eyeD3.ID3_V2_3)
tag.setArtist('Fugazi')
tag.update()
``` |
8,966 | <p>I want to implement a paperless filing system and was looking to use WIA with C# for the image acquisition. There are quite a few sample projects on CodeProject, etc. However, after downloading every one of them that I can find, I have run into a problem.</p>
<p>In each and every one of them, the reference to WIALib is broken. When I go to add "Microsoft Windows Image Acquisition" as a reference, the only version available on my development workstation (also the machine that will run this) is 2.0.</p>
<p>Unfortunately, every one of these sample projects appear to have been coded against 1.x. The reference goes in as "WIA" instead of "WIALib". I took a shot, just changing the namespace import, but clearly the API is drastically different.</p>
<p>Is there any information on either implementing v2.0 or on upgrading one of these existing sample projects out there?</p>
| [
{
"answer_id": 9026,
"author": "J Wynia",
"author_id": 1124,
"author_profile": "https://Stackoverflow.com/users/1124",
"pm_score": 0,
"selected": false,
"text": "<p>It doesn't <strong>need</strong> to be WIA. I was mostly looking at the WIA setup because it offers the same basic interface for different scanners. I've got 3 scanners on this machine and the TWAIN drivers/software for all of them suck (like blocking the screen during scanning).</p>\n\n<p>For document management, I'm really looking for simple 200dpi grayscale scans, so most of the stuff in the TWAIN drivers is overkill. </p>\n\n<p>That said, asking here was part of my last attempt to figure out how to do it in WIA before moving on to TWAIN.</p>\n"
},
{
"answer_id": 107940,
"author": "Paul Jenkins",
"author_id": 657177,
"author_profile": "https://Stackoverflow.com/users/657177",
"pm_score": 6,
"selected": true,
"text": "<p>To access WIA, you'll need to add a reference to the COM library, \"Microsoft Windows Image Acquisition Library v2.0\" (wiaaut.dll).\nadd a \"using WIA;\"</p>\n\n<pre><code>const string wiaFormatJPEG = \"{B96B3CAE-0728-11D3-9D7B-0000F81EF32E}\";\nCommonDialogClass wiaDiag = new CommonDialogClass();\nWIA.ImageFile wiaImage = null;\n\nwiaImage = wiaDiag.ShowAcquireImage(\n WiaDeviceType.UnspecifiedDeviceType, \n WiaImageIntent.GrayscaleIntent, \n WiaImageBias.MaximizeQuality, \n wiaFormatJPEG, true, true, false);\n\nWIA.Vector vector = wiaImage.FileData;\n</code></pre>\n\n<p>(System.Drawing)</p>\n\n<pre><code>Image i = Image.FromStream(new MemoryStream((byte[])vector.get_BinaryData()));\ni.Save(filename)\n</code></pre>\n\n<p>Thats a basic way, works with my flatbed/doc feeder. If you need more than one document/page at a time though, there is probably a better way to do it (from what I could see, this only handles one image at a time, although I'm not entirely sure). While it is a WIA v1 doc, Scott Hanselman's <a href=\"http://blogs.msdn.com/coding4fun/archive/2006/10/31/912546.aspx\" rel=\"noreferrer\">Coding4Fun article on WIA</a> does contain some more info on how to do it for multiple pages, I think (I'm yet to go further than that myself)</p>\n\n<p>If its for a paperless office system, you might want also check out MODI (Office Document Imaging) to do all the OCR for you.</p>\n"
},
{
"answer_id": 146127,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 0,
"selected": false,
"text": "<p>Another note: You have to download the WIA 2.0 dll from Microsoft.com and then browse to the dll and add it to your project.</p>\n"
},
{
"answer_id": 3321118,
"author": "gideon",
"author_id": 368070,
"author_profile": "https://Stackoverflow.com/users/368070",
"pm_score": 1,
"selected": false,
"text": "<p>Heres how to target WIA 1.0 also so you can ship your app to Windows Xp. Something I was desperately looking for!!\n<a href=\"https://stackoverflow.com/questions/678844/how-to-develop-using-wia-1-under-vista\">How to develop using WIA 1 under Vista?</a></p>\n"
},
{
"answer_id": 7220414,
"author": "gideon",
"author_id": 368070,
"author_profile": "https://Stackoverflow.com/users/368070",
"pm_score": 1,
"selected": false,
"text": "<p><strong>Update</strong>: I'm adding this separately since its a different answer (a year later). I learnt XP has WIA 1.0 and Vista onward has WIA2.0. You can however install WIA 2.0 for Windows XP Sp1+ from <a href=\"http://www.microsoft.com/download/en/details.aspx?id=18287\" rel=\"nofollow\">here</a>.</p>\n\n<p>I then also made a small library with code I found somewhere on the interweb here, it also has the ability to scan multiple pages:\n<a href=\"http://adfwia.codeplex.com/\" rel=\"nofollow\">http://adfwia.codeplex.com/</a></p>\n"
}
] | 2008/08/12 | [
"https://Stackoverflow.com/questions/8966",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1124/"
] | I want to implement a paperless filing system and was looking to use WIA with C# for the image acquisition. There are quite a few sample projects on CodeProject, etc. However, after downloading every one of them that I can find, I have run into a problem.
In each and every one of them, the reference to WIALib is broken. When I go to add "Microsoft Windows Image Acquisition" as a reference, the only version available on my development workstation (also the machine that will run this) is 2.0.
Unfortunately, every one of these sample projects appear to have been coded against 1.x. The reference goes in as "WIA" instead of "WIALib". I took a shot, just changing the namespace import, but clearly the API is drastically different.
Is there any information on either implementing v2.0 or on upgrading one of these existing sample projects out there? | To access WIA, you'll need to add a reference to the COM library, "Microsoft Windows Image Acquisition Library v2.0" (wiaaut.dll).
add a "using WIA;"
```
const string wiaFormatJPEG = "{B96B3CAE-0728-11D3-9D7B-0000F81EF32E}";
CommonDialogClass wiaDiag = new CommonDialogClass();
WIA.ImageFile wiaImage = null;
wiaImage = wiaDiag.ShowAcquireImage(
WiaDeviceType.UnspecifiedDeviceType,
WiaImageIntent.GrayscaleIntent,
WiaImageBias.MaximizeQuality,
wiaFormatJPEG, true, true, false);
WIA.Vector vector = wiaImage.FileData;
```
(System.Drawing)
```
Image i = Image.FromStream(new MemoryStream((byte[])vector.get_BinaryData()));
i.Save(filename)
```
Thats a basic way, works with my flatbed/doc feeder. If you need more than one document/page at a time though, there is probably a better way to do it (from what I could see, this only handles one image at a time, although I'm not entirely sure). While it is a WIA v1 doc, Scott Hanselman's [Coding4Fun article on WIA](http://blogs.msdn.com/coding4fun/archive/2006/10/31/912546.aspx) does contain some more info on how to do it for multiple pages, I think (I'm yet to go further than that myself)
If its for a paperless office system, you might want also check out MODI (Office Document Imaging) to do all the OCR for you. |
8,970 | <p>Is it possible to access the iSight camera on a macbook programmatically? By this I mean I would like to be able to just grab still frames from the iSight camera on command and then do something with them. If so, is it only accessible using objective c, or could other languages be used as well? </p>
| [
{
"answer_id": 8977,
"author": "Michael Stum",
"author_id": 91,
"author_profile": "https://Stackoverflow.com/users/91",
"pm_score": 2,
"selected": false,
"text": "<p>I don't have a Mac here, but there is some Documentation up here:</p>\n\n<p><a href=\"http://developer.apple.com/documentation/Hardware/Conceptual/iSightProgGuide/01introduction/chapter_1_section_1.html\" rel=\"nofollow noreferrer\">http://developer.apple.com/documentation/Hardware/Conceptual/iSightProgGuide/01introduction/chapter_1_section_1.html</a></p>\n\n<p>It looks like you have to go through the QuickTime API. There is supposed to be a Sample Project called \"MungGrab\" which could be worth a look according to <a href=\"http://www.mailinglistarchive.com/[email protected]/msg02698.html\" rel=\"nofollow noreferrer\">this thread</a>.</p>\n"
},
{
"answer_id": 9128,
"author": "dbr",
"author_id": 745,
"author_profile": "https://Stackoverflow.com/users/745",
"pm_score": 0,
"selected": false,
"text": "<p>Aside from ObjC, you can use the PyObjC or RubyCocoa bindings to access it also. If you're not picky about which language, I'd say use Ruby, as PyObjC is horribly badly documented (even the official Apple page on it refers to the old version, not the one that came with OS X Leopard)</p>\n\n<p>Quartz Composer is probably the easiest way to access it, and .quartz files can be embed in applications pretty easily (and the data piped out to ObjC or such)</p>\n\n<p>Also, I suppose there should be an example or two of this in the /Developer/Examples/</p>\n"
},
{
"answer_id": 9975,
"author": "Theo",
"author_id": 1109,
"author_profile": "https://Stackoverflow.com/users/1109",
"pm_score": 1,
"selected": false,
"text": "<p>There's a command line utility called <code><a href=\"http://www.intergalactic.de/pages/iSight.html\" rel=\"nofollow noreferrer\">isightcapture</a></code> that does more or less what you want to do. You could probably get the code from the developer (his e-mail address is in the readme you get when you download the utility).</p>\n"
},
{
"answer_id": 10698,
"author": "Nick Brosnahan",
"author_id": 528,
"author_profile": "https://Stackoverflow.com/users/528",
"pm_score": 3,
"selected": false,
"text": "<p>You should check out the <a href=\"http://developer.apple.com/documentation/QuickTime/Conceptual/QTKitCaptureProgrammingGuide/Introduction/chapter_1_section_1.html#//apple_ref/doc/uid/TP40004574-CH1-DontLinkElementID_41\" rel=\"nofollow noreferrer\">QTKit Capture documentation</a>.</p>\n\n<p>On Leopard, you can get at all of it over the RubyCocoa bridge:</p>\n\n<pre><code>require 'osx/cocoa'\nOSX.require_framework(\"/System/Library/Frameworks/QTKit.framework\")\n\nOSX::QTCaptureDevice.inputDevices.each do |device|\n puts device.localizedDisplayName\nend\n</code></pre>\n"
},
{
"answer_id": 11150,
"author": "Jeremy",
"author_id": 1114,
"author_profile": "https://Stackoverflow.com/users/1114",
"pm_score": 2,
"selected": false,
"text": "<p>If you poke around Apple's mailing lists you can find some code to do it in Java as well. <a href=\"http://lists.apple.com/archives/QuickTime-java/2007/Jan/msg00003.html\" rel=\"nofollow noreferrer\">Here's a simple example suitable for capturing individual frames</a>, and <a href=\"http://lists.apple.com/archives/QuickTime-java/2005/Nov/msg00036.html\" rel=\"nofollow noreferrer\">here's a more complicated one that's fast enough to display live video</a>.</p>\n"
},
{
"answer_id": 280972,
"author": "Kristof Van Landschoot",
"author_id": 15745,
"author_profile": "https://Stackoverflow.com/users/15745",
"pm_score": 1,
"selected": false,
"text": "<p>One thing that hasn't been mentioned so far is the <a href=\"http://developer.apple.com/documentation/GraphicsImaging/Reference/IKImagePicker_Class/IKImagePicker_Reference.html\" rel=\"nofollow noreferrer\">IKPictureTaker</a>, which is part of Image Kit. This will come up with the standard OS provided panel to take pictures though, with all the possible filter functionality etc. included. I'm not sure if that's what you want.</p>\n\n<p>I suppose you can use it from other languages as well, considering there are things like <a href=\"http://www.cocoadev.com/index.pl?CocoaBridges\" rel=\"nofollow noreferrer\">cocoa bridges</a> but I have no experience with them.</p>\n\n<p>Googling also came up with <a href=\"https://stackoverflow.com/questions/57424?sort=newest\">another question on stackoverflow</a> that seems to address this issue.</p>\n"
},
{
"answer_id": 2193100,
"author": "meduz",
"author_id": 234547,
"author_profile": "https://Stackoverflow.com/users/234547",
"pm_score": 0,
"selected": false,
"text": "<p>From a related question which specifically asked the solution to be pythonic, you should give a try to <a href=\"http://github.com/motmot/pycamiface\" rel=\"nofollow noreferrer\">motmot's camiface</a> library from Andrew Straw. It also works with firewire cameras, but it works also with the isight, which is what you are looking for.</p>\n\n<p>From the tutorial:</p>\n\n<pre><code>import motmot.cam_iface.cam_iface_ctypes as cam_iface\nimport numpy as np\n\nmode_num = 0\ndevice_num = 0\nnum_buffers = 32\n\ncam = cam_iface.Camera(device_num,num_buffers,mode_num)\ncam.start_camera()\nframe = np.asarray(cam.grab_next_frame_blocking())\nprint 'grabbed frame with shape %s'%(frame.shape,)\n</code></pre>\n"
}
] | 2008/08/12 | [
"https://Stackoverflow.com/questions/8970",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/85/"
] | Is it possible to access the iSight camera on a macbook programmatically? By this I mean I would like to be able to just grab still frames from the iSight camera on command and then do something with them. If so, is it only accessible using objective c, or could other languages be used as well? | You should check out the [QTKit Capture documentation](http://developer.apple.com/documentation/QuickTime/Conceptual/QTKitCaptureProgrammingGuide/Introduction/chapter_1_section_1.html#//apple_ref/doc/uid/TP40004574-CH1-DontLinkElementID_41).
On Leopard, you can get at all of it over the RubyCocoa bridge:
```
require 'osx/cocoa'
OSX.require_framework("/System/Library/Frameworks/QTKit.framework")
OSX::QTCaptureDevice.inputDevices.each do |device|
puts device.localizedDisplayName
end
``` |
9,002 | <p>When I use the sp_send_dbmail stored procedure, I get a message saying that my mail was queued. However, it never seems to get delivered. I can see them in the queue if I run this SQL:</p>
<pre><code>SELECT * FROM msdb..sysmail_allitems WHERE sent_status = 'unsent'
</code></pre>
<p>This SQL returns a 1:</p>
<pre><code>SELECT is_broker_enabled FROM sys.databases WHERE name = 'msdb'
</code></pre>
<p>This stored procedure returns STARTED:</p>
<pre><code>msdb.dbo.sysmail_help_status_sp
</code></pre>
<p>The appropriate accounts and profiles have been set up and the mail was functioning at one point. There are no errors in msdb.dbo.sysmail_event_log. </p>
| [
{
"answer_id": 9212,
"author": "Stu",
"author_id": 414,
"author_profile": "https://Stackoverflow.com/users/414",
"pm_score": 2,
"selected": false,
"text": "<p>Have you tried </p>\n\n<pre><code>sysmail_stop_sp\n</code></pre>\n\n<p>then </p>\n\n<pre><code>sysmail_start_sp\n</code></pre>\n"
},
{
"answer_id": 9875,
"author": "Stu",
"author_id": 414,
"author_profile": "https://Stackoverflow.com/users/414",
"pm_score": 2,
"selected": true,
"text": "<p>Could be oodles of things. For example, I've seen (yes, actually seen) this happen after:</p>\n\n<ul>\n<li>Domain controller reboot </li>\n<li>Exchange server reboot</li>\n<li>Router outage</li>\n<li>Service account changes</li>\n<li>SQL Server running out of disk space</li>\n</ul>\n\n<p>So until it happens again, I wouldn't freak out over it.</p>\n"
},
{
"answer_id": 5979759,
"author": "UB.",
"author_id": 142962,
"author_profile": "https://Stackoverflow.com/users/142962",
"pm_score": 2,
"selected": false,
"text": "<p>I had the same problem and this is how I was able to resolve it.</p>\n\n<p>Go to <strong>Sql Agent >> Properties >> Alert System >> Check the Enable box for DBMail</strong> and add a profile.</p>\n\n<p><strong>Restart</strong> Agent and it works since then.</p>\n\n<p>Hope this helps,\n_Ub</p>\n"
}
] | 2008/08/12 | [
"https://Stackoverflow.com/questions/9002",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/162/"
] | When I use the sp\_send\_dbmail stored procedure, I get a message saying that my mail was queued. However, it never seems to get delivered. I can see them in the queue if I run this SQL:
```
SELECT * FROM msdb..sysmail_allitems WHERE sent_status = 'unsent'
```
This SQL returns a 1:
```
SELECT is_broker_enabled FROM sys.databases WHERE name = 'msdb'
```
This stored procedure returns STARTED:
```
msdb.dbo.sysmail_help_status_sp
```
The appropriate accounts and profiles have been set up and the mail was functioning at one point. There are no errors in msdb.dbo.sysmail\_event\_log. | Could be oodles of things. For example, I've seen (yes, actually seen) this happen after:
* Domain controller reboot
* Exchange server reboot
* Router outage
* Service account changes
* SQL Server running out of disk space
So until it happens again, I wouldn't freak out over it. |
9,009 | <p>This snippet of Perl code in my program is giving the wrong result.</p>
<pre><code>$condition ? $a = 2 : $a = 3 ;
print $a;
</code></pre>
<p>No matter what the value of <code>$condition</code> is, the output is always 3, how come?</p>
| [
{
"answer_id": 9011,
"author": "Pat",
"author_id": 238,
"author_profile": "https://Stackoverflow.com/users/238",
"pm_score": 7,
"selected": true,
"text": "<p>This is explained in the Perl <a href=\"http://perldoc.perl.org/perlop.html#Conditional-Operator\" rel=\"noreferrer\">documentation</a>.</p>\n\n<p>Because of Perl operator precedence the statement is being parsed as</p>\n\n<pre><code>($condition ? $a= 2 : $a ) = 3 ;\n</code></pre>\n\n<p>Because the ?: operator produces an assignable result, 3 is assigned to the result of the condition.</p>\n\n<p>When $condition is true this means ($a=2)=3 giving $a=3</p>\n\n<p>When $condition is false this means ($a)=3 giving $a=3</p>\n\n<p>The correct way to write this is</p>\n\n<pre><code>$a = ( $condition ? 2 : 3 );\nprint $a;\n</code></pre>\n\n<p>We got bitten by this at work, so I am posting here hoping others will find it useful.</p>\n"
},
{
"answer_id": 21800,
"author": "Tithonium",
"author_id": 2425,
"author_profile": "https://Stackoverflow.com/users/2425",
"pm_score": 4,
"selected": false,
"text": "<p>Just to extend the previous answer... If, for whatever reason, the assignments need to be part of the conditional, you'd want to write it thusly:</p>\n\n<pre><code>$condition ? ($a=2) : ($a=3);\n</code></pre>\n\n<p>This would be useful if you're assigning to different variables based on the condition.</p>\n\n<pre><code>$condition ? ($a=2) : ($b=3);\n</code></pre>\n\n<p>And if you're choosing the variable, but assigning the same thing no matter what, you could even do this:</p>\n\n<pre><code>($condition ? $a : $b) = 3;\n</code></pre>\n"
},
{
"answer_id": 43697,
"author": "Jagmal",
"author_id": 4406,
"author_profile": "https://Stackoverflow.com/users/4406",
"pm_score": 0,
"selected": false,
"text": "<p>One suggestion to Tithonium's answer above:</p>\n\n<p>If you are want to assign different values to the same variable, this might be better (the copy-book way): </p>\n\n<p>$a = ($condition) ? 2 : 3;</p>\n"
},
{
"answer_id": 46956,
"author": "theorbtwo",
"author_id": 4839,
"author_profile": "https://Stackoverflow.com/users/4839",
"pm_score": 5,
"selected": false,
"text": "<p>Once you have an inkling that you might be suffering from precedence problems, a trick to figure out what Perl thought you meant:</p>\n\n<pre><code>perl -MO=Deparse,-p -e '$condition ? $a= 2 : $a= 3 ; print $a;'\n</code></pre>\n\n<p>In your case, that'll show you:</p>\n\n<pre><code>(($condition ? ($a = 2) : $a) = 3);\nprint($a);\n-e syntax OK\n</code></pre>\n\n<p>...at which point you should be saying \"oh, that explains it\"!</p>\n"
},
{
"answer_id": 73753,
"author": "raldi",
"author_id": 7598,
"author_profile": "https://Stackoverflow.com/users/7598",
"pm_score": 2,
"selected": false,
"text": "<p>Because of Perl operator precedence the statement is being parsed as:</p>\n\n<pre><code>($condition ? $a = 2 : $a ) = 3 ;\n</code></pre>\n\n<p>Because the ?: operator produces an assignable result, 3 is assigned to the result of the condition.</p>\n\n<p>When $condition is true this means $a=2=3 giving $a=3</p>\n\n<p>When $condition is false this means $a=3 giving $a=3</p>\n\n<p>The correct way to write this is</p>\n\n<pre><code>$a = $condition ? 2 : 3;\n</code></pre>\n\n<p>In general, you should really get out of the habit of using conditionals to do assignment, as in the original example -- it's the sort of thing that leads to Perl getting a reputation for being write-only.</p>\n\n<p>A good rule of thumb is that conditionals are only for simple values, never expressions with side effects. When you or someone else needs to read this code eight months from now, would you prefer it to read like this?</p>\n\n<pre><code>$x < 3 ? foo($x) : bar($y);\n</code></pre>\n\n<p>Or like this?</p>\n\n<pre><code>if ($x < 3) {\n $foo($x);\n} else {\n $bar($y);\n}\n</code></pre>\n"
}
] | 2008/08/12 | [
"https://Stackoverflow.com/questions/9009",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/238/"
] | This snippet of Perl code in my program is giving the wrong result.
```
$condition ? $a = 2 : $a = 3 ;
print $a;
```
No matter what the value of `$condition` is, the output is always 3, how come? | This is explained in the Perl [documentation](http://perldoc.perl.org/perlop.html#Conditional-Operator).
Because of Perl operator precedence the statement is being parsed as
```
($condition ? $a= 2 : $a ) = 3 ;
```
Because the ?: operator produces an assignable result, 3 is assigned to the result of the condition.
When $condition is true this means ($a=2)=3 giving $a=3
When $condition is false this means ($a)=3 giving $a=3
The correct way to write this is
```
$a = ( $condition ? 2 : 3 );
print $a;
```
We got bitten by this at work, so I am posting here hoping others will find it useful. |
9,018 | <p>I am working at a client site where there is a proxy server (<code>HTTP</code>) in place. If I do a hard reset of the emulator it forgets network connection settings for the emulator and settings in the hosted Windows Mobile OS. If I 'save state and exit' it will lose all of these settings. I need to do hard resets regularly which means that I lose this information and spend a lot of time setting:</p>
<ul>
<li>The emulators associated network card</li>
<li>DNS servers for network card in the WM OS.</li>
<li>Proxy servers in connection settings of WM OS.</li>
</ul>
<p>How can I make my life easier? Can I save this as defaults in the emulator, or create an installer easily?</p>
| [
{
"answer_id": 9011,
"author": "Pat",
"author_id": 238,
"author_profile": "https://Stackoverflow.com/users/238",
"pm_score": 7,
"selected": true,
"text": "<p>This is explained in the Perl <a href=\"http://perldoc.perl.org/perlop.html#Conditional-Operator\" rel=\"noreferrer\">documentation</a>.</p>\n\n<p>Because of Perl operator precedence the statement is being parsed as</p>\n\n<pre><code>($condition ? $a= 2 : $a ) = 3 ;\n</code></pre>\n\n<p>Because the ?: operator produces an assignable result, 3 is assigned to the result of the condition.</p>\n\n<p>When $condition is true this means ($a=2)=3 giving $a=3</p>\n\n<p>When $condition is false this means ($a)=3 giving $a=3</p>\n\n<p>The correct way to write this is</p>\n\n<pre><code>$a = ( $condition ? 2 : 3 );\nprint $a;\n</code></pre>\n\n<p>We got bitten by this at work, so I am posting here hoping others will find it useful.</p>\n"
},
{
"answer_id": 21800,
"author": "Tithonium",
"author_id": 2425,
"author_profile": "https://Stackoverflow.com/users/2425",
"pm_score": 4,
"selected": false,
"text": "<p>Just to extend the previous answer... If, for whatever reason, the assignments need to be part of the conditional, you'd want to write it thusly:</p>\n\n<pre><code>$condition ? ($a=2) : ($a=3);\n</code></pre>\n\n<p>This would be useful if you're assigning to different variables based on the condition.</p>\n\n<pre><code>$condition ? ($a=2) : ($b=3);\n</code></pre>\n\n<p>And if you're choosing the variable, but assigning the same thing no matter what, you could even do this:</p>\n\n<pre><code>($condition ? $a : $b) = 3;\n</code></pre>\n"
},
{
"answer_id": 43697,
"author": "Jagmal",
"author_id": 4406,
"author_profile": "https://Stackoverflow.com/users/4406",
"pm_score": 0,
"selected": false,
"text": "<p>One suggestion to Tithonium's answer above:</p>\n\n<p>If you are want to assign different values to the same variable, this might be better (the copy-book way): </p>\n\n<p>$a = ($condition) ? 2 : 3;</p>\n"
},
{
"answer_id": 46956,
"author": "theorbtwo",
"author_id": 4839,
"author_profile": "https://Stackoverflow.com/users/4839",
"pm_score": 5,
"selected": false,
"text": "<p>Once you have an inkling that you might be suffering from precedence problems, a trick to figure out what Perl thought you meant:</p>\n\n<pre><code>perl -MO=Deparse,-p -e '$condition ? $a= 2 : $a= 3 ; print $a;'\n</code></pre>\n\n<p>In your case, that'll show you:</p>\n\n<pre><code>(($condition ? ($a = 2) : $a) = 3);\nprint($a);\n-e syntax OK\n</code></pre>\n\n<p>...at which point you should be saying \"oh, that explains it\"!</p>\n"
},
{
"answer_id": 73753,
"author": "raldi",
"author_id": 7598,
"author_profile": "https://Stackoverflow.com/users/7598",
"pm_score": 2,
"selected": false,
"text": "<p>Because of Perl operator precedence the statement is being parsed as:</p>\n\n<pre><code>($condition ? $a = 2 : $a ) = 3 ;\n</code></pre>\n\n<p>Because the ?: operator produces an assignable result, 3 is assigned to the result of the condition.</p>\n\n<p>When $condition is true this means $a=2=3 giving $a=3</p>\n\n<p>When $condition is false this means $a=3 giving $a=3</p>\n\n<p>The correct way to write this is</p>\n\n<pre><code>$a = $condition ? 2 : 3;\n</code></pre>\n\n<p>In general, you should really get out of the habit of using conditionals to do assignment, as in the original example -- it's the sort of thing that leads to Perl getting a reputation for being write-only.</p>\n\n<p>A good rule of thumb is that conditionals are only for simple values, never expressions with side effects. When you or someone else needs to read this code eight months from now, would you prefer it to read like this?</p>\n\n<pre><code>$x < 3 ? foo($x) : bar($y);\n</code></pre>\n\n<p>Or like this?</p>\n\n<pre><code>if ($x < 3) {\n $foo($x);\n} else {\n $bar($y);\n}\n</code></pre>\n"
}
] | 2008/08/12 | [
"https://Stackoverflow.com/questions/9018",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/636/"
] | I am working at a client site where there is a proxy server (`HTTP`) in place. If I do a hard reset of the emulator it forgets network connection settings for the emulator and settings in the hosted Windows Mobile OS. If I 'save state and exit' it will lose all of these settings. I need to do hard resets regularly which means that I lose this information and spend a lot of time setting:
* The emulators associated network card
* DNS servers for network card in the WM OS.
* Proxy servers in connection settings of WM OS.
How can I make my life easier? Can I save this as defaults in the emulator, or create an installer easily? | This is explained in the Perl [documentation](http://perldoc.perl.org/perlop.html#Conditional-Operator).
Because of Perl operator precedence the statement is being parsed as
```
($condition ? $a= 2 : $a ) = 3 ;
```
Because the ?: operator produces an assignable result, 3 is assigned to the result of the condition.
When $condition is true this means ($a=2)=3 giving $a=3
When $condition is false this means ($a)=3 giving $a=3
The correct way to write this is
```
$a = ( $condition ? 2 : 3 );
print $a;
```
We got bitten by this at work, so I am posting here hoping others will find it useful. |
9,019 | <p>I have a stored procedure which takes as its parameter a <em>varchar</em> which needs to be cast as a <em>datetime</em> for later use:</p>
<pre><code>SET @the_date = CAST(@date_string AS DATETIME)
</code></pre>
<p>I'm expecting the date string to be supplied in the format "DD-MON-YYYY", but in an effort to code defensively, if for some reason it can't be cast successfully, I want to default to the system date and continue. In PL/SQL I could use exception handling to achieve this and I could do this fairly easily with regular expressions too, but the limited pattern matching supported out of the box by Sybase doesn't let me do this and I can't rely on third party libraries or extensions. Is there a simple way of doing this in T-SQL?</p>
<p><em>NB: using Sybase ASE 12.5.3, there is no ISDATE function</em></p>
| [
{
"answer_id": 9023,
"author": "Nick Berardi",
"author_id": 17,
"author_profile": "https://Stackoverflow.com/users/17",
"pm_score": 0,
"selected": false,
"text": "<p>Found <a href=\"http://blog.sqlauthority.com/2007/07/12/sql-server-validate-field-for-date-datatype-using-function-isdate/\" rel=\"nofollow noreferrer\">this in the second result</a> in Google when searching for \"validate date string sql\".</p>\n\n<pre><code>----Invalid date\nSELECT ISDATE('30/2/2007')\nRETURNS : 0 (Zero)\n----Valid date\nSELECT ISDATE('12/12/20007')\nRETURNS : 1 (ONE)\n----Invalid DataType\nSELECT ISDATE('SQL')\nRETURNS : 0 (Zero)\n</code></pre>\n"
},
{
"answer_id": 9029,
"author": "Marius",
"author_id": 1008,
"author_profile": "https://Stackoverflow.com/users/1008",
"pm_score": 0,
"selected": false,
"text": "<p>Make sure SQL Server knows the order of Days, Months and Years in your string by executing</p>\n\n<pre><code>SET DATEFORMAT mdy;\n</code></pre>\n"
},
{
"answer_id": 9039,
"author": "Mike Woodhouse",
"author_id": 1060,
"author_profile": "https://Stackoverflow.com/users/1060",
"pm_score": 1,
"selected": false,
"text": "<p>My goodness, if the question was about Microsoft SQL Server then we'd have been in business!</p>\n\n<p>Sybase, sadly, is a whole 'nother database these days, since about 1997, in fact, give or take a year.</p>\n\n<p>If the input format simply has to be 'DD-MON-YYYY' and no exceptions, then I think a fair amount of validation was be achieved by slicing the input using SUBSTR(), after first doing some simple things, such as checking length.</p>\n\n<p>I thought that recent releases of Sybase (SQL Anywhere 11, for example) have regular expression support, however, although it's been a while since I've had to suffer T-SQL. Some googling leaves me in rather more doubt.</p>\n"
},
{
"answer_id": 941940,
"author": "Rebthor",
"author_id": 103630,
"author_profile": "https://Stackoverflow.com/users/103630",
"pm_score": 2,
"selected": true,
"text": "<p>I'm having a similar issue. You might be able to do something like this:</p>\n\n<pre><code>SET arithabort arith_overflow off\nSET @the_date = CAST(@date_string AS DATETIME)\nIF @the_date is NULL\n set @the_date = getdate()\nSET arithabort arith_overflow on\n</code></pre>\n\n<p>However, this doesn't work well in a select. It will work well in a cursor (boo) or in logic before / after a SQL batch.</p>\n"
},
{
"answer_id": 941999,
"author": "Vincent Buck",
"author_id": 90352,
"author_profile": "https://Stackoverflow.com/users/90352",
"pm_score": 0,
"selected": false,
"text": "<p>Did you try <code>convert</code> instead of <code>cast</code>?</p>\n\n<pre><code>select convert( datetime , @date_string ) \n</code></pre>\n"
},
{
"answer_id": 987884,
"author": "B0rG",
"author_id": 122093,
"author_profile": "https://Stackoverflow.com/users/122093",
"pm_score": 1,
"selected": false,
"text": "<p>Can't you do something like this:</p>\n\n<pre><code>SELECT @the_date = CASE @date_string\n WHEN '[0-9][0-9]-[A-Z][A-Z][A-Z]-[0-9][0-9][0-9][0-9]'\n THEN CONVERT(datetime, @date_string)\n ELSE GETDATE()\n END\n</code></pre>\n\n<p>?</p>\n"
}
] | 2008/08/12 | [
"https://Stackoverflow.com/questions/9019",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1030/"
] | I have a stored procedure which takes as its parameter a *varchar* which needs to be cast as a *datetime* for later use:
```
SET @the_date = CAST(@date_string AS DATETIME)
```
I'm expecting the date string to be supplied in the format "DD-MON-YYYY", but in an effort to code defensively, if for some reason it can't be cast successfully, I want to default to the system date and continue. In PL/SQL I could use exception handling to achieve this and I could do this fairly easily with regular expressions too, but the limited pattern matching supported out of the box by Sybase doesn't let me do this and I can't rely on third party libraries or extensions. Is there a simple way of doing this in T-SQL?
*NB: using Sybase ASE 12.5.3, there is no ISDATE function* | I'm having a similar issue. You might be able to do something like this:
```
SET arithabort arith_overflow off
SET @the_date = CAST(@date_string AS DATETIME)
IF @the_date is NULL
set @the_date = getdate()
SET arithabort arith_overflow on
```
However, this doesn't work well in a select. It will work well in a cursor (boo) or in logic before / after a SQL batch. |
9,022 | <p>Inside an asp.net page, should I use</p>
<pre><code><html><title>My page's title from México</title></html>
</code></pre>
<p>Or </p>
<pre><code><html><title>My page&rsquo;s title from M&eacute;xico</title></html>
</code></pre>
<p>Both examples have the same output. Since asp.net encodes all my pages to utf-8, there is no need to use html entities, is that right?</p>
| [
{
"answer_id": 9023,
"author": "Nick Berardi",
"author_id": 17,
"author_profile": "https://Stackoverflow.com/users/17",
"pm_score": 0,
"selected": false,
"text": "<p>Found <a href=\"http://blog.sqlauthority.com/2007/07/12/sql-server-validate-field-for-date-datatype-using-function-isdate/\" rel=\"nofollow noreferrer\">this in the second result</a> in Google when searching for \"validate date string sql\".</p>\n\n<pre><code>----Invalid date\nSELECT ISDATE('30/2/2007')\nRETURNS : 0 (Zero)\n----Valid date\nSELECT ISDATE('12/12/20007')\nRETURNS : 1 (ONE)\n----Invalid DataType\nSELECT ISDATE('SQL')\nRETURNS : 0 (Zero)\n</code></pre>\n"
},
{
"answer_id": 9029,
"author": "Marius",
"author_id": 1008,
"author_profile": "https://Stackoverflow.com/users/1008",
"pm_score": 0,
"selected": false,
"text": "<p>Make sure SQL Server knows the order of Days, Months and Years in your string by executing</p>\n\n<pre><code>SET DATEFORMAT mdy;\n</code></pre>\n"
},
{
"answer_id": 9039,
"author": "Mike Woodhouse",
"author_id": 1060,
"author_profile": "https://Stackoverflow.com/users/1060",
"pm_score": 1,
"selected": false,
"text": "<p>My goodness, if the question was about Microsoft SQL Server then we'd have been in business!</p>\n\n<p>Sybase, sadly, is a whole 'nother database these days, since about 1997, in fact, give or take a year.</p>\n\n<p>If the input format simply has to be 'DD-MON-YYYY' and no exceptions, then I think a fair amount of validation was be achieved by slicing the input using SUBSTR(), after first doing some simple things, such as checking length.</p>\n\n<p>I thought that recent releases of Sybase (SQL Anywhere 11, for example) have regular expression support, however, although it's been a while since I've had to suffer T-SQL. Some googling leaves me in rather more doubt.</p>\n"
},
{
"answer_id": 941940,
"author": "Rebthor",
"author_id": 103630,
"author_profile": "https://Stackoverflow.com/users/103630",
"pm_score": 2,
"selected": true,
"text": "<p>I'm having a similar issue. You might be able to do something like this:</p>\n\n<pre><code>SET arithabort arith_overflow off\nSET @the_date = CAST(@date_string AS DATETIME)\nIF @the_date is NULL\n set @the_date = getdate()\nSET arithabort arith_overflow on\n</code></pre>\n\n<p>However, this doesn't work well in a select. It will work well in a cursor (boo) or in logic before / after a SQL batch.</p>\n"
},
{
"answer_id": 941999,
"author": "Vincent Buck",
"author_id": 90352,
"author_profile": "https://Stackoverflow.com/users/90352",
"pm_score": 0,
"selected": false,
"text": "<p>Did you try <code>convert</code> instead of <code>cast</code>?</p>\n\n<pre><code>select convert( datetime , @date_string ) \n</code></pre>\n"
},
{
"answer_id": 987884,
"author": "B0rG",
"author_id": 122093,
"author_profile": "https://Stackoverflow.com/users/122093",
"pm_score": 1,
"selected": false,
"text": "<p>Can't you do something like this:</p>\n\n<pre><code>SELECT @the_date = CASE @date_string\n WHEN '[0-9][0-9]-[A-Z][A-Z][A-Z]-[0-9][0-9][0-9][0-9]'\n THEN CONVERT(datetime, @date_string)\n ELSE GETDATE()\n END\n</code></pre>\n\n<p>?</p>\n"
}
] | 2008/08/12 | [
"https://Stackoverflow.com/questions/9022",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/296/"
] | Inside an asp.net page, should I use
```
<html><title>My page's title from México</title></html>
```
Or
```
<html><title>My page’s title from México</title></html>
```
Both examples have the same output. Since asp.net encodes all my pages to utf-8, there is no need to use html entities, is that right? | I'm having a similar issue. You might be able to do something like this:
```
SET arithabort arith_overflow off
SET @the_date = CAST(@date_string AS DATETIME)
IF @the_date is NULL
set @the_date = getdate()
SET arithabort arith_overflow on
```
However, this doesn't work well in a select. It will work well in a cursor (boo) or in logic before / after a SQL batch. |
9,024 | <p>I'm using <code>IIS 5.1</code> in Windows XP on my development computer. I'm going to set up HTTPS on my company's web server, but I want to try doing it locally before doing it on a production system.</p>
<p>But when I go into the Directory Security tab of my web site's configuration section, the "Secure communication" groupbox is disabled. Is there something I need to do to make this groupbox enabled?</p>
| [
{
"answer_id": 9023,
"author": "Nick Berardi",
"author_id": 17,
"author_profile": "https://Stackoverflow.com/users/17",
"pm_score": 0,
"selected": false,
"text": "<p>Found <a href=\"http://blog.sqlauthority.com/2007/07/12/sql-server-validate-field-for-date-datatype-using-function-isdate/\" rel=\"nofollow noreferrer\">this in the second result</a> in Google when searching for \"validate date string sql\".</p>\n\n<pre><code>----Invalid date\nSELECT ISDATE('30/2/2007')\nRETURNS : 0 (Zero)\n----Valid date\nSELECT ISDATE('12/12/20007')\nRETURNS : 1 (ONE)\n----Invalid DataType\nSELECT ISDATE('SQL')\nRETURNS : 0 (Zero)\n</code></pre>\n"
},
{
"answer_id": 9029,
"author": "Marius",
"author_id": 1008,
"author_profile": "https://Stackoverflow.com/users/1008",
"pm_score": 0,
"selected": false,
"text": "<p>Make sure SQL Server knows the order of Days, Months and Years in your string by executing</p>\n\n<pre><code>SET DATEFORMAT mdy;\n</code></pre>\n"
},
{
"answer_id": 9039,
"author": "Mike Woodhouse",
"author_id": 1060,
"author_profile": "https://Stackoverflow.com/users/1060",
"pm_score": 1,
"selected": false,
"text": "<p>My goodness, if the question was about Microsoft SQL Server then we'd have been in business!</p>\n\n<p>Sybase, sadly, is a whole 'nother database these days, since about 1997, in fact, give or take a year.</p>\n\n<p>If the input format simply has to be 'DD-MON-YYYY' and no exceptions, then I think a fair amount of validation was be achieved by slicing the input using SUBSTR(), after first doing some simple things, such as checking length.</p>\n\n<p>I thought that recent releases of Sybase (SQL Anywhere 11, for example) have regular expression support, however, although it's been a while since I've had to suffer T-SQL. Some googling leaves me in rather more doubt.</p>\n"
},
{
"answer_id": 941940,
"author": "Rebthor",
"author_id": 103630,
"author_profile": "https://Stackoverflow.com/users/103630",
"pm_score": 2,
"selected": true,
"text": "<p>I'm having a similar issue. You might be able to do something like this:</p>\n\n<pre><code>SET arithabort arith_overflow off\nSET @the_date = CAST(@date_string AS DATETIME)\nIF @the_date is NULL\n set @the_date = getdate()\nSET arithabort arith_overflow on\n</code></pre>\n\n<p>However, this doesn't work well in a select. It will work well in a cursor (boo) or in logic before / after a SQL batch.</p>\n"
},
{
"answer_id": 941999,
"author": "Vincent Buck",
"author_id": 90352,
"author_profile": "https://Stackoverflow.com/users/90352",
"pm_score": 0,
"selected": false,
"text": "<p>Did you try <code>convert</code> instead of <code>cast</code>?</p>\n\n<pre><code>select convert( datetime , @date_string ) \n</code></pre>\n"
},
{
"answer_id": 987884,
"author": "B0rG",
"author_id": 122093,
"author_profile": "https://Stackoverflow.com/users/122093",
"pm_score": 1,
"selected": false,
"text": "<p>Can't you do something like this:</p>\n\n<pre><code>SELECT @the_date = CASE @date_string\n WHEN '[0-9][0-9]-[A-Z][A-Z][A-Z]-[0-9][0-9][0-9][0-9]'\n THEN CONVERT(datetime, @date_string)\n ELSE GETDATE()\n END\n</code></pre>\n\n<p>?</p>\n"
}
] | 2008/08/12 | [
"https://Stackoverflow.com/questions/9024",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/614/"
] | I'm using `IIS 5.1` in Windows XP on my development computer. I'm going to set up HTTPS on my company's web server, but I want to try doing it locally before doing it on a production system.
But when I go into the Directory Security tab of my web site's configuration section, the "Secure communication" groupbox is disabled. Is there something I need to do to make this groupbox enabled? | I'm having a similar issue. You might be able to do something like this:
```
SET arithabort arith_overflow off
SET @the_date = CAST(@date_string AS DATETIME)
IF @the_date is NULL
set @the_date = getdate()
SET arithabort arith_overflow on
```
However, this doesn't work well in a select. It will work well in a cursor (boo) or in logic before / after a SQL batch. |
9,033 | <p>This came to my mind after I learned the following from <a href="http://www.stackoverflow.com/questions/8941/generic-type-checking">this question</a>:</p>
<pre><code>where T : struct
</code></pre>
<p>We, C# developers, all know the basics of C#. I mean declarations, conditionals, loops, operators, etc.</p>
<p>Some of us even mastered the stuff like <a href="http://msdn.microsoft.com/en-us/library/512aeb7t.aspx" rel="nofollow noreferrer">Generics</a>, <a href="http://msdn.microsoft.com/en-us/library/bb397696.aspx" rel="nofollow noreferrer">anonymous types</a>, <a href="http://msdn.microsoft.com/en-us/library/bb397687.aspx" rel="nofollow noreferrer">lambdas</a>, <a href="http://msdn.microsoft.com/en-us/library/bb397676.aspx" rel="nofollow noreferrer">LINQ</a>, ...</p>
<p>But what are the most hidden features or tricks of C# that even C# fans, addicts, experts barely know?</p>
<h1>Here are the revealed features so far:</h1>
<p><br /></p>
<h2>Keywords</h2>
<ul>
<li><a href="http://msdn.microsoft.com/en-us/library/9k7k7cf0.aspx" rel="nofollow noreferrer"><code>yield</code></a> by <a href="https://stackoverflow.com/questions/9033/hidden-features-of-c/9035#9035">Michael Stum</a></li>
<li><code>var</code> by <a href="https://stackoverflow.com/questions/9033/hidden-features-of-c/9035#9035">Michael Stum</a></li>
<li><code>using()</code> statement by <a href="https://stackoverflow.com/questions/9033/hidden-features-of-c/9036#9036">kokos</a></li>
<li><code>readonly</code> by <a href="https://stackoverflow.com/questions/9033/hidden-features-of-c/9036#9036">kokos</a></li>
<li><code>as</code> by <a href="https://stackoverflow.com/questions/9033/hidden-features-of-c/9041#9041">Mike Stone</a></li>
<li><code>as</code> / <code>is</code> by <a href="https://stackoverflow.com/questions/9033/hidden-features-of-c/9070#9070">Ed Swangren</a></li>
<li><code>as</code> / <code>is</code> (improved) by <a href="https://stackoverflow.com/questions/9033/hidden-features-of-c/9092#9092">Rocketpants</a></li>
<li><code>default</code> by <a href="https://stackoverflow.com/questions/9033/hidden-features-of-c/9639#9639">deathofrats</a></li>
<li><code>global::</code> by <a href="https://stackoverflow.com/questions/9033/hidden-features-of-c/12152#12152">pzycoman</a></li>
<li><code>using()</code> blocks by <a href="https://stackoverflow.com/questions/9033/hidden-features-of-c/12316#12316">AlexCuse</a></li>
<li><code>volatile</code> by <a href="https://stackoverflow.com/questions/9033/hidden-features-of-c/59691#59691">Jakub Šturc</a></li>
<li><code>extern alias</code> by <a href="https://stackoverflow.com/questions/9033/hidden-features-of-c/37926#37926">Jakub Šturc</a></li>
</ul>
<h2>Attributes</h2>
<ul>
<li><a href="http://msdn.microsoft.com/en-us/library/system.componentmodel.defaultvalueattribute.aspx" rel="nofollow noreferrer"><code>DefaultValueAttribute</code></a> by <a href="https://stackoverflow.com/questions/9033/hidden-features-of-c/9035#9035">Michael Stum</a></li>
<li><a href="http://msdn.microsoft.com/en-us/library/system.obsoleteattribute.aspx" rel="nofollow noreferrer"><code>ObsoleteAttribute</code></a> by <a href="https://stackoverflow.com/questions/9033/hidden-features-of-c/9037#9037">DannySmurf</a></li>
<li><a href="http://msdn.microsoft.com/en-us/library/system.diagnostics.debuggerdisplayattribute.aspx" rel="nofollow noreferrer"><code>DebuggerDisplayAttribute</code></a> by <a href="https://stackoverflow.com/questions/9033/hidden-features-of-c/9048#9048">Stu</a></li>
<li><a href="http://msdn.microsoft.com/en-us/library/system.diagnostics.debuggerbrowsableattribute.aspx" rel="nofollow noreferrer"><code>DebuggerBrowsable</code></a> and <a href="http://msdn.microsoft.com/en-us/library/system.diagnostics.debuggerstepthroughattribute.aspx" rel="nofollow noreferrer"><code>DebuggerStepThrough</code></a> by <a href="https://stackoverflow.com/questions/9033/hidden-features-of-c/33474#33474">bdukes</a></li>
<li><a href="http://msdn.microsoft.com/en-us/library/system.threadstaticattribute(VS.71).aspx" rel="nofollow noreferrer"><code>ThreadStaticAttribute</code></a> by <a href="https://stackoverflow.com/questions/9033/hidden-features-of-c/13932#13932">marxidad</a></li>
<li><a href="http://msdn.microsoft.com/en-us/library/system.flagsattribute.aspx" rel="nofollow noreferrer"><code>FlagsAttribute</code></a> by <a href="https://stackoverflow.com/questions/9033/hidden-features-of-c/21752#21752">Martin Clarke</a></li>
<li><a href="http://msdn.microsoft.com/en-us/library/4xssyw96.aspx" rel="nofollow noreferrer"><code>ConditionalAttribute</code></a> by <a href="https://stackoverflow.com/questions/9033/hidden-features-of-c/35342#35342">AndrewBurns</a></li>
</ul>
<h2>Syntax</h2>
<ul>
<li><a href="http://msdn.microsoft.com/en-us/library/ms173224.aspx" rel="nofollow noreferrer"><code>??</code></a> (coalesce nulls) operator by <a href="https://stackoverflow.com/questions/9033/hidden-features-of-c/9036#9036">kokos</a></li>
<li>Number flaggings by <a href="https://stackoverflow.com/questions/9033/hidden-features-of-c/9038#9038">Nick Berardi</a></li>
<li><code>where T:new</code> by <a href="https://stackoverflow.com/questions/9033/hidden-features-of-c/9067#9067">Lars Mæhlum</a></li>
<li>Implicit generics by <a href="https://stackoverflow.com/questions/9033/hidden-features-of-c/9099#9099">Keith</a></li>
<li>One-parameter lambdas by <a href="https://stackoverflow.com/questions/9033/hidden-features-of-c/9099#9099">Keith</a></li>
<li>Auto properties by <a href="https://stackoverflow.com/questions/9033/hidden-features-of-c/9099#9099">Keith</a></li>
<li>Namespace aliases by <a href="https://stackoverflow.com/questions/9033/hidden-features-of-c/9099#9099">Keith</a></li>
<li>Verbatim string literals with @ by <a href="https://stackoverflow.com/questions/9033/hidden-features-of-c/9114#9114">Patrick</a></li>
<li><code>enum</code> values by <a href="https://stackoverflow.com/questions/9033/hidden-features-of-c/11738#11738">lfoust</a></li>
<li>@variablenames by <a href="https://stackoverflow.com/questions/9033/hidden-features-of-c/14088#14088">marxidad</a></li>
<li><code>event</code> operators by <a href="https://stackoverflow.com/questions/9033/hidden-features-of-c/14277#14277">marxidad</a></li>
<li>Format string brackets by <a href="https://stackoverflow.com/questions/9033/hidden-features-of-c/15321#15321">Portman</a></li>
<li>Property accessor accessibility modifiers by <a href="https://stackoverflow.com/questions/9033/hidden-features-of-c/15715#15715">xanadont</a></li>
<li>Conditional (ternary) operator (<code>?:</code>) by <a href="https://stackoverflow.com/questions/9033/hidden-features-of-c/16450#16450">JasonS</a></li>
<li><code>checked</code> and <code>unchecked</code> operators by <a href="https://stackoverflow.com/questions/9033/hidden-features-of-c/355991#355991">Binoj Antony</a></li>
<li><code>implicit and explicit</code> operators by <a href="https://stackoverflow.com/questions/9033/hidden-features-of-c/121470#121470">Flory</a></li>
</ul>
<h2>Language Features</h2>
<ul>
<li>Nullable types by <a href="https://stackoverflow.com/questions/9033/hidden-features-of-c/9055#9055">Brad Barker</a></li>
<li>Anonymous types by <a href="https://stackoverflow.com/questions/9033/hidden-features-of-c/9099#9099">Keith</a></li>
<li><code>__makeref __reftype __refvalue</code> by <a href="https://stackoverflow.com/questions/9033/hidden-features-of-c/9125#9125">Judah Himango</a></li>
<li>Object initializers by <a href="https://stackoverflow.com/questions/9033/hidden-features-of-c/9547#9547">lomaxx</a></li>
<li>Format strings by <a href="https://stackoverflow.com/questions/9033/hidden-features-of-c/10207#10207">David in Dakota</a></li>
<li>Extension Methods by <a href="https://stackoverflow.com/questions/9033/hidden-features-of-c/13932#13932">marxidad</a></li>
<li><code>partial</code> methods by <a href="https://stackoverflow.com/questions/9033/hidden-features-of-c/16395#16395">Jon Erickson</a></li>
<li>Preprocessor directives by <a href="https://stackoverflow.com/questions/9033/hidden-features-of-c/16482#16482">John Asbeck</a></li>
<li><code>DEBUG</code> pre-processor directive by <a href="https://stackoverflow.com/questions/9033/hidden-features-of-c/29081#29081">Robert Durgin</a></li>
<li>Operator overloading by <a href="https://stackoverflow.com/questions/9033/hidden-features-of-c/24914#24914">SefBkn</a></li>
<li>Type inferrence by <a href="https://stackoverflow.com/questions/9033/hidden-features-of-c/28811#28811">chakrit</a></li>
<li>Boolean operators <a href="http://www.java2s.com/Tutorial/CSharp/0160__Operator-Overload/truefalseoperatorforComplex.htm" rel="nofollow noreferrer">taken to next level</a> by <a href="https://stackoverflow.com/questions/9033/hidden-features-of-c/32148#32148">Rob Gough</a></li>
<li>Pass value-type variable as interface without boxing by <a href="https://stackoverflow.com/questions/9033/hidden-features-of-c/1820538#1820538">Roman Boiko</a></li>
<li>Programmatically determine declared variable type by <a href="https://stackoverflow.com/questions/9033/hidden-features-of-c/1789985#1789985">Roman Boiko</a></li>
<li>Static Constructors by <a href="https://stackoverflow.com/questions/9033/hidden-features-of-c/100321#100321">Chris</a></li>
<li>Easier-on-the-eyes / condensed ORM-mapping using LINQ by <a href="https://stackoverflow.com/questions/9033/hidden-features-of-c/2026781#2026781">roosteronacid</a></li>
<li><code>__arglist</code> by <a href="https://stackoverflow.com/a/1836944/171819">Zac Bowling</a></li>
</ul>
<h2>Visual Studio Features</h2>
<ul>
<li>Select block of text in editor by <a href="https://stackoverflow.com/questions/9033/hidden-features-of-c/1699477#1699477" title="block text selecting with alt key">Himadri</a></li>
<li>Snippets by <a href="https://stackoverflow.com/questions/9033/hidden-features-of-c/9037#9037">DannySmurf</a> </li>
</ul>
<h2>Framework</h2>
<ul>
<li><code>TransactionScope</code> by <a href="https://stackoverflow.com/questions/9033/hidden-features-of-c/9042#9042">KiwiBastard</a></li>
<li><code>DependantTransaction</code> by <a href="https://stackoverflow.com/questions/9033/hidden-features-of-c/9042#9042">KiwiBastard</a></li>
<li><code>Nullable<T></code> by <a href="https://stackoverflow.com/questions/9033/hidden-features-of-c/9118#9118">IainMH</a></li>
<li><code>Mutex</code> by <a href="https://stackoverflow.com/questions/9033/hidden-features-of-c/9181#9181">Diago</a></li>
<li><code>System.IO.Path</code> by <a href="https://stackoverflow.com/questions/9033/hidden-features-of-c/9401#9401">ageektrapped</a></li>
<li><code>WeakReference</code> by <a href="https://stackoverflow.com/questions/9033/hidden-features-of-c/14723#14723">Juan Manuel</a></li>
</ul>
<h2>Methods and Properties</h2>
<ul>
<li><code>String.IsNullOrEmpty()</code> method by <a href="https://stackoverflow.com/questions/9033/hidden-features-of-c/9042#9042">KiwiBastard</a></li>
<li><code>List.ForEach()</code> method by <a href="https://stackoverflow.com/questions/9033/hidden-features-of-c/9042#9042">KiwiBastard</a></li>
<li><code>BeginInvoke()</code>, <code>EndInvoke()</code> methods by <a href="https://stackoverflow.com/questions/9033/hidden-features-of-c/9581#9581">Will Dean</a></li>
<li><code>Nullable<T>.HasValue</code> and <code>Nullable<T>.Value</code> properties by <a href="https://stackoverflow.com/questions/9033/hidden-features-of-c/15393#15393">Rismo</a></li>
<li><code>GetValueOrDefault</code> method by <a href="https://stackoverflow.com/questions/9033/hidden-features-of-c/18158#18158">John Sheehan</a></li>
</ul>
<h2>Tips & Tricks</h2>
<ul>
<li>Nice method for event handlers by <a href="https://stackoverflow.com/questions/9033/hidden-features-of-c/9282#9282">Andreas H.R. Nilsson</a></li>
<li>Uppercase comparisons by <a href="https://stackoverflow.com/questions/9033/hidden-features-of-c/12137#12137">John</a></li>
<li>Access anonymous types without reflection by <a href="https://stackoverflow.com/questions/9033/hidden-features-of-c/13441#13441">dp</a></li>
<li>A quick way to lazily instantiate collection properties by <a href="https://stackoverflow.com/questions/9033/hidden-features-of-c/58945#58945">Will</a></li>
<li>JavaScript-like anonymous inline-functions by <a href="https://stackoverflow.com/questions/9033/hidden-features-of-c/1399130#1399130">roosteronacid</a></li>
</ul>
<h2>Other</h2>
<ul>
<li>netmodules by <a href="https://stackoverflow.com/questions/9033/hidden-features-of-c/9036#9036">kokos</a> </li>
<li><a href="http://www.albahari.com/nutshell/linqbridge.html" rel="nofollow noreferrer">LINQBridge</a> by <a href="https://stackoverflow.com/questions/9033/hidden-features-of-c/10886#10886">Duncan Smart</a> </li>
<li><a href="http://msdn.microsoft.com/en-us/concurrency/default.aspx" rel="nofollow noreferrer">Parallel Extensions</a> by <a href="https://stackoverflow.com/questions/9033/hidden-features-of-c/31293#31293">Joel Coehoorn</a></li>
</ul>
| [
{
"answer_id": 9035,
"author": "Michael Stum",
"author_id": 91,
"author_profile": "https://Stackoverflow.com/users/91",
"pm_score": 8,
"selected": false,
"text": "<p>\"<a href=\"http://msdn.microsoft.com/en-us/library/9k7k7cf0(VS.80).aspx\" rel=\"nofollow noreferrer\">yield</a>\" would come to my mind. Some of the attributes like <a href=\"http://msdn.microsoft.com/en-us/library/system.componentmodel.defaultvalueattribute.aspx\" rel=\"nofollow noreferrer\">[DefaultValue()]</a> are also among my favorites.</p>\n\n<p>The \"<a href=\"http://msdn.microsoft.com/en-us/library/bb383973.aspx\" rel=\"nofollow noreferrer\">var</a>\" keyword is a bit more known, but that you can use it in .NET 2.0 applications as well (as long as you <a href=\"http://blogs.msdn.com/msbuild/archive/2006/11/03/msbuild-orcas-and-multi-targeting.aspx\" rel=\"nofollow noreferrer\">use the .NET 3.5 compiler</a> and set it to output 2.0 code) does not seem to be known very well.</p>\n\n<p>Edit: kokos, thanks for pointing out the ?? operator, that's indeed really useful. Since it's a bit hard to google for it (as ?? is just ignored), here is the MSDN documentation page for that operator: <em><a href=\"http://msdn.microsoft.com/en-us/library/ms173224.aspx\" rel=\"nofollow noreferrer\">?? Operator (C# Reference)</a></em></p>\n"
},
{
"answer_id": 9036,
"author": "kokos",
"author_id": 1065,
"author_profile": "https://Stackoverflow.com/users/1065",
"pm_score": 7,
"selected": false,
"text": "<ol>\n<li><a href=\"http://msdn.microsoft.com/en-us/library/ms173224.aspx\" rel=\"nofollow noreferrer\">??</a> - coalescing operator </li>\n<li>using (<a href=\"http://msdn.microsoft.com/en-us/library/yh598w02(VS.80).aspx\" rel=\"nofollow noreferrer\">statement</a> / <a href=\"http://msdn.microsoft.com/en-us/library/sf0df423(VS.71).aspx\" rel=\"nofollow noreferrer\">directive</a>) - great keyword that can be used for more than just calling Dispose </li>\n<li><a href=\"http://msdn.microsoft.com/en-us/library/acdd6hb7(VS.100).aspx\" rel=\"nofollow noreferrer\">readonly</a> - should be used more </li>\n<li>netmodules - too bad there's no support in Visual Studio</li>\n</ol>\n"
},
{
"answer_id": 9037,
"author": "TheSmurf",
"author_id": 1975282,
"author_profile": "https://Stackoverflow.com/users/1975282",
"pm_score": 5,
"selected": false,
"text": "<p>Two of my personal favourites, which I see rarely used:</p>\n\n<ol>\n<li>Snippets (particularly for properties, which was made even better for Visual Studio 2008)</li>\n<li>The <a href=\"http://msdn.microsoft.com/en-us/library/system.obsoleteattribute.aspx\" rel=\"nofollow noreferrer\">ObsoleteAttribute</a></li>\n</ol>\n"
},
{
"answer_id": 9038,
"author": "Nick Berardi",
"author_id": 17,
"author_profile": "https://Stackoverflow.com/users/17",
"pm_score": 6,
"selected": false,
"text": "<p>Honestly the experts by the very definition should know this stuff. But to answer your question: <em><a href=\"http://msdn.microsoft.com/en-us/library/ya5y69ds.aspx\" rel=\"nofollow noreferrer\">Built-In Types Table (C# Reference)</a></em></p>\n\n<p>The compiler flagging for numbers are widely known for these:</p>\n\n<pre><code>Decimal = M\nFloat = F\nDouble = D\n\n// for example\ndouble d = 30D;\n</code></pre>\n\n<p>However these are more obscure:</p>\n\n<pre><code>Long = L\nUnsigned Long = UL\nUnsigned Int = U\n</code></pre>\n"
},
{
"answer_id": 9041,
"author": "Mike Stone",
"author_id": 122,
"author_profile": "https://Stackoverflow.com/users/122",
"pm_score": 8,
"selected": false,
"text": "<p>I didn't know the \"as\" keyword for quite a while.</p>\n\n<pre><code>MyClass myObject = (MyClass) obj;\n</code></pre>\n\n<p>vs</p>\n\n<pre><code>MyClass myObject = obj as MyClass;\n</code></pre>\n\n<p>The second will return null if obj isn't a MyClass, rather than throw a class cast exception.</p>\n"
},
{
"answer_id": 9042,
"author": "JamesSugrue",
"author_id": 1075,
"author_profile": "https://Stackoverflow.com/users/1075",
"pm_score": 6,
"selected": false,
"text": "<ul>\n<li>TransactionScope and <a href=\"http://msdn.microsoft.com/en-us/library/system.transactions.dependenttransaction.aspx\" rel=\"nofollow noreferrer\">DependentTransaction</a> in System.Transactions is a lightweight way to use transaction processing in .NET - it's not just for <a href=\"http://msdn.microsoft.com/en-us/library/ms229973.aspx\" rel=\"nofollow noreferrer\">Database transactions either</a></li>\n<li>String.IsNullOrEmpty is one that I am surprised to learn a lot of developers don't know about</li>\n<li>List.ForEach - iterate through your generic list using a delegate method</li>\n</ul>\n\n<p>There are more, but that is the three obvious ones of the top of my head...</p>\n"
},
{
"answer_id": 9048,
"author": "Stu",
"author_id": 414,
"author_profile": "https://Stackoverflow.com/users/414",
"pm_score": 8,
"selected": false,
"text": "<p>Attributes in general, but most of all <a href=\"http://msdn.microsoft.com/en-us/library/x810d419.aspx\" rel=\"nofollow noreferrer\">DebuggerDisplay</a>. Saves you years.</p>\n"
},
{
"answer_id": 9055,
"author": "Brad Barker",
"author_id": 12081,
"author_profile": "https://Stackoverflow.com/users/12081",
"pm_score": 8,
"selected": false,
"text": "<p>I tend to find that most C# developers don't know about 'nullable' types. Basically, primitives that can have a null value.</p>\n\n<pre><code>double? num1 = null; \ndouble num2 = num1 ?? -100;\n</code></pre>\n\n<p>Set a nullable double, <em>num1</em>, to null, then set a regular double, <em>num2</em>, to <em>num1</em> or <em>-100</em> if <em>num1</em> was null.</p>\n\n<p><a href=\"http://msdn.microsoft.com/en-us/library/1t3y8s4s(VS.80).aspx\" rel=\"nofollow noreferrer\">http://msdn.microsoft.com/en-us/library/1t3y8s4s(VS.80).aspx</a></p>\n\n<p>one more thing about Nullable type:</p>\n\n<pre><code>DateTime? tmp = new DateTime();\ntmp = null;\nreturn tmp.ToString();\n</code></pre>\n\n<p>it is return String.Empty. Check <a href=\"https://stackoverflow.com/questions/4547112/is-nullable-datetime-work-correct\">this</a> link for more details</p>\n"
},
{
"answer_id": 9067,
"author": "Lars Mæhlum",
"author_id": 960,
"author_profile": "https://Stackoverflow.com/users/960",
"pm_score": 4,
"selected": false,
"text": "<p>I have often come across the need to have a generic parameter-object persisted into the viewstate in a base class.</p>\n\n<pre><code>public abstract class BaseListControl<ListType,KeyType,ParameterType>\n : UserControl \n where ListType : BaseListType\n && ParameterType : BaseParameterType, new\n{\n\n private const string viewStateFilterKey = \"FilterKey\";\n\n protected ParameterType Filters\n {\n get\n {\n if (ViewState[viewStateFilterKey] == null)\n ViewState[viewStateFilterKey]= new ParameterType();\n\n return ViewState[viewStateFilterKey] as ParameterType;\n }\n set\n {\n ViewState[viewStateFilterKey] = value;\n }\n }\n\n}\n</code></pre>\n\n<p>Usage:</p>\n\n<pre><code>private void SomeEventHappened(object sender, EventArgs e)\n{\n Filters.SomeValue = SomeControl.SelectedValue;\n}\n\nprivate void TimeToFetchSomeData()\n{\n GridView.DataSource = Repository.GetList(Filters);\n}\n</code></pre>\n\n<p>This little trick with the \"where ParameterType : BaseParameterType, new\" is what makes it really work.</p>\n\n<p>With this property in my baseclass, I can automate handling of paging, setting filter values to filter a gridview, make sorting really easy, etc.</p>\n\n<p>I am really just saying that generics can be an enormously powerful beast in the wrong hands.</p>\n"
},
{
"answer_id": 9092,
"author": "Dogmang",
"author_id": 1135,
"author_profile": "https://Stackoverflow.com/users/1135",
"pm_score": 7,
"selected": false,
"text": "<p>@Ed, I'm a bit reticent about posting this as it's little more than nitpicking. However, I would point out that in your code sample:</p>\n\n<pre><code>MyClass c;\n if (obj is MyClass)\n c = obj as MyClass\n</code></pre>\n\n<p>If you're going to use 'is', why follow it up with a safe cast using 'as'? If you've ascertained that obj is indeed MyClass, a bog-standard cast:</p>\n\n<pre><code>c = (MyClass)obj\n</code></pre>\n\n<p>...is never going to fail.</p>\n\n<p>Similarly, you could just say:</p>\n\n<pre><code>MyClass c = obj as MyClass;\nif(c != null)\n{\n ...\n}\n</code></pre>\n\n<p>I don't know enough about .NET's innards to be sure, but my instincts tell me that this would cut a maximum of two type casts operations down to a maximum of one. It's hardly likely to break the processing bank either way; personally, I think the latter form looks cleaner too.</p>\n"
},
{
"answer_id": 9099,
"author": "Keith",
"author_id": 905,
"author_profile": "https://Stackoverflow.com/users/905",
"pm_score": 8,
"selected": false,
"text": "<p>Everything else, plus </p>\n\n<p>1) implicit generics (why only on methods and not on classes?)</p>\n\n<pre><code>void GenericMethod<T>( T input ) { ... }\n\n//Infer type, so\nGenericMethod<int>(23); //You don't need the <>.\nGenericMethod(23); //Is enough.\n</code></pre>\n\n<p>2) simple lambdas with one parameter:</p>\n\n<pre><code>x => x.ToString() //simplify so many calls\n</code></pre>\n\n<p>3) anonymous types and initialisers:</p>\n\n<pre><code>//Duck-typed: works with any .Add method.\nvar colours = new Dictionary<string, string> {\n { \"red\", \"#ff0000\" },\n { \"green\", \"#00ff00\" },\n { \"blue\", \"#0000ff\" }\n};\n\nint[] arrayOfInt = { 1, 2, 3, 4, 5 };\n</code></pre>\n\n<hr>\n\n<p>Another one:</p>\n\n<p>4) Auto properties can have different scopes:</p>\n\n<pre><code>public int MyId { get; private set; }\n</code></pre>\n\n<hr>\n\n<p>Thanks @pzycoman for reminding me:</p>\n\n<p>5) Namespace aliases (not that you're likely to need this particular distinction):</p>\n\n<pre><code>using web = System.Web.UI.WebControls;\nusing win = System.Windows.Forms;\n\nweb::Control aWebControl = new web::Control();\nwin::Control aFormControl = new win::Control();\n</code></pre>\n"
},
{
"answer_id": 9114,
"author": "Patrick",
"author_id": 429,
"author_profile": "https://Stackoverflow.com/users/429",
"pm_score": 7,
"selected": false,
"text": "<p>Here's a useful one for regular expressions and file paths:</p>\n\n<pre><code>\"c:\\\\program files\\\\oldway\"\n@\"c:\\program file\\newway\"\n</code></pre>\n\n<p>The @ tells the compiler to ignore any escape characters in a string.</p>\n"
},
{
"answer_id": 9118,
"author": "Iain Holder",
"author_id": 1122,
"author_profile": "https://Stackoverflow.com/users/1122",
"pm_score": 3,
"selected": false,
"text": "<p>@Brad Barker</p>\n\n<p>I think if you have to use nullable types, it's better to use Nullable<.T> rather than the question mark notation. It makes it eye-achingly obvious that magic is occurring.\nNot sure why anyone would ever want to use Nullable<.bool> though. :-)</p>\n\n<p>Krzysztof Cwalina (one of the authors of Framwork Design Guidlines) has a good post here:\n<a href=\"http://blogs.msdn.com/kcwalina/archive/2008/07/16/Nullable.aspx\" rel=\"nofollow noreferrer\">http://blogs.msdn.com/kcwalina/archive/2008/07/16/Nullable.aspx</a></p>\n\n<p>And Mike Hadlow has a nice post on <a href=\"http://mikehadlow.blogspot.com/2006/10/nullability-voodoo.html\" rel=\"nofollow noreferrer\">Nullability Voodoo</a></p>\n"
},
{
"answer_id": 9125,
"author": "Judah Gabriel Himango",
"author_id": 536,
"author_profile": "https://Stackoverflow.com/users/536",
"pm_score": 8,
"selected": false,
"text": "<p>Here are some interesting hidden C# features, in the form of undocumented C# keywords:</p>\n\n<pre><code>__makeref\n\n__reftype\n\n__refvalue\n\n__arglist\n</code></pre>\n\n<p>These are undocumented C# keywords (even Visual Studio recognizes them!) that were added to for a more efficient boxing/unboxing prior to generics. They work in coordination with the System.TypedReference struct.</p>\n\n<p>There's also __arglist, which is used for variable length parameter lists.</p>\n\n<p>One thing folks don't know much about is <a href=\"http://msdn.microsoft.com/en-us/library/ms404247.aspx\" rel=\"noreferrer\">System.WeakReference</a> -- a very useful class that keeps track of an object but still allows the garbage collector to collect it.</p>\n\n<p>The most useful \"hidden\" feature would be the yield return keyword. It's not really hidden, but a lot of folks don't know about it. LINQ is built atop this; it allows for delay-executed queries by generating a state machine under the hood. Raymond Chen recently posted about the <a href=\"http://blogs.msdn.com/oldnewthing/archive/2008/08/12/8849519.aspx\" rel=\"noreferrer\">internal, gritty details</a>.</p>\n"
},
{
"answer_id": 9129,
"author": "Michael Stum",
"author_id": 91,
"author_profile": "https://Stackoverflow.com/users/91",
"pm_score": 7,
"selected": false,
"text": "<blockquote>\n <p>Not sure why anyone would ever want to use Nullable<bool> though. :-)</p>\n</blockquote>\n\n<p>True, False, <a href=\"http://thedailywtf.com/Articles/What_Is_Truth_0x3f_.aspx\" rel=\"nofollow noreferrer\">FileNotFound</a>?</p>\n"
},
{
"answer_id": 9181,
"author": "BinaryMisfit",
"author_id": 146270,
"author_profile": "https://Stackoverflow.com/users/146270",
"pm_score": 3,
"selected": false,
"text": "<p>In no particular order:</p>\n\n<pre><code>Lists<>\nMutex\n</code></pre>\n\n<p>The new property definitions shortcut in Framework 3.5.</p>\n"
},
{
"answer_id": 9282,
"author": "andynil",
"author_id": 446,
"author_profile": "https://Stackoverflow.com/users/446",
"pm_score": 8,
"selected": false,
"text": "<p><strong>Avoid checking for null event handlers</strong></p>\n\n<p>Adding an empty delegate to events at declaration, suppressing the need to always check the event for null before calling it is awesome. Example:</p>\n\n<pre><code>public delegate void MyClickHandler(object sender, string myValue);\npublic event MyClickHandler Click = delegate {}; // add empty delegate!\n</code></pre>\n\n<p>Let you do this</p>\n\n<pre><code>public void DoSomething()\n{\n Click(this, \"foo\");\n}\n</code></pre>\n\n<p>Instead of this</p>\n\n<pre><code>public void DoSomething()\n{\n // Unnecessary!\n MyClickHandler click = Click;\n if (click != null) // Unnecessary! \n {\n click(this, \"foo\");\n }\n}\n</code></pre>\n\n<p>Please also see this <a href=\"https://stackoverflow.com/questions/840715/the-proper-way-of-raising-events-in-the-net-framework\">related discussion</a> and this <a href=\"http://blogs.msdn.com/ericlippert/archive/2009/04/29/events-and-races.aspx\" rel=\"nofollow noreferrer\">blog post</a> by Eric Lippert on this topic (and possible downsides).</p>\n"
},
{
"answer_id": 9401,
"author": "ageektrapped",
"author_id": 631,
"author_profile": "https://Stackoverflow.com/users/631",
"pm_score": 10,
"selected": false,
"text": "<p>This isn't C# per se, but I haven't seen anyone who really uses <code>System.IO.Path.Combine()</code> to the extent that they should. In fact, the whole Path class is really useful, but <strong>no one uses it!</strong></p>\n\n<p>I'm willing to bet that every production app has the following code, even though it shouldn't:</p>\n\n<pre><code>string path = dir + \"\\\\\" + fileName;\n</code></pre>\n"
},
{
"answer_id": 9406,
"author": "lomaxx",
"author_id": 493,
"author_profile": "https://Stackoverflow.com/users/493",
"pm_score": 8,
"selected": false,
"text": "<blockquote>\n <p>The @ tells the compiler to ignore any\n escape characters in a string.</p>\n</blockquote>\n\n<p>Just wanted to clarify this one... it doesn't tell it to ignore the escape characters, it actually tells the compiler to interpret the string as a literal.</p>\n\n<p>If you have </p>\n\n<pre><code>string s = @\"cat\n dog\n fish\"\n</code></pre>\n\n<p>it will actually print out as (note that it even includes the whitespace used for indentation):</p>\n\n<pre><code>cat\n dog\n fish\n</code></pre>\n"
},
{
"answer_id": 9547,
"author": "lomaxx",
"author_id": 493,
"author_profile": "https://Stackoverflow.com/users/493",
"pm_score": 8,
"selected": false,
"text": "<p>Two things I like are Automatic properties so you can collapse your code down even further:</p>\n\n<pre><code>private string _name;\npublic string Name\n{\n get\n {\n return _name;\n }\n set\n {\n _name = value;\n }\n}\n</code></pre>\n\n<p>becomes</p>\n\n<pre><code>public string Name { get; set;}\n</code></pre>\n\n<p>Also object initializers:</p>\n\n<pre><code>Employee emp = new Employee();\nemp.Name = \"John Smith\";\nemp.StartDate = DateTime.Now();\n</code></pre>\n\n<p>becomes</p>\n\n<pre><code>Employee emp = new Employee {Name=\"John Smith\", StartDate=DateTime.Now()}\n</code></pre>\n"
},
{
"answer_id": 9581,
"author": "Will Dean",
"author_id": 987,
"author_profile": "https://Stackoverflow.com/users/987",
"pm_score": 4,
"selected": false,
"text": "<p>On the basis that this thread should be entitled \"<em>things you didn't know about C# until recently despite thinking you already knew everything</em>\", my personal feature is asynchronous delegates.</p>\n\n<p>Until I read Jeff Richter's C#/CLR book (excellent book, everyone doing .NET should read it) I didn't know that you could call <em>any</em> delegate using <code>BeginInvoke</code> / <code>EndInvoke</code>. I tend to do a lot of <code>ThreadPool.QueueUserWorkItem</code> calls (which I guess is much like what the delegate <code>BeginInvoke</code> is doing internally), but the addition of a standardised join/rendezvous pattern may be really useful sometimes.</p>\n"
},
{
"answer_id": 9639,
"author": "Eric Minkes",
"author_id": 1172,
"author_profile": "https://Stackoverflow.com/users/1172",
"pm_score": 8,
"selected": false,
"text": "<p>The 'default' keyword in generic types:</p>\n\n<pre><code>T t = default(T);\n</code></pre>\n\n<p>results in a 'null' if T is a reference type, and 0 if it is an int, false if it is a boolean,\netcetera.</p>\n"
},
{
"answer_id": 10207,
"author": "t3rse",
"author_id": 64,
"author_profile": "https://Stackoverflow.com/users/64",
"pm_score": 4,
"selected": false,
"text": "<p><strong>Lambda Expressions</strong></p>\n\n<pre><code>Func<int, int, int> add = (a, b) => (a + b);\n</code></pre>\n\n<p><strong>Obscure String Formats</strong></p>\n\n<pre><code>Console.WriteLine(\"{0:D10}\", 2); // 0000000002\n\nDictionary<string, string> dict = new Dictionary<string, string> { \n {\"David\", \"C#\"}, \n {\"Johann\", \"Perl\"}, \n {\"Morgan\", \"Python\"}\n};\n\nConsole.WriteLine( \"{0,10} {1, 10}\", \"Programmer\", \"Language\" );\n\nConsole.WriteLine( \"-\".PadRight( 21, '-' ) );\n\nforeach (string key in dict.Keys)\n{\n Console.WriteLine( \"{0, 10} {1, 10}\", key, dict[key] ); \n}\n</code></pre>\n"
},
{
"answer_id": 10886,
"author": "Duncan Smart",
"author_id": 1278,
"author_profile": "https://Stackoverflow.com/users/1278",
"pm_score": 4,
"selected": false,
"text": "<p>I love the fact that I can use LINQ to objects on plain old .NET 2.0 (i.e. without requiring .NET 3.5 to be installed everywhere). All you need is an implementation of all the query operator Extension methods - see <a href=\"http://www.albahari.com/nutshell/linqbridge.html\" rel=\"nofollow noreferrer\">LINQBridge</a></p>\n"
},
{
"answer_id": 10892,
"author": "Serhat Ozgel",
"author_id": 31505,
"author_profile": "https://Stackoverflow.com/users/31505",
"pm_score": 3,
"selected": false,
"text": "<p>In addition to duncansmart's reply, also extension methods can be used on Framework 2.0. Just add an <code>ExtensionAttribute</code> class under System.Runtime.CompilerServices namespace and you can use extension methods (only with C# 3.0 of course).</p>\n\n<pre><code>namespace System.Runtime.CompilerServices\n{\n public class ExtensionAttribute : Attribute\n { \n }\n}\n</code></pre>\n"
},
{
"answer_id": 11738,
"author": "Luke Foust",
"author_id": 646,
"author_profile": "https://Stackoverflow.com/users/646",
"pm_score": 5,
"selected": false,
"text": "<p>Being able to have enum types have values other than int (the default)</p>\n\n<pre><code>public enum MyEnum : long\n{\n Val1 = 1,\n Val2 = 2\n}\n</code></pre>\n\n<p>Also, the fact that you can assign any numeric value to that enum:</p>\n\n<pre><code>MyEnum e = (MyEnum)123;\n</code></pre>\n"
},
{
"answer_id": 12137,
"author": "jfs",
"author_id": 718,
"author_profile": "https://Stackoverflow.com/users/718",
"pm_score": 9,
"selected": false,
"text": "<blockquote>\n <p>From <a href=\"https://rads.stackoverflow.com/amzn/click/com/0735621632\" rel=\"noreferrer\" rel=\"nofollow noreferrer\">CLR via C#</a>:</p>\n \n <p>When normalizing strings, it is highly\n recommended that you use\n ToUpperInvariant instead of\n ToLowerInvariant because <strong>Microsoft has\n optimized the code for performing\n uppercase comparisons</strong>.</p>\n</blockquote>\n\n<p>I remember one time my coworker always changed strings to uppercase before comparing. I've always wondered why he does that because I feel it's more \"natural\" to convert to lowercase first. After reading the book now I know why.</p>\n"
},
{
"answer_id": 12152,
"author": "Surgical Coder",
"author_id": 1276,
"author_profile": "https://Stackoverflow.com/users/1276",
"pm_score": 5,
"selected": false,
"text": "<p>My favourite is the</p>\n\n<pre><code>global::\n</code></pre>\n\n<p>keyword to escape namespace hell with some of our 3rd party code providers...</p>\n\n<p>Example:</p>\n\n<pre><code>global::System.Collections.Generic.List<global::System.String> myList =\n new global::System.Collections.Generic.List<global::System.String>();\n</code></pre>\n"
},
{
"answer_id": 12316,
"author": "AlexCuse",
"author_id": 794,
"author_profile": "https://Stackoverflow.com/users/794",
"pm_score": 4,
"selected": false,
"text": "<p>I didn't start to really appreciate the \"using\" blocks until recently. They make things so much more tidy :)</p>\n"
},
{
"answer_id": 13422,
"author": "Brad Wilson",
"author_id": 1554,
"author_profile": "https://Stackoverflow.com/users/1554",
"pm_score": 7,
"selected": false,
"text": "<p>This one is not \"hidden\" so much as it is misnamed.</p>\n\n<p>A lot of attention is paid to the algorithms \"map\", \"reduce\", and \"filter\". What most people don't realize is that .NET 3.5 added all three of these algorithms, but it gave them very SQL-ish names, based on the fact that they're part of LINQ.</p>\n\n<blockquote>\n <p>\"map\" => Select <br>Transforms data\n from one form into another</p>\n \n <p>\"reduce\" => Aggregate <br>Aggregates\n values into a single result</p>\n \n <p>\"filter\" => Where <br>Filters data\n based on a criteria</p>\n</blockquote>\n\n<p>The ability to use LINQ to do inline work on collections that used to take iteration and conditionals can be incredibly valuable. It's worth learning how all the LINQ extension methods can help make your code much more compact and maintainable.</p>\n"
},
{
"answer_id": 13441,
"author": "denis phillips",
"author_id": 748,
"author_profile": "https://Stackoverflow.com/users/748",
"pm_score": 7,
"selected": false,
"text": "<p>Returning anonymous types from a method and accessing members without reflection.</p>\n\n<pre><code>// Useful? probably not.\nprivate void foo()\n{\n var user = AnonCast(GetUserTuple(), new { Name = default(string), Badges = default(int) });\n Console.WriteLine(\"Name: {0} Badges: {1}\", user.Name, user.Badges);\n}\n\nobject GetUserTuple()\n{\n return new { Name = \"dp\", Badges = 5 };\n} \n\n// Using the magic of Type Inference...\nstatic T AnonCast<T>(object obj, T t)\n{\n return (T) obj;\n}\n</code></pre>\n"
},
{
"answer_id": 13932,
"author": "Mark Cidade",
"author_id": 1659,
"author_profile": "https://Stackoverflow.com/users/1659",
"pm_score": 5,
"selected": false,
"text": "<p>There's also the ThreadStaticAttribute to make a static field unique per thread, so you can have strongly typed thread-local storage.</p>\n\n<p>Even if extension methods aren't that secret (LINQ is based on them), it may not be so obvious as to how useful and more readable they can be for utility helper methods:</p>\n\n<pre><code>//for adding multiple elements to a collection that doesn't have AddRange\n//e.g., collection.Add(item1, item2, itemN);\nstatic void Add<T>(this ICollection<T> coll, params T[] items)\n { foreach (var item in items) coll.Add(item);\n }\n\n//like string.Format() but with custom string representation of arguments\n//e.g., \"{0} {1} {2}\".Format<Custom>(c=>c.Name,\"string\",new object(),new Custom())\n// result: \"string {System.Object} Custom1Name\"\nstatic string Format<T>(this string format, Func<T,object> select, params object[] args)\n { for(int i=0; i < args.Length; ++i)\n { var x = args[i] as T;\n if (x != null) args[i] = select(x);\n }\n return string.Format(format, args);\n }\n</code></pre>\n"
},
{
"answer_id": 14036,
"author": "Pat Hermens",
"author_id": 1677,
"author_profile": "https://Stackoverflow.com/users/1677",
"pm_score": 2,
"selected": false,
"text": "<blockquote>\n <p>I think if you have to use nullable\n types, it's better to use Nullable<.T>\n rather than the question mark\n notation. It makes it eye-achingly\n obvious that magic is occurring. Not\n sure why anyone would ever want to use\n Nullable<.bool> though.</p>\n</blockquote>\n\n<p>In a VB.NET Web service where the parameter might not be passed through <em>(because the partners request wasn't consistent or reliable)</em>, but had to pass validation against the proposed type <em>(Boolean for \"if is search request\")</em>. Chalk it up to \"another demand by management\"...</p>\n\n<p><em>...and yes, I know some people think it's not the right way to do these things, but <strong>IsSearchRequest As Nullable(Of Boolean)</strong> saved me losing my mind that night!</em></p>\n"
},
{
"answer_id": 14088,
"author": "Mark Cidade",
"author_id": 1659,
"author_profile": "https://Stackoverflow.com/users/1659",
"pm_score": 7,
"selected": false,
"text": "<p>Using @ for variable names that are keywords.</p>\n\n<pre><code>var @object = new object();\nvar @string = \"\";\nvar @if = IpsoFacto(); \n</code></pre>\n"
},
{
"answer_id": 14277,
"author": "Mark Cidade",
"author_id": 1659,
"author_profile": "https://Stackoverflow.com/users/1659",
"pm_score": 6,
"selected": false,
"text": "<p>Events are really delegates under the hood and any delegate object can have multiple functions attached to it and detatched from it using the += and -= operators, respectively.</p>\n\n<p>Events can also be controlled with the add/remove, similar to get/set except they're invoked when += and -= are used:</p>\n\n<pre><code>public event EventHandler SelectiveEvent(object sender, EventArgs args) \n { add \n { if (value.Target == null) throw new Exception(\"No static handlers!\");\n _SelectiveEvent += value;\n }\n remove\n { _SelectiveEvent -= value;\n }\n } EventHandler _SelectiveEvent;\n</code></pre>\n"
},
{
"answer_id": 14723,
"author": "juan",
"author_id": 1782,
"author_profile": "https://Stackoverflow.com/users/1782",
"pm_score": 5,
"selected": false,
"text": "<p>It's not actually a C# hidden feature, but I recently discovered the <a href=\"http://msdn.microsoft.com/en-us/library/system.weakreference.aspx\" rel=\"nofollow noreferrer\">WeakReference class</a> and was blown away by it (although this may be biased by the fact that it helped me found a solution to a <a href=\"http://www.juanformoso.com.ar/post/2008/07/30/Weak-References.aspx\" rel=\"nofollow noreferrer\">particular problem of mine</a>...)</p>\n"
},
{
"answer_id": 14926,
"author": "martinlund",
"author_id": 1808,
"author_profile": "https://Stackoverflow.com/users/1808",
"pm_score": 2,
"selected": false,
"text": "<p>I must admit that i'm not sure wether this performs better or worse than the normal ASP.NET repeater onItemDatabound cast code, but anyway here's my 5 cent.</p>\n\n<pre><code>MyObject obj = e.Item.DataItem as MyObject;\nif(obj != null)\n{\n //Do work\n}\n</code></pre>\n"
},
{
"answer_id": 15321,
"author": "Portman",
"author_id": 1690,
"author_profile": "https://Stackoverflow.com/users/1690",
"pm_score": 7,
"selected": false,
"text": "<p>If you're trying to use curly brackets inside a String.Format expression...</p>\n\n<pre><code>int foo = 3;\nstring bar = \"blind mice\";\nString.Format(\"{{I am in brackets!}} {0} {1}\", foo, bar);\n//Outputs \"{I am in brackets!} 3 blind mice\"\n</code></pre>\n"
},
{
"answer_id": 15352,
"author": "mgsloan",
"author_id": 1164871,
"author_profile": "https://Stackoverflow.com/users/1164871",
"pm_score": 5,
"selected": false,
"text": "<p>Near all the cool ones have been mentioned. Not sure if this one's well known or not</p>\n\n<p>C# property/field constructor initialization:</p>\n\n<pre><code>var foo = new Rectangle() \n{ \n Fill = new SolidColorBrush(c), \n Width = 20, \n Height = 20 \n};\n</code></pre>\n\n<p>This creates the rectangle, and sets the listed properties.</p>\n\n<p>I've noticed something funny - you can have a comma at the end of the properties list, without it being a syntax error. So this is also valid:</p>\n\n<pre><code>var foo = new Rectangle() \n{ \n Fill = new SolidColorBrush(c), \n Width = 20, \n Height = 20,\n};\n</code></pre>\n"
},
{
"answer_id": 15393,
"author": "Rismo",
"author_id": 1560,
"author_profile": "https://Stackoverflow.com/users/1560",
"pm_score": 5,
"selected": false,
"text": "<p>Not hidden, but I think that a lot of developers are not using the HasValue and Value properties on the nullable types.</p>\n\n<pre><code> int? x = null;\n int y;\n if (x.HasValue)\n y = x.Value;\n</code></pre>\n"
},
{
"answer_id": 15715,
"author": "xanadont",
"author_id": 1886,
"author_profile": "https://Stackoverflow.com/users/1886",
"pm_score": 5,
"selected": false,
"text": "<p>@lomaxx I also learned the other day (the same time I learned your tip) is that you can now have disparate access levels on the same property:</p>\n\n<pre><code>public string Name { get; private set;}\n</code></pre>\n\n<p>That way only the class itself can set the Name property.</p>\n\n<pre><code>public MyClass(string name) { Name = name; }\n</code></pre>\n"
},
{
"answer_id": 15765,
"author": "jfs",
"author_id": 718,
"author_profile": "https://Stackoverflow.com/users/718",
"pm_score": 9,
"selected": false,
"text": "<p>From <a href=\"http://www.west-wind.com/weblog/posts/236298.aspx\" rel=\"nofollow noreferrer\">Rick Strahl</a>:</p>\n\n<p>You can chain the ?? operator so that you can do a bunch of null comparisons.</p>\n\n<pre><code>string result = value1 ?? value2 ?? value3 ?? String.Empty;\n</code></pre>\n"
},
{
"answer_id": 16395,
"author": "Jon Erickson",
"author_id": 1950,
"author_profile": "https://Stackoverflow.com/users/1950",
"pm_score": 5,
"selected": false,
"text": "<h1>Partial Methods</h1>\n\n<p><a href=\"http://blogs.msdn.com/charlie/archive/2007/11/11/partial-methods.aspx\" rel=\"nofollow noreferrer\">Charlie Calvert explains partial methods on his blog</a></p>\n\n<p><a href=\"http://weblogs.asp.net/scottcate/archive/2008/06/18/teched-orlando-compiler-tricks.aspx\" rel=\"nofollow noreferrer\">Scott Cate has a nice partial method demo here</a></p>\n\n<ol>\n<li>Points of extensibility in Code Generated class (LINQ to SQL, EF)</li>\n<li>Does not get compiled into the dll if it is not implemented (check it out with .NET Reflector)</li>\n</ol>\n"
},
{
"answer_id": 16450,
"author": "JasonS",
"author_id": 1865,
"author_profile": "https://Stackoverflow.com/users/1865",
"pm_score": 7,
"selected": false,
"text": "<p>Maybe not an advanced technique, but one I see all the time that drives me crazy:</p>\n\n<pre><code>if (x == 1)\n{\n x = 2;\n}\nelse\n{\n x = 3;\n}\n</code></pre>\n\n<p>can be condensed to:</p>\n\n<pre><code>x = (x==1) ? 2 : 3;\n</code></pre>\n"
},
{
"answer_id": 16482,
"author": "John Asbeck",
"author_id": 1767,
"author_profile": "https://Stackoverflow.com/users/1767",
"pm_score": 3,
"selected": false,
"text": "<p>Preprocessor Directives can be nifty if you want different behavior between Debug and Release modes.</p>\n\n<p><a href=\"http://msdn.microsoft.com/en-us/library/ed8yd1ha.aspx\" rel=\"nofollow noreferrer\">http://msdn.microsoft.com/en-us/library/ed8yd1ha.aspx</a></p>\n"
},
{
"answer_id": 18158,
"author": "John Sheehan",
"author_id": 1786,
"author_profile": "https://Stackoverflow.com/users/1786",
"pm_score": 4,
"selected": false,
"text": "<p>I see a lot of people replicate the functionality of <code>Nullable<T>.GetValueOrDefault(T)</code>.</p>\n"
},
{
"answer_id": 18619,
"author": "Nelson Miranda",
"author_id": 1130097,
"author_profile": "https://Stackoverflow.com/users/1130097",
"pm_score": 3,
"selected": false,
"text": "<p>You type \"prop\" and then press [TAB] twice, it generates useful code for your properties and can speed your typing.</p>\n\n<p>I know this works in VS 2005 (I use it) but I don´t know in previous versions.</p>\n"
},
{
"answer_id": 21752,
"author": "Martin Clarke",
"author_id": 2422,
"author_profile": "https://Stackoverflow.com/users/2422",
"pm_score": 4,
"selected": false,
"text": "<p>How about the <a href=\"http://msdn.microsoft.com/en-us/library/system.flagsattribute.aspx\" rel=\"noreferrer\">FlagsAttribute</a> on an enumeration? It allows you to perform bitwise operations... took me forever to find out how to do bitwise operations in .NET nicely.</p>\n"
},
{
"answer_id": 24914,
"author": "SemiColon",
"author_id": 1994,
"author_profile": "https://Stackoverflow.com/users/1994",
"pm_score": 3,
"selected": false,
"text": "<p>I'm pretty sure everyone is familiar with operator overloading, but maybe some aren't.</p>\n\n<pre><code>class myClass\n{\n private string myClassValue = \"\";\n\n public myClass(string myString)\n {\n myClassValue = myString;\n }\n\n public override string ToString()\n {\n return myClassValue;\n }\n\n public static myClass operator <<(myClass mc, int shiftLen)\n {\n string newString = \"\";\n for (int i = shiftLen; i < mc.myClassValue.Length; i++)\n newString += mc.myClassValue[i].ToString();\n mc.myClassValue = newString.ToString();\n return mc;\n }\n\n public static myClass operator >>(myClass mc, int shiftLen)\n {\n char[] newString = new char[shiftLen + mc.myClassValue.Length];\n\n for (int i = shiftLen; i < mc.myClassValue.Length; i++)\n newString[i] += mc.myClassValue[i - shiftLen];\n\n mc.myClassValue = new string(newString);\n return mc;\n }\n\n public static myClass operator +(myClass mc, string args)\n {\n if (args.Trim().Length > 1)\n mc.myClassValue += args;\n return mc;\n }\n\n public static myClass operator -(myClass mc, string args)\n {\n if (args.Trim().Length > 1)\n {\n Regex rgx = new Regex(args);\n mc.myClassValue = rgx.Replace(mc.myClassValue, \"\");\n }\n return mc;\n }\n}\n</code></pre>\n\n<p>I think it's pretty cool to be able to shift a string left and right using << and >> or to remove a set of strings that follow a regular expression pattern using -=</p>\n\n<pre><code>myClass tmpClass = new myClass(\" HelloWorld123\");\ntmpClass -= @\"World\";\ntmpClass <<= 2;\nConsole.WriteLine(tmpClass);\n</code></pre>\n"
},
{
"answer_id": 25393,
"author": "Haacked",
"author_id": 598,
"author_profile": "https://Stackoverflow.com/users/598",
"pm_score": 2,
"selected": false,
"text": "<p>One interesting thing I've learned is that different parts of the framework and C# language were written at different times, hence inconsistencies. For example, the framework itself violates many FxCop rules because the rules weren't all in place when the framework was written.</p>\n\n<p>Also, the using statement was intended for delinieating \"scopes\" and not specifically for disposing resources. It was written after the lock statement. Eric Gunnerson <a href=\"http://haacked.com/archive/2004/05/27/DifficultiesOfLanguageDesign.aspx\" rel=\"nofollow noreferrer\">once mentioned</a> something along the lines of that if the using statement came first, they might have not needed to write the lock statement (though who knows, maybe they would have anyways), because the using statement might have been sufficient.</p>\n"
},
{
"answer_id": 26096,
"author": "John Boker",
"author_id": 2847,
"author_profile": "https://Stackoverflow.com/users/2847",
"pm_score": 3,
"selected": false,
"text": "<p>@lainMH,</p>\n\n<p>Nullable booleans are useful when retrieving values from a database that are nullable and when putting values back in. Sometimes you want to know the field has not been set.</p>\n"
},
{
"answer_id": 26192,
"author": "David Basarab",
"author_id": 2469,
"author_profile": "https://Stackoverflow.com/users/2469",
"pm_score": 3,
"selected": false,
"text": "<p>In reading the book on development of the .NET framework. A good piece of advice is not to use bool to turn stuff on or off, but rather use ENums.</p>\n\n<p>With ENums you give yourself some expandability without having to rewrite any code to add a new feature to a function.</p>\n"
},
{
"answer_id": 27941,
"author": "Frep D-Oronge",
"author_id": 3024,
"author_profile": "https://Stackoverflow.com/users/3024",
"pm_score": 5,
"selected": false,
"text": "<p>The C# ?? null coalescing operator - </p>\n\n<p>Not really hidden, but rarely used. Probably because a lot of developers run a mile when they see the conditional ? operator, so they run two when they see this one. Used:</p>\n\n<pre><code>string mystring = foo ?? \"foo was null\"\n</code></pre>\n\n<p>rather than</p>\n\n<pre><code>string mystring;\nif (foo==null)\n mystring = \"foo was null\";\nelse\n mystring = foo;\n</code></pre>\n"
},
{
"answer_id": 28811,
"author": "chakrit",
"author_id": 3055,
"author_profile": "https://Stackoverflow.com/users/3055",
"pm_score": 9,
"selected": false,
"text": "<p><strong>lambdas and type inference</strong> are underrated. <strong>Lambdas can have multiple statements</strong> and they <strong>double as a compatible delegate object</strong> automatically (just make sure the signature match) as in:</p>\n\n<pre><code>Console.CancelKeyPress +=\n (sender, e) => {\n Console.WriteLine(\"CTRL+C detected!\\n\");\n e.Cancel = true;\n };\n</code></pre>\n\n<p>Note that I don't have a <code>new CancellationEventHandler</code> nor do I have to specify types of <code>sender</code> and <code>e</code>, they're inferable from the event. Which is why this is less cumbersome to writing the whole <code>delegate (blah blah)</code> which also requires you to specify types of parameters.</p>\n\n<p><strong>Lambdas don't need to return anything</strong> and type inference is extremely powerful in context like this.</p>\n\n<p>And BTW, you can always return <strong>Lambdas that make Lambdas</strong> in the functional programming sense. For example, here's a lambda that makes a lambda that handles a Button.Click event:</p>\n\n<pre><code>Func<int, int, EventHandler> makeHandler =\n (dx, dy) => (sender, e) => {\n var btn = (Button) sender;\n btn.Top += dy;\n btn.Left += dx;\n };\n\nbtnUp.Click += makeHandler(0, -1);\nbtnDown.Click += makeHandler(0, 1);\nbtnLeft.Click += makeHandler(-1, 0);\nbtnRight.Click += makeHandler(1, 0);\n</code></pre>\n\n<p>Note the chaining: <code>(dx, dy) => (sender, e) =></code></p>\n\n<p>Now that's why I'm happy to have taken the functional programming class :-)</p>\n\n<p>Other than the pointers in C, I think it's the other fundamental thing you should learn :-)</p>\n"
},
{
"answer_id": 28830,
"author": "Drakiula",
"author_id": 2437,
"author_profile": "https://Stackoverflow.com/users/2437",
"pm_score": 3,
"selected": false,
"text": "<p>Reflection Emit and Expression trees come to mind...</p>\n\n<p>Don't miss Jeffrey Richter's CLR via C# and Jon Skeet's <img src=\"https://www.manning.com/skeet/skeet_cover150.jpg\" alt=\"alt text\"></p>\n\n<p>See here for some resources:</p>\n\n<p><a href=\"http://www.codeproject.com/KB/trace/releasemodebreakpoint.aspx\" rel=\"nofollow noreferrer\">http://www.codeproject.com/KB/trace/releasemodebreakpoint.aspx</a></p>\n\n<p><a href=\"http://www.codeproject.com/KB/dotnet/Creating_Dynamic_Types.aspx\" rel=\"nofollow noreferrer\">http://www.codeproject.com/KB/dotnet/Creating_Dynamic_Types.aspx</a></p>\n\n<p><a href=\"http://www.codeproject.com/KB/cs/lambdaexpressions.aspx\" rel=\"nofollow noreferrer\">http://www.codeproject.com/KB/cs/lambdaexpressions.aspx</a></p>\n"
},
{
"answer_id": 29081,
"author": "Robert Durgin",
"author_id": 3132,
"author_profile": "https://Stackoverflow.com/users/3132",
"pm_score": 5,
"selected": false,
"text": "<p>The <em>#if DEBUG</em> pre-processor directive. It is Useful for\ntesting and debugging (though I usually prefer to go the\nunit testing route).</p>\n\n<pre><code>string customerName = null;\n#if DEBUG\n customerName = \"Bob\"\n#endif\n</code></pre>\n\n<p>It will only execute code block if Visual Studio is set to\ncompile in 'Debug' mode. Otherwise the code block will be\nignored by the compiler (and grayed out in Visual Studio).</p>\n"
},
{
"answer_id": 31293,
"author": "Joel Coehoorn",
"author_id": 3043,
"author_profile": "https://Stackoverflow.com/users/3043",
"pm_score": 4,
"selected": false,
"text": "<p>I'm late to this party, so my first choices are already taken. But I didn't see anyone mention this gem yet:</p>\n\n<p><a href=\"http://msdn.microsoft.com/en-us/concurrency/default.aspx\" rel=\"nofollow noreferrer\">Parallel Extensions to the .NET Framework</a></p>\n\n<p>It has things like replace with Parallel.For or foreach with Parallel.ForEach</p>\n\n<hr>\n\n<p>Parallel Sample :<br>\nIn your opinion, how many CLR object can be created in one second?\n<img src=\"https://i.stack.imgur.com/nqJ2u.png\" alt=\"enter image description here\">\n<br>See fallowing example :</p>\n\n<pre><code>using System;\nusing System.Collections.Generic;\nusing System.Diagnostics;\nusing System.Threading;\nusing System.Threading.Tasks;\n\nnamespace ObjectInitSpeedTest\n{\n class Program\n {\n //Note: don't forget to build it in Release mode.\n static void Main()\n {\n normalSpeedTest(); \n parallelSpeedTest();\n\n Console.ForegroundColor = ConsoleColor.White;\n Console.WriteLine(\"Press a key ...\");\n Console.ReadKey();\n }\n\n private static void parallelSpeedTest()\n {\n Console.ForegroundColor = ConsoleColor.Yellow;\n Console.WriteLine(\"parallelSpeedTest\");\n\n long totalObjectsCreated = 0;\n long totalElapsedTime = 0;\n\n var tasks = new List<Task>();\n var processorCount = Environment.ProcessorCount;\n\n Console.WriteLine(\"Running on {0} cores\", processorCount);\n\n for (var t = 0; t < processorCount; t++)\n {\n tasks.Add(Task.Factory.StartNew(\n () =>\n {\n const int reps = 1000000000;\n var sp = Stopwatch.StartNew();\n for (var j = 0; j < reps; ++j)\n {\n new object();\n }\n sp.Stop();\n\n Interlocked.Add(ref totalObjectsCreated, reps);\n Interlocked.Add(ref totalElapsedTime, sp.ElapsedMilliseconds);\n }\n ));\n }\n\n // let's complete all the tasks\n Task.WaitAll(tasks.ToArray());\n\n Console.WriteLine(\"Created {0:N} objects in 1 sec\\n\", (totalObjectsCreated / (totalElapsedTime / processorCount)) * 1000);\n }\n\n private static void normalSpeedTest()\n {\n Console.ForegroundColor = ConsoleColor.Green;\n Console.WriteLine(\"normalSpeedTest\");\n\n const int reps = 1000000000;\n var sp = Stopwatch.StartNew();\n sp.Start();\n for (var j = 0; j < reps; ++j)\n {\n new object();\n }\n sp.Stop();\n\n Console.WriteLine(\"Created {0:N} objects in 1 sec\\n\", (reps / sp.ElapsedMilliseconds) * 1000);\n }\n }\n}\n</code></pre>\n"
},
{
"answer_id": 32148,
"author": "Jakub Šturc",
"author_id": 2361,
"author_profile": "https://Stackoverflow.com/users/2361",
"pm_score": 5,
"selected": false,
"text": "<p><a href=\"http://msdn.microsoft.com/en-us/library/6x6y6z4d.aspx\" rel=\"nofollow noreferrer\">true</a> and <a href=\"http://msdn.microsoft.com/en-us/library/6292hy1k.aspx\" rel=\"nofollow noreferrer\">false</a> operators are really weird.</p>\n\n<p>More comprehensive example can be found <a href=\"http://www.java2s.com/Tutorial/CSharp/0160__Operator-Overload/truefalseoperatorforComplex.htm\" rel=\"nofollow noreferrer\">here</a>.</p>\n\n<p><em>Edit: There is related SO question <a href=\"https://stackoverflow.com/questions/33265/whats-the-false-operator-in-c-good-for\">What’s the false operator in C# good for?</a></em></p>\n"
},
{
"answer_id": 32472,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 2,
"selected": false,
"text": "<p>Returning IQueryable projections</p>\n\n<pre><code>protected void LdsPostings_Selecting(object sender, LinqDataSourceSelectEventArgs e)\n{ \n var dc = new MyDataContext();\n var query = dc.Posting.AsQueryable();\n\n if (isCondition1)\n {\n query = query.Where(q => q.PostedBy == Username);\n e.Result = QueryProjection(query);\n return;\n }\n\n ...\n\n if (isConditionN)\n {\n query = query.Where(q => q.Status.StatusName == \"submitted\");\n query = query.Where(q => q.ReviewedBy == Username);\n e.Result = QueryProjection(query);\n return;\n }\n}\n</code></pre>\n\n<p>and rather than coding the projection multiple times, create a single method:</p>\n\n<pre><code>private IQueryable QueryProjection(IQueryable<Posting> query)\n{\n return query.Select(p => new\n {\n p.PostingID,\n p.Category.CategoryName,\n p.Type.TypeName,\n p.Status.StatusName,\n p.Description,\n p.Updated,\n p.PostedBy,\n p.ReviewedBy,\n });\n}\n</code></pre>\n"
},
{
"answer_id": 32706,
"author": "Nathan Lee",
"author_id": 3453,
"author_profile": "https://Stackoverflow.com/users/3453",
"pm_score": 4,
"selected": false,
"text": "<p>I love using the @ character for SQL queries. It keeps the sql nice and formatted and without having to surround each line with a string delimiter.</p>\n\n<pre><code>string sql = @\"SELECT firstname, lastname, email\n FROM users\n WHERE username = @username AND password = @password\";\n</code></pre>\n"
},
{
"answer_id": 33271,
"author": "chakrit",
"author_id": 3055,
"author_profile": "https://Stackoverflow.com/users/3055",
"pm_score": 3,
"selected": false,
"text": "<p>Thought about <strong>@dp AnonCast</strong> and decided to try it out a bit. Here's what I come up with that might be useful to some:</p>\n\n<pre><code>// using the concepts of dp's AnonCast\nstatic Func<T> TypeCurry<T>(Func<object> f, T type)\n{\n return () => (T)f();\n}\n</code></pre>\n\n<p>And here's how it might be used:</p>\n\n<pre><code>static void Main(string[] args)\n{\n\n var getRandomObjectX = TypeCurry(GetRandomObject,\n new { Name = default(string), Badges = default(int) });\n\n do {\n\n var obj = getRandomObjectX();\n\n Console.WriteLine(\"Name : {0} Badges : {1}\",\n obj.Name,\n obj.Badges);\n\n } while (Console.ReadKey().Key != ConsoleKey.Escape);\n\n}\n\nstatic Random r = new Random();\nstatic object GetRandomObject()\n{\n return new {\n Name = Guid.NewGuid().ToString().Substring(0, 4),\n Badges = r.Next(0, 100)\n };\n}\n</code></pre>\n"
},
{
"answer_id": 33384,
"author": "ljs",
"author_id": 3394,
"author_profile": "https://Stackoverflow.com/users/3394",
"pm_score": 6,
"selected": false,
"text": "<p>I like looking up stuff in a list like:-</p>\n\n<pre><code>bool basketContainsFruit(string fruit) {\n return new[] { \"apple\", \"orange\", \"banana\", \"pear\" }.Contains(fruit);\n}\n</code></pre>\n\n<p>Rather than:-</p>\n\n<pre><code>bool basketContainsFruit(string fruit) {\n return fruit == \"apple\" || fruit == \"orange\" || fruit == \"banana\" ||\n fruit == \"pear\";\n}\n</code></pre>\n\n<p>Doesn't come up that much in practice, but the idea of matching items against the subject of the search can be really quite useful + succinct.</p>\n"
},
{
"answer_id": 33474,
"author": "bdukes",
"author_id": 2688,
"author_profile": "https://Stackoverflow.com/users/2688",
"pm_score": 5,
"selected": false,
"text": "<p>A couple other attributes from the <a href=\"http://msdn.microsoft.com/en-us/library/system.diagnostics.aspx\" rel=\"nofollow noreferrer\">System.Diagnostics</a> namespace are quite helpful.</p>\n\n<p><a href=\"http://msdn.microsoft.com/en-us/library/system.diagnostics.debuggerbrowsableattribute.aspx\" rel=\"nofollow noreferrer\">DebuggerBrowsable</a> will let you hide variables from the debugger window (we use it for all private backing variables of exposed properties). Along with that, <a href=\"http://msdn.microsoft.com/en-us/library/system.diagnostics.debuggerstepthroughattribute.aspx\" rel=\"nofollow noreferrer\">DebuggerStepThrough</a> makes the debugger step over that code, very useful for dumb properties (probably should be converted to auto-properties if you can take a dependency to the C# 3.0 compiler). As an example</p>\n\n<pre><code>[DebuggerBrowsable(DebuggerBrowsableState.Never)]\nprivate string nickName;\npublic string NickName {\n [DebuggerStepThrough]\n get { return nickName; }\n [DebuggerStepThrough]\n set { this.nickName = value; }\n}\n</code></pre>\n"
},
{
"answer_id": 35342,
"author": "Andrew Burns",
"author_id": 3683,
"author_profile": "https://Stackoverflow.com/users/3683",
"pm_score": 4,
"selected": false,
"text": "<p><a href=\"http://msdn.microsoft.com/en-us/library/aa664622(VS.71).aspx\" rel=\"nofollow noreferrer\">ConditionalAttribute</a></p>\n\n<p>Allows you to tell the compiler to omit the call to the method marked with the attribute under certain conditions (#define).</p>\n\n<p>The fact that the method call is omitted also means that its parameters are not evaluated. This is very handy and it's what allows you to call expensive validation functions in Debug.Assert() and not worry about them slowing down your release build. </p>\n"
},
{
"answer_id": 37285,
"author": "nimish",
"author_id": 3926,
"author_profile": "https://Stackoverflow.com/users/3926",
"pm_score": 7,
"selected": false,
"text": "<pre><code>Environment.NewLine\n</code></pre>\n\n<p>for system independent newlines.</p>\n"
},
{
"answer_id": 37467,
"author": "jfs",
"author_id": 718,
"author_profile": "https://Stackoverflow.com/users/718",
"pm_score": 5,
"selected": false,
"text": "<p><strong>Nesting Using Statements</strong></p>\n\n<p>Usually we do it like this:</p>\n\n<pre><code>StringBuilder sb = new StringBuilder();\nusing (StringWriter sw = new StringWriter()) {\n using (IndentedTextWriter itw = new IndentedTextWriter(sw)) {\n ... \n }\n}\n</code></pre>\n\n<p>But we can do it this way:</p>\n\n<pre><code>StringBuilder sb = new StringBuilder();\nusing (StringWriter sw = new StringWriter())\nusing (IndentedTextWriter itw = new IndentedTextWriter(sw)) {\n ... \n}\n</code></pre>\n"
},
{
"answer_id": 37926,
"author": "Jakub Šturc",
"author_id": 2361,
"author_profile": "https://Stackoverflow.com/users/2361",
"pm_score": 4,
"selected": false,
"text": "<p>The <a href=\"http://msdn.microsoft.com/en-us/library/ms173212.aspx\" rel=\"nofollow noreferrer\">extern alias</a> keyword to reference two versions of assemblies that have the same fully-qualified type names.</p>\n"
},
{
"answer_id": 38703,
"author": "Eduardo Diaz",
"author_id": 3245,
"author_profile": "https://Stackoverflow.com/users/3245",
"pm_score": 2,
"selected": false,
"text": "<p>PreviousPage property:</p>\n\n<p>\"The System.Web.UI.Page representing the page that transferred control to the current page.\"</p>\n\n<p>It is very useful.</p>\n"
},
{
"answer_id": 41872,
"author": "Michael Prewecki",
"author_id": 4403,
"author_profile": "https://Stackoverflow.com/users/4403",
"pm_score": 2,
"selected": false,
"text": "<p>TryParse method for each primitive type is great when validating user input.</p>\n\n<pre><code>double doubleValue\nif (!Double.TryParse(myDataRow(\"myColumn\"), out doubleValue))\n{\n // set validation error\n}\n</code></pre>\n"
},
{
"answer_id": 44782,
"author": "andynil",
"author_id": 446,
"author_profile": "https://Stackoverflow.com/users/446",
"pm_score": 5,
"selected": false,
"text": "<p><strong>Foreach uses Duck Typing</strong></p>\n\n<p>Paraphrasing, or shamelessly stealing from <a href=\"http://blogs.msdn.com/kcwalina/archive/2007/07/18/DuckNotation.aspx\" rel=\"nofollow noreferrer\">Krzysztof Cwalinas blog</a> on this. More interesting trivia than anything.</p>\n\n<p>For your object to support foreach, you <em>don't</em> have to implement <em>IEnumerable</em>. I.e. this is not a constraint and it isn't checked by the compiler. What's checked is that</p>\n\n<ul>\n<li>Your object provide a public method <em>GetEnumerator</em> that\n\n<ul>\n<li>takes no parameters</li>\n<li>return a type that has two members\n\n<ol>\n<li>a parameterless <em>method MoveNext</em> that <em>returns a boolean</em></li>\n<li>a <em>property Current</em> with a getter that <em>returns an Object</em></li>\n</ol></li>\n</ul></li>\n</ul>\n\n<p>For example, </p>\n\n<pre><code>class Foo\n{\n public Bar GetEnumerator() { return new Bar(); }\n\n public struct Bar\n {\n public bool MoveNext()\n {\n return false;\n }\n\n public object Current\n {\n get { return null; }\n }\n }\n}\n\n// the following complies just fine:\nFoo f = new Foo();\nforeach (object o in f)\n{\n Console.WriteLine(\"Krzysztof Cwalina's da man!\");\n}\n</code></pre>\n"
},
{
"answer_id": 45398,
"author": "Pop Catalin",
"author_id": 4685,
"author_profile": "https://Stackoverflow.com/users/4685",
"pm_score": 5,
"selected": false,
"text": "<p>There are some really hidden keywords and features in C# related to the TypedReference undocumented class. The following keywords are undocumented:</p>\n\n<ul>\n<li><code>__makeref</code></li>\n<li><code>__reftype</code></li>\n<li><code>__refvalue</code></li>\n<li><code>__arglist</code></li>\n</ul>\n\n<p>Examples of use:</p>\n\n<pre><code>// Create a typed reference\nint i = 1;\nTypedReference tr1 = __makeref(i);\n// Get the type of a typed reference\nType t = __reftype(tr1);\n// Get the value of a typed referece\nint j = __refvalue(tr1, int); \n// Create a method that accepts and arbitrary number of typed references\nvoid SomeMethod(__arglist) { ...\n// Call the method\nint x = 1;\nstring y = \"Foo\";\nObject o = new Object();\nSomeMethod(__arglist(x,y,o));\n// And finally iterate over method parameters\nvoid SomeMethod(__arglist) {\n ArgIterator ai = new ArgIterator(__arglist);\nwhile(ai.GetRemainingCount() >0)\n{\n TypedReference tr = ai.GetNextArg();\n Console.WriteLine(TypedReference.ToObject(tr));\n}}\n</code></pre>\n"
},
{
"answer_id": 45454,
"author": "Mark Ingram",
"author_id": 986,
"author_profile": "https://Stackoverflow.com/users/986",
"pm_score": 2,
"selected": false,
"text": "<p>@<a href=\"https://stackoverflow.com/questions/9033?#9092\">Robbie Rocketpants</a></p>\n\n<blockquote>\n <p>\"but my instincts tell me that this\n would cut a maximum of two type casts\n operations down to a maximum of one.\"</p>\n</blockquote>\n\n<p>If you do the cast as you were suggesting in example 1 (using is & as), it results in 2 calls to the \"is\" operator. Because when you do \"c = obj as MyClass\", first it calls \"is\" behind the scenes, then if it fails that it simply returns null.</p>\n\n<p>If you do the cast as you were suggesting in example 2,</p>\n\n<pre><code>c = (MyClass)obj\n</code></pre>\n\n<p>Then this actually performs the \"is\" operation again, then if it fails that check,it throws an exception (InvalidCastException).</p>\n\n<p>So, if you wanted to do a lightweight dynamic cast, it's best to do the 3rd example you provided:</p>\n\n<pre><code>MyClass c;\nif (obj is MyClass)\n{\n c = obj as MyClass\n}\n\nif (c != null)\n{\n}\n</code></pre>\n\n<p><strong>vs</strong></p>\n\n<pre><code>MyClass c = obj as MyClass;\n\nif (c != null)\n{\n}\n</code></pre>\n\n<p>You can see which is quicker, more consise and clearer.</p>\n"
},
{
"answer_id": 45873,
"author": "Konamiman",
"author_id": 4574,
"author_profile": "https://Stackoverflow.com/users/4574",
"pm_score": 6,
"selected": false,
"text": "<p>@David in Dakota:</p>\n\n<pre><code>Console.WriteLine( \"-\".PadRight( 21, '-' ) );\n</code></pre>\n\n<p>I used to do this, until I discovered that the String class has a constructor that allows you to do the same thing in a cleaner way:</p>\n\n<pre><code>new String('-',22);\n</code></pre>\n"
},
{
"answer_id": 46157,
"author": "DAC",
"author_id": 1111,
"author_profile": "https://Stackoverflow.com/users/1111",
"pm_score": 6,
"selected": false,
"text": "<p><strong><a href=\"http://msdn.microsoft.com/en-us/library/system.runtime.compilerservices.internalsvisibletoattribute.aspx\" rel=\"nofollow noreferrer\">InternalsVisibleTo</a></strong> attribute is one that is not that well known, but can come in increadibly handy in certain circumstances. It basically allows another assembly to be able to access \"internal\" elements of the defining assembly.</p>\n"
},
{
"answer_id": 46290,
"author": "Judah Gabriel Himango",
"author_id": 536,
"author_profile": "https://Stackoverflow.com/users/536",
"pm_score": 5,
"selected": false,
"text": "<p>I just found out about this one today -- and I've been working with C# for 5 years!</p>\n\n<p>It's the <a href=\"http://msdn.microsoft.com/en-us/library/ms173212(VS.80).aspx\" rel=\"nofollow noreferrer\">namespace alias qualifier</a>:</p>\n\n<pre><code>extern alias YourAliasHere;\n</code></pre>\n\n<p>You can use it to load multiple versions of the same type. This can be useful in maintenance or upgrade scenarios where you have an updated version of your type that won't work in some old code, but you need to upgrade it to the new version. <a href=\"http://blogs.msdn.com/abhinaba/archive/2005/11/30/498278.aspx\" rel=\"nofollow noreferrer\">Slap on a namespace alias qualifier</a>, and the compiler will let you have both types in your code.</p>\n"
},
{
"answer_id": 49607,
"author": "nialljsmith",
"author_id": 5197,
"author_profile": "https://Stackoverflow.com/users/5197",
"pm_score": 5,
"selected": false,
"text": "<p>I like the keyword <em>continue</em>.</p>\n\n<p>If you hit a condition in a loop and don't want to do anything but advance the loop just stick in \"continue;\".</p>\n\n<p>E.g.:</p>\n\n<pre><code>foreach(object o in ACollection)\n{\n if(NotInterested)\n continue;\n}\n</code></pre>\n"
},
{
"answer_id": 50891,
"author": "johnc",
"author_id": 5302,
"author_profile": "https://Stackoverflow.com/users/5302",
"pm_score": 3,
"selected": false,
"text": "<p>Not a C# specific thing, but I am a ternary operations junkie.</p>\n\n<p>Instead of </p>\n\n<pre><code>if (boolean Condition)\n{\n //Do Function\n}\nelse\n{\n //Do something else\n}\n</code></pre>\n\n<p>you can use a succinct</p>\n\n<pre><code>booleanCondtion ? true operation : false operation;\n</code></pre>\n\n<p>e.g.</p>\n\n<p>Instead of</p>\n\n<pre><code>int value = param;\nif (doubleValue)\n{\n value *= 2;\n}\nelse\n{\n value *= 3;\n}\n</code></pre>\n\n<p>you can type</p>\n\n<pre><code>int value = param * (tripleValue ? 3 : 2);\n</code></pre>\n\n<p>It does help write succinct code, but nesting the damn things can be nasty, and they can be used for evil, but I love the little suckers nonetheless</p>\n"
},
{
"answer_id": 51171,
"author": "Thomas H",
"author_id": 4328,
"author_profile": "https://Stackoverflow.com/users/4328",
"pm_score": 2,
"selected": false,
"text": "<p>Saw a mention of List.ForEach above; 2.0 introduced a bevy of predicate-based collection operations - Find, FindAll, Exists, etc. Coupled with anonymous delegates you can almost achieve the simplicity of 3.5's lambda expressions.</p>\n"
},
{
"answer_id": 51966,
"author": "Bryan",
"author_id": 5423,
"author_profile": "https://Stackoverflow.com/users/5423",
"pm_score": 6,
"selected": false,
"text": "<p>A couple of things I like:</p>\n\n<p>-If you create an interface similar to</p>\n\n<pre><code> public interface SomeObject<T> where T : SomeObject<T>, new()\n</code></pre>\n\n<p>you force anything that inherits from this interface to \ncontain a parameterless constructor. It is very useful for a \ncouple of things I've run across.</p>\n\n<p>-Using anonymous types to create a useful object on the fly:</p>\n\n<pre><code>var myAwesomeObject = new {Name=\"Foo\", Size=10};\n</code></pre>\n\n<p>-Finally, many Java developers are familiar with syntax like:</p>\n\n<pre><code>public synchronized void MySynchronizedMethod(){}\n</code></pre>\n\n<p>However, in C# this is not valid syntax. The workaround is a method attribute:</p>\n\n<pre><code> [MethodImpl(MethodImplOptions.Synchronized)]\n public void MySynchronizedMethod(){}\n</code></pre>\n"
},
{
"answer_id": 52998,
"author": "Jason Olson",
"author_id": 5418,
"author_profile": "https://Stackoverflow.com/users/5418",
"pm_score": 8,
"selected": false,
"text": "<p>I think one of the most under-appreciated and lesser-known features of C# (.NET 3.5) are <a href=\"http://msdn.microsoft.com/en-us/library/bb397951.aspx\" rel=\"nofollow noreferrer\">Expression Trees</a>, <strong>especially</strong> when combined with Generics and Lambdas. This is an approach to API creation that newer libraries like NInject and Moq are using.</p>\n\n<p>For example, let's say that I want to register a method with an API and that API needs to get the method name</p>\n\n<p>Given this class:</p>\n\n<pre><code>public class MyClass\n{\n public void SomeMethod() { /* Do Something */ }\n}\n</code></pre>\n\n<p>Before, it was very common to see developers do this with strings and types (or something else largely string-based):</p>\n\n<pre><code>RegisterMethod(typeof(MyClass), \"SomeMethod\");\n</code></pre>\n\n<p>Well, that sucks because of the lack of strong-typing. What if I rename \"SomeMethod\"? Now, in 3.5 however, I can do this in a strongly-typed fashion:</p>\n\n<pre><code>RegisterMethod<MyClass>(cl => cl.SomeMethod());\n</code></pre>\n\n<p>In which the RegisterMethod class uses <code>Expression<Action<T>></code> like this:</p>\n\n<pre><code>void RegisterMethod<T>(Expression<Action<T>> action) where T : class\n{\n var expression = (action.Body as MethodCallExpression);\n\n if (expression != null)\n {\n // TODO: Register method\n Console.WriteLine(expression.Method.Name);\n }\n}\n</code></pre>\n\n<p>This is one big reason that I'm in love with Lambdas and Expression Trees right now.</p>\n"
},
{
"answer_id": 58945,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 9,
"selected": false,
"text": "<p>My favorite trick is using the <a href=\"http://en.wikipedia.org/wiki/%3F%3F_Operator\" rel=\"nofollow noreferrer\">null coalesce operator</a> and parentheses to automagically instantiate collections for me.</p>\n\n<pre><code>private IList<Foo> _foo;\n\npublic IList<Foo> ListOfFoo \n { get { return _foo ?? (_foo = new List<Foo>()); } }\n</code></pre>\n"
},
{
"answer_id": 59691,
"author": "Jakub Šturc",
"author_id": 2361,
"author_profile": "https://Stackoverflow.com/users/2361",
"pm_score": 6,
"selected": false,
"text": "<p>The <a href=\"http://msdn.microsoft.com/en-us/library/x13ttww7.aspx\" rel=\"nofollow noreferrer\">volatile</a> keyword to tell the compiler that a field can be modified by multiple threads concurrently.</p>\n"
},
{
"answer_id": 63661,
"author": "Grokys",
"author_id": 6448,
"author_profile": "https://Stackoverflow.com/users/6448",
"pm_score": 6,
"selected": false,
"text": "<p>I couldn't see this looking above - one that I didn't realise you could do until recently is to call one constructor from another:</p>\n\n<pre><code>class Example\n{\n public Example(int value1)\n : this(value1, \"Default Value\")\n {\n }\n\n public Example(int value1, string value2)\n {\n m_Value1 = value1;\n m_value2 = value2;\n }\n\n int m_Value1;\n string m_value2;\n}\n</code></pre>\n"
},
{
"answer_id": 72518,
"author": "Benjol",
"author_id": 11410,
"author_profile": "https://Stackoverflow.com/users/11410",
"pm_score": 4,
"selected": false,
"text": "<ol>\n<li><p>I can't comment yet, but note that by default Visual Studio 2008 automatically steps over properties, so the DebuggerStepThrough attribute is no longer needed in that case.</p>\n</li>\n<li><p>Also, I haven't noticed anyone showing how to declare a parameter-less lambda (useful for implementing Action<>)</p>\n<p><code>() => DoSomething(x);</code></p>\n</li>\n</ol>\n<p>You should also read up on closures - I'm not clever enough to explain them properly. But basically it means that the compiler does clever stuff so that the x in that line of code will still work even if it goes 'out of scope' after creating the lambda.</p>\n<ol start=\"3\">\n<li><p>I also discovered recently that you can pretend to ignore a lambda parameter:</p>\n<p><code>(e, _) => DoSomething(e)</code></p>\n</li>\n</ol>\n<p>It's not really ignoring it, it's just that _ is a valid identifier. So you couldn't ignore both of the parameters like that, but I think it is a kind of neat way to indicate that we don't care about that parameter (typically the EventArgs which is <code>.Empty</code>).</p>\n"
},
{
"answer_id": 73097,
"author": "Thomas Danecker",
"author_id": 9632,
"author_profile": "https://Stackoverflow.com/users/9632",
"pm_score": 3,
"selected": false,
"text": "<p><a href=\"http://msdn.microsoft.com/en-us/library/system.runtime.remoting.proxies.realproxy.aspx\" rel=\"nofollow noreferrer\">System.Runtime.Remoting.Proxies.RealProxy</a></p>\n\n<p>It enables Aspect Oriented Programming in C#, and you can also do a lot of other fancy stuff with it.</p>\n"
},
{
"answer_id": 74482,
"author": "BlackTigerX",
"author_id": 8411,
"author_profile": "https://Stackoverflow.com/users/8411",
"pm_score": 9,
"selected": false,
"text": "<p>Aliased generics:</p>\n\n<pre><code>using ASimpleName = Dictionary<string, Dictionary<string, List<string>>>;\n</code></pre>\n\n<p>It allows you to use <code>ASimpleName</code>, instead of <code>Dictionary<string, Dictionary<string, List<string>>></code>.</p>\n\n<p>Use it when you would use the same generic big long complex thing in a lot of places.</p>\n"
},
{
"answer_id": 87276,
"author": "Sixto Saez",
"author_id": 9711,
"author_profile": "https://Stackoverflow.com/users/9711",
"pm_score": 3,
"selected": false,
"text": "<p><strong>new modifier</strong></p>\n\n<p>Usage of the \"new\" modifier in C# is not exactly hidden but it's not often seen. The new modifier comes in handy when you need to \"hide\" base class members and not always override them. This means when you cast the derived class as the base class then the \"hidden\" method becomes visible and is called instead of the same method in the derived class.</p>\n\n<p>It is easier to see in code:</p>\n\n<pre><code>public class BaseFoo\n{\n virtual public void DoSomething()\n {\n Console.WriteLine(\"Foo\");\n }\n}\n\npublic class DerivedFoo : BaseFoo\n{\n public new void DoSomething()\n {\n Console.WriteLine(\"Bar\");\n }\n}\n\npublic class DerivedBar : BaseFoo\n{\n public override void DoSomething()\n {\n Console.WriteLine(\"FooBar\");\n }\n}\n\nclass Program\n{\n static void Main(string[] args)\n {\n BaseFoo derivedBarAsBaseFoo = new DerivedBar();\n BaseFoo derivedFooAsBaseFoo = new DerivedFoo();\n\n DerivedFoo derivedFoo = new DerivedFoo();\n\n derivedFooAsBaseFoo.DoSomething(); //Prints \"Foo\" when you might expect \"Bar\"\n derivedBarAsBaseFoo.DoSomething(); //Prints \"FooBar\"\n\n derivedFoo.DoSomething(); //Prints \"Bar\"\n }\n}\n</code></pre>\n\n<p>[Ed: Do I get extra points for puns? Sorry, couldn't be helped.]</p>\n"
},
{
"answer_id": 89505,
"author": "John Spurlock",
"author_id": 3054,
"author_profile": "https://Stackoverflow.com/users/3054",
"pm_score": 6,
"selected": false,
"text": "<p>Don't forget about <strong><a href=\"http://msdn.microsoft.com/en-us/library/13940fs2(VS.71).aspx\" rel=\"nofollow noreferrer\">goto</a></strong>.</p>\n"
},
{
"answer_id": 90432,
"author": "Alex Lyman",
"author_id": 5897,
"author_profile": "https://Stackoverflow.com/users/5897",
"pm_score": 4,
"selected": false,
"text": "<p>Falling through <code>switch</code>-<code>case</code>s can be achieved by having no code in a <code>case</code> (see <code>case 0</code>), or using the special <code>goto case</code> (see <code>case 1</code>) or <code>goto default</code> (see <code>case 2</code>) forms:</p>\n\n<pre><code>switch (/*...*/) {\n case 0: // shares the exact same code as case 1\n case 1:\n // do something\n goto case 2;\n case 2:\n // do something else\n goto default;\n default:\n // do something entirely different\n break;\n}\n</code></pre>\n"
},
{
"answer_id": 99844,
"author": "Statement",
"author_id": 2166173,
"author_profile": "https://Stackoverflow.com/users/2166173",
"pm_score": 2,
"selected": false,
"text": "<p>The #region <em>{string}</em> and #endregion pair is very neat for grouping code (outlining).</p>\n\n<pre><code>#region Using statements\nusing System;\nusing System.IO;\nusing ....;\nusing ....;\n#endregion\n</code></pre>\n\n<p>The code block can be compressed to a single describing line of text. Works inside functions aswell. </p>\n"
},
{
"answer_id": 100321,
"author": "core",
"author_id": 11574,
"author_profile": "https://Stackoverflow.com/users/11574",
"pm_score": 5,
"selected": false,
"text": "<p>Static constructors.</p>\n\n<p>Instances:</p>\n\n<pre><code>public class Example\n{\n static Example()\n {\n // Code to execute during type initialization\n }\n\n public Example()\n {\n // Code to execute during object initialization\n }\n}\n</code></pre>\n\n<p>Static classes:</p>\n\n<pre><code>public static class Example\n{\n static Example()\n {\n // Code to execute during type initialization\n }\n}\n</code></pre>\n\n<p>MSDN <a href=\"http://msdn.microsoft.com/en-us/library/k9x6w0hc.aspx\" rel=\"nofollow noreferrer\">says</a>:</p>\n\n<blockquote>\n <p>A static constructor is used to initialize any static data, or to perform a particular action that needs performed once only. It is called automatically before the first instance is created or any static members are referenced.</p>\n</blockquote>\n\n<p>For example:</p>\n\n<pre><code>public class MyWebService\n{\n public static DateTime StartTime;\n\n static MyWebService()\n {\n MyWebService.StartTime = DateTime.Now;\n }\n\n public TimeSpan Uptime\n {\n get { return DateTime.Now - MyWebService.StartTime; }\n }\n}\n</code></pre>\n\n<p>But, you could also just as easily have done:</p>\n\n<pre><code>public class MyWebService\n{\n public static DateTime StartTime = DateTime.Now;\n\n public TimeSpan Uptime\n {\n get { return DateTime.Now - MyWebService.StartTime; }\n }\n}\n</code></pre>\n\n<p>So you'll be hard-pressed to find any instance when you actually need to use a static constructor.</p>\n\n<p>MSDN offers useful notes on static constructors:</p>\n\n<blockquote>\n <ul>\n <li><p>A static constructor does not take access modifiers or have parameters.</p></li>\n <li><p>A static constructor is called automatically to initialize the class \n before the first instance is created<br>\n or any static members are referenced.</p></li>\n <li><p>A static constructor cannot be called directly.</p></li>\n <li><p>The user has no control on when the static constructor is executed in the \n program.</p></li>\n <li><p>A typical use of static constructors is when the class is\n using a log file and the\n constructor is used to write<br>\n entries to this file.</p></li>\n <li><p>Static constructors are also useful when creating wrapper classes for<br>\n unmanaged code, when the constructor<br>\n can call the LoadLibrary method.</p></li>\n <li><p>If a static constructor throws an exception, the runtime will not<br>\n invoke it a second time, and the type \n will remain uninitialized for the<br>\n lifetime of the application domain in \n which your program is running.</p></li>\n </ul>\n</blockquote>\n\n<p>The most important note is that if an error occurs in the static constructor, a <code>TypeIntializationException</code> is thrown and you cannot drill down to the offending line of code. Instead, you have to examine the <code>TypeInitializationException</code>'s <code>InnerException</code> member, which is the specific cause.</p>\n"
},
{
"answer_id": 102358,
"author": "Rob",
"author_id": 18505,
"author_profile": "https://Stackoverflow.com/users/18505",
"pm_score": 2,
"selected": false,
"text": "<p>Some concurrency utilities in the BCL might qualify as hidden features.</p>\n\n<p>Things like System.Threading.Monitor are used internally by the lock keyword; clearly in C# the lock keyword is preferrable, but sometimes it pays to know how things are done at a lower level; I had to lock in C++/CLI, so I encased a block of code with calls to Monitor.Enter() and Monitor.Exit().</p>\n"
},
{
"answer_id": 103235,
"author": "ilitirit",
"author_id": 9825,
"author_profile": "https://Stackoverflow.com/users/9825",
"pm_score": 3,
"selected": false,
"text": "<p>Literals can be used as variables of that type.\neg.</p>\n\n<pre><code>Console.WriteLine(5.ToString());\nConsole.WriteLine(5M.GetType()); // Returns \"System.Decimal\"\nConsole.WriteLine(\"This is a string!!!\".Replace(\"!!\", \"!\"));\n</code></pre>\n\n<p>Just a bit of trivia...</p>\n\n<p>There's quite a few things people haven't mentioned, but they have mostly to do with unsafe constructs. Here's one that can be used by \"regular\" code though:</p>\n\n<p>The checked/unchecked keywords:</p>\n\n<pre><code>public static int UncheckedAddition(int a, int b)\n{\n unchecked { return a + b; }\n}\n\npublic static int CheckedAddition(int a, int b)\n{\n checked { return a + b; } // or \"return checked(a + b)\";\n}\n\npublic static void Main() \n{\n Console.WriteLine(\"Unchecked: \" + UncheckedAddition(Int32.MaxValue, + 1)); // \"Wraps around\"\n Console.WriteLine(\"Checked: \" + CheckedAddition(Int32.MaxValue, + 1)); // Throws an Overflow exception\n Console.ReadLine();\n}\n</code></pre>\n"
},
{
"answer_id": 103449,
"author": "William Yeung",
"author_id": 16371,
"author_profile": "https://Stackoverflow.com/users/16371",
"pm_score": 2,
"selected": false,
"text": "<p>Before lambda comes into play, it's anonymous delegate. That could be used for blanket code similar to Ruby's blockgiven. I haven't tested how lambda works though because I want to stick with .NET 2.0 so far.</p>\n\n<p>For example when you want to make sure you remember to close your HTML tags:</p>\n\n<pre><code>MyHtmlWriter writer=new MyHtmlWriter();\nwriter.writeTag(\"html\", \n delegate ()\n { \n writer.writeTag(\"head\", \n delegate() \n { \n writer.writeTag(\"title\"...);\n }\n )\n })\n</code></pre>\n\n<p>I am sure if lambda is an option, that could yield much cleaner code :)</p>\n"
},
{
"answer_id": 104738,
"author": "ripper234",
"author_id": 11236,
"author_profile": "https://Stackoverflow.com/users/11236",
"pm_score": 1,
"selected": false,
"text": "<p>If 3rd-party extensions are allowed, then <a href=\"http://www.google.co.il/url?sa=t&source=web&ct=res&cd=1&url=http%3A%2F%2Fwww.itu.dk%2Fresearch%2Fc5%2F&ei=H_vTSPmZGZyw0gTK4t2VDQ&usg=AFQjCNEd1FXV-4rROqtPwZ_jDwmW1w5pFA&sig2=ILE99mEc76cQ6g-iRnPgbQ\" rel=\"nofollow noreferrer\">C5</a> and <a href=\"http://www.google.co.il/url?sa=t&source=web&ct=res&cd=2&url=http%3A%2F%2Fmsdn.microsoft.com%2Fen-us%2Flibrary%2Fbb648752.aspx&ei=N_vTSPzrComE0QSvwemcDQ&usg=AFQjCNFxZGL9m_QDWlvlkRNOpiLSG_q8bA&sig2=NGJmUpq-jE6kawcvaWWGYQ\" rel=\"nofollow noreferrer\">Microsoft CCR</a> (see <a href=\"http://www.lnbogen.com/MicrosoftCCRCleanWayToWriteParallelCodeInNet.aspx\" rel=\"nofollow noreferrer\">this blog post</a> for a quick introduction) are a must-know.</p>\n\n<p>C5 complements .Net's somewhat lacking collections library (not Set???), and CCR makes concurrent programming easier (I hear it's due to be merged with Parallel Extensions).</p>\n"
},
{
"answer_id": 105042,
"author": "Wyzfen",
"author_id": 15261,
"author_profile": "https://Stackoverflow.com/users/15261",
"pm_score": 6,
"selected": false,
"text": "<p>Dictionary.TryGetValue(K key, out V value)</p>\n\n<p>Works as a check and a get in one. Rather than;</p>\n\n<pre><code>if(dictionary.ContainsKey(key)) \n{\n value = dictionary[key];\n ...\n}\n</code></pre>\n\n<p>you can just do;</p>\n\n<pre><code>if(dictionary.TryGetValue(key, out value)) \n{ ... }\n</code></pre>\n\n<p>and the value has been set.</p>\n"
},
{
"answer_id": 106750,
"author": "Ray Lu",
"author_id": 11413,
"author_profile": "https://Stackoverflow.com/users/11413",
"pm_score": 2,
"selected": false,
"text": "<p>I think a lot of people know about pointers in C but are not sure if it works in C#. You can use pointers in C# in an unsafe context:</p>\n\n<pre><code>static void Main()\n{\n int i;\n unsafe\n { \n // pointer pi has the address of variable i\n int* pi = &i; \n // pointer ppi has the address of variable pi\n int** ppi = &pi;\n // ppi(addess of pi) -> pi(addess of i) -> i(0)\n i = 0;\n // dereference the pi, i.e. *pi is i\n Console.WriteLine(\"i = {0}\", *pi); // output: i = 0\n // since *pi is i, equivalent to i++\n (*pi)++;\n Console.WriteLine(\"i = {0}\", *pi); // output: i = 1\n // since *ppi is pi, one more dereference *pi is i \n // equivalent to i += 2\n **ppi += 2;\n Console.WriteLine(\"i = {0}\", *pi);// output: i = 3\n }\n Console.ReadLine();\n}\n</code></pre>\n"
},
{
"answer_id": 119648,
"author": "leppie",
"author_id": 15541,
"author_profile": "https://Stackoverflow.com/users/15541",
"pm_score": 1,
"selected": false,
"text": "<p>Some ?? weirdness :)</p>\n\n<pre><code>Delegate target =\n (target0 = target as CallTargetWithContext0) ??\n (target1 = target as CallTargetWithContext1) ??\n (target2 = target as CallTargetWithContext2) ??\n (target3 = target as CallTargetWithContext3) ??\n (target4 = target as CallTargetWithContext4) ??\n (target5 = target as CallTargetWithContext5) ??\n ((Delegate)(targetN = target as CallTargetWithContextN));\n</code></pre>\n\n<p>Interesting to note the last cast that is needed for some reason. Bug or by design?</p>\n"
},
{
"answer_id": 121405,
"author": "axel_c",
"author_id": 20272,
"author_profile": "https://Stackoverflow.com/users/20272",
"pm_score": 3,
"selected": false,
"text": "<pre><code>System.Diagnostics.Debug.Assert (false);\n</code></pre>\n\n<p>will trigger a popup and allow you to attach a debugger to a running .NET process during execution. Very useful for those times when for some reason you can't directly debug an ASP.NET application.</p>\n"
},
{
"answer_id": 121470,
"author": "Flory",
"author_id": 5551,
"author_profile": "https://Stackoverflow.com/users/5551",
"pm_score": 4,
"selected": false,
"text": "<p>There are operators for performing <a href=\"http://msdn.microsoft.com/en-us/library/z5z9kes2.aspx\" rel=\"nofollow noreferrer\"><code>implicit</code></a> and <a href=\"http://msdn.microsoft.com/en-us/library/xhbhezf4.aspx\" rel=\"nofollow noreferrer\"><code>explicit</code></a> user-defined type conversion between the declared class and one or more arbitrary classes. The <code>implicit</code> operator effectively allows the simulation of overloading the assignement operator, which is possible in languages such as C++ but not C#.</p>\n\n<p>It doesn't seem to be a feature one comes across very often, but it is in fact used in the <a href=\"http://en.wikipedia.org/wiki/Language_Integrated_Query#LINQ_to_XML\" rel=\"nofollow noreferrer\">LINQ to XML</a> (<code>System.Xml.Linq</code>) library, where you can implicitly convert strings to <code>XName</code> objects. Example:</p>\n\n<pre><code>XName tagName = \"x:Name\";\n</code></pre>\n\n<p>I discovered this feature in this <a href=\"http://www.codeproject.com/KB/architecture/smip.aspx\" rel=\"nofollow noreferrer\">article</a> about how to simulate multiple inheritance in C#.</p>\n"
},
{
"answer_id": 123701,
"author": "ZeroBugBounce",
"author_id": 11314,
"author_profile": "https://Stackoverflow.com/users/11314",
"pm_score": 8,
"selected": false,
"text": "<p><strong>Unions (the C++ shared memory kind) in pure, safe C#</strong></p>\n\n<p>Without resorting to unsafe mode and pointers, you can have class members share memory space in a class/struct. Given the following class:</p>\n\n<pre><code>[StructLayout(LayoutKind.Explicit)]\npublic class A\n{\n [FieldOffset(0)]\n public byte One;\n\n [FieldOffset(1)]\n public byte Two;\n\n [FieldOffset(2)]\n public byte Three;\n\n [FieldOffset(3)]\n public byte Four;\n\n [FieldOffset(0)]\n public int Int32;\n}\n</code></pre>\n\n<p>You can modify the values of the byte fields by manipulating the Int32 field and vice-versa. For example, this program:</p>\n\n<pre><code> static void Main(string[] args)\n {\n A a = new A { Int32 = int.MaxValue };\n\n Console.WriteLine(a.Int32);\n Console.WriteLine(\"{0:X} {1:X} {2:X} {3:X}\", a.One, a.Two, a.Three, a.Four);\n\n a.Four = 0;\n a.Three = 0;\n Console.WriteLine(a.Int32);\n }\n</code></pre>\n\n<p>Outputs this:</p>\n\n<pre><code>2147483647\nFF FF FF 7F\n65535\n</code></pre>\n\n<p>just add\nusing System.Runtime.InteropServices;</p>\n"
},
{
"answer_id": 140221,
"author": "Jon Skeet",
"author_id": 22656,
"author_profile": "https://Stackoverflow.com/users/22656",
"pm_score": 6,
"selected": false,
"text": "<p>A few hidden features I've come across:</p>\n\n<ul>\n<li><code>stackalloc</code> which lets you allocate arrays on the stack</li>\n<li>Anonymous methods with no explicit parameter list, which are implicitly convertible to any delegate type with non-out/ref parameters (very handy for events, as noted in an earlier comment)</li>\n<li>A lot of people aren't aware of what events really are (an add/remove pair of methods, like get/set for properties); field-like events in C# really declare both a variable <em>and</em> an event</li>\n<li>The <code>==</code> and <code>!=</code> operators can be overloaded to return types other than <code>bool</code>. Strange but true.</li>\n<li>The query expression translation in C# 3 is really \"simple\" in some ways - which means you can get it to do some <a href=\"http://msmvps.com/blogs/jon_skeet/archive/2008/02/29/odd-query-expressions.aspx\" rel=\"nofollow noreferrer\">very odd things</a>.</li>\n<li>Nullable types have special boxing behaviour: a null value gets boxed to a null reference, and you can unbox from null to the nullable type too.</li>\n</ul>\n"
},
{
"answer_id": 149509,
"author": "Mihai Lazar",
"author_id": 4204,
"author_profile": "https://Stackoverflow.com/users/4204",
"pm_score": 4,
"selected": false,
"text": "<p>One feature that I only learned about here on Stack Overflow was the ability to set an attribute on the return parameter. </p>\n\n<pre><code>[AttributeUsage( AttributeTargets.ReturnValue )]\npublic class CuriosityAttribute:Attribute\n{\n}\n\npublic class Bar\n{\n [return: Curiosity]\n public Bar ReturnANewBar()\n {\n return new Bar();\n }\n}\n</code></pre>\n\n<p>This was truly a hidden feature for me :-)</p>\n"
},
{
"answer_id": 157242,
"author": "dariom",
"author_id": 12389,
"author_profile": "https://Stackoverflow.com/users/12389",
"pm_score": 3,
"selected": false,
"text": "<p>String interning. This is one that I haven't seen come up in this discussion yet. It's a little obscure, but in certain conditions it can be useful.</p>\n\n<p>The CLR keeps a table of references to literal strings (and programmatically interned strings). If you use the same string in several places in your code it will be stored once in the table. This can ease the amount of memory required for allocating strings.</p>\n\n<p>You can test if a string is interned by using <a href=\"http://msdn.microsoft.com/en-us/library/system.string.isinterned.aspx\" rel=\"nofollow noreferrer\">String.IsInterned(string)</a> and you can intern a string using <a href=\"http://msdn.microsoft.com/en-us/library/system.string.intern.aspx\" rel=\"nofollow noreferrer\">String.Intern(string)</a>.</p>\n\n<p><strong>Note:</strong> The CLR can hold a reference to an interned string after application or even AppDomain end. See the MSDN documentation for details.</p>\n"
},
{
"answer_id": 165795,
"author": "Tim Jarvis",
"author_id": 10387,
"author_profile": "https://Stackoverflow.com/users/10387",
"pm_score": 6,
"selected": false,
"text": "<p>The params keyword, i.e.</p>\n\n<pre><code>public void DoSomething(params string[] theStrings)\n{\n foreach(string s in theStrings)\n {\n // Something with the Strings…\n }\n}\n</code></pre>\n\n<p>Called like</p>\n\n<pre><code>DoSomething(“The”, “cat”, “sat”, “on”, “the” ,”mat”);\n</code></pre>\n"
},
{
"answer_id": 165845,
"author": "tsilb",
"author_id": 11112,
"author_profile": "https://Stackoverflow.com/users/11112",
"pm_score": 4,
"selected": false,
"text": "<p>Labeling my endregions...</p>\n\n<pre><code>#region stuff1\n #region stuff1a\n //...\n #endregion stuff1a\n#endregion stuff1\n</code></pre>\n"
},
{
"answer_id": 174763,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 6,
"selected": false,
"text": "<p>I picked this one up when using <a href=\"http://www.jetbrains.com/resharper/\" rel=\"nofollow noreferrer\">ReSharper</a>:</p>\n\n<p>Implicit Method Group Conversion </p>\n\n<pre><code>//If given this:\nvar myStrings = new List<string>(){\"abc\",\"def\",\"xyz\"};\n//Then this:\nmyStrings.ForEach(s => Console.WriteLine(s));\n//Is equivalent to this:\nmyStrings.ForEach(Console.WriteLine);\n</code></pre>\n\n<p>See \"<a href=\"http://blog.opennetcf.com/ncowburn/2007/03/23/ImplicitMethodGroupConversionInC.aspx\" rel=\"nofollow noreferrer\">Implicit Method Group Conversion in C#</a>\" for more.</p>\n"
},
{
"answer_id": 176231,
"author": "Patrick Szalapski",
"author_id": 7453,
"author_profile": "https://Stackoverflow.com/users/7453",
"pm_score": 3,
"selected": false,
"text": "<p>Instead of using int.TryParse() or Convert.ToInt32(), I like having a static integer parsing function that returns null when it can't parse. Then I can use ?? and the ternary operator together to more clearly ensure my declaration and initialization are all done on one line in a easy-to-understand way. </p>\n\n<pre><code>public static class Parser {\n public static int? ParseInt(string s) {\n int result;\n bool parsed = int.TryParse(s, out result);\n if (parsed) return result;\n else return null;\n }\n // ...\n}\n</code></pre>\n\n<p>This is also good to avoid duplicating the left side of an assignment, but even better to avoid duplicating long calls on the right side of an assignment, such as a database calls in the following example. Instead of ugly if-then trees (which I run into often):</p>\n\n<pre><code>int x = 0;\nYourDatabaseResultSet data = new YourDatabaseResultSet();\nif (cond1)\n if (int.TryParse(x_input, x)){\n data = YourDatabaseAccessMethod(\"my_proc_name\", 2, x);\n }\n else{\n x = -1;\n // do something to report \"Can't Parse\" \n }\n}\nelse {\n x = y;\n data = YourDatabaseAccessMethod(\"my_proc_name\", \n new SqlParameter(\"@param1\", 2),\n new SqlParameter(\"@param2\", x));\n}\n</code></pre>\n\n<p>You can do:</p>\n\n<pre><code>int x = cond1 ? (Parser.ParseInt(x_input) ?? -1) : y;\nif (x >= 0) data = YourDatabaseAccessMethod(\"my_proc_name\", \n new SqlParameter(\"@param1\", 2),\n new SqlParameter(\"@param2\", x));\n</code></pre>\n\n<p>Much cleaner and easier to understand</p>\n"
},
{
"answer_id": 181714,
"author": "GvS",
"author_id": 11492,
"author_profile": "https://Stackoverflow.com/users/11492",
"pm_score": 5,
"selected": false,
"text": "<p>The <a href=\"http://msdn.microsoft.com/en-us/library/system.environment.userinteractive.aspx\" rel=\"nofollow noreferrer\">Environment.UserInteractive</a> property. </p>\n\n<blockquote>\n <p>The UserInteractive property reports\n false for a Windows process or a\n service like IIS that runs without a\n user interface. If this property is\n false, do not display modal dialogs or\n message boxes because there is no\n graphical user interface for the user\n to interact with.</p>\n</blockquote>\n"
},
{
"answer_id": 189100,
"author": "Scott McKenzie",
"author_id": 26625,
"author_profile": "https://Stackoverflow.com/users/26625",
"pm_score": 2,
"selected": false,
"text": "<p>ContextBoundObject</p>\n\n<p>Not so much a C# thing as a .NET thing. It's another way of achieving DI although it can be hardwork. And you have to inherit from it which can be off putting.</p>\n\n<p><a href=\"http://msdn.microsoft.com/en-us/library/system.contextboundobject.aspx\" rel=\"nofollow noreferrer\">http://msdn.microsoft.com/en-us/library/system.contextboundobject.aspx</a></p>\n\n<p>I've used it to add logging when I decorate a class/method with a custom logging attribute.</p>\n"
},
{
"answer_id": 192127,
"author": "IgorM",
"author_id": 17823,
"author_profile": "https://Stackoverflow.com/users/17823",
"pm_score": 5,
"selected": false,
"text": "<p>Full access to the call stack:</p>\n\n<pre><code>public static void Main()\n{\n StackTrace stackTrace = new StackTrace(); // get call stack\n StackFrame[] stackFrames = stackTrace.GetFrames(); // get method calls (frames)\n\n // write call stack method names\n foreach (StackFrame stackFrame in stackFrames)\n {\n Console.WriteLine(stackFrame.GetMethod().Name); // write method name\n }\n}\n</code></pre>\n\n<p>So, if you'll take the first one - you know what function you are in. If you're creating a helper tracing function - take one before the last one - you'll know your caller.</p>\n"
},
{
"answer_id": 195097,
"author": "sbeskur",
"author_id": 10446,
"author_profile": "https://Stackoverflow.com/users/10446",
"pm_score": 3,
"selected": false,
"text": "<p>I find this technique interesting while working with linqxml:</p>\n\n<pre><code>public bool GetFooSetting(XElement ndef){\n return (bool?)ndef.Element(\"MyBoolSettingValue\") ?? true;\n}\n</code></pre>\n\n<p>as opposed to:</p>\n\n<pre><code>public bool GetFooSetting(XElement ndef){\n return ndef.Element(\"MyBoolSettingValue\") != null ? bool.Parse(ndef.Element(\"MyBoolSettingValue\") ) : true;\n}\n</code></pre>\n"
},
{
"answer_id": 199247,
"author": "Jan Bannister",
"author_id": 460845,
"author_profile": "https://Stackoverflow.com/users/460845",
"pm_score": 7,
"selected": false,
"text": "<p>If you want to exit your program without calling any finally blocks or finalizers use <a href=\"http://msdn.microsoft.com/en-us/library/ms131100.aspx\" rel=\"nofollow noreferrer\">FailFast</a>:</p>\n\n<pre><code>Environment.FailFast()\n</code></pre>\n"
},
{
"answer_id": 199257,
"author": "Jan Bannister",
"author_id": 460845,
"author_profile": "https://Stackoverflow.com/users/460845",
"pm_score": 2,
"selected": false,
"text": "<pre><code>double dSqrd = Math.Pow(d,2.0); \n</code></pre>\n\n<p>is more accurate than </p>\n\n<pre><code>double dSqrd = d * d; // Here we can lose precision\n</code></pre>\n"
},
{
"answer_id": 199269,
"author": "Jan Bannister",
"author_id": 460845,
"author_profile": "https://Stackoverflow.com/users/460845",
"pm_score": 3,
"selected": false,
"text": "<p>You can switch on string!</p>\n\n<pre><code>switch(name)\n{\n case \"Dave\":\n return true;\n case \"Bob\":\n return false;\n default:\n throw new ApplicationException();\n}\n</code></pre>\n\n<p>Very handy! and a lot cleaner than a bunch of if-else statements</p>\n"
},
{
"answer_id": 212905,
"author": "Cristian Libardo",
"author_id": 16526,
"author_profile": "https://Stackoverflow.com/users/16526",
"pm_score": 6,
"selected": false,
"text": "<p>Just learned, anonymous types can infer property names from the variable name:</p>\n\n<pre><code>string hello = \"world\";\nvar o = new { hello };\nConsole.WriteLine(o.hello);\n</code></pre>\n"
},
{
"answer_id": 214951,
"author": "Mike Two",
"author_id": 23659,
"author_profile": "https://Stackoverflow.com/users/23659",
"pm_score": 6,
"selected": false,
"text": "<p>More of a runtime feature, but I recently learned that there are two garbage collectors. The workstation gc and the server gc. Workstation is the default on client versions of windows, but server is much faster on multicore machines.</p>\n\n<pre><code>\n<configuration>\n <runtime>\n <gcServer enabled=\"true\"/>\n </runtime>\n</configuration>\n</code></pre>\n\n<p>Be careful. The server gc requires more memory.</p>\n"
},
{
"answer_id": 223087,
"author": "Ian Andrews",
"author_id": 2382102,
"author_profile": "https://Stackoverflow.com/users/2382102",
"pm_score": 2,
"selected": false,
"text": "<p>This may be pretty basic to database application developers, but it took me a while to realize that null is not the same as DBNull.value. </p>\n\n<p>You have to use DBNull.value when you want to see if a value from a database record is null.</p>\n"
},
{
"answer_id": 236173,
"author": "splattne",
"author_id": 6461,
"author_profile": "https://Stackoverflow.com/users/6461",
"pm_score": 3,
"selected": false,
"text": "<h2>Object.ReferenceEquals Method</h2>\n\n<p>Determines whether the specified Object instances are the same instance.</p>\n\n<p><strong>Parameters:</strong></p>\n\n<ul>\n<li>objA: System.Object - The first Object to compare. </li>\n<li>objB: System.Object - The second Object to compare. </li>\n</ul>\n\n<p><strong>Example:</strong></p>\n\n<pre><code> object o = null;\n object p = null;\n object q = new Object();\n\n Console.WriteLine(Object.ReferenceEquals(o, p));\n p = q;\n Console.WriteLine(Object.ReferenceEquals(p, q));\n Console.WriteLine(Object.ReferenceEquals(o, p));\n</code></pre>\n\n<p><strong>Difference to \"==\" and \".Equals\":</strong></p>\n\n<p>Basically, Equals() tests of object A has the same content as object B.</p>\n\n<p>The method System.Object.ReferenceEquals() always compares references.\nAlthough a class can provide its own behavior for the equality operator\n(below), that re-defined operator isn't invoked if the operator is called\nvia a reference to System.Object. </p>\n\n<p>For strings there isn't really a difference, because both == and Equals have been overriden to compare the content of the string.</p>\n\n<p>See also <a href=\"https://stackoverflow.com/questions/73713/how-do-i-check-for-nulls-in-an-operator-overload-without-infinite-recursion#73732\">this answer</a> to another question (\"How do I check for nulls in an ‘==’ operator overload without infinite recursion?\").</p>\n"
},
{
"answer_id": 238462,
"author": "Dmitri Nesteruk",
"author_id": 9476,
"author_profile": "https://Stackoverflow.com/users/9476",
"pm_score": 7,
"selected": false,
"text": "<p>Mixins. Basically, if you want to add a feature to several classes, but cannot use one base class for all of them, get each class to implement an interface (with no members). Then, write an extension method <strong>for the interface</strong>, i.e.</p>\n\n<pre><code>public static DeepCopy(this IPrototype p) { ... }\n</code></pre>\n\n<p>Of course, some clarity is sacrificed. But it works!</p>\n"
},
{
"answer_id": 256013,
"author": "dviljoen",
"author_id": 29021,
"author_profile": "https://Stackoverflow.com/users/29021",
"pm_score": 2,
"selected": false,
"text": "<p>ThreadStaticAttribute is a favorite of mine. Also, NonSerializableAttribute is useful. (Can you tell I do a lot of server stuff using remoting?)</p>\n"
},
{
"answer_id": 258982,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 3,
"selected": false,
"text": "<p>The generic event handler:</p>\n\n<pre><code>public event EventHandler<MyEventArgs> MyEvent;\n</code></pre>\n\n<p>This way you don't have to declare your own delegates all the time,</p>\n"
},
{
"answer_id": 259028,
"author": "Dan Fleet",
"author_id": 7470,
"author_profile": "https://Stackoverflow.com/users/7470",
"pm_score": 2,
"selected": false,
"text": "<p>Just learned the joys of <code>[UnmanagedFunctionPointerAttribute(CallingConvention.CDecl)]</code> from trying to interface with an unmanaged C++ function library that defined callbacks without __stdcall.</p>\n"
},
{
"answer_id": 259134,
"author": "Gavin Miller",
"author_id": 33226,
"author_profile": "https://Stackoverflow.com/users/33226",
"pm_score": 3,
"selected": false,
"text": "<p>I didn't discover - for almost a year - that Strongly Typed DataRows contain an Is[ColumnName]Null() method.</p>\n\n<p>For example:</p>\n\n<pre><code>Units.UnitsDataTable dataTable = new Units.UnitsDataTable();\n\nforeach (Units.UnitsRow row in dataTable.Rows)\n{\n if (row.IsPrimaryKeyNull())\n //....\n\n if (row.IsForeignKeyNull())\n //....\n}\n</code></pre>\n"
},
{
"answer_id": 263868,
"author": "Cohen",
"author_id": 34474,
"author_profile": "https://Stackoverflow.com/users/34474",
"pm_score": 3,
"selected": false,
"text": "<p>Math.Max and Min to check boundaries:\nI 've seen this in a lot of code:</p>\n\n<pre><code>if (x < lowerBoundary) \n{\n x = lowerBoundary;\n}\n</code></pre>\n\n<p>I find this smaller, cleaner and more readable:</p>\n\n<pre><code>x = Math.Max(x, lowerBoundary);\n</code></pre>\n\n<p>Or you can also use a ternary operator:</p>\n\n<pre><code>x = ( x < lowerBoundary) ? lowerBoundary : x;\n</code></pre>\n"
},
{
"answer_id": 263883,
"author": "Cohen",
"author_id": 34474,
"author_profile": "https://Stackoverflow.com/users/34474",
"pm_score": 4,
"selected": false,
"text": "<p>Something I missed for a long time:\nyou can compare strings with </p>\n\n<pre><code>\"string\".equals(\"String\", StringComparison.InvariantCultureIgnoreCase)\n</code></pre>\n\n<p>instead of doing: </p>\n\n<pre><code>\"string\".ToLower() == \"String\".ToLower();\n</code></pre>\n"
},
{
"answer_id": 270430,
"author": "Dmitri Nesteruk",
"author_id": 9476,
"author_profile": "https://Stackoverflow.com/users/9476",
"pm_score": 3,
"selected": false,
"text": "<p>Mixins are a nice feature. Basically, mixins let you have concrete code for an interface instead of a class. Then, just implement the interface in a bunch of classes, and you automatically get mixin functionality. For example, to mix in deep copying into several classes, define an interface</p>\n\n<pre><code>internal interface IPrototype<T> { }\n</code></pre>\n\n<p>Add functionality for this interface</p>\n\n<pre><code>internal static class Prototype\n{\n public static T DeepCopy<T>(this IPrototype<T> target)\n {\n T copy;\n using (var stream = new MemoryStream())\n {\n var formatter = new BinaryFormatter();\n formatter.Serialize(stream, (T)target);\n stream.Seek(0, SeekOrigin.Begin);\n copy = (T) formatter.Deserialize(stream);\n stream.Close();\n }\n return copy;\n }\n}\n</code></pre>\n\n<p>Then implement interface in any type to get a mixin.</p>\n"
},
{
"answer_id": 292258,
"author": "Bryan Watts",
"author_id": 37815,
"author_profile": "https://Stackoverflow.com/users/37815",
"pm_score": 2,
"selected": false,
"text": "<p>ViewState getters can be one-liners.</p>\n\n<p><strong>Using a default value:</strong></p>\n\n<pre><code>public string Caption\n{\n get { return (string) (ViewState[\"Caption\"] ?? \"Foo\"); }\n set { ViewState[\"Caption\"] = value; }\n}\n\npublic int Index\n{\n get { return (int) (ViewState[\"Index\"] ?? 0); }\n set { ViewState[\"Index\"] = value; }\n}\n</code></pre>\n\n<p><strong>Using null as the default:</strong></p>\n\n<pre><code>public string Caption\n{\n get { return (string) ViewState[\"Caption\"]; }\n set { ViewState[\"Caption\"] = value; }\n}\n\npublic int? Index\n{\n get { return (int?) ViewState[\"Index\"]; }\n set { ViewState[\"Index\"] = value; }\n}\n</code></pre>\n\n<p>This works for anything backed by a dictionary.</p>\n"
},
{
"answer_id": 295174,
"author": "Eyvind",
"author_id": 25746,
"author_profile": "https://Stackoverflow.com/users/25746",
"pm_score": 3,
"selected": false,
"text": "<p>Regarding <code>foreach</code>: It does not use 'duck typing', as duck typing IMO refers to a runtime check. It uses <em>structural type checking</em> (as opposed to nominal) at compile time to check for the required method in the type.</p>\n"
},
{
"answer_id": 298424,
"author": "Enes",
"author_id": 2921654,
"author_profile": "https://Stackoverflow.com/users/2921654",
"pm_score": 1,
"selected": false,
"text": "<p><a href=\"https://stackoverflow.com/questions/169276/is-the-region-directive-really-useful-in-net#287438\">Here is a TIP</a> of how you can use #Region directive to document your code.</p>\n"
},
{
"answer_id": 299153,
"author": "Bryan Watts",
"author_id": 37815,
"author_profile": "https://Stackoverflow.com/users/37815",
"pm_score": 3,
"selected": false,
"text": "<p>(I just used this one) Set a field null and return it without an intermediate variable:</p>\n\n<pre><code>try\n{\n return _field;\n}\nfinally\n{\n _field = null;\n}\n</code></pre>\n"
},
{
"answer_id": 299173,
"author": "Rytmis",
"author_id": 266,
"author_profile": "https://Stackoverflow.com/users/266",
"pm_score": 3,
"selected": false,
"text": "<p><a href=\"http://msdn.microsoft.com/en-us/library/aa664591(VS.71).aspx\" rel=\"nofollow noreferrer\">Explicit interface member implementation</a>, wherein an interface member is implemented, but hidden unless the instance is cast to the interface type. </p>\n"
},
{
"answer_id": 299236,
"author": "Bryan Watts",
"author_id": 37815,
"author_profile": "https://Stackoverflow.com/users/37815",
"pm_score": 5,
"selected": false,
"text": "<p>On-demand field initialization in one line:</p>\n\n<pre><code>public StringBuilder Builder\n{\n get { return _builder ?? (_builder = new StringBuilder()); }\n}\n</code></pre>\n\n<p>I'm not sure how I feel about C# supporting assignment expressions, but hey, it's there :-)</p>\n"
},
{
"answer_id": 300100,
"author": "open-collar",
"author_id": 21686,
"author_profile": "https://Stackoverflow.com/users/21686",
"pm_score": 4,
"selected": false,
"text": "<p>Several people have mentioned <em>using</em> blocks, but I think they are much more useful than people have realised. Think of them as the poor man's AOP tool. I have a host of simple objects that capture state in the constructor and then restore it in the <em>Dispose()</em> method. That allows me to wrap a piece of functionality in a <em>using</em> block and be sure that the state is restored at the end. For example:</p>\n\n<pre><code>using(new CursorState(this, BusyCursor));\n{\n // Do stuff\n}\n</code></pre>\n\n<p><em>CursorState</em> captures the current cursor being used by form, then sets the form to use the cursor supplied. At the end it restores the original cursor. I do loads of things like this, for example capturing the selections and current row on a grid before refreshing and so on.</p>\n"
},
{
"answer_id": 302484,
"author": "Tor Haugen",
"author_id": 32050,
"author_profile": "https://Stackoverflow.com/users/32050",
"pm_score": 4,
"selected": false,
"text": "<p>You can use any Unicode character in C# names, for example:</p>\n\n<pre><code>public class MyClass\n{\n public string Hårføner()\n {\n return \"Yes, it works!\";\n }\n}\n</code></pre>\n\n<p>You can even use Unicode escapes. This one is equivalent to the above:</p>\n\n<pre><code>public class MyClass\n{\n public string H\\u00e5rføner()\n {\n return \"Yes, it (still) works!\";\n }\n}\n</code></pre>\n"
},
{
"answer_id": 302602,
"author": "MysticSlayer",
"author_id": 28139,
"author_profile": "https://Stackoverflow.com/users/28139",
"pm_score": 4,
"selected": false,
"text": "<p>What about using this:</p>\n\n<pre><code>#if DEBUG\n Console.Write(\"Debugging\");\n#else\n Console.Write(\"Final\");\n#endif\n</code></pre>\n\n<p>When you have your solution compiled with DEBUG defined it will output \"Debugging\".</p>\n\n<p>If your compile is set to Release it will write \"Final\".</p>\n"
},
{
"answer_id": 312756,
"author": "Gregor",
"author_id": 26153,
"author_profile": "https://Stackoverflow.com/users/26153",
"pm_score": 2,
"selected": false,
"text": "<p><strong>Framework Feature</strong></p>\n\n<p>I don't know but I was quite suprised about <a href=\"http://msdn.microsoft.com/de-de/library/system.windows.forms.visualstyles.visualstylerenderer(VS.85).aspx\" rel=\"nofollow noreferrer\">VisualStyleRenderer</a> and the whole <a href=\"http://msdn.microsoft.com/de-de/library/system.windows.forms.visualstyles(VS.85).aspx\" rel=\"nofollow noreferrer\">System.Windows.Forms.VisualStyles-Namespace</a>. Pretty cool!</p>\n"
},
{
"answer_id": 314065,
"author": "Richard Ev",
"author_id": 39709,
"author_profile": "https://Stackoverflow.com/users/39709",
"pm_score": 3,
"selected": false,
"text": "<p><code>IEnumerable</code>'s <code>SelectMany</code>, which flattens a list of lists into a single list. Let's say I have a list of <code>Orders</code>, and each <code>Order</code> has a list of <code>LineItems</code> on that order.</p>\n\n<p>I want to know the total number of <code>LineItems</code> sold... </p>\n\n<pre><code>int totalItems = Orders.Select(o => o.LineItems).SelectMany(i => i).Sum();\n</code></pre>\n"
},
{
"answer_id": 319182,
"author": "Rob",
"author_id": 34224,
"author_profile": "https://Stackoverflow.com/users/34224",
"pm_score": 3,
"selected": false,
"text": "<p>This isn't a C# specific type, but I just found the ISurrogateSelector and ISerializationSurrogate interfaces --</p>\n\n<p><a href=\"http://msdn.microsoft.com/en-us/library/system.runtime.serialization.isurrogateselector.aspx\" rel=\"nofollow noreferrer\">http://msdn.microsoft.com/en-us/library/system.runtime.serialization.isurrogateselector.aspx</a></p>\n\n<p><a href=\"http://msdn.microsoft.com/en-us/library/system.runtime.serialization.isurrogateselector.aspx\" rel=\"nofollow noreferrer\">http://msdn.microsoft.com/en-us/library/system.runtime.serialization.isurrogateselector.aspx</a></p>\n\n<p>Using these in conjunction with the BinaryFormatter allows for non-serializable objects to be serialized via the implementation of a surrogate class. The surrogate pattern is well-understood in computer science, particularly when dealing with the problem of serialization. I think that this implementation is just tucked away as a parameter of the constructor to BinaryFormatter, and that's too bad.</p>\n\n<p>Still - VERY hidden. :)</p>\n"
},
{
"answer_id": 336237,
"author": "Phillip Ngan",
"author_id": 41410,
"author_profile": "https://Stackoverflow.com/users/41410",
"pm_score": 4,
"selected": false,
"text": "<p>The delegate syntax have evolved over successive versions of C#, but I still find them difficult to remember. Fortunately the <code>Action<></code> and <code>Func<></code> delegates are easy to remember.</p>\n\n<p>For example:</p>\n\n<ul>\n<li><code>Action<int></code> is a delegate method that takes a single int argument and returns void.</li>\n<li><code>Func<int></code> is a delegate method that takes no arguments and returns an int.</li>\n<li><code>Func<int, bool></code> is a delegate method that takes a single int argument and returns a bool.</li>\n</ul>\n\n<p>These features were introduced in version 3.5 of the .NET framework.</p>\n"
},
{
"answer_id": 343526,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 4,
"selected": false,
"text": "<p>One great class I like is <code>System.Xml.XmlConvert</code> which can be used to read values from xml tag. Especially, if I am reading a boolean value from xml attribute or element, I use </p>\n\n<pre><code>bool myFlag = System.Xml.XmlConvert.ToBoolean(myAttribute.Value);\n</code></pre>\n\n<p>Note: since boolean type in xml accepts 1 and 0 in addition to \"true\" and \"false\" as valid values, using string comparison in this case is error-prone.</p>\n"
},
{
"answer_id": 355991,
"author": "Binoj Antony",
"author_id": 33015,
"author_profile": "https://Stackoverflow.com/users/33015",
"pm_score": 6,
"selected": false,
"text": "<p>Other underused operators are <code>checked</code> and <code>unchecked</code>:</p>\n\n<pre><code>short x = 32767; // 32767 is the max value for short\nshort y = 32767;\nint z1 = checked((short)(x + y)); //will throw an OverflowException\nint z2 = unchecked((short)(x + y)); // will return -2\nint z3 = (short)(x + y); // will return -2\n</code></pre>\n"
},
{
"answer_id": 365801,
"author": "Binoj Antony",
"author_id": 33015,
"author_profile": "https://Stackoverflow.com/users/33015",
"pm_score": 3,
"selected": false,
"text": "<p>To call the base class constructor just put base() inline with the constructor.<br />\nTo call the base class method you can just put base.MethodName() inside the derived class method</p>\n\n<pre><code>class ClassA \n{\n public ClassA(int a)\n {\n //Do something\n }\n\n public void Method1()\n {\n //Do Something\n }\n}\n\nclass ClassB : ClassA\n{\n public ClassB(int a) : base(a) // calling the base class constructor\n {\n //Do something\n }\n\n public void Method2()\n {\n base.Method1(); // calling the base class method\n }\n}\n</code></pre>\n\n<p>Of course you can call the methods of the base class by just saying <code>base.MethodName()</code></p>\n"
},
{
"answer_id": 368625,
"author": "amazedsaint",
"author_id": 45956,
"author_profile": "https://Stackoverflow.com/users/45956",
"pm_score": 3,
"selected": false,
"text": "<p><strong>dynamic keyword in C# 4.0</strong></p>\n\n<p>You can use dynamic keyword, if you want your method calls to be resolved only at the runtime. </p>\n\n<pre><code>dynamic invoker=new DynamicInvoker();\ndynamic result1=invoker.MyMethod1();\ndynamic result2=invoker.MyMethod2();\n</code></pre>\n\n<p>Here I'm implementing a dynamic invoker.</p>\n\n<pre><code>public class DynamicInvoker : IDynamicObject\n {\n public MetaObject GetMetaObject\n (System.Linq.Expressions.Expression parameter)\n {\n return new DynamicReaderDispatch (parameter);\n }\n }\n\n public class DynamicDispatcher : MetaObject\n {\n public DynamicDispatcher (Expression parameter) \n : base(parameter, Restrictions.Empty){ }\n\n public override MetaObject Call(CallAction action, MetaObject[] args)\n {\n //You'll get MyMethod1 and MyMethod2 here (and what ever you call)\n Console.WriteLine(\"Logic to invoke Method '{0}'\", action.Name);\n return this; //Return a meta object\n }\n }\n</code></pre>\n"
},
{
"answer_id": 370561,
"author": "Rinat Abdullin",
"author_id": 47366,
"author_profile": "https://Stackoverflow.com/users/47366",
"pm_score": 4,
"selected": false,
"text": "<p>Ability to use LINQ Expressions to perform strongly-typed reflection:</p>\n\n<pre><code>static void Main(string[] args)\n{\n var domain = \"matrix\";\n Check(() => domain);\n Console.ReadLine();\n}\n\nstatic void Check<T>(Expression<Func<T>> expr)\n{\n var body = ((MemberExpression)expr.Body);\n Console.WriteLine(\"Name is: {0}\", body.Member.Name);\n Console.WriteLine(\"Value is: {0}\", ((FieldInfo)body.Member)\n .GetValue(((ConstantExpression)body.Expression).Value));\n}\n\n// output:\n// Name is: 'domain'\n// Value is: 'matrix'\n</code></pre>\n\n<p>More details are available at <a href=\"http://rabdullin.com/journal/2008/12/13/how-to-find-out-variable-or-parameter-name-in-c.html\" rel=\"nofollow noreferrer\">How to Find Out Variable or Parameter Name in C#?</a></p>\n"
},
{
"answer_id": 372964,
"author": "Steven Behnke",
"author_id": 42588,
"author_profile": "https://Stackoverflow.com/users/42588",
"pm_score": 3,
"selected": false,
"text": "<p>This isn't a C# specific feature but it is an addon that I find very useful. It is called the Resource Refactoring Tool. It allows you to right click on a literal string and extract it into a resource file. It will search the code and find any other literal strings that match and replace it with the same resource from the Resx file.</p>\n\n<p><a href=\"http://www.codeplex.com/ResourceRefactoring\" rel=\"nofollow noreferrer\">http://www.codeplex.com/ResourceRefactoring</a></p>\n"
},
{
"answer_id": 388760,
"author": "Moran Helman",
"author_id": 1409636,
"author_profile": "https://Stackoverflow.com/users/1409636",
"pm_score": 3,
"selected": false,
"text": "<p>TrueForAll Method of <code>List<T></code> :</p>\n\n<pre><code>List<int> s = new List<int> { 6, 1, 2 };\n\nbool a = s.TrueForAll(p => p > 0);\n</code></pre>\n"
},
{
"answer_id": 391966,
"author": "Michael Meadows",
"author_id": 7643,
"author_profile": "https://Stackoverflow.com/users/7643",
"pm_score": 5,
"selected": false,
"text": "<h2>Closures</h2>\n\n<p>Since anonymous delegates were added to 2.0, we have been able to develop closures. They are rarely used by programmers but provide great benefits such as immediate code reuse. Consider this piece of code:</p>\n\n<pre><code>bool changed = false;\n\nif (model.Prop1 != prop1)\n{\n changed = true;\n model.Prop1 = prop1;\n}\nif (model.Prop2 != prop2)\n{\n changed = true;\n model.Prop2 = prop2;\n}\n// ... etc. \n</code></pre>\n\n<p>Note that the if-statements above perform similar pieces of code with the exception of one line of code, i.e. setting different properties. This can be shortened with the following, where the varying line of code is entered as a parameter to an <code>Action</code> object, appropriately named <code>setAndTagChanged</code>:</p>\n\n<pre><code>bool changed = false;\nAction<Action> setAndTagChanged = (action) => \n{ \n changed = true; \n action(); \n};\n\nif (model.Prop1 != prop1) setAndTagChanged(() => model.Prop1 = prop1);\nif (model.Prop2 != prop2) setAndTagChanged(() => model.Prop2 = prop2);\n</code></pre>\n\n<p>In the second case, the closure allows you to scope the <code>change</code> variable in your lambda, which is a concise way to approach this problem.</p>\n\n<p>An alternate way is to use another unused feature, the \"or equal\" binary assignment operator. The following code shows how:</p>\n\n<pre><code>private bool conditionalSet(bool condition, Action action)\n{\n if (condition) action();\n return condition;\n}\n\n// ...\n\nbool changed = false;\nchanged |= conditionalSet(model.Prop1 == prop1, () => model.Prop1 = prop1);\nchanged |= conditionalSet(model.Prop2 == prop2, () => model.Prop2 = prop2);\n</code></pre>\n"
},
{
"answer_id": 399297,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 3,
"selected": false,
"text": "<p>I call this AutoDebug because you can drop right into debug where and when you need based on a bool value which could also be stored as a project user setting as well.</p>\n\n<p>Example:</p>\n\n<pre><code>//Place at top of your code\npublic UseAutoDebug = true;\n\n\n//Place anywhere in your code including catch areas in try/catch blocks\nDebug.Assert(!this.UseAutoDebug);\n</code></pre>\n\n<p>Simply place the above in try/catch blocks or other areas of your code and set UseAutoDebug to true or false and drop into debug anytime you wish for testing.</p>\n\n<p>You can leave this code in place and toggle this feature on and off when testing, You can also save it as a Project Setting, and manually change it after deployment to get additional bug information from users when/if needed as well.</p>\n\n<p>You can see a functional and working example of using this technique in this Visual Studio C# Project Template here, where it is used heavily:</p>\n\n<p><a href=\"http://code.msdn.microsoft.com/SEHE\" rel=\"nofollow noreferrer\">http://code.msdn.microsoft.com/SEHE</a></p>\n"
},
{
"answer_id": 405088,
"author": "Mark Cidade",
"author_id": 1659,
"author_profile": "https://Stackoverflow.com/users/1659",
"pm_score": 4,
"selected": false,
"text": "<p><strong>C# 3.0's LINQ query comprehensions are full-blown monadic comprehensions</strong> <em>a la</em> Haskell (in fact they were designed by one of Haskell's designers). They will work for any generic type that follows the \"LINQ pattern\" and allows you to write in a pure monadic functional style, which means that all of your variables are immutable (as if the only variables you used were <code>IDisposable</code>s and <code>IEnumerable</code>s in <em>using</em> and <em>foreach</em> statements). This is helpful for keeping variable declarations close to where they're used and making sure that all side-effects are explicitly declared, if there are any at all.</p>\n\n<pre><code> interface IFoo<T>\n { T Bar {get;}\n }\n\n class MyFoo<T> : IFoo<T> \n { public MyFoo(T t) {Bar = t;}\n public T Bar {get; private set;} \n }\n\n static class Foo \n { public static IFoo<T> ToFoo<T>(this T t) {return new MyFoo<T>(t);}\n\n public static void Do<T>(this T t, Action<T> a) { a(t);}\n\n public static IFoo<U> Select<T,U>(this IFoo<T> foo, Func<T,U> f) \n { return f(foo.Bar).ToFoo();\n }\n }\n\n /* ... */\n\n using (var file = File.OpenRead(\"objc.h\"))\n { var x = from f in file.ToFoo()\n let s = new Scanner(f)\n let p = new Parser {scanner = s}\n select p.Parse();\n\n x.Do(p => \n { /* drop into imperative code to handle file \n in Foo monad if necessary */ \n });\n\n }\n</code></pre>\n"
},
{
"answer_id": 407325,
"author": "hugoware",
"author_id": 17091,
"author_profile": "https://Stackoverflow.com/users/17091",
"pm_score": 5,
"selected": false,
"text": "<p>I'd say using certain system classes for extension methods is very handy, for example System.Enum, you can do something like below...</p>\n\n<pre><code>[Flags]\npublic enum ErrorTypes : int {\n None = 0,\n MissingPassword = 1,\n MissingUsername = 2,\n PasswordIncorrect = 4\n}\n\npublic static class EnumExtensions {\n\n public static T Append<T> (this System.Enum type, T value) where T : struct\n {\n return (T)(ValueType)(((int)(ValueType) type | (int)(ValueType) value));\n }\n\n public static T Remove<T> (this System.Enum type, T value) where T : struct\n {\n return (T)(ValueType)(((int)(ValueType)type & ~(int)(ValueType)value));\n }\n\n public static bool Has<T> (this System.Enum type, T value) where T : struct\n {\n return (((int)(ValueType)type & (int)(ValueType)value) == (int)(ValueType)value);\n }\n\n}\n\n...\n\n//used like the following...\n\nErrorTypes error = ErrorTypes.None;\nerror = error.Append(ErrorTypes.MissingUsername);\nerror = error.Append(ErrorTypes.MissingPassword);\nerror = error.Remove(ErrorTypes.MissingUsername);\n\n//then you can check using other methods\nif (error.Has(ErrorTypes.MissingUsername)) {\n ...\n}\n</code></pre>\n\n<p>This is just an example of course - the methods could use a little more work...</p>\n"
},
{
"answer_id": 475559,
"author": "JohnOpincar",
"author_id": 16245,
"author_profile": "https://Stackoverflow.com/users/16245",
"pm_score": 3,
"selected": false,
"text": "<p>You can have generic methods in a non-generic class.</p>\n"
},
{
"answer_id": 498292,
"author": "Andrew Peters",
"author_id": 608,
"author_profile": "https://Stackoverflow.com/users/608",
"pm_score": 3,
"selected": false,
"text": "<p>Cool trick to emulate functional \"wildcard\" arguments (like '_' in Haskell) when using lambdas:</p>\n\n<pre><code>(_, b, __) => b.DoStuff(); // only interested in b here\n</code></pre>\n"
},
{
"answer_id": 508371,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 2,
"selected": false,
"text": "<p>Only for reference - enum binary operations using the extension method.</p>\n\n<pre><code>using System;\nusing System.Collections.Generic;\nusing System.Linq;\nusing System.Text;\nusing System.Linq.Expressions;\n\nnamespace BinaryOpGenericTest\n{\n [Flags]\n enum MyFlags\n {\n A = 1,\n B = 2,\n C = 4\n\n }\n\n static class EnumExtensions\n {\n private static Dictionary<Type, Delegate> m_operations = new Dictionary<Type, Delegate>();\n\n public static bool IsFlagSet<T>(this T firstOperand, T secondOperand) \n where T : struct\n {\n\n Type enumType = typeof(T);\n\n\n if (!enumType.IsEnum)\n {\n throw new InvalidOperationException(\"Enum type parameter required\");\n }\n\n\n Delegate funcImplementorBase = null;\n m_operations.TryGetValue(enumType, out funcImplementorBase);\n\n Func<T, T, bool> funcImplementor = funcImplementorBase as Func<T, T, bool>;\n\n if (funcImplementor == null)\n {\n funcImplementor = buildFuncImplementor(secondOperand);\n }\n\n\n\n return funcImplementor(firstOperand, secondOperand);\n }\n\n\n private static Func<T, T, bool> buildFuncImplementor<T>(T val)\n where T : struct\n {\n var first = Expression.Parameter(val.GetType(), \"first\");\n var second = Expression.Parameter(val.GetType(), \"second\");\n\n Expression convertSecondExpresion = Expression.Convert(second, typeof(int));\n var andOperator = Expression.Lambda<Func<T, T, bool>>(Expression.Equal(\n Expression.And(\n Expression.Convert(first, typeof(int)),\n convertSecondExpresion),\n convertSecondExpresion),\n new[] { first, second });\n Func<T, T, bool> andOperatorFunc = andOperator.Compile();\n m_operations[typeof(T)] = andOperatorFunc;\n return andOperatorFunc;\n }\n }\n\n\n class Program\n {\n static void Main(string[] args)\n {\n MyFlags flag = MyFlags.A | MyFlags.B;\n\n Console.WriteLine(flag.IsFlagSet(MyFlags.A)); \n Console.WriteLine(EnumExtensions.IsFlagSet(flag, MyFlags.C));\n Console.ReadLine();\n }\n }\n}\n</code></pre>\n"
},
{
"answer_id": 593134,
"author": "Jonathan Parker",
"author_id": 4504,
"author_profile": "https://Stackoverflow.com/users/4504",
"pm_score": 3,
"selected": false,
"text": "<p>Method groups aren't well known.</p>\n\n<p>Given:</p>\n\n<pre><code>Func<Func<int,int>,int,int> myFunc1 = (i, j) => i(j);\nFunc<int, int> myFunc2 = i => i + 2;\n</code></pre>\n\n<p>You can do this:</p>\n\n<pre><code>var x = myFunc1(myFunc2, 1);\n</code></pre>\n\n<p>instead of this:</p>\n\n<pre><code>var x = myFunc1(z => myFunc2(z), 1);\n</code></pre>\n"
},
{
"answer_id": 618582,
"author": "tuinstoel",
"author_id": 43901,
"author_profile": "https://Stackoverflow.com/users/43901",
"pm_score": 4,
"selected": false,
"text": "<p>You can use generics to check (compile time) if a method argument implements two interfaces:</p>\n\n<pre><code>interface IPropA \n{\n string PropA { get; set; } \n}\n\ninterface IPropB \n{\n string PropB { get; set; }\n}\n\nclass TestClass \n{\n void DoSomething<T>(T t) where T : IPropA, IPropB \n {\n MessageBox.Show(t.PropA);\n MessageBox.Show(t.PropB);\n }\n}\n</code></pre>\n\n<p>Same with an argument that is inherited from a base class and an interface. </p>\n"
},
{
"answer_id": 637760,
"author": "kentaromiura",
"author_id": 27340,
"author_profile": "https://Stackoverflow.com/users/27340",
"pm_score": 3,
"selected": false,
"text": "<p>Is constructor chain already cited?</p>\n\n<pre><code>namespace constructorChain {\n using System;\n\n public class Class1 {\n public string x;\n public string y;\n\n public Class1() {\n x = \"class1\";\n y = \"\";\n }\n\n public Class1(string y)\n : this() {\n this.y = y;\n }\n }\n\n public class Class2 : Class1 {\n public Class2(int y)\n : base(y.ToString()) {\n\n }\n }\n}\n</code></pre>\n\n<p>...</p>\n\n<pre><code> constructorChain.Class1 c1 = new constructorChain.Class1();\n constructorChain.Class1 c12 = new constructorChain.Class1(\"Hello, Constructor!\");\n constructorChain.Class2 c2 = new constructorChain.Class2(10);\n Console.WriteLine(\"{0}:{1}\", c1.x, c1.y);\n Console.WriteLine(\"{0}:{1}\", c12.x, c12.y);\n Console.WriteLine(\"{0}:{1}\", c2.x, c2.y);\n\n Console.ReadLine();\n</code></pre>\n"
},
{
"answer_id": 699973,
"author": "Raghu Dodda",
"author_id": 84940,
"author_profile": "https://Stackoverflow.com/users/84940",
"pm_score": 1,
"selected": false,
"text": "<p>Not hidden, but pretty neat. I find this a more succinct substitute for a simple if-then-else that just assigns a value based on a condition.</p>\n\n<pre><code>string result = \n i < 2 ? //question\n \"less than 2\" : //answer\n i < 5 ? //question\n \"less than 5\": //answer \n i < 10 ? //question\n \"less than 10\": //answer\n \"something else\"; //default answer \n</code></pre>\n"
},
{
"answer_id": 707480,
"author": "DSO",
"author_id": 38087,
"author_profile": "https://Stackoverflow.com/users/38087",
"pm_score": 3,
"selected": false,
"text": "<p>Here's one I discovered recently which has been useful:</p>\n\n<pre><code>Microsoft.VisualBasic.Logging.FileLogTraceListener\n</code></pre>\n\n<p><a href=\"http://msdn.microsoft.com/en-us/library/microsoft.visualbasic.logging.filelogtracelistener.aspx\" rel=\"nofollow noreferrer\">MSDN Link</a></p>\n\n<p>This is a TraceListener implementation which has a lot of features, such as automatic log file roll over, which I previously would use a custom logging framework for. The nice thing is that it is a core part of .NET and is integrated with the Trace framework, so its easy to pick up and use immediately.</p>\n\n<p>This is \"hidden\" because its in the Microsoft.VisualBasic assembly... but you can use it from C# as well.</p>\n"
},
{
"answer_id": 709198,
"author": "Waleed Eissa",
"author_id": 676066,
"author_profile": "https://Stackoverflow.com/users/676066",
"pm_score": 3,
"selected": false,
"text": "<p>Working with enums.</p>\n\n<p>Convert a string to an Enum:</p>\n\n<pre><code>enum MyEnum\n{\n FirstValue,\n SecondValue,\n ThirdValue\n}\n\nstring enumValueString = \"FirstValue\";\nMyEnum val = (MyEnum)Enum.Parse(typeof(MyEnum), enumValueString, true)\n</code></pre>\n\n<ul>\n<li>I use this to load the value of CacheItemPriority in my ASP.NET applications from a settings table in a database so that I can control caching (along with other settings) dynamically without taking the application down.</li>\n</ul>\n\n<p>When comparing variables of type enum, you don't have to cast to int:</p>\n\n<pre><code>MyEnum val = MyEnum.SecondValue;\nif (val < MyEnum.ThirdValue)\n{\n // Do something\n}\n</code></pre>\n"
},
{
"answer_id": 710507,
"author": "Gorkem Pacaci",
"author_id": 51749,
"author_profile": "https://Stackoverflow.com/users/51749",
"pm_score": 3,
"selected": false,
"text": "<p>I quite enjoy implicit generic parameters on functions. For example, if you have:</p>\n\n<pre><code>public void DoStuff<T>(T value);\n</code></pre>\n\n<p>Instead of calling it like this:</p>\n\n<pre><code>DoStuff<int>(5);\n</code></pre>\n\n<p>You can:</p>\n\n<pre><code>DoStuff(5);\n</code></pre>\n\n<p>And it'll work out the generic type from the parameter's type. </p>\n\n<ul>\n<li>This doesn't work if you're calling the method through reflection.</li>\n<li>I remember having some weird problems on Mono.</li>\n</ul>\n"
},
{
"answer_id": 749846,
"author": "Ralph Caraveo",
"author_id": 71079,
"author_profile": "https://Stackoverflow.com/users/71079",
"pm_score": 7,
"selected": false,
"text": "<p>Many people don't realize that they can compare strings using: OrdinalIgnoreCase instead of having to do someString.ToUpper(). This removes the additional string allocation overhead.</p>\n\n<pre><code>if( myString.ToUpper() == theirString.ToUpper() ){ ... }\n</code></pre>\n\n<p>becomes</p>\n\n<pre><code>if( myString.Equals( theirString, StringComparison.OrdinalIgnoreCase ) ){ ... }\n</code></pre>\n"
},
{
"answer_id": 759323,
"author": "Peter Lillevold",
"author_id": 35245,
"author_profile": "https://Stackoverflow.com/users/35245",
"pm_score": 4,
"selected": false,
"text": "<p>My favorite attribute: <a href=\"http://msdn.microsoft.com/en-us/library/system.runtime.compilerservices.internalsvisibletoattribute.aspx\" rel=\"nofollow noreferrer\">InternalsVisibleTo</a></p>\n\n<p>At assembly level you can declare that another assembly can see your internals. For testing purposes this is absolutely wonderful. </p>\n\n<p>Stick this in your AssemblyInfo.cs or equivalent and your test assembly get full access to all the internal stuff that requires testing.</p>\n\n<pre><code>[assembly: InternalsVisibleTo(\"MyLibrary.Test, PublicKey=0024...5c042cb\")]\n</code></pre>\n\n<p>As you can see, the test assembly must have <a href=\"http://msdn.microsoft.com/en-us/library/xc31ft41.aspx\" rel=\"nofollow noreferrer\">a strong name</a> to gain the trust of the assembly under test.</p>\n\n<p>Available in .Net Framework 2.0+, Compact Framework 2.0+ and XNA Framework 1.0+.</p>\n"
},
{
"answer_id": 781561,
"author": "Akash Kava",
"author_id": 85597,
"author_profile": "https://Stackoverflow.com/users/85597",
"pm_score": 3,
"selected": false,
"text": "<blockquote>\n <p><strong>FIXED</strong> / Power of Pointers in C# - This topic is too big, but I will just outline simple things.</p>\n</blockquote>\n\n<p>In C we had facility of loading structure like...</p>\n\n<pre><code>struct cType{\n char type[4];\n int size;\n char name[50];\n char email[100];\n}\n\ncType myType;\nfread(file, &mType, sizeof(mType));\n</code></pre>\n\n<p>We can use fixed keyword in \"unsafe\" method to read byte array aligned structure.</p>\n\n<pre><code>[Layout(LayoutKind.Sequential, Pack=1)]\npublic unsafe class CType{\n public fixed byte type[4];\n public int size;\n public fixed byte name[50];\n public fixed byte email[100];\n}\n</code></pre>\n\n<p>Method 1 (Reading from regular stream in to byte buffer and mapping byte array to individual bytes of struct)</p>\n\n<pre><code>CType mType = new CType();\nbyte[] buffer = new byte[Marshal.SizeOf(CType)];\nstream.Read(buffer,0,buffer.Length);\n// you can map your buffer back to your struct...\nfixed(CType* sp = &mType)\n{\n byte* bsp = (byte*) sp;\n fixed(byte* bp = &buffer)\n {\n for(int i=0;i<buffer.Length;i++)\n {\n (*bsp) = (*bp);\n bsp++;bp++;\n }\n }\n}\n</code></pre>\n\n<p>Method 2, you can map Win32 User32.dll's ReadFile to directly read bytes...</p>\n\n<pre><code>CType mType = new CType();\nfixed(CType* p = &mType)\n{\n User32.ReadFile(fileHandle, (byte*) p, Marshal.SizeOf(mType),0);\n}\n</code></pre>\n"
},
{
"answer_id": 791096,
"author": "Elroy",
"author_id": 56097,
"author_profile": "https://Stackoverflow.com/users/56097",
"pm_score": 3,
"selected": false,
"text": "<p>The usage of the default keyword in generic code to return the default value for a type.</p>\n\n<pre><code>public class GenericList<T>\n{\n private class Node\n {\n //...\n\n public Node Next;\n public T Data;\n }\n\n private Node head;\n\n //...\n\n public T GetNext()\n {\n T temp = default(T);\n\n Node current = head;\n if (current != null)\n {\n temp = current.Data;\n current = current.Next;\n }\n return temp;\n }\n}\n</code></pre>\n\n<p><a href=\"https://stackoverflow.com/questions/367378/returning-a-default-value-c\">Another example here</a></p>\n"
},
{
"answer_id": 794343,
"author": "Dries Van Hansewijck",
"author_id": 95981,
"author_profile": "https://Stackoverflow.com/users/95981",
"pm_score": 2,
"selected": false,
"text": "<p>The InternalsVisibleToAttribute specifies that types that are ordinarily visible only within the current assembly are visible to another assembly. <a href=\"http://msdn.microsoft.com/en-us/library/system.runtime.compilerservices.internalsvisibletoattribute.aspx\" rel=\"nofollow noreferrer\" title=\"InternalsVisibleToAttribute class\">Article on msdn</a></p>\n"
},
{
"answer_id": 821718,
"author": "rein",
"author_id": 100142,
"author_profile": "https://Stackoverflow.com/users/100142",
"pm_score": 3,
"selected": false,
"text": "<p>Instead of doing something cheesy like this:</p>\n\n<pre><code>Console.WriteLine(\"{0} item(s) found.\", count);\n</code></pre>\n\n<p>I use the following inline trick:</p>\n\n<pre><code>Console.WriteLine(\"{0} item{1} found.\", count, count==1 ? \"\" : \"s\");\n</code></pre>\n\n<p>This will display \"item\" when there's one item or \"items\" when there are more (or less) than 1. Not much effort for a little bit of professionalism.</p>\n"
},
{
"answer_id": 840445,
"author": "nsantorello",
"author_id": 94824,
"author_profile": "https://Stackoverflow.com/users/94824",
"pm_score": 3,
"selected": false,
"text": "<p>One thing not many people know about are some of the C#-introduced preprocessor directives. You can use <code>#error This is an error.</code> to generate a compiler error and <code>#warning This is a warning.</code></p>\n\n<p>I usually use these when I'm developing with a top-down approach as a \"todo\" list. I'll <code>#error Implement this function</code>, or <code>#warning Eventually implement this corner case</code> as a reminder.</p>\n"
},
{
"answer_id": 840998,
"author": "Drew Hoskins",
"author_id": 97235,
"author_profile": "https://Stackoverflow.com/users/97235",
"pm_score": 2,
"selected": false,
"text": "<p>In dealing with interop between C++ and C#, many people don't realize that C++/CLI is a great option.</p>\n\n<p>Say you have a C++ DLL and a C# DLL which depends on the C++ DLL. Often, the easiest technique is to compile some (or all) modules of the C++ DLL with the /clr switch. To have the C# call the C++ DLL is to write managed C++ wrapper classes in the C++ DLL. The C++/CLI classes can call the native C++ code much more seamlessly than C#, because the C++ compiler will automatically generate P/invokes for you, has a library specifically for interop, plus language features for interop like <a href=\"http://msdn.microsoft.com/en-us/library/1dz8byfh(VS.80).aspx\" rel=\"nofollow noreferrer\">pin_ptr</a>. And it allows managed and native code to coexist within the same binary.</p>\n\n<p>On the C# side, you just call into the DLL as you would any other .NET binary.</p>\n"
},
{
"answer_id": 841140,
"author": "Jeff Yates",
"author_id": 23234,
"author_profile": "https://Stackoverflow.com/users/23234",
"pm_score": 3,
"selected": false,
"text": "<p>I am so so late to this question, but I wanted to add a few that I don't think have been covered. These aren't C#-specific, but I think they're worthy of mention for any C# developer.</p>\n\n<p><a href=\"http://msdn.microsoft.com/en-us/library/system.componentmodel.ambientvalueattribute.aspx\" rel=\"nofollow noreferrer\"><h3>AmbientValueAttribute</h3></a>\nThis is similar to <code>DefaultValueAttribute</code>, but instead of providing the value that a property defaults to, it provides the value that a property uses to decide whether to request its value from somewhere else. For example, for many controls in WinForms, their <code>ForeColor</code> and <code>BackColor</code> properties have an <code>AmbientValue</code> of <code>Color.Empty</code> so that they know to get their colors from their parent control.</p>\n\n<p><a href=\"http://msdn.microsoft.com/en-us/library/system.io.isolatedstorage.isolatedstoragesettings(VS.95).aspx\" rel=\"nofollow noreferrer\"><h3>IsolatedStorageSettings</h3></a>\nThis is a Silverlight one. The framework handily includes this sealed class for providing settings persistence at both the per-application and per-site level.</p>\n\n<h3>Flag interaction with extension methods</h3>\n\n<p>Using extension methods, flag enumeration use can be a lot more readable.</p>\n\n<pre><code> public static bool Contains(\n this MyEnumType enumValue,\n MyEnumType flagValue)\n {\n return ((enumValue & flagValue) == flagValue);\n }\n\n public static bool ContainsAny(\n this MyEnumType enumValue,\n MyEnumType flagValue)\n {\n return ((enumValue & flagValue) > 0);\n }\n</code></pre>\n\n<p>This makes checks for flag values nice and easy to read and write. Of course, it would be nicer if we could use generics and enforce T to be an enum, but that isn't allowed. Perhaps <code>dynamic</code> will make this easier.</p>\n"
},
{
"answer_id": 862323,
"author": "Ash",
"author_id": 5023,
"author_profile": "https://Stackoverflow.com/users/5023",
"pm_score": 3,
"selected": false,
"text": "<p>The built-in (2.0) MethodInvoker delegate is useful when you want to Invoke/BeginInvoke inline code. This avoids needing to create an actual delegate and separate method.</p>\n\n<pre><code> void FileMessageEvent(object sender, MessageEventArgs e)\n {\n\n if (this.InvokeRequired == true)\n {\n this.BeginInvoke((MethodInvoker)delegate { \n lblMessage.Text=e.Message; \n Application.DoEvents(); \n }\n ); \n\n }\n }\n</code></pre>\n\n<p>Resolves the error: \"Cannot convert anonymous method to type 'System.Delegate' because it is not a delegate type\".</p>\n"
},
{
"answer_id": 874167,
"author": "Josef Pfleger",
"author_id": 98401,
"author_profile": "https://Stackoverflow.com/users/98401",
"pm_score": 3,
"selected": false,
"text": "<p>I find it incredible what type of trouble the compiler goes through to sugar code the use of <strong>Outer Variables</strong>:</p>\n\n<pre><code>string output = \"helo world!\";\nAction action = () => Console.WriteLine(output);\noutput = \"hello!\";\naction();\n</code></pre>\n\n<p>This actually prints <code>hello!</code>. Why? Because the compiler creates a nested class for the delegate, with public fields for all <em>outer variables</em> and inserts setting-code before every single call to the delegate :) Here is above code 'reflectored':</p>\n\n<pre><code>Action action;\n<>c__DisplayClass1 CS$<>8__locals2;\nCS$<>8__locals2 = new <>c__DisplayClass1();\nCS$<>8__locals2.output = \"helo world!\";\naction = new Action(CS$<>8__locals2.<Main>b__0);\nCS$<>8__locals2.output = \"hello!\";\naction();\n</code></pre>\n\n<p>Pretty cool I think.</p>\n"
},
{
"answer_id": 882100,
"author": "Shalom Craimer",
"author_id": 54491,
"author_profile": "https://Stackoverflow.com/users/54491",
"pm_score": 3,
"selected": false,
"text": "<p>I couldn't figure out what use some of the functions in the <code>Convert</code> class had (such as Convert.ToDouble(int), Convert.ToInt(double)) until I combined them with <code>Array.ConvertAll</code>:</p>\n\n<pre><code>int[] someArrayYouHaveAsInt;\ndouble[] copyOfArrayAsDouble = Array.ConvertAll<int, double>(\n someArrayYouHaveAsInt,\n new Converter<int,double>(Convert.ToDouble));\n</code></pre>\n\n<p>Which avoids the resource allocation issues that arise from defining an inline delegate/closure (and slightly more readable):</p>\n\n<pre><code>int[] someArrayYouHaveAsInt;\ndouble[] copyOfArrayAsDouble = Array.ConvertAll<int, double>(\n someArrayYouHaveAsInt,\n new Converter<int,double>(\n delegate(int i) { return (double)i; }\n ));\n</code></pre>\n"
},
{
"answer_id": 883586,
"author": "JoshL",
"author_id": 20625,
"author_profile": "https://Stackoverflow.com/users/20625",
"pm_score": 3,
"selected": false,
"text": "<p>Array initialization without specifying the array element type:</p>\n\n<pre><code>var pets = new[] { \"Cat\", \"Dog\", \"Bird\" };\n</code></pre>\n"
},
{
"answer_id": 899593,
"author": "Oorang",
"author_id": 102270,
"author_profile": "https://Stackoverflow.com/users/102270",
"pm_score": 2,
"selected": false,
"text": "<p>Well... <strong><em>Don't use it</em></strong>, but a lot of people don't know C# supports the evil goto:)</p>\n\n<pre><code>static void Example()\n{\n int i = 0;\ntop:\n Console.WriteLine(i.ToString());\n if (i == 0)\n {\n i++;\n goto top;\n }\n}\n</code></pre>\n"
},
{
"answer_id": 912833,
"author": "sourcenouveau",
"author_id": 111327,
"author_profile": "https://Stackoverflow.com/users/111327",
"pm_score": 3,
"selected": false,
"text": "<p>Having just learned the meaning of invariance, covariance and contravariance, I discovered the <a href=\"http://msdn.microsoft.com/en-us/library/dd469484(VS.100).aspx\" rel=\"nofollow noreferrer\">in</a> and <a href=\"http://msdn.microsoft.com/en-us/library/dd469487(VS.100).aspx\" rel=\"nofollow noreferrer\">out</a> generic modifiers that will be included in .NET 4.0. They seem obscure enough that most programmers would not know about them.</p>\n\n<p>There's an <a href=\"http://visualstudiomagazine.com/articles/2009/05/01/generic-covariance-and-contravariance-in-c-40.aspx\" rel=\"nofollow noreferrer\">article</a> at Visual Studio Magazine which discusses these keywords and how they will be used.</p>\n"
},
{
"answer_id": 938302,
"author": "Dave Van den Eynde",
"author_id": 455874,
"author_profile": "https://Stackoverflow.com/users/455874",
"pm_score": 4,
"selected": false,
"text": "<p><a href=\"http://msdn.microsoft.com/en-us/library/b3787ac0.aspx\" rel=\"nofollow noreferrer\">Atrribute Targets</a></p>\n\n<p>Everyone has seen one. Basically, when you see this:</p>\n\n<pre><code>[assembly: ComVisible(false)]\n</code></pre>\n\n<p>The \"assembly:\" portion of that attribute is the target. In this case, the attribute is applied to the assembly, but there are others:</p>\n\n<pre><code>[return: SomeAttr]\nint Method3() { return 0; } \n</code></pre>\n\n<p>In this sample the attribute is applied to the return value. </p>\n"
},
{
"answer_id": 945247,
"author": "Showtime",
"author_id": 114893,
"author_profile": "https://Stackoverflow.com/users/114893",
"pm_score": 1,
"selected": false,
"text": "<p>If you want to prevent the garbage collector from running the finalizer of an object, just use <code>GC.SuppressFinalize(object);</code>. In a similar vein, <code>GC.KeepAlive(object);</code> will prevent the garbage collector from collecting that object by referencing it. Not very commonly used, at least in my experience, but nice to know just in case.</p>\n"
},
{
"answer_id": 945300,
"author": "Lloyd Powell",
"author_id": 67258,
"author_profile": "https://Stackoverflow.com/users/67258",
"pm_score": 3,
"selected": false,
"text": "<p>Properties to display when viewing components Properties in design view:</p>\n\n<pre><code>private double _Zoom = 1;\n\n[Category(\"View\")]\n[Description(\"The Current Zoom Level\")]\npublic double Zoom\n{\nget { return _Zoom;}\nset { _Zoom = value;}\n}\n</code></pre>\n\n<p>Makes things a lot easier for other users of your component libraries.</p>\n"
},
{
"answer_id": 945458,
"author": "Jeffrey Hines",
"author_id": 107972,
"author_profile": "https://Stackoverflow.com/users/107972",
"pm_score": 2,
"selected": false,
"text": "<p>Relection is so powerfull when used carefully. I used it in an e-mail templating system. The template manager would be passed an object and the html templates would have embedded fields that referred to Properties that could be retrieved off the passed object using reflection. Worked out very nicely.</p>\n"
},
{
"answer_id": 949309,
"author": "RCIX",
"author_id": 117069,
"author_profile": "https://Stackoverflow.com/users/117069",
"pm_score": 2,
"selected": false,
"text": "<p>Definitely the Func<> types when used with statement lambdas in .NET 3.5. These allow customizable functions, and can be a great aid in offering user customizable objects without subclassing them or resorting to some limited system like keeping track of a variable that lists what button or key the user wants to monitor. Also, they can be called just like regular methods and can be assigned like variables. The only downside that I can think of is that you're limited to 5 arguments! Although by that point you might want to consider a different solution...\nEdit: Providing some examples.</p>\n\n<pre><code>...\npublic Func<InputHelper, float> _horizontalCameraMovement = (InputHelper input) => \n{\n return (input.LeftStickPosition.X * _moveRate) * _zoom;\n}\npublic Func<InputHelper, float> _verticalCameraMovement = (InputHelper input) => \n{\n return (-input.LeftStickPosition.Y * _moveRate) * _zoom;\n}\n...\npublic void Update(InputHelper input)\n{\n ...\n position += new Vector2(_horizontalCameraMovement(input), _verticalCameraMovement(input));\n ...\n}\n</code></pre>\n\n<p>In this example, you can write a function that does arbitrary calculation and returns a float that will determine the amount that the camera moves by. Not the best code but it gets the point across.</p>\n\n<pre><code>private int foo;\npublic int FooProperty {\n get\n {\n if (_onFooGotten() == true)\n return _foo;\n }\n set\n {\n if (onFooSet() == true)\n _foo = value;\n }\n}\n...\npublic Func<bool> _onFooGotten = () => \n{\n //do whatever...\n return true;\n}\npublic Func<bool> _onFooSet = () =>\n{\n //do whatever...\n return true;\n}\n</code></pre>\n\n<p>This isn't the best example (as I haven't really explored this use yet) but it shows an example of using a lambda function for a quick event raiser without the hassle of delegates.\nEdit: thought of another one. Nullables! The closest thing C# has to optional parameters.</p>\n"
},
{
"answer_id": 957443,
"author": "Andrew Lavers",
"author_id": 77501,
"author_profile": "https://Stackoverflow.com/users/77501",
"pm_score": 4,
"selected": false,
"text": "<p>FlagsAttribute, a small but <a href=\"http://msdn.microsoft.com/en-us/library/system.flagsattribute.aspx\" rel=\"nofollow noreferrer\">nice feature</a> when using enum to make a bitmasks:</p>\n\n<pre><code>[Flags]\npublic enum ConfigOptions\n{\n None = 0,\n A = 1 << 0,\n B = 1 << 1,\n Both = A | B\n}\n\nConsole.WriteLine( ConfigOptions.A.ToString() );\nConsole.WriteLine( ConfigOptions.Both.ToString() );\n// Will print:\n// A\n// A, B\n</code></pre>\n"
},
{
"answer_id": 958103,
"author": "Kevin Doyon",
"author_id": 78804,
"author_profile": "https://Stackoverflow.com/users/78804",
"pm_score": 2,
"selected": false,
"text": "<p>If you have the search textbox in your Visual Studio toolbar, you can type \">of Program.cs\" to open the file Program.cs</p>\n"
},
{
"answer_id": 961401,
"author": "Tolgahan Albayrak",
"author_id": 104468,
"author_profile": "https://Stackoverflow.com/users/104468",
"pm_score": 3,
"selected": false,
"text": "<p>The data type can be defined for an enumeration:</p>\n\n<pre><code>enum EnumName : [byte, char, int16, int32, int64, uint16, uint32, uint64]\n{\n A = 1,\n B = 2\n}\n</code></pre>\n"
},
{
"answer_id": 993118,
"author": "zebrabox",
"author_id": 122755,
"author_profile": "https://Stackoverflow.com/users/122755",
"pm_score": 2,
"selected": false,
"text": "<p>A few from me - make of them what you will.</p>\n\n<p>The attribute:</p>\n\n<pre><code>[assembly::InternalsVisibleTo(\"SomeAssembly\")]\n</code></pre>\n\n<p>Allows you to expose out the internal methods/properties or data from your assembly to another assembly called 'SomeAssembly'. All protected/private stuff remains hidden.</p>\n\n<hr>\n\n<p>Static constructors ( otherwise called 'Type Constructor' )</p>\n\n<pre><code>public MyClass\n{\n public static MyClass()\n {\n // type init goes here\n }\n ......\n} \n</code></pre>\n\n<hr>\n\n<p>The keyword <code>internal</code>. So useful in so many ways.</p>\n"
},
{
"answer_id": 993271,
"author": "ShuggyCoUk",
"author_id": 12748,
"author_profile": "https://Stackoverflow.com/users/12748",
"pm_score": 3,
"selected": false,
"text": "<h2>Advanced Debugging</h2>\n<h3>Display</h3>\n<p>The already mentioned attributes DebuggerDisplay and DebuggerBrowsable control the visibility of elements and the textual value displayed. Simply overriding ToString() will cause the debugger to use the output of that method.</p>\n<p>If you want more complex output you can use/create a <a href=\"http://msdn.microsoft.com/en-us/library/zayyhzts.aspx\" rel=\"nofollow noreferrer\">Debugger Visualizer</a>, several examples\nare available <a href=\"http://www.dotnetpowered.com/DebuggerVisualizers.aspx\" rel=\"nofollow noreferrer\">here</a>.</p>\n<h3>Son Of Strike</h3>\n<p>Microsoft provide a debugger extension known as <a href=\"http://msdn.microsoft.com/en-us/library/bb190764(vs.80).aspx\" rel=\"nofollow noreferrer\">SOS</a>. This is an extremely powerful (though often confusing) extension which is an excellent way to diagnose 'leaks', more accurately unwanted references to objects no longer required.</p>\n<h3>Symbol Server for framework source</h3>\n<p>Following these <a href=\"http://blogs.msdn.com/sburke/archive/2008/01/16/configuring-visual-studio-to-debug-net-framework-source-code.aspx\" rel=\"nofollow noreferrer\">instructions</a> will allow you to step through the source of some parts of the framework.</p>\n<h3>Changes in 2010</h3>\n<p>Several enhancements and new features exist in Visual Studio 2010:</p>\n<ul>\n<li><a href=\"http://www.danielmoth.com/Blog/2009/05/parallel-tasks-new-visual-studio-2010.html\" rel=\"nofollow noreferrer\">Debugging Parallel Tasks</a></li>\n<li><a href=\"http://www.danielmoth.com/Blog/2009/05/parallel-stacks-another-new-vs2010.html\" rel=\"nofollow noreferrer\">Parallel Stacks</a> allow viewing multiple threads call stacks at the same time.</li>\n<li><a href=\"http://channel9.msdn.com/posts/VisualStudio/Historical-Debugger-and-Test-Impact-Analysis-in-Visual-Studio-Team-System-2010/\" rel=\"nofollow noreferrer\">Historical Debugging</a> lets you see events and non-local variables back in time (so long as you enable the collection in advance). Potentially a significant change to how you debug things.</li>\n</ul>\n"
},
{
"answer_id": 1002816,
"author": "JoshL",
"author_id": 20625,
"author_profile": "https://Stackoverflow.com/users/20625",
"pm_score": 6,
"selected": false,
"text": "<p><strong>Use \"throw;\" instead of \"throw ex;\" to preserve stack trace</strong></p>\n\n<p>If re-throwing an exception without adding additional information, use \"throw\" instead of \"throw ex\". An empty \"throw\" statement in a catch block will emit specific IL that re-throws the exception while preserving the original stack trace. \"throw ex\" loses the stack trace to the original source of the exception.</p>\n"
},
{
"answer_id": 1003232,
"author": "epitka",
"author_id": 103682,
"author_profile": "https://Stackoverflow.com/users/103682",
"pm_score": 2,
"selected": false,
"text": "<p>Ability to create instance of the type based on the generic parameter like this</p>\n\n<p>new T();</p>\n"
},
{
"answer_id": 1010679,
"author": "statenjason",
"author_id": 88340,
"author_profile": "https://Stackoverflow.com/users/88340",
"pm_score": 3,
"selected": false,
"text": "<p>The Yield keyword is often overlooked when it has a lot of power. I blogged about it awhile ago and discussed benefits (differed processing) and happens under the hood of yield to help give a stronger understanding.</p>\n\n<p><a href=\"http://jxs.me/2010/05/14/using-yield-in-c/\" rel=\"nofollow noreferrer\">Using Yield in C#</a></p>\n"
},
{
"answer_id": 1016037,
"author": "SLaks",
"author_id": 34397,
"author_profile": "https://Stackoverflow.com/users/34397",
"pm_score": 3,
"selected": false,
"text": "<p>You can create delegates from extension methods as if they were regular methods, currying the <code>this</code> parameter. For example, </p>\n\n<pre><code>static class FunnyExtension {\n public static string Double(this string str) { return str + str; }\n public static int Double(this int num) { return num + num; }\n}\n\n\nFunc<string> aaMaker = \"a\".Double;\nFunc<string, string> doubler = FunnyExtension.Double;\n\nConsole.WriteLine(aaMaker()); //Prints \"aa\"\nConsole.WriteLine(doubler(\"b\")); //Prints \"bb\"\n</code></pre>\n\n<p>Note that this won't work on extension methods that extend \na value type; see <a href=\"https://stackoverflow.com/questions/1016033/extension-methods-defined-on-value-types-cannot-be-used-to-create-delegates-why\">this question</a>.</p>\n"
},
{
"answer_id": 1017882,
"author": "Titian Cernicova-Dragomir",
"author_id": 125734,
"author_profile": "https://Stackoverflow.com/users/125734",
"pm_score": 3,
"selected": false,
"text": "<p>Not sure if this one got mentioned yet but the ThreadStatic attribute is a realy useful one. This makes a static field static just for the current thread.</p>\n\n<pre><code>[ThreadStatic]\nprivate static int _ThreadStaticInteger;\n</code></pre>\n\n<p>You should not include an initializer because it only get executed once for the entire application, you're better off making the field nullable and checking if the value is null before you use it.</p>\n\n<p>And one more thing for ASP.NET applications threads are reused so if you modify the value it could end up being used for another page request.</p>\n\n<p>Still I have found this useful on several occasions. For example in creating a custom transaction class that:</p>\n\n<pre><code>using (DbTransaction tran = new DbTransaction())\n{\n DoQuery(\"...\");\n DoQuery(\"...\"); \n}\n</code></pre>\n\n<p>The DbTransaction constructor sets a ThreadStatic field to its self and resets it to null in the dispose method. DoQuery checks the static field and if != null uses the current transaction if not it defaults to something else. We avoid having to pass the transaction to each method plus it makes it easy to wrap other methods that were not originaly meant to be used with transaction inside a transaction ...</p>\n\n<p>Just one use :)</p>\n"
},
{
"answer_id": 1025614,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 3,
"selected": false,
"text": "<pre><code>HttpContext.Current.Server.Execute \n</code></pre>\n\n<p>is great for rendering HTML to strings for AJAX callbacks. You can use this with a component instead of piecing together HTML string snippets. I was able to cut page bloat down a couple of hundred KB with virtually no mess. I used it like this:</p>\n\n<pre><code>Page pageHolder = new Page();\nUserControl viewControl = (UserControl)pageHolder.LoadControl(@\"MyComponent.ascx\");\npageHolder.Controls.Add(viewControl);\nStringWriter output = new StringWriter();\nHttpContext.Current.Server.Execute(pageHolder, output, false);\nreturn output.ToString();\n</code></pre>\n"
},
{
"answer_id": 1026941,
"author": "Paul Ruane",
"author_id": 83264,
"author_profile": "https://Stackoverflow.com/users/83264",
"pm_score": 2,
"selected": false,
"text": "<p>Marketing events as non-serializable:</p>\n\n<pre><code>[field:NonSerializable]\npublic event SomeDelegate SomeEvent;\n</code></pre>\n"
},
{
"answer_id": 1049977,
"author": "Mike",
"author_id": 127831,
"author_profile": "https://Stackoverflow.com/users/127831",
"pm_score": 4,
"selected": false,
"text": "<p>You can add and remove delegates with less typing.</p>\n\n<p>Usual way:</p>\n\n<pre><code>handler += new EventHandler(func);\n</code></pre>\n\n<p>Less typing way:</p>\n\n<pre><code>handler += func;\n</code></pre>\n"
},
{
"answer_id": 1062170,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 2,
"selected": false,
"text": "<p>Generic constraints:</p>\n\n<pre><code> //Constructor constraint, T has a default empty constructor\nclass Node<K,T> where T : new() \n{\n}\n\n//Reference\\Value Type constraints\n//T is a struct\npublic class MyClass<T> where T : struct \n\n{...}\n\n//T is a reference type\npublic class MyClass<T> where T : class \n\n{...}\n\npublic class MyClass<T> where T : SomeBaseClass, ISomeInterface \n\n{...}\n</code></pre>\n"
},
{
"answer_id": 1062556,
"author": "Mark Seemann",
"author_id": 126014,
"author_profile": "https://Stackoverflow.com/users/126014",
"pm_score": 3,
"selected": false,
"text": "<p>The <code>Or</code> assignment operator is quite nice. You can write this:</p>\n\n<pre><code>x |= y\n</code></pre>\n\n<p>instead of this:</p>\n\n<pre><code>x = x | y\n</code></pre>\n\n<p>This is often practical if you have to a variable or property (<code>x</code> in the example) that starts out as <code>false</code> but you want to change it to the value of some other boolean variable/property <em>only when</em> that other value is <code>true</code>.</p>\n"
},
{
"answer_id": 1071983,
"author": "Wim Coenen",
"author_id": 52626,
"author_profile": "https://Stackoverflow.com/users/52626",
"pm_score": 4,
"selected": false,
"text": "<p>Extension methods can be called on <code>null</code>; this will not cause a <code>NullReferenceException</code> to be thrown.</p>\n\n<p>Example application: you can define an alternative for <code>ToString()</code> called <code>ToStringOrEmpty()</code> which will return the empty string when called on <code>null</code>.</p>\n"
},
{
"answer_id": 1114418,
"author": "Yvo",
"author_id": 136819,
"author_profile": "https://Stackoverflow.com/users/136819",
"pm_score": 5,
"selected": false,
"text": "<p>I've read through all seven pages, and I'm missing these:</p>\n\n<p><strong>String.Join</strong></p>\n\n<p>I've seen a lot of for-loops to convert a list of items to a string with separators. It's always a pain to make sure you doin't start with a separator and don't end with a separator. A built-in method makes this easier:</p>\n\n<pre><code>String.Join(\",\", new String[] { \"a\", \"b\", \"c\"});\n</code></pre>\n\n<p><strong>TODO in comment</strong></p>\n\n<p>Not really a C# feature, more of a Visual Studio feature. When you start your comment with TODO, it's added to your Visual Studio Task List (View -> Task List. Comments)</p>\n\n<pre><code>// TODO: Implement this!\nthrow new NotImplementedException();\n</code></pre>\n\n<p><strong>Extension methods meets Generics</strong></p>\n\n<p>You can combine extension methods with Generics, when you think of the tip earlier in this topic, you can add extensions to specific interfaces</p>\n\n<pre><code>public static void Process<T>(this T item) where T:ITest,ITest2 {}\n</code></pre>\n\n<p><strong>Enumerable.Range</strong></p>\n\n<p>Just want a list of integers?</p>\n\n<pre><code>Enumerable.Range(0, 15)\n</code></pre>\n\n<p>I'll try to think of some more...</p>\n"
},
{
"answer_id": 1118859,
"author": "softveda",
"author_id": 11711,
"author_profile": "https://Stackoverflow.com/users/11711",
"pm_score": 3,
"selected": false,
"text": "<p>Pointers in C#. </p>\n\n<p>They can be used to do in-place string manipulation. This is an unsafe feature so the unsafe keyword is used to mark the region of unsafe code. Also note how the fixed keyword is used to indicate that the memory pointed to is pinned and cannot be moved by the GC. This is essential a pointers point to memory addresses and the GC can move the memory to different address otherwise resulting in an invalid pointer.</p>\n\n<pre><code> string str = \"some string\";\n Console.WriteLine(str);\n unsafe\n {\n fixed(char *s = str)\n {\n char *c = s;\n while(*c != '\\0')\n {\n *c = Char.ToUpper(*c++); \n }\n }\n }\n Console.WriteLine(str);\n</code></pre>\n\n<p>I wouldn't ever do it but just for the sake of this question to demonstrate this feature.</p>\n"
},
{
"answer_id": 1135505,
"author": "David.Chu.ca",
"author_id": 62776,
"author_profile": "https://Stackoverflow.com/users/62776",
"pm_score": 3,
"selected": false,
"text": "<p>I like to use the <em>using</em> directive to rename some classes for easy reading like this:</p>\n\n<pre><code>// defines a descriptive name for a complexed data type\nusing MyDomainClassList = System.Collections.Generic.List<\n MyProjectNameSpace.MyDomainClass>;\n\n....\n\n\nMyDomainClassList myList = new MyDomainClassList();\n/* instead of \nList<MyDomainClass> myList = new List<MyDomainClass>();\n*/\n</code></pre>\n\n<p>This is also very handy for code maintenance. If you need to change the class name, there is only one place you need to change. Another example:</p>\n\n<pre><code>using FloatValue = float; // you only need to change it once to decimal, double...\n\n....\nFloatValue val1;\n...\n</code></pre>\n"
},
{
"answer_id": 1143637,
"author": "RandomNickName42",
"author_id": 67819,
"author_profile": "https://Stackoverflow.com/users/67819",
"pm_score": 1,
"selected": false,
"text": "<p><a href=\"http://code.msdn.microsoft.com/ExceptionFilterInjct\" rel=\"nofollow noreferrer\">Exception Filters</a>. So \"hidden\" you <em>can't</em> even use them (at least from C#) without a post-compilation patch ;) </p>\n"
},
{
"answer_id": 1161934,
"author": "Dan Diplo",
"author_id": 140392,
"author_profile": "https://Stackoverflow.com/users/140392",
"pm_score": 2,
"selected": false,
"text": "<p>How about <a href=\"http://msdn.microsoft.com/en-us/library/bb397951.aspx\" rel=\"nofollow noreferrer\">Expression Trees</a>? They are the heart of LINQ and allow for defered execution:</p>\n\n<p>Taken from <a href=\"http://www.davidhayden.com/blog/dave/archive/2006/12/18/ExpressionTrees.aspx\" rel=\"nofollow noreferrer\">David Hayden's blog</a>:</p>\n\n<p>In C# 3.0, you can define a delegate as follows using a lambda expression:</p>\n\n<pre><code>Func<int,int> f = x => x + 1;\n</code></pre>\n\n<p>This delegate is compiled into executable code in your application and can be called as such:</p>\n\n<pre><code>var three = f(2); // 2 + 1\n</code></pre>\n\n<p>The code works as you would expect. Nothing fancy here.</p>\n\n<p><strong>Expression Trees</strong></p>\n\n<p>When you define the delegate as an Expression Tree by using System.Query.Expression:</p>\n\n<pre><code>Expression<Func<int,int>> expression = x => x + 1;\n</code></pre>\n\n<p>The delegate is no longer compiled into executable code, but compiled as data that can be converted and compiled into the original delegate.</p>\n\n<p>To actually use the delegate represented as an Expression Tree in your application, you would have to compile and invoke it in your application:</p>\n\n<pre><code>var originalDelegate = expression.Compile();\n\nvar three = originalDelegate.Invoke(2);\n</code></pre>\n"
},
{
"answer_id": 1162648,
"author": "Martin Konicek",
"author_id": 90998,
"author_profile": "https://Stackoverflow.com/users/90998",
"pm_score": 3,
"selected": false,
"text": "<pre><code>[field: NonSerialized]\npublic event EventHandler Event;\n</code></pre>\n\n<p>This way, the event listener is not serialized.</p>\n\n<p>Just [NonSerialized] does not work, because NonSerializedAttribute can only be applied to fields.</p>\n"
},
{
"answer_id": 1163889,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 3,
"selected": false,
"text": "<p>I especially like the nullable DateTime. So if you have some cases where a Date is given and other cases where no Date is given I think this is best to use and IMHO easier to understand as using <code>DateTime.MinValue</code> or anything else...</p>\n\n<pre><code>DateTime? myDate = null;\n\nif (myDate.HasValue)\n{\n //doSomething\n}\nelse\n{\n //soSomethingElse\n}\n</code></pre>\n"
},
{
"answer_id": 1173935,
"author": "Brad",
"author_id": 70130,
"author_profile": "https://Stackoverflow.com/users/70130",
"pm_score": 2,
"selected": false,
"text": "<p>If you are trying to create a comma delimited string from a list of items:</p>\n\n<pre><code>string[] itemList = { \"Example 1\", \"Example 2\", \"Example 3\" };\nCommaDelimitedStringCollection commaStr = new CommaDelimitedStringCollection();\ncommaStr.AddRange(itemList);\n//outputs Example 1,Example 2,Example 3\n</code></pre>\n\n<p>Look <a href=\"http://blog.crowe.co.nz/archive/2007/08/25/c---How-to-create-a-comma-seperated-string-from.aspx\" rel=\"nofollow noreferrer\">here</a> for another example.</p>\n"
},
{
"answer_id": 1185988,
"author": "Paul van Brenk",
"author_id": 1837197,
"author_profile": "https://Stackoverflow.com/users/1837197",
"pm_score": 3,
"selected": false,
"text": "<p>Zero parameter Lambdas</p>\n\n<pre><code>()=>Console.ReadLine()\n</code></pre>\n"
},
{
"answer_id": 1204390,
"author": "ccook",
"author_id": 51275,
"author_profile": "https://Stackoverflow.com/users/51275",
"pm_score": 3,
"selected": false,
"text": "<p>I didn't see this:</p>\n\n<pre><code>for (;;);\n</code></pre>\n\n<p>The same as</p>\n\n<pre><code>while (true) ;\n</code></pre>\n"
},
{
"answer_id": 1204441,
"author": "Brian Surowiec",
"author_id": 39605,
"author_profile": "https://Stackoverflow.com/users/39605",
"pm_score": 4,
"selected": false,
"text": "<p>I'm becoming a big fan of extension methods since they can add much wanted functionality to existing code or code you can't edit. One of my favorites I add in to everything I do now is for string.IsNullOrEmpty()</p>\n\n<pre><code>public static class Strings\n{\n public static bool IsNullOrEmpty(this string value)\n {\n return string.IsNullOrEmpty(value);\n }\n}\n</code></pre>\n\n<p>This lets you shorten your code a bit like this</p>\n\n<pre><code>var input = Console.ReadLine();\nif (input.IsNullOrEmpty())\n{\n Console.WriteLine(\"try again\");\n}\n</code></pre>\n"
},
{
"answer_id": 1231428,
"author": "Christian Hubmann",
"author_id": 62910,
"author_profile": "https://Stackoverflow.com/users/62910",
"pm_score": 6,
"selected": false,
"text": "<p><a href=\"http://msdn.microsoft.com/en-us/library/0c899ak8.aspx#SectionSeparator\" rel=\"noreferrer\">Conditional string.Format</a>:</p>\n\n<p>Applies different formatting to a number depending on whether the number is positive, negative, or zero.</p>\n\n<pre><code>string s = string.Format(\"{0:positive;negative;zero}\", i);\n</code></pre>\n\n<p>e.g.</p>\n\n<pre><code>string format = \"000;-#;(0)\";\n\nstring pos = 1.ToString(format); // 001\nstring neg = (-1).ToString(format); // -1\nstring zer = 0.ToString(format); // (0)\n</code></pre>\n"
},
{
"answer_id": 1234502,
"author": "John Leidegren",
"author_id": 58961,
"author_profile": "https://Stackoverflow.com/users/58961",
"pm_score": 2,
"selected": false,
"text": "<p>A lot of this is explained already, in <a href=\"http://www.ecma-international.org/publications/standards/Ecma-334.htm\" rel=\"nofollow noreferrer\">the standard</a>. It's a good read for any beginner as well as expert, it's a lot to read, but it's the official standard, and it's filled with juicy details.</p>\n\n<p>Once you fully understand C#, it's time to take this further to understand the fundamentals of the <a href=\"http://www.ecma-international.org/publications/standards/Ecma-335.htm\" rel=\"nofollow noreferrer\">Common Language Infrastructure</a>. The architecture and underpinnings of C#.</p>\n\n<p>I've met a variety of programmers that don't know the difference between an object and a ValueType except the adherent limitations thereof. </p>\n\n<p>Familiarize yourself with these two documents and you'll never become that person.</p>\n"
},
{
"answer_id": 1234603,
"author": "Ray",
"author_id": 149650,
"author_profile": "https://Stackoverflow.com/users/149650",
"pm_score": 1,
"selected": false,
"text": "<p>When you need to (a)synchronously communicate between objects about occurance of an event there is special purpose interface called <strong>ISynchronizeInvoke</strong>.</p>\n\n<p>Quoting MSDN article (<a href=\"http://msdn.microsoft.com/en-us/library/system.componentmodel.isynchronizeinvoke.aspx\" rel=\"nofollow noreferrer\">link</a>): </p>\n\n<blockquote>\n <p>Objects that implement this interface can receive notification that an event has occurred, and they can respond to queries about the event. In this way, clients can ensure that one request has been processed before they submit a subsequent request that depends on completion of the first.</p>\n</blockquote>\n\n<p>Here is a generic wrapper:</p>\n\n<pre><code>protected void OnEvent<T>(EventHandler<T> eventHandler, T args) where T : EventArgs\n{\n if (eventHandler == null) return;\n\n foreach (EventHandler<T> singleEvent in eventHandler.GetInvocationList())\n {\n if (singleEvent.Target != null && singleEvent.Target is ISynchronizeInvoke)\n {\n var target = (ISynchronizeInvoke)singleEvent.Target;\n\n if (target.InvokeRequired) {\n target.BeginInvoke(singleEvent, new object[] { this, args });\n continue;\n }\n }\n singleEvent(this, args);\n }\n}\n</code></pre>\n\n<p>and here is an example usage:</p>\n\n<pre><code>public event EventHandler<ProgressEventArgs> ProgressChanged;\n\nprivate void OnProgressChanged(int processed, int total)\n{\n OnEvent(ProgressChanged, new ProgressEventArgs(processed, total));\n}\n</code></pre>\n"
},
{
"answer_id": 1242225,
"author": "JoshL",
"author_id": 20625,
"author_profile": "https://Stackoverflow.com/users/20625",
"pm_score": 3,
"selected": false,
"text": "<p>Expression to initialize a Dictionary in C# 3.5:</p>\n\n<p><code>new Dictionary<string, Int64>() {{\"Testing\", 123}, {\"Test\", 125}};</code></p>\n"
},
{
"answer_id": 1243242,
"author": "ata",
"author_id": 150830,
"author_profile": "https://Stackoverflow.com/users/150830",
"pm_score": 3,
"selected": false,
"text": "<p>I don't think someone has mentioned that appending ? after a value type name will make it nullable.</p>\n\n<p>You can do: </p>\n\n<pre><code>DateTime? date = null;\n</code></pre>\n\n<p>DateTime is a structure.</p>\n"
},
{
"answer_id": 1243265,
"author": "Jason Williams",
"author_id": 97385,
"author_profile": "https://Stackoverflow.com/users/97385",
"pm_score": 5,
"selected": false,
"text": "<p>Programmers moving from C/C++ may miss this one:</p>\n\n<p>In C#, % (modulus operator) works on floats!</p>\n"
},
{
"answer_id": 1247323,
"author": "paracycle",
"author_id": 98634,
"author_profile": "https://Stackoverflow.com/users/98634",
"pm_score": 2,
"selected": false,
"text": "<p>Generics and the <a href=\"http://en.wikipedia.org/wiki/Curiously_recurring_template_pattern\" rel=\"nofollow noreferrer\">Curiously-Recurring Template Pattern</a> really help with some static method/property declarations.</p>\n\n<p>Suppose you are building a class hierarchy:</p>\n\n<pre><code>class Base\n{\n}\n\nclass Foo: Base\n{\n}\n\nclass Bar: Base\n{\n}\n</code></pre>\n\n<p>Now, you want to declare static methods on your types that should take parameters (or return values) of the same type or static properties of the same type. For example, you want:</p>\n\n<pre><code>class Base\n{\n public static Base Get()\n {\n // Return a suitable Base.\n }\n}\n\nclass Foo: Base\n{\n public static Foo Get()\n {\n // Return a suitable Foo.\n }\n}\n\nclass Bar: Base\n{\n public static Bar Get()\n {\n // Return a suitable Bar.\n }\n}\n</code></pre>\n\n<p>If these static methods basically all do the same thing, then you have lots of duplicated code on your hands. One solution would be to drop type safety on the return values and to always return type <code>Base</code>. However, if you want type safety, then the solution is to declare the <code>Base</code> as:</p>\n\n<pre><code>class Base<T> where T: Base<T>\n{\n public static T Get<T>()\n {\n // Return a suitable T.\n }\n}\n</code></pre>\n\n<p>and you <code>Foo</code> and <code>Bar</code> as:</p>\n\n<pre><code>class Foo: Base<Foo>\n{\n}\n\nclass Bar: Base<Bar>\n{\n}\n</code></pre>\n\n<p>This way, they will automatically get their <strong>copies</strong> of the static methods.</p>\n\n<p>This also works wonders to encapsulate the <strong>Singleton</strong> pattern in a base class (I know the code below is not thread-safe, it just to demonstrate a point):</p>\n\n<pre><code>public class Singleton<T> where T: Singleton<T>, new()\n{\n public static T Instance { get; private set; }\n\n static Singleton<T>()\n {\n Instance = new T();\n }\n}\n</code></pre>\n\n<p>I realize that this forces you to have a public parameterless constructor on your singleton subclass but there is no way to avoid that at compile time without a <code>where T: protected new()</code> construct; however one can use <a href=\"http://www.codeproject.com/KB/architecture/GenericSingletonPattern.aspx\" rel=\"nofollow noreferrer\">reflection</a> to invoke the protected/private parameterless constructor of the sub-class at runtime to achieve that.</p>\n"
},
{
"answer_id": 1277525,
"author": "Ali Ersöz",
"author_id": 4215,
"author_profile": "https://Stackoverflow.com/users/4215",
"pm_score": 3,
"selected": false,
"text": "<p><a href=\"http://blogs.msdn.com/ericlippert/archive/2009/08/13/four-switch-oddities.aspx\" rel=\"nofollow noreferrer\">Four switch oddities</a> by Eric Lippert</p>\n"
},
{
"answer_id": 1280160,
"author": "Maslow",
"author_id": 57883,
"author_profile": "https://Stackoverflow.com/users/57883",
"pm_score": 2,
"selected": false,
"text": "<p>Keeps DataGridView from showing the property:</p>\n\n<pre><code>[System.ComponentModel.Browsable(false)]\npublic String LastActionID{get; private set;}\n</code></pre>\n\n<p>Lets you set a friendly display for components (like a DataGrid or DataGridView):</p>\n\n<pre><code>[System.ComponentModel.DisplayName(\"Last Action\")]\npublic String LastAction{get; private set;}\n</code></pre>\n\n<p>For your backing variables, if you don't want anything accessing them directly this makes it tougher:</p>\n\n<pre><code>[System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)]\n private DataController p_dataSources;\n</code></pre>\n"
},
{
"answer_id": 1311431,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 3,
"selected": false,
"text": "<p>The ability to use LINQ to do inline work on collections that used to take iteration and conditionals can be incredibly valuable. It's worth learning how all the LINQ extension methods can help make your code much more compact and maintainable.</p>\n"
},
{
"answer_id": 1318297,
"author": "mezoid",
"author_id": 39532,
"author_profile": "https://Stackoverflow.com/users/39532",
"pm_score": 3,
"selected": false,
"text": "<p>One that I just learned recently is that you can still call <a href=\"https://stackoverflow.com/questions/1242883/is-there-a-better-way-to-write-this-line-of-c-code-in-c3-0\">methods on a nullable value</a>....</p>\n\n<p>It turns out what when you have a nullable value:</p>\n\n<pre><code>decimal? MyValue = null;\n</code></pre>\n\n<p>where you might think you would have to write:</p>\n\n<pre><code>MyValue == null ? null : MyValue .ToString()\n</code></pre>\n\n<p>you can instead write:</p>\n\n<pre><code>MyValue.ToString()\n</code></pre>\n\n<p>I've been aware that I could call MyValue.HasValue and MyValue.Value...but it didn't fully click that I could call ToString().</p>\n"
},
{
"answer_id": 1371317,
"author": "manji",
"author_id": 166538,
"author_profile": "https://Stackoverflow.com/users/166538",
"pm_score": 3,
"selected": false,
"text": "<p>This will not compile:</p>\n\n<pre><code>namespace ns\n{\n class Class1\n {\n Nullable<int> a;\n }\n}\n</code></pre>\n\n<p><em>The type or namespace name 'Nullable' could not be found (are you missing a using directive or an assembly reference?)</em> <-- missing '<code>using System;</code>'</p>\n\n<p>But</p>\n\n<pre><code>namespace ns\n{\n class Class1\n {\n int? a;\n }\n}\n</code></pre>\n\n<p>will compile! (.NET 2.0).</p>\n"
},
{
"answer_id": 1399045,
"author": "jpierson",
"author_id": 83658,
"author_profile": "https://Stackoverflow.com/users/83658",
"pm_score": 3,
"selected": false,
"text": "<p>Nested classes can access private members of a outer class.</p>\n\n<pre><code>public class Outer\n{\n private int Value { get; set; }\n\n public class Inner\n {\n protected void ModifyOuterMember(Outer outer, int value)\n {\n outer.Value = value;\n }\n }\n}\n</code></pre>\n\n<p>And now together with the above feature you can also inherit from nested classes as if they were top level classes as shown below.</p>\n\n<pre><code>public class Cheater : Outer.Inner\n{\n protected void MakeValue5(Outer outer)\n {\n ModifyOuterMember(outer, 5);\n }\n}\n</code></pre>\n\n<p>These features allow for some interesting possibilities as far as providing access to particular members via somewhat hidden classes.</p>\n"
},
{
"answer_id": 1399130,
"author": "cllpse",
"author_id": 20946,
"author_profile": "https://Stackoverflow.com/users/20946",
"pm_score": 5,
"selected": false,
"text": "<p><strong>JavaScript-like anonymous inline-functions</strong></p>\n\n<p>Return a String:</p>\n\n<pre><code>var s = new Func<String>(() =>\n{\n return \"Hello World!\";\n})();\n</code></pre>\n\n<p>Return a more complex Object:</p>\n\n<pre><code>var d = new Func<Dictionary<Int32, String>>(() =>\n{\n return new Dictionary<Int32, String>\n {\n { 0, \"Foo\" },\n { 1, \"Bar\" },\n { 2, \"...\" }\n };\n})();\n</code></pre>\n\n<p>A real-world use-case:</p>\n\n<pre><code>var tr = new TableRow();\n\ntr.Cells.AddRange\n(\n new[]\n {\n new TableCell { Text = \"\" },\n new TableCell { Text = \"\" },\n new TableCell { Text = \"\" },\n\n new TableCell\n {\n Text = new Func<String>(() =>\n {\n return @\"Result of a chunk of logic, without having to define\n the logic outside of the TableCell constructor\";\n })()\n },\n\n new TableCell { Text = \"\" },\n new TableCell { Text = \"\" }\n }\n);\n</code></pre>\n\n<p><em>Note: You cannot re-use variable names inside the inline-function's scope.</em></p>\n\n<p><br /></p>\n\n<p><strong>Alternative syntax</strong></p>\n\n<pre><code>// The one-liner\nFunc<Int32, Int32, String> Add = (a, b) => Convert.ToString(a + b);\n\n// Multiple lines\nFunc<Int32, Int32, String> Add = (a, b) =>\n{\n var i = a + b;\n\n return i.ToString();\n};\n\n// Without parameters\nFunc<String> Foo = () => \"\";\n\n// Without parameters, multiple lines\nFunc<String> Foo = () =>\n{\n return \"\";\n};\n</code></pre>\n\n<p>Shorten a string and add horizontal ellipsis...</p>\n\n<pre><code>Func<String, String> Shorten = s => s.Length > 100 ? s.Substring(0, 100) + \"&hellip;\" : s;\n</code></pre>\n"
},
{
"answer_id": 1404712,
"author": "madcyree",
"author_id": 167809,
"author_profile": "https://Stackoverflow.com/users/167809",
"pm_score": 2,
"selected": false,
"text": "<p>At first - <a href=\"http://msdn.microsoft.com/en-us/library/d8eyd8zc.aspx\" rel=\"nofollow noreferrer\">DebuggerTypeProxy</a>.</p>\n\n<pre><code>[DebuggerTypeProxy(typeof(HashtableDebugView))]\nclass MyHashtable : Hashtable\n{\n private const string TestString = \n \"This should not appear in the debug window.\";\n\n internal class HashtableDebugView\n {\n private Hashtable hashtable;\n public const string TestStringProxy = \n \"This should appear in the debug window.\";\n\n // The constructor for the type proxy class must have a \n // constructor that takes the target type as a parameter.\n public HashtableDebugView(Hashtable hashtable)\n {\n this.hashtable = hashtable;\n }\n }\n}\n</code></pre>\n\n<p>At second:</p>\n\n<p><a href=\"http://msdn.microsoft.com/en-us/library/ms171819.aspx\" rel=\"nofollow noreferrer\">ICustomTypeDescriptor</a></p>\n"
},
{
"answer_id": 1408887,
"author": "Todd Richardson",
"author_id": 93964,
"author_profile": "https://Stackoverflow.com/users/93964",
"pm_score": 3,
"selected": false,
"text": "<p>I apologize if this one has been mentioned, but I use this a lot. </p>\n\n<p>An add-in for Visual Studio was developed by Alex Papadimoulis. It's used for pasting regular text as string, string builder, comment or region.</p>\n\n<p><a href=\"http://weblogs.asp.net/alex_papadimoulis/archive/2004/05/25/Smart-Paster-1.1-Add-In---StringBuilder-and-Better-C_2300_-Handling.aspx\" rel=\"nofollow noreferrer\">http://weblogs.asp.net/alex_papadimoulis/archive/2004/05/25/Smart-Paster-1.1-Add-In---StringBuilder-and-Better-C_2300_-Handling.aspx</a></p>\n\n<p>In this plugin (I also don't know if this has been mentioned) I noticed that strings are pasted with the string literal prefix:</p>\n\n<pre><code>@\n</code></pre>\n\n<p>I knew about these, but I didn't know about using a double quote within a literal to escape the quote. </p>\n\n<p>For example</p>\n\n<pre><code>string s = \"A line of text\" + Environment.NewLine + \"Another with a \\\"quote\\\"!!\";\n</code></pre>\n\n<p>can be expressed as</p>\n\n<pre><code>string s = @\"A line of text \nAnother with a \"\"quote\"\"!!\";\n</code></pre>\n"
},
{
"answer_id": 1415909,
"author": "codymanix",
"author_id": 44952,
"author_profile": "https://Stackoverflow.com/users/44952",
"pm_score": 4,
"selected": false,
"text": "<p>When defining custom attributes you can use them with [MyAttAttribute] or with [MyAtt].\nWhen classes exist for both writings, then a compilation error occures.</p>\n\n<p>The @ special character can be used to distinguish between them:</p>\n\n<pre><code>[AttributeUsage(AttributeTargets.All)]\npublic class X: Attribute\n{}\n\n[AttributeUsage(AttributeTargets.All)]\npublic class XAttribute: Attribute\n{}\n\n[X] // Error: ambiguity\nclass Class1 {}\n\n[XAttribute] // Refers to XAttribute\nclass Class2 {}\n\n[@X] // Refers to X\nclass Class3 {}\n\n[@XAttribute] // Refers to XAttribute\nclass Class4 {}\n</code></pre>\n"
},
{
"answer_id": 1415952,
"author": "codymanix",
"author_id": 44952,
"author_profile": "https://Stackoverflow.com/users/44952",
"pm_score": 5,
"selected": false,
"text": "<p>You can \"use\" multiple objects in one using statement.</p>\n\n<pre><code>using (Font f1= new Font(\"Arial\", 10.0f), f2 = new Font(\"Arial\", 10.0f))\n{\n // Use f1 and f2.\n}\n</code></pre>\n\n<p>Note that there is already an answer stating that you can do this:</p>\n\n<pre><code>using (Font f1= new Font(\"Arial\", 10.0f))\nusing (Font f2 = new Font(\"Arial\", 10.0f))\n{ }\n</code></pre>\n\n<p>Which is different from mine.</p>\n"
},
{
"answer_id": 1416182,
"author": "Oliver",
"author_id": 67494,
"author_profile": "https://Stackoverflow.com/users/67494",
"pm_score": 2,
"selected": false,
"text": "<p>Not sure Microsoft would like this question, especially with so many responses. \nI'm sure I once heard a Microsoft head say:</p>\n\n<blockquote>\n <p>a hidden feature is a wasted feature</p>\n</blockquote>\n\n<p>... or something to that effect.</p>\n"
},
{
"answer_id": 1435045,
"author": "Keith Adler",
"author_id": 135952,
"author_profile": "https://Stackoverflow.com/users/135952",
"pm_score": 4,
"selected": false,
"text": "<p>You can limit the life and thus scope of variables by using <code>{ }</code> brackets.</p>\n\n<pre><code>{\n string test2 = \"3\";\n Console.Write(test2);\n}\n\nConsole.Write(test2); //compile error\n</code></pre>\n\n<p><code>test2</code> only lives within the brackets.</p>\n"
},
{
"answer_id": 1464831,
"author": "rikoe",
"author_id": 177117,
"author_profile": "https://Stackoverflow.com/users/177117",
"pm_score": 4,
"selected": false,
"text": "<p>Apologies for posting so late, I am new to Stack Overflow so missed the earlier opportunity.</p>\n\n<p>I find that <code>EventHandler<T></code> is a great feature of the framework that is underutilised. </p>\n\n<p>Most C# developers I come across still define a custom event handler delegate when they are defining custom events, which is simply not necessary anymore.</p>\n\n<p>Instead of:</p>\n\n<pre><code>public delegate void MyCustomEventHandler(object sender, MyCustomEventArgs e);\n\npublic class MyCustomEventClass \n{\n public event MyCustomEventHandler MyCustomEvent;\n}\n</code></pre>\n\n<p>you can go:</p>\n\n<pre><code>public class MyCustomEventClass \n{\n public event EventHandler<MyCustomEventArgs> MyCustomEvent;\n}\n</code></pre>\n\n<p>which is a lot more concise, plus you don't get into the dilemma of whether to put the delegate in the .cs file for the class that contains the event, or the EventArgs derived class.</p>\n"
},
{
"answer_id": 1484202,
"author": "Mike Valenty",
"author_id": 124839,
"author_profile": "https://Stackoverflow.com/users/124839",
"pm_score": 3,
"selected": false,
"text": "<p>Open generics are another handy feature especially when using <a href=\"http://en.wikipedia.org/wiki/Inversion_of_control\" rel=\"nofollow noreferrer\">Inversion of Control</a>:</p>\n\n<pre><code>container.RegisterType(typeof(IRepository<>), typeof(NHibernateRepository<>));\n</code></pre>\n"
},
{
"answer_id": 1593594,
"author": "Himadri",
"author_id": 173655,
"author_profile": "https://Stackoverflow.com/users/173655",
"pm_score": 2,
"selected": false,
"text": "<p>Use of @ before a string that contains escape char.\nBasically when a physical path is used to assign in a string variable everybody uses '\\' where escape character is present in a string.</p>\n\n<p>e.g.\nstring strPath=\"D:\\websites\\web1\\images\\\";</p>\n\n<p>But escape characters can be ignored using @ before the string value. </p>\n\n<p>e.g. \nstring strPath=@\"D:\\websites\\web1\\images\\\";</p>\n"
},
{
"answer_id": 1625860,
"author": "Florian Doyon",
"author_id": 91585,
"author_profile": "https://Stackoverflow.com/users/91585",
"pm_score": 2,
"selected": false,
"text": "<p>I love abusing the fact that static templated classes don't share their static members.</p>\n\n<p>Here's a threadsafe (at creation time) and cheap substitute to any <code>Dictionary<Type,...></code> when the <code>Type</code> instance is known at compile-time.</p>\n\n<pre><code>public static class MyCachedData<T>{\n static readonly CachedData Value;\n static MyCachedData(){\n Value=// Heavy computation, such as baking IL code or doing lots of reflection on a type\n }\n}\n</code></pre>\n\n<p>Cheers,\nFlorian</p>\n"
},
{
"answer_id": 1647219,
"author": "Lyubomyr Shaydariv",
"author_id": 166589,
"author_profile": "https://Stackoverflow.com/users/166589",
"pm_score": 2,
"selected": false,
"text": "<p>The following one is not hidden, but it's quite implicit. I don't know whether samples like the following one have been published here, and I can't see are there any benefits (probably there are none), but I'll try to show a \"weird\" code. The following sample simulates <code>for</code> statement via functors in C# (delegates / anonymous delegates [lambdas]) and closures. Other flow statements like <code>if</code>, <code>if/else</code>, <code>while</code> and <code>do/whle</code> are simulated as well, but I'm not sure for <code>switch</code> (perhaps, I'm too lazy :)). I've compacted the sample source code a little to make it more clear.</p>\n\n<pre><code>private static readonly Action EmptyAction = () => { };\nprivate static readonly Func<bool> EmptyCondition = () => { return true; };\n\nprivate sealed class BreakStatementException : Exception { }\nprivate sealed class ContinueStatementException : Exception { }\nprivate static void Break() { throw new BreakStatementException(); }\nprivate static void Continue() { throw new ContinueStatementException(); }\n\nprivate static void For(Action init, Func<bool> condition, Action postBlock, Action statement) {\n init = init ?? EmptyAction;\n condition = condition ?? EmptyCondition;\n postBlock = postBlock ?? EmptyAction;\n statement = statement ?? EmptyAction;\n for ( init(); condition(); postBlock() ) {\n try {\n statement();\n } catch ( BreakStatementException ) {\n break;\n } catch ( ContinueStatementException ) {\n continue;\n }\n }\n}\n\nprivate static void Main() {\n int i = 0; // avoiding error \"Use of unassigned local variable 'i'\" if not using `for` init block\n For(() => i = 0, () => i < 10, () => i++,\n () => {\n if ( i == 5 )\n Continue();\n Console.WriteLine(i);\n }\n );\n}\n</code></pre>\n\n<p>If I'm not wrong, this approach is pretty relative to the functional programming practice. Am I right?</p>\n"
},
{
"answer_id": 1677556,
"author": "plaureano",
"author_id": 46265,
"author_profile": "https://Stackoverflow.com/users/46265",
"pm_score": 3,
"selected": false,
"text": "<p>C# allows you to add property setter methods to concrete types that implement readonly interface properties even though the interface declaration itself has no property setter. For example:</p>\n\n<pre><code>public interface IReadOnlyFoo\n{\n object SomeReadOnlyProperty { get; }\n}\n</code></pre>\n\n<p>The concrete class looks like this:</p>\n\n<pre><code>internal class Foo : IReadOnlyFoo\n{\n public object SomeReadOnlyProperty { get; internal set; }\n}\n</code></pre>\n\n<p>What's interesting about this is that the Foo class is immutable if you cast it to the IReadOnlyFoo interface:</p>\n\n<pre><code>// Create a Foo instance\nFoo foo = new Foo();\n\n// This statement is legal\nfoo.SomeReadOnlyProperty = 12345;\n\n// Make Foo read only\nIReadOnlyFoo readOnlyFoo = foo;\n\n// This statement won't compile\nreadOnlyFoo.SomeReadOnlyProperty = 54321;\n</code></pre>\n"
},
{
"answer_id": 1699477,
"author": "Himadri",
"author_id": 173655,
"author_profile": "https://Stackoverflow.com/users/173655",
"pm_score": 6,
"selected": false,
"text": "<p>I just wanted to copy that code without the comments. So, the trick is to simply press the Alt button, and then highlight the rectangle you like.(e. g. below).</p>\n\n<pre><code>protected void GridView1_RowCommand(object sender, GridViewCommandEventArgs e)\n {\n //if (e.CommandName == \"sel\")\n //{\n // lblCat.Text = e.CommandArgument.ToString();\n //}\n }\n</code></pre>\n\n<p>In the above code if I want to select :</p>\n\n<pre><code>e.CommandName == \"sel\"\n\nlblCat.Text = e.Comman\n</code></pre>\n\n<p>Then I press ALt key and select the rectangle and no need to uncomment the lines.</p>\n\n<p>Check this out.</p>\n"
},
{
"answer_id": 1707290,
"author": "Shital Shah",
"author_id": 207661,
"author_profile": "https://Stackoverflow.com/users/207661",
"pm_score": 5,
"selected": false,
"text": "<p>C# + CLR:</p>\n\n<ol>\n<li><p><code>Thread.MemoryBarrier</code>: Most people wouldn't have used it and there is some inaccurate information on MSDN. But if you know <a href=\"http://www.albahari.com/threading/part4.aspx\" rel=\"noreferrer\">intricacies</a> then you can do nifty lock-free synchronization.</p></li>\n<li><p><code>volatile, Thread.VolatileRead, Thread.VolatileWrite</code>: There are very very few people who gets the use of these and even fewer who understands all the risks they avoid and introduce :).</p></li>\n<li><p><code>ThreadStatic</code> variables: There was only one situation in past few years I've found that ThreadStatic variables were absolutely god send and indispensable. When you want to do something for entire call chain, for example, they are very useful.</p></li>\n<li><p><code>fixed</code> keyword: It's a hidden weapon when you want to make access to elements of large array almost as fast as C++ (by default C# enforces bound checks that slows down things).</p></li>\n<li><p><code>default(typeName)</code> keyword can be used outside of generic class as well. It's useful to create empty copy of struct.</p></li>\n<li><p>One of the handy feature I use is <code>DataRow[columnName].ToString()</code> always returns non-null value. If value in database was NULL, you get empty string.</p></li>\n<li><p>Use Debugger object to break automatically when you want developer's attention even if s/he hasn't enabled automatic break on exception:</p></li>\n</ol>\n\n<pre><code>\n#if DEBUG \n if (Debugger.IsAttached) \n Debugger.Break(); \n#endif\n</code></pre>\n\n<ol start=\"8\">\n<li>You can alias complicated ugly looking generic types so you don't have to copy paste them again and again. Also you can make changes to that type in one place. For example, </li>\n</ol>\n\n<pre><code>\n using ComplicatedDictionary = Dictionary<int, Dictionary<string, object>>;\n ComplicatedDictionary myDictionary = new ComplicatedDictionary();\n</code></pre>\n"
},
{
"answer_id": 1724852,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 4,
"selected": false,
"text": "<p>Need to return an empty IEnumerable?</p>\n\n<pre><code>public IEnumerable<T> GetEnumerator(){\n yield break;\n}\n</code></pre>\n"
},
{
"answer_id": 1770965,
"author": "thr",
"author_id": 452521,
"author_profile": "https://Stackoverflow.com/users/452521",
"pm_score": 4,
"selected": false,
"text": "<h1>Type-inference for factory methods</h1>\n\n<p><em>I don't know if this has been posted already (I scanned the first post, couldn't find it).</em></p>\n\n<p>This is best shown with an example, assuming you have this class (to simulate a tuple), in in an attempt to demonstrate all the language features that make this possible I will go through it step by step.</p>\n\n<pre><code>public class Tuple<V1, V2> : Tuple\n{\n public readonly V1 v1;\n public readonly V2 v2;\n\n public Tuple(V1 v1, V2 v2)\n {\n this.v1 = v1;\n this.v2 = v2;\n }\n}\n</code></pre>\n\n<p>Everyone knows how to create an instance of it, such as:</p>\n\n<pre><code>Tuple<int, string> tup = new Tuple<int, string>(1, \"Hello, World!\");\n</code></pre>\n\n<p>Not exactly rocket science, now we can of course change the type declaration of the variable to <em>var</em>, like this:</p>\n\n<pre><code>var tup = new Tuple<int, string>(1, \"Hello, World!\");\n</code></pre>\n\n<p>Still well known, to digress a bit here's a static method with type parameters, which everyone should be familiar with:</p>\n\n<pre><code>public static void Create<T1, T2>()\n{\n // stuff\n}\n</code></pre>\n\n<p>Calling it is, again common knowledge, done like this:</p>\n\n<pre><code>Create<float, double>();\n</code></pre>\n\n<p>What most people don't know is that if the arguments to the generic method contains all the types it requires they can be inferred, for example:</p>\n\n<pre><code>public static void Create<T1, T2>(T1 a, T2 b)\n{\n // stuff\n}\n</code></pre>\n\n<p>These two calls are identical:</p>\n\n<pre><code>Create<float, string>(1.0f, \"test\");\nCreate(1.0f, \"test\");\n</code></pre>\n\n<p>Since T1 and T2 is inferred from the arguments you passed. Combining this knowledge with the var keyword, we can by adding a second static class with a static method, such as:</p>\n\n<pre><code>public abstract class Tuple\n{\n public static Tuple<V1, V2> Create<V1, V2>(V1 v1, V2 v2)\n {\n return new Tuple<V1, V2>(v1, v2);\n }\n}\n</code></pre>\n\n<p>Achieve this effect:</p>\n\n<pre><code>var tup = Tuple.Create(1, \"Hello, World!\");\n</code></pre>\n\n<p>This means that the types of the: variable \"tup\", the type-parameters of \"Create\" and the return value of \"Create\" are all inferred from the types you <strong>pass as arguments to Create</strong></p>\n\n<p>The full code looks something like this:</p>\n\n<pre><code>public abstract class Tuple\n{\n public static Tuple<V1, V2> Create<V1, V2>(V1 v1, V2 v2)\n {\n return new Tuple<V1, V2>(v1, v2);\n }\n}\n\npublic class Tuple<V1, V2> : Tuple\n{\n public readonly V1 v1;\n public readonly V2 v2;\n\n public Tuple(V1 v1, V2 v2)\n {\n this.v1 = v1;\n this.v2 = v2;\n }\n}\n\n// Example usage:\nvar tup = Tuple.Create(1, \"test\");\n</code></pre>\n\n<p>Which gives you fully type inferred factory methods everywhere!</p>\n"
},
{
"answer_id": 1774916,
"author": "Brian",
"author_id": 320,
"author_profile": "https://Stackoverflow.com/users/320",
"pm_score": 3,
"selected": false,
"text": "<p>I like the <a href=\"http://msdn.microsoft.com/en-us/library/system.componentmodel.editorbrowsableattribute.aspx\" rel=\"nofollow noreferrer\">EditorBrowsableAttribute</a>. It lets you control whether a method/property is displayed or not in Intellisense. You can set the values to Always, Advanced, or Never.</p>\n\n<p><a href=\"http://msdn.microsoft.com/en-us/library/system.componentmodel.editorbrowsableattribute.aspx\" rel=\"nofollow noreferrer\">From MSDN</a>...</p>\n\n<p><strong>Remarks</strong></p>\n\n<p>EditorBrowsableAttribute is a hint to a designer indicating whether a property or method is to be displayed. You can use this type in a visual designer or text editor to determine what is visible to the user. For example, the IntelliSense engine in Visual Studio uses this attribute to determine whether to show a property or method.</p>\n\n<p>In Visual C#, you can control when advanced properties appear in IntelliSense and the Properties Window with the Hide Advanced Members setting under Tools | Options | Text Editor | C#. The corresponding EditorBrowsableState is Advanced.</p>\n"
},
{
"answer_id": 1789985,
"author": "Roman Boiko",
"author_id": 118478,
"author_profile": "https://Stackoverflow.com/users/118478",
"pm_score": 5,
"selected": false,
"text": "<p>Easily determine type with which variable was <strong>declared</strong> (from <a href=\"https://stackoverflow.com/questions/1786750/how-to-know-in-c-code-which-type-a-variable-was-declared-with/1786775#1786775\" title=\"Determine declared type of a variable\">my answer</a>):</p>\n\n<pre><code>using System;\nusing System.Collections.Generic;\n\nstatic class Program\n{\n public static Type GetDeclaredType<T>(T x)\n {\n return typeof(T);\n }\n\n // Demonstrate how GetDeclaredType works\n static void Main(string[] args)\n {\n IList<string> iList = new List<string>();\n List<string> list = null;\n\n Console.WriteLine(GetDeclaredType(iList).Name);\n Console.WriteLine(GetDeclaredType(list).Name);\n }\n}\n</code></pre>\n\n<p>Results:</p>\n\n<pre><code>IList`1\nList`1\n</code></pre>\n\n<p>And its <strong>name</strong> (borrowed from <a href=\"https://stackoverflow.com/questions/1386642/get-variable-not-hard-coded-name/1386730#1386730\" title=\"Get variable name\">\"Get variable name\"</a>):</p>\n\n<pre><code>static void Main(string[] args)\n{\n Console.WriteLine(\"Name is '{0}'\", GetName(new {args}));\n Console.ReadLine();\n}\n\nstatic string GetName<T>(T item) where T : class\n{\n var properties = typeof(T).GetProperties();\n return properties[0].Name;\n}\n</code></pre>\n\n<p>Result: <code>Name is 'args'</code></p>\n"
},
{
"answer_id": 1798482,
"author": "Phillip Ngan",
"author_id": 41410,
"author_profile": "https://Stackoverflow.com/users/41410",
"pm_score": 2,
"selected": false,
"text": "<p><strong>Convert enum values to a string value</strong></p>\n\n<p>Given the enum</p>\n\n<pre><code>enum Country\n{\n UnitedKingdom, \n UnitedStates,\n UnitedArabEmirates,\n}\n</code></pre>\n\n<p>using it:</p>\n\n<pre><code>public static void PrintEnumAsString( Country country )\n{\n Console.Writeline( country.ToString() );\n}\n</code></pre>\n\n<p>will print the name of the enum value as a string, e.g. \"UnitedKingdom\"</p>\n"
},
{
"answer_id": 1820538,
"author": "Roman Boiko",
"author_id": 118478,
"author_profile": "https://Stackoverflow.com/users/118478",
"pm_score": 5,
"selected": false,
"text": "<p>I found that only few developers know about this feature.</p>\n\n<p>If you need a method that works with a <strong>value-type variable via some interface</strong> (implemented by this value type), it's easy to <strong>avoid boxing</strong> during the method call.</p>\n\n<p>Example code:</p>\n\n<pre><code>using System;\nusing System.Collections;\n\ninterface IFoo {\n void Foo();\n}\nstruct MyStructure : IFoo {\n public void Foo() {\n }\n}\npublic static class Program {\n static void MethodDoesNotBoxArguments<T>(T t) where T : IFoo {\n t.Foo();\n }\n static void Main(string[] args) {\n MyStructure s = new MyStructure();\n MethodThatDoesNotBoxArguments(s);\n }\n}\n</code></pre>\n\n<p>IL code doesn't contain any box instructions:</p>\n\n<pre><code>.method private hidebysig static void MethodDoesNotBoxArguments<(IFoo) T>(!!T t) cil managed\n{\n // Code size 14 (0xe)\n .maxstack 8\n IL_0000: ldarga.s t\n IL_0002: constrained. !!T\n IL_0008: callvirt instance void IFoo::Foo()\n IL_000d: ret\n} // end of method Program::MethodDoesNotBoxArguments\n\n.method private hidebysig static void Main(string[] args) cil managed\n{\n .entrypoint\n // Code size 15 (0xf)\n .maxstack 1\n .locals init ([0] valuetype MyStructure s)\n IL_0000: ldloca.s s\n IL_0002: initobj MyStructure\n IL_0008: ldloc.0\n IL_0009: call void Program::MethodDoesNotBoxArguments<valuetype MyStructure>(!!0)\n IL_000e: ret\n} // end of method Program::Main\n</code></pre>\n\n<p>See <a href=\"http://rads.stackoverflow.com/amzn/click/0735621632\" rel=\"nofollow noreferrer\">Richter, J. CLR via C#</a>, 2nd edition, chapter 14: Interfaces, section about Generics and Interface Constraints.</p>\n\n<p>See also <a href=\"https://stackoverflow.com/questions/1816419/does-passing-a-struct-into-an-interface-field-allocate/1817137#1817137\">my answer</a> to another question.</p>\n"
},
{
"answer_id": 1821257,
"author": "Paul Ruane",
"author_id": 83264,
"author_profile": "https://Stackoverflow.com/users/83264",
"pm_score": 4,
"selected": false,
"text": "<p>A couple I can think of:</p>\n\n<pre><code>[field: NonSerialized()]\npublic EventHandler event SomeEvent;\n</code></pre>\n\n<p>This prevents the event from being serialised. The 'field:' indicates that the attribute should be applied to the event's backing field.</p>\n\n<p>Another little known feature is overriding the add/remove event handlers:</p>\n\n<pre><code>public event EventHandler SomeEvent\n{\n add\n {\n // ...\n }\n\n remove\n {\n // ...\n }\n}\n</code></pre>\n"
},
{
"answer_id": 1836944,
"author": "Zac Bowling",
"author_id": 171819,
"author_profile": "https://Stackoverflow.com/users/171819",
"pm_score": 3,
"selected": false,
"text": "<p>__arglist as well</p>\n\n<pre><code>[DllImport(\"msvcrt40.dll\")]\npublic static extern int printf(string format, __arglist);\n\nstatic void Main(string[] args)\n{\n printf(\"Hello %s!\\n\", __arglist(\"Bart\"));\n}\n</code></pre>\n"
},
{
"answer_id": 1858602,
"author": "Matt Dotson",
"author_id": 226060,
"author_profile": "https://Stackoverflow.com/users/226060",
"pm_score": 3,
"selected": false,
"text": "<p>Dictionary initializers are always useful for quick hacks and unit tests where you need to hardcode some data.</p>\n\n<pre><code>var dict = new Dictionary<int, string> { { 10, \"Hello\" }, { 20, \"World\" } };\n</code></pre>\n"
},
{
"answer_id": 1962004,
"author": "Dave Jellison",
"author_id": 184725,
"author_profile": "https://Stackoverflow.com/users/184725",
"pm_score": 3,
"selected": false,
"text": "<p>The Action and Func delegate helpers in conjunction with lambda methods. I use these for simple patterns that need a delegate to improve readability. For example, a simple caching pattern would be to check if the requested object exists in the cache. If it does exist: return the cached object. If it doesn't exist, generate a new instance, cache the new instance and return the new instance. Rather that write this code 1000 times for each object I may store/retrieve from the cache I can write a simple pattern method like so...</p>\n\n<pre><code>private static T CachePattern<T>(string key, Func<T> create) where T : class\n{\n if (cache[key] == null)\n {\n cache.Add(key, create());\n }\n\n return cache[key] as T;\n}\n</code></pre>\n\n<p>... then I can greatly simplify my cache get/set code by using the following in my custom cache manager</p>\n\n<pre><code>public static IUser CurrentUser\n{\n get\n {\n return CachePattern<IUser>(\"CurrentUserKey\", () => repository.NewUpUser());\n }\n}\n</code></pre>\n\n<p>Now simple \"everyday\" code patterns can be written once and reused much more easily IMHO. I don't have to go write a delegate type and figure out how I want to implement a callback, etc. If I can write it in 10 seconds I'm much less apt. to resort to cutting/pasting simple code patterns whether they be lazy initialization and some other examples shown above...</p>\n"
},
{
"answer_id": 1977121,
"author": "Jerod Venema",
"author_id": 25330,
"author_profile": "https://Stackoverflow.com/users/25330",
"pm_score": 2,
"selected": false,
"text": "<p>The \"TODO\" property and the tasks list</p>\n\n<pre><code>//TODO: [something] \n</code></pre>\n\n<p>Adding that to your code (the spacing is important) throws an item in your task list, and double clicking the item will jump you to the appropriate location in your code.</p>\n"
},
{
"answer_id": 2005795,
"author": "Ravi Vanapalli",
"author_id": 188822,
"author_profile": "https://Stackoverflow.com/users/188822",
"pm_score": 2,
"selected": false,
"text": "<p>I didn't knew about Generic methods which could help avoid using Method Overloadding.\nBelow are overloaded methods to print int and double numbers.</p>\n\n<pre><code> private static void printNumbers(int [] intNumbers)\n { \n foreach(int element in intNumbers)\n {\n Console.WriteLine(element);\n }\n\n }\n\n private static void printNumbers(double[] doubleNumbers)\n {\n foreach (double element in doubleNumbers)\n {\n Console.WriteLine(element);\n }\n }\n</code></pre>\n\n<p>Generic method which help to have one method for both of the above</p>\n\n<pre><code> private static void printNumbers<E>(E [] Numbers)\n {\n foreach (E element in Numbers)\n {\n Console.WriteLine(element);\n }\n }\n</code></pre>\n"
},
{
"answer_id": 2021617,
"author": "iChaib",
"author_id": 185854,
"author_profile": "https://Stackoverflow.com/users/185854",
"pm_score": 2,
"selected": false,
"text": "<ul>\n<li>Attaching <strong>?</strong> to a Type to make it\nnullable, ex: int? </li>\n<li>\"c:\\dir\" instead of <strong>@\"C:\\dir\"</strong></li>\n</ul>\n"
},
{
"answer_id": 2026781,
"author": "cllpse",
"author_id": 20946,
"author_profile": "https://Stackoverflow.com/users/20946",
"pm_score": 4,
"selected": false,
"text": "<p><strong>Easier-on-the-eyes / condensed ORM-mapping using LINQ</strong></p>\n\n<p>Consider this table:</p>\n\n<pre><code>[MessageId] INT,\n[MessageText] NVARCHAR(MAX)\n[MessageDate] DATETIME\n</code></pre>\n\n<p>... And this structure:</p>\n\n<pre><code>struct Message\n{\n Int32 Id;\n String Text;\n DateTime Date;\n}\n</code></pre>\n\n<p><br />\n<br />\nInstead of doing something along the lines of:</p>\n\n<pre><code>List<Message> messages = new List<Message>();\n\nforeach (row in DataTable.Rows)\n{\n var message = new Message\n {\n Id = Convert.ToInt32(row[\"MessageId\"]),\n Text = Convert.ToString(row[\"MessageText\"]),\n Date = Convert.ToDateTime(row[\"MessageDate\"])\n };\n\n messages.Add(message);\n}\n</code></pre>\n\n<p>You can use LINQ and do the same thing with fewer lines of code, and in my opinion; more style. Like so:</p>\n\n<pre><code>var messages = DataTable.AsEnumerable().Select(r => new Message\n{\n Id = Convert.ToInt32(r[\"MessageId\"]),\n Text = Convert.ToString(r[\"MessageText\"]),\n Date = Convert.ToDateTime(r[\"MessageDate\"])\n}).ToList();\n</code></pre>\n\n<p>This approach can be nested, just like loops can.</p>\n"
},
{
"answer_id": 2031994,
"author": "t0mm13b",
"author_id": 206367,
"author_profile": "https://Stackoverflow.com/users/206367",
"pm_score": 3,
"selected": false,
"text": "<p>Having read through all 9 pages of this I felt I had to point out a little unknown feature...</p>\n\n<p>This was held true for .NET 1.1, using compression/decompression on gzipped files, one had to either:</p>\n\n<ul>\n<li>Download <a href=\"http://www.icsharpcode.net/OpenSource/SharpZipLib/\" rel=\"nofollow noreferrer\">ICSharpCode.ZipLib</a></li>\n<li>Or, reference the Java library into your project and use the Java's in-built library to take advantage of the GZip's compression/decompression methods.</li>\n</ul>\n\n<p>It is underused, that I did not know about, (still use ICSharpCode.ZipLib still, even with .NET 2/3.5) was that it was incorporated into the standard BCL version 2 upwards, in the System.IO.Compression namespace... see the MSDN page \"<a href=\"http://msdn.microsoft.com/en-us/library/system.io.compression.gzipstream(VS.80).aspx\" rel=\"nofollow noreferrer\">GZipStream Class</a>\".</p>\n"
},
{
"answer_id": 2035708,
"author": "Jamie Keeling",
"author_id": 218159,
"author_profile": "https://Stackoverflow.com/users/218159",
"pm_score": 3,
"selected": false,
"text": "<p>I find the use of the conditional break function in Visual Studio very useful. I like the way it allows me to set the value to something that, for example can only be met in rare occasions and from there I can examine the code further.</p>\n"
},
{
"answer_id": 2055618,
"author": "David Stocking",
"author_id": 249602,
"author_profile": "https://Stackoverflow.com/users/249602",
"pm_score": 2,
"selected": false,
"text": "<p>Don't know if this is a secret per se but I loved the added Enumerable (adds to IEnumerable) class in System.Linq.</p>\n\n<p><a href=\"http://msdn.microsoft.com/en-us/library/system.linq.enumerable_members.aspx\" rel=\"nofollow noreferrer\">http://msdn.microsoft.com/en-us/library/system.linq.enumerable_members.aspx</a></p>\n\n<p>While the yield keyword is already listed. Iterator blocks are freaking amazing. I used them to build Lists that would be tested to see if they were co-prime. It basically allows you to go though a function that returns values one by one and stop any time.</p>\n\n<p>Oh, I almost forgot the best class in the world when you can't optimize it any more. The BackgroundWorker!!!!</p>\n\n<p><a href=\"http://msdn.microsoft.com/en-us/library/system.componentmodel.backgroundworker.aspx\" rel=\"nofollow noreferrer\">http://msdn.microsoft.com/en-us/library/system.componentmodel.backgroundworker.aspx</a></p>\n"
},
{
"answer_id": 2132689,
"author": "Mohammad Tayseer",
"author_id": 85245,
"author_profile": "https://Stackoverflow.com/users/85245",
"pm_score": 5,
"selected": false,
"text": "<p>I didn't find anyone who is using string.Join to join strings using a separator. Everyone keeps writing the same ugly for-loop</p>\n\n<pre><code>var sb = new StringBuilder();\nvar count = list.Count();\nfor(int i = 0; i < count; i++)\n{\n if (sb.Length > 0) sb.Append(seperator);\n sb.Append(list[i]);\n}\n\nreturn sb.ToString();\n</code></pre>\n\n<p>instead of</p>\n\n<pre><code>return string.Join(separator, list.ToArray());\n</code></pre>\n"
},
{
"answer_id": 2141921,
"author": "devforall",
"author_id": 43838,
"author_profile": "https://Stackoverflow.com/users/43838",
"pm_score": 2,
"selected": false,
"text": "<p>Another way of geting IEnumerable through yield without explicity creating an IEnumerable object</p>\n\n<pre><code>public IEnumerable<Request> SomeMethod(IEnumerable<Request> requests)\n{\n foreach (Request request in requests)\n yield return DoSomthing(request);\n}\n</code></pre>\n"
},
{
"answer_id": 2188117,
"author": "murki",
"author_id": 5953,
"author_profile": "https://Stackoverflow.com/users/5953",
"pm_score": 2,
"selected": false,
"text": "<p>I just want to mention (because of the OP metioning where T : struct) that one of the C# compiler gotchas is that </p>\n\n<pre><code>where T : Enum\n</code></pre>\n\n<p>will NOT compile. It throws the error \"Constraint cannot be special class 'System.Enum'\".</p>\n"
},
{
"answer_id": 2231697,
"author": "Max Toro",
"author_id": 39923,
"author_profile": "https://Stackoverflow.com/users/39923",
"pm_score": 2,
"selected": false,
"text": "<p>Collection Initializer inside Object Initializer:</p>\n\n<pre><code>MailMessage mail = new MailMessage {\n To = { new MailAddress(\"[email protected]\"), new MailAddress(\"[email protected]\") },\n Subject = \"Password Recovery\"\n};\n</code></pre>\n\n<p>You can initialize a whole tree in a single expression.</p>\n"
},
{
"answer_id": 2243846,
"author": "Mubashar",
"author_id": 806076,
"author_profile": "https://Stackoverflow.com/users/806076",
"pm_score": 2,
"selected": false,
"text": "<p>I am bit late in this conversation and I would like to contribute the following. It may be a new thing for some developers.</p>\n\n<pre><code>public class User\n{\n public long UserId { get; set; }\n public String Name { get; set; }\n public String Password { get; set; }\n public String Email { get; set; }\n}\n</code></pre>\n\n<p>The usual way to declare and initialize it is with a constructor or like following.</p>\n\n<pre><code>User user = new User();\nuser.UserId = 1;\nuser.Name = \"myname\";\netc\n</code></pre>\n\n<p>But I learned following way to initialize it. I know Visual Basic developers will love it because it's like with operator available only in VB.NET and not in C# that is as follows.</p>\n\n<pre><code>User user = new User()\n{\n UserId = 1,\n Name = \"myname\",\n Email = \"[email protected]\",\n Password = \"mypassword\"\n};\n</code></pre>\n"
},
{
"answer_id": 2262310,
"author": "A1exandr Belan",
"author_id": 87713,
"author_profile": "https://Stackoverflow.com/users/87713",
"pm_score": 4,
"selected": false,
"text": "<p>You can store colors in Enum.</p>\n\n<pre><code>public enum MyEnumColors : uint\n{\n Normal = 0xFF9F9F9F,\n Active = 0xFF8EA98A,\n Error = 0xFFFF0000\n}\n</code></pre>\n"
},
{
"answer_id": 2271941,
"author": "Ruben Bartelink",
"author_id": 11635,
"author_profile": "https://Stackoverflow.com/users/11635",
"pm_score": 2,
"selected": false,
"text": "<p>This <a href=\"http://elegantcode.com/2010/01/28/calling-non-public-methods/\" rel=\"nofollow noreferrer\">trick for calling private methods using Delegate.CreateDelegate</a> is extremely neat. </p>\n\n<pre><code>var subject = new Subject();\nvar doSomething = (Func<String, String>)\n Delegate.CreateDelegate(typeof(Func<String, String>), subject, \"DoSomething\");\nConsole.WriteLine(doSomething(\"Hello Freggles\"));\n</code></pre>\n\n<p><a href=\"https://stackoverflow.com/questions/1043899/non-code-generated-forwarding-shim-for-testing-private-methods/1804696#1804696\">Here's a context where it's useful</a></p>\n"
},
{
"answer_id": 2293955,
"author": "rerun",
"author_id": 149458,
"author_profile": "https://Stackoverflow.com/users/149458",
"pm_score": 0,
"selected": false,
"text": "<p>I don't know if this is a hidden feature (\"\"). Any string function.</p>\n"
},
{
"answer_id": 2359623,
"author": "Grokys",
"author_id": 6448,
"author_profile": "https://Stackoverflow.com/users/6448",
"pm_score": 3,
"selected": false,
"text": "<p>To test if an IEnumerable<code><T></code> is empty with LINQ, use:</p>\n\n<blockquote>\n <p>IEnumerable<code><T></code>.Any();</p>\n</blockquote>\n\n<ul>\n<li>At first, I was using (IEnumerable<code><T></code>.Count() != 0)...\n\n<ul>\n<li>Which unnecessarily causes all items in the IEnumerable<code><T></code> to be enumerated.</li>\n</ul></li>\n<li>As an improvement to this, I went on to use (IEnumerable<code><T></code>.FirstOrDefault() == null)...\n\n<ul>\n<li>Which is better...</li>\n</ul></li>\n<li>But IEnumerable<code><T></code>.Any() is the most succinct and performs the best.</li>\n</ul>\n"
},
{
"answer_id": 2361060,
"author": "Dax70",
"author_id": 182227,
"author_profile": "https://Stackoverflow.com/users/182227",
"pm_score": 2,
"selected": false,
"text": "<p>Most of the <a href=\"http://en.wikipedia.org/wiki/Platform_Invocation_Services\" rel=\"nofollow noreferrer\">P/Invoke</a> stuff is a bit strange.</p>\n\n<p>Example of attributes:</p>\n\n<pre><code>[DllImport (\"gdi32.dll\")] \n[return : MarshalAs(UnmanagedType.I4)]\n[StructLayout(LayoutKind.Sequential)]\n</code></pre>\n"
},
{
"answer_id": 2405367,
"author": "Anthony Mastrean",
"author_id": 3619,
"author_profile": "https://Stackoverflow.com/users/3619",
"pm_score": 3,
"selected": false,
"text": "<p><strong>Empty blocks with braces are allowed.</strong></p>\n\n<p>You can write code like this</p>\n\n<pre><code>{\n service.DoTonsOfWork(args);\n}\n</code></pre>\n\n<p>It's helpful when you want to try something without a <code>using</code> or <code>try... finally</code> that you've already written.</p>\n\n<pre><code>//using(var scope = new TransactionScope)\n{\n service.DoTonsOfWork(args);\n}\n</code></pre>\n"
},
{
"answer_id": 2425985,
"author": "Silviu",
"author_id": 260847,
"author_profile": "https://Stackoverflow.com/users/260847",
"pm_score": 2,
"selected": false,
"text": "<p>One of the most useful features Visual Studio has is \"Make object id\". It generates an id and \"attaches\" to the object so wherever you look at the object you will also see the id (regardless of the thread).</p>\n\n<p>While debugging right click on the variable tooltip and there you have it.\nIt also works on watched/autos/locals variables.</p>\n"
},
{
"answer_id": 2455744,
"author": "Edison Chuang",
"author_id": 83946,
"author_profile": "https://Stackoverflow.com/users/83946",
"pm_score": 4,
"selected": false,
"text": "<p><strong>Using \"~\" operator with FlagAttribute and enum</strong><br>\nSometime we would use Flag attribute with enum to perform bitwise manipulation on the enumeration.</p>\n\n<pre><code> [Flags]\n public enum Colors\n {\n None = 0,\n Red = 1,\n Blue = 2,\n White = 4,\n Black = 8,\n Green = 16,\n All = 31 //It seems pretty bad...\n }\n</code></pre>\n\n<p>Notice that, the value of option \"All\" which in enum is quite strange.<br>\nInstead of that we can use \"~\" operator with flagged enum.</p>\n\n<pre><code> [Flags]\n public enum Colors\n {\n None = 0,\n Red = 1,\n Blue = 2,\n White = 4,\n Black = 8,\n Green = 16,\n All = ~0 //much better now. that mean 0xffffffff in default.\n }\n</code></pre>\n"
},
{
"answer_id": 2484117,
"author": "user287107",
"author_id": 287107,
"author_profile": "https://Stackoverflow.com/users/287107",
"pm_score": 3,
"selected": false,
"text": "<p>With LINQ it's possible to create new functions based on parameters.\nThat's very nice if you have a tiny function which is exectued very often, but the parameters need some time to calculate.</p>\n\n<pre><code> public Func<int> RandomGenerator\n {\n get\n {\n var r = new Random();\n return () => { return r.Next(); };\n }\n }\n\n void SomeFunction()\n {\n var result1 = RandomGenerator();\n\n var x = RandomGenerator;\n var result2 = x();\n }\n</code></pre>\n"
},
{
"answer_id": 2495330,
"author": "John K",
"author_id": 179972,
"author_profile": "https://Stackoverflow.com/users/179972",
"pm_score": 5,
"selected": false,
"text": "<h1>Arbitrary nested scopes { }</h1>\n\n<p><br /> </p>\n\n<h2>1. For finer scoping behaviour</h2>\n\n<p><strong>{</strong> anywhere inside members <strong>}</strong>, <strong>{</strong> using only braces <strong>}</strong>, <strong>{</strong> with no control statement <strong>}</strong>.</p>\n\n<pre><code>void MyWritingMethod() {\n\n int sameAge = 35;\n\n\n { // scope some work\n string name = \"Joe\";\n Log.Write(name + sameAge.ToString());\n }\n\n\n { // scope some other work\n string name = \"Susan\";\n Log.Write(name + sameAge.ToString());\n }\n\n // I'll never mix up Joe and Susan again\n}\n</code></pre>\n\n<p>Inside large, confusing or archaic members (not that they should ever exist, however,) it helps me prevent against using wrong variable names. Scope stuff to finer levels. \n<br />\n<br /></p>\n\n<h2>2. For code beautification or visual semantics</h2>\n\n<p>For example, this XML writing code follows the indentation level of the actual generated XML (i.e. Visual Studio will indent the scoping braces accordingly)</p>\n\n<pre><code>XmlWriter xw = new XmlWriter(..);\n\n//<root>\nxw.WriteStartElement(\"root\");\n{\n //<game>\n xw.WriteStartElement(\"game\");\n {\n //<score>#</score>\n for (int i = 0; i < scores.Length; ++i) // multiple scores\n xw.WriteElementString(\"score\", scores[i].ToString());\n\n }\n //</game>\n xw.WriteEndElement();\n}\n//</root>\nxw.WriteEndElement();\n</code></pre>\n\n<h2>3. Mimic a 'with' statement</h2>\n\n<p>(Also another use to keep temp work out of the main scope)<br>\nProvided by <a href=\"https://stackoverflow.com/users/46187/\">Patrik</a>: sometimes used to mimic the VB \"with-statement\" in C#.</p>\n\n<pre><code>var somePerson = this.GetPerson(); // whatever \n{ \n var p = somePerson; \n p.FirstName = \"John\"; \n p.LastName = \"Doe\"; \n //... \n p.City = \"Gotham\"; \n} \n</code></pre>\n\n<p>For the discerning programmer.</p>\n"
},
{
"answer_id": 2531350,
"author": "Dariusz",
"author_id": 59528,
"author_profile": "https://Stackoverflow.com/users/59528",
"pm_score": 3,
"selected": false,
"text": "<p>You can change rounding scheme using:</p>\n\n<pre><code>var value = -0.5;\nvar value2 = 0.5;\nvar value3 = 1.4;\n\nConsole.WriteLine( Math.Round(value, MidpointRounding.AwayFromZero) ); //out: -1\nConsole.WriteLine(Math.Round(value2, MidpointRounding.AwayFromZero)); //out: 1\nConsole.WriteLine(Math.Round(value3, MidpointRounding.ToEven)); //out: 1\n</code></pre>\n"
},
{
"answer_id": 2576855,
"author": "Joshua Rodgers",
"author_id": 308118,
"author_profile": "https://Stackoverflow.com/users/308118",
"pm_score": 2,
"selected": false,
"text": "<p>This relates to static constructors. This is a method for performing static destruction (i.e. cleaning up resources when the program quits).</p>\n\n<p>First off the class:</p>\n\n<pre><code>class StaticDestructor\n{\n /// <summary>\n /// The delegate that is invoked when the destructor is called.\n /// </summary>\n public delegate void Handler();\n private Handler doDestroy;\n\n /// <summary>\n /// Creates a new static destructor with the specified delegate to handle the destruction.\n /// </summary>\n /// <param name=\"method\">The delegate that will handle destruction.</param>\n public StaticDestructor(Handler method)\n {\n doDestroy = method;\n }\n\n ~StaticDestructor()\n {\n doDestroy();\n }\n}\n</code></pre>\n\n<p>Then as a member of the class you wish to have a \"static destructor\" do:</p>\n\n<pre><code>private static readonly StaticDestructor destructor = new StaticDestructor\n(\n delegate()\n {\n //Cleanup here\n }\n);\n</code></pre>\n\n<p>This will now be called when final garbage collection occurs. This is useful if you absolutely need to free up certain resources.</p>\n\n<p>A quick and dirty program exhibiting this behavior:</p>\n\n<pre><code>using System;\n\nnamespace TestStaticDestructor\n{\n class StaticDestructor\n {\n public delegate void Handler();\n private Handler doDestroy;\n\n public StaticDestructor(Handler method)\n {\n doDestroy = method;\n }\n\n ~StaticDestructor()\n {\n doDestroy();\n }\n }\n\n class SomeClass\n {\n static SomeClass()\n {\n Console.WriteLine(\"Statically constructed!\");\n }\n\n static readonly StaticDestructor destructor = new StaticDestructor(\n delegate()\n {\n Console.WriteLine(\"Statically destructed!\");\n }\n );\n }\n\n class Program\n {\n static void Main(string[] args)\n {\n SomeClass someClass = new SomeClass();\n someClass = null;\n System.Threading.Thread.Sleep(1000);\n }\n }\n}\n</code></pre>\n\n<p>When the program exits, the \"static destructor\" is called.</p>\n"
},
{
"answer_id": 2578029,
"author": "Anemoia",
"author_id": 162694,
"author_profile": "https://Stackoverflow.com/users/162694",
"pm_score": 3,
"selected": false,
"text": "<p>Nullable.GetValueOrDefault ? </p>\n"
},
{
"answer_id": 2578334,
"author": "Nakul Chaudhary",
"author_id": 34588,
"author_profile": "https://Stackoverflow.com/users/34588",
"pm_score": 3,
"selected": false,
"text": "<p>I like </p>\n\n<pre><code>#if DEBUG\n //Code run in debugging mode\n\n#else\n //Code run in release mode\n\n#endif\n</code></pre>\n"
},
{
"answer_id": 2602813,
"author": "k25",
"author_id": 312219,
"author_profile": "https://Stackoverflow.com/users/312219",
"pm_score": 2,
"selected": false,
"text": "<p>With reference to the post w/ perma link \"<a href=\"https://stackoverflow.com/questions/9033/hidden-features-of-c/2495330#2495330\">Hidden Features of C#?</a>\", there is another way to accomplish the same - indentation / line breaks. Check this out..</p>\n\n<pre><code>XmlWriterSettings xmlWriterSettings = new XmlWriterSettings();\nxmlWriterSettings.NewLineOnAttributes = true;\nxmlWriterSettings.Indent = true;\n\n\nXmlWriter xml = XmlWriter.Create(@\"C:\\file.xml\", xmlWriterSettings);\n\n// Start writing the data using xml.WriteStartElement(), xml.WriteElementString(...), xml.WriteEndElement() etc\n</code></pre>\n\n<p>I am not sure whether this is an unknown feature though!</p>\n"
},
{
"answer_id": 2684383,
"author": "ntziolis",
"author_id": 268742,
"author_profile": "https://Stackoverflow.com/users/268742",
"pm_score": 4,
"selected": false,
"text": "<p>What about <strong>IObservable</strong>?</p>\n\n<p>Pretty much everybody knows <a href=\"http://msdn.microsoft.com/en-us/library/9eekhta0.aspx\" rel=\"nofollow noreferrer\"><strong>IEnumerable</strong></a> but their mathematical dual seems to be unknown <a href=\"http://msdn.microsoft.com/en-us/library/dd990377.aspx\" rel=\"nofollow noreferrer\"><strong>IObservable</strong></a>. Maybe because its new in .NET 4.</p>\n\n<p>What it does is instead of pulling the information (like an enumerable) it pushes information to the subscriber(s) of the observerable.</p>\n\n<p>Together with the <a href=\"http://msdn.microsoft.com/en-us/devlabs/ee794896.aspx\" rel=\"nofollow noreferrer\"><strong>Rx extensions</strong></a> it will change how we deal with events. Just to illustrate how powerful it is check a very short example <a href=\"http://channel9.msdn.com/posts/J.Van.Gogh/Writing-your-first-Rx-Application/\" rel=\"nofollow noreferrer\"><strong>here</strong></a>.</p>\n"
},
{
"answer_id": 2689007,
"author": "Jehof",
"author_id": 83039,
"author_profile": "https://Stackoverflow.com/users/83039",
"pm_score": 4,
"selected": false,
"text": "<p>When a class implements <a href=\"http://msdn.microsoft.com/en-us/library/system.componentmodel.inotifypropertychanged%28v=VS.80%29.aspx\" rel=\"nofollow noreferrer\">INotifyPropertyChanged</a> and you want to inform the binding system (WPF, Silverlight, etc.) that multiple bound properties of an object (ViewModel) have changed you can raise the PropertyChanged-Event with <strong>null</strong> or <strong>String.Empty</strong>.</p>\n\n<p>This is documented in MSDN, but code examples and articles often don´t explain this possibility. I found it very useful.</p>\n\n<pre><code>public class BoundObject : INotifyPropertyChanged {\n\n private int _value;\n private string _text;\n\n public event PropertyChangedEventHandler PropertyChanged;\n\n public int Value {\n get {\n return _value;\n }\n set {\n if (_value != value) {\n _value = value;\n OnPropertyChanged(\"Value\");\n }\n }\n }\n\n public string Text {\n get {\n return _text;\n }\n set {\n if (_text != value) {\n _text = value;\n OnPropertyChanged(\"Text\");\n }\n }\n }\n\n public void Init(){\n _text = \"InitialValue\";\n _value = 1;\n OnPropertyChanged(string.Empty);\n }\n\n public void Reset() {\n _text = \"DefaultValue\";\n _value = 0;\n OnPropertyChanged(string.Empty);\n }\n\n private void OnPropertyChanged(string propertyName) {\n PropertyChangedEventArgs e = new PropertyChangedEventArgs(propertyName);\n\n if (PropertyChanged != null) {\n PropertyChanged(this, e);\n }\n }\n}\n</code></pre>\n"
},
{
"answer_id": 2753564,
"author": "Navid Farhadi",
"author_id": 184756,
"author_profile": "https://Stackoverflow.com/users/184756",
"pm_score": 3,
"selected": false,
"text": "<p>This means T must have a public parameterless constructor :</p>\n\n<pre><code> class MyClass<T> where T : new()\n {\n\n }\n</code></pre>\n"
},
{
"answer_id": 2836741,
"author": "Pretzel",
"author_id": 21244,
"author_profile": "https://Stackoverflow.com/users/21244",
"pm_score": 3,
"selected": false,
"text": "<p>I was reading thru the book \"Pro ASP.NET MVC Framework\" (APress) and observed something the author was doing with a Dictionary object that was foreign to me. </p>\n\n<p>He added a new Key/Value Pair without using the Add() method. He then overwrote that same Key/Value pair without having to check if that key already existed. For example:</p>\n\n<pre><code>Dictionary<string, int> nameAgeDict = new Dictionary<string, int>();\nnameAgeDict[\"Joe\"] = 34; // no error. will just auto-add key/value\nnameAgeDict[\"Joe\"] = 41; // no error. key/value just get overwritten\nnameAgeDict.Add(\"Joe\", 30); // ERROR! key already exists\n</code></pre>\n\n<p>There are many cases where I don't need to check if my Dictionary already has a key or not and I just want to add the respective key/value pair (overwriting the existing key/value pair, if necessary.) Prior to this discovery, I would always have to check to see if the key already existed before adding it.</p>\n"
},
{
"answer_id": 2843263,
"author": "Razor",
"author_id": 17211,
"author_profile": "https://Stackoverflow.com/users/17211",
"pm_score": 1,
"selected": false,
"text": "<p>Separate static fields depending on the generic type of the surrounding class.</p>\n\n<pre><code> public class StaticConstrucEx2Outer<T> {\n\n // Will hold a different value depending on the specicified generic type\n public T SomeProperty { get; set; }\n\n static StaticConstrucEx2Outer() {\n Console.WriteLine(\"StaticConstrucEx2Outer \" + typeof(T).Name);\n }\n\n public class StaticConstrucEx2Inner<U, V> {\n\n static StaticConstrucEx2Inner() {\n\n Console.WriteLine(\"Outer <{0}> : Inner <{1}><{2}>\",\n typeof(T).Name,\n typeof(U).Name,\n typeof(V).Name);\n }\n\n public static void FooBar() {}\n }\n\n public class SCInner {\n\n static SCInner() {\n Console.WriteLine(\"SCInner init <{0}>\", typeof(T).Name);\n }\n\n public static void FooBar() {}\n }\n}\n\n\nStaticConstrucEx2Outer<int>.StaticConstrucEx2Inner<string, DateTime>.FooBar();\nStaticConstrucEx2Outer<int>.SCInner.FooBar();\n\nStaticConstrucEx2Outer<string>.StaticConstrucEx2Inner<string, DateTime>.FooBar();\nStaticConstrucEx2Outer<string>.SCInner.FooBar();\n\nStaticConstrucEx2Outer<string>.StaticConstrucEx2Inner<string, Int16>.FooBar();\nStaticConstrucEx2Outer<string>.SCInner.FooBar();\n\nStaticConstrucEx2Outer<string>.StaticConstrucEx2Inner<string, UInt32>.FooBar();\n\nStaticConstrucEx2Outer<long>.StaticConstrucEx2Inner<string, UInt32>.FooBar();\n</code></pre>\n\n<p>Will produce the following output</p>\n\n<pre><code>Outer <Int32> : Inner <String><DateTime>\nSCInner init <Int32>\n\nOuter <String> : Inner <String><DateTime>\nSCInner init <String>\n\nOuter <String> : Inner <String><Int16>\n\nOuter <String> : Inner <String><UInt32>\n\nOuter <Int64> : Inner <String><UInt32>\n</code></pre>\n"
},
{
"answer_id": 2905415,
"author": "Thomas Levesque",
"author_id": 98713,
"author_profile": "https://Stackoverflow.com/users/98713",
"pm_score": 4,
"selected": false,
"text": "<p>OK, it may seem obvious, but I want to mention the <code>Object.Equals</code> method (the static one, with two arguments).</p>\n\n<p>I'm pretty sure many people don't even know about it, or forget it's there, yet it can really help in some cases. For instance, when you want to compare two objects for equality, not knowing if they're null. How many times did you write something like that :</p>\n\n<pre><code>if ((x == y) || ((x != null && y != null) && x.Equals(y)))\n{\n ...\n}\n</code></pre>\n\n<p>When you can just write :</p>\n\n<pre><code>if (Object.Equals(x, y))\n{\n ...\n}\n</code></pre>\n\n<p>(<code>Object.Equals</code> is actually implemented exactly like in the first code sample)</p>\n"
},
{
"answer_id": 2918238,
"author": "Kim Tranjan",
"author_id": 340381,
"author_profile": "https://Stackoverflow.com/users/340381",
"pm_score": 5,
"selected": false,
"text": "<p>Width in <code>string.Format()</code></p>\n\n<pre><code>Console.WriteLine(\"Product: {0,-7} Price: {1,5}\", product1, price1);\nConsole.WriteLine(\"Product: {0,-7} Price: {1,5}\", product2, price2);\n</code></pre>\n\n<p>produces</p>\n\n<p><img src=\"https://i.imgur.com/e0hg3.png\" alt=\"alt text\"></p>\n\n<p>from <a href=\"http://blog.prabir.me/post/Hidden-C-feature-stringFormat-Width.aspx\" rel=\"nofollow noreferrer\">Prabir's Blog | Hidden C# feature</a> </p>\n"
},
{
"answer_id": 3006868,
"author": "Centro",
"author_id": 362287,
"author_profile": "https://Stackoverflow.com/users/362287",
"pm_score": 2,
"selected": false,
"text": "<p>Lately I learned about the String.Join method. It is really useful when building strings like columns to select by a query.</p>\n"
},
{
"answer_id": 3031174,
"author": "Buildstarted",
"author_id": 365526,
"author_profile": "https://Stackoverflow.com/users/365526",
"pm_score": 5,
"selected": false,
"text": "<p>typedefs</p>\n\n<p>Someone posted that they miss typedefs but you can do it like this</p>\n\n<pre><code>using ListOfDictionary = System.Collections.Generic.List<System.Collections.Generic.Dictionary<string, string>>;\n</code></pre>\n\n<p>and declare it as</p>\n\n<pre><code>ListOfDictionary list = new ListOfDictionary();\n</code></pre>\n"
},
{
"answer_id": 3090178,
"author": "jcruz",
"author_id": 358007,
"author_profile": "https://Stackoverflow.com/users/358007",
"pm_score": 6,
"selected": false,
"text": "<p>Here is a new method of the string class in C# 4.0:</p>\n\n<pre><code>String.IsNullOrWhiteSpace(String value)\n</code></pre>\n\n<p>It's about time.</p>\n"
},
{
"answer_id": 3093285,
"author": "Steve Dunn",
"author_id": 28901,
"author_profile": "https://Stackoverflow.com/users/28901",
"pm_score": 4,
"selected": false,
"text": "<p>Not really hidden, but useful. When you've got an <code>enum</code> with <code>flags</code>, you can use shift-left to make things clearer. e.g.</p>\n\n<pre><code>[Flags]\npublic enum ErrorTypes {\n None = 0,\n MissingPassword = 1 << 0,\n MissingUsername = 1 << 1,\n PasswordIncorrect = 1 << 2 \n}\n</code></pre>\n"
},
{
"answer_id": 3094954,
"author": "Bill Barry",
"author_id": 108993,
"author_profile": "https://Stackoverflow.com/users/108993",
"pm_score": 4,
"selected": false,
"text": "<p>Another note on event handlers: you can simply create a raise extension method like so:</p>\n\n<pre><code>public static class EventExtensions {\n public static void Raise<T>(this EventHandler<T> @event, \n object sender, T args) where T : EventArgs {\n if(@event!= null) {\n @event(sender, args);\n }\n }\n}\n</code></pre>\n\n<p>Then you can use it to raise events:</p>\n\n<pre><code>public class MyImportantThing {\n public event EventHandler<MyImportantEventEventArgs> SomethingHappens;\n ...\n public void Bleh() {\n SomethingHappens.Raise(this, new MyImportantEventEventArgs { X=true });\n }\n}\n</code></pre>\n\n<p>This method has the added advantage of enforcing a coding standard (using <code>EventHandler<></code>).</p>\n\n<p>There isn't a point in writing the same exact function over and over and over again. Perhaps the next version of C# will finally have an <code>InlineAttribute</code> that can be placed on the extension method and will cause the compiler to inline the method definition (which would make this way nearly standard, and the fastest).</p>\n\n<p>edit: removed temp variable inside extension method based on comments</p>\n"
},
{
"answer_id": 3096408,
"author": "Steve Dunn",
"author_id": 28901,
"author_profile": "https://Stackoverflow.com/users/28901",
"pm_score": 6,
"selected": false,
"text": "<p>When debugging, you can type <code>$exception</code> in the Watch\\QuickWatch\\Immediate window and get all the info on the exception of the current frame. This is very useful if you've got 1st chance exceptions turned on!</p>\n"
},
{
"answer_id": 3096656,
"author": "STW",
"author_id": 60724,
"author_profile": "https://Stackoverflow.com/users/60724",
"pm_score": 2,
"selected": false,
"text": "<p>I don't condone it, but I was surprised that <a href=\"http://msdn.microsoft.com/en-us/library/13940fs2(VS.100).aspx\" rel=\"nofollow noreferrer\">goto</a> is still around <em>ducks incoming projectiles</em></p>\n"
},
{
"answer_id": 3138039,
"author": "Keith Bluestone",
"author_id": 378081,
"author_profile": "https://Stackoverflow.com/users/378081",
"pm_score": 5,
"selected": false,
"text": "<p><strong>RealProxy lets you create your own proxies for existing types.</strong></p>\n\n<p>This is super-advanced and I haven't seen anyone else use it -- which may mean that it's also really not that useful for most folks -- but it's one of those things that's good to know. </p>\n\n<p>Basically, the .NET <strong>RealProxy</strong> class lets you create what is called a <em>transparent proxy</em> to another type. Transparent in this case means that it looks completely like the proxied target object to its client -- but it's really not: it's an instance of your class, which is derived from RealProxy. </p>\n\n<p>This lets you apply powerful and comprehensive interception and \"intermediation\" services between the client and any methods or properties invoked on the real target object. Couple this power with the factory pattern (IoC etc), and you can hand back transparent proxies instead of real objects, allowing you to intercept all calls to the real objects and perform actions before and after each method invocation. In fact, I believe this is the very functionality .NET uses for remoting across app domain, process, and machine boundaries: .NET intercepts all access, sends serialized info to the remote object, receives the response, and returns it to your code.</p>\n\n<p>Maybe an example will make it clear how this can be useful: I created a reference service stack for my last job as enterprise architect which specified the standard internal composition (the \"stack\") of any new WCF services across the division. The model mandated that the data access layer for (say) the Foo service implement <code>IDAL<Foo>:</code> create a Foo, read a Foo, update a Foo, delete a Foo. Service developers used supplied common code (from me) that would locate and load the required DAL for a service: </p>\n\n<pre><code>IDAL<T> GetDAL<T>(); // retrieve data access layer for entity T\n</code></pre>\n\n<p>Data access strategies in that company had often been, well, performance-challenged. As an architect, I couldn't watch over every service developer to make sure that he/she wrote a performant data access layer. But what I could do within the <em>GetDAL</em> factory pattern was create <strong>a transparent proxy</strong> to the requested DAL (once the common service model code located the DLL and loaded it), and use high-performance timing APIs to profile all calls to any method of the DAL. Ranking laggards then is just a matter of sorting DAL call timings by descending total time. The advantage to this over development profiling (e.g. in the IDE) is that it can be done in the production environment as well, to ensure SLAs. </p>\n\n<p>Here is an example of test code I wrote for the \"entity profiler,\" which was common code to create a profiling proxy for any type with a single line:</p>\n\n<pre><code>[Test, Category(\"ProfileEntity\")]\npublic void MyTest()\n{\n // this is the object that we want profiled.\n // we would normally pass this around and call\n // methods on this instance.\n DALToBeProfiled dal = new DALToBeProfiled();\n\n // To profile, instead we obtain our proxy\n // and pass it around instead.\n DALToBeProfiled dalProxy = (DALToBeProfiled)EntityProfiler.Instance(dal);\n\n // or...\n DALToBeProfiled dalProxy2 = EntityProfiler<DALToBeProfiled>.Instance(dal);\n\n // Now use proxy wherever we would have used the original...\n // All methods' timings are automatically recorded\n // with a high-resolution timer\n DoStuffToThisObject(dalProxy);\n\n // Output profiling results\n ProfileManager.Instance.ToConsole();\n}\n</code></pre>\n\n<p>Again, this lets you intercept all methods and properties called by the client on the target object! In your <em>RealProxy-derived</em> class, you have to override <strong>Invoke:</strong></p>\n\n<pre><code>[System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)]\n[SecurityPermission(SecurityAction.LinkDemand, \n Flags = SecurityPermissionFlag.Infrastructure)] // per FxCop\npublic override IMessage Invoke(IMessage msg)\n{\n IMethodCallMessage msgMethodCall = msg as IMethodCallMessage;\n Debug.Assert(msgMethodCall != null); // should not be null - research Invoke if this trips. KWB 2009.05.28\n\n // The MethodCallMessageWrapper\n // provides read/write access to the method \n // call arguments. \n MethodCallMessageWrapper mc =\n new MethodCallMessageWrapper(msgMethodCall);\n\n // This is the reflected method base of the called method. \n MethodInfo mi = (MethodInfo)mc.MethodBase;\n\n IMessage retval = null;\n\n // Pass the call to the method and get our return value\n string profileName = ProfileClassName + \".\" + mi.Name;\n\n using (ProfileManager.Start(profileName))\n {\n IMessage myReturnMessage =\n RemotingServices.ExecuteMessage(_target, msgMethodCall);\n\n retval = myReturnMessage;\n }\n\n return retval;\n}\n</code></pre>\n\n<p>Isn't it fascinating what .NET can do? The only restriction is that the target type <em>must</em> be derived from <strong><em>MarshalByRefObject</em></strong>. I hope this is helpful to someone.</p>\n"
},
{
"answer_id": 3138257,
"author": "Incognito",
"author_id": 303756,
"author_profile": "https://Stackoverflow.com/users/303756",
"pm_score": 4,
"selected": false,
"text": "<p>Also useful, but not commonly used : <a href=\"http://msdn.microsoft.com/en-us/library/ms228973.aspx\" rel=\"nofollow noreferrer\">Constrained Execution Regions</a>.</p>\n\n<p>A quote from BCL Team blog :</p>\n\n<blockquote>\n <p>Constrained execution regions (CER's)\n exist to help a developer write her\n code to maintain consistency. The CLR\n doesn't guarantee that the developer's\n code is correct, but the CLR does\n hoist all of the runtime-induced\n failure points (ie, async exceptions)\n to either before the code runs, or\n after it has completed. Combined with\n constraints on what the developer can\n put in a CER, these are a useful way\n of making strong guarantees about\n whether your code will execute. CER's\n are eagerly prepared, meaning that\n when we see one, we will eagerly JIT\n any code found in its\n statically-discoverable call graph. \n If the CLR's host cares about stack\n overflow, we'll probe for some amount\n of stack space as well (though perhaps\n not enough stack space for any\n arbitrary method*). We also delay\n thread aborts until the CER has\n finished running.</p>\n</blockquote>\n\n<p>It can be useful when making edits to more than one field of a data structure in an atomic fashion. So it helps to have transactions on objects.</p>\n\n<p>Also <a href=\"http://msdn.microsoft.com/en-us/library/system.runtime.constrainedexecution.criticalfinalizerobject.aspx\" rel=\"nofollow noreferrer\">CriticalFinalizerObject</a> seems to be hidden(at least who are not writing unsafe code).\nA CriticalFinalizerObject guarantees that garbage collection will execute the finalizer. Upon allocation, the finalizer and its call graph are prepared in advance. </p>\n"
},
{
"answer_id": 3146453,
"author": "Incognito",
"author_id": 303756,
"author_profile": "https://Stackoverflow.com/users/303756",
"pm_score": 5,
"selected": false,
"text": "<p><a href=\"http://msdn.microsoft.com/en-us/library/system.appdomain.unhandledexception.aspx\" rel=\"nofollow noreferrer\">AppDomain.UnhandledException Event</a> is also candidate for being hidden.</p>\n\n<blockquote>\n <p>This event provides notification of uncaught exceptions. It allows the application to log information about the exception before the system default handler reports the exception to the user and terminates the application. If sufficient information about the state of the application is available, other actions may be undertaken — such as saving program data for later recovery. Caution is advised, because program data can become corrupted when exceptions are not handled.</p>\n</blockquote>\n\n<p>We can see, even on this site, a lot of people are wondering why their application is not starting, why it crashed, etc. The <code>AppDomain.UnhandledException</code> event can be very useful for such cases as it provides the possibility at least to log the reason of application failure. </p>\n"
},
{
"answer_id": 3147945,
"author": "Dan",
"author_id": 59532,
"author_profile": "https://Stackoverflow.com/users/59532",
"pm_score": 4,
"selected": false,
"text": "<pre><code>string.Empty\n</code></pre>\n\n<p>I know it's not fantastical (ludicrously odd), but I use it all the time instead of \"\".</p>\n\n<p>And it's pretty well hidden until someone tells you it's there.</p>\n"
},
{
"answer_id": 3152079,
"author": "Incognito",
"author_id": 303756,
"author_profile": "https://Stackoverflow.com/users/303756",
"pm_score": 4,
"selected": false,
"text": "<p><a href=\"http://msdn.microsoft.com/en-us/library/f58wzh21(VS.80).aspx\" rel=\"nofollow noreferrer\">fixed</a> statement</p>\n\n<p>This statement prevents the garbage collector from relocating a movable variable. Fixed can also be used to create fixed size buffers.</p>\n\n<blockquote>\n <p>The fixed statement sets a pointer to a managed variable and \"pins\" that variable during the execution of statement.</p>\n</blockquote>\n\n<p><a href=\"http://msdn.microsoft.com/en-us/library/cx9s2sy4(VS.71).aspx\" rel=\"nofollow noreferrer\">stackalloc</a></p>\n\n<p>The stackalloc allocates a block of memory on the stack.</p>\n"
},
{
"answer_id": 3172255,
"author": "Ozan",
"author_id": 137065,
"author_profile": "https://Stackoverflow.com/users/137065",
"pm_score": 4,
"selected": false,
"text": "<p>You can put several attributes in one pair of square brackets:</p>\n\n<pre><code> [OperationContract, ServiceKnownType(typeof(Prism)), ServiceKnownType(typeof(Cuboid))]\n Shape GetShape();\n</code></pre>\n"
},
{
"answer_id": 3189640,
"author": "WedTM",
"author_id": 88770,
"author_profile": "https://Stackoverflow.com/users/88770",
"pm_score": 3,
"selected": false,
"text": "<p>Not sure if this one has been mentioned or not (11 pages!!)</p>\n\n<p>But the <code>OptionalField</code> attribute for classes is amazing when you are versioning classes/objects that are going to be serialized.</p>\n\n<p><a href=\"http://msdn.microsoft.com/en-us/library/ms229752(VS.80).aspx\" rel=\"nofollow noreferrer\">http://msdn.microsoft.com/en-us/library/ms229752(VS.80).aspx</a></p>\n"
},
{
"answer_id": 3189688,
"author": "AaronLS",
"author_id": 84206,
"author_profile": "https://Stackoverflow.com/users/84206",
"pm_score": 3,
"selected": false,
"text": "<p>Accessing local variables from anonymous methods allows you to wrap just about any code with new control flow logic, without having to factor out that code into another method. Local variables declared outside the method are available inside the method such as the <code>endOfLineChar</code> local variable in the example here:</p>\n\n<p><a href=\"http://aaronls.wordpress.com/2010/02/02/retrying-on-exception-conditionally/\" rel=\"nofollow noreferrer\">http://aaronls.wordpress.com/2010/02/02/retrying-on-exception-conditionally/</a></p>\n"
},
{
"answer_id": 9413174,
"author": "Laradda",
"author_id": 820089,
"author_profile": "https://Stackoverflow.com/users/820089",
"pm_score": 2,
"selected": false,
"text": "<p>You can combine the <code>protected</code> and <code>internal</code> accessor to make it public within the same assembly, but protected in a diffrent assembly. This can be used on fields, properties, method and even constants.</p>\n"
}
] | 2008/08/12 | [
"https://Stackoverflow.com/questions/9033",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/31505/"
] | This came to my mind after I learned the following from [this question](http://www.stackoverflow.com/questions/8941/generic-type-checking):
```
where T : struct
```
We, C# developers, all know the basics of C#. I mean declarations, conditionals, loops, operators, etc.
Some of us even mastered the stuff like [Generics](http://msdn.microsoft.com/en-us/library/512aeb7t.aspx), [anonymous types](http://msdn.microsoft.com/en-us/library/bb397696.aspx), [lambdas](http://msdn.microsoft.com/en-us/library/bb397687.aspx), [LINQ](http://msdn.microsoft.com/en-us/library/bb397676.aspx), ...
But what are the most hidden features or tricks of C# that even C# fans, addicts, experts barely know?
Here are the revealed features so far:
======================================
Keywords
--------
* [`yield`](http://msdn.microsoft.com/en-us/library/9k7k7cf0.aspx) by [Michael Stum](https://stackoverflow.com/questions/9033/hidden-features-of-c/9035#9035)
* `var` by [Michael Stum](https://stackoverflow.com/questions/9033/hidden-features-of-c/9035#9035)
* `using()` statement by [kokos](https://stackoverflow.com/questions/9033/hidden-features-of-c/9036#9036)
* `readonly` by [kokos](https://stackoverflow.com/questions/9033/hidden-features-of-c/9036#9036)
* `as` by [Mike Stone](https://stackoverflow.com/questions/9033/hidden-features-of-c/9041#9041)
* `as` / `is` by [Ed Swangren](https://stackoverflow.com/questions/9033/hidden-features-of-c/9070#9070)
* `as` / `is` (improved) by [Rocketpants](https://stackoverflow.com/questions/9033/hidden-features-of-c/9092#9092)
* `default` by [deathofrats](https://stackoverflow.com/questions/9033/hidden-features-of-c/9639#9639)
* `global::` by [pzycoman](https://stackoverflow.com/questions/9033/hidden-features-of-c/12152#12152)
* `using()` blocks by [AlexCuse](https://stackoverflow.com/questions/9033/hidden-features-of-c/12316#12316)
* `volatile` by [Jakub Šturc](https://stackoverflow.com/questions/9033/hidden-features-of-c/59691#59691)
* `extern alias` by [Jakub Šturc](https://stackoverflow.com/questions/9033/hidden-features-of-c/37926#37926)
Attributes
----------
* [`DefaultValueAttribute`](http://msdn.microsoft.com/en-us/library/system.componentmodel.defaultvalueattribute.aspx) by [Michael Stum](https://stackoverflow.com/questions/9033/hidden-features-of-c/9035#9035)
* [`ObsoleteAttribute`](http://msdn.microsoft.com/en-us/library/system.obsoleteattribute.aspx) by [DannySmurf](https://stackoverflow.com/questions/9033/hidden-features-of-c/9037#9037)
* [`DebuggerDisplayAttribute`](http://msdn.microsoft.com/en-us/library/system.diagnostics.debuggerdisplayattribute.aspx) by [Stu](https://stackoverflow.com/questions/9033/hidden-features-of-c/9048#9048)
* [`DebuggerBrowsable`](http://msdn.microsoft.com/en-us/library/system.diagnostics.debuggerbrowsableattribute.aspx) and [`DebuggerStepThrough`](http://msdn.microsoft.com/en-us/library/system.diagnostics.debuggerstepthroughattribute.aspx) by [bdukes](https://stackoverflow.com/questions/9033/hidden-features-of-c/33474#33474)
* [`ThreadStaticAttribute`](http://msdn.microsoft.com/en-us/library/system.threadstaticattribute(VS.71).aspx) by [marxidad](https://stackoverflow.com/questions/9033/hidden-features-of-c/13932#13932)
* [`FlagsAttribute`](http://msdn.microsoft.com/en-us/library/system.flagsattribute.aspx) by [Martin Clarke](https://stackoverflow.com/questions/9033/hidden-features-of-c/21752#21752)
* [`ConditionalAttribute`](http://msdn.microsoft.com/en-us/library/4xssyw96.aspx) by [AndrewBurns](https://stackoverflow.com/questions/9033/hidden-features-of-c/35342#35342)
Syntax
------
* [`??`](http://msdn.microsoft.com/en-us/library/ms173224.aspx) (coalesce nulls) operator by [kokos](https://stackoverflow.com/questions/9033/hidden-features-of-c/9036#9036)
* Number flaggings by [Nick Berardi](https://stackoverflow.com/questions/9033/hidden-features-of-c/9038#9038)
* `where T:new` by [Lars Mæhlum](https://stackoverflow.com/questions/9033/hidden-features-of-c/9067#9067)
* Implicit generics by [Keith](https://stackoverflow.com/questions/9033/hidden-features-of-c/9099#9099)
* One-parameter lambdas by [Keith](https://stackoverflow.com/questions/9033/hidden-features-of-c/9099#9099)
* Auto properties by [Keith](https://stackoverflow.com/questions/9033/hidden-features-of-c/9099#9099)
* Namespace aliases by [Keith](https://stackoverflow.com/questions/9033/hidden-features-of-c/9099#9099)
* Verbatim string literals with @ by [Patrick](https://stackoverflow.com/questions/9033/hidden-features-of-c/9114#9114)
* `enum` values by [lfoust](https://stackoverflow.com/questions/9033/hidden-features-of-c/11738#11738)
* @variablenames by [marxidad](https://stackoverflow.com/questions/9033/hidden-features-of-c/14088#14088)
* `event` operators by [marxidad](https://stackoverflow.com/questions/9033/hidden-features-of-c/14277#14277)
* Format string brackets by [Portman](https://stackoverflow.com/questions/9033/hidden-features-of-c/15321#15321)
* Property accessor accessibility modifiers by [xanadont](https://stackoverflow.com/questions/9033/hidden-features-of-c/15715#15715)
* Conditional (ternary) operator (`?:`) by [JasonS](https://stackoverflow.com/questions/9033/hidden-features-of-c/16450#16450)
* `checked` and `unchecked` operators by [Binoj Antony](https://stackoverflow.com/questions/9033/hidden-features-of-c/355991#355991)
* `implicit and explicit` operators by [Flory](https://stackoverflow.com/questions/9033/hidden-features-of-c/121470#121470)
Language Features
-----------------
* Nullable types by [Brad Barker](https://stackoverflow.com/questions/9033/hidden-features-of-c/9055#9055)
* Anonymous types by [Keith](https://stackoverflow.com/questions/9033/hidden-features-of-c/9099#9099)
* `__makeref __reftype __refvalue` by [Judah Himango](https://stackoverflow.com/questions/9033/hidden-features-of-c/9125#9125)
* Object initializers by [lomaxx](https://stackoverflow.com/questions/9033/hidden-features-of-c/9547#9547)
* Format strings by [David in Dakota](https://stackoverflow.com/questions/9033/hidden-features-of-c/10207#10207)
* Extension Methods by [marxidad](https://stackoverflow.com/questions/9033/hidden-features-of-c/13932#13932)
* `partial` methods by [Jon Erickson](https://stackoverflow.com/questions/9033/hidden-features-of-c/16395#16395)
* Preprocessor directives by [John Asbeck](https://stackoverflow.com/questions/9033/hidden-features-of-c/16482#16482)
* `DEBUG` pre-processor directive by [Robert Durgin](https://stackoverflow.com/questions/9033/hidden-features-of-c/29081#29081)
* Operator overloading by [SefBkn](https://stackoverflow.com/questions/9033/hidden-features-of-c/24914#24914)
* Type inferrence by [chakrit](https://stackoverflow.com/questions/9033/hidden-features-of-c/28811#28811)
* Boolean operators [taken to next level](http://www.java2s.com/Tutorial/CSharp/0160__Operator-Overload/truefalseoperatorforComplex.htm) by [Rob Gough](https://stackoverflow.com/questions/9033/hidden-features-of-c/32148#32148)
* Pass value-type variable as interface without boxing by [Roman Boiko](https://stackoverflow.com/questions/9033/hidden-features-of-c/1820538#1820538)
* Programmatically determine declared variable type by [Roman Boiko](https://stackoverflow.com/questions/9033/hidden-features-of-c/1789985#1789985)
* Static Constructors by [Chris](https://stackoverflow.com/questions/9033/hidden-features-of-c/100321#100321)
* Easier-on-the-eyes / condensed ORM-mapping using LINQ by [roosteronacid](https://stackoverflow.com/questions/9033/hidden-features-of-c/2026781#2026781)
* `__arglist` by [Zac Bowling](https://stackoverflow.com/a/1836944/171819)
Visual Studio Features
----------------------
* Select block of text in editor by [Himadri](https://stackoverflow.com/questions/9033/hidden-features-of-c/1699477#1699477 "block text selecting with alt key")
* Snippets by [DannySmurf](https://stackoverflow.com/questions/9033/hidden-features-of-c/9037#9037)
Framework
---------
* `TransactionScope` by [KiwiBastard](https://stackoverflow.com/questions/9033/hidden-features-of-c/9042#9042)
* `DependantTransaction` by [KiwiBastard](https://stackoverflow.com/questions/9033/hidden-features-of-c/9042#9042)
* `Nullable<T>` by [IainMH](https://stackoverflow.com/questions/9033/hidden-features-of-c/9118#9118)
* `Mutex` by [Diago](https://stackoverflow.com/questions/9033/hidden-features-of-c/9181#9181)
* `System.IO.Path` by [ageektrapped](https://stackoverflow.com/questions/9033/hidden-features-of-c/9401#9401)
* `WeakReference` by [Juan Manuel](https://stackoverflow.com/questions/9033/hidden-features-of-c/14723#14723)
Methods and Properties
----------------------
* `String.IsNullOrEmpty()` method by [KiwiBastard](https://stackoverflow.com/questions/9033/hidden-features-of-c/9042#9042)
* `List.ForEach()` method by [KiwiBastard](https://stackoverflow.com/questions/9033/hidden-features-of-c/9042#9042)
* `BeginInvoke()`, `EndInvoke()` methods by [Will Dean](https://stackoverflow.com/questions/9033/hidden-features-of-c/9581#9581)
* `Nullable<T>.HasValue` and `Nullable<T>.Value` properties by [Rismo](https://stackoverflow.com/questions/9033/hidden-features-of-c/15393#15393)
* `GetValueOrDefault` method by [John Sheehan](https://stackoverflow.com/questions/9033/hidden-features-of-c/18158#18158)
Tips & Tricks
-------------
* Nice method for event handlers by [Andreas H.R. Nilsson](https://stackoverflow.com/questions/9033/hidden-features-of-c/9282#9282)
* Uppercase comparisons by [John](https://stackoverflow.com/questions/9033/hidden-features-of-c/12137#12137)
* Access anonymous types without reflection by [dp](https://stackoverflow.com/questions/9033/hidden-features-of-c/13441#13441)
* A quick way to lazily instantiate collection properties by [Will](https://stackoverflow.com/questions/9033/hidden-features-of-c/58945#58945)
* JavaScript-like anonymous inline-functions by [roosteronacid](https://stackoverflow.com/questions/9033/hidden-features-of-c/1399130#1399130)
Other
-----
* netmodules by [kokos](https://stackoverflow.com/questions/9033/hidden-features-of-c/9036#9036)
* [LINQBridge](http://www.albahari.com/nutshell/linqbridge.html) by [Duncan Smart](https://stackoverflow.com/questions/9033/hidden-features-of-c/10886#10886)
* [Parallel Extensions](http://msdn.microsoft.com/en-us/concurrency/default.aspx) by [Joel Coehoorn](https://stackoverflow.com/questions/9033/hidden-features-of-c/31293#31293) | This isn't C# per se, but I haven't seen anyone who really uses `System.IO.Path.Combine()` to the extent that they should. In fact, the whole Path class is really useful, but **no one uses it!**
I'm willing to bet that every production app has the following code, even though it shouldn't:
```
string path = dir + "\\" + fileName;
``` |
9,044 | <p>I have a base class that represents a database test in TestNG, and I want to specify that all classes extending from this class are of a group "db-test", however I have found that this doesn't seem possible. I have tried the @Test annotation:</p>
<pre><code>@Test(groups = { "db-test" })
public class DBTestBase {
}
</code></pre>
<p>However, this doesn't work because the @Test annotation will try to make a bunch of methods into tests, and warnings/errors pop up in eclipse when the tests are run.</p>
<p>So I tried disabling the test, so at least the groups are assigned:</p>
<pre><code>@Test(enabled = false, groups = { "db-test" })
public class DBTestBase {
}
</code></pre>
<p>but then any @BeforeTest (and other similar annotations) ALSO get disabled... which is of course not what I want.</p>
<p>I would like some way to annotate a class as being of a particular type of group, but it doesn't quite seem possible in TestNG. Does anyone have any other ideas?</p>
| [
{
"answer_id": 9137,
"author": "Sam Merrell",
"author_id": 782,
"author_profile": "https://Stackoverflow.com/users/782",
"pm_score": 1,
"selected": false,
"text": "<p>I'm not sure how the annotation inheritance works for TestNG but this <a href=\"http://web.archive.org/web/20100104232432/http://beust.com/weblog/archives/000170.html\" rel=\"nofollow noreferrer\">article</a> may be of some use.</p>\n<p>Actually, this may <a href=\"http://testng.org/doc/documentation-main.html#annotations\" rel=\"nofollow noreferrer\">help better</a>, look at inheritGroups.</p>\n"
},
{
"answer_id": 75209,
"author": "Alejandro Bologna",
"author_id": 9263,
"author_profile": "https://Stackoverflow.com/users/9263",
"pm_score": 2,
"selected": false,
"text": "<p>TestNG will run all the public methods from a class with a @Test annotation. Maybe you could change the methods you don't want TestNG to run to be non-public</p>\n"
},
{
"answer_id": 154080,
"author": "Jorge Ferreira",
"author_id": 6508,
"author_profile": "https://Stackoverflow.com/users/6508",
"pm_score": 0,
"selected": false,
"text": "<p>You can specify the @Test annotation at method level that allows for maximum flexibility.</p>\n\n<pre><code>public class DBTestBase {\n\n @BeforeTest(groups = \"db-test\")\n public void beforeTest() {\n System.out.println(\"Running before test\");\n }\n\n public void method1() {\n Assert.fail(); // this does not run. It does not belong to 'db-test' group.\n }\n\n @Test(groups = \"db-test\")\n public void testMethod1() {\n Assert.assertTrue(true);\n }\n}\n</code></pre>\n\n<p>Does this works for you or I am missing something from your question.</p>\n"
},
{
"answer_id": 275342,
"author": "VonC",
"author_id": 6309,
"author_profile": "https://Stackoverflow.com/users/6309",
"pm_score": 1,
"selected": false,
"text": "<p>It would seem to me as the following <strong>code-challenge</strong> (community wiki post):</p>\n\n<p>How to be able to execute all test methods of Extended class from the group 'aGlobalGroup' without:</p>\n\n<ul>\n<li>specifying the 'aGlobalGroup' group on the Extended class itself ?</li>\n<li>testing non-annotated public methods of Extended class ?</li>\n</ul>\n\n<p>The first answer is easy:<br>\n<strong>add a class TestNG(groups = { \"aGlobalGroup\" }) on the Base class level</strong></p>\n\n<p>That group will apply to all public methods of both Base class and Extended class.</p>\n\n<p>BUT: even non-testng public methods (with no TestNG annotation) will be included in that group.</p>\n\n<p>CHALLENGE: avoid including those non-TestNG methods.</p>\n\n<pre><code>@Test(groups = { \"aGlobalGroup\" })\npublic class Base {\n\n /**\n * \n */\n @BeforeClass\n public final void setUp() {\n System.out.println(\"Base class: @BeforeClass\");\n }\n\n\n /**\n * Test not part a 'aGlobalGroup', but still included in that group due to the class annotation. <br />\n * Will be executed even if the TestNG class tested is a sub-class.\n */\n @Test(groups = { \"aLocalGroup\" })\n public final void aFastTest() {\n System.out.println(\"Base class: Fast test\");\n }\n\n /**\n * Test not part a 'aGlobalGroup', but still included in that group due to the class annotation. <br />\n * Will be executed even if the TestNG class tested is a sub-class.\n */\n @Test(groups = { \"aLocalGroup\" })\n public final void aSlowTest() {\n System.out.println(\"Base class: Slow test\");\n //throw new IllegalArgumentException(\"oups\");\n }\n\n /**\n * Should not be executed. <br />\n * Yet the global annotation Test on the class would include it in the TestNG methods...\n */\n public final void notATest() {\n System.out.println(\"Base class: NOT a test\");\n }\n\n /**\n * SubClass of a TestNG class. Some of its methods are TestNG methods, other are not. <br />\n * The goal is to check if a group specify in the super-class will include methods of this class. <br />\n * And to avoid including too much methods, such as public methods not intended to be TestNG methods.\n * @author <a href=\"http://stackoverflow.com/users/6309/vonc\">VonC</a>\n */\n public static class Extended extends Base\n {\n /**\n * Test not part a 'aGlobalGroup', but still included in that group due to the super-class annotation. <br />\n * Will be executed even if the TestNG class tested is a sub-class.\n */\n @Test\n public final void anExtendedTest() {\n System.out.println(\"Extended class: An Extended test\");\n }\n\n /**\n * Should not be executed. <br />\n * Yet the global annotation Test on the class would include it in the TestNG methods...\n */ \n public final void notAnExtendedTest() {\n System.out.println(\"Extended class: NOT an Extended test\");\n }\n }\n</code></pre>\n"
},
{
"answer_id": 275353,
"author": "VonC",
"author_id": 6309,
"author_profile": "https://Stackoverflow.com/users/6309",
"pm_score": 3,
"selected": true,
"text": "<p>The answer is through a custom <strong>org.testng.IMethodSelector</strong>:</p>\n\n<p>Its <strong>includeMethod()</strong> can exclude any method we want, like a public not-annotated method.</p>\n\n<p>However, to register a custom <em>Java</em> MethodSelector, you must add it to the <strong>XMLTest</strong> instance managed by any TestRunner, which means you need your own <strong>custom TestRunner</strong>.</p>\n\n<p>But, to build a custom TestRunner, you need to register a <strong>TestRunnerFactory</strong>, through the <strong>-testrunfactory</strong> option.</p>\n\n<p>BUT that -testrunfactory is NEVER taken into account by <strong>TestNG</strong> class... so you need also to define a custom TestNG class :</p>\n\n<ul>\n<li>in order to override the configure(Map) method, </li>\n<li>so you can actually set the TestRunnerFactory</li>\n<li>TestRunnerFactory which will build you a custom TestRunner,</li>\n<li>TestRunner which will set to the XMLTest instance a custom XMLMethodSelector</li>\n<li>XMLMethodSelector which will build a custom IMethodSelector</li>\n<li>IMethodSelector which will exclude any TestNG methods of your choosing!</li>\n</ul>\n\n<p>Ok... it's a nightmare. But it is also a code-challenge, so it must be a little challenging ;)</p>\n\n<p>All the code is available at <a href=\"http://snippets.dzone.com/posts/show/6446\" rel=\"nofollow noreferrer\"><strong>DZone snippets</strong></a>.</p>\n\n<p>As usual for a code challenge:</p>\n\n<ul>\n<li>one java class (and quite a few inner classes)</li>\n<li>copy-paste the class in a 'source/test' directory (since the package is 'test')</li>\n<li>run it (no arguments needed)</li>\n</ul>\n\n<hr>\n\n<p><strong>Update from Mike Stone:</strong></p>\n\n<p>I'm going to accept this because it sounds pretty close to what I ended up doing, but I figured I would add what I did as well.</p>\n\n<p>Basically, I created a Groups annotation that behaves like the groups property of the Test (and other) annotations.</p>\n\n<p>Then, I created a GroupsAnnotationTransformer, which uses IAnnotationTransformer to look at all tests and test classes being defined, then modifies the test to add the groups, which works perfectly with group exclusion and inclusion.</p>\n\n<p>Modify the build to use the new annotation transformer, and it all works perfectly!</p>\n\n<p>Well... the one caveat is that it doesn't add the groups to non-test methods... because at the time I did this, there was another annotation transformer that lets you transform ANYTHING, but it somehow wasn't included in the TestNG I was using for some reason... so it is a good idea to make your before/after annotated methods to alwaysRun=true... which is sufficient for me.</p>\n\n<p>The end result is I can do:</p>\n\n<pre><code>@Groups({ \"myGroup1\", \"myGroup2\"})\npublic class MyTestCase {\n @Test\n @Groups(\"aMethodLevelGroup\")\n public void myTest() {\n }\n}\n</code></pre>\n\n<p>And I made the transformer work with subclassing and everything.</p>\n"
}
] | 2008/08/12 | [
"https://Stackoverflow.com/questions/9044",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/122/"
] | I have a base class that represents a database test in TestNG, and I want to specify that all classes extending from this class are of a group "db-test", however I have found that this doesn't seem possible. I have tried the @Test annotation:
```
@Test(groups = { "db-test" })
public class DBTestBase {
}
```
However, this doesn't work because the @Test annotation will try to make a bunch of methods into tests, and warnings/errors pop up in eclipse when the tests are run.
So I tried disabling the test, so at least the groups are assigned:
```
@Test(enabled = false, groups = { "db-test" })
public class DBTestBase {
}
```
but then any @BeforeTest (and other similar annotations) ALSO get disabled... which is of course not what I want.
I would like some way to annotate a class as being of a particular type of group, but it doesn't quite seem possible in TestNG. Does anyone have any other ideas? | The answer is through a custom **org.testng.IMethodSelector**:
Its **includeMethod()** can exclude any method we want, like a public not-annotated method.
However, to register a custom *Java* MethodSelector, you must add it to the **XMLTest** instance managed by any TestRunner, which means you need your own **custom TestRunner**.
But, to build a custom TestRunner, you need to register a **TestRunnerFactory**, through the **-testrunfactory** option.
BUT that -testrunfactory is NEVER taken into account by **TestNG** class... so you need also to define a custom TestNG class :
* in order to override the configure(Map) method,
* so you can actually set the TestRunnerFactory
* TestRunnerFactory which will build you a custom TestRunner,
* TestRunner which will set to the XMLTest instance a custom XMLMethodSelector
* XMLMethodSelector which will build a custom IMethodSelector
* IMethodSelector which will exclude any TestNG methods of your choosing!
Ok... it's a nightmare. But it is also a code-challenge, so it must be a little challenging ;)
All the code is available at [**DZone snippets**](http://snippets.dzone.com/posts/show/6446).
As usual for a code challenge:
* one java class (and quite a few inner classes)
* copy-paste the class in a 'source/test' directory (since the package is 'test')
* run it (no arguments needed)
---
**Update from Mike Stone:**
I'm going to accept this because it sounds pretty close to what I ended up doing, but I figured I would add what I did as well.
Basically, I created a Groups annotation that behaves like the groups property of the Test (and other) annotations.
Then, I created a GroupsAnnotationTransformer, which uses IAnnotationTransformer to look at all tests and test classes being defined, then modifies the test to add the groups, which works perfectly with group exclusion and inclusion.
Modify the build to use the new annotation transformer, and it all works perfectly!
Well... the one caveat is that it doesn't add the groups to non-test methods... because at the time I did this, there was another annotation transformer that lets you transform ANYTHING, but it somehow wasn't included in the TestNG I was using for some reason... so it is a good idea to make your before/after annotated methods to alwaysRun=true... which is sufficient for me.
The end result is I can do:
```
@Groups({ "myGroup1", "myGroup2"})
public class MyTestCase {
@Test
@Groups("aMethodLevelGroup")
public void myTest() {
}
}
```
And I made the transformer work with subclassing and everything. |
9,052 | <p>I'm working on a spec for a piece of software for my company and as part of the auditing system I think it would be neat if there was a way to grab the current Active Directory user.</p>
<p>Hopefully something like:</p>
<pre><code>Dim strUser as String
strUser = ActiveDirectory.User()
MsgBox "Welcome back, " & strUser
</code></pre>
| [
{
"answer_id": 9054,
"author": "JamesSugrue",
"author_id": 1075,
"author_profile": "https://Stackoverflow.com/users/1075",
"pm_score": 4,
"selected": true,
"text": "<p><a href=\"http://bytes.com/forum/thread717576.html\" rel=\"nofollow noreferrer\">Try this article</a> - I have some code at work that will erm, work if this doesn't...</p>\n\n<p>Relevant quote:</p>\n\n\n\n<blockquote>\n<pre class=\"lang-vba prettyprint-override\"><code>Private Declare Function GetUserName Lib \"advapi32.dll\" Alias \"GetUserNameA\" _\n (ByVal IpBuffer As String, nSize As Long) As Long\nPrivate Declare Function GetComputerName Lib \"kernel32\" Alias \"GetComputerNameA\" _\n (ByVal lpBuffer As String, nSize As Long) As Long\n\nFunction ThisUserName() As String\n Dim LngBufLen As Long\n Dim strUser As String\n\n strUser = String$(15, \" \")\n LngBufLen = 15\n\n If GetUserName(strUser, LngBufLen) = 1 Then\n ThisUserName = Left(strUser, LngBufLen - 1)\n Else\n ThisUserName = \"Unknown\"\n End If\nEnd Function\n\nFunction ThisComputerID() As String\n Dim LngBufLen As Long\n Dim strUser As String\n\n strUser = String$(15, \" \")\n LngBufLen = 15\n\n If GetComputerName(strUser, LngBufLen) = 1 Then\n ThisComputerID = Left(strUser, LngBufLen)\n Else\n ThisComputerID = 0\n End If\nEnd Function\n</code></pre>\n</blockquote>\n"
},
{
"answer_id": 67563,
"author": "David-W-Fenton",
"author_id": 9787,
"author_profile": "https://Stackoverflow.com/users/9787",
"pm_score": 2,
"selected": false,
"text": "<p>Depending on environment variables to remain valid is a bad idea, since they can easily be changed within a user session.</p>\n"
},
{
"answer_id": 249759,
"author": "Yarik",
"author_id": 31415,
"author_profile": "https://Stackoverflow.com/users/31415",
"pm_score": 2,
"selected": false,
"text": "<p>David made a very good point about risk of using environment variables. I can only add that there may be other problems with environment variables. Just look at this actual code fragment from our 5-year old project:</p>\n\n<pre class=\"lang-vb prettyprint-override\"><code>Public Function CurrentWorkbenchUser() As String\n\n ' 2004-01-05, YM: Using Application.CurrentUser for identification of \n ' current user is very problematic (more specifically, extremely \n ' cumbersome to set up and administer for all users). \n ' Therefore, as a quick fix, let's use the OS-level user's \n ' identity instead (NB: the environment variables used below must work fine\n ' on Windows NT/2000/2003 but may not work on Windows 98/ME)\n ' CurrentWorkbenchUser = Application.CurrentUser\n '\n ' 2005-06-13, YM: Environment variables do not work in Windows 2003. \n ' Use Windows Scripting Host (WSH) Networking object instead.\n ' CurrentWorkbenchUser = Environ(\"UserDomain\") & \"\\\" & Environ(\"UserName\")\n '\n ' 2007-01-23, YM: Somewhere between 2007-01-09 and 2007-01-20, \n ' the WshNetwork object stopped working on CONTROLLER3. \n ' We could not find any easy way to fix that.\n ' At the same time, it turns out that environment variables \n ' do work on Windows 2003.\n ' (Apparently, it was some weird configuration problem back in 2005: \n ' we had only one Windows 2003 computer at that time and it was \n ' Will's workstation).\n '\n ' In any case, at the time of this writing, \n ' returning to environment variables \n ' appears to be the simplest solution to the problem on CONTROLLER3.\n ' Dim wshn As New WshNetwork\n ' CurrentWorkbenchUser = wshn.UserDomain & \"\\\" & wshn.UserName\n\n CurrentWorkbenchUser = Environ(\"USERDOMAIN\") & \"\\\" & Environ(\"USERNAME\")\n\nEnd Function\n</code></pre>\n"
},
{
"answer_id": 31496094,
"author": "bgmCoder",
"author_id": 1038866,
"author_profile": "https://Stackoverflow.com/users/1038866",
"pm_score": 2,
"selected": false,
"text": "<p>Here's my version: it will fetch anything you like:</p>\n\n<pre class=\"lang-vb prettyprint-override\"><code>'gets firstname, lastname, fullname or username\nPublic Function GetUser(Optional whatpart = \"username\")\n Dim returnthis As String\n If whatpart = \"username\" Then GetUser = Environ(\"USERNAME\"): Exit Function\n Set objSysInfo = CreateObject(\"ADSystemInfo\")\n Set objUser = GetObject(\"LDAP://\" & objSysInfo.USERNAME)\n Select Case whatpart\n Case \"fullname\": returnthis = objUser.FullName\n Case \"firstname\", \"givenname\": returnthis = objUser.givenName\n Case \"lastname\": returnthis = objUser.LastName\n Case Else: returnthis = Environ(\"USERNAME\")\n End Select\n GetUser = returnthis\nEnd Function\n</code></pre>\n\n<p><a href=\"http://community.spiceworks.com/scripts/show/425-get-the-current-logged-on-user-s-first-last-name\" rel=\"nofollow noreferrer\">I got the original idea from Spiceworks</a>.</p>\n"
}
] | 2008/08/12 | [
"https://Stackoverflow.com/questions/9052",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/428190/"
] | I'm working on a spec for a piece of software for my company and as part of the auditing system I think it would be neat if there was a way to grab the current Active Directory user.
Hopefully something like:
```
Dim strUser as String
strUser = ActiveDirectory.User()
MsgBox "Welcome back, " & strUser
``` | [Try this article](http://bytes.com/forum/thread717576.html) - I have some code at work that will erm, work if this doesn't...
Relevant quote:
>
>
> ```vba
> Private Declare Function GetUserName Lib "advapi32.dll" Alias "GetUserNameA" _
> (ByVal IpBuffer As String, nSize As Long) As Long
> Private Declare Function GetComputerName Lib "kernel32" Alias "GetComputerNameA" _
> (ByVal lpBuffer As String, nSize As Long) As Long
>
> Function ThisUserName() As String
> Dim LngBufLen As Long
> Dim strUser As String
>
> strUser = String$(15, " ")
> LngBufLen = 15
>
> If GetUserName(strUser, LngBufLen) = 1 Then
> ThisUserName = Left(strUser, LngBufLen - 1)
> Else
> ThisUserName = "Unknown"
> End If
> End Function
>
> Function ThisComputerID() As String
> Dim LngBufLen As Long
> Dim strUser As String
>
> strUser = String$(15, " ")
> LngBufLen = 15
>
> If GetComputerName(strUser, LngBufLen) = 1 Then
> ThisComputerID = Left(strUser, LngBufLen)
> Else
> ThisComputerID = 0
> End If
> End Function
>
> ```
>
> |
9,081 | <p>How do I <code>grep</code> and show the preceding and following 5 lines surrounding each matched line?</p>
| [
{
"answer_id": 9083,
"author": "Pat Notz",
"author_id": 825,
"author_profile": "https://Stackoverflow.com/users/825",
"pm_score": 13,
"selected": true,
"text": "<p>For <strong>BSD</strong> or <strong>GNU</strong> <code>grep</code> you can use <code>-B num</code> to set how many lines before the match and <code>-A num</code> for the number of lines after the match.</p>\n\n<pre><code>grep -B 3 -A 2 foo README.txt\n</code></pre>\n\n<p>If you want the same number of lines before and after you can use <code>-C num</code>.</p>\n\n<pre><code>grep -C 3 foo README.txt\n</code></pre>\n\n<p>This will show 3 lines before and 3 lines after.</p>\n"
},
{
"answer_id": 9084,
"author": "dbr",
"author_id": 745,
"author_profile": "https://Stackoverflow.com/users/745",
"pm_score": 5,
"selected": false,
"text": "<pre><code>grep astring myfile -A 5 -B 5\n</code></pre>\n\n<p>That will grep \"myfile\" for \"astring\", and show 5 lines before and after each match</p>\n"
},
{
"answer_id": 9088,
"author": "Stu",
"author_id": 414,
"author_profile": "https://Stackoverflow.com/users/414",
"pm_score": 9,
"selected": false,
"text": "<p><code>-A</code> and <code>-B</code> will work, as will <code>-C n</code> (for <code>n</code> lines of context), or just <code>-n</code> (for <code>n</code> lines of context... as long as n is 1 to 9).</p>\n"
},
{
"answer_id": 9120,
"author": "Sam Merrell",
"author_id": 782,
"author_profile": "https://Stackoverflow.com/users/782",
"pm_score": 4,
"selected": false,
"text": "<p>I normally use</p>\n<pre><code>grep searchstring file -C n # n for number of lines of context up and down\n</code></pre>\n<p>Many of the tools like grep also have really great man files too. I find myself referring to <a href=\"http://unixhelp.ed.ac.uk/CGI/man-cgi?grep\" rel=\"nofollow noreferrer\">grep's man page</a> a lot because there is so much you can do with it.</p>\n<pre><code>man grep\n</code></pre>\n<p>Many GNU tools also have an <a href=\"http://web.archive.org/web/20090427121543/http://www.gnu.org:80/software/grep/doc/grep_toc.html\" rel=\"nofollow noreferrer\">info page</a> that may have more useful information in addition to the man page.</p>\n<pre><code>info grep\n</code></pre>\n"
},
{
"answer_id": 48325,
"author": "elmarco",
"author_id": 1277510,
"author_profile": "https://Stackoverflow.com/users/1277510",
"pm_score": 6,
"selected": false,
"text": "<p><a href=\"http://beyondgrep.com/\" rel=\"noreferrer\">ack</a> works with similar arguments as grep, and accepts <code>-C</code>. But it's usually better for searching through code.</p>\n"
},
{
"answer_id": 19237071,
"author": "Malcolm Boekhoff",
"author_id": 1388639,
"author_profile": "https://Stackoverflow.com/users/1388639",
"pm_score": 4,
"selected": false,
"text": "<p>Search for "17655" in <code>/some/file.txt</code> showing 10 lines context before and after (using <code>Awk</code>), output preceded with line number followed by a colon. Use this on Solaris when <code>grep</code> does not support the <code>-[ACB]</code> options.</p>\n<pre class=\"lang-sh prettyprint-override\"><code>awk '\n\n/17655/ {\n for (i = (b + 1) % 10; i != b; i = (i + 1) % 10) {\n print before[i]\n }\n print (NR ":" ($0))\n a = 10\n}\n\na-- > 0 {\n print (NR ":" ($0))\n}\n\n{\n before[b] = (NR ":" ($0))\n b = (b + 1) % 10\n}' /some/file.txt;\n</code></pre>\n"
},
{
"answer_id": 48225316,
"author": "chtenb",
"author_id": 1546844,
"author_profile": "https://Stackoverflow.com/users/1546844",
"pm_score": 4,
"selected": false,
"text": "<p>Use grep </p>\n\n<pre><code>$ grep --help | grep -i context\nContext control:\n -B, --before-context=NUM print NUM lines of leading context\n -A, --after-context=NUM print NUM lines of trailing context\n -C, --context=NUM print NUM lines of output context\n -NUM same as --context=NUM\n</code></pre>\n"
},
{
"answer_id": 49772613,
"author": "kenorb",
"author_id": 55075,
"author_profile": "https://Stackoverflow.com/users/55075",
"pm_score": 3,
"selected": false,
"text": "<p>Here is the <a href=\"https://www.unix.com/302098992-post2.html?s=4309a3b1b120fabe0d81368129bc8921\" rel=\"noreferrer\">@Ygor solution</a> in <code>awk</code></p>\n\n<pre><code>awk 'c-->0;$0~s{if(b)for(c=b+1;c>1;c--)print r[(NR-c+1)%b];print;c=a}b{r[NR%b]=$0}' b=3 a=3 s=\"pattern\" myfile\n</code></pre>\n\n<p><sup>Note: Replace <code>a</code> and <code>b</code> variables with number of lines before and after.</sup></p>\n\n<p>It's especially useful for system which doesn't support grep's <code>-A</code>, <code>-B</code> and <code>-C</code> parameters.</p>\n"
},
{
"answer_id": 49772704,
"author": "kenorb",
"author_id": 55075,
"author_profile": "https://Stackoverflow.com/users/55075",
"pm_score": 4,
"selected": false,
"text": "<h3><a href=\"https://github.com/BurntSushi/ripgrep\" rel=\"noreferrer\"><code>ripgrep</code></a></h3>\n\n<p>If you care about the performance, use <a href=\"https://github.com/BurntSushi/ripgrep\" rel=\"noreferrer\"><code>ripgrep</code></a> which has similar syntax to <code>grep</code>, e.g.</p>\n\n<pre><code>rg -C5 \"pattern\" .\n</code></pre>\n\n<blockquote>\n <p><code>-C</code>, <code>--context NUM</code> - Show NUM lines before and after each match.</p>\n</blockquote>\n\n<p>There are also parameters such as <code>-A</code>/<code>--after-context</code> and <code>-B</code>/<code>--before-context</code>.</p>\n\n<p>The tool is built on top of <a href=\"https://github.com/rust-lang-nursery/regex\" rel=\"noreferrer\">Rust's regex engine</a> which makes it very <a href=\"http://blog.burntsushi.net/ripgrep/\" rel=\"noreferrer\">efficient</a> on the large data.</p>\n"
},
{
"answer_id": 54055064,
"author": "JBone",
"author_id": 4969849,
"author_profile": "https://Stackoverflow.com/users/4969849",
"pm_score": 2,
"selected": false,
"text": "<pre><code>$ grep thestring thefile -5\n</code></pre>\n\n<p><code>-5</code> gets you <code>5</code> lines above and below the match 'thestring' is equivalent to <code>-C 5</code> or <code>-A 5 -B 5</code>.</p>\n"
},
{
"answer_id": 55096777,
"author": "prime",
"author_id": 2523147,
"author_profile": "https://Stackoverflow.com/users/2523147",
"pm_score": 3,
"selected": false,
"text": "<p>Grep has an option called <code>Context Line Control</code>, you can use the <code>--context</code> in that, simply,</p>\n\n<pre><code>| grep -C 5\n</code></pre>\n\n<p>or</p>\n\n<pre><code>| grep -5\n</code></pre>\n\n<p>Should do the trick</p>\n"
},
{
"answer_id": 59291057,
"author": "franzisk",
"author_id": 2716142,
"author_profile": "https://Stackoverflow.com/users/2716142",
"pm_score": 3,
"selected": false,
"text": "<p>I do it the compact way:</p>\n<pre><code>grep -5 string file\n</code></pre>\n<p>That is the equivalent of:</p>\n<pre><code>grep -A 5 -B 5 string file\n</code></pre>\n"
},
{
"answer_id": 61486000,
"author": "Rose",
"author_id": 466884,
"author_profile": "https://Stackoverflow.com/users/466884",
"pm_score": 4,
"selected": false,
"text": "<p>If you search code often, <a href=\"https://github.com/ggreer/the_silver_searcher\" rel=\"noreferrer\">AG the silver searcher</a> is much more efficient (ie faster) than grep.</p>\n<p>You show context lines by using the <code>-C</code> option.</p>\n<p>Eg:</p>\n<pre><code>ag -C 3 "foo" myFile\n\nline 1\nline 2\nline 3\nline that has "foo"\nline 5\nline 6\nline 7\n</code></pre>\n"
},
{
"answer_id": 72938054,
"author": "Tushar",
"author_id": 9730403,
"author_profile": "https://Stackoverflow.com/users/9730403",
"pm_score": 3,
"selected": false,
"text": "<p><strong>Let's understand using an example.</strong><br>\nWe can use grep with options:</p>\n<pre><code>-A 5 # this will give you 5 lines after searched string.\n-B 5 # this will give you 5 lines before searched string.\n-C 5 # this will give you 5 lines before & after searched string\n</code></pre>\n<p><strong>Example.</strong>\nFile.txt contains 6 lines and following are the operations.</p>\n<pre class=\"lang-bash prettyprint-override\"><code>[abc@xyz]~/% cat file.txt # print all file data\nthis is first line\nthis is 2nd line\nthis is 3rd line\nthis is 4th line\nthis is 5th line\nthis is 6th line\n\n[abc@xyz]~% grep "3rd" file.txt # we are searching for keyword '3rd' in the file\nthis is 3rd line\n\n[abc@xyz]~% grep -A 2 "3rd" file.txt # print 2 lines after finding the searched string\nthis is 3rd line\nthis is 4th line\nthis is 5th line\n\n[abc@xyz]~% grep -B 2 "3rd" file.txt # Print 2 lines before the search string.\nthis is first line\nthis is 2nd line\nthis is 3rd line\n\n[abc@xyz]~% grep -C 2 "3rd" file.txt # print 2 line before and 2 line after the searched string \nthis is first line\nthis is 2nd line\nthis is 3rd line\nthis is 4th line\nthis is 5th line\n</code></pre>\n"
}
] | 2008/08/12 | [
"https://Stackoverflow.com/questions/9081",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/116/"
] | How do I `grep` and show the preceding and following 5 lines surrounding each matched line? | For **BSD** or **GNU** `grep` you can use `-B num` to set how many lines before the match and `-A num` for the number of lines after the match.
```
grep -B 3 -A 2 foo README.txt
```
If you want the same number of lines before and after you can use `-C num`.
```
grep -C 3 foo README.txt
```
This will show 3 lines before and 3 lines after. |
9,104 | <p>I'm thinking that the reason I can't do this is because it might be a huge security hole, but here goes...</p>
<p>I want to have a bookmark on my browser (FF3, preferably) that is only a snippet of javascript code. It would merely construct a URL based on the current date and then do a window.location = on that URL.</p>
<p>I know that I could make a page and keep it on my local machine and just refer to it that way, but I was just wondering if you could bypass that step and actually have the "location" of the bookmark really just be javascript. I could have sworn that this was possible years ago, but I can't find anything that tells me either way now.</p>
| [
{
"answer_id": 9105,
"author": "Pat",
"author_id": 238,
"author_profile": "https://Stackoverflow.com/users/238",
"pm_score": 7,
"selected": true,
"text": "<p>What you want is a <a href=\"http://en.wikipedia.org/wiki/Bookmarklet\" rel=\"noreferrer\">bookmarklet</a> they are easy to create and should work in most major browsers.</p>\n\n<p>Edit: Stack overflow seems not to allow creating bookmarklets in the context of the site, basically you can create a new bookmark and type the following in the location field</p>\n\n<pre>javascript:window.location='http://www.google.com/search?q='+Date()</pre>\n\n<p>to get a bookmarklet that searches google for the current date.</p>\n"
},
{
"answer_id": 9109,
"author": "Dillie-O",
"author_id": 71,
"author_profile": "https://Stackoverflow.com/users/71",
"pm_score": 3,
"selected": false,
"text": "<p>Well, I just created a bookmark in FF3, went back and updated it and added the following test:</p>\n\n<pre><code>javascript:alert('Wacky%20test%20yo');\n</code></pre>\n\n<p>Low and behold, after I saved and loaded, I was able to get my alert.</p>\n\n<p>I'm sure you can work up something similar for your needs.</p>\n"
},
{
"answer_id": 68718,
"author": "scunliffe",
"author_id": 6144,
"author_profile": "https://Stackoverflow.com/users/6144",
"pm_score": 4,
"selected": false,
"text": "<p>One minor catch. <strong>IE</strong> can only handle a <strong>508</strong> character URL in this format. If you save it in IE with a url longer than this, it will truncate without warning and thus fail.</p>\n\n<p>If you need a really complex script, you'll need to use a \"hosted\" bookmarklet, where you have a short bookmark that injects a script tag into the page, to \"call\" your hosted bookmarklet.</p>\n\n<p>It isn't as nice/portable, but its the only workaround.</p>\n"
},
{
"answer_id": 476592,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 3,
"selected": false,
"text": "<p>Google Bookmark</p>\n\n<pre><code>javascript:(function(){var%20a=window,b=document,c=encodeURIComponent,d=a.open(\"http://www.google.com/bookmarks/mark?op=edit&output=popup&bkmk=\"+c(b.location)+\"&title=\"+c(b.title),\"bkmk_popup\",\"left=\"+((a.screenX||a.screenLeft)+10)+\",top=\"+((a.screenY||a.screenTop)+10)+\",height=420px,width=550px,resizable=1,alwaysRaised=1\");a.setTimeout(function(){d.focus()},300)})();\n</code></pre>\n"
},
{
"answer_id": 6764379,
"author": "Joseph Marikle",
"author_id": 854246,
"author_profile": "https://Stackoverflow.com/users/854246",
"pm_score": 5,
"selected": false,
"text": "<p>It is worthy of note that you can put that in a function wrapper as well. imranamajeed nicely illustrated that for us... but apparently I'm too new to the site to up his post. :P</p>\n\n<p>so for clarity:</p>\n\n<pre><code>javascript:(function(){\n location.href = location.href + \"#\";\n})();\n</code></pre>\n\n<p>(the carriage returns did not affect performance in chrome and IE)</p>\n"
}
] | 2008/08/12 | [
"https://Stackoverflow.com/questions/9104",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/232/"
] | I'm thinking that the reason I can't do this is because it might be a huge security hole, but here goes...
I want to have a bookmark on my browser (FF3, preferably) that is only a snippet of javascript code. It would merely construct a URL based on the current date and then do a window.location = on that URL.
I know that I could make a page and keep it on my local machine and just refer to it that way, but I was just wondering if you could bypass that step and actually have the "location" of the bookmark really just be javascript. I could have sworn that this was possible years ago, but I can't find anything that tells me either way now. | What you want is a [bookmarklet](http://en.wikipedia.org/wiki/Bookmarklet) they are easy to create and should work in most major browsers.
Edit: Stack overflow seems not to allow creating bookmarklets in the context of the site, basically you can create a new bookmark and type the following in the location field
```
javascript:window.location='http://www.google.com/search?q='+Date()
```
to get a bookmarklet that searches google for the current date. |
9,122 | <p>I'm trying to use a select statement to get all of the columns from a certain MySQL table except one. Is there a simple way to do this?</p>
<p>EDIT: There are 53 columns in this table (NOT MY DESIGN)</p>
| [
{
"answer_id": 9123,
"author": "Thomas Owens",
"author_id": 572,
"author_profile": "https://Stackoverflow.com/users/572",
"pm_score": 5,
"selected": false,
"text": "<p>To the best of my knowledge, there isn't. You can do something like:</p>\n\n<pre><code>SELECT col1, col2, col3, col4 FROM tbl\n</code></pre>\n\n<p>and manually choose the columns you want. However, if you want a lot of columns, then you might just want to do a:</p>\n\n<pre><code>SELECT * FROM tbl \n</code></pre>\n\n<p>and just ignore what you don't want.</p>\n\n<p>In your particular case, I would suggest:</p>\n\n<pre><code>SELECT * FROM tbl\n</code></pre>\n\n<p>unless you only want a few columns. If you only want four columns, then:</p>\n\n<pre><code>SELECT col3, col6, col45, col 52 FROM tbl\n</code></pre>\n\n<p>would be fine, but if you want 50 columns, then any code that makes the query would become (too?) difficult to read.</p>\n"
},
{
"answer_id": 9124,
"author": "Mike Stone",
"author_id": 122,
"author_profile": "https://Stackoverflow.com/users/122",
"pm_score": 5,
"selected": false,
"text": "<p>You can do:</p>\n\n<pre><code>SELECT column1, column2, column4 FROM table WHERE whatever\n</code></pre>\n\n<p>without getting column3, though perhaps you were looking for a more general solution?</p>\n"
},
{
"answer_id": 9131,
"author": "Stacey Richards",
"author_id": 1142,
"author_profile": "https://Stackoverflow.com/users/1142",
"pm_score": 4,
"selected": false,
"text": "<p>If the column that you didn't want to select had a massive amount of data in it, and you didn't want to include it due to speed issues and you select the other columns often, I would suggest that you create a new table with the one field that you don't usually select with a key to the original table and remove the field from the original table. Join the tables when that extra field is actually required.</p>\n"
},
{
"answer_id": 9135,
"author": "jammycakes",
"author_id": 886,
"author_profile": "https://Stackoverflow.com/users/886",
"pm_score": 3,
"selected": false,
"text": "<p>You could use <a href=\"http://dev.mysql.com/doc/refman/5.0/en/describe.html\" rel=\"noreferrer\">DESCRIBE my_table</a> and use the results of that to generate the SELECT statement dynamically.</p>\n"
},
{
"answer_id": 9146,
"author": "Brian Childress",
"author_id": 721,
"author_profile": "https://Stackoverflow.com/users/721",
"pm_score": 6,
"selected": false,
"text": "<p>Would a View work better in this case? </p>\n\n<pre><code>CREATE VIEW vwTable\nas \nSELECT \n col1 \n , col2 \n , col3 \n , col.. \n , col53 \nFROM table\n</code></pre>\n"
},
{
"answer_id": 9147,
"author": "nlucaroni",
"author_id": 157,
"author_profile": "https://Stackoverflow.com/users/157",
"pm_score": 2,
"selected": false,
"text": "<p>I agree that it isn't sufficient to <code>Select *</code>, if that one you don't need, as mentioned elsewhere, is a BLOB, you don't want to have that overhead creep in. </p>\n\n<p>I would create a <strong>view</strong> with the required data, then you can <code>Select *</code> in comfort --if the database software supports them. Else, put the huge data in another table.</p>\n"
},
{
"answer_id": 9153,
"author": "Gareth Simpson",
"author_id": 147,
"author_profile": "https://Stackoverflow.com/users/147",
"pm_score": 1,
"selected": false,
"text": "<p>If it's always the same one column, then you can create a view that doesn't have it in it.</p>\n\n<p>Otherwise, no I don't think so.</p>\n"
},
{
"answer_id": 9156,
"author": "mbillard",
"author_id": 810,
"author_profile": "https://Stackoverflow.com/users/810",
"pm_score": 2,
"selected": false,
"text": "<p>It is good practice to specify the columns that you are querying even if you query all the columns.</p>\n\n<p>So I would suggest you write the name of each column in the statement (excluding the one you don't want).</p>\n\n<pre><code>SELECT\n col1\n , col2\n , col3\n , col..\n , col53\n\nFROM table\n</code></pre>\n"
},
{
"answer_id": 9217,
"author": "icco",
"author_id": 1063,
"author_profile": "https://Stackoverflow.com/users/1063",
"pm_score": 2,
"selected": false,
"text": "<p>At first I thought you could use regular expressions, but as I've been reading the <a href=\"http://dev.mysql.com/doc/refman/5.0/en/select.html\" rel=\"nofollow noreferrer\">MYSQL docs</a> it seems you can't. If I were you I would use another language (such as PHP) to generate a list of columns you want to get, store it as a string and then use that to generate the SQL. </p>\n"
},
{
"answer_id": 9222,
"author": "OJ.",
"author_id": 611,
"author_profile": "https://Stackoverflow.com/users/611",
"pm_score": 2,
"selected": false,
"text": "<p>While I agree with Thomas' answer (+1 ;)), I'd like to add the caveat that I'll assume the column that you <em>don't</em> want contains hardly any data. If it contains enormous amounts of text, xml or binary blobs, then take the time to select each column individually. Your performance will suffer otherwise. Cheers!</p>\n"
},
{
"answer_id": 1375831,
"author": "rplevy",
"author_id": 163815,
"author_profile": "https://Stackoverflow.com/users/163815",
"pm_score": 2,
"selected": false,
"text": "<p>You can use SQL to generate SQL if you like and evaluate the SQL it produces. This is a general solution as it extracts the column names from the information schema. Here is an example from the Unix command line. </p>\n\n<p>Substituting</p>\n\n<ul>\n<li>MYSQL with your mysql command</li>\n<li>TABLE with the table name</li>\n<li>EXCLUDEDFIELD with excluded field name</li>\n</ul>\n\n\n\n<pre><code>echo $(echo 'select concat(\"select \", group_concat(column_name) , \" from TABLE\") from information_schema.columns where table_name=\"TABLE\" and column_name != \"EXCLUDEDFIELD\" group by \"t\"' | MYSQL | tail -n 1) | MYSQL\n</code></pre>\n\n<p>You will really only need to extract the column names in this way only once to construct the column list excluded that column, and then just use the query you have constructed.</p>\n\n<p>So something like:</p>\n\n<pre><code>column_list=$(echo 'select group_concat(column_name) from information_schema.columns where table_name=\"TABLE\" and column_name != \"EXCLUDEDFIELD\" group by \"t\"' | MYSQL | tail -n 1)\n</code></pre>\n\n<p>Now you can reuse the <code>$column_list</code> string in queries you construct.</p>\n"
},
{
"answer_id": 1495476,
"author": "Mahomedalid",
"author_id": 143393,
"author_profile": "https://Stackoverflow.com/users/143393",
"pm_score": 9,
"selected": true,
"text": "<p>Actually there is a way, you need to have permissions of course for doing this ...</p>\n\n<pre><code>SET @sql = CONCAT('SELECT ', (SELECT REPLACE(GROUP_CONCAT(COLUMN_NAME), '<columns_to_omit>,', '') FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_NAME = '<table>' AND TABLE_SCHEMA = '<database>'), ' FROM <table>');\n\nPREPARE stmt1 FROM @sql;\nEXECUTE stmt1;\n</code></pre>\n\n<p>Replacing <code><table>, <database> and <columns_to_omit></code></p>\n"
},
{
"answer_id": 2019450,
"author": "Soth",
"author_id": 182619,
"author_profile": "https://Stackoverflow.com/users/182619",
"pm_score": 2,
"selected": false,
"text": "<p>Just do</p>\n\n<pre><code>SELECT * FROM table WHERE whatever\n</code></pre>\n\n<p>Then drop the column in you favourite programming language: php</p>\n\n<pre><code>while (($data = mysql_fetch_array($result, MYSQL_ASSOC)) !== FALSE) {\n unset($data[\"id\"]);\n foreach ($data as $k => $v) { \n echo\"$v,\";\n } \n}\n</code></pre>\n"
},
{
"answer_id": 2322117,
"author": "Nathan A",
"author_id": 279884,
"author_profile": "https://Stackoverflow.com/users/279884",
"pm_score": 3,
"selected": false,
"text": "<p>Yes, though it can be high I/O depending on the table here is a workaround I found for it.</p>\n\n<pre><code>SELECT *\nINTO #temp\nFROM table\n\nALTER TABLE #temp DROP COlUMN column_name\n\nSELECT *\nFROM #temp\n</code></pre>\n"
},
{
"answer_id": 4461117,
"author": "bortunac",
"author_id": 544803,
"author_profile": "https://Stackoverflow.com/users/544803",
"pm_score": 6,
"selected": false,
"text": "<p>(Do not try this on a big table, the result might be... surprising !)</p>\n<blockquote>\n<p>TEMPORARY TABLE</p>\n</blockquote>\n<pre><code>DROP TABLE IF EXISTS temp_tb;\nCREATE TEMPORARY TABLE ENGINE=MEMORY temp_tb SELECT * FROM orig_tb;\nALTER TABLE temp_tb DROP col_a, DROP col_f,DROP col_z; #// MySQL\nSELECT * FROM temp_tb;\n</code></pre>\n<p>DROP syntax may vary for databases <a href=\"http://www.oracle-base.com/articles/8i/dropping-columns.php\" rel=\"nofollow noreferrer\">@Denis Rozhnev</a></p>\n"
},
{
"answer_id": 4622233,
"author": "David Poor",
"author_id": 111796,
"author_profile": "https://Stackoverflow.com/users/111796",
"pm_score": 2,
"selected": false,
"text": "<p>I agree with the \"simple\" solution of listing all the columns, but this can be burdensome, and typos can cause lots of wasted time. I use a function \"getTableColumns\" to retrieve the names of my columns suitable for pasting into a query. Then all I need to do is to delete those I don't want. </p>\n\n<pre><code>CREATE FUNCTION `getTableColumns`(tablename varchar(100)) \n RETURNS varchar(5000) CHARSET latin1\nBEGIN\n DECLARE done INT DEFAULT 0;\n DECLARE res VARCHAR(5000) DEFAULT \"\";\n\n DECLARE col VARCHAR(200);\n DECLARE cur1 CURSOR FOR \n select COLUMN_NAME from information_schema.columns \n where TABLE_NAME=@table AND TABLE_SCHEMA=\"yourdatabase\" ORDER BY ORDINAL_POSITION;\n DECLARE CONTINUE HANDLER FOR NOT FOUND SET done = 1;\n OPEN cur1;\n REPEAT\n FETCH cur1 INTO col;\n IF NOT done THEN \n set res = CONCAT(res,IF(LENGTH(res)>0,\",\",\"\"),col);\n END IF;\n UNTIL done END REPEAT;\n CLOSE cur1;\n RETURN res;\n</code></pre>\n\n<p>Your result returns a comma delimited string, for example...</p>\n\n<blockquote>\n <p>col1,col2,col3,col4,...col53</p>\n</blockquote>\n"
},
{
"answer_id": 6624383,
"author": "cwd",
"author_id": 288032,
"author_profile": "https://Stackoverflow.com/users/288032",
"pm_score": 3,
"selected": false,
"text": "<p>My main problem is the many columns I get when joining tables. While this is not the answer to your question (how to select all but certain columns from <em>one</em> table), I think it is worth mentioning that you can specify <code>table.<em></code> to get all columns from a particular table, instead of just specifying <code></em></code>. </p>\n\n<p>Here is an example of how this could be very useful:</p>\n\n<pre>\nselect users.*, phone.meta_value as phone, zipcode.meta_value as zipcode\n\nfrom users\n\nleft join user_meta as phone\non ( (users.user_id = phone.user_id) AND (phone.meta_key = 'phone') )\n\nleft join user_meta as zipcode\non ( (users.user_id = zipcode.user_id) AND (zipcode.meta_key = 'zipcode') )\n\n</pre>\n\n<p>The result is all the columns from the users table, and two additional columns which were joined from the meta table.</p>\n"
},
{
"answer_id": 8035440,
"author": "neurotico79",
"author_id": 1033534,
"author_profile": "https://Stackoverflow.com/users/1033534",
"pm_score": 2,
"selected": false,
"text": "<p>The answer posted by Mahomedalid has a small problem:</p>\n\n<p>Inside replace function code was replacing \"<code><columns_to_delete>,</code>\" by \"\", this replacement has a problem if the field to replace is the last one in the concat string due to the last one doesn't have the char comma \",\" and is not removed from the string.</p>\n\n<p>My proposal:</p>\n\n<pre><code>SET @sql = CONCAT('SELECT ', (SELECT REPLACE(GROUP_CONCAT(COLUMN_NAME),\n '<columns_to_delete>', '\\'FIELD_REMOVED\\'')\n FROM INFORMATION_SCHEMA.COLUMNS\n WHERE TABLE_NAME = '<table>'\n AND TABLE_SCHEMA = '<database>'), ' FROM <table>');\n</code></pre>\n\n<p>Replacing <code><table></code>, <code><database></code> and `</p>\n\n<p>The column removed is replaced by the string \"FIELD_REMOVED\" in my case this works because I was trying to safe memory. (The field I was removing is a BLOB of around 1MB)</p>\n"
},
{
"answer_id": 10598274,
"author": "Junaid",
"author_id": 806440,
"author_profile": "https://Stackoverflow.com/users/806440",
"pm_score": 3,
"selected": false,
"text": "<p>I liked the answer from <code>@Mahomedalid</code> besides this fact informed in comment from <code>@Bill Karwin</code>. The possible problem raised by <code>@Jan Koritak</code> is true I faced that but I have found a trick for that and just want to share it here for anyone facing the issue.</p>\n\n<p>we can replace the REPLACE function with where clause in the sub-query of Prepared statement like this:</p>\n\n<p>Using my table and column name</p>\n\n<pre><code>SET @SQL = CONCAT('SELECT ', (SELECT GROUP_CONCAT(COLUMN_NAME) FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_NAME = 'users' AND COLUMN_NAME NOT IN ('id')), ' FROM users');\nPREPARE stmt1 FROM @SQL;\nEXECUTE stmt1;\n</code></pre>\n\n<p>So, this is going to exclude only the field <code>id</code> but not <code>company_id</code></p>\n"
},
{
"answer_id": 11060861,
"author": "hahakubile",
"author_id": 709096,
"author_profile": "https://Stackoverflow.com/users/709096",
"pm_score": 2,
"selected": false,
"text": "<p>Based on @Mahomedalid answer, I have done some improvements to support \"select all columns except some in mysql\"</p>\n\n<pre><code>SET @database = 'database_name';\nSET @tablename = 'table_name';\nSET @cols2delete = 'col1,col2,col3';\n\nSET @sql = CONCAT(\n'SELECT ', \n(\n SELECT GROUP_CONCAT( IF(FIND_IN_SET(COLUMN_NAME, @cols2delete), NULL, COLUMN_NAME ) )\n FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_NAME = @tablename AND TABLE_SCHEMA = @database\n), \n' FROM ',\n@tablename);\n\nSELECT @sql;\n</code></pre>\n\n<p>If you do have a lots of cols, use this sql to change group_concat_max_len</p>\n\n<pre><code>SET @@group_concat_max_len = 2048;\n</code></pre>\n"
},
{
"answer_id": 15012522,
"author": "Nick",
"author_id": 1953467,
"author_profile": "https://Stackoverflow.com/users/1953467",
"pm_score": -1,
"selected": false,
"text": "<p>Im pretty late at throing out an answer for this, put this is the way i have always done it and frankly, its 100 times better and neater than the best answer, i only hope someone will see it. And find it useful</p>\n\n<pre><code> //create an array, we will call it here. \n $here = array();\n //create an SQL query in order to get all of the column names\n $SQL = \"SHOW COLUMNS FROM Table\";\n //put all of the column names in the array\n foreach($conn->query($SQL) as $row) {\n $here[] = $row[0];\n }\n //now search through the array containing the column names for the name of the column, in this case i used the common ID field as an example\n $key = array_search('ID', $here);\n //now delete the entry\n unset($here[$key]);\n</code></pre>\n"
},
{
"answer_id": 15571552,
"author": "Kilise",
"author_id": 1715913,
"author_profile": "https://Stackoverflow.com/users/1715913",
"pm_score": 2,
"selected": false,
"text": "<p>I wanted this too so I created a function instead.</p>\n\n<pre><code>public function getColsExcept($table,$remove){\n $res =mysql_query(\"SHOW COLUMNS FROM $table\");\n\n while($arr = mysql_fetch_assoc($res)){\n $cols[] = $arr['Field'];\n }\n if(is_array($remove)){\n $newCols = array_diff($cols,$remove);\n return \"`\".implode(\"`,`\",$newCols).\"`\";\n }else{\n $length = count($cols);\n for($i=0;$i<$length;$i++){\n if($cols[$i] == $remove)\n unset($cols[$i]);\n }\n return \"`\".implode(\"`,`\",$cols).\"`\";\n }\n}\n</code></pre>\n\n<p>So how it works is that you enter the table, then a column you don't want or as in an array: array(\"id\",\"name\",\"whatevercolumn\")</p>\n\n<p>So in select you could use it like this:</p>\n\n<pre><code>mysql_query(\"SELECT \".$db->getColsExcept('table',array('id','bigtextcolumn')).\" FROM table\");\n</code></pre>\n\n<p>or</p>\n\n<pre><code>mysql_query(\"SELECT \".$db->getColsExcept('table','bigtextcolumn').\" FROM table\");\n</code></pre>\n"
},
{
"answer_id": 17093312,
"author": "Sean O",
"author_id": 5701,
"author_profile": "https://Stackoverflow.com/users/5701",
"pm_score": 5,
"selected": false,
"text": "<p>If you are looking to exclude the value of a field, e.g. for security concerns / sensitive info, you can retrieve that column as null.</p>\n\n<p>e.g.</p>\n\n<pre><code>SELECT *, NULL AS salary FROM users\n</code></pre>\n"
},
{
"answer_id": 17719025,
"author": "Suraj",
"author_id": 1065227,
"author_profile": "https://Stackoverflow.com/users/1065227",
"pm_score": 4,
"selected": false,
"text": "<p>While trying the solutions by @Mahomedalid and @Junaid I found a problem. So thought of sharing it. If the column name is having spaces or hyphens like check-in then the query will fail. The simple workaround is to use backtick around column names. The modified query is below</p>\n\n<pre><code>SET @SQL = CONCAT('SELECT ', (SELECT GROUP_CONCAT(CONCAT(\"`\", COLUMN_NAME, \"`\")) FROM\nINFORMATION_SCHEMA.COLUMNS WHERE TABLE_NAME = 'users' AND COLUMN_NAME NOT IN ('id')), ' FROM users');\nPREPARE stmt1 FROM @SQL;\nEXECUTE stmt1;\n</code></pre>\n"
},
{
"answer_id": 17747307,
"author": "Bhavik Shah",
"author_id": 1680256,
"author_profile": "https://Stackoverflow.com/users/1680256",
"pm_score": 2,
"selected": false,
"text": "<p>May be I have a solution to <strong>Jan Koritak's</strong> pointed out discrepancy</p>\n\n<pre><code>SELECT CONCAT('SELECT ',\n( SELECT GROUP_CONCAT(t.col)\nFROM\n(\n SELECT CASE\n WHEN COLUMN_NAME = 'eid' THEN NULL\n ELSE COLUMN_NAME\n END AS col \n FROM INFORMATION_SCHEMA.COLUMNS \n WHERE TABLE_NAME = 'employee' AND TABLE_SCHEMA = 'test'\n) t\nWHERE t.col IS NOT NULL) ,\n' FROM employee' );\n</code></pre>\n\n<p><strong>Table :</strong> </p>\n\n<pre><code>SELECT table_name,column_name \nFROM INFORMATION_SCHEMA.COLUMNS \nWHERE TABLE_NAME = 'employee' AND TABLE_SCHEMA = 'test'\n</code></pre>\n\n<p>================================</p>\n\n<pre><code>table_name column_name\nemployee eid\nemployee name_eid\nemployee sal\n</code></pre>\n\n<p>================================</p>\n\n<p><strong>Query Result:</strong></p>\n\n<pre><code>'SELECT name_eid,sal FROM employee'\n</code></pre>\n"
},
{
"answer_id": 20396621,
"author": "Héctor Paúl Cervera-García",
"author_id": 2814721,
"author_profile": "https://Stackoverflow.com/users/2814721",
"pm_score": 1,
"selected": false,
"text": "<p>I would like to add another point of view in order to solve this problem, specially if you have a small number of columns to remove.</p>\n\n<p>You could use a DB tool like <a href=\"http://www.mysql.fr/products/workbench/\" rel=\"nofollow\">MySQL Workbench</a> in order to generate the select statement for you, so you just have to manually remove those columns for the generated statement and copy it to your SQL script.</p>\n\n<p>In MySQL Workbench the way to generate it is: </p>\n\n<p>Right click on the table -> send to Sql Editor -> Select All Statement.</p>\n"
},
{
"answer_id": 21169876,
"author": "HLGEM",
"author_id": 9034,
"author_profile": "https://Stackoverflow.com/users/9034",
"pm_score": -1,
"selected": false,
"text": "<p>Select * is a SQL antipattern. It should not be used in production code for many reasons including:</p>\n\n<p>It takes a tiny bit longer to process. When things are run millions of times, those tiny bits can matter. A slow database where the slowness is caused by this type of sloppy coding throughout is the hardest kind to performance tune.</p>\n\n<p>It means you are probably sending more data than you need which causes both server and network bottlenecks. If you have an inner join, the chances of sending more data than you need are 100%. </p>\n\n<p>It causes maintenance problems especially when you have added new columns that you do not want seen everywhere. Further if you have a new column, you may need to do something to the interface to determine what to do with that column. </p>\n\n<p>It can break views (I know this is true in SQl server, it may or may not be true in mysql). </p>\n\n<p>If someone is silly enough to rebuild the tables with the columns in a differnt order (which you shouldn't do but it happens all teh time), all sorts of code can break. Espcially code for an insert for example where suddenly you are putting the city into the address_3 field becasue without specifying, the database can only go on the order of the columns. This is bad enough when the data types change but worse when the swapped columns have the same datatype becasue you can go for sometime inserting bad data that is a mess to clean up. You need to care about data integrity. </p>\n\n<p>If it is used in an insert, it will break the insert if a new column is added in one table but not the other. </p>\n\n<p>It might break triggers. Trigger problems can be difficult to diagnose. </p>\n\n<p>Add up all this against the time it take to add in the column names (heck you may even have an interface that allows you to drag over the columns names (I know I do in SQL Server, I'd bet there is some way to do this is some tool you use to write mysql queries.) Let's see, \"I can cause maintenance problems, I can cause performance problems and I can cause data integrity problems, but hey I saved five minutes of dev time.\" Really just put in the specific columns you want.</p>\n\n<p>I also suggest you read this book:\n<a href=\"https://rads.stackoverflow.com/amzn/click/com/B00A376BB2\" rel=\"nofollow noreferrer\" rel=\"nofollow noreferrer\">http://www.amazon.com/SQL-Antipatterns-Programming-Pragmatic-Programmers-ebook/dp/B00A376BB2/ref=sr_1_1?s=digital-text&ie=UTF8&qid=1389896688&sr=1-1&keywords=sql+antipatterns</a></p>\n"
},
{
"answer_id": 31871062,
"author": "neelabh",
"author_id": 633638,
"author_profile": "https://Stackoverflow.com/users/633638",
"pm_score": 2,
"selected": false,
"text": "<p>I agree with @Mahomedalid's answer, but I didn't want to do something like a prepared statement and I didn't want to type all the fields, so what I had was a silly solution. </p>\n\n<p>Go to the table in phpmyadmin->sql->select, it dumps the query: copy, replace and done! :)</p>\n"
},
{
"answer_id": 56431536,
"author": "Eaten by a Grue",
"author_id": 1767412,
"author_profile": "https://Stackoverflow.com/users/1767412",
"pm_score": 1,
"selected": false,
"text": "<p>The accepted answer has several shortcomings.</p>\n\n<ul>\n<li>It fails where the table or column names requires backticks</li>\n<li>It fails if the column you want to omit is last in the list</li>\n<li>It requires listing the table name twice (once for the select and another for the query text) which is redundant and unnecessary</li>\n<li>It can potentially return column names in the <em>wrong order</em></li>\n</ul>\n\n<p>All of these issues can be overcome by simply including backticks in the <code>SEPARATOR</code> for your <code>GROUP_CONCAT</code> and using a <code>WHERE</code> condition instead of <code>REPLACE()</code>. For my purposes (and I imagine many others') I wanted the column names returned in the same order that they appear in the table itself. To achieve this, here we use an explicit <code>ORDER BY</code> clause inside of the <code>GROUP_CONCAT()</code> function:</p>\n\n<pre><code>SELECT CONCAT(\n 'SELECT `',\n GROUP_CONCAT(COLUMN_NAME ORDER BY `ORDINAL_POSITION` SEPARATOR '`,`'),\n '` FROM `',\n `TABLE_SCHEMA`,\n '`.`',\n TABLE_NAME,\n '`;'\n)\nFROM INFORMATION_SCHEMA.COLUMNS\nWHERE `TABLE_SCHEMA` = 'my_database'\n AND `TABLE_NAME` = 'my_table'\n AND `COLUMN_NAME` != 'column_to_omit';\n</code></pre>\n"
},
{
"answer_id": 57268792,
"author": "MR_AMDEV",
"author_id": 10114772,
"author_profile": "https://Stackoverflow.com/users/10114772",
"pm_score": 1,
"selected": false,
"text": "<p>I have a suggestion but not a solution.\nIf some of your columns have a larger data sets then you should try with following</p>\n\n<pre><code>SELECT *, LEFT(col1, 0) AS col1, LEFT(col2, 0) as col2 FROM table\n</code></pre>\n"
},
{
"answer_id": 64573062,
"author": "Adam",
"author_id": 2311074,
"author_profile": "https://Stackoverflow.com/users/2311074",
"pm_score": 0,
"selected": false,
"text": "<p>If you use MySQL Workbench you can right-click your table and click <code>Send to sql editor</code> and then <code>Select All Statement</code> This will create an statement where all fields are listed, like this:</p>\n<pre><code>SELECT `purchase_history`.`id`,\n `purchase_history`.`user_id`,\n `purchase_history`.`deleted_at`\nFROM `fs_normal_run_2`.`purchase_history`;\nSELECT * FROM fs_normal_run_2.purchase_history;\n</code></pre>\n<p>Now you can just remove those that you dont want.</p>\n"
},
{
"answer_id": 65052272,
"author": "DropHit",
"author_id": 1656124,
"author_profile": "https://Stackoverflow.com/users/1656124",
"pm_score": 2,
"selected": false,
"text": "<p>I use this work around although it may be "Off topic" - using mysql workbench and the query builder -</p>\n<ol>\n<li>Open the columns view</li>\n<li>Shift select all the columns you want in your query (in your case all but one which is what i do)</li>\n<li>Right click and select send to SQL Editor-> name short.</li>\n<li>Now you have the list and you can then copy paste the query to where ever.</li>\n</ol>\n<p><a href=\"https://i.stack.imgur.com/NNnAY.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/NNnAY.png\" alt=\"enter image description here\" /></a></p>\n"
},
{
"answer_id": 70622146,
"author": "Lukas Eder",
"author_id": 521799,
"author_profile": "https://Stackoverflow.com/users/521799",
"pm_score": 0,
"selected": false,
"text": "<p>The question was about MySQL, but I still think it's worth mentioning that at least <a href=\"https://blog.jooq.org/the-useful-bigquery-except-syntax/\" rel=\"nofollow noreferrer\">Google BigQuery and H2 support a <code>* EXCEPT</code> syntax natively</a>, e.g.</p>\n<pre class=\"lang-sql prettyprint-override\"><code>SELECT * FROM actor\n</code></pre>\n<p>Producing:</p>\n<pre><code>|actor_id|first_name|last_name |last_update |\n|--------|----------|------------|-----------------------|\n|1 |PENELOPE |GUINESS |2006-02-15 04:34:33.000|\n|2 |NICK |WAHLBERG |2006-02-15 04:34:33.000|\n|3 |ED |CHASE |2006-02-15 04:34:33.000|\n</code></pre>\n<p>Whereas</p>\n<pre class=\"lang-sql prettyprint-override\"><code>SELECT * EXCEPT (last_update) FROM actor\n</code></pre>\n<p>Producing:</p>\n<pre><code>|actor_id|first_name|last_name |\n|--------|----------|------------|\n|1 |PENELOPE |GUINESS |\n|2 |NICK |WAHLBERG |\n|3 |ED |CHASE |\n</code></pre>\n<p>Maybe, a future version of MySQL will support this syntax as well?</p>\n"
}
] | 2008/08/12 | [
"https://Stackoverflow.com/questions/9122",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/44/"
] | I'm trying to use a select statement to get all of the columns from a certain MySQL table except one. Is there a simple way to do this?
EDIT: There are 53 columns in this table (NOT MY DESIGN) | Actually there is a way, you need to have permissions of course for doing this ...
```
SET @sql = CONCAT('SELECT ', (SELECT REPLACE(GROUP_CONCAT(COLUMN_NAME), '<columns_to_omit>,', '') FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_NAME = '<table>' AND TABLE_SCHEMA = '<database>'), ' FROM <table>');
PREPARE stmt1 FROM @sql;
EXECUTE stmt1;
```
Replacing `<table>, <database> and <columns_to_omit>` |
9,191 | <p>I'd like to ask a question then follow it up with my own answer, but also see what answers other people have.</p>
<p>We have two large files which we'd like to read from two separate threads concurrently. One thread will sequentially read fileA while the other thread will sequentially read fileB. There is no locking or communication between the threads, both are sequentially reading as fast as they can, and both are immediately discarding the data they read.</p>
<p>Our experience with this setup on Windows is very poor. The combined throughput of the two threads is in the order of 2-3 MiB/sec. The drive seems to be spending most of its time seeking backwards and forwards between the two files, presumably reading very little after each seek.</p>
<p>If we disable one of the threads and temporarily look at the performance of a single thread then we get much better bandwidth (~45 MiB/sec for this machine). So clearly the bad two-thread performance is an artefact of the OS disk scheduler.</p>
<p><strong>Is there anything we can do to improve the concurrent thread read performance?</strong> Perhaps by using different APIs or by tweaking the OS disk scheduler parameters in some way.</p>
<p>Some details:</p>
<p>The files are in the order of 2 GiB each on a machine with 2GiB of RAM. For the purpose of this question we consider them not to be cached and perfectly defragmented. We have used defrag tools and rebooted to ensure this is the case.</p>
<p>We are using no special APIs to read these files. The behaviour is repeatable across various bog-standard APIs such as Win32's CreateFile, C's fopen, C++'s std::ifstream, Java's FileInputStream, etc.</p>
<p>Each thread spins in a loop making calls to the read function. We have varied the number of bytes requested from the API each iteration from values between 1KiB up to 128MiB. Varying this has had no effect, so clearly the amount the OS is physically reading after each disk seek is not dictated by this number. This is exactly what should be expected.</p>
<p>The dramatic difference between one-thread and two-thread performance is repeatable across Windows 2000, Windows XP (32-bit and 64-bit), Windows Server 2003, and also with and without hardware RAID5.</p>
| [
{
"answer_id": 9193,
"author": "pauldoo",
"author_id": 755,
"author_profile": "https://Stackoverflow.com/users/755",
"pm_score": 3,
"selected": false,
"text": "<p>I'd like to add some further notes in my response. All other non-Microsoft operating systems we have tested do not suffer from this problem. Linux, FreeBSD, and Mac OS X (this final one on different hardware) all degrade much more gracefully in terms of aggregate bandwidth when moving from one thread to two. Linux for example degraded from ~45 MiB/sec to ~42 MiB/sec. These other operating systems must be reading larger chunks of the file between each seek, and therefor not spending nearly all their time waiting on the disk to seek.</p>\n\n<p>Our solution for Windows is to pass the <code>FILE_FLAG_NO_BUFFERING</code> flag to <code>CreateFile</code> and use large (~16MiB) reads in each call to <code>ReadFile</code>. This is suboptimal for several reasons:</p>\n\n<ul>\n<li>Files don't get cached when read like this, so there are none of the advantages that caching normally gives.</li>\n<li>The constraints when working with this flag are much more complicated than normal reading (alignment of read buffers to page boundaries, etc).</li>\n</ul>\n\n<p>(As a final remark. Does this explain why swapping under Windows is so hellish? Ie, Windows is incapable of doing IO to multiple files concurrently with any efficiency, so while swapping all other IO operations are forced to be disproportionately slow.)</p>\n\n<hr>\n\n<p><em>Edit to add some further details for Will Dean:</em></p>\n\n<p>Of course across these different hardware configurations the raw figures did change (sometimes substantially). The problem however is the consistent degradation in performance that only Windows suffers when moving from one thread to two. Here is a summary of the machines tested:</p>\n\n<ul>\n<li>Several Dell workstations (Intel Xeon) of various ages running Windows 2000, Windows XP (32-bit), and Windows XP (64-bit) with single drive.</li>\n<li>A Dell 1U server (Intel Xeon) running Windows Server 2003 (64-bit) with RAID 1+0.</li>\n<li>An HP workstation (AMD Opteron) with Windows XP (64-bit), and Windows Server 2003, and hardware RAID 5.</li>\n<li>My home unbranded PC (AMD Athlon64) running Windows XP (32-bit), FreeBSD (64-bit), and Linux (64-bit) with single drive.</li>\n<li>My home MacBook (Intel Core1) running Mac OS X, single SATA drive.</li>\n<li>My home <a href=\"http://koolu.com/Koolu-WE-Appliance/Works-Everywhere-Appliance.html\" rel=\"nofollow noreferrer\">Koolu</a> PC running Linux. Vastly underpowered compared to the other systems but I demonstrated that even this machine can outperform a Windows server with RAID5 when doing multi-threaded disk reads.</li>\n</ul>\n\n<p>CPU usage on all of these systems was very low during the tests and anti-virus was disabled.</p>\n\n<p>I forgot to mention before but we also tried the normal Win32 <code>CreateFile</code> API with the <code>FILE_FLAG_SEQUENTIAL_SCAN</code> flag set. This flag didn't fix the problem.</p>\n"
},
{
"answer_id": 9201,
"author": "Stacey Richards",
"author_id": 1142,
"author_profile": "https://Stackoverflow.com/users/1142",
"pm_score": 0,
"selected": false,
"text": "<p>I would create some kind of in memory thread safe lock. Each thread could wait on the lock until it was free. When the lock becomes free, take the lock and read the file for a defined length of time or a defined amount of data, then release the lock for any other waiting threads.</p>\n"
},
{
"answer_id": 9215,
"author": "Will Dean",
"author_id": 987,
"author_profile": "https://Stackoverflow.com/users/987",
"pm_score": 1,
"selected": false,
"text": "<p>It does seem a little strange that you see no difference across quite a wide range of windows versions and nothing between a single drive and hardware raid-5.</p>\n\n<p>It's only 'gut feel', but that does make me doubtful that this is really a simple seeking problem. Other than the OS X and the Raid5, was all this tried on the same machine - have you tried another machine? Is your CPU usage basically zero during this test?</p>\n\n<p>What's the shortest app you can write which demonstrates this problem? - I would be interested to try it here.</p>\n"
},
{
"answer_id": 9267,
"author": "graham.reeds",
"author_id": 342,
"author_profile": "https://Stackoverflow.com/users/342",
"pm_score": 0,
"selected": false,
"text": "<p>Do you use <a href=\"http://msdn.microsoft.com/en-us/library/aa363862(VS.85).aspx\" rel=\"nofollow noreferrer\">IOCompletionPorts</a> under Windows? Windows via C++ has an in-depth chapter on this subject and as luck would have it, <a href=\"http://msdn.microsoft.com/en-us/library/cc500399.aspx\" rel=\"nofollow noreferrer\">it is also available on MSDN</a>.</p>\n"
},
{
"answer_id": 9616,
"author": "Will Dean",
"author_id": 987,
"author_profile": "https://Stackoverflow.com/users/987",
"pm_score": 0,
"selected": false,
"text": "<p>Paul - saw the update. Very interesting.</p>\n\n<p>It would be interesting to try it on Vista or Win2008, as people seem to be reporting some considerable I/O improvements on these in some circumstances.</p>\n\n<p>My only suggestion about a different API would be to try memory mapping the files - have you tried that? Unfortunately at 2GB per file, you're not going to be able to map multiple whole files on a 32-bit machine, which means this isn't quite as trivial as it might be.</p>\n"
},
{
"answer_id": 9826,
"author": "Andrea Bertani",
"author_id": 1005,
"author_profile": "https://Stackoverflow.com/users/1005",
"pm_score": 5,
"selected": true,
"text": "<p>The problem seems to be in Windows I/O scheduling policy. According to what I found <a href=\"http://engr.smu.edu/~kocan/7343/fall05/slides/chapter11.ppt\" rel=\"noreferrer\" title=\"I/O management and disk scheduling\">here</a> there are many ways for an O.S. to schedule disk requests. While Linux and others can choose between different policies, before Vista Windows was locked in a single policy: a FIFO queue, where all requests where splitted in 64 KB blocks. I believe that this policy is the cause for the problem you are experiencing: the scheduler will mix requests from the two threads, causing continuous seek between different areas of the disk.<br>\nNow, the good news is that according to <a href=\"http://technet.microsoft.com/en-us/magazine/cc162494.aspx\" rel=\"noreferrer\" title=\"Inside Windows Vista Kernel\">here</a> and <a href=\"http://widefox.pbwiki.com/IO\" rel=\"noreferrer\" title=\"Kernel Comparison: Linux (2.6.22) versus Windows (Vista)\">here</a>, Vista introduced a smarter disk scheduler, where you can set the priority of your requests and also allocate a minimum badwidth for your process.<br>\nThe bad news is that I found no way to change disk policy or buffers size in previous versions of Windows. Also, even if raising disk I/O priority of your process will boost the performance against the other processes, you still have the problems of your threads competing against each other.<br>\nWhat I can suggest is to modify your software by introducing a self-made disk access policy.<br>\nFor example, you could use a policy like this in your thread B (similar for Thread A): </p>\n\n<pre><code>if THREAD A is reading from disk then wait for THREAD A to stop reading or wait for X ms\nRead for X ms (or Y MB)\nStop reading and check status of thread A again \n</code></pre>\n\n<p>You could use semaphores for status checking or you could use perfmon counters to get the status of the actual disk queue.\nThe values of X and/or Y could also be auto-tuned by checking the actual trasfer rates and slowly modify them, thus maximizing the throughtput when the application runs on different machines and/or O.S. You could find that cache, memory or RAID levels affect them in a way or the other, but with auto-tuning you will always get the best performance in every scenario.</p>\n"
}
] | 2008/08/12 | [
"https://Stackoverflow.com/questions/9191",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/755/"
] | I'd like to ask a question then follow it up with my own answer, but also see what answers other people have.
We have two large files which we'd like to read from two separate threads concurrently. One thread will sequentially read fileA while the other thread will sequentially read fileB. There is no locking or communication between the threads, both are sequentially reading as fast as they can, and both are immediately discarding the data they read.
Our experience with this setup on Windows is very poor. The combined throughput of the two threads is in the order of 2-3 MiB/sec. The drive seems to be spending most of its time seeking backwards and forwards between the two files, presumably reading very little after each seek.
If we disable one of the threads and temporarily look at the performance of a single thread then we get much better bandwidth (~45 MiB/sec for this machine). So clearly the bad two-thread performance is an artefact of the OS disk scheduler.
**Is there anything we can do to improve the concurrent thread read performance?** Perhaps by using different APIs or by tweaking the OS disk scheduler parameters in some way.
Some details:
The files are in the order of 2 GiB each on a machine with 2GiB of RAM. For the purpose of this question we consider them not to be cached and perfectly defragmented. We have used defrag tools and rebooted to ensure this is the case.
We are using no special APIs to read these files. The behaviour is repeatable across various bog-standard APIs such as Win32's CreateFile, C's fopen, C++'s std::ifstream, Java's FileInputStream, etc.
Each thread spins in a loop making calls to the read function. We have varied the number of bytes requested from the API each iteration from values between 1KiB up to 128MiB. Varying this has had no effect, so clearly the amount the OS is physically reading after each disk seek is not dictated by this number. This is exactly what should be expected.
The dramatic difference between one-thread and two-thread performance is repeatable across Windows 2000, Windows XP (32-bit and 64-bit), Windows Server 2003, and also with and without hardware RAID5. | The problem seems to be in Windows I/O scheduling policy. According to what I found [here](http://engr.smu.edu/~kocan/7343/fall05/slides/chapter11.ppt "I/O management and disk scheduling") there are many ways for an O.S. to schedule disk requests. While Linux and others can choose between different policies, before Vista Windows was locked in a single policy: a FIFO queue, where all requests where splitted in 64 KB blocks. I believe that this policy is the cause for the problem you are experiencing: the scheduler will mix requests from the two threads, causing continuous seek between different areas of the disk.
Now, the good news is that according to [here](http://technet.microsoft.com/en-us/magazine/cc162494.aspx "Inside Windows Vista Kernel") and [here](http://widefox.pbwiki.com/IO "Kernel Comparison: Linux (2.6.22) versus Windows (Vista)"), Vista introduced a smarter disk scheduler, where you can set the priority of your requests and also allocate a minimum badwidth for your process.
The bad news is that I found no way to change disk policy or buffers size in previous versions of Windows. Also, even if raising disk I/O priority of your process will boost the performance against the other processes, you still have the problems of your threads competing against each other.
What I can suggest is to modify your software by introducing a self-made disk access policy.
For example, you could use a policy like this in your thread B (similar for Thread A):
```
if THREAD A is reading from disk then wait for THREAD A to stop reading or wait for X ms
Read for X ms (or Y MB)
Stop reading and check status of thread A again
```
You could use semaphores for status checking or you could use perfmon counters to get the status of the actual disk queue.
The values of X and/or Y could also be auto-tuned by checking the actual trasfer rates and slowly modify them, thus maximizing the throughtput when the application runs on different machines and/or O.S. You could find that cache, memory or RAID levels affect them in a way or the other, but with auto-tuning you will always get the best performance in every scenario. |
9,240 | <p>Say you have an application divided into 3-tiers: GUI, business logic, and data access. In your business logic layer you have described your business objects: getters, setters, accessors, and so on... you get the idea. The interface to the business logic layer guarantees safe usage of the business logic, so all the methods and accessors you call will validate input. </p>
<p>This great when you first write the UI code, because you have a neatly defined interface that you can trust.</p>
<p>But here comes the tricky part, when you start writing the data access layer, the interface to the business logic does not accommodate your needs. You need to have more accessors and getters to set fields which are/used to be hidden. Now you are forced to erode the interface of your business logic; now it is possible set fields from the UI layer, which the UI layer has no business setting. </p>
<p>Because of the changes needed for the data access layer, the interface to the business logic has eroded to the point where it is possible to even set the business logic with invalid data. Thus, the interface does not guarantee safe usage anymore.</p>
<p>I hope I explained the problem clearly enough. How do you prevent interface eroding, maintain information hiding and encapsulation, and yet still accommodate different interface needs among different layers? </p>
| [
{
"answer_id": 9250,
"author": "Lars Mæhlum",
"author_id": 960,
"author_profile": "https://Stackoverflow.com/users/960",
"pm_score": 0,
"selected": false,
"text": "<p>I always create a separate assembly that contains: </p>\n\n<ul>\n<li>A lot of small Interfaces (think ICreateRepository, IReadRepository, IReadListRepsitory.. the list goes on and most of them relies heavily on generics) </li>\n<li>A lot of concrete Interfaces, like an IPersonRepository, that inherits from IReadRepository, you get the point..<br>\nAnything you cannot describe with just the smaller interfaces, you put into the concrete interface.<br>\nAs long as you use the IPersonRepository to declare your object, you get a clean, consistent interface to work with. But the kicker is, you can also make a class that takes f.x. a ICreateRepository in its constructor, so the code will end up being very easy to do some really funky stuff with. There are also interfaces for the Services in the business tier here.</li>\n<li>At last i stick all the domain objects into the extra assembly, just to make the code base itself a bit cleaner and more loosely coupled. These objects dont have any logic, they are just a common way to describe the data for all 3+ layers.</li>\n</ul>\n\n<p>Btw. Why would you define methods in the business logic tier to accommodate the data tier?<br>\nThe data tier should have no reason to even know there is a business tier..</p>\n"
},
{
"answer_id": 9251,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 0,
"selected": false,
"text": "<p>It could be a solution, as it would not erode the interface. I guess you could have a class like this:</p>\n\n<pre><code>public class BusinessObjectRecord : BusinessObject\n{\n}\n</code></pre>\n"
},
{
"answer_id": 9257,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 0,
"selected": false,
"text": "<p>What do you mean by that the data tier should not be aware of the business logic tier? How would you fill an business object with data?</p>\n\n<p>I often do this:</p>\n\n<pre><code>namespace Data\n{\n public class BusinessObjectDataManager\n {\n public void SaveObject(BusinessObject object)\n {\n // Exec stored procedure\n {\n }\n}\n</code></pre>\n"
},
{
"answer_id": 9258,
"author": "Dan",
"author_id": 230,
"author_profile": "https://Stackoverflow.com/users/230",
"pm_score": 3,
"selected": false,
"text": "<p>This is a classic problem - separating your domain model from your database model. There are several ways to attack it, it really depends on the size of your project in my opinion. You could use the repository pattern as others have said. If you are using .net or java you could use <a href=\"http://www.hibernate.org/343.html\" rel=\"nofollow noreferrer\">NHibernate</a> or <a href=\"http://www.hibernate.org/\" rel=\"nofollow noreferrer\">Hibernate</a>. </p>\n\n<p>What I do is use <a href=\"http://en.wikipedia.org/wiki/Test-driven_development\" rel=\"nofollow noreferrer\">Test Driven Development</a> so I write my UI and Model layers first and the Data layer is mocked, so the UI and model is build around domain specific objects, then later I map these object to what ever technology I'm using the the Data Layer. Is a very bad idea to let the database determine the design of your app, write the app first and think about the data later.</p>\n\n<p>ps the title of the question is a little mis-leading</p>\n"
},
{
"answer_id": 9264,
"author": "Lars Mæhlum",
"author_id": 960,
"author_profile": "https://Stackoverflow.com/users/960",
"pm_score": 1,
"selected": false,
"text": "<p>@Ice^^Heat:</p>\n\n<blockquote>\n <p>What do you mean by that the data tier should not be aware of the business logic tier? How would you fill an business object with data?</p>\n</blockquote>\n\n<p>The UI asks the ServiceClass in the business tier for a service, namely getting a list of objects filtered by an object with the needed parameter data.<br>\nThen the ServiceClass creates an instance of one of the repository classes in the data tier, and calls the GetList(ParameterType filters).<br>\nThen the data tier accesses the database, pulls up the data, and maps it to the common format defined in the \"domain\" assembly.<br>\nThe BL has no more work to do with this data, so it outputs it to the UI.</p>\n\n<p>Then the UI wants to edit Item X. It sends the item (or business object) to the service in the Business Tier. The business tier validates the object, and if it is OK, it sends it to the data tier for storage.</p>\n\n<p>The UI knows the service in the business tier which again knows about the data tier.</p>\n\n<p>The UI is responsible for mapping the users data input to and from the objects, and the data tier is responsible for mapping the data in the db to and from the objects. The Business tier stays purely business. :)</p>\n"
},
{
"answer_id": 9277,
"author": "Derek Park",
"author_id": 872,
"author_profile": "https://Stackoverflow.com/users/872",
"pm_score": 0,
"selected": false,
"text": "<p>So the problem is that the business layer needs to expose more functionality to the data layer, and adding this functionality means exposing too much to the UI layer? If I'm understanding your problem correctly, it sounds like you're trying to satisfy too much with a single interface, and that's just causing it to become cluttered. Why not have two interfaces into the business layer? One would be a simple, safe interface for the UI layer. The other would be a lower-level interface for the data layer.</p>\n\n<p>You can apply this two-interface approach to any objects which need to be passed to both the UI and the data layers, too.</p>\n\n<pre><code>public class BusinessLayer : ISimpleBusiness\n{}\n\npublic class Some3LayerObject : ISimpleSome3LayerObject\n{}\n</code></pre>\n"
},
{
"answer_id": 9369,
"author": "Jon Limjap",
"author_id": 372,
"author_profile": "https://Stackoverflow.com/users/372",
"pm_score": 0,
"selected": false,
"text": "<p>You may want to split your interfaces into two types, namely:</p>\n\n<ul>\n<li>View interfaces -- which are interfaces that specify your interactions with your UI, and</li>\n<li>Data interfaces -- which are interfaces that will allow you to specify interactions with your data</li>\n</ul>\n\n<p>It is possible to inherit and implement both set of interfaces such that:</p>\n\n<pre><code>public class BusinessObject : IView, IData\n</code></pre>\n\n<p>This way, in your data layer you only need to see the interface implementation of IData, while in your UI you only need to see the interface implementation of IView.</p>\n\n<p>Another strategy you might want to use is to compose your objects in the UI or Data layers such that they are merely consumed by these layers, e.g.,</p>\n\n<pre><code>public class BusinessObject : DomainObject\n\npublic class ViewManager<T> where T : DomainObject\n\npublic class DataManager<T> where T : DomainObject\n</code></pre>\n\n<p>This in turn allows your business object to remain ignorant of both the UI/View layer and the data layer.</p>\n"
},
{
"answer_id": 9502,
"author": "Wheelie",
"author_id": 1131,
"author_profile": "https://Stackoverflow.com/users/1131",
"pm_score": 4,
"selected": true,
"text": "<p>If I understand the question correctly, you've created a domain model and you would like to write an object-relational mapper to map between records in your database and your domain objects. However, you're concerned about polluting your domain model with the 'plumbing' code that would be necessary to read and write to your object's fields.</p>\n\n<p>Taking a step back, you essentially have two choices of where to put your data mapping code - within the domain class itself or in an external mapping class.\nThe first option is often called the Active Record pattern and has the advantage that each object knows how to persist itself and has sufficient access to its internal structure to allow it to perform the mapping without needing to expose non-business related fields.</p>\n\n<p>E.g</p>\n\n<pre><code>public class User\n{\n private string name;\n private AccountStatus status;\n\n private User()\n {\n }\n\n public string Name\n {\n get { return name; }\n set { name = value; }\n }\n\n public AccountStatus Status\n {\n get { return status; }\n }\n\n public void Activate()\n {\n status = AccountStatus.Active;\n }\n\n public void Suspend()\n {\n status = AccountStatus.Suspended;\n }\n\n public static User GetById(int id)\n {\n User fetchedUser = new User();\n\n // Lots of database and error-checking code\n // omitted for clarity\n // ...\n\n fetchedUser.name = (string) reader[\"Name\"];\n fetchedUser.status = (int)reader[\"statusCode\"] == 0 ? AccountStatus.Suspended : AccountStatus.Active;\n\n return fetchedUser;\n }\n\n public static void Save(User user)\n {\n // Code to save User's internal structure to database\n // ...\n }\n}\n</code></pre>\n\n<p>In this example, we have an object that represents a User with a Name and an AccountStatus. We don't want to allow the Status to be set directly, perhaps because we want to check that the change is a valid status transition, so we don't have a setter. Fortunately, the mapping code in the GetById and Save static methods have full access to the object's name and status fields.</p>\n\n<p>The second option is to have a second class that is responsible for the mapping. This has the advantage of seperating out the different concerns of business logic and persistence which can allow your design to be more testable and flexible. The challenge with this method is how to expose the name and status fields to the external class. Some options are:\n 1. Use reflection (which has no qualms about digging deep into your object's private parts)\n 2. Provide specially-named, public setters (e.g. prefix them with the word 'Private') and hope no one uses them accidentally\n 3. If your language suports it, make the setters internal but grant your data mapper module access. E.g. use the InternalsVisibleToAttribute in .NET 2.0 onwards or friend functions in C++</p>\n\n<p>For more information, I'd recommend Martin Fowler's classic book 'Patterns of Enterprise Architecture'</p>\n\n<p>However, as a word of warning, before going down the path of writing your own mappers I'd strongly recommend looking at using a 3rd-party object relational mapper (ORM) tool such as nHibernate or Microsoft's Entity Framework. I've worked on four different projects where, for various reasons, we wrote our own mapper and it is very easy to waste a lot of time maintaining and extending the mapper instead of writing code that provides end user value. I've used nHibernate on one project so far and, although it has quite a steep learning curve initially, the investment you put in early on pays off considerably.</p>\n"
},
{
"answer_id": 10448,
"author": "Eric Z Beard",
"author_id": 1219,
"author_profile": "https://Stackoverflow.com/users/1219",
"pm_score": 0,
"selected": false,
"text": "<p>I'm going to continue my habit of going against the grain and say that you should question why you are building all these horribly complex object layers.</p>\n\n<p>I think many developers think of the database as a simple persistence layer for their objects, and are only concerned with the CRUD operations that those objects need. Too much effort is being put into the \"impedence mismatch\" between object and relational models. Here's an idea: stop trying.</p>\n\n<p>Write stored procedures to encapsulate your data. Use results sets, DataSet, DataTable, SqlCommand (or the java/php/whatever equivalent) as needed from code to interact with the database. You don't need those objects. An excellent example is embedding a SqlDataSource into a .ASPX page.</p>\n\n<p>You shouldn't try to hide your data from anyone. Developers need to understand exactly how and when they are interacting with the physical data store.</p>\n\n<p>Object-relational mappers are the devil. Stop using them.</p>\n\n<p>Building enterprise applications is often an exercise in managing complexity. You have to keep things as simple as possible, or you will have an absolutely un-maintainable system. If you are willing to allow some coupling (which is inherent in any application anyway), you can do away with both your business logic layer and your data access layer (replacing them with stored procedures), and you won't need any of those interfaces.</p>\n"
}
] | 2008/08/12 | [
"https://Stackoverflow.com/questions/9240",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] | Say you have an application divided into 3-tiers: GUI, business logic, and data access. In your business logic layer you have described your business objects: getters, setters, accessors, and so on... you get the idea. The interface to the business logic layer guarantees safe usage of the business logic, so all the methods and accessors you call will validate input.
This great when you first write the UI code, because you have a neatly defined interface that you can trust.
But here comes the tricky part, when you start writing the data access layer, the interface to the business logic does not accommodate your needs. You need to have more accessors and getters to set fields which are/used to be hidden. Now you are forced to erode the interface of your business logic; now it is possible set fields from the UI layer, which the UI layer has no business setting.
Because of the changes needed for the data access layer, the interface to the business logic has eroded to the point where it is possible to even set the business logic with invalid data. Thus, the interface does not guarantee safe usage anymore.
I hope I explained the problem clearly enough. How do you prevent interface eroding, maintain information hiding and encapsulation, and yet still accommodate different interface needs among different layers? | If I understand the question correctly, you've created a domain model and you would like to write an object-relational mapper to map between records in your database and your domain objects. However, you're concerned about polluting your domain model with the 'plumbing' code that would be necessary to read and write to your object's fields.
Taking a step back, you essentially have two choices of where to put your data mapping code - within the domain class itself or in an external mapping class.
The first option is often called the Active Record pattern and has the advantage that each object knows how to persist itself and has sufficient access to its internal structure to allow it to perform the mapping without needing to expose non-business related fields.
E.g
```
public class User
{
private string name;
private AccountStatus status;
private User()
{
}
public string Name
{
get { return name; }
set { name = value; }
}
public AccountStatus Status
{
get { return status; }
}
public void Activate()
{
status = AccountStatus.Active;
}
public void Suspend()
{
status = AccountStatus.Suspended;
}
public static User GetById(int id)
{
User fetchedUser = new User();
// Lots of database and error-checking code
// omitted for clarity
// ...
fetchedUser.name = (string) reader["Name"];
fetchedUser.status = (int)reader["statusCode"] == 0 ? AccountStatus.Suspended : AccountStatus.Active;
return fetchedUser;
}
public static void Save(User user)
{
// Code to save User's internal structure to database
// ...
}
}
```
In this example, we have an object that represents a User with a Name and an AccountStatus. We don't want to allow the Status to be set directly, perhaps because we want to check that the change is a valid status transition, so we don't have a setter. Fortunately, the mapping code in the GetById and Save static methods have full access to the object's name and status fields.
The second option is to have a second class that is responsible for the mapping. This has the advantage of seperating out the different concerns of business logic and persistence which can allow your design to be more testable and flexible. The challenge with this method is how to expose the name and status fields to the external class. Some options are:
1. Use reflection (which has no qualms about digging deep into your object's private parts)
2. Provide specially-named, public setters (e.g. prefix them with the word 'Private') and hope no one uses them accidentally
3. If your language suports it, make the setters internal but grant your data mapper module access. E.g. use the InternalsVisibleToAttribute in .NET 2.0 onwards or friend functions in C++
For more information, I'd recommend Martin Fowler's classic book 'Patterns of Enterprise Architecture'
However, as a word of warning, before going down the path of writing your own mappers I'd strongly recommend looking at using a 3rd-party object relational mapper (ORM) tool such as nHibernate or Microsoft's Entity Framework. I've worked on four different projects where, for various reasons, we wrote our own mapper and it is very easy to waste a lot of time maintaining and extending the mapper instead of writing code that provides end user value. I've used nHibernate on one project so far and, although it has quite a steep learning curve initially, the investment you put in early on pays off considerably. |
9,256 | <p>Thanks to FireFox's buggy implementation of ActiveX components (it really should take an image of them when printing) Flex components (in our case charts) don't print in FX.</p>
<p>They print fine in IE7, even IE6.</p>
<p>We need these charts to print, but they also have dynamic content. I don't really want to draw them again as images when the user prints - the Flex component should do it.</p>
<p>We've found a <a href="http://www.anychart.com/blog/2007/09/23/solving-problem-with-printing-flash-content-in-firefox-browser/" rel="nofollow noreferrer">potential workaround</a>, but unfortunately it doesn't work in FireFox3 (in FireFox2 it sort-of works, but not well enough).</p>
<p>Anyone know a workaround?</p>
| [
{
"answer_id": 16362,
"author": "Matt MacLean",
"author_id": 22,
"author_profile": "https://Stackoverflow.com/users/22",
"pm_score": 3,
"selected": true,
"text": "<p>Using the ACPrintManager I was able to get firefox 3 to print perfectly!</p>\n\n<p>The one thing I had to add to the example was to check if stage was null, and callLater if the stage was null.</p>\n\n<pre><code>private function initPrint():void {\n //if we don't have a stage, wait until the next frame and try again\n if ( stage == null ) {\n callLater(initPrint);\n return;\n }\n\n PrintManager.init(stage);\n\n var data:BitmapData = new BitmapData(stage.stageWidth, stage.stageHeight);\n data.draw(myDataGrid);\n\n PrintManager.setPrintableContent(data);\n}\n</code></pre>\n"
},
{
"answer_id": 27930,
"author": "Keith",
"author_id": 905,
"author_profile": "https://Stackoverflow.com/users/905",
"pm_score": 0,
"selected": false,
"text": "<p>Thanks. A load of <code>callLater</code>-s added to our custom chart code seems to have done it.</p>\n"
}
] | 2008/08/12 | [
"https://Stackoverflow.com/questions/9256",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/905/"
] | Thanks to FireFox's buggy implementation of ActiveX components (it really should take an image of them when printing) Flex components (in our case charts) don't print in FX.
They print fine in IE7, even IE6.
We need these charts to print, but they also have dynamic content. I don't really want to draw them again as images when the user prints - the Flex component should do it.
We've found a [potential workaround](http://www.anychart.com/blog/2007/09/23/solving-problem-with-printing-flash-content-in-firefox-browser/), but unfortunately it doesn't work in FireFox3 (in FireFox2 it sort-of works, but not well enough).
Anyone know a workaround? | Using the ACPrintManager I was able to get firefox 3 to print perfectly!
The one thing I had to add to the example was to check if stage was null, and callLater if the stage was null.
```
private function initPrint():void {
//if we don't have a stage, wait until the next frame and try again
if ( stage == null ) {
callLater(initPrint);
return;
}
PrintManager.init(stage);
var data:BitmapData = new BitmapData(stage.stageWidth, stage.stageHeight);
data.draw(myDataGrid);
PrintManager.setPrintableContent(data);
}
``` |
9,275 | <p>I writing a report in Visual Studio that takes a user input parameter and runs against an ODBC datasource. I would like to write the query manually and have reporting services replace part of the where clause with the parameter value before sending it to the database. What seems to be happening is that the <code>@parmName</code> I am assuming will be replaced is actually being sent as part of the SQL statement. Am I missing a configuration setting somewhere or is this simply not possible?</p>
<p>I am not using the filter option in the tool because this appears to bring back the full dataset from the database and do the filtering on the SQL Server.</p>
| [
{
"answer_id": 9325,
"author": "Jorriss",
"author_id": 621,
"author_profile": "https://Stackoverflow.com/users/621",
"pm_score": 4,
"selected": true,
"text": "<p>It sounds like you'll need to treat the SQL Statement as an expression. For example:</p>\n\n<pre><code>=\"Select col1, col2 from table 1 Where col3 = \" & Parameters!Param1.Value \n</code></pre>\n\n<p>If the where clause is a string you would need to do the following:</p>\n\n<pre><code>=\"Select col1, col2 from table 1 Where col3 = '\" & Parameters!Param1.Value & \"'\"\n</code></pre>\n\n<p>Important: Do not use line breaks in your SQL expression. If you do you will get an error.</p>\n\n<p>Holla back if you need any more assistance.</p>\n"
},
{
"answer_id": 19600,
"author": "Matt Hamilton",
"author_id": 615,
"author_profile": "https://Stackoverflow.com/users/615",
"pm_score": 1,
"selected": false,
"text": "<p>Doesn't ODBC use the old \"?\" syntax for parameters? Try this:</p>\n\n<pre><code>select col1, col2 from table1 where col3 = ?\n</code></pre>\n\n<p>The order of your parameters becomes important then, but it's less vulnerable to SQL injection than simply appending the parameter value.</p>\n"
},
{
"answer_id": 28572,
"author": "stjohnroe",
"author_id": 2985,
"author_profile": "https://Stackoverflow.com/users/2985",
"pm_score": 0,
"selected": false,
"text": "<p>I am a bit confused about this question, if you are looking for simple parameter usage then the notation is :<code>*paramName*</code> , however if you want to structurally change the <code>WHERE</code> clause (as you might in sql+ using ?) then you should really be using custom code within the report to define a function that returns the required sql for the query.</p>\n\n<p>Unfortunately, when using custom code, parameters cannot be referenced directly in the generated query but have to have there values concatenated into the resultant String, thus introducing the potential for <code>SQL</code> injection.</p>\n"
},
{
"answer_id": 10551669,
"author": "H.G.",
"author_id": 1238246,
"author_profile": "https://Stackoverflow.com/users/1238246",
"pm_score": 1,
"selected": false,
"text": "<p>Encountered same problem trying to query an access database via ODBC. </p>\n\n<p>My original query: <code>SELECT A.1 FROM A WHERE A.1 = @parameter</code> resulted in error. Altered to: <code>SELECT A.1 FROM A WHERE A.1 = ?</code>.</p>\n\n<p>You then have to map the query parameter with your report parameter.</p>\n"
}
] | 2008/08/12 | [
"https://Stackoverflow.com/questions/9275",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1104/"
] | I writing a report in Visual Studio that takes a user input parameter and runs against an ODBC datasource. I would like to write the query manually and have reporting services replace part of the where clause with the parameter value before sending it to the database. What seems to be happening is that the `@parmName` I am assuming will be replaced is actually being sent as part of the SQL statement. Am I missing a configuration setting somewhere or is this simply not possible?
I am not using the filter option in the tool because this appears to bring back the full dataset from the database and do the filtering on the SQL Server. | It sounds like you'll need to treat the SQL Statement as an expression. For example:
```
="Select col1, col2 from table 1 Where col3 = " & Parameters!Param1.Value
```
If the where clause is a string you would need to do the following:
```
="Select col1, col2 from table 1 Where col3 = '" & Parameters!Param1.Value & "'"
```
Important: Do not use line breaks in your SQL expression. If you do you will get an error.
Holla back if you need any more assistance. |
9,279 | <p>I absolutely love the <a href="http://winscp.net/eng/docs/task_keep_up_to_date" rel="noreferrer">Keep Remote Directory Up-to-date</a> feature in <a href="http://winscp.net/" rel="noreferrer">Winscp</a>. Unfortunately, I can't find anything as simple to use in OS X or Linux. I know the same thing can <em>theoretically</em> be accomplished using <a href="http://freshmeat.net/projects/changedfiles/" rel="noreferrer">changedfiles</a> or <a href="http://samba.anu.edu.au/rsync/" rel="noreferrer">rsync</a>, but I've always found the tutorials for both tools to be lacking and/or contradictory. </p>
<p>I basically just need a tool that works in OSX or Linux and keeps a remote directory in sync (mirrored) with a local directory while I make changes to the local directory.</p>
<hr>
<p><strong>Update</strong></p>
<p>Looking through the solutions, I see a couple which solve the general problem of keeping a remote directory in sync with a local directory <em>manually</em>. I know that I can set a cron task to run rsync every minute, and this should be fairly close to real time. </p>
<p>This is not the exact solution I was looking for as winscp does this and more: it detects file changes in a directory (while I work on them) and then automatically pushes the changes to the remote server. I know this is not the best solution (no code repository), but it allows me to very quickly test code on a server while I develop it. Does anyone know how to combine rsync with any other commands to get this functionality?</p>
| [
{
"answer_id": 9287,
"author": "dwj",
"author_id": 346,
"author_profile": "https://Stackoverflow.com/users/346",
"pm_score": 5,
"selected": true,
"text": "<p>How \"real-time\" do you want the syncing? I would still lean toward rsync since you know it is going to be fully supported on both platforms (Windows, too, with cygwin) and you can run it via a cron job. I have a super-simple bash file that I run on my system (this does <em>not</em> remove old files):</p>\n\n<pre><code>#!/bin/sh\nrsync -avrz --progress --exclude-from .rsync_exclude_remote . remote_login@remote_computer:remote_dir \n\n# options\n# -a archive\n# -v verbose\n# -r recursive\n# -z compress \n</code></pre>\n\n<p>Your best bet is to set it up and try it out. The <code>-n (--dry-run)</code> option is your friend!</p>\n\n<p>Keep in mind that rsync (at least in cygwin) does not support unicode file names (as of 16 Aug 2008).</p>\n"
},
{
"answer_id": 9288,
"author": "icco",
"author_id": 1063,
"author_profile": "https://Stackoverflow.com/users/1063",
"pm_score": 2,
"selected": false,
"text": "<p>You could always use version control, like SVN, so all you have to do is have the server run svn up on a folder every night. This runs into security issues if you are sharing your files publicly, but it works. </p>\n\n<p>If you are using Linux though, learn to use rsync. It's really not that difficult as you can test every command with -n. Go through the <a href=\"http://www.samba.org/ftp/rsync/rsync.html\" rel=\"nofollow noreferrer\">man page</a>, the basic format you will want is </p>\n\n<blockquote>\n <p>rsync [OPTION...] SRC... [USER@]HOST:DEST</p>\n</blockquote>\n\n<p>the command I run from my school server to my home backup machine is this</p>\n\n<blockquote>\n <p>rsync -avi --delete ~ me@homeserv:~/School/ >> BackupLog.txt</p>\n</blockquote>\n\n<p>This takes all of the files in my home directory (~) and uses rsync's archive mode (-a), verbosly (-v), lists all of the changes made (-i), while deleting any files that don't exist anymore (--delete) and puts the in the Folder /home/me/School/ on my remote server. All of the information it prints out (what was copied, what was deleted, etc.) is also appended to the file BackupLog.txt</p>\n\n<p>I know that's a whirlwind tour of rsync, but I hope it helps. </p>\n"
},
{
"answer_id": 9302,
"author": "Pat Notz",
"author_id": 825,
"author_profile": "https://Stackoverflow.com/users/825",
"pm_score": 2,
"selected": false,
"text": "<p>The <code>rsync</code> solutions are really good, especially if you're only pushing changes one way. Another great tool is <code>unison</code> -- it attempts to syncronize changes in both directions. Read more at <a href=\"http://www.cis.upenn.edu/~bcpierce/unison/\" rel=\"nofollow noreferrer\" title=\"Unison Home Page\">the Unison homepage</a>.</p>\n"
},
{
"answer_id": 9346,
"author": "Marie Fischer",
"author_id": 719,
"author_profile": "https://Stackoverflow.com/users/719",
"pm_score": 2,
"selected": false,
"text": "<p>To detect changed files, you could try fam (file alteration monitor) or inotify. The latter is linux-specific, fam has a bsd port which might work on OS X. Both have userspace tools that could be used in a script together with rsync.</p>\n"
},
{
"answer_id": 9353,
"author": "stimms",
"author_id": 361,
"author_profile": "https://Stackoverflow.com/users/361",
"pm_score": 1,
"selected": false,
"text": "<p>It seems like perhaps you're solving the wrong problem. If you're trying to edit files on a remote computer then you might try using something like the ftp plugin for jedit. <a href=\"http://plugins.jedit.org/plugins/?FTP\" rel=\"nofollow noreferrer\">http://plugins.jedit.org/plugins/?FTP</a> This ensures that you have only one version of the file so it can't ever be out of sync.</p>\n"
},
{
"answer_id": 14718,
"author": "Matthew Schinckel",
"author_id": 188,
"author_profile": "https://Stackoverflow.com/users/188",
"pm_score": 0,
"selected": false,
"text": "<p>You can also use Fetch as an SFTP client, and then edit files directly on the server from within that. There are also SSHFS (mount an ssh folder as a Volume) options. This is in line with what stimms said - are you sure you want stuff kept in sync, or just want to edit files on the server?</p>\n\n<p>OS X has it's own file notifications system - this is what Spotlight is based upon. I haven't heard of any program that uses this to then keep things in sync, but it's certainly conceivable.</p>\n\n<p>I personally use RCS for this type of thing:- whilst it's got a manual aspect, it's unlikely I want to push something to even the test server from my dev machine without testing it first. And if I am working on a development server, then I use one of the options given above.</p>\n"
},
{
"answer_id": 73415,
"author": "Daniel Papasian",
"author_id": 7548,
"author_profile": "https://Stackoverflow.com/users/7548",
"pm_score": 1,
"selected": false,
"text": "<p>Building off of icco's suggestion of SVN, I'd actually suggest that if you are using subversion or similar for source control (and if you aren't, you should probably start) you can keep the production environment up to date by putting the command to update the repository into the post-commit hook.</p>\n\n<p>There are a lot of variables in how you'd want to do that, but what I've seen work is have the development or live site be a working copy and then have the post-commit use an ssh key with a forced command to log into the remote site and trigger an svn up on the working copy. Alternatively in the post-commit hook you could trigger an svn export on the remote machine, or a local (to the svn repository) svn export and then an rsync to the remote machine.</p>\n\n<p>I would be worried about things that detect changes and push them, and I'd even be worried about things that ran every minute, just because of race conditions. How do you know it's not going to transfer the file at the very same instant it's being written to? Stumble across that once or twice and you'll lose all of the time-saving advantage you had by constantly rsyncing or similar.</p>\n"
},
{
"answer_id": 112881,
"author": "Scott",
"author_id": 7399,
"author_profile": "https://Stackoverflow.com/users/7399",
"pm_score": 1,
"selected": false,
"text": "<p>Will DropBox (<a href=\"http://www.getdropbox.com/\" rel=\"nofollow noreferrer\">http://www.getdropbox.com/</a>) do what you want?</p>\n"
},
{
"answer_id": 289305,
"author": "KevinButler",
"author_id": 34463,
"author_profile": "https://Stackoverflow.com/users/34463",
"pm_score": 3,
"selected": false,
"text": "<p>What you want to do for linux remote access is use 'sshfs' - the SSH File System.</p>\n\n<pre><code># sshfs username@host:path/to/directory local_dir\n</code></pre>\n\n<p>Then treat it like an network mount, which it is...</p>\n\n<p>A bit more detail, like how to set it up so you can do this as a regular user, on <a href=\"http://soi.kd6.us/2008/11/05/so-i-used-sshfs-to-mount-a-remote-filesystem/\" rel=\"noreferrer\">my blog</a></p>\n\n<p>If you want the asynchronous behavior of winSCP, you'll want to use rsync combined with something that executes it periodically. The cron solution above works, but may be overkill for the winscp use case.</p>\n\n<p>The following command will execute rsync every 5 seconds to push content to the remote host. You can adjust the sleep time as needed to reduce server load.</p>\n\n<pre><code># while true; do rsync -avrz localdir user@host:path; sleep 5; done\n</code></pre>\n\n<p>If you have a very large directory structure and need to reduce the overhead of the polling, you can use 'find':</p>\n\n<pre><code># touch -d 01/01/1970 last; while true; do if [ \"`find localdir -newer last -print -quit`\" ]; then touch last; rsync -avrz localdir user@host:path; else echo -ne .; fi; sleep 5; done\n</code></pre>\n\n<p>And I said cron may be overkill? But at least this is all just done from the command line, and can be stopped via a ctrl-C. </p>\n\n<p>kb</p>\n"
},
{
"answer_id": 4378901,
"author": "webasdf",
"author_id": 228301,
"author_profile": "https://Stackoverflow.com/users/228301",
"pm_score": 2,
"selected": false,
"text": "<p>I have the same issue. I loved winscp \"keep remote directory up to date\" command. However, in my quest to rid myself of Windows, I lost winscp. I did write a script that uses fileschanged and rsync to do something similar much closer to real time.</p>\n\n<p>How to use:</p>\n\n<ul>\n<li>Make sure you have fileschanged installed</li>\n<li>Save this script in /usr/local/bin/livesync or somewhere reachable in your $PATH and make it executable</li>\n<li>Use Nautilus to connect to the remote host (sftp or ftp)</li>\n<li>Run this script by doing livesync <strong>SOURCE DEST</strong></li>\n<li>The DEST directory will be in /home/[username]/.gvfs/[path to ftp scp or whatever]</li>\n</ul>\n\n<p>A Couple downsides:</p>\n\n<ul>\n<li>It is slower than winscp (my guess is because it goes through Nautilus and has to detect changes through rsync as well)</li>\n<li>You have to manually create the destination directory if it doesn't already exist. So if you're adding a directory, it won't detect and create the directory on the DEST side.</li>\n<li>Probably more that I haven't noticed yet</li>\n<li>Also, do not attempt to synchronize a SRC directory named \"rsyncThis\". That will probably not be good :)</li>\n</ul>\n\n<hr>\n\n\n\n<pre class=\"lang-sh prettyprint-override\"><code>#!/bin/sh\n\nupload_files()\n{\n if [ \"$HOMEDIR\" = \".\" ]\n then\n HOMEDIR=`pwd`\n fi\n\n while read input\n do\n SYNCFILE=${input#$HOMEDIR}\n echo -n \"Sync File: $SYNCFILE...\"\n rsync -Cvz --temp-dir=\"$REMOTEDIR\" \"$HOMEDIR/$SYNCFILE\" \"$REMOTEDIR/$SYNCFILE\" > /dev/null\n echo \"Done.\"\n done\n}\n\n\nhelp()\n{\n echo \"Live rsync copy from one directory to another. This will overwrite the existing files on DEST.\"\n echo \"Usage: $0 SOURCE DEST\" \n}\n\n\ncase \"$1\" in\n rsyncThis)\n HOMEDIR=$2\n REMOTEDIR=$3\n echo \"HOMEDIR=$HOMEDIR\"\n echo \"REMOTEDIR=$REMOTEDIR\"\n upload_files\n ;;\n\n help)\n help\n ;;\n\n *)\n if [ -n \"$1\" ] && [ -n \"$2\" ]\n then\n fileschanged -r \"$1\" | \"$0\" rsyncThis \"$1\" \"$2\"\n else\n help\n fi\n ;;\nesac\n</code></pre>\n"
},
{
"answer_id": 8854595,
"author": "iPatch",
"author_id": 1148185,
"author_profile": "https://Stackoverflow.com/users/1148185",
"pm_score": 1,
"selected": false,
"text": "<p>I used to have the same setup under Windows as you, that is a local filetree (versioned) and a test environment on a remote server, which I kept mirrored in realtime with WinSCP. When I switched to Mac I had to do quite some digging before I was happy, but finally ended up using:</p>\n<ul>\n<li><a href=\"https://www.smartsvn.com/\" rel=\"nofollow noreferrer\">SmartSVN</a> as my subversion client</li>\n<li><a href=\"http://www.sublimetext.com/2\" rel=\"nofollow noreferrer\">Sublime Text 2</a> as my editor (already used it on Windows)</li>\n<li>SFTP-plugin to ST2 which handles the uploading on save (sorry, can't post more than 2 links)</li>\n</ul>\n<p>I can really recommend this setup, hope it helps!</p>\n"
},
{
"answer_id": 14435664,
"author": "Eduardo Russo",
"author_id": 1302318,
"author_profile": "https://Stackoverflow.com/users/1302318",
"pm_score": 0,
"selected": false,
"text": "<p>Well, I had the same kind of problem and it is possible using these together: rsync, SSH Passwordless Login, Watchdog (a Python sync utility) and Terminal Notifier (an OS X notification utility made with Ruby. Not needed, but helps to know when the sync has finished).</p>\n\n<ol>\n<li><p>I created the key to Passwordless Login using this tutorial from Dreamhost wiki: <a href=\"http://cl.ly/MIw5\" rel=\"nofollow\">http://cl.ly/MIw5</a></p>\n\n<p>1.1. When you finish, test if everything is ok… if you can't Passwordless Login, maybe you have to try afp mount. Dreamhost (where my site is) does not allow afp mount, but allows Passwordless Login. In terminal, type:</p>\n\n<p><code>ssh [email protected]\n</code>\n You should login without passwords being asked :P</p></li>\n<li><p>I installed the Terminal Notifier from the Github page: <a href=\"http://cl.ly/MJ5x\" rel=\"nofollow\">http://cl.ly/MJ5x</a></p>\n\n<p>2.1. I used the Gem installer command. In Terminal, type:</p>\n\n<p><code>gem install terminal-notifier\n</code></p>\n\n<p>2.3. Test if the notification works.In Terminal, type:</p>\n\n<p><code>terminal-notifier -message \"Starting sync\"\n</code></p></li>\n<li><p>Create a sh script to test the rsync + notification. Save it anywhere you like, with the name you like. In this example, I'll call it <strong>~/Scripts/sync.sh</strong> I used the \".sh extension, but I don't know if its needed.</p>\n\n<p><code>#!/bin/bash\nterminal-notifier -message \"Starting sync\"\nrsync -azP ~/Sites/folder/ [email protected]:site_folder/\nterminal-notifier -message \"Sync has finished\"\n</code></p>\n\n<p>3.1. Remember to give execution permission to this sh script. In Terminal, type:</p>\n\n<p><code>sudo chmod 777 ~/Scripts/sync.sh\n</code>\n 3.2. Run the script and verify if the messages are displayed correctly and the rsync actually sync your local folder with the remote folder.</p></li>\n<li><p>Finally, I downloaded and installed Watchdog from the Github page: <a href=\"http://cl.ly/MJfb\" rel=\"nofollow\">http://cl.ly/MJfb</a></p>\n\n<p>4.1. First, I installed the libyaml dependency using Brew (there are lot's of help how to install Brew - like an \"aptitude\" for OS X). In Terminal, type:</p>\n\n<p><code>brew install libyaml\n</code></p>\n\n<p>4.2. Then, I used the \"easy_install command\". Go the folder of Watchdog, and type in Terminal:</p>\n\n<p><code>easy_install watchdog\n</code></p></li>\n<li><p>Now, everything is installed! <strong>Go the folder you want to be synced</strong>, <strong>change this code to your needs</strong>, and type in Terminal:</p>\n\n<pre><code> watchmedo shell-command\n --patterns=\"*.php;*.txt;*.js;*.css\" \\\n --recursive \\\n --command='~/Scripts/Sync.sh' \\\n .\n</code></pre>\n\n<p>It has to be <strong>EXACTLY</strong> this way, with the slashes and line breaks, so you'll have to copy these lines to a text editor, change the script, paste in terminal and press return.</p>\n\n<p>I tried without the line breaks, and it doesn't work!</p>\n\n<p>In my Mac, I always get an error, but it doesn't seem to affect anything:</p>\n\n<p><code>/Library/Python/2.7/site-packages/argh-0.22.0-py2.7.egg/argh/completion.py:84: UserWarning: Bash completion not available. Install argcomplete.\n</code></p>\n\n<p>Now, made some changes in a file inside the folder, and watch the magic!</p></li>\n</ol>\n"
},
{
"answer_id": 15283061,
"author": "juwens",
"author_id": 534812,
"author_profile": "https://Stackoverflow.com/users/534812",
"pm_score": 5,
"selected": false,
"text": "<p><a href=\"https://github.com/axkibe/lsyncd#readme\" rel=\"noreferrer\">lsyncd</a> seems to be the perfect solution. it combines <strong>inotify</strong> (kernel builtin function which watches for file changes in a directory trees) and <strong>rsync</strong> (cross platform file-syncing-tool). </p>\n\n<pre><code>lsyncd -rsyncssh /home remotehost.org backup-home/\n</code></pre>\n\n<p>Quote from github:</p>\n\n<blockquote>\n <p>Lsyncd watches a local directory trees event monitor interface (inotify or fsevents). It aggregates and combines events for a few seconds and then spawns one (or more) process(es) to synchronize the changes. By default this is rsync. Lsyncd is thus a light-weight live mirror solution that is comparatively easy to install not requiring new filesystems or blockdevices and does not hamper local filesystem performance. </p>\n</blockquote>\n"
},
{
"answer_id": 24455670,
"author": "Mike Mitterer",
"author_id": 504184,
"author_profile": "https://Stackoverflow.com/users/504184",
"pm_score": 0,
"selected": false,
"text": "<p>I'm using this little Ruby-Script:</p>\n\n<pre class=\"lang-ruby prettyprint-override\"><code>#!/usr/bin/env ruby\n#~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\n# Rsyncs 2Folders\n#\n# watchAndSync by Mike Mitterer, 2014 <http://www.MikeMitterer.at>\n# with credit to Brett Terpstra <http://brettterpstra.com>\n# and Carlo Zottmann <https://github.com/carlo/haml-sass-file-watcher>\n# Found link on: http://brettterpstra.com/2011/03/07/watch-for-file-changes-and-refresh-your-browser-automatically/\n#\n\ntrap(\"SIGINT\") { exit }\n\nif ARGV.length < 2\n puts \"Usage: #{$0} watch_folder sync_folder\"\n puts \"Example: #{$0} web keepInSync\"\n exit\nend\n\ndev_extension = 'dev'\nfiletypes = ['css','html','htm','less','js', 'dart']\n\nwatch_folder = ARGV[0]\nsync_folder = ARGV[1]\n\nputs \"Watching #{watch_folder} and subfolders for changes in project files...\"\nputs \"Syncing with #{sync_folder}...\"\n\nwhile true do\n files = []\n filetypes.each {|type|\n files += Dir.glob( File.join( watch_folder, \"**\", \"*.#{type}\" ) )\n }\n new_hash = files.collect {|f| [ f, File.stat(f).mtime.to_i ] }\n hash ||= new_hash\n diff_hash = new_hash - hash\n\n unless diff_hash.empty?\n hash = new_hash\n\n diff_hash.each do |df|\n puts \"Detected change in #{df[0]}, syncing...\"\n system(\"rsync -avzh #{watch_folder} #{sync_folder}\")\n end\n end\n\n sleep 1\nend\n</code></pre>\n\n<p>Adapt it for your needs!</p>\n"
},
{
"answer_id": 28635944,
"author": "k2k2e6",
"author_id": 2138554,
"author_profile": "https://Stackoverflow.com/users/2138554",
"pm_score": 1,
"selected": false,
"text": "<p>User watcher.py and rsync to automate this. Read the following step by step instructions here:</p>\n\n<p><a href=\"http://kushellig.de/linux-file-auto-sync-directories/\" rel=\"nofollow\">http://kushellig.de/linux-file-auto-sync-directories/</a></p>\n"
},
{
"answer_id": 56051542,
"author": "deserve",
"author_id": 11473221,
"author_profile": "https://Stackoverflow.com/users/11473221",
"pm_score": 0,
"selected": false,
"text": "<p>If you are developing python on remote server, Pycharm may be a good choice to you. You can synchronize your remote files with your local files utilizing pycharm remote development feature. The guide link as:\n<a href=\"https://www.jetbrains.com/help/pycharm/creating-a-remote-server-configuration.html\" rel=\"nofollow noreferrer\">https://www.jetbrains.com/help/pycharm/creating-a-remote-server-configuration.html</a></p>\n"
},
{
"answer_id": 56717832,
"author": "doom",
"author_id": 1619521,
"author_profile": "https://Stackoverflow.com/users/1619521",
"pm_score": 2,
"selected": false,
"text": "<p>Great question I have searched answer for hours !</p>\n\n<p>I have tested <a href=\"https://github.com/axkibe/lsyncd\" rel=\"nofollow noreferrer\">lsyncd</a> and the problem is that the <strong>default delay is far too long</strong> and no example command line give the <code>-delay</code> option.</p>\n\n<p>Other problem is that by default rsync ask <strong>password</strong> each time !</p>\n\n<p>Solution with <strong>lsyncd</strong> :</p>\n\n<pre><code>lsyncd --nodaemon -rsyncssh local_dir remote_user@remote_host remote_dir -delay .2\n</code></pre>\n\n<p>other way is to use <strong>inotify-wait</strong> in a script :</p>\n\n<pre><code>while inotifywait -r -e modify,create,delete local_dir ; do\n # if you need you can add wait here\n rsync -avz local_dir remote_user@remote_host:remote_dir\ndone\n</code></pre>\n\n<p>For this second solution you will have to install <code>inotify-tools</code> package</p>\n\n<p>To <strong>suppress the need</strong> to enter password at each change, simply use <code>ssh-keygen</code> :\n<a href=\"https://superuser.com/a/555800/510714\">https://superuser.com/a/555800/510714</a></p>\n"
}
] | 2008/08/12 | [
"https://Stackoverflow.com/questions/9279",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/302/"
] | I absolutely love the [Keep Remote Directory Up-to-date](http://winscp.net/eng/docs/task_keep_up_to_date) feature in [Winscp](http://winscp.net/). Unfortunately, I can't find anything as simple to use in OS X or Linux. I know the same thing can *theoretically* be accomplished using [changedfiles](http://freshmeat.net/projects/changedfiles/) or [rsync](http://samba.anu.edu.au/rsync/), but I've always found the tutorials for both tools to be lacking and/or contradictory.
I basically just need a tool that works in OSX or Linux and keeps a remote directory in sync (mirrored) with a local directory while I make changes to the local directory.
---
**Update**
Looking through the solutions, I see a couple which solve the general problem of keeping a remote directory in sync with a local directory *manually*. I know that I can set a cron task to run rsync every minute, and this should be fairly close to real time.
This is not the exact solution I was looking for as winscp does this and more: it detects file changes in a directory (while I work on them) and then automatically pushes the changes to the remote server. I know this is not the best solution (no code repository), but it allows me to very quickly test code on a server while I develop it. Does anyone know how to combine rsync with any other commands to get this functionality? | How "real-time" do you want the syncing? I would still lean toward rsync since you know it is going to be fully supported on both platforms (Windows, too, with cygwin) and you can run it via a cron job. I have a super-simple bash file that I run on my system (this does *not* remove old files):
```
#!/bin/sh
rsync -avrz --progress --exclude-from .rsync_exclude_remote . remote_login@remote_computer:remote_dir
# options
# -a archive
# -v verbose
# -r recursive
# -z compress
```
Your best bet is to set it up and try it out. The `-n (--dry-run)` option is your friend!
Keep in mind that rsync (at least in cygwin) does not support unicode file names (as of 16 Aug 2008). |
9,289 | <p>I would like to filter an array of items by using the <code>map()</code> function. Here is a code snippet:</p>
<pre><code>var filteredItems = items.map(function(item)
{
if( ...some condition... )
{
return item;
}
});
</code></pre>
<p>The problem is that filtered out items still uses space in the array and I would like to completely wipe them out.</p>
<p>Any idea?</p>
<p>EDIT: Thanks, I forgot about <code>filter()</code>, what I wanted is actually a <code>filter()</code> then a <code>map()</code>.</p>
<p>EDIT2: Thanks for pointing that <code>map()</code> and <code>filter()</code> are not implemented in all browsers, although my specific code was not intended to run in a browser.</p>
| [
{
"answer_id": 9295,
"author": "Patrick",
"author_id": 429,
"author_profile": "https://Stackoverflow.com/users/429",
"pm_score": 4,
"selected": false,
"text": "<p>That's not what map does. You really want <a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/filter\" rel=\"nofollow noreferrer\"><code>Array.filter</code></a>. Or if you really want to remove the elements from the original list, you're going to need to do it imperatively with a for loop.</p>\n"
},
{
"answer_id": 9297,
"author": "olliej",
"author_id": 784,
"author_profile": "https://Stackoverflow.com/users/784",
"pm_score": 8,
"selected": true,
"text": "<p>You should use the <code>filter</code> method rather than map unless you want to mutate the items in the array, in addition to filtering.</p>\n\n<p>eg.</p>\n\n<pre><code>var filteredItems = items.filter(function(item)\n{\n return ...some condition...;\n});\n</code></pre>\n\n<p>[Edit: Of course you could always do <code>sourceArray.filter(...).map(...)</code> to both filter and mutate]</p>\n"
},
{
"answer_id": 9329,
"author": "ggasp",
"author_id": 527,
"author_profile": "https://Stackoverflow.com/users/527",
"pm_score": 1,
"selected": false,
"text": "<p>You must note however that the <code>Array.filter</code> is not supported in all browser so, you must to prototyped:</p>\n\n<pre><code>//This prototype is provided by the Mozilla foundation and\n//is distributed under the MIT license.\n//http://www.ibiblio.org/pub/Linux/LICENSES/mit.license\n\nif (!Array.prototype.filter)\n{\n Array.prototype.filter = function(fun /*, thisp*/)\n {\n var len = this.length;\n\n if (typeof fun != \"function\")\n throw new TypeError();\n\n var res = new Array();\n var thisp = arguments[1];\n\n for (var i = 0; i < len; i++)\n {\n if (i in this)\n {\n var val = this[i]; // in case fun mutates this\n\n if (fun.call(thisp, val, i, this))\n res.push(val);\n }\n }\n\n return res;\n };\n}\n</code></pre>\n\n<p>And doing so, you can prototype any method you may need. </p>\n"
},
{
"answer_id": 1498642,
"author": "vsync",
"author_id": 104380,
"author_profile": "https://Stackoverflow.com/users/104380",
"pm_score": 3,
"selected": false,
"text": "<h1>Array <a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/filter\" rel=\"nofollow noreferrer\">Filter method</a></h1>\n\n<p><div class=\"snippet\" data-lang=\"js\" data-hide=\"false\" data-console=\"true\" data-babel=\"false\">\r\n<div class=\"snippet-code\">\r\n<pre class=\"snippet-code-js lang-js prettyprint-override\"><code>var arr = [1, 2, 3]\r\n\r\n// ES5 syntax\r\narr = arr.filter(function(item){ return item != 3 })\r\n\r\n// ES2015 syntax\r\narr = arr.filter(item => item != 3)\r\n\r\nconsole.log( arr )</code></pre>\r\n</div>\r\n</div>\r\n</p>\n"
},
{
"answer_id": 36557522,
"author": "Kyle Baker",
"author_id": 4526479,
"author_profile": "https://Stackoverflow.com/users/4526479",
"pm_score": 6,
"selected": false,
"text": "<p>Inspired by writing this answer, I ended up later expanding and writing a blog post going over this in careful detail. I recommend <a href=\"http://code.kylebaker.io/2018/03/16/stack-overflow/\" rel=\"noreferrer\">checking that out</a> if you want to develop a deeper understanding of how to think about this problem--I try to explain it piece by piece, and also give a JSperf comparison at the end, going over speed considerations.</p>\n<p>That said, **The tl;dr is this:</p>\n<h2>To accomplish what you're asking for (filtering and mapping within one function call), you would use <code>Array.reduce()</code>**.</h2>\n<h2>However, the <em>more readable</em> <strong>and</strong> (less importantly) <em>usually significantly faster</em><sup><a href=\"http://code.kylebaker.io/2018/03/16/stack-overflow/#What-about-performance\" rel=\"noreferrer\">2</a></sup> approach is to just use filter and map chained together:</h2>\n<p><code>[1,2,3].filter(num => num > 2).map(num => num * 2)</code></p>\n<p>What follows is a description of how <code>Array.reduce()</code> works, and how it can be used to accomplish filter and map in one iteration. Again, if this is too condensed, I highly recommend seeing the blog post linked above, which is a much more friendly intro with clear examples and progression.</p>\n<hr />\n<p>You give reduce an argument that is a (usually anonymous) function.</p>\n<p><em>That anonymous function</em> takes two parameters--one (like the anonymous functions passed in to map/filter/forEach) is the iteratee to be operated on. There is another argument for the anonymous function passed to reduce, however, that those functions do not accept, and that is <strong>the value that will be passed along between function calls, often referred to as the <em>memo</em></strong>.</p>\n<p>Note that while Array.filter() takes only one argument (a function), Array.reduce() also takes an important (though optional) second argument: an initial value for 'memo' that will be passed into that anonymous function as its first argument, and subsequently can be mutated and passed along between function calls. (If it is not supplied, then 'memo' in the first anonymous function call will by default be the first iteratee, and the 'iteratee' argument will actually be the second value in the array)</p>\n<p>In our case, we'll pass in an empty array to start, and then choose whether to inject our iteratee into our array or not based on our function--this is the filtering process.</p>\n<p>Finally, we'll return our 'array in progress' on each anonymous function call, and reduce will take that return value and pass it as an argument (called memo) to its next function call.</p>\n<p>This allows filter and map to happen in one iteration, cutting down our number of required iterations in half--just doing twice as much work each iteration, though, so nothing is really saved other than function calls, which are not so expensive in javascript.</p>\n<p>For a more complete explanation, refer to <a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/Reduce\" rel=\"noreferrer\">MDN</a> docs (or to my post referenced at the beginning of this answer).</p>\n<p>Basic example of a Reduce call:</p>\n<pre><code>let array = [1,2,3];\nconst initialMemo = [];\n\narray = array.reduce((memo, iteratee) => {\n // if condition is our filter\n if (iteratee > 1) {\n // what happens inside the filter is the map\n memo.push(iteratee * 2); \n }\n\n // this return value will be passed in as the 'memo' argument\n // to the next call of this function, and this function will have\n // every element passed into it at some point.\n return memo; \n}, initialMemo)\n\nconsole.log(array) // [4,6], equivalent to [(2 * 2), (3 * 2)]\n</code></pre>\n<p>more succinct version:</p>\n<pre><code>[1,2,3].reduce((memo, value) => value > 1 ? memo.concat(value * 2) : memo, [])\n</code></pre>\n<p>Notice that the first iteratee was not greater than one, and so was filtered. Also note the initialMemo, named just to make its existence clear and draw attention to it. Once again, it is passed in as 'memo' to the first anonymous function call, and then the returned value of the anonymous function is passed in as the 'memo' argument to the next function.</p>\n<p>Another example of the classic use case for memo would be returning the smallest or largest number in an array. Example:</p>\n<pre><code>[7,4,1,99,57,2,1,100].reduce((memo, val) => memo > val ? memo : val)\n// ^this would return the largest number in the list.\n</code></pre>\n<p>An example of how to write your own reduce function (this often helps understanding functions like these, I find):</p>\n<pre><code>test_arr = [];\n\n// we accept an anonymous function, and an optional 'initial memo' value.\ntest_arr.my_reducer = function(reduceFunc, initialMemo) {\n // if we did not pass in a second argument, then our first memo value \n // will be whatever is in index zero. (Otherwise, it will \n // be that second argument.)\n const initialMemoIsIndexZero = arguments.length < 2;\n\n // here we use that logic to set the memo value accordingly.\n let memo = initialMemoIsIndexZero ? this[0] : initialMemo;\n\n // here we use that same boolean to decide whether the first\n // value we pass in as iteratee is either the first or second\n // element\n const initialIteratee = initialMemoIsIndexZero ? 1 : 0;\n\n for (var i = initialIteratee; i < this.length; i++) {\n // memo is either the argument passed in above, or the \n // first item in the list. initialIteratee is either the\n // first item in the list, or the second item in the list.\n memo = reduceFunc(memo, this[i]);\n // or, more technically complete, give access to base array\n // and index to the reducer as well:\n // memo = reduceFunc(memo, this[i], i, this);\n }\n\n // after we've compressed the array into a single value,\n // we return it.\n return memo;\n}\n</code></pre>\n<p>The real implementation allows access to things like the index, for example, but I hope this helps you get an uncomplicated feel for the gist of it.</p>\n"
},
{
"answer_id": 58272005,
"author": "Nicolas",
"author_id": 6325415,
"author_profile": "https://Stackoverflow.com/users/6325415",
"pm_score": 0,
"selected": false,
"text": "<p>following statement cleans object using map function.</p>\n<p><div class=\"snippet\" data-lang=\"js\" data-hide=\"false\" data-console=\"true\" data-babel=\"false\">\r\n<div class=\"snippet-code\">\r\n<pre class=\"snippet-code-js lang-js prettyprint-override\"><code>var arraytoclean = [{v:65, toberemoved:\"gronf\"}, {v:12, toberemoved:null}, {v:4}];\narraytoclean.map((x,i)=>x.toberemoved=undefined);\nconsole.dir(arraytoclean);</code></pre>\r\n</div>\r\n</div>\r\n</p>\n"
},
{
"answer_id": 58880113,
"author": "gkucmierz",
"author_id": 3573210,
"author_profile": "https://Stackoverflow.com/users/3573210",
"pm_score": 0,
"selected": false,
"text": "<p>I just wrote array intersection that correctly handles also duplicates</p>\n\n<p><a href=\"https://gist.github.com/gkucmierz/8ee04544fa842411f7553ef66ac2fcf0\" rel=\"nofollow noreferrer\">https://gist.github.com/gkucmierz/8ee04544fa842411f7553ef66ac2fcf0</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>// array intersection that correctly handles also duplicates\r\n\r\nconst intersection = (a1, a2) => {\r\n const cnt = new Map();\r\n a2.map(el => cnt[el] = el in cnt ? cnt[el] + 1 : 1);\r\n return a1.filter(el => el in cnt && 0 < cnt[el]--);\r\n};\r\n\r\nconst l = console.log;\r\nl(intersection('1234'.split``, '3456'.split``)); // [ '3', '4' ]\r\nl(intersection('12344'.split``, '3456'.split``)); // [ '3', '4' ]\r\nl(intersection('1234'.split``, '33456'.split``)); // [ '3', '4' ]\r\nl(intersection('12334'.split``, '33456'.split``)); // [ '3', '3', '4' ]</code></pre>\r\n</div>\r\n</div>\r\n</p>\n"
},
{
"answer_id": 61328209,
"author": "Rishab Surana",
"author_id": 6183464,
"author_profile": "https://Stackoverflow.com/users/6183464",
"pm_score": 0,
"selected": false,
"text": "<p>First you can use map and with chaining you can use filter </p>\n\n<pre><code>state.map(item => {\n if(item.id === action.item.id){ \n return {\n id : action.item.id,\n name : item.name,\n price: item.price,\n quantity : item.quantity-1\n }\n\n }else{\n return item;\n }\n }).filter(item => {\n if(item.quantity <= 0){\n return false;\n }else{\n return true;\n }\n });\n</code></pre>\n"
},
{
"answer_id": 66282857,
"author": "Senseful",
"author_id": 35690,
"author_profile": "https://Stackoverflow.com/users/35690",
"pm_score": 1,
"selected": false,
"text": "<p>TLDR: Use <code>map</code> (returning <code>undefined</code> when needed) and <em>then</em> <code>filter</code>.</p>\n<hr />\n<p>First, I believe that a map + filter function is useful since you don't want to repeat a computation in both. Swift originally called this function <code>flatMap</code> but then renamed it to <code>compactMap</code>.</p>\n<p>For example, if we don't have a <code>compactMap</code> function, we might end up with <code>computation</code> defined twice:</p>\n<pre><code> let array = [1, 2, 3, 4, 5, 6, 7, 8];\n let mapped = array\n .filter(x => {\n let computation = x / 2 + 1;\n let isIncluded = computation % 2 === 0;\n return isIncluded;\n })\n .map(x => {\n let computation = x / 2 + 1;\n return `${x} is included because ${computation} is even`\n })\n\n // Output: [2 is included because 2 is even, 6 is included because 4 is even]\n</code></pre>\n<p>Thus <code>compactMap</code> would be useful to reduce duplicate code.</p>\n<p>A really simple way to do something similar to <code>compactMap</code> is to:</p>\n<ol>\n<li>Map on real values or <code>undefined</code>.</li>\n<li>Filter out all the <code>undefined</code> values.</li>\n</ol>\n<p>This of course relies on you never needing to return undefined values as part of your original map function.</p>\n<p>Example:</p>\n<pre><code> let array = [1, 2, 3, 4, 5, 6, 7, 8];\n let mapped = array\n .map(x => {\n let computation = x / 2 + 1;\n let isIncluded = computation % 2 === 0;\n if (isIncluded) {\n return `${x} is included because ${computation} is even`\n } else {\n return undefined\n }\n })\n .filter(x => typeof x !== "undefined")\n</code></pre>\n"
}
] | 2008/08/12 | [
"https://Stackoverflow.com/questions/9289",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/268/"
] | I would like to filter an array of items by using the `map()` function. Here is a code snippet:
```
var filteredItems = items.map(function(item)
{
if( ...some condition... )
{
return item;
}
});
```
The problem is that filtered out items still uses space in the array and I would like to completely wipe them out.
Any idea?
EDIT: Thanks, I forgot about `filter()`, what I wanted is actually a `filter()` then a `map()`.
EDIT2: Thanks for pointing that `map()` and `filter()` are not implemented in all browsers, although my specific code was not intended to run in a browser. | You should use the `filter` method rather than map unless you want to mutate the items in the array, in addition to filtering.
eg.
```
var filteredItems = items.filter(function(item)
{
return ...some condition...;
});
```
[Edit: Of course you could always do `sourceArray.filter(...).map(...)` to both filter and mutate] |
9,301 | <p>I'm having trouble with events in Internet Explorer 7.</p>
<p>When I have a form with <strong>two or more</strong> <code>input[type=text]</code> and I press enter, the events occurs in this order:</p>
<ol>
<li>submit button (<code>onClick</code>)</li>
<li>form (<code>onSubmit</code>)</li>
</ol>
<p>Sample code:</p>
<pre><code><form onSubmit="{alert('form::onSubmit'); return false;}">
<input type="text">
<input type="text">
<input type="submit" onClick="{alert('button::onClick');}">
</form>
</code></pre>
<p>If I have only <strong>one</strong> <code>input[type=text]</code> and I press enter the submit button <code>onClick</code> event doesn't fire. Sample code:</p>
<pre><code><form onSubmit="{alert('form::onSubmit'); return false;}">
<input type="text">
<input type="submit" onClick="{alert('button::onClick');}">
</form>
</code></pre>
| [
{
"answer_id": 9327,
"author": "andrewrk",
"author_id": 432,
"author_profile": "https://Stackoverflow.com/users/432",
"pm_score": 1,
"selected": false,
"text": "<p>If you want code to run when the user presses enter, <strong>just use the onSubmit handler.</strong></p>\n\n<p>If you want code to run when the user presses the button, and <em>not</em> when the user presses enter, use a button other than type=\"submit\".</p>\n"
},
{
"answer_id": 9340,
"author": "TheSmurf",
"author_id": 1975282,
"author_profile": "https://Stackoverflow.com/users/1975282",
"pm_score": 3,
"selected": false,
"text": "<p>The button's onclick should (I think) only fire if the button is actually clicked (or when the focus is on it and the user clicks enter), unless you've added logic to change that.</p>\n\n<p>Is the addition of the extra textbox possibly changing the tab order of your elements (perhaps making the button the default control in that case)?</p>\n"
},
{
"answer_id": 22765,
"author": "bubbassauro",
"author_id": 1328,
"author_profile": "https://Stackoverflow.com/users/1328",
"pm_score": 1,
"selected": false,
"text": "<p>Interestingly, if you click on the screen (remove the focus from the textbox) on second example with only one textbox, the event onClick fires... So it's not an expected behaviour since it only occurs when you have just one textbox <em>and</em> you have the focus on the textbox.<br>\nI'm afraid you've found a bug on the browser and you'll have to find a workaround, or avoid using the onClick event in that case.<br>\nI use the onSubmit event for validations because it's a \"safer\" event that is more likely to work on different browsers and situations.</p>\n"
},
{
"answer_id": 22768,
"author": "Brian Warshaw",
"author_id": 1344,
"author_profile": "https://Stackoverflow.com/users/1344",
"pm_score": 1,
"selected": false,
"text": "<p>Out of curiosity, are you using a DOCTYPE, and if so, which one? I'm not saying incompatabilities with the DOCTYPE are the issue, but quirks mode is something to rule out before trying anything else.</p>\n"
},
{
"answer_id": 3196171,
"author": "mplungjan",
"author_id": 295783,
"author_profile": "https://Stackoverflow.com/users/295783",
"pm_score": 2,
"selected": false,
"text": "<p>From the dawn of browsers, a single input field in a form would submit on enter with or without a submit button. This was to make it simpler for people to search a site from a single search field.</p>\n\n<p>If you need to execute some javascript in a form, it is safer practice to use the onsubmit of the form (and return false to stop submission) rather than executing script in the onClick of the submit button. If you need to execute javascript from a button, use type=\"button\" instead of type=\"submit\" - hope this clarified what I meant</p>\n"
},
{
"answer_id": 35775438,
"author": "Crystal Paladin",
"author_id": 5917094,
"author_profile": "https://Stackoverflow.com/users/5917094",
"pm_score": 0,
"selected": false,
"text": "<p>You might want to include a dummy hidden input element to recreate the situation where you had two input elements... that way, you'll get both of the events fired</p>\n\n<pre><code><FORM onSubmit=\"{alert('form::onSubmit'); return false;}\">\n <INPUT TYPE=\"text\">\n <input type=\"hidden\" name=\"dummy\">\n <INPUT TYPE=\"submit\" onClick=\"{alert('buttom::onClick');}\">\n</FORM>\n</code></pre>\n\n<p>IE has a lot of confusing fixes that needs to be done for improving compatibility of our code</p>\n"
}
] | 2008/08/12 | [
"https://Stackoverflow.com/questions/9301",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1100/"
] | I'm having trouble with events in Internet Explorer 7.
When I have a form with **two or more** `input[type=text]` and I press enter, the events occurs in this order:
1. submit button (`onClick`)
2. form (`onSubmit`)
Sample code:
```
<form onSubmit="{alert('form::onSubmit'); return false;}">
<input type="text">
<input type="text">
<input type="submit" onClick="{alert('button::onClick');}">
</form>
```
If I have only **one** `input[type=text]` and I press enter the submit button `onClick` event doesn't fire. Sample code:
```
<form onSubmit="{alert('form::onSubmit'); return false;}">
<input type="text">
<input type="submit" onClick="{alert('button::onClick');}">
</form>
``` | The button's onclick should (I think) only fire if the button is actually clicked (or when the focus is on it and the user clicks enter), unless you've added logic to change that.
Is the addition of the extra textbox possibly changing the tab order of your elements (perhaps making the button the default control in that case)? |
9,303 | <p>How do you retrieve selected text using Regex in C#?</p>
<p>I am looking for C# code that is equivalent to this Perl code:</p>
<pre><code>$indexVal = 0;
if($string =~ /Index: (\d*)/){$indexVal = $1;}
</code></pre>
| [
{
"answer_id": 9306,
"author": "Patrick",
"author_id": 429,
"author_profile": "https://Stackoverflow.com/users/429",
"pm_score": 4,
"selected": true,
"text": "<pre><code>int indexVal = 0;\nRegex re = new Regex(@\"Index: (\\d*)\")\nMatch m = re.Match(s)\n\nif(m.Success)\n indexVal = int.TryParse(m.Groups[1].toString());\n</code></pre>\n\n<p>I might have the group number wrong, but you should be able to figure it out from here.</p>\n"
},
{
"answer_id": 9307,
"author": "Dillie-O",
"author_id": 71,
"author_profile": "https://Stackoverflow.com/users/71",
"pm_score": 1,
"selected": false,
"text": "<p>You'll want to utilize the matched groups, so something like...</p>\n\n<pre><code>Regex MagicRegex = new Regex(RegexExpressionString);\nMatch RegexMatch;\nstring CapturedResults;\n\nRegexMatch = MagicRegex.Match(SourceDataString);\nCapturedResults = RegexMatch.Groups[1].Value;\n</code></pre>\n"
},
{
"answer_id": 9318,
"author": "Jeff Atwood",
"author_id": 1,
"author_profile": "https://Stackoverflow.com/users/1",
"pm_score": 3,
"selected": false,
"text": "<p>I think Patrick nailed this one -- my only suggestion is to remember that named regex groups exist, too, so you don't <em>have</em> to use array index numbers.</p>\n\n<pre><code>Regex.Match(s, @\"Index (?<num>\\d*)\").Groups[\"num\"].Value\n</code></pre>\n\n<p>I find the regex is a bit more readable this way as well, though <a href=\"http://www.codinghorror.com/blog/archives/001016.html\" rel=\"noreferrer\">opinions vary</a>...</p>\n"
},
{
"answer_id": 9322,
"author": "andynil",
"author_id": 446,
"author_profile": "https://Stackoverflow.com/users/446",
"pm_score": 1,
"selected": false,
"text": "<p>That would be</p>\n\n<pre><code>int indexVal = 0;\nRegex re = new Regex(@\"Index: (\\d*)\");\nMatch m = re.Match(s);\n\nif (m.Success)\n indexVal = m.Groups[1].Index;\n</code></pre>\n\n<p>You can also name you group (here I've also skipped compilation of the regexp)</p>\n\n<pre><code>int indexVal = 0;\nMatch m2 = Regex.Match(s, @\"Index: (?<myIndex>\\d*)\");\n\nif (m2.Success)\n indexVal = m2.Groups[\"myIndex\"].Index;\n</code></pre>\n"
},
{
"answer_id": 11302661,
"author": "burning_LEGION",
"author_id": 1477076,
"author_profile": "https://Stackoverflow.com/users/1477076",
"pm_score": 0,
"selected": false,
"text": "<pre><code>int indexVal = 0;\nRegex re = new Regex.Match(s, @\"(<?=Index: )(\\d*)\");\n\nif(re.Success)\n{\n indexVal = Convert.ToInt32(re.Value);\n}\n</code></pre>\n"
}
] | 2008/08/12 | [
"https://Stackoverflow.com/questions/9303",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/889/"
] | How do you retrieve selected text using Regex in C#?
I am looking for C# code that is equivalent to this Perl code:
```
$indexVal = 0;
if($string =~ /Index: (\d*)/){$indexVal = $1;}
``` | ```
int indexVal = 0;
Regex re = new Regex(@"Index: (\d*)")
Match m = re.Match(s)
if(m.Success)
indexVal = int.TryParse(m.Groups[1].toString());
```
I might have the group number wrong, but you should be able to figure it out from here. |
9,304 | <p><em>Note: This was posted when I was starting out C#. With 2014 knowledge, I can truly say that auto-properties are among the best things that ever happened to the C# language.</em></p>
<p>I am used to create my properties in C# using a private and a public field:</p>
<pre><code>private string title;
public string Title
{
get { return title; }
set { title = value; }
}
</code></pre>
<p>Now, with <a href="http://en.wikipedia.org/wiki/.NET_Framework" rel="noreferrer">.NET</a> 3.0, we got auto-properties:</p>
<pre><code>public string Title { get; set; }
</code></pre>
<p>I know this is more a philosophical/subjective questions, but is there any reason to use these auto-properties except from saving five lines of code for each field? My personal gripe is that those properties are hiding stuff from me, and I am not a big fan of black magic.</p>
<p>In fact, the hidden private field does not even show up in the debugger, which is OK given the fact that the get/set functions do nothing. But when I want to actually implement some getter/setter logic, I have to use the private/public pair anyway.</p>
<p>I see the benefit that I save a lot of code (one vs six lines) without losing the ability to change the getter/setter logic later, but then again I can already do that by simply declaring a public field "Public string Title" without the need of the { get; set; } block, thus even saving more code.</p>
<p>So, what am I missing here? Why would anyone actually want to use auto-properties?</p>
| [
{
"answer_id": 9308,
"author": "Ray",
"author_id": 233,
"author_profile": "https://Stackoverflow.com/users/233",
"pm_score": 5,
"selected": false,
"text": "<p>I personally love auto-properties. What's wrong with saving the lines of code? If you want to do stuff in getters or setters, there's no problem to convert them to normal properties later on.</p>\n\n<p>As you said you could use fields, and if you wanted to add logic to them later you'd convert them to properties. But this might present problems with any use of reflection (and possibly elsewhere?).</p>\n\n<p>Also the properties allow you to set different access levels for the getter and setter which you can't do with a field.</p>\n\n<p>I guess it's the same as the var keyword. A matter of personal preference.</p>\n"
},
{
"answer_id": 9309,
"author": "lomaxx",
"author_id": 493,
"author_profile": "https://Stackoverflow.com/users/493",
"pm_score": 6,
"selected": false,
"text": "<p>The three big downsides to using fields instead of properties are:</p>\n\n<ol>\n<li>You can't databind to a field whereas you can to a property</li>\n<li>If you start off using a field, you can't later (easily) change them to a property</li>\n<li>There are some attributes that you can add to a property that you can't add to a field</li>\n</ol>\n"
},
{
"answer_id": 9310,
"author": "Jeff Atwood",
"author_id": 1,
"author_profile": "https://Stackoverflow.com/users/1",
"pm_score": 8,
"selected": true,
"text": "<p>We use them all the time in Stack Overflow.</p>\n\n<p>You may also be interested in a discussion of <a href=\"http://blog.codinghorror.com/properties-vs-public-variables/\" rel=\"noreferrer\">Properties vs. Public Variables</a>. IMHO that's really what this is a reaction to, and for that purpose, it's great.</p>\n"
},
{
"answer_id": 9315,
"author": "Orion Edwards",
"author_id": 234,
"author_profile": "https://Stackoverflow.com/users/234",
"pm_score": 3,
"selected": false,
"text": "<p>I use auto-properties all the time. Before C#3 I couldn't be bothered with all the typing and just used public variables instead.</p>\n\n<p>The only thing I miss is being able to do this:</p>\n\n<pre><code>public string Name = \"DefaultName\";\n</code></pre>\n\n<p>You have to shift the defaults into your constructors with properties. tedious :-(</p>\n"
},
{
"answer_id": 9342,
"author": "Mike Stone",
"author_id": 122,
"author_profile": "https://Stackoverflow.com/users/122",
"pm_score": 3,
"selected": false,
"text": "<p>I think any construct that is intuitive AND reduces the lines of code is a big plus.</p>\n\n<p>Those kinds of features are what makes languages like Ruby so powerful (that and dynamic features, which also help reduce excess code).</p>\n\n<p>Ruby has had this all along as:</p>\n\n<pre><code>attr_accessor :my_property\nattr_reader :my_getter\nattr_writer :my_setter\n</code></pre>\n"
},
{
"answer_id": 9398,
"author": "David Wengier",
"author_id": 489,
"author_profile": "https://Stackoverflow.com/users/489",
"pm_score": 2,
"selected": false,
"text": "<p>The only problem I have with them is that they don't go far enough. The same release of the compiler that added automatic properties, added partial methods. Why they didnt put the two together is beyond me. A simple \"partial On<PropertyName>Changed\" would have made these things really really useful.</p>\n"
},
{
"answer_id": 9529,
"author": "Keith",
"author_id": 905,
"author_profile": "https://Stackoverflow.com/users/905",
"pm_score": 6,
"selected": false,
"text": "<p>Yes, it does <em>just</em> save code. It's miles easier to read when you have loads of them. They're quicker to write and easier to maintain. Saving code is always a good goal.</p>\n\n<p>You can set different scopes:</p>\n\n<pre><code>public string PropertyName { get; private set; }\n</code></pre>\n\n<p>So that the property can only be changed inside the class. This isn't really immutable as you can still access the private setter through reflection.</p>\n\n<p>As of C#6 you can also create true <code>readonly</code> properties - i.e. immutable properties that cannot be changed outside of the constructor:</p>\n\n<pre><code>public string PropertyName { get; }\n\npublic MyClass() { this.PropertyName = \"whatever\"; }\n</code></pre>\n\n<p>At compile time that will become:</p>\n\n<pre><code>readonly string pName;\npublic string PropertyName { get { return this.pName; } }\n\npublic MyClass() { this.pName = \"whatever\"; }\n</code></pre>\n\n<p>In immutable classes with a lot of members this saves a lot of excess code.</p>\n"
},
{
"answer_id": 13992,
"author": "pbh101",
"author_id": 1266,
"author_profile": "https://Stackoverflow.com/users/1266",
"pm_score": 1,
"selected": false,
"text": "<p>One thing to note here is that, to my understanding, this is <em>just</em> syntactic sugar on the C# 3.0 end, meaning that the IL generated by the compiler is the same. I agree about avoiding black magic, but all the same, fewer lines for the same thing is usually a good thing.</p>\n"
},
{
"answer_id": 14006,
"author": "ESV",
"author_id": 150,
"author_profile": "https://Stackoverflow.com/users/150",
"pm_score": 1,
"selected": false,
"text": "<p>In my opinion, you should always use auto-properties instead of public fields. That said, here's a compromise:</p>\n\n<p>Start off with an <a href=\"http://msdn.microsoft.com/en-us/library/7c5ka91b.aspx\" rel=\"nofollow noreferrer\">internal</a> field using the naming convention you'd use for a property. When you first either</p>\n\n<ul>\n<li>need access to the field from outside its assembly, or </li>\n<li>need to attach logic to a getter/setter</li>\n</ul>\n\n<p>Do this:</p>\n\n<ol>\n<li>rename the field</li>\n<li>make it private</li>\n<li>add a public property</li>\n</ol>\n\n<p>Your client code won't need to change.</p>\n\n<p>Someday, though, your system will grow and you'll decompose it into separate assemblies and multiple solutions. When that happens, any exposed fields will come back to haunt you because, as Jeff mentioned, <a href=\"http://blogs.msdn.com/abhinaba/archive/2006/04/11/572694.aspx\" rel=\"nofollow noreferrer\">changing a public field to a public property is a breaking API change</a>.</p>\n"
},
{
"answer_id": 14048,
"author": "ICR",
"author_id": 214,
"author_profile": "https://Stackoverflow.com/users/214",
"pm_score": 3,
"selected": false,
"text": "<p>Auto-properties are as much a black magic as anything else in C#. Once you think about it in terms of compiling down to IL rather than it being expanded to a normal C# property first it's a lot less black magic than a lot of other language constructs.</p>\n"
},
{
"answer_id": 19624,
"author": "Brian Leahy",
"author_id": 580,
"author_profile": "https://Stackoverflow.com/users/580",
"pm_score": 0,
"selected": false,
"text": "<p>I use CodeRush, it's faster than auto-properties.</p>\n\n<p>To do this:</p>\n\n<pre><code> private string title;\npublic string Title\n{\n get { return title; }\n set { title = value; }\n}\n</code></pre>\n\n<p>Requires eight keystrokes total.</p>\n"
},
{
"answer_id": 30747,
"author": "Domenic",
"author_id": 3191,
"author_profile": "https://Stackoverflow.com/users/3191",
"pm_score": 4,
"selected": false,
"text": "<p>One thing nobody seems to have mentioned is how auto-properties are unfortunately not useful for immutable objects (usually immutable structs). Because for that you really should do:</p>\n\n<pre><code>private readonly string title;\npublic string Title\n{\n get { return this.title; }\n}\n</code></pre>\n\n<p>(where the field is initialized in the constructor via a passed parameter, and then is read only.)</p>\n\n<p>So this has advantages over a simple <code>get</code>/<code>private set</code> autoproperty.</p>\n"
},
{
"answer_id": 35909,
"author": "Andrei Rînea",
"author_id": 1796,
"author_profile": "https://Stackoverflow.com/users/1796",
"pm_score": 0,
"selected": false,
"text": "<p>@Domenic : I don't get it.. can't you do this with auto-properties?:</p>\n\n<pre><code>public string Title { get; }\n</code></pre>\n\n<p>or</p>\n\n<pre><code>public string Title { get; private set; }\n</code></pre>\n\n<p>Is this what you are referring to?</p>\n"
},
{
"answer_id": 48237,
"author": "Omer van Kloeten",
"author_id": 4979,
"author_profile": "https://Stackoverflow.com/users/4979",
"pm_score": 2,
"selected": false,
"text": "<p>It's simple, it's short and if you want to create a real implementation inside the property's body somewhere down the line, it won't break your type's external interface.</p>\n\n<p>As simple as that.</p>\n"
},
{
"answer_id": 182226,
"author": "Giovanni Galbo",
"author_id": 4050,
"author_profile": "https://Stackoverflow.com/users/4050",
"pm_score": 5,
"selected": false,
"text": "<p>From Bjarne Stroustrup, creator of C++:</p>\n\n<blockquote>\n <p>I particularly dislike classes with a lot of get and set functions. That is often an indication that it shouldn't have been a class in the first place. It's just a data structure. And if it really is a data structure, make it a data structure.</p>\n</blockquote>\n\n<p>And you know what? He's right. How often are you simply wrapping private fields in a get and set, without actually doing anything within the get/set, simply because it's the \"object oriented\" thing to do. This is Microsoft's solution to the problem; they're basically public fields that you can bind to.</p>\n"
},
{
"answer_id": 343414,
"author": "Johnno Nolan",
"author_id": 1116,
"author_profile": "https://Stackoverflow.com/users/1116",
"pm_score": 0,
"selected": false,
"text": "<p>My biggest gripe with auto-properties is that they are designed to save time but I often find I have to expand them into full blown properties later.</p>\n\n<p>What VS2008 is missing is an <strong>Explode Auto-Property</strong> refactor.</p>\n\n<p>The fact we have an <strong>encapsulate field</strong> refactor makes the way I work quicker to just use public fields.</p>\n"
},
{
"answer_id": 343495,
"author": "Theo",
"author_id": 43402,
"author_profile": "https://Stackoverflow.com/users/43402",
"pm_score": 4,
"selected": false,
"text": "<p>I always create properties instead of public fields because you can use properties in an interface definition, you can't use public fields in an interface definition. </p>\n"
}
] | 2008/08/12 | [
"https://Stackoverflow.com/questions/9304",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/91/"
] | *Note: This was posted when I was starting out C#. With 2014 knowledge, I can truly say that auto-properties are among the best things that ever happened to the C# language.*
I am used to create my properties in C# using a private and a public field:
```
private string title;
public string Title
{
get { return title; }
set { title = value; }
}
```
Now, with [.NET](http://en.wikipedia.org/wiki/.NET_Framework) 3.0, we got auto-properties:
```
public string Title { get; set; }
```
I know this is more a philosophical/subjective questions, but is there any reason to use these auto-properties except from saving five lines of code for each field? My personal gripe is that those properties are hiding stuff from me, and I am not a big fan of black magic.
In fact, the hidden private field does not even show up in the debugger, which is OK given the fact that the get/set functions do nothing. But when I want to actually implement some getter/setter logic, I have to use the private/public pair anyway.
I see the benefit that I save a lot of code (one vs six lines) without losing the ability to change the getter/setter logic later, but then again I can already do that by simply declaring a public field "Public string Title" without the need of the { get; set; } block, thus even saving more code.
So, what am I missing here? Why would anyone actually want to use auto-properties? | We use them all the time in Stack Overflow.
You may also be interested in a discussion of [Properties vs. Public Variables](http://blog.codinghorror.com/properties-vs-public-variables/). IMHO that's really what this is a reaction to, and for that purpose, it's great. |
9,314 | <p>I have a .NET 2.0 windows forms app, which makes heavy use of the <code>ListView</code> control.</p>
<p>I've subclassed the <code>ListView</code> class into a templated <code>SortableListView<T></code> class, so it can be a bit smarter about how it displays things, and sort itself.</p>
<p>Unfortunately this seems to break the Visual Studio Forms Designer, in both VS2005 and 2008.</p>
<p>The program compiles and runs fine, but when I try view the owning form in the designer, I get these Errors:</p>
<ul>
<li>Could not find type 'MyApp.Controls.SortableListView'. Please make sure that the assembly that contains this type is referenced. If this type is a part of your development project, make sure that the project has been successfully built.</li>
</ul>
<p>There is no stack trace or error line information available for this error </p>
<ul>
<li>The variable 'listViewImages' is either undeclared or was never assigned. </li>
</ul>
<p>At MyApp.Main.Designer.cs Line:XYZ Column:1</p>
<pre><code>Call stack:
at System.ComponentModel.Design.Serialization.CodeDomSerializerBase.Error(IDesignerSerializationManager manager, String exceptionText, String helpLink)
at System.ComponentModel.Design.Serialization.CodeDomSerializerBase.DeserializeExpression(IDesignerSerializationManager manager, String name, CodeExpression expression)
at System.ComponentModel.Design.Serialization.CodeDomSerializerBase.DeserializeExpression(IDesignerSerializationManager manager, String name, CodeExpression expression)
at System.ComponentModel.Design.Serialization.CodeDomSerializerBase.DeserializeStatement(IDesignerSerializationManager manager, CodeStatement statement)
</code></pre>
<p>The line of code in question is where it is actually added to the form, and is</p>
<pre><code>this.imagesTab.Controls.Add( this.listViewImages );
</code></pre>
<p>listViewImages is declared as</p>
<pre><code>private MyApp.Controls.SortableListView<Image> listViewImages;
</code></pre>
<p>and is instantiated in the <code>InitializeComponent</code> method as follows:</p>
<pre><code>this.listViewImages = new MyApp.Controls.SortableListView<Image>();
</code></pre>
<p>As mentioned earlier, the program compiles and runs perfectly, and I've tried shifting the <code>SortableListView</code> class out to a seperate assembly so it can be compiled seperately, but this makes no difference.</p>
<p>I have no idea where to go from here. Any help would be appreciated!</p>
| [
{
"answer_id": 9320,
"author": "lomaxx",
"author_id": 493,
"author_profile": "https://Stackoverflow.com/users/493",
"pm_score": 3,
"selected": false,
"text": "<p>I've had a problem like this (tho not the same) in the past where my control was in a different namespace to my form even tho it was in the same project. To fix it I had to add a </p>\n\n<pre><code>using My.Other.Namespace;\n</code></pre>\n\n<p>to the top of the designer generated code file. The annoying thing was it kept getting blown away when the designer regenerated the page.</p>\n"
},
{
"answer_id": 9345,
"author": "lomaxx",
"author_id": 493,
"author_profile": "https://Stackoverflow.com/users/493",
"pm_score": 2,
"selected": false,
"text": "<p>The assembly that contains MyApp.Controls.SortableListView isn't installed in the GAC by any chance is it?</p>\n"
},
{
"answer_id": 9378,
"author": "lomaxx",
"author_id": 493,
"author_profile": "https://Stackoverflow.com/users/493",
"pm_score": 2,
"selected": false,
"text": "<p>when you added the listview, did you add it to the toolbox and then add it to the form?</p>\n"
},
{
"answer_id": 9387,
"author": "Orion Edwards",
"author_id": 234,
"author_profile": "https://Stackoverflow.com/users/234",
"pm_score": 4,
"selected": true,
"text": "<blockquote>\n <p>when you added the listview, did you add it to the toolbox and then add it to the form?</p>\n</blockquote>\n\n<p>No, I just edited <code>Main.Designer.cs</code> and changed it from <code>System.Windows.Forms.ListView</code> to <code>MyApp.Controls.SortableListView<Image></code></p>\n\n<p>Suspecting it might have been due to the generics led me to actually finding a solution.</p>\n\n<p>For each class that I need to make a SortableListView for, I defined a 'stub class' like this</p>\n\n<pre><code>class ImagesListView : SortableListView<Image> { }\n</code></pre>\n\n<p>Then made the <code>Main.Designer.cs</code> file refer to these stub classes instead of the <code>SortableListView</code>.</p>\n\n<p>It now works, hooray!</p>\n\n<p>Thankfully I am able to do this because all my types are known up front, and I'm only using the <code>SortableListView</code> as a method of reducing duplicate code.</p>\n"
},
{
"answer_id": 1293135,
"author": "Unsliced",
"author_id": 2902,
"author_profile": "https://Stackoverflow.com/users/2902",
"pm_score": 1,
"selected": false,
"text": "<p>I had something similar - a user control was referring to a remote serice (which I couldn't guarantee being available at design time). </p>\n\n<p><a href=\"http://social.msdn.microsoft.com/Forums/en-US/wcf/thread/6d3147b0-8343-44aa-a191-f0e58b96c7ea\" rel=\"nofollow noreferrer\">This post on MSDN</a> suggested that I add </p>\n\n<pre><code>if (this.DesignMode) return;\n</code></pre>\n\n<p>to the Load function of the control, or in my case to the point before the WCF client was initialised. That did the trick. </p>\n\n<p>So</p>\n\n<pre><code>private readonly Client _client = new Client();\n</code></pre>\n\n<p>becomes</p>\n\n<pre><code>private Client _client;\n\npublic new void Load()\n{\n if(DesignMode) return;\n _client = new Client();\n}\n</code></pre>\n"
},
{
"answer_id": 11748957,
"author": "PahanCS",
"author_id": 1566944,
"author_profile": "https://Stackoverflow.com/users/1566944",
"pm_score": 2,
"selected": false,
"text": "<p>Perhaps you forgot to add that:</p>\n\n<pre><code> /// <summary>\n /// Required designer variable.\n /// </summary>\n private System.ComponentModel.IContainer components = null;\n\n /// <summary>\n /// Release all resources used.\n /// </summary>\n /// <param name=\"disposing\">true if managed resources should be removed otherwise; false.</param>\n protected override void Dispose(bool disposing)\n {\n if (disposing && (components != null))\n {\n components.Dispose();\n }\n base.Dispose(disposing);\n }\n\n private void InitializeComponent()\n {\n // ...\n this.components = new System.ComponentModel.Container(); // Not necessarily, if You do not use\n // ...\n }\n</code></pre>\n"
},
{
"answer_id": 12206923,
"author": "Mark Lakata",
"author_id": 364818,
"author_profile": "https://Stackoverflow.com/users/364818",
"pm_score": 3,
"selected": false,
"text": "<p>I had this problem too, related to merging massive SVN changes (with conflicts) in the *.Designer.cs file. The solution was to just open up the design view graphically, edit a control (move it to the left then right) and resave the design. The *.Designer.cs file magically changed, and the warning went away on the next compilation.</p>\n\n<p>To be clear, you need to fix all of the code merge problems first. This is just a work around to force VS to reload them.</p>\n"
},
{
"answer_id": 19428824,
"author": "cAko",
"author_id": 2890786,
"author_profile": "https://Stackoverflow.com/users/2890786",
"pm_score": -1,
"selected": false,
"text": "<p>In my case the problem was the folder's name of my project! Why I think this:\nI use SVN and in the 'trunk\\SGIMovel' works perfectly. But in a branch folder named as 'OS#125\\SGIMovel' I can't open the designer for a form that uses a custom control and works in the trunk folder.</p>\n<p>Just get off the # and works nice.</p>\n"
},
{
"answer_id": 20070749,
"author": "Nila",
"author_id": 2663777,
"author_profile": "https://Stackoverflow.com/users/2663777",
"pm_score": 1,
"selected": false,
"text": "<p>I had the same issue. In my case this issue was due to resource initialization. I moved the following code from <code>InitializeComponent</code> method to ctor(After calling <code>InitializeComponent</code>). After that this issue was resolved:</p>\n\n<pre><code>this->resources = (gcnew System::ComponentModel::ComponentResourceManager(XXX::typeid));\n</code></pre>\n"
},
{
"answer_id": 33771556,
"author": "Val",
"author_id": 681830,
"author_profile": "https://Stackoverflow.com/users/681830",
"pm_score": 5,
"selected": false,
"text": "<p>It happened to me because of x86 / x64 architecture.</p>\n\n<p>Since Visual Studio (the development tool itself) has no x64 version, it's not possible to load x64 control into GUI designer.</p>\n\n<p>The best approach for this might be tuning GUI under x86, and compile it for x64 when necessary.</p>\n"
},
{
"answer_id": 42020055,
"author": "user1027167",
"author_id": 1027167,
"author_profile": "https://Stackoverflow.com/users/1027167",
"pm_score": 2,
"selected": false,
"text": "<p>I have had the same problem. After removing some of my own controls of the *.Designer.cs-File the problem was solved. After going back to the original code the problem still was solved. So it seems to be a problem with the Visual Sudio cache. At the moment I cannot reproduce this problem. </p>\n\n<p>If you have the problem try to emtpy the folder </p>\n\n<p>C:\\Users\\YOURNAME\\AppData\\Local\\Microsoft\\VisualStudio\\VERSION\\Designer\\ShadowCache</p>\n\n<p>Did it work?</p>\n"
}
] | 2008/08/12 | [
"https://Stackoverflow.com/questions/9314",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/234/"
] | I have a .NET 2.0 windows forms app, which makes heavy use of the `ListView` control.
I've subclassed the `ListView` class into a templated `SortableListView<T>` class, so it can be a bit smarter about how it displays things, and sort itself.
Unfortunately this seems to break the Visual Studio Forms Designer, in both VS2005 and 2008.
The program compiles and runs fine, but when I try view the owning form in the designer, I get these Errors:
* Could not find type 'MyApp.Controls.SortableListView'. Please make sure that the assembly that contains this type is referenced. If this type is a part of your development project, make sure that the project has been successfully built.
There is no stack trace or error line information available for this error
* The variable 'listViewImages' is either undeclared or was never assigned.
At MyApp.Main.Designer.cs Line:XYZ Column:1
```
Call stack:
at System.ComponentModel.Design.Serialization.CodeDomSerializerBase.Error(IDesignerSerializationManager manager, String exceptionText, String helpLink)
at System.ComponentModel.Design.Serialization.CodeDomSerializerBase.DeserializeExpression(IDesignerSerializationManager manager, String name, CodeExpression expression)
at System.ComponentModel.Design.Serialization.CodeDomSerializerBase.DeserializeExpression(IDesignerSerializationManager manager, String name, CodeExpression expression)
at System.ComponentModel.Design.Serialization.CodeDomSerializerBase.DeserializeStatement(IDesignerSerializationManager manager, CodeStatement statement)
```
The line of code in question is where it is actually added to the form, and is
```
this.imagesTab.Controls.Add( this.listViewImages );
```
listViewImages is declared as
```
private MyApp.Controls.SortableListView<Image> listViewImages;
```
and is instantiated in the `InitializeComponent` method as follows:
```
this.listViewImages = new MyApp.Controls.SortableListView<Image>();
```
As mentioned earlier, the program compiles and runs perfectly, and I've tried shifting the `SortableListView` class out to a seperate assembly so it can be compiled seperately, but this makes no difference.
I have no idea where to go from here. Any help would be appreciated! | >
> when you added the listview, did you add it to the toolbox and then add it to the form?
>
>
>
No, I just edited `Main.Designer.cs` and changed it from `System.Windows.Forms.ListView` to `MyApp.Controls.SortableListView<Image>`
Suspecting it might have been due to the generics led me to actually finding a solution.
For each class that I need to make a SortableListView for, I defined a 'stub class' like this
```
class ImagesListView : SortableListView<Image> { }
```
Then made the `Main.Designer.cs` file refer to these stub classes instead of the `SortableListView`.
It now works, hooray!
Thankfully I am able to do this because all my types are known up front, and I'm only using the `SortableListView` as a method of reducing duplicate code. |
9,321 | <p>How do you create a static class in C++? I should be able to do something like:</p>
<pre><code>cout << "bit 5 is " << BitParser::getBitAt(buffer, 5) << endl;
</code></pre>
<p>Assuming I created the <code>BitParser</code> class. What would the <code>BitParser</code> class definition look like?</p>
| [
{
"answer_id": 9326,
"author": "Philip Reynolds",
"author_id": 1087,
"author_profile": "https://Stackoverflow.com/users/1087",
"pm_score": 4,
"selected": false,
"text": "<p>In C++ you want to create a static function of a class (not a static class).</p>\n\n<pre><code>class BitParser {\npublic:\n ...\n static ... getBitAt(...) {\n }\n};\n</code></pre>\n\n<p>You should then be able to call the function using BitParser::getBitAt() without instantiating an object which I presume is the desired result.</p>\n"
},
{
"answer_id": 9328,
"author": "OJ.",
"author_id": 611,
"author_profile": "https://Stackoverflow.com/users/611",
"pm_score": 9,
"selected": true,
"text": "<p>If you're looking for a way of applying the "static" keyword to a class, like you can in C# for example, then you won't be able to without using Managed C++.</p>\n<p>But the looks of your sample, you just need to create a public static method on your BitParser object. Like so:</p>\n<p><strong>BitParser.h</strong></p>\n<pre><code>class BitParser\n{\n public:\n static bool getBitAt(int buffer, int bitIndex);\n\n // ...lots of great stuff\n\n private:\n // Disallow creating an instance of this object\n BitParser() {}\n};\n</code></pre>\n<p><strong>BitParser.cpp</strong></p>\n<pre><code>bool BitParser::getBitAt(int buffer, int bitIndex)\n{\n bool isBitSet = false;\n // .. determine if bit is set\n return isBitSet;\n}\n</code></pre>\n<p>You can use this code to call the method in the same way as your example code.</p>\n"
},
{
"answer_id": 9339,
"author": "Orion Edwards",
"author_id": 234,
"author_profile": "https://Stackoverflow.com/users/234",
"pm_score": 4,
"selected": false,
"text": "<blockquote>\n <p>If you're looking for a way of applying the \"static\" keyword to a class, like you can in C# for example</p>\n</blockquote>\n\n<p>static classes are just the compiler hand-holding you and stopping you from writing any instance methods/variables.</p>\n\n<p>If you just write a normal class without any instance methods/variables, it's the same thing, and this is what you'd do in C++</p>\n"
},
{
"answer_id": 9348,
"author": "Matt Price",
"author_id": 852,
"author_profile": "https://Stackoverflow.com/users/852",
"pm_score": 6,
"selected": false,
"text": "<p>You can also create a free function in a namespace:</p>\n\n<p>In BitParser.h</p>\n\n<pre><code>namespace BitParser\n{\n bool getBitAt(int buffer, int bitIndex);\n}\n</code></pre>\n\n<p>In BitParser.cpp</p>\n\n<pre><code>namespace BitParser\n{\n bool getBitAt(int buffer, int bitIndex)\n {\n //get the bit :)\n }\n}\n</code></pre>\n\n<p>In general this would be the preferred way to write the code. When there's no need for an object don't use a class.</p>\n"
},
{
"answer_id": 112451,
"author": "paercebal",
"author_id": 14089,
"author_profile": "https://Stackoverflow.com/users/14089",
"pm_score": 8,
"selected": false,
"text": "<p>Consider <a href=\"https://stackoverflow.com/questions/9321/how-do-you-create-a-static-class-in-c/9348#9348\">Matt Price's solution</a>.</p>\n\n<ol>\n<li>In C++, a \"static class\" has no meaning. The nearest thing is a class with only static methods and members.</li>\n<li>Using static methods will only limit you.</li>\n</ol>\n\n<p>What you want is, expressed in C++ semantics, to put your function (for it <strong>is</strong> a function) in a namespace.</p>\n\n<h2>Edit 2011-11-11</h2>\n\n<p>There is no \"static class\" in C++. The nearest concept would be a class with only static methods. For example:</p>\n\n<pre><code>// header\nclass MyClass\n{\n public :\n static void myMethod() ;\n} ;\n\n// source\nvoid MyClass::myMethod()\n{\n // etc.\n}\n</code></pre>\n\n<p>But you must remember that \"static classes\" are hacks in the Java-like kind of languages (e.g. C#) that are unable to have non-member functions, so they have instead to move them inside classes as static methods.</p>\n\n<p>In C++, what you really want is a non-member function that you'll declare in a namespace:</p>\n\n<pre><code>// header\nnamespace MyNamespace\n{\n void myMethod() ;\n}\n\n// source\nnamespace MyNamespace\n{\n void myMethod()\n {\n // etc.\n }\n}\n</code></pre>\n\n<h3>Why is that?</h3>\n\n<p>In C++, the namespace is more powerful than classes for the \"Java static method\" pattern, because:</p>\n\n<ul>\n<li>static methods have access to the classes private symbols</li>\n<li>private static methods are still visible (if inaccessible) to everyone, which breaches somewhat the encapsulation</li>\n<li>static methods cannot be forward-declared</li>\n<li>static methods cannot be overloaded by the class user without modifying the library header</li>\n<li>there is nothing that can be done by a static method that can't be done better than a (possibly friend) non-member function in the same namespace</li>\n<li>namespaces have their own semantics (they can be combined, they can be anonymous, etc.)</li>\n<li>etc.</li>\n</ul>\n\n<p>Conclusion: Do not copy/paste that Java/C#'s pattern in C++. In Java/C#, the pattern is mandatory. But in C++, it is bad style.</p>\n\n<h2>Edit 2010-06-10</h2>\n\n<p>There was an argument in favor to the static method because sometimes, one needs to use a static private member variable.</p>\n\n<p>I disagree somewhat, as show below:</p>\n\n<h3>The \"Static private member\" solution</h3>\n\n<pre><code>// HPP\n\nclass Foo\n{\n public :\n void barA() ;\n private :\n void barB() ;\n static std::string myGlobal ;\n} ;\n</code></pre>\n\n<p>First, myGlobal is called myGlobal because it is still a global private variable. A look at the CPP source will clarify that:</p>\n\n<pre><code>// CPP\nstd::string Foo::myGlobal ; // You MUST declare it in a CPP\n\nvoid Foo::barA()\n{\n // I can access Foo::myGlobal\n}\n\nvoid Foo::barB()\n{\n // I can access Foo::myGlobal, too\n}\n\nvoid barC()\n{\n // I CAN'T access Foo::myGlobal !!!\n}\n</code></pre>\n\n<p>At first sight, the fact the free function barC can't access Foo::myGlobal seems a good thing from an encapsulation viewpoint... It's cool because someone looking at the HPP won't be able (unless resorting to sabotage) to access Foo::myGlobal.</p>\n\n<p>But if you look at it closely, you'll find that it is a colossal mistake: Not only your private variable must still be declared in the HPP (and so, visible to all the world, despite being private), but you must declare in the same HPP all (as in ALL) functions that will be authorized to access it !!!</p>\n\n<p>So <b>using a private static member is like walking outside in the nude with the list of your lovers tattooed on your skin : No one is authorized to touch, but everyone is able to peek at. And the bonus: Everyone can have the names of those authorized to play with your privies.</b></p>\n\n<p><code>private</code> indeed...\n:-D</p>\n\n<h3>The \"Anonymous namespaces\" solution</h3>\n\n<p>Anonymous namespaces will have the advantage of making things private really private.</p>\n\n<p>First, the HPP header</p>\n\n<pre><code>// HPP\n\nnamespace Foo\n{\n void barA() ;\n}\n</code></pre>\n\n<p>Just to be sure you remarked: There is no useless declaration of barB nor myGlobal. Which means that no one reading the header knows what's hidden behind barA.</p>\n\n<p>Then, the CPP:</p>\n\n<pre><code>// CPP\nnamespace Foo\n{\n namespace\n {\n std::string myGlobal ;\n\n void Foo::barB()\n {\n // I can access Foo::myGlobal\n }\n }\n\n void barA()\n {\n // I can access myGlobal, too\n }\n}\n\nvoid barC()\n{\n // I STILL CAN'T access myGlobal !!!\n}\n</code></pre>\n\n<p>As you can see, like the so-called \"static class\" declaration, fooA and fooB are still able to access myGlobal. But no one else can. And no one else outside this CPP knows fooB and myGlobal even exist!</p>\n\n<p><b>Unlike the \"static class\" walking on the nude with her address book tattooed on her skin the \"anonymous\" namespace is fully clothed</b>, which seems quite better encapsulated AFAIK.</p>\n\n<h3>Does it really matter?</h3>\n\n<p>Unless the users of your code are saboteurs (I'll let you, as an exercise, find how one can access to the private part of a public class using a dirty behaviour-undefined hack...), what's <code>private</code> is <code>private</code>, even if it is visible in the <code>private</code> section of a class declared in a header.</p>\n\n<p>Still, if you need to add another \"private function\" with access to the private member, you still must declare it to all the world by modifying the header, which is a paradox as far as I am concerned: <b>If I change the implementation of my code (the CPP part), then the interface (the HPP part) should NOT change.</b> Quoting Leonidas : \"<b>This is ENCAPSULATION!</b>\"</p>\n\n<h2>Edit 2014-09-20</h2>\n\n<p>When are classes static methods are actually better than namespaces with non-member functions?</p>\n\n<p>When you need to group together functions and feed that group to a template:</p>\n\n<pre><code>namespace alpha\n{\n void foo() ;\n void bar() ;\n}\n\nstruct Beta\n{\n static void foo() ;\n static void bar() ;\n};\n\ntemplate <typename T>\nstruct Gamma\n{\n void foobar()\n {\n T::foo() ;\n T::bar() ;\n }\n};\n\nGamma<alpha> ga ; // compilation error\nGamma<Beta> gb ; // ok\ngb.foobar() ; // ok !!!\n</code></pre>\n\n<p>Because, if a class can be a template parameter, a namespaces cannot.</p>\n"
},
{
"answer_id": 1785945,
"author": "Netzer",
"author_id": 217347,
"author_profile": "https://Stackoverflow.com/users/217347",
"pm_score": 3,
"selected": false,
"text": "<p>You 'can' have a static class in C++, as mentioned before, a static class is one that does not have any objects of it instantiated it. In C++, this can be obtained by declaring the constructor/destructor as private. End result is the same.</p>\n"
},
{
"answer_id": 2715977,
"author": "John",
"author_id": 326261,
"author_profile": "https://Stackoverflow.com/users/326261",
"pm_score": 2,
"selected": false,
"text": "<p>This is similar to C#'s way of doing it in C++</p>\n\n<p>In C# file.cs you can have private var inside a public function.\nWhen in another file you can use it by calling the namespace with the function as in:</p>\n\n<pre><code>MyNamespace.Function(blah);\n</code></pre>\n\n<p>Here's how to imp the same in C++:</p>\n\n<p><strong>SharedModule.h</strong></p>\n\n<pre><code>class TheDataToBeHidden\n{\n public:\n static int _var1;\n static int _var2;\n};\n\nnamespace SharedData\n{\n void SetError(const char *Message, const char *Title);\n void DisplayError(void);\n}\n</code></pre>\n\n<p><strong>SharedModule.cpp</strong></p>\n\n<pre><code>//Init the data (Link error if not done)\nint TheDataToBeHidden::_var1 = 0;\nint TheDataToBeHidden::_var2 = 0;\n\n\n//Implement the namespace\nnamespace SharedData\n{\n void SetError(const char *Message, const char *Title)\n {\n //blah using TheDataToBeHidden::_var1, etc\n }\n\n void DisplayError(void)\n {\n //blah\n }\n}\n</code></pre>\n\n<hr>\n\n<p><strong>OtherFile.h</strong></p>\n\n<pre><code>#include \"SharedModule.h\"\n</code></pre>\n\n<p><strong>OtherFile.cpp</strong></p>\n\n<pre><code>//Call the functions using the hidden variables\nSharedData::SetError(\"Hello\", \"World\");\nSharedData::DisplayError();\n</code></pre>\n"
},
{
"answer_id": 3015915,
"author": "Malc B",
"author_id": 363621,
"author_profile": "https://Stackoverflow.com/users/363621",
"pm_score": 2,
"selected": false,
"text": "<p>In Managed C++, static class syntax is:-</p>\n\n<pre><code>public ref class BitParser abstract sealed\n{\n public:\n static bool GetBitAt(...)\n {\n ...\n }\n}\n</code></pre>\n\n<p>... better late than never...</p>\n"
},
{
"answer_id": 21423774,
"author": "Bharath Ravindra",
"author_id": 2022210,
"author_profile": "https://Stackoverflow.com/users/2022210",
"pm_score": 2,
"selected": false,
"text": "<p>Unlike other managed programming language, \"static class\" has NO meaning in C++. You can make use of static member function. </p>\n"
},
{
"answer_id": 31201984,
"author": "Ciro Santilli OurBigBook.com",
"author_id": 895245,
"author_profile": "https://Stackoverflow.com/users/895245",
"pm_score": 4,
"selected": false,
"text": "<p><strong>Can I write something like <code>static class</code>?</strong></p>\n\n<p><strong>No</strong>, according to the <a href=\"http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2012/n3337.pdf\" rel=\"nofollow noreferrer\">C++11 N3337 standard draft</a> Annex C 7.1.1:</p>\n\n<blockquote>\n <p>Change: In C ++, the static or extern specifiers can only be applied to names of objects or functions.\n Using these specifiers with type declarations is illegal in C ++. In C, these specifiers are ignored when used\n on type declarations. Example:</p>\n\n<pre><code>static struct S { // valid C, invalid in C++\n int i;\n};\n</code></pre>\n \n <p>Rationale: Storage class specifiers don’t have any meaning when associated with a type. In C ++, class\n members can be declared with the static storage class specifier. Allowing storage class specifiers on type\n declarations could render the code confusing for users.</p>\n</blockquote>\n\n<p>And like <code>struct</code>, <code>class</code> is also a type declaration.</p>\n\n<p>The same can be deduced by walking the syntax tree in Annex A.</p>\n\n<p>It is interesting to note that <code>static struct</code> was legal in C, but had no effect: <a href=\"https://stackoverflow.com/questions/7259830/why-and-when-to-use-static-structures-in-c-programming\">Why and when to use static structures in C programming?</a></p>\n"
},
{
"answer_id": 49405640,
"author": "Mikhail Vasilyev",
"author_id": 4432988,
"author_profile": "https://Stackoverflow.com/users/4432988",
"pm_score": 3,
"selected": false,
"text": "<p>As it has been noted here, a better way of achieving this in C++ might be using namespaces. But since no one has mentioned the <code>final</code> keyword here, I'm posting what a direct equivalent of <code>static class</code> from C# would look like in C++11 or later:</p>\n\n<pre><code>class BitParser final\n{\npublic:\n BitParser() = delete;\n\n static bool GetBitAt(int buffer, int pos);\n};\n\nbool BitParser::GetBitAt(int buffer, int pos)\n{\n // your code\n}\n</code></pre>\n"
},
{
"answer_id": 50016722,
"author": "Josh Olson",
"author_id": 9209968,
"author_profile": "https://Stackoverflow.com/users/9209968",
"pm_score": 0,
"selected": false,
"text": "<p>One case where namespaces may not be so useful for achieving \"static classes\" is when using these classes to achieve composition over inheritance. Namespaces cannot be friends of classes and so cannot access private members of a class.</p>\n\n<pre><code>class Class {\n public:\n void foo() { Static::bar(*this); } \n\n private:\n int member{0};\n friend class Static;\n}; \n\nclass Static {\n public:\n template <typename T>\n static void bar(T& t) {\n t.member = 1;\n }\n};\n</code></pre>\n"
},
{
"answer_id": 61626014,
"author": "hecate",
"author_id": 6426767,
"author_profile": "https://Stackoverflow.com/users/6426767",
"pm_score": 2,
"selected": false,
"text": "<p>One (of the many) alternative, but the most (in my opinion) elegant (in comparison to using namespaces and private constructors to emulate the static behavior), way to achieve the \"class that cannot be instantiated\" behavior in C++ would be to declare a dummy pure virtual function with the <code>private</code> access modifier.</p>\n\n<pre><code>class Foo {\n public:\n static int someMethod(int someArg);\n\n private:\n virtual void __dummy() = 0;\n};\n</code></pre>\n\n<p>If you are using C++11, you could go the extra mile to ensure that the class is not inherited (to purely emulate the behavior of a static class) by using the <code>final</code> specifier in the class declaration to restrict the other classes from inheriting it.</p>\n\n<pre><code>// C++11 ONLY\nclass Foo final {\n public:\n static int someMethod(int someArg);\n\n private:\n virtual void __dummy() = 0;\n};\n</code></pre>\n\n<p>As silly and illogical as it may sound, C++11 allows the declaration of a \"pure virtual function that cannot be overridden\", which you can use alongside declaring the class <code>final</code> to purely and fully implement the static behavior as this results in the resultant class to not be inheritable and the dummy function to not be overridden in any way.</p>\n\n<pre><code>// C++11 ONLY\nclass Foo final {\n public:\n static int someMethod(int someArg);\n\n private:\n // Other private declarations\n\n virtual void __dummy() = 0 final;\n}; // Foo now exhibits all the properties of a static class\n</code></pre>\n"
},
{
"answer_id": 66422537,
"author": "Саша Зезюлинский",
"author_id": 857684,
"author_profile": "https://Stackoverflow.com/users/857684",
"pm_score": 0,
"selected": false,
"text": "<pre><code>class A final {\n ~A() = delete;\n static bool your_func();\n}\n</code></pre>\n<p><code>final</code> means that a class cannot be inherited from.</p>\n<p><code>delete</code> for a destructor means that you can not create an instance of such a class.</p>\n<p>This pattern is also know as an "util" class.</p>\n<p>As many say the concept of <code>static class</code> doesn't exist in C++.</p>\n<p>A canonical <code>namespace</code> that contains <code>static</code> functions preferred as a solution in this case.</p>\n"
},
{
"answer_id": 68140352,
"author": "Sarath Govind",
"author_id": 12284466,
"author_profile": "https://Stackoverflow.com/users/12284466",
"pm_score": 0,
"selected": false,
"text": "<p>There is no such thing as a static class in C++. The closest approximation is a class that only contains static data members and static methods.\nStatic data members in a class are shared by all the class objects as there is only one copy of them in memory, regardless of the number of objects of the class.\nA static method of a class can access all other static members ,static methods and methods outside the class</p>\n"
}
] | 2008/08/12 | [
"https://Stackoverflow.com/questions/9321",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/432/"
] | How do you create a static class in C++? I should be able to do something like:
```
cout << "bit 5 is " << BitParser::getBitAt(buffer, 5) << endl;
```
Assuming I created the `BitParser` class. What would the `BitParser` class definition look like? | If you're looking for a way of applying the "static" keyword to a class, like you can in C# for example, then you won't be able to without using Managed C++.
But the looks of your sample, you just need to create a public static method on your BitParser object. Like so:
**BitParser.h**
```
class BitParser
{
public:
static bool getBitAt(int buffer, int bitIndex);
// ...lots of great stuff
private:
// Disallow creating an instance of this object
BitParser() {}
};
```
**BitParser.cpp**
```
bool BitParser::getBitAt(int buffer, int bitIndex)
{
bool isBitSet = false;
// .. determine if bit is set
return isBitSet;
}
```
You can use this code to call the method in the same way as your example code. |
9,336 | <p>I'm trying to generate a sitemap.xml on the fly for a particular asp.net website.</p>
<p>I found a couple solutions:<br /></p>
<ol>
<li><a href="http://sitemap.chinookwebs.com/" rel="nofollow noreferrer">chinookwebs</a></li>
<li><a href="http://web.archive.org/web/20080307061444/http://www.cervoproject.info:80/sitemaps.aspx" rel="nofollow noreferrer">cervoproject</a></li>
<li><a href="http://www.codeplex.com/Sitemaps" rel="nofollow noreferrer">newtonking</a></li>
</ol>
<p>Chinookwebs is working great but seems a bit inactive right now and it's impossible to personalize the "priority" and the "changefreq" tags of each and every page, they all inherit the same value from the config file.</p>
<p>What solutions do you guys use?</p>
| [
{
"answer_id": 9360,
"author": "Nick Berardi",
"author_id": 17,
"author_profile": "https://Stackoverflow.com/users/17",
"pm_score": 0,
"selected": false,
"text": "<p>Custom handler to generate the sitemap. </p>\n"
},
{
"answer_id": 9382,
"author": "Matt Mitchell",
"author_id": 364,
"author_profile": "https://Stackoverflow.com/users/364",
"pm_score": 0,
"selected": false,
"text": "<p>Using ASP.NET MVC just whipped up a quick bit of code using the .NET XML generation library and then just passed that to a view page that had an XML control on it. In the code-behind I tied the control with the ViewData. This seemed to override the default behaviour of view pages to present a different header.</p>\n"
},
{
"answer_id": 9533,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 4,
"selected": true,
"text": "<p>Usually you'll use an <a href=\"http://www.google.com/search?q=HTTPHandler+ASP.NET&spell=1\" rel=\"noreferrer\">HTTP Handler</a> for this. Given a request for...</p>\n\n<blockquote>\n <p><a href=\"http://www.yoursite.com/sitemap.axd\" rel=\"noreferrer\">http://www.yoursite.com/sitemap.axd</a></p>\n</blockquote>\n\n<p>...your handler will respond with a formatted XML sitemap. Whether that sitemap is generated on the fly, from a database, or some other method is up to the HTTP Handler implementation.</p>\n\n<p>Here's roughly what it would look like:</p>\n\n<pre><code>void IHttpHandler.ProcessRequest(HttpContext context)\n{\n //\n // Important to return qualified XML (text/xml) for sitemaps\n //\n context.Response.ClearHeaders();\n context.Response.ClearContent();\n context.Response.ContentType = \"text/xml\";\n //\n // Create an XML writer\n //\n XmlTextWriter writer = new XmlTextWriter(context.Response.Output);\n writer.WriteStartDocument();\n writer.WriteStartElement(\"urlset\", \"http://www.sitemaps.org/schemas/sitemap/0.9\");\n //\n // Now add entries for individual pages..\n //\n writer.WriteStartElement(\"url\");\n writer.WriteElementString(\"loc\", \"http://www.codingthewheel.com\");\n // use W3 date format..\n writer.WriteElementString(\"lastmod\", postDate.ToString(\"yyyy-MM-dd\"));\n writer.WriteElementString(\"changefreq\", \"daily\");\n writer.WriteElementString(\"priority\", \"1.0\");\n writer.WriteEndElement();\n //\n // Close everything out and go home.\n //\n result.WriteEndElement();\n result.WriteEndDocument();\n writer.Flush();\n}\n</code></pre>\n\n<p>This code can be improved but that's the basic idea.</p>\n"
}
] | 2008/08/13 | [
"https://Stackoverflow.com/questions/9336",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/296/"
] | I'm trying to generate a sitemap.xml on the fly for a particular asp.net website.
I found a couple solutions:
1. [chinookwebs](http://sitemap.chinookwebs.com/)
2. [cervoproject](http://web.archive.org/web/20080307061444/http://www.cervoproject.info:80/sitemaps.aspx)
3. [newtonking](http://www.codeplex.com/Sitemaps)
Chinookwebs is working great but seems a bit inactive right now and it's impossible to personalize the "priority" and the "changefreq" tags of each and every page, they all inherit the same value from the config file.
What solutions do you guys use? | Usually you'll use an [HTTP Handler](http://www.google.com/search?q=HTTPHandler+ASP.NET&spell=1) for this. Given a request for...
>
> <http://www.yoursite.com/sitemap.axd>
>
>
>
...your handler will respond with a formatted XML sitemap. Whether that sitemap is generated on the fly, from a database, or some other method is up to the HTTP Handler implementation.
Here's roughly what it would look like:
```
void IHttpHandler.ProcessRequest(HttpContext context)
{
//
// Important to return qualified XML (text/xml) for sitemaps
//
context.Response.ClearHeaders();
context.Response.ClearContent();
context.Response.ContentType = "text/xml";
//
// Create an XML writer
//
XmlTextWriter writer = new XmlTextWriter(context.Response.Output);
writer.WriteStartDocument();
writer.WriteStartElement("urlset", "http://www.sitemaps.org/schemas/sitemap/0.9");
//
// Now add entries for individual pages..
//
writer.WriteStartElement("url");
writer.WriteElementString("loc", "http://www.codingthewheel.com");
// use W3 date format..
writer.WriteElementString("lastmod", postDate.ToString("yyyy-MM-dd"));
writer.WriteElementString("changefreq", "daily");
writer.WriteElementString("priority", "1.0");
writer.WriteEndElement();
//
// Close everything out and go home.
//
result.WriteEndElement();
result.WriteEndDocument();
writer.Flush();
}
```
This code can be improved but that's the basic idea. |
9,338 | <p>One of the articles I really enjoyed reading recently was <a href="http://blog.last.fm/2008/08/01/quality-control" rel="nofollow noreferrer">Quality Control by Last.FM</a>. In the spirit of this article, I was wondering if anyone else had favorite monitoring setups for web type applications. Or maybe if you don't believe in Log Monitoring, why?<br>
I'm looking for a mix of opinion slash experience here I guess.</p>
| [
{
"answer_id": 9360,
"author": "Nick Berardi",
"author_id": 17,
"author_profile": "https://Stackoverflow.com/users/17",
"pm_score": 0,
"selected": false,
"text": "<p>Custom handler to generate the sitemap. </p>\n"
},
{
"answer_id": 9382,
"author": "Matt Mitchell",
"author_id": 364,
"author_profile": "https://Stackoverflow.com/users/364",
"pm_score": 0,
"selected": false,
"text": "<p>Using ASP.NET MVC just whipped up a quick bit of code using the .NET XML generation library and then just passed that to a view page that had an XML control on it. In the code-behind I tied the control with the ViewData. This seemed to override the default behaviour of view pages to present a different header.</p>\n"
},
{
"answer_id": 9533,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 4,
"selected": true,
"text": "<p>Usually you'll use an <a href=\"http://www.google.com/search?q=HTTPHandler+ASP.NET&spell=1\" rel=\"noreferrer\">HTTP Handler</a> for this. Given a request for...</p>\n\n<blockquote>\n <p><a href=\"http://www.yoursite.com/sitemap.axd\" rel=\"noreferrer\">http://www.yoursite.com/sitemap.axd</a></p>\n</blockquote>\n\n<p>...your handler will respond with a formatted XML sitemap. Whether that sitemap is generated on the fly, from a database, or some other method is up to the HTTP Handler implementation.</p>\n\n<p>Here's roughly what it would look like:</p>\n\n<pre><code>void IHttpHandler.ProcessRequest(HttpContext context)\n{\n //\n // Important to return qualified XML (text/xml) for sitemaps\n //\n context.Response.ClearHeaders();\n context.Response.ClearContent();\n context.Response.ContentType = \"text/xml\";\n //\n // Create an XML writer\n //\n XmlTextWriter writer = new XmlTextWriter(context.Response.Output);\n writer.WriteStartDocument();\n writer.WriteStartElement(\"urlset\", \"http://www.sitemaps.org/schemas/sitemap/0.9\");\n //\n // Now add entries for individual pages..\n //\n writer.WriteStartElement(\"url\");\n writer.WriteElementString(\"loc\", \"http://www.codingthewheel.com\");\n // use W3 date format..\n writer.WriteElementString(\"lastmod\", postDate.ToString(\"yyyy-MM-dd\"));\n writer.WriteElementString(\"changefreq\", \"daily\");\n writer.WriteElementString(\"priority\", \"1.0\");\n writer.WriteEndElement();\n //\n // Close everything out and go home.\n //\n result.WriteEndElement();\n result.WriteEndDocument();\n writer.Flush();\n}\n</code></pre>\n\n<p>This code can be improved but that's the basic idea.</p>\n"
}
] | 2008/08/13 | [
"https://Stackoverflow.com/questions/9338",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1063/"
] | One of the articles I really enjoyed reading recently was [Quality Control by Last.FM](http://blog.last.fm/2008/08/01/quality-control). In the spirit of this article, I was wondering if anyone else had favorite monitoring setups for web type applications. Or maybe if you don't believe in Log Monitoring, why?
I'm looking for a mix of opinion slash experience here I guess. | Usually you'll use an [HTTP Handler](http://www.google.com/search?q=HTTPHandler+ASP.NET&spell=1) for this. Given a request for...
>
> <http://www.yoursite.com/sitemap.axd>
>
>
>
...your handler will respond with a formatted XML sitemap. Whether that sitemap is generated on the fly, from a database, or some other method is up to the HTTP Handler implementation.
Here's roughly what it would look like:
```
void IHttpHandler.ProcessRequest(HttpContext context)
{
//
// Important to return qualified XML (text/xml) for sitemaps
//
context.Response.ClearHeaders();
context.Response.ClearContent();
context.Response.ContentType = "text/xml";
//
// Create an XML writer
//
XmlTextWriter writer = new XmlTextWriter(context.Response.Output);
writer.WriteStartDocument();
writer.WriteStartElement("urlset", "http://www.sitemaps.org/schemas/sitemap/0.9");
//
// Now add entries for individual pages..
//
writer.WriteStartElement("url");
writer.WriteElementString("loc", "http://www.codingthewheel.com");
// use W3 date format..
writer.WriteElementString("lastmod", postDate.ToString("yyyy-MM-dd"));
writer.WriteElementString("changefreq", "daily");
writer.WriteElementString("priority", "1.0");
writer.WriteEndElement();
//
// Close everything out and go home.
//
result.WriteEndElement();
result.WriteEndDocument();
writer.Flush();
}
```
This code can be improved but that's the basic idea. |
9,341 | <p>Simple ASP.NET application.</p>
<p>I have two drop-down controls. On the first-drop down I have a JavaScript <code>onChange</code> event. The JavaScript enables the second drop-down and removes a value from it (the value selected in the first drop-down). If they click the blank first value of the drop-down, then the second drop-down will be disabled (and the options reset).</p>
<p>I also have code in the <code>OnPreRender</code> method that will enable or disable the second drop-down based on the value of the first drop-down. This is so that the value of the first drop-down can be selected in code (loading user settings).</p>
<p>My problem is:</p>
<ol>
<li>The user selects something in the first drop-down. The second drop-down will become enabled through JavaScript. </li>
<li>They then change a third drop-down that initiates a post back. After the post back the drop-downs are in the correct state (first value selected, second drop-down enabled).</li>
<li>If they then click the back button, the second drop-down will no longer be enabled although it should be since there's something selected in the first drop-down.</li>
</ol>
<p>I've tried adding a startup script (that will set the correct state of the second-drop down) through <code>ClientScript.RegisterStartupScript</code>, however when this gets called the first drop-down has a <code>selectedIndex</code> of <code>0</code>, not what it actually is. My guess is that the value of the selection gets set after my start script (but still doesn't call the <code>onChange</code> script).</p>
<p>Any ideas on what to try?</p>
| [
{
"answer_id": 9343,
"author": "TheSmurf",
"author_id": 1975282,
"author_profile": "https://Stackoverflow.com/users/1975282",
"pm_score": 2,
"selected": false,
"text": "<p>If the second dropdown is initially enabled through javascript (I'm assuming this is during a javascript onchange, since you didn't specify), then clicking the back button to reload the previous postback will never enable it. </p>\n\n<p>Mixing ASP.NET with classic javascript can be hairy. You might want to have a look at ASP.NET's Ajax implementation (or the third-party AjaxPanel control if you're forced to use an older ASP.NET version). Those will give you the behaviour that you want through pure C#, without forcing you to resort to javascript hackery-pokery.</p>\n"
},
{
"answer_id": 9365,
"author": "Adhip Gupta",
"author_id": 384,
"author_profile": "https://Stackoverflow.com/users/384",
"pm_score": 3,
"selected": true,
"text": "<pre><code><%@ Page Language=\"C#\" %>\n\n<!DOCTYPE html PUBLIC \"-//W3C//DTD XHTML 1.0 Transitional//EN\" \"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd\">\n\n<script runat=\"server\">\n protected void indexChanged(object sender, EventArgs e)\n {\n Label1.Text = \" I did something! \";\n }\n</script>\n\n<html xmlns=\"http://www.w3.org/1999/xhtml\">\n<head runat=\"server\">\n <title>Test Page</title>\n</head>\n<body>\n <script type=\"text/javascript\">\n function firstChanged() {\n if(document.getElementById(\"firstSelect\").selectedIndex != 0)\n document.getElementById(\"secondSelect\").disabled = false;\n else\n document.getElementById(\"secondSelect\").disabled = true;\n }\n </script>\n <form id=\"form1\" runat=\"server\">\n <div>\n <select id=\"firstSelect\" onchange=\"firstChanged()\">\n <option value=\"0\"></option>\n <option value=\"1\">One</option>\n <option value=\"2\">Two</option>\n <option value=\"3\">Three</option>\n </select>\n <select id=\"secondSelect\" disabled=\"disabled\">\n <option value=\"1\">One</option>\n <option value=\"2\">Two</option>\n <option value=\"3\">Three</option>\n </select>\n <asp:DropDownList ID=\"DropDownList1\" AutoPostBack=\"true\" OnSelectedIndexChanged=\"indexChanged\" runat=\"server\">\n <asp:ListItem Text=\"One\" Value=\"1\"></asp:ListItem>\n <asp:ListItem Text=\"Two\" Value=\"2\"></asp:ListItem> \n </asp:DropDownList>\n <asp:Label ID=\"Label1\" runat=\"server\"></asp:Label>\n </div>\n </form>\n <script type=\"text/javascript\">\n window.onload = function() {firstChanged();}\n </script>\n</body>\n</html>\n</code></pre>\n\n<p>Edit: Replaced the whole code. This should work even in your user control.\nI believe that Register.ClientScriptBlock is not working because the code you write in that block is executed <em>before</em> window.onload is called. And, I assume (I am not sure of this point) that the DOM objects do not have their values set at that time. And, this is why you are getting selectedIndex as always 0.</p>\n"
}
] | 2008/08/13 | [
"https://Stackoverflow.com/questions/9341",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/233/"
] | Simple ASP.NET application.
I have two drop-down controls. On the first-drop down I have a JavaScript `onChange` event. The JavaScript enables the second drop-down and removes a value from it (the value selected in the first drop-down). If they click the blank first value of the drop-down, then the second drop-down will be disabled (and the options reset).
I also have code in the `OnPreRender` method that will enable or disable the second drop-down based on the value of the first drop-down. This is so that the value of the first drop-down can be selected in code (loading user settings).
My problem is:
1. The user selects something in the first drop-down. The second drop-down will become enabled through JavaScript.
2. They then change a third drop-down that initiates a post back. After the post back the drop-downs are in the correct state (first value selected, second drop-down enabled).
3. If they then click the back button, the second drop-down will no longer be enabled although it should be since there's something selected in the first drop-down.
I've tried adding a startup script (that will set the correct state of the second-drop down) through `ClientScript.RegisterStartupScript`, however when this gets called the first drop-down has a `selectedIndex` of `0`, not what it actually is. My guess is that the value of the selection gets set after my start script (but still doesn't call the `onChange` script).
Any ideas on what to try? | ```
<%@ Page Language="C#" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<script runat="server">
protected void indexChanged(object sender, EventArgs e)
{
Label1.Text = " I did something! ";
}
</script>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title>Test Page</title>
</head>
<body>
<script type="text/javascript">
function firstChanged() {
if(document.getElementById("firstSelect").selectedIndex != 0)
document.getElementById("secondSelect").disabled = false;
else
document.getElementById("secondSelect").disabled = true;
}
</script>
<form id="form1" runat="server">
<div>
<select id="firstSelect" onchange="firstChanged()">
<option value="0"></option>
<option value="1">One</option>
<option value="2">Two</option>
<option value="3">Three</option>
</select>
<select id="secondSelect" disabled="disabled">
<option value="1">One</option>
<option value="2">Two</option>
<option value="3">Three</option>
</select>
<asp:DropDownList ID="DropDownList1" AutoPostBack="true" OnSelectedIndexChanged="indexChanged" runat="server">
<asp:ListItem Text="One" Value="1"></asp:ListItem>
<asp:ListItem Text="Two" Value="2"></asp:ListItem>
</asp:DropDownList>
<asp:Label ID="Label1" runat="server"></asp:Label>
</div>
</form>
<script type="text/javascript">
window.onload = function() {firstChanged();}
</script>
</body>
</html>
```
Edit: Replaced the whole code. This should work even in your user control.
I believe that Register.ClientScriptBlock is not working because the code you write in that block is executed *before* window.onload is called. And, I assume (I am not sure of this point) that the DOM objects do not have their values set at that time. And, this is why you are getting selectedIndex as always 0. |
9,355 | <p>I can display and select a single file in windows explorer like this:</p>
<pre><code>explorer.exe /select, "c:\path\to\file.txt"
</code></pre>
<p>However, I can't work out how to select more than one file. None of the permutations of select I've tried work.</p>
<p>Note: I looked at these pages for docs, neither helped.</p>
<p><a href="https://support.microsoft.com/kb/314853" rel="nofollow noreferrer">https://support.microsoft.com/kb/314853</a><br />
<a href="http://web.archive.org/web/20100716112458/http://www.infocellar.com:80/Win98/explorer-switches.htm" rel="nofollow noreferrer">http://web.archive.org/web/20100716112458/http://www.infocellar.com:80/Win98/explorer-switches.htm</a></p>
| [
{
"answer_id": 9359,
"author": "Nick Berardi",
"author_id": 17,
"author_profile": "https://Stackoverflow.com/users/17",
"pm_score": 2,
"selected": false,
"text": "<p>it cannot be done through explorer.exe</p>\n"
},
{
"answer_id": 9497,
"author": "bruceatk",
"author_id": 791,
"author_profile": "https://Stackoverflow.com/users/791",
"pm_score": 2,
"selected": false,
"text": "<p>Depending on what you actually want to accomplish you may be able to do it with <a href=\"http://www.autohotkey.com/\" rel=\"nofollow noreferrer\">AutoHotKey</a>. It is an amazing free tool for automating things you normally can't do. It should come with Windows. This script will select your file and highlight the next two files below it when you hit F12.</p>\n\n<pre><code>F12:: \n run explorer.exe /select`, \"c:\\path\\to\\file.txt\"\n SendInput {Shift Down}{Down}{Down}{Shift Up}\nreturn\n</code></pre>\n\n<p>It is also possible to just put those two middle lines in a text file and then pass it is a parm to autohotkey.exe. They have an option to compile the script also, which would make it a standalone exe that you could call. Works great with a great help file. </p>\n\n<p>@Orion, It is possible to use autohotkey from C#. You can make an autohotkey script into a standalone executable (about 400k) that can be launched by your C# app (just the way you are launching explorer). You can also pass it command line parameters. It does not have any runtime requirements.</p>\n"
},
{
"answer_id": 13920,
"author": "Orion Edwards",
"author_id": 234,
"author_profile": "https://Stackoverflow.com/users/234",
"pm_score": 1,
"selected": false,
"text": "<blockquote>\n <p>This is one of those questions where it may be good to consider what you're trying to achieve, and whether there's a better method.</p>\n</blockquote>\n\n<p>To add some more context - \nOur company develops a C# client application, which allows users to load files and do stuff with them, kind of like how iTunes manages your MP3 files without showing you the actual file on disk.</p>\n\n<p>It's useful to select a file in the application, and do a 'Show me this file in Windows Explorer` command - this is what I'm trying to achieve, and have done so for single files.</p>\n\n<p>We have a ListView which allows users to select multiple files within the application, and move/delete/etc them. It would be nice to have this 'show me this file in windows' command work for multiple selected files - at least if all the source files are in the same directory, but if it's not possible then it's not a major feature.</p>\n"
},
{
"answer_id": 233129,
"author": "PhiLho",
"author_id": 15459,
"author_profile": "https://Stackoverflow.com/users/15459",
"pm_score": 0,
"selected": false,
"text": "<p>I suppose you can use <code>FindWindowEx</code> to get the SysListView32 of Windows Explorer, then use <code>SendMessage</code> with <code>LVM_SETITEMSTATE</code> to select the items. The difficulty being to know the position of the items... Perhaps <code>LVM_FINDITEM</code> can be used for this.</p>\n"
},
{
"answer_id": 339174,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 0,
"selected": false,
"text": "<p>Grr i would like to do this as well. Media Player does it when you select 2+ files and right click and do \"open file location\" but not exactly sure how (nor do i really feel like spending the time w/ procmon to figure it out).</p>\n"
},
{
"answer_id": 3011284,
"author": "flashk",
"author_id": 25149,
"author_profile": "https://Stackoverflow.com/users/25149",
"pm_score": 5,
"selected": true,
"text": "<p>This should be possible with the shell function <a href=\"http://msdn.microsoft.com/en-us/library/bb762232(VS.85).aspx\" rel=\"noreferrer\"><code>SHOpenFolderAndSelectItems</code></a></p>\n\n<p><strong>EDIT</strong></p>\n\n<p>Here is some sample code showing how to use the function in C/C++, without error checking:</p>\n\n<pre><code>//Directory to open\nITEMIDLIST *dir = ILCreateFromPath(_T(\"C:\\\\\"));\n\n//Items in directory to select\nITEMIDLIST *item1 = ILCreateFromPath(_T(\"C:\\\\Program Files\\\\\"));\nITEMIDLIST *item2 = ILCreateFromPath(_T(\"C:\\\\Windows\\\\\"));\nconst ITEMIDLIST* selection[] = {item1,item2};\nUINT count = sizeof(selection) / sizeof(ITEMIDLIST);\n\n//Perform selection\nSHOpenFolderAndSelectItems(dir, count, selection, 0);\n\n//Free resources\nILFree(dir);\nILFree(item1);\nILFree(item2);\n</code></pre>\n"
},
{
"answer_id": 3576444,
"author": "Siarhei Kuchuk",
"author_id": 212746,
"author_profile": "https://Stackoverflow.com/users/212746",
"pm_score": 3,
"selected": false,
"text": "<p>The true way of selecting multiple files in Explorer is the next</p>\n\n<p>Unmanaged code looks like this (compiled from China code posts with fixing its bugs)</p>\n\n<pre><code>static class NativeMethods\n{\n [DllImport(\"shell32.dll\", ExactSpelling = true)]\n public static extern int SHOpenFolderAndSelectItems(\n IntPtr pidlFolder,\n uint cidl,\n [In, MarshalAs(UnmanagedType.LPArray)] IntPtr[] apidl,\n uint dwFlags);\n\n [DllImport(\"shell32.dll\", CharSet = CharSet.Auto)]\n public static extern IntPtr ILCreateFromPath([MarshalAs(UnmanagedType.LPTStr)] string pszPath);\n\n [ComImport]\n [InterfaceType(ComInterfaceType.InterfaceIsIUnknown)]\n [Guid(\"000214F9-0000-0000-C000-000000000046\")]\n public interface IShellLinkW\n {\n [PreserveSig]\n int GetPath(StringBuilder pszFile, int cch, [In, Out] ref WIN32_FIND_DATAW pfd, uint fFlags);\n\n [PreserveSig]\n int GetIDList([Out] out IntPtr ppidl);\n\n [PreserveSig]\n int SetIDList([In] ref IntPtr pidl);\n\n [PreserveSig]\n int GetDescription(StringBuilder pszName, int cch);\n\n [PreserveSig]\n int SetDescription([MarshalAs(UnmanagedType.LPWStr)] string pszName);\n\n [PreserveSig]\n int GetWorkingDirectory(StringBuilder pszDir, int cch);\n\n [PreserveSig]\n int SetWorkingDirectory([MarshalAs(UnmanagedType.LPWStr)] string pszDir);\n\n [PreserveSig]\n int GetArguments(StringBuilder pszArgs, int cch);\n\n [PreserveSig]\n int SetArguments([MarshalAs(UnmanagedType.LPWStr)] string pszArgs);\n\n [PreserveSig]\n int GetHotkey([Out] out ushort pwHotkey);\n\n [PreserveSig]\n int SetHotkey(ushort wHotkey);\n\n [PreserveSig]\n int GetShowCmd([Out] out int piShowCmd);\n\n [PreserveSig]\n int SetShowCmd(int iShowCmd);\n\n [PreserveSig]\n int GetIconLocation(StringBuilder pszIconPath, int cch, [Out] out int piIcon);\n\n [PreserveSig]\n int SetIconLocation([MarshalAs(UnmanagedType.LPWStr)] string pszIconPath, int iIcon);\n\n [PreserveSig]\n int SetRelativePath([MarshalAs(UnmanagedType.LPWStr)] string pszPathRel, uint dwReserved);\n\n [PreserveSig]\n int Resolve(IntPtr hwnd, uint fFlags);\n\n [PreserveSig]\n int SetPath([MarshalAs(UnmanagedType.LPWStr)] string pszFile);\n }\n\n [Serializable, StructLayout(LayoutKind.Sequential, CharSet = CharSet.Unicode), BestFitMapping(false)]\n public struct WIN32_FIND_DATAW\n {\n public uint dwFileAttributes;\n public FILETIME ftCreationTime;\n public FILETIME ftLastAccessTime;\n public FILETIME ftLastWriteTime;\n public uint nFileSizeHigh;\n public uint nFileSizeLow;\n public uint dwReserved0;\n public uint dwReserved1;\n\n [MarshalAs(UnmanagedType.ByValTStr, SizeConst = 260)]\n public string cFileName;\n\n [MarshalAs(UnmanagedType.ByValTStr, SizeConst = 14)]\n public string cAlternateFileName;\n }\n\n public static void OpenFolderAndSelectFiles(string folder, params string[] filesToSelect)\n {\n IntPtr dir = ILCreateFromPath(folder);\n\n var filesToSelectIntPtrs = new IntPtr[filesToSelect.Length];\n for (int i = 0; i < filesToSelect.Length; i++)\n {\n filesToSelectIntPtrs[i] = ILCreateFromPath(filesToSelect[i]);\n }\n\n SHOpenFolderAndSelectItems(dir, (uint) filesToSelect.Length, filesToSelectIntPtrs, 0);\n ReleaseComObject(dir);\n ReleaseComObject(filesToSelectIntPtrs);\n }\n\n private static void ReleaseComObject(params object[] comObjs)\n {\n foreach (object obj in comObjs)\n {\n if (obj != null && Marshal.IsComObject(obj))\n Marshal.ReleaseComObject(obj);\n }\n }\n}\n</code></pre>\n"
},
{
"answer_id": 59517153,
"author": "stax76",
"author_id": 4526366,
"author_profile": "https://Stackoverflow.com/users/4526366",
"pm_score": 2,
"selected": false,
"text": "<p>There are COM Automation LateBinding IDispatch interfaces, these are easy to use from PowerShell, Visual Basic.NET and C#, some sample code:</p>\n\n<pre><code>$shell = New-Object -ComObject Shell.Application\n\nfunction SelectFiles($filesToSelect)\n{\n foreach ($fileToSelect in $filesToSelect)\n {\n foreach ($window in $shell.Windows())\n {\n foreach ($folderItem in $window.Document.Folder.Items())\n {\n if ($folderItem.Path -eq $fileToSelect)\n {\n $window.Document.SelectItem($folderItem, 1 + 8)\n }\n }\n }\n }\n}\n</code></pre>\n\n<p>-</p>\n\n<pre><code>Option Strict Off\n\nImports Microsoft.VisualBasic\n\nPublic Class ExplorerHelp\n Shared ShellApp As Object = CreateObject(\"Shell.Application\")\n\n Shared Sub SelectFile(filepath As String)\n For Each i In ShellApp.Windows\n For Each i2 In i.Document.Folder.Items()\n If i2.Path = filepath Then\n i.Document.SelectItem(i2, 1 + 8)\n Exit Sub\n End If\n Next\n Next\n End Sub\nEnd Class\n</code></pre>\n\n<p><a href=\"https://learn.microsoft.com/en-us/windows/win32/shell/shellfolderview-selectitem\" rel=\"nofollow noreferrer\">https://learn.microsoft.com/en-us/windows/win32/shell/shellfolderview-selectitem</a></p>\n"
}
] | 2008/08/13 | [
"https://Stackoverflow.com/questions/9355",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/234/"
] | I can display and select a single file in windows explorer like this:
```
explorer.exe /select, "c:\path\to\file.txt"
```
However, I can't work out how to select more than one file. None of the permutations of select I've tried work.
Note: I looked at these pages for docs, neither helped.
<https://support.microsoft.com/kb/314853>
<http://web.archive.org/web/20100716112458/http://www.infocellar.com:80/Win98/explorer-switches.htm> | This should be possible with the shell function [`SHOpenFolderAndSelectItems`](http://msdn.microsoft.com/en-us/library/bb762232(VS.85).aspx)
**EDIT**
Here is some sample code showing how to use the function in C/C++, without error checking:
```
//Directory to open
ITEMIDLIST *dir = ILCreateFromPath(_T("C:\\"));
//Items in directory to select
ITEMIDLIST *item1 = ILCreateFromPath(_T("C:\\Program Files\\"));
ITEMIDLIST *item2 = ILCreateFromPath(_T("C:\\Windows\\"));
const ITEMIDLIST* selection[] = {item1,item2};
UINT count = sizeof(selection) / sizeof(ITEMIDLIST);
//Perform selection
SHOpenFolderAndSelectItems(dir, count, selection, 0);
//Free resources
ILFree(dir);
ILFree(item1);
ILFree(item2);
``` |
9,409 | <p>I have a datagrid getting bound to a dataset, and I want to display the average result in the footer for a column populated with integers.</p>
<p>The way I figure, there's 2 ways I can think of:</p>
<p>1."Use the <strong>Source</strong>, Luke"<br>
In the code where I'm calling DataGrid.DataBind(), use the DataTable.Compute() method (<em>or in my case DataSet.DataTable(0).Compute()</em>). For example: </p>
<pre><code>Dim strAverage = DataTable.Compute("Avg(ColumnName)", "")
</code></pre>
<p>But once I have this, how can I insert it into the footer?</p>
<p>2."<strong>Bound</strong> for Glory"<br>
Using the DataGrid.ItemDataBound event, and calculating a running total from every ListItemType.Item and ListItemType.AlternatingItem, finally displaying in ListItemType.Footer. For example: </p>
<pre><code>Select Case e.Item.ItemType
Case ListItemType.Item, ListItemType.AlternatingItem
runningTotal += CInt(e.Item.Cells(2).Text)
Case ListItemType.Footer
e.Item.Cells(2).Text = runningTotal/DataGrid.Items.Count
End Select
</code></pre>
<p>This just feels wrong, plus I would have to make sure the runningTotal is reset on every DataBind. </p>
<p>Is there a better way?</p>
| [
{
"answer_id": 9384,
"author": "Ray",
"author_id": 233,
"author_profile": "https://Stackoverflow.com/users/233",
"pm_score": 4,
"selected": true,
"text": "<p>See this KB Article. <a href=\"http://support.microsoft.com/default.aspx?scid=kb;EN-US;914277\" rel=\"noreferrer\">How to configure SQL Server 2005 to allow remote connections</a>.<br>\nOh, and remember that the SQLServer name will probably be MyMachineName\\SQLExpress</p>\n"
},
{
"answer_id": 9896,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 1,
"selected": false,
"text": "<p>If you're running it on a 2k3 box, you need to install all updates for Sql Server and the 2003 server. </p>\n\n<p>Check the event logs after you start the Sql Server. It logs everything well, telling you if its being blocked, and where it is listening for connections.</p>\n\n<p>From a remote machine, you can use telnet to see if a sql server is listening for remote connections. You just need the IP and the port of the server (default is 1433). From the command line:</p>\n\n<pre><code>telnet 192.168.10.10 1433\n</code></pre>\n\n<p>If you get a blank screen, its listening. If you get thrown back to the command prompt, something is blocking you.</p>\n"
}
] | 2008/08/13 | [
"https://Stackoverflow.com/questions/9409",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/952/"
] | I have a datagrid getting bound to a dataset, and I want to display the average result in the footer for a column populated with integers.
The way I figure, there's 2 ways I can think of:
1."Use the **Source**, Luke"
In the code where I'm calling DataGrid.DataBind(), use the DataTable.Compute() method (*or in my case DataSet.DataTable(0).Compute()*). For example:
```
Dim strAverage = DataTable.Compute("Avg(ColumnName)", "")
```
But once I have this, how can I insert it into the footer?
2."**Bound** for Glory"
Using the DataGrid.ItemDataBound event, and calculating a running total from every ListItemType.Item and ListItemType.AlternatingItem, finally displaying in ListItemType.Footer. For example:
```
Select Case e.Item.ItemType
Case ListItemType.Item, ListItemType.AlternatingItem
runningTotal += CInt(e.Item.Cells(2).Text)
Case ListItemType.Footer
e.Item.Cells(2).Text = runningTotal/DataGrid.Items.Count
End Select
```
This just feels wrong, plus I would have to make sure the runningTotal is reset on every DataBind.
Is there a better way? | See this KB Article. [How to configure SQL Server 2005 to allow remote connections](http://support.microsoft.com/default.aspx?scid=kb;EN-US;914277).
Oh, and remember that the SQLServer name will probably be MyMachineName\SQLExpress |
9,410 | <p>I want to create a function that performs a function passed by parameter on a set of data. How do you pass a function as a parameter in C?</p>
| [
{
"answer_id": 9411,
"author": "saint_groceon",
"author_id": 59,
"author_profile": "https://Stackoverflow.com/users/59",
"pm_score": 2,
"selected": false,
"text": "<p>You need to pass a <a href=\"http://www.newty.de/fpt/fpt.html#passPtr\" rel=\"nofollow noreferrer\">function pointer</a>. The syntax is a little cumbersome, but it's really powerful once you get familiar with it.</p>\n"
},
{
"answer_id": 9413,
"author": "Niyaz",
"author_id": 184,
"author_profile": "https://Stackoverflow.com/users/184",
"pm_score": 11,
"selected": true,
"text": "<p><strong>Declaration</strong></p>\n\n<p>A prototype for a function which takes a function parameter looks like the following:</p>\n\n<pre><code>void func ( void (*f)(int) );\n</code></pre>\n\n<p>This states that the parameter <code>f</code> will be a pointer to a function which has a <code>void</code> return type and which takes a single <code>int</code> parameter. The following function (<code>print</code>) is an example of a function which could be passed to <code>func</code> as a parameter because it is the proper type:</p>\n\n<pre><code>void print ( int x ) {\n printf(\"%d\\n\", x);\n}\n</code></pre>\n\n<p><strong>Function Call</strong></p>\n\n<p>When calling a function with a function parameter, the value passed must be a pointer to a function. Use the function's name (without parentheses) for this:</p>\n\n<pre><code>func(print);\n</code></pre>\n\n<p>would call <code>func</code>, passing the print function to it.</p>\n\n<p><strong>Function Body</strong></p>\n\n<p>As with any parameter, <code>func</code> can now use the parameter's name in the function body to access the value of the parameter. Let's say that <code>func</code> will apply the function it is passed to the numbers 0-4. Consider, first, what the loop would look like to call print directly:</p>\n\n<pre><code>for ( int ctr = 0 ; ctr < 5 ; ctr++ ) {\n print(ctr);\n}\n</code></pre>\n\n<p>Since <code>func</code>'s parameter declaration says that <code>f</code> is the name for a pointer to the desired function, we recall first that if <code>f</code> is a pointer then <code>*f</code> is the thing that <code>f</code> points to (i.e. the function <code>print</code> in this case). As a result, just replace every occurrence of print in the loop above with <code>*f</code>:</p>\n\n<pre><code>void func ( void (*f)(int) ) {\n for ( int ctr = 0 ; ctr < 5 ; ctr++ ) {\n (*f)(ctr);\n }\n}\n</code></pre>\n\n<p><a href=\"http://math.hws.edu/bridgeman/courses/331/f05/handouts/c-c++-notes.html\" rel=\"noreferrer\">Source</a></p>\n"
},
{
"answer_id": 9421,
"author": "roo",
"author_id": 716,
"author_profile": "https://Stackoverflow.com/users/716",
"pm_score": 7,
"selected": false,
"text": "<p>This question already has the answer for defining function pointers, however they can get very messy, especially if you are going to be passing them around your application. To avoid this unpleasantness I would recommend that you typedef the function pointer into something more readable. For example.</p>\n\n<pre><code>typedef void (*functiontype)();\n</code></pre>\n\n<p>Declares a function that returns void and takes no arguments. To create a function pointer to this type you can now do:</p>\n\n<pre><code>void dosomething() { }\n\nfunctiontype func = &dosomething;\nfunc();\n</code></pre>\n\n<p>For a function that returns an int and takes a char you would do</p>\n\n<pre><code>typedef int (*functiontype2)(char);\n</code></pre>\n\n<p>and to use it</p>\n\n<pre><code>int dosomethingwithchar(char a) { return 1; }\n\nfunctiontype2 func2 = &dosomethingwithchar\nint result = func2('a');\n</code></pre>\n\n<p>There are libraries that can help with turning function pointers into nice readable types. The <a href=\"http://www.boost.org/doc/libs/1_36_0/doc/html/function.html\" rel=\"noreferrer\">boost function</a> library is great and is well worth the effort!</p>\n\n<pre><code>boost::function<int (char a)> functiontype2;\n</code></pre>\n\n<p>is so much nicer than the above.</p>\n"
},
{
"answer_id": 31521586,
"author": "Richard",
"author_id": 752843,
"author_profile": "https://Stackoverflow.com/users/752843",
"pm_score": 7,
"selected": false,
"text": "<p>Since C++11 you can use the <a href=\"http://www.cplusplus.com/reference/functional/function/function/\" rel=\"noreferrer\">functional library</a> to do this in a succinct and generic fashion. The syntax is, e.g.,</p>\n\n<pre><code>std::function<bool (int)>\n</code></pre>\n\n<p>where <code>bool</code> is the return type here of a one-argument function whose first argument is of type <code>int</code>.</p>\n\n<p>I have included an example program below:</p>\n\n<pre><code>// g++ test.cpp --std=c++11\n#include <functional>\n\ndouble Combiner(double a, double b, std::function<double (double,double)> func){\n return func(a,b);\n}\n\ndouble Add(double a, double b){\n return a+b;\n}\n\ndouble Mult(double a, double b){\n return a*b;\n}\n\nint main(){\n Combiner(12,13,Add);\n Combiner(12,13,Mult);\n}\n</code></pre>\n\n<p>Sometimes, though, it is more convenient to use a template function:</p>\n\n<pre><code>// g++ test.cpp --std=c++11\n\ntemplate<class T>\ndouble Combiner(double a, double b, T func){\n return func(a,b);\n}\n\ndouble Add(double a, double b){\n return a+b;\n}\n\ndouble Mult(double a, double b){\n return a*b;\n}\n\nint main(){\n Combiner(12,13,Add);\n Combiner(12,13,Mult);\n}\n</code></pre>\n"
},
{
"answer_id": 33870738,
"author": "Yogeesh H T",
"author_id": 3725702,
"author_profile": "https://Stackoverflow.com/users/3725702",
"pm_score": 5,
"selected": false,
"text": "<p>Pass <strong>address of a function as parameter to another function</strong> as shown below</p>\n\n<pre><code>#include <stdio.h>\n\nvoid print();\nvoid execute(void());\n\nint main()\n{\n execute(print); // sends address of print\n return 0;\n}\n\nvoid print()\n{\n printf(\"Hello!\");\n}\n\nvoid execute(void f()) // receive address of print\n{\n f();\n}\n</code></pre>\n\n<p>Also we can pass function as parameter using <strong>function pointer</strong></p>\n\n<pre><code>#include <stdio.h>\n\nvoid print();\nvoid execute(void (*f)());\n\nint main()\n{\n execute(&print); // sends address of print\n return 0;\n}\n\nvoid print()\n{\n printf(\"Hello!\");\n}\n\nvoid execute(void (*f)()) // receive address of print\n{\n f();\n}\n</code></pre>\n"
},
{
"answer_id": 53503192,
"author": "doppelheathen",
"author_id": 4206613,
"author_profile": "https://Stackoverflow.com/users/4206613",
"pm_score": 4,
"selected": false,
"text": "<p>Functions can be \"passed\" as function pointers, as per ISO C11 6.7.6.3p8: \"<em>A declaration of a parameter as ‘‘function returning type’’ shall be adjusted to ‘‘pointer to function returning type’’</em>, as in 6.3.2.1. \". For example, this:</p>\n\n<pre><code>void foo(int bar(int, int));\n</code></pre>\n\n<p>is equivalent to this:</p>\n\n<pre><code>void foo(int (*bar)(int, int));\n</code></pre>\n"
},
{
"answer_id": 55174838,
"author": "Walter",
"author_id": 7270598,
"author_profile": "https://Stackoverflow.com/users/7270598",
"pm_score": -1,
"selected": false,
"text": "<p>It's not really a function, but it is an localised piece of code. Of course it doesn't pass the code just the result. It won't work if passed to an event dispatcher to be run at a later time (as the result is calculated now and not when the event occurs). But it does localise your code into one place if that is all you are trying to do.</p>\n\n<pre><code>#include <stdio.h>\n\nint IncMultInt(int a, int b)\n{\n a++;\n return a * b;\n}\n\nint main(int argc, char *argv[])\n\n{\n int a = 5;\n int b = 7;\n\n printf(\"%d * %d = %d\\n\", a, b, IncMultInt(a, b));\n\n b = 9;\n\n // Create some local code with it's own local variable\n printf(\"%d * %d = %d\\n\", a, b, ( { int _a = a+1; _a * b; } ) );\n\n return 0;\n}\n</code></pre>\n"
},
{
"answer_id": 65977096,
"author": "Hemanth Kollipara",
"author_id": 11534375,
"author_profile": "https://Stackoverflow.com/users/11534375",
"pm_score": 2,
"selected": false,
"text": "<p>I am gonna explain with a simple example code which takes a <code>compare</code> function as parameter to another <code>sorting</code> function.\nLets say I have a bubble sort function that takes a custom compare function and uses it instead of a fixed if statement.</p>\n<p>Compare Function</p>\n<pre><code>bool compare(int a, int b) {\n return a > b;\n}\n</code></pre>\n<p>Now , the Bubble sort that takes another function as its parameter to perform comparison</p>\n<p>Bubble sort function</p>\n<pre><code>void bubble_sort(int arr[], int n, bool (&cmp)(int a, int b)) {\n\n for (int i = 0;i < n - 1;i++) {\n for (int j = 0;j < (n - 1 - i);j++) {\n \n if (cmp(arr[j], arr[j + 1])) {\n swap(arr[j], arr[j + 1]);\n }\n }\n }\n}\n</code></pre>\n<p>Finally , the <code>main</code> which calls the Bubble sort function by passing the boolean compare function as argument.</p>\n<pre><code>int main()\n{\n int i, n = 10, key = 11;\n int arr[10] = { 20, 22, 18, 8, 12, 3, 6, 12, 11, 15 };\n\n bubble_sort(arr, n, compare);\n cout<<"Sorted Order"<<endl;\n for (int i = 0;i < n;i++) {\n cout << arr[i] << " ";\n }\n}\n</code></pre>\n<p>Output:</p>\n<pre><code>Sorted Order\n3 6 8 11 12 12 15 18 20 22\n</code></pre>\n"
},
{
"answer_id": 69301994,
"author": "mada",
"author_id": 16972547,
"author_profile": "https://Stackoverflow.com/users/16972547",
"pm_score": -1,
"selected": false,
"text": "<pre><code>typedef int function();\n\nfunction *g(function *f)\n{\n f();\n return f;\n}\n\nint main(void)\n{\n function f;\n\n function *fn = g(f);\n\n fn();\n}\n\nint f() { return 0; }\n</code></pre>\n"
}
] | 2008/08/13 | [
"https://Stackoverflow.com/questions/9410",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/432/"
] | I want to create a function that performs a function passed by parameter on a set of data. How do you pass a function as a parameter in C? | **Declaration**
A prototype for a function which takes a function parameter looks like the following:
```
void func ( void (*f)(int) );
```
This states that the parameter `f` will be a pointer to a function which has a `void` return type and which takes a single `int` parameter. The following function (`print`) is an example of a function which could be passed to `func` as a parameter because it is the proper type:
```
void print ( int x ) {
printf("%d\n", x);
}
```
**Function Call**
When calling a function with a function parameter, the value passed must be a pointer to a function. Use the function's name (without parentheses) for this:
```
func(print);
```
would call `func`, passing the print function to it.
**Function Body**
As with any parameter, `func` can now use the parameter's name in the function body to access the value of the parameter. Let's say that `func` will apply the function it is passed to the numbers 0-4. Consider, first, what the loop would look like to call print directly:
```
for ( int ctr = 0 ; ctr < 5 ; ctr++ ) {
print(ctr);
}
```
Since `func`'s parameter declaration says that `f` is the name for a pointer to the desired function, we recall first that if `f` is a pointer then `*f` is the thing that `f` points to (i.e. the function `print` in this case). As a result, just replace every occurrence of print in the loop above with `*f`:
```
void func ( void (*f)(int) ) {
for ( int ctr = 0 ; ctr < 5 ; ctr++ ) {
(*f)(ctr);
}
}
```
[Source](http://math.hws.edu/bridgeman/courses/331/f05/handouts/c-c++-notes.html) |
9,434 | <p>In my ASP.NET User Control I'm adding some JavaScript to the <code>window.onload</code> event:</p>
<pre><code>if (!Page.ClientScript.IsStartupScriptRegistered(this.GetType(), onloadScriptName))
Page.ClientScript.RegisterStartupScript(this.GetType(), onloadScriptName,
"window.onload = function() {myFunction();};", true);
</code></pre>
<p>My problem is, if there is already something in the <code>onload</code> event, than this overwrites it. How would I go about allowing two user controls to each execute JavaScript in the <code>onload</code> event?</p>
<p><strong>Edit:</strong> Thanks for the info on third party libraries. I'll keep them in mind. </p>
| [
{
"answer_id": 9440,
"author": "Derek Park",
"author_id": 872,
"author_profile": "https://Stackoverflow.com/users/872",
"pm_score": 1,
"selected": false,
"text": "<p>I don't know a lot about ASP.NET, but why not write a custom function for the onload event that in turn calls both functions for you? If you've got two functions, call them both from a third script which you register for the event.</p>\n"
},
{
"answer_id": 9447,
"author": "Chris Farmer",
"author_id": 404,
"author_profile": "https://Stackoverflow.com/users/404",
"pm_score": 2,
"selected": false,
"text": "<p>Try this:</p>\n\n<pre><code>window.attachEvent(\"onload\", myOtherFunctionToCall);\n\nfunction myOtherFunctionToCall() {\n // do something\n}\n</code></pre>\n\n<p>edit: hey, I was just getting ready to log in with Firefox and reformat this myself! Still doesn't seem to format code for me with IE7.</p>\n"
},
{
"answer_id": 9451,
"author": "Derek Park",
"author_id": 872,
"author_profile": "https://Stackoverflow.com/users/872",
"pm_score": 1,
"selected": false,
"text": "<p>Actually, according to <a href=\"http://msdn.microsoft.com/en-us/library/z9h4dk8y.aspx\" rel=\"nofollow noreferrer\">this MSDN page</a>, it looks like you <em>can</em> call this function multiple times to register multiple scripts. You just need to use different keys (the second argument).</p>\n\n<pre><code>Page.ClientScript.RegisterStartupScript(\n this.GetType(), key1, function1, true);\n\nPage.ClientScript.RegisterStartupScript(\n this.GetType(), key2, function2, true);\n</code></pre>\n\n<p>I believe that should work.</p>\n"
},
{
"answer_id": 9470,
"author": "cole",
"author_id": 910,
"author_profile": "https://Stackoverflow.com/users/910",
"pm_score": 2,
"selected": false,
"text": "<p><a href=\"http://mootools.net/\" rel=\"nofollow noreferrer\">Mootools</a> is another great JavaScript framework which is fairly easy to use, and like RedWolves said with <a href=\"http://jquery.com/\" rel=\"nofollow noreferrer\">jQuery</a> you can can just keep chucking as many handlers as you want.</p>\n\n<p>For every *.js file I include I just wrap the code in a function.</p>\n\n<pre><code>window.addEvent('domready', function(){\n alert('Just put all your code here');\n});\n</code></pre>\n\n<p>And there are also <a href=\"http://walkthrough.ifupdown.com/walkthrough-1.2/domready.\" rel=\"nofollow noreferrer\">advantages of using domready instead of onload</a></p>\n"
},
{
"answer_id": 9814,
"author": "Vincent Robert",
"author_id": 268,
"author_profile": "https://Stackoverflow.com/users/268",
"pm_score": 4,
"selected": false,
"text": "<p>There still is an ugly solution (which is far inferior to using a framework or <code>addEventListener</code>/<code>attachEvent</code>) that is to save the current <code>onload</code> event:</p>\n\n<pre><code>function addOnLoad(fn)\n{ \n var old = window.onload;\n window.onload = function()\n {\n old();\n fn();\n };\n}\n\naddOnLoad(function()\n{\n // your code here\n});\naddOnLoad(function()\n{\n // your code here\n});\naddOnLoad(function()\n{\n // your code here\n});\n</code></pre>\n\n<p>Note that frameworks like jQuery will provide a way to execute code when the DOM is ready and not when the page loads. </p>\n\n<p>DOM being ready means that your HTML has loaded but not external components like images or stylesheets, allowing you to be called long before the load event fires.</p>\n"
},
{
"answer_id": 688199,
"author": "user83421",
"author_id": 83421,
"author_profile": "https://Stackoverflow.com/users/83421",
"pm_score": 8,
"selected": true,
"text": "<p>Most of the \"solutions\" suggested are Microsoft-specific, or require bloated libraries. Here's one good way. This works with W3C-compliant browsers and with Microsoft IE.</p>\n\n<pre><code>if (window.addEventListener) // W3C standard\n{\n window.addEventListener('load', myFunction, false); // NB **not** 'onload'\n} \nelse if (window.attachEvent) // Microsoft\n{\n window.attachEvent('onload', myFunction);\n}\n</code></pre>\n"
},
{
"answer_id": 4320764,
"author": "Fábio de Lima Souto",
"author_id": 495410,
"author_profile": "https://Stackoverflow.com/users/495410",
"pm_score": 3,
"selected": false,
"text": "<p>I had a similar problem today so I solved it having an <code>index.js</code> with the following:</p>\n\n<pre><code>window.onloadFuncs = [];\n\nwindow.onload = function()\n{\n for(var i in this.onloadFuncs)\n {\n this.onloadFuncs[i]();\n }\n}\n</code></pre>\n\n<p>and in additional js files that i want to attach the onload event I just have to do this:</p>\n\n<pre><code>window.onloadFuncs.push(function(){\n // code here\n});\n</code></pre>\n\n<p>I normally use jQuery though, but this time I was restricted to pure js wich forced to use my mind for a while!</p>\n"
},
{
"answer_id": 12192966,
"author": "DadViegas",
"author_id": 1354106,
"author_profile": "https://Stackoverflow.com/users/1354106",
"pm_score": 1,
"selected": false,
"text": "<p>You can do this with jquery </p>\n\n<pre><code>$(window).load(function () {\n // jQuery functions to initialize after the page has loaded.\n});\n</code></pre>\n"
}
] | 2008/08/13 | [
"https://Stackoverflow.com/questions/9434",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/233/"
] | In my ASP.NET User Control I'm adding some JavaScript to the `window.onload` event:
```
if (!Page.ClientScript.IsStartupScriptRegistered(this.GetType(), onloadScriptName))
Page.ClientScript.RegisterStartupScript(this.GetType(), onloadScriptName,
"window.onload = function() {myFunction();};", true);
```
My problem is, if there is already something in the `onload` event, than this overwrites it. How would I go about allowing two user controls to each execute JavaScript in the `onload` event?
**Edit:** Thanks for the info on third party libraries. I'll keep them in mind. | Most of the "solutions" suggested are Microsoft-specific, or require bloated libraries. Here's one good way. This works with W3C-compliant browsers and with Microsoft IE.
```
if (window.addEventListener) // W3C standard
{
window.addEventListener('load', myFunction, false); // NB **not** 'onload'
}
else if (window.attachEvent) // Microsoft
{
window.attachEvent('onload', myFunction);
}
``` |
9,486 | <p>I could swear I've seen people typing function headers and then hitting some key combination to auto-create function braces and insert the cursor between them like so:</p>
<pre><code>void foo()_
</code></pre>
<p>to</p>
<pre><code>void foo()
{
_
}
</code></pre>
<p>Is this a built-in feature?</p>
| [
{
"answer_id": 9488,
"author": "Rob Cooper",
"author_id": 832,
"author_profile": "https://Stackoverflow.com/users/832",
"pm_score": 2,
"selected": false,
"text": "<p>It can be achieved by using code snippets, some are already built in (try typing \"svm\" and hitting TAB-TAB)..</p>\n\n<p>There's a wealth of info on the net on creating these:</p>\n\n<p><a href=\"http://www.codinghorror.com/blog/archives/000419.html\" rel=\"nofollow noreferrer\">Jeff did a post himself here</a></p>\n\n<p>Have a google! I use them LOTS! :D</p>\n"
},
{
"answer_id": 9489,
"author": "David McGraw",
"author_id": 568,
"author_profile": "https://Stackoverflow.com/users/568",
"pm_score": 2,
"selected": false,
"text": "<p>Take a look at <a href=\"http://www.wholetomato.com/\" rel=\"nofollow noreferrer\">visual assist</a> as well.</p>\n"
},
{
"answer_id": 9491,
"author": "pc1oad1etter",
"author_id": 525,
"author_profile": "https://Stackoverflow.com/users/525",
"pm_score": 4,
"selected": true,
"text": "<p>Check out <a href=\"http://www.jetbrains.com/resharper/documentation/feature_map.html\" rel=\"nofollow noreferrer\">Resharper</a> - it is a Visual Studio add-on with this feature, among many other development helps.</p>\n\n<p>Also see <a href=\"http://www.knowdotnet.com/articles/csharpcompleter.html\" rel=\"nofollow noreferrer\">C# Completer</a>, another add-on.</p>\n\n<p>If you want to roll your own, check out <a href=\"http://www.developer.com/net/cplus/article.php/3347271\" rel=\"nofollow noreferrer\">this article</a>. Insane that one should have to do that, though.</p>\n"
},
{
"answer_id": 9494,
"author": "Luke",
"author_id": 327,
"author_profile": "https://Stackoverflow.com/users/327",
"pm_score": 3,
"selected": false,
"text": "<p>The tools look nice (especially Resharper but at $200-350 ouch!) but I ended up just recording a macro and assigning it to ctrl+alt+[</p>\n\n<p>Macro came out like this:</p>\n\n<pre><code>Sub FunctionBraces()\n DTE.ActiveDocument.Selection.NewLine\n DTE.ActiveDocument.Selection.Text = \"{}\"\n DTE.ActiveDocument.Selection.CharLeft\n DTE.ActiveDocument.Selection.NewLine(2)\n DTE.ActiveDocument.Selection.LineUp\n DTE.ActiveDocument.Selection.Indent\nEnd Sub\n</code></pre>\n\n<p>Edit: I used the macro recorder to make this and it wasn't too bad</p>\n"
},
{
"answer_id": 12285187,
"author": "PCPGMR",
"author_id": 323650,
"author_profile": "https://Stackoverflow.com/users/323650",
"pm_score": 0,
"selected": false,
"text": "<p>I just created one based on @Luke's above. This one, you want to hit Enter then hit your key combination and it will insert:</p>\n\n<pre><code>if ()\n{\n\n}\nelse\n{\n\n}\n</code></pre>\n\n<p>And it will put your cursor in the parenthesis by the if statement.</p>\n\n<pre><code>Sub IfStatement()\n DTE.ActiveDocument.Selection.Text = \"if ()\"\n DTE.ActiveDocument.Selection.NewLine()\n DTE.ActiveDocument.Selection.Text = \"{\"\n DTE.ActiveDocument.Selection.NewLine(2)\n DTE.ActiveDocument.Selection.Text = \"}\"\n DTE.ActiveDocument.Selection.NewLine()\n DTE.ActiveDocument.Selection.Text = \"else\"\n DTE.ActiveDocument.Selection.NewLine(2)\n DTE.ActiveDocument.Selection.Text = \"{\"\n DTE.ActiveDocument.Selection.NewLine(2)\n DTE.ActiveDocument.Selection.Text = \"}\"\n DTE.ActiveDocument.Selection.LineUp(False, 7)\n DTE.ActiveDocument.Selection.EndOfLine()\n DTE.ActiveDocument.Selection.CharLeft(3)\nEnd Sub\n</code></pre>\n"
}
] | 2008/08/13 | [
"https://Stackoverflow.com/questions/9486",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/327/"
] | I could swear I've seen people typing function headers and then hitting some key combination to auto-create function braces and insert the cursor between them like so:
```
void foo()_
```
to
```
void foo()
{
_
}
```
Is this a built-in feature? | Check out [Resharper](http://www.jetbrains.com/resharper/documentation/feature_map.html) - it is a Visual Studio add-on with this feature, among many other development helps.
Also see [C# Completer](http://www.knowdotnet.com/articles/csharpcompleter.html), another add-on.
If you want to roll your own, check out [this article](http://www.developer.com/net/cplus/article.php/3347271). Insane that one should have to do that, though. |
9,614 | <p>Suppose we have a table A:</p>
<pre><code>itemid mark
1 5
2 3
</code></pre>
<p>and table B:</p>
<pre><code>itemid mark
1 3
3 5
</code></pre>
<p>I want to join A*B on A.itemid=B.itemid both right and left ways. i.e. result:</p>
<pre><code>itemid A.mark B.mark
1 5 3
2 3 NULL
3 NULL 5
</code></pre>
<p>Is there a way to do it in one query in MySQL?</p>
| [
{
"answer_id": 9625,
"author": "roo",
"author_id": 716,
"author_profile": "https://Stackoverflow.com/users/716",
"pm_score": 2,
"selected": false,
"text": "<p>Could do with some work but here is some sql</p>\n\n<pre><code>select distinct T.itemid, A.mark as \"A.mark\", B.mark as \"B.mark\"\n from (select * from A union select * from B) T \n left join A on T.itemid = A.itemid \n left join B on T.itemid = B.itemid;\n</code></pre>\n\n<p>This relies on the left join, which returns all the rows in the original table (in this case this is the subselect table T). If there are no matches in the joined table, then it will set the column to NULL.</p>\n"
},
{
"answer_id": 9626,
"author": "Matt Hamilton",
"author_id": 615,
"author_profile": "https://Stackoverflow.com/users/615",
"pm_score": -1,
"selected": false,
"text": "<p>This works for me on SQL Server:</p>\n\n<pre><code>select isnull(a.id, b.id), a.mark, b.mark\nfrom a \nfull outer join b on b.id = a.id\n</code></pre>\n"
},
{
"answer_id": 9635,
"author": "Nickolay",
"author_id": 1026,
"author_profile": "https://Stackoverflow.com/users/1026",
"pm_score": 4,
"selected": true,
"text": "<p>It's called a full outer join and it's not supported natively in MySQL, judging from its <a href=\"http://dev.mysql.com/doc/refman/4.1/en/join.html\" rel=\"noreferrer\">docs</a>. You can work around this limitation using UNION as described in the comments to the page I linked to.</p>\n\n<p>[edit] Since others posted snippets, here you go. You can see explanation on the linked page.</p>\n\n<pre><code>SELECT *\nFROM A LEFT JOIN B ON A.id = B.id\nUNION ALL\nSELECT *\nFROM A RIGHT JOIN B ON A.id = B.id\nWHERE A.id IS NULL\n</code></pre>\n"
}
] | 2008/08/13 | [
"https://Stackoverflow.com/questions/9614",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/844/"
] | Suppose we have a table A:
```
itemid mark
1 5
2 3
```
and table B:
```
itemid mark
1 3
3 5
```
I want to join A\*B on A.itemid=B.itemid both right and left ways. i.e. result:
```
itemid A.mark B.mark
1 5 3
2 3 NULL
3 NULL 5
```
Is there a way to do it in one query in MySQL? | It's called a full outer join and it's not supported natively in MySQL, judging from its [docs](http://dev.mysql.com/doc/refman/4.1/en/join.html). You can work around this limitation using UNION as described in the comments to the page I linked to.
[edit] Since others posted snippets, here you go. You can see explanation on the linked page.
```
SELECT *
FROM A LEFT JOIN B ON A.id = B.id
UNION ALL
SELECT *
FROM A RIGHT JOIN B ON A.id = B.id
WHERE A.id IS NULL
``` |
9,632 | <p>Apparantly when users right-click in our WPF application, and they use the Windows Classic theme, the default ContextMenu of the TextBox (which contains Copy, Cut and Paste) has a black background.</p>
<p>I know this works well:</p>
<pre><code><Page xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml">
<TextBox ContextMenu="{x:Null}"/>
</Page>
</code></pre>
<p>But this doesn't work:</p>
<pre><code><Page xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml">
<Page.Resources>
<Style x:Key="{x:Type TextBox}" TargetType="{x:Type TextBox}">
<Setter Property="ContextMenu" Value="{x:Null}"/>
</Style>
</Page.Resources>
<TextBox/>
</Page>
</code></pre>
<p>Does anyone know how to style or disable the default ContextMenu for all TextBoxes in WPF?</p>
| [
{
"answer_id": 9864,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 1,
"selected": false,
"text": "<p>Try removing the x:Key attribute from the Style resource, leaving TargetType. I know, you're supposed to have that x:Key for a resource, but if you have it along with your TargetType the Key prevails. </p>\n\n<p>Here's a sample style that I use in a project to skin all tooltips in one of my apps (this is in App.Resources--notice, no Key) </p>\n\n<pre><code> <Style\n TargetType=\"{x:Type ToolTip}\">\n <Setter\n Property=\"Template\">\n <Setter.Value>\n <ControlTemplate\n TargetType=\"{x:Type ToolTip}\">\n <Grid\n Width=\"{TemplateBinding Width}\"\n Height=\"{TemplateBinding Height}\">\n <Rectangle\n RadiusX=\"9\"\n RadiusY=\"9\"\n Stroke=\"LightGray\"\n StrokeThickness=\"2\">\n <Rectangle.Fill>\n <RadialGradientBrush>\n <GradientStop />\n <GradientStop\n Color=\"FloralWhite\"\n Offset=\"0\" />\n <GradientStop\n Color=\"Cornsilk\"\n Offset=\"2\" />\n </RadialGradientBrush>\n </Rectangle.Fill>\n </Rectangle>\n <ContentPresenter\n Margin=\"6 4 6 4\" />\n </Grid>\n </ControlTemplate>\n </Setter.Value>\n </Setter>\n </Style>\n</code></pre>\n"
},
{
"answer_id": 9878,
"author": "Arcturus",
"author_id": 900,
"author_profile": "https://Stackoverflow.com/users/900",
"pm_score": 2,
"selected": false,
"text": "<p>Doesn't matter, if you do not provide a key, it will use the <code>TargetType</code> as key just the same way my example uses :)</p>\n\n<p>Taken from MSDN on Style:</p>\n\n<blockquote>\n <p>Setting the <code>TargetType</code> property to the <code>TextBlock</code> type without\n setting an <code>x:Key</code> implicitly sets the <code>x:Key</code> to <code>{x:Type TextBlock}</code>. This also means that if you > > give the above Style an <code>x:Key</code> value of anything other than <code>{x:Type TextBlock}</code>, the Style\n would not be applied to all TextBlock elements automatically. Instead,\n you need to apply the style to the <code>TextBlock</code> elements explicitly.</p>\n</blockquote>\n\n<p><a href=\"http://msdn.microsoft.com/en-us/library/system.windows.style.targettype.aspx\" rel=\"nofollow noreferrer\">http://msdn.microsoft.com/en-us/library/system.windows.style.targettype.aspx</a></p>\n"
},
{
"answer_id": 9897,
"author": "Brad Leach",
"author_id": 708,
"author_profile": "https://Stackoverflow.com/users/708",
"pm_score": 5,
"selected": false,
"text": "<p>To style ContextMenu's for all TextBoxes, I would do something like the following:</p>\n\n<p>First, in the resources section, add a ContextMenu which you plan to use as your standard ContextMenu in a textbox.<br /> e.g.</p>\n\n<pre><code><ContextMenu x:Key=\"TextBoxContextMenu\" Background=\"White\">\n <MenuItem Command=\"ApplicationCommands.Copy\" />\n <MenuItem Command=\"ApplicationCommands.Cut\" />\n <MenuItem Command=\"ApplicationCommands.Paste\" />\n</ContextMenu>\n</code></pre>\n\n<p>Secondly, create a style for your TextBoxes, which uses the context menu resource:</p>\n\n<pre><code><Style TargetType=\"{x:Type TextBox}\">\n <Setter Property=\"ContextMenu\" Value=\"{StaticResource TextBoxContextMenu}\" />\n</Style>\n</code></pre>\n\n<p>Finally, use your text box as normal:</p>\n\n<pre><code><TextBox />\n</code></pre>\n\n<p>If instead you want to apply this context menu to only some of your textboxes, do not create the style above, and add the following to your TextBox markup:</p>\n\n<pre><code><TextBox ContextMenu=\"{StaticResource TextBoxContextMenu}\" />\n</code></pre>\n\n<p>Hope this helps!</p>\n"
},
{
"answer_id": 2523372,
"author": "Arcturus",
"author_id": 900,
"author_profile": "https://Stackoverflow.com/users/900",
"pm_score": 4,
"selected": true,
"text": "<p>Due to a late bug report we discovered that we cannot use the ApplicationComands Cut Paste and Copy directly in a partial trusted application. Therefor, using these commands in any Commmand of your controls will do absolutely nothing when executed.</p>\n\n<p>So in essence Brads answer was almost there, it sure looked the right way i.e. no black background, but did not fix the problem.</p>\n\n<p>We decided to \"remove\" the menu based on Brads answer, like so:</p>\n\n<pre><code><ContextMenu x:Key=\"TextBoxContextMenu\" Width=\"0\" Height=\"0\" />\n</code></pre>\n\n<p>And use this empty context menu like so:</p>\n\n<pre><code><Style TargetType=\"{x:Type TextBox}\">\n <Setter Property=\"ContextMenu\" Value=\"{StaticResource TextBoxContextMenu}\" />\n</Style>\n</code></pre>\n"
},
{
"answer_id": 3484929,
"author": "Robin Davies",
"author_id": 415713,
"author_profile": "https://Stackoverflow.com/users/415713",
"pm_score": 5,
"selected": false,
"text": "<p>Bizarre. <code>ContextMenu=\"{x:Null}\"</code> doesn't do the trick. </p>\n\n<p>This does, however: </p>\n\n<pre><code><TextBox.ContextMenu>\n <ContextMenu Visibility=\"Collapsed\">\n </ContextMenu>\n</TextBox.ContextMenu>\n</code></pre>\n"
},
{
"answer_id": 53862931,
"author": "MrBi",
"author_id": 10765214,
"author_profile": "https://Stackoverflow.com/users/10765214",
"pm_score": 2,
"selected": false,
"text": "<p>This is way is what I always use:</p>\n<pre><code> <TextBox x:Name="MyTextbox">\n <TextBox.ContextMenu>\n <ContextMenu Visibility="Hidden"/>\n </TextBox.ContextMenu>\n </TextBox>\n</code></pre>\n<p>And also can use:</p>\n<pre class=\"lang-cs prettyprint-override\"><code> MyTextbox.ContextMenu.Visibility = Visibility.Hidden;\n MyTextbox.ContextMenu.Visibility = Visibility.Visble;\n</code></pre>\n"
}
] | 2008/08/13 | [
"https://Stackoverflow.com/questions/9632",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/900/"
] | Apparantly when users right-click in our WPF application, and they use the Windows Classic theme, the default ContextMenu of the TextBox (which contains Copy, Cut and Paste) has a black background.
I know this works well:
```
<Page xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml">
<TextBox ContextMenu="{x:Null}"/>
</Page>
```
But this doesn't work:
```
<Page xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml">
<Page.Resources>
<Style x:Key="{x:Type TextBox}" TargetType="{x:Type TextBox}">
<Setter Property="ContextMenu" Value="{x:Null}"/>
</Style>
</Page.Resources>
<TextBox/>
</Page>
```
Does anyone know how to style or disable the default ContextMenu for all TextBoxes in WPF? | Due to a late bug report we discovered that we cannot use the ApplicationComands Cut Paste and Copy directly in a partial trusted application. Therefor, using these commands in any Commmand of your controls will do absolutely nothing when executed.
So in essence Brads answer was almost there, it sure looked the right way i.e. no black background, but did not fix the problem.
We decided to "remove" the menu based on Brads answer, like so:
```
<ContextMenu x:Key="TextBoxContextMenu" Width="0" Height="0" />
```
And use this empty context menu like so:
```
<Style TargetType="{x:Type TextBox}">
<Setter Property="ContextMenu" Value="{StaticResource TextBoxContextMenu}" />
</Style>
``` |
9,666 | <p>I've been raised to believe that if multiple threads can access a variable, then all reads from and writes to that variable must be protected by synchronization code, such as a "lock" statement, because the processor might switch to another thread halfway through a write.</p>
<p>However, I was looking through System.Web.Security.Membership using Reflector and found code like this:</p>
<pre><code>public static class Membership
{
private static bool s_Initialized = false;
private static object s_lock = new object();
private static MembershipProvider s_Provider;
public static MembershipProvider Provider
{
get
{
Initialize();
return s_Provider;
}
}
private static void Initialize()
{
if (s_Initialized)
return;
lock(s_lock)
{
if (s_Initialized)
return;
// Perform initialization...
s_Initialized = true;
}
}
}
</code></pre>
<p>Why is the s_Initialized field read outside of the lock? Couldn't another thread be trying to write to it at the same time? <strong>Are reads and writes of variables atomic?</strong> </p>
| [
{
"answer_id": 9682,
"author": "Keith",
"author_id": 905,
"author_profile": "https://Stackoverflow.com/users/905",
"pm_score": 0,
"selected": false,
"text": "<p>I thought they were - I'm not sure of the point of the lock in your example unless you're also doing something to s_Provider at the same time - then the lock would ensure that these calls happened together.</p>\n\n<p>Does that <code>//Perform initialization</code> comment cover creating s_Provider? For instance</p>\n\n<pre><code>private static void Initialize()\n{\n if (s_Initialized)\n return;\n\n lock(s_lock)\n {\n s_Provider = new MembershipProvider ( ... )\n s_Initialized = true;\n }\n}\n</code></pre>\n\n<p>Otherwise that static property-get's just going to return null anyway.</p>\n"
},
{
"answer_id": 9689,
"author": "John Richardson",
"author_id": 887,
"author_profile": "https://Stackoverflow.com/users/887",
"pm_score": 2,
"selected": false,
"text": "<p>The Initialize function is faulty. It should look more like this:</p>\n\n<pre><code>private static void Initialize()\n{\n if(s_initialized)\n return;\n\n lock(s_lock)\n {\n if(s_Initialized)\n return;\n s_Initialized = true;\n }\n}\n</code></pre>\n\n<p>Without the second check inside the lock it's possible the initialisation code will be executed twice. So the first check is for performance to save you taking a lock unnecessarily, and the second check is for the case where a thread is executing the initialisation code but hasn't yet set the <code>s_Initialized</code> flag and so a second thread would pass the first check and be waiting at the lock.</p>\n"
},
{
"answer_id": 9699,
"author": "olliej",
"author_id": 784,
"author_profile": "https://Stackoverflow.com/users/784",
"pm_score": 0,
"selected": false,
"text": "<p>What you're asking is whether accessing a field in a method multiple times atomic -- to which the answer is no.</p>\n\n<p>In the example above, the initialise routine is faulty as it may result in multiple initialization. You would need to check the <code>s_Initialized</code> flag inside the lock as well as outside, to prevent a race condition in which multiple threads read the <code>s_Initialized</code> flag before any of them actually does the initialisation code. E.g.,</p>\n\n<pre><code>private static void Initialize()\n{\n if (s_Initialized)\n return;\n\n lock(s_lock)\n {\n if (s_Initialized)\n return;\n s_Provider = new MembershipProvider ( ... )\n s_Initialized = true;\n }\n}\n</code></pre>\n"
},
{
"answer_id": 9701,
"author": "Peteter",
"author_id": 1192,
"author_profile": "https://Stackoverflow.com/users/1192",
"pm_score": 0,
"selected": false,
"text": "<p>Perhaps <a href=\"http://msdn.microsoft.com/en-us/library/system.threading.interlocked(VS.85).aspx\" rel=\"nofollow noreferrer\">Interlocked</a> gives a clue. And otherwise <a href=\"http://msdn.microsoft.com/sv-se/magazine/cc188793(en-us).aspx\" rel=\"nofollow noreferrer\">this one</a> i pretty good.</p>\n\n<p>I would have guessed that their not atomic.</p>\n"
},
{
"answer_id": 9711,
"author": "John Richardson",
"author_id": 887,
"author_profile": "https://Stackoverflow.com/users/887",
"pm_score": 1,
"selected": false,
"text": "<p>I think you're asking if <code>s_Initialized</code> could be in an unstable state when read outside the lock. The short answer is no. A simple assignment/read will boil down to a single assembly instruction which is atomic on every processor I can think of. </p>\n\n<p>I'm not sure what the case is for assignment to 64 bit variables, it depends on the processor, I would assume that it is not atomic but it probably is on modern 32 bit processors and certainly on all 64 bit processors. Assignment of complex value types will not be atomic.</p>\n"
},
{
"answer_id": 9712,
"author": "OJ.",
"author_id": 611,
"author_profile": "https://Stackoverflow.com/users/611",
"pm_score": 1,
"selected": false,
"text": "<p>Reads and writes of variables are not atomic. You need to use Synchronisation APIs to emulate atomic reads/writes.</p>\n\n<p>For an awesome reference on this and many more issues to do with concurrency, make sure you grab a copy of Joe Duffy's <a href=\"https://rads.stackoverflow.com/amzn/click/com/032143482X\" rel=\"nofollow noreferrer\" rel=\"nofollow noreferrer\">latest spectacle</a>. It's a ripper!</p>\n"
},
{
"answer_id": 9715,
"author": "Leon Bambrick",
"author_id": 49,
"author_profile": "https://Stackoverflow.com/users/49",
"pm_score": 1,
"selected": false,
"text": "<p>\"Is accessing a variable in C# an atomic operation?\"</p>\n\n<p>Nope. And it's not a C# thing, nor is it even a .net thing, it's a processor thing.</p>\n\n<p>OJ is spot on that Joe Duffy is the guy to go to for this kind of info. ANd \"interlocked\" is a great search term to use if you're wanting to know more.</p>\n\n<p>\"Torn reads\" can occur on any value whose fields add up to more than the size of a pointer.</p>\n"
},
{
"answer_id": 9721,
"author": "JoshL",
"author_id": 630,
"author_profile": "https://Stackoverflow.com/users/630",
"pm_score": -1,
"selected": false,
"text": "<p>Ack, nevermind... as pointed out, this is indeed incorrect. It doesn't prevent a second thread from entering the \"initialize\" code section. Bah.</p>\n\n<blockquote>\n <p>You could also decorate s_Initialized with the volatile keyword and forego the use of lock entirely.</p>\n</blockquote>\n"
},
{
"answer_id": 9788,
"author": "John Richardson",
"author_id": 887,
"author_profile": "https://Stackoverflow.com/users/887",
"pm_score": 6,
"selected": true,
"text": "<p>For the definitive answer go to the spec. :)</p>\n\n<p>Partition I, Section 12.6.6 of the CLI spec states: \"A conforming CLI shall guarantee that read and write access to properly aligned memory locations no larger than the native word size is atomic when all the write accesses to a location are the same size.\"</p>\n\n<p>So that confirms that s_Initialized will never be unstable, and that read and writes to primitve types smaller than 32 bits are atomic.</p>\n\n<p>In particular, <code>double</code> and <code>long</code> (<code>Int64</code> and <code>UInt64</code>) are <strong>not</strong> guaranteed to be atomic on a 32-bit platform. You can use the methods on the <code>Interlocked</code> class to protect these.</p>\n\n<p>Additionally, while reads and writes are atomic, there is a race condition with addition, subtraction, and incrementing and decrementing primitive types, since they must be read, operated on, and rewritten. The interlocked class allows you to protect these using the <code>CompareExchange</code> and <code>Increment</code> methods.</p>\n\n<p>Interlocking creates a memory barrier to prevent the processor from reordering reads and writes. The lock creates the only required barrier in this example.</p>\n"
},
{
"answer_id": 9792,
"author": "John Richardson",
"author_id": 887,
"author_profile": "https://Stackoverflow.com/users/887",
"pm_score": 1,
"selected": false,
"text": "<blockquote>\n <p>You could also decorate s_Initialized with the volatile keyword and forego the use of lock entirely.</p>\n</blockquote>\n\n<p>That is not correct. You will still encounter the problem of a second thread passing the check before the first thread has had a chance to to set the flag which will result in multiple executions of the initialisation code.</p>\n"
},
{
"answer_id": 10103,
"author": "Rory MacLeod",
"author_id": 1016,
"author_profile": "https://Stackoverflow.com/users/1016",
"pm_score": 3,
"selected": false,
"text": "<p>The correct answer seems to be, "Yes, mostly."</p>\n<ol>\n<li>John's answer referencing the CLI spec indicates that accesses to variables not larger than 32 bits on a 32-bit processor are atomic.</li>\n<li>Further confirmation from the C# spec, section 5.5, <a href=\"https://learn.microsoft.com/en-us/dotnet/csharp/language-reference/language-specification/variables#atomicity-of-variable-references\" rel=\"nofollow noreferrer\">Atomicity of variable references</a>:</li>\n</ol>\n<blockquote>\n<p>Reads and writes of the following data types are atomic: bool, char,\nbyte, sbyte, short, ushort, uint, int, float, and reference types. In\naddition, reads and writes of enum types with an underlying type in\nthe previous list are also atomic. Reads and writes of other types,\nincluding long, ulong, double, and decimal, as well as user-defined\ntypes, are not guaranteed to be atomic.</p>\n</blockquote>\n<ol start=\"3\">\n<li>The code in my example was paraphrased from the Membership class, as written by the ASP.NET team themselves, so it was always safe to assume that the way it accesses the s_Initialized field is correct. Now we know why.</li>\n</ol>\n<p>Edit: As Thomas Danecker points out, even though the access of the field is atomic, s_Initialized should really be marked <em>volatile</em> to make sure that the locking isn't broken by the processor reordering the reads and writes.</p>\n"
},
{
"answer_id": 12206,
"author": "Leon Bambrick",
"author_id": 49,
"author_profile": "https://Stackoverflow.com/users/49",
"pm_score": 4,
"selected": false,
"text": "<p>Hang about -- the question that is in the title is definitely not the real question that Rory is asking.</p>\n\n<p>The titular question has the simple answer of \"No\" -- but this is no help at all, when you see the real question -- which i don't think anyone has given a simple answer to.</p>\n\n<p>The real question Rory asks is presented much later and is more pertinent to the example he gives.</p>\n\n<blockquote>\n <p>Why is the s_Initialized field read\n outside of the lock?</p>\n</blockquote>\n\n<p>The answer to this is also simple, though completely unrelated to the atomicity of variable access.</p>\n\n<p>The s_Initialized field is read outside of the lock because <strong>locks are expensive</strong>.</p>\n\n<p>Since the s_Initialized field is essentially \"write once\" it will never return a false positive.</p>\n\n<p>It's economical to read it outside the lock.</p>\n\n<p>This is a <em>low cost</em> activity with a <em>high</em> chance of having a benefit.</p>\n\n<p>That's why it's read outside of the lock -- to avoid paying the cost of using a lock unless it's indicated.</p>\n\n<p>If locks were cheap the code would be simpler, and omit that first check.</p>\n\n<p><em>(edit: nice response from rory follows. Yeh, boolean reads are very much atomic. If someone built a processor with non-atomic boolean reads, they'd be featured on the DailyWTF.)</em></p>\n"
},
{
"answer_id": 73827,
"author": "Thomas Danecker",
"author_id": 9632,
"author_profile": "https://Stackoverflow.com/users/9632",
"pm_score": 5,
"selected": false,
"text": "<p>This is a (bad) form of the double check locking pattern which is <strong>not</strong> thread safe in C#!</p>\n\n<p>There is one big problem in this code:</p>\n\n<p>s_Initialized is not volatile. That means that writes in the initialization code can move after s_Initialized is set to true and other threads can see uninitialized code even if s_Initialized is true for them. This doesn't apply to Microsoft's implementation of the Framework because every write is a volatile write.</p>\n\n<p>But also in Microsoft's implementation, reads of the uninitialized data can be reordered (i.e. prefetched by the cpu), so if s_Initialized is true, reading the data that should be initialized can result in reading old, uninitialized data because of cache-hits (ie. the reads are reordered).</p>\n\n<p>For example: </p>\n\n<pre><code>Thread 1 reads s_Provider (which is null) \nThread 2 initializes the data \nThread 2 sets s\\_Initialized to true \nThread 1 reads s\\_Initialized (which is true now) \nThread 1 uses the previously read Provider and gets a NullReferenceException\n</code></pre>\n\n<p>Moving the read of s_Provider before the read of s_Initialized is perfectly legal because there is no volatile read anywhere.</p>\n\n<p>If s_Initialized would be volatile, the read of s_Provider would not be allowed to move before the read of s_Initialized and also the initialization of the Provider is not allowed to move after s_Initialized is set to true and everything is ok now.</p>\n\n<p>Joe Duffy also wrote an Article about this problem: <a href=\"http://joeduffyblog.com/2006/01/26/broken-variants-on-doublechecked-locking/\" rel=\"nofollow noreferrer\">Broken variants on double-checked locking</a></p>\n"
},
{
"answer_id": 12206783,
"author": "doug65536",
"author_id": 1127972,
"author_profile": "https://Stackoverflow.com/users/1127972",
"pm_score": 0,
"selected": false,
"text": "<p>To make your code always work on weakly ordered architectures, you must put a MemoryBarrier before you write s_Initialized.</p>\n\n<pre><code>s_Provider = new MemershipProvider;\n\n// MUST PUT BARRIER HERE to make sure the memory writes from the assignment\n// and the constructor have been wriitten to memory\n// BEFORE the write to s_Initialized!\nThread.MemoryBarrier();\n\n// Now that we've guaranteed that the writes above\n// will be globally first, set the flag\ns_Initialized = true;\n</code></pre>\n\n<p>The memory writes that happen in the MembershipProvider constructor and the write to s_Provider are not guaranteed to happen before you write to s_Initialized on a weakly ordered processor.</p>\n\n<p>A lot of thought in this thread is about whether something is atomic or not. That is not the issue. The issue is <strong>the order that your thread's writes are visible to other threads</strong>. On weakly ordered architectures, writes to memory do not occur in order and THAT is the real issue, not whether a variable fits within the data bus.</p>\n\n<p><strong>EDIT:</strong> Actually, I'm mixing platforms in my statements. In C# the CLR spec requires that writes are globally visible, in-order (by using expensive store instructions for every store if necessary). Therefore, you don't need to actually have that memory barrier there. However, if it were C or C++ where no such guarantee of global visibility order exists, and your target platform may have weakly ordered memory, and it is multithreaded, then you would need to ensure that the constructors writes are globally visible before you update s_Initialized, which is tested outside the lock.</p>\n"
},
{
"answer_id": 15125936,
"author": "James Anderson",
"author_id": 38207,
"author_profile": "https://Stackoverflow.com/users/38207",
"pm_score": 1,
"selected": false,
"text": "<p>An <code>If (itisso) {</code> check on a boolean is atomic, but even if it was not\nthere is no need to lock the first check.</p>\n\n<p>If any thread has completed the Initialization then it will be true. It does not matter if several threads are checking at once. They will all get the same answer, and, there will be no conflict.</p>\n\n<p>The second check inside the lock is necessary because another thread may have grabbed the lock first and completed the initialization process already.</p>\n"
}
] | 2008/08/13 | [
"https://Stackoverflow.com/questions/9666",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1016/"
] | I've been raised to believe that if multiple threads can access a variable, then all reads from and writes to that variable must be protected by synchronization code, such as a "lock" statement, because the processor might switch to another thread halfway through a write.
However, I was looking through System.Web.Security.Membership using Reflector and found code like this:
```
public static class Membership
{
private static bool s_Initialized = false;
private static object s_lock = new object();
private static MembershipProvider s_Provider;
public static MembershipProvider Provider
{
get
{
Initialize();
return s_Provider;
}
}
private static void Initialize()
{
if (s_Initialized)
return;
lock(s_lock)
{
if (s_Initialized)
return;
// Perform initialization...
s_Initialized = true;
}
}
}
```
Why is the s\_Initialized field read outside of the lock? Couldn't another thread be trying to write to it at the same time? **Are reads and writes of variables atomic?** | For the definitive answer go to the spec. :)
Partition I, Section 12.6.6 of the CLI spec states: "A conforming CLI shall guarantee that read and write access to properly aligned memory locations no larger than the native word size is atomic when all the write accesses to a location are the same size."
So that confirms that s\_Initialized will never be unstable, and that read and writes to primitve types smaller than 32 bits are atomic.
In particular, `double` and `long` (`Int64` and `UInt64`) are **not** guaranteed to be atomic on a 32-bit platform. You can use the methods on the `Interlocked` class to protect these.
Additionally, while reads and writes are atomic, there is a race condition with addition, subtraction, and incrementing and decrementing primitive types, since they must be read, operated on, and rewritten. The interlocked class allows you to protect these using the `CompareExchange` and `Increment` methods.
Interlocking creates a memory barrier to prevent the processor from reordering reads and writes. The lock creates the only required barrier in this example. |
9,667 | <p>Given a handle of type <code>HWND</code> is it possible to confirm that the handle represents a real window?</p>
| [
{
"answer_id": 9670,
"author": "Serge",
"author_id": 1007,
"author_profile": "https://Stackoverflow.com/users/1007",
"pm_score": 5,
"selected": true,
"text": "<p>There is a function <code>IsWindow</code> which does exactly what you asked for.</p>\n\n<pre><code>BOOL isRealHandle = IsWindow(unknwodnHandle);\n</code></pre>\n\n<p>Look at <a href=\"http://msdn.microsoft.com/en-us/library/ms633528(VS.85).aspx\" rel=\"nofollow noreferrer\">this link</a> for more information.</p>\n"
},
{
"answer_id": 9671,
"author": "graham.reeds",
"author_id": 342,
"author_profile": "https://Stackoverflow.com/users/342",
"pm_score": 2,
"selected": false,
"text": "<p>Generally no. By the time you've got confirmation that a Window is valid another process/thread my come along and remove it for you.</p>\n"
}
] | 2008/08/13 | [
"https://Stackoverflow.com/questions/9667",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/887/"
] | Given a handle of type `HWND` is it possible to confirm that the handle represents a real window? | There is a function `IsWindow` which does exactly what you asked for.
```
BOOL isRealHandle = IsWindow(unknwodnHandle);
```
Look at [this link](http://msdn.microsoft.com/en-us/library/ms633528(VS.85).aspx) for more information. |
9,673 | <p>I have been working with a <code>string[]</code> array in C# that gets returned from a function call. I could possibly cast to a <code>Generic</code> collection, but I was wondering if there was a better way to do it, possibly by using a temp array.</p>
<p><strong>What is the best way to remove duplicates from a C# array?</strong></p>
| [
{
"answer_id": 9677,
"author": "Matthew Schinckel",
"author_id": 188,
"author_profile": "https://Stackoverflow.com/users/188",
"pm_score": 4,
"selected": false,
"text": "<p>If you needed to sort it, then you could implement a sort that also removes duplicates.</p>\n\n<p>Kills two birds with one stone, then.</p>\n"
},
{
"answer_id": 9685,
"author": "Jeff Atwood",
"author_id": 1,
"author_profile": "https://Stackoverflow.com/users/1",
"pm_score": 10,
"selected": true,
"text": "<p>You could possibly use a LINQ query to do this:</p>\n\n<pre><code>int[] s = { 1, 2, 3, 3, 4};\nint[] q = s.Distinct().ToArray();\n</code></pre>\n"
},
{
"answer_id": 9735,
"author": "Lasse V. Karlsen",
"author_id": 267,
"author_profile": "https://Stackoverflow.com/users/267",
"pm_score": 3,
"selected": false,
"text": "<p>Add all the strings to a dictionary and get the Keys property afterwards. This will produce each unique string, but not necessarily in the same order your original input had them in.</p>\n\n<p>If you require the end result to have the same order as the original input, when you consider the first occurance of each string, use the following algorithm instead:</p>\n\n<ol>\n<li>Have a list (final output) and a dictionary (to check for duplicates)</li>\n<li>For each string in the input, check if it exists in the dictionary already</li>\n<li>If not, add it both to the dictionary and to the list</li>\n</ol>\n\n<p>At the end, the list contains the first occurance of each unique string.</p>\n\n<p>Make sure you consider things like culture and such when constructing your dictionary, to make sure you handle duplicates with accented letters correctly.</p>\n"
},
{
"answer_id": 9755,
"author": "GateKiller",
"author_id": 383,
"author_profile": "https://Stackoverflow.com/users/383",
"pm_score": 4,
"selected": false,
"text": "<p>The following tested and working code will remove duplicates from an array. You must include the System.Collections namespace.</p>\n\n<pre><code>string[] sArray = {\"a\", \"b\", \"b\", \"c\", \"c\", \"d\", \"e\", \"f\", \"f\"};\nvar sList = new ArrayList();\n\nfor (int i = 0; i < sArray.Length; i++) {\n if (sList.Contains(sArray[i]) == false) {\n sList.Add(sArray[i]);\n }\n}\n\nvar sNew = sList.ToArray();\n\nfor (int i = 0; i < sNew.Length; i++) {\n Console.Write(sNew[i]);\n}\n</code></pre>\n\n<p>You could wrap this up into a function if you wanted to.</p>\n"
},
{
"answer_id": 9763,
"author": "rjzii",
"author_id": 1185,
"author_profile": "https://Stackoverflow.com/users/1185",
"pm_score": 3,
"selected": false,
"text": "<p>This might depend on how much you want to engineer the solution - if the array is never going to be that big and you don't care about sorting the list you might want to try something similar to the following:</p>\n\n<pre><code> public string[] RemoveDuplicates(string[] myList) {\n System.Collections.ArrayList newList = new System.Collections.ArrayList();\n\n foreach (string str in myList)\n if (!newList.Contains(str))\n newList.Add(str);\n return (string[])newList.ToArray(typeof(string));\n }\n</code></pre>\n"
},
{
"answer_id": 9768,
"author": "ZombieSheep",
"author_id": 377,
"author_profile": "https://Stackoverflow.com/users/377",
"pm_score": 2,
"selected": false,
"text": "<p>NOTE : NOT tested!</p>\n\n<pre><code>string[] test(string[] myStringArray)\n{\n List<String> myStringList = new List<string>();\n foreach (string s in myStringArray)\n {\n if (!myStringList.Contains(s))\n {\n myStringList.Add(s);\n }\n }\n return myStringList.ToString();\n}\n</code></pre>\n\n<p>Might do what you need...</p>\n\n<p><strong>EDIT</strong> Argh!!! beaten to it by rob by under a minute!</p>\n"
},
{
"answer_id": 9833,
"author": "Arcturus",
"author_id": 900,
"author_profile": "https://Stackoverflow.com/users/900",
"pm_score": 6,
"selected": false,
"text": "<p>Here is the <a href=\"http://msdn.microsoft.com/en-us/library/bb359438.aspx\" rel=\"noreferrer\">HashSet<string></a> approach:</p>\n\n<pre><code>public static string[] RemoveDuplicates(string[] s)\n{\n HashSet<string> set = new HashSet<string>(s);\n string[] result = new string[set.Count];\n set.CopyTo(result);\n return result;\n}\n</code></pre>\n\n<p>Unfortunately this solution also requires .NET framework 3.5 or later as HashSet was not added until that version. You could also use <a href=\"http://msdn.microsoft.com/en-us/library/system.linq.enumerable.distinct.aspx\" rel=\"noreferrer\">array.Distinct()</a>, which is a feature of LINQ.</p>\n"
},
{
"answer_id": 9873,
"author": "Will Dean",
"author_id": 987,
"author_profile": "https://Stackoverflow.com/users/987",
"pm_score": 3,
"selected": false,
"text": "<blockquote>\n<pre><code>List<String> myStringList = new List<string>();\nforeach (string s in myStringArray)\n{\n if (!myStringList.Contains(s))\n {\n myStringList.Add(s);\n }\n}\n</code></pre>\n</blockquote>\n\n<p>This is <strong>O(n^2)</strong>, which won't matter for a short list which is going to be stuffed into a combo, but could be rapidly be a problem on a big collection.</p>\n"
},
{
"answer_id": 1856035,
"author": "Sesh",
"author_id": 38212,
"author_profile": "https://Stackoverflow.com/users/38212",
"pm_score": 3,
"selected": false,
"text": "<p>Here is a <strong>O(n*n)</strong> approach that uses <strong>O(1)</strong> space. </p>\n\n<pre><code>void removeDuplicates(char* strIn)\n{\n int numDups = 0, prevIndex = 0;\n if(NULL != strIn && *strIn != '\\0')\n {\n int len = strlen(strIn);\n for(int i = 0; i < len; i++)\n {\n bool foundDup = false;\n for(int j = 0; j < i; j++)\n {\n if(strIn[j] == strIn[i])\n {\n foundDup = true;\n numDups++;\n break;\n }\n }\n\n if(foundDup == false)\n {\n strIn[prevIndex] = strIn[i];\n prevIndex++;\n }\n }\n\n strIn[len-numDups] = '\\0';\n }\n}\n</code></pre>\n\n<p>The <strong>hash/linq</strong> approaches above are what you would generally use in real life. However in interviews they usually want to put some constraints e.g. constant space which rules out hash or no internal <strong>api</strong> - which rules out using <strong>LINQ</strong>.</p>\n"
},
{
"answer_id": 2644115,
"author": "Vijay Swami",
"author_id": 317324,
"author_profile": "https://Stackoverflow.com/users/317324",
"pm_score": 3,
"selected": false,
"text": "<p>The following piece of code attempts to remove duplicates from an ArrayList though this is not an optimal solution. I was asked this question during an interview to remove duplicates through recursion, and without using a second/temp arraylist: </p>\n\n<pre><code>private void RemoveDuplicate() \n{\n\nArrayList dataArray = new ArrayList(5);\n\n dataArray.Add(\"1\");\n dataArray.Add(\"1\");\n dataArray.Add(\"6\");\n dataArray.Add(\"6\");\n dataArray.Add(\"6\");\n dataArray.Add(\"3\");\n dataArray.Add(\"6\");\n dataArray.Add(\"4\");\n dataArray.Add(\"5\");\n dataArray.Add(\"4\");\n dataArray.Add(\"1\");\n\n dataArray.Sort();\n\n GetDistinctArrayList(dataArray, 0);\n}\n\nprivate void GetDistinctArrayList(ArrayList arr, int idx)\n\n{\n\n int count = 0;\n\n if (idx >= arr.Count) return;\n\n string val = arr[idx].ToString();\n foreach (String s in arr)\n {\n if (s.Equals(arr[idx]))\n {\n count++;\n }\n }\n\n if (count > 1)\n {\n arr.Remove(val);\n GetDistinctArrayList(arr, idx);\n }\n else\n {\n idx += 1;\n GetDistinctArrayList(arr, idx);\n }\n }\n</code></pre>\n"
},
{
"answer_id": 9272477,
"author": "Pintu",
"author_id": 1177685,
"author_profile": "https://Stackoverflow.com/users/1177685",
"pm_score": 3,
"selected": false,
"text": "<pre><code>protected void Page_Load(object sender, EventArgs e)\n{\n string a = \"a;b;c;d;e;v\";\n string[] b = a.Split(';');\n string[] c = b.Distinct().ToArray();\n\n if (b.Length != c.Length)\n {\n for (int i = 0; i < b.Length; i++)\n {\n try\n {\n if (b[i].ToString() != c[i].ToString())\n {\n Response.Write(\"Found duplicate \" + b[i].ToString());\n return;\n }\n }\n catch (Exception ex)\n {\n Response.Write(\"Found duplicate \" + b[i].ToString());\n return;\n }\n } \n }\n else\n {\n Response.Write(\"No duplicate \");\n }\n}\n</code></pre>\n"
},
{
"answer_id": 13996868,
"author": "komizo",
"author_id": 1792434,
"author_profile": "https://Stackoverflow.com/users/1792434",
"pm_score": 3,
"selected": false,
"text": "<p>Maybe hashset which do not store duplicate elements and silently ignore requests to add\nduplicates.</p>\n\n<pre><code>static void Main()\n{\n string textWithDuplicates = \"aaabbcccggg\"; \n\n Console.WriteLine(textWithDuplicates.Count()); \n var letters = new HashSet<char>(textWithDuplicates);\n Console.WriteLine(letters.Count());\n\n foreach (char c in letters) Console.Write(c);\n Console.WriteLine(\"\");\n\n int[] array = new int[] { 12, 1, 1, 1, 1, 1, 1, 1, 2, 2, 2, 2, 2 };\n\n Console.WriteLine(array.Count());\n var distinctArray = new HashSet<int>(array);\n Console.WriteLine(distinctArray.Count());\n\n foreach (int i in distinctArray) Console.Write(i + \",\");\n}\n</code></pre>\n"
},
{
"answer_id": 17121191,
"author": "AptSenSDET",
"author_id": 2488362,
"author_profile": "https://Stackoverflow.com/users/2488362",
"pm_score": 2,
"selected": false,
"text": "<p>Tested the below & it works. What's cool is that it does a culture sensitive search too</p>\n\n<pre><code>class RemoveDuplicatesInString\n{\n public static String RemoveDups(String origString)\n {\n String outString = null;\n int readIndex = 0;\n CompareInfo ci = CultureInfo.CurrentCulture.CompareInfo;\n\n\n if(String.IsNullOrEmpty(origString))\n {\n return outString;\n }\n\n foreach (var ch in origString)\n {\n if (readIndex == 0)\n {\n outString = String.Concat(ch);\n readIndex++;\n continue;\n }\n\n if (ci.IndexOf(origString, ch.ToString().ToLower(), 0, readIndex) == -1)\n {\n //Unique char as this char wasn't found earlier.\n outString = String.Concat(outString, ch); \n }\n\n readIndex++;\n\n }\n\n\n return outString;\n }\n\n\n static void Main(string[] args)\n {\n String inputString = \"aAbcefc\";\n String outputString;\n\n outputString = RemoveDups(inputString);\n\n Console.WriteLine(outputString);\n }\n</code></pre>\n\n<p>}</p>\n\n<p>--AptSenSDET</p>\n"
},
{
"answer_id": 17442504,
"author": "Muhammad Mubashir",
"author_id": 878106,
"author_profile": "https://Stackoverflow.com/users/878106",
"pm_score": 3,
"selected": false,
"text": "<p>-- This is <strong>Interview Question</strong> asked every time. Now i done its coding.</p>\n\n<pre><code>static void Main(string[] args)\n{ \n int[] array = new int[] { 4, 8, 4, 1, 1, 4, 8 }; \n int numDups = 0, prevIndex = 0;\n\n for (int i = 0; i < array.Length; i++)\n {\n bool foundDup = false;\n for (int j = 0; j < i; j++)\n {\n if (array[i] == array[j])\n {\n foundDup = true;\n numDups++; // Increment means Count for Duplicate found in array.\n break;\n } \n }\n\n if (foundDup == false)\n {\n array[prevIndex] = array[i];\n prevIndex++;\n }\n }\n\n // Just Duplicate records replce by zero.\n for (int k = 1; k <= numDups; k++)\n { \n array[array.Length - k] = '\\0'; \n }\n\n\n Console.WriteLine(\"Console program for Remove duplicates from array.\");\n Console.Read();\n }\n</code></pre>\n"
},
{
"answer_id": 24587289,
"author": "Salman Ramzan",
"author_id": 3807840,
"author_profile": "https://Stackoverflow.com/users/3807840",
"pm_score": 2,
"selected": false,
"text": "<p>This code 100% remove duplicate values from an array[as I used a[i]].....You can convert it in any OO language..... :)</p>\n\n<pre><code>for(int i=0;i<size;i++)\n{\n for(int j=i+1;j<size;j++)\n {\n if(a[i] == a[j])\n {\n for(int k=j;k<size;k++)\n {\n a[k]=a[k+1];\n }\n j--;\n size--;\n }\n }\n\n}\n</code></pre>\n"
},
{
"answer_id": 29020414,
"author": "Fábio Delboni",
"author_id": 4664826,
"author_profile": "https://Stackoverflow.com/users/4664826",
"pm_score": 3,
"selected": false,
"text": "<p>Simple solution:</p>\n\n<pre><code>using System.Linq;\n...\n\npublic static int[] Distinct(int[] handles)\n{\n return handles.ToList().Distinct().ToArray();\n}\n</code></pre>\n"
},
{
"answer_id": 29587789,
"author": "R.Akhlaghi",
"author_id": 2830315,
"author_profile": "https://Stackoverflow.com/users/2830315",
"pm_score": 1,
"selected": false,
"text": "<p>you can using This code when work with an ArrayList</p>\n\n<pre><code>ArrayList arrayList;\n//Add some Members :)\narrayList.Add(\"ali\");\narrayList.Add(\"hadi\");\narrayList.Add(\"ali\");\n\n//Remove duplicates from array\n for (int i = 0; i < arrayList.Count; i++)\n {\n for (int j = i + 1; j < arrayList.Count ; j++)\n if (arrayList[i].ToString() == arrayList[j].ToString())\n arrayList.Remove(arrayList[j]);\n</code></pre>\n"
},
{
"answer_id": 35145623,
"author": "HMartyrossian",
"author_id": 5075542,
"author_profile": "https://Stackoverflow.com/users/5075542",
"pm_score": 1,
"selected": false,
"text": "<pre><code>public static int RemoveDuplicates(ref int[] array)\n{\n int size = array.Length;\n\n // if 0 or 1, return 0 or 1:\n if (size < 2) {\n return size;\n }\n\n int current = 0;\n for (int candidate = 1; candidate < size; ++candidate) {\n if (array[current] != array[candidate]) {\n array[++current] = array[candidate];\n }\n }\n\n // index to count conversion:\n return ++current;\n}\n</code></pre>\n"
},
{
"answer_id": 39868699,
"author": "Papasani Mohansrinivas",
"author_id": 6504878,
"author_profile": "https://Stackoverflow.com/users/6504878",
"pm_score": 1,
"selected": false,
"text": "<p>Below is an simple logic in java you traverse elements of array twice and if you see any same element you assign zero to it plus you don't touch the index of element you are comparing.</p>\n\n<pre><code>import java.util.*;\nclass removeDuplicate{\nint [] y ;\n\npublic removeDuplicate(int[] array){\n y=array;\n\n for(int b=0;b<y.length;b++){\n int temp = y[b];\n for(int v=0;v<y.length;v++){\n if( b!=v && temp==y[v]){\n y[v]=0;\n }\n }\n }\n}\n</code></pre>\n"
},
{
"answer_id": 47568568,
"author": "Arie Yehieli",
"author_id": 4604796,
"author_profile": "https://Stackoverflow.com/users/4604796",
"pm_score": 0,
"selected": false,
"text": "<pre><code> private static string[] distinct(string[] inputArray)\n {\n bool alreadyExists;\n string[] outputArray = new string[] {};\n\n for (int i = 0; i < inputArray.Length; i++)\n {\n alreadyExists = false;\n for (int j = 0; j < outputArray.Length; j++)\n {\n if (inputArray[i] == outputArray[j])\n alreadyExists = true;\n }\n if (alreadyExists==false)\n {\n Array.Resize<string>(ref outputArray, outputArray.Length + 1);\n outputArray[outputArray.Length-1] = inputArray[i];\n }\n }\n return outputArray;\n }\n</code></pre>\n"
},
{
"answer_id": 52789546,
"author": "Ali Bayat",
"author_id": 3427324,
"author_profile": "https://Stackoverflow.com/users/3427324",
"pm_score": 2,
"selected": false,
"text": "<p>Generic Extension method :</p>\n\n<pre><code>public static IEnumerable<TSource> Distinct<TSource>(this IEnumerable<TSource> source, IEqualityComparer<TSource> comparer)\n{\n if (source == null)\n throw new ArgumentNullException(nameof(source));\n\n HashSet<TSource> set = new HashSet<TSource>(comparer);\n foreach (TSource item in source)\n {\n if (set.Add(item))\n {\n yield return item;\n }\n }\n}\n</code></pre>\n"
},
{
"answer_id": 55854713,
"author": "Rohan",
"author_id": 10154571,
"author_profile": "https://Stackoverflow.com/users/10154571",
"pm_score": -1,
"selected": false,
"text": "<pre><code>using System;\nusing System.Collections.Generic;\nusing System.Linq;\n\n\nnamespace Rextester\n{\n public class Program\n {\n public static void Main(string[] args)\n {\n List<int> listofint1 = new List<int> { 4, 8, 4, 1, 1, 4, 8 };\n List<int> updatedlist= removeduplicate(listofint1);\n foreach(int num in updatedlist)\n Console.WriteLine(num);\n }\n\n\n public static List<int> removeduplicate(List<int> listofint)\n {\n List<int> listofintwithoutduplicate= new List<int>();\n\n\n foreach(var num in listofint)\n {\n if(!listofintwithoutduplicate.Any(p=>p==num))\n {\n listofintwithoutduplicate.Add(num);\n }\n }\n return listofintwithoutduplicate;\n }\n }\n\n\n\n}\n</code></pre>\n"
},
{
"answer_id": 58223263,
"author": "Kudakwashe Mafutah",
"author_id": 2917482,
"author_profile": "https://Stackoverflow.com/users/2917482",
"pm_score": -1,
"selected": false,
"text": "<pre><code>strINvalues = \"1,1,2,2,3,3,4,4\";\nstrINvalues = string.Join(\",\", strINvalues .Split(',').Distinct().ToArray());\nDebug.Writeline(strINvalues);\n</code></pre>\n\n<p>Kkk Not sure if this is witchcraft or just beautiful code</p>\n\n<p><strong>1</strong> strINvalues .Split(',').Distinct().ToArray()</p>\n\n<p><strong>2</strong> string.Join(\",\", XXX);</p>\n\n<p><em>1</em> Splitting the array and using Distinct [LINQ] to remove duplicates\n<em>2</em> Joining it back without the duplicates.</p>\n\n<p>Sorry I never read the text on StackOverFlow just the code. it make more sense than the text ;) </p>\n"
},
{
"answer_id": 61983714,
"author": "P_P",
"author_id": 1673752,
"author_profile": "https://Stackoverflow.com/users/1673752",
"pm_score": 1,
"selected": false,
"text": "<p>The best way? Hard to say, the HashSet approach looks fast,\nbut (depending on the data) using a sort algorithm (CountSort ?)\ncan be much faster.</p>\n<pre><code>using System;\nusing System.Collections.Generic;\nusing System.Linq;\nclass Program\n{\n static void Main()\n {\n Random r = new Random(0); int[] a, b = new int[1000000];\n for (int i = b.Length - 1; i >= 0; i--) b[i] = r.Next(b.Length);\n a = new int[b.Length]; Array.Copy(b, a, b.Length);\n a = dedup0(a); Console.WriteLine(a.Length);\n a = new int[b.Length]; Array.Copy(b, a, b.Length);\n var w = System.Diagnostics.Stopwatch.StartNew();\n a = dedup0(a); Console.WriteLine(w.Elapsed); Console.Read();\n }\n\n static int[] dedup0(int[] a) // 48 ms \n {\n return new HashSet<int>(a).ToArray();\n }\n\n static int[] dedup1(int[] a) // 68 ms\n {\n Array.Sort(a); int i = 0, j = 1, k = a.Length; if (k < 2) return a;\n while (j < k) if (a[i] == a[j]) j++; else a[++i] = a[j++];\n Array.Resize(ref a, i + 1); return a;\n }\n\n static int[] dedup2(int[] a) // 8 ms\n {\n var b = new byte[a.Length]; int c = 0;\n for (int i = 0; i < a.Length; i++) \n if (b[a[i]] == 0) { b[a[i]] = 1; c++; }\n a = new int[c];\n for (int j = 0, i = 0; i < b.Length; i++) if (b[i] > 0) a[j++] = i;\n return a;\n }\n}\n</code></pre>\n<p>Almost branch free. How? Debug mode, Step Into (F11) with a small array: {1,3,1,1,0}</p>\n<pre><code> static int[] dedupf(int[] a) // 4 ms\n {\n if (a.Length < 2) return a;\n var b = new byte[a.Length]; int c = 0, bi, ai, i, j;\n for (i = 0; i < a.Length; i++)\n { ai = a[i]; bi = 1 ^ b[ai]; b[ai] |= (byte)bi; c += bi; }\n a = new int[c]; i = 0; while (b[i] == 0) i++; a[0] = i++;\n for (j = 0; i < b.Length; i++) a[j += bi = b[i]] += bi * i; return a;\n }\n</code></pre>\n<p>A solution with two nested loops might take some time,\nespecially for larger arrays.</p>\n<pre><code> static int[] dedup(int[] a)\n {\n int i, j, k = a.Length - 1;\n for (i = 0; i < k; i++)\n for (j = i + 1; j <= k; j++) if (a[i] == a[j]) a[j--] = a[k--];\n Array.Resize(ref a, k + 1); return a;\n }\n</code></pre>\n"
},
{
"answer_id": 62239378,
"author": "Swathi Sriramaneni",
"author_id": 13697010,
"author_profile": "https://Stackoverflow.com/users/13697010",
"pm_score": 0,
"selected": false,
"text": "<pre><code>int size = a.Length;\n for (int i = 0; i < size; i++)\n {\n for (int j = i + 1; j < size; j++)\n {\n if (a[i] == a[j])\n {\n for (int k = j; k < size; k++)\n {\n if (k != size - 1)\n {\n int temp = a[k];\n a[k] = a[k + 1];\n a[k + 1] = temp;\n\n }\n }\n j--;\n size--;\n }\n }\n }\n</code></pre>\n"
},
{
"answer_id": 63166358,
"author": "Sourcephy",
"author_id": 8196012,
"author_profile": "https://Stackoverflow.com/users/8196012",
"pm_score": -1,
"selected": false,
"text": "<p>Removing duplicate and ignore case sensitive using Distinct & StringComparer.InvariantCultureIgnoreCase</p>\n<pre><code>string[] array = new string[] { "A", "a", "b", "B", "a", "C", "c", "C", "A", "1" };\nvar r = array.Distinct(StringComparer.InvariantCultureIgnoreCase).ToList();\nConsole.WriteLine(r.Count); // return 4 items\n</code></pre>\n"
},
{
"answer_id": 64519180,
"author": "AKINNUBI ABIOLA SYLVESTER",
"author_id": 6596443,
"author_profile": "https://Stackoverflow.com/users/6596443",
"pm_score": -1,
"selected": false,
"text": "<p>Find answer below.</p>\n<pre><code>class Program\n{\n static void Main(string[] args)\n {\n var nums = new int[] { 1, 4, 3, 3, 3, 5, 5, 7, 7, 7, 7, 9, 9, 9 };\n var result = removeDuplicates(nums);\n foreach (var item in result)\n {\n Console.WriteLine(item);\n }\n }\n static int[] removeDuplicates(int[] nums)\n {\n nums = nums.ToList().OrderBy(c => c).ToArray();\n int j = 1;\n int i = 0;\n int stop = 0;\n while (j < nums.Length)\n {\n if (nums[i] != nums[j])\n {\n nums[i + 1] = nums[j];\n stop = i + 2;\n i++;\n }\n j++;\n }\n nums = nums.Take(stop).ToArray();\n return nums;\n }\n}\n</code></pre>\n<p>Just a bit of contribution based on a test i just solved, maybe helpful and open to improvement by other top contributors here.\nHere are the things i did:</p>\n<ol>\n<li>I used OrderBy which allows me order or sort the items from smallest to the highest using LINQ</li>\n<li>I then convert it to back to an array and then re-assign it back to the primary datasource</li>\n<li>So i then initialize j which is my right hand side of the array to be 1 and i which is my left hand side of the array to be 0, i also initialize where i would i to stop to be 0.</li>\n<li>I used a while loop to increment through the array by going from one position to the other left to right, for each increment the stop position is the current value of i + 2 which i will use later to truncate the duplicates from the array.</li>\n<li>I then increment by moving from left to right from the if statement and from right to right outside of the if statement until i iterate through the entire values of the array.</li>\n<li>I then pick from the first element to the stop position which becomes the last i index plus 2. that way i am able to remove all the duplicate items from the int array. which is then reassigned.</li>\n</ol>\n"
},
{
"answer_id": 68816360,
"author": "Faisal Ansari",
"author_id": 6898760,
"author_profile": "https://Stackoverflow.com/users/6898760",
"pm_score": 0,
"selected": false,
"text": "<p>So I was doing an interview session and got the same question to sort and distinct</p>\n<pre><code>static void Sort()\n {\n try\n {\n int[] number = new int[Convert.ToInt32(Console.ReadLine())];\n for (int i = 0; i < number.Length; i++)\n {\n number[i] = Convert.ToInt32(Console.ReadLine());\n }\n Array.Sort(number);\n int[] num = number.Distinct().ToArray();\n for (int i = 0; i < num.Length; i++)\n {\n Console.WriteLine(num[i]);\n }\n }\n catch (Exception ex)\n {\n Console.WriteLine(ex);\n }\n Console.Read();\n }\n</code></pre>\n"
}
] | 2008/08/13 | [
"https://Stackoverflow.com/questions/9673",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/493/"
] | I have been working with a `string[]` array in C# that gets returned from a function call. I could possibly cast to a `Generic` collection, but I was wondering if there was a better way to do it, possibly by using a temp array.
**What is the best way to remove duplicates from a C# array?** | You could possibly use a LINQ query to do this:
```
int[] s = { 1, 2, 3, 3, 4};
int[] q = s.Distinct().ToArray();
``` |
9,687 | <p>I'm looking for a pattern for performing a dynamic search on multiple tables.</p>
<p>I have no control over the legacy (and poorly designed) database table structure.</p>
<p>Consider a scenario similar to a resume search where a user may want to perform a search against any of the data in the resume and get back a list of resumes that match their search criteria. Any field can be searched at anytime and in combination with one or more other fields.</p>
<p>The actual sql query gets created dynamically depending on which fields are searched. Most solutions I've found involve complicated if blocks, but I can't help but think there must be a more elegant solution since this must be a solved problem by now.</p>
<hr>
<p>Yeah, so I've started down the path of dynamically building the sql in code. Seems godawful. If I really try to support the requested ability to query any combination of any field in any table this is going to be one MASSIVE set of if statements. <em>shiver</em></p>
<hr>
<p>I believe I read that COALESCE only works if your data does not contain NULLs. Is that correct? If so, no go, since I have NULL values all over the place.</p>
| [
{
"answer_id": 9889,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 3,
"selected": false,
"text": "<p>As far as I understand (and I'm also someone who has written against a horrible legacy database), there is no such thing as dynamic WHERE clauses. It has NOT been solved. </p>\n\n<p>Personally, I prefer to generate my dynamic searches in code. Makes testing convenient. Note, when you create your sql queries in code, don't concatenate in user input. Use your @variables!</p>\n\n<p>The only alternative is to use the COALESCE operator. Let's say you have the following table:</p>\n\n<pre><code>Users\n-----------\nName nvarchar(20)\nNickname nvarchar(10)\n</code></pre>\n\n<p>and you want to search optionally for name or nickname. The following query will do this:</p>\n\n<pre><code>SELECT Name, Nickname\nFROM Users\nWHERE\n Name = COALESCE(@name, Name) AND\n Nickname = COALESCE(@nick, Nickname)\n</code></pre>\n\n<p>If you don't want to search for something, just pass in a null. For example, passing in \"brian\" for @name and null for @nick results in the following query being evaluated:</p>\n\n<pre><code>SELECT Name, Nickname\nFROM Users\nWHERE\n Name = 'brian' AND\n Nickname = Nickname\n</code></pre>\n\n<p>The coalesce operator turns the null into an identity evaluation, which is always true and doesn't affect the where clause.</p>\n"
},
{
"answer_id": 9918,
"author": "DevelopingChris",
"author_id": 1220,
"author_profile": "https://Stackoverflow.com/users/1220",
"pm_score": 1,
"selected": false,
"text": "<p>Search and normalization can be at odds with each other. So probably first thing would be to get some kind of \"view\" that shows all the fields that can be searched as a single row with a single key getting you the resume. then you can throw something like <a href=\"http://lucene.apache.org/java/docs/\" rel=\"nofollow noreferrer\">Lucene</a> in front of that to give you a full text index of those rows, the way that works is, you ask it for \"x\" in this view and it returns to you the key. Its a great solution and come recommended by joel himself on the podcast within the first 2 months IIRC.</p>\n"
},
{
"answer_id": 1081248,
"author": "elviejo79",
"author_id": 54848,
"author_profile": "https://Stackoverflow.com/users/54848",
"pm_score": 1,
"selected": false,
"text": "<p>What you need is something like <a href=\"http://sphinxsearch.com/\" rel=\"nofollow noreferrer\">SphinxSearch</a> (for MySQL) or <a href=\"http://lucene.apache.org/java/docs/\" rel=\"nofollow noreferrer\">Apache Lucene</a>.</p>\n\n<p>As you said in your example lets imagine a Resume that will composed of several fields: </p>\n\n<ul>\n<li>List item</li>\n<li>Name, </li>\n<li>Adreess, </li>\n<li>Education (this could be a table on its own) or </li>\n<li>Work experience (this could grow to its own table where each row represents a previous job)</li>\n</ul>\n\n<p>So searching for a word in all those fields with WHERE rapidly becomes a very long query with several JOINS.</p>\n\n<p>Instead you could change your framework of reference and think of the Whole resume as what it is a Single Document and you just want to search said document.</p>\n\n<p>This is where tools like Sphinx Search do. They create a FULL TEXT index of your 'document' and then you can query sphinx and it will give you back where in the Database that record was found.</p>\n\n<p>Really good search results.</p>\n\n<p>Don't worry about this tools not being part of your RDBMS it will save you a lot of headaches to use the appropriate model \"Documents\" vs the incorrect one \"TABLES\" for this application.</p>\n"
}
] | 2008/08/13 | [
"https://Stackoverflow.com/questions/9687",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1097/"
] | I'm looking for a pattern for performing a dynamic search on multiple tables.
I have no control over the legacy (and poorly designed) database table structure.
Consider a scenario similar to a resume search where a user may want to perform a search against any of the data in the resume and get back a list of resumes that match their search criteria. Any field can be searched at anytime and in combination with one or more other fields.
The actual sql query gets created dynamically depending on which fields are searched. Most solutions I've found involve complicated if blocks, but I can't help but think there must be a more elegant solution since this must be a solved problem by now.
---
Yeah, so I've started down the path of dynamically building the sql in code. Seems godawful. If I really try to support the requested ability to query any combination of any field in any table this is going to be one MASSIVE set of if statements. *shiver*
---
I believe I read that COALESCE only works if your data does not contain NULLs. Is that correct? If so, no go, since I have NULL values all over the place. | As far as I understand (and I'm also someone who has written against a horrible legacy database), there is no such thing as dynamic WHERE clauses. It has NOT been solved.
Personally, I prefer to generate my dynamic searches in code. Makes testing convenient. Note, when you create your sql queries in code, don't concatenate in user input. Use your @variables!
The only alternative is to use the COALESCE operator. Let's say you have the following table:
```
Users
-----------
Name nvarchar(20)
Nickname nvarchar(10)
```
and you want to search optionally for name or nickname. The following query will do this:
```
SELECT Name, Nickname
FROM Users
WHERE
Name = COALESCE(@name, Name) AND
Nickname = COALESCE(@nick, Nickname)
```
If you don't want to search for something, just pass in a null. For example, passing in "brian" for @name and null for @nick results in the following query being evaluated:
```
SELECT Name, Nickname
FROM Users
WHERE
Name = 'brian' AND
Nickname = Nickname
```
The coalesce operator turns the null into an identity evaluation, which is always true and doesn't affect the where clause. |
9,702 | <p>As part of our current database work, we are looking at a dealing with the process of updating databases.</p>
<p>A point which has been brought up recurrently, is that of dealing with system vs. user values; in our project user and system vals are stored together. For example...</p>
<p>We have a list of templates.</p>
<pre><code>1, <system template>
2, <system template>
3, <system template>
</code></pre>
<p>These are mapped in the app to an enum (1, 2, 3)</p>
<p>Then a user comes in and adds...</p>
<pre><code>4, <user template>
</code></pre>
<p>...and...</p>
<pre><code>5, <user template>
</code></pre>
<p>Then.. we issue an upgrade.. and insert as part of our upgrade scripts...</p>
<pre><code><new id> [6], <new system template>
</code></pre>
<p>THEN!!... we find a bug in the new system template and need to update it... The problem is how? We cannot update record using ID6 (as we may have inserted it as 9, or 999, so we have to identify the record using some other mechanism)</p>
<p>So, we've come to two possible solutions for this.</p>
<h2><strong>In the red corner (speed)....</strong></h2>
<p>We simply start user Ids at 5000 (or some other value) and test data at 10000 (or some other value). This would allow us to make modifications to system values and test them up to the lower limit of the next ID range. </p>
<p>Advantage...Quick and easy to implement, </p>
<p>Disadvantage... could run out of values if we don't choose a big enough range!</p>
<h2><strong>In the blue corner (scalability)...</strong></h2>
<p>We store, system and user data separately, use GUIDs as Ids and merge the two lists using a view.</p>
<p>Advantage...Scalable..No limits w/regard to DB size. </p>
<p>Disadvantage.. More complicated to implement. (many to one updatable views etc.)</p>
<hr>
<p>I plump squarely for the first option, but looking for some ammo to back me up!</p>
<p>Does anyone have any thoughts on these approaches, or even one(s) that we've missed?</p>
| [
{
"answer_id": 9707,
"author": "John Smithers",
"author_id": 1069,
"author_profile": "https://Stackoverflow.com/users/1069",
"pm_score": 0,
"selected": false,
"text": "<p>Maybe I didn't get it, but couldn't you use GUIDs as Ids and still have user and system data together? Then you can access the system data by the (non-changable) GUIDs.</p>\n"
},
{
"answer_id": 9713,
"author": "Biri",
"author_id": 968,
"author_profile": "https://Stackoverflow.com/users/968",
"pm_score": 1,
"selected": false,
"text": "<p>I recommend using the second with the modification that you store the system and user values in one table. GUID is quite reliable in this manner.</p>\n\n<p>Another idea: use any text-based ID (not necessary GUID), which you give for the system values and is generated by a random string or a string based on some kind of custom logic for the user values.</p>\n\n<p>Another idea: use the first approach, but extend the table with a flag which shows if a value is system or user. Maybe this is the easiest. Ok, you have to write some kind of mechanism to update the correct system value, but it can be done easily.</p>\n"
},
{
"answer_id": 9728,
"author": "Biri",
"author_id": 968,
"author_profile": "https://Stackoverflow.com/users/968",
"pm_score": 0,
"selected": false,
"text": "<p>I don't think that GUID should make any problem.</p>\n\n<p>If you want to avoid it, then use a flag:</p>\n\n<blockquote>\n <p>ID int</p>\n \n <p>template whatever</p>\n \n <p>flag enum/int/bool</p>\n</blockquote>\n\n<p>Flag shows whether the actual value is a system or a user value.</p>\n\n<p>If you would like to update a system value, then ask only for system values ordered by ID, and it will show you actual order of insertion (you should have a bigint or something for ID to make sure that it doesn't get full and it doesn't get the deleted IDs back to work). With this list the x. record is the x. inserted system value.</p>\n"
},
{
"answer_id": 9731,
"author": "ninesided",
"author_id": 1030,
"author_profile": "https://Stackoverflow.com/users/1030",
"pm_score": 1,
"selected": false,
"text": "<p>+1 for Biri's text based ID - define a \"template_mnemonic\" text based column and make it the primary key. This will be a known value when you insert it as you, the developers will have decided on it (or auto-generated it) and you will always be able to reference a template by its mnemonic regardless of how many user specified templates there are. It also allows users to have a meaningful naming convention for their templates.</p>\n"
},
{
"answer_id": 9857,
"author": "RobertTheGrey",
"author_id": 1107,
"author_profile": "https://Stackoverflow.com/users/1107",
"pm_score": 2,
"selected": true,
"text": "<p>I have never had problems (performance or development - TDD & unit testing included) using GUIDs as the ID for my databases, and I've worked on some pretty big ones. Have a look <a href=\"http://www.sql-server-performance.com/articles/per/guid_performance_p2.aspx\" rel=\"nofollow noreferrer\">here</a>, <a href=\"http://weblogs.asp.net/wwright/archive/2007/11/04/the-gospel-of-the-guid-and-why-it-matters.aspx\" rel=\"nofollow noreferrer\">here</a> and <a href=\"http://weblogs.asp.net/wwright/archive/2007/11/11/gospel-of-the-guid-answers-to-your-burning-questions-comments-and-insults.aspx\" rel=\"nofollow noreferrer\">here</a> if you want to find out more about using GUIDs (and the potential GOTCHAS involved) as your primary keys - but I can't recommend it highly enough since moving data around safely and DB synchronisation becomes as easy as brushing your teeth in the morning :-)</p>\n\n<p>For your question above, I would either recommend a third column (if possible) that indicates whether or not the template is user or system based, or you can at the very least generate GUIDs for system templates as you insert them and keep a list of those on hand, so that if you need to update the template, you can just target that same GUID in your DEV, UAT and /or PRODUCTION databases without fear of overwriting other templates. The third column would come in handy though for selecting all system or user templates at will, without the need to seperate them into two tables (this is overkill IMHO).</p>\n\n<p>I hope that helps,</p>\n\n<p>Rob G</p>\n"
},
{
"answer_id": 14660,
"author": "David Hayes",
"author_id": 1769,
"author_profile": "https://Stackoverflow.com/users/1769",
"pm_score": 0,
"selected": false,
"text": "<p>I think there is a better third solution. \nIt strikes me that you're storing two different things in the same table and that you might be better off creating 2 separate tables one for user templates and one for system templates. You might then be able to create a view over the two tables to make them appear as a single object to your application. \nObviously I don't have full knowledge of your application and this may be impossible for you for any number of reasons but I think it's a neater solution than GUIDs and way safer than ranges of IDs (seriously don't do ID ranges it'll bite you one day)</p>\n"
}
] | 2008/08/13 | [
"https://Stackoverflow.com/questions/9702",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1193/"
] | As part of our current database work, we are looking at a dealing with the process of updating databases.
A point which has been brought up recurrently, is that of dealing with system vs. user values; in our project user and system vals are stored together. For example...
We have a list of templates.
```
1, <system template>
2, <system template>
3, <system template>
```
These are mapped in the app to an enum (1, 2, 3)
Then a user comes in and adds...
```
4, <user template>
```
...and...
```
5, <user template>
```
Then.. we issue an upgrade.. and insert as part of our upgrade scripts...
```
<new id> [6], <new system template>
```
THEN!!... we find a bug in the new system template and need to update it... The problem is how? We cannot update record using ID6 (as we may have inserted it as 9, or 999, so we have to identify the record using some other mechanism)
So, we've come to two possible solutions for this.
**In the red corner (speed)....**
---------------------------------
We simply start user Ids at 5000 (or some other value) and test data at 10000 (or some other value). This would allow us to make modifications to system values and test them up to the lower limit of the next ID range.
Advantage...Quick and easy to implement,
Disadvantage... could run out of values if we don't choose a big enough range!
**In the blue corner (scalability)...**
---------------------------------------
We store, system and user data separately, use GUIDs as Ids and merge the two lists using a view.
Advantage...Scalable..No limits w/regard to DB size.
Disadvantage.. More complicated to implement. (many to one updatable views etc.)
---
I plump squarely for the first option, but looking for some ammo to back me up!
Does anyone have any thoughts on these approaches, or even one(s) that we've missed? | I have never had problems (performance or development - TDD & unit testing included) using GUIDs as the ID for my databases, and I've worked on some pretty big ones. Have a look [here](http://www.sql-server-performance.com/articles/per/guid_performance_p2.aspx), [here](http://weblogs.asp.net/wwright/archive/2007/11/04/the-gospel-of-the-guid-and-why-it-matters.aspx) and [here](http://weblogs.asp.net/wwright/archive/2007/11/11/gospel-of-the-guid-answers-to-your-burning-questions-comments-and-insults.aspx) if you want to find out more about using GUIDs (and the potential GOTCHAS involved) as your primary keys - but I can't recommend it highly enough since moving data around safely and DB synchronisation becomes as easy as brushing your teeth in the morning :-)
For your question above, I would either recommend a third column (if possible) that indicates whether or not the template is user or system based, or you can at the very least generate GUIDs for system templates as you insert them and keep a list of those on hand, so that if you need to update the template, you can just target that same GUID in your DEV, UAT and /or PRODUCTION databases without fear of overwriting other templates. The third column would come in handy though for selecting all system or user templates at will, without the need to seperate them into two tables (this is overkill IMHO).
I hope that helps,
Rob G |
9,734 | <p>Why does C#.Net allow the declaration of the string object to be case-insensitive?</p>
<pre><code>String sHello = "Hello";
string sHello = "Hello";
</code></pre>
<p>Both the lower-case and upper-case S of the word String are acceptable and this seems to be the only object that allows this.</p>
<p>Can anyone explain why?</p>
| [
{
"answer_id": 9739,
"author": "lubos hasko",
"author_id": 275,
"author_profile": "https://Stackoverflow.com/users/275",
"pm_score": 2,
"selected": false,
"text": "<p>\"String\" is the name of the class. \"string\" is keyword that maps this class.</p>\n\n<p>it's the same like</p>\n\n<ul>\n<li>Int32 => int</li>\n<li>Decimal => decimal</li>\n<li>Int64 => long</li>\n</ul>\n\n<p>... and so on...</p>\n"
},
{
"answer_id": 9742,
"author": "ZombieSheep",
"author_id": 377,
"author_profile": "https://Stackoverflow.com/users/377",
"pm_score": 0,
"selected": false,
"text": "<p>string is an alias for System.String. They are the same thing.</p>\n\n<p>By convention, though, objects of type (System.String) are generally refered to as the alias - e.g.</p>\n\n<pre><code>string myString = \"Hello\";\n</code></pre>\n\n<p>whereas operations on the class use the uppercase version\ne.g.</p>\n\n<pre><code>String.IsNullOrEmpty(myStringVariable);\n</code></pre>\n"
},
{
"answer_id": 9746,
"author": "aku",
"author_id": 1196,
"author_profile": "https://Stackoverflow.com/users/1196",
"pm_score": 1,
"selected": false,
"text": "<p>\"string\" is a C# keyword. it's just an alias for \"System.String\" - one of the .NET BCL classes. </p>\n"
},
{
"answer_id": 9747,
"author": "Keith",
"author_id": 905,
"author_profile": "https://Stackoverflow.com/users/905",
"pm_score": 5,
"selected": true,
"text": "<p><strong><code>string</code></strong> is a language keyword while <code>System.String</code> is the type it aliases.</p>\n\n<p>Both compile to exactly the same thing, similarly:</p>\n\n<ul>\n<li><strong><code>int</code></strong> is <code>System.Int32</code></li>\n<li><strong><code>long</code></strong> is <code>System.Int64</code></li>\n<li><strong><code>float</code></strong> is <code>System.Single</code></li>\n<li><strong><code>double</code></strong> is <code>System.Double</code></li>\n<li><strong><code>char</code></strong> is <code>System.Char</code></li>\n<li><strong><code>byte</code></strong> is <code>System.Byte</code></li>\n<li><strong><code>short</code></strong> is <code>System.Int16</code></li>\n<li><strong><code>ushort</code></strong> is <code>System.UInt16</code></li>\n<li><strong><code>uint</code></strong> is <code>System.UInt32</code></li>\n<li><strong><code>ulong</code></strong> is <code>System.UInt64</code></li>\n</ul>\n\n<p>I think in most cases this is about code legibility - all the basic system value types have aliases, I think the lower case <code>string</code> might just be for consistency.</p>\n"
},
{
"answer_id": 9748,
"author": "Patrik Svensson",
"author_id": 936,
"author_profile": "https://Stackoverflow.com/users/936",
"pm_score": 1,
"selected": false,
"text": "<p>\"string\" is just an C# alias for the class \"String\" in the System-namespace.</p>\n"
},
{
"answer_id": 9754,
"author": "Iain Holder",
"author_id": 1122,
"author_profile": "https://Stackoverflow.com/users/1122",
"pm_score": 3,
"selected": false,
"text": "<p>Further to the other answers, it's good practice to use keywords if they exist. </p>\n\n<p>E.g. you should use <strong>string</strong> rather than <strong>System.String</strong>.</p>\n"
},
{
"answer_id": 10226,
"author": "Brian Leahy",
"author_id": 580,
"author_profile": "https://Stackoverflow.com/users/580",
"pm_score": 0,
"selected": false,
"text": "<p>I use String and not string,\nInt32 instead of int, \nso that my syntax highlighting picks up on a string as a Type and not a keyword. I want keywords to jump out at me.</p>\n"
}
] | 2008/08/13 | [
"https://Stackoverflow.com/questions/9734",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/383/"
] | Why does C#.Net allow the declaration of the string object to be case-insensitive?
```
String sHello = "Hello";
string sHello = "Hello";
```
Both the lower-case and upper-case S of the word String are acceptable and this seems to be the only object that allows this.
Can anyone explain why? | **`string`** is a language keyword while `System.String` is the type it aliases.
Both compile to exactly the same thing, similarly:
* **`int`** is `System.Int32`
* **`long`** is `System.Int64`
* **`float`** is `System.Single`
* **`double`** is `System.Double`
* **`char`** is `System.Char`
* **`byte`** is `System.Byte`
* **`short`** is `System.Int16`
* **`ushort`** is `System.UInt16`
* **`uint`** is `System.UInt32`
* **`ulong`** is `System.UInt64`
I think in most cases this is about code legibility - all the basic system value types have aliases, I think the lower case `string` might just be for consistency. |
9,750 | <p>I was reading Joel's book where he was suggesting as interview question:</p>
<blockquote>
<p>Write a program to reverse the "ON" bits in a given byte.</p>
</blockquote>
<p>I only can think of a solution using C. </p>
<p>Asking here so you can show me how to do in a Non C way (if possible)</p>
| [
{
"answer_id": 9752,
"author": "Lasse V. Karlsen",
"author_id": 267,
"author_profile": "https://Stackoverflow.com/users/267",
"pm_score": 2,
"selected": false,
"text": "<p>What specifically does that question mean?</p>\n\n<p>Does <em>reverse</em> mean setting 1's to 0's and vice versa?</p>\n\n<p>Or does it mean <em>00001100</em> --> <em>00110000</em> where you reverse their order in the byte? Or perhaps just reversing the part that is from the first 1 to the last 1? ie. <em>00110101</em> --> <em>00101011</em>?</p>\n\n<p>Assuming it means reversing the bit order in the whole byte, here's an x86 assembler version:</p>\n\n<pre><code>; al is input register\n; bl is output register\n\nxor bl, bl ; clear output\n\n; first bit\nrcl al, 1 ; rotate al through carry\nrcr bl, 1 ; rotate carry into bl\n\n; duplicate above 2-line statements 7 more times for the other bits\n</code></pre>\n\n<p>not the most optimal solution, a table lookup is faster.</p>\n"
},
{
"answer_id": 9756,
"author": "Coincoin",
"author_id": 42,
"author_profile": "https://Stackoverflow.com/users/42",
"pm_score": 2,
"selected": false,
"text": "<p>Reversing the order of bits in C#:</p>\n\n<pre><code>byte ReverseByte(byte b)\n{\n byte r = 0;\n for(int i=0; i<8; i++)\n {\n int mask = 1 << i;\n int bit = (b & mask) >> i;\n int reversedMask = bit << (7 - i);\n r |= (byte)reversedMask;\n }\n return r;\n}\n</code></pre>\n\n<p>I'm sure there are more clever ways of doing it but in that precise case, the interview question is meant to determine if you know bitwise operations so I guess this solution would work.</p>\n\n<p>In an interview, the interviewer usually wants to know how you find a solution, what are you problem solving skills, if it's clean or if it's a hack. So don't come up with too much of a clever solution because that will <em>probably</em> mean you found it somewhere on the Internet beforehand. Don't try to fake that you don't know it neither and that you just come up with the answer because you are a genius, this is will be even worst if she figures out since you are basically lying.</p>\n"
},
{
"answer_id": 9758,
"author": "GaryF",
"author_id": 1035,
"author_profile": "https://Stackoverflow.com/users/1035",
"pm_score": 2,
"selected": false,
"text": "<p>The classic <a href=\"http://graphics.stanford.edu/~seander/bithacks.html\" rel=\"nofollow noreferrer\">Bit Hacks</a> page has several (really very clever) ways to do this, but it's all in C. Any language derived from C syntax (notably Java) will likely have similar methods. I'm sure we'll get some Haskell versions in this thread ;)</p>\n"
},
{
"answer_id": 9778,
"author": "James A. Rosen",
"author_id": 1190,
"author_profile": "https://Stackoverflow.com/users/1190",
"pm_score": 2,
"selected": false,
"text": "<blockquote>\n <p><code>byte ReverseByte(byte b)\n {\n return b ^ 0xff;\n }</code></p>\n</blockquote>\n\n<p>That works if <code>^</code> is XOR in your language, but not if it's <code>AND</code>, which it often is.</p>\n"
},
{
"answer_id": 9907,
"author": "Jason Day",
"author_id": 737,
"author_profile": "https://Stackoverflow.com/users/737",
"pm_score": 4,
"selected": false,
"text": "<blockquote>\n <p>What specifically does that question mean?</p>\n</blockquote>\n\n<p>Good question. If reversing the \"ON\" bits means reversing only the bits that are \"ON\", then you will always get 0, no matter what the input is. If it means reversing <em>all</em> the bits, i.e. changing all 1s to 0s and all 0s to 1s, which is how I initially read it, then that's just a bitwise NOT, or complement. C-based languages have a complement operator, <code>~</code>, that does this. For example:</p>\n\n<pre><code>unsigned char b = 102; /* 0x66, 01100110 */\nunsigned char reverse = ~b; /* 0x99, 10011001 */\n</code></pre>\n"
},
{
"answer_id": 9929,
"author": "palmsey",
"author_id": 521,
"author_profile": "https://Stackoverflow.com/users/521",
"pm_score": 2,
"selected": false,
"text": "<p>If you're talking about switching 1's to 0's and 0's to 1's, using Ruby:</p>\n\n<pre><code>n = 0b11001100\n~n\n</code></pre>\n\n<p>If you mean reverse the order:</p>\n\n<pre><code>n = 0b11001100\neval(\"0b\" + n.to_s(2).reverse)\n</code></pre>\n\n<p>If you mean counting the on bits, as mentioned by another user:</p>\n\n<pre><code>n = 123\ncount = 0\n0.upto(8) { |i| count = count + n[i] }\n</code></pre>\n\n<p>♥ Ruby</p>\n"
},
{
"answer_id": 10130,
"author": "Nick",
"author_id": 1236,
"author_profile": "https://Stackoverflow.com/users/1236",
"pm_score": 1,
"selected": false,
"text": "<p>I'm probably misremembering, but I thought that Joel's question was about <strong>counting</strong> the \"on\" bits rather than reversing them.</p>\n"
},
{
"answer_id": 10561,
"author": "C. K. Young",
"author_id": 13,
"author_profile": "https://Stackoverflow.com/users/13",
"pm_score": 0,
"selected": false,
"text": "<p>Since the question asked for a non-C way, here's a Scheme implementation, cheerfully plagiarised from <a href=\"http://people.csail.mit.edu/jaffer/SLIB\" rel=\"nofollow noreferrer\">SLIB</a>:</p>\n\n<pre><code>(define (bit-reverse k n)\n (do ((m (if (negative? n) (lognot n) n) (arithmetic-shift m -1))\n (k (+ -1 k) (+ -1 k))\n (rvs 0 (logior (arithmetic-shift rvs 1) (logand 1 m))))\n ((negative? k) (if (negative? n) (lognot rvs) rvs))))\n\n(define (reverse-bit-field n start end)\n (define width (- end start))\n (let ((mask (lognot (ash -1 width))))\n (define zn (logand mask (arithmetic-shift n (- start))))\n (logior (arithmetic-shift (bit-reverse width zn) start)\n (logand (lognot (ash mask start)) n))))\n</code></pre>\n\n<p>Rewritten as C (for people unfamiliar with Scheme), it'd look something like this (with the understanding that in Scheme, numbers can be arbitrarily big):</p>\n\n<pre><code>int\nbit_reverse(int k, int n)\n{\n int m = n < 0 ? ~n : n;\n int rvs = 0;\n while (--k >= 0) {\n rvs = (rvs << 1) | (m & 1);\n m >>= 1;\n }\n return n < 0 ? ~rvs : rvs;\n}\n\nint\nreverse_bit_field(int n, int start, int end)\n{\n int width = end - start;\n int mask = ~(-1 << width);\n int zn = mask & (n >> start);\n return (bit_reverse(width, zn) << start) | (~(mask << start) & n);\n}\n</code></pre>\n"
},
{
"answer_id": 10563,
"author": "C. K. Young",
"author_id": 13,
"author_profile": "https://Stackoverflow.com/users/13",
"pm_score": 2,
"selected": false,
"text": "<p>And here's a version directly cut and pasted from <a href=\"http://openjdk.java.net/\" rel=\"nofollow noreferrer\">OpenJDK</a>, which is interesting because it involves no loop. On the other hand, unlike the Scheme version I posted, this version only works for 32-bit and 64-bit numbers. :-)</p>\n\n<p>32-bit version:</p>\n\n<pre><code>public static int reverse(int i) {\n // HD, Figure 7-1\n i = (i & 0x55555555) << 1 | (i >>> 1) & 0x55555555;\n i = (i & 0x33333333) << 2 | (i >>> 2) & 0x33333333;\n i = (i & 0x0f0f0f0f) << 4 | (i >>> 4) & 0x0f0f0f0f;\n i = (i << 24) | ((i & 0xff00) << 8) |\n ((i >>> 8) & 0xff00) | (i >>> 24);\n return i;\n}\n</code></pre>\n\n<p>64-bit version:</p>\n\n<pre><code>public static long reverse(long i) {\n // HD, Figure 7-1\n i = (i & 0x5555555555555555L) << 1 | (i >>> 1) & 0x5555555555555555L;\n i = (i & 0x3333333333333333L) << 2 | (i >>> 2) & 0x3333333333333333L;\n i = (i & 0x0f0f0f0f0f0f0f0fL) << 4 | (i >>> 4) & 0x0f0f0f0f0f0f0f0fL;\n i = (i & 0x00ff00ff00ff00ffL) << 8 | (i >>> 8) & 0x00ff00ff00ff00ffL;\n i = (i << 48) | ((i & 0xffff0000L) << 16) |\n ((i >>> 16) & 0xffff0000L) | (i >>> 48);\n return i;\n}\n</code></pre>\n"
},
{
"answer_id": 11412,
"author": "andrewrk",
"author_id": 432,
"author_profile": "https://Stackoverflow.com/users/432",
"pm_score": 2,
"selected": false,
"text": "<blockquote>\n <p>I'm probably misremembering, but I\n thought that Joel's question was about\n counting the \"on\" bits rather than\n reversing them.</p>\n</blockquote>\n\n<p>Here you go:</p>\n\n<pre><code>#include <stdio.h>\n\nint countBits(unsigned char byte);\n\nint main(){\n FILE* out = fopen( \"bitcount.c\" ,\"w\");\n\n int i;\n fprintf(out, \"#include <stdio.h>\\n#include <stdlib.h>\\n#include <time.h>\\n\\n\");\n\n fprintf(out, \"int bitcount[256] = {\");\n for(i=0;i<256;i++){\n fprintf(out, \"%i\", countBits((unsigned char)i));\n if( i < 255 ) fprintf(out, \", \");\n }\n fprintf(out, \"};\\n\\n\");\n\n fprintf(out, \"int main(){\\n\");\n\n fprintf(out, \"srand ( time(NULL) );\\n\");\n fprintf(out, \"\\tint num = rand() %% 256;\\n\");\n fprintf(out, \"\\tprintf(\\\"The byte %%i has %%i bits set to ON.\\\\n\\\", num, bitcount[num]);\\n\");\n\n fprintf(out, \"\\treturn 0;\\n\");\n fprintf(out, \"}\\n\");\n fclose(out);\n\n return 0;\n}\n\nint countBits(unsigned char byte){\n unsigned char mask = 1;\n int count = 0;\n while(mask){\n if( mask&byte ) count++;\n mask <<= 1;\n }\n return count;\n}\n</code></pre>\n"
},
{
"answer_id": 124792,
"author": "ja.",
"author_id": 15467,
"author_profile": "https://Stackoverflow.com/users/15467",
"pm_score": 1,
"selected": false,
"text": "<p>Here's the obligatory Haskell soln for complementing the bits, it uses the library function, complement:</p>\n\n<pre><code>import Data.Bits\nimport Data.Int\n\ni = 123::Int\ni32 = 123::Int32\ni64 = 123::Int64\nvar2 = 123::Integer\n\ntest1 = sho i\ntest2 = sho i32\ntest3 = sho i64\ntest4 = sho var2 -- Exception\n\nsho i = putStrLn $ showBits i ++ \"\\n\" ++ (showBits $complement i)\nshowBits v = concatMap f (showBits2 v) where\n f False = \"0\"\n f True = \"1\"\nshowBits2 v = map (testBit v) [0..(bitSize v - 1)]\n</code></pre>\n"
},
{
"answer_id": 1282737,
"author": "Brad Ackerman",
"author_id": 113222,
"author_profile": "https://Stackoverflow.com/users/113222",
"pm_score": 1,
"selected": false,
"text": "<p>I'd modify palmsey's second example, eliminating a bug and eliminating the <code>eval</code>:</p>\n\n<pre><code>n = 0b11001100\nn.to_s(2).rjust(8, '0').reverse.to_i(2)\n</code></pre>\n\n<p>The <code>rjust</code> is important if the number to be bitwise-reversed is a fixed-length bit field -- without it, the reverse of <code>0b00101010</code> would be <code>0b10101</code> rather than the correct <code>0b01010100</code>. (Obviously, the 8 should be replaced with the length in question.) I just got tripped up by this one.</p>\n"
},
{
"answer_id": 1282817,
"author": "Jason",
"author_id": 100902,
"author_profile": "https://Stackoverflow.com/users/100902",
"pm_score": 1,
"selected": false,
"text": "<p>If the question means to flip all the bits, and you aren't allowed to use C-like operators such as XOR and NOT, then this will work:</p>\n\n<pre><code>bFlipped = -1 - bInput;\n</code></pre>\n"
},
{
"answer_id": 1282858,
"author": "GManNickG",
"author_id": 87234,
"author_profile": "https://Stackoverflow.com/users/87234",
"pm_score": 4,
"selected": false,
"text": "<p>I claim trick question. :) Reversing all bits means a flip-flop, but only the bits that are on clearly means:</p>\n\n<pre><code>return 0;\n</code></pre>\n"
},
{
"answer_id": 1282893,
"author": "tsilb",
"author_id": 11112,
"author_profile": "https://Stackoverflow.com/users/11112",
"pm_score": 2,
"selected": false,
"text": "<p>pseudo code..</p>\n\n<pre><code>while (Read())\n Write(0);\n</code></pre>\n"
},
{
"answer_id": 1282970,
"author": "Matthew Iselin",
"author_id": 118364,
"author_profile": "https://Stackoverflow.com/users/118364",
"pm_score": 1,
"selected": false,
"text": "<blockquote>\n <p>Asking here so you can show me how to do in a <strong>Non C way</strong> (if possible)</p>\n</blockquote>\n\n<p>Say you have the number 10101010. To change 1s to 0s (and vice versa) you just use XOR:</p>\n\n<pre><code> 10101010\n^11111111\n --------\n 01010101\n</code></pre>\n\n<p>Doing it by hand is about as \"Non C\" as you'll get.</p>\n\n<p>However from the wording of the question it really sounds like it's <em>only</em> turning off \"ON\" bits... In which case the answer is zero (as has already been mentioned) (unless of course the question is actually asking to swap the order of the bits).</p>\n"
},
{
"answer_id": 17915867,
"author": "Vineet Setia",
"author_id": 2613413,
"author_profile": "https://Stackoverflow.com/users/2613413",
"pm_score": 0,
"selected": false,
"text": "<p>Reversing the bits.\nFor example we have a number represented by 01101011 . Now if we reverse the bits then this number will become 11010110. Now to achieve this you should first know how to do swap two bits in a number.\nSwapping two bits in a number:-\nXOR both the bits with one and see if results are different. If they are not then both the bits are same otherwise XOR both the bits with XOR and save it in its original number;\nNow for reversing the number \nFOR I less than Numberofbits/2\n swap(Number,I,NumberOfBits-1-I);</p>\n"
}
] | 2008/08/13 | [
"https://Stackoverflow.com/questions/9750",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/123/"
] | I was reading Joel's book where he was suggesting as interview question:
>
> Write a program to reverse the "ON" bits in a given byte.
>
>
>
I only can think of a solution using C.
Asking here so you can show me how to do in a Non C way (if possible) | >
> What specifically does that question mean?
>
>
>
Good question. If reversing the "ON" bits means reversing only the bits that are "ON", then you will always get 0, no matter what the input is. If it means reversing *all* the bits, i.e. changing all 1s to 0s and all 0s to 1s, which is how I initially read it, then that's just a bitwise NOT, or complement. C-based languages have a complement operator, `~`, that does this. For example:
```
unsigned char b = 102; /* 0x66, 01100110 */
unsigned char reverse = ~b; /* 0x99, 10011001 */
``` |
9,805 | <p>I am currently writing a small calendar in ASP.Net C#. Currently to produce the rows of the weeks I do the following for loop:</p>
<pre><code>var iWeeks = 6;
for (int w = 0; w < iWeeks; w++) {
</code></pre>
<p>This works fine, however, some month will only have 5 weeks and in some rare cases, 4.</p>
<p>How can I calculate the number of rows that will be required for a particular month?</p>
<p>This is an example of what I am creating:</p>
<p><img src="https://i.stack.imgur.com/NkxN7.png" alt="enter image description here"></p>
<p>As you can see for the above month, there are only 5 rows required, however. Take the this month (August 2008) which started on a Saturday and ends on a Monday on the 6th Week/Row.</p>
<p><strong><em>Image found on google</em></strong></p>
<hr>
<p>This is an example of what I am creating:</p>
<p><img src="https://i.stack.imgur.com/NkxN7.png" alt="enter image description here"></p>
<p>As you can see for the above month, there are only 5 rows required, however. Take the this month (August 2008) which started on a Saturday and ends on a Monday on the 6th Week/Row.</p>
<p><strong><em>Image found on google</em></strong></p>
| [
{
"answer_id": 9806,
"author": "Lasse V. Karlsen",
"author_id": 267,
"author_profile": "https://Stackoverflow.com/users/267",
"pm_score": 0,
"selected": false,
"text": "<p>How about checking which week the first and last days will be in?</p>\n"
},
{
"answer_id": 9810,
"author": "kokos",
"author_id": 1065,
"author_profile": "https://Stackoverflow.com/users/1065",
"pm_score": 0,
"selected": false,
"text": "<p>The months in the Julian / Gregorian calendar have the same number of days each year, except February who can have 28 or 29 days depending on the leapness of the year. You can find the number of days in the Description section at <a href=\"http://en.wikipedia.org/wiki/Gregorian_calendar\" rel=\"nofollow noreferrer\">http://en.wikipedia.org/wiki/Gregorian_calendar</a>.</p>\n\n<p>As @darkdog mentioned you have DateTime.DaysInMonth. Just do this:</p>\n\n<pre><code>var days = DateTime.DaysInMonth(year, month) + \n WhatDayOfWeekTheMonthStarts(year, month); \nint rows = (days / 7); \nif (0 < days % 7) \n{ \n ++rows;\n} \n</code></pre>\n\n<p>Take into consideration the fact that for globalization / localization purposes, some parts of the world use different calendars / methods of organization of the year.</p>\n"
},
{
"answer_id": 9815,
"author": "darkdog",
"author_id": 1094,
"author_profile": "https://Stackoverflow.com/users/1094",
"pm_score": 0,
"selected": false,
"text": "<p>Try this,</p>\n\n<pre><code>DateTime.DaysInMonth\n</code></pre>\n"
},
{
"answer_id": 9821,
"author": "Lasse V. Karlsen",
"author_id": 267,
"author_profile": "https://Stackoverflow.com/users/267",
"pm_score": 2,
"selected": false,
"text": "<p>Well, it depends on the culture you're using, but let's assume you can use Thread.CurrentThread.CurrentCulture, then the code to get the week of today would be:</p>\n\n<pre><code>Culture culture = Thread.CurrentThread.CurrentCulture;\nCalendar cal = culture.Calendar;\nInt32 week = cal.GetWeekOfYear(DateTime.Today,\n culture.DateTimeFormat.CalendarWeekRule,\n culture.DateTimeFormat.FirstDayOfWeek);\n</code></pre>\n"
},
{
"answer_id": 9822,
"author": "Biri",
"author_id": 968,
"author_profile": "https://Stackoverflow.com/users/968",
"pm_score": 0,
"selected": false,
"text": "<p>Check <a href=\"https://learn.microsoft.com/en-in/dotnet/api/system.globalization.calendar.getweekofyear\" rel=\"nofollow noreferrer\">Calendar.GetWeekOfYear</a>. It should do the trick.</p>\n<p>There is a problem with it, it does not follow the 4 day rule by ISO 8601, but otherwise it is neat.</p>\n"
},
{
"answer_id": 9827,
"author": "darkdog",
"author_id": 1094,
"author_profile": "https://Stackoverflow.com/users/1094",
"pm_score": 0,
"selected": false,
"text": "<p>you can get the days of a month by using DateTime.DaysInMonth(int WhichYear,int WhichMonth);</p>\n"
},
{
"answer_id": 9830,
"author": "Lasse V. Karlsen",
"author_id": 267,
"author_profile": "https://Stackoverflow.com/users/267",
"pm_score": 0,
"selected": false,
"text": "<p>The problem isn't the number of days in the month, it's how many weeks it spans over.</p>\n\n<p>February in a non-leap year will have 28 days, and if the first day of the month is a monday, february will span exactly 4 week numbers.</p>\n\n<p>However, if the first day of the month is a tuesday, or any other day of the week, february will span 5 week numbers.</p>\n\n<p>A 31 day month can span 5 or 6 weeks the same way. If the month starts on a monday, the 31 days gives you 5 week numbers. If the month starts on saturday or sunday, it will span 6 week numbers.</p>\n\n<p>So the right way to obtain this number is to find the week number of the first and last days of the month.</p>\n\n<hr>\n\n<p><strong>Edit #1</strong>: Here's how to calculate the number of weeks a given month spans:\n<strong>Edit #2</strong>: Fixed bugs in code</p>\n\n<pre><code>public static Int32 GetWeekForDateCurrentCulture(DateTime dt)\n{\n CultureInfo culture = Thread.CurrentThread.CurrentCulture;\n Calendar cal = culture.Calendar;\n return cal.GetWeekOfYear(dt,\n culture.DateTimeFormat.CalendarWeekRule,\n culture.DateTimeFormat.FirstDayOfWeek);\n}\n\npublic static Int32 GetWeekSpanCountForMonth(DateTime dt)\n{\n DateTime firstDayInMonth = new DateTime(dt.Year, dt.Month, 1);\n DateTime lastDayInMonth = firstDayInMonth.AddMonths(1).AddDays(-1);\n return\n GetWeekForDateCurrentCulture(lastDayInMonth)\n - GetWeekForDateCurrentCulture(firstDayInMonth)\n + 1;\n}\n</code></pre>\n"
},
{
"answer_id": 9844,
"author": "DevelopingChris",
"author_id": 1220,
"author_profile": "https://Stackoverflow.com/users/1220",
"pm_score": 0,
"selected": false,
"text": "<p>First Find out which weekday the first day of the month is in. Just new up a datetime with the first day, always 1, and the year and month in question, there is a day of week property on it.</p>\n\n<p>Then from here, you can use the number of days in the month, <code>DateTime.DaysInMonth</code>, in order to determine how many weeks when you divide by seven and then add the number of days from 1 that your first day falls on. For instance,</p>\n\n<pre><code>public static int RowsForMonth(int month, int year)\n{\n DateTime first = new DateTime(year, month, 1);\n\n //number of days pushed beyond monday this one sits\n int offset = ((int)first.DayOfWeek) - 1;\n\n int actualdays = DateTime.DaysInMonth(month, year) + offset;\n\n decimal rows = (actualdays / 7);\n if ((rows - ((int)rows)) > .1)\n {\n rows++;\n }\n return rows;\n}\n</code></pre>\n"
},
{
"answer_id": 9851,
"author": "Serhat Ozgel",
"author_id": 31505,
"author_profile": "https://Stackoverflow.com/users/31505",
"pm_score": 4,
"selected": true,
"text": "<p>Here is the method that does it:</p>\n\n<pre><code>public int GetWeekRows(int year, int month)\n{\n DateTime firstDayOfMonth = new DateTime(year, month, 1);\n DateTime lastDayOfMonth = new DateTime(year, month, 1).AddMonths(1).AddDays(-1);\n System.Globalization.Calendar calendar = System.Threading.Thread.CurrentThread.CurrentCulture.Calendar;\n int lastWeek = calendar.GetWeekOfYear(lastDayOfMonth, System.Globalization.CalendarWeekRule.FirstFourDayWeek, DayOfWeek.Monday);\n int firstWeek = calendar.GetWeekOfYear(firstDayOfMonth, System.Globalization.CalendarWeekRule.FirstFourDayWeek, DayOfWeek.Monday);\n return lastWeek - firstWeek + 1;\n}\n</code></pre>\n\n<p>You can customize the calendar week rule by modifying the System.Globalization.CalendarWeekRule.FirstFourDayWeek part. I hope the code is self explanatory.</p>\n"
}
] | 2008/08/13 | [
"https://Stackoverflow.com/questions/9805",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/383/"
] | I am currently writing a small calendar in ASP.Net C#. Currently to produce the rows of the weeks I do the following for loop:
```
var iWeeks = 6;
for (int w = 0; w < iWeeks; w++) {
```
This works fine, however, some month will only have 5 weeks and in some rare cases, 4.
How can I calculate the number of rows that will be required for a particular month?
This is an example of what I am creating:

As you can see for the above month, there are only 5 rows required, however. Take the this month (August 2008) which started on a Saturday and ends on a Monday on the 6th Week/Row.
***Image found on google***
---
This is an example of what I am creating:

As you can see for the above month, there are only 5 rows required, however. Take the this month (August 2008) which started on a Saturday and ends on a Monday on the 6th Week/Row.
***Image found on google*** | Here is the method that does it:
```
public int GetWeekRows(int year, int month)
{
DateTime firstDayOfMonth = new DateTime(year, month, 1);
DateTime lastDayOfMonth = new DateTime(year, month, 1).AddMonths(1).AddDays(-1);
System.Globalization.Calendar calendar = System.Threading.Thread.CurrentThread.CurrentCulture.Calendar;
int lastWeek = calendar.GetWeekOfYear(lastDayOfMonth, System.Globalization.CalendarWeekRule.FirstFourDayWeek, DayOfWeek.Monday);
int firstWeek = calendar.GetWeekOfYear(firstDayOfMonth, System.Globalization.CalendarWeekRule.FirstFourDayWeek, DayOfWeek.Monday);
return lastWeek - firstWeek + 1;
}
```
You can customize the calendar week rule by modifying the System.Globalization.CalendarWeekRule.FirstFourDayWeek part. I hope the code is self explanatory. |
9,831 | <p>I've asked this question to the forums on the Mootools website and one person said that my class selection was corrupted before an admin came along and changed my post status to invalid. Needless to say this did not help much. I then posted to a google group for Mootools with no response. My question is why doesn't the 'enter', 'leave', 'drop' events fire for my '.drop' elements? The events for the .drag elements are working.</p>
<pre><code><title>Untitled Page</title>
<script type="text/javascript" src="/SDI/includes/mootools-1.2.js"></script>
<script type="text/javascript" src="/SDI/includes/mootools-1.2-more.js"></script>
<script type="text/javascript" charset="utf-8">
window.addEvent('domready', function() {
var fx = [];
$$('#draggables div').each(function(drag){
new Drag.Move(drag, {
droppables: $$('#droppables div'),
onDrop: function(element, droppable){
if(!droppable) {
}
else {
element.setStyle('background-color', '#1d1d20');
}
element.dispose();
},
onEnter: function(element, droppable){
element.setStyle('background-color', '#ffffff');
},
onLeave: function(element, droppable){
element.setStyle('background-color', '#000000');
}
});
});
$$('#droppables div').each(function(drop, index){
drop.addEvents({
'enter': function(el, obj){
drop.setStyle('background-color', '#78ba91');
},
'leave': function(el, obj){
drop.setStyle('background-color', '#1d1d20');
},
'drop': function(el, obj){
el.remove();
}
});
});
});
</script>
<form id="form1" runat="server">
<div>
<div id="draggables">
<div class="drag"></div>
<div class="drag"></div>
<div class="drag"></div>
<div class="drag"></div>
<div class="drag"></div>
<div class="drag"></div>
<div class="drag"></div>
<div class="drag"></div>
<div class="drag"></div>
<div class="drag"></div>
</div>
<div id="droppables">
<div class="drop"></div>
<div class="drop"></div>
<div class="drop"></div>
<div class="drop"></div>
<div class="drop"></div>
<div class="drop"></div>
</div>
</div>
</form>
</code></pre>
| [
{
"answer_id": 12910,
"author": "maxsilver",
"author_id": 1477,
"author_profile": "https://Stackoverflow.com/users/1477",
"pm_score": 3,
"selected": true,
"text": "<p>Ok, it looks like there are a couple of issues here. As far as I can tell, there is no such thing as a \"droppable\" in mootools. This means your events like 'enter', 'leave' and 'drop' won't work. (These are events on the drag object)</p>\n\n<p>If you change those names to events that elements in mootools have (as in, DOM events) your code works perfectly. For instance, if you change 'enter' and 'leave' to 'mouseover' and 'mouseout', your events fire with no problem. (Opera 9.51 on Windows Vista)</p>\n\n<p>This appears to be the revelant line in the documentation for this, which stats to use DOM events.</p>\n\n<p><a href=\"http://docs.mootools.net/Element/Element.Event#Element:addEvents\" rel=\"nofollow noreferrer\">http://docs.mootools.net/Element/Element.Event#Element:addEvents</a></p>\n\n<p>Also, on that page, is a link to the events that regular elements can have</p>\n\n<p><a href=\"http://www.w3schools.com/html/html_eventattributes.asp\" rel=\"nofollow noreferrer\">http://www.w3schools.com/html/html_eventattributes.asp</a></p>\n\n<p>However, <a href=\"http://mootools-users.660466.n2.nabble.com/Drag-and-drop-problem-I-m-having-td686391.html\" rel=\"nofollow noreferrer\">the advice \"TG in SD\" gave you in the nabble forums</a> is probably best. If you can, don't bother using these events. Put whatever it is you need to do in the draggable object, and save yourself all this hassle.</p>\n"
},
{
"answer_id": 9935722,
"author": "Neil",
"author_id": 1302175,
"author_profile": "https://Stackoverflow.com/users/1302175",
"pm_score": 1,
"selected": false,
"text": "<p>According to <a href=\"http://mootools.net/docs/more/Drag/Drag.Move\" rel=\"nofollow\">Mootools Docs</a>, \"<code>droppables</code>\" is one of the options expected by the <code>Drag.Move</code> class. In fact, this is the array of elements that interact with the element when it fires the \"<code>drop</code>,\" \"<code>enter</code>,\" and \"<code>leave</code>\" event.</p>\n"
}
] | 2008/08/13 | [
"https://Stackoverflow.com/questions/9831",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1491425/"
] | I've asked this question to the forums on the Mootools website and one person said that my class selection was corrupted before an admin came along and changed my post status to invalid. Needless to say this did not help much. I then posted to a google group for Mootools with no response. My question is why doesn't the 'enter', 'leave', 'drop' events fire for my '.drop' elements? The events for the .drag elements are working.
```
<title>Untitled Page</title>
<script type="text/javascript" src="/SDI/includes/mootools-1.2.js"></script>
<script type="text/javascript" src="/SDI/includes/mootools-1.2-more.js"></script>
<script type="text/javascript" charset="utf-8">
window.addEvent('domready', function() {
var fx = [];
$$('#draggables div').each(function(drag){
new Drag.Move(drag, {
droppables: $$('#droppables div'),
onDrop: function(element, droppable){
if(!droppable) {
}
else {
element.setStyle('background-color', '#1d1d20');
}
element.dispose();
},
onEnter: function(element, droppable){
element.setStyle('background-color', '#ffffff');
},
onLeave: function(element, droppable){
element.setStyle('background-color', '#000000');
}
});
});
$$('#droppables div').each(function(drop, index){
drop.addEvents({
'enter': function(el, obj){
drop.setStyle('background-color', '#78ba91');
},
'leave': function(el, obj){
drop.setStyle('background-color', '#1d1d20');
},
'drop': function(el, obj){
el.remove();
}
});
});
});
</script>
<form id="form1" runat="server">
<div>
<div id="draggables">
<div class="drag"></div>
<div class="drag"></div>
<div class="drag"></div>
<div class="drag"></div>
<div class="drag"></div>
<div class="drag"></div>
<div class="drag"></div>
<div class="drag"></div>
<div class="drag"></div>
<div class="drag"></div>
</div>
<div id="droppables">
<div class="drop"></div>
<div class="drop"></div>
<div class="drop"></div>
<div class="drop"></div>
<div class="drop"></div>
<div class="drop"></div>
</div>
</div>
</form>
``` | Ok, it looks like there are a couple of issues here. As far as I can tell, there is no such thing as a "droppable" in mootools. This means your events like 'enter', 'leave' and 'drop' won't work. (These are events on the drag object)
If you change those names to events that elements in mootools have (as in, DOM events) your code works perfectly. For instance, if you change 'enter' and 'leave' to 'mouseover' and 'mouseout', your events fire with no problem. (Opera 9.51 on Windows Vista)
This appears to be the revelant line in the documentation for this, which stats to use DOM events.
<http://docs.mootools.net/Element/Element.Event#Element:addEvents>
Also, on that page, is a link to the events that regular elements can have
<http://www.w3schools.com/html/html_eventattributes.asp>
However, [the advice "TG in SD" gave you in the nabble forums](http://mootools-users.660466.n2.nabble.com/Drag-and-drop-problem-I-m-having-td686391.html) is probably best. If you can, don't bother using these events. Put whatever it is you need to do in the draggable object, and save yourself all this hassle. |
9,882 | <p>I am working on a project that requires the parsing of log files. I am looking for a fast algorithm that would take groups messages like this:</p>
<blockquote>
<p>The temperature at P1 is 35F.</p>
<p>The temperature at P1 is 40F.</p>
<p>The temperature at P3 is 35F.</p>
<p>Logger stopped.</p>
<p>Logger started.</p>
<p>The temperature at P1 is 40F.</p>
</blockquote>
<p>and puts out something in the form of a printf():</p>
<pre><code>"The temperature at P%d is %dF.", Int1, Int2"
{(1,35), (1, 40), (3, 35), (1,40)}
</code></pre>
<p>The algorithm needs to be generic enough to recognize almost any data load in message groups.</p>
<p>I tried searching for this kind of technology, but I don't even know the correct terms to search for.</p>
| [
{
"answer_id": 9886,
"author": "John Downey",
"author_id": 200,
"author_profile": "https://Stackoverflow.com/users/200",
"pm_score": 4,
"selected": false,
"text": "<p>I think you might be overlooking and missed fscanf() and sscanf(). Which are the opposite of fprintf() and sprintf().</p>\n"
},
{
"answer_id": 9980,
"author": "Niels",
"author_id": 930,
"author_profile": "https://Stackoverflow.com/users/930",
"pm_score": 2,
"selected": false,
"text": "<p>It depends on what you are trying to do, if your goal is to quickly generate sprintf() input, this works. If you are trying to parse data, maybe regular expressions would do too.. </p>\n"
},
{
"answer_id": 10576,
"author": "C. K. Young",
"author_id": 13,
"author_profile": "https://Stackoverflow.com/users/13",
"pm_score": 0,
"selected": false,
"text": "<p>@John: I think that the question relates to an algorithm that actually recognises patterns in log files and automatically \"guesses\" appropriate format strings and data for it. The <code>*scanf</code> family can't do that on its own, it can only be of help once the patterns have been recognised in the first place.</p>\n"
},
{
"answer_id": 10589,
"author": "Derek Park",
"author_id": 872,
"author_profile": "https://Stackoverflow.com/users/872",
"pm_score": 1,
"selected": false,
"text": "<p>You're not going to find a tool that can simply take arbitrary input, guess what data you want from it, and produce the output you want. That sounds like strong AI to me.</p>\n\n<p>Producing something like this, even just to recognize numbers, gets really hairy. For example is \"123.456\" one number or two? How about this \"123,456\"? Is \"35F\" a decimal number and an 'F' or is it the hex value 0x35F? You're going to have to build something that will parse in the way you need. You can do this with regular expressions, or you can do it with <code>sscanf</code>, or you can do it some other way, but you're going to have to write something custom.</p>\n\n<p>However, with basic regular expressions, you can do this yourself. It won't be magic, but it's not that much work. Something like this will parse the lines you're interested in and consolidate them (Perl):</p>\n\n<pre><code>my @vals = ();\nwhile (defined(my $line = <>))\n{\n if ($line =~ /The temperature at P(\\d*) is (\\d*)F./)\n {\n push(@vals, \"($1,$2)\");\n }\n}\nprint \"The temperature at P%d is %dF. {\";\nfor (my $i = 0; $i < @vals; $i++)\n{\n print $vals[$i];\n if ($i < @vals - 1)\n {\n print \",\";\n }\n}\nprint \"}\\n\";\n</code></pre>\n\n<p>The output from this isL</p>\n\n<pre><code>The temperature at P%d is %dF. {(1,35),(1,40),(3,35),(1,40)}\n</code></pre>\n\n<p>You could do something similar for each type of line you need to parse. You could even read these regular expressions from a file, instead of custom coding each one.</p>\n"
},
{
"answer_id": 12321,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 2,
"selected": false,
"text": "<p>Thanks for all the great suggestions.\nChris, is right. I am looking for a generic solution for normalizing any kind of text. The solution of the problem boils down to dynmamically finding patterns in two or more similar strings. \nAlmost like predicting the next element in a set, based on the previous two:</p>\n\n<p>1: Everest is 30000 feet high</p>\n\n<p>2: K2 is 28000 feet high</p>\n\n<p>=> What is the pattern?\n=> Answer:</p>\n\n<p>[name] is [number] feet high</p>\n\n<p>Now the text file can have millions of lines and thousands of patterns. I would like to parse the files very, very fast, find the patterns and collect the data sets that are associated with each pattern.</p>\n\n<p>I thought about creating some high level semantic hashes to represent the patterns in the message strings.\nI would use a tokenizer and give each of the tokens types a specific \"weight\". \nThen I would group the hashes and rate their similarity. Once the grouping is done I would collect the data sets.</p>\n\n<p>I was hoping, that I didn't have to reinvent the wheel and could reuse something that is already out there.</p>\n\n<p>Klaus</p>\n"
},
{
"answer_id": 12379,
"author": "Vincent Robert",
"author_id": 268,
"author_profile": "https://Stackoverflow.com/users/268",
"pm_score": 1,
"selected": false,
"text": "<p>I don't know of any specific tool to do that. What I did when I had a similar problem to solve was trying to guess regular expressions to match lines.</p>\n\n<p>I then processed the files and displayed only the unmatched lines. If a line is unmatched, it means that the pattern is wrong and should be tweaked or another pattern should be added.</p>\n\n<p>After around an hour of work, I succeeded in finding the ~20 patterns to match 10000+ lines.</p>\n\n<p>In your case, you can first \"guess\" that one pattern is <code>\"The temperature at P[1-3] is [0-9]{2}F.\"</code>. If you reprocess the file removing any matched line, it leaves \"only\":</p>\n\n<blockquote>\n <p>Logger stopped. </p>\n \n <p>Logger started.</p>\n</blockquote>\n\n<p>Which you can then match with <code>\"Logger (.+).\"</code>.</p>\n\n<p>You can then refine the patterns and find new ones to match your whole log.</p>\n"
},
{
"answer_id": 12466,
"author": "jcsalterego",
"author_id": 1416,
"author_profile": "https://Stackoverflow.com/users/1416",
"pm_score": 4,
"selected": true,
"text": "<p>Overview:</p>\n\n<p>A <strong>naïve!!</strong> algorithm keeps track of the frequency of words in a per-column manner, where one can assume that each line can be separated into columns with a delimiter.</p>\n\n<p>Example input:</p>\n\n<blockquote>\n <p>The dog jumped over the moon<br>\n The cat jumped over the moon<br>\n The moon jumped over the moon<br>\n The car jumped over the moon </p>\n</blockquote>\n\n<p>Frequencies:</p>\n\n<pre><code>Column 1: {The: 4}\nColumn 2: {car: 1, cat: 1, dog: 1, moon: 1}\nColumn 3: {jumped: 4}\nColumn 4: {over: 4}\nColumn 5: {the: 4}\nColumn 6: {moon: 4}\n</code></pre>\n\n<p>We could partition these frequency lists further by grouping based on the total number of fields, but in this simple and convenient example, we are only working with a fixed number of fields (6).</p>\n\n<p>The next step is to iterate through lines which generated these frequency lists, so let's take the first example.</p>\n\n<ol>\n<li><strong>The</strong>: meets some hand-wavy criteria and the algorithm decides it must be static.</li>\n<li><strong>dog</strong>: doesn't appear to be static based on the rest of the frequency list, and thus it must be dynamic as opposed to static text. We loop through a few pre-defined regular expressions and come up with <code>/[a-z]+/i</code>.</li>\n<li><strong>over</strong>: same deal as #1; it's static, so leave as is.</li>\n<li><strong>the</strong>: same deal as #1; it's static, so leave as is.</li>\n<li><strong>moon</strong>: same deal as #1; it's static, so leave as is.</li>\n</ol>\n\n<p>Thus, just from going over the first line we can put together the following regular expression:</p>\n\n<pre><code>/The ([a-z]+?) jumps over the moon/\n</code></pre>\n\n<p>Considerations:</p>\n\n<ul>\n<li><p>Obviously one can choose to scan part or the whole document for the first pass, as long as one is confident the frequency lists will be a sufficient sampling of the entire data.</p></li>\n<li><p>False positives may creep into the results, and it will be up to the filtering algorithm (hand-waving) to provide the best threshold between static and dynamic fields, or some human post-processing.</p></li>\n<li><p>The overall idea is probably a good one, but the actual implementation will definitely weigh in on the speed and efficiency of this algorithm.</p></li>\n</ul>\n"
},
{
"answer_id": 12558,
"author": "Anders Eurenius",
"author_id": 1421,
"author_profile": "https://Stackoverflow.com/users/1421",
"pm_score": 0,
"selected": false,
"text": "<p>@Derek Park: Well, even a strong AI couldn't be sure it had the right answer.</p>\n\n<p>Perhaps some compression-like mechanism could be used:</p>\n\n<ol start=\"2\">\n<li>Find large, frequent substrings</li>\n<li>Find large, frequent substring patterns. (i.e. [pattern:1] [junk] [pattern:2])</li>\n</ol>\n\n<p>Another item to consider might be to group lines by <a href=\"http://en.wikipedia.org/wiki/Edit_distance\" rel=\"nofollow noreferrer\">edit-distance</a>. Grouping similar lines should split the problem into one-pattern-per-group chunks.</p>\n\n<p>Actually, if you manage to write this, <em>let the whole world know</em>, I think a lot of us would like this tool!</p>\n"
},
{
"answer_id": 12566,
"author": "Derek Park",
"author_id": 872,
"author_profile": "https://Stackoverflow.com/users/872",
"pm_score": 0,
"selected": false,
"text": "<p>@Anders</p>\n\n<blockquote>\n <p>Well, even a strong AI couldn't be sure it had the right answer.</p>\n</blockquote>\n\n<p>I was thinking that sufficiently strong AI could <em>usually</em> figure out the right answer from the context. e.g. Strong AI could recognize that \"35F\" in this context is a temperature and not a hex number. There are definitely cases where even strong AI would be unable to answer. Those are the same cases where a human would be unable to answer, though (assuming <em>very</em> strong AI).</p>\n\n<p>Of course, it doesn't really matter, since we don't have strong AI. :)</p>\n"
},
{
"answer_id": 119150,
"author": "pngaz",
"author_id": 10972,
"author_profile": "https://Stackoverflow.com/users/10972",
"pm_score": 0,
"selected": false,
"text": "<p><a href=\"http://www.logparser.com\" rel=\"nofollow noreferrer\">http://www.logparser.com</a> forwards to an IIS forum which seems fairly active. This is the official site for Gabriele Giuseppini's \"Log Parser Toolkit\". While I have never actually used this tool, I did pick up a cheap copy of the book from Amazon Marketplace - today a copy is as low as $16. Nothing beats a dead-tree-interface for just flipping through pages.<p>\nGlancing at this forum, I had not previously heard about the \"New GUI tool for MS Log Parser, Log Parser Lizard\" at <a href=\"http://www.lizardl.com/\" rel=\"nofollow noreferrer\">http://www.lizardl.com/</a>.<p>\nThe key issue of course is the complexity of your GRAMMAR. To use any kind of log-parser as the term is commonly used, you need to know exactly what you're scanning for, you can write a BNF for it. Many years ago I took a course based on Aho-and-Ullman's \"Dragon Book\", and the thoroughly understood LALR technology can give you optimal speed, provided of course that you have that CFG.<p>\nOn the other hand it does seem you're possibly reaching for something AI-like, which is a different order of complexity entirely.</p>\n"
}
] | 2008/08/13 | [
"https://Stackoverflow.com/questions/9882",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] | I am working on a project that requires the parsing of log files. I am looking for a fast algorithm that would take groups messages like this:
>
> The temperature at P1 is 35F.
>
>
> The temperature at P1 is 40F.
>
>
> The temperature at P3 is 35F.
>
>
> Logger stopped.
>
>
> Logger started.
>
>
> The temperature at P1 is 40F.
>
>
>
and puts out something in the form of a printf():
```
"The temperature at P%d is %dF.", Int1, Int2"
{(1,35), (1, 40), (3, 35), (1,40)}
```
The algorithm needs to be generic enough to recognize almost any data load in message groups.
I tried searching for this kind of technology, but I don't even know the correct terms to search for. | Overview:
A **naïve!!** algorithm keeps track of the frequency of words in a per-column manner, where one can assume that each line can be separated into columns with a delimiter.
Example input:
>
> The dog jumped over the moon
>
> The cat jumped over the moon
>
> The moon jumped over the moon
>
> The car jumped over the moon
>
>
>
Frequencies:
```
Column 1: {The: 4}
Column 2: {car: 1, cat: 1, dog: 1, moon: 1}
Column 3: {jumped: 4}
Column 4: {over: 4}
Column 5: {the: 4}
Column 6: {moon: 4}
```
We could partition these frequency lists further by grouping based on the total number of fields, but in this simple and convenient example, we are only working with a fixed number of fields (6).
The next step is to iterate through lines which generated these frequency lists, so let's take the first example.
1. **The**: meets some hand-wavy criteria and the algorithm decides it must be static.
2. **dog**: doesn't appear to be static based on the rest of the frequency list, and thus it must be dynamic as opposed to static text. We loop through a few pre-defined regular expressions and come up with `/[a-z]+/i`.
3. **over**: same deal as #1; it's static, so leave as is.
4. **the**: same deal as #1; it's static, so leave as is.
5. **moon**: same deal as #1; it's static, so leave as is.
Thus, just from going over the first line we can put together the following regular expression:
```
/The ([a-z]+?) jumps over the moon/
```
Considerations:
* Obviously one can choose to scan part or the whole document for the first pass, as long as one is confident the frequency lists will be a sufficient sampling of the entire data.
* False positives may creep into the results, and it will be up to the filtering algorithm (hand-waving) to provide the best threshold between static and dynamic fields, or some human post-processing.
* The overall idea is probably a good one, but the actual implementation will definitely weigh in on the speed and efficiency of this algorithm. |
9,928 | <p>I am working on a small webapp and I want to use Groovy to write some unit testing for my app. Most of my coding is done on Eclipse and I really want to run all the unit testing with the graphical test runner within Eclipse (I really like the green bar :) )</p>
<p>Sadly, after 4 hours of try-and-error, I'm still not able to setup properly. I tried to use the Eclipse Junit4 test runner to run a Groovy file with method annotated for testing using <code>@Test</code>. But it keeps complaining <code>NoClassDefFoundException</code></p>
<p>Anyone can help? </p>
<p>Here is content of my groovy file, named simpleTest.groovy</p>
<pre><code>import org.junit.Test
import static org.junit.Assert.assertEquals
class simpleTest{
@Test
void trial(){
assertEquals 6, 3+3
}
}
</code></pre>
<p>Anyone can help?</p>
| [
{
"answer_id": 55705,
"author": "Kivus",
"author_id": 5590,
"author_profile": "https://Stackoverflow.com/users/5590",
"pm_score": 0,
"selected": false,
"text": "<p>Unfortunately, the Groovy Eclipse plugin is pretty horrible at giving actual helpful information to let you know what is going wrong with your setup. I'm going to assume you already did the verification to make sure the plugin is actually building your Groovy files (i.e. doing a sample with no dependencies, checking the properly output directory, etc...) After that, it's a lot of really small configuration verification...I've run into problems where the particular \"runner\" I'm using in Eclipse (i.e. in the Run menu) doesn't have the write class name defined there or for some reason my project didn't get the JUnit library dependency properly inserted into it. </p>\n\n<p>Ultimately, it can be a configuration headache, but long term you'll end up saving some time and gaining some cool functionality if you can knock it out...</p>\n"
},
{
"answer_id": 79907,
"author": "Peter Kelley",
"author_id": 14893,
"author_profile": "https://Stackoverflow.com/users/14893",
"pm_score": 1,
"selected": false,
"text": "<p>I have this working in my environment so here is a brief summary of what I have:</p>\n\n<p>In the run dialog under JUnit:</p>\n\n<ul>\n<li><strong>Test Tab:</strong> The test class, this must have already been compiled by the Groovy plugin.</li>\n<li><strong>Classpath:</strong> All of the Jar files from my project as well as the <em>Groovy Libraries</em> library</li>\n</ul>\n\n<p>In Window->Preferences->Java->Build Path</p>\n\n<ul>\n<li><strong>Classpath Variables:</strong> <pre>GROOVY<code>_ECLIPSE</code>_HOME</pre> = the location where the Groovy plugin is installed</li>\n</ul>\n\n<p>That does the trick for me.</p>\n"
},
{
"answer_id": 1215323,
"author": "Robert Munteanu",
"author_id": 112671,
"author_profile": "https://Stackoverflow.com/users/112671",
"pm_score": 2,
"selected": false,
"text": "<p>You might want to give the updated plugin a try, see the <a href=\"http://blog.springsource.com/2009/07/30/a-groovier-eclipse-experience\" rel=\"nofollow noreferrer\">the recent blog post</a> for more details. The theme of this alpha release is <em>providing an optimized edit/save/compile/test experience</em>, which seems to be your exact use case.</p>\n\n<p><img src=\"https://i.stack.imgur.com/0joPq.png\" alt=\"Groovy Eclipse 2.0\"></p>\n"
},
{
"answer_id": 4826104,
"author": "Arun R",
"author_id": 211967,
"author_profile": "https://Stackoverflow.com/users/211967",
"pm_score": 0,
"selected": false,
"text": "<p>I had faced a similar issue and it was the missing package statement that caused me to have problems. Groovy Eclipse plugin did not complain about it but my class was present in a package. I got the noClassDefError when running the file as a JUnit Test.</p>\n\n<p>Adding the package statement to top of class solved this issue.</p>\n"
}
] | 2008/08/13 | [
"https://Stackoverflow.com/questions/9928",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] | I am working on a small webapp and I want to use Groovy to write some unit testing for my app. Most of my coding is done on Eclipse and I really want to run all the unit testing with the graphical test runner within Eclipse (I really like the green bar :) )
Sadly, after 4 hours of try-and-error, I'm still not able to setup properly. I tried to use the Eclipse Junit4 test runner to run a Groovy file with method annotated for testing using `@Test`. But it keeps complaining `NoClassDefFoundException`
Anyone can help?
Here is content of my groovy file, named simpleTest.groovy
```
import org.junit.Test
import static org.junit.Assert.assertEquals
class simpleTest{
@Test
void trial(){
assertEquals 6, 3+3
}
}
```
Anyone can help? | You might want to give the updated plugin a try, see the [the recent blog post](http://blog.springsource.com/2009/07/30/a-groovier-eclipse-experience) for more details. The theme of this alpha release is *providing an optimized edit/save/compile/test experience*, which seems to be your exact use case.
 |
9,938 | <p>I am trying to find a generic way of accessing a set of containers. I have a standard vector and list in addition to another custom list.</p>
<p>The custom list defines an iterator;</p>
<pre><code>class Iterator: public std::iterator<std::forward_iterator_tag, T> {
// ...
}
Iterator begin() {
return (Iterator(root));
}
Iterator end() {
return (Iterator(NULL));
}
</code></pre>
<p>with the appropriate operators overloaded. </p>
<p>Ideally, I would like to do this;</p>
<pre><code>class Foo {
public:
Foo() {
std::list<int> x;
std::vector<int> y;
custom_list<int> z;
iter = x.begin(); // OR
iter = y.begin(); // OR
iter = z.begin();
// ...
};
private:
std::iterator<int> iter;
};
</code></pre>
<p>But obviously these are all iterators of different types. I can assume all the containers are of the same type however.</p>
<p>Is there an elegant way to solve this problem?</p>
| [
{
"answer_id": 9972,
"author": "David Sykes",
"author_id": 259,
"author_profile": "https://Stackoverflow.com/users/259",
"pm_score": 5,
"selected": true,
"text": "<p>Here are some articles you might find of interest</p>\n\n<p><a href=\"http://accu.org/index.php/journals/479\" rel=\"noreferrer\">Giving STL Iterators a Base Class</a></p>\n\n<p><a href=\"http://thbecker.net/free_software_utilities/type_erasure_for_cpp_iterators/start_page.html\" rel=\"noreferrer\">Type Erasure for C++ Iterators</a></p>\n\n<p><a href=\"http://stlab.adobe.com/classadobe_1_1any__iterator.html\" rel=\"noreferrer\">any_iterator Class Reference</a></p>\n"
},
{
"answer_id": 10895,
"author": "graham.reeds",
"author_id": 342,
"author_profile": "https://Stackoverflow.com/users/342",
"pm_score": 1,
"selected": false,
"text": "<p>Better late than never...</p>\n\n<p>The latest issue of <a href=\"http://accu.org/index.php/aboutus/aboutjournals\" rel=\"nofollow noreferrer\">C-Vu</a> turned up and guess what was in it: That's right, iterators that do <em>exactly</em> what you wanted.</p>\n\n<p>Unfortunately you need to become a member of the <a href=\"http://accu.org/\" rel=\"nofollow noreferrer\">ACCU</a> to view the magazine (the article references the Overload article from 2000 that David links to). But for a measly price a year you get a nice magazine to read, conferences and user groups. When you become a member you can view PDF's of the back issues so <a href=\"http://accu.org/index.php/joining\" rel=\"nofollow noreferrer\">what are you waiting for</a>?</p>\n"
},
{
"answer_id": 127971,
"author": "MSalters",
"author_id": 15416,
"author_profile": "https://Stackoverflow.com/users/15416",
"pm_score": 1,
"selected": false,
"text": "<p>A case of being careful what you ask for. The any_iterator classes you see work on an unbounded set of iterator types. You only have three, which you know up front. Sure, you might need to add a fourth type in the future, but so what if that takes O(1) extra lines of code ?</p>\n\n<p>The big advantage of a closed set of possible contained types is that you have an upper bound on sizeof(), which means you can avoid the heap and the indirection it brings. Basically, stuff them all in a boost::variant and call apply_visitor.</p>\n"
}
] | 2008/08/13 | [
"https://Stackoverflow.com/questions/9938",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/263/"
] | I am trying to find a generic way of accessing a set of containers. I have a standard vector and list in addition to another custom list.
The custom list defines an iterator;
```
class Iterator: public std::iterator<std::forward_iterator_tag, T> {
// ...
}
Iterator begin() {
return (Iterator(root));
}
Iterator end() {
return (Iterator(NULL));
}
```
with the appropriate operators overloaded.
Ideally, I would like to do this;
```
class Foo {
public:
Foo() {
std::list<int> x;
std::vector<int> y;
custom_list<int> z;
iter = x.begin(); // OR
iter = y.begin(); // OR
iter = z.begin();
// ...
};
private:
std::iterator<int> iter;
};
```
But obviously these are all iterators of different types. I can assume all the containers are of the same type however.
Is there an elegant way to solve this problem? | Here are some articles you might find of interest
[Giving STL Iterators a Base Class](http://accu.org/index.php/journals/479)
[Type Erasure for C++ Iterators](http://thbecker.net/free_software_utilities/type_erasure_for_cpp_iterators/start_page.html)
[any\_iterator Class Reference](http://stlab.adobe.com/classadobe_1_1any__iterator.html) |
9,974 | <p>This is a question I asked on another forum which received some decent answers, but I wanted to see if anyone here has more insight.</p>
<p>The problem is that you have one of your pages in a web application timing out when it gets to a stored procedure call, so you use Sql Profiler, or your application trace logs, to find the query and you paste it into management studio to figure our why it's running slow. But you run it from there and it just blazes along, returning in less than a second each time.</p>
<p>My particular case was using ASP.NET 2.0 and Sql Server 2005, but I think the problem could apply to any RDBMS system.</p>
| [
{
"answer_id": 9982,
"author": "GateKiller",
"author_id": 383,
"author_profile": "https://Stackoverflow.com/users/383",
"pm_score": -1,
"selected": false,
"text": "<p>Try changing the SelectCommand timeout value:</p>\n\n<pre><code>DataAdapter.SelectCommand.CommandTimeout = 120;\n</code></pre>\n"
},
{
"answer_id": 9996,
"author": "Eric Z Beard",
"author_id": 1219,
"author_profile": "https://Stackoverflow.com/users/1219",
"pm_score": 6,
"selected": true,
"text": "<p>This is what I've learned so far from my research.</p>\n\n<p>.NET sends in connection settings that are not the same as what you get when you log in to management studio. Here is what you see if you sniff the connection with Sql Profiler:</p>\n\n<pre><code>-- network protocol: TCP/IP \nset quoted_identifier off \nset arithabort off \nset numeric_roundabort off \nset ansi_warnings on \nset ansi_padding on \nset ansi_nulls off \nset concat_null_yields_null on \nset cursor_close_on_commit off \nset implicit_transactions off \nset language us_english \nset dateformat mdy \nset datefirst 7 \nset transaction isolation level read committed \n</code></pre>\n\n<p>I am now pasting those setting in above every query that I run when logged in to sql server, to make sure the settings are the same.</p>\n\n<p>For this case, I tried each setting individually, after disconnecting and reconnecting, and found that changing arithabort from off to on reduced the problem query from 90 seconds to 1 second.</p>\n\n<p>The most probable explanation is related to parameter sniffing, which is a technique Sql Server uses to pick what it thinks is the most effective query plan. When you change one of the connection settings, the query optimizer might choose a different plan, and in this case, it apparently chose a bad one.</p>\n\n<p>But I'm not totally convinced of this. I have tried comparing the actual query plans after changing this setting and I have yet to see the diff show any changes.</p>\n\n<p>Is there something else about the arithabort setting that might cause a query to run slowly in some cases?</p>\n\n<p>The solution seemed simple: Just put set arithabort on into the top of the stored procedure. But this could lead to the opposite problem: change the query parameters and suddenly it runs faster with 'off' than 'on'. </p>\n\n<p>For the time being I am running the procedure 'with recompile' to make sure the plan gets regenerated each time. It's Ok for this particular report, since it takes maybe a second to recompile, and this isn't too noticeable on a report that takes 1-10 seconds to return (it's a monster).</p>\n\n<p>But it's not an option for other queries that run much more frequently and need to return as quickly as possible, in just a few milliseconds.</p>\n"
},
{
"answer_id": 10028,
"author": "SQLMenace",
"author_id": 740,
"author_profile": "https://Stackoverflow.com/users/740",
"pm_score": 1,
"selected": false,
"text": "<p>test this out on a staging box first, change it on a server level for sql server</p>\n\n<blockquote>\n <p>declare @option int</p>\n \n <p>set @option = @@options | 64</p>\n \n <p>exec sp_configure 'user options',\n @option</p>\n \n <p>RECONFIGURE</p>\n</blockquote>\n"
},
{
"answer_id": 10163,
"author": "Dillie-O",
"author_id": 71,
"author_profile": "https://Stackoverflow.com/users/71",
"pm_score": 2,
"selected": false,
"text": "<p>Have you turned on ASP.NET tracing yet? I've had an instance where it wasn't the SQL stored procedure itself that was the problem, it was the fact that the procedure returned 5000 rows and the app was attempting to create databound ListItems with those 5000 items that was causing the problem. </p>\n\n<p>You might look into the execution times between the web app functions as well through the trace to help track things down.</p>\n"
},
{
"answer_id": 51082,
"author": "tbreffni",
"author_id": 637,
"author_profile": "https://Stackoverflow.com/users/637",
"pm_score": 0,
"selected": false,
"text": "<p>You could try using the sp_who2 command to see what process in question is doing. This will show you if it's blocked by another process, or using up an excessive amount of cpu and/or io time.</p>\n"
},
{
"answer_id": 73111,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 2,
"selected": false,
"text": "<p>Same problem I had with SQL reporting services.\nTry to check type of variables, \nI was sending different type of variable to SQL like sending varchar in place where it should\nbe integer, or something like that.\nAfter I synchronized the types of variables in Reporting Service and in stored procedure on SQL, I solved the problem.</p>\n"
},
{
"answer_id": 255869,
"author": "Brian Adams",
"author_id": 32992,
"author_profile": "https://Stackoverflow.com/users/32992",
"pm_score": 3,
"selected": false,
"text": "<p>I've had similar problems. Try setting the with \"WITH RECOMPILE\" option on the sproc create to force the system to recompute the execution plan each time it is called. Sometimes the Query processor gets confused in complex stored procedures with lots of branching or case statements and just pulls a really sub-optimal execution plan. If that seems to \"fix\" the problem, you will probably need to verify statistics are up to date and/or break down the sproc.</p>\n\n<p>You can also confirm this by profiling the sproc. When you execute it from SQL Managment Studio, how does the IO compare to when you profile it from the ASP.NET application. If they very a lot, it just re-enforces that its pulling a bad execution plan.</p>\n"
},
{
"answer_id": 20200058,
"author": "Lac Ho",
"author_id": 1030454,
"author_profile": "https://Stackoverflow.com/users/1030454",
"pm_score": 0,
"selected": false,
"text": "<p>We had the same issue and here's what we found out.</p>\n\n<p>our database log size was being kept at the default (814 MB) and auto growth was 10%. \nOn the server, maximum server memory was kept at the default setting as well (2147483647 MB).</p>\n\n<p>When our log got full and needed to grow, it used all the memory from the server and there's nothing left for code to be run so it timed out. What we ended up doing was set database log file initial size to 1 MB and maximum server memory to 2048 MB. This instantly fixed our problem. Of course, you can change these two properties to fit your need but this is an idea for someone running into the timing out issue when executing a stored procedure via code but it runs super fast in SSMS and the solutions above do not help.</p>\n"
}
] | 2008/08/13 | [
"https://Stackoverflow.com/questions/9974",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1219/"
] | This is a question I asked on another forum which received some decent answers, but I wanted to see if anyone here has more insight.
The problem is that you have one of your pages in a web application timing out when it gets to a stored procedure call, so you use Sql Profiler, or your application trace logs, to find the query and you paste it into management studio to figure our why it's running slow. But you run it from there and it just blazes along, returning in less than a second each time.
My particular case was using ASP.NET 2.0 and Sql Server 2005, but I think the problem could apply to any RDBMS system. | This is what I've learned so far from my research.
.NET sends in connection settings that are not the same as what you get when you log in to management studio. Here is what you see if you sniff the connection with Sql Profiler:
```
-- network protocol: TCP/IP
set quoted_identifier off
set arithabort off
set numeric_roundabort off
set ansi_warnings on
set ansi_padding on
set ansi_nulls off
set concat_null_yields_null on
set cursor_close_on_commit off
set implicit_transactions off
set language us_english
set dateformat mdy
set datefirst 7
set transaction isolation level read committed
```
I am now pasting those setting in above every query that I run when logged in to sql server, to make sure the settings are the same.
For this case, I tried each setting individually, after disconnecting and reconnecting, and found that changing arithabort from off to on reduced the problem query from 90 seconds to 1 second.
The most probable explanation is related to parameter sniffing, which is a technique Sql Server uses to pick what it thinks is the most effective query plan. When you change one of the connection settings, the query optimizer might choose a different plan, and in this case, it apparently chose a bad one.
But I'm not totally convinced of this. I have tried comparing the actual query plans after changing this setting and I have yet to see the diff show any changes.
Is there something else about the arithabort setting that might cause a query to run slowly in some cases?
The solution seemed simple: Just put set arithabort on into the top of the stored procedure. But this could lead to the opposite problem: change the query parameters and suddenly it runs faster with 'off' than 'on'.
For the time being I am running the procedure 'with recompile' to make sure the plan gets regenerated each time. It's Ok for this particular report, since it takes maybe a second to recompile, and this isn't too noticeable on a report that takes 1-10 seconds to return (it's a monster).
But it's not an option for other queries that run much more frequently and need to return as quickly as possible, in just a few milliseconds. |
10,042 | <p>What's the best way to make a linked list in Java?</p>
| [
{
"answer_id": 10050,
"author": "dlinsin",
"author_id": 198,
"author_profile": "https://Stackoverflow.com/users/198",
"pm_score": 6,
"selected": false,
"text": "<p>Java has a <a href=\"http://java.sun.com/j2se/1.5.0/docs/api/java/util/LinkedList.html\" rel=\"noreferrer\">LinkedList</a> implementation, that you might wanna check out. You can download the JDK and it's sources at <a href=\"http://java.sun.com/javase/downloads/index.jsp\" rel=\"noreferrer\">java.sun.com</a>.</p>\n"
},
{
"answer_id": 12432,
"author": "Juha Syrjälä",
"author_id": 1431,
"author_profile": "https://Stackoverflow.com/users/1431",
"pm_score": 5,
"selected": false,
"text": "<p>Use <a href=\"http://java.sun.com/j2se/1.5.0/docs/api/java/util/LinkedList.html\" rel=\"noreferrer\">java.util.LinkedList</a>. Like this:</p>\n\n<pre><code>list = new java.util.LinkedList()\n</code></pre>\n"
},
{
"answer_id": 25311,
"author": "Aaron",
"author_id": 2628,
"author_profile": "https://Stackoverflow.com/users/2628",
"pm_score": 9,
"selected": true,
"text": "<p>The obvious solution to developers familiar to Java is to use the <strong>LinkedList</strong> class already provided in <strong>java.util</strong>. Say, however, you wanted to make your own implementation for some reason. Here is a quick example of a linked list that inserts a new link at the beginning of the list, deletes from the beginning of the list and loops through the list to print the links contained in it. <strong>Enhancements</strong> to this implementation include making it a <strong>double-linked list</strong>, adding methods to <strong>insert</strong> and <strong>delete</strong> from the middle or end, and by adding <strong>get</strong> and <strong>sort</strong> methods as well. </p>\n\n<p><strong>Note</strong>: In the example, the Link object doesn't actually contain another Link object - <em>nextLink</em> is actually only a reference to another link. </p>\n\n<pre><code>class Link {\n public int data1;\n public double data2;\n public Link nextLink;\n\n //Link constructor\n public Link(int d1, double d2) {\n data1 = d1;\n data2 = d2;\n }\n\n //Print Link data\n public void printLink() {\n System.out.print(\"{\" + data1 + \", \" + data2 + \"} \");\n }\n}\n\nclass LinkList {\n private Link first;\n\n //LinkList constructor\n public LinkList() {\n first = null;\n }\n\n //Returns true if list is empty\n public boolean isEmpty() {\n return first == null;\n }\n\n //Inserts a new Link at the first of the list\n public void insert(int d1, double d2) {\n Link link = new Link(d1, d2);\n link.nextLink = first;\n first = link;\n }\n\n //Deletes the link at the first of the list\n public Link delete() {\n Link temp = first;\n if(first == null){\n return null;\n //throw new NoSuchElementException(); // this is the better way. \n }\n first = first.nextLink;\n return temp;\n }\n\n //Prints list data\n public void printList() {\n Link currentLink = first;\n System.out.print(\"List: \");\n while(currentLink != null) {\n currentLink.printLink();\n currentLink = currentLink.nextLink;\n }\n System.out.println(\"\");\n }\n} \n\nclass LinkListTest {\n public static void main(String[] args) {\n LinkList list = new LinkList();\n\n list.insert(1, 1.01);\n list.insert(2, 2.02);\n list.insert(3, 3.03);\n list.insert(4, 4.04);\n list.insert(5, 5.05);\n\n list.printList();\n\n while(!list.isEmpty()) {\n Link deletedLink = list.delete();\n System.out.print(\"deleted: \");\n deletedLink.printLink();\n System.out.println(\"\");\n }\n list.printList();\n }\n}\n</code></pre>\n"
},
{
"answer_id": 690660,
"author": "Jakub Arnold",
"author_id": 72583,
"author_profile": "https://Stackoverflow.com/users/72583",
"pm_score": 3,
"selected": false,
"text": "<p>Its much better to use java.util.LinkedList, because it's probably much more optimized, than the one that you will write.</p>\n"
},
{
"answer_id": 1963840,
"author": "arnab sarkar",
"author_id": 238899,
"author_profile": "https://Stackoverflow.com/users/238899",
"pm_score": 4,
"selected": false,
"text": "<p>The above linked list display in opposite direction. I think the correct implementation of insert method should be</p>\n\n<pre><code>public void insert(int d1, double d2) { \n Link link = new Link(d1, d2); \n\n if(first==null){\n link.nextLink = null;\n first = link; \n last=link;\n }\n else{\n last.nextLink=link;\n link.nextLink=null;\n last=link;\n }\n} \n</code></pre>\n"
},
{
"answer_id": 6674458,
"author": "Anitha A",
"author_id": 842022,
"author_profile": "https://Stackoverflow.com/users/842022",
"pm_score": 3,
"selected": false,
"text": "<pre><code>//slightly improved code without using collection framework\n\npackage com.test;\n\npublic class TestClass {\n\n private static Link last;\n private static Link first;\n\n public static void main(String[] args) {\n\n //Inserting\n for(int i=0;i<5;i++){\n Link.insert(i+5);\n }\n Link.printList();\n\n //Deleting\n Link.deletefromFirst();\n Link.printList();\n }\n\n\n protected static class Link {\n private int data;\n private Link nextlink;\n\n public Link(int d1) {\n this.data = d1;\n }\n\n public static void insert(int d1) {\n Link a = new Link(d1);\n a.nextlink = null;\n if (first != null) {\n last.nextlink = a;\n last = a;\n } else {\n first = a;\n last = a;\n }\n System.out.println(\"Inserted -:\"+d1);\n }\n\n public static void deletefromFirst() {\n if(null!=first)\n {\n System.out.println(\"Deleting -:\"+first.data);\n first = first.nextlink;\n }\n else{\n System.out.println(\"No elements in Linked List\");\n }\n }\n\n public static void printList() {\n System.out.println(\"Elements in the list are\");\n System.out.println(\"-------------------------\");\n Link temp = first;\n while (temp != null) {\n System.out.println(temp.data);\n temp = temp.nextlink;\n }\n }\n }\n}\n</code></pre>\n"
}
] | 2008/08/13 | [
"https://Stackoverflow.com/questions/10042",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/571/"
] | What's the best way to make a linked list in Java? | The obvious solution to developers familiar to Java is to use the **LinkedList** class already provided in **java.util**. Say, however, you wanted to make your own implementation for some reason. Here is a quick example of a linked list that inserts a new link at the beginning of the list, deletes from the beginning of the list and loops through the list to print the links contained in it. **Enhancements** to this implementation include making it a **double-linked list**, adding methods to **insert** and **delete** from the middle or end, and by adding **get** and **sort** methods as well.
**Note**: In the example, the Link object doesn't actually contain another Link object - *nextLink* is actually only a reference to another link.
```
class Link {
public int data1;
public double data2;
public Link nextLink;
//Link constructor
public Link(int d1, double d2) {
data1 = d1;
data2 = d2;
}
//Print Link data
public void printLink() {
System.out.print("{" + data1 + ", " + data2 + "} ");
}
}
class LinkList {
private Link first;
//LinkList constructor
public LinkList() {
first = null;
}
//Returns true if list is empty
public boolean isEmpty() {
return first == null;
}
//Inserts a new Link at the first of the list
public void insert(int d1, double d2) {
Link link = new Link(d1, d2);
link.nextLink = first;
first = link;
}
//Deletes the link at the first of the list
public Link delete() {
Link temp = first;
if(first == null){
return null;
//throw new NoSuchElementException(); // this is the better way.
}
first = first.nextLink;
return temp;
}
//Prints list data
public void printList() {
Link currentLink = first;
System.out.print("List: ");
while(currentLink != null) {
currentLink.printLink();
currentLink = currentLink.nextLink;
}
System.out.println("");
}
}
class LinkListTest {
public static void main(String[] args) {
LinkList list = new LinkList();
list.insert(1, 1.01);
list.insert(2, 2.02);
list.insert(3, 3.03);
list.insert(4, 4.04);
list.insert(5, 5.05);
list.printList();
while(!list.isEmpty()) {
Link deletedLink = list.delete();
System.out.print("deleted: ");
deletedLink.printLink();
System.out.println("");
}
list.printList();
}
}
``` |
10,071 | <p>I'm working on an app that grabs and installs a bunch of updates off an an external server, and need some help with threading. The user follows this process:</p>
<ul>
<li>Clicks button</li>
<li>Method checks for updates, count is returned.</li>
<li>If greater than 0, then ask the user if they want to install using MessageBox.Show().</li>
<li>If yes, it runs through a loop and call BeginInvoke() on the run() method of each update to run it in the background.</li>
<li>My update class has some events that are used to update a progress bar etc. </li>
</ul>
<p>The progress bar updates are fine, but the MessageBox is not fully cleared from the screen because the update loop starts right after the user clicks yes (see screenshot below).</p>
<ul>
<li>What should I do to make the messagebox disappear instantly before the update loop starts?</li>
<li>Should I be using Threads instead of BeginInvoke()?</li>
<li>Should I be doing the initial update check on a separate thread and calling MessageBox.Show() from that thread?</li>
</ul>
<p><strong>Code</strong></p>
<pre><code>// Button clicked event handler code...
DialogResult dlgRes = MessageBox.Show(
string.Format("There are {0} updates available.\n\nInstall these now?",
um2.Updates.Count), "Updates Available",
MessageBoxButtons.YesNo,
MessageBoxIcon.Question,
MessageBoxDefaultButton.Button2
);
if (dlgRes == DialogResult.Yes)
{
ProcessAllUpdates(um2);
}
// Processes a bunch of items in a loop
private void ProcessAllUpdates(UpdateManager2 um2)
{
for (int i = 0; i < um2.Updates.Count; i++)
{
Update2 update = um2.Updates[i];
ProcessSingleUpdate(update);
int percentComplete = Utilities.CalculatePercentCompleted(i, um2.Updates.Count);
UpdateOverallProgress(percentComplete);
}
}
// Process a single update with IAsyncResult
private void ProcessSingleUpdate(Update2 update)
{
update.Action.OnStart += Action_OnStart;
update.Action.OnProgress += Action_OnProgress;
update.Action.OnCompletion += Action_OnCompletion;
//synchronous
//update.Action.Run();
// async
IAsyncResult ar = this.BeginInvoke((MethodInvoker)delegate() { update.Action.Run(); });
}
</code></pre>
<p><strong>Screenshot</strong></p>
<p><a href="http://www.flickr.com/photos/brianly/2760435228/" rel="nofollow noreferrer" title="Windows Mobile Bug by BrianLy, on Flickr"><img src="https://farm4.static.flickr.com/3043/2760435228_1af7dbf365_o.gif" width="233" height="266" alt="Windows Mobile Bug" /></a></p>
| [
{
"answer_id": 10116,
"author": "JamesSugrue",
"author_id": 1075,
"author_profile": "https://Stackoverflow.com/users/1075",
"pm_score": 1,
"selected": false,
"text": "<p>Have you tried putting a </p>\n\n<pre><code>Application.DoEvents()\n</code></pre>\n\n<p>in here</p>\n\n<pre><code>if (dlgRes == DialogResult.Yes)\n{\n Application.DoEvents(); \n ProcessAllUpdates(um2); \n}\n</code></pre>\n"
},
{
"answer_id": 10157,
"author": "John Sibly",
"author_id": 1078,
"author_profile": "https://Stackoverflow.com/users/1078",
"pm_score": 4,
"selected": true,
"text": "<p>Your UI isn't updating because all the work is happening in the user interface thread.\nYour call to: </p>\n\n<pre><code>this.BeginInvoke((MethodInvoker)delegate() {update.Action.Run(); }) \n</code></pre>\n\n<p>is saying invoke update.Action.Run() on the thread that created \"this\" (your form), which is the user interface thread.</p>\n\n<pre><code>Application.DoEvents()\n</code></pre>\n\n<p>will indeed give the UI thread the chance to redraw the screen, but I'd be tempted to create new delegate, and call BeginInvoke on that. </p>\n\n<p>This will execute the update.Action.Run() function on a seperate thread allocated from the thread pool. You can then keep checking the IAsyncResult until the update is complete, querying the update object for its progress after every check (because you can't have the other thread update the progress bar/UI), then calling Application.DoEvents(). </p>\n\n<p>You also are supposed to call EndInvoke() afterwards otherwise you may end up leaking resources</p>\n\n<p>I would also be tempted to put a cancel button on the progress dialog, and add a timeout, otherwise if the update gets stuck (or takes too long) then your application will have locked up forever.</p>\n"
},
{
"answer_id": 21054,
"author": "Quibblesome",
"author_id": 1143,
"author_profile": "https://Stackoverflow.com/users/1143",
"pm_score": 1,
"selected": false,
"text": "<p>@ John Sibly</p>\n\n<p><a href=\"http://www.interact-sw.co.uk/iangblog/2005/05/16/endinvokerequired\" rel=\"nofollow noreferrer\">You can get away with <em>not</em> calling EndInvoke when dealing with WinForms without any negative consequences.</a></p>\n\n<blockquote>\n <p>The only documented exception to the rule that I'm aware of is in Windows Forms, where you are officially allowed to call Control.BeginInvoke without bothering to call Control.EndInvoke.</p>\n</blockquote>\n\n<p>However in all other cases when dealing with the Begin/End Async pattern you should assume it will leak, as you stated.</p>\n"
}
] | 2008/08/13 | [
"https://Stackoverflow.com/questions/10071",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/636/"
] | I'm working on an app that grabs and installs a bunch of updates off an an external server, and need some help with threading. The user follows this process:
* Clicks button
* Method checks for updates, count is returned.
* If greater than 0, then ask the user if they want to install using MessageBox.Show().
* If yes, it runs through a loop and call BeginInvoke() on the run() method of each update to run it in the background.
* My update class has some events that are used to update a progress bar etc.
The progress bar updates are fine, but the MessageBox is not fully cleared from the screen because the update loop starts right after the user clicks yes (see screenshot below).
* What should I do to make the messagebox disappear instantly before the update loop starts?
* Should I be using Threads instead of BeginInvoke()?
* Should I be doing the initial update check on a separate thread and calling MessageBox.Show() from that thread?
**Code**
```
// Button clicked event handler code...
DialogResult dlgRes = MessageBox.Show(
string.Format("There are {0} updates available.\n\nInstall these now?",
um2.Updates.Count), "Updates Available",
MessageBoxButtons.YesNo,
MessageBoxIcon.Question,
MessageBoxDefaultButton.Button2
);
if (dlgRes == DialogResult.Yes)
{
ProcessAllUpdates(um2);
}
// Processes a bunch of items in a loop
private void ProcessAllUpdates(UpdateManager2 um2)
{
for (int i = 0; i < um2.Updates.Count; i++)
{
Update2 update = um2.Updates[i];
ProcessSingleUpdate(update);
int percentComplete = Utilities.CalculatePercentCompleted(i, um2.Updates.Count);
UpdateOverallProgress(percentComplete);
}
}
// Process a single update with IAsyncResult
private void ProcessSingleUpdate(Update2 update)
{
update.Action.OnStart += Action_OnStart;
update.Action.OnProgress += Action_OnProgress;
update.Action.OnCompletion += Action_OnCompletion;
//synchronous
//update.Action.Run();
// async
IAsyncResult ar = this.BeginInvoke((MethodInvoker)delegate() { update.Action.Run(); });
}
```
**Screenshot**
[](http://www.flickr.com/photos/brianly/2760435228/ "Windows Mobile Bug by BrianLy, on Flickr") | Your UI isn't updating because all the work is happening in the user interface thread.
Your call to:
```
this.BeginInvoke((MethodInvoker)delegate() {update.Action.Run(); })
```
is saying invoke update.Action.Run() on the thread that created "this" (your form), which is the user interface thread.
```
Application.DoEvents()
```
will indeed give the UI thread the chance to redraw the screen, but I'd be tempted to create new delegate, and call BeginInvoke on that.
This will execute the update.Action.Run() function on a seperate thread allocated from the thread pool. You can then keep checking the IAsyncResult until the update is complete, querying the update object for its progress after every check (because you can't have the other thread update the progress bar/UI), then calling Application.DoEvents().
You also are supposed to call EndInvoke() afterwards otherwise you may end up leaking resources
I would also be tempted to put a cancel button on the progress dialog, and add a timeout, otherwise if the update gets stuck (or takes too long) then your application will have locked up forever. |
10,123 | <p>I'm trying to decode the result of the Python os.wait() function. This returns, according to the Python docs:</p>
<blockquote>
<p>a tuple containing its pid and exit status indication: a 16-bit number, whose low byte is the signal number that killed the process, and whose high byte is the exit status (if the signal number is zero); the high bit of the low byte is set if a core file was produced.</p>
</blockquote>
<p>How do I decode the exit status indication (which is an integer) to obtain the high and low byte? To be specific, how do I implement the decode function used in the following code snippet:</p>
<pre><code>(pid,status) = os.wait()
(exitstatus, signum) = decode(status)
</code></pre>
| [
{
"answer_id": 10129,
"author": "Mark Harrison",
"author_id": 116,
"author_profile": "https://Stackoverflow.com/users/116",
"pm_score": 5,
"selected": true,
"text": "<p>This will do what you want:</p>\n\n<pre><code>signum = status & 0xff\nexitstatus = (status & 0xff00) >> 8\n</code></pre>\n"
},
{
"answer_id": 10132,
"author": "Derek Park",
"author_id": 872,
"author_profile": "https://Stackoverflow.com/users/872",
"pm_score": 1,
"selected": false,
"text": "<p>You can unpack the status using <a href=\"https://docs.python.org/3/reference/expressions.html#shifting-operations\" rel=\"nofollow noreferrer\">bit-shifting</a> and <a href=\"https://docs.python.org/3/reference/expressions.html#binary-bitwise-operations\" rel=\"nofollow noreferrer\">masking</a> operators.</p>\n<pre><code>low = status & 0x00FF\nhigh = (status & 0xFF00) >> 8\n</code></pre>\n<p>I'm not a Python programmer, so I hope got the syntax correct.</p>\n"
},
{
"answer_id": 10148,
"author": "Patrick",
"author_id": 429,
"author_profile": "https://Stackoverflow.com/users/429",
"pm_score": 0,
"selected": false,
"text": "<p>The folks before me've nailed it, but if you really want it on one line, you can do this:</p>\n\n<pre><code>(signum, exitstatus) = (status & 0xFF, (status >> 8) & 0xFF)\n</code></pre>\n\n<p>EDIT: Had it backwards.</p>\n"
},
{
"answer_id": 10213,
"author": "Jason Pratt",
"author_id": 99,
"author_profile": "https://Stackoverflow.com/users/99",
"pm_score": 4,
"selected": false,
"text": "<p>To answer your general question, you can use <a href=\"https://en.wikipedia.org/wiki/Bit_manipulation\" rel=\"nofollow noreferrer\">bit manipulation</a></p>\n<pre><code>pid, status = os.wait()\nexitstatus, signum = status & 0xFF, (status & 0xFF00) >> 8\n</code></pre>\n<p>However, there are also <a href=\"https://docs.python.org/3/library/functions.html\" rel=\"nofollow noreferrer\">built-in functions</a> for interpreting exit status values:</p>\n<pre><code>pid, status = os.wait()\nexitstatus, signum = os.WEXITSTATUS( status ), os.WTERMSIG( status )\n</code></pre>\n<p>See also:</p>\n<ul>\n<li>os.WCOREDUMP()</li>\n<li>os.WIFCONTINUED()</li>\n<li>os.WIFSTOPPED()</li>\n<li>os.WIFSIGNALED()</li>\n<li>os.WIFEXITED()</li>\n<li>os.WSTOPSIG()</li>\n</ul>\n"
},
{
"answer_id": 686128,
"author": "RobM",
"author_id": 83100,
"author_profile": "https://Stackoverflow.com/users/83100",
"pm_score": 2,
"selected": false,
"text": "<p>You can get break your int into a string of unsigned bytes with the <a href=\"http://docs.python.org/library/struct.html\" rel=\"nofollow noreferrer\">struct</a> module:</p>\n\n<pre><code>import struct\ni = 3235830701 # 0xC0DEDBAD\ns = struct.pack(\">L\", i) # \">\" = Big-endian, \"<\" = Little-endian\nprint s # '\\xc0\\xde\\xdb\\xad'\nprint s[0] # '\\xc0'\nprint ord(s[0]) # 192 (which is 0xC0)\n</code></pre>\n\n<p>If you couple this with the <a href=\"http://docs.python.org/library/array.html\" rel=\"nofollow noreferrer\">array</a> module you can do this more conveniently:</p>\n\n<pre><code>import struct\ni = 3235830701 # 0xC0DEDBAD\ns = struct.pack(\">L\", i) # \">\" = Big-endian, \"<\" = Little-endian\n\nimport array\na = array.array(\"B\") # B: Unsigned bytes\na.fromstring(s)\nprint a # array('B', [192, 222, 219, 173])\n</code></pre>\n"
},
{
"answer_id": 687977,
"author": "tzot",
"author_id": 6899,
"author_profile": "https://Stackoverflow.com/users/6899",
"pm_score": 2,
"selected": false,
"text": "<pre><code>exitstatus, signum= divmod(status, 256)\n</code></pre>\n"
},
{
"answer_id": 50074196,
"author": "Barish Ahsen",
"author_id": 9712098,
"author_profile": "https://Stackoverflow.com/users/9712098",
"pm_score": 0,
"selected": false,
"text": "<pre><code>import amp as amp\nimport status\nsignum = status &amp; 0xff\nexitstatus = (status &amp; 0xff00) &gt;&gt; 8\n</code></pre>\n"
}
] | 2008/08/13 | [
"https://Stackoverflow.com/questions/10123",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/742/"
] | I'm trying to decode the result of the Python os.wait() function. This returns, according to the Python docs:
>
> a tuple containing its pid and exit status indication: a 16-bit number, whose low byte is the signal number that killed the process, and whose high byte is the exit status (if the signal number is zero); the high bit of the low byte is set if a core file was produced.
>
>
>
How do I decode the exit status indication (which is an integer) to obtain the high and low byte? To be specific, how do I implement the decode function used in the following code snippet:
```
(pid,status) = os.wait()
(exitstatus, signum) = decode(status)
``` | This will do what you want:
```
signum = status & 0xff
exitstatus = (status & 0xff00) >> 8
``` |
10,149 | <p>For context, I am something of an emacs newbie. I haven't used it for very long, but have been using it more and more (I like it a lot). Also I'm comfortable with lisp, but not super familiar with elisp.</p>
<p>What I need to do is bind a regular expression to a keyboard combination because I use this particular regex so often.</p>
<p>What I've been doing: </p>
<pre><code>M-C-s ^.*Table\(\(.*\n\)*?GO\)
</code></pre>
<p>Note, I used newline above, but I've found that for <code>isearch-forward-regexp</code>, you really need to replace the <code>\n</code> in the regular expression with the result of <kbd>C-q Q-j</kbd>. This inserts a literal newline (without ending the command) enabling me to put a newline into the expression and match across lines.</p>
<p>How can I bind this to a key combination? </p>
<p>I vaguely understand that I need to create an elisp function which executes <code>isearch-forward-regexp</code> with the expression, but I'm fuzzy on the details. I've searched google and found most documentation to be a tad confusing.</p>
<p><em>How can I bind a regular expression to a key combination in emacs?</em></p>
<hr>
<p><strong>Mike Stone had the best answer so far -- not <em>exactly</em> what I was looking for but it worked for what I needed</strong> </p>
<p>Edit - this sort of worked, but after storing the macro, when I went back to use it later, I couldn't use it with <kbd>C-x e</kbd>. (i.e., if I reboot emacs and then type <kbd>M-x macro-name</kbd>, and then <kbd>C-x e</kbd>, I get a message in the minibuffer like 'no last kbd macro' or something similar)</p>
<hr>
<p>@Mike Stone - Thanks for the information. I tried creating a macro like so:</p>
<pre><code>C-x( M-C-s ^.*Table\(\(.*C-q C-J\)*?GO\) C-x)
</code></pre>
<p>This created my macro, but when I executed my macro I didn't get the same highlighting that I ordinarily get when I use <code>isearch-forward-regexp</code>. Instead it just jumped to the end of the next match of the expression. So that doesn't really work for what I need. Any ideas?</p>
<p>Edit: It looks like I <em>can</em> use macros to do what I want, I just have to think outside the box of <code>isearch-forward-regexp</code>. I'll try what you suggested.</p>
| [
{
"answer_id": 10161,
"author": "Mike Stone",
"author_id": 122,
"author_profile": "https://Stackoverflow.com/users/122",
"pm_score": 4,
"selected": true,
"text": "<p>You can use macros, just do <kbd>C-x (</kbd> then do everything for the macro, then <kbd>C-x )</kbd> to end the macro, then <kbd>C-x e</kbd> will execute the last defined macro. Then, you can name it using <kbd>M-x name-last-kbd-macro</kbd> which lets you assign a name to it, which you can then invoke with <kbd>M-x TESTIT</kbd>, then store the definition using <kbd>M-x insert-kbd-macro</kbd> which will put the macro into your current buffer, and then you can store it in your <code>.emacs</code> file.</p>\n\n<p>Example:</p>\n\n<pre><code>C-x( abc *return* C-x)\n</code></pre>\n\n<p>Will define a macro to type \"abc\" and press return.</p>\n\n<pre><code>C-xeee\n</code></pre>\n\n<p>Executes the above macro immediately, 3 times (first e executes it, then following 2 e's will execute it twice more).</p>\n\n<pre><code>M-x name-last-kbd-macro testit\n</code></pre>\n\n<p>Names the macro to \"testit\"</p>\n\n<pre><code>M-x testit\n</code></pre>\n\n<p>Executes the just named macro (prints \"abc\" then return).</p>\n\n<pre><code>M-x insert-kbd-macro\n</code></pre>\n\n<p>Puts the following in your current buffer:</p>\n\n<pre><code>(fset 'testit\n [?a ?b ?c return])\n</code></pre>\n\n<p>Which can then be saved in your <code>.emacs</code> file to use the named macro over and over again after restarting emacs.</p>\n"
},
{
"answer_id": 10202,
"author": "Mike Stone",
"author_id": 122,
"author_profile": "https://Stackoverflow.com/users/122",
"pm_score": 1,
"selected": false,
"text": "<p>@Justin:</p>\n\n<p>When executing a macro, it's a little different... incremental searches will just happen once, and you will have to execute the macro again if you want to search again. You can do more powerful and complex things though, such as search for a keyword, jump to the beginning of the line, mark, go to end of the line, M-w (to copy), then jump to another buffer, then C-y (paste), then jump back to the other buffer and end your macro. Then, each time you execute the macro you will be copying a line to the next buffer.</p>\n\n<p>The really cool thing about emacs macros is it will stop when it sees the bell... which happens when you fail to match an incremental search (among other things). So the above macro, you can do C-u 1000 C-x e which will execute the macro 1000 times... but since you did a search, it will only copy 1000 lines, OR UNTIL THE SEARCH FAILS! Which means if there are 100 matches, it will only execute the macro 100 times.</p>\n\n<p>EDIT: Check out C-hf highlight-lines-matching-regexp which will show the help of a command that highlights everything matching a regex... I don't know how to undo the highlighting though... anyways you could use a stored macro to highlight all matching the regex, and then another macro to find the next one...?</p>\n\n<p>FURTHER EDIT: M-x unhighlight-regexp will undo the highlighting, you have to enter the last regex though (but it defaults to the regex you used to highlight)</p>\n"
},
{
"answer_id": 24920,
"author": "Natalie Weizenbaum",
"author_id": 2518,
"author_profile": "https://Stackoverflow.com/users/2518",
"pm_score": 1,
"selected": false,
"text": "<p>In general, to define a custom keybinding in Emacs, you'd write</p>\n\n<pre><code>(define-key global-map (kbd \"C-c C-f\") 'function-name)\n</code></pre>\n\n<p><code>define-key</code> is, unsurprisingly, the function to define a new key. <code>global-map</code> is the global keymap, as opposed to individual maps for each mode. <code>(kbd \"C-c C-f\")</code> returns a string representing the key sequence <code>C-c C-f</code>. There are other ways of doing this, including inputting the string directly, but this is usually the most straightforward since it takes the normal written representation. <code>'function-name</code> is a symbol that's the name of the function.</p>\n\n<p>Now, unless your function is already defined, you'll want to define it before you use this. To do that, write</p>\n\n<pre><code>(defun function-name (args)\n (interactive)\n stuff\n ...)\n</code></pre>\n\n<p><code>defun</code> defines a function - use <code>C-h f defun</code> for more specific information. The <code>(interactive)</code> there isn't really a function call; it tells the compiler that it's okay for the function to be called by the user using <code>M-x function-name</code> and via keybindings.</p>\n\n<p>Now, for interactive searching in particular, this is tricky; the <code>isearch</code> module doesn't really seem to be set up for what you're trying to do. But you can use this to do something similar.</p>\n"
},
{
"answer_id": 60207,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 2,
"selected": false,
"text": "<p>I've started with solving your problem literally,</p>\n\n<pre><code>(defun search-maker (s)\n `(lambda ()\n (interactive)\n (let ((regexp-search-ring (cons ,s regexp-search-ring)) ;add regexp to history\n (isearch-mode-map (copy-keymap isearch-mode-map)))\n (define-key isearch-mode-map (vector last-command-event) 'isearch-repeat-forward) ;make last key repeat\n (isearch-forward-regexp)))) ;`\n\n(global-set-key (kbd \"C-. t\") (search-maker \"^.*Table\\\\(\\\\(.*\\\\n\\\\)*?GO\\\\)\"))\n(global-set-key (kbd \"<f6>\") (search-maker \"HELLO WORLD\"))\n</code></pre>\n\n<p>The keyboard sequence from <code>(kbd ...)</code> starts a new blank search. To actually search for your string, you press <em>last key</em> again as many times as you need. So <code>C-. t t t</code> or <code><f6> <f6> <f6></code>. The solution is basically a hack, but I'll leave it here if you want to experiment with it.</p>\n\n<p>The following is probably the closest to what you need,</p>\n\n<pre><code>(defmacro define-isearch-yank (key string)\n `(define-key isearch-mode-map ,key \n (lambda ()\n (interactive) \n (isearch-yank-string ,string)))) ;`\n\n(define-isearch-yank (kbd \"C-. t\") \"^.*Table\\\\(\\\\(.*\\\\n\\\\)*?GO\\\\)\")\n(define-isearch-yank (kbd \"<f6>\") \"HELLO WORLD\")\n</code></pre>\n\n<p>The key combos now only work in isearch mode. You start the search normally, and then press key combos to insert your predefined string.</p>\n"
}
] | 2008/08/13 | [
"https://Stackoverflow.com/questions/10149",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/92/"
] | For context, I am something of an emacs newbie. I haven't used it for very long, but have been using it more and more (I like it a lot). Also I'm comfortable with lisp, but not super familiar with elisp.
What I need to do is bind a regular expression to a keyboard combination because I use this particular regex so often.
What I've been doing:
```
M-C-s ^.*Table\(\(.*\n\)*?GO\)
```
Note, I used newline above, but I've found that for `isearch-forward-regexp`, you really need to replace the `\n` in the regular expression with the result of `C-q Q-j`. This inserts a literal newline (without ending the command) enabling me to put a newline into the expression and match across lines.
How can I bind this to a key combination?
I vaguely understand that I need to create an elisp function which executes `isearch-forward-regexp` with the expression, but I'm fuzzy on the details. I've searched google and found most documentation to be a tad confusing.
*How can I bind a regular expression to a key combination in emacs?*
---
**Mike Stone had the best answer so far -- not *exactly* what I was looking for but it worked for what I needed**
Edit - this sort of worked, but after storing the macro, when I went back to use it later, I couldn't use it with `C-x e`. (i.e., if I reboot emacs and then type `M-x macro-name`, and then `C-x e`, I get a message in the minibuffer like 'no last kbd macro' or something similar)
---
@Mike Stone - Thanks for the information. I tried creating a macro like so:
```
C-x( M-C-s ^.*Table\(\(.*C-q C-J\)*?GO\) C-x)
```
This created my macro, but when I executed my macro I didn't get the same highlighting that I ordinarily get when I use `isearch-forward-regexp`. Instead it just jumped to the end of the next match of the expression. So that doesn't really work for what I need. Any ideas?
Edit: It looks like I *can* use macros to do what I want, I just have to think outside the box of `isearch-forward-regexp`. I'll try what you suggested. | You can use macros, just do `C-x (` then do everything for the macro, then `C-x )` to end the macro, then `C-x e` will execute the last defined macro. Then, you can name it using `M-x name-last-kbd-macro` which lets you assign a name to it, which you can then invoke with `M-x TESTIT`, then store the definition using `M-x insert-kbd-macro` which will put the macro into your current buffer, and then you can store it in your `.emacs` file.
Example:
```
C-x( abc *return* C-x)
```
Will define a macro to type "abc" and press return.
```
C-xeee
```
Executes the above macro immediately, 3 times (first e executes it, then following 2 e's will execute it twice more).
```
M-x name-last-kbd-macro testit
```
Names the macro to "testit"
```
M-x testit
```
Executes the just named macro (prints "abc" then return).
```
M-x insert-kbd-macro
```
Puts the following in your current buffer:
```
(fset 'testit
[?a ?b ?c return])
```
Which can then be saved in your `.emacs` file to use the named macro over and over again after restarting emacs. |
10,158 | <p>What's the easiest way to do an "instring" type function with a regex? For example, how could I reject a whole string because of the presence of a single character such as <code>:</code>? For example: </p>
<ul>
<li><code>this</code> - okay</li>
<li><code>there:is</code> - not okay because of <code>:</code></li>
</ul>
<p>More practically, how can I match the following string: </p>
<pre><code>//foo/bar/baz[1]/ns:foo2/@attr/text()
</code></pre>
<p>For any node test on the xpath that doesn't include a namespace?</p>
<pre><code>(/)?(/)([^:/]+)
</code></pre>
<p>Will match the node tests but includes the namespace prefix which makes it faulty.</p>
| [
{
"answer_id": 10168,
"author": "Adam Lerman",
"author_id": 673,
"author_profile": "https://Stackoverflow.com/users/673",
"pm_score": 0,
"selected": false,
"text": "<p>I dont know regex syntax very well but could you not do:</p>\n\n<p><code>[any alpha numeric]\\*:[any alphanumeric]\\*</code></p>\n\n<p>I think something like that should work no?</p>\n"
},
{
"answer_id": 10186,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 1,
"selected": false,
"text": "<p>Match on :? I think the question isn't clear enough, because the answer is so obvious:</p>\n\n<pre><code>if(Regex.Match(\":\", input)) // reject\n</code></pre>\n"
},
{
"answer_id": 10187,
"author": "Mike Stone",
"author_id": 122,
"author_profile": "https://Stackoverflow.com/users/122",
"pm_score": 0,
"selected": false,
"text": "<p>You might want \\w which is a \"word\" character. From <a href=\"http://java.sun.com/j2se/1.5.0/docs/api/java/util/regex/Pattern.html\" rel=\"nofollow noreferrer\">javadocs</a>, it is defined as [a-zA-Z_0-9], so if you don't want underscores either, that may not work....</p>\n"
},
{
"answer_id": 10325,
"author": "t3rse",
"author_id": 64,
"author_profile": "https://Stackoverflow.com/users/64",
"pm_score": 0,
"selected": false,
"text": "<p>Yeah, my question was not very clear. Here's a solution but rather than a single pass with a regex, I use a <strong>split</strong> and perform iteration. It works as well but isn't as elegant: </p>\n\n<pre><code>string xpath = \"//foo/bar/baz[1]/ns:foo2/@attr/text()\";\nstring[] nodetests = xpath.Split( new char[] { '/' } );\nfor (int i = 0; i < nodetests.Length; i++) \n{\n if (nodetests[i].Length > 0 && Regex.IsMatch( nodetests[i], @\"^(\\w|\\[|\\])+$\" ))\n {\n // does not have a \":\", we can manipulate it.\n }\n}\n\nxpath = String.Join( \"/\", nodetests );\n</code></pre>\n"
},
{
"answer_id": 10516,
"author": "OJ.",
"author_id": 611,
"author_profile": "https://Stackoverflow.com/users/611",
"pm_score": 2,
"selected": false,
"text": "<p>I'm still not sure whether you just wanted to detect if the Xpath contains a namespace, or whether you want to remove the references to the namespace. So here's some sample code (in C#) that does both.</p>\n\n<pre><code>class Program\n{\n static void Main(string[] args)\n {\n string withNamespace = @\"//foo/ns2:bar/baz[1]/ns:foo2/@attr/text()\";\n string withoutNamespace = @\"//foo/bar/baz[1]/foo2/@attr/text()\";\n\n ShowStuff(withNamespace);\n ShowStuff(withoutNamespace);\n }\n\n static void ShowStuff(string input)\n {\n Console.WriteLine(\"'{0}' does {1}contain namespaces\", input, ContainsNamespace(input) ? \"\" : \"not \");\n Console.WriteLine(\"'{0}' without namespaces is '{1}'\", input, StripNamespaces(input));\n }\n\n static bool ContainsNamespace(string input)\n {\n // a namspace must start with a character, but can have characters and numbers\n // from that point on.\n return Regex.IsMatch(input, @\"/?\\w[\\w\\d]+:\\w[\\w\\d]+/?\");\n }\n\n static string StripNamespaces(string input)\n {\n return Regex.Replace(input, @\"(/?)\\w[\\w\\d]+:(\\w[\\w\\d]+)(/?)\", \"$1$2$3\");\n }\n}\n</code></pre>\n\n<p>Hope that helps! Good luck.</p>\n"
}
] | 2008/08/13 | [
"https://Stackoverflow.com/questions/10158",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/64/"
] | What's the easiest way to do an "instring" type function with a regex? For example, how could I reject a whole string because of the presence of a single character such as `:`? For example:
* `this` - okay
* `there:is` - not okay because of `:`
More practically, how can I match the following string:
```
//foo/bar/baz[1]/ns:foo2/@attr/text()
```
For any node test on the xpath that doesn't include a namespace?
```
(/)?(/)([^:/]+)
```
Will match the node tests but includes the namespace prefix which makes it faulty. | I'm still not sure whether you just wanted to detect if the Xpath contains a namespace, or whether you want to remove the references to the namespace. So here's some sample code (in C#) that does both.
```
class Program
{
static void Main(string[] args)
{
string withNamespace = @"//foo/ns2:bar/baz[1]/ns:foo2/@attr/text()";
string withoutNamespace = @"//foo/bar/baz[1]/foo2/@attr/text()";
ShowStuff(withNamespace);
ShowStuff(withoutNamespace);
}
static void ShowStuff(string input)
{
Console.WriteLine("'{0}' does {1}contain namespaces", input, ContainsNamespace(input) ? "" : "not ");
Console.WriteLine("'{0}' without namespaces is '{1}'", input, StripNamespaces(input));
}
static bool ContainsNamespace(string input)
{
// a namspace must start with a character, but can have characters and numbers
// from that point on.
return Regex.IsMatch(input, @"/?\w[\w\d]+:\w[\w\d]+/?");
}
static string StripNamespaces(string input)
{
return Regex.Replace(input, @"(/?)\w[\w\d]+:(\w[\w\d]+)(/?)", "$1$2$3");
}
}
```
Hope that helps! Good luck. |
10,190 | <p>Many applications have grids that display data from a database table one page at a time. Many of them also let the user pick the number of records per page, sort by any column, and navigate back and forth through the results.</p>
<p>What's a good algorithm to implement this pattern without bringing the entire table to the client and then filtering the data on the client. How do you bring just the records you want to display to the user?</p>
<p>Does LINQ simplify the solution?</p>
| [
{
"answer_id": 10194,
"author": "Michael Stum",
"author_id": 91,
"author_profile": "https://Stackoverflow.com/users/91",
"pm_score": 5,
"selected": true,
"text": "<p>On MS SQL Server 2005 and above, <a href=\"http://msdn.microsoft.com/en-us/library/ms186734.aspx\" rel=\"noreferrer\">ROW_NUMBER()</a> seems to work:</p>\n\n<p><a href=\"http://blogs.x2line.com/al/archive/2005/11/18/1323.aspx\" rel=\"noreferrer\">T-SQL: Paging with ROW_NUMBER()</a></p>\n\n<pre><code>DECLARE @PageNum AS INT;\nDECLARE @PageSize AS INT;\nSET @PageNum = 2;\nSET @PageSize = 10;\n\nWITH OrdersRN AS\n(\n SELECT ROW_NUMBER() OVER(ORDER BY OrderDate, OrderID) AS RowNum\n ,OrderID\n ,OrderDate\n ,CustomerID\n ,EmployeeID\n FROM dbo.Orders\n)\n\nSELECT * \n FROM OrdersRN\n WHERE RowNum BETWEEN (@PageNum - 1) * @PageSize + 1 \n AND @PageNum * @PageSize\n ORDER BY OrderDate\n ,OrderID;\n</code></pre>\n"
},
{
"answer_id": 10197,
"author": "Vaibhav",
"author_id": 380,
"author_profile": "https://Stackoverflow.com/users/380",
"pm_score": 1,
"selected": false,
"text": "<p>Actually, LINQ has Skip and Take methods which can be combined to choose which records are fetched.</p>\n<p>Check those out.</p>\n<p>For DB: <a href=\"http://web.archive.org/web/20170901080057/http://www.singingeels.com:80/Articles/Pagination_In_SQL_Server_2005.aspx\" rel=\"nofollow noreferrer\">Pagination In SQL Server 2005</a></p>\n"
},
{
"answer_id": 10227,
"author": "Mark Harrison",
"author_id": 116,
"author_profile": "https://Stackoverflow.com/users/116",
"pm_score": 1,
"selected": false,
"text": "<p>Oracle Solution:</p>\n\n<pre><code>select * from (\n select a.*, rownum rnum from (\n YOUR_QUERY_GOES_HERE -- including the order by\n ) a\n where rownum <= MAX_ROW\n ) where rnum >= MIN_ROW\n</code></pre>\n"
},
{
"answer_id": 10282,
"author": "Rory MacLeod",
"author_id": 1016,
"author_profile": "https://Stackoverflow.com/users/1016",
"pm_score": 3,
"selected": false,
"text": "<p>I'd recommend either using LINQ, or try to copy what it does. I've got an app where I use the LINQ Take and Skip methods to retrieve paged data. The code looks something like this:</p>\n\n<pre><code>MyDataContext db = new MyDataContext();\nvar results = db.Products\n .Skip((pageNumber - 1) * pageSize)\n .Take(pageSize);\n</code></pre>\n\n<p>Running SQL Server Profiler reveals that LINQ is converting this query into SQL similar to:</p>\n\n<pre><code>SELECT [ProductId], [Name], [Cost], and so on...\nFROM (\n SELECT [ProductId], [Name], [Cost], [ROW_NUMBER]\n FROM (\n SELECT ROW_NUMBER() OVER (ORDER BY [Name]) AS [ROW_NUMBER], \n [ProductId], [Name], [Cost]\n FROM [Products]\n )\n WHERE [ROW_NUMBER] BETWEEN 10 AND 20\n)\nORDER BY [ROW_NUMBER]\n</code></pre>\n\n<p>In plain English:<br>\n1. Filter your rows and use the ROW_NUMBER function to add row numbers in the order you want.<br>\n2. Filter (1) to return only the row numbers you want on your page.<br>\n3. Sort (2) by the row number, which is the same as the order you wanted (in this case, by Name).</p>\n"
},
{
"answer_id": 12799,
"author": "Grzegorz Gierlik",
"author_id": 1483,
"author_profile": "https://Stackoverflow.com/users/1483",
"pm_score": 1,
"selected": false,
"text": "<p>There are a few solutions which I use with MS SQL 2005.</p>\n\n<p>One of them is ROW_NUMBER(). But, personally, I don't like ROW_NUMBER() because it doesn't work for big results (DB which I work on is really big -- over 1TB data running thousands of queries in second -- you know -- big social networking site).</p>\n\n<p>Here are my favourite solution.</p>\n\n<p>I will use kind of pseudo code of T-SQL.</p>\n\n<p>Let's find 2nd page of users sorted by forename, surname, where each page has 10 records.</p>\n\n<pre><code>@page = 2 -- input parameter\n@size = 10 -- can be optional input parameter\n\nif @page < 1 then begin\n @page = 1 -- check page number\nend\n@start = (@page-1) * @size + 1 -- @page starts at record no @start\n\n-- find the beginning of page @page\nSELECT TOP (@start)\n @forename = forename,\n @surname = surname\n @id = id\nFROM\n users\nORDER BY\n forename,\n surname,\n id -- to keep correct order in case of have two John Smith.\n\n-- select @size records starting from @start\nSELECT TOP (@size)\n id,\n forename,\n surname\nFROM\n users\nWHERE\n (forename = @forename and surname = @surname and id >= @id) -- the same name and surname, but bigger id\n OR (forename = @forename and surname > @surname) -- the same name, but bigger surname, id doesn't matter\n OR (forename > @forename) -- bigger forename, the rest doesn't matter\nORDER BY\n forename,\n surname,\n id\n</code></pre>\n"
},
{
"answer_id": 12820,
"author": "Adam Lassek",
"author_id": 1249,
"author_profile": "https://Stackoverflow.com/users/1249",
"pm_score": 2,
"selected": false,
"text": "<p>LINQ combined with lambda expressions and anonymous classes in .Net 3.5 <em>hugely</em> simplifies this sort of thing.</p>\n\n<p>Querying the database:</p>\n\n<pre><code>var customers = from c in db.customers\n join p in db.purchases on c.CustomerID equals p.CustomerID\n where p.purchases > 5\n select c;\n</code></pre>\n\n<p>Number of records per page:</p>\n\n<pre><code>customers = customers.Skip(pageNum * pageSize).Take(pageSize);\n</code></pre>\n\n<p>Sorting by any column:</p>\n\n<pre><code>customers = customers.OrderBy(c => c.LastName);\n</code></pre>\n\n<p>Getting only selected fields from server:</p>\n\n<pre><code>var customers = from c in db.customers\n join p in db.purchases on c.CustomerID equals p.CustomerID\n where p.purchases > 5\n select new\n {\n CustomerID = c.CustomerID,\n FirstName = c.FirstName,\n LastName = c.LastName\n };\n</code></pre>\n\n<p>This creates a statically-typed anonymous class in which you can access its properties:</p>\n\n<pre><code>var firstCustomer = customer.First();\nint id = firstCustomer.CustomerID;\n</code></pre>\n\n<p>Results from queries are lazy-loaded by default, so you aren't talking to the database until you actually need the data. LINQ in .Net also greatly simplifies updates by keeping a datacontext of any changes you have made, and only updating the fields which you change.</p>\n"
},
{
"answer_id": 56989,
"author": "Loofer",
"author_id": 5552,
"author_profile": "https://Stackoverflow.com/users/5552",
"pm_score": 0,
"selected": false,
"text": "<p>There is a discussion about this <a href=\"https://web.archive.org/web/20211020131201/https://www.4guysfromrolla.com/webtech/042606-1.shtml\" rel=\"nofollow noreferrer\">Here</a></p>\n\n<p>The technique gets page number 100,000 from a 150,000 line database in 78ms</p>\n\n<blockquote>\n <p>Using optimizer knowledge and SET ROWCOUNT, the first EmployeeID in the page that is requested is stored in a local variable for a starting point. Next, SET ROWCOUNT to the maximum number of records that is requested in @maximumRows. This allows paging the result set in a much more efficient manner. Using this method also takes advantage of pre-existing indexes on the table as it goes directly to the base table and not to a locally created table. </p>\n</blockquote>\n\n<p>I am afraid I am not able to judge if it is better than the current accepted answer.</p>\n"
},
{
"answer_id": 19610367,
"author": "Lukas Eder",
"author_id": 521799,
"author_profile": "https://Stackoverflow.com/users/521799",
"pm_score": 3,
"selected": false,
"text": "<p>There are essentially two ways of doing pagination in the database (I'm assuming you're using SQL Server):</p>\n\n<h3>Using OFFSET</h3>\n\n<p>Others have explained how the <code>ROW_NUMBER() OVER()</code> ranking function can be used to perform pages. It's worth mentioning that SQL Server 2012 finally included support for the SQL standard <a href=\"http://technet.microsoft.com/en-us/library/gg699618.aspx\" rel=\"nofollow noreferrer\"><code>OFFSET .. FETCH</code></a> clause:</p>\n\n<pre><code>SELECT first_name, last_name, score\nFROM players\nORDER BY score DESC\nOFFSET 40 ROWS FETCH NEXT 10 ROWS ONLY\n</code></pre>\n\n<p>If you're using SQL Server 2012 and backwards-compatibility is not an issue, you should probably prefer this clause as it will be executed more optimally by SQL Server in corner cases.</p>\n\n<h3>Using the SEEK Method</h3>\n\n<p>There is an entirely different, much faster, but less known way to perform paging in SQL. This is often called the \"seek method\" as described in <a href=\"http://blog.jooq.org/2013/10/26/faster-sql-paging-with-jooq-using-the-seek-method/\" rel=\"nofollow noreferrer\">this blog post here</a>.</p>\n\n<pre><code>SELECT TOP 10 first_name, last_name, score\nFROM players\nWHERE (score < @previousScore)\n OR (score = @previousScore AND player_id < @previousPlayerId)\nORDER BY score DESC, player_id DESC\n</code></pre>\n\n<p>The <code>@previousScore</code> and <code>@previousPlayerId</code> values are the respective values of the last record from the previous page. This allows you to fetch the \"next\" page. If the <code>ORDER BY</code> direction is <code>ASC</code>, simply use <code>></code> instead.</p>\n\n<p>With the above method, you cannot immediately jump to page 4 without having first fetched the previous 40 records. But often, you do not want to jump that far anyway. Instead, you get a much faster query that might be able to fetch data in constant time, depending on your indexing. Plus, your pages remain \"stable\", no matter if the underlying data changes (e.g. on page 1, while you're on page 4).</p>\n\n<p>This is the best way to implement paging when lazy loading more data in web applications, for instance.</p>\n\n<p>Note, the \"seek method\" is also called <a href=\"https://stackoverflow.com/a/3215973/521799\">keyset paging</a>.</p>\n"
}
] | 2008/08/13 | [
"https://Stackoverflow.com/questions/10190",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/373/"
] | Many applications have grids that display data from a database table one page at a time. Many of them also let the user pick the number of records per page, sort by any column, and navigate back and forth through the results.
What's a good algorithm to implement this pattern without bringing the entire table to the client and then filtering the data on the client. How do you bring just the records you want to display to the user?
Does LINQ simplify the solution? | On MS SQL Server 2005 and above, [ROW\_NUMBER()](http://msdn.microsoft.com/en-us/library/ms186734.aspx) seems to work:
[T-SQL: Paging with ROW\_NUMBER()](http://blogs.x2line.com/al/archive/2005/11/18/1323.aspx)
```
DECLARE @PageNum AS INT;
DECLARE @PageSize AS INT;
SET @PageNum = 2;
SET @PageSize = 10;
WITH OrdersRN AS
(
SELECT ROW_NUMBER() OVER(ORDER BY OrderDate, OrderID) AS RowNum
,OrderID
,OrderDate
,CustomerID
,EmployeeID
FROM dbo.Orders
)
SELECT *
FROM OrdersRN
WHERE RowNum BETWEEN (@PageNum - 1) * @PageSize + 1
AND @PageNum * @PageSize
ORDER BY OrderDate
,OrderID;
``` |
10,205 | <p>I'm looking at parsing a delimited string, something on the order of</p>
<p>a,b,c</p>
<p>But this is a very simple example, and parsing delimited data can get complex; for instance</p>
<p>1,"Your simple algorithm, it fails",True</p>
<p>would blow your naiive string.Split implementation to bits. Is there anything I can freely use/steal/copy and paste that offers a relatively bulletproof solution to parsing delimited text? .NET, plox.</p>
<p><em>Update:</em> I decided to go with the <a href="http://msdn.microsoft.com/en-us/library/f68t4563.aspx" rel="nofollow noreferrer">TextFieldParser</a>, which is part of VB.NET's pile of goodies hidden away in Microsoft.VisualBasic.DLL.</p>
| [
{
"answer_id": 10210,
"author": "Vaibhav",
"author_id": 380,
"author_profile": "https://Stackoverflow.com/users/380",
"pm_score": 0,
"selected": false,
"text": "<p>I am thinking that a generic framework would need to specify between two things:\n1. What are the delimiting characters.\n2. Under what condition do those characters not count (such as when they are between quotes).</p>\n\n<p>I think it may just be better off writing custom logic for every time you need to do something like this.</p>\n"
},
{
"answer_id": 10217,
"author": "Michael Stum",
"author_id": 91,
"author_profile": "https://Stackoverflow.com/users/91",
"pm_score": 2,
"selected": false,
"text": "<p>I am not aware of any framework, but a simple state machine works:</p>\n\n<ul>\n<li>State 1: Read every char until you hit a \" or a ,\n\n<ul>\n<li>In case of a \": Move to State 2</li>\n<li>In case of a ,: Move to State 3</li>\n<li>In case of the end of file: Move to state 4</li>\n</ul></li>\n<li>State 2: Read every char until you hit a \"\n\n<ul>\n<li>In case of a \": Move to State 1</li>\n<li>In case of the end of the file: Either Move to State 4 or signal an error because of an unterminated string</li>\n</ul></li>\n<li>State 3: Add the current buffer to the output array, move the cursor forward behind the , and back to State 1.</li>\n<li>State 4: this is the final state, does nothing except returning the output array.</li>\n</ul>\n"
},
{
"answer_id": 10222,
"author": "Patrick McElhaney",
"author_id": 437,
"author_profile": "https://Stackoverflow.com/users/437",
"pm_score": 1,
"selected": false,
"text": "<p>There are some good answers here: <a href=\"https://stackoverflow.com/questions/6209/split-a-string-ignoring-quoted-sections\">Split a string ignoring quoted sections</a></p>\n\n<p>You might want to rephrase your question to something more precise (e.g. <strong>What code snippet or library I can use to parse CSV data in .NET</strong>?). </p>\n"
},
{
"answer_id": 10223,
"author": "Stu",
"author_id": 414,
"author_profile": "https://Stackoverflow.com/users/414",
"pm_score": 2,
"selected": false,
"text": "<p>Such as</p>\n\n<pre><code>var elements = new List<string>();\nvar current = new StringBuilder();\nvar p = 0;\n\nwhile (p < internalLine.Length) {\n if (internalLine[p] == '\"') {\n p++;\n\n while (internalLine[p] != '\"') {\n current.Append(internalLine[p]);\n p++;\n }\n\n // Skip past last ',\n p += 2;\n }\n else {\n while ((p < internalLine.Length) && (internalLine[p] != ',')) {\n current.Append(internalLine[p]);\n p++;\n }\n\n // Skip past ,\n p++;\n }\n\n elements.Add(current.ToString());\n current.Length = 0;\n}\n</code></pre>\n"
},
{
"answer_id": 10224,
"author": "Keith",
"author_id": 905,
"author_profile": "https://Stackoverflow.com/users/905",
"pm_score": 0,
"selected": false,
"text": "<p>Simplest way is just to split the string into a char array and look for your string determiners and split char. </p>\n\n<p>It should be relatively easy to unit test.</p>\n\n<p>You can wrap it in an extension method similar to the basic .Spilt method.</p>\n"
},
{
"answer_id": 10262,
"author": "Jedi Master Spooky",
"author_id": 1154,
"author_profile": "https://Stackoverflow.com/users/1154",
"pm_score": 3,
"selected": true,
"text": "<p>I use this to read from a file</p>\n\n<pre><code>string filename = @textBox1.Text;\nstring[] fields;\nstring[] delimiter = new string[] {\"|\"};\nusing (Microsoft.VisualBasic.FileIO.TextFieldParser parser =\n new Microsoft.VisualBasic.FileIO.TextFieldParser(filename)) {\n parser.Delimiters = delimiter;\n parser.HasFieldsEnclosedInQuotes = false;\n\n while (!parser.EndOfData) {\n fields = parser.ReadFields();\n //Do what you need\n }\n}\n</code></pre>\n\n<p>I am sure someone here can transform this to parser a string that is in memory.</p>\n"
},
{
"answer_id": 10307,
"author": "Dillie-O",
"author_id": 71,
"author_profile": "https://Stackoverflow.com/users/71",
"pm_score": 1,
"selected": false,
"text": "<p>To do a shameless plug, I've been working on a library for a while called <a href=\"http://www.codeplex.com/fotelo\" rel=\"nofollow noreferrer\">fotelo</a> (Formatted Text Loader) that I use to quickly parse large amounts of text based off of delimiter, position, or regex. For a quick string it is overkill, but if you're working with logs or large amounts, it may be just what you need. It works off a control file model similar to SQL*Loader (kind of the inspiration behind it).</p>\n"
},
{
"answer_id": 265861,
"author": "rohancragg",
"author_id": 5351,
"author_profile": "https://Stackoverflow.com/users/5351",
"pm_score": 2,
"selected": false,
"text": "<p>A very complrehesive library can be found here: <a href=\"http://www.filehelpers.com/\" rel=\"nofollow noreferrer\">FileHelpers</a></p>\n"
},
{
"answer_id": 6533735,
"author": "gjvdkamp",
"author_id": 65747,
"author_profile": "https://Stackoverflow.com/users/65747",
"pm_score": 1,
"selected": false,
"text": "<p>Better late than never (add to the completeness of SO):</p>\n\n<p><a href=\"http://www.codeproject.com/KB/database/CsvReader.aspx\" rel=\"nofollow\">http://www.codeproject.com/KB/database/CsvReader.aspx</a></p>\n\n<p>This one ff-ing rules. </p>\n\n<p>GJ</p>\n"
}
] | 2008/08/13 | [
"https://Stackoverflow.com/questions/10205",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] | I'm looking at parsing a delimited string, something on the order of
a,b,c
But this is a very simple example, and parsing delimited data can get complex; for instance
1,"Your simple algorithm, it fails",True
would blow your naiive string.Split implementation to bits. Is there anything I can freely use/steal/copy and paste that offers a relatively bulletproof solution to parsing delimited text? .NET, plox.
*Update:* I decided to go with the [TextFieldParser](http://msdn.microsoft.com/en-us/library/f68t4563.aspx), which is part of VB.NET's pile of goodies hidden away in Microsoft.VisualBasic.DLL. | I use this to read from a file
```
string filename = @textBox1.Text;
string[] fields;
string[] delimiter = new string[] {"|"};
using (Microsoft.VisualBasic.FileIO.TextFieldParser parser =
new Microsoft.VisualBasic.FileIO.TextFieldParser(filename)) {
parser.Delimiters = delimiter;
parser.HasFieldsEnclosedInQuotes = false;
while (!parser.EndOfData) {
fields = parser.ReadFields();
//Do what you need
}
}
```
I am sure someone here can transform this to parser a string that is in memory. |
10,229 | <p>Consider this problem: I have a program which should fetch (let's say) 100 records from a database, and then for each one it should get updated information from a web service. There are two ways to introduce parallelism in this scenario:</p>
<ol>
<li><p>I start each request to the web service on a new Thread. The number of simultaneous threads is controlled by some external parameter (or dynamically adjusted somehow).</p></li>
<li><p>I create smaller batches (let's say of 10 records each) and launch each batch on a separate thread (so taking our example, 10 threads).</p></li>
</ol>
<p>Which is a better approach, and why do you think so?</p>
| [
{
"answer_id": 10264,
"author": "Derek Park",
"author_id": 872,
"author_profile": "https://Stackoverflow.com/users/872",
"pm_score": 2,
"selected": false,
"text": "<p>Two things to consider.</p>\n<h3>1. How long will it take to process a record?</h3>\n<p>If record processing is very quick, the overhead of handing off records to threads can become a bottleneck. In this case, you would want to bundle records so that you don't have to hand them off so often.</p>\n<p>If record processing is reasonably long-running, the difference will be negligible, so the simpler approach (1 record per thread) is probably the best.</p>\n<h3>2. How many threads are you planning on starting?</h3>\n<p>If you aren't using a threadpool, I think you either need to manually limit the number of threads, or you need to break the data into big chunks. Starting a new thread for every record will leave your system thrashing if the number of records get large.</p>\n"
},
{
"answer_id": 10291,
"author": "Hugo",
"author_id": 972,
"author_profile": "https://Stackoverflow.com/users/972",
"pm_score": 0,
"selected": false,
"text": "<p>The computer running the program is probably not the bottleneck, so:\nRemember that the HTTP protocol has a keep-alive header, that lets you send several GET requests on the same sockets, which saves you from the TCP/IP hand shake. Unfortunately I don't know how to use that in the .net libraries. (Should be possible.)</p>\n\n<p>There will probably also be a delay in answering your requests. You could try making sure that you allways have a given number of outstanding requests to the server.</p>\n"
},
{
"answer_id": 10296,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 0,
"selected": false,
"text": "<p>Get the <a href=\"http://www.microsoft.com/downloads/details.aspx?FamilyID=e848dc1d-5be3-4941-8705-024bc7f180ba\" rel=\"nofollow noreferrer\">Parallel Fx</a>. Look at the BlockingCollection. Use a thread to feed it batches of records, and 1 to n threads pulling records off the collection to service. You can control the rate at which the collection is fed, and the number of threads that call to web services. Make it configurable via a ConfigSection, and make it generic by feeding the collection Action delegates, and you'll have a nice little batcher you can reuse to your heart's content.</p>\n"
},
{
"answer_id": 10484,
"author": "Orion Edwards",
"author_id": 234,
"author_profile": "https://Stackoverflow.com/users/234",
"pm_score": 4,
"selected": true,
"text": "<p>Option 3 is the best:</p>\n\n<p>Use Async IO.</p>\n\n<p>Unless your request processing is complex and heavy, your program is going to spend 99% of it's time waiting for the HTTP requests.</p>\n\n<p>This is exactly what Async IO is designed for - Let the windows networking stack (or .net framework or whatever) worry about all the waiting, and just use a single thread to dispatch and 'pick up' the results.</p>\n\n<p>Unfortunately the .NET framework makes it a right pain in the ass. It's easier if you're just using raw sockets or the Win32 api. Here's a (tested!) example using C#3 anyway:</p>\n\n<pre><code>using System.Net; // need this somewhere\n\n// need to declare an class so we can cast our state object back out\nclass RequestState {\n public WebRequest Request { get; set; }\n}\n\nstatic void Main( string[] args ) {\n // stupid cast neccessary to create the request\n HttpWebRequest request = WebRequest.Create( \"http://www.stackoverflow.com\" ) as HttpWebRequest;\n\n request.BeginGetResponse(\n /* callback to be invoked when finished */\n (asyncResult) => { \n // fetch the request object out of the AsyncState\n var state = (RequestState)asyncResult.AsyncState; \n var webResponse = state.Request.EndGetResponse( asyncResult ) as HttpWebResponse;\n\n // there we go;\n Debug.Assert( webResponse.StatusCode == HttpStatusCode.OK ); \n\n Console.WriteLine( \"Got Response from server:\" + webResponse.Server );\n },\n /* pass the request through to our callback */\n new RequestState { Request = request } \n );\n\n // blah\n Console.WriteLine( \"Waiting for response. Press a key to quit\" );\n Console.ReadKey();\n}\n</code></pre>\n\n<p>EDIT:</p>\n\n<p>In the case of .NET, the 'completion callback' actually gets fired in a ThreadPool thread, not in your main thread, so you will still need to lock any shared resources, but it still saves you all the trouble of managing threads.</p>\n"
}
] | 2008/08/13 | [
"https://Stackoverflow.com/questions/10229",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/380/"
] | Consider this problem: I have a program which should fetch (let's say) 100 records from a database, and then for each one it should get updated information from a web service. There are two ways to introduce parallelism in this scenario:
1. I start each request to the web service on a new Thread. The number of simultaneous threads is controlled by some external parameter (or dynamically adjusted somehow).
2. I create smaller batches (let's say of 10 records each) and launch each batch on a separate thread (so taking our example, 10 threads).
Which is a better approach, and why do you think so? | Option 3 is the best:
Use Async IO.
Unless your request processing is complex and heavy, your program is going to spend 99% of it's time waiting for the HTTP requests.
This is exactly what Async IO is designed for - Let the windows networking stack (or .net framework or whatever) worry about all the waiting, and just use a single thread to dispatch and 'pick up' the results.
Unfortunately the .NET framework makes it a right pain in the ass. It's easier if you're just using raw sockets or the Win32 api. Here's a (tested!) example using C#3 anyway:
```
using System.Net; // need this somewhere
// need to declare an class so we can cast our state object back out
class RequestState {
public WebRequest Request { get; set; }
}
static void Main( string[] args ) {
// stupid cast neccessary to create the request
HttpWebRequest request = WebRequest.Create( "http://www.stackoverflow.com" ) as HttpWebRequest;
request.BeginGetResponse(
/* callback to be invoked when finished */
(asyncResult) => {
// fetch the request object out of the AsyncState
var state = (RequestState)asyncResult.AsyncState;
var webResponse = state.Request.EndGetResponse( asyncResult ) as HttpWebResponse;
// there we go;
Debug.Assert( webResponse.StatusCode == HttpStatusCode.OK );
Console.WriteLine( "Got Response from server:" + webResponse.Server );
},
/* pass the request through to our callback */
new RequestState { Request = request }
);
// blah
Console.WriteLine( "Waiting for response. Press a key to quit" );
Console.ReadKey();
}
```
EDIT:
In the case of .NET, the 'completion callback' actually gets fired in a ThreadPool thread, not in your main thread, so you will still need to lock any shared resources, but it still saves you all the trouble of managing threads. |
10,314 | <p>Being new to Objective-C (but a long term C/++) programmer I'm looking for advice/recommendations on naming conventions for variables.</p>
<p>My personal preference would be to utilize a prefix for instance variables both for clarity within functions and to prevent shadowing of function parameters. However I'm a fan of properties which rules out prefixes (unless you also prefix your property names, which doesn't work too well and looks daft). Similarly I could use the "self.variable" convention, but only if I make EVERYTHING a property.</p>
<p>So given the code below what's your preferred naming style for instance/function variables? And if you don't bother, how do you deal with shadowing on function params?</p>
<pre><code>@interface GridItem : NSObject
{
CGRect _rect;
...
}
@end
-(void) initFromRect:(CGRect)rect
{
_rect = rect;
...
}
</code></pre>
<p>Cheers!</p>
| [
{
"answer_id": 10342,
"author": "Kristopher Johnson",
"author_id": 1175,
"author_profile": "https://Stackoverflow.com/users/1175",
"pm_score": 1,
"selected": false,
"text": "<p>I don't like using underscores as prefixes for any identifiers, because C and C++ both reserve certain underscore prefixes for use by the implementation.</p>\n\n<p>I think using \"self.variable\" is ugly.</p>\n\n<p>In general, I use unadorned identifiers (that is, no prefixes nor suffixes) for instance variables. If your class is so complicated that you can't remember the instance variables, you're in trouble. So for your example, I'd use \"rect\" as the name of the instance variable and \"newRect\" or \"aRect\" as the parameter name.</p>\n"
},
{
"answer_id": 10344,
"author": "TheSmurf",
"author_id": 1975282,
"author_profile": "https://Stackoverflow.com/users/1975282",
"pm_score": 2,
"selected": false,
"text": "<p>Personally, I follow the Cocoa naming conventions, using camel-casing for functions and variables, and capitalized camel-casing for object names (without the leading NS of course).</p>\n\n<p>I find type prefixing makes code more opaque to anyone who didn't write it (since everyone invariably uses different prefixes), and in a modern IDE it's not really that difficult to figure out something's type.</p>\n"
},
{
"answer_id": 11994,
"author": "Chris Hanson",
"author_id": 714,
"author_profile": "https://Stackoverflow.com/users/714",
"pm_score": 5,
"selected": true,
"text": "<p>Most Cocoa projects use underbar as a non-<code>IBOutlet</code> instance variable prefix, and use no prefix for <code>IBOutlet</code> instance variables.</p>\n\n<p>The reason I don't use underbars for <code>IBOutlet</code> instance variables is that when a nib file is loaded, if you have a setter method for a connected outlet, that setter will be called. <em>However</em> this mechanism does <em>not</em> use Key-Value Coding, so an IBOutlet whose name is prefixed with an underbar (<em>e.g.</em> <code>_myField</code>) will <em>not</em> be set unless the setter is named exactly like the outlet (<em>e.g.</em> <code>set_myField:</code>), which is non-standard and gross.</p>\n\n<p>Also, be aware that using properties like <code>self.myProp</code> is <strong>not</strong> the same as accessing instance variables. You are <strong>sending a message</strong> when you use a property, just like if you used bracket notation like <code>[self myProp]</code>. All properties do is give you a concise syntax for specifying both the getter and setter in a single line, and allow you to synthesize their implementation; they do not actually short-circuit the message dispatch mechanism. If you want to access an instance variable directly but prefix it with <code>self</code> you need to treat <code>self</code> as a pointer, like <code>self->myProp</code> which really is a C-style field access.</p>\n\n<p>Finally, never use Hungarian notation when writing Cocoa code, and shy away from other prefixes like \"f\" and \"m_\" — that will mark the code as having been written by someone who doesn't \"get it\" and will cause it to be viewed by suspicion by other Cocoa developers.</p>\n\n<p>In general, follow the advice in the <a href=\"http://developer.apple.com/documentation/Cocoa/Conceptual/CodingGuidelines/index.html\" rel=\"noreferrer\" title=\"Coding Guidelines for Cocoa\">Coding Guidelines for Cocoa</a> document at the <a href=\"http://developer.apple.com/\" rel=\"noreferrer\" title=\"Apple Developer Connection\">Apple Developer Connection</a>, and other developers will be able to pick up and understand your code, and your code will work well with all of the Cocoa features that use runtime introspection.</p>\n\n<p>Here's what a window controller class might look like, using my conventions:</p>\n\n<pre><code>// EmployeeWindowController.h\n#import <AppKit/NSWindowController.h>\n\n@interface EmployeeWindowController : NSWindowController {\n@private\n // model object this window is presenting\n Employee *_employee;\n\n // outlets connected to views in the window\n IBOutlet NSTextField *nameField;\n IBOutlet NSTextField *titleField;\n}\n\n- (id)initWithEmployee:(Employee *)employee;\n\n@property(readwrite, retain) Employee *employee;\n\n@end\n\n// EmployeeWindowController.m\n#import \"EmployeeWindowController.h\"\n\n@implementation EmployeeWindowController\n\n@synthesize employee = _employee;\n\n- (id)initWithEmployee:(Employee *)employee {\n if (self = [super initWithWindowNibName:@\"Employee\"]) {\n _employee = [employee retain];\n }\n return self;\n}\n\n- (void)dealloc {\n [_employee release];\n\n [super dealloc];\n}\n\n- (void)windowDidLoad {\n // populates the window's controls, not necessary if using bindings\n [nameField setStringValue:self.employee.name];\n [titleField setStringValue:self.employee.title];\n}\n\n@end\n</code></pre>\n\n<p>You'll see that I'm using the instance variable that references an <code>Employee</code> directly in my <code>-init</code> and <code>-dealloc</code> method, while I'm using the property in other methods. That's generally a good pattern with properties: Only ever touch the underlying instance variable for a property in initializers, in <code>-dealloc</code>, and in the getter and setter for the property.</p>\n"
},
{
"answer_id": 11997,
"author": "Chris Hanson",
"author_id": 714,
"author_profile": "https://Stackoverflow.com/users/714",
"pm_score": 1,
"selected": false,
"text": "<p>Andrew: There actually are plenty of Cocoa developers who don't use instance variable prefixes at all. It's also extremely common in the Smalltalk world (in fact, I'd say it's nearly unheard-of in Smalltalk to use prefixes on instance variables).</p>\n\n<p>Prefixes on instance variables have always struck me as a C++-ism that was brought over to Java and then to C#. Since the Objective-C world was largely parallel to the C++ world, where as the Java and C# worlds are successors to it, that would explain the \"cultural\" difference you might see on this between the different sets of developers.</p>\n"
},
{
"answer_id": 61924,
"author": "Kendall Helmstetter Gelner",
"author_id": 6330,
"author_profile": "https://Stackoverflow.com/users/6330",
"pm_score": 2,
"selected": false,
"text": "<p>With the introduction of properties I see no need for prefixing \"_\" to class instance variables. You can set a simple rule (described in your header file) that any variables to be accessed external to the class must be accessed via the property, or by using custom methods on the class to affect values. This to me seems much cleaner than having names with \"_\" stuck on the front of them. It also properly encapsulates the values so that you can control how they are changed.</p>\n"
},
{
"answer_id": 64371,
"author": "Scott Marcy",
"author_id": 8168,
"author_profile": "https://Stackoverflow.com/users/8168",
"pm_score": 2,
"selected": false,
"text": "<p>You can use the underbar prefix on your ivars and still use the non-underbar name for your properties. For synthesized accessors, just do this:</p>\n\n<pre><code>@synthesize foo = _foo;\n</code></pre>\n\n<p>This tells the compiler to synthesize the foo property using the_foo ivar.</p>\n\n<p>If you write your own accessors, then you just use the underbar ivar in your implementation and keep the non-underbar method name.</p>\n"
},
{
"answer_id": 157990,
"author": "schwa",
"author_id": 23113,
"author_profile": "https://Stackoverflow.com/users/23113",
"pm_score": 1,
"selected": false,
"text": "<p>My style is hybrid and really a holdover from PowerPlant days:</p>\n\n<p>THe most useful prefixes I use are \"in\" and \"out\" for function/method parameters. This helps you know what the parameters are for at a glance and really helps prevent conflicts between method parameters and instance variables (how many times have you seen the parameter \"table\" conflict with an instance variable of the same name). E.g.:</p>\n\n<pre><code>- (void)doSomethingWith:(id)inSomeObject error:(NSError **)outError;\n</code></pre>\n\n<p>Then I use the bare name for instance variables and property names:</p>\n\n<p>Then I use \"the\" as a prefix for local variables: theTable, theURL, etc. Again this helps differentiate between local and and instance variables.</p>\n\n<p>Then following PowerPlant styling I use a handful of other prefixes: k for constants, E for enums, g for globals, and s for statics.</p>\n\n<p>I've been using this style for something like 12 years now.</p>\n"
},
{
"answer_id": 278360,
"author": "Dave Dribin",
"author_id": 26825,
"author_profile": "https://Stackoverflow.com/users/26825",
"pm_score": 3,
"selected": false,
"text": "<p>I follow Chris Hanson's advice in regards to the underscore ivar prefix, though I admit I do use underscore's for IBOutlets as well. However, I've recently starting moving my <code>IBOutlet</code> declarations to the <code>@property</code> line, as per <a href=\"https://stackoverflow.com/questions/155964/what-are-best-practices-that-you-use-when-writing-objective-c-and-cocoa#167495\">@mmalc's suggestion</a>. The benefit is that all my ivars now have an underscore and standard KVC setters are called (i.e. <code>setNameField:</code>). Also, the outlet names don't have underscores in Interface Builder.</p>\n\n<pre><code>@interface EmployeeWindowController : NSWindowController {\n@private\n // model object this window is presenting\n Employee *_employee;\n\n // outlets connected to views in the window\n NSTextField *_nameField;\n NSTextField *_titleField;\n}\n\n- (id)initWithEmployee:(Employee *)employee;\n\n@property(readwrite, retain) Employee *employee;\n@property(nonatomic, retain) IBOutlet NSTextField *nameField;\n@property(nonatomic, retain) IBOutlet NSTextField *titleField;\n\n@end\n</code></pre>\n"
},
{
"answer_id": 278387,
"author": "Dave Dribin",
"author_id": 26825,
"author_profile": "https://Stackoverflow.com/users/26825",
"pm_score": 1,
"selected": false,
"text": "<p>While I love using the underscore prefix for ivars, I loathe writing <code>@synthesize</code> lines because of all the duplication (it's not very <a href=\"http://en.wikipedia.org/wiki/Don't_repeat_yourself\" rel=\"nofollow noreferrer\">DRY</a>). I created a macro to help do this and reduce code duplication. Thus, instead of:</p>\n\n<pre><code>@synthesize employee = _employee;\n</code></pre>\n\n<p>I write this:</p>\n\n<pre><code>ddsynthesize(employee);\n</code></pre>\n\n<p>It's a simple macro using token pasting to add an underscore to the right hand side:</p>\n\n<pre><code>#define ddsynthesize(_X_) @synthesize _X_ = _##_X_\n</code></pre>\n\n<p>The only downside is that it will confuse Xcode's refactoring tool, and it won't get renamed, if you rename the property by refactoring.</p>\n"
},
{
"answer_id": 296979,
"author": "Marc Charbonneau",
"author_id": 35136,
"author_profile": "https://Stackoverflow.com/users/35136",
"pm_score": 1,
"selected": false,
"text": "<p>Along with what's been said here, be sure to read the Cocoa documentation on Key Value Observing compliant naming. Strictly following this pattern will help you greatly in the long run.</p>\n"
}
] | 2008/08/13 | [
"https://Stackoverflow.com/questions/10314",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1043/"
] | Being new to Objective-C (but a long term C/++) programmer I'm looking for advice/recommendations on naming conventions for variables.
My personal preference would be to utilize a prefix for instance variables both for clarity within functions and to prevent shadowing of function parameters. However I'm a fan of properties which rules out prefixes (unless you also prefix your property names, which doesn't work too well and looks daft). Similarly I could use the "self.variable" convention, but only if I make EVERYTHING a property.
So given the code below what's your preferred naming style for instance/function variables? And if you don't bother, how do you deal with shadowing on function params?
```
@interface GridItem : NSObject
{
CGRect _rect;
...
}
@end
-(void) initFromRect:(CGRect)rect
{
_rect = rect;
...
}
```
Cheers! | Most Cocoa projects use underbar as a non-`IBOutlet` instance variable prefix, and use no prefix for `IBOutlet` instance variables.
The reason I don't use underbars for `IBOutlet` instance variables is that when a nib file is loaded, if you have a setter method for a connected outlet, that setter will be called. *However* this mechanism does *not* use Key-Value Coding, so an IBOutlet whose name is prefixed with an underbar (*e.g.* `_myField`) will *not* be set unless the setter is named exactly like the outlet (*e.g.* `set_myField:`), which is non-standard and gross.
Also, be aware that using properties like `self.myProp` is **not** the same as accessing instance variables. You are **sending a message** when you use a property, just like if you used bracket notation like `[self myProp]`. All properties do is give you a concise syntax for specifying both the getter and setter in a single line, and allow you to synthesize their implementation; they do not actually short-circuit the message dispatch mechanism. If you want to access an instance variable directly but prefix it with `self` you need to treat `self` as a pointer, like `self->myProp` which really is a C-style field access.
Finally, never use Hungarian notation when writing Cocoa code, and shy away from other prefixes like "f" and "m\_" — that will mark the code as having been written by someone who doesn't "get it" and will cause it to be viewed by suspicion by other Cocoa developers.
In general, follow the advice in the [Coding Guidelines for Cocoa](http://developer.apple.com/documentation/Cocoa/Conceptual/CodingGuidelines/index.html "Coding Guidelines for Cocoa") document at the [Apple Developer Connection](http://developer.apple.com/ "Apple Developer Connection"), and other developers will be able to pick up and understand your code, and your code will work well with all of the Cocoa features that use runtime introspection.
Here's what a window controller class might look like, using my conventions:
```
// EmployeeWindowController.h
#import <AppKit/NSWindowController.h>
@interface EmployeeWindowController : NSWindowController {
@private
// model object this window is presenting
Employee *_employee;
// outlets connected to views in the window
IBOutlet NSTextField *nameField;
IBOutlet NSTextField *titleField;
}
- (id)initWithEmployee:(Employee *)employee;
@property(readwrite, retain) Employee *employee;
@end
// EmployeeWindowController.m
#import "EmployeeWindowController.h"
@implementation EmployeeWindowController
@synthesize employee = _employee;
- (id)initWithEmployee:(Employee *)employee {
if (self = [super initWithWindowNibName:@"Employee"]) {
_employee = [employee retain];
}
return self;
}
- (void)dealloc {
[_employee release];
[super dealloc];
}
- (void)windowDidLoad {
// populates the window's controls, not necessary if using bindings
[nameField setStringValue:self.employee.name];
[titleField setStringValue:self.employee.title];
}
@end
```
You'll see that I'm using the instance variable that references an `Employee` directly in my `-init` and `-dealloc` method, while I'm using the property in other methods. That's generally a good pattern with properties: Only ever touch the underlying instance variable for a property in initializers, in `-dealloc`, and in the getter and setter for the property. |
10,323 | <p>I recently read a nice <a href="http://macdevelopertips.com/ruby/using-a-string-as-a-file-in-ruby.html" rel="noreferrer">post</a> on using <code>StringIO</code> in Ruby. What the author doesn't mention, though, is that <code>StringIO</code> is just an "I." There's no "O." You <em>can't</em> do this, for example:</p>
<pre><code>s = StringIO.new
s << 'foo'
s << 'bar'
s.to_s
# => should be "foo\nbar"
# => really is ''`
</code></pre>
<p>Ruby really needs a StringBuffer just like the one Java has. StringBuffers serve two important purposes. First, they let you test the output half of what Ruby's StringIO does. Second, they are useful for building up long strings from small parts -- something that Joel reminds us over and over again is otherwise very very slow.</p>
<p>Is there a good replacement?</p>
<p>It's true that Strings in Ruby are mutable, but that doesn't mean we should always rely on that functionality. If <code>stuff</code> is large, the performance and memory requirements of this, for example, is really bad.</p>
<pre><code>result = stuff.map(&:to_s).join(' ')
</code></pre>
<p>The "correct" way to do this in Java is:</p>
<pre><code>result = StringBuffer.new("")
for(String s : stuff) {
result.append(s);
}
</code></pre>
<p>Though my Java is a bit rusty.</p>
| [
{
"answer_id": 10335,
"author": "Mike Stone",
"author_id": 122,
"author_profile": "https://Stackoverflow.com/users/122",
"pm_score": 2,
"selected": false,
"text": "<p>Well, a StringBuffer is not quite as necessary in Ruby, mainly because Strings in Ruby are mutable... thus you can build up a string by modifying the existing string instead of constructing new strings with each concat.</p>\n\n<p>As a note, you can also use special string syntax where you can build a string which references other variables within the string, which makes for very readable string construction. Consider:</p>\n\n<pre><code>first = \"Mike\"\nlast = \"Stone\"\nname = \"#{first} #{last}\"\n</code></pre>\n\n<p>These strings can also contain expressions, not just variables... such as:</p>\n\n<pre><code>str = \"The count will be: #{count + 1}\"\ncount = count + 1\n</code></pre>\n"
},
{
"answer_id": 10350,
"author": "Mike Stone",
"author_id": 122,
"author_profile": "https://Stackoverflow.com/users/122",
"pm_score": 8,
"selected": true,
"text": "<p>I looked at the ruby documentation for <code>StringIO</code>, and it looks like what you want is <a href=\"http://ruby-doc.org/stdlib/libdoc/stringio/rdoc/classes/StringIO.html#method-i-string\" rel=\"noreferrer\"><code>StringIO#string</code></a>, not <code>StringIO#to_s</code></p>\n\n<p>Thus, change your code to:</p>\n\n<pre><code>s = StringIO.new\ns << 'foo'\ns << 'bar'\ns.string\n</code></pre>\n"
},
{
"answer_id": 10358,
"author": "palmsey",
"author_id": 521,
"author_profile": "https://Stackoverflow.com/users/521",
"pm_score": 4,
"selected": false,
"text": "<p>Your example works in Ruby - I just tried it.</p>\n\n<pre><code>irb(main):001:0> require 'stringio'\n=> true\nirb(main):002:0> s = StringIO.new\n=> #<StringIO:0x2ced9a0>\nirb(main):003:0> s << 'foo'\n=> #<StringIO:0x2ced9a0>\nirb(main):004:0> s << 'bar'\n=> #<StringIO:0x2ced9a0>\nirb(main):005:0> s.string\n=> \"foobar\"\n</code></pre>\n\n<p>Unless I'm missing the reason you're using to_s - that just outputs the object id.</p>\n"
},
{
"answer_id": 1252057,
"author": "Colin Curtin",
"author_id": 69464,
"author_profile": "https://Stackoverflow.com/users/69464",
"pm_score": 5,
"selected": false,
"text": "<p>Like other IO-type objects in Ruby, when you write to an IO, the character pointer advances.</p>\n\n<pre><code>>> s = StringIO.new\n=> #<StringIO:0x3659d4>\n>> s << 'foo'\n=> #<StringIO:0x3659d4>\n>> s << 'bar'\n=> #<StringIO:0x3659d4>\n>> s.pos\n=> 6\n>> s.rewind\n=> 0\n>> s.read\n=> \"foobar\"\n</code></pre>\n"
},
{
"answer_id": 13276313,
"author": "jmanrubia",
"author_id": 469697,
"author_profile": "https://Stackoverflow.com/users/469697",
"pm_score": 5,
"selected": false,
"text": "<p>I did some benchmarks and the fastest approach is using the <code>String#<<</code> method. Using <code>StringIO</code> is a little bit slower.</p>\n\n<pre><code>s = \"\"; Benchmark.measure{5000000.times{s << \"some string\"}}\n=> 3.620000 0.100000 3.720000 ( 3.970463)\n\n>> s = StringIO.new; Benchmark.measure{5000000.times{s << \"some string\"}}\n=> 4.730000 0.120000 4.850000 ( 5.329215)\n</code></pre>\n\n<p>Concatenating strings using the <code>String#+</code> method is the slowest approach by many orders of magnitude:</p>\n\n<pre><code>s = \"\"; Benchmark.measure{10000.times{s = s + \"some string\"}}\n=> 0.700000 0.560000 1.260000 ( 1.420272)\n\ns = \"\"; Benchmark.measure{10000.times{s << \"some string\"}}\n=> 0.000000 0.000000 0.000000 ( 0.005639)\n</code></pre>\n\n<p>So I think the right answer is that the equivalent to Java's <code>StringBuffer</code> is simply using <code>String#<<</code> in Ruby.</p>\n"
}
] | 2008/08/13 | [
"https://Stackoverflow.com/questions/10323",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1190/"
] | I recently read a nice [post](http://macdevelopertips.com/ruby/using-a-string-as-a-file-in-ruby.html) on using `StringIO` in Ruby. What the author doesn't mention, though, is that `StringIO` is just an "I." There's no "O." You *can't* do this, for example:
```
s = StringIO.new
s << 'foo'
s << 'bar'
s.to_s
# => should be "foo\nbar"
# => really is ''`
```
Ruby really needs a StringBuffer just like the one Java has. StringBuffers serve two important purposes. First, they let you test the output half of what Ruby's StringIO does. Second, they are useful for building up long strings from small parts -- something that Joel reminds us over and over again is otherwise very very slow.
Is there a good replacement?
It's true that Strings in Ruby are mutable, but that doesn't mean we should always rely on that functionality. If `stuff` is large, the performance and memory requirements of this, for example, is really bad.
```
result = stuff.map(&:to_s).join(' ')
```
The "correct" way to do this in Java is:
```
result = StringBuffer.new("")
for(String s : stuff) {
result.append(s);
}
```
Though my Java is a bit rusty. | I looked at the ruby documentation for `StringIO`, and it looks like what you want is [`StringIO#string`](http://ruby-doc.org/stdlib/libdoc/stringio/rdoc/classes/StringIO.html#method-i-string), not `StringIO#to_s`
Thus, change your code to:
```
s = StringIO.new
s << 'foo'
s << 'bar'
s.string
``` |
10,349 | <p>I'm sure there is a good (or at least decent) reason for this. What is it?</p>
| [
{
"answer_id": 10354,
"author": "Adam Haile",
"author_id": 194,
"author_profile": "https://Stackoverflow.com/users/194",
"pm_score": 1,
"selected": false,
"text": "<p>It is so that you don't have two things trying to update the control at the same time. (This could happen if the CPU switches to the other thread in the middle of a write/read)\nSame reason you need to use mutexes (or some other synchronization) when accessing shared variables between multiple threads.</p>\n\n<p>Edit:</p>\n\n<blockquote>\n <p>In other languages such as C++ you are\n free to try and do this (without an\n exception being thrown as in\n WinForms), but you'll end up learning\n the hard way!</p>\n</blockquote>\n\n<p>Ahh yes...I switch between C/C++ and C# and therefore was a little more generic then I should've been, sorry... He is correct, you <em>can</em> do this in C/C++, but it will come back to bite you!</p>\n"
},
{
"answer_id": 10359,
"author": "John Sibly",
"author_id": 1078,
"author_profile": "https://Stackoverflow.com/users/1078",
"pm_score": 4,
"selected": true,
"text": "<p>Because you can easily end up with a deadlock (among other issues). </p>\n\n<p>For exmaple, your secondary thread could be trying to update the UI control, but the UI control will be waiting for a resource locked by the secondary thread to be released, so both threads end up waiting for each other to finish. As others have commented this situation is not unique to UI code, but is particularly common.</p>\n\n<p>In other languages such as C++ you are free to try and do this (without an exception being thrown as in WinForms), but your application may freeze and stop responding should a deadlock occur. </p>\n\n<p>Incidentally, you can easily tell the UI thread that you want to update a control, just create a delegate, then call the (asynchronous) BeginInvoke method on that control passing it your delegate. E.g.</p>\n\n<pre><code>myControl.BeginInvoke(myControl.UpdateFunction);\n</code></pre>\n\n<p>This is the equivalent to doing a C++/MFC PostMessage from a worker thread</p>\n"
},
{
"answer_id": 10362,
"author": "Quibblesome",
"author_id": 1143,
"author_profile": "https://Stackoverflow.com/users/1143",
"pm_score": 2,
"selected": false,
"text": "<p>Back in 1.0/1.1 no exception was thrown during debugging, what you got instead was an intermittent run-time hanging scenario. Nice! :)\nTherefore with 2.0 they made this scenario throw an exception and quite rightly so.</p>\n\n<p>The actual reason for this is probably (as Adam Haile states) some kind of concurrency/locky issue. \nNote that the normal .NET api (such as TextBox.Text = \"Hello\";) wraps SEND commands (that require immediate action) which can create issues if performed on separate thread from the one that actions the update. Using Invoke/BeginInvoke uses a POST instead which queues the action.</p>\n\n<p>More information on SEND and POST <a href=\"http://msdn.microsoft.com/en-us/library/ms644927.aspx#posting_sending\" rel=\"nofollow noreferrer\">here</a>.</p>\n"
},
{
"answer_id": 10388,
"author": "Andrew Grant",
"author_id": 1043,
"author_profile": "https://Stackoverflow.com/users/1043",
"pm_score": 1,
"selected": false,
"text": "<p>There would also be the need to implement synchronization within update functions that are sensitive to being called simultaneously. Doing this for UI elements would be costly at both application and OS levels, and completely redundant for the vast majority of code. </p>\n\n<p>Some APIs provide a way to change the current thread ownership of a system so you can temporarily (or permanently) update systems from other threads without needing to resort to inter-thread communication.</p>\n"
},
{
"answer_id": 10439,
"author": "Brian Ensink",
"author_id": 1254,
"author_profile": "https://Stackoverflow.com/users/1254",
"pm_score": 5,
"selected": false,
"text": "<blockquote>\n <p>I think this is a brilliant question -\n and I think there is need of a better\n answer.</p>\n \n <p>Surely the only reason is that there\n is something in a framework somewhere\n that isn't very thread-safe. </p>\n</blockquote>\n\n<p>That \"something\" is almost every single instance member on every single control in System.Windows.Forms.</p>\n\n<p>The MSDN documentation for many controls in System.Windows.Forms, if not all of them, say <em>\"Any public static (Shared in Visual Basic) members of this type are thread safe. Any instance members are not guaranteed to be thread safe.\"</em></p>\n\n<p>This means that instance members such as <code>TextBox.Text {get; set;}</code> are not <strong><em>reentrant</em></strong>.</p>\n\n<p>Making each of those instance members thread safe could introduce a lot of overhead that most applications do not need. Instead the designers of the .Net framework decided, and I think correctly, that the burden of synchronizing access to forms controls from multiple threads should be put on the programmer.</p>\n\n<p>[Edit]</p>\n\n<p>Although this question only asks \"why\" here is a link to an article that explains \"how\":</p>\n\n<p><em>How to: Make Thread-Safe Calls to Windows Forms Controls</em> on MSDN</p>\n\n<p><a href=\"http://msdn.microsoft.com/en-us/library/ms171728.aspx\" rel=\"noreferrer\">http://msdn.microsoft.com/en-us/library/ms171728.aspx</a></p>\n"
},
{
"answer_id": 10462,
"author": "Björn Waide",
"author_id": 1253,
"author_profile": "https://Stackoverflow.com/users/1253",
"pm_score": 3,
"selected": false,
"text": "<p>Although it sounds reasonable Johns answer isn't correct. In fact even when using Invoke you're still not safe not running into dead-lock situations. When dealing with events fired on a background thread using Invoke might even lead to this problem.</p>\n\n<p><br/></p>\n\n<p>The real reason has more to do with race conditions and lays back in ancient Win32 times. I can't explain the details here, the keywords are message pumps, WM_PAINT events and the subtle differences between \"SEND\" and \"POST\".</p>\n\n<p><br/></p>\n\n<p>Further information can be found here <a href=\"http://weblogs.asp.net/justin_rogers/articles/126345.aspx\" rel=\"noreferrer\">here</a> and <a href=\"http://msdn.microsoft.com/en-us/library/ms644927.aspx#posting_sending\" rel=\"noreferrer\">here</a>.</p>\n"
},
{
"answer_id": 197611,
"author": "Chris Hughes",
"author_id": 27405,
"author_profile": "https://Stackoverflow.com/users/27405",
"pm_score": -1,
"selected": false,
"text": "<p>Hmm I'm not pretty sure but I think that when we have a progress controls like waiting bars, progress bars we can update their values from another thread and everything works great without any glitches. </p>\n"
}
] | 2008/08/13 | [
"https://Stackoverflow.com/questions/10349",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/337/"
] | I'm sure there is a good (or at least decent) reason for this. What is it? | Because you can easily end up with a deadlock (among other issues).
For exmaple, your secondary thread could be trying to update the UI control, but the UI control will be waiting for a resource locked by the secondary thread to be released, so both threads end up waiting for each other to finish. As others have commented this situation is not unique to UI code, but is particularly common.
In other languages such as C++ you are free to try and do this (without an exception being thrown as in WinForms), but your application may freeze and stop responding should a deadlock occur.
Incidentally, you can easily tell the UI thread that you want to update a control, just create a delegate, then call the (asynchronous) BeginInvoke method on that control passing it your delegate. E.g.
```
myControl.BeginInvoke(myControl.UpdateFunction);
```
This is the equivalent to doing a C++/MFC PostMessage from a worker thread |
10,366 | <p>I have an absolutely positioned <code>div</code> that I want to show when the user clicks a link. The <code>onclick</code> of the link calls a js function that sets the display of the div to block (also tried: "", <code>inline</code>, <code>table-cell</code>, <code>inline-table</code>, etc). This works great in IE7, not at all in every other browser I've tried (FF2, FF3, Opera 9.5, Safari).</p>
<p>I've tried adding alerts before and after the call, and they show that the display has changed from <code>none</code> to <code>block</code> but the <code>div</code> does not display.</p>
<p>I can get the <code>div</code> to display in FF3 if I change the display value using Firebug's HTML inspector (but not by running javascript through Firebug's console) - so I know it's not just showing up off-screen, etc.</p>
<p>I've tried everything I can think of, including:</p>
<ul>
<li>Using a different doctype (XHTML 1, HTML 4, etc)</li>
<li>Using visibility visible/hidden instead of display block/none</li>
<li>Using inline javascript instead of a function call</li>
<li>Testing from different machines</li>
</ul>
<p>Any ideas about what could cause this?</p>
| [
{
"answer_id": 10368,
"author": "TheSmurf",
"author_id": 1975282,
"author_profile": "https://Stackoverflow.com/users/1975282",
"pm_score": 1,
"selected": false,
"text": "<p>Check the error console (Tools Menu > Error Console in Firefox 3) to make sure that there isn't another error happening that you're not seeing, which is stopping your script from working.</p>\n"
},
{
"answer_id": 10378,
"author": "Serhat Ozgel",
"author_id": 31505,
"author_profile": "https://Stackoverflow.com/users/31505",
"pm_score": 3,
"selected": false,
"text": "<p>Can you provide some markup that reproduce the error?</p>\n\n<p>Your situation must have something to do with your code since I can get this to work on IE, FF3 and Opera 9.5:</p>\n\n<p><div class=\"snippet\" data-lang=\"js\" data-hide=\"false\" data-console=\"true\" data-babel=\"false\">\r\n<div class=\"snippet-code\">\r\n<pre class=\"snippet-code-js lang-js prettyprint-override\"><code>function show() {\r\n var d = document.getElementById('testdiv');\r\n d.style.display = 'block';\r\n}</code></pre>\r\n<pre class=\"snippet-code-css lang-css prettyprint-override\"><code>#testdiv {\r\n position: absolute;\r\n height: 20px;\r\n width: 20px; \r\n display: none;\r\n background-color: red;\r\n}</code></pre>\r\n<pre class=\"snippet-code-html lang-html prettyprint-override\"><code><div id=\"testdiv\"></div>\r\n<a href=\"javascript:show();\">Click me</a></code></pre>\r\n</div>\r\n</div>\r\n</p>\n"
},
{
"answer_id": 10485,
"author": "Lance Fisher",
"author_id": 571,
"author_profile": "https://Stackoverflow.com/users/571",
"pm_score": 1,
"selected": false,
"text": "<p>Try setting the height and width of the div, and make sure it is on top by setting its z-index higher than everything else. If the absolutely positioned div is inside an element that is relatively positioned, it's top and left location is based off the top and left of the relatively positioned element. Try putting your div just under the body element.</p>\n"
},
{
"answer_id": 11197,
"author": "palmsey",
"author_id": 521,
"author_profile": "https://Stackoverflow.com/users/521",
"pm_score": 4,
"selected": true,
"text": "<p>Since setting the properties with javascript never seemed to work, but setting using Firebug's inspect did, I started to suspect that the javascript ID selector was broken - maybe there were multiple items in the DOM with the same ID? The source didn't show that there were, but looping through all divs using javascript I found that that was the case. Here's the function I ended up using to show the popup:</p>\n\n<pre><code>function openPopup(popupID)\n{\n var divs = getObjectsByTagAndClass('div','popupDiv');\n if (divs != undefined && divs != null)\n {\n for (var i = 0; i < divs.length; i++)\n {\n if (divs[i].id == popupID)\n divs[i].style.display = 'block'; \n }\n }\n}\n</code></pre>\n\n<p>(utility function getObjectsByTagAndClass not listed)</p>\n\n<p>Ideally I'll find out why the same item is being inserted multiple times, but I don't have control over the rendering platform, just its inputs.</p>\n\n<p>So when debugging issues like this, <strong>remember to check for duplicate IDs in the DOM, which can break getElementById</strong>.</p>\n\n<p>To everyone who answered, thanks for your help!</p>\n"
},
{
"answer_id": 927045,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 3,
"selected": false,
"text": "<p>Found the answer :\nI need to use the following to make it work on both browsers :</p>\n\n<pre class=\"lang-js prettyprint-override\"><code>document.getElementById('editRow').style.display = '';\n</code></pre>\n"
},
{
"answer_id": 1776793,
"author": "Paul",
"author_id": 216232,
"author_profile": "https://Stackoverflow.com/users/216232",
"pm_score": 0,
"selected": false,
"text": "<p>There is an annoying display error on Firefox 3.5 but not on IE7 or Firefox 2.0.9</p>\n\n<p>I have 3 DIV's position absolute - the first with plain text; the second with a CSS menu (sucklefish type with UL and LI) and the third ditto. The third will not display at all even though the coding has been checked and found to be perfect with W3C's HTML validator.</p>\n\n<p>As a temporary measure, I have merged the second and third DIV's contents.</p>\n\n<p>Things must be bad at Mozilla when IE7 and FF2 display OK but not FF 3.5</p>\n"
},
{
"answer_id": 5705775,
"author": "Neal Connolly",
"author_id": 713750,
"author_profile": "https://Stackoverflow.com/users/713750",
"pm_score": 2,
"selected": false,
"text": "<p>Actually I was experiencing the same problem you're describing here. What actually fixed my issue was changing the document properties. </p>\n\n<p><strong>Old DOCTYPE/html spec</strong></p>\n\n<pre><code><!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.01 Transitional//EN\" \"http://www.w3.org/TR/html4/loose.dtd\">\n<html xmlns=\"http://www.w3.org/1999/xhtml\">\n</code></pre>\n\n<p><strong>Replaced with</strong></p>\n\n<pre><code><html>\n</code></pre>\n"
},
{
"answer_id": 6952255,
"author": "fadzzz",
"author_id": 879981,
"author_profile": "https://Stackoverflow.com/users/879981",
"pm_score": 1,
"selected": false,
"text": "<p>You must write a <code>window.onload</code> method:</p>\n\n<pre><code>window.onload = document.getElementById('testdiv').style.display='inline';\n</code></pre>\n\n<p>Or you can also make a variable:</p>\n\n<pre><code>var d = document.getElementById('testdiv');\nwindow.onload = d.style.display = 'inline';\n</code></pre>\n"
},
{
"answer_id": 17100771,
"author": "Ron Lentjes",
"author_id": 2484613,
"author_profile": "https://Stackoverflow.com/users/2484613",
"pm_score": 0,
"selected": false,
"text": "<p>I'll give you a BIG hint:</p>\n\n<pre><code><div style=\"...\" class=\"...\"> ... </div>\n</code></pre>\n\n<p>If you have something in style, then document.style will work!\nIf you have something in class, it will not show up in document.style and class=\"...\" will OVERRIDE it!</p>\n\n<p>Think about this and this will clear up SO MANY ISSUES. Just this one little understanding will RID you of this MIND VIRUS. Have a good day. Cheers, Ron Lentjes, LC CLS.</p>\n"
}
] | 2008/08/13 | [
"https://Stackoverflow.com/questions/10366",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/521/"
] | I have an absolutely positioned `div` that I want to show when the user clicks a link. The `onclick` of the link calls a js function that sets the display of the div to block (also tried: "", `inline`, `table-cell`, `inline-table`, etc). This works great in IE7, not at all in every other browser I've tried (FF2, FF3, Opera 9.5, Safari).
I've tried adding alerts before and after the call, and they show that the display has changed from `none` to `block` but the `div` does not display.
I can get the `div` to display in FF3 if I change the display value using Firebug's HTML inspector (but not by running javascript through Firebug's console) - so I know it's not just showing up off-screen, etc.
I've tried everything I can think of, including:
* Using a different doctype (XHTML 1, HTML 4, etc)
* Using visibility visible/hidden instead of display block/none
* Using inline javascript instead of a function call
* Testing from different machines
Any ideas about what could cause this? | Since setting the properties with javascript never seemed to work, but setting using Firebug's inspect did, I started to suspect that the javascript ID selector was broken - maybe there were multiple items in the DOM with the same ID? The source didn't show that there were, but looping through all divs using javascript I found that that was the case. Here's the function I ended up using to show the popup:
```
function openPopup(popupID)
{
var divs = getObjectsByTagAndClass('div','popupDiv');
if (divs != undefined && divs != null)
{
for (var i = 0; i < divs.length; i++)
{
if (divs[i].id == popupID)
divs[i].style.display = 'block';
}
}
}
```
(utility function getObjectsByTagAndClass not listed)
Ideally I'll find out why the same item is being inserted multiple times, but I don't have control over the rendering platform, just its inputs.
So when debugging issues like this, **remember to check for duplicate IDs in the DOM, which can break getElementById**.
To everyone who answered, thanks for your help! |
10,435 | <p>I have a website that works correctly under IIS 6.0: It authenticates users with windows credentials, and then when talking to the service that hits the DB, it passes the credentials.</p>
<p>In IIS 7.0, the same config settings do not pass the credentials, and the DB gets hit with NT AUTHORITY\ANONYMOUS.</p>
<p>Is there something I'm missing? I've turned ANONYMOUS access off in my IIS 7.0 website, but I can't get the thing to work.</p>
<p>These are the settings that I'm using on both IIS 6.0 and 7.0:</p>
<pre><code><authentication mode="Windows">
<identity impersonate="true">
</code></pre>
<p>What changed from 6.0 to 7.0?</p>
| [
{
"answer_id": 10444,
"author": "Guy",
"author_id": 993,
"author_profile": "https://Stackoverflow.com/users/993",
"pm_score": 0,
"selected": false,
"text": "<p>Interesting... I have the opposite problem - <strong>Not being able</strong> to get the authentication to be passed from the client browser, through the webserver and onto the database within a large corporate network over firewalls.</p>\n\n<p>I also feel that \"end to end user\" authentication to the database is a bad idea and a potential security risk. There is nothing to stop the end user from loading up SQL Query and connecting directly to your database, so you'd better have your schema locked down!</p>\n\n<p>@Esteban - Clarified my <em>not very useful in helping you</em> answer.</p>\n"
},
{
"answer_id": 80558,
"author": "Christopher G. Lewis",
"author_id": 13532,
"author_profile": "https://Stackoverflow.com/users/13532",
"pm_score": 0,
"selected": false,
"text": "<p>Typically if you are doing double hop authentication like this, Kerberos is typically involved unless the first authentication is Basic.</p>\n\n<p>I would check the authentication on the IIS 6 servers and make sure that it's the same on IIS 7.</p>\n\n<p>If the IIS 6 box is set to Windows Integrated, then you need to verify the kerberos settings - SPNs, Delegation etc.</p>\n"
},
{
"answer_id": 228364,
"author": "tvanfosson",
"author_id": 12950,
"author_profile": "https://Stackoverflow.com/users/12950",
"pm_score": 1,
"selected": false,
"text": "<p>Is your IIS server set up to be trusted for delegation by the SQLServer? I've run into this before with WebDAV where we've had to have the server running IIS trusted by the file server to authenticate on the file server's behalf.</p>\n"
},
{
"answer_id": 267243,
"author": "Maxime Rouiller",
"author_id": 24975,
"author_profile": "https://Stackoverflow.com/users/24975",
"pm_score": 4,
"selected": true,
"text": "<p>There has been changes between IIS7 and IIS6.0. I found for you one blog post that might actually help you (<a href=\"http://mvolo.com/blogs/serverside/archive/2007/12/08/IIS-7.0-Breaking-Changes-ASP.NET-2.0-applications-Integrated-mode.aspx\" rel=\"noreferrer\">click here to see it</a>).</p>\n\n<p>Are you running your application in Integrated Mode or in Classic Mode? From what I saw, putting the Impersonate attribute at true should display you a 500 error with the following error message:</p>\n\n<blockquote>\n <p>Internal Server Error. This is HTTP\n Error 500.19: The requested page\n cannot be accessed because the related\n configuration data for the page is\n invalid.</p>\n</blockquote>\n\n<p>Here is the workaround that is proposed:</p>\n\n<blockquote>\n <p>Workaround:</p>\n \n <p>1) If your application does not rely\n on impersonating the requesting user\n in the BeginRequest and\n AuthenticateRequest stages (the only\n stages where impersonation is not\n possible in Integrated mode), ignore\n this error by adding the following to\n your application’s web.config:\n </p>\n\n<pre><code><validation validateIntegratedModeConfiguration=\"false\"\n</code></pre>\n \n <p>/></p>\n \n <p></p>\n \n <p>2) If your application does rely on\n impersonation in BeginRequest and\n AuthenticateRequest, or you are not\n sure, move to classic mode.</p>\n</blockquote>\n\n<p>I hoped that was useful to understand how IIS 7.0 now works.</p>\n"
}
] | 2008/08/13 | [
"https://Stackoverflow.com/questions/10435",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/781/"
] | I have a website that works correctly under IIS 6.0: It authenticates users with windows credentials, and then when talking to the service that hits the DB, it passes the credentials.
In IIS 7.0, the same config settings do not pass the credentials, and the DB gets hit with NT AUTHORITY\ANONYMOUS.
Is there something I'm missing? I've turned ANONYMOUS access off in my IIS 7.0 website, but I can't get the thing to work.
These are the settings that I'm using on both IIS 6.0 and 7.0:
```
<authentication mode="Windows">
<identity impersonate="true">
```
What changed from 6.0 to 7.0? | There has been changes between IIS7 and IIS6.0. I found for you one blog post that might actually help you ([click here to see it](http://mvolo.com/blogs/serverside/archive/2007/12/08/IIS-7.0-Breaking-Changes-ASP.NET-2.0-applications-Integrated-mode.aspx)).
Are you running your application in Integrated Mode or in Classic Mode? From what I saw, putting the Impersonate attribute at true should display you a 500 error with the following error message:
>
> Internal Server Error. This is HTTP
> Error 500.19: The requested page
> cannot be accessed because the related
> configuration data for the page is
> invalid.
>
>
>
Here is the workaround that is proposed:
>
> Workaround:
>
>
> 1) If your application does not rely
> on impersonating the requesting user
> in the BeginRequest and
> AuthenticateRequest stages (the only
> stages where impersonation is not
> possible in Integrated mode), ignore
> this error by adding the following to
> your application’s web.config:
>
>
>
>
> ```
> <validation validateIntegratedModeConfiguration="false"
>
> ```
>
> />
>
>
>
> 2) If your application does rely on
> impersonation in BeginRequest and
> AuthenticateRequest, or you are not
> sure, move to classic mode.
>
>
>
I hoped that was useful to understand how IIS 7.0 now works. |
10,443 | <p>I have this program, we'll call it Host. Host does all kinds of good stuff, but it needs to be able to accept input through the command line <strong>while it's running</strong>. This means it has to somehow send its other process data and then quit. For example, I need to be able to do this:</p>
<pre><code>./Host --blahblah 3 6 3 5
</code></pre>
<p>This should somehow end up calling some function in Host called</p>
<pre><code>handleBlahBlah(int x1, int y1, int x2, int y2){
//do some more sweet stuff
}
</code></pre>
<p>Host is a C program, and does not need to support multiple instances.</p>
<p>An example of this is Amarok music player. With Amarok running and playing, you can type "amarok --pause" and it will pause the music.</p>
<p>I need to be able to do this in Linux or Windows. Preferably Linux.</p>
<p>What is the cleanest way to implement this?</p>
| [
{
"answer_id": 10445,
"author": "Ed S.",
"author_id": 1053,
"author_profile": "https://Stackoverflow.com/users/1053",
"pm_score": -1,
"selected": false,
"text": "<p>So, I may be missing the point here, but by deafult a C program's main function takes two arguments; argc, a count of the number of arguments (at least one), and argv (or arg vector), the argument list. You could just parse through the arguments and call the correct method.\nFor example:</p>\n\n<pre><code> int main(int argc, *argv[])\n {\n /*loop through each argument and take action*/\n while (--argc > 0)\n {\n printf(%s%s, *++argv, (argc > 1) ? \" \" : \"\");\n }\n } \n</code></pre>\n\n<p>would print all of the arguments to screen. I am no C guru, so I hope I haven't made any mistakes.</p>\n\n<p>EDIT: Ok, he was after something else, but it wasn't really clear before the question was edited. Don't have to jump on my rep...</p>\n"
},
{
"answer_id": 10450,
"author": "Derek Park",
"author_id": 872,
"author_profile": "https://Stackoverflow.com/users/872",
"pm_score": 3,
"selected": false,
"text": "<p>If you were on Windows, I'd tell you to use a hidden window to receive the messages, but since you used <code>./</code>, I assume you want something Unix-based.</p>\n\n<p>In that case, I'd go with a <a href=\"http://en.wikipedia.org/wiki/Named_pipe\" rel=\"noreferrer\">named pipe</a>. Sun has a <a href=\"http://developers.sun.com/solaris/articles/named_pipes.html\" rel=\"noreferrer\">tutorial</a> about named pipes that might be useful.</p>\n\n<p>The program would probably create the pipe and listen. You could have a separate command-line script which would open the pipe and just echo its command-line arguments to it.</p>\n\n<p>You <em>could</em> modify your program to support the command-line sending instead of using a separate script. You'd do the same basic thing in that case. Your program would look at it's command-line arguments, and if applicable, open the pipe to the \"main\" instance of the program, and send the arguments through.</p>\n"
},
{
"answer_id": 10451,
"author": "Stu",
"author_id": 414,
"author_profile": "https://Stackoverflow.com/users/414",
"pm_score": 3,
"selected": false,
"text": "<p>If it needs to be cross-platform, you might want to consider making the running instance listen on a TCP port, and have the instance you fire up from the command-line send a message to that port.</p>\n"
},
{
"answer_id": 14352,
"author": "T Percival",
"author_id": 954,
"author_profile": "https://Stackoverflow.com/users/954",
"pm_score": 2,
"selected": false,
"text": "<p>I suggest using either a <a href=\"http://en.wikipedia.org/wiki/Unix_domain_socket\" rel=\"nofollow noreferrer\">Unix socket</a> or <a href=\"http://en.wikipedia.org/wiki/D-Bus\" rel=\"nofollow noreferrer\">D-Bus</a>. Using a socket might be faster if you're familiar with Unix sockets programming and only want a few operations, whereas D-Bus might make it easier to concentrate on implementing the functionality in a familiar object-oriented way.</p>\n\n<p>Take a look at <a href=\"http://beej.us/guide/bgipc/output/html/multipage/index.html\" rel=\"nofollow noreferrer\">Beej's Guide to Unix IPC</a>, particularly the chapter on <a href=\"http://beej.us/guide/bgipc/output/html/multipage/unixsock.html\" rel=\"nofollow noreferrer\">Unix sockets</a>.</p>\n"
},
{
"answer_id": 2990496,
"author": "pbernatchez",
"author_id": 336867,
"author_profile": "https://Stackoverflow.com/users/336867",
"pm_score": 1,
"selected": false,
"text": "<p>What no one has said here is this:\n\"you can't get there from here\".</p>\n\n<p>The command line is only available as it was when your program was invoked.</p>\n\n<p>The example of invoking \"<strong>fillinthename</strong> arguments ...\" to communicate with <strong>fillinthename</strong> once <strong>fillinthename</strong> is running can only be accomplished by using two instances of the program which communicate with each other.</p>\n\n<p>The other answers suggest ways to achieve the communication.</p>\n\n<p>An <strong>amarok</strong> like program needs to detect the existence of another instance\nof itself in order to know which role it must play, the major role of\npersistent message receiver/server, or the minor role of one shot \nmessage sender.</p>\n\n<p>edited to make the word fillinthename actually be displayed.</p>\n"
},
{
"answer_id": 3461155,
"author": "bta",
"author_id": 79566,
"author_profile": "https://Stackoverflow.com/users/79566",
"pm_score": 0,
"selected": false,
"text": "<p>One technique I have seen is to have your <code>Host</code> program be merely a \"shell\" for your real program. For example when you launch your application normally (e.g.: <code>./Host</code>), the program will fork into the \"main app\" part of your code. When you launch your program in a way that suggests you want to signal the running instance (e.g.: <code>./Host --send-message restart</code>), the program will fork into the \"message sender\" part of your code. It's like having two apps in one. Another option that doesn't use <code>fork</code> is to make <code>Host</code> purely a \"message sender\" app and have your \"main app\" as a separate executable (e.g.: <code>Host_core</code>) that <code>Host</code> can launch separately.</p>\n\n<p>The \"main app\" part of your program will need to open up some kind of a communication channel to receive messages, and the \"message sender\" part will need to connect to that channel and use it to send messages. There are several different options available for sending messages between processes. Some of the more common methods are <a href=\"http://www.tldp.org/LDP/lpg/node15.html\" rel=\"nofollow noreferrer\">pipes</a> and <a href=\"http://www.kernel.org/doc/man-pages/online/pages/man2/socket.2.html\" rel=\"nofollow noreferrer\">sockets</a>. Depending on your OS, you may have additional options available; for instance, QNX has <a href=\"http://www.qnx.com/developers/docs/6.3.2/neutrino/lib_ref/c/channelcreate.html\" rel=\"nofollow noreferrer\">channels</a> and BeOS/Haiku have <a href=\"http://api.haiku-os.org/classBMessage.html\" rel=\"nofollow noreferrer\">BMessages</a>. You may also be able to find a library that neatly wraps up this functionality, such as <a href=\"http://code.google.com/p/lcm/\" rel=\"nofollow noreferrer\">lcm</a>.</p>\n"
}
] | 2008/08/13 | [
"https://Stackoverflow.com/questions/10443",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/432/"
] | I have this program, we'll call it Host. Host does all kinds of good stuff, but it needs to be able to accept input through the command line **while it's running**. This means it has to somehow send its other process data and then quit. For example, I need to be able to do this:
```
./Host --blahblah 3 6 3 5
```
This should somehow end up calling some function in Host called
```
handleBlahBlah(int x1, int y1, int x2, int y2){
//do some more sweet stuff
}
```
Host is a C program, and does not need to support multiple instances.
An example of this is Amarok music player. With Amarok running and playing, you can type "amarok --pause" and it will pause the music.
I need to be able to do this in Linux or Windows. Preferably Linux.
What is the cleanest way to implement this? | If you were on Windows, I'd tell you to use a hidden window to receive the messages, but since you used `./`, I assume you want something Unix-based.
In that case, I'd go with a [named pipe](http://en.wikipedia.org/wiki/Named_pipe). Sun has a [tutorial](http://developers.sun.com/solaris/articles/named_pipes.html) about named pipes that might be useful.
The program would probably create the pipe and listen. You could have a separate command-line script which would open the pipe and just echo its command-line arguments to it.
You *could* modify your program to support the command-line sending instead of using a separate script. You'd do the same basic thing in that case. Your program would look at it's command-line arguments, and if applicable, open the pipe to the "main" instance of the program, and send the arguments through. |
10,456 | <p>The 'click sound' in question is actually a system wide preference, so I only want it to be disabled when my application has focus and then re-enable when the application closes/loses focus.</p>
<p>Originally, I wanted to ask this question here on stackoverflow, but I was not yet in the beta. So, after googling for the answer and finding only a little bit of information on it I came up with the following and decided to post it here now that I'm in the beta.</p>
<pre><code>using System;
using Microsoft.Win32;
namespace HowTo
{
class WebClickSound
{
/// <summary>
/// Enables or disables the web browser navigating click sound.
/// </summary>
public static bool Enabled
{
get
{
RegistryKey key = Registry.CurrentUser.OpenSubKey(@"AppEvents\Schemes\Apps\Explorer\Navigating\.Current");
string keyValue = (string)key.GetValue(null);
return String.IsNullOrEmpty(keyValue) == false && keyValue != "\"\"";
}
set
{
string keyValue;
if (value)
{
keyValue = "%SystemRoot%\\Media\\";
if (Environment.OSVersion.Version.Major == 5 && Environment.OSVersion.Version.Minor > 0)
{
// XP
keyValue += "Windows XP Start.wav";
}
else if (Environment.OSVersion.Version.Major == 6)
{
// Vista
keyValue += "Windows Navigation Start.wav";
}
else
{
// Don't know the file name so I won't be able to re-enable it
return;
}
}
else
{
keyValue = "\"\"";
}
// Open and set the key that points to the file
RegistryKey key = Registry.CurrentUser.OpenSubKey(@"AppEvents\Schemes\Apps\Explorer\Navigating\.Current", true);
key.SetValue(null, keyValue, RegistryValueKind.ExpandString);
isEnabled = value;
}
}
}
}
</code></pre>
<p>Then in the main form we use the above code in these 3 events: </p>
<ul>
<li>Activated </li>
<li>Deactivated </li>
<li><p>FormClosing</p>
<pre><code>private void Form1_Activated(object sender, EventArgs e)
{
// Disable the sound when the program has focus
WebClickSound.Enabled = false;
}
private void Form1_Deactivate(object sender, EventArgs e)
{
// Enable the sound when the program is out of focus
WebClickSound.Enabled = true;
}
private void Form1_FormClosing(object sender, FormClosingEventArgs e)
{
// Enable the sound on app exit
WebClickSound.Enabled = true;
}
</code></pre></li>
</ul>
<p>The one problem I see currently is if the program crashes they won't have the click sound until they re-launch my application, but they wouldn't know to do that.</p>
<p>What do you guys think? Is this a good solution? What improvements can be made?</p>
| [
{
"answer_id": 10463,
"author": "Matt Hamilton",
"author_id": 615,
"author_profile": "https://Stackoverflow.com/users/615",
"pm_score": 5,
"selected": true,
"text": "<p>I've noticed that if you use WebBrowser.Document.Write rather than WebBrowser.DocumentText then the click sound doesn't happen.</p>\n\n<p>So instead of this:</p>\n\n<pre><code>webBrowser1.DocumentText = \"<h1>Hello, world!</h1>\";\n</code></pre>\n\n<p>try this:</p>\n\n<pre><code>webBrowser1.Document.OpenNew(true);\nwebBrowser1.Document.Write(\"<h1>Hello, world!</h1>\");\n</code></pre>\n"
},
{
"answer_id": 10465,
"author": "pix0r",
"author_id": 72,
"author_profile": "https://Stackoverflow.com/users/72",
"pm_score": 0,
"selected": false,
"text": "<p>Definitely feels like a hack, but having done some research on this a long time ago and not finding any other solutions, probably your best bet.</p>\n\n<p>Better yet would be designing your application so it doesn't require many annoying page reloads.. for example, if you're refreshing an iframe to check for updates on the server, use XMLHttpRequest instead. (Can you tell that I was dealing with this problem back in the days before the term \"AJAX\" was coined?)</p>\n"
},
{
"answer_id": 4588327,
"author": "DjCzermino",
"author_id": 561764,
"author_profile": "https://Stackoverflow.com/users/561764",
"pm_score": 0,
"selected": false,
"text": "<p>If you want to use replacing Windows Registry, use this:</p>\n\n<pre><code>// backup value\nRegistryKey key = Registry.CurrentUser.OpenSubKey(@\"AppEvents\\Schemes\\Apps\\Explorer\\Navigating\\.Current\");\nstring BACKUP_keyValue = (string)key.GetValue(null);\n\n// write nothing\nkey = Registry.CurrentUser.OpenSubKey(@\"AppEvents\\Schemes\\Apps\\Explorer\\Navigating\\.Current\", true);\nkey.SetValue(null, \"\", RegistryValueKind.ExpandString);\n\n// do navigation ...\n\n// write backup key\nRegistryKey key = Registry.CurrentUser.OpenSubKey(@\"AppEvents\\Schemes\\Apps\\Explorer\\Navigating\\.Current\", true);\nkey.SetValue(null, BACKUP_keyValue, RegistryValueKind.ExpandString);\n</code></pre>\n"
},
{
"answer_id": 4655871,
"author": "John black",
"author_id": 566868,
"author_profile": "https://Stackoverflow.com/users/566868",
"pm_score": 5,
"selected": false,
"text": "<pre><code>const int FEATURE_DISABLE_NAVIGATION_SOUNDS = 21;\nconst int SET_FEATURE_ON_PROCESS = 0x00000002;\n\n[DllImport(\"urlmon.dll\")]\n[PreserveSig]\n[return: MarshalAs(UnmanagedType.Error)]\nstatic extern int CoInternetSetFeatureEnabled(int FeatureEntry,\n [MarshalAs(UnmanagedType.U4)] int dwFlags,\n bool fEnable);\n\nstatic void DisableClickSounds()\n{\n CoInternetSetFeatureEnabled(FEATURE_DISABLE_NAVIGATION_SOUNDS,\n SET_FEATURE_ON_PROCESS,\n true);\n}\n</code></pre>\n"
},
{
"answer_id": 17822223,
"author": "user2612427",
"author_id": 2612427,
"author_profile": "https://Stackoverflow.com/users/2612427",
"pm_score": 1,
"selected": false,
"text": "<p>You disable it by changing Internet Explorer registry value of navigating sound to \"NULL\":</p>\n\n<pre><code>Registry.SetValue(\"HKEY_CURRENT_USER\\\\AppEvents\\\\Schemes\\\\Apps\\\\Explorer\\\\Navigating\\\\.Current\",\"\",\"NULL\");\n</code></pre>\n\n<p>And enable it by changing Internet Explorer registry value of navigating sound to \"C:\\Windows\\Media\\Cityscape\\Windows Navigation Start.wav\":</p>\n\n<pre><code>Registry.SetValue(\"HKEY_CURRENT_USER\\\\AppEvents\\\\Schemes\\\\Apps\\\\Explorer\\\\Navigating\\\\.Current\",\"\",\"C:\\Windows\\Media\\Cityscape\\Windows Navigation Start.wav\");\n</code></pre>\n"
}
] | 2008/08/13 | [
"https://Stackoverflow.com/questions/10456",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1147/"
] | The 'click sound' in question is actually a system wide preference, so I only want it to be disabled when my application has focus and then re-enable when the application closes/loses focus.
Originally, I wanted to ask this question here on stackoverflow, but I was not yet in the beta. So, after googling for the answer and finding only a little bit of information on it I came up with the following and decided to post it here now that I'm in the beta.
```
using System;
using Microsoft.Win32;
namespace HowTo
{
class WebClickSound
{
/// <summary>
/// Enables or disables the web browser navigating click sound.
/// </summary>
public static bool Enabled
{
get
{
RegistryKey key = Registry.CurrentUser.OpenSubKey(@"AppEvents\Schemes\Apps\Explorer\Navigating\.Current");
string keyValue = (string)key.GetValue(null);
return String.IsNullOrEmpty(keyValue) == false && keyValue != "\"\"";
}
set
{
string keyValue;
if (value)
{
keyValue = "%SystemRoot%\\Media\\";
if (Environment.OSVersion.Version.Major == 5 && Environment.OSVersion.Version.Minor > 0)
{
// XP
keyValue += "Windows XP Start.wav";
}
else if (Environment.OSVersion.Version.Major == 6)
{
// Vista
keyValue += "Windows Navigation Start.wav";
}
else
{
// Don't know the file name so I won't be able to re-enable it
return;
}
}
else
{
keyValue = "\"\"";
}
// Open and set the key that points to the file
RegistryKey key = Registry.CurrentUser.OpenSubKey(@"AppEvents\Schemes\Apps\Explorer\Navigating\.Current", true);
key.SetValue(null, keyValue, RegistryValueKind.ExpandString);
isEnabled = value;
}
}
}
}
```
Then in the main form we use the above code in these 3 events:
* Activated
* Deactivated
* FormClosing
```
private void Form1_Activated(object sender, EventArgs e)
{
// Disable the sound when the program has focus
WebClickSound.Enabled = false;
}
private void Form1_Deactivate(object sender, EventArgs e)
{
// Enable the sound when the program is out of focus
WebClickSound.Enabled = true;
}
private void Form1_FormClosing(object sender, FormClosingEventArgs e)
{
// Enable the sound on app exit
WebClickSound.Enabled = true;
}
```
The one problem I see currently is if the program crashes they won't have the click sound until they re-launch my application, but they wouldn't know to do that.
What do you guys think? Is this a good solution? What improvements can be made? | I've noticed that if you use WebBrowser.Document.Write rather than WebBrowser.DocumentText then the click sound doesn't happen.
So instead of this:
```
webBrowser1.DocumentText = "<h1>Hello, world!</h1>";
```
try this:
```
webBrowser1.Document.OpenNew(true);
webBrowser1.Document.Write("<h1>Hello, world!</h1>");
``` |
10,499 | <p>Sometimes I get Oracle connection problems because I can't figure out which tnsnames.ora file my database client is using.</p>
<p>What's the best way to figure this out? ++happy for various platform solutions. </p>
| [
{
"answer_id": 10501,
"author": "Mark Harrison",
"author_id": 116,
"author_profile": "https://Stackoverflow.com/users/116",
"pm_score": 5,
"selected": false,
"text": "<p>For linux:</p>\n\n<pre><code>$ strace sqlplus -L scott/tiger@orcl 2>&1| grep -i 'open.*tnsnames.ora'\n</code></pre>\n\n<p>shows something like this:</p>\n\n<pre><code>open(\"/opt/oracle/product/10.2.0/db_1/network/admin/tnsnames.ora\",O_RDONLY)=7\n</code></pre>\n\n<p>Changing to </p>\n\n<pre><code>$ strace sqlplus -L scott/tiger@orcl 2>&1| grep -i 'tnsnames.ora'\n</code></pre>\n\n<p>will show all the file paths that are failing.</p>\n"
},
{
"answer_id": 11373,
"author": "BIBD",
"author_id": 685,
"author_profile": "https://Stackoverflow.com/users/685",
"pm_score": 1,
"selected": false,
"text": "<p>Shouldn't it always be \"$ORACLE_ HOME/network/admin/tnsnames.ora\"?\nThen you can just do \"echo $oracle_ home\" or the *nix equivalent.</p>\n\n<p>@Pete Holberton\nYou are entirely correct. Which reminds me, there's another monkey wrench in the works called TWO_ TASK</p>\n\n<p>According <a href=\"http://www.orafaq.com/wiki/TNS_ADMIN\" rel=\"nofollow noreferrer\">http://www.orafaq.com/wiki/TNS_ADMIN</a><br>\nTNS_ADMIN is an environment variable that points to the directory where the SQL*Net configuration files (like sqlnet.ora and tnsnames.ora) are located. </p>\n"
},
{
"answer_id": 29767,
"author": "Ishmaeel",
"author_id": 227,
"author_profile": "https://Stackoverflow.com/users/227",
"pm_score": 2,
"selected": false,
"text": "<p>For Windows: <a href=\"http://technet.microsoft.com/en-us/sysinternals/bb896642.aspx\" rel=\"nofollow noreferrer\">Filemon</a> from SysInternals will show you what files are being accessed.</p>\n\n<p>Remember to set your filters so you are not overwhelmed by the chatty file system traffic.</p>\n\n<p><img src=\"https://i.stack.imgur.com/tY0Ov.jpg\" alt=\"Filter Dialog\"></p>\n\n<p><strong>Added:</strong> Filemon does not work with newer Windows versions, so you might have to use <a href=\"http://technet.microsoft.com/en-us/sysinternals/bb896645\" rel=\"nofollow noreferrer\">Process Monitor</a>.</p>\n"
},
{
"answer_id": 29807,
"author": "stjohnroe",
"author_id": 2985,
"author_profile": "https://Stackoverflow.com/users/2985",
"pm_score": 7,
"selected": true,
"text": "<p>Oracle provides a utility called <code>tnsping</code>:</p>\n\n<pre><code>R:\\>tnsping someconnection\n\nTNS Ping Utility for 32-bit Windows: Version 9.0.1.3.1 - Production on 27-AUG-20\n08 10:38:07\n\nCopyright (c) 1997 Oracle Corporation. All rights reserved.\n\nUsed parameter files:\nC:\\Oracle92\\network\\ADMIN\\sqlnet.ora\nC:\\Oracle92\\network\\ADMIN\\tnsnames.ora\n\nTNS-03505: Failed to resolve name\n\nR:\\>\n\n\nR:\\>tnsping entpr01\n\nTNS Ping Utility for 32-bit Windows: Version 9.0.1.3.1 - Production on 27-AUG-20\n08 10:39:22\n\nCopyright (c) 1997 Oracle Corporation. All rights reserved.\n\nUsed parameter files:\nC:\\Oracle92\\network\\ADMIN\\sqlnet.ora\nC:\\Oracle92\\network\\ADMIN\\tnsnames.ora\n\nUsed TNSNAMES adapter to resolve the alias\nAttempting to contact (DESCRIPTION = (ADDRESS_LIST = (ADDRESS = (COMMUNITY = **)\n (PROTOCOL = TCP) (Host = ****) (Port = 1521))) (CONNECT_DATA = (SID = ENTPR0\n1)))\nOK (40 msec)\n\nR:\\>\n</code></pre>\n\n<p>This should show what file you're using. The utility sits in the Oracle <code>bin</code> directory.</p>\n"
},
{
"answer_id": 35804,
"author": "Sir Rippov the Maple",
"author_id": 2822,
"author_profile": "https://Stackoverflow.com/users/2822",
"pm_score": 3,
"selected": false,
"text": "<p>There is another place where the TNS location is stored: If you're using Windows, open <code>regedit</code> and navigate to <code>My HKEY Local Machine/Software/ORACLE/KEY_OraClient10_home1</code> where <code>KEY_OraClient10_home1</code> is your Oracle home. If there is a string entry called <code>TNS_ADMIN</code>, then the value of that entry will point to the TNS file that Oracle is using on your computer.</p>\n"
},
{
"answer_id": 37235,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 2,
"selected": false,
"text": "<p>By default, tnsnames.ora is located in the $ORACLE_HOME/network/admin directory on UNIX operating systems and in the ORACLE_HOME\\network\\admin directory on Windows operating systems. tnsnames.ora can also be stored the following locations:</p>\n\n<p>The directory specified by the TNS_ADMIN environment variable (or registry value)</p>\n\n<p>On UNIX operating systems, the global configuration directory. For example, on the Solaris Operating System, this directory is /var/opt/oracle</p>\n\n<p>If you have multiple ORACLE_HOMES, be aware of which one you are using, as the location of the tnsnames.ora file can vary from one ORACLE_HOME to the next.</p>\n\n<p>For the person who mentioned the TWO_TASK environment variable, that is used to set a default database service name to connect to (which could be a database on another server). The service name you set TWO_TASK to is then looked up in the tnsnames.ora file when you connect.</p>\n"
},
{
"answer_id": 189142,
"author": "DCookie",
"author_id": 8670,
"author_profile": "https://Stackoverflow.com/users/8670",
"pm_score": 2,
"selected": false,
"text": "<p>Codeslave asks \"Shouldn't it always be \"$ORACLE_ HOME/network/admin/tnsnames.ora\"? The answer is no, it isn't. Consider these two invocations of tnsping on the same machine:</p>\n\n<pre><code>C:\\Documents and Settings\\me>D:\\Oracle\\10.2.0_DB\\BIN\\tnsping orcl\n\nTNS Ping Utility for 32-bit Windows: Version 10.2.0.4.0 - Production on 09-OCT-2\n008 14:30:12\n\nCopyright (c) 1997, 2007, Oracle. All rights reserved.\n\nUsed parameter files:\nD:\\Oracle\\10.2.0_DB\\network\\admin\\sqlnet.ora\n\n\nUsed TNSNAMES adapter to resolve the alias\nAttempting to contact (DESCRIPTION = (ADDRESS = (PROTOCOL = TCP)(HOST = xxxx\n)(PORT = 1521)) (CONNECT_DATA = (SERVER = DEDICATED) (SERVICE_NAME = ORCL)))\n\nOK (40 msec)\n\nC:\\Documents and Settings\\me>tnsping orcl\n\nTNS Ping Utility for 32-bit Windows: Version 10.2.0.1.0 - Production on 09-OCT-2\n008 14:30:21\n\nCopyright (c) 1997, 2005, Oracle. All rights reserved.\n\nUsed parameter files:\nD:\\oracle\\10.2.0_Client\\network\\admin\\sqlnet.ora\n\n\nUsed TNSNAMES adapter to resolve the alias\nAttempting to contact (DESCRIPTION = (ADDRESS_LIST = (ADDRESS = (PROTOCOL = TCP)\n(HOST = XXXX)(PORT = 1521))) (CONNECT_DATA = (SERVICE_NAME = ORCL)))\nOK (20 msec)\n\nC:\\Documents and Settings\\me>\n</code></pre>\n\n<p>Note the two different parameter file locations, that are dependent on which tnsping executable you're running (and perhaps where it's being run from). For tnsnames-based oracle networking, using the TNS_ADMIN variable is the only way to ensure you're getting a consistent tnsnames.ora file. (NOTE: Windows-centric answer)</p>\n"
},
{
"answer_id": 200344,
"author": "Rene",
"author_id": 17323,
"author_profile": "https://Stackoverflow.com/users/17323",
"pm_score": 3,
"selected": false,
"text": "<p>On my development machine I have three different versions of Oracle client software. I manage the <code>tnsnames.ora</code> file in one of them. In the other two, I have entered in the <code>tnsnames.ora</code> file:</p>\n\n<pre><code>ifile=path_to_tnsnames.ora_file/tnsnames.ora\n</code></pre>\n\n<p>This way, if for some reason the wrong <code>tnsnames.ora</code> file is used by a client, it will always end up at the up-to-date version.</p>\n"
},
{
"answer_id": 341948,
"author": "stili",
"author_id": 20763,
"author_profile": "https://Stackoverflow.com/users/20763",
"pm_score": 0,
"selected": false,
"text": "<p>The easiest way is probably to check the <strong>PATH</strong> environment variable of the process that is connecting to the database. Most likely the tnsnames.ora file is in <em>first Oracle bin directory in path</em>..\\network\\admin. TNS_ADMIN environment variable or value in registry (for the current Oracle home) may override this.</p>\n\n<p>Using filemon like suggested by others will also do the trick.</p>\n"
},
{
"answer_id": 20523156,
"author": "sri",
"author_id": 3091747,
"author_profile": "https://Stackoverflow.com/users/3091747",
"pm_score": 1,
"selected": false,
"text": "<p><code>strace sqlplus -L scott/tiger@orcl</code> helps to find <code>.tnsnames.ora</code> file on <code>/home/oracle</code> to find the file it takes instead of <code>$ORACLE_HOME/network/admin/tnsnames.ora</code> file. Thanks for the posting.</p>\n"
},
{
"answer_id": 36229027,
"author": "artybug",
"author_id": 6080126,
"author_profile": "https://Stackoverflow.com/users/6080126",
"pm_score": 1,
"selected": false,
"text": "<p>Not direct answer to your question, but I've been quite frustrated myself trying find and update all of the tnsnames files, as I had several oracle installs: Client, BI tools, OWB, etc, each of which had its own oracle home. I ended up creating a utility called TNSNamesSync that will update all of the tnsnames in all of the oracle homes. It's under the MIT license, free to use here <a href=\"https://github.com/artybug/TNSNamesSync/releases\" rel=\"nofollow\">https://github.com/artybug/TNSNamesSync/releases</a></p>\n\n<p>The docs are here:\n<a href=\"https://github.com/artchik/TNSNamesSync/blob/master/README.md\" rel=\"nofollow\">https://github.com/artchik/TNSNamesSync/blob/master/README.md</a></p>\n\n<p>This is for Windows only, though.</p>\n"
}
] | 2008/08/13 | [
"https://Stackoverflow.com/questions/10499",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/116/"
] | Sometimes I get Oracle connection problems because I can't figure out which tnsnames.ora file my database client is using.
What's the best way to figure this out? ++happy for various platform solutions. | Oracle provides a utility called `tnsping`:
```
R:\>tnsping someconnection
TNS Ping Utility for 32-bit Windows: Version 9.0.1.3.1 - Production on 27-AUG-20
08 10:38:07
Copyright (c) 1997 Oracle Corporation. All rights reserved.
Used parameter files:
C:\Oracle92\network\ADMIN\sqlnet.ora
C:\Oracle92\network\ADMIN\tnsnames.ora
TNS-03505: Failed to resolve name
R:\>
R:\>tnsping entpr01
TNS Ping Utility for 32-bit Windows: Version 9.0.1.3.1 - Production on 27-AUG-20
08 10:39:22
Copyright (c) 1997 Oracle Corporation. All rights reserved.
Used parameter files:
C:\Oracle92\network\ADMIN\sqlnet.ora
C:\Oracle92\network\ADMIN\tnsnames.ora
Used TNSNAMES adapter to resolve the alias
Attempting to contact (DESCRIPTION = (ADDRESS_LIST = (ADDRESS = (COMMUNITY = **)
(PROTOCOL = TCP) (Host = ****) (Port = 1521))) (CONNECT_DATA = (SID = ENTPR0
1)))
OK (40 msec)
R:\>
```
This should show what file you're using. The utility sits in the Oracle `bin` directory. |
10,506 | <p>I am having a strange DB2 issue when I run DBUnit tests. My DBUnit tests are highly customized, but I don't think it is the issue. When I run the tests, I get a failure: </p>
<blockquote>
<p>SQLCODE: -1084, SQLSTATE: 57019</p>
</blockquote>
<p><a href="https://www1.columbia.edu/sec/acis/db2/db2m0/sql1000.htm" rel="nofollow noreferrer">which translates to</a> </p>
<blockquote>
<p>SQL1084C Shared memory segments cannot be allocated.</p>
</blockquote>
<p>It sounds like a weird memory issue, though here's the big strange thing. If I ssh to the test database server, then go in to db2 and do "connect to MY_DB", the tests start succeeding! This seems to have no relation to the supposed memory error that is being reported.</p>
<p>I have 2 tests, and the first one actually succeeds, the second one is the one that fails. However, it fails in the DBUnit setup code, when it is obtaining the connection to the DB server to load my xml dataset.</p>
<p>Any ideas what might be going on?</p>
| [
{
"answer_id": 10501,
"author": "Mark Harrison",
"author_id": 116,
"author_profile": "https://Stackoverflow.com/users/116",
"pm_score": 5,
"selected": false,
"text": "<p>For linux:</p>\n\n<pre><code>$ strace sqlplus -L scott/tiger@orcl 2>&1| grep -i 'open.*tnsnames.ora'\n</code></pre>\n\n<p>shows something like this:</p>\n\n<pre><code>open(\"/opt/oracle/product/10.2.0/db_1/network/admin/tnsnames.ora\",O_RDONLY)=7\n</code></pre>\n\n<p>Changing to </p>\n\n<pre><code>$ strace sqlplus -L scott/tiger@orcl 2>&1| grep -i 'tnsnames.ora'\n</code></pre>\n\n<p>will show all the file paths that are failing.</p>\n"
},
{
"answer_id": 11373,
"author": "BIBD",
"author_id": 685,
"author_profile": "https://Stackoverflow.com/users/685",
"pm_score": 1,
"selected": false,
"text": "<p>Shouldn't it always be \"$ORACLE_ HOME/network/admin/tnsnames.ora\"?\nThen you can just do \"echo $oracle_ home\" or the *nix equivalent.</p>\n\n<p>@Pete Holberton\nYou are entirely correct. Which reminds me, there's another monkey wrench in the works called TWO_ TASK</p>\n\n<p>According <a href=\"http://www.orafaq.com/wiki/TNS_ADMIN\" rel=\"nofollow noreferrer\">http://www.orafaq.com/wiki/TNS_ADMIN</a><br>\nTNS_ADMIN is an environment variable that points to the directory where the SQL*Net configuration files (like sqlnet.ora and tnsnames.ora) are located. </p>\n"
},
{
"answer_id": 29767,
"author": "Ishmaeel",
"author_id": 227,
"author_profile": "https://Stackoverflow.com/users/227",
"pm_score": 2,
"selected": false,
"text": "<p>For Windows: <a href=\"http://technet.microsoft.com/en-us/sysinternals/bb896642.aspx\" rel=\"nofollow noreferrer\">Filemon</a> from SysInternals will show you what files are being accessed.</p>\n\n<p>Remember to set your filters so you are not overwhelmed by the chatty file system traffic.</p>\n\n<p><img src=\"https://i.stack.imgur.com/tY0Ov.jpg\" alt=\"Filter Dialog\"></p>\n\n<p><strong>Added:</strong> Filemon does not work with newer Windows versions, so you might have to use <a href=\"http://technet.microsoft.com/en-us/sysinternals/bb896645\" rel=\"nofollow noreferrer\">Process Monitor</a>.</p>\n"
},
{
"answer_id": 29807,
"author": "stjohnroe",
"author_id": 2985,
"author_profile": "https://Stackoverflow.com/users/2985",
"pm_score": 7,
"selected": true,
"text": "<p>Oracle provides a utility called <code>tnsping</code>:</p>\n\n<pre><code>R:\\>tnsping someconnection\n\nTNS Ping Utility for 32-bit Windows: Version 9.0.1.3.1 - Production on 27-AUG-20\n08 10:38:07\n\nCopyright (c) 1997 Oracle Corporation. All rights reserved.\n\nUsed parameter files:\nC:\\Oracle92\\network\\ADMIN\\sqlnet.ora\nC:\\Oracle92\\network\\ADMIN\\tnsnames.ora\n\nTNS-03505: Failed to resolve name\n\nR:\\>\n\n\nR:\\>tnsping entpr01\n\nTNS Ping Utility for 32-bit Windows: Version 9.0.1.3.1 - Production on 27-AUG-20\n08 10:39:22\n\nCopyright (c) 1997 Oracle Corporation. All rights reserved.\n\nUsed parameter files:\nC:\\Oracle92\\network\\ADMIN\\sqlnet.ora\nC:\\Oracle92\\network\\ADMIN\\tnsnames.ora\n\nUsed TNSNAMES adapter to resolve the alias\nAttempting to contact (DESCRIPTION = (ADDRESS_LIST = (ADDRESS = (COMMUNITY = **)\n (PROTOCOL = TCP) (Host = ****) (Port = 1521))) (CONNECT_DATA = (SID = ENTPR0\n1)))\nOK (40 msec)\n\nR:\\>\n</code></pre>\n\n<p>This should show what file you're using. The utility sits in the Oracle <code>bin</code> directory.</p>\n"
},
{
"answer_id": 35804,
"author": "Sir Rippov the Maple",
"author_id": 2822,
"author_profile": "https://Stackoverflow.com/users/2822",
"pm_score": 3,
"selected": false,
"text": "<p>There is another place where the TNS location is stored: If you're using Windows, open <code>regedit</code> and navigate to <code>My HKEY Local Machine/Software/ORACLE/KEY_OraClient10_home1</code> where <code>KEY_OraClient10_home1</code> is your Oracle home. If there is a string entry called <code>TNS_ADMIN</code>, then the value of that entry will point to the TNS file that Oracle is using on your computer.</p>\n"
},
{
"answer_id": 37235,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 2,
"selected": false,
"text": "<p>By default, tnsnames.ora is located in the $ORACLE_HOME/network/admin directory on UNIX operating systems and in the ORACLE_HOME\\network\\admin directory on Windows operating systems. tnsnames.ora can also be stored the following locations:</p>\n\n<p>The directory specified by the TNS_ADMIN environment variable (or registry value)</p>\n\n<p>On UNIX operating systems, the global configuration directory. For example, on the Solaris Operating System, this directory is /var/opt/oracle</p>\n\n<p>If you have multiple ORACLE_HOMES, be aware of which one you are using, as the location of the tnsnames.ora file can vary from one ORACLE_HOME to the next.</p>\n\n<p>For the person who mentioned the TWO_TASK environment variable, that is used to set a default database service name to connect to (which could be a database on another server). The service name you set TWO_TASK to is then looked up in the tnsnames.ora file when you connect.</p>\n"
},
{
"answer_id": 189142,
"author": "DCookie",
"author_id": 8670,
"author_profile": "https://Stackoverflow.com/users/8670",
"pm_score": 2,
"selected": false,
"text": "<p>Codeslave asks \"Shouldn't it always be \"$ORACLE_ HOME/network/admin/tnsnames.ora\"? The answer is no, it isn't. Consider these two invocations of tnsping on the same machine:</p>\n\n<pre><code>C:\\Documents and Settings\\me>D:\\Oracle\\10.2.0_DB\\BIN\\tnsping orcl\n\nTNS Ping Utility for 32-bit Windows: Version 10.2.0.4.0 - Production on 09-OCT-2\n008 14:30:12\n\nCopyright (c) 1997, 2007, Oracle. All rights reserved.\n\nUsed parameter files:\nD:\\Oracle\\10.2.0_DB\\network\\admin\\sqlnet.ora\n\n\nUsed TNSNAMES adapter to resolve the alias\nAttempting to contact (DESCRIPTION = (ADDRESS = (PROTOCOL = TCP)(HOST = xxxx\n)(PORT = 1521)) (CONNECT_DATA = (SERVER = DEDICATED) (SERVICE_NAME = ORCL)))\n\nOK (40 msec)\n\nC:\\Documents and Settings\\me>tnsping orcl\n\nTNS Ping Utility for 32-bit Windows: Version 10.2.0.1.0 - Production on 09-OCT-2\n008 14:30:21\n\nCopyright (c) 1997, 2005, Oracle. All rights reserved.\n\nUsed parameter files:\nD:\\oracle\\10.2.0_Client\\network\\admin\\sqlnet.ora\n\n\nUsed TNSNAMES adapter to resolve the alias\nAttempting to contact (DESCRIPTION = (ADDRESS_LIST = (ADDRESS = (PROTOCOL = TCP)\n(HOST = XXXX)(PORT = 1521))) (CONNECT_DATA = (SERVICE_NAME = ORCL)))\nOK (20 msec)\n\nC:\\Documents and Settings\\me>\n</code></pre>\n\n<p>Note the two different parameter file locations, that are dependent on which tnsping executable you're running (and perhaps where it's being run from). For tnsnames-based oracle networking, using the TNS_ADMIN variable is the only way to ensure you're getting a consistent tnsnames.ora file. (NOTE: Windows-centric answer)</p>\n"
},
{
"answer_id": 200344,
"author": "Rene",
"author_id": 17323,
"author_profile": "https://Stackoverflow.com/users/17323",
"pm_score": 3,
"selected": false,
"text": "<p>On my development machine I have three different versions of Oracle client software. I manage the <code>tnsnames.ora</code> file in one of them. In the other two, I have entered in the <code>tnsnames.ora</code> file:</p>\n\n<pre><code>ifile=path_to_tnsnames.ora_file/tnsnames.ora\n</code></pre>\n\n<p>This way, if for some reason the wrong <code>tnsnames.ora</code> file is used by a client, it will always end up at the up-to-date version.</p>\n"
},
{
"answer_id": 341948,
"author": "stili",
"author_id": 20763,
"author_profile": "https://Stackoverflow.com/users/20763",
"pm_score": 0,
"selected": false,
"text": "<p>The easiest way is probably to check the <strong>PATH</strong> environment variable of the process that is connecting to the database. Most likely the tnsnames.ora file is in <em>first Oracle bin directory in path</em>..\\network\\admin. TNS_ADMIN environment variable or value in registry (for the current Oracle home) may override this.</p>\n\n<p>Using filemon like suggested by others will also do the trick.</p>\n"
},
{
"answer_id": 20523156,
"author": "sri",
"author_id": 3091747,
"author_profile": "https://Stackoverflow.com/users/3091747",
"pm_score": 1,
"selected": false,
"text": "<p><code>strace sqlplus -L scott/tiger@orcl</code> helps to find <code>.tnsnames.ora</code> file on <code>/home/oracle</code> to find the file it takes instead of <code>$ORACLE_HOME/network/admin/tnsnames.ora</code> file. Thanks for the posting.</p>\n"
},
{
"answer_id": 36229027,
"author": "artybug",
"author_id": 6080126,
"author_profile": "https://Stackoverflow.com/users/6080126",
"pm_score": 1,
"selected": false,
"text": "<p>Not direct answer to your question, but I've been quite frustrated myself trying find and update all of the tnsnames files, as I had several oracle installs: Client, BI tools, OWB, etc, each of which had its own oracle home. I ended up creating a utility called TNSNamesSync that will update all of the tnsnames in all of the oracle homes. It's under the MIT license, free to use here <a href=\"https://github.com/artybug/TNSNamesSync/releases\" rel=\"nofollow\">https://github.com/artybug/TNSNamesSync/releases</a></p>\n\n<p>The docs are here:\n<a href=\"https://github.com/artchik/TNSNamesSync/blob/master/README.md\" rel=\"nofollow\">https://github.com/artchik/TNSNamesSync/blob/master/README.md</a></p>\n\n<p>This is for Windows only, though.</p>\n"
}
] | 2008/08/13 | [
"https://Stackoverflow.com/questions/10506",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/122/"
] | I am having a strange DB2 issue when I run DBUnit tests. My DBUnit tests are highly customized, but I don't think it is the issue. When I run the tests, I get a failure:
>
> SQLCODE: -1084, SQLSTATE: 57019
>
>
>
[which translates to](https://www1.columbia.edu/sec/acis/db2/db2m0/sql1000.htm)
>
> SQL1084C Shared memory segments cannot be allocated.
>
>
>
It sounds like a weird memory issue, though here's the big strange thing. If I ssh to the test database server, then go in to db2 and do "connect to MY\_DB", the tests start succeeding! This seems to have no relation to the supposed memory error that is being reported.
I have 2 tests, and the first one actually succeeds, the second one is the one that fails. However, it fails in the DBUnit setup code, when it is obtaining the connection to the DB server to load my xml dataset.
Any ideas what might be going on? | Oracle provides a utility called `tnsping`:
```
R:\>tnsping someconnection
TNS Ping Utility for 32-bit Windows: Version 9.0.1.3.1 - Production on 27-AUG-20
08 10:38:07
Copyright (c) 1997 Oracle Corporation. All rights reserved.
Used parameter files:
C:\Oracle92\network\ADMIN\sqlnet.ora
C:\Oracle92\network\ADMIN\tnsnames.ora
TNS-03505: Failed to resolve name
R:\>
R:\>tnsping entpr01
TNS Ping Utility for 32-bit Windows: Version 9.0.1.3.1 - Production on 27-AUG-20
08 10:39:22
Copyright (c) 1997 Oracle Corporation. All rights reserved.
Used parameter files:
C:\Oracle92\network\ADMIN\sqlnet.ora
C:\Oracle92\network\ADMIN\tnsnames.ora
Used TNSNAMES adapter to resolve the alias
Attempting to contact (DESCRIPTION = (ADDRESS_LIST = (ADDRESS = (COMMUNITY = **)
(PROTOCOL = TCP) (Host = ****) (Port = 1521))) (CONNECT_DATA = (SID = ENTPR0
1)))
OK (40 msec)
R:\>
```
This should show what file you're using. The utility sits in the Oracle `bin` directory. |
10,533 | <p>Here's a problem I ran into recently. I have attributes strings of the form</p>
<pre><code>"x=1 and y=abc and z=c4g and ..."
</code></pre>
<p>Some attributes have numeric values, some have alpha values, some have mixed, some have dates, etc.</p>
<p>Every string is <em>supposed</em> to have "<code>x=someval and y=anotherval</code>" at the beginning, but some don't. I have three things I need to do. </p>
<ol>
<li>Validate the strings to be certain that they have <code>x</code> and <code>y</code>. </li>
<li>Actually parse the values for <code>x</code> and <code>y</code>.</li>
<li>Get the rest of the string.</li>
</ol>
<p>Given the example at the top, this would result in the following variables:</p>
<pre><code>$x = 1;
$y = "abc";
$remainder = "z=c4g and ..."
</code></pre>
<p>My question is: Is there a (reasonably) simple way to parse these <em>and</em> validate with a single regular expression? i.e.:</p>
<pre><code>if ($str =~ /someexpression/)
{
$x = $1;
$y = $2;
$remainder = $3;
}
</code></pre>
<p>Note that the string may consist of <em>only</em> <code>x</code> and <code>y</code> attributes. This is a valid string.</p>
<p>I'll post my solution as an answer, but it doesn't meet my single-regex preference.</p>
| [
{
"answer_id": 10537,
"author": "Derek Park",
"author_id": 872,
"author_profile": "https://Stackoverflow.com/users/872",
"pm_score": 0,
"selected": false,
"text": "<p>Here's basically what I did to solve this:</p>\n\n<pre><code>($x_str, $y_str, $remainder) = split(/ and /, $str, 3);\n\nif ($x_str !~ /x=(.*)/)\n{\n # error\n}\n\n$x = $1;\n\nif ($y_str !~ /y=(.*)/)\n{\n # error\n}\n\n$y = $1;\n</code></pre>\n\n<p>I've omitted some additional validation and error handling. This technique works, but it's not as concise or pretty as I would have liked. I'm hoping someone will have a better suggestion for me.</p>\n"
},
{
"answer_id": 10573,
"author": "Rudd Zwolinski",
"author_id": 219,
"author_profile": "https://Stackoverflow.com/users/219",
"pm_score": 2,
"selected": true,
"text": "<p>I'm not the best at regular expressions, but this seems pretty close to what you're looking for:</p>\n\n<pre><code>/x=(.+) and y=([^ ]+)( and (.*))?/\n</code></pre>\n\n<p>Except you use $1, $2, and $4. In use:</p>\n\n<pre><code>my @strs = (\"x=1 and y=abc and z=c4g and w=v4l\",\n \"x=yes and y=no\",\n \"z=nox and w=noy\");\n\nforeach (@strs) {\n if ($_ =~ /x=(.+) and y=([^ ]+)( and (.*))?/) {\n $x = $1;\n $y = $2;\n $remainder = $4;\n print \"x: $x; y: $y; remainder: $remainder\\n\";\n } else {\n print \"Failed.\\n\";\n }\n}\n</code></pre>\n\n<p>Output:</p>\n\n<pre><code>x: 1; y: abc; remainder: z=c4g and w=v4l\nx: yes; y: no; remainder: \nFailed.\n</code></pre>\n\n<p>This of course leaves out plenty of error checking, and I don't know everything about your inputs, but this seems to work.</p>\n"
},
{
"answer_id": 13677,
"author": "Cebjyre",
"author_id": 1612,
"author_profile": "https://Stackoverflow.com/users/1612",
"pm_score": 1,
"selected": false,
"text": "<p>As a fairly simple modification to Rudd's version,</p>\n\n<pre><code>/^x=(.+) and y=([^ ]+)(?: and (.*))?/\n</code></pre>\n\n<p>will allow you to use $1, $2 and $3 (the ?: makes it a noncapturing group), and will ensure that the string starts with \"x=\" rather than allowing a \"not_x=\" to match</p>\n\n<p>If you have better knowledge of what the x and y values will be, this should be used to tighten the regex further:</p>\n\n<pre><code>my @strs = (\"x=1 and y=abc and z=c4g and w=v4l\",\n \"x=yes and y=no\",\n \"z=nox and w=noy\",\n \"not-x=nox and y=present\",\n \"x=yes and w='there is no and y=something arg here'\");\n\nforeach (@strs) {\n if ($_ =~ /^x=(.+) and y=([^ ]+)(?: and (.*))?/) {\n $x = $1;\n $y = $2;\n $remainder = $3;\n print \"x: {$x}; y: {$y}; remainder: {$remainder}\\n\";\n } else {\n print \"$_ Failed.\\n\";\n }\n}\n</code></pre>\n\n<p>Output:</p>\n\n<pre><code>x: {1}; y: {abc}; remainder: {z=c4g and w=v4l}\nx: {yes}; y: {no}; remainder: {}\nz=nox and w=noy Failed.\nnot-x=nox and y=present Failed.\nx: {yes and w='there is no}; y: {something}; remainder: {}\n</code></pre>\n\n<p>Note that the missing part of the last test is due to the current version of the y test requiring no spaces, if the x test had the same restriction that string would have failed.</p>\n"
},
{
"answer_id": 21003,
"author": "Brad Gilbert",
"author_id": 1337,
"author_profile": "https://Stackoverflow.com/users/1337",
"pm_score": 2,
"selected": false,
"text": "<p>Assuming you also want to do something with the other name=value pairs this is how I would do it ( using Perl version 5.10 ):</p>\n\n<pre><code>use 5.10.0;\nuse strict;\nuse warnings;\n\nmy %hash;\nwhile(\n $string =~ m{\n (?: ^ | \\G ) # start of string or previous match\n \\s*\n\n (?<key> \\w+ ) # word characters\n =\n (?<value> \\S+ ) # non spaces\n\n \\s* # get to the start of the next match\n (?: and )?\n }xgi\n){\n $hash{$+{key}} = $+{value};\n}\n\n# to make sure that x & y exist\ndie unless exists $hash{x} and exists $hash{y};\n</code></pre>\n\n<p>On older Perls ( at least Perl 5.6 );</p>\n\n<pre><code>use strict;\nuse warnings;\n\nmy %hash;\nwhile(\n $string =~ m{\n (?: ^ | \\G ) # start of string or previous match\n \\s*\n\n ( \\w+ ) = ( \\S+ )\n\n \\s* # get to the start of the next match\n (?: and )?\n }xgi\n){\n $hash{$1} = $2;\n}\n\n# to make sure that x & y exist\ndie unless exists $hash{x} and exists $hash{y};\n</code></pre>\n\n<p>These have the added benefit of continuing to work if you need to work with more data.</p>\n"
},
{
"answer_id": 63872,
"author": "Frosty",
"author_id": 7476,
"author_profile": "https://Stackoverflow.com/users/7476",
"pm_score": 1,
"selected": false,
"text": "<p>Rudd and Cebjyre have gotten you most of the way there but they both have certain problems:</p>\n\n<p>Rudd suggested:</p>\n\n<blockquote>\n <p>/x=(.+) and y=([^ ]+)( and (.*))?/</p>\n</blockquote>\n\n<p>Cebjyre modified it to:</p>\n\n<blockquote>\n <p>/^x=(.+) and y=([^ ]+)(?: and (.*))?/</p>\n</blockquote>\n\n<p>The second version is better because it will not confuse \"not_x=foo\" with \"x=foo\" but will accept things such as \"x=foo z=bar y=baz\" and set $1 = \"foo z=bar\" which is undesirable.</p>\n\n<p>This is probably what you are looking for:</p>\n\n<blockquote>\n <p>/^x=(\\w+) and y=(\\w+)(?: and (.*))?/</p>\n</blockquote>\n\n<p>This disallows anything between the x= and y= options, places and allows and optional \" and...\" which will be in $3</p>\n"
}
] | 2008/08/14 | [
"https://Stackoverflow.com/questions/10533",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/872/"
] | Here's a problem I ran into recently. I have attributes strings of the form
```
"x=1 and y=abc and z=c4g and ..."
```
Some attributes have numeric values, some have alpha values, some have mixed, some have dates, etc.
Every string is *supposed* to have "`x=someval and y=anotherval`" at the beginning, but some don't. I have three things I need to do.
1. Validate the strings to be certain that they have `x` and `y`.
2. Actually parse the values for `x` and `y`.
3. Get the rest of the string.
Given the example at the top, this would result in the following variables:
```
$x = 1;
$y = "abc";
$remainder = "z=c4g and ..."
```
My question is: Is there a (reasonably) simple way to parse these *and* validate with a single regular expression? i.e.:
```
if ($str =~ /someexpression/)
{
$x = $1;
$y = $2;
$remainder = $3;
}
```
Note that the string may consist of *only* `x` and `y` attributes. This is a valid string.
I'll post my solution as an answer, but it doesn't meet my single-regex preference. | I'm not the best at regular expressions, but this seems pretty close to what you're looking for:
```
/x=(.+) and y=([^ ]+)( and (.*))?/
```
Except you use $1, $2, and $4. In use:
```
my @strs = ("x=1 and y=abc and z=c4g and w=v4l",
"x=yes and y=no",
"z=nox and w=noy");
foreach (@strs) {
if ($_ =~ /x=(.+) and y=([^ ]+)( and (.*))?/) {
$x = $1;
$y = $2;
$remainder = $4;
print "x: $x; y: $y; remainder: $remainder\n";
} else {
print "Failed.\n";
}
}
```
Output:
```
x: 1; y: abc; remainder: z=c4g and w=v4l
x: yes; y: no; remainder:
Failed.
```
This of course leaves out plenty of error checking, and I don't know everything about your inputs, but this seems to work. |
10,564 | <p>I'm trying out <strong>Git on Windows</strong>. I got to the point of trying "git commit" and I got this error:</p>
<blockquote>
<p>Terminal is dumb but no VISUAL nor
EDITOR defined. Please supply the
message using either -m or -F option.</p>
</blockquote>
<p>So I figured out I need to have an environment variable called EDITOR. No problem. I set it to point to Notepad. That worked, almost. The default commit message opens in Notepad. But Notepad doesn't support bare line feeds. I went out and got <a href="http://notepad-plus.sourceforge.net/uk/site.htm" rel="noreferrer">Notepad++</a>, but I can't figure out how to get Notepad++ set up as the <code>%EDITOR%</code> in such a way that it works with Git as expected.</p>
<p>I'm not married to Notepad++. At this point I don't mind what editor I use. I just want to be able to <strong>type commit messages in an editor</strong> rather than the command line (with <code>-m</code>).</p>
<p>Those of you using Git on Windows: What tool do you use to edit your commit messages, and what did you have to do to make it work?</p>
| [
{
"answer_id": 10574,
"author": "J Wynia",
"author_id": 1124,
"author_profile": "https://Stackoverflow.com/users/1124",
"pm_score": 1,
"selected": false,
"text": "<p>I've had difficulty getting Git to cooperate with <a href=\"http://en.wikipedia.org/wiki/WordPad\" rel=\"nofollow noreferrer\">WordPad</a>, <a href=\"https://en.wikipedia.org/wiki/Komodo_Edit\" rel=\"nofollow noreferrer\">Komodo Edit</a> and pretty much every other editor I give it. Most open for editing, but Git clearly doesn't wait for the save/close to happen. </p>\n\n<p>As a crutch, I've just been doing i.e.</p>\n\n<pre><code>git commit -m \"Fixed the LoadAll method\"\n</code></pre>\n\n<p>to keep things moving. It tends to keep my commit messages a little shorter than they probably should be, but clearly there's some work to be done on the Windows version of Git.</p>\n\n<p>The GitGUI also isn't that bad. It takes a little bit of orientation, but after that, it works fairly well.</p>\n"
},
{
"answer_id": 10625,
"author": "Patrick Johnmeyer",
"author_id": 363,
"author_profile": "https://Stackoverflow.com/users/363",
"pm_score": 4,
"selected": false,
"text": "<p>Notepad++ works just fine, although I choose to stick with Notepad, -m, or even sometimes the built-in \"edit.\"</p>\n\n<p>The problem you are encountering using Notepad++ is related to how Git is launching the editor executable. My solution to this is to set environment variable <code>EDITOR</code> to a batch file, rather than the actual editor executable, that does the following:</p>\n\n<pre><code>start /WAIT \"E:\\PortableApps\\Notepad++Portable\\Notepad++Portable.exe\" %*\n</code></pre>\n\n<p><code>/WAIT</code> tells the command line session to halt until the application exits, thus you will be able to edit to your heart's content while Git happily waits for you. %* passes all arguments to the batch file through to Notepad++.</p>\n\n<pre><code>C:\\src> echo %EDITOR%\nC:\\tools\\runeditor.bat\n</code></pre>\n"
},
{
"answer_id": 11129,
"author": "Matt McMinn",
"author_id": 1322,
"author_profile": "https://Stackoverflow.com/users/1322",
"pm_score": 3,
"selected": false,
"text": "<p><a href=\"http://www.vim.org/\" rel=\"nofollow noreferrer\">Vim/gVim</a> works well for me.</p>\n\n<pre><code>>echo %EDITOR%\n\nc:\\Vim\\Vim71\\vim.exe\n</code></pre>\n"
},
{
"answer_id": 640142,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 2,
"selected": false,
"text": "<p>It seems as if Git won't find the editor if there are spaces in the path. So you will have to put the batch file mentioned in <a href=\"https://stackoverflow.com/questions/10564/how-can-i-set-up-an-editor-to-work-with-git-on-windows/10625#10625\">Patrick's answer</a> into a non-whitespace path.</p>\n"
},
{
"answer_id": 773973,
"author": "VonC",
"author_id": 6309,
"author_profile": "https://Stackoverflow.com/users/6309",
"pm_score": 10,
"selected": true,
"text": "<p>Update September 2015 (6 years later)</p>\n\n<p>The <a href=\"https://github.com/git-for-windows/git/releases/tag/v2.5.3.windows.1\" rel=\"noreferrer\">last release of git-for-Windows (2.5.3)</a> now includes:</p>\n\n<blockquote>\n <p>By configuring <strong><code>git config core.editor notepad</code></strong>, users <a href=\"https://github.com/git-for-windows/git/issues/381\" rel=\"noreferrer\">can now use <code>notepad.exe</code> as their default editor</a>.<br>\n Configuring <code>git config format.commitMessageColumns 72</code> will be picked up by the notepad wrapper and line-wrap the commit message after the user edits it.</p>\n</blockquote>\n\n<p>See <a href=\"https://github.com/git-for-windows/build-extra/commit/69b301bbd7c18226c63d83638991cb2b7f84fb64\" rel=\"noreferrer\">commit 69b301b</a> by <a href=\"https://github.com/dscho\" rel=\"noreferrer\">Johannes Schindelin (<code>dscho</code>)</a>.</p>\n\n<p>And Git 2.16 (Q1 2018) will show a message to tell the user that it is waiting for the user to finish editing when spawning an editor, in case the editor\nopens to a hidden window or somewhere obscure and the user gets\nlost.</p>\n\n<p>See <a href=\"https://github.com/git/git/commit/abfb04d0c74cde804c734015ff5868a88c84fb6f\" rel=\"noreferrer\">commit abfb04d</a> (07 Dec 2017), and <a href=\"https://github.com/git/git/commit/a64f213d3fa13fa01e582b6734fe7883ed975dc9\" rel=\"noreferrer\">commit a64f213</a> (29 Nov 2017) by <a href=\"https://github.com/larsxschneider\" rel=\"noreferrer\">Lars Schneider (<code>larsxschneider</code>)</a>.<br>\nHelped-by: <a href=\"https://github.com/gitster\" rel=\"noreferrer\">Junio C Hamano (<code>gitster</code>)</a>.<br>\n<sup>(Merged by <a href=\"https://github.com/gitster\" rel=\"noreferrer\">Junio C Hamano -- <code>gitster</code> --</a> in <a href=\"https://github.com/git/git/commit/0c69a132cb1adf0ce9f31e6631f89321e437cb76\" rel=\"noreferrer\">commit 0c69a13</a>, 19 Dec 2017)</sup></p>\n\n<blockquote>\n <h2><code>launch_editor()</code>: indicate that Git waits for user input</h2>\n \n <p>When a graphical <code>GIT_EDITOR</code> is spawned by a Git command that opens\n and waits for user input (e.g. \"<code>git rebase -i</code>\"), then the editor window\n might be obscured by other windows.<br>\n The user might be left staring at\n the original Git terminal window without even realizing that s/he needs\n to interact with another window before Git can proceed. To this user Git\n appears hanging.</p>\n \n <p>Print a message that Git is waiting for editor input in the original\n terminal and get rid of it when the editor returns, if the terminal\n supports erasing the last line</p>\n</blockquote>\n\n<hr>\n\n<p>Original answer</p>\n\n<p>I just tested it with git version 1.6.2.msysgit.0.186.gf7512 and Notepad++5.3.1</p>\n\n<p>I prefer to <em>not</em> have to set an EDITOR variable, so I tried:</p>\n\n<pre class=\"lang-bash prettyprint-override\"><code>git config --global core.editor \"\\\"c:\\Program Files\\Notepad++\\notepad++.exe\\\"\"\n# or\ngit config --global core.editor \"\\\"c:\\Program Files\\Notepad++\\notepad++.exe\\\" %*\"\n</code></pre>\n\n<p>That always gives:</p>\n\n<pre><code>C:\\prog\\git>git config --global --edit\n\"c:\\Program Files\\Notepad++\\notepad++.exe\" %*: c:\\Program Files\\Notepad++\\notepad++.exe: command not found\nerror: There was a problem with the editor '\"c:\\Program Files\\Notepad++\\notepad++.exe\" %*'.\n</code></pre>\n\n<p>If I define a npp.bat including:</p>\n\n<pre><code>\"c:\\Program Files\\Notepad++\\notepad++.exe\" %*\n</code></pre>\n\n<p>and I type:</p>\n\n<pre><code>C:\\prog\\git>git config --global core.editor C:\\prog\\git\\npp.bat\n</code></pre>\n\n<p>It just works from the DOS session, <strong>but not from the git shell</strong>.<br>\n(not that with the core.editor configuration mechanism, a script with \"<code>start /WAIT...</code>\" in it would not work, but only open a new DOS window)</p>\n\n<hr>\n\n<p><a href=\"https://stackoverflow.com/questions/10564/how-can-i-set-up-an-editor-to-work-with-git-on-windows/1431003#1431003\">Bennett's answer</a> mentions the possibility to avoid adding a script, but to reference directly the program itself <strong>between simple quotes</strong>. Note the direction of the slashes! Use <code>/</code> NOT <code>\\</code> to separate folders in the path name!</p>\n\n<pre class=\"lang-bash prettyprint-override\"><code>git config --global core.editor \\\n\"'C:/Program Files/Notepad++/notepad++.exe' -multiInst -notabbar -nosession -noPlugin\"\n</code></pre>\n\n<p>Or if you are in a 64 bit system:</p>\n\n<pre class=\"lang-bash prettyprint-override\"><code>git config --global core.editor \\\n\"'C:/Program Files (x86)/Notepad++/notepad++.exe' -multiInst -notabbar -nosession -noPlugin\"\n</code></pre>\n\n<p>But I prefer using a script (see below): that way I can play with different paths or different options without having to register again a <code>git config</code>.</p>\n\n<hr>\n\n<p>The actual solution (with a script) was to realize that:<br>\n<strong>what you refer to in the config file is actually a shell (<code>/bin/sh</code>) script</strong>, not a DOS script.</p>\n\n<p>So what does work is:</p>\n\n<pre><code>C:\\prog\\git>git config --global core.editor C:/prog/git/npp.bat\n</code></pre>\n\n<p>with <code>C:/prog/git/npp.bat</code>:</p>\n\n<pre class=\"lang-bash prettyprint-override\"><code>#!/bin/sh\n\"c:/Program Files/Notepad++/notepad++.exe\" -multiInst \"$*\"\n</code></pre>\n\n<p>or</p>\n\n<pre class=\"lang-bash prettyprint-override\"><code>#!/bin/sh\n\"c:/Program Files/Notepad++/notepad++.exe\" -multiInst -notabbar -nosession -noPlugin \"$*\"\n</code></pre>\n\n<p>With that setting, I can do '<code>git config --global --edit</code>' from DOS or Git Shell, or I can do '<code>git rebase -i ...</code>' from DOS or Git Shell.<br>\nBot commands will trigger a new instance of notepad++ (hence the <code>-multiInst</code>' option), and wait for that instance to be closed before going on.</p>\n\n<p>Note that I use only '/', not <code>\\</code>'. And I <a href=\"https://stackoverflow.com/questions/623518/msysgit-on-windows-what-should-i-be-aware-of-if-any\">installed msysgit using option 2.</a> (Add the <code>git\\bin</code> directory to the <code>PATH</code> environment variable, but without overriding some built-in windows tools)</p>\n\n<p>The fact that the notepad++ wrapper is called .bat is not important.<br>\nIt would be better to name it 'npp.sh' and to put it in the <code>[git]\\cmd</code> directory though (or in any directory referenced by your PATH environment variable).</p>\n\n<hr>\n\n<p>See also:</p>\n\n<ul>\n<li><a href=\"https://stackoverflow.com/questions/255202/how-do-i-view-git-diff-output-with-visual-diff-program/255212#255212\">How do I view ‘git diff’ output with visual diff program?</a> for the general theory</li>\n<li><a href=\"https://stackoverflow.com/questions/780425/how-do-i-setup-diffmerge-with-msysgit-gitk/783667#783667\">How do I setup DiffMerge with msysgit / gitk?</a> for another example of external tool (DiffMerge, and WinMerge)</li>\n</ul>\n\n<hr>\n\n<p><a href=\"https://stackoverflow.com/users/2716305/lightfire228\">lightfire228</a> adds <a href=\"https://stackoverflow.com/questions/10564/how-can-i-set-up-an-editor-to-work-with-git-on-windows/773973#comment74027740_773973\">in the comments</a>:</p>\n\n<blockquote>\n <p>For anyone having an issue where N++ just opens a blank file, and git doesn't take your commit message, see \"<a href=\"https://stackoverflow.com/q/30085970/6309\">Aborting commit due to empty message</a>\": change your <code>.bat</code> or <code>.sh</code> file to say:</p>\n</blockquote>\n\n<pre><code>\"<path-to-n++\" .git/COMMIT_EDITMSG -<arguments>. \n</code></pre>\n\n<blockquote>\n <p>That will tell notepad++ to open the temp commit file, rather than a blank new one.</p>\n</blockquote>\n"
},
{
"answer_id": 1083830,
"author": "Darren Bishop",
"author_id": 133330,
"author_profile": "https://Stackoverflow.com/users/133330",
"pm_score": 6,
"selected": false,
"text": "<p>Anyway, I've just been playing around with this and found the following to work nicely for me:</p>\n\n<pre><code>git config --global core.editor \"'C:/Program Files/TextPad 5/TextPad.exe' -m\"\n</code></pre>\n\n<p>I don't think CMD likes single-quotes so you must use double quotes \"to specify the space embedded string argument\".</p>\n\n<p>Cygwin (which I believe is the underlying platform for Git's Bash) on the other hand likes both <code>'</code> and <code>\"</code>; you can specify a CMD-like paths, using <code>/</code> instead of <code>\\</code>, so long as the string is quoted i.e. in this instance, using single-quotes.</p>\n\n<p>The <code>-m</code> overrides/indicates the use of multiple editors and there is no need for a <code>%*</code> tacked on the end.</p>\n"
},
{
"answer_id": 1086587,
"author": "bjnortier",
"author_id": 35448,
"author_profile": "https://Stackoverflow.com/users/35448",
"pm_score": 2,
"selected": false,
"text": "<p>I use <a href=\"http://en.wikipedia.org/wiki/Cygwin\" rel=\"nofollow noreferrer\">Cygwin</a> on Windows, so I use:</p>\n\n<pre><code>export EDITOR=\"emacs -nw\"\n</code></pre>\n\n<p>The <code>-nw</code> is for <code>no-windows</code>, i.e. tell Emacs not to try and use <a href=\"http://en.wikipedia.org/wiki/X_Window_System\" rel=\"nofollow noreferrer\">X Window</a>.</p>\n\n<p>The Emacs keybindings don't work for me from a Windows shell, so I would only use this from a Cygwin shell... (<a href=\"https://en.wikipedia.org/wiki/Rxvt\" rel=\"nofollow noreferrer\">rxvt</a> is recommended.)</p>\n"
},
{
"answer_id": 1380109,
"author": "Tom Dunham",
"author_id": 6402,
"author_profile": "https://Stackoverflow.com/users/6402",
"pm_score": 1,
"selected": false,
"text": "<p>I've just had the same problem and found a different solution. I was getting </p>\n\n<pre><code>error: There was a problem with the editor 'ec'\n</code></pre>\n\n<p>I've got <code>VISUAL=ec</code>, and a batch file called <code>ec.bat</code> on my path that contains one line:</p>\n\n<pre><code>c:\\emacs\\emacs-23.1\\bin\\emacsclient.exe %*\n</code></pre>\n\n<p>This lets me edit files from the command line with <code>ec <filename></code>, and having <code>VISUAL</code> set means most unixy programs pick it up too. Git seems to search the path differently to my other commands though - when I looked at a <code>git commit</code> in <a href=\"http://en.wikipedia.org/wiki/Process_Monitor\" rel=\"nofollow noreferrer\">Process Monitor</a> I saw it look in every folder on the path for <code>ec</code> and for <code>ec.exe</code>, but not for <code>ec.bat</code>. I added another environment variable (<code>GIT_EDITOR=ec.bat</code>) and all was fine.</p>\n"
},
{
"answer_id": 1431003,
"author": "Bennett McElwee",
"author_id": 61754,
"author_profile": "https://Stackoverflow.com/users/61754",
"pm_score": 8,
"selected": false,
"text": "<p>Building on <a href=\"https://stackoverflow.com/questions/10564/how-can-i-set-up-an-editor-to-work-with-git-on-windows/1083830#1083830\">Darren's answer</a>, to use Notepad++ you can simply do this (all on one line):</p>\n<pre><code>git config --global core.editor "'C:/Program Files/Notepad++/notepad++.exe' -multiInst -notabbar -nosession -noPlugin"\n</code></pre>\n<p>Obviously, the <code>C:/Program Files/Notepad++/notepad++.exe</code> part should be the path to the Notepad++ executable on your system. For example, it might be <code>C:/Program Files (x86)/Notepad++/notepad++.exe</code>.</p>\n<p>It works like a charm for me.</p>\n<p>Article <a href=\"https://www.theserverside.com/blog/Coffee-Talk-Java-News-Stories-and-Opinions/How-to-set-Notepad-as-the-default-Git-editor-for-commits-instead-of-Vim\" rel=\"noreferrer\">How to set Notepad++ as the default Git editor for commits instead of Vim</a> explains parameters of the command.</p>\n"
},
{
"answer_id": 1574521,
"author": "Tim Henigan",
"author_id": 63147,
"author_profile": "https://Stackoverflow.com/users/63147",
"pm_score": 3,
"selected": false,
"text": "<p>I also use Cygwin on Windows, but with gVim (as opposed to the terminal-based <a href=\"http://en.wikipedia.org/wiki/Vim_%28text_editor%29\" rel=\"nofollow noreferrer\">Vim</a>).</p>\n\n<p>To make this work, I have done the following:</p>\n\n<ol>\n<li>Created a one-line batch file (named <code>git_editor.bat</code>) which contains the following:\n<code>\"C:/Program Files/Vim/vim72/gvim.exe\" --nofork \"%*\"</code></li>\n<li>Placed <code>git_editor.bat</code> on in my <code>PATH</code>.</li>\n<li>Set <code>GIT_EDITOR=git_editor.bat</code></li>\n</ol>\n\n<p>With this done, <code>git commit</code>, etc. will correctly invoke the gVim executable.</p>\n\n<p>NOTE 1: The <code>--nofork</code> option to gVim ensures that it blocks until the commit message has been written.</p>\n\n<p>NOTE 2: The quotes around the path to gVim is required if you have spaces in the path.</p>\n\n<p>NOTE 3: The quotes around \"%*\" are needed just in case Git passes a file path with spaces.</p>\n"
},
{
"answer_id": 2583824,
"author": "Whome",
"author_id": 185565,
"author_profile": "https://Stackoverflow.com/users/185565",
"pm_score": 3,
"selected": false,
"text": "<p>I had PortableGit 1.6 working fine, but after upgrading to the PortableGit 1.7 Windows release, I had problems. Some of the Git commands opens up the Notepad++.exe fine, but some don't, especially <em>Git rebase</em> behaves differently.</p>\n\n<p>The problem is some commands run the Windows cmd process and some use the Unix cmd process. I want to give startup attributes to Notepad++ editor, so I need to have a customized script. My solution is this.</p>\n\n<ol>\n<li><p>Create a script to run an appropriate text editor. The script looks weird, but it handles both the Windows and Unix variation.</p>\n\n<p><strong>c:/PortableGit/cmd/git-editor.bat</strong></p>\n\n<pre><code>#!/bin/sh\n# Open a new instance\n\nfunction doUnix() {\n \"c:\\program files\\notepad++\\notepad++.exe\" -multiInst -nosession -notabbar $*\n exit\n}\n\ndoUnix $*\n\n:WINCALL\n\"c:\\program files\\notepad++\\notepad++.exe\" -multiInst -nosession -notabbar %*\n</code></pre></li>\n<li><p>Set the global core.editor variable</p>\n\n<p>The script was saved to git/cmd folder, so it's already in a gitconsole path. This is mandatory as a full path may not work properly.</p>\n\n<pre><code>git config --global core.editor \"git-editor.bat\"\n</code></pre></li>\n</ol>\n\n<p>Now I can run the <em>git commit -a</em> and <em>git rebase -i master</em> commands. Give it a try if you have problems in the Git Windows tool.</p>\n"
},
{
"answer_id": 3319715,
"author": "Michael Steele",
"author_id": 71116,
"author_profile": "https://Stackoverflow.com/users/71116",
"pm_score": 2,
"selected": false,
"text": "<p>I prefer to use Emacs. Getting it set up can be a little tricky.</p>\n\n<ol>\n<li>Download Emacs and unpack it somewhere like <code>c:\\emacs</code>.</li>\n<li>Run <code>c:\\emacs\\bin\\addpm.exe</code>. You need to right-click and \"Run as Administrator\" if you are using Windows Vista or above. This will put the executables in your path.</li>\n<li>Add <code>(server-start)</code> somewhere in your <code>.emacs</code> file. See the <a href=\"http://www.gnu.org/software/emacs/windows/Installing-Emacs.html#Installing-Emacs\" rel=\"nofollow noreferrer\">Emacs Windows FAQ</a> for advice on where to put your <code>.emacs</code> file.</li>\n<li><code>git config --global core.editor emacsclientw</code></li>\n</ol>\n\n<p>Git will now open files within an existing Emacs process. You will have to run that existing process manually from <code>c:\\emacs\\bin\\runemacs.exe</code>.</p>\n"
},
{
"answer_id": 3422569,
"author": "Gavin",
"author_id": 78216,
"author_profile": "https://Stackoverflow.com/users/78216",
"pm_score": 4,
"selected": false,
"text": "<p><strong><a href=\"http://en.wikipedia.org/wiki/WordPad\" rel=\"nofollow noreferrer\">WordPad</a>!</strong></p>\n\n<p>I'm happy using Vim, but since I'm trying to introduce Git to the company I wanted something that we'd all have, and found that WordPad seems to work okay (i.e. Git does wait until you're finished editing and close the window).</p>\n\n<pre><code>git config core.editor '\"C:\\Program Files\\Windows NT\\Accessories\\wordpad.exe\"'\n</code></pre>\n\n<p>That's using Git Bash on msysgit; I've not tried from the Windows command prompt (if that makes any difference).</p>\n"
},
{
"answer_id": 3820077,
"author": "CharlesB",
"author_id": 11343,
"author_profile": "https://Stackoverflow.com/users/11343",
"pm_score": 2,
"selected": false,
"text": "<p>This is my setup to use <a href=\"http://www.geany.org/\" rel=\"nofollow noreferrer\">Geany</a> as an editor for Git:</p>\n\n<pre><code>git config --global core.editor C:/path/to/geany.bat\n</code></pre>\n\n<p>with the following content in <code>geany.bat</code>:</p>\n\n<pre><code>#!/bin/sh\n\"C:\\Program Files\\Geany\\bin\\Geany.exe\" --new-instance \"$*\"\n</code></pre>\n\n<p>It works in both a DOS console and msysgit.</p>\n"
},
{
"answer_id": 4652019,
"author": "Nick Knowlson",
"author_id": 224354,
"author_profile": "https://Stackoverflow.com/users/224354",
"pm_score": 5,
"selected": false,
"text": "<p><strong>Edit:</strong> After updating to Vim 7.3, I've come to the conclusion that the cleanest and easiest way to do this is:</p>\n\n<ol>\n<li><p>Add Vim's main folder to your path (right click on <em>My Computer</em> → <em>Properties</em> → <em>Advanced</em> → <em>Environment Variables</em>)</p></li>\n<li><p>Run this:</p>\n\n<pre><code>git config --global core.editor \"gvim --nofork '%*'\"\n</code></pre></li>\n</ol>\n\n<p>If you do it this way, then I am fairly sure it will work with Cygwin as well.</p>\n\n<p><strong>Original answer:</strong></p>\n\n<p>Even with a couple of Vim-related answers, I was having trouble getting this to work with gVim under Windows (while not using a batch file or %EDITOR% or Cygwin).</p>\n\n<p>What I eventually arrived at is nice and clean, and draws from a few of the solutions here:</p>\n\n<pre class=\"lang-bash prettyprint-override\"><code>git config --global core.editor \\\n\"'C:/Program Files/Vim/vim72/gvim.exe' --nofork '%*'\"\n</code></pre>\n\n<p>One gotcha that took me a while is these are not the Windows-style backslashes. They are normal forward slashes.</p>\n"
},
{
"answer_id": 4792999,
"author": "Mike",
"author_id": 419934,
"author_profile": "https://Stackoverflow.com/users/419934",
"pm_score": 1,
"selected": false,
"text": "<p>I managed to get the environment version working by setting the EDITOR variable using quotes and <code>/</code>:</p>\n\n<pre><code>EDITOR=\"c:/Program Files (x86)/Notepad++/notepad++.exe\"\n</code></pre>\n"
},
{
"answer_id": 6626128,
"author": "lambacck",
"author_id": 108518,
"author_profile": "https://Stackoverflow.com/users/108518",
"pm_score": 3,
"selected": false,
"text": "<p>This is the one symptom of greater issues. Notably that you have something setting <code>TERM=dumb</code>. Other things that don't work properly are the <code>less</code> command which says you don't have a fully functional terminal.</p>\n\n<p>It seems like this is most commonly caused by having TERM set to something in your global Windows environment variables. For me, the issue came up when I installed <a href=\"http://en.wikipedia.org/wiki/Strawberry_Perl\" rel=\"nofollow noreferrer\">Strawberry Perl</a> some information about this is on the <a href=\"http://code.google.com/p/msysgit/issues/detail?id=184#c42\" rel=\"nofollow noreferrer\">msysgit bug for this problem</a> as well as several solutions.</p>\n\n<p>The first solution is to fix it in your ~/.bashrc by adding:</p>\n\n<pre><code>export TERM=msys\n</code></pre>\n\n<p>You can do this from the Git Bash prompt like so:</p>\n\n<pre><code>echo \"export TERM=msys\" >> ~/.bashrc\n</code></pre>\n\n<p>The other solution, which ultimately is what I did because I don't care about Strawberry Perl's reasons for adding <code>TERM=dumb</code> to my environment settings, is to go and remove the <code>TERM=dumb</code> as <a href=\"http://code.google.com/p/msysgit/issues/detail?id=184#c40\" rel=\"nofollow noreferrer\">directed in this comment on the msysgit bug report</a>.</p>\n\n<blockquote>\n <p>Control\n Panel/System/Advanced/Environment\n Variables... (or similar, depending on\n your version of Windows) is where\n sticky environment variables are set\n on Windows. By default, TERM is not\n set. If TERM is set in there, then you\n (or one of the programs you have\n installed - e.g. Strawberry Perl) has\n set it. Delete that setting, and you\n should be fine.</p>\n</blockquote>\n\n<p>Similarly if you use Strawberry Perl and care about the <a href=\"http://en.wikipedia.org/wiki/CPAN\" rel=\"nofollow noreferrer\">CPAN</a> client or something like that, you can leave the <code>TERM=dumb</code> alone and use <code>unset TERM</code> in your ~/.bashrc file which will have a similar effect to setting an explicit term as above.</p>\n\n<p>Of course, all the other solutions are correct in that you can use <code>git config --global core.editor $MYFAVORITEEDITOR</code> to make sure that Git uses your favorite editor when it needs to launch one for you.</p>\n"
},
{
"answer_id": 7163913,
"author": "mbx",
"author_id": 303290,
"author_profile": "https://Stackoverflow.com/users/303290",
"pm_score": 0,
"selected": false,
"text": "<p>When using a remotely mounted homedrive (<a href=\"http://en.wikipedia.org/wiki/Samba_%28software%29\" rel=\"nofollow noreferrer\">Samba</a> share, NFS, ...) your <code>~/.git</code> folder is shared across all systems which can lead to several problems. Thus I prefer a script to determine the right editor for the right system:</p>\n\n<pre><code>#!/usr/bin/perl\n# Detect which system I'm on and choose the right editor\n$unamea = `uname -a`;\nif($unamea =~ /mingw/i){\n if($unamea =~ /devsystem/i){#Check hostname\n exec('C:\\Program Files (x86)\\Notepad++\\notepad++.exe', '-multiInst', '-nosession', @ARGV);\n }\n if($unamea =~ /testsystem/i){\n exec('C:\\Program Files\\Notepad++\\notepad++.exe', '-multiInst', '-nosession', @ARGV);\n }\n}\n$MCEDIT=`which mcedit`;\nif($MCEDIT =~ /mcedit/){\n exec($MCEDIT, @ARGV);\n}\n$NANO=`which nano`;\nif($NANO =~ /nano/){\n exec($NANO, @ARGV);\n}\ndie \"You don't have a suitable editor!\\n\";\n</code></pre>\n\n<p>One might consider a plain shell script, but I used Perl as it is shipped with msysgit and your <a href=\"https://en.wikipedia.org/wiki/Unix-like\" rel=\"nofollow noreferrer\">Unix-like</a> systems will usually provide one as well.\nPutting the script in <code>/home/username/bin</code>, which should be added to <code>PATH</code> in <code>.bashrc</code> or <code>.profile</code>. Once added with <code>git config --global core.editor giteditor.pl</code> you have the right editor, wherever you are.</p>\n"
},
{
"answer_id": 7549705,
"author": "Edward J Beckett",
"author_id": 538921,
"author_profile": "https://Stackoverflow.com/users/538921",
"pm_score": 3,
"selected": false,
"text": "<p>Thanks to the Stack Overflow community ... and a little research I was able to get my favorite editor, <a href=\"http://www.editpadpro.com\" rel=\"nofollow noreferrer\"><strong>EditPad Pro</strong></a>, to work as the core editor with msysgit 1.7.5.GIT and TortoiseGit v1.7.3.0 over Windows XP SP3...</p>\n\n<p>Following the advice above, I added the path to a Bash script for the code editor...</p>\n\n<pre><code>git config --global core.editor c:/msysgit/cmd/epp.sh\n</code></pre>\n\n<p>However, after several failed attempts at the above mentioned solutions ... I was finally able to get this working. Per EditPad Pro's documentation, adding the '/newinstance' flag would allow the shell to wait for the editor input...</p>\n\n<p>The '<strong>/newinstance</strong>' flag was the key in my case...</p>\n\n<pre><code>#!/bin/sh\n\"C:/Program Files/JGsoft/EditPadPro6/EditPadPro.exe\" //newinstance \"$*\"\n</code></pre>\n"
},
{
"answer_id": 10968585,
"author": "icc97",
"author_id": 327074,
"author_profile": "https://Stackoverflow.com/users/327074",
"pm_score": -1,
"selected": false,
"text": "<p>I just use <a href=\"http://en.wikipedia.org/wiki/TortoiseGit\" rel=\"nofollow noreferrer\">TortoiseGit</a> straight out the box. It integrates beautifully with my <a href=\"http://en.wikipedia.org/wiki/PuTTY\" rel=\"nofollow noreferrer\">PuTTY</a> public keys. </p>\n\n<p>It has a perfect editor for commit messages.</p>\n"
},
{
"answer_id": 12899808,
"author": "kghastie",
"author_id": 1028062,
"author_profile": "https://Stackoverflow.com/users/1028062",
"pm_score": 0,
"selected": false,
"text": "<p>This is working for me using Cygwin and <a href=\"http://en.wikipedia.org/wiki/TextPad\" rel=\"nofollow noreferrer\">TextPad</a> 6 (EDIT: it is also working with TextPad 5 as long as you make the obvious change to the script), and presumably the model could be used for other editors as well:</p>\n\n<p>File <code>~/.gitconfig</code>:</p>\n\n<pre><code>[core]\n editor = ~/script/textpad.sh\n</code></pre>\n\n<p>File <code>~/script/textpad.sh</code>:</p>\n\n<pre><code>#!/bin/bash\n\nAPP_PATH=`cygpath \"c:/program files (x86)/textpad 6/textpad.exe\"`\nFILE_PATH=`cygpath -w $1`\n\n\"$APP_PATH\" -m \"$FILE_PATH\"\n</code></pre>\n\n<p>This one-liner works as well:</p>\n\n<p>File <code>~/script/textpad.sh</code> (option 2):</p>\n\n<pre><code>\"`cygpath \"c:/program files (x86)/textpad 6/textpad.exe\"`\" -m \"`cygpath -w $1`\"\n</code></pre>\n"
},
{
"answer_id": 17024500,
"author": "Bill",
"author_id": 368316,
"author_profile": "https://Stackoverflow.com/users/368316",
"pm_score": 3,
"selected": false,
"text": "<p>I use Git on multiple platforms, and I like to use the same Git settings on all of them. (In fact, I have all my configuration files under release control with Git, and put a Git repository clone on each machine.) The solution I came up with is this:</p>\n\n<p>I set my <strong>editor</strong> to <strong>giteditor</strong></p>\n\n<pre><code>git config --global core.editor giteditor\n</code></pre>\n\n<p>Then I create a symbolic link called <strong>giteditor</strong> which is in my <strong>PATH</strong>. (I have a personal <strong>bin</strong> directory, but anywhere in the <strong>PATH</strong> works.) That link points to my current editor of choice. On different machines and different platforms, I use different editors, so this means that I don't have to change my universal Git configuration (<strong>.gitconfig</strong>), just the link that <strong>giteditor</strong> points to.</p>\n\n<p>Symbolic links are handled by every operating system I know of, though they may use different commands. For Linux, you use <strong>ln -s</strong>. For Windows, you use the <strong>cmd</strong> built-in <strong>mklink</strong>. They have different syntaxes (which you should look up), but it all works the same way, really.</p>\n"
},
{
"answer_id": 21127799,
"author": "javimsevilla",
"author_id": 3196339,
"author_profile": "https://Stackoverflow.com/users/3196339",
"pm_score": 0,
"selected": false,
"text": "<p>This worked for me:</p>\n\n<ol>\n<li>Add the directory which contains the editor's executable to your <strong><em>PATH</em></strong> variable. (E.g. <em>\"C:\\Program Files\\Sublime Text 3\\\"</em>)</li>\n<li>Reboot your computer.</li>\n<li>Change the <em>core.editor</em> global Git variable to the name of the editor executable <strong>without the extension</strong> <em>'.exe'</em> (e.g. git config --global core.editor sublime_text)</li>\n</ol>\n\n<p>That's it!</p>\n\n<p><strong>NOTE:</strong> <a href=\"http://en.wikipedia.org/wiki/Sublime_Text\" rel=\"nofollow noreferrer\">Sublime Text</a> 3 is the editor I used for this example.</p>\n"
},
{
"answer_id": 28386190,
"author": "JaKXz",
"author_id": 1444541,
"author_profile": "https://Stackoverflow.com/users/1444541",
"pm_score": 1,
"selected": false,
"text": "<p>I'm using GitHub for Windows which is a nice visual option. But I also prefer the command line, so to make it work when I open a repository in a Git shell I just set the following:</p>\n\n<pre><code>git config --global core.editor vim\n</code></pre>\n\n<p>which works great.</p>\n"
},
{
"answer_id": 31757683,
"author": "rofrol",
"author_id": 588759,
"author_profile": "https://Stackoverflow.com/users/588759",
"pm_score": 1,
"selected": false,
"text": "<p>This works for PowerShell and <a href=\"https://cmder.net/\" rel=\"nofollow noreferrer\">cmder</a> 1.2 (when used with PowerShell). In file <code>~/.gitconfig</code>:</p>\n\n<pre><code>[core]\n editor = 'c:/program files/sublime text 3/subl.exe' -w\n</code></pre>\n\n<p><em><a href=\"https://stackoverflow.com/questions/8951275/how-can-i-make-sublime-text-the-default-editor-for-git/9408117#9408117\">How can I make Sublime Text the default editor for Git?</a></em></p>\n"
},
{
"answer_id": 33368301,
"author": "avg",
"author_id": 1295023,
"author_profile": "https://Stackoverflow.com/users/1295023",
"pm_score": 1,
"selected": false,
"text": "<p>I found a a beautifully simple solution posted <a href=\"https://danlimerick.wordpress.com/2014/01/07/git-for-windows-tip-opening-sublime-text-from-bash/\" rel=\"nofollow noreferrer\" title=\"here\">here</a> - although there may be a mistake in the path in which you have to copy over the \"subl\" file given by the author.</p>\n\n<p>I am running Windows 7 x64, and I had to put the \"subl\" file in my <code>/Git/cmd/</code> folder to make it work. </p>\n\n<p>It works like a charm, though.</p>\n"
},
{
"answer_id": 37169060,
"author": "Daniel",
"author_id": 3592441,
"author_profile": "https://Stackoverflow.com/users/3592441",
"pm_score": 3,
"selected": false,
"text": "<p>Based on <a href=\"https://stackoverflow.com/users/6309/vonc\">VonC's</a> <a href=\"https://stackoverflow.com/a/773973/6309\">suggestion</a>, this worked for me (was driving me crazy):</p>\n\n<pre><code>git config --global core.editor \"'C:/Program Files (x86)/Sublime Text 3/subl.exe' -wait\"\n</code></pre>\n\n<p>Omitting <code>-wait</code> can cause problems, especially if you are working with <a href=\"https://en.wikipedia.org/wiki/Gerrit_(software)\" rel=\"nofollow noreferrer\">Gerrit</a> and change ids that have to be manually copied to the bottom of your commit message.</p>\n"
},
{
"answer_id": 37558341,
"author": "Jonathan Ramos",
"author_id": 5934012,
"author_profile": "https://Stackoverflow.com/users/5934012",
"pm_score": 1,
"selected": false,
"text": "<h2>Atom and Windows 10</h2>\n<ol>\n<li><p>I right clicked the Atom icon at the desktop and clicked on properties.</p>\n</li>\n<li><p>Copied the "Start in" location path</p>\n</li>\n<li><p>Looked over there with Windows Explorer and found "atom.exe".</p>\n</li>\n<li><p>I typed this in Git Bash:</p>\n<pre><code>git config --global core.editor C:/Users/YOURNAMEUSER/AppData/Local/atom/app-1.7.4/atom.exe"\n</code></pre>\n</li>\n</ol>\n<p>Note: I changed all <code>\\</code> for <code>/</code> . I created a .bashrc at my home directory and used <code>/</code> to set my home directory and it worked, so I assumed <code>/</code> will be the way to go.</p>\n<p><a href=\"/questions/tagged/atom-editor\" class=\"post-tag\" title=\"show questions tagged 'atom-editor'\" rel=\"tag\">atom-editor</a> <a href=\"/questions/tagged/git\" class=\"post-tag\" title=\"show questions tagged 'git'\" rel=\"tag\">git</a> <a href=\"/questions/tagged/git-bash\" class=\"post-tag\" title=\"show questions tagged 'git-bash'\" rel=\"tag\">git-bash</a> <a href=\"/questions/tagged/windows-10\" class=\"post-tag\" title=\"show questions tagged 'windows-10'\" rel=\"tag\">windows-10</a></p>\n"
},
{
"answer_id": 39900408,
"author": "OmgKemuel",
"author_id": 4318447,
"author_profile": "https://Stackoverflow.com/users/4318447",
"pm_score": 4,
"selected": false,
"text": "<p>For <strong><a href=\"https://en.wikipedia.org/wiki/Atom_(text_editor)\" rel=\"noreferrer\">Atom</a></strong> you can do</p>\n\n<pre><code>git config --global core.editor \"atom --wait\"\n</code></pre>\n\n<p>and similar for <strong><a href=\"https://en.wikipedia.org/wiki/Visual_Studio_Code\" rel=\"noreferrer\">Visual Studio Code</a></strong></p>\n\n<pre><code>git config --global core.editor \"code --wait\"\n</code></pre>\n\n<p>which will open up an <strong>Atom</strong> or <strong>Visual Studio Code</strong> window for you to commit through, </p>\n\n<p>or for <strong><a href=\"http://en.wikipedia.org/wiki/Sublime_Text\" rel=\"noreferrer\">Sublime Text</a></strong>:</p>\n\n<pre><code>git config --global core.editor \"subl -n -w\"\n</code></pre>\n"
},
{
"answer_id": 41315379,
"author": "Zombo",
"author_id": 1002260,
"author_profile": "https://Stackoverflow.com/users/1002260",
"pm_score": 0,
"selected": false,
"text": "<p>Here is a solution with Cygwin:</p>\n\n<pre class=\"lang-sh prettyprint-override\"><code>#!/bin/dash -e\nif [ \"$1\" ]\nthen k=$(cygpath -w \"$1\")\nelif [ \"$#\" != 0 ]\nthen k=\nfi\nNotepad2 ${k+\"$k\"}\n</code></pre>\n\n<ol>\n<li><p>If no path, pass no path</p></li>\n<li><p>If path is empty, pass empty path</p></li>\n<li><p>If path is not empty, convert to Windows format.</p></li>\n</ol>\n\n<p>Then I set these variables:</p>\n\n<pre class=\"lang-c prettyprint-override\"><code>export EDITOR=notepad2.sh\nexport GIT_EDITOR='dash /usr/local/bin/notepad2.sh'\n</code></pre>\n\n<ol>\n<li><p>EDITOR allows script to work with Git</p></li>\n<li><p>GIT_EDITOR allows script to work with <a href=\"//hub.github.com\" rel=\"nofollow noreferrer\">Hub commands</a></p></li>\n</ol>\n\n<p><a href=\"//github.com/svnpenn/dotfiles/tree/2973070/editor\" rel=\"nofollow noreferrer\">Source</a></p>\n"
},
{
"answer_id": 41637069,
"author": "guwer",
"author_id": 5144040,
"author_profile": "https://Stackoverflow.com/users/5144040",
"pm_score": 3,
"selected": false,
"text": "<p>Edit .gitconfig file in c:\\Users\\YourUser folder and add:</p>\n\n<pre><code>[core]\neditor = 'C:\\\\Program files\\\\path\\\\to\\\\editor.exe'\n</code></pre>\n"
},
{
"answer_id": 53048541,
"author": "JL_SO",
"author_id": 4026629,
"author_profile": "https://Stackoverflow.com/users/4026629",
"pm_score": 3,
"selected": false,
"text": "<p>I needed to do <em>both</em> of the following to get Git to launch Notepad++ in Windows:</p>\n\n<ul>\n<li><p>Add the following to .gitconfig:</p>\n\n<pre><code>editor = 'C:/Program Files/Notepad++/notepad++.exe' -multiInst -notabbar -nosession -noPlugin\n</code></pre></li>\n<li><p>Modify the shortcut to launch the Git Bash shell to run as administrator, and then use that to launch the Git Bash shell. I was guessing that the context menu entry \"Git Bash here\" was not launching Notepad++ with the required permissions. </p></li>\n</ul>\n\n<p>After doing both of the above, it worked. </p>\n"
},
{
"answer_id": 61967726,
"author": "Gabriel Staples",
"author_id": 4561887,
"author_profile": "https://Stackoverflow.com/users/4561887",
"pm_score": 0,
"selected": false,
"text": "<blockquote>\n <p>Those of you using Git on Windows: What tool do you use to edit your commit messages, and what did you have to do to make it work?</p>\n</blockquote>\n\n<p>The tool that I find the most useful as both my <em>git editor <strong>and</strong> my general-purpose code editor</em>, in both Windows <em>and</em> Linux, is <a href=\"https://www.sublimetext.com/\" rel=\"nofollow noreferrer\">Sublime Text 3</a>. It works really well, but requires a little bit of setup to get it just right, so I've fully documented that fully here:</p>\n\n<ul>\n<li><a href=\"https://stackoverflow.com/questions/2596805/how-do-i-make-git-use-the-editor-of-my-choice-for-commits/48212377#48212377\">How do I make Git use the editor of my choice for commits? - Best settings for Sublime Text 3 as your Git editor (Windows & Linux instructions)</a></li>\n</ul>\n\n<p>Side note about my main editor: for big projects I use Eclipse as my primary editor, and Sublime Text 3 as my git editor and additional file editor when I need to make use of its advanced features such as multi-cursor mode, vertical/column selection mode, etc. For small to medium projects I use just Sublime Text 3 by itself. For setup instructions for Eclipse, see <a href=\"https://github.com/ElectricRCAircraftGuy/eRCaGuy_dotfiles/blob/master/eclipse/Eclipse%20setup%20instructions%20on%20a%20new%20Linux%20(or%20other%20OS)%20computer.pdf\" rel=\"nofollow noreferrer\">my PDF document here</a>.</p>\n"
},
{
"answer_id": 65355708,
"author": "Ruan Nawe",
"author_id": 6069435,
"author_profile": "https://Stackoverflow.com/users/6069435",
"pm_score": 1,
"selected": false,
"text": "<p>to add sublime <code>git config --global core.editor "'C:\\Program Files\\Sublime Text 3\\sublime_text.exe'"</code></p>\n"
},
{
"answer_id": 68527047,
"author": "cxxl",
"author_id": 1045800,
"author_profile": "https://Stackoverflow.com/users/1045800",
"pm_score": 1,
"selected": false,
"text": "<p>I solved a similar issue using <code>GIT_EDITOR</code> variable and <code>notepad2</code> as editor.</p>\n<p>Solution 1: Set the environment variable <code>GIT_EDITOR</code> to <code>C:/tools/notepad2.exe</code>. This works nicely, but git complains if the commit message has non-ASCII characters.</p>\n<p>Solution 2: Set <code>GIT_EDITOR</code> to <code>C:/tools/notepad2.exe //utf8</code>. Notice the double slash in front of the program switch. BTW: <code>-utf8</code> would have worked as well.</p>\n"
},
{
"answer_id": 71192747,
"author": "Tal Jacob - Sir Jacques",
"author_id": 14427765,
"author_profile": "https://Stackoverflow.com/users/14427765",
"pm_score": 0,
"selected": false,
"text": "<p>Say you want to configure <em>VsCode</em> to be your editor.\nDo the following:</p>\n<h2>Add the following lines to your <code>.gitconfig</code> file:</h2>\n<blockquote>\n<p>The default location of <code>.gitconfig</code> file is <code>C:\\Users\\USER_NAME\\.gitconfig</code></p>\n</blockquote>\n<pre><code>[core]\n editor = code -w -n\n[diff]\n tool = vscode\n[difftool "vscode"]\n cmd = code -w -n --diff $LOCAL $REMOTE\n[merge]\n tool = vscode\n[mergetool "vscode"]\n cmd = code -w -n $MERGED\n</code></pre>\n<blockquote>\n<p>NOTE:</p>\n<ul>\n<li><code>-w</code> is mandatory, and tells <code>git</code> to wait for <em>vscode</em> to load.</li>\n<li><code>-n</code> is optional, and tells <code>git</code> to open <em>vscode</em> in a new-window.</li>\n</ul>\n</blockquote>\n<h3>In case you want to configure a custom path to the editor in Windows:</h3>\n<p>You need to replace the word <code>code</code> with <em>Path to '.exe' of VsCode</em>.</p>\n<p>For example:</p>\n<pre><code>[core]\n editor = "'C:/Users/Tal/AppData/Local/Programs/Microsoft VS Code/Code.exe'" -w -n\n[diff]\n tool = vscode\n[difftool "vscode"]\n cmd = "'C:/Users/Tal/AppData/Local/Programs/Microsoft VS Code/Code.exe'" -w -n --diff $LOCAL $REMOTE\n[merge]\n tool = vscode\n[mergetool "vscode"]\n cmd = "'C:/Users/Tal/AppData/Local/Programs/Microsoft VS Code/Code.exe'" -w -n $MERGED\n</code></pre>\n<blockquote>\n<p>Note:</p>\n<ul>\n<li>You need to surround the path with <em>single-quotes</em> <code>''</code>.</li>\n<li>The slashes in the path should be <em>forward-slashes</em> <code>/</code>.</li>\n</ul>\n</blockquote>\n<p>Or another example:</p>\n<pre><code>[core]\n editor = \\"C:\\\\Users\\\\Tal\\\\AppData\\\\Local\\\\Programs\\\\Microsoft VS Code\\\\Code.exe\\" -w -n\n\n[diff]\n tool = vscode\n[difftool "vscode"]\n cmd = \\"C:\\\\Users\\\\Tal\\\\AppData\\\\Local\\\\Programs\\\\Microsoft VS Code\\\\Code.exe\\" -w -n --diff $LOCAL $REMOTE\n\n[merge]\n tool = vscode\n[mergetool "vscode"]\n cmd = \\"C:\\\\Users\\\\Tal\\\\AppData\\\\Local\\\\Programs\\\\Microsoft VS Code\\\\Code.exe\\" -w -n $MERGED\n</code></pre>\n<hr />\n<h3>UPDATE:</h3>\n<p><strong>VsCode supports now "3-way merges"!</strong>\nThe update was done in versions <a href=\"https://code.visualstudio.com/updates/v1_69#_3-way-merge-editor\" rel=\"nofollow noreferrer\">1.69.0</a> and <a href=\"https://code.visualstudio.com/updates/v1_70#_command-line-option-merge\" rel=\"nofollow noreferrer\">1.70.0</a>.\nSo now you can enable the VsCode "mergetool" to view 3-way merges.</p>\n<p>To do so, you need to update the line:</p>\n<pre><code>[mergetool "vscode"]\n cmd = code -w -n $MERGED\n</code></pre>\n<p>with the new line:</p>\n<pre><code>[mergetool "vscode"]\n cmd = code -w -n --merge $REMOTE $LOCAL $BASE $MERGED\n</code></pre>\n"
}
] | 2008/08/14 | [
"https://Stackoverflow.com/questions/10564",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/437/"
] | I'm trying out **Git on Windows**. I got to the point of trying "git commit" and I got this error:
>
> Terminal is dumb but no VISUAL nor
> EDITOR defined. Please supply the
> message using either -m or -F option.
>
>
>
So I figured out I need to have an environment variable called EDITOR. No problem. I set it to point to Notepad. That worked, almost. The default commit message opens in Notepad. But Notepad doesn't support bare line feeds. I went out and got [Notepad++](http://notepad-plus.sourceforge.net/uk/site.htm), but I can't figure out how to get Notepad++ set up as the `%EDITOR%` in such a way that it works with Git as expected.
I'm not married to Notepad++. At this point I don't mind what editor I use. I just want to be able to **type commit messages in an editor** rather than the command line (with `-m`).
Those of you using Git on Windows: What tool do you use to edit your commit messages, and what did you have to do to make it work? | Update September 2015 (6 years later)
The [last release of git-for-Windows (2.5.3)](https://github.com/git-for-windows/git/releases/tag/v2.5.3.windows.1) now includes:
>
> By configuring **`git config core.editor notepad`**, users [can now use `notepad.exe` as their default editor](https://github.com/git-for-windows/git/issues/381).
>
> Configuring `git config format.commitMessageColumns 72` will be picked up by the notepad wrapper and line-wrap the commit message after the user edits it.
>
>
>
See [commit 69b301b](https://github.com/git-for-windows/build-extra/commit/69b301bbd7c18226c63d83638991cb2b7f84fb64) by [Johannes Schindelin (`dscho`)](https://github.com/dscho).
And Git 2.16 (Q1 2018) will show a message to tell the user that it is waiting for the user to finish editing when spawning an editor, in case the editor
opens to a hidden window or somewhere obscure and the user gets
lost.
See [commit abfb04d](https://github.com/git/git/commit/abfb04d0c74cde804c734015ff5868a88c84fb6f) (07 Dec 2017), and [commit a64f213](https://github.com/git/git/commit/a64f213d3fa13fa01e582b6734fe7883ed975dc9) (29 Nov 2017) by [Lars Schneider (`larsxschneider`)](https://github.com/larsxschneider).
Helped-by: [Junio C Hamano (`gitster`)](https://github.com/gitster).
(Merged by [Junio C Hamano -- `gitster` --](https://github.com/gitster) in [commit 0c69a13](https://github.com/git/git/commit/0c69a132cb1adf0ce9f31e6631f89321e437cb76), 19 Dec 2017)
>
> `launch_editor()`: indicate that Git waits for user input
> ---------------------------------------------------------
>
>
> When a graphical `GIT_EDITOR` is spawned by a Git command that opens
> and waits for user input (e.g. "`git rebase -i`"), then the editor window
> might be obscured by other windows.
>
> The user might be left staring at
> the original Git terminal window without even realizing that s/he needs
> to interact with another window before Git can proceed. To this user Git
> appears hanging.
>
>
> Print a message that Git is waiting for editor input in the original
> terminal and get rid of it when the editor returns, if the terminal
> supports erasing the last line
>
>
>
---
Original answer
I just tested it with git version 1.6.2.msysgit.0.186.gf7512 and Notepad++5.3.1
I prefer to *not* have to set an EDITOR variable, so I tried:
```bash
git config --global core.editor "\"c:\Program Files\Notepad++\notepad++.exe\""
# or
git config --global core.editor "\"c:\Program Files\Notepad++\notepad++.exe\" %*"
```
That always gives:
```
C:\prog\git>git config --global --edit
"c:\Program Files\Notepad++\notepad++.exe" %*: c:\Program Files\Notepad++\notepad++.exe: command not found
error: There was a problem with the editor '"c:\Program Files\Notepad++\notepad++.exe" %*'.
```
If I define a npp.bat including:
```
"c:\Program Files\Notepad++\notepad++.exe" %*
```
and I type:
```
C:\prog\git>git config --global core.editor C:\prog\git\npp.bat
```
It just works from the DOS session, **but not from the git shell**.
(not that with the core.editor configuration mechanism, a script with "`start /WAIT...`" in it would not work, but only open a new DOS window)
---
[Bennett's answer](https://stackoverflow.com/questions/10564/how-can-i-set-up-an-editor-to-work-with-git-on-windows/1431003#1431003) mentions the possibility to avoid adding a script, but to reference directly the program itself **between simple quotes**. Note the direction of the slashes! Use `/` NOT `\` to separate folders in the path name!
```bash
git config --global core.editor \
"'C:/Program Files/Notepad++/notepad++.exe' -multiInst -notabbar -nosession -noPlugin"
```
Or if you are in a 64 bit system:
```bash
git config --global core.editor \
"'C:/Program Files (x86)/Notepad++/notepad++.exe' -multiInst -notabbar -nosession -noPlugin"
```
But I prefer using a script (see below): that way I can play with different paths or different options without having to register again a `git config`.
---
The actual solution (with a script) was to realize that:
**what you refer to in the config file is actually a shell (`/bin/sh`) script**, not a DOS script.
So what does work is:
```
C:\prog\git>git config --global core.editor C:/prog/git/npp.bat
```
with `C:/prog/git/npp.bat`:
```bash
#!/bin/sh
"c:/Program Files/Notepad++/notepad++.exe" -multiInst "$*"
```
or
```bash
#!/bin/sh
"c:/Program Files/Notepad++/notepad++.exe" -multiInst -notabbar -nosession -noPlugin "$*"
```
With that setting, I can do '`git config --global --edit`' from DOS or Git Shell, or I can do '`git rebase -i ...`' from DOS or Git Shell.
Bot commands will trigger a new instance of notepad++ (hence the `-multiInst`' option), and wait for that instance to be closed before going on.
Note that I use only '/', not `\`'. And I [installed msysgit using option 2.](https://stackoverflow.com/questions/623518/msysgit-on-windows-what-should-i-be-aware-of-if-any) (Add the `git\bin` directory to the `PATH` environment variable, but without overriding some built-in windows tools)
The fact that the notepad++ wrapper is called .bat is not important.
It would be better to name it 'npp.sh' and to put it in the `[git]\cmd` directory though (or in any directory referenced by your PATH environment variable).
---
See also:
* [How do I view ‘git diff’ output with visual diff program?](https://stackoverflow.com/questions/255202/how-do-i-view-git-diff-output-with-visual-diff-program/255212#255212) for the general theory
* [How do I setup DiffMerge with msysgit / gitk?](https://stackoverflow.com/questions/780425/how-do-i-setup-diffmerge-with-msysgit-gitk/783667#783667) for another example of external tool (DiffMerge, and WinMerge)
---
[lightfire228](https://stackoverflow.com/users/2716305/lightfire228) adds [in the comments](https://stackoverflow.com/questions/10564/how-can-i-set-up-an-editor-to-work-with-git-on-windows/773973#comment74027740_773973):
>
> For anyone having an issue where N++ just opens a blank file, and git doesn't take your commit message, see "[Aborting commit due to empty message](https://stackoverflow.com/q/30085970/6309)": change your `.bat` or `.sh` file to say:
>
>
>
```
"<path-to-n++" .git/COMMIT_EDITMSG -<arguments>.
```
>
> That will tell notepad++ to open the temp commit file, rather than a blank new one.
>
>
> |
10,616 | <p>I'm an <a href="http://en.wikipedia.org/wiki/ASP.NET" rel="noreferrer">ASP.NET</a> developer who has used <code>Microsoft SQL Server</code> for all my database needs (both at work and for personal projects). </p>
<p>I am considering trying out the <a href="http://en.wikipedia.org/wiki/LAMP_%28software_bundle%29" rel="noreferrer">LAMP</a> stack for some of my personal projects. </p>
<p>What are some of the main differences between <code>MySQL</code> and <code>SQL Server</code>? Is using <a href="http://en.wikipedia.org/wiki/Stored_procedure" rel="noreferrer">stored procedures</a> a common practice in <code>MySQL</code>? </p>
<p>Any advice or resources you'd recommend to help me with the switch? </p>
<p>To those who have experience with both, are there any missing features from <code>MySQL</code>?</p>
| [
{
"answer_id": 10623,
"author": "Jeff Atwood",
"author_id": 1,
"author_profile": "https://Stackoverflow.com/users/1",
"pm_score": 8,
"selected": true,
"text": "<p>One thing you have to watch out for is the fairly severe differences in the way SQL Server and MySQL implement the SQL syntax.</p>\n\n<p>Here's a nice <a href=\"http://troels.arvin.dk/db/rdbms/\" rel=\"noreferrer\">Comparison of Different SQL Implementations</a>.</p>\n\n<p>For example, take a look at the top-n section. In MySQL:</p>\n\n<pre><code>SELECT age\nFROM person\nORDER BY age ASC\nLIMIT 1 OFFSET 2\n</code></pre>\n\n<p>In SQL Server (T-SQL):</p>\n\n<pre><code>SELECT TOP 3 WITH TIES *\nFROM person\nORDER BY age ASC\n</code></pre>\n"
},
{
"answer_id": 10628,
"author": "Jon Limjap",
"author_id": 372,
"author_profile": "https://Stackoverflow.com/users/372",
"pm_score": 3,
"selected": false,
"text": "<p>I think one of the major things to watch out for is that versions prior to MySQL 5.0 did not have views, triggers, and stored procedures.</p>\n\n<p>More of this is explained in the <a href=\"http://dev.mysql.com/downloads/mysql/5.0.html#downloads\" rel=\"nofollow noreferrer\">MySQL 5.0 Download page</a>.</p>\n"
},
{
"answer_id": 10900,
"author": "dlinsin",
"author_id": 198,
"author_profile": "https://Stackoverflow.com/users/198",
"pm_score": 2,
"selected": false,
"text": "<blockquote>\n <p>Anyone have any good experience with a\n \"port\" of a database from SQL Server\n to MySQL?</p>\n</blockquote>\n\n<p>This should be fairly painful! I switched versions of MySQL from 4.x to 5.x and various statements wouldn't work anymore as they used to. The query analyzer was \"improved\" so statements which previously were tuned for performance would not work anymore as expected. </p>\n\n<p>The lesson learned from working with a 500GB MySQL database: It's a subtle topic and anything else but trivial!</p>\n"
},
{
"answer_id": 18320,
"author": "Jon Galloway",
"author_id": 5,
"author_profile": "https://Stackoverflow.com/users/5",
"pm_score": 4,
"selected": false,
"text": "<p>MySQL is more likely to have database corruption issues, and it doesn't fix them automatically when they happen. I've worked with MSSQL since version 6.5 and don't remember a database corruption issue taking the database offline. The few times I've worked with MySQL in a production environment, a database corruption issue took the entire database offline until we ran the magic \"please fix my corrupted index\" thing from the commandline.</p>\n\n<p>MSSQL's transaction and journaling system, in my experience, handles just about anything - including a power cycle or hardware failure - without database corruption, and if something gets messed up it fixes it automatically.</p>\n\n<p>This has been my experience, and I'd be happy to hear that this has been fixed or we were doing something wrong.</p>\n\n<p><a href=\"http://dev.mysql.com/doc/refman/6.0/en/corrupted-myisam-tables.html\" rel=\"noreferrer\">http://dev.mysql.com/doc/refman/6.0/en/corrupted-myisam-tables.html</a></p>\n\n<p><a href=\"http://www.google.com/search?q=site%3Abugs.mysql.com+index+corruption\" rel=\"noreferrer\">http://www.google.com/search?q=site%3Abugs.mysql.com+index+corruption</a></p>\n"
},
{
"answer_id": 51244,
"author": "Abdu",
"author_id": 5232,
"author_profile": "https://Stackoverflow.com/users/5232",
"pm_score": 3,
"selected": false,
"text": "<p>Frankly, I can't find a single reason to use MySQL rather than MSSQL. The issue before used to be cost but SQL Server 2005 Express is free and there are lots of web hosting companies which offer full hosting with sql server for less than $5.00 a month.</p>\n\n<p>MSSQL is easier to use and has many features which do not exist in MySQL. </p>\n"
},
{
"answer_id": 51254,
"author": "Cebjyre",
"author_id": 1612,
"author_profile": "https://Stackoverflow.com/users/1612",
"pm_score": 2,
"selected": false,
"text": "<p>@abdu</p>\n\n<p>The main thing I've found that MySQL has over MSSQL is timezone support - the ability to nicely change between timezones, respecting daylight savings is fantastic.</p>\n\n<p>Compare this:</p>\n\n<pre><code>mysql> SELECT CONVERT_TZ('2008-04-01 12:00:00', 'UTC', 'America/Los_Angeles');\n+-----------------------------------------------------------------+\n| CONVERT_TZ('2008-04-01 12:00:00', 'UTC', 'America/Los_Angeles') |\n+-----------------------------------------------------------------+\n| 2008-04-01 05:00:00 |\n+-----------------------------------------------------------------+\n</code></pre>\n\n<p>to the contortions involved at <a href=\"https://stackoverflow.com/questions/24797/effectively-converting-dates-between-utc-and-local-ie-pst-time-in-sql-2005#25073\">this answer</a>.</p>\n\n<p>As for the 'easier to use' comment, I would say that the point is that they are different, and if you know one, there will be an overhead in learning the other.</p>\n"
},
{
"answer_id": 53150,
"author": "Abdu",
"author_id": 5232,
"author_profile": "https://Stackoverflow.com/users/5232",
"pm_score": 2,
"selected": false,
"text": "<p>@Cebjyre. The IDE whether Enterprise Manager or Management Studio is better than anything I have seen so far for MySQL. I say 'easier to use' because I can do many things in MSSQL where MySQL has no counterparts. In MySQL I have no idea how to tune the queries by simply looking at the query plan or looking at the statistics. The index tuning wizard in MSSQL takes most of the guess work on what indexes are missing or misplaced. </p>\n\n<p>One shortcoming of MySQL is there's no max size for a database. The database would just increase in size till it fills up the disk. Imagine if this disk is sharing databases with other users and suddenly all of their queries are failing because their databases can't grow. I have reported this issue to MySQL long time ago. I don't think it's fixed yet.</p>\n"
},
{
"answer_id": 312893,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 1,
"selected": false,
"text": "<p>Spending some time working with MySQL from the MSSQL to MySQL syntax POV I kept finding myself limited in what I could do.</p>\n\n<p>There are bizzare limits on updating a table while refrencing the same table during an update.</p>\n\n<p>Additionally UPDATE FROM does not work and last time I checked they don't support the Oracle MERGE INTO syntax either. This was a show stopper for me and I stopped thinking I would get anywhere with MySQL after that.</p>\n"
},
{
"answer_id": 312962,
"author": "dkretz",
"author_id": 31641,
"author_profile": "https://Stackoverflow.com/users/31641",
"pm_score": 3,
"selected": false,
"text": "<p>Everything in MySQL seems to be done closer to the metal than in MSSQL, And the documentation treats it that way. Especially for optimization, you'll need to understand how indexes, system configuration, and the optimizer interact under various circumstances.</p>\n\n<p>The \"optimizer\" is more a parser. In MSSQL your query plan is often a surprise (usually good, sometimes not). In MySQL, it pretty much does what you asked it to do, the way you expected it to. Which means you yourself need to have a deep understanding of the various ways it might be done.</p>\n\n<p>Not built around a good TRANSACTION model (default MyISAM engine).</p>\n\n<p>File-system setup is your problem.</p>\n\n<p>All the database configuration is your problem - especially various cache sizes.</p>\n\n<p>Sometimes it seems best to think of it as an ad-hoc, glorified isam. Codd and Date don't carry much weight here. They would say it with no embarrassment.</p>\n"
},
{
"answer_id": 2401837,
"author": "prince",
"author_id": 288831,
"author_profile": "https://Stackoverflow.com/users/288831",
"pm_score": 3,
"selected": false,
"text": "<p>Both are DBMS's Product Sql server is an commercial application while MySql is an opensouces application.Both the product include similar feature,however sql server should be used for an enterprise solution ,while mysql might suit a smaller implementation.if you need feature like recovery,replication,granalar security and significant,you need sql server</p>\n\n<p>MySql takes up less spaces on disk, and uses less memory and cpu than does sql server</p>\n"
},
{
"answer_id": 3615943,
"author": "Remy",
"author_id": 375192,
"author_profile": "https://Stackoverflow.com/users/375192",
"pm_score": 6,
"selected": false,
"text": "<p>Lots of comments here sound more like religious arguments than real life statements. \nI've worked for years with both MySQL and MSSQL and both are good products. \nI would choose MySQL mainly based on the environment that you are working on. Most open source projects use MySQL, so if you go into that direction MySQL is your choice. If you develop something with .Net I would choose MSSQL, not because it's much better, but just cause that is what most people use. \nI'm actually currently on a Project that uses ASP.NET with MySQL and C#. It works perfectly fine.</p>\n"
},
{
"answer_id": 12865681,
"author": "ely",
"author_id": 567620,
"author_profile": "https://Stackoverflow.com/users/567620",
"pm_score": 5,
"selected": false,
"text": "<p>I can't believe that no one mentioned that MySQL doesn't support Common Table Expressions (CTE) / \"with\" statements. It's a pretty annoying difference.</p>\n"
}
] | 2008/08/14 | [
"https://Stackoverflow.com/questions/10616",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/285/"
] | I'm an [ASP.NET](http://en.wikipedia.org/wiki/ASP.NET) developer who has used `Microsoft SQL Server` for all my database needs (both at work and for personal projects).
I am considering trying out the [LAMP](http://en.wikipedia.org/wiki/LAMP_%28software_bundle%29) stack for some of my personal projects.
What are some of the main differences between `MySQL` and `SQL Server`? Is using [stored procedures](http://en.wikipedia.org/wiki/Stored_procedure) a common practice in `MySQL`?
Any advice or resources you'd recommend to help me with the switch?
To those who have experience with both, are there any missing features from `MySQL`? | One thing you have to watch out for is the fairly severe differences in the way SQL Server and MySQL implement the SQL syntax.
Here's a nice [Comparison of Different SQL Implementations](http://troels.arvin.dk/db/rdbms/).
For example, take a look at the top-n section. In MySQL:
```
SELECT age
FROM person
ORDER BY age ASC
LIMIT 1 OFFSET 2
```
In SQL Server (T-SQL):
```
SELECT TOP 3 WITH TIES *
FROM person
ORDER BY age ASC
``` |
10,635 | <p>I wrote a simple batch file as a PowerShell script, and I am getting errors when they run.</p>
<p>It's in a scripts directory in my path. This is the error I get:</p>
<blockquote>
<p>Cannot be loaded because the execution of scripts is disabled on this system.
Please see "get-help about-signing".</p>
</blockquote>
<p>I looked in the help, but it's less than helpful.</p>
| [
{
"answer_id": 10638,
"author": "Matt Hamilton",
"author_id": 615,
"author_profile": "https://Stackoverflow.com/users/615",
"pm_score": 8,
"selected": true,
"text": "<p>It could be PowerShell's default security level, which (IIRC) will only run signed scripts.</p>\n\n<p>Try typing this:</p>\n\n<pre class=\"lang-none prettyprint-override\"><code>set-executionpolicy remotesigned\n</code></pre>\n\n<p>That will tell PowerShell to allow local (that is, on a local drive) unsigned scripts to run.</p>\n\n<p>Then try executing your script again.</p>\n"
},
{
"answer_id": 10640,
"author": "Leon Bambrick",
"author_id": 49,
"author_profile": "https://Stackoverflow.com/users/49",
"pm_score": 3,
"selected": false,
"text": "<p>Also it's worth knowing that you may need to include <code>.\\</code> in front of the script name. For example: </p>\n\n<pre><code>.\\scriptname.ps1\n</code></pre>\n"
},
{
"answer_id": 11549657,
"author": "ExchangeAdmin",
"author_id": 1536046,
"author_profile": "https://Stackoverflow.com/users/1536046",
"pm_score": 1,
"selected": false,
"text": "<p>The command <code>set-executionpolicy unrestricted</code> will allow any script you create to run as the logged in user. Just be sure to set the executionpolicy setting back to signed using the <code>set-executionpolicy signed</code> command prior to logging out. </p>\n"
},
{
"answer_id": 16141428,
"author": "Naveen",
"author_id": 2306339,
"author_profile": "https://Stackoverflow.com/users/2306339",
"pm_score": 5,
"selected": false,
"text": "<p>Use:</p>\n\n<pre><code>Set-ExecutionPolicy -ExecutionPolicy Bypass -Scope Process\n</code></pre>\n\n<p>Always use the above command to enable to executing PowerShell in the current session.</p>\n"
},
{
"answer_id": 19974975,
"author": "Nadeem_MK",
"author_id": 2416510,
"author_profile": "https://Stackoverflow.com/users/2416510",
"pm_score": 6,
"selected": false,
"text": "<p>You need to run <code>Set-ExecutionPolicy</code>:</p>\n\n<pre class=\"lang-none prettyprint-override\"><code>Set-ExecutionPolicy Restricted <-- Will not allow any powershell scripts to run. Only individual commands may be run.\n\nSet-ExecutionPolicy AllSigned <-- Will allow signed powershell scripts to run.\n\nSet-ExecutionPolicy RemoteSigned <-- Allows unsigned local script and signed remote powershell scripts to run.\n\nSet-ExecutionPolicy Unrestricted <-- Will allow unsigned powershell scripts to run. Warns before running downloaded scripts.\n\nSet-ExecutionPolicy Bypass <-- Nothing is blocked and there are no warnings or prompts.\n</code></pre>\n"
},
{
"answer_id": 21922658,
"author": "user3335140",
"author_id": 3335140,
"author_profile": "https://Stackoverflow.com/users/3335140",
"pm_score": 3,
"selected": false,
"text": "<pre><code>Set-ExecutionPolicy -ExecutionPolicy Bypass -Scope Process\n</code></pre>\n\n<p>The above command worked for me even when the following error happens:</p>\n\n<pre><code>Access to the registry key 'HKEY_LOCAL_MACHINE\\SOFTWARE\\Microsoft\\PowerShell\\1\\ShellIds\\Microsoft.PowerShell' is denied.\n</code></pre>\n"
},
{
"answer_id": 34007144,
"author": "Be Kind To New Users",
"author_id": 192044,
"author_profile": "https://Stackoverflow.com/users/192044",
"pm_score": 4,
"selected": false,
"text": "<p>I was able to bypass this error by invoking PowerShell like this:</p>\n\n<pre><code>powershell -executionpolicy bypass -File .\\MYSCRIPT.ps1\n</code></pre>\n\n<p>That is, I added the <code>-executionpolicy bypass</code> to the way I invoked the script.</p>\n\n<p>This worked on Windows 7 Service Pack 1. I am new to PowerShell, so there could be caveats to doing that that I am not aware of.</p>\n\n<p>[Edit 2017-06-26] I have continued to use this technique on other systems including Windows 10 and Windows 2012 R2 without issue.</p>\n\n<p>Here is what I am using now. This keeps me from accidentally running the script by clicking on it. When I run it in the scheduler I add one argument: \"scheduler\" and that bypasses the prompt.</p>\n\n<p>This also pauses the window at the end so I can see the output of PowerShell.</p>\n\n<pre><code>if NOT \"%1\" == \"scheduler\" (\n @echo looks like you started the script by clicking on it.\n @echo press space to continue or control C to exit.\n pause\n)\n\nC:\ncd \\Scripts\n\npowershell -executionpolicy bypass -File .\\rundps.ps1\n\nset psexitcode=%errorlevel%\n\nif NOT \"%1\" == \"scheduler\" (\n @echo Powershell finished. Press space to exit.\n pause\n)\n\nexit /b %psexitcode%\n</code></pre>\n"
},
{
"answer_id": 58025263,
"author": "user2781940",
"author_id": 2781940,
"author_profile": "https://Stackoverflow.com/users/2781940",
"pm_score": 0,
"selected": false,
"text": "<p>On Windows 10: \nClick change security property of myfile.ps1 and change \"allow access\" by right click / properties on myfile.ps1</p>\n"
},
{
"answer_id": 64084268,
"author": "Wasif",
"author_id": 12269857,
"author_profile": "https://Stackoverflow.com/users/12269857",
"pm_score": 1,
"selected": false,
"text": "<p>We can bypass execution policy in a nice way (inside command prompt):</p>\n<pre><code>type file.ps1 | powershell -command -\n</code></pre>\n<p>Or inside powershell:</p>\n<pre><code>gc file.ps1|powershell -c -\n</code></pre>\n"
},
{
"answer_id": 67022880,
"author": "Christian Brüggemann",
"author_id": 1502352,
"author_profile": "https://Stackoverflow.com/users/1502352",
"pm_score": 0,
"selected": false,
"text": "<p>It would be ideal to bypass execution policies e.g. through</p>\n<pre><code>powershell -executionpolicy bypass -File .\\MYSCRIPT.ps1\n</code></pre>\n<p>Unfortunately this can still be prevented by group policies. As a workaround, you can encode your script as Base64 by running this in PowerShell:</p>\n<pre><code>[Convert]::ToBase64String([Text.Encoding]::Unicode.GetBytes((Get-Content .\\MYSCRIPT.ps1)))\n</code></pre>\n<p>Then execute the result like this:</p>\n<pre><code>powershell.exe -EncodedCommand "put-your-base64-string-here"\n</code></pre>\n<p>Caveat: This won't work with scripts that require parameters.</p>\n"
}
] | 2008/08/14 | [
"https://Stackoverflow.com/questions/10635",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1220/"
] | I wrote a simple batch file as a PowerShell script, and I am getting errors when they run.
It's in a scripts directory in my path. This is the error I get:
>
> Cannot be loaded because the execution of scripts is disabled on this system.
> Please see "get-help about-signing".
>
>
>
I looked in the help, but it's less than helpful. | It could be PowerShell's default security level, which (IIRC) will only run signed scripts.
Try typing this:
```none
set-executionpolicy remotesigned
```
That will tell PowerShell to allow local (that is, on a local drive) unsigned scripts to run.
Then try executing your script again. |
10,668 | <p>I've been trying to understand how to read the memory of other processes on Mac OS X, but I'm not having much luck. I've seen many examples online using <code>ptrace</code> with <code>PEEKDATA</code> and such, however it doesn't have that option on BSD <sup>[<a href="http://developer.apple.com/documentation/Darwin/Reference/ManPages/man2/ptrace.2.html" rel="noreferrer"><code>man ptrace</code></a>]</sup>.</p>
<pre><code>int pid = fork();
if (pid > 0) {
// mess around with child-process's memory
}
</code></pre>
<p>How is it possible to read from and write to the memory of another process on Mac OS X?</p>
| [
{
"answer_id": 10676,
"author": "Derek Park",
"author_id": 872,
"author_profile": "https://Stackoverflow.com/users/872",
"pm_score": 4,
"selected": false,
"text": "<p>Matasano Chargen had a good post a while back on porting some debugging code to OS X, which included learning how to read and write memory in another process (among other things).</p>\n\n<p><a href=\"http://replay.web.archive.org/20090627062246/http://www.matasano.com/log/1100/what-ive-been-doing-on-my-summer-vacation-or-it-has-to-work-otherwise-gdb-wouldnt/\" rel=\"nofollow noreferrer\">It has to work, otherwise GDB wouldn't</a>:</p>\n\n<blockquote>\n <p>It turns out Apple, in their infinite wisdom, had gutted <code>ptrace()</code>. The OS X man page lists the following request codes:</p>\n \n <ul>\n <li><code>PT_ATTACH</code> — to pick a process to debug</li>\n <li><code>PT_DENY_ATTACH</code> — so processes can stop themselves from being debugged<br>\n [...]</li>\n </ul>\n \n <p>No mention of reading or writing memory or registers. Which would have been discouraging if the man page had not also mentioned <code>PT_GETREGS</code>, <code>PT_SETREGS</code>, <code>PT_GETFPREGS</code>, and <code>PT_SETFPREGS</code> in the error codes section. So, I checked <code>ptrace.h</code>. There I found:</p>\n \n <ul>\n <li><code>PT_READ_I</code> — to read instruction words</li>\n <li><code>PT_READ_D</code> — to read data words</li>\n <li><code>PT_READ_U</code> — to read U area data if you’re old enough to remember what the U area is<br>\n [...]</li>\n </ul>\n \n <p>There’s one problem solved. I can read and write memory for breakpoints. But I still can’t get access to registers, and I need to be able to mess with EIP.</p>\n</blockquote>\n"
},
{
"answer_id": 10829,
"author": "Chris Hanson",
"author_id": 714,
"author_profile": "https://Stackoverflow.com/users/714",
"pm_score": 1,
"selected": false,
"text": "<p>Manipulating a process's memory behind its back is a Bad Thing and is fraught with peril. That's why Mac OS X (like any Unix system) has protected memory, and keeps processes isolated from one another.</p>\n\n<p>Of course it can be done: There are facilities for shared memory between processes that explicitly cooperate. There are also ways to manipulate other processes' address spaces as long as the process doing so has explicit right to do so (as granted by the security framework). But that's there for people who are writing debugging tools to use. It's not something that should be a normal — or even rare — occurrence for the vast majority of development on Mac OS X.</p>\n"
},
{
"answer_id": 63033,
"author": "Trance Diviner",
"author_id": 7365,
"author_profile": "https://Stackoverflow.com/users/7365",
"pm_score": 4,
"selected": false,
"text": "<p>Use <code>task_for_pid()</code> or other methods to obtain the target process’s task port. Thereafter, you can directly manipulate the process’s address space using <code>vm_read()</code>, <code>vm_write()</code>, and others.</p>\n"
},
{
"answer_id": 64276,
"author": "Scott Marcy",
"author_id": 8168,
"author_profile": "https://Stackoverflow.com/users/8168",
"pm_score": 3,
"selected": false,
"text": "<p>It you're looking to be able to share chunks of memory between processes, you should check out shm_open(2) and mmap(2). It's pretty easy to allocate a chunk of memory in one process and pass the path (for shm_open) to another and both can then go crazy together. This is a lot safer than poking around in another process's address space as Chris Hanson mentions. Of course, if you don't have control over both processes, this won't do you much good.</p>\n\n<p>(Be aware that the max path length for shm_open appears to be 26 bytes, although this doesn't seem to be documented anywhere.)</p>\n\n<pre><code>// Create shared memory block\nvoid* sharedMemory = NULL;\nsize_t shmemSize = 123456;\nconst char* shmName = \"mySharedMemPath\"; \nint shFD = shm_open(shmName, (O_CREAT | O_EXCL | O_RDWR), 0600);\nif (shFD >= 0) {\n if (ftruncate(shFD, shmemSize) == 0) {\n sharedMemory = mmap(NULL, shmemSize, (PROT_READ | PROT_WRITE), MAP_SHARED, shFD, 0);\n if (sharedMemory != MAP_FAILED) {\n // Initialize shared memory if needed\n // Send 'shmemSize' & 'shmemSize' to other process(es)\n } else handle error\n } else handle error\n close(shFD); // Note: sharedMemory still valid until munmap() called\n} else handle error\n\n...\nDo stuff with shared memory\n...\n\n// Tear down shared memory\nif (sharedMemory != NULL) munmap(sharedMemory, shmemSize);\nif (shFD >= 0) shm_unlink(shmName);\n\n\n\n\n\n// Get the shared memory block from another process\nvoid* sharedMemory = NULL;\nsize_t shmemSize = 123456; // Or fetched via some other form of IPC\nconst char* shmName = \"mySharedMemPath\";// Or fetched via some other form of IPC\nint shFD = shm_open(shmName, (O_RDONLY), 0600); // Can be R/W if you want\nif (shFD >= 0) {\n data = mmap(NULL, shmemSize, PROT_READ, MAP_SHARED, shFD, 0);\n if (data != MAP_FAILED) {\n // Check shared memory for validity\n } else handle error\n close(shFD); // Note: sharedMemory still valid until munmap() called\n} else handle error\n\n\n...\nDo stuff with shared memory\n...\n\n// Tear down shared memory\nif (sharedMemory != NULL) munmap(sharedMemory, shmemSize);\n// Only the creator should shm_unlink()\n</code></pre>\n"
},
{
"answer_id": 2095086,
"author": "fixermark",
"author_id": 57720,
"author_profile": "https://Stackoverflow.com/users/57720",
"pm_score": 1,
"selected": false,
"text": "<p>In general, I would recommend that you use regular open() to open a temporary file. Once it's open in both processes, you can unlink() it from the filesystem and you'll be set up much like you would be if you'd used shm_open. The procedure is extremely similar to the one specified by Scott Marcy for shm_open.</p>\n\n<p>The disadvantage to this approach is that if the process that will be doing the unlink() crashes, you end up with an unused file and no process has the responsibility of cleaning it up. This disadvantage is shared with shm_open, because if nothing shm_unlinks a given name, the name remains in the shared memory space, available to be shm_opened by future processes.</p>\n"
},
{
"answer_id": 19105476,
"author": "user2284570",
"author_id": 2284570,
"author_profile": "https://Stackoverflow.com/users/2284570",
"pm_score": 2,
"selected": false,
"text": "<p>You want to do Inter-Process-Communication with the shared memory method. For a summary of other commons method, see <a href=\"https://en.wikipedia.org/wiki/Inter-process_communication#Main_IPC_methods\" rel=\"nofollow noreferrer\" title=\"short brief of main IPC methods\">here</a></p>\n\n<p>It didn't take me long to find what you need in this <a href=\"http://books.google.fr/books?id=V8xQAAAAMAAJ&q=Unix+System+V:+Programmer's+Reference+Manual&dq=Unix+System+V:+Programmer's+Reference+Manual&hl=fr&sa=X&ei=yq1KUuSYN-WX1AXY04HABw&ved=0CEgQ6AEwAQ\" rel=\"nofollow noreferrer\" title=\"AT&T Unix System V: Programmer's Reference Manual\">book</a> which contains all the APIs which are common to all UNIXes today (which many more than I thought). You should buy it in the future. This book is a set of (several hundred) printed man pages which are rarely installed on modern machines.\nEach man page details a C function.</p>\n\n<p>It didn't take me long to find <strong><em>shmat()</em></strong> <strong><em>shmctl()</em></strong>; <strong><em>shmdt()</em></strong> and <strong><em>shmget()</em></strong> in it. I didn't search extensively, maybe there's more.</p>\n\n<p>It looked a bit outdated, but: YES, the base user-space API of modern UNIX OS back to the old 80's.</p>\n\n<p>Update: most functions described in the book are part of the POSIX C headers, you don't need to install anything. There are few exceptions, like with \"curses\", the original library.</p>\n"
},
{
"answer_id": 19236711,
"author": "user2284570",
"author_id": 2284570,
"author_profile": "https://Stackoverflow.com/users/2284570",
"pm_score": 2,
"selected": false,
"text": "<p>I have definitely found a short implementation of what you need (only one source file (main.c)).\nIt is specially designed for XNU.</p>\n<p>It is in the top ten result of Google search with the following keywords « dump process memory os x »</p>\n<p>The source code is <a href=\"https://github.com/gdbinit/readmem\" rel=\"nofollow noreferrer\" title=\"readmem\">here</a></p>\n<p>but from a strict point of virtual address space point de vue, you should be more interested with this question: <a href=\"https://stackoverflow.com/questions/2179416/os-x-generate-core-dump-without-bringing-down-the-process\">OS X: Generate core dump without bringing down the process?</a> (look also <a href=\"https://web.archive.org/web/20200103164014/https://osxbook.com/book/bonus/chapter8/core/\" rel=\"nofollow noreferrer\">this</a>)</p>\n<p>When you look at gcore source code, it is quite complex to do this since you need to deal with treads and their state...</p>\n<p>On most Linux distributions, the gcore program is now part of the GDB package. I think the OSX version is installed with xcode/the development tools.</p>\n<p><em><strong>UPDATE: wxHexEditor is an editor which can edit devices. IT CAN also edit process memory the same way it does for regular files. It work on all UNIX machines.</strong></em></p>\n"
},
{
"answer_id": 24985204,
"author": "Jona",
"author_id": 2029914,
"author_profile": "https://Stackoverflow.com/users/2029914",
"pm_score": 3,
"selected": false,
"text": "<p>I know this thread is 100 years old, but for people coming here from a search engine:</p>\n\n<p><a href=\"https://github.com/jona-t4/xnumem\" rel=\"noreferrer\">xnumem</a> does exactly what you are looking for, manipulate and read inter-process memory.</p>\n\n<pre><code>// Create new xnu_proc instance\nxnu_proc *Process = new xnu_proc();\n\n// Attach to pid (or process name)\nProcess->Attach(getpid());\n\n// Manipulate memory\nint i = 1337, i2 = 0;\ni2 = process->memory().Read<int>((uintptr_t)&i);\n\n// Detach from process\nProcess->Detach();\n</code></pre>\n"
}
] | 2008/08/14 | [
"https://Stackoverflow.com/questions/10668",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1114/"
] | I've been trying to understand how to read the memory of other processes on Mac OS X, but I'm not having much luck. I've seen many examples online using `ptrace` with `PEEKDATA` and such, however it doesn't have that option on BSD [[`man ptrace`](http://developer.apple.com/documentation/Darwin/Reference/ManPages/man2/ptrace.2.html)].
```
int pid = fork();
if (pid > 0) {
// mess around with child-process's memory
}
```
How is it possible to read from and write to the memory of another process on Mac OS X? | Matasano Chargen had a good post a while back on porting some debugging code to OS X, which included learning how to read and write memory in another process (among other things).
[It has to work, otherwise GDB wouldn't](http://replay.web.archive.org/20090627062246/http://www.matasano.com/log/1100/what-ive-been-doing-on-my-summer-vacation-or-it-has-to-work-otherwise-gdb-wouldnt/):
>
> It turns out Apple, in their infinite wisdom, had gutted `ptrace()`. The OS X man page lists the following request codes:
>
>
> * `PT_ATTACH` — to pick a process to debug
> * `PT_DENY_ATTACH` — so processes can stop themselves from being debugged
>
> [...]
>
>
> No mention of reading or writing memory or registers. Which would have been discouraging if the man page had not also mentioned `PT_GETREGS`, `PT_SETREGS`, `PT_GETFPREGS`, and `PT_SETFPREGS` in the error codes section. So, I checked `ptrace.h`. There I found:
>
>
> * `PT_READ_I` — to read instruction words
> * `PT_READ_D` — to read data words
> * `PT_READ_U` — to read U area data if you’re old enough to remember what the U area is
>
> [...]
>
>
> There’s one problem solved. I can read and write memory for breakpoints. But I still can’t get access to registers, and I need to be able to mess with EIP.
>
>
> |
10,680 | <p>Is there any difference between</p>
<pre><code> int on_exit(void (*function)(int , void *), void *arg);
</code></pre>
<p>and</p>
<pre><code> int atexit(void (*function)(void));
</code></pre>
<p>other than the fact that the function used by on_exit gets the exit status?</p>
<p>That is, if I don't care about the exit status, is there any reason to use one or the other?</p>
<p><strong>Edit:</strong> Many of the answers warned against <code>on_exit</code> because it's non-standard. If I'm developing an app that is for internal corporate use and guaranteed to run on specific configurations, should I worry about this? </p>
| [
{
"answer_id": 10684,
"author": "Derek Park",
"author_id": 872,
"author_profile": "https://Stackoverflow.com/users/872",
"pm_score": 4,
"selected": false,
"text": "<p>You should use <code>atexit()</code> if possible. <code>on_exit()</code> is nonstandard and less common. For example, it's not available on OS X.</p>\n\n<p>Kernel.org - <a href=\"http://www.kernel.org/doc/man-pages/online/pages/man3/on_exit.3.html\" rel=\"noreferrer\"><code>on_exit()</code></a>:</p>\n\n<blockquote>\n <p>This function comes from SunOS 4, but is also present in libc4, libc5 and\n glibc. It no longer occurs in Solaris (SunOS 5). Avoid this function, and\n use the standard atexit(3) instead.</p>\n</blockquote>\n"
},
{
"answer_id": 10686,
"author": "Mike Stone",
"author_id": 122,
"author_profile": "https://Stackoverflow.com/users/122",
"pm_score": 5,
"selected": true,
"text": "<p>According to <a href=\"http://www.delorie.com/gnu/docs/glibc/libc_560.html\" rel=\"noreferrer\">this link</a> I found, it seems there are a few differences. <code>on_exit</code> will let you pass in an argument that is passed in to the <code>on_exit</code> function when it is called... which might let you set up some pointers to do some cleanup work on when it is time to exit.</p>\n\n<p>Furthermore, it appears that <code>on_exit</code> was a SunOS specific function that may not be compatible on all platforms... so you may want to stick with atexit, despite it being more restrictive.</p>\n"
},
{
"answer_id": 10770,
"author": "Mike Stone",
"author_id": 122,
"author_profile": "https://Stackoverflow.com/users/122",
"pm_score": 0,
"selected": false,
"text": "<p>@Nathan</p>\n\n<p>First, see if there is another API call to determine exit status... a quick glance and I don't see one, but I am not well versed in the standard C API.</p>\n\n<p>An easy alternative is to have a global variable that stores the exit status... the default being an unknown error cause (for if the program terminates abnormally). Then, when you call exit, you can store the exit status in the global and retrieve it from any atexit functions. This requires storing the exit status diligently before every exit call, and clearly is not ideal, but if there is no API and you don't want to risk <code>on_exit</code> not being on the platform... it might be the only option.</p>\n"
},
{
"answer_id": 10796,
"author": "Derek Park",
"author_id": 872,
"author_profile": "https://Stackoverflow.com/users/872",
"pm_score": 1,
"selected": false,
"text": "<p>@Nathan, I can't find any function that will return the exit code for the current running process. I expect that it isn't set yet at the point when <code>atexit()</code> is called, anyway. By this I mean that the runtime knows what it is, but probably hasn't reported it to the OS. This is pretty much just conjecture, though.</p>\n\n<p>It looks like you will either need to use <code>on_exit()</code> or structure your program so that the exit code doesn't matter. It would not be unreasonable to have the last statement in your main function flip a global <code>exited_cleanly</code> variable to true. In the function you register with <code>atexit()</code>, you could check this variable to determine how the program exited. This will only give you two states, but I expect that would be sufficient for most needs. You could also expand this type of scheme to support more exit states if necessary.</p>\n"
},
{
"answer_id": 3273116,
"author": "R.. GitHub STOP HELPING ICE",
"author_id": 379897,
"author_profile": "https://Stackoverflow.com/users/379897",
"pm_score": 3,
"selected": false,
"text": "<p>The difference is that <code>atexit</code> is C and <code>on_exit</code> is some weird extension available on GNU and who-knows-what-other Unixy systems (but <strong>NOT</strong> part of POSIX).</p>\n"
}
] | 2008/08/14 | [
"https://Stackoverflow.com/questions/10680",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1084/"
] | Is there any difference between
```
int on_exit(void (*function)(int , void *), void *arg);
```
and
```
int atexit(void (*function)(void));
```
other than the fact that the function used by on\_exit gets the exit status?
That is, if I don't care about the exit status, is there any reason to use one or the other?
**Edit:** Many of the answers warned against `on_exit` because it's non-standard. If I'm developing an app that is for internal corporate use and guaranteed to run on specific configurations, should I worry about this? | According to [this link](http://www.delorie.com/gnu/docs/glibc/libc_560.html) I found, it seems there are a few differences. `on_exit` will let you pass in an argument that is passed in to the `on_exit` function when it is called... which might let you set up some pointers to do some cleanup work on when it is time to exit.
Furthermore, it appears that `on_exit` was a SunOS specific function that may not be compatible on all platforms... so you may want to stick with atexit, despite it being more restrictive. |
10,752 | <p>I know the so-called textbook definition of unit tests and integration tests. What I am curious about is when it is time to write unit tests... I will write them to cover as many sets of classes as possible.</p>
<p>For example, if I have a <code>Word</code> class, I will write some unit tests for the <code>Word</code> class. Then, I begin writing my <code>Sentence</code> class, and when it needs to interact with the <code>Word</code> class, I will often write my unit tests such that they test both <code>Sentence</code> and <code>Word</code>... at least in the places where they interact.</p>
<p><em>Have these tests essentially become integration tests because they now test the integration of these 2 classes, or is it just a unit test that spans 2 classes?</em></p>
<p>In general, because of this uncertain line, I will rarely actually write integration tests... or is my using the finished product to see if all the pieces work properly the actual integration tests, even though they are manual and rarely repeated beyond the scope of each individual feature?</p>
<p>Am I misunderstanding integration tests, or is there really just very little difference between integration and unit tests?</p>
| [
{
"answer_id": 10756,
"author": "DevelopingChris",
"author_id": 1220,
"author_profile": "https://Stackoverflow.com/users/1220",
"pm_score": 4,
"selected": false,
"text": "<p>using Single responsibility design, its black and white. More than 1 responsibility, its an integration test. </p>\n\n<p>By the duck test (looks, quacks, waddles, its a duck), its just a unit test with more than 1 newed object in it.</p>\n\n<p>When you get into mvc and testing it, controller tests are always integration, because the controller contains both a model unit and a view unit. Testing logic in that model, I would call a unit test.</p>\n"
},
{
"answer_id": 10758,
"author": "Jon Limjap",
"author_id": 372,
"author_profile": "https://Stackoverflow.com/users/372",
"pm_score": 4,
"selected": false,
"text": "<p>I think when you start thinking about integration tests, you are speaking more of a cross between physical layers rather than logical layers.</p>\n\n<p>For example, if your tests concern itself with generating content, it's a unit test: if your test concerns itself with just writing to disk, it's still a unit test, but once you test for both I/O AND the content of the file, then you have yourself an integration test. When you test the output of a function within a service, it's a unit-test, but once you make a service call and see if the function result is the same, then that's an integration test.</p>\n\n<p>Technically you cannot unit test just-one-class anyway. What if your class is composed with several other classes? Does that automatically make it an integration test? I don't think so.</p>\n"
},
{
"answer_id": 10760,
"author": "Christian Hagelid",
"author_id": 202,
"author_profile": "https://Stackoverflow.com/users/202",
"pm_score": 2,
"selected": false,
"text": "<p>Unit testing is testing against a unit of work or a block of code if you like. Usually performed by a single developer.</p>\n\n<p>Integration testing refers to the test that is performed, preferably on an integration server, when a developer commits their code to a source control repository. Integration testing might be performed by utilities such as Cruise Control.</p>\n\n<p>So you do your unit testing to validate that the unit of work you have built is working and then the integration test validates that whatever you have added to the repository didn't break something else.</p>\n"
},
{
"answer_id": 10761,
"author": "Lance Fisher",
"author_id": 571,
"author_profile": "https://Stackoverflow.com/users/571",
"pm_score": 2,
"selected": false,
"text": "<p>I think I would still call a couple of interacting classes a unit test provided that the unit tests for class1 are testing class1's features, and the unit tests for class2 are testing its features, and also that they are not hitting the database.</p>\n\n<p>I call a test an integration test when it runs through most of my stack and even hits the database.</p>\n\n<p>I really like this question, because TDD discussion sometimes feels a bit too purist to me, and it's good for me to see some concrete examples.</p>\n"
},
{
"answer_id": 10762,
"author": "John Smithers",
"author_id": 1069,
"author_profile": "https://Stackoverflow.com/users/1069",
"pm_score": 1,
"selected": false,
"text": "<p>A little bit academic this question, isn't it? ;-)\nMy point of view:\nFor me an integration test is the test of the whole part, not if two parts out of ten are going together.\nOur integration test shows, if the master build (containing 40 projects) will succeed.\nFor the projects we have tons of unit tests.\nThe most important thing concerning unit tests for me is, that one unit test must not be dependent on another unit test. So for me both test you describe above are unit tests, if they are independent. For integration tests this need not to be important.</p>\n"
},
{
"answer_id": 10769,
"author": "Michael Neale",
"author_id": 699,
"author_profile": "https://Stackoverflow.com/users/699",
"pm_score": 2,
"selected": false,
"text": "<p>I do the same - I call them all unit tests, but at some point I have a \"unit test\" that covers so much I often rename it to \"..IntegrationTest\" - just a name change only, nothing else changes. </p>\n\n<p>I think there is a continuation from \"atomic tests\" (testing one tiny class, or a method) to unit tests (class level) and integration tests - and then functional test (which are normally covering a lot more stuff from the top down) - there doesn't seem to be a clean cut off. </p>\n\n<p>If your test sets up data, and perhaps loads a database/file etc, then perhaps its more of an integration test (integration tests I find use less mocks and more real classes, but that doesn't mean you can't mock out some of the system).</p>\n"
},
{
"answer_id": 10817,
"author": "Rob Cooper",
"author_id": 832,
"author_profile": "https://Stackoverflow.com/users/832",
"pm_score": 6,
"selected": false,
"text": "<p>My 10 bits :D</p>\n\n<p>I was always told that <strong>Unit Tests</strong> is the testing of an <em>individual component</em> - which should be exercised to its fullest. Now, this tends to have many levels, since most components are made of smaller parts. For me, a <em>unit</em> is a functional part of the system. So it has to provide something of value (i.e. not a method for string parsing, but a <em>HtmlSanitizer</em> perhaps).</p>\n\n<p><strong>Integration Tests</strong> is the next step up, its taking one or more components and making sure they work together as they should.. You are then above the intricacies of worry about <em>how</em> the components work individually, but when you enter html into your <em>HtmlEditControl</em> , it somehow magically knows wether its valid or not..</p>\n\n<p>Its a real movable line though.. I'd rather focus more on getting the damn code to work full stop ^_^</p>\n"
},
{
"answer_id": 10861,
"author": "grom",
"author_id": 486,
"author_profile": "https://Stackoverflow.com/users/486",
"pm_score": 3,
"selected": false,
"text": "<p><a href=\"http://en.wikipedia.org/wiki/Unit_testing\" rel=\"noreferrer\">Unit Testing</a> is a method of testing that verifies the individual units of source code are working properly.</p>\n\n<p><a href=\"http://en.wikipedia.org/wiki/Integration_testing\" rel=\"noreferrer\">Integration Testing</a> is the phase of software testing in which individual software modules are combined and tested as a group. </p>\n\n<p><a href=\"http://en.wikipedia.org/wiki/Unit_testing\" rel=\"noreferrer\">Wikipedia</a> defines a unit as the smallest testable part of an application, which in Java/C# is a method. But in your example of Word and Sentence class I would probably just write the tests for sentence since I would likely find it overkill to use a <a href=\"http://en.wikipedia.org/wiki/Mock_object\" rel=\"noreferrer\">mock</a> word class in order to test the sentence class. So sentence would be my unit and word is an implementation detail of that unit.</p>\n"
},
{
"answer_id": 10924,
"author": "CVertex",
"author_id": 209,
"author_profile": "https://Stackoverflow.com/users/209",
"pm_score": 2,
"selected": false,
"text": "<p>I call unit tests those tests that white box test a class. Any dependencies that class requires is replaced with fake ones (mocks).</p>\n\n<p>Integration tests are those tests where multiple classes and their interactions are tested at the same time. Only some dependencies in these cases are faked/mocked.</p>\n\n<p>I wouldn't call Controller's integration tests unless one of their dependencies is a real one (i.e. not faked) (e.g. IFormsAuthentication).</p>\n\n<p>Separating the two types of tests is useful for testing the system at different levels. Also, integration tests tend to be long lived, and unit tests are supposed to be quick. The execution speed distinction means they're executed differently. In our dev processes, unit tests are run at check-in (which is fine cos they're super quick), and integration tests are run once/twice per day. I try and run integration tests as often as possible, but usually hitting the database/writing to files/making rpc's/etc slows.</p>\n\n<p>That raises another important point, unit tests should avoid hitting IO (e.g. disk, network, db). Otherwise they slow down alot. It takes a bit of effort to design these IO dependencies out - i can't admit I've been faithful to the \"unit tests must be fast\" rule, but if you are, the benefits on a much larger system become apparent very quickly.</p>\n"
},
{
"answer_id": 38328,
"author": "Larry Foulkrod",
"author_id": 1642688,
"author_profile": "https://Stackoverflow.com/users/1642688",
"pm_score": 6,
"selected": false,
"text": "<p>When I write unit tests I limit the scope of the code being tested to the class I am currently writing by mocking dependencies. If I am writing a Sentence class, and Sentence has a dependency on Word, I will use a mock Word. By mocking Word I can focus only on its interface and test the various behaviors of my Sentence class as it interacts with Word's interface. This way I am only testing the behavior and implementation of Sentence and not at the same time testing the implementation of Word.</p>\n\n<p>Once I've written the unit tests to ensure Sentence behaves correctly when it interacts with Word based on Word's interface, then I write the integration test to make sure that my assumptions about the interactions were correct. For this I supply the actual objects and write a test that exercises a feature that will end up using both Sentence and Word.</p>\n"
},
{
"answer_id": 132341,
"author": "Pavel Feldman",
"author_id": 5507,
"author_profile": "https://Stackoverflow.com/users/5507",
"pm_score": 1,
"selected": false,
"text": "<blockquote>\n <p>Have these tests essentially become integration tests because they now test the integration of these 2 classes? Or is it just a unit test that spans 2 classes?</p>\n</blockquote>\n\n<p>I think Yes and Yes. Your unit test that spans 2 classes became an integration test. </p>\n\n<p>You could avoid it by testing Sentence class with mock implementation - MockWord class, which is important when those parts of system are large enough to be implemented by different developers. In that case Word is unit tested alone, Sentence is unit tested with help of MockWord, and then Sentence is integration-tested with Word.</p>\n\n<p>Exaple of real difference can be following\n1) Array of 1,000,000 elements is easily unit tested and works fine.\n2) BubbleSort is easily unit tested on mock array of 10 elements and also works fine\n3) Integration testing shows that something is not so fine.</p>\n\n<p>If these parts are developed by single person, most likely problem will be found while unit testing BubbleSoft just because developer already has real array and he does not need mock implementation.</p>\n"
},
{
"answer_id": 1223466,
"author": "Robert Koritnik",
"author_id": 75642,
"author_profile": "https://Stackoverflow.com/users/75642",
"pm_score": 5,
"selected": false,
"text": "<p><strong>Unit tests use mocks</strong></p>\n\n<p>The thing you're talking about are integration tests that actually test the whole integration of your system. But when you do unit testing you should actually test each unit separately. Everything else should be mocked. So in your case of <code>Sentence</code> class, if it uses <code>Word</code> class, then your <code>Word</code> class should be mocked. This way, you'll only test your <code>Sentence</code> class functionality.</p>\n"
},
{
"answer_id": 7876055,
"author": "Arialdo Martini",
"author_id": 202443,
"author_profile": "https://Stackoverflow.com/users/202443",
"pm_score": 8,
"selected": false,
"text": "<p>The key difference, to me, is that <strong>integration tests</strong> reveal if a feature is working or is broken, since they stress the code in a scenario close to reality. They invoke one or more software methods or features and test if they act as expected.</p>\n\n<p>On the opposite, a <strong>Unit test</strong> testing a single method relies on the (often wrong) assumption that the rest of the software is correctly working, because it explicitly mocks every dependency.</p>\n\n<p>Hence, when a unit test for a method implementing some feature is green, it does <b>not</b> mean the feature is working.</p>\n\n<p>Say you have a method somewhere like this:</p>\n\n<pre><code>public SomeResults DoSomething(someInput) {\n var someResult = [Do your job with someInput];\n Log.TrackTheFactYouDidYourJob();\n return someResults;\n}\n</code></pre>\n\n<p><code>DoSomething</code> is very important to your customer: it's a feature, the only thing that matters. That's why you usually write a Cucumber specification asserting it: you wish to <i>verify</i> and <i>communicate</i> the feature is working or not.</p>\n\n<pre><code>Feature: To be able to do something\n In order to do something\n As someone\n I want the system to do this thing\n\nScenario: A sample one\n Given this situation\n When I do something\n Then what I get is what I was expecting for\n</code></pre>\n\n<p>No doubt: if the test passes, you can assert you are delivering a working feature. This is what you can call <b>Business Value</b>.</p>\n\n<p>If you want to write a unit test for <code>DoSomething</code> you should pretend (using some mocks) that the rest of the classes and methods are working (that is: that, all dependencies the method is using are correctly working) and assert your method is working.</p>\n\n<p>In practice, you do something like:</p>\n\n<pre><code>public SomeResults DoSomething(someInput) {\n var someResult = [Do your job with someInput];\n FakeAlwaysWorkingLog.TrackTheFactYouDidYourJob(); // Using a mock Log\n return someResults;\n}\n</code></pre>\n\n<p>You can do this with Dependency Injection, or some Factory Method or any Mock Framework or just extending the class under test.</p>\n\n<p>Suppose there's a bug in <code>Log.DoSomething()</code>.\nFortunately, the Gherkin spec will find it and your end-to-end tests will fail.</p>\n\n<p>The feature won't work, because <code>Log</code> is broken, not because <code>[Do your job with someInput]</code> is not doing its job. And, by the way, <code>[Do your job with someInput]</code> is the sole responsibility for that method.</p>\n\n<p>Also, suppose <code>Log</code> is used in 100 other features, in 100 other methods of 100 other classes.</p>\n\n<p>Yep, 100 features will fail. But, fortunately, 100 end-to-end tests are failing as well and revealing the problem. And, yes: <b>they are telling the truth</b>.</p>\n\n<p>It's very useful information: I know I have a broken product. It's also very confusing information: it tells me nothing about where the problem is. It communicates me the symptom, not the root cause.</p>\n\n<p>Yet, <code>DoSomething</code>'s unit test is green, because it's using a fake <code>Log</code>, built to never break. And, yes: <b>it's clearly lying</b>. It's communicating a broken feature is working. How can it be useful?</p>\n\n<p>(If <code>DoSomething()</code>'s unit test fails, be sure: <code>[Do your job with someInput]</code> has some bugs.)</p>\n\n<p>Suppose this is a system with a broken class:\n<img src=\"https://i.stack.imgur.com/611ZY.jpg\" alt=\"A system with a broken class\"></p>\n\n<p>A single bug will break several features, and several integration tests will fail.</p>\n\n<p><img src=\"https://i.stack.imgur.com/rKhSr.jpg\" alt=\"A single bug will break several features, and several integration tests will fail\"></p>\n\n<p>On the other hand, the same bug will break just one unit test.</p>\n\n<p><img src=\"https://i.stack.imgur.com/M64Vb.jpg\" alt=\"The same bug will break just one unit test\"></p>\n\n<p>Now, compare the two scenarios.</p>\n\n<p>The same bug will break just one unit test.</p>\n\n<ul>\n<li>All your features using the broken <code>Log</code> are red</li>\n<li>All your unit tests are green, only the unit test for <code>Log</code> is red</li>\n</ul>\n\n<p>Actually, unit tests for all modules using a broken feature are green because, by using mocks, they removed dependencies. In other words, they run in an ideal, completely fictional world. And this is the only way to isolate bugs and seek them. Unit testing means mocking. If you aren't mocking, you aren't unit testing.</p>\n\n<h2>The difference</h2>\n\n<p>Integration tests tell <b>what</b>'s not working. But they are of no use in <b>guessing where</b> the problem could be.</p>\n\n<p>Unit tests are the sole tests that tell you <b>where</b> exactly the bug is. To draw this information, they must run the method in a mocked environment, where all other dependencies are supposed to correctly work.</p>\n\n<p>That's why I think that your sentence \"Or is it just a unit test that spans 2 classes\" is somehow displaced. A unit test should never span 2 classes.</p>\n\n<p>This reply is basically a summary of what I wrote here: <a href=\"http://arialdomartini.wordpress.com/2011/10/21/unit-tests-lie-thats-why-i-love-them/\" rel=\"noreferrer\">Unit tests lie, that's why I love them</a>.</p>\n"
},
{
"answer_id": 11476650,
"author": "Pascal",
"author_id": 401643,
"author_profile": "https://Stackoverflow.com/users/401643",
"pm_score": 2,
"selected": false,
"text": "<p>Integration tests: Database persistence is tested.<br>\nUnit tests: Database access is mocked. Code methods are tested.</p>\n"
},
{
"answer_id": 17767843,
"author": "David Sackstein",
"author_id": 2603228,
"author_profile": "https://Stackoverflow.com/users/2603228",
"pm_score": 3,
"selected": false,
"text": "<p>In my opinion the answer is \"Why does it matter?\"</p>\n\n<p>Is it because unit tests are something you do and integration tests are something you don't? Or vice versa? Of course not, you should try to do both.</p>\n\n<p>Is it because unit tests need to be Fast, Isolated, Repeatable, Self-Validating and Timely and integration tests should not? Of course not, all tests should be these.</p>\n\n<p>It is because you use mocks in unit tests but you don't use them in integration tests? Of course not. This would imply that if I have a useful integration test I am not allowed to add a mock for some part, fear I would have to rename my test to \"unit test\" or hand it over to another programmer to work on.</p>\n\n<p>Is it because unit tests test one unit and integration tests test a number of units? Of course not. Of what practical importance is that? The theoretical discussion on the scope of tests breaks down in practice anyway because the term \"unit\" is entirely context dependent. At the class level, a unit might be a method. At an assembly level, a unit might be a class, and at the service level, a unit might be a component.\nAnd even classes use other classes, so which is the unit?</p>\n\n<p>It is of no importance.</p>\n\n<p>Testing is important, F.I.R.S.T is important, splitting hairs about definitions is a waste of time which only confuses newcomers to testing.</p>\n"
},
{
"answer_id": 18725056,
"author": "Paulo Merson",
"author_id": 317522,
"author_profile": "https://Stackoverflow.com/users/317522",
"pm_score": 1,
"selected": false,
"text": "<p>In addition, it's important to remember that both unit tests and integration tests can be automated and written using, for example, JUnit. \nIn JUnit integration tests, one can use the <code>org.junit.Assume</code> class to test the availability of environment elements (e.g., database connection) or other conditions. </p>\n"
},
{
"answer_id": 25976990,
"author": "Lutz Prechelt",
"author_id": 2810305,
"author_profile": "https://Stackoverflow.com/users/2810305",
"pm_score": 3,
"selected": false,
"text": "<h1>The nature of your tests</h1>\n\n<p>A <strong>unit test</strong> of module X is a test that expects (and checks for) problems only in module X.</p>\n\n<p>An <strong>integration test</strong> of many modules is a test that expects problems that arise from the cooperation <em>between</em> the modules so that these problems would be difficult to find using unit tests alone.</p>\n\n<p>Think of the nature of your tests in the following terms:</p>\n\n<ul>\n<li><strong>Risk reduction</strong>: That's what tests are for. Only a <em>combination of unit tests and integration tests</em> can give you full risk reduction, because on the one hand unit tests can inherently not test the proper interaction between modules and on the other hand integration tests can exercise the functionality of a non-trivial module only to a small degree.</li>\n<li><strong>Test writing effort</strong>: Integration tests can save effort because you may then not need to write stubs/fakes/mocks. But unit tests can save effort, too, when implementing (and maintaining!) those stubs/fakes/mocks happens to be easier than configuring the test setup without them.</li>\n<li><strong>Test execution delay</strong>: Integration tests involving heavyweight operations (such as access to external systems like DBs or remote servers) tend to be slow(er). This means unit tests can be executed far more frequently, which reduces debugging effort if anything fails, because you have a better idea what you have changed in the meantime. This becomes particularly important if you use test-driven development (TDD).</li>\n<li><strong>Debugging effort</strong>: If an integration test fails, but none of the unit tests does, this can be very inconvenient, because there is so much code involved that <em>may</em> contain the problem. This is not a big problem if you have previously changed only a few lines -- but as integration tests run slowly, you perhaps did <em>not</em> run them in such short intervals...</li>\n</ul>\n\n<p>Remember that an integration test may still stub/fake/mock away <em>some</em> of its dependencies.\nThis provides plenty of middle ground between unit tests and system tests (the most comprehensive integration tests, testing all of the system).</p>\n\n<h2>Pragmatic approach to using both</h2>\n\n<p>So a pragmatic approach would be: Flexibly rely on integration tests as much as you sensibly can and use unit tests where this would be too risky or inconvenient.\nThis manner of thinking may be more useful than some dogmatic discrimination of unit tests and integration tests.</p>\n"
},
{
"answer_id": 40986071,
"author": "BenKoshy",
"author_id": 4880924,
"author_profile": "https://Stackoverflow.com/users/4880924",
"pm_score": 2,
"selected": false,
"text": "<h2>Simple Explanation with Analogies</h2>\n\n<p>The above examples do very well and I needn't repeat them. So I'll focus on using examples to help you understand. </p>\n\n<h3>Integration Tests</h3>\n\n<p>Integration tests check if everything is working together. Imagine a series of cogs working together in a watch. An integration test would be: is the watch telling the correct time? Is it still telling the correct time in 3 days?</p>\n\n<p>All it tells you is whether the overall piece is working. If it fails: it doesn’t tell you exactly where it is failing.</p>\n\n<h3>Unit Tests</h3>\n\n<p>These are really specific types of test. They tell you whether one specific thing is working or failing. The key to this type of test is that it tests only one specific thing while assuming that everything else is working just fine. That’s the key point. </p>\n\n<p><em>Example:</em>\nLet’s elaborate on this point using an example:</p>\n\n<ul>\n<li>Let’s take a car as an example. </li>\n<li><strong>Integration</strong> test for a car: e.g. does the car drive to Woop Woop and back? If it does this, you can safely say that a car is working from an overall view point. It is an integration test. If it fails you have no idea where it is actually failing: is it the radiator, transmission, engine, or carburettor? You have no idea. It could be anything.</li>\n<li><strong>Unit test</strong> for a car: Is the engine is working? This tests assumes that everything else in the car is working just fine. That way, if this particular unit test fails: you can be very confident that the problem lies in the engine – so you can quickly isolate and fix the problem.</li>\n</ul>\n\n<h3>Using Stubs</h3>\n\n<ul>\n<li><p>Suppose your car integration test fails. It doesn’t drive successfully to Echuca. Where is the problem?</p></li>\n<li><p>Now let us suppose that your engine uses a special fuel injection system and that this engine unit test has also failed. In other words, both the integration test and the engine unit test have failed. Where then is the problem? (Give yourself 10 seconds to get the answer.)</p></li>\n<li><p>Is the problem with the engine, or with the fuel injection system?</p></li>\n</ul>\n\n<p>You see the problem here? You don’t know what exactly is failing. If you use different external dependencies, then every single one of those 10 could have caused the problem – and you won’t know where to start. That’s why unit tests use stubs to assume that everything else is working just fine.</p>\n"
},
{
"answer_id": 53123030,
"author": "StevePoling",
"author_id": 1839838,
"author_profile": "https://Stackoverflow.com/users/1839838",
"pm_score": 0,
"selected": false,
"text": "<p>If you're a TDD purist, you write the tests before you write production code. Of course, the tests won't compile, so you first make the tests compile, then make the tests pass.</p>\n\n<p>You can do this with unit tests, but you can't with integration or acceptance tests. If you tried with an integration test, nothing would ever compile until you've finished!</p>\n"
},
{
"answer_id": 57283806,
"author": "Michu93",
"author_id": 4952262,
"author_profile": "https://Stackoverflow.com/users/4952262",
"pm_score": 5,
"selected": false,
"text": "<p>In unit test you test every part isolated:\n<a href=\"https://i.stack.imgur.com/bmhZg.jpg\" rel=\"noreferrer\"><img src=\"https://i.stack.imgur.com/bmhZg.jpg\" alt=\"enter image description here\"></a></p>\n\n<p>in integration test you test many modules of your system:</p>\n\n<p><a href=\"https://i.stack.imgur.com/v186T.jpg\" rel=\"noreferrer\"><img src=\"https://i.stack.imgur.com/v186T.jpg\" alt=\"enter image description here\"></a></p>\n\n<p>and this what happens when you only use unit tests (generally both windows are working, unfortunately not together):</p>\n\n<p><a href=\"https://i.stack.imgur.com/yHGn1.gif\" rel=\"noreferrer\"><img src=\"https://i.stack.imgur.com/yHGn1.gif\" alt=\"enter image description here\"></a></p>\n\n<p>Sources:\n<a href=\"https://dariuszwozniak.net/posts/kurs-tdd-2-testy-jednostkowe-a-testy-integracyjne/\" rel=\"noreferrer\">source1</a>\n<a href=\"http://softwaretestingfundamentals.com/integration-testing/\" rel=\"noreferrer\">source2</a></p>\n"
},
{
"answer_id": 74559852,
"author": "John",
"author_id": 866333,
"author_profile": "https://Stackoverflow.com/users/866333",
"pm_score": 0,
"selected": false,
"text": "<p>I get asked this a lot in interviews. Until now I'd ramble on pretentiously about my expertise and pontificate about component and acceptance testing.</p>\n<p>For years I'd understood <strong>only</strong> integration and unit tests. I could, but didn't always bother to, write unit tests as a solo developer honing my skills.</p>\n<h2>Unit tests</h2>\n<p>That is a crucial difference. Unit tests are easy to implement and execute, requiring, ideally, no dependencies. That is what mocks are for. It is often easier to <em>not</em> mock <em>everything</em>, particularly where you gain coverage of other functions you wrote. Easier, maybe, but that isn't the idea of unit testing.</p>\n<p>I'll reiterate, unit tests are meant to be easy to run and small. Their failure provides immediate insight into where a bug has been introduced.</p>\n<p>Here is the hierarchy of tests, from cheap and plentiful at the bottom to slow, expensive, and few, at the top:</p>\n<p><a href=\"https://i.stack.imgur.com/gFsdT.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/gFsdT.png\" alt=\"hierarchy of test expense and breadth.\" /></a></p>\n<p>Several more layers can be conceptualised, but were omitted for clarity.</p>\n<h2>Integration tests</h2>\n<p>With integration tests you would consider bringing in serious external dependencies, such as VMs, virtual networks and appliances. Possibly you could use actual modems, routers, and firewalls where the expense was justified.</p>\n<p>These wouldn't be run locally but on a build server. A mixture of local Jenkins and cloud based CI providers fulfil this need.</p>\n<h2>Other test terminology</h2>\n<p>That is my understanding that has served me for several years in industry. We could talk about component tests, and get a definition, but if the definition isn't in common circulation then it loses value.</p>\n<p>Acceptance tests were what we would call business unit or customer requirements. These would lead the direction of everything and sit at the top of the pyramid (picture a dollar sign).</p>\n<p>E2E, or end to end testing was used synonymously with integration tests, but I noticed online it is placed above. I guess it could have more relevance to acceptance tests the integration tests, which would tend to be more detailed with less interest from stakeholders (though immense interest internally in the department).</p>\n"
}
] | 2008/08/14 | [
"https://Stackoverflow.com/questions/10752",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/122/"
] | I know the so-called textbook definition of unit tests and integration tests. What I am curious about is when it is time to write unit tests... I will write them to cover as many sets of classes as possible.
For example, if I have a `Word` class, I will write some unit tests for the `Word` class. Then, I begin writing my `Sentence` class, and when it needs to interact with the `Word` class, I will often write my unit tests such that they test both `Sentence` and `Word`... at least in the places where they interact.
*Have these tests essentially become integration tests because they now test the integration of these 2 classes, or is it just a unit test that spans 2 classes?*
In general, because of this uncertain line, I will rarely actually write integration tests... or is my using the finished product to see if all the pieces work properly the actual integration tests, even though they are manual and rarely repeated beyond the scope of each individual feature?
Am I misunderstanding integration tests, or is there really just very little difference between integration and unit tests? | The key difference, to me, is that **integration tests** reveal if a feature is working or is broken, since they stress the code in a scenario close to reality. They invoke one or more software methods or features and test if they act as expected.
On the opposite, a **Unit test** testing a single method relies on the (often wrong) assumption that the rest of the software is correctly working, because it explicitly mocks every dependency.
Hence, when a unit test for a method implementing some feature is green, it does **not** mean the feature is working.
Say you have a method somewhere like this:
```
public SomeResults DoSomething(someInput) {
var someResult = [Do your job with someInput];
Log.TrackTheFactYouDidYourJob();
return someResults;
}
```
`DoSomething` is very important to your customer: it's a feature, the only thing that matters. That's why you usually write a Cucumber specification asserting it: you wish to *verify* and *communicate* the feature is working or not.
```
Feature: To be able to do something
In order to do something
As someone
I want the system to do this thing
Scenario: A sample one
Given this situation
When I do something
Then what I get is what I was expecting for
```
No doubt: if the test passes, you can assert you are delivering a working feature. This is what you can call **Business Value**.
If you want to write a unit test for `DoSomething` you should pretend (using some mocks) that the rest of the classes and methods are working (that is: that, all dependencies the method is using are correctly working) and assert your method is working.
In practice, you do something like:
```
public SomeResults DoSomething(someInput) {
var someResult = [Do your job with someInput];
FakeAlwaysWorkingLog.TrackTheFactYouDidYourJob(); // Using a mock Log
return someResults;
}
```
You can do this with Dependency Injection, or some Factory Method or any Mock Framework or just extending the class under test.
Suppose there's a bug in `Log.DoSomething()`.
Fortunately, the Gherkin spec will find it and your end-to-end tests will fail.
The feature won't work, because `Log` is broken, not because `[Do your job with someInput]` is not doing its job. And, by the way, `[Do your job with someInput]` is the sole responsibility for that method.
Also, suppose `Log` is used in 100 other features, in 100 other methods of 100 other classes.
Yep, 100 features will fail. But, fortunately, 100 end-to-end tests are failing as well and revealing the problem. And, yes: **they are telling the truth**.
It's very useful information: I know I have a broken product. It's also very confusing information: it tells me nothing about where the problem is. It communicates me the symptom, not the root cause.
Yet, `DoSomething`'s unit test is green, because it's using a fake `Log`, built to never break. And, yes: **it's clearly lying**. It's communicating a broken feature is working. How can it be useful?
(If `DoSomething()`'s unit test fails, be sure: `[Do your job with someInput]` has some bugs.)
Suppose this is a system with a broken class:

A single bug will break several features, and several integration tests will fail.

On the other hand, the same bug will break just one unit test.

Now, compare the two scenarios.
The same bug will break just one unit test.
* All your features using the broken `Log` are red
* All your unit tests are green, only the unit test for `Log` is red
Actually, unit tests for all modules using a broken feature are green because, by using mocks, they removed dependencies. In other words, they run in an ideal, completely fictional world. And this is the only way to isolate bugs and seek them. Unit testing means mocking. If you aren't mocking, you aren't unit testing.
The difference
--------------
Integration tests tell **what**'s not working. But they are of no use in **guessing where** the problem could be.
Unit tests are the sole tests that tell you **where** exactly the bug is. To draw this information, they must run the method in a mocked environment, where all other dependencies are supposed to correctly work.
That's why I think that your sentence "Or is it just a unit test that spans 2 classes" is somehow displaced. A unit test should never span 2 classes.
This reply is basically a summary of what I wrote here: [Unit tests lie, that's why I love them](http://arialdomartini.wordpress.com/2011/10/21/unit-tests-lie-thats-why-i-love-them/). |
10,793 | <p>I'm dynamically loading user controls adding them to the Controls collection of the web form.</p>
<p>I'd like to hide user controls if they cause a unhandled exception while rendering.</p>
<p>So, I tried hooking to the Error event of each UserControl but it seems that this event never fires for the UserControls as it does for Page class. </p>
<p>Did some googling around and it doesn't seem promising. Any ideas here?</p>
| [
{
"answer_id": 10797,
"author": "Michael Stum",
"author_id": 91,
"author_profile": "https://Stackoverflow.com/users/91",
"pm_score": 0,
"selected": false,
"text": "<p>Global.asax and Application_Error?</p>\n\n<p><a href=\"http://www.15seconds.com/issue/030102.htm\" rel=\"nofollow noreferrer\">http://www.15seconds.com/issue/030102.htm</a></p>\n\n<p>Or the Page_Error Event on an individual Page only:</p>\n\n<p><a href=\"http://support.microsoft.com/kb/306355\" rel=\"nofollow noreferrer\">http://support.microsoft.com/kb/306355</a></p>\n\n<pre><code>void Page_Load(object sender, System.EventArgs e)\n{\n throw(new ArgumentNullException());\n}\n\npublic void Page_Error(object sender,EventArgs e)\n{\n Exception objErr = Server.GetLastError().GetBaseException();\n string err = \"<b>Error Caught in Page_Error event</b><hr><br>\" + \n \"<br><b>Error in: </b>\" + Request.Url.ToString() +\n \"<br><b>Error Message: </b>\" + objErr.Message.ToString()+\n \"<br><b>Stack Trace:</b><br>\" + \n objErr.StackTrace.ToString();\n Response.Write(err.ToString());\n Server.ClearError();\n}\n</code></pre>\n\n<p>Also, Karl Seguin (Hi Karl!) had a Post on using HttpHandler instead:</p>\n\n<p><a href=\"http://codebetter.com/blogs/karlseguin/archive/2006/06/12/146356.aspx\" rel=\"nofollow noreferrer\">http://codebetter.com/blogs/karlseguin/archive/2006/06/12/146356.aspx</a></p>\n\n<p>(Not sure what the permission to reproduce it, but if you want to write up an answer, you got my Upvote ☺)</p>\n"
},
{
"answer_id": 10812,
"author": "Keith",
"author_id": 905,
"author_profile": "https://Stackoverflow.com/users/905",
"pm_score": 0,
"selected": false,
"text": "<p>How about adding a new sub-class of UserControl that error-handles its render and load methods (so that they hide as you wish) and then inheriting from that for your user controls?</p>\n"
},
{
"answer_id": 10815,
"author": "Rob Cooper",
"author_id": 832,
"author_profile": "https://Stackoverflow.com/users/832",
"pm_score": 2,
"selected": false,
"text": "<p>This is an interesting problem.. I am still pretty fresh when it comes to custom controls etc, but here are my thoughts (feel free to comment/correct people!).. (I am kinda thinking/writing out loud here!)</p>\n\n<ul>\n<li>If an error occurs during rendering, in some cases, would it not be too late? (since some of the controls HTML may have already been sent to the Writer and output).</li>\n<li>Therefore, would it not be best to wrap the user control's Render method, but rather than passing it the reference to the \"Live\" HtmlTextWriter, you pass your own, trap any Exceptions raised in this little safety \"bubble\", if all goes well, you then pass your resultant HTML to the actual HtmlTextWriter?</li>\n<li>This logic could probably be slung to a generic wrapper class which you would use to dynamically load/render the controls at run time..</li>\n<li>If any errors do occur, you have all the information you need at your disposal! (i.e control references etc).</li>\n</ul>\n\n<p>Just my thoughts, flame away! :D ;)</p>\n"
},
{
"answer_id": 10916,
"author": "Keith",
"author_id": 905,
"author_profile": "https://Stackoverflow.com/users/905",
"pm_score": 1,
"selected": false,
"text": "<p>Depending on where your errors are occurring you can do something like...</p>\n\n<pre><code>public abstract class SilentErrorControl : UserControl\n{\n protected override void Render( HtmlTextWriter writer )\n {\n //call the base's render method, but with a try catch\n try { base.Render( writer ); }\n catch ( Exception ex ) { /*do nothing*/ }\n }\n}\n</code></pre>\n\n<p>Then inherit SilentErrorControl instead of UserControl.</p>\n"
},
{
"answer_id": 12055,
"author": "Rob Cooper",
"author_id": 832,
"author_profile": "https://Stackoverflow.com/users/832",
"pm_score": 5,
"selected": true,
"text": "<p>mmilic, following on from <a href=\"https://stackoverflow.com/questions/10793/catching-unhandled-exceptions-in-aspnet-usercontrols#10910\">your response</a> to my <a href=\"https://stackoverflow.com/questions/10793/catching-unhandled-exceptions-in-aspnet-usercontrols#10815\">previous idea</a>..</p>\n\n<p>No additional logic required! That's the point, your doing nothing to the classes in question, just wrapping them in some instantiation bubble-wrap! :)</p>\n\n<p>OK, I was going to just bullet point but I wanted to see this work for myself, so I cobbled together some <em>very</em> rough code but the concept is there and it seems to work.</p>\n\n<p><strong>APOLOGIES FOR THE LONG POST</strong></p>\n\n<h2>The SafeLoader</h2>\n\n<p>This will basically be the \"bubble\" I mentioned.. It will get the controls HTML, catching any errors that occur during Rendering.</p>\n\n<pre><code>public class SafeLoader\n{\n public static string LoadControl(Control ctl)\n {\n // In terms of what we could do here, its down\n // to you, I will just return some basic HTML saying\n // I screwed up.\n try\n {\n // Get the Controls HTML (which may throw)\n // And store it in our own writer away from the\n // actual Live page.\n StringWriter writer = new StringWriter();\n HtmlTextWriter htmlWriter = new HtmlTextWriter(writer);\n ctl.RenderControl(htmlWriter);\n\n return writer.GetStringBuilder().ToString();\n }\n catch (Exception)\n {\n string ctlType = ctl.GetType().Name;\n return \"<span style=\\\"color: red; font-weight:bold; font-size: smaller;\\\">\" + \n \"Rob + Controls = FAIL (\" + \n ctlType + \" rendering failed) Sad face :(</span>\";\n }\n }\n}\n</code></pre>\n\n<h2>And Some Controls..</h2>\n\n<p>Ok I just mocked together two controls here, one will throw the other will render junk. Point here, I don't give a crap. These will be replaced with your custom controls..</p>\n\n<h3>BadControl</h3>\n\n<pre><code>public class BadControl : WebControl\n{\n protected override void Render(HtmlTextWriter writer)\n {\n throw new ApplicationException(\"Rob can't program controls\");\n }\n}\n</code></pre>\n\n<h3>GoodControl</h3>\n\n<pre><code>public class GoodControl : WebControl\n{\n protected override void Render(HtmlTextWriter writer)\n {\n writer.Write(\"<b>Holy crap this control works</b>\");\n }\n}\n</code></pre>\n\n<h2>The Page</h2>\n\n<p>OK, so lets look at the \"test\" page.. Here I simply instantiate the controls, grab their html and output it, I will follow with thoughts on designer support etc..</p>\n\n<h3>Page Code-Behind</h3>\n\n<pre><code> protected void Page_Load(object sender, EventArgs e)\n {\n // Create some controls (BadControl will throw)\n string goodHtml = SafeLoader.LoadControl(new BadControl());\n Response.Write(goodHtml);\n\n string badHtml = SafeLoader.LoadControl(new GoodControl());\n Response.Write(badHtml);\n }\n</code></pre>\n\n<h3>Thoughts</h3>\n\n<p>OK, I know what you are thinking, \"these controls are instantiated programatically, what about designer support? I spent freaking hours getting these controls nice for the designer, now you're messing with my mojo\".</p>\n\n<p>OK, so I havent really tested this yet (probably will do in a min!) but the idea here is to override the CreateChildControls method for the page, and take the instance of each control added on the form and run it through the SafeLoader. If the code passes, you can add it to the Controls collection as normal, if not, then you can create erroneous literals or something, up to you my friend.</p>\n\n<h2>Finally..</h2>\n\n<p>Again, sorry for the long post, but I wanted to get the code here so we can discuss this :)\nI hope this helps demonstrate my idea :)</p>\n\n<h2>Update</h2>\n\n<p>Tested by chucking a control in on the designer and overriding the CreateChildControls method with this, works fine, may need some clean up to make things better looking, but I'll leave that to you ;)</p>\n\n<pre><code>protected override void CreateChildControls()\n{\n // Pass each control through the Loader to check\n // its not lame\n foreach (Control ctl in Controls)\n {\n string s = SafeLoader.LoadControl(ctl);\n // If its bad, smack it downnnn!\n if (s == string.Empty)\n {\n ctl.Visible = false; // Prevent Rendering\n string ctlType = ctl.GetType().Name;\n Response.Write(\"<b>Problem Occurred Rendering \" + \n ctlType + \" '\" + ctl.ID + \"'.</b>\");\n }\n }\n}\n</code></pre>\n\n<p>Enjoy!</p>\n"
},
{
"answer_id": 17871,
"author": "Rob Cooper",
"author_id": 832,
"author_profile": "https://Stackoverflow.com/users/832",
"pm_score": 0,
"selected": false,
"text": "<p>I am not sure I understand <a href=\"https://stackoverflow.com/questions/10793/catching-unhandled-exceptions-in-aspnet-usercontrols#15999\">your response</a>.. How are you loading your controls and adding them to your controls collection?</p>\n\n<p>That was the whole point of the bit added in the \"Update\" section.. You have the flexibility to use the <em>SafeLoader</em> wherever you please.</p>\n\n<p>I am not sure why you feel you don't have access/control over the Html? The goal of the SafeLoader is that you dont <em>care</em> what the html is, you simply try and \"output\" the control (within the \"bubble\") and determine if it loads OK in its current state.</p>\n\n<p>If it does (i.e. the html is returned) then you can do what you like with it, output the html, add the control to the controls collection, whatever!</p>\n\n<p>If not, then again, you can do what you like, render an error message, throw a custom exception.. The choice is yours!</p>\n\n<p>I hope this helps clarify things for you, if not, then please shout :)</p>\n"
},
{
"answer_id": 10954250,
"author": "ThisGuy",
"author_id": 910348,
"author_profile": "https://Stackoverflow.com/users/910348",
"pm_score": 0,
"selected": false,
"text": "<p>I used @Keith's approach, but the problem is that the control is rendered up until the Exception is thrown, potentially resulting in open HTML tags. I'm also rendering the exception information in the Control if in Debug mode.</p>\n\n<pre><code> protected override void Render(System.Web.UI.HtmlTextWriter writer)\n {\n try\n {\n // Render the module to a local a temporary writer so that if an Exception occurs\n // the control is not halfway rendered - \"it is all or nothing\" proposition\n System.IO.StringWriter sw = new System.IO.StringWriter();\n System.Web.UI.HtmlTextWriter htw = new System.Web.UI.HtmlTextWriter(sw);\n base.Render(htw);\n\n // We made it! Copy the Control Render over\n writer.Write(sw.GetStringBuilder().ToString());\n }\n catch (System.Exception ex)\n {\n string message = string.Format(\"Error Rendering Control {0}\\n\", ID);\n Log.Error(message, ex);\n if (Page.IsDebug)\n writer.Write(string.Format(\"{0}<br>Exception:<br><pre>{1}\\n{2}</pre>\", message, ex.Message, ex.StackTrace));\n }\n }\n</code></pre>\n"
}
] | 2008/08/14 | [
"https://Stackoverflow.com/questions/10793",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1269/"
] | I'm dynamically loading user controls adding them to the Controls collection of the web form.
I'd like to hide user controls if they cause a unhandled exception while rendering.
So, I tried hooking to the Error event of each UserControl but it seems that this event never fires for the UserControls as it does for Page class.
Did some googling around and it doesn't seem promising. Any ideas here? | mmilic, following on from [your response](https://stackoverflow.com/questions/10793/catching-unhandled-exceptions-in-aspnet-usercontrols#10910) to my [previous idea](https://stackoverflow.com/questions/10793/catching-unhandled-exceptions-in-aspnet-usercontrols#10815)..
No additional logic required! That's the point, your doing nothing to the classes in question, just wrapping them in some instantiation bubble-wrap! :)
OK, I was going to just bullet point but I wanted to see this work for myself, so I cobbled together some *very* rough code but the concept is there and it seems to work.
**APOLOGIES FOR THE LONG POST**
The SafeLoader
--------------
This will basically be the "bubble" I mentioned.. It will get the controls HTML, catching any errors that occur during Rendering.
```
public class SafeLoader
{
public static string LoadControl(Control ctl)
{
// In terms of what we could do here, its down
// to you, I will just return some basic HTML saying
// I screwed up.
try
{
// Get the Controls HTML (which may throw)
// And store it in our own writer away from the
// actual Live page.
StringWriter writer = new StringWriter();
HtmlTextWriter htmlWriter = new HtmlTextWriter(writer);
ctl.RenderControl(htmlWriter);
return writer.GetStringBuilder().ToString();
}
catch (Exception)
{
string ctlType = ctl.GetType().Name;
return "<span style=\"color: red; font-weight:bold; font-size: smaller;\">" +
"Rob + Controls = FAIL (" +
ctlType + " rendering failed) Sad face :(</span>";
}
}
}
```
And Some Controls..
-------------------
Ok I just mocked together two controls here, one will throw the other will render junk. Point here, I don't give a crap. These will be replaced with your custom controls..
### BadControl
```
public class BadControl : WebControl
{
protected override void Render(HtmlTextWriter writer)
{
throw new ApplicationException("Rob can't program controls");
}
}
```
### GoodControl
```
public class GoodControl : WebControl
{
protected override void Render(HtmlTextWriter writer)
{
writer.Write("<b>Holy crap this control works</b>");
}
}
```
The Page
--------
OK, so lets look at the "test" page.. Here I simply instantiate the controls, grab their html and output it, I will follow with thoughts on designer support etc..
### Page Code-Behind
```
protected void Page_Load(object sender, EventArgs e)
{
// Create some controls (BadControl will throw)
string goodHtml = SafeLoader.LoadControl(new BadControl());
Response.Write(goodHtml);
string badHtml = SafeLoader.LoadControl(new GoodControl());
Response.Write(badHtml);
}
```
### Thoughts
OK, I know what you are thinking, "these controls are instantiated programatically, what about designer support? I spent freaking hours getting these controls nice for the designer, now you're messing with my mojo".
OK, so I havent really tested this yet (probably will do in a min!) but the idea here is to override the CreateChildControls method for the page, and take the instance of each control added on the form and run it through the SafeLoader. If the code passes, you can add it to the Controls collection as normal, if not, then you can create erroneous literals or something, up to you my friend.
Finally..
---------
Again, sorry for the long post, but I wanted to get the code here so we can discuss this :)
I hope this helps demonstrate my idea :)
Update
------
Tested by chucking a control in on the designer and overriding the CreateChildControls method with this, works fine, may need some clean up to make things better looking, but I'll leave that to you ;)
```
protected override void CreateChildControls()
{
// Pass each control through the Loader to check
// its not lame
foreach (Control ctl in Controls)
{
string s = SafeLoader.LoadControl(ctl);
// If its bad, smack it downnnn!
if (s == string.Empty)
{
ctl.Visible = false; // Prevent Rendering
string ctlType = ctl.GetType().Name;
Response.Write("<b>Problem Occurred Rendering " +
ctlType + " '" + ctl.ID + "'.</b>");
}
}
}
```
Enjoy! |
10,808 | <p>Ok, so I've been refactoring my code in my little Rails app in an effort to remove duplication, and in general make my life easier (as I like an easy life). Part of this refactoring, has been to move code that's common to two of my models to a module that I can include where I need it.</p>
<p>So far, so good. Looks like it's going to work out, but I've just hit a problem that I'm not sure how to get around. The module (which I've called sendable), is just going to be the code that handles faxing, e-mailing, or printing a PDF of the document. So, for example, I have a purchase order, and I have Internal Sales Orders (imaginatively abbreviated to ISO).</p>
<p>The problem I've struck, is that I want some variables initialised (initialized for people who don't spell correctly :P ) after the object is loaded, so I've been using the <strong>after_initialize</strong> hook. No problem... until I start adding some more mixins.</p>
<p>The problem I have, is that I can have an <strong><code>after_initialize</code></strong> in any one of my mixins, so I need to include a <strong>super</strong> call at the start to make sure the other mixin <strong><code>after_initialize</code></strong> calls get called. Which is great, until I end up calling super and I get an error because there is no super to call.</p>
<p>Here's a little example, in case I haven't been confusing enough:</p>
<pre><code>class Iso < ActiveRecord::Base
include Shared::TracksSerialNumberExtension
include Shared::OrderLines
extend Shared::Filtered
include Sendable::Model
validates_presence_of :customer
validates_associated :lines
owned_by :customer
order_lines :despatched # Mixin
tracks_serial_numbers :items # Mixin
sendable :customer # Mixin
attr_accessor :address
def initialize( params = nil )
super
self.created_at ||= Time.now.to_date
end
end
</code></pre>
<p>So, if each one of the mixins have an after_initialize call, with a <strong>super</strong> call, how can I stop that last <strong>super</strong> call from raising the error? How can I test that the super method exists before I call it?</p>
| [
{
"answer_id": 11719,
"author": "Orion Edwards",
"author_id": 234,
"author_profile": "https://Stackoverflow.com/users/234",
"pm_score": 0,
"selected": false,
"text": "<p>Rather than checking if the super method exists, you can just define it</p>\n\n<pre><code>class ActiveRecord::Base\n def after_initialize\n end\nend\n</code></pre>\n\n<p>This works in my testing, and shouldn't break any of your existing code, because all your other classes which define it will just be silently overriding this method anyway</p>\n"
},
{
"answer_id": 11744,
"author": "newtonapple",
"author_id": 1376,
"author_profile": "https://Stackoverflow.com/users/1376",
"pm_score": 2,
"selected": false,
"text": "<p>Have you tried <code>alias_method_chain</code>? You can basically chained up all your <code>after_initialize</code> calls. It acts like a decorator: each new method adds a new layer of functionality and passes the control onto the \"overridden\" method to do the rest. </p>\n"
},
{
"answer_id": 11866,
"author": "James A. Rosen",
"author_id": 1190,
"author_profile": "https://Stackoverflow.com/users/1190",
"pm_score": 2,
"selected": false,
"text": "<p>The including class (the thing that inherits from <code>ActiveRecord::Base</code>, which, in this case is <code>Iso</code>) <em>could</em> define its own <code>after_initialize</code>, so any solution other than <code>alias_method_chain</code> (or other aliasing that saves the original) risks overwriting code. @Orion Edwards' solution is the best I can come up with. There are others, but they are <strong>far</strong> more hackish.</p>\n\n<p><code>alias_method_chain</code> also has the benefit of creating named versions of the after_initialize method, meaning you can customize the call order in those rare cases that it matters. Otherwise, you're at the mercy of whatever order the including class includes the mixins.</p>\n\n<p><em>later</em>:</p>\n\n<p>I've posted a question to the ruby-on-rails-core mailing list about creating default empty implementations of all callbacks. The saving process checks for them all anyway, so I don't see why they shouldn't be there. The only downside is creating extra empty stack frames, but that's pretty cheap on every known implementation.</p>\n"
},
{
"answer_id": 905638,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 2,
"selected": false,
"text": "<p>You can just throw a quick conditional in there:</p>\n\n<pre><code>super if respond_to?('super')\n</code></pre>\n\n<p>and you should be fine - no adding useless methods; nice and clean.</p>\n"
},
{
"answer_id": 3867490,
"author": "valo",
"author_id": 467285,
"author_profile": "https://Stackoverflow.com/users/467285",
"pm_score": 6,
"selected": true,
"text": "<p>You can use this:</p>\n\n<pre><code>super if defined?(super)\n</code></pre>\n\n<p>Here is an example:</p>\n\n<pre><code>class A\nend\n\nclass B < A\n def t\n super if defined?(super)\n puts \"Hi from B\"\n end\nend\n\nB.new.t\n</code></pre>\n"
}
] | 2008/08/14 | [
"https://Stackoverflow.com/questions/10808",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/841/"
] | Ok, so I've been refactoring my code in my little Rails app in an effort to remove duplication, and in general make my life easier (as I like an easy life). Part of this refactoring, has been to move code that's common to two of my models to a module that I can include where I need it.
So far, so good. Looks like it's going to work out, but I've just hit a problem that I'm not sure how to get around. The module (which I've called sendable), is just going to be the code that handles faxing, e-mailing, or printing a PDF of the document. So, for example, I have a purchase order, and I have Internal Sales Orders (imaginatively abbreviated to ISO).
The problem I've struck, is that I want some variables initialised (initialized for people who don't spell correctly :P ) after the object is loaded, so I've been using the **after\_initialize** hook. No problem... until I start adding some more mixins.
The problem I have, is that I can have an **`after_initialize`** in any one of my mixins, so I need to include a **super** call at the start to make sure the other mixin **`after_initialize`** calls get called. Which is great, until I end up calling super and I get an error because there is no super to call.
Here's a little example, in case I haven't been confusing enough:
```
class Iso < ActiveRecord::Base
include Shared::TracksSerialNumberExtension
include Shared::OrderLines
extend Shared::Filtered
include Sendable::Model
validates_presence_of :customer
validates_associated :lines
owned_by :customer
order_lines :despatched # Mixin
tracks_serial_numbers :items # Mixin
sendable :customer # Mixin
attr_accessor :address
def initialize( params = nil )
super
self.created_at ||= Time.now.to_date
end
end
```
So, if each one of the mixins have an after\_initialize call, with a **super** call, how can I stop that last **super** call from raising the error? How can I test that the super method exists before I call it? | You can use this:
```
super if defined?(super)
```
Here is an example:
```
class A
end
class B < A
def t
super if defined?(super)
puts "Hi from B"
end
end
B.new.t
``` |
10,810 | <p>I'm doing a authorization check from a WinForms application with the help of the AzMan authorization provider from Enterprise Library and am receiving the the following error:</p>
<blockquote>
<p>Unable to update the password. The value provided as the current password is incorrect. (Exception from HRESULT: 0x8007052B) (Microsoft.Practices.EnterpriseLibrary.Security.AzMan) </p>
<hr>
<p>Unable to update the password. The value provided as the current password is incorrect. (Exception from HRESULT: 0x8007052B) (Microsoft.Interop.Security.AzRoles) </p>
</blockquote>
<p>The AzMan store is hosted in ADAM on another computer in the same domain. Other computers and users do not have this problem. The user making the call has read access to both ADAM and the AzMan store. The computer running the WinForms app and the computer running ADAM are both on Windows XP SP2.</p>
<p>I've had access problems with AzMan before that I've resolved, but this is a new one... What am I missing?</p>
| [
{
"answer_id": 11719,
"author": "Orion Edwards",
"author_id": 234,
"author_profile": "https://Stackoverflow.com/users/234",
"pm_score": 0,
"selected": false,
"text": "<p>Rather than checking if the super method exists, you can just define it</p>\n\n<pre><code>class ActiveRecord::Base\n def after_initialize\n end\nend\n</code></pre>\n\n<p>This works in my testing, and shouldn't break any of your existing code, because all your other classes which define it will just be silently overriding this method anyway</p>\n"
},
{
"answer_id": 11744,
"author": "newtonapple",
"author_id": 1376,
"author_profile": "https://Stackoverflow.com/users/1376",
"pm_score": 2,
"selected": false,
"text": "<p>Have you tried <code>alias_method_chain</code>? You can basically chained up all your <code>after_initialize</code> calls. It acts like a decorator: each new method adds a new layer of functionality and passes the control onto the \"overridden\" method to do the rest. </p>\n"
},
{
"answer_id": 11866,
"author": "James A. Rosen",
"author_id": 1190,
"author_profile": "https://Stackoverflow.com/users/1190",
"pm_score": 2,
"selected": false,
"text": "<p>The including class (the thing that inherits from <code>ActiveRecord::Base</code>, which, in this case is <code>Iso</code>) <em>could</em> define its own <code>after_initialize</code>, so any solution other than <code>alias_method_chain</code> (or other aliasing that saves the original) risks overwriting code. @Orion Edwards' solution is the best I can come up with. There are others, but they are <strong>far</strong> more hackish.</p>\n\n<p><code>alias_method_chain</code> also has the benefit of creating named versions of the after_initialize method, meaning you can customize the call order in those rare cases that it matters. Otherwise, you're at the mercy of whatever order the including class includes the mixins.</p>\n\n<p><em>later</em>:</p>\n\n<p>I've posted a question to the ruby-on-rails-core mailing list about creating default empty implementations of all callbacks. The saving process checks for them all anyway, so I don't see why they shouldn't be there. The only downside is creating extra empty stack frames, but that's pretty cheap on every known implementation.</p>\n"
},
{
"answer_id": 905638,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 2,
"selected": false,
"text": "<p>You can just throw a quick conditional in there:</p>\n\n<pre><code>super if respond_to?('super')\n</code></pre>\n\n<p>and you should be fine - no adding useless methods; nice and clean.</p>\n"
},
{
"answer_id": 3867490,
"author": "valo",
"author_id": 467285,
"author_profile": "https://Stackoverflow.com/users/467285",
"pm_score": 6,
"selected": true,
"text": "<p>You can use this:</p>\n\n<pre><code>super if defined?(super)\n</code></pre>\n\n<p>Here is an example:</p>\n\n<pre><code>class A\nend\n\nclass B < A\n def t\n super if defined?(super)\n puts \"Hi from B\"\n end\nend\n\nB.new.t\n</code></pre>\n"
}
] | 2008/08/14 | [
"https://Stackoverflow.com/questions/10810",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/966/"
] | I'm doing a authorization check from a WinForms application with the help of the AzMan authorization provider from Enterprise Library and am receiving the the following error:
>
> Unable to update the password. The value provided as the current password is incorrect. (Exception from HRESULT: 0x8007052B) (Microsoft.Practices.EnterpriseLibrary.Security.AzMan)
>
>
>
>
> ---
>
>
> Unable to update the password. The value provided as the current password is incorrect. (Exception from HRESULT: 0x8007052B) (Microsoft.Interop.Security.AzRoles)
>
>
>
The AzMan store is hosted in ADAM on another computer in the same domain. Other computers and users do not have this problem. The user making the call has read access to both ADAM and the AzMan store. The computer running the WinForms app and the computer running ADAM are both on Windows XP SP2.
I've had access problems with AzMan before that I've resolved, but this is a new one... What am I missing? | You can use this:
```
super if defined?(super)
```
Here is an example:
```
class A
end
class B < A
def t
super if defined?(super)
puts "Hi from B"
end
end
B.new.t
``` |
10,819 | <p>For certain types of sql queries, an auxiliary table of numbers can be very useful. It may be created as a table with as many rows as you need for a particular task or as a user defined function that returns the number of rows required in each query.</p>
<p>What is the optimal way to create such a function?</p>
| [
{
"answer_id": 39122,
"author": "mrdenny",
"author_id": 4197,
"author_profile": "https://Stackoverflow.com/users/4197",
"pm_score": 4,
"selected": false,
"text": "<p>The most optimal function would be to use a table instead of a function. Using a function causes extra CPU load to create the values for the data being returned, especially if the values being returned cover a very large range.</p>\n"
},
{
"answer_id": 1479258,
"author": "Chadwick",
"author_id": 80714,
"author_profile": "https://Stackoverflow.com/users/80714",
"pm_score": 3,
"selected": false,
"text": "<p><a href=\"http://web.archive.org/web/20120413120912/http://www.projectdmx.com:80/tsql/tblnumbers.aspx\" rel=\"nofollow noreferrer\">This article</a> gives 14 different possible solutions with discussion of each. The important point is that:</p>\n\n<blockquote>\n <p>suggestions regarding efficiency and\n performance are often subjective.\n Regardless of how a query is being\n used, the physical implementation\n determines the efficiency of a query.\n Therefore, rather than relying on\n biased guidelines, it is imperative\n that you test the query and determine\n which one performs better.</p>\n</blockquote>\n\n<p>I personally liked:</p>\n\n<pre><code>WITH Nbrs ( n ) AS (\n SELECT 1 UNION ALL\n SELECT 1 + n FROM Nbrs WHERE n < 500 )\nSELECT n FROM Nbrs\nOPTION ( MAXRECURSION 500 )\n</code></pre>\n"
},
{
"answer_id": 2663232,
"author": "Jeff Moden",
"author_id": 313265,
"author_profile": "https://Stackoverflow.com/users/313265",
"pm_score": 8,
"selected": true,
"text": "<p>Heh... sorry I'm so late responding to an old post. And, yeah, I had to respond because the most popular answer (at the time, the Recursive CTE answer with the link to 14 different methods) on this thread is, ummm... performance challenged at best.</p>\n\n<p>First, the article with the 14 different solutions is fine for seeing the different methods of creating a Numbers/Tally table on the fly but as pointed out in the article and in the cited thread, there's a <em>very</em> important quote...</p>\n\n<blockquote>\n <p>\"suggestions regarding efficiency and\n performance are often subjective.\n Regardless of how a query is being\n used, the physical implementation\n determines the efficiency of a query.\n Therefore, rather than relying on\n biased guidelines, it is imperative\n that you test the query and determine\n which one performs better.\"</p>\n</blockquote>\n\n<p>Ironically, the article itself contains many subjective statements and \"biased guidelines\" such as <em>\"a recursive CTE can generate a number listing <strong>pretty efficiently</strong>\"</em> and <em>\"This is <strong>an efficient method</strong> of using WHILE loop from a newsgroup posting by Itzik Ben-Gen\"</em> (which I'm sure he posted just for comparison purposes). C'mon folks... Just mentioning Itzik's good name may lead some poor slob into actually using that horrible method. The author should practice what (s)he preaches and should do a little performance testing before making such ridiculously incorrect statements especially in the face of any scalablility.</p>\n\n<p>With the thought of actually doing some testing before making any subjective claims about what any code does or what someone \"likes\", here's some code you can do your own testing with. Setup profiler for the SPID you're running the test from and check it out for yourself... just do a \"Search'n'Replace\" of the number 1000000 for your \"favorite\" number and see...</p>\n\n<pre><code>--===== Test for 1000000 rows ==================================\nGO\n--===== Traditional RECURSIVE CTE method\n WITH Tally (N) AS \n ( \n SELECT 1 UNION ALL \n SELECT 1 + N FROM Tally WHERE N < 1000000 \n ) \n SELECT N \n INTO #Tally1 \n FROM Tally \n OPTION (MAXRECURSION 0);\nGO\n--===== Traditional WHILE LOOP method\n CREATE TABLE #Tally2 (N INT);\n SET NOCOUNT ON;\nDECLARE @Index INT;\n SET @Index = 1;\n WHILE @Index <= 1000000 \n BEGIN \n INSERT #Tally2 (N) \n VALUES (@Index);\n SET @Index = @Index + 1;\n END;\nGO\n--===== Traditional CROSS JOIN table method\n SELECT TOP (1000000)\n ROW_NUMBER() OVER (ORDER BY (SELECT 1)) AS N\n INTO #Tally3\n FROM Master.sys.All_Columns ac1\n CROSS JOIN Master.sys.ALL_Columns ac2;\nGO\n--===== Itzik's CROSS JOINED CTE method\n WITH E00(N) AS (SELECT 1 UNION ALL SELECT 1),\n E02(N) AS (SELECT 1 FROM E00 a, E00 b),\n E04(N) AS (SELECT 1 FROM E02 a, E02 b),\n E08(N) AS (SELECT 1 FROM E04 a, E04 b),\n E16(N) AS (SELECT 1 FROM E08 a, E08 b),\n E32(N) AS (SELECT 1 FROM E16 a, E16 b),\n cteTally(N) AS (SELECT ROW_NUMBER() OVER (ORDER BY N) FROM E32)\n SELECT N\n INTO #Tally4\n FROM cteTally\n WHERE N <= 1000000;\nGO\n--===== Housekeeping\n DROP TABLE #Tally1, #Tally2, #Tally3, #Tally4;\nGO\n</code></pre>\n\n<p>While we're at it, here's the numbers I get from SQL Profiler for the values of 100, 1000, 10000, 100000, and 1000000...</p>\n\n<pre><code>SPID TextData Dur(ms) CPU Reads Writes\n---- ---------------------------------------- ------- ----- ------- ------\n 51 --===== Test for 100 rows ============== 8 0 0 0\n 51 --===== Traditional RECURSIVE CTE method 16 0 868 0\n 51 --===== Traditional WHILE LOOP method CR 73 16 175 2\n 51 --===== Traditional CROSS JOIN table met 11 0 80 0\n 51 --===== Itzik's CROSS JOINED CTE method 6 0 63 0\n 51 --===== Housekeeping DROP TABLE #Tally 35 31 401 0\n\n 51 --===== Test for 1000 rows ============= 0 0 0 0\n 51 --===== Traditional RECURSIVE CTE method 47 47 8074 0\n 51 --===== Traditional WHILE LOOP method CR 80 78 1085 0\n 51 --===== Traditional CROSS JOIN table met 5 0 98 0\n 51 --===== Itzik's CROSS JOINED CTE method 2 0 83 0\n 51 --===== Housekeeping DROP TABLE #Tally 6 15 426 0\n\n 51 --===== Test for 10000 rows ============ 0 0 0 0\n 51 --===== Traditional RECURSIVE CTE method 434 344 80230 10\n 51 --===== Traditional WHILE LOOP method CR 671 563 10240 9\n 51 --===== Traditional CROSS JOIN table met 25 31 302 15\n 51 --===== Itzik's CROSS JOINED CTE method 24 0 192 15\n 51 --===== Housekeeping DROP TABLE #Tally 7 15 531 0\n\n 51 --===== Test for 100000 rows =========== 0 0 0 0\n 51 --===== Traditional RECURSIVE CTE method 4143 3813 800260 154\n 51 --===== Traditional WHILE LOOP method CR 5820 5547 101380 161\n 51 --===== Traditional CROSS JOIN table met 160 140 479 211\n 51 --===== Itzik's CROSS JOINED CTE method 153 141 276 204\n 51 --===== Housekeeping DROP TABLE #Tally 10 15 761 0\n\n 51 --===== Test for 1000000 rows ========== 0 0 0 0\n 51 --===== Traditional RECURSIVE CTE method 41349 37437 8001048 1601\n 51 --===== Traditional WHILE LOOP method CR 59138 56141 1012785 1682\n 51 --===== Traditional CROSS JOIN table met 1224 1219 2429 2101\n 51 --===== Itzik's CROSS JOINED CTE method 1448 1328 1217 2095\n 51 --===== Housekeeping DROP TABLE #Tally 8 0 415 0\n</code></pre>\n\n<p>As you can see, <strong>the Recursive CTE method is the second worst only to the While Loop for Duration and CPU and has 8 times the memory pressure in the form of logical reads than the While Loop</strong>. It's RBAR on steroids and should be avoided, at all cost, for any single row calculations just as a While Loop should be avoided. <strong>There are places where recursion is quite valuable but this ISN'T one of them</strong>.</p>\n\n<p>As a side bar, Mr. Denny is absolutely spot on... a correctly sized permanent Numbers or Tally table is the way to go for most things. What does correctly sized mean? Well, most people use a Tally table to generate dates or to do splits on VARCHAR(8000). If you create an 11,000 row Tally table with the correct clustered index on \"N\", you'll have enough rows to create more than 30 years worth of dates (I work with mortgages a fair bit so 30 years is a key number for me) and certainly enough to handle a VARCHAR(8000) split. Why is \"right sizing\" so important? If the Tally table is used a lot, it easily fits in cache which makes it blazingly fast without much pressure on memory at all.</p>\n\n<p>Last but not least, every one knows that if you create a permanent Tally table, it doesn't much matter which method you use to build it because 1) it's only going to be made once and 2) if it's something like an 11,000 row table, all of the methods are going to run \"good enough\". <strong>So why all the indigination on my part about which method to use???</strong></p>\n\n<p>The answer is that some poor guy/gal who doesn't know any better and just needs to get his or her job done might see something like the Recursive CTE method and decide to use it for something much larger and much more frequently used than building a permanent Tally table and I'm trying to <strong>protect those people, the servers their code runs on, and the company that owns the data on those servers</strong>. Yeah... it's that big a deal. It should be for everyone else, as well. Teach the right way to do things instead of \"good enough\". Do some testing before posting or using something from a post or book... the life you save may, in fact, be your own especially if you think a recursive CTE is the way to go for something like this. ;-)</p>\n\n<p>Thanks for listening...</p>\n"
},
{
"answer_id": 4745368,
"author": "Ruskin",
"author_id": 581414,
"author_profile": "https://Stackoverflow.com/users/581414",
"pm_score": 0,
"selected": false,
"text": "<p>edit: see Conrad's comment below.</p>\n\n<p>Jeff Moden's answer is great ... but I find on Postgres that the Itzik method fails unless you remove the E32 row.</p>\n\n<p>Slightly faster on postgres (40ms vs 100ms) is another method I found on <a href=\"http://www.sqlservercentral.com/articles/T-SQL/67899/\" rel=\"nofollow\">here</a> adapted for postgres:</p>\n\n<pre><code>WITH \n E00 (N) AS ( \n SELECT 1 UNION ALL SELECT 1 UNION ALL SELECT 1 UNION ALL SELECT 1 UNION ALL SELECT 1 UNION ALL \n SELECT 1 UNION ALL SELECT 1 UNION ALL SELECT 1 UNION ALL SELECT 1 UNION ALL SELECT 1 ),\n E01 (N) AS (SELECT a.N FROM E00 a CROSS JOIN E00 b),\n E02 (N) AS (SELECT a.N FROM E01 a CROSS JOIN E01 b ),\n E03 (N) AS (SELECT a.N FROM E02 a CROSS JOIN E02 b \n LIMIT 11000 -- end record 11,000 good for 30 yrs dates\n ), -- max is 100,000,000, starts slowing e.g. 1 million 1.5 secs, 2 mil 2.5 secs, 3 mill 4 secs\n Tally (N) as (SELECT row_number() OVER (ORDER BY a.N) FROM E03 a)\n\nSELECT N\nFROM Tally\n</code></pre>\n\n<p>As I am moving from SQL Server to Postgres world, may have missed a better way to do tally tables on that platform ... INTEGER()? SEQUENCE()?</p>\n"
},
{
"answer_id": 6571438,
"author": "Anthony Faull",
"author_id": 63264,
"author_profile": "https://Stackoverflow.com/users/63264",
"pm_score": 2,
"selected": false,
"text": "<p>This view is super fast and contains all positive <code>int</code> values.</p>\n\n<pre><code>CREATE VIEW dbo.Numbers\nWITH SCHEMABINDING\nAS\n WITH Int1(z) AS (SELECT 0 UNION ALL SELECT 0)\n , Int2(z) AS (SELECT 0 FROM Int1 a CROSS JOIN Int1 b)\n , Int4(z) AS (SELECT 0 FROM Int2 a CROSS JOIN Int2 b)\n , Int8(z) AS (SELECT 0 FROM Int4 a CROSS JOIN Int4 b)\n , Int16(z) AS (SELECT 0 FROM Int8 a CROSS JOIN Int8 b)\n , Int32(z) AS (SELECT TOP 2147483647 0 FROM Int16 a CROSS JOIN Int16 b)\n SELECT ROW_NUMBER() OVER (ORDER BY z) AS n\n FROM Int32\nGO\n</code></pre>\n"
},
{
"answer_id": 26505041,
"author": "HansLindgren",
"author_id": 1202332,
"author_profile": "https://Stackoverflow.com/users/1202332",
"pm_score": 0,
"selected": false,
"text": "<p>Still much later, I'd like to contribute a slightly different 'traditional' CTE (does not touch base tables to get the volume of rows):</p>\n\n<pre><code>--===== Hans CROSS JOINED CTE method\nWITH Numbers_CTE (Digit)\nAS\n(SELECT 0 UNION ALL SELECT 1 UNION ALL SELECT 2 UNION ALL SELECT 3 UNION ALL SELECT 4 UNION ALL SELECT 5 UNION ALL SELECT 6 UNION ALL SELECT 7 UNION ALL SELECT 8 UNION ALL SELECT 9)\nSELECT HundredThousand.Digit * 100000 + TenThousand.Digit * 10000 + Thousand.Digit * 1000 + Hundred.Digit * 100 + Ten.Digit * 10 + One.Digit AS Number\nINTO #Tally5\nFROM Numbers_CTE AS One CROSS JOIN Numbers_CTE AS Ten CROSS JOIN Numbers_CTE AS Hundred CROSS JOIN Numbers_CTE AS Thousand CROSS JOIN Numbers_CTE AS TenThousand CROSS JOIN Numbers_CTE AS HundredThousand\n</code></pre>\n\n<p>This CTE performs more READs then Itzik's CTE but less then the Traditional CTE.\n<strong>However, it consistently performs less WRITES then the other queries.</strong>\nAs you know, Writes are consistently quite much more expensive then Reads.</p>\n\n<p>The duration depends heavily on the number of cores (MAXDOP) but, on my 8core, performs consistently quicker (less duration in ms) then the other queries.</p>\n\n<p>I am using:</p>\n\n<pre><code>Microsoft SQL Server 2012 - 11.0.5058.0 (X64) \nMay 14 2014 18:34:29 \nCopyright (c) Microsoft Corporation\nEnterprise Edition (64-bit) on Windows NT 6.3 <X64> (Build 9600: )\n</code></pre>\n\n<p>on Windows Server 2012 R2, 32 GB, Xeon X3450 @2.67Ghz, 4 cores HT enabled.</p>\n"
},
{
"answer_id": 36987175,
"author": "Lukasz Szozda",
"author_id": 5070879,
"author_profile": "https://Stackoverflow.com/users/5070879",
"pm_score": 1,
"selected": false,
"text": "<p>Using <code>SQL Server 2016+</code> to generate numbers table you could use <code>OPENJSON</code> :</p>\n\n<pre><code>-- range from 0 to @max - 1\nDECLARE @max INT = 40000;\n\nSELECT rn = CAST([key] AS INT) \nFROM OPENJSON(CONCAT('[1', REPLICATE(CAST(',1' AS VARCHAR(MAX)),@max-1),']'));\n</code></pre>\n\n<p><kbd><strong><a href=\"https://data.stackexchange.com/stackoverflow/query/481961\" rel=\"nofollow\"><code>LiveDemo</code></a></strong></kbd></p>\n\n<p><hr>\nIdea taken from <a href=\"https://blogs.msdn.microsoft.com/sqlserverstorageengine/2015/11/03/generate-serie-of-numbers-in-sql-server-2016-using-openjson/\" rel=\"nofollow\">How can we use OPENJSON to generate series of numbers?</a></p>\n"
},
{
"answer_id": 71426969,
"author": "Martin Smith",
"author_id": 73226,
"author_profile": "https://Stackoverflow.com/users/73226",
"pm_score": 2,
"selected": false,
"text": "<p>From SQL Server 2022 <a href=\"https://learn.microsoft.com/en-us/sql/t-sql/functions/generate-series-transact-sql\" rel=\"nofollow noreferrer\">you will be able to do</a></p>\n<pre><code>SELECT Value\nFROM GENERATE_SERIES(START = 1, STOP = 100, STEP=1)\n</code></pre>\n<p>In the public preview of SQL Server 2022 (CTP2.0) there are some very promising elements and other less so. Hopefully the negative aspects can be addressed before the actual release.</p>\n<p>✅ <strong>Execution time for number generation</strong>\nThe below generates 10,000,000 numbers in 700 ms in my test VM (the assigning to a variable removes any overhead from sending results to the client)</p>\n<pre><code>DECLARE @Value INT \n\nSELECT @Value =[value]\nFROM GENERATE_SERIES(START=1, STOP=10000000)\n</code></pre>\n<p>✅ <strong>Cardinality estimates</strong></p>\n<p>It is simple to calculate how many numbers will be returned from the operator and SQL Server takes advantage of this as shown below.</p>\n<p><a href=\"https://i.stack.imgur.com/k9IOk.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/k9IOk.png\" alt=\"enter image description here\" /></a></p>\n<p>❌ <strong>Unnecessary <a href=\"https://en.wikipedia.org/wiki/Halloween_Problem\" rel=\"nofollow noreferrer\">Halloween Protection</a></strong></p>\n<p>The plan for the below insert has a completely unnecessary spool - presumably as SQL Server does not currently have logic to determine the source of the rows is not potentially the destination.</p>\n<pre><code>CREATE TABLE dbo.NumberHeap(Number INT);\n\nINSERT INTO dbo.Numbers\nSELECT [value]\nFROM GENERATE_SERIES(START=1, STOP=10);\n</code></pre>\n<p>When inserting into a table with a clustered index on Number the spool may be replaced by a sort instead (that also provides the phase separation)</p>\n<p><a href=\"https://i.stack.imgur.com/wsj5n.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/wsj5n.png\" alt=\"enter image description here\" /></a></p>\n<p>❌ <strong>Unnecessary sorts</strong></p>\n<p>The below will return the rows in order anyway but SQL Server apparently does not yet have the properties set to guarantee this and take advantage of it in the execution plan.</p>\n<pre><code>SELECT [value]\nFROM GENERATE_SERIES(START=1, STOP=10)\nORDER BY [value] \n</code></pre>\n<p><a href=\"https://i.stack.imgur.com/WWQ0O.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/WWQ0O.png\" alt=\"enter image description here\" /></a></p>\n<p>RE: This last point <a href=\"https://www.mssqltips.com/sqlservertip/7265/sql-server-2022-t-sql-enhancements/\" rel=\"nofollow noreferrer\">Aaron Bertrand indicates</a> that this is not a box currently ticked but that this may be forthcoming.</p>\n"
}
] | 2008/08/14 | [
"https://Stackoverflow.com/questions/10819",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/224/"
] | For certain types of sql queries, an auxiliary table of numbers can be very useful. It may be created as a table with as many rows as you need for a particular task or as a user defined function that returns the number of rows required in each query.
What is the optimal way to create such a function? | Heh... sorry I'm so late responding to an old post. And, yeah, I had to respond because the most popular answer (at the time, the Recursive CTE answer with the link to 14 different methods) on this thread is, ummm... performance challenged at best.
First, the article with the 14 different solutions is fine for seeing the different methods of creating a Numbers/Tally table on the fly but as pointed out in the article and in the cited thread, there's a *very* important quote...
>
> "suggestions regarding efficiency and
> performance are often subjective.
> Regardless of how a query is being
> used, the physical implementation
> determines the efficiency of a query.
> Therefore, rather than relying on
> biased guidelines, it is imperative
> that you test the query and determine
> which one performs better."
>
>
>
Ironically, the article itself contains many subjective statements and "biased guidelines" such as *"a recursive CTE can generate a number listing **pretty efficiently**"* and *"This is **an efficient method** of using WHILE loop from a newsgroup posting by Itzik Ben-Gen"* (which I'm sure he posted just for comparison purposes). C'mon folks... Just mentioning Itzik's good name may lead some poor slob into actually using that horrible method. The author should practice what (s)he preaches and should do a little performance testing before making such ridiculously incorrect statements especially in the face of any scalablility.
With the thought of actually doing some testing before making any subjective claims about what any code does or what someone "likes", here's some code you can do your own testing with. Setup profiler for the SPID you're running the test from and check it out for yourself... just do a "Search'n'Replace" of the number 1000000 for your "favorite" number and see...
```
--===== Test for 1000000 rows ==================================
GO
--===== Traditional RECURSIVE CTE method
WITH Tally (N) AS
(
SELECT 1 UNION ALL
SELECT 1 + N FROM Tally WHERE N < 1000000
)
SELECT N
INTO #Tally1
FROM Tally
OPTION (MAXRECURSION 0);
GO
--===== Traditional WHILE LOOP method
CREATE TABLE #Tally2 (N INT);
SET NOCOUNT ON;
DECLARE @Index INT;
SET @Index = 1;
WHILE @Index <= 1000000
BEGIN
INSERT #Tally2 (N)
VALUES (@Index);
SET @Index = @Index + 1;
END;
GO
--===== Traditional CROSS JOIN table method
SELECT TOP (1000000)
ROW_NUMBER() OVER (ORDER BY (SELECT 1)) AS N
INTO #Tally3
FROM Master.sys.All_Columns ac1
CROSS JOIN Master.sys.ALL_Columns ac2;
GO
--===== Itzik's CROSS JOINED CTE method
WITH E00(N) AS (SELECT 1 UNION ALL SELECT 1),
E02(N) AS (SELECT 1 FROM E00 a, E00 b),
E04(N) AS (SELECT 1 FROM E02 a, E02 b),
E08(N) AS (SELECT 1 FROM E04 a, E04 b),
E16(N) AS (SELECT 1 FROM E08 a, E08 b),
E32(N) AS (SELECT 1 FROM E16 a, E16 b),
cteTally(N) AS (SELECT ROW_NUMBER() OVER (ORDER BY N) FROM E32)
SELECT N
INTO #Tally4
FROM cteTally
WHERE N <= 1000000;
GO
--===== Housekeeping
DROP TABLE #Tally1, #Tally2, #Tally3, #Tally4;
GO
```
While we're at it, here's the numbers I get from SQL Profiler for the values of 100, 1000, 10000, 100000, and 1000000...
```
SPID TextData Dur(ms) CPU Reads Writes
---- ---------------------------------------- ------- ----- ------- ------
51 --===== Test for 100 rows ============== 8 0 0 0
51 --===== Traditional RECURSIVE CTE method 16 0 868 0
51 --===== Traditional WHILE LOOP method CR 73 16 175 2
51 --===== Traditional CROSS JOIN table met 11 0 80 0
51 --===== Itzik's CROSS JOINED CTE method 6 0 63 0
51 --===== Housekeeping DROP TABLE #Tally 35 31 401 0
51 --===== Test for 1000 rows ============= 0 0 0 0
51 --===== Traditional RECURSIVE CTE method 47 47 8074 0
51 --===== Traditional WHILE LOOP method CR 80 78 1085 0
51 --===== Traditional CROSS JOIN table met 5 0 98 0
51 --===== Itzik's CROSS JOINED CTE method 2 0 83 0
51 --===== Housekeeping DROP TABLE #Tally 6 15 426 0
51 --===== Test for 10000 rows ============ 0 0 0 0
51 --===== Traditional RECURSIVE CTE method 434 344 80230 10
51 --===== Traditional WHILE LOOP method CR 671 563 10240 9
51 --===== Traditional CROSS JOIN table met 25 31 302 15
51 --===== Itzik's CROSS JOINED CTE method 24 0 192 15
51 --===== Housekeeping DROP TABLE #Tally 7 15 531 0
51 --===== Test for 100000 rows =========== 0 0 0 0
51 --===== Traditional RECURSIVE CTE method 4143 3813 800260 154
51 --===== Traditional WHILE LOOP method CR 5820 5547 101380 161
51 --===== Traditional CROSS JOIN table met 160 140 479 211
51 --===== Itzik's CROSS JOINED CTE method 153 141 276 204
51 --===== Housekeeping DROP TABLE #Tally 10 15 761 0
51 --===== Test for 1000000 rows ========== 0 0 0 0
51 --===== Traditional RECURSIVE CTE method 41349 37437 8001048 1601
51 --===== Traditional WHILE LOOP method CR 59138 56141 1012785 1682
51 --===== Traditional CROSS JOIN table met 1224 1219 2429 2101
51 --===== Itzik's CROSS JOINED CTE method 1448 1328 1217 2095
51 --===== Housekeeping DROP TABLE #Tally 8 0 415 0
```
As you can see, **the Recursive CTE method is the second worst only to the While Loop for Duration and CPU and has 8 times the memory pressure in the form of logical reads than the While Loop**. It's RBAR on steroids and should be avoided, at all cost, for any single row calculations just as a While Loop should be avoided. **There are places where recursion is quite valuable but this ISN'T one of them**.
As a side bar, Mr. Denny is absolutely spot on... a correctly sized permanent Numbers or Tally table is the way to go for most things. What does correctly sized mean? Well, most people use a Tally table to generate dates or to do splits on VARCHAR(8000). If you create an 11,000 row Tally table with the correct clustered index on "N", you'll have enough rows to create more than 30 years worth of dates (I work with mortgages a fair bit so 30 years is a key number for me) and certainly enough to handle a VARCHAR(8000) split. Why is "right sizing" so important? If the Tally table is used a lot, it easily fits in cache which makes it blazingly fast without much pressure on memory at all.
Last but not least, every one knows that if you create a permanent Tally table, it doesn't much matter which method you use to build it because 1) it's only going to be made once and 2) if it's something like an 11,000 row table, all of the methods are going to run "good enough". **So why all the indigination on my part about which method to use???**
The answer is that some poor guy/gal who doesn't know any better and just needs to get his or her job done might see something like the Recursive CTE method and decide to use it for something much larger and much more frequently used than building a permanent Tally table and I'm trying to **protect those people, the servers their code runs on, and the company that owns the data on those servers**. Yeah... it's that big a deal. It should be for everyone else, as well. Teach the right way to do things instead of "good enough". Do some testing before posting or using something from a post or book... the life you save may, in fact, be your own especially if you think a recursive CTE is the way to go for something like this. ;-)
Thanks for listening... |
10,822 | <p>What would be a very fast way to determine if your connectionstring lets you connect to a database?</p>
<p>Normally a connection attempt keeps the user waiting a long time before notifying the attempt was futile anyway.</p>
| [
{
"answer_id": 10823,
"author": "Keith",
"author_id": 905,
"author_profile": "https://Stackoverflow.com/users/905",
"pm_score": 2,
"selected": false,
"text": "<p>Shorten the timeout on the connection string and execute something trivial.</p>\n\n<p>The wait should be about the same as the timeout.</p>\n\n<p>You would still need a second or two though.</p>\n"
},
{
"answer_id": 10824,
"author": "GateKiller",
"author_id": 383,
"author_profile": "https://Stackoverflow.com/users/383",
"pm_score": 5,
"selected": true,
"text": "<p>You haven't mentioned what database you are connecting to, however. In <a href=\"http://en.wikipedia.org/wiki/Microsoft_SQL_Server#SQL_Server_2005\" rel=\"nofollow noreferrer\">SQL Server 2005</a>, from .NET, you can specify a connection timeout in your connection string like so:</p>\n\n<pre><code>server=<server>;database=<database>;uid=<user>;password=<password>;Connect Timeout=3\n</code></pre>\n\n<p>This will try to connect to the server and if it doesn't do so in three seconds, it will throw a timeout error.</p>\n"
}
] | 2008/08/14 | [
"https://Stackoverflow.com/questions/10822",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1271/"
] | What would be a very fast way to determine if your connectionstring lets you connect to a database?
Normally a connection attempt keeps the user waiting a long time before notifying the attempt was futile anyway. | You haven't mentioned what database you are connecting to, however. In [SQL Server 2005](http://en.wikipedia.org/wiki/Microsoft_SQL_Server#SQL_Server_2005), from .NET, you can specify a connection timeout in your connection string like so:
```
server=<server>;database=<database>;uid=<user>;password=<password>;Connect Timeout=3
```
This will try to connect to the server and if it doesn't do so in three seconds, it will throw a timeout error. |
10,825 | <p>In SQL Server I have a <code>DATETIME</code> column which includes a time element.</p>
<p>Example: </p>
<pre><code>'14 AUG 2008 14:23:019'
</code></pre>
<p>What is the <strong>best</strong> method to only select the records for a particular day, ignoring the time part?</p>
<p>Example: (Not safe, as it does not match the time part and returns no rows)</p>
<pre><code>DECLARE @p_date DATETIME
SET @p_date = CONVERT( DATETIME, '14 AUG 2008', 106 )
SELECT *
FROM table1
WHERE column_datetime = @p_date
</code></pre>
<p><em>Note: Given this site is also about jotting down notes and techniques you pick up and then forget, I'm going to post my own answer to this question as DATETIME stuff in MSSQL is probably the topic I lookup most in SQLBOL.</em></p>
<hr>
<p><strong>Update</strong> Clarified example to be more specific.</p>
<hr>
<p><strong>Edit</strong> Sorry, But I've had to down-mod WRONG answers (answers that return wrong results).</p>
<p>@Jorrit: <code>WHERE (date>'20080813' AND date<'20080815')</code> will return the 13th and the 14th.</p>
<p>@wearejimbo: <em>Close, but no cigar!</em> badge awarded to you. You missed out records written at 14/08/2008 23:59:001 to 23:59:999 (i.e. Less than 1 second before midnight.)</p>
| [
{
"answer_id": 10826,
"author": "Guy",
"author_id": 993,
"author_profile": "https://Stackoverflow.com/users/993",
"pm_score": 6,
"selected": true,
"text": "<p>Technique 1:</p>\n\n<pre><code> DECLARE @p_date DATETIME\n SET @p_date = CONVERT( DATETIME, '14 AUG 2008', 106 )\n\n SELECT *\n FROM table1\n WHERE column_datetime >= @p_date\n AND column_datetime < DATEADD(d, 1, @p_date)\n</code></pre>\n\n<p>The advantage of this is that it will use any index on 'column_datetime' if it exists.</p>\n"
},
{
"answer_id": 10828,
"author": "Lars Mæhlum",
"author_id": 960,
"author_profile": "https://Stackoverflow.com/users/960",
"pm_score": 1,
"selected": false,
"text": "<pre><code>SELECT *\nFROM table1\nWHERE CONVERT(varchar(10),columnDatetime,121) = \n CONVERT(varchar(10),CONVERT('14 AUG 2008' ,smalldatetime),121)\n</code></pre>\n\n<p>This will convert the datatime and the string into varchars of the format \"YYYY-MM-DD\".</p>\n\n<p>This is very ugly, but should work</p>\n"
},
{
"answer_id": 10830,
"author": "Guy",
"author_id": 993,
"author_profile": "https://Stackoverflow.com/users/993",
"pm_score": 2,
"selected": false,
"text": "<p>Technique 2:</p>\n\n<pre><code>DECLARE @p_date DATETIME\nSET @p_date = CONVERT( DATETIME, '14 AUG 2008', 106 )\n\nSELECT *\nFROM table1\nWHERE DATEDIFF( d, column_datetime, @p_date ) = 0\n</code></pre>\n\n<p>If the column_datetime field is not indexed, and is unlikely to be (or the index is unlikely to be used) then using DATEDIFF() is shorter.</p>\n"
},
{
"answer_id": 10832,
"author": "Yaakov Ellis",
"author_id": 51,
"author_profile": "https://Stackoverflow.com/users/51",
"pm_score": 3,
"selected": false,
"text": "<p>Just compare the year, month and day values.</p>\n\n<pre><code>Declare @DateToSearch DateTime\nSet @DateToSearch = '14 AUG 2008'\n\nSELECT * \nFROM table1\nWHERE Year(column_datetime) = Year(@DateToSearch)\n AND Month(column_datetime) = Month(@DateToSearch)\n AND Day(column_datetime) = Day(@DateToSearch)\n</code></pre>\n"
},
{
"answer_id": 10833,
"author": "GateKiller",
"author_id": 383,
"author_profile": "https://Stackoverflow.com/users/383",
"pm_score": 2,
"selected": false,
"text": "<p>This function <strong>Cast(Floor(Cast(GetDate() As Float)) As DateTime)</strong> returns a datetime datatype with the time portion removed and could be used as so.</p>\n\n<pre><code>Select\n*\nTable1\nWhere\nCast(Floor(Cast(Column_DateTime As Float)) As DateTime) = '14-AUG-2008'\n</code></pre>\n\n<p>or</p>\n\n<pre><code>DECLARE @p_date DATETIME\nSET @p_date = Cast('14 AUG 2008' as DateTime)\n\nSELECT *\nFROM table1\nWHERE Cast(Floor(Cast(column_datetime As Float)) As DateTime) = @p_date\n</code></pre>\n"
},
{
"answer_id": 10834,
"author": "Jon Limjap",
"author_id": 372,
"author_profile": "https://Stackoverflow.com/users/372",
"pm_score": 1,
"selected": false,
"text": "<p>I know this isn't exactly how you want to do this, but it could be a start:</p>\n\n<pre><code>SELECT *\nFROM (SELECT *, DATEPART(yy, column_dateTime) as Year, \n DATEPART(mm, column_dateTime) as Month, \n DATEPART(dd, column_dateTime) as Day \n FROM table1)\nWHERE Year = '2008'\nAND Month = '8'\nAND Day = '14'\n</code></pre>\n"
},
{
"answer_id": 10835,
"author": "ila",
"author_id": 1178,
"author_profile": "https://Stackoverflow.com/users/1178",
"pm_score": 2,
"selected": false,
"text": "<p>Something like this?</p>\n\n<pre><code>SELECT *\nFROM table1\nWHERE convert(varchar, column_datetime, 111) = '2008/08/14'\n</code></pre>\n"
},
{
"answer_id": 10844,
"author": "vzczc",
"author_id": 224,
"author_profile": "https://Stackoverflow.com/users/224",
"pm_score": 4,
"selected": false,
"text": "<p>In SQL Server 2008, you could use the new DATE datatype</p>\n\n<pre><code>DECLARE @pDate DATE='2008-08-14' \n\nSELECT colA, colB\nFROM table1\nWHERE convert(date, colDateTime) = @pDate \n</code></pre>\n\n<p>@Guy. I think you will find that this solution scales just fine. Have a look at the <a href=\"http://cid-936d87e62ae20947.skydrive.live.com/self.aspx/vzczcPublic/Stackoverflow10825Query1.JPG\" rel=\"noreferrer\">query execution plan</a> of your original query.</p>\n\n<p>And for <a href=\"http://cid-936d87e62ae20947.skydrive.live.com/self.aspx/vzczcPublic/Stackoverflow10825Query2.JPG\" rel=\"noreferrer\">mine</a>:</p>\n"
},
{
"answer_id": 14581,
"author": "Guy",
"author_id": 993,
"author_profile": "https://Stackoverflow.com/users/993",
"pm_score": 2,
"selected": false,
"text": "<p><strong>How to get the DATE portion of a DATETIME field in MS SQL Server:</strong></p>\n\n<p>One of the quickest and neatest ways to do this is using</p>\n\n<pre><code>DATEADD(dd, DATEDIFF( dd, 0, @DAY ), 0)\n</code></pre>\n\n<p>It avoids the CPU busting \"convert the date into a string without the time and then converting it back again\" logic.</p>\n\n<p>It also does not expose the internal implementation that the \"time portion is expressed as a fraction\" of the date.</p>\n\n<p><strong>Get the date of the first day of the month</strong></p>\n\n<pre><code>DATEADD(dd, DATEDIFF( dd, -1, GetDate() - DAY(GetDate()) ), 0)\n</code></pre>\n\n<p><strong>Get the date rfom 1 year ago</strong></p>\n\n<pre><code>DATEADD(m,-12,DATEADD(dd, DATEDIFF( dd, -1, GetDate() - DAY(GetDate()) ), 0))\n</code></pre>\n"
},
{
"answer_id": 2271064,
"author": "Jai",
"author_id": 274113,
"author_profile": "https://Stackoverflow.com/users/274113",
"pm_score": 0,
"selected": false,
"text": "<pre><code>SELECT CONVERT(VARCHAR(2),DATEPART(\"dd\",doj)) + \n '/' + CONVERT(VARCHAR(2),DATEPART(\"mm\",doj)) + \n '/' + CONVERT(VARCHAR(4),DATEPART(\"yy\",doj)) FROM emp\n</code></pre>\n"
},
{
"answer_id": 2271172,
"author": "Jai",
"author_id": 274113,
"author_profile": "https://Stackoverflow.com/users/274113",
"pm_score": 1,
"selected": false,
"text": "<pre><code>DECLARE @Dat\n\nSELECT * \nFROM Jai\nWHERE \nCONVERT(VARCHAR(2),DATEPART(\"dd\",Date)) +'/'+ \n CONVERT(VARCHAR(2),DATEPART(\"mm\",Date)) +'/'+ \n CONVERT(VARCHAR(4), DATEPART(\"yy\",Date)) = @Dat\n</code></pre>\n"
},
{
"answer_id": 2271336,
"author": "van",
"author_id": 99594,
"author_profile": "https://Stackoverflow.com/users/99594",
"pm_score": 2,
"selected": false,
"text": "<p>Good point about the index in the answer you accepted. </p>\n\n<p>Still, if you really search only on specific <code>DATE</code> or <code>DATE ranges</code> <strong>often</strong>, then the best solution I found is to add another persisted computed column to your table which would only contain the <code>DATE</code>, and add index on this column:</p>\n\n<pre><code>ALTER TABLE \"table1\" \n ADD \"column_date\" AS CONVERT(DATE, \"column_datetime\") PERSISTED\n</code></pre>\n\n<p>Add index on that column:</p>\n\n<pre><code>CREATE NONCLUSTERED INDEX \"table1_column_date_nu_nci\"\nON \"table1\" ( \"column_date\" ASC )\nGO\n</code></pre>\n\n<p>Then your search will be even faster:</p>\n\n<pre><code>DECLARE @p_date DATE\nSET @p_date = CONVERT( DATE, '14 AUG 2008', 106 )\n\nSELECT *\nFROM table1\nWHERE column_date = @p_date\n</code></pre>\n"
},
{
"answer_id": 2570952,
"author": "javad",
"author_id": 308248,
"author_profile": "https://Stackoverflow.com/users/308248",
"pm_score": -1,
"selected": false,
"text": "<p>In sqlserver</p>\n\n<pre><code>DECLARE @p_date DATE\n\nSELECT * \nFROM table1\nWHERE column_dateTime=@p_date\n</code></pre>\n\n<p>In C#\nPass the short string of date value using ToShortDateString() function.\nsample:\n DateVariable.ToShortDateString();</p>\n"
},
{
"answer_id": 4373895,
"author": "Naresh Goradara",
"author_id": 284313,
"author_profile": "https://Stackoverflow.com/users/284313",
"pm_score": 1,
"selected": false,
"text": "<p>Date can be compared in sqlserver using string comparision:\ne.g.</p>\n\n<pre><code>DECLARE @strDate VARCHAR(15)\nSET @strDate ='07-12-2010'\n\n\nSELECT * FROM table\nWHERE CONVERT(VARCHAR(15),dtInvoice, 112)>= CONVERT(VARCHAR(15),@strDate , 112)\n</code></pre>\n"
},
{
"answer_id": 9061984,
"author": "Michael Gasa",
"author_id": 1177766,
"author_profile": "https://Stackoverflow.com/users/1177766",
"pm_score": 0,
"selected": false,
"text": "<pre><code>SELECT * FROM tablename\nWHERE CAST(FLOOR(CAST(column_datetime AS FLOAT))AS DATETIME) = '30 jan 2012'\n</code></pre>\n"
},
{
"answer_id": 9439193,
"author": "Jaider",
"author_id": 480700,
"author_profile": "https://Stackoverflow.com/users/480700",
"pm_score": 2,
"selected": false,
"text": "<p>I normally convert date-time to date and compare them, like these:</p>\n\n<pre><code>SELECT 'Same Date' WHERE CAST(getDate() as date) = cast('2/24/2012 2:23 PM' as date)\n</code></pre>\n\n<p>or</p>\n\n<pre><code>SELECT 'Same Date' WHERE DATEDIFF(dd, cast(getDate() as date), cast('2/24/2012 2:23 PM' as date)) = 0\n</code></pre>\n"
},
{
"answer_id": 30414576,
"author": "user4932286",
"author_id": 4932286,
"author_profile": "https://Stackoverflow.com/users/4932286",
"pm_score": 0,
"selected": false,
"text": "<p>The best way is to simply extract the date part using the SQL DATE() Function:</p>\n\n<pre><code>SELECT * \nFROM table1\nWHERE DATE(column_datetime) = @p_date;\n</code></pre>\n"
},
{
"answer_id": 35849283,
"author": "Arun",
"author_id": 6030147,
"author_profile": "https://Stackoverflow.com/users/6030147",
"pm_score": 0,
"selected": false,
"text": "<p>There are many formats for date in SQL which are being specified. Refer <a href=\"https://msdn.microsoft.com/en-in/library/ms187928.aspx\" rel=\"nofollow\">https://msdn.microsoft.com/en-in/library/ms187928.aspx</a></p>\n\n<p>Converting and comparing varchar column with selected dates.</p>\n\n<p>Syntax:</p>\n\n<pre><code>SELECT * FROM tablename where CONVERT(datetime,columnname,103) \n between '2016-03-01' and '2016-03-03'\n</code></pre>\n\n\n\n<pre><code>In CONVERT(DATETIME,COLUMNNAME,103) \"103\" SPECIFIES THE DATE FORMAT as dd/mm/yyyy\n</code></pre>\n"
}
] | 2008/08/14 | [
"https://Stackoverflow.com/questions/10825",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/993/"
] | In SQL Server I have a `DATETIME` column which includes a time element.
Example:
```
'14 AUG 2008 14:23:019'
```
What is the **best** method to only select the records for a particular day, ignoring the time part?
Example: (Not safe, as it does not match the time part and returns no rows)
```
DECLARE @p_date DATETIME
SET @p_date = CONVERT( DATETIME, '14 AUG 2008', 106 )
SELECT *
FROM table1
WHERE column_datetime = @p_date
```
*Note: Given this site is also about jotting down notes and techniques you pick up and then forget, I'm going to post my own answer to this question as DATETIME stuff in MSSQL is probably the topic I lookup most in SQLBOL.*
---
**Update** Clarified example to be more specific.
---
**Edit** Sorry, But I've had to down-mod WRONG answers (answers that return wrong results).
@Jorrit: `WHERE (date>'20080813' AND date<'20080815')` will return the 13th and the 14th.
@wearejimbo: *Close, but no cigar!* badge awarded to you. You missed out records written at 14/08/2008 23:59:001 to 23:59:999 (i.e. Less than 1 second before midnight.) | Technique 1:
```
DECLARE @p_date DATETIME
SET @p_date = CONVERT( DATETIME, '14 AUG 2008', 106 )
SELECT *
FROM table1
WHERE column_datetime >= @p_date
AND column_datetime < DATEADD(d, 1, @p_date)
```
The advantage of this is that it will use any index on 'column\_datetime' if it exists. |
10,855 | <p>I'm trying to perform a LINQ query on a DataTable object and bizarrely I am finding that performing such queries on DataTables is not straightforward. For example:</p>
<pre><code>var results = from myRow in myDataTable
where results.Field("RowNo") == 1
select results;
</code></pre>
<p>This is not allowed. How do I get something like this working?</p>
<p>I'm amazed that LINQ queries are not allowed on DataTables!</p>
| [
{
"answer_id": 10856,
"author": "Jon Limjap",
"author_id": 372,
"author_profile": "https://Stackoverflow.com/users/372",
"pm_score": 6,
"selected": false,
"text": "<p>It's not that they were deliberately not allowed on DataTables, it's just that DataTables pre-date the IQueryable and generic IEnumerable constructs on which Linq queries can be performed. </p>\n\n<p>Both interfaces require some sort type-safety validation. DataTables are not strongly typed. This is the same reason why people can't query against an ArrayList, for example.</p>\n\n<p>For Linq to work you need to map your results against type-safe objects and query against that instead.</p>\n"
},
{
"answer_id": 10857,
"author": "David Wengier",
"author_id": 489,
"author_profile": "https://Stackoverflow.com/users/489",
"pm_score": 4,
"selected": false,
"text": "<p>You can use LINQ to objects on the Rows collection, like so:</p>\n\n<pre><code>var results = from myRow in myDataTable.Rows where myRow.Field(\"RowNo\") == 1 select myRow;\n</code></pre>\n"
},
{
"answer_id": 10893,
"author": "Keith",
"author_id": 905,
"author_profile": "https://Stackoverflow.com/users/905",
"pm_score": 6,
"selected": false,
"text": "<p>As @ch00k said:</p>\n\n<pre><code>using System.Data; //needed for the extension methods to work\n\n...\n\nvar results = \n from myRow in myDataTable.Rows \n where myRow.Field<int>(\"RowNo\") == 1 \n select myRow; //select the thing you want, not the collection\n</code></pre>\n\n<p>You also need to add a project reference to <code>System.Data.DataSetExtensions</code></p>\n"
},
{
"answer_id": 11593,
"author": "Collin K",
"author_id": 1369,
"author_profile": "https://Stackoverflow.com/users/1369",
"pm_score": 11,
"selected": true,
"text": "<p>You can't query against the <code>DataTable</code>'s <em>Rows</em> collection, since <code>DataRowCollection</code> doesn't implement <code>IEnumerable<T></code>. You need to use the <code>AsEnumerable()</code> extension for <code>DataTable</code>. Like so:</p>\n<pre><code>var results = from myRow in myDataTable.AsEnumerable()\nwhere myRow.Field<int>("RowNo") == 1\nselect myRow;\n</code></pre>\n<p>And as <a href=\"https://stackoverflow.com/a/10893/5519709\">@Keith</a> says, you'll need to add a reference to <a href=\"http://msdn.microsoft.com/en-us/library/system.data.datarowextensions.aspx\" rel=\"noreferrer\">System.Data.DataSetExtensions</a></p>\n<p><code>AsEnumerable()</code> returns <code>IEnumerable<DataRow></code>. If you need to convert <code>IEnumerable<DataRow></code> to a <code>DataTable</code>, use the <code>CopyToDataTable()</code> extension.</p>\n<p>Below is query with Lambda Expression,</p>\n<pre><code>var result = myDataTable\n .AsEnumerable()\n .Where(myRow => myRow.Field<int>("RowNo") == 1);\n</code></pre>\n"
},
{
"answer_id": 613431,
"author": "JoelFan",
"author_id": 16012,
"author_profile": "https://Stackoverflow.com/users/16012",
"pm_score": 7,
"selected": false,
"text": "<pre><code>var results = from DataRow myRow in myDataTable.Rows\n where (int)myRow[\"RowNo\"] == 1\n select myRow\n</code></pre>\n"
},
{
"answer_id": 2890640,
"author": "Ravi",
"author_id": 348127,
"author_profile": "https://Stackoverflow.com/users/348127",
"pm_score": 5,
"selected": false,
"text": "<pre><code>var query = from p in dt.AsEnumerable()\n where p.Field<string>(\"code\") == this.txtCat.Text\n select new\n {\n name = p.Field<string>(\"name\"),\n age= p.Field<int>(\"age\") \n };\n</code></pre>\n\n<p>the name and age fields are now part of the query object and can be accessed like so: <strong>Console.WriteLine(query.name);</strong></p>\n"
},
{
"answer_id": 6678063,
"author": "Salim",
"author_id": 842567,
"author_profile": "https://Stackoverflow.com/users/842567",
"pm_score": 5,
"selected": false,
"text": "<p><a href=\"http://dotnetarchitect.wordpress.com/2009/03/18/using-linq-to-manipulate-data-in-datasetdatatable/\">Using LINQ to manipulate data in DataSet/DataTable</a></p>\n\n<pre><code>var results = from myRow in tblCurrentStock.AsEnumerable()\n where myRow.Field<string>(\"item_name\").ToUpper().StartsWith(tbSearchItem.Text.ToUpper())\n select myRow;\nDataView view = results.AsDataView();\n</code></pre>\n"
},
{
"answer_id": 8739712,
"author": "sushil pandey",
"author_id": 843294,
"author_profile": "https://Stackoverflow.com/users/843294",
"pm_score": 5,
"selected": false,
"text": "<pre><code>//Create DataTable \nDataTable dt= new DataTable();\ndt.Columns.AddRange(new DataColumn[]\n{\n new DataColumn(\"ID\",typeof(System.Int32)),\n new DataColumn(\"Name\",typeof(System.String))\n\n});\n\n//Fill with data\n\ndt.Rows.Add(new Object[]{1,\"Test1\"});\ndt.Rows.Add(new Object[]{2,\"Test2\"});\n\n//Now Query DataTable with linq\n//To work with linq it should required our source implement IEnumerable interface.\n//But DataTable not Implement IEnumerable interface\n//So we call DataTable Extension method i.e AsEnumerable() this will return EnumerableRowCollection<DataRow>\n\n\n// Now Query DataTable to find Row whoes ID=1\n\nDataRow drow = dt.AsEnumerable().Where(p=>p.Field<Int32>(0)==1).FirstOrDefault();\n // \n</code></pre>\n"
},
{
"answer_id": 10648288,
"author": "midhun sankar",
"author_id": 1402739,
"author_profile": "https://Stackoverflow.com/users/1402739",
"pm_score": 4,
"selected": false,
"text": "<p>Try this</p>\n\n<pre><code>var row = (from result in dt.AsEnumerable().OrderBy( result => Guid.NewGuid()) select result).Take(3) ; \n</code></pre>\n"
},
{
"answer_id": 12938526,
"author": "Abdul Saboor",
"author_id": 1176903,
"author_profile": "https://Stackoverflow.com/users/1176903",
"pm_score": 3,
"selected": false,
"text": "<p>For VB.NET The code will look like this:</p>\n\n<pre><code>Dim results = From myRow In myDataTable \nWhere myRow.Field(Of Int32)(\"RowNo\") = 1 Select myRow\n</code></pre>\n"
},
{
"answer_id": 16198286,
"author": "xadriel",
"author_id": 618083,
"author_profile": "https://Stackoverflow.com/users/618083",
"pm_score": 4,
"selected": false,
"text": "<p>Most likely, the classes for the DataSet, DataTable and DataRow are already defined in the solution. If that's the case you won't need the DataSetExtensions reference.</p>\n\n<p>Ex. DataSet class name-> CustomSet, DataRow class name-> CustomTableRow (with defined columns: RowNo, ...)</p>\n\n<pre><code>var result = from myRow in myDataTable.Rows.OfType<CustomSet.CustomTableRow>()\n where myRow.RowNo == 1\n select myRow;\n</code></pre>\n\n<p>Or (as I prefer)</p>\n\n<pre><code>var result = myDataTable.Rows.OfType<CustomSet.CustomTableRow>().Where(myRow => myRow.RowNo);\n</code></pre>\n"
},
{
"answer_id": 19756035,
"author": "AuthorProxy",
"author_id": 1763061,
"author_profile": "https://Stackoverflow.com/users/1763061",
"pm_score": 3,
"selected": false,
"text": "<p>You can get it work elegant via linq like this:</p>\n\n<pre><code>from prod in TenMostExpensiveProducts().Tables[0].AsEnumerable()\nwhere prod.Field<decimal>(\"UnitPrice\") > 62.500M\nselect prod\n</code></pre>\n\n<p>Or like dynamic linq this (AsDynamic is called directly on DataSet):</p>\n\n<pre><code>TenMostExpensiveProducts().AsDynamic().Where (x => x.UnitPrice > 62.500M)\n</code></pre>\n\n<p>I prefer the last approach while is is the most flexible.\nP.S.: Don't forget to connect <code>System.Data.DataSetExtensions.dll</code> reference</p>\n"
},
{
"answer_id": 21497646,
"author": "Vinay",
"author_id": 2074385,
"author_profile": "https://Stackoverflow.com/users/2074385",
"pm_score": 3,
"selected": false,
"text": "<pre><code>var results = from myRow in myDataTable\nwhere results.Field<Int32>(\"RowNo\") == 1\nselect results;\n</code></pre>\n"
},
{
"answer_id": 22985291,
"author": "Uthaiah",
"author_id": 1488323,
"author_profile": "https://Stackoverflow.com/users/1488323",
"pm_score": 3,
"selected": false,
"text": "<p>Try this... </p>\n\n<pre><code>SqlCommand cmd = new SqlCommand( \"Select * from Employee\",con);\nSqlDataReader dr = cmd.ExecuteReader( );\nDataTable dt = new DataTable( \"Employee\" );\ndt.Load( dr );\nvar Data = dt.AsEnumerable( );\nvar names = from emp in Data select emp.Field<String>( dt.Columns[1] );\nforeach( var name in names )\n{\n Console.WriteLine( name );\n}\n</code></pre>\n"
},
{
"answer_id": 26367127,
"author": "LandedGently",
"author_id": 103965,
"author_profile": "https://Stackoverflow.com/users/103965",
"pm_score": 3,
"selected": false,
"text": "<p>In my application I found that using LINQ to Datasets with the AsEnumerable() extension for DataTable as suggested in the answer was extremely slow. If you're interested in optimizing for speed, use James Newtonking's Json.Net library (<a href=\"http://james.newtonking.com/json/help/index.html\" rel=\"noreferrer\">http://james.newtonking.com/json/help/index.html</a>)</p>\n\n<pre><code>// Serialize the DataTable to a json string\nstring serializedTable = JsonConvert.SerializeObject(myDataTable); \nJarray dataRows = Jarray.Parse(serializedTable);\n\n// Run the LINQ query\nList<JToken> results = (from row in dataRows\n where (int) row[\"ans_key\"] == 42\n select row).ToList();\n\n// If you need the results to be in a DataTable\nstring jsonResults = JsonConvert.SerializeObject(results);\nDataTable resultsTable = JsonConvert.DeserializeObject<DataTable>(jsonResults);\n</code></pre>\n"
},
{
"answer_id": 29133713,
"author": "Matt Kemp",
"author_id": 631277,
"author_profile": "https://Stackoverflow.com/users/631277",
"pm_score": 4,
"selected": false,
"text": "<p>This is a simple way that works for me and uses lambda expressions:</p>\n\n<pre><code>var results = myDataTable.Select(\"\").FirstOrDefault(x => (int)x[\"RowNo\"] == 1)\n</code></pre>\n\n<p>Then if you want a particular value:</p>\n\n<pre><code>if(results != null) \n var foo = results[\"ColName\"].ToString()\n</code></pre>\n"
},
{
"answer_id": 31803241,
"author": "Iman",
"author_id": 184572,
"author_profile": "https://Stackoverflow.com/users/184572",
"pm_score": 3,
"selected": false,
"text": "<pre><code>IEnumerable<string> result = from myRow in dataTableResult.AsEnumerable()\n select myRow[\"server\"].ToString() ;\n</code></pre>\n"
},
{
"answer_id": 35164023,
"author": "vandsh",
"author_id": 2242217,
"author_profile": "https://Stackoverflow.com/users/2242217",
"pm_score": 6,
"selected": false,
"text": "<p>I realize this has been answered a few times over, but just to offer another approach:</p>\n<p>I like to use the <code>.Cast<T>()</code> method, it helps me maintain sanity in seeing the explicit type defined and deep down I think <code>.AsEnumerable()</code> calls it anyways:</p>\n<pre class=\"lang-cs prettyprint-override\"><code>var results = from myRow in myDataTable.Rows.Cast<DataRow>() \n where myRow.Field<int>("RowNo") == 1 select myRow;\n</code></pre>\n<p>or</p>\n<pre class=\"lang-cs prettyprint-override\"><code>var results = myDataTable.Rows.Cast<DataRow>()\n .FirstOrDefault(x => x.Field<int>("RowNo") == 1);\n</code></pre>\n<p><em>As noted in comments, does not require <code>System.Data.DataSetExtensions</code> or any other assemblies (<a href=\"https://learn.microsoft.com/en-us/dotnet/api/system.linq.enumerable.cast\" rel=\"noreferrer\">Reference</a>)</em></p>\n"
},
{
"answer_id": 36422555,
"author": "Mohit Verma",
"author_id": 6049604,
"author_profile": "https://Stackoverflow.com/users/6049604",
"pm_score": 5,
"selected": false,
"text": "<p>Try this simple line of query:</p>\n\n<pre><code>var result=myDataTable.AsEnumerable().Where(myRow => myRow.Field<int>(\"RowNo\") == 1);\n</code></pre>\n"
},
{
"answer_id": 46937157,
"author": "Ryan Gavin",
"author_id": 6294612,
"author_profile": "https://Stackoverflow.com/users/6294612",
"pm_score": 3,
"selected": false,
"text": "<p>Example on how to achieve this provided below: </p>\n\n<pre><code>DataSet dataSet = new DataSet(); //Create a dataset\ndataSet = _DataEntryDataLayer.ReadResults(); //Call to the dataLayer to return the data\n\n//LINQ query on a DataTable\nvar dataList = dataSet.Tables[\"DataTable\"]\n .AsEnumerable()\n .Select(i => new\n {\n ID = i[\"ID\"],\n Name = i[\"Name\"]\n }).ToList();\n</code></pre>\n"
},
{
"answer_id": 48572211,
"author": "Gabriel Martinez Bustos",
"author_id": 6328328,
"author_profile": "https://Stackoverflow.com/users/6328328",
"pm_score": 3,
"selected": false,
"text": "<p>you can try this, but you must be sure the type of values for each Column</p>\n\n<pre><code>List<MyClass> result = myDataTable.AsEnumerable().Select(x=> new MyClass(){\n Property1 = (string)x.Field<string>(\"ColumnName1\"),\n Property2 = (int)x.Field<int>(\"ColumnName2\"),\n Property3 = (bool)x.Field<bool>(\"ColumnName3\"), \n});\n</code></pre>\n"
},
{
"answer_id": 57558642,
"author": "Alan",
"author_id": 10656609,
"author_profile": "https://Stackoverflow.com/users/10656609",
"pm_score": 0,
"selected": false,
"text": "<p>I propose following solution:</p>\n\n<pre><code>DataView view = new DataView(myDataTable); \nview.RowFilter = \"RowNo = 1\";\nDataTable results = view.ToTable(true);\n</code></pre>\n\n<p>Looking at the <a href=\"https://learn.microsoft.com/de-de/dotnet/api/system.data.dataview?view=netframework-4.8\" rel=\"nofollow noreferrer\">DataView Documentation</a>, the first thing we can see is this:</p>\n\n<blockquote>\n <p>Represents a databindable, customized view of a DataTable for sorting, filtering, searching, editing, and navigation.</p>\n</blockquote>\n\n<p>What I am getting from this is that DataTable is meant to only store data and DataView is there enable us to \"query\" against the DataTable. </p>\n\n<p>Here is how this works in this particular case:</p>\n\n<p>You try to implement the SQL Statement</p>\n\n<pre><code>SELECT *\nFROM myDataTable\nWHERE RowNo = 1\n</code></pre>\n\n<p>in \"DataTable language\". In C# we would read it like this:</p>\n\n<pre><code>FROM myDataTable\nWHERE RowNo = 1\nSELECT *\n</code></pre>\n\n<p>which looks in C# like this:</p>\n\n<pre><code>DataView view = new DataView(myDataTable); //FROM myDataTable\nview.RowFilter = \"RowNo = 1\"; //WHERE RowNo = 1\nDataTable results = view.ToTable(true); //SELECT *\n</code></pre>\n"
}
] | 2008/08/14 | [
"https://Stackoverflow.com/questions/10855",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/445/"
] | I'm trying to perform a LINQ query on a DataTable object and bizarrely I am finding that performing such queries on DataTables is not straightforward. For example:
```
var results = from myRow in myDataTable
where results.Field("RowNo") == 1
select results;
```
This is not allowed. How do I get something like this working?
I'm amazed that LINQ queries are not allowed on DataTables! | You can't query against the `DataTable`'s *Rows* collection, since `DataRowCollection` doesn't implement `IEnumerable<T>`. You need to use the `AsEnumerable()` extension for `DataTable`. Like so:
```
var results = from myRow in myDataTable.AsEnumerable()
where myRow.Field<int>("RowNo") == 1
select myRow;
```
And as [@Keith](https://stackoverflow.com/a/10893/5519709) says, you'll need to add a reference to [System.Data.DataSetExtensions](http://msdn.microsoft.com/en-us/library/system.data.datarowextensions.aspx)
`AsEnumerable()` returns `IEnumerable<DataRow>`. If you need to convert `IEnumerable<DataRow>` to a `DataTable`, use the `CopyToDataTable()` extension.
Below is query with Lambda Expression,
```
var result = myDataTable
.AsEnumerable()
.Where(myRow => myRow.Field<int>("RowNo") == 1);
``` |
10,870 | <p>Once I've called <code>DragManager.acceptDrag</code> is there any way to "unaccept" the drag? Say that I have a view which can accept drag and drop, but only in certain areas. Once the user drags over one of these areas I call <code>DragManager.acceptDrag(this)</code> (from a <code>DragEvent.DRAG_OVER</code> handler), but if the user then moves out of this area I'd like to change the status of the drag to not accepted and show the <code>DragManager.NONE</code> feedback. However, neither calling <code>DragManager.acceptDrag(null)</code> nor <code>DragManager.showFeedback(DragManager.NONE)</code> seems to have any effect. Once I've accepted the drag an set the feedback type I can't seem to change it.</p>
<p>Just to make it clear: the areas where the user should be able to drop are not components or even display objects, in fact they are just ranges in the text of a text field (like the selection). Had they been components of their own I could have solved it by making each of them accept drag events individually. I guess I could create proxy components that float over the text to emulate it, but I'd rather not if it isn't necessary.</p>
<hr>
<p>I've managed to get it working in both AIR and the browser now, but only by putting proxy components on top of the ranges of text where you should be able to drop things. That way I get the right feedback and drops are automatically unaccepted on drag exit.</p>
<p>This is the oddest thing about D&D in AIR:</p>
<pre><code>DragManager.doDrag(initiator, source, event, dragImage, offsetX, offsetY);
</code></pre>
<p>In browser-based Flex, <code>offsetX</code> and <code>offsetY</code> should be negative (so says the documentation, and it works fine). However, when running <em>exactly the same code</em> in AIR you have to make the offsets positive. The same numbers, but positive. That is very, very weird.</p>
<hr>
<p>I've tested some more and what <a href="https://stackoverflow.com/questions/10870/how-can-i-unaccept-a-drag-in-flex#11209">@maclema</a> works, but not if you run in AIR. It seems like drag and drop in AIR is different. It's really, really weird because not only is the feedback not showing correctly, and it's not possible to unaccept, but the coordinates are also completely off. I just tried my application in a browser instead of AIR and dragging and dropping is completely broken.</p>
<p>Also, skipping the <code>dragEnter</code> handler works fine in AIR, but breaks everything when running in a browser.</p>
| [
{
"answer_id": 11209,
"author": "Matt MacLean",
"author_id": 22,
"author_profile": "https://Stackoverflow.com/users/22",
"pm_score": 3,
"selected": false,
"text": "<p>Are you using only the dragEnter method? If you are trying to reject the drag while still dragging over the same component you need to use both the dragEnter and dragOver methods.</p>\n\n<p>Check out this example:</p>\n\n<pre><code><?xml version=\"1.0\" encoding=\"utf-8\"?>\n<mx:Application xmlns:mx=\"http://www.adobe.com/2006/mxml\" layout=\"absolute\">\n <mx:Script>\n <![CDATA[\n import mx.core.DragSource;\n import mx.managers.DragManager;\n import mx.events.DragEvent;\n\n private function onDragEnter(e:DragEvent):void {\n if ( e.target == lbl ) {\n\n if ( e.localX < lbl.width/2 ) {\n trace(\"accept\");\n DragManager.acceptDragDrop(this);\n }\n else {\n DragManager.acceptDragDrop(null);\n }\n }\n }\n\n private function doStartDrag(e:MouseEvent):void {\n if ( e.buttonDown ) {\n var ds:DragSource = new DragSource();\n ds.addData(\"test\", \"text\");\n\n DragManager.doDrag(btn, ds, e);\n }\n }\n ]]>\n </mx:Script>\n <mx:Label id=\"lbl\" text=\"hello world!\" left=\"10\" top=\"10\" dragEnter=\"onDragEnter(event)\" dragOver=\"onDragEnter(event)\" />\n <mx:Button id=\"btn\" x=\"47\" y=\"255\" label=\"Button\" mouseMove=\"doStartDrag(event)\"/>\n</mx:Application>\n</code></pre>\n"
},
{
"answer_id": 12552,
"author": "Matt MacLean",
"author_id": 22,
"author_profile": "https://Stackoverflow.com/users/22",
"pm_score": 0,
"selected": false,
"text": "<p>ok, I see the problem now. Rather than null, try setting it to the dragInitiator.</p>\n\n<p>Check this out.</p>\n\n<pre><code><?xml version=\"1.0\" encoding=\"utf-8\"?>\n<mx:WindowedApplication xmlns:mx=\"http://www.adobe.com/2006/mxml\" layout=\"absolute\">\n <mx:Script>\n <![CDATA[\n import mx.controls.Alert;\n import mx.events.DragEvent;\n import mx.managers.DragManager;\n import mx.core.DragSource;\n\n private function doStartDrag(e:MouseEvent):void {\n if ( e.buttonDown && !DragManager.isDragging ) {\n var ds:DragSource = new DragSource();\n ds.addData(\"test\", \"test\");\n\n DragManager.doDrag(btn, ds, e);\n }\n }\n\n private function handleDragOver(e:DragEvent):void {\n if ( e.localX < cvs.width/2 ) {\n //since null does nothing, lets just set to accept the drag\n //operation, but accept it to the dragInitiator\n DragManager.acceptDragDrop(e.dragInitiator);\n } \n else {\n //accept drag\n DragManager.acceptDragDrop(cvs);\n DragManager.showFeedback( DragManager.COPY );\n }\n }\n\n private function handleDragDrop(e:DragEvent):void {\n if ( e.dragSource.hasFormat(\"test\") ) {\n Alert.show(\"Got a drag drop!\");\n }\n }\n ]]>\n </mx:Script>\n <mx:Canvas x=\"265\" y=\"66\" width=\"321\" height=\"245\" backgroundColor=\"#FF0000\" id=\"cvs\" dragOver=\"handleDragOver(event)\" dragDrop=\"handleDragDrop(event)\">\n </mx:Canvas>\n <mx:Button id=\"btn\" x=\"82\" y=\"140\" label=\"Drag Me\" mouseDown=\"doStartDrag(event)\"/>\n</mx:WindowedApplication>\n</code></pre>\n"
},
{
"answer_id": 16376,
"author": "Matt MacLean",
"author_id": 22,
"author_profile": "https://Stackoverflow.com/users/22",
"pm_score": 0,
"selected": false,
"text": "<p>Yes, drag and drop is different in AIR. I HATE that! It takes a lot of playing around to figure out how to get things to work the same as custom dnd that was built in flex.</p>\n\n<p>As for the coordinates, maybe play around with localToContent, and localToGlobal methods. They may help in translating the coordinates to something useful.</p>\n\n<p>Good luck. I will let you know if I think of anything else.</p>\n"
},
{
"answer_id": 90321,
"author": "Christophe Herreman",
"author_id": 17255,
"author_profile": "https://Stackoverflow.com/users/17255",
"pm_score": 1,
"selected": false,
"text": "<p>If you don't need native drag and drop in AIR, you can get the Flex drag and drop behavior by subclassing WindowedApplication and setting the DragManager. See this post on the Adobe Jira for more info: <a href=\"https://bugs.adobe.com/jira/browse/SDK-13983\" rel=\"nofollow noreferrer\">https://bugs.adobe.com/jira/browse/SDK-13983</a></p>\n"
},
{
"answer_id": 15009919,
"author": "bebbo",
"author_id": 1412279,
"author_profile": "https://Stackoverflow.com/users/1412279",
"pm_score": 1,
"selected": false,
"text": "<p>You are misunderstanding the concept. Your \"unaccept\" is achieved by implementing the dragOverHandler and signaling that the data is not wanted.</p>\n\n<p>Here is the basic concept:</p>\n\n<ol>\n<li><p>register the dragEnterHandler or override the already registered method.</p>\n\n<pre><code>function dragEnterHandler(event: DragEvent):void {\n if (data suites at least one location in this component)\n DragManager.acceptDragDrop(this);\n}\n</code></pre>\n\n<p>This enables your container to receive further messages (dragOver/dragExit). But this is <strong>NOT</strong> the location to decide which kind of mouse cursor should be displayed.</p>\n\n<p>Without <strong>DragManager.acceptDragDrop(this);</strong> the other handlers aren't called.</p></li>\n<li><p>register the dragOverHandler or override the already registered method.</p>\n\n<pre><code>function dragOverHandler(event: DragEvent):void {\n if (data suites at least no location in this component) {\n DragManager.showFeedback(DragManager.NONE);\n return;\n }\n\n ... // handle other cases and show the cursor / icon you want\n}\n</code></pre>\n\n<p>Calling <strong>DragManager.showFeedback(DragManager.NONE);</strong> does the trick to display the \"unaccept\".</p></li>\n<li><p>register the dragExitHandler or override the already registered method.</p>\n\n<pre><code>function dragOverHandler(event: DragEvent):void {\n // handle the recieved data as you like.\n}\n</code></pre></li>\n</ol>\n"
}
] | 2008/08/14 | [
"https://Stackoverflow.com/questions/10870",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1109/"
] | Once I've called `DragManager.acceptDrag` is there any way to "unaccept" the drag? Say that I have a view which can accept drag and drop, but only in certain areas. Once the user drags over one of these areas I call `DragManager.acceptDrag(this)` (from a `DragEvent.DRAG_OVER` handler), but if the user then moves out of this area I'd like to change the status of the drag to not accepted and show the `DragManager.NONE` feedback. However, neither calling `DragManager.acceptDrag(null)` nor `DragManager.showFeedback(DragManager.NONE)` seems to have any effect. Once I've accepted the drag an set the feedback type I can't seem to change it.
Just to make it clear: the areas where the user should be able to drop are not components or even display objects, in fact they are just ranges in the text of a text field (like the selection). Had they been components of their own I could have solved it by making each of them accept drag events individually. I guess I could create proxy components that float over the text to emulate it, but I'd rather not if it isn't necessary.
---
I've managed to get it working in both AIR and the browser now, but only by putting proxy components on top of the ranges of text where you should be able to drop things. That way I get the right feedback and drops are automatically unaccepted on drag exit.
This is the oddest thing about D&D in AIR:
```
DragManager.doDrag(initiator, source, event, dragImage, offsetX, offsetY);
```
In browser-based Flex, `offsetX` and `offsetY` should be negative (so says the documentation, and it works fine). However, when running *exactly the same code* in AIR you have to make the offsets positive. The same numbers, but positive. That is very, very weird.
---
I've tested some more and what [@maclema](https://stackoverflow.com/questions/10870/how-can-i-unaccept-a-drag-in-flex#11209) works, but not if you run in AIR. It seems like drag and drop in AIR is different. It's really, really weird because not only is the feedback not showing correctly, and it's not possible to unaccept, but the coordinates are also completely off. I just tried my application in a browser instead of AIR and dragging and dropping is completely broken.
Also, skipping the `dragEnter` handler works fine in AIR, but breaks everything when running in a browser. | Are you using only the dragEnter method? If you are trying to reject the drag while still dragging over the same component you need to use both the dragEnter and dragOver methods.
Check out this example:
```
<?xml version="1.0" encoding="utf-8"?>
<mx:Application xmlns:mx="http://www.adobe.com/2006/mxml" layout="absolute">
<mx:Script>
<![CDATA[
import mx.core.DragSource;
import mx.managers.DragManager;
import mx.events.DragEvent;
private function onDragEnter(e:DragEvent):void {
if ( e.target == lbl ) {
if ( e.localX < lbl.width/2 ) {
trace("accept");
DragManager.acceptDragDrop(this);
}
else {
DragManager.acceptDragDrop(null);
}
}
}
private function doStartDrag(e:MouseEvent):void {
if ( e.buttonDown ) {
var ds:DragSource = new DragSource();
ds.addData("test", "text");
DragManager.doDrag(btn, ds, e);
}
}
]]>
</mx:Script>
<mx:Label id="lbl" text="hello world!" left="10" top="10" dragEnter="onDragEnter(event)" dragOver="onDragEnter(event)" />
<mx:Button id="btn" x="47" y="255" label="Button" mouseMove="doStartDrag(event)"/>
</mx:Application>
``` |
10,877 | <p>How can I left-align the numbers in an ordered list?</p>
<pre><code>1. an item
// skip some items for brevity
9. another item
10. notice the 1 is under the 9, and the item contents also line up
</code></pre>
<p>Change the character after the number in an ordered list?</p>
<pre><code>1) an item
</code></pre>
<p>Also is there a CSS solution to change from numbers to alphabetic/roman lists instead of using the type attribute on the ol element.</p>
<p>I am mostly interested in answers that work on Firefox 3.</p>
| [
{
"answer_id": 10887,
"author": "Marcus Downing",
"author_id": 1000,
"author_profile": "https://Stackoverflow.com/users/1000",
"pm_score": 5,
"selected": false,
"text": "<p>The CSS for styling lists is <a href=\"http://www.w3.org/TR/REC-CSS2/generate.html#lists\" rel=\"noreferrer\">here</a>, but is basically:</p>\n\n<pre class=\"lang-css prettyprint-override\"><code>li {\n list-style-type: decimal;\n list-style-position: inside;\n}\n</code></pre>\n\n<p>However, the specific layout you're after can probably only be achieved by delving into the innards of the layout with something like <a href=\"http://www.w3.org/TR/REC-CSS2/generate.html#counters\" rel=\"noreferrer\">this</a> (note that I haven't actually tried it):</p>\n\n<pre class=\"lang-css prettyprint-override\"><code>ol { counter-reset: item }\nli { display: block }\nli:before { content: counter(item) \") \"; counter-increment: item }\n</code></pre>\n"
},
{
"answer_id": 10889,
"author": "GateKiller",
"author_id": 383,
"author_profile": "https://Stackoverflow.com/users/383",
"pm_score": 1,
"selected": false,
"text": "<p>There is the <a href=\"http://www.htmlcodetutorial.com/_OL_TYPE.html\" rel=\"nofollow noreferrer\">Type attribute</a> which allows you to change the numbering style, however, you cannot change the full stop after the number/letter.</p>\n\n<pre><code><ol type=\"a\">\n <li>Turn left on Maple Street</li>\n <li>Turn right on Clover Court</li>\n</ol>\n</code></pre>\n"
},
{
"answer_id": 14738,
"author": "Marcus Downing",
"author_id": 1000,
"author_profile": "https://Stackoverflow.com/users/1000",
"pm_score": 3,
"selected": false,
"text": "<p>I suggest playing with the :before attribute and seeing what you can achieve with it. It will mean your code really is limited to nice new browsers, and excludes the (annoyingly large) section of the market still using rubbish old browsers,</p>\n\n<p>Something like the following, which forces a fixed with on the items. Yes, I know it's less elegant to have to choose the width yourself, but using CSS for your layout is like undercover police work: however good your motives, it always gets messy.</p>\n\n<pre><code>li:before {\n content: counter(item) \") \";\n counter-increment: item;\n display: marker;\n width: 2em;\n}\n</code></pre>\n\n<p>But you're going to have to experiment to find the exact solution.</p>\n"
},
{
"answer_id": 24960,
"author": "Peter Hilton",
"author_id": 2670,
"author_profile": "https://Stackoverflow.com/users/2670",
"pm_score": 3,
"selected": false,
"text": "<p>The numbers line up better if you add leading-zeroes to the numbers, by setting <a href=\"http://www.w3.org/TR/REC-CSS2/generate.html#propdef-list-style-type\" rel=\"noreferrer\">list-style-type</a> to:</p>\n\n<pre><code>ol { list-style-type: decimal-leading-zero; }\n</code></pre>\n"
},
{
"answer_id": 486662,
"author": "grom",
"author_id": 486,
"author_profile": "https://Stackoverflow.com/users/486",
"pm_score": 8,
"selected": true,
"text": "<p>This is the solution I have working in Firefox 3, Opera and Google Chrome. The list still displays in IE7 (but without the close bracket and left align numbers):</p>\n\n<p><div class=\"snippet\" data-lang=\"js\" data-hide=\"false\" data-console=\"true\" data-babel=\"false\">\r\n<div class=\"snippet-code\">\r\n<pre class=\"snippet-code-css lang-css prettyprint-override\"><code>ol {\r\n counter-reset: item;\r\n margin-left: 0;\r\n padding-left: 0;\r\n}\r\nli {\r\n display: block;\r\n margin-bottom: .5em;\r\n margin-left: 2em;\r\n}\r\nli::before {\r\n display: inline-block;\r\n content: counter(item) \") \";\r\n counter-increment: item;\r\n width: 2em;\r\n margin-left: -2em;\r\n}</code></pre>\r\n<pre class=\"snippet-code-html lang-html prettyprint-override\"><code><ol>\r\n <li>One</li>\r\n <li>Two</li>\r\n <li>Three</li>\r\n <li>Four</li>\r\n <li>Five</li>\r\n <li>Six</li>\r\n <li>Seven</li>\r\n <li>Eight</li>\r\n <li>Nine<br>Items</li>\r\n <li>Ten<br>Items</li>\r\n</ol></code></pre>\r\n</div>\r\n</div>\r\n</p>\n\n<p><strong>EDIT:</strong> Included multiple line fix by strager</p>\n\n<blockquote>\n <p>Also is there a CSS solution to change from numbers to alphabetic/roman lists instead of using the type attribute on the ol element.</p>\n</blockquote>\n\n<p>Refer to <a href=\"http://www.w3.org/TR/CSS2/generate.html#lists\" rel=\"noreferrer\">list-style-type</a> CSS property. Or when using counters the second argument accepts a list-style-type value. For example the following will use upper roman:</p>\n\n<pre><code>li::before {\n content: counter(item, upper-roman) \") \";\n counter-increment: item;\n/* ... */\n</code></pre>\n"
},
{
"answer_id": 486704,
"author": "Stephen Denne",
"author_id": 11721,
"author_profile": "https://Stackoverflow.com/users/11721",
"pm_score": 1,
"selected": false,
"text": "<p>The docs say regarding <a href=\"http://www.w3.org/TR/CSS2/generate.html#propdef-list-style-position\" rel=\"nofollow noreferrer\"><code>list-style-position</code></a><code>: outside</code></p>\n\n<blockquote>\n <p>CSS1 did not specify the precise location of the marker box and for reasons of compatibility, CSS2 remains equally ambiguous. For more precise control of marker boxes, please use markers.</p>\n</blockquote>\n\n<p>Further up that page is the stuff about markers.</p>\n\n<p>One example is:</p>\n\n<pre><code> LI:before { \n display: marker;\n content: \"(\" counter(counter) \")\";\n counter-increment: counter;\n width: 6em;\n text-align: center;\n }\n</code></pre>\n"
},
{
"answer_id": 487884,
"author": "Marcus Downing",
"author_id": 1000,
"author_profile": "https://Stackoverflow.com/users/1000",
"pm_score": -1,
"selected": false,
"text": "<p>I have it. Try the following:</p>\n\n<pre><code><html>\n<head>\n<style type='text/css'>\n\n ol { counter-reset: item; }\n\n li { display: block; }\n\n li:before { content: counter(item) \")\"; counter-increment: item; \n display: inline-block; width: 50px; }\n\n</style>\n</head>\n<body>\n<ol>\n <li>Something</li>\n <li>Something</li>\n <li>Something</li>\n <li>Something</li>\n <li>Something</li>\n <li>Something</li>\n <li>Something</li>\n <li>Something</li>\n <li>Something</li>\n <li>Something</li>\n <li>Something</li>\n <li>Something</li>\n</ol>\n</body>\n</code></pre>\n\n<p>The catch is that this <em>definitely</em> won't work on older or less compliant browsers: <code>display: inline-block</code> is a very new property.</p>\n"
},
{
"answer_id": 488160,
"author": "Steve Perks",
"author_id": 16124,
"author_profile": "https://Stackoverflow.com/users/16124",
"pm_score": 3,
"selected": false,
"text": "<p>Stole a lot of this from other answers, but this is working in FF3 for me. It has <code>upper-roman</code>, uniform indenting, a close bracket.</p>\n<p><div class=\"snippet\" data-lang=\"js\" data-hide=\"false\" data-console=\"false\" data-babel=\"false\">\r\n<div class=\"snippet-code\">\r\n<pre class=\"snippet-code-css lang-css prettyprint-override\"><code>ol {\n counter-reset: item;\n margin-left: 0;\n padding-left: 0;\n}\nli {\n margin-bottom: .5em;\n}\nli:before {\n display: inline-block;\n content: counter(item, upper-roman) \")\";\n counter-increment: item;\n width: 3em;\n}</code></pre>\r\n<pre class=\"snippet-code-html lang-html prettyprint-override\"><code><ol>\n <li>One</li>\n <li>Two</li>\n <li>Three</li>\n <li>Four</li>\n <li>Five</li>\n <li>Six</li>\n <li>Seven</li>\n <li>Eight</li>\n <li>Nine</li>\n <li>Ten</li>\n</ol></code></pre>\r\n</div>\r\n</div>\r\n</p>\n"
},
{
"answer_id": 489088,
"author": "strager",
"author_id": 39992,
"author_profile": "https://Stackoverflow.com/users/39992",
"pm_score": 2,
"selected": false,
"text": "<p>Borrowed and improved <a href=\"https://stackoverflow.com/questions/10877/how-can-you-customize-the-numbers-in-an-ordered-list#10887\">Marcus Downing's answer</a>. Tested and works in Firefox 3 and Opera 9. Supports multiple lines, too.</p>\n\n<pre class=\"lang-css prettyprint-override\"><code>ol {\n counter-reset: item;\n margin-left: 0;\n padding-left: 0;\n}\n\nli {\n display: block;\n margin-left: 3.5em; /* Change with margin-left on li:before. Must be -li:before::margin-left + li:before::padding-right. (Causes indention for other lines.) */\n}\n\nli:before {\n content: counter(item) \")\"; /* Change 'item' to 'item, upper-roman' or 'item, lower-roman' for upper- and lower-case roman, respectively. */\n counter-increment: item;\n display: inline-block;\n text-align: right;\n width: 3em; /* Must be the maximum width of your list's numbers, including the ')', for compatability (in case you use a fixed-width font, for example). Will have to beef up if using roman. */\n padding-right: 0.5em;\n margin-left: -3.5em; /* See li comments. */\n}\n</code></pre>\n"
},
{
"answer_id": 501153,
"author": "Marco Luglio",
"author_id": 14263,
"author_profile": "https://Stackoverflow.com/users/14263",
"pm_score": 0,
"selected": false,
"text": "<p><strong>Quick and dirt</strong> alternative solution. You can use a tabulation character along with preformatted text. Here's a possibility:</p>\n\n<pre><code><style type=\"text/css\">\nol {\n list-style-position: inside;\n}\nli:first-letter {\n white-space: pre;\n}\n</style>\n</code></pre>\n\n<p>and your html:</p>\n\n<pre><code><ol>\n<li> an item</li>\n<li> another item</li>\n...\n</ol>\n</code></pre>\n\n<p>Note that the space between the <code>li</code> tag and the beggining of the text is a tabulation character (what you get when you press the tab key inside notepad).</p>\n\n<p>If you need to support older browsers, you can do this instead:</p>\n\n<pre><code><style type=\"text/css\">\nol {\n list-style-position: inside;\n}\n</style>\n\n<ol>\n <li><pre> </pre>an item</li>\n <li><pre> </pre>another item</li>\n ...\n</ol>\n</code></pre>\n"
},
{
"answer_id": 8235507,
"author": "William Entriken",
"author_id": 300224,
"author_profile": "https://Stackoverflow.com/users/300224",
"pm_score": 1,
"selected": false,
"text": "<p>Nope... just use a DL:</p>\n\n<pre><code>dl { overflow:hidden; }\ndt {\n float:left;\n clear: left;\n width:4em; /* adjust the width; make sure the total of both is 100% */\n text-align: right\n}\ndd {\n float:left;\n width:50%; /* adjust the width; make sure the total of both is 100% */\n margin: 0 0.5em;\n}\n</code></pre>\n"
},
{
"answer_id": 8290965,
"author": "Metro",
"author_id": 18978,
"author_profile": "https://Stackoverflow.com/users/18978",
"pm_score": -1,
"selected": false,
"text": "<p>The other answers are better from a conceptual point of view. However, you can just left-pad the numbers with the appropriate number of '&ensp;' to make them line up. </p>\n\n<p><em>*</em> Note: I did not at first recognize that a numbered list was being used. I thought the list was being explicitly generated.</p>\n"
},
{
"answer_id": 21649098,
"author": "tomasofen",
"author_id": 1253788,
"author_profile": "https://Stackoverflow.com/users/1253788",
"pm_score": 0,
"selected": false,
"text": "<p>I will give here the kind of answer i usually don't like to read, but i think that as there are other answers telling you how to achive what you want, it could be nice to rethink if what you are trying to achive is really a good idea.</p>\n\n<p>First, you should think if it is a good idea to show the items in a non-standard way, with a separator charater diferent than the provided.</p>\n\n<p>I don't know the reasons for that, but let's suppose you have good reasons.</p>\n\n<p>The ways propossed here to achive that consist in add content to your markup, mainly trough the CSS :before pseudoclass. This content is really modifing your DOM structure, adding those items to it.</p>\n\n<p>When you use standard \"ol\" numeration, you will have a rendered content in which the \"li\" text is selectable, but the number preceding it is not selectable. That is, the standard numbering system seems to be more \"decoration\" than real content. If you add content for numbers using for example those \":before\" methods, this content will be selectable, and dued to this, performing undesired vopy/paste issues, or accesibility issues with screen readers that will read this \"new\" content in addition to the standard numeration system.</p>\n\n<p>Perhaps another approach could be to style the numbers using images, although this alternative will bring its own problems (numbers not shown when images are disabled, text size for number not changing, ...).</p>\n\n<p>Anyway, the reason for this answer is not just to propose this \"images\" alternative, but to make people think in the consequences of trying to change the standard numeration system for ordered lists.</p>\n"
},
{
"answer_id": 31823704,
"author": "z0r",
"author_id": 320036,
"author_profile": "https://Stackoverflow.com/users/320036",
"pm_score": 4,
"selected": false,
"text": "<p>You can also specify your own numbers in the HTML - e.g. if the numbers are being provided by a database:</p>\n\n<p><div class=\"snippet\" data-lang=\"js\" data-hide=\"false\" data-console=\"true\" data-babel=\"false\">\r\n<div class=\"snippet-code\">\r\n<pre class=\"snippet-code-css lang-css prettyprint-override\"><code>ol {\r\n list-style: none;\r\n}\r\n\r\nol>li:before {\r\n content: attr(seq) \". \";\r\n}</code></pre>\r\n<pre class=\"snippet-code-html lang-html prettyprint-override\"><code><ol>\r\n <li seq=\"1\">Item one</li>\r\n <li seq=\"20\">Item twenty</li>\r\n <li seq=\"300\">Item three hundred</li>\r\n</ol></code></pre>\r\n</div>\r\n</div>\r\n</p>\n\n<p>The <code>seq</code> attribute is made visible using a method similar to that given in other answers. But instead of using <code>content: counter(foo)</code>, we use <code>content: attr(seq)</code>.</p>\n\n<p><a href=\"http://codepen.io/anon/pen/xGMERG\" rel=\"nofollow noreferrer\">Demo in CodePen with more styling</a></p>\n"
},
{
"answer_id": 43049714,
"author": "Vlad Alivanov",
"author_id": 5622540,
"author_profile": "https://Stackoverflow.com/users/5622540",
"pm_score": 0,
"selected": false,
"text": "<p>This code makes numbering style same as headers of li content.</p>\n\n<pre><code><style>\n h4 {font-size: 18px}\n ol.list-h4 {counter-reset: item; padding-left:27px}\n ol.list-h4 > li {display: block}\n ol.list-h4 > li::before {display: block; position:absolute; left:16px; top:auto; content: counter(item)\".\"; counter-increment: item; font-size: 18px}\n ol.list-h4 > li > h4 {padding-top:3px}\n</style>\n\n<ol class=\"list-h4\">\n <li>\n <h4>...</h4>\n <p>...</p> \n </li>\n <li>...</li>\n</ol>\n</code></pre>\n"
},
{
"answer_id": 60100741,
"author": "Flimm",
"author_id": 247696,
"author_profile": "https://Stackoverflow.com/users/247696",
"pm_score": 5,
"selected": false,
"text": "<h1>HTML5: Use the <code>value</code> attribute (no CSS needed)</h1>\n\n<p>Modern browsers will interpret the <code>value</code> attribute and will display it as you expect. See <a href=\"https://developer.mozilla.org/en-US/docs/Web/HTML/Element/li#attr-value\" rel=\"noreferrer\">MDN documentation</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-html lang-html prettyprint-override\"><code><ol>\r\n <li value=\"3\">This is item three.</li>\r\n <li value=\"50\">This is item fifty.</li>\r\n <li value=\"100\">This is item one hundred.</li>\r\n</ol></code></pre>\r\n</div>\r\n</div>\r\n</p>\n\n<p>Also have a look at <a href=\"https://developer.mozilla.org/en-US/docs/Web/HTML/Element/ol\" rel=\"noreferrer\">the <code><ol></code> article on MDN</a>, especially the documentation for the <code>start</code> and attribute.</p>\n"
},
{
"answer_id": 70883910,
"author": "TylerH",
"author_id": 2756409,
"author_profile": "https://Stackoverflow.com/users/2756409",
"pm_score": 0,
"selected": false,
"text": "<p>Vhndaree <a href=\"https://stackoverflow.com/a/70835307/2756409\">posted an interesting implementation of this</a> problem on a duplicate question, which goes a step further than any of the existing answers in that it implements a custom character <em>before</em> the incrementing numbers:</p>\n<blockquote>\n<p><div class=\"snippet\" data-lang=\"js\" data-hide=\"false\" data-console=\"false\" data-babel=\"false\">\r\n<div class=\"snippet-code\">\r\n<pre class=\"snippet-code-css lang-css prettyprint-override\"><code> \n .custom {\n list-style-type: none;\n }\n .custom li {\n counter-increment: step-counter;\n }\n .custom li::before {\n content: '(' counter(step-counter) ')';\n margin-right: 5px;\n }\n \n </code></pre>\r\n<pre class=\"snippet-code-html lang-html prettyprint-override\"><code> \n <ol class=\"custom\">\n <li>First</li>\n <li>Second</li>\n <li>Third</li>\n <li>Fourth</li>\n <li>Fifth</li>\n <li>Sixth</li>\n <li>Seventh</li>\n <li>Eighth</li>\n <li>Ninth</li>\n <li>Tenth</li>\n </ol>\n \n </code></pre>\r\n</div>\r\n</div>\r\n</p>\n</blockquote>\n"
}
] | 2008/08/14 | [
"https://Stackoverflow.com/questions/10877",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/486/"
] | How can I left-align the numbers in an ordered list?
```
1. an item
// skip some items for brevity
9. another item
10. notice the 1 is under the 9, and the item contents also line up
```
Change the character after the number in an ordered list?
```
1) an item
```
Also is there a CSS solution to change from numbers to alphabetic/roman lists instead of using the type attribute on the ol element.
I am mostly interested in answers that work on Firefox 3. | This is the solution I have working in Firefox 3, Opera and Google Chrome. The list still displays in IE7 (but without the close bracket and left align numbers):
```css
ol {
counter-reset: item;
margin-left: 0;
padding-left: 0;
}
li {
display: block;
margin-bottom: .5em;
margin-left: 2em;
}
li::before {
display: inline-block;
content: counter(item) ") ";
counter-increment: item;
width: 2em;
margin-left: -2em;
}
```
```html
<ol>
<li>One</li>
<li>Two</li>
<li>Three</li>
<li>Four</li>
<li>Five</li>
<li>Six</li>
<li>Seven</li>
<li>Eight</li>
<li>Nine<br>Items</li>
<li>Ten<br>Items</li>
</ol>
```
**EDIT:** Included multiple line fix by strager
>
> Also is there a CSS solution to change from numbers to alphabetic/roman lists instead of using the type attribute on the ol element.
>
>
>
Refer to [list-style-type](http://www.w3.org/TR/CSS2/generate.html#lists) CSS property. Or when using counters the second argument accepts a list-style-type value. For example the following will use upper roman:
```
li::before {
content: counter(item, upper-roman) ") ";
counter-increment: item;
/* ... */
``` |
10,905 | <p>You should be able to create a generic form:</p>
<pre><code>public partial class MyGenericForm<T> :
Form where T : class
{
/* form code */
public List<T> TypedList { get; set; }
}
</code></pre>
<p>Is valid C#, and compiles. However the designer won't work and the form will throw a runtime exception if you have any images stating that it cannot find the resource.</p>
<p>I think this is because the windows forms designer assumes that the resources will be stored under the simple type's name.</p>
| [
{
"answer_id": 10906,
"author": "Keith",
"author_id": 905,
"author_profile": "https://Stackoverflow.com/users/905",
"pm_score": 0,
"selected": false,
"text": "<p>I have a hack to workaround this, which works but isn't ideal:</p>\n\n<p>Add a new class to the project that inherits the form with its simple name.</p>\n\n<pre><code>internal class MyGenericForm:\n MyGenericForm<object> { }\n</code></pre>\n\n<p>This means that although the designer is still wrong the expected simple type (i.e without <code><></code>) is still found.</p>\n"
},
{
"answer_id": 10907,
"author": "Matt Hamilton",
"author_id": 615,
"author_profile": "https://Stackoverflow.com/users/615",
"pm_score": 5,
"selected": true,
"text": "<p>Yes you can! Here's a blog post I made a while ago with the trick:</p>\n\n<p><a href=\"http://www.madprops.org/blog/designing-generic-forms/\" rel=\"noreferrer\">Designing Generic Forms</a></p>\n\n<p>Edit: Looks like you're already doing it this way. This method works fine so I wouldn't consider it too hacky.</p>\n"
},
{
"answer_id": 57163033,
"author": "Ali Osman Yavuz",
"author_id": 6342642,
"author_profile": "https://Stackoverflow.com/users/6342642",
"pm_score": 0,
"selected": false,
"text": "<p>You can do it in three steps.</p>\n\n<p>1) Replace in Form1.cs File</p>\n\n<pre><code>public partial class Form1<TEntity, TContext> : Formbase // where....\n</code></pre>\n\n<p>2) Replace in Form1.Designer.cs</p>\n\n<pre><code> partial class Form1<TEntity, TContext>\n</code></pre>\n\n<p>3) Create new file : Form1.Generic.cs (for opening design)</p>\n\n<pre><code>partial class Form1\n{\n} \n</code></pre>\n"
},
{
"answer_id": 60053845,
"author": "Nando",
"author_id": 2139449,
"author_profile": "https://Stackoverflow.com/users/2139449",
"pm_score": 0,
"selected": false,
"text": "<p>If paleolithic code doesn't affraid you</p>\n\n<pre><code> public static MyForm GetInstance<T>(T arg) where T : MyType\n{\n MyForm myForm = new MyForm();\n\n myForm.InitializeStuffs<T>(arg);\n myForm.StartPosition = myForm.CenterParent;\n\n return myForm;\n}\n</code></pre>\n\n<p>Use it </p>\n\n<pre><code>var myFormInstance = MyForm.GetInstance<T>(arg); myFormInstance.ShowDialog(this);\n</code></pre>\n"
}
] | 2008/08/14 | [
"https://Stackoverflow.com/questions/10905",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/905/"
] | You should be able to create a generic form:
```
public partial class MyGenericForm<T> :
Form where T : class
{
/* form code */
public List<T> TypedList { get; set; }
}
```
Is valid C#, and compiles. However the designer won't work and the form will throw a runtime exception if you have any images stating that it cannot find the resource.
I think this is because the windows forms designer assumes that the resources will be stored under the simple type's name. | Yes you can! Here's a blog post I made a while ago with the trick:
[Designing Generic Forms](http://www.madprops.org/blog/designing-generic-forms/)
Edit: Looks like you're already doing it this way. This method works fine so I wouldn't consider it too hacky. |
10,915 | <p>Warning - I am very new to NHibernate. I know this question seems simple - and I'm sure there's a simple answer, but I've been spinning my wheels for some time on this one. I am dealing with a legacy db which really can't be altered structurally. I have a details table which lists payment plans that have been accepted by a customer. Each payment plan has an ID which links back to a reference table to get the plan's terms, conditions, etc. In my object model, I have an AcceptedPlan class, and a Plan class. Originally, I used a many-to-one relationship from the detail table back to the ref table to model this relationship in NHibernate. I also created a one-to-many relationship going in the opposite direction from the Plan class over to the AcceptedPlan class. This was fine while I was simply reading data. I could go to my Plan object, which was a property of my AcceptedPlan class to read the plan's details. My problem arose when I had to start inserting new rows to the details table. From my reading, it seems the only way to create a new child object is to add it to the parent object and then save the session. But I don't want to have to create a new parent Plan object every time I want to create a new detail record. This seems like unnecessary overhead. Does anyone know if I am going about this in the wrong way?</p>
| [
{
"answer_id": 10993,
"author": "DavidWhitney",
"author_id": 1297,
"author_profile": "https://Stackoverflow.com/users/1297",
"pm_score": 0,
"selected": false,
"text": "<p>The approach I'd take to model this is as follows:</p>\n\n<p>Customer object contains an ICollection <PaymentPlan> PaymentPlans which represent the plans that customer has accepted.</p>\n\n<p>The PaymentPlan to the Customer would be mapped using a bag which uses the details table to establish which customer id's mapped to which PaymentPlans. Using cascade all-delete-orphan, if the customer was deleted, both the entries from details and the PaymentPlans that customer owned would be deleted.</p>\n\n<p>The PaymentPlan object contains a PlanTerms object which represented the terms of the payment plan.</p>\n\n<p>The PlanTerms would be mapped to a PaymentPlan using a many-to-one mapping cascading save-update which would just insert a reference to the relevant PlanTerms object in to the PaymentPlan.</p>\n\n<p>Using this model, you could create PlanTerms independantly and then when you add a new PaymentPlan to a customer, you'd create a new PaymentPlan object passing in the relevant PlanTerms object and then add it to the collection on the relevant Customer. Finally you'd save the Customer and let nhibernate cascade the save operation.</p>\n\n<p>You'd end up with a Customer object, a PaymentPlan object and a PlanTerms object with the Customer (customer table) owning instances of PaymentPlans (the details table) which all adhear to specific PlanTerms (the plan table).</p>\n\n<p>I've got some more concrete examples of the mapping syntax if required but it's probably best to work it through with your own model and I don't have enough information on the database tables to provide any specific examples.</p>\n"
},
{
"answer_id": 10996,
"author": "lomaxx",
"author_id": 493,
"author_profile": "https://Stackoverflow.com/users/493",
"pm_score": 0,
"selected": false,
"text": "<p>I don't know if this is possibly because my NHibernate experience is limited, but could you create a BaseDetail class which has just the properties for the Details as they map directly to the Detail table.</p>\n\n<p>Then create a second class that inherits from the BaseDetail class that has the additional Parent Plan object so you can create a BaseDetail class when you want to just create a Detail row and assign the PlanId to it, but if you need to populate a full Detail record with the Parent plan object you can use the inherited Detail class.</p>\n\n<p>I don't know if that makes a whole lot of sense, but let me know and I'll clarify further.</p>\n"
},
{
"answer_id": 11149,
"author": "Jon Limjap",
"author_id": 372,
"author_profile": "https://Stackoverflow.com/users/372",
"pm_score": 0,
"selected": false,
"text": "<p>I think the problem you have here is that your AcceptedOffer object contains a Plan object, and then your Plan object appears to contain an AcceptedOffers collection that contains AcceptedOffer objects. Same thing with Customers. The fact that the objects are a child of each other is what causes your problem, I think.</p>\n\n<p>Likewise, what makes your AcceptedOffer complex is it has a two responsibilities: it indicates offers included in a plan, it indicates acceptance by a customer. That violates the Single Responsibility Principle.</p>\n\n<p>You may have to differentiate between an Offer that is under a Plan, and an Offer that is accepted by customers. So here's what I'm going to do:</p>\n\n<ol>\n<li>Create a separate Offer object which does not have a state, e.g., it does not have a customer and it does not have a status -- it only has an OfferId and the Plan it belongs to as its attributes. </li>\n<li>Modify your Plan object to have an Offers collection (it does not have to have accepted offer in its context). </li>\n<li>Finally, modify your AcceptedOffer object so that it contains an Offer, the Customer, and a Status. Customer remains the same.</li>\n</ol>\n\n<p>I think this will sufficiently untangle your NHibernate mappings and object saving problems. :)</p>\n"
},
{
"answer_id": 11164,
"author": "DavidWhitney",
"author_id": 1297,
"author_profile": "https://Stackoverflow.com/users/1297",
"pm_score": 3,
"selected": true,
"text": "<p>I'd steer away from having child object containing their logical parent, it can get very messy and very recursive pretty quickly when you do that. I'd take a look at how you're intending to use the domain model before you do that sort of thing. You can easily still have the ID references in the tables and just leave them unmapped.</p>\n\n<p>Here are two example mappings that might nudge you in the right direction, I've had to adlib table names etc but it could possibly help. I'd probably also suggest mapping the StatusId to an enumeration.</p>\n\n<p>Pay attention to the way the bag effectivly maps the details table into a collection.</p>\n\n<pre><code><?xml version=\"1.0\" encoding=\"utf-8\" ?>\n<hibernate-mapping default-cascade=\"save-update\" xmlns=\"urn:nhibernate-mapping-2.2\">\n <class lazy=\"false\" name=\"Namespace.Customer, Namespace\" table=\"Customer\">\n <id name=\"Id\" type=\"Int32\" unsaved-value=\"0\">\n <column name=\"CustomerAccountId\" length=\"4\" sql-type=\"int\" not-null=\"true\" unique=\"true\" index=\"CustomerPK\"/>\n <generator class=\"native\" />\n </id>\n\n <bag name=\"AcceptedOffers\" inverse=\"false\" lazy=\"false\" cascade=\"all-delete-orphan\" table=\"details\">\n <key column=\"CustomerAccountId\" foreign-key=\"AcceptedOfferFK\"/>\n <many-to-many\n class=\"Namespace.AcceptedOffer, Namespace\"\n column=\"AcceptedOfferFK\"\n foreign-key=\"AcceptedOfferID\"\n lazy=\"false\"\n />\n </bag>\n\n </class>\n</hibernate-mapping>\n\n\n<?xml version=\"1.0\" encoding=\"utf-8\" ?>\n<hibernate-mapping default-cascade=\"save-update\" xmlns=\"urn:nhibernate-mapping-2.2\">\n <class lazy=\"false\" name=\"Namespace.AcceptedOffer, Namespace\" table=\"AcceptedOffer\">\n <id name=\"Id\" type=\"Int32\" unsaved-value=\"0\">\n <column name=\"AcceptedOfferId\" length=\"4\" sql-type=\"int\" not-null=\"true\" unique=\"true\" index=\"AcceptedOfferPK\"/>\n <generator class=\"native\" />\n </id>\n\n <many-to-one \n name=\"Plan\"\n class=\"Namespace.Plan, Namespace\"\n lazy=\"false\"\n cascade=\"save-update\"\n >\n <column name=\"PlanFK\" length=\"4\" sql-type=\"int\" not-null=\"false\"/>\n </many-to-one>\n\n <property name=\"StatusId\" type=\"Int32\">\n <column name=\"StatusId\" length=\"4\" sql-type=\"int\" not-null=\"true\"/>\n </property>\n\n </class>\n</hibernate-mapping>\n</code></pre>\n"
},
{
"answer_id": 11166,
"author": "Jon Limjap",
"author_id": 372,
"author_profile": "https://Stackoverflow.com/users/372",
"pm_score": 0,
"selected": false,
"text": "<p>A tip that may (or may not) be helpful in NHibernate: you can map your objects against Views as though the View was a table. Just specify the view name as a table name; as long as all NOT NULL fields are included in the view and the mapping it will work fine.</p>\n"
},
{
"answer_id": 11176,
"author": "DavidWhitney",
"author_id": 1297,
"author_profile": "https://Stackoverflow.com/users/1297",
"pm_score": 1,
"selected": false,
"text": "<p>Didn't see your database diagram whilst I was writing.</p>\n\n<pre><code><?xml version=\"1.0\" encoding=\"utf-8\" ?>\n<hibernate-mapping default-cascade=\"save-update\" xmlns=\"urn:nhibernate-mapping-2.2\">\n <class lazy=\"false\" name=\"Namespace.Customer, Namespace\" table=\"Customer\">\n <id name=\"Id\" type=\"Int32\" unsaved-value=\"0\">\n <column name=\"customer_id\" length=\"4\" sql-type=\"int\" not-null=\"true\" unique=\"true\" index=\"CustomerPK\"/>\n <generator class=\"native\" />\n </id>\n\n <bag name=\"AcceptedOffers\" inverse=\"false\" lazy=\"false\" cascade=\"all-delete-orphan\">\n <key column=\"accepted_offer_id\"/>\n <one-to-many class=\"Namespace.AcceptedOffer, Namespace\"/>\n </bag>\n\n </class>\n</hibernate-mapping>\n\n\n<?xml version=\"1.0\" encoding=\"utf-8\" ?>\n<hibernate-mapping default-cascade=\"save-update\" xmlns=\"urn:nhibernate-mapping-2.2\">\n <class lazy=\"false\" name=\"Namespace.AcceptedOffer, Namespace\" table=\"Accepted_Offer\">\n <id name=\"Id\" type=\"Int32\" unsaved-value=\"0\">\n <column name=\"accepted_offer_id\" length=\"4\" sql-type=\"int\" not-null=\"true\" unique=\"true\" />\n <generator class=\"native\" />\n </id>\n\n <many-to-one name=\"Plan\" class=\"Namespace.Plan, Namespace\" lazy=\"false\" cascade=\"save-update\">\n <column name=\"plan_id\" length=\"4\" sql-type=\"int\" not-null=\"false\"/>\n </many-to-one>\n\n </class>\n</hibernate-mapping>\n</code></pre>\n\n<p>Should probably do the trick (I've only done example mappings for the collections, you'll have to add other properties).</p>\n"
}
] | 2008/08/14 | [
"https://Stackoverflow.com/questions/10915",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1284/"
] | Warning - I am very new to NHibernate. I know this question seems simple - and I'm sure there's a simple answer, but I've been spinning my wheels for some time on this one. I am dealing with a legacy db which really can't be altered structurally. I have a details table which lists payment plans that have been accepted by a customer. Each payment plan has an ID which links back to a reference table to get the plan's terms, conditions, etc. In my object model, I have an AcceptedPlan class, and a Plan class. Originally, I used a many-to-one relationship from the detail table back to the ref table to model this relationship in NHibernate. I also created a one-to-many relationship going in the opposite direction from the Plan class over to the AcceptedPlan class. This was fine while I was simply reading data. I could go to my Plan object, which was a property of my AcceptedPlan class to read the plan's details. My problem arose when I had to start inserting new rows to the details table. From my reading, it seems the only way to create a new child object is to add it to the parent object and then save the session. But I don't want to have to create a new parent Plan object every time I want to create a new detail record. This seems like unnecessary overhead. Does anyone know if I am going about this in the wrong way? | I'd steer away from having child object containing their logical parent, it can get very messy and very recursive pretty quickly when you do that. I'd take a look at how you're intending to use the domain model before you do that sort of thing. You can easily still have the ID references in the tables and just leave them unmapped.
Here are two example mappings that might nudge you in the right direction, I've had to adlib table names etc but it could possibly help. I'd probably also suggest mapping the StatusId to an enumeration.
Pay attention to the way the bag effectivly maps the details table into a collection.
```
<?xml version="1.0" encoding="utf-8" ?>
<hibernate-mapping default-cascade="save-update" xmlns="urn:nhibernate-mapping-2.2">
<class lazy="false" name="Namespace.Customer, Namespace" table="Customer">
<id name="Id" type="Int32" unsaved-value="0">
<column name="CustomerAccountId" length="4" sql-type="int" not-null="true" unique="true" index="CustomerPK"/>
<generator class="native" />
</id>
<bag name="AcceptedOffers" inverse="false" lazy="false" cascade="all-delete-orphan" table="details">
<key column="CustomerAccountId" foreign-key="AcceptedOfferFK"/>
<many-to-many
class="Namespace.AcceptedOffer, Namespace"
column="AcceptedOfferFK"
foreign-key="AcceptedOfferID"
lazy="false"
/>
</bag>
</class>
</hibernate-mapping>
<?xml version="1.0" encoding="utf-8" ?>
<hibernate-mapping default-cascade="save-update" xmlns="urn:nhibernate-mapping-2.2">
<class lazy="false" name="Namespace.AcceptedOffer, Namespace" table="AcceptedOffer">
<id name="Id" type="Int32" unsaved-value="0">
<column name="AcceptedOfferId" length="4" sql-type="int" not-null="true" unique="true" index="AcceptedOfferPK"/>
<generator class="native" />
</id>
<many-to-one
name="Plan"
class="Namespace.Plan, Namespace"
lazy="false"
cascade="save-update"
>
<column name="PlanFK" length="4" sql-type="int" not-null="false"/>
</many-to-one>
<property name="StatusId" type="Int32">
<column name="StatusId" length="4" sql-type="int" not-null="true"/>
</property>
</class>
</hibernate-mapping>
``` |
10,926 | <p>I'm building a listing/grid control in a <code>Flex</code> application and using it in a <code>.NET</code> web application. To make a really long story short I am getting XML from a webservice of serialized objects. I have a page limit of how many things can be on a page. I've taken a data grid and made it page, sort across pages, and handle some basic filtering. </p>
<p>In regards to paging I'm using a Dictionary keyed on the page and storing the XML for that page. This way whenever a user comes back to a page that I've saved into this dictionary I can grab the XML from local memory instead of hitting the webservice. Basically, I'm caching the data retrieved from each call to the webservice for a page of data.</p>
<p>There are several things that can expire my cache. Filtering and sorting are the main reason. However, a user may edit a row of data in the grid by opening an editor. The data they edit could cause the data displayed in the row to be stale. I could easily go to the webservice and get the whole page of data, but since the page size is set at runtime I could be looking at a large amount of records to retrieve.</p>
<p>So let me now get to the heart of the issue that I am experiencing. In order to prevent getting the whole page of data back I make a call to the webservice asking for the completely updated record (the editor handles saving its data).</p>
<p>Since I'm using custom objects I need to serialize them on the server to XML (this is handled already for other portions of our software). All data is handled through XML in e4x. The cache in the Dictionary is stored as an XMLList.</p>
<p><strong>Now let me show you my code...</strong></p>
<pre><code>var idOfReplacee:String = this._WebService.GetSingleModelXml.lastResult.*[0].*[0].@Id;
var xmlToReplace:XMLList = this._DataPages[this._Options.PageIndex].Data.(@Id == idOfReplacee);
if(xmlToReplace.length() > 0)
{
delete (this._DataPages[this._Options.PageIndex].Data.(@Id == idOfReplacee)[0]);
this._DataPages[this._Options.PageIndex].Data += this._WebService.GetSingleModelXml.lastResult.*[0].*[0];
}
</code></pre>
<p>Basically, I get the id of the node I want to replace. Then I find it in the cache's Data property (<code>XMLList</code>). I make sure it exists since the filter on the second line returns the <code>XMLList</code>.</p>
<p>The problem I have is with the delete line. I cannot make that line delete that node from the list. The line following the delete line works. I've added the node to the list.</p>
<p>How do I replace or delete that node (meaning the node that I find from the filter statement out of the .Data property of the cache)???</p>
<p>Hopefully the underscores for all of my variables do not stay escaped when this is posted! otherwise <code>this.&#95 == this</code>._</p>
| [
{
"answer_id": 11048,
"author": "Matt Dillard",
"author_id": 863,
"author_profile": "https://Stackoverflow.com/users/863",
"pm_score": 0,
"selected": false,
"text": "<p>I don't immediately see the problem, so I can only venture a guess. The <code>delete</code> line that you've got is looking for the first item <em>at the top level</em> of the list which has an attribute \"Id\" with a value equal to <code>idOfReplacee</code>. Ensure that you don't need to dig deeper into the XML structure to find that matching id.</p>\n\n<p>Try this instead:</p>\n\n<pre><code>delete (this._DataPages[this._Options.PageIndex].Data..(@Id == idOfReplacee)[0]);\n</code></pre>\n\n<p>(Notice the extra '.' after <code>Data</code>). You could more easily debug this by setting a breakpoint on the second line of the code you posted, and ensure that the XMLList looks like you expect.</p>\n"
},
{
"answer_id": 11059,
"author": "Theo",
"author_id": 1109,
"author_profile": "https://Stackoverflow.com/users/1109",
"pm_score": 1,
"selected": false,
"text": "<p>Perhaps you could use <code>replace</code> instead?</p>\n\n<pre><code>var oldNode : XML = this._DataPages[this._Options.PageIndex].Data.(@Id == idOfReplacee)[0];\nvar newNode : XML = this._WebService.GetSingleModelXml.lastResult.*[0].*[0]; \n\noldNode.parent.replace(oldNode, newNode);\n</code></pre>\n"
},
{
"answer_id": 11527,
"author": "Mike G",
"author_id": 1290,
"author_profile": "https://Stackoverflow.com/users/1290",
"pm_score": 2,
"selected": false,
"text": "<p>Thanks for the answers guys.</p>\n\n<p>@Theo:\nI tried the replace several different ways. For some reason it would never error, but never update the list.</p>\n\n<p>@Matt:\nI figured out a solution. The issue wasn't coming from what you suggested, but from how the delete works with Lists (at least how I have it in this instance).</p>\n\n<p>The Data property of the _DataPages dictionary object is list of the definition nodes (was arrived at by a previous filtering of another XML document).</p>\n\n<pre><code><Models>\n <Definition Id='1' />\n <Definition Id='2' />\n</Models>\n</code></pre>\n\n<p>I ended up doing this little deal:</p>\n\n<pre><code>//gets the index of the node to replace from the same filter\nvar childIndex:int = (this._DataPages[this._Options.PageIndex].Data.(@Id == idOfReplacee)[0]).childIndex();\n//deletes the node from the list\ndelete this._DataPages[this._Options.PageIndex].Data[childIndex];\n//appends the new node from the webservice to the list\nthis._DataPages[this._Options.PageIndex].Data += this._WebService.GetSingleModelXml.lastResult.*[0].*[0];\n</code></pre>\n\n<p>So basically I had to get the index of the node in the XMLList that is the Data property. From there I could use the delete keyword to remove it from the list. The += adds my new node to the list.</p>\n\n<p>I'm so used to using the ActiveX or Mozilla XmlDocument stuff where you call \"SelectSingleNode\" and then use \"replaceChild\" to do this kind of stuff. Oh well, at least this is in some forum where someone else can find it. I do not know the procedure for what happens when I answer my own question. Perhaps this insight will help someone else come along and help answer the question better!</p>\n"
},
{
"answer_id": 37029264,
"author": "Harbs",
"author_id": 5475183,
"author_profile": "https://Stackoverflow.com/users/5475183",
"pm_score": 1,
"selected": false,
"text": "<p>I know this is an incredibly old question, but I don't see (what I think is) the simplest solution to this problem.</p>\n\n<p>Theo had the right direction here, but there's a number of errors with the way replace was being used (and the fact that pretty much everything in E4X is a function).</p>\n\n<p>I believe this will do the trick:</p>\n\n<pre><code>oldNode.parent().replace(oldNode.childIndex(), newNode);\n</code></pre>\n\n<p><code>replace()</code> can take a number of different types in the first parameter, but AFAIK, XML objects are not one of them.</p>\n"
}
] | 2008/08/14 | [
"https://Stackoverflow.com/questions/10926",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1290/"
] | I'm building a listing/grid control in a `Flex` application and using it in a `.NET` web application. To make a really long story short I am getting XML from a webservice of serialized objects. I have a page limit of how many things can be on a page. I've taken a data grid and made it page, sort across pages, and handle some basic filtering.
In regards to paging I'm using a Dictionary keyed on the page and storing the XML for that page. This way whenever a user comes back to a page that I've saved into this dictionary I can grab the XML from local memory instead of hitting the webservice. Basically, I'm caching the data retrieved from each call to the webservice for a page of data.
There are several things that can expire my cache. Filtering and sorting are the main reason. However, a user may edit a row of data in the grid by opening an editor. The data they edit could cause the data displayed in the row to be stale. I could easily go to the webservice and get the whole page of data, but since the page size is set at runtime I could be looking at a large amount of records to retrieve.
So let me now get to the heart of the issue that I am experiencing. In order to prevent getting the whole page of data back I make a call to the webservice asking for the completely updated record (the editor handles saving its data).
Since I'm using custom objects I need to serialize them on the server to XML (this is handled already for other portions of our software). All data is handled through XML in e4x. The cache in the Dictionary is stored as an XMLList.
**Now let me show you my code...**
```
var idOfReplacee:String = this._WebService.GetSingleModelXml.lastResult.*[0].*[0].@Id;
var xmlToReplace:XMLList = this._DataPages[this._Options.PageIndex].Data.(@Id == idOfReplacee);
if(xmlToReplace.length() > 0)
{
delete (this._DataPages[this._Options.PageIndex].Data.(@Id == idOfReplacee)[0]);
this._DataPages[this._Options.PageIndex].Data += this._WebService.GetSingleModelXml.lastResult.*[0].*[0];
}
```
Basically, I get the id of the node I want to replace. Then I find it in the cache's Data property (`XMLList`). I make sure it exists since the filter on the second line returns the `XMLList`.
The problem I have is with the delete line. I cannot make that line delete that node from the list. The line following the delete line works. I've added the node to the list.
How do I replace or delete that node (meaning the node that I find from the filter statement out of the .Data property of the cache)???
Hopefully the underscores for all of my variables do not stay escaped when this is posted! otherwise `this._ == this`.\_ | Thanks for the answers guys.
@Theo:
I tried the replace several different ways. For some reason it would never error, but never update the list.
@Matt:
I figured out a solution. The issue wasn't coming from what you suggested, but from how the delete works with Lists (at least how I have it in this instance).
The Data property of the \_DataPages dictionary object is list of the definition nodes (was arrived at by a previous filtering of another XML document).
```
<Models>
<Definition Id='1' />
<Definition Id='2' />
</Models>
```
I ended up doing this little deal:
```
//gets the index of the node to replace from the same filter
var childIndex:int = (this._DataPages[this._Options.PageIndex].Data.(@Id == idOfReplacee)[0]).childIndex();
//deletes the node from the list
delete this._DataPages[this._Options.PageIndex].Data[childIndex];
//appends the new node from the webservice to the list
this._DataPages[this._Options.PageIndex].Data += this._WebService.GetSingleModelXml.lastResult.*[0].*[0];
```
So basically I had to get the index of the node in the XMLList that is the Data property. From there I could use the delete keyword to remove it from the list. The += adds my new node to the list.
I'm so used to using the ActiveX or Mozilla XmlDocument stuff where you call "SelectSingleNode" and then use "replaceChild" to do this kind of stuff. Oh well, at least this is in some forum where someone else can find it. I do not know the procedure for what happens when I answer my own question. Perhaps this insight will help someone else come along and help answer the question better! |
10,985 | <p>Does anyone know how I can, in platform-independent C++ code prevent an object from being created on the heap? That is, for a class "Foo", I want to prevent users from doing this:</p>
<pre><code>Foo *ptr = new Foo;
</code></pre>
<p>and only allow them to do this:</p>
<pre><code>Foo myfooObject;
</code></pre>
<p>Does anyone have any ideas?</p>
<p>Cheers,</p>
| [
{
"answer_id": 11000,
"author": "David",
"author_id": 381,
"author_profile": "https://Stackoverflow.com/users/381",
"pm_score": 0,
"selected": false,
"text": "<p>You could declare a function called \"operator new\" inside the Foo class which would block the access to the normal form of new.</p>\n\n<p>Is this the kind of behaviour you want ?</p>\n"
},
{
"answer_id": 11003,
"author": "Nick",
"author_id": 1236,
"author_profile": "https://Stackoverflow.com/users/1236",
"pm_score": 4,
"selected": false,
"text": "<p>You could overload new for Foo and make it private. This would mean that the compiler would moan... unless you're creating an instance of Foo on the heap from within Foo. To catch this case, you could simply not write Foo's new method and then the linker would moan about undefined symbols.</p>\n\n<pre><code>class Foo {\nprivate:\n void* operator new(size_t size);\n};\n</code></pre>\n\n<p>PS. Yes, I know this can be circumvented easily. I'm really not recommending it - I think it's a bad idea - I was just answering the question! ;-)</p>\n"
},
{
"answer_id": 11011,
"author": "Will Dean",
"author_id": 987,
"author_profile": "https://Stackoverflow.com/users/987",
"pm_score": -1,
"selected": false,
"text": "<p>Not sure if this offers any compile-time opportunities, but have you looked at overloading the 'new' operator for your class?</p>\n"
},
{
"answer_id": 11014,
"author": "pauldoo",
"author_id": 755,
"author_profile": "https://Stackoverflow.com/users/755",
"pm_score": 3,
"selected": false,
"text": "<p>I don't know how to do it reliably and in a portable way.. but..</p>\n\n<p>If the object is on the stack then you might be able to assert within the constructor that the value of 'this' is always close to stack pointer. There's a good chance that the object will be on the stack if this is the case.</p>\n\n<p>I believe that not all platforms implement their stacks in the same direction, so you might want to do a one-off test when the app starts to verify which way the stack grows.. Or do some fudge:</p>\n\n<pre><code>FooClass::FooClass() {\n char dummy;\n ptrdiff_t displacement = &dummy - reinterpret_cast<char*>(this);\n if (displacement > 10000 || displacement < -10000) {\n throw \"Not on the stack - maybe..\";\n }\n}\n</code></pre>\n"
},
{
"answer_id": 11018,
"author": "pauldoo",
"author_id": 755,
"author_profile": "https://Stackoverflow.com/users/755",
"pm_score": 2,
"selected": false,
"text": "<p>@Nick</p>\n\n<p>This could be circumvented by creating a class that derives from or aggregates Foo. I think what I suggest (while not robust) would still work for derived and aggregating classes.</p>\n\n<p>E.g:</p>\n\n<pre><code>struct MyStruct {\n Foo m_foo;\n};\n\nMyStruct* p = new MyStruct();\n</code></pre>\n\n<p>Here I have created an instance of 'Foo' on the heap, bypassing Foo's hidden new operator.</p>\n"
},
{
"answer_id": 11022,
"author": "Lasse V. Karlsen",
"author_id": 267,
"author_profile": "https://Stackoverflow.com/users/267",
"pm_score": 0,
"selected": false,
"text": "<p>You could declare it as an interface and control the implementation class more directly from your own code.</p>\n"
},
{
"answer_id": 11299,
"author": "Patrick Johnmeyer",
"author_id": 363,
"author_profile": "https://Stackoverflow.com/users/363",
"pm_score": 6,
"selected": true,
"text": "<p><a href=\"https://stackoverflow.com/questions/10985/how-to-prevent-an-object-being-created-on-the-heap#11003\">Nick's answer</a> is a good starting point, but incomplete, as you actually need to overload:</p>\n\n<pre><code>private:\n void* operator new(size_t); // standard new\n void* operator new(size_t, void*); // placement new\n void* operator new[](size_t); // array new\n void* operator new[](size_t, void*); // placement array new\n</code></pre>\n\n<p>(Good coding practice would suggest you should also overload the delete and delete[] operators -- I would, but since they're not going to get called it isn't <em>really</em> necessary.) </p>\n\n<p><a href=\"https://stackoverflow.com/questions/10985/how-to-prevent-an-object-being-created-on-the-heap#11018\">Pauldoo</a> is also correct that this doesn't survive aggregating on Foo, although it does survive inheriting from Foo. You could do some template meta-programming magic to HELP prevent this, but it would not be immune to \"evil users\" and thus is probably not worth the complication. Documentation of how it should be used, and code review to ensure it is used properly, are the only ~100% way.</p>\n"
},
{
"answer_id": 37472123,
"author": "MerkX",
"author_id": 2251119,
"author_profile": "https://Stackoverflow.com/users/2251119",
"pm_score": 2,
"selected": false,
"text": "<p>Because debug headers can override the operator new signature, it is best to use the ... signatures as a complete remedy:</p>\n\n<pre><code>private:\nvoid* operator new(size_t, ...) = delete;\nvoid* operator new[](size_t, ...) = delete;\n</code></pre>\n"
},
{
"answer_id": 48359317,
"author": "Bala",
"author_id": 9245009,
"author_profile": "https://Stackoverflow.com/users/9245009",
"pm_score": 0,
"selected": false,
"text": "<p>this can be prevented by making constructors private and providing a static member to create an object in the stack </p>\n\n<pre><code>Class Foo\n{\n private:\n Foo();\n Foo(Foo& );\n public:\n static Foo GenerateInstance() { \n Foo a ; return a; \n }\n}\n</code></pre>\n\n<p>this will make creation of the object always in the stack.</p>\n"
}
] | 2008/08/14 | [
"https://Stackoverflow.com/questions/10985",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1304/"
] | Does anyone know how I can, in platform-independent C++ code prevent an object from being created on the heap? That is, for a class "Foo", I want to prevent users from doing this:
```
Foo *ptr = new Foo;
```
and only allow them to do this:
```
Foo myfooObject;
```
Does anyone have any ideas?
Cheers, | [Nick's answer](https://stackoverflow.com/questions/10985/how-to-prevent-an-object-being-created-on-the-heap#11003) is a good starting point, but incomplete, as you actually need to overload:
```
private:
void* operator new(size_t); // standard new
void* operator new(size_t, void*); // placement new
void* operator new[](size_t); // array new
void* operator new[](size_t, void*); // placement array new
```
(Good coding practice would suggest you should also overload the delete and delete[] operators -- I would, but since they're not going to get called it isn't *really* necessary.)
[Pauldoo](https://stackoverflow.com/questions/10985/how-to-prevent-an-object-being-created-on-the-heap#11018) is also correct that this doesn't survive aggregating on Foo, although it does survive inheriting from Foo. You could do some template meta-programming magic to HELP prevent this, but it would not be immune to "evil users" and thus is probably not worth the complication. Documentation of how it should be used, and code review to ensure it is used properly, are the only ~100% way. |
10,990 | <p>Sorry for the basic question - I'm a .NET developer and don't have much experience with LAMP setups.</p>
<p>I have a PHP site that will allow uploads to a specific folder. I have been told that this folder needs to be owned by the webserver user for the upload process to work, so I created the folder and then set permissions as such:</p>
<pre><code>chown apache:apache -R uploads/
chmod 755 -R uploads/
</code></pre>
<p>The only problem now is that the FTP user can not modify the uploaded files at all.</p>
<p>Is there a permission setting that will allow me to still upload files and then modify them later as a user other than the webserver user?</p>
| [
{
"answer_id": 11005,
"author": "Ryan Ahearn",
"author_id": 75,
"author_profile": "https://Stackoverflow.com/users/75",
"pm_score": 7,
"selected": true,
"text": "<p>You can create a new group with both the apache user and FTP user as members and then make the permission on the upload folder 775. This should give both the apache and FTP users the ability to write to the files in the folder but keep everyone else from modifying them.</p>\n"
},
{
"answer_id": 11025,
"author": "palehorse",
"author_id": 312,
"author_profile": "https://Stackoverflow.com/users/312",
"pm_score": 1,
"selected": false,
"text": "<p>I will add that if you are using SELinux that you need to make sure the type context is tmp_t You can accomplish this by using the chcon utility</p>\n\n<blockquote>\n <p>chcon -t tmp_t uploads</p>\n</blockquote>\n"
},
{
"answer_id": 11029,
"author": "Max",
"author_id": 1309,
"author_profile": "https://Stackoverflow.com/users/1309",
"pm_score": 4,
"selected": false,
"text": "<p>I would go with Ryan's answer if you really want to do this.</p>\n\n<p>In general on a *nix environment, you always want to err on giving away as little permissions as possible.</p>\n\n<p>9 times out of 10, 755 is the ideal permission for this - as the only user with the ability to modify the files will be the webserver. Change this to 775 with your ftp user in a group if you REALLY need to change this.</p>\n\n<p>Since you're new to php by your own admission, here's a helpful link for improving the security of your upload service:\n<a href=\"http://www.php.net/move_uploaded_file\" rel=\"noreferrer\"><code>move_uploaded_file</code></a></p>\n"
},
{
"answer_id": 9460755,
"author": "M. Ahmad Zafar",
"author_id": 462732,
"author_profile": "https://Stackoverflow.com/users/462732",
"pm_score": 1,
"selected": false,
"text": "<p>What is important is that the <code>apache</code> user and group should have minimum <code>read</code> access and in some cases <code>execute</code> access. For the rest you can give <code>0</code> access.</p>\n\n<p>This is the most safe setting.</p>\n"
},
{
"answer_id": 24689360,
"author": "CesareoAguirre",
"author_id": 960117,
"author_profile": "https://Stackoverflow.com/users/960117",
"pm_score": 0,
"selected": false,
"text": "<p>Remember also <code>CHOWN</code> or <code>chgrp</code> your website folder. Try <code>myusername# chown -R myusername:_www uploads</code></p>\n"
},
{
"answer_id": 35366052,
"author": "Lazarus Rising",
"author_id": 4299423,
"author_profile": "https://Stackoverflow.com/users/4299423",
"pm_score": 2,
"selected": false,
"text": "<p>I would support the idea of creating a ftp group that will have the rights to upload. However, i don't think it is necessary to give 775 permission. 7 stands for read, write, execute. Normally you want to allow certain groups to read and write, but depending on the case, execute may not be necessary. </p>\n"
},
{
"answer_id": 44402979,
"author": "Eric",
"author_id": 1568658,
"author_profile": "https://Stackoverflow.com/users/1568658",
"pm_score": -1,
"selected": false,
"text": "<p>Based on the answer from <code>@Ryan Ahearn</code>, following is what I did on <code>Ubuntu</code> 16.04 to create a user <code>front</code> that only has permission for nginx's web dir <code>/var/www/html</code>.</p>\n\n<p><strong>Steps:</strong></p>\n\n<pre>\n* pre-steps:\n * basic prepare of server,\n * create user 'dev'\n which will be the owner of \"/var/www/html\",\n * \n * install nginx,\n * \n* \n* create user 'front'\n sudo useradd -d /home/front -s /bin/bash front\n sudo passwd front\n\n # create home folder, if not exists yet,\n sudo mkdir /home/front\n # set owner of new home folder,\n sudo chown -R front:front /home/front\n\n # switch to user,\n su - front\n\n # copy .bashrc, if not exists yet,\n cp /etc/skel/.bashrc ~front/\n cp /etc/skel/.profile ~front/\n\n # enable color,\n vi ~front/.bashrc\n # uncomment the line start with \"force_color_prompt\",\n\n # exit user\n exit\n* \n* add to group 'dev',\n sudo usermod -a -G dev front\n* change owner of web dir,\n sudo chown -R dev:dev /var/www\n* change permission of web dir,\n chmod 775 $(find /var/www/html -type d)\n chmod 664 $(find /var/www/html -type f)\n* \n* re-login as 'front'\n to make group take effect,\n* \n* test\n* \n* ok\n* \n\n</pre>\n"
},
{
"answer_id": 73532081,
"author": "Julio Vinachi",
"author_id": 4929137,
"author_profile": "https://Stackoverflow.com/users/4929137",
"pm_score": 1,
"selected": false,
"text": "<pre><code>chmod -R 775 uploads/\nchown -R www-data uploads/\n</code></pre>\n<p>Important add to group public for web users standars in ubuntu <code>www-data</code></p>\n"
}
] | 2008/08/14 | [
"https://Stackoverflow.com/questions/10990",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1153/"
] | Sorry for the basic question - I'm a .NET developer and don't have much experience with LAMP setups.
I have a PHP site that will allow uploads to a specific folder. I have been told that this folder needs to be owned by the webserver user for the upload process to work, so I created the folder and then set permissions as such:
```
chown apache:apache -R uploads/
chmod 755 -R uploads/
```
The only problem now is that the FTP user can not modify the uploaded files at all.
Is there a permission setting that will allow me to still upload files and then modify them later as a user other than the webserver user? | You can create a new group with both the apache user and FTP user as members and then make the permission on the upload folder 775. This should give both the apache and FTP users the ability to write to the files in the folder but keep everyone else from modifying them. |
11,028 | <p>When I'm joining three or more tables together by a common column, I'd write my query like this:</p>
<pre><code>SELECT *
FROM a, b, c
WHERE a.id = b.id
AND b.id = c.id
</code></pre>
<p>a colleague recently asked my why I didn't do explicit <em>Join Transitive Closure</em> in my queries like this:</p>
<pre><code>SELECT *
FROM a, b, c
WHERE a.id = b.id
AND b.id = c.id
AND c.id = a.id
</code></pre>
<p>are the really any advantages to this? Surely the optimiser can imply this for itself?</p>
<p><em>edit: I know it's evil syntax, but it's a quick and dirty example of legitimate legacy code +1 @<a href="https://stackoverflow.com/questions/11028/what-are-the-advantages-of-explicit-join-transitive-closure-in-sql#11114">Stu</a> for cleaning it up</em></p>
| [
{
"answer_id": 11031,
"author": "Nick Berardi",
"author_id": 17,
"author_profile": "https://Stackoverflow.com/users/17",
"pm_score": 2,
"selected": false,
"text": "<p>No this syntax stems from the days before joins were in the language. Not sure of the problems associated with it, but there are definitely language constructs that are more supported for jointing tables.</p>\n"
},
{
"answer_id": 11035,
"author": "GateKiller",
"author_id": 383,
"author_profile": "https://Stackoverflow.com/users/383",
"pm_score": 1,
"selected": false,
"text": "<p>If you look at it from a mathematical point of view, your examples should yield the same results.</p>\n\n<p>a = b = c</p>\n\n<p>So your first example would yield the same results as the second, so no need to do the extra work.</p>\n"
},
{
"answer_id": 11038,
"author": "Lars Mæhlum",
"author_id": 960,
"author_profile": "https://Stackoverflow.com/users/960",
"pm_score": 1,
"selected": false,
"text": "<p>I just want to say that this kind of joining is the devils work.<br>\nJust think about it; the conditions for joining and filtering gets mixed together in the where statement.<br>\nWhat happens when you need to join across 20 tables and filter on 15 values?</p>\n\n<p>Again, just my $.02</p>\n"
},
{
"answer_id": 11041,
"author": "Keith",
"author_id": 905,
"author_profile": "https://Stackoverflow.com/users/905",
"pm_score": 1,
"selected": false,
"text": "<p>In Microsoft SQL the query plans for these two queries are identical - they are executed in the same way.</p>\n"
},
{
"answer_id": 11044,
"author": "Lasse V. Karlsen",
"author_id": 267,
"author_profile": "https://Stackoverflow.com/users/267",
"pm_score": 3,
"selected": true,
"text": "<p>You don't need to do this in todays database engines, but there was a time when things like that would give the query optimizer more hints as to possible index paths and thus to speedier results.</p>\n\n<p>These days that entire syntax is going out anyway.</p>\n"
},
{
"answer_id": 11114,
"author": "Stu",
"author_id": 414,
"author_profile": "https://Stackoverflow.com/users/414",
"pm_score": 2,
"selected": false,
"text": "<p>This is filthy, evil legacy syntax. You write this as</p>\n\n<blockquote>\n<pre><code>Select\n * -- Oh, and don't ever use *, either\nFrom\n A \n Inner Join B On A.ID = B.ID\n Inner Join C On B.ID = C.ID\n</code></pre>\n</blockquote>\n"
},
{
"answer_id": 11410,
"author": "Rad",
"author_id": 1349,
"author_profile": "https://Stackoverflow.com/users/1349",
"pm_score": -1,
"selected": false,
"text": "<p>That syntax has its uses though ... there are times when you find you need to join two tables on more than one field</p>\n"
},
{
"answer_id": 519910,
"author": "sdfx",
"author_id": 3445,
"author_profile": "https://Stackoverflow.com/users/3445",
"pm_score": 0,
"selected": false,
"text": "<p>This question is similar to this one here with a very in-depth explanation:</p>\n\n<p><a href=\"https://stackoverflow.com/questions/397089/sql-question-from-joel-spolsky-article\">SQL question from Joel Spolsky article</a></p>\n\n<p>The short answer is, that the explicit declaration of the transitiv property may speed the query up. This is because query optimization is not a trivial task and some SQL servers might have problems with it.</p>\n"
}
] | 2008/08/14 | [
"https://Stackoverflow.com/questions/11028",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1030/"
] | When I'm joining three or more tables together by a common column, I'd write my query like this:
```
SELECT *
FROM a, b, c
WHERE a.id = b.id
AND b.id = c.id
```
a colleague recently asked my why I didn't do explicit *Join Transitive Closure* in my queries like this:
```
SELECT *
FROM a, b, c
WHERE a.id = b.id
AND b.id = c.id
AND c.id = a.id
```
are the really any advantages to this? Surely the optimiser can imply this for itself?
*edit: I know it's evil syntax, but it's a quick and dirty example of legitimate legacy code +1 @[Stu](https://stackoverflow.com/questions/11028/what-are-the-advantages-of-explicit-join-transitive-closure-in-sql#11114) for cleaning it up* | You don't need to do this in todays database engines, but there was a time when things like that would give the query optimizer more hints as to possible index paths and thus to speedier results.
These days that entire syntax is going out anyway. |
11,043 | <p>What are the pros and cons of using table aliases in SQL? I personally try to avoid them, as I think they make the code less readable (especially when reading through large where/and statements), but I'd be interested in hearing any counter-points to this. When is it generally a good idea to use table aliases, and do you have any preferred formats?</p>
| [
{
"answer_id": 11049,
"author": "Lasse V. Karlsen",
"author_id": 267,
"author_profile": "https://Stackoverflow.com/users/267",
"pm_score": 5,
"selected": false,
"text": "<p>Well, there are some cases you <em>must</em> use them, like when you need to join to the same table twice in one query.</p>\n\n<p>It also depends on wether you have unique column names across tables. In our legacy database we have 3-letter prefixes for all columns, stemming from an abbreviated form from the table, simply because one ancient database system we were once compatible with didn't support table aliases all that well.</p>\n\n<p>If you have column names that occur in more than one table, specifying the table name as part of the column reference is a must, and thus a table alias will allow for a shorter syntax.</p>\n"
},
{
"answer_id": 11050,
"author": "Adam Lerman",
"author_id": 673,
"author_profile": "https://Stackoverflow.com/users/673",
"pm_score": 1,
"selected": false,
"text": "<p>IMHO, it doesn't really matter with short table names that make sense, I have on occasion worked on databases where the table name could be something like VWRECOFLY or some other random string (dictated by company policy) that really represents users, so in that case I find aliases really help to make the code FAR more readable. (users.username makes a lot more sence then VWRECOFLY.username)</p>\n"
},
{
"answer_id": 11053,
"author": "Rob Allen",
"author_id": 149,
"author_profile": "https://Stackoverflow.com/users/149",
"pm_score": 6,
"selected": true,
"text": "<p>Table aliases are a necessary evil when dealing with highly normalized schemas. For example, and I'm not the architect on this DB so bear with me, it can take 7 joins in order to get a clean and complete record back which includes a person's name, address, phone number and company affiliation. </p>\n\n<p>Rather than the somewhat standard single character aliases, I tend to favor short word aliases so the above example's SQL ends up looking like: </p>\n\n<pre><code>select person.FirstName\n ,person.LastName\n ,addr.StreetAddress\n ,addr.City\n ,addr.State\n ,addr.Zip\n ,phone.PhoneNumber\n ,company.CompanyName\nfrom tblPeople person\nleft outer join tblAffiliations affl on affl.personID = person.personID\nleft outer join tblCompany company on company.companyID = affl.companyID\n</code></pre>\n\n<p>... etc</p>\n"
},
{
"answer_id": 11056,
"author": "mbillard",
"author_id": 810,
"author_profile": "https://Stackoverflow.com/users/810",
"pm_score": 1,
"selected": false,
"text": "<p>I like long explicit table names (it's not uncommon to be more than 100 characters) because I use many tables and if the names aren't explicit, I might get confused as to what each table stores.</p>\n\n<p>So when I write a query, I tend to use shorter aliases that make sense within the scope of the query and that makes the code much more readable.</p>\n"
},
{
"answer_id": 11057,
"author": "Shawn",
"author_id": 26,
"author_profile": "https://Stackoverflow.com/users/26",
"pm_score": 2,
"selected": false,
"text": "<p>You need them if you're going to join a table to itself, or if you use the column again in a subquery...</p>\n"
},
{
"answer_id": 11064,
"author": "Keith",
"author_id": 905,
"author_profile": "https://Stackoverflow.com/users/905",
"pm_score": 3,
"selected": false,
"text": "<p>Microsoft SQL's query optimiser benefits from using either fully qualified names or aliases.</p>\n\n<p>Personally I prefer aliases, and unless I have a lot of tables they tend to be single letter ones.</p>\n\n<pre><code>--seems pretty readable to me ;-)\nselect a.Text\nfrom Question q\n inner join Answer a\n on a.QuestionId = q.QuestionId\n</code></pre>\n\n<p>There's also a practical limit on how long a Sql string can be executed - aliases make this limit easier to avoid.</p>\n"
},
{
"answer_id": 11072,
"author": "BTB",
"author_id": 961,
"author_profile": "https://Stackoverflow.com/users/961",
"pm_score": 3,
"selected": false,
"text": "<p><p>If I write a query myself (by typing into the editor and not using a designer) I always use aliases for the table name just so I only have to type the full table name once.</p>I really hate reading queries generated by a designer with the full table name as a prefix to every column name. </p>\n"
},
{
"answer_id": 11121,
"author": "Stu",
"author_id": 414,
"author_profile": "https://Stackoverflow.com/users/414",
"pm_score": 0,
"selected": false,
"text": "<p>I always use aliases, since to get proper performance on MSSQL you need to prefix with schema at all times. So you'll see a lot of</p>\n\n<blockquote>\n <p>Select\n Person.Name \n From<br>\n dbo.Person As Person</p>\n</blockquote>\n"
},
{
"answer_id": 12403,
"author": "Juha Syrjälä",
"author_id": 1431,
"author_profile": "https://Stackoverflow.com/users/1431",
"pm_score": -1,
"selected": false,
"text": "<p>Aliases are required when joining tables with columns that have identical names.</p>\n"
},
{
"answer_id": 14394,
"author": "Craig",
"author_id": 1073,
"author_profile": "https://Stackoverflow.com/users/1073",
"pm_score": 0,
"selected": false,
"text": "<p>I always use aliases when writing queries. Generally I try and abbreviate the table name to 1 or 2 representative letters. So Users becomes u and debtor_transactions becomes dt etc...</p>\n\n<p>It saves on typing and still carries some meaning. </p>\n\n<p>The shorter names makes it more readable to me as well.</p>\n"
},
{
"answer_id": 14406,
"author": "Sören Kuklau",
"author_id": 1600,
"author_profile": "https://Stackoverflow.com/users/1600",
"pm_score": 3,
"selected": false,
"text": "<p>I suppose the only thing that really speaks against them is excessive abstraction. If you will have a good idea what the alias refers to (good naming helps; 'a', 'b', 'c' can be quite problematic especially when you're reading the statement months or years later), I see nothing wrong with aliasing.</p>\n\n<p>As others have said, joins <em>require</em> them if you're using the same table (or view) multiple times, but even outside that situation, an alias can serve to clarify a data source's purpose in a particular context. In the alias's name, try to answer <em>why</em> you are accessing particular data, not <em>what</em> the data is.</p>\n"
},
{
"answer_id": 15160,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 1,
"selected": false,
"text": "<p>I always use aliases in my queries and it is part of the code guidebook in my company. First of all you need aliases or table names when there are columns with identical names in the joining tables. In my opinion the aliases improve readability in complex queries and allow me to see quickly the location of each columns. We even use aliases with single table queries, because experience has shown that single table queries don´t stay single table for long.</p>\n"
},
{
"answer_id": 26616,
"author": "Pulsehead",
"author_id": 2156,
"author_profile": "https://Stackoverflow.com/users/2156",
"pm_score": 2,
"selected": false,
"text": "<p>Aliases are great if you consider that my organization has table names like:\nSchemaName.DataPointName_SubPoint_Sub-SubPoint_Sub-Sub-SubPoint...\nMy team uses a pretty standard set of abbreviations, so the guesswork is minimized. We'll have say ProgramInformationDataPoint shortened to pidp, and submissions to just sub.</p>\n\n<p>The good thing is that once you get going in this manner and people agree with it, it makes those HAYUGE files just a little smaller and easier to manage. At least for me, fewer characters to convey the same info seems to go a little easier on my brain.</p>\n"
},
{
"answer_id": 202162,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 0,
"selected": false,
"text": "<p>If you do not use an alias, it's a bug in your code just waiting to happen.</p>\n\n<pre><code>SELECT Description -- actually in a\n FROM\n table_a a,\n table_b b\n WHERE\n a.ID = b.ID\n</code></pre>\n\n<p>What happens when you do a little thing like add a column called Description to Table_B. That's right, you'll get an error. Adding a column doesn't need to break anything. I never see writing good code, bug free code, as a necessary evil.</p>\n"
},
{
"answer_id": 265977,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 3,
"selected": false,
"text": "<h1>Good</h1>\n\n<p>As it has been mentioned multiple times before, it is a good practice to prefix <em>all</em> column names to easily see which column belongs to which table - and aliases are shorter than full table names so the query is easier to read and thus understand. If you use a good aliasing scheme of course.</p>\n\n<p>And if you create or read the code of an application, which uses externally stored or dynamically generated table names, then without aliases it is really hard to tell at the first glance what all those \"%s\"es or other placeholders stand for. It is not an extreme case, for example many web apps allow to customize the table name prefix at installation time.</p>\n"
},
{
"answer_id": 6299649,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 5,
"selected": false,
"text": "<p>Am I the only person here who really hates them?</p>\n\n<p>Generally, I don't use them unless I have to. I just really hate having to read something like</p>\n\n<pre><code>select a.id, a.region, a.firstname, a.blah, b.yadda, b.huminahumina, c.crap\nfrom table toys as a\ninner join prices as b on a.blah = b.yadda\ninner join customers as c on c.crap = something else\netc\n</code></pre>\n\n<p>When I read SQL, I like to know exactly what I'm selecting when I read it; aliases actually confuse me more because I've got to slog through lines of columns before I actually get to the table name, which generally represents information about the data that the alias doesn't. Perhaps it's okay if you made the aliases, but I commonly read questions on StackOverflow with code that seems to use aliases for no good reason. (Additionally, sometimes, someone will create an alias in a statement and just not use it. Why?)</p>\n\n<p>I think that table aliases are used so much because a lot of people are averse to typing. I don't think that's a good excuse, though. That excuse is the reason we end up with terrible variable naming, terrible function acronyms, bad code...I would take the time to type out the full name. I'm a quick typer, though, so maybe that has something to do with it. (Maybe in the future, when I've got carpal tunnel, I'll reconsider my opinion on aliases. :P ) I especially hate running across table aliases in PHP code, where I believe there's absolutely no reason to have to do that - you've only got to type it once!</p>\n\n<p>I always use column qualifiers in my statements, but I'm not averse to typing a lot, so I will gladly type the full name multiple times. (Granted, I do abuse MySQL's tab completion.) Unless it's a situation where I have to use an alias (like some described in other answers), I find the extra layer of abstraction cumbersome and unnecessary.</p>\n\n<p><strong>Edit:</strong> (Over a year later) I'm dealing with some stored procedures that use aliases (I did not write them and I'm new to this project), and they're kind of painful. I realize that the reason I don't like aliases is because of how they're defined. You know how it's generally good practice to declare variables at the top of your scope? (And usually at the beginning of a line?) Aliases in SQL don't follow this convention, which makes me grind my teeth. Thus, I have to search the entire code for a single alias to find out where it is (and what's frustrating is, I have to read through the logic before I find the alias declaration). If it weren't for that, I honestly might like the system better.</p>\n\n<p>If I ever write a stored procedure that someone else will have to deal with, I'm putting my alias definitions in a comment block at the beginning of the file, as a reference. I honestly can't understand how you guys don't go crazy without it.</p>\n"
},
{
"answer_id": 13294802,
"author": "Kirk Harrington",
"author_id": 1810120,
"author_profile": "https://Stackoverflow.com/users/1810120",
"pm_score": 2,
"selected": false,
"text": "<p>I LOVE aliases!!!! I have done some tests using them vs. not and have seen some processing gains. My guess is the processing gains would be higher when you're dealing with larger datasets and complex nested queries than without. If I'm able to test this, I'll let you know. </p>\n"
}
] | 2008/08/14 | [
"https://Stackoverflow.com/questions/11043",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/637/"
] | What are the pros and cons of using table aliases in SQL? I personally try to avoid them, as I think they make the code less readable (especially when reading through large where/and statements), but I'd be interested in hearing any counter-points to this. When is it generally a good idea to use table aliases, and do you have any preferred formats? | Table aliases are a necessary evil when dealing with highly normalized schemas. For example, and I'm not the architect on this DB so bear with me, it can take 7 joins in order to get a clean and complete record back which includes a person's name, address, phone number and company affiliation.
Rather than the somewhat standard single character aliases, I tend to favor short word aliases so the above example's SQL ends up looking like:
```
select person.FirstName
,person.LastName
,addr.StreetAddress
,addr.City
,addr.State
,addr.Zip
,phone.PhoneNumber
,company.CompanyName
from tblPeople person
left outer join tblAffiliations affl on affl.personID = person.personID
left outer join tblCompany company on company.companyID = affl.companyID
```
... etc |
11,045 | <p>How can I get a user-defined function to re-evaluate itself based on changed data in the spreadsheet?</p>
<p>I tried <strong><kbd>F9</kbd></strong> and <strong><kbd>Shift</kbd>+<kbd>F9</kbd></strong>.</p>
<p>The only thing that seems to work is editing the cell with the function call and then pressing Enter.</p>
| [
{
"answer_id": 11061,
"author": "Brian Sullivan",
"author_id": 767,
"author_profile": "https://Stackoverflow.com/users/767",
"pm_score": 4,
"selected": false,
"text": "<p>Okay, found this one myself. You can use <kbd>Ctrl</kbd>+<kbd>Alt</kbd>+<kbd>F9</kbd> to accomplish this.</p>\n"
},
{
"answer_id": 12018,
"author": "vzczc",
"author_id": 224,
"author_profile": "https://Stackoverflow.com/users/224",
"pm_score": 8,
"selected": true,
"text": "<p>You should use <code>Application.Volatile</code> in the top of your function:</p>\n\n<pre><code>Function doubleMe(d)\n Application.Volatile\n doubleMe = d * 2\nEnd Function\n</code></pre>\n\n<p>It will then reevaluate whenever the workbook changes (if your calculation is set to automatic).</p>\n"
},
{
"answer_id": 48548,
"author": "Robert Mearns",
"author_id": 5050,
"author_profile": "https://Stackoverflow.com/users/5050",
"pm_score": 5,
"selected": false,
"text": "<p>Some more information on the F9 keyboard shortcuts for calculation in Excel</p>\n\n<ul>\n<li><kbd>F9</kbd> Recalculates all worksheets in all open workbooks</li>\n<li><kbd>Shift</kbd>+ <kbd>F9</kbd> Recalculates the active worksheet</li>\n<li><kbd>Ctrl</kbd>+<kbd>Alt</kbd>+ <kbd>F9</kbd> Recalculates all worksheets in all open workbooks (Full recalculation)</li>\n<li><kbd>Shift</kbd> + <kbd>Ctrl</kbd>+<kbd>Alt</kbd>+ <kbd>F9</kbd> Rebuilds the dependency tree and does a full recalculation </li>\n</ul>\n"
},
{
"answer_id": 120363,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 4,
"selected": false,
"text": "<p>If you include ALL references to the spreadsheet data in the UDF parameter list, Excel will recalculate your function whenever the referenced data changes:</p>\n\n<pre><code>Public Function doubleMe(d As Variant)\n doubleMe = d * 2\nEnd Function\n</code></pre>\n\n<p>You can also use <code>Application.Volatile</code>, but this has the disadvantage of making your UDF always recalculate - even when it does not need to because the referenced data has not changed.</p>\n\n<pre><code>Public Function doubleMe()\n Application.Volatile\n doubleMe = Worksheets(\"Fred\").Range(\"A1\") * 2\nEnd Function\n</code></pre>\n"
},
{
"answer_id": 26507013,
"author": "Prashanth",
"author_id": 4169806,
"author_profile": "https://Stackoverflow.com/users/4169806",
"pm_score": 0,
"selected": false,
"text": "<pre><code>Public Sub UpdateMyFunctions()\n Dim myRange As Range\n Dim rng As Range\n\n 'Considering The Functions are in Range A1:B10\n Set myRange = ActiveSheet.Range(\"A1:B10\")\n\n For Each rng In myRange\n rng.Formula = rng.Formula\n Next\nEnd Sub\n</code></pre>\n"
},
{
"answer_id": 27279953,
"author": "ayman",
"author_id": 3180806,
"author_profile": "https://Stackoverflow.com/users/3180806",
"pm_score": 1,
"selected": false,
"text": "<p>To switch to Automatic:</p>\n\n<pre><code>Application.Calculation = xlCalculationAutomatic \n</code></pre>\n\n<p>To switch to Manual:</p>\n\n<pre><code>Application.Calculation = xlCalculationManual \n</code></pre>\n"
},
{
"answer_id": 30745135,
"author": "MfJ",
"author_id": 4992736,
"author_profile": "https://Stackoverflow.com/users/4992736",
"pm_score": 1,
"selected": false,
"text": "<p>This refreshes the calculation better than <code>Range(A:B).Calculate</code>:</p>\n\n<pre><code>Public Sub UpdateMyFunctions()\n Dim myRange As Range\n Dim rng As Range\n\n ' Assume the functions are in this range A1:B10.\n Set myRange = ActiveSheet.Range(\"A1:B10\")\n\n For Each rng In myRange\n rng.Formula = rng.Formula\n Next\nEnd Sub\n</code></pre>\n"
},
{
"answer_id": 47408310,
"author": "alex303411",
"author_id": 8978155,
"author_profile": "https://Stackoverflow.com/users/8978155",
"pm_score": 1,
"selected": false,
"text": "<p>The <code>Application.Volatile</code> doesn't work for recalculating a formula with my own function inside. I use the following function:\n<code>Application.CalculateFull</code></p>\n"
},
{
"answer_id": 57929883,
"author": "Gene Sorg",
"author_id": 12065022,
"author_profile": "https://Stackoverflow.com/users/12065022",
"pm_score": 1,
"selected": false,
"text": "<p>I found it best to only update the calculation when a specific cell is changed. Here is an example VBA code to place in the \"Worksheet\" \"Change\" event:</p>\n\n<pre><code>Private Sub Worksheet_Change(ByVal Target As Range)\n If Not Intersect(Target, Range(\"F3\")) Is Nothing Then\n Application.CalculateFull\n End If\nEnd Sub\n</code></pre>\n"
}
] | 2008/08/14 | [
"https://Stackoverflow.com/questions/11045",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/767/"
] | How can I get a user-defined function to re-evaluate itself based on changed data in the spreadsheet?
I tried **`F9`** and **`Shift`+`F9`**.
The only thing that seems to work is editing the cell with the function call and then pressing Enter. | You should use `Application.Volatile` in the top of your function:
```
Function doubleMe(d)
Application.Volatile
doubleMe = d * 2
End Function
```
It will then reevaluate whenever the workbook changes (if your calculation is set to automatic). |
11,085 | <p>In Perl, an object is just a reference to any of the basic Perl data types that has been blessed into a particular class. When you use the ref() function on an unblessed reference, you are told what data type the reference points to. However, when you call ref() on a blessed reference, you are returned the name of the package that reference has been blessed into. </p>
<p>I want to know the actual underlying type of the blessed reference. How can I determine this?</p>
| [
{
"answer_id": 42237,
"author": "Jagmal",
"author_id": 4406,
"author_profile": "https://Stackoverflow.com/users/4406",
"pm_score": 2,
"selected": false,
"text": "<p>And my first thought on this was: \"Objects in Perl are always hash refs, so what the hack?\"</p>\n\n<p>But, Scalar::Util::reftype is the answer. Thanks for putting the question here.</p>\n\n<p>Here is a code snippet to prove this.. (in case it is of any use to anyone).</p>\n\n<pre>\n$> perl -e 'use strict; use warnings \"all\";\n my $x = [1]; bless ($x, \"ABC::Def\");\n use Data::Dumper; print Dumper $x;\n print ref($x) . \"\\n\";\n use Scalar::Util \"reftype\"; print reftype($x) . \"\\n\"'`\n</pre>\n\n<p>Output:</p>\n\n<pre>\n$VAR1 = bless( [\n 1\n ], 'ABC::Def' );\nABC::Def\nARRAY\n</pre>\n"
},
{
"answer_id": 45629,
"author": "Leon Timmermans",
"author_id": 4727,
"author_profile": "https://Stackoverflow.com/users/4727",
"pm_score": 3,
"selected": false,
"text": "<p>You probably shouldn't do this. The underlying type of an object is an implementation detail you shouldn't mess with. Why would you want to know this?</p>\n"
},
{
"answer_id": 64160,
"author": "Michael Carman",
"author_id": 8233,
"author_profile": "https://Stackoverflow.com/users/8233",
"pm_score": 5,
"selected": true,
"text": "<p><code>Scalar::Util::reftype()</code> is the cleanest solution. The <a href=\"http://search.cpan.org/dist/Scalar-List-Utils/lib/Scalar/Util.pm\" rel=\"noreferrer\"><code>Scalar::Util</code></a> module was added to the Perl core in version 5.7 but is available for older versions (5.004 or later) from CPAN.</p>\n\n<p>You can also probe with <code>UNIVERSAL::isa()</code>:</p>\n\n<pre><code>$x->isa('HASH') # if $x is known to be an object\nUNIVERSAL::isa($x, 'HASH') # if $x might not be an object or reference\n</code></pre>\n\n<p>Obviously, you'd also have to check for <code>ARRAY</code> and <code>SCALAR</code> types. The UNIVERSAL module (which serves as the base class for all objects) has been part of the core since Perl 5.003.</p>\n\n<p>Another way -- easy but a little dirty -- is to stringify the reference. Assuming that the class hasn't overloaded stringification you'll get back something resembling <code>Class=HASH(0x1234ABCD)</code>, which you can parse to extract the underlying data type:</p>\n\n<pre><code>my $type = ($object =~ /=(.+)\\(0x[0-9a-f]+\\)$/i);\n</code></pre>\n"
}
] | 2008/08/14 | [
"https://Stackoverflow.com/questions/11085",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/166/"
] | In Perl, an object is just a reference to any of the basic Perl data types that has been blessed into a particular class. When you use the ref() function on an unblessed reference, you are told what data type the reference points to. However, when you call ref() on a blessed reference, you are returned the name of the package that reference has been blessed into.
I want to know the actual underlying type of the blessed reference. How can I determine this? | `Scalar::Util::reftype()` is the cleanest solution. The [`Scalar::Util`](http://search.cpan.org/dist/Scalar-List-Utils/lib/Scalar/Util.pm) module was added to the Perl core in version 5.7 but is available for older versions (5.004 or later) from CPAN.
You can also probe with `UNIVERSAL::isa()`:
```
$x->isa('HASH') # if $x is known to be an object
UNIVERSAL::isa($x, 'HASH') # if $x might not be an object or reference
```
Obviously, you'd also have to check for `ARRAY` and `SCALAR` types. The UNIVERSAL module (which serves as the base class for all objects) has been part of the core since Perl 5.003.
Another way -- easy but a little dirty -- is to stringify the reference. Assuming that the class hasn't overloaded stringification you'll get back something resembling `Class=HASH(0x1234ABCD)`, which you can parse to extract the underlying data type:
```
my $type = ($object =~ /=(.+)\(0x[0-9a-f]+\)$/i);
``` |
11,088 | <p>In Java, there is no such thing as an unsigned byte.</p>
<p>Working with some low level code, occasionally you need to work with bytes that have unsigned values greater than 128, which causes Java to interpret them as a negative number due to the MSB being used for sign.</p>
<p>What's a good way to work around this? (Saying don't use Java is not an option)</p>
| [
{
"answer_id": 11092,
"author": "Nick Berardi",
"author_id": 17,
"author_profile": "https://Stackoverflow.com/users/17",
"pm_score": -1,
"selected": false,
"text": "<p>I guess you could just use a short to store them. Not very efficient, but really the only option besides some herculean effort that I have seen.</p>\n"
},
{
"answer_id": 11098,
"author": "stimms",
"author_id": 361,
"author_profile": "https://Stackoverflow.com/users/361",
"pm_score": 0,
"selected": false,
"text": "<p>Probably your best bet is to use an integer rather than a byte. It has the room to allow for numbers greater than 128 without the overhead of having to create a special object to replace byte. </p>\n\n<p>This is also suggested by people smarter than me (everybody)</p>\n\n<ul>\n<li><a href=\"http://www.darksleep.com/player/JavaAndUnsignedTypes.html\" rel=\"nofollow noreferrer\">http://www.darksleep.com/player/JavaAndUnsignedTypes.html</a></li>\n<li><a href=\"http://www.jguru.com/faq/view.jsp?EID=13647\" rel=\"nofollow noreferrer\">http://www.jguru.com/faq/view.jsp?EID=13647</a></li>\n</ul>\n"
},
{
"answer_id": 11101,
"author": "pauldoo",
"author_id": 755,
"author_profile": "https://Stackoverflow.com/users/755",
"pm_score": 5,
"selected": true,
"text": "<p>When reading any single value from the array copy it into something like a short or an int and manually convert the negative number into the positive value it should be.</p>\n\n<pre><code>byte[] foobar = ..;\nint value = foobar[10];\nif (value < 0) value += 256 // Patch up the 'falsely' negative value\n</code></pre>\n\n<p>You can do a similar conversion when writing into the array.</p>\n"
},
{
"answer_id": 15657,
"author": "martinatime",
"author_id": 1353,
"author_profile": "https://Stackoverflow.com/users/1353",
"pm_score": 0,
"selected": false,
"text": "<p>The best way to do bit manipulation/unsigned bytes is through using <strong>int</strong>s. Even though they are signed they have plenty of spare bits (32 total) to treat as an unsigned byte. Also, all of the mathematical operators will convert smaller fixed precision numbers to <strong>int</strong>. Example:</p>\n\n<pre><code>short a = 1s;\nshort b = 2s;\nint c = a + b; // the result is up-converted\nshort small = (short)c; // must cast to get it back to short\n</code></pre>\n\n<p>Because of this it is best to just stick with integer and mask it to get the bits that you are interested in. Example:</p>\n\n<pre><code>int a = 32;\nint b = 128;\nint foo = (a + b) | 255;\n</code></pre>\n\n<p>Here is some more info on Java primitive types <a href=\"http://mindprod.com/jgloss/primitive.html\" rel=\"nofollow noreferrer\">http://mindprod.com/jgloss/primitive.html</a></p>\n\n<p>One last trivial note, there is one unsigned fixed precision number in Java. That is the <strong>char</strong> primitive.</p>\n"
},
{
"answer_id": 15874,
"author": "izb",
"author_id": 974,
"author_profile": "https://Stackoverflow.com/users/974",
"pm_score": 1,
"selected": false,
"text": "<p>Using ints is generally better than using shorts because java uses 32-bit values internally anyway (Even for bytes, unless in an array) so using ints will avoid unnecessary conversion to/from short values in the bytecode.</p>\n"
},
{
"answer_id": 19186,
"author": "ejack",
"author_id": 1377,
"author_profile": "https://Stackoverflow.com/users/1377",
"pm_score": 6,
"selected": false,
"text": "<p>It is actually possible to get rid of the if statement and the addition if you do it like this.</p>\n\n<pre><code>byte[] foobar = ..;\nint value = (foobar[10] & 0xff);\n</code></pre>\n\n<p>This way Java doesn't interpret the byte as a negative number and flip the sign bit on the integer also.</p>\n"
},
{
"answer_id": 5047679,
"author": "octo",
"author_id": 282400,
"author_profile": "https://Stackoverflow.com/users/282400",
"pm_score": 0,
"selected": false,
"text": "<p>I know this is a very late response, but I came across this thread when trying to do the exact same thing. The issue is simply trying to determine if a Java byte is >127.</p>\n\n<p>The simple solution is:</p>\n\n<pre><code>if((val & (byte)0x80) != 0) { ... }\n</code></pre>\n\n<p>If the real issue is >128 instead, just adding another condition to that if-statement will do the trick.</p>\n"
}
] | 2008/08/14 | [
"https://Stackoverflow.com/questions/11088",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1309/"
] | In Java, there is no such thing as an unsigned byte.
Working with some low level code, occasionally you need to work with bytes that have unsigned values greater than 128, which causes Java to interpret them as a negative number due to the MSB being used for sign.
What's a good way to work around this? (Saying don't use Java is not an option) | When reading any single value from the array copy it into something like a short or an int and manually convert the negative number into the positive value it should be.
```
byte[] foobar = ..;
int value = foobar[10];
if (value < 0) value += 256 // Patch up the 'falsely' negative value
```
You can do a similar conversion when writing into the array. |
11,099 | <p>In the case of languages that support single decision and action without brackets, such as the following example:</p>
<pre><code>if (var == true)
doSomething();
</code></pre>
<p>What is the preferred way of writing this? Should brackets always be used, or should their usage be left as a preference of the individual developer? Additionally, does this practice depend on the size of the code block, such as in the following example:</p>
<pre><code>if (var == 1)
doSomething(1);
else if (var > 1 && var < 10)
doSomething(2);
else
{
validate(var);
doSomething(var);
}
</code></pre>
| [
{
"answer_id": 11102,
"author": "Stu",
"author_id": 414,
"author_profile": "https://Stackoverflow.com/users/414",
"pm_score": 2,
"selected": false,
"text": "<p>It doesn't really matter, as long as you're consistent with it.</p>\n\n<p>There does seem to be a tendency to demand sameness within a single statement, i.e. if there's brackets in one branch, there's brackets everywhere. The Linux kernel coding standards, for one, mandate that.</p>\n"
},
{
"answer_id": 11105,
"author": "Chris Benard",
"author_id": 448,
"author_profile": "https://Stackoverflow.com/users/448",
"pm_score": 0,
"selected": false,
"text": "<p>Our boss makes us put { } after a decision statement no matter what, even if it's a single statement. It's really annoying to add two extra lines. The only exception is ternary operators.</p>\n\n<p>I guess it's a good thing I have my code monitor in portrait orientation at 1200x1600.</p>\n"
},
{
"answer_id": 11106,
"author": "Jon Limjap",
"author_id": 372,
"author_profile": "https://Stackoverflow.com/users/372",
"pm_score": 2,
"selected": false,
"text": "<p>My preference is to be consistent, e.g., if you use brackets on one block, use brackets all throughout even with just one statement:</p>\n\n<pre><code>if (cond1)\n{\n SomeOperation();\n Another();\n}\nelseif (cond2)\n{\n DoSomething();\n}\nelse\n{\n DoNothing();\n DoAnother();\n}\n</code></pre>\n\n<p>But if you have just a bunch of one liners:</p>\n\n<pre><code>if (cond1)\n DoFirst();\nelseif (cond2)\n DoSecond();\nelse\n DoElse();\n</code></pre>\n\n<p>Looks cleaner (if you don't mind the dummy method names ;) that way, but that's just me.</p>\n\n<p>This also applies to loop constructs and the like:</p>\n\n<pre><code>foreach (var s as Something)\n if (s == someCondition)\n yield return SomeMethod(s);\n</code></pre>\n\n<p>You should also consider that this is a convention that might be more suited to .NET (notice that Java peepz like to have their first curly brace in the same line as the if).</p>\n"
},
{
"answer_id": 11107,
"author": "stimms",
"author_id": 361,
"author_profile": "https://Stackoverflow.com/users/361",
"pm_score": 4,
"selected": true,
"text": "<p>There isn't really a right answer. This is what coding standards within the company are for. If you can keep it consistent across the whole company then it will be easy to read. I personally like</p>\n\n<pre><code>if ( a == b) {\n doSomething();\n}\nelse {\n doSomething();\n}\n</code></pre>\n\n<p>but this is a holy war. </p>\n"
},
{
"answer_id": 11110,
"author": "Ryan Ahearn",
"author_id": 75,
"author_profile": "https://Stackoverflow.com/users/75",
"pm_score": 1,
"selected": false,
"text": "<p>I've always used brackets at all times except for the case where I'm checking a variable for NULL before freeing it, like is necessary in C</p>\n\n<p>In that case, I make sure it's clear that it's a single statement by keeping everything on one line, like this:</p>\n\n<pre><code>if (aString) free(aString);\n</code></pre>\n"
},
{
"answer_id": 11116,
"author": "ZombieSheep",
"author_id": 377,
"author_profile": "https://Stackoverflow.com/users/377",
"pm_score": 3,
"selected": false,
"text": "<p>I recommend</p>\n\n<pre><code>if(a==b)\n{\n doSomething();\n}\n</code></pre>\n\n<p>because I find it far easier to do it up-front than to try to remember to add the braces when I add a second statement to to success condition...</p>\n\n<pre><code>if(a==b)\n doSomething();\n doSomethingElse();\n</code></pre>\n\n<p>is very different to </p>\n\n<pre><code>if(a==b)\n{\n doSomething();\n doSomethingElse();\n}\n</code></pre>\n\n<p>see <a href=\"http://www.joelonsoftware.com/articles/Wrong.html\" rel=\"nofollow noreferrer\">Joel's article</a> for further details</p>\n"
},
{
"answer_id": 11117,
"author": "Kev",
"author_id": 419,
"author_profile": "https://Stackoverflow.com/users/419",
"pm_score": 3,
"selected": false,
"text": "<p>I tend to use braces at all times. You can get some subtle bugs where you started off with something like:</p>\n\n<pre><code>if(something)\n DoOneThing();\nelse\n DoItDifferently();\n</code></pre>\n\n<p>and then decide to add another operation to the <code>else</code> clause and forget to wrap it in braces:</p>\n\n<pre><code>if(something)\n DoOneThing();\nelse\n DoItDifferently();\n AlwaysGetsCalled(); \n</code></pre>\n\n<p><code>AlwaysGetsCalled()</code> will always get called, and if you're sitting there at 3am wondering why your code is behaving all strange, something like that could elude you for quite some time. For this reason alone, I always use braces.</p>\n"
},
{
"answer_id": 11118,
"author": "Eldila",
"author_id": 889,
"author_profile": "https://Stackoverflow.com/users/889",
"pm_score": 1,
"selected": false,
"text": "<p>There is no right or wrong way to write the above statement. There are plenty of accepted coding <a href=\"http://en.wikipedia.org/wiki/Indent_style\" rel=\"nofollow noreferrer\">styles</a>. However, for me, I prefer keeping the coding style consist throughout the entire project. ie. If the project is using K&R style, you should use K&R.</p>\n"
},
{
"answer_id": 11119,
"author": "Nick",
"author_id": 1236,
"author_profile": "https://Stackoverflow.com/users/1236",
"pm_score": 2,
"selected": false,
"text": "<p>I would strongly advocate <em>always</em> using braces, even when they're optional. Why? Take this chunk of C++ code:</p>\n\n<pre><code>if (var == 1)\n doSomething();\ndoSomethingElse();\n</code></pre>\n\n<p>Now, someone comes along who isn't really paying enough attention and decides that something extra needs to happen if (var == 1), so they do this:</p>\n\n<pre><code>if (var == 1)\n doSomething();\n doSomethingExtra();\ndoSomethingElse();\n</code></pre>\n\n<p>It's all still beautifully indented but it won't do what was intended.</p>\n\n<p>By always using braces, you're more likely to avoid this sort of bug.</p>\n"
},
{
"answer_id": 11120,
"author": "Pascal Paradis",
"author_id": 1291,
"author_profile": "https://Stackoverflow.com/users/1291",
"pm_score": 0,
"selected": false,
"text": "<p>I tend to agree with Joel Spolsky on that one with that article (<a href=\"http://www.joelonsoftware.com/articles/Wrong.html\" rel=\"nofollow noreferrer\">Making Wrong Code Look Wrong</a>) with the following code example : </p>\n\n<pre><code>if (i != 0)\nbar(i);\nfoo(i);\n</code></pre>\n\n<p>Foo is now unconditionnal. Wich is real bad!</p>\n\n<p>I always use brackets for decision statements. It helps code maintainability and it makes the code less bug prone.</p>\n"
},
{
"answer_id": 11134,
"author": "Baltimark",
"author_id": 1179,
"author_profile": "https://Stackoverflow.com/users/1179",
"pm_score": 0,
"selected": false,
"text": "<p>I prefer </p>\n\n<pre><code>if (cond)\n {\n //statement\n }\n</code></pre>\n\n<p>even with only a single statement. If you were going to write something once, had no doubts that it worked, and never planned on another coder ever looking at that code, go ahead and use whatever format you want. But, what does the extra bracketing really cost you? Less time in the course of a year than it takes to type up this post. </p>\n\n<p>Yes, I like to indent my brackets to the level of the block, too. </p>\n\n<p>Python is nice in that the indentation defines the block. The question is moot in a language like that. </p>\n"
},
{
"answer_id": 11167,
"author": "t3rse",
"author_id": 64,
"author_profile": "https://Stackoverflow.com/users/64",
"pm_score": 0,
"selected": false,
"text": "<p>I used to follow the \"use curly braces always\" line like an apparatchik. However, I've modified my style to allow for omitting them on single line conditional expressions: </p>\n\n<pre><code>if(!ok)return;\n</code></pre>\n\n<p>For any multistatement scenario though I'm still of the opinion that braces should be mandatory: </p>\n\n<pre><code>if(!ok){\n\n do();\n\n that();\n\n thing();\n}\n</code></pre>\n"
},
{
"answer_id": 11283,
"author": "James A. Rosen",
"author_id": 1190,
"author_profile": "https://Stackoverflow.com/users/1190",
"pm_score": 1,
"selected": false,
"text": "<p>Ruby nicely obviates one issue in the discussion. The standard for a one-liner is:</p>\n\n<pre><code>do_something if (a == b)\n</code></pre>\n\n<p>and for a multi-line:</p>\n\n<pre><code>if (a == b)\n do_something\n do_something_else\nend\n</code></pre>\n\n<p>This allows concise one-line statements, but it forces you to reorganize the statement if you go from single- to multi-line.</p>\n\n<p>This is not (yet) available in Java, nor in many other languages, AFAIK.</p>\n"
},
{
"answer_id": 11542,
"author": "Adam Lassek",
"author_id": 1249,
"author_profile": "https://Stackoverflow.com/users/1249",
"pm_score": 1,
"selected": false,
"text": "<p>As others have mentioned, doing an if statement in two lines without braces can lead to confusion:</p>\n\n<pre><code>if (a == b)\n DoSomething();\n DoSomethingElse(); <-- outside if statement\n</code></pre>\n\n<p>so I place it on a single line if I can do so without hurting readability:</p>\n\n<pre><code>if (a == b) DoSomething();\n</code></pre>\n\n<p>and at all other times I use braces.</p>\n\n<p>Ternary operators are a little different. Most of the time I do them on one line:</p>\n\n<pre><code>var c = (a == b) ? DoSomething() : DoSomethingElse();\n</code></pre>\n\n<p>but sometimes the statements have nested function calls, or lambda expressions which \nmake a one-line statement difficult to parse visually, so I prefer something like this:</p>\n\n<pre><code>var c = (a == b)\n ? AReallyReallyLongFunctionName()\n : AnotherReallyReallyLongFunctionOrStatement();\n</code></pre>\n\n<p>Still more concise than an if/else block but easy to see what's going on.</p>\n"
},
{
"answer_id": 11557,
"author": "Rytmis",
"author_id": 266,
"author_profile": "https://Stackoverflow.com/users/266",
"pm_score": 2,
"selected": false,
"text": "<p>Chalk this one to lack of experience, but during my seven-year stint as a code monkey I've <em>never</em> actually seen anyone make the mistake of not adding braces when adding code to a block that doesn't have braces. That's precisely <em>zero</em> times. </p>\n\n<p>And before the wisecrackers get to it, no, the reason wasn't \"everyone always uses braces\".</p>\n\n<p>So, an honest question -- I really would like to get actual replies instead of just downvotes: does that ever actually happen?</p>\n\n<p>(Edit: I've heard enough outsourcing horror stories to clarify a bit: does it ever actually happen to <strong>competent programmers</strong>?)</p>\n"
},
{
"answer_id": 39418,
"author": "Dewm Solo",
"author_id": 4225,
"author_profile": "https://Stackoverflow.com/users/4225",
"pm_score": 2,
"selected": false,
"text": "<p>I personnally side with McConnell's explanation from Code Complete.</p>\n\n<p>Use them whenever you can. They enhance your code's readability and remove the few and scarce confusions that might occur.</p>\n\n<p>There is one thing that's more important though....Consistency. Which ever style you use,make sure you always do it the same way.</p>\n\n<p>Start writing stuff like:</p>\n\n<pre>\n<code>\nIf A == true\n FunctA();\n\nIf B == \"Test\"\n{\n FunctB();\n}\n</code>\n</pre>\n\n<p>You are bound to end up looking for an odd bug where the compiler won't understand what you were trying to do and that will be hard to find.</p>\n\n<p>Basically find the one you are comfortable writing everytime and stick to it. I do believe in using the block delimeters('{', '}') as much as possible is the way to go.</p>\n\n<p>I don't want to start a question inside another, but there is something related to this that I want to mention to get your mental juices going. One the decision of using the brackets has been made. Where do you put the opening bracket? On the same line as the statement or underneath. Indented brackets or not?</p>\n\n<pre>\n<code>\nIf A == false {\n //calls and whatnot\n}\n//or\nIf B == \"BlaBla\"\n{\n //calls and whatnot\n}\n//or\nIf C == B\n {\n //calls and whatnot\n }\n</code>\n</pre>\n\n<p>Please don't answer to this since this would be a new question. If I see an interest in this I will open a new question your input.</p>\n"
},
{
"answer_id": 77547,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 0,
"selected": false,
"text": "<p>I use curly braces around every statement if and only if at least one of them requires it.</p>\n"
},
{
"answer_id": 78060,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 1,
"selected": false,
"text": "<p>Sun's <a href=\"http://java.sun.com/docs/codeconv/\" rel=\"nofollow noreferrer\">Code Conventions for the Java programming Language</a> has <a href=\"http://java.sun.com/docs/codeconv/html/CodeConventions.doc6.html#449\" rel=\"nofollow noreferrer\">this</a> to say:</p>\n\n<blockquote>\n <p>The if-else class of statements should\n have the following form:</p>\n\n<pre><code>if (condition) {\n statements;\n}\n\nif (condition) {\n statements;\n} else {\n statements;\n}\n\nif (condition) {\n statements;\n} else if (condition) {\n statements;\n} else {\n statements;\n}\n</code></pre>\n</blockquote>\n"
},
{
"answer_id": 85924,
"author": "Brad Gilbert",
"author_id": 1337,
"author_profile": "https://Stackoverflow.com/users/1337",
"pm_score": 0,
"selected": false,
"text": "<p>In Perl if you are doing a simple test, sometime you will write it in this form:</p>\n\n<pre><code>do_something if condition;\n\ndo_something unless condition;\n</code></pre>\n\n<p>Which can be really useful to check the arguments at the start of a subroutine.</p>\n\n<pre><code>sub test{\n my($self,@args) = @_;\n\n return undef unless defined $self;\n\n # rest of code goes here\n\n}\n</code></pre>\n"
},
{
"answer_id": 639794,
"author": "David Thornley",
"author_id": 14148,
"author_profile": "https://Stackoverflow.com/users/14148",
"pm_score": 0,
"selected": false,
"text": "<p>The golden rule is that, when working in an existing project, follow those coding standards.</p>\n\n<p>When I'm at home, I have two forms.</p>\n\n<p>The first is the single line:</p>\n\n<pre><code>if (condition) doThis();\n</code></pre>\n\n<p>and the second is for multiple lines:</p>\n\n<pre><code>if (condition) {\n doThis();\n}\n</code></pre>\n"
}
] | 2008/08/14 | [
"https://Stackoverflow.com/questions/11099",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1185/"
] | In the case of languages that support single decision and action without brackets, such as the following example:
```
if (var == true)
doSomething();
```
What is the preferred way of writing this? Should brackets always be used, or should their usage be left as a preference of the individual developer? Additionally, does this practice depend on the size of the code block, such as in the following example:
```
if (var == 1)
doSomething(1);
else if (var > 1 && var < 10)
doSomething(2);
else
{
validate(var);
doSomething(var);
}
``` | There isn't really a right answer. This is what coding standards within the company are for. If you can keep it consistent across the whole company then it will be easy to read. I personally like
```
if ( a == b) {
doSomething();
}
else {
doSomething();
}
```
but this is a holy war. |
11,112 | <p>Most wiki software I've presents lots of "features" on their pages. This is fine for desktop users, but is annoying when using an iPhone or other mobile device. <br /><br />I'd prefer pages that just had the content, along with maybe an Edit button and a Search button. The editors are also often too fancy for mobile users; a simple multi-line edit field would be better for mobile users than a bunch of formatting controls.</p>
<p>What is a good wiki package for mobile users?</p>
| [
{
"answer_id": 11102,
"author": "Stu",
"author_id": 414,
"author_profile": "https://Stackoverflow.com/users/414",
"pm_score": 2,
"selected": false,
"text": "<p>It doesn't really matter, as long as you're consistent with it.</p>\n\n<p>There does seem to be a tendency to demand sameness within a single statement, i.e. if there's brackets in one branch, there's brackets everywhere. The Linux kernel coding standards, for one, mandate that.</p>\n"
},
{
"answer_id": 11105,
"author": "Chris Benard",
"author_id": 448,
"author_profile": "https://Stackoverflow.com/users/448",
"pm_score": 0,
"selected": false,
"text": "<p>Our boss makes us put { } after a decision statement no matter what, even if it's a single statement. It's really annoying to add two extra lines. The only exception is ternary operators.</p>\n\n<p>I guess it's a good thing I have my code monitor in portrait orientation at 1200x1600.</p>\n"
},
{
"answer_id": 11106,
"author": "Jon Limjap",
"author_id": 372,
"author_profile": "https://Stackoverflow.com/users/372",
"pm_score": 2,
"selected": false,
"text": "<p>My preference is to be consistent, e.g., if you use brackets on one block, use brackets all throughout even with just one statement:</p>\n\n<pre><code>if (cond1)\n{\n SomeOperation();\n Another();\n}\nelseif (cond2)\n{\n DoSomething();\n}\nelse\n{\n DoNothing();\n DoAnother();\n}\n</code></pre>\n\n<p>But if you have just a bunch of one liners:</p>\n\n<pre><code>if (cond1)\n DoFirst();\nelseif (cond2)\n DoSecond();\nelse\n DoElse();\n</code></pre>\n\n<p>Looks cleaner (if you don't mind the dummy method names ;) that way, but that's just me.</p>\n\n<p>This also applies to loop constructs and the like:</p>\n\n<pre><code>foreach (var s as Something)\n if (s == someCondition)\n yield return SomeMethod(s);\n</code></pre>\n\n<p>You should also consider that this is a convention that might be more suited to .NET (notice that Java peepz like to have their first curly brace in the same line as the if).</p>\n"
},
{
"answer_id": 11107,
"author": "stimms",
"author_id": 361,
"author_profile": "https://Stackoverflow.com/users/361",
"pm_score": 4,
"selected": true,
"text": "<p>There isn't really a right answer. This is what coding standards within the company are for. If you can keep it consistent across the whole company then it will be easy to read. I personally like</p>\n\n<pre><code>if ( a == b) {\n doSomething();\n}\nelse {\n doSomething();\n}\n</code></pre>\n\n<p>but this is a holy war. </p>\n"
},
{
"answer_id": 11110,
"author": "Ryan Ahearn",
"author_id": 75,
"author_profile": "https://Stackoverflow.com/users/75",
"pm_score": 1,
"selected": false,
"text": "<p>I've always used brackets at all times except for the case where I'm checking a variable for NULL before freeing it, like is necessary in C</p>\n\n<p>In that case, I make sure it's clear that it's a single statement by keeping everything on one line, like this:</p>\n\n<pre><code>if (aString) free(aString);\n</code></pre>\n"
},
{
"answer_id": 11116,
"author": "ZombieSheep",
"author_id": 377,
"author_profile": "https://Stackoverflow.com/users/377",
"pm_score": 3,
"selected": false,
"text": "<p>I recommend</p>\n\n<pre><code>if(a==b)\n{\n doSomething();\n}\n</code></pre>\n\n<p>because I find it far easier to do it up-front than to try to remember to add the braces when I add a second statement to to success condition...</p>\n\n<pre><code>if(a==b)\n doSomething();\n doSomethingElse();\n</code></pre>\n\n<p>is very different to </p>\n\n<pre><code>if(a==b)\n{\n doSomething();\n doSomethingElse();\n}\n</code></pre>\n\n<p>see <a href=\"http://www.joelonsoftware.com/articles/Wrong.html\" rel=\"nofollow noreferrer\">Joel's article</a> for further details</p>\n"
},
{
"answer_id": 11117,
"author": "Kev",
"author_id": 419,
"author_profile": "https://Stackoverflow.com/users/419",
"pm_score": 3,
"selected": false,
"text": "<p>I tend to use braces at all times. You can get some subtle bugs where you started off with something like:</p>\n\n<pre><code>if(something)\n DoOneThing();\nelse\n DoItDifferently();\n</code></pre>\n\n<p>and then decide to add another operation to the <code>else</code> clause and forget to wrap it in braces:</p>\n\n<pre><code>if(something)\n DoOneThing();\nelse\n DoItDifferently();\n AlwaysGetsCalled(); \n</code></pre>\n\n<p><code>AlwaysGetsCalled()</code> will always get called, and if you're sitting there at 3am wondering why your code is behaving all strange, something like that could elude you for quite some time. For this reason alone, I always use braces.</p>\n"
},
{
"answer_id": 11118,
"author": "Eldila",
"author_id": 889,
"author_profile": "https://Stackoverflow.com/users/889",
"pm_score": 1,
"selected": false,
"text": "<p>There is no right or wrong way to write the above statement. There are plenty of accepted coding <a href=\"http://en.wikipedia.org/wiki/Indent_style\" rel=\"nofollow noreferrer\">styles</a>. However, for me, I prefer keeping the coding style consist throughout the entire project. ie. If the project is using K&R style, you should use K&R.</p>\n"
},
{
"answer_id": 11119,
"author": "Nick",
"author_id": 1236,
"author_profile": "https://Stackoverflow.com/users/1236",
"pm_score": 2,
"selected": false,
"text": "<p>I would strongly advocate <em>always</em> using braces, even when they're optional. Why? Take this chunk of C++ code:</p>\n\n<pre><code>if (var == 1)\n doSomething();\ndoSomethingElse();\n</code></pre>\n\n<p>Now, someone comes along who isn't really paying enough attention and decides that something extra needs to happen if (var == 1), so they do this:</p>\n\n<pre><code>if (var == 1)\n doSomething();\n doSomethingExtra();\ndoSomethingElse();\n</code></pre>\n\n<p>It's all still beautifully indented but it won't do what was intended.</p>\n\n<p>By always using braces, you're more likely to avoid this sort of bug.</p>\n"
},
{
"answer_id": 11120,
"author": "Pascal Paradis",
"author_id": 1291,
"author_profile": "https://Stackoverflow.com/users/1291",
"pm_score": 0,
"selected": false,
"text": "<p>I tend to agree with Joel Spolsky on that one with that article (<a href=\"http://www.joelonsoftware.com/articles/Wrong.html\" rel=\"nofollow noreferrer\">Making Wrong Code Look Wrong</a>) with the following code example : </p>\n\n<pre><code>if (i != 0)\nbar(i);\nfoo(i);\n</code></pre>\n\n<p>Foo is now unconditionnal. Wich is real bad!</p>\n\n<p>I always use brackets for decision statements. It helps code maintainability and it makes the code less bug prone.</p>\n"
},
{
"answer_id": 11134,
"author": "Baltimark",
"author_id": 1179,
"author_profile": "https://Stackoverflow.com/users/1179",
"pm_score": 0,
"selected": false,
"text": "<p>I prefer </p>\n\n<pre><code>if (cond)\n {\n //statement\n }\n</code></pre>\n\n<p>even with only a single statement. If you were going to write something once, had no doubts that it worked, and never planned on another coder ever looking at that code, go ahead and use whatever format you want. But, what does the extra bracketing really cost you? Less time in the course of a year than it takes to type up this post. </p>\n\n<p>Yes, I like to indent my brackets to the level of the block, too. </p>\n\n<p>Python is nice in that the indentation defines the block. The question is moot in a language like that. </p>\n"
},
{
"answer_id": 11167,
"author": "t3rse",
"author_id": 64,
"author_profile": "https://Stackoverflow.com/users/64",
"pm_score": 0,
"selected": false,
"text": "<p>I used to follow the \"use curly braces always\" line like an apparatchik. However, I've modified my style to allow for omitting them on single line conditional expressions: </p>\n\n<pre><code>if(!ok)return;\n</code></pre>\n\n<p>For any multistatement scenario though I'm still of the opinion that braces should be mandatory: </p>\n\n<pre><code>if(!ok){\n\n do();\n\n that();\n\n thing();\n}\n</code></pre>\n"
},
{
"answer_id": 11283,
"author": "James A. Rosen",
"author_id": 1190,
"author_profile": "https://Stackoverflow.com/users/1190",
"pm_score": 1,
"selected": false,
"text": "<p>Ruby nicely obviates one issue in the discussion. The standard for a one-liner is:</p>\n\n<pre><code>do_something if (a == b)\n</code></pre>\n\n<p>and for a multi-line:</p>\n\n<pre><code>if (a == b)\n do_something\n do_something_else\nend\n</code></pre>\n\n<p>This allows concise one-line statements, but it forces you to reorganize the statement if you go from single- to multi-line.</p>\n\n<p>This is not (yet) available in Java, nor in many other languages, AFAIK.</p>\n"
},
{
"answer_id": 11542,
"author": "Adam Lassek",
"author_id": 1249,
"author_profile": "https://Stackoverflow.com/users/1249",
"pm_score": 1,
"selected": false,
"text": "<p>As others have mentioned, doing an if statement in two lines without braces can lead to confusion:</p>\n\n<pre><code>if (a == b)\n DoSomething();\n DoSomethingElse(); <-- outside if statement\n</code></pre>\n\n<p>so I place it on a single line if I can do so without hurting readability:</p>\n\n<pre><code>if (a == b) DoSomething();\n</code></pre>\n\n<p>and at all other times I use braces.</p>\n\n<p>Ternary operators are a little different. Most of the time I do them on one line:</p>\n\n<pre><code>var c = (a == b) ? DoSomething() : DoSomethingElse();\n</code></pre>\n\n<p>but sometimes the statements have nested function calls, or lambda expressions which \nmake a one-line statement difficult to parse visually, so I prefer something like this:</p>\n\n<pre><code>var c = (a == b)\n ? AReallyReallyLongFunctionName()\n : AnotherReallyReallyLongFunctionOrStatement();\n</code></pre>\n\n<p>Still more concise than an if/else block but easy to see what's going on.</p>\n"
},
{
"answer_id": 11557,
"author": "Rytmis",
"author_id": 266,
"author_profile": "https://Stackoverflow.com/users/266",
"pm_score": 2,
"selected": false,
"text": "<p>Chalk this one to lack of experience, but during my seven-year stint as a code monkey I've <em>never</em> actually seen anyone make the mistake of not adding braces when adding code to a block that doesn't have braces. That's precisely <em>zero</em> times. </p>\n\n<p>And before the wisecrackers get to it, no, the reason wasn't \"everyone always uses braces\".</p>\n\n<p>So, an honest question -- I really would like to get actual replies instead of just downvotes: does that ever actually happen?</p>\n\n<p>(Edit: I've heard enough outsourcing horror stories to clarify a bit: does it ever actually happen to <strong>competent programmers</strong>?)</p>\n"
},
{
"answer_id": 39418,
"author": "Dewm Solo",
"author_id": 4225,
"author_profile": "https://Stackoverflow.com/users/4225",
"pm_score": 2,
"selected": false,
"text": "<p>I personnally side with McConnell's explanation from Code Complete.</p>\n\n<p>Use them whenever you can. They enhance your code's readability and remove the few and scarce confusions that might occur.</p>\n\n<p>There is one thing that's more important though....Consistency. Which ever style you use,make sure you always do it the same way.</p>\n\n<p>Start writing stuff like:</p>\n\n<pre>\n<code>\nIf A == true\n FunctA();\n\nIf B == \"Test\"\n{\n FunctB();\n}\n</code>\n</pre>\n\n<p>You are bound to end up looking for an odd bug where the compiler won't understand what you were trying to do and that will be hard to find.</p>\n\n<p>Basically find the one you are comfortable writing everytime and stick to it. I do believe in using the block delimeters('{', '}') as much as possible is the way to go.</p>\n\n<p>I don't want to start a question inside another, but there is something related to this that I want to mention to get your mental juices going. One the decision of using the brackets has been made. Where do you put the opening bracket? On the same line as the statement or underneath. Indented brackets or not?</p>\n\n<pre>\n<code>\nIf A == false {\n //calls and whatnot\n}\n//or\nIf B == \"BlaBla\"\n{\n //calls and whatnot\n}\n//or\nIf C == B\n {\n //calls and whatnot\n }\n</code>\n</pre>\n\n<p>Please don't answer to this since this would be a new question. If I see an interest in this I will open a new question your input.</p>\n"
},
{
"answer_id": 77547,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 0,
"selected": false,
"text": "<p>I use curly braces around every statement if and only if at least one of them requires it.</p>\n"
},
{
"answer_id": 78060,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 1,
"selected": false,
"text": "<p>Sun's <a href=\"http://java.sun.com/docs/codeconv/\" rel=\"nofollow noreferrer\">Code Conventions for the Java programming Language</a> has <a href=\"http://java.sun.com/docs/codeconv/html/CodeConventions.doc6.html#449\" rel=\"nofollow noreferrer\">this</a> to say:</p>\n\n<blockquote>\n <p>The if-else class of statements should\n have the following form:</p>\n\n<pre><code>if (condition) {\n statements;\n}\n\nif (condition) {\n statements;\n} else {\n statements;\n}\n\nif (condition) {\n statements;\n} else if (condition) {\n statements;\n} else {\n statements;\n}\n</code></pre>\n</blockquote>\n"
},
{
"answer_id": 85924,
"author": "Brad Gilbert",
"author_id": 1337,
"author_profile": "https://Stackoverflow.com/users/1337",
"pm_score": 0,
"selected": false,
"text": "<p>In Perl if you are doing a simple test, sometime you will write it in this form:</p>\n\n<pre><code>do_something if condition;\n\ndo_something unless condition;\n</code></pre>\n\n<p>Which can be really useful to check the arguments at the start of a subroutine.</p>\n\n<pre><code>sub test{\n my($self,@args) = @_;\n\n return undef unless defined $self;\n\n # rest of code goes here\n\n}\n</code></pre>\n"
},
{
"answer_id": 639794,
"author": "David Thornley",
"author_id": 14148,
"author_profile": "https://Stackoverflow.com/users/14148",
"pm_score": 0,
"selected": false,
"text": "<p>The golden rule is that, when working in an existing project, follow those coding standards.</p>\n\n<p>When I'm at home, I have two forms.</p>\n\n<p>The first is the single line:</p>\n\n<pre><code>if (condition) doThis();\n</code></pre>\n\n<p>and the second is for multiple lines:</p>\n\n<pre><code>if (condition) {\n doThis();\n}\n</code></pre>\n"
}
] | 2008/08/14 | [
"https://Stackoverflow.com/questions/11112",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1175/"
] | Most wiki software I've presents lots of "features" on their pages. This is fine for desktop users, but is annoying when using an iPhone or other mobile device.
I'd prefer pages that just had the content, along with maybe an Edit button and a Search button. The editors are also often too fancy for mobile users; a simple multi-line edit field would be better for mobile users than a bunch of formatting controls.
What is a good wiki package for mobile users? | There isn't really a right answer. This is what coding standards within the company are for. If you can keep it consistent across the whole company then it will be easy to read. I personally like
```
if ( a == b) {
doSomething();
}
else {
doSomething();
}
```
but this is a holy war. |
11,141 | <p>Recently I have been investigating the possibilities of caching in ASP.NET.</p>
<p>I rolled my own "Cache", because I didn't know any better, it looked a bit like this:</p>
<pre><code>public class DataManager
{
private static DataManager s_instance;
public static DataManager GetInstance()
{
}
private Data[] m_myData;
private DataTime m_cacheTime;
public Data[] GetData()
{
TimeSpan span = DateTime.Now.Substract(m_cacheTime);
if(span.TotalSeconds > 10)
{
// Do SQL to get data
m_myData = data;
m_cacheTime = DateTime.Now;
return m_myData;
}
else
{
return m_myData;
}
}
}
</code></pre>
<p>So the values are stored for a while in a singleton, and when the time expires, the values are renewed. If time has not expired, and a request for the data is done, the stored values in the field are returned.</p>
<p>What are the benefits over using the real method (<a href="http://msdn.microsoft.com/en-us/library/aa478965.aspx" rel="nofollow noreferrer">http://msdn.microsoft.com/en-us/library/aa478965.aspx</a>) instead of this?</p>
| [
{
"answer_id": 11146,
"author": "TheSmurf",
"author_id": 1975282,
"author_profile": "https://Stackoverflow.com/users/1975282",
"pm_score": 3,
"selected": true,
"text": "<p>I think the maxim \"let the computer do it; it's smarter than you\" applies here. Just like memory management and other complicated things, the computer is a lot more informed about what it's doing than your are; consequently, able to get more performance than you are.</p>\n\n<p>Microsoft has had a team of engineers working on it and they've probably managed to squeeze much more performance out of the system than would be possible for you to. It's also likely that ASP.NET's built-in caching operates at a different level (which is inaccessible to your application), making it much faster.</p>\n"
},
{
"answer_id": 11148,
"author": "Eric Z Beard",
"author_id": 1219,
"author_profile": "https://Stackoverflow.com/users/1219",
"pm_score": 2,
"selected": false,
"text": "<p>The ASP.NET caching mechanism has been around for a while, so it's stable and well understood. There are lots of resources out there to help you make the most of it.</p>\n\n<p>Rolling your own might be the right solution, depending on your requirements.</p>\n\n<p>The hard part about caching is choosing what is safe to cache, and when. For applications in which data changes frequently, you can introduce some hard to troubleshoot bugs with caching, so be careful.</p>\n"
},
{
"answer_id": 11154,
"author": "Kev",
"author_id": 419,
"author_profile": "https://Stackoverflow.com/users/419",
"pm_score": 1,
"selected": false,
"text": "<p>Caching in ASP.NET is feature rich and you can configure caching in quite a granular way. </p>\n\n<p>In your case (data caching) one of the features you're missing out on is the ability to invalidate and refresh the cache if data on the SQL server is updated in some way (SQL Cache Dependency).</p>\n\n<p><a href=\"http://msdn.microsoft.com/en-us/library/ms178604.aspx\" rel=\"nofollow noreferrer\">http://msdn.microsoft.com/en-us/library/ms178604.aspx</a></p>\n"
}
] | 2008/08/14 | [
"https://Stackoverflow.com/questions/11141",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] | Recently I have been investigating the possibilities of caching in ASP.NET.
I rolled my own "Cache", because I didn't know any better, it looked a bit like this:
```
public class DataManager
{
private static DataManager s_instance;
public static DataManager GetInstance()
{
}
private Data[] m_myData;
private DataTime m_cacheTime;
public Data[] GetData()
{
TimeSpan span = DateTime.Now.Substract(m_cacheTime);
if(span.TotalSeconds > 10)
{
// Do SQL to get data
m_myData = data;
m_cacheTime = DateTime.Now;
return m_myData;
}
else
{
return m_myData;
}
}
}
```
So the values are stored for a while in a singleton, and when the time expires, the values are renewed. If time has not expired, and a request for the data is done, the stored values in the field are returned.
What are the benefits over using the real method (<http://msdn.microsoft.com/en-us/library/aa478965.aspx>) instead of this? | I think the maxim "let the computer do it; it's smarter than you" applies here. Just like memory management and other complicated things, the computer is a lot more informed about what it's doing than your are; consequently, able to get more performance than you are.
Microsoft has had a team of engineers working on it and they've probably managed to squeeze much more performance out of the system than would be possible for you to. It's also likely that ASP.NET's built-in caching operates at a different level (which is inaccessible to your application), making it much faster. |
11,194 | <p>We're working on a Log Viewer. The use will have the option to filter by user, severity, etc. In the Sql days I'd add to the query string, but I want to do it with Linq. How can I conditionally add where-clauses?</p>
| [
{
"answer_id": 11201,
"author": "TheSmurf",
"author_id": 1975282,
"author_profile": "https://Stackoverflow.com/users/1975282",
"pm_score": 0,
"selected": false,
"text": "<p>Just use C#'s && operator:</p>\n\n<pre><code>var items = dc.Users.Where(l => l.Date == DateTime.Today && l.Severity == \"Critical\")\n</code></pre>\n\n<p>Edit: Ah, need to read more carefully. You wanted to know how to <em>conditionally</em> add additional clauses. In that case, I have no idea. :) What I'd probably do is just prepare several queries, and execute the right one, depending on what I ended up needing.</p>\n"
},
{
"answer_id": 11203,
"author": "Darren Kopp",
"author_id": 77,
"author_profile": "https://Stackoverflow.com/users/77",
"pm_score": 8,
"selected": true,
"text": "<p>if you want to only filter if certain criteria is passed, do something like this</p>\n\n<pre><code>var logs = from log in context.Logs\n select log;\n\nif (filterBySeverity)\n logs = logs.Where(p => p.Severity == severity);\n\nif (filterByUser)\n logs = logs.Where(p => p.User == user);\n</code></pre>\n\n<p>Doing so this way will allow your Expression tree to be exactly what you want. That way the SQL created will be exactly what you need and nothing less.</p>\n"
},
{
"answer_id": 11204,
"author": "Keith",
"author_id": 905,
"author_profile": "https://Stackoverflow.com/users/905",
"pm_score": 0,
"selected": false,
"text": "<p>You could use an external method:</p>\n\n<pre><code>var results =\n from rec in GetSomeRecs()\n where ConditionalCheck(rec)\n select rec;\n\n...\n\nbool ConditionalCheck( typeofRec input ) {\n ...\n}\n</code></pre>\n\n<p>This would work, but can't be broken down into expression trees, which means Linq to SQL would run the check code against every record.</p>\n\n<p>Alternatively:</p>\n\n<pre><code>var results =\n from rec in GetSomeRecs()\n where \n (!filterBySeverity || rec.Severity == severity) &&\n (!filterByUser|| rec.User == user)\n select rec;\n</code></pre>\n\n<p>That might work in expression trees, meaning Linq to SQL would be optimised.</p>\n"
},
{
"answer_id": 11225,
"author": "Jon Limjap",
"author_id": 372,
"author_profile": "https://Stackoverflow.com/users/372",
"pm_score": 0,
"selected": false,
"text": "<p>Well, what I thought was you could put the filter conditions into a generic list of Predicates:</p>\n\n<pre><code> var list = new List<string> { \"me\", \"you\", \"meyou\", \"mow\" };\n\n var predicates = new List<Predicate<string>>();\n\n predicates.Add(i => i.Contains(\"me\"));\n predicates.Add(i => i.EndsWith(\"w\"));\n\n var results = new List<string>();\n\n foreach (var p in predicates)\n results.AddRange(from i in list where p.Invoke(i) select i); \n</code></pre>\n\n<p>That results in a list containing \"me\", \"meyou\", and \"mow\".</p>\n\n<p>You could optimize that by doing the foreach with the predicates in a totally different function that ORs all the predicates.</p>\n"
},
{
"answer_id": 11241,
"author": "t3rse",
"author_id": 64,
"author_profile": "https://Stackoverflow.com/users/64",
"pm_score": 1,
"selected": false,
"text": "<p>It isn't the prettiest thing but you can use a lambda expression and pass your conditions optionally. In TSQL I do a lot of the following to make parameters optional: </p>\n\n<blockquote>\n <p>WHERE Field = @FieldVar OR @FieldVar IS NULL</p>\n</blockquote>\n\n<p>You could duplicate the same style with a the following lambda (an example of checking authentication): </p>\n\n<blockquote>\n <p>MyDataContext db = new MyDataContext();</p>\n \n <p>void RunQuery(string param1, string param2, int? param3){</p>\n \n <blockquote>\n <p>Func checkUser = user => </p>\n \n <blockquote>\n <p>((param1.Length > 0)? user.Param1 == param1 : 1 == 1) &&</p>\n \n <p>((param2.Length > 0)? user.Param2 == param2 : 1 == 1) && </p>\n \n <p>((param3 != null)? user.Param3 == param3 : 1 == 1);</p>\n </blockquote>\n \n <p>User foundUser = db.Users.SingleOrDefault(checkUser);</p>\n </blockquote>\n \n <p>}</p>\n</blockquote>\n"
},
{
"answer_id": 11729,
"author": "Lars Mæhlum",
"author_id": 960,
"author_profile": "https://Stackoverflow.com/users/960",
"pm_score": 4,
"selected": false,
"text": "<p>When it comes to conditional linq, I am very fond of the filters and pipes pattern.<br>\n<a href=\"http://blog.wekeroad.com/mvc-storefront/mvcstore-part-3/\" rel=\"noreferrer\">http://blog.wekeroad.com/mvc-storefront/mvcstore-part-3/</a></p>\n\n<p>Basically you create an extension method for each filter case that takes in the IQueryable and a parameter.</p>\n\n<pre><code>public static IQueryable<Type> HasID(this IQueryable<Type> query, long? id)\n{\n return id.HasValue ? query.Where(o => i.ID.Equals(id.Value)) : query;\n}\n</code></pre>\n"
},
{
"answer_id": 11769,
"author": "Brad Leach",
"author_id": 708,
"author_profile": "https://Stackoverflow.com/users/708",
"pm_score": 2,
"selected": false,
"text": "<p>Another option would be to use something like the PredicateBuilder discussed <a href=\"http://www.albahari.com/nutshell/predicatebuilder.html\" rel=\"nofollow noreferrer\">here</a>.\nIt allows you to write code like the following:</p>\n\n<pre><code>var newKids = Product.ContainsInDescription (\"BlackBerry\", \"iPhone\");\n\nvar classics = Product.ContainsInDescription (\"Nokia\", \"Ericsson\")\n .And (Product.IsSelling());\n\nvar query = from p in Data.Products.Where (newKids.Or (classics))\n select p;\n</code></pre>\n\n<p>Note that I've only got this to work with Linq 2 SQL. EntityFramework does not implement Expression.Invoke, which is required for this method to work. I have a question regarding this issue <a href=\"https://stackoverflow.com/questions/10524/expressioninvoke-in-entity-framework\">here</a>.</p>\n"
},
{
"answer_id": 14560,
"author": "Andy Rose",
"author_id": 1762,
"author_profile": "https://Stackoverflow.com/users/1762",
"pm_score": 1,
"selected": false,
"text": "<p>I had a similar requirement recently and eventually found this in he MSDN.\n<a href=\"http://code.msdn.microsoft.com/csharpsamples\" rel=\"nofollow noreferrer\">CSharp Samples for Visual Studio 2008</a></p>\n\n<p>The classes included in the DynamicQuery sample of the download allow you to create dynamic queries at runtime in the following format:</p>\n\n<pre><code>var query =\ndb.Customers.\nWhere(\"City = @0 and Orders.Count >= @1\", \"London\", 10).\nOrderBy(\"CompanyName\").\nSelect(\"new(CompanyName as Name, Phone)\");\n</code></pre>\n\n<p>Using this you can build a query string dynamically at runtime and pass it into the Where() method:</p>\n\n<pre><code>string dynamicQueryString = \"City = \\\"London\\\" and Order.Count >= 10\"; \nvar q = from c in db.Customers.Where(queryString, null)\n orderby c.CompanyName\n select c;\n</code></pre>\n"
},
{
"answer_id": 19950,
"author": "sgwill",
"author_id": 1204,
"author_profile": "https://Stackoverflow.com/users/1204",
"pm_score": 4,
"selected": false,
"text": "<p>I ended using an answer similar to Daren's, but with an IQueryable interface:</p>\n\n<pre><code>IQueryable<Log> matches = m_Locator.Logs;\n\n// Users filter\nif (usersFilter)\n matches = matches.Where(l => l.UserName == comboBoxUsers.Text);\n\n // Severity filter\n if (severityFilter)\n matches = matches.Where(l => l.Severity == comboBoxSeverity.Text);\n\n Logs = (from log in matches\n orderby log.EventTime descending\n select log).ToList();\n</code></pre>\n\n<p>That builds up the query before hitting the database. The command won't run until .ToList() at the end.</p>\n"
},
{
"answer_id": 5941594,
"author": "Carlos",
"author_id": 745725,
"author_profile": "https://Stackoverflow.com/users/745725",
"pm_score": 5,
"selected": false,
"text": "<p>If you need to filter base on a List / Array use the following:</p>\n\n<pre><code> public List<Data> GetData(List<string> Numbers, List<string> Letters)\n {\n if (Numbers == null)\n Numbers = new List<string>();\n\n if (Letters == null)\n Letters = new List<string>();\n\n var q = from d in database.table\n where (Numbers.Count == 0 || Numbers.Contains(d.Number))\n where (Letters.Count == 0 || Letters.Contains(d.Letter))\n select new Data\n {\n Number = d.Number,\n Letter = d.Letter,\n };\n return q.ToList();\n\n }\n</code></pre>\n"
},
{
"answer_id": 6330322,
"author": "James Livingston",
"author_id": 145966,
"author_profile": "https://Stackoverflow.com/users/145966",
"pm_score": 3,
"selected": false,
"text": "<p>Doing this:</p>\n\n<pre><code>bool lastNameSearch = true/false; // depending if they want to search by last name,\n</code></pre>\n\n<p>having this in the <code>where</code> statement:</p>\n\n<pre><code>where (lastNameSearch && name.LastNameSearch == \"smith\")\n</code></pre>\n\n<p>means that when the final query is created, if <code>lastNameSearch</code> is <code>false</code> the query will completely omit any SQL for the last name search.</p>\n"
},
{
"answer_id": 51278965,
"author": "Ryan",
"author_id": 2266345,
"author_profile": "https://Stackoverflow.com/users/2266345",
"pm_score": 4,
"selected": false,
"text": "<p>I solved this with an extension method to allow LINQ to be conditionally enabled in the middle of a fluent expression. This removes the need to break up the expression with <code>if</code> statements.</p>\n\n<p><code>.If()</code> extension method:</p>\n\n<pre><code>public static IQueryable<TSource> If<TSource>(\n this IQueryable<TSource> source,\n bool condition,\n Func<IQueryable<TSource>, IQueryable<TSource>> branch)\n {\n return condition ? branch(source) : source;\n }\n</code></pre>\n\n<p>This allows you to do this:</p>\n\n<pre><code>return context.Logs\n .If(filterBySeverity, q => q.Where(p => p.Severity == severity))\n .If(filterByUser, q => q.Where(p => p.User == user))\n .ToList();\n</code></pre>\n\n<p>Here's also an <code>IEnumerable<T></code> version which will handle most other LINQ expressions:</p>\n\n<pre><code>public static IEnumerable<TSource> If<TSource>(\n this IEnumerable<TSource> source,\n bool condition,\n Func<IEnumerable<TSource>, IEnumerable<TSource>> branch)\n {\n return condition ? branch(source) : source;\n }\n</code></pre>\n"
},
{
"answer_id": 55732512,
"author": "Gustavo",
"author_id": 6672759,
"author_profile": "https://Stackoverflow.com/users/6672759",
"pm_score": 1,
"selected": false,
"text": "<p>You can create and use this extension method</p>\n\n<pre><code>public static IQueryable<TSource> WhereIf<TSource>(this IQueryable<TSource> source, bool isToExecute, Expression<Func<TSource, bool>> predicate)\n{\n return isToExecute ? source.Where(predicate) : source;\n}\n</code></pre>\n"
}
] | 2008/08/14 | [
"https://Stackoverflow.com/questions/11194",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1204/"
] | We're working on a Log Viewer. The use will have the option to filter by user, severity, etc. In the Sql days I'd add to the query string, but I want to do it with Linq. How can I conditionally add where-clauses? | if you want to only filter if certain criteria is passed, do something like this
```
var logs = from log in context.Logs
select log;
if (filterBySeverity)
logs = logs.Where(p => p.Severity == severity);
if (filterByUser)
logs = logs.Where(p => p.User == user);
```
Doing so this way will allow your Expression tree to be exactly what you want. That way the SQL created will be exactly what you need and nothing less. |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.