input
stringlengths
51
42.3k
output
stringlengths
18
55k
Is it possible to change the natural order of columns in Postgres? <p>Is it possible to change the natural order of columns in Postgres 8.1?</p> <p>I know that you shouldn't rely on column order - it's not <em>essential</em> to what I am doing - I only need it to make some auto-generated stuff come out in a way that is more pleasing, so that the field order matches all the way from pgadmin through the back end and out to the front end.</p>
<p>You can actually just straight up change the column order, but I'd hardly recommend it, and you should be very careful if you decide to do it.</p> <p>eg.</p> <pre> # CREATE TABLE test (a int, b int, c int); # INSERT INTO test VALUES (1,2,3); # SELECT * FROM test; a | b | c ---+---+--- 1 | 2 | 3 (1 row) </pre> <p>Now for the tricky bit, you need to connect to your database using the postgres user so you can modify the system tables.</p> <pre> # SELECT relname, relfilenode FROM pg_class WHERE relname='test'; relname | relfilenode ---------+------------- test_t | 27666 (1 row) # SELECT attrelid, attname, attnum FROM pg_attribute WHERE attrelid=27666; attrelid | attname | attnum ----------+----------+-------- 27666 | tableoid | -7 27666 | cmax | -6 27666 | xmax | -5 27666 | cmin | -4 27666 | xmin | -3 27666 | ctid | -1 27666 | b | 1 27666 | a | 2 27666 | c | 3 (9 rows) </pre> <p>attnum is a unique column, so you need to use a temporary value when you're modifying the column numbers as such:</p> <pre> # UPDATE pg_attribute SET attnum=4 WHERE attname='a' AND attrelid=27666; UPDATE 1 # UPDATE pg_attribute SET attnum=1 WHERE attname='b' AND attrelid=27666; UPDATE 1 # UPDATE pg_attribute SET attnum=2 WHERE attname='a' AND attrelid=27666; UPDATE 1 # SELECT * FROM test; b | a | c ---+---+--- 1 | 2 | 3 (1 row) </pre> <p>Again, because this is playing around with database system tables, use extreme caution if you feel you really need to do this.</p> <p>This is working as of postgres 8.3, with prior versions, your milage may vary.</p>
Call Stack at Runtime <p>I want to access the call stack at runtime in a Native C++ application. I am not using the IDE. How do I display the call stack?</p> <p>Update: I have a function which is called from many points all over the application. It crashes on rare occasions. I was looking for a way to get name of the caller and log it.</p>
<p>Have a look at <a href="http://msdn.microsoft.com/en-us/library/ms680650%28VS.85%29.aspx" rel="nofollow">StackWalk64</a>.</p> <p>If you're used to doing this on .NET, then you're in for a nasty surprise.</p>
SWD files in Flash Player 9 <p>Does anybody have any pointers to what SWD files are in Flash 9, why Flash Player wants to download them sometimes, how to make ones, how to make use of them? Didn't manage to dig anything useful myself yet.</p> <p><em>Update</em></p> <p>I know roughly what are swd files used in Flash8, and <a href="http://livedocs.adobe.com/flex/15/flex_docs_en/wwhelp/wwhimpl/common/html/wwhelp.htm?context=Flex_Documentation&amp;file=00000838.htm" rel="nofollow">there is even a way to make them</a>, but Flash 9 doesn't seem to need it at first glance, but still attempts to use sometimes.</p>
<p>SWD files are needed to debug content with Adobe's debugging tools. You can see this in action by publishing from Flash authoring with shift-control-enter. </p> <p>The SWD itself is only needed for the debugging tool to see inside the SWF. You can throw it away once you're done debugging, and you never need to upload it to the server unless you're planning to do remote debugging.</p> <p>Docs:<br /> <a href="http://livedocs.adobe.com/flash/9.0/UsingFlash/help.html?content=WS3e7c64e37a1d85e1e229110db38dec34-7fc0.html" rel="nofollow">Debugging local files</a><br /> <a href="http://livedocs.adobe.com/flash/9.0/UsingFlash/help.html?content=WSE9184681-3417-4849-B487-8D6C2F8CC688.html" rel="nofollow">Debugging remote files</a></p>
GIS/Mapping solutions that provide easy access to routing data <p>I'm look for a GIS/Mapping tool that will give me easy SERVER-SIDE access to route information (specifically, trip time and distance) in an ASP.NET web application.</p> <p>From what I can tell, Google and Yahoo maps do everything client-side in javascript, but neither provide services to retrieve just the route information. I'm interested in both free and paid products. Also, if you have experience with a product I like to hear about what you think (complexity of API, runtime performance, likes, dislikes, etc.)</p>
<p>ESRI's ArcGIS Server and ArcWeb services provide point-to-point routing. You have full control over creating the data (if you want), changing the data, customizing parameters, and even adding dynamic cost analysis. Server might be a bit heavy-weight for JUST routing as its a full mapping and analysis server system. ArcWeb is an online service where you can buy just the services you want.</p> <p>Another option is Oracle Spatial. They have some built-in networking/routing capabilities to do point-to-point routing. I personally have been unable to get it to work, but I've heard second/third-hand comments that it works, but has the normal complexities of Oracle (i.e. not a DIY job).</p> <p>MapQuest also has a comprehensive set of API's (much better than Google or Yahoo IMHO) that can do routing without a map. Not sure what their licensing/costs are and how they compare to Google/Yahoo for non-personal use.</p> <p>(One note: many of the "free" services require you to pay a license fee for non-personal use... they might ignore you until your traffic gets high enough for them to notice so watch out)</p>
Algorithm for counting the number of unique colors in an image <p>Looking for one that is fast enough and still graceful with memory. The image is a 24bpp System.Drawing.Bitmap.</p>
<p>If you need an exact number, then you are going to have to loop over all of the pixels. Probably storing the color and a count in a hash is the best way to go because of the sparseness of the colors. </p> <p>Using the Color.ToArgb() in the hash instead of the color object would probably be a good idea too.</p> <p>Also, if speed is a major concern, you don't want to use a function like GetPixel(x, y) -- instead try to process chunks at a time (row a time). If you can, get a pointer to the beginning of the image memory and do it unsafe.</p>
How does SOA service discovery (UDDI) work in practice? <p>I'm just reading up on SOA and the service registry / UDDI get mentioned regularly. It sounds nice but how is used in reality?</p> <ul> <li>Is the registry meant to decouple a logical service from its' physical implementation (port, url etc)? </li> <li>Is the registry meant to be browsed by a human looking for an interesting service to play with?</li> <li>Would it be 'wrong' to hard-wire an application to the services it uses?</li> </ul>
<p>I find it to be more theoretically useful than practically useful. It is infrequently implemented and infrequently used. In reality, DNS provides a sufficient abstraction tool for the location of resources on the network. </p>
How accurate can I expect the time to be from a stratum 0 NTP server on the same subnet on ethernet? <p>I have an application that depends on gpsd and ntpd to accurately set the system time on a linux machine.</p> <p>gpsd is fed NMEA + PPS</p> <p>The application is punping ~25MB per second over the network and I think the loading on the system is causing jitter in the time somehow. (loaded PCI express bus causing irregular interrupt latency)</p> <p>I have another machine that is not loaded at all that I could setup to read the GPS and act as an NTP server for the loaded machine. (the loaded machine would be getting startum 1 ???)</p> <p><strong>How accurate can I expect the time to be from a stratum 0 NTP server on the same subnet on Ethernet?</strong></p> <p>I hope this is not too off topic, I am sure sometime someone else will be happy the answer is documented here. ;-)</p>
<p>Best info I could find on <a href="https://web.archive.org/web/20100414014404/http://www.netcordia.com/community/blogs/terrys_blog/archive/2008/01/07/ntp-accuracy.aspx" rel="nofollow">NTP accuracy</a>, seems to point at 1-2 ms in a LAN setting:</p> <blockquote> <p>NTP v4 with kernel mods to support it, is capable of much better than 1ms accuracy, possibly as good as 1ns. According to [Dave Mills] article, NTP v3 is accurate to 1-2ms in a LAN and 10s of ms in WAN nets. <a href="http://www.cis.udel.edu/~mills/ntp.html" rel="nofollow">http://www.cis.udel.edu/~mills/ntp.html</a></p> <p>Other articles suggest that with an accurate time source, such as a GPS time source, NTP is accurate to 50us, but the links on the Linux kernel support say that accuracy of a few ms are possible. <a href="http://www.atomic-clock.galleon.eu.com/support/ntp-time-server-accuracy.html" rel="nofollow">http://www.atomic-clock.galleon.eu.com/support/ntp-time-server-accuracy.html</a> </p> <p>Another article says that it is dependent on the predictability of network delays (i.e. a low jitter network). <a href="http://www.postel.org/pipermail/end2end-interest/2003-April/002925.html" rel="nofollow">http://www.postel.org/pipermail/end2end-interest/2003-April/002925.html</a> </p> </blockquote>
How to avoid storing credentials to connect to Oracle with JDBC? <p>Is it possible to setup a JDBC connection to Oracle without providing username/password information in a configuration file (or in any other standard readable location)?</p> <p>Typically applications have a configuration file that contains setup parameters to connect to a database. Some DBAs have problems with the fact that usernames and passwords are in clear text in config files.</p> <p>I don't think this is possible with Oracle and JDBC, but I need some confirmation...</p> <p>A possible compromise is to encrypt the password in the config file and decrypt it before setting up the connection. Of course, the decryption key should not be in the same config file. This will only solve accidental opening of the config file by unauthorized users.</p>
<p>You may want to try Kerberos which can use the OS user's credentials and adding the OS user to the database as identified externally. Make sure that you use Kerberos and not the old way of doing this, which had serious security issues.</p> <p>For Kerberos support you would need the advanced security option and a recent JDBC driver, probably 11g version. Before trying to get it to work in Java, try it out in Sql*Plus using '/' as username and empty password. "select user from dual" should give you user@domain. You may also find that there is a fundamental difference between using thin or OCI driver when it comes to Kerberos configuration.</p>
If you already know LISP, why would you also want to learn F#? <p>What is the added value for learning F# when you are already familiar with LISP?</p>
<ul> <li><a href="http://research.microsoft.com/fsharp/manual/quicktour.aspx#QuickTourTypes">Static typing</a> (with type inference)</li> <li><a href="http://research.microsoft.com/fsharp/manual/quicktour.aspx#QuickTourDiscriminatedUnions">Algebraic data types</a></li> <li><a href="http://research.microsoft.com/fsharp/manual/quicktour.aspx#QuickTourPatterns">Pattern matching</a></li> <li><a href="http://blogs.msdn.com/dsyme/archive/2007/04/07/draft-paper-on-f-active-patterns.aspx">Extensible pattern matching</a> with active patterns.</li> <li>Currying (with a nice syntax)</li> <li><a href="http://blogs.msdn.com/dsyme/archive/2007/10/11/introducing-f-asynchronous-workflows.aspx">Monadic programming</a>, called 'workflows', provides a nice way to do asynchronous programming.</li> </ul> <p>A lot of these are relatively recent developments in the programming language world. This is something you'll see in F# that you won't in Lisp, especially Common Lisp, because the F# standard is still under development. As a result, you'll find there is a quite a bit to learn. Of course things like ADTs, pattern matching, monads and currying can be built as a library in Lisp, but it's nicer to learn how to use them in a language where they are conveniently built-in.</p> <p>The biggest advantage of learning F# for real-world use is its integration with .NET.</p>
Is there a way to determine if an exception is occurring? <p>In a destructor, is there a way to determine if an exception is currently being processed?</p>
<p>You can use std::uncaught_exception(), but it might not do what you think it does: see <a href="http://www.gotw.ca/gotw/047.htm" rel="nofollow" title="GoTW#47">GoTW#47</a> for more information.</p>
Best design for lookup-and-possibly-change method <p>I am designing a class that stores (caches) a set of data. I want to lookup a value, if the class contains the value then use it and modify a property of the class. I am concerned about the design of the public interface.<br /> Here is how the class is going to be used:</p> <pre> ClassItem *pClassItem = myClass.Lookup(value); if (pClassItem) { // item is found in class so modify and use it pClassItem->SetAttribute(something); ... // use myClass } else { // value doesn't exist in the class so add it myClass.Add(value, something); } </pre> <p>However I don't want to have to expose ClassItem to this client (ClassItem is an implementation detail of MyClass). To get round that the following could be considered:</p> <pre> bool found = myClass.Lookup(value); if (found) { // item is found in class so modify and use it myClass.ModifyAttribute(value, something); ... // use myClass } else { // value doesn't exist in the class so add it myClass.Add(value, something); } </pre> <p>However this is inefficient as Modify will have to do the lookup again. This would suggest a lookupAndModify type of method:</p> <pre> bool found = myClass.LookupAndModify(value, something); if (found) { // item is found in class ... // use myClass } else { // value doesn't exist in the class so add it myClass.Add(value, something); } </pre> <p>But rolling LookupAndModify into one method seems like very poor design. It also only modifies if value is found and so the name is not only cumbersome but misleading as well.</p> <p>Is there another better design that gets round this issue? Any design patterns for this (I couldn't find anything through google)?</p>
<p>Actually <code>std::set&lt;&gt;::insert()</code> does precisely this. If the value exists, it returns the iterator pointing to the existing item. Otherwise, the iterator where the insertion was made is returned.</p> <p>It is likely that you are using a similar data structure for fast lookups anyway, so a clean public interface (calling site) will be:</p> <pre><code>myClass.SetAttribute(value, something) </code></pre> <p>which always does the right thing. MyClass handles the internal plumbing and clients don't worry about whether the value exists.</p>
Keyboard shortcuts in an XBAP <p>I would like to support keyboard shortcuts in my WPF XBAP application, such as <kbd>Ctrl</kbd>+<kbd>O</kbd> for 'Open' etc. How do I disable the browsers built-in keyboard shortcuts and replace them with my own?</p>
<p>You can't disable the browser's built-in handling of keys. It's not your place as browser content to override the browser's own shortcut keys.</p>
Copy / Put text on the clipboard with FireFox, Safari and Chrome <p>In Internet Explorer I can use the clipboardData object to access the clipboard. How can I do that in FireFox, Safari and/or Chrome?</p>
<p>For security reasons, Firefox doesn't allow you to place text on the clipboard. However, there is a work-around available using Flash.</p> <pre><code>function copyIntoClipboard(text) { var flashId = 'flashId-HKxmj5'; /* Replace this with your clipboard.swf location */ var clipboardSWF = 'http://appengine.bravo9.com/copy-into-clipboard/clipboard.swf'; if(!document.getElementById(flashId)) { var div = document.createElement('div'); div.id = flashId; document.body.appendChild(div); } document.getElementById(flashId).innerHTML = ''; var content = '&lt;embed src="' + clipboardSWF + '" FlashVars="clipboard=' + encodeURIComponent(text) + '" width="0" height="0" type="application/x-shockwave-flash"&gt;&lt;/embed&gt;'; document.getElementById(flashId).innerHTML = content; } </code></pre> <p>The only disadvantage is that this requires Flash to be enabled.</p> <p>source is currently dead: <a href="http://bravo9.com/journal/copying-text-into-the-clipboard-with-javascript-in-firefox-safari-ie-opera-292559a2-cc6c-4ebf-9724-d23e8bc5ad8a/" rel="nofollow">http://bravo9.com/journal/copying-text-into-the-clipboard-with-javascript-in-firefox-safari-ie-opera-292559a2-cc6c-4ebf-9724-d23e8bc5ad8a/</a> (and so is it's <a href="http://webcache.googleusercontent.com/search?q=cache:DaMt_LgPWUYJ:rokr-blargh.appspot.com/copying-text-into-the-clipboard-with-javascript-in-firefox-safari-ie-opera-292559a2cc6c4ebf9724d23e8bc5ad8a%20&amp;cd=1&amp;hl=en&amp;ct=clnk&amp;gl=us" rel="nofollow">Google cache</a>) </p>
QTP_errObject CaptureBitmap <p>May I request you to clarify the issue I have with QTP err object.</p> <p>I am trying to capture the screen shot of an object on which error occured. I use the code <code>object.captureBitmap(filename)</code> to achieve this.</p> <p>I would like to know if it is possible to get the screen shot of the entire page with the err object higlighted.</p>
<p>You can get this in your results file. go to tools->options and select the run tab. Check the box "Save still image captures to results" and select either always or for errors. When you run your test it will show the full screen and highlight the object it has a problem with, if it could find it.</p>
Good Haskell coding style of if/else control block? <p>I'm learning Haskell hope it could let me getting closer to functional programming, before learing it, I mostly use C-sytanx like languages, like C, Java or D Programming Language.</p> <p>I followed the <a href="http://en.wikibooks.org/wiki/Haskell/Simple_input_and_output">tutorial on Wikibook</a>, it goes well so far, I could understand most of them before the chapter "Simple input and output"</p> <p>But I do have a little question about the coding style of if/else control block used by the tutorial.</p> <p>In the wikibook, the code look like the following:</p> <pre><code>doGuessing num = do putStrLn "Enter your guess:" guess &lt;- getLine if (read guess) &lt; num then do putStrLn "Too low!" doGuessing num else if (read guess) &gt; num then do putStrLn "Too high!" doGuessing num else do putStrLn "You Win!" </code></pre> <p>It makes me confusing, because this coding style is totally volate "Good Coding Style" in C-sytnax like programming language, where we should ident if/else if/else at same column.</p> <p>I know it just not work in Haskell, because it would cause parse error if I ident "else" at same column of "if".</p> <p>But what about the following one? I think it is much more clear then the above one. But since the above is used by Wikibook and Yet Another Haskell Tutorial, which marked "best tutorial available online" at offical Haskell website, so I'm not sure whether this coding style is a convention in Haskell programs.</p> <pre><code>doGuessing num = do putStrLn "Enter your guess:" guess &lt;- getLine if (read guess) &lt; num then do putStrLn "Too low!" doGuessing num else if (read guess) &gt; num then do putStrLn "Too high!" doGuessing num else do putStrLn "You Win!" </code></pre> <p>So, I'm curious about which coding style is used more often or is there anthoer coding style for this piece of code? I would like to know it too.</p>
<p>Haskell style is functional, not imperative! Rather than "do this then that," think about combining functions and describing <em>what</em> your program will do, not how.</p> <p>In the game, your program asks the user for a guess. A correct guess is a winner. Otherwise, the user tries again. The game continues until the user guesses correctly, so we write that:</p> <pre><code>main = untilM (isCorrect 42) (read `liftM` getLine) </code></pre> <p>This uses a combinator that repeatedly runs an action (<code>getLine</code> pulls a line of input and <code>read</code> converts that string to an integer in this case) and checks its result:</p> <pre><code>untilM :: Monad m =&gt; (a -&gt; m Bool) -&gt; m a -&gt; m () untilM p a = do x &lt;- a done &lt;- p x if done then return () else untilM p a </code></pre> <p>The predicate (partially applied in <code>main</code>) checks the guess against the correct value and responds accordingly:</p> <pre><code>isCorrect :: Int -&gt; Int -&gt; IO Bool isCorrect num guess = case compare num guess of EQ -&gt; putStrLn "You Win!" &gt;&gt; return True LT -&gt; putStrLn "Too high!" &gt;&gt; return False GT -&gt; putStrLn "Too low!" &gt;&gt; return False </code></pre> <p>The action to be run until the player guesses correctly is</p> <pre><code>read `liftM` getLine </code></pre> <p>Why not keep it simple and just compose the two functions?</p> <pre>*Main> :type read . getLine &lt;interactive>:1:7: Couldn't match expected type `a -> String' against inferred type `IO String' In the second argument of `(.)', namely `getLine' In the expression: read . getLine</pre> <p>The type of <code>getLine</code> is <code>IO String</code>, but <code>read</code> wants a pure <code>String</code>.</p> <p>The function <a href="http://www.haskell.org/ghc/docs/latest/html/libraries/base/Control-Monad.html#v%3AliftM"><code>liftM</code></a> from Control.Monad takes a pure function and “lifts” it into a monad. The type of the expression tells us a great deal about what it does:</p> <pre>*Main> :type read `liftM` getLine read `liftM` getLine :: (Read a) => IO a</pre> <p>It's an I/O action that when run gives us back a value converted with <code>read</code>, an <code>Int</code> in our case. Recall that <code>readLine</code> is an I/O action that yields <code>String</code> values, so you can think of <code>liftM</code> as allowing us to apply <code>read</code> “inside” the <code>IO</code> monad.</p> <p>Sample game:</p> <pre>1 Too low! 100 Too high! 42 You Win!</pre>
Is it possible to subclass a C struct in C++ and use pointers to the struct in C code? <p>Is there a side effect in doing this:</p> <p>C code:</p> <pre><code>struct foo { int k; }; int ret_foo(const struct foo* f){ return f.k; } </code></pre> <p>C++ code:</p> <pre><code>class bar : public foo { int my_bar() { return ret_foo( (foo)this ); } }; </code></pre> <p>There's an <code>extern "C"</code> around the C++ code and each code is inside its own compilation unit.</p> <p>Is this portable across compilers?</p>
<p>This is entirely legal. In C++, classes and structs are identical concepts, with the exception that all struct members are public by default. That's the only difference. So asking whether you can extend a struct is no different than asking if you can extend a class.</p> <p>There is one caveat here. There is <em>no guarantee</em> of layout consistency from compiler to compiler. So if you compile your C code with a different compiler than your C++ code, you may run into problems related to member layout (padding especially). This can even occur when using C and C++ compilers from the same vendor.</p> <p>I <em>have</em> had this happen with gcc and g++. I worked on a project which used several large structs. Unfortunately, g++ packed the structs significantly looser than gcc, which caused significant problems sharing objects between C and C++ code. We eventually had to manually set packing and insert padding to make the C and C++ code treat the structs the same. Note however, that this problem can occur regardless of subclassing. In fact we weren't subclassing the C struct in this case.</p>
Is there a rating system for the maintainability of source code? <p>I'm interested in finding some software that can analyze some C# files or an entire C# project/solution and give it a score which rates its ease or difficulty to maintain. Are there products or methods out there that do this?</p>
<p>There is a Tool called SourceMonitor. It scans and analyzes your source code and rates it. You can find it here <a href="http://www.campwoodsw.com/" rel="nofollow">http://www.campwoodsw.com/</a></p>
How to write a class library for OLE Automation? <p>I have Excel add-in which I add so many class modules that it is now very bulky. I want to convert it into a type library or a COM package so that I can re-use it for the other apps in the MS Office suite.</p> <p>I ported the add-in to Visual Studio as a class library project but Excel Automation doesn't recognize the classes in the compiled .dll file. Intuitively I think I would need a manifest, an interface or the something like that in my code.</p> <p>What do I need to know in order to expose a class's methods and properties for use in OLE Automation?</p>
<p>I am assuming since you used the phrase manifest, you are assembling this DLL using a .net development platform VS2003, VS2005 or VS2008 as compared to a VS 6.0 </p> <p>This <a href="http://dn.codegear.com/article/32754" rel="nofollow">link</a> provides a detailed set of steps required to register a .NET assembly for use as COM component. </p> <p>The one thing the article doesn't mention that I routinely do is create my own GUIDs. Use the Create GUID item in the Tools menu then insert them above the classes, interfaces, and enums you want exposed for COM. </p> <pre><code>[Guid("3838ADC1-E901-4003-BD0C-A889A7CF25A1")] public interface IMyCOMClass { void MyMethod(); } [Guid("476BDEB6-B933-4ed5-8B86-7D9330A59356"), ClassInterface(ClassInterfaceType.None)] public class MyCOMClass : IMyCOMClass { public void MyMethod() { //implementation here } } </code></pre> <p>The second thing I do is use a separate interface for the COM portion that is implemented by the class. The reasoning for doing this has to do with the breakability of COM when the interface changes, think DLL Hell. </p> <p>Hope this helps, Bill.</p>
How do I reorder the fields/columns in a SharePoint view? <p>I'm adding a new field to a list and view. To add the field to the view, I'm using this code:</p> <pre><code>view.ViewFields.Add("My New Field"); </code></pre> <p>However this just tacks it on to the end of the view. How do I add the field to a particular column, or rearrange the field order? view.ViewFields is an SPViewFieldCollection object that inherits from SPBaseCollection and there are no Insert / Reverse / Sort / RemoveAt methods available.</p>
<p>I've found removing all items from the list and readding them in the order that I'd like works well (although a little drastic). Here is the code I'm using:</p> <pre><code>string[] fieldNames = new string[] { "Title", "My New Field", "Modified", "Created" }; SPViewFieldCollection viewFields = view.ViewFields; viewFields.DeleteAll(); foreach (string fieldName in fieldNames) { viewFields.Add(fieldName); } view.Update(); </code></pre>
How to programmatically change the work flow between SSIS control flow tasks? <p>I have an SSIS package, which depending on a boolean variable, should either go to a Script Task or an Email task.(Note: the paths are coming <em>from</em> a Script Task)</p> <p>I recall in the old dts designer there was a way to do this via code. What is the proper way to accomplish this in SSIS?</p>
<blockquote> <p>Isn't a Conditional Split a data flow task, which takes a row of data and pushes it in one of two directions according to some property of the data???</p> </blockquote> <p>Oops, that is correct. I found <a href="http://dichotic.wordpress.com/2006/11/01/ssis-test-for-data-files-existence/" rel="nofollow">this</a> blog entry which explains how to do proper control flow conditional branching based on boolean values.</p>
Is there a good tool for MySQL that will help me optimise my queries and index settings? <p>I use MySQL in a fairly complex web site (PHP driven).</p> <p>Ideally, there would be a tool I could use that would help me test the SQL queries I am using and suggest better table indexes that will improve performance and avoid table scans.</p> <p>Failing that, something that will tell me exactly what each query is up to, so I can perform the optimisation myself.</p> <p>Edit: a simple guide to understanding the output from EXPLAIN ... would also be useful.</p> <p>Thank you.</p>
<p>OK, before my answer, subscribe to the <a href="http://www.mysqlperformanceblog.com/">MySQL Performance Blog</a>, I've learned a lot (and I thought I already knew a lot about MySQL). Also, he's got a bitchin' tools page <a href="http://www.mysqlperformanceblog.com/tools/">here</a>.</p> <p>Second off, here's some info about EXPLAIN (referenced from the High Performance MySQL book from O'Reilly):</p> <p>When you run an EXPLAIN on a query, it tells you everything MySQL knows about that query in the form of reports for each table involved in the query.</p> <p>Each of these reports will tell you...</p> <ul> <li>the ID of the table (in the query)</li> <li>the table's role in a larger selection (if applicable, might just say SIMPLE if it's only one table)</li> <li>the name of the table (duh)</li> <li>the join type (if applicable, defaults to <em>const</em>)</li> <li>a list of indexes on the table (or NULL if none), *possible_keys*</li> <li>the name of the index that MySQL decided to use, <em>key</em></li> <li>the size of the key value (in bytes)</li> <li><em>ref</em> shows the cols or values used to match against the key</li> <li><em>rows</em> is the number of rows that MySQL thinks it needs to examine in order to satisfy the query. <strong>This should be kept as close to your calculated minimum as possible!</strong></li> <li>...then any extra information MySQL wishes to convey</li> </ul> <p>The book is completely awesome at providing information like this, so if you haven't already, get your boss to sign off on a purchase.</p> <p>Otherwise, I hope some more knowledgeable SO user can help :)</p>
Is every DDL SQL command reversible? [database version control] <p>I want to setup a mechanism for tracking DB schema changes, such the one described in <a href="http://stackoverflow.com/questions/1607/mechanisms-for-tracking-db-schema-changes#1666">this answer</a>:</p> <blockquote> <p>For every change you make to the database, you write a new migration. Migrations typically have two methods: an "up" method in which the changes are applied and a "down" method in which the changes are undone. A single command brings the database up to date, and can also be used to bring the database to a specific version of the schema.</p> </blockquote> <p>My question is the following: Is every DDL command in an "up" method reversible? In other words, can we always provide a "down" method? Can you imagine any DDL command that can not be "down"ed? </p> <p>Please, do not consider the typical data migration problem where during the "up" method we have loss of data: e.g. changing a field type from <code>datetime</code> (<code>DateOfBirth</code>) to <code>int</code> (<code>YearOfBirth</code>) we are losing data that can not be restored.</p>
<p>in sql server every DDL command that i know of is an up/down pair.</p>
Which design patterns are underutilized? <p>Is there a specfic <a href="http://en.wikipedia.org/wiki/Design_Patterns" rel="nofollow">Gang Of Four Design Pattern</a> that you frequently use, yet hardly see used in other peoples designs? If possible, please describe a simple example where this pattern can be useful. It doesn't have to necessarily be a Gang Of Four pattern, but please include a hyperlink to the pattern's description if you choose a non-GoF pattern.</p> <p>Put another way:<br /> <strong>What are some good/useful design patterns that I, or someone else who does have a passing knowledge of the main patterns, may not already know?</strong></p>
<p>Steve Yegge wrote a (typically) long <a href="http://steve-yegge.blogspot.com/2007/12/codes-worst-enemy.html" rel="nofollow">blog entry about the Interpreter Pattern</a>, making the claim that this pattern is the only GoF pattern that can make code "smaller", and is criminally underutilized by programmers who otherwise are quite comfortable with the other GoF patterns. I am one of those programmers - I've never used the Interpreter pattern, although I recognize it's importance to things like DSL's. Anyway, it's a very thought-provoking essay if you have the intestinal fortitude to read an entire Yegge post.</p>
Assembler file as input for a driver build with the WDK tools <p>How to get an assembler file to be compiled and linked into a driver build.</p> <p>To clarify a bit</p> <p>The SOURCES file :</p> <pre><code>TARGETTYPE=DRIVER DRIVERTYPE=WDM TARGETPATH=obj TARGETNAME=bla INCLUDES=$(DDK_INC_PATH) TARGETLIBS=$(DDK_LIB_PATH)\ks.lib SOURCES=x.cpp y.cpp z.asm </code></pre> <p>The problem occurs with the <code>z.asm file</code>. <code>NMAKE</code> complains that it does not know how to build <code>z.obj</code>.</p> <p>So the question is, how to get the asm file assembled with <code>build</code> and linked into <code>bla.sys</code>.</p>
<p>Have you tried the I386_SOURCES?</p> <p>E.g</p> <pre><code>SOURCES=x.cpp y.cpp I386_SOURCES=i386\z.asm </code></pre> <p>And putting the file in the i386 directory.<br> Also see <a href="http://msdn.microsoft.com/en-us/library/ms792148.aspx">MSDN</a> regarding the SOURCES macro</p>
Retrieve Error text from SQL Server 2000 error <p>I need help logging errors from T-SQL in SQL Server 2000. We need to log errors that we trap, but are having trouble getting the same information we would have had sitting in front of SQL Server Management Studio.</p> <p>I can get a message without any argument substitution like this:</p> <pre><code>SELECT MSG.description from master.dbo.sysmessages MSG INNER JOIN sys.syslanguages LANG ON MSG.msglangID=LANG.msglangid WHERE MSG.error=@err AND LANG.langid=@@LANGID </code></pre> <p>But I have not found any way of finding out the error arguments. I want to see:</p> <p>Constraint violation MYCONSTRAINT2 on table MYTABLE7</p> <p>not</p> <p>Constraint violation %s on table %s</p> <p>Googling has only turned up exotic schemes using DBCC OUTPUTBUFFER that require admin access and aren't appropriate for production code. How do I get an error message with argument replacement?</p>
<p>In .Net, retrieving error messages (and anything output from <em>print</em> or <em>raiserror</em>) from sql server is as simple as setting one property on your SqlConnection ( <em>.FireInfoMessageEventOnUserErrors = True</em>) and handling the connection's InfoMessage event. The data received by .Net matches what you get in the <em>Messages</em> window in the SQL Server Management Studio results grid.</p> <p>All the code goes in the function that handles the event, and you can abstract that so that all your connections point to the same method, so there's nothing else to change in the rest of the app aside from the two lines of code when you create new connections to set the property and event (<em>and you have that abstracted away so you only need to do it in one place, right?</em>)</p> <p>Here is a link to what I consider the <a href="http://www.sommarskog.se/error-handling-I.html" rel="nofollow">definitive error guide for SQL Server</a>.<br /> <a href="http://www.sommarskog.se/error-handling-I.html" rel="nofollow">http://www.sommarskog.se/error-handling-I.html</a></p> <p>In certain circumstances SQL Server will continue processing even after an error. See the heading labeled <em><a href="http://www.sommarskog.se/error-handling-I.html#whathappens" rel="nofollow">What Happens when an Error Occurs?</a></em> from the previous link.</p>
PHP: using preg_replace with htmlentities <p>I'm writing an <code>RSS</code> to <code>JSON parser</code> and as a part of that, I need to use <code>htmlentities()</code> on any tag found inside the description tag. Currently, I'm trying to use <code>preg_replace()</code>, but I'm struggling a little with it. My current (non-working) code looks like:</p> <pre><code>$pattern[0] = "/\&lt;description\&gt;(.*?)\&lt;\/description\&gt;/is"; $replace[0] = '&lt;description&gt;'.htmlentities("$1").'&lt;/description&gt;'; $rawFeed = preg_replace($pattern, $replace, $rawFeed); </code></pre> <p>If you have a more elegant solution to this as well, please share. Thanks.</p>
<p>Simple. Use <code>preg_replace_callback</code>:</p> <pre><code>function _handle_match($match) { return '&lt;description&gt;' . htmlentities($match[1]) . '&lt;/description&gt;'; } $pattern = "/\&lt;description\&gt;(.*?)\&lt;\/description\&gt;/is"; $rawFeed = preg_replace_callback($pattern, '_handle_match', $rawFeed); </code></pre> <p>It accepts any callback type, so also methods in classes.</p>
Reverse-projection 2D points into 3D <p>Suppose we have a 3d Space with a plane on it with an arbitary equation : ax+by+cz+d=0 now suppose that we pick 3 random points on that plane: (x0,y0,z0) (x1,y1,z1) (x1,y1,z1)</p> <p>now i have a different point of view(camera) for this plane. i mean i have a different camera that will look at this plane from a different point of view. From that camera point of view these points have different locations. for example (x0,y0,z0) will be (x0',y0') and (x1,y1,z1) will be (x1',y1') and (x2,y2,z2) will be (x2',y2') from the new camera point of view.</p> <p>So here is my a little hard question! I want to pick a point for example (X,Y) from the new camera point of view and tell where it will be on that plane. All i know is that 3 points and their locations on 3d space and their projection locations on the new camera view.</p> <p><hr /></p> <p>Do you know the coefficients of the plane-equation and the camera positions (along with the projection), or do you only have the six points? - Nils</p> <p>i know the location of first 3 points. therefore we can calculate the coefficients of the plane. so we know exactly where the plane is from (0,0,0) point of view. and then we have the camera that can only see the points! So the only thing that camera sees is 3 points and also it knows their locations in 3d space (and for sure their locations on 2d camera view plane). and after all i want to look at camera view, pick a point (for example (x1,y1)) and tell where is that point on that plane. (for sure this (X,Y,Z) point should fit on the plane equation). Also i know nothing about the camera location.</p>
<p>It is not possible to give an unambiguous solution to this problem. However, here's how I would extract the different solutions:</p> <p>1) Solve for the camera position and direction using the P3P (Perspective-3-Point) algorithm from the original <a href="http://www.ai.sri.com/pubs/files/836.pdf" rel="nofollow">RANSAC paper</a>, which give up to four possible feasible solutions (with the points in front of the camera).</p> <p>2) Project a ray with the camera position as origin having (X,Y) as projection in the camera and calculate its intersection with the plane.</p>
Best Practices for reusing code between controllers in Ruby on Rails <p>I have some controller methods I'd like to share. What is the best practice for doing this in ruby on rails? Should I create an abstract class that my controllers extend, or should I create module and add it in to each controller? Below are the controller methods I want to share:</p> <pre><code>def driving_directions @address_to = params[:address_to] @address_from = params[:address_from] @map_center = params[:map_center_start] # if we were not given a center point to start our map on # let's create one. if !@map_center &amp;&amp; @address_to @map_center = GeoKit::Geocoders::MultiGeocoder.geocode(@address_to).ll elsif !@map_center &amp;&amp; @address_from @map_center = GeoKit::Geocoders::MultiGeocoder.geocode(@address_from).ll end end def printer_friendly starting_point = params[:starting_point].split(',').collect{|e|e.to_f} ne = params[:ne].split(',').collect{|e|e.to_f} sw = params[:sw].split(',').collect{|e|e.to_f} size = params[:size].split(',').collect{|e|e.to_f} address = params[:address] @markers = retrieve_points(ne,sw,size,false) @map = initialize_map([[sw[0],sw[1]],[ne[0],ne[1]]],[starting_point[0],starting_point[1]],false,@markers,true) @address_string = address end </code></pre>
<p>In my opinion, normal OO design principles apply:</p> <ul> <li>If the code is really a set of utilities that doesn't need access to object state, I would consider putting it in a module to be called separately. For instance, if the code is all mapping utilities, create a module <code>Maps</code>, and access the methods like: <code>Maps::driving_directions</code>.</li> <li>If the code needs state and is used or could be used in every controller, put the code in ApplicationController.</li> <li>If the code needs state and is used in a subset of all controllers that are closely and logically related (i.e. all about maps) then create a base class (<code>class MapController &lt; ApplicationController</code>) and put the shared code there.</li> <li>If the code needs state and is used in a subset of all controllers that are not very closely related, put it in a module and include it in necessary controllers.</li> </ul> <p>In your case, the methods need state (<code>params</code>), so the choice depends on the logical relationship between the controllers that need it. In addition:</p> <p>Also:</p> <ul> <li>Use partials when possible for repeated code and either place in a common 'partials' directory or include via a specific path.</li> <li>Stick to a RESTful approach when possible (for methods) and if you find yourself creating a lot of non-RESTful methods consider extracting them to their own controller.</li> </ul>
How do I write a working IThumbnailProvider for Windows Vista <p>I have written a thumbnail provider following the interfaces specified on MSDN. However, I have been unable to figure out how to register it in a way that Vista actually calls into it. Has anyone gotten a thumbnail provider working for Vista? Sample code or links would be especially helpful.</p>
<p>The <a href="http://msdn.microsoft.com/en-us/library/cc144118(VS.85).aspx#reg" rel="nofollow">documented</a> way to register your IThumbnailProvider is to create a registry entry at HKCR\.ext\ShellEx\{E357FCCD-A995-4576-B01F-234630154E96} and set the (Default) string value to the GUID of your IThumbnailProvider.</p> <p>Your assembly will need to be registered first. If using .NET, that means you will need to use the RegAsm.exe tool to register it.</p> <p>There is sample code available here: <a href="http://www.benryves.com/?mode=filtered&amp;single_post=3189294" rel="nofollow">http://www.benryves.com/?mode=filtered&amp;single_post=3189294</a></p>
Recovering browser textareas <p>Is there a way to recover the contents of a browser textarea? Say, you've typed a long post and then accidentally clicked on a link. Then when you come back, the textfields tantalizingly retain the text you typed in, but the textarea is blank. Where does IE and Firefox store the stuff that prepopulates? Can textareas be brought back? </p>
<p>Whenever I type something really long, I always copy it to my clipboard before submitting the form in case something happens. Or, sometimes I type it in Notepad and copy it over when I'm done. That may not be the answer you're looking for, but it might help.</p>
When do I use the PHP constant "PHP_EOL"? <p>When is it a good idea to use <a href="http://us3.php.net/manual/en/reserved.constants.php"><code>PHP_EOL</code></a>?</p> <p>I sometimes see this in code samples of PHP. Does this handle DOS/Mac/Unix endline issues?</p>
<p>Yes, PHP_EOL is ostensibly used to find the newline character in a cross-platform-compatible way, so it handles DOS/Mac/Unix issues.</p>
Problem POSTing to webservice in .net 3.5 solution <p>I'm at my wit's end here. I'm trying to use an auto-complete extender from the asp.net ajax extensions toolkit, which is filled from a bog-standard webservice. The application is a .net 3.5 web site, hosting the webservice in a subdirectory (real, not virtual).</p> <p>Whenever I try to post to the webservice I get the following error: <b>The HTTP verb POST used to access path '/Workarea/webservices/FindAdvisorNameService.asmx/FindAdvisorName' is not allowed.</b></p> <p>To complicate matters, a co-worker of mine pulled down the solution and can run it fine. </p> <p>After doing some Googling, it seems that there are some issues with URL rewriting, so I had him try using my web.config -- he still has no problem, and I still have no success.</p> <p>Anyone have any thoughts on what could be up, or where to start looking?</p> <p>To complicate matters, this is an <a href="http://www.ektron.com" rel="nofollow">Ektron CMS400.Net</a> solution, but he has the same version of Ektron installed that I do. The project was recently upgraded from the 2.0 to 3.5 framework, but still, it's in 3.5 on his machine as well.</p> <p>I've checked the IIS mappings, and GET, POST, and DEBUG are allowed on ASMX files.</p> <p>Help me Obi-Wan KeSObi, you're my only hope!</p> <p>Edit: Oh, yeah, to complicate matters, this is a brand new machine I have, so there's not likely to be that much weird stuff in the registry, etc. etc.. The co-worker's machine is almost as new.</p>
<p>Ok, found the issue with the help of a colleague. Seems the Ektron CMS added a mapping in IIS -- it mapped * to aspnet_isapi.dll. That overrode all the other mappings. I deleted that, and now things work.</p>
Parsing XML with namespaces using jQuery $().find <p>I'm trying to get the contents of a XML document element, but the element has a colon in it's name.</p> <p>This line works for every element but the ones with a colon in the name:</p> <pre><code>$(this).find("geo:lat").text(); </code></pre> <p>I assume that the colon needs escaping. How do I fix this?</p>
<p>Use a backslash, which itself should be escaped so JavaScript doesn't eat it:</p> <pre><code>$(this).find("geo\\:lat").text(); </code></pre>
How can I make Ruby's SOAP::RPC::Driver work with self signed certificates? <p>How can I prevent this exception when making a soap call to a server that is using a self signed certificate?</p> <pre><code>require "rubygems" gem "httpclient", "2.1.2" require 'http-access2' require 'soap/rpc/driver' client = SOAP::RPC::Driver.new( url, 'http://removed' ) client.options[ 'protocol.http.ssl_config.verify_mode' ] = OpenSSL::SSL::VERIFY_NONE client.options[ 'protocol.http.basic_auth' ] &lt;&lt; [ url, user, pass ] at depth 0 - 18: self signed certificate /opt/local/lib/ruby/1.8/soap/streamHandler.rb:200:in `send_post': 415: (SOAP::HTTPStreamError) from /opt/local/lib/ruby/1.8/soap/streamHandler.rb:109:in `send' from /opt/local/lib/ruby/1.8/soap/rpc/proxy.rb:170:in `route' from /opt/local/lib/ruby/1.8/soap/rpc/proxy.rb:141:in `call' from /opt/local/lib/ruby/1.8/soap/rpc/driver.rb:178:in `call' </code></pre>
<p>Try:</p> <pre><code>client.options["protocol.http.ssl_config.verify_mode"] = nil </code></pre>
Best tool for Software System Diagramming <p>Over the years, I have tried many times to find a good, easy to use, cross platform tool for some basic software system diagramming. The UML tools I have tried seemed to get in my way more than help. So far, the solution I keep returning to is Visio, which is both Windows-only and expensive. Although its far from ideal, it does provide some basic building block and allows things like grid placement and zooming. I wanted to see if there is a great tool out there that I'm just missing that fits at least some of the criteria mentioned.</p>
<p>You could try DIA, though it is a bit basic it will keep out of your way when doing pure diagrams.</p> <p><a href="http://www.gnome.org/projects/dia/" rel="nofollow">http://www.gnome.org/projects/dia/</a></p>
SQL sp_help_operator <p>Anyone know what group I need to belong to show up in the sp_help_operator list?</p>
<p>Judging from the docs for <code>sp_help_operator</code>, it looks like you need to explicitly add/remove operators using <code>sp_add_operator</code> and <code>sp_delete_operator</code>.</p> <p><a href="http://msdn.microsoft.com/en-us/library/aa238703(SQL.80).aspx" rel="nofollow">http://msdn.microsoft.com/en-us/library/aa238703(SQL.80).aspx</a></p>
Who uses a digital notepad for saving UML and other diagrams? <p>I often find that for an initial design document, I just want to lob in a couple of rough UML / other diagrams. </p> <p>Most diagramming tools, even Visio, slow me down considerably. I admit that this is probably <a href="http://en.wikipedia.org/wiki/PEBKAC" rel="nofollow">PEBCAK</a>.</p> <p>I usually end up drawing a sketch, and then running it through a scanner.</p> <p>I was wondering who uses a digital notepad, and would they recommend it?</p>
<p>I am also more the pen and paper guy, but I recently found <a href="http://abstratt.com/textuml/" rel="nofollow">textuml</a> and want to give a try as it seems more natural for a developer to do things in text and let the tool do the graphics magic.</p>
Absolute URL from base + relative URL in C# <p>I have a base URL :</p> <pre><code>http://my.server.com/folder/directory/sample </code></pre> <p>And a relative one :</p> <pre><code>../../other/path </code></pre> <p>How to get the absolute URL from this ? It's pretty straighforward using string manipulation, but I would like to do this in a secure way, using the <code>Uri</code> class or something similar.</p> <p>It's for a standard a C# app, not an ASP.NET one.</p>
<pre><code>var baseUri = new Uri("http://my.server.com/folder/directory/sample"); var absoluteUri = new Uri(baseUri,"../../other/path"); </code></pre> <p>OR</p> <pre><code>Uri uri; if ( Uri.TryCreate("http://base/","../relative", out uri) ) doSomething(uri); </code></pre>
When should I use Debug.Assert()? <p>I've been a professional software engineer for about a year now, having graduated with a CS degree. I've known about assertions for a while in C++ and C, but had no idea they existed in C# and .NET at all until recently.</p> <p>Our production code contains no asserts whatsoever and my question is this...</p> <p>Should I begin using Asserts in our production code? And if so, When is its use most appropriate? Would it make more sense to do</p> <pre><code>Debug.Assert(val != null); </code></pre> <p>or</p> <pre><code>if ( val == null ) throw new exception(); </code></pre>
<p>In <a href="http://rads.stackoverflow.com/amzn/click/0735622027">Debugging Microsoft .NET 2.0 Applications</a> John Robbins has a big section on assertions. His main points are:</p> <ol> <li>Assert liberally. You can never have too many assertions.</li> <li>Assertions don't replace exceptions. Exceptions cover the things your code demands; assertions cover the things it assumes.</li> <li>A well-written assertion can tell you not just what happened and where (like an exception), but why.</li> <li>An exception message can often be cryptic, requiring you to work backwards through the code to recreate the context that caused the error. An assertion can preserve the program's state at the time the error occurred.</li> <li>Assertions double as documentation, telling other developers what implied assumptions your code depends on.</li> <li>The dialog that appears when an assertion fails lets you attach a debugger to the process, so you can poke around the stack as if you had put a breakpoint there.</li> </ol> <p>PS: If you liked Code Complete, I recommend following it up with this book. I bought it to learn about using WinDBG and dump files, but the first half is packed with tips to help avoid bugs in the first place.</p>
How to avoid storing passwords in the clear for tomcat's server.xml Resource definition of a DataSource? <p>The resource definition in tomcat's <code>server.xml</code> looks something like this...</p> <pre class="lang-xml prettyprint-override"><code>&lt;Resource name="jdbc/tox" scope="Shareable" type="javax.sql.DataSource" url="jdbc:oracle:thin:@yourDBserver.yourCompany.com:1521:yourDBsid" driverClassName="oracle.jdbc.pool.OracleDataSource" username="tox" password="toxbaby" maxIdle="3" maxActive="10" removeAbandoned="true" removeAbandonedTimeout="60" testOnBorrow="true" validationQuery="select * from dual" logAbandoned="true" debug="99"/&gt; </code></pre> <p>The password is in the clear. How to avoid this?</p>
<p>As said before encrypting passwords is just moving the problem somewhere else.</p> <p>Anyway, it's quite simple. Just write a class with static fields for your secret key and so on, and static methods to encrypt, decrypt your passwords. Encrypt your password in Tomcat's configuration file (<code>server.xml</code> or <code>yourapp.xml</code>...) using this class.</p> <p>And to decrypt the password "on the fly" in Tomcat, extend the DBCP's <code>BasicDataSourceFactory</code> and use this factory in your resource.</p> <p>It will look like:</p> <pre class="lang-xml prettyprint-override"><code> &lt;Resource name="jdbc/myDataSource" auth="Container" type="javax.sql.DataSource" username="user" password="encryptedpassword" driverClassName="driverClass" factory="mypackage.MyCustomBasicDataSourceFactory" url="jdbc:blabla://..."/&gt; </code></pre> <p>And for the custom factory:</p> <pre class="lang-java prettyprint-override"><code>package mypackage; .... public class MyCustomBasicDataSourceFactory extends org.apache.tomcat.dbcp.dbcp.BasicDataSourceFactory { @Override public Object getObjectInstance(Object obj, Name name, Context nameCtx, Hashtable environment) throws Exception { Object o = super.getObjectInstance(obj, name, nameCtx, environment); if (o != null) { BasicDataSource ds = (BasicDataSource) o; if (ds.getPassword() != null &amp;&amp; ds.getPassword().length() &gt; 0) { String pwd = MyPasswordUtilClass.unscramblePassword(ds.getPassword()); ds.setPassword(pwd); } return ds; } else { return null; } } </code></pre> <p>Hope this helps.</p>
What browser features/plugins for opera, IE, firefox, chrome, safari, etc. do you use for browser compatibility testing? <p>I use the <a href="https://addons.mozilla.org/en-US/firefox/addon/6543" rel="nofollow">Nightly Tester Tools</a> for Firefox and <a href="http://fiddlertool.com/fiddler/" rel="nofollow">Fiddler</a> for IE. What do you use?</p>
<p>Web Developer toolbar for Firefox, Visual Studio JIT debugger for IE, and Chrome's Resource Inspector. We don't use Opera for debugging due to the aforementioned tools, but we do take a look at our stuff to make sure it looks correct in Opera to be on the safe side.</p>
How do I make a custom Flex component for a gap-fill exercise? <p>The purpose of this component is to test knowledge of a student on a given subject - in the example below it would be geography. The student is given a piece of text with missing words in it. He/she has to fill in (type in this case) the missing words - hence this kind of test/exercise is called gap-fill.There could be several sentences in the exercise with multiple gaps - something that looks like this:</p> <p><strong>*London is the ______</strong> and largest urban area in the <strong>_________</strong>. An important settlement for two millennia, London's history goes back to its founding by the <strong>_______</strong>.***</p> <p>The component must be able to display text with 'floating' gaps within the text. These gaps would have similar behaviour to TextInput control. Once the student submits the answer the component will return the words that were typed in and these are then compared against the expected answers. </p> <p>The component should be able to display the text and the gaps dynamically derive all required parameters from the text. The position of the gaps could be marked by a special token - such as #10# - which would mark the position of the gap within the text and the size of the gap (number of characters).</p> <p>Therefore the above text could look like this before being loaded into the component:</p> <p>London is the #10# and largest urban area in the #15#. An important settlement for two millennia, London's history goes back to its founding by the #8#.</p>
<p>You need a container that supports flow layout. It's not part of the standard Flex framework but you can find some working implementation <a href="http://flexlib.googlecode.com/svn/trunk/docs/flexlib/containers/FlowBox.html" rel="nofollow">here</a> (part of the excellent FlexLib) and <a href="http://www.munkiihouse.com/?p=60" rel="nofollow">here</a> (standalone implementation).</p>
Passing in parameter from html element with jQuery <p>I'm working with jQuery for the first time and need some help. I have html that looks like the following:</p> <pre><code>&lt;div id='comment-8' class='comment'&gt; &lt;p&gt;Blah blah&lt;/p&gt; &lt;div class='tools'&gt;&lt;/div&gt; &lt;/div&gt; &lt;div id='comment-9' class='comment'&gt; &lt;p&gt;Blah blah something else&lt;/p&gt; &lt;div class='tools'&gt;&lt;/div&gt; &lt;/div&gt; </code></pre> <p>I'm trying to use jQuery to add spans to the .tools divs that call variouis functions when clicked. The functions needs to receive the id (either the entire 'comment-8' or just the '8' part) of the parent comment so I can then show a form or other information about the comment.</p> <p>What I have thus far is:</p> <pre><code>&lt;script type='text/javascript'&gt; $(function() { var actionSpan = $('&lt;span&gt;[Do Something]&lt;/span&gt;'); actionSpan.bind('click', doSomething); $('.tools').append(actionSpan); }); function doSomething(commentId) { alert(commentId); } &lt;/script&gt; </code></pre> <p>I'm stuck on how to populate the commentId parameter for doSomething. Perhaps instead of the id, I should be passing in a reference to the span that was clicked. That would probably be fine as well, but I'm unsure of how to accomplish that.</p> <p>Thanks, Brian</p>
<p>Event callbacks are called with an event object as the first argument, you can't pass something else in that way. This event object has a <code>target</code> property that references the element it was called for, and the <code>this</code> variable is a reference to the element the event handler was attached to. So you could do the following:</p> <pre><code>function doSomething(event) { var id = $(event.target).parents(".tools").attr("id"); id = substring(id.indexOf("-")+1); alert(id); } </code></pre> <p>...or:</p> <pre><code>function doSomething(event) { var id = $(this).parents(".tools").attr("id"); id = substring(id.indexOf("-")+1); alert(id); } </code></pre>
Is it a bad idea to reload routes dynamically in Rails? <p>I have an application I'm writing where I'm allowing the administrators to add aliases for pages, categories, etc, and I would like to use a different controller/action depending on the alias (without redirecting, and I've found that render doesn't actually call the method. I just renders the template). I have tried a catch all route, but I'm not crazy about causing and catching a DoubleRender exception that gets thrown everytime.</p> <p>The solution for this I've come up with is dynamically generated routes when the server is started, and using callbacks from the Alias model to reload routes when an alias is created/updated/destroyed. Here is the code from my routes.rb:</p> <pre><code>Alias.find(:all).each do |alias_to_add| map.connect alias_to_add.name, :controller =&gt; alias_to_add.page_type.controller, :action =&gt; alias_to_add.page_type.action, :navigation_node_id =&gt; alias_to_add.navigation_node.id end </code></pre> <p>I am using callbacks in my Alias model as follows:</p> <pre><code>after_save :rebuild_routes after_destroy :rebuild_routes def rebuild_routes ActionController::Routing::Routes.reload! end </code></pre> <p>Is this against Rails best practices? Is there a better solution?</p>
<p>Ben,</p> <p>I find the method you're already using to be the best. Using Rails 3, you'd have to change the code a bit, to:</p> <pre><code>MyNewApplication::Application.reload_routes! </code></pre> <p>That's all.</p>
Sql server real datatype, what is the C# equivalent? <p>What is the C# equivalent to the sql server 2005 real type?</p>
<p>it is a Single</p> <p>see <a href="http://msdn.microsoft.com/en-us/library/ms131092.aspx">here</a> for more info on SQL Server to .Net DataTypes</p>
C# + Castle ActiveRecord: HasAndBelongsToMany and collections <p>Let's say I have many-to-many relationship (using the ActiveRecord attribute HasAndBelongsToMany) between Posts and Tags (domain object names changed to protect the innocent), and I wanted a method like <pre>FindAllPostByTags(IList&lt;Tag&gt; tags)</pre> that returns all Posts that have all (not just some of) the Tags in the parameter. Any way I could accomplish this either with NHibernate Expressions or HQL? I've searched through the HQL documentation and couldn't find anything that suited my needs. I hope I'm just missing something obvious!</p>
<p>You could also just use an <code>IN</code> statement</p> <pre><code>DetachedCriteria query = DetachedCriteria.For&lt;Post&gt;(); query.CreateCriteria("Post").Add(Expression.In("TagName", string.Join(",",tags.ToArray()) ); </code></pre> <p>I haven't compiled that so it could have errors</p>
Any good collection module in perl? <p>Can someone suggest a good module in perl which can be used to store collection of objects?</p> <p>Or is ARRAY a good enough substitute for most of the needs?</p> <p><strong>Update:</strong> I am looking for a collections class because I want to be able to do an operation like compute collection level property from each element.</p> <p>Since I need to perform many such operations, I might as well write a class which can be extended by individual objects. This class will obviously work with arrays (or may be hashes).</p>
<p>There are collection modules for more complex structures, but it is common style in Perl to use Arrays for arrays, stacks and lists. Perl has built in functions for using the array as a stack or list : push/pop, shift/unshift, splice (inserting or removing in the middle) and the foreach form for iteration.</p> <p>Perl also has a map, called a hashmap which is the equivalent to a Dictionary in Python - allowing you to have an association between a single key and a single value.</p> <p>Perl developers often compose these two data-structures to build what they need - need multiple values? Store array-references in the value part of the hashtable (Map). Trees can be built in a similar manner - if you need unique keys, use multiple-levels of hashmaps, or if you don't use nested array references.</p> <p>These two primitive collection types in Perl don't have an Object Oriented api, but they still are collections.</p> <p>If you look on CPAN you'll likely find modules that provide other Object Oriented data structures, it really depends on your need. Is there a particular data structure you need besides a List, Stack or Map? You might get a more precise answer (eg a specific module) if you're asking about a particular data structure.</p> <p>Forgot to mention, if you're looking for small code examples across a variety of languages, <a href="http://pleac.sourceforge.net/" rel="nofollow">PLEAC</a> (Programming Language Examples Alike Cookbook) is a decent resource.</p>
How can I find out what category a product belongs to? <p>Basically, when a user inputs a product name (such as "iPhone 3g"), I would like to know the parent categories of that item (such as Electronics / Mobile phones). Is there a web api (ie. for ebay, amazon etc.) or any other way to figure out that information?</p>
<p>Yahoo Product API has a ton of information. Now, there is no authoritative source, just Yahoo's hierarchy or individual store results, so you could just pick the first one (look under "Categories" to get the category info). <a href="http://developer.yahoo.com/shopping/V3/productSearch.html" rel="nofollow">http://developer.yahoo.com/shopping/V3/productSearch.html</a></p> <p>e.g. <a href="http://shopping.yahooapis.com/ShoppingService/v3/productSearch?appid=YahooDemo&amp;query=iphone" rel="nofollow">http://shopping.yahooapis.com/ShoppingService/v3/productSearch?appid=YahooDemo&amp;query=iphone</a></p> <p><a href="http://shopping.yahooapis.com/ShoppingService/v3/productSearch?appid=YahooDemo&amp;query=ipod" rel="nofollow">http://shopping.yahooapis.com/ShoppingService/v3/productSearch?appid=YahooDemo&amp;query=ipod</a></p>
Pass NSMutableArray object <p>I'm getting lost in pointer land, I believe. I've got this (code syntax might be a little off, I am not looking at the machine with this code on it...but all the pertinent details are correct):</p> <pre><code>NSMutableArray *tmp = [[NSMutableArray alloc] init]; </code></pre> <p>I them pass that to a routine in another class</p> <pre><code>- (BOOL)myRoutine: (NSMutableArray *)inArray { // Adds items to the array -- if I break at the end of this function, the inArray variable has a count of 10 } </code></pre> <p>But when the code comes back into the calling routine, [tmp count] is 0.</p> <p>I must be missing something very simple and yet very fundamental, but for the life of me I can't see it. Can anyone point out what I'm doing wrong?</p> <p>EDIT: www.stray-bits.com asked if I have retained a reference to it, and I said "maybe...we tried this: NSMutableArray *tmp = [[[NSMutableArray alloc] init] retain]; not sure if that is what you mean, or if I did it right.</p> <p>EDIT2: Mike McMaster and Andy -- you guys are probably right, then. I don't have the code here (it's on a colleague's machine and they have left for the day), but to fill the array with values we were doing something along the lines of using a decoder(?) object. </p> <p>The purpose of this function is to open a file from the iPhone, read that file into an array (it's an array of objects that we saved in a previous run of the program). That "decoder" thing has a method that puts data into the array. </p> <p>Man, I've totally butchered this. I really hope you all can follow, and thanks for the advice. We'll look more closely at it.</p>
<p>You don't need to call retain in this case. [[NSMutableArray alloc] init] creates the object with a retain count of 1, so it won't get released until you specifically release it.</p> <p>It would be good to see more of the code. I don't think the error is in the very small amount you've posted so far..</p>
How do you sign your Firefox extensions? <p>I have developed a couple of extensions for Firefox, and am annoyed that it is so hard to get the extension signed. When an extension isn't signed, it says "Author not verified" when it is installed, and to me that just looks wrong.</p> <p>I have a simple build script that builds my .xpi file from sources, and I have a licenced copy of PKZip (which according to a number of tutorials is required to build a signed xpi file that Firefox requires), but I haven't found a way to get a free/cheap certificate that actually works or a set of instructions that do the trick.</p> <p>Since my extensions are free, I don't want to spend $400 on a commercial certificate, but I don't mind spending $50 or so to get it done. I have both Linux and Windows machines, although my build script currently uses Windows and that would be most convenient to use.</p> <p>How have you solved this? What do I need to do to automatically and securely sign my extensions when they are built?</p> <p>Edit: I appreciate the Google hits, but the steps they provide aren't complete enough on how to actually get a certificate that works. The feeling I get reminds me of this classic:</p> <p><img src="http://www.sciencecartoonsplus.com/images/miracle3.gif" alt="alt text" title="Then a miracle occurs..." /></p>
<p>Avoid the GoDaddy codesigning certs as the necessary intermediate CA certificate isn't in Firefox by default. C=US,ST=Arizona,L=Scottsdale,O=GoDaddy.com\,Inc.,OU=<a href="http://certificates.godaddy.com/repository,CN=Go" rel="nofollow">http://certificates.godaddy.com/repository,CN=Go</a> Daddy Secure Certification Authority,SERIALNUMBER=07969287'</p> <p>If you sign with it your users will get signing errors with it.</p> <p>e.g. <pre>SIgning could not be verified. -260</pre></p>
Dropdownlist control with <optgroup>s for asp.net (webforms)? <p>Can anyone recommend a dropdownlist control for asp.net (3.5) that can render option groups? Thanks</p>
<p>I've used the standard control in the past, and just added a simple <a href="http://msdn.microsoft.com/en-us/library/system.web.ui.adapters.controladapter.aspx" rel="nofollow">ControlAdapter</a> for it that would override the default behavior so it could render &lt;optgroup>s in certain places. This works great even if you have controls that don't need the special behavior, because the additional feature doesn't get in the way.</p> <p>Note that this was for a specific purpose and written in .Net 2.0, so it may not suit you as well, but it should at least give you a starting point. Also, you have to hook it up using a .browserfile in your project (see the end of the post for an example).</p> <pre class="lang-vb prettyprint-override"><code>'This codes makes the dropdownlist control recognize items with "--" 'for the label or items with an OptionGroup attribute and render them 'as &lt;optgroup&gt; instead of &lt;option&gt;. Public Class DropDownListAdapter Inherits System.Web.UI.WebControls.Adapters.WebControlAdapter Protected Overrides Sub RenderContents(ByVal writer As HtmlTextWriter) Dim list As DropDownList = Me.Control Dim currentOptionGroup As String Dim renderedOptionGroups As New Generic.List(Of String) For Each item As ListItem In list.Items Page.ClientScript.RegisterForEventValidation(list.UniqueID, item.Value) If item.Attributes("OptionGroup") IsNot Nothing Then 'The item is part of an option group currentOptionGroup = item.Attributes("OptionGroup") If Not renderedOptionGroups.Contains(currentOptionGroup) Then 'the header was not written- do that first 'TODO: make this stack-based, so the same option group can be used more than once in longer select element (check the most-recent stack item instead of anything in the list) If (renderedOptionGroups.Count &gt; 0) Then RenderOptionGroupEndTag(writer) 'need to close previous group End If RenderOptionGroupBeginTag(currentOptionGroup, writer) renderedOptionGroups.Add(currentOptionGroup) End If RenderListItem(item, writer) ElseIf item.Text = "--" Then 'simple separator RenderOptionGroupBeginTag("--", writer) RenderOptionGroupEndTag(writer) Else 'default behavior: render the list item as normal RenderListItem(item, writer) End If Next item If renderedOptionGroups.Count &gt; 0 Then RenderOptionGroupEndTag(writer) End If End Sub Private Sub RenderOptionGroupBeginTag(ByVal name As String, ByVal writer As HtmlTextWriter) writer.WriteBeginTag("optgroup") writer.WriteAttribute("label", name) writer.Write(HtmlTextWriter.TagRightChar) writer.WriteLine() End Sub Private Sub RenderOptionGroupEndTag(ByVal writer As HtmlTextWriter) writer.WriteEndTag("optgroup") writer.WriteLine() End Sub Private Sub RenderListItem(ByVal item As ListItem, ByVal writer As HtmlTextWriter) writer.WriteBeginTag("option") writer.WriteAttribute("value", item.Value, True) If item.Selected Then writer.WriteAttribute("selected", "selected", False) End If For Each key As String In item.Attributes.Keys writer.WriteAttribute(key, item.Attributes(key)) Next key writer.Write(HtmlTextWriter.TagRightChar) HttpUtility.HtmlEncode(item.Text, writer) writer.WriteEndTag("option") writer.WriteLine() End Sub End Class </code></pre> <p>Here's a C# implementation of the same Class:</p> <pre><code>/* This codes makes the dropdownlist control recognize items with "--" * for the label or items with an OptionGroup attribute and render them * as &lt;optgroup&gt; instead of &lt;option&gt;. */ public class DropDownListAdapter : WebControlAdapter { protected override void RenderContents(HtmlTextWriter writer) { //System.Web.HttpContext.Current.Response.Write("here"); var list = (DropDownList)this.Control; string currentOptionGroup; var renderedOptionGroups = new List&lt;string&gt;(); foreach (ListItem item in list.Items) { Page.ClientScript.RegisterForEventValidation(list.UniqueID, item.Value); //Is the item part of an option group? if (item.Attributes["OptionGroup"] != null) { currentOptionGroup = item.Attributes["OptionGroup"]; //Was the option header already written, then just render the list item if (renderedOptionGroups.Contains(currentOptionGroup)) RenderListItem(item, writer); //The header was not written,do that first else { //Close previous group if (renderedOptionGroups.Count &gt; 0) RenderOptionGroupEndTag(writer); RenderOptionGroupBeginTag(currentOptionGroup, writer); renderedOptionGroups.Add(currentOptionGroup); RenderListItem(item, writer); } } //Simple separator else if (item.Text == "--") { RenderOptionGroupBeginTag("--", writer); RenderOptionGroupEndTag(writer); } //Default behavior, render the list item as normal else RenderListItem(item, writer); } if (renderedOptionGroups.Count &gt; 0) RenderOptionGroupEndTag(writer); } private void RenderOptionGroupBeginTag(string name, HtmlTextWriter writer) { writer.WriteBeginTag("optgroup"); writer.WriteAttribute("label", name); writer.Write(HtmlTextWriter.TagRightChar); writer.WriteLine(); } private void RenderOptionGroupEndTag(HtmlTextWriter writer) { writer.WriteEndTag("optgroup"); writer.WriteLine(); } private void RenderListItem(ListItem item, HtmlTextWriter writer) { writer.WriteBeginTag("option"); writer.WriteAttribute("value", item.Value, true); if (item.Selected) writer.WriteAttribute("selected", "selected", false); foreach (string key in item.Attributes.Keys) writer.WriteAttribute(key, item.Attributes[key]); writer.Write(HtmlTextWriter.TagRightChar); HttpUtility.HtmlEncode(item.Text, writer); writer.WriteEndTag("option"); writer.WriteLine(); } } </code></pre> <p>My browser file was named "App_Browsers\BrowserFile.browser" and looked like this:</p> <pre><code>&lt;!-- You can find existing browser definitions at &lt;windir&gt;\Microsoft.NET\Framework\&lt;ver&gt;\CONFIG\Browsers --&gt; &lt;browsers&gt; &lt;browser refID="Default"&gt; &lt;controlAdapters&gt; &lt;adapter controlType="System.Web.UI.WebControls.DropDownList" adapterType="DropDownListAdapter" /&gt; &lt;/controlAdapters&gt; &lt;/browser&gt; &lt;/browsers&gt; </code></pre>
Starteam 2005 COM API <p>Has anyone worked with the StarTeam COM API (Specifically, intergrating with C#).</p> <p>I need to write a helper function that returns a directory structure out of Starteam, but all I've been able to retrieve using this API has been a list of views.</p> <p>Has anyone else tried this?</p>
<p>Oh, in the interests of completeness, if you don't want to write the recursive code to navigate the heirachy of folders yourself, there is a helper class you can use to do the hard work for you called FolderListManager</p> <pre><code>void BtnFindClick(object sender, EventArgs e) { Borland.StarTeam.View v = StarTeamFinder.OpenView("username:pwd@server:49201/Project"); FolderListManager lm = new FolderListManager(v); lm.IncludeFolders(v.RootFolder,-1); // -1 means recursively add child folders StringBuilder sb = new StringBuilder(); foreach(Folder f in lm.Folders) { sb.AppendLine(f.Path); } txtResults.Text = sb.ToString(); } </code></pre>
Is there a free/pay web service that I can query to get MLS data? <p>Given an <a href="http://en.wikipedia.org/wiki/Multiple_Listing_Service">MLS</a>#, I'd like to get an XML document with details about the listing, like address, price and such. Not a NAR or CREA member. Mostly interested in North American rental property listing data.</p>
<p>If you're an NAR member, you can utilize their Internet Data Exchange (IDX) system, but it isn't available to non-members.</p>
Can I use a generated variable name in PHP? <p>I have a bunch a values I would like to add together which are entered into a form. Right now, the form has 11 lines but it could get larger in the future. I can easily add all the values together with something like:</p> <pre><code>$total = $value1 + $value2 + ... + $value11; </code></pre> <p>All the values I want to add together are coming from an <code>HTML</code> form. I want to avoid javascript.</p> <p>But, I want to avoid having to manually do it, especially if it grows much larger. This is my attempt at adding all the values together using a loop but it returns an "undefined variable" error (it is just some test code to try out the idea):</p> <pre><code>&lt;?php $tempTotal = 0; $pBalance1 = 5; $pBalance2 = 5; $pBalance3 = 5; for ($i = 1 ; $i &lt;= 3 ; $i++){ $tempTotal = $tempTotal + $pBalance.$i; } echo $tempTotal; ?&gt; </code></pre> <p>Is what I want to do possible in PHP?</p>
<p>I would use @unexist's solution.. give the input fields names like:</p> <pre><code>&lt;input name="myInput[]" /&gt; &lt;input name="myInput[]" /&gt; &lt;input name="myInput[]" /&gt; ... </code></pre> <p>Then in your PHP get the sum like this:</p> <pre><code>$total = array_sum($_REQUEST['myInput']); </code></pre> <p>Because of the '[]' at the end of each input name, PHP will make $_REQUEST['myInput'] automatically be an array. A handy feature of PHP!</p>
Oracle load spikes couple hours after startup <p>We use oracle as the back-end database for our product. I have been running series of stress tests on our system and I have started noticing that oracle is much faster right after the database was restarted. Over time (a couple hours or so) the database seems to get slower and slower and I will see the database machine under more stress.</p> <p>Running the test right after an oracle restart, i will see a 1 min load average of 5 or so and average CPU around 10-15%. After a few hours, I see the load average at 13 and CPU at 40-70%. (This is red hat linux 2x Quad core xeon, Raid 10 10k rpm sas drives).</p> <p>My first thought was wouldn't database transactions get faster because those queries are getting cached?</p> <p>I can't seem to figure out the problem. </p> <p>EDIT: Turns out this was a problem on the connecting software side due to bad design. Every action on the system created a new insert, delete, and select. With all these unique queries being generated, what was cached was constantly changing. The spike I am talking about is when the query cache filled up.</p>
<p>What version of oracle are you running? Do you have statspack or AWR setup? if you do, check those to show you what the database is doing over time.</p>
In Installshield, what is the best event to use to launch applications only on install, not on uninstall or repair? <p>We have recently moved back to InstallShield 2008 from rolling our own install. So, I am still trying to get up the learning curve on it. </p> <p>We are using Firebird and a usb driver, that we couldn't find good msi install solutions. So, we have a cmd line to install firebird silently and the usb driver mostly silently.</p> <p>We have put this code into the event handler DefaultFeatureInstalled. This works really well on the first time install. But, when I do an uninstall it trys to launch the firebird installer again, so it must be sending the DefaultFeatureInstalled event again.</p> <p>Is their another event to use, or is there a way to detect whether its an install or uninstall in the DefaultFeatureInstalled event?</p>
<p>Chris, I had trouble getting the MsiGetProperty to work at all. Just adding the code that you have </p> <pre><code>string sRemove; number nBuffer; nBuffer = 256; if (MsiGetProperty(ISMSI_HANDLE, "REMOVE", sRemove, nBuffer) = ERROR_SUCCESS) then //do something endif; </code></pre> <p>I get "undefined identifier". I tried several things to get IS to recognize it without success. After some more poking around, I realized that IS was not calling the function on uninstall in the first place. I had another function, onEnd I think that was calling the same things. After cleaning that up, I was getting the result I had expected in the beginning.</p> <p>So the correct answer would be that you don't have to do anything for the code in the DefaultFeature_Installed event not to be called on uninstall.</p>
Is there a reasonable way to implement a cd command on VMS? <p>I would like to be able to say things like</p> <p><strong>cd [.fred]</strong> and have my default directory go there, and my prompt change to indicate the full path to my current location.</p>
<p>Just type</p> <p><code>cd:==set default</code> </p> <p>at the command prompt. You can also put this in your LOGIN.COM file, but be sure to put a $ in front, i.e.</p> <p><code>$ cd:==set default</code></p> <p>To change your prompt to show your default, something like this may work up to a point</p> <p><code>$ set prompt='f$env("default")'</code></p> <p>There is a problem though with the fact that VMS prompt has maximum 32 characters, and your default might be longer than that. Have a look at <a href="http://www.phrack.com/issues.html?issue=19&amp;id=2">this page</a> for a way around that problem.</p>
Flex: Why can't I handle certain events? <p>In certain cases, I can't seem to get components to receive events.</p> <p>[edit] </p> <p>To clarify, the example code is just for demonstration sake, what I was really asking was if there was a central location that a listener could be added, to which one can reliably dispatch events to and from arbitrary objects.</p> <p>I ended up using parentApplication to dispatch and receive the event I needed to handle.</p> <p>[/edit]</p> <p>If two components have differing parents, or as in the example below, one is a popup, it would seem the event never reaches the listener (See the method "popUp" for the dispatch that doesn't work):</p> <pre><code>&lt;?xml version="1.0" encoding="utf-8"?&gt; &lt;mx:Application xmlns:mx="http://www.adobe.com/2006/mxml" layout="absolute" initialize="init()"&gt; &lt;mx:Script&gt; &lt;![CDATA[ import mx.controls.Menu; import mx.managers.PopUpManager; // Add listeners public function init():void { this.addEventListener("child", handleChild); this.addEventListener("stepchild", handleStepchild); } // Handle the no pop button event public function noPop(event:Event):void { dispatchEvent(new Event("child")); } // Handle the pop up public function popUp(event:Event):void { var menu:Menu = new Menu(); var btnMenu:Button = new Button(); btnMenu.label = "stepchild"; menu.addChild(btnMenu); PopUpManager.addPopUp(menu, this); // neither of these work... this.callLater(btnMenu.dispatchEvent, [new Event("stepchild", true)]); btnMenu.dispatchEvent(new Event("stepchild", true)); } // Event handlers public function handleChild(event:Event):void { trace("I handled child"); } public function handleStepchild(event:Event):void { trace("I handled stepchild"); } ]]&gt; &lt;/mx:Script&gt; &lt;mx:VBox&gt; &lt;mx:Button label="NoPop" id="btnNoPop" click="noPop(event)"/&gt; &lt;mx:Button label="PopUp" id="btnPop" click="popUp(event)"/&gt; &lt;/mx:VBox&gt; &lt;/mx:Application&gt; </code></pre> <p><strong>I can think of work-arounds, but it seems like there ought to be some central event bus...</strong> </p> <p>Am I missing something?</p>
<p>Above is correct. You are dispatching the event from btnMenu, but you are not listening for events on btnMenu - you are listening for events on the Application.</p> <p>Either dispatch from Application:</p> <pre><code>dispatchEvent(new Event("stepchild", true)); </code></pre> <p>or listen on the btnMenu</p> <pre><code>btnMenu.addEventListener("stepchild",handleStepChild); btnMenu.dispatchEvent(new Event("stepchild",true)); </code></pre>
How to unit test immutable class constructors? <p>I have an immutable class with some private fields that are set during the constructor execution. I want to unit test this constructor but I'm not sure the "best practice" in this case.</p> <p><strong>Simple Example</strong></p> <p>This class is defined in Assembly1:</p> <pre><code>public class Class2Test { private readonly string _StringProperty; public Class2Test() { _StringProperty = ConfigurationManager.AppSettings["stringProperty"]; } } </code></pre> <p>This class is defined in Assembly2:</p> <pre><code>[TestClass] public class TestClass { [TestMethod] public void Class2Test_Default_Constructor() { Class2Test x = new Class2Test(); //what do I assert to validate that the field was set properly? } } </code></pre> <p><strong>EDIT 1</strong>: I have answered this question with a potential solution but I'm not sure if it's the "right way to go". So if you think you have a better idea please post it.</p> <p>This example isn't really worth testing, but assume the constructor has some more complex logic. Is the best approach to avoid testing the constructor and to just assume it works if all the tests for the methods on the class work?</p> <p><strong>EDIT 2</strong>: Looks like I made the sample a little to simple. I have updated it with a more reasonable situation.</p>
<p>Nothing, unless you are using that field. You don't want over-specification via tests. In other words, there is no need to test that the assignment operator works.</p> <p>If you are using that field in a method or something, call that method and assert on that.</p> <p>Edit: </p> <blockquote> <p>assume the constructor has some more complex logic</p> </blockquote> <p>You shouldn't be performing any logic in constructors.</p> <p>Edit 2:</p> <blockquote> <pre><code>public Class2Test() { _StringProperty = ConfigurationManager.AppSettings["stringProperty"]; } </code></pre> </blockquote> <p>Don't do that! =) Your simple unit test has now become an integration test because it depends on the successful operation of more than one class. Write a class that handles configuration values. WebConfigSettingsReader could be the name, and it should encapsulate the <code>ConfigurationManager.AppSettings</code> call. Pass an instance of that SettingsReader class into the constructor of <code>Class2Test</code>. Then, in your <em>unit test</em>, you can mock your <code>WebConfigSettingsReader</code> and stub out a response to any calls you might make to it.</p>
Link error when compiling gcc atomic operation in 32-bit mode <p>I have the following program:</p> <pre><code>~/test&gt; cat test.cc int main() { int i = 3; int j = __sync_add_and_fetch(&amp;i, 1); return 0; } </code></pre> <p>I'm compiling this program using GCC 4.2.2 on Linux running on a multi-cpu 64-bit Intel machine:</p> <pre><code>~/test&gt; uname --all Linux doom 2.6.9-67.ELsmp #1 SMP Wed Nov 7 13:56:44 EST 2007 x86_64 x86_64 x86_64 GNU/Linux </code></pre> <p>When I compile the program in 64-bit mode, it compiles and links fine:</p> <pre><code>~/test&gt; /share/tools/gcc-4.2.2/bin/g++ test.cc ~/test&gt; </code></pre> <p>When I compile it in 32-bit mode, I get the following error:</p> <pre><code>~/test&gt; /share/tools/gcc-4.2.2/bin/g++ -m32 test.cc /tmp/ccEVHGkB.o(.text+0x27): In function `main': : undefined reference to `__sync_add_and_fetch_4' collect2: ld returned 1 exit status ~/test&gt; </code></pre> <p>Although I will never actually run on a 32-bit processor, I do need a 32-bit executable so I can link with some 32-bit libraries.</p> <p>My 2 questions are:</p> <ol> <li><p>Why do I get a link error when I compile in 32-bit mode?</p></li> <li><p>Is there some way to get the program to compile and link, while still being able to link with a 32-bit library?</p></li> </ol>
<p>The answer from Dan Udey was close, close enough in fact to allow me to find the real solution.</p> <p>According to the man page "-mcpu" is a deprecated synonym for "-mtune" and just means "optimize for a particular CPU (but still run on older CPUs, albeit less optimal)". I tried this, and it did not solve the issue.</p> <p>However, "-march=" means "generate code for a particular CPU (and don't run on older CPUs)". When I tried this it solved the problem: specifying a CPU of i486 or better got rid of the link error.</p> <pre><code>~/test&gt; /share/tools/gcc-4.2.2/bin/g++ -m32 test.cc /tmp/ccYnYLj6.o(.text+0x27): In function `main': : undefined reference to `__sync_add_and_fetch_4' collect2: ld returned 1 exit status ~/test&gt; /share/tools/gcc-4.2.2/bin/g++ -m32 -march=i386 test.cc /tmp/ccOr3ww8.o(.text+0x22): In function `main': : undefined reference to `__sync_add_and_fetch_4' collect2: ld returned 1 exit status ~/test&gt; /share/tools/gcc-4.2.2/bin/g++ -m32 -march=i486 test.cc ~/test&gt; /share/tools/gcc-4.2.2/bin/g++ -m32 -march=pentium test.cc </code></pre>
GDI+ System.Drawing.Bitmap gives error Parameter is not valid intermittently <p>I have some C# code in an ASP.Net application that does this:</p> <p>Bitmap bmp = new Bitmap(1184, 1900);</p> <p>And occasionally it throws an exception "Parameter is not valid". Now i've been googling around and apparently GDI+ is infamous for throwing random exceptions, and lots of people have had this problem, but nobody has a solution to it! I've checked the system and it has plenty of both RAM and swap space. Now in the past if i do an 'iisreset' then the problem goes away, but it comes back in a few days. But i'm not convinced i've caused a memory leak, because as i say above there is plenty of ram+swap free.</p> <p>Anyone have any solutions?</p>
<p>Stop using GDI+ and start using the WPF Imaging classes (.NET 3.0). These are a major cleanup of the GDI+ classes and tuned for performance. Additionally, it sets up a "bitmap chain" that allows you to easily perform multiple actions on the bitmap in an efficient manner.</p> <p>Find more by reading about <a href="http://msdn.microsoft.com/en-us/library/system.windows.media.imaging.bitmapsource.aspx">BitmapSource</a></p> <p>Here's an example of starting with a blank bitmap just waiting to receive some pixels:</p> <pre><code>using System.Windows.Media.Imaging; class Program { public static void Main(string[] args) { var bmp = new WriteableBitmap(1184, 1900, 96.0, 96.0, PixelFormat.Bgr32, null); } } </code></pre>
Data visualization in desktop applications <p>I would like to create data visualizations in desktop apps, using frameworks, languages and libraries that help with this kind of task. Visualizations should be interactive: clickable, draggable, customizable, animated...</p> <p>What I would like to create is something similar to the examples seen here: <a href="http://www.visualcomplexity.com/vc/" rel="nofollow">http://www.visualcomplexity.com/vc/</a> </p> <p>These are the links I already know: <a href="http://delicious.com/laura_laura/visualization?setcount=100" rel="nofollow">http://delicious.com/laura_laura/visualization?setcount=100</a></p> <p>The preferred language is C++/Visual C++ (MFC) because I'm familiar with it, but any other technology is welcome, I would like to make a list from "as similar as possible" to Visual C++ to "very different" from Visual C++. </p> <p>WPF, flex, Adobe Air, flare, Javascript (running in a browser as client-side apps with access to local files or as desktop apps) are possibilities, post any good links to examples, tutorials, how-tos, etc. that you know of. </p> <p>What are the learning curves and complexity for the different options? Wich one would you choose and why? Wich one have you already worked with and how was your experience? How would you start with a project of this characteristics?</p>
<p>Your post has far too many questions in it to be answered easily in one response, so you might try re-posting with specific questions. Data visualization is a HUGE area of study and it's not significantly different for web applications versus desktop applications. </p> <p>Put simply, it's the display of data in a way that visually tells the story of the data. It's most useful in cases where the volume of data is such that tabular display isn't effective. Trends, outliers, and abnormal occurrences can sometimes only be seen when data is represented visually. Visually can be a simple chart, or it can be more advanced visualizations such as treemaps or thematic mapping/GIS presentations.</p> <p>If it's an area you're interested in studying, look into:</p> <p><a href="http://www.edwardtufte.com/tufte/">Edward Tufte</a> - Author, professor, and all-around guru for the display of information</p> <p><a href="http://services.alphaworks.ibm.com/manyeyes/home">Many Eyes</a> - from IBM AlphaWorks</p> <p><a href="http://www.processing.org">Processing</a> - A visual "sketching" language based on Java</p> <p><a href="http://rads.stackoverflow.com/amzn/click/0596514557">Visualizing Data</a> - An O'Reilly book by Ben Fry, one of the co-creators of Processing</p> <p>Beyond that, I think specifics would depend on what you want to accomplish -- what data is being analyzed, who the audience is, and what the desired "message" is.</p>
How can I provide custom error messages using JAXP DocumentBuilder? <p>I want to provide my own message from the validation done in <code>DocumentBuilder</code>, rather than the one from <code>XMLMessages.properties</code>.</p> <p>Now I see that a property <a href="http://apache.org/xml/properties/internal/error-reporter" rel="nofollow"><code>error-reporter</code></a> needs to be set to a class which extends <code>XMLErrorReporter</code>.</p> <p>However, I've not been able to get <code>ComponentManager</code> from <code>Document</code>/<code>Builder</code>/<code>Factory</code>.</p> <p>Doing parsing of string in <code>SAXParseException</code> is the last option, but I'm just thinking there may be a 'best practice' way of doing it.</p>
<p>have you already looked at <a href="http://java.sun.com/j2se/1.4.2/docs/api/javax/xml/parsers/DocumentBuilder.html#setErrorHandler(org.xml.sax.ErrorHandler)" rel="nofollow">DocumentBuilder#setErrorHandler</a>?</p> <p>if yes, could you explain why this approach doesn't work for you?</p>
Migrations for Java <p>I use both ruby on rails and Java. I really enjoy using migrations when I am working on a rails project. so I am wondering is there a migrations like tool for Java? If there is no such tool is it a good idea to use migrations as a tool to control a database used by a Java project? </p>
<p>For a <strong>feature comparison</strong> between </p> <ul> <li>Flyway</li> <li>Liquibase</li> <li>c5-db-migration</li> <li>dbdeploy</li> <li>mybatis</li> <li>MIGRATEdb</li> <li>migrate4j</li> <li>dbmaintain</li> <li>AutoPatch</li> </ul> <p>have a look at <a href="http://flywaydb.org">http://flywaydb.org</a></p> <p>This should be a good start for you and anyone else to <strong>select the right tool for the job</strong></p>
Converting string to uint in actionscript / Flex <p>I am creating a component and want to expose a color property as many flex controls do, lets say I have simple component like this, lets call it foo_label:</p> <pre> <code> &lt;mx:Canvas> &lt;mx:Script> [Bindable] public var color:uint; &lt;/mx:Script> &lt;mx:Label text="foobar" color="{color}" /> &lt;/mx:Canvas> </code> </pre> <p>and then add the component in another mxml file, something along the lines of:</p> <pre> <code> &lt;foo:foo_label color="red" /> </code> </pre> <p>When I compile the compiler complains: cannot parse value of type uint from text 'red'. However if I use a plain label I can do</p> <pre><code>&lt;mx:Label text="foobar" color="red"></code></pre> <p>without any problems, and the color property is still type uint. </p> <p>My question is how can I expose a public property so that I can control the color of my components text? Why can I use the string "red" as a uint field for the mx controls but cannot seem to do the same in a custom component, do I need to do something special?</p> <p>Thanks.</p>
<p>Color is not a property, it is a style. You need to define the style like this:</p> <pre><code>[Style(name="labelColor", type="uint", format="Color" )] </code></pre> <p>(enclose it in tag if you define it directly in MXML). You then need to add some ActionScript to handle this style and apply it to whichever control you need, please refer to <a href="http://livedocs.adobe.com/flex/3/html/help.html?content=skinstyle_1.html">http://livedocs.adobe.com/flex/3/html/help.html?content=skinstyle_1.html</a> for more information.</p>
What is the best way to implement a singleton pattern class in Actionscript 3? <p>Since AS3 does not allow private constructors, it seems the only way to construct a singleton and guarantee the constructor isn't explicitly created via "new" is to pass a single parameter and check it.</p> <p>I've heard two recommendations, one is to check the caller and ensure it's the static getInstance(), and the other is to have a private/internal class in the same package namespace.</p> <p>The private object passed on the constructor seems preferable but it does not look like you can have a private class in the same package. Is this true? And more importantly is it the best way to implement a singleton?</p>
<p>A slight adaptation of enobrev's answer is to have instance as a getter. Some would say this is more elegant. Also, enobrev's answer won't enforce a Singleton if you call the constructor before calling getInstance. This may not be perfect, but I have tested this and it works. (There is definitely another good way to do this in the book "Advanced ActionScrpt3 with Design Patterns" too).</p> <pre><code>package { public class Singleton { private static var _instance:Singleton; public function Singleton(enforcer:SingletonEnforcer) { if( !enforcer) { throw new Error( "Singleton and can only be accessed through Singleton.getInstance()" ); } } public static function get instance():Singleton { if(!Singleton._instance) { Singleton._instance = new Singleton(new SingletonEnforcer()); } return Singleton._instance; } } } class SingletonEnforcer{} </code></pre>
Writing a cookie from an ASP.Net HTTPHandler - Page.Response object? <p>I am creating an HTTP handler that listens for calls to a specific file type, and handles it accordingly. My HTTP Handler listens for .bcn files, then writes a cookie to the user's computer and sends back an image... this will be used in advertising banners so that the user is tagged as seeing the banner, and we can then offer special deals when they visit our site later.</p> <p>The problem i'm having is getting access to the Page object... of course an HTTPHandler is not actually a page, and since the Response object lives within the Page object, I can't get access to it to write the cookie.</p> <p>Is there a way around this, or do i need to revert back to just using a standard aspx page to do this?</p> <p>Thanks heaps.. Greg</p>
<p>You can access the Response object from the HttpContext object passed to the ProcessRequest method from IHttpHandler. This is the same object exposed by Page.Response.</p>
Is it expected that all the units of a Project Group in Delphi 7 to be in one folder? <p>Maybe this applied to other Delphi's (I've only used 7). We've got our code broken up so that nearly every DLL in our fairly massive app is in a different folder. <p> 99% of the open source stuff I've downloaded to plug into Delphi have had all their source munged into one folder. <p> It seems like this was an assumption that the developers of Delphi made about the coding practices of it's users that may be non-obvious.</p>
<p>I don't think so. In fact, In more recent versions they've added features to the project manager to make it easier to deal with the fact that code is spread around different directories (such as the flatten directories option), so I think it is accepted that this is how many people organize their code.</p> <p>I suspect it's more to do with projects growing organically over time, and whether anyone takes the time to tidy up. </p>
How do I create an installer for a .Net website, Windows Service, and more? <p>I need to create an installer program that will do install the following:</p> <ol> <li>ASP.Net Website </li> <li>Windows Service</li> <li>SQL Express if it isn't installed and the user doesn't have a SQL Server</li> <li>Dundas Charts</li> <li>ASP.Net AJAX v.1.0</li> <li>ReportViewer control (for 2.0 Framework)</li> <li>Check Framework prerequisites (2.0)</li> <li>Configure IIS and app.config (data connection strings, etc.)</li> </ol> <p>Is it realistic to be able to do this with a VS Setup Project? Or, should I be looking at other install tools? </p>
<p>You can use <a href="http://wix.sourceforge.net/" rel="nofollow">WiX</a></p>
How can I programmatically manipulate Windows desktop icon locations? <p>Several years back, I innocently tried to write a little app to save my tactically placed desktop icons because I was sick of dragging them back to their locations when some event reset them. I gave up after buring WAY too much time having failed to find a way to query, much less save and reset, my icons' desktop position.</p> <p>Anyone know where Windows persists this info and if there's an API to set them?</p> <p>Thanks, Richard</p>
<p>If I'm not mistaken the desktop is just a ListView, and you'll have to send the <a href="http://msdn.microsoft.com/en-us/library/bb761192(VS.85).aspx">LVM_SETITEMPOSITION</a> message to the handle of the desktop.</p> <p>I googled a bit for some c# code and couldn't find a example, but I did found the following article. <a href="http://www.swissdelphicenter.ch/torry/showcode.php?id=1897">Torry: ...get/set the positions of desktop icons?</a>. It's delphi code, but I find it very readable and with some P/Invokes you'll be able to translate it to c#.</p>
JSP pagination without retrieving the whole result set? <p>I need to display the log entries from a database. Of course the log data is huge, so I have to show the results on several pages, and that **without** getting **all** the log data at once, but as the user navigates through the pages.</p> <p>I know about <a href="http://displaytag.sourceforge.net/11/" rel="nofollow">DisplayTag</a> and <a href="http://code.google.com/p/tabletags/" rel="nofollow">TableTags</a>, but it seems to me that they both fetch all the data before applying pagination.</p> <p>Before I start developing my own JSP tag, does anyone know of a 3rd party solution for this problem?</p> <p>Thanks,<br>Marius</p>
<p>About DisplayTag: it does support <a href="http://displaytag.sourceforge.net/11/tut_externalSortAndPage.html" rel="nofollow">Value List</a> design pattern.</p>
Recommendations for a good C#/ .NET based lexical analyser <p>Can anyone recommend a good .NET based lexical analyser, preferably written in C#?</p>
<p>Download the Visual Studio SDK; it includes a managed parser/lexer generator.</p> <p>(Edit: It was written on my university campus, apparantly :D)</p>
Deployment of custom content type, forms, cqwp, and xsl <p>Right now I have a visual studio project which contains a custom content type that I made. It also contains all the necessary files for making a sharepoint solution (wsp) file and a script to generate this. </p> <p>Now, I would like to do 2 things. </p> <p>First, I'd like to create a custom display form for the content type and include it in my solution so that it is automatically deployed when I deploy my solution. How do I include this in my solution and make my content type use it?</p> <p>Secondly, you can query this type with the CQWP. I've thought about exporting it, adding more common view fields, and then modifying the XSL that is used to render it. How do I include this into my solution so that it is also deployed. I know i can export the CQWP webpart once it's all setup and include it in my project as a feature. But what abuot the XSL?</p> <p>Looking forward to see your suggestions, cheers.</p> <p>Did as described in the first answer. Worked like a charm.</p>
<p>Use <a href="http://www.codeplex.com/stsdev" rel="nofollow">STSDev</a> to create the solution package. That should help with creating the WSP. The custom form, CQWP webpart and the .xls file should also be deployable within the project.</p> <p>To deploy the xslt, your feature will have an</p> <p><code>&lt;ElementManifest Location="mywebpartManifest.xml"&gt;</code></p> <p>This then points to a files such as</p> <pre><code>&lt;Elements xmlns="http://schemas.microsoft.com/sharepoint/"&gt; &lt;Module Name="Yourfile.xslt" Url="Style Library" Path="" RootWebOnly="TRUE"&gt; &lt;File Url="yourfile.xslt" Type="GhostableInLibrary" /&gt; &lt;/Module&gt; &lt;/Elements&gt; </code></pre> <p>for the webpart:</p> <pre><code>&lt;Module Name="myWebpart" List="113" Url="_catalogs/wp" RootWebOnly="FALSE"&gt; &lt;File Url="myWebpart.webpart" Type="GhostableInLibrary" /&gt; &lt;/Module&gt; </code></pre> <p>Now that file will need to be contained in the solution manifest.xml. This is done automatically from the STSDev project.</p> <p>e.g.</p> <pre><code>&lt;Resources&gt; &lt;Resource Location="SimpleFeature\Feature.xml"/&gt; </code></pre> <p>The actual schemas are:</p> <p><a href="http://msdn.microsoft.com/en-us/library/aa544502.aspx" rel="nofollow">Site</a></p> <p><a href="http://msdn.microsoft.com/en-us/library/ms442108.aspx" rel="nofollow">Solution</a></p> <p><a href="http://msdn.microsoft.com/en-us/library/ms414322.aspx" rel="nofollow">Feature</a></p> <p><a href="http://social.msdn.microsoft.com/Forums/en-US/sharepointecm/thread/335399ea-f07f-43a5-a4e2-21d88ba2743e/" rel="nofollow">and a link to someone else with the issue</a></p>
image archive VS image strip <p>i've noticed that plenty of games / applications (very common on mobile builds) pack numerous images into an image strip. I figured that the advantages in this are making the program more tidy (file system - wise) and reducing (un)installation time. During the runtime of the application, the entire image strip is allocated and copied from FS to RAM. On the contrary, images can be stored in an image archive and unpacked during runtime to a number of image structures in RAM.</p> <p>The way I see it, the image strip approach is less efficient because of worse caching performance and because that even if the optimal rectangle packing algorithm is used, there will be empty spaces between the stored images in the strip, causing a waste of RAM.</p> <p>What are the advantages in using an image strip over using an image archive file?</p>
<p>Caching will not be as much of an issue as you think, if the images in the strip are likely to appear at the same time - i.e. are all part of an animation. As far as packing algorithms are concerned, most generic algorithms produce similar levels of efficiency - to get huge increases in packing efficiency you normally have to write an algorithm that is optimised for the dataset involved.</p> <p>As is usually the case with optimization of any kind - caching or packing - don't worry about it until it's been proved to be an issue, and then you need to approach the problem with a good understanding of the context.</p>
How do I check that I removed required data only? <p>I have a really big database (running on PostgreSQL) containing a lot of tables with sophisticated relations between them (foreign keys, on delete cascade and so on). I need remove some data from a number of tables, but I'm not sure what amount of data will be really deleted from database due to cascade removals.</p> <p>How can I check that I'll not delete data that should not be deleted?</p> <p>I have a test database - just a copy of real one where I can do what I want :)</p> <p>The only idea I have is dump database before and after and check it. But it not looks comfortable. Another idea - dump part of database, that, as I think, should not be affected by my DELETE statements and check this part before and after data removal. But I see no simple ways to do it (there are hundreds of tables and removal should work with ~10 of them). Is there some way to do it?</p> <p>Any other ideas how to solve the problem?</p>
<p>You can query the information_schema to draw yourself a picture on how the constraints are defined in the database. Then you'll know what is going to happen when you delete. This will be useful not only for this case, but always. </p> <p>Something like (for constraints)</p> <pre><code>select table_catalog,table_schema,table_name,column_name,rc.* from information_schema.constraint_column_usage ccu, information_schema.referential_constraints rc where ccu.constraint_name = rc.constraint_name </code></pre>
Distributed Processing: C++ equivalent of JTA <p>I'm developing a mission-critical solution where data integrity is paramount and performance a close second. If data gets stuffed up, it's gonna be cata$trophic.</p> <p>So, I'm looking for the C/C++ version of JTA (Java Transaction API). Does anyone know of any C or C++ libraries that supports distributed transactions? And yes, I've googled it ... unsuccessfully.</p> <p>I'd hate to be told that there isn't one and I'd need to implement the protocol specified by <a href="http://www.opengroup.org/pubs/catalog/c193.htm" rel="nofollow">Distributed TP: The XA Specification</a>.</p> <p>Please help!</p> <p><hr /></p> <p>Edit (responding to kervin): If I need to insert records across multiple database servers and I need to commit them atomically, products like Oracle will have solutions for it. If I've written my own message queue server and I want to commit messages to multiple servers atomically, I'll need something like JTA to make sure that I don't stuff up the atomicity of the transaction.</p>
<p>Encina, DCE-RPC, TUXEDO, possibly CORBA (though I hesitate to suggest using CORBA), MTS (again, hmm).</p> <p>These are the kind of things you want for distributed transaction processing.</p> <p><a href="http://www.zois.co.uk/tpm/encina.html" rel="nofollow">Encina</a> used to have a lot of good documentation for its DCE-based system.</p>
fatal error C1900: Il mismatch between 'P1' version '20060201' and 'P2' version '20050411' <p>I compile my project with VIsual Studio 2005 Express Edition, and get this linking error. Can anyone suggest how to solve that?</p>
<p>I downloaded VS2005 Service Pack 1 from Microsoft, installed it and it fixed the problem.</p>
Are there any tips/tricks about using Subsonic with Asp.Net MVC Framework? <p>Is there anyone using Subsonic with asp.net mvc framework? If so, can you tell us something about your experience. Are there tips and tricks that can be shared?</p>
<p>If you're planning on doing database first design, and you don't need any mapping (i.e. you're in control of your db naming) then SubSonic is a decent option.</p> <p>It's straight-forward, doesn't hide a lot from you. On the same token, for advanced scenarios I have to side-step it a lot and execute raw sql (or a sproc).</p> <p>If you're looking for a better object abstraction over the database, something that more closely matches your problem domain, then I'd look at NHibernate or Castle ActiveRecord. This gives you a lot more flexibility in how you want your object model to look, and you have a powerful query API at your disposal.</p> <p>None of this really has to do with ASP.NET MVC, other than you just use your objects in your web project. I'd suggest putting the entities inside of a separate class library project anyway.</p>
maximum size for xml files <p>whats your rule of thumb for maximum size for xml files.</p> <p>What if I ask maximum no of records, and one record have 10 values for instance? Another condition is we are loading it from web.</p>
<p>My rule is that <strong>if it's too slow to do what I want, then it's too big</strong>, and your data probably needs to be moved to some other format... database or such.</p> <p>Traversing XML nodes or using XPath can be a dog.</p>
Passing timestamp parameters in SQLAnalyzer to debug stored procedures <p>Hi I'm trying to debug a stored procedure through SQL Analyzer and one of the parameters is a timestamp datatype. If I wanted to pass 0x00000001410039E2 through as a parameter how would i do this? When I pass 0x00000001410039E2 I get a string truncation error and when I pass just 1410039E2 I get 0x1410039E20000000?</p> <p>Edit: @Frans Yes this works but my issue is that in SQLAnalyzer when i right-click and debug when I enter the value in the value textbox I get the error message:</p> <pre><code>[Microsoft][ODBC SQL Server Driver]String data, right truncation </code></pre>
<p>The debug input screen expects you to enter a hexadecimal value. You don't have to enter the 0x in front of this value. </p> <p>Just enter 00000001410039E2 and it will work.</p>
Is Java the best language for Mobile App Devlopment? <p>I was wondering what are the benefits of using anything else but Java for Mobile Application Development.</p>
<p>I do think that yes, Java is the most common language for devices, with two exceptions:</p> <ul> <li><p>Windows mobile applications, that are frequently built in C++ but that will be built more on the .NET framework in the future.</p></li> <li><p>iPhone applications, that use Cocoa and Objective-C. </p></li> </ul>
Can a web service return a stream? <p>I've been writing a little application that will let people upload &amp; download files to me. I've added a web service to this applciation to provide the upload/download functionality that way but I'm not too sure on how well my implementation is going to cope with large files.</p> <p>At the moment the definitions of the upload &amp; download methods look like this (written using Apache CXF):</p> <pre><code>boolean uploadFile(@WebParam(name = "username") String username, @WebParam(name = "password") String password, @WebParam(name = "filename") String filename, @WebParam(name = "fileContents") byte[] fileContents) throws UploadException, LoginException; byte[] downloadFile(@WebParam(name = "username") String username, @WebParam(name = "password") String password, @WebParam(name = "filename") String filename) throws DownloadException, LoginException; </code></pre> <p>So the file gets uploaded and downloaded as a byte array. But if I have a file of some stupid size (e.g. 1GB) surely this will try and put all that information into memory and crash my service.</p> <p>So my question is - is it possible to return some kind of stream instead? I would imagine this isn't going to be terribly OS independent though. Although I know the theory behind web services, the practical side is something that I still need to pick up a bit of information on.</p> <p>Cheers for any input, Lee</p>
<p>Yes, it is possible with Metro. See the <a href="https://metro.java.net/guide/ch06.html#large-attachments" rel="nofollow">Large Attachments</a> example, which looks like it does what you want.</p> <blockquote> <p>JAX-WS RI provides support for sending and receiving large attachments in a streaming fashion.</p> <ul> <li>Use MTOM and DataHandler in the programming model.</li> <li>Cast the DataHandler to StreamingDataHandler and use its methods.</li> <li>Make sure you call StreamingDataHandler.close() and also close the StreamingDataHandler.readOnce() stream.</li> <li>Enable HTTP chunking on the client-side.</li> </ul> </blockquote>
How do you retrieve a list of logged-in/connected users in .NET? <p>Here's the scenario:</p> <p>You have a Windows server that users remotely connect to via RDP. You want your program (which runs as a service) to know who is currently connected. This may or may not include an interactive console session.</p> <p>Please note that this is the <strong>not</strong> the same as just retrieving the current interactive user.</p> <p>I'm guessing that there is some sort of API access to Terminal Services to get this info?</p>
<p>Here's my take on the issue:</p> <pre><code>using System; using System.Collections.Generic; using System.Text; using System.Runtime.InteropServices; namespace EnumerateRDUsers { class Program { [DllImport("wtsapi32.dll")] static extern IntPtr WTSOpenServer([MarshalAs(UnmanagedType.LPStr)] String pServerName); [DllImport("wtsapi32.dll")] static extern void WTSCloseServer(IntPtr hServer); [DllImport("wtsapi32.dll")] static extern Int32 WTSEnumerateSessions( IntPtr hServer, [MarshalAs(UnmanagedType.U4)] Int32 Reserved, [MarshalAs(UnmanagedType.U4)] Int32 Version, ref IntPtr ppSessionInfo, [MarshalAs(UnmanagedType.U4)] ref Int32 pCount); [DllImport("wtsapi32.dll")] static extern void WTSFreeMemory(IntPtr pMemory); [DllImport("Wtsapi32.dll")] static extern bool WTSQuerySessionInformation( System.IntPtr hServer, int sessionId, WTS_INFO_CLASS wtsInfoClass, out System.IntPtr ppBuffer, out uint pBytesReturned); [StructLayout(LayoutKind.Sequential)] private struct WTS_SESSION_INFO { public Int32 SessionID; [MarshalAs(UnmanagedType.LPStr)] public String pWinStationName; public WTS_CONNECTSTATE_CLASS State; } public enum WTS_INFO_CLASS { WTSInitialProgram, WTSApplicationName, WTSWorkingDirectory, WTSOEMId, WTSSessionId, WTSUserName, WTSWinStationName, WTSDomainName, WTSConnectState, WTSClientBuildNumber, WTSClientName, WTSClientDirectory, WTSClientProductId, WTSClientHardwareId, WTSClientAddress, WTSClientDisplay, WTSClientProtocolType } public enum WTS_CONNECTSTATE_CLASS { WTSActive, WTSConnected, WTSConnectQuery, WTSShadow, WTSDisconnected, WTSIdle, WTSListen, WTSReset, WTSDown, WTSInit } static void Main(string[] args) { ListUsers("&lt;INSERT SERVERNAME HERE&gt;"); } public static IntPtr OpenServer(String Name) { IntPtr server = WTSOpenServer(Name); return server; } public static void CloseServer(IntPtr ServerHandle) { WTSCloseServer(ServerHandle); } public static void ListUsers(String ServerName) { IntPtr serverHandle = IntPtr.Zero; List&lt;String&gt; resultList = new List&lt;string&gt;(); serverHandle = OpenServer(ServerName); try { IntPtr SessionInfoPtr = IntPtr.Zero; IntPtr userPtr = IntPtr.Zero; IntPtr domainPtr = IntPtr.Zero; Int32 sessionCount = 0; Int32 retVal = WTSEnumerateSessions(serverHandle, 0, 1, ref SessionInfoPtr, ref sessionCount); Int32 dataSize = Marshal.SizeOf(typeof(WTS_SESSION_INFO)); Int32 currentSession = (int)SessionInfoPtr; uint bytes = 0; if (retVal != 0) { for (int i = 0; i &lt; sessionCount; i++) { WTS_SESSION_INFO si = (WTS_SESSION_INFO)Marshal.PtrToStructure((System.IntPtr)currentSession, typeof(WTS_SESSION_INFO)); currentSession += dataSize; WTSQuerySessionInformation(serverHandle, si.SessionID, WTS_INFO_CLASS.WTSUserName, out userPtr, out bytes); WTSQuerySessionInformation(serverHandle, si.SessionID, WTS_INFO_CLASS.WTSDomainName, out domainPtr, out bytes); Console.WriteLine("Domain and User: " + Marshal.PtrToStringAnsi(domainPtr) + "\\" + Marshal.PtrToStringAnsi(userPtr)); WTSFreeMemory(userPtr); WTSFreeMemory(domainPtr); } WTSFreeMemory(SessionInfoPtr); } } finally { CloseServer(serverHandle); } } } } </code></pre>
Method 'XYZ' cannot be reflected <p>We have consumed a third party web service and are trying to invoke it from an ASP.NET web application. However when I instantiate the web service the following System.InvalidOperationException exception is thrown:</p> <blockquote> <p>Method 'ABC.XYZ' can not be reflected. System.InvalidOperationException: Method 'ABC.XYZ' can not be reflected. ---> System.InvalidOperationException: The XML element 'MyDoc' from namespace '<a href="http://mysoftware.com/ns">http://mysoftware.com/ns</a>' references a method and a type. Change the method's message name using WebMethodAttribute or change the type's root element using the XmlRootAttribute.</p> </blockquote> <p>From what I can gather there appears to be some ambiguity between a method and a type in the web service. Can anyone clarify the probably cause of this exception and is there anything I can do to rectify this or should I just go to the web service owners to rectify?</p> <p>Edit: Visual Studio 2008 has created the proxy class. Unfortunately I can't provide a link to the wsdl as it is a web service for a locally installed thrid party app.</p>
<p>I ran into the same problem earlier today. The reason was - the class generated by Visual Studio and passed as a parameter into one of the methods did not have a default parameterless constructor. Once I have added it, the error had gone.</p>
jQuery - running a function on a new image <p>I'm a jQuery novice, so the answer to this may be quite simple:</p> <p>I have an image, and I would like to do several things with it. When a user clicks on a 'Zoom' icon, I'm running the 'imagetool' plugin (<a href="http://code.google.com/p/jquery-imagetool/" rel="nofollow">http://code.google.com/p/jquery-imagetool/</a>) to load a larger version of the image. The plugin creates a new div around the image and allows the user to pan around.</p> <p>When a user clicks on an alternative image, I'm removing the old one and loading in the new one.</p> <p>The problem comes when a user clicks an alternative image, and then clicks on the zoom button - the imagetool plugin creates the new div, but the image appears after it...</p> <p>The code is as follows:</p> <pre><code>// Product Zoom (jQuery) $(document).ready(function(){ $("#productZoom").click(function() { // Set new image src var imageSrc = $("#productZoom").attr("href"); $("#productImage").attr('src', imageSrc); // Run the imagetool plugin on the image $(function() { $("#productImage").imagetool({ viewportWidth: 300, viewportHeight: 300, topX: 150, topY: 150, bottomX: 450, bottomY: 450 }); }); return false; }); }); // Alternative product photos (jQuery) $(document).ready(function(){ $(".altPhoto").click(function() { $('#productImageDiv div.viewport').remove(); $('#productImage').remove(); // Set new image src var altImageSrc = $(this).attr("href"); $("#productZoom").attr('href', altImageSrc); var img = new Image(); $(img).load(function () { $(this).hide(); $('#productImageDiv').append(this); $(this).fadeIn(); }).error(function () { // notify the user that the image could not be loaded }).attr({ src: altImageSrc, id: "productImage" }); return false; }); }); </code></pre> <p>It seems to me, that the imagetool plugin can no longer see the #productImage image once it has been replaced with a new image... So I think this has something to do with binding? As in because the new image is added to the dom after the page has loaded, the iamgetool plugin can no longer use it correctly... is this right? If so, any ideas how to deal with it?</p>
<p>Wehey! I've sorted it out myself...</p> <p>Turns out if I remove the containing div completely, and then rewrite it with .html, the imagetool plugin recognises it again.</p> <p>Amended code for anyone who's interested:</p> <pre><code>$(document).ready(function(){ // Product Zoom (jQuery) $("#productZoom").click(function() { $('#productImage').remove(); $('#productImageDiv').html('&lt;img src="" id="productImage"&gt;'); // Set new image src var imageSrc = $("#productZoom").attr("href"); $("#productImage").attr('src', imageSrc); // Run the imagetool plugin on the image $(function() { $("#productImage").imagetool({ viewportWidth: 300, viewportHeight: 300, topX: 150, topY: 150, bottomX: 450, bottomY: 450 }); }); return false; }); // Alternative product photos (jQuery) $(".altPhoto").click(function() { $('#productImageDiv div.viewport').remove(); $('#productImage').remove(); // Set new image src var altImageSrc = $(this).attr("href"); // Set new image Zoom link (from the ID... is that messy?) var altZoomLink = $(this).attr("id"); $("#productZoom").attr('href', altZoomLink); var img = new Image(); $(img).load(function () { $(this).hide(); $('#productImageDiv').append(this); $(this).fadeIn(); }).error(function () { // notify the user that the image could not be loaded }).attr({ src: altImageSrc, id: "productImage" }); return false; }); }); </code></pre>
Deterministic dispose of ThreadStatic objects <p>The <a href="http://stackoverflow.com/questions/9033?#13932">ThreadStatic attribute</a> declares a static variable as unique-per-thread. Do you know an easy pattern to correctly dispose such variables?</p> <p>What we used before ThreadStatic is a ThreadContextManager. Every thread was allocated a ThreadContext which retained all thread-specific information. We spawned some threads and let them work. Then, when they all finished, we disposed of the ThreadContentManager, which in turn disposed all the contexts if they were IDisposable.</p> <p>I don't see an immediate way to translate this pattern to ThreadStatic objects. The objects will be disposed of eventualy, because the threads die, and so nothing reference them. However, we prefer deterministic dispose whenever possible.</p> <p><strong>Update</strong></p> <p>I do not really control the threads directly - I'm using Microsoft CCR, which has a ThreadPool that does tasks. When all the tasks are done, I'm disposing the Dispatcher (which holds the threadpool). The thing is - I do not get a chance to do anything "at the end of a thread's main function" - so I can't dispose things manually at the end of a thread's run. Can I access the thread's static objects from outside the thread somehow?</p>
<p>You can still use the equivalent of your ThreadContextManager class to handle the dispose. The spawned threads dispose of this 'manager' object which in turn takes out all the other thread static objects it knows about.</p> <p>I prefer to have relatively few thread static objects and use a context object instead. This keeps the thread specific state in only a few places, and makes patterns like this easier.</p> <p><strong>Update:</strong> to handle the threadpool case you could create a base 'task' object that is the one that you pass to the thread pool. It can perform any generic initialization your code needs, invoke the 'real' task and then performs any cleanup needed.</p>
How do I add an action to visio (2003) <p>In a visio shapesheet one can add actions. I want to create an action that updates the value of another cell (the position of a control). How can one do that. Does it need a separate macro, or can it be specified directly? And how?</p>
<p>You don't need an addon or macro, you can do this in the Shapesheet. </p> <p>In the Shapesheet look for the Action section. If you don't find it right click and add it. In the Action section add a row. Set the cells to something like:</p> <pre><code>Action = SETF(GetRef(Controls.Row_1),"2 in.")+SETF(GetRef(Controls.Row_1.Y),"2 in.") Menu = "Move Control" </code></pre> <p>Change Row_1 to the name of your control row. You can also change "2 in." to a reference to a cell in which you calculate the new position.</p> <p>To learn more see:</p> <p><a href="http://msdn.microsoft.com/en-us/library/aa200979(office.10).aspx" rel="nofollow">MSDN: Shortcut Menu Commands</a></p> <p><a href="http://blogs.msdn.com/wmorein/archive/2006/08/09/693527.aspx" rel="nofollow">Bill Morein's: Meet A Shapesheet Function: Setf</a></p>
Why does Castle Windsor hold onto transient objects? <p>Recently I noticed my application appears to be eating memory that never gets released. After profiling with CLRProfiler I've found that the Castle Windsor container I'm using is holding onto objects. These objects are declared with the lifestyle="transient" attribute in the config xml.</p> <p>I've found if I put an explicit call to <code>IWindsorContainer.Release(hangingObject)</code>, that it will drop its references.</p> <p>This is causing a problem though, I wasn't expecting that with a transient lifestyle object CastleWindsor would keep a reference and effectively create a leak. It's going to be a rather mundane and error prone task going around inserting explicit Release calls in all the appropriate places.</p> <p>Have you seen this problem, and do you have any suggestions for how to get around it?</p>
<p>I think the answers here are missing a vital point - that this behavior is configurable out of the box via release policies - check out the documentation on the castle project site <a href="http://www.castleproject.org/container/documentation/trunk/advanced/releasepolicy.html" rel="nofollow">here</a>.</p> <p>In many scenarios especially where your container exists for the lifetime of the hosting application, and where transient components really don't need to be tracked (because you're handling disposal in your calling code or component that's been injected with the service) then you can just set the release policy to the <code>NoTrackingReleasePolicy</code> implementation and be done with it.</p> <p>Prior to Castle v 1.0 I believe Component Burden will be implemented/introduced - which will help alleviate some of these issues as well around disposal of injected dependencies etc.</p> <p><strong>Edit:</strong></p> <p>Check out the following posts for more discussion of component burden.</p> <p><a href="http://elegantcode.com/2008/12/14/the-component-burden/" rel="nofollow">The Component Burden - Davy Brions</a></p> <p>Also component burden is implemented in the <a href="http://ayende.com/Blog/archive/2009/05/05/castle-windsor-2.0-rtm-released.aspx" rel="nofollow">official 2.0 release</a> of the Windsor Container.</p>
Illustrating usage of the volatile keyword in C# <p>I would like to code a little program which visually illustrates the behavior of the <code>volatile</code> keyword. Ideally, it should be a program which performs concurrent access to a non volatile static field and which gets incorrect behavior because of that. </p> <p>Adding the volatile keyword in the same program should fix the problem.</p> <p>That something I didn't manage to achieve. Even trying several times, enabling optimization, etc., I always get a correct behavior without the 'volatile' keyword.</p> <p>Do you have any idea about this topic? Do you know how to simulate such a problem in a simple demo app? Does it depend on hardware?</p>
<p>I've achieved a working example!</p> <p>The main idea received from wiki, but with some changes for C#. The wiki article demonstrates this for static field of C++, it is looks like C# always carefully compile requests to static fields... and i make example with non static one:</p> <p>If you run this example in <strong>Release</strong> mode and <strong>without debugger</strong> (Ctrl+F5) then a line 'while (test.foo != 255)' will be optimized to 'while(true)' and this program never returns. But after adding 'volatile' keyword, you always get 'OK'.</p> <pre><code>class Test { /*volatile*/ int foo; static void Main() { var test = new Test(); new Thread(delegate() { Thread.Sleep(500); test.foo = 255; }).Start(); while (test.foo != 255) ; Console.WriteLine("OK"); } } </code></pre>
How can I get jQuery to perform a synchronous, rather than asynchronous, Ajax request? <p>I have a JavaScript widget which provides standard extension points. One of them is the <code>beforecreate</code> function. It should return <code>false</code> to prevent an item from being created. </p> <p>I've added an Ajax call into this function using jQuery:</p> <pre><code>beforecreate: function (node, targetNode, type, to) { jQuery.get('http://example.com/catalog/create/' + targetNode.id + '?name=' + encode(to.inp[0].value), function (result) { if (result.isOk == false) alert(result.message); }); } </code></pre> <p>But I want to prevent my widget from creating the item, so I should return <code>false</code> in the mother-function, not in the callback. Is there a way to perform a synchronized Ajax request using jQuery or any other API?</p>
<p>From the <a href="http://docs.jquery.com/Ajax/jQuery.ajax">jQuery documentation</a>: you specify the <strong>asynchronous</strong> option to be <strong>false</strong> to get a synchronous Ajax request. Then your callback can set some data before your mother function proceeds.</p> <p>Here's what your code would look like if changed as suggested:</p> <pre><code>beforecreate: function (node, targetNode, type, to) { jQuery.ajax({ url: 'http://example.com/catalog/create/' + targetNode.id + '?name=' + encode(to.inp[0].value), success: function (result) { if (result.isOk == false) alert(result.message); }, async: false }); } </code></pre>
In Perforce, can you rename a folder to the same name but cased differently? <p>Can I rename a folder in Perforce from <em>//depot/FooBar/</em> to <em>//depot/Foobar/</em>?</p> <p>I've tried this by renaming from <em>//depot/FooBar/</em> to <em>//depot/Temp/</em> to <em>//Depot/Foobar/</em> but the end result ends up the same as <em>//depot/FooBar/</em>.</p>
<p>Once it is in Perforce, the case remains set. As mentioned by Johan you can obliterate, set the name up correctly, and add it in again. However, there is a slight gotcha....</p> <p>If anyone else (running Windows) has already synced the wrong-cased version, then when they sync again the right one, it will not change the case on their PC. This is a peculiarity of the Windows file system acknowledging case but still being fundamentally case-independent.</p> <p>If a number of users have synced, and it is not convenient to get them to remove-from-client too (and blasting the folders from their machines), then you can resort to a dark and dirty Perforce technique called "Checkpoint surgery". It's not for the fainthearted, but you do this:</p> <ol> <li>Stop your server, take a checkpoint.</li> <li>Using your favourite text editor that can handle multi-megabyte files, search &amp; replace all occurances of the old case name with the new. You could of course use a script too.</li> <li>Replay your checkpoint file to recreate the Perforce database meta data.</li> <li>Restart your server.</li> </ol> <p>This will affect all user client specs transparently, and so when they sync they will get the right case as if by magic.</p> <p>It sounds hairy, but I've had to do it before and as long as you take care, backup, do a trial run etc, then all should be OK.</p>
Programatically delete emails and SMSs on a Window Mobile device <p>I'm looking for a code snippet that can delete all emails and text messages on a Windows Mobile device. Preferably the code would delete items in the Sent and Drafts folders as well as the Inbox. </p> <p>My platform is Windows Mobile (5.0 SDK) and .net 2.0 compact framework (C# / VB.NET)</p> <p>Many thanks</p>
<p>Unfortunately Microsoft has <strong>not</strong> made this easy for managed developers. Why the WindowsMobile.PocketOutlook class wrappers don't provide this functionality one can only guess. What you have to do is write your own COM interop object to MAPI. Sorry, I don't have one to give you as a sample, but I can at least give you pointers to the methods you'll be interested in:</p> <ul> <li><a href="http://msdn.microsoft.com/en-us/library/ms859847.aspx" rel="nofollow">IMAPI::GetMsgStoresTable</a></li> <li><a href="http://msdn.microsoft.com/en-us/library/ms859878.aspx" rel="nofollow">IMAPISession::OpenMessageStore</a></li> <li><a href="http://msdn.microsoft.com/en-us/library/ms860167.aspx" rel="nofollow">IMsgStore::OpenEntry</a></li> <li><a href="http://msdn.microsoft.com/en-us/library/ms859723.aspx" rel="nofollow">IMAPIFolder::DeleteMessages</a></li> </ul> <p><a href="http://inthehand.com/content/Mobile.aspx" rel="nofollow">InTheHand has a wrapper</a> that has additional methods for POOM, but I've never used it and I don't know if it has anything that does what you need. Might be worth a look, though, before embarking on rolling this yourself.</p>
What's the difference between a "Data Service Layer" and a "Data Access Layer"? <p>I remember reading that one abstracts the low level calls into a data agnostic framework (eg. ExecuteCommand methods etc), and the other usually contains business specific methods (eg. UpdateCustomer).</p> <p>Is this correct? Which is which?</p>
<p>To me this is a personal design decision on how you want to handle your project design. At times data access and data service are one and the same. For .NET and LINQ that is the case.</p> <p>To me the data service layer is what actually does the call to the database. The data access layer receives the objects and creates them or modify them for the data service layer to make the call to the database.</p> <p>In my designs the Business Logic Layer manipulates the objects based on the business rules, then passes them to the data access layer which will format them to go into the database or the objects from the database, and the data service layer handles the actual database call.</p>
Configure db used for ASP.Net Authentication <p>I want to use forms authentication in my asp.net mvc site.</p> <p>Can I use an already existing sql db (on a remote server) for it? How do I configure the site to use this db for authentication? Which tables do I need/are used for authentication?</p>
<p>You can. Check <code>aspnet_regsql.exe</code> program parameters in your Windows\Microsoft.NET\Framework\v2.xxx folder, specially <code>sqlexportonly</code>.</p> <p>After creating the needed tables, you can configure: create a connection string in the web.config file and then set up the MemberShipProvider to use this connection string:</p> <pre><code> &lt;connectionStrings&gt; &lt;add name="MyLocalSQLServer" connectionString="Initial Catalog=aspnetdb;data source=servername;uid=whatever;pwd=whatever;"/&gt; &lt;/connectionStrings&gt; &lt;authentication mode="Forms"&gt; &lt;forms name="SqlAuthCookie" timeout="10" loginUrl="Login.aspx"/&gt; &lt;/authentication&gt; &lt;authorization&gt; &lt;deny users="?"/&gt; &lt;allow users="*"/&gt; &lt;/authorization&gt; &lt;membership defaultProvider="MySqlMembershipProvider"&gt; &lt;providers&gt; &lt;clear/&gt; &lt;add name="MySqlMembershipProvider" connectionStringName="MyLocalSQLServer" applicationName="MyAppName" type="System.Web.Security.SqlMembershipProvider, System.Web, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a"/&gt; &lt;/providers&gt; &lt;/membership&gt; </code></pre> <p>Ps: There are some very good articles about the whole concept <a href="http://aspnet.4guysfromrolla.com/articles/120705-1.aspx" rel="nofollow">here</a>.</p>
How do you handle small sets of data? <p>With really small sets of data, the policy where I work is generally to stick them into text files, but in my experience this can be a development headache. Data generally comes from the database and when it doesn't, the process involved in setting it/storing it is generally hidden in the code. With the database you can generally see all the data available to you and the ways with which it relates to other data.</p> <p>Sometimes for really small sets of data I just store them in an internal data structure in the code (like A Perl hash) but then when a change is needed, it's in the hands of a developer. </p> <p>So how do you handle small sets of infrequently changed data? Do you have set criteria of when to use a database table or a text file or..? </p> <p>I'm tempted to just use a database table for absolutely everything but I'm not sure if there are any implications to this.</p> <p><strong>Edit:</strong> For context:</p> <p>I've been asked to put a new contact form on the website for a handful of companies, with more to be added occasionally in the future. Except, companies don't have contact email addresses.. the users inside these companies do (as they post jobs through their own accounts). Now though, we want a "speculative application" type functionality and the form needs an email address to send these applications to. But we also don't want to put an email address as a property in the form or else spammers can just use it as an open email gateway. So clearly, we need an ID -> contact_email type relationship with companies. </p> <p>SO, I can either add a column to a table with millions of rows which will be used, literally, about 20 times OR create a new table that at most is going to hold about 20 rows. Typically how we handle this in the past is just to create a nasty text file and read it from there. But this creates maintenance nightmares and these text files are frequently looked over when data that they depend on changes. Perhaps this is a fault with the process, but I'm just interested in hearing views on this.</p>
<p>Put it in the database. If it changes infrequently, cache it in your middle tier.</p>
propertyNameFieldSpecified when generating a 2.0 web service proxy from a WCF Service <p>I have created a web reference (Add Web Reference) from Visual Studio 2008 and strangely, I need to set the <em>propertyNameField</em>Specified to true for all the fields I want to submit. Failure to do that and values are not passed back to the WCF Service. </p> <p>I have read at several places that this was fixed in the RTM version of Visual Studio. Why does it still occurring?</p> <p>My data contracts are all valid with nothing else than properties and lists. Any ideas?</p>
<p>Here is a complete answer: <a href="http://blogs.msdn.com/eugeneos/archive/2007/02/05/solving-the-disappearing-data-issue-when-using-add-web-reference-or-wsdl-exe-with-wcf-services.aspx" rel="nofollow">http://blogs.msdn.com/eugeneos/archive/2007/02/05/solving-the-disappearing-data-issue-when-using-add-web-reference-or-wsdl-exe-with-wcf-services.aspx</a></p>
Balancing a Binary Tree (AVL) <p>Ok, this is another one in the theory realm for the CS guys around.</p> <p>In the 90's I did fairly well in implementing BST's. The only thing I could never get my head around was the intricacy of the algorithm to balance a Binary Tree (AVL).</p> <p>Can you guys help me on this?</p>
<p>I don't think it's good to post complete codes for node balancing algorithms here since they get quite big. However, the Wikipedia article on <a href="http://en.wikipedia.org/wiki/Red-black_tree">red-black trees</a> contains a complete C implementation of the algorithm and the article on <a href="http://en.wikipedia.org/wiki/AVL_tree">AVL trees</a> has several links to high-quality implementations as well.</p> <p>These two implementations are enough for most general-purpose scenarios.</p>
How can I access a mapped network drive with System.IO.DirectoryInfo? <p>I need to create a directory on a mapped network drive. I am using a code:</p> <pre><code>DirectoryInfo targetDirectory = new DirectoryInfo(path); if (targetDirectory != null) { targetDirectory.Create(); } </code></pre> <p>If I specify the path like "\\\\ServerName\\Directory", it all goes OK. If I map the "\\ServerName\Directory" as, say drive Z:, and specify the path like "Z:\\", it fails.</p> <p>After the creating the targetDirectory object, VS shows (in the debug mode) that targetDirectory.Exists = false, and trying to do targetDirectory.Create() throws an exception:</p> <pre><code>System.IO.DirectoryNotFoundException: "Could not find a part of the path 'Z:\'." </code></pre> <p>However, the same code works well with local directories, e.g. C:.</p> <p>The application is a Windows service (WinXP Pro, SP2, .NET 2) running under the same account as the user that mapped the drive. Qwinsta replies that the user's session is the session 0, so it is the same session as the service's.</p>
<p>Mapped network drives are user specific, so if the app is running under a different identity than the user that created the mapped drive letter (z:) it won't work.</p>
spawn a new xterm window <p>When I am using Bitvise Tunnelier and I spawn a new xterm window connecting to our sun station everything works nicely. We have visual slick edit installed on the sun station and I have been instructed to open it using the command vs&amp;. When I do this I get the following:</p> <pre><code>fbm240-1:/home/users/ajahn 1 % vs&amp; [1] 4716 fbm240-1:/home/users/ajahn 2 % Visual SlickEdit: Can't open connection to X. DIS PLAY='&lt;Default Display&gt;' </code></pre> <p>I would rather not go jumping through hoops ftping my material back and forth to the server. Advice?</p>
<p>You're going to need an Xwindows server on your Windows box in order to run graphical Unix apps remotely on the Sun server and have it display on your Windows box. I don't think Tunnelier supports Xwindows tunneling. Take a look at Xming, an Xwindows server for Windows that comes with Putty, an ssh client:</p> <p><a href="http://sourceforge.net/projects/xming" rel="nofollow">http://sourceforge.net/projects/xming</a></p> <p><strong>edit:</strong> Glad to see this worked for you. Here's some more explanation on what's happening. X-Windows, the Unix graphical environment is client-server based. IE: it's able to display individual graphical windows on remote systems without full-screen software like VNC or remote desktop. A graphical program in Unix is called the X-Windows client, and the thing that actually does the displaying is called an X-Windows server.</p> <p>Now, Bitvise Tunnelier is just an ssh client. IE: it only deals with command-line terminal connections. However, the ssh protocol is actually able to tunnel X-Windows over ssh, but you need two things: 1) an X-Windows server running on your desktop (to actually display the app), and 2) an ssh client that supports X-Windows tunneling. Enter Xming, a lightweight X server for windows, and Putty, the ssh client.</p> <p>So, you were fine ssh-ing in to your Sun box, and typing terminal commands, but Visual SlickEdit is an X-Windows client app. To run that, you needed an X-Windows server. When an X-Windows server is available, it sets the DISPLAY variable on the terminal to tell graphical apps where to display stuff.</p> <p>One more note: Some of the answers below recommended that you set the DISPLAY variable to the hostname of your Sun box. That might have worked, but it would have displayed the VS windows on the Sun's screen, not your Windows box.</p>
.NET - How to hide invalid choices in a DateTimePicker <p>I've set the MaxDate and MinDate properties of a DateTimePicker. However, when I test the control at runtime, there is no way to tell the invalid dates from the valid ones. The only difference is that clicking on an invalid date does nothing.</p> <p>This is not very intuitive for the user. I want to be able to tell at a glance what the valid dates are.</p> <p>Is there any way to highlight the valid date range - or more appropriately, 'dim' the invalid dates? Or, is there another control which would be more appropriate? I'm sure a couple of combo boxes would work, but I really think the user should be presented with a calendar control when asked for a date.</p> <p>CONTEXT: This is a WinForms charting application. The range of valid data is fixed (new data is added via another process). The user needs to pick a date and time for the chart's start time (as well as a duration, which is handled separately).</p>
<p>I have a similar issue. I've extended the DateTimePicker control to run a validate process whenever the value changes and to either revert to the previous value or to the nearest legal value in the event of an illegal choice. </p> <p>The logical extension to this is to flash up a warning dialog or label to inform the user that this has happened. </p> <p>You could also override the calendar display portion of the control to highlight/lowlight the invalid options - it already highlights the current day and the current selection, for example. </p>