input
stringlengths 51
42.3k
| output
stringlengths 18
55k
|
---|---|
What are the useful new ASP.NET features in the .NET Framework 3.5? <p>I've kept up to date with new features in the C# language as it's moved from version 1 through version 3. I haven't done such a good job keeping up to date with ASP.NET. I feel like some of the post version 1 features are not so good (e.g. the AJAX framework) or are just not that useful to me (e.g. the membership framework). Can anyone recommend any new killer ASP.NET features that might have gone unnoticed?</p>
| <p>For ASP.NET, you have a lot of improvements:</p>
<ul>
<li>split view (code and design)</li>
<li>faster switching between code and design view</li>
<li>embedded master pages (one master page in another)</li>
<li>javascript debugging</li>
</ul>
<p>Anyway most of the useful stuff are really in the meat of the language, and for .NET 3.5 the new language features for C# 3.0 will be (and yes, I find ALL of them useful)</p>
<ul>
<li>anonymous objects</li>
<li>automatic properties</li>
<li>object initializers</li>
<li>collection initializers (inline initialization for collections)</li>
<li>implicit typing (var keyword)</li>
<li>lambda expressions</li>
<li>LINQ</li>
<li>Extension methods</li>
</ul>
<p>I might have forgotten a few, but I think this is about most of the new cool <em>and</em> useful stuff.</p>
|
Validating posted form data in the ASP.NET MVC framework <p>I've been playing around with the ASP.NET MVC Framework and the one thing that's really confusing me is how I'm meant to do server side validation of posted form data. I presume I don't post back to the same URL, but if I don't, how do I redisplay the form with the entered data and error messages? Also, where should the validation logic go? In the model or the controller? This seems to be one of the few areas where web forms are much stronger (I miss the validation controls).</p>
| <p>Here's an overview of the flow in MVC:</p>
<ol>
<li>/new - render your "New" view containing a form for the user to fill out</li>
<li>User fills out form and it is posted to /create</li>
<li>The post is routed to the Create action on your controller</li>
<li>In your action method, update the model with the data that was posted.</li>
<li>Your Model should validate itself.</li>
<li>Your Controller should read if the model is valid.</li>
<li>If the Model is valid, save it to your db. Redirect to /show to render the show View for your object.</li>
<li>If the Model is invalid, save the form values and error messages in the TempData, and redirect to the New action again. Fill your form fields with the data from TempData and show the error message(s).</li>
</ol>
<p>The validation frameworks will help you along in this process. Also, I think the ASP.NET MVC team is planning a validation framework for the next preview.</p>
|
What is the difference between Early and Late Binding? <p>What is the difference between early and late binding?</p>
| <p>The short answer is that early (or static) binding refers to compile time binding and late (or dynamic) binding refers to runtime binding (for example when you use reflection).</p>
|
What's the best database storage device? <p>So, the answer should probably be presented in tiers for the size of the application, but I'm wondering about people's experience with choosing where the disk drives used by the database should reside.</p>
<p>Here are some of the options:</p>
<ul>
<li>JBOD - (just a bunch of disks) Old fashioned internal disks - fast but not very expandable</li>
<li>NAS - Slow but cheap and expandable, probably best for backups</li>
<li>DAS - A decent compromise, but generally accessible from only one or two machines</li>
<li>SAN - Expensive but very good</li>
</ul>
<p>How much should you worry about choosing a 15k drive over a 10k or 7200RPM?</p>
<p>What's your favorite RAID level?</p>
| <p>Although SAS-based DAS is likely to be quickest for a single DB server (ideally with 15krpm 2.5 inch SFF disks in a RAID 10 configuration) for most systems you lose a lot of the advantages that a SAN can bring. For that reason I'd always build databases with dual FC (4 or 8Gbps fibre links) adapters into dual SAN switches, connected to a dual-controller SAN array. Not only will this scenario be very quick indeed but it will open up the options to utilise the various snapshot techniques that these boxes have to offer. These can enable'live-live' DB replication between sites for DR, instant database restoration and excellent capacity expansion/reduction with no impact on the server/s themselves. Hope this helps, let me know if I can add any more.</p>
|
Pre-built regular expression patterns or Regex Libraries? <p>Does anyone use have a good regex library that they like to use? Most of the regexes that you find online either contain bugs or are so focused on the edge cases that it turns into a competition to validate whatever spec 100%. Of course you can write your own, but when you are billing by the hour its handy to have a library around. </p>
| <p>Boost, for c++</p>
|
Asynchronous Remoting calls <p>We have a remoting singleton server running in a separate windows service (let's call her RemotingService). The clients of the RemotingService are ASP.NET instances (many many).</p>
<p>Currently, the clients remoting call RemotingService and blocks while the RemotingService call is serviced. However, the remoting service is getting complicated enough (with more RPC calls and complex algorithms) that the asp.net worker threads are blocked for a significantly long time (4-5 seconds).</p>
<p>According to <a href="http://msdn.microsoft.com/en-us/magazine/cc164128.aspx">this msdn article</a>, doing this will not scale well because an asp.net worker thread is blocked for each remoting RPC. It advises switching to async handlers to free up asp.net worker threads.</p>
<blockquote>
<p>The purpose of an asynchronous handler
is to free up an ASP.NET thread pool
thread to service additional requests
while the handler is processing the
original request.</p>
</blockquote>
<p>This seems fine, except the remoting call still takes up a thread from the thread pool.
Is this the same thread pool as the asp.net worker threads? </p>
<p><strong>How should I go about turning my remoting singleton server into an async system such that I free up my asp.net worker threads?</strong></p>
<p>I've probably missed out some important information, please let me know if there is anything else you need to know to answer the question.</p>
| <p>The idea behind using the ThreadPool is that through it you can control the amount of synchronous threads, and if those get too many, then the thread pool automatically manages the waiting of newer threads.</p>
<p>The Asp.Net worked thread (AFAIK) doesn't come from the Thread Pool and shouldn't get affected by your call to the remoting service (unless this is a very slow processor, and your remoting function is very CPU intensive - in which case, everything on your computer will be affected).</p>
<p>You could always host the remoting service on a different physical server. In that case, your asp.net worker thread will be totally independent of your remoting call (if the remoting call is called on a separate thread that is).</p>
|
Is there a difference between the on_exit() and atexit() functions? <p>Is there any difference between</p>
<pre><code> int on_exit(void (*function)(int , void *), void *arg);
</code></pre>
<p>and</p>
<pre><code> int atexit(void (*function)(void));
</code></pre>
<p>other than the fact that the function used by on_exit gets the exit status?</p>
<p>That is, if I don't care about the exit status, is there any reason to use one or the other?</p>
<p><strong>Edit:</strong> Many of the answers warned against <code>on_exit</code> because it's non-standard. If I'm developing an app that is for internal corporate use and guaranteed to run on specific configurations, should I worry about this? </p>
| <p>You should use <code>atexit()</code> if possible. <code>on_exit()</code> is nonstandard and less common. For example, it's not available on OS X.</p>
<p>Kernel.org - <a href="http://www.kernel.org/doc/man-pages/online/pages/man3/on_exit.3.html"><code>on_exit()</code></a>:</p>
<blockquote>
<p>This function comes from SunOS 4, but is also present in libc4, libc5 and
glibc. It no longer occurs in Solaris (SunOS 5). Avoid this function, and
use the standard atexit(3) instead.</p>
</blockquote>
|
Why do I get the error "Unable to update the password" when calling AzMan? <p>I'm doing a authorization check from a WinForms application with the help of the AzMan authorization provider from Enterprise Library and am receiving the the following error:</p>
<blockquote>
<p>Unable to update the password. The value provided as the current password is incorrect. (Exception from HRESULT: 0x8007052B) (Microsoft.Practices.EnterpriseLibrary.Security.AzMan) </p>
<hr>
<p>Unable to update the password. The value provided as the current password is incorrect. (Exception from HRESULT: 0x8007052B) (Microsoft.Interop.Security.AzRoles) </p>
</blockquote>
<p>The AzMan store is hosted in ADAM on another computer in the same domain. Other computers and users do not have this problem. The user making the call has read access to both ADAM and the AzMan store. The computer running the WinForms app and the computer running ADAM are both on Windows XP SP2.</p>
<p>I've had access problems with AzMan before that I've resolved, but this is a new one... What am I missing?</p>
| <p>For AzMan with ASP.NET, turn on impersonation in <code>web.config</code> (<code><identity impersonate="true" username="xx" pasword="xx" /></code>), and make sure with an AD administrator that the impersonation account has "reader" permissions on the AzMan store; plus, give write permissions to this account on the <code>Temporary ASP.NET Files</code> folder (under <code>C:\Windows\Microsoft.NET\<framework></code>).</p>
|
Data Layer Best Practices <p>I am in the middle of a "discussion" with a colleague about the best way to implement the data layer in a new application.</p>
<p>One viewpoint is that the data layer should be aware of business objects (our own classes that represent an entity), and be able to work with that object natively. </p>
<p>The opposing viewpoint is that the data layer should be object-agnostic, and purely handle simple data types (strings, bools, dates, etc.)</p>
<p>I can see that both approaches may be valid, but my own viewpoint is that I prefer the former. That way, if the data storage medium changes, the business layer doesn't (necessarily) have to change to accommodate the new data layer. It would therefore be a trivial thing to change from a SQL data store to a serialized xml filesystem store.</p>
<p>My colleague's point of view is that the data layer shouldn't have to know about object definitions, and that as long as the data is passed about appropriately, that is enough. </p>
<p>Now, I know that this is one of those questions that has the potential to start a religious war, but I'd appreciate any feedback from the community on how you approach such things. </p>
<p>TIA</p>
| <p>It really depends on your view of the world - I used to be in the uncoupled camp. The DAL was only there to supply data to the BAL - end of story.</p>
<p>With emerging technologies such as Linq to SQL and Entity Framework becoming a bit more popular, then the line between DAL and BAL have been blurred a bit. In L2S especially your DAL is quite tightly coupled to the Business objects as the object model has a 1-1 mapping to your database field.</p>
<p>Like anything in software development there is no right or wrong answer. You need to understand your requirements and future requirments and work from there. I would no more use a Ferrari on the Dakhar rally as I would a Range Rover on a track day.</p>
|
How can I "unaccept" a drag in Flex? <p>Once I've called <code>DragManager.acceptDrag</code> is there any way to "unaccept" the drag? Say that I have a view which can accept drag and drop, but only in certain areas. Once the user drags over one of these areas I call <code>DragManager.acceptDrag(this)</code> (from a <code>DragEvent.DRAG_OVER</code> handler), but if the user then moves out of this area I'd like to change the status of the drag to not accepted and show the <code>DragManager.NONE</code> feedback. However, neither calling <code>DragManager.acceptDrag(null)</code> nor <code>DragManager.showFeedback(DragManager.NONE)</code> seems to have any effect. Once I've accepted the drag an set the feedback type I can't seem to change it.</p>
<p>Just to make it clear: the areas where the user should be able to drop are not components or even display objects, in fact they are just ranges in the text of a text field (like the selection). Had they been components of their own I could have solved it by making each of them accept drag events individually. I guess I could create proxy components that float over the text to emulate it, but I'd rather not if it isn't necessary.</p>
<hr>
<p>I've managed to get it working in both AIR and the browser now, but only by putting proxy components on top of the ranges of text where you should be able to drop things. That way I get the right feedback and drops are automatically unaccepted on drag exit.</p>
<p>This is the oddest thing about D&D in AIR:</p>
<pre><code>DragManager.doDrag(initiator, source, event, dragImage, offsetX, offsetY);
</code></pre>
<p>In browser-based Flex, <code>offsetX</code> and <code>offsetY</code> should be negative (so says the documentation, and it works fine). However, when running <em>exactly the same code</em> in AIR you have to make the offsets positive. The same numbers, but positive. That is very, very weird.</p>
<hr>
<p>I've tested some more and what <a href="http://stackoverflow.com/questions/10870/how-can-i-unaccept-a-drag-in-flex#11209">@maclema</a> works, but not if you run in AIR. It seems like drag and drop in AIR is different. It's really, really weird because not only is the feedback not showing correctly, and it's not possible to unaccept, but the coordinates are also completely off. I just tried my application in a browser instead of AIR and dragging and dropping is completely broken.</p>
<p>Also, skipping the <code>dragEnter</code> handler works fine in AIR, but breaks everything when running in a browser.</p>
| <p>Are you using only the dragEnter method? If you are trying to reject the drag while still dragging over the same component you need to use both the dragEnter and dragOver methods.</p>
<p>Check out this example:</p>
<pre><code><?xml version="1.0" encoding="utf-8"?>
<mx:Application xmlns:mx="http://www.adobe.com/2006/mxml" layout="absolute">
<mx:Script>
<![CDATA[
import mx.core.DragSource;
import mx.managers.DragManager;
import mx.events.DragEvent;
private function onDragEnter(e:DragEvent):void {
if ( e.target == lbl ) {
if ( e.localX < lbl.width/2 ) {
trace("accept");
DragManager.acceptDragDrop(this);
}
else {
DragManager.acceptDragDrop(null);
}
}
}
private function doStartDrag(e:MouseEvent):void {
if ( e.buttonDown ) {
var ds:DragSource = new DragSource();
ds.addData("test", "text");
DragManager.doDrag(btn, ds, e);
}
}
]]>
</mx:Script>
<mx:Label id="lbl" text="hello world!" left="10" top="10" dragEnter="onDragEnter(event)" dragOver="onDragEnter(event)" />
<mx:Button id="btn" x="47" y="255" label="Button" mouseMove="doStartDrag(event)"/>
</mx:Application>
</code></pre>
|
Any good advice on using emacs for C++ project? <p>I'm looking for a good article on using emacs as C/C++ IDE.</p>
<p>Something like Steve Yegge's <a href="http://steve.yegge.googlepages.com/effective-emacs">"Effective emacs"</a>.</p>
| <p>No specific article, really, but I've found <a href="http://www.emacswiki.org/cgi-bin/wiki">EmacsWiki</a> to be full of useful information. Consider checking out these entries:</p>
<ul>
<li><a href="http://www.emacswiki.org/cgi-bin/wiki/CPlusPlus">CPlusPlus</a> as a starting point for many C++-related articles, and</li>
<li><a href="http://www.emacswiki.org/cgi-bin/wiki/CppTemplate">CppTemplate</a> to define a template that can give you a good skeleton when you start new files</li>
</ul>
|
IKVM and Licensing <p>I have been looking into IKVMing Apache's FOP project to use with our .NET app. It's a commercial product, and looking into licensing, IKVM runs into some sticky areas because of its use of GNU Classpath. From what I've seen, no one can say for sure if this stuff can be used in a commercial product. Has anyone used IKVM, or an IKVM'd product, in a commercial product? Here's what I've found so far:</p>
<p><a href="http://weblog.ikvm.net/story.aspx/license" rel="nofollow" title="Config Section Generator">IKVM license page</a>, which notes that one dll contains code from other projects, their license <a href="http://openjdk.java.net/legal/gplv2+ce.html" rel="nofollow">GPLv2 + Classpath Exception</a></p>
<p><a href="http://saxon.sourceforge.net/" rel="nofollow">Saxon for .NET</a> is generated with IKVM, but released under the Apache license...</p>
<p>Anyone have experience with this?</p>
| <p>There are multiple issues here as ikvm is currently being transitioned away from the GNU classpath system to Sun's OpenJDK. Both are licensed as GPL+Exceptions to state explicitly that applications which merely use the OpenJDK libraries will not be considered derived works.</p>
<p>Generally speaking, applications which rely upon components with defined specs such as this do not fall under the GPL anyway. For example, linking against public POSIX APIs does not trigger GPL reliance in a Linux application, despite the kernel being GPL. A similar principal will usually (the details can be tricky) apply to replacing Sun's Java with a FOSS/GPL implementation.</p>
|
What are the proper permissions for an upload folder with PHP/Apache? <p>Sorry for the basic question - I'm a .NET developer and don't have much experience with LAMP setups.</p>
<p>I have a PHP site that will allow uploads to a specific folder. I have been told that this folder needs to be owned by the webserver user for the upload process to work, so I created the folder and then set permissions as such:</p>
<pre><code>chown apache:apache -R uploads/
chmod 755 -R uploads/
</code></pre>
<p>The only problem now is that the FTP user can not modify the uploaded files at all.</p>
<p>Is there a permission setting that will allow me to still upload files and then modify them later as a user other than the webserver user?</p>
| <p>You can create a new group with both the apache user and FTP user as members and then make the permission on the upload folder 775. This should give both the apache and FTP users the ability to write to the files in the folder but keep everyone else from modifying them.</p>
|
How should I unit test a code-generator? <p>This is a difficult and open-ended question I know, but I thought I'd throw it to the floor and see if anyone had any interesting suggestions.</p>
<p>I have developed a code-generator that takes our python interface to our C++ code (generated via SWIG) and generates code needed to expose this as WebServices. When I developed this code I did it using TDD, but I've found my tests to be brittle as hell. Because each test essentially wanted to verify that for a given bit of input code (which happens to be a C++ header) I'd get a given bit of outputted code I wrote a small engine that reads test definitions from XML input files and generates test cases from these expectations.</p>
<p>The problem is I dread going in to modify the code at all. That and the fact that the unit tests themselves are a: complex, and b: brittle.</p>
<p>So I'm trying to think of alternative approaches to this problem, and it strikes me I'm perhaps tackling it the wrong way. Maybe I need to focus more on the outcome, IE: does the code I generate actually run and do what I want it to, rather than, does the code look the way I want it to.</p>
<p>Has anyone got any experiences of something similar to this they would care to share?</p>
| <p>I started writing up a summary of my experience with my own code generator, then went back and re-read your question and found you had already touched upon the same issues yourself, focus on the execution results instead of the code layout/look.</p>
<p>Problem is, this is hard to test, the generated code might not be suited to actually run in the environment of the unit test system, and how do you encode the expected results?</p>
<p>I've found that you need to break down the code generator into smaller pieces and unit test those. Unit testing a full code generator is more like integration testing than unit testing if you ask me.</p>
|
T-Sql date format for seconds since last epoch / formatting for sqlite input <p>I'm guessing it needs to be something like:</p>
<pre><code>CONVERT(CHAR(24), lastModified, 101)
</code></pre>
<p>However I'm not sure of the right value for the third parameter.</p>
<p>Thanks!</p>
<hr>
<p>Well I'm trying to write a script to copy my sql server db to a sqlite file, which gets downloaded to an air app, which then syncs the data to another sqlite file. I'm having a ton of trouble with dates. If I select a date in air and try to insert it, it fails because it's not in the right format... even if it was a valid date to begin with. I figured I'd try to experiment with the unix time since that's the only thing thats worked so far. I am considering just leaving them as varchar because I don't sort by them anyway.</p>
| <p>Last epoch is when 1970 GMT?</p>
<pre><code>SELECT DATEDIFF(s,'19700101 05:00:00:000',lastModified)
</code></pre>
<p>See also <a href="http://wiki.lessthandot.com/index.php/Epoch_Date" rel="nofollow" title="excanvas">Epoch Date</a></p>
|
Passing more parameters in C function pointers <p>Let's say I'm creating a chess program. I have a function</p>
<pre><code>void foreachMove( void (*action)(chess_move*), chess_game* game);
</code></pre>
<p>which will call the function pointer action on each valid move. This is all well and good, but what if I need to pass more parameters to the action function? For example:</p>
<pre><code>chess_move getNextMove(chess_game* game, int depth){
//for each valid move, determine how good the move is
foreachMove(moveHandler, game);
}
void moveHandler(chess_move* move){
//uh oh, now I need the variables "game" and "depth" from the above function
}
</code></pre>
<p>Redefining the function pointer is not the optimal solution. The foreachMove function is versatile and many different places in the code reference it. It doesn't make sense for each one of those references to have to update their function to include parameters that they don't need.</p>
<p>How can I pass extra parameters to a function that I'm calling through a pointer?</p>
| <p>Ah, if only C supported closures...</p>
<p>Antonio is right; if you need to pass extra parameters, you'll need to redefine your function pointer to accept the additional arguments. If you don't know exactly what parameters you'll need, then you have at least three choices:</p>
<ol>
<li>Have the last argument in your prototype be a void*. This gives you flexibility of passing in anything else that you need, but it definitely isn't type-safe.</li>
<li>Use variadic parameters (...). Given my lack of experience with variadic parameters in C, I'm not sure if you can use this with a function pointer, but this gives even more flexibility than the first solution, albeit still with the lack of type safety.</li>
<li>Upgrade to C++ and use <a href="http://en.wikipedia.org/wiki/Function_object">function objects</a>.</li>
</ol>
|
What version of .Net framework ships with SQL Server 2008? <p>Does SQL Server 2008 ship with the .NET 3.5 CLR, so that stored procedures written in CLR can use 3.5 features?</p>
| <p>Actually it ships with .NET 3.5 SP1. So yes, the stored procs can use 3.5 features and libraries.</p>
|
ASP.NET Proxy Application <p>Let me try to explain what I need. I have a server that is visible from the internet. What I need is to create a ASP.NET application that get the request of a web Site and send to a internal server, then it gets the response and publish the the info. For the client this should be totally transparent.</p>
<p>For different reasons I cannot redirect the port to the internal server. What I can do but no know how - maybe the answer is there - is to create a new Web Site that its host in the other server.</p>
| <p>Why won't any old proxy software work for this? Why does it need to be an ASP.NET application? There are TONS of tools out there (both Windows and *nix) that will get the job done quite easily. Check <a href="http://www.squid-cache.org/" rel="nofollow" title="excanvas">Squid</a> or <a href="http://www.grok.co.uk/netproxy/" rel="nofollow">NetProxy</a> for starters.</p>
<p>If you need to integrate with IIS, <a href="http://www.iisproxy.net/" rel="nofollow">IISProxy</a> looks like it would do the trick too.</p>
|
Speeding up an ASP.Net Web Site or Application <p>I have an Ajax.Net enabled ASP.Net 2.0 web site. Hosting for both the site and the database are out of my control as is the database's schema. In testing on hardware I do control the site performs well however on the client's hardware, there are noticeable delays when reloading or changing pages. </p>
<p>What I would like to do is make my application as compact and speedy as possible when I deliver it. One idea is to set expiration dates for all of the site's static resources so they aren't recalled on page loads. By resources I mean images, linked style sheets and JavaScript source files. Is there an easy way to do this?</p>
<p>What other ways are there to optimize a .Net web site?</p>
<p>UPDATE:
I've run YSlow on the site and the areas where I am getting hit the hardest are in the number of JavaScript and Style Sheets being loaded (23 JS files and 5 style sheets). All but one (the main style sheet) has been inserted by Ajax.net and Asp. Why so many? </p>
| <ol>
<li><a href="http://weblogs.asp.net/scottgu/archive/2008/05/12/visual-studio-2008-and-net-framework-3-5-service-pack-1-beta.aspx">Script Combining in .net 3.5 SP1</a></li>
<li><a href="http://developer.yahoo.com/performance/rules.html">Best Practices for fast websites</a></li>
<li>HTTP Compression (gzip)</li>
<li>Compress JS / CSS (different than http compression, minify javascript)
<ol>
<li><a href="http://developer.yahoo.com/yui/compressor/">YUI Compressor</a></li>
<li><a href="http://www.codeplex.com/YUICompressor">.NET YUI Compressor</a></li>
</ol></li>
</ol>
<p>My best advice is to check out the <a href="http://developer.yahoo.com/YUI">YUI content</a>. They have some great articles that talk about things like <a href="http://www.alistapart.com/articles/sprites/">CSS sprites</a> and have some <a href="http://developer.yahoo.com/yui/imageloader/">nice javascript libraries to help reduce the number of requests</a> the browser is making.</p>
|
What are the list of Resharper like plugins for VS I should consider? <p>My license for Whole Tomatoes Visual AssistX is about to expire and I'm not really planning on renewing it. I use it for spell checking but that's about it. The refactoring abilities have been a little disappointing. Before I just jump into Resharper though what are your thoughts on other possible plugins?</p>
| <p>Aside from trying out Visual AssistX, the only other one I've tried is ReSharper (which I highly recommend). If you do decide to go for ReSharper, you'll likely notice that it's missing a spell checker for code though - however the <a href="http://www.agentsmithplugin.com/" rel="nofollow" title="excanvas">Agent Smith plugin</a> fixes that.</p>
|
How do you kill all current connections to a SQL Server 2005 database? <p>I want to rename a database, but keep getting the error that 'couldn't get exclusive lock' on the database, which implies there is some connection(s) still active.</p>
<p>How can I kill all the connections to the database so that I can rename it?</p>
| <p>See <a href="http://wiki.lessthandot.com/index.php/Kill_All_Active_Connections_To_A_Database">Kill All Active Connections To A Database</a>.</p>
<p>The reason that the approach that <a href="http://stackoverflow.com/questions/11620/how-do-you-kill-all-current-connections-to-a-sql-server-2005-database/11627#11627">Adam suggested</a> won't work is that during the time that you are looping over the active connections new one can be established, and you'll miss those. The article I linked to uses the following approach which does not have this drawback:</p>
<pre><code>-- set your current connection to use master otherwise you might get an error
use master
ALTER DATABASE YourDatabase SET SINGLE_USER WITH ROLLBACK IMMEDIATE
--do you stuff here
ALTER DATABASE YourDatabase SET MULTI_USER
</code></pre>
|
Design pattern for parsing binary file data and storing in a database <p>Does anybody recommend a design pattern for taking a binary data file, parsing parts of it into objects and storing the resultant data into a database? </p>
<p>I think a similar pattern could be used for taking an XML or tab-delimited file and parse it into their representative objects.</p>
<p>A common data structure would include:</p>
<blockquote>
<p>(Header) (DataElement1) (DataElement1SubData1) (DataElement1SubData2)(DataElement2) (DataElement2SubData1) (DataElement2SubData2) (EOF)</p>
</blockquote>
<p>I think a good design would include a way to change out the parsing definition based on the file type or some defined metadata included in the header. So a <a href="http://www.oodesign.com/factory-method-pattern.html" rel="nofollow">Factory Pattern</a> would be part of the overall design for the Parser part.</p>
| <ol>
<li>Just write your file parser, using whatever techniques come to mind</li>
<li>Write lots of unit tests for it to make sure all your edge cases are covered</li>
</ol>
<p>Once you've done this, you will actually have a reasonable idea of the problem/solution.</p>
<p>Right now you just have theories floating around in your head, most of which will turn out to be misguided.</p>
<p>Step 3: Refactor mercilessly. Your aim should be to delete about half of your code</p>
<p>You'll find that your code at the end will either resemble an existing design pattern, or you'll have created a new one. You'll then be qualified to answer this question :-)</p>
|
How can I get Unicode characters to display properly for the tooltip for the IMG ALT in IE7? <p>I've got some Japanese in the ALT attribute, but the tooltip is showing me the ugly block characters in the tooltip. The rest of the content on the page renders correctly. So far, it seems to be limited to the tooltips.</p>
| <p>This is because the font used in the tooltip doesn't include the characters you are trying to display. Try installing a font pack that includes those characters. I'm affraid you can't do much for your site's visitors other than implementating a tooltip yourself using javascript.</p>
|
How can I create virtual machines as part of a build process using MSBuild and MS Virtual Server and/or Hyper-V Server Virtualization? <p>What I would like to do is create a clean virtual machine image as the output of a build of an application.</p>
<p>So a new virtual machine would be created (from a template is fine, with the OS installed, and some base software installed) --- a new web site would be created in IIS, and the web app build output copied to a location on the virtual machine hard disk, and IIS configured correctly, the VM would start up and run.</p>
<p>I know there are MSBuild tasks to script all the administrative actions in IIS, but how do you script all the actions with Virtual machines? Specifically, creating a new virtual machine from a template, naming it uniquely, starting it, configuring it, etc...</p>
<p>Specifically I was wondering if anyone has successfully implemented any VM scripting as part of a build process.</p>
<p>Update: I assume with Hyper-V, there is a different set of libraries/APIs to script virtual machines, anyone played around with this? And anyone with real practical experience of doing something like this?</p>
| <p>You can actually script a fair number of tasks in MS Virtual Server:</p>
<p><a href="http://www.microsoft.com/technet/scriptcenter/scripts/vs/default.mspx?mfr=true" rel="nofollow" title="excanvas"><a href="http://www.microsoft.com/technet/scriptcenter/scripts/vs/default.mspx?mfr=true" rel="nofollow">http://www.microsoft.com/technet/scriptcenter/scripts/vs/default.mspx?mfr=true</a></a></p>
<p><a href="http://msdn.microsoft.com/en-us/library/aa368876(VS.85).aspx" rel="nofollow"><a href="http://msdn.microsoft.com/en-us/library/aa368876" rel="nofollow">http://msdn.microsoft.com/en-us/library/aa368876</a>(VS.85).aspx</a></p>
<p>Also Virtual PC guy has got a ton of stuff on his blog about scripting Virtual Server/PC and now Hyper-V here:</p>
<p><a href="http://blogs.msdn.com/virtual_pc_guy/default.aspx" rel="nofollow"><a href="http://blogs.msdn.com/virtual_pc_guy/default.aspx" rel="nofollow">http://blogs.msdn.com/virtual_pc_guy/default.aspx</a></a></p>
<p>VMware has similar capabilities:</p>
<p><a href="http://www.vmware.com/support/developer/scripting-API/" rel="nofollow"><a href="http://www.vmware.com/support/developer/scripting-API/" rel="nofollow">http://www.vmware.com/support/developer/scripting-API/</a></a></p>
|
Configurable Table Prefixes with a .Net OR/M? <p>In a web application like wiki or forums or blogging software, it is often useful to store your data in a relational database. Since many hosting companies offer a single database with their hosting plans (with additional databases costing extra) it is very useful for your users when your database objects (tables, views, constraints, and stored procedures) have a common prefix. It is typical for applications aware of database scarcity to have a hard-coded table prefix. I want more, however. Specifically, I'd like to have a table prefix that users can designate—say in the web.config file (with an appropriate default, of course).</p>
<p>Since I hate coding <a href="http://en.wikipedia.org/wiki/Create%2C_read%2C_update_and_delete" rel="nofollow">CRUD</a> operations by hand, I prefer to work through a competent OR/M and have used (and enjoyed) LINQ to SQL, Subsonic, and ADO.Net. I'm having some thrash in a new project, however, when it comes to putting a table prefix in a user's web.config file. Are there any .Net-based OR/M products that can handle this scenario elegantly?</p>
<p>The best I have been able to come up with so far is using LINQ to SQL with an external mapping file that I'd have to update somehow based on an as-yet hypothetical web.config setting.</p>
<p>Anyone have a better solution? I tried to make it happen in Entity Framework, but that turned into a mess quickly. (Due to my unfamiliarity with EF? Possibly.) How about SubSonic? Does it have an option to apply a table prefix besides at code generation time?</p>
| <p>I've now researched what it takes to do this in both Entity Framework and LINQ to SQL and <a href="http://theruntime.com/blogs/jacob/archive/2008/08/27/changing-table-names-in-an-orm.aspx" rel="nofollow">documented the steps required in each</a>. It's much longer than answers here tend to be so I'll be content with a link to the answer rather than duplicate it here. It's relatively involved for each, but the LINQ to SQL is the more flexible solution and also the easiest to implment.</p>
|
How much extra overhead is generated when sending a file over a web service as a byte array? <p>This <a href="http://stackoverflow.com/questions/11782/file-uploads-via-web-services" rel="nofollow" title="excanvas">question and answer</a> shows how to send a file as a byte array through an XML web service. How much overhead is generated by using this method for file transfer? I assume the data looks something like this:</p>
<pre><code><?xml version="1.0" encoding="UTF-8" ?>
<bytes>
<byte>16</byte>
<byte>28</byte>
<byte>127</byte>
...
</bytes>
</code></pre>
<p>If this format is correct, the bytes must first be converted to UTF-8 characters. Each of these characters allocates 8 bytes. Are the bytes stored in base 10, hex, or binary characters? How much larger does the file appear as it is being sent due to the XML data and character encoding? Is compression built into web services?</p>
| <p>Typically a byte array is sent as a <code>base64</code> encoded string, not as individual bytes in tags. </p>
<p><a href="http://en.wikipedia.org/wiki/Base64" rel="nofollow">http://en.wikipedia.org/wiki/Base64</a></p>
<p>The <code>base64</code> encoded version is about <strong>137%</strong> of the size of the original content.</p>
|
How can I determine the IP of my router/gateway in Java? <p>How can I determine the IP of my router/gateway in Java? I can get my IP easily enough. I can get my internet IP using a service on a website. But how can I determine my gateway's IP?</p>
<p>This is somewhat easy in .NET if you know your way around. But how do you do it in Java?</p>
| <p>On Windows, OSX, Linux, etc then Chris Bunch's answer can be much improved by using </p>
<pre><code>netstat -rn
</code></pre>
<p>in place of a <code>traceroute</code> command.</p>
<p>Your gateway's IP address will appear in the second field of the line that starts either <code>default</code> or <code>0.0.0.0</code>.</p>
<p>This gets around a number of problems with trying to use <code>traceroute</code>:</p>
<ol>
<li>on Windows <code>traceroute</code> is actually <code>tracert.exe</code>, so there's no need for O/S dependencies in the code</li>
<li>it's a quick command to run - it gets information from the O/S, not from the network</li>
<li><code>traceroute</code> is sometimes blocked by the network</li>
</ol>
<p>The only downside is that it will be necessary to keep reading lines from the <code>netstat</code> output until the right line is found, since there'll be more than one line of output.</p>
<p><strong>EDIT:</strong> The Default Gateway's IP Address is in the second field of the line that starts with 'default' if you are on a MAC (tested on Lion), or in the <strong>third field</strong> of the line that starts with '0.0.0.0' (tested on Windows 7)</p>
<p>Windows:</p>
<blockquote>
<blockquote>
<p>Network Destination Netmask Gateway Interface Metric</p>
<p>0.0.0.0 0.0.0.0 <strong>192.168.2.254</strong> 192.168.2.46 10</p>
</blockquote>
</blockquote>
<p>Mac:</p>
<blockquote>
<blockquote>
<p>Destination Gateway Flags Refs Use Netif Expire</p>
<p>default <strong>192.168.2.254</strong> UGSc 104 4 en1</p>
</blockquote>
</blockquote>
|
How do you log errors (Exceptions) in your ASP.NET apps? <p>I'm looking for the best way to log errors in an ASP.NET application.
I want to be able to receive emails when errors occurs in my application, with detailed information about the Exception and the current Request.</p>
<p>In my company we used to have our own ErrorMailer, catching everything in the Global.asax Application_Error. It was "Ok" but not very flexible nor configurable.</p>
<p>We swithed recently to NLog. It's much more configurable, we can define different targets for the errors, filter them, buffer them (not tried yet). It's a very good improvement.</p>
<p>But I discovered lately that there's a whole Namespace in the .Net framework for this purpose : <a href="http://msdn.microsoft.com/en-us/library/system.web.management.aspx">System.Web.Management</a> and it can be configured in the <a href="http://msdn.microsoft.com/en-us/library/2fwh2ss9(VS.80).aspx">healthMonitoring</a> section of web.config.</p>
<p>Have you ever worked with .Net health monitoring? What is your solution for error logging?</p>
<p>Thanks,</p>
<p>Vincent</p>
| <p>I use <a href="http://code.google.com/p/elmah/">elmah</a>. It has some really nice features and here is a <a href="http://www.codeproject.com/KB/aspnet/ELMAHDemo.aspx">CodeProject</a> article on it. I think the StackOverflow team uses elmah also!</p>
|
Access to global application settings <p>A database application that I'm currently working on, stores all sorts of settings in the database. Most of those settings are there to customize certain business rules, but there's also some other stuff in there.</p>
<p>The app contains objects that specifically do a certain task, e.g., a certain complicated calculation. Those non-UI objects are unit-tested, but also need access to lots of those global settings. The way we've implemented this right now, is by giving the objects properties that are filled by the Application Controller at runtime. When testing, we create the objects in the test and fill in values for testing (not from the database).</p>
<p>This works better, in any case much better than having all those objects need some global <em>Settings</em> object --- that of course effectively makes unit testing impossible :) Disadvantage can be that you sometimes need to set a dozen of properties, or that you need to let those properties 'percolate' into sub-objects.</p>
<p><strong>So the general question is</strong>: how do you provide access to global application settings in your projects, without the need for global variables, while still being able to unit test your code? This must be a problem that's been solved 100's of times...</p>
<p>(Note: I'm not too much of an experienced programmer, as you'll have noticed; but I love to learn! And of course, I've already done research into this topic, but I'm really looking for some first-hand experiences)</p>
| <p>You could use Martin Fowlers ServiceLocator pattern. In php it could look like this:</p>
<pre><code>class ServiceLocator {
private static $soleInstance;
private $globalSettings;
public static function load($locator) {
self::$soleInstance = $locator;
}
public static function globalSettings() {
if (!isset(self::$soleInstance->globalSettings)) {
self::$soleInstance->setGlobalSettings(new GlobalSettings());
}
return self::$soleInstance->globalSettings;
}
}
</code></pre>
<p>Your production code then initializes the service locator like this:</p>
<pre><code>ServiceLocator::load(new ServiceLocator());
</code></pre>
<p>In your test-code, you insert your mock-settings like this:</p>
<pre><code>ServiceLocator s = new ServiceLocator();
s->setGlobalSettings(new MockGlobalSettings());
ServiceLocator::load(s);
</code></pre>
<p>It's a repository for singletons that can be exchanged for testing purposes.</p>
|
Considering N2 CMS but worried about performance. Is this justified? <p>Hy, does anyone worked with N2 Content Management System(<a href="http://www.codeplex.com/n2" rel="nofollow">http://www.codeplex.com/n2</a>).
If yes, how does it perform, performance wise(under heavy load)?
It seems pretty simple and easy to use.</p>
<p>Adrian</p>
| <p>Maybe try this question at <a href="http://www.codeplex.com/n2/Thread/List.aspx" rel="nofollow"><a href="http://www.codeplex.com/n2/Thread/List.aspx" rel="nofollow">http://www.codeplex.com/n2/Thread/List.aspx</a></a></p>
<p>They might be able to tell you about performance limitations or bottlenecks.</p>
|
Programmatically list WMI classes and their properties <p>Hey everyone,
Is there any known way of listing the WMI classes and their properties available for a particular system? Im interested in a vbscript approach, but please suggest anything really :)</p>
<p>P.S. Great site.</p>
| <p>I believe this is what you want.</p>
<p><a href="http://www.microsoft.com/downloads/details.aspx?familyid=2cc30a64-ea15-4661-8da4-55bbc145c30e&displaylang=en" rel="nofollow">WMI Code Creator</a></p>
<p>A part of this nifty utility allows you to browse namespaces/classes/properties on the local and remote PCs, not to mention generating WMI code in VBScript/C#/VB on the fly. Very useful.</p>
<p>Also, the source code used to create the utility is included in the download, which could provide a reference if you wanted to create your own browser like interface.</p>
|
Add .NET 2.0 SP1 as a prerequisite for deployment project <p>I have a .NET 2.0 application that has recently had contributions that are Service Pack 1 dependent. The deployment project has detected .NET 2.0 as a prerequisite, but NOT SP1. How do I include SP1 as a dependency/prerequisite in my deployment project?</p>
| <p>You'll want to setup launch condition in your deployment project to make sure version 2.0 SP1 is installed. You'll want to set a requirement based off the MsiNetAssemblySupport variable, tied to the version number of .NET 2.0 SP1 (2.0.50727.1433 and above according to <a href="http://blogs.msdn.com/astebner/archive/2005/07/12/what-net-framework-version-numbers-go-with-what-service-pack.aspx" rel="nofollow">this page</a>.)</p>
<p>Bootstrapping the project to actually download the framework if it isn't installed is a different matter, and there are plenty of articles out there on how to do that.</p>
|
Arrays of Arrays in Java <p>This is a nasty one for me... I'm a PHP guy working in Java on a JSP project. I know how to do what I'm attempting through too much code and a complete lack of finesse. I'd prefer to do it RIGHT. :) Here is the situation:</p>
<p>I'm writing a small display to show customers what days they can water their lawns based on their watering group (ABCDE) and what time of year it is. Our seasons look like this:
Summer (5-1 to 8-31)
Spring (3-1 to 4-30)
Fall (9-1 to 10-31)
Winter (11-1 to 2-28) </p>
<p>An example might be:</p>
<p>If I'm in group A, here would be my allowed times:
Winter: Mondays only
Spring: Tues, Thurs, Sat
Summer: Any Day
Fall: Tues, Thurs, Sat</p>
<p>If I was writing this in PHP I would use arrays like this:</p>
<pre><code>//M=Monday,t=Tuesday,T=Thursday.... etc
$schedule["A"]["Winter"]='M';
$schedule["A"]["Spring"]='tTS';
$schedule["A"]["Summer"]='Any';
$schedule["A"]["Fall"]='tTS';
$schedule["B"]["Winter"]='t';
</code></pre>
<p>I COULD make the days arrays (array("Tuesday","Thursday","Saturday")) etc, but it is not necessary for what I'm really trying to accomplish.</p>
<p>I will also need to setup arrays to determine what season I'm in:</p>
<pre><code>$seasons["Summer"]["start"]=0501;
$seasons["Summer"]["end"]=0801;
</code></pre>
<p>Can anyone suggest a really cool way to do this? I will have today's date and the group letter. I will need to get out of my function a day (M) or a series of days (tTS), (Any).</p>
<p>Thanks, folks!</p>
| <p>Don't try to be as dynamic as PHP is. You could try to first <strong>define</strong> what you need.</p>
<pre><code>interface Season
{
public string getDays();
}
interface User
{
public Season getWinter();
public Season getSpring();
public Season getSummer();
public Season getFall();
}
interface UserMap
{
public User getUser(string name);
}
</code></pre>
<p>And please, read the documentation of <a href="http://java.sun.com/javase/6/docs/api/java/util/Hashtable.html">Hashtable</a> before using it. This class is synchronized which means that each call is protected against multithreading which really slows the access when you don't need the extra protection. Please use any <a href="http://java.sun.com/javase/6/docs/api/java/util/Map.html">Map</a> implementation instead like <a href="http://java.sun.com/javase/6/docs/api/java/util/HashMap.html">HashMap</a> or <a href="http://java.sun.com/javase/6/docs/api/java/util/TreeMap.html">TreeMap</a>.</p>
|
Large Data Sets <p>I'm always looking for large data sets to test various types of programs on. Does anyone have any suggestions?</p>
| <p>Check out the <a href="http://www.netflixprize.com/">netflix contest</a>. I believe they exposed their database, or a large subset, to facilitate the contest.</p>
<p>UPDATE: <a href="http://www.netflixprize.com/faq">Their faq</a> says they have 100 million entries in the subset you can download.</p>
|
What is a good way to denormalize a mysql database? <p>I have a large database of normalized order data that is becoming very slow to query for reporting. Many of the queries that I use in reports join five or six tables and are having to examine tens or hundreds of thousands of lines.</p>
<p>There are lots of queries and most have been optimized as much as possible to reduce server load and increase speed. I think it's time to start keeping a copy of the data in a denormalized format.</p>
<p>Any ideas on an approach? Should I start with a couple of my worst queries and go from there?</p>
| <p>I know more about mssql that mysql, but I don't think the number of joins or number of rows you are talking about should cause you too many problems with the correct indexes in place. Have you analyzed the query plan to see if you are missing any?</p>
<p><a href="http://dev.mysql.com/doc/refman/5.0/en/explain.html"><a href="http://dev.mysql.com/doc/refman/5.0/en/explain.html">http://dev.mysql.com/doc/refman/5.0/en/explain.html</a></a></p>
<p>That being said, once you are satisifed with your indexes and have exhausted all other avenues, de-normalization might be the right answer. If you just have one or two queries that are problems, a manual approach is probably appropriate, whereas some sort of data warehousing tool might be better for creating a platform to develop data cubes.</p>
<p>Here's a site I found that touches on the subject:</p>
<p><a href="http://www.meansandends.com/mysql-data-warehouse/?link_body%2Fbody=%7Bincl%3AAggregation%7D"><a href="http://www.meansandends.com/mysql-data-warehouse/?link_body%2Fbody=%7Bincl%3AAggregation%7D">http://www.meansandends.com/mysql-data-warehouse/?link_body%2Fbody=%7Bincl%3AAggregation%7D</a></a></p>
<p>Here's a simple technique that you can use to keep denormalizing queries simple, if you're just doing a few at a time (and I'm not replacing your OLTP tables, just creating a new one for reporting purposes). Let's say you have this query in your application:</p>
<pre><code>select a.name, b.address from tbla a
join tblb b on b.fk_a_id = a.id where a.id=1
</code></pre>
<p>You could create a denormalized table and populate with almost the same query:</p>
<pre><code>create table tbl_ab (a_id, a_name, b_address);
-- (types elided)
</code></pre>
<p>Notice the underscores match the table aliases you use</p>
<pre><code>insert tbl_ab select a.id, a.name, b.address from tbla a
join tblb b on b.fk_a_id = a.id
-- no where clause because you want everything
</code></pre>
<p>Then to fix your app to use the new denormalized table, switch the dots for underscores. </p>
<pre><code>select a_name as name, b_address as address
from tbl_ab where a_id = 1;
</code></pre>
<p>For huge queries this can save a lot of time and makes it clear where the data came from, and you can re-use the queries you already have.</p>
<p>Remember, I'm only advocating this as the last resort. I bet there's a few indexes that would help you. And when you de-normalize, don't forget to account for the extra space on your disks, and figure out when you will run the query to populate the new tables. This should probably be at night, or whenever activity is low. And the data in that table, of course, will never exactly be up to date.</p>
<p>[Yet another edit] Don't forget that the new tables you create need to be indexed too! The good part is that you can index to your heart's content and not worry about update lock contention, since aside from your bulk insert the table will only see selects.</p>
|
How to setup site-wide variables in php? <p>I want to define something like this in <em>php</em>:</p>
<pre><code>$EL = "\n<br />\n";
</code></pre>
<p>and then use that variable as an "endline" marker all over my site, like this:</p>
<pre><code>echo "Blah blah blah{$EL}";
</code></pre>
<p>How do I define $EL once (in only 1 file), include it on every page on my site, and <em>not</em> have to reference it using the (strangely backwards) <code>global $EL;</code> statement in every page function?</p>
| <p>Most PHP sites should have a file (I call it a header) that you include on every single page of the site. If you put that first line of code in the header file, then include it like this on every page:</p>
<pre><code> include 'header.php';
</code></pre>
<p>you won't have to use the global keyword or anything, the second line of code you wrote should work.</p>
<p>Edit: Oh sorry, that won't work inside functions... now I see your problem.</p>
<p>Edit #2: Ok, take my original advice with the header, but use a <a href="http://php.net/define" rel="nofollow" title="Dr. Explain">define()</a> rather than a variable. Those work inside functions after being included.</p>
|
What do ref, val and out mean on method parameters? <p>I'm looking for a clear, concise and accurate answer. </p>
<p>Ideally as the actual answer, although links to good explanations welcome.</p>
<p>This also applies to VB.Net, but the keywords are different - <code>ByRef</code> and <code>ByVal</code>.</p>
| <p>By default (in C#), passing an object to a function actually passes a copy of the reference to that object. Changing the parameter itself only changes the value in the parameter, and not the variable that was specified.</p>
<pre><code>void Test1(string param)
{
param = "new value";
}
string s1 = "initial value";
Test1(s1);
// s1 == "initial value"
</code></pre>
<p>Using <code>out</code> or <code>ref</code> passes a reference to the variable specified in the call to the function. Any changes to the value of an <code>out</code> or <code>ref</code> parameter will be passed back to the caller.</p>
<p>Both <code>out</code> and <code>ref</code> behave identically except for one slight difference: <code>ref</code> parameters are required to be initialised before calling, while <code>out</code> parameters can be uninitialised. By extension, <code>ref</code> parameters are guaranteed to be initialised at the start of the method, while <code>out</code> parameters are treated as uninitialised.</p>
<pre><code>void Test2(ref string param)
{
param = "new value";
}
void Test3(out string param)
{
// Use of param here will not compile
param = "another value";
}
string s2 = "initial value";
string s3;
Test2(ref s2);
// s2 == "new value"
// Test2(ref s3); // Passing ref s3 will not compile
Test3(out s2);
// s2 == "another value"
Test3(out s3);
// s3 == "another value"
</code></pre>
<p><strong>Edit</strong>: As <a href="http://stackoverflow.com/questions/13060/what-do-ref-val-and-out-mean-on-method-parameters#13105" rel="nofollow" title="dp">dp</a> points out, the difference between <code>out</code> and <code>ref</code> is only enforced by the C# compiler, not by the CLR. As far as I know, VB has no equivalent for <code>out</code> and implements <code>ref</code> (as <code>ByRef</code>) only, matching the support of the CLR.</p>
|
Best practice for webservices <p>I've created a webservice and when I want to use its methods I instantiate it in the a procedure, call the method, and I finally I dispose it, however I think also it could be okay to instantiate the webservice in the "private void Main_Load(object sender, EventArgs e)" event.</p>
<p>The thing is that if I do it the first way I have to instantiate the webservice every time I need one of its methods but in the other way I have to keep a webservice connected all the time when I use it in a form for example. </p>
<p>I would like to know which of these practices are better or if there's a much better way to do it</p>
<p><strong>Strategy 1</strong></p>
<pre><code>private void btnRead_Click(object sender, EventArgs e)
{
try
{
//Show clock
this.picResult.Image = new Bitmap(pathWait);
Application.DoEvents();
//Connect to webservice
svc = new ForPocketPC.ServiceForPocketPC();
svc.Credentials = new System.Net.NetworkCredential(Settings.UserName, Settings.Password);
svc.AllowAutoRedirect = false;
svc.UserAgent = Settings.UserAgent;
svc.PreAuthenticate = true;
svc.Url = Settings.Url;
svc.Timeout = System.Threading.Timeout.Infinite;
svc.CallMethod();
...
}
catch (Exception ex)
{
ShowError(ex);
}
finally
{
if (svc != null)
svc.Dispose();
}
}
</code></pre>
<p><strong>Strategy 2</strong></p>
<pre><code>private myWebservice svc;
private void Main_Load(object sender, EventArgs e)
{
//Connect to webservice
svc = new ForPocketPC.ServiceForPocketPC();
svc.Credentials = new System.Net.NetworkCredential(Settings.UserName, Settings.Password);
svc.AllowAutoRedirect = false;
svc.UserAgent = Settings.UserAgent;
svc.PreAuthenticate = true;
svc.Url = Settings.Url;
svc.Timeout = System.Threading.Timeout.Infinite;
}
private void btnRead_Click(object sender, EventArgs e)
{
try
{
//Show clock
this.picResult.Image = new Bitmap(pathWait);
Application.DoEvents();
svc.CallMethod();
...
}
catch (Exception ex)
{
ShowError(ex);
}
}
private void Main_Closing(object sender, CancelEventArgs e)
{
svc.Dispose();
}
</code></pre>
| <p>It depends on how often you are going to be calling the web service. If you're going to be calling it almost constantly, it would probably be better to use method #2. However, if it's not going to be getting called quite so often, you are better off using method #1, and only instantiating it when you need it.</p>
|
A ThreadStateException occures when trying to restart a thread <p>From time to time I get a System.Threading.ThreadStateException when attempting to restart a thread. The code in question is as follows:</p>
<pre><code>// Make sure the thread is done stopping
while (this.mThread.ThreadState == ThreadState.Running)
{
Thread.Sleep(0);
}
// Respawn a thread if the current one is stopped or doesn't exist
if (this.mThread == null || this.mThread.ThreadState == ThreadState.Stopped)
{
this.mThread = new Thread(new ParameterizedThreadStart(Monitor)); }
// Start the thread
if (check)
{
this.mThread.Start(60000);
}
else
{
this.mThread.Start(0);
}
</code></pre>
<p>So two questions - is this the correct way of doing things, and it is, is there a way to prevent the error from occurring?</p>
| <p>It's possible for a thread to be in more than one state at once therefore the ThreadState property is actually a bitmap of possible states. So testing for equality with just one state will not give you the right result. You would need to do something like:</p>
<pre><code>if((mThread.ThreadState & ThreadState.Running) != 0)
</code></pre>
<p>However, checking thread state is the wrong to do anything. I'm not entirely clear what you're trying to achieve but I will guess that you're waiting for a thread to terminate before restarting it. In that case you should do:</p>
<pre><code>mThread.Join();
mThread = new Thread(new ParameterizedThreadStart(Monitor));
if(check)
mThread.Start(60000);
else
mThread.Start(0);
</code></pre>
<p>Although if you describe the problem you're trying to solve in more detail I'm almost certain there will be a better solution. Waiting around for a thread to end just to restart it again doesn't seem that efficient to me. Perhaps you just need some kind of inter-thread communication?</p>
<p>John.</p>
|
How do I integrate my continuous integration system with my bug tracking system? <p>I use cruisecontrol.rb for CI and FogBugz for bug tracking, but the more general the answers, the better.</p>
<p>First is the technical problem: is there an API for FogBugz? Are there good tutorials, or better yet, pre-written code?</p>
<p>Second is the procedural problem: what, exactly, should the CI put in the bug tracker when the build breaks? Perhaps:</p>
<p>Title: "#{last committer} broke the build!"</p>
<p>Body: "#{ error traces }"</p>
<p>I suppose this presupposes the answer to this question: should I even put CI breaks into my bug tracking?</p>
| <p>At my company we've recently adopted the (commercial) Atlassian stack - including JIRA for issue tracking and Bamboo for builds. Much like the Microsoft world (I'm guessing - we're a Java shop), if you get all your products from a single vendor you get the bonus of tight integration.</p>
<p>For an example of how they've done interoperability, view their <a href="http://www.atlassian.com/software/bamboo/features/interoperability.jsp" rel="nofollow" title="interoperability">interoperability page</a>.</p>
<p>Enough shilling. Generally speaking, I can summarize their general approach as:</p>
<ul>
<li>Create issues in your bug tracker (ex: issue key of PROJ-123).</li>
<li>When you commit code, add "PROJ-123" to your commit comment to indicate what bug this code change fixes.</li>
<li>When your CI server checks out the code, scan the commit comments of the diffs. Record any strings matching the regex of your issue keys.</li>
<li>When the build completes, generate a report of what issue keys were found.</li>
</ul>
<p>Specifically to your second problem:</p>
<p>Your CI doesn't doesn't have to put anything into your bug tracker. Bamboo doesn't put anything into JIRA. Instead, the Atlassian folks have provided a plugin to JIRA that will make a remote api call into Bamboo, asking the question "Bamboo, to what builds am I (a JIRA issue) related?". This is probably best explained with a <a href="http://confluence.atlassian.com/display/BAMBOO/Bamboo+2.1+Release+Notes#Bamboo2.1ReleaseNotes-LinkIssuesandBuilds" rel="nofollow" title="screenshot">screenshot</a>.</p>
|
Does CruiseControl.NET run on IIS 7.0? <p>I'm new to development (an admin by trade) and I'm setting up my development environment and I would like to set up a CruiseControl.Net server on Server 2008. A quick Google did not turn up any instructions for getting it running on IIS 7.0, so I was wondering if anyone had experience getting this set up.</p>
| <p>Here is a helpful article that worked for me:</p>
<p><a href="http://huntjason.wordpress.com/2009/08/13/getting-cruisecontrol-net-working-under-iis7/" rel="nofollow">Getting CruiseControl.NET working under IIS7</a></p>
|
The theory (and terminology) behind Source Control <p>I've tried using source control for a couple projects but still don't really understand it. For these projects, we've used TortoiseSVN and have only had one line of revisions. (No trunk, branch, or any of that.) If there is a recommended way to set up source control systems, what are they? What are the reasons and benifits for setting it up that way? What is the underlying differences between the workings of a centralized and distributed source control system?</p>
| <p>Think of source control as a giant "Undo" button for your source code. Every time you check in, you're adding a point to which you can roll back. Even if you don't use branching/merging, this feature alone can be very valuable.</p>
<p>Additionally, by having one 'authoritative' version of the source control, it becomes much easier to back up.</p>
<p>Centralized vs. distributed... the difference is really that in distributed, there isn't necessarily one 'authoritative' version of the source control, although in practice people usually still do have the master tree.</p>
<p>The big advantage to distributed source control is two-fold:</p>
<ol>
<li><p>When you use distributed source control, you have the whole source tree on your local machine. You can commit, create branches, and work pretty much as though you were all alone, and then when you're ready to push up your changes, you can promote them from your machine to the master copy. If you're working "offline" a lot, this can be a huge benefit.</p></li>
<li><p>You don't have to ask anybody's permission to become a distributor of the source control. If person A is running the project, but person B and C want to make changes, and share those changes with each other, it becomes much easier with distributed source control.</p></li>
</ol>
|
Purpose of {1} in this regular expression to match url protocols <p>I was reading <a href="http://stackoverflow.com/questions/6173/regular-expression-for-parsing-links-from-a-webpage">this question</a> about how to parse URLs out of web pages and had a question about the <a href="http://stackoverflow.com/questions/6173/regular-expression-for-parsing-links-from-a-webpage#6183">accepted answer</a> which offered this solution:</p>
<pre class="lang-none prettyprint-override"><code>((mailto\:|(news|(ht|f)tp(s?))\://){1}\S+)
</code></pre>
<p>The solution was offered by <a href="http://stackoverflow.com/users/350/csmba">csmba</a> and he credited it to <a href="http://regexlib.com/Search.aspx?k=URL" rel="nofollow">regexlib.com</a>. Whew. Credits done.</p>
<p>I think this is a fairly naive regular expression but it's a fine starting point for building something better. But, my question is this:</p>
<p>What is the point of <code>{1}</code>? It means "exactly one of the previous grouping", right? Isn't that the default behavior of a grouping in a regular expression? Would the expression be changed in any way if the <code>{1}</code> were removed?</p>
<p>If I saw this from a coworker I would point out his or her error but as I write this the response is rated at a 6 and the expression on regexlib.com is rated a 4 of 5. So maybe I'm missing something?</p>
| <p>@<a href="http://stackoverflow.com/questions/13470/question-about-specific-regular-expression#13479" rel="nofollow">Rob</a>: I disagree. To enforce what you are asking for I think you would need to use negative-look-behind, which is possible but is certainly not related to use {1}. Neither version of the regexp address that particular issue.</p>
<p>To let the code speak:</p>
<pre><code>tibook 0 /home/jj33/swap > cat text
Text this is <http://example.com> text this is
Text this is <http://http://example.com> text this is
tibook 0 /home/jj33/swap > cat p
#!/usr/bin/perl
my $re1 = '((mailto\:|(news|(ht|f)tp(s?))\://){1}\S+)';
my $re2 = '((mailto\:|(news|(ht|f)tp(s?))\://)\S+)';
while (<>) {
print "Evaluating: $_";
print "re1 saw \$1 = $1\n" if (/$re1/);
print "re2 saw \$1 = $1\n" if (/$re2/);
}
tibook 0 /home/jj33/swap > cat text | perl p
Evaluating: Text this is <http://example.com> text this is
re1 saw $1 = <http://example.com>
re2 saw $1 = <http://example.com>
Evaluating: Text this is <http://http://example.com> text this is
re1 saw $1 = <http://http://example.com>
re2 saw $1 = <http://http://example.com>
tibook 0 /home/jj33/swap >
</code></pre>
<p>So, if there is a difference between the two versions, it's doesn't seem to be the one you suggest.</p>
|
Insert Update stored proc on SQL Server <p>I've written a stored proc that will do an update if a record exists, otherwise it will do an insert. It looks something like this:</p>
<pre><code>update myTable set Col1=@col1, Col2=@col2 where ID=@ID
if @@rowcount = 0
insert into myTable (Col1, Col2) values (@col1, @col2)
</code></pre>
<p>My logic behind writing it in this way is that the update will perform an implicit select using the where clause and if that returns 0 then the insert will take place.</p>
<p>The alternative to doing it this way would be to do a select and then based on the number of rows returned either do an update or insert. This I considered inefficient because if you are to do an update it will cause 2 selects (the first explicit select call and the second implicit in the where of the update). If the proc were to do an insert then there'd be no difference in efficiency.</p>
<p>Is my logic sound here?
Is this how you would combine an insert and update into a stored proc?</p>
| <p>Your assumption is right, this is the optimal way to do it and it's called <a href="http://en.wikipedia.org/wiki/Upsert">upsert/merge</a>.</p>
<p><a href="http://www.sqlservercentral.com/articles/T-SQL/61773/">Importance of UPSERT - from sqlservercentral.com</a>: </p>
<blockquote>
<p>For every update in the case mentioned above we are removing one
additional read from the table if we
use the UPSERT instead of EXISTS.
Unfortunately for an Insert, both the
UPSERT and IF EXISTS methods use the
same number of reads on the table.
Therefore the check for existence
should only be done when there is a
very valid reason to justify the
additional I/O. The optimized way to
do things is to make sure that you
have little reads as possible on the
DB.</p>
<p>The best strategy is to attempt the
update. If no rows are affected by the
update then insert. In most
circumstances, the row will already
exist and only one I/O will be
required.</p>
</blockquote>
<p><strong>Edit</strong>:
Please check out <a href="http://stackoverflow.com/questions/13540/insert-update-stored-proc-on-sql-server/193876#193876">this answer</a> and the linked blog post to learn about the problems with this pattern and how to make it work safe.</p>
|
CASE tools <p>I was using a CASE called <a href="http://www.magicsoftware.com/" rel="nofollow">MAGIC</a> for a system I'm developing, I've never used this kind of tool before and at first sight I liked, a month later I had a lot of the application generated, I felt very productive and ... I would say ... satisfied.</p>
<p>In some way a felt uncomfortable, cause, there is no code and everything I was used to, but in the other hand I could speed up my developing. The fact is that eventually I returned to use C# because I find it more flexible to develop, I can make unit testing, use CVS, I have access to more resources and basically I had "all the control". I felt that this tool didn't give me confidence and I thought that later in the project I could not manage it due to its forced established rules of development. And also a lot of things like sending emails, using my own controls, and other things had their complication, it seemed that at some point it was not going to be as easy as initially I thought and as initially the product claims. This reminds me a very nice article called "<a href="http://www.virtualschool.edu/mon/SoftwareEngineering/BrooksNoSilverBullet.html" rel="nofollow">No Silver Bullet</a>".</p>
<p>This CASE had its advantages but on the other hand it doesn't have resources you can consult and actually the license and certification are very expensive. For me another dissapointing thing is that because of its simplistic approach for development I felt scared on first hand cause of my unexperience on these kind of tools and second cause I thought that if I continued using it maybe it would have turned to be a complex monster that I could not manage later in the project.</p>
<p>I think its good to use these kind of solutions to speed up things but I wonder, why aren't these programs as popular as VS.Net, J2EE, Ruby, Python, etc. if they claim to enhace productivity better than the tools I've pointed?</p>
| <p>We use a CASE tool at my current company for code generation and we are trying to move away from it.</p>
<p>The benefits that it brings - a graphical representation of the code making components 'easier' to pick up for new developers - are outweighed by the disadvantges in my opinion.</p>
<p>Those main disadvantages are:</p>
<ol>
<li><p>We cannot do automatic merges, making it close to impossible for parallel development on one component.</p></li>
<li><p>Developers get dependant on the tool and 'forget' how to handcode.</p></li>
</ol>
|
Speed difference in using inline strings vs concatenation in php5? <p>(assume php5) consider</p>
<pre><code><?php
$foo = 'some words';
//case 1
print "these are $foo";
//case 2
print "these are {$foo}";
//case 3
print 'these are ' . $foo;
?>
</code></pre>
<p>Is there much of a difference between 1 and 2?</p>
<p>If not, what about between 1/2 and 3?</p>
| <p>The performance difference has been <a href="http://nikic.github.com/2012/01/09/Disproving-the-Single-Quotes-Performance-Myth.html" rel="nofollow">irrelevant</a> since at least January 2012, and likely earlier:</p>
<pre><code>Single quotes: 0.061846971511841 seconds
Double quotes: 0.061599016189575 seconds
</code></pre>
<p>Earlier versions of PHP may have had a difference - I personally prefer single quotes to double quotes, so it was a convenient difference. The conclusion of the article makes an excellent point:</p>
<blockquote>
<p>Never trust a statistic you didnât forge yourself.</p>
</blockquote>
<p>(Although the article quotes the phrase, the original quip was likely falsely <a href="http://www.statistik.baden-wuerttemberg.de/Service/Veroeff/Monatshefte/20041111.mha" rel="nofollow">attributed</a> to Winston Churchill, invented by Joseph Goebbels' propaganda ministry to portray Churchill as a liar:</p>
<blockquote>
<p>Ich traue keiner Statistik, die ich nicht selbst gefälscht habe.</p>
</blockquote>
<p>This loosely translates to, "I do not trust a statistic that I did not fake myself.")</p>
|
Developer testing vs. QA team testing - What is the right division of work? <p>While trying to advocate more developer testing, I find the argument "Isn't that QA's job?" is used a lot. In my mind, it doesn't make sense to give the QA team all testing responsibilities, but at the same time Spolsky and others say you shouldn't be using the $100/hr developers to do something a $30/hr tester could be doing. What are the experiences of others in a company with a dedicated QA team? Where should the division of work be drawn?</p>
<p>Clarification: I meant QA as a validation and verification team. Devs should not be doing the validation (customer-focused testing), but where is the verification (functional testing) division point?</p>
| <p>It's the difference between "black box" testing (where you know what the code is supposed to do, but not how it works), and "white box" testing (where knowing how it works drives how you test it). "Black box" testing is what most people think of when you mention Quality Assurance.</p>
<p>I work for a company where the QA team are also software developers. (That narrows the field <em>a lot</em> if you care to guess the company.) I know Joel's opinion, and my experience leads me to partially disagree: for the same reason that a "white hat" hacker is more effective finding security holes, certain kinds of errors are more effectively found by white box testers who know how to write code (and therefore what the common mistakes are - for example, resource management issues like memory leaks). </p>
<p>Also, since QA-oriented developers are part of the process from the initial design phase, they can theoretically help to drive higher-quality code throughout the process. Ideally, for each developer working on the project with a mental focus on functionality, you have an opposing developer with a mental focus on breaking the code (and thus making it better). </p>
<p>Seen in that light, it's less a matter of using developers for testers than it is kind of disconnected pair-programming where one developer has an emphasis on controlling quality. </p>
<p>On the other hand, a lot of testing (such as basic UI functionality) frankly doesn't need that kind of skill. That's where Joel has a point. </p>
<p>For many businesses, I could see a system where programming teams trade off code review and testing duties for each others' code. Members of the Business Logic team, for example, could spend an occasional tour testing and reviewing code for the UI team, and vice-versa. That way you're not "wasting" developer talent on full-time testing, but you are gaining the advantages of exposing the code to (hopefully) expert scrutiny and punishment. Then, a more traditional QA team can take up the "black box" testing.</p>
|
How do I make Powershell run a batch file and then stay open? <p>For example; with the old command prompt it would be:</p>
<pre><code>cmd.exe /k mybatchfile.bat
</code></pre>
| <p>Drop into a cmd instance (or indeed PowerShell itself) and type this:</p>
<pre><code>powershell -?
</code></pre>
<p>You'll see that powershell.exe has a "-noexit" parameter which tells it not to exit after executing a "startup command".</p>
|
Using OpenGL textures larger than window/display size <p>I'm having problems using textures that are larger than the OpenGL window or the display size as non-display render targets.<br>
What's the solution for this problem?</p>
| <p>There's a simple solution.</p>
<p>Assuming your (non-display) textures are <strong>1024x1024</strong> and you are restricted to a <strong>256x256</strong> window/display.</p>
<pre><code>unsigned int WIN_WIDTH = 256;
unsigned int WIN_HEIGHT = WIN_WIDTH;
unsigned int TEX_WIDTH = 1024;
unsigned int TEX_HEIGHT = TEX_WIDTH;
</code></pre>
<p>Use the <em>window size</em> to create your OpenGL window:</p>
<pre><code>glutInitWindowSize(WIN_WIDTH, WIN_HEIGHT);
</code></pre>
<p>But, use the <em>texture size</em> for everything else:</p>
<pre><code>glViewport(0, 0, TEX_WIDTH, TEX_HEIGHT);
gluOrtho2D(0.0, TEX_WIDTH, 0.0, TEX_HEIGHT);
glTexCoord2i(TEX_WIDTH, TEX_HEIGHT);
</code></pre>
|
RGB to monochrome conversion <p>How do I convert the RGB values of a pixel to a single monochrome value?</p>
| <p>I found one possible solution in the <a href="http://www.poynton.com/notes/colour_and_gamma/ColorFAQ.html">Color FAQ</a>. The <em>luminance component</em> Y (from the <em>CIE XYZ system</em>) captures what is most perceived by humans as color in one channel. So, use those coefficients:</p>
<pre><code>mono = (0.2125 * color.r) + (0.7154 * color.g) + (0.0721 * color.b);
</code></pre>
|
How do I call a Flex SWF from a remote domain using Flash (AS3)? <p>I have a Flex swf hosted at <a href="http://www.a.com/a.swf" rel="nofollow">http://www.a.com/a.swf</a>.
I have a flash code on another doamin that tries loading the SWF:</p>
<pre><code>_loader = new Loader();
var req:URLRequest = new URLRequest("http://services.nuconomy.com/n.swf");
_loader.contentLoaderInfo.addEventListener(Event.COMPLETE,onLoaderFinish);
_loader.load(req);
</code></pre>
<p>On the onLoaderFinish event I try to load classes from the remote SWF and create them:</p>
<pre><code>_loader.contentLoaderInfo.applicationDomain.getDefinition("someClassName") as Class
</code></pre>
<p>When this code runs I get the following exception</p>
<pre><code>SecurityError: Error #2119: Security sandbox violation: caller http://localhost.service:1234/flashTest/Main.swf cannot access LoaderInfo.applicationDomain owned by http://www.b.com/b.swf.
at flash.display::LoaderInfo/get applicationDomain()
at NuconomyLoader/onLoaderFinish()
</code></pre>
<p>Is there any way to get this code working?</p>
| <p>This is all described in <a href="http://livedocs.adobe.com/flex/3/progAS_flex3.pdf" rel="nofollow" title="Flex Documentation: System.Security.allowDomain">The Adobe Flex 3 Programming ActionScript 3 PDF</a> on page 550 (Chapter 27: Flash Player Security / Cross-scripting):</p>
<blockquote>
<p>If two SWF files written with ActionScript 3.0 are served from different domainsâfor example, <a href="http://siteA.com/swfA.swf" rel="nofollow">http://siteA.com/swfA.swf</a> and <a href="http://siteB.com/swfB.swf" rel="nofollow">http://siteB.com/swfB.swf</a>âthen, by default, Flash Player does not allow swfA.swf to script swfB.swf, nor swfB.swf to script swfA.swf. A SWF file gives permission to SWF files from other domains by calling Security.allowDomain(). By calling Security.allowDomain("siteA.com"), swfB.swf gives SWF files from siteA.com permission to script it.</p>
</blockquote>
<p>It goes on in some more detail, with diagrams and all.</p>
|
GLUT pop-up menus <p>Is it easy to create GLUT pop-up menus for my OpenGL application? If yes, how?</p>
| <p>Creating and using pop-up menus with GLUT is very simple. Here is a code sample that creates a pop-up menu with 4 options:</p>
<pre class="lang-c prettyprint-override"><code>// Menu items
enum MENU_TYPE
{
MENU_FRONT,
MENU_SPOT,
MENU_BACK,
MENU_BACK_FRONT,
};
// Assign a default value
MENU_TYPE show = MENU_BACK_FRONT;
// Menu handling function declaration
void menu(int);
int main()
{
// ...
// Create a menu
glutCreateMenu(menu);
// Add menu items
glutAddMenuEntry("Show Front", MENU_FRONT);
glutAddMenuEntry("Show Back", MENU_BACK);
glutAddMenuEntry("Spotlight", MENU_SPOT);
glutAddMenuEntry("Blend 'em all", MENU_BACK_FRONT);
// Associate a mouse button with menu
glutAttachMenu(GLUT_RIGHT_BUTTON);
// ...
return;
}
// Menu handling function definition
void menu(int item)
{
switch (item)
{
case MENU_FRONT:
case MENU_SPOT:
case MENU_DEPTH:
case MENU_BACK:
case MENU_BACK_FRONT:
{
show = (MENU_TYPE) item;
}
break;
default:
{ /* Nothing */ }
break;
}
glutPostRedisplay();
return;
}
</code></pre>
|
Why are there so few modal-editors that aren't vi*? <p>Pretty much every other editor that isn't a vi descendant (vim, cream, vi-emu) seems to use the emacs shortcuts (<kbd>ctrl</kbd>+<kbd>w</kbd> to delete back a word and so on)</p>
| <p>Early software was often modal, but usability took a turn at some point, away from this style. </p>
<p>VI-based editors are total enigmas -- they're the only real surviving members of that order of software. </p>
<p>Modes are a no-no in usability and interaction design because we humans are fickle mammals who cannot be trusted to remember what mode the application is in. </p>
<p>If you think you are in one "mode" when you are actually in another, then all sorts of badness can ensue. What you believe to be a series of harmless keystrokes can (in the wrong mode) cause unlimited catastrophe. This is known as a "mode error".</p>
<p>To learn more, search for the term "modeless" (and "usability")</p>
<p>As mentioned in the comments below, a Modal interface in the hands of an experienced and non-fickle person can be extremely efficient.</p>
|
LINQ-to-SQL vs stored procedures? <p>I took a look at the "Beginner's Guide to LINQ" post here on StackOverflow (<a href="http://stackoverflow.com/questions/8050/beginners-guide-to-linq">http://stackoverflow.com/questions/8050/beginners-guide-to-linq</a>), but had a follow-up question:</p>
<p>We're about to ramp up a new project where nearly all of our database op's will be fairly simple data retrievals (there's another segment of the project which already writes the data). Most of our other projects up to this point make use of stored procedures for such things. However, I'd like to leverage LINQ-to-SQL if it makes more sense.</p>
<p>So, the question is this: For simple data retrievals, which approach is better, LINQ-to-SQL or stored procs? Any specific pro's or con's?</p>
<p>Thanks.</p>
| <p>Some advantages of LINQ over sprocs:</p>
<ol>
<li><strong>Type safety</strong>: I think we all understand this.</li>
<li><strong>Abstraction</strong>: This is especially true with <a href="http://msdn.microsoft.com/en-us/library/bb386964.aspx">LINQ-to-Entities</a>. This abstraction also allows the framework to add additional improvements that you can easily take advantage of. <a href="http://msdn.microsoft.com/en-us/magazine/cc163329.aspx">PLINQ</a> is an example of adding multi-threading support to LINQ. Code changes are minimal to add this support. It would be MUCH harder to do this data access code that simply calls sprocs.</li>
<li><strong>Debugging support</strong>: I can use any .NET debugger to debug the queries. With sprocs, you cannot easily debug the SQL and that experience is largely tied to your database vendor (MS SQL Server provides a query analyzer, but often that isn't enough).</li>
<li><strong>Vendor agnostic</strong>: LINQ works with lots of databases and the number of supported databases will only increase. Sprocs are not always portable between databases, either because of varying syntax or feature support (if the database supports sprocs at all).</li>
<li><strong>Deployment</strong>: Others have mentioned this already, but it's easier to deploy a single assembly than to deploy a set of sprocs. This also ties in with #4.</li>
<li><strong>Easier</strong>: You don't have to learn T-SQL to do data access, nor do you have to learn the data access API (e.g. ADO.NET) necessary for calling the sprocs. This is related to #3 and #4.</li>
</ol>
<p>Some disadvantages of LINQ vs sprocs:</p>
<ol>
<li><strong>Network traffic</strong>: sprocs need only serialize sproc-name and argument data over the wire while LINQ sends the entire query. This can get really bad if the queries are very complex. However, LINQ's abstraction allows Microsoft to improve this over time.</li>
<li><strong>Less flexible</strong>: Sprocs can take full advantage of a database's featureset. LINQ tends to be more generic in it's support. This is common in any kind of language abstraction (e.g. C# vs assembler).</li>
<li><strong>Recompiling</strong>: If you need to make changes to the way you do data access, you need to recompile, version, and redeploy your assembly. Sprocs can <em>sometimes</em> allow a DBA to tune the data access routine without a need to redeploy anything.</li>
</ol>
<p>Security and manageability are something that people argue about too.</p>
<ol>
<li><strong>Security</strong>: For example, you can protect your sensitive data by restricting access to the tables directly, and put ACLs on the sprocs. With LINQ, however, you can still restrict direct access to tables and instead put ACLs on updatable table <em>views</em> to achieve a similar end (assuming your database supports updatable views). </li>
<li><strong>Manageability</strong>: Using views also gives you the advantage of shielding your application non-breaking from schema changes (like table normalization). You can update the view without requiring your data access code to change.</li>
</ol>
<p>I used to be a big sproc guy, but I'm starting to lean towards LINQ as a better alternative in general. If there are some areas where sprocs are clearly better, then I'll probably still write a sproc but access it using LINQ. :)</p>
|
How to organize dataset queries to improve performance <p>I don't know when to add to a dataset a tableadapter or a query from toolbox. Does it make any difference?</p>
<p>I also dont know where to create instances of the adapters. </p>
<ul>
<li>Should I do it in the <code>Page_Load</code>? </li>
<li>Should I just do it when I'm going to use it? </li>
<li>Am I opening a new connection when I create a new instance?</li>
</ul>
<p>This doesn't seem very important, but every time I create a query a little voice on my brain asks me these questions.</p>
| <blockquote>
<p>Should I just do it when I'm going to use it?</p>
</blockquote>
<p>I would recommend that you only retrieve the data when you are going to use it. If you are not going to need it, there is no reason to waste resources by retrieving it in Page_Load. If you are going to need it multiple times throughout the page load, consider saving the query results to a private variable or collection so that the same data can be reused multiple times throughout the page load.</p>
<blockquote>
<p>Am I opening a new connection when I create a new instance?</p>
</blockquote>
<p>Asp.net handles <a href="http://msdn.microsoft.com/en-us/library/8xx3tyca(vs.71).aspx" rel="nofollow">connection pooling</a>, and opens and closes connections in an efficient way. You shouldn't have to worry about this.</p>
<p>One other thing to consider from a performance perspective is to avoid using Datasets and TableAdapters. In many cases, they add <a href="http://aspnet.4guysfromrolla.com/articles/050405-1.aspx" rel="nofollow">extra overhead</a> into data retrieval that does not exist when using Linq to Sql, Stored Procedures or DataReaders.</p>
|
Is it possible to disable command input in the toolbar search box? <p>In the Visual Studio toolbar, you can enter commands into the search box by prefixing them with a > symbol. Is there any way to disable this? I've never used the feature, and it's slightly annoying when trying to actually search for something that you know is prefixed by greater-than in the code. It's particularly annoying when you accidentally search for "> exit" and the IDE quits (I knew there was a line in the code that was something like <code>if(counter > exitCount)</code> so entered that search without thinking).</p>
<p>At the very least, can you escape the > symbol so that you can search for it? Prefixing with ^ doesn't seem to work.</p>
| <p>This is a really cool feature. I've poked through the <a href="http://msdn.microsoft.com/en-us/library/1665hyw1(VS.80).aspx" rel="nofollow">feature documentation</a>, and the accompanying <a href="http://msdn.microsoft.com/en-us/library/c338aexd(VS.80).aspx" rel="nofollow">command list</a>, and not a heck of a lot is showing up in terms of turning it off.</p>
<p>If you want to search for <code>>exit</code>, you could always type <code>>Edit.Find >exit</code> in the search box; that seems to do the trick. A bit verbose, though, but it really is an edge case.</p>
|
How best to use File Version and Assembly Version? <p>In .NET there are two version numbers available when building a project, File Version and Assembly Version. How are you using these numbers? Keeping them the same? Auto-incrementing one, but manually changing the other?</p>
<p>Also what about the <code>AssemblyInformationalVersion</code> attribute?</p>
<p>I'd found this support Microsoft Knowledge Base (KB) article that provided some help: <a href="http://support.microsoft.com/kb/556041">How to use Assembly Version and Assembly File Version</a>.</p>
| <p>In solutions with multiple projects, one thing I've found very helpful is to have all the AssemblyInfo files point to a single project that governs the versioning. So my AssemblyInfos have a line:</p>
<pre><code>[assembly: AssemblyVersion(Foo.StaticVersion.Bar)]
</code></pre>
<p>I have a project with a single file that declares the string:</p>
<pre><code>namespace Foo
{
public static class StaticVersion
{
public const string Bar= "3.0.216.0"; // 08/01/2008 17:28:35
}
}
</code></pre>
<p>My automated build process then just changes that string by pulling the most recent version from the database and incrementing the second last number.</p>
<p>I only change the Major build number when the featureset changes dramatically.</p>
<p>I don't change the file version at all.</p>
|
How do you set your LAMP testing server? <p>I am using xampp on Windows, but I would like to use something closer to my server setup.</p>
<p><a href="http://phpimpact.wordpress.com/2008/05/24/virtual-appliances-lamp-development-made-easy/" rel="nofollow">Federico Cargnelutti tutorial</a> explains how to setup LAMP VMWARE appliance; it is a great introduction to VMware appliances, but one of the commands was not working and it doesn't describe how to change the keyboard layout and the timezone.</p>
<p>ps: the commands are easy to find but I don't want to look for them each time I reinstall the server. I am using this question as a reminder.</p>
| <p>Assuming you have VMware workstation, VMware player or anything that can run vmware appliance, you just need to:</p>
<ol>
<li>Download, unzip <a href="http://www.vmware.com/appliances/directory/1248" rel="nofollow">Ubuntu 8.04 Server</a> and start the virtual machine.</li>
<li>Update ubuntu and set the layout and the timezone:
<pre>
sudo apt-get update
sudo apt-get upgrade
sudo dpkg-reconfigure console-setup
sudo dpkg-reconfigure tzdata
sudo vim /etc/network/interfaces
</pre></li>
<li><a href="http://www.cyberciti.biz/tips/howto-ubuntu-linux-convert-dhcp-network-configuration-to-static-ip-configuration.html" rel="nofollow">set a fixed IP</a> (Optional). </li>
<li>install apache+mysql+php:
<pre>sudo tasksel install lamp-server
</pre></li>
</ol>
|
Changing CURRENT save/default directory in Delphi 2007 without using Save-As <p>I have a project group that contains a project I'm working on as well as some related component and packages. I prefer to keep the database links active during design-time. </p>
<p>I know how to write the code which would change the database file location, but in this case, I'm just using <code>".\data"</code> instead, for various design-time reasons. Unfortunately, using a relative folder means that Delphi needs to be "pointing" to the same folder that the project is in.</p>
<p>I'd like to be able to force the folder location to a different root, without using the "Save As" feature. Does anyone happen to know where the Delphi IDE retrieves that info?</p>
| <p>I am not sure I completely understand your question.</p>
<ul>
<li>If you are referring to the folder the IDE has as the current folder, then you can just change the shortcut that launches Delphi to set the current directory where ever you want it to be.</li>
</ul>
|
How do you create a debug only function that takes a variable argument list? Like printf() <p>I'd like to make a debug logging function with the same parameters as <code>printf</code>. But one that can be removed by the pre-processor during optimized builds.</p>
<p>For example:</p>
<pre><code>Debug_Print("Warning: value %d > 3!\n", value);
</code></pre>
<p>I've looked at variadic macros but those aren't available on all platforms. <code>gcc</code> supports them, <code>msvc</code> does not.</p>
| <p>I still do it the old way, by defining a macro (XTRACE, below) which correlates to either a no-op or a function call with a variable argument list. Internally, call vsnprintf so you can keep the printf syntax:</p>
<pre><code>#include <stdio.h>
void XTrace0(LPCTSTR lpszText)
{
::OutputDebugString(lpszText);
}
void XTrace(LPCTSTR lpszFormat, ...)
{
va_list args;
va_start(args, lpszFormat);
int nBuf;
TCHAR szBuffer[512]; // get rid of this hard-coded buffer
nBuf = _vsnprintf(szBuffer, 511, lpszFormat, args);
::OutputDebugString(szBuffer);
va_end(args);
}
</code></pre>
<p>Then a typical #ifdef switch:</p>
<pre><code>#ifdef _DEBUG
#define XTRACE XTrace
#else
#define XTRACE
#endif
</code></pre>
<p>Well that can be cleaned up quite a bit but it's the basic idea.</p>
|
Optimizing the PDF Export of Huge Reports in Sql Reporting Services 2005 <p>First off I understand that it is a horrible idea to run extremely large/long running reports. I am aware that Microsoft has a rule of thumb stating that a SSRS report should take no longer than 30 seconds to execute. However sometimes gargantuan reports are a preferred evil due to external forces such complying with state laws.</p>
<p>At my place of employment, we have an asp.net (2.0) app that we have migrated from Crystal Reports to SSRS. Due to the large user base and complex reporting UI requirements we have a set of screens that accepts user inputted parameters and creates schedules to be run over night. Since the application supports multiple reporting frameworks we do not use the scheduling/snapshot facilities of SSRS. All of the reports in the system are generated by a scheduled console app which takes user entered parameters and generates the reports with the corresponding reporting solutions the reports were created with. In the case of SSRS reports, the console app generates the SSRS reports and exports them as PDFs via the SSRS web service API. </p>
<p>So far SSRS has been much easier to deal with than Crystal with the exception of a certain 25,000 page report that we have recently converted from crystal reports to SSRS. The SSRS server is a 64bit 2003 server with 32 gigs of ram running SSRS 2005. All of our smaller reports work fantastically, but we are having trouble with our larger reports such as this one. Unfortunately, we can't seem to generate the aforemention report through the web service API. The following error occurs roughly 30-35 minutes into the generation/export:</p>
<p>Exception Message: The underlying connection was closed: An unexpected error occurred on a receive.</p>
<p>The web service call is something I'm sure you all have seen before: </p>
<pre><code>data = rs.Render(this.ReportPath, this.ExportFormat, null, deviceInfo,
selectedParameters, null, null, out encoding, out mimeType, out usedParameters,
out warnings, out streamIds);
</code></pre>
<p>The odd thing is that this report will run/render/export if the report is run directly on the reporting server using the report manager. The proc that produces the data for the report runs for about 5 minutes. The report renders in SSRS native format in the browser/viewer after about 12 minutes. Exporting to pdf through the browser/viewer in the report manager takes an additional 55 minutes. This works reliably and it produces a whopping 1.03gb pdf.</p>
<p>Here are some of the more obvious things I've tried to get the report working via the web service API: </p>
<ul>
<li>set the HttpRuntime ExecutionTimeout
value to 3 hours on the report
server</li>
<li>disabled http keep alives on the report server</li>
<li>increased the script timeout on the report server</li>
<li>set the report to never time out on the server</li>
<li>set the report timeout to several hours on the client call </li>
</ul>
<p>From the tweaks I have tried, I am fairly comfortable saying that any timeout issues have been eliminated. </p>
<p>Based off of my research of the error message, I believe that the web service API does not send chunked responses by default. This means that it tries to send all 1.3gb over the wire in one response. At a certain point, IIS throws in the towel. Unfortunately the API abstracts away web service configuration so I can't seem to find a way to enable response chunking. </p>
<ol>
<li>Does anyone know of anyway to reduce/optimize the PDF export phase and or the size of the PDF without lowering the total page count?</li>
<li>Is there a way to turn on response chunking for SSRS?</li>
<li>Does anyone else have any other theories as to why this runs on the server but not through the API?</li>
</ol>
<p>EDIT: After reading kcrumley's post I began to take a look at the average page size by taking file size / page count. Interestingly enough on smaller reports the math works out so that each page is roughly 5K. Interestingly, when the report gets larger this "average" increases. An 8000 page report for example is averaging over 40K/page. Very odd. I will also add that the number of records per page is set except for the last page in each grouping, so it's not a case where some pages have more records than another. </p>
| <blockquote>
<ol>
<li>Does anyone know of anyway to
reduce/optimize the PDF export phase
and or the size of the PDF without
lowering the total page count?</li>
</ol>
</blockquote>
<p>I have a few ideas and questions:<br />
1. Is this a graphics-heavy report? If not, do you have tables that start out as text but are converted into a graphic by the SSRS PDF renderer (check if you can select the text in the PDF)? 41K per page might be more than it should be, or it might not, depending on how information-dense your report is. But we've had cases where we had minor issues with a report's layout, like having a table bleed into the page's margins, that resulted in the SSRS PDF renderer "throwing up its hands" and rendering the table as an image instead of as text. Obviously, the fewer graphics in your report, the smaller your file size will be.<br />
2. Is there a way that you could easily break the report into pieces? E.g., if it's a 10-location report, where Location 1 is followed by Location 2, etc., on your final report, could you run the Location 1 portion independent of the Location 2 portion, etc.? If so, you could join the 10 sub-reports into one final PDF using <a href="http://pdfsharp.com/" rel="nofollow">PDFSharp</a> after you've received them all. This leads to some difficulties with page numbering, but nothing insurmountable.</p>
<blockquote>
<p>3. Does anyone else have any other
theories as to why this runs on the
server but not through the API?</p>
</blockquote>
<p>My guess would be the sheer size of the report. I don't remember everything about what's an IIS setting and what's SSRS-specific, but there might be some overall IIS settings (maybe in Metabase.xml) that you would have to be updated to even allow that much data to pass through. </p>
<p>You could isolate the question of whether the time is the problem by taking one of your working reports and building in a long wait time in your stored procedures with WAITFOR (assuming SQL Server for your DBMS).</p>
<p>Not solutions, per se, but ideas. Hope it helps.</p>
|
Best practices for managing and deploying large JavaScript apps <p>What are some standard practices for managing a medium-large JavaScript application? My concerns are both speed for browser download and ease and maintainability of development.</p>
<p>Our JavaScript code is roughly "namespaced" as:</p>
<pre><code>var Client = {
var1: '',
var2: '',
accounts: {
/* 100's of functions and variables */
},
orders: {
/* 100's of functions and variables and subsections */
}
/* etc, etc for a couple hundred kb */
}
</code></pre>
<p>At the moment, we have one (unpacked, unstripped, highly readable) JavaScript file to handle all the business logic on the web application. In addition, there is jQuery and several jQuery extensions. The problem we face is that it takes <em>forever</em> to find anything in the JavaScript code and the browser still has a dozen files to download.</p>
<p>Is it common to have a handful of "source" JavaScript files that gets "compiled" into one final, compressed JavaScript file? Any other handy hints or best practices?</p>
| <p>The approach that I've found works for me is having seperate JS files for each class (just as you would in Java, C# and others). Alternatively you can group your JS into application functional areas if that's easier for you to navigate.</p>
<p>If you put all your JS files into one directory, you can have your server-side environment (PHP for instance) loop through each file in that directory and output a <code><script src='/path/to/js/$file.js' type='text/javascript'></code> in some header file that is included by all your UI pages. You'll find this auto-loading especially handy if you're regularly creating and removing JS files.</p>
<p>When deploying to production, you should have a script that combines them all into one JS file and "minifies" it to keep the size down.</p>
|
How do I get rid of Home in ASP.Net MVC? <p>I know this site is written using ASP.Net MVC and I do not see "/Home" in the url. This proves to me that it can be done. What special route and do I need?</p>
| <p>Just change "Home" to an empty string.</p>
<pre><code>routes.MapRoute(
"Home",
"",
new { action = Index, controller = Home }
);
</code></pre>
|
How do you begin designing a large system? <p>It's been mentioned to me that I'll be the sole developer behind a large new system. Among other things I'll be designing a UI and database schema.</p>
<p>I'm sure I'll receive some guidance, but I'd like to be able to knock their socks off. What can I do in the meantime to prepare, and what will I need to keep in mind when I sit down at my computer with the spec?</p>
<p>A few things to keep in mind: I'm a college student at my first real programming job. I'll be using Java. We already have SCM set up with automated testing, etc...so tools are not an issue.</p>
| <p>Do you know much about OOP? If so, look into Spring and Hibernate to keep your implementation clean and <a href="http://codebetter.com/blogs/jeremy.miller/archive/2007/01/08/Orthogonal-Code.aspx">orthogonal</a>. If you get that, you should find TDD a good way to keep your design compact and lean, especially since you have "automated testing" up and running.</p>
<p>UPDATE:
Looking at the first slew of answers, I couldn't disagree more. Particularly in the Java space, you should find plenty of mentors/resources on working out your application with Objects, <strong>not a database-centric approach</strong>. Database design is typically the first step for Microsoft folks (which I do daily, but am in a recovery program, er, Alt.Net). If you keep the focus on what you need to deliver to a customer and let your ORM figure out how to persist your objects, your design should be better.</p>
|
Runtime Configuration in .Net (specifically the EntLib) <p>I'm looking for a way to configure a DB connection at runtime; specifically using the Enterprise Library. I see that there's a *.Data.Configuration (or something close to this ... don't recall off the top of my head) assembly but am finding not much on the interwebs. Complicating matters is the fact that the API help is broken on Vista.</p>
<p>Now, I found this work-around:</p>
<pre><code>Configuration cfg = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
ConnectionStringSettings connection = new ConnectionStringSettings();
connection.Name = "Runtime Connection";
connection.ProviderName = "System.Data.OleDb";
connection.ConnectionString = "myconstring";
cfg.ConnectionStrings.ConnectionStrings.Add(connection);
cfg.Save(ConfigurationSaveMode.Modified);
ConfigurationManager.RefreshSection("connectionStrings");
var runtimeCon = DatabaseFactory.CreateDatabase("Runtime Connection");
</code></pre>
<p>And although it gives me what I want, it permanently edits the App.config. Sure I can go back and delete the changes, but I'd rather not go through this hassle.</p>
| <p>If you're using a winforms app you could try using <a href="http://msdn.microsoft.com/en-us/library/aa221771(office.11).aspx" rel="nofollow">UserProperties</a> to store this info. Another possible solution could be <a href="http://msdn.microsoft.com/en-us/library/2tw134k3.aspx" rel="nofollow">custom configuration sections</a>.</p>
|
Read from .msg files <p>I need to read from Outlook .MSG file in .NET <em>without</em> using COM API for Outlook (cos it will not be installed on the machines that my app will run). Are there any free 3rd party libraries to do that? I want to extract From, To, CC and BCC fields. Sent/Receive date fields would be good if they are also stored in MSG files.</p>
| <p><strong>Update:</strong> I have found a 3rd party COM library called <a href="http://www.dimastr.com/redemption/">Outlook Redemption</a> which is working fine for me at the moment. If you use it via COM-Interop in .NET, don't forget to release every COM object after you are done with it, otherwise your application crashes randomly.</p>
|
Entity diagrams in ASP.NET MVC <p>What's the best way/tool to display nice diagrams with entity relationships in ASP MVC views? <br />
i.e. servers and and applications, or servers with other servers.</p>
<p>Are there any third party tools out there that can do this? <br />
I've been searching around things like Telerik, but it's really hard to google for this!</p>
| <p>Here are some 3rd-party diagramming tools:</p>
<ul>
<li><a href="http://www.nevron.com/Products.DiagramFor.NET.Overview.aspx" rel="nofollow">http://www.nevron.com/Products.DiagramFor.NET.Overview.aspx</a></li>
<li><a href="http://www.nwoods.com/GO/dotnet.htm" rel="nofollow">http://www.nwoods.com/GO/dotnet.htm</a></li>
<li><a href="http://www.syncfusion.com/products/diagram/web/default.aspx" rel="nofollow">http://www.syncfusion.com/products/diagram/web/default.aspx</a></li>
</ul>
|
How do I convert a string to an enum in C#? <p>What's the best way to convert a string to an enumeration value in C#?</p>
<p>I have an HTML select tag containing the values of an enumeration. When the page is posted, I want to pick up the value (which will be in the form of a string) and convert it to the enumeration value.</p>
<p>In an ideal world, I could do something like this:</p>
<pre><code>StatusEnum MyStatus = StatusEnum.Parse("Active");
</code></pre>
<p>but that isn't valid code.</p>
| <p>It's rather ugly:</p>
<pre><code>StatusEnum MyStatus = (StatusEnum) Enum.Parse(typeof(StatusEnum), "Active", true);
</code></pre>
<p>I tend to simplify this with:</p>
<pre><code>public static T ParseEnum<T>(string value)
{
return (T) Enum.Parse(typeof(T), value, true);
}
</code></pre>
<p>Then I can do:</p>
<pre><code>StatusEnum MyStatus = EnumUtil.ParseEnum<StatusEnum>("Active");
</code></pre>
<p>One option suggested in the comments is to add an extension, which is simple enough:</p>
<pre><code>public static T ToEnum<T>(this string value)
{
return (T) Enum.Parse(typeof(T), value, true);
}
StatusEnum MyStatus = "Active".ToEnum<StatusEnum>();
</code></pre>
<p>Finally, you may want to have a default enum to use if the string cannot be parsed:</p>
<pre><code>public static T ToEnum<T>(this string value, T defaultValue)
{
if (string.IsNullOrEmpty(value))
{
return defaultValue;
}
T result;
return Enum.TryParse<T>(value, true, out result) ? result : defaultValue;
}
</code></pre>
<p>Which makes this the call:</p>
<pre><code>StatusEnum MyStatus = "Active".ToEnum(StatusEnum.None);
</code></pre>
<p>However, I would be careful adding an extension method like this to <code>string</code> as (without namespace control) it will appear on all instances of <code>string</code> whether they hold an enum or not (so <code>1234.ToString().ToEnum(StatusEnum.None)</code> would be valid but nonsensical) . It's often be best to avoid cluttering Microsoft's core classes with extra methods that only apply in very specific contexts unless your entire development team has a very good understanding of what those extensions do. </p>
|
C# Auto Clearing Winform Textbox <p>I have a user that want to be able to select a textbox and have the current text selected so that he doesn't have to highlight it all in order to change the contents. </p>
<p>The contents need to be handle when enter is pushed. That part I think I have figured out but any suggestions would be welcome. </p>
<p>The part I need help with is that once enter has been pushed, any entry into the textbox should clear the contents again.</p>
<p><strong>Edit:</strong> The textbox controls an piece of RF hardware. What the user wants to be able to do is enter a setting and press enter. The setting is sent to the hardware. Without doing anything else the user wants to be able to type in a new setting and press enter again.</p>
| <p>Hook into the KeyPress event on the TextBox, and when it encounters the Enter key, run your hardware setting code, and then highlight the full text of the textbox again (see below) - Windows will take care of clearing the text with the next keystroke for you.</p>
<pre><code>TextBox1.Select(0, TextBox1.Text.Length);
</code></pre>
|
What's the best way to get started with OSGI? <p>What makes a module/service/bit of application functionality a particularly good candidate for an OSGi module? </p>
<p>I'm interested in using <a href="http://en.wikipedia.org/wiki/OSGi">OSGi</a> in my applications. We're a Java shop and we use Spring pretty extensively, so I'm leaning toward using <a href="http://www.springframework.org/osgi">Spring Dynamic Modules for OSGi(tm) Service Platforms</a>. I'm looking for a good way to incorporate a little bit of OSGi into an application as a trial. Has anyone here used this or a similar OSGi technology? Are there any pitfalls? </p>
<p>@Nicolas - Thanks, I've seen that one. It's a good tutorial, but I'm looking more for ideas on how to do my first "real" OSGi bundle, as opposed to a Hello World example.</p>
<p>@david - Thanks for the link! Ideally, with a greenfield app, I'd design the whole thing to be dynamic. What I'm looking for right now, though, is to introduce it in a small piece of an existing application. Assuming I can pick any piece of the app, what are some factors to consider that would make that piece better or worse as an OSGi guinea pig?</p>
| <p>Well, since you can not have one part OSGi and one part non-OSGi you'll need to make your entire app OSGi. In its simplest form you make a single OSGi bundle out of your entire application. Clearly this is not a best practice but it can be useful to get a feel for deploying a bundle in an OSGi container (Equinox, Felix, Knoplerfish, etc).</p>
<p>To take it to the next level you'll want to start splitting your app into components, components should typically have a set of responsibilities that can be isolated from the rest of your application through a set of interfaces and class dependencies. Identifying these purely by hand can range from rather straightforward for a well designed highly cohesive but loosely coupled application to a nightmare for interlocked source code that you are not familiar with.</p>
<p>Some help can come from tools like <a href="http://clarkware.com/software/JDepend.html">JDepend</a> which can show you the coupling of Java packages against other packages/classes in your system. A package with low efferent coupling should be easier to extract into an OSGi bundle than one with high efferent coupling. Even more architectural insight can be had with pro tools like <a href="http://www.headwaysoftware.com/products/structure101/index.php">Structure 101</a>.</p>
<p>Purely on a technical level, working daily with an application that consists of 160 OSGi bundles and using Spring DM I can confirm that the transition from "normal" Spring to Spring DM is largely pain free. The extra namespace and the fact that you can (and should) isolate your OSGi specific Spring configuration in separate files makes it even easier to have both with and without OSGi deployment scenarios.</p>
<p>OSGi is a deep and wide component model, documentation I recommend:</p>
<ul>
<li><a href="http://www.osgi.org/Release4/Download">OSGi R4 Specification</a>: Get the PDFs of the Core and Compendium specification, they are canonical, authoritative and very readable. Have a shortcut to them handy at all times, you will consult them.</li>
<li>Read up on OSGi best practices, there is a large set of things you <strong>can</strong> do but a somewhat smaller set of things you <strong>should</strong> do and there are some things you should <strong>never do</strong> (DynamicImport: * for example). </li>
</ul>
<p>Some links: </p>
<ul>
<li><a href="http://felix.apache.org/site/presentations.data/best-practices-apachecon-20060628.pdf">OSGi best practices and using Apache Felix</a></li>
<li><a href="http://www.osgi.org/wiki/uploads/CommunityEvent2007/OSGiBestPractices.pdf">Peter Kriens and BJ Hargrave in a Sun presentation on OSGi best practices</a> </li>
<li>one key OSGi concept are Services, learn why and how they supplant the Listener pattern with the <a href="http://www.osgi.org/wiki/uploads/Links/whiteboard.pdf">Whiteboard pattern</a></li>
<li><strike><a href="http://groups.google.com/group/spring-osgi">The Spring DM Google Group</a> is very responsive and friendly in my experience</strike><br>
<a href="http://groups.google.com/group/spring-osgi">The Spring DM Google Group</a> is <a href="https://groups.google.com/forum/#!topic/spring-osgi/e-3gVCgl-_M">no longer active</a> and has moved to Eclipse.org as the Gemini Blueprint project which has a forum <a href="http://www.eclipse.org/forums/index.php?t=thread&frm_id=153">here</a>.</li>
</ul>
|
Should DB layer members be static or instance? <p>I've seen projects where the classes in the DB layer have just static functions in them and other projects where those classes need to be instantiated to get access to the member functions. </p>
<p>Which is "better" and why?</p>
| <p>I like a single object to be correlated to a single record in the database, i.e. an object must be instantiated. This is your basic <a href="http://martinfowler.com/eaaCatalog/activeRecord.html" rel="nofollow">ActiveRecord</a> pattern. In my experience, the one-object-to-one-row approach creates a much more fluid and literate presentation in code. Also, I like to treat objects as records and the class as the table. For example to change the name of a record I do:</p>
<pre><code>objPerson = new Person(id)
objPerson.name = "George"
objPerson.save()
</code></pre>
<p>while to get all people who live in Louisiana I might do</p>
<pre><code>aryPeople = Person::getPeopleFromState("LA")
</code></pre>
<p>There are plenty of criticisms of Active Record. You can especially run into problems where you are querying the database for each record or your classes are tightly coupled to your database, creating inflexibility in both. In that case you can move up a level and go with something like <a href="http://martinfowler.com/eaaCatalog/dataMapper.html" rel="nofollow">DataMapper</a>. </p>
<p>Many of the modern frameworks and <a href="http://en.wikipedia.org/wiki/Object-relational_mapping" rel="nofollow">ORM's</a> are aware of some of these drawbacks and provide solutions for them. Do a little research and you will start to see that this is a problem that has a number of solutions and it all depend on your needs. </p>
|
How do I handle page flow in MVC (particularly asp.net) <p>If you had to provide a wizard like form entry experience in mvc how would you abstract the page flow?</p>
| <p>Investigate the post-redirect-get pattern.</p>
<p><a href="http://weblogs.asp.net/mhawley/archive/tags/MVC/default.aspx" rel="nofollow">http://weblogs.asp.net/mhawley/archive/tags/MVC/default.aspx</a><br />
<a href="http://devlicio.us/blogs/tim_barcz/archive/2008/08/22/prg-pattern-in-the-asp-net-mvc-framework.aspx" rel="nofollow">http://devlicio.us/blogs/tim_barcz/archive/2008/08/22/prg-pattern-in-the-asp-net-mvc-framework.aspx</a></p>
<p>Use that along with a robust domain model (for tracking steps or form completion state or whatever you call it) and you're golden.</p>
|
How do I generate a hashcode from a byte array in C#? <p>Say I have an object that stores a byte array and I want to be able to efficiently generate a hashcode for it. I've used the cryptographic hash functions for this in the past because they are easy to implement, but they are doing a lot more work than they should to be cryptographically oneway, and I don't care about that (I'm just using the hashcode as a key into a hashtable).</p>
<p>Here's what I have today:</p>
<pre><code>struct SomeData : IEquatable<SomeData>
{
private readonly byte[] data;
public SomeData(byte[] data)
{
if (null == data || data.Length <= 0)
{
throw new ArgumentException("data");
}
this.data = new byte[data.Length];
Array.Copy(data, this.data, data.Length);
}
public override bool Equals(object obj)
{
return obj is SomeData && Equals((SomeData)obj);
}
public bool Equals(SomeData other)
{
if (other.data.Length != data.Length)
{
return false;
}
for (int i = 0; i < data.Length; ++i)
{
if (data[i] != other.data[i])
{
return false;
}
}
return true;
}
public override int GetHashCode()
{
return BitConverter.ToInt32(new MD5CryptoServiceProvider().ComputeHash(data), 0);
}
}
</code></pre>
<p>Any thoughts?</p>
<hr>
<p>dp: You are right that I missed a check in Equals, I have updated it. Using the existing hashcode from the byte array will result in reference equality (or at least that same concept translated to hashcodes).
for example:</p>
<pre><code>byte[] b1 = new byte[] { 1 };
byte[] b2 = new byte[] { 1 };
int h1 = b1.GetHashCode();
int h2 = b2.GetHashCode();
</code></pre>
<p>With that code, despite the two byte arrays having the same values within them, they are referring to different parts of memory and will result in (probably) different hash codes. I need the hash codes for two byte arrays with the same contents to be equal.</p>
| <p>The hash code of an object shouldn't be unique. </p>
<p>The checking rule is: </p>
<ul>
<li>Are the hash codes equal? Then call the full (slow) <code>Equals</code> method.</li>
<li>Are the hash codes not equal? Then the two items are definitely not equal.</li>
</ul>
<p>All you want is a <code>GetHashCode</code> algorithm that splits up your collection into roughly even groups - it shouldn't form the key as the <code>HashTable</code> or <code>Dictionary<></code> will need to use the hash to optimise retrieval.</p>
<p>How long do you expect the data to be? How random? If lengths vary greatly (say for files) then just return the length. If lengths are likely to be similar look at a subset of the bytes that varies.</p>
<p><code>GetHashCode</code> should be a lot quicker than <code>Equals</code>, but doesn't need to be unique.</p>
<p>Two identical things <em>must never</em> have different hash codes. Two different objects <em>should not</em> have the same hash code, but some collisions are to be expected (after all, there are more permutations than possible 32 bit integers).</p>
|
Removing N items from a list conditionally <p>I was writing some <strong>ASP.NET</strong> control when I came to the scenario where I needed to remove items from a list, only when they matched a certain condition.</p>
<p>The <code>RemoveAll</code> method of the generic <code>List</code> class does a good job, but removes <em>all</em> items that match the condition, specified by the predicate.</p>
<p>What if I want to only remove a certain number of items specifying the condition? What do you think is the best way to do this?</p>
| <p>If you want to specify both a limit for number of items to remove and a condition to select the items to remove, you can use this approach:</p>
<pre><code>int limit = 30; // Suppose you want to remove 30 items at most
list.RemoveAll(item => ShouldIRemoveThis(item) && limit-- > 0);
</code></pre>
|
Best .NET build tool <blockquote>
<p><strong>Possible Duplicate:</strong><br>
<a href="http://stackoverflow.com/questions/476163">NAnt or MSBuild, which one to choose and when?</a> </p>
</blockquote>
<p>What is the best build tool for <a href="http://en.wikipedia.org/wiki/.NET_Framework">.NET</a>?</p>
<p>I currently use <a href="http://en.wikipedia.org/wiki/NAnt">NAnt</a> but only because I have experience with <a href="http://en.wikipedia.org/wiki/Apache_Ant">Ant</a>. Is <a href="http://en.wikipedia.org/wiki/MSBuild">MSBuild</a> preferred?</p>
| <p>We actually use a combination of <a href="http://en.wikipedia.org/wiki/NAnt">NAnt</a> and <a href="http://en.wikipedia.org/wiki/MSBuild">MSBuild</a> with <a href="http://en.wikipedia.org/wiki/CruiseControl">CruiseControl</a>. NAnt is used for script flow control and calls MSBuild to compile projects. After the physical build is triggered, NAnt is used to publish the individual project build outputs to a shared location.</p>
<p>I am not sure this is <i>the best</i> process. I think many of us are still looking for a great build tool. One promising thing I heard recently on .NET Rocks, <a href="http://www.dotnetrocks.com/default.aspx?showNum=362">episode 362</a>, is <a href="http://codebetter.com/blogs/james.kovacs/archive/2008/06/27/introducing-psake.aspx">James Kovac's PSake</a>, a build system he based entirely on PowerShell. It sounds really promising since what you can do with PowerShell is fairly limitless in theory.</p>
|
How do you deal with transport-level errors in SqlConnection? <p>Every now and then in a high volume .NET application, you might see this exception when you try to execute a query:</p>
<blockquote>
<p>System.Data.SqlClient.SqlException: A transport-level error has
occurred when sending the request to the server.</p>
</blockquote>
<p>According to my research, this is something that "just happens" and not much can be done to prevent it. It does not happen as a result of a bad query, and generally cannot be duplicated. It just crops up maybe once every few days in a busy OLTP system when the TCP connection to the database goes bad for some reason.</p>
<p>I am forced to detect this error by parsing the exception message, and then retrying the entire operation from scratch, to include using a new connection. None of that is pretty.</p>
<p>Anybody have any alternate solutions?</p>
| <p>I posted <a href="http://stackoverflow.com/questions/154897/what-do-you-do-if-you-cannot-resolve-a-bug#155077">an answer on another question</a> on another topic that might have some use here. That answer involved SMB connections, not SQL. However it was identical in that it involved a low-level transport error.</p>
<p>What we found was that in a heavy load situation, it was fairly easy for the remote server to time out connections <em>at the TCP layer</em> simply because the server was busy. Part of the reason was the defaults for how many times TCP will retransmit data on Windows weren't appropriate for our situation.</p>
<p>Take a look at the <a href="http://support.microsoft.com/kb/314053">registry settings for tuning TCP/IP</a> on Windows. In particular you want to look at <strong>TcpMaxDataRetransmissions</strong> and maybe <strong>TcpMaxConnectRetransmissions</strong>. These default to 5 and 2 respectively, try upping them a little bit on the client system and duplicate the load situation.</p>
<p>Don't go crazy! TCP doubles the timeout with each successive retransmission, so the timeout behavior for bad connections can go exponential on you if you increase these too much. As I recall upping <strong>TcpMaxDataRetransmissions</strong> to 6 or 7 solved our problem in the vast majority of cases.</p>
|
Internationalization in SSRS <p>What's the best way to handle translations for stock text in a <code>SSRS</code>. For instance - if I have a report that shows a grid of contents what's the best way to have the correct translation for the header of that grid show up, assuming the culture of the report is set correctly.</p>
<p>Put another way - is it possible to do resources in a <code>SSRS</code> report, or am I stuck with storing all that text in the database and querying for it?</p>
| <p>AS far as I know, there is no way to localize a report (meaning automating the translation of string litterals)...</p>
<p>Like you said,you basically have to use the User!Language global variable to catch the user's settings and then use that to retrieve the appropriate strings from the DB...</p>
<p>However, you can adapt the display of currency/numeric/date fields according to the user locale. Also possible is changing the interface of the Report Viewer to match your user's langage.</p>
<p>Here are a few links giving tips on how to adapt the locale:</p>
<p><a href="http://www.ssw.com.au/Ssw/Standards/Rules/RulesToBetterSQLReportingServices.aspx#LanguageSetting">http://www.ssw.com.au/Ssw/Standards/Rules/RulesToBetterSQLReportingServices.aspx#LanguageSetting</a></p>
<p>Langage pack for Report Viewer:</p>
<p><a href="http://www.microsoft.com/downloads/details.aspx?displaylang=en&FamilyID=e3d3071b-d919-4ff9-9696-c11d312a36a0">http://www.microsoft.com/downloads/details.aspx?displaylang=en&FamilyID=e3d3071b-d919-4ff9-9696-c11d312a36a0</a></p>
|
Haskell's algebraic data types <p>I'm trying to fully understand all of Haskell's concepts.</p>
<p>In what ways are algebraic data types similar to generic types, e.g., in C# and Java? And how are they different? What's so algebraic about them anyway? </p>
<p>I'm familiar with universal algebra and its rings and fields, but I only have a vague idea of how Haskell's types work.</p>
| <p>Haskell's <em>algebraic data types</em> are named such since they correspond to an <em>initial algebra</em> in category theory, giving us some laws, some operations and some symbols to manipulate. We may even use algebraic notation for describing regular data structures, where:</p>
<ul>
<li><code>+</code> represents sum types (disjoint unions, e.g. <code>Either</code>).</li>
<li><code>â¢</code> represents product types (e.g. structs or tuples)</li>
<li><code>X</code> for the singleton type (e.g. <code>data X a = X a</code>)</li>
<li><code>1</code> for the unit type <code>()</code></li>
<li>and <em><code>μ</code></em> for the least fixed point (e.g. recursive types), usually implicit.</li>
</ul>
<p>with some additional notation:</p>
<ul>
<li><code>X²</code> for <code>Xâ¢X</code></li>
</ul>
<p>In fact, you might say (following Brent Yorgey) that a Haskell data type is regular if it can be expressed in terms of <code>1</code>, <code>X</code>, <code>+</code>, <code>â¢</code>, and a least ï¬xed point.</p>
<p>With this notation, we can concisely describe many regular data structures:</p>
<ul>
<li><p>Units: <code>data () = ()</code></p>
<p><code>1</code></p></li>
<li><p>Options: <code>data Maybe a = Nothing | Just a</code></p>
<p><code>1 + X</code></p></li>
<li><p>Lists: <code>data [a] = [] | a : [a]</code></p>
<p><code>L = 1+Xâ¢L</code></p></li>
<li><p>Binary trees: <code>data BTree a = Empty | Node a (BTree a) (BTree a)</code></p>
<p><code>B = 1 + Xâ¢B²</code></p></li>
</ul>
<p>Other operations hold (taken from Brent Yorgey's paper, listed in the references):</p>
<ul>
<li><p>Expansion: unfolding the fix point can be helpful for thinking about lists. <code>L = 1 + X + X² + X³ + ...</code> (that is, lists are either empty, or they have one element, or two elements, or three, or ...)</p></li>
<li><p>Composition, <code>â¦</code>, given types <code>F</code> and <code>G</code>, the composition <code>F ⦠G</code> is a type which builds âF-structures made out of G-structuresâ (e.g. <code>R = X ⢠(L ⦠R)</code> ,where <code>L</code> is lists, is a rose tree.</p></li>
<li><p>Differentiation, the derivative of a data type D (given as D') is the type of D-structures with a single âholeâ, that is, a distinguished location not containing any data. That amazingly satisfy the same rules as for differentiation in calculus:</p>
<p><code>1â² = 0</code></p>
<p><code>Xâ² = 1</code></p>
<p><code>(F + G)â² = F' + Gâ²</code></p>
<p><code>(F ⢠G)Ⲡ= F ⢠GⲠ+ FⲠ⢠G</code></p>
<p><code>(F ⦠G)â² = (FⲠ⦠G) ⢠Gâ²</code></p></li>
</ul>
<hr>
<p><em>References:</em></p>
<ul>
<li><a href="http://www.cis.upenn.edu/~byorgey/papers/species-pearl.pdf">Species and Functors and Types</a>, Oh My!, Brent A. Yorgey, Haskellâ10, September 30, 2010, Baltimore, Maryland, USA</li>
<li><a href="http://personal.cis.strath.ac.uk/~conor/Dissect.pdf">Clowns to the left of me, jokers to the right (Dissecting Data Structures)</a>, Conor McBride POPL 2008</li>
</ul>
|
Getting Started with Unit Testing <blockquote>
<p>Unit testing is, roughly speaking, testing bits of your code in isolation with test code. The immediate advantages that come to mind are:</p>
<ul>
<li>Running the tests becomes automate-able and repeatable</li>
<li>You can test at a much more granular level than point-and-click testing via a GUI</li>
</ul>
<p><a href="http://stackoverflow.com/questions/1383/what-is-unit-testing">Rytmis</a></p>
</blockquote>
<p>My question is, what are the current "best practices" in terms of tools as well as when and where to use unit testing as part of your daily coding?</p>
<p>Lets try to be somewhat language agnostic and cover all the bases.</p>
| <p>Ok here's some best practices from some one who doesn't unit test as much as he should...cough.</p>
<ol>
<li>Make sure your tests test <a href="http://www.artima.com/weblogs/viewpost.jsp?thread=35578" rel="nofollow" title="one">one</a>
thing and one thing only.</li>
<li>Write unit tests as you go. Preferably <a href="http://en.wikipedia.org/wiki/Test-driven_development" rel="nofollow" title="before">before</a> you write the code you are testing against.</li>
<li>Do not unit test the GUI. </li>
<li><a href="http://en.wikipedia.org/wiki/Separation_of_concerns" rel="nofollow" title="Separate your concerns">Separate your concerns</a>. </li>
<li>Minimise the dependencies of your tests.</li>
<li>Mock behviour with <a href="http://en.wikipedia.org/wiki/Mock_object" rel="nofollow" title="mocks">mocks</a>.</li>
</ol>
|
VS 2008 - Detachable code tabs <p>Admittedly this might not be a problem on larger screens, but my employer is abit tight and refuses to buy monitors larger than 19inch, this means that I dont have much screen real estate to view all the Visual Studio windows and my code at the same time, or two pieces of code at once. Is there anything that allows me to detach the code panels so that I can view two different classes at once on each of my screens? </p>
| <p>You can right click on the tab strip and insert a new vertical (or horizontal) tab group.</p>
<p>This allows you to view multiple tabs at the same time.</p>
|
Recommended notes/doc service that offers an API? <p>I'm looking for a good online service for notes/documents (think Google Docs) that has a decent web UI and offers an API for clients to read/write the stored data.</p>
<p>Google Docs is almost perfect - except there's no way to update the contents of existing documents.</p>
| <p>None of the APIs for the more 'Word' like online editors seem to have any 'edit' functionality, just download and upload. This is obviously due to the complexity of the documents being stored.</p>
<p>With Google Docs API you can get a document, edit it, and then re-upload it (you may need to delete the previous version as well I think). Zoho seems to provide an 'update' method which combines the two operations.</p>
<p>Have you looked at the Google Notebook API instead? This might provide more granular access to the data in the 'note' due to its structured approach to storing the data.</p>
|
What is the best way to partition terabyte drive in a linux development machine? <p>I have a new 1 TB drive coming in tomorrow. What is the best way to divide this space for a development workstation?</p>
<p>The biggest problem I think I'm going to have is that some partitions (probably /usr) will become to small after a bit of use. Other partitions are probably to huge. The swap drive for example is currently 2GB (2x 1GB RAM), but it is almost never used (only once that I know of).</p>
| <p>If you partition your drive using <a href="http://en.wikipedia.org/wiki/Logical_Volume_Manager_(Linux)">LVM</a> you won't have to worry about any individual partition running out of space in the future. Just move space around as necessary.</p>
|
How do you spawn another process in C? <p>How do you run an external program and pass it command line parameters using C? If you have to use operating system API, include a solution for Windows, Mac, and Linux.</p>
| <p>If you want to perform more complicated operations, like reading the output of the external program, you may be better served by the <a href="http://man.he.net/man3/popen">popen</a> system call. For example, to programmatically access a directory listing (this is a somewhat silly example, but useful <em>as</em> an example), you could write something like this:</p>
<pre><code>#include <stdio.h>
int main()
{
int entry = 1;
char line[200];
FILE* output = popen("/usr/bin/ls -1 /usr/man", "r");
while ( fgets(line, 199, output) )
{
printf("%5d: %s", entry++, line);
}
}
</code></pre>
<p>to give output like this</p>
<pre><code>1: cat1
2: cat1b
3: cat1c
4: cat1f
5: cat1m
6: cat1s
...
</code></pre>
|
When to use IList and when to use List <p>I know that IList is the interface and List is the concrete type but I still don't know when to use each one. What I'm doing now is if I don't need the Sort or FindAll methods I use the interface. Am I right? Is there a better way to decide when to use the interface or the concrete type?</p>
| <p>There are two rules I follow:</p>
<ul>
<li>Accept the most basic type that will work</li>
<li>Return the richest type your user will need</li>
</ul>
<p>So when writing a function or method that takes a collection, write it not to take a List, but an IList<T>, an ICollection<T>, or IEnumerable<T>. The generic interfaces will still work even for heterogenous lists because System.Object can be a T too. Doing this will save you headache if you decide to use a Stack or some other data structure further down the road. If all you need to do in the function is foreach through it, IEnumerable<T> is really all you should be asking for.</p>
<p>On the other hand, when returning an object out of a function, you want to give the user the richest possible set of operations without them having to cast around. So in that case, if it's a List<T> internally, return a copy as a List<T>.</p>
|
Create an encrypted ZIP file in Python <p>I'm creating an ZIP file with ZipFile in Python 2.5, it works ok so far:</p>
<pre><code>import zipfile, os
locfile = "test.txt"
loczip = os.path.splitext (locfile)[0] + ".zip"
zip = zipfile.ZipFile (loczip, "w")
zip.write (locfile)
zip.close()
</code></pre>
<p>but I couldn't find how to encrypt the files in the ZIP file.
I could use system and call PKZIP -s, but I suppose there must be a more "Pythonic" way. I'm looking for an open source solution.</p>
| <p>I created a simple library to create a password encrypted zip file in python. - <a href="https://github.com/smihica/pyminizip"><strong>here</strong></a></p>
<pre><code>import pyminizip
compression_level = 5 # 1-9
pyminizip.compress("src.txt", "dst.zip", "password", compression_level)
</code></pre>
<p><strong>The library requires zlib.</strong></p>
<p>I have checked that the file can be extracted in WINDOWS/MAC.</p>
|
What areas of specialization within programming would you recommend to a beginner <p>I am a student studying software development, and I feel programming, in general, is too broad of a subject to try to know everything. To be proficient, you have to decide which areas to focus your learning and understanding. Certain skill sets synergize with each other, like data-driven web development and SQL experience. However, all the win32 API experience in the world may not directly apply to linux development. This leads me to believe, as a beginning programmer, I should start deciding where I want to specialize after I have general understanding of the basic principles of software development. </p>
<p>This is a multi-part question really: </p>
<ol>
<li>What are the common specializations within computer programming and software development? </li>
<li>Which of these specializations have more long-term value, both as a foundation for other specializations and/or as marketable skills? </li>
<li>Which skill sets complement each other? </li>
<li>Are there any areas of specialization that hinder your ability of developing other areas of specialization.</li>
</ol>
| <p>Ben, Almost all seasoned programmers are still students in programming. You never stops learning anything when you are a developer. But if you are really starting off on your career then you should be least worried about the specialization thing. All APIs, frameworks and skills that you expect that gives you a long term existence in the field is not going to happen. Technology seems changing a lot and you should be versatile and flexible enough to learn anything. The knowledge you acquire on one platform/api/framework doesn't die off. You can apply the skills to the next greatest platform/api/framework. </p>
<p>That being said you should just stop worrying about the future and concentrate on the basics. DataStructures, Algorithm Analysis and Design, Compiler Design, Operating system design are the bare minimum stuff you need. And further you should be willing to go back and read tho books in those field any time in your career. Thats all is required. Good luck. </p>
<p>Sorry if I sounded like a big ass advisor; but thats what I think. :-)</p>
|
Using GLEW to use OpenGL extensions under Windows <p>I've been using OpenGL extensions on Windows the <a href="http://stackoverflow.com/questions/14413/using-opengl-extensions-on-windows" rel="nofollow">painful way</a>. Is GLEW the easier way to go? How do I get started with it?</p>
| <p>Yes, the <strong>OpenGL Extension Wrangler Library</strong> (GLEW) is a painless way to use OpenGL extensions on Windows. Here's how to get started on it:</p>
<p>Identify the OpenGL extension and the extension APIs you wish to use. OpenGL extensions are listed in the <a href="http://www.opengl.org/registry/">OpenGL Extension Registry</a>.</p>
<p>Check if your graphic card supports the extensions you wish to use. Download and install the latest drivers and SDKs for your graphics card.</p>
<p>Recent versions of <a href="http://developer.nvidia.com/object/sdk_home.html">NVIDIA OpenGL SDK</a> ship with GLEW. If you're using this, then you don't need to do some of the following steps.</p>
<p>Download <a href="http://glew.sourceforge.net/">GLEW</a> and unzip it.</p>
<p>Add the GLEW <strong>bin</strong> path to your Windows <strong>PATH</strong> environment variable. Alternatively, you can also place the <strong>glew32.dll</strong> in a directory where Windows picks up its DLLs.</p>
<p>Add the GLEW <strong>include</strong> path to your compiler's include directory list.</p>
<p>Add the GLEW <strong>lib</strong> path to your compiler's library directory list.</p>
<p>Instruct your compiler to use <strong>glew32.lib</strong> during linking. If you're using Visual C++ compilers then one way to do this is by adding the following line to your code:</p>
<pre><code>#pragma comment(lib, "glew32.lib")
</code></pre>
<p>Add a <code>#include <GL/glew.h></code> line to your code. Ensure that this is placed above the includes of other GL header files. (You may actually not need the GL header files includes if you include <code>glew.h</code>.)</p>
<p>Initialize GLEW using <code>glewInit()</code> after you've initialized GLUT or GL. If it fails, then something is wrong with your setup.</p>
<pre><code>if (GLEW_OK != glewInit())
{
// GLEW failed!
exit(1);
}
</code></pre>
<p>Check if the extension(s) you wish to use are now available through GLEW. You do this by checking a boolean variable named <strong>GLEW<em>_your_extension_name</em></strong> which is exposed by GLEW.</p>
<blockquote>
<p>Example:</p>
</blockquote>
<pre><code>if (!GLEW_EXT_framebuffer_object)
{
exit(1);
}
</code></pre>
<p>That's it! You can now use the OpenGL extension calls in your code just as if they existed naturally for Windows.</p>
|
Language Conversion Testing <p>We created a tool which converts a language called P2, a language similar to assembly which I think exists only in Japan, to C#. There are at least a hundred modules written in P2 and we want to verify if the conversion to C# is right? How can we test this?</p>
| <p>You don't test the converter, you test the final code. </p>
<p>If the code doesn't compile, clearly your converter is failing. If the code compiles and your functionality tests fail, then you can tweak the code so that it passes the test. If you are fairly successful you should see that you only need to fix the modules that actually fail.</p>
<p>Goodluck!</p>
|
Why are DispatcherObject.CheckAccess() and VerifyAccess() hidden from Intellisense? <p>The <code>System.Windows.Threading.DispatcherObject</code> class (which <code>DependencyObject</code> is based on) contains a useful function, called <code>CheckAccess()</code>, that determines whether or not the code is running on the UI thread.</p>
<p>When I wanted to use it yesterday, I was puzzled to find out that Intellisense didn't show the function (nor <code>VerifyAccess()</code>, which throws an exception when not on the UI thread), even though the MSDN library lists it. I decided to investigate the class using Reflector. It seems that the function in question has an <code>EditorBrowsable(EditorBrowsableState.Never)</code> attribute attached to it. The <code>Dispatcher</code> class, which is used by <code>DispatcherObject</code>, has the same attribute attached to <code>CheckAccess()</code> and <code>VerifyAccess()</code>:</p>
<pre><code>public abstract class DispatcherObject
{
// ...
[EditorBrowsable(EditorBrowsableState.Never)]
public bool CheckAccess();
[EditorBrowsable(EditorBrowsableState.Never)]
public void VerifyAccess();
// ...
[EditorBrowsable(EditorBrowsableState.Advanced)]
public Dispatcher Dispatcher { get; }
}
public sealed class Dispatcher
{
// ...
[EditorBrowsable(EditorBrowsableState.Never)]
public bool CheckAccess();
[EditorBrowsable(EditorBrowsableState.Never)]
public void VerifyAccess();
// ...
}
</code></pre>
<p>I don't believe that the application of that attribute is random (or a joke), so my question is: why is it there? Should those methods not be called directly? Then why aren't they <code>protected</code> (or <code>internal</code>, like some of the most useful methods in the WPF)?</p>
| <p>A Microsoft employee <a href="http://social.msdn.microsoft.com/Forums/en-US/wpf/thread/bd0e6f6c-cadd-48f1-8e1a-163c2f17e4ca/">recently stated</a> CheckAccess is used only for "advanced scenarios", so they hid it from Intellisense.</p>
<blockquote>
<p>"CheckAccess and VerifyAccess have
always been marked to be not visible,
maybe IntelliSense wasn't respecting
it. You can use Reflector to confirm.
The idea here is that CheckAccess and
VerifyAccess are advances scenarios,
that normal developers don't need.</p>
<p>However, I do think that
EditorBrowsableState.Advanced would
have been a more appropriate level."</p>
</blockquote>
<p>There's a Microsoft Connect case for this shortcoming. <a href="https://connect.microsoft.com/VisualStudio/feedback/ViewFeedback.aspx?FeedbackID=367777">Vote for it</a> if it's important to you.</p>
|
Suitable alternative to CryptEncrypt <p>We have a situation in our product where for a long time some data has been stored in the application's database as SQL string (choice of MS SQL server or sybase SQL anywhere) which was encrypted via the Windows API function <a href="http://msdn.microsoft.com/en-us/library/aa379924.aspx" rel="nofollow">CryptEncrypt.</a> (direct and decryptable)</p>
<p>The problem is that CryptEncrypt can produce NULL's in the output, meaning that when it's stored in the database, the string manipulations will at some point truncate the ciphertext.</p>
<p>Ideally we'd like to use an algo that will produce cyphertext that doesn't contain NULLs as that will cause the least amount of change to the existing databases (changing a column from string to binary and code to deal with binary instead of strings) and just decrypt existing data and re-encrypt with the new algo at database upgrade time.</p>
<p>The algorithm doesn't need to be the most secure, as the database is already in a reasonably secure environment (not an open network / teh interwebs) but does need to bebetter than ROT13 (which I can almost decrypt in my head now!)</p>
<p>Cheers</p>
<p>edit: btw, any particular reason for changing ciphertext to cyphertext? ciphertext seems more widely used...</p>
| <p>Any semi-decent algorithm will end up with a strong chance of generating a NULL value somewhere in the resulting ciphertext.</p>
<p>Why not do something like <a href="http://en.wikipedia.org/wiki/Base64" rel="nofollow">base-64 encode</a> your resulting binary blob before persisting to the DB? (<a href="http://synesis.com.au/software/b64.html" rel="nofollow">sample implementation in C++</a>).</p>
|
Tracking Useful Information <p>What do the clever programmers here do to keep track of handy programming tricks and useful information they pick up over their many years of experience? Things like useful compiler arguments, IDE short-cuts, clever code snippets, etc.</p>
<p>I sometimes find myself frustrated when looking up something that I used to know a year or two ago. My IE favourites probably represent a good chunk of the Internet in the late 1990s, so clearly that isn't effective (at least for me). Or am I just getting old?</p>
<p>So.. what do you do?</p>
| <p>Two Things I do:</p>
<ul>
<li>I blog about it - this allows me to go back and search my own blog.</li>
<li>We use the code snippet feature in Visual Studio.</li>
</ul>
<p>Cheers.</p>
|
How can I learn about parser combinators? <p>I've found a few resources on the subject, but they all require a deep understanding of <a href="http://en.wikipedia.org/wiki/Smalltalk">SmallTalk</a> or <a href="http://en.wikipedia.org/wiki/Haskell_%28programming_language%29">Haskell</a>, neither of which I know.</p>
| <p>I wrote 8 longish blog entries on monadic parser combinators in C# and F#; see <a href="http://lorgonblog.spaces.live.com/blog/cns!701679AD17B6D310!123.entry">here</a> for the first one.</p>
<p>See also <a href="http://www.quanttec.com/fparsec/">FParsec</a> (Parsec for F#)</p>
|
Select ..... where .... OR <p>Is there a way to select data where any one of multiple conditions occur on the same field?</p>
<p>Example: I would typically write a statement such as:</p>
<pre><code>select * from TABLE where field = 1 or field = 2 or field = 3
</code></pre>
<p>Is there a way to instead say something like:</p>
<pre><code>select * from TABLE where field = 1 || 2 || 3
</code></pre>
<p>Any help is appreciated.</p>
| <p>Sure thing, the simplest way is this:</p>
<pre><code>select foo from bar where baz in (1,2,3)
</code></pre>
|
Mac iWork/Pages Automation <p>There is a rich scripting model for Microsoft Office, but not so with Apple iWork, and specifically the word processor Pages. While there are some AppleScript hooks, it looks like the best approach is to manipulate the underlying XML data.</p>
<p>This turns out to be pretty ugly because (for example) page breaks are stored in XML. So for example, you have something like:</p>
<pre><code>... we hold these truths to be self evident, that </page>
<page>all men are created equal, and are ...
</code></pre>
<p>So if you want to add or remove text, you have to move the start/end tags around based on the size of the text on the page. This is pretty impossible without computing the number of words a page can hold, which seems wildly inelegant.</p>
<p>Anybody have any thoughts on this?</p>
| <p>I'd suggest that modifying the underlying XML file is "considered harmful". Especially if you haven't checked to see if the document is open!</p>
<p>I've had a quick look at the Scripting Dictionary for Pages, and it seems pretty comprehensive; here is part of one entry:</p>
<blockquote>
<p><strong>document</strong>ân [inh. <em>document</em> > <em>item</em>; see also Standard Suite] : A Pages document.</p>
<p><em>elements</em></p>
<p>contains <strong>captured pages, character
styles, charts, graphics, images,
lines, list styles, pages, paragraph
styles, sections, shapes, tables, text
boxes</strong>.</p>
<p><em>properties</em></p>
<p><strong>body text</strong> (text) : The main text flow of the document.</p>
<p><strong>bottom margin</strong> (real) : The bottom margin of the publication.</p>
<p><strong>facing pages</strong> (boolean) : Whether or not the view is set to facing
pages.</p>
<p><strong>footer margin</strong> (real) : The footer margin of the publication.</p>
<p><strong>header margin</strong> (real) : The header margin of the publication.</p>
<p><strong>id</strong> (integer, r/o) : The unique identifier of the document.</p>
<p>...</p>
</blockquote>
<p>So, I guess I'd want to know what it is that you want to do that you can't do with AppleScript?</p>
|
PowerShell App.Config <p>Has anyone worked out how to get PowerShell to use <code>app.config</code> files? I have a couple of .NET DLL's I'd like to use in one of my scripts but they expect their own config sections to be present in <code>app.config</code>/<code>web.config</code>.</p>
| <p>Cross-referencing with this thread, which helped me with the same question:
<a href="http://stackoverflow.com/questions/2789920/subsonic-access-to-app-config-connection-strings-from-referenced-dll-in-powershel">Subsonic Access To App.Config Connection Strings From Referenced DLL in Powershell Script</a></p>
<p>I added the following to my script, before invoking the DLL that needs config settings, where $configpath is the location of the file I want to load:</p>
<pre><code>[appdomain]::CurrentDomain.SetData("APP_CONFIG_FILE", $configpath)
Add-Type -AssemblyName System.Configuration
</code></pre>
|
What Comes After The %? <p>I've searched for this a little but I have not gotten a particularly straight answer. In C (and I guess C++), how do you determine what comes after the % when using <code>printf</code>?. For example:</p>
<pre><code>double radius = 1.0;
double area = 0.0;
area = calculateArea( radius );
printf( "%10.1f %10.2\n", radius, area );
</code></pre>
<p>I took this example straight from a book that I have on the C language. This does not make sense to me at all. Where do you come up with <code>10.1f</code> and <code>10.2f</code>? Could someone please explain this?</p>
| <p><a href="http://en.wikipedia.org/wiki/Printf#printf_format_placeholders"><a href="http://en.wikipedia.org/wiki/Printf#printf_format_placeholders">http://en.wikipedia.org/wiki/Printf#printf_format_placeholders</a></a> is Wikipedia's reference for format placeholders in printf. <a href="http://www.cplusplus.com/reference/clibrary/cstdio/printf.html"><a href="http://www.cplusplus.com/reference/clibrary/cstdio/printf.html">http://www.cplusplus.com/reference/clibrary/cstdio/printf.html</a></a> is also helpful</p>
<p>Basically in a simple form it's %[width].[precision][type]. Width allows you to make sure that the variable which is being printed is at least a certain length (useful for tables etc). Precision allows you to specify the precision a number is printed to (eg. decimal places etc) and the informs C/C++ what the variable you've given it is (character, integer, double etc).</p>
<p>Hope this helps</p>
<p><strong>UPDATE:</strong></p>
<p>To clarify using your examples:</p>
<pre><code>printf( "%10.1f %10.2\n", radius, area );
</code></pre>
<p>%10.1f (referring to the first argument: radius) means make it 10 characters long (ie. pad with spaces), and print it as a float with one decimal place.</p>
<p>%10.2 (referring to the second argument: area) means make it 10 character long (as above) and print with two decimal places.</p>
|
Is AnkhSVN any good? <p>I asked a couple of coworkers about <a href="http://ankhsvn.open.collab.net" rel="nofollow">AnkhSVN</a> and neither one of them was happy with it. One of them went as far as saying that AnkhSVN has messed up his devenv several times.</p>
<p>What's your experience with AnkhSVN? I really miss having an IDE integrated source control tool.</p>
| <p>Older AnkhSVN (pre 2.0) was very crappy and I was only using it for shiny icons in the solution explorer. I relied on Tortoise for everything except reverts.</p>
<p>The newer Ankh is a complete rewrite (it is now using the Source Control API of the IDE) and looks & works much better. Still, I haven't forced it to any heavy lifting. Icons is enough for me.</p>
<p>The only gripe I have with 2.0 is the fact that it slaps its footprint to <strong>.sln</strong> files. I always revert them lest they cause problems for co-workers who do not have Ankh installed. Dunno if my fears are groundless or not.</p>
<p><hr /></p>
<p>addendum:</p>
<p>I have been using v2.1.7141 a bit more extensively for the last few weeks and here are the new things I have to add:</p>
<ul>
<li>No ugly crashes that plagued v1.x. Yay!</li>
<li>For some reason, "Show Changes" (diff) windows are limited to only two. Meh.</li>
<li>Diff windows do not allow editing/reverting yet. Boo!</li>
<li>Updates, commits and browsing are MUCH faster than Tortoise. Yay!</li>
</ul>
<p>All in all, I would not use it standalone, but once you start using it, it becomes an almost indispensable companion to Tortoise.</p>
|
Best traffic / performance / usage monitoring module? <p>Are there any open source (or I guess commercial) packages that you can plug into your site for monitoring purposes? I'd like something that we can hook up to our ASP.NET site and use to provide reporting on things like:</p>
<ul>
<li>performance over time</li>
<li>current load</li>
<li>page traffic</li>
<li>SQL performance</li>
<li>PU time monitoring </li>
</ul>
<p>Ideally in c# :)</p>
<p>With some sexy graphs.</p>
<p><strong>Edit</strong>: I'd also be happy with a package that I can feed statistics and views of data to, and it would analyse trends, spot abnormal behaviour (e.g. "no one has logged in for the last hour. is this Ok?", "high traffic levels detected", "low number of API calls detected") and generally be very useful indeed. Does such a thing exist?</p>
<p>At my last office we had a big screen which showed us loads and loads of performance counters over a couple of time ranges, and we could spot weird stuff happening, but the data was not stored and there was no way to report on it. Its a package for doing this that I'm after.</p>
| <p>It should be noted that google analytics is not an accurate representation of web site usage. This is because the web beacon (web bug) used on the page does not always load for these reasons:</p>
<ol>
<li>Google analytics servers are called by millions of pages every second and can not always process the requests in a timely fashion.</li>
<li>Users often browse away from a page before the full page has loaded and thus there is not enough time to load Googles web beacon to record a hit.</li>
<li>Google analytics require javascript to be installed which can be disabled.</li>
<li>Quite a few (but not substantial amount) of people block google-analytics.com from their browsers, myself included.</li>
</ol>
<p>The physical log files are the best 'real' representation of site usage as they record every request. Alternatively there are far better 'professional' packages, of which Omniture is my favourite, which have much better response times, alternative methods for recording actions and more functionality.</p>
|
Creation Date of Compiled Executable (VC++ 2005) <p>The creation date of an executable linked in VS2005 is not set to the real creation-date of the exe-file. Only a complete re-build will set the current date, a re-link will not do it. Obviously the file is set to some date, which is taken from one of the project-files. </p>
<p>So: is there a way to force the linker to set the creation-date to the real link-date?</p>
| <p>Delete the executable as part of a pre-link event.</p>
<p>Edit:
Hah, I forgot about Explorer resetting the creation date if you name a file exactly the same as a file that was recently deleted.</p>
<p>Why are you keying off the creation date anyway?</p>
|
How Do You Secure database.yml? <p>Within Ruby on Rails applications database.yml is a plain text file that stores database credentials.</p>
<p>When I deploy my Rails applications I have an after deploy callback in my Capistrano
recipe that creates a symbolic link within the application's /config directory to the database.yml file. The file itself is stored in a separate directory that's outside the standard Capistrano /releases directory structure. I chmod 400 the file so it's only readable by the user who created it.</p>
<ul>
<li>Is this sufficient to lock it down? If not, what else do you do?</li>
<li>Is anyone encrypting their database.yml files?</li>
</ul>
| <p>The way I have tackled this is to put the database password in a file with read permissions only for the user I run my application as. Then, in database.yml I use ERB to read the file:</p>
<pre><code>production:
adapter: mysql
database: my_db
username: db_user
password: <%= begin IO.read("/home/my_deploy_user/.db") rescue "" end %>
</code></pre>
<p>Works a treat.</p>
|
Subsets and Splits