instruction
stringlengths
0
30k
@Juan Manuel Did you ever work in classic ASP? When you had to program all of your own events and "viewstatish" items (like a dropdown recalling its selected value after form submission)? If so, then ASP.NET MVC will not feel that awkward off the bat. I would check out Rob Conery's Awesome Series "[MVC Storefront][1]" where he has been walking through the framework and building each expected component for a storefront site. It's really impressive and easy to follow along (catching up is tough because Rob has been reall active and posted A LOT in that series). Personally, and quite contrary to Jeff Atwood's [feelings on the topic][2], I rather liked the webform model. It was totally different than the vbscript/classic ASP days for sure but keeping viewstate in check and writing your own CSS friendly controls was enjoyable, actually. Then again, note that I said "liked". ASP.NET MVC is really awesome and more alike other web technologies out there. It certainly is easier to shift from ASP.NET MVC to RAILS if you like to or need to work on multiple platforms. And while, yes, it is very stable obviously (this very site), if your company disallows "beta" software of any color; implementing it into production at the this time might be an issue. [1]: http://blog.wekeroad.com/mvc-storefront/ [2]: https://stackoverflow.fogbugz.com/default.asp?W24212
Honestly I think it depends on the discipline of the developers. I use Subversion for my personal work and I've used it at a few jobs. What I like about Subversion is I don't have to hunt someone down and ask them why they're working on something and if it would be OK for me to do some work. The problem comes when someone decides to start working on something and doesn't check it in for a while; this can make merging difficult as several changes get made between their check-out and check-in. I use Perforce right now and for some reason I like SVN better. Perforce definitely gives me a better indication that there's going to be merge conflicts, and even has built-in tools to help me resolve the merges. It has the same problem where if someone makes tons of changes over a long time, the merge will be more difficult. Basically both models require you to check in changes often. If you make numerous check-ins, then you reduce the likelihood that you'll require a merge. I'm guilty of keeping stuff checked out for too long way too often. Personally I feel like SVN's price tag makes up for anything it lacks compared to Perforce; I haven't found a difference between them yet.
I know almost nothing about linq. I'm doing this: var apps = from app in Process.GetProcesses() where app.ProcessName.Contains( "MyAppName" ) && app.MainWindowHandle != IntPtr.Zero select app; Which gets me all the running processes which match that criteria. But I don't know how to get the first one. The examples I can find on the net seem to imply I have to do this var matchedApp = (from app in Process.GetProcesses() where app.ProcessName.Contains( "MyAppName" ) && app.MainWindowHandle != IntPtr.Zero select app).First(); which strikes me as somewhat ugly, and also throws an exception if there are no matching processes. Is there a better way? **UPDATE** I'm actually trying to find the first matching item, and call `SetForegroundWindow` on it I've come up with this solution, which also strikes me as ugly and awful, but better than above. Any ideas? var unused = from app in Process.GetProcesses() where app.ProcessName.Contains( "MyAppName" ) && app.MainWindowHandle != IntPtr.Zero select SetForegroundWindow( app.MainWindowHandle ); // side-effects in linq-query is technically bad I guess
One useful strategy to keep in mind might be the [composite pattern][1]. At a low level, it might allow you to treat all GUI objects (and collections of objects) more easily once built. But I have no idea what's involved in GUI framework design, so one place to find general inspiration is in the source code of an existing project. [WxWidgets][2] is a cross-platform GUI framework with source available. Good luck with your project! [1]: http://en.wikipedia.org/wiki/Composite_pattern [2]: http://www.wxwidgets.org/downloads/
Assuming that in your first example apps is an IEnumerable<Process> you could make use of the .Count and .FirstOrDefault properties to get the single item that you want to pass to SetForegroundWindow. var apps = from app in Process.GetProcesses() where app.ProcessName.Contains( "MyAppName" ) && app.MainWindowHandle != IntPtr.Zero select app; if (apps.Count > 0) { SetForegroundWindow(apps.FirstOrDefault().MainWindowHandle ); }
I found Ted Jensen's "Tutorial on Pointers and Arrays in C" an excellent resource for learning about pointers. It is divided into 10 lessons, beginning with an explanation of what pointers are (and what they're for) and finishing with function pointers. <http://home.netcom.com/~tjensen/ptr/cpoint.htm> Moving on from there, Beej's Guide to Network Programming teaches the Unix sockets API, from which you can begin to do really fun things. <http://beej.us/guide/bgnet/>
I think looking at the way other GUI toolkits have done it would be an excellent place to start. For C++ examples, I hear lots of good things about [Qt][1]. I haven't used it personally though. And of course WxWidgets as Nick mentioned. [1]:http://trolltech.com/products/qt/
@FryHard FirstOrDefault will work but remember that it returns null if none are found. This code isn't tested but should be close to what you want: var app = Process.GetProcesses().FirstOrDefault(p => p.ProcessName.Contains("MyAppName") && p.MainWindowHandle != IntPtr.Zero); if (app == null) return; SetForegroundWindow(app.MainWindowHandle);
Well, you can already lock up a browser and *seriously* slow down a system with badly-behaved JS. Enlightened browsers have implemented checks for this sort of thing, and will stop it before it gets out of hand. I would tend to assume that threads would be dealt with in a similar manner.
Well, you can already lock up a browser and *seriously* slow down a system with badly-behaved JS. Enlightened browsers have implemented checks for this sort of thing, and will stop it before it gets out of hand. I would tend to assume that threads would be dealt with in a similar manner. --- Perhaps you could explain what you mean by "undefined behavior" then? An interpreter that allowed untrusted script to *directly* control the number of OS-native threads being run would be *incredibly* naive - i don't know how Gears runs things, but since the API is centered around `Worker`s in `WorkerPool`s, i would be very surprised if they aren't limiting the total number of native threads in use to some very low number.
I would probably use struct as the type, and then throw an exception if it isn't an Enum type. I don't see how your (Type, string) option is any safer than using object or struct.
**Install the ASP.NET AJAX Control Toolkit** Download the ZIP file AjaxControlToolkit-Framework3.5SP1-DllOnly.zip from the ASP.NET AJAX Control Toolkit Releases page of the CodePlex web site. Copy the contents of this zip file directly into the bin directory of your web site. http://www.codeplex.com/AjaxControlToolkit/Release/ProjectReleases.aspx?ReleaseId=16488 **Update web.config** Put this in your web.config under the <controls> section <add tagPrefix="ajaxtoolkit" namespace="AjaxControlToolkit" assembly="AjaxControlToolKit"/> **Configure Visual Studio** Right-click on the Toolbox and select "Add Tab", and add a tab called "AJAX Control Toolkit" Inside that tab, right-click on the Toolbox and select "Choose Items..." When the "Choose Toolbox Items" dialog appears, click the "Browse..." button. Navigate to your project's "bin" folder. Inside that folder, select "AjaxControlToolkit.dll" and click OK. Click OK again to close the Choose Items Dialog. You can now use the controls in your web sites!
**Install the ASP.NET AJAX Control Toolkit** 1. Download the ZIP file AjaxControlToolkit-Framework3.5SP1-DllOnly.zip from the [ASP.NET AJAX Control Toolkit Releases][1] page of the CodePlex web site. 2. Copy the contents of this zip file directly into the bin directory of your web site. **Update web.config** 3. Put this in your web.config under the &lt;controls&gt; section: <?xml version="1.0"?> <configuration> ... <system.web> ... <pages> ... <controls> ... <add tagPrefix="ajaxtoolkit" namespace="AjaxControlToolkit" assembly="AjaxControlToolKit"/> </controls> </pages> ... </system.web> ... </configuration> **Setup Visual Studio** 4. Right-click on the Toolbox and select "Add Tab", and add a tab called "AJAX Control Toolkit" 5. Inside that tab, right-click on the Toolbox and select "Choose Items..." 6. When the "Choose Toolbox Items" dialog appears, click the "Browse..." button. Navigate to your project's "bin" folder. Inside that folder, select "AjaxControlToolkit.dll" and click OK. Click OK again to close the Choose Items Dialog. You can now use the controls in your web sites! [1]: http://www.codeplex.com/AjaxControlToolkit/Release/ProjectReleases.aspx?ReleaseId=16488
Here's my html-light version: <script type="text/javascript"> function switchTo(index) { $('#switches li').css('font-weight', 'normal'); $('#switches li').eq(index).css('font-weight', 'bold'); $('#slides div').css('display', 'none'); $('#slides div').eq(index).css('display', 'block'); } function switchover(event) { switchTo($('#switches li').index(event.target)); } $(document).ready(function(){ $('#switches li').mouseover(switchover); switchTo(0); }); </script> <ul id="switches"> <li>First slide</li> <li>Second slide</li> <li>Third slide</li> <li>Fourth slide</li> </ul> <div id="slides"> <div>Well well.</div> <div>Oh no!</div> <div>You again?</div> <div>I'm gone!</div> </div> This has the advantage of showing all the slides if the user has javascript turned off, uses very little HTML markup and the javascript is pretty readable.
Here's my html-light version: <script type="text/javascript" src="jquery.js"></script> <script type="text/javascript"> function switchTo(index) { $('#switches li').css('font-weight', 'normal'); $('#switches li').eq(index).css('font-weight', 'bold'); $('#slides div').css('display', 'none'); $('#slides div').eq(index).css('display', 'block'); } function switchover(event) { switchTo($('#switches li').index(event.target)); } $(document).ready(function(){ $('#switches li').mouseover(switchover); switchTo(0); }); </script> <ul id="switches"> <li>First slide</li> <li>Second slide</li> <li>Third slide</li> <li>Fourth slide</li> </ul> <div id="slides"> <div>Well well.</div> <div>Oh no!</div> <div>You again?</div> <div>I'm gone!</div> </div> This has the advantage of showing all the slides if the user has javascript turned off, uses very little HTML markup and the javascript is pretty readable.
Here's my html-light version: <script type="text/javascript" src="jquery.js"></script> <script type="text/javascript"> function switchTo(index) { $('#switches li').css('font-weight', 'normal'); $('#switches li').eq(index).css('font-weight', 'bold'); $('#slides div').css('display', 'none'); $('#slides div').eq(index).css('display', 'block'); } function switchover(event) { switchTo($('#switches li').index(event.target)); } $(document).ready(function(){ $('#switches li').mouseover(switchover); switchTo(0); }); </script> <ul id="switches"> <li>First slide</li> <li>Second slide</li> <li>Third slide</li> <li>Fourth slide</li> </ul> <div id="slides"> <div>Well well.</div> <div>Oh no!</div> <div>You again?</div> <div>I'm gone!</div> </div> This has the advantage of showing all the slides if the user has javascript turned off, uses very little HTML markup and the javascript is pretty readable. A less-readable but shorter version of the script part: function switchTo(i) { $('#switches li').css('font-weight','normal').eq(i).css('font-weight','bold'); $('#slides div').css('display','none').eq(i).css('display','block'); } $(document).ready(function(){ $('#switches li').mouseover(function(event){ switchTo($('#switches li').index(event.target)); }); switchTo(0); }); This shorter version defines the mouseover function in-place and takes advantage of the "chainability" of jQuery objects.
- I would use a minor variation in the second union: where (ISNULL(feed_tbl.name, 'NONAME') <> ISNULL(data_tbl.name, 'NONAME')) OR (ISNULL(data_tbl.status, 'NOSTATUS') <> ISNULL(feed_tbl.status, 'NOSTATUS')) OR (ISNULL(data_tbl.update, '12/31/2039') <> ISNULL(feed_tbl.update, '12/31/2039')) For reasons I have never understood, NULL does not equal NULL (at least in SQL Server).
Agree with Frank here, there's not a problem with static (global) functions (of course providing they are organised).. The problems only start to really creep in when people think "oh I will just make the scope on this bit of data a little wider".. Slippery slope :)
Agree with Frank here, there's not a problem with static (global) functions (of course providing they are organised).. The problems only start to really creep in when people think "oh I will just make the scope on this bit of data a little wider".. Slippery slope :) To put it really into perspective.. [Functional Programming](http://en.wikipedia.org/wiki/Functional_programming) ;)
Visual Assist X. Spell checks your comments and a whole lot more. [http://www.wholetomato.com/][1] [1]: http://www.wholetomato.com/
Regex (C#): Replace \n with \r\n
|c#|regex|
How can I replace lone instances of \n with \r\n (LF alone with CRLF) using a regular expression in C#? Sorry if it's a stupid question, I'm new to Regex. I know to do it by: myStr.Replace("\n", "\r\n"); myStr.Replace("\r\r\n", "\r\n"); But this is inelegant, and would destroy any "\r+\r\n" already in the text (not that it's likely to be there).
For more of this kind of silliness see this nice article pertaining to Windows calculator. [When you change the insides, nobody notices](http://blogs.msdn.com/oldnewthing/archive/2004/05/25/141253.aspx)
For more of this kind of silliness see this nice article pertaining to Windows calculator. [When you change the insides, nobody notices](http://blogs.msdn.com/oldnewthing/archive/2004/05/25/141253.aspx) > The innards of Calc - the arithmetic > engine - was completely thrown away > and rewritten from scratch. The > standard IEEE floating point library > was replaced with an > arbitrary-precision arithmetic > library. This was done after people > kept writing ha-ha articles about how > Calc couldn't do decimal arithmetic > correctly, that for example computing > 10.21 - 10.2 resulted in 0.0100000000000016.
Setting up replicated repositories in Plastic SCM
|plasticscm|repository|version-control|distributed|
So we're trying to set up replicated repositories using PlasticSCM, one in the US, and one in Australia and running into a bit of a snag. The US configuration is Active Directory, the AU configuration is User/Password. This in itself is not a big deal, I've already set up the SID translation table. The problem is with plasticscm's replicate command itself. This is the command which should replicate from the US to AU, run ON the AU server. cm replicate br:/main@rep:default@repserver:US:8084 rep:myrep@repserver:AU:9090 --trmode=name --trtable=trans.txt --authdata=ActiveDirectory:192.168.1.3:389:john.doe@factory.com:fPBea2rPsQaagEW3pKNveA==:dc=factory,dc=com The part I'm stuck at is the authdata part (the above is an EXAMPLE only). How can I generate the obscured password? I think it's the only thing preventing these two repositories from talking to each other.
I often use this little snippet I've written long time ago. It's short and easy to add anywhere when debugging etc... #include <ctype.h> #include <stdio.h> void hexdump(void *ptr, int buflen) { unsigned char *buf = (unsigned char*)ptr; int i, j; for (i=0; i<buflen; i+=16) { printf("%06x: ", i); for (j=0; j<16; j++) if (i+j < buflen) printf("%02x ", buf[i+j]); else printf(" "); printf(" "); for (j=0; j<16; j++) if (i+j < buflen) printf("%c", isprint(buf[i+j]) ? buf[i+j] : '.'); printf("\n"); } }
You'll need to instance a [`ResourceManager`](http://msdn.microsoft.com/en-us/library/aa984408%28VS.71%29.aspx) for the `Login.resx`: var resman = new System.Resources.ResourceManager( "RootNamespace.Login", System.Reflection.Assembly.GetExecutingAssembly() ) var text = resman.GetString("resname"); It might help to look at the generated code in the code-behind files of the resource files that are created by the IDE. These files basically contain readonly properties for each resource that makes a query to an internal resource manager.
I've worked with Word documents in SVN. With [TortoiseSVN](http://tortoisesvn.tigris.org/), you can easily diff Word documents (between working copy and repository, or between two repository revisions). It's really slick and definitely recommended. The other thing to do if you're using Word documents in SVN is to add the [svn:needs-lock](http://svnbook.red-bean.com/en/1.2/svn.advanced.locking.html) property to the Word documents. This will prevent two people from trying to edit the same document at the same time, since unfortunately there's no good way to merge Word documents. With the above two things, handling revision controlled Word documents is at least tolerable. It certainly beats the alternative of using a shared folder and track-changes.
How to bring in a web app
|web-applications|beta|launching|
I run a game and the running is done by hand, I have a few scripts that help me but essentially it's me doing the work. I am at the moment working on web app that will allow the users to input directly some of their game actions and thus save me a lot of work. The problem is that I'm one man working on a moderately sized (upwards of 20 tables) project, the workload isn't the issue, it's that bugs will have slipped in even though I test as I write. So my question is thus two-fold. 1. Beta testing, I love open beta's but would a closed beta be somehow more effective and give better results? 2. How should I bring in the app? Should I one turn drop it in and declare it's being used or should I use it alongside the normal construct of the game? Thanks for your time and help.
> Thinstall is great for single apps, but not an entire stack.... I didn't try it yet, but with the new version of thinstall you are able to let different thinstalled application communicate. But I guess you're right a vm-ware image would be easier
We're talking about C++ right? Why on earth are we still using macros!? C++ inline functions give you the same speed as a macro, with the added benefit of type-safety and parameter evaluation (which avoids the issue that Rodney and dwj mentioned. inline const char * const BoolToString(bool b) { return b ? "true" : "false"; } Aside from that I have a few other gripes, particularly with the accepted answer :) // this is used in C, not C++. if you want to use printf, instead include <cstdio> //#include <stdio.h> // instead you should use the iostream libs #include <iostream> // not only is this a C include, it's totally unnecessary! //#include <stdarg.h> // Macros - not type-safe, has side-effects. Use inline functions instead //#define BOOL_STR(b) (b?"true":"false") inline const char * const BoolToString(bool b) { return b ? "true" : "false"; } int main (int argc, char const *argv[]) { bool alpha = true; // printf? that's C, not C++ //printf( BOOL_STR(alpha) ); // use the iostream functionality std::cout << BoolToString(alpha); return 0; } Cheers :)
Here's my light-markup jQuery version: <script type="text/javascript" src="jquery.js"></script> <script type="text/javascript"> function switchTo(i) { $('#switches li').css('font-weight','normal').eq(i).css('font-weight','bold'); $('#slides div').css('display','none').eq(i).css('display','block'); } $(document).ready(function(){ $('#switches li').mouseover(function(event){ switchTo($('#switches li').index(event.target)); }); switchTo(0); }); </script> <ul id="switches"> <li>First slide</li> <li>Second slide</li> <li>Third slide</li> <li>Fourth slide</li> </ul> <div id="slides"> <div>Well well.</div> <div>Oh no!</div> <div>You again?</div> <div>I'm gone!</div> </div> This has the advantage of showing all the slides if the user has javascript turned off, uses very little HTML markup and the javascript is pretty readable. The "switchTo()" function takes an index number of which &lt;li&gt; / &lt;div&gt; pair to activate, resets all the relevant elements to their default styles (non-bold for list items, display:none for the divs) and the sets the desired list-item and div to bold and display. As long as the client has javascript enabled, the functionality will be exactly the same as your original example.
I know this is going to be heresy for a cygwin user, but you could just use [PuTTY][1] instead. [1]: http://www.chiark.greenend.org.uk/~sgtatham/putty/
Always use nvarchar. You may never need the double-byte characters for most applications. However, if you need to support double-byte languages and you only have single-byte support in your database schema it's really expensive to go back and modify throughout your application. The cost of migrating one application from varchar to nvarchar will be much more than the little bit of extra disk space you'll use in most applications.
As far as I know this is not possible. You **might** be able to do it if you use uncompressed wave files already encoded in DTS or something and put a surround receiver in between. This will however stop you from doing anything with the sound before outputting it, not even changing the volume. And I guess that's not an option? I think going with an external application for sound would be your best choice, maybe you can do something using Director.
The question is ill-posed in the standard [ZFC][1] (Zermelo-Fraenkel + axiom of Choice) set theory because the object thus defined is not a set. Since (again, assuming standard ZFC) your _class_ {x : x\not\in x} is not a set, the answer becomes no, it's not an element of itself (even as a class) since only sets can be elements of classes or sets. By the way, as soon as you agree to the [axiom of foundation][2], no set can be an element of itself. Of course the nice thing about math is you can choose whichever axioms you want :) but believing in paradoxes is just weird. [1]: http://en.wikipedia.org/wiki/Zermelo-Fraenkel_set_theory [2]: http://en.wikipedia.org/wiki/Axiom_of_foundation
How can I change the way my Drupal theme displays the front page
|css|drupal|themes|
Here are the rules for the types that can be included as Attribute parameters: <http://tinyurl.com/59blgw>
Best way to pass a large number of arguments into a configuration dialog
|c#|
I've got a situation where I have a main form that pops up an advanced configuration form that just has half a dozen matched check boxes and combo boxes to select some advanced options (the check boxes to enable/disable, the combo to select a media if enabled). If I just pass the individual settings for the check and combo boxes in to the constructor for the dialog that's obviously a dozen arguments, which seems a bit excessive. My other obvious option would be since in the main form these settings are stored in a large IDictionary with all the other main form settings I could just pass this dictionary in and fetch it back afterward with the updated values, but my understanding is that this wouldn't really be very good coding practice. Am I missing a good way to do this that is both efficient and good coding practice? (this particular code is in C#, although I have a feeling a general solution would apply to other languages as well)
You really need to use a memory profiler that tracks allocations. Take a look at [JProfiler][1] - their "heap walker" feature is great, and they have integration with all of the major Java IDEs. It's not free, but it isn't that expensive either ($499 for a single license) - you will burn $500 worth of time pretty quickly struggling to find a leak with less sophisticated tools. [1]: http://www.ej-technologies.com/products/jprofiler/overview.html
Check out this LGPL project. I know it can set foreground for a window. Otherwise aku is correct. It'll require most likely some pinvoke calls. http://mwinapi.sourceforge.net/ If you need information on pinvoke use: http://www.pinvoke.net/
I'm a bit confused, I'm not being flippant -- you say you want to return exceptions serialised as XML on the one hand and that the user will never see the exceptions on the other hand. Who will be seeing these exceptions? Normally I'd say to use WCF fault contracts.
It turns out that the answer was easier than I expected. There is a `--batch` parameter missing, gpg tries to read from /dev/tty that doesn't exist for cron jobs. To debug that I have used `--exit-on-status-write-error` param. But to use that I was inspired by exit status 2, reported by echoing `$?` as Cd-Man suggested.
I personally would create a carrier object to store the values. You then get the nice intellisense for it, and changes to it would be quite straightforward. It would also be faster than dictionary lookups for parameter values. And of course, you get type safety. :)
Personally, I use a set of methods I have developed for bridging the server-side ASP.NET "magic" (I have yet to use the MS MVC stuff yet) and my client-side code because of the munging of the IDs that happens. Here is just one that may or may not prove useful: public void RegisterControlClientID(Control control) { string variableDeclaration = string.Format("var {0} = \"{1}\";", control.ID, control.ClientID); ClientScript.RegisterClientScriptBlock(GetType(), control.ID, variableDeclaration, true); } So, in your server-side code you simply call this and pass in the instance of a control for which you want to use a friendlier name for. In other words, during **design time**, you may have a textbox with the ID of "m_SomeTextBox" and you want to be able to write your JavaScript using that same name - you would simply call this method in your server-side code: RegisterControlClientID(m_SomeTextBox); And then on the client the following is rendered: var m_SomeTextBox = "ctl00_m_ContentPlaceHolder_m_SomeTextBox"; That way all of your JavaScript code can be fairly ignorant of what ASP.NET decides to name the variable. Granted, there are some caveats to this, such as when you have multiple instances of a control on a page (because of using multiple instances of user controls that all have an instance of m_SomeTextBox within them, for example), but generally this method may be useful for your most basic needs.
From some of the initial research it doesn't appear to be a super simple solution. It appears that doing this involves having Visual Studio 2008 actually installed on the continuous integration server, which could be a deal breaker. Then configure the MSTest.exe to run in the tasks list, but first you'll have to make a batch file to delete the results files from previous passes as this file's existence causes an error. Then create a xslt to format the results and put it into the dashboard.config file. The code project article I found has a lot more detail. [http://www.codeproject.com/KB/tips/VSTS2008_Tests_With_CCNET.aspx][1] [1]: http://www.codeproject.com/KB/tips/VSTS2008_Tests_With_CCNET.aspx
You should be able to check out the current version of the code and then create a git repository around it. Updating that and committing it to your local git repository should be painless. As should cloning it. The only catch is that you need to have them both ignore each other (I've done something similar with SVN) by messing with the appropriate ignore files. I'm presuming SourceSafe let's you ignore things. And you'll need to do certain operations twice (like telling both that you are deleting a file).
A short form is convenient and helps avoid spelling mistakes. Localize as applicable, but be sure to display the expected format (do not leave the user blind). Provide a date-picker control as an *optional* aide to filling in the field. As an extra, on-the-fly parsing and display of the date in long form might help too.
Well... KernelTrap has [something on this][1]. Looks like you can use [vss2svn][2] to pipe the Source Safe repo into a Subversion repository, then use the very nice git-svn to pull into a local git repo. I would assume the commits back to VSS would not be a smooth, automatic process using this method. [1]: http://kerneltrap.org/mailarchive/git/2008/5/27/1952124 [2]: http://www.pumacode.org/projects/vss2svn/wiki/RunningTheMigration
While I would still like an answer to why my JS wasn't being recognized, the solution I found in the meantime (and should have done in the first place) is to use an Asp:CompareValidator instead of an Asp:CustomValidator.
While you cannot prevent usage of those inherited members to my knowledge, you should be able to hide them from IntelliSense using the [EditorBrowsableAttribute][1]: Using System.ComponentModel; [EditorBrowsable(EditorBrowsableState.Never)] private string MyHiddenString = "Muahahahahahahahaha"; [1]: http://msdn.microsoft.com/en-us/library/system.componentmodel.editorbrowsableattribute.aspx
I think you're best least hackish way is to consider composition as opposed to inheritance. Or, you could create an interface that has the members you want, have your derived class implement that interface, and program against the interface.
Reducing duplicate error handling code in C#?
|c#|exception|error-handling|
I've never been completely happy with the way exception handling works, there's a lot exceptions and try/catch brings to the table (stack unwinding, etc.), but it seems to break a lot of the OO model in the process. Anyway, here's the problem: Let's say you have some class which wraps or includes networked file IO operations (e.g. reading and writing to some file at some particular UNC path somewhere). For various reasons you don't want those IO operations to fail, so if you detect that they fail you retry them and you keep retrying them until they succeed or you reach a timeout. I already have a convenient RetryTimer class which I can instantiate and use to sleep the current thread between retries and determine when the timeout period has elapsed, etc. The problem is that you have a bunch of IO operations in several methods of this class, and you need to wrap each of them in try-catch / retry logic. Here's an example code snippet: RetryTimer fileIORetryTimer = new RetryTimer(TimeSpan.FromHours(10)); bool success = false; while (!success) { try { // do some file IO which may succeed or fail success = true; } catch (IOException e) { if (fileIORetryTimer.HasExceededRetryTimeout) { throw e; } fileIORetryTimer.SleepUntilNextRetry(); } } So, how do you avoid duplicating most of this code for every file IO operation throughout the class? My solution was to use anonymous delegate blocks and a single method in the class which executed the delegate block passed to it. This allowed me to do things like this in other methods: this.RetryFileIO( delegate() { // some code block } ); I like this somewhat, but it leaves a lot to be desired. I'd like to hear how other people would solve this sort of problem.
I've used [JMeter](http://jakarta.apache.org/jmeter/). Besides testing the web server you can also test your database backend, messaging services and email servers.
My opinion is if you are depending on a minimum/maximum/specific size **don't** just assume that (say) an `unsigned int` is 32 bytes - use `uint32_t` instead (assuming your compiler supports C99).
There have already been a bunch of great answers, but for an absolute beginner, I would wholeheartedly recommend [Hackety Hack][1]. It was created by the unreasonably prolific [why_the_lucky_stiff][2] specifically to provide a BASIC/LOGO/Pascal-like environment for new programmers to experiment in. It's essentially a slick Ruby IDE with some great libraries (flash video, IM, web server) and interactive lessons. It makes a good pitch for programming, as it chose lessons that do fun, useful things. "Hello, world" may not impress right off the bat, but creating a custom IM client in 20 minutes can inspire someone to keep learning. Have fun! [1]: http://hacketyhack.net/ [2]: http://whytheluckystiff.net/
And some more links, just in case the above didn't suffice: [Windows Presentation Foundation - Data Binding How-to Topics](http://msdn.microsoft.com/en-us/library/ms752039.aspx) (approx 30 'How To' articles from MSDN) "The topics in this section describe how to use data binding to bind elements to data from a variety of data sources in the form of common language runtime (CLR) objects and XML. " [Moving Toward WPF Data Binding One Step at a Time](http://www.codeproject.com/KB/WPF/MovingTowardWpfBinding.aspx) (By WPF guru [Josh Smith](http://joshsmithonwpf.wordpress.com/)) "This article explains the absolute basics of WPF data binding. It shows four different ways how to perform the same simple task. Each iteration moves closer to the most compact, XAML-only implementation possible. This article is for people with no experience in WPF data binding."
And some more links, just in case the above didn't suffice: [Windows Presentation Foundation - Data Binding How-to Topics](http://msdn.microsoft.com/en-us/library/ms752039.aspx) - Approx 30 'How To' articles from MSDN. "The topics in this section describe how to use data binding to bind elements to data from a variety of data sources in the form of common language runtime (CLR) objects and XML. " [Moving Toward WPF Data Binding One Step at a Time](http://www.codeproject.com/KB/WPF/MovingTowardWpfBinding.aspx) - By WPF guru [Josh Smith](http://joshsmithonwpf.wordpress.com/) "This article explains the absolute basics of WPF data binding. It shows four different ways how to perform the same simple task. Each iteration moves closer to the most compact, XAML-only implementation possible. This article is for people with no experience in WPF data binding."
We use the [Web Service Software Factory][1], and we really like it because it makes it easier for developers to follow standards and appropriate patterns. The learning curve for us wasn't bad - a few hours per developer at most. Other than that, there aren't any other pros & cons worth mentioning. [1]: http://www.codeplex.com/servicefactory
Facebook does it, when you write on people's walls, but only resizes vertically. Horizontal resize strikes me as being a terrible mess, due to word-wrap, long lines, and so on, but vertical resize would be pretty safe and nice Facebook is inhabited by every idiot on the planet, and none of the facebook-using-idiots I know have ever mentioned anything about it or been remotely confused. I'd use this as anecdotal evidence to say 'go ahead, implement it' Some javascript to do it, using prototype.js (cos that's what I know) <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <html> <head> <script src="http://www.google.com/jsapi"></script> <script language="javascript"> google.load('prototype', '1.6.0.2'); </script> </head> <body> <textarea id="text-area" rows="1" cols="50"></textarea> <script type="text/javascript" language="javascript"> resizeIt = function() { var str = $('text-area').value; var cols = $('text-area').cols; var linecount = 0; $A(str.split("\n")).each( function(l) { linecount += Math.ceil( l.length / cols ); // take into account long lines } ) $('text-area').rows = linecount + 1; }; Event.observe('text-area', 'keydown', resizeIt ); // you could attach to keyUp or whatever if keydown doesn't work resizeIt(); //initial on load </script> </body> </html>
I am trying to build an website for my college's magazine. I used the "views" module to show a block of static content I created on the front page. My question is: how can I edit the theme's css so it changes the way that block of static content is displayed? For reference, <a href="http://www.historia.uff.br/aroda/">here's the link</a> to the site (in portuguese, and with almost zero content for now).
Best practices for signing .NET assemblies?
|.net|assembly|signing|
I have a solution consisting of 5 projects, each of which compile to separate assemblies. Right now I'm code-signing them, but I'm pretty sure I'm doing it wrong. What's the best practice here? - Sign each with a different key; make sure the passwords are different - Sign each with a different key; use the same password if you want - Sign each with the same key - Something else entirely Basically I'm not quite sure what "signing" does to them, or what the best practices are here, so a more generally discussion would be good. All I really know is that FxCop yelled at me, and it was easy to fix by clicking the "Sign this assembly" checkbox and generating a .pfx file using Visual Studio (2008). Thanks!
Since your application is small, there is essentially no appreciable cost increase to using nvarchar over varchar, and you save yourself potential headaches down the road if you have a need to store unicode data.
A better solution is to store the MD5 in the configuration file. But instead of the MD5 being just of the configuration file, also include some "key" value, like a fixed guid, in the MD5. write(MD5(FixedGUID + ConfigFileText)); Then you simply remove that MD5 and rehash it with your secret key. If the MD5's are the same, then no-one modified it. This prevents someone from modifying it and re-applying the MD5 since they don't know your secret key. Keep in mind this is a fairly weak solution (as is the one you are suggesting) as they could easily track into your program to find the key or where the MD5 is stored. If you REALLY want to store the information in your executable (which I would discourage) then you can just try appending it at the end of the EXE. That is usually safe. Modifying executable programs is *virus like* behavior and most operating system security will try to stop you too. If your program is in the Program Files directory, and your configuration file is in the Application Data directory, and the user is logged in as a non-administrator, then you will be unable to update the EXE.
A better solution is to store the MD5 in the configuration file. But instead of the MD5 being just of the configuration file, also include some secret "key" value, like a fixed guid, in the MD5. write(MD5(SecretKey + ConfigFileText)); Then you simply remove that MD5 and rehash the file (including your secret key). If the MD5's are the same, then no-one modified it. This prevents someone from modifying it and re-applying the MD5 since they don't know your secret key. Keep in mind this is a fairly weak solution (as is the one you are suggesting) as they could easily track into your program to find the key or where the MD5 is stored. A better solution would be to use a public key system and sign the configuration file. Again that is weak since that would require the private key to be stored on their local machine. Pretty much anything that is contained on their local PC can be bypassed with enough effort. If you REALLY want to store the information in your executable (which I would discourage) then you can just try appending it at the end of the EXE. That is usually safe. Modifying executable programs is *virus like* behavior and most operating system security will try to stop you too. If your program is in the Program Files directory, and your configuration file is in the Application Data directory, and the user is logged in as a non-administrator (in XP or Vista), then you will be unable to update the EXE.
If you use Active Directory you could have each app use AD for authentication, login could then be seamless. Otherwise, if the applications can talk to each other behind the scenes, you could use sessionids and have one app handling id generation serving all of your other applications.
Assuming you meant "How do I test against things that are hard/impossible to mock": If you have a class that "goes out and gets the Win32_LogicalDisk object for a server" AND does something else (consumes the 'Win32_LogicalDisk' object in some way), assuming you want to test the pieces of the class that consume this object, you can use [Dependency Injection](http://en.wikipedia.org/wiki/Dependency_injection) to allow you to mock the 'Win32_LogicalDisk' object. For instance: class LogicalDiskConsumer(object): def __init__(self, arg1, arg2, LogicalDiskFactory) self.arg1=arg1 self.arg2=arg2 self.LogicalDisk=LogicalDiskFactory() def consumedisk(self): self.LogicalDisk.someaction() Then in your unit test code, pass in a 'LogicalDiskFactory' that returns a mock object for the 'Win32_LogicalDisk'. [1]: http://en.wikipedia.org/wiki/Dependency_injection/ "Dependency Injection"
WPF - Load Font from Stream?
|wpf|fonts|stream|
I have a MemoryStream with the contents of a Font File (.ttf) and I would like to be able to create a FontFamily WPF object from that stream **WITHOUT** writing the contents of the stream to disk. I know this is possible with a System.Drawing.FontFamily but I cannot find out how to do it with System.Windows.Media.FontFamily. Note: I will only have the stream, so I can't pack it as a resource in the application and because of disk permissions issues, will not be able to write the font file to disk for reference as "content"
|wpf|fonts|stream|
XML is often used for configuration, and in this case there are some other simple storage formats that are often used (less document oriented): 1. [.property files][1] 2. [INI files][2] There's various ways for reading and writing both, depending on platform and language. [1]: http://en.wikipedia.org/wiki/.properties [2]: http://en.wikipedia.org/wiki/INI_file
Depending on what you are encoding (size, framerate, hardware, etc) real-time encoding may not even be possible. Video encoding is VERY CPU intensive.
I'm looking for "unbreakable" watermarks, so data stored in exif or image metadata are out. I have found some interesting stuff on the web while waiting for replies here: http://www.cosy.sbg.ac.at/~pmeerw/Watermarking/ There is a master thesis that's fairly exhaustive about algorithms and their caracteristics (what they do and how unbreakable they are). I haven't got any time to read it in depth, but this stuff looks serious. There are algorithms that support JPEG compression, cropping, gamma correction or down scaling scaling in some way. It's C, but I can port it to Python or use C libraries from Python. However, it's from 2001 and I guess 7 years are a long time in this field :( Does anybody have some similar and more recent stuff?
We're talking about C++ right? Why on earth are we still using macros!? C++ inline functions give you the same speed as a macro, with the added benefit of type-safety and parameter evaluation (which avoids the issue that Rodney and dwj mentioned. inline const char * const BoolToString(bool b) { return b ? "true" : "false"; } Aside from that I have a few other gripes, particularly with the accepted answer :) // this is used in C, not C++. if you want to use printf, instead include <cstdio> //#include <stdio.h> // instead you should use the iostream libs #include <iostream> // not only is this a C include, it's totally unnecessary! //#include <stdarg.h> // Macros - not type-safe, has side-effects. Use inline functions instead //#define BOOL_STR(b) (b?"true":"false") inline const char * const BoolToString(bool b) { return b ? "true" : "false"; } int main (int argc, char const *argv[]) { bool alpha = true; // printf? that's C, not C++ //printf( BOOL_STR(alpha) ); // use the iostream functionality std::cout << BoolToString(alpha); return 0; } Cheers :) ---------- At Dr Pizza: Include a whole boost lib for the sake of a function this simple? You've got to be kidding?
Assuming that this will work in PERL as it does in languages that claim to use PERL-compatible syntax: `/<\/?[^p][^>]*>/`
Assuming that this will work in PERL as it does in languages that claim to use PERL-compatible syntax: `/<\/?[^p][^>]*>/` EDIT: But that won't match a `<pre>` or `<param>` tag, unfortunately. This, perhaps? /<\/?(?!p>|p )[^>]+>/ That should cover `<p>` tags that have attributes, too.
How to keep the browser history in sync when using Ajax?
|asp.net|web|ajax|
I'm writing a simple photo album app using ASP.NET Ajax. The app uses async Ajax calls to pre-load the next photo in the album, without changing the URL in the browser. The problem is that when the user clicks the **back** button in the browser, the app doesn't go back to the previous photo, instead, it navigates to the home page of the application. Is there a way to trick the browser into adding each Ajax call to the browsing history?
Since HTML is not a regular language I would not expect a regular expression to do a very good job at matching it. They might be up to this task (though I'm not convinced), but I would consider looking elsewhere; I'm sure perl must have some off-the-shelf libraries for manipulating HTML. Anyway, I would think that what you want to match is &lt;/?(p.+|.\*)(\s\*.\*)&gt; non-greedily (I don't know the vagaries of perl's regexp syntax so I cannot help further). I am assuming that \s means whitespace. Perhaps it doesn't. Either way, you want something that'll match attributes offset from the tag name by whitespace. But it's more difficult than that as people often put unescaped angle brackets inside scripts and comments and perhaps even quoted attribute values, which you don't want to match against. So as I say, I don't really think regexps are the right tool for the job.
There are tools that should help you find your leak, like JProbe, YourKit, AD4J or JRockit Mission Control. The last is the one that I personally know best. Any good tool should let you drill down to a level where you can easily identify what leaks, and where the leaking objects are allocated. Using HashTables, Hashmaps or similar is one of the few ways that you can acually leak memory in Java at all. If I had to find the leak by hand I would peridically print the size of my HashMaps, and from there find the one where I add items and forget to delete them.
Something like this should be good: MyConfigurationDialog dialog = new MyConfigurationDialog(); //Copy the dictionary so that the dialog can't mess with our settings dialog.Settings = new Dictionary(existingSettings); if(DialogResult.OK == dialog.Show()) { //grab the settings that the dialog may have changed existingSettings["setting1"] = dialog.Settings["setting1"]; existingSettings["setting2"] = dialog.Settings["setting2"]; }
Well, why not just throw the standard SOAPExceptions? The problem with error codes and serialized XML is that they both require additional logic to recognize that an error did in fact happen. Such an approach is only useful if you have specialized logging or logic that needs to happen on the other side of the web service. Such an example would be returning a flag that says "it's ok to continue" with an error exception report. Regardless of how you throw it, it won't make the job any easier, as the calling side still needs to recognize there was an exception and deal with it.
Update in Linq
|c#|linq|
How can i update an entity that is disconnected from database? Code below does not run correctly and throws InvalidOperationExcepiton. public void Foo() { DataContext context = new DataContext(); LinqEntity item = new LinqEntity(){ Id = 1, Name = "John", Surname = "Doe"} ; context.LinqEntities.Attach(item, true); }
I think that [mod_filter_ext][1] is the module you are looking for. You can write a short Perl script for example to insert the JS code in the pages and register it to process HTML pages: while (<>) { s/<html>/\Q<script>....\E/; print $_; } You could even use something like `sed` to perform the substitution. [1]: http://httpd.apache.org/docs/2.2/mod/mod_ext_filter.html