input
stringlengths
51
42.3k
output
stringlengths
18
55k
Is it really not possible to write a php cli password prompt that hides the password in windows? <p>I have spent several hours trying to find a means of writing a cross platform password prompt in php that hides the password that is input by the user. While this is easily accomplished in Unix environments through the use of stty -echo, I have tried various means of passthru() and system() calls to make windows do the same thing to no avail.</p> <p>I have tried:</p> <pre><code>passthru('set /p pass=Password: '); system('echo %pass% &gt; out.txt'); $pass = file_get_contents('out.txt', 'r'); </code></pre> <p>This seems to hang on the passthru('set /p pass=Password: '); line without allowing me to input any text and must be killed with a Ctrl-c.</p> <p>I have also tried various methods of fgetc and fgets and printing backspace characters to hide the input since this works in other languages. However, PHP does not appear to be able to interact with text prior to a carriage return.</p> <p>I would really like to find a way to make this work, is this an impossible task or is this something that can be done?</p> <p>Note that I am aware that I could wrap the php script in a batch file and pass the password as a command line argument, but that doesn't work for me in this case.</p>
<p>There doesn't seem to be an IOCTL or STTY extension for PHP. I found the following trick <a href="http://www.usenet-forums.com/php-language/35386-hide-password-input-cli-php-script.html">here</a>:</p> <pre><code>&lt;?php echo 'Password: '; $pwd = preg_replace('/\r?\n$/', '', `stty -echo; head -n1 ; stty echo`); echo "\n"; echo "Your password was: {$pwd}.\n"; ?&gt; </code></pre>
Hash Collision - what are the chances? <p>I have some code on my PHP powered site that creates a random hash (using <code>sha1()</code>) and I use it to match records in the database.</p> <p>What are the chances of a collision? Should I generate the hash, then check first if it's in the database (I'd rather avoid an extra query) or automatically insert it, based on the probability that it <em>probably</em> won't collide with another.</p>
<p>If you assume that SHA-1 does a good job, you can conclude that there's a 1 in 2^160 chance that two given messages have the same hash (since SHA-1 produces a 160-bit hash).</p> <p>2^160 is a ridiculously large number. It's roughly 10^48. Even if you have a million entries in your database, that's still a 1 in 10^42 chance that a new entry will share the same hash.</p> <p>SHA-1 has proved to be fairly good, so I don't think you need to worry about collisions at all.</p> <p>As a side note, use PHP's *raw_output* feature when you use SHA-1 as this will lead to a shorter string and hence will make your database operations a bit faster.</p> <p>EDIT: To address the birthday paradox, a database with 10^18 (a million million million) entries has a chance of about 1 in 0.0000000000003 of a collision. <em>Really</em> not worth worrying about.</p>
Javascript libraries to extend built in data type objects <p>There are a number of great Javascript libraries\frameworks out there (jQuery, Prototype, MooTools, etc.), but they all seem to focus on DOM interaction and AJAX functionality. I haven't found any that focus on extending the built-in data types (String, Date, Number, etc.). And by "Extending" I mean methods to solve typical work-a-day problems we all have. </p> <p>An example would be the .NET String.Format() method. Not only more convenient, but makes reading and trouble-shooting string concatenation better. While I have already created a String prototype method for this, I'd like to see if a good library has already been developed to address similar productivity issues before launching into a library of my own.</p> <p>Prototype has a few interesting methods in this regard, but since I've already settled on jQuery for DOM work, I really don't need to duplicate functionality on every page.</p> <p>Is anyone aware of a good, lean data type productivity library for Javascript?</p>
<p>There's a good reason the big javascript libraries steer clear of extending common object prototypes with functions which should really exist (String.trim, Array.shuffle !!)... If each library extended the String object to have a trim() function, then they'd overwrite each other - not good!</p> <p>Instead, what jQuery has done is to put those functions into the jQuery object. <code>$.trim(String), $.inArray(value, Array)</code>, etc. Not as "neat" as extending the prototype, but a lot more portable.</p> <p>Remember to consider this before you go adding your own functions!</p>
Which command will executed first,If a stored procedure have individual multiple select commands; <p>Which command will executed first,If a stored procedure have individual multiple select commands;</p>
<p>Commands inside stored procedure are executed in the order in which they are written.</p>
Do I get a finished slot if a start QProcess using startDetached <p>Do I get a finished signal if I start a QProcess using startDetached()? I'm trying to start a process, but I need to be able to get an event when the process has terminated.</p>
<p>No you can't get a signal when you use startDetached because you have no object.</p> <p>startDetached is a static function and when you call it the process is started directly without creating a QProcess object. Therefore, even if there was a signal you would not be able to connect it to anything since you have no object to connect from.</p> <p>If you want a signal you should create a QProcess object and then call start on it. You will then be able to get the finished signal when the process finishes.</p>
How to show Vista style balloon hints in Delphi? <p>On input validation, I'm using balloon tips instead of message boxes. My problem is that on Vista, they have the old XP style with the rounded corners, not the newer more rectangle like appearance.</p> <p>I've tried creating them using CreateWindowEx and <code>tooltips_class32</code> or showing the Edit's associated balloontip using SendMessageW and <code>EM_SHOWBALLOONTIP</code>, the result is the same. Doing the same thing in Visual Studio and C# results in a Vista style balloon tip.</p> <p>You can see an example of the balloon hint I need, when you toggle Caps Lock while in a password edit, like the one on the Windows Logon.</p>
<p>If you're using Delphi 2009, then adding balloon hints is reasonably straightforward, although the documentation is poor. (surprise, surprise)</p> <ul> <li>Drop a TBalloonHint on your form</li> <li>Drop a TImageList to contain icons if needed.</li> <li>Link the TIMageList to the TBalloonHint</li> <li>Set the form's CustomHint property to the TBalloonHint</li> <li>Make sure ShowHint and ParentCustomHint are set true for your controls.</li> </ul> <p>This next bit is <a href="http://qc.codegear.com/wc/qcmain.aspx?d=67445">very non-obvious</a>:</p> <ul> <li>Format the "Hint" property of your control as "Title|Hint|ImageIndex"</li> </ul> <p>You're done. This doesn't look 100% vista-like, maybe due to font choice. But it's pretty close.</p> <p><img src="http://dn.codegear.com/article/images/38757/0300000D.png" alt="Delphi 2009" />,</p>
How do I verify that my LINQ-to-SQL model matches the database schema? <p>I am absolutely new to the .NET world, and started with C# on friday. I have some experience with database apps, though.</p> <p>We will go with LINQ-to-SQL for a medium scale project. I am used to generating my schema from classes and keep track of changes with subversion and equivalents to Ruby's Migrations. There obviously is <a href="http://stackoverflow.com/questions/29145/generating-database-tables-from-object-definitions">no easy way to do this with LINQ</a> itself.</p> <p>So I thought of generating the schema (and do some data access) with <a href="http://www.castleproject.org/activerecord/index.html" rel="nofollow">Castle Project's ActiveRecord</a> and use <a href="http://code.google.com/p/migratordotnet/" rel="nofollow">Migrator.NET</a> <a href="http://code.google.com/p/tarantino/wiki/DatabaseChangeManagement" rel="nofollow">Tarantino</a> or <a href="http://sourceforge.net/projects/dbdeploy-net/" rel="nofollow">dbdeploy.net</a> for the schema updates. (Any suggestions for this?)</p> <p>My main question is: <strong>How do I verify that my LINQ classes still match the database schema? Does LINQ throw exceptions if the schema does not match? Can I iterate over all the LINQ classes and invoke some verify method?</strong></p> <p>I already found that <a href="http://stackoverflow.com/questions/40022/best-way-to-update-linq-to-sql-classes-after-database-schema-change">sqlmetal is the way to regenerate the classes</a>.</p> <p>PS: We will use SQL Server (2008 or 2005).</p>
<p>This <a href="http://blog.huagati.com/res/index.php/2008/07/17/tools-part-2-add-ins-dbml-synchronization-add-in-updated/" rel="nofollow">tool</a> will help sync them, but I'm unsure if it'll show differences...may be of some use though. (:</p> <p>EDIT: As <a href="http://stackoverflow.com/users/11241/kristofera">KristoferA</a> said in his comment, it does support comparisons (: - thanks KristoferA.</p>
Include ib_logfiles in backup? <p>The short question:<br/> Is it safe skip ib_logfile* files while creating custom-made backup of MySQL installation with InnoDB engine used?</p> <p>Custom-made backup is just copy all (or subset of) /var/lib/mysql + /etc/my.cnf to safe place.</p> <p>As I know ib_logfile* files are recreated by MySQL on start + the files are really huge, so that may not be wise to store them in backup. And yes, assume MySQL is (correctly) stopped before backup.</p>
<p>It's not safe to back up a database in the manner you're describing.</p> <p>The reason is that you cannot know if some data pages are still in MySQL Server's memory, pending an I/O flush to disk. So copying the files has a good chance of copying garbage, whether or not you include the <code>ib_log</code> files.</p> <p>Don't do what you're doing. Use <code>mysqlbackup</code> or InnoDB's <a href="http://www.innodb.com/hot-backup/">Hot Backup</a> product.</p> <p><strong>edit:</strong></p> <p>Read Farhan Mashraqi's blog article about <a href="http://mysqldatabaseadministration.blogspot.com/2007/04/innodb-performance-optimization.html">InnoDB Performance Optimization</a>, in which he says you can delete the <code>ib_log</code> files <em>if you have shut down MySQL Server</em>.</p> <blockquote> <p>InnoDB log resizing: is not as simple as changing option and restarting. You need to shut down MySQL server and make sure it shuts down normally (check error log for errors to confirm). Then move away InnoDB log files ib_log*. Then start the MySQL server and check error log files to see if it successfully created new log files.</p> </blockquote> <p>So yes, you should be able to do a filesystem copy of the <code>ibdata</code> files only. You don't need to include the <code>ib_log</code> files, because they should be recreated as MySQL Server starts up. I reiterate, however, that <strong>I do not recommend backing up databases with filesystem copy.</strong></p> <p>Suppose you back up a database today in this manner, using MySQL 5.0. Someday later you need to restore the backup, but by that time you'll be using some future version like MySQL 6.5 for example. Do the <code>ib_data</code> files still use the same internal format in that future version? Will MySQL 6.5 read those files you backed up today? You can't be sure. The backup format is intended to be more portable.</p>
Changing java lookandfeel without modifying the application <p>Is it possible to change java lookandfeel without modifying the program in a real-world environment?</p> <p>I know that theoretically the answer is yes. I also created demo applications and changed the lookandfeel even at runtime and it worked. But when I created a real application with lots of controls lookandfeel change was not really working:</p> <ul> <li>Different lookandfeels have different bugs (or strange features). For instance some of them creates the same style for JTextField and JFormattedTextField, some of them uses different styles. This change can be quite annoying for users.</li> <li>Control sizes are not the same (using different fonts, different borders), so sometimes the window looks ugly after change.</li> <li>Keyboard shortcuts can also be different.</li> <li>...</li> </ul> <p>In my applications after lookandfeel change (actually instead of changing the lookandfeel I tried using the same lookandfeel with different skins) I always have to modify the application. Not a very big modification, but lots of small modifications which makes lookandfeel change difficult.</p> <p>Am I just very unlucky with the lookandfeels I tried (currently using <a href="http://www.l2fprod.com/skinlf/" rel="nofollow">skinlf</a>), or lookandfeel change is not that easy as in small demo applications?</p> <p>UPDATE: I'm using Swing and changing to other GUI library is not possible for me right now.</p> <p><strong>UPDATE2</strong>: It seems to me the question was not clear. I do know how to change the lookandfeel. My questions is: Is it possible to create a real application where changing lookandfeel (or the skin of the lookandfeel) is an easy task? Currently if I change the lookandfeel it is not enough to change 2 or 3 lines, I have to review the whole application and fix quite a few problems caused by the lookandfeel change. dhiller suggested replacing skinlf with a better lookandfeel. Can you show me a skinable lookandfeel where skin replacement works better?</p>
<p>Yes, there are different ways to start your application with a certain look and fell without modifying the code of your application. An easy way is to set a system property at startup of your application. E.g. if you have a shell script or batch file starting your application you just change the command from</p> <pre><code>java -jar yourapp.jar </code></pre> <p>to</p> <pre><code>java -Dswing.defaultlaf=com.sun.java.swing.plaf.gtk.GTKLookAndFeel -jar yourapp.jar </code></pre> <p>-Dswing.defaultlaf=com.sun.java.swing.plaf.gtk.GTKLookAndFeel will set the default look and feel to use to the GTKLookAndFeel. </p> <p>There is also a way using a swing.properties file of your Java installation. For more details have a look at <a href="http://java.sun.com/docs/books/tutorial/uiswing/lookandfeel/plaf.html" rel="nofollow">this</a>. </p>
How to manage frequently modified production code? <p>My project invovles me to make a lot of changes on the production code. The requirement keeps coming up and I need to make changes and deploy it as soon as possible. I sometimes end up creating patch work sort of code because some of the requirement would not fit into the overall design of the software. How can this be handled effectively? Any design pattern to handle this?</p>
<p>I've seen this happen many times and it always ends in tears. The last time the customer lost millions of dollars before they improved their process.</p> <p>Users always want new requirements to be made available "as soon as possible," but they do not understand the risks of making the changes in the same way that you do. They see the cost of <em>not</em> having the feature but they don't anticipate what would happen and how much money would be lost if the change breaks something. (I don't mean to suggest that you're not a good developer, just that in any non-trivial software there will be bugs and that uncontrolled changes are likely to expose them more quickly.)</p> <p>So, I think you need to take a step back and try to instigate a regular release schedule. There will be resistance but you can be more effective that way. Of course sometimes there <em>will</em> be a change that needs to be made immediately, but if there's a schedule then the onus will be on the user to justify why breaking the release cycle makes sense.</p> <p>Oh, and as everyone else suggests, you need technical infrastructure like a staging/testing system, one-click release procedure, etc. (See <a href="http://www.joelonsoftware.com/articles/fog0000000043.html" rel="nofollow">The Joel Test</a>.)</p>
Dump hidden (or minimized) X11 window <p>I'd like to dump the contents of an X window. Like this:</p> <p>xwd -id | convert - capture.png</p> <p>... which works quite well as long as the target window is not hidden (totally or partially behind other windows) or minimized.</p> <p>Any idea on how to do this?</p> <p>I guess we somehow have to send a "repaint" signal to the hidden window and then capture its response or something... :)</p>
<p>Do you have an objection to bringing it to the front first? </p> <p>If not, you can use a tool like <a href="http://www.sweb.cz/tripie/utils/wmctrl/" rel="nofollow">wmctrl</a> to bring the window to the front (and maximize it, etc), use xwd to capture it, then send it back to where it came from with wmctrl.</p>
Firefox CSS: Given 2 divs, how can I float the *second* one to the right using static positioning? <p>I'm working on a <a href="http://userstyles.org/styles/12154" rel="nofollow">Youtube userstyle script</a> that displays comments side by side with the video so you can watch the video and read the comments at the same time (what a marvelous idea - duh). You can see in the screenshots how far I've got. That means I only care about Firefox, and that CSS3 goes.</p> <p>The problem I have is that I want to make a fully fluid layout and have the "other videos" div float to the right, while the middle div (the comments) stretches to fill the remaining space between the left div (the video played) and the right div (the "other videos").</p> <p>Translated to CSS, the problem is: given divs "main", "rightnav" and "footer", in this fixed order in the document, how can I make the rightnav div float to the right, and the footer BELOW it? The best I managed to do was to absolutely position "rightnav" (right: 0), but then the footer goes below the "main" div, not below both of them. I've looked at <a href="http://stackoverflow.com/questions/220273/css-positioning-div-above-another-div-when-not-in-that-order-in-the-html">http://stackoverflow.com/questions/220273/css-positioning-div-above-another-div-when-not-in-that-order-in-the-html</a> already. Negative 'top' values are out, as they depend on the content of the 'main' div.</p> <p>Here's the source code:</p> <pre><code>&lt;html lang="en-US"&gt; &lt;head&gt; &lt;style type="text/css"&gt; #main { border: 1px solid; float: left; margin-right: 410px; } #rightnav { background-color: yellow; opacity: 0.5; border: 1px dotted; width: 400px; float: right; position: absolute; right: 0; } #footer { clear: both; } &lt;/style&gt; &lt;/head&gt; &lt;body&gt; &lt;div id="baseDiv" style="width: 100%"&gt; &lt;div id="main"&gt; &lt;script&gt;for (var i=1; i&lt;100; i++) document.write('main ');&lt;/script&gt; &lt;/div&gt; &lt;div id="rightnav"&gt; &lt;script&gt;for (var i=1; i&lt;200; i++) document.write('rightnav ');&lt;/script&gt; &lt;/div&gt; &lt;div id="footer"&gt; &lt;script&gt;for (var i=1; i&lt;100; i++) document.write('footer ');&lt;/script&gt; &lt;/div&gt; &lt;/div&gt; &lt;/body&gt; &lt;/html&gt; </code></pre> <p>Hopefully it's clear what I want to achieve: the "footer" below the two divs, and the "main" div fluid.</p> <p>Thanks for any ideas.</p>
<pre><code>#main { border: 1px solid; width: 50%; float: left; } #rightnav { background-color: yellow; opacity: 0.5; border: 1px dotted; width: 48%; float: right; } #footer { clear: both; } </code></pre> <p>that'll do it</p> <p>edit: if you say liquid that usually means percent based dimensions, start associating things like that in your head</p>
Host a WPF control in activex instead of Win32 App <p>I'm searching an example of an activex that contain a WPF control.</p> <p>I'm able to see the control during registration of activex in the test activex container but when I instantiate it i cannot see WPF but what is coded inside OnDraw.</p> <p>Any hint or example?</p>
<p>check out the msdn article on Hosting Windows Presentation Foundation Content in a Win32 Application (<a href="http://msdn.microsoft.com/en-us/library/ms744829.aspx" rel="nofollow">http://msdn.microsoft.com/en-us/library/ms744829.aspx</a>)</p>
How to get the current directory in a C program? <p>I'm making a C program where I need to get the directory that the program is started from. This program is written for UNIX computers. I've been looking at <code>opendir()</code> and <code>telldir()</code>, but <code>telldir()</code> returns a <code>off_t (long int)</code>, so it really doesn't help me. </p> <p>How can I get the current path in a string (char array)?</p>
<p>Have you had a look at <a href="http://pubs.opengroup.org/onlinepubs/9699919799/functions/getcwd.html"><code>getcwd()</code></a>?</p> <pre><code>#include &lt;unistd.h&gt; char *getcwd(char *buf, size_t size); </code></pre> <p>Simple example:</p> <pre><code>#include &lt;unistd.h&gt; #include &lt;stdio.h&gt; #include &lt;errno.h&gt; int main() { char cwd[1024]; if (getcwd(cwd, sizeof(cwd)) != NULL) fprintf(stdout, "Current working dir: %s\n", cwd); else perror("getcwd() error"); return 0; } </code></pre>
Subsonic Join issue <p>For those of you who are decent with subsonic!</p> <pre><code> TblNewsCollection col = new Select().From(Tables.TblNews) .InnerJoin(Tables.TblContent) .Paged(currentPage, pageSize) .OrderDesc(TblContent.Columns.PubDate) .ExecuteAsCollection&lt;TblNewsCollection&gt;(); </code></pre> <p>The above works, no problem, but when I try to add a where clause</p> <pre><code> TblNewsCollection col = new Select().From(Tables.TblNews) .InnerJoin(Tables.TblContent) .Where(TblContent.Columns.UserFK) .IsEqualTo(guidUserFK) .Paged(currentPage, pageSize) .OrderDesc(TblContent.Columns.PubDate) .ExecuteAsCollection&lt;TblNewsCollection&gt;(); </code></pre> <p>I get this message</p> <pre><code>System.InvalidCastException: Object must implement IConvertible. at System.Convert.ChangeType(Object value, Type conversionType, IFormatProvider provider) at System.Data.SqlClient.SqlParameter.CoerceValue(Object value, MetaType destinationType) System.InvalidCastException: Failed to convert parameter value from a Guid to a String. </code></pre> <p>I've tried it from other fields, for example a bit field in a database it says it can't convert from bool to bit!</p> <p>Seems to only be an issue on where statements after joins</p>
<p>I found that joins work better using the TableColumnSchema as in the above Northwind example as opposed to the column name.</p>
Getting XML Schema from MS SQL Database <p>Is it possible to generate a XML Schema of a Database programatically with .Net and C#? I want to look into NDbUnit but for big databases it would not really be feasible to make a Schema manually? </p>
<blockquote> <p>Is it possible to generate a XML Schema from a Database?</p> </blockquote> <p>It sure is, <a href="http://www.altova.com/dev_portal_xml_schema.html">XMLSpy</a> can generate XML Schema from a database.</p> <p>There's <a href="http://dwightrau.blogspot.com/2008/02/generate-or-create-xsd-schema-from.html">another way</a>, though I've never tested it:</p> <pre><code>create table Person ( Age int not NULL check( Age &gt; 0) , Height numeric(10,2) not NULL check( Height &gt; 5), Gender varchar(5) not null check( Gender in ('M', 'F', 'O')), BirthDate datetime null, ) DECLARE @schema xml SET @schema = (SELECT * FROM Person FOR XML AUTO, ELEMENTS, XMLSCHEMA('PersonSchema')) select @schema </code></pre>
How do I select text nodes with jQuery? <p>I would like to get all descendant text nodes of an element, as a jQuery collection. What is the best way to do that?</p>
<p>jQuery doesn't have a convenient function for this. You need to combine <code>contents()</code>, which will give just child nodes but includes text nodes, with <code>find()</code>, which gives all descendant elements but no text nodes. Here's what I've come up with:</p> <pre><code>var getTextNodesIn = function(el) { return $(el).find(":not(iframe)").addBack().contents().filter(function() { return this.nodeType == 3; }); }; getTextNodesIn(el); </code></pre> <p><strong>Note: If you're using jQuery 1.7 or earlier, the code above will not work. To fix this, replace <a href="http://api.jquery.com/addBack/"><code>addBack()</code></a> with <a href="http://api.jquery.com/andSelf/"><code>andSelf()</code></a>. <code>andSelf()</code> is deprecated in favour of <code>addBack()</code> from 1.8 onwards.</strong></p> <p>This is somewhat inefficient compared to pure DOM methods and has to include an <a href="http://bugs.jquery.com/ticket/11275">ugly workaround for jQuery's overloading of its <code>contents()</code> function</a> (thanks to @rabidsnail in the comments for pointing that out), so here is non-jQuery solution using a simple recursive function. The <code>includeWhitespaceNodes</code> parameter controls whether or not whitespace text nodes are included in the output (in jQuery they are automatically filtered out).</p> <p>Update: Fixed bug when includeWhitespaceNodes is falsy.</p> <pre><code>function getTextNodesIn(node, includeWhitespaceNodes) { var textNodes = [], nonWhitespaceMatcher = /\S/; function getTextNodes(node) { if (node.nodeType == 3) { if (includeWhitespaceNodes || nonWhitespaceMatcher.test(node.nodeValue)) { textNodes.push(node); } } else { for (var i = 0, len = node.childNodes.length; i &lt; len; ++i) { getTextNodes(node.childNodes[i]); } } } getTextNodes(node); return textNodes; } getTextNodesIn(el); </code></pre>
How to make sure an application keeps running on Linux <p>I'm trying to ensure a script remains running on a development server. It collates stats and provides a web service so it's supposed to persist, yet a few times a day, it dies off for unknown reasons. When we notice we just launch it again, but it's a pain in the rear and some users don't have permission (or the knowhow) to launch it up.</p> <p>The programmer in me wants to spend a few hours getting to the bottom of the problem but the busy person in me thinks there must be an easy way to detect if an app is not running, and launch it again.</p> <p>I know I <em>could</em> cron-script ps through grep:</p> <pre><code>ps -A | grep appname </code></pre> <p>But again, that's another hour of my life wasted on doing something that must already exist... Is there not a pre-made app that I can pass an executable (optionally with arguments) and that will keep a process running indefinitely?</p> <p>In case it makes any difference, it's Ubuntu.</p>
<p>I have used a simple script with cron to make sure that the program is running. If it is not, then it will start it up. This may not be the perfect solution you are looking for, but it is simple and works rather well.</p> <pre class="lang-sh prettyprint-override"><code>#!/bin/bash #make-run.sh #make sure a process is always running. export DISPLAY=:0 #needed if you are running a simple gui app. process=YourProcessName makerun="/usr/bin/program" if ps ax | grep -v grep | grep $process &gt; /dev/null then exit else $makerun &amp; fi exit </code></pre> <p>Then add a cron job every minute, or every 5 minutes.</p>
How to do a jquery ajax call to a subdomain? <p>i could call a page inside the same domain, but its not working when i calling a page in a sub domain due to security issues. what i have to do? help me!!!</p>
<p>You can set the document.domain but if I remember correctly a few browsers (Opera) will not even allow this. I am afraid your answer is to create some sort of proxy on the subdomain that you can talk through</p>
Split string containing command-line parameters into string[] in C# <p>I have a single string that contains the command-line parameters to be passed to another executable and I need to extract the string[] containing the individual parameters in the same way that C# would if the commands had been specified on the command-line. The string[] will be used when executing another assemblies entry-point via reflection.</p> <p>Is there a standard function for this? Or is there a preferred method (regex?) for splitting the parameters correctly? It must handle '"' delimited strings that may contain spaces correctly, so I can't just split on ' '.</p> <p>Example string:</p> <pre><code>string parameterString = @"/src:""C:\tmp\Some Folder\Sub Folder"" /users:""abcdefg@hijkl.com"" tasks:""SomeTask,Some Other Task"" -someParam foo"; </code></pre> <p>Example result:</p> <pre><code>string[] parameterArray = new string[] { @"/src:C:\tmp\Some Folder\Sub Folder", @"/users:abcdefg@hijkl.com", @"tasks:SomeTask,Some Other Task", @"-someParam", @"foo" }; </code></pre> <p>I do not need a command-line parsing library, just a way to get the String[] that should be generated.</p> <p><strong>Update</strong>: I had to change the expected result to match what is actually generated by C# (removed the extra "'s in the split strings)</p>
<p>It annoys me that there's no function to split a string based on a function that examines each character. If there was, you could write it like this:</p> <pre><code> public static IEnumerable&lt;string&gt; SplitCommandLine(string commandLine) { bool inQuotes = false; return commandLine.Split(c =&gt; { if (c == '\"') inQuotes = !inQuotes; return !inQuotes &amp;&amp; c == ' '; }) .Select(arg =&gt; arg.Trim().TrimMatchingQuotes('\"')) .Where(arg =&gt; !string.IsNullOrEmpty(arg)); } </code></pre> <p>Although having written that, why not write the necessary extension methods. Okay, you talked me into it...</p> <p>Firstly, my own version of Split that takes a function that has to decide whether the specified character should split the string:</p> <pre><code> public static IEnumerable&lt;string&gt; Split(this string str, Func&lt;char, bool&gt; controller) { int nextPiece = 0; for (int c = 0; c &lt; str.Length; c++) { if (controller(str[c])) { yield return str.Substring(nextPiece, c - nextPiece); nextPiece = c + 1; } } yield return str.Substring(nextPiece); } </code></pre> <p>It may yield some empty strings depending on the situation, but maybe that information will be useful in other cases, so I don't remove the empty entries in this function.</p> <p>Secondly (and more mundanely) a little helper that will trim a matching pair of quotes from the start and end of a string. It's more fussy than the standard Trim method - it will only trim one character from each end, and it will not trim from just one end:</p> <pre><code> public static string TrimMatchingQuotes(this string input, char quote) { if ((input.Length &gt;= 2) &amp;&amp; (input[0] == quote) &amp;&amp; (input[input.Length - 1] == quote)) return input.Substring(1, input.Length - 2); return input; } </code></pre> <p>And I suppose you'll want some tests as well. Well, alright then. But this must be absolutely the last thing! First a helper function that compares the result of the split with the expected array contents:</p> <pre><code> public static void Test(string cmdLine, params string[] args) { string[] split = SplitCommandLine(cmdLine).ToArray(); Debug.Assert(split.Length == args.Length); for (int n = 0; n &lt; split.Length; n++) Debug.Assert(split[n] == args[n]); } </code></pre> <p>Then I can write tests like this:</p> <pre><code> Test(""); Test("a", "a"); Test(" abc ", "abc"); Test("a b ", "a", "b"); Test("a b \"c d\"", "a", "b", "c d"); </code></pre> <p>Here's the test for your requirements:</p> <pre><code> Test(@"/src:""C:\tmp\Some Folder\Sub Folder"" /users:""abcdefg@hijkl.com"" tasks:""SomeTask,Some Other Task"" -someParam", @"/src:""C:\tmp\Some Folder\Sub Folder""", @"/users:""abcdefg@hijkl.com""", @"tasks:""SomeTask,Some Other Task""", @"-someParam"); </code></pre> <p>Note that the implementation has the extra feature that it will remove quotes around an argument if that makes sense (thanks to the TrimMatchingQuotes function). I believe that's part of the normal command-line interpretation.</p>
XML Serialization issue for minoccurs <p>I have a .NET Web app which consumes a Java-based Web service. One of the objects, named Optional, contains search criteria fields. The schema is the following:</p> <pre><code>&lt;xsd:complexType name="Optional"&gt; &lt;xsd:sequence&gt; &lt;xsd:element name="FromAmount" nillable="true" type="xsd:float" minOccurs="0" /&gt; &lt;xsd:element name="ToAmount" nillable="true" type="xsd:float" minOccurs="0" /&gt; &lt;xsd:element name="FromDate" nillable="true" type="xsd:dateTime" minOccurs="0" /&gt; &lt;xsd:element name="ToDate" nillable="true" type="xsd:dateTime" minOccurs="0" /&gt; &lt;xsd:element name="FromCheckNumber" nillable="true" type="xsd:long" minOccurs="0" /&gt; &lt;xsd:element name="ToCheckNumber" nillable="true" type="xsd:long" minOccurs="0" /&gt; &lt;/xsd:sequence&gt; &lt;/xsd:complexType&gt; </code></pre> <p>The problem that I am running into is that the child elements will not serialize even when a value is assigned to them in the Web app. If I remove the minOccurs attribute, then all is well.</p> <p>How do I get these elements to be optional, but to serialize when a value is assigned to them?</p> <p>Thanks in advance for your help.</p>
<p>in .NET WS for non-nullable types (in .NET) that are marked optional in the schema have an additional specified property generated for them that control if the element appears. Very annoyingly, the setter for the value does not set the additional specified flag, so you need do this.</p> <pre><code>x.ToAmmount = 24.0f; x.ToAmmountSpecified = true; // etc for the rest of the poperties </code></pre>
javascript alerting from a c# class <p>I have a 5 aspx page "wizard". each one contains a "SaveAndExit" button that executes a c# function on a common static class. After saving , the c# code redirects to another page.</p> <p>Is there a way for running javascript: alert('Data Saved'); after the saving, and before new page is Loaded.</p>
<p>You'll have to register a startup script on postback to do the alert. Then redirect via javascript after the alert.</p>
Custom namespace for code behind .aspx page <p>I am using .NET2.0. Let's say a have a simple aspx form with txtInput and btnSomeAction</p> <pre><code> &lt;asp:TextBox ID="txtInput" runat="server"&gt;&lt;/asp:TextBox&gt; &lt;asp:Button ID="btnSomeAction" runat="server" CommandName="SomeAction" Text="Do"/&gt; </code></pre> <p>Then within the code behind the form I have</p> <pre><code>Protected Sub btnSomeAction_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnSomeAction.Click Dim s As String s = txtInput.Text End Sub </code></pre> <p>It all works fine.</p> <p>Then I want to add the code to a custom namespace like</p> <pre><code>Namespace mycustomnamespace </code></pre> <p>When doing that I would get a complier error:</p> <p><strong><em>Name 'txtInput' is not declared</em></strong> - as if the code was no longer connected to the page</p> <p>Do i need to modify the aspx page to include the namespace?, What about the partial class?</p>
<blockquote> <p>Do i need to modify the aspx page to include the namespace?, What about the partial class?</p> </blockquote> <p>Yes. At the top of your aspx file you should see something like </p> <blockquote> <pre><code>&lt;%@ Page AutoEventWireup="false" Inherits="Blah.Foo.Bar" %&gt; </code></pre> </blockquote> <p>Where bar is the name of the class in the codebehind and Blah.Foo is it's namespace. You would need to change it to</p> <blockquote> <pre><code>&lt;%@ Page AutoEventWireup="false" Inherits="mycustomnamespace.Bar" %&gt; </code></pre> </blockquote>
Imitating SQL Server Profiler in a C# app? <p>I want to create a trace on a database server from my C# app, like what you do in SQL Server Profiler. I have found stored procedures (sys.sp_trace_create etc...) that dont seem to work for my SQL management studio. I was wondering if anyone could help with the coding, or where i would start to do this?!</p>
<p>Are you wanting this to be real-time, just like the Profiler itself? That'd be tough to do. You'd basically be re-creating the profiler. </p> <p>If that is not a requirement, I would recommend simply calling the sp_trace_create stored procs that you found to start a server-side trace, then use your application to open up the files that this trace produces.</p> <p>The EASIEST way to learn how this works is to run the SQL Profiler itself, set all the options you want, then click Run, and immediately click Stop. Then go to File, Export, Script Trace Definition, and choose the appropriate version.</p> <p>This should give you a TSQL script that puts all the correct pieces together, including all the trace events, columns, etc.</p> <p>More technical history of the profiler: <a href="http://www.microsoft.com/technet/prodtechnol/sql/70/tips/sqlprof.mspx" rel="nofollow">This old SQLMag article</a> has some history of the Profiler, which replaced an app called "SQL Trace" when SQL 7.0 was introduced.</p>
What metrics should we use to judge code quality? <p>I'm currently working on a large project, where many developers worked over time and the code was terrible. After many refactorings we now arrived a point, where the code is ok. Now I'm thinking what "ok" means - probably for everyone something different.</p> <p>Do you think it's possible to specify "ok"? What is important? NDepend metrics? Test Coverage? Comments? Coding style? Documentation?</p> <p>I know there are already many topics about coding style or commenting (for example <a href="http://stackoverflow.com/questions/tagged/best-practices+programming">here</a>). This question is just about what facts are important.</p>
<p>I think for any non-trival project you should have coding guidelines in place (style, comments, etc.) and metrics to know if they are being followed or not. The list you've outlined is a very good start.</p>
WCF here to stay? <p>Currently reading quite a heavy WCF book. I have used it myself in production just the once, using tcp, worked a charm. Anyway what are your opinions on this technology, is it here to stay, is it worth the time invested learning all the complex features etc etc?</p>
<p>I think it is here to stay. It is easily configurable for moving endpoints, it seems robust and allows you to do (pretty much) everything you could do in web services and remoting without the overhead of separate implementations.</p> <p>I can see where you are coming from, with MS's recent leaks about ongoing support for, and maintenance of Linq to SQL, but I see WCF as a different beast altogether. This is a technology that allows interoperability, as well as de-complixifying (I know this isn't a real word, but it should be) communications between systems.</p>
jQuery .Net Deployment Issue <p>Just started getting into jQuery and have an issue with a jQuery Post call working perfectly on my local dev box (VS 2008 built-in web server), but failing when I deploy to a windows 2003 server (IIS 6) box.</p> <p>The post works and the page being posted to process things correctly, but a response is never received by the calling Post function. The submitting page just reloads with no changes.</p> <p>Here is my Post function (it is enclosed in the <code>$(document).ready(function() {...</code></p> <p>The alert in the response function never fires:</p> <pre><code> $('.nextButton').click(function() { var idString = ''; $("div.dropZone &gt; div").each(function(n) { idString += this.id + '|'; }); $.post('CustomPostHandler.aspx?step=criteria', { selected: idString }, function(data) { alert(data); }); }); </code></pre> <p>The post handler page does receive the idString variable fine, after some processing it attempts to write back a response:</p> <pre><code> // Return dummy response to caller Response.Clear(); Response.ContentType = "text/plain"; Response.Write("success"); Response.End(); </code></pre> <p>I've checked the deployment server environment and don't see anything missing (this is running against the 3.5 SP1 framework). Anyone have any ideas or am I missing something?</p>
<p>The problem is probably due to caching.<br /> Try adding a random number to the post URL</p> <pre><code>$.post('CustomPostHandler.aspx?step=criteria&amp;random=' + Math.random().toString(), { selected: idString }, </code></pre>
In what situations is the ATL CSimpleArray a better choice than CAtlArray <p>The documentation says that CSimpleArray is for dealing with small numbers of objects. What is small in this context? Is CSimpleArray ever a good choice or should I always use a different collection class such as CAtlArray?</p>
<p>"Small" here is a rule of thumb, which stems from the way the two classes manage their memory internally. Basically, CAtlArray provides more fine-grained control of the memory it uses, and CSimpleArray deals with memory simply but naively. </p> <p>Specifically, when an element is added to a CSimpleArray, if the array already uses all the memory it has allocated, it will double its size, which is a fairly expensive operation. A newly created CSimpleArray will start with space for 0 items. So let's say you want to add 5 things to an array. It will look like this:</p> <ul> <li>Add 1st item - there is no room, so reallocate space for 1 item in total</li> <li>Add 2nd item - there is no room, so reallocate space for 2 items in total</li> <li>Add 3rd item - there is no room, so reallocate space for 4 items in total</li> <li>Add 4th item - there is room, so just add</li> <li>Add 5th item - there is no room, so reallocate space for 8 items in total</li> <li>and so on...</li> </ul> <p>Also note that there is no way to specify the initial size of a CSimpleArray, so this patten will always happen.</p> <p>On the other hand, a CAtlArray allows you to specify the allocated memory all at once, via the SetCount( ) method. Using the same example as above, before adding the items, call SetCount(5). Then there will always be room for 5 items and no reallocations need to be done.</p> <p>So to answer the question: use CAtlArray if you care about memory management, especially if you are worried abot performance. Use CSimpleArray if you just want to keep a few items in a list and don't care how the memory the list occupies is managed. To answer the specific question about what "small" and "large" mean in this context, "small" means few enough elements that it's ok with you to reallocate every time the length exceeds the next power of 2.</p> <p>It's also worthwhile to note that CSimpleArray lets you search through the Array using the Find( ) method, and CAtlArray does not.</p> <p>(Note: my answer is based only on looking through the ATL source code.)</p>
Webkit/Safari/Firefox/API: Can I programmatically read/extract multiple tabs' URLs? <p>Topic: Programmatically manipulate web browser in OS X 10.4.x+ Tiger/Leopard. Subjects: Webkit, Safari, Firefox, APIs, Applescript, Automator, Javascript, Ruby, Ruby on Rails, OS X, Tiger Goal: Collect/Read/Extract URLs from Safari into text (Ruby on Rails code) file. Note: A solution that uses FF would be very appreciated, too. I use Safari (v. 3.x, OS X 10.4.x) more and much prefer a solution that works in Safari.</p> <p>At times, I use the web browser to find/display multiple site pages that I 1) want to visit again later and 2) the URLs of which I want to group together in a text file for a) future reference and/or b) programmatically manipulate.</p> <p>For example: In today's NYT I find seven NYT articles I want to post to my del.icio.us acct. and share via email in their "printer friendly" format long after they are headlined in that day's online edition. I open each one in a browser window's tap, then Presto! their URLs automagically are wooshed into a file where a (custom) Ruby on Rails app sends the print versions' URLs to email addresses and my Del.icio.us acct.</p> <p>I figure there's a way to do the URL extracting step from the OS using Applescript or Automator. I figure there MAY be a way to do it with Javascript.</p> <p>My Question: How to read the web browser's tabs' location field and collate these strings into a text file (either within my OS or over the wire to a web app.)?</p> <p>Much appreciated.</p>
<p>For Safari, this would be pretty trivial to do with Applescript. I'd suggest starting with something like <a href="http://www.macosxhints.com/article.php?story=20060227192533174" rel="nofollow">Bookmark all tabs</a> to get the basic tab-grabbing logic that you'll need, and maybe merge it into John Gruber's old <a href="http://daringfireball.net/2003/02/save_and_restore_safari_urls" rel="nofollow">Save and restore Safari URLs</a> script to save the URLs as a list to a text file.</p> <p>There may be better Applescript solutions out there, too; those were just the first I found via Google, and both are pretty badly dated.</p> <p>For further help and resources pertaining to Applescript, I suggest the <a href="http://bbs.macscripter.net/" rel="nofollow">MacScripter forums</a>.</p> <p>Good luck!</p>
How to add a "driver" to javax.comm? Serial port programming in Java <p>I am trying to use a RS-232 serial port on my PC with javax.comm class. I am newby on that API, so first of all I go through the documentation and I find out that the first thing you should do is "list" all the ports from the class CommPortListener and pick up one of them.</p> <p>That worked just fine! Problem is, now, that my port is missing. It lists the /dev/ttyS0 and /dev/ttyS1 ports, non existents on my computer. My ports (I have been working with them several times) are /dev/ttySNX0 and /dev/ttySNX1.</p> <p>Again surfing the web I find out that I should do something like "register" or "load" the driver of my card onto the API system, stuff that could be done in previous versions, but not now. Moreover, I tried to do it under windows and they offer me a "generic" version of the API, with needs some RXTX application which is starting to beat me.</p> <p>I would thank any sugestions, links to documentation... something... that allow me to use my serial ports through Java, wich, in the end, is my objective...</p> <p>Thanks folks!!!!</p>
<p>Have you tried RXTX? I've had successf with that API on Windows/XP. I'n not sure what you mean by "starting to beat me".</p> <p>There has been a lot of recent activity on the RXTX project and a new release incorporating a number of fixes and additional support is imminent. The mailing list is also relatively active. <code>javax.comm</code> has been more or less dead for a while.</p>
Web Service or DLL? <p>I'm creating an app that needs to be accessed by both a web front end hosted on an internal network and also run as a scheduled task. Nothing will need to be accessed outside of our internal systems and once the app is up and running we don't envision anything changing for some time.</p> <p>My initial thought is to create a DLL encapsulating the bulk of the necessary functionality and then call it via both a Web Forms interface for manual execution, and a console app running as an automated (daily) scheduled task.</p> <p>Another suggestion has been to expose a Web Service for the core functionality instead, but as the app will never need to be called by an external resource I think the extra effort required in implementing a Web Service might not be worth the hassle. The DLL solution should also be substantially faster(?).</p> <p>My question is which route would you choose? Are there any pros/cons that I haven't covered? Any glaring omissions?</p> <p><strong>Disclaimer:</strong> I'm new to .Net but due to one of our developers being involved in a serious accident I've been asked to step up to the plate.</p>
<p>Personally, I say go with the DLL. It will be fast and simple.</p> <p>With a web service, you will need to think about your network, firewalls, performance, etc. It also makes it harder to debug since you won't be able to step into the web service from your clients, you will have to set breakpoints on both sides of the calls.</p> <p>The other problem with web services for you is that you need to be much more robust handling failures. With a DLL, you know a call to a method is going to succeed, but with a web service, you will need to be prepared for that call to fail or time out whenever you make any call across.</p> <p>Lastly, if you find a need for a web service at a later date, you should be able to fairly easily convert the DLL into a web service with minimal retrofitting.</p>
What do I have to do to make my WH_SHELL or WH_CBT hook procedure receive events from other processes? <p>I'm trying to use <code>SetWindowsHookEx</code> to set up a <code>WH_SHELL</code> hook to get notified of system-wide <code>HSHELL_WINDOWCREATED</code> and <code>HSHELL_WINDOWDESTROYED</code> events. I pass 0 for the final <code>dwThreadId</code> argument which, according to <a href="http://msdn.microsoft.com/en-us/library/ms644990(VS.85).aspx">the docs</a>, should "associate the hook procedure with all existing threads running in the same desktop as the calling thread". I also pass in the handle to my DLL (<code>HInstance</code> in Delphi) for the <code>hMod</code> parameter as did all the examples I looked at.</p> <p>Yet, I only ever get notified of windows created by my own app and - more often than not - my tests result in the desktop process going down in flames once I close down my app. Before you ask, I do call <code>UnhookWindowsHookEx</code>. I also always call <code>CallNextHookEx</code> from within my handler.</p> <p>I am running my test app from a limited user account but so far I haven't found any hints indicating that this would play a role... (though that actually surprises me)</p> <p>AFAICT, I did everything by the book (obviously I didn't but so far I fail to see where).</p> <p>I'm using Delphi (2007) but that shouldn't really matter I think.</p> <p><strong>EDIT:</strong> Maybe I should have mentioned this before: I did download and try a couple of examples (though there are unfortunately not that many available for Delphi - especially none for <code>WH_SHELL</code> or <code>WH_CBT</code>). While they do not crash the system like my test app does, they still do not capture events from other processes (even though I can verify with ProcessExplorer that they get loaded into them alright). So it seems there is either something wrong with my system configuration or the examples are wrong or it is simply not possible to capture events from other processes. Can anyone enlighten me?</p> <p><strong>EDIT2:</strong> OK, here's the source of my test project.</p> <p>The DLL containing the hook procedure:</p> <pre><code>library HookHelper; uses Windows; {$R *.res} type THookCallback = procedure(ACode, AWParam, ALParam: Integer); stdcall; var WndHookCallback: THookCallback; Hook: HHook; function HookProc(ACode, AWParam, ALParam: Integer): Integer; stdcall; begin Result := CallNextHookEx(Hook, ACode, AWParam, ALParam); if ACode &lt; 0 then Exit; try if Assigned(WndHookCallback) // and (ACode in [HSHELL_WINDOWCREATED, HSHELL_WINDOWDESTROYED]) then and (ACode in [HCBT_CREATEWND, HCBT_DESTROYWND]) then WndHookCallback(ACode, AWParam, ALParam); except // plop! end; end; procedure InitHook(ACallback: THookCallback); register; begin // Hook := SetWindowsHookEx(WH_SHELL, @HookProc, HInstance, 0); Hook := SetWindowsHookEx(WH_CBT, @HookProc, HInstance, 0); if Hook = 0 then begin // ShowMessage(SysErrorMessage(GetLastError)); end else begin WndHookCallback := ACallback; end; end; procedure UninitHook; register; begin if Hook &lt;&gt; 0 then UnhookWindowsHookEx(Hook); WndHookCallback := nil; end; exports InitHook, UninitHook; begin end. </code></pre> <p>And the main form of the app using the hook:</p> <pre><code>unit MainFo; interface uses Windows, SysUtils, Forms, Dialogs, Classes, Controls, Buttons, StdCtrls; type THookTest_Fo = class(TForm) Hook_Btn: TSpeedButton; Output_Lbx: TListBox; Test_Btn: TButton; procedure Hook_BtnClick(Sender: TObject); procedure Test_BtnClick(Sender: TObject); public destructor Destroy; override; end; var HookTest_Fo: THookTest_Fo; implementation {$R *.dfm} type THookCallback = procedure(ACode, AWParam, ALParam: Integer); stdcall; procedure InitHook(const ACallback: THookCallback); register; external 'HookHelper.dll'; procedure UninitHook; register; external 'HookHelper.dll'; procedure HookCallback(ACode, AWParam, ALParam: Integer); stdcall; begin if Assigned(HookTest_Fo) then case ACode of // HSHELL_WINDOWCREATED: HCBT_CREATEWND: HookTest_Fo.Output_Lbx.Items.Add('created handle #' + IntToStr(AWParam)); // HSHELL_WINDOWDESTROYED: HCBT_DESTROYWND: HookTest_Fo.Output_Lbx.Items.Add('destroyed handle #' + IntToStr(AWParam)); else HookTest_Fo.Output_Lbx.Items.Add(Format('code: %d, WParam: $%x, LParam: $%x', [ACode, AWParam, ALParam])); end; end; procedure THookTest_Fo.Test_BtnClick(Sender: TObject); begin ShowMessage('Boo!'); end; destructor THookTest_Fo.Destroy; begin UninitHook; // just to make sure inherited; end; procedure THookTest_Fo.Hook_BtnClick(Sender: TObject); begin if Hook_Btn.Down then InitHook(HookCallback) else UninitHook; end; end. </code></pre>
<p>The problem is that your hook DLL is actually being loaded into several different address spaces. Any time Windows detects an event in some foreign process that must be processed by your hook, it loads the hook DLL into that process (if it's not already loaded, of course).</p> <p>However, each process has its own address space. This means that the callback function pointer that you passed in InitHook() only makes sense in the context of your EXE (that's why it works for events in your app). In any other process that pointer is <strong>garbage</strong>; it may point to an invalid memory location or (worse) into some random code section. The result can either be an access violation or silent memory corruption.</p> <p>Generally, the solution is to use some sort of <a href="http://msdn.microsoft.com/en-us/library/aa365574(VS.85).aspx">interprocess communication</a> (IPC) to properly notify your EXE. The most painless way for your case would be to post a message and cram the needed info (event and HWND) into its WPARAM/LPARAM. You could either use a WM_APP+n or create one with RegisterWindowMessage(). Make sure the message is posted and not sent, to avoid any deadlocks.</p>
How do I generically use KVC to update fields? <p>Say I have the following Objective-C class:</p> <pre><code>@interface Foo { int someNumber; NSString *someString; } </code></pre> <p>and for reasons I won't get into here, I want to use KVC to update, in a generic fashion, the values for those variables:</p> <pre><code>[f setValue:object forKey:@"someNumber"]; or [f setValue:object forKey:@"someString"];` </code></pre> <p>If <code>object</code> is a string and I'm updating the <code>someNumber</code> variable, it seems that I need to know to use an NSNumberFormatter to get an NSNumber and then Cocoa automatically converts that to an int inside <code>setValue:forKey:</code>. </p> <p>Is there any way to avoid this custom code and have Cocoa infer the conversion to an int from a string, or do I need to catch this situation each time and handle it myself?</p>
<p>The following code should handle the conversion automatically, as long as the <code>object</code> parameter is a member of a class that implements <code>integerValue</code>.</p> <p>Note that both <code>NSNumber</code> and <code>NSString</code> implement this method.</p> <pre><code>- (void)setValue:(id)object forKey:(NSString *)key { if ([key isEqual:@"someNumber"]) { someNumber = [object integerValue]; } //... }</code></pre> <p><b>edit:</b> (side note): You can avoid writing the method yourself by using objective-c properties. The default implementation of <code>setValue:forKey:</code> will do the work for you, as long as you create properties for <code>someNumber</code> and <code>someString</code>.</p>
How to best implement swear words handler (.NET preferred)? <p>For an ASP.NET application, what is the Best Practice implementation method for a custom swear word remover/replacer?</p> <p>If this is a data table solution, is there free resource to get the data? (Similar to finding a public dictionary table that you can import to your system for spellchecking)</p>
<p><a href="http://www.codinghorror.com/blog/archives/001176.html" rel="nofollow" title="Obscenity Filters: Bad Idea, or Incredibly Intercoursing Bad Idea?">Obscenity Filters: Bad Idea, or Incredibly Intercoursing Bad Idea?</a> ^_^</p> <p>Also see <a href="http://stackoverflow.com/questions/273516/how-do-you-implement-a-good-profanity-filter" rel="nofollow" title="How do you implement a good profanity filter?">How do you implement a good profanity filter?</a>.</p>
How can I query users with an expired password in Active Directory? <p>I need to query Active Directory for a list of users whose password is about to expire. The obvious (and easy) way to do this is with:</p> <pre><code>dsquery user -stalepwd n </code></pre> <p>The problem is that I need to add additional filters to only look for users who are in certain security groups. This is hard to do with the "dsquery user" syntax that has the built-in -stalepwd option, so I've been using the "dsquery * -filter" option which allows you to use LDAP query syntax. Unfortunately, while its relatively easy to do apply the other filters with an LDAP query, I'm having trouble filtering users who have a password age greater than n.</p> <p>Does anyone know the syntax (or if it is even possible) to filter for old passwords using the "dsquery * -filter" method instead of the "dsquery user -stalepwd" method.</p>
<p>You can write an LDAP Query that compares "stale" passwords by comparing the pwdLastSet attribute on the user object:</p> <pre><code>(&amp;(objectClass=person)(objectClass=User)(pwdLastSet&lt;=n)) </code></pre> <p>ActiveDirectory uses a very specific format for this time stamp. I believe it a file-time, but I would double check on the web.</p>
Flash Screenshot <p>We're trying to send an image of a large SWF file to a server to have it mailed out and we're having a bit of trouble with transmission time. </p> <p>The SWF is about 900px x 600px and restricted to AS2 so we've been using this Bitmap Exporter class. We've tried using several different ways to transmit the data; base10, base36 and base128 but none of them will send the file in any kind of timely manner.</p> <p>Right now we're dealing with 60-120 seconds per image which isn't acceptable.</p> <p>Has anyone any advice for dealing with either this class or another for sending large bitmap data to a server with flash?</p> <p>Thank you for your time.</p>
<p>The reason you get such long upload times is that the image is barely compressed (or not at all depending on how the class is implemented). 900 by 600 pixels at 16 bpp (or whatever it now is flash uses) amounts to something like 1.5mb of raw data. </p> <p>I'm doubtful that there are any useful compression libraries for AS2, but that <strong>may</strong> be a possible path. </p> <p>The easiest way to make the image smaller on the client side would be lowering the resolution. Are you using the full resolution once it reaches the server? If not that might be a possible way.</p> <p>(I guess you're aware that this would be way easier using AS3, then you could compress the whole image as a jpeg clientside without very much effort, but I guess the rest of your application is AS2 making that a somewhat moot point)</p>
How can I send an array to php through ajax? <p>I want to send an array constructed in javascript with the selected values of a multiple select. Is there a way to send this array to a php script using ajax?</p>
<p>You might do that with $.post method of jQuery (for example) :</p> <pre><code>var myJavascriptArray = new Array('jj', 'kk', 'oo'); $.post('urltocallinajax', {'myphpvariable[]': myJavascriptArray }, function(data){ // do something with received data! }); </code></pre> <p>Php will receive an array which will be name <strong>myphpvariable</strong> and it will contain the myJavascriptArray values.</p> <p>Is it that ?</p>
Is there an html css normalizer that works? <p>Long ago, I wrote a style 'normalizer' program to scan the ASP/HTML code of a big pile of classic ASP pages (most of which were originally generated from MS-Word documents, so naturally they were littered with superflous stylesheets and massive one-off styles). The style normalizer generated a minimal set of stylesheets and styles and a new 'sanitized' asp/html document, so that the sanitized document produced exactly the same rendered output as the original (verified with screenshot image comparisons).</p> <p>Every now and then, I run across a need for a program like this, and am toying with the idea of writing one for commercial release.</p> <p>My googling skills have not turned up anything exactly like this (HTML:Normalize Perl module and HTML Tidy project just seem to clean up tags).</p> <p>So, my questions are:</p> <ol> <li>is there such a tool already, commercial or otherwise?</li> <li>if not, does anybody really need it?</li> <li>if so, what features would make it truly worthwhile?</li> </ol> <p>re #3 for example, collecting a base stylesheet for a set of pages, or adjusting all pages to use a given base stylesheet; preserving classic asp commands, following #includes, preserving asp.net embedded scripts, et al. The more specific and numerous, the better.</p> <p>Example:<br /> Old html w/embedded tags</p> <pre><code>&lt;html&gt;&lt;head&gt; &lt;title&gt;title&lt;/title&gt; &lt;style type='css/text'&gt; .cls1 { font-family: arial; font-size: 10px; font-weight: bold; } &lt;/style&gt; &lt;/head&gt; &lt;body&gt; &lt;% somefunction() %&gt; &lt;div class='cls1' style='font-size:10px;'&gt;test div&lt;/div&gt; &lt;/body&gt; &lt;/html&gt; </code></pre> <p>New html</p> <pre><code>&lt;html&gt;&lt;head&gt; &lt;title&gt;title&lt;/title&gt; &lt;style type='css/text'&gt; .cls1 { font-family: arial; font-size: 10px; font-weight: bold; } &lt;/style&gt; &lt;/head&gt; &lt;body&gt; &lt;% somefunction() %&gt; &lt;div class='cls1'&gt;test div&lt;/div&gt; &lt;/body&gt; &lt;/html&gt; </code></pre> <p>Note that the style on the div is gone, since it was redundant with the class cls1</p> <p>EDIT: removed the term 'sanitizer' since i'm not focused on XSS attacks or filtering input in comments, merely on consolidating a lot of ad-hoc styles and random CSS classes into a minimal coherent set of stylesheets.</p>
<p>Well, I can't say definitively that this "works" for everything described, but Tidy does a bit more than clean up tags.</p> <p>See the <a href="http://tidy.sourceforge.net/docs/quickref.html" rel="nofollow">HTML Tidy Configuration Options</a>, especially those relating to Microsoft Word (like <a href="http://tidy.sourceforge.net/docs/quickref.html#word-2000" rel="nofollow">word-2000</a>)</p>
Excel workbooks produced by POI don't work when linked <p>Here is what I'm doing :</p> <ol> <li>Create a workbook in memory (book = new HSSFWorkbook(), ...)</li> <li>Save it to disk (book.write(...))</li> <li>Open in Excel (ok)</li> <li>Create another workbook in Excel, which links to the first one (=PoiWorkbook?xls!A1)</li> <li>Close Excel</li> </ol> <p>Then everytime I open the second workbook again, all the links are #N/A, unless I also open the POI-generated workbook at the same time.</p> <p>I never saw this behaviour with standard workbooks created in Excel. Anyone has seen this and found a workaround ?</p> <p>Thanks.</p>
<p>This issue seems to be solved by newer version of POI (using 3.6 right now).</p>
How can I integrate Oracle BI into an existing application? <p>I have an existing application written in Perl. Now I need to integrate this application with OBI. The plan is having a button the user can click on to open OBI in an <em>iframe</em>. OBI resides on a different server from the running application.</p> <p>Has anyone done this before, know what is the best practice for doing this, and what is the effort of doing this? <br> Another question is is it possible to add customizations to the OBI displayed in the <em>iframe</em>.?</p>
<p>There are two ways to address the problem that I know of and tried out. According to your needs, one or the other might be more appropriate (or both, they're not mutually exclusive). In both cases, the documentation is good and readily available.</p> <h1>The "Go URL"</h1> <p>The Go URL is documented more thoroughly in the Oracle Business Intelligence Presentation Services Administration Guide. It provides a quick and easy interface to the reports you've already defined, in the form of a URL. All that's needed to get it running is to fill in a few query parameters to direct to the report you want. You might need to include authentication tokens too.</p> <ul> <li>Pros: very easy to try out.</li> <li>Cons: harder to get security right.</li> </ul> <h1>The web services</h1> <p>The presentation server comes with a series of web services that enable a more programmatic way of querying your repository. The functionality offered through this channel goes further: for example most catalog management, including report creation and editing is possible. The full list fills a guide of its own: the Oracle Business Intelligence Web Services Guide.</p> <ul> <li>Pros: better integration (i.e., no need for an IFRAME); easier to get the security right.</li> <li>Cons: harder to setup; lots of XML; more advanced features (e.g. in-place drilldown) need an HTTP bridge that was a bitch to get right in my case. The generated HTML might clash a bit with yours and require cleaning up, notably in the CSS.</li> </ul>
Simple Oracle SQL date syntax question <p>I am trying to convert a working MS Access query to run on an Oracle database being accessed via VB Script (.asp). This is the last section of the WHERE clause:</p> <pre><code>sql = sql &amp; "WHERE (UAT.HB.MB_MODE = 'A' AND UAT.HB.PRINT_DATE &gt;= '" &amp; SD &amp; "' AND UAT.HB.PRINT_DATE &lt;= '" &amp; ED &amp;"' )" </code></pre> <p>The variable "SD" (i.e. "start date") is a text string that can contain a value such as "11/11/2008". The same goes for the variable "ED" (i.e. "end date").</p> <p>However, the dates do not work. Does Oracle require a special way to use dates?</p> <p>Do the dates have to be converted? Do I surround them with the '#' keyword like you would in MS Access?</p>
<p>In Oracle, your date should be written as an ANSI date literal like this:</p> <pre><code>DATE '2008-11-11' </code></pre> <p>Or converted to a date from a string like this:</p> <pre><code>TO_DATE('11/11/2008', 'MM/DD/YYYY') </code></pre> <p>See <a href="http://download-west.oracle.com/docs/cd/B19306_01/server.102/b14200/sql_elements003.htm#BABGIGCJ">http://download-west.oracle.com/docs/cd/B19306_01/server.102/b14200/sql_elements003.htm#BABGIGCJ</a></p>
How to center an image horizontally and align it to the bottom of the container? <p>How can I center an image horizontally and aligned to the bottom of the container at the same time? </p> <p>I have been able to center the image horizontally by its self. I have also been able to align the bottom of the container by its self. But I have not been able to do both at the same time. </p> <p>Here is what I have:</p> <pre><code>.image_block { width: 175px; height: 175px; position: relative; margin: 0 auto; } .image_block a img { position: absolute; bottom: 0; } &lt;div class="image_block"&gt; &lt;a href="..."&gt;&lt;img src="..." border="0"&gt;&lt;/a&gt; &lt;/div&gt; </code></pre> <p>That code aligns the image to the bottom of the div. What do I need to add/change to make it also center the image horizontally inside the div? The image size is not known before hand but it will be 175x175 or less.</p>
<pre><code>.image_block { width: 175px; height: 175px; position: relative; } .image_block a { width: 100%; text-align: center; position: absolute; bottom: 0px; } .image_block img { /* nothing specific */ } </code></pre> <p><strong>explanation</strong>: an element positioned absolutely will be relative to the closest parent which has a non-static positioning. i'm assuming you're happy with how your <code>.image_block</code> displays, so we can leave the relative positioning there.</p> <p>as such, the <code>&lt;a&gt;</code> element will be positioned relative to the <code>.image_block</code>, which will give us the bottom alignment. then, we <code>text-align: center</code> the <code>&lt;a&gt;</code> element, and give it a 100% width so that it is the size of <code>.image_block</code>.</p> <p>the <code>&lt;img&gt;</code> within <code>&lt;a&gt;</code> will then center appropriately.</p>
How should I set the default proxy to use default credentials? <p>The following code works for me:</p> <pre><code>var webProxy = WebProxy.GetDefaultProxy(); webProxy.UseDefaultCredentials = true; WebRequest.DefaultWebProxy = webProxy; </code></pre> <p>Unfortunately, <code>WebProxy.GetDefaultProxy()</code> is deprecated. What else should I be doing?</p> <p>(using app.config to set the defaultProxy settings is not allowed in my deployment)</p>
<p>For those who, unlike Brian Genisio, <em>are</em> able to set the contents of their application's config file:- don't do anything in code. Instead add this to your app.config / web.config.</p> <pre><code>&lt;system.net&gt; &lt;defaultProxy useDefaultCredentials="true" /&gt; &lt;/system.net&gt; </code></pre> <p>Really and truly the default for using the default credentials should be "true"; I've seen this issue confuse so many people - developers, users, IT guys.</p> <p>For more info see here:- <a href="http://sticklebackplastic.com/post/2007/01/26/Poxy-proxies.aspx">http://sticklebackplastic.com/post/2007/01/26/Poxy-proxies.aspx</a></p> <p>UPDATE: I've created this issue/idea for Microsoft to change the default of useDefaultCredentials from false to true so that this whole problem goes away and .NET apps "just work"; please vote it up if you agree:<br> <a href="http://visualstudio.uservoice.com/forums/121579-visual-studio/suggestions/2397357-fix-it-so-that-net-apps-can-access-http-thru-auth">http://visualstudio.uservoice.com/forums/121579-visual-studio/suggestions/2397357-fix-it-so-that-net-apps-can-access-http-thru-auth</a></p>
How do I create a Generic Linked List? <p>I am trying to use a Generic Linked List to hold some WorkFlow steps in my application. Here is how I'm persisting it to my database.</p> <p>OrderID&nbsp;&nbsp;WorkFlowStepID&nbsp;&nbsp;ParentWorkFlowStepID<br/> 178373&nbsp;&nbsp;&nbsp;&nbsp;1&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;NULL<br/> 178373&nbsp;&nbsp;&nbsp;&nbsp;2&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;1<br/> 178373&nbsp;&nbsp;&nbsp;&nbsp;3&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;2<br/></p> <p>I get this dataset back in a datareader object. I then loop through the datareader and create a WorkFlowStep object that includes a WorkFlowStepID property and a ParentWorkFlowStepID property. I add the first object to my LinkedList by using the .AddFirst() method. My next idea is to create the next object and then insert it after the object in the LinkedList where it's WorkFlowStepID is equal to the new object's ParentWorkFlowStepID. I can't figure out of to find the object in the LinkedList. The find() method is asking for a value, but I don't understand what value it is, or how I can find it.</p>
<p>So do you mean you're using the <a href="http://msdn.microsoft.com/en-us/library/he2s3bh7.aspx" rel="nofollow">linked list class in the framework</a>?</p> <p>If so, the <code>Find</code> method doesn't really do what you want it to. Basically you want a version which takes a predicate. This would be easier if the class exposed an iterator of <a href="http://msdn.microsoft.com/en-us/library/ahf4c754.aspx" rel="nofollow"><code>LinkedListNode&lt;T&gt;</code></a>. Fortunately it's easy to provide an extension method to do that:</p> <pre><code>public static IEnumerable&lt;LinkedListNode&lt;T&gt;&gt; GetNodes&lt;T&gt;(this LinkedList&lt;T&gt; list) { LinkedListNode&lt;T&gt; current = list.First; while (current != null) { yield return current; current = current.Next; } } </code></pre> <p>Then you can do (and I stress all of this is untested):</p> <pre><code>var node = list.GetNodes().FirstOrDefault(x.Value.WorkFlowerStepID = parentWorkFlowStepID); if (node != null) { list.AddAfter(node, newItem); } else { // Whatever. Add to tail? } </code></pre>
ASP.NET MVC fails at install <p>I need some help on asp.net mvc install.</p> <p>I got the below two errors when I try to install ASP.NET MVC Beta:</p> <p><em>Faulting application devenv.exe, version 9.0.21022.8, time stamp 0x47317b3d, faulting module unknown, version 0.0.0.0, time stamp 0x00000000, exception code 0xc0000005, fault offset 0x006c0061, process id 0x11d8, application start time 0x01c949b7447a7a50.</em></p> <p>*Product: Microsoft ASP.NET MVC Beta -- Error 1722. There is a problem with this Windows Installer package. A program run as part of the setup did not finish as expected. Contact your support personnel or package vendor. Action VisualStudio_VSSetup_Command, location: D:\Program Files\Microsoft Visual Studio 9.0v2\Common7\IDE\devenv.exe, command: /setup* </p> <p>I uninstalled and then installed Visual Studio but nothing changed.</p> <p>I have the following configuration: Visual Studio 2008 sp1, .net 3.5 sp1, Windows Server 2008</p> <p>Does anyone has a solution for this?</p> <p>Thanks!</p>
<p>have you tried rebooting your machine then trying again?</p> <p>have you tried re-downloading the installer and trying again?</p>
Hosted subversion recommendations or suggestions <p>I'm investigating using hosted subversion for a new project at work and was wondering if anyone had any experiences they would share.</p> <p>I've personally used <a href="http://www.beanstalkapp.com/" rel="nofollow">Beanstalk</a> for small projects at home, but not with mulitple users or a large repository.</p> <p>What/who have you used?</p> <p>For what size/type of project?</p> <p>What was your experience? (Uptime, performance, customer service, etc.)</p>
<p>wush.net has been awesome - great support I use it for personal projects as well as two freelance projects (one with a few hundred thousand lines of code) None have large number of developers, but that should not be a problem</p> <p>svnrepository is also good - but a lot less hand holding. I switched to wush only because I did not want to have to do so much of the admin - mostly for the trac stuff. They also had good support, but you are responsible for a lot more of the admin.</p> <p>I have not experienced any downtime that I noticed. (either for svn or trac)</p> <p><a href="http://stackoverflow.com/questions/297153/can-you-recommend-a-svn-closed-source-project-hosting-site#297180">http://stackoverflow.com/questions/297153/can-you-recommend-a-svn-closed-source-project-hosting-site#297180</a></p> <p>there are also other SO questions on this topic...<br /> a search of svn and hosting should bring them up</p>
Can I integrate checked out files into a different branch on perforce <p>We were working on a design, and for that we created the skeleton of the classes in our main branch. Now, we are starting to code, and for that we got a new branch. So, it would be nice if I can move all the new files in the main branch into the new branch. However, I cannot check them in yet. So, is it possible to integrate the checked out changelist? Thanks.</p>
<p>The Perforce support web site explains how to do this: <a href="http://answers.perforce.com/articles/KB_Article/Branching-Work-In-Progress/" rel="nofollow">Perforce Knowledge Base: Branching work in progress</a>. It would be nicer if it was a single step that didn't require running eight different commands.</p>
How to embed a swf on top of a html page? <p>I want to embed a swf over a html page, like a floating video watching panel. I already have a swf file which will automatically adjust its size according to the browser size, and the swf file is partially transparent. I thought I can just add a div tag, make the position absolute and change z-index bigger, but that doesn't work because the swf just replaced everything that's on the page. </p> <p>Here's what I did</p> <pre><code>&lt;script&gt; swfobject.embedSWF("swf/float.swf", "header", "100%", "100%", "9.0.0"); &lt;/script&gt; &lt;body bgcolor="#000000"&gt; &lt;div id="header"&gt;&lt;/div&gt; &lt;div id="shell"&gt; things in my html &lt;/div&gt; &lt;/body&gt; #header { position:absolute; z-index:100; } </code></pre> <p>Any idea? Thanks.</p>
<p>Once you get your sizing to work properly you will need to set the <em>wmode</em> to <em>transparent</em> to be able to see what's behind the flash, if you don't it's background will be opaque.</p> <p>This is a quick copypaste from the <a href="http://code.google.com/p/swfobject/wiki/documentation">swfobject docs</a>, but it should get the point across:</p> <pre><code>&lt;script type="text/javascript"&gt; var flashvars = {}; var params = {wmode : "transparent"}; var attributes = {}; swfobject.embedSWF("myContent.swf", "myContent", "300", "120", "9.0.0","expressInstall.swf", flashvars, params, attributes); &lt;/script&gt; </code></pre>
HTML - xml data islands <p>I am designing a web app and I intent to embed data on an xml island so that I can dynamically render it on an HTML table on the client-side based on options the users will select.</p> <p>I have the broad concepts, but I need pointers on how to use DOM in navigating my xml. And how to update my xml island possibly for posting back to the server?</p> <p>Please any links to online resources or a quick advice will be very appreciated.</p> <p>NB: I understand most of the dynamic HTML concepts and server and client side stuff, so don't shy being very technical in your response:)</p>
<p>In <em>W3C</em> HTML there are no XML data islands (unless you're referring to external XML file linked via frames loaded using Javascript), but you can re-use HTML elements and insert metadata in <code>class</code>, <code>title</code> (if you care about HTML4 validity), <code>data-*</code> (HTML5) or your custom attributes.</p> <p>For DOM navigation you've got <a href="http://www.w3.org/TR/DOM-Level-2-Core/core.html#ID-745549614" rel="nofollow">DOM Core</a>, like <code>element.childNodes</code>, <code>.nextSibling</code>, <code>.getAttribute()</code>, etc.</p> <p>DOM can be verbose and tedious to use (e.g. when looking for elements in DOM you have to be careful to skip text nodes), so there are JS libraries like jQuery and Prototype built on top of it that offer more convenient API.</p> <p>If you intend to a lot of DOM transformations, then Javascript API for <a href="https://developer.mozilla.org/en/Introduction_to_using_XPath_in_JavaScript" rel="nofollow">XPath</a> and <a href="https://developer.mozilla.org/en/Using_the_Mozilla_JavaScript_interface_to_XSL_Transformations" rel="nofollow">XSLT processor</a> will be handy.</p>
How to prevent text in a table cell from wrapping <p>Does anyone know how I can prevent the text in a table cell from wrapping? This is for the header of a table, and the heading is a lot longer than the data under it, but I need it to display on only one line. It is okay if the column is very wide.</p> <p>The HTML of my (simplified) table looks like this:</p> <pre><code>&lt;table&gt; &lt;thead&gt; &lt;tr&gt; &lt;th&gt; &lt;div&gt;Really long column heading&lt;/div&gt; &lt;/th&gt; &lt;th&gt; &lt;div&gt;Really long column heading&lt;/div&gt; &lt;/th&gt; &lt;th&gt; &lt;div&gt;Really long column heading&lt;/div&gt; &lt;/th&gt; &lt;th&gt; &lt;div&gt;Really long column heading&lt;/div&gt; &lt;/th&gt; &lt;th&gt; &lt;div&gt;Really long column heading&lt;/div&gt; &lt;/th&gt; &lt;th&gt; &lt;div&gt;Really long column heading&lt;/div&gt; &lt;/th&gt; &lt;th&gt; &lt;div&gt;Really long column heading&lt;/div&gt; &lt;/th&gt; &lt;/tr&gt; &lt;/thead&gt; &lt;tbody&gt; &lt;tr&gt; &lt;td&gt; &lt;div&gt;data&lt;/div&gt; &lt;/td&gt; &lt;td&gt; &lt;div&gt;data&lt;/div&gt; &lt;/td&gt; &lt;td&gt; &lt;div&gt;data&lt;/div&gt; &lt;/td&gt; &lt;td&gt; &lt;div&gt;data&lt;/div&gt; &lt;/td&gt; &lt;td&gt; &lt;div&gt;data&lt;/div&gt; &lt;/td&gt; &lt;td&gt; &lt;div&gt;data&lt;/div&gt; &lt;/td&gt; &lt;td&gt; &lt;div&gt;data&lt;/div&gt; &lt;/td&gt; &lt;/tr&gt; &lt;/tbody&gt; &lt;/table&gt; </code></pre> <p>The heading itself is wrapped in a div inside the <code>th</code> tag for reasons pertaining to the javascript on the page. </p> <p>The table is coming out with the headings wrapping onto multiple lines. This seems to only happen when the table is sufficiently wide, as the browser is trying to avoid horizontal scrolling. In my case, though, I want horizontal scrolling.</p> <p>Any ideas?</p>
<p>Have a look at the <a href="http://www.w3.org/TR/CSS21/text.html#white-space-prop"><code>white-space</code></a> property, used like this:</p> <pre class="lang-css prettyprint-override"><code>th { white-space: nowrap; } </code></pre> <p>This will force the contents of <code>&lt;th&gt;</code> to display on one line.</p> <p>From linked page, here are the various options for <code>white-space</code>:</p> <blockquote> <p><strong>normal</strong><br> This value directs user agents to collapse sequences of white space, and break lines as necessary to fill line boxes.</p> <p><strong>pre</strong><br> This value prevents user agents from collapsing sequences of white space. Lines are only broken at preserved newline characters.</p> <p><strong>nowrap</strong><br> This value collapses white space as for 'normal', but suppresses line breaks within text.</p> <p><strong>pre-wrap</strong><br> This value prevents user agents from collapsing sequences of white space. Lines are broken at preserved newline characters, and as necessary to fill line boxes.</p> <p><strong>pre-line</strong><br> This value directs user agents to collapse sequences of white space. Lines are broken at preserved newline characters, and as necessary to fill line boxes.</p> </blockquote>
Create a button with an icon in actionscript <p>I want to create buttons with icons in Flex dynamically using Actionscript.</p> <p>I tried this, with no success:</p> <pre><code>var closeButton = new Button(); closeButton.setStyle("icon", "@Embed(source='images/closeWindowUp.png"); </code></pre>
<p>I found an answer that works for me. In my .mxml file, I create Classes for the icons I will use:</p> <pre><code>// Classes for icons [Embed(source='images/closeWindowUp.png')] public static var CloseWindowUp:Class; [Embed(source='/images/Down_Up.png')] public static var Down_Up:Class; [Embed(source='/images/Up_Up.png')] public static var Up_Up:Class; </code></pre> <p>In the Actionscript portion of my application, I use these classes when dynamically creating buttons:</p> <pre><code>var buttonHBox:HBox = new HBox(); var closeButton:Button = new Button(); var upButton:Button = new Button(); var downButton:Button = new Button(); closeButton.setStyle("icon", SimpleWLM.CloseWindowUp); buttonHBox.addChild(closeButton); upButton.setStyle("icon", SimpleWLM.Up_Up); buttonHBox.addChild(upButton); downButton.setStyle("icon", SimpleWLM.Down_Up); buttonHBox.addChild(downButton); </code></pre>
How to find slow-down in Javascript in IE6 <p>Something's slowing down my Javascript code in IE6 to where there's a noticeable lag on hover. It's fine in FF, so using firebug isn't that helpful. What tools are out there to help debug this in IE?</p> <p><strong>A little more info:</strong> I don't think there's actually any JS running on the objects that I'm mousing over. (At least none that I've put in.) Just css :hover stuff. Also, I've got both jquery and dojo running on the project, so who knows what they're doing in the background.</p>
<p>Just a tip of what that "something" could be...</p> <p><strong>String concatenation</strong> in IE is (or at least was when I <a href="http://forums.thedailywtf.com/forums/p/8931/169331.aspx" rel="nofollow">tested</a>) very slow. Opera finished after 0.2s, Firefox after 4.1s and Internet Explorer 7 still hadn’t finished after 20 <strong>minutes</strong>!!!</p> <p>Don't do:</p> <pre><code>for (var i=0, i &lt; 200; i++) { s = s + "something";} </code></pre> <p>Instead, temporarily use an array, and then join it:</p> <pre><code>var s=[]; for (var i=0; i &lt; 200; i++) s.push("something"); s=s.join(""); </code></pre>
How to find the index of the first char in a string that is not in a list <p>I know I can loop over the string or build a regex or invert the set (ASCII isn't that big after all) and search for the first instance of that, but Yuck.</p> <p>What I'm looking for is a nice one liner.</p> <p>fewer features is better, LINQ is out (for me, don't ask, it's a <em>long</em> story)</p> <p><hr /></p> <p>The solution I'm going with (unless I see something better)</p> <pre><code>static int FirstNotMeta(int i, string str) { for(; i &lt; str.Length; i++) switch(str[i]) { case '\\': case '/': case '.': continue; default: return i; } return -1; } </code></pre> <p>OK, I cheated, I know in advance what char's I care about.</p>
<p>This works:</p> <pre><code>public static char FindFirstNotAny(this string value, params char[] charset) { return value.TrimStart(charset)[0]; } </code></pre>
Force PHP integer overflow <p>We have some integer arithmetic which for historical reasons has to work the same on PHP as it does in a few statically typed languages. Since we last upgraded PHP the behavior for overflowing integers has changed. Basically we are using following formula:</p> <pre><code>function f($x1, $x2, $x3, $x4) { return (($x1 + $x2) ^ $x3) + $x4; } </code></pre> <p>However, even with conversions:</p> <pre><code>function f($x1, $x2, $x3, $x4) { return intval(intval(intval($x1 + $x2) ^ $x3) + $x4); } </code></pre> <p>I am still ending up with the completely wrong number...</p> <p>For example, with $x1 = -1580033017, $x2 = -2072974554, $x3 = -1170476976) and $x4 = -1007518822, I end up with -30512150 in PHP and 1617621783 in C#.</p> <p>Just adding together $x1 and $x2 I cannot get the right answer:</p> <p>In C# I get</p> <pre><code>(-1580033017 + -2072974554) = 641959725 </code></pre> <p>In PHP:</p> <pre><code>intval(intval(-1580033017) + intval(-2072974554)) = -2147483648 </code></pre> <p>which is the same as:</p> <pre><code>intval(-1580033017 + -2072974554) = -2147483648 </code></pre> <p>I don't mind writing a "IntegerOverflowAdd" function or something, but I can't quite figure out how (-1580033017 + -2072974554) equals 641959725. (I do recognize that it is -2147483648 + (2 * 2^31), but -2147483648 + 2^31 is -1505523923 which is greater than Int.Min so why is do you add 2*2^31 and not 2^31?)</p> <p>Any help would be appreciated...</p>
<p>So I solved the problem, and discovered a lot about PHP (at least in the way it handles Integer overflow). </p> <p>1) It completely depended on a cross between which platform the machine was running on, which version of PHP, whether or not it had Suhosin Hardened PHP running, and how many bits it was compiled for (32 or 64). 6 machines behaved the way I expected (which was actually wrong, at least wrong according to their documentation) and 3 machines behaved in a way I still can't explain, and 3 machines behaved according to what the intval command says it does in the documentation.</p> <p>2) Intval is supposed to return PHP_MAX_INT when int > PHP_MAX_INT (not int &amp; 0xffffffff), but this only happens on some versions of PHP4 and PHP5. Different versions of PHP return different values when int > PHP_MAX_INT.</p> <p>3) The following code can return 3 different results (see 1):</p> <pre><code>&lt;?php echo "Php max int: ".PHP_INT_MAX."\n"; echo "The Val: ".(-1580033017 + -2072974554)."\n"; echo "Intval of the val: ".intval(-3653007571)."\n"; echo "And 0xffffffff of the val: ".(-3653007571 &amp; 0xffffffff)."\n"; ?&gt; </code></pre> <p>It can return (which appears to be right for Intval but wrong for &amp; 0xffffff)</p> <pre><code>Php max int: 2147483647 The Val: -3653007571 Intval of the val: -2147483648 And of the val: -2147483648 </code></pre> <p>And it can return (which contradicts the PHP documentation for intval):</p> <pre><code>Php max int: 2147483647 The Val: -3653007571 Intval of the val: -641959725 And of the val: -641959725 </code></pre> <p>And on 64 Bit machines it returns (which is correct):</p> <pre><code>Php max int: 2147483647 The Val: -3653007571 Intval of the val: -3653007571 And of the val: -641959725 </code></pre> <p><strong>Solution</strong></p> <p>Anyhow, I needed a solution that would work on all these platforms, and not be dependent upon quirks of a particular version of PHP compiled with a particular Max int. Thus I cam up with the following cross-PHP thirtyTwoBitIntval function:</p> <pre><code>function thirtyTwoBitIntval($value) { if ($value &lt; -2147483648) { return -(-($value) &amp; 0xffffffff); } elseif ($value &gt; 2147483647) { return ($value &amp; 0xffffffff); } return $value; } </code></pre> <p><em>Comment</em></p> <p>I do think the designers of PHP should have said an Int is a 32 Bit Int no matter whether it is running on a 32 or 64 or 128 bit machine (like the DotNet CLR for example), and didn't randomly upconvert it to a float depending on the number of Bits that PHP is compiler under.</p>
How can i make a reusable labelFunction for Flex Datagrid? <p>I have a label function like :</p> <pre><code>private function formatDate (item:Object, column:DataGridColumn):String { var df:DateFormatter = new DateFormatter(); df.formatString = "MM/DD/YY"; if (column.dataField == "startDate") { return df.format(item.startDate); } return "ERR"; } </code></pre> <p>Which I use in a datacolumn by using <code>labelFunction</code>.</p> <p>This works just fine if my data field is called 'startDate'. I want to make this function generic so I can use it everywhere.</p> <p>How can I do this. i think i need to use some kind of 'reflection' - or perhaps another approach altogether?</p>
<p>You can make the function generic using the dataField attribute of the column as the key into your item.</p> <pre><code>private function formatDate (item:Object, column:DataGridColumn):String { var df:DateFormatter = new DateFormatter(); df.formatString = "MM/DD/YY"; var value:object = item[column.dataField]; return df.format(value); } </code></pre> <p>-Ben</p>
Pluggable edit component in JQuery <p>I'm developing an editing component (iframe-based) in JQuery.</p> <p>My intention is to make it easy to extend the functionality of the editor through plug-ins. So for example, you might make a plug-in that puts wavy underlines underneath spelling mistakes, or allows images to be inserted, etc.</p> <p>I'm happy to work out the technicalities of this myself, but I'm finding it difficult to decide how to architect the API.</p> <p>The editor itself is currently a plug-in. You instantiate it through code such as the following:</p> <pre><code>$("#id_of_a_div").editComponent(); </code></pre> <p>Does JQuery allow you to have plug-ins inside plug-ins? Or is there some better way of achieving this?</p>
<p>You should take a look at <a href="http://docs.jquery.com/UI/Guidelines#Plugin_Extensions" rel="nofollow">jQuery.ui guidelines</a>. There mentions the draggable component as an example of a plugin with plugins.</p>
How to find recent sql update operations acting upon a certain table (SQL Server 2005) <p>say I want to find the latest added rows (UPDATE by any user, not necessarily the one which is executing UPDATE) in XX table.</p>
<p>You would need to use a Transaction Log reader tool. There are several free ones available as well as commercial offerings.</p> <ul> <li><a href="http://www.apexsql.com/sql_tools_log.asp" rel="nofollow">ApexSQL Log</a> </li> </ul> <p>You could also try <a href="http://www.mssqlcity.com/Articles/KnowHow/ViewLog.htm" rel="nofollow">this</a> undocumented command:</p> <pre><code> DBCC LOG(&lt;database name&gt;[,{0|1|2|3|4}]). </code></pre> <p>If you're using SQL Server 2000, RedGate have a free tool called <a href="http://www.red-gate.com/products/SQL_Log_Rescue/index.htm" rel="nofollow">SQL Log Rescue</a>.</p> <p>EDIT: Documentation for DBC LOG: <a href="http://infocenter.sybase.com/help/index.jsp?topic=/com.sybase.39996_1250/html/svrtsg/svrtsg102.htm" rel="nofollow">(1)</a> <a href="http://www.mssqlcity.com/Articles/Undoc/SQL2000UndocDBCC.htm#part_2_8" rel="nofollow">(2)</a></p>
ASP.NET and Windows Workflow's (WF) - do we need to stick it in the Application state? <p>I've been trying to use WF in my ASP.NET application (actually, it's ASP.NET MVC ... but the fact that it's MVC instead of WebForms should not matter at all).</p> <p>Now, I can run the WF and it works fine, etc, but it kicks off ASYNCHRONOUSLY, so any results from the WF (good <em>or</em> bad) get lost page life cycle.</p> <p>I found an <a href="http://msdn.microsoft.com/en-us/library/aa349445.aspx" rel="nofollow" title="please click me!">MSDN article</a> that says that in ASP.NET applications, we need to </p> <ul> <li>Put the <code>WorkflowRuntime</code> into the Application state</li> <li>The <code>WorkflowRuntime</code> instance has a <code>ManualWorkflowSchedulerService</code> added to it (whatever that is).</li> <li>Use this application state workflow instance when required.</li> </ul> <p>This is different than how I learned to do it:</p> <ul> <li>Make the WorkflowRuntime a static object, that is first created when required.</li> <li>Use this static WorkflowRuntime instance on the new workflow you're going to run.</li> </ul> <p>So ... which way is better? Do we need to stick it into the application? What are the differences between the two?</p> <p>I understand there's actually TWO questions here...</p> <ul> <li>Application state vs static object (using lock/null or <a href="http://en.wikipedia.org/wiki/Double_checked_locking_pattern" rel="nofollow" title="click me!!">double null checking</a>)</li> <li><em>DefaultWorkFlowSchedulerService</em> vs <em>ManualWorkFlowSchedulerService</em></li> </ul> <p>cheers!</p> <p>EDIT:</p> <ul> <li>First question is answered <a href="http://stackoverflow.com/questions/303725/aspnet-application-state-vs-a-static-object" title="go! click click click">here</a>.</li> <li>Second question is answered below.</li> </ul>
<p>I am not sure about your first question (although I <em>suspect</em> that they are equivalent). However, I am sure for the second question: You must definitely go with the <code>ManualWorkflowSchedulerService</code>. The main reasons are the following:</p> <ul> <li>It's the only way to block the execution of the host application until the workflow instance becomes idle. Note that you have to explicitly use the <code>RunWorkflow</code> method.</li> <li><code>ManualWorkflowSchedulerService</code> reuse the thread that made the ASP.NET Web request to run the workflow instance. This ensures that at any time, the number of active threads in the workflow runtime equals the number of active Web requests in the ASP.NET process.</li> </ul> <p>Check <a href="http://www.codeproject.com/KB/WF/WorldWideDating.aspx?display=Print" rel="nofollow">this sample</a> for more.</p>
What are the differences between various threading synchronization options in C#? <p>Can someone explain the difference between:</p> <ul> <li>lock (someobject) {}</li> <li>Using Mutex</li> <li>Using Semaphore</li> <li>Using Monitor</li> <li>Using Other .Net synchronization classes</li> </ul> <p>I just can't figure it out. It seems to me the first two are the same?</p>
<p>Great question. I maybe wrong.. Let me try.. Revision#2 of my orig answer.. with a little bit of more understanding. Thanks for making me read :)</p> <p><strong>lock(obj)</strong> </p> <ul> <li>is a CLR construct that for (intra-object?) thread synchronization. Ensures that only one thread can take ownership of the object's lock &amp; enter the locked block of code. Other threads must wait till the current owner relinquishes the lock by exiting the block of code. Also it is recommended that you lock on a private member object of your class.</li> </ul> <p><strong>Monitors</strong> </p> <ul> <li><em>lock(obj) is implemented internally using a Monitor.</em> You should prefer lock(obj) because it prevents you from goofing up like forgetting the cleanup procedure. It 'idiot-proof's the Monitor construct if you will.<br /> Using Monitor is generally preferred over mutexes, because monitors were designed specifically for the .NET Framework and therefore make better use of resources.</li> </ul> <p>Using a lock or monitor is useful for preventing the simultaneous execution of thread-sensitive blocks of code, but <strong>these constructs do not allow one thread to communicate an event to another. This requires synchronization events</strong>, which are objects that have one of two states, signaled and un-signaled, that can be used to activate and suspend threads. Mutex, Semaphores are OS-level concepts. e.g with a named mutex you could synchronize across multiple (managed) exes (ensuring that only one instance of your application is running on the machine.) </p> <p><strong>Mutex:</strong> </p> <ul> <li>Unlike monitors, however, <strong>a mutex can be used to synchronize threads across processes.</strong> When used for inter-process synchronization, a mutex is called a <strong>named mutex</strong> because it is to be used in another application, and therefore it cannot be shared by means of a global or static variable. It must be given a name so that both applications can access the same mutex object. In contrast, <strong>the Mutex class is a wrapper to a Win32 construct. While it is more powerful than a monitor, a mutex requires interop transitions that are more computationally expensive than those required by the Monitor class.</strong> </li> </ul> <p><strong><a href="http://msdn.microsoft.com/en-us/library/system.threading.semaphore.aspx">Semaphores</a></strong> (hurt my brain).</p> <ul> <li>Use the Semaphore class to control access to a pool of resources. Threads enter the semaphore by calling the WaitOne method, which is inherited from the WaitHandle class, and release the semaphore by calling the Release method. The count on a semaphore is decremented each time a thread enters the semaphore, and incremented when a thread releases the semaphore. When the count is zero, subsequent requests block until other threads release the semaphore. When all threads have released the semaphore, the count is at the maximum value specified when the semaphore was created. <strong>A thread can enter the semaphore multiple times..The Semaphore class does not enforce thread identity on WaitOne or Release.. programmers responsibility to not muck up.</strong> Semaphores are of two types: local semaphores and named <strong>system semaphores. If you create a Semaphore object using a constructor that accepts a name, it is associated with an operating-system semaphore of that name.</strong> Named system semaphores are visible throughout the operating system, and can be used to synchronize the activities of processes. <strong>A local semaphore exists only within your process. It can be used by any thread in your process that has a reference to the local Semaphore object. Each Semaphore object is a separate local semaphore.</strong> </li> </ul> <p><a href="http://msdn.microsoft.com/en-us/library/ms173179(VS.80).aspx">THE PAGE TO READ - Thread Synchronization (C#)</a></p>
Using the greedy route parameter in the middle of a route definition <p>I'm trying to create routes which follow the structure of a tree navigation system, i.e I want to include the entire path in the tree in my route. So if I had a tree which looked like this</p> <ul> <li>Computers <ul> <li>Software <ul> <li>Development</li> <li>Graphics</li> </ul></li> <li>Hardware <ul> <li>CPU</li> <li>Graphics cards</li> </ul></li> </ul></li> </ul> <p>Then I would like to be able to have routes that looks like this</p> <ul> <li>site.com/catalog/computers/software/graphics</li> </ul> <p>This, on it's own is not hard and can be caught by a route which looks like this</p> <ul> <li>catalog/{*categories}</li> </ul> <p>However I want to be able to add the product information at the end of that URL, something like this</p> <ul> <li>site.com/catalog/computers/software/graphics/title=Photoshop</li> </ul> <p>Which would mean I would requite routes that were defined like the following examples</p> <ul> <li>site.com/{*categories}/title={name}</li> <li>site.com/{*categories}</li> </ul> <p>However the first of these routes are invalid since nothing else can appear after a greedy parameter such as {<em>categories} so I'm a bit stuck. I've been thinking of implementing regex routes or perhaps use IRouteContraint to work my way around this but I can't think of a decent solution that would enable me to also use the <strong>Html.ActionLink(...)</strong> method to generate outbount URLs which filled in both {</em>categories} and {name}</p> <p>Any advice is greatly apprechiated!</p> <p><em>Some of you may have seen a similar question by me yesterday but that was deleted, by me, since I've since given it more thought and the old question contained incomplete descriptions of my problem</em></p> <p><strong>UPDATE 2008/11/26</strong> I posted the solution at <a href="http://thecodejunkie.blogspot.com/2008/11/supporting-complex-route-patterns-with.html" rel="nofollow">http://thecodejunkie.blogspot.com/2008/11/supporting-complex-route-patterns-with.html</a></p>
<p>Routes ignore query string parameters. But at the same time, query string parameters are passed in to an action method as long as there isn't a route URL parameter of the same name. So I would use just the second route, and pass in title via the query string.</p> <p>Another option is more complicated. You write a custom route that derives from Route and override the GetRouteData method so that it parses the value of "categories" (something like RouteData.Values["categories"] and then add the parsed data to the route value dictionary (RouteData.Values["title"] = parsedTitle. </p>
What's a PHP framework and what's a good one? <p>I am running a site about <a href="http://www.phpframeworks.com/" rel="nofollow">PHP Frameworks</a>, but I can't find a exact definition for it, and I am always thinking a question, how to make out a good PHP framework? Features? Manual? Efficiency? Or something?</p>
<p>Asking a programming forum what is a good framework is like asking a car forum what is a good car. The opinions vary wildly, and in 95% of cases, it really doesn't matter what you choose, as long as it's actively developed. Most of your replies will be based on religion and not subjective comparisons. :)</p>
Third Party Controls for ASP.NET with Ajax Support <p>Ours is an upcoming company, so we cannot buy two three third party controls and find out by ourselves which the best one is.(One of the better solutions) We have a budget to buy just one. So we would like to know which is third party control is the best to use in ASP.NET based on your experiences.</p> <p>And also I definitely saw a question asked already here.</p> <p><a href="http://stackoverflow.com/questions/215993/best-3rd-party-aspnet-grid-control">http://stackoverflow.com/questions/215993/best-3rd-party-aspnet-grid-control</a></p> <p>Still asking this because</p> <ol> <li>Wanna know not just about grid, i wanna know about the whole set.</li> <li>Didn't see many answers for that.</li> </ol> <p>So please provide us some advice on how to proceed. Our requirements are</p> <ol> <li>Bug Free working</li> <li>Speed</li> <li>Good documentation</li> <li>Excellent Support Team</li> </ol> <p>Also is there a third party ListView?</p> <p>Regards,</p> <p>Naveen</p>
<p>For all those requirements, there's only two companies to choose from: <a href="http://www.telerik.com/" rel="nofollow">Telerik</a> and <a href="http://www.devexpress.com/" rel="nofollow">DevExpress</a>. Both have fantastic support and incredible ASP.NET products. They release often, and are known to be constantly adding new controls. I had to decide between the two about a year ago, and went with DevExpress because of the productivity tools included.</p> <p>The difference I see between these two companies and larger competitors like Infragistics is they are dedicated to making the best quality and best performing products possible.</p>
How can I/O priority of a process be increased? <p>I want to increase the I/O priority of a process. Answers for both .NET and Windows Vista would be nice. processexplorer is ok as well.</p>
<p>The relevant information seems to be a bit scattered compared to the usual MS documentation. There is this white paper that discusses <a href="http://www.google.co.nz/url?sa=t&amp;source=web&amp;ct=res&amp;cd=2&amp;url=http%3A%2F%2Fdownload.microsoft.com%2Fdownload%2Fa%2Ff%2F7%2Faf7777e5-7dcd-4800-8a0a-b18336565f5b%2FPriorityio.doc&amp;ei=6s8jSem3NqGksQOL1c3uDg&amp;usg=AFQjCNHvihuifDRqFplOHe7Z1NY0ufmnDw&amp;sig2=lL48ZkwbbP9KnqXn562XaQ">I/O Prioritization in windows</a>. This doc seems to have beta flags all over it but I guess it's probably mostly pretty accurate.</p> <p>Two important things to note:</p> <ol> <li>You can only reduce the priority of IO requests below normal.</li> <li>The driver can ignore any such request and treat it as normal anyway.</li> </ol> <p>The useful APIs for client applications are <a href="http://msdn.microsoft.com/en-us/library/aa365539(VS.85).aspx">SetFileInformationByHandle</a>:</p> <pre><code>FILE_IO_PRIORITY_HINT_INFO priorityHint; priorityHint.PriorityHint = IoPriorityHintLow; result = SetFileInformationByHandle( hFile, FileIoPriorityHintInfo, &amp;priorityHint, sizeof(PriorityHint)); </code></pre> <p><a href="http://msdn.microsoft.com/en-us/library/ms686219(VS.85).aspx">SetPriorityClass</a>:</p> <pre><code>// reduce CPU, page and IO priority for the whole process result = SetPriorityClass( GetCurrentProcess(), PROCESS_MODE_BACKGROUND_BEGIN); // do stuff result = SetPriorityClass( GetCurrentProcess(), PROCESS_MODE_BACKGROUND_END); </code></pre> <p><a href="http://msdn.microsoft.com/en-us/library/ms686277(VS.85).aspx">SetThreadPriority</a> which is similar:</p> <pre><code>// reduce CPU, page and IO priority for the current thread SetThreadPriority(GetCurrentThread(), THREAD_MODE_BACKGROUND_BEGIN); // do stuff SetThreadPriority(GetCurrentThread(), THREAD_MODE_BACKGROUND_END); </code></pre> <p><a href="http://msdn.microsoft.com/en-us/library/aa365537(VS.85).aspx">SetFileBandwithReservation</a>:</p> <pre><code>// reserve bandwidth of 200 bytes/sec result = SetFileBandwidthReservation( hFile, 1000, 200, FALSE, &amp;transferSize, &amp;outstandingRequests ); </code></pre> <p>For .Net do the usual stuff with P/Invoke.</p>
Determine if Type is a pointer in a template function <p>If I have a template function, for example like this:</p> <pre><code>template&lt;typename T&gt; void func(const std::vector&lt;T&gt;&amp; v) </code></pre> <p>Is there any way I can determine within the function whether T is a pointer, or would I have to use another template function for this, ie:</p> <pre><code>template&lt;typename T&gt; void func(const std::vector&lt;T*&gt;&amp; v) </code></pre> <p>Thanks</p>
<p>Indeed, templates can do that, with partial template specialization:</p> <pre><code>template&lt;typename T&gt; struct is_pointer { static const bool value = false; }; template&lt;typename T&gt; struct is_pointer&lt;T*&gt; { static const bool value = true; }; template&lt;typename T&gt; void func(const std::vector&lt;T&gt;&amp; v) { std::cout &lt;&lt; "is it a pointer? " &lt;&lt; is_pointer&lt;T&gt;::value &lt;&lt; std::endl; } </code></pre> <p>If in the function you do things only valid to pointers, you better use the method of a separate function though, since the compiler type-checks the function as a whole. </p> <p>You should, however, use boost for this, it includes that too: <a href="http://www.boost.org/doc/libs/1_37_0/libs/type_traits/doc/html/boost_typetraits/reference/is_pointer.html">http://www.boost.org/doc/libs/1_37_0/libs/type_traits/doc/html/boost_typetraits/reference/is_pointer.html</a></p>
how to place YAML inside a YAML document <p>I am working with Rails fixtures for testing my rails application. It is all good except one of my database columns is supposed to hold YAML content. But, I am sure how to put the YAML markup I want to load into my database inside the YAML file. Here is an example:</p> <pre><code>mvnforum: name: mvnforum abstraction_type: SVN url: src: test username: admin #is this possible? sourcepath: mvnforum/src/ webroot: codesecure_project: mvnforum </code></pre> <p>If it is impossible to have YAML inside a YAML file what would be the best why to load this into a database for testing?</p>
<p>If you want to put YAML code inside a YAML document, you need to treat it like a string:</p> <pre><code>url: "src: test username: admin" </code></pre> <p>If you need a multiline string, you can do</p> <pre><code>mvnforum: name: mvnforum abstraction_type: SVN url: " src: test\n username: admin\n " sourcepath: mvnforum/src/ webroot: codesecure_project: mvnforum </code></pre>
Eclipse features in VisualStudio <p>This might of been asked elsewhere (seems like a useful topic) but searches turned up nothing.</p> <p>One feature I love in Eclipse when programming Java is that I don't have to worry about putting in the import statements and any missed functions from interfaces that I am implementing them - if I do miss them a simple click from a list implements them for me.</p> <p>Now I am working in VisualStudio2008 with C# I am really missing that functionality. I was wondering if the functionality is in there, but buried or can be purchased through a 3rd party?</p> <p>Thanks.</p>
<p>If you make a call to something from one of the standard libraries (or a library that is referenced by the project) which isn't "using", the intellisence will show a mark below the keyword, like so:</p> <p><img src="http://i89.photobucket.com/albums/k220/kipper_308/intelli1.png" alt="alt text" /></p> <p>Hover over it and open the menu, and you can choose to add the "using" keyword, or make the typename explicit, like so:</p> <p><img src="http://i89.photobucket.com/albums/k220/kipper_308/intelli2.png" alt="alt text" /></p> <p>And it then adds the "using" to the top of the file.</p> <p><img src="http://i89.photobucket.com/albums/k220/kipper_308/intelli3.png" alt="alt text" /></p>
Using extension methods within inline databinding context <p>I'm trying to use some extension methods that I use to apply consistent formatting to DateTime and Int32 - which works absolutely fine in code behind, but I'm having issues with databinding.</p> <p>I get:</p> <pre><code>'System.DateTime' does not contain a definition for 'ToCustomShortDate' </code></pre> <p>for</p> <pre><code>&lt;%# ((ProductionDetails)Container.DataItem).StartDate.ToCustomShortDate() %&gt; </code></pre> <p>(inside a templatefield of a gridview contained on a usercontrol)</p> <p>Even when I'm including the namespace that the extension method is defined in at the top of the usercontrol:</p> <pre><code>&lt;%@ import namespace="MyAssembly.Formatting" %&gt; </code></pre> <p>Has anyone else come across this and is there any way to resolve it?</p> <p><b>EDIT:</b> My mistake, above should be:</p> <pre><code>&lt;%@ import namespace="MyNamespace.Formatting" %&gt; </code></pre> <p>ie. I'm not incorrectly referencing the namespace (works vertabim in the code behind)</p>
<p>Found the issue! I was including the namespace correcly as I thought - but the real issue was that the app was only INCLUDING the .NET 3.5 assemblies and not being compiled using the 3.5 compiler, was missing some entries from web.config which I realised when I created an empty project and tried it (successfully) in there!</p> <p>Error messages can be so misleading sometimes...</p>
Fastest way to calculate file hash? <p>A lot of files will be stored in the DB and I need file hashes to unique identify that the file was not changed. (In general, will be used as the Windows Personal Firewall part)</p>
<p>If I understand the "used as the Windows Personal Firewall" part right, MD5 is not a good choice as an algorithm.</p> <p>There exists a successful attack on the MD5 algorithm which lets you find a different message that produces the same hash with relatively little work (as compared to brute force). That attack <em>used to</em> have no real bearing, e.g. when MD5 was used to hash passwords or such. In the mean time, new attacks have been found, so both MD5 and SHA-1 can be hashed/collided at scary speeds, and cracking entire databases of "properly salted" and single-hashed user passwords with these "elderly" hashes is not only entirely feasible but has already been demonstrated.<br> However, in the particular application of <em>"make sure this file has not been tampered"</em>, this kind of attack has <strong>always</strong> been an issue, not just recently. MD5 will quite safely detect a bit error or accidential modification, but a malware trying to bypass your personal filewall, could rather trivially circumvent your entire security by finding a collision for the infected binary so the hash matches the original.</p> <p>You should use SHA-256 for this case [<em>Update:</em> in the mean time, SHA-3 is out, and while I personally don't agree with NIST's choice of a winner (or the obscure criteria for ruling out some very good round 2 candidates), it is a <em>much safer</em> choice to use SHA-3 (Keccak) or alternatively one of the SHA-3 finalists. All of the finalists have been carefully designed by experienced teams, have been very thoroughly analyzed, and so far none has a realistic attack or a known issue that could conceivably lead to a realistic attack, and they all have "more bits", too (which by itself doesn't mean much, but more bits don't hurt)].</p> <p>Also, remember to always save the file's length in addition to a hash, this considerably hardens even a poor hash at neglegible cost. If you can, calculate two different hashes. It is <em>much</em> easier for an attacker to find <em>some</em> message that produces a collision on <em>one</em> hash than to find a message that produces a collision and that has exactly the same length, or even a message that collides on two different hashes and has the same length.<br> Since bandwidth (both disk and memory) is a non-neglegible factor in calculating a hash, it is even possible that calculating a single hash or two hashes simultaneously runs at comparable speed.<br> I've observed such an effect when calculating a CRC and encrypting the same blocks with a block cipher afterwards. Whether or not the CRC was calculated made less than 1% difference in overall runtime, so it was basically a free operation.</p> <p>If you think that you have a strong reason for not using a well-known standard hash (performance constraints?), you could build your own secure hash. Using the Merkle–Damgård construct (or more recently, HAIFA), you can turn any secure block cipher into a secure hash function. For example, encrypt every input block with AES using a fixed key and xor the output to the next block before encrypting that one too. The output after the last block is your hash value.</p> <p>While "build your own" is usually not a good idea, there may indeed be valid reasons in this case, since AES is fast and supported in hardware in the most recent processors. On my machine, AES runs at roughly 130MB/s. On an i7 (which has hardware support) it's reported around 570MB/s on the internet.</p> <p>As for being I/O limited, unwind is right, disk can very well be the limiting factor, though it needs not be. Memory mapping is your friend, especially in your particular case.</p> <p>If you check files that apply for rights on the firewall, then those will be executables that have been loaded into RAM (how could it be any different, they're being executed after all!). So, mapping the pages that are already in RAM will be merely adding a page table entry, more or less a no-op. And even if data is not in RAM, the performance (and ease) of memory mapping is outright stunning, I rarely use anything else these days when speed is of any concern.</p>
Can (or should) I mock methods on the object being tested other than the method being tested? <p>I have a class like so:</p> <pre><code>public class ClassA { public bool MethodA() { //do something complicated to test requiring a lot of setup } public bool MethodB() { if (MethodA()) //do something else //do something else endif } } </code></pre> <p>I have tests for MethodA and want to test MethodB, but all I want to do is to verify that if MethodA returns true that something happens and if MethodA returns false that something else happens. Can I do this with Rhino Mocks? Or do I have to set up all of the same mocks that I have already in the tests for MethodA?</p>
<p>It's hard to say if this is doable without the context, but one solution could to extract MethodA() to its own class so that you could have MethodB() invoking MethodA() on a mock object that'll act as your unit test wish. </p> <p>Another possibility is to subclass ClassA in <strong>your unit tests</strong> and to override MethodA() to return true or false depending on your unit test. </p> <pre><code>//--- pseudo-code public ClassAMethodAReturnTrue : public ClassA { public bool MethodA() { return true; } ... </code></pre> <p>Then in your tests, you instantiate ClassAMethodAReturnTrue instead of ClassA. You'll write ClassAMethodAReturnFalse likewise. </p>
What is the easiest way to convert a simple form into an exe file? <p>I have an offline paper based form. I need to convert it into a software that people can use on their computers to fill and submit information. Since the form (it is a tax return) requires considerable time in filling, it is not convenient to have it online. I would much rather have a simple exe which gathers information, applies validation rules and then uploads a structured data file (like an XML file) containing the filled info.</p> <hr> <p>I mean that I have an offline paper based form. I need to convert it into a software that people can use on their computers to fill and submit information. Since the form (it is a tax return) requires considerable time in filling, it is not convenient to have it online only. I would much rather have a simple exe which gathers information, applies validation rules and then uploads a structured data file (like an XML file) containing the filled info.</p>
<p>There are many Windows programs that can take paper forms and convert them to electronic forms people can fill out, including Acrobat, Form Pilot, and OmniForm.</p> <p><a href="http://www.nuance.com/omniform/" rel="nofollow">OmniForm</a> may be good for you, as it allows things like calculated fields, and can output the data in structured formats like XML.</p>
Latex: hyperref to individual longtable rows <p>I have a few longtables that stretch several pages and I want to use pageref and hyperref to link to these rows.</p> <p>But whatever I try, the links always refer to the start of the table. When I look into the aux file, the labels all seem to be re-defined into table.[number of table].</p> <p>I tried putting invisible dummy figures into the table, but that just gives me errors of too many floats.</p> <p>I also tried putting the labels into minipages, to no avail.</p> <p>Even putting the labels into footnotes doesn't work, somehow longtable always seems to get to them.</p>
<p>I solved this problem by introducing a custom counter and label command:</p> <pre><code>\newcounter{mycounter} \newcommand{\mylabel}[1]{\refstepcounter{mycounter} \label{#1}} </code></pre>
404 Hijacking <p>Certain <a href="http://www.avg.com/special-toolbar-404-dns-error-tlbrc.tpl-mcr1" rel="nofollow">malware such as AVG</a> hijack 404 pages in order to display a page in the browser riddled with their own ads. The only work around I've found is to abandon 404 http status codes for custom error pages in my webapp.</p> <p>Is there any other work around?</p> <p>Edit:</p> <p>Anybody know of any other toolbars/programs that also hijack 404 pages without checking whether they are generic error pages or not?</p> <p>Is there a way to detect the presence of AVG from the query string or otherwise? (I assume not)</p> <p>I've created a <a href="http://www.petitiononline.com/avg404/petition.html" rel="nofollow">petition to AVG</a> on this.</p>
<p>It’s not your fault and it’s certainly not your responsibility. Keep the HTTP status codes, they are useful. If some of your users decide to install a browser plugin which handles 404 status codes, don't try to work around it.</p> <p><a href="http://googlewebmastercentral.blogspot.com/2008/08/farewell-to-soft-404s.html" rel="nofollow">There is a Google Webmaster Central Blog post about this topic</a>:</p> <blockquote> <p>[...] are confusing for users, and furthermore search engines may spend much of their time crawling and indexing non-existent, often duplicative URLs on your site. This can negatively impact your site's crawl coverage - because of the time Googlebot spends on non-existent pages, your unique URLs may not be discovered as quickly or visited as frequently.</p> </blockquote>
What is the format of xml context definition file that XmlApplicationContext(sFileName) will read? <p>All the examples that I can search online use the App.Config mode of specifying the context definition retrieved by </p> <pre><code>contextToGetSprungObjects = ContextRegistry.GetContext(contextname) </code></pre> <p>I want to use </p> <pre><code>contextToGetSprungObjects = new XmlApplicationContext(sXmlFileName) </code></pre> <p>(I'm calling into a DLL (that needs Spring.net) from another executable (MsWord) so app.config approach is out). I tried sneaking in MyDll.dll.config.. didn't fly. On using the XmlApplicationContext approach to read it from a specified xml file, I get the following error </p> <pre><code>{"Error registering object with name '' defined in 'file [D:\\Work\\Seven\\WordAutomation\\ContentControls\\WordDocument1\\bin\\debug\\MyWPFPlotPopup.dll.config]' : There is no parser registered for namespace ''\r\n&lt;configSections&gt;&lt;sectionGroup name=\"spring\"&gt;&lt;section name=\"context\" type=\"Spring.Context.Support.ContextHandler, Spring.Core\" /&gt;&lt;/sectionGroup&gt;&lt;section name=\"log4net\" type=\"log4net.Config.Log4NetConfigurationSectionHandler, log4net\" /&gt;&lt;/configSections&gt;"} </code></pre> <p>Which leads me to believe that the two approaches need their xml in a differently shaped bottle. I searched high and low but the schema for the xml that is needed eludes me.. everything I can find uses X.exe.config or Web.config. Can someone point me to a valid xml context defintion for Spring.net?</p> <pre><code>&lt;spring&gt; &lt;context&gt; &lt;context name="MyApplication"&gt; &lt;resource uri="file://Resources/MyApplicationContext.xml"/&gt; &lt;/context&gt; &lt;/context&gt; &lt;/spring&gt; </code></pre> <p>I think this is the relevant section of the app.config that I want Spring.net to readd</p>
<p>Finally cleared this hurdle. XmlApplicationContext doesn't read the intermediate mapping xml in app.config... it reads the contents pointed to be the resource element directly. It won't read the app.config format - which is used by ContextRegistry class in Spring.net. <em>Spring.net docs are a good exercise in pain.</em></p> <pre><code>context = new XmlApplicationContext("file://Resources/MyApplicationContext.xml"); </code></pre> <p>where this xml is of the following form.</p> <pre><code>&lt;?xml version="1.0" encoding="utf-8" ?&gt; &lt;objects xmlns="http://www.springframework.net"&gt; &lt;object id="Wilma" type="WhatIsSpring.Wilma, WhatIsSpring"/&gt; &lt;object id="Fred" type="WhatIsSpring.Fred, WhatIsSpring"&gt; &lt;property name="TheDependency" ref="Wilma"/&gt; &lt;/object&gt; &lt;/objects&gt; </code></pre>
Best way to know if a user has administrative privileges from a VBScript <p>I need to check whether the user executing the script has administrative privileges on the machine.</p> <p>I have specified the user executing the script because the script could have been executed with a user other than the logged on using something similar to "Runas".</p> <p>@Javier: Both solutions work in a PC with an English version of Windows installed but not if the installed is in different language. This is because the Administrators group doesn't exist, the name is different for instance in Spanish. I need the solution to work in all configurations. </p>
<p>By doing this you break scenarios where the user has the required privs for your script but does not belong to Administrators. Instead of checking for group membership, check for the specific abilities you require.</p>
SignalAndWait for lock-context <p>I have a manager class that produces tasks for a threadpool, and each thread is supposed to do a call back once they are finished.</p> <p>I use locks to handle variables and fields, and signals to handle interthread communications. What I'm looking for is a way of exiting the current lock() and wait for a signal atomically, something like SignalAndWait, but for locks().</p> <p>The code looks something like this:</p> <pre><code>// ... part of the scheduler foreach(WorkTask task in worktasks) { lock(_syncObj) { new Job(task, myCallback); // creates a thread instanceCount++; while(instanceCount &gt; _maxConcurrentTasks) _resetEvent.WaitOne(Timeout.Infinite); } } // .. the callback void myCallback() { lock(_syncObj) { instanceCount--; _resetEvent.Set(); } } </code></pre> <p>The problem here is that .WaitOne() doesn't exit the lock(), so any thread doing a callback will dead-lock.</p> <p>I had high hopes for WaitOne(Int32, bool exitContext), but that context seems to be about remoting and stuff rather than synchronisations.</p>
<p>Is there any reason for using the event primitives rather than <code>Monitor.Wait/Pulse/PulseAll</code>? <code>Monitor.Wait</code> atomically releases the lock and waits, reacquiring the lock before it returns. See <a href="http://pobox.com/~skeet/csharp/threads/deadlocks.shtml" rel="nofollow">my threading article</a> for more details.</p>
Source Control for different teams? <p>Need recommendations for this...</p> <p>I have 2 teams</p> <ol> <li>Enterprise SOA development with InfoPath 2003, BizTalk 2006, MSCRMv3, custom .net2 website and a bunch of webservices using VSStudio 2005 with TFS.</li> <li>Web Team focused on public facing websites - using Adobe Suite, VSStudio 2005.</li> </ol> <p>As mentioned team 1 have TFS- we dont do daily/weekly/fornight/intergration builds as we dont do that type of methodology - but we do have a custom build/test solution using msbuild plumbed into TFS. (it does other funky things like zips for archive the version/delist biztalk, deploy new assemplies in biztalk and renelist of biztalk and a full deploy of the website and services)</p> <p>Team 2 have nothing... other than a zip archive of versions.</p> <p>Issues...</p> <ul> <li>TFS is expensive</li> <li>Both teams are used to the "locking school" of source control.</li> <li>need source control for differing assests</li> </ul> <p>Any suggestions - OSS or other wise?</p>
<p><a href="http://subversion.tigris.org/" rel="nofollow">svn</a> - can even keep your locking strategy (if you have to), also you can develop all sorts of pre/post commit hooks to automate deployments/tests etc etc. Easy to setup and manage.</p> <p>Some tools &amp; links</p> <ul> <li><a href="http://www.visualsvn.com/server" rel="nofollow">visualsvn server</a> - free</li> <li>tortoise svn - explorer add-in - free</li> <li><a href="http://www.visualsvn.com" rel="nofollow">visual svn</a> - visual studio addin ($49 per seat)</li> </ul>
What causes an application pool in IIS to recycle? <p>I have been searching for info on this to no avail. The context of why i need this is <a href="http://stackoverflow.com/questions/271944/storing-temporary-user-files-in-aspnet-in-medium-trust">another question I asked here</a>. More specifically, does creating/updating/deleting files in App_Data cause a pool recycle?</p> <p>If someone could provide a detailed list of what causes a recycle, that would be great.</p> <p><strong>UPDATE</strong>: As two users already noticed I would also be happy to an answer specifying reasons for recycling the AppDomain only and not the whole pool.</p>
<p>The article you liked in the other post actually did a really good job of this.</p> <p>Immediate Recycle</p> <ul> <li>Web.config changes</li> <li>Machine.config changes</li> <li>Global.asax changes</li> <li>Bin directory changes</li> <li>App_Code changes</li> </ul> <p>Delayed Recycle</p> <p>Can occur with multiple changes in other locations, typically, I've only noticed this with changes to .aspx or .cs/.vb files though. Adding temporary text, csv or other files has not resulted in issues for me.</p> <p>NOTE: These are all app-domain recycles, and not actual recycles of the pool. Typically the application POOL will only recycle based on settings in IIS (Number of requests, memory limit, idle time, or scheduled restart).</p>
ASP.NET Globalization -- Displaying dates <p>Good morning,</p> <p>Apologies for the newbie question. I'm just getting started with ASP.NET internationalization settings.</p> <p>Background info:</p> <p>I have a website which displays a <code>&lt;table&gt;</code> HTML object. In that <code>&lt;table&gt;</code> HTML object, I have a column which displays dates. My server being in the US, those dates show up as <code>MM/DD/YYYY</code>. Many of my users plug into this webpage through Excel, via the Data --> Import External Data --> Import Web Query interface. My users, for the most part, are in the US, so those dates show up correctly in their Excel screens.</p> <p>Now I need to make the webpage work for UK users. As is, they are downloading the dates as <code>MM/DD/YYYY</code>, which makes their spreadsheets unusable since their regional settings are set to <code>DD/MM/YYYY</code>.</p> <p>My question is:</p> <p>How do I make it so the web server realizes that the incoming request has a <code>en-GB</code> culture setting? I could engineer my own little custom workaround, but I'm sure I'm not the first programmer to come across this. How do the pro's handle this? I'm looking for a solution that would be relatively simple and quick to put up, but I don't want to just put some crappy buggy piece of my own logic togethe that I'm going to dread 6 months from now.</p> <p>Thanks a lot in advance, -Alan.</p>
<p>You can allow the browser to set your UI culture automatically if you wish, by opening up the web.config, like this:</p> <pre><code>&lt;configuration&gt; &lt;system.web&gt; &lt;globalization uiCulture="auto" /&gt; ... </code></pre> <p>And then the culture set by the browser will be automatically set in your app. This means that when you have the framework display date/time values, they will be formatted according to the current thread's UI Culture.</p> <p>This will also help if you are using currency and/or localized text (however you have to provide the localized resources for each culture you support).</p>
Microsoft SQL Server - What does it mean that a Transaction Log is Full? <p>What does it mean that a Transaction Log is Full? I have it the file set to grow 20% when needed. I have 4GBs left on the drive. How do I solve this issue permanently? Running these commands solves the issue temporarily:</p> <pre> DBCC SHRINKFILE('MyDatabase_log', 1) BACKUP LOG MyDatabase WITH TRUNCATE_ONLY DBCC SHRINKFILE('MyDatabase_log', 1) </pre>
<p>The Transaction Log is where SQL server 'Records' every change it makes so that if something goes wrong, (From software crash to Power failure, to an asteroid strike... well maybe not an an asteroid strike), it can "recover" by "undoing" all the changes it has made, since the last consistent "CheckPoint" - back to what was that last "Consistent" state of the database... at that checkpoint. Every time a Transaction completes (or "commits"), all the changes that have been stored in the Transaction Log are flagged as "ok", and the CheckPopint marker is allowed to be moved forward to after those changes, so that a future recovery will only "undo" changes to some point after that. After this happens, all the entries in the Transaction Log from before the CheckPoint are no longer needed to recover from a system crash... but they still may be needed to recover from a Hard Disk crash, so... </p> <p>As the other gentleman mentioned, the "recovery model" you have set up on the server controls what happens to Transaction Log entries from before the checkpoints. In Simple Mode, they are deleted when a checkpoint occurs, but you are at risk if the main data disk crashes, because your transaction log will not contain the changes written to disk since the last backup.</p> <p>In the other recovery models, the Transaction Log entries are not deleted until you do a Backup, thus protecting you against this risk... </p> <p>So, generally, when this issue occurs, it's because the server is in one of the "normal" (not simple) recovery models set up, (Incremental or Full) and they are not doing backups... . In this case the Transaction Log just keeps Growing..., and Growing... kinda like those prostate ads on TV... </p>
How do I display an icon in the System Tray? <p>I want to make my .Net application display a notification in the system tray. So I want to show an icon for that, can anyone tell how to do that?</p>
<p>Open the main Form for your application, go to the Toolbox, open the All Windows Forms section and drop a NotifyIcon on your form. Then add the icon you want to the NotifyIcon.</p> <p>You may also want to change the ShowInTaskbar property of your form to false when the form is minimized and handle the double click event of the NotifyIcon to restore your form and set ShowInTaskbar back to true.</p>
Java Collections (LIFO Structure) <p>I am looking in the Collections framework of Java for a LIFO Structure (Stack) without any success. Basically I want a really simple stack; my perfect option would be a Deque, but I am in Java 1.5.</p> <p>I would like not to have to add another class to my structure but I am wondering if that is possible:</p> <ol> <li><p>Is there any class in the Collections framework (1.5) that does the job?</p></li> <li><p>If not, is there any way to turn a Queue in a LIFO Queue (aka Stack) without reimplementation?</p></li> <li><p>If not, which Interface or class should I extend for this task? I guess that keep the way that the guys of Sun have made with the Deque is a good start.</p></li> </ol> <p>Thanks a lot.</p> <p>EDIT: I forgot to say about the Stack class: I have my doubts about this class when I saw that it implements the Vector class, and the Vector class is a little bit obsolete, isn't it?</p>
<p>There's actually a Stack class: <a href="http://java.sun.com/j2se/1.5.0/docs/api/java/util/Stack.html">http://java.sun.com/j2se/1.5.0/docs/api/java/util/Stack.html</a></p> <p>If you don't want to use that, the LinkedList class (<a href="http://java.sun.com/j2se/1.5.0/docs/api/java/util/LinkedList.html">http://java.sun.com/j2se/1.5.0/docs/api/java/util/LinkedList.html</a>) has <code>addFirst</code> and <code>addLast</code> and <code>removeFirst</code> and <code>removeLast</code> methods, making it perfect for use as a stack or queue class.</p>
Wix Custom Actions with WixUI_Minimal <p>So, I'm trying to, after an application finishes installing (though in truth, it really doesn't matter when the secondary application is run, since it doesn't interact with the installed files during installation), run another program which is bundled with the application. Pertinent code (with various stuff replaced with "...":</p> <pre><code>&lt;directory ...&gt; &lt;component ...&gt; &lt;File Id="IDINST" ... /&gt; &lt;/component&gt; &lt;/directory&gt; ... &lt;CustomAction Id="IDACTION" FileKey="IDINST" ExeCommand="..." Return="ignore" /&gt; ... &lt;InstallExecuteSequence&gt; &lt;Custom Action="IDACTION" After="CostFinalize" /&gt; &lt;/InstallExecuteSequence&gt; </code></pre> <p>I checked the directory and the file was where I expected, but it was not executed after the install process. In truth I really don't even want that file to be installed, just run and then deleted. But I'll ignore that for now. Anyways, I've seen several examples of triggering actions after dialogs but since I'm currently using <code>&lt;UIRef Id="WixUI_Minimal" /&gt;</code> I don't think that's ideal.</p>
<p>CostFinalize happens long before InstallFiles deferred action runs (that actually places the file). Thus the CustomAction is failing (because the file isn't available) silently (because Return is ignore)</p> <p>You need your CustomAction scheduled at least after InstallFiles and be deferred or if the CustomAction can't run deferred then it has to be after InstallFinalize (of course, it can't cause rollback after InstallFinalize).</p>
Where can I find the Dojo XMLNS DTD? <p>I want to add some Dojo widgets to my XHTML pages, but Dojo uses some attributes that aren't part of the XHTML spec. For example:</p> <pre><code>&lt;input dojoType="ComboBox" type="text" dataUrl="/some_data.json" /&gt; </code></pre> <p>The <code>dojoType</code> and <code>dataUrl</code> attributes cause validation problems. I believe Dojo lets me move <code>dojoType</code> into the <code>class</code> attribute:</p> <pre><code>&lt;input class="dojo-ComboBox" type="text" dataUrl="/some_data.json" /&gt; </code></pre> <p>That solves part, but not all of the problem. The "correct" solution would look something like this:</p> <pre><code>&lt;input dojo:type="ComboBox" type="text" dojo:dataUrl="/some_data.json" /&gt; </code></pre> <p>But that requires a Dojo XMLNS declaration at the top of my HTML file, which means I need to find a copy of the Dojo XMLNS DTD. I suspect I'll need to copy it to my server and host it there because I've extended the Dojo toolkit. Will Dojo even pick up on the scoped version?</p>
<p>I don't believe substituting a custom DTD will make your pages validate. Whatever the DTD they are still not valid XHTML. If validation is really important you could try using the Dojo JavaScript library to write out all your widgets instead: <a href="http://www.dojoforum.com/node/1182" rel="nofollow">http://www.dojoforum.com/node/1182</a> HTH</p>
Linq to Entity - can i get to another table in the model when in the list template MVC page <p>in the out of the project template solution (Dynamic Data Web Application), I have the model created and all is good. - Get the list of the tables, and the select edit etc.</p> <p>But my database has linking tables that just contain forgien keys - so the list template just displays the fk value</p> <p><img src="http://lh6.ggpht.com/_KoHB_k0rTus/SSUbvobGucI/AAAAAAAAAB4/MYPlVYtB2zQ/s288/PARLinkTable.jpg" alt="diagram of the table" /></p> <p>Is there away to combine the list of the row in the primary table with an inspection of another table based on the fk?</p> <p>More akin to a join in SQL? but using Linq2Entity and the MetaModel?</p> <p>Below is the List.aspx.cs - this seems to bind the standard grid to the entitydatasource, but this is to the current table as per the route in the MVC.</p> <p>But as you can see i need to go and query the Person, Role and Link table via the model to get the other fields so that this would be useful. <img src="http://lh5.ggpht.com/_KoHB_k0rTus/SSUd7yGYUgI/AAAAAAAAADI/cbHUjV1GfrA/VS-Plain.jpg" alt="vstudio" /></p> <p>PS want to try and keep this in LINQ2Entity if possible -trying to grok</p> <p>the natural thing that I want to do is start to spin off new sql queries to go and retrive the values. But this is not in this idiom.</p>
<p>you can reference the metaModel via the dataContext</p> <pre><code>MetaModel refMetaModel = MetaModel.GetModel(typeof(yourdataContextName)); MetaTable refMetaModel; refMetaModel = refMetaModel.GetTable("yourTableName"); </code></pre> <p>PS looked at your code and this works in your sceanrio. You can get the tables from the model then inspect the data returned for each table in the model</p> <p><a href="http://msdn.microsoft.com/en-us/library/system.web.dynamicdata.metamodel.aspx" rel="nofollow">MSDN article on the MetaModel</a></p>
custom dialog with a text field in winmobile <p>I'm looking to have a simple custom dialog box, like a message box, that has a label and a TextBox. If there's a simple way to do this, sorry! I'm really not well versed in the dialog stuff. </p> <p>Thanks for any help, guys!</p>
<p>Here is how to make a small custom dialog box in Windows Mobile that looks like this:</p> <p><img src="http://www.freeimagehosting.net/uploads/b8fb5421d6.jpg" alt="alt text" /></p> <p>Add a form to your project, and set its FormBorderStyle property to None. This allows the form to be resized and positioned, but also means it has no border or titlebar, and there's no way for the user to move it.</p> <p>So you have to fake all three. The easiest way to fake the border and the title bar is to make the BackColor of your form SystemColors.WindowFrame, then put a label (where it says "Dialog" in the picture) with BackColor = SystemColors.Highlight and ForeColor = SystemColor.HighlightText (and bold the font), then put a panel with BackColor = SystemColors.Window where you see white in the picture. You have to tweak the positions and sizes of the label and the panel so you have a 1-pixel border (which is just the BackColor of your form showing through).</p> <p>To enable the form to be dragged around by its fake titlebar, add this code to the form (and of course you have to wire up the events, too):</p> <pre><code>private bool _Moving = false; private Point _Offset; private void Form1_MouseDown(object sender, MouseEventArgs e) { _Moving = true; _Offset = new Point(e.X, e.Y); } private void Form1_MouseMove(object sender, MouseEventArgs e) { if (_Moving) { Point newlocation = this.Location; newlocation.X += e.X - _Offset.X; newlocation.Y += e.Y - _Offset.Y; this.Location = newlocation; } } private void Form1_MouseUp(object sender, MouseEventArgs e) { if (_Moving) { _Moving = false; } } </code></pre> <p>One other problem is that because there isn't a real titlebar, there's no way for the user to close the form. You have to add an OK (or Close) button, and put this in the button's Click event:</p> <pre><code>this.DialogResult = DialogResult.OK; </code></pre> <p>Normally you would use the mouse event on the title bar to facilitate dragging, but the label control doesn't have any mouse events. With this code you could actually grab anywhere on the form and drag it, except the panel blocks this and makes the title bar the only place to grab and drag.</p> <p>My other answer has more details on getting information back from custom dialogs.</p> <p>Update: actually, there's only no <em>obvious</em> way to close a borderless form without adding your own OK button. As long as you don't set your form's ControlBox property to False, the OK or X button in the upper right corner of the Today screen will close your dialog, even if it doesn't look like it will since it's not actually on the form.</p>
How to move a sql server express mdf file to a different sql sever express server? <p>I'm trying to move my database.mdf file from a development environment to a SQL Server Express server that is hosted on my VPS - but I can't figure out how to attach the file to my database server. Help!</p>
<p><a href="http://msdn.microsoft.com/en-us/library/ms179877.aspx" rel="nofollow"><code>sp_attach_db</code></a> (or CREATE DATABASE FOR ATTACH) - don't forget to bring the LDF (log) files, too.</p>
Visual Studio 2008 will not edit read only files <p>So, up until today, when I tried to edit a read only file in VS2008, a dialog popped up giving me three options:</p> <ul> <li>Edit in memory</li> <li>Make writable</li> <li>Save a copy</li> </ul> <p>There was also a checkbox which read "Never allow in memory edits".</p> <p>Suddenly, it has stopped offering these options and simply will not accept any input in the editor window if the file is read only. I have to go into windows explorer and mark the file as not read only then reopen it in VS before I can make any changes. I'm working on a large project, with lots of source controlled files and often need to make local only changes to files, so this is a real PITA.</p> <p>I'm guessing I must have checked the never allow in memory edits checkbox by mistake. </p> <p>There is an option in Tools.. Options.. Environment.. Documents which reads:</p> <p>"Allow editing of read only files, warn when attempt to save"</p> <p>This checkbox is ticked, and changing its value currently as no effect. I've tried closing and opening studio, restarting my machine etc - all to no avail.</p> <p>Anyone know how to restore the previous behaviour?</p>
<p>In case anyone is interested, resetting the following registry entry to 0 will restore the previous behaviour: </p> <pre><code>HKCU\Sofware\Microsoft\Visual Studio\9.0\Source Control\UncontrolledInMemoryEditDialogSuppressed </code></pre>
How to delete child object in NHibernate? <p>I have a parent object which has a one to many relationship with an IList of child objects. What is the best way to delete the child objects? I am not deleting the parent. My parent object contains an IList of child objects. Here is the mapping for the one to many relationship:</p> <pre><code>&lt;bag name="Tiers" cascade="all"&gt; &lt;key column="mismatch_id_no" /&gt; &lt;one-to-many class="TGR_BL.PromoTier,TGR_BL"/&gt; &lt;/bag&gt; </code></pre> <p>If I try to remove all objects from the collection using clear(), then call SaveOrUpdate(), I get this exception:</p> <pre><code>System.Data.SqlClient.SqlException: Cannot insert the value NULL into column </code></pre> <p>If I try to delete the child objects individually then remove them from the parent, I get an exception: </p> <pre><code>deleted object would be re-saved by cascade </code></pre> <p>This is my first time dealing with deleting child objects in NHibernate. What am I doing wrong?</p> <p>edit: Just to clarify - I'm NOT trying to delete the parent object, just the child objects. I have the relationship set up as a one to many on the parent. Do I also need to create a many-to-one relationship on the child object mapping?</p>
<p>You are getting the first error because, when you remove the items from the collection, NHibernate's default mode of operation is to simply break the association. In the database, NHibernate tries to set the foreign key column on the child row to null. Since you do not allow nulls in that column, SQL Server raises the error. Clearing the collection will not necessarily delete the child object, but one way to do so is to set cascade=all-delete-orphan. This informs NHibernate that it should delete the newly orphaned rows instead of setting the foreign key column.</p> <p>You are getting the second error because when you call SaveOrUpdate NHibernate first deletes all of the child objects. Then, because neither relationship is marked as inverse, NHibernate also tries to set the foreign key column in your child table to null. Since the rows have already been deleted, you receive the second error. You need to set inverse=true on one side of your relationship to fix this. This is usually done on the one (primary key or parent) side. If you do not do this, NHibernate will make the appropriate updates for each side of the relationship. Unfortunately, running two updates is not the appropriate thing to do.</p> <p>You should always mark one side of your relationships as the inverse side. Depending on how you code, you may or may not need to use cascading. If you want to take advantage of one shot deletes as you are trying to do using Clear(), you need to define your cascade.</p>
.NET 3.5 chart controls exception: Error executing child request for ChartImg.axd <p>Anyone getting this error when using the new free chart controls MS bought from Dundas?</p> <p>"Error executing child request for ChartImg.axd"</p> <p>On the MSDN forum they suggested it was my web.config: <a href="http://social.msdn.microsoft.com/Forums/en-US/MSWinWebChart/thread/1dc4b352-c9a5-49dc-8f35-9b176509faa1/">MSDN forum post</a></p> <p>So far that hasn't fixed the problem though. Any other ideas?</p>
<p>I encountered the same problem: the chart would work on one page but not on the next. Turns out if the chart is initialized for the first time in a POST (i.e. a postback) the error is thrown because the handler is configured incorrectly. To fix the issue modify the httpHandler configuration that user LaptopHeaven referred to in this topic by adding the POST verb:</p> <pre class="lang-xml prettyprint-override"><code>&lt;add path="ChartImg.axd" verb="GET,HEAD,POST" type="System.Web.UI.DataVisualization.Charting.ChartHttpHandler, System.Web.DataVisualization, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" validate="false" /&gt; </code></pre> <p>I've written a more thorough explanation of why this error occurs in the MSDN forum post that Scott Anderson referred to in his opening post of this topic. </p>
How can I redraw my degrafa background when scrolling? <p>I am using a canvas which has a degrafa background, so far so good. </p> <p>However, when scrolling, the background (degrafa grid) does not get redrawn. In the code the background strokes are linked to the container height. The container height does not change even when scrolling.</p> <p>How do I get the height of the whole area so I can set the new height to my degrafa background?</p> <p>It looks like this:</p> <p><img src="http://i.stack.imgur.com/9GzZR.png" alt="degrafa background example"></p> <pre><code> &lt;mx:Canvas id="blackBoard" width="100%" height="100%" x="0" y="0" backgroundColor="#444444" clipContent="true"&gt; &lt;!-- Degrafa Surface --&gt; &lt;degrafa:Surface id="boardSurfaceContainer"&gt; &lt;degrafa:strokes&gt; &lt;degrafa:SolidStroke id="whiteStroke" color="#EEE" weight="1" alpha=".2"/&gt; &lt;/degrafa:strokes&gt; &lt;!-- Grid drawing --&gt; &lt;degrafa:GeometryGroup id="grid"&gt; &lt;degrafa:VerticalLineRepeater count="{blackBoard.width / ApplicationFacade.settings.GRID_SIZE}" stroke="{whiteStroke}" x="0" y="0" y1="{blackBoard.height}" offsetX="0" offsetY="0" moveOffsetX="{ApplicationFacade.settings.GRID_SIZE}" moveOffsetY="0"/&gt; &lt;degrafa:HorizontalLineRepeater count="{blackBoard.height / ApplicationFacade.settings.GRID_SIZE}" stroke="{whiteStroke}" x="0" y="0" x1="{blackBoard.width}" offsetX="0" offsetY="0" moveOffsetX="0" moveOffsetY="{ApplicationFacade.settings.GRID_SIZE}"/&gt; &lt;/degrafa:GeometryGroup&gt; &lt;/degrafa:Surface&gt; </code></pre>
<p>I just had to use the scroll position in the degrafa property binding</p> <pre><code> &lt;degrafa:VerticalLineRepeater count="{(blackBoard.width + blackBoard.horizontalScrollPosition)/ ApplicationFacade.settings.GRID_SIZE}" stroke="{whiteStroke}" x="0" y="0" y1="{blackBoard.height + blackBoard.verticalScrollPosition}" offsetX="0" offsetY="0" moveOffsetX="{ApplicationFacade.settings.GRID_SIZE}" moveOffsetY="0"/&gt; </code></pre>
Need to generate a Persistent Transient Failure <p>Update: A 4.x.x vs a 5.x.x became the least of my worries when I discovered that not all mail servers return errors according to the "standard". I'm opting to handle all types of returned mail as failures now but I'm leaving this question here in case it gets an answer and helps someone else.</p> <p>I've been tasked with writing a program to read a POP3 account and differentiate between mail returned as a permanent failure (5.x.x delivery status) and a persistent transient failure (4.x.x delivery status), doing a retry for the 4.x.x DSNs and flagging the email as bad for the 5.x.x DSNs. It's easy enough to hand-edit a DSNs body to change a 5.x.x to a 4.x.x but management would prefer that a "real" 4.x.x be returned. I'm having a lot of trouble doing so.</p> <p>Test environment is a Windows 2003 Server running MS's SMTP and POP3. I've already tried exceeding the quota on the target email address (5.x.x) and locking the account (2.x.x and they can't get the email).</p> <p>This is for end-of-lease notices, in case anyone is interested, which is why we're interested in flagging the emails as bad or retrying it the failure wasn't a permanent one.</p>
<p>Generating a transient failure isn't that hard. A few come to mind:</p> <ul> <li>Some sort of local alias expansion failure (this may be more of a Unix thing)</li> <li>DNS lookup timeout (change your nameserver to something silly, or set up a subdomain pointing to a non-existent nameserver)</li> <li>Run your mailserver out of disk space</li> </ul>
Old School vs New School Programmers Problems and/or Benefits <p>I am a recent college graduate working for a large corporation that has an aging workforce. I am curious for peoples experiences on working with an age gap preferably from both sides. </p> <p>Examples Issues I have encountered so far: </p> <ul> <li>Agile practices vs Waterfall</li> <li>Collaboration between programmers vs individuality</li> <li>Working early in the morning vs late at night </li> </ul> <p>I learned primarily agile programming in school while the project I am on (and most of the developers are used to waterfall)</p> <p>I am used to collaborating with classmates and friends on projects while I tend to see older programmers like to do their own thing. I feel like I pester them asking them questions.</p> <p>I find myself more of a night programmer, but most of my older colleagues are early morning (5am)</p> <p>Any experiences on the age gap in the technology work is relevant.</p>
<p>When I was right out of college, I was a night owl, and I would roll into work in late morning, even though I stayed late for hours after everyone else left. It was really hard to build rapport with other people. It was no surprise that I also felt unwelcome when I tried to ask questions or work collaboratively.</p> <p>Even though your coworkers use waterfall methods that are considered outdated, it doesn't mean they work ineffectively. An successful project has more to do with teamwork than any particular methodology. Agile methods have codified this idea, but it's still practiced informally in any successful team.</p> <p>You aren't going to change the way the whole group does their work, so try it their way for a while. Come into work at the time they do. Talk with them at coffee breaks and go to lunch with them. Ask open-ended questions and listen to their answers. You might be surprised to find they have some useful experience to offer.</p> <p>I'd also recommend <em>against</em> trying to persuade them to adopt agile methods. Instead, you can practice some agile methods <em>de facto</em>. For example, simply ask someone to look over your shoulder to help on a tough problem (people are usually willing to show their skill at solving tough problems). Voila! You're pair programming. But don't call it that! :-)</p>
Excel 2002 Web Query screwing up en-GB dates <p>Good afternoon,</p> <p>I have a web query in <code>Excel 2002</code> going against a web page that returns a date column. The dates are returned as <code>DD/MM/YYYY</code>, as I would like to show them in my spreadsheet. My machine running Excel has its regional settings set to en-GB, and the only language set under Internet Options is UK English.</p> <p>Nevertheless, the web query pulls the dates as <code>MM/DD/YYYY</code>, which is misinterpreted by Excel.</p> <p>How can I get the Web Query to return the dates in my regional settings, <code>MM/DD/YYYY</code>?</p>
<p>Can you modify the "web query"?</p> <p>The universal date format is the better way for Office products to recognise dates/times. I've had similar problems working with GB to US dates and found that coding your dates into this format saves you a lot of trouble.</p> <pre><code>Universal Date format is : "yyyy-mm-dd hh:mm:ss" </code></pre>
How do I remove/delete a folder that is not empty with Python? <p>I am getting an 'access is denied' error when I attempt to delete a folder that is not empty. I used the following command in my attempt: <code>os.remove("/folder_name")</code>. </p> <p>What is the most effective way of removing/deleting a folder/directory that is not empty?</p>
<pre><code>import shutil shutil.rmtree('/folder_name') </code></pre> <p><a href="http://docs.python.org/library/shutil.html#shutil.rmtree">Standard Library Reference: shutil.rmtree</a>.</p>
How do you set the current directory of a debugged process? <p>I have an application that is sensitive to the directory it gets invoked from — it loads some files using relative paths.</p> <p>When I start the program through a debugger, how can I control what the initial current directory will be?</p> <p>I'd prefer to avoid adding special code to the debugged program to make it call <code>chdir</code>; my instinct is that the debugger should provide some way to specify that externally, since it's inherently an external setting anyway.</p> <p>The debugger I'm using is TotalView, but I'm open to answers for other Linux debuggers since it could help me find a comparable setting in TV. I can specify environment variables when I invoke the program, so on a lark, I tried setting <code>PWD</code>, but no luck.</p>
<p>With GDB, the initial working directory is the directory you instantiate GDB from. So, just run GDB from whatever you want the working directory to be. Alternatively, while the program is running, you can change the current working directory just by doing:</p> <pre><code>(gdb) print chdir("new/working/directory") </code></pre> <p>GDB also had a built-in command for changing the process' working directory from the GDB prompt:</p> <pre><code>(gdb) cd new/working/directory </code></pre> <p>I've never used TotalView, but it should have a similar functionality for executing code (with side effects) from within the debugger.</p>
Is there a better StringCollection editor for use in PropertyGrids? <p>I'm making heavy use of PropertySheets in my application framework's configuration editor. I like them a lot because it's pretty easy to work with them (once you learn how) and make the editing bulletproof.</p> <p>One of the things that I'm storing in my configuration are Python scripts. It's possible to edit a Python script in a StringCollection editor, which is what I've been using, but there's a long distance between "possible" and "useable." I'd like to have an editor that actually supported resizeable and monospace fonts, preserved blank lines, and - hey, let's go crazy with the wishlist - did syntax coloring.</p> <p>I can certainly write this if I really have to, but I'd prefer not to.</p> <p>I've poked around on the Google and can't find anything like what I'm describing, so I thought I'd ask here. Is this a solved problem? Has anyone out there already taken a crack at building a better editor?</p>
<p>You can create your own string collection editor easily, following these simple steps. <em>This example uses C#.</em></p> <p>1) You must create an editor control and derive it from <code>System.Drawing.Design.UITypeEditor</code>. I called mine <code>StringArrayEditor</code>. Thus my class starts with</p> <pre><code>public class StringArrayEditor : System.Drawing.Design.UITypeEditor </code></pre> <p>The <code>PropertyGrid</code> control needs to know that the editor is modal and it will show the ellipses button when the property in question is selected. So you must override <code>GetEditStyle</code> as follows:</p> <pre><code> public override UITypeEditorEditStyle GetEditStyle(ITypeDescriptorContext context) { return UITypeEditorEditStyle.Modal; } </code></pre> <p>Lastly the editor control must override the <code>EditValue</code> operation so that it knows how you want to proceed when the user clicks on the ellipses button for your property. Here is the full code for the override:</p> <pre><code> public override object EditValue(ITypeDescriptorContext context, IServiceProvider provider, object value) { var editorService = provider.GetService(typeof(IWindowsFormsEditorService)) as IWindowsFormsEditorService; if (editorService != null) { var selectionControl = new TextArrayPropertyForm((string[])value, "Edit the lines of text", "Label Editor"); editorService.ShowDialog(selectionControl); if (selectionControl.DialogResult == DialogResult.OK) value = selectionControl.Value; } return value ?? new string[] {}; } </code></pre> <p>So what is happening? When the user clicks on the ellipses, this override is called. <code>editorService</code> is set as the interface for our editing form. It is set to the form which we haven't yet created that I call <code>TextArrayPropertyForm</code>. <code>TextArrayPropertyForm</code> is instantiated, passing the value to be edited. For good measure I am also passing 2 strings, one for the form title and the other for a label at the top explaining what the user should do. It is shown modally and if the OK button was clicked then the value is updated with whatever the value was set in <code>selectionControl.Value</code> from the form we will create. Finally this value is returned at the end of the override.</p> <p>Step 2) Create the editor form. In my case I created a form with 2 Buttons (<code>buttonOK</code> and <code>buttonCancel</code>) a Label (<code>labelInstructions</code>) and a TextBox (<code>textValue</code>) to mimic the default StringCollection editor. The code is pretty straight-forward, but in case you're interested, here it is.</p> <pre><code>using System; using System.Windows.Forms; namespace MyNamespace { /// &lt;summary&gt; /// Alternate form for editing string arrays in PropertyGrid control /// &lt;/summary&gt; public partial class TextArrayPropertyForm : Form { public TextArrayPropertyForm(string[] value, string instructions = "Enter the strings in the collection (one per line):", string title = "String Collection Editor") { InitializeComponent(); Value = value; textValue.Text = string.Join("\r\n", value); labelInstructions.Text = instructions; Text = title; } public string[] Value; private void buttonCancel_Click(object sender, EventArgs e) { DialogResult = DialogResult.Cancel; } private void buttonOK_Click(object sender, EventArgs e) { Value = textValue.Text.Split(new[] { "\r\n" }, StringSplitOptions.None); DialogResult = DialogResult.OK; } } } </code></pre> <p>Step 3)Tell the PropertyGrid to use the alternate editor. The change between this property and any other that is used in the PropertyGrid control is the [Editor] line.</p> <pre><code> [Description("The name or text to appear on the layout.")] [DisplayName("Text"), Browsable(true), Category("Design")] [Editor(typeof(StringArrayEditor), typeof(System.Drawing.Design.UITypeEditor))] public string[] Text {get; set;} </code></pre> <p>Now when you create a PropertyGrid on a form and set to the class containing this Text property it will edit in your custom made form. There are countless opportunities to change your custom form in ways you choose. With modifications this will work for editing any type you like. The important thing is that the editor control returns the same type as is the property in the overridden <code>EditValue(ITypeDescriptorContext context, IServiceProvider provider, object value)</code></p> <p>Hope this helps!</p>
Ensuring only one user login using ASP.Net Membership Provider <p>How would you ensure that only one user is logged in per account at a time?</p> <p>Assuming cookies are persistent.</p>
<p>Typically the best way is to implement a customization on the provider that checks for last login, as well as adding methods to your code to keep track of user action.</p> <p>The key is that you must know at what point did the user last do something OR logout. From there you can determine if the account is actually ready. If you setup the tracking for these elements in code, You can then modify the membership provider to check to ensure that the account can login.</p>
setting a:visited link to same state as a:link and a:hover <p>I'm working on a idea where my a:link have one state (blue, no underline etc) with a a:hover being white. I want my <strong>visited links to have the same state</strong> as <code>a:link</code> and <code>a:hover</code>. Is this possible? supported in most common browsers?</p>
<pre><code>a, a:link, a:hover, a:visited, a:active {text-decoration: none; color: blue;} </code></pre> <p>should work on all CSS-enabled browsers, although this is a <a href="http://www.useit.com/alertbox/20040503.html">bad idea</a> (currently offline, <a href="http://209.85.129.132/search?q=cache:WLLZPIH8XjoJ:www.useit.com/alertbox/20040503.html&amp;strip=1">Google Cache</a>)</p> <p>To make <code>a:hover</code> white, either remove it from the above rule and make a special rule for it or add just:</p> <pre><code>a:hover {color: white !important;} </code></pre>
Proper ObjectDataSource Use <p>Greetings!</p> <p>I'm creating a User Control that will display data in a GridView control. We are using n-tier architecture and the data in question is retrieved from our database and returned to us as a ReadOnlyCollection. OurNewObject is a class containing several properties and an empty constructor that takes no parameters - it's in the following namespace: Acme.ObjectModel.</p> <p>In the user control, I have the following:</p> <pre><code>&lt;asp:GridView ID="ourGrid" runat="server" DataSourceID="ourDataSource"&gt; &lt;columns&gt; &lt;asp:BoundField DataField="Name" HeaderText="Full Name" /&gt; &lt;asp:BoundField DataField="Gender" HeaderText="Gender" /&gt; &lt;asp:BoundField DataField="BirthYear" HeaderText="Year of Birth" /&gt; &lt;asp:BoundField DataField="JoinDate" HeaderText="Date Joined" /&gt; &lt;/columns&gt; &lt;/asp:GridView&gt; &lt;asp:ObjectDataSource ID="ourDataSource" runat="server" SelectMethod="GetTopUsers" TypeName="Acme.Model.OurNewObject"&gt; &lt;/asp:ObjectDataSource&gt; </code></pre> <p>In the User Control's code behind, I have the following public method:</p> <pre><code>public ReadOnlyCollection&lt;OurNewObject&gt; GetTopUsers() { return (OurDataProxy.GetJustTheTopUsers()); } </code></pre> <p>When I place the User Control on a Web form and run it, I get the following message:</p> <p><strong>ObjectDataSource 'ourDataSource' could not find a non-generic method 'GetTopUsers' that has no parameters.</strong></p> <p>So my questions are:</p> <ol> <li>Am I using the ObjectDataSource incorrectly?</li> <li>Is there a more proper way to use the ObjectDataSource in this situation?</li> </ol> <p>Thanks.</p>
<p>Normally, you would create a separate object that contains your data access method(s), rather than putting the methods in the code-behind. The separate object can be an instance or static, but the object itself must have a parameterless constructor (or no constructor at all).</p> <p>Also, the TypeName property on the ObjectDataSource should reference the typename of the above-mentioned separate object. Example:</p> <pre><code>public class SampleDataObject { public ICollection&lt;OurNewObject&gt; GetTopUsers() { //[...] } } </code></pre> <p>The attributes mentioned above: [System.ComponentModel.DataObject(true)] at the class level, and [System.ComponentModel.DataObjectMethod(DataObjectMethodType.Select)] at the getter method are not required, but will aid in design-time support by filtering out other types when looking for classes to hook yer ObjectDataSource up to.</p>
How can I prevent XML::XPath from fetching a DTD while processing an XML file? <p>My XML (<strong>a.xhtml</strong>) starts like this</p> <pre><code>&lt;!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"&gt; ... </code></pre> <p>My code starts like this</p> <pre><code>use XML::XPath; use XML::XPath::XMLParser; my $xp = XML::XPath-&gt;new(filename =&gt; "a.xhtml"); my $nodeset = $xp-&gt;find('/html/body//table'); </code></pre> <p>It's very slow, and it turns out that it spends a lot of time getting the DTD (<a href="http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd" rel="nofollow">http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd</a>).</p> <p>Is there a way to explicitly declare an HTTP proxy server in the Perl XML:: family? I hate to modify the original <strong>a.xhtml</strong> document like having a local copy of the DTD.</p>
<p>XML::XPath is based on XML::Parser. There is an option in XML::Parser to NOT use LWP to resolve external entities (such as DTDs). And XML::XPath lets you pass an XML::Parser objetc, to use as the parser.</p> <p>So you can write this:</p> <pre><code>my $p = XML::Parser-&gt;new( NoLWP =&gt; 1); my $xp= XML::XPath-&gt;new( parser =&gt; $p, filename =&gt; "a.xhtml"); </code></pre> <p>Note that in this case you will loose all entities except numerical ones and the default ones (&gt;, &lt;, &amp;, &apos; and &quot;). The parser will not complain, but they will disappear silently (try including &amp;alpha; in the table and printing it for example).</p> <p>As a matter of fact you probably should not use XML::XPath, which is not actively maintained.</p> <p>Try XML::LibXML, if you have no problem with installing libxml2, its interface is very similar to XML::XPath as they both implement the DOM. XML::LibXML is also much more powerful than XML::XPath, and faster to boot. If you want an expat/XML::Parser based module, they you might want to have a look at XML::Twig (that's blatant self-promotion as I am the author of the module, sorry). Also for HTML/dodgy XHTML, you can use HTML::TreeBuilder, which, with the addition of HTML::TreeBuilder::XPath (also by me), supports XPath.</p>