qid
int64
4
8.14M
question
stringlengths
20
48.3k
answers
list
date
stringlengths
10
10
metadata
list
input
stringlengths
12
45k
output
stringlengths
2
31.8k
270,677
<p>How do I access specific sections of man pages?</p>
[ { "answer_id": 270694, "author": "Jason Coco", "author_id": 34218, "author_profile": "https://Stackoverflow.com/users/34218", "pm_score": 5, "selected": true, "text": "<p>Put the section number in front of the item you want to reference. For example, to access the sysctl function from the library section, you can write:</p>\n\n<pre><code>man 3 sysctl\n</code></pre>\n\n<p>and to access the sysctl tool from the system administrator's section, you would write:</p>\n\n<pre><code>man 8 sysctl\n</code></pre>\n" }, { "answer_id": 270718, "author": "Adam Rosenfield", "author_id": 9530, "author_profile": "https://Stackoverflow.com/users/9530", "pm_score": 2, "selected": false, "text": "<p>To add to what <a href=\"https://stackoverflow.com/questions/270677/man-sections#270694\">Jason</a> said: if you're not sure what section something is in, you can also see <em>all</em> of the man pages for a given topic by typing</p>\n\n<pre><code>man -a topic\n</code></pre>\n\n<p>This is useful for topics such as <code>printf</code>, for which there is both a command and a C function that do similar things.</p>\n" }, { "answer_id": 270727, "author": "Rob Wells", "author_id": 2974, "author_profile": "https://Stackoverflow.com/users/2974", "pm_score": 0, "selected": false, "text": "<p>use the -s flag, for example:</p>\n\n<pre><code>man -s 2 read\n</code></pre>\n\n<p>you might like to look at</p>\n\n<pre><code>man intro\n</code></pre>\n\n<p>to get an idea of what's where.</p>\n\n<p>HTH.</p>\n\n<p>cheers,</p>\n\n<p>Rob</p>\n" } ]
2008/11/06
[ "https://Stackoverflow.com/questions/270677", "https://Stackoverflow.com", "https://Stackoverflow.com/users/30924/" ]
How do I access specific sections of man pages?
Put the section number in front of the item you want to reference. For example, to access the sysctl function from the library section, you can write: ``` man 3 sysctl ``` and to access the sysctl tool from the system administrator's section, you would write: ``` man 8 sysctl ```
270,695
<p>Working with an Oracle 9i database from an ASP.NET 2.0 (VB) application using OLEDB. Is there a way to have an insert statement return a value? I have a sequence set up to number entries as they go into the database, but I need that value to come back after the insert so I can do some manipulation to the set I just entered in the code-behind VB.</p>
[ { "answer_id": 270698, "author": "TravisO", "author_id": 35116, "author_profile": "https://Stackoverflow.com/users/35116", "pm_score": 0, "selected": false, "text": "<p>If this value is the key the database creates, you've ran into a good example why you should use UUIDs as your table key, and generate them in code.</p>\n\n<p>This method will give you faster performance in your setup.</p>\n" }, { "answer_id": 270726, "author": "jishi", "author_id": 33663, "author_profile": "https://Stackoverflow.com/users/33663", "pm_score": 2, "selected": false, "text": "<p>Oracle seem to have a keywod called \"returning\" which can return a given column of the inserted row, however that might require you to set the \"autoincrement\" field manually by invoking the next value in your sequence.</p>\n\n<p>Check this discussion about it:</p>\n\n<p><a href=\"http://forums.oracle.com/forums/thread.jspa?threadID=354998\" rel=\"nofollow noreferrer\">http://forums.oracle.com/forums/thread.jspa?threadID=354998</a></p>\n\n<p>However, you can always select the current sequence-number in a second query, sort of like MySQLs <code>last_insert_id()</code></p>\n" }, { "answer_id": 270901, "author": "Mark Stock", "author_id": 19737, "author_profile": "https://Stackoverflow.com/users/19737", "pm_score": 0, "selected": false, "text": "<p>First use a <strong>SELECT</strong> statement to get the next sequence. You may use <a href=\"http://www.adp-gmbh.ch/ora/misc/dual.html\" rel=\"nofollow noreferrer\">the Oracle dual table</a> to do this.</p>\n\n<pre><code>SELECT my_seq.nextval FROM dual\n</code></pre>\n\n<p>Use the sequence that you retrieved in subsequent <strong>INSERT</strong> statements.</p>\n\n<pre><code>INSERT ...\nINSERT ...\n</code></pre>\n" }, { "answer_id": 271669, "author": "Tony Andrews", "author_id": 18747, "author_profile": "https://Stackoverflow.com/users/18747", "pm_score": 4, "selected": true, "text": "<p>Some possibilities:</p>\n\n<p>1) Use the RETURNING clause:</p>\n\n<pre><code>INSERT INTO emp (empno, ename) VALUES (emp_seq.NEXTVAL, 'ANDREWS')\nRETURNING empno INTO :variable;\n</code></pre>\n\n<p>2) Use the sequence CURRVAL:</p>\n\n<pre><code>INSERT INTO emp (empno, ename) VALUES (emp_seq.NEXTVAL, 'ANDREWS');\nSELECT emp_seq.CURRVAL INTO :variable FROM DUAL;\n</code></pre>\n\n<p>CURRVAL returns the last sequence value generated by your session.</p>\n" } ]
2008/11/06
[ "https://Stackoverflow.com/questions/270695", "https://Stackoverflow.com", "https://Stackoverflow.com/users/12545/" ]
Working with an Oracle 9i database from an ASP.NET 2.0 (VB) application using OLEDB. Is there a way to have an insert statement return a value? I have a sequence set up to number entries as they go into the database, but I need that value to come back after the insert so I can do some manipulation to the set I just entered in the code-behind VB.
Some possibilities: 1) Use the RETURNING clause: ``` INSERT INTO emp (empno, ename) VALUES (emp_seq.NEXTVAL, 'ANDREWS') RETURNING empno INTO :variable; ``` 2) Use the sequence CURRVAL: ``` INSERT INTO emp (empno, ename) VALUES (emp_seq.NEXTVAL, 'ANDREWS'); SELECT emp_seq.CURRVAL INTO :variable FROM DUAL; ``` CURRVAL returns the last sequence value generated by your session.
270,708
<p>I have a char array buffer that I am using to store characters that the user will input one by one. My code below works but has a few glitches that I can't figure out:</p> <ol> <li>when I execute a printf to see what's in Buffer, it does fill up but I get garbage characters at the end</li> <li>it won't stop at 8 characters despite being declared as char Buffer[8];</li> </ol> <p>Can somebody please explain to me what is going on and perhaps how I could fix this? Thanks.</p> <pre><code>char Buffer[8]; //holds the byte stream int i=0; if (/* user input event has occurred */) { Buffer[i] = charInput; i++; // Display a response to input printf("Buffer is %s!\n", Buffer); } </code></pre> <p>Output:</p> <pre> tagBuffer is 1┬┬w! tagBuffer is 12┬w! tagBuffer is 123w! tagBuffer is 1234! tagBuffer is 12345! tagBuffer is 123456=! tagBuffer is 1234567! tagBuffer is 12345678!</pre> <p>tagBuffer is 123456789!</p>
[ { "answer_id": 270713, "author": "Toon Krijthe", "author_id": 18061, "author_profile": "https://Stackoverflow.com/users/18061", "pm_score": 6, "selected": true, "text": "<p>You have to end the string with a <code>\\0</code> character. That's why they are called zero terminated strings.</p>\n<p>It is also wise to allocate 1 extra char to hold the <code>\\0</code>.</p>\n" }, { "answer_id": 270719, "author": "Paige Ruten", "author_id": 813, "author_profile": "https://Stackoverflow.com/users/813", "pm_score": 3, "selected": false, "text": "<p>The only thing you are passing to the printf() function is a pointer to the first character of your string. printf() has no way of knowing the size of your array. (It doesn't even know if it's an actual array, since a pointer is just a memory address.)</p>\n\n<p>printf() and all the standard c string functions assume that there is a 0 at the end of your string. printf() for example will keep printing characters in memory, starting at the char that you pass to the function, until it hits a 0.</p>\n\n<p>Therefore you should change your code to something like this:</p>\n\n<pre><code>char Buffer[9]; //holds the byte stream\nint i=0;\n\nif( //user input event has occured ) \n{\n Buffer[i] = charInput;\n i++;\n\n Buffer[i] = 0; // You can also assign the char '\\0' to it to get the same result.\n\n // Display a response to input\n printf(\"Buffer is %s!\\n\", Buffer);\n\n}\n</code></pre>\n" }, { "answer_id": 270722, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 0, "selected": false, "text": "<p>If you are programming in C or C++, you have to remember that:\n1) the strings are finished with a \\0 character.\n2) C does not have boundary check at strings, they are just character arrays.</p>\n" }, { "answer_id": 270730, "author": "Brian", "author_id": 18192, "author_profile": "https://Stackoverflow.com/users/18192", "pm_score": -1, "selected": false, "text": "<p>You might also want to look into using a <code>stringstream</code>.</p>\n" }, { "answer_id": 270743, "author": "joel.neely", "author_id": 3525, "author_profile": "https://Stackoverflow.com/users/3525", "pm_score": 2, "selected": false, "text": "<p>In addition to the previous comments about zero termination, you also have to accept responsibility for not overflowing your own buffer. It doesn't stop at 8 characters because your code is not stopping! You need something like the following (piggy-backing onto Jeremy's suggestion):</p>\n\n<pre><code>#define DATA_LENGTH 8\n#define BUFFER_LENGTH (DATA_LENGTH + 1)\n\nchar Buffer[BUFFER_LENGTH]; //holds the byte stream\nint charPos=0; //index to next character position to fill\n\nwhile (charPos &lt;= DATA_LENGTH ) { //user input event has occured\n Buffer[i] = charInput;\n\n Buffer[i+1] = '\\0';\n\n // Display a response to input\n printf(\"Buffer is %s!\\n\", Buffer);\n\n i++; \n\n}\n</code></pre>\n\n<p>In other words, make sure to stop accepting data when the maximum length has been reached, regardless of what the environment tries to push at you.</p>\n" }, { "answer_id": 271377, "author": "Jonathan Leffler", "author_id": 15168, "author_profile": "https://Stackoverflow.com/users/15168", "pm_score": 0, "selected": false, "text": "<p>It's odd that no-one has mentioned this possibility:</p>\n\n<pre><code>char Buffer[8]; //holds the byte stream\nint i = 0;\n\nwhile (i &lt; sizeof(Buffer) &amp;&amp; (charInput = get_the_users_character()) != EOF)\n{\n Buffer[i] = charInput;\n i++;\n\n // Display a response to input\n printf(\"Buffer is %.*s!\\n\", i, Buffer);\n}\n</code></pre>\n\n<p>This notation in the printf() format string specifies the maximum length of the string to be displayed, and does not require null termination (though null termination is ultimately the best way to go -- at least once you leave this loop).</p>\n\n<p>The <code>while</code> loop is more plausible than a simple <code>if</code>, and this version ensures that you do not overflow the end of the buffer (but does not ensure you leave enough space for a trailing NUL <code>'\\0'</code>. If you want to handle that, use <code>sizeof(Buffer) - 1</code> and then add the NUL after the loop.</p>\n" }, { "answer_id": 41102124, "author": "Mani Kanth", "author_id": 6355827, "author_profile": "https://Stackoverflow.com/users/6355827", "pm_score": 0, "selected": false, "text": "<p>Since <code>Buffer</code> is not initialized, it starts with all 9 garbage values.\nFrom the observed output, 2nd, 3rd, 4th, 5th, 6th, 7th, 8th and 2 immediate next memory location(outside the array) elements are clearly <code>'T'</code>, <code>'T'</code>, <code>'W'</code>, <code>'\\0'</code>, <code>'\\0'</code>, <code>'='</code>, <code>'\\0'</code>, <code>'\\0'</code>, <code>'\\0'</code>.</p>\n\n<p>Strings consume all the characters up until they see NULL character. That is why, in every iteration, as the array elements are assigned one by one, buffer is printed up to the part where a garbage NULL is present.</p>\n\n<p>That is to say, string has an undefined behavior if the character array doesn't end with <code>'\\0'</code>. You can avoid this by having an extra space for <code>'\\0'</code> at the end of the buffer.</p>\n" } ]
2008/11/06
[ "https://Stackoverflow.com/questions/270708", "https://Stackoverflow.com", "https://Stackoverflow.com/users/28462/" ]
I have a char array buffer that I am using to store characters that the user will input one by one. My code below works but has a few glitches that I can't figure out: 1. when I execute a printf to see what's in Buffer, it does fill up but I get garbage characters at the end 2. it won't stop at 8 characters despite being declared as char Buffer[8]; Can somebody please explain to me what is going on and perhaps how I could fix this? Thanks. ``` char Buffer[8]; //holds the byte stream int i=0; if (/* user input event has occurred */) { Buffer[i] = charInput; i++; // Display a response to input printf("Buffer is %s!\n", Buffer); } ``` Output: ``` tagBuffer is 1┬┬w! tagBuffer is 12┬w! tagBuffer is 123w! tagBuffer is 1234! tagBuffer is 12345! tagBuffer is 123456=! tagBuffer is 1234567! tagBuffer is 12345678! ``` tagBuffer is 123456789!
You have to end the string with a `\0` character. That's why they are called zero terminated strings. It is also wise to allocate 1 extra char to hold the `\0`.
270,724
<p>I'm checking out the Delphi 2009 Trial, but run into problems with the generics stuff right away.</p> <p>The following code does not compile, and I haven't the slightest idea why it's giving me E2015 for the Equals() method:</p> <pre><code>type TPrimaryKey&lt;T&gt; = class(TObject) strict private fValue: T; public constructor Create(AValue: T); function Equals(Obj: TObject): boolean; override; function GetValue: T; end; constructor TPrimaryKey&lt;T&gt;.Create(AValue: T); begin inherited Create; fValue := AValue; end; function TPrimaryKey&lt;T&gt;.Equals(Obj: TObject): boolean; begin Result := (Obj &lt;&gt; nil) and (Obj is TPrimaryKey&lt;T&gt;) and (TPrimaryKey&lt;T&gt;(Obj).GetValue = fValue); end; function TPrimaryKey&lt;T&gt;.GetValue: T; begin Result := fValue; end; </code></pre> <p>Why does the compiler think that fValue and the result of GetValue() can not be compared?</p>
[ { "answer_id": 270789, "author": "Angus Glashier", "author_id": 35063, "author_profile": "https://Stackoverflow.com/users/35063", "pm_score": 2, "selected": false, "text": "<p>You can't use operators with untyped generics. See <a href=\"https://forums.codegear.com/message.jspa?messageID=26273\" rel=\"nofollow noreferrer\">here</a> for a discussion.</p>\n\n<p>It compiles if you change it to:</p>\n\n<pre><code>TPrimaryKey&lt;T: class&gt; = class(TObject)\n</code></pre>\n" }, { "answer_id": 270810, "author": "Steve", "author_id": 22712, "author_profile": "https://Stackoverflow.com/users/22712", "pm_score": 2, "selected": false, "text": "<p>I think the original poster is trying to create an object wrapper around simple types (Integer, double etc etc), so constraining T to Class would perhaps not work for what he wants.</p>\n" }, { "answer_id": 270814, "author": "Toon Krijthe", "author_id": 18061, "author_profile": "https://Stackoverflow.com/users/18061", "pm_score": 1, "selected": false, "text": "<p>The compiler has trouble in determining that both \"T\"'s are the same. But with a little trick you can make it work:</p>\n\n<pre><code>type\n TPrimaryKey&lt;T&gt; = class(TObject)\n public\n type\n TCompare&lt;T1&gt; = reference to function(const A1, A2: TPrimaryKey&lt;T1&gt;): Boolean;\n private\n fValue: T;\n fCompare : TCompare&lt;T&gt;;\n public\n constructor Create(AValue: T; ACompare: TCompare&lt;T&gt;);\n function Equals(Obj: TPrimaryKey&lt;T&gt;): Boolean; reintroduce;\n function GetValue: T;\n function CreateNew(const AValue: T): TPrimaryKey&lt;T&gt;;\n\n end;\n\nconstructor TPrimaryKey&lt;T&gt;.Create(AValue: T; ACompare: TCompare&lt;T&gt;);\nbegin\n inherited Create;\n fValue := AValue;\n fCompare := ACompare;\nend;\n\nfunction TPrimaryKey&lt;T&gt;.Equals(Obj: TPrimaryKey&lt;T&gt;): Boolean;\nbegin\n Result := FCompare(self, Obj);\nend;\n\nfunction TPrimaryKey&lt;T&gt;.GetValue: T;\nbegin\n Result := fValue;\nend;\n\nfunction TPrimaryKey&lt;T&gt;.CreateNew(const AValue: T): TPrimaryKey&lt;T&gt;;\nbegin\n Result := TPrimaryKey&lt;T&gt;.Create(AValue, FCompare);\nend;\n</code></pre>\n\n<p>You instantiate it with:</p>\n\n<pre><code>var\n p1, p2 : TPrimaryKey&lt;Integer&gt;;\nbegin\n p1 := TPrimaryKey&lt;Integer&gt;.Create(10,\n function(const A1, A2: TPrimaryKey&lt;Integer&gt;): Boolean\n begin\n Result := (A1&lt;&gt;nil) and (A2&lt;&gt;nil) and (A1.GetValue=A2.GetValue);\n end);\n p2 := p1.CreateNew(10);\n\n p1.Equals(p2);\nend;\n</code></pre>\n" }, { "answer_id": 270837, "author": "Barry Kelly", "author_id": 3712, "author_profile": "https://Stackoverflow.com/users/3712", "pm_score": 4, "selected": true, "text": "<p>What if T is a string? What if it's a TSize record?</p>\n\n<p>Without constraining T (e.g. with &lt;T :class>), you can't be sure that the comparison will be meaningful.</p>\n\n<p>If, instead, you wanted to compare two values of type T, you can use the Generics.Defaults unit and use:</p>\n\n<pre><code>TEqualityComparer&lt;T&gt;.Default.Equals(x, y)\n</code></pre>\n\n<p>to compare values x and y of type T.</p>\n" } ]
2008/11/06
[ "https://Stackoverflow.com/questions/270724", "https://Stackoverflow.com", "https://Stackoverflow.com/users/30568/" ]
I'm checking out the Delphi 2009 Trial, but run into problems with the generics stuff right away. The following code does not compile, and I haven't the slightest idea why it's giving me E2015 for the Equals() method: ``` type TPrimaryKey<T> = class(TObject) strict private fValue: T; public constructor Create(AValue: T); function Equals(Obj: TObject): boolean; override; function GetValue: T; end; constructor TPrimaryKey<T>.Create(AValue: T); begin inherited Create; fValue := AValue; end; function TPrimaryKey<T>.Equals(Obj: TObject): boolean; begin Result := (Obj <> nil) and (Obj is TPrimaryKey<T>) and (TPrimaryKey<T>(Obj).GetValue = fValue); end; function TPrimaryKey<T>.GetValue: T; begin Result := fValue; end; ``` Why does the compiler think that fValue and the result of GetValue() can not be compared?
What if T is a string? What if it's a TSize record? Without constraining T (e.g. with <T :class>), you can't be sure that the comparison will be meaningful. If, instead, you wanted to compare two values of type T, you can use the Generics.Defaults unit and use: ``` TEqualityComparer<T>.Default.Equals(x, y) ``` to compare values x and y of type T.
270,745
<p>I have multiple Network Interface Cards on my computer, each with its own IP address.</p> <p>When I use <code>gethostbyname(gethostname())</code> from Python's (built-in) <code>socket</code> module, it will only return one of them. How do I get the others?</p>
[ { "answer_id": 270777, "author": "Martin v. Löwis", "author_id": 33006, "author_profile": "https://Stackoverflow.com/users/33006", "pm_score": 0, "selected": false, "text": "<p>You should directly obtain all IP configured IP addresses, e.g. by running ifconfig and parsing its output (it's also possible to do what <a href=\"http://pypi.python.org/pypi/netifaces/0.3\" rel=\"nofollow noreferrer\">ifconfig does directly in Python</a>, <a href=\"https://stackoverflow.com/questions/259389/finding-an-ip-from-an-interface-name\">see how it is done in C</a>). If you want host names, use gethostbyaddr.</p>\n" }, { "answer_id": 273112, "author": "JimB", "author_id": 32880, "author_profile": "https://Stackoverflow.com/users/32880", "pm_score": 1, "selected": false, "text": "<p>It's linux only, but there's a very simple recipe here <a href=\"http://code.activestate.com/recipes/439094/\" rel=\"nofollow noreferrer\">http://code.activestate.com/recipes/439094/</a> </p>\n\n<p>It probably uses similar code to the <a href=\"http://pypi.python.org/pypi/netifaces/\" rel=\"nofollow noreferrer\">netifaces package</a> mentioned in another answer (but current version linked here)</p>\n\n<p>The socket.getaddrinfo() doesn't actually return the bound ip address for the device. If your hosts file contains a line with \"127.0.1.1 yourhost.example.com yourhost\", which is a common configuration, getaddrinfo is only going to return 127.0.1.1.</p>\n" }, { "answer_id": 274644, "author": "Harley Holcombe", "author_id": 1057, "author_profile": "https://Stackoverflow.com/users/1057", "pm_score": 7, "selected": true, "text": "<p>Use the <a href=\"https://pypi.org/project/netifaces/\" rel=\"noreferrer\"><code>netifaces</code></a> module. Because networking is complex, using netifaces can be a little tricky, but here's how to do what you want:</p>\n<pre><code>&gt;&gt;&gt; import netifaces\n&gt;&gt;&gt; netifaces.interfaces()\n['lo', 'eth0']\n&gt;&gt;&gt; netifaces.ifaddresses('eth0')\n{17: [{'broadcast': 'ff:ff:ff:ff:ff:ff', 'addr': '00:11:2f:32:63:45'}], 2: [{'broadcast': '10.0.0.255', 'netmask': '255.255.255.0', 'addr': '10.0.0.2'}], 10: [{'netmask': 'ffff:ffff:ffff:ffff::', 'addr': 'fe80::211:2fff:fe32:6345%eth0'}]}\n&gt;&gt;&gt; for interface in netifaces.interfaces():\n... print netifaces.ifaddresses(interface)[netifaces.AF_INET]\n...\n[{'peer': '127.0.0.1', 'netmask': '255.0.0.0', 'addr': '127.0.0.1'}]\n[{'broadcast': '10.0.0.255', 'netmask': '255.255.255.0', 'addr': '10.0.0.2'}]\n&gt;&gt;&gt; for interface in netifaces.interfaces():\n... for link in netifaces.ifaddresses(interface)[netifaces.AF_INET]:\n... print link['addr']\n...\n127.0.0.1\n10.0.0.2\n</code></pre>\n<p>This can be made a little more readable like this:</p>\n<pre><code>from netifaces import interfaces, ifaddresses, AF_INET\n\ndef ip4_addresses():\n ip_list = []\n for interface in interfaces():\n for link in ifaddresses(interface)[AF_INET]:\n ip_list.append(link['addr'])\n return ip_list\n</code></pre>\n<p>If you want IPv6 addresses, use <code>AF_INET6</code> instead of <code>AF_INET</code>. If you're wondering why <code>netifaces</code> uses lists and dictionaries all over the place, it's because a single computer can have multiple NICs, and each NIC can have multiple addresses, and each address has its own set of options.</p>\n" }, { "answer_id": 1491617, "author": "DamonJW", "author_id": 180219, "author_profile": "https://Stackoverflow.com/users/180219", "pm_score": 0, "selected": false, "text": "<p>Here is a routine for finding all IPv4 and IPv6 interfaces. As a previous poster pointed out, socket.gethostbyname_ex() does not work for IPv6, and the Python documentation recommends one use <a href=\"http://docs.python.org/library/socket.html#socket.getaddrinfo\" rel=\"nofollow noreferrer\">socket.getaddressinfo()</a> instead.</p>\n\n<p>This routine adds the callback IPv4 interface (127.0.0.1), and if there are any IPv6 interfaces then it also adds the callback IPv6 interface (::1). On my machine, socket.getaddrinfo() will give me one or both of these but only if I have no other interfaces available.</p>\n\n<p>For my needs, I wanted to try to open a UDP socket on a specified port on each of my available interfaces, which is why the code has \"port\" and socket.SOCK_DGRAM in it. It is safe to change those, e.g. if you don't have a port in mind.</p>\n\n<pre><code>addrinfo_ipv4 = socket.getaddrinfo(hostname,port,socket.AF_INET,socket.SOCK_DGRAM)\naddrinfo_ipv6 = []\ntry:\n addrinfo_ipv6 = socket.getaddrinfo(hostname,port,socket.AF_INET6,socket.SOCK_DGRAM)\nexcept socket.gaierror:\n pass\naddrinfo = [(f,t,a) for f,t,p,cn,a in addrinfo_ipv4+addrinfo_ipv6]\naddrinfo_local = [(socket.AF_INET,socket.SOCK_DGRAM,('127.0.0.1',port))]\nif addrinfo_ipv6: \n addrinfo_local.append( (socket.AF_INET6,socket.SOCK_DGRAM,('::1',port)) )\n[addrinfo.append(ai) for ai in addrinfo_local if ai not in addrinfo]\n</code></pre>\n" }, { "answer_id": 16412986, "author": "Nakilon", "author_id": 322020, "author_profile": "https://Stackoverflow.com/users/322020", "pm_score": 4, "selected": false, "text": "<pre><code>import socket\n[i[4][0] for i in socket.getaddrinfo(socket.gethostname(), None)]\n</code></pre>\n" }, { "answer_id": 27494105, "author": "The Demz", "author_id": 844700, "author_profile": "https://Stackoverflow.com/users/844700", "pm_score": 3, "selected": false, "text": "<p><a href=\"https://docs.python.org/3.4/library/socket.html#socket.if_nameindex\" rel=\"noreferrer\">https://docs.python.org/3.4/library/socket.html#socket.if_nameindex</a></p>\n\n<p>socket.if_nameindex()</p>\n\n<p>Return a list of network interface information (index int, name string) tuples. OSError if the system call fails.</p>\n\n<p>Availability: Unix.</p>\n\n<p><strong>New in version 3.3.</strong></p>\n\n<hr>\n\n<p>made this code that is runable on Python 3.4, UNIX / Linux</p>\n\n<pre><code>#!/env/python3.4\nimport socket\nimport fcntl\nimport struct\n\ndef active_nic_addresses():\n \"\"\"\n Return a list of IPv4 addresses that are active on the computer.\n \"\"\"\n\n addresses = [ip for ip in socket.gethostbyname_ex(socket.gethostname())[2] if not ip.startswith(\"127.\")][:1]\n\n return addresses\n\ndef get_ip_address( NICname ):\n s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)\n return socket.inet_ntoa(fcntl.ioctl(\n s.fileno(),\n 0x8915, # SIOCGIFADDR\n struct.pack('256s', NICname[:15].encode(\"UTF-8\"))\n )[20:24])\n\n\ndef nic_info():\n \"\"\"\n Return a list with tuples containing NIC and IPv4\n \"\"\"\n nic = []\n\n for ix in socket.if_nameindex():\n name = ix[1]\n ip = get_ip_address( name )\n\n nic.append( (name, ip) )\n\n return nic\n\nif __name__ == \"__main__\":\n\n print( active_nic_addresses() )\n print( nic_info() )\n</code></pre>\n\n<hr>\n\n<p>Will print something like:</p>\n\n<pre><code>['192.168.0.2']\n[('lo', '127.0.0.1'), ('enp3s0', '192.168.0.2')]\n</code></pre>\n" }, { "answer_id": 33946251, "author": "Elemag", "author_id": 2436840, "author_profile": "https://Stackoverflow.com/users/2436840", "pm_score": 3, "selected": false, "text": "<p>All addresses in one line with the help of the <code>netifaces</code> module:</p>\n\n<pre><code>[netifaces.ifaddresses(iface)[netifaces.AF_INET][0]['addr'] for iface in netifaces.interfaces() if netifaces.AF_INET in netifaces.ifaddresses(iface)]\n</code></pre>\n" }, { "answer_id": 35776008, "author": "Tlili Marwen", "author_id": 5854219, "author_profile": "https://Stackoverflow.com/users/5854219", "pm_score": 0, "selected": false, "text": "<p>You can do it fairly easily like this:</p>\n\n<pre><code>import netifaces\n\nfor interface in netifaces.interfaces():\n print netifaces.ifaddresses(interface)\n</code></pre>\n\n<p>For more information you can look up the <a href=\"https://pypi.python.org/pypi/netifaces\" rel=\"nofollow\">netifaces documentation</a>.</p>\n" }, { "answer_id": 39951087, "author": "Sandeep", "author_id": 218857, "author_profile": "https://Stackoverflow.com/users/218857", "pm_score": 1, "selected": false, "text": "<p>This snippet will give a list of all available IPV4 addresses in the system.</p>\n\n<pre><code>import itertools\nfrom netifaces import interfaces, ifaddresses, AF_INET\n\nlinks = filter(None, (ifaddresses(x).get(AF_INET) for x in interfaces()))\nlinks = itertools.chain(*links)\nip_addresses = [x['addr'] for x in links]\n</code></pre>\n" }, { "answer_id": 43478599, "author": "pmav99", "author_id": 592289, "author_profile": "https://Stackoverflow.com/users/592289", "pm_score": 4, "selected": false, "text": "<p>Just for completeness, another option would be to use <a href=\"https://pypi.python.org/pypi/psutil\" rel=\"nofollow noreferrer\">psutil</a>.</p>\n<h2><strong>tldr;</strong></h2>\n<pre><code>import socket\nimport psutil\n\ndef get_ip_addresses(family):\n for interface, snics in psutil.net_if_addrs().items():\n for snic in snics:\n if snic.family == family:\n yield (interface, snic.address)\n\nipv4s = list(get_ip_addresses(socket.AF_INET))\nipv6s = list(get_ip_addresses(socket.AF_INET6))\n</code></pre>\n<h2>Explanation</h2>\n<p>The function you need is <a href=\"https://pythonhosted.org/psutil/#psutil.net_if_addrs\" rel=\"nofollow noreferrer\"><code>net_if_addrs</code></a>. I.e.:</p>\n<pre><code>import psutil\npsutil.net_if_addrs()\n</code></pre>\n<p>Which results in something like this (Python 3):</p>\n<pre><code>{'br-ae4880aa80cf': [snic(family=&lt;AddressFamily.AF_INET: 2&gt;, address='172.18.0.1', netmask='255.255.0.0', broadcast='172.18.0.1', ptp=None),\n snic(family=&lt;AddressFamily.AF_PACKET: 17&gt;, address='02:42:e5:ae:39:94', netmask=None, broadcast='ff:ff:ff:ff:ff:ff', ptp=None)],\n 'docker0': [snic(family=&lt;AddressFamily.AF_INET: 2&gt;, address='172.17.0.1', netmask='255.255.0.0', broadcast='172.17.0.1', ptp=None),\n snic(family=&lt;AddressFamily.AF_PACKET: 17&gt;, address='02:42:38:d2:4d:77', netmask=None, broadcast='ff:ff:ff:ff:ff:ff', ptp=None)],\n 'eno1': [snic(family=&lt;AddressFamily.AF_PACKET: 17&gt;, address='54:be:f7:0b:cf:a9', netmask=None, broadcast='ff:ff:ff:ff:ff:ff', ptp=None)],\n 'lo': [snic(family=&lt;AddressFamily.AF_INET: 2&gt;, address='127.0.0.1', netmask='255.0.0.0', broadcast=None, ptp=None),\n snic(family=&lt;AddressFamily.AF_PACKET: 17&gt;, address='00:00:00:00:00:00', netmask=None, broadcast=None, ptp=None)],\n 'wlp2s0': [snic(family=&lt;AddressFamily.AF_INET: 2&gt;, address='192.168.1.4', netmask='255.255.255.0', broadcast='192.168.1.255', ptp=None),\n snic(family=&lt;AddressFamily.AF_PACKET: 17&gt;, address='00:21:27:ee:d6:03', netmask=None, broadcast='ff:ff:ff:ff:ff:ff', ptp=None)]}\n</code></pre>\n<p>(Python 2):</p>\n<pre><code>{'br-ae4880aa80cf': [snic(family=2, address='172.18.0.1', netmask='255.255.0.0', broadcast='172.18.0.1', ptp=None),\n snic(family=17, address='02:42:e5:ae:39:94', netmask=None, broadcast='ff:ff:ff:ff:ff:ff', ptp=None)],\n 'docker0': [snic(family=2, address='172.17.0.1', netmask='255.255.0.0', broadcast='172.17.0.1', ptp=None),\n snic(family=17, address='02:42:38:d2:4d:77', netmask=None, broadcast='ff:ff:ff:ff:ff:ff', ptp=None)],\n 'eno1': [snic(family=17, address='54:be:f7:0b:cf:a9', netmask=None, broadcast='ff:ff:ff:ff:ff:ff', ptp=None)],\n 'lo': [snic(family=2, address='127.0.0.1', netmask='255.0.0.0', broadcast=None, ptp=None),\n snic(family=17, address='00:00:00:00:00:00', netmask=None, broadcast=None, ptp=None)],\n 'wlp2s0': [snic(family=2, address='192.168.1.4', netmask='255.255.255.0', broadcast='192.168.1.255', ptp=None),\n snic(family=17, address='00:21:27:ee:d6:03', netmask=None, broadcast='ff:ff:ff:ff:ff:ff', ptp=None)]}\n</code></pre>\n<p><strong>Note</strong>: Since you can have more than one address of the same family associated with each interface, the dict values are lists.</p>\n<p>Each <code>snic</code> is a <a href=\"https://docs.python.org/3/library/collections.html#collections.namedtuple\" rel=\"nofollow noreferrer\"><code>namedtuple</code></a> which includes 5 fields:</p>\n<ul>\n<li><code>family</code>: the address family, either <code>AF_INET</code>, <code>AF_INET6</code> or <code>psutil.AF_LINK</code>, which refers to a MAC address.</li>\n<li><code>address</code>: the primary NIC address (always set).</li>\n<li><code>netmask</code>: the netmask address (may be None).</li>\n<li><code>broadcast</code>: the broadcast address (may be None).</li>\n<li><code>ptp</code>: stands for “point to point”; it’s the destination address on a point to point interface (typically a VPN). broadcast and ptp are mutually exclusive (may be None).</li>\n</ul>\n" }, { "answer_id": 54338977, "author": "yongdi", "author_id": 6947023, "author_profile": "https://Stackoverflow.com/users/6947023", "pm_score": 0, "selected": false, "text": "<p>I think @Harley Holcombe's answer is workable, but if you have some virtual NICs without ip it will error. so this is i modified:</p>\n\n<pre><code>def get_lan_ip():\nfor interface in interfaces():\n try:\n for link in ifaddresses(interface)[AF_INET]:\n if str(link['addr']).startswith(\"172.\"):\n return str(link['addr'])\n except:\n pass\n</code></pre>\n\n<p>this will only return your lan ipv4</p>\n" }, { "answer_id": 54629245, "author": "chjortlund", "author_id": 209532, "author_profile": "https://Stackoverflow.com/users/209532", "pm_score": 2, "selected": false, "text": "<p>As this thread indicates, there is a lot of ways to acchive the same result, my suggested way is to leverage the build-in family filter in <code>getaddrinfo()</code> and parse the standardised tuple like so:</p>\n\n<pre><code>from socket import getaddrinfo, AF_INET, gethostname\n\nfor ip in getaddrinfo(host=gethostname(), port=None, family=AF_INET): \n print(ip[4][0])\n</code></pre>\n\n<p>Example output:</p>\n\n<pre><code>192.168.55.1\n192.168.170.234\n</code></pre>\n" } ]
2008/11/06
[ "https://Stackoverflow.com/questions/270745", "https://Stackoverflow.com", "https://Stackoverflow.com/users/35305/" ]
I have multiple Network Interface Cards on my computer, each with its own IP address. When I use `gethostbyname(gethostname())` from Python's (built-in) `socket` module, it will only return one of them. How do I get the others?
Use the [`netifaces`](https://pypi.org/project/netifaces/) module. Because networking is complex, using netifaces can be a little tricky, but here's how to do what you want: ``` >>> import netifaces >>> netifaces.interfaces() ['lo', 'eth0'] >>> netifaces.ifaddresses('eth0') {17: [{'broadcast': 'ff:ff:ff:ff:ff:ff', 'addr': '00:11:2f:32:63:45'}], 2: [{'broadcast': '10.0.0.255', 'netmask': '255.255.255.0', 'addr': '10.0.0.2'}], 10: [{'netmask': 'ffff:ffff:ffff:ffff::', 'addr': 'fe80::211:2fff:fe32:6345%eth0'}]} >>> for interface in netifaces.interfaces(): ... print netifaces.ifaddresses(interface)[netifaces.AF_INET] ... [{'peer': '127.0.0.1', 'netmask': '255.0.0.0', 'addr': '127.0.0.1'}] [{'broadcast': '10.0.0.255', 'netmask': '255.255.255.0', 'addr': '10.0.0.2'}] >>> for interface in netifaces.interfaces(): ... for link in netifaces.ifaddresses(interface)[netifaces.AF_INET]: ... print link['addr'] ... 127.0.0.1 10.0.0.2 ``` This can be made a little more readable like this: ``` from netifaces import interfaces, ifaddresses, AF_INET def ip4_addresses(): ip_list = [] for interface in interfaces(): for link in ifaddresses(interface)[AF_INET]: ip_list.append(link['addr']) return ip_list ``` If you want IPv6 addresses, use `AF_INET6` instead of `AF_INET`. If you're wondering why `netifaces` uses lists and dictionaries all over the place, it's because a single computer can have multiple NICs, and each NIC can have multiple addresses, and each address has its own set of options.
270,792
<p>I have the following xml I'd like to deserialize into a class</p> <pre><code>&lt;?xml version="1.0" encoding="utf-8" ?&gt; &lt;root&gt; &lt;element1&gt;String1&lt;/element1&gt; &lt;element2&gt;String2&lt;/element2&gt; &lt;/root&gt; </code></pre> <p>I am trying to serialize it into the following class:</p> <pre class="lang-csharp prettyprint-override"><code> [XmlRoot("root")] public class root { [XmlElement("element1")] internal string element1 { get; set; } [XmlElement("element2")] internal string element2 { get; set; } } </code></pre> <p>When I try deserializing it using the following code, the config object is instantiated, but the strings are null.</p> <pre class="lang-csharp prettyprint-override"><code> using (TextReader reader = new StreamReader(configFile)) { XmlSerializer serializer = new XmlSerializer(typeof(root)); this.config = (root)serializer.Deserialize(reader); } </code></pre> <p>I've tried using xsd.exe to create an xsd, and then create a class based off of that, but there is too much clutter generated by that tool. I think I'm close here. What am I missing?</p>
[ { "answer_id": 270809, "author": "Brody", "author_id": 17131, "author_profile": "https://Stackoverflow.com/users/17131", "pm_score": 4, "selected": true, "text": "<p>You can't serialise/deserialise internal properties - They have to be public.</p>\n" }, { "answer_id": 270821, "author": "Kevin", "author_id": 4599, "author_profile": "https://Stackoverflow.com/users/4599", "pm_score": 3, "selected": false, "text": "<p>I concur with Brody as to the nature of your problem. However, you may have an objection to making these fields public. The way I have handled this problem in the past is to create a serializable class whose only purpose is to read/write .xml and has all of its fields public. Then create a new class which is the external interface. It takes the serializable class as an argument of a constructor and the external class provides public properties which controls the access to the serializable class.</p>\n" }, { "answer_id": 278944, "author": "Peter Walke", "author_id": 12497, "author_profile": "https://Stackoverflow.com/users/12497", "pm_score": 1, "selected": false, "text": "<p>To follow up on my implementation... I ended up abandoning using the XmlSerializer class all together. The classes I was deserializing were pretty complex and contained lists of other objects that needed to be serialized. The amount of attributes I had to add to my classes made the <a href=\"http://en.wikipedia.org/wiki/Code_smell\" rel=\"nofollow noreferrer\">code stink</a></p>\n\n<p>I ended up using Linq to XML to do the deserialization.... the complexity of the class delcarations went down, but the linq statement eneded up being rather complex.</p>\n\n<p>If I were to do it again, I might have thought about using WCF and the datacontract serializer... That might have also been difficult to do also. </p>\n\n<p>I'm curious how people are deserializing xml docs into objects these days. After getting my head around Linq statements, I think this might be the way to go. The objects are much simpler to create, and they don't need to be public. It also seems like the XmlSerializer is \"old-school\" while Linq to XML is more \"new-school\".</p>\n\n<p>I'd love to hear what others had to say.</p>\n" }, { "answer_id": 286015, "author": "Brody", "author_id": 17131, "author_profile": "https://Stackoverflow.com/users/17131", "pm_score": 1, "selected": false, "text": "<p>You can use XSD.exe to generate a class from an XSD (XML Schema Definition). This produces a usable class structure that can serialise and deserialise the relevant XML.</p>\n" } ]
2008/11/06
[ "https://Stackoverflow.com/questions/270792", "https://Stackoverflow.com", "https://Stackoverflow.com/users/12497/" ]
I have the following xml I'd like to deserialize into a class ``` <?xml version="1.0" encoding="utf-8" ?> <root> <element1>String1</element1> <element2>String2</element2> </root> ``` I am trying to serialize it into the following class: ```csharp [XmlRoot("root")] public class root { [XmlElement("element1")] internal string element1 { get; set; } [XmlElement("element2")] internal string element2 { get; set; } } ``` When I try deserializing it using the following code, the config object is instantiated, but the strings are null. ```csharp using (TextReader reader = new StreamReader(configFile)) { XmlSerializer serializer = new XmlSerializer(typeof(root)); this.config = (root)serializer.Deserialize(reader); } ``` I've tried using xsd.exe to create an xsd, and then create a class based off of that, but there is too much clutter generated by that tool. I think I'm close here. What am I missing?
You can't serialise/deserialise internal properties - They have to be public.
270,811
<pre><code>cmd /C "myshortcut1.lnk" cmd /C "myshortcut2.lnk" </code></pre> <p>Works, but gives me a pop-up DOS window which, when closed, kills my two loaded programs. Same is true for this:</p> <pre><code>start /B cmd /C "1.lnk" start /B cmd /C "2.lnk" start /B cmd /C "3.lnk" start /B cmd /C "4.lnk" </code></pre>
[ { "answer_id": 270857, "author": "Bill Karwin", "author_id": 20860, "author_profile": "https://Stackoverflow.com/users/20860", "pm_score": 5, "selected": true, "text": "<p>The MySQL JDBC driver times out after 8 hours of inactivity and drops the connection.</p>\n\n<p>You can set <code>autoReconnect=true</code> in your JDBC URL, and this causes the driver to reconnect if you try to query after it has disconnected. But this has side effects; for instance session state and transactions cannot be maintained over a new connection.</p>\n\n<p>If you use <code>autoReconnect</code>, the JDBC connection is reestablished, but it doesn't automatically re-execute your query that got the exception. So you do need to catch <code>SQLException</code> in your application and retry queries.</p>\n\n<p>Read <a href=\"http://dev.mysql.com/doc/refman/5.0/en/connector-j-reference-configuration-properties.html\" rel=\"noreferrer\">http://dev.mysql.com/doc/refman/5.0/en/connector-j-reference-configuration-properties.html</a> for more details.</p>\n" }, { "answer_id": 270944, "author": "paxdiablo", "author_id": 14860, "author_profile": "https://Stackoverflow.com/users/14860", "pm_score": 1, "selected": false, "text": "<p>I would suggest that, in almost any client/server set-up, it's a bad idea to leave connections open when they're not needed.</p>\n\n<p>I'm thinking specifically about DB2/z connections but it applies equally to all servers (database and otherwise). These connections consume resources at the server that could be best utilized elsewhere.</p>\n\n<p>If you were to hold connections open in a corporate environment where tens of thousand of clients connect to the database, you would probably even bring a mainframe to its knees.</p>\n\n<p>I'm all for the idea of connection pooling but not so much for the idea of trying to hold individual sessions open for ever.</p>\n\n<p>My advice would be as follows:</p>\n\n<p>1/ Have three sorts of connections in your connection pool:</p>\n\n<ul>\n<li>closed (so not actually <strong>in</strong> your pool).</li>\n<li>ready, meaning open but not in use by a client.</li>\n<li>active, meaning in use by a client.</li>\n</ul>\n\n<p>2/ Have your connection pooling maintain a small number of ready connections, minimum of N and maximum of M. N can be adjusted depending on the peak speed at which your clients request connections. If the number of ready connections ever drops to zero, you need a bigger N.</p>\n\n<p>3/ When a client wants a connection, give them one of the ready ones (making it active), then immediately open a new one if there's now less than N ready (but don't make the client wait for this to complete, or you'll lose the advantage of pooling). This ensures there will always be at least N ready connections. If none are ready when the client wants one, they will have to wait around while you create a new one.</p>\n\n<p>4/ When the client finishes with an active connection, return it to the ready state if there's less than M ready connections. Otherwise close it. This prevents you from having more than M ready connections.</p>\n\n<p>5/ Periodically recycle the ready connections to prevent stale connections. If there's more than N ready connections, just close the oldest connection. Otherwise close it and re-open another.</p>\n\n<p>This has the advantage of having enough ready <strong>AND</strong> youthful connections available in your connection pool without overloading the server.</p>\n" }, { "answer_id": 847036, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 3, "selected": false, "text": "<p>MySql basically timeouts by default in <strong>8 hours</strong>.</p>\n\n<p>I got the same exception &amp; resolved the issue after 3 hectic days.Check if you are using I hibernate3. In this version it is required to explicitly mention the connection class name. Also check if the jar is in classpath. Check steps &amp; comments in below link </p>\n\n<p><a href=\"http://hibernatedb.blogspot.com/2009/05/automatic-reconnect-from-hibernate-to.html\" rel=\"noreferrer\">http://hibernatedb.blogspot.com/2009/05/automatic-reconnect-from-hibernate-to.html</a></p>\n\n<p>Remove <code>autoReconnect=true</code></p>\n" }, { "answer_id": 25129022, "author": "Bourkadi", "author_id": 1565794, "author_profile": "https://Stackoverflow.com/users/1565794", "pm_score": 2, "selected": false, "text": "<p>I changed my hibernate configuration file by adding thoses lines and it works for now:</p>\n\n<pre><code> &lt;property name=\"connection.autoReconnect\"&gt;true&lt;/property&gt;\n &lt;property name=\"connection.autoReconnectForPools\"&gt;true&lt;/property&gt;\n &lt;property name=\"connection.is-connection-validation-required\"&gt;true&lt;/property&gt;\n</code></pre>\n\n<p>I think that using c3p0 pool is better and recomanded but this solution is working for now and don't present ant problem.<br>\nI let the Tomcat On for 24hours and the connection wasn't lost .<br>\nPlease try it .</p>\n" } ]
2008/11/06
[ "https://Stackoverflow.com/questions/270811", "https://Stackoverflow.com", "https://Stackoverflow.com/users/34594/" ]
``` cmd /C "myshortcut1.lnk" cmd /C "myshortcut2.lnk" ``` Works, but gives me a pop-up DOS window which, when closed, kills my two loaded programs. Same is true for this: ``` start /B cmd /C "1.lnk" start /B cmd /C "2.lnk" start /B cmd /C "3.lnk" start /B cmd /C "4.lnk" ```
The MySQL JDBC driver times out after 8 hours of inactivity and drops the connection. You can set `autoReconnect=true` in your JDBC URL, and this causes the driver to reconnect if you try to query after it has disconnected. But this has side effects; for instance session state and transactions cannot be maintained over a new connection. If you use `autoReconnect`, the JDBC connection is reestablished, but it doesn't automatically re-execute your query that got the exception. So you do need to catch `SQLException` in your application and retry queries. Read <http://dev.mysql.com/doc/refman/5.0/en/connector-j-reference-configuration-properties.html> for more details.
270,825
<p>Has anyone else run into this problem before? I've got a method that calls a generic method with a delegate, inside of a generic class. I've marked the class as Serializable, and it serializes without complaint. But, when I try to deserialize an object of this class, it pegs the CPU and hangs the machine.</p> <p>Code example:</p> <pre><code>public delegate T CombinationFunctionDelegate&lt;T,U,V&gt;(U a, V b); [Serializable] public class SDictionary&lt;TKey, TValue&gt; : Dictionary&lt;TKey, TValue&gt; { public SDictionary() : base() { } protected SDictionary(SerializationInfo info, StreamingContext context) : base(info, context) {} [SecurityPermissionAttribute(SecurityAction.LinkDemand, Flags = SecurityPermissionFlag.SerializationFormatter)] public override void GetObjectData(SerializationInfo info, StreamingContext context) { base.GetObjectData(info, context); } public List&lt;ListItem&gt; ToListItems() { return Convert(delegate(TKey key, TValue value) { return new ListItem(key.ToString(), value.ToString()); }); } public List&lt;U&gt; Convert&lt;U&gt;(CombinationFunctionDelegate&lt;U, TKey, TValue&gt; converterFunction) { List&lt;U&gt; res = new List&lt;U&gt;(); foreach (TKey key in Keys) res.Add(converterFunction(key, this[key])); return res; } } </code></pre> <p>I can put an instance of this class into ViewState (for example) just fine, but when I try to extract the object from ViewState again, the CPU on the machine spikes and the deserialization call never returns (ie, infinite loop).</p> <p>When I remove the ToListItems() method, everything works wonderfully. Is this really weird, or do I just not understand serialization? =)</p>
[ { "answer_id": 270858, "author": "OJ.", "author_id": 611, "author_profile": "https://Stackoverflow.com/users/611", "pm_score": 0, "selected": false, "text": "<p>First of all, Dictionary&lt;> already implements ISerializable, so you don't need to specify that explicity!</p>\n\n<p>Second, you override GetObjectData(), but you don't seem to call Dictionary.GetObjectData(), so the dictionary may not be getting deserialised? Hence, when you access this.Keys, you end up with \"an issue\".</p>\n\n<p>Yes, I'm thinking out loud here ;)</p>\n\n<p>Perhaps you could try this:</p>\n\n<pre><code>public override void GetObjectData(SerializationInfo info, StreamingContext context)\n{\n // deserialize the dictionary first\n base.GetObjectData(info, context);\n\n // the rest of your code\n // ...\n}\n</code></pre>\n\n<p>I haven't tried or compiled this, but it could be something to consider?</p>\n\n<p>Good luck :)</p>\n" }, { "answer_id": 270886, "author": "OJ.", "author_id": 611, "author_profile": "https://Stackoverflow.com/users/611", "pm_score": 1, "selected": false, "text": "<p>This is the code I currently have, which works fine?</p>\n\n<pre><code> [Serializable]\n public class SDictionary&lt;TKey, TValue&gt; : Dictionary&lt;TKey, TValue&gt;\n {\n public SDictionary()\n : base()\n {\n }\n\n protected SDictionary(SerializationInfo info, StreamingContext context)\n : base(info, context)\n {\n }\n\n public List&lt;ListItem&gt; ToListItems()\n {\n return this.Convert(delegate(TKey key, TValue value)\n {\n return new ListItem(key.ToString(), value.ToString());\n });\n }\n\n public List&lt;U&gt; Convert&lt;U&gt;(CombinationFunctionDelegate&lt;U, TKey, TValue&gt; converterFunction)\n {\n List&lt;U&gt; res = new List&lt;U&gt;();\n foreach (TKey key in Keys)\n res.Add(converterFunction(key, this[key]));\n\n return res;\n }\n\n\n }\n\n class Program\n {\n\n static void Main(string[] args)\n {\n SDictionary&lt;string, string&gt; b = new SDictionary&lt;string, string&gt;();\n b.Add(\"foo\", \"bar\");\n\n System.IO.MemoryStream memStream = new System.IO.MemoryStream();\n System.Runtime.Serialization.Formatters.Binary.BinaryFormatter f = new System.Runtime.Serialization.Formatters.Binary.BinaryFormatter();\n f.Serialize(memStream, b);\n memStream.Position = 0;\n\n b = f.Deserialize(memStream) as SDictionary&lt;string, string&gt;;\n }\n\n }\n</code></pre>\n\n<p>Does that help at all?</p>\n\n<p>Edit: Tweaked again.</p>\n" }, { "answer_id": 271004, "author": "Amy B", "author_id": 8155, "author_profile": "https://Stackoverflow.com/users/8155", "pm_score": 0, "selected": false, "text": "<p>Could it be that the anonymous method has a reference to the instance that it resides in? I can't answer that.</p>\n\n<p>Your comment indicates that this is possible. Here's the simplest way out: don't use anonymous methods.</p>\n\n<pre><code>public ListItem ToListItem(TKey key, TValue value)\n{\n return new ListItem(key.ToString(), value.ToString());\n}\n</code></pre>\n\n<hr>\n\n<p>What I can answer, is that the methods on this class can be issued against the public contract of Dictionary&lt; T, U >, and so there is no need for this class when you could write extension methods against Dictionary&lt; T, U > (assuming C# 3)</p>\n\n<p>Something like this (freehand code so may not be 100% correct)</p>\n\n<pre><code>public static List&lt;ListItem&gt; ToListItems(this Dictionary&lt;T, U&gt; source)\n{\n return source\n .Select(x =&gt; new ListItem(x.key.ToString(), x.value.ToString()))\n .ToList();\n}\n\npublic static List&lt;V&gt; Convert&lt;V&gt;\n(\n this Dictionary&lt;T, U&gt; source,\n Func&lt;T, U, V&gt; converterFunction\n)\n{\n return source\n .Select(x =&gt; converterFunction(x.Key, x.Value))\n .ToList();\n}\n</code></pre>\n" }, { "answer_id": 272129, "author": "eduesing", "author_id": 322538, "author_profile": "https://Stackoverflow.com/users/322538", "pm_score": 1, "selected": true, "text": "<p>Are you using VS2008 SP1? There's a known problem with SP1.<br>\n<a href=\"https://connect.microsoft.com/VisualStudio/feedback/ViewFeedback.aspx?FeedbackID=361615\" rel=\"nofollow noreferrer\">https://connect.microsoft.com/VisualStudio/feedback/ViewFeedback.aspx?FeedbackID=361615</a></p>\n" }, { "answer_id": 273077, "author": "Badjer", "author_id": 35308, "author_profile": "https://Stackoverflow.com/users/35308", "pm_score": 0, "selected": false, "text": "<p>Here's the <a href=\"http://support2.microsoft.com/kb/957543\" rel=\"nofollow noreferrer\">knowledge base article</a> on the bug, too, if anyone needs it:</p>\n<blockquote>\n<p>On a computer that is running the Microsoft .NET Framework 3.5 Service Pack 1 (SP1), you have an application that serializes and deserializes a generic class. If the generic class has at least one static member, you may encounter one of the following symptoms:</p>\n<ul>\n<li>If the application is running as a 32-bit process, the thread that performs the deserialization may enter a loop. Therefore, the application fails, and the application consumes lots of CPU resources.</li>\n<li>If the application is running as a 64-bit process, an exception is thrown, and you receive an error message that resembles the following:</li>\n</ul>\n</blockquote>\n" } ]
2008/11/06
[ "https://Stackoverflow.com/questions/270825", "https://Stackoverflow.com", "https://Stackoverflow.com/users/35308/" ]
Has anyone else run into this problem before? I've got a method that calls a generic method with a delegate, inside of a generic class. I've marked the class as Serializable, and it serializes without complaint. But, when I try to deserialize an object of this class, it pegs the CPU and hangs the machine. Code example: ``` public delegate T CombinationFunctionDelegate<T,U,V>(U a, V b); [Serializable] public class SDictionary<TKey, TValue> : Dictionary<TKey, TValue> { public SDictionary() : base() { } protected SDictionary(SerializationInfo info, StreamingContext context) : base(info, context) {} [SecurityPermissionAttribute(SecurityAction.LinkDemand, Flags = SecurityPermissionFlag.SerializationFormatter)] public override void GetObjectData(SerializationInfo info, StreamingContext context) { base.GetObjectData(info, context); } public List<ListItem> ToListItems() { return Convert(delegate(TKey key, TValue value) { return new ListItem(key.ToString(), value.ToString()); }); } public List<U> Convert<U>(CombinationFunctionDelegate<U, TKey, TValue> converterFunction) { List<U> res = new List<U>(); foreach (TKey key in Keys) res.Add(converterFunction(key, this[key])); return res; } } ``` I can put an instance of this class into ViewState (for example) just fine, but when I try to extract the object from ViewState again, the CPU on the machine spikes and the deserialization call never returns (ie, infinite loop). When I remove the ToListItems() method, everything works wonderfully. Is this really weird, or do I just not understand serialization? =)
Are you using VS2008 SP1? There's a known problem with SP1. <https://connect.microsoft.com/VisualStudio/feedback/ViewFeedback.aspx?FeedbackID=361615>
270,835
<p>I am trying to provide my own labelFunction for a CategoryAxis programatically but am completely stumped. The regular way is to do it in your MXML file, but I want to do it in my Actionscript file.</p> <p>The regular way of doing it is:</p> <pre><code>&lt;mx:Script&gt; &lt;![CDATA[ private function categoryAxis_labelFunc(item:Object, prevValue:Object, axis:CategoryAxis, categoryItem:Object):String { return "Some String"; } ]]&gt; &lt;/mx:Script&gt; &lt;mx:CategoryAxis labelFunction="categoryAxis_labelFunc" /&gt; </code></pre> <p>But I want to achieve the same thing in my subclass of CategoryAxis, something like:</p> <pre><code>public class FauxDateAxis extends CategoryAxis { public function FauxDateAxis() { super(); labelFunction = categoryAxis_labelFunc // Doesn't work of course. } private function categoryAxis_labelFunc(item:Object, prevValue:Object, axis:CategoryAxis, categoryItem:Object):String { return "Another String"; } } </code></pre>
[ { "answer_id": 271352, "author": "Mitch Haile", "author_id": 28807, "author_profile": "https://Stackoverflow.com/users/28807", "pm_score": 1, "selected": false, "text": "<p>This question got me curious, so I went off and tried it.</p>\n\n<p>The labelFunction on CategoryAxis has a slightly different signature than what I am seeing here. For me, this is what works:</p>\n\n<pre><code>function(item:Object, field:String, index:int, pct:Number)\n</code></pre>\n\n<p>I am not a Flex charts wizard, so perhaps you know something I don't, but when I use that signature in this matter,</p>\n\n<pre><code>public function FauxDateAxis() {\n super();\n labelFunction = function(item:Object, field:String, index:int, pct:Number) {\n return \"string\";\n }\n}\n</code></pre>\n\n<p>It works for me in Flex 3 Pro.</p>\n\n<p>I see that the code sample you provided looks a lot like <a href=\"http://blog.flexexamples.com/2007/11/16/creating-a-custom-label-function-on-a-flex-linechart-controls-category-axis/\" rel=\"nofollow noreferrer\">http://blog.flexexamples.com/2007/11/16/creating-a-custom-label-function-on-a-flex-linechart-controls-category-axis/</a> (I tried to see if I could find an example of the signature you provided). I see other people using this signature too.</p>\n\n<p>This isn't much of an answer; I don't recall this part of the charts API changing between Flex 2 and Flex 3, but maybe this post helps you with your problem.</p>\n" }, { "answer_id": 278855, "author": "Randy Stegbauer", "author_id": 34301, "author_profile": "https://Stackoverflow.com/users/34301", "pm_score": 3, "selected": true, "text": "<p>Well, I'm baffled by your problem, because it works absolutely fine for me.</p>\n\n<p>I took the example application for CategoryAxis from the Adobe Flex site:\n <a href=\"http://livedocs.adobe.com/flex/3/langref/index.html?mx/charts/CategoryAxis.html&amp;mx/charts/class-list.html\" rel=\"nofollow noreferrer\">http://livedocs.adobe.com/flex/3/langref/index.html?mx/charts/CategoryAxis.html&amp;mx/charts/class-list.html</a>, added your code verbatim (well except for adding package and import statments), and it worked just like you want it to.</p>\n\n<p>In the example, I modified the line</p>\n\n<pre><code>&lt;mx:CategoryAxis id=\"haxis\" categoryField=\"Date\" title=\"Date\"/&gt;\n</code></pre>\n\n<p>to read</p>\n\n<pre><code>&lt;local:FauxDateAxis id=\"haxis\" categoryField=\"Date\" title=\"Date\"/&gt;\n</code></pre>\n\n<p>and it displayed \"Another String\" at the base of each column.</p>\n\n<p>I'm using Flex 3, if that matters.</p>\n\n<p>Good Luck,\nRandy Stegbauer</p>\n" }, { "answer_id": 280809, "author": "Matt MacLean", "author_id": 22, "author_profile": "https://Stackoverflow.com/users/22", "pm_score": 0, "selected": false, "text": "<p>Just I though, I don't think it will make a difference, but maybe change your label function scope to protected rather than private???</p>\n" } ]
2008/11/06
[ "https://Stackoverflow.com/questions/270835", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3410/" ]
I am trying to provide my own labelFunction for a CategoryAxis programatically but am completely stumped. The regular way is to do it in your MXML file, but I want to do it in my Actionscript file. The regular way of doing it is: ``` <mx:Script> <![CDATA[ private function categoryAxis_labelFunc(item:Object, prevValue:Object, axis:CategoryAxis, categoryItem:Object):String { return "Some String"; } ]]> </mx:Script> <mx:CategoryAxis labelFunction="categoryAxis_labelFunc" /> ``` But I want to achieve the same thing in my subclass of CategoryAxis, something like: ``` public class FauxDateAxis extends CategoryAxis { public function FauxDateAxis() { super(); labelFunction = categoryAxis_labelFunc // Doesn't work of course. } private function categoryAxis_labelFunc(item:Object, prevValue:Object, axis:CategoryAxis, categoryItem:Object):String { return "Another String"; } } ```
Well, I'm baffled by your problem, because it works absolutely fine for me. I took the example application for CategoryAxis from the Adobe Flex site: <http://livedocs.adobe.com/flex/3/langref/index.html?mx/charts/CategoryAxis.html&mx/charts/class-list.html>, added your code verbatim (well except for adding package and import statments), and it worked just like you want it to. In the example, I modified the line ``` <mx:CategoryAxis id="haxis" categoryField="Date" title="Date"/> ``` to read ``` <local:FauxDateAxis id="haxis" categoryField="Date" title="Date"/> ``` and it displayed "Another String" at the base of each column. I'm using Flex 3, if that matters. Good Luck, Randy Stegbauer
270,845
<p>I've been trying to come up with a way to write generic repositories that work against various data stores:</p> <pre><code>public interface IRepository { IQueryable&lt;T&gt; GetAll&lt;T&gt;(); void Save&lt;T&gt;(T item); void Delete&lt;T&gt;(T item); } public class MemoryRepository : IRepository {...} public class SqlRepository : IRepository {...} </code></pre> <p>I'd like to work against the same POCO domain classes in each. I'm also considering a similar approach, where each domain class has it's own repository:</p> <pre><code>public interface IRepository&lt;T&gt; { IQueryable&lt;T&gt; GetAll(); void Save(T item); void Delete(T item); } public class MemoryCustomerRepository : IRepository {...} public class SqlCustomerRepository : IRepository {...} </code></pre> <p>My questions: 1)Is the first approach even feasible? 2)Is there any advantage to the second approach. </p>
[ { "answer_id": 271216, "author": "cfeduke", "author_id": 5645, "author_profile": "https://Stackoverflow.com/users/5645", "pm_score": 3, "selected": false, "text": "<ol>\n<li><p>The first approach is feasible, I have done something similar in the past when I wrote my own mapping framework that targeted RDBMS and <code>XmlWriter</code>/<code>XmlReader</code>. You can use this sort of approach to ease unit testing, though I think now we have superior OSS tools for doing just that.</p></li>\n<li><p>The second approach is what I currently use now with <a href=\"http://ibatis.apache.org/dotnetdownloads.cgi\" rel=\"nofollow noreferrer\">IBATIS.NET mappers</a>. Every mapper has an interface and every mapper [could] provide your basic CRUD operations. The advantage is each mapper for a domain class also has specific functions (such as <code>SelectByLastName</code> or <code>DeleteFromParent</code>) that are expressed by an interface and defined in the concrete mapper. Because of this there's no need for me to implement separate repositories as you're suggesting - our concrete mappers target the database. To perform unit tests I use <a href=\"http://structuremap.sourceforge.net/Default.htm\" rel=\"nofollow noreferrer\">StructureMap</a> and <a href=\"http://code.google.com/p/moq/\" rel=\"nofollow noreferrer\">Moq</a> to create in-memory repositories that operate as your <code>Memory*Repository</code> does. Its less classes to implement and manage and less work overall for a very testable approach. For data shared across unit tests I use a builder pattern for each domain class which has <code>WithXXX</code> methods and <code>AsSomeProfile</code> methods (the <code>AsSomeProfile</code> just returns a builder instance with preconfigured test data).</p></li>\n</ol>\n\n<p>Here's an example of what I usually end up with in my unit tests:</p>\n\n<pre><code>// Moq mocking the concrete PersonMapper through the IPersonMapper interface\nvar personMock = new Mock&lt;IPersonMapper&gt;(MockBehavior.Strict);\npersonMock.Expect(pm =&gt; pm.Select(It.IsAny&lt;int&gt;())).Returns(\n new PersonBuilder().AsMike().Build()\n);\n\n// StructureMap's ObjectFactory\nObjectFactory.Inject(personMock.Object);\n\n// now anywhere in my actual code where an IPersonMapper instance is requested from\n// ObjectFactory, Moq will satisfy the requirement and return a Person instance\n// set with the PersonBuilder's Mike profile unit test data\n</code></pre>\n" }, { "answer_id": 522657, "author": "thinkbeforecoding", "author_id": 47001, "author_profile": "https://Stackoverflow.com/users/47001", "pm_score": 2, "selected": false, "text": "<p>Actually there is a general consensus now that Domain repositories should not be generic. Your repository should express what you can do when persisting or retrieving your entities.</p>\n\n<p>Some repositories are readonly, some are insert only (no update, no delete), some have only specific lookups...</p>\n\n<p>Using a GetAll return IQueryable, your query logic will leak into your code, possibly to the application layer.</p>\n\n<p>But it's still interesting to use the kind of interface you provide to encapsulate Linq <code>Table&lt;T&gt;</code> objects so that you can replace it with an in memory implementation for test purpose.</p>\n\n<p>So I suggest, to call it <code>ITable&lt;T&gt;</code>, give it the same interface that the linq <code>Table&lt;T&gt;</code> object, and use it <strong>inside</strong> your specific domain repositories (not instead of).</p>\n\n<p>You can then use you specific repositories in memory by using a in memory <code>ITable&lt;T&gt;</code> implementation.</p>\n\n<p>The simplest way to implement <code>ITable&lt;T&gt;</code> in memory is to use a <code>List&lt;T&gt;</code> and get a <code>IQueryable&lt;T&gt;</code> interface using the .AsQueryable() extension method.</p>\n\n<pre><code>public class InMemoryTable&lt;T&gt; : ITable&lt;T&gt;\n{\n private List&lt;T&gt; list;\n private IQueryable&lt;T&gt; queryable;\n\n public InMemoryTable&lt;T&gt;(List&lt;T&gt; list)\n { \n this.list = list;\n this.queryable = list.AsQueryable();\n }\n\n public void Add(T entity) { list.Add(entity); }\n public void Remove(T entity) { list.Remove(entity); }\n\n public IEnumerator&lt;T&gt; GetEnumerator() { return list.GetEnumerator(); }\n\n public Type ElementType { get { return queryable.ElementType; } }\n public IQueryProvider Provider { get { return queryable.Provider; } }\n ...\n}\n</code></pre>\n\n<p>You can work in isolation of the database for testing, but with true specific repositories that give more domain insight.</p>\n" }, { "answer_id": 2418996, "author": "Val", "author_id": 290726, "author_profile": "https://Stackoverflow.com/users/290726", "pm_score": 2, "selected": false, "text": "<p>This is a bit late... but take a look at the IRepository implementation at <a href=\"http://commonlibrarynet.codeplex.com\" rel=\"nofollow noreferrer\">CommonLibrary.NET</a> on codeplex. It's got a pretty good feature set.</p>\n\n<p>Regarding your problem, I see a lot of people using methods like GetAllProducts(), GetAllEmployees()\nin their repository implementation. This is redundant and doesn't allow your repository to be generic.\nAll you need is GetAll() or All(). The solution provided above does solve the naming problem though.</p>\n\n<p>This is taken from CommonLibrary.NET documentation online:</p>\n\n<p>0.9.4 Beta 2 has a powerful Repository implementation.</p>\n\n<pre><code>* Supports all CRUD methods ( Create, Retrieve, Update, Delete )\n* Supports aggregate methods Min, Max, Sum, Avg, Count\n* Supports Find methods using ICriteria&lt;T&gt;\n* Supports Distinct, and GroupBy\n* Supports interface IRepository&lt;T&gt; so you can use an In-Memory table for unit-testing\n* Supports versioning of your entities\n* Supports paging, eg. Get(page, pageSize)\n* Supports audit fields ( CreateUser, CreatedDate, UpdateDate etc )\n* Supports the use of Mapper&lt;T&gt; so you can map any table record to some entity\n* Supports creating entities only if it isn't there already, by checking for field values.\n</code></pre>\n" } ]
2008/11/07
[ "https://Stackoverflow.com/questions/270845", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
I've been trying to come up with a way to write generic repositories that work against various data stores: ``` public interface IRepository { IQueryable<T> GetAll<T>(); void Save<T>(T item); void Delete<T>(T item); } public class MemoryRepository : IRepository {...} public class SqlRepository : IRepository {...} ``` I'd like to work against the same POCO domain classes in each. I'm also considering a similar approach, where each domain class has it's own repository: ``` public interface IRepository<T> { IQueryable<T> GetAll(); void Save(T item); void Delete(T item); } public class MemoryCustomerRepository : IRepository {...} public class SqlCustomerRepository : IRepository {...} ``` My questions: 1)Is the first approach even feasible? 2)Is there any advantage to the second approach.
1. The first approach is feasible, I have done something similar in the past when I wrote my own mapping framework that targeted RDBMS and `XmlWriter`/`XmlReader`. You can use this sort of approach to ease unit testing, though I think now we have superior OSS tools for doing just that. 2. The second approach is what I currently use now with [IBATIS.NET mappers](http://ibatis.apache.org/dotnetdownloads.cgi). Every mapper has an interface and every mapper [could] provide your basic CRUD operations. The advantage is each mapper for a domain class also has specific functions (such as `SelectByLastName` or `DeleteFromParent`) that are expressed by an interface and defined in the concrete mapper. Because of this there's no need for me to implement separate repositories as you're suggesting - our concrete mappers target the database. To perform unit tests I use [StructureMap](http://structuremap.sourceforge.net/Default.htm) and [Moq](http://code.google.com/p/moq/) to create in-memory repositories that operate as your `Memory*Repository` does. Its less classes to implement and manage and less work overall for a very testable approach. For data shared across unit tests I use a builder pattern for each domain class which has `WithXXX` methods and `AsSomeProfile` methods (the `AsSomeProfile` just returns a builder instance with preconfigured test data). Here's an example of what I usually end up with in my unit tests: ``` // Moq mocking the concrete PersonMapper through the IPersonMapper interface var personMock = new Mock<IPersonMapper>(MockBehavior.Strict); personMock.Expect(pm => pm.Select(It.IsAny<int>())).Returns( new PersonBuilder().AsMike().Build() ); // StructureMap's ObjectFactory ObjectFactory.Inject(personMock.Object); // now anywhere in my actual code where an IPersonMapper instance is requested from // ObjectFactory, Moq will satisfy the requirement and return a Person instance // set with the PersonBuilder's Mike profile unit test data ```
270,874
<p>I have a DataTrigger defined in my XAML which I want to use in several places. Is it possible to define it as a resource and then share it?</p> <p>Here's my trigger:</p> <pre><code>&lt;TextBlock.Style&gt; &lt;Style&gt; &lt;Style.Triggers&gt; &lt;DataTrigger Binding="{Binding HasCurrentTest}" Value="True"&gt; &lt;Setter Property="TextBlock.Visibility" Value="Hidden" /&gt; &lt;/DataTrigger&gt; &lt;/Style.Triggers&gt; &lt;/Style&gt; &lt;/TextBlock.Style&gt; </code></pre> <p>While I can define this in my Window.Resources and give it a key, how do I refer to it in the rest of my XAML?</p>
[ { "answer_id": 270904, "author": "MrSlippers", "author_id": 35290, "author_profile": "https://Stackoverflow.com/users/35290", "pm_score": 1, "selected": false, "text": "<p>If the style is in the Windows.Resources with a key, each element can add it to their own style like this.</p>\n\n<pre><code>&lt;Window.Resources&gt;\n &lt;Style x:Key=\"YourStyleKey\"&gt;\n &lt;!-- Your Style --&gt;\n &lt;/Style&gt;\n&lt;/Window.Resources&gt;\n\n&lt;TextBox Text=\"SomeText\" Style=\"{StaticResource YourStyleKey}\"/&gt;\n&lt;TextBox Text=\"SomeOtherText\" Style=\"{StaticResource YourStyleKey}\"/&gt;\n</code></pre>\n" }, { "answer_id": 271005, "author": "Craig Shearer", "author_id": 14537, "author_profile": "https://Stackoverflow.com/users/14537", "pm_score": 2, "selected": false, "text": "<p>As a comment on my own post, I've just seen a much better way to do this anyway - I should be using the built-in BooleanToVisibilityConverter, then I can just do this:</p>\n\n<pre><code>&lt;Window.Resources&gt;\n &lt;BooleanToVisibilityConverter x:Key=\"BoolToVis\" /&gt;\n&lt;/Window.Resources&gt;\n</code></pre>\n\n<p>then...</p>\n\n<pre><code>&lt;TextBlock Visibility=\"{Binding HasNoCurrentTest, \n Converter={StaticResource BoolToVis}}\" /&gt;\n</code></pre>\n\n<p>which is a much better solution!</p>\n" } ]
2008/11/07
[ "https://Stackoverflow.com/questions/270874", "https://Stackoverflow.com", "https://Stackoverflow.com/users/14537/" ]
I have a DataTrigger defined in my XAML which I want to use in several places. Is it possible to define it as a resource and then share it? Here's my trigger: ``` <TextBlock.Style> <Style> <Style.Triggers> <DataTrigger Binding="{Binding HasCurrentTest}" Value="True"> <Setter Property="TextBlock.Visibility" Value="Hidden" /> </DataTrigger> </Style.Triggers> </Style> </TextBlock.Style> ``` While I can define this in my Window.Resources and give it a key, how do I refer to it in the rest of my XAML?
As a comment on my own post, I've just seen a much better way to do this anyway - I should be using the built-in BooleanToVisibilityConverter, then I can just do this: ``` <Window.Resources> <BooleanToVisibilityConverter x:Key="BoolToVis" /> </Window.Resources> ``` then... ``` <TextBlock Visibility="{Binding HasNoCurrentTest, Converter={StaticResource BoolToVis}}" /> ``` which is a much better solution!
270,879
<p>I'm starting a new application and looking at using an ORM -- in particular, SQLAlchemy.</p> <p>Say I've got a column 'foo' in my database and I want to increment it. In straight sqlite, this is easy:</p> <pre><code>db = sqlite3.connect('mydata.sqlitedb') cur = db.cursor() cur.execute('update table stuff set foo = foo + 1') </code></pre> <p>I figured out the SQLAlchemy SQL-builder equivalent:</p> <pre><code>engine = sqlalchemy.create_engine('sqlite:///mydata.sqlitedb') md = sqlalchemy.MetaData(engine) table = sqlalchemy.Table('stuff', md, autoload=True) upd = table.update(values={table.c.foo:table.c.foo+1}) engine.execute(upd) </code></pre> <p>This is slightly slower, but there's not much in it.</p> <p>Here's my best guess for a SQLAlchemy ORM approach:</p> <pre><code># snip definition of Stuff class made using declarative_base # snip creation of session object for c in session.query(Stuff): c.foo = c.foo + 1 session.flush() session.commit() </code></pre> <p>This does the right thing, but it takes just under fifty times as long as the other two approaches. I presume that's because it has to bring all the data into memory before it can work with it.</p> <p>Is there any way to generate the efficient SQL using SQLAlchemy's ORM? Or using any other python ORM? Or should I just go back to writing the SQL by hand?</p>
[ { "answer_id": 270891, "author": "Matthew Schinckel", "author_id": 188, "author_profile": "https://Stackoverflow.com/users/188", "pm_score": 1, "selected": false, "text": "<p>Withough testing, I'd try:</p>\n\n<pre><code>for c in session.query(Stuff).all():\n c.foo = c.foo+1\nsession.commit()\n</code></pre>\n\n<p>(IIRC, commit() works without flush()).</p>\n\n<p>I've found that at times doing a large query and then iterating in python can be up to 2 orders of magnitude faster than lots of queries. I assume that iterating over the query object is less efficient than iterating over a list generated by the all() method of the query object.</p>\n\n<p>[Please note comment below - this did not speed things up at all].</p>\n" }, { "answer_id": 270942, "author": "Matthew Schinckel", "author_id": 188, "author_profile": "https://Stackoverflow.com/users/188", "pm_score": 2, "selected": false, "text": "<p>If it is because of the overhead in terms of creating objects, then it probably can't be sped up at all with SA.</p>\n\n<p>If it is because it is loading up related objects, then you might be able to do something with lazy loading. Are there lots of objects being created due to references? (IE, getting a Company object also gets all of the related People objects).</p>\n" }, { "answer_id": 278606, "author": "Ants Aasma", "author_id": 107366, "author_profile": "https://Stackoverflow.com/users/107366", "pm_score": 9, "selected": true, "text": "<p>SQLAlchemy's ORM is meant to be used together with the SQL layer, not hide it. But you do have to keep one or two things in mind when using the ORM and plain SQL in the same transaction. Basically, from one side, ORM data modifications will only hit the database when you flush the changes from your session. From the other side, SQL data manipulation statements don't affect the objects that are in your session.</p>\n\n<p>So if you say</p>\n\n<pre><code>for c in session.query(Stuff).all():\n c.foo = c.foo+1\nsession.commit()\n</code></pre>\n\n<p>it will do what it says, go fetch all the objects from the database, modify all the objects and then when it's time to flush the changes to the database, update the rows one by one.</p>\n\n<p>Instead you should do this:</p>\n\n<pre><code>session.execute(update(stuff_table, values={stuff_table.c.foo: stuff_table.c.foo + 1}))\nsession.commit()\n</code></pre>\n\n<p>This will execute as one query as you would expect, and because at least the default session configuration expires all data in the session on commit you don't have any stale data issues.</p>\n\n<p>In the almost-released 0.5 series you could also use this method for updating:</p>\n\n<pre><code>session.query(Stuff).update({Stuff.foo: Stuff.foo + 1})\nsession.commit()\n</code></pre>\n\n<p>That will basically run the same SQL statement as the previous snippet, but also select the changed rows and expire any stale data in the session. If you know you aren't using any session data after the update you could also add <code>synchronize_session=False</code> to the update statement and get rid of that select.</p>\n" }, { "answer_id": 4540110, "author": "Vin", "author_id": 555137, "author_profile": "https://Stackoverflow.com/users/555137", "pm_score": 7, "selected": false, "text": "<pre><code>session.query(Clients).filter(Clients.id == client_id_list).update({'status': status})\nsession.commit()\n</code></pre>\n\n<p>Try this =)</p>\n" }, { "answer_id": 32447458, "author": "plowman", "author_id": 426794, "author_profile": "https://Stackoverflow.com/users/426794", "pm_score": 4, "selected": false, "text": "<p>Here's an example of how to solve the same problem without having to map the fields manually:</p>\n\n<pre><code>from sqlalchemy import Column, ForeignKey, Integer, String, Date, DateTime, text, create_engine\nfrom sqlalchemy.exc import IntegrityError\nfrom sqlalchemy.ext.declarative import declarative_base\nfrom sqlalchemy.orm import sessionmaker\nfrom sqlalchemy.orm.attributes import InstrumentedAttribute\n\nengine = create_engine('postgres://postgres@localhost:5432/database')\nsession = sessionmaker()\nsession.configure(bind=engine)\n\nBase = declarative_base()\n\n\nclass Media(Base):\n __tablename__ = 'media'\n id = Column(Integer, primary_key=True)\n title = Column(String, nullable=False)\n slug = Column(String, nullable=False)\n type = Column(String, nullable=False)\n\n def update(self):\n s = session()\n mapped_values = {}\n for item in Media.__dict__.iteritems():\n field_name = item[0]\n field_type = item[1]\n is_column = isinstance(field_type, InstrumentedAttribute)\n if is_column:\n mapped_values[field_name] = getattr(self, field_name)\n\n s.query(Media).filter(Media.id == self.id).update(mapped_values)\n s.commit()\n</code></pre>\n\n<p>So to update a Media instance, you can do something like this:</p>\n\n<pre><code>media = Media(id=123, title=\"Titular Line\", slug=\"titular-line\", type=\"movie\")\nmedia.update()\n</code></pre>\n" }, { "answer_id": 33638391, "author": "Nima Soroush", "author_id": 1952158, "author_profile": "https://Stackoverflow.com/users/1952158", "pm_score": 5, "selected": false, "text": "<p>There are several ways to UPDATE using sqlalchemy</p>\n<pre><code>1) for c in session.query(Stuff).all():\n c.foo += 1\n session.commit()\n\n2) session.query(Stuff).update({&quot;foo&quot;: Stuff.foo + 1})\n session.commit()\n\n3) conn = engine.connect()\n table = Stuff.__table__\n stmt = table.update().values({'foo': Stuff.foo + 'a'})\n conn.execute(stmt)\n conn.commit()\n</code></pre>\n" } ]
2008/11/07
[ "https://Stackoverflow.com/questions/270879", "https://Stackoverflow.com", "https://Stackoverflow.com/users/15154/" ]
I'm starting a new application and looking at using an ORM -- in particular, SQLAlchemy. Say I've got a column 'foo' in my database and I want to increment it. In straight sqlite, this is easy: ``` db = sqlite3.connect('mydata.sqlitedb') cur = db.cursor() cur.execute('update table stuff set foo = foo + 1') ``` I figured out the SQLAlchemy SQL-builder equivalent: ``` engine = sqlalchemy.create_engine('sqlite:///mydata.sqlitedb') md = sqlalchemy.MetaData(engine) table = sqlalchemy.Table('stuff', md, autoload=True) upd = table.update(values={table.c.foo:table.c.foo+1}) engine.execute(upd) ``` This is slightly slower, but there's not much in it. Here's my best guess for a SQLAlchemy ORM approach: ``` # snip definition of Stuff class made using declarative_base # snip creation of session object for c in session.query(Stuff): c.foo = c.foo + 1 session.flush() session.commit() ``` This does the right thing, but it takes just under fifty times as long as the other two approaches. I presume that's because it has to bring all the data into memory before it can work with it. Is there any way to generate the efficient SQL using SQLAlchemy's ORM? Or using any other python ORM? Or should I just go back to writing the SQL by hand?
SQLAlchemy's ORM is meant to be used together with the SQL layer, not hide it. But you do have to keep one or two things in mind when using the ORM and plain SQL in the same transaction. Basically, from one side, ORM data modifications will only hit the database when you flush the changes from your session. From the other side, SQL data manipulation statements don't affect the objects that are in your session. So if you say ``` for c in session.query(Stuff).all(): c.foo = c.foo+1 session.commit() ``` it will do what it says, go fetch all the objects from the database, modify all the objects and then when it's time to flush the changes to the database, update the rows one by one. Instead you should do this: ``` session.execute(update(stuff_table, values={stuff_table.c.foo: stuff_table.c.foo + 1})) session.commit() ``` This will execute as one query as you would expect, and because at least the default session configuration expires all data in the session on commit you don't have any stale data issues. In the almost-released 0.5 series you could also use this method for updating: ``` session.query(Stuff).update({Stuff.foo: Stuff.foo + 1}) session.commit() ``` That will basically run the same SQL statement as the previous snippet, but also select the changed rows and expire any stale data in the session. If you know you aren't using any session data after the update you could also add `synchronize_session=False` to the update statement and get rid of that select.
270,884
<p>I've been doing some socket programming to transmit information across the wire. I've run into a problem with DataOutputStream.writeUTF(). It seems to allow strings of up to 64k but I have a few situations where I can run over this. Are there any good alternatives that support larger strings or do I need to roll my own?</p>
[ { "answer_id": 270915, "author": "Bill the Lizard", "author_id": 1288, "author_profile": "https://Stackoverflow.com/users/1288", "pm_score": 1, "selected": false, "text": "<p>You should be able to use <a href=\"http://java.sun.com/j2se/1.4.2/docs/api/java/io/OutputStreamWriter.html\" rel=\"nofollow noreferrer\">OutputStreamWriter</a> with the UTF-8 encoding. There's no explicit writeUTF method, but you can set the charset in the constructor. Try</p>\n\n<pre><code>Writer osw = new OutputStreamWriter(out, \"UTF-8\");\n</code></pre>\n\n<p>where <code>out</code> is whatever OutputStream you're wrapping now.</p>\n" }, { "answer_id": 270922, "author": "kasperjj", "author_id": 34240, "author_profile": "https://Stackoverflow.com/users/34240", "pm_score": 5, "selected": true, "text": "<p>It actually uses a two bytes to write the length of the string before using an algorithm that compacts it into one, two or three bytes per character. (See the documentation on java.io.DataOutput) It is close to UTF-8, but even though documented as being so, there are compatibility problems. If you are not terribly worried about the amount of data you will be writing, you can easily write your own by writing the length of the string first, and then the raw data of the string using the getBytes method.</p>\n\n<pre><code>// Write data\nString str=\"foo\";\nbyte[] data=str.getBytes(\"UTF-8\");\nout.writeInt(data.length);\nout.write(data);\n\n// Read data\nint length=in.readInt();\nbyte[] data=new byte[length];\nin.readFully(data);\nString str=new String(data,\"UTF-8\");\n</code></pre>\n" }, { "answer_id": 9073621, "author": "ebruchez", "author_id": 5144, "author_profile": "https://Stackoverflow.com/users/5144", "pm_score": 3, "selected": false, "text": "<p><code>ObjectOutputStream.writeObject()</code> properly handles long strings (verified by looking at the source code). Write the string out this way:</p>\n\n<pre><code>ObjectOutputStream oos = new ObjectOutputStream(out);\n... other write operations ...\noos.writeObject(myString);\n... other write operations ...\n</code></pre>\n\n<p>Read it this way:</p>\n\n<pre><code>ObjectInputStream ois = new ObjectInputStream(in);\n... other read operations ...\nString myString = (String) ois.readObject();\n... other read operations ...\n</code></pre>\n\n<p>Another difference with <code>DataOutputStream</code> is that using <code>ObjectOutputStream</code> automatically writes a 4-byte stream header when instantiated, but its usually going to be a pretty small penalty to pay.</p>\n" } ]
2008/11/07
[ "https://Stackoverflow.com/questions/270884", "https://Stackoverflow.com", "https://Stackoverflow.com/users/269171/" ]
I've been doing some socket programming to transmit information across the wire. I've run into a problem with DataOutputStream.writeUTF(). It seems to allow strings of up to 64k but I have a few situations where I can run over this. Are there any good alternatives that support larger strings or do I need to roll my own?
It actually uses a two bytes to write the length of the string before using an algorithm that compacts it into one, two or three bytes per character. (See the documentation on java.io.DataOutput) It is close to UTF-8, but even though documented as being so, there are compatibility problems. If you are not terribly worried about the amount of data you will be writing, you can easily write your own by writing the length of the string first, and then the raw data of the string using the getBytes method. ``` // Write data String str="foo"; byte[] data=str.getBytes("UTF-8"); out.writeInt(data.length); out.write(data); // Read data int length=in.readInt(); byte[] data=new byte[length]; in.readFully(data); String str=new String(data,"UTF-8"); ```
270,895
<p>This fails:</p> <pre><code>my @a = ("a", "b", "c", "d", "e"); my %h = map { "prefix-$_" =&gt; 1 } @a; </code></pre> <p>with this error:</p> <pre><code>Not enough arguments for map at foo.pl line 4, near "} @a" </code></pre> <p>but this works:</p> <pre><code>my @a = ("a", "b", "c", "d", "e"); my %h = map { "prefix-" . $_ =&gt; 1 } @a; </code></pre> <p>why?</p>
[ { "answer_id": 270905, "author": "Leonardo Herrera", "author_id": 7841, "author_profile": "https://Stackoverflow.com/users/7841", "pm_score": 5, "selected": true, "text": "<p>Because Perl is guessing an EXPR (a hash reference, for example) instead of a BLOCK. This should work (note the '+' symbol):</p>\n\n<pre><code>my @a = (\"a\", \"b\", \"c\", \"d\", \"e\");\nmy %h = map { +\"prefix-$_\" =&gt; 1 } @a;\n</code></pre>\n\n<p>See <a href=\"http://perldoc.perl.org/functions/map.html\" rel=\"noreferrer\">http://perldoc.perl.org/functions/map.html</a>.</p>\n" }, { "answer_id": 270912, "author": "Robert Gamble", "author_id": 25222, "author_profile": "https://Stackoverflow.com/users/25222", "pm_score": 4, "selected": false, "text": "<p>From <code>perldoc -f map</code>:</p>\n\n<pre><code> \"{\" starts both hash references and blocks, so \"map { ...\"\n could be either the start of map BLOCK LIST or map EXPR, LIST.\n Because perl doesn’t look ahead for the closing \"}\" it has to\n take a guess at which its dealing with based what it finds just\n after the \"{\". Usually it gets it right, but if it doesn’t it\n won’t realize something is wrong until it gets to the \"}\" and\n encounters the missing (or unexpected) comma. The syntax error\n will be reported close to the \"}\" but you’ll need to change\n something near the \"{\" such as using a unary \"+\" to give perl\n some help:\n\n %hash = map { \"\\L$_\", 1 } @array # perl guesses EXPR. wrong\n %hash = map { +\"\\L$_\", 1 } @array # perl guesses BLOCK. right\n %hash = map { (\"\\L$_\", 1) } @array # this also works\n %hash = map { lc($_), 1 } @array # as does this.\n %hash = map +( lc($_), 1 ), @array # this is EXPR and works!\n %hash = map ( lc($_), 1 ), @array # evaluates to (1, @array)\n\n or to force an anon hash constructor use \"+{\"\n\n @hashes = map +{ lc($_), 1 }, @array # EXPR, so needs , at end\n\n and you get list of anonymous hashes each with only 1 entry.\n</code></pre>\n" }, { "answer_id": 271078, "author": "Andy Lester", "author_id": 8454, "author_profile": "https://Stackoverflow.com/users/8454", "pm_score": 4, "selected": false, "text": "<p>I prefer to write that as</p>\n\n<pre><code>my %h = map { (\"prefix-$_\" =&gt; 1) } @a;\n</code></pre>\n\n<p>to show the intent, that I am returning a 2-element list.</p>\n" }, { "answer_id": 271086, "author": "Andy Lester", "author_id": 8454, "author_profile": "https://Stackoverflow.com/users/8454", "pm_score": 3, "selected": false, "text": "<p>Also, the other way to do what you're doing, initializing the hash, you can do like this:</p>\n\n<pre><code>my @a = qw( a b c d e );\nmy %h;\n@h{@a} = ();\n</code></pre>\n\n<p>That will create undef entries for each of the five keys. If you want to give them all true values, then do this.</p>\n\n<pre><code>@h{@a} = (1) x @a;\n</code></pre>\n\n<p>You can also do it explicitly with a loop;</p>\n\n<pre><code>@h{$_} = 1 for @a;\n</code></pre>\n" }, { "answer_id": 271374, "author": "Axeman", "author_id": 11289, "author_profile": "https://Stackoverflow.com/users/11289", "pm_score": 1, "selected": false, "text": "<p>I think that </p>\n\n<pre><code>map { ; \"prefix-$_\" =&gt; 1 } @a;\n</code></pre>\n\n<p>is more idiomatic, as far as specifying that it is a block of statements and not a hash ref. You're just kicking it off with a null statement. </p>\n" } ]
2008/11/07
[ "https://Stackoverflow.com/questions/270895", "https://Stackoverflow.com", "https://Stackoverflow.com/users/14032/" ]
This fails: ``` my @a = ("a", "b", "c", "d", "e"); my %h = map { "prefix-$_" => 1 } @a; ``` with this error: ``` Not enough arguments for map at foo.pl line 4, near "} @a" ``` but this works: ``` my @a = ("a", "b", "c", "d", "e"); my %h = map { "prefix-" . $_ => 1 } @a; ``` why?
Because Perl is guessing an EXPR (a hash reference, for example) instead of a BLOCK. This should work (note the '+' symbol): ``` my @a = ("a", "b", "c", "d", "e"); my %h = map { +"prefix-$_" => 1 } @a; ``` See <http://perldoc.perl.org/functions/map.html>.
270,917
<p>I know it is a good practice to declare virtual destructors for base classes in C++, but is it always important to declare <code>virtual</code> destructors even for abstract classes that function as interfaces? Please provide some reasons and examples why.</p>
[ { "answer_id": 270925, "author": "Airsource Ltd", "author_id": 18017, "author_profile": "https://Stackoverflow.com/users/18017", "pm_score": 9, "selected": true, "text": "<p>It's even more important for an interface. Any user of your class will probably hold a pointer to the interface, not a pointer to the concrete implementation. When they come to delete it, if the destructor is non-virtual, they will call the interface's destructor (or the compiler-provided default, if you didn't specify one), not the derived class's destructor. Instant memory leak.</p>\n\n<p>For example</p>\n\n<pre><code>class Interface\n{\n virtual void doSomething() = 0;\n};\n\nclass Derived : public Interface\n{\n Derived();\n ~Derived() \n {\n // Do some important cleanup...\n }\n};\n\nvoid myFunc(void)\n{\n Interface* p = new Derived();\n // The behaviour of the next line is undefined. It probably \n // calls Interface::~Interface, not Derived::~Derived\n delete p; \n}\n</code></pre>\n" }, { "answer_id": 270926, "author": "OJ.", "author_id": 611, "author_profile": "https://Stackoverflow.com/users/611", "pm_score": 4, "selected": false, "text": "<p>Yes it is always important. Derived classes may allocate memory or hold reference to other resources that will need to be cleaned up when the object is destroyed. If you do not give your interfaces/abstract classes virtual destructors, then every time you delete a derived class instance via a base class handle your derived class' destructor will not be called.</p>\n\n<p>Hence, you're opening up the potential for memory leaks</p>\n\n<pre><code>class IFoo\n{\n public:\n virtual void DoFoo() = 0;\n};\n\nclass Bar : public IFoo\n{\n char* dooby = NULL;\n public:\n virtual void DoFoo() { dooby = new char[10]; }\n void ~Bar() { delete [] dooby; }\n};\n\nIFoo* baz = new Bar();\nbaz-&gt;DoFoo();\ndelete baz; // memory leak - dooby isn't deleted\n</code></pre>\n" }, { "answer_id": 270929, "author": "Evan Teran", "author_id": 13430, "author_profile": "https://Stackoverflow.com/users/13430", "pm_score": 3, "selected": false, "text": "<p>It is not <em>always</em> required, but I find it to be good practice. What it does, is it allows a derived object to be safely deleted through a pointer of a base type.</p>\n\n<p>So for example:</p>\n\n<pre><code>Base *p = new Derived;\n// use p as you see fit\ndelete p;\n</code></pre>\n\n<p>is ill-formed if <code>Base</code> doesn't have a virtual destructor, because it will attempt to delete the object as if it were a <code>Base *</code>.</p>\n" }, { "answer_id": 270931, "author": "JaredPar", "author_id": 23283, "author_profile": "https://Stackoverflow.com/users/23283", "pm_score": 3, "selected": false, "text": "<p>It's not only good practice. It is rule #1 for any class hierarchy. </p>\n\n<ol>\n<li>The base most class of a hierarchy in C++ must have a virtual destructor</li>\n</ol>\n\n<p>Now for the Why. Take the typical animal hierarchy. Virtual destructors go through virtual dispatch just as any other method call. Take the following example.</p>\n\n<pre><code>Animal* pAnimal = GetAnimal();\ndelete pAnimal;\n</code></pre>\n\n<p>Assume that Animal is an abstract class. The only way that C++ knows the proper destructor to call is via virtual method dispatch. If the destructor is not virtual then it will simply call Animal's destructor and not destroy any objects in derived classes.</p>\n\n<p>The reason for making the destructor virtual in the base class is that it simply removes the choice from derived classes. Their destructor becomes virtual by default. </p>\n" }, { "answer_id": 271075, "author": "Johannes Schaub - litb", "author_id": 34509, "author_profile": "https://Stackoverflow.com/users/34509", "pm_score": 5, "selected": false, "text": "<p>The answer to your question is often, but not always. If your abstract class forbids clients to call delete on a pointer to it (or if it says so in its documentation), you are free to not declare a virtual destructor. </p>\n\n<p>You can forbid clients to call delete on a pointer to it by making its destructor protected. Working like this, it is perfectly safe and reasonable to omit a virtual destructor.</p>\n\n<p>You will eventually end up with no virtual method table, and end up signalling your clients your intention on making it non-deleteable through a pointer to it, so you have indeed reason not to declare it virtual in those cases. </p>\n\n<p><em>[See item 4 in this article: <a href=\"http://www.gotw.ca/publications/mill18.htm\" rel=\"noreferrer\">http://www.gotw.ca/publications/mill18.htm</a>]</em></p>\n" }, { "answer_id": 6634408, "author": "davidag", "author_id": 11441, "author_profile": "https://Stackoverflow.com/users/11441", "pm_score": 5, "selected": false, "text": "<p>I decided to do some research and try to summarise your answers. The following questions will help you to decide what kind of destructor you need:</p>\n\n<ol>\n<li><strong>Is your class intended to be used as a base class?</strong>\n\n<ul>\n<li>No: Declare public non-virtual destructor to avoid v-pointer on each object of the class <sup>*</sup>.</li>\n<li>Yes: Read next question.</li>\n</ul></li>\n<li><strong>Is your base class abstract? (i.e. any virtual pure methods?)</strong>\n\n<ul>\n<li>No: Try to make your base class abstract by redesigning your class hierarchy </li>\n<li>Yes: Read next question.</li>\n</ul></li>\n<li><strong>Do you want to allow polymorphic deletion through a base pointer?</strong>\n\n<ul>\n<li>No: Declare protected virtual destructor to prevent the unwanted usage.</li>\n<li>Yes: Declare public virtual destructor (no overhead in this case).</li>\n</ul></li>\n</ol>\n\n<p>I hope this helps.</p>\n\n<p><sup>*</sup> It is important to note that there is no way in C++ to mark a class as final (i.e. non subclassable), so in the case that you decide to declare your destructor non-virtual and public, remember to explicitly warn your fellow programmers against deriving from your class.</p>\n\n<p>References:</p>\n\n<ul>\n<li>\"S. Meyers. More Effective C++, Item 33 Addison-Wesley, 1996.\"</li>\n<li><a href=\"http://www.gotw.ca/publications/mill18.htm\" rel=\"noreferrer\">Herb Sutter, Virtuality, 2001</a></li>\n<li><a href=\"http://www.parashift.com/c++-faq-lite/virtual-functions.html#faq-20.7\" rel=\"noreferrer\">C++ Faq, 20.7, \"When should my destructor be virtual?\"</a></li>\n<li>The answers to this question, of course.</li>\n</ul>\n" }, { "answer_id": 14056241, "author": "fatma.ekici", "author_id": 1678760, "author_profile": "https://Stackoverflow.com/users/1678760", "pm_score": 2, "selected": false, "text": "<p>The answer is simple, you need it to be virtual otherwise the base class would not be a complete polymorphic class.</p>\n\n<pre><code> Base *ptr = new Derived();\n delete ptr; // Here the call order of destructors: first Derived then Base.\n</code></pre>\n\n<p>You would prefer the above deletion, but if the base class's destructor is not virtual, only the base class's destructor will be called and all data in derived class will remain undeleted.</p>\n" } ]
2008/11/07
[ "https://Stackoverflow.com/questions/270917", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4599/" ]
I know it is a good practice to declare virtual destructors for base classes in C++, but is it always important to declare `virtual` destructors even for abstract classes that function as interfaces? Please provide some reasons and examples why.
It's even more important for an interface. Any user of your class will probably hold a pointer to the interface, not a pointer to the concrete implementation. When they come to delete it, if the destructor is non-virtual, they will call the interface's destructor (or the compiler-provided default, if you didn't specify one), not the derived class's destructor. Instant memory leak. For example ``` class Interface { virtual void doSomething() = 0; }; class Derived : public Interface { Derived(); ~Derived() { // Do some important cleanup... } }; void myFunc(void) { Interface* p = new Derived(); // The behaviour of the next line is undefined. It probably // calls Interface::~Interface, not Derived::~Derived delete p; } ```
270,918
<p>I would like to create a batch script, to go through 20,000 links in a DB, and weed out all the 404s and such. How would I get the HTTP status code for a remote url?</p> <p>Preferably not using curl, since I dont have it installed. </p>
[ { "answer_id": 270966, "author": "Adam Pierce", "author_id": 5324, "author_profile": "https://Stackoverflow.com/users/5324", "pm_score": 5, "selected": true, "text": "<p>CURL would be perfect but since you don't have it, you'll have to get down and dirty with sockets. The technique is:</p>\n\n<ol>\n<li>Open a socket to the server.</li>\n<li>Send an HTTP HEAD request.</li>\n<li>Parse the response.</li>\n</ol>\n\n<p>Here is a quick example:</p>\n\n<pre><code>&lt;?php\n\n$url = parse_url('http://www.example.com/index.html');\n\n$host = $url['host'];\n$port = $url['port'];\n$path = $url['path'];\n$query = $url['query'];\nif(!$port)\n $port = 80;\n\n$request = \"HEAD $path?$query HTTP/1.1\\r\\n\"\n .\"Host: $host\\r\\n\"\n .\"Connection: close\\r\\n\"\n .\"\\r\\n\";\n\n$address = gethostbyname($host);\n$socket = socket_create(AF_INET, SOCK_STREAM, SOL_TCP);\nsocket_connect($socket, $address, $port);\n\nsocket_write($socket, $request, strlen($request));\n\n$response = split(' ', socket_read($socket, 1024));\n\nprint \"&lt;p&gt;Response: \". $response[1] .\"&lt;/p&gt;\\r\\n\";\n\nsocket_close($socket);\n\n?&gt;\n</code></pre>\n\n<p><strong>UPDATE: I've added a few lines to parse the URL</strong></p>\n" }, { "answer_id": 270980, "author": "Sean Schulte", "author_id": 33380, "author_profile": "https://Stackoverflow.com/users/33380", "pm_score": 1, "selected": false, "text": "<p><a href=\"http://www.bin-co.com/php/scripts/load/\" rel=\"nofollow noreferrer\">This page</a> looks like it has a pretty good setup to download a page using either curl or fsockopen, and can get the HTTP headers using either method (which is what you want, really).</p>\n\n<p>After using that method, you'd want to check $output['info']['http_code'] to get the data you want.</p>\n\n<p>Hope that helps.</p>\n" }, { "answer_id": 270982, "author": "sanxiyn", "author_id": 18382, "author_profile": "https://Stackoverflow.com/users/18382", "pm_score": 1, "selected": false, "text": "<p>You can use PEAR's HTTP::head function.<br>\n<a href=\"http://pear.php.net/manual/en/package.http.http.head.php\" rel=\"nofollow noreferrer\">http://pear.php.net/manual/en/package.http.http.head.php</a></p>\n" }, { "answer_id": 270994, "author": "J.C. Inacio", "author_id": 35292, "author_profile": "https://Stackoverflow.com/users/35292", "pm_score": 2, "selected": false, "text": "<p>If im not mistaken none of the php built-in functions return the http status of a remote url, so the best option would be to use sockets to open a connection to the server, send a request and parse the response status:</p>\n\n<p>pseudo code:</p>\n\n<pre><code>parse url =&gt; $host, $port, $path\n$http_request = \"GET $path HTTP/1.0\\nHhost: $host\\n\\n\";\n$fp = fsockopen($host, $port, $errno, $errstr, $timeout), check for any errors\nfwrite($fp, $request)\nwhile (!feof($fp)) {\n $headers .= fgets($fp, 4096);\n $status = &lt;parse $headers &gt;\n if (&lt;status read&gt;)\n break;\n}\nfclose($fp)\n</code></pre>\n\n<p>Another option is to use an already build http client class in php that can return the headers without fetching the full page content, there should be a few open source classes available on the net...</p>\n" } ]
2008/11/07
[ "https://Stackoverflow.com/questions/270918", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
I would like to create a batch script, to go through 20,000 links in a DB, and weed out all the 404s and such. How would I get the HTTP status code for a remote url? Preferably not using curl, since I dont have it installed.
CURL would be perfect but since you don't have it, you'll have to get down and dirty with sockets. The technique is: 1. Open a socket to the server. 2. Send an HTTP HEAD request. 3. Parse the response. Here is a quick example: ``` <?php $url = parse_url('http://www.example.com/index.html'); $host = $url['host']; $port = $url['port']; $path = $url['path']; $query = $url['query']; if(!$port) $port = 80; $request = "HEAD $path?$query HTTP/1.1\r\n" ."Host: $host\r\n" ."Connection: close\r\n" ."\r\n"; $address = gethostbyname($host); $socket = socket_create(AF_INET, SOCK_STREAM, SOL_TCP); socket_connect($socket, $address, $port); socket_write($socket, $request, strlen($request)); $response = split(' ', socket_read($socket, 1024)); print "<p>Response: ". $response[1] ."</p>\r\n"; socket_close($socket); ?> ``` **UPDATE: I've added a few lines to parse the URL**
270,919
<p>I am looking for an example of how to do the following in VB.net with Parallel Extensions.</p> <pre><code>Dim T As Thread = New Thread(AddressOf functiontodowork) T1.Start(InputValueforWork) </code></pre> <p>Where I'm getting stuck is on how to pass into the task my parameter InputValueforWork</p> <pre><code>Dim T As Tasks.Task = Tasks.Task.Create(AddressOf functiontodowork) </code></pre> <p>Any suggests and possibly a coding example would be welcome.</p> <p>Andrew</p>
[ { "answer_id": 271266, "author": "Ana Betts", "author_id": 5728, "author_profile": "https://Stackoverflow.com/users/5728", "pm_score": 0, "selected": false, "text": "<p>Not necessarily the most helpful answer I know, but in C# you could do this with a closure:</p>\n\n<pre><code>var T = Tasks.Task.Create( () =&gt; functionToDoWork(SomeParameter) )\n</code></pre>\n" }, { "answer_id": 349731, "author": "Mauricio Scheffer", "author_id": 21239, "author_profile": "https://Stackoverflow.com/users/21239", "pm_score": 0, "selected": false, "text": "<p>The real problem here is that <a href=\"http://www.paulstovell.com/blog/vbnet-wheres-actiont-support\" rel=\"nofollow noreferrer\">VB 9 doesn't support <code>Action&lt;T&gt;</code></a>, only Funcs</p>\n\n<p>You can work around this limitation by having a helper in C#, like this:</p>\n\n<pre><code>public class VBHelpers {\n public static Action&lt;T&gt; FuncToAction&lt;T&gt;(Func&lt;T, object&gt; f) {\n return p =&gt; f(p);\n }\n}\n</code></pre>\n\n<p>Then you use it from VB like this:</p>\n\n<pre><code>Public Sub DoSomething()\n Dim T As Task = Task.Create(VBHelpers.FuncToAction(Function(p) FunctionToDoWork(p)))\nEnd Sub\n\nPublic Function FunctionToDoWork(ByVal e As Object) As Integer\n ' this does the real work\nEnd Function\n</code></pre>\n" }, { "answer_id": 353454, "author": "Middletone", "author_id": 35331, "author_profile": "https://Stackoverflow.com/users/35331", "pm_score": 2, "selected": true, "text": "<p>I solved my own question. you have to pass in an array with the values.</p>\n\n<pre><code>Dim A(0) as Int32\nA(0) = 1\nTasks.Task.Create(AddressOf TransferData, A)\n</code></pre>\n" } ]
2008/11/07
[ "https://Stackoverflow.com/questions/270919", "https://Stackoverflow.com", "https://Stackoverflow.com/users/35331/" ]
I am looking for an example of how to do the following in VB.net with Parallel Extensions. ``` Dim T As Thread = New Thread(AddressOf functiontodowork) T1.Start(InputValueforWork) ``` Where I'm getting stuck is on how to pass into the task my parameter InputValueforWork ``` Dim T As Tasks.Task = Tasks.Task.Create(AddressOf functiontodowork) ``` Any suggests and possibly a coding example would be welcome. Andrew
I solved my own question. you have to pass in an array with the values. ``` Dim A(0) as Int32 A(0) = 1 Tasks.Task.Create(AddressOf TransferData, A) ```
270,924
<p>I've been reading a text about an extension to C# and at one point it says that "An attribute decoration X may only be applied to fields of type Y."</p> <p>I haven't been able to find a definition for attribute decoration, and I'm not making much sense out of this by exchanging the two.</p>
[ { "answer_id": 271266, "author": "Ana Betts", "author_id": 5728, "author_profile": "https://Stackoverflow.com/users/5728", "pm_score": 0, "selected": false, "text": "<p>Not necessarily the most helpful answer I know, but in C# you could do this with a closure:</p>\n\n<pre><code>var T = Tasks.Task.Create( () =&gt; functionToDoWork(SomeParameter) )\n</code></pre>\n" }, { "answer_id": 349731, "author": "Mauricio Scheffer", "author_id": 21239, "author_profile": "https://Stackoverflow.com/users/21239", "pm_score": 0, "selected": false, "text": "<p>The real problem here is that <a href=\"http://www.paulstovell.com/blog/vbnet-wheres-actiont-support\" rel=\"nofollow noreferrer\">VB 9 doesn't support <code>Action&lt;T&gt;</code></a>, only Funcs</p>\n\n<p>You can work around this limitation by having a helper in C#, like this:</p>\n\n<pre><code>public class VBHelpers {\n public static Action&lt;T&gt; FuncToAction&lt;T&gt;(Func&lt;T, object&gt; f) {\n return p =&gt; f(p);\n }\n}\n</code></pre>\n\n<p>Then you use it from VB like this:</p>\n\n<pre><code>Public Sub DoSomething()\n Dim T As Task = Task.Create(VBHelpers.FuncToAction(Function(p) FunctionToDoWork(p)))\nEnd Sub\n\nPublic Function FunctionToDoWork(ByVal e As Object) As Integer\n ' this does the real work\nEnd Function\n</code></pre>\n" }, { "answer_id": 353454, "author": "Middletone", "author_id": 35331, "author_profile": "https://Stackoverflow.com/users/35331", "pm_score": 2, "selected": true, "text": "<p>I solved my own question. you have to pass in an array with the values.</p>\n\n<pre><code>Dim A(0) as Int32\nA(0) = 1\nTasks.Task.Create(AddressOf TransferData, A)\n</code></pre>\n" } ]
2008/11/07
[ "https://Stackoverflow.com/questions/270924", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
I've been reading a text about an extension to C# and at one point it says that "An attribute decoration X may only be applied to fields of type Y." I haven't been able to find a definition for attribute decoration, and I'm not making much sense out of this by exchanging the two.
I solved my own question. you have to pass in an array with the values. ``` Dim A(0) as Int32 A(0) = 1 Tasks.Task.Create(AddressOf TransferData, A) ```
270,927
<p>The situation is this. I have an asp.net webservice application...say a page called api.asmx</p> <p>In the code behind I have several methods, for example:</p> <pre><code>[WebMethod(Description="Method1")] public int GetSomething(int num1, int num2){ try{ return SomeObject.DatabaseCall.DoSomething(num1, num2); } catch(Exception ex){ object[] pars = new object[] { num1, num2 }; LogError("GetSomething", pars, ex); } } [WebMethod(Description="Method2")] public int GetSomething2(string w, string j, int f){ try{ return AnotherObject.DoSomething(w, j, f); } catch(Exception ex){ object[] pars = new object[] { w, j, f }; LogError("GetSomething2", pars, ex); } } </code></pre> <p>Of course these are just two simple examples where, if an exception is thrown, I can log the method call and parameters passed in.</p> <p>Is there another way to do this? Is there some way that I can extract the method being called and/or the parameters. I guess I'm hoping someone will tell me that I can just have some kind of function like:</p> <pre><code>LogError(ex); </code></pre> <p>And within that function I can access some Server or Environment variables that will expose the method being called. Maybe something like CurrentContext.WebServiceCall.Magic property... Do I need to wrap all my calls in a try/catch and then type out the method name and parameters, or is there another way to access this information.</p> <p>Hopefully this question ins't too stupid.</p>
[ { "answer_id": 270970, "author": "Keltex", "author_id": 28260, "author_profile": "https://Stackoverflow.com/users/28260", "pm_score": 0, "selected": false, "text": "<p>Your LogError method could call <a href=\"http://msdn.microsoft.com/en-us/library/system.environment.stacktrace.aspx\" rel=\"nofollow noreferrer\">Environment.StackTrace</a>. Then it would \"know\" what method called it. </p>\n" }, { "answer_id": 270972, "author": "mark w", "author_id": 345402, "author_profile": "https://Stackoverflow.com/users/345402", "pm_score": 1, "selected": false, "text": "<p>The exception object has a StackTrace property. Your entry method should be in the stack.</p>\n" }, { "answer_id": 270975, "author": "Todd", "author_id": 2572, "author_profile": "https://Stackoverflow.com/users/2572", "pm_score": 2, "selected": false, "text": "<p>Any unhandled exceptions will be bubbled up to your Application_Error event in the Global.asax file. From there, you can call Server.GetLastError() to retrieve the Exception instance. </p>\n\n<p>Once you have the exception, you can look at the stack trace. You will also have access to the Request object so you can see exactly what came from the client.</p>\n" } ]
2008/11/07
[ "https://Stackoverflow.com/questions/270927", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
The situation is this. I have an asp.net webservice application...say a page called api.asmx In the code behind I have several methods, for example: ``` [WebMethod(Description="Method1")] public int GetSomething(int num1, int num2){ try{ return SomeObject.DatabaseCall.DoSomething(num1, num2); } catch(Exception ex){ object[] pars = new object[] { num1, num2 }; LogError("GetSomething", pars, ex); } } [WebMethod(Description="Method2")] public int GetSomething2(string w, string j, int f){ try{ return AnotherObject.DoSomething(w, j, f); } catch(Exception ex){ object[] pars = new object[] { w, j, f }; LogError("GetSomething2", pars, ex); } } ``` Of course these are just two simple examples where, if an exception is thrown, I can log the method call and parameters passed in. Is there another way to do this? Is there some way that I can extract the method being called and/or the parameters. I guess I'm hoping someone will tell me that I can just have some kind of function like: ``` LogError(ex); ``` And within that function I can access some Server or Environment variables that will expose the method being called. Maybe something like CurrentContext.WebServiceCall.Magic property... Do I need to wrap all my calls in a try/catch and then type out the method name and parameters, or is there another way to access this information. Hopefully this question ins't too stupid.
Any unhandled exceptions will be bubbled up to your Application\_Error event in the Global.asax file. From there, you can call Server.GetLastError() to retrieve the Exception instance. Once you have the exception, you can look at the stack trace. You will also have access to the Request object so you can see exactly what came from the client.
270,933
<p>I have a shell script which copies a few files to the current directory, compresses them, and streams the compressed file to stdout.</p> <p>On the client side I use plink to execute the script and stream stdin to a file.</p> <p>This almost works.</p> <p>It seems that the cp command outputs the file name being copied when its executed from inside the script. If I execute '<strong>cp /path/to/file1 .</strong>' in the shell it does it quietly; if I execute it in a script it outputs "file1".</p> <p>How do I prevent this? I've tried piping the output of the cp command to /dev/null and to a dummy text file but with no luck.</p> <p>thanks for any help.</p> <h3>the script</h3> <pre><code>#!/bin/bash cp /path/to/file1 . cp /path/to/file2 . cp /path/to/file3 . tar -cvzf package.tgz file1 file2 file3 cat package.tgz </code></pre> <h3>the output</h3> <pre><code>file1 file2 file3 &lt;&lt;binary data&gt;&gt; </code></pre>
[ { "answer_id": 270935, "author": "CesarB", "author_id": 28258, "author_profile": "https://Stackoverflow.com/users/28258", "pm_score": 5, "selected": true, "text": "<p>It's not cp, it's tar. You are passing it -v, which makes it print the names of the files.</p>\n" }, { "answer_id": 271345, "author": "bendin", "author_id": 33412, "author_profile": "https://Stackoverflow.com/users/33412", "pm_score": 2, "selected": false, "text": "<p>Aha! I'd always assumed that the file names emitted by tar go to <code>stderr</code>, but that isn't always the case: only if you write your tar file to <code>stdout</code> do the files written by <code>-v</code> go to <code>stderr</code>:</p>\n\n<pre><code>$ tar cvf - share &gt; /dev/null\nshare/ # this must be going\nshare/.DS_Store # to stderr since we\nshare/man/ # redirected stdout to\nshare/man/.DS_Store # /dev/null above.\nshare/man/man1/\nshare/man/man1/diffmerge.man1\n</code></pre>\n\n<p>The counter-example:</p>\n\n<pre><code>$ tar cvf blah.tar share &gt; /dev/null\n</code></pre>\n\n<p>This produced no list of file names because they got sent to <code>/dev/null</code>. \nI guess you learn something new every day. :-)</p>\n" }, { "answer_id": 8102364, "author": "bigendian", "author_id": 1013642, "author_profile": "https://Stackoverflow.com/users/1013642", "pm_score": 0, "selected": false, "text": "<p>As others pointed out, the -v (verbose) option to tar is kicking out the file names to STDERR. You can also make your script more efficient by having tar write the compressed file stream to STDOUT:</p>\n\n<pre><code>tar zcf - file1 file2 file3\n</code></pre>\n\n<p>In this example, the \"-\" option passed as the filename makes tar write the output to STDOUT.</p>\n" } ]
2008/11/07
[ "https://Stackoverflow.com/questions/270933", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1851/" ]
I have a shell script which copies a few files to the current directory, compresses them, and streams the compressed file to stdout. On the client side I use plink to execute the script and stream stdin to a file. This almost works. It seems that the cp command outputs the file name being copied when its executed from inside the script. If I execute '**cp /path/to/file1 .**' in the shell it does it quietly; if I execute it in a script it outputs "file1". How do I prevent this? I've tried piping the output of the cp command to /dev/null and to a dummy text file but with no luck. thanks for any help. ### the script ``` #!/bin/bash cp /path/to/file1 . cp /path/to/file2 . cp /path/to/file3 . tar -cvzf package.tgz file1 file2 file3 cat package.tgz ``` ### the output ``` file1 file2 file3 <<binary data>> ```
It's not cp, it's tar. You are passing it -v, which makes it print the names of the files.
270,947
<p>I write a singleton c++ in the follow way:</p> <pre><code>class A { private: static A* m_pA; A(); virtual ~A(); public: static A* GetInstance(); static void FreeInstance(); void WORK1(); void WORK2(); void WORK3(); } } A* A::GetInstance() { if (m_pA == NULL) m_pA = new A(); return m_pA; } A::~A() { FreeInstance() // Can I write this? are there any potential error? } void A::FreeInstance() { delete m_pA; m_pA = NULL; } </code></pre> <p>Thanks! Evan Teran and sep61.myopenid.com 's answer is right, and really good! My way is wrong, I wish any one writting such code can avoid my silly mistake.</p> <p>My singleton A in my project has a vector of smart pointer, and another thread can also edit this vector, so when the application is closing, it always become unstable even I add lots of CMutex. Multithread error + singleton error wasted me 1 day.<p> //----------------------------------------------------------- A new singleton, you are welcome to edit if you think there is any problem in the following sample:</p> <pre><code>class A { private: static A* m_pA; explicit A(); void A(const A&amp; a); void A(A &amp;a); const A&amp; operator=(const A&amp; a); virtual ~A(); public: static A* GetInstance(); static void FreeInstance(); void WORK1(); void WORK2(); void WORK3(); } } A* A::GetInstance() { if (m_pA == NULL){ static A self; m_pA = &amp;self; } return m_pA; } A::~A() { } </code></pre>
[ { "answer_id": 270957, "author": "Evan Teran", "author_id": 13430, "author_profile": "https://Stackoverflow.com/users/13430", "pm_score": 5, "selected": true, "text": "<p>You can avoid needing to delete it by using a static object like this:</p>\n\n<pre><code>if(m_pA == 0) {\n static A static_instance;\n m_pA = &amp;static_instance;\n}\n</code></pre>\n" }, { "answer_id": 270968, "author": "Odd", "author_id": 11908, "author_profile": "https://Stackoverflow.com/users/11908", "pm_score": 1, "selected": false, "text": "<p>I do not think there is any reason to write that line no. Your destructor method is not static and your singleton instance will not be destructed in that fashion. I do not think the destructor is necessary, if you need to cleanup the object use the static method you've alread created, FreeInstance().</p>\n\n<p>Other than that, you create your singletons in roughly the same way that I create mine.</p>\n" }, { "answer_id": 270973, "author": "sep", "author_id": 30333, "author_profile": "https://Stackoverflow.com/users/30333", "pm_score": 2, "selected": false, "text": "<p>A singleton in C++ can be written in this way:</p>\n\n<pre><code>static A* A::GetInstance() {\n static A sin;\n return &amp;sin;\n}\n</code></pre>\n" }, { "answer_id": 270979, "author": "Jasper Bekkers", "author_id": 31486, "author_profile": "https://Stackoverflow.com/users/31486", "pm_score": 2, "selected": false, "text": "<p>Just don't forget to make the copy constructor and assignment operators private.</p>\n" }, { "answer_id": 271104, "author": "Martin York", "author_id": 14065, "author_profile": "https://Stackoverflow.com/users/14065", "pm_score": 8, "selected": false, "text": "<p>Why does everybody want to return a singleton as a pointer?<br>\nReturn it as a reference seems much more logical!</p>\n\n<p>You should never be able to free a singleton manually. How do you know who is keeping a reference to the singleton? If you don't know (or can't guarantee) nobody has a reference (in your case via a pointer) then you have no business freeing the object.</p>\n\n<p>Use the static in a function method.<br>\nThis guarantees that it is created and destroyed only once. It also gives you lazy initialization for free. </p>\n\n<pre><code>class S\n{\n public:\n static S&amp; getInstance()\n {\n static S instance;\n return instance;\n }\n private:\n S() {}\n S(S const&amp;); // Don't Implement.\n void operator=(S const&amp;); // Don't implement\n };\n</code></pre>\n\n<p>Note you also need to make the constructor private.\nAlso make sure that you override the default copy constructor and assignment operator so that you can not make a copy of the singleton (otherwise it would not be a singleton).</p>\n\n<p>Also read:</p>\n\n<ul>\n<li><a href=\"https://stackoverflow.com/a/1008289/14065\">https://stackoverflow.com/a/1008289/14065</a></li>\n<li><a href=\"https://stackoverflow.com/questions/86582/singleton-how-should-it-be-used\">Singleton: How should it be used</a> </li>\n<li><a href=\"https://stackoverflow.com/questions/1008019/c-singleton-design-pattern/1008289#1008289\">C++ Singleton design pattern</a></li>\n</ul>\n\n<p>To make sure you are using a singleton for the correct reasons.</p>\n\n<p>Though technically not thread safe in the general case see:<br>\n<a href=\"https://stackoverflow.com/questions/246564/what-is-the-lifetime-of-a-static-variable-in-a-c-function\">What is the lifetime of a static variable in a C++ function?</a></p>\n\n<p>GCC has an explicit patch to compensate for this:<br>\n<a href=\"http://gcc.gnu.org/ml/gcc-patches/2004-09/msg00265.html\" rel=\"noreferrer\">http://gcc.gnu.org/ml/gcc-patches/2004-09/msg00265.html</a></p>\n" }, { "answer_id": 271784, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 0, "selected": false, "text": "<p>There is a great C++ library, ACE, based on patterns. There's a lot of documentation about different kind of patterns so look at their work:\n<a href=\"http://www.cs.wustl.edu/~schmidt/ACE.html\" rel=\"nofollow noreferrer\">http://www.cs.wustl.edu/~schmidt/ACE.html</a></p>\n" }, { "answer_id": 271835, "author": "Will Dean", "author_id": 987, "author_profile": "https://Stackoverflow.com/users/987", "pm_score": 1, "selected": false, "text": "<p>After a period of wild enthusiasm for Meyers-style singletons (using local static objects as in some of the previous answers), I got completely sick of the lifetime management problems in complicated apps.</p>\n\n<p>I tend to find that you end up referencing the 'Instance' method deliberately early in the app's initialisation, to make sure they're created when you want, and then playing all kinds of games with the tear-down because of the unpredictable (or at least very complicated and somewhat hidden) order in which things get destroyed.</p>\n\n<p>YMMV of course, and it depends a bit on the nature of the singleton itself, but a lot of the waffle about clever singletons (and the threading/locking issues which surround the cleverness) is overrated IMO.</p>\n" }, { "answer_id": 271857, "author": "jab", "author_id": 20367, "author_profile": "https://Stackoverflow.com/users/20367", "pm_score": 1, "selected": false, "text": "<p>if you read \"Modern C++ Design\" you'll realize that a singleton design could be much complex than return a static variable. </p>\n" }, { "answer_id": 271880, "author": "n-alexander", "author_id": 23420, "author_profile": "https://Stackoverflow.com/users/23420", "pm_score": 0, "selected": false, "text": "<p>This implementation is fine as long as you can answer these questions:</p>\n\n<ol>\n<li><p>do you know when the object will be created (if you use a static object instead of new? Do you have a main()?)</p></li>\n<li><p>does you singleton have any dependencies that may not be ready by the time it is created? If you use a static object instead of new, what libraries have been initialized by this time? What your object does in constructor that might require them?</p></li>\n<li><p>when will it be deleted?</p></li>\n</ol>\n\n<p>Using new() is safer because you control where and when the object will be created and deleted. But then you need to delete it explicitly and probably nobody in the system knows when to do so. You may use atexit() for that, if it makes sense.</p>\n\n<p>Using a static object in method means that do do not really know when it will be created or deleted. You could as well use a global static object in a namespace and avoid getInstance() at all - it doesn't add much.</p>\n\n<p>If you do use threads, then you're in big trouble. It is virtually impossible to create usable thread safe singleton in C++ due to:</p>\n\n<ol>\n<li>permanent lock in getInstance is very heavy - a full context switch at every getInstance()</li>\n<li>double checked lock fails due to compiler optimizations and cache/weak memory model, is very tricky to implement, and impossible to test. I wouldn't attempt to do it in a real system, unless you intimately know your architecture and want it to be not portable</li>\n</ol>\n\n<p>These can be Googled easily, but here's a good link on weak memory model: <a href=\"http://ridiculousfish.com/blog/archives/2007/02/17/barrier\" rel=\"nofollow noreferrer\">http://ridiculousfish.com/blog/archives/2007/02/17/barrier</a>.</p>\n\n<p>One solution would be to use locking but require that users cache the pointer they get from getInctance() and be prepared for getInstance() to be heavy.</p>\n\n<p>Another solution would be to let users handle thread safety themselves.</p>\n\n<p>Yet another solution would be to use a function with simple locking and substitute it with another function without locking and checking once the new() has been called. This works, but full implementation is complicated.</p>\n" }, { "answer_id": 54118306, "author": "amightywind", "author_id": 7303716, "author_profile": "https://Stackoverflow.com/users/7303716", "pm_score": 0, "selected": false, "text": "<pre><code>//! @file singleton.h\n//!\n//! @brief Variadic template to make a singleton out of an ordinary type.\n//!\n//! This template makes a singleton out of a type without a default\n//! constructor.\n\n#ifndef SINGLETON_H\n#define SINGLETON_H\n\n#include &lt;stdexcept&gt;\n\ntemplate &lt;typename C, typename ...Args&gt;\nclass singleton\n{\nprivate:\n singleton() = default;\n static C* m_instance;\n\npublic:\n singleton(const singleton&amp;) = delete;\n singleton&amp; operator=(const singleton&amp;) = delete;\n singleton(singleton&amp;&amp;) = delete;\n singleton&amp; operator=(singleton&amp;&amp;) = delete;\n\n ~singleton()\n {\n delete m_instance;\n m_instance = nullptr;\n }\n\n static C&amp; create(Args...args)\n {\n if (m_instance != nullptr)\n {\n delete m_instance;\n m_instance = nullptr;\n }\n m_instance = new C(args...);\n return *m_instance;\n }\n\n static C&amp; instance()\n {\n if (m_instance == nullptr)\n throw std::logic_error(\n \"singleton&lt;&gt;::create(...) must precede singleton&lt;&gt;::instance()\");\n return *m_instance;\n }\n};\n\ntemplate &lt;typename C, typename ...Args&gt;\nC* singleton&lt;C, Args...&gt;::m_instance = nullptr;\n\n#endif // SINGLETON_H\n</code></pre>\n" } ]
2008/11/07
[ "https://Stackoverflow.com/questions/270947", "https://Stackoverflow.com", "https://Stackoverflow.com/users/25749/" ]
I write a singleton c++ in the follow way: ``` class A { private: static A* m_pA; A(); virtual ~A(); public: static A* GetInstance(); static void FreeInstance(); void WORK1(); void WORK2(); void WORK3(); } } A* A::GetInstance() { if (m_pA == NULL) m_pA = new A(); return m_pA; } A::~A() { FreeInstance() // Can I write this? are there any potential error? } void A::FreeInstance() { delete m_pA; m_pA = NULL; } ``` Thanks! Evan Teran and sep61.myopenid.com 's answer is right, and really good! My way is wrong, I wish any one writting such code can avoid my silly mistake. My singleton A in my project has a vector of smart pointer, and another thread can also edit this vector, so when the application is closing, it always become unstable even I add lots of CMutex. Multithread error + singleton error wasted me 1 day. //----------------------------------------------------------- A new singleton, you are welcome to edit if you think there is any problem in the following sample: ``` class A { private: static A* m_pA; explicit A(); void A(const A& a); void A(A &a); const A& operator=(const A& a); virtual ~A(); public: static A* GetInstance(); static void FreeInstance(); void WORK1(); void WORK2(); void WORK3(); } } A* A::GetInstance() { if (m_pA == NULL){ static A self; m_pA = &self; } return m_pA; } A::~A() { } ```
You can avoid needing to delete it by using a static object like this: ``` if(m_pA == 0) { static A static_instance; m_pA = &static_instance; } ```
270,948
<p>Are there any tricks for preventing SQL Server from entitizing chars like &amp;, &lt;, and >? I'm trying to output a URL in my XML file but SQL wants to replace any '&amp;' with '<code>&amp;amp;</code>'</p> <p>Take the following query:</p> <pre><code>SELECT 'http://foosite.com/' + RTRIM(li.imageStore) + '/ImageStore.dll?id=' + RTRIM(li.imageID) + '&amp;raw=1&amp;rev=' + RTRIM(li.imageVersion) AS imageUrl FROM ListingImages li FOR XML PATH ('image'), ROOT ('images'), TYPE </code></pre> <p>The output I get is like this (&amp;s are entitized):</p> <pre><code>&lt;images&gt; &lt;image&gt; &lt;imageUrl&gt;http://foosite.com/pics4/ImageStore.dll?id=7E92BA08829F6847&amp;amp;raw=1&amp;amp;rev=0&lt;/imageUrl&gt; &lt;/image&gt; &lt;/images&gt; </code></pre> <p>What I'd like is this (&amp;s are not entitized):</p> <pre><code>&lt;images&gt; &lt;image&gt; &lt;imageUrl&gt;http://foosite.com/pics4/ImageStore.dll?id=7E92BA08829F6847&amp;raw=1&amp;rev=0&lt;/imageUrl&gt; &lt;/image&gt; &lt;/images&gt; </code></pre> <p>How does one prevent SQL server from entitizing the '&amp;'s into '<code>&amp;amp;</code>'?</p>
[ { "answer_id": 271000, "author": "ykaganovich", "author_id": 10026, "author_profile": "https://Stackoverflow.com/users/10026", "pm_score": 5, "selected": true, "text": "<p>What SQL Server generates is correct. What you expect to see is not well-formed XML. The reason is that <code>&amp;</code> character signifies the start of an entity reference, such as <code>&amp;amp;</code>. See the <a href=\"http://www.w3.org/TR/REC-xml/#sec-references\" rel=\"nofollow noreferrer\">XML specification</a> for more information.</p>\n\n<p>When your XML parser parses this string out of XML, it will understand the <code>&amp;amp;</code> entity references and return the text back in the form you want. So the internal format in the XML file should not cause a problem to you unless you're using a buggy XML parser, or trying to parse it manually (in which case your current parser code is effectively buggy at the moment with respect to the XML specification).</p>\n" }, { "answer_id": 8686690, "author": "Janmonn", "author_id": 1124038, "author_profile": "https://Stackoverflow.com/users/1124038", "pm_score": 6, "selected": false, "text": "<p>There are situations where a person may not want well formed XML - the one I (and perhaps the original poster) encountered was using the For XML Path technique to return a single field list of 'child' items via a recursive query. More information on this technique is here (specifically in the 'The blackbox XML methods' section):\n<a href=\"https://www.simple-talk.com/sql/t-sql-programming/concatenating-row-values-in-transact-sql/\" rel=\"noreferrer\">Concatenating Row Values in Transact-SQL</a></p>\n\n<p>For my situation, seeing 'H&amp;E' (a pathology stain) transformed into 'well formed XML' was a real disappointment. Fortunately, I found a solution... the following page helped me solve this issue relatively easily and without having re-architect my recursive query or add additional parsing at the presentation level (for this as well for as other/future situations where my child-rows data fields contain reserved XML characters): <a href=\"http://blogs.lobsterpot.com.au/2010/04/15/handling-special-characters-with-for-xml-path/\" rel=\"noreferrer\">Handling Special Characters with FOR XML PATH</a></p>\n\n<hr>\n\n<p>EDIT: code below from the referenced blog post.</p>\n\n<pre><code>select\n stuff(\n (select ', &lt;' + name + '&gt;'\n from sys.databases\n where database_id &gt; 4\n order by name\n for xml path(''), root('MyString'), type\n ).value('/MyString[1]','varchar(max)')\n , 1, 2, '') as namelist;\n</code></pre>\n" }, { "answer_id": 22935091, "author": "Siva Sankar Gorantla", "author_id": 2763735, "author_profile": "https://Stackoverflow.com/users/2763735", "pm_score": 3, "selected": false, "text": "<p>Try this....</p>\n\n<pre><code>select \n stuff( \n (select ', &lt;' + name + '&gt;' \n from sys.databases \n where database_id &gt; 4 \n order by name \n for xml path(''), root('MyString'), type \n ).value('/MyString[1]','varchar(max)') \n , 1, 2, '') as namelist;\n</code></pre>\n" } ]
2008/11/07
[ "https://Stackoverflow.com/questions/270948", "https://Stackoverflow.com", "https://Stackoverflow.com/users/19389/" ]
Are there any tricks for preventing SQL Server from entitizing chars like &, <, and >? I'm trying to output a URL in my XML file but SQL wants to replace any '&' with '`&amp;`' Take the following query: ``` SELECT 'http://foosite.com/' + RTRIM(li.imageStore) + '/ImageStore.dll?id=' + RTRIM(li.imageID) + '&raw=1&rev=' + RTRIM(li.imageVersion) AS imageUrl FROM ListingImages li FOR XML PATH ('image'), ROOT ('images'), TYPE ``` The output I get is like this (&s are entitized): ``` <images> <image> <imageUrl>http://foosite.com/pics4/ImageStore.dll?id=7E92BA08829F6847&amp;raw=1&amp;rev=0</imageUrl> </image> </images> ``` What I'd like is this (&s are not entitized): ``` <images> <image> <imageUrl>http://foosite.com/pics4/ImageStore.dll?id=7E92BA08829F6847&raw=1&rev=0</imageUrl> </image> </images> ``` How does one prevent SQL server from entitizing the '&'s into '`&amp;`'?
What SQL Server generates is correct. What you expect to see is not well-formed XML. The reason is that `&` character signifies the start of an entity reference, such as `&amp;`. See the [XML specification](http://www.w3.org/TR/REC-xml/#sec-references) for more information. When your XML parser parses this string out of XML, it will understand the `&amp;` entity references and return the text back in the form you want. So the internal format in the XML file should not cause a problem to you unless you're using a buggy XML parser, or trying to parse it manually (in which case your current parser code is effectively buggy at the moment with respect to the XML specification).
271,015
<p>I need to write a Stored procedure in SQL server whose data returned will be used to generate a XML file.</p> <p>My XML file to be in structure of </p> <pre><code>&lt;root&gt; &lt;ANode&gt;&lt;/ANode&gt; &lt;BNode&gt;&lt;/BNode&gt; &lt;CNode&gt; &lt;C1Node&gt; &lt;C11Node&gt;&lt;/C11Node&gt; &lt;C12Node&gt;&lt;/C12Node&gt; &lt;/C1Node&gt; &lt;C2Node&gt; &lt;C21Node&gt;&lt;/C21Node&gt; &lt;C22Node&gt;&lt;/C22Node&gt; &lt;/C2Node&gt; &lt;C3Node&gt; &lt;C31Node&gt;&lt;/C31Node&gt; &lt;C32Node&gt;&lt;/C32Node&gt; &lt;/C3Node&gt; &lt;/CNode&gt; &lt;/root&gt; </code></pre> <p>My question is, in the stored procedure we can select values for ANode and BNode as a simple SELECT statement like</p> <pre><code>Select ANodeVal,BNodeVal from Table </code></pre> <p>But how to design the stored procedure to get records for the CNode which is a subtree which has 3 or more(dynamic) separate nodes in it for each record in addition to the normal ANode and BNode.</p>
[ { "answer_id": 271191, "author": "Kozyarchuk", "author_id": 52490, "author_profile": "https://Stackoverflow.com/users/52490", "pm_score": 2, "selected": false, "text": "<p>I wouldn't recommend doing this in a stored proc. If created in language such as C#/Python or Java will make the code unit testable and more maintainable.</p>\n" }, { "answer_id": 271202, "author": "Doug L.", "author_id": 19179, "author_profile": "https://Stackoverflow.com/users/19179", "pm_score": 0, "selected": false, "text": "<p>If you are able to modify the database design, consider keeping each node as a record, instead of as a column (as the sample select statement would indicate).</p>\n\n<p>For example, each row might include the following fields:</p>\n\n<ul>\n<li>RowId</li>\n<li>ParentRowId</li>\n<li>Name</li>\n<li>RowData</li>\n</ul>\n\n<p>I'm assuming that you are passing the data to an application befcause you indicated that the returned data will be used to generate the XML. In which case the Stored Procedure would simply be a <code>SELECT</code> statement, leaving the formatting to the application.</p>\n\n<p>Most implementations of XML engines should allow you to add child nodes to existing parent nodes. The XML is built in memory and then \"exported\" by whatever method necessary to get the desired final result.</p>\n" }, { "answer_id": 273975, "author": "6eorge Jetson", "author_id": 23422, "author_profile": "https://Stackoverflow.com/users/23422", "pm_score": 3, "selected": true, "text": "<p>See</p>\n\n<p>&nbsp; &nbsp; <a href=\"https://stackoverflow.com/questions/147897/in-sql-server-can-i-insert-multiple-nodes-into-xml-from-a-table#148877\">Nesting XML-returning scalar valued functions</a> </p>\n\n<p>Once you get the hang of the nesting, and are willing to write the number of scalar-valued functions necessary to construct the node segments from the bottom up (I wouldn't want lots of these laying around), then it's not so hard. </p>\n" } ]
2008/11/07
[ "https://Stackoverflow.com/questions/271015", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3113/" ]
I need to write a Stored procedure in SQL server whose data returned will be used to generate a XML file. My XML file to be in structure of ``` <root> <ANode></ANode> <BNode></BNode> <CNode> <C1Node> <C11Node></C11Node> <C12Node></C12Node> </C1Node> <C2Node> <C21Node></C21Node> <C22Node></C22Node> </C2Node> <C3Node> <C31Node></C31Node> <C32Node></C32Node> </C3Node> </CNode> </root> ``` My question is, in the stored procedure we can select values for ANode and BNode as a simple SELECT statement like ``` Select ANodeVal,BNodeVal from Table ``` But how to design the stored procedure to get records for the CNode which is a subtree which has 3 or more(dynamic) separate nodes in it for each record in addition to the normal ANode and BNode.
See     [Nesting XML-returning scalar valued functions](https://stackoverflow.com/questions/147897/in-sql-server-can-i-insert-multiple-nodes-into-xml-from-a-table#148877) Once you get the hang of the nesting, and are willing to write the number of scalar-valued functions necessary to construct the node segments from the bottom up (I wouldn't want lots of these laying around), then it's not so hard.
271,021
<p>I've recently seen occasional problems with stored procedures on a legacy system which displays error messages like this:</p> <blockquote> <p>Server Message: Number 10901, Severity 17: This query requires <em>X</em> auxiliary scan descriptors but currently there are only <em>Y</em> auxiliary scan descriptors available. Either raise the value of the 'number of aux scan descriptors' configuration parameter or try your query later.</p> </blockquote> <p>where <em>X</em> is slightly lower than <em>Y</em>. The Sybase manual usefully tells me that I should redesign my table to use less auxiliary scan descriptors (how?!), or increase the number available on the system. The weird thing is, it's been working fine for years and the only thing that's changed is that we amended the data types of a couple of columns and added an index. Can anyone shed any light on this?</p>
[ { "answer_id": 271660, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 3, "selected": true, "text": "<p>You don't say what version of Sybase you are on but the following is good for ASE 12.5 onwards.</p>\n\n<p>I suspect that it's the addition of the new index that's thrown out the query plan for that stored procedure. Have you tried running </p>\n\n<pre><code>update statistics *table_name*\n</code></pre>\n\n<p>on it? If that fails you can find out how many scan descriptors you have by running </p>\n\n<pre><code>sp_monitorconfig \"aux scan descriptors\"\n</code></pre>\n\n<p>and then increase that by running</p>\n\n<pre><code>sp_configure \"aux scan descriptors\", x\n</code></pre>\n\n<p>where x is the number of scan descriptors you require.</p>\n\n<p>If you wish to reduce the number of scan descriptors that the store procedure is using then according to <a href=\"http://infocenter.sybase.com/help/index.jsp?topic=/com.sybase.help.ase_15.0.sag1/html/sag1/sag1249.htm\" rel=\"nofollow noreferrer\">here</a> you have to </p>\n\n<p><em>Rewrite the query, or break it into steps using temporary tables. For data-only-locked tables, consider adding indexes if there are many table scans.</em></p>\n\n<p>but without seeing a query plan it's impossible to give more specific advice.</p>\n" }, { "answer_id": 279579, "author": "ninesided", "author_id": 1030, "author_profile": "https://Stackoverflow.com/users/1030", "pm_score": 1, "selected": false, "text": "<p>This is defect in Sybase 12.5.2 for which a CR was submitted, see issue 361967 in <a href=\"http://web.archive.org/web/20131003092614/http://www.sybase.com/detail?id=1038862\" rel=\"nofollow noreferrer\">this list</a>. It was patched for 12.5.3 and above.</p>\n" } ]
2008/11/07
[ "https://Stackoverflow.com/questions/271021", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1030/" ]
I've recently seen occasional problems with stored procedures on a legacy system which displays error messages like this: > > Server Message: Number 10901, Severity 17: > This query requires *X* auxiliary scan > descriptors but currently there are > only *Y* auxiliary scan descriptors > available. Either raise the value of > the 'number of aux scan descriptors' > configuration parameter or try your > query later. > > > where *X* is slightly lower than *Y*. The Sybase manual usefully tells me that I should redesign my table to use less auxiliary scan descriptors (how?!), or increase the number available on the system. The weird thing is, it's been working fine for years and the only thing that's changed is that we amended the data types of a couple of columns and added an index. Can anyone shed any light on this?
You don't say what version of Sybase you are on but the following is good for ASE 12.5 onwards. I suspect that it's the addition of the new index that's thrown out the query plan for that stored procedure. Have you tried running ``` update statistics *table_name* ``` on it? If that fails you can find out how many scan descriptors you have by running ``` sp_monitorconfig "aux scan descriptors" ``` and then increase that by running ``` sp_configure "aux scan descriptors", x ``` where x is the number of scan descriptors you require. If you wish to reduce the number of scan descriptors that the store procedure is using then according to [here](http://infocenter.sybase.com/help/index.jsp?topic=/com.sybase.help.ase_15.0.sag1/html/sag1/sag1249.htm) you have to *Rewrite the query, or break it into steps using temporary tables. For data-only-locked tables, consider adding indexes if there are many table scans.* but without seeing a query plan it's impossible to give more specific advice.
271,043
<p>I'm using jQuery to post a form to a php file, simple script to verify user details.</p> <pre><code>var emailval = $("#email").val(); var invoiceIdval = $("#invoiceId").val(); $.post("includes/verify.php", {invoiceId:invoiceIdval , email:emailval }, function(data) { //stuff here. }); </code></pre> <p>PHP Code:</p> <pre><code>&lt;?php print_r($_POST); ?&gt; </code></pre> <p>I look at the response in firebug, it is an empty array. The array should have at least some value.</p> <p>I can not work out why the <code>$_POST</code> isn't working in the php file. Firebug shows the post to contain the contents posted, email and invoice id, just nothing is actually received in the php file.</p> <p>The form:</p> <pre><code>&lt;form method="post" action="&lt;?=$_SERVER['PHP_SELF']; ?&gt;" enctype="application/x-www-form-urlencoded"&gt; </code></pre> <p>Anyone know what its doing?</p> <p>thanks</p> <hr> <p>found this - <a href="http://www.bradino.com/php/empty-post-array/" rel="nofollow noreferrer">http://www.bradino.com/php/empty-post-array/</a></p> <p>that a sensible route to go?</p>
[ { "answer_id": 271064, "author": "Douglas Mayle", "author_id": 8458, "author_profile": "https://Stackoverflow.com/users/8458", "pm_score": 1, "selected": false, "text": "<pre><code>application/x-www-form-urlencoded\n</code></pre>\n\n<p>There's your answer. It's getting posted, you're just looking for the variables in $_POST array. What you really want is $_REQUEST. Contrary to the name, $_POST contains input variables submitted in the body of the request, regardless of submission method. $_GET contains variables parsed from the query string of the URL. If you just want submitted variables, use the $_REQUEST global.</p>\n\n<p>If you expect to be receiving file uploads, than you want to create a new array including the contents of $_FILES as well:</p>\n\n<p>$arguments = $_REQUEST + $_FILES;</p>\n" }, { "answer_id": 271094, "author": "Owen", "author_id": 4853, "author_profile": "https://Stackoverflow.com/users/4853", "pm_score": 5, "selected": true, "text": "<p><code>$.post()</code> passes data to the underlying <code>$.ajax()</code> call, which sets <code>application/x-www-form-urlencoded</code> by default, so i don't think it's that.</p>\n\n<p>can you try this:</p>\n\n<pre><code>var post = $('#myForm').serialize(); \n\n$.post(\"includes/verify.php\", post, function(data) { \n alert(data);\n});\n</code></pre>\n\n<p>the <code>serialize()</code> call will grab all the current data in <code>form.myForm</code>.</p>\n" }, { "answer_id": 807131, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 2, "selected": false, "text": "<p>I got bitten by the same issue, and I find the solution Owen gives not appropriate. You're serializing the object yourself, while jQuery should do that for you. You might as well do a $.get() in that case.</p>\n\n<p>I found out that in my case it was actually a server redirect from /mydir to /mydir/ (with slash) that invalidated the POST array. The request got sent to an index.php within /mydir</p>\n\n<p>This was on a local machine, so I couldn't check the HTTP traffic. I would have found out earlier if I would have done that.</p>\n" }, { "answer_id": 2587417, "author": "dardub", "author_id": 302760, "author_profile": "https://Stackoverflow.com/users/302760", "pm_score": 0, "selected": false, "text": "<p>I tried the given function from Owen but got a blank alert as well. Strange but i noticed it would output a query string and return a blank alert. Then i'd submit again and it would alert with correct post values. </p>\n\n<p>Also had the field names set in the html using the id attribute (which was how it was done in a jquery tutorial I was following). This didn't allow my form fields to serialize. When I switched the id's to name, it solved my problem.</p>\n\n<p>I ended up going with $.ajax after all that since it did what I was looking for.</p>\n" }, { "answer_id": 7413265, "author": "Josh P", "author_id": 477361, "author_profile": "https://Stackoverflow.com/users/477361", "pm_score": -1, "selected": false, "text": "<p>I had a case where I was using jQuery to disable all the inputs (even the hidden ones I wanted) just before using jQuery to submit the form. I changed my jQuery to only disable the \"button\" type inputs and now the hidden vars are posted when the form is submitted! It seems that if you set a hidden input to disabled its values aren't posted with the form!</p>\n\n<p>Changed:</p>\n\n<pre><code>$('input').attr('disabled',true);\n</code></pre>\n\n<p>to:</p>\n\n<pre><code>$('input[type=button]').attr('disabled',true);\n</code></pre>\n" } ]
2008/11/07
[ "https://Stackoverflow.com/questions/271043", "https://Stackoverflow.com", "https://Stackoverflow.com/users/34975/" ]
I'm using jQuery to post a form to a php file, simple script to verify user details. ``` var emailval = $("#email").val(); var invoiceIdval = $("#invoiceId").val(); $.post("includes/verify.php", {invoiceId:invoiceIdval , email:emailval }, function(data) { //stuff here. }); ``` PHP Code: ``` <?php print_r($_POST); ?> ``` I look at the response in firebug, it is an empty array. The array should have at least some value. I can not work out why the `$_POST` isn't working in the php file. Firebug shows the post to contain the contents posted, email and invoice id, just nothing is actually received in the php file. The form: ``` <form method="post" action="<?=$_SERVER['PHP_SELF']; ?>" enctype="application/x-www-form-urlencoded"> ``` Anyone know what its doing? thanks --- found this - <http://www.bradino.com/php/empty-post-array/> that a sensible route to go?
`$.post()` passes data to the underlying `$.ajax()` call, which sets `application/x-www-form-urlencoded` by default, so i don't think it's that. can you try this: ``` var post = $('#myForm').serialize(); $.post("includes/verify.php", post, function(data) { alert(data); }); ``` the `serialize()` call will grab all the current data in `form.myForm`.
271,045
<p>I'm new to the MVC framework and wondering how to pass the RSS data from the controller to a view. I know there is a need to convert to an IEnumerable list of some sort. I have seen some examples of creating an anonymous type but can not figure out how to convert an RSS feed to a generic list and pass it to the view. </p> <p>I don't want it to be strongly typed either as there will be multiple calls to various RSS feeds. </p> <p>Any suggestions. </p>
[ { "answer_id": 271484, "author": "Javier Suero Santos", "author_id": 34432, "author_profile": "https://Stackoverflow.com/users/34432", "pm_score": 0, "selected": false, "text": "<p>A rss is a xml file with special format. You may design a dataset with that generic format and read the rss(xml) with ReadXml method and the uri as the path to the file. Then you have got a dataset you can consume from another clases.</p>\n" }, { "answer_id": 272576, "author": "Matthew", "author_id": 20162, "author_profile": "https://Stackoverflow.com/users/20162", "pm_score": 4, "selected": true, "text": "<p>I've been playing around with a way of doing WebParts in MVC which are basically UserControls wrapped in a webPart container. One of my test UserControls is an Rss Feed control. I use the RenderAction HtmlHelper extension in the Futures dll to display it so a controller action is called. I use the SyndicationFeed class to do most of the work</p>\n\n<pre><code>using (XmlReader reader = XmlReader.Create(feed))\n{\n SyndicationFeed rssData = SyndicationFeed.Load(reader);\n\n return View(rssData);\n }\n</code></pre>\n\n<p>Below is the controller and UserControl code:</p>\n\n<p>The Controller code is:</p>\n\n<pre><code>using System;\nusing System.Collections.Generic;\nusing System.Linq;\nusing System.Web;\nusing System.Web.Mvc;\nusing System.Web.Mvc.Ajax;\nusing System.Xml;\nusing System.ServiceModel.Syndication;\nusing System.Security;\nusing System.IO;\n\nnamespace MvcWidgets.Controllers\n{\n public class RssWidgetController : Controller\n {\n public ActionResult Index(string feed)\n {\n string errorString = \"\";\n\n try\n {\n if (String.IsNullOrEmpty(feed))\n {\n throw new ArgumentNullException(\"feed\");\n }\n **using (XmlReader reader = XmlReader.Create(feed))\n {\n SyndicationFeed rssData = SyndicationFeed.Load(reader);\n\n return View(rssData);\n }**\n }\n catch (ArgumentNullException)\n {\n errorString = \"No url for Rss feed specified.\";\n }\n catch (SecurityException)\n {\n errorString = \"You do not have permission to access the specified Rss feed.\";\n }\n catch (FileNotFoundException)\n {\n errorString = \"The Rss feed was not found.\";\n }\n catch (UriFormatException)\n {\n errorString = \"The Rss feed specified was not a valid URI.\";\n }\n catch (Exception)\n {\n errorString = \"An error occured accessing the RSS feed.\";\n }\n\n var errorResult = new ContentResult();\n errorResult.Content = errorString;\n return errorResult;\n\n }\n }\n}\n</code></pre>\n\n<p>The UserControl</p>\n\n<pre><code>&lt;%@ Control Language=\"C#\" AutoEventWireup=\"true\" CodeBehind=\"Index.ascx.cs\" Inherits=\"MvcWidgets.Views.RssWidget.Index\" %&gt;\n&lt;div class=\"RssFeedTitle\"&gt;&lt;%= Html.Encode(ViewData.Model.Title.Text) %&gt; &amp;nbsp; &lt;%= Html.Encode(ViewData.Model.LastUpdatedTime.ToString(\"MMM dd, yyyy hh:mm:ss\") )%&gt;&lt;/div&gt;\n\n&lt;div class='RssContent'&gt;\n&lt;% foreach (var item in ViewData.Model.Items)\n {\n string url = item.Links[0].Uri.OriginalString;\n %&gt;\n &lt;p&gt;&lt;a href='&lt;%= url %&gt;'&gt;&lt;b&gt; &lt;%= item.Title.Text%&gt;&lt;/b&gt;&lt;/a&gt;\n &lt;% if (item.Summary != null)\n {%&gt;\n &lt;br/&gt; &lt;%= item.Summary.Text %&gt;\n &lt;% }\n } %&gt; &lt;/p&gt;\n&lt;/div&gt;\n</code></pre>\n\n<p>with the code behind modified to have a typed Model</p>\n\n<pre><code>using System;\nusing System.Collections.Generic;\nusing System.Linq;\nusing System.Web;\nusing System.Web.Mvc;\nusing System.ServiceModel.Syndication;\n\nnamespace MvcWidgets.Views.RssWidget\n{\n public partial class Index : System.Web.Mvc.ViewUserControl&lt;SyndicationFeed&gt;\n {\n }\n}\n</code></pre>\n" }, { "answer_id": 3146522, "author": "viperguynaz", "author_id": 379677, "author_profile": "https://Stackoverflow.com/users/379677", "pm_score": 3, "selected": false, "text": "<p>@Matthew - perfect solution - as an alternative to code behind which tends to break the MVC concept, you can use:</p>\n\n<pre><code>&lt;%@ Page Language=\"C#\" MasterPageFile=\"~/Views/Shared/Site.Master\" Inherits=\"System.Web.Mvc.ViewPage&lt;SyndicationFeed&gt;\" %&gt; \n&lt;%@ Import Namespace=\"System.ServiceModel.Syndication\" %&gt;\n</code></pre>\n" }, { "answer_id": 8838606, "author": "lko", "author_id": 878612, "author_profile": "https://Stackoverflow.com/users/878612", "pm_score": 1, "selected": false, "text": "<p>Using MVC you don't even need to create a view, you can directly return XML to the feed reader using the SyndicationFeed Class.</p>\n\n<p>(Edit) <a href=\"https://stackoverflow.com/questions/5452878/net-servicemodel-syndication-changing-encoding-on-rss-feed\">.NET ServiceModel.Syndication - Changing Encoding on RSS Feed</a> this is a better way. (snip from this link instead.)</p>\n\n<p><a href=\"http://msdn.microsoft.com/en-us/library/system.servicemodel.syndication.syndicationfeed.aspx\" rel=\"nofollow noreferrer\">http://msdn.microsoft.com/en-us/library/system.servicemodel.syndication.syndicationfeed.aspx</a></p>\n\n<pre><code>public ActionResult RSS(string id)\n{ \n return return File(MyModel.CreateFeed(id), \"application/rss+xml; charset=utf-8\");\n}\n</code></pre>\n\n<p>In MyModel</p>\n\n<pre><code>CreateFeed(string id)\n{ \n SyndicationFeed feed = new SyndicationFeed( ... as in the MS link above)\n\n .... (as in the MS link)\n\n //(from the SO Link)\n var settings = new XmlWriterSettings \n { \n Encoding = Encoding.UTF8, \n NewLineHandling = NewLineHandling.Entitize, \n NewLineOnAttributes = true, \n Indent = true \n };\n using (var stream = new MemoryStream())\n using (var writer = XmlWriter.Create(stream, settings))\n {\n feed.SaveAsRss20(writer);\n writer.Flush();\n return stream.ToArray();\n }\n\n\n}\n</code></pre>\n" } ]
2008/11/07
[ "https://Stackoverflow.com/questions/271045", "https://Stackoverflow.com", "https://Stackoverflow.com/users/31148/" ]
I'm new to the MVC framework and wondering how to pass the RSS data from the controller to a view. I know there is a need to convert to an IEnumerable list of some sort. I have seen some examples of creating an anonymous type but can not figure out how to convert an RSS feed to a generic list and pass it to the view. I don't want it to be strongly typed either as there will be multiple calls to various RSS feeds. Any suggestions.
I've been playing around with a way of doing WebParts in MVC which are basically UserControls wrapped in a webPart container. One of my test UserControls is an Rss Feed control. I use the RenderAction HtmlHelper extension in the Futures dll to display it so a controller action is called. I use the SyndicationFeed class to do most of the work ``` using (XmlReader reader = XmlReader.Create(feed)) { SyndicationFeed rssData = SyndicationFeed.Load(reader); return View(rssData); } ``` Below is the controller and UserControl code: The Controller code is: ``` using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.Mvc; using System.Web.Mvc.Ajax; using System.Xml; using System.ServiceModel.Syndication; using System.Security; using System.IO; namespace MvcWidgets.Controllers { public class RssWidgetController : Controller { public ActionResult Index(string feed) { string errorString = ""; try { if (String.IsNullOrEmpty(feed)) { throw new ArgumentNullException("feed"); } **using (XmlReader reader = XmlReader.Create(feed)) { SyndicationFeed rssData = SyndicationFeed.Load(reader); return View(rssData); }** } catch (ArgumentNullException) { errorString = "No url for Rss feed specified."; } catch (SecurityException) { errorString = "You do not have permission to access the specified Rss feed."; } catch (FileNotFoundException) { errorString = "The Rss feed was not found."; } catch (UriFormatException) { errorString = "The Rss feed specified was not a valid URI."; } catch (Exception) { errorString = "An error occured accessing the RSS feed."; } var errorResult = new ContentResult(); errorResult.Content = errorString; return errorResult; } } } ``` The UserControl ``` <%@ Control Language="C#" AutoEventWireup="true" CodeBehind="Index.ascx.cs" Inherits="MvcWidgets.Views.RssWidget.Index" %> <div class="RssFeedTitle"><%= Html.Encode(ViewData.Model.Title.Text) %> &nbsp; <%= Html.Encode(ViewData.Model.LastUpdatedTime.ToString("MMM dd, yyyy hh:mm:ss") )%></div> <div class='RssContent'> <% foreach (var item in ViewData.Model.Items) { string url = item.Links[0].Uri.OriginalString; %> <p><a href='<%= url %>'><b> <%= item.Title.Text%></b></a> <% if (item.Summary != null) {%> <br/> <%= item.Summary.Text %> <% } } %> </p> </div> ``` with the code behind modified to have a typed Model ``` using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.Mvc; using System.ServiceModel.Syndication; namespace MvcWidgets.Views.RssWidget { public partial class Index : System.Web.Mvc.ViewUserControl<SyndicationFeed> { } } ```
271,062
<p>I'm using Emgu.CV which is a C# wrapper for the OpenCV libraries. </p> <p>I changed the Emgu.CV source to invoke from the latest OpenCV library cv110.dll instead of cv100.dll and now I get this error (where ????? is cv110.dll). I have placed the cv110.dll file in all the same locations as the cv100.dll file however this does not help.</p> <p>On a broader scale, what is the folder search order when looking for dlls, and are there anyone other reasons for this error.</p>
[ { "answer_id": 271484, "author": "Javier Suero Santos", "author_id": 34432, "author_profile": "https://Stackoverflow.com/users/34432", "pm_score": 0, "selected": false, "text": "<p>A rss is a xml file with special format. You may design a dataset with that generic format and read the rss(xml) with ReadXml method and the uri as the path to the file. Then you have got a dataset you can consume from another clases.</p>\n" }, { "answer_id": 272576, "author": "Matthew", "author_id": 20162, "author_profile": "https://Stackoverflow.com/users/20162", "pm_score": 4, "selected": true, "text": "<p>I've been playing around with a way of doing WebParts in MVC which are basically UserControls wrapped in a webPart container. One of my test UserControls is an Rss Feed control. I use the RenderAction HtmlHelper extension in the Futures dll to display it so a controller action is called. I use the SyndicationFeed class to do most of the work</p>\n\n<pre><code>using (XmlReader reader = XmlReader.Create(feed))\n{\n SyndicationFeed rssData = SyndicationFeed.Load(reader);\n\n return View(rssData);\n }\n</code></pre>\n\n<p>Below is the controller and UserControl code:</p>\n\n<p>The Controller code is:</p>\n\n<pre><code>using System;\nusing System.Collections.Generic;\nusing System.Linq;\nusing System.Web;\nusing System.Web.Mvc;\nusing System.Web.Mvc.Ajax;\nusing System.Xml;\nusing System.ServiceModel.Syndication;\nusing System.Security;\nusing System.IO;\n\nnamespace MvcWidgets.Controllers\n{\n public class RssWidgetController : Controller\n {\n public ActionResult Index(string feed)\n {\n string errorString = \"\";\n\n try\n {\n if (String.IsNullOrEmpty(feed))\n {\n throw new ArgumentNullException(\"feed\");\n }\n **using (XmlReader reader = XmlReader.Create(feed))\n {\n SyndicationFeed rssData = SyndicationFeed.Load(reader);\n\n return View(rssData);\n }**\n }\n catch (ArgumentNullException)\n {\n errorString = \"No url for Rss feed specified.\";\n }\n catch (SecurityException)\n {\n errorString = \"You do not have permission to access the specified Rss feed.\";\n }\n catch (FileNotFoundException)\n {\n errorString = \"The Rss feed was not found.\";\n }\n catch (UriFormatException)\n {\n errorString = \"The Rss feed specified was not a valid URI.\";\n }\n catch (Exception)\n {\n errorString = \"An error occured accessing the RSS feed.\";\n }\n\n var errorResult = new ContentResult();\n errorResult.Content = errorString;\n return errorResult;\n\n }\n }\n}\n</code></pre>\n\n<p>The UserControl</p>\n\n<pre><code>&lt;%@ Control Language=\"C#\" AutoEventWireup=\"true\" CodeBehind=\"Index.ascx.cs\" Inherits=\"MvcWidgets.Views.RssWidget.Index\" %&gt;\n&lt;div class=\"RssFeedTitle\"&gt;&lt;%= Html.Encode(ViewData.Model.Title.Text) %&gt; &amp;nbsp; &lt;%= Html.Encode(ViewData.Model.LastUpdatedTime.ToString(\"MMM dd, yyyy hh:mm:ss\") )%&gt;&lt;/div&gt;\n\n&lt;div class='RssContent'&gt;\n&lt;% foreach (var item in ViewData.Model.Items)\n {\n string url = item.Links[0].Uri.OriginalString;\n %&gt;\n &lt;p&gt;&lt;a href='&lt;%= url %&gt;'&gt;&lt;b&gt; &lt;%= item.Title.Text%&gt;&lt;/b&gt;&lt;/a&gt;\n &lt;% if (item.Summary != null)\n {%&gt;\n &lt;br/&gt; &lt;%= item.Summary.Text %&gt;\n &lt;% }\n } %&gt; &lt;/p&gt;\n&lt;/div&gt;\n</code></pre>\n\n<p>with the code behind modified to have a typed Model</p>\n\n<pre><code>using System;\nusing System.Collections.Generic;\nusing System.Linq;\nusing System.Web;\nusing System.Web.Mvc;\nusing System.ServiceModel.Syndication;\n\nnamespace MvcWidgets.Views.RssWidget\n{\n public partial class Index : System.Web.Mvc.ViewUserControl&lt;SyndicationFeed&gt;\n {\n }\n}\n</code></pre>\n" }, { "answer_id": 3146522, "author": "viperguynaz", "author_id": 379677, "author_profile": "https://Stackoverflow.com/users/379677", "pm_score": 3, "selected": false, "text": "<p>@Matthew - perfect solution - as an alternative to code behind which tends to break the MVC concept, you can use:</p>\n\n<pre><code>&lt;%@ Page Language=\"C#\" MasterPageFile=\"~/Views/Shared/Site.Master\" Inherits=\"System.Web.Mvc.ViewPage&lt;SyndicationFeed&gt;\" %&gt; \n&lt;%@ Import Namespace=\"System.ServiceModel.Syndication\" %&gt;\n</code></pre>\n" }, { "answer_id": 8838606, "author": "lko", "author_id": 878612, "author_profile": "https://Stackoverflow.com/users/878612", "pm_score": 1, "selected": false, "text": "<p>Using MVC you don't even need to create a view, you can directly return XML to the feed reader using the SyndicationFeed Class.</p>\n\n<p>(Edit) <a href=\"https://stackoverflow.com/questions/5452878/net-servicemodel-syndication-changing-encoding-on-rss-feed\">.NET ServiceModel.Syndication - Changing Encoding on RSS Feed</a> this is a better way. (snip from this link instead.)</p>\n\n<p><a href=\"http://msdn.microsoft.com/en-us/library/system.servicemodel.syndication.syndicationfeed.aspx\" rel=\"nofollow noreferrer\">http://msdn.microsoft.com/en-us/library/system.servicemodel.syndication.syndicationfeed.aspx</a></p>\n\n<pre><code>public ActionResult RSS(string id)\n{ \n return return File(MyModel.CreateFeed(id), \"application/rss+xml; charset=utf-8\");\n}\n</code></pre>\n\n<p>In MyModel</p>\n\n<pre><code>CreateFeed(string id)\n{ \n SyndicationFeed feed = new SyndicationFeed( ... as in the MS link above)\n\n .... (as in the MS link)\n\n //(from the SO Link)\n var settings = new XmlWriterSettings \n { \n Encoding = Encoding.UTF8, \n NewLineHandling = NewLineHandling.Entitize, \n NewLineOnAttributes = true, \n Indent = true \n };\n using (var stream = new MemoryStream())\n using (var writer = XmlWriter.Create(stream, settings))\n {\n feed.SaveAsRss20(writer);\n writer.Flush();\n return stream.ToArray();\n }\n\n\n}\n</code></pre>\n" } ]
2008/11/07
[ "https://Stackoverflow.com/questions/271062", "https://Stackoverflow.com", "https://Stackoverflow.com/users/31045/" ]
I'm using Emgu.CV which is a C# wrapper for the OpenCV libraries. I changed the Emgu.CV source to invoke from the latest OpenCV library cv110.dll instead of cv100.dll and now I get this error (where ????? is cv110.dll). I have placed the cv110.dll file in all the same locations as the cv100.dll file however this does not help. On a broader scale, what is the folder search order when looking for dlls, and are there anyone other reasons for this error.
I've been playing around with a way of doing WebParts in MVC which are basically UserControls wrapped in a webPart container. One of my test UserControls is an Rss Feed control. I use the RenderAction HtmlHelper extension in the Futures dll to display it so a controller action is called. I use the SyndicationFeed class to do most of the work ``` using (XmlReader reader = XmlReader.Create(feed)) { SyndicationFeed rssData = SyndicationFeed.Load(reader); return View(rssData); } ``` Below is the controller and UserControl code: The Controller code is: ``` using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.Mvc; using System.Web.Mvc.Ajax; using System.Xml; using System.ServiceModel.Syndication; using System.Security; using System.IO; namespace MvcWidgets.Controllers { public class RssWidgetController : Controller { public ActionResult Index(string feed) { string errorString = ""; try { if (String.IsNullOrEmpty(feed)) { throw new ArgumentNullException("feed"); } **using (XmlReader reader = XmlReader.Create(feed)) { SyndicationFeed rssData = SyndicationFeed.Load(reader); return View(rssData); }** } catch (ArgumentNullException) { errorString = "No url for Rss feed specified."; } catch (SecurityException) { errorString = "You do not have permission to access the specified Rss feed."; } catch (FileNotFoundException) { errorString = "The Rss feed was not found."; } catch (UriFormatException) { errorString = "The Rss feed specified was not a valid URI."; } catch (Exception) { errorString = "An error occured accessing the RSS feed."; } var errorResult = new ContentResult(); errorResult.Content = errorString; return errorResult; } } } ``` The UserControl ``` <%@ Control Language="C#" AutoEventWireup="true" CodeBehind="Index.ascx.cs" Inherits="MvcWidgets.Views.RssWidget.Index" %> <div class="RssFeedTitle"><%= Html.Encode(ViewData.Model.Title.Text) %> &nbsp; <%= Html.Encode(ViewData.Model.LastUpdatedTime.ToString("MMM dd, yyyy hh:mm:ss") )%></div> <div class='RssContent'> <% foreach (var item in ViewData.Model.Items) { string url = item.Links[0].Uri.OriginalString; %> <p><a href='<%= url %>'><b> <%= item.Title.Text%></b></a> <% if (item.Summary != null) {%> <br/> <%= item.Summary.Text %> <% } } %> </p> </div> ``` with the code behind modified to have a typed Model ``` using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.Mvc; using System.ServiceModel.Syndication; namespace MvcWidgets.Views.RssWidget { public partial class Index : System.Web.Mvc.ViewUserControl<SyndicationFeed> { } } ```
271,067
<p>I have the following CSS and HTML snippet being rendered.</p> <p><div class="snippet" data-lang="js" data-hide="false" data-console="false" data-babel="false"> <div class="snippet-code"> <pre class="snippet-code-css lang-css prettyprint-override"><code>textarea { border:1px solid #999999; width:100%; margin:5px 0; padding:3px; }</code></pre> <pre class="snippet-code-html lang-html prettyprint-override"><code>&lt;div style="display: block;" id="rulesformitem" class="formitem"&gt; &lt;label for="rules" id="ruleslabel"&gt;Rules:&lt;/label&gt; &lt;textarea cols="2" rows="10" id="rules"&gt;&lt;/textarea&gt; &lt;/div&gt;</code></pre> </div> </div> </p> <p>Is the problem is that the text area ends up being 8px wider (2px for border + 6px for padding) than the parent. Is there a way to continue to use border and padding but constrain the total size of the <code>textarea</code> to the width of the parent?</p>
[ { "answer_id": 271302, "author": "buti-oxa", "author_id": 2515, "author_profile": "https://Stackoverflow.com/users/2515", "pm_score": 2, "selected": false, "text": "<p>No, you cannot do that with CSS. That is the reason Microsoft initially introduced another, and maybe more practical <a href=\"http://en.wikipedia.org/wiki/Internet_Explorer_box_model_bug\" rel=\"nofollow noreferrer\">box model</a>. The box model that eventually won, makes it inpractical to mix percentages and units. </p>\n\n<p>I don't think it is OK with you to express padding and border widths in percentage of the parent too.</p>\n" }, { "answer_id": 272632, "author": "Dave Sherohman", "author_id": 18914, "author_profile": "https://Stackoverflow.com/users/18914", "pm_score": 7, "selected": false, "text": "<p>The answer to many CSS formatting problems seems to be \"add another &lt;div>!\"</p>\n\n<p>So, in that spirit, have you tried adding a wrapper div to which the border/padding are applied and then putting the 100% width textarea inside of that? Something like (untested):</p>\n\n<p><div class=\"snippet\" data-lang=\"js\" data-hide=\"false\" data-console=\"false\" data-babel=\"false\">\r\n<div class=\"snippet-code\">\r\n<pre class=\"snippet-code-css lang-css prettyprint-override\"><code>textarea\r\n{\r\n width:100%;\r\n}\r\n.textwrapper\r\n{\r\n border:1px solid #999999;\r\n margin:5px 0;\r\n padding:3px;\r\n}</code></pre>\r\n<pre class=\"snippet-code-html lang-html prettyprint-override\"><code>&lt;div style=\"display: block;\" id=\"rulesformitem\" class=\"formitem\"&gt;\r\n &lt;label for=\"rules\" id=\"ruleslabel\"&gt;Rules:&lt;/label&gt;\r\n &lt;div class=\"textwrapper\"&gt;&lt;textarea cols=\"2\" rows=\"10\" id=\"rules\"/&gt;&lt;/div&gt;\r\n&lt;/div&gt;</code></pre>\r\n</div>\r\n</div>\r\n</p>\n" }, { "answer_id": 272733, "author": "Chris James", "author_id": 3193, "author_profile": "https://Stackoverflow.com/users/3193", "pm_score": 4, "selected": false, "text": "<p>If you're not too bothered about the width of the padding, this solution will actually keep the padding in percentages too..</p>\n\n<pre><code>textarea\n{\n border:1px solid #999999;\n width:98%;\n margin:5px 0;\n padding:1%;\n}\n</code></pre>\n\n<p>Not perfect, but you'll get some padding and the width adds up to 100% so its all good</p>\n" }, { "answer_id": 2499203, "author": "Emanuele Del Grande", "author_id": 299801, "author_profile": "https://Stackoverflow.com/users/299801", "pm_score": 5, "selected": false, "text": "<p>let's consider the <em>final output rendered to the user</em> of what we want to achieve: a padded textarea with both a border and a padding, which characteristics are that being clicked they pass the focus to our textarea, and the advantage of an automatic 100% width typical of block elements.</p>\n\n<p>The best approach in my opinion is to use low level solutions as far as possible, to reach the maximum browsers support.\nIn this case the only HTML could work fine, avoiding the use of Javascript (which anyhow we all love).</p>\n\n<p>The LABEL tag comes in our help because has such behaviour and is allowed to contain the input elements it must address to.\nIts default style is the one of inline elements, so, giving to the label a block display style we can avail ourselves of the automatic 100% width including padding and borders, while the inner textarea has no border, no padding and a 100% width.</p>\n\n<p>Taking a look at the W3C specifics other advantages we may notice are:</p>\n\n<ul>\n<li>no \"for\" attribute is needed: when a LABEL tag contains the target input, it automatically focuses the child input when clicked;</li>\n<li>if an external label for the textarea has already been designed, no conflicts occur, since a given input may have one or more labels.</li>\n</ul>\n\n<p>See <a href=\"http://www.w3.org/TR/html401/interact/forms.html#h-17.9.1\" rel=\"nofollow noreferrer\">W3C specifics</a> for more detailed information.</p>\n\n<p>Simple example:</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>.container { \r\n width: 400px; \r\n border: 3px \r\n solid #f7c; \r\n }\r\n.textareaContainer {\r\n display: block;\r\n border: 3px solid #38c;\r\n padding: 10px;\r\n }\r\ntextarea { \r\n width: 100%; \r\n margin: 0; \r\n padding: 0; \r\n border-width: 0; \r\n }</code></pre>\r\n<pre class=\"snippet-code-html lang-html prettyprint-override\"><code>&lt;body&gt;\r\n&lt;div class=\"container\"&gt;\r\n I am the container\r\n &lt;label class=\"textareaContainer\"&gt;\r\n &lt;textarea name=\"text\"&gt;I am the padded textarea with a styled border...&lt;/textarea&gt;\r\n &lt;/label&gt;\r\n&lt;/div&gt;\r\n&lt;/body&gt;</code></pre>\r\n</div>\r\n</div>\r\n</p>\n\n<p>The padding and border of the .textareaContainer elements are the ones we want to give to the textarea. Try editing them to style it as you want.\nI gave large and visible padding and borders to the .textareaContainer element to let you see their behaviour when clicked.</p>\n" }, { "answer_id": 2515439, "author": "jzfgo", "author_id": 252705, "author_profile": "https://Stackoverflow.com/users/252705", "pm_score": 3, "selected": false, "text": "<p>You can make use of the box-sizing property, it's supported by all the main standard-compliant browsers and IE8+. You still will need a workaround for IE7 though. Read more <a href=\"http://www.quirksmode.org/css/box.html\" rel=\"nofollow noreferrer\">here</a>.</p>\n" }, { "answer_id": 4156343, "author": "Piet Bijl", "author_id": 232872, "author_profile": "https://Stackoverflow.com/users/232872", "pm_score": 11, "selected": true, "text": "<p>Why not forget the hacks and just do it with CSS?</p>\n\n<p>One I use frequently:</p>\n\n<pre class=\"lang-css prettyprint-override\"><code>.boxsizingBorder {\n -webkit-box-sizing: border-box;\n -moz-box-sizing: border-box;\n box-sizing: border-box;\n}\n</code></pre>\n\n<p>See browser support <a href=\"http://caniuse.com/css3-boxsizing\" rel=\"noreferrer\">here</a>.</p>\n" }, { "answer_id": 6876052, "author": "Brian", "author_id": 244191, "author_profile": "https://Stackoverflow.com/users/244191", "pm_score": 4, "selected": false, "text": "<p>I came across another solution <a href=\"http://unwrongest.com/100-percent-width-textareas/\" rel=\"noreferrer\">here</a> that is so simple: add padding-right to the textarea's container. This keeps the margin, border, and padding on the textarea, which avoids the problem that Beck pointed out about the focus highlight that chrome and safari put around the textarea.</p>\n\n<p>The container's padding-right should be the sum of the effective margin, border, and padding on both sides of the textarea, plus any padding you may otherwise want for the container. So, for the case in the original question:</p>\n\n<pre><code>textarea{\n border:1px solid #999999;\n width:100%;\n margin:5px 0;\n padding:3px;\n}\n.textareacontainer{\n padding-right: 8px; /* 1 + 3 + 3 + 1 */\n}\n</code></pre>\n\n<p>\n\n<pre><code>&lt;div class=\"textareacontainer\"&gt;\n &lt;textarea&gt;&lt;/textarea&gt;\n&lt;/div&gt;\n</code></pre>\n" }, { "answer_id": 11041279, "author": "meustrus", "author_id": 710377, "author_profile": "https://Stackoverflow.com/users/710377", "pm_score": 0, "selected": false, "text": "<p>How about negative margins?</p>\n\n<pre><code>textarea {\n border:1px solid #999999;\n width:100%;\n margin:5px -4px; /* 4px = border+padding on one side */\n padding:3px;\n}\n</code></pre>\n" }, { "answer_id": 15798921, "author": "commonpike", "author_id": 95733, "author_profile": "https://Stackoverflow.com/users/95733", "pm_score": 1, "selected": false, "text": "<p>If you pad and offset it like this:</p>\n\n<pre><code>textarea\n{\n border:1px solid #999999;\n width:100%;\n padding: 7px 0 7px 7px; \n position:relative; left:-8px; /* 1px border, too */\n}\n</code></pre>\n\n<p>the right side of the textarea perfectly aligns with the right side of the container, <em>and</em> the text inside the textarea aligns perfectly with the body text in the container... and the left side of the textarea 'sticks out' a bit. it's sometimes prettier.</p>\n" }, { "answer_id": 19942900, "author": "Jeff Guest", "author_id": 2985580, "author_profile": "https://Stackoverflow.com/users/2985580", "pm_score": 4, "selected": false, "text": "<p>This code works for me with IE8 and Firefox</p>\n\n<pre><code>&lt;td&gt;\n &lt;textarea style=\"width:100%\" rows=3 name=\"abc\"&gt;Modify width:% accordingly&lt;/textarea&gt;\n&lt;/td&gt;\n</code></pre>\n" }, { "answer_id": 25103051, "author": "user3074446", "author_id": 3074446, "author_profile": "https://Stackoverflow.com/users/3074446", "pm_score": 1, "selected": false, "text": "<p>Use <a href=\"http://www.w3schools.com/cssref/css3_pr_box-sizing.asp\" rel=\"nofollow\">box sizing property</a>:</p>\n\n<pre><code>-moz-box-sizing:border-box; \n-webkit-box-sizing:border-box; \nbox-sizing:border-box;\n</code></pre>\n\n<p>That will help </p>\n" }, { "answer_id": 25185897, "author": "Gwi7d31", "author_id": 1659082, "author_profile": "https://Stackoverflow.com/users/1659082", "pm_score": 1, "selected": false, "text": "<p>For people who use Bootstrap, textarea.form-control can lead to textarea sizing issues as well. Chrome and Firefox appear to use different heights with the following Bootstrap CSS:</p>\n\n<pre><code>textarea.form-conrtol{\n height:auto;\n}\n</code></pre>\n" }, { "answer_id": 40606642, "author": "Jeroen Bellemans", "author_id": 4118983, "author_profile": "https://Stackoverflow.com/users/4118983", "pm_score": 1, "selected": false, "text": "<p>I often fix that problem with <code>calc()</code>. You just give the textarea a width of 100% and a certain amount of padding, but you have to subtract the total left and right padding of the 100% width you have given to the textarea:</p>\n\n<pre><code>textarea {\n border: 0px;\n width: calc(100% -10px);\n padding: 5px; \n}\n</code></pre>\n\n<p>Or if you want to give the textarea a border:</p>\n\n<pre><code>textarea {\n border: 1px;\n width: calc(100% -12px); /* plus the total left and right border */\n padding: 5px; \n}\n</code></pre>\n" }, { "answer_id": 48556129, "author": "antelove", "author_id": 7656367, "author_profile": "https://Stackoverflow.com/users/7656367", "pm_score": 0, "selected": false, "text": "<p><div class=\"snippet\" data-lang=\"js\" data-hide=\"false\" data-console=\"true\" data-babel=\"false\">\r\n<div class=\"snippet-code\">\r\n<pre class=\"snippet-code-css lang-css prettyprint-override\"><code>* {\r\n box-sizing: border-box;\r\n}\r\n\r\n.container {\r\n border-radius: 5px;\r\n background-color: #f2f2f2;\r\n padding: 20px;\r\n}\r\n\r\n/* Clear floats after the columns */\r\n.row:after {\r\n content: \"\";\r\n display: table;\r\n clear: both;\r\n}\r\n\r\ninput[type=text], select, textarea{\r\n width: 100%;\r\n padding: 12px;\r\n border: 1px solid #ccc;\r\n border-radius: 4px;\r\n box-sizing: border-box;\r\n resize: vertical;\r\n}</code></pre>\r\n<pre class=\"snippet-code-html lang-html prettyprint-override\"><code>&lt;div class=\"container\"&gt;\r\n &lt;div class=\"row\"&gt;\r\n &lt;label for=\"name\"&gt;Name&lt;/label&gt;\r\n &lt;input type=\"text\" id=\"name\" name=\"name\" placeholder=\"Your name..\"&gt;\r\n &lt;/div&gt;\r\n &lt;div class=\"row\"&gt;\r\n &lt;label for=\"country\"&gt;Country&lt;/label&gt;\r\n &lt;select id=\"country\" name=\"country\"&gt;\r\n &lt;option value=\"australia\"&gt;UK&lt;/option&gt;\r\n &lt;option value=\"canada\"&gt;USA&lt;/option&gt;\r\n &lt;option value=\"usa\"&gt;RU&lt;/option&gt;\r\n &lt;/select&gt;\r\n &lt;/div&gt; \r\n &lt;div class=\"row\"&gt;\r\n &lt;label for=\"subject\"&gt;Subject&lt;/label&gt;\r\n &lt;textarea id=\"subject\" name=\"subject\" placeholder=\"Write something..\" style=\"height:200px\"&gt;&lt;/textarea&gt;\r\n &lt;/div&gt;\r\n&lt;/div&gt;</code></pre>\r\n</div>\r\n</div>\r\n</p>\n" }, { "answer_id": 52925521, "author": "Jee Mok", "author_id": 9206753, "author_profile": "https://Stackoverflow.com/users/9206753", "pm_score": 3, "selected": false, "text": "<p>I was looking for an inline-styling solution instead of CSS solution, and this is the best I can go for a responsive textarea:</p>\n\n<pre><code>&lt;div style=\"width: 100%; max-width: 500px;\"&gt;\n &lt;textarea style=\"width: 100%;\"&gt;&lt;/textarea&gt;\n&lt;/div&gt;\n</code></pre>\n" }, { "answer_id": 67253039, "author": "Ali Baghban", "author_id": 10617518, "author_profile": "https://Stackoverflow.com/users/10617518", "pm_score": 2, "selected": false, "text": "<p>The problem lies in the <code>box-sizing</code> property.\nBy default, the initial value of the <code>box-sizing</code> property is <code>content-box</code>.\nso you have something like this under the hood:</p>\n<pre><code>textarea {\n border:1px solid #999999;\n width:100%;\n margin:5px 0;\n padding:3px;\n box-sizing: content-box;\n}\n</code></pre>\n<p><code>box-sizing: content-box;</code> means that the width of the actual element is equal to the width of the element's content box.\nso when you add padding (in this case padding-right and padding-left --&gt; because we are talking about width) and border (in this case border-right and border-left --&gt; because we are talking about width), these values get added to the final width. so your element will be wider than you want.</p>\n<p>set it to <code>box-sizing: border-box;</code>. so the width will be calculated like so:</p>\n<pre><code>horizontal border + horizontal padding + width of content box = width\n</code></pre>\n<p>in this case, when you add horizontal border and horizontal padding, the final width of element does not change, in fact, the content box will shrink to satisfy the equation.</p>\n" }, { "answer_id": 73535847, "author": "Stokely", "author_id": 5555938, "author_profile": "https://Stackoverflow.com/users/5555938", "pm_score": 0, "selected": false, "text": "<p>Below is a more complete CSS design. As already mentioned, the new box-sizing:border-box; setting pushes the border and padding into the width calculation so when you use min-width:100% everything fits inside the parent container and expands.</p>\n<pre><code>&lt;style type=&quot;text/css&quot;&gt;\n body textarea,\n body textarea:visited,\n body textarea:hover,\n body textarea:focus,\n body textarea:active {\n display: block;\n width: auto;\n height: auto;\n min-width: 100%;\n min-height: 10em;\n padding: 1em;\n margin: 0;\n -webkit-appearance: textarea;\n -moz-appearance: textfield-multiline;\n cursor: text;\n overflow: auto;\n resize: both;\n background-color: #eee;\n word-wrap: normal;\n border: 2px solid #bbb;\n border-radius: .2em;\n font-family:inherit;\n line-height: normal;\n}\n\ndiv {\n border:2px solid blue;\n}\n\ntextarea,div {\n box-sizing: border-box;\n -webkit-box-sizing: border-box;\n -moz-box-sizing: border-box;\n}\n&lt;/style&gt;\n\n&lt;div&gt;\n &lt;textarea&gt;Some test text...&lt;/textarea&gt;\n&lt;/div&gt;\n</code></pre>\n<p>The div parent has a blue border and contains the child textarea in grey.</p>\n<p><a href=\"https://i.stack.imgur.com/Qy6r7.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/Qy6r7.png\" alt=\"enter image description here\" /></a></p>\n" } ]
2008/11/07
[ "https://Stackoverflow.com/questions/271067", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3957/" ]
I have the following CSS and HTML snippet being rendered. ```css textarea { border:1px solid #999999; width:100%; margin:5px 0; padding:3px; } ``` ```html <div style="display: block;" id="rulesformitem" class="formitem"> <label for="rules" id="ruleslabel">Rules:</label> <textarea cols="2" rows="10" id="rules"></textarea> </div> ``` Is the problem is that the text area ends up being 8px wider (2px for border + 6px for padding) than the parent. Is there a way to continue to use border and padding but constrain the total size of the `textarea` to the width of the parent?
Why not forget the hacks and just do it with CSS? One I use frequently: ```css .boxsizingBorder { -webkit-box-sizing: border-box; -moz-box-sizing: border-box; box-sizing: border-box; } ``` See browser support [here](http://caniuse.com/css3-boxsizing).
271,076
<p>Correct me if I am wrong,</p> <p>int is 4 bytes, with a range of values from -2,147,483,648 to 2,147,483,647 (2^31)<br> long is 4 bytes, with a range of values from -2,147,483,648 to 2,147,483,647 (2^31)</p> <p>What is the difference in C++? Can they be used interchangeably?</p>
[ { "answer_id": 271083, "author": "Andru Luvisi", "author_id": 5922, "author_profile": "https://Stackoverflow.com/users/5922", "pm_score": 3, "selected": false, "text": "<p>It depends on your compiler. You are guaranteed that a long will be at least as large as an int, but you are not guaranteed that it will be any longer.</p>\n" }, { "answer_id": 271087, "author": "Rob Walker", "author_id": 3631, "author_profile": "https://Stackoverflow.com/users/3631", "pm_score": 8, "selected": true, "text": "<p>It is implementation dependent. </p>\n\n<p>For example, under Windows they are the same, but for example on Alpha systems a long was 64 bits whereas an int was 32 bits. This <a href=\"http://software.intel.com/en-us/articles/size-of-long-integer-type-on-different-architecture-and-os\" rel=\"noreferrer\">article</a> covers the rules for the Intel C++ compiler on variable platforms. To summarize:</p>\n\n<pre><code> OS arch size\nWindows IA-32 4 bytes\nWindows Intel 64 4 bytes\nWindows IA-64 4 bytes\nLinux IA-32 4 bytes\nLinux Intel 64 8 bytes\nLinux IA-64 8 bytes\nMac OS X IA-32 4 bytes\nMac OS X Intel 64 8 bytes \n</code></pre>\n" }, { "answer_id": 271092, "author": "Adrian", "author_id": 31987, "author_profile": "https://Stackoverflow.com/users/31987", "pm_score": 4, "selected": false, "text": "<p>When compiling for x64, the difference between int and long is somewhere between 0 and 4 bytes, depending on what compiler you use.</p>\n\n<p>GCC uses the LP64 model, which means that ints are 32-bits but longs are 64-bits under 64-bit mode.</p>\n\n<p>MSVC for example uses the LLP64 model, which means both ints and longs are 32-bits even in 64-bit mode.</p>\n" }, { "answer_id": 271107, "author": "Kevin Haines", "author_id": 10410, "author_profile": "https://Stackoverflow.com/users/10410", "pm_score": 4, "selected": false, "text": "<p>The <a href=\"https://web.archive.org/web/20071230202350/http://www.kuzbass.ru/docs/isocpp/basic.html#basic.fundamental\" rel=\"nofollow noreferrer\">C++ specification itself</a> (old version but good enough for this) leaves this open.</p>\n\n<blockquote>\n <p>There are four signed integer types:\n '<code>signed char</code>', '<code>short int</code>',\n '<code>int</code>', and '<code>long int</code>'. In this\n list, each type provides at least as\n much storage as those preceding it in\n the list. Plain ints have the natural\n size suggested by the architecture of\n the execution environment* ; </p>\n \n <p>[Footnote: that is, large enough to\n contain any value in the range of\n INT_MIN and INT_MAX, as defined in the\n header <code>&lt;climits&gt;</code>. --- end foonote]</p>\n</blockquote>\n" }, { "answer_id": 271132, "author": "Martin York", "author_id": 14065, "author_profile": "https://Stackoverflow.com/users/14065", "pm_score": 6, "selected": false, "text": "<p>The only guarantee you have are:</p>\n\n<pre><code>sizeof(char) == 1\nsizeof(char) &lt;= sizeof(short) &lt;= sizeof(int) &lt;= sizeof(long) &lt;= sizeof(long long)\n\n// FROM @KTC. The C++ standard also has:\nsizeof(signed char) == 1\nsizeof(unsigned char) == 1\n\n// NOTE: These size are not specified explicitly in the standard.\n// They are implied by the minimum/maximum values that MUST be supported\n// for the type. These limits are defined in limits.h\nsizeof(short) * CHAR_BIT &gt;= 16\nsizeof(int) * CHAR_BIT &gt;= 16\nsizeof(long) * CHAR_BIT &gt;= 32\nsizeof(long long) * CHAR_BIT &gt;= 64\nCHAR_BIT &gt;= 8 // Number of bits in a byte\n</code></pre>\n\n<p>Also see: <a href=\"https://stackoverflow.com/q/4329777/14065\">Is <code>long</code> guaranteed to be at least 32 bits?</a></p>\n" }, { "answer_id": 271143, "author": "Johannes Schaub - litb", "author_id": 34509, "author_profile": "https://Stackoverflow.com/users/34509", "pm_score": 3, "selected": false, "text": "<p>As Kevin Haines points out, ints have the natural size suggested by the execution environment, which has to fit within INT_MIN and INT_MAX.</p>\n\n<p>The C89 standard states that <code>UINT_MAX</code> should be at least 2^16-1, <code>USHRT_MAX</code> 2^16-1 and <code>ULONG_MAX</code> 2^32-1 . That makes a bit-count of at least 16 for short and int, and 32 for long. For char it states explicitly that it should have at least 8 bits (<code>CHAR_BIT</code>).\nC++ inherits those rules for the limits.h file, so in C++ we have the same fundamental requirements for those values. \nYou should however <em>not</em> derive from that that int is at least 2 byte. Theoretically, char, int and long could all be 1 byte, in which case <code>CHAR_BIT</code> must be at least 32. Just remember that \"byte\" is always the size of a char, so if char is bigger, a byte is not only 8 bits any more.</p>\n" }, { "answer_id": 271187, "author": "Windows programmer", "author_id": 23705, "author_profile": "https://Stackoverflow.com/users/23705", "pm_score": 3, "selected": false, "text": "<p>For the most part, the number of bytes and range of values is determined by the CPU's architecture not by C++. However, C++ sets minimum requirements, which litb explained properly and Martin York only made a few mistakes with.</p>\n\n<p>The reason why you can't use int and long interchangeably is because they aren't always the same length. C was invented on a PDP-11 where a byte had 8 bits, int was two bytes and could be handled directly by hardware instructions. Since C programmers often needed four-byte arithmetic, long was invented and it was four bytes, handled by library functions. Other machines had different specifications. The C standard imposed some minimum requirements.</p>\n" }, { "answer_id": 271200, "author": "Roger Nelson", "author_id": 14964, "author_profile": "https://Stackoverflow.com/users/14964", "pm_score": 3, "selected": false, "text": "<p>Relying on the compiler vendor's implementation of primitive type sizes \nWILL come back to haunt you if you ever compile your code on another\nmachine architecture, OS, or another vendor's compiler .</p>\n\n<p>Most compiler vendors provide a header file that defines primitive types with\nexplict type sizes.\nThese primitive types should be used when ever code may be potentially ported\nto another compiler (read this as ALWAYS in EVERY instance).\nFor example, most UNIX compilers have <code>int8_t uint8_t int16_t int32_t uint32_t</code>.\nMicrosoft has <code>INT8 UINT8 INT16 UINT16 INT32 UINT32</code>.\nI prefer Borland/CodeGear's <code>int8 uint8 int16 uint16 int32 uint32</code>.\nThese names also give a little reminder of the size/range of the intended value.</p>\n\n<p>For years I have used Borland's explicit primitive type names\nand <code>#include</code> the following C/C++ header file (primitive.h)\nwhich is intended to define the explicit primitive types with these names for any C/C++ compiler\n(this header file might not actually cover every compiler but it covers several compilers I have used on Windows, UNIX and Linux, it also doesn't (yet) define 64bit types).</p>\n\n<pre><code>#ifndef primitiveH\n#define primitiveH\n// Header file primitive.h\n// Primitive types\n// For C and/or C++\n// This header file is intended to define a set of primitive types\n// that will always be the same number bytes on any operating operating systems\n// and/or for several popular C/C++ compiler vendors.\n// Currently the type definitions cover:\n// Windows (16 or 32 bit)\n// Linux\n// UNIX (HP/US, Solaris)\n// And the following compiler vendors\n// Microsoft, Borland/Imprise/CodeGear, SunStudio, HP/UX\n// (maybe GNU C/C++)\n// This does not currently include 64bit primitives.\n#define float64 double\n#define float32 float\n// Some old C++ compilers didn't have bool type\n// If your compiler does not have bool then add emulate_bool\n// to your command line -D option or defined macros.\n#ifdef emulate_bool\n# ifdef TVISION\n# define bool int\n# define true 1\n# define false 0\n# else\n# ifdef __BCPLUSPLUS__\n //BC++ bool type not available until 5.0\n# define BI_NO_BOOL\n# include &lt;classlib/defs.h&gt;\n# else\n# define bool int\n# define true 1\n# define false 0\n# endif\n# endif\n#endif\n#ifdef __BCPLUSPLUS__\n# include &lt;systypes.h&gt;\n#else\n# ifdef unix\n# ifdef hpux\n# include &lt;sys/_inttypes.h&gt;\n# endif\n# ifdef sun\n# include &lt;sys/int_types.h&gt;\n# endif\n# ifdef linux\n# include &lt;idna.h&gt;\n# endif\n# define int8 int8_t\n# define uint8 uint8_t\n# define int16 int16_t\n# define int32 int32_t\n# define uint16 uint16_t\n# define uint32 uint32_t\n# else\n# ifdef _MSC_VER\n# include &lt;BaseTSD.h&gt;\n# define int8 INT8\n# define uint8 UINT8\n# define int16 INT16\n# define int32 INT32\n# define uint16 UINT16\n# define uint32 UINT32\n# else\n# ifndef OWL6\n// OWL version 6 already defines these types\n# define int8 char\n# define uint8 unsigned char\n# ifdef __WIN32_\n# define int16 short int\n# define int32 long\n# define uint16 unsigned short int\n# define uint32 unsigned long\n# else\n# define int16 int\n# define int32 long\n# define uint16 unsigned int\n# define uint32 unsigned long\n# endif\n# endif\n# endif\n# endif\n#endif\ntypedef int8 sint8;\ntypedef int16 sint16;\ntypedef int32 sint32;\ntypedef uint8 nat8;\ntypedef uint16 nat16;\ntypedef uint32 nat32;\ntypedef const char * cASCIIz; // constant null terminated char array\ntypedef char * ASCIIz; // null terminated char array\n#endif\n//primitive.h\n</code></pre>\n" }, { "answer_id": 3618662, "author": "Jérôme Radix", "author_id": 3673, "author_profile": "https://Stackoverflow.com/users/3673", "pm_score": 3, "selected": false, "text": "<p>The <a href=\"http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2005/n1905.pdf\" rel=\"noreferrer\">C++ Standard</a> says it like this :</p>\n\n<p>3.9.1, §2 :</p>\n\n<blockquote>\n <p>There are five signed integer types :\n \"signed char\", \"short int\", \"int\",\n \"long int\", and \"long long int\". In\n this list, each type provides at least\n as much storage as those preceding it\n in the list. Plain ints have the\n natural size suggested by the\n architecture of the execution\n environment (44); the other signed\n integer types are provided to meet\n special needs.</p>\n \n <p>(44) that is, <b>large enough to contain\n any value in the range of INT_MIN and\n INT_MAX, as defined in the header\n <code>&lt;climits&gt;</code></b>.</p>\n</blockquote>\n\n<p>The conclusion : it depends on which architecture you're working on. Any other assumption is false.</p>\n" } ]
2008/11/07
[ "https://Stackoverflow.com/questions/271076", "https://Stackoverflow.com", "https://Stackoverflow.com/users/25632/" ]
Correct me if I am wrong, int is 4 bytes, with a range of values from -2,147,483,648 to 2,147,483,647 (2^31) long is 4 bytes, with a range of values from -2,147,483,648 to 2,147,483,647 (2^31) What is the difference in C++? Can they be used interchangeably?
It is implementation dependent. For example, under Windows they are the same, but for example on Alpha systems a long was 64 bits whereas an int was 32 bits. This [article](http://software.intel.com/en-us/articles/size-of-long-integer-type-on-different-architecture-and-os) covers the rules for the Intel C++ compiler on variable platforms. To summarize: ``` OS arch size Windows IA-32 4 bytes Windows Intel 64 4 bytes Windows IA-64 4 bytes Linux IA-32 4 bytes Linux Intel 64 8 bytes Linux IA-64 8 bytes Mac OS X IA-32 4 bytes Mac OS X Intel 64 8 bytes ```
271,077
<p>In my views.py, I'm building a list of two-tuples, where the second item in the tuple is another list, like this:</p> <pre><code>[ Product_Type_1, [ product_1, product_2 ], Product_Type_2, [ product_3, product_4 ]] </code></pre> <p>In plain old Python, I could iteration the list like this:</p> <pre><code>for product_type, products in list: print product_type for product in products: print product </code></pre> <p>I can't seem to do the same thing in my Django template:</p> <pre><code>{% for product_type, products in product_list %} print product_type {% for product in products %} print product {% endfor %} {% endfor %} </code></pre> <p>I get this error from Django:</p> <p><strong>Caught an exception while rendering: zip argument #2 must support iteration</strong></p> <p>Of course, there is some HTML markup in the template, not print statements. Is tuple unpacking not supported in the Django template language? Or am I going about this the wrong way? All I am trying to do is display a simple hierarchy of objects - there are several product types, each with several products (in models.py, Product has a foreign key to Product_type, a simple one-to-many relationship).</p> <p>Obviously, I am quite new to Django, so any input would be appreciated.</p>
[ { "answer_id": 271098, "author": "Harley Holcombe", "author_id": 1057, "author_profile": "https://Stackoverflow.com/users/1057", "pm_score": 2, "selected": false, "text": "<p>Just send the template a list of product types and do something like:</p>\n\n<pre><code>{% for product_type in product_type_list %}\n {{ product_type }}\n {% for product in product_type.products.all %}\n {{ product }}\n {% endfor %}\n{% endfor %}\n</code></pre>\n\n<p>It's been a little while so I can't remember exactly what the syntax is, let me know if that works. Check the <a href=\"http://docs.djangoproject.com/en/dev/topics/db/queries/#related-objects\" rel=\"nofollow noreferrer\">documentation</a>.</p>\n" }, { "answer_id": 271128, "author": "Jake", "author_id": 24730, "author_profile": "https://Stackoverflow.com/users/24730", "pm_score": 7, "selected": true, "text": "<p>it would be best if you construct your data like {note the '(' and ')' can be exchanged for '[' and ']' repectively, one being for tuples, one for lists}</p>\n\n<pre><code>[ (Product_Type_1, ( product_1, product_2 )),\n (Product_Type_2, ( product_3, product_4 )) ]\n</code></pre>\n\n<p>and have the template do this:</p>\n\n<pre><code>{% for product_type, products in product_type_list %}\n {{ product_type }}\n {% for product in products %}\n {{ product }}\n {% endfor %}\n{% endfor %}\n</code></pre>\n\n<p>the way tuples/lists are unpacked in for loops is based on the item returned by the list iterator.\neach iteration only one item was returned. the first time around the loop, Product_Type_1, the second your list of products... </p>\n" }, { "answer_id": 1168438, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 3, "selected": false, "text": "<p>You must used this way:</p>\n<pre><code>{% for product_type, products in product_list.items %}\n {{ product_type }}\n {% for product in products %}\n {{ product }}\n {% endfor %}\n{% endfor %}\n</code></pre>\n<p>Don't forget the variable items in the dictionary data</p>\n" }, { "answer_id": 4756748, "author": "Ashwin Rao", "author_id": 584161, "author_profile": "https://Stackoverflow.com/users/584161", "pm_score": 7, "selected": false, "text": "<p>Another way is as follows. </p>\n\n<p>If one has a list of tuples say:</p>\n\n<pre><code>mylst = [(a, b, c), (x, y, z), (l, m, n)]\n</code></pre>\n\n<p>then one can unpack this list in the template file in the following manner.\nIn my case I had a list of tuples which contained the URL, title, and summary of a document.</p>\n\n<pre><code>{% for item in mylst %} \n {{ item.0 }} {{ item.1}} {{ item.2 }} \n{% endfor %}\n</code></pre>\n" }, { "answer_id": 35512819, "author": "famousfilm", "author_id": 5911260, "author_profile": "https://Stackoverflow.com/users/5911260", "pm_score": 2, "selected": false, "text": "<p>If you have a fixed number in your tuples, you could just use indexing. I needed to mix a dictionary and the values were tuples, so I did this:</p>\n\n<p>In the view:</p>\n\n<pre><code>my_dict = {'parrot': ('dead', 'stone'), 'lumberjack': ('sleep_all_night', 'work_all_day')}\n</code></pre>\n\n<p>In the template:</p>\n\n<pre><code>&lt;select&gt;\n {% for key, tuple in my_dict.items %}\n &lt;option value=\"{{ key }}\" important-attr=\"{{ tuple.0 }}\"&gt;{{ tuple.1 }}&lt;/option&gt;\n {% endfor %}\n&lt;/select&gt;\n</code></pre>\n" } ]
2008/11/07
[ "https://Stackoverflow.com/questions/271077", "https://Stackoverflow.com", "https://Stackoverflow.com/users/21245/" ]
In my views.py, I'm building a list of two-tuples, where the second item in the tuple is another list, like this: ``` [ Product_Type_1, [ product_1, product_2 ], Product_Type_2, [ product_3, product_4 ]] ``` In plain old Python, I could iteration the list like this: ``` for product_type, products in list: print product_type for product in products: print product ``` I can't seem to do the same thing in my Django template: ``` {% for product_type, products in product_list %} print product_type {% for product in products %} print product {% endfor %} {% endfor %} ``` I get this error from Django: **Caught an exception while rendering: zip argument #2 must support iteration** Of course, there is some HTML markup in the template, not print statements. Is tuple unpacking not supported in the Django template language? Or am I going about this the wrong way? All I am trying to do is display a simple hierarchy of objects - there are several product types, each with several products (in models.py, Product has a foreign key to Product\_type, a simple one-to-many relationship). Obviously, I am quite new to Django, so any input would be appreciated.
it would be best if you construct your data like {note the '(' and ')' can be exchanged for '[' and ']' repectively, one being for tuples, one for lists} ``` [ (Product_Type_1, ( product_1, product_2 )), (Product_Type_2, ( product_3, product_4 )) ] ``` and have the template do this: ``` {% for product_type, products in product_type_list %} {{ product_type }} {% for product in products %} {{ product }} {% endfor %} {% endfor %} ``` the way tuples/lists are unpacked in for loops is based on the item returned by the list iterator. each iteration only one item was returned. the first time around the loop, Product\_Type\_1, the second your list of products...
271,090
<p>Is there a way to pass a password to ssh automatically. I would like to automatically ssh to a server <b>without</b> using public key authentication or expect scripts, by somehow getting ssh to read the password from stdin or a file.</p> <p>The reason it has to be that way is that I would like to backup my files to a server using rsync/ssh running as a cron job. This server mounts my home directory <i>after</i> it authenticates me, so using public key authentication does not work since ~/.ssh isn't available until after the login is successful. expect(1) is out of the question because I would like to run it as a cron job, and since cron jobs don't run under a terminal the combination of expect/ssh just doesn't work. I do not have root access to that server, and it would be difficult to get the admins to make any changes to the way things work there.</p>
[ { "answer_id": 271100, "author": "vfilby", "author_id": 24279, "author_profile": "https://Stackoverflow.com/users/24279", "pm_score": 1, "selected": false, "text": "<p>Rather than passing your password use a public/private key system. Add the public key for a machine to the authorized keys list on all the machines you want to connect to. Using this method SSH can validate the keys automatically and no password is required.</p>\n\n<p>You can find instructions here: <a href=\"http://linuxproblem.org/art_9.html\" rel=\"nofollow noreferrer\">http://linuxproblem.org/art_9.html</a></p>\n\n<p>Since I just read the question more carefully, you might want to look around for a different SSH client that supports password authentication without user interaction. I quick google search hinted that they exist (<a href=\"http://www.derkeiler.com/Newsgroups/comp.security.ssh/2004-12/0134.html\" rel=\"nofollow noreferrer\">http://www.derkeiler.com/Newsgroups/comp.security.ssh/2004-12/0134.html</a>)</p>\n\n<p><em>Related Stackoverflow questions:</em></p>\n\n<ul>\n<li><a href=\"https://stackoverflow.com/questions/7260/how-do-i-setup-public-key-authentication\">How do I setup Public-Key Authentication?</a></li>\n<li><a href=\"https://stackoverflow.com/questions/224712/provide-password-using-shell-script\">Provide password using Shell script</a></li>\n<li><a href=\"https://stackoverflow.com/questions/243750/how-can-i-automate-running-commands-remotely-over-ssh\">How can I automate running commands remotely over SSH?</a></li>\n</ul>\n" }, { "answer_id": 271112, "author": "Harley Holcombe", "author_id": 1057, "author_profile": "https://Stackoverflow.com/users/1057", "pm_score": -1, "selected": false, "text": "<p>You have misunderstood how public key authentication works. You don't need access to your remote home directory, simply put the local public key in the remote <code>authorized_keys</code> file. Have a google around, there's plenty of guides.</p>\n" }, { "answer_id": 271354, "author": "Joseph", "author_id": 2209, "author_profile": "https://Stackoverflow.com/users/2209", "pm_score": 0, "selected": false, "text": "<p>This discussion talks about what you are trying to do:</p>\n\n<p><a href=\"http://cygwin.com/ml/cygwin/2004-02/msg01449.html\" rel=\"nofollow noreferrer\">http://cygwin.com/ml/cygwin/2004-02/msg01449.html</a></p>\n\n<p>If you can't have the admin create a local directory for you, then this won't work.</p>\n" }, { "answer_id": 328263, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 0, "selected": false, "text": "<p>SSH requires a \"leap of faith\" to secure the initial handshake against future tampering. (You initially trust the key the server gives you)</p>\n\n<p>One currently avaliable but not well known approach is to use SSH-SRP. This uses mutual password knowledge to both authenticate you and provide session encryption keys necessary to securely encrypt your ssh session.</p>\n\n<p>Its MUCH more secure than SSH's initial \"trust me\" and does not require long term storage of keys.</p>\n" }, { "answer_id": 363519, "author": "Jay", "author_id": 20840, "author_profile": "https://Stackoverflow.com/users/20840", "pm_score": 3, "selected": false, "text": "<blockquote>\n <p>expect is out of the question because I would like to run it as a cron job,\n and since cron jobs don't run under a terminal the combination of expect/ssh\n just doesn't work</p>\n</blockquote>\n\n<p>You can run expect scripts from cron, at least you can with expect libraries like \"pexpect\" for Python. I just tested this to confirm, running a pexpect scp/ssh script from cron and I was able to successfully scp a file from a Python script running in cron. </p>\n\n<p>Example code: </p>\n\n<pre><code>#!/usr/bin/python\n\nimport pexpect\n\nFILE=\"/path/to/file\"\nREMOTE_FILE=\"\"\nUSER=\"user\"\nHOST=\"example.com\"\nPASS=\"mypass\"\nCOMMAND=\"scp -oPubKeyAuthentication=no %s %s@%s:%s\" % (FILE, USER, HOST, REMOTE_FILE)\n\nchild = pexpect.spawn(COMMAND)\nchild.expect('password:')\nchild.sendline(PASS)\nchild.expect(pexpect.EOF)\nprint child.before\n</code></pre>\n" }, { "answer_id": 1121479, "author": "slinkp", "author_id": 137635, "author_profile": "https://Stackoverflow.com/users/137635", "pm_score": -1, "selected": false, "text": "<p>Don't use expect, pexpect or the like to feed in a password. If you do that, your password has to be somewhere in plaintext, which can actually be <i>less</i> secure than using a passwordless public/private key pair. And it's more work!</p>\n\n<p>Read this page from \"SSH: The Definitive Guide\" for a discussion of your options:\n<a href=\"http://www.snailbook.com/faq/no-passphrase.auto.html\" rel=\"nofollow noreferrer\">http://www.snailbook.com/faq/no-passphrase.auto.html</a></p>\n" }, { "answer_id": 20748503, "author": "uvsmtid", "author_id": 441652, "author_profile": "https://Stackoverflow.com/users/441652", "pm_score": 3, "selected": true, "text": "<p>Use <code>sshpass</code>.</p>\n\n<p>For example, when password is in <code>password.txt</code> file:</p>\n\n<pre><code>sshpass -fpassword.txt ssh username@hostname\n</code></pre>\n\n<p>(taken from the answer to a <a href=\"https://stackoverflow.com/q/13298487/441652\">similar question</a>)</p>\n" } ]
2008/11/07
[ "https://Stackoverflow.com/questions/271090", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11688/" ]
Is there a way to pass a password to ssh automatically. I would like to automatically ssh to a server **without** using public key authentication or expect scripts, by somehow getting ssh to read the password from stdin or a file. The reason it has to be that way is that I would like to backup my files to a server using rsync/ssh running as a cron job. This server mounts my home directory *after* it authenticates me, so using public key authentication does not work since ~/.ssh isn't available until after the login is successful. expect(1) is out of the question because I would like to run it as a cron job, and since cron jobs don't run under a terminal the combination of expect/ssh just doesn't work. I do not have root access to that server, and it would be difficult to get the admins to make any changes to the way things work there.
Use `sshpass`. For example, when password is in `password.txt` file: ``` sshpass -fpassword.txt ssh username@hostname ``` (taken from the answer to a [similar question](https://stackoverflow.com/q/13298487/441652))
271,106
<p>I am trying to get this program to give me an out put that when I do an addition, subtraction, multiplication, or division problem it will give me the answer. However, it is not working can anyone help.</p> <pre><code>int main () { int choice; float a, b; float sum; float difference; float product; float quotiont; printf("This program adds, subtracts, multiplies, and divides.\n"); printf("**************\n"); printf("* Calculator *\n"); printf("**************\n"); printf("Enter an expression: "); scanf("%f %f", &amp;a, &amp;b); scanf("%f %f %f %f", &amp;sum, &amp;difference, &amp;product, &amp;quotiont); sum = a + b; difference = a - b; product = a * b; quotiont = a / b; if(a + b) printf("Answer = %f\n", &amp;sum); else if(a - b) printf("Answer = %f\n", &amp;difference); else if(a * b) printf("Answer = %f\n", &amp;product); else if(a / b) printf("Answer = %f\n", &amp;quotiont); else printf("Error"); } </code></pre>
[ { "answer_id": 271119, "author": "bog", "author_id": 20909, "author_profile": "https://Stackoverflow.com/users/20909", "pm_score": 1, "selected": false, "text": "<p>You've misspelled quotient.</p>\n\n<p>Actually, don't pass the address of your args to printf. You only need to do that for scanf. Do, e.g., printf(\"Answer = %f\\n\", quotient);</p>\n\n<p>Uh, and that whole if...else if... thing at the end is just wonky. Take it out.</p>\n\n<p>And why are you scanfing for the results of your calculations? Take that out too.</p>\n" }, { "answer_id": 271146, "author": "Paige Ruten", "author_id": 813, "author_profile": "https://Stackoverflow.com/users/813", "pm_score": 4, "selected": false, "text": "<p>What are you trying to accomplish with this line?</p>\n\n<pre><code>scanf(\"%f %f %f %f\", &amp;sum, &amp;difference, &amp;product, &amp;quotiont); \n</code></pre>\n\n<p>What this does is takes four numbers from the user and loads them into the four variables, respectively. Right after this line you assign new values to these four variables, so there is no point in loading them with values in this line of code.</p>\n\n<p>Also, what is the point of the following <code>if</code> statement? (And all of the <code>else if</code> statements)</p>\n\n<pre><code>if(a + b)\n printf(\"Answer = %f\\n\", &amp;sum);\n</code></pre>\n\n<p>This will only print the answer if the sum of <code>a</code> and <code>b</code> is non-zero. If the expression inside the brackets after the 'if' evaluates to zero, it will not execute the code underneath. If it evaluates to a non-zero value, it will execute the code.</p>\n\n<p>Another problem with the above line is that you are passing a pointer to the <code>sum</code> variable to the printf() function instead of the actual value of the <code>sum</code> variable. '&amp;sum' returns the memory address of the variable, but 'sum' returns the actual value of the variable. So it should look like this:</p>\n\n<pre><code>printf(\"Answer = %f\\n\", sum);\n</code></pre>\n\n<hr />\n\n<p>I noticed that you defined a <code>choice</code> variable at the top of your program, but never used it. Because of that and your chain of <code>else if</code> statements, I'm assuming you want to give the user a choice of whether to add, subtract, multiply, or divide.</p>\n\n<p>To do this, I would define <code>choice</code> as a char (character) instead of an int, and would get the user to type in one of these four characters to be assigned to the <code>choice</code> variable: '<code>+</code>', '<code>-</code>', '<code>*</code>', or '<code>/</code>'.</p>\n\n<p>To define <code>choice</code> as a char, write this:</p>\n\n<pre><code>char choice;\n</code></pre>\n\n<p>Then get the user to input a choice like this:</p>\n\n<pre><code>scanf(\"%c\", &amp;choice);\n</code></pre>\n\n<p>This takes a single character from the user and assigns it to <code>choice</code>.</p>\n\n<p>Finally, change your <code>if</code> statements to something like this:</p>\n\n<pre><code>if (choice == '+')\n printf(\"Answer = %f\\n\", sum);\nelse if (choice == '-')\n printf(\"Answer = %f\\n\", difference);\nelse\n printf(\"Error: invalid choice.\\n\");\n</code></pre>\n\n<p>You may also want to use a <code>switch</code> statement for this.</p>\n" }, { "answer_id": 17675089, "author": "zuber mirza", "author_id": 2587075, "author_profile": "https://Stackoverflow.com/users/2587075", "pm_score": -1, "selected": false, "text": "<pre><code>#include&lt;stdio.h&gt;\n#include&lt;conio.h&gt;\n\n\nint main ()\n{ \n int choice; \n float a, b; \n float sum; \n float difference;\n float product;\n float quotiont;\n\n printf(\"This program adds, subtracts, multiplies, and divides.\\n\"); \n printf(\"**************\\n\"); \n printf(\"* Calculator *\\n\"); \n printf(\"**************\\n\"); \n printf(\"Enter thee value of a: \"); \n scanf(\"%f\",&amp;a);\n printf(\"Enter the value of y:\");\n scanf(\"%f\",&amp;b);\n sum=a+b;\n if (sum = a + b); \n printf(\"sum is %f\",sum);\n\n difference = a - b; \n if(difference=a-b)\n printf(\"\\n difference is %f\",difference);\n\n product = a * b; \n if(product=a*b)\n printf(\"\\n product is %f\",product);\n\n quotient = a / b; \n if(quotient=a/b)\n printf(\"\\n quotient is %f\",quotient);\n\n return(main());\n}\n</code></pre>\n" } ]
2008/11/07
[ "https://Stackoverflow.com/questions/271106", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
I am trying to get this program to give me an out put that when I do an addition, subtraction, multiplication, or division problem it will give me the answer. However, it is not working can anyone help. ``` int main () { int choice; float a, b; float sum; float difference; float product; float quotiont; printf("This program adds, subtracts, multiplies, and divides.\n"); printf("**************\n"); printf("* Calculator *\n"); printf("**************\n"); printf("Enter an expression: "); scanf("%f %f", &a, &b); scanf("%f %f %f %f", &sum, &difference, &product, &quotiont); sum = a + b; difference = a - b; product = a * b; quotiont = a / b; if(a + b) printf("Answer = %f\n", &sum); else if(a - b) printf("Answer = %f\n", &difference); else if(a * b) printf("Answer = %f\n", &product); else if(a / b) printf("Answer = %f\n", &quotiont); else printf("Error"); } ```
What are you trying to accomplish with this line? ``` scanf("%f %f %f %f", &sum, &difference, &product, &quotiont); ``` What this does is takes four numbers from the user and loads them into the four variables, respectively. Right after this line you assign new values to these four variables, so there is no point in loading them with values in this line of code. Also, what is the point of the following `if` statement? (And all of the `else if` statements) ``` if(a + b) printf("Answer = %f\n", &sum); ``` This will only print the answer if the sum of `a` and `b` is non-zero. If the expression inside the brackets after the 'if' evaluates to zero, it will not execute the code underneath. If it evaluates to a non-zero value, it will execute the code. Another problem with the above line is that you are passing a pointer to the `sum` variable to the printf() function instead of the actual value of the `sum` variable. '&sum' returns the memory address of the variable, but 'sum' returns the actual value of the variable. So it should look like this: ``` printf("Answer = %f\n", sum); ``` --- I noticed that you defined a `choice` variable at the top of your program, but never used it. Because of that and your chain of `else if` statements, I'm assuming you want to give the user a choice of whether to add, subtract, multiply, or divide. To do this, I would define `choice` as a char (character) instead of an int, and would get the user to type in one of these four characters to be assigned to the `choice` variable: '`+`', '`-`', '`*`', or '`/`'. To define `choice` as a char, write this: ``` char choice; ``` Then get the user to input a choice like this: ``` scanf("%c", &choice); ``` This takes a single character from the user and assigns it to `choice`. Finally, change your `if` statements to something like this: ``` if (choice == '+') printf("Answer = %f\n", sum); else if (choice == '-') printf("Answer = %f\n", difference); else printf("Error: invalid choice.\n"); ``` You may also want to use a `switch` statement for this.
271,109
<p>I have a simple question. Is there a way ( using reflections I suppose ) to iterate all the static values of a class?</p> <p>For instance </p> <pre><code>class Any { static int one = 1; static int two = 2; static int three = 3; public static void main( String [] args ) { for( int i : magicMethod( Any.class ) ){ System.out.println( i ); } } } </code></pre> <p>Output</p> <pre><code> 1 2 3 </code></pre> <p>Thanks.</p>
[ { "answer_id": 271127, "author": "OscarRyz", "author_id": 20654, "author_profile": "https://Stackoverflow.com/users/20654", "pm_score": 2, "selected": false, "text": "<p>Hey.. it was very easy. :P </p>\n\n<pre><code> Field [] constants = Main.class.getFields();\n Object some = new Main();\n for( Field field : constants ){\n if(Modifier.isStatic(field.getModifiers() ) &amp;&amp; \n field.getType() == int.class ) {\n System.out.println( field.getInt( some ) );\n }\n }\n</code></pre>\n" }, { "answer_id": 271134, "author": "Jason Coco", "author_id": 34218, "author_profile": "https://Stackoverflow.com/users/34218", "pm_score": 1, "selected": false, "text": "<p>You could do something like this:</p>\n\n<pre><code>import java.lang.reflect.*;\n\npublic class Foo {\n\npublic static int one = 1;\npublic static int two = 2;\npublic static int three = 3;\n\npublic static void magicMethod( Class clz ) throws Exception {\n Field[] fields = clz.getFields();\n System.out.println(\"\"+fields);\n for( Field field : fields ) {\n int modifiers = field.getModifiers();\n if( ! Modifier.isStatic(modifiers) )\n continue;\n System.out.println(\"\" + field.get(null));\n }\n}\n\npublic static void main(String[] args) throws Exception {\n Foo.magicMethod( Foo.class );\n}}\n</code></pre>\n\n<p>It's important to note, however, that the fields have to be public for this to work. It's not exactly what you asked, but it should be close enough that you should be able to make it work for what you need. Obviously this doesn't do any kind of error handling or anything so you should make sure that you handle any errors or exceptions in your real application.</p>\n" }, { "answer_id": 271135, "author": "Robert Gamble", "author_id": 25222, "author_profile": "https://Stackoverflow.com/users/25222", "pm_score": 2, "selected": false, "text": "<p>Your solution works for public fields but not private fields like you have in your example. If you want to be able to access the private fields of a class you need to use getDeclaredFields() instead of getFields().</p>\n" }, { "answer_id": 271156, "author": "Skip Head", "author_id": 23271, "author_profile": "https://Stackoverflow.com/users/23271", "pm_score": 5, "selected": true, "text": "<pre><code>import java.util.*;\nimport java.lang.reflect.*;\n\nclass Any {\n static int one = 1;\n static int two = 2;\n static int three = 3;\n\n public static void main( String [] args ) {\n for( int i : magicMethod( Any.class ) ){\n System.out.println( i );\n }\n }\n\n public static Integer[] magicMethod(Class&lt;Any&gt; c) {\n List&lt;Integer&gt; list = new ArrayList&lt;Integer&gt;();\n Field[] fields = c.getDeclaredFields();\n for (Field field : fields) {\n try {\n if (field.getType().equals(int.class) &amp;&amp; Modifier.isStatic(field.getModifiers())) {\n list.add(field.getInt(null));\n }\n }\n catch (IllegalAccessException e) {\n // Handle exception here\n }\n }\n return list.toArray(new Integer[list.size()]);\n }\n }\n</code></pre>\n" }, { "answer_id": 7992587, "author": "helpermethod", "author_id": 1178669, "author_profile": "https://Stackoverflow.com/users/1178669", "pm_score": 0, "selected": false, "text": "<p>As an alternative, use an enum and get rid of the class variables entirely (to be precise, the enum is a class variable as well :-)):</p>\n\n<pre><code>class Any {\n enum Number {\n ONE(1),\n TWO(2),\n THREE(3);\n\n Number(int number) {\n this.number = number;\n }\n\n int number;\n };\n\n public static void main(String [] args) {\n for (Number value : Number.values()) {\n System.out.println(value.number);\n }\n }\n}\n</code></pre>\n" } ]
2008/11/07
[ "https://Stackoverflow.com/questions/271109", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20654/" ]
I have a simple question. Is there a way ( using reflections I suppose ) to iterate all the static values of a class? For instance ``` class Any { static int one = 1; static int two = 2; static int three = 3; public static void main( String [] args ) { for( int i : magicMethod( Any.class ) ){ System.out.println( i ); } } } ``` Output ``` 1 2 3 ``` Thanks.
``` import java.util.*; import java.lang.reflect.*; class Any { static int one = 1; static int two = 2; static int three = 3; public static void main( String [] args ) { for( int i : magicMethod( Any.class ) ){ System.out.println( i ); } } public static Integer[] magicMethod(Class<Any> c) { List<Integer> list = new ArrayList<Integer>(); Field[] fields = c.getDeclaredFields(); for (Field field : fields) { try { if (field.getType().equals(int.class) && Modifier.isStatic(field.getModifiers())) { list.add(field.getInt(null)); } } catch (IllegalAccessException e) { // Handle exception here } } return list.toArray(new Integer[list.size()]); } } ```
271,145
<p>Given a UTC time string like this:</p> <pre><code>2005-11-01T00:00:00-04:00 </code></pre> <p>What is the best way to convert it to a DateTime using a Crystal Reports formula?</p> <p>My best solution is posted below.</p> <p>I hope someone out there can blow me away with a one-liner...</p>
[ { "answer_id": 271147, "author": "JosephStyons", "author_id": 672, "author_profile": "https://Stackoverflow.com/users/672", "pm_score": 1, "selected": false, "text": "<p>Here is my best solution, with comments:</p>\n\n<pre><code>//assume a date stored as a string in this format:\n//2005-11-01T00:00:00-04:00\n//return a DateTime value\nStringVar fieldValue;\nStringVar datePortion;\nStringVar timePortion;\nNumberVar yearPortion;\nNumberVar monthPortion;\nNumberVar dayPortion;\nNumberVar hourPortion;\nNumberVar minutePortion;\nNumberVar secondPortion;\n\n//store the field locally so i can easily copy-paste into another formula\n//(where the field name will be different)\n//Crystal formulas do not use a powerful language.\nfieldValue := {PACT.ReferralDate};\n\n//break up the date &amp; time parts.\n//ignore the -04:00 offset part of the time.\ndatePortion := Split (fieldValue,\"T\")[1];\ntimePortion := Split(Split (fieldValue,\"T\")[2],\"-\")[1];\n\nyearPortion := ToNumber(Split(datePortion,\"-\")[1]);\nmonthPortion := ToNumber(Split(datePortion,\"-\")[2]);\ndayPortion := ToNumber(Split(datePortion,\"-\")[3]);\n\nhourPortion := ToNumber(Split(timePortion,\":\")[1]);\nminutePortion := ToNumber(Split(timePortion,\":\")[2]);\nsecondPortion := ToNumber(Split(timePortion,\":\")[3]);\n\n//finally, return the result as a date-time\nDateTime(yearPortion,monthPortion,dayPortion,hourPortion,minutePortion,secondPortion);\n</code></pre>\n" }, { "answer_id": 271167, "author": "jons911", "author_id": 34375, "author_profile": "https://Stackoverflow.com/users/34375", "pm_score": 3, "selected": true, "text": "<p>Here you go:</p>\n\n<pre><code>CDateTime(CDate(Split({?UTCDateString}, \"T\")[1]) , CTime(Split(Split({?UTCDateString}, \"T\")[2], \"-\")[1]))\n</code></pre>\n" }, { "answer_id": 288744, "author": "Anthony K", "author_id": 1682, "author_profile": "https://Stackoverflow.com/users/1682", "pm_score": 2, "selected": false, "text": "<p>May I suggest a simplification to jons911's answer: </p>\n\n<pre><code>CDateTime(CDate(Left({@UTCString}, 10)), CTime(Mid({@UTCString}, 12, 8))); \n</code></pre>\n\n<p>This has the advantage that the formula works for time zones forward of UTC 0 (e.g. +01:00). It does of course rely on the UTC string being a properly formatted ISO 8601 string.</p>\n" }, { "answer_id": 869505, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 0, "selected": false, "text": "<pre><code>StringVar fieldValue;\nStringVar datePortion;\nStringVar timePortion;\nNumberVar yearPortion;\nNumberVar monthPortion;\nNumberVar dayPortion;\nNumberVar hourPortion;\nNumberVar minutePortion;\nNumberVar secondPortion;\ndatetimevar dtlimite;\n\nfieldValue := {dtsecretaria.Data_limite};\n\ndatePortion := Split (fieldValue,\"T\")[1];\ntimePortion := Split(Split (fieldValue,\"T\")[2],\"-\")[1];\n\nyearPortion := ToNumber(Split(datePortion,\"-\")[1]);\nmonthPortion := ToNumber(Split(datePortion,\"-\")[2]);\ndayPortion := ToNumber(Split(datePortion,\"-\")[3]);\n\nhourPortion := ToNumber(Split(timePortion,\":\")[1]);\nminutePortion := ToNumber(Split(timePortion,\":\")[2]);\nsecondPortion := ToNumber(Split(timePortion,\":\")[3]);\n\ndtlimite := DateTime(yearPortion,monthPortion,dayPortion,hourPortion,minutePortion,secondPortion);\n\n\nif dtlimite &gt; CurrentDateTime then\n\nColor(255,0,0)\n\nelse\n\nColor(255,255,0)\n\n\n\nerror of nError in formula &lt;Back_Color&gt;. \\n'\\r'\\nA string is required here.\"\n</code></pre>\n" } ]
2008/11/07
[ "https://Stackoverflow.com/questions/271145", "https://Stackoverflow.com", "https://Stackoverflow.com/users/672/" ]
Given a UTC time string like this: ``` 2005-11-01T00:00:00-04:00 ``` What is the best way to convert it to a DateTime using a Crystal Reports formula? My best solution is posted below. I hope someone out there can blow me away with a one-liner...
Here you go: ``` CDateTime(CDate(Split({?UTCDateString}, "T")[1]) , CTime(Split(Split({?UTCDateString}, "T")[2], "-")[1])) ```
271,149
<p>how do i check if an item is selected or not in my listbox? so i have a button remove, but i only want that button to execute if an item is selected in the list box. im using asp.net code behind C#. I'd prefer if this validation occurred on the server side.</p> <p>cheers..</p>
[ { "answer_id": 271164, "author": "tvanfosson", "author_id": 12950, "author_profile": "https://Stackoverflow.com/users/12950", "pm_score": 1, "selected": false, "text": "<p>On the callback for the button click, just check if the selected index of the list box is greater than or equal to zero.</p>\n\n<pre><code>protected void removeButton_Click( object sender, EventArgs e )\n{\n if (listBox.SelectedIndex &gt;= 0)\n {\n listBox.Items.RemoveAt( listBox.SelectedIndex );\n }\n}\n</code></pre>\n" }, { "answer_id": 271189, "author": "jons911", "author_id": 34375, "author_profile": "https://Stackoverflow.com/users/34375", "pm_score": 1, "selected": false, "text": "<p>Actually, SelectedIndex is zero-based, so your check has to be:</p>\n\n<p>if (listBox.SelectedIndex >= 0)\n...</p>\n" }, { "answer_id": 271245, "author": "Gishu", "author_id": 1695, "author_profile": "https://Stackoverflow.com/users/1695", "pm_score": 0, "selected": false, "text": "<p>You may want to go with the early-break out approach based on your prob desc &amp; the fact that <strong>ListBox.SelectedIndex will return -1 if nothing is selected</strong>.</p>\n\n<p>so to borrow some of tvanfosson's button event handler code.</p>\n\n<pre><code>protected void removeButton_Click( object sender, EventArgs e )\n{\n if (listBox.SelectedIndex &lt; 0) { return; }\n // do whatever you wish to here to remove the list item \n}\n</code></pre>\n" }, { "answer_id": 271476, "author": "Adyt", "author_id": 23491, "author_profile": "https://Stackoverflow.com/users/23491", "pm_score": -1, "selected": true, "text": "<pre><code>for (int i = 0; i &lt; lbSrc.Items.Count; i++)\n{\n if (lbSrc.Items[i].Selected == true)\n {\n lbSrc.Items.RemoveAt(lbSrc.SelectedIndex);\n }\n}\n</code></pre>\n\n<p>this is what i came up with.</p>\n" }, { "answer_id": 271511, "author": "Joacim Andersson", "author_id": 25203, "author_profile": "https://Stackoverflow.com/users/25203", "pm_score": 0, "selected": false, "text": "<p>To remove an item from a collection you need to loop backwards.</p>\n\n<pre><code>for (int i=lbSrc.Items.Count - 1, i&gt;=0, i--)\n{\n //code to check the selected state and remove the item\n}\n</code></pre>\n" }, { "answer_id": 271513, "author": "Sani Singh Huttunen", "author_id": 26742, "author_profile": "https://Stackoverflow.com/users/26742", "pm_score": 1, "selected": false, "text": "<p>To remove multiple items you'll need to parse the items in reverse.</p>\n\n<pre><code>protected void removeButton_Click(object sender, EventArgs e)\n{\n for (int i = listBox.Items.Count - 1; i &gt;= 0; i--)\n listBox.Items.RemoveAt(i);\n}\n</code></pre>\n\n<p>If you parse as usual then the result will be quite unexpected.\nEx:\n If you remove item 0 then item 1 becomes the new item 0.\n If you now try to remove what you believe is item 1,\n you'll actually remove what you see as item 2.</p>\n" } ]
2008/11/07
[ "https://Stackoverflow.com/questions/271149", "https://Stackoverflow.com", "https://Stackoverflow.com/users/23491/" ]
how do i check if an item is selected or not in my listbox? so i have a button remove, but i only want that button to execute if an item is selected in the list box. im using asp.net code behind C#. I'd prefer if this validation occurred on the server side. cheers..
``` for (int i = 0; i < lbSrc.Items.Count; i++) { if (lbSrc.Items[i].Selected == true) { lbSrc.Items.RemoveAt(lbSrc.SelectedIndex); } } ``` this is what i came up with.
271,171
<p>This is a little confusing to explain, so bear with me here...</p> <p>I want to set up a system where a user can send templated emails via my website, except it's not actually sent using my server - it instead just opens up their own local mail client with an email ready to go. The application would fill out the body of the email with predefined variables, to save the user having to type it themselves. They can then edit the message as desired, should it not exactly suit their purposes.</p> <p>There's a number of reasons I want it to go via the user's local mail client, so getting the server to send the email is not an option: it has to be 100% client-side.</p> <p>I already have a mostly-working solution running, and I'll post the details of that as an answer, I'm wondering if there's any better way?</p>
[ { "answer_id": 271172, "author": "nickf", "author_id": 9021, "author_profile": "https://Stackoverflow.com/users/9021", "pm_score": 8, "selected": true, "text": "<p>The way I'm doing it now is basically like this:</p>\n<p>The HTML:</p>\n<pre><code>&lt;textarea id=&quot;myText&quot;&gt;\n Lorem ipsum...\n&lt;/textarea&gt;\n&lt;button onclick=&quot;sendMail(); return false&quot;&gt;Send&lt;/button&gt;\n</code></pre>\n<p>The Javascript:</p>\n<pre><code>function sendMail() {\n var link = &quot;mailto:[email protected]&quot;\n + &quot;[email protected]&quot;\n + &quot;&amp;subject=&quot; + encodeURIComponent(&quot;This is my subject&quot;)\n + &quot;&amp;body=&quot; + encodeURIComponent(document.getElementById('myText').value)\n ;\n \n window.location.href = link;\n}\n</code></pre>\n<p>This, surprisingly, works rather well. The only problem is that if the body is particularly long (somewhere over 2000 characters), then it just opens a new email but there's no information in it. I suspect that it'd be to do with the maximum length of the URL being exceeded.</p>\n" }, { "answer_id": 271179, "author": "tvanfosson", "author_id": 12950, "author_profile": "https://Stackoverflow.com/users/12950", "pm_score": 2, "selected": false, "text": "<p>If this is just going to open up the user's client to send the email, why not let them compose it there as well. You lose the ability to track what they are sending, but if that's not important, then just collect the addresses and subject and pop up the client to let the user fill in the body.</p>\n" }, { "answer_id": 271181, "author": "Ryan Doherty", "author_id": 956, "author_profile": "https://Stackoverflow.com/users/956", "pm_score": 4, "selected": false, "text": "<p>You don't need any javascript, you just need your href to be coded like this:</p>\n\n<pre><code>&lt;a href=\"mailto:[email protected]\"&gt;email me here!&lt;/a&gt;\n</code></pre>\n" }, { "answer_id": 271186, "author": "alex", "author_id": 31671, "author_profile": "https://Stackoverflow.com/users/31671", "pm_score": 3, "selected": false, "text": "<p>What about having a live validation on the textbox, and once it goes over 2000 (or whatever the maximum threshold is) then display 'This email is too long to be completed in the browser, please <code>&lt;span class=\"launchEmailClientLink\"&gt;launch what you have in your email client&lt;/span&gt;</code>'</p>\n\n<p>To which I'd have</p>\n\n<pre><code>.launchEmailClientLink {\ncursor: pointer;\ncolor: #00F;\n}\n</code></pre>\n\n<p>and jQuery this into your onDomReady</p>\n\n<pre><code>$('.launchEmailClientLink').bind('click',sendMail);\n</code></pre>\n" }, { "answer_id": 9366054, "author": "Reignier Julien", "author_id": 1221702, "author_profile": "https://Stackoverflow.com/users/1221702", "pm_score": 4, "selected": false, "text": "<p>Here's the way doing it using jQuery and an \"element\" to click on :</p>\n\n<pre><code>$('#element').click(function(){\n $(location).attr('href', 'mailto:?subject='\n + encodeURIComponent(\"This is my subject\")\n + \"&amp;body=\" \n + encodeURIComponent(\"This is my body\")\n );\n});\n</code></pre>\n\n<p>Then, you can get your contents either by feeding it from input fields (ie. using <code>$('#input1').val()</code> or by a server side script with <code>$.get('...')</code>. Have fun</p>\n" }, { "answer_id": 32722914, "author": "Fabrice NEYRET", "author_id": 5061163, "author_profile": "https://Stackoverflow.com/users/5061163", "pm_score": 2, "selected": false, "text": "<p>The problem with the very idea is that the user has to have an email client, which is not the case if he rely on webmails, which is the case for many users. (at least there was no turn-around to redirect to this webmail when I investigated the issue a dozen years ago).</p>\n\n<p>That's why the normal solution is to rely on php mail() for sending emails (server-side, then).</p>\n\n<p>But if nowadays \"email client\" is always set, automatically, potentially to a webmail client, I'll be happy to know.</p>\n" }, { "answer_id": 33041167, "author": "Vitaly Zdanevich", "author_id": 1879101, "author_profile": "https://Stackoverflow.com/users/1879101", "pm_score": 1, "selected": false, "text": "<p>Send request to <a href=\"http://mandrillapp.com\" rel=\"nofollow\">mandrillapp.com</a>:</p>\n\n<pre><code>var xhttp = new XMLHttpRequest();\nxhttp.onreadystatechange = function() {\n if (xhttp.readyState == 4 &amp;&amp; xhttp.status == 200) {\n console.log(xhttp.responseText);\n }\n}\nxhttp.open('GET', 'https://mandrillapp.com/api/1.0/messages/send.json?message[from_email][email protected]&amp;message[to][0][email][email protected]&amp;message[subject]=Заявка%20с%207995.by&amp;message[html]=xxxxxx&amp;key=oxddROOvCpKCp6InvVDqiGw', true);\nxhttp.send();\n</code></pre>\n" }, { "answer_id": 48368936, "author": "julianm", "author_id": 3530707, "author_profile": "https://Stackoverflow.com/users/3530707", "pm_score": 3, "selected": false, "text": "<p>You can use this free service: <a href=\"https://www.smtpjs.com\" rel=\"nofollow noreferrer\">https://www.smtpjs.com</a></p>\n\n<ol>\n<li>Include the script:</li>\n</ol>\n\n<p><code>&lt;script src=\"https://smtpjs.com/v2/smtp.js\"&gt;&lt;/script&gt;</code></p>\n\n<ol start=\"2\">\n<li>Send an email using: </li>\n</ol>\n\n<pre><code>Email.send(\n \"[email protected]\",\n \"[email protected]\",\n \"This is a subject\",\n \"this is the body\",\n \"smtp.yourisp.com\",\n \"username\",\n \"password\"\n);\n</code></pre>\n" }, { "answer_id": 65701460, "author": "jvel07", "author_id": 3885769, "author_profile": "https://Stackoverflow.com/users/3885769", "pm_score": 1, "selected": false, "text": "<p>You can add the following to the <code>&lt;head&gt;</code> of your HTML file:</p>\n<pre><code>&lt;script src=&quot;https://smtpjs.com/v3/smtp.js&quot;&gt;&lt;/script&gt;\n\n&lt;script type=&quot;text/javascript&quot;&gt;\n function sendEmail() {\n Email.send({\n SecureToken: &quot;security token of your smtp&quot;,\n To: &quot;[email protected]&quot;,\n From: &quot;[email protected]&quot;,\n Subject: &quot;Subject...&quot;,\n Body: document.getElementById('text').value\n }).then( \n message =&gt; alert(&quot;mail sent successfully&quot;)\n );\n }\n&lt;/script&gt;\n</code></pre>\n<p>and below is the HMTL part:</p>\n<pre><code>&lt;textarea id=&quot;text&quot;&gt;write text here...&lt;/textarea&gt;\n&lt;input type=&quot;button&quot; value=&quot;Send Email&quot; onclick=&quot;sendEmail()&quot;&gt;\n</code></pre>\n<p>So the sendEmail() function gets the inputs using:</p>\n<blockquote>\n<p>document.getElementById('id_of_the_element').value</p>\n</blockquote>\n<p>For example, you can add another HTML element such as the subject (with id=&quot;subject&quot;):</p>\n<p><code> &lt;textarea id=&quot;subject&quot;&gt;write text here...&lt;/textarea&gt;</code></p>\n<p>and get its value in the sendEmail() function:</p>\n<blockquote>\n<p>Subject: document.getElementById('subject').value</p>\n</blockquote>\n<p>And you are done!</p>\n<p>Note: If you do not have a SMTP server you can create one for free <a href=\"https://elasticemail.com/account#/create-account?r=20b444a2-b3af-4eb8-bae7-911f6097521c\" rel=\"nofollow noreferrer\">here</a>. And then encrypt your SMTP credentials <a href=\"https://smtpjs.com/\" rel=\"nofollow noreferrer\">here</a> (the SecureToken attribute in sendEmail() corresponds to the encrypted credentials generated there).</p>\n" } ]
2008/11/07
[ "https://Stackoverflow.com/questions/271171", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9021/" ]
This is a little confusing to explain, so bear with me here... I want to set up a system where a user can send templated emails via my website, except it's not actually sent using my server - it instead just opens up their own local mail client with an email ready to go. The application would fill out the body of the email with predefined variables, to save the user having to type it themselves. They can then edit the message as desired, should it not exactly suit their purposes. There's a number of reasons I want it to go via the user's local mail client, so getting the server to send the email is not an option: it has to be 100% client-side. I already have a mostly-working solution running, and I'll post the details of that as an answer, I'm wondering if there's any better way?
The way I'm doing it now is basically like this: The HTML: ``` <textarea id="myText"> Lorem ipsum... </textarea> <button onclick="sendMail(); return false">Send</button> ``` The Javascript: ``` function sendMail() { var link = "mailto:[email protected]" + "[email protected]" + "&subject=" + encodeURIComponent("This is my subject") + "&body=" + encodeURIComponent(document.getElementById('myText').value) ; window.location.href = link; } ``` This, surprisingly, works rather well. The only problem is that if the body is particularly long (somewhere over 2000 characters), then it just opens a new email but there's no information in it. I suspect that it'd be to do with the maximum length of the URL being exceeded.
271,198
<p>One of the frequent causes of memory leaks in .Net are event handlers which are never removed from their source objects. </p> <p>Will this WCF code cause a memory leak, or will the lambda go out of scope too, allowing both the proxy class and the handler to be GCed?</p> <pre><code>void AMethod() { WCFClient proxy; proxy = new WCFClient(); proxy.RemoteOperationCompleted += (sender, e) =&gt; proxy.Close(); proxy.Open(); proxy.RemoteOperationAsync(); } </code></pre>
[ { "answer_id": 271232, "author": "Timothy Khouri", "author_id": 11917, "author_profile": "https://Stackoverflow.com/users/11917", "pm_score": -1, "selected": false, "text": "<p>That object will die... it'll be cleaned up.</p>\n\n<p>Don't forget that the lamda isn't doing anything special... it's a compiler trick (so just assume it's a normal += SomeDelegate).</p>\n\n<p>Also, the \"Close\" method (I don't know why they didn't make it IDisposable) will clean up everything else that was left open.</p>\n" }, { "answer_id": 271259, "author": "Brian Adams", "author_id": 32992, "author_profile": "https://Stackoverflow.com/users/32992", "pm_score": 1, "selected": false, "text": "<p>Don't forget that the proxy's don't correctly implement IDisposable. If an error occurs the code above will not clean up the connection and the handle will remain until the parent process is closed.</p>\n" }, { "answer_id": 271282, "author": "cfeduke", "author_id": 5645, "author_profile": "https://Stackoverflow.com/users/5645", "pm_score": 3, "selected": true, "text": "<p>Here's my test - note the explicit <code>proxy</code> set to <code>null</code> in the lambda - without it the <code>WeakReference</code> lives and therefore a leak is likely:</p>\n\n<pre><code>public class Proxy\n{\n private bool _isOpen;\n\n public event EventHandler Complete;\n\n public void Close() \n {\n _isOpen = false;\n }\n\n public void Open() \n { \n _isOpen = true; \n }\n\n public void RemoteOperationAsync()\n {\n if (!_isOpen)\n throw new ApplicationException();\n Thread.Sleep(1000);\n if (Complete != null)\n Complete(this, EventArgs.Empty);\n }\n}\n\npublic static class Program\n{\n public static void Main()\n {\n WeakReference wr = null;\n\n {\n var proxy = new Proxy();\n proxy.Complete += (sender, e) =&gt;\n {\n proxy.Close();\n wr = new WeakReference(proxy);\n proxy = null;\n };\n proxy.Open();\n proxy.RemoteOperationAsync();\n }\n\n GC.Collect(GC.GetGeneration(wr));\n GC.WaitForPendingFinalizers();\n\n Console.WriteLine(\"[LAMBDA] Is WeakReference alive? \" + wr.IsAlive);\n }\n}\n</code></pre>\n" }, { "answer_id": 7840331, "author": "Karel Frajták", "author_id": 325322, "author_profile": "https://Stackoverflow.com/users/325322", "pm_score": 0, "selected": false, "text": "<p>The context where the lamdba is defined will be captured and will therefore \"survive\" in the compiler created closure class (you can see them with Reflector) - so your proxy too. Use weak event handler or write code for unregistration. But in that case you can't use lambda expression.</p>\n" } ]
2008/11/07
[ "https://Stackoverflow.com/questions/271198", "https://Stackoverflow.com", "https://Stackoverflow.com/users/25201/" ]
One of the frequent causes of memory leaks in .Net are event handlers which are never removed from their source objects. Will this WCF code cause a memory leak, or will the lambda go out of scope too, allowing both the proxy class and the handler to be GCed? ``` void AMethod() { WCFClient proxy; proxy = new WCFClient(); proxy.RemoteOperationCompleted += (sender, e) => proxy.Close(); proxy.Open(); proxy.RemoteOperationAsync(); } ```
Here's my test - note the explicit `proxy` set to `null` in the lambda - without it the `WeakReference` lives and therefore a leak is likely: ``` public class Proxy { private bool _isOpen; public event EventHandler Complete; public void Close() { _isOpen = false; } public void Open() { _isOpen = true; } public void RemoteOperationAsync() { if (!_isOpen) throw new ApplicationException(); Thread.Sleep(1000); if (Complete != null) Complete(this, EventArgs.Empty); } } public static class Program { public static void Main() { WeakReference wr = null; { var proxy = new Proxy(); proxy.Complete += (sender, e) => { proxy.Close(); wr = new WeakReference(proxy); proxy = null; }; proxy.Open(); proxy.RemoteOperationAsync(); } GC.Collect(GC.GetGeneration(wr)); GC.WaitForPendingFinalizers(); Console.WriteLine("[LAMBDA] Is WeakReference alive? " + wr.IsAlive); } } ```
271,204
<p>This loop is slower than I would expect, and I'm not sure where yet. See anything?</p> <p>I'm reading an Accces DB, using client-side cursors. When I have 127,000 rows with 20 columns, this loop takes about 10 seconds. The 20 columns are string, int, and date types. All the types get converted to ANSI strings before they are put into the ostringstream buffer.</p> <pre><code>void LoadRecordsetIntoStream(_RecordsetPtr&amp; pRs, ostringstream&amp; ostrm) { ADODB::FieldsPtr pFields = pRs-&gt;Fields; char buf[80]; ::SYSTEMTIME sysTime; _variant_t var; while(!pRs-&gt;EndOfFile) // loop through rows { for (long i = 0L; i &lt; nColumns; i++) // loop through columns { var = pFields-&gt;GetItem(i)-&gt;GetValue(); if (V_VT(&amp;var) == VT_BSTR) { ostrm &lt;&lt; (const char*) (_bstr_t) var; } else if (V_VT(&amp;var) == VT_I4 || V_VT(&amp;var) == VT_UI1 || V_VT(&amp;var) == VT_I2 || V_VT(&amp;var) == VT_BOOL) { ostrm &lt;&lt; itoa(((int)var),buf,10); } else if (V_VT(&amp;var) == VT_DATE) { ::VariantTimeToSystemTime(var,&amp;sysTime); _stprintf(buf, _T("%4d-%02d-%02d %02d:%02d:%02d"), sysTime.wYear, sysTime.wMonth, sysTime.wDay, sysTime.wHour, sysTime.wMinute, sysTime.wSecond); ostrm &lt;&lt; buf; } } pRs-&gt;MoveNext(); } } </code></pre> <p>EDIT: After more experimentation...</p> <p>I know now that about half the time is used by this line:<br> var = pFields->GetItem(i)->GetValue();</p> <p>If I bypass the Microsoft generated COM wrappers, will my code be faster? My guess is no.</p> <p>The othe half of the time is spent in the statements which convert data and stream it into the ostringstream.</p> <p>I don't know right now as I write this whether it's the conversions or the streaming that is taking more time.</p> <p>Would it be faster if I didn't use ostringstream and instead managed my own buffer, with my own logic to grow the buffer (re-alloc, copy, delete)? Would it be faster if my logic made a pessimistic guesstimate and reserved a lot of space for the ostringstream buffer up front? These might be experiments worth trying.</p> <p>Finally, the conversions themselves. None of the three stand out in my timings as being bad. One answer says that my itoa might be slower than an alternative. Worth checking out.</p>
[ { "answer_id": 271230, "author": "CVertex", "author_id": 209, "author_profile": "https://Stackoverflow.com/users/209", "pm_score": 2, "selected": false, "text": "<p>I can't tell from looking at your code, someone more familiar with COM/ATL may have a better answer.</p>\n\n<p>By trial n error I would find the slow code by commenting out inner loop operations out until you see perf spike, then you have your culprit and should focus on that.</p>\n" }, { "answer_id": 271234, "author": "Kevin Haines", "author_id": 10410, "author_profile": "https://Stackoverflow.com/users/10410", "pm_score": 2, "selected": false, "text": "<p>I assume V_VT is a function - if so, then for each date value, V_VT(&amp;var) is called 6 times. A simple optimisation is to locally store the value of V_VT(&amp;var) to save up to save up to 5 calls to this function each time around the loop.</p>\n\n<p>If you haven't already done so, re-order the if tests for the types to put the most common column types first - this reduces the number of tests required.</p>\n" }, { "answer_id": 271246, "author": "dkretz", "author_id": 31641, "author_profile": "https://Stackoverflow.com/users/31641", "pm_score": 1, "selected": false, "text": "<p>A good part of it is that Access is not a server database - all the file reads/writes, locking, cursor handling, etc. is taking place within the client application (across a network, right?) And needs to be so, if other users have the database open at the same time.</p>\n\n<p>If not, you probably would be able to drop the cursor settings, and open the database read-only.</p>\n" }, { "answer_id": 271430, "author": "Andreas Magnusson", "author_id": 5811, "author_profile": "https://Stackoverflow.com/users/5811", "pm_score": 0, "selected": false, "text": "<p>Try profiling. If you don't have a profiler a simple way could be to wrap all calls in your loop you think may take some time with something like the following:</p>\n\n<pre><code>#define TIME_CALL(x) \\\ndo { \\\n const DWORD t1 = timeGetTime();\\\n x;\\\n const DWORD t2 = timeGetTime();\\\n std::cout &lt;&lt; \"Call to '\" &lt;&lt; #x &lt;&lt; \"' took \" &lt;&lt; (t2 - t1) &lt;&lt; \" ms.\\n\";\\\n}while(false)\n</code></pre>\n\n<p>So now you can say:</p>\n\n<pre><code>TIME_CALL(var = pFields-&gt;GetItem(i)-&gt;GetValue());\nTIME_CALL(ostrm &lt;&lt; (const char*) (_bstr_t) var);\n</code></pre>\n\n<p>and so on...</p>\n" }, { "answer_id": 271445, "author": "ilitirit", "author_id": 9825, "author_profile": "https://Stackoverflow.com/users/9825", "pm_score": 2, "selected": true, "text": "<p>Try commenting out the code in the for loop and comparing the time. Once you have a reading, start uncommenting various sections until you hit the bottle-neck.</p>\n" }, { "answer_id": 271651, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 1, "selected": false, "text": "<p>As a basic idea you should try to see the speed of the code when you have only VT_BSTR conversion, after that with VT_DATE and at last with the other types, see which is taking the most time.</p>\n\n<p>The only observation I have is that itoa is not standard C. The implementation may be very slow as you can see from <a href=\"http://www.jb.man.ac.uk/~slowe/cpp/itoa.html#newest\" rel=\"nofollow noreferrer\">this</a> article.</p>\n" }, { "answer_id": 271695, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 0, "selected": false, "text": "<p>You don't need the itoa - you're writing to a stream.</p>\n" }, { "answer_id": 272513, "author": "Andreas Magnusson", "author_id": 5811, "author_profile": "https://Stackoverflow.com/users/5811", "pm_score": 0, "selected": false, "text": "<p>To answer your new question I think you should use the fact that you can let the stream format your data instead of formatting it into a string and then pass that string to the stream, e.g.:</p>\n\n<pre><code>_stprintf(buf, _T(\"%4d-%02d-%02d %02d:%02d:%02d\"),\n sysTime.wYear, sysTime.wMonth, sysTime.wDay, \n sysTime.wHour, sysTime.wMinute, sysTime.wSecond);\n\nostrm &lt;&lt; buf;\n</code></pre>\n\n<p>Turns into:</p>\n\n<pre><code>ostrm.fill('0');\nostrm.width(4);\nostrm &lt;&lt; sysTime.wYear &lt;&lt; _T(\"-\");\nostrm.width(2);\nostrm &lt;&lt; sysTime.wMonth;\n</code></pre>\n\n<p>And so on...</p>\n" } ]
2008/11/07
[ "https://Stackoverflow.com/questions/271204", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9328/" ]
This loop is slower than I would expect, and I'm not sure where yet. See anything? I'm reading an Accces DB, using client-side cursors. When I have 127,000 rows with 20 columns, this loop takes about 10 seconds. The 20 columns are string, int, and date types. All the types get converted to ANSI strings before they are put into the ostringstream buffer. ``` void LoadRecordsetIntoStream(_RecordsetPtr& pRs, ostringstream& ostrm) { ADODB::FieldsPtr pFields = pRs->Fields; char buf[80]; ::SYSTEMTIME sysTime; _variant_t var; while(!pRs->EndOfFile) // loop through rows { for (long i = 0L; i < nColumns; i++) // loop through columns { var = pFields->GetItem(i)->GetValue(); if (V_VT(&var) == VT_BSTR) { ostrm << (const char*) (_bstr_t) var; } else if (V_VT(&var) == VT_I4 || V_VT(&var) == VT_UI1 || V_VT(&var) == VT_I2 || V_VT(&var) == VT_BOOL) { ostrm << itoa(((int)var),buf,10); } else if (V_VT(&var) == VT_DATE) { ::VariantTimeToSystemTime(var,&sysTime); _stprintf(buf, _T("%4d-%02d-%02d %02d:%02d:%02d"), sysTime.wYear, sysTime.wMonth, sysTime.wDay, sysTime.wHour, sysTime.wMinute, sysTime.wSecond); ostrm << buf; } } pRs->MoveNext(); } } ``` EDIT: After more experimentation... I know now that about half the time is used by this line: var = pFields->GetItem(i)->GetValue(); If I bypass the Microsoft generated COM wrappers, will my code be faster? My guess is no. The othe half of the time is spent in the statements which convert data and stream it into the ostringstream. I don't know right now as I write this whether it's the conversions or the streaming that is taking more time. Would it be faster if I didn't use ostringstream and instead managed my own buffer, with my own logic to grow the buffer (re-alloc, copy, delete)? Would it be faster if my logic made a pessimistic guesstimate and reserved a lot of space for the ostringstream buffer up front? These might be experiments worth trying. Finally, the conversions themselves. None of the three stand out in my timings as being bad. One answer says that my itoa might be slower than an alternative. Worth checking out.
Try commenting out the code in the for loop and comparing the time. Once you have a reading, start uncommenting various sections until you hit the bottle-neck.
271,210
<p>I have a build server running CruiseControl.NET. It works well for the 7 projects that are configured to run on that server (let's call it server A).</p> <p>Now I have a new project that I wish to build on a different server (server B), but I want it to appear in the same ccnet dashboard as the existing projects. </p> <p>How do I configure CCNet for this scenario?</p>
[ { "answer_id": 271858, "author": "John Lemp", "author_id": 12915, "author_profile": "https://Stackoverflow.com/users/12915", "pm_score": 4, "selected": true, "text": "<p>In <code>dashboard.config</code> (default location is <code>c:\\Program Files\\CruiseControl.NET\\webdashboard\\dashboard.config</code>) take a look at the <a href=\"http://confluence.public.thoughtworks.org/display/CCNET/Servers+Configuration+Block\" rel=\"nofollow noreferrer\">Servers Configuration Block</a>:</p>\n\n<pre><code> &lt;servers&gt;\n &lt;server name=\"local\" url=\"tcp://localhost:21234/CruiseManager.rem\"\n allowForceBuild=\"true\" allowStartStopBuild=\"true\" /&gt;\n &lt;/servers&gt;\n</code></pre>\n\n<p>It allows you to configure the remote servers you want to report on - just add another <code>&lt;server /></code> node.\nTo force the changes to appear on your CruiseControl.NET dashboard, edit the web.config file in the same folder and save it. Refresh the dashboard web page.</p>\n" }, { "answer_id": 276599, "author": "David White", "author_id": 30183, "author_profile": "https://Stackoverflow.com/users/30183", "pm_score": 2, "selected": false, "text": "<p>Duckworth's answer is the one I found via Google. I found the complete story (identifying all protagonists) as:</p>\n\n<p>Open the dashboard.config file. Its default location is \\Program Files\\CruiseControl.NET\\webdashboard. </p>\n\n<p>At the top of dashboard.config, add the extra server. Eg</p>\n\n<p> \n\n \n \n \n \n \n </p>\n\n<p>and save the changes.</p>\n\n<p>To force the changes to appear on your CruiseControl.NET dashboard, edit the web.config file in the same folder and save it. Refresh the dashboard web page.</p>\n" } ]
2008/11/07
[ "https://Stackoverflow.com/questions/271210", "https://Stackoverflow.com", "https://Stackoverflow.com/users/30183/" ]
I have a build server running CruiseControl.NET. It works well for the 7 projects that are configured to run on that server (let's call it server A). Now I have a new project that I wish to build on a different server (server B), but I want it to appear in the same ccnet dashboard as the existing projects. How do I configure CCNet for this scenario?
In `dashboard.config` (default location is `c:\Program Files\CruiseControl.NET\webdashboard\dashboard.config`) take a look at the [Servers Configuration Block](http://confluence.public.thoughtworks.org/display/CCNET/Servers+Configuration+Block): ``` <servers> <server name="local" url="tcp://localhost:21234/CruiseManager.rem" allowForceBuild="true" allowStartStopBuild="true" /> </servers> ``` It allows you to configure the remote servers you want to report on - just add another `<server />` node. To force the changes to appear on your CruiseControl.NET dashboard, edit the web.config file in the same folder and save it. Refresh the dashboard web page.
271,218
<p>I am trying something very simple, but for some reason it does not work. Basically, I need to rename some nodes in an XML document. Thus, I created an XSLT file to do the transformation.</p> <p>Here is an example of the XML:</p> <p>EDIT: Addresses and Address elements occur at many levels. This is what caused me to have to try and apply an XSLT. The Visual Studio typed dataset feature, which creates typed datasets from XSD files does not permit you to have nested references to the same table. Thus, having Businesses/Business/Addresses and Businesses/Business/Contact/Addresses causes the Load() to fail. This is a known issue, and all they tell you is something like "Don't have nested table references...edit your XSD to stop having that." Unfortunately, this means that we have to apply XSLT to make the XML conform to the "hacked" XSD, since the files are coming from a third party vendor.</p> <p>So, we are very close with the help rendered here. The last couple of things are these:</p> <p>1.) How can I use the namespace reference in the match attribute of the xsl:template in order to specify that I want to rename Businesses/Business/Addresses to BusinessAddresses, but rename Businesses/Business/Contacts/Contact/Addresses to ContactAddresses?</p> <p>2.) How can I stop the XSLT from cluttering every new element with explicit namespace references? It is causing extreme bloat in the output.</p> <p>I created a namespace called "steel", and was having good success with:</p> <pre><code>&lt;xsl:template match="steel:Addresses&gt; &lt;xsl:element name="BusinessAddresses&gt; &lt;/xsl:template&gt; </code></pre> <p>The obvious problem here is that it renames <strong>ALL</strong> of the Addresses elements to BusinessAddresses, even though I want some of them named ContactAddresses, and so on. The needless addition of explicit namespace references to all of the renamed nodes is also troublesome.</p> <p>I tried this sort of thing, but as soon as I add slashes to the match attribute, it is a a syntax error in the XSLT, like so:</p> <pre><code>&lt;xsl:template match="steel:/Businesses/Business/Addresses"&gt; </code></pre> <p>I feel very close, but need some guidance on how to mix both the namespace usage and a way to use the slashes to select <strong>ANY</strong> nodes under specific paths.</p> <pre><code>&lt;?xml version="1.0"?&gt; &lt;Businesses&gt; &lt;Business&gt; &lt;BusinessName&gt;Steel Stretching&lt;/BusinessName&gt; &lt;Addresses&gt; &lt;Address&gt; &lt;City&gt;Pittsburgh&lt;/City&gt; &lt;/Address&gt; &lt;Address&gt; &lt;City&gt;Philadelphia&lt;/City&gt; &lt;/Address&gt; &lt;/Addresses&gt; &lt;Contacts&gt; &lt;Contact&gt; &lt;FirstName&gt;Paul&lt;/FirstName&gt; &lt;LastName&gt;Jones&lt;/LastName&gt; &lt;Addresses&gt; &lt;Address&gt; &lt;City&gt;Pittsburgh&lt;/City&gt; &lt;/Address&gt; &lt;/Addresses&gt; &lt;/Contact&gt; &lt;/Contacts&gt; &lt;/Business&gt; &lt;Business&gt; &lt;BusinessName&gt;Iron Works&lt;/BusinessName&gt; &lt;Addresses&gt; &lt;Address&gt; &lt;City&gt;Harrisburg&lt;/City&gt; &lt;/Address&gt; &lt;Address&gt; &lt;City&gt;Lancaster&lt;/City&gt; &lt;/Address&gt; &lt;/Addresses&gt; &lt;/Business&gt; &lt;/Businesses&gt; </code></pre> <p>I need to rename Addresses to BusinessAddresses, and I need to rename Address to BusinessAddress, for every instance of Addresses and Address directly under a Business node. I also need to rename Addresses to ContactAddresses, and I need to rename Address to ContactAddress, for every instance of Addresses and Address directly under a Contact Node.</p> <p>I have tried several solutions, but none seem to work. They all end up producing the same XML as the original file.</p> <p>Here is an example of what I have tried:</p> <pre><code> &lt;xsl:template match="/"&gt; &lt;xsl:apply-templates select="@*|node()" /&gt; &lt;/xsl:template&gt; &lt;xsl:template match="@*|*"&gt; &lt;xsl:copy&gt; &lt;xsl:apply-templates select="@*|node()" /&gt; &lt;/xsl:copy&gt; &lt;/xsl:template&gt; &lt;xsl:template match="Addresses"&gt; &lt;BusinessAddresses&gt; &lt;xsl:apply-templates select="@*|node()" /&gt; &lt;/BusinessAddresses&gt; &lt;/xsl:template&gt; </code></pre> <p>This has been tried in at least 6 different flavors, complete with stepping through the XSLT debugger in VB.Net. It never executes the template match for Addresses.</p> <p>Why?</p>
[ { "answer_id": 271301, "author": "Jeff Yates", "author_id": 23234, "author_profile": "https://Stackoverflow.com/users/23234", "pm_score": 4, "selected": true, "text": "<h2>Why might an XSLT fail?</h2>\n\n<p>An XSLT will fail because of obvious things like typos. However, the most likely situation relates to namespace usage. If you declared a default namespace for your XML but don't include that in your XSLT, the XSLT won't match the templates as you might expect.</p>\n\n<p>The following example adds the <code>xmlns:business</code> attribute which declares that items qualified by the <code>business</code> prefix belong to the namespace <code>mynamespace.uri</code>. I then used this prefix to qualify the Address and Addresses template matches. Of course, you will need to change the namespace URI to whatever matches the default namespace of your XML file.</p>\n\n<pre><code>&lt;xsl:stylesheet version=\"1.0\" xmlns:xsl=\"http://www.w3.org/1999/XSL/Transform\"\n xmlns:msxsl=\"urn:schemas-microsoft-com:xslt\"\n xmlns:business=\"mynamespace.uri\"\n exclude-result-prefixes=\"msxsl\"&gt;\n &lt;xsl:template match=\"/\"&gt;\n &lt;xsl:apply-templates select=\"@*|node()\"/&gt;\n &lt;/xsl:template&gt;\n\n &lt;xsl:template match=\"@*|node()\"&gt;\n &lt;xsl:copy&gt;\n &lt;xsl:apply-templates select=\"@*|node()\"/&gt;\n &lt;/xsl:copy&gt;\n &lt;/xsl:template&gt;\n\n &lt;xsl:template match=\"business:Addresses\"&gt;\n &lt;xsl:element name=\"BusinessAddresses\"&gt;\n &lt;xsl:apply-templates select=\"@*|node()\" /&gt;\n &lt;/xsl:element&gt;\n &lt;/xsl:template&gt;\n\n &lt;xsl:template match=\"business:Address\"&gt;\n &lt;xsl:element name=\"BusinessAddress\"&gt;\n &lt;xsl:apply-templates select=\"@*|node()\"/&gt;\n &lt;/xsl:element&gt;\n &lt;/xsl:template&gt;\n&lt;/xsl:stylesheet&gt;\n</code></pre>\n\n<h2>How do you match templates based on element location as well as name?</h2>\n\n<p>There are several ways to achieve this last part to your problem, BusinessAddress or ContactAddress, but the easiest is to modify the template <code>match</code> attributes to consider parent nodes. If you think of the <code>match</code> attribute as a path into the XML for a node, this option becomes clearer (contents of templates left out for brevity):</p>\n\n<pre><code>&lt;xsl:template match=\"business:Business/business:Addresses&gt;\n&lt;/xsl:template&gt;\n\n&lt;xsl:template match=\"business:Business/business:Addresses/business:Address\"&gt;\n&lt;/xsl:template&gt;\n\n&lt;xsl:template match=\"business:Contact/business:Addresses\"&gt;\n&lt;/xsl:template&gt;\n\n&lt;xsl:template match=\"business:Contact/business:Addresses/business:Address\"&gt;\n&lt;/xsl:template&gt;\n</code></pre>\n\n<p>Other methods exist for achieving this if the <code>match</code> remains based on just the element name, but they're harder to implement, follow, and maintain as they involve the use of conditional checks on the parent node hierarchy of the element being processing, all within the template.</p>\n" }, { "answer_id": 274416, "author": "Pride Fallon", "author_id": 35458, "author_profile": "https://Stackoverflow.com/users/35458", "pm_score": 0, "selected": false, "text": "<p>Maybe this, if the data you show is really like what you got to work with</p>\n\n<pre><code>&lt;xsl:stylesheet version=\"1.0\" xmlns:xsl=\"http://www.w3.org/1999/XSL/Transform\"&gt;\n\n&lt;xsl:template match=\"Businesses\"&gt;\n &lt;Businesses&gt;\n &lt;xsl:apply-templates/&gt;\n &lt;/Businesses&gt;\n&lt;/xsl:template&gt;\n\n&lt;xsl:template match=\"*\"&gt;\n &lt;xsl:copy-of select=\".\"/&gt;\n&lt;/xsl:template&gt;\n\n&lt;xsl:template match=\"Addresses\"&gt;\n &lt;BusinessAddresses&gt;\n &lt;xsl:apply-templates/&gt;\n &lt;/BusinessAddresses&gt;\n&lt;/xsl:template&gt;\n\n&lt;xsl:template match=\"Addresses/Address\"&gt;\n &lt;BusinessAddress&gt;\n &lt;xsl:value-of select=\".\"/&gt;\n &lt;/BusinessAddress&gt;\n&lt;/xsl:template&gt;\n\n&lt;/xsl:stylesheet&gt; \n</code></pre>\n" } ]
2008/11/07
[ "https://Stackoverflow.com/questions/271218", "https://Stackoverflow.com", "https://Stackoverflow.com/users/10224/" ]
I am trying something very simple, but for some reason it does not work. Basically, I need to rename some nodes in an XML document. Thus, I created an XSLT file to do the transformation. Here is an example of the XML: EDIT: Addresses and Address elements occur at many levels. This is what caused me to have to try and apply an XSLT. The Visual Studio typed dataset feature, which creates typed datasets from XSD files does not permit you to have nested references to the same table. Thus, having Businesses/Business/Addresses and Businesses/Business/Contact/Addresses causes the Load() to fail. This is a known issue, and all they tell you is something like "Don't have nested table references...edit your XSD to stop having that." Unfortunately, this means that we have to apply XSLT to make the XML conform to the "hacked" XSD, since the files are coming from a third party vendor. So, we are very close with the help rendered here. The last couple of things are these: 1.) How can I use the namespace reference in the match attribute of the xsl:template in order to specify that I want to rename Businesses/Business/Addresses to BusinessAddresses, but rename Businesses/Business/Contacts/Contact/Addresses to ContactAddresses? 2.) How can I stop the XSLT from cluttering every new element with explicit namespace references? It is causing extreme bloat in the output. I created a namespace called "steel", and was having good success with: ``` <xsl:template match="steel:Addresses> <xsl:element name="BusinessAddresses> </xsl:template> ``` The obvious problem here is that it renames **ALL** of the Addresses elements to BusinessAddresses, even though I want some of them named ContactAddresses, and so on. The needless addition of explicit namespace references to all of the renamed nodes is also troublesome. I tried this sort of thing, but as soon as I add slashes to the match attribute, it is a a syntax error in the XSLT, like so: ``` <xsl:template match="steel:/Businesses/Business/Addresses"> ``` I feel very close, but need some guidance on how to mix both the namespace usage and a way to use the slashes to select **ANY** nodes under specific paths. ``` <?xml version="1.0"?> <Businesses> <Business> <BusinessName>Steel Stretching</BusinessName> <Addresses> <Address> <City>Pittsburgh</City> </Address> <Address> <City>Philadelphia</City> </Address> </Addresses> <Contacts> <Contact> <FirstName>Paul</FirstName> <LastName>Jones</LastName> <Addresses> <Address> <City>Pittsburgh</City> </Address> </Addresses> </Contact> </Contacts> </Business> <Business> <BusinessName>Iron Works</BusinessName> <Addresses> <Address> <City>Harrisburg</City> </Address> <Address> <City>Lancaster</City> </Address> </Addresses> </Business> </Businesses> ``` I need to rename Addresses to BusinessAddresses, and I need to rename Address to BusinessAddress, for every instance of Addresses and Address directly under a Business node. I also need to rename Addresses to ContactAddresses, and I need to rename Address to ContactAddress, for every instance of Addresses and Address directly under a Contact Node. I have tried several solutions, but none seem to work. They all end up producing the same XML as the original file. Here is an example of what I have tried: ``` <xsl:template match="/"> <xsl:apply-templates select="@*|node()" /> </xsl:template> <xsl:template match="@*|*"> <xsl:copy> <xsl:apply-templates select="@*|node()" /> </xsl:copy> </xsl:template> <xsl:template match="Addresses"> <BusinessAddresses> <xsl:apply-templates select="@*|node()" /> </BusinessAddresses> </xsl:template> ``` This has been tried in at least 6 different flavors, complete with stepping through the XSLT debugger in VB.Net. It never executes the template match for Addresses. Why?
Why might an XSLT fail? ----------------------- An XSLT will fail because of obvious things like typos. However, the most likely situation relates to namespace usage. If you declared a default namespace for your XML but don't include that in your XSLT, the XSLT won't match the templates as you might expect. The following example adds the `xmlns:business` attribute which declares that items qualified by the `business` prefix belong to the namespace `mynamespace.uri`. I then used this prefix to qualify the Address and Addresses template matches. Of course, you will need to change the namespace URI to whatever matches the default namespace of your XML file. ``` <xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform" xmlns:msxsl="urn:schemas-microsoft-com:xslt" xmlns:business="mynamespace.uri" exclude-result-prefixes="msxsl"> <xsl:template match="/"> <xsl:apply-templates select="@*|node()"/> </xsl:template> <xsl:template match="@*|node()"> <xsl:copy> <xsl:apply-templates select="@*|node()"/> </xsl:copy> </xsl:template> <xsl:template match="business:Addresses"> <xsl:element name="BusinessAddresses"> <xsl:apply-templates select="@*|node()" /> </xsl:element> </xsl:template> <xsl:template match="business:Address"> <xsl:element name="BusinessAddress"> <xsl:apply-templates select="@*|node()"/> </xsl:element> </xsl:template> </xsl:stylesheet> ``` How do you match templates based on element location as well as name? --------------------------------------------------------------------- There are several ways to achieve this last part to your problem, BusinessAddress or ContactAddress, but the easiest is to modify the template `match` attributes to consider parent nodes. If you think of the `match` attribute as a path into the XML for a node, this option becomes clearer (contents of templates left out for brevity): ``` <xsl:template match="business:Business/business:Addresses> </xsl:template> <xsl:template match="business:Business/business:Addresses/business:Address"> </xsl:template> <xsl:template match="business:Contact/business:Addresses"> </xsl:template> <xsl:template match="business:Contact/business:Addresses/business:Address"> </xsl:template> ``` Other methods exist for achieving this if the `match` remains based on just the element name, but they're harder to implement, follow, and maintain as they involve the use of conditional checks on the parent node hierarchy of the element being processing, all within the template.
271,224
<p>Can anyone reccomend a .net control (winforms) that can be used to as a designer to edit xml files / DSL files ??</p>
[ { "answer_id": 271301, "author": "Jeff Yates", "author_id": 23234, "author_profile": "https://Stackoverflow.com/users/23234", "pm_score": 4, "selected": true, "text": "<h2>Why might an XSLT fail?</h2>\n\n<p>An XSLT will fail because of obvious things like typos. However, the most likely situation relates to namespace usage. If you declared a default namespace for your XML but don't include that in your XSLT, the XSLT won't match the templates as you might expect.</p>\n\n<p>The following example adds the <code>xmlns:business</code> attribute which declares that items qualified by the <code>business</code> prefix belong to the namespace <code>mynamespace.uri</code>. I then used this prefix to qualify the Address and Addresses template matches. Of course, you will need to change the namespace URI to whatever matches the default namespace of your XML file.</p>\n\n<pre><code>&lt;xsl:stylesheet version=\"1.0\" xmlns:xsl=\"http://www.w3.org/1999/XSL/Transform\"\n xmlns:msxsl=\"urn:schemas-microsoft-com:xslt\"\n xmlns:business=\"mynamespace.uri\"\n exclude-result-prefixes=\"msxsl\"&gt;\n &lt;xsl:template match=\"/\"&gt;\n &lt;xsl:apply-templates select=\"@*|node()\"/&gt;\n &lt;/xsl:template&gt;\n\n &lt;xsl:template match=\"@*|node()\"&gt;\n &lt;xsl:copy&gt;\n &lt;xsl:apply-templates select=\"@*|node()\"/&gt;\n &lt;/xsl:copy&gt;\n &lt;/xsl:template&gt;\n\n &lt;xsl:template match=\"business:Addresses\"&gt;\n &lt;xsl:element name=\"BusinessAddresses\"&gt;\n &lt;xsl:apply-templates select=\"@*|node()\" /&gt;\n &lt;/xsl:element&gt;\n &lt;/xsl:template&gt;\n\n &lt;xsl:template match=\"business:Address\"&gt;\n &lt;xsl:element name=\"BusinessAddress\"&gt;\n &lt;xsl:apply-templates select=\"@*|node()\"/&gt;\n &lt;/xsl:element&gt;\n &lt;/xsl:template&gt;\n&lt;/xsl:stylesheet&gt;\n</code></pre>\n\n<h2>How do you match templates based on element location as well as name?</h2>\n\n<p>There are several ways to achieve this last part to your problem, BusinessAddress or ContactAddress, but the easiest is to modify the template <code>match</code> attributes to consider parent nodes. If you think of the <code>match</code> attribute as a path into the XML for a node, this option becomes clearer (contents of templates left out for brevity):</p>\n\n<pre><code>&lt;xsl:template match=\"business:Business/business:Addresses&gt;\n&lt;/xsl:template&gt;\n\n&lt;xsl:template match=\"business:Business/business:Addresses/business:Address\"&gt;\n&lt;/xsl:template&gt;\n\n&lt;xsl:template match=\"business:Contact/business:Addresses\"&gt;\n&lt;/xsl:template&gt;\n\n&lt;xsl:template match=\"business:Contact/business:Addresses/business:Address\"&gt;\n&lt;/xsl:template&gt;\n</code></pre>\n\n<p>Other methods exist for achieving this if the <code>match</code> remains based on just the element name, but they're harder to implement, follow, and maintain as they involve the use of conditional checks on the parent node hierarchy of the element being processing, all within the template.</p>\n" }, { "answer_id": 274416, "author": "Pride Fallon", "author_id": 35458, "author_profile": "https://Stackoverflow.com/users/35458", "pm_score": 0, "selected": false, "text": "<p>Maybe this, if the data you show is really like what you got to work with</p>\n\n<pre><code>&lt;xsl:stylesheet version=\"1.0\" xmlns:xsl=\"http://www.w3.org/1999/XSL/Transform\"&gt;\n\n&lt;xsl:template match=\"Businesses\"&gt;\n &lt;Businesses&gt;\n &lt;xsl:apply-templates/&gt;\n &lt;/Businesses&gt;\n&lt;/xsl:template&gt;\n\n&lt;xsl:template match=\"*\"&gt;\n &lt;xsl:copy-of select=\".\"/&gt;\n&lt;/xsl:template&gt;\n\n&lt;xsl:template match=\"Addresses\"&gt;\n &lt;BusinessAddresses&gt;\n &lt;xsl:apply-templates/&gt;\n &lt;/BusinessAddresses&gt;\n&lt;/xsl:template&gt;\n\n&lt;xsl:template match=\"Addresses/Address\"&gt;\n &lt;BusinessAddress&gt;\n &lt;xsl:value-of select=\".\"/&gt;\n &lt;/BusinessAddress&gt;\n&lt;/xsl:template&gt;\n\n&lt;/xsl:stylesheet&gt; \n</code></pre>\n" } ]
2008/11/07
[ "https://Stackoverflow.com/questions/271224", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
Can anyone reccomend a .net control (winforms) that can be used to as a designer to edit xml files / DSL files ??
Why might an XSLT fail? ----------------------- An XSLT will fail because of obvious things like typos. However, the most likely situation relates to namespace usage. If you declared a default namespace for your XML but don't include that in your XSLT, the XSLT won't match the templates as you might expect. The following example adds the `xmlns:business` attribute which declares that items qualified by the `business` prefix belong to the namespace `mynamespace.uri`. I then used this prefix to qualify the Address and Addresses template matches. Of course, you will need to change the namespace URI to whatever matches the default namespace of your XML file. ``` <xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform" xmlns:msxsl="urn:schemas-microsoft-com:xslt" xmlns:business="mynamespace.uri" exclude-result-prefixes="msxsl"> <xsl:template match="/"> <xsl:apply-templates select="@*|node()"/> </xsl:template> <xsl:template match="@*|node()"> <xsl:copy> <xsl:apply-templates select="@*|node()"/> </xsl:copy> </xsl:template> <xsl:template match="business:Addresses"> <xsl:element name="BusinessAddresses"> <xsl:apply-templates select="@*|node()" /> </xsl:element> </xsl:template> <xsl:template match="business:Address"> <xsl:element name="BusinessAddress"> <xsl:apply-templates select="@*|node()"/> </xsl:element> </xsl:template> </xsl:stylesheet> ``` How do you match templates based on element location as well as name? --------------------------------------------------------------------- There are several ways to achieve this last part to your problem, BusinessAddress or ContactAddress, but the easiest is to modify the template `match` attributes to consider parent nodes. If you think of the `match` attribute as a path into the XML for a node, this option becomes clearer (contents of templates left out for brevity): ``` <xsl:template match="business:Business/business:Addresses> </xsl:template> <xsl:template match="business:Business/business:Addresses/business:Address"> </xsl:template> <xsl:template match="business:Contact/business:Addresses"> </xsl:template> <xsl:template match="business:Contact/business:Addresses/business:Address"> </xsl:template> ``` Other methods exist for achieving this if the `match` remains based on just the element name, but they're harder to implement, follow, and maintain as they involve the use of conditional checks on the parent node hierarchy of the element being processing, all within the template.
271,238
<p>I'm just concerned about Windows, so there's no need to go into esoterica about Mono compatibility or anything like that.</p> <p>I should also add that the app that I'm writing is WPF, and I'd prefer to avoid taking a dependency on <code>System.Windows.Forms</code> if at all possible.</p>
[ { "answer_id": 271249, "author": "ine", "author_id": 4965, "author_profile": "https://Stackoverflow.com/users/4965", "pm_score": 1, "selected": false, "text": "<p>The simplest way would be to create an Autoplay Handler:</p>\n\n<p><a href=\"http://www.codeproject.com/KB/system/AutoplayDemo.aspx\" rel=\"nofollow noreferrer\">http://www.codeproject.com/KB/system/AutoplayDemo.aspx</a></p>\n\n<blockquote>\n <p>Autoplay Version 2 is a feature in\n Windows XP that will scan the first\n four levels of a removable media, when\n it arrives, looking for media content\n types (music, graphics, or video).\n Registration of applications is done\n on a content type basis. When a\n removable media arrives, Windows XP\n determines what actions to perform by\n evaluating the content and comparing\n it to registered handlers for that\n content.</p>\n</blockquote>\n\n<p>A <a href=\"http://msdn.microsoft.com/en-us/magazine/cc301341.aspx\" rel=\"nofollow noreferrer\">detailed MSDN article</a> is also available.</p>\n" }, { "answer_id": 271251, "author": "Josh Stodola", "author_id": 54420, "author_profile": "https://Stackoverflow.com/users/54420", "pm_score": 5, "selected": true, "text": "<p>Give this a shot...</p>\n\n<pre><code>using System;\nusing System.Collections.Generic;\nusing System.Text;\nusing System.Management;\n\nnamespace WMITestConsolApplication\n{\n\n class Program\n {\n\n static void Main(string[] args)\n {\n\n AddInsertUSBHandler();\n AddRemoveUSBHandler();\n while (true) {\n }\n\n }\n\n static ManagementEventWatcher w = null;\n\n static void AddRemoveUSBHandler()\n {\n\n WqlEventQuery q;\n ManagementScope scope = new ManagementScope(\"root\\\\CIMV2\");\n scope.Options.EnablePrivileges = true;\n\n try {\n\n q = new WqlEventQuery();\n q.EventClassName = \"__InstanceDeletionEvent\";\n q.WithinInterval = new TimeSpan(0, 0, 3);\n q.Condition = \"TargetInstance ISA 'Win32_USBControllerdevice'\";\n w = new ManagementEventWatcher(scope, q);\n w.EventArrived += USBRemoved;\n\n w.Start();\n }\n catch (Exception e) {\n\n\n Console.WriteLine(e.Message);\n if (w != null)\n {\n w.Stop();\n\n }\n }\n\n }\n\n static void AddInsertUSBHandler()\n {\n\n WqlEventQuery q;\n ManagementScope scope = new ManagementScope(\"root\\\\CIMV2\");\n scope.Options.EnablePrivileges = true;\n\n try {\n\n q = new WqlEventQuery();\n q.EventClassName = \"__InstanceCreationEvent\";\n q.WithinInterval = new TimeSpan(0, 0, 3);\n q.Condition = \"TargetInstance ISA 'Win32_USBControllerdevice'\";\n w = new ManagementEventWatcher(scope, q);\n w.EventArrived += USBInserted;\n\n w.Start();\n }\n catch (Exception e) {\n\n Console.WriteLine(e.Message);\n if (w != null)\n {\n w.Stop();\n\n }\n }\n\n }\n\n static void USBInserted(object sender, EventArgs e)\n {\n\n Console.WriteLine(\"A USB device inserted\");\n\n }\n\n static void USBRemoved(object sender, EventArgs e)\n {\n\n Console.WriteLine(\"A USB device removed\");\n\n }\n }\n\n}\n</code></pre>\n" }, { "answer_id": 271367, "author": "Ana Betts", "author_id": 5728, "author_profile": "https://Stackoverflow.com/users/5728", "pm_score": 3, "selected": false, "text": "<p>There are much less cumbersome ways of doing this than using WMI polling - just capture WM_DEVICECHANGE:</p>\n\n<p><a href=\"http://msdn.microsoft.com/en-us/library/aa363215.aspx\" rel=\"noreferrer\">http://msdn.microsoft.com/en-us/library/aa363215.aspx</a></p>\n" } ]
2008/11/07
[ "https://Stackoverflow.com/questions/271238", "https://Stackoverflow.com", "https://Stackoverflow.com/users/26628/" ]
I'm just concerned about Windows, so there's no need to go into esoterica about Mono compatibility or anything like that. I should also add that the app that I'm writing is WPF, and I'd prefer to avoid taking a dependency on `System.Windows.Forms` if at all possible.
Give this a shot... ``` using System; using System.Collections.Generic; using System.Text; using System.Management; namespace WMITestConsolApplication { class Program { static void Main(string[] args) { AddInsertUSBHandler(); AddRemoveUSBHandler(); while (true) { } } static ManagementEventWatcher w = null; static void AddRemoveUSBHandler() { WqlEventQuery q; ManagementScope scope = new ManagementScope("root\\CIMV2"); scope.Options.EnablePrivileges = true; try { q = new WqlEventQuery(); q.EventClassName = "__InstanceDeletionEvent"; q.WithinInterval = new TimeSpan(0, 0, 3); q.Condition = "TargetInstance ISA 'Win32_USBControllerdevice'"; w = new ManagementEventWatcher(scope, q); w.EventArrived += USBRemoved; w.Start(); } catch (Exception e) { Console.WriteLine(e.Message); if (w != null) { w.Stop(); } } } static void AddInsertUSBHandler() { WqlEventQuery q; ManagementScope scope = new ManagementScope("root\\CIMV2"); scope.Options.EnablePrivileges = true; try { q = new WqlEventQuery(); q.EventClassName = "__InstanceCreationEvent"; q.WithinInterval = new TimeSpan(0, 0, 3); q.Condition = "TargetInstance ISA 'Win32_USBControllerdevice'"; w = new ManagementEventWatcher(scope, q); w.EventArrived += USBInserted; w.Start(); } catch (Exception e) { Console.WriteLine(e.Message); if (w != null) { w.Stop(); } } } static void USBInserted(object sender, EventArgs e) { Console.WriteLine("A USB device inserted"); } static void USBRemoved(object sender, EventArgs e) { Console.WriteLine("A USB device removed"); } } } ```
271,244
<p>Given a Django.db models class:</p> <pre><code>class P(models.Model): type = models.ForeignKey(Type) # Type is another models.Model class name = models.CharField() </code></pre> <p>where one wishes to create a new P with a specified type, i.e. how does one make "type" to be a default, hidden field (from the user), where type is given likeso:</p> <pre><code>http://x.y/P/new?type=3 </code></pre> <p>So that in the form no "type" field will appear, but when the P is saved, its type will have id 3 (i.e. Type.objects.get(pk=3)).</p> <p>Secondarily, how does one (&amp; is it possible) specify a "default" type in the url, via urls.py, when using generic Django views, viz.</p> <pre><code>urlpatterns = ('django.generic.views.create_update', url(r'^/new$', 'create_object', { 'model': P }, name='new_P'), ) </code></pre> <p>I found that terribly difficult to describe, which may be part of the problem. :) Input is much appreciated!</p>
[ { "answer_id": 271252, "author": "Harley Holcombe", "author_id": 1057, "author_profile": "https://Stackoverflow.com/users/1057", "pm_score": 3, "selected": false, "text": "<p>To have a default Foreign Key in a model:</p>\n\n<pre><code>mydefault = Type.objects.get(pk=3)\n\nclass P(models.Model):\n type = models.ForeignKey(Type, default=mydefault) # Type is another models.Model class\n name = models.CharField()\n</code></pre>\n\n<p>Note that using <code>pk=x</code> is pretty ugly, as ideally you shouldn't care what the primary key is equal to. Try to get to the object you want by some other attribute.</p>\n\n<p><a href=\"http://docs.djangoproject.com/en/dev/topics/http/urls/#notes-on-capturing-text-in-urls\" rel=\"nofollow noreferrer\">Here</a>'s how you put defaults in your urls:</p>\n\n<pre><code># URLconf\nurlpatterns = patterns('',\n (r'^blog/$', 'blog.views.page'),\n (r'^blog/page(?P&lt;num&gt;\\d+)/$', 'blog.views.page'),\n)\n\n# View (in blog/views.py)\ndef page(request, num=\"1\"):\n # Output the appropriate page of blog entries, according to num.\n</code></pre>\n\n<blockquote>\n <p>In the above example, both URL patterns point to the same view -- blog.views.page -- but the first pattern doesn't capture anything from the URL. If the first pattern matches, the page() function will use its default argument for num, \"1\". If the second pattern matches, page() will use whatever num value was captured by the regex.</p>\n</blockquote>\n" }, { "answer_id": 271303, "author": "Daniel Naab", "author_id": 32638, "author_profile": "https://Stackoverflow.com/users/32638", "pm_score": 3, "selected": false, "text": "<p>The widget <code>django.forms.widgets.HiddenInput</code> will render your field as hidden.</p>\n\n<p>In most cases, I think you'll find that any hidden form value could also be specified as a url parameter instead. In other words:</p>\n\n<pre><code>&lt;form action=\"new/{{your_hidden_value}}\" method=\"post\"&gt;\n....\n&lt;/form&gt;\n</code></pre>\n\n<p>and in urls.py:</p>\n\n<pre><code>^/new/(?P&lt;hidden_value&gt;\\w+)/\n</code></pre>\n\n<p>I prefer this technique myself because I only really find myself needing hidden form fields when I need to track the primary key of a model instance - in which case an \"edit/pkey\" url serves the purposes of both initiating the edit/returning the form, and receiving the POST on save.</p>\n" }, { "answer_id": 1937451, "author": "surtyaar", "author_id": 164467, "author_profile": "https://Stackoverflow.com/users/164467", "pm_score": 2, "selected": false, "text": "<p>If you go with Andrew's approach of including the hidden value in the url and still want to use one of Django's built in form templates, there are ways for you to exclude the hidden field.</p>\n\n<p><a href=\"http://docs.djangoproject.com/en/1.1/topics/forms/modelforms/#using-a-subset-of-fields-on-the-form\" rel=\"nofollow noreferrer\">http://docs.djangoproject.com/en/1.1/topics/forms/modelforms/#using-a-subset-of-fields-on-the-form</a></p>\n" } ]
2008/11/07
[ "https://Stackoverflow.com/questions/271244", "https://Stackoverflow.com", "https://Stackoverflow.com/users/19212/" ]
Given a Django.db models class: ``` class P(models.Model): type = models.ForeignKey(Type) # Type is another models.Model class name = models.CharField() ``` where one wishes to create a new P with a specified type, i.e. how does one make "type" to be a default, hidden field (from the user), where type is given likeso: ``` http://x.y/P/new?type=3 ``` So that in the form no "type" field will appear, but when the P is saved, its type will have id 3 (i.e. Type.objects.get(pk=3)). Secondarily, how does one (& is it possible) specify a "default" type in the url, via urls.py, when using generic Django views, viz. ``` urlpatterns = ('django.generic.views.create_update', url(r'^/new$', 'create_object', { 'model': P }, name='new_P'), ) ``` I found that terribly difficult to describe, which may be part of the problem. :) Input is much appreciated!
To have a default Foreign Key in a model: ``` mydefault = Type.objects.get(pk=3) class P(models.Model): type = models.ForeignKey(Type, default=mydefault) # Type is another models.Model class name = models.CharField() ``` Note that using `pk=x` is pretty ugly, as ideally you shouldn't care what the primary key is equal to. Try to get to the object you want by some other attribute. [Here](http://docs.djangoproject.com/en/dev/topics/http/urls/#notes-on-capturing-text-in-urls)'s how you put defaults in your urls: ``` # URLconf urlpatterns = patterns('', (r'^blog/$', 'blog.views.page'), (r'^blog/page(?P<num>\d+)/$', 'blog.views.page'), ) # View (in blog/views.py) def page(request, num="1"): # Output the appropriate page of blog entries, according to num. ``` > > In the above example, both URL patterns point to the same view -- blog.views.page -- but the first pattern doesn't capture anything from the URL. If the first pattern matches, the page() function will use its default argument for num, "1". If the second pattern matches, page() will use whatever num value was captured by the regex. > > >
271,260
<p>I was in need of a way to compress images in .net so i looked into using the .net GZipStream class (or DeflateStream). However i found that decompression was not always successful, sometimes the images would decompress fine and other times i would get a GDI+ error that something is corrupted.</p> <p>After investigating the issue i found that the decompression was not giving back all the bytes it compressed. So if i compressed 2257974 bytes i would sometimes get back only 2257870 bytes (real numbers).</p> <p>The most funny thing is that sometimes it would work. So i created this little test method that compresses only 10 bytes and now i don't get back anything at all.</p> <p>I tried it with both compression classes GZipStream and DeflateStream and i double checked my code for possible errors. I even tried positioning the stream to 0 and flushing all the streams but with no luck.</p> <p>Here is my code:</p> <pre><code> public static void TestCompression() { byte[] test = new byte[] { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 }; byte[] result = Decompress(Compress(test)); // This will fail, result.Length is 0 Debug.Assert(result.Length == test.Length); } public static byte[] Compress(byte[] data) { var compressedStream = new MemoryStream(); var zipStream = new GZipStream(compressedStream, CompressionMode.Compress); zipStream.Write(data, 0, data.Length); return compressedStream.ToArray(); } public static byte[] Decompress(byte[] data) { var compressedStream = new MemoryStream(data); var zipStream = new GZipStream(compressedStream, CompressionMode.Decompress); var resultStream = new MemoryStream(); var buffer = new byte[4096]; int read; while ((read = zipStream.Read(buffer, 0, buffer.Length)) &gt; 0) { resultStream.Write(buffer, 0, read); } return resultStream.ToArray(); } </code></pre>
[ { "answer_id": 271264, "author": "Marc Gravell", "author_id": 23354, "author_profile": "https://Stackoverflow.com/users/23354", "pm_score": 7, "selected": true, "text": "<p>You need to <code>Close()</code> the <code>ZipStream</code> after adding all the data you want to compress; it retains a buffer of unwritten bytes internally (even if you <code>Flush()</code>) that needs to be written.</p>\n\n<p>More generally, <code>Stream</code> is <code>IDisposable</code>, so you should also be <code>using</code> each... (yes, I know that <code>MemoryStream</code> isn't going to lose any data, but if you don't get into this habit, it will bite you with other <code>Stream</code>s).</p>\n\n<pre><code>public static byte[] Compress(byte[] data)\n{\n using (var compressedStream = new MemoryStream())\n using (var zipStream = new GZipStream(compressedStream, CompressionMode.Compress))\n {\n zipStream.Write(data, 0, data.Length);\n zipStream.Close();\n return compressedStream.ToArray();\n }\n}\n\npublic static byte[] Decompress(byte[] data)\n{\n using(var compressedStream = new MemoryStream(data))\n using(var zipStream = new GZipStream(compressedStream, CompressionMode.Decompress))\n using (var resultStream = new MemoryStream())\n { ... }\n}\n</code></pre>\n\n<p>[edit : updated re comment]\nRe not <code>using</code> things like <code>MemoryStream</code> - this is always a fun one, with lots of votes on either side of the fence: but ultimatey...</p>\n\n<p>(rhetorical - we all know the answer...) How is <code>MemoryStream</code> implemented? is it a byte[] (owned by .NET)? is it a memory-mapped file (owned by the OS)?</p>\n\n<p>The reason you aren't <code>using</code> it is because you are letting knowledge of internal implementation details change how you code against a public API - i.e. you just broke the laws of encapsulation. The public API says: I am <code>IDisposable</code>; you \"own\" me; therefore, it is your job to <code>Dispose()</code> me when you are through.</p>\n" }, { "answer_id": 410415, "author": "Cheeso", "author_id": 48082, "author_profile": "https://Stackoverflow.com/users/48082", "pm_score": 2, "selected": false, "text": "<p>Also - keep in mind the DeflateStream in System.IO.Compression does not implement the most efficient deflate algorithm. If you like, there is an alternative to the BCL GZipStream and DeflateStream; it is implemented in a fully-managed library based on zlib code, that performs better than the built-in {Deflate,GZip}Stream in this respect. [ But you still need to Close() the stream to get the full bytestream. ] </p>\n\n<p>These stream classes are shipped in the DotNetZlib assembly, available in the DotNetZip distribution at <a href=\"http://DotNetZip.codeplex.com/\" rel=\"nofollow noreferrer\">http://DotNetZip.codeplex.com/</a>. </p>\n" } ]
2008/11/07
[ "https://Stackoverflow.com/questions/271260", "https://Stackoverflow.com", "https://Stackoverflow.com/users/35371/" ]
I was in need of a way to compress images in .net so i looked into using the .net GZipStream class (or DeflateStream). However i found that decompression was not always successful, sometimes the images would decompress fine and other times i would get a GDI+ error that something is corrupted. After investigating the issue i found that the decompression was not giving back all the bytes it compressed. So if i compressed 2257974 bytes i would sometimes get back only 2257870 bytes (real numbers). The most funny thing is that sometimes it would work. So i created this little test method that compresses only 10 bytes and now i don't get back anything at all. I tried it with both compression classes GZipStream and DeflateStream and i double checked my code for possible errors. I even tried positioning the stream to 0 and flushing all the streams but with no luck. Here is my code: ``` public static void TestCompression() { byte[] test = new byte[] { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 }; byte[] result = Decompress(Compress(test)); // This will fail, result.Length is 0 Debug.Assert(result.Length == test.Length); } public static byte[] Compress(byte[] data) { var compressedStream = new MemoryStream(); var zipStream = new GZipStream(compressedStream, CompressionMode.Compress); zipStream.Write(data, 0, data.Length); return compressedStream.ToArray(); } public static byte[] Decompress(byte[] data) { var compressedStream = new MemoryStream(data); var zipStream = new GZipStream(compressedStream, CompressionMode.Decompress); var resultStream = new MemoryStream(); var buffer = new byte[4096]; int read; while ((read = zipStream.Read(buffer, 0, buffer.Length)) > 0) { resultStream.Write(buffer, 0, read); } return resultStream.ToArray(); } ```
You need to `Close()` the `ZipStream` after adding all the data you want to compress; it retains a buffer of unwritten bytes internally (even if you `Flush()`) that needs to be written. More generally, `Stream` is `IDisposable`, so you should also be `using` each... (yes, I know that `MemoryStream` isn't going to lose any data, but if you don't get into this habit, it will bite you with other `Stream`s). ``` public static byte[] Compress(byte[] data) { using (var compressedStream = new MemoryStream()) using (var zipStream = new GZipStream(compressedStream, CompressionMode.Compress)) { zipStream.Write(data, 0, data.Length); zipStream.Close(); return compressedStream.ToArray(); } } public static byte[] Decompress(byte[] data) { using(var compressedStream = new MemoryStream(data)) using(var zipStream = new GZipStream(compressedStream, CompressionMode.Decompress)) using (var resultStream = new MemoryStream()) { ... } } ``` [edit : updated re comment] Re not `using` things like `MemoryStream` - this is always a fun one, with lots of votes on either side of the fence: but ultimatey... (rhetorical - we all know the answer...) How is `MemoryStream` implemented? is it a byte[] (owned by .NET)? is it a memory-mapped file (owned by the OS)? The reason you aren't `using` it is because you are letting knowledge of internal implementation details change how you code against a public API - i.e. you just broke the laws of encapsulation. The public API says: I am `IDisposable`; you "own" me; therefore, it is your job to `Dispose()` me when you are through.
271,265
<p>I'm using JMX to save some diagnostic information from a remote process. Looking at the interface in jconsole shows that the return type is <a href="http://java.sun.com/j2se/1.5.0/docs/api/javax/management/openmbean/CompositeData.html" rel="noreferrer">CompositeData</a> (the data actually comes back as <a href="http://java.sun.com/j2se/1.5.0/docs/api/javax/management/openmbean/CompositeDataSupport.html" rel="noreferrer">CompositeDataSupport</a>). I want to output all the key/value pairs that are associated with this object.</p> <p>The problem is that the interface just seems to have a "values()" method with no way of getting the keys. Am I missing something here? Is there some other way to approach this task?</p> <p>Thanks!</p>
[ { "answer_id": 271400, "author": "Tyler Levine", "author_id": 35339, "author_profile": "https://Stackoverflow.com/users/35339", "pm_score": 4, "selected": true, "text": "<p>If I'm not mistaken you could do</p>\n\n<pre><code>Set&lt; String &gt; keys = cData.getCompositeType().keySet();\n</code></pre>\n\n<p>(given that cData is a CompositeData object)</p>\n\n<p><a href=\"http://java.sun.com/j2se/1.5.0/docs/api/javax/management/openmbean/CompositeType.html#keySet()\" rel=\"noreferrer\">http://java.sun.com/j2se/1.5.0/docs/api/javax/management/openmbean/CompositeType.html#keySet()</a></p>\n" }, { "answer_id": 271408, "author": "VonC", "author_id": 6309, "author_profile": "https://Stackoverflow.com/users/6309", "pm_score": 2, "selected": false, "text": "<p>You can find a more complete example with this <a href=\"http://blogs.oracle.com/jmxetc/entry/a_small_program_that_prints\" rel=\"nofollow noreferrer\">small program that prints the attributes of all JVM MBeans</a></p>\n\n<p>In particular:</p>\n\n<pre><code>StringBuffer writeCompositeData(StringBuffer buffer, \n String prefix, String name, CompositeData data) {\n if (data == null)\n return writeSimple(buffer,prefix,name,null,true);\n writeSimple(buffer,prefix,name,\"CompositeData(\"+\n data.getCompositeType().getTypeName()+\")\",true);\n buffer.append(prefix).append(\"{\").append(\"\\n\");\n final String fieldprefix = prefix + \" \";\n for (String key : data.getCompositeType().keySet()) {\n write(buffer,fieldprefix,name+\".\"+key,data.get(key));\n }\n buffer.append(prefix).append(\"}\").append(\"\\n\");\n return buffer;\n }\n</code></pre>\n\n<p>The part:</p>\n\n<pre><code>for (String key : data.getCompositeType().keySet()) {\n [...] data.get(key) [...];\n}\n</code></pre>\n\n<p>being what you are after.</p>\n" } ]
2008/11/07
[ "https://Stackoverflow.com/questions/271265", "https://Stackoverflow.com", "https://Stackoverflow.com/users/18437/" ]
I'm using JMX to save some diagnostic information from a remote process. Looking at the interface in jconsole shows that the return type is [CompositeData](http://java.sun.com/j2se/1.5.0/docs/api/javax/management/openmbean/CompositeData.html) (the data actually comes back as [CompositeDataSupport](http://java.sun.com/j2se/1.5.0/docs/api/javax/management/openmbean/CompositeDataSupport.html)). I want to output all the key/value pairs that are associated with this object. The problem is that the interface just seems to have a "values()" method with no way of getting the keys. Am I missing something here? Is there some other way to approach this task? Thanks!
If I'm not mistaken you could do ``` Set< String > keys = cData.getCompositeType().keySet(); ``` (given that cData is a CompositeData object) <http://java.sun.com/j2se/1.5.0/docs/api/javax/management/openmbean/CompositeType.html#keySet()>
271,273
<p>I'm trying to take advantage of the constant memory, but I'm having a hard time figuring out how to nest arrays. What I have is an array of data that has counts for internal data but those are different for each entry. So based around the following simplified code I have two problems. First I don't know how to allocate the data pointed to by the members of my data structure. Second, since I can't use cudaGetSymbolAddress for constant memory I'm not sure if I can just pass the global pointer (which you cannot do with plain __device__ memory).</p> <pre><code> struct __align(16)__ data{ int nFiles; int nNames; int* files; int* names; }; __device__ __constant__ data *mydata; __host__ void initMemory(...) { cudaMalloc( (void **) &(mydata), sizeof(data)*dynamicsize ); for(int i=; i lessthan dynamicsize; i++) { cudaMemcpyToSymbol(mydata, &(nFiles[i]), sizeof(int), sizeof(data)*i, cudaMemcpyHostToDevice); //... //Problem 1: Allocate & Set mydata[i].files } } __global__ void myKernel(data *constDataPtr) { //Problem 2: Access constDataPtr[n].files, etc } int main() { //... myKernel grid, threads (mydata); } </code></pre> <p>Thanks for any help offered. :-)</p>
[ { "answer_id": 672941, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 0, "selected": false, "text": "<p>Why don't you just use the so-called \"packed\" data representation? This approach allows you to place all the data you need into one-dimension byte array. E.g., if you need to store</p>\n\n<pre><code>struct data\n{\n int nFiles;\n int nNames;\n int* files;\n int* names;\n}\n</code></pre>\n\n<p>You can just store this data in the array this way:</p>\n\n<pre><code>[struct data (7*4=28 bytes)\n [int nFiles=3 (4 bytes)]\n [int nNames=2 (4 bytes)]\n [file0 (4 bytes)]\n [file1 (4 bytes)]\n [file2 (4 bytes)]\n [name0 (4 bytes)]\n [name1 (4 bytes)]\n]\n</code></pre>\n" }, { "answer_id": 1261307, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 2, "selected": false, "text": "<p>I think constant memory is 64K and you cannot allocate it dynamically using <code>cudaMalloc</code>. It has to be declared constant, say,</p>\n\n<pre><code>__constant__ data mydata[100];\n</code></pre>\n\n<p>Similarly you also don't need to free it. Also, you shouldn't pass the reference to it via pointer, just access it as a global variable. I tried doing a similar thing and it gave me segfault (in devicemu).</p>\n" }, { "answer_id": 5115651, "author": "jwdmsd", "author_id": 583246, "author_profile": "https://Stackoverflow.com/users/583246", "pm_score": 2, "selected": false, "text": "<p>No, you cant do that.</p>\n\n<p>Constant memory (64KB max) can only be hard-coded before compilation.</p>\n\n<p>However you can assign texture memory on the fly which is also cached on the Device.</p>\n" } ]
2008/11/07
[ "https://Stackoverflow.com/questions/271273", "https://Stackoverflow.com", "https://Stackoverflow.com/users/35373/" ]
I'm trying to take advantage of the constant memory, but I'm having a hard time figuring out how to nest arrays. What I have is an array of data that has counts for internal data but those are different for each entry. So based around the following simplified code I have two problems. First I don't know how to allocate the data pointed to by the members of my data structure. Second, since I can't use cudaGetSymbolAddress for constant memory I'm not sure if I can just pass the global pointer (which you cannot do with plain \_\_device\_\_ memory). ``` struct __align(16)__ data{ int nFiles; int nNames; int* files; int* names; }; __device__ __constant__ data *mydata; __host__ void initMemory(...) { cudaMalloc( (void **) &(mydata), sizeof(data)*dynamicsize ); for(int i=; i lessthan dynamicsize; i++) { cudaMemcpyToSymbol(mydata, &(nFiles[i]), sizeof(int), sizeof(data)*i, cudaMemcpyHostToDevice); //... //Problem 1: Allocate & Set mydata[i].files } } __global__ void myKernel(data *constDataPtr) { //Problem 2: Access constDataPtr[n].files, etc } int main() { //... myKernel grid, threads (mydata); } ``` Thanks for any help offered. :-)
I think constant memory is 64K and you cannot allocate it dynamically using `cudaMalloc`. It has to be declared constant, say, ``` __constant__ data mydata[100]; ``` Similarly you also don't need to free it. Also, you shouldn't pass the reference to it via pointer, just access it as a global variable. I tried doing a similar thing and it gave me segfault (in devicemu).
271,274
<p>I am adding objects into a java Vector using its add(Object) method. In my example, the first 5 objects are identical, followed by 2 instances different from the first five. For some reasons, as soon as I insert the first one that is different, it changes the entire vector to that value!</p> <p>'values' is an iterator containing something like '1','1','1','1','1','2','2'</p> <pre><code> Vector temp = new Vector(); while (values.hasNext()) { temp.add(values.next()); System.out.println(temp.toString()); } </code></pre> <p>It will output something like</p> <blockquote> <p>[1]<br> [1,1]<br> [1,1,1]<br> [1,1,1,1]<br> [1,1,1,1,1]<br> [2,2,2,2,2,2]<br> [2,2,2,2,2,2,2] </p> </blockquote> <p>I tried using a LinkedList, as well as using add(object, index). Same thing happened.</p>
[ { "answer_id": 271293, "author": "erickson", "author_id": 3474, "author_profile": "https://Stackoverflow.com/users/3474", "pm_score": 3, "selected": false, "text": "<p>I suspect that, somehow, the \"objects\" you are getting from the iterator are really multiple references to a single instance of a mutable object, which is changing its state from \"1\" to \"2\". The thing I can't guess at is how it's changing state in this apparently single-threaded operation.</p>\n\n<p>Can you post more complete code? Show where <code>values</code> comes from and how it is initialized.</p>\n" }, { "answer_id": 271362, "author": "dlinsin", "author_id": 198, "author_profile": "https://Stackoverflow.com/users/198", "pm_score": 2, "selected": false, "text": "<p>The following program compiled and ran under Mac OS X</p>\n\n<pre><code>import java.util.Arrays;\nimport java.util.Iterator;\nimport java.util.List;\nimport java.util.Vector;\n\n public class Test{ \n\n public static void main( String ... args ){ \n List list = Arrays.asList(new String[] {\"1\",\"1\",\"1\",\"1\",\"1\",\"2\",\"2\"});\n Iterator values = list.iterator();\n Vector temp = new Vector(); \n while (values.hasNext()) {\n temp.add(values.next());\n System.out.println(temp.toString());\n }\n } \n } \n</code></pre>\n\n<p>produced the following results:</p>\n\n<pre><code>[1]\n[1, 1]\n[1, 1, 1]\n[1, 1, 1, 1]\n[1, 1, 1, 1, 1]\n[1, 1, 1, 1, 1, 2]\n[1, 1, 1, 1, 1, 2, 2]\n</code></pre>\n\n<p>So you might want to provide the full implementation especially your Iterator. And I just have to say it, but you really shouldn't use Vector!</p>\n" } ]
2008/11/07
[ "https://Stackoverflow.com/questions/271274", "https://Stackoverflow.com", "https://Stackoverflow.com/users/25645/" ]
I am adding objects into a java Vector using its add(Object) method. In my example, the first 5 objects are identical, followed by 2 instances different from the first five. For some reasons, as soon as I insert the first one that is different, it changes the entire vector to that value! 'values' is an iterator containing something like '1','1','1','1','1','2','2' ``` Vector temp = new Vector(); while (values.hasNext()) { temp.add(values.next()); System.out.println(temp.toString()); } ``` It will output something like > > [1] > > [1,1] > > [1,1,1] > > [1,1,1,1] > > [1,1,1,1,1] > > [2,2,2,2,2,2] > > [2,2,2,2,2,2,2] > > > I tried using a LinkedList, as well as using add(object, index). Same thing happened.
I suspect that, somehow, the "objects" you are getting from the iterator are really multiple references to a single instance of a mutable object, which is changing its state from "1" to "2". The thing I can't guess at is how it's changing state in this apparently single-threaded operation. Can you post more complete code? Show where `values` comes from and how it is initialized.
271,285
<p>My webapp (ASP.NET 2.0) consumes a webservice (asmx on 1.1 framework) on the same machine. After getting XML in return, I pass it to <code>XslCompiledTransform</code> for transform XML to HTML and it works fine.</p> <p>Yesterday I got a <code>System.IO.FileNotFoundException</code> frequently and don't know what causes this kind of problem.</p> <p>First look I thought it's about read/write permission on c:\windows\temp and then I made sure give it full permission for Network Service (also Everybody at last -_-!) but it doesn't help.</p> <p>Any ideas or solutions would be appreciate.</p> <pre><code>-------------------- stack trace -------------------------- Exception: **System.IO.FileNotFoundException** **Could not find file 'C:\WINDOWS\TEMP\sivvt5f6.dll'.** at System.IO.__Error**.WinIOError**(Int32 errorCode, String maybeFullPath) at System.IO.FileStream.Init(String path, FileMode mode, FileAccess access, Int32 rights, Boolean useRights, FileShare share, Int32 bufferSize, FileOptions options, SECURITY_ATTRIBUTES secAttrs, String msgPath, Boolean bFromProxy) at System.IO.FileStream..ctor(String path, FileMode mode, FileAccess access, FileShare share) at Microsoft.CSharp.CSharpCodeGenerator.FromFileBatch(CompilerParameters options, String[] fileNames) at Microsoft.CSharp.CSharpCodeGenerator.FromDomBatch(CompilerParameters options, CodeCompileUnit[] ea) at Microsoft.CSharp.CSharpCodeGenerator.System.CodeDom.Compiler.ICodeCompiler.CompileAssemblyFromDomBatch(CompilerParameters options, CodeCompileUnit[] ea) at System.CodeDom.Compiler.CodeDomProvider.CompileAssemblyFromDom(CompilerParameters options, CodeCompileUnit[] compilationUnits) at System.Xml.Xsl.Xslt.Scripts.CompileAssembly(List`1 scriptsForLang) at System.Xml.Xsl.Xslt.Scripts.CompileScripts() at System.Xml.Xsl.Xslt.QilGenerator.Compile(Compiler compiler) at System.Xml.Xsl.Xslt.**Compiler. Compile**(Object stylesheet, XmlResolver xmlResolver, QilExpression&amp; qil) at System.Xml.Xsl.XslCompiledTransform.LoadInternal(Object stylesheet, XsltSettings settings, XmlResolver stylesheetResolver) at System.Xml.Xsl.**XslCompiledTransform.Load**(String stylesheetUri, XsltSettings settings, XmlResolver stylesheetResolver) </code></pre>
[ { "answer_id": 271304, "author": "Marc Gravell", "author_id": 23354, "author_profile": "https://Stackoverflow.com/users/23354", "pm_score": 1, "selected": false, "text": "<p>OK, that's an interesting one. I've seen similar issues with serializers, but not with <code>XslCompiledTransform</code> specifically.</p>\n\n<p>From the title, I was expecting it to be an issue loading included/imported transforms, which would probably have been fixable by supplying an <code>XmlResolver</code>. Not finding the self-generated dlls is very odd!</p>\n\n<p>As a stop-gap (while you investigate the issue), you might want to see if it still happens with <code>XslTransform</code>. I realise this isn't ideal (given the optimisations etc in <code>XslCompiledTransform</code>), but it might at least let your app work while you investigate...</p>\n\n<p>The first investigative thing I would do is look at the event log. Anything interesting? Also worth checking if your anti-virus software hasn't gone mad with false positives (unlikely).</p>\n\n<p>The next thing I would do is isolate the app - i.e. snip off the 1.1 stuff - since you're calling it via an asmx page (to a separate application) it shouldn't be a factor, so you <em>should</em> (theoretically) be able to reproduce it just from a flat xml file. Ideally, it would be good to have a page (maybe an ashx for simplicity) in you project that <em>just</em> tries to do a transform from a local file.</p>\n\n<p>Is it reproducable with simple xslt/xml? The simpler you can make the code that has an issue, the closer you are to either finding/fixing it, or having something that you can fire at MS via \"connect\".</p>\n" }, { "answer_id": 271417, "author": "tongdee", "author_id": 35682, "author_profile": "https://Stackoverflow.com/users/35682", "pm_score": 1, "selected": false, "text": "<p>Thanks a lot Marc for your response.</p>\n\n<p>My xsl file has no external resource to be referenced to (no include, import) so XmlResolver should not be investigated.</p>\n\n<p>The transform works fine in other server (I got 2 servers) and also in this server,\nafter I did iisreset, it is getting works again. But before an hour, it comes again.\nI did check Event Viewer, and it logged the same error as I got!!</p>\n\n<p>---------------- from Event Viewer -------------\nEvent Type: Warning</p>\n\n<p>Event Source: ASP.NET 2.0.50727.0\nEvent Category: Web Event \nEvent ID: 1309\nDate: 11/7/2008\nTime: 2:07:37 PM\nUser: N/A\nComputer: XXXX\nDescription:\nEvent code: 3005 \nEvent message: An unhandled exception has occurred. \nEvent time: 11/7/2008 2:07:37 PM \nEvent time (UTC): 11/7/2008 7:07:37 AM \nEvent ID: f17058f2126c4a4abb1742a3099010b0 \nEvent sequence: 25407 \nEvent occurrence: 276 \nEvent detail code: 0 </p>\n\n<p>Process information: \n Process ID: 1128 \n Process name: w3wp.exe \n Account name: NT AUTHORITY\\NETWORK SERVICE </p>\n\n<p>Exception information: \n Exception type: FileNotFoundException \n Exception message: Could not find file 'C:\\WINDOWS\\TEMP\\irdt-y8o.dll'. \n .....</p>\n" }, { "answer_id": 274156, "author": "tongdee", "author_id": 35682, "author_profile": "https://Stackoverflow.com/users/35682", "pm_score": 2, "selected": false, "text": "<p>After checking for details and googling for the related topics,</p>\n\n<ol>\n<li>This problem found with .Transform() and also occures with XmlSerialization as Marc said.\nChristoph Schittko has a good article for <a href=\"http://msdn.microsoft.com/en-us/library/aa302290.aspx\" rel=\"nofollow noreferrer\">troubleshooting</a>. </li>\n<li><p>Someone said the problem may because some update patch of windows that can change the behavior of serializer.</p>\n\n<p>I called my administrator to clarify if there's any changes on our server and he said nothing changes and he suggest me for restarting.</p>\n\n<p>and Yes... my problem has been solved by.....restarting server (windows 2003 ;)</p></li>\n</ol>\n" }, { "answer_id": 315026, "author": "Dirk Vollmar", "author_id": 40347, "author_profile": "https://Stackoverflow.com/users/40347", "pm_score": 1, "selected": false, "text": "<p>just some ideas for troubleshooting:</p>\n\n<ul>\n<li>Is the dll file created? You could check e.g. with Filemon from Sysinternals to see if the XSLT is actually compiled.</li>\n<li>Is there enough free disk space?</li>\n<li>How many files are in your temp folder? There might be problems with too many files in %TMP%</li>\n<li>What else is running on the machine? Anything like Antivirus which might clean up the Temp folder?</li>\n</ul>\n" }, { "answer_id": 679693, "author": "tigerdahl", "author_id": 82298, "author_profile": "https://Stackoverflow.com/users/82298", "pm_score": 1, "selected": false, "text": "<p>I am experiencing the same problem on Windows Server 2003. Our ASP.NET application is consuming a web service (on an external machine across the web), and after a while we get this error message.</p>\n\n<p>Running a recycle on the app pool fixes the problem, but i'm searching for an answer to the cause of the problem.</p>\n\n<p>Anyone?</p>\n" } ]
2008/11/07
[ "https://Stackoverflow.com/questions/271285", "https://Stackoverflow.com", "https://Stackoverflow.com/users/35682/" ]
My webapp (ASP.NET 2.0) consumes a webservice (asmx on 1.1 framework) on the same machine. After getting XML in return, I pass it to `XslCompiledTransform` for transform XML to HTML and it works fine. Yesterday I got a `System.IO.FileNotFoundException` frequently and don't know what causes this kind of problem. First look I thought it's about read/write permission on c:\windows\temp and then I made sure give it full permission for Network Service (also Everybody at last -\_-!) but it doesn't help. Any ideas or solutions would be appreciate. ``` -------------------- stack trace -------------------------- Exception: **System.IO.FileNotFoundException** **Could not find file 'C:\WINDOWS\TEMP\sivvt5f6.dll'.** at System.IO.__Error**.WinIOError**(Int32 errorCode, String maybeFullPath) at System.IO.FileStream.Init(String path, FileMode mode, FileAccess access, Int32 rights, Boolean useRights, FileShare share, Int32 bufferSize, FileOptions options, SECURITY_ATTRIBUTES secAttrs, String msgPath, Boolean bFromProxy) at System.IO.FileStream..ctor(String path, FileMode mode, FileAccess access, FileShare share) at Microsoft.CSharp.CSharpCodeGenerator.FromFileBatch(CompilerParameters options, String[] fileNames) at Microsoft.CSharp.CSharpCodeGenerator.FromDomBatch(CompilerParameters options, CodeCompileUnit[] ea) at Microsoft.CSharp.CSharpCodeGenerator.System.CodeDom.Compiler.ICodeCompiler.CompileAssemblyFromDomBatch(CompilerParameters options, CodeCompileUnit[] ea) at System.CodeDom.Compiler.CodeDomProvider.CompileAssemblyFromDom(CompilerParameters options, CodeCompileUnit[] compilationUnits) at System.Xml.Xsl.Xslt.Scripts.CompileAssembly(List`1 scriptsForLang) at System.Xml.Xsl.Xslt.Scripts.CompileScripts() at System.Xml.Xsl.Xslt.QilGenerator.Compile(Compiler compiler) at System.Xml.Xsl.Xslt.**Compiler. Compile**(Object stylesheet, XmlResolver xmlResolver, QilExpression& qil) at System.Xml.Xsl.XslCompiledTransform.LoadInternal(Object stylesheet, XsltSettings settings, XmlResolver stylesheetResolver) at System.Xml.Xsl.**XslCompiledTransform.Load**(String stylesheetUri, XsltSettings settings, XmlResolver stylesheetResolver) ```
After checking for details and googling for the related topics, 1. This problem found with .Transform() and also occures with XmlSerialization as Marc said. Christoph Schittko has a good article for [troubleshooting](http://msdn.microsoft.com/en-us/library/aa302290.aspx). 2. Someone said the problem may because some update patch of windows that can change the behavior of serializer. I called my administrator to clarify if there's any changes on our server and he said nothing changes and he suggest me for restarting. and Yes... my problem has been solved by.....restarting server (windows 2003 ;)
271,319
<p>Could you recommend a lightweight SQL database which doesn't require installation on a client computer to work and could be accessed easily from .NET application? Only basic SQL capabilities are needed.</p> <p>Now I am using Access database in simple projects and distribute .MDB and .EXE files together. Looking for any alternatives.</p>
[ { "answer_id": 271322, "author": "Christian C. Salvadó", "author_id": 5445, "author_profile": "https://Stackoverflow.com/users/5445", "pm_score": 5, "selected": false, "text": "<p>Check <a href=\"http://www.sqlite.org/\" rel=\"noreferrer\">SQLite</a>, it's a software library that implements a self-contained, serverless, zero-configuration, transactional SQL database engine.</p>\n\n<p>It has many <a href=\"http://www.sqlite.org/cvstrac/wiki?p=SqliteWrappers\" rel=\"noreferrer\">wrappers</a> for .NET </p>\n" }, { "answer_id": 271325, "author": "Jarod Elliott", "author_id": 1061, "author_profile": "https://Stackoverflow.com/users/1061", "pm_score": 2, "selected": false, "text": "<p><a href=\"http://www.sqlite.org/\" rel=\"nofollow noreferrer\">SQLite</a> will be what you're after</p>\n" }, { "answer_id": 271331, "author": "stephbu", "author_id": 12702, "author_profile": "https://Stackoverflow.com/users/12702", "pm_score": 2, "selected": false, "text": "<p>Howabout SQL Server 3.5/2008 Compact Edition? A neat embedded version of SQL Server.</p>\n\n<p><a href=\"http://www.microsoft.com/Sqlserver/2008/en/us/compact.aspx\" rel=\"nofollow noreferrer\">http://www.microsoft.com/Sqlserver/2008/en/us/compact.aspx</a></p>\n\n<p>Works pretty nice with .NET, and of course all your regular SQL Server tools and scripts work fine.</p>\n" }, { "answer_id": 271336, "author": "JAG", "author_id": 16032, "author_profile": "https://Stackoverflow.com/users/16032", "pm_score": 2, "selected": false, "text": "<p><a href=\"http://www.sqlite.org/\" rel=\"nofollow noreferrer\">SQLite</a> is great.</p>\n\n<p>Also check out <a href=\"http://www.firebirdsql.org/\" rel=\"nofollow noreferrer\">Firebird</a> embedded. It might be a better option if multiple users need to access the database in the future.</p>\n" }, { "answer_id": 770940, "author": "Jason Short", "author_id": 19974, "author_profile": "https://Stackoverflow.com/users/19974", "pm_score": 2, "selected": false, "text": "<p>You could look at VistaDB if you are writing in .NET. It is 100% managed code, contains true referential integrity, tsql stored procs, clr procs, and much more in a single assembly you can xcopy deploy. </p>\n\n<p>VistaDB runs in shared hosting asp.net sites under medium trust, and in active directory domains as guest (no local permissions) as well.</p>\n\n<p>There are no registry or other configuration settings required on the machine you deploy the engine on, and the runtime is royalty free.</p>\n\n<p>32/64 bit support is included in the single assembly. Mixed mode engines with unmanaged code generally require you to ship more than 1 version of the unmanaged code to support 32 and 64 bit, or to recompile for specific CPU targets.</p>\n\n<p>See the <a href=\"https://stackoverflow.com/questions/55273/what-are-the-advantages-of-vistadb\">Advantages of VistaDB</a> SO thread for more information.</p>\n\n<p><a href=\"http://www.vistadb.net\" rel=\"nofollow noreferrer\">http://www.vistadb.net</a></p>\n" }, { "answer_id": 15044689, "author": "nawfal", "author_id": 661933, "author_profile": "https://Stackoverflow.com/users/661933", "pm_score": 6, "selected": true, "text": "<p>Depends on what you mean by lightweight. Easy on Ram? Or lighter db file? Or lighter connector to connect to db? Or fewer files over all? I'll give a comparison of what I know:</p>\n\n<pre><code> no of files cumulative size of files db size\n\nFirebird 2.5 5 6.82 MB 250 KB\n\nSqlServerCe 4 7 2.08 MB 64 KB\n\nSqlite 3.7.11.0 1 0.83 MB 15 KB\n\nVistaDb 4.3.3.34 1 1.04 MB 48 KB\n\nno of files - includes the .net connector and excludes the db file\n</code></pre>\n\n<p>The dbs are of 1 table with 2 columns and 2 rows. Take the db size with a pinch of salt as dbs could grow differently with further use. For instance <code>SqlServerCe</code> though initially was at 64 KB, it didn't grow at all after adding a few hundred records, while <code>VistaDb</code> grew easily from 48 to 72 to 140 KB. SQLite was the best in that regard which started from the lowest and grew linearly.</p>\n\n<p>Few anecdotes: I had better performance using SqlServerCe with the factory settings which means its the easiest to get kick started without any configuration, while I found Firebird little bit harder to get it started due to lack of online materials. Firebird as I could read had widest standard sql compliance. While VistaDb is written in fully managed C# which means it can be merged with your application's assembly to have one single file, it seemed slowest to me. Of all, considering performance, ease and size I chose SQLite. SqlServerCe would be my second choice.</p>\n\n<p>In short each has its pluses and minuses. Again, take my rant with a pinch of salt, its just my personal experience.</p>\n" }, { "answer_id": 35595613, "author": "AC99", "author_id": 4454932, "author_profile": "https://Stackoverflow.com/users/4454932", "pm_score": 2, "selected": false, "text": "<p>You can store your data as JSON files. If you need it to be stand-alone, there are dll solutions such as <a href=\"http://www.iodb.ca\" rel=\"nofollow\">IODB</a> and <a href=\"http://www.litedb.org\" rel=\"nofollow\">LiteDB</a> </p>\n" } ]
2008/11/07
[ "https://Stackoverflow.com/questions/271319", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11256/" ]
Could you recommend a lightweight SQL database which doesn't require installation on a client computer to work and could be accessed easily from .NET application? Only basic SQL capabilities are needed. Now I am using Access database in simple projects and distribute .MDB and .EXE files together. Looking for any alternatives.
Depends on what you mean by lightweight. Easy on Ram? Or lighter db file? Or lighter connector to connect to db? Or fewer files over all? I'll give a comparison of what I know: ``` no of files cumulative size of files db size Firebird 2.5 5 6.82 MB 250 KB SqlServerCe 4 7 2.08 MB 64 KB Sqlite 3.7.11.0 1 0.83 MB 15 KB VistaDb 4.3.3.34 1 1.04 MB 48 KB no of files - includes the .net connector and excludes the db file ``` The dbs are of 1 table with 2 columns and 2 rows. Take the db size with a pinch of salt as dbs could grow differently with further use. For instance `SqlServerCe` though initially was at 64 KB, it didn't grow at all after adding a few hundred records, while `VistaDb` grew easily from 48 to 72 to 140 KB. SQLite was the best in that regard which started from the lowest and grew linearly. Few anecdotes: I had better performance using SqlServerCe with the factory settings which means its the easiest to get kick started without any configuration, while I found Firebird little bit harder to get it started due to lack of online materials. Firebird as I could read had widest standard sql compliance. While VistaDb is written in fully managed C# which means it can be merged with your application's assembly to have one single file, it seemed slowest to me. Of all, considering performance, ease and size I chose SQLite. SqlServerCe would be my second choice. In short each has its pluses and minuses. Again, take my rant with a pinch of salt, its just my personal experience.
271,330
<p>I use <a href="http://docs.jquery.com/Plugins/Treeview" rel="nofollow noreferrer">jquery tree plugin</a> to render hierarchical data. </p> <p>I have coded additional functions which would allow user to interact with this data (like adding/deleting nodes, swapping nodes, etc...)</p> <p>Currently this plugin supports that whenever you want to add any node, you can call following method,</p> <pre><code>$("#browser").treeview({ add: branches }); </code></pre> <p>here <code>branches</code> is <code>jQuery object</code> created with the HTML block, which would represent a particular node.</p> <p>However, for delete and swapping of nodes, I use common JQuery functions like,</p> <p><strong>for delete,</strong></p> <pre><code>$("#topnd2").remove(); </code></pre> <p><strong>for swapping,</strong></p> <pre><code>var next = $("#topnd2").next(); $("#topnd2").insertAfter(next); </code></pre> <p><code>topnd2</code> is an <code>id</code> of any particular tree node.</p> <p>The nodes get deleted / swapped properly but the problem is the tree does not get rendered and therefore the tree images (mainly vertical lines denoting branches) are not set properly.</p> <p>For example, if I delete the last node then that node will be removed from rendered treeview but the remaining sibling node should get L as branch line image but not | .</p> <p>I tried calling </p> <p><code>$("#browser").treeview();</code> </p> <p>Please let me know your ideas.</p> <p>Thanks, Jatan</p>
[ { "answer_id": 271382, "author": "jatanp", "author_id": 959, "author_profile": "https://Stackoverflow.com/users/959", "pm_score": 1, "selected": false, "text": "<p>I found some workaround as given below,</p>\n\n<p>Once the node is swapped up, virtually add its previous node to its child,</p>\n\n<p>$(\"#browser\").treeview({add:$(\"#topnd2\").insertBefore(previous).next()});</p>\n\n<p>If node is swapped down, virtuall add the current node to its next node.</p>\n\n<p>$(\"#browser\").treeview({add:$(\"#topnd2\").insertAfter(next)});</p>\n\n<p>currently it's working fine, will update this post, if I find any problems in this approach. Also please validate this approach if you know.</p>\n\n<p>Regards,\nJatan</p>\n" }, { "answer_id": 2241672, "author": "Norleb", "author_id": 270765, "author_profile": "https://Stackoverflow.com/users/270765", "pm_score": 0, "selected": false, "text": "<p>If you try to refresh the treeview again after node removal, the link will work but not the [+] or [-] icon. Tried this on several browsers..</p>\n" } ]
2008/11/07
[ "https://Stackoverflow.com/questions/271330", "https://Stackoverflow.com", "https://Stackoverflow.com/users/959/" ]
I use [jquery tree plugin](http://docs.jquery.com/Plugins/Treeview) to render hierarchical data. I have coded additional functions which would allow user to interact with this data (like adding/deleting nodes, swapping nodes, etc...) Currently this plugin supports that whenever you want to add any node, you can call following method, ``` $("#browser").treeview({ add: branches }); ``` here `branches` is `jQuery object` created with the HTML block, which would represent a particular node. However, for delete and swapping of nodes, I use common JQuery functions like, **for delete,** ``` $("#topnd2").remove(); ``` **for swapping,** ``` var next = $("#topnd2").next(); $("#topnd2").insertAfter(next); ``` `topnd2` is an `id` of any particular tree node. The nodes get deleted / swapped properly but the problem is the tree does not get rendered and therefore the tree images (mainly vertical lines denoting branches) are not set properly. For example, if I delete the last node then that node will be removed from rendered treeview but the remaining sibling node should get L as branch line image but not | . I tried calling `$("#browser").treeview();` Please let me know your ideas. Thanks, Jatan
I found some workaround as given below, Once the node is swapped up, virtually add its previous node to its child, $("#browser").treeview({add:$("#topnd2").insertBefore(previous).next()}); If node is swapped down, virtuall add the current node to its next node. $("#browser").treeview({add:$("#topnd2").insertAfter(next)}); currently it's working fine, will update this post, if I find any problems in this approach. Also please validate this approach if you know. Regards, Jatan
271,340
<p>I'm trying to use a dojo combobox with an Ajax data source. What I have is </p> <pre><code>&lt;div dojoType="dojo.data.ItemFileReadStore" jsId="tags" url="&lt;%=ResolveClientUrl("~/Tag/TagMatches")%&gt;" &gt; &lt;/div&gt; &lt;select dojoType="dijit.form.ComboBox" store="tags" value="" name="tagName"&gt; &lt;/select&gt; </code></pre> <p>Which does work except that I can't restrict the search set on the server side because I don't know how to change the url from which the data is pulled in order to specify a parameter. Any hints? </p>
[ { "answer_id": 271443, "author": "Tomalak", "author_id": 18771, "author_profile": "https://Stackoverflow.com/users/18771", "pm_score": 2, "selected": true, "text": "<p>If I understand you correctly, you want the client to load different set of data from the server based on some general condition defined elsewhere.</p>\n\n<p>Basically there is no need to have a <code>&lt;div&gt;</code> pre-defined. You can also create the <code>ItemFileReadStore</code> directly in JavaScript:</p>\n\n<p>earlier...:</p>\n\n<pre><code>var tagMatchUrlBase = '&lt;%=ResolveClientUrl(\"~/Tag/TagMatches\")%&gt;';\n</code></pre>\n\n<p>later...:</p>\n\n<pre><code>var tagMatchUrl = tagMatchUrlBase + \"?f=\" + escape(somefilterString);\nvar store = new dojo.data.ItemFileReadStore({url: tagMatchUrl});\ntagName.store = store;\n// maybe use store.fetch() to pre-select item #1\n</code></pre>\n" }, { "answer_id": 352283, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 0, "selected": false, "text": "<p>Typically this isn't done with ItemFileReadStore, which is designed to download all the data up front rather than filtering on the server.</p>\n\n<p>Rather, you should use <a href=\"http://docs.dojocampus.org/dojox/data/QueryReadStore\" rel=\"nofollow noreferrer\">QueryReadStore</a>, <a href=\"http://docs.dojocampus.org/dojox/data/JsonRestStore\" rel=\"nofollow noreferrer\">JsonReadStore</a>, etc.</p>\n" } ]
2008/11/07
[ "https://Stackoverflow.com/questions/271340", "https://Stackoverflow.com", "https://Stackoverflow.com/users/361/" ]
I'm trying to use a dojo combobox with an Ajax data source. What I have is ``` <div dojoType="dojo.data.ItemFileReadStore" jsId="tags" url="<%=ResolveClientUrl("~/Tag/TagMatches")%>" > </div> <select dojoType="dijit.form.ComboBox" store="tags" value="" name="tagName"> </select> ``` Which does work except that I can't restrict the search set on the server side because I don't know how to change the url from which the data is pulled in order to specify a parameter. Any hints?
If I understand you correctly, you want the client to load different set of data from the server based on some general condition defined elsewhere. Basically there is no need to have a `<div>` pre-defined. You can also create the `ItemFileReadStore` directly in JavaScript: earlier...: ``` var tagMatchUrlBase = '<%=ResolveClientUrl("~/Tag/TagMatches")%>'; ``` later...: ``` var tagMatchUrl = tagMatchUrlBase + "?f=" + escape(somefilterString); var store = new dojo.data.ItemFileReadStore({url: tagMatchUrl}); tagName.store = store; // maybe use store.fetch() to pre-select item #1 ```
271,347
<p>I have a class that stores a serialized value and a type. I want to have a property/method returning the value already casted:</p> <pre><code>public String Value { get; set; } public Type TheType { get; set; } public typeof(TheType) CastedValue { get { return Convert.ChangeType(Value, typeof(_Type)); } </code></pre> <p>Is this possible in C#?</p>
[ { "answer_id": 271356, "author": "Brannon", "author_id": 5745, "author_profile": "https://Stackoverflow.com/users/5745", "pm_score": 7, "selected": false, "text": "<p>It's possible if the class containing the property is generic, and you declare the property using the generic parameter:</p>\n\n<pre><code>class Foo&lt;TValue&gt; {\n public string Value { get; set; }\n public TValue TypedValue {\n get {\n return (TValue)Convert.ChangeType(Value, typeof(TValue));\n }\n }\n}\n</code></pre>\n\n<p>An alternative would be to use a generic method instead:</p>\n\n<pre><code>class Foo {\n public string Value { get; set; }\n public Type TheType { get; set; }\n\n public T CastValue&lt;T&gt;() {\n return (T)Convert.ChangeType(Value, typeof(T));\n }\n}\n</code></pre>\n\n<p>You can also use the <code>System.ComponentModel.TypeConverter</code> classes to convert, since they allow a class to define it's own converter.</p>\n\n<p><strong>Edit</strong>: note that when calling the generic method, you must specify the generic type parameter, since the compiler has no way to infer it:</p>\n\n<pre><code>Foo foo = new Foo();\nfoo.Value = \"100\";\nfoo.Type = typeof(int);\n\nint c = foo.CastValue&lt;int&gt;();\n</code></pre>\n\n<p>You have to know the type at compile time. If you don't know the type at compile time then you must be storing it in an <code>object</code>, in which case you can add the following property to the <code>Foo</code> class:</p>\n\n<pre><code>public object ConvertedValue {\n get {\n return Convert.ChangeType(Value, Type);\n }\n}\n</code></pre>\n" }, { "answer_id": 271358, "author": "Charlie", "author_id": 18529, "author_profile": "https://Stackoverflow.com/users/18529", "pm_score": 3, "selected": false, "text": "<p>I don't believe the example you've given here is possible. The type of CastedValue has to be defined at compile time, which means it can't depend on a runtime value (the value of the TheType property).</p>\n\n<p>EDIT: Brannon's solution has some good ideas for how to handle this using a generic function rather than a property.</p>\n" }, { "answer_id": 271376, "author": "Jon Skeet", "author_id": 22656, "author_profile": "https://Stackoverflow.com/users/22656", "pm_score": 6, "selected": false, "text": "<p>Properties, events, constructors etc can't be generic - only methods and types can be generic. Most of the time that's not a problem, but I agree that sometimes it's a pain. Brannon's answer gives two reasonable workarounds.</p>\n" } ]
2008/11/07
[ "https://Stackoverflow.com/questions/271347", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
I have a class that stores a serialized value and a type. I want to have a property/method returning the value already casted: ``` public String Value { get; set; } public Type TheType { get; set; } public typeof(TheType) CastedValue { get { return Convert.ChangeType(Value, typeof(_Type)); } ``` Is this possible in C#?
It's possible if the class containing the property is generic, and you declare the property using the generic parameter: ``` class Foo<TValue> { public string Value { get; set; } public TValue TypedValue { get { return (TValue)Convert.ChangeType(Value, typeof(TValue)); } } } ``` An alternative would be to use a generic method instead: ``` class Foo { public string Value { get; set; } public Type TheType { get; set; } public T CastValue<T>() { return (T)Convert.ChangeType(Value, typeof(T)); } } ``` You can also use the `System.ComponentModel.TypeConverter` classes to convert, since they allow a class to define it's own converter. **Edit**: note that when calling the generic method, you must specify the generic type parameter, since the compiler has no way to infer it: ``` Foo foo = new Foo(); foo.Value = "100"; foo.Type = typeof(int); int c = foo.CastValue<int>(); ``` You have to know the type at compile time. If you don't know the type at compile time then you must be storing it in an `object`, in which case you can add the following property to the `Foo` class: ``` public object ConvertedValue { get { return Convert.ChangeType(Value, Type); } } ```
271,364
<p><code>:vimgrep</code> looks like a really useful thing.</p> <p>Here's how to use it:</p> <pre><code>:vim[grep][!] /{pattern}/[g][j] {file} ... </code></pre> <p><code>:help</code> says that you can essentially glob <code>{file}</code> to name, say, <code>*.c</code> for the current directory. I may have started Vim with a list of files that is complicated enough that I don't want to manually type it in for <code>{file}</code>, and besides Vim already knows what those files are.</p> <p>What I would like to do is vimgrep over any of:</p> <ul> <li><code>:args</code></li> <li><code>:files</code></li> <li><code>:buffers</code></li> </ul> <p>What variable(s) would I use in place of <code>{file}</code> to name, respectively, any of those lists in a <code>vimgrep</code> command?</p>
[ { "answer_id": 271381, "author": "Jerub", "author_id": 14648, "author_profile": "https://Stackoverflow.com/users/14648", "pm_score": 3, "selected": false, "text": "<p>You can do this:</p>\n\n<pre><code>:bufdo vimgrep /pattern/ %\n</code></pre>\n\n<p>% substitutes the buffer name.</p>\n" }, { "answer_id": 271709, "author": "Luc Hermitte", "author_id": 15934, "author_profile": "https://Stackoverflow.com/users/15934", "pm_score": 5, "selected": true, "text": "<p>Can't you catch the result in these commands into a register (<code>:h :redir</code>), and insert it back into <code>:vimgrep</code> call (with a <code>:exe</code>).</p>\n\n<p>Something like:</p>\n\n<pre><code>:exe \"vimgrep/pattern/ \" . lh#askvim#Exe(':args')\n</code></pre>\n\n<p>Notes:</p>\n\n<ul>\n<li><a href=\"https://github.com/LucHermitte/lh-vim-lib#miscellaneous-functions\" rel=\"nofollow noreferrer\">lh#askvim#Exe</a> is just a wrapper around <code>:redir</code> ; nothing really complex</li>\n<li>some of these results may need some processing (see <code>:args</code> that adds square brackets)</li>\n<li>Sometimes there is a function that returns exactly what you are looking for, see <code>join(argv(), ' ')</code> in <code>:args</code> case</li>\n<li>Regarding :buffers, may be something like:</li>\n</ul>\n\n<p>.</p>\n\n<pre><code>function BuffersList()\n let all = range(0, bufnr('$'))\n let res = []\n for b in all\n if buflisted(b)\n call add(res, bufname(b))\n endif\n endfor\n return res\nendfunction\n:exe 'vimgrep/pattern/ '.join(BuffersList(),' ')\n</code></pre>\n" }, { "answer_id": 8414211, "author": "baltazar", "author_id": 258421, "author_profile": "https://Stackoverflow.com/users/258421", "pm_score": 2, "selected": false, "text": "<p>Here is a slightly refined version of one of the answers. The following command searches for the pattern in all opened tabs and remembers results in quickfix list:</p>\n\n<pre><code>:cex [] | tabdo vimgrepa /pattern/ %\n</code></pre>\n\n<p><code>cex []</code> sets contents of quickfix list to empty list. You need to call it first because <code>vimgrepa</code> accumulates search results from all the tabs. Also, you can replace <code>tabdo</code> with <code>argdo</code>, <code>bufdo</code> and <code>windo</code>.</p>\n\n<p>To view search results execute:</p>\n\n<pre><code>:cope\n</code></pre>\n\n<p>This method, however, has limitation: it can only search in tabs which already have file names assigned to them (<code>%</code> would not expand in a new tab).</p>\n\n<p><strong>EDIT:</strong>\nYou can also shortcut the command into function in your <code>~/.vimrc</code> like this:</p>\n\n<pre><code>function TS(text)\n exe \"cex [] | tabdo vimgrepa /\" . a:text . \"/ %\"\nendfunction\ncommand -nargs=1 TS call TS(&lt;q-args&gt;)\ncnoreabbrev ts TS\n</code></pre>\n\n<p>With last line you can call your function like this:</p>\n\n<pre><code>:ts from game import\n</code></pre>\n\n<p>where words after <code>ts</code> is a search pattern. Without last line you have to type function name in upper case.</p>\n" }, { "answer_id": 19365379, "author": "Steve", "author_id": 1173869, "author_profile": "https://Stackoverflow.com/users/1173869", "pm_score": 3, "selected": false, "text": "<p>To [vim]grep the list of files in the argument list, you may use <code>##</code> (see <code>:help cmdline-special</code>).</p>\n\n<pre><code>:vimgrep /re/ ##\n</code></pre>\n\n<p>I am unaware of a similar shorthand for the buffer list, but you may be able to do something like:</p>\n\n<pre><code>:argdelete ##\n:bufdo argadd %\n</code></pre>\n\n<p>... and then use <code>##</code>. Or use <code>:n</code> to open new files (which will be added to the arg list) instead of <code>:e</code>.</p>\n" }, { "answer_id": 72390199, "author": "Gil Fine", "author_id": 15707183, "author_profile": "https://Stackoverflow.com/users/15707183", "pm_score": 0, "selected": false, "text": "<p>Very helpful script !\nA minor fix: The search finds one of the buffers twice - first time as the numbered buffer, second as buffer #0 =&gt; alternate buffer.\nHence, we shall change the line to &quot;<strong>range(1, bufnr('$'))</strong>&quot; to skip the alternate buffer and show the search results once.</p>\n" } ]
2008/11/07
[ "https://Stackoverflow.com/questions/271364", "https://Stackoverflow.com", "https://Stackoverflow.com/users/35221/" ]
`:vimgrep` looks like a really useful thing. Here's how to use it: ``` :vim[grep][!] /{pattern}/[g][j] {file} ... ``` `:help` says that you can essentially glob `{file}` to name, say, `*.c` for the current directory. I may have started Vim with a list of files that is complicated enough that I don't want to manually type it in for `{file}`, and besides Vim already knows what those files are. What I would like to do is vimgrep over any of: * `:args` * `:files` * `:buffers` What variable(s) would I use in place of `{file}` to name, respectively, any of those lists in a `vimgrep` command?
Can't you catch the result in these commands into a register (`:h :redir`), and insert it back into `:vimgrep` call (with a `:exe`). Something like: ``` :exe "vimgrep/pattern/ " . lh#askvim#Exe(':args') ``` Notes: * [lh#askvim#Exe](https://github.com/LucHermitte/lh-vim-lib#miscellaneous-functions) is just a wrapper around `:redir` ; nothing really complex * some of these results may need some processing (see `:args` that adds square brackets) * Sometimes there is a function that returns exactly what you are looking for, see `join(argv(), ' ')` in `:args` case * Regarding :buffers, may be something like: . ``` function BuffersList() let all = range(0, bufnr('$')) let res = [] for b in all if buflisted(b) call add(res, bufname(b)) endif endfor return res endfunction :exe 'vimgrep/pattern/ '.join(BuffersList(),' ') ```
271,380
<p>One of the files in my current head revision got corrupted. I want to make an older revision of that file the head revision as usually people sync to head revsion in my project. How to do that?</p>
[ { "answer_id": 271387, "author": "Martin v. Löwis", "author_id": 33006, "author_profile": "https://Stackoverflow.com/users/33006", "pm_score": 7, "selected": true, "text": "<p>You should revert all changes since that old reversion. In principle,</p>\n\n<pre><code>svn merge -rHEAD:oldrev filename\nsvn commit -m \"rolled back to oldrev\"\n</code></pre>\n\n<p>should do. The later revisions are still there, but reverted.</p>\n" }, { "answer_id": 271390, "author": "Christian C. Salvadó", "author_id": 5445, "author_profile": "https://Stackoverflow.com/users/5445", "pm_score": 4, "selected": false, "text": "<p>You should do a <a href=\"http://svnbook.red-bean.com/en/1.2/svn.branchmerge.commonuses.html#svn.branchmerge.commonuses.undo\" rel=\"noreferrer\">reverse merge</a>.</p>\n" } ]
2008/11/07
[ "https://Stackoverflow.com/questions/271380", "https://Stackoverflow.com", "https://Stackoverflow.com/users/13440/" ]
One of the files in my current head revision got corrupted. I want to make an older revision of that file the head revision as usually people sync to head revsion in my project. How to do that?
You should revert all changes since that old reversion. In principle, ``` svn merge -rHEAD:oldrev filename svn commit -m "rolled back to oldrev" ``` should do. The later revisions are still there, but reverted.
271,394
<p>A class I am taking currently requires us to do all of our coding in smalltalk (it's a Design class). On one of our projects, I am looking to do some things, and am having a tough time finding how to do them. It seems that what most people do is modify their own version of smalltalk to do what they need it to do. I am not at liberty to do this, as this would cause an error on my prof's computer when he doesn't have the same built-in methods I do.</p> <p>Here's what I'm looking to do:</p> <p>Random Numbers. I need to create a random number between 1 and 1000. Right now I'm faking it by doing </p> <pre><code>rand := Random new. rand := (rand nextValue) * 1000. rand := rand asInteger. </code></pre> <p>This gives me a number between 0 and 1000. Is there a way to do this in one command? similar to </p> <pre><code>Random between: 0 and: 1000 </code></pre> <p>And/Or statements. This one bugs the living daylights out of me. I have tried several different configurations of </p> <pre><code>(statement) and: (statement) ifTrue... (statement) and (statement) ifTrue... </code></pre> <p>So I'm faking it with nested ifTrue statements:</p> <pre><code>(statement) ifTrue:[ (statement) ifTrue:[... </code></pre> <p>What is the correct way to do and/or and Random in smalltalk?</p>
[ { "answer_id": 271402, "author": "Martin v. Löwis", "author_id": 33006, "author_profile": "https://Stackoverflow.com/users/33006", "pm_score": 4, "selected": true, "text": "<p>The problem is that</p>\n\n<pre><code> (expr) and: (expr) ifTrue: aBlock\n</code></pre>\n\n<p>is parsed as the method <code>and:ifTrue:</code> If you look at the Boolean class (and either True or False in particular), you notice that ifTrue: is just a regular method, and that no method and:ifTrue: exists - however, plain and: does. So to make it clear that these are two messages, write</p>\n\n<pre><code>((expr) and: (expr)) ifTrue: aBlock\n</code></pre>\n\n<p>For longer boolean combinations, notice that there are also methods and:and: and and:and:and: implemented.</p>\n" }, { "answer_id": 271500, "author": "Martin v. Löwis", "author_id": 33006, "author_profile": "https://Stackoverflow.com/users/33006", "pm_score": 2, "selected": false, "text": "<p>As for the Random issue: it depends on what ST version you use. In Squeak 3.9, there is <code>Random&gt;&gt;#nextInt:</code>, which is documented as \"Answer a random integer in the interval [1, anInteger].\". Its implementation reads</p>\n\n<pre><code>(self next * anInteger) truncated + 1\n</code></pre>\n\n<p>So I have two comments here:</p>\n\n<ol>\n<li>You should really learn to use the class browser. This can answer the (frequent) questions \"what messages can I send to objects of class X\"</li>\n<li><p>It is common, in ST, to add new methods to existing classes. So if you want Random to have between:and:, just add it, e.g. as</p>\n\n<pre><code>between: low and: high \n ^(self next * (high-low+1)) truncated + low\n</code></pre></li>\n</ol>\n" }, { "answer_id": 285651, "author": "Rydier", "author_id": 22434, "author_profile": "https://Stackoverflow.com/users/22434", "pm_score": 3, "selected": false, "text": "<p>If you're using VisualWorks, and: takes a block as an argument, so you'd write:</p>\n\n<pre><code>(aBoolean and: [anotherBoolean]) ifTrue: [doSomething].\n</code></pre>\n\n<p>There's also <code>&amp;</code>, which does not take a block as argument,</p>\n\n<pre><code>aBoolean &amp; anotherBoolean ifTrue:[doSomething].\n</code></pre>\n\n<p>The difference is and: only evaluates what's in the block if the first bool is true (similar to java), while <code>&amp;</code> always evaluates both.</p>\n\n<p>Thus <code>and:</code> comes in handy if the second condition is computationally expensive, or if it includes state alterations which should only happen when the first condition is true. (that's usually a bad design though).</p>\n\n<p>As for the Random, as long as you deliver your custom method, <code>Random &gt;&gt; between: and:</code> as well as the rest of your code, it runs fine on your professors computer. How to do that specifically, depends on the format in which you are supposed to deliver the assignment.</p>\n" }, { "answer_id": 311121, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 3, "selected": false, "text": "<pre><code>(1 to: 1000) atRandom\n</code></pre>\n" }, { "answer_id": 33855293, "author": "Euan M", "author_id": 1970590, "author_profile": "https://Stackoverflow.com/users/1970590", "pm_score": 0, "selected": false, "text": "<p><strong>To create several random integers between 1 and 1000</strong><br>\nFirst create a random number series. Do this just once.</p>\n\n<p>Then create a new random number by taking the next number from the series. Repeat as necessary.</p>\n\n<pre><code>aRandomSeries := Random new .\n \"Seed a new series of random numbers\" \n\naRandomInt := aRandomSeries newInt: 1000 . \n \"generate a random integer between 0 and 1000\"\n\nanotherRandomInt := aRandomSeries newInt: 1000 .\n \"generate another random integer between 0 and 1000\"\n</code></pre>\n\n<p><strong>Logical operations</strong></p>\n\n<p><code>aBoolean</code> will respond to <code>and:</code> and <code>or:</code>. They both take <em>block arguments</em>.</p>\n\n<p>Here is how they work.</p>\n\n<p><code>and: alternativeBlock</code><br>\nIf the receiver is true, answer the value of alternativeBlock; otherwise answer false without evaluating alternativeBlock.</p>\n\n<p><code>or: alternativeBlock</code><br>\nIf the receiver is false, answer the value of alternativeBlock; otherwise answer true without evaluating alternativeBlock.</p>\n\n<p>e.g.<br>\n<code>( 3 &gt; 2 ) or: [ 3 &lt; 4 ] ifTrue: [ ]</code><br>\n<code>aBoolean and: [ anotherBoolean ] ifFalse: [ ]</code></p>\n\n<p>However, Squeak and Pharo Smalltalks will both accept an argument in parentheses <code>( )</code><br>\nDolphin Smalltalk will not, and strictly requires the standard Smalltalk syntax of a block argument.</p>\n\n<p><strong>Other related methods:</strong><br>\n<code>&amp;</code> an <em>AND</em> that does not require a square bracketted (i.e. block) argument<br>\n<code>|</code> an <em>OR</em> that does not require a square bracketted (i.e. block) argument<br>\n<code>&amp;</code> and <code>|</code> work in Amber, Cuis, Gnu, Pharo, Squeak, VisualAge and VisualWorks Smalltalks. </p>\n\n<p>Squeak Smalltalk also provides:<br>\n<code>and:and: }</code><br>\n<code>and:and:and: }</code> These take multiple block arguments<br>\n<code>and:and:and:and }</code></p>\n\n<p><code>or:or: }</code><br>\n<code>or:or:or: }</code> These take multiple block arguments<br>\n<code>or:or:or:or: }</code></p>\n" }, { "answer_id": 33866017, "author": "John Pfersich", "author_id": 5561176, "author_profile": "https://Stackoverflow.com/users/5561176", "pm_score": 0, "selected": false, "text": "<p>To put it simply, without knowing the Smalltalk dialect, I can only give a general answer. The way you stated the random question, yes that's the only way to do it if your professor needs a generic answer.</p>\n\n<p>As for the and/or statements question,</p>\n\n<blockquote>\n <p>And/Or statements. This one bugs the living daylights out of me. I have tried several different configurations of</p>\n</blockquote>\n\n<pre><code>(statement) and: (statement) ifTrue...\n(statement) and (statement) ifTrue...\n</code></pre>\n\n<p>What you want to try is:</p>\n\n<pre><code>(statement) and: [statement] ifTrue: [ ... ]\n</code></pre>\n\n<p>note the brackets, the and: method takes a block as an argument.</p>\n" } ]
2008/11/07
[ "https://Stackoverflow.com/questions/271394", "https://Stackoverflow.com", "https://Stackoverflow.com/users/50/" ]
A class I am taking currently requires us to do all of our coding in smalltalk (it's a Design class). On one of our projects, I am looking to do some things, and am having a tough time finding how to do them. It seems that what most people do is modify their own version of smalltalk to do what they need it to do. I am not at liberty to do this, as this would cause an error on my prof's computer when he doesn't have the same built-in methods I do. Here's what I'm looking to do: Random Numbers. I need to create a random number between 1 and 1000. Right now I'm faking it by doing ``` rand := Random new. rand := (rand nextValue) * 1000. rand := rand asInteger. ``` This gives me a number between 0 and 1000. Is there a way to do this in one command? similar to ``` Random between: 0 and: 1000 ``` And/Or statements. This one bugs the living daylights out of me. I have tried several different configurations of ``` (statement) and: (statement) ifTrue... (statement) and (statement) ifTrue... ``` So I'm faking it with nested ifTrue statements: ``` (statement) ifTrue:[ (statement) ifTrue:[... ``` What is the correct way to do and/or and Random in smalltalk?
The problem is that ``` (expr) and: (expr) ifTrue: aBlock ``` is parsed as the method `and:ifTrue:` If you look at the Boolean class (and either True or False in particular), you notice that ifTrue: is just a regular method, and that no method and:ifTrue: exists - however, plain and: does. So to make it clear that these are two messages, write ``` ((expr) and: (expr)) ifTrue: aBlock ``` For longer boolean combinations, notice that there are also methods and:and: and and:and:and: implemented.
271,398
<p>Let's make a list of answers where you post your excellent and favorite <a href="http://en.wikipedia.org/wiki/Extension_method" rel="nofollow noreferrer">extension methods</a>. </p> <p>The requirement is that the full code must be posted and a example and an explanation on how to use it.</p> <p>Based on the high interest in this topic I have setup an Open Source Project called extensionoverflow on <a href="http://www.codeplex.com/extensionoverflow" rel="nofollow noreferrer"><strong>Codeplex</strong></a>. </p> <p><strong>Please mark your answers with an acceptance to put the code in the Codeplex project.</strong></p> <p><strong>Please post the full sourcecode and not a link.</strong></p> <p><strong>Codeplex News:</strong></p> <p>24.08.2010 The Codeplex page is now here: <a href="http://extensionoverflow.codeplex.com/" rel="nofollow noreferrer">http://extensionoverflow.codeplex.com/</a></p> <p>11.11.2008 <strong>XmlSerialize / XmlDeserialize</strong> is now <a href="http://www.codeplex.com/extensionoverflow/SourceControl/FileView.aspx?itemId=284374&amp;changeSetId=17001" rel="nofollow noreferrer">Implemented</a> and <a href="http://www.codeplex.com/extensionoverflow/SourceControl/FileView.aspx?itemId=288847&amp;changeSetId=17001" rel="nofollow noreferrer">Unit Tested</a>.</p> <p>11.11.2008 There is still room for more developers. ;-) <strong>Join NOW!</strong></p> <p>11.11.2008 Third contributer joined <a href="http://www.codeplex.com/extensionoverflow" rel="nofollow noreferrer">ExtensionOverflow</a>, welcome to <a href="http://www.codeplex.com/site/users/view/BKristensen" rel="nofollow noreferrer">BKristensen</a></p> <p>11.11.2008 <strong>FormatWith</strong> is now <a href="http://www.codeplex.com/extensionoverflow/SourceControl/FileView.aspx?itemId=284374&amp;changeSetId=16839" rel="nofollow noreferrer">Implemented</a> and <a href="http://www.codeplex.com/extensionoverflow/SourceControl/FileView.aspx?itemId=288847&amp;changeSetId=16839" rel="nofollow noreferrer">Unit Tested</a>.</p> <p>09.11.2008 Second contributer joined <a href="http://www.codeplex.com/extensionoverflow" rel="nofollow noreferrer">ExtensionOverflow</a>. welcome to <a href="https://stackoverflow.com/users/3055/chakrit">chakrit</a>.</p> <p>09.11.2008 We need more developers. ;-)</p> <p>09.11.2008 <strong>ThrowIfArgumentIsNull</strong> in now <a href="http://www.codeplex.com/extensionoverflow/SourceControl/FileView.aspx?itemId=278942&amp;changeSetId=16468" rel="nofollow noreferrer">Implemented</a> and <a href="http://www.codeplex.com/extensionoverflow/SourceControl/FileView.aspx?itemId=284112&amp;changeSetId=16468" rel="nofollow noreferrer">Unit Tested</a> on Codeplex.</p>
[ { "answer_id": 271409, "author": "bovium", "author_id": 11135, "author_profile": "https://Stackoverflow.com/users/11135", "pm_score": 5, "selected": false, "text": "<p>The ThrowIfArgumentIsNull is a nice way to do that null check we all should do.</p>\n\n<pre><code>public static class Extensions\n{\n public static void ThrowIfArgumentIsNull&lt;T&gt;(this T obj, string parameterName) where T : class\n {\n if (obj == null) throw new ArgumentNullException(parameterName + \" not allowed to be null\");\n }\n}\n</code></pre>\n\n<p>Below is the way to use it and it works on all classes in your namespace or wherever you use the namespace its within.</p>\n\n<pre><code>internal class Test\n{\n public Test(string input1)\n {\n input1.ThrowIfArgumentIsNull(\"input1\");\n }\n}\n</code></pre>\n\n<p><strong>It's ok to use this code on the <a href=\"http://www.codeplex.com/extensionmethod\" rel=\"noreferrer\">CodePlex</a> project.</strong> </p>\n" }, { "answer_id": 271411, "author": "chakrit", "author_id": 3055, "author_profile": "https://Stackoverflow.com/users/3055", "pm_score": 7, "selected": false, "text": "<p>string.Format shortcut:</p>\n\n<pre><code>public static class StringExtensions\n{\n // Enable quick and more natural string.Format calls\n public static string F(this string s, params object[] args)\n {\n return string.Format(s, args);\n }\n}\n</code></pre>\n\n<p>Example:</p>\n\n<pre><code>var s = \"The co-ordinate is ({0}, {1})\".F(point.X, point.Y);\n</code></pre>\n\n<p>For quick copy-and-paste go <a href=\"http://pastebin.com/f3e2a94d6\" rel=\"nofollow noreferrer\">here</a>.</p>\n\n<p>Don't you find it more natural to type <code>\"some string\".F(\"param\")</code> instead of <code>string.Format(\"some string\", \"param\")</code> ?</p>\n\n<p>For a more <em>readable</em> name, try one of these suggestion:</p>\n\n<pre><code>s = \"Hello {0} world {1}!\".Fmt(\"Stack\", \"Overflow\");\ns = \"Hello {0} world {1}!\".FormatBy(\"Stack\", \"Overflow\");\ns = \"Hello {0} world {1}!\".FormatWith(\"Stack\", \"Overflow\");\ns = \"Hello {0} world {1}!\".Display(\"Stack\", \"Overflow\");\ns = \"Hello {0} world {1}!\".With(\"Stack\", \"Overflow\");\n</code></pre>\n\n<p>..</p>\n" }, { "answer_id": 271414, "author": "sontek", "author_id": 17176, "author_profile": "https://Stackoverflow.com/users/17176", "pm_score": 5, "selected": false, "text": "<p><a href=\"http://www.gitorious.org/cadenza\" rel=\"nofollow noreferrer\">gitorious.org/cadenza</a> is a full library of some of the most useful extension methods I've seen.</p>\n" }, { "answer_id": 271418, "author": "Christian C. Salvadó", "author_id": 5445, "author_profile": "https://Stackoverflow.com/users/5445", "pm_score": 4, "selected": false, "text": "<p>Convert a double to string formatted using the specified culture:</p>\n\n<pre><code>public static class ExtensionMethods \n{\n public static string ToCurrency(this double value, string cultureName)\n {\n CultureInfo currentCulture = new CultureInfo(cultureName);\n return (string.Format(currentCulture, \"{0:C}\", value));\n }\n}\n</code></pre>\n\n<p>Example:</p>\n\n<pre><code>double test = 154.20;\nstring testString = test.ToCurrency(\"en-US\"); // $154.20\n</code></pre>\n" }, { "answer_id": 271421, "author": "mlarsen", "author_id": 17700, "author_profile": "https://Stackoverflow.com/users/17700", "pm_score": 5, "selected": false, "text": "<pre><code>public static class StringExtensions {\n\n /// &lt;summary&gt;\n /// Parses a string into an Enum\n /// &lt;/summary&gt;\n /// &lt;typeparam name=\"T\"&gt;The type of the Enum&lt;/typeparam&gt;\n /// &lt;param name=\"value\"&gt;String value to parse&lt;/param&gt;\n /// &lt;returns&gt;The Enum corresponding to the stringExtensions&lt;/returns&gt;\n public static T EnumParse&lt;T&gt;(this string value) {\n return StringExtensions.EnumParse&lt;T&gt;(value, false);\n }\n\n public static T EnumParse&lt;T&gt;(this string value, bool ignorecase) {\n\n if (value == null) {\n throw new ArgumentNullException(\"value\");\n }\n\n value = value.Trim();\n\n if (value.Length == 0) {\n throw new ArgumentException(\"Must specify valid information for parsing in the string.\", \"value\");\n }\n\n Type t = typeof(T);\n\n if (!t.IsEnum) {\n throw new ArgumentException(\"Type provided must be an Enum.\", \"T\");\n }\n\n return (T)Enum.Parse(t, value, ignorecase);\n }\n}\n</code></pre>\n\n<p>Useful to parse a string into an Enum.</p>\n\n<pre><code>public enum TestEnum\n{\n Bar,\n Test\n}\n\npublic class Test\n{\n public void Test()\n {\n TestEnum foo = \"Test\".EnumParse&lt;TestEnum&gt;();\n }\n }\n</code></pre>\n\n<p>Credit goes to <a href=\"http://geekswithblogs.net/sdorman/\" rel=\"nofollow noreferrer\">Scott Dorman</a></p>\n\n<p>--- Edit for Codeplex project ---</p>\n\n<p>I have asked Scott Dorman if he would mind us publishing his code in the Codeplex project. This is the reply I got from him:</p>\n\n<blockquote>\n <p>Thanks for the heads-up on both the SO post and the CodePlex project. I have upvoted your answer on the question. Yes, the code is effectively in the public domain currently under the CodeProject Open License (<a href=\"http://www.codeproject.com/info/cpol10.aspx\" rel=\"nofollow noreferrer\">http://www.codeproject.com/info/cpol10.aspx</a>).</p>\n \n <p>I have no problems with this being included in the CodePlex project, and if you want to add me to the project (username is sdorman) I will add that method plus some additional enum helper methods.</p>\n</blockquote>\n" }, { "answer_id": 271423, "author": "TWith2Sugars", "author_id": 35389, "author_profile": "https://Stackoverflow.com/users/35389", "pm_score": 6, "selected": false, "text": "<p>By all means put this in the codeplex project.</p>\n\n<p>Serializing / Deserializing objects to XML:</p>\n\n<pre><code>/// &lt;summary&gt;Serializes an object of type T in to an xml string&lt;/summary&gt;\n/// &lt;typeparam name=\"T\"&gt;Any class type&lt;/typeparam&gt;\n/// &lt;param name=\"obj\"&gt;Object to serialize&lt;/param&gt;\n/// &lt;returns&gt;A string that represents Xml, empty otherwise&lt;/returns&gt;\npublic static string XmlSerialize&lt;T&gt;(this T obj) where T : class, new()\n{\n if (obj == null) throw new ArgumentNullException(\"obj\");\n\n var serializer = new XmlSerializer(typeof(T));\n using (var writer = new StringWriter())\n {\n serializer.Serialize(writer, obj);\n return writer.ToString();\n }\n}\n\n/// &lt;summary&gt;Deserializes an xml string in to an object of Type T&lt;/summary&gt;\n/// &lt;typeparam name=\"T\"&gt;Any class type&lt;/typeparam&gt;\n/// &lt;param name=\"xml\"&gt;Xml as string to deserialize from&lt;/param&gt;\n/// &lt;returns&gt;A new object of type T is successful, null if failed&lt;/returns&gt;\npublic static T XmlDeserialize&lt;T&gt;(this string xml) where T : class, new()\n{\n if (xml == null) throw new ArgumentNullException(\"xml\");\n\n var serializer = new XmlSerializer(typeof(T));\n using (var reader = new StringReader(xml))\n {\n try { return (T)serializer.Deserialize(reader); }\n catch { return null; } // Could not be deserialized to this type.\n }\n}\n</code></pre>\n" }, { "answer_id": 271426, "author": "Christian C. Salvadó", "author_id": 5445, "author_profile": "https://Stackoverflow.com/users/5445", "pm_score": 5, "selected": false, "text": "<p><a href=\"http://www.codeplex.com/DateTimeExtensions\" rel=\"nofollow noreferrer\">DateTimeExtensions</a></p>\n\n<p>Examples:</p>\n\n<pre><code>DateTime firstDayOfMonth = DateTime.Now.First();\nDateTime lastdayOfMonth = DateTime.Now.Last();\nDateTime lastFridayInMonth = DateTime.Now.Last(DayOfWeek.Friday);\nDateTime nextFriday = DateTime.Now.Next(DayOfWeek.Friday);\nDateTime lunchTime = DateTime.Now.SetTime(11, 30);\nDateTime noonOnFriday = DateTime.Now.Next(DayOfWeek.Friday).Noon();\nDateTime secondMondayOfMonth = DateTime.Now.First(DayOfWeek.Monday).Next(DayOfWeek.Monday).Midnight();\n</code></pre>\n" }, { "answer_id": 271433, "author": "sontek", "author_id": 17176, "author_profile": "https://Stackoverflow.com/users/17176", "pm_score": -1, "selected": false, "text": "<p>Easily serialize objects into XML:</p>\n\n<pre><code>public static string ToXml&lt;T&gt;(this T obj) where T : class\n{\n XmlSerializer s = new XmlSerializer(obj.GetType());\n using (StringWriter writer = new StringWriter())\n {\n s.Serialize(writer, obj);\n return writer.ToString();\n }\n}\n\n\"&lt;root&gt;&lt;child&gt;foo&lt;/child&lt;/root&gt;\".ToXml&lt;MyCustomType&gt;();\n</code></pre>\n" }, { "answer_id": 271435, "author": "TWith2Sugars", "author_id": 35389, "author_profile": "https://Stackoverflow.com/users/35389", "pm_score": 3, "selected": false, "text": "<p>Another useful one for me:</p>\n\n<pre><code>/// &lt;summary&gt;\n/// Converts any type in to an Int32\n/// &lt;/summary&gt;\n/// &lt;typeparam name=\"T\"&gt;Any Object&lt;/typeparam&gt;\n/// &lt;param name=\"value\"&gt;Value to convert&lt;/param&gt;\n/// &lt;returns&gt;The integer, 0 if unsuccessful&lt;/returns&gt;\npublic static int ToInt32&lt;T&gt;(this T value)\n{\n int result;\n if (int.TryParse(value.ToString(), out result))\n {\n return result;\n }\n return 0;\n}\n\n/// &lt;summary&gt;\n/// Converts any type in to an Int32 but if null then returns the default\n/// &lt;/summary&gt;\n/// &lt;param name=\"value\"&gt;Value to convert&lt;/param&gt;\n/// &lt;typeparam name=\"T\"&gt;Any Object&lt;/typeparam&gt;\n/// &lt;param name=\"defaultValue\"&gt;Default to use&lt;/param&gt;\n/// &lt;returns&gt;The defaultValue if unsuccessful&lt;/returns&gt;\npublic static int ToInt32&lt;T&gt;(this T value, int defaultValue)\n{\n int result;\n if (int.TryParse(value.ToString(), out result))\n {\n return result;\n }\n return defaultValue;\n}\n</code></pre>\n\n<p>Example:</p>\n\n<pre><code>int number = \"123\".ToInt32();\n</code></pre>\n\n<p>or:</p>\n\n<pre><code>int badNumber = \"a\".ToInt32(100); // Returns 100 since a is nan\n</code></pre>\n" }, { "answer_id": 271437, "author": "Jon Skeet", "author_id": 22656, "author_profile": "https://Stackoverflow.com/users/22656", "pm_score": 7, "selected": false, "text": "<p>I have various extension methods in my <a href=\"http://pobox.com/~skeet/csharp/miscutil\" rel=\"nofollow noreferrer\">MiscUtil</a> project (full source is available there - I'm not going to repeat it here). My favourites, some of which involve other classes (such as ranges):</p>\n\n<p>Date and time stuff - mostly for unit tests. Not sure I'd use them in production :)</p>\n\n<pre><code>var birthday = 19.June(1976);\nvar workingDay = 7.Hours() + 30.Minutes();\n</code></pre>\n\n<p>Ranges and stepping - massive thanks to Marc Gravell for his <a href=\"http://www.pobox.com/~skeet/csharp/miscutil/usage/genericoperators.html\" rel=\"nofollow noreferrer\">operator stuff</a> to make this possible:</p>\n\n<pre><code>var evenNaturals = 2.To(int.MaxValue).Step(2);\nvar daysSinceBirth = birthday.To(DateTime.Today).Step(1.Days());\n</code></pre>\n\n<p>Comparisons:</p>\n\n<pre><code>var myComparer = ProjectionComparer.Create(Person p =&gt; p.Name);\nvar next = myComparer.ThenBy(p =&gt; p.Age);\nvar reversed = myComparer.Reverse();\n</code></pre>\n\n<p>Argument checking:</p>\n\n<pre><code>x.ThrowIfNull(\"x\");\n</code></pre>\n\n<p>LINQ to XML applied to anonymous types (or other types with appropriate properties):</p>\n\n<pre><code>// &lt;Name&gt;Jon&lt;/Name&gt;&lt;Age&gt;32&lt;/Age&gt;\nnew { Name=\"Jon\", Age=32}.ToXElements();\n// Name=\"Jon\" Age=\"32\" (as XAttributes, obviously)\nnew { Name=\"Jon\", Age=32}.ToXAttributes()\n</code></pre>\n\n<p>Push LINQ - would take too long to explain here, but search for it.</p>\n" }, { "answer_id": 271444, "author": "Christian C. Salvadó", "author_id": 5445, "author_profile": "https://Stackoverflow.com/users/5445", "pm_score": 6, "selected": false, "text": "<pre><code>public static class ComparableExtensions\n{\n public static bool Between&lt;T&gt;(this T actual, T lower, T upper) where T : IComparable&lt;T&gt;\n {\n return actual.CompareTo(lower) &gt;= 0 &amp;&amp; actual.CompareTo(upper) &lt; 0;\n }\n}\n</code></pre>\n\n<p>Example:</p>\n\n<pre><code>if (myNumber.Between(3,7))\n{\n // ....\n}\n</code></pre>\n" }, { "answer_id": 271451, "author": "Alan", "author_id": 31223, "author_profile": "https://Stackoverflow.com/users/31223", "pm_score": 2, "selected": false, "text": "<p>An easier way to load default settings from a collection (in real life I use it to populate the settings from any source, including the command line, ClickOnce URL parameters etc.):</p>\n\n<pre><code>public static void LoadFrom(this ApplicationSettingsBase settings, NameValueCollection configuration)\n{\n if (configuration != null)\n foreach (string key in configuration.AllKeys)\n if (!String.IsNullOrEmpty(key))\n try\n {\n settings[key] = configuration.Get(key);\n }\n catch (SettingsPropertyNotFoundException)\n {\n // handle bad arguments as you wish\n }\n}\n</code></pre>\n\n<p>Example:</p>\n\n<pre><code>Settings.Default.LoadFrom(new NameValueCollection() { { \"Setting1\", \"Value1\" }, { \"Setting2\", \"Value2\" } });\n</code></pre>\n" }, { "answer_id": 271478, "author": "cfeduke", "author_id": 5645, "author_profile": "https://Stackoverflow.com/users/5645", "pm_score": 2, "selected": false, "text": "<p>Comes in useful for unit testing:</p>\n\n<pre><code>public static IList&lt;T&gt; Clone&lt;T&gt;(this IList&lt;T&gt; list) where T : ICloneable\n{\n var ret = new List&lt;T&gt;(list.Count);\n foreach (var item in list)\n ret.Add((T)item.Clone());\n\n // done\n return ret;\n}\n</code></pre>\n\n<p>A series of these like TWith2Sugars, alternate shortened syntax:</p>\n\n<pre><code>public static long? ToNullableInt64(this string val)\n{\n long ret;\n return Int64.TryParse(val, out ret) ? ret : new long?();\n}\n</code></pre>\n\n<p>And finally this - is there something already in the BCL that does the following?</p>\n\n<pre><code>public static void Split&lt;T&gt;(this T[] array, \n Func&lt;T,bool&gt; determinator, \n IList&lt;T&gt; onTrue, \n IList&lt;T&gt; onFalse)\n{\n if (onTrue == null)\n onTrue = new List&lt;T&gt;();\n else\n onTrue.Clear();\n\n if (onFalse == null)\n onFalse = new List&lt;T&gt;();\n else\n onFalse.Clear();\n\n if (determinator == null)\n return;\n\n foreach (var item in array)\n {\n if (determinator(item))\n onTrue.Add(item);\n else\n onFalse.Add(item);\n }\n}\n</code></pre>\n" }, { "answer_id": 271592, "author": "mmiika", "author_id": 6846, "author_profile": "https://Stackoverflow.com/users/6846", "pm_score": 1, "selected": false, "text": "<p>I like these NUnit Assert extensions: <a href=\"http://svn.caffeine-it.com/openrasta/trunk/src/Rasta.Testing/AssertExtensions.cs\" rel=\"nofollow noreferrer\">http://svn.caffeine-it.com/openrasta/trunk/src/Rasta.Testing/AssertExtensions.cs</a></p>\n" }, { "answer_id": 271611, "author": "stiduck", "author_id": 35398, "author_profile": "https://Stackoverflow.com/users/35398", "pm_score": 6, "selected": false, "text": "<p>The extension method:</p>\n\n<pre><code>public static void AddRange&lt;T, S&gt;(this ICollection&lt;T&gt; list, params S[] values)\n where S : T\n{\n foreach (S value in values)\n list.Add(value);\n}\n</code></pre>\n\n<p>The method applies for all types and lets you add a range of items to a list as parameters.</p>\n\n<p>Example:</p>\n\n<pre><code>var list = new List&lt;Int32&gt;();\nlist.AddRange(5, 4, 8, 4, 2);\n</code></pre>\n" }, { "answer_id": 271656, "author": "Pure.Krome", "author_id": 30674, "author_profile": "https://Stackoverflow.com/users/30674", "pm_score": 3, "selected": false, "text": "<p>HTH. These are some of my main ones.</p>\n\n<pre><code>using System;\nusing System.Collections.Generic;\nusing System.Globalization;\nusing System.Linq;\nusing System.Text;\n\nnamespace Insert.Your.Namespace.Here.Helpers\n{\n public static class Extensions\n {\n public static bool IsNullOrEmpty&lt;T&gt;(this IEnumerable&lt;T&gt; iEnumerable)\n {\n // Cheers to Joel Mueller for the bugfix. Was .Count(), now it's .Any()\n return iEnumerable == null ||\n !iEnumerable.Any();\n }\n\n public static IList&lt;T&gt; ToListIfNotNullOrEmpty&lt;T&gt;(this IList&lt;T&gt; iList)\n {\n return iList.IsNullOrEmpty() ? null : iList;\n }\n\n public static PagedList&lt;T&gt; ToPagedListIfNotNullOrEmpty&lt;T&gt;(this PagedList&lt;T&gt; pagedList)\n {\n return pagedList.IsNullOrEmpty() ? null : pagedList;\n }\n\n public static string ToPluralString(this int value)\n {\n return value == 1 ? string.Empty : \"s\";\n }\n\n public static string ToReadableTime(this DateTime value)\n {\n TimeSpan span = DateTime.Now.Subtract(value);\n const string plural = \"s\";\n\n\n if (span.Days &gt; 7)\n {\n return value.ToShortDateString();\n }\n\n switch (span.Days)\n {\n case 0:\n switch (span.Hours)\n {\n case 0:\n if (span.Minutes == 0)\n {\n return span.Seconds &lt;= 0\n ? \"now\"\n : string.Format(\"{0} second{1} ago\",\n span.Seconds,\n span.Seconds != 1 ? plural : string.Empty);\n }\n return string.Format(\"{0} minute{1} ago\",\n span.Minutes,\n span.Minutes != 1 ? plural : string.Empty);\n default:\n return string.Format(\"{0} hour{1} ago\",\n span.Hours,\n span.Hours != 1 ? plural : string.Empty);\n }\n default:\n return string.Format(\"{0} day{1} ago\",\n span.Days,\n span.Days != 1 ? plural : string.Empty);\n }\n }\n\n public static string ToShortGuidString(this Guid value)\n {\n return Convert.ToBase64String(value.ToByteArray())\n .Replace(\"/\", \"_\")\n .Replace(\"+\", \"-\")\n .Substring(0, 22);\n }\n\n public static Guid FromShortGuidString(this string value)\n {\n return new Guid(Convert.FromBase64String(value.Replace(\"_\", \"/\")\n .Replace(\"-\", \"+\") + \"==\"));\n }\n\n public static string ToStringMaximumLength(this string value, int maximumLength)\n {\n return ToStringMaximumLength(value, maximumLength, \"...\");\n }\n\n public static string ToStringMaximumLength(this string value, int maximumLength, string postFixText)\n {\n if (string.IsNullOrEmpty(postFixText))\n {\n throw new ArgumentNullException(\"postFixText\");\n }\n\n return value.Length &gt; maximumLength\n ? string.Format(CultureInfo.InvariantCulture,\n \"{0}{1}\",\n value.Substring(0, maximumLength - postFixText.Length),\n postFixText)\n :\n value;\n }\n\n public static string SlugDecode(this string value)\n {\n return value.Replace(\"_\", \" \");\n }\n\n public static string SlugEncode(this string value)\n {\n return value.Replace(\" \", \"_\");\n }\n }\n}\n</code></pre>\n" }, { "answer_id": 271676, "author": "Omer van Kloeten", "author_id": 4979, "author_profile": "https://Stackoverflow.com/users/4979", "pm_score": 2, "selected": false, "text": "<p><a href=\"http://www.codeplex.com/linqext/\" rel=\"nofollow noreferrer\">http://www.codeplex.com/linqext/</a></p>\n" }, { "answer_id": 271884, "author": "xyz", "author_id": 82, "author_profile": "https://Stackoverflow.com/users/82", "pm_score": 6, "selected": false, "text": "<p>Are these any use?</p>\n\n<pre><code>public static bool CoinToss(this Random rng)\n{\n return rng.Next(2) == 0;\n}\n\npublic static T OneOf&lt;T&gt;(this Random rng, params T[] things)\n{\n return things[rng.Next(things.Length)];\n}\n\nRandom rand;\nbool luckyDay = rand.CoinToss();\nstring babyName = rand.OneOf(\"John\", \"George\", \"Radio XBR74 ROCKS!\");\n</code></pre>\n" }, { "answer_id": 271941, "author": "Venr", "author_id": 20385, "author_profile": "https://Stackoverflow.com/users/20385", "pm_score": 5, "selected": false, "text": "<p>Here is one I use frequently for presentation formatting.</p>\n\n<pre><code>public static string ToTitleCase(this string mText)\n{\n if (mText == null) return mText;\n\n System.Globalization.CultureInfo cultureInfo = System.Threading.Thread.CurrentThread.CurrentCulture;\n System.Globalization.TextInfo textInfo = cultureInfo.TextInfo;\n\n // TextInfo.ToTitleCase only operates on the string if is all lower case, otherwise it returns the string unchanged.\n return textInfo.ToTitleCase(mText.ToLower());\n}\n</code></pre>\n" }, { "answer_id": 271945, "author": "user35385", "author_id": 35385, "author_profile": "https://Stackoverflow.com/users/35385", "pm_score": 3, "selected": false, "text": "<p>Find more examples here: <a href=\"http://www.extensionmethod.net/\" rel=\"nofollow noreferrer\">www.extensionmethod.net</a></p>\n" }, { "answer_id": 273648, "author": "Adam Lassek", "author_id": 1249, "author_profile": "https://Stackoverflow.com/users/1249", "pm_score": 4, "selected": false, "text": "<p>I got tired of tedious null-checking while pulling values from MySqlDataReader, so:</p>\n\n<pre><code>public static DateTime? GetNullableDateTime(this MySqlDataReader dr, string fieldName)\n{\n DateTime? nullDate = null;\n return dr.IsDBNull(dr.GetOrdinal(fieldName)) ? nullDate : dr.GetDateTime(fieldName);\n}\n\npublic static string GetNullableString(this MySqlDataReader dr, string fieldName)\n{\n return dr.IsDBNull(dr.GetOrdinal(fieldName)) ? String.Empty : dr.GetString(fieldName);\n}\n\npublic static char? GetNullableChar(this MySqlDataReader dr, string fieldName)\n{\n char? nullChar = null;\n return dr.IsDBNull(dr.GetOrdinal(fieldName)) ? nullChar : dr.GetChar(fieldName);\n}\n</code></pre>\n\n<p>Of course this could be used with any SqlDataReader.</p>\n\n<hr>\n\n<p>Both hangy and Joe had some good comments on how to do this, and I have since had an opportunity to implement something similar in a different context, so here is another version:</p>\n\n<pre><code>public static int? GetNullableInt32(this IDataRecord dr, int ordinal)\n{\n int? nullInt = null;\n return dr.IsDBNull(ordinal) ? nullInt : dr.GetInt32(ordinal);\n}\n\npublic static int? GetNullableInt32(this IDataRecord dr, string fieldname)\n{\n int ordinal = dr.GetOrdinal(fieldname);\n return dr.GetNullableInt32(ordinal);\n}\n\npublic static bool? GetNullableBoolean(this IDataRecord dr, int ordinal)\n{\n bool? nullBool = null;\n return dr.IsDBNull(ordinal) ? nullBool : dr.GetBoolean(ordinal);\n}\n\npublic static bool? GetNullableBoolean(this IDataRecord dr, string fieldname)\n{\n int ordinal = dr.GetOrdinal(fieldname);\n return dr.GetNullableBoolean(ordinal);\n}\n</code></pre>\n" }, { "answer_id": 273665, "author": "hugoware", "author_id": 17091, "author_profile": "https://Stackoverflow.com/users/17091", "pm_score": 2, "selected": false, "text": "<p>I use these in my web projects, mainly with MVC. I have a handful of these written for the <strong>ViewData</strong> and <strong>TempData</strong></p>\n\n<pre><code>/// &lt;summary&gt;\n/// Checks the Request.QueryString for the specified value and returns it, if none \n/// is found then the default value is returned instead\n/// &lt;/summary&gt;\npublic static T QueryValue&lt;T&gt;(this HtmlHelper helper, string param, T defaultValue) {\n object value = HttpContext.Current.Request.QueryString[param] as object;\n if (value == null) { return defaultValue; }\n try {\n return (T)Convert.ChangeType(value, typeof(T));\n } catch (Exception) {\n return defaultValue;\n }\n}\n</code></pre>\n\n<p>That way I can write something like...</p>\n\n<pre><code>&lt;% if (Html.QueryValue(\"login\", false)) { %&gt;\n &lt;div&gt;Welcome Back!&lt;/div&gt;\n\n&lt;% } else { %&gt;\n &lt;%-- Render the control or something --%&gt;\n\n&lt;% } %&gt;\n</code></pre>\n" }, { "answer_id": 274524, "author": "TheSoftwareJedi", "author_id": 18941, "author_profile": "https://Stackoverflow.com/users/18941", "pm_score": 5, "selected": false, "text": "<p>My conversion extensions which allow you to do:</p>\n\n<pre><code>int i = myString.To&lt;int&gt;();\n</code></pre>\n\n<p>Here it is, <a href=\"http://thesoftwarejedi.blogspot.com/2008/05/extension-methods.html\" rel=\"nofollow noreferrer\">as posted on TheSoftwareJedi.com</a></p>\n\n<pre><code>public static T To&lt;T&gt;(this IConvertible obj)\n{\n return (T)Convert.ChangeType(obj, typeof(T));\n}\n\npublic static T ToOrDefault&lt;T&gt;\n (this IConvertible obj)\n{\n try\n {\n return To&lt;T&gt;(obj);\n }\n catch\n {\n return default(T);\n }\n}\n\npublic static bool ToOrDefault&lt;T&gt;\n (this IConvertible obj,\n out T newObj)\n{\n try\n {\n newObj = To&lt;T&gt;(obj); \n return true;\n }\n catch\n {\n newObj = default(T); \n return false;\n }\n}\n\npublic static T ToOrOther&lt;T&gt;\n (this IConvertible obj,\n T other)\n{\n try\n {\n return To&lt;T&gt;obj);\n }\n catch\n {\n return other;\n }\n}\n\npublic static bool ToOrOther&lt;T&gt;\n (this IConvertible obj,\n out T newObj,\n T other)\n{\n try\n {\n newObj = To&lt;T&gt;(obj);\n return true;\n }\n catch\n {\n newObj = other;\n return false;\n }\n}\n\npublic static T ToOrNull&lt;T&gt;\n (this IConvertible obj)\n where T : class\n{\n try\n {\n return To&lt;T&gt;(obj);\n }\n catch\n {\n return null;\n }\n}\n\npublic static bool ToOrNull&lt;T&gt;\n (this IConvertible obj,\n out T newObj)\n where T : class\n{\n try\n {\n newObj = To&lt;T&gt;(obj);\n return true;\n }\n catch\n {\n newObj = null;\n return false;\n }\n}\n</code></pre>\n\n<p>You can ask for default (calls blank constructor or \"0\" for numerics) on failure, specify a \"default\" value (I call it \"other\"), or ask for null (where T : class). I've also provided both silent exception models, and a typical TryParse model that returns a bool indicating the action taken, and an out param holds the new value.\nSo our code can do things like this</p>\n\n<pre><code>int i = myString.To&lt;int&gt;();\nstring a = myInt.ToOrDefault&lt;string&gt;();\n//note type inference\nDateTime d = myString.ToOrOther(DateTime.MAX_VALUE);\ndouble d;\n//note type inference\nbool didItGiveDefault = myString.ToOrDefault(out d);\nstring s = myDateTime.ToOrNull&lt;string&gt;();\n</code></pre>\n\n<p>I couldn't get Nullable types to roll into the whole thing very cleanly. I tried for about 20 minutes before I threw in the towel.</p>\n" }, { "answer_id": 274649, "author": "chakrit", "author_id": 3055, "author_profile": "https://Stackoverflow.com/users/3055", "pm_score": 6, "selected": false, "text": "<p>ForEach for IEnumerables</p>\n\n<pre><code>public static class FrameworkExtensions\n{\n // a map function\n public static void ForEach&lt;T&gt;(this IEnumerable&lt;T&gt; @enum, Action&lt;T&gt; mapFunction)\n {\n foreach (var item in @enum) mapFunction(item);\n }\n}\n</code></pre>\n\n<p>Naive example:</p>\n\n<pre><code>var buttons = GetListOfButtons() as IEnumerable&lt;Button&gt;;\n\n// click all buttons\nbuttons.ForEach(b =&gt; b.Click());\n</code></pre>\n\n<p>Cool example:</p>\n\n<pre><code>// no need to type the same assignment 3 times, just\n// new[] up an array and use foreach + lambda\n// everything is properly inferred by csc :-)\nnew { itemA, itemB, itemC }\n .ForEach(item =&gt; {\n item.Number = 1;\n item.Str = \"Hello World!\";\n });\n</code></pre>\n\n<p>Note:</p>\n\n<p>This is not like <code>Select</code> because <code>Select</code> <em>expects</em> your function to return something as for transforming into another list.</p>\n\n<p>ForEach simply allows you to execute something for each of the items without any transformations/data manipulation.</p>\n\n<p>I made this so I can program in a more functional style and I was surprised that List has a ForEach while IEnumerable does not.</p>\n\n<p><em>Put this in the codeplex project</em></p>\n" }, { "answer_id": 274652, "author": "bruno conde", "author_id": 31136, "author_profile": "https://Stackoverflow.com/users/31136", "pm_score": 3, "selected": false, "text": "<p>Function to compare Files/Directories through the <strong>OS File System Info</strong>. This is useful to compare shares with local files. </p>\n\n<p><strong>Usage:</strong></p>\n\n<pre><code>DirectoryInfo dir = new DirectoryInfo(@\"C:\\test\\myShareDir\");\nConsole.WriteLine(dir.IsSameFileAs(@\"\\\\myMachineName\\myShareDir\"));\n\nFileInfo file = new FileInfo(@\"C:\\test\\myShareDir\\file.txt\");\nConsole.WriteLine(file.IsSameFileAs(@\"\\\\myMachineName\\myShareDir\\file.txt\"));\n</code></pre>\n\n<p><strong>Code:</strong></p>\n\n<pre><code>public static class FileExtensions\n{\n struct BY_HANDLE_FILE_INFORMATION\n {\n public uint FileAttributes;\n public System.Runtime.InteropServices.ComTypes.FILETIME CreationTime;\n public System.Runtime.InteropServices.ComTypes.FILETIME LastAccessTime;\n public System.Runtime.InteropServices.ComTypes.FILETIME LastWriteTime;\n public uint VolumeSerialNumber;\n public uint FileSizeHigh;\n public uint FileSizeLow;\n public uint NumberOfLinks;\n public uint FileIndexHigh;\n public uint FileIndexLow;\n }\n\n //\n // CreateFile constants\n //\n const uint FILE_SHARE_READ = 0x00000001;\n const uint OPEN_EXISTING = 3;\n const uint GENERIC_READ = (0x80000000);\n const uint FILE_FLAG_BACKUP_SEMANTICS = 0x02000000;\n\n\n [DllImport(\"kernel32.dll\", SetLastError = true)]\n static extern IntPtr CreateFile(\n string lpFileName,\n uint dwDesiredAccess,\n uint dwShareMode,\n IntPtr lpSecurityAttributes,\n uint dwCreationDisposition,\n uint dwFlagsAndAttributes,\n IntPtr hTemplateFile);\n\n [DllImport(\"kernel32.dll\", SetLastError = true)]\n static extern bool GetFileInformationByHandle(IntPtr hFile, out BY_HANDLE_FILE_INFORMATION lpFileInformation);\n\n public static bool IsSameFileAs(this FileSystemInfo file, string path)\n {\n BY_HANDLE_FILE_INFORMATION fileInfo1, fileInfo2;\n IntPtr ptr1 = CreateFile(file.FullName, GENERIC_READ, FILE_SHARE_READ, IntPtr.Zero, OPEN_EXISTING, FILE_FLAG_BACKUP_SEMANTICS, IntPtr.Zero);\n if ((int)ptr1 == -1)\n {\n System.ComponentModel.Win32Exception e = new System.ComponentModel.Win32Exception(Marshal.GetLastWin32Error());\n throw e;\n }\n IntPtr ptr2 = CreateFile(path, GENERIC_READ, FILE_SHARE_READ, IntPtr.Zero, OPEN_EXISTING, FILE_FLAG_BACKUP_SEMANTICS, IntPtr.Zero);\n if ((int)ptr2 == -1)\n {\n System.ComponentModel.Win32Exception e = new System.ComponentModel.Win32Exception(Marshal.GetLastWin32Error());\n throw e;\n }\n GetFileInformationByHandle(ptr1, out fileInfo1);\n GetFileInformationByHandle(ptr2, out fileInfo2);\n\n return ((fileInfo1.FileIndexHigh == fileInfo2.FileIndexHigh) &amp;&amp;\n (fileInfo1.FileIndexLow == fileInfo2.FileIndexLow));\n }\n}\n</code></pre>\n" }, { "answer_id": 275303, "author": "Timothy Khouri", "author_id": 11917, "author_profile": "https://Stackoverflow.com/users/11917", "pm_score": 2, "selected": false, "text": "<p>I didn't want to add anything that was already said, so here are some that I use that haven't been mentioned. (Sorry if this is too lengthy):</p>\n\n<pre><code>public static class MyExtensions\n{\n public static bool IsInteger(this string input)\n {\n int temp;\n\n return int.TryParse(input, out temp);\n }\n\n public static bool IsDecimal(this string input)\n {\n decimal temp;\n\n return decimal.TryParse(input, out temp);\n }\n\n public static int ToInteger(this string input, int defaultValue)\n {\n int temp;\n\n return (int.TryParse(input, out temp)) ? temp : defaultValue;\n }\n\n public static decimal ToDecimal(this string input, decimal defaultValue)\n {\n decimal temp;\n\n return (decimal.TryParse(input, out temp)) ? temp : defaultValue;\n }\n\n public static DateTime ToFirstOfTheMonth(this DateTime input)\n {\n return input.Date.AddDays(-1 * input.Day + 1);\n }\n\n // Intentionally returns 0 if the target date is before the input date.\n public static int MonthsUntil(this DateTime input, DateTime targetDate)\n {\n input = input.ToFirstOfTheMonth();\n\n targetDate = targetDate.ToFirstOfTheMonth();\n\n int result = 0;\n\n while (input &lt; targetDate)\n {\n input = input.AddMonths(1);\n result++;\n }\n\n return result;\n }\n\n // Used for backwards compatibility in a system built before my time.\n public static DataTable ToDataTable(this IEnumerable input)\n {\n // too much code to show here right now...\n }\n}\n</code></pre>\n" }, { "answer_id": 275611, "author": "µBio", "author_id": 9796, "author_profile": "https://Stackoverflow.com/users/9796", "pm_score": 4, "selected": false, "text": "<p>Takes a camelCaseWord or PascalCaseWord and \"wordifies\" it, ie camelCaseWord => camel Case Word</p>\n\n<pre><code>public static string Wordify( this string camelCaseWord )\n{\n // if the word is all upper, just return it\n if( !Regex.IsMatch( camelCaseWord, \"[a-z]\" ) )\n return camelCaseWord;\n\n return string.Join( \" \", Regex.Split( camelCaseWord, @\"(?&lt;!^)(?=[A-Z])\" ) );\n}\n</code></pre>\n\n<p>I often use it in conjuction with Capitalize</p>\n\n<pre><code>public static string Capitalize( this string word )\n{\n return word[0].ToString( ).ToUpper( ) + word.Substring( 1 );\n}\n</code></pre>\n\n<p>Example usage</p>\n\n<pre><code>SomeEntityObject entity = DataAccessObject.GetSomeEntityObject( id );\nList&lt;PropertyInfo&gt; properties = entity.GetType().GetPublicNonCollectionProperties( );\n\n// wordify the property names to act as column headers for an html table or something\nList&lt;string&gt; columns = properties.Select( p =&gt; p.Name.Capitalize( ).Wordify( ) ).ToList( );\n</code></pre>\n\n<p><strong>Free to use in codeplex project</strong></p>\n" }, { "answer_id": 275620, "author": "TraumaPony", "author_id": 18658, "author_profile": "https://Stackoverflow.com/users/18658", "pm_score": 3, "selected": false, "text": "<pre><code>public static class EnumerableExtensions\n{\n [Pure]\n public static U MapReduce&lt;T, U&gt;(this IEnumerable&lt;T&gt; enumerable, Func&lt;T, U&gt; map, Func&lt;U, U, U&gt; reduce)\n {\n CodeContract.RequiresAlways(enumerable != null);\n CodeContract.RequiresAlways(enumerable.Skip(1).Any());\n CodeContract.RequiresAlways(map != null);\n CodeContract.RequiresAlways(reduce != null);\n return enumerable.AsParallel().Select(map).Aggregate(reduce);\n }\n [Pure]\n public static U MapReduce&lt;T, U&gt;(this IList&lt;T&gt; list, Func&lt;T, U&gt; map, Func&lt;U, U, U&gt; reduce)\n {\n CodeContract.RequiresAlways(list != null);\n CodeContract.RequiresAlways(list.Count &gt;= 2);\n CodeContract.RequiresAlways(map != null);\n CodeContract.RequiresAlways(reduce != null);\n U result = map(list[0]);\n for (int i = 1; i &lt; list.Count; i++)\n {\n result = reduce(result,map(list[i]));\n }\n return result;\n }\n\n //Parallel version; creates garbage\n [Pure]\n public static U MapReduce&lt;T, U&gt;(this IList&lt;T&gt; list, Func&lt;T, U&gt; map, Func&lt;U, U, U&gt; reduce)\n {\n CodeContract.RequiresAlways(list != null);\n CodeContract.RequiresAlways(list.Skip(1).Any());\n CodeContract.RequiresAlways(map != null);\n CodeContract.RequiresAlways(reduce != null);\n\n U[] mapped = new U[list.Count];\n Parallel.For(0, mapped.Length, i =&gt;\n {\n mapped[i] = map(list[i]);\n });\n U result = mapped[0];\n for (int i = 1; i &lt; list.Count; i++)\n {\n result = reduce(result, mapped[i]);\n }\n return result;\n }\n\n}\n</code></pre>\n" }, { "answer_id": 275640, "author": "Zack Elan", "author_id": 2461, "author_profile": "https://Stackoverflow.com/users/2461", "pm_score": 3, "selected": false, "text": "<p>Pythonic methods for Dictionaries:</p>\n\n<pre><code>/// &lt;summary&gt;\n/// If a key exists in a dictionary, return its value, \n/// otherwise return the default value for that type.\n/// &lt;/summary&gt;\npublic static U GetWithDefault&lt;T, U&gt;(this Dictionary&lt;T, U&gt; dict, T key)\n{\n return dict.GetWithDefault(key, default(U));\n}\n\n/// &lt;summary&gt;\n/// If a key exists in a dictionary, return its value,\n/// otherwise return the provided default value.\n/// &lt;/summary&gt;\npublic static U GetWithDefault&lt;T, U&gt;(this Dictionary&lt;T, U&gt; dict, T key, U defaultValue)\n{\n return dict.ContainsKey(key)\n ? dict[key]\n : defaultValue;\n}\n</code></pre>\n\n<p>Useful for when you want to append a timestamp to a filename to assure uniqueness.</p>\n\n<pre><code>/// &lt;summary&gt;\n/// Format a DateTime as a string that contains no characters\n//// that are banned from filenames, such as ':'.\n/// &lt;/summary&gt;\n/// &lt;returns&gt;YYYY-MM-DD_HH.MM.SS&lt;/returns&gt;\npublic static string ToFilenameString(this DateTime dt)\n{\n return dt.ToString(\"s\").Replace(\":\", \".\").Replace('T', '_');\n}\n</code></pre>\n" }, { "answer_id": 276307, "author": "Michael Stum", "author_id": 91, "author_profile": "https://Stackoverflow.com/users/91", "pm_score": 4, "selected": false, "text": "<p>\"Please mark your answers with an acceptance to put the code in the Codeplex project.\"</p>\n\n<p>Why? All the Stuff on this site under <a href=\"http://creativecommons.org/licenses/by-sa/2.5/\" rel=\"nofollow noreferrer\">CC-by-sa-2.5</a>, so just put your Extension overflow Project under the same license and you can freely use it.</p>\n\n<p>Anyway, here is a String.Reverse function, based on <a href=\"https://stackoverflow.com/questions/228038/best-way-to-reverse-a-string-in-c-20\">this question</a>.</p>\n\n<pre><code>/// &lt;summary&gt;\n/// Reverse a String\n/// &lt;/summary&gt;\n/// &lt;param name=\"input\"&gt;The string to Reverse&lt;/param&gt;\n/// &lt;returns&gt;The reversed String&lt;/returns&gt;\npublic static string Reverse(this string input)\n{\n char[] array = input.ToCharArray();\n Array.Reverse(array);\n return new string(array);\n}\n</code></pre>\n" }, { "answer_id": 276331, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 5, "selected": false, "text": "<p>I have an extension method for logging exceptions:</p>\n\n<pre><code>public static void Log(this Exception obj)\n{\n //your logging logic here\n}\n</code></pre>\n\n<p>And it is used like this:</p>\n\n<pre><code>try\n{\n //Your stuff here\n}\ncatch(Exception ex)\n{\n ex.Log();\n}\n</code></pre>\n\n<p>[sorry for posting twice; the 2nd one is better designed :-)]</p>\n" }, { "answer_id": 279789, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 1, "selected": false, "text": "<p>Here is another ThrowIfNull implementation:</p>\n\n<pre><code>[ThreadStatic]\nprivate static string lastMethodName = null;\n\n[ThreadStatic]\nprivate static int lastParamIndex = 0;\n\n[MethodImpl(MethodImplOptions.NoInlining)]\npublic static void ThrowIfNull&lt;T&gt;(this T parameter)\n{\n var currentStackFrame = new StackFrame(1);\n var props = currentStackFrame.GetMethod().GetParameters();\n\n if (!String.IsNullOrEmpty(lastMethodName)) {\n if (currentStackFrame.GetMethod().Name != lastMethodName) {\n lastParamIndex = 0;\n } else if (lastParamIndex &gt;= props.Length - 1) {\n lastParamIndex = 0;\n } else {\n lastParamIndex++;\n }\n } else {\n lastParamIndex = 0;\n }\n\n if (!typeof(T).IsValueType) {\n for (int i = lastParamIndex; i &amp;lt; props.Length; i++) {\n if (props[i].ParameterType.IsValueType) {\n lastParamIndex++;\n } else {\n break;\n }\n }\n }\n\n if (parameter == null) {\n string paramName = props[lastParamIndex].Name;\n throw new ArgumentNullException(paramName);\n }\n\n lastMethodName = currentStackFrame.GetMethod().Name;\n}\n</code></pre>\n\n<p>It's not as efficient as the other impementations, but has cleaner usage:</p>\n\n<pre><code>public void Foo()\n{\n Bar(1, 2, \"Hello\", \"World\"); //no exception\n Bar(1, 2, \"Hello\", null); //exception\n Bar(1, 2, null, \"World\"); //exception\n}\n\npublic void Bar(int x, int y, string someString1, string someString2)\n{\n //will also work with comments removed\n //x.ThrowIfNull();\n //y.ThrowIfNull();\n someString1.ThrowIfNull();\n someString2.ThrowIfNull();\n\n //Do something incredibly useful here!\n}\n</code></pre>\n\n<p>Changing the parameters to int? will also work.</p>\n\n<p>-bill</p>\n" }, { "answer_id": 280230, "author": "lubos hasko", "author_id": 275, "author_profile": "https://Stackoverflow.com/users/275", "pm_score": 2, "selected": false, "text": "<p>I'm using this one quite a lot...</p>\n\n<p>Original code:</p>\n\n<pre><code>if (guid != Guid.Empty) return guid;\nelse return Guid.NewGuid();\n</code></pre>\n\n<p>New code:</p>\n\n<pre><code>return guid.NewGuidIfEmpty();\n</code></pre>\n\n<p>Extension method:</p>\n\n<pre><code>public static Guid NewGuidIfEmpty(this Guid uuid)\n{\n return (uuid != Guid.Empty ? uuid : Guid.NewGuid());\n}\n</code></pre>\n" }, { "answer_id": 280252, "author": "Jay Bazuzi", "author_id": 5314, "author_profile": "https://Stackoverflow.com/users/5314", "pm_score": 3, "selected": false, "text": "<p>I'm disappointed that the .NET Framework prefers that files and directories be represented as strings rather than objects, and that the FileInfo and DirectoryInfo types aren't as powerful as I'd wish. So, I started to write fluent extension methods as I needed them, e.g.:</p>\n\n<pre><code>public static FileInfo SetExtension(this FileInfo fileInfo, string extension)\n{\n return new FileInfo(Path.ChangeExtension(fileInfo.FullName, extension));\n}\n\npublic static FileInfo SetDirectory(this FileInfo fileInfo, string directory)\n{\n return new FileInfo(Path.Combine(directory, fileInfo.Name));\n}\n</code></pre>\n\n<p>Yes, you can put this in the codeplex </p>\n" }, { "answer_id": 280322, "author": "Eric Schoonover", "author_id": 3957, "author_profile": "https://Stackoverflow.com/users/3957", "pm_score": 4, "selected": false, "text": "<p>This one is for MVC it adds the ability to generate a <code>&lt;label /&gt;</code> tag to the <code>Html</code> variable that is available in every <code>ViewPage</code>. Hopefully it will be of use to others trying to develop similar extensions.</p>\n\n<p><strong>Use:</strong></p>\n\n<pre><code>&lt;%= Html.Label(\"LabelId\", \"ForId\", \"Text\")%&gt;\n</code></pre>\n\n<p><strong>Output:</strong></p>\n\n<pre><code>&lt;label id=\"LabelId\" for=\"ForId\"&gt;Text&lt;/label&gt;\n</code></pre>\n\n<p><strong>Code:</strong></p>\n\n<pre><code>public static class HtmlHelperExtensions\n{\n public static string Label(this HtmlHelper Html, string @for, string text)\n {\n return Html.Label(null, @for, text);\n }\n\n public static string Label(this HtmlHelper Html, string @for, string text, object htmlAttributes)\n {\n return Html.Label(null, @for, text, htmlAttributes);\n }\n\n public static string Label(this HtmlHelper Html, string @for, string text, IDictionary&lt;string, object&gt; htmlAttributes)\n {\n return Html.Label(null, @for, text, htmlAttributes);\n }\n\n public static string Label(this HtmlHelper Html, string id, string @for, string text)\n {\n return Html.Label(id, @for, text, null);\n }\n\n public static string Label(this HtmlHelper Html, string id, string @for, string text, object htmlAttributes)\n {\n return Html.Label(id, @for, text, new RouteValueDictionary(htmlAttributes));\n }\n\n public static string Label(this HtmlHelper Html, string id, string @for, string text, IDictionary&lt;string, object&gt; htmlAttributes)\n {\n TagBuilder tag = new TagBuilder(\"label\");\n\n tag.MergeAttributes(htmlAttributes);\n\n if (!string.IsNullOrEmpty(id))\n tag.MergeAttribute(\"id\", Html.AttributeEncode(id));\n\n tag.MergeAttribute(\"for\", Html.AttributeEncode(@for));\n\n tag.SetInnerText(Html.Encode(text));\n\n return tag.ToString(TagRenderMode.Normal);\n }\n}\n</code></pre>\n" }, { "answer_id": 286327, "author": "BFree", "author_id": 15861, "author_profile": "https://Stackoverflow.com/users/15861", "pm_score": 2, "selected": false, "text": "<p>The Substring method on the string class has always felt inadequate to me. Usually when you do a substring, you know the character(s) from where you want to start, and the charachter(s) where you want to end. Thus, I've always felt that have to specify length as the second parameter is stupid. Therefore, I've written my own extension methods. One that takes a startIndex and an endIndex. And one, that takes a startText (string) and endText (string) so you can just specify the text from where to start the substring, and the text for where to end it.</p>\n\n<p>NOTE: I couldn't name the method Substring as in .NET because my first overload takes the same parameter types as one of the .NET overloads. Therefore I named them Subsetstring. Feel free to add to the CodePlex...</p>\n\n<pre><code>public static class StringExtensions\n{\n /// &lt;summary&gt;\n /// Returns a Subset string starting at the specified start index and ending and the specified end\n /// index.\n /// &lt;/summary&gt;\n /// &lt;param name=\"s\"&gt;The string to retrieve the subset from.&lt;/param&gt;\n /// &lt;param name=\"startIndex\"&gt;The specified start index for the subset.&lt;/param&gt;\n /// &lt;param name=\"endIndex\"&gt;The specified end index for the subset.&lt;/param&gt;\n /// &lt;returns&gt;A Subset string starting at the specified start index and ending and the specified end\n /// index.&lt;/returns&gt;\n public static string Subsetstring(this string s, int startIndex, int endIndex)\n {\n if (startIndex &gt; endIndex)\n {\n throw new InvalidOperationException(\"End Index must be after Start Index.\");\n }\n\n if (startIndex &lt; 0)\n {\n throw new InvalidOperationException(\"Start Index must be a positive number.\");\n }\n\n if(endIndex &lt;0)\n {\n throw new InvalidOperationException(\"End Index must be a positive number.\");\n }\n\n return s.Substring(startIndex, (endIndex - startIndex));\n }\n\n /// &lt;summary&gt;\n /// Finds the specified Start Text and the End Text in this string instance, and returns a string\n /// containing all the text starting from startText, to the begining of endText. (endText is not\n /// included.)\n /// &lt;/summary&gt;\n /// &lt;param name=\"s\"&gt;The string to retrieve the subset from.&lt;/param&gt;\n /// &lt;param name=\"startText\"&gt;The Start Text to begin the Subset from.&lt;/param&gt;\n /// &lt;param name=\"endText\"&gt;The End Text to where the Subset goes to.&lt;/param&gt;\n /// &lt;param name=\"ignoreCase\"&gt;Whether or not to ignore case when comparing startText/endText to the string.&lt;/param&gt;\n /// &lt;returns&gt;A string containing all the text starting from startText, to the begining of endText.&lt;/returns&gt;\n public static string Subsetstring(this string s, string startText, string endText, bool ignoreCase)\n {\n if (string.IsNullOrEmpty(startText) || string.IsNullOrEmpty(endText))\n {\n throw new ArgumentException(\"Start Text and End Text cannot be empty.\");\n }\n string temp = s;\n if (ignoreCase)\n {\n temp = s.ToUpperInvariant();\n startText = startText.ToUpperInvariant();\n endText = endText.ToUpperInvariant();\n }\n int start = temp.IndexOf(startText);\n int end = temp.IndexOf(endText, start);\n return Subsetstring(s, start, end);\n }\n}\n</code></pre>\n\n<p>Usage:</p>\n\n<pre><code>string s = \"This is a tester for my cool extension method!!\";\n s = s.Subsetstring(\"tester\", \"cool\",true);\n</code></pre>\n\n<p>Output: \"tester for my \"</p>\n" }, { "answer_id": 286753, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 3, "selected": false, "text": "<p>Some of my best method extensions (I have a lot!): </p>\n\n<pre><code>public static T ToEnum&lt;T&gt;(this string str) where T : struct\n{\n return (T)Enum.Parse(typeof(T), str);\n}\n\n//DayOfWeek sunday = \"Sunday\".ToEnum&lt;DayOfWeek&gt;();\n\npublic static string ToString&lt;T&gt;(this IEnumerable&lt;T&gt; collection, string separator)\n{\n return ToString(collection, t =&gt; t.ToString(), separator);\n}\n\npublic static string ToString&lt;T&gt;(this IEnumerable&lt;T&gt; collection, Func&lt;T, string&gt; stringElement, string separator)\n{\n StringBuilder sb = new StringBuilder();\n foreach (var item in collection)\n {\n sb.Append(stringElement(item));\n sb.Append(separator);\n }\n return sb.ToString(0, Math.Max(0, sb.Length - separator.Length)); // quita el ultimo separador\n}\n\n//new []{1,2,3}.ToString(i=&gt;i*2, \", \") --&gt; \"2, 4, 6\"\n</code></pre>\n\n<p>Also, the next ones are meant to be able to continue in the same line in almost any situation, not declaring new variables and then removing state:</p>\n\n<pre><code>public static R Map&lt;T, R&gt;(this T t, Func&lt;T, R&gt; func)\n{\n return func(t);\n}\n\nExpensiveFindWally().Map(wally=&gt;wally.FirstName + \" \" + wally.LastName)\n\npublic static R TryCC&lt;T, R&gt;(this T t, Func&lt;T, R&gt; func)\n where T : class\n where R : class\n{\n if (t == null) return null;\n return func(t);\n}\n\npublic static R? TryCS&lt;T, R&gt;(this T t, Func&lt;T, R&gt; func)\n where T : class\n where R : struct\n{\n if (t == null) return null;\n return func(t);\n}\n\npublic static R? TryCS&lt;T, R&gt;(this T t, Func&lt;T, R?&gt; func)\n where T : class\n where R : struct\n{\n if (t == null) return null;\n return func(t);\n}\n\npublic static R TrySC&lt;T, R&gt;(this T? t, Func&lt;T, R&gt; func)\n where T : struct\n where R : class\n{\n if (t == null) return null;\n return func(t.Value);\n}\n\npublic static R? TrySS&lt;T, R&gt;(this T? t, Func&lt;T, R&gt; func)\n where T : struct\n where R : struct\n{\n if (t == null) return null;\n return func(t.Value);\n}\n\npublic static R? TrySS&lt;T, R&gt;(this T? t, Func&lt;T, R?&gt; func)\n where T : struct\n where R : struct\n{\n if (t == null) return null;\n return func(t.Value);\n}\n\n//int? bossNameLength = Departament.Boss.TryCC(b=&gt;b.Name).TryCS(s=&gt;s.Length);\n\n\npublic static T ThrowIfNullS&lt;T&gt;(this T? t, string mensaje)\n where T : struct\n{\n if (t == null)\n throw new NullReferenceException(mensaje);\n return t.Value;\n}\n\npublic static T ThrowIfNullC&lt;T&gt;(this T t, string mensaje)\n where T : class\n{\n if (t == null)\n throw new NullReferenceException(mensaje);\n return t;\n}\n\npublic static T Do&lt;T&gt;(this T t, Action&lt;T&gt; action)\n{\n action(t);\n return t;\n}\n\n//Button b = new Button{Content = \"Click\"}.Do(b=&gt;Canvas.SetColumn(b,2));\n\npublic static T TryDo&lt;T&gt;(this T t, Action&lt;T&gt; action) where T : class\n{\n if (t != null)\n action(t);\n return t;\n}\n\npublic static T? TryDoS&lt;T&gt;(this T? t, Action&lt;T&gt; action) where T : struct\n{\n if (t != null)\n action(t.Value);\n return t;\n}\n</code></pre>\n\n<p>Hope it doesn't look like coming from Mars :)</p>\n" }, { "answer_id": 291402, "author": "Jesse C. Slicer", "author_id": 3312, "author_profile": "https://Stackoverflow.com/users/3312", "pm_score": 5, "selected": false, "text": "<p>Here's a to-and-from for Roman numerals. Not often used, but could be handy. Usage:</p>\n\n<pre><code>if (\"IV\".IsValidRomanNumeral())\n{\n // Do useful stuff with the number 4.\n}\n\nConsole.WriteLine(\"MMMDCCCLXXXVIII\".ParseRomanNumeral());\nConsole.WriteLine(3888.ToRomanNumeralString());\n</code></pre>\n\n<p>The source:</p>\n\n<pre><code> public static class RomanNumeralExtensions\n {\n private const int NumberOfRomanNumeralMaps = 13;\n\n private static readonly Dictionary&lt;string, int&gt; romanNumerals =\n new Dictionary&lt;string, int&gt;(NumberOfRomanNumeralMaps)\n {\n { \"M\", 1000 }, \n { \"CM\", 900 }, \n { \"D\", 500 }, \n { \"CD\", 400 }, \n { \"C\", 100 }, \n { \"XC\", 90 }, \n { \"L\", 50 }, \n { \"XL\", 40 }, \n { \"X\", 10 }, \n { \"IX\", 9 }, \n { \"V\", 5 }, \n { \"IV\", 4 }, \n { \"I\", 1 }\n };\n\n private static readonly Regex validRomanNumeral = new Regex(\n \"^(?i:(?=[MDCLXVI])((M{0,3})((C[DM])|(D?C{0,3}))\"\n + \"?((X[LC])|(L?XX{0,2})|L)?((I[VX])|(V?(II{0,2}))|V)?))$\", \n RegexOptions.Compiled);\n\n public static bool IsValidRomanNumeral(this string value)\n {\n return validRomanNumeral.IsMatch(value);\n }\n\n public static int ParseRomanNumeral(this string value)\n {\n if (value == null)\n {\n throw new ArgumentNullException(\"value\");\n }\n\n value = value.ToUpperInvariant().Trim();\n\n var length = value.Length;\n\n if ((length == 0) || !value.IsValidRomanNumeral())\n {\n throw new ArgumentException(\"Empty or invalid Roman numeral string.\", \"value\");\n }\n\n var total = 0;\n var i = length;\n\n while (i &gt; 0)\n {\n var digit = romanNumerals[value[--i].ToString()];\n\n if (i &gt; 0)\n {\n var previousDigit = romanNumerals[value[i - 1].ToString()];\n\n if (previousDigit &lt; digit)\n {\n digit -= previousDigit;\n i--;\n }\n }\n\n total += digit;\n }\n\n return total;\n }\n\n public static string ToRomanNumeralString(this int value)\n {\n const int MinValue = 1;\n const int MaxValue = 3999;\n\n if ((value &lt; MinValue) || (value &gt; MaxValue))\n {\n throw new ArgumentOutOfRangeException(\"value\", value, \"Argument out of Roman numeral range.\");\n }\n\n const int MaxRomanNumeralLength = 15;\n var sb = new StringBuilder(MaxRomanNumeralLength);\n\n foreach (var pair in romanNumerals)\n {\n while (value / pair.Value &gt; 0)\n {\n sb.Append(pair.Key);\n value -= pair.Value;\n }\n }\n\n return sb.ToString();\n }\n }\n</code></pre>\n" }, { "answer_id": 326701, "author": "Anthony", "author_id": 5599, "author_profile": "https://Stackoverflow.com/users/5599", "pm_score": 1, "selected": false, "text": "<p>Some extensions for working with lists:</p>\n\n<pre><code>/// &lt;summary&gt;\n/// Wrap an object in a list\n/// &lt;/summary&gt;\npublic static IList&lt;T&gt; WrapInList&lt;T&gt;(this T item)\n{\n List&lt;T&gt; result = new List&lt;T&gt;();\n result.Add(item);\n return result;\n}\n</code></pre>\n\n<p>use eg:</p>\n\n<pre><code>myList = someObject.InList();\n</code></pre>\n\n<p>To make an IEnumerable that contains items from one or more sources, in order to make IEnumerable work more like lists. This may not be a good idea for high-performance code but useful for making tests:</p>\n\n<pre><code>public static IEnumerable&lt;T&gt; Append&lt;T&gt;(this IEnumerable&lt;T&gt; enumerable, T newItem)\n{\n foreach (T item in enumerable)\n {\n yield return item;\n }\n\n yield return newItem;\n}\n\npublic static IEnumerable&lt;T&gt; Append&lt;T&gt;(this IEnumerable&lt;T&gt; enumerable, params T[] newItems)\n{\n foreach (T item in enumerable)\n {\n yield return item;\n }\n\n foreach (T newItem in newItems)\n {\n yield return newItem;\n }\n}\n</code></pre>\n\n<p>use e.g.</p>\n\n<pre><code>someEnumeration = someEnumeration.Append(newItem);\n</code></pre>\n\n<p>Other variations of this are possible - e.g.</p>\n\n<pre><code>someEnumeration = someEnumeration.Append(otherEnumeration);\n</code></pre>\n\n<p>If you are cloning items, you may also want to clone lists of them:</p>\n\n<pre><code>public static IList&lt;T&gt; Clone&lt;T&gt;(this IEnumerable&lt;T&gt; source) where T: ICloneable\n{\n List&lt;T&gt; result = new List&lt;T&gt;();\n\n foreach (T item in source)\n {\n result.Add((T)item.Clone());\n }\n\n return result;\n}\n</code></pre>\n\n<p>When I am working with <code>ObservableCollection&lt;T&gt;</code>, I generally extend it with an AddRange method. Other answers here give implementations of this.</p>\n\n<p><strong>You may put this code in the Codeplex project if you want</strong>.</p>\n" }, { "answer_id": 329561, "author": "terjetyl", "author_id": 29519, "author_profile": "https://Stackoverflow.com/users/29519", "pm_score": 2, "selected": false, "text": "<p>These extension methods are pretty useful for me when parsing form input before putting into the database</p>\n\n<pre><code>public static int? ToInt(this string input) \n{\n int val;\n if (int.TryParse(input, out val))\n return val;\n return null;\n}\n\npublic static DateTime? ToDate(this string input)\n{\n DateTime val;\n if (DateTime.TryParse(input, out val))\n return val;\n return null;\n}\n\npublic static decimal? ToDecimal(this string input)\n{\n decimal val;\n if (decimal.TryParse(input, out val))\n return val;\n return null;\n}\n</code></pre>\n" }, { "answer_id": 330044, "author": "cbp", "author_id": 21966, "author_profile": "https://Stackoverflow.com/users/21966", "pm_score": 2, "selected": false, "text": "<p>I like these methods for dealing with enums that have the Flags attribute set:</p>\n\n<pre><code>public static bool AnyOf(this object mask, object flags)\n{\n return ((int)mask &amp; (int)flags) != 0;\n}\npublic static bool AllOf(this object mask, object flags)\n{\n return ((int)mask &amp; (int)flags) == (int)flags;\n}\npublic static object SetOn(this object mask, object flags)\n{\n return (int)mask | (int)flags;\n}\netc.\n</code></pre>\n\n<p>Example usage:</p>\n\n<pre><code>var options = SomeOptions.OptionA;\noptions = options.SetOn(OptionB);\noptions = options.SetOn(OptionC);\n\nif (options.AnyOf(SomeOptions.OptionA | SomeOptions.OptionB))\n{\netc.\n</code></pre>\n\n<p>The original methods were from this article: <a href=\"http://www.codeproject.com/KB/cs/masksandflags.aspx?display=Print\" rel=\"nofollow noreferrer\">http://www.codeproject.com/KB/cs/masksandflags.aspx?display=Print</a>\nI just converted them to extension methods.</p>\n\n<p>The one problem with them though is that the parameters of object type, which means that <em>all</em> objects end up being extended with these methods, whereas ideally they should only apply to enums.</p>\n\n<p><strong>Update</strong>\nAs per the comments, you can get around the \"signature pollution\", at the expense of performance, like this:</p>\n\n<pre><code>public static bool AnyOf(this Enum mask, object flags)\n{\n return (Convert.ToInt642(mask) &amp; (int)flags) != 0;\n}\n</code></pre>\n" }, { "answer_id": 346181, "author": "Rinat Abdullin", "author_id": 47366, "author_profile": "https://Stackoverflow.com/users/47366", "pm_score": 3, "selected": false, "text": "<p>Timespan-related extensions like:</p>\n\n<pre><code>public static TimeSpan Seconds(this int seconds)\n{\n return TimeSpan.FromSeconds(seconds);\n}\n\npublic static TimeSpan Minutes(this int minutes)\n{\n return TimeSpan.FromMinutes(minutes);\n}\n</code></pre>\n\n<p>That allow to use:</p>\n\n<pre><code>1.Seconds()\n20.Minutes()\n</code></pre>\n\n<p>Lock extensions like:</p>\n\n<pre><code>public static IDisposable GetReadLock(this ReaderWriterLockSlim slimLock)\n{\n slimLock.EnterReadLock();\n return new DisposableAction(slimLock.ExitReadLock);\n}\n\npublic static IDisposable GetWriteLock(this ReaderWriterLockSlim slimLock)\n{\n slimLock.EnterWriteLock();\n return new DisposableAction(slimLock.ExitWriteLock);\n}\n\npublic static IDisposable GetUpgradeableReadLock(this ReaderWriterLockSlim slimLock)\n{\n slimLock.EnterUpgradeableReadLock();\n return new DisposableAction(slimLock.ExitUpgradeableReadLock);\n}\n</code></pre>\n\n<p>That allow to use locks like:</p>\n\n<pre><code>using (lock.GetUpgradeableReadLock())\n{\n // try read\n using (lock.GetWriteLock())\n {\n //do write\n }\n}\n</code></pre>\n\n<p>And many other from the <a href=\"http://rabdullin.com/shared-libraries/\" rel=\"nofollow noreferrer\">Lokad Shared Libraries</a></p>\n" }, { "answer_id": 357344, "author": "Robert Dean", "author_id": 3396, "author_profile": "https://Stackoverflow.com/users/3396", "pm_score": 1, "selected": false, "text": "<p>This is an extension method for the ASP.Net MVC action link helper method that allows it to use the controller's authorize attributes to decide if the link should be enabled, disabled or hidden from the current user's view. \nI saves you from having to enclose your restricted actions in \"if\" clauses that check for user membership in all the views. Thanks to <a href=\"http://blog.maartenballiauw.be/post/2008/08/29/Building-an-ASPNET-MVC-sitemap-provider-with-security-trimming.aspx\" rel=\"nofollow noreferrer\">Maarten Balliauw</a> for the idea and the code bits that showed me the way :)</p>\n\n<pre><code>using System;\nusing System.Collections.Generic;\nusing System.Linq;\nusing System.Web;\nusing System.Security.Principal;\nusing System.Web.Routing;\nusing System.Web.Mvc;\nusing System.Collections;\nusing System.Reflection;\nnamespace System.Web.Mvc.Html\n{\n public static class HtmlHelperExtensions\n {\n\n /// &lt;summary&gt;\n /// Shows or hides an action link based on the user's membership status\n /// and the controller's authorize attributes\n /// &lt;/summary&gt;\n /// &lt;param name=\"linkText\"&gt;The link text.&lt;/param&gt;\n /// &lt;param name=\"action\"&gt;The controller action name.&lt;/param&gt;\n /// &lt;param name=\"controller\"&gt;The controller name.&lt;/param&gt;\n /// &lt;returns&gt;&lt;/returns&gt;\n public static string SecurityTrimmedActionLink(\n this HtmlHelper htmlHelper,\n string linkText,\n string action,\n string controller)\n {\n return SecurityTrimmedActionLink(htmlHelper, linkText, action, controller, false, null);\n }\n\n /// &lt;summary&gt;\n /// Enables, disables or hides an action link based on the user's membership status\n /// and the controller's authorize attributes\n /// &lt;/summary&gt;\n /// &lt;param name=\"linkText\"&gt;The link text.&lt;/param&gt;\n /// &lt;param name=\"action\"&gt;The action name.&lt;/param&gt;\n /// &lt;param name=\"controller\"&gt;The controller name.&lt;/param&gt;\n /// &lt;param name=\"showDisabled\"&gt;if set to &lt;c&gt;true&lt;/c&gt; [show link as disabled - \n /// using a span tag instead of an anchor tag ].&lt;/param&gt;\n /// &lt;param name=\"disabledAttributeText\"&gt;Use this to add attributes to the disabled\n /// span tag.&lt;/param&gt;\n /// &lt;returns&gt;&lt;/returns&gt;\n public static string SecurityTrimmedActionLink(\n this HtmlHelper htmlHelper, \n string linkText, \n string action, \n string controller, \n bool showDisabled, \n string disabledAttributeText)\n {\n if (IsAccessibleToUser(action, controller, HttpContext.Current ))\n {\n return htmlHelper.ActionLink(linkText, action, controller);\n }\n else\n {\n return showDisabled ? \n String.Format(\n \"&lt;span{1}&gt;{0}&lt;/span&gt;\", \n linkText, \n disabledAttributeText==null?\"\":\" \"+disabledAttributeText\n ) : \"\";\n }\n }\n\n private static IController GetControllerInstance(string controllerName)\n {\n Assembly assembly = Assembly.GetExecutingAssembly();\n Type controllerType = GetControllerType(controllerName);\n return (IController)Activator.CreateInstance(controllerType);\n }\n\n private static ArrayList GetControllerAttributes(string controllerName, HttpContext context)\n {\n if (context.Cache[controllerName + \"_ControllerAttributes\"] == null)\n {\n var controller = GetControllerInstance(controllerName);\n\n context.Cache.Add(\n controllerName + \"_ControllerAttributes\",\n new ArrayList(controller.GetType().GetCustomAttributes(typeof(AuthorizeAttribute), true)),\n null,\n Caching.Cache.NoAbsoluteExpiration,\n Caching.Cache.NoSlidingExpiration,\n Caching.CacheItemPriority.Default,\n null);\n\n }\n return (ArrayList)context.Cache[controllerName + \"_ControllerAttributes\"];\n\n }\n\n private static ArrayList GetMethodAttributes(string controllerName, string actionName, HttpContext context)\n {\n if (context.Cache[controllerName + \"_\" + actionName + \"_ActionAttributes\"] == null)\n {\n ArrayList actionAttrs = new ArrayList();\n var controller = GetControllerInstance(controllerName);\n MethodInfo[] methods = controller.GetType().GetMethods();\n\n foreach (MethodInfo method in methods)\n {\n object[] attributes = method.GetCustomAttributes(typeof(ActionNameAttribute), true);\n\n if ((attributes.Length == 0 &amp;&amp; method.Name == actionName)\n ||\n (attributes.Length &gt; 0 &amp;&amp; ((ActionNameAttribute)attributes[0]).Name == actionName))\n {\n actionAttrs.AddRange(method.GetCustomAttributes(typeof(AuthorizeAttribute), true));\n }\n }\n\n context.Cache.Add(\n controllerName + \"_\" + actionName + \"_ActionAttributes\",\n actionAttrs,\n null,\n Caching.Cache.NoAbsoluteExpiration,\n Caching.Cache.NoSlidingExpiration,\n Caching.CacheItemPriority.Default,\n null);\n\n }\n\n return (ArrayList)context.Cache[controllerName + \"_\" + actionName+ \"_ActionAttributes\"]; \n }\n\n public static bool IsAccessibleToUser(string actionToAuthorize, string controllerToAuthorize, HttpContext context)\n {\n IPrincipal principal = context.User;\n\n //cache the attribute list for both controller class and it's methods\n\n ArrayList controllerAttributes = GetControllerAttributes(controllerToAuthorize, context);\n\n ArrayList actionAttributes = GetMethodAttributes(controllerToAuthorize, actionToAuthorize, context); \n\n if (controllerAttributes.Count == 0 &amp;&amp; actionAttributes.Count == 0)\n return true;\n\n string roles = \"\";\n string users = \"\";\n if (controllerAttributes.Count &gt; 0)\n {\n AuthorizeAttribute attribute = controllerAttributes[0] as AuthorizeAttribute;\n roles += attribute.Roles;\n users += attribute.Users;\n }\n if (actionAttributes.Count &gt; 0)\n {\n AuthorizeAttribute attribute = actionAttributes[0] as AuthorizeAttribute;\n roles += attribute.Roles;\n users += attribute.Users;\n }\n\n if (string.IsNullOrEmpty(roles) &amp;&amp; string.IsNullOrEmpty(users) &amp;&amp; principal.Identity.IsAuthenticated)\n return true;\n\n string[] roleArray = roles.Split(',');\n string[] usersArray = users.Split(',');\n foreach (string role in roleArray)\n {\n if (role == \"*\" || principal.IsInRole(role))\n return true;\n }\n foreach (string user in usersArray)\n {\n if (user == \"*\" &amp;&amp; (principal.Identity.Name == user))\n return true;\n }\n return false;\n }\n\n private static Type GetControllerType(string controllerName)\n {\n Assembly assembly = Assembly.GetExecutingAssembly();\n foreach (Type type in assembly.GetTypes())\n {\n if (\n type.BaseType!=null \n &amp;&amp; type.BaseType.Name == \"Controller\" \n &amp;&amp; (type.Name.ToUpper() == (controllerName.ToUpper() + \"Controller\".ToUpper())))\n {\n return type;\n }\n }\n return null;\n }\n\n }\n}\n</code></pre>\n" }, { "answer_id": 358259, "author": "Mark Cidade", "author_id": 1659, "author_profile": "https://Stackoverflow.com/users/1659", "pm_score": 3, "selected": false, "text": "<pre><code>static string Format( this string str,\n , params Expression&lt;Func&lt;string,object&gt;&gt;[] args)\n{\n var parameters = args.ToDictionary\n ( e=&gt;string.Format(\"{{{0}}}\",e.Parameters[0].Name)\n , e=&gt;e.Compile()(e.Parameters[0].Name));\n\n var sb = new StringBuilder(str);\n foreach(var kv in parameters)\n {\n sb.Replace( kv.Key\n , kv.Value != null ? kv.Value.ToString() : \"\");\n }\n\n return sb.ToString();\n}\n</code></pre>\n\n<p>With the above extension you can write this:</p>\n\n<pre><code>var str = \"{foo} {bar} {baz}\".Format(foo=&gt;foo, bar=&gt;2, baz=&gt;new object());\n</code></pre>\n\n<p>and you'll get <code>\"foo 2 System.Object</code>\".</p>\n" }, { "answer_id": 375076, "author": "Mark Cidade", "author_id": 1659, "author_profile": "https://Stackoverflow.com/users/1659", "pm_score": 0, "selected": false, "text": "<ul>\n<li><p>For adding multiple elements to a collection that doesn't have AddRange, e.g., <code>collection.Add(item1, item2, itemN);</code></p>\n\n<pre><code>static void Add&lt;T&gt;(this ICollection&lt;T&gt; coll, params T[] items)\n { foreach (var item in items) coll.Add(item);\n }\n</code></pre></li>\n<li><p>The following is like <code>string.Format()</code> but with custom string representation of arguments, e.g., <code>\"{0} {1} {2}\".Format&lt;Custom&gt;(c=&gt;c.Name,\"string\",new object(),new Custom())</code> results in <code>\"string {System.Object} Custom1Name\"</code></p>\n\n<pre><code>static string Format&lt;T&gt;( this string format\n , Func&lt;T,object&gt; select\n , params object[] args)\n { for(int i=0; i &lt; 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></li>\n</ul>\n" }, { "answer_id": 398308, "author": "Mark Maxham", "author_id": 49737, "author_profile": "https://Stackoverflow.com/users/49737", "pm_score": 3, "selected": false, "text": "<p>Simple but nicer than \"Enumerable.Range\", IMHO:</p>\n\n<pre><code>/// &lt;summary&gt;\n/// Replace \"Enumerable.Range(n)\" with \"n.Range()\":\n/// &lt;/summary&gt;\n/// &lt;param name=\"n\"&gt;iterations&lt;/param&gt;\n/// &lt;returns&gt;0..n-1&lt;/returns&gt;\npublic static IEnumerable&lt;int&gt; Range(this int n)\n{\n for (int i = 0; i &lt; n; i++)\n yield return i;\n}\n</code></pre>\n" }, { "answer_id": 398423, "author": "Mark Maxham", "author_id": 49737, "author_profile": "https://Stackoverflow.com/users/49737", "pm_score": 1, "selected": false, "text": "<p>Equivalent to Python's Join method:</p>\n\n<pre><code>/// &lt;summary&gt;\n/// same as python 'join'\n/// &lt;/summary&gt;\n/// &lt;typeparam name=\"T\"&gt;list type&lt;/typeparam&gt;\n/// &lt;param name=\"separator\"&gt;string separator &lt;/param&gt;\n/// &lt;param name=\"list\"&gt;list of objects to be ToString'd&lt;/param&gt;\n/// &lt;returns&gt;a concatenated list interleaved with separators&lt;/returns&gt;\nstatic public string Join&lt;T&gt;(this string separator, IEnumerable&lt;T&gt; list)\n{\n var sb = new StringBuilder();\n bool first = true;\n\n foreach (T v in list)\n {\n if (!first)\n sb.Append(separator);\n first = false;\n\n if (v != null)\n sb.Append(v.ToString());\n }\n\n return sb.ToString();\n}\n</code></pre>\n" }, { "answer_id": 414561, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 3, "selected": false, "text": "<p>I use this extension method usually with anonymous types to get a dictionary ala ruby</p>\n\n<pre><code>public static Dictionary&lt;string, object&gt; ToDictionary(this object o)\n{\n var dictionary = new Dictionary&lt;string, object&gt;();\n\n foreach (var propertyInfo in o.GetType().GetProperties())\n {\n if (propertyInfo.GetIndexParameters().Length == 0)\n {\n dictionary.Add(propertyInfo.Name, propertyInfo.GetValue(o, null));\n }\n }\n\n return dictionary;\n}\n</code></pre>\n\n<p>You can use it </p>\n\n<pre><code>var dummy = new { color = \"#000000\", width = \"100%\", id = \"myid\" };\nDictionary&lt;string, object&gt; dict = dummy.ToDictionary();\n</code></pre>\n\n<p>And with an extended method as </p>\n\n<pre><code>public static void ForEach&lt;T&gt;(this IEnumerable&lt;T&gt; source, Action&lt;T&gt; action)\n{\n foreach (T item in source)\n {\n action(item);\n }\n}\n</code></pre>\n\n<p>You can do it</p>\n\n<pre><code>dummy.ToDictionary().ForEach((p) =&gt; Console.Write(\"{0}='{1}' \", p.Key, p.Value));\n</code></pre>\n\n<p>Output </p>\n\n<p>color='#000000' width='100%' id='myid'</p>\n" }, { "answer_id": 423447, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 1, "selected": false, "text": "<p>Convert any string to type Int32</p>\n\n<pre><code>// Calls the underlying int.TryParse method to convert a string\n// representation of a number to its 32-bit signed integer equivalent.\n// Returns Zero if conversion fails. \npublic static int ToInt32(this string s)\n{\n int retInt;\n int.TryParse(s, out retInt);\n return retInt;\n}\n</code></pre>\n\n<p>SAMPLE USE:<br>\n<code>string s = \"999\";</code><br>\n<code>int i = s.ToInt32();</code></p>\n" }, { "answer_id": 423553, "author": "Chris", "author_id": 52811, "author_profile": "https://Stackoverflow.com/users/52811", "pm_score": 0, "selected": false, "text": "<pre><code>// Values ordered true/false\n// True/false values separated by a capital letter\n// Only two values allowed\n// ---------------------------\n// Limited, but could be useful\npublic enum BooleanFormat\n{\n OneZero,\n YN,\n YesNo,\n TF,\n TrueFalse,\n PassFail,\n YepNope\n}\n\npublic static class BooleanExtension\n{\n /// &lt;summary&gt;\n /// Converts the boolean value of this instance to the specified string value. \n /// &lt;/summary&gt;\n private static string ToString(this bool value, string passValue, string failValue)\n {\n return value ? passValue : failValue;\n }\n\n /// &lt;summary&gt;\n /// Converts the boolean value of this instance to a string. \n /// &lt;/summary&gt;\n /// &lt;param name=\"booleanFormat\"&gt;A BooleanFormat value. \n /// Example: BooleanFormat.PassFail would return \"Pass\" if true and \"Fail\" if false.&lt;/param&gt;\n /// &lt;returns&gt;Boolean formatted string&lt;/returns&gt;\n public static string ToString(this bool value, BooleanFormat booleanFormat)\n {\n string booleanFormatString = Enum.GetName(booleanFormat.GetType(), booleanFormat);\n return ParseBooleanString(value, booleanFormatString); \n }\n\n // Parses boolean format strings, not optimized\n private static string ParseBooleanString(bool value, string booleanFormatString)\n {\n StringBuilder trueString = new StringBuilder();\n StringBuilder falseString = new StringBuilder();\n\n int charCount = booleanFormatString.Length;\n\n bool isTrueString = true;\n\n for (int i = 0; i != charCount; i++)\n {\n if (char.IsUpper(booleanFormatString[i]) &amp;&amp; i != 0)\n isTrueString = false;\n\n if (isTrueString)\n trueString.Append(booleanFormatString[i]);\n else\n falseString.Append(booleanFormatString[i]);\n }\n\n return (value == true ? trueString.ToString() : falseString.ToString());\n }\n</code></pre>\n" }, { "answer_id": 423555, "author": "Jonathan C Dickinson", "author_id": 24064, "author_profile": "https://Stackoverflow.com/users/24064", "pm_score": 1, "selected": false, "text": "<p>A generic Try:</p>\n\n<pre><code>class Program\n{\n static void Main(string[] args)\n {\n var z = 0;\n var a = 0.AsDefaultFor(() =&gt; 1 / z);\n Console.WriteLine(a);\n Console.ReadLine();\n }\n}\n\npublic static class TryExtensions\n{\n public static T AsDefaultFor&lt;T&gt;(this T @this, Func&lt;T&gt; operation)\n {\n try\n {\n return operation();\n }\n catch\n {\n return @this;\n }\n }\n}\n</code></pre>\n\n<p>Put it up on the CodePlex project if you want.</p>\n" }, { "answer_id": 450208, "author": "chakrit", "author_id": 3055, "author_profile": "https://Stackoverflow.com/users/3055", "pm_score": 5, "selected": false, "text": "<p>I miss the <a href=\"http://msdn.microsoft.com/en-us/library/wc500chb(VS.80).aspx\" rel=\"nofollow noreferrer\">Visual Basic's With statement</a> when moving to C#, so here it goes:</p>\n\n<pre><code>public static void With&lt;T&gt;(this T obj, Action&lt;T&gt; act) { act(obj); }\n</code></pre>\n\n<p>And here's how to use it in C#:</p>\n\n<pre><code>someVeryVeryLonggggVariableName.With(x =&gt; {\n x.Int = 123;\n x.Str = \"Hello\";\n x.Str2 = \" World!\";\n});\n</code></pre>\n\n<p>Saves a lot of typing!</p>\n\n<p>Compare this to:</p>\n\n<pre><code>someVeryVeryLonggggVariableName.Int = 123;\nsomeVeryVeryLonggggVariableName.Str = \"Hello\";\nsomeVeryVeryLonggggVariableName.Str2 = \" World!\";\n</code></pre>\n\n<p><em>put in codeplex project</em></p>\n" }, { "answer_id": 486879, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 0, "selected": false, "text": "<p>Perhaps the most useful extension methods I've written and used are here:</p>\n\n<p><a href=\"http://www.codeproject.com/KB/cs/fun-with-cs-extensions.aspx?msg=2838918#xx2838918xx\" rel=\"nofollow noreferrer\">http://www.codeproject.com/KB/cs/fun-with-cs-extensions.aspx?msg=2838918#xx2838918xx</a></p>\n" }, { "answer_id": 572953, "author": "andleer", "author_id": 64262, "author_profile": "https://Stackoverflow.com/users/64262", "pm_score": 1, "selected": false, "text": "<p>The <b>WhereIf()</b> Method</p>\n\n<pre><code>var query = dc.Reviewer \n .Where(r =&gt; r.FacilityID == facilityID) \n .WhereIf(CheckBoxActive.Checked, r =&gt; r.IsActive); \n\npublic static IEnumerable&lt;TSource&gt; WhereIf&lt;TSource&gt;(\n this IEnumerable&lt;TSource&gt; source,\n bool condition, Func&lt;TSource, bool&gt; predicate) \n{ \n if (condition) \n return source.Where(predicate); \n else \n return source; \n}\n\npublic static IQueryable&lt;TSource&gt; WhereIf&lt;TSource&gt;(\n this IQueryable&lt;TSource&gt; source,\n bool condition, Expression&lt;Func&lt;TSource, bool&gt;&gt; predicate) \n{ \n if (condition) \n return source.Where(predicate); \n else \n return source; \n}\n</code></pre>\n\n<p>I also added overloads for the index predicate in the Where() extension method. For more fun, add a flavor that includes an additional 'else' predicate.</p>\n" }, { "answer_id": 572978, "author": "andleer", "author_id": 64262, "author_profile": "https://Stackoverflow.com/users/64262", "pm_score": 1, "selected": false, "text": "<p>Inline Conversions: I like this little pattern. Completed it for Boolean, Double and DateTime. Designed to follow the C# <em>is</em> and <em>as</em> operators.</p>\n\n<pre><code>public static Int32? AsInt32(this string s)\n{\n Int32 value;\n if (Int32.TryParse(s, out value))\n return value;\n\n return null;\n}\n\npublic static bool IsInt32(this string s)\n{\n return s.AsInt32().HasValue;\n}\n\npublic static Int32 ToInt32(this string s)\n{\n return Int32.Parse(s);\n{\n</code></pre>\n" }, { "answer_id": 833363, "author": "Stefan Steinegger", "author_id": 2658202, "author_profile": "https://Stackoverflow.com/users/2658202", "pm_score": 2, "selected": false, "text": "<p>GetMemberName allows to get the string with the name of a member with compile time safety.</p>\n\n<pre><code>public static string GetMemberName&lt;T, TResult&gt;(\n this T anyObject, \n Expression&lt;Func&lt;T, TResult&gt;&gt; expression)\n{\n return ((MemberExpression)expression.Body).Member.Name;\n}\n</code></pre>\n\n<p>Usage:</p>\n\n<pre><code>\"blah\".GetMemberName(x =&gt; x.Length); // returns \"Length\"\n</code></pre>\n\n<hr>\n\n<p>It comes together with a non-extension static method if you don't have a instance:</p>\n\n<pre><code>public static string GetMemberName&lt;T, TReturn&gt;(\n Expression&lt;Func&lt;T, TReturn&gt;&gt; expression)\n where T : class\n{\n return ((MemberExpression)expression.Body).Member.Name;\n}\n</code></pre>\n\n<p>But the call doesn't look as pretty of course:</p>\n\n<pre><code>ReflectionUtility.GetMemberName((string) s =&gt; s.Length); // returns \"Length\"\n</code></pre>\n\n<hr>\n\n<p>You can put it on Codeplex if you want.</p>\n" }, { "answer_id": 833477, "author": "Winston Smith", "author_id": 35086, "author_profile": "https://Stackoverflow.com/users/35086", "pm_score": 8, "selected": false, "text": "<pre><code>public static bool In&lt;T&gt;(this T source, params T[] list)\n{\n if(null==source) throw new ArgumentNullException(\"source\");\n return list.Contains(source);\n}\n</code></pre>\n\n<p>Allows me to replace:</p>\n\n<pre><code>if(reallyLongIntegerVariableName == 1 || \n reallyLongIntegerVariableName == 6 || \n reallyLongIntegerVariableName == 9 || \n reallyLongIntegerVariableName == 11)\n{\n // do something....\n}\n\nand\n\nif(reallyLongStringVariableName == \"string1\" || \n reallyLongStringVariableName == \"string2\" || \n reallyLongStringVariableName == \"string3\")\n{\n // do something....\n}\n\nand\n\nif(reallyLongMethodParameterName == SomeEnum.Value1 || \n reallyLongMethodParameterName == SomeEnum.Value2 || \n reallyLongMethodParameterName == SomeEnum.Value3 || \n reallyLongMethodParameterName == SomeEnum.Value4)\n{\n // do something....\n}\n</code></pre>\n\n<p>With:</p>\n\n<pre><code>if(reallyLongIntegerVariableName.In(1,6,9,11))\n{\n // do something....\n}\n\nand\n\nif(reallyLongStringVariableName.In(\"string1\",\"string2\",\"string3\"))\n{\n // do something....\n}\n\nand\n\nif(reallyLongMethodParameterName.In(SomeEnum.Value1, SomeEnum.Value2, SomeEnum.Value3, SomeEnum.Value4)\n{\n // do something....\n}\n</code></pre>\n" }, { "answer_id": 858681, "author": "Joel Mueller", "author_id": 24380, "author_profile": "https://Stackoverflow.com/users/24380", "pm_score": 4, "selected": false, "text": "<p>It irritated me that LINQ gives me an OrderBy that takes a class implementing IComparer as an argument, but does not support passing in a simple anonymous comparer function. I rectified that.</p>\n\n<p>This class creates an IComparer from your comparer function...</p>\n\n<pre><code>/// &lt;summary&gt;\n/// Creates an &lt;see cref=\"IComparer{T}\"/&gt; instance for the given\n/// delegate function.\n/// &lt;/summary&gt;\ninternal class ComparerFactory&lt;T&gt; : IComparer&lt;T&gt;\n{\n public static IComparer&lt;T&gt; Create(Func&lt;T, T, int&gt; comparison)\n {\n return new ComparerFactory&lt;T&gt;(comparison);\n }\n\n private readonly Func&lt;T, T, int&gt; _comparison;\n\n private ComparerFactory(Func&lt;T, T, int&gt; comparison)\n {\n _comparison = comparison;\n }\n\n #region IComparer&lt;T&gt; Members\n\n public int Compare(T x, T y)\n {\n return _comparison(x, y);\n }\n\n #endregion\n}\n</code></pre>\n\n<p>...and these extension methods expose my new OrderBy overloads on enumerables. I doubt this works for LINQ to SQL, but it's great for LINQ to Objects.</p>\n\n<pre><code>public static class EnumerableExtensions\n{\n /// &lt;summary&gt;\n /// Sorts the elements of a sequence in ascending order by using a specified comparison delegate.\n /// &lt;/summary&gt;\n public static IOrderedEnumerable&lt;TSource&gt; OrderBy&lt;TSource, TKey&gt;(this IEnumerable&lt;TSource&gt; source, Func&lt;TSource, TKey&gt; keySelector,\n Func&lt;TKey, TKey, int&gt; comparison)\n {\n var comparer = ComparerFactory&lt;TKey&gt;.Create(comparison);\n return source.OrderBy(keySelector, comparer);\n }\n\n /// &lt;summary&gt;\n /// Sorts the elements of a sequence in descending order by using a specified comparison delegate.\n /// &lt;/summary&gt;\n public static IOrderedEnumerable&lt;TSource&gt; OrderByDescending&lt;TSource, TKey&gt;(this IEnumerable&lt;TSource&gt; source, Func&lt;TSource, TKey&gt; keySelector,\n Func&lt;TKey, TKey, int&gt; comparison)\n {\n var comparer = ComparerFactory&lt;TKey&gt;.Create(comparison);\n return source.OrderByDescending(keySelector, comparer);\n }\n}\n</code></pre>\n\n<p>You're welcome to put this on codeplex if you like.</p>\n" }, { "answer_id": 953674, "author": "Manish Basantani", "author_id": 93613, "author_profile": "https://Stackoverflow.com/users/93613", "pm_score": 0, "selected": false, "text": "<pre><code>// Checks for an empty collection, and sends the value set in the default constructor for the desired field\npublic static TResult MinGuarded&lt;T, TResult&gt;(this IEnumerable&lt;T&gt; items, Func&lt;T, TResult&gt; expression) where T : new() {\n if(items.IsEmpty()) {\n return (new List&lt;T&gt; { new T() }).Min(expression);\n }\n return items.Min(expression);\n}\n\n// Checks for an empty collection, and sends the value set in the default constructor for the desired field\npublic static TResult MaxGuarded&lt;T, TResult&gt;(this IEnumerable&lt;T&gt; items, Func&lt;T, TResult&gt; expression) where T : new() {\n if(items.IsEmpty()) {\n return (new List&lt;T&gt; { new T() }).Max(expression);\n }\n return items.Max(expression);\n}\n</code></pre>\n\n<p>I am not sure if there is a better way to do this, but this extension is very helpful whenever I want to have control over the default values of fields in my object.<br>\nFor instance, if I want to control the value of a DateTime and want to be set as per my business logic, then I can do so in the default constructor. Otherwise, it comes out to be <code>DateTime.MinDate</code>.</p>\n" }, { "answer_id": 958020, "author": "Vasu Balakrishnan", "author_id": 1879756, "author_profile": "https://Stackoverflow.com/users/1879756", "pm_score": 4, "selected": false, "text": "<p>I found this one helpful</p>\n\n<pre><code>public static IEnumerable&lt;T&gt; EmptyIfNull&lt;T&gt;(this IEnumerable&lt;T&gt; pSeq)\n{\n return pSeq ?? Enumerable.Empty&lt;T&gt;();\n}\n</code></pre>\n\n<p>It removes the null check in the calling code. You could now do</p>\n\n<pre><code>MyList.EmptyIfNull().Where(....)\n</code></pre>\n" }, { "answer_id": 1110456, "author": "Fredy Treboux", "author_id": 55154, "author_profile": "https://Stackoverflow.com/users/55154", "pm_score": 1, "selected": false, "text": "<p>Several times I found myself wanting something like, I think, Groovy's \"Safe navigation\".</p>\n\n<p>From <a href=\"http://groovy.codehaus.org/Statements\" rel=\"nofollow noreferrer\">http://groovy.codehaus.org/Statements</a>:</p>\n\n<blockquote>\n <p>If you are walking a complex object\n graph and don't want to have\n NullPointerExceptions thrown you can\n use the ?. operator rather than . to\n perform your navigation.</p>\n \n <p>def foo = null def bar =\n foo?.something?.myMethod() assert bar\n == null</p>\n</blockquote>\n\n<p>So, do you think is a good idea adding an extension method for it?\nSomething like:</p>\n\n<pre><code>obj.SafelyNavigate(x =&gt; x.SomeProperty.MaybeAMethod().AnotherProperty);\n</code></pre>\n\n<p>I think it would be nice even if it can also bring some trouble.</p>\n\n<p>If you think it's a good idea:</p>\n\n<ul>\n<li>What would you think it should happen for value types?, \nreturn default? throw?, disable it by generic constraint?.</li>\n<li>Swallowing NullReferenceException to implement it would be too risky?,\nWhat do you propose?, \nWalking the expression tree executing every call or member access seems difficult and kind of overkill (if at all possible) doesn't it?.</li>\n</ul>\n\n<p>Maybe it's just a bad idea :D, but I see it like something that can be useful if done right.\nIf there's nothing like it and you think it holds some value, I may give it a shot and edit the answer afterwards.</p>\n" }, { "answer_id": 1130145, "author": "Kenny Eliasson", "author_id": 107342, "author_profile": "https://Stackoverflow.com/users/107342", "pm_score": 3, "selected": false, "text": "<p>Sometimes its handy to write out a string on a selected element in a list with a custom seperator.</p>\n\n<p>For instance if you have a <code>List&lt;Person&gt;</code> and want to loop out lastname seperated with a comma you could do this.</p>\n\n<pre><code>string result = string.Empty;\nforeach (var person in personList) {\n result += person.LastName + \", \";\n}\nresult = result.Substring(0, result.Length - 2);\nreturn result;\n</code></pre>\n\n<p>Or you could use this handy extension method</p>\n\n<pre><code>public static string Join&lt;T&gt;(this IEnumerable&lt;T&gt; collection, Func&lt;T, string&gt; func, string separator)\n{\n return String.Join(separator, collection.Select(func).ToArray());\n}\n</code></pre>\n\n<p>And use it like this</p>\n\n<pre><code>personList.Join(x =&gt; x.LastName, \", \");\n</code></pre>\n\n<p>Which produces the same result, in this case a list of lastnames seperated by a comma.</p>\n" }, { "answer_id": 1251338, "author": "Chris S", "author_id": 21574, "author_profile": "https://Stackoverflow.com/users/21574", "pm_score": 4, "selected": false, "text": "<p>Below is an <a href=\"http://www.shrinkrays.net/code-snippets/csharp/an-extension-method-for-converting-a-byte-array-to-a-string.aspx\" rel=\"nofollow noreferrer\">extension method</a> that adapts <a href=\"http://www.west-wind.com/WebLog/posts/197245.aspx\" rel=\"nofollow noreferrer\">Rick Strahl's code</a> (and the comments too) to stop you having to guess or read the byte order mark of a byte array or text file each time you convert it to a string.</p>\n\n<p>The snippet allows you to simply do:</p>\n\n<pre><code>byte[] buffer = File.ReadAllBytes(@\"C:\\file.txt\");\nstring content = buffer.GetString();\n</code></pre>\n\n<p>If you find any bugs please add to the comments. Feel free to include it in the Codeplex project.</p>\n\n<pre><code>public static class Extensions\n{\n /// &lt;summary&gt;\n /// Converts a byte array to a string, using its byte order mark to convert it to the right encoding.\n /// Original article: http://www.west-wind.com/WebLog/posts/197245.aspx\n /// &lt;/summary&gt;\n /// &lt;param name=\"buffer\"&gt;An array of bytes to convert&lt;/param&gt;\n /// &lt;returns&gt;The byte as a string.&lt;/returns&gt;\n public static string GetString(this byte[] buffer)\n {\n if (buffer == null || buffer.Length == 0)\n return \"\";\n\n // Ansi as default\n Encoding encoding = Encoding.Default; \n\n /*\n EF BB BF UTF-8 \n FF FE UTF-16 little endian \n FE FF UTF-16 big endian \n FF FE 00 00 UTF-32, little endian \n 00 00 FE FF UTF-32, big-endian \n */\n\n if (buffer[0] == 0xef &amp;&amp; buffer[1] == 0xbb &amp;&amp; buffer[2] == 0xbf)\n encoding = Encoding.UTF8;\n else if (buffer[0] == 0xfe &amp;&amp; buffer[1] == 0xff)\n encoding = Encoding.Unicode;\n else if (buffer[0] == 0xfe &amp;&amp; buffer[1] == 0xff)\n encoding = Encoding.BigEndianUnicode; // utf-16be\n else if (buffer[0] == 0 &amp;&amp; buffer[1] == 0 &amp;&amp; buffer[2] == 0xfe &amp;&amp; buffer[3] == 0xff)\n encoding = Encoding.UTF32;\n else if (buffer[0] == 0x2b &amp;&amp; buffer[1] == 0x2f &amp;&amp; buffer[2] == 0x76)\n encoding = Encoding.UTF7;\n\n using (MemoryStream stream = new MemoryStream())\n {\n stream.Write(buffer, 0, buffer.Length);\n stream.Seek(0, SeekOrigin.Begin);\n using (StreamReader reader = new StreamReader(stream, encoding))\n {\n return reader.ReadToEnd();\n }\n }\n }\n}\n</code></pre>\n" }, { "answer_id": 1394563, "author": "Chris S", "author_id": 21574, "author_profile": "https://Stackoverflow.com/users/21574", "pm_score": 1, "selected": false, "text": "<p>I'm always using format that wants a new line with <code>StringBuilder</code> so the very simple extension below saves a few lines of code:</p>\n\n<pre><code>public static class Extensions\n{\n public static void AppendLine(this StringBuilder builder,string format, params object[] args)\n {\n builder.AppendLine(string.Format(format, args));\n }\n}\n</code></pre>\n\n<p>The alternative is <code>AppendFormat</code> in <code>StringBuilder</code> with a <code>\\n</code> or Environment.NewLine.</p>\n" }, { "answer_id": 1434207, "author": "John Kraft", "author_id": 7495, "author_profile": "https://Stackoverflow.com/users/7495", "pm_score": 2, "selected": false, "text": "<p>Two little ones (some people find them silly) that I put in all my projects are:</p>\n\n<pre><code>public static bool IsNull(this object o){\n return o == null;\n}\n</code></pre>\n\n<p>and</p>\n\n<pre><code>public static bool IsNullOrEmpty(this string s){\n return string.IsNullOrEmpty(s);\n}\n</code></pre>\n\n<p>It makes my code so much more fluent..</p>\n\n<pre><code>if (myClassInstance.IsNull()) //... do something\n\nif (myString.IsNullOrEmpty()) //... do something\n</code></pre>\n\n<p>I think these would make really nice extension properties; if we ever get those.</p>\n" }, { "answer_id": 1460681, "author": "Konamiman", "author_id": 4574, "author_profile": "https://Stackoverflow.com/users/4574", "pm_score": 3, "selected": false, "text": "<p>I use these in my Silverlight projects:</p>\n\n<pre><code>public static void Show(this UIElement element)\n{\n element.Visibility = Visibility.Visible;\n}\n\npublic static void Hide(this UIElement element)\n{\n element.Visibility = Visibility.Collapsed;\n}\n</code></pre>\n" }, { "answer_id": 1512463, "author": "Omar", "author_id": 160823, "author_profile": "https://Stackoverflow.com/users/160823", "pm_score": 2, "selected": false, "text": "<p>Reduces the length of a string to <code>toLength</code> and adds an additional string to the end of the shortened string to denote that the string was shortened (Default <code>...</code>)</p>\n\n<pre><code>public static string Shorten(this string str, int toLength, string cutOffReplacement = \" ...\")\n{\n if (string.IsNullOrEmpty(str) || str.Length &lt;= toLength)\n return str;\n else\n return str.Remove(toLength) + cutOffReplacement;\n}\n</code></pre>\n" }, { "answer_id": 1543566, "author": "Paolo Tedesco", "author_id": 15622, "author_profile": "https://Stackoverflow.com/users/15622", "pm_score": 5, "selected": false, "text": "<p>A convenient way to deal with sizes: </p>\n\n<pre><code>public static class Extensions {\n public static int K(this int value) {\n return value * 1024;\n }\n public static int M(this int value) {\n return value * 1024 * 1024;\n }\n}\n\npublic class Program {\n public void Main() {\n WSHttpContextBinding serviceMultipleTokenBinding = new WSHttpContextBinding() {\n MaxBufferPoolSize = 2.M(), // instead of 2097152\n MaxReceivedMessageSize = 64.K(), // instead of 65536\n };\n }\n}\n</code></pre>\n" }, { "answer_id": 1662833, "author": "Greg", "author_id": 12971, "author_profile": "https://Stackoverflow.com/users/12971", "pm_score": 2, "selected": false, "text": "<p>FindControl with built-in casting:</p>\n\n<pre><code>public static T FindControl&lt;T&gt;(this Control control, string id) where T : Control\n{\n return (T)control.FindControl(id);\n}\n</code></pre>\n\n<p>It's nothing amazing, but I feel it makes for cleaner code. </p>\n\n<pre><code>// With extension method\ncontainer.FindControl&lt;TextBox&gt;(\"myTextBox\").SelectedValue = \"Hello world!\";\n\n// Without extension method\n((TextBox)container.FindControl(\"myTextBox\")).SelectedValue = \"Hello world!\";\n</code></pre>\n\n<p><em>This can be put this in the codeplex project, if so desired</em></p>\n" }, { "answer_id": 1662892, "author": "Greg", "author_id": 12971, "author_profile": "https://Stackoverflow.com/users/12971", "pm_score": 1, "selected": false, "text": "<p>A pattern for parsing that avoids <code>out</code> parameters:</p>\n\n<pre><code>public static bool TryParseInt32(this string input, Action&lt;int&gt; action)\n{\n int result;\n if (Int32.TryParse(input, out result))\n {\n action(result);\n return true;\n }\n return false;\n}\n</code></pre>\n\n<p>Usage:</p>\n\n<pre><code>if (!textBox.Text.TryParseInt32(number =&gt; label.Text = SomeMathFunction(number)))\n label.Text = \"Please enter a valid integer\";\n</code></pre>\n\n<p><em>This can be put this in the codeplex project, if so desired</em></p>\n" }, { "answer_id": 1742953, "author": "Dan Diplo", "author_id": 140392, "author_profile": "https://Stackoverflow.com/users/140392", "pm_score": 1, "selected": false, "text": "<p>In ASP.NET I always get fed up using FindControl and then having to cast and check if the value is null before referencing. So, I added a TryParse() method to <a href=\"http://msdn.microsoft.com/en-us/library/system.web.ui.control.aspx\" rel=\"nofollow noreferrer\">Control</a> that mirrors the similar ones in the framework for Int32 etc.</p>\n\n<pre><code>public static bool TryParse&lt;T&gt;(this Control control, string id, out T result) \n where T : Control\n{\n result = control.FindControl(id) as T;\n return result != null;\n}\n</code></pre>\n\n<p>So now you can do this in ASP.NET web-form pages:</p>\n\n<pre><code>Label lbl;\nif (Page.TryParse(\"Label1\", out lbl))\n{\n lbl.Text = \"Safely set text\";\n}\n</code></pre>\n" }, { "answer_id": 1766663, "author": "Juliet", "author_id": 40516, "author_profile": "https://Stackoverflow.com/users/40516", "pm_score": 5, "selected": false, "text": "<p>I find this one pretty useful:</p>\n\n<pre><code>public static class PaulaBean\n{\n private static String paula = \"Brillant\";\n public static String GetPaula&lt;T&gt;(this T obj) {\n return paula;\n }\n}\n</code></pre>\n\n<p>You may use it on CodePlex.</p>\n" }, { "answer_id": 1766799, "author": "Thomas Levesque", "author_id": 98713, "author_profile": "https://Stackoverflow.com/users/98713", "pm_score": 3, "selected": false, "text": "<p>Binary search :</p>\n\n<pre><code>public static T BinarySearch&lt;T, TKey&gt;(this IList&lt;T&gt; list, Func&lt;T, TKey&gt; keySelector, TKey key)\n where TKey : IComparable&lt;TKey&gt;\n{\n int min = 0;\n int max = list.Count;\n int index = 0;\n while (min &lt; max)\n {\n int mid = (max + min) / 2;\n T midItem = list[mid];\n TKey midKey = keySelector(midItem);\n int comp = midKey.CompareTo(key);\n if (comp &lt; 0)\n {\n min = mid + 1;\n }\n else if (comp &gt; 0)\n {\n max = mid - 1;\n }\n else\n {\n return midItem;\n }\n }\n if (min == max &amp;&amp;\n keySelector(list[min]).CompareTo(key) == 0)\n {\n return list[min];\n }\n throw new InvalidOperationException(\"Item not found\");\n}\n</code></pre>\n\n<p>Usage (assuming that the list is sorted by Id) :</p>\n\n<pre><code>var item = list.BinarySearch(i =&gt; i.Id, 42);\n</code></pre>\n\n<p>The fact that it throws an InvalidOperationException may seem strange, but that's what Enumerable.First does when there's no matching item.</p>\n" }, { "answer_id": 1767863, "author": "Thomas Levesque", "author_id": 98713, "author_profile": "https://Stackoverflow.com/users/98713", "pm_score": 2, "selected": false, "text": "<p>This one can be quite useful :</p>\n\n<pre><code> public static IEnumerable&lt;TResult&gt; Zip&lt;TFirst, TSecond, TResult&gt;(this IEnumerable&lt;TFirst&gt; first, IEnumerable&lt;TSecond&gt; second, Func&lt;TFirst, TSecond, TResult&gt; selector)\n {\n if (first == null)\n throw new ArgumentNullException(\"first\");\n if (second == null)\n throw new ArgumentNullException(\"second\");\n if (selector == null)\n throw new ArgumentNullException(\"selector\");\n\n using (var enum1 = first.GetEnumerator())\n using (var enum2 = second.GetEnumerator())\n {\n while (enum1.MoveNext() &amp;&amp; enum2.MoveNext())\n {\n yield return selector(enum1.Current, enum2.Current);\n }\n }\n }\n</code></pre>\n\n<p>It has been added to the <code>Enumerable</code> class in .NET 4.0, but it's handy to have it in 3.5.</p>\n\n<p>Example :</p>\n\n<pre><code>var names = new[] { \"Joe\", \"Jane\", \"Jack\", \"John\" };\nvar ages = new[] { 42, 22, 18, 33 };\n\nvar persons = names.Zip(ages, (n, a) =&gt; new { Name = n, Age = a });\n\nforeach (var p in persons)\n{\n Console.WriteLine(\"{0} is {1} years old\", p.Name, p.Age);\n}\n</code></pre>\n" }, { "answer_id": 1767920, "author": "RCIX", "author_id": 117069, "author_profile": "https://Stackoverflow.com/users/117069", "pm_score": 0, "selected": false, "text": "<p>Aww why not! Here's an extension to IList (can't be IEnumerable because i use list specific features) for insertion sort.</p>\n\n<pre><code>internal static class SortingHelpers\n{\n /// &lt;summary&gt;\n /// Performs an insertion sort on this list.\n /// &lt;/summary&gt;\n /// &lt;typeparam name=\"T\"&gt;The type of the list supplied.&lt;/typeparam&gt;\n /// &lt;param name=\"list\"&gt;the list to sort.&lt;/param&gt;\n /// &lt;param name=\"comparison\"&gt;the method for comparison of two elements.&lt;/param&gt;\n /// &lt;returns&gt;&lt;/returns&gt;\n public static void InsertionSort&lt;T&gt;(this IList&lt;T&gt; list, Comparison&lt;T&gt; comparison)\n {\n for (int i = 2; i &lt; list.Count; i++)\n {\n for (int j = i; j &gt; 1 &amp;&amp; comparison(list[j], list[j - 1]) &lt; 0; j--)\n {\n T tempItem = list[j];\n list.RemoveAt(j);\n list.Insert(j - 1, tempItem);\n }\n }\n }\n}\n</code></pre>\n\n<p>An example:</p>\n\n<pre><code>List&lt;int&gt; list1 = { 3, 5, 1, 2, 9, 4, 6 };\nlist1.InsertionSort((a,b) =&gt; a - b);\n//list is now in order of 1,2,3,4,5,6,9\n</code></pre>\n" }, { "answer_id": 1804870, "author": "tsilb", "author_id": 11112, "author_profile": "https://Stackoverflow.com/users/11112", "pm_score": 0, "selected": false, "text": "<p>In the recent searches section on my blog stats page, I had removed all duplicates, but needed a way to remove nearly-duplicate lines. I'd get tons of similar but not quite the same Google queries. </p>\n\n<p>I ended up using an anonymous type instead of a dictionary, but wanted a way to create a List of that anonymous type. You can't do that, but you can create a <code>List&lt;dynamic&gt;</code> in .NET 4.0 :)</p>\n\n<p>Mostly I like it because I effectively get a <code>List&lt;AnonymousType#1&gt;()</code>.</p>\n\n<pre><code>/// &lt;summary&gt;Remove extraneous entries for common word permutations&lt;/summary&gt;\n/// &lt;param name=\"input\"&gt;Incoming series of words to be filtered&lt;/param&gt;\n/// &lt;param name=\"MaxIgnoreLength\"&gt;Words this long or shorter will not count as duplicates&lt;/param&gt;\n/// &lt;param name=\"words2\"&gt;Instance list from BuildInstanceList()&lt;/param&gt;\n/// &lt;returns&gt;Filtered list of lines from input, based on filter info in words2&lt;/returns&gt;\nprivate static List&lt;string&gt; FilterNearDuplicates(List&lt;string&gt; input, int MaxIgnoreLength, List&lt;dynamic&gt; words2)\n{\n List&lt;string&gt; output = new List&lt;string&gt;();\n foreach (string line in input)\n {\n int Dupes = 0;\n foreach (string word in line.Split(new char[] { ' ', ',', ';', '\\\\', '/', ':', '\\\"', '\\r', '\\n', '.' })\n .Where(p =&gt; p.Length &gt; MaxIgnoreLength)\n .Distinct())\n {\n int Instances = 0;\n foreach (dynamic dyn in words2)\n if (word == dyn.Word)\n {\n Instances = dyn.Instances;\n if (Instances &gt; 1)\n Dupes++;\n break;\n }\n }\n if (Dupes == 0)\n output.Add(line);\n }\n return output;\n}\n/// &lt;summary&gt;Builds a list of words and how many times they occur in the overall list&lt;/summary&gt;\n/// &lt;param name=\"input\"&gt;Incoming series of words to be counted&lt;/param&gt;\n/// &lt;returns&gt;&lt;/returns&gt;\nprivate static List&lt;dynamic&gt; BuildInstanceList(List&lt;string&gt; input)\n{\n List&lt;dynamic&gt; words2 = new List&lt;object&gt;();\n foreach (string line in input)\n foreach (string word in line.Split(new char[] { ' ', ',', ';', '\\\\', '/', ':', '\\\"', '\\r', '\\n', '.' }))\n {\n if (string.IsNullOrEmpty(word))\n continue;\n else if (ExistsInList(word, words2))\n for (int i = words2.Count - 1; i &gt;= 0; i--)\n {\n if (words2[i].Word == word)\n words2[i] = new { Word = words2[i].Word, Instances = words2[i].Instances + 1 };\n }\n else\n words2.Add(new { Word = word, Instances = 1 });\n }\n\n return words2;\n}\n/// &lt;summary&gt;Determines whether a dynamic Word object exists in a List of this dynamic type.&lt;/summary&gt;\n/// &lt;param name=\"word\"&gt;Word to look for&lt;/param&gt;\n/// &lt;param name=\"words\"&gt;Word dynamics to search through&lt;/param&gt;\n/// &lt;returns&gt;Indicator of whether the word exists in the list of words&lt;/returns&gt;\nprivate static bool ExistsInList(string word, List&lt;dynamic&gt; words)\n{\n foreach (dynamic dyn in words)\n if (dyn.Word == word)\n return true;\n return false;\n}\n</code></pre>\n" }, { "answer_id": 1804876, "author": "tsilb", "author_id": 11112, "author_profile": "https://Stackoverflow.com/users/11112", "pm_score": 2, "selected": false, "text": "<p>Wraps a string every n chars.</p>\n\n<pre><code>public static string WrapAt(this string str, int WrapPos)\n{\n if (string.IsNullOrEmpty(str))\n throw new ArgumentNullException(\"str\", \"Cannot wrap a null string\");\n str = str.Replace(\"\\r\", \"\").Replace(\"\\n\", \"\");\n\n if (str.Length &lt;= WrapPos)\n return str;\n\n for (int i = str.Length; i &gt;= 0; i--)\n if (i % WrapPos == 0 &amp;&amp; i &gt; 0 &amp;&amp; i != str.Length)\n str = str.Insert(i, \"\\r\\n\");\n return str;\n}\n</code></pre>\n" }, { "answer_id": 1804880, "author": "tsilb", "author_id": 11112, "author_profile": "https://Stackoverflow.com/users/11112", "pm_score": -1, "selected": false, "text": "<p>Gets the root domain of a URI.</p>\n\n<pre><code>/// &lt;summary&gt;Gets the root domain of any URI&lt;/summary&gt;\n/// &lt;param name=\"uri\"&gt;URI to get root domain of&lt;/param&gt;\n/// &lt;returns&gt;Root domain with TLD&lt;/returns&gt;\npublic static string GetRootDomain(this System.Uri uri)\n{\n if (uri == null)\n return null;\n\n string Domain = uri.Host;\n while (System.Text.RegularExpressions.Regex.Matches(Domain, @\"[\\.]\").Count &gt; 1)\n Domain = Domain.Substring(Domain.IndexOf('.') + 1);\n Domain = Domain.Substring(0, Domain.IndexOf('.'));\n return Domain;\n}\n</code></pre>\n" }, { "answer_id": 1804940, "author": "CaffGeek", "author_id": 54746, "author_profile": "https://Stackoverflow.com/users/54746", "pm_score": 0, "selected": false, "text": "<p>Some DataSet/DataRow extensions to make working with db results a little simpler</p>\n\n<p>Just use .Field(\"fieldname\") on the DataRow and it will cast it if it can, optional default can be included.</p>\n\n<p>Also .HasRows() on the DataSet so you don't need to check for the existence of a table and rows.</p>\n\n<p>Example:</p>\n\n<pre><code>using (DataSet ds = yourcall()) \n{\n if (ds.HasRows())\n {\n foreach (DataRow dr in ds.Tables[0].Rows)\n {\n int id = dr.Field&lt;int&gt;(\"ID\");\n string name = dr.Field&lt;string&gt;(\"Name\");\n string Action = dr.Field&lt;string&gt;(\"Action\", \"N/A\");\n }\n }\n}\n</code></pre>\n\n<p>Code:</p>\n\n<pre><code>using System;\nusing System.Data;\n\npublic static class DataSetExtensions\n{\n public static T Field&lt;T&gt;(this DataRow row, string columnName, T defaultValue)\n {\n try\n {\n return row.Field&lt;T&gt;(columnName);\n }\n catch\n {\n return defaultValue;\n }\n }\n\n public static T Field&lt;T&gt;(this DataRow row, string columnName)\n {\n if (row[columnName] == null)\n throw new NullReferenceException(columnName + \" does not exist in DataRow\");\n\n string value = row[columnName].ToString();\n\n if (typeof(T) == \"\".GetType())\n {\n return (T)Convert.ChangeType(value, typeof(T));\n }\n else if (typeof(T) == 0.GetType())\n {\n return (T)Convert.ChangeType(int.Parse(value), typeof(T));\n }\n else if (typeof(T) == false.GetType())\n {\n return (T)Convert.ChangeType(bool.Parse(value), typeof(T));\n }\n else if (typeof(T) == DateTime.Now.GetType())\n {\n return (T)Convert.ChangeType(DateTime.Parse(value), typeof(T));\n }\n else if (typeof(T) == new byte().GetType())\n {\n return (T)Convert.ChangeType(byte.Parse(value), typeof(T));\n }\n else if (typeof(T) == new float().GetType())\n {\n return (T)Convert.ChangeType(float.Parse(value), typeof(T));\n }\n else\n {\n throw new ArgumentException(string.Format(\"Cannot cast '{0}' to '{1}'.\", value, typeof(T).ToString()));\n }\n }\n\n public static bool HasRows(this DataSet dataSet) \n {\n return (dataSet.Tables.Count &gt; 0 &amp;&amp; dataSet.Tables[0].Rows.Count &gt; 0);\n }\n}\n</code></pre>\n" }, { "answer_id": 1812003, "author": "Matt Kocaj", "author_id": 56145, "author_profile": "https://Stackoverflow.com/users/56145", "pm_score": 1, "selected": false, "text": "<p>Some handy string helpers:</p>\n\n<p><strong>Usage:</strong></p>\n\n<p>I hate unwanted spaces trailing or leading strings and since string can take on a <code>null</code> value, it can be tricky, so i use this:</p>\n\n<pre><code>public bool IsGroup { get { return !this.GroupName.IsNullOrTrimEmpty(); } }\n</code></pre>\n\n<p>Here is another extention method that i use for a new <a href=\"https://stackoverflow.com/questions/1721327/validate-object-based-on-external-factors-ie-data-store-uniqueness/1741831#1741831\">validation framework</a> i'm trialing. You can see the regex extensions within that help clean otherwise messy regex:</p>\n\n<pre><code>public static bool IsRequiredWithLengthLessThanOrEqualNoSpecial(this String str, int length)\n{\n return !str.IsNullOrTrimEmpty() &amp;&amp;\n str.RegexMatch(\n @\"^[- \\r\\n\\\\\\.!:*,@$%&amp;\"\"?\\(\\)\\w']{1,{0}}$\".RegexReplace(@\"\\{0\\}\", length.ToString()),\n RegexOptions.Multiline) == str;\n}\n</code></pre>\n\n<p><strong>Source:</strong></p>\n\n<pre><code>public static class StringHelpers\n{\n /// &lt;summary&gt;\n /// Same as String.IsNullOrEmpty except that\n /// it captures the Empty state for whitespace\n /// strings by Trimming first.\n /// &lt;/summary&gt;\n public static bool IsNullOrTrimEmpty(this String helper)\n {\n if (helper == null)\n return true;\n else\n return String.Empty == helper.Trim();\n }\n\n public static int TrimLength(this String helper)\n {\n return helper.Trim().Length;\n }\n\n /// &lt;summary&gt;\n /// Returns the matched string from the regex pattern. The\n /// groupName is for named group match values in the form (?&lt;name&gt;group).\n /// &lt;/summary&gt;\n public static string RegexMatch(this String helper, string pattern, RegexOptions options, string groupName)\n {\n if (groupName.IsNullOrTrimEmpty())\n return Regex.Match(helper, pattern, options).Value;\n else\n return Regex.Match(helper, pattern, options).Groups[groupName].Value;\n }\n\n public static string RegexMatch(this String helper, string pattern)\n {\n return RegexMatch(helper, pattern, RegexOptions.None, null);\n }\n\n public static string RegexMatch(this String helper, string pattern, RegexOptions options)\n {\n return RegexMatch(helper, pattern, options, null);\n }\n\n public static string RegexMatch(this String helper, string pattern, string groupName)\n {\n return RegexMatch(helper, pattern, RegexOptions.None, groupName);\n }\n\n /// &lt;summary&gt;\n /// Returns true if there is a match from the regex pattern\n /// &lt;/summary&gt;\n public static bool IsRegexMatch(this String helper, string pattern, RegexOptions options)\n {\n return helper.RegexMatch(pattern, options).Length &gt; 0;\n }\n\n public static bool IsRegexMatch(this String helper, string pattern)\n {\n return helper.IsRegexMatch(pattern, RegexOptions.None);\n }\n\n /// &lt;summary&gt;\n /// Returns a string where matching patterns are replaced by the replacement string.\n /// &lt;/summary&gt;\n /// &lt;param name=\"pattern\"&gt;The regex pattern for matching the items to be replaced&lt;/param&gt;\n /// &lt;param name=\"replacement\"&gt;The string to replace matching items&lt;/param&gt;\n /// &lt;returns&gt;&lt;/returns&gt;\n public static string RegexReplace(this String helper, string pattern, string replacement, RegexOptions options)\n {\n return Regex.Replace(helper, pattern, replacement, options);\n }\n\n public static string RegexReplace(this String helper, string pattern, string replacement)\n {\n return Regex.Replace(helper, pattern, replacement, RegexOptions.None);\n }\n}\n</code></pre>\n\n<p>I like to do a lot of regex so i consider these easier than adding the using statement and the extra code to handle named groups.</p>\n" }, { "answer_id": 1969365, "author": "Kaveh Shahbazian", "author_id": 54467, "author_profile": "https://Stackoverflow.com/users/54467", "pm_score": 2, "selected": false, "text": "<p>I have implemented a package of extension methods (available at <a href=\"http://foop.codeplex.com/\" rel=\"nofollow noreferrer\">http://foop.codeplex.com/</a>) and some of my daily used ones are:</p>\n\n<pre><code>// the most beloved extension method for me is Pipe:\n&lt;%= variable.Pipe(x =&gt; this.SomeFunction(x)).Pipe(y =&gt;\n{\n ...;\n return this.SomeOtherFunction(y);\n}) %&gt;\n\nvar d = 28.December(2009); // some extension methods for creating DateTime\nDateTime justDatePart = d.JustDate();\nTimeSpan justTimePart = d.JustTime();\nvar nextTime = d.Add(5.Hours());\n\nusing(StreamReader reader = new StreamReader(\"lines-of-data-file-for-example\")) {\n ...\n // for reading streams line by line and usable in LINQ\n var query = from line in reader.Lines(); \n where line.Contains(_today)\n select new { Parts = PartsOf(line), Time = _now };\n}\n\n500.Sleep();\n\nXmlSerialize and XmlDeserialize\n\nIsNull and IsNotNull\n\nIfTrue, IfFalse and Iff:\ntrue.IfTrue(() =&gt; Console.WriteLine(\"it is true then!\");\n\nIfNull and IfNotNull\n</code></pre>\n" }, { "answer_id": 1969663, "author": "moomi", "author_id": 50949, "author_profile": "https://Stackoverflow.com/users/50949", "pm_score": 1, "selected": false, "text": "<p>For ASP.NET, I use these extensions to HttpSessionState to load objects in session.\nIt allows you to load session objects in a clean manner, and will create and initialize them if they do not exist.\nI use the two extension methods like so:</p>\n\n<pre><code>private bool CreateMode;\nprivate MyClass SomeClass;\n\nprotected override void OnInit (EventArgs e)\n{\n CreateMode = Session.GetSessionValue&lt;bool&gt; (\"someKey1\", () =&gt; true);\n SomeClass = Session.GetSessionClass&lt;MyClass&gt; (\"someKey2\", () =&gt; new MyClass () \n { \n MyProperty = 123 \n });\n}\n</code></pre>\n\n<p>Here are the extension classes:<code></p>\n\n<pre><code>public static class SessionExtensions \n{\n public delegate object UponCreate ();\n public static T GetSessionClass&lt;T&gt; (this HttpSessionState session, \n string key, UponCreate uponCreate) where T : class\n {\n if (null == session[key])\n {\n var item = uponCreate () as T;\n session[key] = item;\n return item;\n }\n return session[key] as T;\n }\n public static T GetSessionValue&lt;T&gt; (this HttpSessionState session, \n string key, UponCreate uponCreate) where T : struct\n {\n if (null == session[key])\n {\n var item = uponCreate();\n session[key] = item;\n return (T)item;\n }\n return (T)session[key];\n }\n}\n</code></pre>\n\n<p></code></p>\n" }, { "answer_id": 2016298, "author": "jpbochi", "author_id": 123897, "author_profile": "https://Stackoverflow.com/users/123897", "pm_score": 3, "selected": false, "text": "<h2><code>IEnumerable&lt;&gt;</code> Shuffle</h2>\n\n<p>I used the <a href=\"http://en.wikipedia.org/wiki/Fisher-Yates_shuffle\" rel=\"nofollow noreferrer\">Fisher-Yates</a> the algorithm to implement a shuffle function.</p>\n\n<p>By using <code>yield return</code> and breaking the code in two functions, it achieves proper <em>argument validation</em> and <em>deferred execution</em>. (thanks, <a href=\"https://stackoverflow.com/users/105570/dan\">Dan</a>, for pointing this flaw in my first version)</p>\n\n<pre><code>static public IEnumerable&lt;T&gt; Shuffle&lt;T&gt;(this IEnumerable&lt;T&gt; source)\n{\n if (source == null) throw new ArgumentNullException(\"source\");\n\n return ShuffleIterator(source);\n}\n\nstatic private IEnumerable&lt;T&gt; ShuffleIterator&lt;T&gt;(this IEnumerable&lt;T&gt; source)\n{\n T[] array = source.ToArray();\n Random rnd = new Random(); \n for (int n = array.Length; n &gt; 1;)\n {\n int k = rnd.Next(n--); // 0 &lt;= k &lt; n\n\n //Swap items\n if (n != k)\n {\n T tmp = array[k];\n array[k] = array[n];\n array[n] = tmp;\n }\n }\n\n foreach (var item in array) yield return item;\n}\n</code></pre>\n" }, { "answer_id": 2153244, "author": "Gideon", "author_id": 82004, "author_profile": "https://Stackoverflow.com/users/82004", "pm_score": 2, "selected": false, "text": "<p>While working with MVC and having lots of <code>if</code> statements where i only care about either <code>true</code> or <code>false</code>, and printing <code>null</code>, or <code>string.Empty</code> in the other case, I came up with:</p>\n\n<pre><code>public static TResult WhenTrue&lt;TResult&gt;(this Boolean value, Func&lt;TResult&gt; expression)\n{\n return value ? expression() : default(TResult);\n}\n\npublic static TResult WhenTrue&lt;TResult&gt;(this Boolean value, TResult content)\n{\n return value ? content : default(TResult);\n}\n\npublic static TResult WhenFalse&lt;TResult&gt;(this Boolean value, Func&lt;TResult&gt; expression)\n{\n return !value ? expression() : default(TResult);\n}\n\npublic static TResult WhenFalse&lt;TResult&gt;(this Boolean value, TResult content)\n{\n return !value ? content : default(TResult);\n}\n</code></pre>\n\n<p>It allows me to change <code>&lt;%= (someBool) ? \"print y\" : string.Empty %&gt;</code> into <code>&lt;%= someBool.WhenTrue(\"print y\") %&gt;</code> .</p>\n\n<p>I only use it in my Views where I mix code and HTML, in code files writing the \"longer\" version is more clear IMHO.</p>\n" }, { "answer_id": 2212077, "author": "Jordão", "author_id": 31158, "author_profile": "https://Stackoverflow.com/users/31158", "pm_score": 3, "selected": false, "text": "<p>You all probably already know that an interesting usage for extension methods is as a <a href=\"http://codecrafter.blogspot.com/2010/02/c-quasi-mixins-pattern.html\" rel=\"nofollow noreferrer\">kind of mixin</a>. Some extension methods, like the <code>XmlSerializable</code>, pollute almost every class; and it doesn't make sense to most of them, like <code>Thread</code> and <code>SqlConnection</code>.</p>\n\n<p>Some functionality should be <em>explicitly</em> mixed in to the classes that want to have it. I propose a <b>new notation</b> to this kind of type, with the <code>M</code> prefix.</p>\n\n<p>The <code>XmlSerializable</code> then, is this:</p>\n\n<pre><code>public interface MXmlSerializable { }\npublic static class XmlSerializable {\n public static string ToXml(this MXmlSerializable self) {\n if (self == null) throw new ArgumentNullException();\n var serializer = new XmlSerializer(self.GetType());\n using (var writer = new StringWriter()) {\n serializer.Serialize(writer, self);\n return writer.GetStringBuilder().ToString();\n }\n }\n public static T FromXml&lt;T&gt;(string xml) where T : MXmlSerializable {\n var serializer = new XmlSerializer(typeof(T));\n return (T)serializer.Deserialize(new StringReader(xml));\n }\n}\n</code></pre>\n\n<p>A class then mixes it in:</p>\n\n<pre><code>public class Customer : MXmlSerializable {\n public string Name { get; set; }\n public bool Preferred { get; set; }\n}\n</code></pre>\n\n<p>And the usage is simply:</p>\n\n<pre><code>var customer = new Customer { \n Name = \"Guybrush Threepwood\", \n Preferred = true };\nvar xml = customer.ToXml();\n</code></pre>\n\n<p>If you like the idea, you can create a new namespace for useful mixins in the project. What do you think?</p>\n\n<p>Oh, and by the way, I think most extension methods should <a href=\"http://codecrafter.blogspot.com/2008/07/c-extension-methods-and-null-references.html\" rel=\"nofollow noreferrer\">explicitly test for null</a>.</p>\n" }, { "answer_id": 2277064, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 0, "selected": false, "text": "<pre><code>public static class StringHelper\n{\n public static String F(this String str, params object[] args)\n {\n return String.Format(str, args);\n }\n}\n</code></pre>\n\n<p>Using like:</p>\n\n<pre><code>\"Say {0}\".F(\"Hello\");\n</code></pre>\n" }, { "answer_id": 2277084, "author": "moribvndvs", "author_id": 64750, "author_profile": "https://Stackoverflow.com/users/64750", "pm_score": 2, "selected": false, "text": "<p><code>String.As&lt;T&gt;</code>, which can be used to convert a string value <em>as</em> some type (intended to be used primarily with primitives and types that support IConvertable. Works great with <code>Nullable</code> types and even Enums!</p>\n\n<pre><code>public static partial class StringExtensions\n{\n /// &lt;summary&gt;\n /// Converts the string to the specified type, using the default value configured for the type.\n /// &lt;/summary&gt;\n /// &lt;typeparam name=\"T\"&gt;Type the string will be converted to. The type must implement IConvertable.&lt;/typeparam&gt;\n /// &lt;param name=\"original\"&gt;The original string.&lt;/param&gt;\n /// &lt;returns&gt;The converted value.&lt;/returns&gt;\n public static T As&lt;T&gt;(this String original)\n {\n return As(original, CultureInfo.CurrentCulture,\n default(T));\n }\n\n /// &lt;summary&gt;\n /// Converts the string to the specified type, using the default value configured for the type.\n /// &lt;/summary&gt;\n /// &lt;typeparam name=\"T\"&gt;Type the string will be converted to.&lt;/typeparam&gt;\n /// &lt;param name=\"original\"&gt;The original string.&lt;/param&gt;\n /// &lt;param name=\"defaultValue\"&gt;The default value to use in case the original string is null or empty, or can't be converted.&lt;/param&gt;\n /// &lt;returns&gt;The converted value.&lt;/returns&gt;\n public static T As&lt;T&gt;(this String original, T defaultValue)\n {\n return As(original, CultureInfo.CurrentCulture, defaultValue);\n }\n\n /// &lt;summary&gt;\n /// Converts the string to the specified type, using the default value configured for the type.\n /// &lt;/summary&gt;\n /// &lt;typeparam name=\"T\"&gt;Type the string will be converted to.&lt;/typeparam&gt;\n /// &lt;param name=\"original\"&gt;The original string.&lt;/param&gt;\n /// &lt;param name=\"provider\"&gt;Format provider used during the type conversion.&lt;/param&gt;\n /// &lt;returns&gt;The converted value.&lt;/returns&gt;\n public static T As&lt;T&gt;(this String original, IFormatProvider provider)\n {\n return As(original, provider, default(T));\n }\n\n /// &lt;summary&gt;\n /// Converts the string to the specified type.\n /// &lt;/summary&gt;\n /// &lt;typeparam name=\"T\"&gt;Type the string will be converted to.&lt;/typeparam&gt;\n /// &lt;param name=\"original\"&gt;The original string.&lt;/param&gt;\n /// &lt;param name=\"provider\"&gt;Format provider used during the type conversion.&lt;/param&gt;\n /// &lt;param name=\"defaultValue\"&gt;The default value to use in case the original string is null or empty, or can't be converted.&lt;/param&gt;\n /// &lt;returns&gt;The converted value.&lt;/returns&gt;\n /// &lt;remarks&gt;\n /// If an error occurs while converting the specified value to the requested type, the exception is caught and the default is returned. It is strongly recommended you\n /// do NOT use this method if it is important that conversion failures are not swallowed up.\n ///\n /// This method is intended to be used to convert string values to primatives, not for parsing, converting, or deserializing complex types.\n /// &lt;/remarks&gt;\n public static T As&lt;T&gt;(this String original, IFormatProvider provider,\n T defaultValue)\n {\n T result;\n Type type = typeof (T);\n\n if (String.IsNullOrEmpty(original)) result = defaultValue;\n else\n {\n // need to get the underlying type if T is Nullable&lt;&gt;.\n\n if (type.IsNullableType())\n {\n type = Nullable.GetUnderlyingType(type);\n }\n\n try\n {\n // ChangeType doesn't work properly on Enums\n result = type.IsEnum\n ? (T) Enum.Parse(type, original, true)\n : (T) Convert.ChangeType(original, type, provider);\n }\n catch // HACK: what can we do to minimize or avoid raising exceptions as part of normal operation? custom string parsing (regex?) for well-known types? it would be best to know if you can convert to the desired type before you attempt to do so.\n {\n result = defaultValue;\n }\n }\n\n return result;\n }\n}\n</code></pre>\n\n<p>This relies on another simple extension for <code>Type</code>:</p>\n\n<pre><code>/// &lt;summary&gt;\n/// Extension methods for &lt;see cref=\"Type\"/&gt;.\n/// &lt;/summary&gt;\npublic static class TypeExtensions\n{\n /// &lt;summary&gt;\n /// Returns whether or not the specified type is &lt;see cref=\"Nullable{T}\"/&gt;.\n /// &lt;/summary&gt;\n /// &lt;param name=\"type\"&gt;A &lt;see cref=\"Type\"/&gt;.&lt;/param&gt;\n /// &lt;returns&gt;True if the specified type is &lt;see cref=\"Nullable{T}\"/&gt;; otherwise, false.&lt;/returns&gt;\n /// &lt;remarks&gt;Use &lt;see cref=\"Nullable.GetUnderlyingType\"/&gt; to access the underlying type.&lt;/remarks&gt;\n public static bool IsNullableType(this Type type)\n {\n if (type == null) throw new ArgumentNullException(\"type\");\n\n return type.IsGenericType &amp;&amp; type.GetGenericTypeDefinition().Equals(typeof (Nullable&lt;&gt;));\n }\n}\n</code></pre>\n\n<p>Usage:</p>\n\n<pre><code>var someInt = \"1\".As&lt;int&gt;();\nvar someIntDefault = \"bad value\".As(1); // \"bad value\" won't convert, so the default value 1 is returned.\nvar someEnum = \"Sunday\".As&lt;DayOfWeek&gt;();\nsomeEnum = \"0\".As&lt;DayOfWeek&gt;(); // returns Sunday\nvar someNullableEnum = \"\".As&lt;DayOfWeek?&gt;(null); // returns a null value since \"\" can't be converted\n</code></pre>\n" }, { "answer_id": 2437499, "author": "PhilChuang", "author_id": 14392, "author_profile": "https://Stackoverflow.com/users/14392", "pm_score": 1, "selected": false, "text": "<p>Hate this kind of code?</p>\n\n<pre><code>CloneableClass cc1 = new CloneableClass ();\nCloneableClass cc2 = null;\nCloneableClass cc3 = null;\n\ncc3 = (CloneableClass) cc1.Clone (); // this is ok\ncc3 = cc2.Clone (); // this throws null ref exception\n// code to handle both cases\ncc3 = cc1 != null ? (CloneableClass) cc1.Clone () : null;\n</code></pre>\n\n<p>It's a bit clunky, so I replace it with this extension, which I call CloneOrNull - </p>\n\n<pre><code>public static T CloneOrNull&lt;T&gt; (this T self) where T : class, ICloneable\n{\n if (self == null) return null;\n return (T) self.Clone ();\n}\n</code></pre>\n\n<p>Usage is like: </p>\n\n<pre><code>CloneableClass cc1 = new CloneableClass ();\nCloneableClass cc2 = null;\nCloneableClass cc3 = null;\n\ncc3 = cc1.CloneOrNull (); // clone of cc1\ncc3 = cc2.CloneOrNull (); // null\n// look mom, no casts!\n</code></pre>\n\n<p>Please feel free to use this anywhere!</p>\n" }, { "answer_id": 2439537, "author": "Dan Tao", "author_id": 105570, "author_profile": "https://Stackoverflow.com/users/105570", "pm_score": 3, "selected": false, "text": "<p>There's a lot of functionality you can get from the <code>Random</code> class.</p>\n\n<p>Below are some extension methods I use from time to time. With these, in addition to <code>Next</code> and <code>NextDouble</code>, the <code>Random</code> class gives you <code>NextBool</code>, <code>NextChar</code>, <code>NextDateTime</code>, <code>NextTimeSpan</code>, <code>NextDouble</code> (accepting <code>minValue</code> and <code>maxValue</code> parameters), and my <em>personal</em> favorite: <code>NextString</code>. There are more (<code>NextByte</code>, <code>NextShort</code>, <code>NextLong</code>, etc.); but those are mostly for completeness and don't get used as much. So I didn't include them here (this code is long enough as it is!).</p>\n\n<pre><code>// todo: implement additional CharType values (e.g., AsciiAny)\npublic enum CharType {\n AlphabeticLower,\n AlphabeticUpper,\n AlphabeticAny,\n AlphanumericLower,\n AlphanumericUpper,\n AlphanumericAny,\n Numeric\n}\n\npublic static class RandomExtensions {\n // 10 digits vs. 52 alphabetic characters (upper &amp; lower);\n // probability of being numeric: 10 / 62 = 0.1612903225806452\n private const double AlphanumericProbabilityNumericAny = 10.0 / 62.0;\n\n // 10 digits vs. 26 alphabetic characters (upper OR lower);\n // probability of being numeric: 10 / 36 = 0.2777777777777778\n private const double AlphanumericProbabilityNumericCased = 10.0 / 36.0;\n\n public static bool NextBool(this Random random, double probability) {\n return random.NextDouble() &lt;= probability;\n }\n\n public static bool NextBool(this Random random) {\n return random.NextDouble() &lt;= 0.5;\n }\n\n public static char NextChar(this Random random, CharType mode) {\n switch (mode) {\n case CharType.AlphabeticAny:\n return random.NextAlphabeticChar();\n case CharType.AlphabeticLower:\n return random.NextAlphabeticChar(false);\n case CharType.AlphabeticUpper:\n return random.NextAlphabeticChar(true);\n case CharType.AlphanumericAny:\n return random.NextAlphanumericChar();\n case CharType.AlphanumericLower:\n return random.NextAlphanumericChar(false);\n case CharType.AlphanumericUpper:\n return random.NextAlphanumericChar(true);\n case CharType.Numeric:\n return random.NextNumericChar();\n default:\n return random.NextAlphanumericChar();\n }\n }\n\n public static char NextChar(this Random random) {\n return random.NextChar(CharType.AlphanumericAny);\n }\n\n private static char NextAlphanumericChar(this Random random, bool uppercase) {\n bool numeric = random.NextBool(AlphanumericProbabilityNumericCased);\n\n if (numeric)\n return random.NextNumericChar();\n else\n return random.NextAlphabeticChar(uppercase);\n }\n\n private static char NextAlphanumericChar(this Random random) {\n bool numeric = random.NextBool(AlphanumericProbabilityNumericAny);\n\n if (numeric)\n return random.NextNumericChar();\n else\n return random.NextAlphabeticChar(random.NextBool());\n }\n\n private static char NextAlphabeticChar(this Random random, bool uppercase) {\n if (uppercase)\n return (char)random.Next(65, 91);\n else\n return (char)random.Next(97, 123);\n }\n\n private static char NextAlphabeticChar(this Random random) {\n return random.NextAlphabeticChar(random.NextBool());\n }\n\n private static char NextNumericChar(this Random random) {\n return (char)random.Next(48, 58);\n }\n\n public static DateTime NextDateTime(this Random random, DateTime minValue, DateTime maxValue) {\n return DateTime.FromOADate(\n random.NextDouble(minValue.ToOADate(), maxValue.ToOADate())\n );\n }\n\n public static DateTime NextDateTime(this Random random) {\n return random.NextDateTime(DateTime.MinValue, DateTime.MaxValue);\n }\n\n public static double NextDouble(this Random random, double minValue, double maxValue) {\n if (maxValue &lt; minValue)\n throw new ArgumentException(\"Minimum value must be less than maximum value.\");\n\n double difference = maxValue - minValue;\n if (!double.IsInfinity(difference))\n return minValue + (random.NextDouble() * difference);\n\n else {\n // to avoid evaluating to Double.Infinity, we split the range into two halves:\n double halfDifference = (maxValue * 0.5) - (minValue * 0.5);\n\n // 50/50 chance of returning a value from the first or second half of the range\n if (random.NextBool())\n return minValue + (random.NextDouble() * halfDifference);\n else\n return (minValue + halfDifference) + (random.NextDouble() * halfDifference);\n }\n }\n\n public static string NextString(this Random random, int numChars, CharType mode) {\n char[] chars = new char[numChars];\n\n for (int i = 0; i &lt; numChars; ++i)\n chars[i] = random.NextChar(mode);\n\n return new string(chars);\n }\n\n public static string NextString(this Random random, int numChars) {\n return random.NextString(numChars, CharType.AlphanumericAny);\n }\n\n public static TimeSpan NextTimeSpan(this Random random, TimeSpan minValue, TimeSpan maxValue) {\n return TimeSpan.FromMilliseconds(\n random.NextDouble(minValue.TotalMilliseconds, maxValue.TotalMilliseconds)\n );\n }\n\n public static TimeSpan NextTimeSpan(this Random random) {\n return random.NextTimeSpan(TimeSpan.MinValue, TimeSpan.MaxValue);\n }\n}\n</code></pre>\n" }, { "answer_id": 2439988, "author": "Janko R", "author_id": 292466, "author_profile": "https://Stackoverflow.com/users/292466", "pm_score": 0, "selected": false, "text": "<pre><code>public static class DictionaryExtensions\n{\n public static Nullable&lt;TValue&gt; GetValueOrNull&lt;TKey, TValue&gt;(this Dictionary&lt;TKey, TValue&gt; dictionary, TKey key)\n where TValue : struct\n {\n TValue result;\n if (dictionary.TryGetValue(key, out result))\n return result;\n else\n return null;\n }\n}\n</code></pre>\n\n<p>Free to use, just mention my name (Janko Röbisch) in the code.</p>\n" }, { "answer_id": 2549153, "author": "John Leidegren", "author_id": 58961, "author_profile": "https://Stackoverflow.com/users/58961", "pm_score": 3, "selected": false, "text": "<p>I find myself doing this, over and over, again...</p>\n\n<pre><code>public static bool EqualsIgnoreCase(this string a, string b)\n{\n return string.Equals(a, b, StringComparison.OrdinalIgnoreCase);\n}\n</code></pre>\n\n<p>...followed by <code>StartsWithIgnoreCase</code>, <code>EndsWithIgnoreCase</code> and <code>ContainsIgnoreCase</code>.</p>\n" }, { "answer_id": 2550726, "author": "Max Toro", "author_id": 39923, "author_profile": "https://Stackoverflow.com/users/39923", "pm_score": 4, "selected": false, "text": "<p>Turn this:</p>\n\n<pre><code>DbCommand command = connection.CreateCommand();\ncommand.CommandText = \"SELECT @param\";\n\nDbParameter param = command.CreateParameter();\nparam.ParameterName = \"@param\";\nparam.Value = \"Hello World\";\n\ncommand.Parameters.Add(param);\n</code></pre>\n\n<p>... into this:</p>\n\n<pre><code>DbCommand command = connection.CreateCommand(\"SELECT {0}\", \"Hello World\");\n</code></pre>\n\n<p>... using this extension method:</p>\n\n<pre><code>using System;\nusing System.Data.Common;\nusing System.Globalization;\nusing System.Reflection;\n\nnamespace DbExtensions {\n\n public static class Db {\n\n static readonly Func&lt;DbConnection, DbProviderFactory&gt; getDbProviderFactory;\n static readonly Func&lt;DbCommandBuilder, int, string&gt; getParameterName;\n static readonly Func&lt;DbCommandBuilder, int, string&gt; getParameterPlaceholder;\n\n static Db() {\n\n getDbProviderFactory = (Func&lt;DbConnection, DbProviderFactory&gt;)Delegate.CreateDelegate(typeof(Func&lt;DbConnection, DbProviderFactory&gt;), typeof(DbConnection).GetProperty(\"DbProviderFactory\", BindingFlags.Instance | BindingFlags.NonPublic).GetGetMethod(true));\n getParameterName = (Func&lt;DbCommandBuilder, int, string&gt;)Delegate.CreateDelegate(typeof(Func&lt;DbCommandBuilder, int, string&gt;), typeof(DbCommandBuilder).GetMethod(\"GetParameterName\", BindingFlags.Instance | BindingFlags.NonPublic, Type.DefaultBinder, new Type[] { typeof(Int32) }, null));\n getParameterPlaceholder = (Func&lt;DbCommandBuilder, int, string&gt;)Delegate.CreateDelegate(typeof(Func&lt;DbCommandBuilder, int, string&gt;), typeof(DbCommandBuilder).GetMethod(\"GetParameterPlaceholder\", BindingFlags.Instance | BindingFlags.NonPublic, Type.DefaultBinder, new Type[] { typeof(Int32) }, null));\n }\n\n public static DbProviderFactory GetProviderFactory(this DbConnection connection) {\n return getDbProviderFactory(connection);\n }\n\n public static DbCommand CreateCommand(this DbConnection connection, string commandText, params object[] parameters) {\n\n if (connection == null) throw new ArgumentNullException(\"connection\");\n\n return CreateCommandImpl(GetProviderFactory(connection).CreateCommandBuilder(), connection.CreateCommand(), commandText, parameters);\n }\n\n private static DbCommand CreateCommandImpl(DbCommandBuilder commandBuilder, DbCommand command, string commandText, params object[] parameters) {\n\n if (commandBuilder == null) throw new ArgumentNullException(\"commandBuilder\");\n if (command == null) throw new ArgumentNullException(\"command\");\n if (commandText == null) throw new ArgumentNullException(\"commandText\");\n\n if (parameters == null || parameters.Length == 0) {\n command.CommandText = commandText;\n return command;\n }\n\n object[] paramPlaceholders = new object[parameters.Length];\n\n for (int i = 0; i &lt; paramPlaceholders.Length; i++) {\n\n DbParameter dbParam = command.CreateParameter();\n dbParam.ParameterName = getParameterName(commandBuilder, i);\n dbParam.Value = parameters[i] ?? DBNull.Value;\n command.Parameters.Add(dbParam);\n\n paramPlaceholders[i] = getParameterPlaceholder(commandBuilder, i);\n }\n\n command.CommandText = String.Format(CultureInfo.InvariantCulture, commandText, paramPlaceholders);\n\n return command;\n }\n }\n}\n</code></pre>\n\n<p>More ADO.NET extension methods: <a href=\"http://dbextensions.sourceforge.net/\" rel=\"nofollow noreferrer\"><strong>DbExtensions</strong></a></p>\n" }, { "answer_id": 2687774, "author": "Mark Rushakoff", "author_id": 126042, "author_profile": "https://Stackoverflow.com/users/126042", "pm_score": 3, "selected": false, "text": "<p>I just went through all 4 pages of this so far, and I was rather surprised that I didn't see this way to shorten a check for <code>InvokeRequired</code>:</p>\n\n<pre><code>using System;\nusing System.Windows.Forms;\n\n/// &lt;summary&gt;\n/// Extension methods acting on Control objects.\n/// &lt;/summary&gt;\ninternal static class ControlExtensionMethods\n{\n /// &lt;summary&gt;\n /// Invokes the given action on the given control's UI thread, if invocation is needed.\n /// &lt;/summary&gt;\n /// &lt;param name=\"control\"&gt;Control on whose UI thread to possibly invoke.&lt;/param&gt;\n /// &lt;param name=\"action\"&gt;Action to be invoked on the given control.&lt;/param&gt;\n public static void MaybeInvoke(this Control control, Action action)\n {\n if (control != null &amp;&amp; control.InvokeRequired)\n {\n control.Invoke(action);\n }\n else\n {\n action();\n }\n }\n\n /// &lt;summary&gt;\n /// Maybe Invoke a Func that returns a value.\n /// &lt;/summary&gt;\n /// &lt;typeparam name=\"T\"&gt;Return type of func.&lt;/typeparam&gt;\n /// &lt;param name=\"control\"&gt;Control on which to maybe invoke.&lt;/param&gt;\n /// &lt;param name=\"func\"&gt;Function returning a value, to invoke.&lt;/param&gt;\n /// &lt;returns&gt;The result of the call to func.&lt;/returns&gt;\n public static T MaybeInvoke&lt;T&gt;(this Control control, Func&lt;T&gt; func)\n {\n if (control != null &amp;&amp; control.InvokeRequired)\n {\n return (T)(control.Invoke(func));\n }\n else\n {\n return func();\n }\n }\n}\n</code></pre>\n\n<p>Usage:</p>\n\n<pre><code>myForm.MaybeInvoke(() =&gt; this.Text = \"Hello world\");\n\n// Sometimes the control might be null, but that's okay.\nvar dialogResult = this.Parent.MaybeInvoke(() =&gt; MessageBox.Show(this, \"Yes or no?\", \"Choice\", MessageBoxButtons.YesNo));\n</code></pre>\n" }, { "answer_id": 2832683, "author": "ytoledano", "author_id": 245452, "author_profile": "https://Stackoverflow.com/users/245452", "pm_score": 2, "selected": false, "text": "<p>I use this a lot with nullable numbers. I helps catch those division by 0, NaN, Infinity...</p>\n\n<pre><code>public static bool IsNullOrDefault&lt;T&gt;(this T? o) \n where T : struct\n{\n return o == null || o.Value.Equals(default(T));\n}\n</code></pre>\n" }, { "answer_id": 2844557, "author": "Thomas Levesque", "author_id": 98713, "author_profile": "https://Stackoverflow.com/users/98713", "pm_score": 2, "selected": false, "text": "<p>I find the following extension method quite useful:</p>\n\n<pre><code>public static T GetService&lt;T&gt;(this IServiceProvider provider)\n{\n return (T)provider.GetService(typeof(T));\n}\n</code></pre>\n\n<p>It makes it much easier to use the <code>IServiceProvider</code> interface. Compare:</p>\n\n<pre><code>IProvideValueTarget target = (IProvideValueTarget)serviceProvider(typeof(IProvideValueTarget));\n</code></pre>\n\n<p>and</p>\n\n<pre><code>var target = serviceProvider.GetService&lt;IProvideValueTarget&gt;();\n</code></pre>\n" }, { "answer_id": 2959072, "author": "Chao", "author_id": 300996, "author_profile": "https://Stackoverflow.com/users/300996", "pm_score": 2, "selected": false, "text": "<p>NullPartial HTML helper for ASP MVC.</p>\n\n<p>When passed a null Model, HTML.Partial and HTML.RenderPartial will provide the View's model, if this partial is strongly typed and the View has a different type it will throw an exception rather than passing a null reference. These helpers let you specify two different partials so you can keep your null tests out of the view.</p>\n\n<p><strong>You have permission to include this on the Codeplex page</strong></p>\n\n<pre><code>public static class nullpartials\n {\n public static MvcHtmlString NullPartial(this HtmlHelper helper, string Partial, string NullPartial, object Model)\n {\n if (Model == null)\n return helper.Partial(NullPartial);\n else\n return helper.Partial(Partial, Model);\n }\n\n public static MvcHtmlString NullPartial(this HtmlHelper helper, string Partial, string NullPartial, object Model, ViewDataDictionary viewdata)\n {\n if (Model == null)\n return helper.Partial(NullPartial, viewdata);\n else\n return helper.Partial(Partial, Model, viewdata);\n }\n\n public static void RenderNullPartial(this HtmlHelper helper, string Partial, string NullPartial, object Model)\n {\n if (Model == null)\n {\n helper.RenderPartial(NullPartial);\n return;\n }\n else\n {\n helper.RenderPartial(Partial, Model);\n return;\n }\n }\n\n public static void RenderNullPartial(this HtmlHelper helper, string Partial, string NullPartial, object Model, ViewDataDictionary viewdata)\n {\n if (Model == null)\n {\n helper.RenderPartial(NullPartial, viewdata);\n return;\n }\n else\n {\n helper.RenderPartial(Partial, Model, viewdata);\n return;\n }\n }\n }\n</code></pre>\n" }, { "answer_id": 2966853, "author": "si618", "author_id": 44540, "author_profile": "https://Stackoverflow.com/users/44540", "pm_score": 3, "selected": false, "text": "<p>When using a dictionary where the key is a string, return existing key using a case-insensitive search. Our use case for this was for file paths.</p>\n\n<pre><code>/// &lt;summary&gt;\n/// Gets the key using &lt;paramref name=\"caseInsensitiveKey\"/&gt; from &lt;paramref name=\"dictionary\"/&gt;.\n/// &lt;/summary&gt;\n/// &lt;typeparam name=\"T\"&gt;The dictionary value.&lt;/typeparam&gt;\n/// &lt;param name=\"dictionary\"&gt;The dictionary.&lt;/param&gt;\n/// &lt;param name=\"caseInsensitiveKey\"&gt;The case insensitive key.&lt;/param&gt;\n/// &lt;returns&gt;\n/// An existing key; or &lt;see cref=\"string.Empty\"/&gt; if not found.\n/// &lt;/returns&gt;\npublic static string GetKeyIgnoringCase&lt;T&gt;(this IDictionary&lt;string, T&gt; dictionary, string caseInsensitiveKey)\n{\n if (string.IsNullOrEmpty(caseInsensitiveKey)) return string.Empty;\n foreach (string key in dictionary.Keys)\n {\n if (key.Equals(caseInsensitiveKey, StringComparison.InvariantCultureIgnoreCase))\n {\n return key;\n }\n }\n return string.Empty;\n}\n</code></pre>\n" }, { "answer_id": 3098630, "author": "cbp", "author_id": 21966, "author_profile": "https://Stackoverflow.com/users/21966", "pm_score": 1, "selected": false, "text": "<p>I use this one <em>all the time</em>:</p>\n\n<pre><code>public static void DelimitedAppend(this StringBuilder sb, string value, string delimiter)\n{\n if (sb.Length &gt; 0)\n sb.Append(delimiter);\n sb.Append(value);\n}\n</code></pre>\n\n<p>This just ensures that the delimiter is not inserted when the string is empty.\nFor example, to create a comma-seperated list of words:</p>\n\n<pre><code>var farmAnimals = new[] { new { Species = \"Dog\", IsTasty = false }, new { Species = \"Cat\", IsTasty = false }, new { Species = \"Chicken\", IsTasty = true }, };\nvar soupIngredients = new StringBuilder();\nforeach (var edible in farmAnimals.Where(farmAnimal =&gt; farmAnimal.IsTasty))\n soupIngredients.DelimitedAppend(edible.Species, \", \");\n</code></pre>\n" }, { "answer_id": 3098674, "author": "johnc", "author_id": 5302, "author_profile": "https://Stackoverflow.com/users/5302", "pm_score": 3, "selected": false, "text": "<p>Similar to the string As and Is above, but global to all objects.</p>\n\n<p>It's quite simple, but I use these a lot to alleviate parens explosion with boxing.</p>\n\n<pre><code>public static class ExtensionMethods_Object\n{\n [DebuggerStepThrough()]\n public static bool Is&lt;T&gt;(this object item) where T : class\n {\n return item is T;\n }\n\n [DebuggerStepThrough()]\n public static bool IsNot&lt;T&gt;(this object item) where T : class\n {\n return !(item.Is&lt;T&gt;());\n }\n\n [DebuggerStepThrough()]\n public static T As&lt;T&gt;(this object item) where T : class\n {\n return item as T;\n }\n}\n</code></pre>\n\n<p>I am happy for this code to be used at codeplex, indeed it already is.</p>\n" }, { "answer_id": 3132635, "author": "John", "author_id": 83091, "author_profile": "https://Stackoverflow.com/users/83091", "pm_score": 1, "selected": false, "text": "<p>A couple of useful extensions if you work with Fiscal Years</p>\n\n<pre><code>/// &lt;summary&gt;\n/// Returns the fiscal year for the passed in date\n/// &lt;/summary&gt;\n/// &lt;param name=\"value\"&gt;the date&lt;/param&gt;\n/// &lt;returns&gt;the fiscal year&lt;/returns&gt;\npublic static int FiscalYear(this DateTime value)\n{\n int ret = value.Year;\n if (value.Month &gt;= 7) ret++;\n return ret;\n}\n\n/// &lt;summary&gt;\n/// Returns the fiscal year for the passed in date\n/// &lt;/summary&gt;\n/// &lt;param name=\"value\"&gt;the date&lt;/param&gt;\n/// &lt;returns&gt;the fiscal year&lt;/returns&gt;\npublic static string FiscalYearString(this DateTime value)\n{\n int fy = FiscalYear(value);\n return \"{0}/{1}\".Format(fy - 1, fy);\n}\n</code></pre>\n" }, { "answer_id": 3232611, "author": "fre0n", "author_id": 252004, "author_profile": "https://Stackoverflow.com/users/252004", "pm_score": 5, "selected": false, "text": "<p>For Winform Controls:</p>\n\n<pre><code>/// &lt;summary&gt;\n/// Returns whether the function is being executed during design time in Visual Studio.\n/// &lt;/summary&gt;\npublic static bool IsDesignTime(this Control control)\n{\n if (LicenseManager.UsageMode == LicenseUsageMode.Designtime)\n {\n return true;\n }\n\n if (control.Site != null &amp;&amp; control.Site.DesignMode)\n {\n return true;\n }\n\n var parent = control.Parent;\n while (parent != null)\n {\n if (parent.Site != null &amp;&amp; parent.Site.DesignMode)\n {\n return true;\n }\n parent = parent.Parent;\n }\n return false;\n}\n\n/// &lt;summary&gt;\n/// Sets the DropDownWidth to ensure that no item's text is cut off.\n/// &lt;/summary&gt;\npublic static void SetDropDownWidth(this ComboBox comboBox)\n{\n var g = comboBox.CreateGraphics();\n var font = comboBox.Font;\n float maxWidth = 0;\n\n foreach (var item in comboBox.Items)\n {\n maxWidth = Math.Max(maxWidth, g.MeasureString(item.ToString(), font).Width);\n }\n\n if (comboBox.Items.Count &gt; comboBox.MaxDropDownItems)\n {\n maxWidth += SystemInformation.VerticalScrollBarWidth;\n }\n\n comboBox.DropDownWidth = Math.Max(comboBox.Width, Convert.ToInt32(maxWidth));\n}\n</code></pre>\n\n<p>IsDesignTime Usage:</p>\n\n<pre><code>public class SomeForm : Form\n{\n public SomeForm()\n {\n InitializeComponent();\n\n if (this.IsDesignTime())\n {\n return;\n }\n\n // Do something that makes the visual studio crash or hang if we're in design time,\n // but any other time executes just fine\n }\n}\n</code></pre>\n\n<p>SetDropdownWidth Usage:</p>\n\n<pre><code>ComboBox cbo = new ComboBox { Width = 50 };\ncbo.Items.Add(\"Short\");\ncbo.Items.Add(\"A little longer\");\ncbo.Items.Add(\"Holy cow, this is a really, really long item. How in the world will it fit?\");\ncbo.SetDropDownWidth();\n</code></pre>\n\n<p>I forgot to mention, feel free to use these on Codeplex...</p>\n" }, { "answer_id": 3237976, "author": "Soonts", "author_id": 126995, "author_profile": "https://Stackoverflow.com/users/126995", "pm_score": 0, "selected": false, "text": "<pre><code>// This file contains extension methods for generic List&lt;&gt; class to operate on sorted lists.\n// Duplicate values are OK.\n// O(ln(n)) is still much faster then the O(n) of LINQ's searches/filters.\nstatic partial class SortedList\n{\n // Return the index of the first element with the key greater then provided.\n // If there's no such element within the provided range, it returns iAfterLast.\n public static int sortedFirstGreaterIndex&lt;tElt, tKey&gt;( this IList&lt;tElt&gt; list, Func&lt;tElt, tKey, int&gt; comparer, tKey key, int iFirst, int iAfterLast )\n {\n if( iFirst &lt; 0 || iAfterLast &lt; 0 || iFirst &gt; list.Count || iAfterLast &gt; list.Count )\n throw new IndexOutOfRangeException();\n if( iFirst &gt; iAfterLast )\n throw new ArgumentException();\n if( iFirst == iAfterLast )\n return iAfterLast;\n\n int low = iFirst, high = iAfterLast;\n // The code below is inspired by the following article:\n // http://en.wikipedia.org/wiki/Binary_search#Single_comparison_per_iteration\n while( low &lt; high )\n {\n int mid = ( high + low ) / 2;\n // 'mid' might be 'iFirst' in case 'iFirst+1 == iAfterLast'.\n // 'mid' will never be 'iAfterLast'.\n if( comparer( list[ mid ], key ) &lt;= 0 ) // \"&lt;=\" since we gonna find the first \"greater\" element\n low = mid + 1;\n else\n high = mid;\n }\n return low;\n }\n\n // Return the index of the first element with the key greater then the provided key.\n // If there's no such element, returns list.Count.\n public static int sortedFirstGreaterIndex&lt;tElt, tKey&gt;( this IList&lt;tElt&gt; list, Func&lt;tElt, tKey, int&gt; comparer, tKey key )\n {\n return list.sortedFirstGreaterIndex( comparer, key, 0, list.Count );\n }\n\n // Add an element to the sorted array.\n // This could be an expensive operation if frequently adding elements that sort firstly.\n // This is cheap operation when adding elements that sort near the tail of the list.\n public static int sortedAdd&lt;tElt&gt;( this List&lt;tElt&gt; list, Func&lt;tElt, tElt, int&gt; comparer, tElt elt )\n {\n if( list.Count == 0 || comparer( list[ list.Count - 1 ], elt ) &lt;= 0 )\n {\n // either the list is empty, or the item is greater then all elements already in the collection.\n list.Add( elt );\n return list.Count - 1;\n }\n int ind = list.sortedFirstGreaterIndex( comparer, elt );\n list.Insert( ind, elt );\n return ind;\n }\n\n // Find first exactly equal element, return -1 if not found.\n public static int sortedFindFirstIndex&lt;tElt, tKey&gt;( this List&lt;tElt&gt; list, Func&lt;tElt, tKey, int&gt; comparer, tKey elt )\n {\n int low = 0, high = list.Count - 1;\n\n while( low &lt; high )\n {\n int mid = ( high + low ) / 2;\n if( comparer( list[ mid ], elt ) &lt; 0 )\n low = mid + 1;\n else\n high = mid; // this includes the case when we've found an element exactly matching the key\n }\n if( high &gt;= 0 &amp;&amp; 0 == comparer( list[ high ], elt ) )\n return high;\n return -1;\n }\n\n // Return the IEnumerable that returns array elements in the reverse order.\n public static IEnumerable&lt;tElt&gt; sortedReverse&lt;tElt&gt;( this List&lt;tElt&gt; list )\n {\n for( int i=list.Count - 1; i &gt;= 0; i-- )\n yield return list[ i ];\n }\n}\n</code></pre>\n" }, { "answer_id": 3282815, "author": "Tadas Šukys", "author_id": 135877, "author_profile": "https://Stackoverflow.com/users/135877", "pm_score": 2, "selected": false, "text": "<p>My suggestion:</p>\n\n<pre><code>public static bool IsNullOrEmpty(this ICollection obj)\n{\n return (obj == null || obj.Count == 0);\n}\n</code></pre>\n\n<p>Works with collections and arrays:</p>\n\n<pre><code>bool isNullOrEmpty = array.IsNullOrEmpty()\n</code></pre>\n\n<p>instead of</p>\n\n<pre><code>bool isNullOrEmpty = array == null || array.Length == 0;\n</code></pre>\n" }, { "answer_id": 3317559, "author": "stoic", "author_id": 261257, "author_profile": "https://Stackoverflow.com/users/261257", "pm_score": 2, "selected": false, "text": "<p>Converts a List to a datatable</p>\n\n<pre><code>public static class DataTableConverter\n{\n /// &lt;summary&gt;\n /// Convert a List{T} to a DataTable.\n /// &lt;/summary&gt;\n public static DataTable ToDataTable&lt;T&gt;(this IList&lt;T&gt; items)\n {\n var tb = new DataTable(typeof(T).Name);\n\n PropertyInfo[] props = typeof(T).GetProperties(BindingFlags.Public | BindingFlags.Instance);\n\n foreach (PropertyInfo prop in props)\n {\n Type t = GetCoreType(prop.PropertyType);\n tb.Columns.Add(prop.Name, t);\n }\n\n foreach (T item in items)\n {\n var values = new object[props.Length];\n\n for (int i = 0; i &lt; props.Length; i++)\n {\n values[i] = props[i].GetValue(item, null);\n }\n\n tb.Rows.Add(values);\n }\n\n return tb;\n }\n\n /// &lt;summary&gt;\n /// Determine of specified type is nullable\n /// &lt;/summary&gt;\n public static bool IsNullable(Type t)\n {\n return !t.IsValueType || (t.IsGenericType &amp;&amp; t.GetGenericTypeDefinition() == typeof(Nullable&lt;&gt;));\n }\n\n /// &lt;summary&gt;\n /// Return underlying type if type is Nullable otherwise return the type\n /// &lt;/summary&gt;\n public static Type GetCoreType(Type t)\n {\n if (t != null &amp;&amp; IsNullable(t))\n {\n if (!t.IsValueType)\n {\n return t;\n }\n else\n {\n return Nullable.GetUnderlyingType(t);\n }\n }\n else\n {\n return t;\n }\n }\n}\n</code></pre>\n\n<p>Usage:</p>\n\n<pre><code> IList&lt;MyClass&gt; myClassList = new List&lt;MyClass&gt;();\n DataTable myClassDataTable = myClassList.ToDataTable();\n</code></pre>\n" }, { "answer_id": 3321163, "author": "Krisc", "author_id": 299946, "author_profile": "https://Stackoverflow.com/users/299946", "pm_score": 2, "selected": false, "text": "<p>I am sure this has been done before, but I find myself using this method (and simpler derivatives) often:</p>\n\n<pre><code>public static bool CompareEx(this string strA, string strB, CultureInfo culture, bool ignoreCase)\n{\n return string.Compare(strA, strB, ignoreCase, culture) == 0;\n}\n</code></pre>\n\n<p>You can write it in a number of ways, but I like it because it very quickly unifies my approach to comparing strings while saving me lines of code (or characters of code).</p>\n" }, { "answer_id": 3321394, "author": "Kenneth J", "author_id": 195456, "author_profile": "https://Stackoverflow.com/users/195456", "pm_score": 2, "selected": false, "text": "<p>Here is the only extension that I wrote that I use regularly. \nIt makes sending email with System.Net.Mail a bit easier.</p>\n\n<pre><code>public static class MailExtension\n{\n // GetEmailCreditial(out strServer) gets credentials from an XML file\n public static void Send(this MailMessage email)\n {\n string strServer = String.Empty;\n NetworkCredential credentials = GetEmailCreditial(out strServer);\n SmtpClient client = new SmtpClient(strServer) { Credentials = credentials };\n client.Send(email);\n }\n\n public static void Send(this IEnumerable&lt;MailMessage&gt; emails)\n {\n string strServer = String.Empty;\n NetworkCredential credentials = GetEmailCreditial(out strServer);\n SmtpClient client = new SmtpClient(strServer) { Credentials = credentials };\n foreach (MailMessage email in emails)\n client.Send(email);\n }\n}\n\n// Example of use: \nnew MailMessage(\"[email protected]\",\"[email protected]\",\"This is an important Subject\", \"Body goes here\").Send();\n//Assume email1,email2,email3 are MailMessage objects\nnew List&lt;MailMessage&gt;(){email1, email2, email}.Send();\n</code></pre>\n" }, { "answer_id": 3423109, "author": "Daniel A.A. Pelsmaeker", "author_id": 146622, "author_profile": "https://Stackoverflow.com/users/146622", "pm_score": 2, "selected": false, "text": "<p>My most used extension is one which can format byte arrays:</p>\n\n<pre><code>/// &lt;summary&gt;\n/// Returns a string representation of a byte array.\n/// &lt;/summary&gt;\n/// &lt;param name=\"bytearray\"&gt;The byte array to represent.&lt;/param&gt;\n/// &lt;param name=\"subdivision\"&gt;The number of elements per group,\n/// or 0 to not restrict it. The default is 0.&lt;/param&gt;\n/// &lt;param name=\"subsubdivision\"&gt;The number of elements per line,\n/// or 0 to not restrict it. The default is 0.&lt;/param&gt;\n/// &lt;param name=\"divider\"&gt;The string dividing the individual bytes. The default is \" \".&lt;/param&gt;\n/// &lt;param name=\"subdivider\"&gt;The string dividing the groups. The default is \" \".&lt;/param&gt;\n/// &lt;param name=\"subsubdivider\"&gt;The string dividing the lines. The default is \"\\r\\n\".&lt;/param&gt;\n/// &lt;param name=\"uppercase\"&gt;Whether the representation is in uppercase hexadecimal.\n/// The default is &lt;see langword=\"true\"/&gt;.&lt;/param&gt;\n/// &lt;param name=\"prebyte\"&gt;The string to put before each byte. The default is an empty string.&lt;/param&gt;\n/// &lt;param name=\"postbyte\"&gt;The string to put after each byte. The default is an empty string.&lt;/param&gt;\n/// &lt;returns&gt;The string representation.&lt;/returns&gt;\n/// &lt;exception cref=\"ArgumentNullException\"&gt;\n/// &lt;paramref name=\"bytearray\"/&gt; is &lt;see langword=\"null\"/&gt;.\n/// &lt;/exception&gt;\npublic static string ToArrayString(this byte[] bytearray,\n int subdivision = 0,\n int subsubdivision = 0,\n string divider = \" \",\n string subdivider = \" \",\n string subsubdivider = \"\\r\\n\",\n bool uppercase = true,\n string prebyte = \"\",\n string postbyte = \"\")\n{\n #region Contract\n if (bytearray == null)\n throw new ArgumentNullException(\"bytearray\");\n #endregion\n\n StringBuilder sb = new StringBuilder(\n bytearray.Length * (2 + divider.Length + prebyte.Length + postbyte.Length) +\n (subdivision &gt; 0 ? (bytearray.Length / subdivision) * subdivider.Length : 0) +\n (subsubdivision &gt; 0 ? (bytearray.Length / subsubdivision) * subsubdivider.Length : 0));\n int groupElements = (subdivision &gt; 0 ? subdivision - 1 : -1);\n int lineElements = (subsubdivision &gt; 0 ? subsubdivision - 1 : -1);\n for (long i = 0; i &lt; bytearray.LongLength - 1; i++)\n {\n sb.Append(prebyte);\n sb.Append(String.Format(CultureInfo.InvariantCulture, (uppercase ? \"{0:X2}\" : \"{0:x2}\"), bytearray[i]));\n sb.Append(postbyte);\n\n if (lineElements == 0)\n {\n sb.Append(subsubdivider);\n groupElements = subdivision;\n lineElements = subsubdivision;\n }\n else if (groupElements == 0)\n {\n sb.Append(subdivider);\n groupElements = subdivision;\n }\n else\n sb.Append(divider);\n\n lineElements--;\n groupElements--;\n }\n sb.Append(prebyte);\n sb.Append(String.Format(CultureInfo.InvariantCulture, (uppercase ? \"{0:X2}\" : \"{0:x2}\"), bytearray[bytearray.LongLength - 1]));\n sb.Append(postbyte);\n\n return sb.ToString();\n}\n</code></pre>\n\n<p>By default <code>ToArrayString()</code> just prints the byte array as a long string of individual bytes. However, <code>ToArrayString(4, 16)</code> groups the bytes in groups of four, with 16 bytes on a line, just as it is in your favorite hex editor. And the following nicely formats the byte array for usage in C# code:</p>\n\n<pre><code>byte[] bytearray = new byte[]{ ... };\nConsole.Write(bytearray.ToArrayString(4, 16, \", \", \", \", \",\\r\\n\", true, \"0x\"));\n</code></pre>\n\n<p>It was written by me, so you may put it on Codeplex.</p>\n" }, { "answer_id": 3524142, "author": "Luke Puplett", "author_id": 107783, "author_profile": "https://Stackoverflow.com/users/107783", "pm_score": 1, "selected": false, "text": "<p>ASP.NET <strong>HTML Encode</strong> - short and sweet:</p>\n\n<pre><code>public static string ToHtmlEncodedString(this string s)\n{\n if (String.IsNullOrEmpty(s))\n return s;\n return HttpUtility.HtmlEncode(s);\n}\n</code></pre>\n" }, { "answer_id": 3527407, "author": "Thomas Levesque", "author_id": 98713, "author_profile": "https://Stackoverflow.com/users/98713", "pm_score": 2, "selected": false, "text": "<p>Wildcard string comparison:</p>\n\n<pre><code>public static bool MatchesWildcard(this string text, string pattern)\n{\n int it = 0;\n while (text.CharAt(it) != 0 &amp;&amp;\n pattern.CharAt(it) != '*')\n {\n if (pattern.CharAt(it) != text.CharAt(it) &amp;&amp; pattern.CharAt(it) != '?')\n return false;\n it++;\n }\n\n int cp = 0;\n int mp = 0;\n int ip = it;\n\n while (text.CharAt(it) != 0)\n {\n if (pattern.CharAt(ip) == '*')\n {\n if (pattern.CharAt(++ip) == 0)\n return true;\n mp = ip;\n cp = it + 1;\n }\n else if (pattern.CharAt(ip) == text.CharAt(it) || pattern.CharAt(ip) == '?')\n {\n ip++;\n it++;\n }\n else\n {\n ip = mp;\n it = cp++;\n }\n }\n\n while (pattern.CharAt(ip) == '*')\n {\n ip++;\n }\n return pattern.CharAt(ip) == 0;\n}\n\npublic static char CharAt(this string s, int index)\n{\n if (index &lt; s.Length)\n return s[index];\n return '\\0';\n}\n</code></pre>\n\n<p>It's a direct translation of the C code from <a href=\"http://www.codeproject.com/KB/string/wildcmp.aspx\" rel=\"nofollow noreferrer\">this article</a>, hence the <code>CharAt</code> method that returns 0 for the end of the string</p>\n\n<pre><code>if (fileName.MatchesWildcard(\"*.cs\"))\n{\n Console.WriteLine(\"{0} is a C# source file\", fileName);\n}\n</code></pre>\n" }, { "answer_id": 3576617, "author": "fre0n", "author_id": 252004, "author_profile": "https://Stackoverflow.com/users/252004", "pm_score": 2, "selected": false, "text": "<p>These extension methods invoke an event asynchronously. They were inspired by <a href=\"https://stackoverflow.com/questions/1916095/how-do-i-make-an-eventhandler-run-asynchronously/1916241#1916241\">this StackOverflow answer</a>.</p>\n\n<pre><code>/// &lt;summary&gt;\n/// Invoke an event asynchronously. Each subscriber to the event will be invoked on a separate thread.\n/// &lt;/summary&gt;\n/// &lt;param name=\"someEvent\"&gt;The event to be invoked asynchronously.&lt;/param&gt;\n/// &lt;param name=\"sender\"&gt;The sender of the event.&lt;/param&gt;\n/// &lt;param name=\"args\"&gt;The args of the event.&lt;/param&gt;\n/// &lt;typeparam name=\"TEventArgs\"&gt;The type of &lt;see cref=\"EventArgs\"/&gt; to be used with the event.&lt;/typeparam&gt;\npublic static void InvokeAsync&lt;TEventArgs&gt;(this EventHandler&lt;TEventArgs&gt; someEvent, object sender, TEventArgs args)\n where TEventArgs : EventArgs\n{\n if (someEvent == null)\n {\n return;\n }\n\n var eventListeners = someEvent.GetInvocationList();\n\n AsyncCallback endAsyncCallback = delegate(IAsyncResult iar)\n {\n var ar = iar as AsyncResult;\n if (ar == null)\n {\n return;\n }\n\n var invokedMethod = ar.AsyncDelegate as EventHandler&lt;TEventArgs&gt;;\n if (invokedMethod != null)\n {\n invokedMethod.EndInvoke(iar);\n }\n };\n\n foreach (EventHandler&lt;TEventArgs&gt; methodToInvoke in eventListeners)\n {\n methodToInvoke.BeginInvoke(sender, args, endAsyncCallback, null);\n }\n}\n\n/// &lt;summary&gt;\n/// Invoke an event asynchronously. Each subscriber to the event will be invoked on a separate thread.\n/// &lt;/summary&gt;\n/// &lt;param name=\"someEvent\"&gt;The event to be invoked asynchronously.&lt;/param&gt;\n/// &lt;param name=\"sender\"&gt;The sender of the event.&lt;/param&gt;\n/// &lt;param name=\"args\"&gt;The args of the event.&lt;/param&gt;\npublic static void InvokeAsync(this EventHandler someEvent, object sender, EventArgs args)\n{\n if (someEvent == null)\n {\n return;\n }\n\n var eventListeners = someEvent.GetInvocationList();\n\n AsyncCallback endAsyncCallback = delegate(IAsyncResult iar)\n {\n var ar = iar as AsyncResult;\n if (ar == null)\n {\n return;\n }\n\n var invokedMethod = ar.AsyncDelegate as EventHandler;\n if (invokedMethod != null)\n {\n invokedMethod.EndInvoke(iar);\n }\n };\n\n foreach (EventHandler methodToInvoke in eventListeners)\n {\n methodToInvoke.BeginInvoke(sender, args, endAsyncCallback, null);\n }\n}\n</code></pre>\n\n<p>To use:</p>\n\n<pre><code>public class Foo\n{\n public event EventHandler&lt;EventArgs&gt; Bar;\n\n public void OnBar()\n {\n Bar.InvokeAsync(this, EventArgs.Empty);\n }\n}\n</code></pre>\n\n<p>Notice the added benefit that you don't have to check for null on the event before invoking it. e.g.:</p>\n\n<pre><code>EventHandler&lt;EventArgs&gt; handler = Bar;\nif (handler != null)\n{\n // Invoke the event\n}\n</code></pre>\n\n<p>To test:</p>\n\n<pre><code>void Main()\n{\n EventHandler&lt;EventArgs&gt; handler1 =\n delegate(object sender, EventArgs args)\n {\n // Simulate performing work in handler1\n Thread.Sleep(100);\n Console.WriteLine(\"Handled 1\");\n };\n\n EventHandler&lt;EventArgs&gt; handler2 =\n delegate(object sender, EventArgs args)\n {\n // Simulate performing work in handler2\n Thread.Sleep(50);\n Console.WriteLine(\"Handled 2\");\n };\n\n EventHandler&lt;EventArgs&gt; handler3 =\n delegate(object sender, EventArgs args)\n {\n // Simulate performing work in handler3\n Thread.Sleep(25);\n Console.WriteLine(\"Handled 3\");\n };\n\n var foo = new Foo();\n foo.Bar += handler1;\n foo.Bar += handler2;\n foo.Bar += handler3;\n foo.OnBar();\n\n Console.WriteLine(\"Start executing important stuff\");\n\n // Simulate performing some important stuff here, where we don't want to\n // wait around for the event handlers to finish executing\n Thread.Sleep(1000);\n\n Console.WriteLine(\"Finished executing important stuff\");\n}\n</code></pre>\n\n<p>Invoking the event will (usually) yield this output:</p>\n\n<blockquote>\n <p>Start executing important stuff<br>\n Handled 3<br>\n Handled 2<br>\n Handled 1<br>\n Finished executing important stuff</p>\n</blockquote>\n\n<p>If the event were invoked synchronously, it would <em>always</em> yield this output - and delay execution of the \"important\" stuff:</p>\n\n<blockquote>\n <p>Handled 1<br>\n Handled 2<br>\n Handled 3<br>\n Start executing important stuff<br>\n Finished executing important stuff</p>\n</blockquote>\n" }, { "answer_id": 3690091, "author": "prabir", "author_id": 157260, "author_profile": "https://Stackoverflow.com/users/157260", "pm_score": 2, "selected": false, "text": "<p>Would be great to have Unix TimeStamp and ISO 8601 formatted date and times. heavily used in websites and rest services.</p>\n\n<p>I use it in my Facebook Library. You can find the source <a href=\"http://github.com/prabirshrestha/FacebookSharp/blob/master/src/FacebookSharp.Core/FacebookUtils/DateUtils.cs\" rel=\"nofollow noreferrer\">http://github.com/prabirshrestha/FacebookSharp/blob/master/src/FacebookSharp.Core/FacebookUtils/DateUtils.cs</a></p>\n\n<pre><code>private static readonly DateTime EPOCH = DateTime.SpecifyKind(new DateTime(1970, 1, 1, 0, 0, 0, 0),DateTimeKind.Utc);\n\npublic static DateTime FromUnixTimestamp(long timestamp)\n{\n return EPOCH.AddSeconds(timestamp);\n}\n\npublic static long ToUnixTimestamp(DateTime date)\n{\n TimeSpan diff = date.ToUniversalTime() - EPOCH;\n return (long)diff.TotalSeconds;\n}\n\npublic static DateTime FromIso8601FormattedDateTime(string iso8601DateTime){\n return DateTime.ParseExact(iso8601DateTime, \"o\", System.Globalization.CultureInfo.InvariantCulture);\n}\n\npublic static string ToIso8601FormattedDateTime(DateTime dateTime)\n{\n return dateTime.ToString(\"o\");\n}\n</code></pre>\n\n<p>Feel free to use in the codeplex project.</p>\n" }, { "answer_id": 3757152, "author": "benPearce", "author_id": 4490, "author_profile": "https://Stackoverflow.com/users/4490", "pm_score": 1, "selected": false, "text": "<p>Overwrite a portion of a string at a specified index.</p>\n\n<p>I have to work with a system that expects some input values to be fixed width, fixed position strings.</p>\n\n<pre><code>public static string Overwrite(this string s, int startIndex, string newStringValue)\n{\n return s.Remove(startIndex, newStringValue.Length).Insert(startIndex, newStringValue);\n}\n</code></pre>\n\n<p>So I can do:</p>\n\n<pre><code>string s = new String(' ',60);\ns = s.Overwrite(7,\"NewValue\");\n</code></pre>\n" }, { "answer_id": 3757160, "author": "benPearce", "author_id": 4490, "author_profile": "https://Stackoverflow.com/users/4490", "pm_score": 3, "selected": false, "text": "<p>Some Date functions:</p>\n\n<pre><code>public static bool IsFuture(this DateTime date, DateTime from)\n{\n return date.Date &gt; from.Date;\n}\n\npublic static bool IsFuture(this DateTime date)\n{\n return date.IsFuture(DateTime.Now);\n}\n\npublic static bool IsPast(this DateTime date, DateTime from)\n{\n return date.Date &lt; from.Date;\n}\n\npublic static bool IsPast(this DateTime date)\n{\n return date.IsPast(DateTime.Now);\n}\n</code></pre>\n" }, { "answer_id": 3834758, "author": "mattmc3", "author_id": 83144, "author_profile": "https://Stackoverflow.com/users/83144", "pm_score": 4, "selected": false, "text": "<p>One of my favorites is an IsLike() extension on String. IsLike() matches <a href=\"http://msdn.microsoft.com/en-us/library/swf8kaxw(v=VS.100).aspx\" rel=\"noreferrer\">VB's Like operator</a>, and is handy when you don't want to write a full-on regex to solve your problem. Usage would be something like this:</p>\n\n<pre><code>\"abc\".IsLike(\"a*\"); // true\n\"Abc\".IsLike(\"[A-Z][a-z][a-z]\"); // true\n\"abc123\".IsLike(\"*###\"); // true\n\"hat\".IsLike(\"?at\"); // true\n\"joe\".IsLike(\"[!aeiou]*\"); // true\n\n\"joe\".IsLike(\"?at\"); // false\n\"joe\".IsLike(\"[A-Z][a-z][a-z]\"); // false\n</code></pre>\n\n<p>Here's the code</p>\n\n<pre><code>public static class StringEntentions {\n /// &lt;summary&gt;\n /// Indicates whether the current string matches the supplied wildcard pattern. Behaves the same\n /// as VB's \"Like\" Operator.\n /// &lt;/summary&gt;\n /// &lt;param name=\"s\"&gt;The string instance where the extension method is called&lt;/param&gt;\n /// &lt;param name=\"wildcardPattern\"&gt;The wildcard pattern to match. Syntax matches VB's Like operator.&lt;/param&gt;\n /// &lt;returns&gt;true if the string matches the supplied pattern, false otherwise.&lt;/returns&gt;\n /// &lt;remarks&gt;See http://msdn.microsoft.com/en-us/library/swf8kaxw(v=VS.100).aspx&lt;/remarks&gt;\n public static bool IsLike(this string s, string wildcardPattern) {\n if (s == null || String.IsNullOrEmpty(wildcardPattern)) return false;\n // turn into regex pattern, and match the whole string with ^$\n var regexPattern = \"^\" + Regex.Escape(wildcardPattern) + \"$\";\n\n // add support for ?, #, *, [], and [!]\n regexPattern = regexPattern.Replace(@\"\\[!\", \"[^\")\n .Replace(@\"\\[\", \"[\")\n .Replace(@\"\\]\", \"]\")\n .Replace(@\"\\?\", \".\")\n .Replace(@\"\\*\", \".*\")\n .Replace(@\"\\#\", @\"\\d\");\n\n var result = false;\n try {\n result = Regex.IsMatch(s, regexPattern);\n }\n catch (ArgumentException ex) {\n throw new ArgumentException(String.Format(\"Invalid pattern: {0}\", wildcardPattern), ex);\n }\n return result;\n }\n}\n</code></pre>\n" }, { "answer_id": 3842545, "author": "scobi", "author_id": 14582, "author_profile": "https://Stackoverflow.com/users/14582", "pm_score": 4, "selected": false, "text": "<p>Here's one I just created today.</p>\n\n<pre><code>// requires .NET 4\n\npublic static TReturn NullOr&lt;TIn, TReturn&gt;(this TIn obj, Func&lt;TIn, TReturn&gt; func,\n TReturn elseValue = default(TReturn)) where TIn : class\n { return obj != null ? func(obj) : elseValue; }\n\n// versions for CLR 2, which doesn't support optional params\n\npublic static TReturn NullOr&lt;TIn, TReturn&gt;(this TIn obj, Func&lt;TIn, TReturn&gt; func,\n TReturn elseValue) where TIn : class\n { return obj != null ? func(obj) : elseValue; }\npublic static TReturn NullOr&lt;TIn, TReturn&gt;(this TIn obj, Func&lt;TIn, TReturn&gt; func)\n where TIn : class\n { return obj != null ? func(obj) : default(TReturn); }\n</code></pre>\n\n<p>It lets you do this:</p>\n\n<pre><code>var lname = thingy.NullOr(t =&gt; t.Name).NullOr(n =&gt; n.ToLower());\n</code></pre>\n\n<p>which is more fluent and (IMO) easier to read than this:</p>\n\n<pre><code>var lname = (thingy != null ? thingy.Name : null) != null\n ? thingy.Name.ToLower() : null;\n</code></pre>\n" }, { "answer_id": 3932311, "author": "RameshVel", "author_id": 97572, "author_profile": "https://Stackoverflow.com/users/97572", "pm_score": 2, "selected": false, "text": "<p>Inspired by String.IsNullOrEmpty</p>\n\n<p>To validate the given List is null or empty</p>\n\n<pre><code>public static bool IsNullOrEmpty&lt;TSource&gt;(this List&lt;TSource&gt; src)\n{ \n return (src == null || src.Count == 0);\n}\n</code></pre>\n\n<p>And this one is to validate given 2 files and properties</p>\n\n<pre><code>public static bool Compare(this FileInfo f1, FileInfo f2, string propertyName)\n{\n try\n {\n PropertyInfo p1 = f1.GetType().GetProperty(propertyName);\n PropertyInfo p2 = f2.GetType().GetProperty(propertyName);\n\n if (p1.GetValue(f1, null) == p2.GetValue(f1, null))\n return true;\n }\n catch (Exception ex)\n {\n return false;\n }\n return false;\n}\n</code></pre>\n\n<p>And use it like this</p>\n\n<pre><code>FileInfo fo = new FileInfo(\"c:\\\\netlog.txt\");\nFileInfo f1 = new FileInfo(\"c:\\\\regkey.txt\");\n\nfo.compare(f1, \"CreationTime\");\n</code></pre>\n" }, { "answer_id": 3935547, "author": "scobi", "author_id": 14582, "author_profile": "https://Stackoverflow.com/users/14582", "pm_score": 3, "selected": false, "text": "<p>Here's a fun one from our codebase at work. Walk an expensive lazy-eval enumerable on a job thread and push the results back through an observable.</p>\n\n<pre><code>public static IObservable&lt;T&gt; ToAsyncObservable&lt;T&gt;(this IEnumerable&lt;T&gt; @this)\n{\n return Observable.Create&lt;T&gt;(observer =&gt;\n {\n var task = new Task(() =&gt;\n {\n try\n {\n @this.Run(observer.OnNext);\n observer.OnCompleted();\n }\n catch (Exception e)\n {\n observer.OnError(e);\n }\n });\n\n task.Start();\n\n return () =&gt; { };\n });\n}\n</code></pre>\n\n<p>Silly sample:</p>\n\n<pre><code>new DirectoryInfo(@\"c:\\program files\")\n .EnumerateFiles(\"*\", SearchOption.AllDirectories)\n .ToAsyncObservable()\n .BufferWithTime(TimeSpan.FromSeconds(0.5))\n .ObserveOnDispatcher()\n .Subscribe(\n l =&gt; Console.WriteLine(\"{0} received\", l.Count),\n () =&gt; Console.WriteLine(\"Done!\"));\n\nfor (;;)\n{\n Thread.Sleep(10);\n Dispatcher.PushFrame(new DispatcherFrame());\n}\n</code></pre>\n\n<p>Obviously this extension will be useless to you if you aren't using the brilliant Reactive Extensions!</p>\n\n<p><strong>UPDATE</strong> thanks to Richard in the comments, this extension method is unnecessary. RX already has an extension method \"ToObservable\" that takes an IScheduler. Use that instead!</p>\n" }, { "answer_id": 3936445, "author": "Richard Szalay", "author_id": 3603, "author_profile": "https://Stackoverflow.com/users/3603", "pm_score": 2, "selected": false, "text": "<p>I actually just <a href=\"http://blog.richardszalay.com/2010/10/14/201010creating-strongly-typed-reactive-html/\" rel=\"nofollow\">blogged</a> this today. It's a strongly typed reactive wrapper around a <code>INotifyPropertyChanged</code> property.</p>\n\n<p><code>GetPropertyValues</code> returns an <code>IObservable&lt;T&gt;</code> of the values as they change, starting with the current value. If ignore the current value, you can just call <code>Skip(1)</code> on the result.</p>\n\n<p>Usage is like so:</p>\n\n<pre><code>IObservable&lt;int&gt; values = viewModel.GetPropertyValues(x =&gt; x.IntProperty);\n</code></pre>\n\n<p>Implementation:</p>\n\n<pre><code>public static class NotifyPropertyChangeReactiveExtensions\n{\n // Returns the values of property (an Expression) as they change, \n // starting with the current value\n public static IObservable&lt;TValue&gt; GetPropertyValues&lt;TSource, TValue&gt;(\n this TSource source, Expression&lt;Func&lt;TSource, TValue&gt;&gt; property)\n where TSource : INotifyPropertyChanged\n {\n MemberExpression memberExpression = property.Body as MemberExpression;\n\n if (memberExpression == null)\n {\n throw new ArgumentException(\n \"property must directly access a property of the source\");\n }\n\n string propertyName = memberExpression.Member.Name;\n\n Func&lt;TSource, TValue&gt; accessor = property.Compile();\n\n return source.GetPropertyChangedEvents()\n .Where(x =&gt; x.EventArgs.PropertyName == propertyName)\n .Select(x =&gt; accessor(source))\n .StartWith(accessor(source));\n }\n\n // This is a wrapper around FromEvent(PropertyChanged)\n public static IObservable&lt;IEvent&lt;PropertyChangedEventArgs&gt;&gt;\n GetPropertyChangedEvents(this INotifyPropertyChanged source)\n {\n return Observable.FromEvent&lt;PropertyChangedEventHandler, \n PropertyChangedEventArgs&gt;(\n h =&gt; new PropertyChangedEventHandler(h),\n h =&gt; source.PropertyChanged += h,\n h =&gt; source.PropertyChanged -= h);\n }\n}\n</code></pre>\n" }, { "answer_id": 3940680, "author": "Will Vousden", "author_id": 58635, "author_profile": "https://Stackoverflow.com/users/58635", "pm_score": 2, "selected": false, "text": "<p>For raising events concisely:</p>\n\n<pre><code>public static void Raise(this EventHandler handler, object sender, EventArgs e)\n{\n if (handler != null)\n {\n handler(sender, e);\n }\n}\n\npublic static void Raise&lt;T&gt;(this EventHandler&lt;T&gt; handler, object sender, T e) where T : EventArgs\n{\n if (handler != null)\n {\n handler(sender, e);\n }\n}\n</code></pre>\n\n<p>Usage:</p>\n\n<pre><code>public event EventHandler Bar;\n\npublic void Foo()\n{\n Bar.Raise(this, EventArgs.Empty);\n}\n</code></pre>\n\n<p>There's a bit of discussion about potential thread-safety issues <a href=\"https://stackoverflow.com/questions/2123608/is-this-a-valid-pattern-for-raising-events-in-c\">here</a>. Since .NET 4, the above form is thread-safe, but requires rearranging and some locks if using an older version.</p>\n" }, { "answer_id": 3944491, "author": "dejanb", "author_id": 376044, "author_profile": "https://Stackoverflow.com/users/376044", "pm_score": 2, "selected": false, "text": "<p>I've written like a quad zillion extension methods, so here are a few ones I find particulary usefull. Feel free to implement.</p>\n\n<pre><code>public static class ControlExtenders\n{\n /// &lt;summary&gt;\n /// Advanced version of find control.\n /// &lt;/summary&gt;\n /// &lt;typeparam name=\"T\"&gt;Type of control to find.&lt;/typeparam&gt;\n /// &lt;param name=\"id\"&gt;Control id to find.&lt;/param&gt;\n /// &lt;returns&gt;Control of given type.&lt;/returns&gt;\n /// &lt;remarks&gt;\n /// If the control with the given id is not found\n /// a new control instance of the given type is returned.\n /// &lt;/remarks&gt;\n public static T FindControl&lt;T&gt;(this Control control, string id) where T : Control\n {\n // User normal FindControl method to get the control\n Control _control = control.FindControl(id);\n\n // If control was found and is of the correct type we return it\n if (_control != null &amp;&amp; _control is T)\n {\n // Return new control\n return (T)_control;\n }\n\n // Create new control instance\n _control = (T)Activator.CreateInstance(typeof(T));\n\n // Add control to source control so the\n // next it is found and the value can be\n // passed on itd, remember to hide it and\n // set an ID so it can be found next time\n if (!(_control is ExtenderControlBase))\n {\n _control.Visible = false;\n }\n _control.ID = id;\n control.Controls.Add(_control);\n\n // Use reflection to create a new instance of the control\n return (T)_control;\n }\n}\n\npublic static class GenericListExtenders\n{\n /// &lt;summary&gt;\n /// Sorts a generic list by items properties.\n /// &lt;/summary&gt;\n /// &lt;typeparam name=\"T\"&gt;Type of collection.&lt;/typeparam&gt;\n /// &lt;param name=\"list\"&gt;Generic list.&lt;/param&gt;\n /// &lt;param name=\"fieldName\"&gt;Field to sort data on.&lt;/param&gt;\n /// &lt;param name=\"sortDirection\"&gt;Sort direction.&lt;/param&gt;\n /// &lt;remarks&gt;\n /// Use this method when a dinamyc sort field is requiered. If the \n /// sorting field is known manual sorting might improve performance.\n /// &lt;/remarks&gt;\n public static void SortObjects&lt;T&gt;(this List&lt;T&gt; list, string fieldName, SortDirection sortDirection)\n {\n PropertyInfo propInfo = typeof(T).GetProperty(fieldName);\n if (propInfo != null)\n {\n Comparison&lt;T&gt; compare = delegate(T a, T b)\n {\n bool asc = sortDirection == SortDirection.Ascending;\n object valueA = asc ? propInfo.GetValue(a, null) : propInfo.GetValue(b, null);\n object valueB = asc ? propInfo.GetValue(b, null) : propInfo.GetValue(a, null);\n return valueA is IComparable ? ((IComparable)valueA).CompareTo(valueB) : 0;\n };\n list.Sort(compare);\n }\n }\n\n /// &lt;summary&gt;\n /// Creates a pagged collection from generic list.\n /// &lt;/summary&gt;\n /// &lt;typeparam name=\"T\"&gt;Type of collection.&lt;/typeparam&gt;\n /// &lt;param name=\"list\"&gt;Generic list.&lt;/param&gt;\n /// &lt;param name=\"sortField\"&gt;Field to sort data on.&lt;/param&gt;\n /// &lt;param name=\"sortDirection\"&gt;Sort direction.&lt;/param&gt;\n /// &lt;param name=\"from\"&gt;Page from item index.&lt;/param&gt;\n /// &lt;param name=\"to\"&gt;Page to item index.&lt;/param&gt;\n /// &lt;param name=\"copy\"&gt;Creates a copy and returns a new list instead of changing the current one.&lt;/param&gt;\n /// &lt;returns&gt;Pagged list collection.&lt;/returns&gt;\n public static List&lt;T&gt; Page&lt;T&gt;(this List&lt;T&gt; list, string sortField, bool sortDirection, int from, int to, bool copy)\n {\n List&lt;T&gt; _pageList = new List&lt;T&gt;();\n\n // Copy list\n if (copy)\n {\n T[] _arrList = new T[list.Count];\n list.CopyTo(_arrList);\n _pageList = new List&lt;T&gt;(_arrList);\n }\n else\n {\n _pageList = list;\n }\n\n // Make sure there are enough items in the list\n if (from &gt; _pageList.Count)\n {\n int diff = Math.Abs(from - to);\n from = _pageList.Count - diff;\n }\n if (to &gt; _pageList.Count)\n {\n to = _pageList.Count;\n }\n\n // Sort items\n if (!string.IsNullOrEmpty(sortField))\n {\n SortDirection sortDir = SortDirection.Descending;\n if (!sortDirection) sortDir = SortDirection.Ascending;\n _pageList.SortObjects(sortField, sortDir);\n }\n\n // Calculate max number of items per page\n int count = to - from;\n if (from + count &gt; _pageList.Count) count -= (from + count) - _pageList.Count;\n\n // Get max number of items per page\n T[] pagged = new T[count];\n _pageList.CopyTo(from, pagged, 0, count);\n\n // Return pagged items\n return new List&lt;T&gt;(pagged);\n }\n\n /// &lt;summary&gt;\n /// Shuffle's list items.\n /// &lt;/summary&gt;\n /// &lt;typeparam name=\"T\"&gt;List type.&lt;/typeparam&gt;\n /// &lt;param name=\"list\"&gt;Generic list.&lt;/param&gt;\n public static void Shuffle&lt;T&gt;(this List&lt;T&gt; list)\n {\n Random rng = new Random();\n for (int i = list.Count - 1; i &gt; 0; i--)\n {\n int swapIndex = rng.Next(i + 1);\n if (swapIndex != i)\n {\n T tmp = list[swapIndex];\n list[swapIndex] = list[i];\n list[i] = tmp;\n }\n }\n }\n\n /// &lt;summary&gt;\n /// Converts generic List to DataTable.\n /// &lt;/summary&gt;\n /// &lt;typeparam name=\"T\"&gt;Type.&lt;/typeparam&gt;\n /// &lt;param name=\"list\"&gt;Generic list.&lt;/param&gt;\n /// &lt;param name=\"columns\"&gt;Name of the columns to copy to the DataTable.&lt;/param&gt;\n /// &lt;returns&gt;DataTable.&lt;/returns&gt;\n public static DataTable ToDataTable&lt;T&gt;(this List&lt;T&gt; list, string[] columns)\n {\n List&lt;string&gt; _columns = new List&lt;string&gt;(columns);\n DataTable dt = new DataTable();\n\n foreach (PropertyInfo info in typeof(T).GetProperties())\n {\n if (_columns.Contains(info.Name) || columns == null)\n {\n dt.Columns.Add(new DataColumn(info.Name, info.PropertyType));\n }\n }\n foreach (T t in list)\n {\n DataRow row = dt.NewRow();\n foreach (PropertyInfo info in typeof(T).GetProperties())\n {\n if (_columns.Contains(info.Name) || columns == null)\n {\n row[info.Name] = info.GetValue(t, null);\n }\n }\n dt.Rows.Add(row);\n }\n return dt;\n }\n}\n\npublic static class DateTimeExtenders\n{\n /// &lt;summary&gt;\n /// Returns number of month from a string representation.\n /// &lt;/summary&gt;\n /// &lt;returns&gt;Number of month.&lt;/returns&gt;\n public static int MonthToNumber(this DateTime datetime, string month)\n {\n month = month.ToLower();\n for (int i = 1; i &lt;= 12; i++)\n {\n DateTime _dt = DateTime.Parse(\"1.\" + i + \".2000\");\n string _month = CultureInfo.InvariantCulture.DateTimeFormat.GetMonthName(i).ToLower();\n if (_month == month)\n {\n return i;\n }\n }\n return 0;\n }\n\n /// &lt;summary&gt;\n /// Returns month name from month number.\n /// &lt;/summary&gt;\n /// &lt;returns&gt;Name of month.&lt;/returns&gt;\n public static string MonthToName(this DateTime datetime, int month)\n {\n for (int i = 1; i &lt;= 12; i++)\n {\n if (i == month)\n {\n return CultureInfo.InvariantCulture.DateTimeFormat.GetMonthName(i);\n }\n }\n return \"\";\n }\n}\n\npublic static class ObjectExtender\n{\n public static object CloneBinary&lt;T&gt;(this T originalObject)\n {\n using (var stream = new System.IO.MemoryStream())\n {\n BinaryFormatter binaryFormatter = new BinaryFormatter();\n binaryFormatter.Serialize(stream, originalObject);\n stream.Position = 0;\n return (T)binaryFormatter.Deserialize(stream);\n }\n }\n\n public static object CloneObject(this object obj)\n {\n using (MemoryStream memStream = new MemoryStream())\n {\n BinaryFormatter binaryFormatter = new BinaryFormatter(null, new StreamingContext(StreamingContextStates.Clone));\n binaryFormatter.Serialize(memStream, obj);\n memStream.Position = 0;\n return binaryFormatter.Deserialize(memStream);\n }\n }\n}\n\npublic static class StringExtenders\n{\n /// &lt;summary&gt;\n /// Returns string as unit.\n /// &lt;/summary&gt;\n /// &lt;param name=\"value\"&gt;Value.&lt;/param&gt;\n /// &lt;returns&gt;Unit&lt;/returns&gt;\n public static Unit ToUnit(this string value)\n {\n // Return empty unit\n if (string.IsNullOrEmpty(value))\n return Unit.Empty;\n\n // Trim value\n value = value.Trim();\n\n // Return pixel unit\n if (value.EndsWith(\"px\"))\n {\n // Set unit type\n string _int = value.Replace(\"px\", \"\");\n\n // Try parsing to int\n double _val = 0;\n if (!double.TryParse(_int, out _val))\n {\n // Invalid value\n return Unit.Empty;\n }\n\n // Return unit\n return new Unit(_val, UnitType.Pixel);\n }\n\n // Return percent unit\n if (value.EndsWith(\"%\"))\n {\n // Set unit type\n string _int = value.Replace(\"%\", \"\");\n\n // Try parsing to int\n double _val = 0;\n if (!double.TryParse(_int, out _val))\n {\n // Invalid value\n return Unit.Empty;\n }\n\n // Return unit\n return new Unit(_val, UnitType.Percentage);\n }\n\n // No match found\n return new Unit();\n }\n\n /// &lt;summary&gt;\n /// Returns alternative string if current string is null or empty.\n /// &lt;/summary&gt;\n /// &lt;param name=\"str\"&gt;&lt;/param&gt;\n /// &lt;param name=\"alternative\"&gt;&lt;/param&gt;\n /// &lt;returns&gt;&lt;/returns&gt;\n public static string Alternative(this string str, string alternative)\n {\n if (string.IsNullOrEmpty(str)) return alternative;\n return str;\n }\n\n /// &lt;summary&gt;\n /// Removes all HTML tags from string.\n /// &lt;/summary&gt;\n /// &lt;param name=\"html\"&gt;String containing HTML tags.&lt;/param&gt;\n /// &lt;returns&gt;String with no HTML tags.&lt;/returns&gt;\n public static string StripHTML(this string html)\n {\n string nohtml = Regex.Replace(html, \"&lt;(.|\\n)*?&gt;\", \"\");\n nohtml = nohtml.Replace(\"\\r\\n\", \"\").Replace(\"\\n\", \"\").Replace(\"&amp;nbsp;\", \"\").Trim();\n return nohtml;\n }\n}\n</code></pre>\n\n<p>The first one is my favourite as it enables me to replace:</p>\n\n<pre><code>Control c = this.FindControl(\"tbName\");\nif (c != null)\n{\n // Do something with c\n customer.Name = ((TextBox)c).Text;\n}\n</code></pre>\n\n<p>With this:</p>\n\n<pre><code>TextBox c = this.FindControl&lt;TextBox&gt;(\"tbName\");\ncustomer.Name = c.Text;\n</code></pre>\n\n<p>Settings default string values:</p>\n\n<pre><code>string str = \"\";\nif (string.IsNullOrEmpty(str))\n{\n str = \"I'm empty!\";\n}\n</code></pre>\n\n<p>Becomes:</p>\n\n<pre><code>str = str.Alternative(\"I'm empty!\");\n</code></pre>\n" }, { "answer_id": 3973579, "author": "KeithS", "author_id": 436376, "author_profile": "https://Stackoverflow.com/users/436376", "pm_score": 2, "selected": false, "text": "<p>Didn't check the whole thread, so it may already be here, but:</p>\n\n<pre><code>public static class FluentOrderingExtensions\n public class FluentOrderer&lt;T&gt; : IEnumerable&lt;T&gt;\n {\n internal List&lt;Comparison&lt;T&gt;&gt; Comparers = new List&lt;Comparison&lt;T&gt;&gt;();\n\n internal IEnumerable&lt;T&gt; Source;\n\n public FluentOrderer(IEnumerable&lt;T&gt; source)\n {\n Source = source;\n }\n\n #region Implementation of IEnumerable\n\n public IEnumerator&lt;T&gt; GetEnumerator()\n {\n var workingArray = Source.ToArray();\n Array.Sort(workingArray, IterativeComparison);\n\n foreach(var element in workingArray) yield return element;\n }\n\n private int IterativeComparison(T a, T b)\n {\n foreach (var comparer in Comparers)\n {\n var result = comparer(a,b);\n if(result != 0) return result;\n }\n return 0;\n }\n\n IEnumerator IEnumerable.GetEnumerator()\n {\n return GetEnumerator();\n }\n\n #endregion\n }\n\n public static FluentOrderer&lt;T&gt; OrderFluentlyBy&lt;T,TResult&gt;(this IEnumerable&lt;T&gt; source, Func&lt;T,TResult&gt; predicate) \n where TResult : IComparable&lt;TResult&gt;\n {\n var result = new FluentOrderer&lt;T&gt;(source);\n result.Comparers.Add((a,b)=&gt;predicate(a).CompareTo(predicate(b)));\n return result;\n }\n\n public static FluentOrderer&lt;T&gt; OrderFluentlyByDescending&lt;T,TResult&gt;(this IEnumerable&lt;T&gt; source, Func&lt;T,TResult&gt; predicate) \n where TResult : IComparable&lt;TResult&gt;\n {\n var result = new FluentOrderer&lt;T&gt;(source);\n result.Comparers.Add((a,b)=&gt;predicate(a).CompareTo(predicate(b)) * -1);\n return result;\n }\n\n public static FluentOrderer&lt;T&gt; ThenBy&lt;T, TResult&gt;(this FluentOrderer&lt;T&gt; source, Func&lt;T, TResult&gt; predicate)\n where TResult : IComparable&lt;TResult&gt;\n {\n source.Comparers.Add((a, b) =&gt; predicate(a).CompareTo(predicate(b)));\n return source;\n }\n\n public static FluentOrderer&lt;T&gt; ThenByDescending&lt;T, TResult&gt;(this FluentOrderer&lt;T&gt; source, Func&lt;T, TResult&gt; predicate)\n where TResult : IComparable&lt;TResult&gt;\n {\n source.Comparers.Add((a, b) =&gt; predicate(a).CompareTo(predicate(b)) * -1);\n return source;\n }\n}\n</code></pre>\n\n<p>Usage:</p>\n\n<pre><code>var myFluentlyOrderedList = GetABunchOfComplexObjects()\n .OrderFluentlyBy(x=&gt;x.PropertyA)\n .ThenByDescending(x=&gt;x.PropertyB)\n .ThenBy(x=&gt;x.SomeMethod())\n .ThenBy(x=&gt;SomeOtherMethodAppliedTo(x))\n .ToList();\n</code></pre>\n\n<p>... assuming of course that all the predicates return types that are IComparable to themselves. It would work better with a stable sort like a MergeSort instead of .NET's built-in QuickSort, but it provides you with readable multi-field ordering ability similar to SQL (as close as a method chain can get, anyway). You can extend this to accomodate members that aren't IComparable, by defining overloads that take a comparison lambda instead of creating it based on a predicate.</p>\n\n<p>EDIT: A little explanation, since the commenter got some upticks: this set of methods improves upon the basic OrderBy() functionality by allowing you to sort based on multiple fields in descending order of importance. A real-world example would be sorting a list of invoices by customer, then by invoice number (or invoice date). Other methods of getting the data in this order either wouldn't work (OrderBy() uses an unstable sort, so it cannot be chained) or would be inefficient and not look like it does what you're trying to do.</p>\n" }, { "answer_id": 3997753, "author": "John", "author_id": 83091, "author_profile": "https://Stackoverflow.com/users/83091", "pm_score": 0, "selected": false, "text": "<p>This one is not fully baked as we just came up with it this morning. It will generate a full class definition for a Type. Useful for situations where you have a a large class and want to create a subset or full definition but don't have access to it. For example, to store the object in a database etc.</p>\n\n<pre><code>public static class TypeExtensions\n{\n public static string GenerateClassDefinition(this Type type)\n {\n var properties = type.GetFields();\n var sb = new StringBuilder();\n var classtext = @\"private class $name\n {\n $props}\";\n\n foreach (var p in GetTypeInfo(type))\n {\n sb.AppendFormat(\" public {0} {1} \", p.Item2, p.Item1).AppendLine(\" { get; set; }\");\n }\n\n return classtext.Replace(\"$name\", type.Name).Replace(\"$props\", sb.ToString());\n }\n\n #region Private Methods\n private static List&lt;Tuple&lt;string, string&gt;&gt; GetTypeInfo(Type type)\n {\n var ret = new List&lt;Tuple&lt;string, string&gt;&gt;();\n var fields = type.GetFields();\n var props = type.GetProperties();\n\n foreach(var p in props) ret.Add(new Tuple&lt;string, string&gt;(p.Name, TranslateType(p.PropertyType))); \n foreach(var f in fields) ret.Add(new Tuple&lt;string, string&gt;(f.Name, TranslateType(f.FieldType)));\n\n return ret;\n }\n\n\n private static string TranslateType(Type input)\n {\n string ret;\n\n if (Nullable.GetUnderlyingType(input) != null)\n {\n ret = string.Format(\"{0}?\", TranslateType(Nullable.GetUnderlyingType(input)));\n }\n else\n {\n switch (input.Name)\n {\n case \"Int32\": ret = \"int\"; break;\n case \"Int64\": ret = \"long\"; break;\n case \"IntPtr\": ret = \"long\"; break;\n case \"Boolean\": ret = \"bool\"; break;\n case \"String\":\n case \"Char\":\n case \"Decimal\":\n ret = input.Name.ToLower(); break;\n default: ret = input.Name; break;\n }\n }\n\n return ret;\n }\n #endregion\n}\n</code></pre>\n\n<p>Example usage:</p>\n\n<pre><code>Process.GetProcesses().First().GetType().GenerateClassDefinition();\n</code></pre>\n\n<p>Becomes even more handy if using linqpad:</p>\n\n<pre><code>Process.GetProcesses().First().GetType().GenerateClassDefinition().Dump();\n</code></pre>\n" }, { "answer_id": 4001342, "author": "KeithS", "author_id": 436376, "author_profile": "https://Stackoverflow.com/users/436376", "pm_score": 3, "selected": false, "text": "<p>Here's another pair I've found endless use for:</p>\n\n<pre><code>public static T ObjectWithMin&lt;T, TResult&gt;(this IEnumerable&lt;T&gt; sequence, Func&lt;T, TResult&gt; predicate)\n where T : class\n where TResult : IComparable\n{\n if (!sequence.Any()) return null;\n\n //get the first object with its predicate value\n var seed = sequence.Select(x =&gt; new {Object = x, Value = predicate(x)}).FirstOrDefault();\n //compare against all others, replacing the accumulator with the lesser value\n //tie goes to first object found\n return\n sequence.Select(x =&gt; new {Object = x, Value = predicate(x)})\n .Aggregate(seed,(acc, x) =&gt; acc.Value.CompareTo(x.Value) &lt;= 0 ? acc : x).Object;\n}\n\npublic static T ObjectWithMax&lt;T, TResult&gt;(this IEnumerable&lt;T&gt; sequence, Func&lt;T, TResult&gt; predicate)\n where T : class\n where TResult : IComparable\n{\n if (!sequence.Any()) return null;\n\n //get the first object with its predicate value\n var seed = sequence.Select(x =&gt; new {Object = x, Value = predicate(x)}).FirstOrDefault();\n //compare against all others, replacing the accumulator with the greater value\n //tie goes to last object found\n return\n sequence.Select(x =&gt; new {Object = x, Value = predicate(x)})\n .Aggregate(seed, (acc, x) =&gt; acc.Value.CompareTo(x.Value) &gt; 0 ? acc : x).Object;\n}\n</code></pre>\n\n<p>Usage:</p>\n\n<pre><code>var myObject = myList.ObjectWithMin(x=&gt;x.PropA);\n</code></pre>\n\n<p>These methods basically replace usages like</p>\n\n<pre><code>var myObject = myList.OrderBy(x=&gt;x.PropA).FirstOrDefault(); //O(nlog(n)) and unstable\n</code></pre>\n\n<p>and</p>\n\n<pre><code>var myObject = myList.Where(x=&gt;x.PropA == myList.Min(x=&gt;x.PropA)).FirstOrDefault(); //O(N^2) but stable\n</code></pre>\n\n<p>and</p>\n\n<pre><code>var minValue = myList.Min(x=&gt;x.PropA);\nvar myObject = myList.Where(x=&gt;x.PropA == minValue).FirstOrDefault(); //not a one-liner, and though linear and stable it's slower (evaluates the enumerable twice)\n</code></pre>\n" }, { "answer_id": 4001549, "author": "KeithS", "author_id": 436376, "author_profile": "https://Stackoverflow.com/users/436376", "pm_score": 1, "selected": false, "text": "<p>And one more:</p>\n\n<pre><code>public enum ParseFailBehavior\n{\n ReturnNull,\n ReturnDefault,\n ThrowException\n}\n\npublic static T? ParseNullableEnum&lt;T&gt;(this string theValue, ParseFailBehavior desiredBehavior = ParseFailBehavior.ReturnNull) where T:struct\n{\n T output;\n T? result = Enum.TryParse&lt;T&gt;(theValue, out output) \n ? (T?)output\n : desiredBehavior == ParseFailBehavior.ReturnDefault\n ? (T?)default(T)\n : null;\n\n if(result == null &amp;&amp; desiredBehavior == ParseFailBehavior.ThrowException)\n throw new ArgumentException(\"Parse Failed for value {0} of enum type {1}\".\n FormatWith(theValue, typeof(T).Name)); \n}\n</code></pre>\n\n<p>This version requires .NET 4.0; in 3.5 you have no TryParse and no optional parameters; you're stuck with Enum.Parse() which you have to try-catch. It's still totally doable in 3.5 (and much more useful as Enum.Parse() is oogly and your only other option):</p>\n\n<pre><code>public static T? ParseNummableEnum&lt;T&gt;(this string theValue)\n{\n return theValue.ParseNullableEnum&lt;T&gt;(ParseFailBehavior.ReturnNull);\n}\n\npublic static T? ParseNullableEnum&lt;T&gt;(this string theValue, \n ParseFailBehavior desiredBehavior) where T:struct\n{\n try\n {\n return (T?) Enum.Parse(typeof (T), theValue);\n }\n catch (Exception)\n {\n if(desiredBehavior == ParseFailBehavior.ThrowException) throw;\n }\n\n return desiredBehavior == ParseFailBehavior.ReturnDefault ? (T?)default(T) : null;\n}\n</code></pre>\n\n<p>Usage:</p>\n\n<pre><code>//returns null if OptionOne isn't an enum constant\nvar myEnum = \"OptionOne\".ParseNullableEnum&lt;OptionEnum&gt;(); \n\n//guarantees a return value IF the enum has a \"zero\" constant value (generally a good practice)\nvar myEnum = \"OptionTwo\".ParseNullableEnum&lt;OptionEnum&gt;(ParseFailBehavior.ReturnDefault).Value \n</code></pre>\n" }, { "answer_id": 4152788, "author": "Will Vousden", "author_id": 58635, "author_profile": "https://Stackoverflow.com/users/58635", "pm_score": 2, "selected": false, "text": "<p>Here are a couple of methods that I use to make extracting single attributes a little less painful:</p>\n\n<pre><code>public static T GetAttribute&lt;T&gt;(this ICustomAttributeProvider provider, bool inherit = false, int index = 0) where T : Attribute\n{\n return provider.GetAttribute(typeof(T), inherit, index) as T;\n}\n\npublic static Attribute GetAttribute(this ICustomAttributeProvider provider, Type type, bool inherit = false, int index = 0)\n{\n bool exists = provider.IsDefined(type, inherit);\n if (!exists)\n {\n return null;\n }\n\n object[] attributes = provider.GetCustomAttributes(type, inherit);\n if (attributes != null &amp;&amp; attributes.Length != 0)\n {\n return attributes[index] as Attribute;\n }\n else\n {\n return null;\n }\n}\n</code></pre>\n\n<p>Usage (implementation of <a href=\"http://blog.spontaneouspublicity.com/post/2008/01/17/Associating-Strings-with-enums-in-C.aspx\" rel=\"nofollow\">this</a> enum description hack):</p>\n\n<pre><code>public static string GetDescription(this Enum value)\n{\n var fieldInfo = value.GetType().GetField(value.ToString());\n var attribute = fieldInfo.GetAttribute&lt;DescriptionAttribute&gt;();\n return attribute != null ? attribute.Description : null;\n}\n</code></pre>\n\n<p>Feel free to include this in the CodePlex project!</p>\n" }, { "answer_id": 4178109, "author": "Roman A. Taycher", "author_id": 259130, "author_profile": "https://Stackoverflow.com/users/259130", "pm_score": 0, "selected": false, "text": "<p><a href=\"https://github.com/rtaycher/Smalltalk-like-control-structures/blob/master/SmalltalkBooleanExtensionMethods/BooleanExtension.cs\" rel=\"nofollow\">Smalltalk style if/else in c#.</a></p>\n\n<p>Feel free to put this on codeplex under whatever license you are using</p>\n\n<pre><code>using System;\nnamespace SmalltalkBooleanExtensionMethods\n{\n\n public static class BooleanExtension\n {\n public static T ifTrue&lt;T&gt; (this bool aBoolean, Func&lt;T&gt; method)\n {\n if (aBoolean)\n return (T)method();\n else\n return default(T);\n }\n\n public static void ifTrue (this bool aBoolean, Action method)\n {\n if (aBoolean)\n method();\n }\n\n\n public static T ifFalse&lt;T&gt; (this bool aBoolean, Func&lt;T&gt; method)\n {\n if (!aBoolean)\n return (T)method();\n else\n return default(T);\n }\n\n public static void ifFalse (this bool aBoolean, Action method)\n {\n if (!aBoolean)\n method();\n }\n\n\n public static T ifTrueifFalse&lt;T&gt; (this Boolean aBoolean, Func&lt;T&gt; methodA, Func&lt;T&gt; methodB)\n {\n if (aBoolean)\n return (T)methodA();\n else\n return (T)methodB();\n }\n\n public static void ifTrueifFalse (this Boolean aBoolean, Action methodA, Action methodB)\n {\n if (aBoolean)\n methodA();\n else\n methodB();\n }\n\n }\n\n\n}\n</code></pre>\n\n<p>You probably already have a timesRepeat method but its in there.</p>\n\n<pre><code>using System;\n\nnamespace SmalltalkBooleanExtensionMethods\n{\n public static class IntExtension\n {\n public static int timesRepeat&lt;T&gt;(this int x, Func&lt;T&gt; method)\n {\n for (int i = x; i &gt; 0; i--)\n {\n method();\n }\n\n return x;\n }\n\n public static int timesRepeat(this int x, Action method)\n {\n for (int i = x; i &gt; 0; i--)\n {\n method();\n }\n\n return x;\n }\n }\n}\n</code></pre>\n\n<p>Nunit Tests</p>\n\n<pre><code>using System;\nusing SmalltalkBooleanExtensionMethods;\nusing NUnit.Framework;\n\nnamespace SmalltalkBooleanExtensionMethodsTest\n{\n [TestFixture]\n public class SBEMTest\n {\n int i;\n bool itWorks;\n\n [SetUp]\n public void Init()\n {\n\n i = 0;\n itWorks = false;\n }\n\n [Test()]\n public void TestifTrue()\n {\n\n itWorks = (true.ifTrue(() =&gt; true));\n Assert.IsTrue(itWorks);\n }\n [Test()]\n public void TestifFalse()\n {\n itWorks = (false.ifFalse(() =&gt; true));\n Assert.IsTrue(itWorks);\n }\n\n [Test()]\n public void TestifTrueifFalse()\n {\n itWorks = false.ifTrueifFalse(() =&gt; false, () =&gt; true);\n Assert.IsTrue(itWorks);\n itWorks = false;\n itWorks = true.ifTrueifFalse(() =&gt; true, () =&gt; false);\n Assert.IsTrue(itWorks);\n }\n\n [Test()]\n public void TestTimesRepeat()\n {\n (5).timesRepeat(() =&gt; i = i + 1);\n Assert.AreEqual(i, 5);\n }\n\n [Test()]\n public void TestVoidMethodIfTrue()\n {\n\n true.ifTrue(() =&gt; SetItWorksBooleanToTrue());\n Assert.IsTrue(itWorks);\n }\n\n [Test()]\n public void TestVoidMethodIfFalse()\n {\n\n false.ifFalse(() =&gt; SetItWorksBooleanToTrue());\n Assert.IsTrue(itWorks);\n }\n\n public void TestVoidMethodIfTrueIfFalse()\n {\n true.ifTrueifFalse(() =&gt; SetItWorksBooleanToTrue(), () =&gt; SetItWorksBooleanToFalse());\n false.ifTrueifFalse(() =&gt; SetItWorksBooleanToFalse(), () =&gt; SetItWorksBooleanToTrue());\n Assert.IsTrue(itWorks);\n\n }\n\n public void TestVoidMethodTimesRepeat()\n {\n (5).timesRepeat(() =&gt; AddOneToi());\n Assert.AreEqual(i, 5);\n }\n\n public void SetItWorksBooleanToTrue()\n {\n itWorks = true;\n }\n\n public void SetItWorksBooleanToFalse()\n {\n itWorks = false;\n }\n\n public void AddOneToi()\n {\n i = i + 1;\n }\n }\n}\n</code></pre>\n" }, { "answer_id": 4339648, "author": "Nicholas Carey", "author_id": 467473, "author_profile": "https://Stackoverflow.com/users/467473", "pm_score": 1, "selected": false, "text": "<p>Whitespace normalization is rather useful, especially when dealing with user input:</p>\n\n<pre><code>namespace Extensions.String\n{\n using System.Text.RegularExpressions;\n\n public static class Extensions\n {\n /// &lt;summary&gt;\n /// Normalizes whitespace in a string.\n /// Leading/Trailing whitespace is eliminated and\n /// all sequences of internal whitespace are reduced to\n /// a single SP (ASCII 0x20) character.\n /// &lt;/summary&gt;\n /// &lt;param name=\"s\"&gt;The string whose whitespace is to be normalized&lt;/param&gt;\n /// &lt;returns&gt;a normalized string&lt;/returns&gt;\n public static string NormalizeWS( this string @this )\n {\n string src = @this ?? \"\" ;\n string normalized = rxWS.Replace( src , m =&gt;{\n bool isLeadingTrailingWS = ( m.Index == 0 || m.Index+m.Length == src.Length ? true : false ) ;\n string p = ( isLeadingTrailingWS ? \"\" : \" \" ) ;\n return p ;\n }) ;\n\n return normalized ;\n\n }\n private static Regex rxWS = new Regex( @\"\\s+\" ) ;\n }\n}\n</code></pre>\n" }, { "answer_id": 4525903, "author": "Chris", "author_id": 553218, "author_profile": "https://Stackoverflow.com/users/553218", "pm_score": 0, "selected": false, "text": "<p>Ive created a extension method to select an item in a dropdown in ASP.NET.</p>\n\n<p>Below is the code</p>\n\n<pre><code> public static class Utilities\n{\n public enum DropDownListSelectionType\n {\n ByValue,\n ByText\n }\n\n public static void SelectItem(this System.Web.UI.WebControls.DropDownList drp, string selectedValue, DropDownListSelectionType type)\n {\n drp.ClearSelection();\n System.Web.UI.WebControls.ListItem li;\n if (type == DropDownListSelectionType.ByValue)\n li = drp.Items.FindByValue(selectedValue.Trim());\n else\n li = drp.Items.FindByText(selectedValue.Trim());\n if (li != null)\n li.Selected = true;\n }}\n</code></pre>\n\n<p>This method can be called by the following lines of code to either select by text</p>\n\n<pre><code>DropDownList1.SelectItem(\"ABCD\", Utilities.DropDownListSelectionType.ByText);\n</code></pre>\n\n<p>or select by value</p>\n\n<pre><code>DropDownList1.SelectItem(\"11\", Utilities.DropDownListSelectionType.ByValue);\n</code></pre>\n\n<p>The above code doesnt select anything if it cant find the text/value passed in.</p>\n" }, { "answer_id": 4689138, "author": "HuseyinUslu", "author_id": 170181, "author_profile": "https://Stackoverflow.com/users/170181", "pm_score": 3, "selected": false, "text": "<p>Here's a bitmap extension which can convert bitmaps to grayscale;</p>\n\n<pre><code>public static Bitmap GrayScale(this Bitmap bitmap)\n{\n Bitmap newBitmap = new Bitmap(bitmap.Width, bitmap.Height);\n Graphics g = Graphics.FromImage(newBitmap);\n\n //the grayscale ColorMatrix\n ColorMatrix colorMatrix = new ColorMatrix(new float[][] {\n new float[] {.3f, .3f, .3f, 0, 0},\n new float[] {.59f, .59f, .59f, 0, 0},\n new float[] {.11f, .11f, .11f, 0, 0},\n new float[] {0, 0, 0, 1, 0},\n new float[] {0, 0, 0, 0, 1}\n });\n\n ImageAttributes attributes = new ImageAttributes();\n attributes.SetColorMatrix(colorMatrix);\n g.DrawImage(bitmap, new Rectangle(0, 0, bitmap.Width, bitmap.Height), 0, 0, bitmap.Width, bitmap.Height, GraphicsUnit.Pixel, attributes);\n g.Dispose();\n return newBitmap;\n}\n</code></pre>\n\n<p>Sample usage:</p>\n\n<pre><code>Bitmap grayscaled = bitmap.GrayScale()\n</code></pre>\n" }, { "answer_id": 4689170, "author": "HuseyinUslu", "author_id": 170181, "author_profile": "https://Stackoverflow.com/users/170181", "pm_score": 0, "selected": false, "text": "<p>And here's the control-invoke extension i'm using regularly;</p>\n\n<pre><code>public static class InvokeExtensions\n{\n public static void InvokeHandler(this Control control, MethodInvoker del) // Sync. control-invoke extension.\n {\n if (control.InvokeRequired)\n {\n control.Invoke(del);\n return; \n }\n del(); // run the actual code.\n }\n\n public static void AsyncInvokeHandler(this Control control, MethodInvoker del) // Async. control-invoke extension.\n {\n if (control.InvokeRequired)\n {\n control.BeginInvoke(del);\n return; \n }\n del(); // run the actual code.\n }\n}\n</code></pre>\n\n<p>sample;</p>\n\n<pre><code>this.TreeView.AsyncInvokeHandler(() =&gt;\n {\n this.Text = 'xyz'\n });\n</code></pre>\n\n<p>which allows cross-thread gui-updates.</p>\n" }, { "answer_id": 4690969, "author": "19WAS85", "author_id": 79191, "author_profile": "https://Stackoverflow.com/users/79191", "pm_score": 1, "selected": false, "text": "<p>Some tools to IEnumerable: ToString(Format), ToString(Function) and Join(Separator).</p>\n\n<p>For example:</p>\n\n<pre><code>var names = new[] { \"Wagner\", \"Francine\", \"Arthur\", \"Bernardo\" };\n\nnames.ToString(\"Name: {0}\\n\");\n// Name: Wagner\n// Name: Francine\n// Name: Arthur\n// Name: Bernardo\n\nnames.ToString(name =&gt; name.Length &gt; 6 ? String.Format(\"{0} \", name) : String.Empty);\n// Francine Bernardo\n\nnames.Join(\" - \");\n// Wagner - Francine - Arthur - Bernardo\n</code></pre>\n\n<p>Extensions:</p>\n\n<pre><code>public static string ToString&lt;T&gt;(this IEnumerable&lt;T&gt; self, string format)\n{\n return self.ToString(i =&gt; String.Format(format, i));\n}\n\npublic static string ToString&lt;T&gt;(this IEnumerable&lt;T&gt; self, Func&lt;T, object&gt; function)\n{\n var result = new StringBuilder();\n\n foreach (var item in self) result.Append(function(item));\n\n return result.ToString();\n}\n\npublic static string Join&lt;T&gt;(this IEnumerable&lt;T&gt; self, string separator)\n{\n return String.Join(separator, values: self.ToArray());\n}\n</code></pre>\n" }, { "answer_id": 4714651, "author": "Shaul Behr", "author_id": 7850, "author_profile": "https://Stackoverflow.com/users/7850", "pm_score": 2, "selected": false, "text": "<p>I thought I'd seen this somewhere before, but couldn't find it suggested anywhere here. MS has a TryGetValue function on the IDictionary interface, but it returns a bool and gives the value in an <code>out</code> parameter, so here's a simpler, cleaner implementation:</p>\n\n<pre><code>public static TVal GetValueOrDefault&lt;TKey, TVal&gt;(this IDictionary&lt;TKey, TVal&gt; d, TKey key) {\n if (d.ContainsKey(key))\n return d[key];\n return default(TVal);\n}\n</code></pre>\n" }, { "answer_id": 4723915, "author": "HuseyinUslu", "author_id": 170181, "author_profile": "https://Stackoverflow.com/users/170181", "pm_score": 2, "selected": false, "text": "<p>Here's another control-extension i've been using though i don't know if it's posted here before.</p>\n\n<pre><code>public static class ControlExtensions\n{\n public static void DoubleBuffer(this Control control) \n {\n // http://stackoverflow.com/questions/76993/how-to-double-buffer-net-controls-on-a-form/77233#77233\n // Taxes: Remote Desktop Connection and painting: http://blogs.msdn.com/oldnewthing/archive/2006/01/03/508694.aspx\n\n if (System.Windows.Forms.SystemInformation.TerminalServerSession) return;\n System.Reflection.PropertyInfo dbProp = typeof(System.Windows.Forms.Control).GetProperty(\"DoubleBuffered\", System.Reflection.BindingFlags.NonPublic | System.Reflection.BindingFlags.Instance);\n dbProp.SetValue(control, true, null);\n }\n}\n</code></pre>\n\n<p>usage:</p>\n\n<pre><code>this.someControl.DoubleBuffer();\n</code></pre>\n" }, { "answer_id": 4838802, "author": "Steve Potter", "author_id": 574723, "author_profile": "https://Stackoverflow.com/users/574723", "pm_score": 2, "selected": false, "text": "<p>I created a nice Each extension that has the same behavior as jQuery's each function.</p>\n\n<p>It allows something like below, where you can get the index of the current value and break out of the loop by returning false:</p>\n\n<pre><code>new[] { \"first\", \"second\", \"third\" }.Each((value, index) =&gt;\n{\n if (value.Contains(\"d\"))\n return false;\n Console.Write(value);\n return true;\n});\n</code></pre>\n\n<p>Here's the code</p>\n\n<pre><code>/// &lt;summary&gt;\n/// Generic iterator function that is useful to replace a foreach loop with at your discretion. A provided action is performed on each element.\n/// &lt;/summary&gt;\n/// &lt;typeparam name=\"T\"&gt;&lt;/typeparam&gt;\n/// &lt;param name=\"source\"&gt;&lt;/param&gt;\n/// &lt;param name=\"action\"&gt;Function that takes in the current value in the sequence. \n/// &lt;returns&gt;&lt;/returns&gt;\npublic static IEnumerable&lt;T&gt; Each&lt;T&gt;(this IEnumerable&lt;T&gt; source, Action&lt;T&gt; action)\n{\n return source.Each((value, index) =&gt;\n {\n action(value);\n return true;\n });\n}\n\n\n/// &lt;summary&gt;\n/// Generic iterator function that is useful to replace a foreach loop with at your discretion. A provided action is performed on each element.\n/// &lt;/summary&gt;\n/// &lt;typeparam name=\"T\"&gt;&lt;/typeparam&gt;\n/// &lt;param name=\"source\"&gt;&lt;/param&gt;\n/// &lt;param name=\"action\"&gt;Function that takes in the current value and its index in the sequence. \n/// &lt;returns&gt;&lt;/returns&gt;\npublic static IEnumerable&lt;T&gt; Each&lt;T&gt;(this IEnumerable&lt;T&gt; source, Action&lt;T, int&gt; action)\n{\n return source.Each((value, index) =&gt;\n {\n action(value, index);\n return true;\n });\n}\n\n/// &lt;summary&gt;\n/// Generic iterator function that is useful to replace a foreach loop with at your discretion. A provided action is performed on each element.\n/// &lt;/summary&gt;\n/// &lt;typeparam name=\"T\"&gt;&lt;/typeparam&gt;\n/// &lt;param name=\"source\"&gt;&lt;/param&gt;\n/// &lt;param name=\"action\"&gt;Function that takes in the current value in the sequence. Returns a value indicating whether the iteration should continue. So return false if you don't want to iterate anymore.&lt;/param&gt;\n/// &lt;returns&gt;&lt;/returns&gt;\npublic static IEnumerable&lt;T&gt; Each&lt;T&gt;(this IEnumerable&lt;T&gt; source, Func&lt;T, bool&gt; action)\n{\n return source.Each((value, index) =&gt;\n {\n return action(value);\n });\n}\n\n/// &lt;summary&gt;\n/// Generic iterator function that is useful to replace a foreach loop with at your discretion. A provided action is performed on each element.\n/// &lt;/summary&gt;\n/// &lt;typeparam name=\"T\"&gt;&lt;/typeparam&gt;\n/// &lt;param name=\"source\"&gt;&lt;/param&gt;\n/// &lt;param name=\"action\"&gt;Function that takes in the current value and its index in the sequence. Returns a value indicating whether the iteration should continue. So return false if you don't want to iterate anymore.&lt;/param&gt;\n/// &lt;returns&gt;&lt;/returns&gt;\npublic static IEnumerable&lt;T&gt; Each&lt;T&gt;(this IEnumerable&lt;T&gt; source, Func&lt;T, int, bool&gt; action)\n{\n if (source == null)\n return source;\n\n int index = 0;\n foreach (var sourceItem in source)\n {\n if (!action(sourceItem, index))\n break;\n index++;\n }\n return source;\n}\n</code></pre>\n" }, { "answer_id": 5569514, "author": "fre0n", "author_id": 252004, "author_profile": "https://Stackoverflow.com/users/252004", "pm_score": 0, "selected": false, "text": "<p>Compare the equality of two objects without (necessarily) overriding Equals or implementing IEquatable&lt;>.</p>\n\n<p>Why would you want to do this? When you really want to know if two objects are equal, but you're too lazy to override <code>Equals(object)</code> or implement <code>IEquatable&lt;T&gt;</code>. Or, more realistically, if you have a terribly complex class and implementing Equals by hand would be extremely tedious, error prone, and not fun to maintain. It also helps if you don't care too much about performance.</p>\n\n<p>I am currently using <code>IsEqualTo</code> because of the second reason - I have a class with many properties whose types are other user-defined classes, each of which has many other properties whose types are other user-defined classes, ad infinitum. Throw in a bunch of collections in many of these classes, and implementing <code>Equals(object)</code> truly becomes a nightmare.</p>\n\n<p>Usage:</p>\n\n<pre><code>if (myTerriblyComplexObject.IsEqualTo(myOtherTerriblyComplexObject))\n{\n // Do something terribly interesting.\n}\n</code></pre>\n\n<p>In order to determine equality, I make numerous comparisons. I make every attempt to do the \"right\" one in the \"right\" order. The comparisons, in order are:</p>\n\n<ol>\n<li>Use the static <code>Equals(object, object)</code> method. If it returns true, return true. It will return true if the references are the same. It will also return true if <code>thisObject</code> overrides <code>Equals(object)</code>.</li>\n<li>If <code>thisObject</code> is null, return false. No further comparisons can be made if it is null.</li>\n<li>If <code>thisObject</code> has overridden <code>Equals(object)</code>, return false. Since it overrides Equals, it must mean that Equals was executed at step #1 and returned false. If someone has bothered to override Equals, we should respect that and return what Equals returns.</li>\n<li>If <code>thisObject</code> inherits from <code>IEquatable&lt;T&gt;</code>, where <code>otherObject</code> can be assigned to <code>T</code>, get the <code>Equals(T)</code> method using reflection. Invoke that method and return its return value.</li>\n<li>If both objects are <code>IEnumerable</code>, return whether contain the same items, in the same order, using IsEqualTo to compare the items.</li>\n<li>If the objects have different types, return false. Since we know now that <code>thisObject</code> does not have an Equals method, there isn't any way to realistically evaluate two object of different types to be true.</li>\n<li>If the objects are a value type (primitive or struct) or a string, return false. We have already failed the <code>Equals(object)</code> test - enough said.</li>\n<li>For each property of <code>thisObject</code>, test its value with IsEqualTo. If any return false, return false. If all return true, return true.</li>\n</ol>\n\n<p>String comparisons could be better, but easy to implement. Also, I'm not 100% sure I'm handling structs right.</p>\n\n<p>Without further ado, here is the extension method:</p>\n\n<pre><code>/// &lt;summary&gt;\n/// Provides extension methods to determine if objects are equal.\n/// &lt;/summary&gt;\npublic static class EqualsEx\n{\n /// &lt;summary&gt;\n /// The &lt;see cref=\"Type\"/&gt; of &lt;see cref=\"string\"/&gt;.\n /// &lt;/summary&gt;\n private static readonly Type StringType = typeof(string);\n\n /// &lt;summary&gt;\n /// The &lt;see cref=\"Type\"/&gt; of &lt;see cref=\"object\"/&gt;.\n /// &lt;/summary&gt;\n private static readonly Type ObjectType = typeof(object);\n\n /// &lt;summary&gt;\n /// The &lt;see cref=\"Type\"/&gt; of &lt;see cref=\"IEquatable{T}\"/&gt;.\n /// &lt;/summary&gt;\n private static readonly Type EquatableType = typeof(IEquatable&lt;&gt;);\n\n /// &lt;summary&gt;\n /// Determines whether &lt;paramref name=\"thisObject\"/&gt; is equal to &lt;paramref name=\"otherObject\"/&gt;.\n /// &lt;/summary&gt;\n /// &lt;param name=\"thisObject\"&gt;\n /// This object.\n /// &lt;/param&gt;\n /// &lt;param name=\"otherObject\"&gt;\n /// The other object.\n /// &lt;/param&gt;\n /// &lt;returns&gt;\n /// True, if they are equal, otherwise false.\n /// &lt;/returns&gt;\n public static bool IsEqualTo(this object thisObject, object otherObject)\n {\n if (Equals(thisObject, otherObject))\n {\n // Always check Equals first. If the object has overridden Equals, use it. This will also capture the case where both are the same reference.\n return true;\n }\n\n if (thisObject == null)\n {\n // Because Equals(object, object) returns true if both are null, if either is null, return false.\n return false;\n }\n\n var thisObjectType = thisObject.GetType();\n var equalsMethod = thisObjectType.GetMethod(\"Equals\", BindingFlags.Public | BindingFlags.Instance, null, new[] { ObjectType }, null);\n if (equalsMethod.DeclaringType == thisObjectType)\n {\n // thisObject overrides Equals, and we have already failed the Equals test, so return false.\n return false;\n }\n\n var otherObjectType = otherObject == null ? null : otherObject.GetType();\n\n // If thisObject inherits from IEquatable&lt;&gt;, and otherObject can be passed into its Equals method, use it.\n var equatableTypes = thisObjectType.GetInterfaces().Where( // Get interfaces of thisObjectType that...\n i =&gt; i.IsGenericType // ...are generic...\n &amp;&amp; i.GetGenericTypeDefinition() == EquatableType // ...and are IEquatable of some type...\n &amp;&amp; (otherObjectType == null || i.GetGenericArguments()[0].IsAssignableFrom(otherObjectType))); // ...and otherObjectType can be assigned to the IEquatable's type.\n\n if (equatableTypes.Any())\n {\n // If we found any interfaces that meed our criteria, invoke the Equals method for each interface.\n // If any return true, return true. If all return false, return false.\n return equatableTypes\n .Select(equatableType =&gt; equatableType.GetMethod(\"Equals\", BindingFlags.Public | BindingFlags.Instance))\n .Any(equatableEqualsMethod =&gt; (bool)equatableEqualsMethod.Invoke(thisObject, new[] { otherObject }));\n }\n\n if (thisObjectType != StringType &amp;&amp; thisObject is IEnumerable &amp;&amp; otherObject is IEnumerable)\n {\n // If both are IEnumerable, check their items.\n var thisEnumerable = ((IEnumerable)thisObject).Cast&lt;object&gt;();\n var otherEnumerable = ((IEnumerable)otherObject).Cast&lt;object&gt;();\n\n return thisEnumerable.SequenceEqual(otherEnumerable, IsEqualToComparer.Instance);\n }\n\n if (thisObjectType != otherObjectType)\n {\n // If they have different types, they cannot be equal.\n return false;\n }\n\n if (thisObjectType.IsValueType || thisObjectType == StringType)\n {\n // If it is a value type, we have already determined that they are not equal, so return false.\n return false;\n }\n\n // Recurse into each public property: if any are not equal, return false. If all are true, return true.\n return !(from propertyInfo in thisObjectType.GetProperties()\n let thisPropertyValue = propertyInfo.GetValue(thisObject, null)\n let otherPropertyValue = propertyInfo.GetValue(otherObject, null)\n where !thisPropertyValue.IsEqualTo(otherPropertyValue)\n select thisPropertyValue).Any();\n }\n\n /// &lt;summary&gt;\n /// A &lt;see cref=\"IEqualityComparer{T}\"/&gt; to be used when comparing sequences of collections.\n /// &lt;/summary&gt;\n private class IsEqualToComparer : IEqualityComparer&lt;object&gt;\n {\n /// &lt;summary&gt;\n /// The singleton instance of &lt;see cref=\"IsEqualToComparer\"/&gt;.\n /// &lt;/summary&gt;\n public static readonly IsEqualToComparer Instance;\n\n /// &lt;summary&gt;\n /// Initializes static members of the &lt;see cref=\"EqualsEx.IsEqualToComparer\"/&gt; class.\n /// &lt;/summary&gt;\n static IsEqualToComparer()\n {\n Instance = new IsEqualToComparer();\n }\n\n /// &lt;summary&gt;\n /// Prevents a default instance of the &lt;see cref=\"EqualsEx.IsEqualToComparer\"/&gt; class from being created.\n /// &lt;/summary&gt;\n private IsEqualToComparer()\n {\n }\n\n /// &lt;summary&gt;\n /// Determines whether the specified objects are equal.\n /// &lt;/summary&gt;\n /// &lt;param name=\"x\"&gt;\n /// The first object to compare.\n /// &lt;/param&gt;\n /// &lt;param name=\"y\"&gt;\n /// The second object to compare.\n /// &lt;/param&gt;\n /// &lt;returns&gt;\n /// true if the specified objects are equal; otherwise, false.\n /// &lt;/returns&gt;\n bool IEqualityComparer&lt;object&gt;.Equals(object x, object y)\n {\n return x.IsEqualTo(y);\n }\n\n /// &lt;summary&gt;\n /// Not implemented - throws an &lt;see cref=\"NotImplementedException\"/&gt;.\n /// &lt;/summary&gt;\n /// &lt;param name=\"obj\"&gt;\n /// The &lt;see cref=\"object\"/&gt; for which a hash code is to be returned.\n /// &lt;/param&gt;\n /// &lt;returns&gt;\n /// A hash code for the specified object.\n /// &lt;/returns&gt;\n int IEqualityComparer&lt;object&gt;.GetHashCode(object obj)\n {\n throw new NotImplementedException();\n }\n }\n}\n</code></pre>\n" }, { "answer_id": 5709002, "author": "Amy B", "author_id": 8155, "author_profile": "https://Stackoverflow.com/users/8155", "pm_score": 0, "selected": false, "text": "<p>Sql server has a limit of ~2000 parameters, which is a pain if you have 10k Ids and want the records connected with them. I wrote these methods which accept batched lists of ids and are called like this:</p>\n\n<pre><code>List&lt;Order&gt; orders = dataContext.Orders.FetchByIds(\n orderIdChunks,\n list =&gt; row =&gt; list.Contains(row.OrderId)\n);\n\nList&lt;Customer&gt; customers = dataContext.Orders.FetchByIds(\n orderIdChunks,\n list =&gt; row =&gt; list.Contains(row.OrderId),\n row =&gt; row.Customer\n);\n\npublic static List&lt;ResultType&gt; FetchByIds&lt;RecordType, ResultType&gt;(\n this IQueryable&lt;RecordType&gt; querySource,\n List&lt;List&lt;int&gt;&gt; IdChunks,\n Func&lt;List&lt;int&gt;, Expression&lt;Func&lt;RecordType, bool&gt;&gt;&gt; filterExpressionGenerator,\n Expression&lt;Func&lt;RecordType, ResultType&gt;&gt; projectionExpression\n ) where RecordType : class\n{\n List&lt;ResultType&gt; result = new List&lt;ResultType&gt;();\n foreach (List&lt;int&gt; chunk in IdChunks)\n {\n Expression&lt;Func&lt;RecordType, bool&gt;&gt; filterExpression =\n filterExpressionGenerator(chunk);\n\n IQueryable&lt;ResultType&gt; query = querySource\n .Where(filterExpression)\n .Select(projectionExpression);\n\n List&lt;ResultType&gt; rows = query.ToList();\n result.AddRange(rows);\n }\n\n return result;\n}\n\npublic static List&lt;RecordType&gt; FetchByIds&lt;RecordType&gt;(\n this IQueryable&lt;RecordType&gt; querySource,\n List&lt;List&lt;int&gt;&gt; IdChunks,\n Func&lt;List&lt;int&gt;, Expression&lt;Func&lt;RecordType, bool&gt;&gt;&gt; filterExpressionGenerator\n ) where RecordType : class\n{\n Expression&lt;Func&lt;RecordType, RecordType&gt;&gt; identity = r =&gt; r;\n\n return FetchByIds(\n querySource,\n IdChunks,\n filterExpressionGenerator,\n identity\n );\n}\n</code></pre>\n" }, { "answer_id": 5751106, "author": "Chuck Savage", "author_id": 353147, "author_profile": "https://Stackoverflow.com/users/353147", "pm_score": 2, "selected": false, "text": "<p>I've been looking for a way to contribute back to the community some of the things I've developed. </p>\n\n<p>Here's some FileInfo extensions that I find quite useful.</p>\n\n<pre><code>/// &lt;summary&gt;\n/// Open with default 'open' program\n/// &lt;/summary&gt;\n/// &lt;param name=\"value\"&gt;&lt;/param&gt;\npublic static Process Open(this FileInfo value)\n{\n if (!value.Exists)\n throw new FileNotFoundException(\"File doesn't exist\");\n Process p = new Process();\n p.StartInfo.FileName = value.FullName;\n p.StartInfo.Verb = \"Open\";\n p.Start();\n return p;\n}\n\n/// &lt;summary&gt;\n/// Print the file\n/// &lt;/summary&gt;\n/// &lt;param name=\"value\"&gt;&lt;/param&gt;\npublic static void Print(this FileInfo value)\n{\n if (!value.Exists)\n throw new FileNotFoundException(\"File doesn't exist\");\n Process p = new Process();\n p.StartInfo.FileName = value.FullName;\n p.StartInfo.Verb = \"Print\";\n p.Start();\n}\n\n/// &lt;summary&gt;\n/// Send this file to the Recycle Bin\n/// &lt;/summary&gt;\n/// &lt;exception cref=\"File doesn't exist\" /&gt;\n/// &lt;param name=\"value\"&gt;&lt;/param&gt;\npublic static void Recycle(this FileInfo value)\n{ \n value.Recycle(false);\n}\n\n/// &lt;summary&gt;\n/// Send this file to the Recycle Bin\n/// On show, if person refuses to send file to the recycle bin, \n/// exception is thrown or otherwise delete fails\n/// &lt;/summary&gt;\n/// &lt;exception cref=\"File doesn't exist\" /&gt;\n/// &lt;exception cref=\"On show, if user refuses, throws exception 'The operation was canceled.'\" /&gt;\n/// &lt;param name=\"value\"&gt;File being recycled&lt;/param&gt;\n/// &lt;param name=\"showDialog\"&gt;true to show pop-up&lt;/param&gt;\npublic static void Recycle(this FileInfo value, bool showDialog)\n{\n if (!value.Exists)\n throw new FileNotFoundException(\"File doesn't exist\");\n if( showDialog )\n FileSystem.DeleteFile\n (value.FullName, UIOption.AllDialogs, \n RecycleOption.SendToRecycleBin);\n else\n FileSystem.DeleteFile\n (value.FullName, UIOption.OnlyErrorDialogs, \n RecycleOption.SendToRecycleBin);\n}\n</code></pre>\n\n<p><strong>Open any file in the user's favorite editor:</strong></p>\n\n<pre><code>new FileInfo(\"C:\\image.jpg\").Open();\n</code></pre>\n\n<p><strong>Print any file that the operating system knows how to print:</strong></p>\n\n<pre><code>new FileInfo(\"C:\\image.jpg\").Print();\n</code></pre>\n\n<p><strong>Send any file to the recycle bin:</strong></p>\n\n<ol>\n<li>You have to include the <code>Microsoft.VisualBasic</code> reference</li>\n<li>use the <code>using Microsoft.VisualBasic.FileIO;</code></li>\n</ol>\n\n<p>Example:</p>\n\n<pre><code>new FileInfo(\"C:\\image.jpg\").Recycle();\n</code></pre>\n\n<p>Or</p>\n\n<pre><code>// let user have a chance to cancel send to recycle bin.\nnew FileInfo(\"C:\\image.jpg\").Recycle(true);\n</code></pre>\n" }, { "answer_id": 5913908, "author": "John", "author_id": 83091, "author_profile": "https://Stackoverflow.com/users/83091", "pm_score": 0, "selected": false, "text": "<p>We have a deployment tool to deploy between environments. Since the files could be marked as modified but not actually different I came up with this:</p>\n\n<pre><code>/// &lt;summary&gt;\n/// Compares the files to see if they are different. \n/// First checks file size\n/// Then modified if the file is larger than the specified size\n/// Then compares the bytes\n/// &lt;/summary&gt;\n/// &lt;param name=\"file1\"&gt;The source file&lt;/param&gt;\n/// &lt;param name=\"file2\"&gt;The destination file&lt;/param&gt;\n/// &lt;param name=\"mb\"&gt;Skip the smart check if the file is larger than this many megabytes. Default is 10.&lt;/param&gt;\n/// &lt;returns&gt;&lt;/returns&gt;\npublic static bool IsDifferentThan(this FileInfo file1, FileInfo file2, int mb = 10)\n{\n var ret = false;\n\n // different size is a different file\n if(file1.Length != file2.Length) return true;\n\n // if the file times are different and the file is bigger than 10mb flag it for updating\n if(file1.LastWriteTimeUtc &gt; file2.LastWriteTimeUtc &amp;&amp; file1.Length &gt; ((mb*1024)*1024)) return true;\n\n var f1 = File.ReadAllBytes(file1.FullName);\n var f2 = File.ReadAllBytes(file2.FullName);\n\n // loop through backwards because if they are different\n // it is more likely that the last few bytes will be different\n // than the first few\n for(var i = file1.Length - 1; i &gt; 0; i--)\n {\n if(f1[i] != f2[i])\n {\n ret = true;\n break;\n }\n }\n\n return ret;\n}\n</code></pre>\n" }, { "answer_id": 6031710, "author": "takrl", "author_id": 520044, "author_profile": "https://Stackoverflow.com/users/520044", "pm_score": 2, "selected": false, "text": "<p>Two color extensions I use, mostly for control development:</p>\n\n<pre><code>public static class ColorExtensions\n{\n // Gets a color that will be readable on top of a given background color\n public static Color GetForegroundColor(this Color input)\n {\n // Math taken from one of the replies to\n // http://stackoverflow.com/questions/2241447/make-foregroundcolor-black-or-white-depending-on-background\n if (Math.Sqrt(input.R * input.R * .241 + input.G * input.G * .691 + input.B * input.B * .068) &gt; 128)\n return Color.Black;\n else\n return Color.White;\n }\n\n // Converts a given Color to gray\n public static Color ToGray(this Color input)\n {\n int g = (int)(input.R * .299) + (int)(input.G * .587) + (int)(input.B * .114);\n return Color.FromArgb(input.A, g, g, g);\n }\n}\n</code></pre>\n\n<p>Usage:</p>\n\n<pre><code>Color foreColor = someBackColor.GetForegroundColor();\nColor grayColor = someBackColor.ToGray();\n</code></pre>\n" }, { "answer_id": 6038212, "author": "Gleno", "author_id": 427673, "author_profile": "https://Stackoverflow.com/users/427673", "pm_score": 1, "selected": false, "text": "<p>Use reflection to find the TryParse method and invoke it upon string target. The optional parameter specifies what should be returned if the conversion fails. I find this method quite useful, most of the time. Well aware of the <code>Convert.ChangeType</code> option, but I find this more useful what with the default result handy and whatnot. Note that the found methods are kept in a dictionary, although I do suspect that boxing ultimately slows this down a bit. </p>\n\n<p>This method is my favorite, because it legitimately uses a lot of language features.</p>\n\n<pre><code>private static readonly Dictionary&lt;Type, MethodInfo&gt; Parsers = new Dictionary&lt;Type, MethodInfo&gt;();\n\npublic static T Parse&lt;T&gt;(this string value, T defaultValue = default(T))\n{\n if (string.IsNullOrEmpty(value)) return defaultValue;\n\n if (!Parsers.ContainsKey(typeof(T)))\n Parsers[typeof (T)] = typeof (T).GetMethods(BindingFlags.Public | BindingFlags.Static)\n .Where(mi =&gt; mi.Name == \"TryParse\")\n .Single(mi =&gt;\n {\n var parameters = mi.GetParameters();\n if (parameters.Length != 2) return false;\n return parameters[0].ParameterType == typeof (string) &amp;&amp;\n parameters[1].ParameterType == typeof (T).MakeByRefType();\n });\n\n var @params = new object[] {value, default(T)};\n return (bool) Parsers[typeof (T)].Invoke(null, @params) ?\n (T) @params[1] : defaultValue;\n}\n</code></pre>\n\n<p>Usage:</p>\n\n<pre><code>var hundredTwentyThree = \"123\".Parse(0);\nvar badnumber = \"test\".Parse(-1);\nvar date = \"01/01/01\".Parse&lt;DateTime&gt;();\n</code></pre>\n" }, { "answer_id": 7089538, "author": "NeverFade", "author_id": 604351, "author_profile": "https://Stackoverflow.com/users/604351", "pm_score": 0, "selected": false, "text": "<p>If you have persian language and must show the numbers to users in persian language:</p>\n\n<pre><code>static public string ToFaString (this string value)\n {\n // 1728 , 1584\n string result = \"\";\n if (value != null)\n {\n char[] resChar = value.ToCharArray();\n for (int i = 0; i &lt; resChar.Length; i++)\n {\n if (resChar[i] &gt;= '0' &amp;&amp; resChar[i] &lt;= '9')\n result += (char)(resChar[i] + 1728);\n else\n result += resChar[i];\n }\n }\n return result;\n }\n</code></pre>\n" }, { "answer_id": 7089576, "author": "NeverFade", "author_id": 604351, "author_profile": "https://Stackoverflow.com/users/604351", "pm_score": 0, "selected": false, "text": "<p>If you need for check your string for Is All char is 0 :</p>\n\n<pre><code> static public bool IsAllZero (this string input)\n {\n if(string.IsNullOrEmpty(input))\n return true;\n foreach (char ch in input)\n {\n if(ch != '0')\n return false;\n }\n return true;\n }\n</code></pre>\n" }, { "answer_id": 7201703, "author": "sasjaq", "author_id": 913610, "author_profile": "https://Stackoverflow.com/users/913610", "pm_score": 1, "selected": false, "text": "<p>There is somethimes need to have instance of class no matter if valid but not null</p>\n\n<pre><code>public static T Safe&lt;T&gt;(this T obj) where T : new()\n{\n if (obj == null)\n {\n obj = new T();\n }\n\n return obj;\n}\n</code></pre>\n\n<p>usage will be like:</p>\n\n<pre><code>MyClass myClass = Provider.GetSomeResult();\nstring temp = myClass.Safe().SomeValue;\n</code></pre>\n\n<p>instead of:</p>\n\n<pre><code>MyClass myClass = Provider.GetSomeResult();\nstring temp = \"some default value\";\nif (myClass != null)\n{\n temp = myClass.SomeValue;\n}\n</code></pre>\n\n<p>sorry if it is a duplicity, but I dont find it.</p>\n" }, { "answer_id": 7201807, "author": "sasjaq", "author_id": 913610, "author_profile": "https://Stackoverflow.com/users/913610", "pm_score": 0, "selected": false, "text": "<p>on serializing and configs there is better using long as DateTime, so:</p>\n\n<pre><code> public static readonly DateTime Epoch = new DateTime(1970, 1, 1, 0, 0, 0);\n\n public static long ToUnixTimestamp(this DateTime dateTime)\n {\n return (long) (dateTime - Epoch).TotalSeconds;\n }\n\n public static long ToUnixUltraTimestamp(this DateTime dateTime)\n {\n return (long) (dateTime - Epoch).TotalMilliseconds;\n }\n</code></pre>\n\n<p>and backwards</p>\n\n<pre><code> public static DateTime ToDateTime(this long unixDateTime)\n {\n return Epoch.AddSeconds(unixDateTime);\n }\n\n public static DateTime ToDateTimeUltra(this long unixUltraDateTime)\n {\n return Epoch.AddMilliseconds(unixUltraDateTime);\n }\n</code></pre>\n" }, { "answer_id": 7926954, "author": "Otiel", "author_id": 825024, "author_profile": "https://Stackoverflow.com/users/825024", "pm_score": 2, "selected": false, "text": "<p>In .NET, there is a <a href=\"http://msdn.microsoft.com/en-us/library/k8b1470s.aspx\" rel=\"nofollow\"><code>IndexOf</code></a> and a <a href=\"http://msdn.microsoft.com/en-us/library/1wdsy8fy.aspx\" rel=\"nofollow\"><code>LastIndexOf</code></a> methods that return the index of the first and the last occurrence of a match in a <code>String</code> object. I have an extension method to get the index of the nth occurrence:</p>\n\n<pre><code>public static partial class StringExtensions {\n\n public static int NthIndexOf(this String str, String match, int occurrence) {\n int i = 1;\n int index = 0;\n\n while (i &lt;= occurrence &amp;&amp; \n ( index = str.IndexOf(match, index + 1) ) != -1) {\n\n if (i == occurrence) {\n // Occurrence match found!\n return index;\n }\n i++;\n }\n\n // Match not found\n return -1;\n }\n}\n</code></pre>\n" }, { "answer_id": 8068261, "author": "jaekie", "author_id": 1398964, "author_profile": "https://Stackoverflow.com/users/1398964", "pm_score": 1, "selected": false, "text": "<p>I haven't seen any answer with this one yet...</p>\n\n<pre><code>public static string[] Split(this string value, string regexPattern)\n{\n return value.Split(regexPattern, RegexOptions.None);\n}\n\npublic static string[] Split(this string value, string regexPattern, \n RegexOptions options)\n{\n return Regex.Split(value, regexPattern, options);\n}\n</code></pre>\n\n<p>Usage:</p>\n\n<pre><code>var obj = \"test1,test2,test3\";\nstring[] arrays = obj.Split(\",\");\n</code></pre>\n" }, { "answer_id": 8472175, "author": "Otiel", "author_id": 825024, "author_profile": "https://Stackoverflow.com/users/825024", "pm_score": 2, "selected": false, "text": "<p>Used in <em>winforms</em> to fill a comboBox:</p>\n\n<pre><code>List&lt;MyObject&gt; myObjects = new List&lt;MyObject&gt;() { \n new MyObject() {Name = \"a\", Id = 0}, \n new MyObject() {Name = \"b\", Id = 1}, \n new MyObject() {Name = \"c\", Id = 2} }\ncomboBox.FillDataSource&lt;MyObject&gt;(myObjects, x =&gt; x.Name);\n</code></pre>\n\n<p>The extension method:</p>\n\n<pre><code>/** &lt;summary&gt;Fills the System.Windows.Forms.ComboBox object DataSource with a \n * list of T objects.&lt;/summary&gt;\n * &lt;param name=\"values\"&gt;The list of T objects.&lt;/param&gt;\n * &lt;param name=\"displayedValue\"&gt;A function to apply to each element to get the \n * display value.&lt;/param&gt;\n */\npublic static void FillDataSource&lt;T&gt;(this ComboBox comboBox, List&lt;T&gt; values,\n Func&lt;T, String&gt; displayedValue) {\n\n // Create dataTable\n DataTable data = new DataTable();\n data.Columns.Add(\"ValueMember\", typeof(T));\n data.Columns.Add(\"DisplayMember\");\n\n for (int i = 0; i &lt; values.Count; i++) {\n // For each value/displayed value\n\n // Create new row with value &amp; displayed value\n DataRow dr = data.NewRow();\n dr[\"ValueMember\"] = values[i];\n dr[\"DisplayMember\"] = displayedValue(values[i]) ?? \"\";\n // Add row to the dataTable\n data.Rows.Add(dr);\n }\n\n // Bind datasource to the comboBox\n comboBox.DataSource = data;\n comboBox.ValueMember = \"ValueMember\";\n comboBox.DisplayMember = \"DisplayMember\";\n}\n</code></pre>\n" }, { "answer_id": 9593534, "author": "jerone", "author_id": 108448, "author_profile": "https://Stackoverflow.com/users/108448", "pm_score": 0, "selected": false, "text": "<p>I use the following extensions to extend all collections (maybe someone find these useful):</p>\n\n<pre><code>/// &lt;summary&gt;\n/// Collection Helper\n/// &lt;/summary&gt;\n/// &lt;remarks&gt;\n/// Use IEnumerable by default, but when altering or getting item at index use IList.\n/// &lt;/remarks&gt;\npublic static class CollectionHelper\n{\n\n #region Alter;\n\n /// &lt;summary&gt;\n /// Swap item to another place\n /// &lt;/summary&gt;\n /// &lt;typeparam name=\"T\"&gt;Collection type&lt;/typeparam&gt;\n /// &lt;param name=\"this\"&gt;Collection&lt;/param&gt;\n /// &lt;param name=\"IndexA\"&gt;Index a&lt;/param&gt;\n /// &lt;param name=\"IndexB\"&gt;Index b&lt;/param&gt;\n /// &lt;returns&gt;New collection&lt;/returns&gt;\n public static IList&lt;T&gt; Swap&lt;T&gt;(this IList&lt;T&gt; @this, Int32 IndexA, Int32 IndexB)\n {\n T Temp = @this[IndexA];\n @this[IndexA] = @this[IndexB];\n @this[IndexB] = Temp;\n return @this;\n }\n\n /// &lt;summary&gt;\n /// Swap item to the left\n /// &lt;/summary&gt;\n /// &lt;typeparam name=\"T\"&gt;Collection type&lt;/typeparam&gt;\n /// &lt;param name=\"this\"&gt;Collection&lt;/param&gt;\n /// &lt;param name=\"Index\"&gt;Index&lt;/param&gt;\n /// &lt;returns&gt;New collection&lt;/returns&gt;\n public static IList&lt;T&gt; SwapLeft&lt;T&gt;(this IList&lt;T&gt; @this, Int32 Index)\n {\n return @this.Swap(Index, Index - 1);\n }\n\n /// &lt;summary&gt;\n /// Swap item to the right\n /// &lt;/summary&gt;\n /// &lt;typeparam name=\"T\"&gt;Collection type&lt;/typeparam&gt;\n /// &lt;param name=\"this\"&gt;Collection&lt;/param&gt;\n /// &lt;param name=\"Index\"&gt;Index&lt;/param&gt;\n /// &lt;returns&gt;New collection&lt;/returns&gt;\n public static IList&lt;T&gt; SwapRight&lt;T&gt;(this IList&lt;T&gt; @this, Int32 Index)\n {\n return @this.Swap(Index, Index + 1);\n }\n\n #endregion Alter;\n\n #region Action;\n\n /// &lt;summary&gt;\n /// Execute action at specified index\n /// &lt;/summary&gt;\n /// &lt;typeparam name=\"T\"&gt;Collection type&lt;/typeparam&gt;\n /// &lt;param name=\"this\"&gt;Collection&lt;/param&gt;\n /// &lt;param name=\"Index\"&gt;Index&lt;/param&gt;\n /// &lt;param name=\"ActionAt\"&gt;Action to execute&lt;/param&gt;\n /// &lt;returns&gt;New collection&lt;/returns&gt;\n public static IList&lt;T&gt; ActionAt&lt;T&gt;(this IList&lt;T&gt; @this, Int32 Index, Action&lt;T&gt; ActionAt)\n {\n ActionAt(@this[Index]);\n return @this;\n }\n\n #endregion Action;\n\n #region Randomize;\n\n /// &lt;summary&gt;\n /// Take random items\n /// &lt;/summary&gt;\n /// &lt;typeparam name=\"T\"&gt;Collection type&lt;/typeparam&gt;\n /// &lt;param name=\"this\"&gt;Collection&lt;/param&gt;\n /// &lt;param name=\"Count\"&gt;Number of items to take&lt;/param&gt;\n /// &lt;returns&gt;New collection&lt;/returns&gt;\n public static IEnumerable&lt;T&gt; TakeRandom&lt;T&gt;(this IEnumerable&lt;T&gt; @this, Int32 Count)\n {\n return @this.Shuffle().Take(Count);\n }\n\n /// &lt;summary&gt;\n /// Take random item\n /// &lt;/summary&gt;\n /// &lt;typeparam name=\"T\"&gt;Collection type&lt;/typeparam&gt;\n /// &lt;param name=\"this\"&gt;Collection&lt;/param&gt;\n /// &lt;returns&gt;Item&lt;/returns&gt;\n public static T TakeRandom&lt;T&gt;(this IEnumerable&lt;T&gt; @this)\n {\n return @this.TakeRandom(1).Single();\n }\n\n /// &lt;summary&gt;\n /// Shuffle list\n /// &lt;/summary&gt;\n /// &lt;typeparam name=\"T\"&gt;Collection type&lt;/typeparam&gt;\n /// &lt;param name=\"this\"&gt;Collection&lt;/param&gt;\n /// &lt;returns&gt;New collection&lt;/returns&gt;\n public static IEnumerable&lt;T&gt; Shuffle&lt;T&gt;(this IEnumerable&lt;T&gt; @this)\n {\n return @this.OrderBy(Item =&gt; Guid.NewGuid());\n }\n\n #endregion Randomize;\n\n #region Navigate;\n\n /// &lt;summary&gt;\n /// Get next item in collection and give first item, when last item is selected;\n /// &lt;/summary&gt;\n /// &lt;typeparam name=\"T\"&gt;Collection type&lt;/typeparam&gt;\n /// &lt;param name=\"this\"&gt;Collection&lt;/param&gt;\n /// &lt;param name=\"Index\"&gt;Index in collection&lt;/param&gt;\n /// &lt;returns&gt;Next item&lt;/returns&gt;\n public static T Next&lt;T&gt;(this IList&lt;T&gt; @this, ref Int32 Index)\n {\n Index = ++Index &gt;= 0 &amp;&amp; Index &lt; @this.Count ? Index : 0;\n return @this[Index];\n }\n\n /// &lt;summary&gt;\n /// Get previous item in collection and give last item, when first item is selected;\n /// &lt;/summary&gt;\n /// &lt;typeparam name=\"T\"&gt;Collection type&lt;/typeparam&gt;\n /// &lt;param name=\"this\"&gt;Collection&lt;/param&gt;\n /// &lt;param name=\"Index\"&gt;Index in collection&lt;/param&gt;\n /// &lt;returns&gt;Previous item&lt;/returns&gt;\n public static T Previous&lt;T&gt;(this IList&lt;T&gt; @this, ref Int32 Index)\n {\n Index = --Index &gt;= 0 &amp;&amp; Index &lt; @this.Count ? Index : @this.Count - 1;\n return @this[Index];\n }\n\n #endregion Navigate;\n\n #region Clone;\n\n /// &lt;summary&gt;\n /// \n /// &lt;/summary&gt;\n /// &lt;typeparam name=\"T\"&gt;Collection type&lt;/typeparam&gt;\n /// &lt;param name=\"this\"&gt;Collection&lt;/param&gt;\n /// &lt;returns&gt;Cloned collection&lt;/returns&gt;\n public static IEnumerable&lt;T&gt; Clone&lt;T&gt;(this IEnumerable&lt;T&gt; @this) where T : ICloneable\n {\n return @this.Select(Item =&gt; (T)Item.Clone());\n }\n\n #endregion Clone;\n\n #region String;\n\n /// &lt;summary&gt;\n /// Joins multiple string with Separator\n /// &lt;/summary&gt;\n /// &lt;param name=\"this\"&gt;Collection&lt;/param&gt;\n /// &lt;param name=\"Separator\"&gt;Separator&lt;/param&gt;\n /// &lt;returns&gt;Joined string&lt;/returns&gt;\n public static String Join(this IEnumerable&lt;String&gt; @this, String Separator = \"\")\n {\n return String.Join(Separator, @this);\n }\n\n #endregion String;\n\n}\n</code></pre>\n" }, { "answer_id": 9839800, "author": "takrl", "author_id": 520044, "author_profile": "https://Stackoverflow.com/users/520044", "pm_score": 0, "selected": false, "text": "<p>How about ...</p>\n\n<pre><code>public static bool IsWinXPOrHigher(this OperatingSystem OS)\n{\n return (OS.Platform == PlatformID.Win32NT)\n &amp;&amp; ((OS.Version.Major &gt; 5) || ((OS.Version.Major == 5) &amp;&amp; (OS.Version.Minor &gt;= 1)));\n}\n\npublic static bool IsWinVistaOrHigher(this OperatingSystem OS)\n{\n return (OS.Platform == PlatformID.Win32NT)\n &amp;&amp; (OS.Version.Major &gt;= 6);\n}\n\npublic static bool IsWin7OrHigher(this OperatingSystem OS)\n{\n return (OS.Platform == PlatformID.Win32NT)\n &amp;&amp; ((OS.Version.Major &gt; 6) || ((OS.Version.Major == 6) &amp;&amp; (OS.Version.Minor &gt;= 1)));\n}\n\npublic static bool IsWin8OrHigher(this OperatingSystem OS)\n{\n return (OS.Platform == PlatformID.Win32NT)\n &amp;&amp; ((OS.Version.Major &gt; 6) || ((OS.Version.Major == 6) &amp;&amp; (OS.Version.Minor &gt;= 2)));\n}\n</code></pre>\n\n<p>Usage:</p>\n\n<pre><code>if (Environment.OSVersion.IsWinXPOrHigher())\n{\n // do stuff\n}\n\nif (Environment.OSVersion.IsWinVistaOrHigher())\n{\n // do stuff\n}\n\nif (Environment.OSVersion.IsWin7OrHigher())\n{\n // do stuff\n}\n\nif (Environment.OSVersion.IsWin8OrHigher())\n{\n // do stuff\n}\n</code></pre>\n" }, { "answer_id": 10042182, "author": "Luke Puplett", "author_id": 107783, "author_profile": "https://Stackoverflow.com/users/107783", "pm_score": 0, "selected": false, "text": "<p>Another one, this time to make UriBuilder more friendly when dealing with query params.</p>\n\n<pre><code> /// &lt;summary&gt;\n /// Adds the specified query parameter to the URI builder.\n /// &lt;/summary&gt;\n /// &lt;param name=\"builder\"&gt;The builder.&lt;/param&gt;\n /// &lt;param name=\"parameterName\"&gt;Name of the parameter.&lt;/param&gt;\n /// &lt;param name=\"value\"&gt;The URI escaped value.&lt;/param&gt;\n /// &lt;returns&gt;The final full query string.&lt;/returns&gt;\n public static string AddQueryParam(this UriBuilder builder, string parameterName, string value)\n {\n if (parameterName == null)\n throw new ArgumentNullException(\"parameterName\");\n\n if (parameterName.Length == 0)\n throw new ArgumentException(\"The parameter name is empty.\");\n\n if (value == null)\n throw new ArgumentNullException(\"value\");\n\n if (value.Length == 0)\n throw new ArgumentException(\"The value is empty.\");\n\n if (builder.Query.Length == 0)\n {\n builder.Query = String.Concat(parameterName, \"=\", value);\n }\n else if\n (builder.Query.Contains(String.Concat(\"&amp;\", parameterName, \"=\"))\n || builder.Query.Contains(String.Concat(\"?\", parameterName, \"=\")))\n {\n throw new InvalidOperationException(String.Format(\"The parameter {0} already exists.\", parameterName));\n }\n else\n {\n builder.Query = String.Concat(builder.Query.Substring(1), \"&amp;\", parameterName, \"=\", value);\n }\n\n return builder.Query;\n }\n</code></pre>\n" } ]
2008/11/07
[ "https://Stackoverflow.com/questions/271398", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11135/" ]
Let's make a list of answers where you post your excellent and favorite [extension methods](http://en.wikipedia.org/wiki/Extension_method). The requirement is that the full code must be posted and a example and an explanation on how to use it. Based on the high interest in this topic I have setup an Open Source Project called extensionoverflow on [**Codeplex**](http://www.codeplex.com/extensionoverflow). **Please mark your answers with an acceptance to put the code in the Codeplex project.** **Please post the full sourcecode and not a link.** **Codeplex News:** 24.08.2010 The Codeplex page is now here: <http://extensionoverflow.codeplex.com/> 11.11.2008 **XmlSerialize / XmlDeserialize** is now [Implemented](http://www.codeplex.com/extensionoverflow/SourceControl/FileView.aspx?itemId=284374&changeSetId=17001) and [Unit Tested](http://www.codeplex.com/extensionoverflow/SourceControl/FileView.aspx?itemId=288847&changeSetId=17001). 11.11.2008 There is still room for more developers. ;-) **Join NOW!** 11.11.2008 Third contributer joined [ExtensionOverflow](http://www.codeplex.com/extensionoverflow), welcome to [BKristensen](http://www.codeplex.com/site/users/view/BKristensen) 11.11.2008 **FormatWith** is now [Implemented](http://www.codeplex.com/extensionoverflow/SourceControl/FileView.aspx?itemId=284374&changeSetId=16839) and [Unit Tested](http://www.codeplex.com/extensionoverflow/SourceControl/FileView.aspx?itemId=288847&changeSetId=16839). 09.11.2008 Second contributer joined [ExtensionOverflow](http://www.codeplex.com/extensionoverflow). welcome to [chakrit](https://stackoverflow.com/users/3055/chakrit). 09.11.2008 We need more developers. ;-) 09.11.2008 **ThrowIfArgumentIsNull** in now [Implemented](http://www.codeplex.com/extensionoverflow/SourceControl/FileView.aspx?itemId=278942&changeSetId=16468) and [Unit Tested](http://www.codeplex.com/extensionoverflow/SourceControl/FileView.aspx?itemId=284112&changeSetId=16468) on Codeplex.
``` public static bool In<T>(this T source, params T[] list) { if(null==source) throw new ArgumentNullException("source"); return list.Contains(source); } ``` Allows me to replace: ``` if(reallyLongIntegerVariableName == 1 || reallyLongIntegerVariableName == 6 || reallyLongIntegerVariableName == 9 || reallyLongIntegerVariableName == 11) { // do something.... } and if(reallyLongStringVariableName == "string1" || reallyLongStringVariableName == "string2" || reallyLongStringVariableName == "string3") { // do something.... } and if(reallyLongMethodParameterName == SomeEnum.Value1 || reallyLongMethodParameterName == SomeEnum.Value2 || reallyLongMethodParameterName == SomeEnum.Value3 || reallyLongMethodParameterName == SomeEnum.Value4) { // do something.... } ``` With: ``` if(reallyLongIntegerVariableName.In(1,6,9,11)) { // do something.... } and if(reallyLongStringVariableName.In("string1","string2","string3")) { // do something.... } and if(reallyLongMethodParameterName.In(SomeEnum.Value1, SomeEnum.Value2, SomeEnum.Value3, SomeEnum.Value4) { // do something.... } ```
271,406
<p>I have a table in lua with some data.</p> <pre><code>sometable = { {name = "bob", something = "foo"}, {name = "greg", something = "bar"} } </code></pre> <p>I then want to loop through the table and assign a number to each name as a variable. New to lua and tried it like this.</p> <pre><code>for i,t in ipairs(sometable) do t.name = i end </code></pre> <p>I was then assuming print("name1", bob) would give me name1 = 1. Right now I'm getting nil. So I'm back to my ugly static list of variables till some kind soul tells me how I'm an idiot.</p>
[ { "answer_id": 271413, "author": "Tyler Levine", "author_id": 35339, "author_profile": "https://Stackoverflow.com/users/35339", "pm_score": -1, "selected": false, "text": "<p>The <a href=\"http://www.lua.org/manual/5.1/manual.html#5.1\" rel=\"nofollow noreferrer\">ipairs</a> function will iterate only through numerically indexed tables in ascending order.</p>\n\n<p>What you want to use is the pairs function. It will iterate over every key in the table, no matter what type it is.</p>\n" }, { "answer_id": 274107, "author": "Doug Currie", "author_id": 33252, "author_profile": "https://Stackoverflow.com/users/33252", "pm_score": 3, "selected": true, "text": "<pre class=\"lang-lua prettyprint-override\"><code>&gt; sometable = {{name = &quot;bob&quot;, something = &quot;foo&quot;},{name = &quot;greg&quot;, something = &quot;bar&quot;}}\n&gt; for i,t in ipairs(sometable) do t[t.name] = i end\n&gt; for i,t in ipairs(sometable) do for j,u in pairs (t) do print (j,u) end end \nname bob\nsomething foo\nbob 1\ngreg 2\nsomething bar\nname greg\n&gt; return sometable[1].bob\n1&gt;\n</code></pre>\n" } ]
2008/11/07
[ "https://Stackoverflow.com/questions/271406", "https://Stackoverflow.com", "https://Stackoverflow.com/users/18933/" ]
I have a table in lua with some data. ``` sometable = { {name = "bob", something = "foo"}, {name = "greg", something = "bar"} } ``` I then want to loop through the table and assign a number to each name as a variable. New to lua and tried it like this. ``` for i,t in ipairs(sometable) do t.name = i end ``` I was then assuming print("name1", bob) would give me name1 = 1. Right now I'm getting nil. So I'm back to my ugly static list of variables till some kind soul tells me how I'm an idiot.
```lua > sometable = {{name = "bob", something = "foo"},{name = "greg", something = "bar"}} > for i,t in ipairs(sometable) do t[t.name] = i end > for i,t in ipairs(sometable) do for j,u in pairs (t) do print (j,u) end end name bob something foo bob 1 greg 2 something bar name greg > return sometable[1].bob 1> ```
271,428
<hr> <p>Thanks for answers,Actually I am not puzzled about draw 1024*768 pixels is slower than 100* 100 pixels... It is so simple a logic.. Which made me puzzled is that DrawImage's interpolation algorithm may be very slow, while there exists lots of better algorithm, and its decoder seems can decode from a jpg with a certain resolution, it is really cool, I search for sometime but do not find any free lib to do this...</p> <p>It is really strange! I add the following code into on Paint method. c:\1.jpg is 5M jpg file, about 4000*3000</p> <p>//--------------------------------------------------------------</p> <pre><code>HDC hdc = pDC-&gt;GetSafeHdc(); bitmap = Bitmap::FromFile(L"c:\\1.jpg",true); Graphics graphics(hdc); graphics.SetInterpolationMode( InterpolationModeNearestNeighbor ); graphics.DrawImage(bitmap,0,0,200,200); </code></pre> <p>The above is really fast! even real time! I don't think decode a 5m JPG can be that fast!</p> <p>//--------------------------------------------------------------</p> <pre><code>HDC hdc = pDC-&gt;GetSafeHdc(); bitmap = Bitmap::FromFile(L"c:\\1.jpg",true); Graphics graphics(hdc); graphics.SetInterpolationMode( InterpolationModeNearestNeighbor ); graphics.DrawImage(bitmap,0,0,2000,2000); </code></pre> <p>The above code become really slow</p> <p>//--------------------------------------------------------------</p> <p>If I add Bitmap = Bitmap::FromFile(L"c:\1.jpg", true); // into construct</p> <p>leave </p> <pre><code> Graphics graphics(hdc); graphics.SetInterpolationMode( InterpolationModeNearestNeighbor ); graphics.DrawImage(bitmap,0,0,2000,2000); </code></pre> <p>in OnPaint method, The code is still a bit slow~~~</p> <p>//------------------------------------------------------------------</p> <p>Comparing with decoding, the drawImage Process is really slow...</p> <p>Why and How did they do that? Did Microsoft pay the men taking charge of decoder double salary than the men taking charge of writing drawingImage?</p>
[ { "answer_id": 271463, "author": "Johann Gerell", "author_id": 6345, "author_profile": "https://Stackoverflow.com/users/6345", "pm_score": 3, "selected": false, "text": "<p>So, what you're really wondering is why</p>\n\n<pre><code>graphics.DrawImage(bitmap,0,0,200,200);\n</code></pre>\n\n<p>is faster than</p>\n\n<pre><code>graphics.DrawImage(bitmap,0,0,2000,2000);\n</code></pre>\n\n<p>Correct?</p>\n\n<p>Well, the fact that you are drawing 100 times more pixels in the second case could have something to do with it.</p>\n" }, { "answer_id": 271468, "author": "chakrit", "author_id": 3055, "author_profile": "https://Stackoverflow.com/users/3055", "pm_score": 2, "selected": false, "text": "<p>It could be possible that the decoding is deferred until needed. That's why it is so fast.</p>\n\n<p>Maybe on the 200x200 case GDI+ only decodes enough blocks to paint 200x200 and on 2000x2000 they decodes more.</p>\n\n<p>Graphic routines always contains some obscure optimizations, you could never know.</p>\n\n<p>Maybe <a href=\"http://www.red-gate.com/products/reflector/\" rel=\"nofollow noreferrer\">Reflector</a> will tell you?</p>\n" }, { "answer_id": 271663, "author": "schnaader", "author_id": 34065, "author_profile": "https://Stackoverflow.com/users/34065", "pm_score": 0, "selected": false, "text": "<p>Just a guess, but could you try drawing with 4000x3000 or 2000x1500? Perhaps the fact that 4000 and 3000 are divisible by 200 is speeding up the whole and 3000 not being divisible by 200 slows it down (although this really would be weird).</p>\n\n<p>Generally, do some profiling or time measurement. If 2000x2000 is about 100 times slower than 200x200, everything is okay. And don't bother if 2000x2000 is too slow. If your screen is at 1024x768, you can't see the whole image, so you better pick the part of the image that is visible on the screen and draw it, 1024x768 is 5 times faster than 2000x2000.</p>\n" }, { "answer_id": 271703, "author": "MSalters", "author_id": 15416, "author_profile": "https://Stackoverflow.com/users/15416", "pm_score": 3, "selected": true, "text": "<p>You don't need to decode JPGs if you're scaling down by a factor of 8. JPG images consist of blocks of 8 by 8 pixels, DCT-transformed. The average value of this block is the 0,0 coefficient of the DCT. So, scaling down a factor of 8 is merely a matter of throwing away all other components. Scaling down even further (eg 4000->200) is just a matter of scaling down from 4000 to 500, and then scaling normally from 500 to 200 pixels.</p>\n" } ]
2008/11/07
[ "https://Stackoverflow.com/questions/271428", "https://Stackoverflow.com", "https://Stackoverflow.com/users/25749/" ]
--- Thanks for answers,Actually I am not puzzled about draw 1024\*768 pixels is slower than 100\* 100 pixels... It is so simple a logic.. Which made me puzzled is that DrawImage's interpolation algorithm may be very slow, while there exists lots of better algorithm, and its decoder seems can decode from a jpg with a certain resolution, it is really cool, I search for sometime but do not find any free lib to do this... It is really strange! I add the following code into on Paint method. c:\1.jpg is 5M jpg file, about 4000\*3000 //-------------------------------------------------------------- ``` HDC hdc = pDC->GetSafeHdc(); bitmap = Bitmap::FromFile(L"c:\\1.jpg",true); Graphics graphics(hdc); graphics.SetInterpolationMode( InterpolationModeNearestNeighbor ); graphics.DrawImage(bitmap,0,0,200,200); ``` The above is really fast! even real time! I don't think decode a 5m JPG can be that fast! //-------------------------------------------------------------- ``` HDC hdc = pDC->GetSafeHdc(); bitmap = Bitmap::FromFile(L"c:\\1.jpg",true); Graphics graphics(hdc); graphics.SetInterpolationMode( InterpolationModeNearestNeighbor ); graphics.DrawImage(bitmap,0,0,2000,2000); ``` The above code become really slow //-------------------------------------------------------------- If I add Bitmap = Bitmap::FromFile(L"c:\1.jpg", true); // into construct leave ``` Graphics graphics(hdc); graphics.SetInterpolationMode( InterpolationModeNearestNeighbor ); graphics.DrawImage(bitmap,0,0,2000,2000); ``` in OnPaint method, The code is still a bit slow~~~ //------------------------------------------------------------------ Comparing with decoding, the drawImage Process is really slow... Why and How did they do that? Did Microsoft pay the men taking charge of decoder double salary than the men taking charge of writing drawingImage?
You don't need to decode JPGs if you're scaling down by a factor of 8. JPG images consist of blocks of 8 by 8 pixels, DCT-transformed. The average value of this block is the 0,0 coefficient of the DCT. So, scaling down a factor of 8 is merely a matter of throwing away all other components. Scaling down even further (eg 4000->200) is just a matter of scaling down from 4000 to 500, and then scaling normally from 500 to 200 pixels.
271,440
<p>I met an interesting issue about C#. I have code like below.</p> <pre><code>List&lt;Func&lt;int&gt;&gt; actions = new List&lt;Func&lt;int&gt;&gt;(); int variable = 0; while (variable &lt; 5) { actions.Add(() =&gt; variable * 2); ++ variable; } foreach (var act in actions) { Console.WriteLine(act.Invoke()); } </code></pre> <p>I expect it to output 0, 2, 4, 6, 8. However, it actually outputs five 10s.</p> <p>It seems that it is due to all actions referring to one captured variable. As a result, when they get invoked, they all have same output.</p> <p>Is there a way to work round this limit to have each action instance have its own captured variable?</p>
[ { "answer_id": 271447, "author": "Jon Skeet", "author_id": 22656, "author_profile": "https://Stackoverflow.com/users/22656", "pm_score": 9, "selected": true, "text": "<p>Yes - take a copy of the variable inside the loop:</p>\n\n<pre><code>while (variable &lt; 5)\n{\n int copy = variable;\n actions.Add(() =&gt; copy * 2);\n ++ variable;\n}\n</code></pre>\n\n<p>You can think of it as if the C# compiler creates a \"new\" local variable every time it hits the variable declaration. In fact it'll create appropriate new closure objects, and it gets complicated (in terms of implementation) if you refer to variables in multiple scopes, but it works :)</p>\n\n<p>Note that a more common occurrence of this problem is using <code>for</code> or <code>foreach</code>:</p>\n\n<pre><code>for (int i=0; i &lt; 10; i++) // Just one variable\nforeach (string x in foo) // And again, despite how it reads out loud\n</code></pre>\n\n<p>See section 7.14.4.2 of the C# 3.0 spec for more details of this, and my <a href=\"http://csharpindepth.com/Articles/Chapter5/Closures.aspx\" rel=\"noreferrer\">article on closures</a> has more examples too.</p>\n\n<p>Note that as of the C# 5 compiler and beyond (even when specifying an earlier version of C#), the behavior of <code>foreach</code> changed so you no longer need to make local copy. See <a href=\"https://stackoverflow.com/questions/8898925/is-there-a-reason-for-cs-reuse-of-the-variable-in-a-foreach/8899347#8899347\">this answer</a> for more details.</p>\n" }, { "answer_id": 271449, "author": "cfeduke", "author_id": 5645, "author_profile": "https://Stackoverflow.com/users/5645", "pm_score": 3, "selected": false, "text": "<p>Yes you need to scope <code>variable</code> within the loop and pass it to the lambda that way:</p>\n\n<pre><code>List&lt;Func&lt;int&gt;&gt; actions = new List&lt;Func&lt;int&gt;&gt;();\n\nint variable = 0;\nwhile (variable &lt; 5)\n{\n int variable1 = variable;\n actions.Add(() =&gt; variable1 * 2);\n ++variable;\n}\n\nforeach (var act in actions)\n{\n Console.WriteLine(act.Invoke());\n}\n\nConsole.ReadLine();\n</code></pre>\n" }, { "answer_id": 271450, "author": "Tyler Levine", "author_id": 35339, "author_profile": "https://Stackoverflow.com/users/35339", "pm_score": 4, "selected": false, "text": "<p>The way around this is to store the value you need in a proxy variable, and have that variable get captured.</p>\n\n<p>I.E.</p>\n\n<pre><code>while( variable &lt; 5 )\n{\n int copy = variable;\n actions.Add( () =&gt; copy * 2 );\n ++variable;\n}\n</code></pre>\n" }, { "answer_id": 271455, "author": "TheCodeJunkie", "author_id": 25319, "author_profile": "https://Stackoverflow.com/users/25319", "pm_score": 5, "selected": false, "text": "<p>I believe what you are experiencing is something known as Closure <a href=\"http://en.wikipedia.org/wiki/Closure_(computer_science)\" rel=\"noreferrer\">http://en.wikipedia.org/wiki/Closure_(computer_science)</a>. Your lamba has a reference to a variable which is scoped outside the function itself. Your lamba is not interpreted until you invoke it and once it is it will get the value the variable has at execution time.</p>\n" }, { "answer_id": 4829027, "author": "Sunil", "author_id": 593932, "author_profile": "https://Stackoverflow.com/users/593932", "pm_score": 3, "selected": false, "text": "<p>The same situation is happening in multi-threading (C#, <a href=\"http://en.wikipedia.org/wiki/.NET_Framework\" rel=\"noreferrer\">.NET</a> 4.0].</p>\n\n<p>See the following code:</p>\n\n<p>Purpose is to print 1,2,3,4,5 in order.</p>\n\n<pre><code>for (int counter = 1; counter &lt;= 5; counter++)\n{\n new Thread (() =&gt; Console.Write (counter)).Start();\n}\n</code></pre>\n\n<p>The output is interesting! (It might be like 21334...)</p>\n\n<p>The only solution is to use local variables.</p>\n\n<pre><code>for (int counter = 1; counter &lt;= 5; counter++)\n{\n int localVar= counter;\n new Thread (() =&gt; Console.Write (localVar)).Start();\n}\n</code></pre>\n" }, { "answer_id": 15707665, "author": "gerrard00", "author_id": 1011470, "author_profile": "https://Stackoverflow.com/users/1011470", "pm_score": 4, "selected": false, "text": "<p>Behind the scenes, the compiler is generating a class that represents the closure for your method call. It uses that single instance of the closure class for each iteration of the loop. The code looks something like this, which makes it easier to see why the bug happens:</p>\n\n<pre><code>void Main()\n{\n List&lt;Func&lt;int&gt;&gt; actions = new List&lt;Func&lt;int&gt;&gt;();\n\n int variable = 0;\n\n var closure = new CompilerGeneratedClosure();\n\n Func&lt;int&gt; anonymousMethodAction = null;\n\n while (closure.variable &lt; 5)\n {\n if(anonymousMethodAction == null)\n anonymousMethodAction = new Func&lt;int&gt;(closure.YourAnonymousMethod);\n\n //we're re-adding the same function \n actions.Add(anonymousMethodAction);\n\n ++closure.variable;\n }\n\n foreach (var act in actions)\n {\n Console.WriteLine(act.Invoke());\n }\n}\n\nclass CompilerGeneratedClosure\n{\n public int variable;\n\n public int YourAnonymousMethod()\n {\n return this.variable * 2;\n }\n}\n</code></pre>\n\n<p>This isn't actually the compiled code from your sample, but I've examined my own code and this looks very much like what the compiler would actually generate.</p>\n" }, { "answer_id": 50837161, "author": "Maverick Meerkat", "author_id": 6296435, "author_profile": "https://Stackoverflow.com/users/6296435", "pm_score": 3, "selected": false, "text": "<h1>This has nothing to do with loops. </h1>\n\n<p>This behavior is triggered because you use a lambda expression <code>() =&gt; variable * 2</code> where the outer scoped <code>variable</code> not actually defined in the lambda's inner scope. </p>\n\n<p>Lambda expressions (in C#3+, as well as anonymous methods in C#2) still create actual methods. Passing variables to these methods involve some dilemmas (pass by value? pass by reference? C# goes with by reference - but this opens another problem where the reference can outlive the actual variable). What C# does to resolve all these dilemmas is to create a new helper class (\"closure\") with fields corresponding to the local variables used in the lambda expressions, and methods corresponding to the actual lambda methods. Any changes to <code>variable</code> in your code is actually translated to change in that <code>ClosureClass.variable</code></p>\n\n<p>So your while loop keeps updating the <code>ClosureClass.variable</code> until it reaches 10, then you for loops executes the actions, which all operate on the same <code>ClosureClass.variable</code>.</p>\n\n<p>To get your expected result, you need to create a separation between the loop variable, and the variable that is being closured. You can do this by introducing another variable, i.e.:</p>\n\n<pre><code>List&lt;Func&lt;int&gt;&gt; actions = new List&lt;Func&lt;int&gt;&gt;();\nint variable = 0;\nwhile (variable &lt; 5)\n{\n var t = variable; // now t will be closured (i.e. replaced by a field in the new class)\n actions.Add(() =&gt; t * 2);\n ++variable; // changing variable won't affect the closured variable t\n}\nforeach (var act in actions)\n{\n Console.WriteLine(act.Invoke());\n}\n</code></pre>\n\n<p>You could also move the closure to another method to create this separation:</p>\n\n<pre><code>List&lt;Func&lt;int&gt;&gt; actions = new List&lt;Func&lt;int&gt;&gt;();\n\nint variable = 0;\nwhile (variable &lt; 5)\n{\n actions.Add(Mult(variable));\n ++variable;\n}\n\nforeach (var act in actions)\n{\n Console.WriteLine(act.Invoke());\n}\n</code></pre>\n\n<p>You can implement Mult as a lambda expression (implicit closure) </p>\n\n<pre><code>static Func&lt;int&gt; Mult(int i)\n{\n return () =&gt; i * 2;\n}\n</code></pre>\n\n<p>or with an actual helper class:</p>\n\n<pre><code>public class Helper\n{\n public int _i;\n public Helper(int i)\n {\n _i = i;\n }\n public int Method()\n {\n return _i * 2;\n }\n}\n\nstatic Func&lt;int&gt; Mult(int i)\n{\n Helper help = new Helper(i);\n return help.Method;\n}\n</code></pre>\n\n<p>In any case, <strong>\"Closures\" are NOT a concept related to loops</strong>, but rather to anonymous methods / lambda expressions use of local scoped variables - although some incautious use of loops demonstrate closures traps.</p>\n" }, { "answer_id": 53744561, "author": "Junaid Pathan", "author_id": 8304176, "author_profile": "https://Stackoverflow.com/users/8304176", "pm_score": -1, "selected": false, "text": "<p>It is called the closure problem,\nsimply use a copy variable, and it's done.</p>\n\n<pre><code>List&lt;Func&lt;int&gt;&gt; actions = new List&lt;Func&lt;int&gt;&gt;();\n\nint variable = 0;\nwhile (variable &lt; 5)\n{\n int i = variable;\n actions.Add(() =&gt; i * 2);\n ++ variable;\n}\n\nforeach (var act in actions)\n{\n Console.WriteLine(act.Invoke());\n}\n</code></pre>\n" }, { "answer_id": 60474255, "author": "Nathan Chappell", "author_id": 6084517, "author_profile": "https://Stackoverflow.com/users/6084517", "pm_score": -1, "selected": false, "text": "<p>Since no one here directly quoted <a href=\"https://ecma-international.org/publications/files/ECMA-ST/ECMA-334.pdf\" rel=\"nofollow noreferrer\">ECMA-334</a>:</p>\n\n<blockquote>\n <p>10.4.4.10 For statements </p>\n \n <p>Definite assignment checking for a for-statement of the form:</p>\n</blockquote>\n\n<pre><code>for (for-initializer; for-condition; for-iterator) embedded-statement\n</code></pre>\n\n<blockquote>\n <p>is done as if the statement were written:</p>\n</blockquote>\n\n<pre><code>{\n for-initializer;\n while (for-condition) {\n embedded-statement;\n LLoop: for-iterator;\n }\n}\n</code></pre>\n\n<p>Further on in the spec,</p>\n\n<blockquote>\n <p>12.16.6.3 Instantiation of local variables</p>\n \n <p>A local variable is considered to be instantiated when execution enters the scope of the variable. </p>\n \n <p>[Example: For example, when the following method is invoked, the local variable <code>x</code> is instantiated and initialized three times—once for each iteration of the loop.</p>\n</blockquote>\n\n<pre><code>static void F() {\n for (int i = 0; i &lt; 3; i++) {\n int x = i * 2 + 1;\n ...\n }\n}\n</code></pre>\n\n<blockquote>\n <p>However, moving the declaration of <code>x</code> outside the loop results in a single instantiation of <code>x</code>:</p>\n</blockquote>\n\n<pre><code>static void F() {\n int x;\n for (int i = 0; i &lt; 3; i++) {\n x = i * 2 + 1;\n ...\n }\n}\n</code></pre>\n\n<blockquote>\n <p>end example]</p>\n \n <p>When not captured, there is no way to observe exactly how often a local variable is instantiated—because the lifetimes of the instantiations are disjoint, it is possible for each instantation to simply use the same storage location. However, when an anonymous function captures a local variable, the effects of instantiation become apparent.</p>\n \n <p>[Example: The example </p>\n</blockquote>\n\n<pre><code>using System;\n\ndelegate void D();\n\nclass Test{\n static D[] F() {\n D[] result = new D[3];\n for (int i = 0; i &lt; 3; i++) {\n int x = i * 2 + 1;\n result[i] = () =&gt; { Console.WriteLine(x); };\n }\n return result;\n }\n static void Main() {\n foreach (D d in F()) d();\n }\n}\n</code></pre>\n\n<blockquote>\n <p>produces the output:</p>\n</blockquote>\n\n<pre><code>1\n3\n5\n</code></pre>\n\n<blockquote>\n <p>However, when the declaration of <code>x</code> is moved outside the loop:</p>\n</blockquote>\n\n<pre><code>static D[] F() {\n D[] result = new D[3];\n int x;\n for (int i = 0; i &lt; 3; i++) {\n x = i * 2 + 1;\n result[i] = () =&gt; { Console.WriteLine(x); };\n }\n return result;\n}\n</code></pre>\n\n<blockquote>\n <p>the output is:</p>\n</blockquote>\n\n<pre><code>5\n5\n5\n</code></pre>\n\n<blockquote>\n <p>Note that the compiler is permitted (but not required) to optimize the three instantiations into a single delegate instance (§11.7.2).</p>\n \n <p>If a for-loop declares an iteration variable, that variable itself is considered to be declared outside of the loop. \n [Example: Thus, if the example is changed to capture the iteration variable itself:</p>\n</blockquote>\n\n<pre><code>static D[] F() {\n D[] result = new D[3];\n for (int i = 0; i &lt; 3; i++) {\n result[i] = () =&gt; { Console.WriteLine(i); };\n }\n return result;\n}\n</code></pre>\n\n<blockquote>\n <p>only one instance of the iteration variable is captured, which produces the output:</p>\n</blockquote>\n\n<pre><code>3\n3\n3\n</code></pre>\n\n<blockquote>\n <p>end example]</p>\n</blockquote>\n\n<p>Oh yea, I guess it should be mentioned that in C++ this problem doesn't occur because you can choose if the variable is captured by value or by reference (see: <a href=\"https://en.cppreference.com/w/cpp/language/lambda#Lambda_capture\" rel=\"nofollow noreferrer\">Lambda capture</a>).</p>\n" }, { "answer_id": 65439550, "author": "Arshman Saleem", "author_id": 6366945, "author_profile": "https://Stackoverflow.com/users/6366945", "pm_score": 0, "selected": false, "text": "<pre><code>for (int n=0; n &lt; 10; n++) //forloop syntax\nforeach (string item in foo) foreach syntax\n</code></pre>\n" } ]
2008/11/07
[ "https://Stackoverflow.com/questions/271440", "https://Stackoverflow.com", "https://Stackoverflow.com/users/26349/" ]
I met an interesting issue about C#. I have code like below. ``` List<Func<int>> actions = new List<Func<int>>(); int variable = 0; while (variable < 5) { actions.Add(() => variable * 2); ++ variable; } foreach (var act in actions) { Console.WriteLine(act.Invoke()); } ``` I expect it to output 0, 2, 4, 6, 8. However, it actually outputs five 10s. It seems that it is due to all actions referring to one captured variable. As a result, when they get invoked, they all have same output. Is there a way to work round this limit to have each action instance have its own captured variable?
Yes - take a copy of the variable inside the loop: ``` while (variable < 5) { int copy = variable; actions.Add(() => copy * 2); ++ variable; } ``` You can think of it as if the C# compiler creates a "new" local variable every time it hits the variable declaration. In fact it'll create appropriate new closure objects, and it gets complicated (in terms of implementation) if you refer to variables in multiple scopes, but it works :) Note that a more common occurrence of this problem is using `for` or `foreach`: ``` for (int i=0; i < 10; i++) // Just one variable foreach (string x in foo) // And again, despite how it reads out loud ``` See section 7.14.4.2 of the C# 3.0 spec for more details of this, and my [article on closures](http://csharpindepth.com/Articles/Chapter5/Closures.aspx) has more examples too. Note that as of the C# 5 compiler and beyond (even when specifying an earlier version of C#), the behavior of `foreach` changed so you no longer need to make local copy. See [this answer](https://stackoverflow.com/questions/8898925/is-there-a-reason-for-cs-reuse-of-the-variable-in-a-foreach/8899347#8899347) for more details.
271,464
<p>I have a multiline text string (e.g. "Stuff\nMore Stuff\nYet More Stuff"), and I want to paint it, along with a bitmap into a tooltip. Since I am painting the bitmap, I need to set OwnerDraw to true, which I am doing. I am also handling the Popup event, so I can size the tooltip to be large enough to hold the text and the bitmap.</p> <p>I am calling e.DrawBackground and e.DrawBorder(), and then painting my bitmap on the left side of the tooltip area. </p> <p>Is there a set of flags I can pass to e.DrawText() in order to left-align the text, but to offset it so that it doesn't get painted over my bitmap? Or do I need to custom draw all the text as well (which will probably involve splitting the string on newlines, etc)?</p> <p>UPDATED: The final code looks like this:</p> <pre><code>private void _ItemTip_Draw(object sender, DrawToolTipEventArgs e) { e.DrawBackground(); e.DrawBorder(); // Reserve a square of size e.Bounds.Height x e.Bounds.Height // for the image. Keep a margin around it so that it looks good. int margin = 2; Image i = _ItemTip.Tag as Image; if (i != null) { int side = e.Bounds.Height - 2 * margin; e.Graphics.DrawImage(i, new Rectangle(margin, margin, side, side)); } // Construct bounding rectangle for text (don't want to paint it over the image). int textOffset = e.Bounds.Height + 2 * margin; RectangleF rText = e.Bounds; rText.Offset(textOffset, 0); rText.Width -= textOffset; e.Graphics.DrawString(e.ToolTipText, e.Font, Brushes.Black, rText); } </code></pre>
[ { "answer_id": 271628, "author": "Robert Jeppesen", "author_id": 9436, "author_profile": "https://Stackoverflow.com/users/9436", "pm_score": 3, "selected": true, "text": "<p>I assume that if you define the bounding rectangle to draw in (calculating the image offset yourself) you could just: </p>\n\n<pre><code> RectangleF rect = new RectangleF(100,100,100,100);\n e.Graphics.DrawString(myString, myFont, myBrush, rect);\n</code></pre>\n" }, { "answer_id": 271658, "author": "tamberg", "author_id": 3588, "author_profile": "https://Stackoverflow.com/users/3588", "pm_score": 0, "selected": false, "text": "<p>to calculate the Height of an owner drawn string s given a certain width w, we use the following code:</p>\n\n<pre><code>double MeasureStringHeight (Graphics g, string s, Font f, int w) {\n double result = 0;\n int n = s.Length;\n int i = 0;\n while (i &lt; n) {\n StringBuilder line = new StringBuilder();\n int iLineStart = i;\n int iSpace = -1;\n SizeF sLine = new SizeF(0, 0);\n while ((i &lt; n) &amp;&amp; (sLine.Width &lt;= w)) {\n char ch = s[i];\n if ((ch == ' ') || (ch == '-')) {\n iSpace = i;\n }\n line.Append(ch);\n sLine = g.MeasureString(line.ToString(), f);\n i++;\n }\n if (sLine.Width &gt; w) {\n if (iSpace &gt;= 0) {\n i = iSpace + 1;\n } else {\n i--;\n }\n // Assert(w &gt; largest ch in line)\n }\n result += sLine.Height;\n }\n return result;\n}\n</code></pre>\n\n<p>Regards,\ntamberg</p>\n" } ]
2008/11/07
[ "https://Stackoverflow.com/questions/271464", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2683/" ]
I have a multiline text string (e.g. "Stuff\nMore Stuff\nYet More Stuff"), and I want to paint it, along with a bitmap into a tooltip. Since I am painting the bitmap, I need to set OwnerDraw to true, which I am doing. I am also handling the Popup event, so I can size the tooltip to be large enough to hold the text and the bitmap. I am calling e.DrawBackground and e.DrawBorder(), and then painting my bitmap on the left side of the tooltip area. Is there a set of flags I can pass to e.DrawText() in order to left-align the text, but to offset it so that it doesn't get painted over my bitmap? Or do I need to custom draw all the text as well (which will probably involve splitting the string on newlines, etc)? UPDATED: The final code looks like this: ``` private void _ItemTip_Draw(object sender, DrawToolTipEventArgs e) { e.DrawBackground(); e.DrawBorder(); // Reserve a square of size e.Bounds.Height x e.Bounds.Height // for the image. Keep a margin around it so that it looks good. int margin = 2; Image i = _ItemTip.Tag as Image; if (i != null) { int side = e.Bounds.Height - 2 * margin; e.Graphics.DrawImage(i, new Rectangle(margin, margin, side, side)); } // Construct bounding rectangle for text (don't want to paint it over the image). int textOffset = e.Bounds.Height + 2 * margin; RectangleF rText = e.Bounds; rText.Offset(textOffset, 0); rText.Width -= textOffset; e.Graphics.DrawString(e.ToolTipText, e.Font, Brushes.Black, rText); } ```
I assume that if you define the bounding rectangle to draw in (calculating the image offset yourself) you could just: ``` RectangleF rect = new RectangleF(100,100,100,100); e.Graphics.DrawString(myString, myFont, myBrush, rect); ```
271,485
<p>whats the best way to export a Datagrid to excel? I have no experience whatsoever in exporting datagrid to excel, so i want to know how you guys export datagrid to excel. i read that there are a lot of ways, but i am thinking to just make a simple export excel to datagrid function.i am using asp.net C#</p> <p>cheers.. </p>
[ { "answer_id": 271487, "author": "Marc Gravell", "author_id": 23354, "author_profile": "https://Stackoverflow.com/users/23354", "pm_score": 4, "selected": true, "text": "<p>The simplest way is to simply write either csv, or html (in particular, a <code>&lt;table&gt;&lt;tr&gt;&lt;td&gt;...&lt;/td&gt;&lt;/tr&gt;...&lt;/table&gt;</code>) to the output, and simply pretend that it is in excel format via the content-type header. Excel will happily load either; csv is simpler...</p>\n\n<p>Here's a similar example (it actually takes an IEnumerable, but it would be similar from any source (such as a <code>DataTable</code>, looping over the rows).</p>\n\n<pre><code> public static void WriteCsv(string[] headers, IEnumerable&lt;string[]&gt; data, string filename)\n {\n if (data == null) throw new ArgumentNullException(\"data\");\n if (string.IsNullOrEmpty(filename)) filename = \"export.csv\";\n\n HttpResponse resp = System.Web.HttpContext.Current.Response;\n resp.Clear();\n // remove this line if you don't want to prompt the user to save the file\n resp.AddHeader(\"Content-Disposition\", \"attachment;filename=\" + filename);\n // if not saving, try: \"application/ms-excel\"\n resp.ContentType = \"text/csv\";\n string csv = GetCsv(headers, data);\n byte[] buffer = resp.ContentEncoding.GetBytes(csv);\n resp.AddHeader(\"Content-Length\", buffer.Length.ToString());\n resp.BinaryWrite(buffer);\n resp.End();\n }\n static void WriteRow(string[] row, StringBuilder destination)\n {\n if (row == null) return;\n int fields = row.Length;\n for (int i = 0; i &lt; fields; i++)\n {\n string field = row[i];\n if (i &gt; 0)\n {\n destination.Append(',');\n }\n if (string.IsNullOrEmpty(field)) continue; // empty field\n\n bool quote = false;\n if (field.Contains(\"\\\"\"))\n {\n // if contains quotes, then needs quoting and escaping\n quote = true;\n field = field.Replace(\"\\\"\", \"\\\"\\\"\");\n }\n else\n {\n // commas, line-breaks, and leading-trailing space also require quoting\n if (field.Contains(\",\") || field.Contains(\"\\n\") || field.Contains(\"\\r\")\n || field.StartsWith(\" \") || field.EndsWith(\" \"))\n {\n quote = true;\n }\n }\n if (quote)\n {\n destination.Append('\\\"');\n destination.Append(field);\n destination.Append('\\\"');\n }\n else\n {\n destination.Append(field);\n }\n\n }\n destination.AppendLine();\n }\n static string GetCsv(string[] headers, IEnumerable&lt;string[]&gt; data)\n {\n StringBuilder sb = new StringBuilder();\n if (data == null) throw new ArgumentNullException(\"data\");\n WriteRow(headers, sb);\n foreach (string[] row in data)\n {\n WriteRow(row, sb);\n\n }\n return sb.ToString();\n }\n</code></pre>\n" }, { "answer_id": 271496, "author": "Christian C. Salvadó", "author_id": 5445, "author_profile": "https://Stackoverflow.com/users/5445", "pm_score": 2, "selected": false, "text": "<p>You can do it in this way:</p>\n\n<pre><code>private void ExportButton_Click(object sender, System.EventArgs e)\n{\n Response.Clear();\n Response.Buffer = true;\n Response.ContentType = \"application/vnd.ms-excel\";\n Response.Charset = \"\";\n this.EnableViewState = false;\n System.IO.StringWriter oStringWriter = new System.IO.StringWriter();\n System.Web.UI.HtmlTextWriter oHtmlTextWriter = new System.Web.UI.HtmlTextWriter(oStringWriter);\n this.ClearControls(dataGrid);\n dataGrid.RenderControl(oHtmlTextWriter);\n Response.Write(oStringWriter.ToString());\n Response.End();\n}\n</code></pre>\n\n<p>Complete example <a href=\"http://www.c-sharpcorner.com/UploadFile/DipalChoksi/ExportASPNetDataGridToExcel11222005041447AM/ExportASPNetDataGridToExcel.aspx\" rel=\"nofollow noreferrer\">here</a>.</p>\n" }, { "answer_id": 1352066, "author": "Joe Erickson", "author_id": 56710, "author_profile": "https://Stackoverflow.com/users/56710", "pm_score": 0, "selected": false, "text": "<p><a href=\"http://www.spreadsheetgear.com/\" rel=\"nofollow noreferrer\">SpreadsheetGear for .NET</a> will do it.</p>\n\n<p>You can see live ASP.NET samples with C# and VB source code <a href=\"http://www.spreadsheetgear.com/support/samples/\" rel=\"nofollow noreferrer\">here</a>. Several of these samples demonstrate converting a DataSet or DataTable to Excel - and you can easily get a DataSet or DataTable from a DataGrid. You can download the free trial <a href=\"https://www.spreadsheetgear.com/downloads/register.aspx\" rel=\"nofollow noreferrer\">here</a> if you want to try it yourself.</p>\n\n<p>Disclaimer: I own SpreadsheetGear LLC</p>\n" } ]
2008/11/07
[ "https://Stackoverflow.com/questions/271485", "https://Stackoverflow.com", "https://Stackoverflow.com/users/23491/" ]
whats the best way to export a Datagrid to excel? I have no experience whatsoever in exporting datagrid to excel, so i want to know how you guys export datagrid to excel. i read that there are a lot of ways, but i am thinking to just make a simple export excel to datagrid function.i am using asp.net C# cheers..
The simplest way is to simply write either csv, or html (in particular, a `<table><tr><td>...</td></tr>...</table>`) to the output, and simply pretend that it is in excel format via the content-type header. Excel will happily load either; csv is simpler... Here's a similar example (it actually takes an IEnumerable, but it would be similar from any source (such as a `DataTable`, looping over the rows). ``` public static void WriteCsv(string[] headers, IEnumerable<string[]> data, string filename) { if (data == null) throw new ArgumentNullException("data"); if (string.IsNullOrEmpty(filename)) filename = "export.csv"; HttpResponse resp = System.Web.HttpContext.Current.Response; resp.Clear(); // remove this line if you don't want to prompt the user to save the file resp.AddHeader("Content-Disposition", "attachment;filename=" + filename); // if not saving, try: "application/ms-excel" resp.ContentType = "text/csv"; string csv = GetCsv(headers, data); byte[] buffer = resp.ContentEncoding.GetBytes(csv); resp.AddHeader("Content-Length", buffer.Length.ToString()); resp.BinaryWrite(buffer); resp.End(); } static void WriteRow(string[] row, StringBuilder destination) { if (row == null) return; int fields = row.Length; for (int i = 0; i < fields; i++) { string field = row[i]; if (i > 0) { destination.Append(','); } if (string.IsNullOrEmpty(field)) continue; // empty field bool quote = false; if (field.Contains("\"")) { // if contains quotes, then needs quoting and escaping quote = true; field = field.Replace("\"", "\"\""); } else { // commas, line-breaks, and leading-trailing space also require quoting if (field.Contains(",") || field.Contains("\n") || field.Contains("\r") || field.StartsWith(" ") || field.EndsWith(" ")) { quote = true; } } if (quote) { destination.Append('\"'); destination.Append(field); destination.Append('\"'); } else { destination.Append(field); } } destination.AppendLine(); } static string GetCsv(string[] headers, IEnumerable<string[]> data) { StringBuilder sb = new StringBuilder(); if (data == null) throw new ArgumentNullException("data"); WriteRow(headers, sb); foreach (string[] row in data) { WriteRow(row, sb); } return sb.ToString(); } ```
271,488
<p>I asked <a href="https://stackoverflow.com/questions/269417/which-language-should-i-use">a question</a> earlier about which language to use for an AI prototype. The consensus seemed to be that if I want it to be fast, I need to use a language like Java or C++, but that Python / Perl / Ruby would be good for the interface bits. </p> <p>So, this leads me on to another question. How easy is it to link these languages together? And which combination works best? So, if I wanted to have a Ruby CGI-type program calling C++ or Java AI functions, is that easy to do? Any pointers for where I look for information on doing that kind of thing? Or would a different combination be better?</p> <p>My main experience with writing web applications started with C++ CGI and then moved on to Java servlets (about 10 years ago) and then after a long gap away from programming I did some PHP. But I've not had experience of writing a web application in a scripting language which then calls out to a compiled language for the speed-critical bits. So any advice will be welcome!</p>
[ { "answer_id": 271494, "author": "VonC", "author_id": 6309, "author_profile": "https://Stackoverflow.com/users/6309", "pm_score": 2, "selected": false, "text": "<p>It may be a good approach to start with a script, and call a compilation-based language from that script only for more advanced needs.</p>\n\n<p>For instance, <a href=\"http://www.javaworld.com/javaworld/jw-07-2006/jw-0717-ruby.html\" rel=\"nofollow noreferrer\">calling java from ruby script</a> works quite well.</p>\n\n<pre><code>require \"java\"\n# The next line exposes Java's String as JString\ninclude_class(\"java.lang.String\") { |pkg, name| \"J\" + name }\ns = JString.new(\"f\")\n</code></pre>\n" }, { "answer_id": 271501, "author": "Mendelt", "author_id": 3320, "author_profile": "https://Stackoverflow.com/users/3320", "pm_score": 2, "selected": false, "text": "<p>You can build your program in one of the higher level languages for example Python or Ruby and then call modules that are compiled in the lower level language for the parts you need performance. You can choose a platform depending on the lower level language you want.</p>\n\n<p>For example if you want to do C++ for the speedy stuff you can just use plain Python or Ruby and call DLLs compiled in C++. If you want to use Java you can use Jython or one of the other dynamic languages on the Java platform to call the Java code this is easier than the C++ route because you've got a common virtual machine so a Java object can be used directly in Jython or JRuby. The same can be done on the .Net platform with the Iron-languages and C# although you seem to have more experience with C++ and Java so those would be better options.</p>\n" }, { "answer_id": 271590, "author": "Ryan Ginstrom", "author_id": 10658, "author_profile": "https://Stackoverflow.com/users/10658", "pm_score": 3, "selected": false, "text": "<p>First, a meta comment: I would highly recommend coding the entire thing in a high-level language, profiling like mad, and optimizing only where profiling shows it's necessary. First optimize the algorithm, then the code, then think about bringing in the heavy iron. Having an optimum algorithm and clean code will make things much easier when/if you need to reimplement in a lower-level language.</p>\n\n<p>Speaking for Python, <a href=\"http://www.codeplex.com/Wiki/View.aspx?ProjectName=IronPython\" rel=\"noreferrer\">IronPython</a>/C# is probably the easiest optimization path. </p>\n\n<p>CPython with C++ is doable, but I find C a lot easier to handle (but not all that easy, being C). Two tools that ease this are <a href=\"http://cython.org/\" rel=\"noreferrer\">cython</a>/<a href=\"http://www.cosc.canterbury.ac.nz/greg.ewing/python/Pyrex/\" rel=\"noreferrer\">pyrex</a> (for C) and <a href=\"http://shed-skin.blogspot.com/\" rel=\"noreferrer\">shedskin</a> (for C++). These compile Python into C/C++, and from there you can access C/C++ libraries without too much ado.</p>\n\n<p>I've never used jython, but I hear that the jython/Java optimization path isn't all that bad.</p>\n" }, { "answer_id": 271642, "author": "Pieter", "author_id": 5822, "author_profile": "https://Stackoverflow.com/users/5822", "pm_score": 5, "selected": true, "text": "<p><a href=\"http://www.boost.org/doc/libs/1_36_0/libs/python/doc/tutorial/doc/html/index.html\" rel=\"noreferrer\">Boost.Python</a> provides an easy way to turn C++ code into Python modules. It's rather mature and works well in my experience. </p>\n\n<p>For example, the inevitable Hello World...</p>\n\n<pre><code>char const* greet()\n{\n return \"hello, world\";\n}\n</code></pre>\n\n<p>can be exposed to Python by writing a Boost.Python wrapper:</p>\n\n<pre><code>#include &lt;boost/python.hpp&gt;\n\nBOOST_PYTHON_MODULE(hello_ext)\n{\n using namespace boost::python;\n def(\"greet\", greet);\n}\n</code></pre>\n\n<p>That's it. We're done. We can now build this as a shared library. The resulting DLL is now visible to Python. Here's a sample Python session:</p>\n\n<pre><code>&gt;&gt;&gt; import hello_ext\n&gt;&gt;&gt; print hello.greet()\nhello, world\n</code></pre>\n\n<p>(example taken from boost.org)</p>\n" }, { "answer_id": 271729, "author": "Dan Goldsmith", "author_id": 35163, "author_profile": "https://Stackoverflow.com/users/35163", "pm_score": 3, "selected": false, "text": "<p>I agree with the Idea of coding first in a high level language such as Python, Profiling and then Implementing any code that needs speeding up in C / C++ and wrapping it for use in the high level language.</p>\n\n<p>As an alternative to boost I would like to suggest <a href=\"http://www.swig.org/\" rel=\"noreferrer\" title=\"SWIG\">SWIG</a> for creating Python callable code from C. Its reasonably painless to use, and will compile callable modules for a wide range of languages. (Python, Ruby, Java, Lua. to name a few) from C code.</p>\n\n<p>The wrapping process is semi automated, so there is no need to add new functions to the base C code, making a smoother work flow. </p>\n" }, { "answer_id": 272163, "author": "mpeters", "author_id": 12094, "author_profile": "https://Stackoverflow.com/users/12094", "pm_score": 2, "selected": false, "text": "<p>Perl has several ways to use other languages. Look at the <a href=\"http://search.cpan.org/perldoc?Inline\" rel=\"nofollow noreferrer\">Inline::<em></a> family of modules on CPAN. Following the advice from others in this question, I'd write the whole thing in a single dynamic language (Perl, Python, Ruby, etc) and then optimize the bits that need it. With Perl and Inline::</em> you can optimize in C, C++, or Java. Or you could look at <a href=\"http://search.cpan.org/perldoc?AI::Prolog\" rel=\"nofollow noreferrer\">AI::Prolog</a> which allows you to embed Prolog for AI/Logic programming.</p>\n" }, { "answer_id": 272363, "author": "Brad Gilbert", "author_id": 1337, "author_profile": "https://Stackoverflow.com/users/1337", "pm_score": 3, "selected": false, "text": "<p>If you choose Perl there are plenty of resources for interfacing other languages.</p>\n\n<p><a href=\"http://search.cpan.org/dist/Inline/C/C.podI\" rel=\"nofollow noreferrer\">Inline::C</a><br>\n<a href=\"http://search.cpan.org/dist/Inline-CPP/\" rel=\"nofollow noreferrer\">Inline::CPP</a><br>\n<a href=\"http://search.cpan.org/dist/Inline-Java/Java.pod\" rel=\"nofollow noreferrer\">Inline::Java</a></p>\n\n<p>From <a href=\"http://search.cpan.org/dist/Inline/C/C-Cookbook.pod\" rel=\"nofollow noreferrer\">Inline::C-Cookbook</a>:</p>\n\n<pre><code>use Inline C =&gt; &lt;&lt;'END_C';\n\n void greet() {\n printf(\"Hello, world\\n\");\n }\nEND_C\n\ngreet;\n</code></pre>\n\n<hr>\n\n<p>With Perl 6 it gets even easier to import subroutine from native library code using <a href=\"https://doc.perl6.org/language/nativecall\" rel=\"nofollow noreferrer\">NativeCall</a>.</p>\n\n<pre class=\"lang-perl6 prettyprint-override\"><code>use v6.c;\n\nsub c-print ( Str() $s ){\n use NativeCall;\n\n # restrict the function to inside of this subroutine because printf is\n # vararg based, and we only handle '%s' based inputs here\n\n # it should be possible to handle more but it requires generating\n # a Signature object based on the format string and then do a\n # nativecast with that Signature, and a pointer to printf\n\n sub printf ( str, str --&gt; int32 ) is native('libc:6') {}\n\n printf '%s', $s\n}\n\nc-print 'Hello World';\n</code></pre>\n\n<p>This is just a simple example, you can create a class that has a representation of a Pointer, and have some of the methods be C code from the library you are using. ( only works if the first argument of the C code is the pointer, otherwise you would have to wrap it )</p>\n\n<p>If you need the Perl 6 subroutine/method name to be different you can use the <code>is symbol</code> trait modifier.</p>\n\n<p>There are also Inline modules for Perl 6 as well.</p>\n" }, { "answer_id": 276021, "author": "Jim Carroll", "author_id": 35922, "author_profile": "https://Stackoverflow.com/users/35922", "pm_score": 1, "selected": false, "text": "<p>I have a different perspective, having had lots of luck with integrating C++ and Python for some real time live video image processing.</p>\n\n<p>I would say you should match the language to the task for each module. If you're responding to a network, do it in Python, Python can keep up with network traffic just fine. UI: Python, People are slow, and Python is great for UIs using wxPython or PyObjC on Mac, or PyGTK. If you're doing math on lots of data, or signal processing, or image processing... code it in C or C++ with unit tests, then use <strong>SWIG</strong> to create the binding to any higher level language.</p>\n\n<p>I used the image libraries in wxWidgets in my C++, which are already exposed to Python through wxPython, so it was extremely powerful and quick. SCONS is a build tool (like make) which knows what to do with swig's .i files.</p>\n\n<p>The topmost level can be in C or Python, you'll have more control and fewer packaging and deployment issues if the top level is in C or C++... but it will take a really long time to duplicate what Py2EXE or Py2App gives you on Windows or Mac (or freeze on Linux.) </p>\n\n<p>Enjoy the power of hybrid programming! (I call using multiple languages in a tightly coupled way 'hybrid' but it's just a quirk of mine.)</p>\n" }, { "answer_id": 276242, "author": "Denis Hennessy", "author_id": 35958, "author_profile": "https://Stackoverflow.com/users/35958", "pm_score": 1, "selected": false, "text": "<p>If the problem domain is hard (and AI problems can often be hard), then I'd choose a language which is expressive or suited to the domain first, and then worry about speeding it up second. For example, Ruby has meta-programming primitives (ability to easily examine and modify the running program) which can make it very easy/interesting to implement certain types of algorithms.</p>\n\n<p>If you implement it in that way and then later need to speed it up, then you can use benchmarking/profiling to locate the bottleneck and either link to a compiled language for that, or optimise the algorithm. In my experience, the biggest performance gain is from tweaking the algorithm, not from using a different implementation language.</p>\n" } ]
2008/11/07
[ "https://Stackoverflow.com/questions/271488", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11522/" ]
I asked [a question](https://stackoverflow.com/questions/269417/which-language-should-i-use) earlier about which language to use for an AI prototype. The consensus seemed to be that if I want it to be fast, I need to use a language like Java or C++, but that Python / Perl / Ruby would be good for the interface bits. So, this leads me on to another question. How easy is it to link these languages together? And which combination works best? So, if I wanted to have a Ruby CGI-type program calling C++ or Java AI functions, is that easy to do? Any pointers for where I look for information on doing that kind of thing? Or would a different combination be better? My main experience with writing web applications started with C++ CGI and then moved on to Java servlets (about 10 years ago) and then after a long gap away from programming I did some PHP. But I've not had experience of writing a web application in a scripting language which then calls out to a compiled language for the speed-critical bits. So any advice will be welcome!
[Boost.Python](http://www.boost.org/doc/libs/1_36_0/libs/python/doc/tutorial/doc/html/index.html) provides an easy way to turn C++ code into Python modules. It's rather mature and works well in my experience. For example, the inevitable Hello World... ``` char const* greet() { return "hello, world"; } ``` can be exposed to Python by writing a Boost.Python wrapper: ``` #include <boost/python.hpp> BOOST_PYTHON_MODULE(hello_ext) { using namespace boost::python; def("greet", greet); } ``` That's it. We're done. We can now build this as a shared library. The resulting DLL is now visible to Python. Here's a sample Python session: ``` >>> import hello_ext >>> print hello.greet() hello, world ``` (example taken from boost.org)
271,518
<p>I am using axis 2 webservice client.</p> <p>The first https call to the webservice throws a exception with the message: "Message did not contain a valid Security Element".</p> <p>I think that the problem could be the security mode: maybe it has to be message level security. In this case, how can I configure it in axis?.</p> <p>The code:</p> <pre><code>System.setProperty("javax.net.ssl.keyStore", jksFile); System.setProperty("javax.net.ssl.keyStorePassword", jksPassword); MyServicePortProxy proxy = new MyServicePortProxy(); Stub stub = (Stub) proxy.getMyServicePort(); proxy.setEndpoint(endpoint); stub.setUsername(username); stub.setPassword(password); // throws exception with the above message: proxy.serviceMethod(...); </code></pre>
[ { "answer_id": 354882, "author": "Matt Campbell", "author_id": 41895, "author_profile": "https://Stackoverflow.com/users/41895", "pm_score": 1, "selected": false, "text": "<p>If you don't mind using EXT-GWT, a much prettier fully compliant GWT UI toolkit then this might be more what your looking for. </p>\n\n<p><a href=\"http://extjs.com/examples/layouts/accordionlayout.html\" rel=\"nofollow noreferrer\">The Example</a>. </p>\n\n<p>GXT as it is also called can do lots of good things for a GUI.</p>\n" }, { "answer_id": 12115006, "author": "Joel", "author_id": 502360, "author_profile": "https://Stackoverflow.com/users/502360", "pm_score": 0, "selected": false, "text": "<p>I took the TabPanel source code and modified it so it drew the tabs to look like Outlook.</p>\n" } ]
2008/11/07
[ "https://Stackoverflow.com/questions/271518", "https://Stackoverflow.com", "https://Stackoverflow.com/users/29600/" ]
I am using axis 2 webservice client. The first https call to the webservice throws a exception with the message: "Message did not contain a valid Security Element". I think that the problem could be the security mode: maybe it has to be message level security. In this case, how can I configure it in axis?. The code: ``` System.setProperty("javax.net.ssl.keyStore", jksFile); System.setProperty("javax.net.ssl.keyStorePassword", jksPassword); MyServicePortProxy proxy = new MyServicePortProxy(); Stub stub = (Stub) proxy.getMyServicePort(); proxy.setEndpoint(endpoint); stub.setUsername(username); stub.setPassword(password); // throws exception with the above message: proxy.serviceMethod(...); ```
If you don't mind using EXT-GWT, a much prettier fully compliant GWT UI toolkit then this might be more what your looking for. [The Example](http://extjs.com/examples/layouts/accordionlayout.html). GXT as it is also called can do lots of good things for a GUI.
271,520
<p>I could do this in C#..</p> <pre><code>int number = 2; string str = "Hello " + number + " world"; </code></pre> <p>..and str ends up as "Hello 2 world".</p> <p>In VB.NET i could do this..</p> <pre><code>Dim number As Integer = 2 Dim str As String = "Hello " + number + " world" </code></pre> <p>..but I get an InvalidCastException "Conversion from string "Hello " to type 'Double' is not valid."</p> <p>I am aware that I should use .ToString() in both cases, but whats going on here with the code as it is?</p>
[ { "answer_id": 271529, "author": "Jon Skeet", "author_id": 22656, "author_profile": "https://Stackoverflow.com/users/22656", "pm_score": 5, "selected": true, "text": "<p>In VB I believe the string concatenation operator is &amp; rather than + so try this:</p>\n\n<pre><code>Dim number As Integer = 2\nDim str As String = \"Hello \" &amp; number &amp; \" world\"\n</code></pre>\n\n<p>Basically when VB sees + I suspect it tries do numeric addition or use the addition operator defined in a type (or no doubt other more complicated things, based on options...) Note that <code>System.String</code> doesn't define an addition operator - it's all hidden in the compiler by calls to <code>String.Concat</code>. (This allows much more efficient concatenation of multiple strings.)</p>\n" }, { "answer_id": 271531, "author": "TheCodeJunkie", "author_id": 25319, "author_profile": "https://Stackoverflow.com/users/25319", "pm_score": 3, "selected": false, "text": "<p>Visual Basic makes a distinction between the <code>+</code> and <code>&amp;</code> operators. The <code>&amp;</code> will make the conversion to a string if an expression is not a string.</p>\n\n<p><a href=\"http://msdn.microsoft.com/en-us/library/wfx50zyk.aspx\" rel=\"nofollow noreferrer\"><code>&amp;</code>Operator (Visual Basic)</a></p>\n\n<p>The <code>+</code> operator uses more complex evaluation logic to determine what to make the final cast into (for example it's affected by things like <strong>Option Strict</strong> configuration)</p>\n\n<p><a href=\"http://msdn.microsoft.com/en-us/library/9c5t70w2.aspx\" rel=\"nofollow noreferrer\"><code>+</code>Operator (Visual Basic)</a></p>\n" }, { "answer_id": 271532, "author": "chakrit", "author_id": 3055, "author_profile": "https://Stackoverflow.com/users/3055", "pm_score": 1, "selected": false, "text": "<p>The VB plus (+) operator is ambiguous.</p>\n\n<p>If you don't have Option Explicit on, if my memory serves me right, it is possible to do this:</p>\n\n<pre><code>Dim str = 1 + \"2\"\n</code></pre>\n\n<p>and gets str as integer = 3.</p>\n\n<p>If you explicitly want a string concatenation, use the ampersand operator</p>\n\n<pre><code>Dim str = \"Hello \" &amp; number &amp; \" world\"\n</code></pre>\n\n<p>And it'll happily convert number to string for you.</p>\n\n<p>I think this behavior is left in for backward compatibility.</p>\n\n<p>When you program in VB, always use an ampersand to concatenate strings.</p>\n" }, { "answer_id": 271585, "author": "Loris", "author_id": 23824, "author_profile": "https://Stackoverflow.com/users/23824", "pm_score": 2, "selected": false, "text": "<p>I'd suggest to stay away from raw string concatenation, if possible.</p>\n\n<p>Good alternatives are using string.format:</p>\n\n<pre><code>str = String.Format(\"Hello {0} workd\", Number)\n</code></pre>\n\n<p>Or using the System.Text.StringBuilder class, which is also more efficient on larger string concatenations.</p>\n\n<p>Both automatically cast their parameters to string.</p>\n" } ]
2008/11/07
[ "https://Stackoverflow.com/questions/271520", "https://Stackoverflow.com", "https://Stackoverflow.com/users/15233/" ]
I could do this in C#.. ``` int number = 2; string str = "Hello " + number + " world"; ``` ..and str ends up as "Hello 2 world". In VB.NET i could do this.. ``` Dim number As Integer = 2 Dim str As String = "Hello " + number + " world" ``` ..but I get an InvalidCastException "Conversion from string "Hello " to type 'Double' is not valid." I am aware that I should use .ToString() in both cases, but whats going on here with the code as it is?
In VB I believe the string concatenation operator is & rather than + so try this: ``` Dim number As Integer = 2 Dim str As String = "Hello " & number & " world" ``` Basically when VB sees + I suspect it tries do numeric addition or use the addition operator defined in a type (or no doubt other more complicated things, based on options...) Note that `System.String` doesn't define an addition operator - it's all hidden in the compiler by calls to `String.Concat`. (This allows much more efficient concatenation of multiple strings.)
271,526
<p>I use <code>x != null</code> to avoid <a href="https://docs.oracle.com/javase/9/docs/api/java/lang/NullPointerException.html" rel="noreferrer"><code>NullPointerException</code></a>. Is there an alternative?</p> <pre class="lang-java prettyprint-override"><code>if (x != null) { // ... } </code></pre>
[ { "answer_id": 271553, "author": "Jim Nelson", "author_id": 32168, "author_profile": "https://Stackoverflow.com/users/32168", "pm_score": 6, "selected": false, "text": "<p>Rather than Null Object Pattern -- which has its uses -- you might consider situations where the null object is a bug.</p>\n\n<p>When the exception is thrown, examine the stack trace and work through the bug.</p>\n" }, { "answer_id": 271557, "author": "pgras", "author_id": 12719, "author_profile": "https://Stackoverflow.com/users/12719", "pm_score": 7, "selected": false, "text": "<ul>\n<li>If you consider an object should not be null (or it is a bug) use an assert.</li>\n<li>If your method doesn't accept null params say it in the javadoc and use an assert.</li>\n</ul>\n\n<p>You have to check for object != null only if you want to handle the case where the object may be null...</p>\n\n<p>There is a proposal to add new annotations in Java7 to help with null / notnull params:\n<a href=\"http://tech.puredanger.com/java7/#jsr308\" rel=\"noreferrer\">http://tech.puredanger.com/java7/#jsr308</a></p>\n" }, { "answer_id": 271576, "author": "Johannes Schaub - litb", "author_id": 34509, "author_profile": "https://Stackoverflow.com/users/34509", "pm_score": 6, "selected": false, "text": "<p>Sometimes, you have methods that operate on its parameters that define a symmetric operation:</p>\n\n<pre><code>a.f(b); &lt;-&gt; b.f(a);\n</code></pre>\n\n<p>If you know b can never be null, you can just swap it. It is most useful for equals:\nInstead of <code>foo.equals(\"bar\");</code> better do <code>\"bar\".equals(foo);</code>.</p>\n" }, { "answer_id": 271587, "author": "javamonkey79", "author_id": 27657, "author_profile": "https://Stackoverflow.com/users/27657", "pm_score": 7, "selected": false, "text": "<p>Depending on what kind of objects you are checking you may be able to use some of the classes in the apache commons such as: <a href=\"http://commons.apache.org/lang/\" rel=\"noreferrer\">apache commons lang</a> and <a href=\"http://commons.apache.org/collections/\" rel=\"noreferrer\">apache commons collections</a></p>\n\n<p>Example: </p>\n\n<pre><code>String foo;\n...\nif( StringUtils.isBlank( foo ) ) {\n ///do something\n}\n</code></pre>\n\n<p>or (depending on what you need to check):</p>\n\n<pre><code>String foo;\n...\nif( StringUtils.isEmpty( foo ) ) {\n ///do something\n}\n</code></pre>\n\n<p>The StringUtils class is only one of many; there are quite a few good classes in the commons that do null safe manipulation.</p>\n\n<p>Here follows an example of how you can use null vallidation in JAVA when you include apache library(commons-lang-2.4.jar)</p>\n\n<pre><code>public DOCUMENT read(String xml, ValidationEventHandler validationEventHandler) {\n Validate.notNull(validationEventHandler,\"ValidationHandler not Injected\");\n return read(new StringReader(xml), true, validationEventHandler);\n}\n</code></pre>\n\n<p>And if you are using Spring, Spring also has the same functionality in its package, see library(spring-2.4.6.jar) </p>\n\n<p>Example on how to use this static classf from spring(org.springframework.util.Assert)</p>\n\n<pre><code>Assert.notNull(validationEventHandler,\"ValidationHandler not Injected\");\n</code></pre>\n" }, { "answer_id": 271616, "author": "myplacedk", "author_id": 28683, "author_profile": "https://Stackoverflow.com/users/28683", "pm_score": 8, "selected": false, "text": "<h2>If null-values are not allowed</h2>\n\n<p>If your method is called externally, start with something like this:</p>\n\n<pre><code>public void method(Object object) {\n if (object == null) {\n throw new IllegalArgumentException(\"...\");\n }\n</code></pre>\n\n<p>Then, in the rest of that method, you'll know that <code>object</code> is not null.</p>\n\n<p>If it is an internal method (not part of an API), just document that it cannot be null, and that's it.</p>\n\n<p>Example:</p>\n\n<pre><code>public String getFirst3Chars(String text) {\n return text.subString(0, 3);\n}\n</code></pre>\n\n<p>However, if your method just passes the value on, and the next method passes it on etc. it could get problematic. In that case you may want to check the argument as above.</p>\n\n<h2>If null is allowed</h2>\n\n<p>This really depends. If find that I often do something like this:</p>\n\n<pre><code>if (object == null) {\n // something\n} else {\n // something else\n}\n</code></pre>\n\n<p>So I branch, and do two completely different things. There is no ugly code snippet, because I really need to do two different things depending on the data. For example, should I work on the input, or should I calculate a good default value?</p>\n\n<hr>\n\n<p>It's actually rare for me to use the idiom \"<code>if (object != null &amp;&amp; ...</code>\".</p>\n\n<p>It may be easier to give you examples, if you show examples of where you typically use the idiom.</p>\n" }, { "answer_id": 271617, "author": "xtofl", "author_id": 6610, "author_profile": "https://Stackoverflow.com/users/6610", "pm_score": 5, "selected": false, "text": "<p>Asking that question points out that you may be interested in error handling strategies. How and where to handle errors is a pervasive architectural question. There are several ways to do this.</p>\n<p>My favorite: allow the Exceptions to ripple through - catch them at the 'main loop' or in some other function with the appropriate responsibilities. Checking for error conditions and handling them appropriately can be seen as a specialized responsibility.</p>\n<p>Sure do have a look at Aspect Oriented Programming, too - they have neat ways to insert <code>if( o == null ) handleNull()</code> into your bytecode.</p>\n" }, { "answer_id": 271735, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 3, "selected": false, "text": "<p>Wherever you pass an array or a Vector, initialise these to empty ones, instead of null. - This way you can avoid lots of checking for null and all is good :)</p>\n\n<pre><code>public class NonNullThing {\n\n Vector vectorField = new Vector();\n\n int[] arrayField = new int[0];\n\n public NonNullThing() {\n\n // etc\n\n }\n\n}\n</code></pre>\n" }, { "answer_id": 271874, "author": "cletus", "author_id": 18393, "author_profile": "https://Stackoverflow.com/users/18393", "pm_score": 12, "selected": true, "text": "<p>This to me sounds like a reasonably common problem that junior to intermediate developers tend to face at some point: they either don't know or don't trust the contracts they are participating in and defensively overcheck for nulls. Additionally, when writing their own code, they tend to rely on returning nulls to indicate something thus requiring the caller to check for nulls.</p>\n<p>To put this another way, there are two instances where null checking comes up:</p>\n<ol>\n<li><p>Where null is a valid response in terms of the contract; and</p>\n</li>\n<li><p>Where it isn't a valid response.</p>\n</li>\n</ol>\n<p>(2) is easy. As of Java 1.7 you can use <a href=\"https://docs.oracle.com/en/java/javase/17/docs/api/java.base/java/util/Objects.html#requireNonNull(T)\" rel=\"noreferrer\"><code>Objects.requireNonNull(foo)</code></a>. (If you are stuck with a previous version then <a href=\"https://docs.oracle.com/javase/7/docs/technotes/guides/language/assert.html\" rel=\"noreferrer\"><code>assert</code>ions</a> may be a good alternative.)</p>\n<p>&quot;Proper&quot; usage of this method would be like below. The method returns the object passed into it and throws a <code>NullPointerException</code> if the object is null. This means that the returned value is always non-null. The method is primarily intended for validating parameters.</p>\n<pre><code>public Foo(Bar bar) {\n this.bar = Objects.requireNonNull(bar);\n}\n</code></pre>\n<p>It can also be used like an <code>assert</code>ion though since it throws an exception if the object is null. In both uses, a message can be added which will be shown in the exception. Below is using it like an assertion and providing a message.</p>\n<pre><code>Objects.requireNonNull(someobject, &quot;if someobject is null then something is wrong&quot;);\nsomeobject.doCalc();\n</code></pre>\n<p>Generally throwing a specific exception like <code>NullPointerException</code> when a value is null but shouldn't be is favorable to throwing a more general exception like <code>AssertionError</code>. This is the approach the Java library takes; favoring <code>NullPointerException</code> over <code>IllegalArgumentException</code> when an argument is not allowed to be null.</p>\n<p>(1) is a little harder. If you have no control over the code you're calling then you're stuck. If null is a valid response, you have to check for it.</p>\n<p>If it's code that you do control, however (and this is often the case), then it's a different story. Avoid using nulls as a response. With methods that return collections, it's easy: return empty collections (or arrays) instead of nulls pretty much all the time.</p>\n<p>With non-collections it might be harder. Consider this as an example: if you have these interfaces:</p>\n<pre><code>public interface Action {\n void doSomething();\n}\n\npublic interface Parser {\n Action findAction(String userInput);\n}\n</code></pre>\n<p>where Parser takes raw user input and finds something to do, perhaps if you're implementing a command line interface for something. Now you might make the contract that it returns null if there's no appropriate action. That leads the null checking you're talking about.</p>\n<p>An alternative solution is to never return null and instead use the <a href=\"https://en.wikipedia.org/wiki/Null_Object_pattern\" rel=\"noreferrer\">Null Object pattern</a>:</p>\n<pre><code>public class MyParser implements Parser {\n private static Action DO_NOTHING = new Action() {\n public void doSomething() { /* do nothing */ }\n };\n\n public Action findAction(String userInput) {\n // ...\n if ( /* we can't find any actions */ ) {\n return DO_NOTHING;\n }\n }\n}\n</code></pre>\n<p>Compare:</p>\n<pre><code>Parser parser = ParserFactory.getParser();\nif (parser == null) {\n // now what?\n // this would be an example of where null isn't (or shouldn't be) a valid response\n}\nAction action = parser.findAction(someInput);\nif (action == null) {\n // do nothing\n} else {\n action.doSomething();\n}\n</code></pre>\n<p>to</p>\n<pre><code>ParserFactory.getParser().findAction(someInput).doSomething();\n</code></pre>\n<p>which is a much better design because it leads to more concise code.</p>\n<p>That said, perhaps it is entirely appropriate for the findAction() method to throw an Exception with a meaningful error message -- especially in this case where you are relying on user input. It would be much better for the findAction method to throw an Exception than for the calling method to blow up with a simple NullPointerException with no explanation.</p>\n<pre><code>try {\n ParserFactory.getParser().findAction(someInput).doSomething();\n} catch(ActionNotFoundException anfe) {\n userConsole.err(anfe.getMessage());\n}\n</code></pre>\n<p>Or if you think the try/catch mechanism is too ugly, rather than Do Nothing your default action should provide feedback to the user.</p>\n<pre><code>public Action findAction(final String userInput) {\n /* Code to return requested Action if found */\n return new Action() {\n public void doSomething() {\n userConsole.err(&quot;Action not found: &quot; + userInput);\n }\n }\n}\n</code></pre>\n" }, { "answer_id": 275869, "author": "echox", "author_id": 35915, "author_profile": "https://Stackoverflow.com/users/35915", "pm_score": 8, "selected": false, "text": "<p>Only for this situation -</p>\n\n<p>Not checking if a variable is null before invoking an equals method (a string compare example below):</p>\n\n<pre><code>if ( foo.equals(\"bar\") ) {\n // ...\n}\n</code></pre>\n\n<p>will result in a <code>NullPointerException</code> if <code>foo</code> doesn't exist.</p>\n\n<p>You can avoid that if you compare your <code>String</code>s like this:</p>\n\n<pre><code>if ( \"bar\".equals(foo) ) {\n // ...\n}\n</code></pre>\n" }, { "answer_id": 288524, "author": "OscarRyz", "author_id": 20654, "author_profile": "https://Stackoverflow.com/users/20654", "pm_score": 5, "selected": false, "text": "<p>I've tried the <code>NullObjectPattern</code> but for me is not always the best way to go. There are sometimes when a \"no action\" is not appropiate.</p>\n\n<p><code>NullPointerException</code> is a <em>Runtime exception</em> that means it's developers fault and with enough experience it tells you exactly where is the error.</p>\n\n<p>Now to the answer:</p>\n\n<p>Try to make all your attributes and its accessors as private as possible or avoid to expose them to the clients at all. You can have the argument values in the constructor of course, but by reducing the scope you don't let the client class pass an invalid value. If you need to modify the values, you can always create a new <code>object</code>. You check the values in the constructor only <strong>once</strong> and in the rest of the methods you can be almost sure that the values are not null.</p>\n\n<p>Of course, experience is the better way to understand and apply this suggestion.</p>\n\n<p>Byte!</p>\n" }, { "answer_id": 397740, "author": "user2427", "author_id": 1356709, "author_profile": "https://Stackoverflow.com/users/1356709", "pm_score": 6, "selected": false, "text": "<p>The Google collections framework offers a good and elegant way to achieve the null check.</p>\n\n<p>There is a method in a library class like this:</p>\n\n<pre><code>static &lt;T&gt; T checkNotNull(T e) {\n if (e == null) {\n throw new NullPointerException();\n }\n return e;\n}\n</code></pre>\n\n<p>And the usage is (with <code>import static</code>):</p>\n\n<pre><code>...\nvoid foo(int a, Person p) {\n if (checkNotNull(p).getAge() &gt; a) {\n ...\n }\n else {\n ...\n }\n}\n...\n</code></pre>\n\n<p>Or in your example:</p>\n\n<pre><code>checkNotNull(someobject).doCalc();\n</code></pre>\n" }, { "answer_id": 452820, "author": "erickson", "author_id": 3474, "author_profile": "https://Stackoverflow.com/users/3474", "pm_score": 8, "selected": false, "text": "<p>Wow, I almost hate to add another answer when we have 57 different ways to recommend the <code>NullObject pattern</code>, but I think that some people interested in this question may like to know that there is a proposal on the table for Java 7 to add <a href=\"http://tech.puredanger.com/java7/#null\" rel=\"noreferrer\">\"null-safe handling\"</a>&mdash;a streamlined syntax for if-not-equal-null logic.</p>\n\n<p>The example given by Alex Miller looks like this:</p>\n\n<pre><code>public String getPostcode(Person person) { \n return person?.getAddress()?.getPostcode(); \n} \n</code></pre>\n\n<p>The <code>?.</code> means only de-reference the left identifier if it is not null, otherwise evaluate the remainder of the expression as <code>null</code>. Some people, like Java Posse member Dick Wall and the <a href=\"http://blog.joda.org/2008/12/jdk-7-language-changes-devoxx-votes_3751.html\" rel=\"noreferrer\">voters at Devoxx</a> really love this proposal, but there is opposition too, on the grounds that it will actually encourage more use of <code>null</code> as a sentinel value.</p>\n\n<hr>\n\n<p><em>Update:</em> An <a href=\"http://mail.openjdk.java.net/pipermail/coin-dev/2009-March/000047.html\" rel=\"noreferrer\">official proposal</a> for a null-safe operator in Java 7 has been submitted under <a href=\"http://openjdk.java.net/projects/coin/\" rel=\"noreferrer\">Project Coin.</a> The syntax is a little different than the example above, but it's the same notion.</p>\n\n<hr>\n\n<p><em>Update:</em> The null-safe operator proposal didn't make it into Project Coin. So, you won't be seeing this syntax in Java 7.</p>\n" }, { "answer_id": 1202969, "author": "Michael Borgwardt", "author_id": 16883, "author_profile": "https://Stackoverflow.com/users/16883", "pm_score": 6, "selected": false, "text": "<p>Ultimately, the only way to completely solve this problem is by using a different programming language:</p>\n\n<ul>\n<li>In Objective-C, you can do the equivalent of invoking a method on <code>nil</code>, and absolutely nothing will happen. This makes most null checks unnecessary, but it can make errors much harder to diagnose.</li>\n<li>In <a href=\"http://nice.sourceforge.net/safety.html#id2487946\" rel=\"noreferrer\">Nice</a>, a Java-derived language, there are two versions of all types: a potentially-null version and a not-null version. You can only invoke methods on not-null types. Potentially-null types can be converted to not-null types through explicit checking for null. This makes it much easier to know where null checks are necessary and where they aren't.</li>\n</ul>\n" }, { "answer_id": 2064441, "author": "thSoft", "author_id": 90874, "author_profile": "https://Stackoverflow.com/users/90874", "pm_score": 8, "selected": false, "text": "<h2>If undefined values are not permitted:</h2>\n\n<p>You might configure your IDE to warn you about potential null dereferencing. E.g. in Eclipse, see <em>Preferences > Java > Compiler > Errors/Warnings/Null analysis</em>.</p>\n\n<h2>If undefined values are permitted:</h2>\n\n<p><em>If you want to define a new API where undefined values make sense</em>, use the <a href=\"http://www.codecommit.com/blog/scala/the-option-pattern\" rel=\"noreferrer\">Option Pattern</a> (may be familiar from functional languages). It has the following advantages:</p>\n\n<ul>\n<li>It is stated explicitly in the API whether an input or output exists or not.</li>\n<li>The compiler forces you to handle the \"undefined\" case.</li>\n<li><a href=\"http://james-iry.blogspot.com/2007/08/martians-vs-monads-null-considered.html\" rel=\"noreferrer\">Option is a monad</a>, so there is no need for verbose null checking, just use map/foreach/getOrElse or a similar combinator to safely use the value <a href=\"http://blog.tackley.net/2010/09/option-in-scala-vs-null-in-java.html\" rel=\"noreferrer\">(example)</a>.</li>\n</ul>\n\n<p>Java 8 has a built-in <a href=\"http://docs.oracle.com/javase/8/docs/api/java/util/Optional.html\" rel=\"noreferrer\"><code>Optional</code></a> class (recommended); for earlier versions, there are library alternatives, for example <a href=\"http://code.google.com/p/guava-libraries/wiki/UsingAndAvoidingNullExplained\" rel=\"noreferrer\">Guava</a>'s <a href=\"https://google.github.io/guava/releases/19.0/api/docs/com/google/common/base/Optional.html\" rel=\"noreferrer\"><code>Optional</code></a> or <a href=\"http://code.google.com/p/functionaljava\" rel=\"noreferrer\">FunctionalJava</a>'s <a href=\"http://www.functionaljava.org/javadoc/4.4/functionaljava/fj/data/Option.html\" rel=\"noreferrer\"><code>Option</code></a>. But like many functional-style patterns, using Option in Java (even 8) results in quite some boilerplate, which you can reduce using a less verbose JVM language, e.g. Scala or Xtend.</p>\n\n<p><em>If you have to deal with an API which might return nulls</em>, you can't do much in Java. Xtend and Groovy have the <a href=\"https://www.eclipse.org/xtend/documentation.html#operators\" rel=\"noreferrer\">Elvis operator</a> <code>?:</code> and the <a href=\"https://www.eclipse.org/xtend/documentation.html#nullSafeFeatureCalls\" rel=\"noreferrer\">null-safe dereference operator</a> <code>?.</code>, but note that this returns null in case of a null reference, so it just \"defers\" the proper handling of null.</p>\n" }, { "answer_id": 2386013, "author": "Luca Molteni", "author_id": 4206, "author_profile": "https://Stackoverflow.com/users/4206", "pm_score": 9, "selected": false, "text": "<p>If you use (or planning to use) a Java IDE like <a href=\"https://www.jetbrains.com/idea/\" rel=\"noreferrer\">JetBrains IntelliJ IDEA</a>, <a href=\"https://www.eclipse.org/\" rel=\"noreferrer\">Eclipse</a> or <a href=\"https://netbeans.org/\" rel=\"noreferrer\">Netbeans</a> or a tool like findbugs then you can use annotations to solve this problem.</p>\n\n<p>Basically, you've got <code>@Nullable</code> and <code>@NotNull</code>.</p>\n\n<p>You can use in method and parameters, like this:</p>\n\n<pre><code>@NotNull public static String helloWorld() {\n return \"Hello World\";\n}\n</code></pre>\n\n<p>or</p>\n\n<pre><code>@Nullable public static String helloWorld() {\n return \"Hello World\";\n}\n</code></pre>\n\n<p>The second example won't compile (in IntelliJ IDEA).</p>\n\n<p>When you use the first <code>helloWorld()</code> function in another piece of code:</p>\n\n<pre><code>public static void main(String[] args)\n{\n String result = helloWorld();\n if(result != null) {\n System.out.println(result);\n }\n}\n</code></pre>\n\n<p>Now the IntelliJ IDEA compiler will tell you that the check is useless, since the <code>helloWorld()</code> function won't return <code>null</code>, ever.</p>\n\n<p>Using parameter</p>\n\n<pre><code>void someMethod(@NotNull someParameter) { }\n</code></pre>\n\n<p>if you write something like:</p>\n\n<pre><code>someMethod(null);\n</code></pre>\n\n<p>This won't compile.</p>\n\n<p>Last example using <code>@Nullable</code></p>\n\n<pre><code>@Nullable iWantToDestroyEverything() { return null; }\n</code></pre>\n\n<p>Doing this</p>\n\n<pre><code>iWantToDestroyEverything().something();\n</code></pre>\n\n<p>And you can be sure that this won't happen. :)</p>\n\n<p>It's a nice way to let the compiler check something more than it usually does and to enforce your contracts to be stronger. Unfortunately, it's not supported by all the compilers.</p>\n\n<p>In IntelliJ IDEA 10.5 and on, they added support for any other <code>@Nullable</code> <code>@NotNull</code> implementations.</p>\n\n<p>See blog post <em><a href=\"https://blog.jetbrains.com/idea/2011/03/more-flexible-and-configurable-nullublenotnull-annotations/\" rel=\"noreferrer\">More flexible and configurable @Nullable/@NotNull annotations</a></em>.</p>\n" }, { "answer_id": 2874026, "author": "daniel", "author_id": 346135, "author_profile": "https://Stackoverflow.com/users/346135", "pm_score": 0, "selected": false, "text": "<p>For utility classes, you can check that parameters are not null.</p>\n\n<p>In all other cases, you may not have to. Use encapsulation as much as possible, thus reducing the places you feel tempted to check for null.</p>\n" }, { "answer_id": 3499225, "author": "fastcodejava", "author_id": 184730, "author_profile": "https://Stackoverflow.com/users/184730", "pm_score": 5, "selected": false, "text": "<p>In addition to using <code>assert</code> you can use the following:</p>\n\n<pre><code>if (someobject == null) {\n // Handle null here then move on.\n}\n</code></pre>\n\n<p>This is slightly better than:</p>\n\n<pre><code>if (someobject != null) {\n .....\n .....\n\n\n\n .....\n}\n</code></pre>\n" }, { "answer_id": 3925191, "author": "tltester", "author_id": 474659, "author_profile": "https://Stackoverflow.com/users/474659", "pm_score": 4, "selected": false, "text": "<pre><code>public static &lt;T&gt; T ifNull(T toCheck, T ifNull) {\n if (toCheck == null) {\n return ifNull;\n }\n return toCheck;\n}\n</code></pre>\n" }, { "answer_id": 5023357, "author": "LarryN", "author_id": 10324, "author_profile": "https://Stackoverflow.com/users/10324", "pm_score": -1, "selected": false, "text": "<p>Another suggestion is to program defensively - where your classes/functions provide default values that are known and safe, and where null is reserved for true errors/exceptions.</p>\n\n<p>For example, instead of functions that return Strings returning null when there is a problem (say converting a number to a string), have them return an empty String (\"\"). You still have to test the return value before proceeding, but there would be no special cases for exceptions. An additional benefit of this style of programming is that your program will be able to differentiate and respond accordingly between normal operations and exceptions.</p>\n" }, { "answer_id": 5266443, "author": "Leen Toelen", "author_id": 250816, "author_profile": "https://Stackoverflow.com/users/250816", "pm_score": 3, "selected": false, "text": "<p>You can use <a href=\"http://findbugs.sourceforge.net\" rel=\"nofollow noreferrer\">FindBugs</a>. They also have an <a href=\"http://en.wikipedia.org/wiki/Eclipse_%28software%29\" rel=\"nofollow noreferrer\">Eclipse</a> plugin) that helps you find duplicate null checks (among other things), but keep in mind that sometimes you should opt for defensive programming. There is also <a href=\"http://code.google.com/p/cofoja/\" rel=\"nofollow noreferrer\">Contracts for Java</a> which may be helpful.</p>\n" }, { "answer_id": 5311857, "author": "Oleg", "author_id": 634475, "author_profile": "https://Stackoverflow.com/users/634475", "pm_score": 5, "selected": false, "text": "<p>Common \"problem\" in Java indeed.</p>\n\n<p>First, my thoughts on this:</p>\n\n<p>I consider that it is bad to \"eat\" something when NULL was passed where NULL isn't a valid value. If you're not exiting the method with some sort of error then it means nothing went wrong in your method which is not true. Then you probably return null in this case, and in the receiving method you again check for null, and it never ends, and you end up with \"if != null\", etc..</p>\n\n<p>So, IMHO, null must be a critical error which prevents further execution (that is, where null is not a valid value).</p>\n\n<p>The way I solve this problem is this:</p>\n\n<p>First, I follow this convention:</p>\n\n<ol>\n<li>All public methods / API always check its arguments for null</li>\n<li>All private methods do not check for null since they are controlled methods (just let die with nullpointer exception in case it wasn't handled above)</li>\n<li>The only other methods which do not check for null are utility methods. They are public, but if you call them for some reason, you know what parameters you pass. This is like trying to boil water in the kettle without providing water...</li>\n</ol>\n\n<p>And finally, in the code, the first line of the public method goes like this:</p>\n\n<pre><code>ValidationUtils.getNullValidator().addParam(plans, \"plans\").addParam(persons, \"persons\").validate();\n</code></pre>\n\n<p>Note that addParam() returns self, so that you can add more parameters to check.</p>\n\n<p>Method <code>validate()</code> will throw checked <code>ValidationException</code> if any of the parameters is null (checked or unchecked is more a design/taste issue, but my <code>ValidationException</code> is checked).</p>\n\n<pre><code>void validate() throws ValidationException;\n</code></pre>\n\n<p>The message will contain the following text if, for example, \"plans\" is null:</p>\n\n<p>\"<strong>Illegal argument value null is encountered for parameter [plans]</strong>\"</p>\n\n<p>As you can see, the second value in the addParam() method (string) is needed for the user message, because you cannot easily detect passed-in variable name, even with reflection (not subject of this post anyway...).</p>\n\n<p>And yes, we know that beyond this line we will no longer encounter a null value so we just safely invoke methods on those objects.</p>\n\n<p>This way, the code is clean, easy maintainable and readable.</p>\n" }, { "answer_id": 6101200, "author": "Alex Worden", "author_id": 181551, "author_profile": "https://Stackoverflow.com/users/181551", "pm_score": 7, "selected": false, "text": "<p>I'm a fan of &quot;fail fast&quot; code. Ask yourself - are you doing something useful in the case where the parameter is null? If you don't have a clear answer for what your code should do in that case... i.e. - it should never be null in the first place, then ignore it and allow a <code>NullPointerException</code> to be thrown. The calling code will make just as much sense of an NPE as it would an <code>IllegalArgumentException</code>, but it'll be easier for the developer to debug and understand what went wrong if an NPE is thrown rather than your code attempting to execute some other unexpected contingency logic - which ultimately results in the application failing anyway.</p>\n" }, { "answer_id": 7140229, "author": "Mr Palo", "author_id": 904825, "author_profile": "https://Stackoverflow.com/users/904825", "pm_score": 5, "selected": false, "text": "<p>I like articles from Nat Pryce. Here are the links:</p>\n\n<ul>\n<li><a href=\"http://www.natpryce.com/articles/000778.html\" rel=\"noreferrer\">Avoiding Nulls with Polymorphic Dispatch</a></li>\n<li><a href=\"http://www.natpryce.com/articles/000777.html\" rel=\"noreferrer\">Avoiding Nulls with \"Tell, Don't Ask\" Style</a></li>\n</ul>\n\n<p>In the articles there is also a link to a Git repository for a Java Maybe Type which I find interesting, but I don't think it alone could decrease the\nchecking code bloat. After doing some research on the Internet, I think <strong>!= null</strong> code bloat could be decreased mainly by careful design.</p>\n" }, { "answer_id": 7847199, "author": "jeha", "author_id": 571271, "author_profile": "https://Stackoverflow.com/users/571271", "pm_score": 3, "selected": false, "text": "<p>One more alternative:</p>\n\n<p>The following simple function helps to hide the null-check (I don't know why, but I haven't found it as part of the same <em>common</em> library):</p>\n\n<pre><code>public static &lt;T&gt; boolean isNull(T argument) {\n return (argument == null);\n}\n</code></pre>\n\n<p>You could now write</p>\n\n<pre><code>if (!isNull(someobject)) {\n someobject.doCalc();\n}\n</code></pre>\n\n<p>which is IMO a better way of expressing <code>!= null</code>.</p>\n" }, { "answer_id": 8212184, "author": "Mike", "author_id": 448078, "author_profile": "https://Stackoverflow.com/users/448078", "pm_score": 6, "selected": false, "text": "<p>Null is not a 'problem'. It is an integral part of a <a href=\"http://en.wikipedia.org/wiki/Functional_completeness\" rel=\"noreferrer\">complete</a> modeling tool set. Software aims to model the complexity of the world and null bears its burden. <strong>Null indicates 'No data' or 'Unknown'</strong> in Java and the like. So it is appropriate to use nulls for these purposes. I don't prefer the 'Null object' pattern; I think it rise the '<a href=\"http://en.wikipedia.org/wiki/Who_will_guard_the_guards%3F\" rel=\"noreferrer\">who will guard\nthe guardians</a>' problem. <br/>\nIf you ask me what is the name of my girlfriend I'll tell you that I have no girlfriend. In the Java language I'll return null. \nAn alternative would be to throw meaningful exception to indicate some problem that can't be (or don't want to be) solved right there and delegate it somewhere higher in the stack to retry or report data access error to the user. </p>\n\n<ol>\n<li><p><strong>For an 'unknown question' give 'unknown answer'.</strong> (Be null-safe where this is correct from business point of view) Checking arguments for null once inside a method before usage relieves multiple callers from checking them before a call.</p>\n\n<pre><code>public Photo getPhotoOfThePerson(Person person) {\n if (person == null)\n return null;\n // Grabbing some resources or intensive calculation\n // using person object anyhow.\n}\n</code></pre>\n\n<p>Previous leads to normal logic flow to get no photo of a non-existent girlfriend from my photo library.</p>\n\n<pre><code>getPhotoOfThePerson(me.getGirlfriend())\n</code></pre>\n\n<p>And it fits with new coming Java API (looking forward)</p>\n\n<pre><code>getPhotoByName(me.getGirlfriend()?.getName())\n</code></pre>\n\n<p>While it is rather 'normal business flow' not to find photo stored into the DB for some person, I used to use pairs like below for some other cases</p>\n\n<pre><code>public static MyEnum parseMyEnum(String value); // throws IllegalArgumentException\npublic static MyEnum parseMyEnumOrNull(String value);\n</code></pre>\n\n<p>And don't loathe to type <code>&lt;alt&gt; + &lt;shift&gt; + &lt;j&gt;</code> (generate javadoc in Eclipse) and write three additional words for you public API. This will be more than enough for all but those who don't read documentation.</p>\n\n<pre><code>/**\n * @return photo or null\n */\n</code></pre>\n\n<p>or</p>\n\n<pre><code>/**\n * @return photo, never null\n */\n</code></pre></li>\n<li><p><strong>This is rather theoretical case and in most cases you should prefer java null safe API (in case it will be released in another 10 years), but <code>NullPointerException</code> is subclass of an <code>Exception</code>.</strong> Thus it is a form of <code>Throwable</code> that indicates conditions that a reasonable application might want to catch (<a href=\"http://javasourcecode.org/html/open-source/jdk/jdk-6u23/java/lang/Exception.html\" rel=\"noreferrer\">javadoc</a>)! To use the first most advantage of exceptions and separate error-handling code from 'regular' code (<a href=\"http://docs.oracle.com/javase/tutorial/essential/exceptions/advantages.html\" rel=\"noreferrer\">according to creators of Java</a>) it is appropriate, as for me, to catch <code>NullPointerException</code>.</p>\n\n<pre><code>public Photo getGirlfriendPhoto() {\n try {\n return appContext.getPhotoDataSource().getPhotoByName(me.getGirlfriend().getName());\n } catch (NullPointerException e) {\n return null;\n }\n}\n</code></pre>\n\n<p>Questions could arise:</p>\n\n<p>Q. What if <code>getPhotoDataSource()</code> returns null?<br>\nA. It is up to business logic. If I fail to find a photo album I'll show you no photos. What if appContext is not initialized? This method's business logic puts up with this. If the same logic should be more strict then throwing an exception it is part of the business logic and explicit check for null should be used (case 3). The <strong>new Java Null-safe API fits better here to specify selectively what implies and what does not imply to be initialized</strong> to be fail-fast in case of programmer errors.</p>\n\n<p>Q. Redundant code could be executed and unnecessary resources could be grabbed.<br>\nA. It could take place if <code>getPhotoByName()</code> would try to open a database connection, create <code>PreparedStatement</code> and use the person name as an SQL parameter at last. The approach <em>for an unknown question gives an unknown answer</em> (case 1) works here. Before grabbing resources the method should check parameters and return 'unknown' result if needed.</p>\n\n<p>Q. This approach has a performance penalty due to the try closure opening.<br>\nA. Software should be easy to understand and modify firstly. Only after this, one could think about performance, and only if needed! and where needed! (<a href=\"http://www.amazon.co.uk/Code-Complete-Practical-Handbook-Construction/dp/0735619670/ref=dp_ob_title_bk\" rel=\"noreferrer\">source</a>), and many others).</p>\n\n<p>PS. This approach will be as reasonable to use as the <em>separate error-handling code from \"regular\" code</em> principle is reasonable to use in some place. Consider the next example:</p>\n\n<pre><code>public SomeValue calculateSomeValueUsingSophisticatedLogic(Predicate predicate) {\n try {\n Result1 result1 = performSomeCalculation(predicate);\n Result2 result2 = performSomeOtherCalculation(result1.getSomeProperty());\n Result3 result3 = performThirdCalculation(result2.getSomeProperty());\n Result4 result4 = performLastCalculation(result3.getSomeProperty());\n return result4.getSomeProperty();\n } catch (NullPointerException e) {\n return null;\n }\n}\n\npublic SomeValue calculateSomeValueUsingSophisticatedLogic(Predicate predicate) {\n SomeValue result = null;\n if (predicate != null) {\n Result1 result1 = performSomeCalculation(predicate);\n if (result1 != null &amp;&amp; result1.getSomeProperty() != null) {\n Result2 result2 = performSomeOtherCalculation(result1.getSomeProperty());\n if (result2 != null &amp;&amp; result2.getSomeProperty() != null) {\n Result3 result3 = performThirdCalculation(result2.getSomeProperty());\n if (result3 != null &amp;&amp; result3.getSomeProperty() != null) {\n Result4 result4 = performLastCalculation(result3.getSomeProperty());\n if (result4 != null) {\n result = result4.getSomeProperty();\n }\n }\n }\n }\n }\n return result;\n}\n</code></pre>\n\n<p>PPS. For those fast to downvote (and not so fast to read documentation) I would like to say that I've never caught a null-pointer exception (NPE) in my life. But this possibility was <strong>intentionally designed</strong> by the Java creators because NPE is a subclass of <code>Exception</code>. We have a precedent in Java history when <code>ThreadDeath</code> is an <code>Error</code> not because it is actually an application error, but solely because it was not intended to be caught! How much NPE fits to be an <code>Error</code> than <code>ThreadDeath</code>! But it is not.</p></li>\n<li><p><strong>Check for 'No data' only if business logic implies it.</strong></p>\n\n<pre><code>public void updatePersonPhoneNumber(Long personId, String phoneNumber) {\n if (personId == null)\n return;\n DataSource dataSource = appContext.getStuffDataSource();\n Person person = dataSource.getPersonById(personId);\n if (person != null) {\n person.setPhoneNumber(phoneNumber);\n dataSource.updatePerson(person);\n } else {\n Person = new Person(personId);\n person.setPhoneNumber(phoneNumber);\n dataSource.insertPerson(person);\n }\n}\n</code></pre>\n\n<p>and</p>\n\n<pre><code>public void updatePersonPhoneNumber(Long personId, String phoneNumber) {\n if (personId == null)\n return;\n DataSource dataSource = appContext.getStuffDataSource();\n Person person = dataSource.getPersonById(personId);\n if (person == null)\n throw new SomeReasonableUserException(\"What are you thinking about ???\");\n person.setPhoneNumber(phoneNumber);\n dataSource.updatePerson(person);\n}\n</code></pre>\n\n<p>If appContext or dataSource is not initialized unhandled runtime NullPointerException will kill current thread and will be processed by <a href=\"https://docs.oracle.com/javase/7/docs/api/java/lang/Thread.UncaughtExceptionHandler.html\" rel=\"noreferrer\">Thread.defaultUncaughtExceptionHandler</a> (for you to define and use your favorite logger or other notification mechanizm). If not set, <a href=\"https://docs.oracle.com/javase/7/docs/api/java/lang/ThreadGroup.html#uncaughtException(java.lang.Thread,%20java.lang.Throwable)\" rel=\"noreferrer\">ThreadGroup#uncaughtException</a> will print stacktrace to system err. One should monitor application error log and open Jira issue for each unhandled exception which in fact is application error. Programmer should fix bug somewhere in initialization stuff.</p></li>\n</ol>\n" }, { "answer_id": 9845966, "author": "Murat Derya Özen", "author_id": 396216, "author_profile": "https://Stackoverflow.com/users/396216", "pm_score": 5, "selected": false, "text": "<p>Guava, a very useful core library by Google, has a nice and useful API to avoid nulls. I find <a href=\"http://code.google.com/p/guava-libraries/wiki/UsingAndAvoidingNullExplained\" rel=\"noreferrer\">UsingAndAvoidingNullExplained</a> very helpful.</p>\n\n<p>As explained in the wiki:</p>\n\n<blockquote>\n <p><code>Optional&lt;T&gt;</code> is a way of replacing a nullable T reference with a\n non-null value. An Optional may either contain a non-null T reference\n (in which case we say the reference is \"present\"), or it may contain\n nothing (in which case we say the reference is \"absent\"). It is never\n said to \"contain null.\"</p>\n</blockquote>\n\n<p>Usage:</p>\n\n<pre><code>Optional&lt;Integer&gt; possible = Optional.of(5);\npossible.isPresent(); // returns true\npossible.get(); // returns 5\n</code></pre>\n" }, { "answer_id": 9846141, "author": "Jochen", "author_id": 1088846, "author_profile": "https://Stackoverflow.com/users/1088846", "pm_score": 2, "selected": false, "text": "<p>You can also use the Checker Framework (with JDK 7 and beyond) to statically check for null values. This might solve a lot of problems, but requires running an extra tool that currently only works with OpenJDK AFAIK. <a href=\"https://checkerframework.org/\" rel=\"nofollow noreferrer\">https://checkerframework.org/</a></p>\n" }, { "answer_id": 11478811, "author": "Alex Vaz", "author_id": 1022180, "author_profile": "https://Stackoverflow.com/users/1022180", "pm_score": 2, "selected": false, "text": "<p>OK, I now this has been technically answered a million times but I have to say this because this is an un-ending discussion with Java programmers.</p>\n\n<p>Sorry but I disagree will almost all of above. The reason we have to be testing for null in Java is because must Java programmers don’t know how to handle memory. </p>\n\n<p>I say this because I have a long experience programming in C++ and we don’t do this. In other words, you don’t need to. And note that, in Java, if you hit a dangling pointer you get a normal exception; in C++ this exception normally is not caught and terminates the program.</p>\n\n<p>Don’t want to do this? Then follow some simple rules ala C/C++.</p>\n\n<p>Don’t instantiate things so easily, <em>think</em> that every \"new\" can get you in lots of trouble and FOLLOW these simple rules.</p>\n\n<p>A class shall access memory in only 3 ways -></p>\n\n<ol>\n<li><p>It can \"HAVE\" class members, and they will follow these rules:</p>\n\n<ol>\n<li>ALL \"HAS\" members are created \"new\" in the constructor.</li>\n<li>You will close /de allocate in destructor or equivalent close()\nfunction in Java for that same class and in NO other.</li>\n</ol></li>\n</ol>\n\n<p>This means that you need to have in mind (just like Java does) who is the owner or parent of each resource and respect that ownership. An object is only deleted by the class who created it. Also -></p>\n\n<ol start=\"2\">\n<li><p>Some members will be \"USED\" but not own or \"HAVE\". This are \"OWN\" in another class and passed as arguments to the constructor. Since these are owned by another class, we will NEVER delete or close this, only the parent can.</p></li>\n<li><p>A method in a class can also instantiate local objects for internal use which will NEVER pass out side of the class, or they should have been normal \"has\" objects.</p></li>\n</ol>\n\n<p>Finally for all this to work, you need to have a disciplined design with classes in hierarchy form and making no cycles.</p>\n\n<p>Under this design, AND following the above rules, there is no way that a child class in a hierarchy design will ever access a pointer which was destroyed, because that means that a parent was destroyed before a child, which the hierarchical acyclic design will not allow it.</p>\n\n<p>Finally, also remember when starting your system you should build from top to bottom of the hierarchy and destroy bottom to top. You will never have a null pointer anywhere, or someone is violating the rules.</p>\n" }, { "answer_id": 11896966, "author": "Stuart Marks", "author_id": 1441122, "author_profile": "https://Stackoverflow.com/users/1441122", "pm_score": 6, "selected": false, "text": "<p>Java 7 has a new <code>java.util.Objects</code> utility class on which there is a <code>requireNonNull()</code> method. All this does is throw a <code>NullPointerException</code> if its argument is null, but it cleans up the code a bit. Example:</p>\n\n<pre><code>Objects.requireNonNull(someObject);\nsomeObject.doCalc();\n</code></pre>\n\n<hr>\n\n<p>The method is most useful for <a href=\"https://stackoverflow.com/questions/3322638/is-it-okay-to-throw-nullpointerexception-programatically\">checking</a> just before an assignment in a constructor, where each use of it can save three lines of code:</p>\n\n<pre><code>Parent(Child child) {\n if (child == null) {\n throw new NullPointerException(\"child\");\n }\n this.child = child;\n}\n</code></pre>\n\n<p>becomes</p>\n\n<pre><code>Parent(Child child) {\n this.child = Objects.requireNonNull(child, \"child\");\n}\n</code></pre>\n" }, { "answer_id": 12390983, "author": "drzymala", "author_id": 1391568, "author_profile": "https://Stackoverflow.com/users/1391568", "pm_score": 1, "selected": false, "text": "<p>I prefer this</p>\n\n<pre><code>public void simpleFunc(SomeObject someObject){\n someObject = someObject != null ? someObject : new SomeObject(null);\n someObject.doSomething();\n}\n</code></pre>\n\n<p>Of course in my example SomeObject handles gracefully a null parameter. For example logging such event and doing nothing more.</p>\n" }, { "answer_id": 12946734, "author": "ianpojman", "author_id": 1342121, "author_profile": "https://Stackoverflow.com/users/1342121", "pm_score": 5, "selected": false, "text": "<p>Just don't ever use null. Don't allow it.</p>\n\n<p>In my classes, most fields and local variables have non-null default values, and I add contract statements (always-on asserts) everywhere in the code to make sure this is being enforced (since it's more succinct, and more expressive than letting it come up as an NPE and then having to resolve the line number, etc.).</p>\n\n<p>Once I adopted this practice, I noticed that the problems seemed to fix themselves. You'd catch things much earlier in the development process just by accident and realize you had a weak spot.. and more importantly.. it helps encapsulate different modules' concerns, different modules can 'trust' each other, and no more littering the code with <code>if = null else</code> constructs!</p>\n\n<p>This is defensive programming and results in much cleaner code in the long run. Always sanitize the data, e.g. here by enforcing rigid standards, and the problems go away.</p>\n\n<pre><code>class C {\n private final MyType mustBeSet;\n public C(MyType mything) {\n mustBeSet=Contract.notNull(mything);\n }\n private String name = \"&lt;unknown&gt;\";\n public void setName(String s) {\n name = Contract.notNull(s);\n }\n}\n\n\nclass Contract {\n public static &lt;T&gt; T notNull(T t) { if (t == null) { throw new ContractException(\"argument must be non-null\"); return t; }\n}\n</code></pre>\n\n<p>The contracts are like mini-unit tests which are always running, even in production, and when things fail, you know why, rather than a random NPE you have to somehow figure out.</p>\n" }, { "answer_id": 13676682, "author": "abishkar bhattarai", "author_id": 1564766, "author_profile": "https://Stackoverflow.com/users/1564766", "pm_score": 2, "selected": false, "text": "<p>You can use an interceptor before the method call. That is what <a href=\"https://en.wikipedia.org/wiki/Aspect-oriented_programming\" rel=\"nofollow\">aspect-oriented programming</a> focus on.</p>\n\n<p>Suppose M1(Object test) is a method and M2 is a method where we apply an aspect before a method call, <code>M2(Object test2)</code>. If <code>test2 != null</code> then call M1, otherwise do another thing. It works for all methods with whom you want to apply an aspect for. If you want to apply an aspect for an instance field and constructor you can use <a href=\"https://en.wikipedia.org/wiki/AspectJ\" rel=\"nofollow\">AspectJ</a>. <a href=\"http://en.wikipedia.org/wiki/Spring_Framework\" rel=\"nofollow\">Spring</a> can also be the best choice for a method aspect.</p>\n" }, { "answer_id": 14253016, "author": "Vinay Lodha", "author_id": 212665, "author_profile": "https://Stackoverflow.com/users/212665", "pm_score": 2, "selected": false, "text": "<p>First of all, we can't really remove all null conditions. We can reduce them using <code>@NotNull</code> and <code>@Nullable</code> annotations (<strong>as mentioned already</strong>). But this needs to be backed by some framework. This is where <a href=\"http://oval.sourceforge.net\" rel=\"nofollow\">OVal</a> can help.</p>\n\n<p>The basic idea is object/parameters/constructor should always satisfy preconditions. You can have a whole lot of preconditions such as <code>Nullable</code>, <code>NotNull</code> and OVal would take care that an object should be in a consistent state when invoked.</p>\n\n<p>I guess OVal internally uses AspectJ to validate the preconditions.</p>\n\n<pre><code>@Guarded\npublic class BusinessObject\n{\n public BusinessObject(@NotNull String name)\n {\n this.name = name;\n }\n\n ...\n}\n</code></pre>\n\n<p>For example,</p>\n\n<pre><code>// Throws a ConstraintsViolatedException because parameter name is null\nBusinessObject bo = new BusinessObject(null);\n</code></pre>\n" }, { "answer_id": 16218718, "author": "Pierre Henry", "author_id": 315677, "author_profile": "https://Stackoverflow.com/users/315677", "pm_score": 8, "selected": false, "text": "<p>With Java 8 comes the new <code>java.util.Optional</code> class that arguably solves some of the problem. One can at least say that it improves the readability of the code, and in the case of public APIs make the API's contract clearer to the client developer.</p>\n\n<p>They work like that:</p>\n\n<p>An optional object for a given type (<code>Fruit</code>) is created as the return type of a method. It can be empty or contain a <code>Fruit</code> object:</p>\n\n<pre><code>public static Optional&lt;Fruit&gt; find(String name, List&lt;Fruit&gt; fruits) {\n for (Fruit fruit : fruits) {\n if (fruit.getName().equals(name)) {\n return Optional.of(fruit);\n }\n }\n return Optional.empty();\n}\n</code></pre>\n\n<p>Now look at this code where we search a list of <code>Fruit</code> (<code>fruits</code>) for a given Fruit instance:</p>\n\n<pre><code>Optional&lt;Fruit&gt; found = find(\"lemon\", fruits);\nif (found.isPresent()) {\n Fruit fruit = found.get();\n String name = fruit.getName();\n}\n</code></pre>\n\n<p>You can use the <code>map()</code> operator to perform a computation on--or extract a value from--an optional object. <code>orElse()</code> lets you provide a fallback for missing values.</p>\n\n<pre><code>String nameOrNull = find(\"lemon\", fruits)\n .map(f -&gt; f.getName())\n .orElse(\"empty-name\");\n</code></pre>\n\n<p>Of course, the check for null/empty value is still necessary, but at least the developer is conscious that the value might be empty and the risk of forgetting to check is limited.</p>\n\n<p>In an API built from scratch using <code>Optional</code> whenever a return value might be empty, and returning a plain object only when it cannot be <code>null</code> (convention), the client code might abandon null checks on simple object return values...</p>\n\n<p>Of course <code>Optional</code> could also be used as a method argument, perhaps a better way to indicate optional arguments than 5 or 10 overloading methods in some cases.</p>\n\n<p><code>Optional</code> offers other convenient methods, such as <code>orElse</code> that allow the use of a default value, and <code>ifPresent</code> that works with <a href=\"https://en.wikipedia.org/wiki/Anonymous_function\" rel=\"noreferrer\">lambda expressions</a>.</p>\n\n<p>I invite you to read this article (my main source for writing this answer) in which the <code>NullPointerException</code> (and in general null pointer) problematic as well as the (partial) solution brought by <code>Optional</code> are well explained: <em><a href=\"http://java.dzone.com/articles/java-optional-objects\" rel=\"noreferrer\">Java Optional Objects</a></em>.</p>\n" }, { "answer_id": 17109182, "author": "Stuart Axon", "author_id": 62709, "author_profile": "https://Stackoverflow.com/users/62709", "pm_score": 4, "selected": false, "text": "<ol>\n<li>Never initialise variables to null.</li>\n<li>If (1) is not possible, initialise all collections and arrays to empty collections/arrays.</li>\n</ol>\n\n<p>Doing this in your own code and you can avoid != null checks.</p>\n\n<p>Most of the time null checks seem to guard loops over collections or arrays, so just initialise them empty, you won't need any null checks.</p>\n\n<pre><code>// Bad\nArrayList&lt;String&gt; lemmings;\nString[] names;\n\nvoid checkLemmings() {\n if (lemmings != null) for(lemming: lemmings) {\n // do something\n }\n}\n\n\n\n// Good\nArrayList&lt;String&gt; lemmings = new ArrayList&lt;String&gt;();\nString[] names = {};\n\nvoid checkLemmings() {\n for(lemming: lemmings) {\n // do something\n }\n}\n</code></pre>\n\n<p>There is a tiny overhead in this, but it's worth it for cleaner code and less NullPointerExceptions.</p>\n" }, { "answer_id": 19714883, "author": "iowatiger08", "author_id": 552782, "author_profile": "https://Stackoverflow.com/users/552782", "pm_score": 1, "selected": false, "text": "<p>We have been using Apache libraries (Apache Commons) for this issue.</p>\n\n<pre><code>ObjectUtils.equals(object, null)\n</code></pre>\n\n<p>or</p>\n\n<pre><code>CollectionUtils.isEmpty(myCollection);\n</code></pre>\n\n<p>or </p>\n\n<pre><code>StringUtils.isEmpty(\"string\");\n</code></pre>\n\n<p>I like the previous answer before, as a practice, of providing initial default values or empty sets for collections to minimize the need.</p>\n\n<p>These can be simple uses that keep you from having NullPointerException or using an empty collection. This doesnt answer the question for what to do with the null object, but these provide some checks for basic validations of the object or collection. </p>\n\n<p>Hope this helps. </p>\n" }, { "answer_id": 21391466, "author": "Tobb", "author_id": 1054021, "author_profile": "https://Stackoverflow.com/users/1054021", "pm_score": 2, "selected": false, "text": "<p>The way to avoid unnecessary <code>null-checks</code> is simple to state:</p>\n\n<p><code>You need to know which variables can be null, and which cannot, and you need to be confident about which category a given variable fall into.</code></p>\n\n<p>But, although it can be stated simply enough, achieving it is harder. The key lies in the <code>confident</code> part, because how can you be sure that a variable can't be null?</p>\n\n<p>There are no quick-fix, easy answers to this, but here are some pointers:</p>\n\n<ol>\n<li><p>Clean code. The most important thing for being able to reason about the behaviour of a piece of code is that it is written in a matter that is easy to understand. Name your variables based on what they represent, name your methods after what they do, apply the <code>Single responsibility principle</code> (the <code>S</code> in <code>SOLID</code>: <a href=\"http://en.wikipedia.org/wiki/SOLID_(object-oriented_design)\" rel=\"nofollow\">http://en.wikipedia.org/wiki/SOLID_(object-oriented_design)</a>, it means that each piece of code should have a single responsibility, and do this and nothing else). Once your code is clean, it is much easier to reason about it, also across multiple tiers/layers of code. With messy code, trying to understand what a method does might make you forget why you are reading the method in the first place. (Tip: Read \"Clean Code\" by Robert C. Martin)</p></li>\n<li><p>Avoid returning <code>null</code> values. If a <code>null</code> value would keep your program from functioning correctly, throw an <code>exception</code> instead (make sure to add the appropriate error-handling.) Cases where returning a <code>null</code> value might be acceptable is for instance trying to fetch an object from the database. In these cases, write code that handles the <code>null</code> values, and make a note behind your ear that here we have something that might return <code>null</code>. Handle returned <code>null</code> values as close to the caller of the method returning <code>null</code> as possible (don't just blindly pass it back up the call-chain.)</p></li>\n<li><p>Never EVER pass explicit <code>null</code> values as parameters (at least not across classes). If you are ever in a position where passing a <code>null</code>-parameter is the only option, creating a new method that does not have this parameter is the way to go. </p></li>\n<li><p>Validate your input! Identify the \"entry-points\" to your application. They can everything from webservices, REST-services, remote EJB classes, controllers, etc. For each method in these entry-points, ask yourself: \"Will this method execute correctly if this parameter is null?\" If the answer is no, add <code>Validate.notNull(someParam, \"Can't function when someParam is null!\");</code>. This will throw an <code>IllegalArgumentException</code> if the required parameter is missing. The good thing about this type of validation in the entry-points, is that you can then easily assume in the code being executed from the entry-point, that this variable will never be null! Also, if this fails, being at the entry-point, debugging is made a lot easier than it would if you just got a <code>NullPointerException</code> deep down in your code, since a failure like this can only mean one thing: The client didn't send you all the required information. In most cases you want to validate all input parameters, if you find yourself in a position where you need to allow a lot of <code>null</code>-values, it might be a sign of a badly designed interface, which needs refactoring/additions to suite the needs of the clients.</p></li>\n<li><p>When working with <code>Collection</code>s, return an empty one rather than null! </p></li>\n<li><p>When working with a database, utilize <code>not null</code>-constraints. In that way, you'll know that a value read from the database cannot be null, and you won't have to check for it.</p></li>\n<li><p>Structure your code and stick with it. Doing this allows you to make assumptions about the behaviour of the code, for instance if all input to your application is validated, then you can assume that these values will never be null. </p></li>\n<li><p>If you are not already doing it, write automated tests of your code. By writing tests, you will reason about your code, and you will also become more confident that it does what it's supposed to. Also, automated tests guards you from blunders during refactoring, by letting you know immediatly that this piece of code is not doing what it used to.</p></li>\n</ol>\n\n<p>You still have to null-check of course, but it can trimmed down to the bare minimum (i.e. the situation where <em>know</em> you might be getting a null-value, instead of everywhere just to be sure.) When it comes to null-checks, i actually prefer to use the ternary operator (but use with care, when you start nesting them they come really messy.)</p>\n\n<pre><code>public String nullSafeToString(final Object o) {\n return o != null ? o.toString() : \"null\";\n}\n</code></pre>\n" }, { "answer_id": 21726959, "author": "Alireza Fattahi", "author_id": 2648077, "author_profile": "https://Stackoverflow.com/users/2648077", "pm_score": 4, "selected": false, "text": "<p>May I answer it more generally!</p>\n\n<p>We <strong>usually</strong> face this issue when the methods get the parameters in the way we not expected (bad method call is programmer's fault). For example: you expect to get an object, instead you get a null. You expect to get an String with at least one character, instead you get an empty String ...</p>\n\n<p>So there is no difference between:</p>\n\n<pre><code>if(object == null){\n //you called my method badly!\n</code></pre>\n\n<p>}</p>\n\n<p>or</p>\n\n<pre><code>if(str.length() == 0){\n //you called my method badly again!\n}\n</code></pre>\n\n<p>They both want to make sure that we received valid parameters, before we do any other functions.</p>\n\n<p>As mentioned in some other answers, to avoid above problems you can follow the <strong>Design by contract</strong> pattern. Please see <a href=\"http://en.wikipedia.org/wiki/Design_by_contract\">http://en.wikipedia.org/wiki/Design_by_contract</a>. </p>\n\n<p>To implement this pattern in java, you can use core java annotations like <strong>javax.annotation.NotNull</strong> or use more sophisticated libraries like <strong>Hibernate Validator</strong>.</p>\n\n<p>Just a sample:</p>\n\n<pre><code>getCustomerAccounts(@NotEmpty String customerId,@Size(min = 1) String accountType)\n</code></pre>\n\n<p>Now you can safely develop the core function of your method without needing to check input parameters, they guard your methods from unexpected parameters.</p>\n\n<p>You can go a step further and make sure that only valid pojos could be created in your application. (sample from hibernate validator site)</p>\n\n<pre><code>public class Car {\n\n @NotNull\n private String manufacturer;\n\n @NotNull\n @Size(min = 2, max = 14)\n private String licensePlate;\n\n @Min(2)\n private int seatCount;\n\n // ...\n}\n</code></pre>\n" }, { "answer_id": 22211014, "author": "Gal Morad", "author_id": 1940722, "author_profile": "https://Stackoverflow.com/users/1940722", "pm_score": 3, "selected": false, "text": "<p>I find Guava Preconditions to be very useful in this case. I don't like leaving nulls to null pointer exception since the only way to understand an NPE is by locating the line number. Line numbers in production version and development version can be different.</p>\n\n<p>Using Guava Preconditions, I can check null parameters and define a meaningful exception message in one line.</p>\n\n<p>For example,</p>\n\n<pre><code>Preconditions.checkNotNull(paramVal, \"Method foo received null paramVal\");\n</code></pre>\n" }, { "answer_id": 23021801, "author": "Sireesh Yarlagadda", "author_id": 2057902, "author_profile": "https://Stackoverflow.com/users/2057902", "pm_score": 4, "selected": false, "text": "<p>This is the most common error occurred for most of the developers.</p>\n\n<p>We have number of ways to handle this.</p>\n\n<p><strong>Approach 1:</strong></p>\n\n<pre><code>org.apache.commons.lang.Validate //using apache framework\n</code></pre>\n\n<p>notNull(Object object, String message) </p>\n\n<p><strong>Approach 2:</strong></p>\n\n<pre><code>if(someObject!=null){ // simply checking against null\n}\n</code></pre>\n\n<p><strong>Approach 3:</strong></p>\n\n<pre><code>@isNull @Nullable // using annotation based validation\n</code></pre>\n\n<p><strong>Approach 4:</strong></p>\n\n<pre><code>// by writing static method and calling it across whereever we needed to check the validation\n\nstatic &lt;T&gt; T isNull(someObject e){ \n if(e == null){\n throw new NullPointerException();\n }\n return e;\n}\n</code></pre>\n" }, { "answer_id": 23031015, "author": "luke1985", "author_id": 2000185, "author_profile": "https://Stackoverflow.com/users/2000185", "pm_score": 4, "selected": false, "text": "<p>I highly disregard answers that suggest using the null objects in every situation. This pattern may break the contract and bury problems deeper and deeper instead of solving them, not mentioning that used inappropriately will create another pile of boilerplate code that will require future maintenance.</p>\n\n<p>In reality if something returned from a method can be null and the calling code has to make decision upon that, there should an earlier call that ensures the state. </p>\n\n<p>Also keep in mind, that null object pattern will be memory hungry if used without care. For this - the instance of a NullObject should be shared between owners, and not be an unigue instance for each of these.</p>\n\n<p>Also I would not recommend using this pattern where the type is meant to be a primitive type representation - like mathematical entities, that are not scalars: vectors, matrices, complex numbers and POD(Plain Old Data) objects, which are meant to hold state in form of Java built-in types. In the latter case you would end up calling getter methods with arbitrary results. For example what should a NullPerson.getName() method return? </p>\n\n<p>It's worth considering such cases in order to avoid absurd results.</p>\n" }, { "answer_id": 29887121, "author": "Yogesh Devatraj", "author_id": 1646333, "author_profile": "https://Stackoverflow.com/users/1646333", "pm_score": 5, "selected": false, "text": "<p>This is a very common problem for every Java developer. So there is official support in Java&nbsp;8 to address these issues without cluttered code.</p>\n\n<p>Java 8 has introduced <code>java.util.Optional&lt;T&gt;</code>. It is a container that may or may not hold a non-null value. Java 8 has given a safer way to handle an object whose value may be null in some of the cases. It is inspired from the ideas of <a href=\"http://en.wikipedia.org/wiki/Haskell_%28programming_language%29\" rel=\"noreferrer\">Haskell</a> and <a href=\"http://en.wikipedia.org/wiki/Scala_%28programming_language%29\" rel=\"noreferrer\">Scala</a>.</p>\n\n<p>In a nutshell, the Optional class includes methods to explicitly deal with the cases where a value is present or absent. However, the advantage compared to null references is that the Optional&lt;T> class forces you to think about the case when the value is not present. As a consequence, you can prevent unintended null pointer exceptions.</p>\n\n<p>In above example we have a home service factory that returns a handle to multiple appliances available in the home. But these services may or may not be available/functional; it means it may result in a NullPointerException. Instead of adding a null <code>if</code> condition before using any service, let's wrap it in to Optional&lt;Service>.</p>\n\n<p>WRAPPING TO OPTION&lt;T></p>\n\n<p>Let's consider a method to get a reference of a service from a factory. Instead of returning the service reference, wrap it with Optional. It lets the API user know that the returned service may or may not available/functional, use defensively</p>\n\n<pre><code>public Optional&lt;Service&gt; getRefrigertorControl() {\n Service s = new RefrigeratorService();\n //...\n return Optional.ofNullable(s);\n }\n</code></pre>\n\n<p>As you see <code>Optional.ofNullable()</code> provides an easy way to get the reference wrapped. There are another ways to get the reference of Optional, either <code>Optional.empty()</code> &amp; <code>Optional.of()</code>. One for returning an empty object instead of retuning null and the other to wrap a non-nullable object, respectively.</p>\n\n<p>SO HOW EXACTLY IT HELPS TO AVOID A NULL CHECK?</p>\n\n<p>Once you have wrapped a reference object, Optional provides many useful methods to invoke methods on a wrapped reference without NPE.</p>\n\n<pre><code>Optional ref = homeServices.getRefrigertorControl();\nref.ifPresent(HomeServices::switchItOn);\n</code></pre>\n\n<p>Optional.ifPresent invokes the given Consumer with a reference if it is a non-null value. Otherwise, it does nothing.</p>\n\n<pre><code>@FunctionalInterface\npublic interface Consumer&lt;T&gt;\n</code></pre>\n\n<p>Represents an operation that accepts a single input argument and returns no result. Unlike most other functional interfaces, Consumer is expected to operate via side-effects.\nIt is so clean and easy to understand. In the above code example, <code>HomeService.switchOn(Service)</code> gets invoked if the Optional holding reference is non-null.</p>\n\n<p>We use the ternary operator very often for checking null condition and return an alternative value or default value. Optional provides another way to handle the same condition without checking null. Optional.orElse(defaultObj) returns defaultObj if the Optional has a null value. Let's use this in our sample code:</p>\n\n<pre><code>public static Optional&lt;HomeServices&gt; get() {\n service = Optional.of(service.orElse(new HomeServices()));\n return service;\n}\n</code></pre>\n\n<p>Now HomeServices.get() does same thing, but in a better way. It checks whether the service is already initialized of not. If it is then return the same or create a new New service. Optional&lt;T>.orElse(T) helps to return a default value.</p>\n\n<p>Finally, here is our NPE as well as null check-free code:</p>\n\n<pre><code>import java.util.Optional;\npublic class HomeServices {\n private static final int NOW = 0;\n private static Optional&lt;HomeServices&gt; service;\n\npublic static Optional&lt;HomeServices&gt; get() {\n service = Optional.of(service.orElse(new HomeServices()));\n return service;\n}\n\npublic Optional&lt;Service&gt; getRefrigertorControl() {\n Service s = new RefrigeratorService();\n //...\n return Optional.ofNullable(s);\n}\n\npublic static void main(String[] args) {\n /* Get Home Services handle */\n Optional&lt;HomeServices&gt; homeServices = HomeServices.get();\n if(homeServices != null) {\n Optional&lt;Service&gt; refrigertorControl = homeServices.get().getRefrigertorControl();\n refrigertorControl.ifPresent(HomeServices::switchItOn);\n }\n}\n\npublic static void switchItOn(Service s){\n //...\n }\n}\n</code></pre>\n\n<p>The complete post is <em><a href=\"http://ydtech.blogspot.in/2015/04/npe-as-well-as-null-check-free-code.html\" rel=\"noreferrer\">NPE as well as Null check-free code … Really?</a></em>.</p>\n" }, { "answer_id": 33216446, "author": "Mehdi", "author_id": 1624839, "author_profile": "https://Stackoverflow.com/users/1624839", "pm_score": 0, "selected": false, "text": "<p>You can couple your Class with Unit Testing using a framework like JUnit.\nThis way your code will be clean (no useless checkings) and you will be sure your instances wont be null.</p>\n\n<p>This is one good reason (of many) to use Unit Testing.</p>\n" }, { "answer_id": 33763493, "author": "Lii", "author_id": 452775, "author_profile": "https://Stackoverflow.com/users/452775", "pm_score": 1, "selected": false, "text": "<p>It is possible to define util methods which handles nested null-checks in an almost pretty way with Java 8 lambdas.</p>\n\n<pre><code>void example() {\n Entry entry = new Entry();\n // This is the same as H-MANs solution \n Person person = getNullsafe(entry, e -&gt; e.getPerson()); \n // Get object in several steps\n String givenName = getNullsafe(entry, e -&gt; e.getPerson(), p -&gt; p.getName(), n -&gt; n.getGivenName());\n // Call void methods\n doNullsafe(entry, e -&gt; e.getPerson(), p -&gt; p.getName(), n -&gt; n.nameIt()); \n}\n\n/** Return result of call to f1 with o1 if it is non-null, otherwise return null. */\npublic static &lt;R, T1&gt; R getNullsafe(T1 o1, Function&lt;T1, R&gt; f1) {\n if (o1 != null) return f1.apply(o1);\n return null; \n}\n\npublic static &lt;R, T0, T1&gt; R getNullsafe(T0 o0, Function&lt;T0, T1&gt; f1, Function&lt;T1, R&gt; f2) {\n return getNullsafe(getNullsafe(o0, f1), f2);\n}\n\npublic static &lt;R, T0, T1, T2&gt; R getNullsafe(T0 o0, Function&lt;T0, T1&gt; f1, Function&lt;T1, T2&gt; f2, Function&lt;T2, R&gt; f3) {\n return getNullsafe(getNullsafe(o0, f1, f2), f3);\n}\n\n\n/** Call consumer f1 with o1 if it is non-null, otherwise do nothing. */\npublic static &lt;T1&gt; void doNullsafe(T1 o1, Consumer&lt;T1&gt; f1) {\n if (o1 != null) f1.accept(o1);\n}\n\npublic static &lt;T0, T1&gt; void doNullsafe(T0 o0, Function&lt;T0, T1&gt; f1, Consumer&lt;T1&gt; f2) {\n doNullsafe(getNullsafe(o0, f1), f2);\n}\n\npublic static &lt;T0, T1, T2&gt; void doNullsafe(T0 o0, Function&lt;T0, T1&gt; f1, Function&lt;T1, T2&gt; f2, Consumer&lt;T2&gt; f3) {\n doNullsafe(getNullsafe(o0, f1, f2), f3);\n}\n\n\nclass Entry {\n Person getPerson() { return null; }\n}\n\nclass Person {\n Name getName() { return null; }\n}\n\nclass Name {\n void nameIt() {}\n String getGivenName() { return null; }\n}\n</code></pre>\n\n<p><i><sup>(This answer was first posted <a href=\"https://stackoverflow.com/questions/4390141/java-operator-for-checking-null-what-is-it-not-ternary/33711967#33711967\">here</a>.)</sup></i></p>\n" }, { "answer_id": 34304851, "author": "sidgate", "author_id": 977919, "author_profile": "https://Stackoverflow.com/users/977919", "pm_score": 2, "selected": false, "text": "<p>Java 8 now has Optional class that wraps the object in consideration and if a value is present, isPresent() will return true and get() will return the value.</p>\n\n<p><a href=\"http://www.oracle.com/technetwork/articles/java/java8-optional-2175753.html\" rel=\"nofollow\">http://www.oracle.com/technetwork/articles/java/java8-optional-2175753.html</a></p>\n" }, { "answer_id": 34996504, "author": "Ravindra babu", "author_id": 4999394, "author_profile": "https://Stackoverflow.com/users/4999394", "pm_score": 3, "selected": false, "text": "<p>I follow below guidelines to avoid null checks.</p>\n\n<ol>\n<li><p>Avoid <strong><em>lazy initialization</em></strong> of member variables as much as possible. Initialize the variables in declaration itself. This will handle NullPointerExceptions. </p></li>\n<li><p>Decide on <strong><em>mutability</em></strong> of member variables early in the cycle. Use language constructs like <code>final</code> keyword effectively. </p></li>\n<li><p>If you know that augments for method won't be changed, declare them as <code>final</code>.</p></li>\n<li><p>Limit the <strong><em>mutation</em></strong> of data as much as possible. Some variables can be created in a constructor and can never be changed. <strong><em>Remove public setter methods unless they are really required</em></strong>.</p>\n\n<p>E.g. Assume that one class in your application (<code>A.java</code>) is maintaining a collection like <code>HashMap</code>. Don't provide <code>public</code> getter method in A.java and allow <code>B.java</code> to directly add an element in <code>Map</code>. Instead provide an API in <code>A.java</code>, which adds an element into collection. </p>\n\n<pre><code>// Avoid\na.getMap().put(key,value)\n\n//recommended\n\npublic void addElement(Object key, Object value){\n // Have null checks for both key and value here : single place\n map.put(key,value);\n}\n</code></pre></li>\n<li><p>And finally, use <code>try{} catch{} finally{}</code> blocks at right places effectively.</p></li>\n</ol>\n" }, { "answer_id": 36167495, "author": "Raghu K Nair", "author_id": 2194364, "author_profile": "https://Stackoverflow.com/users/2194364", "pm_score": 5, "selected": false, "text": "<p>Probably the best alternative for Java 8 or newer is to use the <a href=\"https://docs.oracle.com/javase/8/docs/api/java/util/Optional.html\" rel=\"noreferrer\"><code>Optional</code></a> class. </p>\n\n<pre><code>Optional stringToUse = Optional.of(\"optional is there\");\nstringToUse.ifPresent(System.out::println);\n</code></pre>\n\n<p>This is especially handy for long chains of possible null values. Example:</p>\n\n<pre><code>Optional&lt;Integer&gt; i = Optional.ofNullable(wsObject.getFoo())\n .map(f -&gt; f.getBar())\n .map(b -&gt; b.getBaz())\n .map(b -&gt; b.getInt());\n</code></pre>\n\n<p>Example on how to throw exception on null:</p>\n\n<pre><code>Optional optionalCarNull = Optional.ofNullable(someNull);\noptionalCarNull.orElseThrow(IllegalStateException::new);\n</code></pre>\n\n<p>Java 7 introduced the <a href=\"https://docs.oracle.com/javase/7/docs/api/java/util/Objects.html#requireNonNull(T,%20java.lang.String)\" rel=\"noreferrer\"><code>Objects.requireNonNull</code></a> method which can be handy when something should be checked for non-nullness. Example:</p>\n\n<pre><code>String lowerVal = Objects.requireNonNull(someVar, \"input cannot be null or empty\").toLowerCase();\n</code></pre>\n" }, { "answer_id": 38207227, "author": "Ivan Golovach", "author_id": 6546993, "author_profile": "https://Stackoverflow.com/users/6546993", "pm_score": 3, "selected": false, "text": "<p>In Java 8 you can use type <code>T</code> for local-variable/field/method-argument/method-return-type if it never assigned <code>null</code> (and do not check for <code>null</code>) or type <code>Optional&lt;T&gt;</code> if it can be <code>null</code>. Then use method <code>map</code> for processing <code>T -&gt;</code> and method <code>flatMap</code> for processing <code>T -&gt; Optional&lt;R&gt;</code>:</p>\n\n<pre><code>class SomeService {\n @Inject\n private CompanyDao companyDao;\n\n // return Optional&lt;String&gt;\n public Optional&lt;String&gt; selectCeoCityByCompanyId0(int companyId) {\n return companyDao.selectById(companyId)\n .map(Company::getCeo)\n .flatMap(Person::getHomeAddress)\n .flatMap(Address::getCity);\n }\n\n // return String + default value\n public String selectCeoCityByCompanyId1(int companyId) {\n return companyDao.selectById(companyId)\n .map(Company::getCeo)\n .flatMap(Person::getHomeAddress)\n .flatMap(Address::getCity)\n .orElse(\"UNKNOWN\");\n }\n\n // return String + exception\n public String selectCeoCityByCompanyId2(int companyId) throws NoSuchElementException {\n return companyDao.selectById(companyId)\n .map(Company::getCeo)\n .flatMap(Person::getHomeAddress)\n .flatMap(Address::getCity)\n .orElseThrow(NoSuchElementException::new);\n }\n}\n\ninterface CompanyDao {\n // real situation: no company for such id -&gt; use Optional&lt;Company&gt; \n Optional&lt;Company&gt; selectById(int id);\n}\n\nclass Company {\n // company always has ceo -&gt; use Person \n Person ceo;\n public Person getCeo() {return ceo;}\n}\n\nclass Person {\n // person always has name -&gt; use String\n String firstName;\n // person can be without address -&gt; use Optional&lt;Address&gt;\n Optional&lt;Address&gt; homeAddress = Optional.empty();\n\n public String getFirstName() {return firstName;} \n public Optional&lt;Address&gt; getHomeAddress() {return homeAddress;}\n}\n\nclass Address {\n // address always contains country -&gt; use String\n String country;\n // city field is optional -&gt; use Optional&lt;String&gt;\n Optional&lt;String&gt; city = Optional.empty();\n\n String getCountry() {return country;} \n Optional&lt;String&gt; getCity() {return city;}\n}\n</code></pre>\n" }, { "answer_id": 39848137, "author": "Vidura Mudalige", "author_id": 3719179, "author_profile": "https://Stackoverflow.com/users/3719179", "pm_score": -1, "selected": false, "text": "<p>Null object pattern can be used as a solution for this problem. For that, the class of the someObject should be modified. </p>\n\n<pre><code>public abstract class SomeObject {\n public abstract boolean isNil();\n}\n\npublic class NullObject extends SomeObject {\n @Override\n public boolean isNil() {\n return true;\n }\n}\npublic class RealObject extends SomeObject {\n @Override\n public boolean isNil() {\n return false;\n }\n}\n</code></pre>\n\n<p>Now istead of checking,</p>\n\n<pre><code> if (someobject != null) {\n someobject.doCalc();\n}\n</code></pre>\n\n<p>We can use,</p>\n\n<pre><code>if (!someObject.isNil()) {\n someobject.doCalc();\n}\n</code></pre>\n\n<p>Reference : <a href=\"https://www.tutorialspoint.com/design_pattern/null_object_pattern.htm\" rel=\"nofollow\">https://www.tutorialspoint.com/design_pattern/null_object_pattern.htm</a></p>\n" }, { "answer_id": 40840957, "author": "Philip John", "author_id": 4256410, "author_profile": "https://Stackoverflow.com/users/4256410", "pm_score": 3, "selected": false, "text": "<p>Since <code>Java 7</code> the class <code>java.util.Objects</code> exists.</p>\n\n<p>But since <code>Java 8</code>, you can use <code>Objects.isNull(var)</code> and <code>Objects.nonNull(var)</code> methods of <code>Objects</code> class to do the null pointer check.</p>\n\n<p>For example,</p>\n\n<pre><code>String var1 = null;\nDate var2 = null;\nLong var3 = null;\n\nif(Objects.isNull(var1) &amp;&amp; Objects.isNull(var2) &amp;&amp; Objects.isNull(var3))\n System.out.println(\"All Null\");\nelse if (Objects.nonNull(var1) &amp;&amp; Objects.nonNull(var2) &amp;&amp; Objects.nonNull(var3))\n System.out.println(\"All Not Null\");\n</code></pre>\n" }, { "answer_id": 44902405, "author": "Jobin", "author_id": 2893693, "author_profile": "https://Stackoverflow.com/users/2893693", "pm_score": 3, "selected": false, "text": "<p>If you are using java8 or later go for the <code>isNull(yourObject)</code> from <code>java.util.Objects</code>.</p>\n<p>Example:-</p>\n<pre><code>String myObject = null;\n\nObjects.isNull(myObject); //will return true\n</code></pre>\n<p>Usage: The below code returns a non null value (if the name is not null then that value will be returned else the default value will be returned).</p>\n<pre><code>final String name = &quot;Jobin&quot;;\nString nonNullValue = Optional.ofNullable(name).orElse(&quot;DefaultName&quot;);\n</code></pre>\n" }, { "answer_id": 46644408, "author": "NeeruKSingh", "author_id": 8432237, "author_profile": "https://Stackoverflow.com/users/8432237", "pm_score": 4, "selected": false, "text": "<p><strong>Java 8 has introduced a new class Optional in java.util package.</strong></p>\n\n<p><strong>Advantages of Java 8 Optional:</strong></p>\n\n<p>1.) Null checks are not required.<br>\n2.) No more NullPointerException at run-time.<br>\n3.) We can develop clean and neat APIs. </p>\n\n<p><strong>Optional</strong> - A container object which may or may not contain a non-null value. If a value is present, isPresent() will return true and get() will return the value.</p>\n\n<p>For more details find here oracle docs :-\n<a href=\"https://docs.oracle.com/javase/8/docs/api/java/util/Optional.html\" rel=\"noreferrer\">https://docs.oracle.com/javase/8/docs/api/java/util/Optional.html</a></p>\n" }, { "answer_id": 47285263, "author": "yanefedor", "author_id": 4545552, "author_profile": "https://Stackoverflow.com/users/4545552", "pm_score": 4, "selected": false, "text": "<p>All in all to avoid statement</p>\n<pre><code>if (object != null) {\n ....\n}\n</code></pre>\n<ol>\n<li><p>since java 7 you can use <code>Objects</code> methods:</p>\n<p>Objects.isNull(object)</p>\n<p>Objects.nonNull(object)</p>\n<p>Objects.requireNonNull(object)</p>\n<p>Objects.equals(object1, object2)</p>\n</li>\n<li><p>since java 8 you can use Optional class (<a href=\"https://stackoverflow.com/questions/23454952/uses-for-optional\">when to use</a>)</p>\n</li>\n</ol>\n<p><code>object.ifPresent(obj -&gt; ...);</code> java 8</p>\n<p><code>object.ifPresentOrElse(obj -&gt; ..., () -&gt; ...);</code> java 9</p>\n<ol start=\"3\">\n<li><p>rely on method contract (<a href=\"https://minds.coremedia.com/2012/10/31/jsr-305-nonnull-and-guava-preconditions/\" rel=\"noreferrer\">JSR 305</a>) and use <a href=\"http://findbugs.sourceforge.net/\" rel=\"noreferrer\">Find Bugs</a>. Mark your code with annotations <code>@javax.annotation.Nullable</code> and <code>@javax.annotation.Nonnnul</code>. Also Preconditions are available.</p>\n<p>Preconditions.checkNotNull(object);</p>\n</li>\n<li><p>In special cases (for example for Strings and Collections) you can use apache-commons (or Google guava) utility methods:</p>\n</li>\n</ol>\n<blockquote>\n<p>public static boolean isEmpty(CharSequence cs) //apache CollectionUtils</p>\n<p>public static boolean isEmpty(Collection coll) //apache StringUtils</p>\n<p>public static boolean isEmpty(Map map) //apache MapUtils</p>\n<p>public static boolean isNullOrEmpty(@Nullable String string) //Guava Strings</p>\n</blockquote>\n<ol start=\"5\">\n<li>When you need to assign default value when null use apache commons lang</li>\n</ol>\n<blockquote>\n<p>public static Object defaultIfNull(Object object, Object defaultValue)</p>\n</blockquote>\n" }, { "answer_id": 47986378, "author": "Binod Pant", "author_id": 1119386, "author_profile": "https://Stackoverflow.com/users/1119386", "pm_score": 1, "selected": false, "text": "<p>One Option you have</p>\n\n<ul>\n<li><p>Use <a href=\"https://checkerframework.org/api/org/checkerframework/checker/nullness/qual/RequiresNonNull.html\" rel=\"nofollow noreferrer\">checker framework</a>'s @RequiresNonNull on methods. for ex you get this if you call a method annotated as such, with a null argument. It will fail during compile, even before your code runs! since at runtime it will be NullPointerException</p>\n\n<pre><code>@RequiresNonNull(value = { \"#1\" })\nstatic void check( Boolean x) {\n if (x) System.out.println(\"true\");\n else System.out.println(\"false\");\n}\n\npublic static void main(String[] args) {\n\n\n check(null);\n\n}\n</code></pre></li>\n</ul>\n\n<p>gets </p>\n\n<pre><code>[ERROR] found : null\n[ERROR] required: @Initialized @NonNull Boolean\n[ERROR] -&gt; [Help 1]\n</code></pre>\n\n<p>There are other methods like Use Java 8's Optional, Guava Annotations, Null Object pattern etc. Does not matter as long as you obtain your goal of avoiding !=null</p>\n" }, { "answer_id": 48671389, "author": "nilesh", "author_id": 503804, "author_profile": "https://Stackoverflow.com/users/503804", "pm_score": 2, "selected": false, "text": "<p>With Java 8, you could pass a supplier to a helper method like below,</p>\n\n<pre><code>if(CommonUtil.resolve(()-&gt; a.b().c()).isPresent()) {\n\n}\n</code></pre>\n\n<p>Above replaces boiler plate code like below,</p>\n\n<pre><code>if(a!=null &amp;&amp; a.b()!=null &amp;&amp; a.b().c()!=null) {\n\n}\n</code></pre>\n\n<p>//CommonUtil.java</p>\n\n<pre><code> public static &lt;T&gt; Optional&lt;T&gt; resolve(Supplier&lt;T&gt; resolver) {\n try {\n T result = resolver.get();\n return Optional.ofNullable(result);\n } catch (NullPointerException var2) {\n return Optional.empty();\n }\n }\n</code></pre>\n" }, { "answer_id": 51311500, "author": "Mukesh A", "author_id": 4014678, "author_profile": "https://Stackoverflow.com/users/4014678", "pm_score": 3, "selected": false, "text": "<p>You can avoid most a lot to avoid <code>NullPointerException</code> by just following most of the others answers to the Question, I just want to add few <strong>more ways which have been introduced in <code>Java 9</code></strong> to handle this scenario gracefully and also showcase a few of the older ones can also be used and thus reducing your efforts.</p>\n\n<ol>\n<li><p><code>public static boolean isNull(Object obj)</code></p>\n\n<p>Returns true if the provided reference is null otherwise returns\nfalse.</p>\n\n<p>Since Java 1.8</p></li>\n<li><p><code>public static boolean nonNull(Object obj)</code></p>\n\n<p>Returns true if the provided reference is non-null otherwise returns\nfalse.</p>\n\n<p>Since Java 1.8</p></li>\n<li><p><code>public static &lt;T&gt; T requireNonNullElse​(T obj, T defaultObj)</code></p>\n\n<p>Returns the first argument if it is non-null and otherwise returns\nthe non-null second argument.</p>\n\n<p>Since Java 9</p></li>\n<li><p><code>public static &lt;T&gt; T requireNonNullElseGet​(T obj, Supplier&lt;? extends T&gt; supplier)</code></p>\n\n<p>Returns the first argument if it is non-null and otherwise returns the non-null value of supplier.get().</p>\n\n<p>Since Java 9</p></li>\n<li><p><code>public static &lt;T&gt; T requireNonNull​(T obj, Supplier&lt;String&gt; messageSupplier)</code></p>\n\n<p>Checks that the specified object reference is not null and throws a customized NullPointerException otherwise.</p>\n\n<p>Since Java 1.8</p></li>\n</ol>\n\n<p>Further details about the above functions can be found <a href=\"https://docs.oracle.com/javase/9/docs/api/java/util/Objects.html#isNull-java.lang.Object-\" rel=\"noreferrer\">here</a>.</p>\n" }, { "answer_id": 51939089, "author": "Francis", "author_id": 4353365, "author_profile": "https://Stackoverflow.com/users/4353365", "pm_score": 1, "selected": false, "text": "<p><a href=\"https://kotlinlang.org\" rel=\"nofollow noreferrer\">Kotlin</a> with null safety is elegant alternative, but it means a larger change.</p>\n" }, { "answer_id": 54017256, "author": "Ramprabhu", "author_id": 7236932, "author_profile": "https://Stackoverflow.com/users/7236932", "pm_score": 0, "selected": false, "text": "<p>Functional approach may help to wrap the repetitive null checks and execute anonymous code like the below sample.</p>\n\n<pre><code> BiConsumer&lt;Object, Consumer&lt;Object&gt;&gt; consumeIfPresent = (s,f) -&gt;{\n if(s!=null) {\n f.accept(s);\n }\n };\n\n consumeIfPresent.accept(null, (s)-&gt; System.out.println(s) );\n consumeIfPresent.accept(\"test\", (s)-&gt; System.out.println(s));\n\n BiFunction&lt;Object, Function&lt;Object,Object&gt;,Object&gt; executeIfPresent = (a,b) -&gt;{\n if(a!=null) {\n return b.apply(a);\n }\n return null;\n };\n executeIfPresent.apply(null, (s)-&gt; {System.out.println(s);return s;} );\n executeIfPresent.apply(\"test\", (s)-&gt; {System.out.println(s);return s;} );\n</code></pre>\n" }, { "answer_id": 56145630, "author": "Sebastian3000", "author_id": 2785025, "author_profile": "https://Stackoverflow.com/users/2785025", "pm_score": 2, "selected": false, "text": "<p>Another alternative to the != null check is (if you can't get rid of it design-wise):</p>\n\n<pre><code>Optional.ofNullable(someobject).ifPresent(someobject -&gt; someobject.doCalc());\n</code></pre>\n\n<p>or</p>\n\n<pre><code>Optional.ofNullable(someobject).ifPresent(SomeClass::doCalc);\n</code></pre>\n\n<p>With SomeClass being someobject's type.</p>\n\n<p>You can't get a return value back from doCalc() though, so only useful for void methods.</p>\n" }, { "answer_id": 56543966, "author": "rohit prakash", "author_id": 6024604, "author_profile": "https://Stackoverflow.com/users/6024604", "pm_score": 3, "selected": false, "text": "<p>Java 8 has introduced a new class Optional in <code>java.util</code> package. It is used to represent a value is present or absent. The main advantage of this new construct is that No more too many null checks and <code>NullPointerException</code>. It avoids any runtime <code>NullPointerExceptions</code> and supports us in developing clean and neat Java APIs or Applications. Like <code>Collections</code> and <code>arrays</code>, it is also a Container to hold at most one value.</p>\n<p>Below are some useful link you can follow</p>\n<p><a href=\"https://www.mkyong.com/java8/java-8-optional-in-depth/\" rel=\"nofollow noreferrer\">https://www.mkyong.com/java8/java-8-optional-in-depth/</a></p>\n<p><a href=\"https://dzone.com/articles/java-8-optional-avoid-null-and\" rel=\"nofollow noreferrer\">https://dzone.com/articles/java-8-optional-avoid-null-and</a></p>\n" }, { "answer_id": 63325067, "author": "Satish Hawalppagol", "author_id": 12079719, "author_profile": "https://Stackoverflow.com/users/12079719", "pm_score": 0, "selected": false, "text": "<p>You can make one generic Method for object and string so that you can use it through out in your application-\nThis could help you and your colleagues :\nCreate a class eg. StringUtilities and add the method eg. getNullString</p>\n<pre><code>public static String getNullString(Object someobject)\n{\n if(null==someobject )\n return null;\n\n else if(someobject.getClass().isInstance(&quot;&quot;) &amp;&amp; \n (((String)someobject).trim().equalsIgnoreCase(&quot;null&quot;)|| \n ((String)someobject).trim().equalsIgnoreCase(&quot;&quot;)))\n return null;\n\n else if(someobject.getClass().isInstance(&quot;&quot;))\n return (String)someobject;\n\n else\n return someobject.toString().trim();\n}\n</code></pre>\n<p>And simply call this method as,</p>\n<pre><code>if (StringUtilities.getNullString(someobject) != null)\n{ \n //Do something\n}\n</code></pre>\n" }, { "answer_id": 64437815, "author": "Dan Chase", "author_id": 3152516, "author_profile": "https://Stackoverflow.com/users/3152516", "pm_score": 0, "selected": false, "text": "<p>The best way to avoid Null Checks in Java, is to properly handle and use exceptions. Null Checks in my experience have become more common and required as you move closer to the front-end, because it's closer to the user who may supply invalid information through the UI (such as, no value, being submitted for a field).</p>\n<p>One may argue that you should be able to control what the UI is doing, lest you forget most UI is done through a third party library of some kind, which for example, may return either NULL or an Empty String for a blank text box, depending on the situation or the library.</p>\n<p>You can combine the two like this:</p>\n<pre><code>try\n{\n myvar = get_user_supplied_value(); \n if (myvar == null || myvar.length() == 0) { alert_the_user_somehow(); return; };\n\n process_user_input(myvar);\n} catch (Exception ex) {\n handle_exception(ex);\n}\n</code></pre>\n<p>Another approach people take is to say:</p>\n<pre><code>if (myvar &amp;&amp; myvar.length() &gt; 0) { };\n</code></pre>\n<p>You could also throw an exception (which is what I prefer)</p>\n<pre><code>if (myvar == null || myvar.length() == 0) {\n throw new Exception(&quot;You must supply a name!&quot;);\n};\n</code></pre>\n<p>But that's up to you.</p>\n" }, { "answer_id": 64455793, "author": "Allen", "author_id": 12716256, "author_profile": "https://Stackoverflow.com/users/12716256", "pm_score": 2, "selected": false, "text": "<p>There has a good way to check the null value from JDK.\nIt is Optional.java that has a sea of methods to resolve these problems. Such as follow:</p>\n<pre><code> /**\n * Returns an {@code Optional} describing the specified value, if non-null,\n * otherwise returns an empty {@code Optional}.\n *\n * @param &lt;T&gt; the class of the value\n * @param value the possibly-null value to describe\n * @return an {@code Optional} with a present value if the specified value\n * is non-null, otherwise an empty {@code Optional}\n */\n public static &lt;T&gt; Optional&lt;T&gt; ofNullable(T value) {\n return value == null ? empty() : of(value);\n }\n</code></pre>\n<pre><code> /**\n * Return {@code true} if there is a value present, otherwise {@code false}.\n *\n * @return {@code true} if there is a value present, otherwise {@code false}\n */\n public boolean isPresent() {\n return value != null;\n }\n</code></pre>\n<pre><code> /**\n * If a value is present, invoke the specified consumer with the value,\n * otherwise do nothing.\n *\n * @param consumer block to be executed if a value is present\n * @throws NullPointerException if value is present and {@code consumer} is\n * null\n */\n public void ifPresent(Consumer&lt;? super T&gt; consumer) {\n if (value != null)\n consumer.accept(value);\n }\n</code></pre>\n<p>It is really, really useful to help javer.</p>\n" }, { "answer_id": 64747393, "author": "vidy", "author_id": 9993935, "author_profile": "https://Stackoverflow.com/users/9993935", "pm_score": 2, "selected": false, "text": "<pre><code>public class Null {\n\npublic static void main(String[] args) {\n String str1 = null;\n String str2 = &quot;&quot;;\n\n if(isNullOrEmpty(str1))\n System.out.println(&quot;First string is null or empty.&quot;);\n else\n System.out.println(&quot;First string is not null or empty.&quot;);\n\n if(isNullOrEmpty(str2))\n System.out.println(&quot;Second string is null or empty.&quot;);\n else\n System.out.println(&quot;Second string is not null or empty.&quot;);\n}\n\npublic static boolean isNullOrEmpty(String str) {\n if(str != null &amp;&amp; !str.isEmpty())\n return false;\n return true;\n}\n}\n</code></pre>\n<p>Output</p>\n<pre><code>str1 is null or empty.\nstr2 is null or empty.\n</code></pre>\n<p>In the above program, we've two strings str1 and str2. str1 contains null value and str2 is an empty string.</p>\n<p>We've also created a function isNullOrEmpty() which checks, as the name suggests, whether the string is null or empty. It checks it using a null check using != null and isEmpty() method of string.</p>\n<p>In plain terms, if a string isn't a null and isEmpty() returns false, it's not either null or empty. Else, it is.</p>\n<p>However, the above program doesn't return empty if a string contains only whitespace characters (spaces). Technically, isEmpty() sees it contains spaces and returns false. For string with spaces, we use the string method trim() to trim out all the leading and trailing whitespace characters.</p>\n" }, { "answer_id": 69973748, "author": "Premakumar Tatireddy", "author_id": 5671333, "author_profile": "https://Stackoverflow.com/users/5671333", "pm_score": 1, "selected": false, "text": "<p><code>Objects.isNull(null)</code>\nIf you are using Java8 then you can try this code.</p>\n<blockquote>\n<p>Try using below code if you are not using Java8</p>\n</blockquote>\n<pre><code>Object ob=null;\nif(ob==null){ **do something}\n</code></pre>\n" }, { "answer_id": 72436784, "author": "Greg7000", "author_id": 6210975, "author_profile": "https://Stackoverflow.com/users/6210975", "pm_score": 0, "selected": false, "text": "<p>Personally, I would either go with <a href=\"https://stackoverflow.com/a/271553/6210975\">jim-nelson's answer</a> or if I do find a null check is convenient for a specific context I would incorporate <a href=\"https://stackoverflow.com/a/271553/6210975\">lombok</a> into my project and use the <a href=\"https://projectlombok.org/features/NonNull\" rel=\"nofollow noreferrer\">@NonNull</a> annotation.</p>\n<p>Example:</p>\n<pre><code>import lombok.NonNull;\n\npublic class NonNullExample extends Something {\n private String name;\n \n public NonNullExample(@NonNull Person person) {\n super(&quot;Hello&quot;);\n this.name = person.getName();\n }\n}\n</code></pre>\n<p>Even the <a href=\"https://projectlombok.org/features/NonNull\" rel=\"nofollow noreferrer\">@NonNull</a> preface mention:</p>\n<ul>\n<li><em>or: How I learned to stop worrying and love the NullPointerException.</em></li>\n</ul>\n" } ]
2008/11/07
[ "https://Stackoverflow.com/questions/271526", "https://Stackoverflow.com", "https://Stackoverflow.com/users/34856/" ]
I use `x != null` to avoid [`NullPointerException`](https://docs.oracle.com/javase/9/docs/api/java/lang/NullPointerException.html). Is there an alternative? ```java if (x != null) { // ... } ```
This to me sounds like a reasonably common problem that junior to intermediate developers tend to face at some point: they either don't know or don't trust the contracts they are participating in and defensively overcheck for nulls. Additionally, when writing their own code, they tend to rely on returning nulls to indicate something thus requiring the caller to check for nulls. To put this another way, there are two instances where null checking comes up: 1. Where null is a valid response in terms of the contract; and 2. Where it isn't a valid response. (2) is easy. As of Java 1.7 you can use [`Objects.requireNonNull(foo)`](https://docs.oracle.com/en/java/javase/17/docs/api/java.base/java/util/Objects.html#requireNonNull(T)). (If you are stuck with a previous version then [`assert`ions](https://docs.oracle.com/javase/7/docs/technotes/guides/language/assert.html) may be a good alternative.) "Proper" usage of this method would be like below. The method returns the object passed into it and throws a `NullPointerException` if the object is null. This means that the returned value is always non-null. The method is primarily intended for validating parameters. ``` public Foo(Bar bar) { this.bar = Objects.requireNonNull(bar); } ``` It can also be used like an `assert`ion though since it throws an exception if the object is null. In both uses, a message can be added which will be shown in the exception. Below is using it like an assertion and providing a message. ``` Objects.requireNonNull(someobject, "if someobject is null then something is wrong"); someobject.doCalc(); ``` Generally throwing a specific exception like `NullPointerException` when a value is null but shouldn't be is favorable to throwing a more general exception like `AssertionError`. This is the approach the Java library takes; favoring `NullPointerException` over `IllegalArgumentException` when an argument is not allowed to be null. (1) is a little harder. If you have no control over the code you're calling then you're stuck. If null is a valid response, you have to check for it. If it's code that you do control, however (and this is often the case), then it's a different story. Avoid using nulls as a response. With methods that return collections, it's easy: return empty collections (or arrays) instead of nulls pretty much all the time. With non-collections it might be harder. Consider this as an example: if you have these interfaces: ``` public interface Action { void doSomething(); } public interface Parser { Action findAction(String userInput); } ``` where Parser takes raw user input and finds something to do, perhaps if you're implementing a command line interface for something. Now you might make the contract that it returns null if there's no appropriate action. That leads the null checking you're talking about. An alternative solution is to never return null and instead use the [Null Object pattern](https://en.wikipedia.org/wiki/Null_Object_pattern): ``` public class MyParser implements Parser { private static Action DO_NOTHING = new Action() { public void doSomething() { /* do nothing */ } }; public Action findAction(String userInput) { // ... if ( /* we can't find any actions */ ) { return DO_NOTHING; } } } ``` Compare: ``` Parser parser = ParserFactory.getParser(); if (parser == null) { // now what? // this would be an example of where null isn't (or shouldn't be) a valid response } Action action = parser.findAction(someInput); if (action == null) { // do nothing } else { action.doSomething(); } ``` to ``` ParserFactory.getParser().findAction(someInput).doSomething(); ``` which is a much better design because it leads to more concise code. That said, perhaps it is entirely appropriate for the findAction() method to throw an Exception with a meaningful error message -- especially in this case where you are relying on user input. It would be much better for the findAction method to throw an Exception than for the calling method to blow up with a simple NullPointerException with no explanation. ``` try { ParserFactory.getParser().findAction(someInput).doSomething(); } catch(ActionNotFoundException anfe) { userConsole.err(anfe.getMessage()); } ``` Or if you think the try/catch mechanism is too ugly, rather than Do Nothing your default action should provide feedback to the user. ``` public Action findAction(final String userInput) { /* Code to return requested Action if found */ return new Action() { public void doSomething() { userConsole.err("Action not found: " + userInput); } } } ```
271,530
<p>There is an application with an extensive object graph. This graph mainly consists of a set of subgraphs which are connected to the rest of the graph through the only reference. But internally each such subgraph has some number of cross-references among objects. Once in a while such a sub graph needs to be thrown away. Would it be enough just to set to null the only referece which points to that subgraph to make it eligible for garbage collection?</p> <p>My concern is that internal cross-references may "protect" the entire subgraph from garbage collection. In other words, is the garbage collector wise enough to figure out that all references in a subgraph do not leave the boundaries of the subgraph and therefore entire subgraph can be purged.</p>
[ { "answer_id": 271535, "author": "Jon Skeet", "author_id": 22656, "author_profile": "https://Stackoverflow.com/users/22656", "pm_score": 2, "selected": false, "text": "<p>Yes - the garbage collector can cope with circular references etc.</p>\n" }, { "answer_id": 271556, "author": "VonC", "author_id": 6309, "author_profile": "https://Stackoverflow.com/users/6309", "pm_score": 5, "selected": true, "text": "<p>As stated in this <a href=\"https://stackoverflow.com/questions/176745/circular-references-in-java\">SO question</a>, circular reference is well managed.</p>\n\n<p>Java does not do reference counting, it does uses <a href=\"https://en.wikipedia.org/wiki/Tracing_garbage_collection\" rel=\"nofollow noreferrer\">tracing garbage collection</a> (for example mark-and-sweep, copying collection or a some combination thereof). If follows all the active references to find out what objects are \"reachable\" and then it cleans up everything else.</p>\n\n<p>References in objects not themselves reachable don't affect reachability so it doesn't matter if they are null or not.</p>\n\n<p>About the only case in which setting a reference to null might, conceivably, have a significant effect is in discarding a very large object in the middle of a long running method. </p>\n\n<p>In that case, setting null to the reference of the graph will help making an <strong>island of isolation</strong> (even for internal circular references) as described in this <a href=\"http://detailfocused.blogspot.com/2008/03/garbage-collection.html\" rel=\"nofollow noreferrer\">article</a>.</p>\n\n<p>You will find more details about the unreachable state in <a href=\"http://java.sun.com/docs/books/performance/1st_edition/html/JPAppGC.fm.html\" rel=\"nofollow noreferrer\">The Truth About Garbage Collection</a>:</p>\n\n<p><strong>Unreachable</strong></p>\n\n<p>An object enters an unreachable state when no more strong references to it exist.<br>\nWhen an object is unreachable, it is a candidate for collection. </p>\n\n<p>Note the wording:<br>\nJust because an object is a candidate for collection doesn’t mean it will be immediately\ncollected. The JVM is free to delay collection until there is an immediate need for thememory being consumed by the object.</p>\n\n<p>It’s important to note that not just any strong reference will hold an object in memory. These must be references that chain from a garbage collection root. GC roots are a special class of variable that includes:</p>\n\n<ul>\n<li>Temporary variables on the stack (of any thread)</li>\n<li>Static variables (from any class)</li>\n<li>Special references from JNI native code</li>\n</ul>\n\n<p><strong>Circular strong references don’t necessarily cause memory leaks</strong>. \nConsider a code creating two objects, and assigns them references to each other.</p>\n\n<pre><code>public void buidDog() {\n Dog newDog = new Dog();\n Tail newTail = new Tail();\n newDog.tail = newTail;\n newTail.dog = newDog;\n}\n</code></pre>\n\n<p>Before the method returns, there are strong references from the temporary stack variables in the <code>buildDog</code> method pointing to both the <code>Dog</code> and the <code>Tail</code>.</p>\n\n<p>After the <code>buildDog</code> method returns, the <code>Dog</code> and <code>Tail</code> both become unreachable from a root and are candidates for collection (although the VM might not actually collect these objects for an indefinite amount of time).</p>\n" }, { "answer_id": 271562, "author": "izb", "author_id": 974, "author_profile": "https://Stackoverflow.com/users/974", "pm_score": 0, "selected": false, "text": "<p>The JVM operates on the notion of \"islands of unreachability\". If there is an unreachable 'island' of interconnected objects then that set of objects is eligible for garbage collection in its entirety.</p>\n" } ]
2008/11/07
[ "https://Stackoverflow.com/questions/271530", "https://Stackoverflow.com", "https://Stackoverflow.com/users/31993/" ]
There is an application with an extensive object graph. This graph mainly consists of a set of subgraphs which are connected to the rest of the graph through the only reference. But internally each such subgraph has some number of cross-references among objects. Once in a while such a sub graph needs to be thrown away. Would it be enough just to set to null the only referece which points to that subgraph to make it eligible for garbage collection? My concern is that internal cross-references may "protect" the entire subgraph from garbage collection. In other words, is the garbage collector wise enough to figure out that all references in a subgraph do not leave the boundaries of the subgraph and therefore entire subgraph can be purged.
As stated in this [SO question](https://stackoverflow.com/questions/176745/circular-references-in-java), circular reference is well managed. Java does not do reference counting, it does uses [tracing garbage collection](https://en.wikipedia.org/wiki/Tracing_garbage_collection) (for example mark-and-sweep, copying collection or a some combination thereof). If follows all the active references to find out what objects are "reachable" and then it cleans up everything else. References in objects not themselves reachable don't affect reachability so it doesn't matter if they are null or not. About the only case in which setting a reference to null might, conceivably, have a significant effect is in discarding a very large object in the middle of a long running method. In that case, setting null to the reference of the graph will help making an **island of isolation** (even for internal circular references) as described in this [article](http://detailfocused.blogspot.com/2008/03/garbage-collection.html). You will find more details about the unreachable state in [The Truth About Garbage Collection](http://java.sun.com/docs/books/performance/1st_edition/html/JPAppGC.fm.html): **Unreachable** An object enters an unreachable state when no more strong references to it exist. When an object is unreachable, it is a candidate for collection. Note the wording: Just because an object is a candidate for collection doesn’t mean it will be immediately collected. The JVM is free to delay collection until there is an immediate need for thememory being consumed by the object. It’s important to note that not just any strong reference will hold an object in memory. These must be references that chain from a garbage collection root. GC roots are a special class of variable that includes: * Temporary variables on the stack (of any thread) * Static variables (from any class) * Special references from JNI native code **Circular strong references don’t necessarily cause memory leaks**. Consider a code creating two objects, and assigns them references to each other. ``` public void buidDog() { Dog newDog = new Dog(); Tail newTail = new Tail(); newDog.tail = newTail; newTail.dog = newDog; } ``` Before the method returns, there are strong references from the temporary stack variables in the `buildDog` method pointing to both the `Dog` and the `Tail`. After the `buildDog` method returns, the `Dog` and `Tail` both become unreachable from a root and are candidates for collection (although the VM might not actually collect these objects for an indefinite amount of time).
271,546
<p>I have an object instance which I access with the ME as it accesses the instantiated object. I have a method that gets a collection of these objects and I wish to assign the first one to the instantiated object. </p> <p>This is some of the code</p> <pre><code>Dim Books As New BookCollection(True) Books.ListByThemeFeatured(ThemeID, 1) ' Fills the collection If Books.Count &gt; 0 Then Me = Books(0) ' Should set the first item to the current object End If </code></pre> <p>Is this possible?</p> <p>EDIT: Me refers to the class that was instantiated. In this case it is a BookEntity Class. THis method would have been called using the following code</p> <pre><code> Dim Book As New BookEntity Book.FeaturedBook() ' Should fill the book entity with a featured book </code></pre>
[ { "answer_id": 271535, "author": "Jon Skeet", "author_id": 22656, "author_profile": "https://Stackoverflow.com/users/22656", "pm_score": 2, "selected": false, "text": "<p>Yes - the garbage collector can cope with circular references etc.</p>\n" }, { "answer_id": 271556, "author": "VonC", "author_id": 6309, "author_profile": "https://Stackoverflow.com/users/6309", "pm_score": 5, "selected": true, "text": "<p>As stated in this <a href=\"https://stackoverflow.com/questions/176745/circular-references-in-java\">SO question</a>, circular reference is well managed.</p>\n\n<p>Java does not do reference counting, it does uses <a href=\"https://en.wikipedia.org/wiki/Tracing_garbage_collection\" rel=\"nofollow noreferrer\">tracing garbage collection</a> (for example mark-and-sweep, copying collection or a some combination thereof). If follows all the active references to find out what objects are \"reachable\" and then it cleans up everything else.</p>\n\n<p>References in objects not themselves reachable don't affect reachability so it doesn't matter if they are null or not.</p>\n\n<p>About the only case in which setting a reference to null might, conceivably, have a significant effect is in discarding a very large object in the middle of a long running method. </p>\n\n<p>In that case, setting null to the reference of the graph will help making an <strong>island of isolation</strong> (even for internal circular references) as described in this <a href=\"http://detailfocused.blogspot.com/2008/03/garbage-collection.html\" rel=\"nofollow noreferrer\">article</a>.</p>\n\n<p>You will find more details about the unreachable state in <a href=\"http://java.sun.com/docs/books/performance/1st_edition/html/JPAppGC.fm.html\" rel=\"nofollow noreferrer\">The Truth About Garbage Collection</a>:</p>\n\n<p><strong>Unreachable</strong></p>\n\n<p>An object enters an unreachable state when no more strong references to it exist.<br>\nWhen an object is unreachable, it is a candidate for collection. </p>\n\n<p>Note the wording:<br>\nJust because an object is a candidate for collection doesn’t mean it will be immediately\ncollected. The JVM is free to delay collection until there is an immediate need for thememory being consumed by the object.</p>\n\n<p>It’s important to note that not just any strong reference will hold an object in memory. These must be references that chain from a garbage collection root. GC roots are a special class of variable that includes:</p>\n\n<ul>\n<li>Temporary variables on the stack (of any thread)</li>\n<li>Static variables (from any class)</li>\n<li>Special references from JNI native code</li>\n</ul>\n\n<p><strong>Circular strong references don’t necessarily cause memory leaks</strong>. \nConsider a code creating two objects, and assigns them references to each other.</p>\n\n<pre><code>public void buidDog() {\n Dog newDog = new Dog();\n Tail newTail = new Tail();\n newDog.tail = newTail;\n newTail.dog = newDog;\n}\n</code></pre>\n\n<p>Before the method returns, there are strong references from the temporary stack variables in the <code>buildDog</code> method pointing to both the <code>Dog</code> and the <code>Tail</code>.</p>\n\n<p>After the <code>buildDog</code> method returns, the <code>Dog</code> and <code>Tail</code> both become unreachable from a root and are candidates for collection (although the VM might not actually collect these objects for an indefinite amount of time).</p>\n" }, { "answer_id": 271562, "author": "izb", "author_id": 974, "author_profile": "https://Stackoverflow.com/users/974", "pm_score": 0, "selected": false, "text": "<p>The JVM operates on the notion of \"islands of unreachability\". If there is an unreachable 'island' of interconnected objects then that set of objects is eligible for garbage collection in its entirety.</p>\n" } ]
2008/11/07
[ "https://Stackoverflow.com/questions/271546", "https://Stackoverflow.com", "https://Stackoverflow.com/users/23230/" ]
I have an object instance which I access with the ME as it accesses the instantiated object. I have a method that gets a collection of these objects and I wish to assign the first one to the instantiated object. This is some of the code ``` Dim Books As New BookCollection(True) Books.ListByThemeFeatured(ThemeID, 1) ' Fills the collection If Books.Count > 0 Then Me = Books(0) ' Should set the first item to the current object End If ``` Is this possible? EDIT: Me refers to the class that was instantiated. In this case it is a BookEntity Class. THis method would have been called using the following code ``` Dim Book As New BookEntity Book.FeaturedBook() ' Should fill the book entity with a featured book ```
As stated in this [SO question](https://stackoverflow.com/questions/176745/circular-references-in-java), circular reference is well managed. Java does not do reference counting, it does uses [tracing garbage collection](https://en.wikipedia.org/wiki/Tracing_garbage_collection) (for example mark-and-sweep, copying collection or a some combination thereof). If follows all the active references to find out what objects are "reachable" and then it cleans up everything else. References in objects not themselves reachable don't affect reachability so it doesn't matter if they are null or not. About the only case in which setting a reference to null might, conceivably, have a significant effect is in discarding a very large object in the middle of a long running method. In that case, setting null to the reference of the graph will help making an **island of isolation** (even for internal circular references) as described in this [article](http://detailfocused.blogspot.com/2008/03/garbage-collection.html). You will find more details about the unreachable state in [The Truth About Garbage Collection](http://java.sun.com/docs/books/performance/1st_edition/html/JPAppGC.fm.html): **Unreachable** An object enters an unreachable state when no more strong references to it exist. When an object is unreachable, it is a candidate for collection. Note the wording: Just because an object is a candidate for collection doesn’t mean it will be immediately collected. The JVM is free to delay collection until there is an immediate need for thememory being consumed by the object. It’s important to note that not just any strong reference will hold an object in memory. These must be references that chain from a garbage collection root. GC roots are a special class of variable that includes: * Temporary variables on the stack (of any thread) * Static variables (from any class) * Special references from JNI native code **Circular strong references don’t necessarily cause memory leaks**. Consider a code creating two objects, and assigns them references to each other. ``` public void buidDog() { Dog newDog = new Dog(); Tail newTail = new Tail(); newDog.tail = newTail; newTail.dog = newDog; } ``` Before the method returns, there are strong references from the temporary stack variables in the `buildDog` method pointing to both the `Dog` and the `Tail`. After the `buildDog` method returns, the `Dog` and `Tail` both become unreachable from a root and are candidates for collection (although the VM might not actually collect these objects for an indefinite amount of time).
271,561
<p>In c#, is there any difference in the excecution speed for the order in which you state the condition?</p> <pre><code>if (null != variable) ... if (variable != null) ... </code></pre> <p>Since recently, I saw the first one quite often, and it caught my attention since I was used to the second one.</p> <p>If there is no difference, what is the advantage of the first one?</p>
[ { "answer_id": 271573, "author": "Lasse V. Karlsen", "author_id": 267, "author_profile": "https://Stackoverflow.com/users/267", "pm_score": 3, "selected": false, "text": "<p>I guess this is a C programmer that has switched languages.</p>\n\n<p>In C, you can write the following:</p>\n\n<pre><code>int i = 0;\nif (i = 1)\n{\n ...\n}\n</code></pre>\n\n<p>Notice the use of a single equal sign there, which means the code will assign 1 to the variable i, then return 1 (an assignment is an expression), and use 1 in the if-statement, which will be handled as true. In other words, the above is a bug.</p>\n\n<p>In C# however, this is not possible. There is indeed no difference between the two.</p>\n" }, { "answer_id": 271574, "author": "Rik", "author_id": 5409, "author_profile": "https://Stackoverflow.com/users/5409", "pm_score": 2, "selected": false, "text": "<p>In earlier times, people would forget the '!' (or the extra '=' for equality, which is more difficult to spot) and do an assignment instead of a comparison. putting the null in front eliminates the possibility for the bug, since null is not an l-value (I.E. it can't be assigned to).</p>\n\n<p>Most modern compilers give a warning when you do an assignment in a conditional nowadays, and C# actually gives an error. Most people just stick with the var == null scheme since it's easier to read for some people.</p>\n" }, { "answer_id": 271575, "author": "Jon Skeet", "author_id": 22656, "author_profile": "https://Stackoverflow.com/users/22656", "pm_score": 8, "selected": true, "text": "<p>It's a hold-over from C. In C, if you either use a bad compiler or don't have warnings turned up high enough, this will compile with no warning whatsoever (and is indeed legal code):</p>\n\n<pre><code>// Probably wrong\nif (x = 5)\n</code></pre>\n\n<p>when you actually probably meant</p>\n\n<pre><code>if (x == 5)\n</code></pre>\n\n<p>You can work around this in C by doing:</p>\n\n<pre><code>if (5 == x)\n</code></pre>\n\n<p>A typo here will result in invalid code.</p>\n\n<p>Now, in C# this is all piffle. Unless you're comparing two Boolean values (which is rare, IME) you can write the more readable code, as an \"if\" statement requires a Boolean expression to start with, and the type of \"<code>x=5</code>\" is <code>Int32</code>, not <code>Boolean</code>.</p>\n\n<p>I suggest that if you see this in your colleagues' code, you educate them in the ways of modern languages, and suggest they write the more natural form in future.</p>\n" }, { "answer_id": 271581, "author": "TheCodeJunkie", "author_id": 25319, "author_profile": "https://Stackoverflow.com/users/25319", "pm_score": 0, "selected": false, "text": "<p>To me it's always been which style you prefer</p>\n\n<p>@Shy - Then again if you confuse the operators then you should want to get a compilation error or you will be running code with a bug - a bug that come back and bite you later down the road since it produced unexpected behaviour</p>\n" }, { "answer_id": 970563, "author": "Gad", "author_id": 25152, "author_profile": "https://Stackoverflow.com/users/25152", "pm_score": -1, "selected": false, "text": "<p>One more thing... If you are comparing a variable to a constant (integer or string for ex.), putting the constant on the left is good practice because you'll never run into NullPointerExceptions :</p>\n\n<pre><code>int i;\nif(i==1){ // Exception raised: i is not initialized. (C/C++)\n doThis();\n}\n</code></pre>\n\n<p>whereas</p>\n\n<pre><code>int i;\nif(1==i){ // OK, but the condition is not met.\n doThis();\n}\n</code></pre>\n\n<p>Now, since by default C# instanciates all variables, you shouldn't have that problem in that language.</p>\n" }, { "answer_id": 10741601, "author": "DanW", "author_id": 1415586, "author_profile": "https://Stackoverflow.com/users/1415586", "pm_score": 4, "selected": false, "text": "<p>There is a good reason to use null first: <code>if(null == myDuck)</code></p>\n\n<p>If your <code>class Duck</code> overrides the <code>==</code> operator, then <code>if(myDuck == null)</code> can go into an infinite loop.</p>\n\n<p>Using <code>null</code> first uses a default equality comparator and actually does what you were intending.</p>\n\n<p>(I hear you get used to reading code written that way eventually - I just haven't experienced that transformation yet).</p>\n\n<p>Here is an example:</p>\n\n<pre><code>public class myDuck\n{\n public int quacks;\n static override bool operator ==(myDuck a, myDuck b)\n {\n // these will overflow the stack - because the a==null reenters this function from the top again\n if (a == null &amp;&amp; b == null)\n return true;\n if (a == null || b == null)\n return false;\n\n // these wont loop\n if (null == a &amp;&amp; null == b)\n return true;\n if (null == a || null == b)\n return false;\n return a.quacks == b.quacks; // this goes to the integer comparison\n }\n}\n</code></pre>\n" }, { "answer_id": 14622883, "author": "Oliver", "author_id": 1838048, "author_profile": "https://Stackoverflow.com/users/1838048", "pm_score": 4, "selected": false, "text": "<p>Like everybody already noted it comes more or less from the C language where you could get false code if you accidentally forget the second equals sign. But there is another reason that also matches C#: Readability.</p>\n\n<p>Just take this simple example:</p>\n\n<pre><code>if(someVariableThatShouldBeChecked != null\n &amp;&amp; anotherOne != null\n &amp;&amp; justAnotherCheckThatIsNeededForTestingNullity != null\n &amp;&amp; allTheseChecksAreReallyBoring != null\n &amp;&amp; thereSeemsToBeADesignFlawIfSoManyChecksAreNeeded != null)\n{\n // ToDo: Everything is checked, do something...\n}\n</code></pre>\n\n<p>If you would simply swap all the <em>null</em> words to the beginning you can much easier spot all the checks:</p>\n\n<pre><code>if(null != someVariableThatShouldBeChecked\n &amp;&amp; null != anotherOne\n &amp;&amp; null != justAnotherCheckThatIsNeededForTestingNullity\n &amp;&amp; null != allTheseChecksAreReallyBoring\n &amp;&amp; null != thereSeemsToBeADesignFlawIfSoManyChecksAreNeeded)\n{\n // ToDo: Everything is checked, do something...\n}\n</code></pre>\n\n<p>So this example is maybe a bad example (refer to coding guidelines) but just think about you quick scroll over a complete code file. By simply seeing the pattern</p>\n\n<pre><code>if(null ...\n</code></pre>\n\n<p>you immediately know what's coming next.</p>\n\n<p>If it would be the other way around, you always have to <em>scan</em> to the end of the line to see the nullity check, just letting you stumble for a second to find out what kind of check is made there. So maybe syntax highlighting may help you, but you are always slower when those keywords are at the end of the line instead of the front.</p>\n" }, { "answer_id": 26175819, "author": "Gokkula Sudan R", "author_id": 4089930, "author_profile": "https://Stackoverflow.com/users/4089930", "pm_score": 2, "selected": false, "text": "<p>I don't see any advantage in following this convention. In C, where boolean types don't exist, it's useful to write</p>\n\n<pre><code>if( 5 == variable)\n</code></pre>\n\n<p>rather than</p>\n\n<pre><code>if (variable == 5)\n</code></pre>\n\n<p>because if you forget one of the eaqual sign, you end up with</p>\n\n<pre><code>if (variable = 5)\n</code></pre>\n\n<p>which assigns 5 to variable and always evaluate to true. But in Java, a boolean is a boolean. And with !=, there is no reason at all.</p>\n\n<p>One good advice, though, is to write</p>\n\n<pre><code>if (CONSTANT.equals(myString))\n</code></pre>\n\n<p>rather than</p>\n\n<pre><code>if (myString.equals(CONSTANT))\n</code></pre>\n\n<p>because it helps avoiding NullPointerExceptions.</p>\n\n<p>My advice would be to ask for a justification of the rule. If there's none, why follow it? It doesn't help readability</p>\n" }, { "answer_id": 63130262, "author": "Anand Shah", "author_id": 4129423, "author_profile": "https://Stackoverflow.com/users/4129423", "pm_score": 0, "selected": false, "text": "<p>As many pointed out, it is mostly in old C code it was used to identify compilation error, as compiler accepted it as legal</p>\n<p>New programming language like java, go are smart enough to capture such compilation errors</p>\n<p>One should not use &quot;null != variable&quot; like conditions in code as it very unreadable</p>\n" } ]
2008/11/07
[ "https://Stackoverflow.com/questions/271561", "https://Stackoverflow.com", "https://Stackoverflow.com/users/26070/" ]
In c#, is there any difference in the excecution speed for the order in which you state the condition? ``` if (null != variable) ... if (variable != null) ... ``` Since recently, I saw the first one quite often, and it caught my attention since I was used to the second one. If there is no difference, what is the advantage of the first one?
It's a hold-over from C. In C, if you either use a bad compiler or don't have warnings turned up high enough, this will compile with no warning whatsoever (and is indeed legal code): ``` // Probably wrong if (x = 5) ``` when you actually probably meant ``` if (x == 5) ``` You can work around this in C by doing: ``` if (5 == x) ``` A typo here will result in invalid code. Now, in C# this is all piffle. Unless you're comparing two Boolean values (which is rare, IME) you can write the more readable code, as an "if" statement requires a Boolean expression to start with, and the type of "`x=5`" is `Int32`, not `Boolean`. I suggest that if you see this in your colleagues' code, you educate them in the ways of modern languages, and suggest they write the more natural form in future.
271,569
<p>I can't seem to set a ContentTemplate for a ComboBoxItem. There reason I'm trying to do this is I want to have 2 appearances for my data in the combo box. When the combo box is open (menu is down) I want a text box (with the name of the image) and an image control below it. When I select the item I want the combo box to just show a text box with the name of the image.</p> <p>I thought I could achieve this by modifying the ItemTemplate and ItemContainerStyle of the ComboBox. The ItemContainerStyle contains the following ContentPresenter:</p> <pre><code>&lt;ContentPresenter HorizontalAlignment="Left" Margin="{TemplateBinding Padding}" x:Name="contentPresenter" Content="{TemplateBinding Content}" ContentTemplate="{TemplateBinding ContentTemplate}"/&gt; </code></pre> <p>So I assumed that I could just set the ContentTemplate here and it would work. But I can't seem to get it to work:</p> <pre><code>&lt;DataTemplate x:Key="ComboBoxDataTemplate"&gt; &lt;Grid&gt; &lt;TextBlock Text="{Binding Path='Name'}"/&gt; &lt;/Grid&gt; &lt;/DataTemplate&gt; &lt;DataTemplate x:Key="ComboBoxItemTemplate"&gt; &lt;StackPanel&gt; &lt;TextBlock Text="{Binding Path='Name'}"/&gt; &lt;Image Source="{Binding Path='Source'}" Width="64" Height="64"/&gt; &lt;/StackPanel&gt; &lt;/DataTemplate&gt; &lt;Style x:Key="ComboBoxItemStyle1" TargetType="ComboBoxItem"&gt; ... &lt;Setter Property="ContentTemplate" Value="{StaticResource ComboBoxItemTemplate}"/&gt; ... </code></pre> <p>Here's my combo box:</p> <pre><code>&lt;ComboBox Width="70" Margin="3,0,0,0" ItemsSource="{StaticResource Source}" ItemTemplate="{StaticResource ComboBoxDataTemplate}" ItemContainerStyle="{StaticResource ComboBoxItemStyle1}" /&gt; </code></pre> <p>The only way I can get this to work is to remove the ContentPresenter from the ItemContainerStyle, and replace it with the contents of my custom template (ComboBoxItemTemplate). But I didn't think I should use this approach as it would mean the ContentPresenter no longer exists (and code in the ComboBox might rely on it existing).</p> <p>Any help on showing a combo box with a different drop down and selected template would be greatly appreciated!</p>
[ { "answer_id": 271707, "author": "Jobi Joy", "author_id": 8091, "author_profile": "https://Stackoverflow.com/users/8091", "pm_score": 0, "selected": false, "text": "<p>You can achieve this with just ItemsContainerStyle. Add your TextBlock and Image instead of the ContentPresenter. Add the VisualStateManager and toggle the Visibility of the Image control based on the Selected State of the VSM. </p>\n" }, { "answer_id": 307010, "author": "Jobi Joy", "author_id": 8091, "author_profile": "https://Stackoverflow.com/users/8091", "pm_score": 0, "selected": false, "text": "<p>DataTemplate is mainly for your Data visualization, It is better to give all UI related dynamics inside the ControlTemplate(Control behaviors). There is no potential issue if you dont have a ContentPresenter. The only issue is that if you want to reuse this ControlTemplate from some other ComboBox. Then you can declare another clean Control template with a ContentPresenter there.</p>\n" }, { "answer_id": 3708512, "author": "CodeNaked", "author_id": 142794, "author_profile": "https://Stackoverflow.com/users/142794", "pm_score": 4, "selected": true, "text": "<p>The ComboBox.ItemTemplate is just a convenient way to set the ComboBoxItem.ContentTemplate. So your code above basically tries to set the ComboBoxItem.ContentTemplate twice.</p>\n\n<p>As Jobi pointed out, you could try to use just a custom Style. You can safely exclude the ContentPresenter, if you always know the type of the Content. The ContentPresenter just allows you to use a DataTemplate to display some random data. But you could just replace it with a TextBlock and an Image. You just lose the ability to specify a DataTemplate.</p>\n\n<p>The problem with Jobi's approach is that the select item won't show it's image, even if it's in the drop-down. Really the selected item is displayed in two locations (the drop-down and the main body of the ComboBox). In one location you want one DataTemplate, and in you want a different DataTemplate in the other.</p>\n\n<p>Your best bet is to restyle the ComboBox. You can get the default Style from <a href=\"http://msdn.microsoft.com/en-us/library/dd334408(v=VS.95).aspx1.1.\" rel=\"noreferrer\">here</a>. There is a ContentPresenter with the name \"ContentPresenter\". You would need to:</p>\n\n<ol>\n<li>Remove/change the name of the ContentPresenter, so the ComboBox will not automatically set the Content/ContentTemplate properties</li>\n<li>Bind the ContentPresenter.Content property like so: \"{TemplateBinding SelectedObject}\"</li>\n<li>Set the ContentPresenter.ContentTemplate property to your DataTemplate without the Image</li>\n<li>Set the ComboBox.ItemTemplate property to the DataTemplate with an Image and TextBlock like you were</li>\n<li>Give the ComboBox Style an explicit key, like x:Key=\"MyComboBoxStyle\"</li>\n<li>Use the Style on your ComboBox, like Style=\"{StaticResource MyComboBoxStyle}\"</li>\n</ol>\n\n<p>This effectively ignores the ComboBoxItem.ContentTemplate when displaying the selected item in the body of the ComboBox, but uses it when display the ComboBoxItem in the drop-down.</p>\n" } ]
2008/11/07
[ "https://Stackoverflow.com/questions/271569", "https://Stackoverflow.com", "https://Stackoverflow.com/users/986/" ]
I can't seem to set a ContentTemplate for a ComboBoxItem. There reason I'm trying to do this is I want to have 2 appearances for my data in the combo box. When the combo box is open (menu is down) I want a text box (with the name of the image) and an image control below it. When I select the item I want the combo box to just show a text box with the name of the image. I thought I could achieve this by modifying the ItemTemplate and ItemContainerStyle of the ComboBox. The ItemContainerStyle contains the following ContentPresenter: ``` <ContentPresenter HorizontalAlignment="Left" Margin="{TemplateBinding Padding}" x:Name="contentPresenter" Content="{TemplateBinding Content}" ContentTemplate="{TemplateBinding ContentTemplate}"/> ``` So I assumed that I could just set the ContentTemplate here and it would work. But I can't seem to get it to work: ``` <DataTemplate x:Key="ComboBoxDataTemplate"> <Grid> <TextBlock Text="{Binding Path='Name'}"/> </Grid> </DataTemplate> <DataTemplate x:Key="ComboBoxItemTemplate"> <StackPanel> <TextBlock Text="{Binding Path='Name'}"/> <Image Source="{Binding Path='Source'}" Width="64" Height="64"/> </StackPanel> </DataTemplate> <Style x:Key="ComboBoxItemStyle1" TargetType="ComboBoxItem"> ... <Setter Property="ContentTemplate" Value="{StaticResource ComboBoxItemTemplate}"/> ... ``` Here's my combo box: ``` <ComboBox Width="70" Margin="3,0,0,0" ItemsSource="{StaticResource Source}" ItemTemplate="{StaticResource ComboBoxDataTemplate}" ItemContainerStyle="{StaticResource ComboBoxItemStyle1}" /> ``` The only way I can get this to work is to remove the ContentPresenter from the ItemContainerStyle, and replace it with the contents of my custom template (ComboBoxItemTemplate). But I didn't think I should use this approach as it would mean the ContentPresenter no longer exists (and code in the ComboBox might rely on it existing). Any help on showing a combo box with a different drop down and selected template would be greatly appreciated!
The ComboBox.ItemTemplate is just a convenient way to set the ComboBoxItem.ContentTemplate. So your code above basically tries to set the ComboBoxItem.ContentTemplate twice. As Jobi pointed out, you could try to use just a custom Style. You can safely exclude the ContentPresenter, if you always know the type of the Content. The ContentPresenter just allows you to use a DataTemplate to display some random data. But you could just replace it with a TextBlock and an Image. You just lose the ability to specify a DataTemplate. The problem with Jobi's approach is that the select item won't show it's image, even if it's in the drop-down. Really the selected item is displayed in two locations (the drop-down and the main body of the ComboBox). In one location you want one DataTemplate, and in you want a different DataTemplate in the other. Your best bet is to restyle the ComboBox. You can get the default Style from [here](http://msdn.microsoft.com/en-us/library/dd334408(v=VS.95).aspx1.1.). There is a ContentPresenter with the name "ContentPresenter". You would need to: 1. Remove/change the name of the ContentPresenter, so the ComboBox will not automatically set the Content/ContentTemplate properties 2. Bind the ContentPresenter.Content property like so: "{TemplateBinding SelectedObject}" 3. Set the ContentPresenter.ContentTemplate property to your DataTemplate without the Image 4. Set the ComboBox.ItemTemplate property to the DataTemplate with an Image and TextBlock like you were 5. Give the ComboBox Style an explicit key, like x:Key="MyComboBoxStyle" 6. Use the Style on your ComboBox, like Style="{StaticResource MyComboBoxStyle}" This effectively ignores the ComboBoxItem.ContentTemplate when displaying the selected item in the body of the ComboBox, but uses it when display the ComboBoxItem in the drop-down.
271,571
<p>Using <a href="http://search.cpan.org/dist/DBIx-Class/" rel="nofollow noreferrer">DBIx::Class</a> and I have a resultset which needs to be filtered by data which cannot be generated by SQL. What I need to do is something effectively equivalent to this hypothetical example:</p> <pre><code>my $resultset = $schema-&gt;resultset('Service')-&gt;search(\%search); my $new_resultset = $resultset-&gt;filter( sub { my $web_service = shift; return $web_service-&gt;is_available; } ); </code></pre> <p>Reading through the docs gives me no clue how to accomplish a strategy like this.</p>
[ { "answer_id": 271646, "author": "Aristotle Pagaltzis", "author_id": 9410, "author_profile": "https://Stackoverflow.com/users/9410", "pm_score": 4, "selected": true, "text": "<p>You can’t really, due to the goals for which DBIC result sets are designed:</p>\n\n<ul>\n<li>They compile down to SQL and run a single query, which they do no earlier than when you ask for results.</li>\n<li>They are composable.</li>\n</ul>\n\n<p>Allowing filtering by code that runs on the Perl side would make it extremely hairy to achieve those properties, and would hide the fact that such result sets actually run N queries when composed.</p>\n\n<p>Why do you want this, anyway? Why is simply retrieving the results and filtering them yourself insufficient?</p>\n\n<ul>\n<li><p><b>Encapsulation</b>? (Eg. hiding the filtering logic in your business logic layer but kicking off the query in the display logic layer.) Then write a custom ResultSet subclass that has an accessor that runs the query and does the desired filtering.</p></li>\n<li><p><b>Overhead</b>? (Eg. you will reject most results so you don’t want the overhead of creating objects for them.) Then use HashRefInflator.</p></li>\n</ul>\n" }, { "answer_id": 5144361, "author": "cubabit", "author_id": 76644, "author_profile": "https://Stackoverflow.com/users/76644", "pm_score": 0, "selected": false, "text": "<p>If you filter the results and end up with a list of rows you can create a new resultset like this: <a href=\"http://search.cpan.org/~abraxxa/DBIx-Class-0.08127/lib/DBIx/Class/Manual/Cookbook.pod#Creating_a_result_set_from_a_set_of_rows\" rel=\"nofollow\">http://search.cpan.org/~abraxxa/DBIx-Class-0.08127/lib/DBIx/Class/Manual/Cookbook.pod#Creating_a_result_set_from_a_set_of_rows</a>.</p>\n\n<p>This may keep things consistent in keeping the results as a resultset but I imagine you would not be able to chain it or use any other resultset methods on it.</p>\n" } ]
2008/11/07
[ "https://Stackoverflow.com/questions/271571", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8003/" ]
Using [DBIx::Class](http://search.cpan.org/dist/DBIx-Class/) and I have a resultset which needs to be filtered by data which cannot be generated by SQL. What I need to do is something effectively equivalent to this hypothetical example: ``` my $resultset = $schema->resultset('Service')->search(\%search); my $new_resultset = $resultset->filter( sub { my $web_service = shift; return $web_service->is_available; } ); ``` Reading through the docs gives me no clue how to accomplish a strategy like this.
You can’t really, due to the goals for which DBIC result sets are designed: * They compile down to SQL and run a single query, which they do no earlier than when you ask for results. * They are composable. Allowing filtering by code that runs on the Perl side would make it extremely hairy to achieve those properties, and would hide the fact that such result sets actually run N queries when composed. Why do you want this, anyway? Why is simply retrieving the results and filtering them yourself insufficient? * **Encapsulation**? (Eg. hiding the filtering logic in your business logic layer but kicking off the query in the display logic layer.) Then write a custom ResultSet subclass that has an accessor that runs the query and does the desired filtering. * **Overhead**? (Eg. you will reject most results so you don’t want the overhead of creating objects for them.) Then use HashRefInflator.
271,577
<p>i met a problem with iphone simulator application directory, when i run the application everytime, the name of application directory was changed each of time,can anyone tell me how to keep a static application directory ?</p>
[ { "answer_id": 271956, "author": "Louis Gerbarg", "author_id": 30506, "author_profile": "https://Stackoverflow.com/users/30506", "pm_score": 0, "selected": false, "text": "<p>If you simply relaunch the app from within the simulator springboard it will keep using the same directory. If you rebuild the app in Xcode it will move, and there is no way to prevent that. Xcode should migrate any data you have from the old directory to the new directory when it installs the new build.</p>\n" }, { "answer_id": 579088, "author": "ShoeLace", "author_id": 3825, "author_profile": "https://Stackoverflow.com/users/3825", "pm_score": 3, "selected": true, "text": "<p>i'm going to take a guess here and say..</p>\n\n<p>you don't need a static directory.</p>\n\n<p>I think what you need is to get the 'base directory' programatically.</p>\n\n<pre>\nNSString *docsDirectory = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0];\nNSString *path = [docsDirectory stringByAppendingPathComponent:@\"fileName.txt\"];\n</pre>\n\n<p>you should be saving your user files there (or somewhere similar)</p>\n\n<p>or alternatively something like</p>\n\n<pre>\nNSBundle* bundle = [NSBundle mainBundle];\nNSString* path = [bundle executablePath]\n//or\nNSString* path = [bundle resourcePath];\n</pre>\n\n<p>and then append your own paths onto that.</p>\n\n<p>hope that helps.</p>\n\n<p>NEW INFO:</p>\n\n<p>If you are saving information, (a log, stats etc..) you can retrieve the files saved in the NSDocumentDirectory above using the Xcode organiser.</p>\n\n<ul>\n<li>select your device</li>\n<li>got the summary tab</li>\n<li>find you application in 'Applications' section.</li>\n<li>expand the entry and it should have an 'Applcation data' entry.</li>\n<li>press the down arrow on the right to save your files.</li>\n</ul>\n" }, { "answer_id": 1047476, "author": "n13", "author_id": 129213, "author_profile": "https://Stackoverflow.com/users/129213", "pm_score": 0, "selected": false, "text": "<p>I guess the problem is that XCode sometimes \"loses\" files.</p>\n\n<p>So I lost all my preferences just now, and unable to get them back because XCode, once they are lost, can't recover them.</p>\n\n<p>Here is what I did to resolve:</p>\n\n<ul>\n<li>Open the console, note the directory it's using for the new launch, in my case that was \n/Users/nik/Library/Application Support/iPhone Simulator/User/Applications/D713AFE6-D6B3-4D1E-A1B9-28FD679FD124/Documents/</li>\n<li>Quit the app</li>\n<li>Go to /Users/nik/Library/Application Support/iPhone Simulator/User/Applications and look for a launch that still has the preferences files in /Documents</li>\n<li>Copy the preferences files to the last launch location above</li>\n<li>Launch again - now it all worked. XCode created yet another temporary launch directory, but moved the files from the \"last\" launch over. </li>\n</ul>\n\n<p>I am now also saving the preferences file in another location so next time this happens I have them handy.</p>\n" } ]
2008/11/07
[ "https://Stackoverflow.com/questions/271577", "https://Stackoverflow.com", "https://Stackoverflow.com/users/35405/" ]
i met a problem with iphone simulator application directory, when i run the application everytime, the name of application directory was changed each of time,can anyone tell me how to keep a static application directory ?
i'm going to take a guess here and say.. you don't need a static directory. I think what you need is to get the 'base directory' programatically. ``` NSString *docsDirectory = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0]; NSString *path = [docsDirectory stringByAppendingPathComponent:@"fileName.txt"]; ``` you should be saving your user files there (or somewhere similar) or alternatively something like ``` NSBundle* bundle = [NSBundle mainBundle]; NSString* path = [bundle executablePath] //or NSString* path = [bundle resourcePath]; ``` and then append your own paths onto that. hope that helps. NEW INFO: If you are saving information, (a log, stats etc..) you can retrieve the files saved in the NSDocumentDirectory above using the Xcode organiser. * select your device * got the summary tab * find you application in 'Applications' section. * expand the entry and it should have an 'Applcation data' entry. * press the down arrow on the right to save your files.
271,583
<p>I have a CGI-script which produces a <code>.pdf</code> file from the HTML page. My problem is that when it is launched from the Web Browser, there is no creation of the <code>.pdf</code> document.</p> <p>What I have done so far:</p> <ul> <li>chmod settings set to above recommended (777)</li> <li>tested normal output on the file from the script, which works fine</li> <li>when running locally on the server from the command line, the <code>.cgi</code> script works</li> </ul> <p>Why does the script not work when run from the web browser?</p> <pre><code>#!/usr/bin/perl use LWP::Simple; use HTML::HTMLDoc; use CGI; print "Content-type: text/html\n\n"; print "&lt;html&gt;&lt;head&gt;&lt;title&gt;test&lt;/title&gt;&lt;/head&gt;"; print "&lt;body&gt;"; my $htmldoc-&gt;set_html_content(qq~&lt;html&gt;&lt;body&gt;A PDF file&lt;/body&gt;&lt;/html&gt;~); my $pdf = $htmldoc-&gt;generate_pdf() or die($!); $pdf-&gt;to_file('/var/www/tom.pdf'); print "&lt;/body&gt;&lt;/html&gt;"; </code></pre>
[ { "answer_id": 271956, "author": "Louis Gerbarg", "author_id": 30506, "author_profile": "https://Stackoverflow.com/users/30506", "pm_score": 0, "selected": false, "text": "<p>If you simply relaunch the app from within the simulator springboard it will keep using the same directory. If you rebuild the app in Xcode it will move, and there is no way to prevent that. Xcode should migrate any data you have from the old directory to the new directory when it installs the new build.</p>\n" }, { "answer_id": 579088, "author": "ShoeLace", "author_id": 3825, "author_profile": "https://Stackoverflow.com/users/3825", "pm_score": 3, "selected": true, "text": "<p>i'm going to take a guess here and say..</p>\n\n<p>you don't need a static directory.</p>\n\n<p>I think what you need is to get the 'base directory' programatically.</p>\n\n<pre>\nNSString *docsDirectory = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0];\nNSString *path = [docsDirectory stringByAppendingPathComponent:@\"fileName.txt\"];\n</pre>\n\n<p>you should be saving your user files there (or somewhere similar)</p>\n\n<p>or alternatively something like</p>\n\n<pre>\nNSBundle* bundle = [NSBundle mainBundle];\nNSString* path = [bundle executablePath]\n//or\nNSString* path = [bundle resourcePath];\n</pre>\n\n<p>and then append your own paths onto that.</p>\n\n<p>hope that helps.</p>\n\n<p>NEW INFO:</p>\n\n<p>If you are saving information, (a log, stats etc..) you can retrieve the files saved in the NSDocumentDirectory above using the Xcode organiser.</p>\n\n<ul>\n<li>select your device</li>\n<li>got the summary tab</li>\n<li>find you application in 'Applications' section.</li>\n<li>expand the entry and it should have an 'Applcation data' entry.</li>\n<li>press the down arrow on the right to save your files.</li>\n</ul>\n" }, { "answer_id": 1047476, "author": "n13", "author_id": 129213, "author_profile": "https://Stackoverflow.com/users/129213", "pm_score": 0, "selected": false, "text": "<p>I guess the problem is that XCode sometimes \"loses\" files.</p>\n\n<p>So I lost all my preferences just now, and unable to get them back because XCode, once they are lost, can't recover them.</p>\n\n<p>Here is what I did to resolve:</p>\n\n<ul>\n<li>Open the console, note the directory it's using for the new launch, in my case that was \n/Users/nik/Library/Application Support/iPhone Simulator/User/Applications/D713AFE6-D6B3-4D1E-A1B9-28FD679FD124/Documents/</li>\n<li>Quit the app</li>\n<li>Go to /Users/nik/Library/Application Support/iPhone Simulator/User/Applications and look for a launch that still has the preferences files in /Documents</li>\n<li>Copy the preferences files to the last launch location above</li>\n<li>Launch again - now it all worked. XCode created yet another temporary launch directory, but moved the files from the \"last\" launch over. </li>\n</ul>\n\n<p>I am now also saving the preferences file in another location so next time this happens I have them handy.</p>\n" } ]
2008/11/07
[ "https://Stackoverflow.com/questions/271583", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
I have a CGI-script which produces a `.pdf` file from the HTML page. My problem is that when it is launched from the Web Browser, there is no creation of the `.pdf` document. What I have done so far: * chmod settings set to above recommended (777) * tested normal output on the file from the script, which works fine * when running locally on the server from the command line, the `.cgi` script works Why does the script not work when run from the web browser? ``` #!/usr/bin/perl use LWP::Simple; use HTML::HTMLDoc; use CGI; print "Content-type: text/html\n\n"; print "<html><head><title>test</title></head>"; print "<body>"; my $htmldoc->set_html_content(qq~<html><body>A PDF file</body></html>~); my $pdf = $htmldoc->generate_pdf() or die($!); $pdf->to_file('/var/www/tom.pdf'); print "</body></html>"; ```
i'm going to take a guess here and say.. you don't need a static directory. I think what you need is to get the 'base directory' programatically. ``` NSString *docsDirectory = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0]; NSString *path = [docsDirectory stringByAppendingPathComponent:@"fileName.txt"]; ``` you should be saving your user files there (or somewhere similar) or alternatively something like ``` NSBundle* bundle = [NSBundle mainBundle]; NSString* path = [bundle executablePath] //or NSString* path = [bundle resourcePath]; ``` and then append your own paths onto that. hope that helps. NEW INFO: If you are saving information, (a log, stats etc..) you can retrieve the files saved in the NSDocumentDirectory above using the Xcode organiser. * select your device * got the summary tab * find you application in 'Applications' section. * expand the entry and it should have an 'Applcation data' entry. * press the down arrow on the right to save your files.
271,588
<p>Is there a way to pass null arguments to C# methods (something like null arguments in c++)?</p> <p>For example:</p> <p>Is it possible to translate the following c++ function to C# method:</p> <pre><code>private void Example(int* arg1, int* arg2) { if(arg1 == null) { //do something } if(arg2 == null) { //do something else } } </code></pre>
[ { "answer_id": 271593, "author": "Marcin K", "author_id": 28722, "author_profile": "https://Stackoverflow.com/users/28722", "pm_score": 3, "selected": false, "text": "<p>From C# 2.0:</p>\n\n<pre><code>private void Example(int? arg1, int? arg2)\n{\n if(arg1 == null)\n {\n //do something\n }\n if(arg2 == null)\n {\n //do something else\n }\n}\n</code></pre>\n" }, { "answer_id": 271594, "author": "MADMap", "author_id": 17558, "author_profile": "https://Stackoverflow.com/users/17558", "pm_score": 3, "selected": false, "text": "<p>You can use NullableValueTypes (like int?) for this. The code would be like this:</p>\n\n<pre><code>private void Example(int? arg1, int? arg2)\n{\n if(!arg1.HasValue)\n {\n //do something\n }\n if(!arg2.HasValue)\n {\n //do something else\n }\n}\n</code></pre>\n" }, { "answer_id": 271597, "author": "user35412", "author_id": 35412, "author_profile": "https://Stackoverflow.com/users/35412", "pm_score": 2, "selected": false, "text": "<p>Starting from C# 2.0, you can use the nullable generic type Nullable, and in C# there is a shorthand notation the type followed by ?</p>\n\n<p>e.g.</p>\n\n<pre><code>private void Example(int? arg1, int? arg2)\n{\n if(arg1 == null)\n {\n //do something\n }\n if(arg2 == null)\n {\n //do something else\n }\n}\n</code></pre>\n" }, { "answer_id": 271600, "author": "Sander", "author_id": 2928, "author_profile": "https://Stackoverflow.com/users/2928", "pm_score": 7, "selected": true, "text": "<p>Yes. There are two kinds of types in .NET: reference types and value types.</p>\n\n<p>References types (generally classes) are always referred to by references, so they support null without any extra work. This means that if a variable's type is a reference type, the variable is automatically a reference.</p>\n\n<p>Value types (e.g. int) by default do not have a concept of null. However, there is a wrapper for them called Nullable. This enables you to encapsulate the non-nullable value type and include null information.</p>\n\n<p>The usage is slightly different, though.</p>\n\n<pre><code>// Both of these types mean the same thing, the ? is just C# shorthand.\nprivate void Example(int? arg1, Nullable&lt;int&gt; arg2)\n{\n if (arg1.HasValue)\n DoSomething();\n\n arg1 = null; // Valid.\n arg1 = 123; // Also valid.\n\n DoSomethingWithInt(arg1); // NOT valid!\n DoSomethingWithInt(arg1.Value); // Valid.\n}\n</code></pre>\n" }, { "answer_id": 271667, "author": "mackenir", "author_id": 25457, "author_profile": "https://Stackoverflow.com/users/25457", "pm_score": 3, "selected": false, "text": "<p>I think the nearest C# equivalent to <code><strong>int*</strong></code> would be <code><strong>ref int?</strong></code>. Because <code><strong>ref int?</strong></code> allows the called method to pass a value back to the calling method.</p>\n\n<p><code><strong>int*</strong></code></p>\n\n<ul>\n<li>Can be null.</li>\n<li>Can be non-null and point to an integer value.</li>\n<li><strong><em>If not null, value can be changed</em></strong>, and the change propagates to the caller.</li>\n<li><strong><em>Setting to null is not passed back to the caller</em></strong>.</li>\n</ul>\n\n<p><code><strong>ref int?</strong></code></p>\n\n<ul>\n<li>Can be null.</li>\n<li>Can have an integer value.</li>\n<li><strong><em>Value can be always be changed</em></strong>, and the change propagates to the caller.</li>\n<li><strong><em>Value can be set to null, and this change will also propagate to the caller</em></strong>.</li>\n</ul>\n" }, { "answer_id": 13724965, "author": "ruffin", "author_id": 1028230, "author_profile": "https://Stackoverflow.com/users/1028230", "pm_score": 2, "selected": false, "text": "<p>The OP's question is answered well already, but the title is just broad enough that I think it benefits from the following primer:</p>\n\n<pre><code>using System;\nusing System.Collections.Generic;\nusing System.Linq;\nusing System.Text;\n\nnamespace consolePlay\n{\n class Program\n {\n static void Main(string[] args)\n {\n Program.test(new DateTime());\n Program.test(null);\n //Program.test(); // &lt;&lt;&lt; Error. \n // \"No overload for method 'test' takes 0 arguments\" \n // So don't mistake nullable to be optional.\n\n Console.WriteLine(\"Done. Return to quit\");\n Console.Read();\n }\n\n static public void test(DateTime? dteIn)\n {\n Console.WriteLine(\"#\" + dteIn.ToString() + \"#\");\n }\n }\n}\n</code></pre>\n\n<p>output:</p>\n\n<pre><code>#1/1/0001 12:00:00 AM#\n##\nDone. Return to quit\n</code></pre>\n" }, { "answer_id": 31465371, "author": "juancalbarran", "author_id": 3119676, "author_profile": "https://Stackoverflow.com/users/3119676", "pm_score": 2, "selected": false, "text": "<p>You can use 2 ways: int? or Nullable, both have the same behavior. You could to make a mix without problems but is better choice one to make code cleanest.</p>\n\n<p>Option 1 (With ?):</p>\n\n<pre><code>private void Example(int? arg1, int? arg2)\n {\n if (arg1.HasValue)\n {\n //do something\n }\n if (arg1.HasValue)\n {\n //do something else\n }\n }\n</code></pre>\n\n<p>Option 2 (With Nullable):</p>\n\n<pre><code>private void Example(Nullable&lt;int&gt; arg1, Nullable&lt;int&gt; arg2)\n {\n if (arg1.HasValue)\n {\n //do something\n }\n if (arg1.HasValue)\n {\n //do something else\n }\n }\n</code></pre>\n\n<p>From C#4.0 comes a new way to do the same with more flexibility, in this case the framework offers <a href=\"https://msdn.microsoft.com/en-us/library/dd264739.aspx\" rel=\"nofollow\">optional parameters with default values</a>, of this way you can set a default value if the method is called without all parameters.</p>\n\n<p>Option 3 (With default values)</p>\n\n<pre><code>private void Example(int arg1 = 0, int arg2 = 1)\n {\n //do something else\n }\n</code></pre>\n" } ]
2008/11/07
[ "https://Stackoverflow.com/questions/271588", "https://Stackoverflow.com", "https://Stackoverflow.com/users/22996/" ]
Is there a way to pass null arguments to C# methods (something like null arguments in c++)? For example: Is it possible to translate the following c++ function to C# method: ``` private void Example(int* arg1, int* arg2) { if(arg1 == null) { //do something } if(arg2 == null) { //do something else } } ```
Yes. There are two kinds of types in .NET: reference types and value types. References types (generally classes) are always referred to by references, so they support null without any extra work. This means that if a variable's type is a reference type, the variable is automatically a reference. Value types (e.g. int) by default do not have a concept of null. However, there is a wrapper for them called Nullable. This enables you to encapsulate the non-nullable value type and include null information. The usage is slightly different, though. ``` // Both of these types mean the same thing, the ? is just C# shorthand. private void Example(int? arg1, Nullable<int> arg2) { if (arg1.HasValue) DoSomething(); arg1 = null; // Valid. arg1 = 123; // Also valid. DoSomethingWithInt(arg1); // NOT valid! DoSomethingWithInt(arg1.Value); // Valid. } ```
271,595
<p>I need to get all the dates present in the date range using SQL Server 2005</p>
[ { "answer_id": 271607, "author": "Ed Guiness", "author_id": 4200, "author_profile": "https://Stackoverflow.com/users/4200", "pm_score": 3, "selected": false, "text": "<p>If you have the dates in a table and simply want to select those between two dates you can use</p>\n\n<pre><code>select * from yourTable where yourDate between date1 and date2\n</code></pre>\n\n<p>If you want to produce the dates from nothing you could do it with a loop or you could populate a temporary table with dates and then select from that.</p>\n" }, { "answer_id": 271775, "author": "ConcernedOfTunbridgeWells", "author_id": 15401, "author_profile": "https://Stackoverflow.com/users/15401", "pm_score": -1, "selected": false, "text": "<p>To generate a range of dates you could write a table-valued function. This is a function that creates a date dimension for a data warehouse - you could probably adapt it fairly readily by trimming out the specials.</p>\n\n<p>Edit: Here it is without the date dimension hierarchy.</p>\n\n<pre><code>if object_id ('ods.uf_DateHierarchy') is not null\n drop function ods.uf_DateHierarchy\ngo\n\ncreate function ods.uf_DateHierarchy (\n @DateFrom datetime\n ,@DateTo datetime\n) returns @DateHierarchy table (\n DateKey datetime\n) as begin\n declare @today datetime \n set @today = @Datefrom\n\n while @today &lt;= @DateTo begin\n insert @DateHierarchy (DateKey) values (@today)\n set @today = dateadd (dd, 1, @today)\n end\n\n return\nend\n\ngo\n</code></pre>\n" }, { "answer_id": 271878, "author": "Incidently", "author_id": 34187, "author_profile": "https://Stackoverflow.com/users/34187", "pm_score": 6, "selected": false, "text": "<p>Here you go:</p>\n\n<pre><code>DECLARE @DateFrom smalldatetime, @DateTo smalldatetime;\nSET @DateFrom='20000101';\nSET @DateTo='20081231';\n-------------------------------\nWITH T(date)\nAS\n( \nSELECT @DateFrom \nUNION ALL\nSELECT DateAdd(day,1,T.date) FROM T WHERE T.date &lt; @DateTo\n)\nSELECT date FROM T OPTION (MAXRECURSION 32767);\n</code></pre>\n" }, { "answer_id": 271910, "author": "Soraz", "author_id": 24610, "author_profile": "https://Stackoverflow.com/users/24610", "pm_score": -1, "selected": false, "text": "<p>If what you want is to get all dates present in your database between two dates (i.e. what dates have customers placed orders in Q3 of 2008) you would write something like this:</p>\n\n<pre><code>select distinct(orderPlacedDate) \nfrom orders \nwhere orderPlacedDate between '2008-07-01' and 2008-09-30' \norder by orderPlacedDate\n</code></pre>\n" }, { "answer_id": 272568, "author": "user34850", "author_id": 34850, "author_profile": "https://Stackoverflow.com/users/34850", "pm_score": 1, "selected": false, "text": "<p>Here's Oracle version of date generation:</p>\n\n<pre><code>SELECT TO_DATE ('01-OCT-2008') + ROWNUM - 1 g_date\n FROM all_objects\n WHERE ROWNUM &lt;= 15\n</code></pre>\n\n<p>instead of all_objects it can be any table with enough rows to cover the required range.</p>\n" }, { "answer_id": 1271024, "author": "Chris Moutray", "author_id": 81053, "author_profile": "https://Stackoverflow.com/users/81053", "pm_score": 0, "selected": false, "text": "<p>Slightly more complicated but perhaps more flexible would be to make use of a table containing a sequential set of numbers. This allows for more than one date range with different intervals.</p>\n\n<pre><code>/* holds a sequential set of number ie 0 to max */\n/* where max is the total number of rows expected */\ndeclare @Numbers table ( Number int )\n\ndeclare @max int \ndeclare @cnt int\n\nset @cnt = 0\n/* this value could be limited if you knew the total rows expected */\nset @max = 999 \n\n/* we are building the NUMBERS table on the fly */\n/* but this could be a proper table in the database */\n/* created at the point of first deployment */\nwhile (@cnt &lt;= @max)\nbegin\n insert into @Numbers select @cnt\n set @cnt = @cnt + 1\nend\n\n/* EXAMPLE of creating dates with different intervals */\n\ndeclare @DateRanges table ( \n StartDateTime datetime, EndDateTime datetime, Interval int )\n\n/* example set of date ranges */\ninsert into @DateRanges\nselect '01 Jan 2009', '10 Jan 2009', 1 /* 1 day interval */\nunion select '01 Feb 2009', '10 Feb 2009', 2 /* 2 day interval */\n\n/* heres the important bit generate the dates */\nselect\n StartDateTime\nfrom\n(\n select\n d.StartDateTime as RangeStart,\n d.EndDateTime as RangeEnd,\n dateadd(DAY, d.Interval * n.Number, d.StartDateTime) as StartDateTime\n from \n @DateRanges d, @Numbers n\n) as dates\nwhere\n StartDateTime between RangeStart and RangeEnd\norder by StartDateTime\n</code></pre>\n\n<p>I actully use a variation of this to split dates into time slots (with various intervals but usually 5 mins long). My @numbers table contains a max of 288 since thats the total number of 5 min slots you can have in a 24 hour period.</p>\n\n<pre><code>/* EXAMPLE of creating times with different intervals */\n\ndelete from @DateRanges \n\n/* example set of date ranges */\ninsert into @DateRanges\nselect '01 Jan 2009 09:00:00', '01 Jan 2009 12:00:00', 30 /* 30 minutes interval */\nunion select '02 Feb 2009 09:00:00', '02 Feb 2009 10:00:00', 5 /* 5 minutes interval */\n\n/* heres the import bit generate the times */\nselect\n StartDateTime,\n EndDateTime\nfrom\n(\n select\n d.StartDateTime as RangeStart,\n d.EndDateTime as RangeEnd,\n dateadd(MINUTE, d.Interval * n.Number, d.StartDateTime) as StartDateTime,\n dateadd(MINUTE, d.Interval * (n.Number + 1) , StartDateTime) as EndDateTime\n from \n @DateRanges d, @Numbers n\n) as dates\nwhere\n StartDateTime &gt;= RangeStart and EndDateTime &lt;= RangeEnd\norder by StartDateTime\n</code></pre>\n" }, { "answer_id": 40958788, "author": "Surinder Singh", "author_id": 6892711, "author_profile": "https://Stackoverflow.com/users/6892711", "pm_score": 3, "selected": false, "text": "<pre><code>DECLARE @Date1 DATE='2016-12-21', @Date2 DATE='2016-12-25'\nSELECT DATEADD(DAY,number,@Date1) [Date] FROM master..spt_values WHERE type = 'P' AND DATEADD(DAY,number,@Date1) &lt;= @Date2\n</code></pre>\n" } ]
2008/11/07
[ "https://Stackoverflow.com/questions/271595", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
I need to get all the dates present in the date range using SQL Server 2005
Here you go: ``` DECLARE @DateFrom smalldatetime, @DateTo smalldatetime; SET @DateFrom='20000101'; SET @DateTo='20081231'; ------------------------------- WITH T(date) AS ( SELECT @DateFrom UNION ALL SELECT DateAdd(day,1,T.date) FROM T WHERE T.date < @DateTo ) SELECT date FROM T OPTION (MAXRECURSION 32767); ```
271,598
<p>How do I save a Tlistviews layout in Delphi 2007?</p> <p>I have been asked to write some code to allow users to re-order columns in a TListview (well all TListviews in our application), I have the code working (by manipulating the columns index and setting width to zero to hide columns not needed) but now I need a way to save the state of the view when to form exits.</p> <p>What is the best way to do this? I thought about serialization, but I dont need the data or sort order so that seamed a bit overkill to me.</p> <p>Some things to ponder It needs to be on a per user basis It needs to be flexible, in-case we add a new column in the middle of the listview There is no garantee that the Column headding will be unique The listview name may not be unique across the application</p> <p>Any ideas?</p>
[ { "answer_id": 271619, "author": "Toon Krijthe", "author_id": 18061, "author_profile": "https://Stackoverflow.com/users/18061", "pm_score": 2, "selected": false, "text": "<p>If you only want to save and load a certain part of the data you can store it n an ini or xml file. \nGeneral data can be written to the file. Columns is another problem. You need to find an unique identification for each column. The ini could be something like:</p>\n\n<pre><code>[Settings]\n\n[Col_1]\nposition=1\nwidth=500\ntitle=hello world\nalign=left\nsort=ascending\n\n.. etc for more fields and more columns.\n</code></pre>\n\n<p>If you uses a listview helper class, you only need to write the code once:</p>\n\n<pre><code>TListviewHelper = class helper for TListView;\npublic\n procedure SaveToFile(const AFilename: string);\n procedure LoadFromFile(const AFileName: string);\nend;\n\nprocedure TListviewHelper.SaveToFile(const AFilename: string);\nvar\n ini : TIniFile;\nbegin\n ini := TIniFile.Create(AFileName);\n try\n // Save to ini file\n finally\n ini.Free;\n end;\nend;\n\nprocedure TListviewHelper.LoadFromFile(const AFileName: string);\nvar\n ini : TIniFile;\nbegin\n ini := TIniFile.Create(AFileName);\n try\n // Load from ini file\n finally\n ini.Free;\n end;\nend;\n</code></pre>\n\n<p>If TListviewHelper is within scope, you have access to the extra methods.</p>\n" }, { "answer_id": 278091, "author": "Osama Al-Maadeed", "author_id": 25544, "author_profile": "https://Stackoverflow.com/users/25544", "pm_score": 0, "selected": false, "text": "<p>I suggest you inherit from Tlistview (or is there a TCustomListView) to create your own component, class helpers are nice but unofficial.</p>\n" }, { "answer_id": 44900707, "author": "C. MARIN", "author_id": 8237709, "author_profile": "https://Stackoverflow.com/users/8237709", "pm_score": 0, "selected": false, "text": "<p>Perhaps the easiest way to store the order of the columns would be to define a ID for each as a meaningfull string, and store the list in the right order in the registry.\nFor instance, let's suppose your columns were ordered like:</p>\n\n<pre><code>Name | First name | Age | Job title\n</code></pre>\n\n<p>Then the stored string in the registry could be:</p>\n\n<pre><code>\"Name,FName,Age,JTitle\"\n</code></pre>\n\n<p>To be stored in the appropriate registry entry, under the appropriate key (typically <code>HCKU\\SOFTWARE\\MyApplication</code>, under the key <code>ColumnOrder</code> for instance)</p>\n" } ]
2008/11/07
[ "https://Stackoverflow.com/questions/271598", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2098/" ]
How do I save a Tlistviews layout in Delphi 2007? I have been asked to write some code to allow users to re-order columns in a TListview (well all TListviews in our application), I have the code working (by manipulating the columns index and setting width to zero to hide columns not needed) but now I need a way to save the state of the view when to form exits. What is the best way to do this? I thought about serialization, but I dont need the data or sort order so that seamed a bit overkill to me. Some things to ponder It needs to be on a per user basis It needs to be flexible, in-case we add a new column in the middle of the listview There is no garantee that the Column headding will be unique The listview name may not be unique across the application Any ideas?
If you only want to save and load a certain part of the data you can store it n an ini or xml file. General data can be written to the file. Columns is another problem. You need to find an unique identification for each column. The ini could be something like: ``` [Settings] [Col_1] position=1 width=500 title=hello world align=left sort=ascending .. etc for more fields and more columns. ``` If you uses a listview helper class, you only need to write the code once: ``` TListviewHelper = class helper for TListView; public procedure SaveToFile(const AFilename: string); procedure LoadFromFile(const AFileName: string); end; procedure TListviewHelper.SaveToFile(const AFilename: string); var ini : TIniFile; begin ini := TIniFile.Create(AFileName); try // Save to ini file finally ini.Free; end; end; procedure TListviewHelper.LoadFromFile(const AFileName: string); var ini : TIniFile; begin ini := TIniFile.Create(AFileName); try // Load from ini file finally ini.Free; end; end; ``` If TListviewHelper is within scope, you have access to the extra methods.
271,609
<p>We have a couple of applications running on Java 5 and would like now to bring in an application based on Java 6. Can both java versions live together under Windows? </p> <p>Is there any control panel to set the appropriate Java version for different applications, or any other way to set up, what version of Java will be used to run that particular application?</p>
[ { "answer_id": 271623, "author": "reallyinsane", "author_id": 35407, "author_profile": "https://Stackoverflow.com/users/35407", "pm_score": 7, "selected": true, "text": "<p>Of course you can use multiple versions of Java under Windows. And different applications can use different Java versions. How is your application started? Usually you will have a batch file where there is something like </p>\n\n<pre><code>java ...\n</code></pre>\n\n<p>This will search the Java executable using the PATH variable. So if Java 5 is first on the PATH, you will have problems running a Java 6 application. You should then modify the batch file to use a certain Java version e.g. by defining a environment variable <code>JAVA6HOME</code> with the value <code>C:\\java\\java6</code> (if Java 6 is installed in this directory) and change the batch file calling</p>\n\n<pre><code>%JAVA6HOME%\\bin\\java ...\n</code></pre>\n" }, { "answer_id": 271624, "author": "Moshe", "author_id": 9941, "author_profile": "https://Stackoverflow.com/users/9941", "pm_score": 4, "selected": false, "text": "<p>It is absolutely possible to install side-by-side several JRE/JDK versions. Moreover, you don't have to do anything special for that to happen, as Sun is creating a different folder for each (under Program Files).</p>\n\n<p>There is no control panel to check which JRE works for each application. Basically, the JRE that will work would be the first in your PATH environment variable. You can change that, or the JAVA_HOME variable, or create specific cmd/bat files to launch the applications you desire, each with a different JRE in path.</p>\n" }, { "answer_id": 271630, "author": "Ruben", "author_id": 26919, "author_profile": "https://Stackoverflow.com/users/26919", "pm_score": 2, "selected": false, "text": "<p>It should be possible changing setting the JAVA_HOME environment variable differently for specific applications. </p>\n\n<p>When starting from the command line or from a batch script you can use <code>set JAVA_HOME=C:\\...\\j2dskXXX</code> to change the JAVA_HOME environment.</p>\n\n<p>It is possible that you also need to change the <code>PATH</code> environment variable to use the correct java binary. To do this you can use <code>set PATH=%JAVA_HOME%\\bin;%PATH%</code>.</p>\n" }, { "answer_id": 271895, "author": "jcoder", "author_id": 417292, "author_profile": "https://Stackoverflow.com/users/417292", "pm_score": 1, "selected": false, "text": "<p>Invoking Java with \"java -version:1.5\", etc. should run with the correct version of Java. (Obviously replace 1.5 with the version you want.)</p>\n\n<p>If Java is properly installed on Windows there are paths to the vm for each version stored in the registry which it uses so you don't need to mess about with environment versions on Windows.</p>\n" }, { "answer_id": 1141550, "author": "Peter Lawrey", "author_id": 57695, "author_profile": "https://Stackoverflow.com/users/57695", "pm_score": 1, "selected": false, "text": "<p>If you use <a href=\"http://en.wikipedia.org/wiki/Java_Web_Start\" rel=\"nofollow noreferrer\">Java Web Start</a> (you can start applications from any URL, even the local file system) it will take care of finding the right version for your application.</p>\n" }, { "answer_id": 12281016, "author": "Drikus", "author_id": 1648979, "author_profile": "https://Stackoverflow.com/users/1648979", "pm_score": 4, "selected": false, "text": "<p>I was appalled at the clumsiness of the CLASSPATH, JAVA_HOME, and PATH ideas, in Windows, to keep track of Java files. I got here, because of multiple JREs, and how to content with it. Without regurgitating information, from a guy much more clever than me, I would rather point to to his article on this issue, which for me, resolves it perfectly.</p>\n\n<p>Article by: Ted Neward: <a href=\"http://www.tedneward.com/files/Papers/MultipleJavaHomes/MultipleJavaHomes.pdf\">Multiple Java Homes: Giving Java Apps Their Own JRE</a></p>\n\n<blockquote>\n <p>With the exponential growth of Java as a server-side development language has come an equivablent\n exponential growth in Java development tools, environments, frameworks, and extensions.\n Unfortunately, not all of these tools play nicely together under the same Java VM installation. Some\n require a Servlet 2.1-compliant environment, some require 2.2. Some only run under JDK 1.2 or above,\n some under JDK 1.1 (and no higher). Some require the \"com.sun.swing\" packages from pre-Swing 1.0\n days, others require the \"javax.swing\" package names.</p>\n \n <p>Worse yet, this problem can be found even within the corporate enterprise, as systems developed using\n Java from just six months ago may suddenly \"not work\" due to the installation of some Java Extension\n required by a new (seemingly unrelated) application release. This can complicate deployment of Java\n applications across the corporation, and lead customers to wonder precisely why, five years after the\n start of the infamous \"Installing-this-app-breaks-my-system\" woes began with Microsoft's DLL schemes,\n we still haven't progressed much beyond that. (In fact, the new .NET initiative actually seeks to solve the\n infamous \"DLL-Hell\" problem just described.)</p>\n \n <p>This paper describes how to configure a Java installation such that a given application receives its own,\n private, JRE, allowing multiple Java environments to coexist without driving customers (or system\n administrators) insane...</p>\n</blockquote>\n" }, { "answer_id": 30927415, "author": "jan.supol", "author_id": 1026104, "author_profile": "https://Stackoverflow.com/users/1026104", "pm_score": 2, "selected": false, "text": "<p>Or use links. While it is rather unpleasant to update the PATH in a running environment, it's easy to recreate a link to a new version of JRE/JDK. So: </p>\n\n<ul>\n<li>install different versions of JDK you want to use</li>\n<li>create a link to that folder either by <a href=\"https://technet.microsoft.com/en-us/sysinternals/bb896768.aspx\" rel=\"nofollow\">junction</a> or by built-in mklink command</li>\n<li>set the PATH to the link</li>\n<li>If other version of java is to be used, delete the link, create a new one, PATH/JAVA_HOME/hardcoded scripts remain untouched</li>\n</ul>\n" }, { "answer_id": 49688921, "author": "Felipe Ferreira", "author_id": 6489237, "author_profile": "https://Stackoverflow.com/users/6489237", "pm_score": 2, "selected": false, "text": "<p>I use a simple script when starting JMeter with my own java version</p>\n<pre><code>setlocal\nset JAVA_HOME=&quot;c:\\java8&quot;\nset PATH=%JAVA_HOME%\\bin;%PATH%;\njava -version\n</code></pre>\n<p>To have a java &quot;portable&quot;\nyou can use this method here:</p>\n<p><a href=\"https://www.whitebyte.info/programming/java/how-to-install-a-portable-jdk-in-windows-without-admin-rights\" rel=\"nofollow noreferrer\">https://www.whitebyte.info/programming/java/how-to-install-a-portable-jdk-in-windows-without-admin-rights</a></p>\n" }, { "answer_id": 51889553, "author": "eliana_zulato", "author_id": 10106043, "author_profile": "https://Stackoverflow.com/users/10106043", "pm_score": 0, "selected": false, "text": "<p>Using Java Web Start, you can install multiple JRE, then call what you need.\nOn win, you can make a .bat file:</p>\n\n<p>1- online version:\n&lt;<em>your_JRE_version</em>\\bin\\javaws.exe> -localfile -J-Djnlp.application.href=&lt;<em>the url of .jnlp file</em>.jnlp> -localfile -J \"&lt;<em>path_temp_jnlp_file_</em>.jnlp>\"</p>\n\n<p>2- launch from cache:\n&lt;<em>your_JRE_version</em>\\bin\\javaws.exe> -localfile -J \"&lt;<em>path_of_your_local_jnlp_file</em>.jnlp>\"</p>\n" }, { "answer_id": 55476231, "author": "Naresh Joshi", "author_id": 2078093, "author_profile": "https://Stackoverflow.com/users/2078093", "pm_score": 3, "selected": false, "text": "<p>We can install multiple versions of Java Development kits on the same machine using SDKMan.</p>\n\n<p>Some points about SDKMan are as following: </p>\n\n<ol>\n<li>SDKMan is free to use and it is developed by the open source community.</li>\n<li>SDKMan is written in <a href=\"https://www.gnu.org/software/bash/\" rel=\"noreferrer\">bash</a> and it only requires <a href=\"http://curl.haxx.se/\" rel=\"noreferrer\">curl</a> and <a href=\"http://www.info-zip.org/\" rel=\"noreferrer\">zip/unzip</a> programs to be present on your system.</li>\n<li>SDKMan can install around 29 Software Development Kits for the JVM such as Java, Groovy, Scala, Kotlin and Ceylon. Ant, Gradle, Grails, Maven, SBT, Spark, Spring Boot, Vert.x.</li>\n<li>We do not need to worry about setting the <code>_HOME</code> and <code>PATH</code> environment variables because SDKMan handles it automatically.</li>\n</ol>\n\n<p>SDKMan can run on any UNIX based platforms such as Mac OSX, Linux, Cygwin, Solaris and FreeBSD and we can install it using following commands:</p>\n\n<pre><code>$ curl -s \"https://get.sdkman.io\" | bash \n$ source \"$HOME/.sdkman/bin/sdkman-init.sh\" \n</code></pre>\n\n<blockquote>\n <p>Because SDKMan is written in <a href=\"https://www.gnu.org/software/bash/\" rel=\"noreferrer\">bash</a> and only requires <a href=\"http://curl.haxx.se/\" rel=\"noreferrer\">curl</a> and <a href=\"http://www.info-zip.org/\" rel=\"noreferrer\">zip/unzip</a> to be present on your system. You can install SDKMan on windows as well either by first installing <a href=\"https://www.cygwin.com/install.html\" rel=\"noreferrer\">Cygwin</a> or <a href=\"https://git-scm.com/download/win\" rel=\"noreferrer\">Git Bash for Windows</a> environment and then running above commands.</p>\n</blockquote>\n\n<p>Command <code>sdk list java</code> will give us a list of java versions which we can install using SDKMan.</p>\n\n<p><strong>Installing Java 8</strong></p>\n\n<pre><code>$ sdk install java 8.0.201-oracle\n</code></pre>\n\n<p><strong>Installing Java 9</strong></p>\n\n<pre><code>$ sdk install java 9.0.4-open \n</code></pre>\n\n<p><strong>Installing Java 11</strong></p>\n\n<pre><code>$ sdk install java 11.0.2-open\n</code></pre>\n\n<p><strong>Uninstalling a Java version</strong></p>\n\n<p>In case you want to uninstall any JDK version e.g., 11.0.2-open you can do that as follows:</p>\n\n<pre><code>$ sdk uninstall java 11.0.2-open\n</code></pre>\n\n<p><strong>Switching current Java version</strong></p>\n\n<p>If you want to activate one version of JDK for all terminals and applications, you can use the command </p>\n\n<pre><code>sdk default java &lt;your-java_version&gt;\n</code></pre>\n\n<p>Above commands will also update the PATH and JAVA_HOME variables automatically. You can read more on my article <a href=\"https://www.programmingmitra.com/2019/03/how-to-install-multiple-versions-of-java-on-the-same-machine.html\" rel=\"noreferrer\">How to Install Multiple Versions of Java on the Same Machine</a>.</p>\n" } ]
2008/11/07
[ "https://Stackoverflow.com/questions/271609", "https://Stackoverflow.com", "https://Stackoverflow.com/users/35061/" ]
We have a couple of applications running on Java 5 and would like now to bring in an application based on Java 6. Can both java versions live together under Windows? Is there any control panel to set the appropriate Java version for different applications, or any other way to set up, what version of Java will be used to run that particular application?
Of course you can use multiple versions of Java under Windows. And different applications can use different Java versions. How is your application started? Usually you will have a batch file where there is something like ``` java ... ``` This will search the Java executable using the PATH variable. So if Java 5 is first on the PATH, you will have problems running a Java 6 application. You should then modify the batch file to use a certain Java version e.g. by defining a environment variable `JAVA6HOME` with the value `C:\java\java6` (if Java 6 is installed in this directory) and change the batch file calling ``` %JAVA6HOME%\bin\java ... ```
271,612
<p>I have the following file/line:</p> <pre><code>pc=1 ct=1 av=112 cv=1100 cp=1700 rec=2 p=10001 g=0 a=0 sz=5 cr=200 pc=1 ct=1 av=113 cv=1110 cp=1800 rec=2 p=10001 g=0 a=10 sz=5 cr=200 </code></pre> <p>and so on. I wish to parse this and take the key value pairs and put them in a structure:</p> <pre><code>struct pky { pky() : a_id(0), sz_id(0), cr_id(0), cp_id(0), cv_id(0), ct_id(0), fr(0), g('U'), a(0), pc(0), p_id(0) { } }; </code></pre> <p>wherein either all the structure fields are used or some might be omitted.</p> <p>How do I create a C++ class, which will do the same? I am new to C++ and not aware of any functions or library which would do this work.</p> <p>Each line is to be processed, and the structure will be populated with one line each time and used, before it is flushed. The structure is later used as a parameter to a function.</p>
[ { "answer_id": 271649, "author": "Nik Reiman", "author_id": 14302, "author_profile": "https://Stackoverflow.com/users/14302", "pm_score": 1, "selected": false, "text": "<p>Unfortunately, your source data file is human-oriented, which means that you're going to have to do a bunch of string parsing in order to get it into the structure. Otherwise, if the data had been written directly as a binary file, you could just use fread() to pop it directly into the struct.</p>\n\n<p>If you want to use an \"elegant\" (ie, ugly minimalistic approach), you could make a loop of sorts to parse each line, basically using strchr() to first find the '=' character, then the next space, then using atoi() to convert each number into a real int, and then using some pointer hackery to push them all into the structure. The obvious disadvantage there is that if the structure changes, or is even reorganized somehow, then the whole algorithm here would silently break.</p>\n\n<p>So, for something that would be more maintainable and readable (but result in more code), you could just push each value into a vector, and then go through the vector and copy each value into the appropriate strucutre field.</p>\n" }, { "answer_id": 271654, "author": "Johannes Schaub - litb", "author_id": 34509, "author_profile": "https://Stackoverflow.com/users/34509", "pm_score": 4, "selected": true, "text": "<p>You can do something like this:</p>\n\n<pre><code>std::string line;\nstd::map&lt;std::string, std::string&gt; props;\nstd::ifstream file(\"foo.txt\");\nwhile(std::getline(file, line)) {\n std::string token;\n std::istringstream tokens(line);\n while(tokens &gt;&gt; token) {\n std::size_t pos = token.find('=');\n if(pos != std::string::npos) {\n props[token.substr(0, pos)] = token.substr(pos + 1);\n }\n }\n\n /* work with those keys/values by doing properties[\"name\"] */\n Line l(props[\"pc\"], props[\"ct\"], ...);\n\n /* clear the map for the next line */\n props.clear();\n}\n</code></pre>\n\n<p>i hope it's helpful. Line can be like this:</p>\n\n<pre><code>struct Line { \n std::string pc, ct; \n Line(std::string const&amp; pc, std::string const&amp; ct):pc(pc), ct(ct) {\n\n }\n};\n</code></pre>\n\n<p>now that works only if the delimiter is a space. you can make it work with other delimiters too. change </p>\n\n<pre><code>while(tokens &gt;&gt; token) {\n</code></pre>\n\n<p>into for example the following, if you want to have a semicolon:</p>\n\n<pre><code>while(std::getline(tokens, token, ';')) {\n</code></pre>\n\n<p>actually, it looks like you have only integers as values, and whitespace as delimiters. you might want to change</p>\n\n<pre><code> std::string token;\n std::istringstream tokens(line);\n while(tokens &gt;&gt; token) {\n std::size_t pos = token.find('=');\n if(pos != std::string::npos) {\n props[token.substr(0, pos)] = token.substr(pos + 1);\n }\n }\n</code></pre>\n\n<p>into this then:</p>\n\n<pre><code> int value;\n std::string key;\n std::istringstream tokens(line);\n while(tokens &gt;&gt; std::ws &amp;&amp; std::getline(tokens, key, '=') &amp;&amp; \n tokens &gt;&gt; std::ws &gt;&gt; value) {\n props[key] = value;\n }\n</code></pre>\n\n<p><code>std::ws</code> just eats whitespace. you should change the type of props to </p>\n\n<pre><code>std::map&lt;std::string, int&gt; props;\n</code></pre>\n\n<p>then too, and make Line accept int instead of std::string's. i hope this is not too much information at once. </p>\n" }, { "answer_id": 271670, "author": "korona", "author_id": 25731, "author_profile": "https://Stackoverflow.com/users/25731", "pm_score": 2, "selected": false, "text": "<p>This seemed to do the trick. Of course you'd extract the code I've written in main and stick it in a class or something, but you get the idea.</p>\n\n<pre><code>#include &lt;sstream&gt;\n#include &lt;string&gt;\n#include &lt;vector&gt;\n#include &lt;map&gt;\n\nusing namespace std;\n\nvector&lt;string&gt; Tokenize(const string &amp;str, const string &amp;delim)\n{\n vector&lt;string&gt; tokens;\n\n size_t p0 = 0, p1 = string::npos;\n while(p0 != string::npos)\n {\n p1 = str.find_first_of(delim, p0);\n if(p1 != p0)\n {\n string token = str.substr(p0, p1 - p0);\n tokens.push_back(token);\n }\n p0 = str.find_first_not_of(delim, p1);\n }\n\n return tokens;\n}\n\nint main()\n{\n string data = \"pc=1 ct=1 av=112 cv=1100 cp=1700 rec=2 p=10001 g=0 a=0 sz=5 cr=200 pc=1 ct=1 av=113 cv=1110 cp=1800 rec=2 p=10001 g=0 a=10 sz=5 cr=200\";\n vector&lt;string&gt; entries = Tokenize(data, \" \");\n map&lt;string, int&gt; items;\n\n for (size_t i = 0; i &lt; entries.size(); ++i)\n {\n string item = entries[i];\n\n size_t pos = item.find_first_of('=');\n if(pos == string::npos)\n continue;\n\n string key = item.substr(0, pos);\n int value;\n stringstream stream(item.substr(pos + 1));\n stream &gt;&gt; value;\n items.insert (pair&lt;string, int&gt;(key, value));\n }\n\n}\n</code></pre>\n" }, { "answer_id": 272265, "author": "Martin York", "author_id": 14065, "author_profile": "https://Stackoverflow.com/users/14065", "pm_score": 2, "selected": false, "text": "<p>This is the perfect place to define the stream operators for your structure:</p>\n\n<pre><code>#include &lt;string&gt;\n#include &lt;fstream&gt;\n#include &lt;sstream&gt;\n#include &lt;istream&gt;\n#include &lt;vector&gt;\n#include &lt;algorithm&gt;\n#include &lt;iterator&gt;\n\nstd::istream&amp; operator&gt;&gt; (std::istream&amp; str,pky&amp; value)\n{\n std::string line;\n std::getline(str,line);\n\n std::stringstream dataStr(line);\n\n static const std::streamsize max = std::numeric_limits&lt;std::streamsize&gt;::max();\n\n // Code assumes the ordering is always as follows\n // pc=1 ct=1 av=112 cv=1100 cp=1700 rec=2 p=10001 g=0 a=0 sz=5 cr=200\n dataStr.ignore(max,'=') &gt;&gt; value.pc;\n dataStr.ignore(max,'=') &gt;&gt; value.ct_id;\n dataStr.ignore(max,'=') &gt;&gt; value.a; // Guessing av=\n dataStr.ignore(max,'=') &gt;&gt; value.cv_id;\n dataStr.ignore(max,'=') &gt;&gt; value.cp_id;\n dataStr.ignore(max,'=') &gt;&gt; value.fr; // Guessing rec=\n dataStr.ignore(max,'=') &gt;&gt; value.p_id;\n dataStr.ignore(max,'=') &gt;&gt; value.g;\n dataStr.ignore(max,'=') &gt;&gt; value.a_id;\n dataStr.ignore(max,'=') &gt;&gt; value.sz_id;\n dataStr.ignore(max,'=') &gt;&gt; value.cr_id;\n\n return str;\n}\n\nint main()\n{\n std::ifstream file(\"plop\");\n\n std::vector&lt;pky&gt; v;\n pky data;\n\n while(file &gt;&gt; data)\n {\n // Do Somthing with data\n v.push_back(data);\n }\n\n // Even use the istream_iterators\n std::ifstream file2(\"plop2\");\n std::vector&lt;pky&gt; v2;\n\n std::copy(std::istream_iterator&lt;pky&gt;(file2),\n std::istream_iterator&lt;pky&gt;(),\n std::back_inserter(v2)\n );\n}\n</code></pre>\n" }, { "answer_id": 1727555, "author": "3yE", "author_id": 207427, "author_profile": "https://Stackoverflow.com/users/207427", "pm_score": 1, "selected": false, "text": "<p>What you get taught here, are <strong>monstrosities</strong>.</p>\n\n<p><a href=\"http://en.wikipedia.org/wiki/Scanf\" rel=\"nofollow noreferrer\">http://en.wikipedia.org/wiki/Scanf</a></p>\n\n<p>Do not use this function to extract strings from untrusted data, but as long as you either trust data, or only get numbers, why not.</p>\n\n<p>If you are familiar with Regular Expressions from using another language, use <code>std::tr1::regex</code> or <code>boost::regex</code> - they are the same. If not familiar, you will do yourself a favor by familiarizing yourself.</p>\n" } ]
2008/11/07
[ "https://Stackoverflow.com/questions/271612", "https://Stackoverflow.com", "https://Stackoverflow.com/users/35416/" ]
I have the following file/line: ``` pc=1 ct=1 av=112 cv=1100 cp=1700 rec=2 p=10001 g=0 a=0 sz=5 cr=200 pc=1 ct=1 av=113 cv=1110 cp=1800 rec=2 p=10001 g=0 a=10 sz=5 cr=200 ``` and so on. I wish to parse this and take the key value pairs and put them in a structure: ``` struct pky { pky() : a_id(0), sz_id(0), cr_id(0), cp_id(0), cv_id(0), ct_id(0), fr(0), g('U'), a(0), pc(0), p_id(0) { } }; ``` wherein either all the structure fields are used or some might be omitted. How do I create a C++ class, which will do the same? I am new to C++ and not aware of any functions or library which would do this work. Each line is to be processed, and the structure will be populated with one line each time and used, before it is flushed. The structure is later used as a parameter to a function.
You can do something like this: ``` std::string line; std::map<std::string, std::string> props; std::ifstream file("foo.txt"); while(std::getline(file, line)) { std::string token; std::istringstream tokens(line); while(tokens >> token) { std::size_t pos = token.find('='); if(pos != std::string::npos) { props[token.substr(0, pos)] = token.substr(pos + 1); } } /* work with those keys/values by doing properties["name"] */ Line l(props["pc"], props["ct"], ...); /* clear the map for the next line */ props.clear(); } ``` i hope it's helpful. Line can be like this: ``` struct Line { std::string pc, ct; Line(std::string const& pc, std::string const& ct):pc(pc), ct(ct) { } }; ``` now that works only if the delimiter is a space. you can make it work with other delimiters too. change ``` while(tokens >> token) { ``` into for example the following, if you want to have a semicolon: ``` while(std::getline(tokens, token, ';')) { ``` actually, it looks like you have only integers as values, and whitespace as delimiters. you might want to change ``` std::string token; std::istringstream tokens(line); while(tokens >> token) { std::size_t pos = token.find('='); if(pos != std::string::npos) { props[token.substr(0, pos)] = token.substr(pos + 1); } } ``` into this then: ``` int value; std::string key; std::istringstream tokens(line); while(tokens >> std::ws && std::getline(tokens, key, '=') && tokens >> std::ws >> value) { props[key] = value; } ``` `std::ws` just eats whitespace. you should change the type of props to ``` std::map<std::string, int> props; ``` then too, and make Line accept int instead of std::string's. i hope this is not too much information at once.
271,613
<p>I was reading <em><a href="http://java.sun.com/docs/books/performance/1st_edition/html/JPAppGC.fm.html" rel="nofollow noreferrer">Java Platform Performance</a></em> (sadly the link seems to have disappeared from the internet since I originally posed this question) and section A.3.3 worried me.</p> <p>I had been working on the assumption that a variable that dropped out of scope would no longer be considered a GC root, but this paper appears to contradict that.</p> <p>Do recent JVMs, in particular Sun's 1.6.0_07 version, still have this limitation? If so, then I have a lot of code to analyse...</p> <p>I ask the question because the paper is from 1999 - sometimes things change, particularly in the world of GC.</p> <hr/> <p>As the paper is no longer available, I'd like to paraphrase the concern. The paper implied that variables that were defined inside a method would be considered a GC root until the method exited, and not until the code block ended. Therefore setting the variable to null was necessary to permit the Object referenced to be garbage collected.</p> <p>This meant that a local variable defined in a conditional block in the main() method (or similar method that contained an infinite loop) would cause a one-off memory leak unless you nulled a variable just before it dropped out of scope.</p> <p>The code from the <a href="https://stackoverflow.com/a/271824/7938">chosen answer</a> illustrates the issue well. On the version of the JVM referenced in the document, the foo object can not be garbage collected when it drops out of scope at the end of the try block. Instead, the JVM will hold open the reference until the end of the main() method, even though it is impossible for anything to use that reference.</p> <p>This appears to be the origin of the idea that nulling a variable reference would help the garbage collector out, even if the variable was just about to drop out of scope.</p>
[ { "answer_id": 271636, "author": "Jon Skeet", "author_id": 22656, "author_profile": "https://Stackoverflow.com/users/22656", "pm_score": 1, "selected": false, "text": "<p>Would you really have that much code to analyse? Basically I can only see this being a significant problem for very long-running methods - which are typically just the ones at the top of each thread's stack.</p>\n\n<p>I wouldn't be at all surprised if it's unfixed at the moment, but I don't think it's likely to be as significant as you seem to fear.</p>\n" }, { "answer_id": 271824, "author": "Rasmus Faber", "author_id": 5542, "author_profile": "https://Stackoverflow.com/users/5542", "pm_score": 4, "selected": true, "text": "<p>This code should clear it up:</p>\n<pre><code>public class TestInvisibleObject{\n public static class PrintWhenFinalized{\n private String s;\n public PrintWhenFinalized(String s){\n System.out.println(&quot;Constructing from &quot;+s);\n this.s = s;\n }\n protected void finalize() throws Throwable {\n System.out.println(&quot;Finalizing from &quot;+s);\n } \n }\n public static void main(String[] args) {\n try {\n PrintWhenFinalized foo = new PrintWhenFinalized(&quot;main&quot;);\n } catch (Exception e) {\n // whatever\n }\n while (true) {\n // Provoke garbage-collection by allocating lots of memory\n byte[] o = new byte[1024];\n } \n }\n}\n</code></pre>\n<p>On my machine (jdk1.6.0_05) it prints:</p>\n<blockquote>\n<p>Constructing from main</p>\n<p>Finalizing from main</p>\n</blockquote>\n<p>So it looks like the problems has been fixed.</p>\n<p>Note that using System.gc() instead of the loop does not cause the object to be collected for some reason.</p>\n" }, { "answer_id": 271932, "author": "bruno conde", "author_id": 31136, "author_profile": "https://Stackoverflow.com/users/31136", "pm_score": 2, "selected": false, "text": "<p>The article states that:</p>\n\n<blockquote>\n <p>... an efficient implementation of the\n JVM is unlikely to zero the reference\n when it goes out of scope</p>\n</blockquote>\n\n<p>I think this happens because of situations like this:</p>\n\n<pre><code>public void doSomething() { \n for(int i = 0; i &lt; 10 ; i++) {\n String s = new String(\"boo\");\n System.out.println(s);\n }\n}\n</code></pre>\n\n<p>Here, the same reference is used by the \"efficient JVM\" in each declaration of String s, but there will be 10 new Strings in the heap if the GC doesn't kick in.</p>\n\n<p>In the article example I think that the reference to foo keeps in the stack because the \"efficient JVM\" <em>thinks</em> that is very likely that another foo object will be created and, if so, it will use the same reference. Thoughts???</p>\n\n<pre><code>public void run() {\n try {\n Object foo = new Object();\n foo.doSomething();\n } catch (Exception e) {\n // whatever\n }\n while (true) { // do stuff } // loop forever\n}\n</code></pre>\n\n<p>I've also performed the next test with profiling:</p>\n\n<pre><code>public class A {\n\n public static void main(String[] args) {\n A a = new A(); \n a.test4();\n }\n\n public void test1() { \n for(int i = 0; i &lt; 10 ; i++) {\n B b = new B();\n System.out.println(b.toString());\n }\n System.out.println(\"b is collected\");\n }\n\n public void test2() {\n try {\n B b = new B();\n System.out.println(b.toString());\n } catch (Exception e) {\n }\n System.out.println(\"b is invisible\");\n }\n\n public void test3() {\n if (true) {\n B b = new B();\n System.out.println(b.toString());\n }\n System.out.println(\"b is invisible\");\n }\n\n public void test4() {\n int i = 0;\n while (i &lt; 10) {\n B b = new B();\n System.out.println(b.toString());\n i++;\n }\n System.out.println(\"b is collected\");\n }\n\n public A() {\n }\n\n class B {\n public B() {\n }\n\n @Override\n public String toString() {\n return \"I'm B.\";\n }\n }\n}\n</code></pre>\n\n<p>and come to the conclusions:</p>\n\n<p>teste1 -> b is collected</p>\n\n<p>teste2 -> b is invisible</p>\n\n<p>teste3 -> b is invisible</p>\n\n<p>teste4 -> b is collected</p>\n\n<p>... so I think that, in loops, the JVM doesn't create invisible variables when the loop ends because it's unlikely they will be declared again outside the loop.</p>\n\n<p>Any Thoughts??</p>\n" }, { "answer_id": 18406054, "author": "Holger", "author_id": 2711488, "author_profile": "https://Stackoverflow.com/users/2711488", "pm_score": 2, "selected": false, "text": "<p>The problem is still there. I tested it with Java 8 and could prove it.</p>\n\n<p>You should note the following things:</p>\n\n<ol>\n<li><p>The only way to force a guaranteed garbage collection is to try an allocation which ends in an OutOfMemoryError as the JVM is required to try freeing unused objects before throwing. This however does not hold if the requested amount is too large to ever succeed, i.e. excesses the address space. Trying to raise the allocation until getting an OOME is a good strategy.</p></li>\n<li><p>The guaranteed GC described in Point 1 does not guaranty a finalization. The time when finalize() methods are invoked is not specified, they might be never called at all. So adding a finalize() method to a class might prevent its instances from being collected, so finalize is not a good choice to analyse GC behavior.</p></li>\n<li><p>Creating another new local variable after a local variable went out of scope will reuse its place in the stack frame. In the following example, object a will be collected as its place in the stack frame is occupied by the local variable b. But b last until the end of the main method as there is no other local variable to occupy its place.</p>\n\n<pre><code>import java.lang.ref.*;\n\npublic class Test {\n static final ReferenceQueue&lt;Object&gt; RQ=new ReferenceQueue&lt;&gt;();\n static Reference&lt;Object&gt; A, B;\n public static void main(String[] s) {\n {\n Object a=new Object();\n A=new PhantomReference&lt;&gt;(a, RQ);\n }\n {\n Object b=new Object();\n B=new PhantomReference&lt;&gt;(b, RQ);\n }\n forceGC();\n checkGC();\n }\n\n private static void forceGC() {\n try {\n for(int i=100000;;i+=i) {\n byte[] b=new byte[i];\n }\n } catch(OutOfMemoryError err){ err.printStackTrace();}\n }\n\n private static void checkGC() {\n for(;;) {\n Reference&lt;?&gt; r=RQ.poll();\n if(r==null) break;\n if(r==A) System.out.println(\"Object a collected\");\n if(r==B) System.out.println(\"Object b collected\");\n }\n }\n}\n</code></pre></li>\n</ol>\n" } ]
2008/11/07
[ "https://Stackoverflow.com/questions/271613", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7938/" ]
I was reading *[Java Platform Performance](http://java.sun.com/docs/books/performance/1st_edition/html/JPAppGC.fm.html)* (sadly the link seems to have disappeared from the internet since I originally posed this question) and section A.3.3 worried me. I had been working on the assumption that a variable that dropped out of scope would no longer be considered a GC root, but this paper appears to contradict that. Do recent JVMs, in particular Sun's 1.6.0\_07 version, still have this limitation? If so, then I have a lot of code to analyse... I ask the question because the paper is from 1999 - sometimes things change, particularly in the world of GC. --- As the paper is no longer available, I'd like to paraphrase the concern. The paper implied that variables that were defined inside a method would be considered a GC root until the method exited, and not until the code block ended. Therefore setting the variable to null was necessary to permit the Object referenced to be garbage collected. This meant that a local variable defined in a conditional block in the main() method (or similar method that contained an infinite loop) would cause a one-off memory leak unless you nulled a variable just before it dropped out of scope. The code from the [chosen answer](https://stackoverflow.com/a/271824/7938) illustrates the issue well. On the version of the JVM referenced in the document, the foo object can not be garbage collected when it drops out of scope at the end of the try block. Instead, the JVM will hold open the reference until the end of the main() method, even though it is impossible for anything to use that reference. This appears to be the origin of the idea that nulling a variable reference would help the garbage collector out, even if the variable was just about to drop out of scope.
This code should clear it up: ``` public class TestInvisibleObject{ public static class PrintWhenFinalized{ private String s; public PrintWhenFinalized(String s){ System.out.println("Constructing from "+s); this.s = s; } protected void finalize() throws Throwable { System.out.println("Finalizing from "+s); } } public static void main(String[] args) { try { PrintWhenFinalized foo = new PrintWhenFinalized("main"); } catch (Exception e) { // whatever } while (true) { // Provoke garbage-collection by allocating lots of memory byte[] o = new byte[1024]; } } } ``` On my machine (jdk1.6.0\_05) it prints: > > Constructing from main > > > Finalizing from main > > > So it looks like the problems has been fixed. Note that using System.gc() instead of the loop does not cause the object to be collected for some reason.
271,615
<p>I have two lists of custom objects and want to update a field for all objects in one list if there is an object in the other list which matches on another pair of fields.</p> <p>This code explains the problem better and produces the results I want. However for larger lists 20k, and a 20k list with matching objects, this takes a considerable time (31s). I can improve this with ~50% by using the generic lists Find(Predicate) method.</p> <pre><code>using System; using System.Linq; using System.Linq.Expressions; using System.Collections.Generic; namespace ExperimentFW3 { public class PropValue { public string Name; public decimal Val; public decimal Total; } public class Adjustment { public string PropName; public decimal AdjVal; } class Program { static List&lt;PropValue&gt; propList; static List&lt;Adjustment&gt; adjList; public static void Main() { propList = new List&lt;PropValue&gt;{ new PropValue{Name = "Alfa", Val=2.1M}, new PropValue{Name = "Beta", Val=1.0M}, new PropValue{Name = "Gamma", Val=8.0M} }; adjList = new List&lt;Adjustment&gt;{ new Adjustment{PropName = "Alfa", AdjVal=-0.1M}, new Adjustment{PropName = "Beta", AdjVal=3M} }; foreach (var p in propList) { Adjustment a = adjList.SingleOrDefault( av =&gt; av.PropName.Equals(p.Name) ); if (a != null) p.Total = p.Val + a.AdjVal; else p.Total = p.Val; } } } } </code></pre> <p>The desired result is: Alfa total=2,Beta total=4,Gamma total=8</p> <p>But I wonder if this is possible to do even faster. Inner joining the two lists takes very little time, even when looping over 20k items in the resultset.</p> <pre><code>var joined = from p in propList join a in adjList on p.Name equals a.PropName select new { p.Name, p.Val, p.Total, a.AdjVal }; </code></pre> <p>So my question is if it's possible to do something like I would do with T-SQL? An UPDATE from a left join using ISNULL(val,0) on the adjustment value.</p>
[ { "answer_id": 271645, "author": "Jon Skeet", "author_id": 22656, "author_profile": "https://Stackoverflow.com/users/22656", "pm_score": 4, "selected": true, "text": "<p>That join should be fairly fast, as it will first loop through all of <code>adjList</code> to create a lookup, then for each element in <code>propList</code> it will just use the lookup. This is faster than your O(N * M) method in the larger code - although that could easily be fixed by calling <a href=\"http://msdn.microsoft.com/en-us/library/system.linq.enumerable.tolookup.aspx\" rel=\"nofollow noreferrer\"><code>ToLookup</code></a> (or <a href=\"http://msdn.microsoft.com/en-us/library/system.linq.enumerable.todictionary.aspx\" rel=\"nofollow noreferrer\"><code>ToDictionary</code></a> as you only need one value) on <code>adjList</code> before the loop.</p>\n\n<p>EDIT: Here's the modified code using <code>ToDictionary</code>. Untested, mind you...</p>\n\n<pre><code>var adjDictionary = adjList.ToDictionary(av =&gt; av.PropName);\nforeach (var p in propList)\n{\n Adjustment a;\n if (adjDictionary.TryGetValue(p.Name, out a))\n {\n p.Total = p.Val + a.AdjVal;\n }\n else\n {\n p.Total = p.Val;\n }\n}\n</code></pre>\n" }, { "answer_id": 272155, "author": "Amy B", "author_id": 8155, "author_profile": "https://Stackoverflow.com/users/8155", "pm_score": 0, "selected": false, "text": "<p>If adjList might have duplicate names, you should group the items before pushing to dictionary.</p>\n\n<pre><code>Dictionary&lt;string, decimal&gt; adjDictionary = adjList\n .GroupBy(a =&gt; a.PropName)\n .ToDictionary(g =&gt; g.Key, g =&gt; g.Sum(a =&gt; a.AdjVal))\n\npropList.ForEach(p =&gt; \n {\n decimal a;\n adjDictionary.TryGetValue(p.Name, out a);\n p.Total = p.Val + a;\n });\n</code></pre>\n" }, { "answer_id": 2093104, "author": "DRBlaise", "author_id": 234720, "author_profile": "https://Stackoverflow.com/users/234720", "pm_score": 0, "selected": false, "text": "<p>I know I am late posting this, but I thought someone would appreciate the clearer shorter answer below that handles multiple records per lookup in adjList. Creating a LookUp will allow fast lookups on multiple items and will return an empty list if there are no records in LookUp.</p>\n\n<pre><code>var adjLookUp = adjList.ToLookUp(a =&gt; a.PropName);\nforeach (var p in propList) \n p.Total = p.Val + adjLookUp[p.Name].Sum(a =&gt; a.AdjVal);\n</code></pre>\n" } ]
2008/11/07
[ "https://Stackoverflow.com/questions/271615", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2006748/" ]
I have two lists of custom objects and want to update a field for all objects in one list if there is an object in the other list which matches on another pair of fields. This code explains the problem better and produces the results I want. However for larger lists 20k, and a 20k list with matching objects, this takes a considerable time (31s). I can improve this with ~50% by using the generic lists Find(Predicate) method. ``` using System; using System.Linq; using System.Linq.Expressions; using System.Collections.Generic; namespace ExperimentFW3 { public class PropValue { public string Name; public decimal Val; public decimal Total; } public class Adjustment { public string PropName; public decimal AdjVal; } class Program { static List<PropValue> propList; static List<Adjustment> adjList; public static void Main() { propList = new List<PropValue>{ new PropValue{Name = "Alfa", Val=2.1M}, new PropValue{Name = "Beta", Val=1.0M}, new PropValue{Name = "Gamma", Val=8.0M} }; adjList = new List<Adjustment>{ new Adjustment{PropName = "Alfa", AdjVal=-0.1M}, new Adjustment{PropName = "Beta", AdjVal=3M} }; foreach (var p in propList) { Adjustment a = adjList.SingleOrDefault( av => av.PropName.Equals(p.Name) ); if (a != null) p.Total = p.Val + a.AdjVal; else p.Total = p.Val; } } } } ``` The desired result is: Alfa total=2,Beta total=4,Gamma total=8 But I wonder if this is possible to do even faster. Inner joining the two lists takes very little time, even when looping over 20k items in the resultset. ``` var joined = from p in propList join a in adjList on p.Name equals a.PropName select new { p.Name, p.Val, p.Total, a.AdjVal }; ``` So my question is if it's possible to do something like I would do with T-SQL? An UPDATE from a left join using ISNULL(val,0) on the adjustment value.
That join should be fairly fast, as it will first loop through all of `adjList` to create a lookup, then for each element in `propList` it will just use the lookup. This is faster than your O(N \* M) method in the larger code - although that could easily be fixed by calling [`ToLookup`](http://msdn.microsoft.com/en-us/library/system.linq.enumerable.tolookup.aspx) (or [`ToDictionary`](http://msdn.microsoft.com/en-us/library/system.linq.enumerable.todictionary.aspx) as you only need one value) on `adjList` before the loop. EDIT: Here's the modified code using `ToDictionary`. Untested, mind you... ``` var adjDictionary = adjList.ToDictionary(av => av.PropName); foreach (var p in propList) { Adjustment a; if (adjDictionary.TryGetValue(p.Name, out a)) { p.Total = p.Val + a.AdjVal; } else { p.Total = p.Val; } } ```
271,657
<p>I have many emails coming in from different sources. they all have attachments, many of them have attachment names in chinese, so these names are converted to base64 by their email clients.</p> <p>When I receive these emails, I wish to decode the name. but there are other names which are not base64. How can I differentiate whether a string is base64 or not, using the <strong>jython</strong> programming language?</p> <p>Ie. </p> <p>First attachment: </p> <pre><code>------=_NextPart_000_0091_01C940CC.EF5AC860 Content-Type: application/vnd.ms-excel; name="Copy of Book1.xls" Content-Transfer-Encoding: base64 Content-Disposition: attachment; filename="Copy of Book1.xls" </code></pre> <p>second attachment:</p> <pre><code>------=_NextPart_000_0091_01C940CC.EF5AC860 Content-Type: application/vnd.ms-excel; name="=?gb2312?B?uLGxvmhlbrixsb5nLnhscw==?=" Content-Transfer-Encoding: base64 Content-Disposition: attachment; filename="=?gb2312?B?uLGxvmhlbrixsb5nLnhscw==?=" </code></pre> <p>Please note both "<strong>Content-Transfer-Encoding</strong>" have base64</p>
[ { "answer_id": 271693, "author": "gnud", "author_id": 27204, "author_profile": "https://Stackoverflow.com/users/27204", "pm_score": 0, "selected": false, "text": "<p>Well, you parse the email header into a dictionary. And then you check if Content-Transfer-Encoding is set, and if it = \"base64\" or \"base-64\".</p>\n" }, { "answer_id": 271705, "author": "Corey Trager", "author_id": 9328, "author_profile": "https://Stackoverflow.com/users/9328", "pm_score": 3, "selected": false, "text": "<p>@gnud, @edg - Unless I misunderstand, he's asking about the filename, not the file content\n@setori - the Content-Trasfer-Encoding is telling you how the CONTENT of the file is encoded, not the &quot;filename&quot;.</p>\n<p>I'm not an expert, but this part here in the filename is telling him about the characters that follow:</p>\n<p>=?gb2312?B?</p>\n<p>I'm looking for the documentation in the RFCs... Ah! here it is: <a href=\"https://www.rfc-editor.org/rfc/rfc2047\" rel=\"nofollow noreferrer\">https://www.rfc-editor.org/rfc/rfc2047</a></p>\n<p>The RFC says:</p>\n<p><em><strong>Generally, an &quot;encoded-word&quot; is a sequence of printable ASCII characters that begins with &quot;=?&quot;, ends with &quot;?=&quot;, and has two &quot;?&quot;s in between.</strong></em></p>\n<p>Something else to look at is the code in SharpMimeTools, a MIME parser (in C#) that I use in my <a href=\"http://ifdefined.com/bugtrackernet.html\" rel=\"nofollow noreferrer\">bug tracking</a> app, <a href=\"http://ifdefined.com/bugtrackernet.html\" rel=\"nofollow noreferrer\">BugTracker.NET</a></p>\n" }, { "answer_id": 271720, "author": "Tomalak", "author_id": 18771, "author_profile": "https://Stackoverflow.com/users/18771", "pm_score": 4, "selected": false, "text": "<p>The header value tells you this:</p>\n\n<pre>\n=?gb2312?B?uLGxvmhlbrixsb5nLnhscw==?=\n\n\"=?\" introduces an encoded value\n\"gb2312\" denotes the character encoding of the original value\n\"B\" denotes that B-encoding (equal to Base64) was used (the alternative \n is \"Q\", which refers to something close to quoted-printable)\n\"?\" functions as a separator\n\"uLG...\" is the actual value, encoded using the encoding specified before\n\"?=\" ends the encoded value\n</pre>\n\n<p>So splitting on \"?\" actually gets you this (JSON notation)</p>\n\n<pre>\n[\"=\", \"gb2312\", \"B\", \"uLGxvmhlbrixsb5nLnhscw==\", \"=\"]\n</pre>\n\n<p>In the resulting array, if \"B\" is on position 2, you face a base-64 encoded string on position 3. Once you decoded it, be sure to pay attention to the encoding on position 1, probably it would be best to convert the whole thing to UTF-8 using that info.</p>\n" }, { "answer_id": 271832, "author": "bobince", "author_id": 18936, "author_profile": "https://Stackoverflow.com/users/18936", "pm_score": 5, "selected": true, "text": "<blockquote>\n <p>Please note both <code>Content-Transfer-Encoding</code> have base64</p>\n</blockquote>\n\n<p>Not relevant in this case, the <code>Content-Transfer-Encoding</code> only applies to the body payload, not to the headers.</p>\n\n<pre><code>=?gb2312?B?uLGxvmhlbrixsb5nLnhscw==?=\n</code></pre>\n\n<p>That's an <strong>RFC2047</strong>-encoded header atom. The stdlib function to decode it is <code>email.header.decode_header</code>. It still needs a little post-processing to interpret the outcome of that function though:</p>\n\n<pre><code>import email.header\nx= '=?gb2312?B?uLGxvmhlbrixsb5nLnhscw==?='\ntry:\n name= u''.join([\n unicode(b, e or 'ascii') for b, e in email.header.decode_header(x)\n ])\nexcept email.Errors.HeaderParseError:\n pass # leave name as it was\n</code></pre>\n\n<p>However...</p>\n\n<pre><code>Content-Type: application/vnd.ms-excel;\n name=\"=?gb2312?B?uLGxvmhlbrixsb5nLnhscw==?=\"\n</code></pre>\n\n<p>This is simply wrong. What mailer created it? RFC2047 encoding can only happen in atoms, and a quoted-string is not an atom. RFC2047 §5 explicitly denies this:</p>\n\n<blockquote>\n <ul>\n <li>An 'encoded-word' MUST NOT appear within a 'quoted-string'.</li>\n </ul>\n</blockquote>\n\n<p>The accepted way to encode parameter headers when long string or Unicode characters are present is <strong>RFC2231</strong>, which is a whole new bag of hurt. But you should be using a standard mail-parsing library which will cope with that for you.</p>\n\n<p>So, you could detect the <code>'=?'</code> in filename parameters if you want, and try to decode it via RFC2047. However, the strictly-speaking-correct thing to do is to take the mailer at its word and really call the file <code>=?gb2312?B?uLGxvmhlbrixsb5nLnhscw==?=</code>!</p>\n" }, { "answer_id": 1687765, "author": "Ringding", "author_id": 135811, "author_profile": "https://Stackoverflow.com/users/135811", "pm_score": 2, "selected": false, "text": "<p>There is a better way than bobince’s method to handle the output of <code>decode_header</code>. I found it here: <a href=\"http://mail.python.org/pipermail/email-sig/2007-March/000332.html\" rel=\"nofollow noreferrer\">http://mail.python.org/pipermail/email-sig/2007-March/000332.html</a></p>\n\n<pre><code>name = unicode(email.header.make_header(email.header.decode_header(x)))\n</code></pre>\n" }, { "answer_id": 2955981, "author": "John Machin", "author_id": 84270, "author_profile": "https://Stackoverflow.com/users/84270", "pm_score": 0, "selected": false, "text": "<p>Question: \"\"\"Also I actually need to know what type of file it is ie .xls or .doc so I do need to decode the filename in order to correctly process the attachment, but as above, seems gb2312 is not supported in jython, know any roundabouts?\"\"\"</p>\n\n<p>Data:</p>\n\n<pre><code>Content-Type: application/vnd.ms-excel;\n name=\"=?gb2312?B?uLGxvmhlbrixsb5nLnhscw==?=\"\n</code></pre>\n\n<p>Observations:</p>\n\n<p>(1) The first line indicates Microsoft Excel, so <code>.xls</code> is looking better than <code>.doc</code></p>\n\n<p>(2) </p>\n\n<pre><code>&gt;&gt;&gt; import base64\n&gt;&gt;&gt; base64.b64decode(\"uLGxvmhlbrixsb5nLnhscw==\")\n'\\xb8\\xb1\\xb1\\xbehen\\xb8\\xb1\\xb1\\xbeg.xls'\n&gt;&gt;&gt;\n</code></pre>\n\n<p>(a) The extension appears to be <code>.xls</code> -- no need for a <code>gb2312</code> codec<br>\n(b) If you want a file-system-safe file name, you could use the \"-_\" variant of base64 OR you could percent-encode it<br>\n(c) For what it's worth, the file name is <code>XYhenXYg.xls</code> where X and Y are 2 Chinese characters that together mean \"copy\" and the remainder are literal ASCII characters.</p>\n" } ]
2008/11/07
[ "https://Stackoverflow.com/questions/271657", "https://Stackoverflow.com", "https://Stackoverflow.com/users/21537/" ]
I have many emails coming in from different sources. they all have attachments, many of them have attachment names in chinese, so these names are converted to base64 by their email clients. When I receive these emails, I wish to decode the name. but there are other names which are not base64. How can I differentiate whether a string is base64 or not, using the **jython** programming language? Ie. First attachment: ``` ------=_NextPart_000_0091_01C940CC.EF5AC860 Content-Type: application/vnd.ms-excel; name="Copy of Book1.xls" Content-Transfer-Encoding: base64 Content-Disposition: attachment; filename="Copy of Book1.xls" ``` second attachment: ``` ------=_NextPart_000_0091_01C940CC.EF5AC860 Content-Type: application/vnd.ms-excel; name="=?gb2312?B?uLGxvmhlbrixsb5nLnhscw==?=" Content-Transfer-Encoding: base64 Content-Disposition: attachment; filename="=?gb2312?B?uLGxvmhlbrixsb5nLnhscw==?=" ``` Please note both "**Content-Transfer-Encoding**" have base64
> > Please note both `Content-Transfer-Encoding` have base64 > > > Not relevant in this case, the `Content-Transfer-Encoding` only applies to the body payload, not to the headers. ``` =?gb2312?B?uLGxvmhlbrixsb5nLnhscw==?= ``` That's an **RFC2047**-encoded header atom. The stdlib function to decode it is `email.header.decode_header`. It still needs a little post-processing to interpret the outcome of that function though: ``` import email.header x= '=?gb2312?B?uLGxvmhlbrixsb5nLnhscw==?=' try: name= u''.join([ unicode(b, e or 'ascii') for b, e in email.header.decode_header(x) ]) except email.Errors.HeaderParseError: pass # leave name as it was ``` However... ``` Content-Type: application/vnd.ms-excel; name="=?gb2312?B?uLGxvmhlbrixsb5nLnhscw==?=" ``` This is simply wrong. What mailer created it? RFC2047 encoding can only happen in atoms, and a quoted-string is not an atom. RFC2047 §5 explicitly denies this: > > * An 'encoded-word' MUST NOT appear within a 'quoted-string'. > > > The accepted way to encode parameter headers when long string or Unicode characters are present is **RFC2231**, which is a whole new bag of hurt. But you should be using a standard mail-parsing library which will cope with that for you. So, you could detect the `'=?'` in filename parameters if you want, and try to decode it via RFC2047. However, the strictly-speaking-correct thing to do is to take the mailer at its word and really call the file `=?gb2312?B?uLGxvmhlbrixsb5nLnhscw==?=`!
271,668
<p>Is there a way of converting special folder paths to a full file name (and back) or do I need to code my own (not hard I know, but no point if it exists)</p> <p>e.g. I want to store the file name of a template for an application, which the user can then change, it exists in the LocalApplicationData folder.</p> <p>what I would like to store is the location of the file in the format:</p> <p>%LOCALAPPDATA%\MyApp\Templates\Report Template.xls</p> <p>so that this application file can be used by many users, each user when they open it will get the Report Template from their own local app directory.</p> <p>I can write</p> <pre><code>replace("%LOCALAPPDATA%", _ System.Environment.GetFolderPath( System.Environment.SpecialFolder.LocalApplicationData)) and vice versa </code></pre> <p>when I come to save the file location, however is there a System.IO (or similar) call to do this for me, rather than having to go through every possible special folder?</p>
[ { "answer_id": 271683, "author": "chakrit", "author_id": 3055, "author_profile": "https://Stackoverflow.com/users/3055", "pm_score": 3, "selected": true, "text": "<p>Look at: <a href=\"http://msdn.microsoft.com/en-us/library/system.environment.expandenvironmentvariables.aspx\" rel=\"nofollow noreferrer\">Environment.ExpandEnvironmentVariables</a></p>\n\n<p>After some looking around I don't think there is a built-in way available to convert it back, though.</p>\n\n<p>You can do this though:</p>\n\n<pre><code>static void Main(string[] args)\n{\n var values = Enum.GetValues(typeof(Environment.SpecialFolder));\n\n foreach (Environment.SpecialFolder value in values)\n Console.WriteLine(value + \" : \" + Environment.GetFolderPath(value));\n\n Console.ReadKey();\n}\n</code></pre>\n" }, { "answer_id": 271734, "author": "MSalters", "author_id": 15416, "author_profile": "https://Stackoverflow.com/users/15416", "pm_score": 0, "selected": false, "text": "<p>The normal Windows way to identify \"special folders\" is by their <a href=\"http://msdn.microsoft.com/en-us/library/bb762494.aspx\" rel=\"nofollow noreferrer\">CSIDL</a>. Environment.SpecialFolder is just a small wrapper around it. As you noted, in a comment to chakrit's post, most CSIDLs simply do not have corresponding environment variables. This is a likely reason why there is no function to find the environment variable for the few CSIDLs that do.</p>\n" } ]
2008/11/07
[ "https://Stackoverflow.com/questions/271668", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6684/" ]
Is there a way of converting special folder paths to a full file name (and back) or do I need to code my own (not hard I know, but no point if it exists) e.g. I want to store the file name of a template for an application, which the user can then change, it exists in the LocalApplicationData folder. what I would like to store is the location of the file in the format: %LOCALAPPDATA%\MyApp\Templates\Report Template.xls so that this application file can be used by many users, each user when they open it will get the Report Template from their own local app directory. I can write ``` replace("%LOCALAPPDATA%", _ System.Environment.GetFolderPath( System.Environment.SpecialFolder.LocalApplicationData)) and vice versa ``` when I come to save the file location, however is there a System.IO (or similar) call to do this for me, rather than having to go through every possible special folder?
Look at: [Environment.ExpandEnvironmentVariables](http://msdn.microsoft.com/en-us/library/system.environment.expandenvironmentvariables.aspx) After some looking around I don't think there is a built-in way available to convert it back, though. You can do this though: ``` static void Main(string[] args) { var values = Enum.GetValues(typeof(Environment.SpecialFolder)); foreach (Environment.SpecialFolder value in values) Console.WriteLine(value + " : " + Environment.GetFolderPath(value)); Console.ReadKey(); } ```
271,672
<p>I tried this on J2ME</p> <pre><code>try { Image immutableThumb = Image.createImage( temp, 0, temp.length); } catch (Exception ex) { System.out.println(ex); } </code></pre> <p>I hit this error: <code>java.lang.IllegalArgumentException:</code></p> <p>How do I solve this?</p>
[ { "answer_id": 271680, "author": "Tyler Levine", "author_id": 35339, "author_profile": "https://Stackoverflow.com/users/35339", "pm_score": 1, "selected": false, "text": "<p>Image.createImage() throws an IllegalArgumentException if the first argument is incorrectly formatted or otherwise cannot be decoded. (I'm assuming that temp is a byte[]).</p>\n\n<p><a href=\"http://java.sun.com/javame/reference/apis/jsr118/javax/microedition/lcdui/Image.html#createImage(byte[],%20int,%20int)\" rel=\"nofollow noreferrer\">http://java.sun.com/javame/reference/apis/jsr118/javax/microedition/lcdui/Image.html#createImage(byte[],%20int,%20int)</a></p>\n\n<p>(This URL refuses to become a hyperlink for some reason (?))</p>\n" }, { "answer_id": 271787, "author": "izb", "author_id": 974, "author_profile": "https://Stackoverflow.com/users/974", "pm_score": 1, "selected": false, "text": "<p>It's hard to say without more details or more surrounding code, but my initial suspicion is that the file your are trying to load is in a format not supported by the device.</p>\n" }, { "answer_id": 365128, "author": "Malcolm", "author_id": 45668, "author_profile": "https://Stackoverflow.com/users/45668", "pm_score": 1, "selected": false, "text": "<p>Let us have a look at the docs: IllegalArgumentException is thrown </p>\n\n<blockquote>\n <p>if imageData is incorrectly formatted or otherwise cannot be decoded</p>\n</blockquote>\n\n<p>So the possible reason can be either unsupported format of the image, or truncated data. Remember, you should pass entire file to that method, including all the headers. If you have doubts about the format, you'd better choose <strong>PNG</strong>, it must be supported anyway.</p>\n" }, { "answer_id": 2461625, "author": "Cipi", "author_id": 191164, "author_profile": "https://Stackoverflow.com/users/191164", "pm_score": 0, "selected": false, "text": "<p>I just had the same problem with my MIDLET and the problem in my case was the HTTP header that comes along the JPEG image that I read from the socket's InputStream. And I solved it by finding the JPEG SOI marker that is identified by two bytes: <code>FFD8</code> in my byte array. Then when I find the location of the <code>FFD8</code> in my byte array, I trim the starting bytes that represent the HTTP header, and then I could call <code>createImage()</code> without any Exception being thrown... </p>\n\n<p>You should check if this is the case with you. Just check is this true <code>(temp[0] == 0xFF &amp;&amp; temp[1] == 0xD8)</code> and if it is not, trim the start of <code>temp</code> so you remove HTTP header or some other junk...</p>\n\n<p><strong>P.S.</strong> \nI presume that you are reading JPEG image, if not, look for the appropriate header in the <code>temp</code> array. </p>\n\n<p>Also if this doesn't help, and you are reading JPEG image make sure that the array starts with <code>FFD8</code> and ends with <code>FFD9</code> (which is the EOI marker). And if it doesn't end with the EOI just trim the end like I explained for SOI...</p>\n\n<p><strong>P.P.S</strong>\nAnd if you find that the data in <code>temp</code> is valid, then your platform cannot decode the JPEG images or the image in <code>temp</code> is to large for JPEG decoder.</p>\n" } ]
2008/11/07
[ "https://Stackoverflow.com/questions/271672", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
I tried this on J2ME ``` try { Image immutableThumb = Image.createImage( temp, 0, temp.length); } catch (Exception ex) { System.out.println(ex); } ``` I hit this error: `java.lang.IllegalArgumentException:` How do I solve this?
Image.createImage() throws an IllegalArgumentException if the first argument is incorrectly formatted or otherwise cannot be decoded. (I'm assuming that temp is a byte[]). <http://java.sun.com/javame/reference/apis/jsr118/javax/microedition/lcdui/Image.html#createImage(byte[],%20int,%20int)> (This URL refuses to become a hyperlink for some reason (?))
271,675
<p>I have a binded DataGridView where depending on some BoundItem property value that line will be read only. What is the best way to implement this? Thanks</p>
[ { "answer_id": 271679, "author": "CestLaGalere", "author_id": 6684, "author_profile": "https://Stackoverflow.com/users/6684", "pm_score": 0, "selected": false, "text": "<p>in the rowenter event, set the readonly property of the row accordingly</p>\n\n<pre><code>private sub MyView_RowEnter(...) handles MyView.RowEnter\n MyView.Rows(e.Rowindex).ReadOnly = (condition)\nend sub\n</code></pre>\n" }, { "answer_id": 3176471, "author": "x77", "author_id": 494800, "author_profile": "https://Stackoverflow.com/users/494800", "pm_score": 2, "selected": false, "text": "<p>Try The event CellBeginEdit</p>\n\n<pre><code>Private Sub Dgv_CellBeginEdit(ByVal sender As Object, ByVal e As System.Windows.Forms.DataGridViewCellCancelEventArgs) Handles Dgv.CellBeginEdit\n If YourCondition(BoundItem.Property) then e.cancel = true\nEnd Sub\n</code></pre>\n\n<p>This makes the cell readOnly depending on your condition.</p>\n" } ]
2008/11/07
[ "https://Stackoverflow.com/questions/271675", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
I have a binded DataGridView where depending on some BoundItem property value that line will be read only. What is the best way to implement this? Thanks
Try The event CellBeginEdit ``` Private Sub Dgv_CellBeginEdit(ByVal sender As Object, ByVal e As System.Windows.Forms.DataGridViewCellCancelEventArgs) Handles Dgv.CellBeginEdit If YourCondition(BoundItem.Property) then e.cancel = true End Sub ``` This makes the cell readOnly depending on your condition.
271,688
<p><a href="http://dl.getdropbox.com/u/240752/stars.gif" rel="nofollow noreferrer">My screenshot http://dl.getdropbox.com/u/240752/stars.gif</a></p> <p>I want to have it so that only the text is underlined. The only way I can see of doing this is this:</p> <pre><code>.no-underline { text-decoration:none; } .underline { text-decoration:underline; } &lt;a href="#" class="no-underline"&gt;&lt;span class="underline"&gt;Average customer review rating&lt;/span&gt;&lt;img src="img/five-stars.gif" alt="five stars" width="78" height="16" title="5 star review rating" /&gt;&lt;/a&gt; </code></pre> <p>Is this the best way? or does someone know a leaner way? Thanks.</p>
[ { "answer_id": 271697, "author": "Lasar", "author_id": 9438, "author_profile": "https://Stackoverflow.com/users/9438", "pm_score": 4, "selected": true, "text": "<p>No other solution really. Though you can shorten it a little:</p>\n\n<pre><code>&lt;a href=\"#\" class=\"imgLink\"&gt;&lt;span&gt;Link Text&lt;/span&gt; &lt;img src=\"...\"&gt;&lt;/a&gt;\n\na.imgLink { text-decoration: none; }\na.imgLink span { text-decoration: underline; }\n</code></pre>\n\n<p>That way you only need to specify one class.</p>\n" }, { "answer_id": 271732, "author": "jishi", "author_id": 33663, "author_profile": "https://Stackoverflow.com/users/33663", "pm_score": 0, "selected": false, "text": "<p>In which browser do you have a problem with this? Most browsers do not apply text-decoration to images since it makes no sence.</p>\n\n<p>othersize, just do like this:</p>\n\n<p><code>&lt;a class=\"imgLink\" href=\"\"&gt;some text&lt;img src=\"\" /&gt;&lt;/a&gt;</code></p>\n\n<pre>\n\n.imgLink {\n text-decoration: underline;\n}\n\n.imgLink img {\n text-decoration: none;\n}\n\n</pre>\n" }, { "answer_id": 1915596, "author": "elliott", "author_id": 230861, "author_profile": "https://Stackoverflow.com/users/230861", "pm_score": 0, "selected": false, "text": "<p>If you want to add non-underlined image badges for reusable link types, such as displaying a wikipedia-style external link arrow, try the following style:</p>\n\n<pre><code>a.externalLink{\n padding-right: 15px;\n background: transparent url('badge.png') no-repeat center right;\n}\n</code></pre>\n\n<p>Then in your markup:</p>\n\n<pre><code>&lt;a href=\"foo\" class=\"externalLink\"&gt;bar&lt;/a&gt;\n</code></pre>\n" } ]
2008/11/07
[ "https://Stackoverflow.com/questions/271688", "https://Stackoverflow.com", "https://Stackoverflow.com/users/26107/" ]
[My screenshot http://dl.getdropbox.com/u/240752/stars.gif](http://dl.getdropbox.com/u/240752/stars.gif) I want to have it so that only the text is underlined. The only way I can see of doing this is this: ``` .no-underline { text-decoration:none; } .underline { text-decoration:underline; } <a href="#" class="no-underline"><span class="underline">Average customer review rating</span><img src="img/five-stars.gif" alt="five stars" width="78" height="16" title="5 star review rating" /></a> ``` Is this the best way? or does someone know a leaner way? Thanks.
No other solution really. Though you can shorten it a little: ``` <a href="#" class="imgLink"><span>Link Text</span> <img src="..."></a> a.imgLink { text-decoration: none; } a.imgLink span { text-decoration: underline; } ``` That way you only need to specify one class.
271,699
<p>Is there any way to (unit) test my own HtmlHelpers? In case when I'd like to have custom control (rendered by HtmlHelper) and I know requierements for that control how could I write tests first - and then write code? Is there a specific (nice) way to do that? </p> <p>Is it worth?</p>
[ { "answer_id": 747186, "author": "Marc Climent", "author_id": 58791, "author_profile": "https://Stackoverflow.com/users/58791", "pm_score": 6, "selected": true, "text": "<p>The main problem is that you have to mock the HtmlHelper because you may be using methods of the helper to get routes or values or returning the result of another extension method. The HtmlHelper class has quite a lot of properties and some of them quite complex like the ViewContext or the current Controller.</p>\n\n<p><a href=\"http://web.archive.org/web/20090615064637/http://blog.benhartonline.com/post/2008/10/17/Mocking-ASPNET-MVC-HtmlHelper-extension-methods-using-Moq.aspx\" rel=\"noreferrer\">This post from Ben Hart</a> that explains how to create such a mock with Moq. Can be easily translated to another mock framework.</p>\n\n<p>This is my Rhino Mocks version adapted to the changes in the MVC Framework. It's not fully tested but it's working for me but don't expect perfect results:</p>\n\n<pre><code> public static HtmlHelper CreateHtmlHelper(ViewDataDictionary viewData)\n {\n var mocks = new MockRepository();\n\n var cc = mocks.DynamicMock&lt;ControllerContext&gt;(\n mocks.DynamicMock&lt;HttpContextBase&gt;(),\n new RouteData(),\n mocks.DynamicMock&lt;ControllerBase&gt;());\n\n var mockViewContext = mocks.DynamicMock&lt;ViewContext&gt;(\n cc,\n mocks.DynamicMock&lt;IView&gt;(),\n viewData,\n new TempDataDictionary());\n\n var mockViewDataContainer = mocks.DynamicMock&lt;IViewDataContainer&gt;();\n\n mockViewDataContainer.Expect(v =&gt; v.ViewData).Return(viewData);\n\n return new HtmlHelper(mockViewContext, mockViewDataContainer);\n }\n</code></pre>\n" }, { "answer_id": 4863413, "author": "Razvan Dimescu", "author_id": 34296, "author_profile": "https://Stackoverflow.com/users/34296", "pm_score": 0, "selected": false, "text": "<p>I'm creating a custom helper, and this is the code i'm using to mock the httphelper with Moq and ASP MVC 2. I'm also passing as a parameter a mock of the HttpRequestBase. You can remove that if you don't need it</p>\n\n<pre>\npublic static HtmlHelper CreateHtmlHelper(ViewDataDictionary viewData, Mock requestMock)\n {\n var contextBaseMock = new Mock();\n contextBaseMock.SetupGet(cb => cb.Request).Returns(requestMock.Object);\n\n var cc = new ControllerContext(contextBaseMock.Object,\n new RouteData(),\n new Mock().Object);\n var vctx = new ViewContext(\n cc,\n new Mock().Object,\n viewData,\n new TempDataDictionary(),\n new HtmlTextWriter(new StreamWriter(new MemoryStream())));\n\n var mockViewDataContainer = new Mock();\n\n mockViewDataContainer.SetupGet(v => v.ViewData).Returns(viewData);\n\n return new HtmlHelper(vctx, mockViewDataContainer.Object);\n }\n</pre>\n" }, { "answer_id": 5957990, "author": "CRice", "author_id": 55693, "author_profile": "https://Stackoverflow.com/users/55693", "pm_score": 3, "selected": false, "text": "<p>If anyone is looking for how to create <code>HtmlHelper&lt;T&gt;</code> (that's what I was after), here is an implementation that might help - my type is a class named Model:</p>\n\n<pre><code>public static HtmlHelper&lt;Model&gt; CreateHtmlHelper()\n{\n ViewDataDictionary vd = new ViewDataDictionary(new Model());\n\n var controllerContext = new ControllerContext(new Mock&lt;HttpContextBase&gt;().Object,\n new RouteData(),\n new Mock&lt;ControllerBase&gt;().Object);\n\n var viewContext = new ViewContext(controllerContext, new Mock&lt;IView&gt;().Object, vd, new TempDataDictionary(), new Mock&lt;TextWriter&gt;().Object);\n\n var mockViewDataContainer = new Mock&lt;IViewDataContainer&gt;();\n mockViewDataContainer.Setup(v =&gt; v.ViewData).Returns(vd);\n\n return new HtmlHelper&lt;Model&gt;(viewContext, mockViewDataContainer.Object);\n}\n</code></pre>\n\n<p>Or a more generic implementation:</p>\n\n<pre><code> public HtmlHelper&lt;T&gt; CreateHtmlHelper&lt;T&gt;() where T : new()\n {\n var vd = new ViewDataDictionary(new T());\n\n var controllerContext = new ControllerContext(new Mock&lt;HttpContextBase&gt;().Object,\n new RouteData(),\n new Mock&lt;ControllerBase&gt;().Object);\n\n var viewContext = new ViewContext(controllerContext, new Mock&lt;IView&gt;().Object, vd, new TempDataDictionary(), new Mock&lt;TextWriter&gt;().Object);\n\n var mockViewDataContainer = new Mock&lt;IViewDataContainer&gt;();\n mockViewDataContainer.Setup(v =&gt; v.ViewData).Returns(vd);\n\n return new HtmlHelper&lt;T&gt;(viewContext, mockViewDataContainer.Object);\n }\n</code></pre>\n" } ]
2008/11/07
[ "https://Stackoverflow.com/questions/271699", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3182/" ]
Is there any way to (unit) test my own HtmlHelpers? In case when I'd like to have custom control (rendered by HtmlHelper) and I know requierements for that control how could I write tests first - and then write code? Is there a specific (nice) way to do that? Is it worth?
The main problem is that you have to mock the HtmlHelper because you may be using methods of the helper to get routes or values or returning the result of another extension method. The HtmlHelper class has quite a lot of properties and some of them quite complex like the ViewContext or the current Controller. [This post from Ben Hart](http://web.archive.org/web/20090615064637/http://blog.benhartonline.com/post/2008/10/17/Mocking-ASPNET-MVC-HtmlHelper-extension-methods-using-Moq.aspx) that explains how to create such a mock with Moq. Can be easily translated to another mock framework. This is my Rhino Mocks version adapted to the changes in the MVC Framework. It's not fully tested but it's working for me but don't expect perfect results: ``` public static HtmlHelper CreateHtmlHelper(ViewDataDictionary viewData) { var mocks = new MockRepository(); var cc = mocks.DynamicMock<ControllerContext>( mocks.DynamicMock<HttpContextBase>(), new RouteData(), mocks.DynamicMock<ControllerBase>()); var mockViewContext = mocks.DynamicMock<ViewContext>( cc, mocks.DynamicMock<IView>(), viewData, new TempDataDictionary()); var mockViewDataContainer = mocks.DynamicMock<IViewDataContainer>(); mockViewDataContainer.Expect(v => v.ViewData).Return(viewData); return new HtmlHelper(mockViewContext, mockViewDataContainer); } ```
271,706
<p>I basically have a page which shows a "processing" screen which has been flushed to the browser. Later on I need to redirect this page, currently we use meta refresh and this normally works fine. </p> <p>With a new payment system, which includes 3D secure, we potentially end up within an iframe being directed back to our site from a third party.</p> <p>I need to be able to redirect from this page, either using javascript or meta-refresh, and bust out of the iframe if it exists.</p> <p>Cheers!</p> <p>(I have done busting out of iframes before but can't find my old code and a google search was useless, thought it was the perfect time to try Stackoverflow out!)</p>
[ { "answer_id": 271902, "author": "Ben Lynch", "author_id": 15363, "author_profile": "https://Stackoverflow.com/users/15363", "pm_score": 3, "selected": true, "text": "<p>So I added the following to my redirected pages. Luckily they have nothing posted at them so can be simply redirected. Also the use of javascript is ok as it is required to get to that point in the site.</p>\n\n<pre><code>&lt;script type=\"text/javascript\" language=\"javascript\"&gt;\n if (top.frames.length&gt;0)\n setTimeout(\"top.location = window.location;\",100);\n&lt;/script&gt;\n</code></pre>\n" }, { "answer_id": 272218, "author": "Adam Tuttle", "author_id": 751, "author_profile": "https://Stackoverflow.com/users/751", "pm_score": 0, "selected": false, "text": "<p>I'm doing something similar to keep an old site inside it's frameset:</p>\n\n<pre><code>&lt;SCRIPT TYPE=\"text/JavaScript\"&gt;\n if (window == top){top.location.replace(\"/foo.html\");}\n&lt;/SCRIPT&gt;\n</code></pre>\n\n<p>So to break out of the iframe, just change == to !=</p>\n\n<p>I see that you're using setTimeout in your example. Is waiting to break out of the iframe a requirement, or would you rather it happen immediately?</p>\n" }, { "answer_id": 11338554, "author": "Devaroop", "author_id": 909297, "author_profile": "https://Stackoverflow.com/users/909297", "pm_score": 0, "selected": false, "text": "<p>if you are using javascript:</p>\n\n<pre><code>parent.document.location = \"http://www.google.com\"\n</code></pre>\n\n<p>and if you are using html:</p>\n\n<pre><code>&lt;a href=\"http://www.google.com\" target=_top &gt;Google&lt;/a&gt;\n</code></pre>\n" } ]
2008/11/07
[ "https://Stackoverflow.com/questions/271706", "https://Stackoverflow.com", "https://Stackoverflow.com/users/15363/" ]
I basically have a page which shows a "processing" screen which has been flushed to the browser. Later on I need to redirect this page, currently we use meta refresh and this normally works fine. With a new payment system, which includes 3D secure, we potentially end up within an iframe being directed back to our site from a third party. I need to be able to redirect from this page, either using javascript or meta-refresh, and bust out of the iframe if it exists. Cheers! (I have done busting out of iframes before but can't find my old code and a google search was useless, thought it was the perfect time to try Stackoverflow out!)
So I added the following to my redirected pages. Luckily they have nothing posted at them so can be simply redirected. Also the use of javascript is ok as it is required to get to that point in the site. ``` <script type="text/javascript" language="javascript"> if (top.frames.length>0) setTimeout("top.location = window.location;",100); </script> ```
271,710
<p>The code looks like below:</p> <pre><code>namespace Test { public interface IMyClass { List&lt;IMyClass&gt; GetList(); } public class MyClass : IMyClass { public List&lt;IMyClass&gt; GetList() { return new List&lt;IMyClass&gt;(); } } } </code></pre> <p>When I Run Code Analysis i get the following recommendation.</p> <blockquote> <p>Warning 3 CA1002 : Microsoft.Design : Change 'List' in 'IMyClass.GetList()' to use Collection, ReadOnlyCollection or KeyedCollection</p> </blockquote> <p>How should I fix this and what is good practice here?</p>
[ { "answer_id": 271711, "author": "Jon Skeet", "author_id": 22656, "author_profile": "https://Stackoverflow.com/users/22656", "pm_score": 6, "selected": false, "text": "<p>I would personally declare it to return an interface rather than a concrete collection. If you really want list access, use <a href=\"http://msdn.microsoft.com/en-us/library/5y536ey6.aspx\" rel=\"noreferrer\"><code>IList&lt;T&gt;</code></a>. Otherwise, consider <a href=\"http://msdn.microsoft.com/en-us/library/92t2ye13.aspx\" rel=\"noreferrer\"><code>ICollection&lt;T&gt;</code></a> and <a href=\"http://msdn.microsoft.com/en-us/library/9eekhta0.aspx\" rel=\"noreferrer\"><code>IEnumerable&lt;T&gt;</code></a>.</p>\n" }, { "answer_id": 271719, "author": "Tamas Czinege", "author_id": 8954, "author_profile": "https://Stackoverflow.com/users/8954", "pm_score": -1, "selected": false, "text": "<p>Well the Collection class is really just a wrapper class around other collections to hide their implementation details and other features. I reckon this has something to do with the property hiding coding pattern in object-oriented languages.</p>\n\n<p>I think you shouldn't worry about it, but if you really want to please the code analysis tool, just do the following:</p>\n\n<pre><code>//using System.Collections.ObjectModel;\n\nCollection&lt;MyClass&gt; myCollection = new Collection&lt;MyClass&gt;(myList);\n</code></pre>\n" }, { "answer_id": 271726, "author": "Timothy Khouri", "author_id": 11917, "author_profile": "https://Stackoverflow.com/users/11917", "pm_score": 3, "selected": false, "text": "<p>I don't think anyone has answered the \"why\" part yet... so here goes. The reason \"why\" you \"should\" use a <code>Collection&lt;T&gt;</code> instead of a <code>List&lt;T&gt;</code> is because if you expose a <code>List&lt;T&gt;</code>, then anyone who gets access to your object can modify the items in the list. Whereas <code>Collection&lt;T&gt;</code> is supposed to indicate that you are making your own \"Add\", \"Remove\", etc methods.</p>\n\n<p>You likely don't need to worry about it, because you're probably coding the interface for yourself only (or maybe a few collegues). Here's another example that might make sense.</p>\n\n<p>If you have a public array, ex:</p>\n\n<pre><code>public int[] MyIntegers { get; }\n</code></pre>\n\n<p>You would think that because there is only a \"get\" accessor that no-one can mess with the values, but that's not true. Anyone can change the values inside there just like this:</p>\n\n<pre><code>someObject.MyIngegers[3] = 12345;\n</code></pre>\n\n<p>Personally, I would just use <code>List&lt;T&gt;</code> in most cases. But if you are designing a class library that you are going to give out to random developers, and you need to rely on the state of the objects... then you'll want to make your own Collection and lock it down from there :)</p>\n" }, { "answer_id": 271781, "author": "chakrit", "author_id": 3055, "author_profile": "https://Stackoverflow.com/users/3055", "pm_score": 2, "selected": false, "text": "<p>It's mostly about abstracting your own implementations away instead of exposing the List object to be manipulated directly.</p>\n\n<p>It's not good practice to let other objects (or people) modify the state of your objects directly. Think property getters/setters.</p>\n\n<p>Collection -> For normal collection<br>\nReadOnlyCollection -> For collections that shouldn't be modified<br>\nKeyedCollection -> When you want dictionaries instead.</p>\n\n<p>How to fix it depends on what you want your class to do and the purpose of the GetList() method. Can you elaborate?</p>\n" }, { "answer_id": 271786, "author": "Harald Scheirich", "author_id": 22080, "author_profile": "https://Stackoverflow.com/users/22080", "pm_score": 1, "selected": false, "text": "<p>In these kind of case I usually try to expose the least amount of implemententation that is needed. If the consumers do not need to know that you are actually using a list then you don't need to return a list. By returning as Microsoft suggests a Collection you hide the fact that you are using a list from the consumers of your class and isolate them against an internal change. </p>\n" }, { "answer_id": 271842, "author": "Greg Beech", "author_id": 13552, "author_profile": "https://Stackoverflow.com/users/13552", "pm_score": 9, "selected": true, "text": "<p>To answer the \"why\" part of the question as to why not <a href=\"https://learn.microsoft.com/en-us/dotnet/api/system.collections.generic.list-1\" rel=\"noreferrer\"><code>List&lt;T&gt;</code></a>, The reasons are future-proofing and API simplicity.</p>\n\n<p><strong>Future-proofing</strong></p>\n\n<p><a href=\"https://learn.microsoft.com/en-us/dotnet/api/system.collections.generic.list-1\" rel=\"noreferrer\"><code>List&lt;T&gt;</code></a> is not designed to be easily extensible by subclassing it; it is designed to be fast for internal implementations. You'll notice the methods on it are not virtual and so cannot be overridden, and there are no hooks into its <a href=\"https://learn.microsoft.com/en-us/dotnet/api/system.collections.generic.list-1.add\" rel=\"noreferrer\"><code>Add</code></a>/<a href=\"https://learn.microsoft.com/en-us/dotnet/api/system.collections.generic.list-1.insert\" rel=\"noreferrer\"><code>Insert</code></a>/<a href=\"https://learn.microsoft.com/en-us/dotnet/api/system.collections.generic.list-1.remove\" rel=\"noreferrer\"><code>Remove</code></a> operations. </p>\n\n<p>This means that if you need to alter the behavior of the collection in the future (e.g. to reject null objects that people try to add, or to perform additional work when this happens such as updating your class state) then you need to change the type of collection you return to one you can subclass, which will be a breaking interface change (of course changing the semantics of things like not allowing null may also be an interface change, but things like updating your internal class state would not be).</p>\n\n<p>So by returning either a class that can be easily subclassed such as <a href=\"https://learn.microsoft.com/en-us/dotnet/api/system.collections.objectmodel.collection-1\" rel=\"noreferrer\"><code>Collection&lt;T&gt;</code></a> or an interface such as <a href=\"https://learn.microsoft.com/en-us/dotnet/api/system.collections.generic.ilist-1\" rel=\"noreferrer\"><code>IList&lt;T&gt;</code></a>, <a href=\"https://learn.microsoft.com/en-us/dotnet/api/system.collections.generic.icollection-1\" rel=\"noreferrer\"><code>ICollection&lt;T&gt;</code></a> or <a href=\"https://learn.microsoft.com/en-us/dotnet/api/system.collections.generic.ienumerable-1\" rel=\"noreferrer\"><code>IEnumerable&lt;T&gt;</code></a> you can change your internal implementation to be a different collection type to meet your needs, without breaking the code of consumers because it can still be returned as the type they are expecting.</p>\n\n<p><strong>API Simplicity</strong></p>\n\n<p><a href=\"https://learn.microsoft.com/en-us/dotnet/api/system.collections.generic.list-1\" rel=\"noreferrer\"><code>List&lt;T&gt;</code></a> contains a lot of useful operations such as <a href=\"https://learn.microsoft.com/en-us/dotnet/api/system.collections.generic.list-1.binarysearch\" rel=\"noreferrer\"><code>BinarySearch</code></a>, <a href=\"https://learn.microsoft.com/en-us/dotnet/api/system.collections.generic.list-1.sort\" rel=\"noreferrer\"><code>Sort</code></a> and so on. However if this is a collection you are exposing then it is likely that you control the semantics of the list, and not the consumers. So while your class internally may need these operations it is very unlikely that consumers of your class would want to (or even should) call them.</p>\n\n<p>As such, by offering a simpler collection class or interface, you reduce the number of members that users of your API see, and make it easier for them to use.</p>\n" }, { "answer_id": 8859865, "author": "Konstantin Isaev", "author_id": 1026676, "author_profile": "https://Stackoverflow.com/users/1026676", "pm_score": 0, "selected": false, "text": "<p>I don't see any problem with returning something like </p>\n\n<pre><code>this.InternalData.Filter(crteria).ToList();\n</code></pre>\n\n<p>If I returned a disconnected <em>copy</em> of internal data, or detached result of a data query - I can safely return <code>List&lt;TItem&gt;</code> without exposing any of implementation details, and allow to use the returned data in the convenient way.</p>\n\n<p>But this depends on what type of consumer I expect - if this is a something like data grid I prefer to return <code>IEnumerable&lt;TItem&gt;</code> <em>which will be the copied list of items</em> anyway in most cases :)</p>\n" }, { "answer_id": 33654749, "author": "NullReference", "author_id": 2170850, "author_profile": "https://Stackoverflow.com/users/2170850", "pm_score": 1, "selected": false, "text": "<p>Something to add though it's been a long time since this was asked.</p>\n\n<p>When your list type derives from <code>List&lt;T&gt;</code> instead of <code>Collection&lt;T&gt;</code>, you cannot implement the protected virtual methods that <code>Collection&lt;T&gt;</code> implements.\nWhat this means is that you derived type cannot respond in case any modifications are made to the list. This is because <code>List&lt;T&gt;</code> assumes you are aware when you add or remove items. Being able to response to notifications is an overhead and hence <code>List&lt;T&gt;</code> doesn't offer it.</p>\n\n<p>In cases when external code has access to your collection, you may not be in control of when an item is being added or removed. Therefore <code>Collection&lt;T&gt;</code> provides a way to know when your list was modified.</p>\n" } ]
2008/11/07
[ "https://Stackoverflow.com/questions/271710", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11135/" ]
The code looks like below: ``` namespace Test { public interface IMyClass { List<IMyClass> GetList(); } public class MyClass : IMyClass { public List<IMyClass> GetList() { return new List<IMyClass>(); } } } ``` When I Run Code Analysis i get the following recommendation. > > Warning 3 CA1002 : Microsoft.Design : Change 'List' in 'IMyClass.GetList()' to use Collection, ReadOnlyCollection or KeyedCollection > > > How should I fix this and what is good practice here?
To answer the "why" part of the question as to why not [`List<T>`](https://learn.microsoft.com/en-us/dotnet/api/system.collections.generic.list-1), The reasons are future-proofing and API simplicity. **Future-proofing** [`List<T>`](https://learn.microsoft.com/en-us/dotnet/api/system.collections.generic.list-1) is not designed to be easily extensible by subclassing it; it is designed to be fast for internal implementations. You'll notice the methods on it are not virtual and so cannot be overridden, and there are no hooks into its [`Add`](https://learn.microsoft.com/en-us/dotnet/api/system.collections.generic.list-1.add)/[`Insert`](https://learn.microsoft.com/en-us/dotnet/api/system.collections.generic.list-1.insert)/[`Remove`](https://learn.microsoft.com/en-us/dotnet/api/system.collections.generic.list-1.remove) operations. This means that if you need to alter the behavior of the collection in the future (e.g. to reject null objects that people try to add, or to perform additional work when this happens such as updating your class state) then you need to change the type of collection you return to one you can subclass, which will be a breaking interface change (of course changing the semantics of things like not allowing null may also be an interface change, but things like updating your internal class state would not be). So by returning either a class that can be easily subclassed such as [`Collection<T>`](https://learn.microsoft.com/en-us/dotnet/api/system.collections.objectmodel.collection-1) or an interface such as [`IList<T>`](https://learn.microsoft.com/en-us/dotnet/api/system.collections.generic.ilist-1), [`ICollection<T>`](https://learn.microsoft.com/en-us/dotnet/api/system.collections.generic.icollection-1) or [`IEnumerable<T>`](https://learn.microsoft.com/en-us/dotnet/api/system.collections.generic.ienumerable-1) you can change your internal implementation to be a different collection type to meet your needs, without breaking the code of consumers because it can still be returned as the type they are expecting. **API Simplicity** [`List<T>`](https://learn.microsoft.com/en-us/dotnet/api/system.collections.generic.list-1) contains a lot of useful operations such as [`BinarySearch`](https://learn.microsoft.com/en-us/dotnet/api/system.collections.generic.list-1.binarysearch), [`Sort`](https://learn.microsoft.com/en-us/dotnet/api/system.collections.generic.list-1.sort) and so on. However if this is a collection you are exposing then it is likely that you control the semantics of the list, and not the consumers. So while your class internally may need these operations it is very unlikely that consumers of your class would want to (or even should) call them. As such, by offering a simpler collection class or interface, you reduce the number of members that users of your API see, and make it easier for them to use.
271,718
<p>In a detailsview, how can I prepopulate one of the textboxes on the insertcommand (When the user clicks insert and the view is insert).</p> <p>I think this would work for codebehind:</p> <p>Dim txtBox As TextBox = FormView1.FindControl("txtbox")</p> <p>txtbox.Text = "Whatever I want"</p> <p>Is this right? What do I need in the aspx (not as sure)? Also, I'm assuming the server-side code will go in the itemcommand or insertcreating event.</p> <p>I have typed this in VB.NET but I am using C# (I can do both so on a language agnostic forum I might type the problem in another language). I am also using a SqlDataSource, with my parameters and insert/delete/edit commands all created.</p> <p>I am trying to generate a random GUID (using the GUID object), which will be prepopulated in the textbox.</p> <p>Also, is the postbackurl property of a button not another way of preserving form state?</p> <p>Thanks</p>
[ { "answer_id": 277797, "author": "Alexander Taran", "author_id": 35954, "author_profile": "https://Stackoverflow.com/users/35954", "pm_score": 0, "selected": false, "text": "<p>I'm guessing you need to use one of detailsview events.\nHook up to ItemCommand, ModeChanging or ModeChanged events and fill your value there.</p>\n" }, { "answer_id": 684039, "author": "Anthony K", "author_id": 1682, "author_profile": "https://Stackoverflow.com/users/1682", "pm_score": 0, "selected": false, "text": "<p>I am doing something like this as well. I am hiding the DetailsView and showing it when the user clicks a button.</p>\n\n<pre><code>dvDetails.ChangeMode(DetailsViewMode.Insert)\npnlDetailMenu.Visible = True\nDim ColumnTextBox As TextBox\nColumnTextBox = dvDetails.Rows(0).Cells(1).Controls(0)\nIf Not ColumnTextBox Is Nothing Then\n ColumnTextBox.Text = \"Initial Value\"\nEnd If\n</code></pre>\n" }, { "answer_id": 696436, "author": "Mark Glorie", "author_id": 952, "author_profile": "https://Stackoverflow.com/users/952", "pm_score": 1, "selected": false, "text": "<p>I would update the field in the DetailsView to a TemplateField: </p>\n\n<pre><code>&lt;asp:TemplateField&gt;\n &lt;InsertItemTemplate&gt;\n &lt;asp:TextBox ID=\"txtField\" runat=\"server\" Text='&lt;%# Bind(\"GUID\") %&gt;'/&gt;\n &lt;/InsertItemTemplate&gt;\n &lt;ItemTemplate&gt;\n &lt;asp:Label ID=\"lblField\" runat=\"server\" Text='&lt;%# Bind(\"GUID\") %&gt;'/&gt;\n &lt;/ItemTemplate&gt;\n&lt;/asp:TemplateField&gt;\n</code></pre>\n\n<p>Then you have two options: </p>\n\n<ul>\n<li>generate your GUID and insert into\nyour datasource. This may have to be done with SQL since you mentioned using SqlDataSource</li>\n<li><p>remove the binding and access the controls from code in the\nDataBound event of your DetailsView </p>\n\n<pre><code>Private Sub dv_DataBound(ByVal sender As Object, ByVal e As EventArgs) Handles dv.DataBound\n dim txt as Textbox = dv.FindControl(\"txtField\")\n txt.Text = GenerateGUID()\nEnd Sub\n</code></pre></li>\n</ul>\n" } ]
2008/11/07
[ "https://Stackoverflow.com/questions/271718", "https://Stackoverflow.com", "https://Stackoverflow.com/users/32484/" ]
In a detailsview, how can I prepopulate one of the textboxes on the insertcommand (When the user clicks insert and the view is insert). I think this would work for codebehind: Dim txtBox As TextBox = FormView1.FindControl("txtbox") txtbox.Text = "Whatever I want" Is this right? What do I need in the aspx (not as sure)? Also, I'm assuming the server-side code will go in the itemcommand or insertcreating event. I have typed this in VB.NET but I am using C# (I can do both so on a language agnostic forum I might type the problem in another language). I am also using a SqlDataSource, with my parameters and insert/delete/edit commands all created. I am trying to generate a random GUID (using the GUID object), which will be prepopulated in the textbox. Also, is the postbackurl property of a button not another way of preserving form state? Thanks
I would update the field in the DetailsView to a TemplateField: ``` <asp:TemplateField> <InsertItemTemplate> <asp:TextBox ID="txtField" runat="server" Text='<%# Bind("GUID") %>'/> </InsertItemTemplate> <ItemTemplate> <asp:Label ID="lblField" runat="server" Text='<%# Bind("GUID") %>'/> </ItemTemplate> </asp:TemplateField> ``` Then you have two options: * generate your GUID and insert into your datasource. This may have to be done with SQL since you mentioned using SqlDataSource * remove the binding and access the controls from code in the DataBound event of your DetailsView ``` Private Sub dv_DataBound(ByVal sender As Object, ByVal e As EventArgs) Handles dv.DataBound dim txt as Textbox = dv.FindControl("txtField") txt.Text = GenerateGUID() End Sub ```
271,724
<p>I am playing around with ASP.NET MVC for the first time, so I apologize in advance if this sounds academic. </p> <p>I have created a simple content management system using ASP.NET MVC. The url to retrieve a list of content, in this case, announcements, looks like:</p> <pre><code>http://www.mydomain.com/announcements/list/10 </code></pre> <p>This will return the top ten most recent announcements.</p> <p>My questions are as follows:</p> <ol> <li><p>Is it possible for any website to consume this service? Or would I also have to expose it using something like WCF?</p></li> <li><p>What are some examples, of how to consume this service to display this data on another website? I'm primarily programming in the .NET world, but I'm thinking if I could consume the service using javascript, or do something with Json, it could really work for any technology.</p></li> </ol> <p>I am looking to dynamically generate something like the following output:</p> <pre><code>&lt;div class="announcement"&gt; &lt;h1&gt;Title&lt;/h1&gt; &lt;h2&gt;Posted Date&lt;/h3&gt; &lt;p&gt;Teaser&lt;/p&gt; &lt;a href="www.someotherdomain.com"&gt;More&lt;/a&gt; &lt;/div&gt; </code></pre> <hr> <p>For now ... is it possible to return an Html representation and display it in a webpage? Is this possible using just Javascript?</p>
[ { "answer_id": 277797, "author": "Alexander Taran", "author_id": 35954, "author_profile": "https://Stackoverflow.com/users/35954", "pm_score": 0, "selected": false, "text": "<p>I'm guessing you need to use one of detailsview events.\nHook up to ItemCommand, ModeChanging or ModeChanged events and fill your value there.</p>\n" }, { "answer_id": 684039, "author": "Anthony K", "author_id": 1682, "author_profile": "https://Stackoverflow.com/users/1682", "pm_score": 0, "selected": false, "text": "<p>I am doing something like this as well. I am hiding the DetailsView and showing it when the user clicks a button.</p>\n\n<pre><code>dvDetails.ChangeMode(DetailsViewMode.Insert)\npnlDetailMenu.Visible = True\nDim ColumnTextBox As TextBox\nColumnTextBox = dvDetails.Rows(0).Cells(1).Controls(0)\nIf Not ColumnTextBox Is Nothing Then\n ColumnTextBox.Text = \"Initial Value\"\nEnd If\n</code></pre>\n" }, { "answer_id": 696436, "author": "Mark Glorie", "author_id": 952, "author_profile": "https://Stackoverflow.com/users/952", "pm_score": 1, "selected": false, "text": "<p>I would update the field in the DetailsView to a TemplateField: </p>\n\n<pre><code>&lt;asp:TemplateField&gt;\n &lt;InsertItemTemplate&gt;\n &lt;asp:TextBox ID=\"txtField\" runat=\"server\" Text='&lt;%# Bind(\"GUID\") %&gt;'/&gt;\n &lt;/InsertItemTemplate&gt;\n &lt;ItemTemplate&gt;\n &lt;asp:Label ID=\"lblField\" runat=\"server\" Text='&lt;%# Bind(\"GUID\") %&gt;'/&gt;\n &lt;/ItemTemplate&gt;\n&lt;/asp:TemplateField&gt;\n</code></pre>\n\n<p>Then you have two options: </p>\n\n<ul>\n<li>generate your GUID and insert into\nyour datasource. This may have to be done with SQL since you mentioned using SqlDataSource</li>\n<li><p>remove the binding and access the controls from code in the\nDataBound event of your DetailsView </p>\n\n<pre><code>Private Sub dv_DataBound(ByVal sender As Object, ByVal e As EventArgs) Handles dv.DataBound\n dim txt as Textbox = dv.FindControl(\"txtField\")\n txt.Text = GenerateGUID()\nEnd Sub\n</code></pre></li>\n</ul>\n" } ]
2008/11/07
[ "https://Stackoverflow.com/questions/271724", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1768/" ]
I am playing around with ASP.NET MVC for the first time, so I apologize in advance if this sounds academic. I have created a simple content management system using ASP.NET MVC. The url to retrieve a list of content, in this case, announcements, looks like: ``` http://www.mydomain.com/announcements/list/10 ``` This will return the top ten most recent announcements. My questions are as follows: 1. Is it possible for any website to consume this service? Or would I also have to expose it using something like WCF? 2. What are some examples, of how to consume this service to display this data on another website? I'm primarily programming in the .NET world, but I'm thinking if I could consume the service using javascript, or do something with Json, it could really work for any technology. I am looking to dynamically generate something like the following output: ``` <div class="announcement"> <h1>Title</h1> <h2>Posted Date</h3> <p>Teaser</p> <a href="www.someotherdomain.com">More</a> </div> ``` --- For now ... is it possible to return an Html representation and display it in a webpage? Is this possible using just Javascript?
I would update the field in the DetailsView to a TemplateField: ``` <asp:TemplateField> <InsertItemTemplate> <asp:TextBox ID="txtField" runat="server" Text='<%# Bind("GUID") %>'/> </InsertItemTemplate> <ItemTemplate> <asp:Label ID="lblField" runat="server" Text='<%# Bind("GUID") %>'/> </ItemTemplate> </asp:TemplateField> ``` Then you have two options: * generate your GUID and insert into your datasource. This may have to be done with SQL since you mentioned using SqlDataSource * remove the binding and access the controls from code in the DataBound event of your DetailsView ``` Private Sub dv_DataBound(ByVal sender As Object, ByVal e As EventArgs) Handles dv.DataBound dim txt as Textbox = dv.FindControl("txtField") txt.Text = GenerateGUID() End Sub ```
271,730
<p>I run a website where users can post items (e.g. pictures). The items are stored in a MySQL database. </p> <p>I want to query for the last ten posted items BUT with the constraint of a maximum of 3 items can come from any single user. </p> <p>What is the best way of doing it? My preferred solution is a constraint that is put on the SQL query requesting the last ten items. But ideas on how to set up the database design is very welcome.</p> <p>Thanks in advance!</p> <p>BR</p>
[ { "answer_id": 271768, "author": "Tomalak", "author_id": 18771, "author_profile": "https://Stackoverflow.com/users/18771", "pm_score": 2, "selected": false, "text": "<p>This is difficult because MySQL does not support the LIMIT clause on sub-queries. If it did, this would be rather trivial... But alas, here is my naïve approach:</p>\n\n<pre><code>SELECT\n i.UserId,\n i.ImageId\nFROM\n UserSuppliedImages i\nWHERE\n /* second valid ImageId */\n ImageId = (\n SELECT MAX(ImageId)\n FROM UserSuppliedImages\n WHERE UserId = i.UserId\n )\n OR\n /* second valid ImageId */\n ImageId = (\n SELECT MAX(ImageId)\n FROM UserSuppliedImages\n WHERE UserId = i.UserId\n AND ImageId &lt; (\n SELECT MAX(ImageId)\n FROM UserSuppliedImages\n WHERE UserId = i.UserId\n )\n )\n /* you get the picture... \n the more \"per user\" images you want, the more complex this will get */\nLIMIT 10;\n</code></pre>\n\n<p>You did not comment on having a preferred result order, so this selects the latest images (assuming <code>ImageId</code> is an ascending auto-incrementing value).</p>\n\n<p>For comparison, on SQL Server the same would look like this:</p>\n\n<pre><code>SELECT TOP 10\n img.ImageId,\n img.ImagePath,\n img.UserId\nFROM\n UserSuppliedImages img\nWHERE\n ImageId IN (\n SELECT TOP 3 ImageId\n FROM UserSuppliedImages \n WHERE UserId = img.UserId\n )\n</code></pre>\n" }, { "answer_id": 271782, "author": "jishi", "author_id": 33663, "author_profile": "https://Stackoverflow.com/users/33663", "pm_score": 1, "selected": false, "text": "<p>I would first select 10 distinct users, then selecting images from each of those users with a LIMIT 3, possibly by a union of all those and limit that to 10.</p>\n\n<p>That would atleast narrow down the data you need to process to a fair amount.</p>\n" }, { "answer_id": 271996, "author": "Incidently", "author_id": 34187, "author_profile": "https://Stackoverflow.com/users/34187", "pm_score": 4, "selected": true, "text": "<p>It's pretty easy with a correlated sub-query:</p>\n\n<pre><code>SELECT `img`.`id` , `img`.`userid`\nFROM `img`\nWHERE 3 &gt; (\nSELECT count( * )\nFROM `img` AS `img1`\nWHERE `img`.`userid` = `img1`.`userid`\nAND `img`.`id` &gt; `img1`.`id` )\nORDER BY `img`.`id` DESC\nLIMIT 10 \n</code></pre>\n\n<p>The query assumes that larger <code>id</code> means added later</p>\n\n<p>Correlated sub-queries are a powerful tool! :-)</p>\n" } ]
2008/11/07
[ "https://Stackoverflow.com/questions/271730", "https://Stackoverflow.com", "https://Stackoverflow.com/users/103373/" ]
I run a website where users can post items (e.g. pictures). The items are stored in a MySQL database. I want to query for the last ten posted items BUT with the constraint of a maximum of 3 items can come from any single user. What is the best way of doing it? My preferred solution is a constraint that is put on the SQL query requesting the last ten items. But ideas on how to set up the database design is very welcome. Thanks in advance! BR
It's pretty easy with a correlated sub-query: ``` SELECT `img`.`id` , `img`.`userid` FROM `img` WHERE 3 > ( SELECT count( * ) FROM `img` AS `img1` WHERE `img`.`userid` = `img1`.`userid` AND `img`.`id` > `img1`.`id` ) ORDER BY `img`.`id` DESC LIMIT 10 ``` The query assumes that larger `id` means added later Correlated sub-queries are a powerful tool! :-)
271,741
<p>I'm trying to parse a html page and extract 2 values from a table row. The html for the table row is as follows: -</p> <pre><code>&lt;tr&gt; &lt;td title="Associated temperature in (ºC)" class="TABLEDATACELL" nowrap="nowrap" align="Left" colspan="1" rowspan="1"&gt;Max Temperature (ºC)&lt;/td&gt; &lt;td class="TABLEDATACELLNOTT" nowrap="nowrap" align="Center" colspan="1" rowspan="1"&gt;6&lt;/td&gt; &lt;td class="TABLEDATACELLNOTT" nowrap="nowrap" align="Center" colspan="1" rowspan="1"&gt; 13:41:30&lt;/td&gt; &lt;/tr&gt; </code></pre> <p>and the expression I have at the moment is:</p> <pre><code>&lt;tr&gt;[\s]&lt;td[^&lt;]+?&gt;Max Temperature[\w\s]*&lt;/td&gt;[\s] &lt;td[^&lt;]+?&gt;(?&lt;value&gt;([\d]+))&lt;/td&gt;[\s] &lt;td[^&lt;]+?&gt;(?&lt;time&gt;([\d\:]+))&lt;/td&gt;[\s]&lt;/tr&gt; </code></pre> <p>However I don't seem to be able to extract any matches. Could anyone point me in the right direction, thanks.</p>
[ { "answer_id": 271748, "author": "siukurnin", "author_id": 35273, "author_profile": "https://Stackoverflow.com/users/35273", "pm_score": 0, "selected": false, "text": "<p>When you write <code>&lt;td[^&lt;]+?&gt;</code> I guess you really mean <code>&lt;td[^&gt;]*&gt;</code></p>\n\n<p>That is \"opening brace, td, maybe stuff other than <em>closing</em> brace...\"</p>\n" }, { "answer_id": 271750, "author": "The Archetypal Paul", "author_id": 21755, "author_profile": "https://Stackoverflow.com/users/21755", "pm_score": 0, "selected": false, "text": "<pre><code>&lt;tr&gt;[\\s]&lt;td[^&lt;]+?&gt;Max Temperature[\\w\\s]*&lt;/td&gt;[\\s]\n</code></pre>\n\n<p>Not looked at it all yet, but that [^&lt;] probably needs to be [^>] as you're trying to match all non-> until the > that's before Max temperature.</p>\n" }, { "answer_id": 271751, "author": "Stefan Gehrig", "author_id": 11354, "author_profile": "https://Stackoverflow.com/users/11354", "pm_score": 2, "selected": true, "text": "<p>Try </p>\n\n<pre><code>&lt;tr&gt;\\s*\n&lt;td[^&gt;]*&gt;.*?&lt;/td&gt;\\s*\n&lt;td[^&gt;]*&gt;\\s*(?&lt;value&gt;\\d+)\\s*&lt;/td&gt;\\s*\n&lt;td[^&gt;]*&gt;\\s*(?&lt;time&gt;\\d{2}:\\d{2}:\\d{2})\\s*&lt;/td&gt;\\s*\n&lt;/tr&gt;\\s*\n</code></pre>\n" }, { "answer_id": 271754, "author": "chakrit", "author_id": 3055, "author_profile": "https://Stackoverflow.com/users/3055", "pm_score": 0, "selected": false, "text": "<p>The \" (ºC)\" before the closing td was matched against:</p>\n\n<pre><code>&lt;tr&gt;[\\s]&lt;td[^&lt;]+?&gt;Max Temperature[^&lt;]*&lt;/td&gt;[\\s]\n</code></pre>\n\n<p>Is that \\w a word-boundary? I think that it gets a little tricky there, I'd use a more general approach.</p>\n\n<p>And on the third line, there is one whitespace after the td tag, is that accounted for?</p>\n\n<pre><code>&lt;td[^&lt;]+?&gt;[\\s]?(?&lt;time&gt;([\\d\\:]+))&lt;/td&gt;[\\s]&lt;/tr&gt;\n</code></pre>\n" }, { "answer_id": 271757, "author": "Bjarke Ebert", "author_id": 31890, "author_profile": "https://Stackoverflow.com/users/31890", "pm_score": 2, "selected": false, "text": "<p>Parsing HTML reliably using regexp is known to be notoriously difficult. </p>\n\n<p>I think I would be looking for a HTML parsing library, or a \"screen scraping\" library ;)</p>\n\n<p>If the HTML comes from an unreliable source, you have to be extra careful to handle malicious HTML syntax well. Bad HTML handling is a major source of security attacks.</p>\n" }, { "answer_id": 271771, "author": "yusuf", "author_id": 35012, "author_profile": "https://Stackoverflow.com/users/35012", "pm_score": 0, "selected": false, "text": "<p>I use <a href=\"http://www.regexbuddy.com/\" rel=\"nofollow noreferrer\">http://www.regexbuddy.com/</a> for such controls. \nSo far I tested @sgehrig's suggestion is correct </p>\n" }, { "answer_id": 5204827, "author": "TrueWill", "author_id": 161457, "author_profile": "https://Stackoverflow.com/users/161457", "pm_score": 0, "selected": false, "text": "<p>Use the <a href=\"http://htmlagilitypack.codeplex.com/\" rel=\"nofollow\">Html Agility Pack</a> or a similar library instead, as @Bjarke Ebert suggests. It's the right tool for the task.</p>\n" } ]
2008/11/07
[ "https://Stackoverflow.com/questions/271741", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
I'm trying to parse a html page and extract 2 values from a table row. The html for the table row is as follows: - ``` <tr> <td title="Associated temperature in (ºC)" class="TABLEDATACELL" nowrap="nowrap" align="Left" colspan="1" rowspan="1">Max Temperature (ºC)</td> <td class="TABLEDATACELLNOTT" nowrap="nowrap" align="Center" colspan="1" rowspan="1">6</td> <td class="TABLEDATACELLNOTT" nowrap="nowrap" align="Center" colspan="1" rowspan="1"> 13:41:30</td> </tr> ``` and the expression I have at the moment is: ``` <tr>[\s]<td[^<]+?>Max Temperature[\w\s]*</td>[\s] <td[^<]+?>(?<value>([\d]+))</td>[\s] <td[^<]+?>(?<time>([\d\:]+))</td>[\s]</tr> ``` However I don't seem to be able to extract any matches. Could anyone point me in the right direction, thanks.
Try ``` <tr>\s* <td[^>]*>.*?</td>\s* <td[^>]*>\s*(?<value>\d+)\s*</td>\s* <td[^>]*>\s*(?<time>\d{2}:\d{2}:\d{2})\s*</td>\s* </tr>\s* ```
271,742
<p>What are the advantages of rendering a control like this:</p> <pre><code>&lt;% Html.RenderPartial("MyControl") %&gt; or &lt;%=Html.TextBox("txtName", Model.Name) %&gt; </code></pre> <p>over the web Forms style:</p> <pre><code>&lt;uc1:MyControl ID=MyControl runat=server /&gt; </code></pre> <p>I understand that performance can be one reason because no object needs to be created but having the possibility of calling it from the codebehing just to do some basic rendering logic can be very useful. </p> <p>If this is discouraged then how you are suposed to deal with this scenarios:</p> <ul> <li><p>You need to make the control visible conditionally and you dont want to fill your HTML with rendering logic.</p></li> <li><p>You have <code>&lt;input type="text" value="&lt;%= Model.Name %&gt;" /&gt;</code> but you need to check if Model is null because otherways a NullPointerException will raise.</p></li> </ul> <p><strong>[EDIT]</strong> I asked this when I was beginning with ASP MVC, now I see the advantages of the MVC way like in Cristian answer.</p>
[ { "answer_id": 271780, "author": "TheCodeJunkie", "author_id": 25319, "author_profile": "https://Stackoverflow.com/users/25319", "pm_score": 3, "selected": false, "text": "<p>There are a couple of reasons for this. A \"traditional\" ASP.NET WebForm control encapsulates both the Controller and View aspect of an MVC application and that would be a violation to the pattern. Also by making them extension methods you gain nice abilities such as being able to swap them out with your own implementation and to swap them out for testing</p>\n\n<p>Phil Haack (Program Manager of ASP.NET MVC) talks a bit about this when he got interviewed on the Herdering Code podcast</p>\n\n<p>Episode 24: Phil Haack on the ASP.NET MVC Beta Release (part 1)</p>\n\n<p><a href=\"http://herdingcode.com/?p=75\" rel=\"noreferrer\">http://herdingcode.com/?p=75</a></p>\n\n<p>Episode 24: Phil Haack on the ASP.NET MVC Beta Release (part 2)</p>\n\n<p><a href=\"http://herdingcode.com/?p=82\" rel=\"noreferrer\">http://herdingcode.com/?p=82</a></p>\n" }, { "answer_id": 272531, "author": "Santiago Corredoira", "author_id": 4264, "author_profile": "https://Stackoverflow.com/users/4264", "pm_score": 0, "selected": false, "text": "<p>I found <a href=\"https://stackoverflow.com/questions/108320/code-behind-in-aspnet-mvc\">this question</a> where @Matt answers:</p>\n\n<blockquote>\n <p>Does this code A) Process, store,\n retrieve, perform operations on or\n analyze the data, or B) Help to\n display the data?</p>\n \n <p>If the answer is A, it belongs in your\n controller. If the answer is B, then\n it belongs in the view.</p>\n \n <p>If B, it ultimately becomes a question\n of style. If you have some rather long\n conditional operations for trying to\n figure out if you display something to\n the user, then you might hide those\n conditional operations in the code\n behind in a Property.</p>\n</blockquote>\n\n<p>and I agree. To me it is cleaner to write in the aspx:</p>\n\n<pre><code>&lt;custom:HtmlTextBox ID=\"txtName\" runat=\"server\" /&gt;\n</code></pre>\n\n<p>and in the codebehind something like:</p>\n\n<pre><code>if(this.Model != null) \n{\n this.txtName.Text = Model.Name;\n}\n</code></pre>\n\n<p>than in the .aspx for instance:</p>\n\n<pre><code>&lt;% if(this.Model != null) { %&gt;\n &lt;input type=\"text\" name=\"txtName\" value=\"&lt;%= Model.Name %&gt;\" /&gt;\n&lt;% } else { %&gt;\n &lt;input type=\"text\" name=\"txtName\" value=\"\" /&gt;\n&lt;% } %&gt;\n</code></pre>\n\n<p>Being able to manipulate controls from the codebehind is very useful and doesn't violate the MVC pattern. Maybe I am missing something?</p>\n\n<p>Thanks!</p>\n" }, { "answer_id": 272606, "author": "Keith Williams", "author_id": 20376, "author_profile": "https://Stackoverflow.com/users/20376", "pm_score": 2, "selected": false, "text": "<p>Well for your second question, why not do:</p>\n\n<pre>\n&lt;%= Html.TextBox(\"txtName\", ((Model != null) ? Model.Name : \"\")) %&gt;\n</pre>\n\n<p>In any case, you should be checking in your controller to make sure that your Model isn't null!</p>\n" }, { "answer_id": 272737, "author": "Cristian Libardo", "author_id": 16526, "author_profile": "https://Stackoverflow.com/users/16526", "pm_score": 3, "selected": true, "text": "<p>Doing null checks in the view is probably going to cause grief in the long run. The way I interpret the MVC style of programming is to prepare the view data in the controller so that the view can be really clean and not sprincled with checks and conditions.</p>\n\n<p>On the other hand, if there is the need follow potentially null associations it's perfectly fine to put that code in a reusable helper, e.g.:</p>\n\n<pre><code>&lt;%= Html.BindTextBox(\"txtName\", Model, \"Person.Name\") %&gt;\n</code></pre>\n" }, { "answer_id": 288636, "author": "Atanas Korchev", "author_id": 10141, "author_profile": "https://Stackoverflow.com/users/10141", "pm_score": 1, "selected": false, "text": "<p>Some purists may say that having code in your view is a violation of the MVC paradigm. RenderPartial creates a fake Page object for your user control - make sure the latter does not depend on the Page object for anything.</p>\n" } ]
2008/11/07
[ "https://Stackoverflow.com/questions/271742", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4264/" ]
What are the advantages of rendering a control like this: ``` <% Html.RenderPartial("MyControl") %> or <%=Html.TextBox("txtName", Model.Name) %> ``` over the web Forms style: ``` <uc1:MyControl ID=MyControl runat=server /> ``` I understand that performance can be one reason because no object needs to be created but having the possibility of calling it from the codebehing just to do some basic rendering logic can be very useful. If this is discouraged then how you are suposed to deal with this scenarios: * You need to make the control visible conditionally and you dont want to fill your HTML with rendering logic. * You have `<input type="text" value="<%= Model.Name %>" />` but you need to check if Model is null because otherways a NullPointerException will raise. **[EDIT]** I asked this when I was beginning with ASP MVC, now I see the advantages of the MVC way like in Cristian answer.
Doing null checks in the view is probably going to cause grief in the long run. The way I interpret the MVC style of programming is to prepare the view data in the controller so that the view can be really clean and not sprincled with checks and conditions. On the other hand, if there is the need follow potentially null associations it's perfectly fine to put that code in a reusable helper, e.g.: ``` <%= Html.BindTextBox("txtName", Model, "Person.Name") %> ```
271,767
<p>I have in my Form constructor, after the InitializeComponent the following code:</p> <pre><code>using (WebClient client = new WebClient()) { client.DownloadDataCompleted += new DownloadDataCompletedEventHandler(client_DownloadDataCompleted); client.DownloadDataAsync("http://example.com/version.txt"); } </code></pre> <p>When I start my form, the UI doesn't appears till client_DownloadDataCompleted is raised. The client_DownloadDataCompleted method is empty, so there's no problem there.</p> <p>What I'm doing wrong? How is supposed to do this without freezing the UI?</p> <p>Thanks for your time.<br> Best regards.</p> <p><strong>FULL CODE:</strong> </p> <p><strong>Program.cs</strong></p> <pre><code>using System; using System.Windows.Forms; namespace Lala { static class Program { /// &lt;summary&gt; /// The main entry point for the application. /// &lt;/summary&gt; [STAThread] static void Main() { Application.EnableVisualStyles(); Application.SetCompatibleTextRenderingDefault(false); Application.Run(new Form1()); } } } </code></pre> <p><strong>Form1.cs</strong></p> <pre><code>using System; using System.Net; using System.Windows.Forms; namespace Lala { public partial class Form1 : Form { WebClient client = new WebClient(); public Form1() { client.DownloadDataCompleted += new DownloadDataCompletedEventHandler(client_DownloadDataCompleted); client.DownloadDataAsync(new Uri("http://www.google.com")); InitializeComponent(); } void client_DownloadDataCompleted(object sender, DownloadDataCompletedEventArgs e) { textBox1.Text += "A"; } } partial class Form1 { /// &lt;summary&gt; /// Required designer variable. /// &lt;/summary&gt; private System.ComponentModel.IContainer components = null; /// &lt;summary&gt; /// Clean up any resources being used. /// &lt;/summary&gt; /// &lt;param name="disposing"&gt;true if managed resources should be disposed; otherwise, false.&lt;/param&gt; protected override void Dispose(bool disposing) { if (disposing &amp;&amp; (components != null)) { components.Dispose(); } base.Dispose(disposing); } #region Windows Form Designer generated code /// &lt;summary&gt; /// Required method for Designer support - do not modify /// the contents of this method with the code editor. /// &lt;/summary&gt; private void InitializeComponent() { this.button1 = new System.Windows.Forms.Button(); this.textBox1 = new System.Windows.Forms.TextBox(); this.SuspendLayout(); // // button1 // this.button1.Location = new System.Drawing.Point(12, 12); this.button1.Name = "button1"; this.button1.Size = new System.Drawing.Size(75, 23); this.button1.TabIndex = 0; this.button1.Text = "button1"; this.button1.UseVisualStyleBackColor = true; // // textBox1 // this.textBox1.Location = new System.Drawing.Point(12, 41); this.textBox1.Multiline = true; this.textBox1.Name = "textBox1"; this.textBox1.Size = new System.Drawing.Size(468, 213); this.textBox1.TabIndex = 1; // // Form1 // this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F); this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font; this.ClientSize = new System.Drawing.Size(492, 266); this.Controls.Add(this.textBox1); this.Controls.Add(this.button1); this.Name = "Form1"; this.Text = "Form1"; this.ResumeLayout(false); this.PerformLayout(); } #endregion private System.Windows.Forms.Button button1; private System.Windows.Forms.TextBox textBox1; } } </code></pre>
[ { "answer_id": 271774, "author": "Andrew Bullock", "author_id": 28543, "author_profile": "https://Stackoverflow.com/users/28543", "pm_score": 1, "selected": false, "text": "<p>You want to run the download in a different thread, see <a href=\"http://msdn.microsoft.com/en-us/library/system.componentmodel.backgroundworker.aspx\" rel=\"nofollow noreferrer\">this</a> as a starting point.</p>\n" }, { "answer_id": 271790, "author": "Robert Wagner", "author_id": 10784, "author_profile": "https://Stackoverflow.com/users/10784", "pm_score": 0, "selected": false, "text": "<p>I've tried your code and it works fine.</p>\n\n<p>Could you post your Main(Args[]) method and the value of a and b when this is run:</p>\n\n<pre><code> int a, b;\n ThreadPool.GetMaxThreads(out a, out b);\n</code></pre>\n\n<p>I tried it in .NET 3.5 and VS2008. I'm at a loss, but I am convinced it's to do with the setup on your machine. Not the code. Check these things:</p>\n\n<ul>\n<li>Check the thread pool (above). I get a=250 b=1000</li>\n<li>Disable all third party plugins</li>\n<li>Load VS \"Clean\" (Have you rebooted)</li>\n<li>Close as many programs/services as you can</li>\n<li>Check your IE config. I think that class uses IE code/settings</li>\n<li>Firewall? AntiVirus?</li>\n<li>Try it on another computer</li>\n</ul>\n" }, { "answer_id": 271791, "author": "CVertex", "author_id": 209, "author_profile": "https://Stackoverflow.com/users/209", "pm_score": 0, "selected": false, "text": "<p>That looks a little weird to me.</p>\n\n<p>Try keeping a member ref of the WebClient so you don't destroy it in the constructor, maybe it's blocking on the client.Dispose()</p>\n" }, { "answer_id": 271795, "author": "chakrit", "author_id": 3055, "author_profile": "https://Stackoverflow.com/users/3055", "pm_score": 1, "selected": false, "text": "<p><strong>UNDELETED:</strong> As many think about the using block like I do, I've confirmed that it is <em>not</em> related.</p>\n\n<p>Can you remove the using block, I think it is waiting to dispose the webclient instance.</p>\n" }, { "answer_id": 271805, "author": "Jon Skeet", "author_id": 22656, "author_profile": "https://Stackoverflow.com/users/22656", "pm_score": 1, "selected": false, "text": "<p>I strongly suspect that it's to do with disposing of the WebClient while you're still using it for an asynchronous call.</p>\n\n<p>Try removing the using statement, and call Dispose in an event handler instead. (Or just for testing, don't worry about disposing it at all.</p>\n\n<p>If you could post a <a href=\"http://pobox.com/~skeet/csharp/complete.html\" rel=\"nofollow noreferrer\">short but complete program</a> which demonstrates the issue, that would be really handy.</p>\n" }, { "answer_id": 271810, "author": "Stephan Leclercq", "author_id": 34838, "author_profile": "https://Stackoverflow.com/users/34838", "pm_score": 0, "selected": false, "text": "<p>The using() statement is trying to call Dispose() of the WebClient while it is still downloading. The Dispose method probably waits for the download to finish before continuing.</p>\n\n<p>Try not using a using() statement and dispose of the WebClient in your DownloadDataCompleted event.</p>\n" }, { "answer_id": 271813, "author": "Will Dean", "author_id": 987, "author_profile": "https://Stackoverflow.com/users/987", "pm_score": 1, "selected": false, "text": "<p>As well as the disposing of something which is possibly still running the async call that's been mentioned by other people, I would STRONGLY recommend against doing heavyweight stuff like this in a form's constructor.</p>\n\n<p>Do it in an OnLoad override instead, where you will also be able to check the DesignMode property which will help you avoid several levels of hell with the VS forms designer.</p>\n" }, { "answer_id": 271831, "author": "chakrit", "author_id": 3055, "author_profile": "https://Stackoverflow.com/users/3055", "pm_score": 0, "selected": false, "text": "<p>I can run your code fine. And the form shows up and the download is completed AFTER the form showed up.</p>\n\n<p><strong>I do not have any freezes as you mentioned.</strong></p>\n\n<p>I think it has something to do with the environment you are running it inside.</p>\n\n<p>What version of .NET/Visual Studio are you on?</p>\n" }, { "answer_id": 271851, "author": "chakrit", "author_id": 3055, "author_profile": "https://Stackoverflow.com/users/3055", "pm_score": 0, "selected": false, "text": "<p>Ummm.... I am just curious</p>\n\n<p><strong>Do you have any Firewalls on?</strong></p>\n\n<p><em>any</em> firewalls at all on your machine?</p>\n\n<p>Maybe ZoneAlarm?</p>\n" }, { "answer_id": 271928, "author": "Jon Skeet", "author_id": 22656, "author_profile": "https://Stackoverflow.com/users/22656", "pm_score": 4, "selected": true, "text": "<p>Now that we've got full code, I can say I'm definitely not seeing the problem - not quite as described, anyway.</p>\n\n<p>I've got a bit of logging to indicate just before and after the DownloadDataAsync calls, and when the completed handler is fired. If I download a large file over 3G, there <em>is</em> a pause between \"before\" and \"after\" but the UI comes up ages before the file completes downloading.</p>\n\n<p>I have a suspicion that the <em>connect</em> is done synchronously, but the actual download is asynchronous. That's still unfortunate, of course - and possibly punting all of that into a different thread is the way to go - but if I'm right it's at least worth knowing about.</p>\n" }, { "answer_id": 322282, "author": "mbeckish", "author_id": 21727, "author_profile": "https://Stackoverflow.com/users/21727", "pm_score": 1, "selected": false, "text": "<p>DownloadDataAsync vs. DownloadData in a non-UI thread:</p>\n\n<p>DownloadDataAsync is nice because it doesn't actually tie up a thread until handling the DownloadDataCompletedEvent, after the request has been made and the server responds.</p>\n\n<p>I believe Jon Skeet is on the right track - I've read that DNS resolution must complete synchronously before the asynchronous HTTP request is queued up and the DownloadDataAsync call returns.</p>\n\n<p>Could the DNS resolution be slow?</p>\n" }, { "answer_id": 1694351, "author": "Dan", "author_id": 68473, "author_profile": "https://Stackoverflow.com/users/68473", "pm_score": 0, "selected": false, "text": "<p>In my experience, it sort-of blocks the thread when running debugging the project (running it inside Visual Studio) and when accessing the server for the first time. </p>\n\n<p>When running the compiled exe, the blocking is not perceivable.</p>\n" }, { "answer_id": 2869611, "author": "Adrian", "author_id": 345527, "author_profile": "https://Stackoverflow.com/users/345527", "pm_score": 1, "selected": false, "text": "<p>I've just tested the same thing in a WPF project under VS2010, .NET 4. </p>\n\n<p>I'm downloading a file with a progress bar to show percentage completed using WebClient.DownloadDataCompleted etc.</p>\n\n<p>And, to my amazement, I'm finding the same thing @Dan mentioned:\nWithin the debugger it blocks the thread in a funny way. In debug, my progress meter gets updated at 1%, then does nothing for a while, then updates again suddenly at 100%. (Debug.WriteLn statements print smoothly throughout). And between these two times, the UI is frozen.</p>\n\n<p>But outside the debugger, the progress bar moves smoothly from 0% to 100%, and the UI never freezes. Which is what you'd expect.</p>\n" }, { "answer_id": 5544274, "author": "Roman Pushkin", "author_id": 337085, "author_profile": "https://Stackoverflow.com/users/337085", "pm_score": 1, "selected": false, "text": "<p>try this:</p>\n\n<pre><code>client.Proxy = GlobalProxySelection.GetEmptyProxy();\n</code></pre>\n" }, { "answer_id": 22886642, "author": "Wiseman", "author_id": 125264, "author_profile": "https://Stackoverflow.com/users/125264", "pm_score": 3, "selected": false, "text": "<p>Encountered the same problem, and found a solution.\nQuite complex discussion here:\n<a href=\"http://social.msdn.microsoft.com/Forums/en-US/a00dba00-5432-450b-9904-9d343c11888d/webclient-downloadstringasync-freeze-my-ui?forum=ncl\" rel=\"noreferrer\">http://social.msdn.microsoft.com/Forums/en-US/a00dba00-5432-450b-9904-9d343c11888d/webclient-downloadstringasync-freeze-my-ui?forum=ncl</a></p>\n\n<p>In short, the problem is web client is searching for proxy servers and hanging the app.\nThe following solution helps:</p>\n\n<pre><code>WebClient webClient = new WebClient();\nwebClient.Proxy = null;\n... Do whatever else ...\n</code></pre>\n" }, { "answer_id": 41352331, "author": "Reese", "author_id": 7347412, "author_profile": "https://Stackoverflow.com/users/7347412", "pm_score": 1, "selected": false, "text": "<p>This problem is still ongoing even in VS2015. I finally figured this out, there's nothing wrong with the code people are using, the problem is actually how fast you can write data to a label control and this is what hangs up the process and causes your UI to freeze. Try replacing your labels that you reference with textboxes in your progresschanged handlers. This solved all lags in the UI for me, I hope this helps others as I spent hours trying to figure out why the code worked sometimes and not others.</p>\n" } ]
2008/11/07
[ "https://Stackoverflow.com/questions/271767", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4386/" ]
I have in my Form constructor, after the InitializeComponent the following code: ``` using (WebClient client = new WebClient()) { client.DownloadDataCompleted += new DownloadDataCompletedEventHandler(client_DownloadDataCompleted); client.DownloadDataAsync("http://example.com/version.txt"); } ``` When I start my form, the UI doesn't appears till client\_DownloadDataCompleted is raised. The client\_DownloadDataCompleted method is empty, so there's no problem there. What I'm doing wrong? How is supposed to do this without freezing the UI? Thanks for your time. Best regards. **FULL CODE:** **Program.cs** ``` using System; using System.Windows.Forms; namespace Lala { static class Program { /// <summary> /// The main entry point for the application. /// </summary> [STAThread] static void Main() { Application.EnableVisualStyles(); Application.SetCompatibleTextRenderingDefault(false); Application.Run(new Form1()); } } } ``` **Form1.cs** ``` using System; using System.Net; using System.Windows.Forms; namespace Lala { public partial class Form1 : Form { WebClient client = new WebClient(); public Form1() { client.DownloadDataCompleted += new DownloadDataCompletedEventHandler(client_DownloadDataCompleted); client.DownloadDataAsync(new Uri("http://www.google.com")); InitializeComponent(); } void client_DownloadDataCompleted(object sender, DownloadDataCompletedEventArgs e) { textBox1.Text += "A"; } } partial class Form1 { /// <summary> /// Required designer variable. /// </summary> private System.ComponentModel.IContainer components = null; /// <summary> /// Clean up any resources being used. /// </summary> /// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param> protected override void Dispose(bool disposing) { if (disposing && (components != null)) { components.Dispose(); } base.Dispose(disposing); } #region Windows Form Designer generated code /// <summary> /// Required method for Designer support - do not modify /// the contents of this method with the code editor. /// </summary> private void InitializeComponent() { this.button1 = new System.Windows.Forms.Button(); this.textBox1 = new System.Windows.Forms.TextBox(); this.SuspendLayout(); // // button1 // this.button1.Location = new System.Drawing.Point(12, 12); this.button1.Name = "button1"; this.button1.Size = new System.Drawing.Size(75, 23); this.button1.TabIndex = 0; this.button1.Text = "button1"; this.button1.UseVisualStyleBackColor = true; // // textBox1 // this.textBox1.Location = new System.Drawing.Point(12, 41); this.textBox1.Multiline = true; this.textBox1.Name = "textBox1"; this.textBox1.Size = new System.Drawing.Size(468, 213); this.textBox1.TabIndex = 1; // // Form1 // this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F); this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font; this.ClientSize = new System.Drawing.Size(492, 266); this.Controls.Add(this.textBox1); this.Controls.Add(this.button1); this.Name = "Form1"; this.Text = "Form1"; this.ResumeLayout(false); this.PerformLayout(); } #endregion private System.Windows.Forms.Button button1; private System.Windows.Forms.TextBox textBox1; } } ```
Now that we've got full code, I can say I'm definitely not seeing the problem - not quite as described, anyway. I've got a bit of logging to indicate just before and after the DownloadDataAsync calls, and when the completed handler is fired. If I download a large file over 3G, there *is* a pause between "before" and "after" but the UI comes up ages before the file completes downloading. I have a suspicion that the *connect* is done synchronously, but the actual download is asynchronous. That's still unfortunate, of course - and possibly punting all of that into a different thread is the way to go - but if I'm right it's at least worth knowing about.
271,806
<p>This is a simplification of the issue (there are lots of ways of doing things), but among applications that need to talk to a database I have usually seen one of two patterns:</p> <ol> <li>Object-Relational Mapping (ORM), where (usually) each table in the database has a corresponding "row wrapper" class with public properties that match the columns in the table. Sometimes these classes also automagically retrieve related information, so that foreign key columns can instead be exposed and displayed as the related data (rather than just the PK values).</li> <li>DataTables (and/or DataSets), where data is retrieved from the server as a DataTable and worked with in that form (even in the UI).</li> </ol> <p>One of the major differences between the two approaches is that ORM allows you to reference strongly-typed fields in your code like so:</p> <pre><code>Person bob = new Person(); bob.FirstName = "Bob"; collectionPeople.Add(bob); </code></pre> <p>whereas with the DataTable approach your code would be something like:</p> <pre><code>DataRow newrow = datatablePeople.NewRow(); newrow["FirstName"] = "Bob"; datatablePeople.Rows.Add(newrow); </code></pre> <p>In this case, the ORM approach benefits from compile-time checking while the DataTable approach does not. On the other hand, the DataTable (and the DataSet) are already-written data structures that do an excellent job of representing relational data directly, so code that uses them can usually be implemented more quickly. In addition, code that uses DataTables can be easily understood and modified by others; home-grown (and often COTS) ORM systems often do extra database access "under the hood" to populate foreign keys and so forth, which can create problems for the unaware.</p> <p>So which approach do you generally favor and why?</p>
[ { "answer_id": 271819, "author": "Andrew Bullock", "author_id": 28543, "author_profile": "https://Stackoverflow.com/users/28543", "pm_score": 0, "selected": false, "text": "<p>I used to just use a datareader to read fields onto my object using GetString, GetInt etc. but i've moved on now to a much more OO and testable approach using a Gateway to return a datatable from a query, this is then passed into a Service class which parses the table onto an object. </p>\n\n<p>I never really liked ORM tools, they were always cumbersome and difficult to maintain, but i havent had a chance to play with LINQ yet so my opinion may change.</p>\n" }, { "answer_id": 271822, "author": "Corey Trager", "author_id": 9328, "author_profile": "https://Stackoverflow.com/users/9328", "pm_score": 3, "selected": false, "text": "<p>I favor the DataTables way, because I'm old, tired, and skeptical of fashions like Subsonic and Linq. </p>\n\n<p>Beyond that, when you are working with an ORM, you are generally minimizing what you do in SQL. You don't put a lot of logic in the SQL and you don't batch up several SQL statements so as to do multiple things in one trip to the database. Therefore, you tend to go to the database more often, and that's a big performance hit.</p>\n\n<p>Using Datasets, I can do something like:</p>\n\n<p>select col1, col2... from table1<br>\nselect col1, col2... from table2<br>\nselect col1, col2... from table3 </p>\n\n<p>and then make ONE trip to the database to get all three DataSets, using Tables[0], Tables[1], Tables[2] to reference them. It makes a very big difference in performance.</p>\n\n<p>Someday maybe the interaction with the database will be so fast that there would be no point in batching up the SQL, but that day isn't here yet. When it comes, I'll switch to ORM, but until then, I'm willing to have my code be a little uglier in exchange for performance. It's no fun for users to use a sluggish app.</p>\n\n<p>Finally, I like SQL. I'm good at SQL. Real good. I don't want to spend my time figuring out how to co-erce Linq to emit the SQL that I want. It would slow down <em>MY</em> performance.</p>\n" }, { "answer_id": 271847, "author": "Alexander Prokofyev", "author_id": 11256, "author_profile": "https://Stackoverflow.com/users/11256", "pm_score": 2, "selected": false, "text": "<p>You could combine both approaches mentioned using <a href=\"http://msdn.microsoft.com/en-us/library/esbykkzb.aspx\" rel=\"nofollow noreferrer\">Strongly Typed DataSets</a>.</p>\n\n<p>It's possible to add them to a Visual Studio project via \"Add New Item\" dialog \"DataSet template\" and then use visual Dataset Designer (it edits XSD file behind the scenes). </p>\n\n<p>There is another <a href=\"http://msdn.microsoft.com/en-us/magazine/cc163877.aspx\" rel=\"nofollow noreferrer\">article</a> on subject.</p>\n" }, { "answer_id": 271890, "author": "tvanfosson", "author_id": 12950, "author_profile": "https://Stackoverflow.com/users/12950", "pm_score": 0, "selected": false, "text": "<p>I find that I'm able to develop less code and test my code better using an ORM than DataSets/DataTables. I'm currently using LINQ-to-SQL and wrapping a thin layer around the designer generated code via partial classes as my ORM. The thin layer basically allows me to add some role-based permissions and increases the testability of the code by refactoring to interfaces and using dependency injection to specify the data context (that way I can mock it up for other tests).</p>\n\n<p>I've done both -- write my own ORM around DS/DT, strongly-typed DS/DT, etc. and have switched to LINQ and am not going back. I may eventually move to something like NHibernate, Entity Framework, or something else, but for now my LINQ solution offers pretty much all I need and is much simpler than my old solutions.</p>\n" }, { "answer_id": 272059, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 4, "selected": true, "text": "<p>Datatable will certainly be conceptually more straight forward in working with data. And its devoid of sometimes unnatural idioms that you find in ORM. (querying a record into local memory, before updating it; joins are pointers; the key value itself is a pointer, hence, adding a record requires loading the parent record)</p>\n\n<p>The big advantages for ORM are...</p>\n\n<p>1) it writes the sql for you, so you dont really have to write any sql to do basic crud. Of course writing more complex statements has to be done in a less powerful sublanguage (i.e. hql)</p>\n\n<p>2) The other big advantage of ORM is when you get results back, it maps it into value objects, without writing a bunch of code to map the values and handle type conversion.</p>\n\n<p>If you have strong sql skills but want advantage 2 covered, i would go with ibatis</p>\n" }, { "answer_id": 272662, "author": "Corbin March", "author_id": 7625, "author_profile": "https://Stackoverflow.com/users/7625", "pm_score": 2, "selected": false, "text": "<p>I would look at the advantages of data objects versus DataTables (a fancy ORM library isn't really necessary though they can be nice):</p>\n\n<ul>\n<li>Conceptually clean. You're forced to apply OO concepts to your data. It's easier to understand \"this is a Person\" versus \"the Person I want is somewhere in this table\".</li>\n<li>Enforces separation of concerns. It's tempting to tack UI context data to a DataTable - for one UI I get a Person with a primary address in the same record, for another I get a Person with credit information in the same record. When I'm working with a model, I want that model to be consistent wherever I consume it.</li>\n<li><p>Transform the data only once. In the DataTable-crunching apps I've seen, there's a lot of this scattered all over:</p>\n\n<p>if(row[\"col\"] == DBNull.Value || string.IsNullOrEmpty(row[\"col\"] as string)) ...</p>\n\n<p>I'd rather check that condition once when I populate the data object versus checking it everywhere the DataTable is used. </p></li>\n<li>Easier to unit test. If you reference a field in a data object that doesn't exist, you get a compile-time error. If you reference a field in a DataTable that doesn't exist, you get a run-time error.</li>\n</ul>\n\n<p>I do believe ORM can make you lazy. For instance, there's absolutely no reason to populate a set of related data objects from individual queries in the objects if those objects are always used together. Instead, write a big and efficient query that grabs all the necessary data and then builds the data object graph. Still, if you keep its limitations in mind, it does save a lot of work.</p>\n\n<p>Related: <a href=\"https://stackoverflow.com/questions/37378/how-to-convince-my-co-workers-not-to-use-datasets-for-enterprise-development-ne\">How to convince my co-workers not to use datasets for enterprise development (.NET 2.0+)</a>.</p>\n" }, { "answer_id": 328247, "author": "Tom A", "author_id": 10226, "author_profile": "https://Stackoverflow.com/users/10226", "pm_score": 2, "selected": false, "text": "<p>In .Net strongly typed datasets have the benefits you attribute to ORM -- the value of strong typing in the IDE and Intellisense,</p>\n\n<p>The TableAdapters created in Visual Studio will write all of your CRUD SQL for you. You put your business logic in the C# (or other lang.) and not in the SQL. </p>\n\n<p>I think the disconnected data model offered by datasets proves to be more efficient in practice than typical hand-coded SQL. It leads to non-chatty DB interactions where you get all of your related table data in a single query. And it has very good support for optimistic locking (providing DBConcurrency exceptions). The dataset also tracks insertions, modifications and deletions to your data, so you don't have to.</p>\n\n<p>Strongly typed datasets also offer straight-forward navigation to related table data. </p>\n\n<p>A good reference on DataSets is </p>\n\n<blockquote>\n <p>Programming Microsoft® ADO.NET 2.0\n Core Reference by David Sceppa </p>\n \n <p>Publisher: Microsoft Press Pub Date:\n May 17, 2006 Print ISBN-10:\n 0-7356-2206-X Print ISBN-13:\n 978-0-7356-2206-7 Pages: 800</p>\n</blockquote>\n\n<p>+tom</p>\n" }, { "answer_id": 3084521, "author": "Binoj Antony", "author_id": 33015, "author_profile": "https://Stackoverflow.com/users/33015", "pm_score": 2, "selected": false, "text": "<p>I used to use DataSets in early .NET days, then started using typed DataSets, over time found that the memory footprint left by DataSets are very high and it did not make sense to use unmanaged objects for every simple tasks. <br/>\nHence concluded that DTOs/POCOs are a better choice and started using NHibernate and iBatis.<br/>\n My average(or below average) developers found them complex and hard to use(no pun intended).<br/> So I made a <I>home grown</I> ORM <a href=\"http://xmldatamapper.codeplex.com//\" rel=\"nofollow noreferrer\">XmlDataMapper</a> that was much easier to use that the complex ORMs out there.</p>\n\n<p>To integrate XmlDataMapper all you need to do is 4 little steps</p>\n\n<ol>\n<li>Create a Business Entity / DTO for the tables</li>\n<li>Create an XML File with the mapping information between the table and the DTO.</li>\n<li>Specify the DTO and xml file in the configuration.</li>\n<li>Just call the DTOConverter.Convert(dataReader) and other such methods to convert your database record to DTO / Business Entity</li>\n</ol>\n" } ]
2008/11/07
[ "https://Stackoverflow.com/questions/271806", "https://Stackoverflow.com", "https://Stackoverflow.com/users/14606/" ]
This is a simplification of the issue (there are lots of ways of doing things), but among applications that need to talk to a database I have usually seen one of two patterns: 1. Object-Relational Mapping (ORM), where (usually) each table in the database has a corresponding "row wrapper" class with public properties that match the columns in the table. Sometimes these classes also automagically retrieve related information, so that foreign key columns can instead be exposed and displayed as the related data (rather than just the PK values). 2. DataTables (and/or DataSets), where data is retrieved from the server as a DataTable and worked with in that form (even in the UI). One of the major differences between the two approaches is that ORM allows you to reference strongly-typed fields in your code like so: ``` Person bob = new Person(); bob.FirstName = "Bob"; collectionPeople.Add(bob); ``` whereas with the DataTable approach your code would be something like: ``` DataRow newrow = datatablePeople.NewRow(); newrow["FirstName"] = "Bob"; datatablePeople.Rows.Add(newrow); ``` In this case, the ORM approach benefits from compile-time checking while the DataTable approach does not. On the other hand, the DataTable (and the DataSet) are already-written data structures that do an excellent job of representing relational data directly, so code that uses them can usually be implemented more quickly. In addition, code that uses DataTables can be easily understood and modified by others; home-grown (and often COTS) ORM systems often do extra database access "under the hood" to populate foreign keys and so forth, which can create problems for the unaware. So which approach do you generally favor and why?
Datatable will certainly be conceptually more straight forward in working with data. And its devoid of sometimes unnatural idioms that you find in ORM. (querying a record into local memory, before updating it; joins are pointers; the key value itself is a pointer, hence, adding a record requires loading the parent record) The big advantages for ORM are... 1) it writes the sql for you, so you dont really have to write any sql to do basic crud. Of course writing more complex statements has to be done in a less powerful sublanguage (i.e. hql) 2) The other big advantage of ORM is when you get results back, it maps it into value objects, without writing a bunch of code to map the values and handle type conversion. If you have strong sql skills but want advantage 2 covered, i would go with ibatis
271,815
<p>Is there a better way to write this code? </p> <p>I want to show a default value ('No data') for any empty fields returned by the query:</p> <pre><code>$archivalie_id = $_GET['archivalie_id']; $query = "SELECT a.*, ip.description AS internal_project, o.description AS origin, to_char(ad.origin_date,'YYYY') AS origin_date FROM archivalie AS a LEFT JOIN archivalie_dating AS ad ON a.id = ad.archivalie_id LEFT JOIN internal_project AS ip ON a.internal_project_id = ip.id LEFT JOIN origin AS o ON a.origin_id = o.id WHERE a.id = $archivalie_id"; $result = pg_query($db, $query); while ($row = pg_fetch_object($result)) { $no_data = '&lt;span class="no-data"&gt;No data&lt;/span&gt;'; $internal_project = ($row-&gt;internal_project != '') ? $row-&gt;internal_project : $no_data; $incoming_date = ($row-&gt;incoming_date != '') ? $row-&gt;incoming_date : $no_data; $origin = ($row-&gt;origin != '') ? $row-&gt;origin : $no_data; } </code></pre>
[ { "answer_id": 271826, "author": "Stefan Gehrig", "author_id": 11354, "author_profile": "https://Stackoverflow.com/users/11354", "pm_score": 3, "selected": true, "text": "<p>You could use a small helper function</p>\n\n<pre><code>function dbValue($value, $default=null)\n{\n if ($default===null) {\n $default='&lt;span class=\"no-data\"&gt;No data&lt;/span&gt;';\n }\n if (!empty($value)) {\n return $value;\n } else {\n return $default;\n }\n}\n</code></pre>\n" }, { "answer_id": 271844, "author": "markus", "author_id": 11995, "author_profile": "https://Stackoverflow.com/users/11995", "pm_score": 1, "selected": false, "text": "<p>If this is not just example code then you surely want to sanitize this query by writing...</p>\n\n<pre><code>$archivalie_id = pg_escape_string($_GET['archivalie_id']);\n</code></pre>\n\n<p>or you want to convert $archivalie_id with intval() if it is clearly always an integer.</p>\n\n<p>furthermore I suggest to replace 'No data' with a constant like '_MYPROJECT_NODATA' so you can easily change the way your no data label looks or implement internationalisation.</p>\n\n<p>You would then use </p>\n\n<pre><code>define('_MYPROJECT_NODATA', '&lt;span class=\"no-data\"&gt;No data&lt;/span&gt;');\n</code></pre>\n" }, { "answer_id": 271887, "author": "Tomalak", "author_id": 18771, "author_profile": "https://Stackoverflow.com/users/18771", "pm_score": 1, "selected": false, "text": "<p>One approach would be to select the default right on the database server.</p>\n\n<pre><code>SELECT \n IFNULL(NULLIF(a.field1, ''), 'No data') AS field1, \n IFNULL(NULLIF(a.field2, ''), 'No data') AS field2, \n IFNULL(NULLIF(ip.description, ''), 'No data') AS internal_project,\n IFNULL(NULLIF(o.description, ''), 'No data') AS origin,\n to_char(ad.origin_date,'YYYY') AS origin_date \nFROM \n archivalie AS a \n LEFT JOIN archivalie_dating AS ad ON a.id = ad.archivalie_id \n LEFT JOIN internal_project AS ip ON a.internal_project_id = ip.id\n LEFT JOIN origin AS o ON a.origin_id = o.id \nWHERE \n a.id = $archivalie_id\n</code></pre>\n\n<p>This way you can output values right away, and you do not have to touch existing code. The <code>IFNULL(NULLIF())</code> turns empty strings to <code>NULL</code>, and <code>NULL</code> to <code>'No data'</code>. If you want to leave empty strings alone, use the <code>IFNULL()</code> only.</p>\n\n<p>From an architectural perspective, this may lack some elegance (depending on how you look at it), but it is effective.</p>\n" }, { "answer_id": 271915, "author": "Tony Andrews", "author_id": 18747, "author_profile": "https://Stackoverflow.com/users/18747", "pm_score": 0, "selected": false, "text": "<p>You can use standard SQL COALESCE function to return a special string instead of null, like this:</p>\n\n<pre><code>$query = \"SELECT \n a.*, \n COALESCE(ip.description,'NO_DATA') AS internal_project,\n COALESCE(o.description,'NO_DATA') AS origin,\n COALESCE(to_char(ad.origin_date,'YYYY'),'NO_DATA') AS origin_date \n</code></pre>\n\n<p>Then you could replace 'NO_DATA' by the appropriate HTML in your program as others have suggested.</p>\n" } ]
2008/11/07
[ "https://Stackoverflow.com/questions/271815", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4196/" ]
Is there a better way to write this code? I want to show a default value ('No data') for any empty fields returned by the query: ``` $archivalie_id = $_GET['archivalie_id']; $query = "SELECT a.*, ip.description AS internal_project, o.description AS origin, to_char(ad.origin_date,'YYYY') AS origin_date FROM archivalie AS a LEFT JOIN archivalie_dating AS ad ON a.id = ad.archivalie_id LEFT JOIN internal_project AS ip ON a.internal_project_id = ip.id LEFT JOIN origin AS o ON a.origin_id = o.id WHERE a.id = $archivalie_id"; $result = pg_query($db, $query); while ($row = pg_fetch_object($result)) { $no_data = '<span class="no-data">No data</span>'; $internal_project = ($row->internal_project != '') ? $row->internal_project : $no_data; $incoming_date = ($row->incoming_date != '') ? $row->incoming_date : $no_data; $origin = ($row->origin != '') ? $row->origin : $no_data; } ```
You could use a small helper function ``` function dbValue($value, $default=null) { if ($default===null) { $default='<span class="no-data">No data</span>'; } if (!empty($value)) { return $value; } else { return $default; } } ```
271,821
<p>I have a site that usually has news items at the top of the homepage, and sometimes (for specific periods) will have one or more 'quicklinks' beneath the news items, to guide users to pages of topical interest. Beneath those is the usual blurb.</p> <p>We have alternative language versions of these sites, which often don't contain either the news items or the quicklinks, but may do from time to time.</p> <p>Previously, when the appearance was less dynamic, each section was absolutely positioned, with a top attribute configured appropriately. But as more subtle variations were required, I find myself chopping and changing both the base HTML and the stylesheet rules. </p> <p>My question is what do people think about the different approaches to this problem, and do they have any suggestions that I haven't considered. Achieving the desired result is easy, but I'm thinking of good coding practice that makes the site easier to read &amp; debug.</p> <p>I could have separate style classes for each variation of each item:</p> <pre><code>.news {top: 100px; etc...;} .news2 {top: 150px; etc...;} .ql {top: 150px; etc...;} .ql2 {top: 200px; etc...;} .main {top: 200px; etc...;} .main2 {top: 250px; etc...;} </code></pre> <p>...which seems a little too verbose.</p> <p>Or, perhaps:</p> <pre><code>.news {etc...;} .ql {etc...;} .main {etc...;} .top100 {top: 100px;} .top150 {top: 150px;} .top200 {top: 200px;} .top250 {top: 250px;} </code></pre> <p>Somewhat more compact, and it keeps the styling in the stylesheet and away from the HTML.</p> <p>Or, perhaps even:</p> <pre><code>.news {etc...;} .ql {etc...;} .main {etc...;} </code></pre> <p>in HTML:</p> <pre><code>&lt;div class="news" style="top:100px;"&gt; &lt;div class="ql" style="top:150px;"&gt; &lt;div class="main" style="top:200px;"&gt; </code></pre> <p>This is the most 'direct' solution, but clearly some of the styling is in the HTML which from a purists point of view is a 'no-no'; There are practical reasons for this view, but in this case, this is probably the easiest way to handle the varied and arbitrary changes that will be requested.</p> <p>Note: The site was (poorly) designed by a 3rd party, although I have tried to rescue it without entirely re-writing it. However, the site will be re-developed, possibly as early as Q3 or Q4 2009. At that stage, I'd hope to be moving away from a absolutely positioned approach, to one that is more fluid - so this question is about what to do in the interim, and also as a general question of style.</p>
[ { "answer_id": 271827, "author": "Toon Krijthe", "author_id": 18061, "author_profile": "https://Stackoverflow.com/users/18061", "pm_score": 3, "selected": true, "text": "<pre><code>.top100 {top: 100px;}\n.top150 {top: 150px;}\n.top200 {top: 200px;}\n.top250 {top: 250px;}\n</code></pre>\n\n<p>Is a bad practice, because you now add style information into the HTML.\nBetter use descriptive names and link them together. Like:</p>\n\n<pre><code>.news {top: 100px; etc...;}\n.news2, .ql {top: 150px; etc...;}\n.ql2, .main {top: 200px; etc...;}\n.main2 {top: 250px; etc...;}\n</code></pre>\n\n<p>You can add more rules later.</p>\n\n<p>If it <strong>really</strong> is a temporary solution, go ahead and make it easy for yourself. But you now that most temporary solutions stick around for a lot of years.</p>\n" }, { "answer_id": 275745, "author": "Lee Kowalkowski", "author_id": 30945, "author_profile": "https://Stackoverflow.com/users/30945", "pm_score": 1, "selected": false, "text": "<p>So, are you using <code>\"&lt;classname&gt;\"</code> for where there are no quick links, and \"<code>&lt;classname&gt;2\"</code> for when there are?</p>\n\n<p>You can use more than one classname on an element, you know. So you can have <code>&lt;elem class=\"&lt;classname&gt; quicklinks\"&gt;</code> for example. And have a separate .quicklinks class in your CSS to move everything down another 50px.</p>\n\n<p>Absolute positioning isn't meant for things like that however. If you resized your text so big, things would start overlapping. </p>\n\n<p>It's possible that just the very presence of the quick links can be used to make everything else drop down, providing you don't position your elements like that.</p>\n" }, { "answer_id": 281352, "author": "CJM", "author_id": 6898, "author_profile": "https://Stackoverflow.com/users/6898", "pm_score": 0, "selected": false, "text": "<p>Actually, the best solution is probably this:</p>\n\n<pre><code>.news, .news2 {top: 100px; etc...;}\n.news2 {top: 150px;}\n.ql, .ql2 {top: 150px; etc...;}\n.ql2 {top: 200px;}\n.main, .main2 {top: 200px; etc...;}\n.main2 {top: 250px;}\n</code></pre>\n\n<p>But I take your point(s) GameCat...</p>\n\n<p>Thanks</p>\n" } ]
2008/11/07
[ "https://Stackoverflow.com/questions/271821", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6898/" ]
I have a site that usually has news items at the top of the homepage, and sometimes (for specific periods) will have one or more 'quicklinks' beneath the news items, to guide users to pages of topical interest. Beneath those is the usual blurb. We have alternative language versions of these sites, which often don't contain either the news items or the quicklinks, but may do from time to time. Previously, when the appearance was less dynamic, each section was absolutely positioned, with a top attribute configured appropriately. But as more subtle variations were required, I find myself chopping and changing both the base HTML and the stylesheet rules. My question is what do people think about the different approaches to this problem, and do they have any suggestions that I haven't considered. Achieving the desired result is easy, but I'm thinking of good coding practice that makes the site easier to read & debug. I could have separate style classes for each variation of each item: ``` .news {top: 100px; etc...;} .news2 {top: 150px; etc...;} .ql {top: 150px; etc...;} .ql2 {top: 200px; etc...;} .main {top: 200px; etc...;} .main2 {top: 250px; etc...;} ``` ...which seems a little too verbose. Or, perhaps: ``` .news {etc...;} .ql {etc...;} .main {etc...;} .top100 {top: 100px;} .top150 {top: 150px;} .top200 {top: 200px;} .top250 {top: 250px;} ``` Somewhat more compact, and it keeps the styling in the stylesheet and away from the HTML. Or, perhaps even: ``` .news {etc...;} .ql {etc...;} .main {etc...;} ``` in HTML: ``` <div class="news" style="top:100px;"> <div class="ql" style="top:150px;"> <div class="main" style="top:200px;"> ``` This is the most 'direct' solution, but clearly some of the styling is in the HTML which from a purists point of view is a 'no-no'; There are practical reasons for this view, but in this case, this is probably the easiest way to handle the varied and arbitrary changes that will be requested. Note: The site was (poorly) designed by a 3rd party, although I have tried to rescue it without entirely re-writing it. However, the site will be re-developed, possibly as early as Q3 or Q4 2009. At that stage, I'd hope to be moving away from a absolutely positioned approach, to one that is more fluid - so this question is about what to do in the interim, and also as a general question of style.
``` .top100 {top: 100px;} .top150 {top: 150px;} .top200 {top: 200px;} .top250 {top: 250px;} ``` Is a bad practice, because you now add style information into the HTML. Better use descriptive names and link them together. Like: ``` .news {top: 100px; etc...;} .news2, .ql {top: 150px; etc...;} .ql2, .main {top: 200px; etc...;} .main2 {top: 250px; etc...;} ``` You can add more rules later. If it **really** is a temporary solution, go ahead and make it easy for yourself. But you now that most temporary solutions stick around for a lot of years.
271,850
<p>After upgrading a project from Delphi 2007 to Delphi 2009 I'm getting an Unknown memory leak, so far I've been tryin to track it down using fastMM, here is what fastMM stack trace reports:</p> <pre><code>A memory block has been leaked. The size is: 20 This block was allocated by thread 0x111C, and the stack trace (return addresses) at the time was: 40339E [System.pas][System][@GetMem][3412] 534873 [crtl][_malloc] 56D1C4 [canex.cpp][MidasLib][DllGetDataSnapClassObject][3918] 56D316 [canex.cpp][MidasLib][DllGetDataSnapClassObject][3961] 56D5EE [canex.cpp][MidasLib][DllGetDataSnapClassObject][4085] 562D48 [DBCommon.pas][DBCommon][TFilterExpr.PutExprNode][1583] 408E46 [System.pas][System][DynArraySetLength][20464] 56D5EE [canex.cpp][MidasLib][DllGetDataSnapClassObject][4085] 408E92 [System.pas][System][@DynArraySetLength][20486] 528C1B [Forms.pas][Forms][TCustomForm.DoCreate][3260] 171A1A [GetRawStackTrace] The block is currently used for an object of class: Unknown The allocation number is: 302844 </code></pre> <p>And sometimes I get this:</p> <pre><code>A memory block has been leaked. The size is: 20 This block was allocated by thread 0x111C, and the stack trace (return addresses) at the time was: 40339E [System.pas][System][@GetMem][3412] 534873 [crtl][_malloc] 56D1C4 [canex.cpp][MidasLib][DllGetDataSnapClassObject][3918] 56D316 [canex.cpp][MidasLib][DllGetDataSnapClassObject][3961] 77DC921A [RtlAnsiStringToUnicodeString] 56D5EE [canex.cpp][MidasLib][DllGetDataSnapClassObject][4085] 7726B8F5 [GetProcAddress] 7726B907 [GetProcAddress] 589B1E [ossrv.cpp][MidasLib][DllGetDataSnapClassObject][3163] 56D5EE [canex.cpp][MidasLib][DllGetDataSnapClassObject][4085] 408E92 [System.pas][System][@DynArraySetLength][20486] The block is currently used for an object of class: Unknown </code></pre> <p>Is there some better way to figure out what really is causing the Memory leak?</p>
[ { "answer_id": 271977, "author": "utku_karatas", "author_id": 14716, "author_profile": "https://Stackoverflow.com/users/14716", "pm_score": 0, "selected": false, "text": "<p>IIRC VCL had a few very small leaks like this that you can ignore without much worry. This might be one of them!? Hope somebody clarifies this point.</p>\n" }, { "answer_id": 272370, "author": "zendar", "author_id": 25732, "author_profile": "https://Stackoverflow.com/users/25732", "pm_score": 1, "selected": false, "text": "<p>I don't know if there are any leaks in D2009 VCL, so presuming leak is in your code, first I would check following:</p>\n\n<ul>\n<li>is there any array or list (because of <code>@DynArraySetLength</code>) created in that form that is not released when you dispose form.</li>\n<li>is there any function that creates and returns some object that should be freed by outside caller, and if you have that kind of function check if caller frees that object. </li>\n<li>if this does not reveal leak, then you should check if each object that you create in your form code, gets destroyed when you destroy the form. </li>\n</ul>\n" }, { "answer_id": 272984, "author": "Jim McKeeth", "author_id": 255, "author_profile": "https://Stackoverflow.com/users/255", "pm_score": 3, "selected": false, "text": "<p>As long as the size of the memory block leaked does not grow the longer/more your program is used, then it isn't a concern. If you have long lived objects that are only freed when you terminate the application it is the same as if you leaked them - all memory is reclaimed on termination (Unless of course they have handles resources beyond memory).</p>\n\n<p>The memory leaks you want to be concerned with are the ones that accumulate over time or usage. If it is 20 bytes everytime then don't sweat it.</p>\n" }, { "answer_id": 273243, "author": "Francesca", "author_id": 9842, "author_profile": "https://Stackoverflow.com/users/9842", "pm_score": 0, "selected": false, "text": "<p>I would say you have something happening in your Form OnCreate event handler that is growing a DynArray.<br>\nAnd that DynArray is not released at the end.<br>\nBut without seeing the code and actually debugging it with FastMM, it's close to impossible to guess what's really happening. </p>\n" }, { "answer_id": 937842, "author": "Loren Pechtel", "author_id": 10659, "author_profile": "https://Stackoverflow.com/users/10659", "pm_score": 1, "selected": false, "text": "<p>The last time I had a puzzling leak along these lines I looked over the raw memory of the offending object--and saw text that showed me what sort of data it was. When it says it doesn't know what sort of object it is that likely means it isn't an object in the first place--so look at dynamically allocated things, including strings.</p>\n" }, { "answer_id": 944345, "author": "Fabio Gomes", "author_id": 727, "author_profile": "https://Stackoverflow.com/users/727", "pm_score": 4, "selected": true, "text": "<p>This memory leak was being caused by a Delphi bug, QC <a href=\"http://qc.embarcadero.com/wc/qcmain.aspx?d=67709\" rel=\"noreferrer\">#67709</a></p>\n\n<p>It was fixed by the last Delphi 2009 update, no wonder I wasn't able to fix it.</p>\n" } ]
2008/11/07
[ "https://Stackoverflow.com/questions/271850", "https://Stackoverflow.com", "https://Stackoverflow.com/users/727/" ]
After upgrading a project from Delphi 2007 to Delphi 2009 I'm getting an Unknown memory leak, so far I've been tryin to track it down using fastMM, here is what fastMM stack trace reports: ``` A memory block has been leaked. The size is: 20 This block was allocated by thread 0x111C, and the stack trace (return addresses) at the time was: 40339E [System.pas][System][@GetMem][3412] 534873 [crtl][_malloc] 56D1C4 [canex.cpp][MidasLib][DllGetDataSnapClassObject][3918] 56D316 [canex.cpp][MidasLib][DllGetDataSnapClassObject][3961] 56D5EE [canex.cpp][MidasLib][DllGetDataSnapClassObject][4085] 562D48 [DBCommon.pas][DBCommon][TFilterExpr.PutExprNode][1583] 408E46 [System.pas][System][DynArraySetLength][20464] 56D5EE [canex.cpp][MidasLib][DllGetDataSnapClassObject][4085] 408E92 [System.pas][System][@DynArraySetLength][20486] 528C1B [Forms.pas][Forms][TCustomForm.DoCreate][3260] 171A1A [GetRawStackTrace] The block is currently used for an object of class: Unknown The allocation number is: 302844 ``` And sometimes I get this: ``` A memory block has been leaked. The size is: 20 This block was allocated by thread 0x111C, and the stack trace (return addresses) at the time was: 40339E [System.pas][System][@GetMem][3412] 534873 [crtl][_malloc] 56D1C4 [canex.cpp][MidasLib][DllGetDataSnapClassObject][3918] 56D316 [canex.cpp][MidasLib][DllGetDataSnapClassObject][3961] 77DC921A [RtlAnsiStringToUnicodeString] 56D5EE [canex.cpp][MidasLib][DllGetDataSnapClassObject][4085] 7726B8F5 [GetProcAddress] 7726B907 [GetProcAddress] 589B1E [ossrv.cpp][MidasLib][DllGetDataSnapClassObject][3163] 56D5EE [canex.cpp][MidasLib][DllGetDataSnapClassObject][4085] 408E92 [System.pas][System][@DynArraySetLength][20486] The block is currently used for an object of class: Unknown ``` Is there some better way to figure out what really is causing the Memory leak?
This memory leak was being caused by a Delphi bug, QC [#67709](http://qc.embarcadero.com/wc/qcmain.aspx?d=67709) It was fixed by the last Delphi 2009 update, no wonder I wasn't able to fix it.
271,888
<p>In my database application I sometimes have to deal with <code>null</code> strings in the database. In most cases this is fine, but when it comes do displaying data in a form the Swing components - using <code>JTextField</code> for example - cannot handle null strings. (<code>.setText(null)</code> fails)</p> <p>(<strong>EDIT:</strong> I just noticed that <code>JTextField</code> actually accepts a <code>null</code> string, but the question remains for all other cases where unexpected <code>null</code> values can lead to problems.)</p> <p>The null values have no special meaning, they can (must) be treated as empty strings. </p> <p>What is the best practice to deal with this problem? <em>Unfortunatly I cannot change the database</em>.</p> <ul> <li>Checking every value if it is <code>null</code> before calling <code>setText()</code>?</li> <li>Adding a try-catch handler to every <code>setText()</code> call?</li> <li>Introducing a static method which filters all <code>null</code> strings?</li> <li>Replace all <code>null</code> values to empty strings immediatly after reading from the database?</li> <li>... [your suggestions]</li> </ul>
[ { "answer_id": 271894, "author": "Tomo", "author_id": 9622, "author_profile": "https://Stackoverflow.com/users/9622", "pm_score": 0, "selected": false, "text": "<p>If you can, add a default value - empty string - for a field in DB .</p>\n" }, { "answer_id": 271897, "author": "Marko", "author_id": 31141, "author_profile": "https://Stackoverflow.com/users/31141", "pm_score": 4, "selected": true, "text": "<p>If you are using any ORM tool or somehow you map your DB fields to Java bean you can allways have:</p>\n\n<pre>\npublic void setFoo(String str) {\n this.foo = str != null ? str : \"\";\n}\n</pre>\n" }, { "answer_id": 271921, "author": "Ron Tuffin", "author_id": 939, "author_profile": "https://Stackoverflow.com/users/939", "pm_score": 2, "selected": false, "text": "<p>From a SQL angle try:</p>\n\n<pre><code>select ISNULL(column_name,'') from ...\n</code></pre>\n" }, { "answer_id": 271927, "author": "Ruben", "author_id": 26919, "author_profile": "https://Stackoverflow.com/users/26919", "pm_score": 0, "selected": false, "text": "<p>You could extend or wrap JTextField and overwrite the setText() method to replace NULL with an empty String.</p>\n" }, { "answer_id": 271963, "author": "Jimoc", "author_id": 24079, "author_profile": "https://Stackoverflow.com/users/24079", "pm_score": 0, "selected": false, "text": "<p>As Ruben said I would extend the JTextField to overwrite the setText() method and replace NULL with the empty string.</p>\n\n<p>However I would also overwrite the getText() method to overwrite empty string with NULL so that when you are saving back into the database you do not overwrite a null value in there with the empty string.</p>\n" }, { "answer_id": 272991, "author": "James Schek", "author_id": 17871, "author_profile": "https://Stackoverflow.com/users/17871", "pm_score": 2, "selected": false, "text": "<p>Use Beans Binding API to bind values from your entity objects to your SWING Widgets. Beanins Binding will transparently handle null values and will not replace the null with an empty string.</p>\n" }, { "answer_id": 274254, "author": "dongilmore", "author_id": 31962, "author_profile": "https://Stackoverflow.com/users/31962", "pm_score": 2, "selected": false, "text": "<p>I think all your answers are reasonable, but since you tagged this \"best practices\", I'd like to remind you of the null object design pattern. Wherever it seems worth the effort, for whatever class need the protection, write special instantiation code for a \"null\" object of that class. The idea is this \"null\" object is real, and can behave appropriately no matter what you ask it to do. Your null \"String\" object could provide whatever you want as it's value. </p>\n\n<p>This pattern also means you can get rid of lots of null checks, and the code is more robust. It does use up a bit of CPU sending messages to nulls and having them do nothing, so it is less desirable when a large percentage of objects are expected to be null.</p>\n" } ]
2008/11/07
[ "https://Stackoverflow.com/questions/271888", "https://Stackoverflow.com", "https://Stackoverflow.com/users/23368/" ]
In my database application I sometimes have to deal with `null` strings in the database. In most cases this is fine, but when it comes do displaying data in a form the Swing components - using `JTextField` for example - cannot handle null strings. (`.setText(null)` fails) (**EDIT:** I just noticed that `JTextField` actually accepts a `null` string, but the question remains for all other cases where unexpected `null` values can lead to problems.) The null values have no special meaning, they can (must) be treated as empty strings. What is the best practice to deal with this problem? *Unfortunatly I cannot change the database*. * Checking every value if it is `null` before calling `setText()`? * Adding a try-catch handler to every `setText()` call? * Introducing a static method which filters all `null` strings? * Replace all `null` values to empty strings immediatly after reading from the database? * ... [your suggestions]
If you are using any ORM tool or somehow you map your DB fields to Java bean you can allways have: ``` public void setFoo(String str) { this.foo = str != null ? str : ""; } ```
271,892
<p>I have a &lt;select&gt;. Using JavaScript, I need to get a specific &lt;option&gt; from the list of options, and all I know is the value of the option. The option may or may not be selected.</p> <p>Here's the catch: there are thousands of options and I need to do this a few hundred times in a loop. Right now I loop through the "options" array and look for the option I want. This is too slow (in the sense that on my very fast machine the browser locked up until I killed it after a few minutes).</p> <p>Is there any faster way to do this? I'll take browser-specific ways, but of course a DOM-standard way would be nice.</p>
[ { "answer_id": 271903, "author": "Davide Gualano", "author_id": 28582, "author_profile": "https://Stackoverflow.com/users/28582", "pm_score": -1, "selected": false, "text": "<p>With jQuery something like this could be faster:</p>\n\n<pre><code>$(\"#idselect option[value='yourval']\")\n</code></pre>\n\n<p><a href=\"http://docs.jquery.com/Selectors/attributeEquals#attributevalue\" rel=\"nofollow noreferrer\">http://docs.jquery.com/Selectors/attributeEquals#attributevalue</a></p>\n" }, { "answer_id": 271905, "author": "Nick Berardi", "author_id": 17, "author_profile": "https://Stackoverflow.com/users/17", "pm_score": 0, "selected": false, "text": "<p>no there isn't, you are doing it really the best way possible. The only other thing you can try for maybe a quicker look up is to give each of the options an ID tag so that you can look them up as a DOM object instead of looping through children of a DOM object.</p>\n" }, { "answer_id": 271906, "author": "Lasar", "author_id": 9438, "author_profile": "https://Stackoverflow.com/users/9438", "pm_score": 0, "selected": false, "text": "<p>You could loop through all the options once and put all items into an associative array. Then you can just look for <code>myOptions[valueImLookingFor]</code>.</p>\n\n<p>I haven't tested this and can't guarantee it will be faster/better. But it should get rid of all those loops.</p>\n\n<p>Depending on your setup and needs you could also generate a javascript array on the client side and put it in the markup instead of (or in addition to) the select.</p>\n" }, { "answer_id": 271908, "author": "Paul Whelan", "author_id": 3050, "author_profile": "https://Stackoverflow.com/users/3050", "pm_score": 2, "selected": false, "text": "<p>I would suggest not having thousands of options in your select.</p>\n\n<p>Perhaps you could structure your data differently a select with thousands of entries to me seems wrong.</p>\n\n<p>Perhaps your app requires this but it would not be typical usage of this element.</p>\n" }, { "answer_id": 271909, "author": "philistyne", "author_id": 16597, "author_profile": "https://Stackoverflow.com/users/16597", "pm_score": 0, "selected": false, "text": "<p>My suggestion would be to look at a framework/toolkit like <a href=\"http://dojotoolkit.org/book/dojo-book-0-9/part-3-programmatic-dijit-and-dojo/selecting-dom-nodes-dojo-query\" rel=\"nofollow noreferrer\">Dojo and its way of selecting DOM nodes</a>.</p>\n\n<p>The toolkit irons out alot of browser inconsistencies and allows you select and manipulate DOM nodes quickly and easily.</p>\n" }, { "answer_id": 271911, "author": "Tomalak", "author_id": 18771, "author_profile": "https://Stackoverflow.com/users/18771", "pm_score": 4, "selected": true, "text": "<p>I'd do it like this:</p>\n\n<pre><code>// first, build a reverse lookup\nvar optCount = mySelect.options.length;\nvar reverseLookup = {};\nfor (var i = 0; i &lt; optCount; i++)\n{\n var option = mySelect.options[i];\n if (!reverseLookup[option.value])\n {\n // use an array to account for multiple options with the same value\n reverseLookup[option.value] = [];\n }\n // store a reference to the DOM element\n reverseLookup[option.value].push(option);\n}\n\n// then, use it to find the option\nvar foundOptions = reverseLookup[\"Value that you are looking for\"];\nif (foundOptions &amp;&amp; foundOptions.length)\n{\n alert(foundOptions[0].id);\n}\n</code></pre>\n" }, { "answer_id": 271914, "author": "John Lemp", "author_id": 12915, "author_profile": "https://Stackoverflow.com/users/12915", "pm_score": 0, "selected": false, "text": "<p>I would think that it may be an indicator that \"thousands\" of items in a select probably isn't the best user experience. Maybe you should consider trying to limit your dropdowns to several that narrow the results as a user selects them.</p>\n" }, { "answer_id": 273448, "author": "Mr. Muskrat", "author_id": 2657951, "author_profile": "https://Stackoverflow.com/users/2657951", "pm_score": 1, "selected": false, "text": "<p>This is Tomalak's answer with a minor speed tweak. You see a while loop that iterates down is faster than a for loop that iterates up. (I'm lazy so I won't provide the link.)</p>\n\n<pre><code>var i = mySelect.options.length - 1;\nvar reverseLookup = {};\nwhile ( i &gt;= 0 )\n{\n var option = mySelect.options[i];\n if (!reverseLookup[option.value])\n {\n // use an array to account for multiple options with the same value\n reverseLookup[option.value] = [];\n }\n // store a reference to the DOM element\n reverseLookup[option.value].push(option);\n i--;\n}\n\n// then, use it to find the option\nvar foundOptions = reverseLookup[\"Value that you are looking for\"];\nif (foundOptions &amp;&amp; foundOptions.length)\n{\n alert(foundOptions[0].id);\n}\n</code></pre>\n" } ]
2008/11/07
[ "https://Stackoverflow.com/questions/271892", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4641/" ]
I have a <select>. Using JavaScript, I need to get a specific <option> from the list of options, and all I know is the value of the option. The option may or may not be selected. Here's the catch: there are thousands of options and I need to do this a few hundred times in a loop. Right now I loop through the "options" array and look for the option I want. This is too slow (in the sense that on my very fast machine the browser locked up until I killed it after a few minutes). Is there any faster way to do this? I'll take browser-specific ways, but of course a DOM-standard way would be nice.
I'd do it like this: ``` // first, build a reverse lookup var optCount = mySelect.options.length; var reverseLookup = {}; for (var i = 0; i < optCount; i++) { var option = mySelect.options[i]; if (!reverseLookup[option.value]) { // use an array to account for multiple options with the same value reverseLookup[option.value] = []; } // store a reference to the DOM element reverseLookup[option.value].push(option); } // then, use it to find the option var foundOptions = reverseLookup["Value that you are looking for"]; if (foundOptions && foundOptions.length) { alert(foundOptions[0].id); } ```
271,904
<p>Say you have a class declaration, e.g.:</p> <pre><code> class MyClass { int myInt=7; int myOtherInt; } </code></pre> <p>Now, is there a way in generic code, using reflection (or any other means, for that matter), that I can deduce that myInt has a default value assigned, whereas myOtherInt does not? Note the difference between being initialised with an explicit default value, and being left to it's implicit default value (myOtherInt will be initialised to 0, by default).</p> <p>From my own research it looks like there is no way to do this - but I thought I'd ask here before giving up.</p> <p>[Edit]</p> <p>Even with nullable and reference types I want to distingush between those that have been left as null, and those that have been explicitly initialised to null. This is so that I can say that fields with an initialiser are "optional" and other fields are "mandatory". At the moment I'm having to do this using attributes - which niggles me with their redundancy of information in this case.</p>
[ { "answer_id": 271919, "author": "John Lemp", "author_id": 12915, "author_profile": "https://Stackoverflow.com/users/12915", "pm_score": 2, "selected": false, "text": "<p>You might want to consider a nullable int for this behavior:</p>\n\n<pre><code>class MyClass\n{\n int? myInt = 7;\n int? myOtherInt = null;\n}\n</code></pre>\n" }, { "answer_id": 271925, "author": "Sander", "author_id": 2928, "author_profile": "https://Stackoverflow.com/users/2928", "pm_score": 2, "selected": false, "text": "<p>A default value is a value like any other. There is no way to differentiate between these two cases:</p>\n\n<pre><code>int explicitly = 0;\nint implicitly;\n</code></pre>\n\n<p>In both cases, you give them the value 0, one way just saves you typing. There is no magic \"default uninitialized value\" - they are both zero. They work out to be exactly the same. However, the fact that you are even contemplating this indicates that you are seriously off the track of good ideas. What are you doing? What is your specific need? You are asking the wrong question ;)</p>\n" }, { "answer_id": 271926, "author": "Hapkido", "author_id": 27646, "author_profile": "https://Stackoverflow.com/users/27646", "pm_score": -1, "selected": false, "text": "<p>The compiler can be set to generate a warning if you try to use a variable before assigning it a value. I have the default setting and that how it behave.</p>\n" }, { "answer_id": 271929, "author": "chakrit", "author_id": 3055, "author_profile": "https://Stackoverflow.com/users/3055", "pm_score": 5, "selected": true, "text": "<p>I compiled your code and load it up in ILDASM and got this</p>\n\n<pre><code>.method public hidebysig specialname rtspecialname \n instance void .ctor() cil managed\n{\n // Code size 15 (0xf)\n .maxstack 8\n IL_0000: ldarg.0\n IL_0001: ldc.i4.7\n IL_0002: stfld int32 dummyCSharp.MyClass::myInt\n IL_0007: ldarg.0\n IL_0008: call instance void [mscorlib]System.Object::.ctor()\n IL_000d: nop\n IL_000e: ret\n} // end of method MyClass::.ctor\n</code></pre>\n\n<p>Note the <code>ldc.i4.7</code> and <code>stfld int32 dummyCSharp.MyClass::myInt</code> seems to be instructions to set the default values for the myInt field.</p>\n\n<p><strong>So such assignment is actually compiled as an additional assignment statement in a constructor.</strong></p>\n\n<p>To detect such assignment, then you will need reflection to reflect on the IL of MyClass's constructor method and look for <code>stfld</code> (set fields?) commands.</p>\n\n<hr>\n\n<p>EDIT: If I add some assignment into the constructor explicitly:</p>\n\n<pre><code>class MyClass\n{\n public int myInt = 7;\n public int myOtherInt;\n\n public MyClass()\n {\n myOtherInt = 8;\n }\n}\n</code></pre>\n\n<p>When I load it up in ILDASM, I got this: </p>\n\n<pre><code>.method public hidebysig specialname rtspecialname \n instance void .ctor() cil managed\n{\n // Code size 24 (0x18)\n .maxstack 8\n IL_0000: ldarg.0\n IL_0001: ldc.i4.7\n IL_0002: stfld int32 dummyCSharp.MyClass::myInt\n IL_0007: ldarg.0\n IL_0008: call instance void [mscorlib]System.Object::.ctor()\n IL_000d: nop\n IL_000e: nop\n IL_000f: ldarg.0\n IL_0010: ldc.i4.8\n IL_0011: stfld int32 dummyCSharp.MyClass::myOtherInt\n IL_0016: nop\n IL_0017: ret\n} // end of method MyClass::.ctor\n</code></pre>\n\n<p>Note that the extra assigment on myOtherInt that I added was addded <em>after</em> a call the Object class's constructor.</p>\n\n<pre><code>IL_0008: call instance void [mscorlib]System.Object::.ctor()\n</code></pre>\n\n<p>So there you have it,</p>\n\n<p><strong>Any assignment done <em>before</em> the call to Object class's constructor in IL is a default value assignment.</strong></p>\n\n<p>Anything following it is a statement inside the class's actual constructor code.</p>\n\n<p>More extensive test should be done though.</p>\n\n<p>p.s. that was fun :-)</p>\n" }, { "answer_id": 271935, "author": "huseyint", "author_id": 39, "author_profile": "https://Stackoverflow.com/users/39", "pm_score": -1, "selected": false, "text": "<p>Does the following help:</p>\n\n<pre><code>bool isAssigned = (myOtherInt == default(int));\n</code></pre>\n" }, { "answer_id": 271951, "author": "Jack Ryan", "author_id": 28882, "author_profile": "https://Stackoverflow.com/users/28882", "pm_score": 1, "selected": false, "text": "<p>For value types using a nullable type for optional parameters should work. Strings could also be initialised to empty if they are not optional. </p>\n\n<pre><code>int mandatoryInt;\nint? optionalInt;\n</code></pre>\n\n<p>However this does strike me as a bit dirty, I would stick with attributes as a clear way of doing this.</p>\n" }, { "answer_id": 272020, "author": "Doug L.", "author_id": 19179, "author_profile": "https://Stackoverflow.com/users/19179", "pm_score": 0, "selected": false, "text": "<p>This approach uses the property get/set process:</p>\n\n<pre><code> class myClass\n {\n #region Property: MyInt\n private int _myIntDefault = 7;\n private bool _myIntChanged = false;\n private int _myInt;\n private int MyInt\n {\n get\n {\n if (_myIntChanged)\n {\n return _myInt;\n }\n else\n {\n return _myIntDefault;\n }\n }\n set\n {\n _myInt = value;\n _myIntChanged = true;\n }\n }\n\n private bool MyIntIsDefault\n {\n get\n {\n if (_myIntChanged)\n {\n return (_myInt == _myIntDefault);\n }\n else\n {\n return true;\n }\n }\n }\n #endregion\n }\n</code></pre>\n\n<p>That's alot of code for one field - hello snippets!</p>\n" }, { "answer_id": 272074, "author": "Javier Suero Santos", "author_id": 34432, "author_profile": "https://Stackoverflow.com/users/34432", "pm_score": 1, "selected": false, "text": "<p>May be this is not the simplest solution...</p>\n\n<p>You can use de DefaultValue attribute to set the value like:</p>\n\n<p>Import System.ComponentModel and System.Reflection</p>\n\n<pre><code>private int myNumber = 3;\n[System.ComponentModel.DefaultValue(3)]\npublic int MyNumber\n{\n get\n {\n return myNumber;\n }\n set\n {\n myNumber = value;\n }\n}\n</code></pre>\n\n<p>And then recover the default value with reflection:</p>\n\n<pre><code>PropertyInfo prop = this.GetType().GetProperty(\"MyNumber\");\nMessageBox.Show(((DefaultValueAttribute)(prop.GetCustomAttributes(typeof(DefaultValueAttribute), true).GetValue(0))).Value.ToString());\n</code></pre>\n" }, { "answer_id": 272359, "author": "dviljoen", "author_id": 29021, "author_profile": "https://Stackoverflow.com/users/29021", "pm_score": 0, "selected": false, "text": "<p>You could wrap the fields in private/protected properties. If you want to know if its been set or not, check the private field (e.g. _myInt.HasValue()).</p>\n\n<pre><code>class MyClass\n{\n\n public MyClass()\n {\n myInt = 7;\n }\n\n int? _myInt;\n protected int myInt\n {\n set { _myInt = value; }\n get { return _myInt ?? 0; }\n }\n\n int? _myOtherInt;\n protected int myOtherInt\n {\n set { _myOtherInt = value; }\n get { return _myOtherInt ?? 0; }\n }\n}\n</code></pre>\n" }, { "answer_id": 272422, "author": "Edward Kmett", "author_id": 34707, "author_profile": "https://Stackoverflow.com/users/34707", "pm_score": 1, "selected": false, "text": "<p>What about making a generic struct that contains a value and an initialized flag?</p>\n\n<pre><code>public struct InitializationKnown&lt;T&gt; {\n private T m_value;\n private bool m_initialized;\n\n // the default constructor leaves m_initialized = false, m_value = default(T)\n // InitializationKnown() {}\n\n InitializationKnown(T value) : m_value(value), m_initialized(true) {}\n\n public bool initialized { \n get { return m_initialized; }\n }\n public static operator T (InitializationKnown that) {\n return that.m_value;\n }\n // ... other operators including assignment go here\n}\n</code></pre>\n\n<p>Then just use this in place of the members you need to know about the initialization of. Its a pretty basic variation on a lazy future or promise.</p>\n" }, { "answer_id": 272516, "author": "plinth", "author_id": 20481, "author_profile": "https://Stackoverflow.com/users/20481", "pm_score": 1, "selected": false, "text": "<p>Here's what I'd do if I wanted to build this as a general runtime feature.\nFor scalar types, I'd create a default value attribute and use that to determine defaulticity.</p>\n\n<p>Here's a partial solution to the task - I'm sure it could be better, but I just knocked it out:</p>\n\n<pre><code>using System;\nusing System.Collections.Generic;\nusing System.Text;\nusing System.Reflection;\nusing System.Linq;\nusing System.Data;\n\n\nnamespace FieldAttribute\n{\n [global::System.AttributeUsage(AttributeTargets.All, Inherited = false, AllowMultiple = true)]\n sealed class DefaultValueAttribute : Attribute\n {\n public DefaultValueAttribute(int i)\n {\n IntVal = i;\n }\n\n public DefaultValueAttribute(bool b)\n {\n BoolVal = b;\n }\n\n public int IntVal { get; set; }\n public bool BoolVal { get; set; }\n\n private static FieldInfo[] GetAttributedFields(object o, string matchName)\n {\n Type t = o.GetType();\n FieldInfo[] fields = t.GetFields(BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance);\n\n return fields.Where(fi =&gt; ((matchName != null &amp;&amp; fi.Name == matchName) || matchName == null) &amp;&amp;\n (fi.GetCustomAttributes(false).Where(attr =&gt; attr is DefaultValueAttribute)).Count() &gt; 0).ToArray();\n }\n\n public static void SetDefaultFieldValues(object o)\n {\n FieldInfo[] fields = GetAttributedFields(o, null);\n foreach (FieldInfo fi in fields)\n {\n IEnumerable&lt;object&gt; attrs = fi.GetCustomAttributes(false).Where(attr =&gt; attr is DefaultValueAttribute);\n foreach (Attribute attr in attrs)\n {\n DefaultValueAttribute def = attr as DefaultValueAttribute;\n Type fieldType = fi.FieldType;\n if (fieldType == typeof(Boolean))\n {\n fi.SetValue(o, def.BoolVal);\n }\n if (fieldType == typeof(Int32))\n {\n fi.SetValue(o, def.IntVal);\n }\n }\n }\n }\n\n public static bool HasDefaultValue(object o, string fieldName)\n {\n FieldInfo[] fields = GetAttributedFields(o, null);\n foreach (FieldInfo fi in fields)\n {\n IEnumerable&lt;object&gt; attrs = fi.GetCustomAttributes(false).Where(attr =&gt; attr is DefaultValueAttribute);\n foreach (Attribute attr in attrs)\n {\n DefaultValueAttribute def = attr as DefaultValueAttribute;\n Type fieldType = fi.FieldType;\n if (fieldType == typeof(Boolean))\n {\n return (Boolean)fi.GetValue(o) == def.BoolVal;\n }\n if (fieldType == typeof(Int32))\n {\n return (Int32)fi.GetValue(o) == def.IntVal;\n }\n }\n }\n return false;\n }\n }\n\n class Program\n {\n [DefaultValue(3)]\n int foo;\n\n [DefaultValue(true)]\n bool b;\n\n public Program()\n {\n DefaultValueAttribute.SetDefaultFieldValues(this);\n Console.WriteLine(b + \" \" + foo);\n Console.WriteLine(\"b has default value? \" + DefaultValueAttribute.HasDefaultValue(this, \"b\"));\n foo = 2;\n Console.WriteLine(\"foo has default value? \" + DefaultValueAttribute.HasDefaultValue(this, \"foo\"));\n }\n\n static void Main(string[] args)\n {\n Program p = new Program();\n }\n }\n}\n</code></pre>\n" }, { "answer_id": 272843, "author": "Robert Giesecke", "author_id": 35443, "author_profile": "https://Stackoverflow.com/users/35443", "pm_score": 0, "selected": false, "text": "<p>If what you want is this, then check out the code at the bottom.<br>\nIt's written in Oxygene[1], hope that's not a problem.</p>\n\n<p>[1]or Delphi Prism how it's called now</p>\n\n<pre><code>\nvar inst1 := new Sample();\nvar inst2 := new Sample(X := 2);\n\nvar test1 := new DefaultValueInspector&lt;Sample&gt;(true);\nvar test2 := new DefaultValueInspector&lt;Sample&gt;(inst2, true);\n\nvar d := test1.DefaultValueByName[\"X\"];\n\nvar inst1HasDefault := test1.HasDefaultValue(inst1, \"X\");\nvar inst2HasDefault := test1.HasDefaultValue(inst2, \"X\");\n\nConsole.WriteLine(\"Value: {0}; inst1HasDefault: {1}; inst2HasDefault {2}\",\n d, inst1HasDefault, inst2HasDefault);\n\nd := test2.DefaultValueByName[\"X\"];\n\ninst1HasDefault := test2.HasDefaultValue(inst1, \"X\");\ninst2HasDefault := test2.HasDefaultValue(inst2, \"X\");\n\nConsole.WriteLine(\"Value: {0}; inst1HasDefault: {1}; inst2HasDefault {2}\",\n d, inst1HasDefault, inst2HasDefault);\n</code></pre>\n\n<p>Output:<pre>Value: 1; inst1HasDefault: True; inst2HasDefault False\nValue: 2; inst1HasDefault: False; inst2HasDefault True</pre></p>\n\n<pre><code>\nuses \n System.Collections.Generic, \n System.Reflection;\n\ntype\n DefaultValueInspector&lt;T&gt; = public class\n private\n method get_DefaultValueByName(memberName : String): Object;\n method get_DefaultValueByMember(memberInfo : MemberInfo) : Object;\n protected\n class method GetMemberErrorMessage(memberName : String) : String;\n method GetMember(memberName : String) : MemberInfo;\n\n property MembersByName : Dictionary&lt;String, MemberInfo&gt; \n := new Dictionary&lt;String, MemberInfo&gt;(); readonly;\n\n property GettersByMember : Dictionary&lt;MemberInfo, Converter&lt;T, Object&gt;&gt; \n := new Dictionary&lt;MemberInfo, Converter&lt;T, Object&gt;&gt;(); readonly;\n\n property DefaultValuesByMember : Dictionary&lt;MemberInfo, Object&gt; \n := new Dictionary&lt;MemberInfo, Object&gt;(); readonly;\n public\n property UseHiddenMembers : Boolean; readonly;\n\n property DefaultValueByName[memberName : String] : Object\n read get_DefaultValueByName;\n property DefaultValueByMember[memberInfo : MemberInfo] : Object\n read get_DefaultValueByMember;\n\n method GetGetMethod(memberName : String) : Converter&lt;T, Object&gt;;\n method GetGetMethod(memberInfo : MemberInfo) : Converter&lt;T, Object&gt;;\n\n method HasDefaultValue(instance : T; memberName : String) : Boolean;\n method HasDefaultValue(instance : T; memberInfo : MemberInfo) : Boolean;\n\n constructor(useHiddenMembers : Boolean);\n constructor(defaultInstance : T; useHiddenMembers : Boolean); \n end;\n\nimplementation\n\nconstructor DefaultValueInspector&lt;T&gt;(useHiddenMembers : Boolean);\nbegin\n var ctorInfo := typeOf(T).GetConstructor([]);\n constructor(ctorInfo.Invoke([]) as T, useHiddenMembers);\nend;\n\nconstructor DefaultValueInspector&lt;T&gt;(defaultInstance : T; useHiddenMembers : Boolean);\nbegin\n var bf := iif(useHiddenMembers, \n BindingFlags.NonPublic)\n or BindingFlags.Public\n or BindingFlags.Instance;\n\n for mi in typeOf(T).GetMembers(bf) do\n case mi.MemberType of\n MemberTypes.Field :\n with matching fi := FieldInfo(mi) do\n begin\n MembersByName.Add(fi.Name, fi);\n GettersByMember.Add(mi, obj -&gt; fi.GetValue(obj));\n end;\n MemberTypes.Property :\n with matching pi := PropertyInfo(mi) do\n if pi.GetIndexParameters().Length = 0 then\n begin\n MembersByName.Add(pi.Name, pi);\n GettersByMember.Add(mi, obj -&gt; pi.GetValue(obj, nil));\n end;\n end;\n\n for g in GettersByMember do\n with val := g.Value(DefaultInstance) do\n if assigned(val) then \n DefaultValuesByMember.Add(g.Key, val);\nend;\n\nclass method DefaultValueInspector&lt;T&gt;.GetMemberErrorMessage(memberName : String) : String;\nbegin\n exit \"The member '\" + memberName + \"' does not exist in type \" + typeOf(T).FullName \n + \" or it has indexers.\"\nend;\n\nmethod DefaultValueInspector&lt;T&gt;.get_DefaultValueByName(memberName : String): Object;\nbegin\n var mi := GetMember(memberName);\n DefaultValuesByMember.TryGetValue(mi, out result);\nend;\n\nmethod DefaultValueInspector&lt;T&gt;.get_DefaultValueByMember(memberInfo : MemberInfo) : Object;\nbegin\n if not DefaultValuesByMember.TryGetValue(memberInfo, out result) then\n raise new ArgumentException(GetMemberErrorMessage(memberInfo.Name),\n \"memberName\"); \nend;\n\nmethod DefaultValueInspector&lt;T&gt;.GetGetMethod(memberName : String) : Converter&lt;T, Object&gt;;\nbegin\n var mi := GetMember(memberName);\n exit GetGetMethod(mi);\nend;\n\nmethod DefaultValueInspector&lt;T&gt;.GetGetMethod(memberInfo : MemberInfo) : Converter&lt;T, Object&gt;;\nbegin\n if not GettersByMember.TryGetValue(memberInfo, out result) then\n raise new ArgumentException(GetMemberErrorMessage(memberInfo.Name),\n \"memberName\"); \nend;\n\nmethod DefaultValueInspector&lt;T&gt;.GetMember(memberName : String) : MemberInfo;\nbegin\n if not MembersByName.TryGetValue(memberName, out result) then\n raise new ArgumentException(GetMemberErrorMessage(memberName),\n \"memberName\"); \nend;\n\nmethod DefaultValueInspector&lt;T&gt;.HasDefaultValue(instance : T; memberName : String) : Boolean;\nbegin\n var getter := GetGetMethod(memberName);\n var instanceValue := getter(instance);\n exit Equals(DefaultValueByName[memberName], instanceValue);\nend;\n\nmethod DefaultValueInspector&lt;T&gt;.HasDefaultValue(instance : T; memberInfo : MemberInfo) : Boolean;\nbegin\n var getter := GetGetMethod(memberInfo);\n var instanceValue := getter(instance);\n exit Equals(DefaultValueByMember[memberInfo], instanceValue);\nend;\n</code></pre>\n" } ]
2008/11/07
[ "https://Stackoverflow.com/questions/271904", "https://Stackoverflow.com", "https://Stackoverflow.com/users/32136/" ]
Say you have a class declaration, e.g.: ``` class MyClass { int myInt=7; int myOtherInt; } ``` Now, is there a way in generic code, using reflection (or any other means, for that matter), that I can deduce that myInt has a default value assigned, whereas myOtherInt does not? Note the difference between being initialised with an explicit default value, and being left to it's implicit default value (myOtherInt will be initialised to 0, by default). From my own research it looks like there is no way to do this - but I thought I'd ask here before giving up. [Edit] Even with nullable and reference types I want to distingush between those that have been left as null, and those that have been explicitly initialised to null. This is so that I can say that fields with an initialiser are "optional" and other fields are "mandatory". At the moment I'm having to do this using attributes - which niggles me with their redundancy of information in this case.
I compiled your code and load it up in ILDASM and got this ``` .method public hidebysig specialname rtspecialname instance void .ctor() cil managed { // Code size 15 (0xf) .maxstack 8 IL_0000: ldarg.0 IL_0001: ldc.i4.7 IL_0002: stfld int32 dummyCSharp.MyClass::myInt IL_0007: ldarg.0 IL_0008: call instance void [mscorlib]System.Object::.ctor() IL_000d: nop IL_000e: ret } // end of method MyClass::.ctor ``` Note the `ldc.i4.7` and `stfld int32 dummyCSharp.MyClass::myInt` seems to be instructions to set the default values for the myInt field. **So such assignment is actually compiled as an additional assignment statement in a constructor.** To detect such assignment, then you will need reflection to reflect on the IL of MyClass's constructor method and look for `stfld` (set fields?) commands. --- EDIT: If I add some assignment into the constructor explicitly: ``` class MyClass { public int myInt = 7; public int myOtherInt; public MyClass() { myOtherInt = 8; } } ``` When I load it up in ILDASM, I got this: ``` .method public hidebysig specialname rtspecialname instance void .ctor() cil managed { // Code size 24 (0x18) .maxstack 8 IL_0000: ldarg.0 IL_0001: ldc.i4.7 IL_0002: stfld int32 dummyCSharp.MyClass::myInt IL_0007: ldarg.0 IL_0008: call instance void [mscorlib]System.Object::.ctor() IL_000d: nop IL_000e: nop IL_000f: ldarg.0 IL_0010: ldc.i4.8 IL_0011: stfld int32 dummyCSharp.MyClass::myOtherInt IL_0016: nop IL_0017: ret } // end of method MyClass::.ctor ``` Note that the extra assigment on myOtherInt that I added was addded *after* a call the Object class's constructor. ``` IL_0008: call instance void [mscorlib]System.Object::.ctor() ``` So there you have it, **Any assignment done *before* the call to Object class's constructor in IL is a default value assignment.** Anything following it is a statement inside the class's actual constructor code. More extensive test should be done though. p.s. that was fun :-)