input
stringlengths
51
42.3k
output
stringlengths
18
55k
Why does Visual Studio launch multiple WebDevs when I debug? <p>I have a Visual Studio 2008 solution with several projects in it - some of which are web applications / sites. </p> <p>Whenever I go "Debug > Start new instance" for a specific web application and VS launches the ASP.net Development Server (WebDev.WebServer.EXE) for that application, VS also launches 3 additional such processes - one for each of 3 other web applications I have in the solution.</p> <p>How can I tell Visual Studio to only launch WebDev for the one project I'm debugging? I've looked both in the project configurations and in the solution configuration and could not find the relevant setting... </p>
<p>See the accepted answer here:</p> <p><a href="http://stackoverflow.com/questions/16363/how-do-you-configure-vs2008-to-only-open-one-webserver-in-a-solution-with-multi#16390">http://stackoverflow.com/questions/16363/how-do-you-configure-vs2008-to-only-open-one-webserver-in-a-solution-with-multi#16390</a></p>
IDictionary<string, string> versus Dictionary<string, string> <p>what is the value of using IDictionary here?</p>
<p>The value of using an interface is always the same: you don't have to change client code when switching to another backend implementation.</p> <p>Consider that profiling your code later shows that a hash table implementation (used in the <code>Dictionary</code> class) isn't suited for your task and that a binary search tree would perform better. If you've coded to an interface then switching the implementation is straightforward. If, however, you've used a concrete class, you've got to change a lot more code in a lot more places. => This costs time and money.</p>
Synchronizing databases <p>I am developing an Adobe AIR application which stores data locally using a SQLite database. At any time, I want the end user to synchronize his/her local data to a central MySQL database.</p> <p>Any tips, advice for getting this right? Performance and stability is the key (besides security ;))</p>
<p>I can think of a couple of ways:</p> <ol> <li><p>Periodically, Dump your MySQL database and create a new SQLite database from the dump. You can then serve the SQLite database (SQLite databases are contained in a single file) for your users client to download and replace the current database.</p></li> <li><p>Create a diff script that generates the necessary statements to bring the current database up to speed (various INSERT, UPDATE and DELETE statements). To do this, you must record the time of each change continuously in your database (the time of creation and update for each row, and keep a history of deleted rows). User's client will download the diff file (a text file of the various statements) and apply it on the local database.</p></li> </ol> <p>Both approaches have their own pros and cons - by dumping the entire database, you make sure all the data gets through. It is also much easier than creating the diff, however it might put more load on the server, depending on how often does the database gets updated between dumps. </p> <p>On the other hand, diffing between the database will give you just the data that changed (hopefully), but it is more open to logical errors. It will incur an additional overhead on the client as well, since it will have to create/update all the necessary records instead of just copying a file.</p>
C: the definitive truth about rand, random and arc4random <p>There's a lot of conflicting information about this topic. So let's try to agree on a definitive answer:</p> <p>Which one of these random number generator in C create better randomness: rand, random or arc4random?</p> <p>note: Just to make the question clear, this is not a question about true randomness, it's only a clash between those 3.</p> <p><hr /></p> <p>As pointed out, this question doesn't make much sense, as this is not about C, but about a specific implementation, in my case, cocoa (more specifically the iphone sdk, but my guess is they are the same as far as these functions go). Still, there's some useful information here. I concluded by implementing arc4random, mostly because of its ease of use (no seeding needed), which is an important factor that no one pointed out.</p> <p>I'm closing the question, and adding the cocoa tag for cocoa developers looking for information on RNGs. Many thanks for those who contributed, and sorry for the confusion.</p>
<p>Of these functions, only rand is part of standard C. random is part of POSIX, and arc4random is only provided in BSD (and derived). So only rand is "in C".</p> <p>For rand, the C standard says nothing about the quality of the generator, i.e. returning always the same number would be conforming. It says that the number must be between 0 and RAND_MAX. The value of RAND_MAX, and the precise algorithm being used, are implementation defined (although RAND_MAX must be at least 32767).</p> <p>For random, POSIX <a href="http://opengroup.org/onlinepubs/009695399/functions/initstate.html">specifies</a> that it must have a period of atleast 2^31 by default, and, if initstate is called with 256 bytes of state, then it must have a period of atleast 2^69; other details are again implementation-defined.</p> <p>For arc4random, the specific implementation is part of its definition (RC4). It's specified that it gives 2^32 different values; I could not find anything about its period.</p> <p>To compare them in detail, one would have to know what specific implementation you refer to.</p>
Looking for some good resources to get started with Django <p>All,</p> <p>I'd like to check Django out and maybe hack together some web pages to see how it feels - but after having a look at a few tutorials like <a href="http://www.showmedo.com/videos/video?name=stoops010" rel="nofollow">this one</a> I am starting to wonder if there is any way of getting it up and runinng without typying cmd line stuff for 1/2 hour.</p> <p>Can people point out some good straightforward resources/tutorials to get the thing up and running? </p> <p>I plan doing this on Windows environment.</p>
<p>As someone who just started playing around with Django as well, I found the official documentation very helpful. Just walk through the "First steps" tutorials at:</p> <p><a href="http://docs.djangoproject.com/en/dev/" rel="nofollow">http://docs.djangoproject.com/en/dev/</a></p> <p>It will teach you the gist of Django it in a very short time. This is definitely one of the best official documentation of a framework I've seen so far.</p> <p>In order to test it out under Windows, just installing the latest release should be enough as described <a href="http://docs.djangoproject.com/en/dev/topics/install/#installing-an-official-release" rel="nofollow">here</a> (given that Python itself is already installed, of course).</p> <p>The second tutorial I looked at, was <a href="http://www.djangobook.com/" rel="nofollow">"The Django Book"</a>. While this is also written very well, it's a little bit outdated and doesn't cover the new style admin yet. Just beware of the admin pages examples if you would like to go through this tutorial as well.</p>
Best Practice: When to dispatch back to the UI Thread <p>I have a question on best pactices. When is the best time to dispatch a call back to the UI when using a helper loading method like the two below? Button1 uses the Dispatcher when returned and Button2 allows the helper loading class to encapsulate the call on the Dispatcher. I tend to favor the Button2.</p> <pre><code>private void Button1_Click(object sender, RoutedEventArgs e) { AsyncLoader.LoadAsyncWithoutDispatcher(delegate(string result) { this.Dispatcher.Invoke((Action)delegate { this.TextBox1.Text = result; }); }); } private void Button2_Click(object sender, RoutedEventArgs e) { AsyncLoader.LoadAsyncWithDispatcher(this.Dispatcher, delegate(string result) { this.TextBox1.Text = result; }); } class AsyncLoader { public static void LoadAsyncWithoutDispatcher(Action&lt;string&gt; completed) { var worker = new AsyncClass(); worker.BeginDoWork(delegate(IAsyncResult result) { string returnValue = worker.EndDoWork(result); completed(returnValue); }, null); } public static void LoadAsyncWithDispatcher(Dispatcher dispatcher, Action&lt;string&gt; completed) { var worker = new AsyncClass(); worker.BeginDoWork(delegate(IAsyncResult result) { string returnValue = worker.EndDoWork(result); dispatcher.Invoke(completed, returnValue); }, null); } } </code></pre>
<p>If the code is generic and not really tight to WPF infrastructure, the first method is definitely more generic as it completely ignores the use of a dispatcher object. If your class is tightly integrated to WPF, the second method is a better practice since you have to call the method using a Dispatcher. In the first method, it's possible to not specify dispatcher at all. This is certainly not a recommended thing in WPF.</p>
Accessing stored structures for which I have an xml description <p>I have set up a sort of introspection-enabling C++ library that allows, using minimum macros and a fair amount of template trickery, to declare structures and classes that get enriched with some meta-information.</p> <p>This meta-information captures all important details about each field of the struct/class that you declare, and at the end of the story you are able, for each struct/class enriched in this way, to produce an xml file that dumps, for each field, its name,type,len,offset etc. etc.</p> <p>For my problem, I don't need to support fields that are pointers, but only primitive types, arrays and STL containers (vectors, lists etc.)</p> <p>The code that populates these meta-enriched structs/classes (the "producer"), at a certain point serializes them (for now it's a simple binary dump of all primitive types and of all the "buffers" used by the STL containers, if any).</p> <p>Now I need to start developing a "reader" counterpart that is able <strong>at runtime</strong>, starting from the xml description that has been built by the "producer", to access the various fields of the stored data.</p> <p>I think it's a problem of dynamic data-dictionary interpretation, but all that I have found up to know is related to read back xml data, while I have binary data and an xml description of it...</p> <p>What is the best way to start on this? Is something out there that resembles this problem and that I could get inspiration from?</p>
<p>/* smarc's keeping it simple */</p> <pre><code> class xmlstream { ... }; class ibase { void read( xmlstream&amp; rStream ) = 0; void write( xmlstream&amp; rStream ) = 0; }; class classfactory { void produce( xmlstream&amp; rStream ); void consume( xmlstream&amp; rStream ); ibase* create( xmlstream&amp; rStream ); void destroy( ibase* pBase ); }; class class1 : public ibase { static class1* create( ); static void destroy( class1* pObject ); void read( xmlstream&amp; rStream ); void write( xmlstream&amp; rStream ); }; class class2 : public ibase { static class1* create( ); static void destroy( class1* pObject ); void read( xmlstream&amp; rStream ); void write( xmlstream&amp; rStream ); }; </code></pre> <p>Let me if this isn't clear.</p>
FileNotFound exception when using XmlSerializer <p>When trying to serialize a type (a generic <code>List&lt;T&gt;</code> which T is a class marked with XmlRootAttribute) into XML using <code>XmlSerializer</code>, a <code>FileNotFoundException</code> is thrown (sometimes) and serialization fails.</p> <p>It seems that <code>XmlSerializer</code> tries to create a temporary file with a random file name in the Temp folder of user under which the application is running, but the file gets deleted somehow.</p> <p>Anyone seen this? Any workarounds?</p>
<p>XmlSerializer works by generating <em>code</em> to do the serialization/deserialization, and storing this in a temporary assembly. (This approach gives good performance for repeated serialization/deserialization but (traditionally) shockingly awful performance for the first run)</p> <p>To help mitigate the shocking performance, from VS2005 onwards (and earlier using less well known techniques), you can explicitly create the serialization assembly at build time and ship it with your main assembly.</p> <p>If you <em>don't</em> create/ship the serialization assembly, then the framework tends to throw an exception when it's looking for it, though normally it catches the exception, builds the assembly on the fly, and gets on with things. If you're running under a debugger, with 'break-on-throw' set though, it can be a bit alarming to have the FileNotFound exception being thrown deep in the bowels of the framework.</p> <p>Are you <em>sure</em> that the FileNotFound exception is directly associated with the serialization failure you're seeing? Have you tried including the serialization assembly explicitly?</p>
Should I design the application or model (database) first? <p>I am getting ready to start building a new web project in my spare time to bring to fruition an idea that has been bouncing around my head for a while.</p> <p>I have never gotten down whether I am better off first building the model and then the consuming application or the other way around.</p> <p>What are the best practices? What would you build first and why?</p> <p>I imagine that in general the application should generally drive the model, however the application like many websites really doesn't do much without the model.</p> <p>For some reason I find it easier at times to think in terms of the model since the application is really just actions on the model. Is this a poor way of thinking about things?</p> <p>What advantages/disadvantages does each option have?</p>
<p>When you're building the whole application yourself, I would start with the user. What does the user want? What information do they need? That should drive the design of the application and model, not the other way round. When the model is designed first, there is a temptation to expose the user to it directly, which will rarely make sense.</p>
UIView bounds with top bar <p>When creating a UIView with a navigation bar in interface builder, the top bar takes some space, but the view still has the same size. This mean that the bottom of the view is not visible.</p> <p>Is there a way to get the "visible size" of a UIView? I would like to show a subview at the bottom of the screen, but part of the subview is hidden since the parent view goes "below" the screen.</p>
<p>You should use the 'struts-and-springs' control in IB to set your base view to be full-justified. Then it will auto-resize. Once you do this, you can just use the view.bounds property to access its visible area.</p>
Singleton heritage <p>The singleton is explained here: <a href="http://en.wikipedia.org/wiki/Singleton_pattern#PHP_5" rel="nofollow">http://en.wikipedia.org/wiki/Singleton_pattern#PHP_5</a>. I want to use the singleton class as a superclass, and extend it in other classes that are supposed to be singletons. The problem is, the superclass makes an instance of itself, not the subclass. Any idea how I can make the Superclass create an instance of the Subclass?</p> <pre><code> class Singleton { // object instance private static $instance; protected function __construct() { } public function __clone() { } public function __wakeup() { } protected static function getInstance() { if (!self::$instance instanceof self) { self::$instance = new self; if(self::$instance instanceof Singleton) echo "made Singleton object&lt;br /&gt;"; if(self::$instance instanceof Text) echo "made Test object&lt;br /&gt;"; } return self::$instance; } } class Test extends Singleton { private static $values=array(); protected function load(){ $this-&gt;values['a-value'] = "test"; } public static function get($arg){ if(count(self::getInstance()-&gt;values)===0) self::getInstance()-&gt;load(); if(isset(self::getInstance()-&gt;values[$arg])) return self::getInstance()-&gt;values[$arg]; return false; } } </code></pre>
<p>This is a limitation of PHP - a parent class cannot determine the name of a subclass on which its methods are statically called.</p> <p>PHP 5.3 now has support for late static bindings, which will let you do what you need to, but it will be a while before that is widely available. See some information <a href="http://php.net/oop5.late-static-bindings" rel="nofollow">here</a></p> <p>There are several similar questions on here which might be worth reading for possible workarounds, for example <a href="http://stackoverflow.com/questions/283004/getting-the-name-of-a-child-class-in-the-parent-class-static-context#283698">this one</a></p>
MySaifu JVM and BlueCove API on an iPAQ <p>Having a bit of an issue running BlueCove on my iPAQ (h5550). I installed MySaifu JVM and added the BlueCove jar library to the classpath, but whenever I try to run the tester jar or any other files that reference the BlueCove API, I get class not found exceptions.</p> <p>Anyone had the same issues? I know from the BlueCove documentation that it's been tested on MySaifu on Windows CE, a name sometimes (confusingly) used interchangeably with Windows Mobile and Pocket PC, so maybe it's just a case of compatibility?</p> <p>Any help would be appreciated.</p> <p>SUMMARY:</p> <ul> <li>Bluecove not working after being added to MySaifu classpath <ul> <li>Class not found exceptions</li> </ul></li> <li>iPAQ h5550 <ul> <li>Windows Mobile 2003 (Pocket PC) </li> </ul></li> </ul>
<p>Some time ago I tested MySaifu JVM and it didn't seem to have a complete imlementation of the CDC Personal Profile 1.1 (the most complete). I don't know what J2ME profile does that program need but problems could start from that point.</p> <p>Other issue is that not all Windows CD/Mobile platforms are identical so what runs ok on a Windows Mobile 2003 PDA may not work on another Windows Mobile 2003 PDA.</p> <p>If you plan to develop enterprise-grade Java applications the only acceptable choice today is the <a href="http://www-01.ibm.com/software/wireless/weme/" rel="nofollow">IBM Everyplace WebSphere Micro Envinronment</a> (previously known as J9 JVM), which is not free though the license is pretty inexpensive.</p> <p>Anyway if you plan to stick to MySaifu pasting the exception would help to clarify where the error is.</p>
How do I programatically change options in Access? <p>in Microsoft Access, is there a way which I can programatically set the Confirm Action Queries flag on the options screen to False? Ideally when the database is started up I would like to check if it's true, and if so, mark it as false for the currently logged in user.</p> <p>The application is locked down reasonably tightly, so ideally, we don't want to have to give users acces to the action menu.</p> <p>Thanks in advance.</p> <p>PG</p>
<p>Place the following in a method when the database starts:</p> <pre><code>If Application.GetOption("Confirm Action Queries") Then Application.SetOption "Confirm Action Queries", False End If </code></pre>
Can you enable [Authorize] for controller but disable it for a single action? <p>I would like to use <code>[Authorize]</code> for every action in my admin controller except the <code>Login</code> action. </p> <pre><code>[Authorize (Roles = "Administrator")] public class AdminController : Controller { // what can I place here to disable authorize? public ActionResult Login() { return View(); } } </code></pre>
<p>You can decorate your controller with [Authorize] and then you can just decorate the method that you want to exempt with [AllowAnonymous]</p>
How to setup 2 actions with the same name, 1 Authorized and 1 not Authorized? <p>Is it possble to have something like this in ASP.NET MVC...</p> <pre><code>[Authorize] [AcceptVerbs(HttpVerbs.Get)] public string AddData(string Issues, string LabelGUID) { return "Authorized"; } [AcceptVerbs(HttpVerbs.Get)] public string AddData() { return "Not Authorized"; } </code></pre> <p>So if the user is not logged in, it defaults to the un-Authorized action.</p>
<p>Yes, its possible. You would need to create your own <code>ControllerActionInvoker</code> and override the <code>FindActionMethod</code> member. I'd let the base class do it's work and then check to see if the method it returns satisfies your criteria and if not, return a better match.</p> <p>I'm doing something like this to allow my Controllers to have a "Default Action" and it works well. Check out MvcContrib and their implementation of their ActionInvoker for a really nice example.</p>
Can any processing be done on the model? [MVC] <p>I've decided to make a big push towards MVC for all new sites I make. I have a question about whether or not you can have any processing on the model level.</p> <p>The case that brought up this question is a video site. I have a Video class (model) and one of the things I need to do when a user views the video I need the view to be logged in the database. I'm not sure if I need to add a query in the controller or if I can add a addView method in the Video class.</p> <p>The basic underlying question for me is what kind of methods am I limited to in the models? Can it be anything or does it have to be only accessor (a.k.a getValue/setValue) methods?</p>
<p>Ruby on Rails has the motto <a href="http://weblog.jamisbuck.org/2006/10/18/skinny-controller-fat-model" rel="nofollow">skinny controller, fat model</a>. This doesn't apply to just Rails and should be practiced with any mvc framework.</p>
Can Silverlight 2.0 pages be removed from a collection manually (garbage collected)? <p>I have multiple xaml based pages stored as children of a canvas on another page. I add and remove the children pages as the application runs. However, pages that are removed from the children collection are still running and respond to keyboard shortcuts. How can I force the older pages to be removed completely? </p>
<p>When you have your XAML pages displayed, are you registering for keyboard events? If so, are you forgetting to unregister from keyboard events when you remove those pages from the screen?</p> <p>Since there is no "Unloading"-like event on either the UserControl or Page class in Silverlight (at least that I know of), what I do is have my pages implement a interface I define that contains a single method like "Cleanup" or "Close". Before I remove the control from the screen, I call Cleanup() on the control and have it do things like unregister from events it may have registered.</p> <p>If you don't unregister from events the page's object will never be garbage collected because the CLR thinks the object is still live.</p>
CSS: Fixed or Float Layout? <p>My question revolves around CSS Fixed Layout vs a Float Layout that extends to fill the width of the browser.</p> <p>Right now the issue I'm running into is to have the masthead resize depending on the width of the page (something that I understand isn't possible given current browser implementation of <a href="http://www.w3.org/TR/2002/WD-css3-background-20020802/" rel="nofollow">CSS3's <code>background-image: size;</code></a>). At this point, I feel like I've reached an impasse all around: Do I rework the site to use a fixed CSS layout, or do I keep the current layout and try to make the masthead image expand to fill most of the space provided? Moreover, what are the pros and cons of moving to a fixed width layout, and the other (unseen) ramifications of using one layout over another?</p> <p>The site in question will be given as a comment to this question -- I don't want to be seen as trying to increase traffic to it.</p> <p>Edit: Any other thoughts?</p>
<p>What about revealing more or less of the image as the browser is resized, rather than scaling the image? It's not quite the same effect, but it's an easy way to fill an entire space with an image.</p> <p>Let's assume, for the sake of the example, that your masthead's background image contains a logo of some sort on top of, say, a photograph of a city skyline. This is, overall, 1600px wide. The logo sits to the left of the image while the cityscape extends far right. And we'll assume your markup looks roughly like this:</p> <pre><code>&lt;div id="page"&gt; &lt;div id="masthead"&gt;...&lt;/div&gt; &lt;div id="navigation"&gt;...&lt;/div&gt; ... &lt;/div&gt; </code></pre> <p>We can set the #page element to an <a href="http://www.alistapart.com/articles/elastic" rel="nofollow">elastic</a> width and apply a background image to the #masthead element:</p> <pre><code>#page { max-width: 1600px; min-width: 800px; width: 80%; } #masthead { background: url('path/to/image.jpg') no-repeat left top; height: 100px; width: auto; } </code></pre> <p>What happens here is that the #masthead element will expand to the width of the #page element, which will be somewhere between 800px and 1600px wide (inclusive) depending on how wide the browser window is. When the #page element is 800px wide, you see only the left-most 800px of the skyline; when it's 1600px wide, you see the entire skyline. That way your logo is always visible and when the browser is resized, more of the cityscape is revealed.</p> <p>This does require having a larger image to start with (at least as wide as your max-width, if you go elastic), but the result is a masthead that will look good no matter what size it is--without relying on, as strager mentioned, browsers' image resizing algorithms.</p>
how can I draw it using starUml <p>I am using staruml, I find it is hard to draw a perfect UML class diagram when the relation is complex.<a href="http://img360.imageshack.us/my.php?image=serviceloadertw5.jpg" rel="nofollow">uml diagram</a></p>
<p>If your UML Diagrams are getting too complex try breaking the digram up into several diagrams each of which covers a smaller subset of classes. You may even want to move your classes into seperate packages to keep them organised. In Star UML (and other UML Tools) classes can appear in more than one diagram so you can include all the classes from one package plus the classes from a differnt package's public interface.</p>
Rationale behind return 0 as default value in C/C++ <p>Is there a reason why zero is used as a "default" function return value? I noticed that several functions from the stdlib and almost everywhere else, when not returning a proper number (e.g pow(), strcpy()) or an error (negative numbers), simply return zero.</p> <p>I just became curious after seeing several tests performed with negated logic. Very confusing.</p> <p>Why not return 1, or 0xff, or any positive number for that matter?</p>
<p>The rationale is that you want to distinguish the set of all the possible (negative) return values corresponding to different errors <em>from</em> the only situation in which all went OK. The simplest, most concise and most C-ish way to pursue such distinction is a logical test, and since in C all integers are "true" except for zero, you want to return zero to mean "the only situation", i.e. you want zero as the "good" value.</p> <p>The same line of reasoning applies to the return values of Unix programs, but indeed in the tests within Unix shell scripts the logic is inverted: a return value of 0 means "true" (for example, look at the return value of /bin/true).</p>
How do I show a caret (^) in math mode in LaTeX? <p>I'm trying to display a caret (<code>^</code>) in math mode in LaTeX to represent the exclusive or operation implemented in the "C languages". By default, <code>^</code> is for creating a superscript in math mode. The closest I can seem to get is by using <code>\wedge</code>, which isn't the same.</p>
<p>You might want to use the common symbol for exclusive or instead, \oplus (but give it a proper name with something like <code>\newcommand\XOR{\oplus}</code>). </p> <p>The caret is a bit too small to be noticeable as a binary operator. However, if you do insist using a caret instead, use this:</p> <pre><code>\newcommand\XOR{\mathbin{\char`\^}} $x \XOR y$ </code></pre> <p>The <code>\mathbin</code> puts the right spacing around the symbol for a binary operator, and the <code>\char</code> ensures that the glyph is obtained from the roman font.</p>
List selectors for Objective-C object <p>I have an object, and I want to list all the selectors to which it responds. It feels like this should be perfectly possible, but I'm having trouble finding the APIs.</p>
<p>This is a solution based on the runtime C functions:</p> <p>class_copyMethodList returns a list of class methods given a Class object obtainable from an object.</p> <pre><code>#import &lt;objc/runtime.h&gt; </code></pre> <p>[..]</p> <pre><code>SomeClass * t = [[SomeClass alloc] init]; int i=0; unsigned int mc = 0; Method * mlist = class_copyMethodList(object_getClass(t), &amp;mc); NSLog(@"%d methods", mc); for(i=0;i&lt;mc;i++) NSLog(@"Method no #%d: %s", i, sel_getName(method_getName(mlist[i]))); /* note mlist needs to be freed */ </code></pre>
Problem using NSURLRequest to POST data to server <p>I create an <code>NSURLRequest</code> to post my data in the iPhone application to a server to proceed the PHP script. My PHP script is look like this.</p> <pre><code>&lt;?php $name = $_POST['name']; $email = $_POST['email']; $link = mysql_connect("localhost", "fffasfdas","Nfdsafafs") or die ("Unable to connect to database."); mysql_select_db("muradsbi_mydatabase") or die ("Unable to select database."); $sqlstatement= "INSERT INTO dbname (name,email) VALUES ('$name','$email')"; $newquery = mysql_query($sqlstatement, $link); echo 'thanks for your register'; ?&gt; </code></pre> <p>and my <code>NSURLRequst</code> is created like below.</p> <pre><code>NSString *myRequestString = @"&amp;name=Hello%20World&amp;email=Ohai2u"; NSData *myRequestData = [NSData dataWithBytes: [myRequestString UTF8String] length: [myRequestString length]]; NSMutableURLRequest *request = [[NSMutableURLRequest alloc] initWithURL: [NSURL URLWithString: @"http://www.google.com/"]]; [request setHTTPMethod: @"POST"]; [request setHTTPBody: myRequestData]; NSData *returnData = [NSURLConnection sendSynchronousRequest: request returningResponse: nil error: nil]; </code></pre> <p>However, this site is unable to get the data from this application and save it to the database, but I know it was connected succussfully because my application is able to get the response data from the server. I don't know whether my variable name is declared in the wrong way or others issues. How can I fix it?</p>
<p>You should remove the leading <code>&amp;</code> in <code>myRequestString</code> and the problem is likely that the correct <code>content-type</code> header is not being sent. Try adding a call to</p> <pre><code>[request setValue:@"application/x-www-form-urlencoded" forHTTPHeaderField:@"content-type"]; </code></pre> <p>You should also not pass <code>nil</code> for error, so you can see what the client thinks is going on.</p> <p>Unrelated, but your PHP code is open to <a href="http://en.wikipedia.org/wiki/SQL_injection">SQL injection attacks</a>.</p>
Strategy for large scale refactoring <p>I'm currently working in a piece of code where both logic and data access are present in the GUI classes. Obviously, I would like to improve on this situation.</p> <p>The current current structure is basically:</p> <ul> <li>Big ball of mud</li> </ul> <p>The ultimate goal is to achieve a DDD-like structure:</p> <ul> <li>DAL</li> <li>Domain model</li> <li>Service layer</li> <li>Presentation model</li> <li>GUI</li> </ul> <p>So, how would you attack the problem?</p> <ul> <li>Big bang <ul> <li>Define the structure for the final state and push code to its ultimate home.</li> </ul></li> <li>Divide and conquer <ul> <li>Try to separate the big ball of mud in to two pieces. Repeat until done...</li> </ul></li> <li>Strangling <ul> <li>Strangle the classes (as described in <a href="http://martinfowler.com/bliki/StranglerApplication.html">http://martinfowler.com/bliki/StranglerApplication.html</a>)</li> </ul></li> </ul>
<p>Never attempt "Big Bang". It almost always blows in your face, since it's a high-risk, desperate measure when everything else has failed.</p> <p>Divide and conquer: This works well ... if your world has only two sides. In real software, you have to conquer so many fronts at the same time, you can rarely afford to live in a black-white fantasy.</p> <p>I guess I've been using something like "Strangling" for most of my career: Gradually morphing bad old code into shiny new code. Here is my recipe:</p> <p>Start somewhere, it doesn't really matter where. Write a few unit tests to see how to the code really behaves. Find out how often it does what you think it does and how often it doesn't. Use your IDE to refactor the code so you can test it.</p> <p>After the first day, make a guess whether you've started at the right place to take this monster apart. If so, go on. If not, find a new place and start over.</p> <p>Advantages of this strategy: It works in small steps, so the risk can be kept in check and if something breaks, if has to be in the code you've been working on last week.</p> <p>Disadvantage: It takes a whole lot of time and you will feel frustrated because often, progress will just seem so slow until the "knot" pops and suddenly, everything starts fall into place as if by magic.</p>
Setting LinqDataSource bound DropDownList using URL querystring <p>This is a puzzle for me, I am able to get three DropDownLists to behave like a cascade (it fetches the correct data) but where I run into problem is where I try to set the value for the dropdownlist based on the value of the querystring. </p> <p>Only the first dropdownlist seems to take it's value from the querystring. The other two does not. In fact the 3rd DropDownlist will also exhibit the error below (it almost looks like the control isn't bound yet:</p> <pre><code>'ddlStation' has a SelectedValue which is invalid because it does not exist in the list of items. Parameter name: value </code></pre> <p>FYI, here is the portion that sets the DropDownList in the Page_Load event:</p> <pre><code>// see if there is any querystring and set dropdownlist accordingly if (Request.QueryString["cell"] != null) { ddlCell.SelectedValue = Request.QueryString["cell"].ToString(); if (Request.QueryString["subcell"] != null) { ddlSubCell.SelectedValue = Request.QueryString["subcell"].ToString(); if (Request.QueryString["station"] != null) { ddlStation.SelectedValue = Request.QueryString["station"].ToString(); } } } </code></pre> <p>Any help is appreciated!</p>
<p>You can only set the SelectItem/Value/Text after databinding has happened.</p>
How to get username without domain <p>In an aspx page I get the Windows username with the function <code>Request.LogonUserIdentity.Name</code>. This function returns a string in the format "domain\user".</p> <p>Is there some function to only get the username, without resorting to the <code>IndexOf</code> and <code>Substring</code>, like this?</p> <pre><code>public static string StripDomain(string username) { int pos = username.IndexOf('\\'); return pos != -1 ? username.Substring(pos + 1) : username; } </code></pre>
<p>If you are using Windows Authentication. This can simply be achieved by calling <code>System.Environment.UserName</code> which will give you the user name only. If you want only the Domain name you can use <code>System.Environment.UserDomainName</code></p>
Restart ASP.NET application when folder contents change <p>I'm writing a web application that will have "plugins". The plugins will be .DLL files which will export their functionality through predefined interfaces 'n stuff. All the .DLL files are in a folder called "Plugins", and the ASP.NET application loads them all upon startup (by using Assembly.LoadFrom).</p> <p>The problem is that when developing, these plugins will change fairly often (all the functionality is in the plugins, the website itself is just a skeleton). Thus, I need a way to automatically restart the application when the .DLL files change.</p> <p>How do I do that?</p>
<p>IF the plugins directory is under your Bin directory, the web app will automatically be restarted when anything changes.</p>
How to resolve this VC++ 6.0 linker error? <p>This is a Windows Console application (actually a service) that a previous guy built 4 years ago and is installed and running. I now need to make some changes but can't even build the current version! Here is the build output:</p> <pre><code>--------------------Configuration: MyApp - Win32 Debug-------------------- Compiling resources... Compiling... Main.cpp winsock.cpp Linking... LINK : warning LNK4098: defaultlib "LIBCMTD" conflicts with use of other libs; use /NODEFAULTLIB:library Main.obj : error LNK2001: unresolved external symbol _socket_dontblock Debug/MyApp.exe : fatal error LNK1120: 1 unresolved externals Error executing link.exe. MyApp.exe - 2 error(s), 1 warning(s) -------------------------------------------------------------------------- </code></pre> <p>If I use <code>/NODEFAULTLIB</code> then I get loads of errors. The code does not actually use <code>_socket_noblock</code> but I can't find anything on it on the 'net. Presumably it is used by some library I am linking to but I don't know what library it is in.</p> <p>--- Alistair.</p>
<p>LNK4098 may not be a problem. For example, it can occur if you link against a release version of some library which uses static runtime linkage and causes LIBCMT (note the absense of "D" suffix) to be added to default libraries. Your application, being built in Debug config, uses LIBCMT**D**, thus the conflict. It may be actually safe, provided that you are not exchanging anything runtime-dependant with that library.</p> <p>As for <code>_socket_noblock</code>, you can use some search utility (such as grep or find) to search for this string in .obj and .lib files. This way you will know which library references the symbol, which may be a starting point for discovering what dependencies that library has.</p>
Why is itemStateChanged on JComboBox is called twice when changed? <p>I'm using a JComboBox with an ItemListener on it. When the value is changed, the itemStateChanged event is called twice. The first call, the ItemEvent is showing the original item selected. On the second time, it is showing the item that has been just selected by the user. Here's some tester code:</p> <pre><code>public Tester(){ JComboBox box = new JComboBox(); box.addItem("One"); box.addItem("Two"); box.addItem("Three"); box.addItem("Four"); box.addItemListener(new ItemListener(){ public void itemStateChanged(ItemEvent e){ System.out.println(e.getItem()); } }); JFrame frame = new JFrame(); frame.getContentPane().add(box); frame.pack(); frame.setVisible(true); } </code></pre> <p>So when I changed the Combo box once from "One" to "Three" the console shows:<br><br></p> <pre><code>One Three </code></pre> <p>Is there a way I can tell using the ItemEvent maybe, that it's the second item (ie. the user selected item)? And if someone can explain why it gets called twice, that would be nice too!</p> <p>Thanks</p>
<p>Have a look at this source:</p> <pre><code>import javax.swing.*; import java.awt.*; import java.awt.event.*; public class Tester { public Tester(){ JComboBox box = new JComboBox(); box.addItem("One"); box.addItem("Two"); box.addItem("Three"); box.addItem("Four"); box.addItemListener(new ItemListener(){ public void itemStateChanged(ItemEvent e){ System.out.println(e.getItem() + " " + e.getStateChange() ); } }); JFrame frame = new JFrame(); frame.getContentPane().add(box); frame.pack(); frame.setVisible(true); } public static void main(String [] args) { Tester tester = new Tester(); } } </code></pre> <p>Use the getStateChange to determine if an item is selected or deselected</p>
PowerShell based database synchronisation using a binary file <p>I have written a database application using a binary file as storage. it is accessed via powershell cmdlets.</p> <p>You can put information into the database using the put- and you can read information using get-.</p> <p>The problem is synchronisation. What is the best way to ensure that the cmdlets don't access the file at the same time?</p> <p>The put- must have exclusive access ie no other writers or readers can access the file. The get- doesn't need exclusive access or readers can access the database at the same time.</p> <p>Am I best using a file based locking mechanism or a .NET based synchronisation mechanism?</p>
<p>I think a <a href="http://msdn.microsoft.com/en-us/library/system.threading.mutex.aspx" rel="nofollow">mutex</a> would work well here. </p>
Can you use SIMBL to develop a plug-in for the iPhone's Safari? <p>Can you use SIMBL to develop a plug-in for the iPhone's Safari?</p>
<p>No, you cannot.</p>
Comparing Infinities in Java <p>What does the following expression return in Java?</p> <pre><code>Math.max(Float.POSITIVE_INFINITY, Double.POSITIVE_INFINITY); </code></pre> <p>I saw this question in a website and the answer is <code>Double.POSITIVE_INFINITY</code>. I'm not sure about this answer as how can we compare 2 infinities? Can someone clarify this? Thanks.</p>
<p>Float.POSITIVE_INFINITY returns float and Double.POSITIVE_INFINITY returns double.</p> <p>There is no method called Math.max(float, double). only Math.max(float, float) and Math.max(double, double)</p> <p>Therefore when the method is called Math.max(float, double), it converts the float argument to double and so the Math.max(double, double) is called so Double.POSITIVE_INFINITY is returned.</p> <p>Java does not convert from double to float since it may lead to precision problem.</p>
Creating a strip of selectable letters for a form <p>I wish to display a list of letters from a through z on a form. Each letter needs to be clickable with that value being passed as a click argument. Aside from creating 26 letters and using the click event of each letter does anyone know of a quick way to do this? I know how to load dynamic controls etc and how to do it that way. Just wondering if anyone knew of a clever way to do this?</p> <p>Cheers</p>
<p>This is the "dynamic way" I would do it in. I know you asked for other clever ways to do it in but I think this is the most accepted way to do it. This will produce those buttons and add a click-handler that takes the button as sender. It will also see to that the buttons location wraps if outside of the forms width.</p> <pre><code>Public Class Form1 Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load Dim ButtonSize As New Size(20, 20) Dim ButtonLocation As New Point(10, 20) For p As Integer = Asc("A") To Asc("Z") Dim newButton As New Button If ButtonLocation.X + ButtonSize.Width &gt; Me.Width Then ButtonLocation.X = 10 ButtonLocation.Y += ButtonSize.Height End If newButton.Size = ButtonSize newButton.Location = ButtonLocation newButton.Text = Chr(p) ButtonLocation.X += newButton.Width + 5 AddHandler newButton.Click, AddressOf ButtonClicked Me.Controls.Add(newButton) Next End Sub Sub ButtonClicked(ByVal sender As Object, ByVal e As System.EventArgs) MsgBox(CType(sender, Button).Text) End Sub End Class </code></pre> <p><img src="http://img235.imageshack.us/img235/2267/testoa6.jpg" alt="alt text" /></p>
PHPMailer error(s) <pre><code>function register_contact ($person = array()) { $nogood = false; foreach ($person as $val) { if (strlen($val)==0) { $nogood = true; $status = "There was an error sending the registration please fill in all fields"; } } if (!$nogood) { require_once("class.phpmailer.php"); $message = "New request for Fox In Touch Recipient:.\r\n\r\n"; $message .= "Forename: " . $person['fname']; $message .= "\r\nSurname: " . $person['sname']; $message .= "\r\nEmail: " . $person['email']; $message .= "\r\nJob Title: " . $person['job']; $message .= "\r\nCompany: " . $person['company']; $message .= "\r\n\r\nFox In Touch."; $mail = new PHPMailer(); $mail-&gt;IsSMTP(); // send via SMTP $mail-&gt;Host = "ahost"; // SMTP servers $mail-&gt;SMTPAuth = true; // turn on SMTP authentication $mail-&gt;Username = "name"; // SMTP username $mail-&gt;Password = "pass"; // SMTP password //$mail-&gt;Post = 587; $mail-&gt;From = "foxintouch@bionic-comms.co.uk"; $mail-&gt;FromName = "Fox In Touch"; //$mail-&gt;AddAddress("foxlicensing.europe@fox.com", "Fox Licensing"); $mail-&gt;AddAddress("andrew@yahoo.co.uk", "Andrew"); $mail-&gt;AddReplyTo("foxintouch@bionic-comms.co.uk","Information"); $mail-&gt;IsHTML(false); // send as HTML $mail-&gt;Subject = "Contact request for Fox In Touch!"; $mail-&gt;Body = $message; if(!$mail-&gt;Send()) { $nogood = true; $status = "Message was not sent &lt;p&gt;"; $status .= "Mailer Error: " . $mail-&gt;ErrorInfo; } else { $status = "Thank you! Your message has been sent to 20th Century Fox. Submit another?"; } } return array('email_failed'=&gt;$nogood, 'status'=&gt;$status); } </code></pre> <p>The above code keeps giving me the error, "Mailer Error: Language string failed to load: recipients_failedandrew@yahoo.co.uk". I have tried changing the AddAddress(). The smtp connection settings are correct, as this was the last error i had! Any help would be much appreciated. Thanks</p>
<p>It sounds like you have two problems.</p> <p>1) Your language file isn't being loaded - see <a href="http://phpmailer.codeworxtech.com/index.php?pg=install" rel="nofollow">installation</a></p> <p>2) The recipient is being rejected - errr double check the SMTP settings and the recipient address</p>
How do I add HTML links in C# TextBox? <p>How can I put a link in a C# <code>TextBox</code>? I have tried to put HTML tags in the box but instead of showing a link it shows the entire HTML tag. Can this be done with a <code>TextBox</code>?</p>
<p>Use the <a href="http://msdn.microsoft.com/en-us/library/f591a55w.aspx">RichTextBox</a>, no need to build your own, it cames with VS</p>
How to quickly parse a list of strings <p>If I want to split a list of words separated by a delimiter character, I can use</p> <pre><code>&gt;&gt;&gt; 'abc,foo,bar'.split(',') ['abc', 'foo', 'bar'] </code></pre> <p>But how to easily and quickly do the same thing if I also want to handle quoted-strings which can contain the delimiter character ?</p> <pre><code>In: 'abc,"a string, with a comma","another, one"' Out: ['abc', 'a string, with a comma', 'another, one'] </code></pre> <p>Related question: <a href="http://stackoverflow.com/questions/118096/how-can-i-parse-a-comma-delimited-string-into-a-list-caveat">How can i parse a comma delimited string into a list (caveat)?</a></p>
<pre><code>import csv input = ['abc,"a string, with a comma","another, one"'] parser = csv.reader(input) for fields in parser: for i,f in enumerate(fields): print i,f # in Python 3 and up, print is a function; use: print(i,f) </code></pre> <p>Result:</p> <pre> 0 abc 1 a string, with a comma 2 another, one </pre>
BlackBerry - How to add content to the Home Screen? <p>In the Windows Mobile world you can create a so-called Today plugin that adds content to the phone's main screen -- the one where you see the number of missed calls, unread sms and upcoming events. Is it possible to do something similar on the BlackBerry? I'd like to show some important info there, so that they are as visible and as easily reachable as possible.</p>
<p>To provide some information on the Home Screen you can use App Icon:<br> <a href="http://stackoverflow.com/questions/1699369/add-a-notification-icon-at-the-status-bar-in-blackberry-jde-4-5-0">Add a notification icon at the status bar in BlackBerry JDE 4.5.0</a><br> <img src="http://img691.imageshack.us/img691/6459/icoupdate3.jpg" alt="alt text"> Other thing available from RIM OS 4.6 if app indicator:<br> <a href="http://stackoverflow.com/questions/1465224/blackberry-how-to-use-notification-icon-in-statusbar">Blackberry - How to use notification icon in statusbar</a><br> <img src="http://img198.imageshack.us/img198/3807/standardindicator.png" alt="alt text"></p>
Localize Images in ASP.NET <p>A couple of years ago, we had a graphic designer revamp our website. His results looked great, but he unfortunately introduced a new unsupported font by the web browser. </p> <p>At first I was like, "What!?!"... since most of our content is dynamic and there was no real way to pre-make all of the images. There was also the issue of multiple languages (since we knew Spanish was on the horizon).</p> <p>Anyway, I decided to create some classes to auto-generate images via GDI+ and programatically cache them as needed. This solved most of our initial problems. However, now that our load has increased dramatically, there has been a drain on our UI server.</p> <p>Now to the question... I am looking to replace most of the dynamic GDI+ images with a standard web browser font. I am thinking of keeping some of the rendered GDI+ images and putting them in a resx file, but plan to replace most of them with Tahoma or Arial fonts via asp:Labels. </p> <p>Which have you found to be a better localized image solution? </p> <ul> <li>Embedding images into the resx</li> <li>Only adding the image url into the resx</li> <li>Some other solution</li> </ul> <p>My main concern is to limit the processing on the UI server. If that is the case, would adding the image url to the resx be a better solution compared to actually embedding the image into the resx?</p>
<p>see my response <a href="http://stackoverflow.com/questions/317191/find-a-localized-file#317231">here</a></p> <p>This can be done manually or using some sort of automated (CMS) system.</p> <p>The basic method is to cache your images in a language specific directory structure and then write an HTTP handler that effectively removes the additional directory layer. eg:</p> <pre><code>/images/ /en/ header1.gif /es/ header1.gif </code></pre> <p>In your markup or CSS you would just reference /images/header1.gif. The http hander then uses session (if language is user specific), or config (if site specific) to choose which directory to serve the image from.</p> <p>This provides a clean line bewteen code and content, and allows for client side caching. Resx is great for small strings but I much prefer a system like this for images and larger content. especially on the web where it is typically easy to switch images around.</p>
URL rewriting problems with ASP .NET 2 on IIS7 and Vista <p>I've got a website running under ASP .NET 2/IIS7/Vista. I have a URL rewriting module which allows me to have extensionless URLs. To get this to work I have configured the system.webServer section of the config file such that all requests are forwarded to the aspnet_isapi.dll. I have also added the URL rewrite module to the modules section and set runAllManagedModulesForAllRequests to true.</p> <p>When I start up the website and visit one of the pages that uses the URL rewriting, the page is rendered correctly. However if I then visit another page the site stops working and I get a 404 not found. I also find that my breakpoint in the URL rewriting module is not getting hit. It's almost as if IIS forwards the first request to the rewriter, but subsequent ones go somewhere else - the error page mentions Notification as being MapRequestHandler and Handler as being StaticFile.</p> <p>If I then make a small change to the web.config file and save it, triggering the website to restart, I can then reload the page in the browser and it all works. Then I click another link and it's broken again.</p> <p>For the record, here's a couple of snippets from the config file. First, under system.web:</p> <pre><code>&lt;httpModules&gt; &lt;add name="UrlRewriteModule" type="Arcs.CoopFurniture.TelesalesWeb.UrlRewriteModule, Arcs.CoopFurniture.TelesalesWeb" /&gt; &lt;/httpModules&gt; </code></pre> <p>and then, under system.webServer:</p> <pre><code>&lt;system.webServer&gt; &lt;modules runAllManagedModulesForAllRequests="true"&gt; &lt;add name="UrlRewriteModule" type="Arcs.CoopFurniture.TelesalesWeb.UrlRewriteModule, Arcs.CoopFurniture.TelesalesWeb" preCondition="managedHandler" /&gt; &lt;/modules&gt; &lt;handlers&gt; &lt;add name="AspNet" path="*" verb="*" modules="IsapiModule" scriptProcessor="%windir%\Microsoft.NET\Framework\v2.0.50727\aspnet_isapi.dll" resourceType="Unspecified" requireAccess="None" preCondition="classicMode,runtimeVersionv2.0,bitness32" /&gt; &lt;/handlers&gt; &lt;validation validateIntegratedModeConfiguration="false" /&gt; &lt;/system.web&gt; </code></pre> <p>The site is running under classic rather than integrated pipeline mode.</p> <p>Does anyone out there have any ideas? I suspect my configuration is wrong somewhere but I can't seem to find where.</p>
<p>This is a bit of a long shot, but have you tried actually making the configuration changes inside of IIS?</p> <p>I know that the web.config way is supposed to be 100% foolproof, but I've seen a few things where it helps to just configure it in IIS to get it working correctly.</p>
Encoding problem classic ASP <p>I have a problem with classic ASP. The encoding is wrong when I send data with <code>XMLHttp.send</code>. The response is a PDF file, but the “ÆØÅ” gets wrong, the “Ø” is read as “øy” for example. It’s like it’s a converting mistake from UTF-8 to ISO-8859-1, but it should be ISO-8859-1 now. I have <code>&lt;%@CODEPAGE="28591"%&gt;</code> at the top at the page and <code>ISO-8859-1</code> as encoding in the XML file, I have checked the file so it’s valid ISO-8859-1. I don’t have access to the server I am sending this data to, but I fixed it in a VB6 program which use the same logic with:</p> <pre><code>aPostBody = StrConv(strBody, vbFromUnicode) WinHttpReq.SetTimeouts 100000, 100000, 100000, 1000000 WinHttpReq.Send aPostBody </code></pre> <p>And in a C# program that also uses the same logic with</p> <pre><code>// ISO-8859-1 byte[] bytes = Encoding.GetEncoding(28591).GetBytes(data); </code></pre> <p>But in ASP classic I need some help to find a way to change the encoding on a string to ISO-8859-1.</p>
<p>Try:</p> <pre><code>Session.CodePage = 28591 </code></pre> <p>There is some good information <a href="http://devlibrary.businessobjects.com/BusinessObjectsXIR2/en/en/RAS_SDK/rassdk_com_doc/doc/rassdk_com_doc/BestPractices11.html" rel="nofollow">here</a>, and I got the CodePage number <a href="http://support.microsoft.com/kb/287946" rel="nofollow">here</a>.</p>
Serializing objects for asynchronous messaging <p>I'm considering using AMQP (using qpid) to enable a mixture of Python and Java services communicate with each other. Basic text messaging seems simple enough but, as with every other messaging technology I've investigated, that's where it seems to stop. Except for building instant messaging applications, I would have thought sending strings wasn't a particularly useful thing to do yet example after example demonstrates sending unformatted text around.</p> <p>My instinct then is to use XML (de-)serialization or something similar (JSON, YAML, Protocol Buffers etc.) which has good library support in both languages. Is this a best practice and, if so, which (de-)serialization protocol would people recommend? Or am I missing the point somewhere and should be quite content sending small bits of text?</p>
<p>Owen, may I offer a few words about RabbitMQ. </p> <p>AMQP is a binary protocol and you can certainly do much more than send strings around! Which Python client do you plan to use? We recommend Barry Pederson's client for most uses: <a href="http://barryp.org/software/py-amqplib/" rel="nofollow" rel="nofollow">http://barryp.org/software/py-amqplib/</a> You are most welcome to come to the RabbitMQ list and ask any questions you like about anything in relation to your post and the comments :-)</p> <p>As James points out, JSON is goodness. RabbitMQ supports JSON-RPC over HTTP connecting to an AMQP back end. People also use RabbitMQ with Orbited for comet type apps.</p> <p>In addition we are fans of, and support XMPP, and STOMP too which James invented. STOMP is handy for a certain class of messaging apps and RabbitMQ supports it for both direct and topic based routing. We've found it a fine way to interop with ActiveMQ, preferring it to JMS in that scenario.</p> <p>I hope you find the right server for your use cases, and recommend you try out different combinations, for best results.</p> <p>Cheers,</p> <p>alexis</p>
Server based reuse - DLL, GAC, or REST? <p>We have a piece of functionality that is used by several different applications (clients) on the same server. It can best be modeled as a service, has a backend database, and there will only be one version of the functionality and the database in use at any one time.</p> <p>Until now we have employed simple DLL-reuse, with the functionality, its configuration file, and dependencies deployed everywhere it is used. Because any changes now have to be made several places, this method is painful when creating new versions of the functionality or when new clients want to use it.</p> <p>We are wondering if there is a better way to do this, and have come up with two possible alternatives.</p> <ol> <li><p>Put the DLL (and the dependencies) in the GAC. The question is then how to configure the component. As the clients have no interest in the configuration, we are leaning towards storing the config file in a hard-coded path on the server.</p></li> <li><p>Publish the functionality as an internal (REST-based) service. Access to it can be limited to internal clients using the firewall.</p></li> </ol> <p>As we see it, the pros of #1 seem to be performance and possibly security, whereas #2 can be seen as simpler to set up.</p> <p>Are we missing anything important here? Has anybody been in a similar situation before and wants to share some insight?</p>
<p>This is a problem I've struggled with many times and there really isn't any best answer other then it depends. My personal opinion is that you need to stay away from option 1 for a couple of reasons:</p> <ol> <li>By having all your clients share a single binary it will now require all of your clients to be tested each time you make a change to it. Now I know in your exact case you might have to do this anyways since we can assume you would be modifying the database that sits behind the component. </li> <li>Do not hard code anything. You can store your configuration path in an AppSettings section in the machine.config file. </li> </ol> <p>As for option 2 one alternative would be to use WCF (assuming your environment can support it). Using WCF you could then use a TCP transport using binary serilization (And there might be a shared memory transport). Both of these would help bring the performance gap closer (Although option 1 will always outperform a service based approach). </p> <p>By going with option 2 you also alleviate the need to retest all clients, as you can develop automated tests to validate that your contract is not broken. This will allow you to publish to a single place, run quick automated tests, and know that your not breaking the clients.</p> <p>With that said you can accomplish the same thing using option 1 and a good set of unit tests, but based on my experience option 2 will be easier in the long run.</p> <p>Option 2 also lets you scale out the service in the future if you ever need more CPU power.</p> <p>Personally I think Option 1 is easier to setup, as you won't have to deal with configuring your firewall, handling authentication, setting up a service etc...It will also be easier to debug (distributing an application introduces new types of failures for example the site hosting your service crashes and your clients start getting failures).</p> <p>One last suggestion is that you use a proxy / facade pattern to insolate your clients from the actual location of the service. This will let you expand over time without having to modify the client code.</p>
What does this Perl conditional do? <p>I'm trying to understand a particular Perl code from <a href="http://sourceforge.net/projects/vcake" rel="nofollow">vcake</a>. Usually I find my way around in Perl but the following statement baffles me. I suspect that this is simply an error but I'm not completely sure. The statement is:</p> <pre><code>foreach my $seq (keys %$set) { if( (defined $set-&gt;{$seq}) and (my $numReads &gt;= ($coverage)) ) { do something; } ... } </code></pre> <p><code>$coverage</code> has been defined at the beginning of the file as a scalar integer (e.g. 10) and is never again written to. <code>$numReads</code> is only used in the line above, <em>nowhere else</em>!</p> <p><code>$set</code>, on the other hand, is modified inside the loop so the first part of the condition makes perfect sense. What I don't understand is the second part because as I see it, this will always evaluate to the same value and <strong>I don't understand the significance of <code>$numReads</code> or <code>&gt;=</code> here</strong>. Can someone please enlighten me? Are there perhaps invisible automatic variables involved?</p>
<p><code>my $numReads</code> means: Create a new local variable within the context of the <code>foreach</code> loop. Its initial value is <code>undef</code>, which in numerical context is treated as <code>0</code>. So the code reads:</p> <pre><code>if ((...) and (0 &gt;= ($coverage)) ) { } </code></pre> <p>which means "do something" is never executed unless $coverage is set to 0 or less.</p> <p>If this was debug code, I'd assume that $coverage is used to enable/disable this statement.</p> <p>My guess is: You've found a bug.</p>
Thread was being aborted <p>I am getting a " Thread was being aborted " Exception in an ASP.NET page.I am not at all using any Response.Redirect/Server.Transfer method.Can any one help me to solve this ?</p>
<p>The <strong>bad</strong> solution is using </p> <pre><code>Response.Redirect(URL, False) </code></pre> <p>which will cause <strong>not</strong> to Response.End() current page, however be careful this might lead problems because rest of the page will get <strong>executed</strong> and might cause <strong>login bypass</strong> and similar security and performance issues.</p> <p>Edit : Apparently you are not using Response.Redirect and you can't catch AbortThreadExecution with Try Catch, which means this answer is totally useless now :)</p> <p>Although to able to get an answer you need to learn how to ask a question. you need to provide information such as : </p> <ul> <li>Exception details</li> <li>When it, what are the symptoms </li> <li>What have you tried and didn't work</li> <li>Have you manage the isolate the problem?</li> </ul>
Why does NSSet objectEnumerator increment the retain count? <p>After getting the objectEnumerator in the following code, the set1 retain count goes to 3. I was surprised to see that because I didn't expect it to change. I searched the <a href="http://developer.apple.com/documentation/Cocoa/Reference/Foundation/Classes/NSSet_Class/Reference/Reference.html#//apple_ref/occ/instm/NSSet/objectEnumerator" rel="nofollow">documentation</a> and can't find where this effect is explained.</p> <p>I assume the extra retains are probably set to autorelease by the Cocoa enumeration logic and won't really have any effect in the current event loop. It makes sense the objectEnumerator logic would need a reference to set1 but I'd like to know why they were made. Here is the reason: if I assume set1 has retain count zero after the release in the code then I could try to reuse it another new set. Wouldn't that cause problems since set1 is now pointing at a completely different object/address?</p> <p>For "bonus" points, is there a way of enumerating the autorelease pool see what it actually contains? TIA</p> <pre><code>#import &lt;Foundation/NSObject.h&gt; #import &lt;Foundation/NSSet.h&gt; #import &lt;Foundation/NSValue.h&gt; #import &lt;Foundation/NSEnumerator.h&gt; #import &lt;Foundation/NSAutoreleasePool.h&gt; #import &lt;Foundation/NSString.h&gt; #import &lt;stdio.h&gt;; // macro to create an integer number: #define INTOBJ(v) [NSNumber numberWithInt: v] int main (int argc, char *argv[]) { NSAutoreleasePool *pool = [NSAutoreleasePool new]; //Make set NSMutableSet *set1 = [[NSMutableSet alloc] initWithObjects: INTOBJ(1), INTOBJ(2), INTOBJ(5), INTOBJ(10), nil]; printf("set1 #%lu\n", [set1 retainCount]); //Get enumerator of the set. This is where the retain count goes to 3: NSEnumerator *setEnum = [set1 objectEnumerator]; printf("setEnum #%lu\n", [setEnum retainCount]); printf("set1 #%lu\n", [set1 retainCount]); //Iterate through the collection: printf("["); NSNumber *element; while ((element = [setEnum nextObject]) != nil) //do some this with item. printf is just for debugging: printf(" %i ", [element intValue]); printf("]\n"); printf("set1 #%lu\n", [set1 retainCount]); [set1 release]; printf("set1 after release #%lu\n", [set1 retainCount]); //More logic could go here reusing variable set1 since I assumed retain count = 0 [pool release]; return 0; } </code></pre>
<p>It's generally not a good idea to rely on the retain count of objects, as it's an internal detail of the framework. Instead make sure your code adheres to the memory management principles, particularly ensuring that retain/new/copy and release/autorelease are balanced.</p>
Namespace Organization - AOP Validators <p>I have started using aspects for parameter validation in our development framework. It works nicely, and I enjoy not littering the first half of a public method with validation code.</p> <p>What I am wondering is if anyone has any recommendations with where in the namespace structure you would place parameter validation? Part of me thinks that since it is top level functionality, it should be in the top-level product namespace - much like the way that System is used in the .NET Framework. I just worry about having the core assembly bloat with more features like this as it goes further down the line.</p> <p>As it stands right now, I have them in something like:</p> <p>[Company].[Product].ParameterValidators</p> <p>In this example, ParameterValidators is the name of the class (aspect) which contains the functionality.</p> <p>Apart from this, I would be appreciative if anyone had further recommendations for incorporating aspects into an existing codebase in relation to structural placement.</p>
<p>Right now you are considering partioning using technical criteria, i.e. "Put all validators in a namespace because they are validators". This does not take into account the reason why the validators <em>exist</em>.</p> <p>My suggestion is to partition by functionality:</p> <ol> <li><p>All-purpose validators (such as nullity and range-checking) go in an all-purpose namespace.</p></li> <li><p>More-specific validators (such as CustomerValidators) go in more-specific namespaces.</p></li> </ol> <p>The general idea is that you don't have 1 class that holds all possible validators, you have several classes (in different namespaces) each of which declares validation <em>for a particular reason</em>.</p>
How to fix "Referenced assembly does not have a strong name" error? <p>I've added a weakly named assembly to my <a href="http://en.wikipedia.org/wiki/Microsoft_Visual_Studio#Visual_Studio_2005">Visual&nbsp;Studio&nbsp;2005</a> project (which is strongly named). I'm now getting the error:</p> <blockquote> <p>"Referenced assembly 'xxxxxxxx' does not have a strong name"</p> </blockquote> <p>Do I need to sign this third-party assembly?</p>
<p>To avoid this error you could either:</p> <ul> <li>Load the assembly dynamically, or</li> <li>Sign the third-party assembly. </li> </ul> <p>You will find instructions on signing third-party assemblies in <em><a href="http://buffered.io/post/2008-07-09-net-fu-signing-an-unsigned-assembly-without-delay-signing/">.NET-fu: Signing an Unsigned Assembly (Without Delay Signing)</a></em>. </p> <h3>Signing Third-Party Assemblies</h3> <p>The basic principle to sign a thirp-party is to </p> <ol> <li><p>Disassemble the assembly using <code>ildasm.exe</code> and save the intermediate language (IL):</p> <pre><code>ildasm /all /out=thirdPartyLib.il thirdPartyLib.dll </code></pre></li> <li><p>Rebuild and sign the assembly:</p> <pre><code>ilasm /dll /key=myKey.snk thirdPartyLib.il </code></pre></li> </ol> <h3>Fixing Additional References</h3> <p>The above steps work fine unless your third-party assembly (<em>A.dll</em>) references another library (<em>B.dll</em>) which also has to be signed. You can disassemble, rebuild and sign both <em>A.dll</em> and <em>B.dll</em> using the commands above, but at runtime, loading of <em>B.dll</em> will fail because <em>A.dll</em> was originally built with a reference to the <em>unsigned</em> version of <em>B.dll</em>. </p> <p>The fix to this issue is to patch the IL file generated in step 1 above. You will need to add the public key token of B.dll to the reference. You get this token by calling </p> <pre><code>sn -Tp B.dll </code></pre> <p>which will give you the following output:</p> <pre><code>Microsoft (R) .NET Framework Strong Name Utility Version 4.0.30319.33440 Copyright (c) Microsoft Corporation. All rights reserved. Public key (hash algorithm: sha1): 002400000480000094000000060200000024000052534131000400000100010093d86f6656eed3 b62780466e6ba30fd15d69a3918e4bbd75d3e9ca8baa5641955c86251ce1e5a83857c7f49288eb 4a0093b20aa9c7faae5184770108d9515905ddd82222514921fa81fff2ea565ae0e98cf66d3758 cb8b22c8efd729821518a76427b7ca1c979caa2d78404da3d44592badc194d05bfdd29b9b8120c 78effe92 Public key token is a8a7ed7203d87bc9 </code></pre> <p>The last line contains the public key token. You then have to search the IL of <em>A.dll</em> for the reference to <em>B.dll</em> and add the token as follows:</p> <pre><code>.assembly extern /*23000003*/ Eurolook.Common { .publickeytoken = (A8 A7 ED 72 03 D8 7B C9 ) .ver 10:0:0:0 } </code></pre>
How to write a Web Service for Google App Engine? <p>I am simply wondering how to write a Web Service (XML - SOAP) for Google App Engine? I am really new with Python and I have been looking for example for a while, but no chance. </p> <p><strong>Does anybody could point me out any article or simply could give me an example of a Web Service in Python with Google App Engine?</strong></p> <p>Thanks!</p>
<p>I was curious about this myself and not finding anything I decided to try to get something to work. The short answer is that it turns out a SOAP service can actually be done using the latest alpha <a href="http://pywebsvcs.sourceforge.net/zsi.html">ZSI library</a>. However it isn't simple and I didn't do much more than a simple request so it could fall apart with a complex type. I'll try to find time to write a tutorial on how to do it and edit this answer with more detail.</p> <p>Unless this is a hard requirement I would do what jamtoday says and go with a REST or RPC service. The SOAP way could be filled with trouble.</p> <p>Update: For anyone interested I've written a <a href="http://www.ioncannon.net/web-services/180/soap-on-the-google-app-engine-platform/">tutorial on how to deploy a SOAP service to the Google App Engine</a>. It is long process so I'm just linking to it instead of pasting it all here.</p>
RewriteRule redirect <p>Okay I have this RewriteRule which is supposed to redirect any request for the file base.css to {folder of .htacces file}/include/style/base.css, but is just keeps redirecting in an infinite loop, I thought the L parameter would make sure that wouldn't happen.</p> <pre><code>RewriteRule (.*)/base.css$ include/style/base.css [L,NC,R=301] </code></pre> <p>Also it redirects to <a href="http://localhost/C:/somemaps/include/style/base.css" rel="nofollow">http://localhost/C:/somemaps/include/style/base.css</a> which it isn't really supposed to do either.</p> <p>Can anyone tell me how to fix this?<br /> Also I would like to have the RewriteRule so it would redirect any file.css to {folder of .htacces file}/include/style/file.css<br /> BTW the .htacces file is in the root of the website (which is not the root of the server!)</p>
<p>You have Redirect and Rewrite confused. A redirect is a HTTP status code that tells the browser to go to another URL. You actually just want to Rewrite the location to another file location. Try</p> <pre><code>RewriteRule (.*)/(.*).css$ /include/style/$2.css [L,NC] </code></pre> <p>If this doesn't work try adding the following right after the RewriteEngine On</p> <pre><code>RewriteBase /my-virtual-folder-path-where-htaccess-is-stored </code></pre>
Using Unicode in C++ source code <p>What is the standard encoding of C++ source code? Does the C++ standard even say something about this? Can I write C++ source in Unicode?</p> <p>For example, can I use non-ASCII characters such as Chinese characters in comments? If so, is full Unicode allowed or just a subset of Unicode? (e.g., that 16-bit first page or whatever it's called.)</p> <p>Furthermore, can I use Unicode for strings? For example:</p> <pre><code>Wstring str=L"Strange chars: â Țđ ě €€"; </code></pre>
<p>Encoding in C++ is quite a bit complicated. Here is my understanding of it.</p> <p>Every implementation has to support characters from the <em>basic source character set</em>. These include common characters listed in §2.2/1 (§2.3/1 in C++11). These characters should all fit into one <code>char</code>. In addition implementations have to support a way to name other characters using a way called <code>universal-character-names</code> and look like <code>\uffff</code> or <code>\Uffffffff</code> and can be used to refer to Unicode characters. A subset of them are usable in identifiers (listed in Annex E). </p> <p>This is all nice, but the mapping from characters in the file, to source characters (used at compile time) is implementation defined. This constitutes the encoding used. Here is what it says literally (C++98 version):</p> <blockquote> <p>Physical source file characters are mapped, in an implementation-defined manner, to the basic source character set (introducing new-line characters for end-of-line indicators) if necessary. Trigraph sequences (2.3) are replaced by corresponding single-character internal representations. Any source file character not in the basic source character set (2.2) is replaced by the universal-character-name that des- ignates that character. (An implementation may use any internal encoding, so long as an actual extended character encountered in the source file, and the same extended character expressed in the source file as a universal-character-name (i.e. using the \uXXXX notation), are handled equivalently.)</p> </blockquote> <p>For gcc, you can change it using the option <code>-finput-charset=charset</code>. Additionally, you can change the execution character used to represet values at runtime. The proper option for this is <code>-fexec-charset=charset</code> for char (it defaults to <code>utf-8</code>) and <code>-fwide-exec-charset=charset</code> (which defaults to either <code>utf-16</code> or <code>utf-32</code> depending on the size of <code>wchar_t</code>). </p>
Validation of viewstate MAC failed <p>I am currently receiving this error:</p> <blockquote> <p>Validation of viewstate MAC failed. If this application is hosted by a Web Farm or cluster, ensure that <code>&lt;machineKey&gt;</code> configuration specifies the same validationKey and validation algorithm. AutoGenerate cannot be used in a cluster. </p> </blockquote> <p>I have found multiple solutions to this error. The solution we are currently using is to add a static MachineKey field at the machine level and to use static validation keys and decryption keys. </p> <pre><code>&lt;MachineKey validationKey="" decryptionKey="" validation="SHA1" decruption="AES" /&gt; </code></pre> <p>Will this solution work for .NET 3.5? Is there a more elegant solution?</p>
<p>Is your web app hosted in a webfarm?</p> <p>If so, the reason for this is that a page is rendered by server 1, and posted to server 2. Therefore, machine keys are different, and the validation failed.</p> <p>It will work on ASP.NET 3.5 as well.</p>
How do I fix this MySQL query? <pre><code>SELECT avg(con_hits) as avg_hits FROM content WHERE con_type = 1 AND con_posttime &lt; $twelve_hrs_ago AND con_refresh = 0 ORDER BY con_posttime DESC LIMIT 100 </code></pre> <p>I would like it to go to the first record that was posted at least 12 hours ago (denoted by the <code>$twelve_hrs_ago</code> variable which has the suitable timestamp), and take the average of the <code>con_hits</code> column, for the next 100 records. In my example, it disregards the <code>LIMIT</code>, and takes the average of every record in the table.</p> <p>Is there a way to bypass that?</p>
<p><code>LIMIT</code> is applied to the resultset, after <code>AVG</code> is calculated. You can do what you want, with a subselect:</p> <pre><code>SELECT avg(con_hits) as avg_hits FROM ( SELECT con_hits FROM content WHERE con_type = 1 AND con_posttime &lt; $twelve_hrs_ago AND con_refresh = 0 ORDER BY con_posttime DESC LIMIT 100 ) x; </code></pre> <p>You can use the database to calculate the time offset too. Replace <code>$twelve_hrs_ago</code> above with:</p> <pre><code>date_add(now(), interval -12 hour) </code></pre>
When should static_cast, dynamic_cast, const_cast and reinterpret_cast be used? <p>What are the proper uses of:</p> <ul> <li><code>static_cast</code></li> <li><code>dynamic_cast</code></li> <li><code>const_cast</code></li> <li><code>reinterpret_cast</code></li> <li>C-style cast <code>(type)value</code></li> <li>Function-style cast <code>type(value)</code></li> </ul> <p>How does one decide which to use in which specific cases?</p>
<p><strong><code>static_cast</code></strong> is the first cast you should attempt to use. It does things like implicit conversions between types (such as <code>int</code> to <code>float</code>, or pointer to <code>void*</code>), and it can also call explicit conversion functions (or implicit ones). In many cases, explicitly stating <code>static_cast</code> isn't necessary, but it's important to note that the <code>T(something)</code> syntax is equivalent to <code>(T)something</code> and should be avoided (more on that later). A <code>T(something, something_else)</code> is safe, however, and guaranteed to call the constructor.</p> <p><code>static_cast</code> can also cast through inheritance hierarchies. It is unnecessary when casting upwards (towards a base class), but when casting downwards it can be used as long as it doesn't cast through <code>virtual</code> inheritance. It does not do checking, however, and it is undefined behavior to <code>static_cast</code> down a hierarchy to a type that isn't actually the type of the object.</p> <hr> <p><strong><code>const_cast</code></strong> can be used to remove or add <code>const</code> to a variable; no other C++ cast is capable of removing it (not even <code>reinterpret_cast</code>). It is important to note that modifying a formerly <code>const</code> value is only undefined if the original variable is <code>const</code>; if you use it to take the <code>const</code> off a reference to something that wasn't declared with <code>const</code>, it is safe. This can be useful when overloading member functions based on <code>const</code>, for instance. It can also be used to add <code>const</code> to an object, such as to call a member function overload.</p> <p><code>const_cast</code> also works similarly on <code>volatile</code>, though that's less common.</p> <hr> <p><strong><code>dynamic_cast</code></strong> is almost exclusively used for handling polymorphism. You can cast a pointer or reference to any polymorphic type to any other class type (a polymorphic type has at least one virtual function, declared or inherited). You can use it for more than just casting downwards -- you can cast sideways or even up another chain. The <code>dynamic_cast</code> will seek out the desired object and return it if possible. If it can't, it will return <code>nullptr</code> in the case of a pointer, or throw <code>std::bad_cast</code> in the case of a reference.</p> <p><code>dynamic_cast</code> has some limitations, though. It doesn't work if there are multiple objects of the same type in the inheritance hierarchy (the so-called 'dreaded diamond') and you aren't using <code>virtual</code> inheritance. It also can only go through public inheritance - it will always fail to travel through <code>protected</code> or <code>private</code> inheritance. This is rarely an issue, however, as such forms of inheritance are rare.</p> <hr> <p><strong><code>reinterpret_cast</code></strong> is the most dangerous cast, and should be used very sparingly. It turns one type directly into another - such as casting the value from one pointer to another, or storing a pointer in an <code>int</code>, or all sorts of other nasty things. Largely, the only guarantee you get with <code>reinterpret_cast</code> is that normally if you cast the result back to the original type, you will get the exact same value (but <strong><em>not</em></strong> if the intermediate type is smaller than the original type). There are a number of conversions that <strong><code>reinterpret_cast</code></strong> cannot do, too. It's used primarily for particularly weird conversions and bit manipulations, like turning a raw data stream into actual data, or storing data in the low bits of an aligned pointer.</p> <hr> <p><strong>C casts</strong> are casts using <code>(type)object</code> or <code>type(object)</code>. A C-style cast is defined as the first of the following which succeeds:</p> <ul> <li><code>const_cast</code></li> <li><code>static_cast</code> (though ignoring access restrictions)</li> <li><code>static_cast</code> (see above), then <code>const_cast</code></li> <li><code>reinterpret_cast</code></li> <li><code>reinterpret_cast</code>, then <code>const_cast</code></li> </ul> <p>It can therefore be used as a replacement for other casts in some instances, but can be extremely dangerous because of the ability to devolve into a <code>reinterpret_cast</code>, and the latter should be preferred when explicit casting is needed, unless you are sure <code>static_cast</code> will succeed or <code>reinterpret_cast</code> will fail. Even then, consider the longer, more explicit option.</p> <p>C-style casts also ignore access control when performing a <code>static_cast</code>, which means that they have the ability to perform an operation that no other cast can. This is mostly a kludge, though, and in my mind is just another reason to avoid C-style casts.</p>
How new programming frameworks help analysts, designers and programmers better work together? <p>It may be Water fall, iterative or agile development or anything else. No matter what development lifecycle mode we talk about there always several perspectives for same problem. From business to problem oriented and further to programming, testing, etc.</p> <p>So question is how are modern companies use modern advanced methodologies to translate requirements to source code?</p> <p>How new programming frameworks help analysts, designers and programmers better work together?</p> <p>New means those which most actively used nowadays. Python or PHP are not quit new but they have actively developing crowd of funs and specialists. Workflow foundation, AJAX, F# etc quite new and give extra productivity developers. But how they impact productivity of a team?</p>
<p>A framework only provides 2 things:</p> <ol> <li>A dictionary which is the same for everybody, so you can communicate and know that you are talking about the same thing</li> <li>A process for people to follow, should you get confused.</li> </ol> <p>The rest is up to you as a team.</p>
How do I Unit Test Actions without Mocking that use UpdateModel? <p>I have been working my way through Scott Guthrie's excellent post on <a href="http://weblogs.asp.net/scottgu/archive/2008/10/16/asp-net-mvc-beta-released.aspx">ASP.NET MVC Beta 1</a>. In it he shows the improvements made to the UpdateModel method and how they improve unit testing. I have recreated a similar project however anytime I run a UnitTest that contains a call to UpdateModel I receive an ArgumentNullException naming the controllerContext parameter.</p> <p>Here's the relevant bits, starting with my model:</p> <pre><code>public class Country { public Int32 ID { get; set; } public String Name { get; set; } public String Iso3166 { get; set; } } </code></pre> <p>The controller action:</p> <pre><code>[AcceptVerbs(HttpVerbs.Post)] public ActionResult Edit(Int32 id, FormCollection form) { using ( ModelBindingDataContext db = new ModelBindingDataContext() ) { Country country = db.Countries.Where(c =&gt; c.CountryID == id).SingleOrDefault(); try { UpdateModel(country, form); db.SubmitChanges(); return RedirectToAction("Index"); } catch { return View(country); } } } </code></pre> <p>And finally my unit test that's failing:</p> <pre><code>[TestMethod] public void Edit() { CountryController controller = new CountryController(); FormCollection form = new FormCollection(); form.Add("Name", "Canada"); form.Add("Iso3166", "CA"); var result = controller.Edit(2 /*Canada*/, form) as RedirectToRouteResult; Assert.IsNotNull(result, "Expected to be redirected on successful POST."); Assert.AreEqual("Show", result.RouteName, "Expected to redirect to the View action."); } </code></pre> <p><code>ArgumentNullException</code> is thrown by the call to <code>UpdateModel</code> with the message "Value cannot be null. Parameter name: controllerContext". I'm assuming that somewhere the <code>UpdateModel</code> requires the <code>System.Web.Mvc.ControllerContext</code> which isn't present during execution of the test.</p> <p>I'm also assuming that I'm doing something wrong somewhere and just need to pointed in the right direction.</p> <p>Help Please!</p>
<p>I don't think it can be done since TryUpdateModel, which UpdateModel uses, references the ControllerContext which is null when invoked from a unit test. I use RhinoMocks to mock or stub the various components needed by the controller.</p> <pre><code>var routeData = new RouteData(); var httpContext = MockRepository.GenerateStub&lt;HttpContextBase&gt;(); FormCollection formParameters = new FormCollection(); EventController controller = new EventController(); ControllerContext controllerContext = MockRepository.GenerateStub&lt;ControllerContext&gt;( httpContext, routeData, controller ); controller.ControllerContext = controllerContext; ViewResult result = controller.Create( formParameters ) as ViewResult; Assert.AreEqual( "Event", result.Values["controller"] ); Assert.AreEqual( "Show", result.Values["action"] ); Assert.AreEqual( 0, result.Values["id"] ); </code></pre> <p>Here's the relevant bit from the Controller.cs source on www.codeplex.com/aspnet:</p> <pre><code>protected internal bool TryUpdateModel&lt;TModel&gt;( ... ) where TModel : class { .... ModelBindingContext bindingContext = new ModelBindingContext( ControllerContext, valueProvider, typeof(TModel), prefix, () =&gt; model, ModelState, propertyFilter ); ... } </code></pre>
iPhone video buffer <p>I'm trying to build a video recorder without jailbreaking my iPhone (i've a Developer license). I began using PhotoLibrary private framework, but i can only reach 2ftp (too slow). Cycoder app have a fps of 15, i think it uses a different approach. I tried to create a bitmap from the previewView of the CameraController, but it always returns e black bitmap.</p> <p>I wonder if there's a way to directly access the video buffer, maybe with IOKit framework.</p> <p>Thanks Marco</p>
<p>Here is the code:</p> <pre><code>image = [window _createCGImageRefRepresentationInFrame:rectToCapture]; </code></pre> <p>Marco</p>
Is there a service which will let me create a snippet of a webpage <p>I am looking for a way to get the essence or the most important aspect of a webpage? If I provide a URL, is there any external service which can accomplish this? I am not looking for snap.com like service as it provides a snapshot.</p> <p>I might be willing to even implement such a system on my own. For beginning I do not want to put excessive effort, but rather would love to able to get some basic results. Are there any thoughts on how I may approach this problem?</p>
<p>You can try <a href="http://developer.yahoo.com/search/content/V2/termExtraction.html" rel="nofollow">Yahoo's Term extraction service</a></p> <p><strong>Update 02-May-2012</strong></p> <p>Yahoo has release a new <a href="http://developer.yahoo.com/contentanalysis/" rel="nofollow">Content Analysis Web service</a> which will be replacing the Term extraction service. It can be invoked by syntactically sweet YQL as shown below</p> <pre><code>select * from contentanalysis.analyze where url='http://www.cnn.com/2011/11/11/world/europe/greece-main/index.html'; </code></pre> <p>There is also <a href="http://www.alchemyapi.com/api/demo.html" rel="nofollow">AlchemyAPI</a> which offers a weservice which may serve your purpose.</p>
Is there a REAL performance difference between INT and VARCHAR primary keys? <p>Is there a measurable performance difference between using INT vs. VARCHAR as a primary key in MySQL? I'd like to use VARCHAR as the primary key for reference lists (think US States, Country Codes) and a coworker won't budge on the INT AUTO_INCREMENT as a primary key for all tables. </p> <p>My argument, as detailed <a href="http://database-programmer.blogspot.com/2008/01/database-skills-sane-approach-to.html#rule1">here</a>, is that the performance difference between INT and VARCHAR is negligible, since every INT foreign key reference will require a JOIN to make sense of the reference, a VARCHAR key will directly present the information.</p> <p>So, does anyone have experience with this particular use-case and the performance concerns associated with it?</p>
<p>It's not about performance. It's about what makes a good primary key. Unique and unchanging over time. You may think an entity such as a country code never changes over time and would be a good candidate for a primary key. But bitter experience is that is seldom so.</p> <p>INT AUTO_INCREMENT meets the "unique and unchanging over time" condition. Hence the preference.</p>
How do you organize C# code in to files? <p>In C#, the questions of what types to create, what members they should have, and what namespaces should hold them, are questions of OO design. They are not the questions I'm interested in here.</p> <p>Instead, I want to ask how you store these in disk artifacts. Here are some example rules:</p> <ul> <li><p>Put all of an assembly's types in a single source file. One friend who did this said "files are an archiac code organization tool; today I use classview and Collapse to Definitions to browse my code".</p></li> <li><p>Put all your code in one assembly. Makes deployment &amp; versioning simpler.</p></li> <li><p>Directory structure reflects namespace structure. </p></li> <li><p>Each namespace gets its own assembly.</p></li> <li><p>Each type goes in its own assembly. (Listed as an extreme example.)</p></li> <li><p>Each type gets its own source file. </p></li> <li><p>Each member gets its own file; each type gets its own directory. (Listed as an extreme example.)</p></li> </ul>
<p>Whatever you do, just PLEASE do it consistently. I don't believe there is any one single answer (though there are a few wrong ones). But just make sure you stay true to your form as this will be the key for your successor(s) to find things easily.</p>
Is it possible to Serialize a LINQ object? <p>I'd like to serialize some LINQ generated objects and store them in a table as a binary field (Never you mind why). I'd like to be able to write some code that looks something like this:</p> <pre><code>SerialTestDataContext db = new SerialTestDataContext(); relation_table row = db.relation_tables.First(); MemoryStream memStream = new MemoryStream(); BinaryFormatter bin = new BinaryFormatter(); bin.Serialize(memStream, row); Console.WriteLine("Serilized successfully"); TestTable tt = new testTable(); tt.data = new System.Data.Linq.Binary(memStream.ToArray()); db.testTables.InsertOnSubmit(tt); db.SubmitChanges(); Console.WriteLine("Inserted successfully"); </code></pre> <p>Currently that fails even though I've marked the generated classes as [Serializable] because one of the LINQ inherited classes is not. Is it even possible to do this?</p>
<p>With linq-to-sql (from tags), then yes: you can mark the dmbl as serializable, which uses the [DataContract]/[DataMember] approach. You do this by setting the "Serialization Mode" to "Unidirectional" in the designer, or you can do it in the dbml itself:</p> <pre><code>&lt;Database ... Serialization="Unidirectional"&gt;... </code></pre> <p>You can then use DataContractSerializer or NetDataContractSerializer to write this (as xml or binary respectively). If you need something portable (i.e. not MS/.NET specific), then <a href="http://code.google.com/p/protobuf-net/">protobuf-net</a> will serialize data-contracts using the "protocol buffers" spec.</p>
SQLite .dump command from SQLiteConnection object <p>Using SQLite from .net, Is there a way to access the <code>.dump</code> command or something equivalent from the SQLiteConnection class?</p>
<p>The <code>.dump</code> command is part of the sqlite command line program (<code>shell.c</code>), not part of the sqlite library. So, it is unlikely to be provided by a .net connection class. </p> <p>However, since the source code for the sqlite command line program is in the public domain, and uses the same library as the .net wrapper, it would be possible to translate the C code for the <code>.dump</code> command to C#. See the function <code>do_meta_command</code> in <a href="http://www.sqlite.org/cvstrac/rlog?f=sqlite/src/shell.c" rel="nofollow">this file</a>.</p>
non-member non-friend function syntax <p>Is their a way to use a non-member non-friend function on an object using the same "dot" notation as member functions?</p> <p>Can I pull a (any) member out of a class, and have users use it in the same way they always have?</p> <p>Longer Explanation:</p> <p><a href="http://www.ddj.com/cpp/184401197" rel="nofollow">Scott Meyers</a>, Herb Sutter, et all, argue that non-member non-friend functions are a part of an object's interface, and can improve encapsulation. I agree with them.</p> <p>However, after recently reading this article: <a href="http://www.gotw.ca/gotw/084.htm" rel="nofollow">http://www.gotw.ca/gotw/084.htm</a> I find myself questioning the syntax implications.</p> <p>In that article, Herb proposes having a single <code>insert</code>, <code>erase</code>, and <code>replace</code> member, and several non-member non-friend functions of the same name.</p> <p>Does this mean, as I think it does, that Herb thinks some functions should be used with the dot notation, and others as a global function?</p> <pre><code>std::string s("foobar"); s.insert( ... ); /* One like this */ insert( s , ...); /* Others like this */ </code></pre> <p>Edit:</p> <p>Thanks everyone for your very useful answers, however, I think the point of my question has been overlooked.</p> <p>I specifically did not mention the specific case of operators, and how they retain the "natural" notation. Nor that you should wrap everything in a namespace. These things are written in the article I linked to.</p> <p><strong>The question itself was:</strong></p> <p>In the article, Herb suggests that one insert() method be a member, while the rest are non-member non-friend functions.</p> <p>This implies that to use one form of insert() you have to use dot notation, while for the others, you do not.</p> <p><strong>Is it just me, or does that sound crazy?</strong></p> <p>I have a hunch that perhaps you can use a single syntax. (Im thinking how Boost::function can take a *this parameter for mem_fun).</p>
<p>Yes, it means that part of the interface of an object is composed of non member functions.</p> <p>And you're right about the fact it involves the use of the following notation, for an object of class T:</p> <pre><code>void T::doSomething(int value) ; // method void doSomething(T &amp; t, int value) ; // non-member non-friend function </code></pre> <p>If you want the doSomething function/method return void, and have an int parameter called "value".</p> <p>But two things are worth mentioning.</p> <p>The first is that the functions part of the interface of a class should be in the same namespace. This is yet another reason (if another reason was needed) to use namespaces, if only to "put together" an object and the functions that are part of its interface.</p> <p>The good part is that it promotes good encapsulation. But bad part is that it uses a function-like notation I, personally, dislike a lot.</p> <p>The second is that operators are not subject to this limitation. For example, the += operator for a class T can be written two ways:</p> <pre><code>T &amp; operator += (T &amp; lhs, const T &amp; rhs) ; { // do something like lhs.value += rhs.value return lhs ; } T &amp; T::operator += (const T &amp; rhs) ; { // do something like this-&gt;value += rhs.value return *this ; } </code></pre> <p>But both notations are used as:</p> <pre><code>void doSomething(T &amp; a, T &amp; b) { a += b ; } </code></pre> <p>which is, from an aesthetic viewpoint, quite better than the function-like notation.</p> <p>Now, it would be a very cool syntactic sugar to be able to write a function from the same interface, and still be able to call it through the "." notation, like in C#, as mentioned by michalmocny.</p> <h2>Edit: Some examples</h2> <p>Let's say I want, for whatever reason, to create two "Integer-like" classes. The first will be IntegerMethod:</p> <pre><code>class IntegerMethod { public : IntegerMethod(const int p_iValue) : m_iValue(p_iValue) {} int getValue() const { return this-&gt;m_iValue ; } void setValue(const int p_iValue) { this-&gt;m_iValue = p_iValue ; } IntegerMethod &amp; operator += (const IntegerMethod &amp; rhs) { this-&gt;m_iValue += rhs.getValue() ; return *this ; } IntegerMethod operator + (const IntegerMethod &amp; rhs) const { return IntegerMethod (this-&gt;m_iValue + rhs.getValue()) ; } std::string toString() const { std::stringstream oStr ; oStr &lt;&lt; this-&gt;m_iValue ; return oStr.str() ; } private : int m_iValue ; } ; </code></pre> <p>This class has 6 methods which can acess its internals.</p> <p>The second is IntegerFunction:</p> <pre><code>class IntegerFunction { public : IntegerFunction(const int p_iValue) : m_iValue(p_iValue) {} int getValue() const { return this-&gt;m_iValue ; } void setValue(const int p_iValue) { this-&gt;m_iValue = p_iValue ; } private : int m_iValue ; } ; IntegerFunction &amp; operator += (IntegerFunction &amp; lhs, const IntegerFunction &amp; rhs) { lhs.setValue(lhs.getValue() + rhs.getValue()) ; return lhs ; } IntegerFunction operator + (const IntegerFunction &amp; lhs, const IntegerFunction &amp; rhs) { return IntegerFunction(lhs.getValue() + rhs.getValue()) ; } std::string toString(const IntegerFunction &amp; p_oInteger) { std::stringstream oStr ; oStr &lt;&lt; p_oInteger.getValue() ; return oStr.str() ; } </code></pre> <p>It has only 3 methods, and such, reduces the quantity of code that can access its internals. It has 3 non-member non-friend functions.</p> <p>The two classes can be used as:</p> <pre><code>void doSomething() { { IntegerMethod iMethod(25) ; iMethod += 35 ; std::cout &lt;&lt; "iMethod : " &lt;&lt; iMethod.toString() &lt;&lt; std::endl ; IntegerMethod result(0), lhs(10), rhs(20) ; result = lhs + 20 ; // result = 10 + rhs ; // WON'T COMPILE result = 10 + 20 ; result = lhs + rhs ; } { IntegerFunction iFunction(125) ; iFunction += 135 ; std::cout &lt;&lt; "iFunction : " &lt;&lt; toString(iFunction) &lt;&lt; std::endl ; IntegerFunction result(0), lhs(10), rhs(20) ; result = lhs + 20 ; result = 10 + rhs ; result = 10 + 20 ; result = lhs + rhs ; } } </code></pre> <p>When we compare the operator use ("+" and "+="), we see that making an operator a member or a non-member has no difference in its apparent use. Still, there are two differences:</p> <ol> <li><p>the member has access to all its internals. The non-member must use public member methods</p></li> <li><p>From some binary operators, like +, *, it is interesting to have type promotion, because in one case (i.e., the lhs promotion, as seen above), it won't work for a member method.</p></li> </ol> <p>Now, if we compare the non-operator use ("toString"), we see the member non-operator use is more "natural" for Java-like developers than the non-member function. Despite this unfamiliarity, for C++ it is important to accept that, despite its syntax, the non-member version is better from a OOP viewpoint because it does not have access to the class internals.</p> <p>As a bonus: If you want to add an operator (resp. a non-operator function) to an object which has none (for example, the GUID structure of &lt;windows.h&gt;), then you can, without needing to modify the structure itself. For the operator, the syntax will be natural, and for the non-operator, well...</p> <p><i>Disclaimer: Of course these class are dumb: the set/getValue are almost direct access to its internals. But replace the Integer by a String, as proposed by Herb Sutter in <a href="http://www.gotw.ca/gotw/084.htm" rel="nofollow">Monoliths "Unstrung"</a>, and you'll see a more real-like case.</i></p>
Msg 64, Level 20, State 0, Line 0 SQL Server Error <p>I am running a sproc on an SQL Server 2005 server which is resulting in the following error:</p> <blockquote> <p>Msg 64, Level 20, State 0, Line 0 A transport-level error has occurred when receiving results from the server. (provider: TCP Provider, error: 0 - The specified network name is no longer available.)</p> </blockquote> <p>Once the error occurs I loose my connection to the server, but able to reconnect.<br> There is nothing in the Event logs. The database is still functional and running its website fine.<br> EDIT: This occurs every time I run this sproc, or it's called by an application.</p> <p>Any suggestions on what may be causing this error?</p>
<p>This happens when the DB server is made unavailable with a client connection open.</p> <p>To reproduce: If you have a query open in SSMS, restart the SQL instance, run the query again to get this error.</p> <p>Thoughts:</p> <ul> <li>Is the SQL instance being restarted?</li> <li>Is the DB being <a href="http://msdn.microsoft.com/en-us/library/ms190249(SQL.90).aspx" rel="nofollow">closed automatically</a>? (eg desktop editions, don't use them myself though)</li> <li>Firewall issues?</li> </ul>
Generating large sets of random data vb6/vb net <p>Is there an easy way in either language to generate a large set of random data quickly so far all the functions I've tried haven't worked too well when I need to generate a group of say 500,000 characters :( Any ideas?</p>
<blockquote> <p>Use UUIDGen.</p> </blockquote> <p>Don't. GUIDs aren't really random. You can actually generate large amounts of data very fast using the <code>System.Random</code> class in VB.NET. 500,000 characters/bytes are no problem:</p> <pre><code>Dim buffer As Byte() = Nothing Array.Resize(buffer, 500000) Call New Random().NextBytes(buffer) My.Computer.FileSystem.WriteAllBytes("filename", buffer, False) </code></pre> <p>This code takes <em>considerably</em> less than one second.</p>
"Atomically" changing a System.Threading.Timer <p>Let's say I have an existing System.Threading.Timer instance and I'd like to call Change on it to push it's firing time back:</p> <pre><code>var timer = new Timer(DelayCallback, null, 10000, Timeout.Infinite); // ... (sometime later but before DelayCallback has executed) timer.Change(20000, Timeout.Infinite); </code></pre> <p>I'm using this timer to perform an "idle callback" after a period of no activity. ("Idle" and "no activity" are application-defined conditions in this case...the specifics aren't terribly important.) Every time I perform an "action", I want to reset the timer so that it is always set to fire 10 seconds after that.</p> <p>However, there is an inherent race condition because when I call Change, I can't tell if the Timer has already fired based on its old settings. (I can, of course, tell if my callback has happened but I can't tell if the CLR's internal timer thread has queued my callback to the threadpool and its execution is imminent.)</p> <p>Now I know I can call Dispose on the timer instance and re-create it each time I need to "push it back". but this <em>seems</em> less efficient than just changing the existing timer. Of course it <em>may</em> not be...I'll run some micro-benchmarks in a bit and let you all know.</p> <p>Alternatively, I can always keep track of the expected firing time (via DateTime.Now.AddSeconds(10)) and, if the original Timer fires, ignore it by checking DateTime.Now in the callback. (I have a nagging concern that this may not be 100% reliable on account of the Timer using TimeSpan and my check using DateTime...this may not be an issue but I'm not completely comfortable with it for some reason...)</p> <p>My questions are:</p> <ol> <li>Is there a good way for me to call Timer.Change and be able to know whether I managed to change it before the callback was queued to the threadpool? (I don't think so, but it doesn't hurt to ask...)</li> <li>Has anyone else implemented (what I term) a "pushback timer" like this? If so, I'd love to hear how you tackled the problem.</li> </ol> <p>This question is somewhat hypothetical in nature since I already have a couple of working solutions (based on Dispose and based on DateTime.Now)...I'm mainly interested in hearing performance-related suggestions (as I'll be "pushing back" the Timer VERY frequently).</p> <p>Thanks!</p>
<p>it sounds like what you really want is the application-idle event</p> <pre><code>System.Windows.Forms.Application.Idle </code></pre>
simple linq to sql has no supported translation to SQL <p>i have this in my BlogRepository</p> <pre><code>public IQueryable&lt;Subnus.MVC.Data.Model.Post&gt; GetPosts() { var query = from p in db.Posts let categories = GetCategoriesByPostId(p.PostId) let comments = GetCommentsByPostId(p.PostId) select new Subnus.MVC.Data.Model.Post { Categories = new LazyList&lt;Category&gt;(categories), Comments = new LazyList&lt;Comment&gt;(comments), PostId = p.PostId, Slug = p.Slug, Title = p.Title, CreatedBy = p.CreatedBy, CreatedOn = p.CreatedOn, Body = p.Body }; return query; } </code></pre> <p>and </p> <pre><code>public IQueryable&lt;Subnus.MVC.Data.Model.Comment&gt; GetCommentsByPostId(int postId) { var query = from c in db.Comments where c.PostId == postId select new Subnus.MVC.Data.Model.Comment { Body = c.Body, EMail = c.EMail, Date = c.CreatedOn, WebSite = c.Website, Name = c.Name }; return query; } private IQueryable&lt;Subnus.MVC.Data.Model.Category&gt; GetCategoriesByPostId(int postId) { var query = from c in db.Categories join pcm in db.Post_Category_Maps on c.CategoryId equals pcm.CategoryId where pcm.PostId == postId select new Subnus.MVC.Data.Model.Category { CategoryId = c.CategoryId, Name = c.Name }; return query; } </code></pre> <p>and when i aplly this filter </p> <pre><code>namespace Subnus.MVC.Data { public static class BlogFilters { public static IQueryable&lt;Post&gt; WherePublicIs(this IQueryable&lt;Post&gt; qry,bool state) { return from p in qry where p.IsPublic == state select p; } } </code></pre> <p>}</p> <p>all this is in the same namespace if that help namespace Subnus.MVC.Data</p> <p>when i try to do this </p> <pre><code>public class BlogService : IBlogService { ... public IList&lt;Post&gt; GetPublicPosts() { return repository.GetPosts().WherePublicIs(true).ToList(); } ... } </code></pre> <p>that is in the namespace Subnus.MVC.Service it throws the error </p> <pre><code>Method 'System.Linq.IQueryable`1[Subnus.MVC.Data.Model.Comment] GetCommentsByPostId(Int32)' has no supported translation to SQL. </code></pre>
<p>You are calling <code>GetCommentsByPostId</code> within what is ultimately an expression tree. That tree, when composed in <code>BlogService.GetPublicPosts</code>, is converted to SQL.</p> <p>During that conversion, it is just a method call, nothing more. Linq to Sql understands certain method calls, and yours is not one of them. Hence the error.</p> <p>On the surface, this seems like it should work. You write reusable queries and compose them from other queries. However, what you are actually saying is: "during the processing of each row on the database server, call this method", which it obviously can't do. The fact that it takes an <code>IQueryable&lt;T&gt;</code> and returns an <code>IQueryable&lt;T&gt;</code> does not make it special.</p> <p>Think about it this way: you are passing <code>postId</code> to <code>GetCategoriesByPostId</code>. You can't call that method until you have a <code>postId</code>, and you don't have one of those until you are on the server in the query.</p> <p>You would probably need to define common <code>Expression&lt;&gt;</code> instances for the sub-queries and use those in the composition. I haven't thought about what this would look like but it's certainly doable.</p> <p><strong>Edit:</strong></p> <p>If you replace</p> <pre><code>let categories = GetCategoriesByPostId(p.PostId) let comments = GetCommentsByPostId(p.PostId) ... Categories = new LazyList&lt;Category&gt;(categories), Comments = new LazyList&lt;Comment&gt;(comments), </code></pre> <p>with</p> <pre><code>Categories = new LazyList&lt;Category&gt;(GetCategoriesByPostId(p.PostId)), Comments = new LazyList&lt;Comment&gt;(GetCommentsByPostId(p.PostId)), </code></pre> <p>the query will no longer throw an exception.</p> <p>This is because <code>let</code> declares range variables, which are in scope for each row. They <strong>must</strong> be calculated on the server.</p> <p>Projections, however, allow you to put arbitrary code in assignments, which is then executed while building results on the client. This means both methods will be called, each of which will issue its own query.</p>
I'm looking for a way to search the values in a .net hashtable using wildcards <p>I've got a whole host of values stored in a .net 2.0 hashtable. What I would really like to find is a way to, essentially, do a SQL select statement on the table.</p> <p>Meaning, I'd like to get a list of keys whose associated values match a very simple text pattern (along the lines of "starts with a number".)</p> <p>The final goal will be to remove these records from the hashtable for further processing.</p> <p>I've been beating my head against this for a while now, and I can't seem to come up with anything.</p> <p>Any ideas?</p> <p>(On the off chance this matters: due to the realities of this project, any 3rd party widgets or upgrading to a more recent version of .net are off the table.)</p>
<p>If you are truly looking for things that start with a number, then you can do it much faster than with a Regex. Just look at the first character of each key and determine if it is a digit. Store the keys you want to remove in a List since you only need to keep the key.</p> <pre><code> List&lt;string&gt; keysToRemove = new List&lt;string&gt;( myhashtable.Count ); foreach (string key in myhashtable.Keys) { if (char.IsDigit(key[0]) { keysToRemove.Add(key); } } foreach (string key in keysToRemove) { myhashtable.Remove(key); } </code></pre>
Ping a site in ruby? <p>What replacements are available for pinging an ip address in Ruby? The stdlib "ping" library seems to be pretty limited in functionality. I'm not interested in rolling my own code here. Are there good gems available? Should I just suck it up and live with it?</p> <p>(I'm coding in Ruby 1.8.6 on Linux)</p>
<p><code><a href="https://rubygems.org/gems/net-ping" rel="nofollow">net-ping</a></code> is worth a look. It allows for TCP pings (like the standard ruby <code>ping</code>) but also UDP, HTTP, and ICMP pings. An ICMP ping requires root privileges but the others do not. </p>
Useful regular expression tutorial <p>Is there a good tutorial on using regular expressions, especially with <a href="http://en.wikipedia.org/wiki/Grep" rel="nofollow">grep</a>? I tried googling for some, but most tutorials are too basic and cover things I already know.</p>
<p><a href="http://www.regular-expressions.info/tutorial.html" rel="nofollow">Regular-expressions.info has a tutorial section</a>. This site is pretty comprehensive for regular expressions in general, although the emphasis is on support in scripting and programming languages.</p> <p>The J. Friedl book, (mentioned previously), is definitely an outstanding resource, and essential reading if you are serious about doing what the title says. If you're just in it for a I'm-in-a-hurry quick-online-scan, then you might want to try the link above, or just hit up a search engine and browse around.</p>
VB.NET Extension Methods <p>when I apply the tag above my methods I get the error </p> <blockquote> <p>Type System.Runtime.CompilerServices.Extension is not defined.</p> </blockquote> <p>Here is my sample</p> <pre><code>&lt;System.Runtime.CompilerServices.Extension()&gt; _ Public Sub test() End Sub </code></pre> <p>Where am I going wrong?</p> <p>Edit ~ Straight from the MSDN Article <a href="http://msdn.microsoft.com/en-us/library/bb384936.aspx">here</a>, the same error</p> <p><code></p> <pre> Imports System.Runtime.CompilerServices Module StringExtensions _ Public Sub Print(ByVal aString As String) Console.WriteLine(aString) End Sub End Module </pre> <p></code></p> <p>I am using Visual Studio 2008 and 3.5 Framework in my project.</p> <blockquote> <p>Solution ~ The project was on 2.0 Framework. Changed to 3.5 and it works.</p> </blockquote>
<p>What version of .net framework the IDE is pointing towards?</p> <p>Also, at first glance the syntax of extension method looks incorrect.</p> <p>The code is incomplete. Please put the using statements in the example for anyone to use the code and compile it - to reproduce the error.</p>
Java Protected Access Not Working <p>In java, there's three levels of access:</p> <ul> <li>Public - Open to the world</li> <li>Private - Open only to the class </li> <li>Protected - Open only to the class and its subclasses (inheritance).</li> </ul> <p>So why does the java compiler allow this to happen?</p> <p>TestBlah.java:</p> <pre><code>public class TestBlah { public static void main(String[] args) { Blah a = new Blah("Blah"); Bloo b = new Bloo("Bloo"); System.out.println(a.getMessage()); System.out.println(b.getMessage()); //Works System.out.println(a.testing); System.out.println(b.testing); //Works } } </code></pre> <p>Blah.java:</p> <pre><code>public class Blah { protected String message; public Blah(String msg) { this.message = msg; } protected String getMessage(){ return(this.message); } } </code></pre> <p>Bloo.java:</p> <pre><code>public class Bloo extends Blah { public Bloo(String testing) { super(testing); } } </code></pre>
<p>Actually it should be:</p> <blockquote> <p>Open only to the <a href="http://java.sun.com/docs/books/tutorial/java/javaOO/accesscontrol.html"><strong>classes on the same package</strong></a> the class and its subclasses (inheritance)</p> </blockquote> <p>That's why</p>
Is there a graceful way to stop svnserve -d <p>I'm looking for something like: </p> <pre><code>svnserve stop </code></pre>
<p>The recommended way is to do it is by using the <code>kill</code> command which will allow subversion to shut down properly. I don't think there is any better way to do it.</p>
Open source or free financial analysis programs/libraries <p>I'm looking for something containing similar functions to Matlab’s financial and financial derivatives toolbox but don’t have the cash to spend on matlab. I would appreciate any info on free or open source libraries or programs that will let me easily calculate interest rates, risk etc.</p>
<p>How about <a href="http://www.jquantlib.org/index.php/Main_Page">JQuantLib</a> or <a href="http://quantlib.org/index.shtml">QuantLib</a>?</p>
Build Tar file from directory in PHP without exec/passthru <p>So I have a client who's current host does not allow me to use tar via exec()/passthru()/ect and I need to backup the site periodicly and programmaticly so is there a solution?</p> <p>This is a linux server.</p>
<p>PHP 5.3 offers a much easier way to solve this issue.</p> <p>Look here: <a href="http://www.php.net/manual/en/phardata.buildfromdirectory.php">http://www.php.net/manual/en/phardata.buildfromdirectory.php</a></p> <pre><code>&lt;?php $phar = new PharData('project.tar'); // add all files in the project $phar-&gt;buildFromDirectory(dirname(__FILE__) . '/project'); ?&gt; </code></pre>
Singleton vs Static Class for exposing data read from xml <p>We have a PageRoles xml file which contains the page path and the user role that can access that page.</p> <p>We are maintaining a Dictionary in a static class, which gets loaded int static constructor for the class. The class has a method CheckIfRoleAllowed that takes in a page path and returns a bool.</p> <p>Each page call the CheckIfRoleAllowed on Page Init.</p> <pre><code>static class PageAccessChecker { static Dictionary&lt;string, UserRoleType[]&gt; _PageAccessPermissions; static FileSystemWatcher _XmlWatcher; static PageAccessChecker() { // Load page access permissions from xml // Set FileSystemWatcher watcher to watch for changes } public static CheckIfRoleAllowed(string pagePath) { } } </code></pre> <p>Would we be better off doing this using the singleton pattern? If yes, why?</p> <p>Kind regards.</p>
<p>I can see two advantages of using the singleton pattern (if implemented through, say, a static property):</p> <ol> <li>you can delay loading the XML file until the first page is accessed.</li> <li>you can check whether the XML file has changed on disk, and automatically reload it on the next access.</li> </ol> <p>A disadvantage might be that you need to make access thread-safe using a lock.</p>
Parallelization: What causes Java threads to block other than synchronization & I/O? <p>Short version is in the title.</p> <p>Long version: I am working on a program for scientific optimization using Java. The workload of the program can be divided into parallel and serial phases -- parallel phases meaning that highly parallelizable work is being performed. To speed up the program (it runs for hours/days) I create a number of threads equal to the number of CPU cores on the machine I'm using -- typically 4 or 8 -- and divide the work between them. I then start these threads and join() them before proceeding to a serial phase.</p> <p>So far so good. What's bothering me is that the CPU utilization and speedup of the parallel phases is nowhere near the "theoretical maximum" -- e.g. if I have 4 cores, I expect to see somewhere between 350-400% "utilization" (as reported by top) but instead it bounces around between 180 and about 310. Using only a single thread, I get 100% CPU utilization.</p> <p>The only reasons I know of for threads not to run at full speed are: -blocking due to I/O -blocking due to synchronization</p> <p>No I/O whatsoever is going on in my parallel threads, nor any synchronization -- the only data structures shared by the threads are read-only, and are either basic types or (non-concurrent) collections. So I'm looking for other explanations. One possibility would be that several threads are repeatedly blocking for garbage collection, but that would only seem to make sense in a situation with memory pressure, and I am allocating well above the required maximum heap space. </p> <p>Any suggestions would be appreciated.</p> <p><b>Update:</b> Just in case anyone is curious, after some more investigation I tweaked the code for general performance and am seeing better utilization, even though nothing I changed has to do with synchronization. However, some of the changes should have resulted in fewer new heap allocations in particular I got rid of some use of <b>iterators</b> and <b>termporary boxed numbers</b> (The CERN "Colt" library for high-performance Java computing was useful here: it provides collections like IntArrayList, DoubleArrayList etc for basic types.). So I think garbage collection was probably the culprit. </p>
<p>All graphics operations run on a single thread in swing. If they are rendering to the screen they will effectively be contending for access to this thread.</p> <p>If you are running on Windows, all graphics operations run on a single thread no matter what. Other operating systems have similar limitations.</p> <p>It's actually fairly difficult to get the proper granularity of threaded workers sometimes, and sometimes it's easy to make them too big or too small, which will typically give you less than 100% usage of all cores.</p> <p>If you're not rendering much gui, the most likely culprit is that you're contending more than you think for some shared resource. This is easily seen with profiler tools like jprofiler. Some VM's like bea's jrockit can even tell you this straight out of the box.</p> <p>This is one of those places where you dont want to act on guesswork. Get a profiler!</p>
Implementing a search page using url parameters in ASP.NET and ASP.NET MVC <p>Let's say I have a search page called Search.aspx that takes a search string as a url parameter ala Google (e.g. Search.aspx?q=This+is+my+search+string).</p> <p>Currently, I have an asp:TextBox and an asp:Button on my page. I'm handling the button's OnClick event and redirecting in the codebehind file to Search.aspx?q= <p>What about with ASP.NET MVC when you don't have a codebehind to redirect with? Would you create a GET form element instead that would post to Search.aspx? Or would you handle the redirect in some other manner (e.g. jQuery event attached to the button)?</p>
<p>You need to understand that MVC doesn't directly reference .aspx pages like WebForms in its URLs. Its main purpose is to separate concerns, that is model (data), controller (logic), and view (presentation).</p> <p>First, you'd have to create a route matching your URLs, which would now look like this for example : /home/search/This+is+my+search+string</p> <p>This would call the Search action method of the Home controller, which would get "This is my search string" as an input parameter. This action is responsible for accessing the model and pulling the results probably from a database.</p> <p>Typically, your search action would then return a ViewResult containing the view placed in the folder /Views/Home/Search.aspx. Here, you can use neither the Postback functionality nor the events of your Web controls like in WebForms, because MVC applications are stateless and not event-driven. It's more like a request/dispatch way of doing things.</p> <p><a href="http://www.asp.net/learn/mvc/" rel="nofollow">Read more about MVC here</a>.</p>
How to design a simple C++ object factory? <p>In my application, there are 10-20 classes that are instantiated once[*]. Here's an example:</p> <pre><code>class SomeOtherManager; class SomeManagerClass { public: SomeManagerClass(SomeOtherManager*); virtual void someMethod1(); virtual void someMethod2(); }; </code></pre> <p>Instances of the classes are contained in one object:</p> <pre><code>class TheManager { public: virtual SomeManagerClass* someManagerClass() const; virtual SomeOtherManager* someOtherManager() const; /** More objects... up to 10-20 */ }; </code></pre> <p>Currently TheManager uses the <em>new</em> operator in order to create objects. </p> <p>My intention is to be able to replace, using plugins, the SomeManagerClass (or any other class) implementation with another one. In order to replace the implementation, 2 steps are needed:</p> <ol> <li>Define a class DerivedSomeManagerClass, which inherits SomeManagerClass [plugin]</li> <li>Create the new class (DerivedSomeManagerClass) instead of the default (SomeManagerClass) [application]</li> </ol> <p>I guess I need some kind of object factory, but it should be fairly simple since there's always only one type to create (the default implementation or the user implementation).</p> <p>Any idea about how to design a simple factory like I just described? Consider the fact that there might be more classes in the future, so it should be easy to extend.</p> <p>[*] I don't care if it happens more than once.</p> <p><strong>Edit:</strong> Please note that there are more than two objects that are contained in TheManager.</p>
<p>Assuming a class (plugin1) which inherits from SomeManagerClass, you need a class hierarchy to build your types:</p> <pre><code>class factory { public: virtual SomeManagerClass* create() = 0; }; class plugin1_factory : public factory { public: SomeManagerClass* create() { return new plugin1(); } }; </code></pre> <p>Then you can assign those factories to a std::map, where they are bound to strings</p> <pre><code>std::map&lt;string, factory*&gt; factory_map; ... factory_map["plugin1"] = new plugin1_factory(); </code></pre> <p>Finally your TheManager just needs to know the name of the plugin (as string) and can return an object of type SomeManagerClass with just one line of code:</p> <pre><code>SomeManagerClass* obj = factory_map[plugin_name]-&gt;create(); </code></pre> <p><strong>EDIT</strong>: If you don't like to have one plugin factory class for each plugin, you could modify the previous pattern with this: </p> <pre><code>template &lt;class plugin_type&gt; class plugin_factory : public factory { public: SomeManagerClass* create() { return new plugin_type(); } }; factory_map["plugin1"] = new plugin_factory&lt;plugin1&gt;(); </code></pre> <p>I think this is a much better solution. Moreover the 'plugin_factory' class could add itself to the 'factory_map' if you pass costructor the string.</p>
Detecting mouse double-click in Flash (AS2) <p>Is there a way to detect mouse double-click on a button object using ActionScript 2.0? </p>
<p>To make explicit what the other answers imply, there's no built-in way. You just have to listen for two clicks and decide whether they're close enough together to count as a double, or else use a package that does that, or else use AS3.</p>
Best Practice for Designing User Roles and Permission System? <p>I need to add user roles and permission system into my web application built using PHP/MySQL. I want to have this functionality: </p> <ol> <li>One root user can create sub-roots, groups, rules and normal users( all privileges) .</li> <li>Sub-roots can create only rules, permissions and users for his/her own group ( no groups).</li> <li>A user can access either content created by him or his group, based on the permission assigned to him, by group root.</li> </ol> <p>I need the system to be flexible enough, so that new roles and permissions are assigned to content.</p> <p>I have a <code>users</code> table storing group key along with other information. Currently I am using two feilds in each content table i.e. <code>createdBy</code> and <code>CreatedByGroup</code>, and using that as the point whether a certain user has permissions. But its not flexible enough, because for every new content, I have to go throug all data updates and permission updates. Please help me by discussing your best practices for schema design.</p>
<p>The pattern that suits your needs is called <a href="http://en.wikipedia.org/wiki/Role-based_access_control" rel="nofollow">role-based access control</a>.</p> <p>There are several good implementations in PHP, including <a href="http://framework.zend.com/manual/1.12/en/zend.acl.html" rel="nofollow">Zend_Acl</a> (good documenation), <a href="http://phpgacl.sourceforge.net/" rel="nofollow">phpGACL</a> and <a href="http://sourceforge.net/projects/tackle/" rel="nofollow">TinyACL</a>. Most frameworks also have their own implementations of an ACL in some form.</p> <p>Even if you choose to roll your own, it'll help you to review well factored solutions such as those.</p>
Symbian S60 - Scrolling text in a CEikLabel <p>I have a single line CEikLabel in my application that needs to scroll text.</p> <p>The simple solution that comes to mind (but possibly naive) would be something like..</p> <pre><code>[begin pseduo code] on timer.fire { set slightly shifted text in label redraw label } start timer [end pseudo code] </code></pre> <p>Using a CPeriodic class as the timer and label.DrawDeferred() on each update.</p> <p>Do you think this is the best way, it may be rather inefficient redrawing the label two or three times a second.. but is there any other way?</p> <p>Thanks :)</p>
<p>I don't know whether there is another way to do it and can't say whether the approach you have in your mind will be inefficient. However, you may want to take a look at <a href="http://www.newlc.com/forum/how-create-moving-text-symbain" rel="nofollow">this thread</a> which discusses pretty much the same question as yours and also briefly mentions somewhat the same solution as the one you have conceived of.</p>
Any easy REST tutorials for Java? <p>Every tutorial or explanation of REST just goes too complicated too quickly - the learning curve rises so fast after the initial explanation of CRUD and the supposed simplicity over SOAP. Why can't people write decent tutorials anymore!</p> <p>I'm looking at Restlet - and its not the best, there are things missing in the tutorial and the language/grammar is a bit confusing and unclear. It has took me hours to untangle their First Steps tutorial (with the help of another Java programmer!)</p> <p><strong>RESTlet Tutorial Comments</strong></p> <p>Overall I'm not sure exactly who the tutorial was aimed at - because there is a fair degree of assumed knowledge all round, so coming into REST and Restlet framework cold leaves you with a lot of 'catchup work' to do, and re-reading paragraphs over and over again.</p> <ol> <li><p>We had difficulty working out that the jars had to be in copied into the correct lib folder. </p></li> <li><p>Problems with web.xml creating a HTTP Status 500 error - </p></li> </ol> <blockquote> <p>The server encountered an internal error () that prevented it from fulfilling this request</p> </blockquote> <p>, the tutorial says: </p> <blockquote> <p>"Create a new Servlet Web application as usual, add a "com.firstStepsServlet" package and put the resource and application classes in."</p> </blockquote> <p>This means that your fully qualified name for your class <strong>FirstStepsApplication</strong> is <strong>com.firstStepsServlet.FirstStepsApplication</strong>, so we had to alter web.xml to refer to the correct class e.g:</p> <p>original:</p> <pre><code>&lt;param-value&gt; firstStepsServlet.FirstStepsApplication &lt;/param-value&gt; </code></pre> <p>should be:</p> <pre><code>&lt;param-value&gt; com.firstStepsServlet.FirstStepsApplication &lt;/param-value&gt; </code></pre> <hr> <p><strong>Conclusion</strong></p> <p>I was under the impression that the concepts of REST were supposed to be much simpler than SOAP - but it seems just as bad if not more complicated - don't get it at all! grrrr</p> <p>Any good links - much appreciated.</p>
<p>Could you describe precisely what caused you troubles in our Restlet tutorials? We are interested in fixing/improving what needs to. </p> <p>Did you check the screencasts? <a href="http://www.restlet.org/documentation/1.1/screencast/">http://www.restlet.org/documentation/1.1/screencast/</a></p> <p>Otherwise, there is a Restlet tutorial in the O'Reilly book that we wrote in their Chapter 12.</p> <p>If you still have troubles, please contact our mailing list: <a href="http://www.restlet.org/community/lists">http://www.restlet.org/community/lists</a></p> <p>Best regards, Jérôme Louvel</p> <p>Restlet ~ Founder and Lead developer ~ <a href="http://www.restlet.org">http://www.restlet.org</a> Noelios Technologies ~ Co-founder ~ <a href="http://www.noelios.com">http://www.noelios.com</a></p>
Fetching only rows that match all entries in a joined table (SQL) <p>I have the following five tables:</p> <ul> <li>ISP</li> <li>Product</li> <li>Connection</li> <li>AddOn</li> <li>AddOn/Product (pivot table for many-to-many relationship).</li> </ul> <p>Each Product is linked to an ISP, each Connection is listed to a Product. Each product can have a number of add-ons, through the use of the pivot table (which simply has 2 fields, one for the product ID and one for the AddOn ID).</p> <p>The result I am interested in is each connection with the addons listed (I am making use of MySQL's GROUP_CONCAT for this, to make a comma-separated list of the addon's <em>name</em> field). This works fine as is, the query looks something like this:</p> <pre><code>SELECT i.name AS ispname, i.img_link, c.download, c.upload, c.monthly_price, c.link, GROUP_CONCAT(a.name) AS addons, SUM(pa.monthly_fee) AS addon_price FROM isp i JOIN product p ON i.id = p.isp_id JOIN `connection` c ON p.id = c.product_id LEFT JOIN product_addon pa ON pa.product_id = p.id AND pa.forced = 0 LEFT JOIN addon a ON pa.addon_id = a.id GROUP BY c.id </code></pre> <p>I am using LEFT JOINS as it is possible for products to have no addons at all.</p> <p>My problem is that it is possible to select some addons that listed connections MUST have, presented as a list of addon IDs, like (1,14,237). If I put it in as an additional condition in the JOIN statements (*AND pa.addon_id IN (...)*), it will return all connections that have just one of the listed addons, but not necessarily all of them.</p> <p>Is there some way to return all connections that as a <strong>minimum</strong> have all the addons (they can have additional as well) via SQL?</p>
<pre><code>GROUP BY set-of-column HAVING SUM(CASE WHEN ISNULL(pa.addon_id, 0) IN (1,14,237) THEN 1 ELSE 0 END) = 3 </code></pre>
How can I print different bands depending on the value of a Field in a DataSet using FastReport? <p>I have a product's dataset and I want to have distinct bands for each type of product, something like, if the product is a fruit, print it's weight, if the product is a car print its color and so on.</p> <p>And I want to let my users customize it, so each band for each type o product will be perfect.</p> <p>My DataSet have all fields from all type of products and I have a field which determines the product type of the actual record.</p> <p>Is there some easy to way to do it?</p>
<p>FastReports allows you to intercept the program's default report construction process with events at several useful places. If you have, for example a master band, in its OnBeforePrint event, you can put code that checks out the type of product and then a case statement could set the visible property to true only on detail bands that are the right kind of property. </p> <p>I have found the news group at <a href="http://news://newsgroups.fast-report.com/fast-reports.public.fastreport.4" rel="nofollow" title="FastReports">news://newsgroups.fast-report.com/fast-reports.public.fastreport.4</a> to be an incredible source of help and encouragement. I am sure you can find a much better answer to your question there.</p>
Passing web context to a 'service' in ASP MVC app <p>I'm trying to work out a way of passing the web current http context to a service class (or initialising the class with a reference to it). I am doing this to abstract the rest of the app away from needing to know anything about the http context. </p> <p>I also want the service to be testable using TDD, probably using one of the Mockable frameworks. Hence it would be preferable to use an interface rather than an actual class.</p> <p>An example of what I'd like to achieve:</p> <pre><code>class WebInstanceService { private IHttpContext _Context; public WebInstanceService( ... , IHttpContext HttpContext ) { .... _Context = HttpContext; } // Methods... public string GetInstanceVariable(string VariableName) { return _Context.Current.Session[VariableName]; } } </code></pre> <p>One of the main issues I have is that there is no IHttpContext, the .net http context is a subclass of an abstract class which can't be mocked (easily?).</p> <p>Another issue is that I can't initialise global instances of the class as then the context won't be relevant for most requests. </p> <p>I could make the class static, and require the Context to be passed to each function as it is called i.e.</p> <pre><code>public static string GetInstanceVariable(string VariableName, HttpContext Context) { ... } </code></pre> <p>but this doesn't make the class any easier to test, I still need to create an HttpContext and additionally any non-web-aware services which want to use this class suddenly need to be able to retrieve the Context requiring them to be closely coupled to the web server - the whole reason for wanting to create this class in the first place.</p> <p>I'm open to ALL suggestions - particularly those which people know facilitate easy tdd testing. <strong>How would people suggest I tackle this problem?</strong></p> <p>Cheers</p>
<p>This is why HttpContextBase and HttpContextWrapper were introduced. You probably want to use HttpContextBase and when passing the real context in, use <code>new HttpContextWrapper( httpContext )</code>, although, I think that what is available to you in the controller is already of type HttpContextBase. I would create one of these in my controller each time rather than trying to reference the current context from the static, global HttpContext.Current instance. If you need it in your view, pass a reference to your strongly typed context in ViewData.</p> <p>I mock up HttpContextBase frequently in my tests.</p> <pre><code>class WebInstanceService { private HttpContextBase _Context; public WebInstanceService( ... , HttpContextBase HttpContext ) { .... _Context = HttpContext; } // Methods... public string GetInstanceVariable(string VariableName) { return _Context.Session[VariableName]; } } </code></pre>
"Copying" a Tree from SVN into a local repository and merging it back afterwards <p>I have a SVN Repository at my main PC, to which only I have access. I also have a Laptop, and I don't want to lose SVN Functionality when I am not connected to my PC. So at the moment, I simply copy accross the whole Repository to the Laptop and copy it back.</p> <p>That works well of course (I am the only developer, so there is no access to the repo when I am not in anyway), but it is somewhat tedious to do every time.</p> <p>I wonder if there is a way to check out a Directory from SVN and store it in a (new) repository on the Laptop, work against that, and then merge that repository with the main one later. (Yes, I know that this would be a good case for distributed systems a la git or Mercurial, but I don't want to lose VisualSVN/TortoiseSVN).</p> <p>I am not really sure what I am looking for, but I guess I am looking for branching and merging between two repositories: Branch the tree off repo1 into repo2, then merge it back. The caveat here: I'd like to keep the history from repo2. So if I made 10 commits against repo2, I'd like to transfer those 10 commits into repo1 as well, so that I am still able to go back.</p> <p>Is that even possible, or am I better off still copying the whole repository every time? (It sits in a VM anyway, which means that I copy the whole VM every time).</p>
<p>Instead of copying the entire repository each time, I recommend to use <a href="http://en.wikipedia.org/wiki/Rsync" rel="nofollow">rsync</a>. If you use the fsfs backend of svn (which you should), then it will synchronize only the new revisions, and do so quickly. Of course, concurrent checkins wouldn't be possible (but I understand they aren't necessary, either).</p>
How should methods updating database tables be unit tested? <p>I have an application that is database intensive. Most of the applications methods are updating data in a database. Some calls are wrappers to stored procedures while others perform database updates in-code using 3rd party APIs. </p> <p>What should I be testing in my unit tests? Should I...</p> <ol> <li>Test that each method completes without throwing an exception -or-</li> <li>Validate the data in the database after each test to make sure the state of data is as expected</li> </ol> <p>My initial thought is #2 but my concern is that I would be writing a bunch of <em>framework code</em> to go along with my unit tests. I read that you shouldn't write a bunch of framework code for unit testing.</p> <p>Thoughts?</p> <p><strong>EDIT:</strong> What I mean by framework is writing a ton of other code that serves as a <em>library</em> to the unit testing code...not a third party framework.</p>
<p>I do number 2, i.e., test the update by updating a record, and then reading it back out and verifying that the values are the same as the ones you put in. Do both the update and the read in a transaction, and then roll it back, to avoid permanent effect on the database. I don't think of this as testing Framework code, any more than I think of it as testing OS code or networking code... The framework (if you mean a non-application specific Database access layer component) should be tested and validated independently.</p>
Is there a way to disable/override the default style for disabled WebControls <p>that one has been nagging me ever since I dabbled in web developpement; is there a way for this? Could I override that style and rely on some other mean to inform my users that that control can't be ineracted with?</p> <p>My problem is that the graying of RadioButton- and CheckBox-Lists' labels makes them unreadable.</p> <p>I could always replace the disabled TextBoxes with Labels styled/themed to look like TextBoxes, but that'd be more invasive...</p> <p>[EDIT] Ok, sorry; that's not a solution; TextBoxes already have the "Readonly" option, which means they look the way I want them to, even when locked from user-input; the problem rather lies with IList Controls (RadioButtonLists and CheckBoxLists.)</p> <p>As ever, thanks for your time!</p>
<p>Sure! What it sounds like you're looking for is a <a href="http://css.maxdesign.com.au/selectutorial/selectors_attribute.htm" rel="nofollow">CSS attribute selector</a>:</p> <pre><code>input[@disabled=true], input[@disabled] { .. insert your new style here .. } </code></pre> <p>Hope that helps!</p>
MySQL - how to SHOW PROCESSLIST only with current user's processes? <p>Is there a way in MySQL 5 to show only the current user's processes(queries)?</p> <p>The user has the <code>PROCESS</code> privilege, therefore <code>SHOW PROCESSLIST</code> displays running processes of all users. According to the documentation, <code>SHOW PROCESSLIST</code> does not allow any kind of <code>WHERE</code> syntax, nor did I manage to make it into a subquery.</p> <p>Of course, I could simply send the query, e.g. in a PHP script, and go through the results in a loop, discarding everything that's not mine, but it seems rather inefficient. Changing the user privileges is not feasible.</p> <p>Are there any other ways? Thanks in advance.</p>
<p>If you use MySQL 5.1.7 or newer, you can use the <a href="http://dev.mysql.com/doc/refman/5.1/en/processlist-table.html">PROCESSLIST</a> table in the INFORMATION_SCHEMA. So you can query it with ordinary <code>SELECT</code> queries and apply filtering conditions in a <code>WHERE</code> clause.</p> <p>This feature is not implemented in MySQL 5.0 and prior.</p>
contextswitchdeadlock <p>Whilst debugging my program in VS 2008 I have come across the following error:</p> <p>The CLR has been unable to transition from COM context 0x34fc1a0 to COM context 0x34fc258 for 60 seconds. The thread that owns the destination context/apartment is most likely either doing a non pumping wait or processing a very long running operation without pumping Windows messages. This situation generally has a negative performance impact and may even lead to the application becoming non responsive or memory usage accumulating continually over time. To avoid this </p> <p>It appears to be deadlocking even though the code only contains a simple C# timer: See Snippet Below:</p> <pre><code> private void RequestWork() { // The timer will be re-intialised if there are still no wating jobs in the database StopTimer(); // assign all the threads some work InitialiseTimer(); } /// &lt;summary&gt; /// Initialise a timer with a timer interval configured from app.config. Enable the timer and /// register an appropriate event handler /// &lt;/summary&gt; private void InitialiseTimer() { if (m_Timer == null) { // look up the default backoff time from the config string backOffInt = ConfigurationSettings.AppSettings["BackOffInterval"]; int backoffInterval = 1000; m_Timer = new System.Timers.Timer(); // set the timer interval to 5 seconds m_Timer.Interval = backoffInterval; m_Timer.Elapsed += new ElapsedEventHandler(m_Timer_Elapsed); } m_Timer.Enabled = true; } private void StopTimer() { if (m_Timer != null) { m_Timer.Enabled = false; } } void m_Timer_Elapsed(object p_Sender, ElapsedEventArgs p_E) { RequestWork(); } </code></pre> <p>As far as I know the timer should run, elapse and then initialise again, I can see no local reason for a deadlock.</p> <p>I am aware of how to turn this error msg off but feel that this is not a solution, instead it is masking the problem.</p>
<p>You can turn this off if you think you've definitely <em>not</em> got a deadlock situation:</p> <p>Debug->Exceptions->Managed Debug Assistants menu in Visual Studio and uncheck the ContextSwitchDeadlock</p>
Using an anchor as a javascript action, what should the link be? <p>I've seen (and used) code to have a link spawn a javascript action many times in my life, but I've never come to a firm conclusion on if the href attribute should be blank or #. Do you have any preference one way or the other, and if so, why?</p> <pre><code>&lt;a href="" onclick="javascript: DoSomething();"&gt;linky&lt;/a&gt; </code></pre> <p>or</p> <pre><code>&lt;a href="#" onclick="javascript: DoSomething();"&gt;linky&lt;/a&gt; </code></pre>
<p>You <strong>must</strong> have <em>something</em> for the <code>href</code> attribute, otherwise the browser will not treat it as a link (for example, making it focusable or giving it an underline) - that's why the use of "#" has become prevalent.</p> <p>Also, the contents of the event attributes (<code>onclick</code>, <code>onmouseover</code>, <code>on...</code>) are already treated as javascript: you don't need to preface it with <code>javascript: </code></p> <p>So given your example, the best way to do that inline (which itself is not the best way, <em>probably</em>), is like this:</p> <pre><code>&lt;a href="#" onclick="DoSomething(); return false"&gt;linky&lt;/a&gt; </code></pre>
Uninstall Without MSI File <p>I often get a problem with Windows Installer trying to uninstall a package, but it complains that</p> <blockquote> <p>The feature you are trying to use is on a network resource that is unavailable.</p> </blockquote> <p>Is there a known means of uninstalling such packages when the original MSI is simply not available?</p>
<p>Please note that Microsoft has now released an official tool to resolve these issues, without the problems that previously existed with MSIZAP.</p> <ul> <li>Microsoft Fixit: <a href="http://support.microsoft.com/mats/Program_Install_and_Uninstall">Fix problems with programs that can't be installed or uninstalled</a></li> </ul>
Which JavaScript library you recommend to use with Java EE + Struts + iBatis? <p>Which JavaScript library you recommend to use with Java EE + Struts + iBatis ? Something like Ext JS, Dojo, frameworks that can be easily integrated with Struts.</p>
<p>There exists a framework that is supposed to tie in nicely with Java Server/Middleware called <a href="http://oss.metaparadigm.com/jsonrpc/" rel="nofollow">JSON-RPC</a></p> <p>However I have never used it and cannot vouch for it.. Aside from that my favourite framework is <em>cough</em> <a href="http://jquery.com/" rel="nofollow">jQuery</a></p> <p><strong>edit</strong> after reading more closely, the JSON-RPC is not quite what you are looking for.. but it still might be useful for ya to look into ;)</p>
Opening a folder in explorer and selecting a file <p>I'm trying to open a folder in explorer with a file selected.</p> <p>The following code produces a file not found exception: </p> <pre><code>System.Diagnostics.Process.Start( "explorer.exe /select," + listView1.SelectedItems[0].SubItems[1].Text + "\\" + listView1.SelectedItems[0].Text); </code></pre> <p>How can I get this command to execute in C#?</p>
<pre><code> // suppose that we have a test.txt at E:\ string filePath = @"E:\test.txt"; if (!File.Exists(filePath)) { return; } // combine the arguments together // it doesn't matter if there is a space after ',' string argument = "/select, \"" + filePath +"\""; System.Diagnostics.Process.Start("explorer.exe", argument); </code></pre>
SQL Server Alerts - Best Practices <p>What SQL Server Alerts do you always setup for every database? What do you always monitor regardless of the database?</p>
<p>You should monitor and be alerted for severity levels 17 to 25. <br></p> <p>Severity levels from 17 through 19 will require intervention from a DBA, they're not as serious as 20-25 but the DBA needs to be alerted.<br> 17 Insufficient Resources<br> 18 Nonfatal Internal Error Detected<br> 19 Error in Resource<br> <br> <br> These are serious errors that will mean SQL Server is no longer working<br> 20 SQL Error in Current Process <br> 21 SQL Fatal Error in Database dbid Processes<br> 22 SQL Fatal Error Table Integrity Suspect<br> 23 SQL Fatal Error: Database Integrity Suspect<br> 24,25 Hardware Error<br></p> <p>for more information on the severity levels see <a href="http://msdn.microsoft.com/en-us/library/aa937483(SQL.80).aspx">http://msdn.microsoft.com/en-us/library/aa937483(SQL.80).aspx</a></p>
C# Problem setting label text on another form <p>I am a very new C# programmer and I am trying to make a kiosk application more accessible by increasing the size of fonts. No problem on the main form. I'm having a problem replacing messageboxes (for which I believe there is no way to increase the font size) with small forms with the same message.</p> <p>This is where I'm running into the problem. The main form can't "see" the error form and its label to set the text. I have tried setting a property for the private label on the error form, but it's still not working.</p> <p>I would be very grateful for any assistance. I have been trying to apply what I've learned in reading several threads from various C# sources.</p> <p>Two strange things I have noticed but am so new to C# that I don't know what they may indicate: (1) In the MainForm when I type ErrorForm. the Intellisense list of suggested code pops up but the variable LblNotCheckedInBecause does not appear on the list. (2) The compiler error says something about the LBlNotCheckedInBecause.get statement and it seems like to me it should be refering to the set statement since I'm trying to set that value.</p> <p>Here are the parts of the code that I believe are involved and if any additional code is needed, just let me know:</p> <p>From the bottom of ErrorForm.Designer.cs...</p> <pre><code> private System.Windows.Forms.Panel panel1; private System.Windows.Forms.Label lblNotCheckedInBecause; public string LblNotCheckedInBecause // property I created to try to be able // to change the label { get { return this.lblNotCheckedInBecause.Text; } set { this.lblNotCheckedInBecause.Text = value; } </code></pre> <p>From MainForm.cs... MessageBox.Show("You were not checked in because of the following reasons:" + sErrors); // this is what I'm trying to replace ErrorForm.LblNotCheckInBecause = "You were not checked in because of the following reasons:" + sErrors; // this line is causing a compiler error</p> <p>Compiler error... Error 1 An object reference is required for the nonstatic field, method, or property 'LogisticsKiosk.ErrorForm.LblNotCheckInBecause.get' C:\Documents and Settings\My Documents\Visual Studio 2005\Projects\LogisticsKiosk\Forms\MainForm.cs 107 17 LogisticsKiosk</p>
<p>You cannot access the ErrorForm as if it was static. That is just the class definition, you need to set the property on an instance of the ErrorForm.</p> <p>Somewhere in your app, you created a new ErrorForm. You need to take that variable and set your LblNotCheckedInBecause property on that.</p> <p>Look for code like this;</p> <pre><code>ErrorForm errorFrm = new ErrorForm(); errorFrm.Show(); </code></pre> <p>Then you can do this if you have a reference to that variable;</p> <pre><code>errorFrm.LblNotCheckedInBecause = "Some Reason"; </code></pre> <p>The following does not work because your Property isn't static (and can't be made static without creating a singleton which you probably don't want to do)</p> <pre><code>// Doesn't work ErrorForm.LblNotCheckedInBecause = "Some Reason"; </code></pre>
Are goto and destructors compatible? <p>This code leads to undefined behavior:</p> <pre><code> void some_func() { goto undefined; { T x = T(); undefined: } } </code></pre> <p>The constructor is not called. </p> <p>But what about this code? Will the destructor of x be called? I think it will be, but I want to be sure. :)</p> <pre><code> void some_func() { { T x = T(); goto out; } out: } </code></pre>
<p>Yes, destructors will be called as expected, the same as if you exited the scope early due to an exception.</p> <p>Standard 6.6/2 (Jump statements):</p> <blockquote> <p>On exit from scope (however accomplished), destructors are called for all constructed objects with automatic storage duration that are declared in that scope, in the reverse order of their declaration.</p> </blockquote>
Implementing Rails' layout functionality with Apache Tiles <p>Has anybody tried duplicating Ruby on Rails' layout functionality with Apache Tiles 2 ? I'm trying to integrate Tiles 2 with Spring. I have a previously written custom view resolver for the Spring framework that does this quite nicely, but I'm upgrading to Spring Webflow 2 and I need to be able to integrate Tiles 2</p>
<p>I've done exactly this. Here's some snippets from that Java app.</p> <pre><code>&lt;definition name="registration" template="/tiles/layouts/defaultLayout.jsp"&gt; &lt;put-attribute name="body" value="undefined" /&gt; &lt;put-attribute name="footer" value="/tiles/footer.jsp?alt=true" /&gt; &lt;/definition&gt; &lt;definition name="site.signup" extends="registration"&gt; &lt;put-attribute name="page" value="Signup" /&gt; &lt;put-attribute name="body" value="/jsp/common/signup.jsp" /&gt; &lt;/definition&gt; </code></pre> <p>Something like that worked for us. It's been a while (I've fled to the Ruby world) so I couldn't honestly actually explain what any of that actually means.</p>
MySQL Composite PK with Nullable FKs <p>First off, let me preface this question by stating that I'm really a pretty terrible data modeler. I know only enough to be dangerous.</p> <p>The table I'm building has four foreign keys, two of which reference the same table. Here's the create statement for that table.</p> <pre><code>CREATE TABLE IF NOT EXISTS `abnr`.`reputation_event_log` ( `id` INT NOT NULL AUTO_INCREMENT , `reputation_event_id` INT NULL , `giver_user_id` INT NULL , `receiver_user_id` INT NULL , `review_id` INT NULL , `giver_point_value` SMALLINT NULL DEFAULT 0 , `receiver_point_value` SMALLINT NULL DEFAULT 0 , `created_at` TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP , PRIMARY KEY (`id`) , INDEX `fk_reputation_log_user` (`giver_user_id` ASC) , INDEX `fk_reputation_log_user1` (`receiver_user_id` ASC) , INDEX `fk_reputation_log_review` (`review_id` ASC) , INDEX `fk_reputation_log_reputation_event` (`reputation_event_id` ASC) , CONSTRAINT `fk_reputation_log_user` FOREIGN KEY (`giver_user_id` ) REFERENCES `abnr`.`user` (`id` ) ON DELETE NO ACTION ON UPDATE NO ACTION, CONSTRAINT `fk_reputation_log_user1` FOREIGN KEY (`receiver_user_id` ) REFERENCES `abnr`.`user` (`id` ) ON DELETE NO ACTION ON UPDATE NO ACTION, CONSTRAINT `fk_reputation_log_review` FOREIGN KEY (`review_id` ) REFERENCES `abnr`.`review` (`id` ) ON DELETE NO ACTION ON UPDATE NO ACTION, CONSTRAINT `fk_reputation_log_reputation_event` FOREIGN KEY (`reputation_event_id` ) REFERENCES `abnr`.`reputation_event` (`id` ) ON DELETE NO ACTION ON UPDATE NO ACTION) ENGINE = InnoDB DEFAULT CHARACTER SET = utf8 COLLATE = utf8_general_ci; </code></pre> <p>The indexes I'm concerned with for this post are <code>fk_reputation_log_user</code> and <code>fk_reputation_log_user1</code>. Every reputation event has a giver, but only some have a receiver. I would <em>like</em> this FK to be nullable, but I don't know how to do that, or if it's even "allowed".</p> <p>I also toyed with the idea of making all FK columns part of the primary key to have database-level protection against duplicate log entries - but that won't work since PK columns have to be NOT NULL.</p> <p>If you need more detail, please state that in the comments. Thanks!</p> <p>(Yes, this is for a reputation system not too dissimilar from what SO has)</p>
<pre><code>CREATE TABLE IF NOT EXISTS `abnr`.`reputation_event_log` ( `id` INT NOT NULL AUTO_INCREMENT , `reputation_event_id` INT NULL , `giver_user_id` INT NOT NULL , -- mandatory giver_user_id `receiver_user_id` INT NULL , -- optional receiver_user_id . . . </code></pre> <p>Yes, you can have <code>NULL</code> in a column with a foreign key constraint declared on it. The <code>NOT NULL</code> constraint on a column is independent from any foreign key constraint(s) on that column. </p> <p>A foreign key means that <em>if</em> the column has a non-NULL value, then that value must exist in the primary key of the table referenced by the foreign key constraint.</p> <p><strong>edit:</strong> As for your <code>UNIQUE</code> requirement, are you aware that you can declare a <code>UNIQUE</code> constraint on nullable columns. The column <em>may</em> contain <code>NULL</code>s (unlike the primary key constraint). This is standard SQL behavior, and is supported by MySQL.</p> <pre><code> . . . PRIMARY KEY (`id`), CONSTRAINT UNIQUE (`giver_user_id`, `receiver_user_id`, `review_id`, `reputation_event_id`), . . . </code></pre>
C# How to replace Microsoft's Smart Quotes with straight quotation marks? <p>My post below asked what the curly quotation marks were and why my app wouldn't work with them, my question now is how can I replace them when my program comes across them, how can I do this in C#? Are they special characters?</p> <p><a href="http://stackoverflow.com/questions/334119/curly-quotation-marks-vs-square-quotation-marks-what-gives">curly-quotation-marks-vs-square-quotation-marks-what-gives</a></p> <p>Thanks</p>
<p>A more extensive listing of problematic word characters</p> <pre><code>if (buffer.IndexOf('\u2013') &gt; -1) buffer = buffer.Replace('\u2013', '-'); if (buffer.IndexOf('\u2014') &gt; -1) buffer = buffer.Replace('\u2014', '-'); if (buffer.IndexOf('\u2015') &gt; -1) buffer = buffer.Replace('\u2015', '-'); if (buffer.IndexOf('\u2017') &gt; -1) buffer = buffer.Replace('\u2017', '_'); if (buffer.IndexOf('\u2018') &gt; -1) buffer = buffer.Replace('\u2018', '\''); if (buffer.IndexOf('\u2019') &gt; -1) buffer = buffer.Replace('\u2019', '\''); if (buffer.IndexOf('\u201a') &gt; -1) buffer = buffer.Replace('\u201a', ','); if (buffer.IndexOf('\u201b') &gt; -1) buffer = buffer.Replace('\u201b', '\''); if (buffer.IndexOf('\u201c') &gt; -1) buffer = buffer.Replace('\u201c', '\"'); if (buffer.IndexOf('\u201d') &gt; -1) buffer = buffer.Replace('\u201d', '\"'); if (buffer.IndexOf('\u201e') &gt; -1) buffer = buffer.Replace('\u201e', '\"'); if (buffer.IndexOf('\u2026') &gt; -1) buffer = buffer.Replace("\u2026", "..."); if (buffer.IndexOf('\u2032') &gt; -1) buffer = buffer.Replace('\u2032', '\''); if (buffer.IndexOf('\u2033') &gt; -1) buffer = buffer.Replace('\u2033', '\"'); </code></pre>